From 5c5d12f603ede6479c81cac7bc2530e42c1b58a8 Mon Sep 17 00:00:00 2001 From: nightcityblade Date: Mon, 7 Sep 2026 11:05:17 +0800 Subject: [PATCH] [aiofiles] Preserve bytes NamedTemporaryFile names --- .editorconfig | 16 + .flake8 | 16 + .gitattributes | 8 + .github/renovate.json5 | 40 + .github/workflows/daily.yml | 154 + .github/workflows/meta_tests.yml | 92 + .github/workflows/mypy_primer.yml | 91 + .github/workflows/mypy_primer_comment.yml | 87 + .github/workflows/stubsabot.yml | 60 + .github/workflows/stubtest_stdlib.yml | 54 + .github/workflows/stubtest_third_party.yml | 101 + .github/workflows/tests.yml | 235 + .gitignore | 77 + .pre-commit-config.yaml | 51 + .vscode/extensions.json | 41 + .vscode/settings.default.json | 125 + AGENTS.md | 47 + CONTRIBUTING.md | 493 ++ LICENSE | 237 + MAINTAINERS.md | 105 + README.md | 124 + lib/pyproject.toml | 9 + lib/ts_utils/__init__.py | 1 + lib/ts_utils/metadata.py | 459 ++ lib/ts_utils/mypy.py | 81 + lib/ts_utils/paths.py | 41 + lib/ts_utils/py.typed | 0 lib/ts_utils/py315.py | 18 + lib/ts_utils/requirements.py | 29 + lib/ts_utils/stubs.py | 80 + lib/ts_utils/utils.py | 298 + pyproject.toml | 283 + pyrefly.toml | 21 + pyrightconfig.json | 48 + pyrightconfig.scripts_and_tests.json | 25 + pyrightconfig.stricter.json | 137 + pyrightconfig.testcases.json | 31 + requirements-tests.txt | 26 + scripts/create_baseline_stubs.py | 255 + .../install_all_third_party_dependencies.py | 15 + scripts/stubsabot.py | 1050 +++ scripts/sync_protobuf/_utils.py | 56 + scripts/sync_protobuf/google_protobuf.py | 97 + scripts/sync_protobuf/s2clientprotocol.py | 76 + scripts/sync_protobuf/tensorflow.py | 141 + stdlib/@tests/stubtest_allowlists/common.txt | 486 ++ .../stubtest_allowlists/darwin-py310.txt | 77 + .../stubtest_allowlists/darwin-py311.txt | 70 + .../stubtest_allowlists/darwin-py312.txt | 57 + .../stubtest_allowlists/darwin-py313.txt | 15 + .../stubtest_allowlists/darwin-py314.txt | 23 + .../stubtest_allowlists/darwin-py315.txt | 25 + stdlib/@tests/stubtest_allowlists/darwin.txt | 53 + .../stubtest_allowlists/linux-py310.txt | 10 + .../stubtest_allowlists/linux-py311.txt | 10 + .../stubtest_allowlists/linux-py312.txt | 10 + .../stubtest_allowlists/linux-py313.txt | 9 + .../stubtest_allowlists/linux-py314.txt | 17 + .../stubtest_allowlists/linux-py315.txt | 19 + stdlib/@tests/stubtest_allowlists/linux.txt | 137 + stdlib/@tests/stubtest_allowlists/py310.txt | 287 + stdlib/@tests/stubtest_allowlists/py311.txt | 268 + stdlib/@tests/stubtest_allowlists/py312.txt | 248 + stdlib/@tests/stubtest_allowlists/py313.txt | 170 + stdlib/@tests/stubtest_allowlists/py314.txt | 199 + stdlib/@tests/stubtest_allowlists/py315.txt | 192 + .../stubtest_allowlists/win32-py310.txt | 77 + .../stubtest_allowlists/win32-py311.txt | 52 + .../stubtest_allowlists/win32-py312.txt | 56 + .../stubtest_allowlists/win32-py313.txt | 7 + .../stubtest_allowlists/win32-py314.txt | 7 + .../stubtest_allowlists/win32-py315.txt | 11 + stdlib/@tests/stubtest_allowlists/win32.txt | 41 + .../test_cases/asyncio/check_coroutines.py | 40 + .../@tests/test_cases/asyncio/check_gather.py | 38 + .../test_cases/asyncio/check_getaddrinfo.py | 20 + .../@tests/test_cases/asyncio/check_task.py | 28 + .../test_cases/asyncio/check_task_factory.py | 13 + .../@tests/test_cases/builtins/check_dict.py | 213 + .../builtins/check_exception_group-py311.py | 354 + .../builtins/check_frozendict-py315.py | 15 + .../test_cases/builtins/check_iteration.py | 16 + .../@tests/test_cases/builtins/check_list.py | 21 + .../test_cases/builtins/check_memoryview.py | 66 + .../@tests/test_cases/builtins/check_min.py | 94 + .../test_cases/builtins/check_object.py | 13 + .../@tests/test_cases/builtins/check_pow.py | 103 + .../test_cases/builtins/check_reversed.py | 48 + .../@tests/test_cases/builtins/check_round.py | 68 + .../@tests/test_cases/builtins/check_set.py | 57 + .../@tests/test_cases/builtins/check_slice.py | 251 + .../@tests/test_cases/builtins/check_sum.py | 55 + .../@tests/test_cases/builtins/check_tuple.py | 13 + .../@tests/test_cases/builtins/check_type.py | 4 + .../@tests/test_cases/builtins/check_zip.py | 15 + .../test_cases/check_SupportsGetItem.py | 38 + stdlib/@tests/test_cases/check_ast.py | 44 + stdlib/@tests/test_cases/check_codecs.py | 13 + stdlib/@tests/test_cases/check_compression.py | 58 + .../test_cases/check_concurrent_futures.py | 78 + .../@tests/test_cases/check_configparser.py | 5 + stdlib/@tests/test_cases/check_contextlib.py | 20 + stdlib/@tests/test_cases/check_copy.py | 39 + stdlib/@tests/test_cases/check_dataclasses.py | 153 + stdlib/@tests/test_cases/check_enum.py | 38 + stdlib/@tests/test_cases/check_functools.py | 165 + stdlib/@tests/test_cases/check_importlib.py | 51 + .../test_cases/check_importlib_metadata.py | 28 + .../test_cases/check_importlib_resources.py | 32 + stdlib/@tests/test_cases/check_inspect.py | 26 + stdlib/@tests/test_cases/check_io.py | 18 + stdlib/@tests/test_cases/check_logging.py | 54 + stdlib/@tests/test_cases/check_mailbox.py | 13 + stdlib/@tests/test_cases/check_math.py | 63 + stdlib/@tests/test_cases/check_os_path.py | 58 + stdlib/@tests/test_cases/check_pathlib.py | 46 + stdlib/@tests/test_cases/check_platform.py | 15 + stdlib/@tests/test_cases/check_re.py | 26 + stdlib/@tests/test_cases/check_socket.py | 13 + stdlib/@tests/test_cases/check_sqlite3.py | 26 + stdlib/@tests/test_cases/check_tarfile.py | 17 + stdlib/@tests/test_cases/check_tempfile.py | 31 + stdlib/@tests/test_cases/check_threading.py | 14 + stdlib/@tests/test_cases/check_tkinter.py | 74 + stdlib/@tests/test_cases/check_turtle.py | 35 + stdlib/@tests/test_cases/check_types.py | 85 + stdlib/@tests/test_cases/check_unittest.py | 255 + stdlib/@tests/test_cases/check_xml.py | 31 + stdlib/@tests/test_cases/check_zipfile.py | 131 + .../collections/check_defaultdict.py | 70 + stdlib/@tests/test_cases/ctypes/check_CDLL.py | 11 + .../@tests/test_cases/ctypes/check_pointer.py | 8 + .../@tests/test_cases/email/check_message.py | 18 + stdlib/@tests/test_cases/email/check_mime.py | 4 + .../@tests/test_cases/email/check_parser.py | 16 + .../test_cases/itertools/check_batched.py | 21 + .../itertools/check_itertools_recipes.py | 415 + .../multiprocessing/check_ctypes.py | 19 + .../multiprocessing/check_pipe_connections.py | 31 + stdlib/@tests/test_cases/sys/check_jit.py | 12 + .../test_cases/typing/check_MutableMapping.py | 53 + stdlib/@tests/test_cases/typing/check_all.py | 13 + .../typing/check_regression_issue_9296.py | 16 + .../test_cases/typing/check_typing_io.py | 21 + .../@tests/test_cases/urllib/check_parse.py | 12 + stdlib/VERSIONS | 349 + stdlib/__future__.pyi | 36 + stdlib/__main__.pyi | 1 + stdlib/_ast.pyi | 141 + stdlib/_asyncio.pyi | 114 + stdlib/_bisect.pyi | 103 + stdlib/_blake2.pyi | 119 + stdlib/_bz2.pyi | 24 + stdlib/_codecs.pyi | 122 + stdlib/_collections_abc.pyi | 105 + stdlib/_compat_pickle.pyi | 10 + stdlib/_compression.pyi | 39 + stdlib/_contextvars.pyi | 69 + stdlib/_csv.pyi | 116 + stdlib/_ctypes.pyi | 380 + stdlib/_curses.pyi | 583 ++ stdlib/_curses_panel.pyi | 27 + stdlib/_dbm.pyi | 46 + stdlib/_decimal.pyi | 73 + stdlib/_frozen_importlib.pyi | 115 + stdlib/_frozen_importlib_external.pyi | 180 + stdlib/_gdbm.pyi | 50 + stdlib/_hashlib.pyi | 127 + stdlib/_heapq.pyi | 18 + stdlib/_imp.pyi | 30 + stdlib/_interpchannels.pyi | 86 + stdlib/_interpqueues.pyi | 31 + stdlib/_interpreters.pyi | 62 + stdlib/_io.pyi | 330 + stdlib/_json.pyi | 59 + stdlib/_locale.pyi | 121 + stdlib/_lsprof.pyi | 34 + stdlib/_lzma.pyi | 71 + stdlib/_markupbase.pyi | 10 + stdlib/_msi.pyi | 97 + stdlib/_multibytecodec.pyi | 49 + stdlib/_operator.pyi | 157 + stdlib/_osx_support.pyi | 34 + stdlib/_pickle.pyi | 114 + stdlib/_posixsubprocess.pyi | 59 + stdlib/_py_abc.pyi | 14 + stdlib/_pydecimal.pyi | 50 + stdlib/_queue.pyi | 18 + stdlib/_random.pyi | 14 + stdlib/_remote_debugging.pyi | 183 + stdlib/_sitebuiltins.pyi | 18 + stdlib/_socket.pyi | 966 +++ stdlib/_sqlite3.pyi | 311 + stdlib/_ssl.pyi | 303 + stdlib/_stat.pyi | 119 + stdlib/_struct.pyi | 24 + stdlib/_thread.pyi | 123 + stdlib/_threading_local.pyi | 24 + stdlib/_tkinter.pyi | 156 + stdlib/_tracemalloc.pyi | 13 + stdlib/_typeshed/README.md | 34 + stdlib/_typeshed/__init__.pyi | 401 + stdlib/_typeshed/_type_checker_internals.pyi | 99 + stdlib/_typeshed/dbapi.pyi | 36 + stdlib/_typeshed/importlib.pyi | 18 + stdlib/_typeshed/wsgi.pyi | 43 + stdlib/_typeshed/xml.pyi | 9 + stdlib/_warnings.pyi | 54 + stdlib/_weakref.pyi | 15 + stdlib/_weakrefset.pyi | 49 + stdlib/_winapi.pyi | 319 + stdlib/_zstd.pyi | 102 + stdlib/abc.pyi | 50 + stdlib/aifc.pyi | 79 + stdlib/annotationlib.pyi | 156 + stdlib/antigravity.pyi | 3 + stdlib/argparse.pyi | 864 ++ stdlib/array.pyi | 113 + stdlib/ast.pyi | 2199 +++++ stdlib/asynchat.pyi | 21 + stdlib/asyncio/__init__.pyi | 1022 +++ stdlib/asyncio/base_events.pyi | 499 ++ stdlib/asyncio/base_futures.pyi | 17 + stdlib/asyncio/base_subprocess.pyi | 62 + stdlib/asyncio/base_tasks.pyi | 17 + stdlib/asyncio/constants.pyi | 20 + stdlib/asyncio/coroutines.pyi | 45 + stdlib/asyncio/events.pyi | 672 ++ stdlib/asyncio/exceptions.pyi | 44 + stdlib/asyncio/format_helpers.pyi | 31 + stdlib/asyncio/futures.pyi | 19 + stdlib/asyncio/graph.pyi | 29 + stdlib/asyncio/locks.pyi | 83 + stdlib/asyncio/log.pyi | 3 + stdlib/asyncio/mixins.pyi | 9 + stdlib/asyncio/proactor_events.pyi | 53 + stdlib/asyncio/protocols.pyi | 39 + stdlib/asyncio/queues.pyi | 45 + stdlib/asyncio/runners.pyi | 41 + stdlib/asyncio/selector_events.pyi | 10 + stdlib/asyncio/sslproto.pyi | 164 + stdlib/asyncio/staggered.pyi | 10 + stdlib/asyncio/streams.pyi | 124 + stdlib/asyncio/subprocess.pyi | 166 + stdlib/asyncio/taskgroups.pyi | 41 + stdlib/asyncio/tasks.pyi | 315 + stdlib/asyncio/threads.pyi | 9 + stdlib/asyncio/timeouts.pyi | 20 + stdlib/asyncio/tools.pyi | 51 + stdlib/asyncio/transports.pyi | 57 + stdlib/asyncio/trsock.pyi | 137 + stdlib/asyncio/unix_events.pyi | 277 + stdlib/asyncio/windows_events.pyi | 122 + stdlib/asyncio/windows_utils.pyi | 49 + stdlib/asyncore.pyi | 91 + stdlib/atexit.pyi | 11 + stdlib/audioop.pyi | 44 + stdlib/base64.pyi | 124 + stdlib/bdb.pyi | 139 + stdlib/binascii.pyi | 102 + stdlib/binhex.pyi | 44 + stdlib/bisect.pyi | 4 + stdlib/builtins.pyi | 2575 ++++++ stdlib/bz2.pyi | 121 + stdlib/cProfile.pyi | 33 + stdlib/calendar.pyi | 249 + stdlib/cgi.pyi | 120 + stdlib/cgitb.pyi | 32 + stdlib/chunk.pyi | 20 + stdlib/cmath.pyi | 36 + stdlib/cmd.pyi | 46 + stdlib/code.pyi | 55 + stdlib/codecs.pyi | 357 + stdlib/codeop.pyi | 21 + stdlib/collections/__init__.pyi | 565 ++ stdlib/collections/abc.pyi | 2 + stdlib/colorsys.pyi | 15 + stdlib/compileall.pyi | 51 + stdlib/compression/__init__.pyi | 0 stdlib/compression/_common/__init__.pyi | 0 stdlib/compression/_common/_streams.pyi | 37 + stdlib/compression/bz2.pyi | 1 + stdlib/compression/gzip.pyi | 1 + stdlib/compression/lzma.pyi | 1 + stdlib/compression/zlib.pyi | 1 + stdlib/compression/zstd/__init__.pyi | 94 + stdlib/compression/zstd/_zstdfile.pyi | 117 + stdlib/concurrent/__init__.pyi | 0 stdlib/concurrent/futures/__init__.pyi | 71 + stdlib/concurrent/futures/_base.pyi | 119 + stdlib/concurrent/futures/interpreter.pyi | 82 + stdlib/concurrent/futures/process.pyi | 248 + stdlib/concurrent/futures/thread.pyi | 143 + stdlib/concurrent/interpreters/__init__.pyi | 68 + .../concurrent/interpreters/_crossinterp.pyi | 30 + stdlib/concurrent/interpreters/_queues.pyi | 74 + stdlib/configparser.pyi | 507 ++ stdlib/contextlib.pyi | 224 + stdlib/contextvars.pyi | 3 + stdlib/copy.pyi | 33 + stdlib/copyreg.pyi | 20 + stdlib/crypt.pyi | 26 + stdlib/csv.pyi | 153 + stdlib/ctypes/__init__.pyi | 394 + stdlib/ctypes/_endian.pyi | 16 + stdlib/ctypes/macholib/__init__.pyi | 3 + stdlib/ctypes/macholib/dyld.pyi | 8 + stdlib/ctypes/macholib/dylib.pyi | 14 + stdlib/ctypes/macholib/framework.pyi | 14 + stdlib/ctypes/util.pyi | 11 + stdlib/ctypes/wintypes.pyi | 321 + stdlib/curses/__init__.pyi | 38 + stdlib/curses/ascii.pyi | 62 + stdlib/curses/has_key.pyi | 1 + stdlib/curses/panel.pyi | 1 + stdlib/curses/textpad.pyi | 11 + stdlib/dataclasses.pyi | 401 + stdlib/datetime.pyi | 381 + stdlib/dbm/__init__.pyi | 105 + stdlib/dbm/dumb.pyi | 41 + stdlib/dbm/gnu.pyi | 1 + stdlib/dbm/ndbm.pyi | 1 + stdlib/dbm/sqlite3.pyi | 34 + stdlib/decimal.pyi | 278 + stdlib/difflib.pyi | 157 + stdlib/dis.pyi | 302 + stdlib/distutils/__init__.pyi | 5 + stdlib/distutils/_msvccompiler.pyi | 13 + stdlib/distutils/archive_util.pyi | 36 + stdlib/distutils/bcppcompiler.pyi | 3 + stdlib/distutils/ccompiler.pyi | 182 + stdlib/distutils/cmd.pyi | 238 + stdlib/distutils/command/__init__.pyi | 41 + stdlib/distutils/command/bdist.pyi | 27 + stdlib/distutils/command/bdist_dumb.pyi | 22 + stdlib/distutils/command/bdist_msi.pyi | 45 + stdlib/distutils/command/bdist_packager.pyi | 0 stdlib/distutils/command/bdist_rpm.pyi | 53 + stdlib/distutils/command/build.pyi | 34 + stdlib/distutils/command/build_clib.pyi | 29 + stdlib/distutils/command/build_ext.pyi | 52 + stdlib/distutils/command/build_py.pyi | 45 + stdlib/distutils/command/build_scripts.pyi | 25 + stdlib/distutils/command/check.pyi | 39 + stdlib/distutils/command/clean.pyi | 18 + stdlib/distutils/command/config.pyi | 84 + stdlib/distutils/command/install.pyi | 67 + stdlib/distutils/command/install_data.pyi | 20 + stdlib/distutils/command/install_egg_info.pyi | 19 + stdlib/distutils/command/install_headers.pyi | 17 + stdlib/distutils/command/install_lib.pyi | 26 + stdlib/distutils/command/install_scripts.pyi | 19 + stdlib/distutils/command/register.pyi | 20 + stdlib/distutils/command/sdist.pyi | 45 + stdlib/distutils/command/upload.pyi | 18 + stdlib/distutils/config.pyi | 17 + stdlib/distutils/core.pyi | 58 + stdlib/distutils/cygwinccompiler.pyi | 20 + stdlib/distutils/debug.pyi | 3 + stdlib/distutils/dep_util.pyi | 14 + stdlib/distutils/dir_util.pyi | 23 + stdlib/distutils/dist.pyi | 318 + stdlib/distutils/errors.pyi | 19 + stdlib/distutils/extension.pyi | 36 + stdlib/distutils/fancy_getopt.pyi | 45 + stdlib/distutils/file_util.pyi | 40 + stdlib/distutils/filelist.pyi | 61 + stdlib/distutils/log.pyi | 26 + stdlib/distutils/msvccompiler.pyi | 3 + stdlib/distutils/spawn.pyi | 10 + stdlib/distutils/sysconfig.pyi | 32 + stdlib/distutils/text_file.pyi | 21 + stdlib/distutils/unixccompiler.pyi | 3 + stdlib/distutils/util.pyi | 53 + stdlib/distutils/version.pyi | 36 + stdlib/doctest.pyi | 265 + stdlib/email/__init__.pyi | 62 + stdlib/email/_header_value_parser.pyi | 414 + stdlib/email/_policybase.pyi | 80 + stdlib/email/base64mime.pyi | 13 + stdlib/email/charset.pyi | 44 + stdlib/email/contentmanager.pyi | 11 + stdlib/email/encoders.pyi | 8 + stdlib/email/errors.pyi | 38 + stdlib/email/feedparser.pyi | 24 + stdlib/email/generator.pyi | 79 + stdlib/email/header.pyi | 32 + stdlib/email/headerregistry.pyi | 193 + stdlib/email/iterators.pyi | 15 + stdlib/email/message.pyi | 191 + stdlib/email/mime/__init__.pyi | 0 stdlib/email/mime/application.pyi | 17 + stdlib/email/mime/audio.pyi | 17 + stdlib/email/mime/base.pyi | 8 + stdlib/email/mime/image.pyi | 17 + stdlib/email/mime/message.pyi | 8 + stdlib/email/mime/multipart.pyi | 18 + stdlib/email/mime/nonmultipart.pyi | 5 + stdlib/email/mime/text.pyi | 9 + stdlib/email/parser.pyi | 42 + stdlib/email/policy.pyi | 77 + stdlib/email/quoprimime.pyi | 28 + stdlib/email/utils.pyi | 72 + stdlib/encodings/__init__.pyi | 15 + stdlib/encodings/aliases.pyi | 1 + stdlib/encodings/ascii.pyi | 30 + stdlib/encodings/base64_codec.pyi | 26 + stdlib/encodings/big5.pyi | 23 + stdlib/encodings/big5hkscs.pyi | 23 + stdlib/encodings/bz2_codec.pyi | 26 + stdlib/encodings/charmap.pyi | 33 + stdlib/encodings/cp037.pyi | 21 + stdlib/encodings/cp1006.pyi | 21 + stdlib/encodings/cp1026.pyi | 21 + stdlib/encodings/cp1125.pyi | 21 + stdlib/encodings/cp1140.pyi | 21 + stdlib/encodings/cp1250.pyi | 21 + stdlib/encodings/cp1251.pyi | 21 + stdlib/encodings/cp1252.pyi | 21 + stdlib/encodings/cp1253.pyi | 21 + stdlib/encodings/cp1254.pyi | 21 + stdlib/encodings/cp1255.pyi | 21 + stdlib/encodings/cp1256.pyi | 21 + stdlib/encodings/cp1257.pyi | 21 + stdlib/encodings/cp1258.pyi | 21 + stdlib/encodings/cp273.pyi | 21 + stdlib/encodings/cp424.pyi | 21 + stdlib/encodings/cp437.pyi | 21 + stdlib/encodings/cp500.pyi | 21 + stdlib/encodings/cp720.pyi | 21 + stdlib/encodings/cp737.pyi | 21 + stdlib/encodings/cp775.pyi | 21 + stdlib/encodings/cp850.pyi | 21 + stdlib/encodings/cp852.pyi | 21 + stdlib/encodings/cp855.pyi | 21 + stdlib/encodings/cp856.pyi | 21 + stdlib/encodings/cp857.pyi | 21 + stdlib/encodings/cp858.pyi | 21 + stdlib/encodings/cp860.pyi | 21 + stdlib/encodings/cp861.pyi | 21 + stdlib/encodings/cp862.pyi | 21 + stdlib/encodings/cp863.pyi | 21 + stdlib/encodings/cp864.pyi | 21 + stdlib/encodings/cp865.pyi | 21 + stdlib/encodings/cp866.pyi | 21 + stdlib/encodings/cp869.pyi | 21 + stdlib/encodings/cp874.pyi | 21 + stdlib/encodings/cp875.pyi | 21 + stdlib/encodings/cp932.pyi | 23 + stdlib/encodings/cp949.pyi | 23 + stdlib/encodings/cp950.pyi | 23 + stdlib/encodings/euc_jis_2004.pyi | 23 + stdlib/encodings/euc_jisx0213.pyi | 23 + stdlib/encodings/euc_jp.pyi | 23 + stdlib/encodings/euc_kr.pyi | 23 + stdlib/encodings/gb18030.pyi | 23 + stdlib/encodings/gb2312.pyi | 23 + stdlib/encodings/gbk.pyi | 23 + stdlib/encodings/hex_codec.pyi | 26 + stdlib/encodings/hp_roman8.pyi | 21 + stdlib/encodings/hz.pyi | 23 + stdlib/encodings/idna.pyi | 26 + stdlib/encodings/iso2022_jp.pyi | 23 + stdlib/encodings/iso2022_jp_1.pyi | 23 + stdlib/encodings/iso2022_jp_2.pyi | 23 + stdlib/encodings/iso2022_jp_2004.pyi | 23 + stdlib/encodings/iso2022_jp_3.pyi | 23 + stdlib/encodings/iso2022_jp_ext.pyi | 23 + stdlib/encodings/iso2022_kr.pyi | 23 + stdlib/encodings/iso8859_1.pyi | 21 + stdlib/encodings/iso8859_10.pyi | 21 + stdlib/encodings/iso8859_11.pyi | 21 + stdlib/encodings/iso8859_13.pyi | 21 + stdlib/encodings/iso8859_14.pyi | 21 + stdlib/encodings/iso8859_15.pyi | 21 + stdlib/encodings/iso8859_16.pyi | 21 + stdlib/encodings/iso8859_2.pyi | 21 + stdlib/encodings/iso8859_3.pyi | 21 + stdlib/encodings/iso8859_4.pyi | 21 + stdlib/encodings/iso8859_5.pyi | 21 + stdlib/encodings/iso8859_6.pyi | 21 + stdlib/encodings/iso8859_7.pyi | 21 + stdlib/encodings/iso8859_8.pyi | 21 + stdlib/encodings/iso8859_9.pyi | 21 + stdlib/encodings/johab.pyi | 23 + stdlib/encodings/koi8_r.pyi | 21 + stdlib/encodings/koi8_t.pyi | 21 + stdlib/encodings/koi8_u.pyi | 21 + stdlib/encodings/kz1048.pyi | 21 + stdlib/encodings/latin_1.pyi | 30 + stdlib/encodings/mac_arabic.pyi | 21 + stdlib/encodings/mac_croatian.pyi | 21 + stdlib/encodings/mac_cyrillic.pyi | 21 + stdlib/encodings/mac_farsi.pyi | 21 + stdlib/encodings/mac_greek.pyi | 21 + stdlib/encodings/mac_iceland.pyi | 21 + stdlib/encodings/mac_latin2.pyi | 21 + stdlib/encodings/mac_roman.pyi | 21 + stdlib/encodings/mac_romanian.pyi | 21 + stdlib/encodings/mac_turkish.pyi | 21 + stdlib/encodings/mbcs.pyi | 28 + stdlib/encodings/oem.pyi | 28 + stdlib/encodings/palmos.pyi | 21 + stdlib/encodings/ptcp154.pyi | 21 + stdlib/encodings/punycode.pyi | 33 + stdlib/encodings/quopri_codec.pyi | 26 + stdlib/encodings/raw_unicode_escape.pyi | 23 + stdlib/encodings/rot_13.pyi | 23 + stdlib/encodings/shift_jis.pyi | 23 + stdlib/encodings/shift_jis_2004.pyi | 23 + stdlib/encodings/shift_jisx0213.pyi | 23 + stdlib/encodings/tis_620.pyi | 21 + stdlib/encodings/undefined.pyi | 20 + stdlib/encodings/unicode_escape.pyi | 23 + stdlib/encodings/utf_16.pyi | 20 + stdlib/encodings/utf_16_be.pyi | 26 + stdlib/encodings/utf_16_le.pyi | 26 + stdlib/encodings/utf_32.pyi | 20 + stdlib/encodings/utf_32_be.pyi | 26 + stdlib/encodings/utf_32_le.pyi | 26 + stdlib/encodings/utf_7.pyi | 26 + stdlib/encodings/utf_8.pyi | 26 + stdlib/encodings/utf_8_sig.pyi | 22 + stdlib/encodings/uu_codec.pyi | 28 + stdlib/encodings/zlib_codec.pyi | 26 + stdlib/ensurepip/__init__.pyi | 12 + stdlib/enum.pyi | 374 + stdlib/errno.pyi | 227 + stdlib/faulthandler.pyi | 61 + stdlib/fcntl.pyi | 157 + stdlib/filecmp.pyi | 65 + stdlib/fileinput.pyi | 141 + stdlib/fnmatch.pyi | 16 + stdlib/fractions.pyi | 185 + stdlib/ftplib.pyi | 174 + stdlib/functools.pyi | 281 + stdlib/gc.pyi | 32 + stdlib/genericpath.pyi | 98 + stdlib/getopt.pyi | 27 + stdlib/getpass.pyi | 14 + stdlib/gettext.pyi | 190 + stdlib/glob.pyi | 54 + stdlib/graphlib.pyi | 29 + stdlib/grp.pyi | 21 + stdlib/gzip.pyi | 181 + stdlib/hashlib.pyi | 112 + stdlib/heapq.pyi | 32 + stdlib/hmac.pyi | 33 + stdlib/html/__init__.pyi | 7 + stdlib/html/entities.pyi | 8 + stdlib/html/parser.pyi | 40 + stdlib/http/__init__.pyi | 118 + stdlib/http/client.pyi | 318 + stdlib/http/cookiejar.pyi | 158 + stdlib/http/cookies.pyi | 53 + stdlib/http/server.pyi | 139 + stdlib/imaplib.pyi | 212 + stdlib/imghdr.pyi | 18 + stdlib/imp.pyi | 63 + stdlib/importlib/__init__.pyi | 17 + stdlib/importlib/_abc.pyi | 19 + stdlib/importlib/_bootstrap.pyi | 2 + stdlib/importlib/_bootstrap_external.pyi | 2 + stdlib/importlib/abc.pyi | 150 + stdlib/importlib/machinery.pyi | 43 + stdlib/importlib/metadata/__init__.pyi | 310 + stdlib/importlib/metadata/_meta.pyi | 65 + stdlib/importlib/metadata/diagnose.pyi | 2 + stdlib/importlib/readers.pyi | 69 + stdlib/importlib/resources/__init__.pyi | 81 + stdlib/importlib/resources/_common.pyi | 43 + stdlib/importlib/resources/_functional.pyi | 35 + stdlib/importlib/resources/abc.pyi | 64 + stdlib/importlib/resources/readers.pyi | 14 + stdlib/importlib/resources/simple.pyi | 59 + stdlib/importlib/simple.pyi | 11 + stdlib/importlib/util.pyi | 75 + stdlib/inspect.pyi | 749 ++ stdlib/io.pyi | 75 + stdlib/ipaddress.pyi | 249 + stdlib/itertools.pyi | 376 + stdlib/json/__init__.pyi | 93 + stdlib/json/decoder.pyi | 50 + stdlib/json/encoder.pyi | 40 + stdlib/json/scanner.pyi | 7 + stdlib/json/tool.pyi | 1 + stdlib/keyword.pyi | 16 + stdlib/lib2to3/__init__.pyi | 0 stdlib/lib2to3/btm_matcher.pyi | 28 + stdlib/lib2to3/fixer_base.pyi | 42 + stdlib/lib2to3/fixes/__init__.pyi | 0 stdlib/lib2to3/fixes/fix_apply.pyi | 8 + stdlib/lib2to3/fixes/fix_asserts.pyi | 10 + stdlib/lib2to3/fixes/fix_basestring.pyi | 8 + stdlib/lib2to3/fixes/fix_buffer.pyi | 8 + stdlib/lib2to3/fixes/fix_dict.pyi | 16 + stdlib/lib2to3/fixes/fix_except.pyi | 14 + stdlib/lib2to3/fixes/fix_exec.pyi | 8 + stdlib/lib2to3/fixes/fix_execfile.pyi | 8 + stdlib/lib2to3/fixes/fix_exitfunc.pyi | 13 + stdlib/lib2to3/fixes/fix_filter.pyi | 9 + stdlib/lib2to3/fixes/fix_funcattrs.pyi | 8 + stdlib/lib2to3/fixes/fix_future.pyi | 8 + stdlib/lib2to3/fixes/fix_getcwdu.pyi | 8 + stdlib/lib2to3/fixes/fix_has_key.pyi | 8 + stdlib/lib2to3/fixes/fix_idioms.pyi | 15 + stdlib/lib2to3/fixes/fix_import.pyi | 16 + stdlib/lib2to3/fixes/fix_imports.pyi | 21 + stdlib/lib2to3/fixes/fix_imports2.pyi | 8 + stdlib/lib2to3/fixes/fix_input.pyi | 11 + stdlib/lib2to3/fixes/fix_intern.pyi | 9 + stdlib/lib2to3/fixes/fix_isinstance.pyi | 8 + stdlib/lib2to3/fixes/fix_itertools.pyi | 9 + .../lib2to3/fixes/fix_itertools_imports.pyi | 7 + stdlib/lib2to3/fixes/fix_long.pyi | 7 + stdlib/lib2to3/fixes/fix_map.pyi | 9 + stdlib/lib2to3/fixes/fix_metaclass.pyi | 17 + stdlib/lib2to3/fixes/fix_methodattrs.pyi | 10 + stdlib/lib2to3/fixes/fix_ne.pyi | 8 + stdlib/lib2to3/fixes/fix_next.pyi | 19 + stdlib/lib2to3/fixes/fix_nonzero.pyi | 8 + stdlib/lib2to3/fixes/fix_numliterals.pyi | 8 + stdlib/lib2to3/fixes/fix_operator.pyi | 12 + stdlib/lib2to3/fixes/fix_paren.pyi | 8 + stdlib/lib2to3/fixes/fix_print.pyi | 12 + stdlib/lib2to3/fixes/fix_raise.pyi | 8 + stdlib/lib2to3/fixes/fix_raw_input.pyi | 8 + stdlib/lib2to3/fixes/fix_reduce.pyi | 8 + stdlib/lib2to3/fixes/fix_reload.pyi | 9 + stdlib/lib2to3/fixes/fix_renames.pyi | 17 + stdlib/lib2to3/fixes/fix_repr.pyi | 8 + stdlib/lib2to3/fixes/fix_set_literal.pyi | 7 + stdlib/lib2to3/fixes/fix_standarderror.pyi | 8 + stdlib/lib2to3/fixes/fix_sys_exc.pyi | 9 + stdlib/lib2to3/fixes/fix_throw.pyi | 8 + stdlib/lib2to3/fixes/fix_tuple_params.pyi | 16 + stdlib/lib2to3/fixes/fix_types.pyi | 8 + stdlib/lib2to3/fixes/fix_unicode.pyi | 12 + stdlib/lib2to3/fixes/fix_urllib.pyi | 15 + stdlib/lib2to3/fixes/fix_ws_comma.pyi | 12 + stdlib/lib2to3/fixes/fix_xrange.pyi | 20 + stdlib/lib2to3/fixes/fix_xreadlines.pyi | 8 + stdlib/lib2to3/fixes/fix_zip.pyi | 9 + stdlib/lib2to3/main.pyi | 42 + stdlib/lib2to3/pgen2/__init__.pyi | 8 + stdlib/lib2to3/pgen2/driver.pyi | 27 + stdlib/lib2to3/pgen2/grammar.pyi | 25 + stdlib/lib2to3/pgen2/literals.pyi | 7 + stdlib/lib2to3/pgen2/parse.pyi | 30 + stdlib/lib2to3/pgen2/pgen.pyi | 53 + stdlib/lib2to3/pgen2/token.pyi | 69 + stdlib/lib2to3/pgen2/tokenize.pyi | 96 + stdlib/lib2to3/pygram.pyi | 114 + stdlib/lib2to3/pytree.pyi | 118 + stdlib/lib2to3/refactor.pyi | 86 + stdlib/linecache.pyi | 18 + stdlib/locale.pyi | 160 + stdlib/logging/__init__.pyi | 674 ++ stdlib/logging/config.pyi | 141 + stdlib/logging/handlers.pyi | 258 + stdlib/lzma.pyi | 181 + stdlib/mailbox.pyi | 306 + stdlib/mailcap.pyi | 11 + stdlib/marshal.pyi | 52 + stdlib/math/__init__.pyi | 157 + stdlib/math/integer.pyi | 8 + stdlib/mimetypes.pyi | 56 + stdlib/mmap.pyi | 187 + stdlib/modulefinder.pyi | 68 + stdlib/msilib/__init__.pyi | 177 + stdlib/msilib/schema.pyi | 95 + stdlib/msilib/sequence.pyi | 13 + stdlib/msilib/text.pyi | 8 + stdlib/msvcrt.pyi | 31 + stdlib/multiprocessing/__init__.pyi | 90 + stdlib/multiprocessing/connection.pyi | 94 + stdlib/multiprocessing/context.pyi | 220 + stdlib/multiprocessing/dummy/__init__.pyi | 89 + stdlib/multiprocessing/dummy/connection.pyi | 39 + stdlib/multiprocessing/forkserver.pyi | 78 + stdlib/multiprocessing/heap.pyi | 41 + stdlib/multiprocessing/managers.pyi | 390 + stdlib/multiprocessing/pool.pyi | 101 + stdlib/multiprocessing/popen_fork.pyi | 26 + stdlib/multiprocessing/popen_forkserver.pyi | 16 + stdlib/multiprocessing/popen_spawn_posix.pyi | 20 + stdlib/multiprocessing/popen_spawn_win32.pyi | 30 + stdlib/multiprocessing/process.pyi | 43 + stdlib/multiprocessing/queues.pyi | 46 + stdlib/multiprocessing/reduction.pyi | 95 + stdlib/multiprocessing/resource_sharer.pyi | 20 + stdlib/multiprocessing/resource_tracker.pyi | 21 + stdlib/multiprocessing/shared_memory.pyi | 43 + stdlib/multiprocessing/sharedctypes.pyi | 140 + stdlib/multiprocessing/spawn.pyi | 32 + stdlib/multiprocessing/synchronize.pyi | 63 + stdlib/multiprocessing/util.pyi | 109 + stdlib/netrc.pyi | 23 + stdlib/nis.pyi | 9 + stdlib/nntplib.pyi | 120 + stdlib/nt.pyi | 116 + stdlib/ntpath.pyi | 134 + stdlib/nturl2path.pyi | 6 + stdlib/numbers.pyi | 220 + stdlib/opcode.pyi | 53 + stdlib/operator.pyi | 219 + stdlib/optparse.pyi | 312 + stdlib/os/__init__.pyi | 1879 +++++ stdlib/os/path.pyi | 8 + stdlib/ossaudiodev.pyi | 132 + stdlib/pathlib/__init__.pyi | 358 + stdlib/pathlib/types.pyi | 8 + stdlib/pdb.pyi | 275 + stdlib/pickle.pyi | 240 + stdlib/pickletools.pyi | 176 + stdlib/pipes.pyi | 16 + stdlib/pkgutil.pyi | 60 + stdlib/platform.pyi | 100 + stdlib/plistlib.pyi | 84 + stdlib/poplib.pyi | 93 + stdlib/posix.pyi | 427 + stdlib/posixpath.pyi | 230 + stdlib/pprint.pyi | 170 + stdlib/profile.pyi | 31 + stdlib/profiling/__init__.pyi | 3 + stdlib/profiling/sampling/__init__.pyi | 17 + stdlib/profiling/sampling/collector.pyi | 25 + stdlib/profiling/sampling/gecko_collector.pyi | 111 + .../profiling/sampling/heatmap_collector.pyi | 24 + stdlib/profiling/sampling/jsonl_collector.pyi | 15 + .../profiling/sampling/pstats_collector.pyi | 17 + stdlib/profiling/sampling/stack_collector.pyi | 39 + stdlib/profiling/sampling/string_table.pyi | 5 + stdlib/profiling/tracing.pyi | 9 + stdlib/pstats.pyi | 96 + stdlib/pty.pyi | 24 + stdlib/pwd.pyi | 27 + stdlib/py_compile.pyi | 28 + stdlib/pyclbr.pyi | 57 + stdlib/pydoc.pyi | 348 + stdlib/pydoc_data/__init__.pyi | 0 stdlib/pydoc_data/module_docs.pyi | 3 + stdlib/pydoc_data/topics.pyi | 3 + stdlib/pyexpat/__init__.pyi | 91 + stdlib/pyexpat/errors.pyi | 53 + stdlib/pyexpat/model.pyi | 13 + stdlib/queue.pyi | 55 + stdlib/quopri.pyi | 12 + stdlib/random.pyi | 135 + stdlib/re.pyi | 347 + stdlib/readline.pyi | 39 + stdlib/reprlib.pyi | 64 + stdlib/resource.pyi | 102 + stdlib/rlcompleter.pyi | 9 + stdlib/runpy.pyi | 24 + stdlib/sched.pyi | 34 + stdlib/secrets.pyi | 17 + stdlib/select.pyi | 171 + stdlib/selectors.pyi | 67 + stdlib/shelve.pyi | 110 + stdlib/shlex.pyi | 63 + stdlib/shutil.pyi | 243 + stdlib/signal.pyi | 174 + stdlib/site.pyi | 46 + stdlib/smtpd.pyi | 92 + stdlib/smtplib.pyi | 223 + stdlib/sndhdr.pyi | 14 + stdlib/socket.pyi | 1586 ++++ stdlib/socketserver.pyi | 170 + stdlib/spwd.pyi | 45 + stdlib/sqlite3/__init__.pyi | 510 ++ stdlib/sqlite3/dbapi2.pyi | 244 + stdlib/sqlite3/dump.pyi | 2 + stdlib/sre_compile.pyi | 12 + stdlib/sre_constants.pyi | 135 + stdlib/sre_parse.pyi | 102 + stdlib/ssl.pyi | 540 ++ stdlib/stat.pyi | 126 + stdlib/statistics.pyi | 161 + stdlib/string/__init__.pyi | 81 + stdlib/string/templatelib.pyi | 36 + stdlib/stringprep.pyi | 29 + stdlib/struct.pyi | 5 + stdlib/subprocess.pyi | 1484 ++++ stdlib/sunau.pyi | 82 + stdlib/symtable.pyi | 95 + stdlib/sys/__init__.pyi | 537 ++ stdlib/sys/__jit.pyi | 11 + stdlib/sys/_monitoring.pyi | 69 + stdlib/sysconfig.pyi | 59 + stdlib/syslog.pyi | 58 + stdlib/tabnanny.pyi | 16 + stdlib/tarfile.pyi | 864 ++ stdlib/telnetlib.pyi | 123 + stdlib/tempfile.pyi | 474 ++ stdlib/termios.pyi | 303 + stdlib/textwrap.pyi | 103 + stdlib/this.pyi | 2 + stdlib/threading.pyi | 221 + stdlib/time.pyi | 117 + stdlib/timeit.pyi | 46 + stdlib/tkinter/__init__.pyi | 4370 ++++++++++ stdlib/tkinter/colorchooser.pyi | 12 + stdlib/tkinter/commondialog.pyi | 14 + stdlib/tkinter/constants.pyi | 80 + stdlib/tkinter/dialog.pyi | 13 + stdlib/tkinter/dnd.pyi | 19 + stdlib/tkinter/filedialog.pyi | 149 + stdlib/tkinter/font.pyi | 120 + stdlib/tkinter/messagebox.pyi | 98 + stdlib/tkinter/scrolledtext.pyi | 9 + stdlib/tkinter/simpledialog.pyi | 58 + stdlib/tkinter/tix.pyi | 299 + stdlib/tkinter/ttk.pyi | 1434 ++++ stdlib/token.pyi | 166 + stdlib/tokenize.pyi | 201 + stdlib/tomllib.pyi | 27 + stdlib/trace.pyi | 85 + stdlib/traceback.pyi | 293 + stdlib/tracemalloc.pyi | 123 + stdlib/tty.pyi | 29 + stdlib/turtle.pyi | 856 ++ stdlib/types.pyi | 746 ++ stdlib/typing.pyi | 1243 +++ stdlib/typing_extensions.pyi | 746 ++ stdlib/unicodedata.pyi | 94 + stdlib/unittest/__init__.pyi | 63 + stdlib/unittest/_log.pyi | 29 + stdlib/unittest/async_case.pyi | 24 + stdlib/unittest/case.pyi | 352 + stdlib/unittest/loader.pyi | 55 + stdlib/unittest/main.pyi | 74 + stdlib/unittest/mock.pyi | 555 ++ stdlib/unittest/result.pyi | 46 + stdlib/unittest/runner.pyi | 93 + stdlib/unittest/signals.pyi | 15 + stdlib/unittest/suite.pyi | 23 + stdlib/unittest/util.pyi | 39 + stdlib/urllib/__init__.pyi | 0 stdlib/urllib/error.pyi | 29 + stdlib/urllib/parse.pyi | 354 + stdlib/urllib/request.pyi | 443 + stdlib/urllib/response.pyi | 45 + stdlib/urllib/robotparser.pyi | 20 + stdlib/uu.pyi | 12 + stdlib/uuid.pyi | 106 + stdlib/venv/__init__.pyi | 86 + stdlib/warnings.pyi | 146 + stdlib/wave.pyi | 105 + stdlib/weakref.pyi | 213 + stdlib/webbrowser.pyi | 79 + stdlib/winreg.pyi | 137 + stdlib/winsound.pyi | 40 + stdlib/wsgiref/__init__.pyi | 0 stdlib/wsgiref/handlers.pyi | 91 + stdlib/wsgiref/headers.pyi | 27 + stdlib/wsgiref/simple_server.pyi | 37 + stdlib/wsgiref/types.pyi | 31 + stdlib/wsgiref/util.pyi | 26 + stdlib/wsgiref/validate.pyi | 50 + stdlib/xdrlib.pyi | 57 + stdlib/xml/__init__.pyi | 9 + stdlib/xml/dom/NodeFilter.pyi | 22 + stdlib/xml/dom/__init__.pyi | 101 + stdlib/xml/dom/domreg.pyi | 8 + stdlib/xml/dom/expatbuilder.pyi | 126 + stdlib/xml/dom/minicompat.pyi | 24 + stdlib/xml/dom/minidom.pyi | 693 ++ stdlib/xml/dom/pulldom.pyi | 109 + stdlib/xml/dom/xmlbuilder.pyi | 82 + stdlib/xml/etree/ElementInclude.pyi | 28 + stdlib/xml/etree/ElementPath.pyi | 42 + stdlib/xml/etree/ElementTree.pyi | 402 + stdlib/xml/etree/__init__.pyi | 0 stdlib/xml/etree/cElementTree.pyi | 1 + stdlib/xml/parsers/__init__.pyi | 1 + stdlib/xml/parsers/expat/__init__.pyi | 7 + stdlib/xml/parsers/expat/errors.pyi | 1 + stdlib/xml/parsers/expat/model.pyi | 1 + stdlib/xml/sax/__init__.pyi | 42 + stdlib/xml/sax/_exceptions.pyi | 19 + stdlib/xml/sax/expatreader.pyi | 72 + stdlib/xml/sax/handler.pyi | 85 + stdlib/xml/sax/saxutils.pyi | 69 + stdlib/xml/sax/xmlreader.pyi | 94 + stdlib/xml/utils.pyi | 2 + stdlib/xmlrpc/__init__.pyi | 0 stdlib/xmlrpc/client.pyi | 300 + stdlib/xmlrpc/server.pyi | 149 + stdlib/xxlimited.pyi | 15 + stdlib/zipapp.pyi | 19 + stdlib/zipfile/__init__.pyi | 411 + stdlib/zipfile/_path/__init__.pyi | 87 + stdlib/zipfile/_path/glob.pyi | 26 + stdlib/zipimport.pyi | 44 + stdlib/zlib.pyi | 81 + stdlib/zoneinfo/__init__.pyi | 36 + stdlib/zoneinfo/_common.pyi | 14 + stdlib/zoneinfo/_tzpath.pyi | 13 + stubs/Authlib/@tests/stubtest_allowlist.txt | 54 + stubs/Authlib/METADATA.toml | 3 + stubs/Authlib/authlib/__init__.pyi | 8 + stubs/Authlib/authlib/common/__init__.pyi | 0 stubs/Authlib/authlib/common/encoding.pyi | 28 + stubs/Authlib/authlib/common/errors.pyi | 21 + stubs/Authlib/authlib/common/language.pyi | 1 + stubs/Authlib/authlib/common/security.pyi | 6 + stubs/Authlib/authlib/common/urls.pyi | 25 + stubs/Authlib/authlib/consts.pyi | 8 + stubs/Authlib/authlib/deprecate.pyi | 3 + .../Authlib/authlib/integrations/__init__.pyi | 0 .../integrations/base_client/__init__.pyi | 29 + .../integrations/base_client/async_app.pyi | 19 + .../integrations/base_client/async_openid.pyi | 12 + .../integrations/base_client/errors.pyi | 23 + .../base_client/framework_integration.pyi | 13 + .../integrations/base_client/registry.pyi | 19 + .../integrations/base_client/sync_app.pyi | 96 + .../integrations/base_client/sync_openid.pyi | 17 + .../integrations/django_client/__init__.pyi | 10 + .../integrations/django_client/apps.pyi | 31 + .../django_client/integration.pyi | 11 + .../integrations/django_oauth1/__init__.pyi | 4 + .../django_oauth1/authorization_server.pyi | 26 + .../integrations/django_oauth1/nonce.pyi | 1 + .../django_oauth1/resource_protector.pyi | 14 + .../integrations/django_oauth2/__init__.pyi | 8 + .../django_oauth2/authorization_server.pyi | 24 + .../integrations/django_oauth2/endpoints.pyi | 5 + .../integrations/django_oauth2/requests.pyi | 20 + .../django_oauth2/resource_protector.pyi | 15 + .../integrations/django_oauth2/signals.pyi | 6 + .../integrations/flask_client/__init__.pyi | 20 + .../integrations/flask_client/apps.pyi | 28 + .../integrations/flask_client/integration.pyi | 10 + .../integrations/flask_oauth1/__init__.pyi | 7 + .../flask_oauth1/authorization_server.pyi | 29 + .../integrations/flask_oauth1/cache.pyi | 8 + .../flask_oauth1/resource_protector.pyi | 18 + .../integrations/flask_oauth2/__init__.pyi | 7 + .../flask_oauth2/authorization_server.pyi | 23 + .../integrations/flask_oauth2/errors.pyi | 14 + .../integrations/flask_oauth2/requests.pyi | 27 + .../flask_oauth2/resource_protector.pyi | 15 + .../integrations/flask_oauth2/signals.pyi | 5 + .../integrations/httpx_client/__init__.pyi | 37 + .../httpx_client/assertion_client.pyi | 50 + .../httpx_client/oauth1_client.pyi | 56 + .../httpx_client/oauth2_client.pyi | 72 + .../integrations/httpx_client/utils.pyi | 7 + .../integrations/requests_client/__init__.pyi | 28 + .../requests_client/assertion_session.pyi | 31 + .../requests_client/oauth1_session.pyi | 29 + .../requests_client/oauth2_session.pyi | 43 + .../integrations/requests_client/utils.pyi | 6 + .../integrations/sqla_oauth2/__init__.pyi | 20 + .../integrations/sqla_oauth2/client_mixin.pyi | 55 + .../integrations/sqla_oauth2/functions.pyi | 21 + .../sqla_oauth2/tokens_mixins.pyi | 39 + .../starlette_client/__init__.pyi | 14 + .../integrations/starlette_client/apps.pyi | 33 + .../starlette_client/integration.pyi | 13 + stubs/Authlib/authlib/jose/__init__.pyi | 42 + .../Authlib/authlib/jose/drafts/__init__.pyi | 3 + .../authlib/jose/drafts/_jwe_algorithms.pyi | 33 + .../jose/drafts/_jwe_enc_cryptodome.pyi | 13 + .../jose/drafts/_jwe_enc_cryptography.pyi | 13 + stubs/Authlib/authlib/jose/errors.pyi | 76 + stubs/Authlib/authlib/jose/jwk.pyi | 7 + .../Authlib/authlib/jose/rfc7515/__init__.pyi | 4 + stubs/Authlib/authlib/jose/rfc7515/jws.pyi | 21 + stubs/Authlib/authlib/jose/rfc7515/models.pyi | 27 + .../Authlib/authlib/jose/rfc7516/__init__.pyi | 9 + stubs/Authlib/authlib/jose/rfc7516/jwe.pyi | 34 + stubs/Authlib/authlib/jose/rfc7516/models.pyi | 60 + .../Authlib/authlib/jose/rfc7517/__init__.pyi | 7 + .../jose/rfc7517/_cryptography_key.pyi | 35 + .../authlib/jose/rfc7517/asymmetric_key.pyi | 53 + .../Authlib/authlib/jose/rfc7517/base_key.pyi | 29 + stubs/Authlib/authlib/jose/rfc7517/jwk.pyi | 20 + .../Authlib/authlib/jose/rfc7517/key_set.pyi | 11 + .../Authlib/authlib/jose/rfc7518/__init__.pyi | 20 + stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi | 24 + .../Authlib/authlib/jose/rfc7518/jwe_algs.pyi | 73 + .../Authlib/authlib/jose/rfc7518/jwe_encs.pyi | 28 + .../Authlib/authlib/jose/rfc7518/jwe_zips.pyi | 14 + .../Authlib/authlib/jose/rfc7518/jws_algs.pyi | 70 + .../Authlib/authlib/jose/rfc7518/oct_key.pyi | 25 + .../Authlib/authlib/jose/rfc7518/rsa_key.pyi | 25 + stubs/Authlib/authlib/jose/rfc7518/util.pyi | 4 + .../Authlib/authlib/jose/rfc7519/__init__.pyi | 4 + stubs/Authlib/authlib/jose/rfc7519/claims.pyi | 22 + stubs/Authlib/authlib/jose/rfc7519/jwt.pyi | 56 + .../Authlib/authlib/jose/rfc8037/__init__.pyi | 4 + .../authlib/jose/rfc8037/jws_eddsa.pyi | 12 + .../Authlib/authlib/jose/rfc8037/okp_key.pyi | 28 + stubs/Authlib/authlib/jose/util.pyi | 7 + stubs/Authlib/authlib/oauth1/__init__.pyi | 33 + stubs/Authlib/authlib/oauth1/client.pyi | 45 + stubs/Authlib/authlib/oauth1/errors.pyi | 1 + .../authlib/oauth1/rfc5849/__init__.pyi | 35 + .../oauth1/rfc5849/authorization_server.pyi | 19 + .../authlib/oauth1/rfc5849/base_server.pyi | 12 + .../authlib/oauth1/rfc5849/client_auth.pyi | 43 + .../Authlib/authlib/oauth1/rfc5849/errors.pyi | 52 + .../Authlib/authlib/oauth1/rfc5849/models.pyi | 21 + .../authlib/oauth1/rfc5849/parameters.pyi | 3 + .../oauth1/rfc5849/resource_protector.pyi | 7 + stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi | 2 + .../authlib/oauth1/rfc5849/signature.pyi | 22 + stubs/Authlib/authlib/oauth1/rfc5849/util.pyi | 2 + .../authlib/oauth1/rfc5849/wrapper.pyi | 37 + stubs/Authlib/authlib/oauth2/__init__.pyi | 22 + stubs/Authlib/authlib/oauth2/auth.pyi | 25 + stubs/Authlib/authlib/oauth2/base.pyi | 23 + stubs/Authlib/authlib/oauth2/claims.pyi | 31 + stubs/Authlib/authlib/oauth2/client.pyi | 77 + .../authlib/oauth2/rfc6749/__init__.pyi | 86 + .../oauth2/rfc6749/authenticate_client.pyi | 13 + .../oauth2/rfc6749/authorization_server.pyi | 55 + .../authlib/oauth2/rfc6749/endpoint.pyi | 19 + .../Authlib/authlib/oauth2/rfc6749/errors.pyi | 102 + .../oauth2/rfc6749/grants/__init__.pyi | 21 + .../rfc6749/grants/authorization_code.pyi | 27 + .../authlib/oauth2/rfc6749/grants/base.pyi | 55 + .../rfc6749/grants/client_credentials.pyi | 10 + .../oauth2/rfc6749/grants/implicit.pyi | 15 + .../oauth2/rfc6749/grants/refresh_token.pyi | 18 + .../resource_owner_password_credentials.pyi | 11 + .../Authlib/authlib/oauth2/rfc6749/hooks.pyi | 8 + .../Authlib/authlib/oauth2/rfc6749/models.pyi | 24 + .../authlib/oauth2/rfc6749/parameters.pyi | 6 + .../authlib/oauth2/rfc6749/requests.pyi | 98 + .../oauth2/rfc6749/resource_protector.pyi | 19 + .../authlib/oauth2/rfc6749/token_endpoint.pyi | 11 + stubs/Authlib/authlib/oauth2/rfc6749/util.pyi | 5 + .../authlib/oauth2/rfc6749/wrappers.pyi | 5 + .../authlib/oauth2/rfc6750/__init__.pyi | 15 + .../Authlib/authlib/oauth2/rfc6750/errors.pyi | 27 + .../authlib/oauth2/rfc6750/parameters.pyi | 6 + .../Authlib/authlib/oauth2/rfc6750/token.pyi | 41 + .../authlib/oauth2/rfc6750/validator.pyi | 6 + .../authlib/oauth2/rfc7009/__init__.pyi | 4 + .../authlib/oauth2/rfc7009/parameters.pyi | 1 + .../authlib/oauth2/rfc7009/revocation.pyi | 9 + .../authlib/oauth2/rfc7521/__init__.pyi | 3 + .../Authlib/authlib/oauth2/rfc7521/client.pyi | 42 + .../authlib/oauth2/rfc7523/__init__.pyi | 18 + .../authlib/oauth2/rfc7523/assertion.pyi | 27 + stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi | 16 + .../Authlib/authlib/oauth2/rfc7523/client.pyi | 28 + .../authlib/oauth2/rfc7523/jwt_bearer.pyi | 25 + .../Authlib/authlib/oauth2/rfc7523/token.pyi | 15 + .../authlib/oauth2/rfc7523/validator.pyi | 21 + .../authlib/oauth2/rfc7591/__init__.pyi | 17 + .../Authlib/authlib/oauth2/rfc7591/claims.pyi | 25 + .../authlib/oauth2/rfc7591/endpoint.pyi | 22 + .../Authlib/authlib/oauth2/rfc7591/errors.pyi | 13 + .../authlib/oauth2/rfc7592/__init__.pyi | 3 + .../authlib/oauth2/rfc7592/endpoint.pyi | 24 + .../authlib/oauth2/rfc7636/__init__.pyi | 3 + .../authlib/oauth2/rfc7636/challenge.pyi | 23 + .../authlib/oauth2/rfc7662/__init__.pyi | 5 + .../authlib/oauth2/rfc7662/introspection.pyi | 11 + .../Authlib/authlib/oauth2/rfc7662/models.pyi | 8 + .../oauth2/rfc7662/token_validator.pyi | 7 + .../authlib/oauth2/rfc8414/__init__.pyi | 4 + .../Authlib/authlib/oauth2/rfc8414/models.pyi | 42 + .../authlib/oauth2/rfc8414/well_known.pyi | 1 + .../authlib/oauth2/rfc8628/__init__.pyi | 19 + .../authlib/oauth2/rfc8628/device_code.pyi | 17 + .../authlib/oauth2/rfc8628/endpoint.pyi | 21 + .../Authlib/authlib/oauth2/rfc8628/errors.pyi | 10 + .../Authlib/authlib/oauth2/rfc8628/models.pyi | 13 + .../authlib/oauth2/rfc8693/__init__.pyi | 0 .../authlib/oauth2/rfc9068/__init__.pyi | 6 + .../Authlib/authlib/oauth2/rfc9068/claims.pyi | 12 + .../authlib/oauth2/rfc9068/introspection.pyi | 14 + .../authlib/oauth2/rfc9068/revocation.pyi | 10 + .../Authlib/authlib/oauth2/rfc9068/token.pyi | 17 + .../oauth2/rfc9068/token_validator.pyi | 16 + .../authlib/oauth2/rfc9101/__init__.pyi | 5 + .../oauth2/rfc9101/authorization_server.pyi | 17 + .../authlib/oauth2/rfc9101/discovery.pyi | 3 + .../Authlib/authlib/oauth2/rfc9101/errors.pyi | 23 + .../authlib/oauth2/rfc9101/registration.pyi | 7 + .../authlib/oauth2/rfc9207/__init__.pyi | 4 + .../authlib/oauth2/rfc9207/discovery.pyi | 5 + .../authlib/oauth2/rfc9207/parameter.pyi | 4 + stubs/Authlib/authlib/oidc/__init__.pyi | 0 stubs/Authlib/authlib/oidc/core/__init__.pyi | 31 + stubs/Authlib/authlib/oidc/core/claims.pyi | 36 + stubs/Authlib/authlib/oidc/core/errors.pyi | 28 + .../authlib/oidc/core/grants/__init__.pyi | 5 + .../authlib/oidc/core/grants/_legacy.pyi | 11 + .../Authlib/authlib/oidc/core/grants/code.pyi | 25 + .../authlib/oidc/core/grants/hybrid.pyi | 16 + .../authlib/oidc/core/grants/implicit.pyi | 21 + .../Authlib/authlib/oidc/core/grants/util.pyi | 21 + stubs/Authlib/authlib/oidc/core/models.pyi | 7 + stubs/Authlib/authlib/oidc/core/userinfo.pyi | 19 + stubs/Authlib/authlib/oidc/core/util.pyi | 7 + .../authlib/oidc/discovery/__init__.pyi | 4 + .../Authlib/authlib/oidc/discovery/models.pyi | 34 + .../authlib/oidc/discovery/well_known.pyi | 1 + .../authlib/oidc/registration/__init__.pyi | 3 + .../authlib/oidc/registration/claims.pyi | 29 + .../authlib/oidc/rpinitiated/__init__.pyi | 5 + .../authlib/oidc/rpinitiated/discovery.pyi | 5 + .../authlib/oidc/rpinitiated/end_session.pyi | 26 + .../authlib/oidc/rpinitiated/registration.pyi | 7 + stubs/Deprecated/METADATA.toml | 2 + stubs/Deprecated/deprecated/__init__.pyi | 9 + stubs/Deprecated/deprecated/classic.pyi | 35 + stubs/Deprecated/deprecated/params.pyi | 21 + stubs/Deprecated/deprecated/sphinx.pyi | 36 + stubs/Flask-Cors/METADATA.toml | 5 + stubs/Flask-Cors/flask_cors/__init__.pyi | 11 + stubs/Flask-Cors/flask_cors/core.pyi | 74 + stubs/Flask-Cors/flask_cors/decorator.pyi | 22 + stubs/Flask-Cors/flask_cors/extension.pyi | 43 + .../@tests/stubtest_allowlist.txt | 2 + stubs/Flask-Migrate/METADATA.toml | 4 + .../Flask-Migrate/flask_migrate/__init__.pyi | 136 + .../@tests/stubtest_allowlist.txt | 4 + stubs/Flask-SocketIO/METADATA.toml | 3 + .../flask_socketio/__init__.pyi | 166 + .../flask_socketio/namespace.pyi | 68 + .../flask_socketio/test_client.pyi | 41 + .../JACK-Client/@tests/stubtest_allowlist.txt | 2 + stubs/JACK-Client/METADATA.toml | 14 + stubs/JACK-Client/jack/__init__.pyi | 341 + .../Jetson.GPIO/@tests/stubtest_allowlist.txt | 9 + stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi | 3 + stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi | 22 + stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi | 44 + stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi | 84 + stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi | 17 + .../Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi | 81 + .../Jetson/GPIO/gpio_pinmux_lookup.pyi | 6 + stubs/Jetson.GPIO/Jetson/__init__.pyi | 0 stubs/Jetson.GPIO/METADATA.toml | 2 + stubs/Markdown/@tests/stubtest_allowlist.txt | 4 + stubs/Markdown/METADATA.toml | 2 + stubs/Markdown/markdown/__init__.pyi | 5 + stubs/Markdown/markdown/__main__.pyi | 10 + stubs/Markdown/markdown/__meta__.pyi | 2 + stubs/Markdown/markdown/blockparser.pyi | 23 + stubs/Markdown/markdown/blockprocessors.pyi | 67 + stubs/Markdown/markdown/core.pyi | 75 + .../Markdown/markdown/extensions/__init__.pyi | 14 + stubs/Markdown/markdown/extensions/abbr.pyi | 39 + .../markdown/extensions/admonition.pyi | 22 + .../markdown/extensions/attr_list.pyi | 23 + .../markdown/extensions/codehilite.pyi | 42 + .../Markdown/markdown/extensions/def_list.pyi | 13 + stubs/Markdown/markdown/extensions/extra.pyi | 8 + .../markdown/extensions/fenced_code.pyi | 21 + .../markdown/extensions/footnotes.pyi | 73 + .../markdown/extensions/legacy_attrs.pyi | 15 + .../markdown/extensions/legacy_em.pyi | 11 + .../markdown/extensions/md_in_html.pyi | 41 + stubs/Markdown/markdown/extensions/meta.pyi | 20 + stubs/Markdown/markdown/extensions/nl2br.pyi | 7 + .../markdown/extensions/sane_lists.pyi | 13 + stubs/Markdown/markdown/extensions/smarty.pyi | 44 + stubs/Markdown/markdown/extensions/tables.pyi | 22 + stubs/Markdown/markdown/extensions/toc.pyi | 70 + .../markdown/extensions/wikilinks.pyi | 17 + stubs/Markdown/markdown/htmlparser.pyi | 29 + stubs/Markdown/markdown/inlinepatterns.pyi | 112 + stubs/Markdown/markdown/postprocessors.pyi | 27 + stubs/Markdown/markdown/preprocessors.pyi | 11 + stubs/Markdown/markdown/serializers.pyi | 9 + stubs/Markdown/markdown/test_tools.pyi | 30 + stubs/Markdown/markdown/treeprocessors.pyi | 26 + stubs/Markdown/markdown/util.pyi | 70 + stubs/PyAutoGUI/@tests/stubtest_allowlist.txt | 1 + stubs/PyAutoGUI/METADATA.toml | 3 + stubs/PyAutoGUI/pyautogui/__init__.pyi | 252 + stubs/PyMeeus/METADATA.toml | 2 + stubs/PyMeeus/pymeeus/Angle.pyi | 100 + stubs/PyMeeus/pymeeus/Coordinates.pyi | 196 + stubs/PyMeeus/pymeeus/CurveFitting.pyi | 45 + stubs/PyMeeus/pymeeus/Earth.pyi | 64 + stubs/PyMeeus/pymeeus/Epoch.pyi | 139 + stubs/PyMeeus/pymeeus/Interpolation.pyi | 44 + stubs/PyMeeus/pymeeus/Jupiter.pyi | 38 + stubs/PyMeeus/pymeeus/JupiterMoons.pyi | 83 + stubs/PyMeeus/pymeeus/Mars.pyi | 38 + stubs/PyMeeus/pymeeus/Mercury.pyi | 42 + stubs/PyMeeus/pymeeus/Minor.pyi | 10 + stubs/PyMeeus/pymeeus/Moon.pyi | 39 + stubs/PyMeeus/pymeeus/Neptune.pyi | 30 + stubs/PyMeeus/pymeeus/Pluto.pyi | 17 + stubs/PyMeeus/pymeeus/Saturn.pyi | 44 + stubs/PyMeeus/pymeeus/Sun.pyi | 35 + stubs/PyMeeus/pymeeus/Uranus.pyi | 34 + stubs/PyMeeus/pymeeus/Venus.pyi | 44 + stubs/PyMeeus/pymeeus/__init__.pyi | 0 stubs/PyMeeus/pymeeus/base.pyi | 8 + stubs/PyMySQL/@tests/stubtest_allowlist.txt | 3 + .../@tests/test_cases/check_connection.py | 15 + stubs/PyMySQL/METADATA.toml | 2 + stubs/PyMySQL/pymysql/__init__.pyi | 107 + stubs/PyMySQL/pymysql/_auth.pyi | 13 + stubs/PyMySQL/pymysql/charset.pyi | 22 + stubs/PyMySQL/pymysql/connections.pyi | 281 + stubs/PyMySQL/pymysql/constants/CLIENT.pyi | 27 + stubs/PyMySQL/pymysql/constants/COMMAND.pyi | 34 + stubs/PyMySQL/pymysql/constants/CR.pyi | 77 + stubs/PyMySQL/pymysql/constants/ER.pyi | 476 ++ .../PyMySQL/pymysql/constants/FIELD_TYPE.pyi | 32 + stubs/PyMySQL/pymysql/constants/FLAG.pyi | 17 + .../pymysql/constants/SERVER_STATUS.pyi | 12 + stubs/PyMySQL/pymysql/constants/__init__.pyi | 0 stubs/PyMySQL/pymysql/converters.pyi | 52 + stubs/PyMySQL/pymysql/cursors.pyi | 58 + stubs/PyMySQL/pymysql/err.pyi | 24 + stubs/PyMySQL/pymysql/optionfile.pyi | 40 + stubs/PyMySQL/pymysql/protocol.pyi | 60 + stubs/PyMySQL/pymysql/times.pyi | 10 + stubs/PyScreeze/@tests/stubtest_allowlist.txt | 2 + .../@tests/stubtest_allowlist_linux.txt | 2 + stubs/PyScreeze/METADATA.toml | 11 + stubs/PyScreeze/pyscreeze/__init__.pyi | 218 + stubs/PySocks/@tests/stubtest_allowlist.txt | 3 + stubs/PySocks/METADATA.toml | 2 + stubs/PySocks/socks.pyi | 144 + stubs/PySocks/sockshandler.pyi | 97 + stubs/PyYAML/@tests/stubtest_allowlist.txt | 11 + stubs/PyYAML/METADATA.toml | 2 + stubs/PyYAML/yaml/__init__.pyi | 450 + stubs/PyYAML/yaml/_yaml.pyi | 60 + stubs/PyYAML/yaml/composer.pyi | 20 + stubs/PyYAML/yaml/constructor.pyi | 105 + stubs/PyYAML/yaml/cyaml.pyi | 68 + stubs/PyYAML/yaml/dumper.pyi | 72 + stubs/PyYAML/yaml/emitter.pyi | 136 + stubs/PyYAML/yaml/error.pyi | 28 + stubs/PyYAML/yaml/events.pyi | 62 + stubs/PyYAML/yaml/loader.pyi | 29 + stubs/PyYAML/yaml/nodes.pyi | 32 + stubs/PyYAML/yaml/parser.pyi | 47 + stubs/PyYAML/yaml/reader.pyi | 40 + stubs/PyYAML/yaml/representer.pyi | 63 + stubs/PyYAML/yaml/resolver.pyi | 27 + stubs/PyYAML/yaml/scanner.pyi | 99 + stubs/PyYAML/yaml/serializer.pyi | 27 + stubs/PyYAML/yaml/tokens.pyi | 93 + stubs/Pygments/@tests/stubtest_allowlist.txt | 20 + .../@tests/test_cases/check_pygments.py | 10 + stubs/Pygments/METADATA.toml | 7 + stubs/Pygments/pygments/__init__.pyi | 25 + stubs/Pygments/pygments/cmdline.pyi | 9 + stubs/Pygments/pygments/console.pyi | 10 + stubs/Pygments/pygments/filter.pyi | 29 + stubs/Pygments/pygments/filters/__init__.pyi | 86 + stubs/Pygments/pygments/formatter.pyi | 60 + .../Pygments/pygments/formatters/__init__.pyi | 51 + .../Pygments/pygments/formatters/_mapping.pyi | 3 + stubs/Pygments/pygments/formatters/bbcode.pyi | 14 + stubs/Pygments/pygments/formatters/groff.pyi | 18 + stubs/Pygments/pygments/formatters/html.pyi | 43 + stubs/Pygments/pygments/formatters/img.pyi | 58 + stubs/Pygments/pygments/formatters/irc.pyi | 16 + stubs/Pygments/pygments/formatters/latex.pyi | 36 + stubs/Pygments/pygments/formatters/other.pyi | 22 + .../pygments/formatters/pangomarkup.pyi | 14 + stubs/Pygments/pygments/formatters/rtf.pyi | 17 + stubs/Pygments/pygments/formatters/svg.pyi | 24 + .../Pygments/pygments/formatters/terminal.pyi | 17 + .../pygments/formatters/terminal256.pyi | 36 + stubs/Pygments/pygments/lexer.pyi | 121 + stubs/Pygments/pygments/lexers/__init__.pyi | 18 + stubs/Pygments/pygments/lexers/javascript.pyi | 40 + stubs/Pygments/pygments/lexers/jsx.pyi | 5 + stubs/Pygments/pygments/lexers/kusto.pyi | 10 + stubs/Pygments/pygments/lexers/ldap.pyi | 6 + stubs/Pygments/pygments/lexers/lean.pyi | 7 + stubs/Pygments/pygments/lexers/lisp.pyi | 96 + stubs/Pygments/pygments/lexers/prql.pyi | 11 + stubs/Pygments/pygments/lexers/vip.pyi | 19 + stubs/Pygments/pygments/lexers/vyper.pyi | 5 + stubs/Pygments/pygments/modeline.pyi | 3 + stubs/Pygments/pygments/plugin.pyi | 20 + stubs/Pygments/pygments/regexopt.pyi | 12 + stubs/Pygments/pygments/scanner.pyi | 19 + stubs/Pygments/pygments/sphinxext.pyi | 17 + stubs/Pygments/pygments/style.pyi | 41 + stubs/Pygments/pygments/styles/__init__.pyi | 12 + stubs/Pygments/pygments/token.pyi | 34 + stubs/Pygments/pygments/unistring.pyi | 71 + stubs/Pygments/pygments/util.pyi | 53 + stubs/RPi.GPIO/METADATA.toml | 10 + stubs/RPi.GPIO/RPi/GPIO/__init__.pyi | 66 + stubs/RPi.GPIO/RPi/__init__.pyi | 0 .../Send2Trash/@tests/stubtest_allowlist.txt | 2 + stubs/Send2Trash/METADATA.toml | 2 + stubs/Send2Trash/send2trash/__init__.pyi | 7 + stubs/Send2Trash/send2trash/__main__.pyi | 3 + stubs/Send2Trash/send2trash/exceptions.pyi | 5 + stubs/Send2Trash/send2trash/util.pyi | 5 + stubs/TgCrypto/@tests/stubtest_allowlist.txt | 7 + stubs/TgCrypto/METADATA.toml | 2 + stubs/TgCrypto/tgcrypto/__init__.pyi | 8 + stubs/WTForms/@tests/stubtest_allowlist.txt | 12 + .../@tests/test_cases/check_choices.py | 67 + .../@tests/test_cases/check_filters.py | 45 + stubs/WTForms/@tests/test_cases/check_form.py | 16 + .../@tests/test_cases/check_validators.py | 33 + .../@tests/test_cases/check_widgets.py | 26 + stubs/WTForms/METADATA.toml | 3 + stubs/WTForms/wtforms/__init__.pyi | 85 + stubs/WTForms/wtforms/csrf/__init__.pyi | 0 stubs/WTForms/wtforms/csrf/core.pyi | 41 + stubs/WTForms/wtforms/csrf/session.pyi | 20 + stubs/WTForms/wtforms/fields/__init__.pyi | 77 + stubs/WTForms/wtforms/fields/choices.pyi | 79 + stubs/WTForms/wtforms/fields/core.pyi | 134 + stubs/WTForms/wtforms/fields/datetime.pyi | 138 + stubs/WTForms/wtforms/fields/form.pyi | 40 + stubs/WTForms/wtforms/fields/list.pyi | 51 + stubs/WTForms/wtforms/fields/numeric.pyi | 146 + stubs/WTForms/wtforms/fields/simple.pyi | 81 + stubs/WTForms/wtforms/form.pyi | 87 + stubs/WTForms/wtforms/i18n.pyi | 32 + stubs/WTForms/wtforms/meta.pyi | 60 + stubs/WTForms/wtforms/utils.pyi | 18 + stubs/WTForms/wtforms/validators.pyi | 214 + stubs/WTForms/wtforms/widgets/__init__.pyi | 59 + stubs/WTForms/wtforms/widgets/core.pyi | 120 + stubs/WebOb/@tests/stubtest_allowlist.txt | 166 + .../@tests/test_cases/check_cachecontrol.py | 102 + stubs/WebOb/@tests/test_cases/check_wsgify.py | 115 + stubs/WebOb/METADATA.toml | 2 + stubs/WebOb/webob/__init__.pyi | 28 + stubs/WebOb/webob/_types.pyi | 23 + stubs/WebOb/webob/acceptparse.pyi | 757 ++ stubs/WebOb/webob/byterange.pyi | 34 + stubs/WebOb/webob/cachecontrol.pyi | 108 + stubs/WebOb/webob/client.pyi | 14 + stubs/WebOb/webob/compat.pyi | 24 + stubs/WebOb/webob/cookies.pyi | 196 + stubs/WebOb/webob/datetime_utils.pyi | 40 + stubs/WebOb/webob/dec.pyi | 204 + stubs/WebOb/webob/descriptors.pyi | 100 + stubs/WebOb/webob/etag.pyi | 45 + stubs/WebOb/webob/exc.pyi | 190 + stubs/WebOb/webob/headers.pyi | 36 + stubs/WebOb/webob/multidict.pyi | 197 + stubs/WebOb/webob/request.pyi | 259 + stubs/WebOb/webob/response.pyi | 181 + stubs/WebOb/webob/static.pyi | 40 + stubs/WebOb/webob/util.pyi | 12 + stubs/WebTest/@tests/stubtest_allowlist.txt | 19 + stubs/WebTest/METADATA.toml | 3 + stubs/WebTest/webtest/__init__.pyi | 14 + stubs/WebTest/webtest/app.pyi | 206 + stubs/WebTest/webtest/debugapp.pyi | 22 + stubs/WebTest/webtest/forms.pyi | 191 + stubs/WebTest/webtest/http.pyi | 30 + stubs/WebTest/webtest/response.pyi | 93 + stubs/aiofiles/@tests/stubtest_allowlist.txt | 91 + .../@tests/stubtest_allowlist_darwin.txt | 2 + .../@tests/stubtest_allowlist_linux.txt | 2 + stubs/aiofiles/METADATA.toml | 6 + stubs/aiofiles/aiofiles/__init__.pyi | 12 + stubs/aiofiles/aiofiles/base.pyi | 31 + stubs/aiofiles/aiofiles/os.pyi | 171 + stubs/aiofiles/aiofiles/ospath.pyi | 47 + stubs/aiofiles/aiofiles/tempfile/__init__.pyi | 324 + .../aiofiles/aiofiles/tempfile/temptypes.pyi | 49 + .../aiofiles/aiofiles/threadpool/__init__.pyi | 110 + stubs/aiofiles/aiofiles/threadpool/binary.pyi | 59 + stubs/aiofiles/aiofiles/threadpool/text.pyi | 45 + stubs/aiofiles/aiofiles/threadpool/utils.pyi | 10 + stubs/antlr4-python3-runtime/METADATA.toml | 5 + .../antlr4/BufferedTokenStream.pyi | 39 + .../antlr4/CommonTokenFactory.pyi | 23 + .../antlr4/CommonTokenStream.pyi | 12 + .../antlr4/FileStream.pyi | 7 + .../antlr4/InputStream.pyi | 24 + .../antlr4/IntervalSet.pyi | 20 + .../antlr4/LL1Analyzer.pyi | 27 + stubs/antlr4-python3-runtime/antlr4/Lexer.pyi | 102 + .../antlr4/ListTokenSource.pyi | 20 + .../antlr4-python3-runtime/antlr4/Parser.pyi | 99 + .../antlr4/ParserInterpreter.pyi | 46 + .../antlr4/ParserRuleContext.pyi | 49 + .../antlr4/PredictionContext.pyi | 87 + .../antlr4/Recognizer.pyi | 38 + .../antlr4/RuleContext.pyi | 31 + .../antlr4/StdinStream.pyi | 4 + stubs/antlr4-python3-runtime/antlr4/Token.pyi | 53 + .../antlr4/TokenStreamRewriter.pyi | 56 + stubs/antlr4-python3-runtime/antlr4/Utils.pyi | 2 + .../antlr4/__init__.pyi | 32 + .../antlr4-python3-runtime/antlr4/_pygrun.pyi | 4 + .../antlr4-python3-runtime/antlr4/atn/ATN.pyi | 41 + .../antlr4/atn/ATNConfig.pyi | 46 + .../antlr4/atn/ATNConfigSet.pyi | 55 + .../antlr4/atn/ATNDeserializationOptions.pyi | 10 + .../antlr4/atn/ATNDeserializer.pyi | 49 + .../antlr4/atn/ATNSimulator.pyi | 18 + .../antlr4/atn/ATNState.pyi | 107 + .../antlr4/atn/ATNType.pyi | 7 + .../antlr4/atn/LexerATNSimulator.pyi | 89 + .../antlr4/atn/LexerAction.pyi | 89 + .../antlr4/atn/LexerActionExecutor.pyi | 16 + .../antlr4/atn/ParserATNSimulator.pyi | 134 + .../antlr4/atn/PredictionMode.pyi | 41 + .../antlr4/atn/SemanticContext.pyi | 52 + .../antlr4/atn/Transition.pyi | 111 + .../antlr4/atn/__init__.pyi | 0 .../antlr4-python3-runtime/antlr4/dfa/DFA.pyi | 22 + .../antlr4/dfa/DFASerializer.pyi | 18 + .../antlr4/dfa/DFAState.pyi | 34 + .../antlr4/dfa/__init__.pyi | 0 .../antlr4/error/DiagnosticErrorListener.pyi | 20 + .../antlr4/error/ErrorListener.pyi | 19 + .../antlr4/error/ErrorStrategy.pyi | 56 + .../antlr4/error/Errors.pyi | 60 + .../antlr4/error/__init__.pyi | 0 .../antlr4/tree/Chunk.pyi | 14 + .../antlr4/tree/ParseTreeMatch.pyi | 17 + .../antlr4/tree/ParseTreePattern.pyi | 16 + .../antlr4/tree/ParseTreePatternMatcher.pyi | 45 + .../antlr4/tree/RuleTagToken.pyi | 18 + .../antlr4/tree/TokenTagToken.pyi | 10 + .../antlr4/tree/Tree.pyi | 56 + .../antlr4/tree/Trees.pyi | 31 + .../antlr4/tree/__init__.pyi | 0 .../antlr4/xpath/XPath.pyi | 67 + .../antlr4/xpath/XPathLexer.pyi | 28 + .../antlr4/xpath/__init__.pyi | 0 stubs/assertpy/@tests/stubtest_allowlist.txt | 7 + stubs/assertpy/METADATA.toml | 2 + stubs/assertpy/assertpy/__init__.pyi | 12 + stubs/assertpy/assertpy/assertpy.pyi | 73 + stubs/assertpy/assertpy/base.pyi | 21 + stubs/assertpy/assertpy/collection.pyi | 20 + stubs/assertpy/assertpy/contains.pyi | 18 + stubs/assertpy/assertpy/date.pyi | 11 + stubs/assertpy/assertpy/dict.pyi | 13 + stubs/assertpy/assertpy/dynamic.pyi | 7 + stubs/assertpy/assertpy/exception.pyi | 9 + stubs/assertpy/assertpy/extracting.pyi | 15 + stubs/assertpy/assertpy/file.pyi | 14 + stubs/assertpy/assertpy/helpers.pyi | 3 + stubs/assertpy/assertpy/numeric.pyi | 25 + stubs/assertpy/assertpy/snapshot.pyi | 6 + stubs/assertpy/assertpy/string.pyi | 17 + stubs/atheris/METADATA.toml | 6 + stubs/atheris/atheris/__init__.pyi | 9 + stubs/atheris/atheris/function_hooks.pyi | 14 + stubs/atheris/atheris/import_hook.pyi | 36 + stubs/atheris/atheris/instrument_bytecode.pyi | 7 + stubs/atheris/atheris/utils.pyi | 20 + stubs/atheris/atheris/version_dependent.pyi | 32 + .../@tests/stubtest_allowlist.txt | 7 + stubs/auth0-python/METADATA.toml | 4 + stubs/auth0-python/auth0/__init__.pyi | 3 + stubs/auth0-python/auth0/asyncify.pyi | 6 + .../auth0/authentication/__init__.pyi | 10 + .../authentication/async_token_verifier.pyi | 24 + .../authentication/back_channel_login.pyi | 13 + .../auth0/authentication/base.pyi | 30 + .../authentication/client_authentication.pyi | 13 + .../auth0/authentication/database.pyi | 21 + .../auth0/authentication/delegated.pyi | 12 + .../auth0/authentication/enterprise.pyi | 5 + .../auth0/authentication/get_token.pyi | 29 + .../auth0/authentication/passwordless.pyi | 5 + .../pushed_authorization_requests.pyi | 4 + .../auth0/authentication/revoke_token.pyi | 4 + .../auth0/authentication/social.pyi | 4 + .../auth0/authentication/token_verifier.pyi | 27 + .../auth0/authentication/users.pyi | 11 + stubs/auth0-python/auth0/exceptions.pyi | 14 + .../auth0/management/__init__.pyi | 65 + .../auth0-python/auth0/management/actions.pyi | 64 + .../auth0/management/async_auth0.pyi | 76 + .../auth0/management/attack_protection.pyi | 30 + stubs/auth0-python/auth0/management/auth0.pyi | 67 + .../auth0/management/blacklists.pyi | 21 + .../auth0/management/branding.pyi | 38 + .../auth0/management/client_credentials.pyi | 26 + .../auth0/management/client_grants.pyi | 60 + .../auth0-python/auth0/management/clients.pyi | 44 + .../auth0/management/connections.pyi | 48 + .../auth0/management/custom_domains.pyi | 28 + .../auth0/management/device_credentials.pyi | 44 + .../auth0/management/email_templates.pyi | 24 + .../auth0-python/auth0/management/emails.pyi | 26 + .../auth0-python/auth0/management/grants.pyi | 34 + .../auth0/management/guardian.pyi | 38 + stubs/auth0-python/auth0/management/hooks.pyi | 52 + stubs/auth0-python/auth0/management/jobs.pyi | 42 + .../auth0/management/log_streams.pyi | 29 + stubs/auth0-python/auth0/management/logs.pyi | 44 + .../auth0/management/organizations.pyi | 134 + .../auth0-python/auth0/management/prompts.pyi | 28 + .../auth0/management/resource_servers.pyi | 28 + stubs/auth0-python/auth0/management/roles.pyi | 63 + stubs/auth0-python/auth0/management/rules.pyi | 46 + .../auth0/management/rules_configs.pyi | 24 + .../management/self_service_profiles.pyi | 26 + stubs/auth0-python/auth0/management/stats.pyi | 24 + .../auth0-python/auth0/management/tenants.pyi | 22 + .../auth0-python/auth0/management/tickets.pyi | 22 + .../auth0/management/user_blocks.pyi | 26 + stubs/auth0-python/auth0/management/users.pyi | 119 + .../auth0/management/users_by_email.pyi | 24 + stubs/auth0-python/auth0/rest.pyi | 48 + stubs/auth0-python/auth0/rest_async.pyi | 23 + stubs/auth0-python/auth0/types.pyi | 5 + stubs/auth0-python/auth0/utils.pyi | 1 + .../@tests/stubtest_allowlist.txt | 36 + stubs/aws-xray-sdk/METADATA.toml | 2 + stubs/aws-xray-sdk/aws_xray_sdk/__init__.pyi | 3 + .../aws_xray_sdk/core/__init__.pyi | 7 + .../aws_xray_sdk/core/async_context.pyi | 23 + .../aws_xray_sdk/core/async_recorder.pyi | 43 + .../aws_xray_sdk/core/context.pyi | 28 + .../aws_xray_sdk/core/daemon_config.pyi | 15 + .../aws_xray_sdk/core/emitters/__init__.pyi | 0 .../core/emitters/udp_emitter.pyi | 18 + .../aws_xray_sdk/core/exceptions/__init__.pyi | 0 .../core/exceptions/exceptions.pyi | 8 + .../aws_xray_sdk/core/lambda_launcher.pyi | 20 + .../aws_xray_sdk/core/models/__init__.pyi | 0 .../core/models/default_dynamic_naming.pyi | 3 + .../core/models/dummy_entities.pyi | 8 + .../aws_xray_sdk/core/models/entity.pyi | 52 + .../core/models/facade_segment.pyi | 9 + .../aws_xray_sdk/core/models/http.pyi | 13 + .../aws_xray_sdk/core/models/noop_traceid.pyi | 8 + .../aws_xray_sdk/core/models/segment.pyi | 59 + .../aws_xray_sdk/core/models/subsegment.pyi | 40 + .../aws_xray_sdk/core/models/throwable.pyi | 29 + .../aws_xray_sdk/core/models/trace_header.pyi | 36 + .../aws_xray_sdk/core/models/traceid.pyi | 8 + .../aws_xray_sdk/core/patcher.pyi | 12 + .../aws_xray_sdk/core/plugins/__init__.pyi | 0 .../aws_xray_sdk/core/plugins/ec2_plugin.pyi | 18 + .../aws_xray_sdk/core/plugins/ecs_plugin.pyi | 8 + .../core/plugins/elasticbeanstalk_plugin.pyi | 9 + .../aws_xray_sdk/core/plugins/utils.pyi | 8 + .../aws_xray_sdk/core/recorder.pyi | 130 + .../aws_xray_sdk/core/sampling/__init__.pyi | 0 .../aws_xray_sdk/core/sampling/connector.pyi | 16 + .../core/sampling/local/__init__.pyi | 0 .../core/sampling/local/reservoir.pyi | 6 + .../core/sampling/local/sampler.pyi | 18 + .../core/sampling/local/sampling_rule.pyi | 38 + .../aws_xray_sdk/core/sampling/reservoir.pyi | 15 + .../aws_xray_sdk/core/sampling/rule_cache.pyi | 19 + .../core/sampling/rule_poller.pyi | 13 + .../aws_xray_sdk/core/sampling/sampler.pyi | 17 + .../core/sampling/sampling_rule.pyi | 47 + .../core/sampling/target_poller.pyi | 11 + .../aws_xray_sdk/core/streaming/__init__.pyi | 0 .../core/streaming/default_streaming.pyi | 15 + .../aws_xray_sdk/core/utils/__init__.pyi | 0 .../core/utils/atomic_counter.pyi | 7 + .../aws_xray_sdk/core/utils/compat.pyi | 4 + .../aws_xray_sdk/core/utils/conversion.pyi | 13 + .../core/utils/search_pattern.pyi | 8 + .../core/utils/sqs_message_helper.pyi | 9 + .../aws_xray_sdk/core/utils/stacktrace.pyi | 3 + .../aws_xray_sdk/ext/__init__.pyi | 0 .../aws_xray_sdk/ext/aiobotocore/__init__.pyi | 3 + .../aws_xray_sdk/ext/aiobotocore/patch.pyi | 1 + .../aws_xray_sdk/ext/aiohttp/__init__.pyi | 0 .../aws_xray_sdk/ext/aiohttp/client.pyi | 10 + .../aws_xray_sdk/ext/aiohttp/middleware.pyi | 1 + .../aws_xray_sdk/ext/boto_utils.pyi | 6 + .../aws_xray_sdk/ext/botocore/__init__.pyi | 3 + .../aws_xray_sdk/ext/botocore/patch.pyi | 1 + .../aws_xray_sdk/ext/bottle/__init__.pyi | 0 .../aws_xray_sdk/ext/bottle/middleware.pyi | 9 + .../aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi | 14 + .../aws_xray_sdk/ext/django/__init__.pyi | 3 + .../aws_xray_sdk/ext/django/apps.pyi | 8 + .../aws_xray_sdk/ext/django/conf.pyi | 17 + .../aws_xray_sdk/ext/django/db.pyi | 12 + .../aws_xray_sdk/ext/django/middleware.pyi | 19 + .../aws_xray_sdk/ext/django/templates.pyi | 5 + .../aws_xray_sdk/ext/flask/__init__.pyi | 0 .../aws_xray_sdk/ext/flask/middleware.pyi | 6 + .../ext/flask_sqlalchemy/__init__.pyi | 0 .../ext/flask_sqlalchemy/query.pyi | 22 + .../aws_xray_sdk/ext/httplib/__init__.pyi | 3 + .../aws_xray_sdk/ext/httplib/patch.pyi | 12 + .../aws_xray_sdk/ext/httpx/__init__.pyi | 3 + .../aws_xray_sdk/ext/httpx/patch.pyi | 9 + .../aws_xray_sdk/ext/mysql/__init__.pyi | 3 + .../aws_xray_sdk/ext/mysql/patch.pyi | 6 + .../aws_xray_sdk/ext/pg8000/__init__.pyi | 3 + .../aws_xray_sdk/ext/pg8000/patch.pyi | 2 + .../aws_xray_sdk/ext/psycopg/__init__.pyi | 3 + .../aws_xray_sdk/ext/psycopg/patch.pyi | 1 + .../aws_xray_sdk/ext/psycopg2/__init__.pyi | 3 + .../aws_xray_sdk/ext/psycopg2/patch.pyi | 1 + .../aws_xray_sdk/ext/pymongo/__init__.pyi | 3 + .../aws_xray_sdk/ext/pymongo/patch.pyi | 8 + .../aws_xray_sdk/ext/pymysql/__init__.pyi | 3 + .../aws_xray_sdk/ext/pymysql/patch.pyi | 3 + .../aws_xray_sdk/ext/pynamodb/__init__.pyi | 3 + .../aws_xray_sdk/ext/pynamodb/patch.pyi | 6 + .../aws_xray_sdk/ext/requests/__init__.pyi | 3 + .../aws_xray_sdk/ext/requests/patch.pyi | 2 + .../aws_xray_sdk/ext/sqlalchemy/__init__.pyi | 0 .../aws_xray_sdk/ext/sqlalchemy/query.pyi | 16 + .../ext/sqlalchemy/util/__init__.pyi | 0 .../ext/sqlalchemy/util/decorators.pyi | 6 + .../ext/sqlalchemy_core/__init__.pyi | 3 + .../ext/sqlalchemy_core/patch.pyi | 2 + .../aws_xray_sdk/ext/sqlite3/__init__.pyi | 3 + .../aws_xray_sdk/ext/sqlite3/patch.pyi | 7 + stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi | 23 + .../aws-xray-sdk/aws_xray_sdk/sdk_config.pyi | 12 + stubs/aws-xray-sdk/aws_xray_sdk/version.pyi | 3 + stubs/behave/METADATA.toml | 6 + stubs/behave/behave/__init__.pyi | 13 + stubs/behave/behave/fixture.pyi | 15 + stubs/behave/behave/runner.pyi | 38 + stubs/behave/behave/step_registry.pyi | 20 + .../binaryornot/@tests/stubtest_allowlist.txt | 1 + stubs/binaryornot/METADATA.toml | 3 + stubs/binaryornot/binaryornot/__init__.pyi | 5 + stubs/binaryornot/binaryornot/check.pyi | 3 + stubs/binaryornot/binaryornot/helpers.pyi | 5 + stubs/bleach/@tests/stubtest_allowlist.txt | 8 + stubs/bleach/METADATA.toml | 6 + stubs/bleach/bleach/__init__.pyi | 33 + stubs/bleach/bleach/callbacks.pyi | 13 + stubs/bleach/bleach/css_sanitizer.pyi | 12 + stubs/bleach/bleach/html5lib_shim.pyi | 71 + stubs/bleach/bleach/linkifier.pyi | 60 + stubs/bleach/bleach/parse_shim.pyi | 1 + stubs/bleach/bleach/sanitizer.pyi | 91 + stubs/boltons/@tests/stubtest_allowlist.txt | 2 + stubs/boltons/METADATA.toml | 2 + stubs/boltons/boltons/__init__.pyi | 3 + stubs/boltons/boltons/cacheutils.pyi | 152 + stubs/boltons/boltons/debugutils.pyi | 10 + stubs/boltons/boltons/deprutils.pyi | 8 + stubs/boltons/boltons/dictutils.pyi | 129 + stubs/boltons/boltons/easterutils.pyi | 3 + stubs/boltons/boltons/ecoutils.pyi | 26 + stubs/boltons/boltons/excutils.pyi | 11 + stubs/boltons/boltons/fileutils.pyi | 96 + stubs/boltons/boltons/formatutils.pyi | 46 + stubs/boltons/boltons/funcutils.pyi | 68 + stubs/boltons/boltons/gcutils.pyi | 16 + stubs/boltons/boltons/ioutils.pyi | 92 + stubs/boltons/boltons/iterutils.pyi | 77 + stubs/boltons/boltons/jsonutils.pyi | 25 + stubs/boltons/boltons/listutils.pyi | 32 + stubs/boltons/boltons/mathutils.pyi | 43 + stubs/boltons/boltons/mboxutils.pyi | 17 + stubs/boltons/boltons/namedutils.pyi | 6 + stubs/boltons/boltons/pathutils.pyi | 15 + stubs/boltons/boltons/queueutils.pyi | 16 + stubs/boltons/boltons/setutils.pyi | 105 + stubs/boltons/boltons/socketutils.pyi | 72 + stubs/boltons/boltons/statsutils.pyi | 76 + stubs/boltons/boltons/strutils.pyi | 103 + stubs/boltons/boltons/tableutils.pyi | 65 + stubs/boltons/boltons/tbutils.pyi | 107 + stubs/boltons/boltons/timeutils.pyi | 62 + stubs/boltons/boltons/typeutils.pyi | 17 + stubs/boltons/boltons/urlutils.pyi | 82 + stubs/braintree/@tests/stubtest_allowlist.txt | 1 + stubs/braintree/METADATA.toml | 2 + stubs/braintree/braintree/__init__.pyi | 111 + .../account_updater_daily_report.pyi | 8 + stubs/braintree/braintree/ach_mandate.pyi | 4 + stubs/braintree/braintree/add_on.pyi | 5 + stubs/braintree/braintree/add_on_gateway.pyi | 9 + stubs/braintree/braintree/address.pyi | 31 + stubs/braintree/braintree/address_gateway.pyi | 17 + .../braintree/amex_express_checkout_card.pyi | 8 + .../braintree/braintree/android_pay_card.pyi | 21 + stubs/braintree/braintree/apple_pay_card.pyi | 21 + .../braintree/braintree/apple_pay_gateway.pyi | 12 + .../braintree/braintree/apple_pay_options.pyi | 3 + .../braintree/braintree/attribute_getter.pyi | 7 + .../braintree/authorization_adjustment.pyi | 7 + ...k_account_instant_verification_gateway.pyi | 13 + .../bank_account_instant_verification_jwt.pyi | 9 + ...count_instant_verification_jwt_request.pyi | 18 + stubs/braintree/braintree/bin_data.pyi | 3 + stubs/braintree/braintree/blik_alias.pyi | 3 + .../braintree/braintree/braintree_gateway.pyi | 70 + stubs/braintree/braintree/client_token.pyi | 9 + .../braintree/client_token_gateway.pyi | 9 + stubs/braintree/braintree/configuration.pyi | 70 + ...nnected_merchant_paypal_status_changed.pyi | 6 + ...connected_merchant_status_transitioned.pyi | 6 + .../braintree/credentials_parser.pyi | 15 + stubs/braintree/braintree/credit_card.pyi | 96 + .../braintree/credit_card_gateway.pyi | 23 + .../braintree/credit_card_verification.pyi | 37 + .../credit_card_verification_gateway.pyi | 14 + .../credit_card_verification_search.pyi | 15 + stubs/braintree/braintree/customer.pyi | 66 + .../braintree/braintree/customer_gateway.pyi | 17 + stubs/braintree/braintree/customer_search.pyi | 27 + .../braintree/customer_session_gateway.pyi | 17 + stubs/braintree/braintree/descriptor.pyi | 4 + stubs/braintree/braintree/disbursement.pyi | 17 + .../braintree/disbursement_detail.pyi | 10 + stubs/braintree/braintree/discount.pyi | 5 + .../braintree/braintree/discount_gateway.pyi | 9 + stubs/braintree/braintree/dispute.pyi | 79 + .../braintree/dispute_details/__init__.pyi | 3 + .../braintree/dispute_details/evidence.pyi | 6 + .../dispute_details/paypal_message.pyi | 6 + .../dispute_details/status_history.pyi | 6 + stubs/braintree/braintree/dispute_gateway.pyi | 18 + stubs/braintree/braintree/dispute_search.pyi | 23 + stubs/braintree/braintree/document_upload.pyi | 16 + .../braintree/document_upload_gateway.pyi | 10 + .../braintree/enriched_customer_data.pyi | 7 + stubs/braintree/braintree/environment.pyi | 45 + stubs/braintree/braintree/error_codes.pyi | 765 ++ stubs/braintree/braintree/error_result.pyi | 20 + stubs/braintree/braintree/errors.pyi | 13 + .../braintree/europe_bank_account.pyi | 11 + .../braintree/exceptions/__init__.pyi | 16 + .../exceptions/authentication_error.pyi | 3 + .../exceptions/authorization_error.pyi | 3 + .../braintree/exceptions/braintree_error.pyi | 1 + .../exceptions/configuration_error.pyi | 3 + .../exceptions/gateway_timeout_error.pyi | 3 + .../braintree/exceptions/http/__init__.pyi | 3 + .../exceptions/http/connection_error.pyi | 3 + .../http/invalid_response_error.pyi | 3 + .../exceptions/http/timeout_error.pyi | 5 + .../exceptions/invalid_challenge_error.pyi | 3 + .../exceptions/invalid_signature_error.pyi | 3 + .../braintree/exceptions/not_found_error.pyi | 3 + .../exceptions/request_timeout_error.pyi | 3 + .../braintree/exceptions/server_error.pyi | 3 + .../exceptions/service_unavailable_error.pyi | 3 + ...peration_performed_in_production_error.pyi | 3 + .../exceptions/too_many_requests_error.pyi | 3 + .../braintree/exceptions/unexpected_error.pyi | 3 + .../exceptions/upgrade_required_error.pyi | 3 + .../braintree/exchange_rate_quote.pyi | 4 + .../braintree/exchange_rate_quote_gateway.pyi | 13 + .../braintree/exchange_rate_quote_input.pyi | 9 + .../braintree/exchange_rate_quote_payload.pyi | 9 + .../braintree/exchange_rate_quote_request.pyi | 9 + .../braintree/facilitated_details.pyi | 3 + .../braintree/facilitator_details.pyi | 3 + .../granted_payment_instrument_update.pyi | 7 + .../braintree/braintree/graphql/__init__.pyi | 20 + .../braintree/graphql/enums/__init__.pyi | 2 + .../graphql/enums/recommendations.pyi | 4 + .../enums/recommended_payment_option.pyi | 5 + .../braintree/graphql/inputs/__init__.pyi | 13 + .../graphql/inputs/billing_address_input.pyi | 22 + .../inputs/create_customer_session_input.pyi | 41 + .../create_local_payment_context_input.pyi | 36 + .../inputs/customer_recommendations_input.pyi | 41 + .../graphql/inputs/customer_session_input.pyi | 43 + .../graphql/inputs/monetary_amount_input.pyi | 11 + .../graphql/inputs/payer_info_input.pyi | 28 + .../graphql/inputs/paypal_payee_input.pyi | 19 + .../inputs/paypal_purchase_unit_input.pyi | 24 + .../braintree/graphql/inputs/phone_input.pyi | 23 + .../graphql/inputs/shipping_address_input.pyi | 22 + .../inputs/update_customer_session_input.pyi | 37 + .../braintree/graphql/types/__init__.pyi | 5 + .../customer_recommendations_payload.pyi | 22 + .../graphql/types/payment_options.pyi | 6 + .../graphql/types/payment_recommendation.pyi | 6 + .../braintree/graphql/unions/__init__.pyi | 1 + .../unions/customer_recommendations.pyi | 7 + .../braintree/braintree/iban_bank_account.pyi | 3 + stubs/braintree/braintree/ids_search.pyi | 4 + stubs/braintree/braintree/liability_shift.pyi | 3 + stubs/braintree/braintree/local_payment.pyi | 3 + .../braintree/local_payment_completed.pyi | 6 + .../braintree/local_payment_context.pyi | 6 + .../local_payment_context_gateway.pyi | 14 + .../braintree/local_payment_expired.pyi | 4 + .../braintree/local_payment_funded.pyi | 7 + .../braintree/local_payment_reversed.pyi | 4 + .../braintree/local_payment_type.pyi | 5 + stubs/braintree/braintree/masterpass_card.pyi | 12 + stubs/braintree/braintree/merchant.pyi | 6 + .../braintree/merchant_account/__init__.pyi | 1 + .../merchant_account/address_details.pyi | 7 + .../merchant_account/merchant_account.pyi | 24 + .../braintree/merchant_account_gateway.pyi | 13 + .../braintree/braintree/merchant_gateway.pyi | 12 + .../braintree/meta_checkout_card.pyi | 8 + .../braintree/meta_checkout_token.pyi | 8 + stubs/braintree/braintree/modification.pyi | 7 + stubs/braintree/braintree/monetary_amount.pyi | 7 + .../braintree/oauth_access_revocation.pyi | 4 + .../braintree/braintree/oauth_credentials.pyi | 3 + stubs/braintree/braintree/oauth_gateway.pyi | 13 + stubs/braintree/braintree/package_details.pyi | 7 + .../braintree/paginated_collection.pyi | 8 + .../braintree/braintree/paginated_result.pyi | 7 + .../braintree/braintree/partner_merchant.pyi | 11 + .../braintree/payment_facilitator.pyi | 6 + .../braintree/payment_instrument_type.pyi | 19 + stubs/braintree/braintree/payment_method.pyi | 66 + ..._method_customer_data_updated_metadata.pyi | 8 + .../braintree/payment_method_gateway.pyi | 45 + .../braintree/payment_method_nonce.pyi | 17 + .../payment_method_nonce_gateway.pyi | 12 + .../braintree/payment_method_parser.pyi | 31 + stubs/braintree/braintree/paypal_account.pyi | 16 + .../braintree/paypal_account_gateway.pyi | 13 + stubs/braintree/braintree/paypal_here.pyi | 4 + .../braintree/paypal_payment_resource.pyi | 12 + .../paypal_payment_resource_gateway.pyi | 10 + stubs/braintree/braintree/plan.pyi | 20 + stubs/braintree/braintree/plan_gateway.pyi | 10 + .../braintree/processor_response_types.pyi | 6 + stubs/braintree/braintree/receiver.pyi | 6 + stubs/braintree/braintree/resource.pyi | 12 + .../braintree/resource_collection.pyi | 14 + .../revoked_payment_method_metadata.pyi | 9 + stubs/braintree/braintree/risk_data.pyi | 4 + .../braintree/braintree/samsung_pay_card.pyi | 12 + stubs/braintree/braintree/search.pyi | 59 + stubs/braintree/braintree/sender.pyi | 6 + .../braintree/sepa_direct_debit_account.pyi | 10 + .../sepa_direct_debit_account_gateway.pyi | 8 + .../braintree/settlement_batch_summary.pyi | 5 + .../settlement_batch_summary_gateway.pyi | 7 + .../braintree/braintree/signature_service.pyi | 8 + stubs/braintree/braintree/status_event.pyi | 7 + stubs/braintree/braintree/sub_merchant.pyi | 4 + stubs/braintree/braintree/subscription.pyi | 59 + .../braintree/subscription_details.pyi | 7 + .../braintree/subscription_gateway.pyi | 19 + .../braintree/subscription_search.pyi | 15 + .../braintree/subscription_status_event.pyi | 8 + .../braintree/braintree/successful_result.pyi | 7 + stubs/braintree/braintree/test/__init__.pyi | 0 .../braintree/test/authentication_ids.pyi | 18 + .../braintree/test/credit_card_defaults.pyi | 5 + .../braintree/test/credit_card_numbers.pyi | 45 + .../braintree/test/merchant_account.pyi | 7 + stubs/braintree/braintree/test/nonces.pyi | 88 + stubs/braintree/braintree/test/venmo_sdk.pyi | 9 + stubs/braintree/braintree/testing_gateway.pyi | 12 + .../braintree/three_d_secure_info.pyi | 3 + stubs/braintree/braintree/transaction.pyi | 196 + .../braintree/transaction_amounts.pyi | 8 + .../braintree/transaction_details.pyi | 7 + .../braintree/transaction_gateway.pyi | 25 + .../braintree/transaction_line_item.pyi | 12 + .../transaction_line_item_gateway.pyi | 9 + .../braintree/transaction_review.pyi | 4 + .../braintree/transaction_search.pyi | 73 + .../transaction_us_bank_account_request.pyi | 17 + stubs/braintree/braintree/transfer.pyi | 8 + .../braintree/unknown_payment_method.pyi | 4 + stubs/braintree/braintree/us_bank_account.pyi | 16 + .../braintree/us_bank_account_gateway.pyi | 9 + .../us_bank_account_verification.pyi | 36 + .../us_bank_account_verification_gateway.pyi | 14 + .../us_bank_account_verification_search.pyi | 15 + stubs/braintree/braintree/util/__init__.pyi | 8 + stubs/braintree/braintree/util/constants.pyi | 7 + stubs/braintree/braintree/util/crypto.pyi | 24 + .../braintree/util/datetime_parser.pyi | 3 + .../braintree/braintree/util/experimental.pyi | 5 + stubs/braintree/braintree/util/generator.pyi | 27 + .../braintree/util/graphql_client.pyi | 38 + stubs/braintree/braintree/util/http.pyi | 29 + stubs/braintree/braintree/util/parser.pyi | 10 + stubs/braintree/braintree/util/xml_util.pyi | 7 + .../braintree/braintree/validation_error.pyi | 3 + .../braintree/validation_error_collection.pyi | 21 + stubs/braintree/braintree/venmo_account.pyi | 6 + .../braintree/venmo_profile_data.pyi | 4 + stubs/braintree/braintree/version.pyi | 3 + .../braintree/visa_checkout_card.pyi | 17 + .../braintree/webhook_notification.pyi | 94 + .../webhook_notification_gateway.pyi | 12 + stubs/braintree/braintree/webhook_testing.pyi | 3 + .../braintree/webhook_testing_gateway.pyi | 7 + .../cachetools/@tests/stubtest_allowlist.txt | 21 + .../@tests/test_cases/check_cachetools.py | 104 + stubs/cachetools/METADATA.toml | 3 + stubs/cachetools/cachetools/__init__.pyi | 183 + stubs/cachetools/cachetools/func.pyi | 54 + stubs/cachetools/cachetools/keys.pyi | 10 + stubs/capturer/@tests/stubtest_allowlist.txt | 2 + stubs/capturer/METADATA.toml | 2 + stubs/capturer/capturer.pyi | 122 + stubs/cffi/@tests/stubtest_allowlist.txt | 4 + .../cffi/@tests/stubtest_allowlist_darwin.txt | 2 + .../cffi/@tests/stubtest_allowlist_linux.txt | 2 + stubs/cffi/METADATA.toml | 7 + stubs/cffi/_cffi_backend.pyi | 286 + stubs/cffi/cffi/__init__.pyi | 15 + stubs/cffi/cffi/api.pyi | 111 + stubs/cffi/cffi/backend_ctypes.pyi | 85 + stubs/cffi/cffi/cffi_opcode.pyi | 92 + stubs/cffi/cffi/commontypes.pyi | 6 + stubs/cffi/cffi/cparser.pyi | 12 + stubs/cffi/cffi/error.pyi | 14 + stubs/cffi/cffi/ffiplatform.pyi | 12 + stubs/cffi/cffi/lock.pyi | 1 + stubs/cffi/cffi/model.pyi | 164 + stubs/cffi/cffi/pkgconfig.pyi | 5 + stubs/cffi/cffi/recompiler.pyi | 96 + stubs/cffi/cffi/setuptools_ext.pyi | 6 + stubs/cffi/cffi/vengine_cpy.pyi | 13 + stubs/cffi/cffi/vengine_gen.pyi | 14 + stubs/cffi/cffi/verifier.pyi | 42 + stubs/channels/@tests/django_settings.py | 12 + stubs/channels/@tests/stubtest_allowlist.txt | 20 + stubs/channels/METADATA.toml | 8 + stubs/channels/channels/__init__.pyi | 4 + stubs/channels/channels/apps.pyi | 7 + stubs/channels/channels/auth.pyi | 28 + stubs/channels/channels/consumer.pyi | 75 + stubs/channels/channels/db.pyi | 31 + stubs/channels/channels/exceptions.pyi | 8 + stubs/channels/channels/generic/__init__.pyi | 0 stubs/channels/channels/generic/http.pyi | 19 + stubs/channels/channels/generic/websocket.pyi | 61 + stubs/channels/channels/layers.pyi | 96 + .../channels/channels/management/__init__.pyi | 0 .../channels/management/commands/__init__.pyi | 0 .../management/commands/runworker.pyi | 25 + stubs/channels/channels/middleware.pyi | 12 + stubs/channels/channels/routing.pyi | 31 + stubs/channels/channels/security/__init__.pyi | 0 .../channels/channels/security/websocket.pyi | 25 + stubs/channels/channels/sessions.pyi | 56 + stubs/channels/channels/testing/__init__.pyi | 6 + .../channels/channels/testing/application.pyi | 21 + stubs/channels/channels/testing/http.pyi | 41 + stubs/channels/channels/testing/live.pyi | 25 + stubs/channels/channels/testing/websocket.pyi | 55 + stubs/channels/channels/utils.pyi | 19 + stubs/channels/channels/worker.pyi | 13 + stubs/chevron/METADATA.toml | 4 + stubs/chevron/chevron/__init__.pyi | 5 + stubs/chevron/chevron/main.pyi | 5 + stubs/chevron/chevron/metadata.pyi | 1 + stubs/chevron/chevron/renderer.pyi | 22 + stubs/chevron/chevron/tokenizer.pyi | 11 + stubs/click-default-group/METADATA.toml | 4 + .../click_default_group.pyi | 84 + stubs/click-log/METADATA.toml | 3 + stubs/click-log/click_log/__init__.pyi | 4 + stubs/click-log/click_log/core.pyi | 15 + stubs/click-log/click_log/options.pyi | 10 + stubs/click-shell/METADATA.toml | 3 + stubs/click-shell/click_shell/__init__.pyi | 7 + stubs/click-shell/click_shell/_cmd.pyi | 28 + stubs/click-shell/click_shell/_compat.pyi | 10 + stubs/click-shell/click_shell/core.pyi | 35 + stubs/click-shell/click_shell/decorators.pyi | 8 + stubs/click-spinner/METADATA.toml | 3 + .../click-spinner/click_spinner/__init__.pyi | 32 + stubs/click-web/METADATA.toml | 3 + stubs/click-web/click_web/__init__.pyi | 16 + stubs/click-web/click_web/exceptions.pyi | 2 + .../click_web/resources/__init__.pyi | 0 .../click_web/resources/cmd_exec.pyi | 93 + .../click_web/resources/cmd_form.pyi | 13 + stubs/click-web/click_web/resources/index.pyi | 9 + .../click_web/resources/input_fields.pyi | 81 + stubs/click-web/click_web/web_click_types.pyi | 20 + stubs/colorama/@tests/stubtest_allowlist.txt | 46 + .../@tests/stubtest_allowlist_linux.txt | 4 + stubs/colorama/METADATA.toml | 5 + stubs/colorama/colorama/__init__.pyi | 9 + stubs/colorama/colorama/ansi.pyi | 69 + stubs/colorama/colorama/ansitowin32.pyi | 53 + stubs/colorama/colorama/initialise.pyi | 23 + stubs/colorama/colorama/win32.pyi | 35 + stubs/colorama/colorama/winterm.pyi | 38 + stubs/colorful/METADATA.toml | 2 + stubs/colorful/colorful/__init__.pyi | 0 stubs/colorful/colorful/ansi.pyi | 14 + stubs/colorful/colorful/colors.pyi | 6 + stubs/colorful/colorful/core.pyi | 104 + stubs/colorful/colorful/styles.pyi | 4 + stubs/colorful/colorful/terminal.pyi | 16 + stubs/colorful/colorful/utils.pyi | 2 + stubs/console-menu/METADATA.toml | 2 + stubs/console-menu/consolemenu/__init__.pyi | 17 + .../console-menu/consolemenu/console_menu.pyi | 97 + .../consolemenu/format/__init__.pyi | 29 + .../consolemenu/format/menu_borders.pyi | 194 + .../consolemenu/format/menu_margins.pyi | 22 + .../consolemenu/format/menu_padding.pyi | 22 + .../consolemenu/format/menu_style.pyi | 33 + .../consolemenu/items/__init__.pyi | 8 + .../consolemenu/items/command_item.pyi | 18 + .../consolemenu/items/external_item.pyi | 5 + .../consolemenu/items/function_item.pyi | 25 + .../consolemenu/items/selection_item.pyi | 11 + .../consolemenu/items/submenu_item.pyi | 22 + .../consolemenu/menu_component.pyi | 103 + .../consolemenu/menu_formatter.pyi | 55 + .../consolemenu/multiselect_menu.pyi | 22 + .../console-menu/consolemenu/prompt_utils.pyi | 47 + stubs/console-menu/consolemenu/screen.pyi | 17 + .../consolemenu/selection_menu.pyi | 31 + .../consolemenu/validators/__init__.pyi | 0 .../consolemenu/validators/base.pyi | 11 + .../consolemenu/validators/regex.pyi | 7 + .../consolemenu/validators/url.pyi | 5 + stubs/console-menu/consolemenu/version.pyi | 0 stubs/convertdate/METADATA.toml | 2 + stubs/convertdate/convertdate/__init__.pyi | 47 + stubs/convertdate/convertdate/armenian.pyi | 24 + stubs/convertdate/convertdate/bahai.pyi | 37 + stubs/convertdate/convertdate/coptic.pyi | 14 + .../convertdate/convertdate/data/__init__.pyi | 0 .../data/french_republican_days.pyi | 3 + .../convertdate/data/positivist.pyi | 6 + stubs/convertdate/convertdate/daycount.pyi | 13 + stubs/convertdate/convertdate/dublin.pyi | 13 + .../convertdate/french_republican.pyi | 27 + stubs/convertdate/convertdate/gregorian.pyi | 20 + stubs/convertdate/convertdate/hebrew.pyi | 37 + stubs/convertdate/convertdate/holidays.pyi | 161 + .../convertdate/convertdate/indian_civil.pyi | 15 + stubs/convertdate/convertdate/islamic.pyi | 17 + stubs/convertdate/convertdate/iso.pyi | 17 + stubs/convertdate/convertdate/julian.pyi | 20 + stubs/convertdate/convertdate/julianday.pyi | 8 + stubs/convertdate/convertdate/mayan.pyi | 43 + stubs/convertdate/convertdate/ordinal.pyi | 4 + stubs/convertdate/convertdate/persian.pyi | 19 + stubs/convertdate/convertdate/positivist.pyi | 15 + stubs/convertdate/convertdate/utils.pyi | 53 + stubs/croniter/@tests/stubtest_allowlist.txt | 1 + stubs/croniter/METADATA.toml | 2 + stubs/croniter/croniter/__init__.pyi | 43 + stubs/croniter/croniter/croniter.pyi | 359 + stubs/datauri/METADATA.toml | 2 + stubs/datauri/datauri/__init__.pyi | 1 + stubs/datauri/datauri/datauri.pyi | 19 + .../dateparser/@tests/stubtest_allowlist.txt | 8 + stubs/dateparser/METADATA.toml | 5 + stubs/dateparser/dateparser/__init__.pyi | 44 + .../dateparser/calendars/__init__.pyi | 47 + .../dateparser/dateparser/calendars/hijri.pyi | 5 + .../dateparser/calendars/hijri_parser.pyi | 28 + .../dateparser/calendars/jalali.pyi | 6 + .../dateparser/calendars/jalali_parser.pyi | 18 + stubs/dateparser/dateparser/conf.pyi | 46 + .../custom_language_detection/__init__.pyi | 0 .../custom_language_detection/fasttext.pyi | 1 + .../custom_language_detection/langdetect.pyi | 1 + .../language_mapping.pyi | 1 + stubs/dateparser/dateparser/data/__init__.pyi | 1 + .../dateparser/data/languages_info.pyi | 5 + stubs/dateparser/dateparser/date.pyi | 146 + stubs/dateparser/dateparser/date_parser.pyi | 14 + .../dateparser/freshness_date_parser.pyi | 20 + .../dateparser/languages/__init__.pyi | 2 + .../dateparser/languages/dictionary.pyi | 32 + .../dateparser/languages/loader.pyi | 29 + .../dateparser/languages/locale.pyi | 25 + .../dateparser/languages/validation.pyi | 11 + stubs/dateparser/dateparser/parser.pyi | 68 + .../dateparser/dateparser/search/__init__.pyi | 24 + .../dateparser/search/detection.pyi | 25 + stubs/dateparser/dateparser/search/search.pyi | 76 + .../dateparser/search/text_detection.pyi | 10 + .../dateparser/dateparser/timezone_parser.pyi | 22 + stubs/dateparser/dateparser/timezones.pyi | 3 + .../dateparser/dateparser/utils/__init__.pyi | 34 + .../dateparser/dateparser/utils/strptime.pyi | 14 + .../dateparser/utils/time_spans.pyi | 23 + stubs/dateparser/dateparser_data/__init__.pyi | 0 stubs/dateparser/dateparser_data/settings.pyi | 6 + stubs/decorator/@tests/stubtest_allowlist.txt | 5 + stubs/decorator/METADATA.toml | 3 + stubs/decorator/decorator.pyi | 72 + stubs/defusedxml/METADATA.toml | 5 + stubs/defusedxml/defusedxml/ElementTree.pyi | 78 + stubs/defusedxml/defusedxml/__init__.pyi | 9 + stubs/defusedxml/defusedxml/cElementTree.pyi | 16 + stubs/defusedxml/defusedxml/common.pyi | 31 + stubs/defusedxml/defusedxml/expatbuilder.pyi | 49 + stubs/defusedxml/defusedxml/expatreader.pyi | 43 + stubs/defusedxml/defusedxml/lxml.pyi | 55 + stubs/defusedxml/defusedxml/minidom.pyi | 22 + stubs/defusedxml/defusedxml/pulldom.pyi | 22 + stubs/defusedxml/defusedxml/sax.pyi | 26 + stubs/defusedxml/defusedxml/xmlrpc.pyi | 48 + stubs/dirhash/METADATA.toml | 2 + stubs/dirhash/dirhash/__init__.pyi | 92 + stubs/dirhash/dirhash/cli.pyi | 5 + stubs/django-filter/@tests/django_settings.py | 12 + .../@tests/stubtest_allowlist.txt | 19 + stubs/django-filter/METADATA.toml | 7 + .../django-filter/django_filters/__init__.pyi | 10 + stubs/django-filter/django_filters/compat.pyi | 1 + stubs/django-filter/django_filters/conf.pyi | 17 + .../django_filters/constants.pyi | 6 + .../django_filters/exceptions.pyi | 8 + stubs/django-filter/django_filters/fields.pyi | 159 + .../django-filter/django_filters/filters.pyi | 328 + .../django_filters/filterset.pyi | 88 + .../rest_framework/__init__.pyi | 34 + .../rest_framework/backends.pyi | 29 + .../django_filters/rest_framework/filters.pyi | 68 + .../rest_framework/filterset.pyi | 17 + stubs/django-filter/django_filters/utils.pyi | 36 + stubs/django-filter/django_filters/views.pyi | 38 + .../django-filter/django_filters/widgets.pyi | 81 + stubs/django-import-export/METADATA.toml | 6 + .../import_export/__init__.pyi | 1 + .../import_export/admin.pyi | 109 + .../import_export/command_utils.pyi | 12 + .../import_export/declarative.pyi | 11 + .../import_export/exceptions.pyi | 11 + .../import_export/fields.pyi | 34 + .../import_export/formats/__init__.pyi | 0 .../import_export/formats/base_formats.pyi | 60 + .../import_export/forms.pyi | 38 + .../import_export/instance_loaders.pyi | 22 + .../import_export/mixins.pyi | 65 + .../import_export/options.pyi | 32 + .../import_export/resources.pyi | 170 + .../import_export/results.pyi | 88 + .../import_export/signals.pyi | 4 + .../import_export/templatetags/__init__.pyi | 0 .../templatetags/import_export_tags.pyi | 8 + .../import_export/tmp_storages.pyi | 34 + .../import_export/utils.pyi | 19 + .../import_export/widgets.pyi | 91 + .../management/__init__.pyi | 0 .../management/commands/__init__.pyi | 0 .../management/commands/export.pyi | 3 + .../management/commands/import.pyi | 3 + stubs/docker/@tests/stubtest_allowlist.txt | 15 + .../docker/@tests/test_cases/check_attach.py | 12 + stubs/docker/METADATA.toml | 4 + stubs/docker/docker/__init__.pyi | 9 + stubs/docker/docker/_types.pyi | 25 + stubs/docker/docker/api/__init__.pyi | 1 + stubs/docker/docker/api/build.pyi | 55 + stubs/docker/docker/api/client.pyi | 55 + stubs/docker/docker/api/config.pyi | 13 + stubs/docker/docker/api/container.pyi | 326 + stubs/docker/docker/api/daemon.pyi | 37 + stubs/docker/docker/api/exec_api.pyi | 137 + stubs/docker/docker/api/image.pyi | 43 + stubs/docker/docker/api/network.pyi | 51 + stubs/docker/docker/api/plugin.pyi | 12 + stubs/docker/docker/api/secret.pyi | 12 + stubs/docker/docker/api/service.pyi | 45 + stubs/docker/docker/api/swarm.pyi | 85 + stubs/docker/docker/api/volume.pyi | 14 + stubs/docker/docker/auth.pyi | 48 + stubs/docker/docker/client.pyi | 127 + stubs/docker/docker/constants.pyi | 22 + stubs/docker/docker/context/__init__.pyi | 2 + stubs/docker/docker/context/api.pyi | 34 + stubs/docker/docker/context/config.pyi | 10 + stubs/docker/docker/context/context.pyi | 81 + stubs/docker/docker/credentials/__init__.pyi | 8 + stubs/docker/docker/credentials/constants.pyi | 4 + stubs/docker/docker/credentials/errors.pyi | 7 + stubs/docker/docker/credentials/store.pyi | 11 + stubs/docker/docker/credentials/utils.pyi | 1 + stubs/docker/docker/errors.pyi | 74 + stubs/docker/docker/models/__init__.pyi | 0 stubs/docker/docker/models/configs.pyi | 25 + stubs/docker/docker/models/containers.pyi | 477 ++ stubs/docker/docker/models/images.pyi | 127 + stubs/docker/docker/models/networks.pyi | 57 + stubs/docker/docker/models/nodes.pyi | 17 + stubs/docker/docker/models/plugins.pyi | 26 + stubs/docker/docker/models/resource.pyi | 33 + stubs/docker/docker/models/secrets.pyi | 22 + stubs/docker/docker/models/services.pyi | 39 + stubs/docker/docker/models/swarm.pyi | 78 + stubs/docker/docker/models/volumes.pyi | 26 + stubs/docker/docker/tls.pyi | 10 + stubs/docker/docker/transport/__init__.pyi | 4 + .../docker/transport/basehttpadapter.pyi | 14 + stubs/docker/docker/transport/npipeconn.pyi | 29 + stubs/docker/docker/transport/npipesocket.pyi | 57 + stubs/docker/docker/transport/sshconn.pyi | 53 + stubs/docker/docker/transport/unixconn.pyi | 34 + stubs/docker/docker/types/__init__.pyi | 35 + stubs/docker/docker/types/base.pyi | 7 + stubs/docker/docker/types/containers.pyi | 199 + stubs/docker/docker/types/daemon.pyi | 14 + stubs/docker/docker/types/healthcheck.pyi | 44 + stubs/docker/docker/types/networks.pyi | 32 + stubs/docker/docker/types/services.pyi | 195 + stubs/docker/docker/types/swarm.pyi | 30 + stubs/docker/docker/utils/__init__.pyi | 32 + stubs/docker/docker/utils/build.pyi | 39 + stubs/docker/docker/utils/config.pyi | 12 + stubs/docker/docker/utils/decorators.pyi | 9 + stubs/docker/docker/utils/fnmatch.pyi | 5 + stubs/docker/docker/utils/json_stream.pyi | 15 + stubs/docker/docker/utils/ports.pyi | 11 + stubs/docker/docker/utils/proxy.pyi | 35 + stubs/docker/docker/utils/socket.pyi | 31 + stubs/docker/docker/utils/utils.pyi | 78 + stubs/docker/docker/version.pyi | 3 + stubs/dockerfile-parse/METADATA.toml | 2 + .../dockerfile_parse/__init__.pyi | 5 + .../dockerfile_parse/constants.pyi | 4 + .../dockerfile_parse/parser.pyi | 70 + .../dockerfile_parse/util.pyi | 51 + stubs/docutils/@tests/stubtest_allowlist.txt | 24 + stubs/docutils/METADATA.toml | 2 + stubs/docutils/docutils/__init__.pyi | 46 + stubs/docutils/docutils/__main__.pyi | 11 + stubs/docutils/docutils/core.pyi | 219 + stubs/docutils/docutils/examples.pyi | 45 + stubs/docutils/docutils/frontend.pyi | 202 + stubs/docutils/docutils/io.pyi | 136 + .../docutils/docutils/languages/__init__.pyi | 25 + stubs/docutils/docutils/languages/af.pyi | 6 + stubs/docutils/docutils/languages/ar.pyi | 6 + stubs/docutils/docutils/languages/ca.pyi | 6 + stubs/docutils/docutils/languages/cs.pyi | 6 + stubs/docutils/docutils/languages/da.pyi | 6 + stubs/docutils/docutils/languages/de.pyi | 6 + stubs/docutils/docutils/languages/en.pyi | 6 + stubs/docutils/docutils/languages/eo.pyi | 6 + stubs/docutils/docutils/languages/es.pyi | 6 + stubs/docutils/docutils/languages/fa.pyi | 6 + stubs/docutils/docutils/languages/fi.pyi | 6 + stubs/docutils/docutils/languages/fr.pyi | 6 + stubs/docutils/docutils/languages/gl.pyi | 6 + stubs/docutils/docutils/languages/he.pyi | 6 + stubs/docutils/docutils/languages/it.pyi | 6 + stubs/docutils/docutils/languages/ja.pyi | 6 + stubs/docutils/docutils/languages/ka.pyi | 6 + stubs/docutils/docutils/languages/ko.pyi | 6 + stubs/docutils/docutils/languages/lt.pyi | 6 + stubs/docutils/docutils/languages/lv.pyi | 6 + stubs/docutils/docutils/languages/nl.pyi | 6 + stubs/docutils/docutils/languages/pl.pyi | 6 + stubs/docutils/docutils/languages/pt_br.pyi | 6 + stubs/docutils/docutils/languages/ru.pyi | 6 + stubs/docutils/docutils/languages/sk.pyi | 6 + stubs/docutils/docutils/languages/sv.pyi | 6 + stubs/docutils/docutils/languages/uk.pyi | 6 + stubs/docutils/docutils/languages/zh_cn.pyi | 6 + stubs/docutils/docutils/languages/zh_tw.pyi | 6 + stubs/docutils/docutils/nodes.pyi | 759 ++ stubs/docutils/docutils/parsers/__init__.pyi | 19 + .../docutils/parsers/commonmark_wrapper.pyi | 9 + .../docutils/parsers/docutils_xml.pyi | 16 + stubs/docutils/docutils/parsers/null.pyi | 9 + .../docutils/parsers/recommonmark_wrapper.pyi | 55 + .../docutils/parsers/rst/__init__.pyi | 70 + .../parsers/rst/directives/__init__.pyi | 43 + .../parsers/rst/directives/admonitions.pyi | 39 + .../docutils/parsers/rst/directives/body.pyi | 73 + .../docutils/parsers/rst/directives/html.pyi | 5 + .../parsers/rst/directives/images.pyi | 18 + .../docutils/parsers/rst/directives/misc.pyi | 46 + .../docutils/parsers/rst/directives/parts.pyi | 14 + .../parsers/rst/directives/references.pyi | 7 + .../parsers/rst/directives/tables.pyi | 62 + .../parsers/rst/languages/__init__.pyi | 20 + .../docutils/parsers/rst/languages/af.pyi | 5 + .../docutils/parsers/rst/languages/ar.pyi | 5 + .../docutils/parsers/rst/languages/ca.pyi | 5 + .../docutils/parsers/rst/languages/cs.pyi | 5 + .../docutils/parsers/rst/languages/da.pyi | 5 + .../docutils/parsers/rst/languages/de.pyi | 5 + .../docutils/parsers/rst/languages/en.pyi | 5 + .../docutils/parsers/rst/languages/eo.pyi | 5 + .../docutils/parsers/rst/languages/es.pyi | 5 + .../docutils/parsers/rst/languages/fa.pyi | 5 + .../docutils/parsers/rst/languages/fi.pyi | 5 + .../docutils/parsers/rst/languages/fr.pyi | 5 + .../docutils/parsers/rst/languages/gl.pyi | 5 + .../docutils/parsers/rst/languages/he.pyi | 5 + .../docutils/parsers/rst/languages/it.pyi | 5 + .../docutils/parsers/rst/languages/ja.pyi | 5 + .../docutils/parsers/rst/languages/ka.pyi | 5 + .../docutils/parsers/rst/languages/ko.pyi | 5 + .../docutils/parsers/rst/languages/lt.pyi | 5 + .../docutils/parsers/rst/languages/lv.pyi | 5 + .../docutils/parsers/rst/languages/nl.pyi | 5 + .../docutils/parsers/rst/languages/pl.pyi | 5 + .../docutils/parsers/rst/languages/pt_br.pyi | 5 + .../docutils/parsers/rst/languages/ru.pyi | 5 + .../docutils/parsers/rst/languages/sk.pyi | 5 + .../docutils/parsers/rst/languages/sv.pyi | 5 + .../docutils/parsers/rst/languages/uk.pyi | 5 + .../docutils/parsers/rst/languages/zh_cn.pyi | 5 + .../docutils/parsers/rst/languages/zh_tw.pyi | 5 + stubs/docutils/docutils/parsers/rst/roles.pyi | 135 + .../docutils/docutils/parsers/rst/states.pyi | 390 + .../docutils/parsers/rst/tableparser.pyi | 64 + stubs/docutils/docutils/readers/__init__.pyi | 31 + stubs/docutils/docutils/readers/doctree.pyi | 10 + stubs/docutils/docutils/readers/pep.pyi | 12 + .../docutils/docutils/readers/standalone.pyi | 11 + stubs/docutils/docutils/statemachine.pyi | 205 + .../docutils/docutils/transforms/__init__.pyi | 35 + .../docutils/transforms/components.pyi | 9 + .../docutils/transforms/frontmatter.pyi | 34 + stubs/docutils/docutils/transforms/misc.pyi | 19 + stubs/docutils/docutils/transforms/parts.pyi | 35 + stubs/docutils/docutils/transforms/peps.pyi | 43 + .../docutils/transforms/references.pyi | 80 + .../docutils/transforms/universal.pyi | 56 + .../docutils/transforms/writer_aux.pyi | 9 + stubs/docutils/docutils/utils/__init__.pyi | 131 + .../docutils/utils/_roman_numerals.pyi | 30 + .../docutils/docutils/utils/code_analyzer.pyi | 28 + .../docutils/docutils/utils/math/__init__.pyi | 13 + .../docutils/utils/math/latex2mathml.pyi | 44 + .../docutils/utils/math/math2html.pyi | 638 ++ .../utils/math/mathalphabet2unichar.pyi | 13 + .../docutils/utils/math/mathml_elements.pyi | 85 + .../docutils/utils/math/tex2mathml_extern.pyi | 9 + .../docutils/utils/math/tex2unichar.pyi | 14 + .../docutils/utils/math/unichar2tex.pyi | 1 + .../docutils/utils/punctuation_chars.pyi | 9 + stubs/docutils/docutils/utils/smartquotes.pyi | 44 + stubs/docutils/docutils/utils/urischemes.pyi | 1 + stubs/docutils/docutils/writers/__init__.pyi | 92 + .../docutils/docutils/writers/_html_base.pyi | 305 + .../docutils/writers/docutils_xml.pyi | 45 + .../docutils/writers/html4css1/__init__.pyi | 125 + .../writers/html5_polyglot/__init__.pyi | 16 + .../docutils/writers/latex2e/__init__.pyi | 423 + stubs/docutils/docutils/writers/manpage.pyi | 253 + stubs/docutils/docutils/writers/null.pyi | 11 + .../docutils/writers/odf_odt/__init__.pyi | 426 + .../docutils/writers/odf_odt/prepstyles.pyi | 7 + .../writers/odf_odt/pygmentsformatter.pyi | 31 + .../docutils/writers/pep_html/__init__.pyi | 20 + stubs/docutils/docutils/writers/pseudoxml.pyi | 9 + .../docutils/writers/s5_html/__init__.pyi | 42 + .../docutils/writers/xetex/__init__.pyi | 30 + .../@tests/stubtest_allowlist.txt | 2 + stubs/editdistance/METADATA.toml | 2 + stubs/editdistance/editdistance/__init__.pyi | 8 + .../entrypoints/@tests/stubtest_allowlist.txt | 2 + stubs/entrypoints/METADATA.toml | 2 + stubs/entrypoints/entrypoints.pyi | 48 + stubs/ephem/@tests/stubtest_allowlist.txt | 11 + stubs/ephem/METADATA.toml | 2 + stubs/ephem/ephem/__init__.pyi | 289 + stubs/ephem/ephem/_libastro.pyi | 394 + stubs/ephem/ephem/cities.pyi | 5 + stubs/ephem/ephem/stars.pyi | 15 + stubs/et_xmlfile/METADATA.toml | 2 + stubs/et_xmlfile/et_xmlfile/__init__.pyi | 9 + .../et_xmlfile/incremental_tree.pyi | 173 + stubs/et_xmlfile/et_xmlfile/xmlfile.pyi | 36 + stubs/fanstatic/@tests/stubtest_allowlist.txt | 69 + stubs/fanstatic/METADATA.toml | 3 + stubs/fanstatic/fanstatic/__init__.pyi | 43 + stubs/fanstatic/fanstatic/checksum.pyi | 10 + stubs/fanstatic/fanstatic/compiler.pyi | 124 + stubs/fanstatic/fanstatic/config.pyi | 10 + stubs/fanstatic/fanstatic/core.pyi | 236 + stubs/fanstatic/fanstatic/inclusion.pyi | 22 + stubs/fanstatic/fanstatic/injector.pyi | 60 + stubs/fanstatic/fanstatic/publisher.pyi | 48 + stubs/fanstatic/fanstatic/registry.pyi | 50 + stubs/fanstatic/fanstatic/wsgi.pyi | 22 + stubs/first/METADATA.toml | 2 + stubs/first/first.pyi | 19 + .../@tests/stubtest_allowlist.txt | 33 + stubs/flake8-bugbear/METADATA.toml | 2 + stubs/flake8-bugbear/bugbear.pyi | 270 + stubs/flake8-builtins/METADATA.toml | 3 + stubs/flake8-builtins/flake8_builtins.pyi | 45 + stubs/flake8-docstrings/METADATA.toml | 3 + stubs/flake8-docstrings/flake8_docstrings.pyi | 24 + stubs/flake8-rst-docstrings/METADATA.toml | 2 + .../flake8_rst_docstrings.pyi | 34 + stubs/flake8-simplify/METADATA.toml | 2 + .../flake8_simplify/__init__.pyi | 31 + .../flake8_simplify/constants.pyi | 6 + .../flake8_simplify/rules/__init__.pyi | 0 .../flake8_simplify/rules/ast_assign.pyi | 6 + .../flake8_simplify/rules/ast_bool_op.pyi | 8 + .../flake8_simplify/rules/ast_call.pyi | 13 + .../flake8_simplify/rules/ast_classdef.pyi | 3 + .../flake8_simplify/rules/ast_compare.pyi | 4 + .../flake8_simplify/rules/ast_expr.pyi | 3 + .../flake8_simplify/rules/ast_for.pyi | 7 + .../flake8_simplify/rules/ast_if.pyi | 11 + .../flake8_simplify/rules/ast_ifexp.pyi | 5 + .../flake8_simplify/rules/ast_subscript.pyi | 3 + .../flake8_simplify/rules/ast_try.pyi | 4 + .../flake8_simplify/rules/ast_unary_op.pyi | 8 + .../flake8_simplify/rules/ast_with.pyi | 3 + .../flake8-simplify/flake8_simplify/utils.pyi | 36 + stubs/flake8-typing-imports/METADATA.toml | 2 + .../flake8_typing_imports.pyi | 40 + stubs/flake8/@tests/stubtest_allowlist.txt | 1 + stubs/flake8/METADATA.toml | 3 + stubs/flake8/flake8/__init__.pyi | 8 + stubs/flake8/flake8/_compat.pyi | 9 + stubs/flake8/flake8/api/__init__.pyi | 0 stubs/flake8/flake8/api/legacy.pyi | 27 + stubs/flake8/flake8/checker.pyi | 55 + stubs/flake8/flake8/defaults.pyi | 12 + stubs/flake8/flake8/discover_files.pyi | 8 + stubs/flake8/flake8/exceptions.pyi | 24 + stubs/flake8/flake8/formatting/__init__.pyi | 0 .../flake8/formatting/_windows_color.pyi | 1 + stubs/flake8/flake8/formatting/base.pyi | 25 + stubs/flake8/flake8/formatting/default.pyi | 29 + stubs/flake8/flake8/main/__init__.pyi | 0 stubs/flake8/flake8/main/application.pyi | 29 + stubs/flake8/flake8/main/cli.pyi | 3 + stubs/flake8/flake8/main/debug.pyi | 5 + stubs/flake8/flake8/main/options.pyi | 12 + stubs/flake8/flake8/options/__init__.pyi | 0 stubs/flake8/flake8/options/aggregator.pyi | 12 + stubs/flake8/flake8/options/config.pyi | 10 + stubs/flake8/flake8/options/manager.pyi | 71 + stubs/flake8/flake8/options/parse_args.pyi | 6 + stubs/flake8/flake8/plugins/__init__.pyi | 0 stubs/flake8/flake8/plugins/finder.pyi | 48 + stubs/flake8/flake8/plugins/pycodestyle.pyi | 32 + stubs/flake8/flake8/plugins/pyflakes.pyi | 21 + stubs/flake8/flake8/plugins/reporter.pyi | 9 + stubs/flake8/flake8/processor.pyi | 72 + stubs/flake8/flake8/statistics.pyi | 27 + stubs/flake8/flake8/style_guide.pyi | 70 + stubs/flake8/flake8/utils.pyi | 25 + stubs/flake8/flake8/violation.pyi | 13 + stubs/fpdf2/@tests/stubtest_allowlist.txt | 15 + stubs/fpdf2/METADATA.toml | 7 + stubs/fpdf2/fpdf/__init__.pyi | 36 + stubs/fpdf2/fpdf/_fonttools_shims.pyi | 55 + stubs/fpdf2/fpdf/actions.pyi | 36 + stubs/fpdf2/fpdf/annotations.pyi | 102 + stubs/fpdf2/fpdf/bidi.pyi | 68 + stubs/fpdf2/fpdf/deprecation.pyi | 12 + stubs/fpdf2/fpdf/drawing.pyi | 502 ++ stubs/fpdf2/fpdf/encryption.pyi | 111 + stubs/fpdf2/fpdf/enums.pyi | 421 + stubs/fpdf2/fpdf/errors.pyi | 12 + stubs/fpdf2/fpdf/fonts.pyi | 182 + stubs/fpdf2/fpdf/fpdf.pyi | 723 ++ stubs/fpdf2/fpdf/graphics_state.pyi | 155 + stubs/fpdf2/fpdf/html.pyi | 96 + stubs/fpdf2/fpdf/image_datastructures.pyi | 56 + stubs/fpdf2/fpdf/image_parsing.pyi | 58 + stubs/fpdf2/fpdf/line_break.pyi | 172 + stubs/fpdf2/fpdf/linearization.pyi | 54 + stubs/fpdf2/fpdf/outline.pyi | 61 + stubs/fpdf2/fpdf/output.pyi | 271 + stubs/fpdf2/fpdf/pattern.pyi | 104 + stubs/fpdf2/fpdf/prefs.pyi | 86 + stubs/fpdf2/fpdf/recorder.pyi | 13 + stubs/fpdf2/fpdf/sign.pyi | 16 + stubs/fpdf2/fpdf/structure_tree.pyi | 51 + stubs/fpdf2/fpdf/svg.pyi | 147 + stubs/fpdf2/fpdf/syntax.pyi | 82 + stubs/fpdf2/fpdf/table.pyi | 140 + stubs/fpdf2/fpdf/template.pyi | 43 + stubs/fpdf2/fpdf/text_region.pyi | 174 + stubs/fpdf2/fpdf/transitions.pyi | 59 + stubs/fpdf2/fpdf/unicode_script.pyi | 172 + stubs/fpdf2/fpdf/util.pyi | 38 + stubs/gdb/@tests/stubtest_allowlist.txt | 83 + stubs/gdb/METADATA.toml | 16 + stubs/gdb/gdb/FrameDecorator.pyi | 24 + stubs/gdb/gdb/FrameIterator.pyi | 8 + stubs/gdb/gdb/__init__.pyi | 1051 +++ stubs/gdb/gdb/dap/__init__.pyi | 21 + stubs/gdb/gdb/dap/breakpoint.pyi | 49 + stubs/gdb/gdb/dap/bt.pyi | 49 + stubs/gdb/gdb/dap/disassemble.pyi | 22 + stubs/gdb/gdb/dap/evaluate.pyi | 31 + stubs/gdb/gdb/dap/events.pyi | 12 + stubs/gdb/gdb/dap/frames.pyi | 7 + stubs/gdb/gdb/dap/io.pyi | 16 + stubs/gdb/gdb/dap/launch.pyi | 14 + stubs/gdb/gdb/dap/locations.pyi | 16 + stubs/gdb/gdb/dap/memory.pyi | 10 + stubs/gdb/gdb/dap/modules.pyi | 21 + stubs/gdb/gdb/dap/next.pyi | 13 + stubs/gdb/gdb/dap/pause.pyi | 3 + stubs/gdb/gdb/dap/scopes.pyi | 47 + stubs/gdb/gdb/dap/server.pyi | 77 + stubs/gdb/gdb/dap/sources.pyi | 23 + stubs/gdb/gdb/dap/startup.pyi | 43 + stubs/gdb/gdb/dap/state.pyi | 1 + stubs/gdb/gdb/dap/threads.pyi | 14 + stubs/gdb/gdb/dap/typecheck.pyi | 6 + stubs/gdb/gdb/dap/varref.pyi | 70 + stubs/gdb/gdb/disassembler.pyi | 60 + stubs/gdb/gdb/events.pyi | 25 + stubs/gdb/gdb/missing_debug.pyi | 8 + stubs/gdb/gdb/missing_files.pyi | 13 + stubs/gdb/gdb/missing_objfile.pyi | 7 + stubs/gdb/gdb/printing.pyi | 56 + stubs/gdb/gdb/prompt.pyi | 1 + stubs/gdb/gdb/types.pyi | 30 + stubs/gdb/gdb/unwinder.pyi | 20 + stubs/gdb/gdb/xmethod.pyi | 47 + stubs/geojson/@tests/stubtest_allowlist.txt | 3 + stubs/geojson/METADATA.toml | 2 + stubs/geojson/geojson/__init__.pyi | 28 + stubs/geojson/geojson/_version.pyi | 2 + stubs/geojson/geojson/base.pyi | 17 + stubs/geojson/geojson/codec.pyi | 33 + stubs/geojson/geojson/feature.pyi | 15 + stubs/geojson/geojson/geometry.pyi | 52 + stubs/geojson/geojson/mapping.pyi | 6 + stubs/geojson/geojson/utils.pyi | 16 + stubs/geopandas/@tests/stubtest_allowlist.txt | 25 + stubs/geopandas/METADATA.toml | 9 + stubs/geopandas/geopandas/__init__.pyi | 20 + stubs/geopandas/geopandas/_config.pyi | 21 + stubs/geopandas/geopandas/_decorator.pyi | 20 + stubs/geopandas/geopandas/_exports.pyi | 21 + stubs/geopandas/geopandas/accessors.pyi | 7 + stubs/geopandas/geopandas/array.pyi | 259 + stubs/geopandas/geopandas/base.pyi | 246 + stubs/geopandas/geopandas/explore.pyi | 65 + stubs/geopandas/geopandas/geodataframe.pyi | 370 + stubs/geopandas/geopandas/geoseries.pyi | 218 + stubs/geopandas/geopandas/io/__init__.pyi | 1 + stubs/geopandas/geopandas/io/_geoarrow.pyi | 68 + stubs/geopandas/geopandas/io/arrow.pyi | 28 + stubs/geopandas/geopandas/io/file.pyi | 48 + stubs/geopandas/geopandas/io/sql.pyi | 117 + stubs/geopandas/geopandas/plotting.pyi | 259 + stubs/geopandas/geopandas/sindex.pyi | 82 + stubs/geopandas/geopandas/testing.pyi | 33 + stubs/geopandas/geopandas/tools/__init__.pyi | 7 + .../geopandas/tools/_show_versions.pyi | 1 + stubs/geopandas/geopandas/tools/clip.pyi | 9 + stubs/geopandas/geopandas/tools/geocoding.pyi | 18 + .../geopandas/tools/hilbert_curve.pyi | 1 + stubs/geopandas/geopandas/tools/overlay.pyi | 11 + stubs/geopandas/geopandas/tools/sjoin.pyi | 26 + stubs/geopandas/geopandas/tools/util.pyi | 12 + stubs/gevent/@tests/stubtest_allowlist.txt | 164 + .../@tests/stubtest_allowlist_darwin.txt | 14 + .../@tests/stubtest_allowlist_linux.txt | 14 + .../@tests/stubtest_allowlist_win32.txt | 19 + stubs/gevent/METADATA.toml | 12 + stubs/gevent/gevent/__init__.pyi | 76 + stubs/gevent/gevent/_abstract_linkable.pyi | 16 + stubs/gevent/gevent/_config.pyi | 204 + stubs/gevent/gevent/_ffi/__init__.pyi | 0 stubs/gevent/gevent/_ffi/loop.pyi | 87 + stubs/gevent/gevent/_ffi/watcher.pyi | 98 + stubs/gevent/gevent/_fileobjectcommon.pyi | 371 + stubs/gevent/gevent/_greenlet_primitives.pyi | 21 + stubs/gevent/gevent/_hub_local.pyi | 15 + stubs/gevent/gevent/_hub_primitives.pyi | 74 + stubs/gevent/gevent/_ident.pyi | 15 + stubs/gevent/gevent/_imap.pyi | 28 + stubs/gevent/gevent/_monitor.pyi | 51 + stubs/gevent/gevent/_threading.pyi | 22 + stubs/gevent/gevent/_types.pyi | 160 + stubs/gevent/gevent/_util.pyi | 62 + stubs/gevent/gevent/_waiter.pyi | 48 + stubs/gevent/gevent/ares.pyi | 3 + stubs/gevent/gevent/backdoor.pyi | 49 + stubs/gevent/gevent/baseserver.pyi | 65 + stubs/gevent/gevent/event.pyi | 70 + stubs/gevent/gevent/events.pyi | 186 + stubs/gevent/gevent/exceptions.pyi | 17 + stubs/gevent/gevent/fileobject.pyi | 157 + stubs/gevent/gevent/greenlet.pyi | 106 + stubs/gevent/gevent/hub.pyi | 118 + stubs/gevent/gevent/libev/__init__.pyi | 1 + stubs/gevent/gevent/libev/corecext.pyi | 103 + stubs/gevent/gevent/libev/corecffi.pyi | 46 + stubs/gevent/gevent/libev/watcher.pyi | 71 + stubs/gevent/gevent/libuv/__init__.pyi | 1 + stubs/gevent/gevent/libuv/loop.pyi | 44 + stubs/gevent/gevent/libuv/watcher.pyi | 37 + stubs/gevent/gevent/local.pyi | 20 + stubs/gevent/gevent/lock.pyi | 44 + stubs/gevent/gevent/monkey/__init__.pyi | 68 + stubs/gevent/gevent/monkey/api.pyi | 7 + stubs/gevent/gevent/os.pyi | 36 + stubs/gevent/gevent/pool.pyi | 209 + stubs/gevent/gevent/pywsgi.pyi | 197 + stubs/gevent/gevent/queue.pyi | 115 + stubs/gevent/gevent/resolver/__init__.pyi | 23 + stubs/gevent/gevent/resolver/ares.pyi | 41 + stubs/gevent/gevent/resolver/blocking.pyi | 15 + stubs/gevent/gevent/resolver/cares.pyi | 52 + stubs/gevent/gevent/resolver/dnspython.pyi | 11 + stubs/gevent/gevent/resolver/thread.pyi | 17 + stubs/gevent/gevent/resolver_ares.pyi | 3 + stubs/gevent/gevent/resolver_thread.pyi | 2 + stubs/gevent/gevent/select.pyi | 20 + stubs/gevent/gevent/selectors.pyi | 24 + stubs/gevent/gevent/server.pyi | 89 + stubs/gevent/gevent/signal.pyi | 13 + stubs/gevent/gevent/socket.pyi | 23 + stubs/gevent/gevent/ssl.pyi | 29 + stubs/gevent/gevent/subprocess.pyi | 4 + stubs/gevent/gevent/threadpool.pyi | 71 + stubs/gevent/gevent/time.pyi | 3 + stubs/gevent/gevent/timeout.pyi | 60 + stubs/gevent/gevent/util.pyi | 51 + stubs/gevent/gevent/win32util.pyi | 5 + .../@tests/stubtest_allowlist.txt | 3 + stubs/google-cloud-ndb/METADATA.toml | 6 + .../google/cloud/ndb/__init__.pyi | 218 + .../google/cloud/ndb/_batch.pyi | 3 + .../google/cloud/ndb/_cache.pyi | 72 + .../google/cloud/ndb/_datastore_api.pyi | 5 + .../google/cloud/ndb/_datastore_query.pyi | 22 + .../google/cloud/ndb/_eventloop.pyi | 27 + .../google/cloud/ndb/_options.pyi | 30 + .../google/cloud/ndb/_transaction.pyi | 20 + .../google/cloud/ndb/blobstore.pyi | 65 + .../google/cloud/ndb/client.pyi | 35 + .../google/cloud/ndb/context.pyi | 112 + .../google/cloud/ndb/django_middleware.pyi | 2 + .../google/cloud/ndb/exceptions.pyi | 22 + .../google/cloud/ndb/global_cache.pyi | 77 + .../google-cloud-ndb/google/cloud/ndb/key.pyi | 99 + .../google/cloud/ndb/metadata.pyi | 51 + .../google/cloud/ndb/model.pyi | 516 ++ .../google/cloud/ndb/msgprop.pyi | 5 + .../google/cloud/ndb/polymodel.pyi | 9 + .../google/cloud/ndb/query.pyi | 167 + .../google/cloud/ndb/stats.pyi | 102 + .../google/cloud/ndb/tasklets.pyi | 58 + .../google/cloud/ndb/utils.pyi | 28 + .../google/cloud/ndb/version.pyi | 1 + stubs/greenlet/@tests/stubtest_allowlist.txt | 7 + .../@tests/test_cases/check_greenlet.py | 15 + stubs/greenlet/METADATA.toml | 2 + stubs/greenlet/greenlet/__init__.pyi | 14 + stubs/greenlet/greenlet/_greenlet.pyi | 90 + stubs/grpcio-channelz/METADATA.toml | 3 + .../grpc_channelz/__init__.pyi | 0 .../grpc_channelz/v1/__init__.pyi | 0 .../grpc_channelz/v1/_async.pyi | 19 + .../grpc_channelz/v1/_servicer.pyi | 25 + .../grpc_channelz/v1/channelz.pyi | 6 + .../grpc_channelz/v1/channelz_pb2.pyi | 604 ++ .../grpc_channelz/v1/channelz_pb2_grpc.pyi | 121 + stubs/grpcio-health-checking/METADATA.toml | 3 + .../grpc_health/__init__.pyi | 0 .../grpc_health/v1/__init__.pyi | 0 .../grpc_health/v1/health.pyi | 37 + .../grpc_health/v1/health_pb2.pyi | 26 + .../grpc_health/v1/health_pb2_grpc.pyi | 41 + .../@tests/test_cases/check_reflection.py | 9 + .../@tests/test_cases/check_reflection_aio.py | 9 + stubs/grpcio-reflection/METADATA.toml | 3 + .../grpc_reflection/__init__.pyi | 0 .../grpc_reflection/v1alpha/__init__.pyi | 0 .../grpc_reflection/v1alpha/_async.pyi | 11 + .../grpc_reflection/v1alpha/_base.pyi | 6 + .../proto_reflection_descriptor_database.pyi | 11 + .../grpc_reflection/v1alpha/reflection.pyi | 27 + .../v1alpha/reflection_pb2.pyi | 107 + .../v1alpha/reflection_pb2_grpc.pyi | 31 + stubs/grpcio-status/METADATA.toml | 3 + stubs/grpcio-status/grpc_status/__init__.pyi | 0 stubs/grpcio-status/grpc_status/_async.pyi | 5 + .../grpcio-status/grpc_status/rpc_status.pyi | 11 + stubs/grpcio/@tests/stubtest_allowlist.txt | 6 + stubs/grpcio/@tests/test_cases/check_aio.py | 24 + .../test_cases/check_aio_multi_callable.py | 37 + stubs/grpcio/@tests/test_cases/check_grpc.py | 47 + .../test_cases/check_handler_inheritance.py | 37 + .../@tests/test_cases/check_multi_callable.py | 35 + .../@tests/test_cases/check_register.py | 14 + .../test_cases/check_server_interceptor.py | 35 + stubs/grpcio/METADATA.toml | 6 + stubs/grpcio/grpc/__init__.pyi | 611 ++ stubs/grpcio/grpc/aio/__init__.pyi | 536 ++ stubs/grpcio/grpc/experimental/gevent.pyi | 1 + stubs/gunicorn/@tests/stubtest_allowlist.txt | 9 + stubs/gunicorn/METADATA.toml | 14 + stubs/gunicorn/gunicorn/__init__.pyi | 6 + stubs/gunicorn/gunicorn/_types.pyi | 23 + stubs/gunicorn/gunicorn/app/__init__.pyi | 0 stubs/gunicorn/gunicorn/app/base.pyi | 33 + stubs/gunicorn/gunicorn/app/pasterapp.pyi | 7 + stubs/gunicorn/gunicorn/app/wsgiapp.pyi | 16 + stubs/gunicorn/gunicorn/arbiter.pyi | 79 + stubs/gunicorn/gunicorn/asgi/__init__.pyi | 4 + stubs/gunicorn/gunicorn/asgi/lifespan.pyi | 14 + stubs/gunicorn/gunicorn/asgi/parser.pyi | 158 + stubs/gunicorn/gunicorn/asgi/protocol.pyi | 61 + stubs/gunicorn/gunicorn/asgi/unreader.pyi | 13 + stubs/gunicorn/gunicorn/asgi/uwsgi.pyi | 39 + stubs/gunicorn/gunicorn/asgi/websocket.pyi | 40 + stubs/gunicorn/gunicorn/config.pyi | 1335 +++ stubs/gunicorn/gunicorn/ctl/__init__.pyi | 5 + stubs/gunicorn/gunicorn/ctl/cli.pyi | 13 + stubs/gunicorn/gunicorn/ctl/client.pyi | 16 + stubs/gunicorn/gunicorn/ctl/handlers.pyi | 113 + stubs/gunicorn/gunicorn/ctl/protocol.pyi | 45 + stubs/gunicorn/gunicorn/ctl/server.pyi | 11 + stubs/gunicorn/gunicorn/debug.pyi | 18 + stubs/gunicorn/gunicorn/dirty/__init__.pyi | 51 + stubs/gunicorn/gunicorn/dirty/app.pyi | 17 + stubs/gunicorn/gunicorn/dirty/arbiter.pyi | 48 + stubs/gunicorn/gunicorn/dirty/client.pyi | 74 + stubs/gunicorn/gunicorn/dirty/errors.pyi | 55 + stubs/gunicorn/gunicorn/dirty/protocol.pyi | 171 + stubs/gunicorn/gunicorn/dirty/stash.pyi | 71 + stubs/gunicorn/gunicorn/dirty/tlv.pyi | 25 + stubs/gunicorn/gunicorn/dirty/worker.pyi | 36 + stubs/gunicorn/gunicorn/errors.pyi | 8 + stubs/gunicorn/gunicorn/glogging.pyi | 159 + stubs/gunicorn/gunicorn/http/__init__.pyi | 25 + stubs/gunicorn/gunicorn/http/body.pyi | 48 + stubs/gunicorn/gunicorn/http/errors.pyi | 104 + stubs/gunicorn/gunicorn/http/message.pyi | 80 + stubs/gunicorn/gunicorn/http/parser.pyi | 28 + stubs/gunicorn/gunicorn/http/unreader.pyi | 25 + stubs/gunicorn/gunicorn/http/wsgi.pyi | 80 + stubs/gunicorn/gunicorn/http2/__init__.pyi | 19 + .../gunicorn/http2/async_connection.pyi | 42 + stubs/gunicorn/gunicorn/http2/connection.pyi | 42 + stubs/gunicorn/gunicorn/http2/errors.pyi | 70 + stubs/gunicorn/gunicorn/http2/request.pyi | 50 + stubs/gunicorn/gunicorn/http2/stream.pyi | 59 + .../gunicorn/gunicorn/instrument/__init__.pyi | 0 stubs/gunicorn/gunicorn/instrument/statsd.pyi | 99 + stubs/gunicorn/gunicorn/pidfile.pyi | 11 + stubs/gunicorn/gunicorn/reloader.pyi | 49 + stubs/gunicorn/gunicorn/sock.pyi | 46 + stubs/gunicorn/gunicorn/systemd.pyi | 8 + stubs/gunicorn/gunicorn/util.pyi | 50 + stubs/gunicorn/gunicorn/uwsgi/__init__.pyi | 17 + stubs/gunicorn/gunicorn/uwsgi/errors.pyi | 19 + stubs/gunicorn/gunicorn/uwsgi/message.pyi | 38 + stubs/gunicorn/gunicorn/uwsgi/parser.pyi | 7 + stubs/gunicorn/gunicorn/workers/__init__.pyi | 13 + stubs/gunicorn/gunicorn/workers/base.pyi | 48 + .../gunicorn/gunicorn/workers/base_async.pyi | 22 + stubs/gunicorn/gunicorn/workers/gasgi.pyi | 32 + stubs/gunicorn/gunicorn/workers/ggevent.pyi | 45 + stubs/gunicorn/gunicorn/workers/gthread.pyi | 80 + stubs/gunicorn/gunicorn/workers/gtornado.pyi | 24 + stubs/gunicorn/gunicorn/workers/sync.pyi | 19 + stubs/gunicorn/gunicorn/workers/workertmp.pyi | 13 + stubs/hdbcli/@tests/stubtest_allowlist.txt | 23 + stubs/hdbcli/METADATA.toml | 2 + stubs/hdbcli/hdbcli/__init__.pyi | 7 + stubs/hdbcli/hdbcli/dbapi.pyi | 193 + stubs/hdbcli/hdbcli/resultrow.pyi | 19 + stubs/hnswlib/@tests/stubtest_allowlist.txt | 3 + stubs/hnswlib/METADATA.toml | 9 + stubs/hnswlib/hnswlib.pyi | 67 + stubs/html5lib/@tests/stubtest_allowlist.txt | 6 + stubs/html5lib/METADATA.toml | 6 + stubs/html5lib/html5lib/__init__.pyi | 10 + stubs/html5lib/html5lib/_ihatexml.pyi | 55 + stubs/html5lib/html5lib/_inputstream.pyi | 150 + stubs/html5lib/html5lib/_tokenizer.pyi | 128 + stubs/html5lib/html5lib/_trie/__init__.pyi | 3 + stubs/html5lib/html5lib/_trie/_base.pyi | 9 + stubs/html5lib/html5lib/_trie/py.pyi | 10 + stubs/html5lib/html5lib/_utils.pyi | 43 + stubs/html5lib/html5lib/constants.pyi | 35 + stubs/html5lib/html5lib/filters/__init__.pyi | 0 .../filters/alphabeticalattributes.pyi | 5 + stubs/html5lib/html5lib/filters/base.pyi | 10 + .../html5lib/filters/inject_meta_charset.pyi | 8 + stubs/html5lib/html5lib/filters/lint.pyi | 10 + .../html5lib/filters/optionaltags.pyi | 9 + stubs/html5lib/html5lib/filters/sanitizer.pyi | 51 + .../html5lib/html5lib/filters/whitespace.pyi | 12 + stubs/html5lib/html5lib/html5parser.pyi | 66 + stubs/html5lib/html5lib/serializer.pyi | 102 + .../html5lib/treeadapters/__init__.pyi | 3 + .../html5lib/html5lib/treeadapters/genshi.pyi | 1 + stubs/html5lib/html5lib/treeadapters/sax.pyi | 3 + .../html5lib/treebuilders/__init__.pyi | 5 + stubs/html5lib/html5lib/treebuilders/base.pyi | 55 + stubs/html5lib/html5lib/treebuilders/dom.pyi | 7 + .../html5lib/html5lib/treebuilders/etree.pyi | 10 + .../html5lib/treebuilders/etree_lxml.pyi | 45 + .../html5lib/treewalkers/__init__.pyi | 7 + stubs/html5lib/html5lib/treewalkers/base.pyi | 33 + stubs/html5lib/html5lib/treewalkers/dom.pyi | 7 + stubs/html5lib/html5lib/treewalkers/etree.pyi | 9 + .../html5lib/treewalkers/etree_lxml.pyi | 58 + .../html5lib/html5lib/treewalkers/genshi.pyi | 5 + stubs/httplib2/@tests/stubtest_allowlist.txt | 2 + stubs/httplib2/METADATA.toml | 2 + stubs/httplib2/httplib2/__init__.pyi | 232 + stubs/httplib2/httplib2/auth.pyi | 18 + stubs/httplib2/httplib2/certs.pyi | 10 + stubs/httplib2/httplib2/decode.pyi | 52 + stubs/httplib2/httplib2/error.pyi | 22 + stubs/httplib2/httplib2/iri2uri.pyi | 14 + stubs/hvac/METADATA.toml | 3 + stubs/hvac/hvac/__init__.pyi | 3 + stubs/hvac/hvac/adapters.pyi | 66 + stubs/hvac/hvac/api/__init__.pyi | 7 + stubs/hvac/hvac/api/auth_methods/__init__.pyi | 40 + stubs/hvac/hvac/api/auth_methods/approle.pyi | 39 + stubs/hvac/hvac/api/auth_methods/aws.pyi | 103 + stubs/hvac/hvac/api/auth_methods/azure.pyi | 42 + stubs/hvac/hvac/api/auth_methods/cert.pyi | 41 + stubs/hvac/hvac/api/auth_methods/gcp.pyi | 38 + stubs/hvac/hvac/api/auth_methods/github.pyi | 12 + stubs/hvac/hvac/api/auth_methods/jwt.pyi | 59 + .../hvac/hvac/api/auth_methods/kubernetes.pyi | 34 + stubs/hvac/hvac/api/auth_methods/ldap.pyi | 56 + .../hvac/hvac/api/auth_methods/legacy_mfa.pyi | 11 + stubs/hvac/hvac/api/auth_methods/oidc.pyi | 33 + stubs/hvac/hvac/api/auth_methods/okta.pyi | 18 + stubs/hvac/hvac/api/auth_methods/radius.pyi | 14 + stubs/hvac/hvac/api/auth_methods/token.pyi | 70 + stubs/hvac/hvac/api/auth_methods/userpass.pyi | 11 + .../hvac/api/secrets_engines/__init__.pyi | 59 + .../api/secrets_engines/active_directory.pyi | 24 + stubs/hvac/hvac/api/secrets_engines/aws.pyi | 28 + stubs/hvac/hvac/api/secrets_engines/azure.pyi | 13 + .../hvac/hvac/api/secrets_engines/consul.pyi | 13 + .../hvac/api/secrets_engines/database.pyi | 45 + stubs/hvac/hvac/api/secrets_engines/gcp.pyi | 46 + .../hvac/api/secrets_engines/identity.pyi | 106 + stubs/hvac/hvac/api/secrets_engines/kv.pyi | 23 + stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi | 13 + stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi | 37 + stubs/hvac/hvac/api/secrets_engines/ldap.pyi | 41 + stubs/hvac/hvac/api/secrets_engines/pki.pyi | 36 + .../hvac/api/secrets_engines/rabbitmq.pyi | 18 + stubs/hvac/hvac/api/secrets_engines/ssh.pyi | 71 + .../hvac/api/secrets_engines/transform.pyi | 79 + .../hvac/hvac/api/secrets_engines/transit.pyi | 93 + .../hvac/hvac/api/system_backend/__init__.pyi | 62 + stubs/hvac/hvac/api/system_backend/audit.pyi | 7 + stubs/hvac/hvac/api/system_backend/auth.pyi | 21 + .../hvac/api/system_backend/capabilities.pyi | 4 + stubs/hvac/hvac/api/system_backend/health.pyi | 14 + stubs/hvac/hvac/api/system_backend/init.pyi | 16 + stubs/hvac/hvac/api/system_backend/key.pyi | 27 + stubs/hvac/hvac/api/system_backend/leader.pyi | 5 + stubs/hvac/hvac/api/system_backend/lease.pyi | 9 + stubs/hvac/hvac/api/system_backend/mount.pyi | 34 + .../hvac/api/system_backend/namespace.pyi | 6 + .../hvac/hvac/api/system_backend/policies.pyi | 15 + stubs/hvac/hvac/api/system_backend/policy.pyi | 7 + stubs/hvac/hvac/api/system_backend/quota.pyi | 9 + stubs/hvac/hvac/api/system_backend/raft.pyi | 21 + stubs/hvac/hvac/api/system_backend/seal.pyi | 8 + .../system_backend/system_backend_mixin.pyi | 8 + .../hvac/hvac/api/system_backend/wrapping.pyi | 6 + stubs/hvac/hvac/api/vault_api_base.pyi | 10 + stubs/hvac/hvac/api/vault_api_category.pyi | 26 + stubs/hvac/hvac/aws_utils.pyi | 11 + stubs/hvac/hvac/constants/__init__.pyi | 0 stubs/hvac/hvac/constants/approle.pyi | 4 + stubs/hvac/hvac/constants/aws.pyi | 7 + stubs/hvac/hvac/constants/azure.pyi | 3 + stubs/hvac/hvac/constants/client.pyi | 8 + stubs/hvac/hvac/constants/gcp.pyi | 8 + stubs/hvac/hvac/constants/identity.pyi | 5 + stubs/hvac/hvac/constants/transit.pyi | 12 + stubs/hvac/hvac/exceptions.pyi | 43 + stubs/hvac/hvac/utils.pyi | 48 + stubs/hvac/hvac/v1/__init__.pyi | 92 + stubs/ibm-db/METADATA.toml | 2 + stubs/ibm-db/ibm_db.pyi | 358 + stubs/ibm-db/ibm_db_ctx.pyi | 8 + stubs/icalendar/@tests/stubtest_allowlist.txt | 11 + .../icalendar/@tests/test_cases/check_cal.py | 9 + stubs/icalendar/METADATA.toml | 7 + stubs/icalendar/icalendar/__init__.pyi | 125 + stubs/icalendar/icalendar/alarms.pyi | 48 + stubs/icalendar/icalendar/attr.pyi | 26 + stubs/icalendar/icalendar/cal.pyi | 551 ++ stubs/icalendar/icalendar/caselessdict.pyi | 49 + stubs/icalendar/icalendar/enums.pyi | 44 + stubs/icalendar/icalendar/error.pyi | 19 + stubs/icalendar/icalendar/param.pyi | 62 + stubs/icalendar/icalendar/parser.pyi | 98 + stubs/icalendar/icalendar/parser_tools.pyi | 21 + stubs/icalendar/icalendar/prop.pyi | 341 + .../icalendar/icalendar/timezone/__init__.pyi | 9 + .../timezone/equivalent_timezone_ids.pyi | 13 + .../equivalent_timezone_ids_result.pyi | 6 + .../icalendar/icalendar/timezone/provider.pyi | 29 + stubs/icalendar/icalendar/timezone/pytz.pyi | 22 + stubs/icalendar/icalendar/timezone/tzid.pyi | 7 + stubs/icalendar/icalendar/timezone/tzp.pyi | 30 + .../icalendar/timezone/windows_to_olson.pyi | 3 + .../icalendar/icalendar/timezone/zoneinfo.pyi | 24 + stubs/icalendar/icalendar/tools.pyi | 25 + stubs/icalendar/icalendar/version.pyi | 8 + stubs/inifile/@tests/stubtest_allowlist.txt | 24 + stubs/inifile/METADATA.toml | 2 + stubs/inifile/inifile.pyi | 138 + stubs/jmespath/METADATA.toml | 2 + stubs/jmespath/jmespath/__init__.pyi | 9 + stubs/jmespath/jmespath/ast.pyi | 56 + stubs/jmespath/jmespath/compat.pyi | 13 + stubs/jmespath/jmespath/exceptions.pyi | 47 + stubs/jmespath/jmespath/functions.pyi | 23 + stubs/jmespath/jmespath/lexer.pyi | 19 + stubs/jmespath/jmespath/parser.pyi | 19 + stubs/jmespath/jmespath/visitor.pyi | 67 + stubs/jsonnet/METADATA.toml | 2 + stubs/jsonnet/_jsonnet.pyi | 35 + .../jsonschema/@tests/stubtest_allowlist.txt | 35 + stubs/jsonschema/METADATA.toml | 6 + stubs/jsonschema/jsonschema/__init__.pyi | 42 + stubs/jsonschema/jsonschema/_format.pyi | 48 + stubs/jsonschema/jsonschema/_keywords.pyi | 36 + .../jsonschema/_legacy_keywords.pyi | 23 + stubs/jsonschema/jsonschema/_types.pyi | 27 + stubs/jsonschema/jsonschema/_typing.pyi | 12 + stubs/jsonschema/jsonschema/_utils.pyi | 38 + stubs/jsonschema/jsonschema/cli.pyi | 65 + stubs/jsonschema/jsonschema/exceptions.pyi | 91 + stubs/jsonschema/jsonschema/protocols.pyi | 32 + stubs/jsonschema/jsonschema/validators.pyi | 144 + stubs/jwcrypto/@tests/stubtest_allowlist.txt | 9 + stubs/jwcrypto/METADATA.toml | 3 + stubs/jwcrypto/jwcrypto/__init__.pyi | 0 stubs/jwcrypto/jwcrypto/common.pyi | 50 + stubs/jwcrypto/jwcrypto/jwa.pyi | 36 + stubs/jwcrypto/jwcrypto/jwe.pyi | 64 + stubs/jwcrypto/jwcrypto/jwk.pyi | 278 + stubs/jwcrypto/jwcrypto/jws.pyi | 63 + stubs/jwcrypto/jwcrypto/jwt.pyi | 85 + stubs/jwcrypto/jwcrypto/version.pyi | 3 + .../@tests/stubtest_allowlist.txt | 24 + .../@tests/stubtest_allowlist_darwin.txt | 2 + stubs/kafka-python/METADATA.toml | 2 + stubs/kafka-python/kafka/__init__.pyi | 13 + stubs/kafka-python/kafka/admin/__init__.pyi | 30 + .../kafka-python/kafka/admin/acl_resource.pyi | 91 + stubs/kafka-python/kafka/admin/client.pyi | 114 + .../kafka/admin/config_resource.pyi | 12 + .../kafka/admin/new_partitions.pyi | 6 + stubs/kafka-python/kafka/admin/new_topic.pyi | 16 + stubs/kafka-python/kafka/cli/__init__.pyi | 0 .../kafka-python/kafka/cli/admin/__init__.pyi | 3 + .../kafka/cli/admin/cluster/__init__.pyi | 3 + .../kafka/cli/admin/cluster/describe.pyi | 3 + .../kafka/cli/admin/configs/__init__.pyi | 3 + .../kafka/cli/admin/configs/describe.pyi | 5 + .../cli/admin/consumer_groups/__init__.pyi | 3 + .../cli/admin/consumer_groups/delete.pyi | 3 + .../cli/admin/consumer_groups/describe.pyi | 3 + .../kafka/cli/admin/consumer_groups/list.pyi | 3 + .../admin/consumer_groups/list_offsets.pyi | 3 + .../kafka/cli/admin/log_dirs/__init__.pyi | 3 + .../kafka/cli/admin/log_dirs/describe.pyi | 3 + .../kafka/cli/admin/topics/__init__.pyi | 3 + .../kafka/cli/admin/topics/create.pyi | 5 + .../kafka/cli/admin/topics/delete.pyi | 3 + .../kafka/cli/admin/topics/describe.pyi | 3 + .../kafka/cli/admin/topics/list.pyi | 3 + .../kafka/cli/consumer/__init__.pyi | 3 + .../kafka/cli/producer/__init__.pyi | 3 + stubs/kafka-python/kafka/client_async.pyi | 56 + stubs/kafka-python/kafka/cluster.pyi | 36 + stubs/kafka-python/kafka/codec.pyi | 25 + stubs/kafka-python/kafka/conn.pyi | 70 + .../kafka-python/kafka/consumer/__init__.pyi | 3 + stubs/kafka-python/kafka/consumer/fetcher.pyi | 150 + stubs/kafka-python/kafka/consumer/group.pyi | 143 + .../kafka/consumer/subscription_state.pyi | 112 + .../kafka/coordinator/__init__.pyi | 0 .../kafka/coordinator/assignors/__init__.pyi | 0 .../kafka/coordinator/assignors/abstract.pyi | 15 + .../kafka/coordinator/assignors/range.pyi | 15 + .../coordinator/assignors/roundrobin.pyi | 15 + .../coordinator/assignors/sticky/__init__.pyi | 0 .../assignors/sticky/partition_movements.pyi | 18 + .../assignors/sticky/sorted_set.pyi | 13 + .../assignors/sticky/sticky_assignor.pyi | 59 + stubs/kafka-python/kafka/coordinator/base.pyi | 86 + .../kafka/coordinator/consumer.pyi | 31 + .../kafka/coordinator/heartbeat.pyi | 22 + .../kafka/coordinator/protocol.pyi | 17 + .../kafka/coordinator/subscription.pyi | 13 + stubs/kafka-python/kafka/errors.pyi | 824 ++ stubs/kafka-python/kafka/future.pyi | 19 + stubs/kafka-python/kafka/metrics/__init__.pyi | 10 + .../kafka/metrics/compound_stat.pyi | 13 + .../kafka/metrics/dict_reporter.pyi | 15 + .../kafka/metrics/kafka_metric.pyi | 13 + .../kafka-python/kafka/metrics/measurable.pyi | 9 + .../kafka/metrics/measurable_stat.pyi | 6 + .../kafka/metrics/metric_config.pyi | 13 + .../kafka/metrics/metric_name.pyi | 13 + stubs/kafka-python/kafka/metrics/metrics.pyi | 24 + .../kafka/metrics/metrics_reporter.pyi | 13 + stubs/kafka-python/kafka/metrics/quota.pyi | 13 + stubs/kafka-python/kafka/metrics/stat.pyi | 5 + .../kafka/metrics/stats/__init__.pyi | 12 + .../kafka-python/kafka/metrics/stats/avg.pyi | 6 + .../kafka/metrics/stats/count.pyi | 6 + .../kafka/metrics/stats/histogram.pyi | 21 + .../kafka/metrics/stats/max_stat.pyi | 6 + .../kafka/metrics/stats/min_stat.pyi | 6 + .../kafka/metrics/stats/percentile.pyi | 6 + .../kafka/metrics/stats/percentiles.pyi | 21 + .../kafka-python/kafka/metrics/stats/rate.pyi | 28 + .../kafka/metrics/stats/sampled_stat.pyi | 26 + .../kafka/metrics/stats/sensor.pyi | 10 + .../kafka/metrics/stats/total.pyi | 6 + .../kafka/partitioner/__init__.pyi | 3 + .../kafka/partitioner/default.pyi | 5 + .../kafka-python/kafka/producer/__init__.pyi | 3 + stubs/kafka-python/kafka/producer/future.pyi | 37 + stubs/kafka-python/kafka/producer/kafka.pyi | 110 + .../kafka/producer/producer_batch.pyi | 42 + .../kafka/producer/record_accumulator.pyi | 45 + stubs/kafka-python/kafka/producer/sender.pyi | 47 + .../kafka/producer/transaction_manager.pyi | 187 + .../kafka-python/kafka/protocol/__init__.pyi | 3 + .../kafka-python/kafka/protocol/abstract.pyi | 9 + .../kafka/protocol/add_offsets_to_txn.pyi | 39 + .../kafka/protocol/add_partitions_to_txn.pyi | 39 + stubs/kafka-python/kafka/protocol/admin.pyi | 506 ++ stubs/kafka-python/kafka/protocol/api.pyi | 37 + .../kafka/protocol/api_versions.pyi | 70 + .../kafka/protocol/broker_api_versions.pyi | 3 + stubs/kafka-python/kafka/protocol/commit.pyi | 166 + stubs/kafka-python/kafka/protocol/end_txn.pyi | 39 + stubs/kafka-python/kafka/protocol/fetch.pyi | 143 + .../kafka/protocol/find_coordinator.pyi | 39 + stubs/kafka-python/kafka/protocol/frame.pyi | 6 + stubs/kafka-python/kafka/protocol/group.pyi | 229 + .../kafka/protocol/init_producer_id.pyi | 28 + .../kafka/protocol/list_offsets.pyi | 85 + stubs/kafka-python/kafka/protocol/message.pyi | 43 + .../kafka-python/kafka/protocol/metadata.pyi | 123 + .../protocol/offset_for_leader_epoch.pyi | 61 + stubs/kafka-python/kafka/protocol/parser.pyi | 15 + stubs/kafka-python/kafka/protocol/produce.pyi | 103 + .../kafka/protocol/sasl_authenticate.pyi | 28 + .../kafka/protocol/sasl_handshake.pyi | 28 + stubs/kafka-python/kafka/protocol/struct.pyi | 14 + .../kafka/protocol/txn_offset_commit.pyi | 39 + stubs/kafka-python/kafka/protocol/types.pyi | 115 + stubs/kafka-python/kafka/record/__init__.pyi | 3 + stubs/kafka-python/kafka/record/_crc32c.pyi | 8 + stubs/kafka-python/kafka/record/abc.pyi | 60 + .../kafka/record/default_records.pyi | 155 + .../kafka/record/legacy_records.pyi | 86 + .../kafka/record/memory_records.pyi | 44 + stubs/kafka-python/kafka/record/util.pyi | 5 + stubs/kafka-python/kafka/sasl/__init__.pyi | 6 + stubs/kafka-python/kafka/sasl/abc.pyi | 14 + stubs/kafka-python/kafka/sasl/gssapi.pyi | 16 + stubs/kafka-python/kafka/sasl/msk.pyi | 33 + stubs/kafka-python/kafka/sasl/oauth.pyi | 23 + stubs/kafka-python/kafka/sasl/plain.pyi | 15 + stubs/kafka-python/kafka/sasl/scram.pyi | 40 + stubs/kafka-python/kafka/sasl/sspi.pyi | 17 + .../kafka/serializer/__init__.pyi | 1 + .../kafka/serializer/abstract.pyi | 15 + stubs/kafka-python/kafka/socks5_wrapper.pyi | 25 + stubs/kafka-python/kafka/structs.pyi | 53 + stubs/kafka-python/kafka/util.pyi | 38 + stubs/kafka-python/kafka/version.pyi | 1 + stubs/keyboard/@tests/stubtest_allowlist.txt | 7 + .../@tests/stubtest_allowlist_darwin.txt | 3 + .../@tests/stubtest_allowlist_linux.txt | 3 + stubs/keyboard/METADATA.toml | 9 + stubs/keyboard/keyboard/__init__.pyi | 113 + stubs/keyboard/keyboard/_canonical_names.pyi | 5 + stubs/keyboard/keyboard/_generic.pyi | 23 + stubs/keyboard/keyboard/_keyboard_event.pyi | 28 + stubs/keyboard/keyboard/_mouse_event.pyi | 42 + stubs/keyboard/keyboard/mouse.pyi | 83 + stubs/ldap3/@tests/stubtest_allowlist.txt | 1 + stubs/ldap3/METADATA.toml | 10 + stubs/ldap3/ldap3/__init__.pyi | 103 + stubs/ldap3/ldap3/abstract/__init__.pyi | 15 + stubs/ldap3/ldap3/abstract/attrDef.pyi | 33 + stubs/ldap3/ldap3/abstract/attribute.pyi | 34 + stubs/ldap3/ldap3/abstract/cursor.pyi | 106 + stubs/ldap3/ldap3/abstract/entry.pyi | 76 + stubs/ldap3/ldap3/abstract/objectDef.pyi | 15 + stubs/ldap3/ldap3/core/__init__.pyi | 0 stubs/ldap3/ldap3/core/connection.pyi | 182 + stubs/ldap3/ldap3/core/exceptions.pyi | 129 + stubs/ldap3/ldap3/core/pooling.pyi | 42 + stubs/ldap3/ldap3/core/rdns.pyi | 12 + stubs/ldap3/ldap3/core/results.pyi | 56 + stubs/ldap3/ldap3/core/server.pyi | 53 + stubs/ldap3/ldap3/core/timezone.pyi | 11 + stubs/ldap3/ldap3/core/tls.pyi | 36 + stubs/ldap3/ldap3/core/usage.pyi | 41 + stubs/ldap3/ldap3/extend/__init__.pyi | 97 + .../ldap3/ldap3/extend/microsoft/__init__.pyi | 0 .../extend/microsoft/addMembersToGroups.pyi | 1 + .../ldap3/ldap3/extend/microsoft/dirSync.pyi | 30 + .../ldap3/extend/microsoft/modifyPassword.pyi | 1 + .../extend/microsoft/persistentSearch.pyi | 15 + .../microsoft/removeMembersFromGroups.pyi | 1 + .../ldap3/extend/microsoft/unlockAccount.pyi | 1 + stubs/ldap3/ldap3/extend/novell/__init__.pyi | 0 .../extend/novell/addMembersToGroups.pyi | 1 + .../extend/novell/checkGroupsMemberships.pyi | 1 + .../ldap3/extend/novell/endTransaction.pyi | 15 + stubs/ldap3/ldap3/extend/novell/getBindDn.pyi | 10 + .../ldap3/extend/novell/listReplicas.pyi | 13 + .../novell/nmasGetUniversalPassword.pyi | 12 + .../novell/nmasSetUniversalPassword.pyi | 12 + .../extend/novell/partition_entry_count.pyi | 11 + .../extend/novell/removeMembersFromGroups.pyi | 1 + .../ldap3/ldap3/extend/novell/replicaInfo.pyi | 11 + .../ldap3/extend/novell/startTransaction.pyi | 15 + stubs/ldap3/ldap3/extend/operation.pyi | 21 + .../ldap3/extend/standard/PagedSearch.pyi | 30 + .../extend/standard/PersistentSearch.pyi | 36 + .../ldap3/ldap3/extend/standard/__init__.pyi | 0 .../ldap3/extend/standard/modifyPassword.pyi | 13 + stubs/ldap3/ldap3/extend/standard/whoAmI.pyi | 7 + stubs/ldap3/ldap3/operation/__init__.pyi | 0 stubs/ldap3/ldap3/operation/abandon.pyi | 2 + stubs/ldap3/ldap3/operation/add.pyi | 3 + stubs/ldap3/ldap3/operation/bind.pyi | 11 + stubs/ldap3/ldap3/operation/compare.pyi | 3 + stubs/ldap3/ldap3/operation/delete.pyi | 3 + stubs/ldap3/ldap3/operation/extended.pyi | 14 + stubs/ldap3/ldap3/operation/modify.pyi | 7 + stubs/ldap3/ldap3/operation/modifyDn.pyi | 3 + stubs/ldap3/ldap3/operation/search.pyi | 65 + stubs/ldap3/ldap3/operation/unbind.pyi | 1 + stubs/ldap3/ldap3/protocol/__init__.pyi | 0 stubs/ldap3/ldap3/protocol/controls.pyi | 1 + stubs/ldap3/ldap3/protocol/convert.pyi | 20 + .../ldap3/protocol/formatters/__init__.pyi | 0 .../ldap3/protocol/formatters/formatters.pyi | 16 + .../ldap3/protocol/formatters/standard.pyi | 7 + .../ldap3/protocol/formatters/validators.pyi | 16 + stubs/ldap3/ldap3/protocol/microsoft.pyi | 25 + stubs/ldap3/ldap3/protocol/novell.pyi | 67 + stubs/ldap3/ldap3/protocol/oid.pyi | 29 + .../ldap3/ldap3/protocol/persistentSearch.pyi | 14 + stubs/ldap3/ldap3/protocol/rfc2696.pyi | 19 + stubs/ldap3/ldap3/protocol/rfc2849.pyi | 18 + stubs/ldap3/ldap3/protocol/rfc3062.pyi | 25 + stubs/ldap3/ldap3/protocol/rfc4511.pyi | 321 + stubs/ldap3/ldap3/protocol/rfc4512.pyi | 204 + stubs/ldap3/ldap3/protocol/rfc4527.pyi | 2 + stubs/ldap3/ldap3/protocol/sasl/__init__.pyi | 0 stubs/ldap3/ldap3/protocol/sasl/digestMd5.pyi | 9 + stubs/ldap3/ldap3/protocol/sasl/external.pyi | 1 + stubs/ldap3/ldap3/protocol/sasl/kerberos.pyi | 8 + stubs/ldap3/ldap3/protocol/sasl/plain.pyi | 1 + stubs/ldap3/ldap3/protocol/sasl/sasl.pyi | 5 + .../ldap3/ldap3/protocol/schemas/__init__.pyi | 0 .../ldap3/ldap3/protocol/schemas/ad2012R2.pyi | 2 + stubs/ldap3/ldap3/protocol/schemas/ds389.pyi | 2 + .../ldap3/ldap3/protocol/schemas/edir888.pyi | 2 + .../ldap3/ldap3/protocol/schemas/edir914.pyi | 2 + .../ldap3/ldap3/protocol/schemas/slapd24.pyi | 2 + stubs/ldap3/ldap3/strategy/__init__.pyi | 0 stubs/ldap3/ldap3/strategy/asyncStream.pyi | 18 + stubs/ldap3/ldap3/strategy/asynchronous.pyi | 28 + stubs/ldap3/ldap3/strategy/base.pyi | 42 + stubs/ldap3/ldap3/strategy/ldifProducer.pyi | 21 + stubs/ldap3/ldap3/strategy/mockAsync.pyi | 11 + stubs/ldap3/ldap3/strategy/mockBase.pyi | 37 + stubs/ldap3/ldap3/strategy/mockSync.pyi | 10 + stubs/ldap3/ldap3/strategy/restartable.pyi | 19 + stubs/ldap3/ldap3/strategy/reusable.pyi | 75 + .../ldap3/ldap3/strategy/safeRestartable.pyi | 5 + stubs/ldap3/ldap3/strategy/safeSync.pyi | 5 + stubs/ldap3/ldap3/strategy/sync.pyi | 19 + stubs/ldap3/ldap3/utils/__init__.pyi | 0 stubs/ldap3/ldap3/utils/asn1.pyi | 52 + stubs/ldap3/ldap3/utils/ciDict.pyi | 29 + stubs/ldap3/ldap3/utils/config.pyi | 6 + stubs/ldap3/ldap3/utils/conv.pyi | 12 + stubs/ldap3/ldap3/utils/dn.pyi | 11 + stubs/ldap3/ldap3/utils/hashed.pyi | 6 + stubs/ldap3/ldap3/utils/log.pyi | 25 + stubs/ldap3/ldap3/utils/ntlm.pyi | 117 + stubs/ldap3/ldap3/utils/port_validators.pyi | 2 + stubs/ldap3/ldap3/utils/repr.pyi | 5 + stubs/ldap3/ldap3/utils/tls_backport.pyi | 3 + stubs/ldap3/ldap3/utils/uri.pyi | 1 + stubs/ldap3/ldap3/version.pyi | 9 + stubs/lunardate/METADATA.toml | 2 + stubs/lunardate/lunardate.pyi | 53 + stubs/lupa/METADATA.toml | 2 + stubs/lupa/lupa/__init__.pyi | 17 + stubs/lupa/lupa/lua51.pyi | 102 + stubs/lupa/lupa/lua52.pyi | 102 + stubs/lupa/lupa/lua53.pyi | 102 + stubs/lupa/lupa/lua54.pyi | 102 + stubs/lupa/lupa/luajit20.pyi | 96 + stubs/lupa/lupa/luajit21.pyi | 96 + stubs/lupa/lupa/version.pyi | 3 + stubs/lzstring/@tests/stubtest_allowlist.txt | 6 + stubs/lzstring/METADATA.toml | 2 + stubs/lzstring/lzstring/__init__.pyi | 17 + stubs/m3u8/@tests/stubtest_allowlist.txt | 5 + stubs/m3u8/METADATA.toml | 2 + stubs/m3u8/m3u8/__init__.pyi | 72 + stubs/m3u8/m3u8/httpclient.pyi | 19 + stubs/m3u8/m3u8/mixins.pyi | 28 + stubs/m3u8/m3u8/model.pyi | 454 + stubs/m3u8/m3u8/parser.pyi | 29 + stubs/m3u8/m3u8/protocol.pyi | 41 + stubs/m3u8/m3u8/version_matching.pyi | 5 + stubs/m3u8/m3u8/version_matching_rules.pyi | 24 + stubs/mock/@tests/stubtest_allowlist.txt | 3 + stubs/mock/METADATA.toml | 2 + stubs/mock/mock/__init__.pyi | 24 + stubs/mock/mock/backports.pyi | 2 + stubs/mock/mock/mock.pyi | 377 + .../@tests/stubtest_allowlist.txt | 6 + stubs/mypy-extensions/METADATA.toml | 2 + stubs/mypy-extensions/mypy_extensions.pyi | 95 + stubs/mysqlclient/METADATA.toml | 5 + stubs/mysqlclient/MySQLdb/__init__.pyi | 95 + stubs/mysqlclient/MySQLdb/_exceptions.pyi | 13 + stubs/mysqlclient/MySQLdb/_mysql.pyi | 92 + stubs/mysqlclient/MySQLdb/connections.pyi | 59 + .../mysqlclient/MySQLdb/constants/CLIENT.pyi | 18 + stubs/mysqlclient/MySQLdb/constants/CR.pyi | 69 + stubs/mysqlclient/MySQLdb/constants/ER.pyi | 790 ++ .../MySQLdb/constants/FIELD_TYPE.pyi | 29 + stubs/mysqlclient/MySQLdb/constants/FLAG.pyi | 16 + .../MySQLdb/constants/__init__.pyi | 3 + stubs/mysqlclient/MySQLdb/converters.pyi | 30 + stubs/mysqlclient/MySQLdb/cursors.pyi | 71 + stubs/mysqlclient/MySQLdb/release.pyi | 1 + stubs/mysqlclient/MySQLdb/times.pyi | 27 + stubs/nanoid/METADATA.toml | 2 + stubs/nanoid/nanoid/__init__.pyi | 4 + stubs/nanoid/nanoid/algorithm.pyi | 1 + stubs/nanoid/nanoid/generate.pyi | 3 + stubs/nanoid/nanoid/method.pyi | 6 + stubs/nanoid/nanoid/non_secure_generate.pyi | 3 + stubs/nanoid/nanoid/resources.pyi | 2 + .../nanoleafapi/@tests/stubtest_allowlist.txt | 1 + stubs/nanoleafapi/METADATA.toml | 2 + stubs/nanoleafapi/nanoleafapi/__init__.pyi | 16 + .../nanoleafapi/nanoleafapi/digital_twin.pyi | 12 + stubs/nanoleafapi/nanoleafapi/discovery.pyi | 1 + stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi | 68 + stubs/netaddr/@tests/stubtest_allowlist.txt | 4 + stubs/netaddr/METADATA.toml | 2 + stubs/netaddr/netaddr/__init__.pyi | 124 + stubs/netaddr/netaddr/cli.pyi | 8 + stubs/netaddr/netaddr/compat.pyi | 0 stubs/netaddr/netaddr/contrib/__init__.pyi | 0 .../netaddr/contrib/subnet_splitter.pyi | 7 + stubs/netaddr/netaddr/core.pyi | 34 + stubs/netaddr/netaddr/eui/__init__.pyi | 91 + stubs/netaddr/netaddr/eui/ieee.pyi | 32 + stubs/netaddr/netaddr/fbsocket.pyi | 8 + stubs/netaddr/netaddr/ip/__init__.pyi | 192 + stubs/netaddr/netaddr/ip/glob.pyi | 19 + stubs/netaddr/netaddr/ip/iana.pyi | 51 + stubs/netaddr/netaddr/ip/nmap.pyi | 6 + stubs/netaddr/netaddr/ip/rfc1924.pyi | 9 + stubs/netaddr/netaddr/ip/sets.pyi | 46 + stubs/netaddr/netaddr/strategy/__init__.pyi | 15 + stubs/netaddr/netaddr/strategy/eui48.pyi | 39 + stubs/netaddr/netaddr/strategy/eui64.pyi | 38 + stubs/netaddr/netaddr/strategy/ipv4.pyi | 39 + stubs/netaddr/netaddr/strategy/ipv6.pyi | 43 + stubs/netifaces/@tests/stubtest_allowlist.txt | 34 + stubs/netifaces/METADATA.toml | 2 + stubs/netifaces/netifaces.pyi | 72 + stubs/networkx/@tests/stubtest_allowlist.txt | 39 + .../check_dispatch_decorator-py312.py | 23 + .../check_tricky_function_params-py312.py | 25 + stubs/networkx/METADATA.toml | 8 + stubs/networkx/networkx/__init__.pyi | 30 + stubs/networkx/networkx/_typing.pyi | 22 + .../networkx/networkx/algorithms/__init__.pyi | 140 + .../algorithms/approximation/__init__.pyi | 14 + .../algorithms/approximation/clique.pyi | 13 + .../approximation/clustering_coefficient.pyi | 8 + .../algorithms/approximation/connectivity.pyi | 15 + .../algorithms/approximation/density.pyi | 14 + .../approximation/distance_measures.pyi | 8 + .../approximation/dominating_set.pyi | 11 + .../algorithms/approximation/kcomponents.pyi | 10 + .../algorithms/approximation/matching.pyi | 9 + .../algorithms/approximation/maxcut.pyi | 16 + .../algorithms/approximation/ramsey.pyi | 9 + .../algorithms/approximation/steinertree.pyi | 18 + .../approximation/traveling_salesman.pyi | 71 + .../algorithms/approximation/treewidth.pyi | 25 + .../algorithms/approximation/vertex_cover.pyi | 9 + .../algorithms/assortativity/__init__.pyi | 5 + .../algorithms/assortativity/connectivity.pyi | 17 + .../algorithms/assortativity/correlation.pyi | 25 + .../algorithms/assortativity/mixing.pyi | 37 + .../assortativity/neighbor_degree.pyi | 16 + .../algorithms/assortativity/pairs.pyi | 14 + .../networkx/algorithms/asteroidal.pyi | 13 + .../algorithms/bipartite/__init__.pyi | 13 + .../networkx/algorithms/bipartite/basic.pyi | 20 + .../algorithms/bipartite/centrality.pyi | 16 + .../networkx/algorithms/bipartite/cluster.pyi | 25 + .../algorithms/bipartite/covering.pyi | 10 + .../algorithms/bipartite/edgelist.pyi | 39 + .../algorithms/bipartite/extendability.pyi | 7 + .../algorithms/bipartite/generators.pyi | 50 + .../algorithms/bipartite/link_analysis.pyi | 20 + .../algorithms/bipartite/matching.pyi | 23 + .../networkx/algorithms/bipartite/matrix.pyi | 27 + .../algorithms/bipartite/projection.pyi | 26 + .../algorithms/bipartite/redundancy.pyi | 10 + .../algorithms/bipartite/spectral.pyi | 12 + .../networkx/networkx/algorithms/boundary.pyi | 112 + .../networkx/networkx/algorithms/bridges.pyi | 17 + .../networkx/algorithms/broadcasting.pyi | 9 + .../algorithms/centrality/__init__.pyi | 20 + .../algorithms/centrality/betweenness.pyi | 23 + .../centrality/betweenness_subset.pyi | 23 + .../algorithms/centrality/closeness.pyi | 19 + .../centrality/current_flow_betweenness.pyi | 33 + .../current_flow_betweenness_subset.pyi | 28 + .../centrality/current_flow_closeness.pyi | 13 + .../algorithms/centrality/degree_alg.pyi | 11 + .../algorithms/centrality/dispersion.pyi | 15 + .../algorithms/centrality/eigenvector.pyi | 20 + .../algorithms/centrality/flow_matrix.pyi | 44 + .../networkx/algorithms/centrality/group.pyi | 41 + .../algorithms/centrality/harmonic.pyi | 12 + .../networkx/algorithms/centrality/katz.pyi | 27 + .../algorithms/centrality/laplacian.pyi | 17 + .../networkx/algorithms/centrality/load.pyi | 16 + .../algorithms/centrality/percolation.pyi | 15 + .../algorithms/centrality/reaching.pyi | 19 + .../algorithms/centrality/second_order.pyi | 9 + .../algorithms/centrality/subgraph_alg.pyi | 15 + .../algorithms/centrality/trophic.pyi | 14 + .../algorithms/centrality/voterank_alg.pyi | 9 + stubs/networkx/networkx/algorithms/chains.pyi | 9 + .../networkx/networkx/algorithms/chordal.pyi | 29 + stubs/networkx/networkx/algorithms/clique.pyi | 60 + .../networkx/networkx/algorithms/cluster.pyi | 35 + .../networkx/algorithms/coloring/__init__.pyi | 4 + .../coloring/equitable_coloring.pyi | 23 + .../algorithms/coloring/greedy_coloring.pyi | 57 + .../algorithms/communicability_alg.pyi | 9 + .../algorithms/community/__init__.pyi | 13 + .../algorithms/community/asyn_fluid.pyi | 11 + .../algorithms/community/bipartitions.pyi | 22 + .../algorithms/community/centrality.pyi | 12 + .../algorithms/community/community_utils.pyi | 9 + .../algorithms/community/divisive.pyi | 13 + .../networkx/algorithms/community/kclique.pyi | 10 + .../community/label_propagation.pyi | 18 + .../networkx/algorithms/community/leiden.pyi | 20 + .../networkx/algorithms/community/local.pyi | 14 + .../networkx/algorithms/community/louvain.pyi | 26 + .../networkx/algorithms/community/lukes.pyi | 17 + .../algorithms/community/modularity_max.pyi | 15 + .../networkx/algorithms/community/quality.pyi | 27 + .../algorithms/components/__init__.pyi | 6 + .../algorithms/components/attracting.pyi | 14 + .../algorithms/components/biconnected.pyi | 15 + .../algorithms/components/connected.pyi | 15 + .../algorithms/components/semiconnected.pyi | 8 + .../components/strongly_connected.pyi | 24 + .../components/weakly_connected.pyi | 14 + .../algorithms/connectivity/__init__.pyi | 9 + .../algorithms/connectivity/connectivity.pyi | 62 + .../networkx/algorithms/connectivity/cuts.pyi | 38 + .../connectivity/disjoint_paths.pyi | 31 + .../connectivity/edge_augmentation.pyi | 71 + .../connectivity/edge_kcomponents.pyi | 26 + .../algorithms/connectivity/kcomponents.pyi | 13 + .../algorithms/connectivity/kcutsets.pyi | 14 + .../algorithms/connectivity/stoerwagner.pyi | 11 + .../algorithms/connectivity/utils.pyi | 9 + stubs/networkx/networkx/algorithms/core.pyi | 28 + .../networkx/networkx/algorithms/covering.pyi | 12 + stubs/networkx/networkx/algorithms/cuts.pyi | 36 + stubs/networkx/networkx/algorithms/cycles.pyi | 33 + .../networkx/algorithms/d_separation.pyi | 24 + stubs/networkx/networkx/algorithms/dag.pyi | 64 + .../networkx/algorithms/distance_measures.pyi | 63 + .../networkx/algorithms/distance_regular.pyi | 16 + .../networkx/algorithms/dominance.pyi | 11 + .../networkx/algorithms/dominating.pyi | 15 + .../algorithms/efficiency_measures.pyi | 11 + stubs/networkx/networkx/algorithms/euler.pyi | 21 + .../networkx/algorithms/flow/__init__.pyi | 11 + .../algorithms/flow/boykovkolmogorov.pyi | 18 + .../algorithms/flow/capacityscaling.pyi | 11 + .../networkx/algorithms/flow/dinitz_alg.pyi | 18 + .../networkx/algorithms/flow/edmondskarp.pyi | 18 + .../networkx/algorithms/flow/gomory_hu.pyi | 15 + .../networkx/algorithms/flow/maxflow.pyi | 47 + .../networkx/algorithms/flow/mincost.pyi | 21 + .../algorithms/flow/networksimplex.pyi | 50 + .../networkx/algorithms/flow/preflowpush.pyi | 18 + .../flow/shortestaugmentingpath.pyi | 19 + .../networkx/algorithms/flow/utils.pyi | 39 + .../networkx/algorithms/graph_hashing.pyi | 24 + .../networkx/algorithms/graphical.pyi | 27 + .../networkx/algorithms/hierarchy.pyi | 8 + stubs/networkx/networkx/algorithms/hybrid.pyi | 13 + .../networkx/networkx/algorithms/isolate.pyi | 14 + .../algorithms/isomorphism/__init__.pyi | 7 + .../algorithms/isomorphism/ismags.pyi | 32 + .../algorithms/isomorphism/isomorph.pyi | 34 + .../algorithms/isomorphism/isomorphvf2.pyi | 67 + .../algorithms/isomorphism/matchhelpers.pyi | 57 + .../isomorphism/temporalisomorphvf2.pyi | 30 + .../isomorphism/tree_isomorphism.pyi | 15 + .../networkx/algorithms/isomorphism/vf2pp.pyi | 42 + .../algorithms/isomorphism/vf2userfunc.pyi | 26 + .../algorithms/link_analysis/__init__.pyi | 2 + .../algorithms/link_analysis/hits_alg.pyi | 15 + .../algorithms/link_analysis/pagerank_alg.pyi | 29 + .../networkx/algorithms/link_prediction.pyi | 41 + .../algorithms/lowest_common_ancestors.pyi | 17 + .../networkx/networkx/algorithms/matching.pyi | 30 + .../networkx/algorithms/minors/__init__.pyi | 9 + .../algorithms/minors/contraction.pyi | 37 + stubs/networkx/networkx/algorithms/mis.pyi | 13 + stubs/networkx/networkx/algorithms/moral.pyi | 9 + .../algorithms/node_classification.pyi | 13 + .../networkx/algorithms/non_randomness.pyi | 7 + .../algorithms/operators/__init__.pyi | 4 + .../networkx/algorithms/operators/all.pyi | 16 + .../networkx/algorithms/operators/binary.pyi | 28 + .../networkx/algorithms/operators/product.pyi | 37 + .../networkx/algorithms/operators/unary.pyi | 15 + .../networkx/algorithms/perfect_graph.pyi | 7 + .../networkx/algorithms/planar_drawing.pyi | 21 + .../networkx/algorithms/planarity.pyi | 114 + .../networkx/algorithms/polynomials.pyi | 9 + .../networkx/algorithms/reciprocity.pyi | 12 + .../networkx/networkx/algorithms/regular.pyi | 13 + .../networkx/networkx/algorithms/richclub.pyi | 12 + .../algorithms/shortest_paths/__init__.pyi | 5 + .../algorithms/shortest_paths/astar.pyi | 28 + .../algorithms/shortest_paths/dense.pyi | 22 + .../algorithms/shortest_paths/generic.pyi | 148 + .../algorithms/shortest_paths/unweighted.pyi | 43 + .../algorithms/shortest_paths/weighted.pyi | 145 + .../networkx/algorithms/similarity.pyi | 125 + .../networkx/algorithms/simple_paths.pyi | 36 + .../networkx/algorithms/smallworld.pyi | 25 + .../networkx/networkx/algorithms/smetric.pyi | 7 + .../networkx/algorithms/sparsifiers.pyi | 12 + .../networkx/algorithms/structuralholes.pyi | 22 + .../networkx/algorithms/summarization.pyi | 21 + stubs/networkx/networkx/algorithms/swap.pyi | 21 + .../networkx/algorithms/threshold.pyi | 40 + .../networkx/algorithms/time_dependent.pyi | 11 + .../networkx/algorithms/tournament.pyi | 31 + .../algorithms/traversal/__init__.pyi | 5 + .../algorithms/traversal/beamsearch.pyi | 11 + .../traversal/breadth_first_search.pyi | 66 + .../traversal/depth_first_search.pyi | 73 + .../networkx/algorithms/traversal/edgebfs.pyi | 18 + .../networkx/algorithms/traversal/edgedfs.pyi | 18 + .../networkx/algorithms/tree/__init__.pyi | 7 + .../networkx/algorithms/tree/branchings.pyi | 72 + .../networkx/algorithms/tree/coding.pyi | 19 + .../algorithms/tree/decomposition.pyi | 9 + .../algorithms/tree/distance_measures.pyi | 10 + .../networkx/networkx/algorithms/tree/mst.pyi | 106 + .../networkx/algorithms/tree/operations.pyi | 12 + .../networkx/algorithms/tree/recognition.pyi | 14 + stubs/networkx/networkx/algorithms/triads.pyi | 25 + .../networkx/networkx/algorithms/vitality.pyi | 11 + .../networkx/networkx/algorithms/voronoi.pyi | 15 + stubs/networkx/networkx/algorithms/walks.pyi | 9 + stubs/networkx/networkx/algorithms/wiener.pyi | 13 + stubs/networkx/networkx/classes/__init__.pyi | 7 + stubs/networkx/networkx/classes/coreviews.pyi | 79 + stubs/networkx/networkx/classes/digraph.pyi | 52 + stubs/networkx/networkx/classes/filters.pyi | 32 + stubs/networkx/networkx/classes/function.pyi | 182 + stubs/networkx/networkx/classes/graph.pyi | 128 + .../networkx/networkx/classes/graphviews.pyi | 62 + .../networkx/classes/multidigraph.pyi | 38 + .../networkx/networkx/classes/multigraph.pyi | 62 + .../networkx/networkx/classes/reportviews.pyi | 427 + stubs/networkx/networkx/convert.pyi | 42 + stubs/networkx/networkx/convert_matrix.pyi | 119 + stubs/networkx/networkx/drawing/__init__.pyi | 4 + stubs/networkx/networkx/drawing/layout.pyi | 158 + stubs/networkx/networkx/drawing/nx_agraph.pyi | 45 + stubs/networkx/networkx/drawing/nx_latex.pyi | 70 + stubs/networkx/networkx/drawing/nx_pydot.pyi | 18 + stubs/networkx/networkx/drawing/nx_pylab.pyi | 376 + stubs/networkx/networkx/exception.pyi | 33 + .../networkx/networkx/generators/__init__.pyi | 29 + stubs/networkx/networkx/generators/atlas.pyi | 22 + .../networkx/networkx/generators/classic.pyi | 88 + .../networkx/networkx/generators/cographs.pyi | 9 + .../networkx/generators/community.pyi | 67 + .../networkx/generators/degree_seq.pyi | 63 + .../networkx/networkx/generators/directed.pyi | 37 + .../networkx/generators/duplication.pyi | 12 + stubs/networkx/networkx/generators/ego.pyi | 7 + .../networkx/generators/expanders.pyi | 36 + .../networkx/generators/geometric.pyi | 78 + .../networkx/generators/harary_graph.pyi | 15 + .../generators/internet_as_graphs.pyi | 46 + .../networkx/generators/intersection.pyi | 10 + .../networkx/generators/interval_graph.pyi | 10 + .../networkx/generators/joint_degree_seq.pyi | 27 + .../networkx/networkx/generators/lattice.pyi | 32 + stubs/networkx/networkx/generators/line.pyi | 11 + .../networkx/generators/mycielski.pyi | 11 + .../generators/nonisomorphic_trees.pyi | 11 + .../networkx/generators/random_clustered.pyi | 18 + .../networkx/generators/random_graphs.pyi | 83 + stubs/networkx/networkx/generators/small.pyi | 80 + stubs/networkx/networkx/generators/social.pyi | 12 + .../generators/spectral_graph_forge.pyi | 9 + .../networkx/generators/stochastic.pyi | 8 + stubs/networkx/networkx/generators/sudoku.pyi | 9 + .../networkx/generators/time_series.pyi | 10 + stubs/networkx/networkx/generators/trees.pyi | 35 + stubs/networkx/networkx/generators/triads.pyi | 12 + stubs/networkx/networkx/lazy_imports.pyi | 14 + stubs/networkx/networkx/linalg/__init__.pyi | 15 + .../networkx/linalg/algebraicconnectivity.pyi | 45 + stubs/networkx/networkx/linalg/attrmatrix.pyi | 41 + .../networkx/linalg/bethehessianmatrix.pyi | 10 + .../networkx/networkx/linalg/graphmatrix.pyi | 31 + .../networkx/linalg/laplacianmatrix.pyi | 39 + .../networkx/linalg/modularitymatrix.pyi | 18 + stubs/networkx/networkx/linalg/spectrum.pyi | 23 + .../networkx/networkx/readwrite/__init__.pyi | 12 + stubs/networkx/networkx/readwrite/adjlist.pyi | 29 + .../networkx/networkx/readwrite/edgelist.pyi | 56 + stubs/networkx/networkx/readwrite/gexf.pyi | 83 + stubs/networkx/networkx/readwrite/gml.pyi | 47 + stubs/networkx/networkx/readwrite/graph6.pyi | 19 + stubs/networkx/networkx/readwrite/graphml.pyi | 140 + .../readwrite/json_graph/__init__.pyi | 4 + .../readwrite/json_graph/adjacency.pyi | 17 + .../readwrite/json_graph/cytoscape.pyi | 12 + .../readwrite/json_graph/node_link.pyi | 31 + .../networkx/readwrite/json_graph/tree.pyi | 11 + stubs/networkx/networkx/readwrite/leda.pyi | 12 + .../networkx/readwrite/multiline_adjlist.pyi | 31 + stubs/networkx/networkx/readwrite/p2g.pyi | 11 + stubs/networkx/networkx/readwrite/pajek.pyi | 16 + stubs/networkx/networkx/readwrite/sparse6.pyi | 17 + stubs/networkx/networkx/readwrite/text.pyi | 70 + stubs/networkx/networkx/relabel.pyi | 30 + stubs/networkx/networkx/utils/__init__.pyi | 11 + stubs/networkx/networkx/utils/backends.pyi | 69 + stubs/networkx/networkx/utils/configs.pyi | 59 + stubs/networkx/networkx/utils/decorators.pyi | 29 + stubs/networkx/networkx/utils/heaps.pyi | 42 + .../networkx/networkx/utils/mapped_queue.pyi | 26 + stubs/networkx/networkx/utils/misc.pyi | 61 + .../networkx/utils/random_sequence.pyi | 20 + stubs/networkx/networkx/utils/rcm.pyi | 15 + stubs/networkx/networkx/utils/union_find.pyi | 13 + stubs/oauthlib/METADATA.toml | 2 + stubs/oauthlib/oauthlib/__init__.pyi | 7 + stubs/oauthlib/oauthlib/common.pyi | 118 + stubs/oauthlib/oauthlib/oauth1/__init__.pyi | 31 + .../oauthlib/oauth1/rfc5849/__init__.pyi | 68 + .../oauth1/rfc5849/endpoints/__init__.pyi | 7 + .../oauth1/rfc5849/endpoints/access_token.pyi | 10 + .../rfc5849/endpoints/authorization.pyi | 8 + .../oauth1/rfc5849/endpoints/base.pyi | 6 + .../rfc5849/endpoints/pre_configured.pyi | 9 + .../rfc5849/endpoints/request_token.pyi | 10 + .../oauth1/rfc5849/endpoints/resource.pyi | 8 + .../rfc5849/endpoints/signature_only.pyi | 8 + .../oauthlib/oauth1/rfc5849/errors.pyi | 26 + .../oauthlib/oauth1/rfc5849/parameters.pyi | 3 + .../oauth1/rfc5849/request_validator.pyi | 67 + .../oauthlib/oauth1/rfc5849/signature.pyi | 36 + .../oauthlib/oauth1/rfc5849/utils.pyi | 18 + stubs/oauthlib/oauthlib/oauth2/__init__.pyi | 65 + .../oauthlib/oauth2/rfc6749/__init__.pyi | 11 + .../oauth2/rfc6749/clients/__init__.pyi | 6 + .../rfc6749/clients/backend_application.pyi | 15 + .../oauthlib/oauth2/rfc6749/clients/base.pyi | 121 + .../rfc6749/clients/legacy_application.pyi | 42 + .../rfc6749/clients/mobile_application.pyi | 18 + .../rfc6749/clients/service_application.pyi | 56 + .../rfc6749/clients/web_application.pyi | 53 + .../oauth2/rfc6749/endpoints/__init__.pyi | 13 + .../rfc6749/endpoints/authorization.pyi | 31 + .../oauth2/rfc6749/endpoints/base.pyi | 27 + .../oauth2/rfc6749/endpoints/introspect.pyi | 20 + .../oauth2/rfc6749/endpoints/metadata.pyi | 27 + .../rfc6749/endpoints/pre_configured.pyi | 83 + .../oauth2/rfc6749/endpoints/resource.pyi | 26 + .../oauth2/rfc6749/endpoints/revocation.pyi | 26 + .../oauth2/rfc6749/endpoints/token.pyi | 32 + .../oauthlib/oauth2/rfc6749/errors.pyi | 150 + .../oauth2/rfc6749/grant_types/__init__.pyi | 5 + .../grant_types/authorization_code.pyi | 24 + .../oauth2/rfc6749/grant_types/base.pyi | 67 + .../grant_types/client_credentials.pyi | 12 + .../oauth2/rfc6749/grant_types/implicit.pyi | 19 + .../rfc6749/grant_types/refresh_token.pyi | 25 + .../resource_owner_password_credentials.pyi | 12 + .../oauthlib/oauth2/rfc6749/parameters.pyi | 47 + .../oauth2/rfc6749/request_validator.pyi | 62 + .../oauthlib/oauth2/rfc6749/tokens.pyi | 69 + .../oauthlib/oauth2/rfc6749/utils.pyi | 18 + .../oauthlib/oauth2/rfc8628/__init__.pyi | 9 + .../oauth2/rfc8628/clients/__init__.pyi | 1 + .../oauth2/rfc8628/clients/device.pyi | 40 + .../oauth2/rfc8628/endpoints/__init__.pyi | 2 + .../endpoints/device_authorization.pyi | 32 + .../rfc8628/endpoints/pre_configured.pyi | 16 + .../oauthlib/oauth2/rfc8628/errors.pyi | 13 + .../oauth2/rfc8628/grant_types/__init__.pyi | 1 + .../rfc8628/grant_types/device_code.pyi | 8 + .../oauth2/rfc8628/request_validator.pyi | 5 + stubs/oauthlib/oauthlib/openid/__init__.pyi | 2 + .../oauthlib/openid/connect/__init__.pyi | 0 .../oauthlib/openid/connect/core/__init__.pyi | 0 .../connect/core/endpoints/__init__.pyi | 2 + .../connect/core/endpoints/pre_configured.pyi | 54 + .../connect/core/endpoints/userinfo.pyi | 22 + .../openid/connect/core/exceptions.pyi | 51 + .../connect/core/grant_types/__init__.pyi | 10 + .../core/grant_types/authorization_code.pyi | 25 + .../openid/connect/core/grant_types/base.pyi | 19 + .../connect/core/grant_types/dispatchers.pyi | 32 + .../connect/core/grant_types/hybrid.pyi | 29 + .../connect/core/grant_types/implicit.pyi | 26 + .../core/grant_types/refresh_token.pyi | 25 + .../openid/connect/core/request_validator.pyi | 24 + .../oauthlib/openid/connect/core/tokens.pyi | 23 + stubs/oauthlib/oauthlib/signals.pyi | 20 + stubs/oauthlib/oauthlib/uri_validate.pyi | 44 + stubs/objgraph/METADATA.toml | 2 + stubs/objgraph/objgraph.pyi | 90 + stubs/olefile/@tests/stubtest_allowlist.txt | 1 + stubs/olefile/METADATA.toml | 2 + stubs/olefile/olefile/__init__.pyi | 2 + stubs/olefile/olefile/olefile.pyi | 247 + stubs/openpyxl/@tests/stubtest_allowlist.txt | 183 + .../test_cases/check_base_descriptors.py | 392 + .../test_cases/check_nested_descriptors.py | 458 ++ stubs/openpyxl/METADATA.toml | 2 + stubs/openpyxl/openpyxl/__init__.pyi | 31 + stubs/openpyxl/openpyxl/_constants.pyi | 7 + stubs/openpyxl/openpyxl/cell/__init__.pyi | 27 + stubs/openpyxl/openpyxl/cell/_writer.pyi | 9 + stubs/openpyxl/openpyxl/cell/cell.pyi | 109 + stubs/openpyxl/openpyxl/cell/read_only.pyi | 73 + stubs/openpyxl/openpyxl/cell/rich_text.pyi | 30 + stubs/openpyxl/openpyxl/cell/text.pyi | 97 + stubs/openpyxl/openpyxl/chart/_3d.pyi | 66 + stubs/openpyxl/openpyxl/chart/__init__.pyi | 15 + stubs/openpyxl/openpyxl/chart/_chart.pyi | 50 + stubs/openpyxl/openpyxl/chart/area_chart.pyi | 59 + stubs/openpyxl/openpyxl/chart/axis.pyi | 312 + stubs/openpyxl/openpyxl/chart/bar_chart.pyi | 86 + .../openpyxl/openpyxl/chart/bubble_chart.pyi | 40 + stubs/openpyxl/openpyxl/chart/chartspace.pyi | 147 + stubs/openpyxl/openpyxl/chart/data_source.pyi | 122 + stubs/openpyxl/openpyxl/chart/descriptors.pyi | 21 + stubs/openpyxl/openpyxl/chart/error_bar.pyi | 44 + stubs/openpyxl/openpyxl/chart/label.pyi | 91 + stubs/openpyxl/openpyxl/chart/layout.pyi | 48 + stubs/openpyxl/openpyxl/chart/legend.pyi | 53 + stubs/openpyxl/openpyxl/chart/line_chart.pyi | 86 + stubs/openpyxl/openpyxl/chart/marker.pyi | 55 + stubs/openpyxl/openpyxl/chart/picture.pyi | 27 + stubs/openpyxl/openpyxl/chart/pie_chart.pyi | 104 + stubs/openpyxl/openpyxl/chart/pivot.pyi | 51 + stubs/openpyxl/openpyxl/chart/plotarea.pyi | 77 + .../openpyxl/chart/print_settings.pyi | 42 + stubs/openpyxl/openpyxl/chart/radar_chart.pyi | 35 + stubs/openpyxl/openpyxl/chart/reader.pyi | 1 + stubs/openpyxl/openpyxl/chart/reference.pyi | 52 + .../openpyxl/openpyxl/chart/scatter_chart.pyi | 34 + stubs/openpyxl/openpyxl/chart/series.pyi | 106 + .../openpyxl/chart/series_factory.pyi | 9 + stubs/openpyxl/openpyxl/chart/shapes.pyi | 50 + stubs/openpyxl/openpyxl/chart/stock_chart.pyi | 33 + .../openpyxl/openpyxl/chart/surface_chart.pyi | 65 + stubs/openpyxl/openpyxl/chart/text.pyi | 26 + stubs/openpyxl/openpyxl/chart/title.pyi | 42 + stubs/openpyxl/openpyxl/chart/trendline.pyi | 67 + stubs/openpyxl/openpyxl/chart/updown_bars.pyi | 18 + .../openpyxl/openpyxl/chartsheet/__init__.pyi | 1 + .../openpyxl/chartsheet/chartsheet.pyi | 59 + stubs/openpyxl/openpyxl/chartsheet/custom.pyi | 49 + .../openpyxl/chartsheet/properties.pyi | 15 + .../openpyxl/chartsheet/protection.pyi | 27 + .../openpyxl/openpyxl/chartsheet/publish.pyi | 53 + .../openpyxl/openpyxl/chartsheet/relation.pyi | 71 + stubs/openpyxl/openpyxl/chartsheet/views.pyi | 30 + stubs/openpyxl/openpyxl/comments/__init__.pyi | 1 + stubs/openpyxl/openpyxl/comments/author.pyi | 11 + .../openpyxl/comments/comment_sheet.pyi | 124 + stubs/openpyxl/openpyxl/comments/comments.pyi | 20 + .../openpyxl/comments/shape_writer.pyi | 20 + stubs/openpyxl/openpyxl/compat/__init__.pyi | 10 + stubs/openpyxl/openpyxl/compat/abc.pyi | 1 + stubs/openpyxl/openpyxl/compat/numbers.pyi | 13 + stubs/openpyxl/openpyxl/compat/product.pyi | 3 + stubs/openpyxl/openpyxl/compat/singleton.pyi | 17 + stubs/openpyxl/openpyxl/compat/strings.pyi | 6 + .../openpyxl/descriptors/__init__.pyi | 12 + stubs/openpyxl/openpyxl/descriptors/base.pyi | 370 + .../openpyxl/descriptors/container.pyi | 18 + stubs/openpyxl/openpyxl/descriptors/excel.pyi | 48 + .../openpyxl/descriptors/namespace.pyi | 2 + .../openpyxl/openpyxl/descriptors/nested.pyi | 289 + .../openpyxl/descriptors/sequence.pyi | 76 + .../openpyxl/descriptors/serialisable.pyi | 54 + stubs/openpyxl/openpyxl/descriptors/slots.pyi | 4 + stubs/openpyxl/openpyxl/drawing/__init__.pyi | 1 + stubs/openpyxl/openpyxl/drawing/colors.pyi | 510 ++ stubs/openpyxl/openpyxl/drawing/connector.pyi | 99 + stubs/openpyxl/openpyxl/drawing/drawing.pyi | 31 + stubs/openpyxl/openpyxl/drawing/effect.pyi | 255 + stubs/openpyxl/openpyxl/drawing/fill.pyi | 314 + stubs/openpyxl/openpyxl/drawing/geometry.pyi | 577 ++ stubs/openpyxl/openpyxl/drawing/graphic.pyi | 83 + stubs/openpyxl/openpyxl/drawing/image.pyi | 23 + stubs/openpyxl/openpyxl/drawing/line.pyi | 88 + stubs/openpyxl/openpyxl/drawing/picture.pyi | 79 + .../openpyxl/openpyxl/drawing/properties.pyi | 120 + stubs/openpyxl/openpyxl/drawing/relation.pyi | 10 + .../openpyxl/drawing/spreadsheet_drawing.pyi | 120 + stubs/openpyxl/openpyxl/drawing/text.pyi | 515 ++ stubs/openpyxl/openpyxl/drawing/xdr.pyi | 26 + .../openpyxl/openpyxl/formatting/__init__.pyi | 1 + .../openpyxl/formatting/formatting.pyi | 32 + stubs/openpyxl/openpyxl/formatting/rule.pyi | 202 + stubs/openpyxl/openpyxl/formula/__init__.pyi | 1 + stubs/openpyxl/openpyxl/formula/tokenizer.pyi | 62 + stubs/openpyxl/openpyxl/formula/translate.pyi | 22 + .../openpyxl/openpyxl/packaging/__init__.pyi | 0 stubs/openpyxl/openpyxl/packaging/core.pyi | 61 + stubs/openpyxl/openpyxl/packaging/custom.pyi | 66 + .../openpyxl/openpyxl/packaging/extended.pyi | 81 + .../openpyxl/openpyxl/packaging/interface.pyi | 8 + .../openpyxl/openpyxl/packaging/manifest.pyi | 41 + .../openpyxl/packaging/relationship.pyi | 57 + .../openpyxl/openpyxl/packaging/workbook.pyi | 100 + stubs/openpyxl/openpyxl/pivot/__init__.pyi | 0 stubs/openpyxl/openpyxl/pivot/cache.pyi | 649 ++ stubs/openpyxl/openpyxl/pivot/fields.pyi | 245 + stubs/openpyxl/openpyxl/pivot/record.pyi | 33 + stubs/openpyxl/openpyxl/pivot/table.pyi | 966 +++ stubs/openpyxl/openpyxl/reader/__init__.pyi | 0 stubs/openpyxl/openpyxl/reader/drawings.pyi | 6 + stubs/openpyxl/openpyxl/reader/excel.pyi | 53 + stubs/openpyxl/openpyxl/reader/strings.pyi | 6 + stubs/openpyxl/openpyxl/reader/workbook.pyi | 24 + stubs/openpyxl/openpyxl/styles/__init__.pyi | 8 + stubs/openpyxl/openpyxl/styles/alignment.pyi | 46 + stubs/openpyxl/openpyxl/styles/borders.pyi | 82 + stubs/openpyxl/openpyxl/styles/builtins.pyi | 53 + stubs/openpyxl/openpyxl/styles/cell_style.pyi | 98 + stubs/openpyxl/openpyxl/styles/colors.pyi | 95 + .../openpyxl/openpyxl/styles/differential.pyi | 42 + stubs/openpyxl/openpyxl/styles/fills.pyi | 117 + stubs/openpyxl/openpyxl/styles/fonts.pyi | 77 + .../openpyxl/openpyxl/styles/named_styles.pyi | 83 + stubs/openpyxl/openpyxl/styles/numbers.pyi | 86 + stubs/openpyxl/openpyxl/styles/protection.pyi | 10 + stubs/openpyxl/openpyxl/styles/proxy.pyi | 13 + stubs/openpyxl/openpyxl/styles/styleable.pyi | 54 + stubs/openpyxl/openpyxl/styles/stylesheet.pyi | 59 + stubs/openpyxl/openpyxl/styles/table.pyi | 79 + stubs/openpyxl/openpyxl/utils/__init__.pyi | 13 + .../openpyxl/utils/bound_dictionary.pyi | 9 + stubs/openpyxl/openpyxl/utils/cell.pyi | 26 + stubs/openpyxl/openpyxl/utils/dataframe.pyi | 5 + stubs/openpyxl/openpyxl/utils/datetime.pyi | 21 + stubs/openpyxl/openpyxl/utils/escape.pyi | 2 + stubs/openpyxl/openpyxl/utils/exceptions.pyi | 7 + stubs/openpyxl/openpyxl/utils/formulas.pyi | 5 + .../openpyxl/openpyxl/utils/indexed_list.pyi | 12 + stubs/openpyxl/openpyxl/utils/inference.pyi | 10 + stubs/openpyxl/openpyxl/utils/protection.pyi | 1 + stubs/openpyxl/openpyxl/utils/units.pyi | 24 + stubs/openpyxl/openpyxl/workbook/__init__.pyi | 1 + stubs/openpyxl/openpyxl/workbook/_writer.pyi | 20 + stubs/openpyxl/openpyxl/workbook/child.pyi | 57 + .../openpyxl/workbook/defined_name.pyi | 71 + .../workbook/external_link/__init__.pyi | 1 + .../workbook/external_link/external.pyi | 80 + .../openpyxl/workbook/external_reference.pyi | 9 + .../openpyxl/workbook/function_group.pyi | 17 + .../openpyxl/openpyxl/workbook/properties.pyi | 102 + .../openpyxl/openpyxl/workbook/protection.pyi | 97 + .../openpyxl/openpyxl/workbook/smart_tags.pyi | 28 + stubs/openpyxl/openpyxl/workbook/views.pyi | 134 + stubs/openpyxl/openpyxl/workbook/web.pyi | 84 + stubs/openpyxl/openpyxl/workbook/workbook.pyi | 126 + .../openpyxl/openpyxl/worksheet/__init__.pyi | 0 .../openpyxl/worksheet/_read_only.pyi | 40 + stubs/openpyxl/openpyxl/worksheet/_reader.pyi | 117 + .../openpyxl/worksheet/_write_only.pyi | 50 + stubs/openpyxl/openpyxl/worksheet/_writer.pyi | 58 + .../openpyxl/worksheet/cell_range.pyi | 105 + .../openpyxl/worksheet/cell_watch.pyi | 16 + .../openpyxl/openpyxl/worksheet/controls.pyi | 65 + stubs/openpyxl/openpyxl/worksheet/copier.pyi | 7 + stubs/openpyxl/openpyxl/worksheet/custom.pyi | 16 + .../openpyxl/worksheet/datavalidation.pyi | 109 + .../openpyxl/worksheet/dimensions.pyi | 149 + stubs/openpyxl/openpyxl/worksheet/drawing.pyi | 9 + stubs/openpyxl/openpyxl/worksheet/errors.pyi | 49 + stubs/openpyxl/openpyxl/worksheet/filters.pyi | 317 + stubs/openpyxl/openpyxl/worksheet/formula.pyi | 37 + .../openpyxl/worksheet/header_footer.pyi | 73 + .../openpyxl/openpyxl/worksheet/hyperlink.pyi | 30 + stubs/openpyxl/openpyxl/worksheet/merge.pyi | 37 + stubs/openpyxl/openpyxl/worksheet/ole.pyi | 116 + stubs/openpyxl/openpyxl/worksheet/page.pyi | 108 + .../openpyxl/openpyxl/worksheet/pagebreak.pyi | 48 + stubs/openpyxl/openpyxl/worksheet/picture.pyi | 6 + .../openpyxl/worksheet/print_settings.pyi | 55 + .../openpyxl/worksheet/properties.pyi | 56 + .../openpyxl/worksheet/protection.pyi | 79 + stubs/openpyxl/openpyxl/worksheet/related.pyi | 9 + .../openpyxl/openpyxl/worksheet/scenario.pyi | 89 + .../openpyxl/openpyxl/worksheet/smart_tag.pyi | 50 + stubs/openpyxl/openpyxl/worksheet/table.pyi | 225 + stubs/openpyxl/openpyxl/worksheet/views.pyi | 98 + .../openpyxl/openpyxl/worksheet/worksheet.pyi | 289 + stubs/openpyxl/openpyxl/writer/__init__.pyi | 0 stubs/openpyxl/openpyxl/writer/excel.pyi | 18 + stubs/openpyxl/openpyxl/writer/theme.pyi | 3 + stubs/openpyxl/openpyxl/xml/__init__.pyi | 11 + .../openpyxl/xml/_functions_overloads.pyi | 146 + stubs/openpyxl/openpyxl/xml/constants.pyi | 91 + stubs/openpyxl/openpyxl/xml/functions.pyi | 28 + .../opentracing/@tests/stubtest_allowlist.txt | 5 + stubs/opentracing/METADATA.toml | 2 + stubs/opentracing/opentracing/__init__.pyi | 24 + .../opentracing/opentracing/ext/__init__.pyi | 0 stubs/opentracing/opentracing/ext/tags.pyi | 1 + .../opentracing/harness/__init__.pyi | 0 .../opentracing/harness/api_check.pyi | 34 + .../opentracing/harness/scope_check.pyi | 15 + stubs/opentracing/opentracing/logs.pyi | 7 + .../opentracing/mocktracer/__init__.pyi | 2 + .../mocktracer/binary_propagator.pyi | 8 + .../opentracing/mocktracer/context.pyi | 13 + .../opentracing/mocktracer/propagator.pyi | 7 + .../opentracing/mocktracer/span.pyi | 38 + .../mocktracer/text_propagator.pyi | 14 + .../opentracing/mocktracer/tracer.pyi | 26 + stubs/opentracing/opentracing/propagation.pyi | 10 + stubs/opentracing/opentracing/scope.pyi | 17 + .../opentracing/opentracing/scope_manager.pyi | 8 + .../opentracing/scope_managers/__init__.pyi | 9 + .../opentracing/scope_managers/asyncio.pyi | 8 + .../opentracing/scope_managers/constants.pyi | 1 + .../scope_managers/contextvars.pyi | 10 + .../opentracing/scope_managers/gevent.pyi | 8 + .../opentracing/scope_managers/tornado.pyi | 16 + stubs/opentracing/opentracing/span.pyi | 29 + stubs/opentracing/opentracing/tags.pyi | 23 + stubs/opentracing/opentracing/tracer.pyi | 47 + .../@tests/stubtest_allowlist_darwin.txt | 3 + .../@tests/stubtest_allowlist_linux.txt | 3 + .../@tests/stubtest_allowlist_win32.txt | 2 + stubs/paramiko/METADATA.toml | 8 + stubs/paramiko/paramiko/__init__.pyi | 47 + stubs/paramiko/paramiko/_winapi.pyi | 105 + stubs/paramiko/paramiko/agent.pyi | 98 + stubs/paramiko/paramiko/auth_handler.pyi | 43 + stubs/paramiko/paramiko/auth_strategy.pyi | 57 + stubs/paramiko/paramiko/ber.pyi | 18 + stubs/paramiko/paramiko/buffered_pipe.pyi | 14 + stubs/paramiko/paramiko/channel.pyi | 101 + stubs/paramiko/paramiko/client.pyi | 86 + stubs/paramiko/paramiko/common.pyi | 133 + stubs/paramiko/paramiko/compress.pyi | 12 + stubs/paramiko/paramiko/config.pyi | 34 + stubs/paramiko/paramiko/ecdsakey.pyi | 57 + stubs/paramiko/paramiko/ed25519key.pyi | 30 + stubs/paramiko/paramiko/file.pyi | 39 + stubs/paramiko/paramiko/hostkeys.pyi | 49 + stubs/paramiko/paramiko/kex_curve25519.pyi | 20 + stubs/paramiko/paramiko/kex_ecdh_nist.pyi | 32 + stubs/paramiko/paramiko/kex_gex.pyi | 33 + stubs/paramiko/paramiko/kex_group14.pyi | 28 + stubs/paramiko/paramiko/kex_group16.pyi | 3 + stubs/paramiko/paramiko/message.pyi | 42 + stubs/paramiko/paramiko/packet.pyi | 69 + stubs/paramiko/paramiko/pipe.pyi | 37 + stubs/paramiko/paramiko/pkey.pyi | 87 + stubs/paramiko/paramiko/primes.pyi | 8 + stubs/paramiko/paramiko/proxy.pyi | 19 + stubs/paramiko/paramiko/rsakey.pyi | 40 + stubs/paramiko/paramiko/server.pyi | 47 + stubs/paramiko/paramiko/sftp.pyi | 61 + stubs/paramiko/paramiko/sftp_attr.pyi | 22 + stubs/paramiko/paramiko/sftp_client.pyi | 73 + stubs/paramiko/paramiko/sftp_file.pyi | 33 + stubs/paramiko/paramiko/sftp_handle.pyi | 12 + stubs/paramiko/paramiko/sftp_server.pyi | 35 + stubs/paramiko/paramiko/sftp_si.pyi | 23 + stubs/paramiko/paramiko/ssh_exception.pyi | 47 + stubs/paramiko/paramiko/transport.pyi | 201 + stubs/paramiko/paramiko/util.pyi | 45 + stubs/paramiko/paramiko/win_openssh.pyi | 12 + stubs/paramiko/paramiko/win_pageant.pyi | 21 + .../@tests/stubtest_allowlist.txt | 5 + stubs/parsimonious/METADATA.toml | 2 + stubs/parsimonious/parsimonious/__init__.pyi | 8 + .../parsimonious/parsimonious/exceptions.pyi | 27 + .../parsimonious/parsimonious/expressions.pyi | 82 + stubs/parsimonious/parsimonious/grammar.pyi | 61 + stubs/parsimonious/parsimonious/nodes.pyi | 48 + stubs/parsimonious/parsimonious/utils.pyi | 11 + stubs/passpy/@tests/stubtest_allowlist.txt | 6 + stubs/passpy/METADATA.toml | 2 + stubs/passpy/passpy/__init__.pyi | 5 + stubs/passpy/passpy/exceptions.pyi | 2 + stubs/passpy/passpy/store.pyi | 31 + stubs/passpy/passpy/util.pyi | 13 + stubs/peewee/@tests/stubtest_allowlist.txt | 43 + .../peewee/@tests/test_cases/check_fields.py | 56 + stubs/peewee/METADATA.toml | 10 + stubs/peewee/peewee.pyi | 2179 +++++ stubs/peewee/playhouse/__init__.pyi | 0 stubs/peewee/playhouse/flask_utils.pyi | 27 + stubs/pep8-naming/METADATA.toml | 2 + stubs/pep8-naming/pep8ext_naming.pyi | 163 + stubs/pexpect/@tests/stubtest_allowlist.txt | 2 + stubs/pexpect/METADATA.toml | 2 + stubs/pexpect/pexpect/ANSI.pyi | 43 + stubs/pexpect/pexpect/FSM.pyi | 35 + stubs/pexpect/pexpect/__init__.pyi | 20 + stubs/pexpect/pexpect/_async.pyi | 19 + stubs/pexpect/pexpect/exceptions.pyi | 6 + stubs/pexpect/pexpect/expect.pyi | 38 + stubs/pexpect/pexpect/fdpexpect.pyi | 36 + stubs/pexpect/pexpect/popen_spawn.pyi | 33 + stubs/pexpect/pexpect/pty_spawn.pyi | 96 + stubs/pexpect/pexpect/pxssh.pyi | 66 + stubs/pexpect/pexpect/replwrap.pyi | 27 + stubs/pexpect/pexpect/run.pyi | 28 + stubs/pexpect/pexpect/screen.pyi | 80 + stubs/pexpect/pexpect/socket_pexpect.pyi | 35 + stubs/pexpect/pexpect/spawnbase.pyi | 152 + stubs/pexpect/pexpect/utils.pyi | 10 + stubs/pika/@tests/stubtest_allowlist.txt | 43 + stubs/pika/METADATA.toml | 7 + stubs/pika/pika/__init__.pyi | 29 + stubs/pika/pika/adapters/__init__.pyi | 6 + .../pika/pika/adapters/asyncio_connection.pyi | 77 + stubs/pika/pika/adapters/base_connection.pyi | 112 + .../pika/adapters/blocking_connection.pyi | 286 + .../pika/pika/adapters/gevent_connection.pyi | 93 + .../pika/pika/adapters/select_connection.pyi | 118 + .../pika/pika/adapters/tornado_connection.pyi | 33 + .../pika/pika/adapters/twisted_connection.pyi | 169 + stubs/pika/pika/adapters/utils/__init__.pyi | 0 .../adapters/utils/connection_workflow.pyi | 61 + .../pika/adapters/utils/io_services_utils.pyi | 89 + .../pika/adapters/utils/nbio_interface.pyi | 85 + .../utils/selector_ioloop_adapter.pyi | 111 + stubs/pika/pika/amqp_object.pyi | 20 + stubs/pika/pika/callback.pyi | 54 + stubs/pika/pika/channel.pyi | 165 + stubs/pika/pika/compat.pyi | 35 + stubs/pika/pika/connection.pyi | 231 + stubs/pika/pika/credentials.pyi | 37 + stubs/pika/pika/data.pyi | 14 + stubs/pika/pika/delivery_mode.pyi | 5 + stubs/pika/pika/diagnostic_utils.pyi | 7 + stubs/pika/pika/exceptions.pyi | 62 + stubs/pika/pika/exchange_type.pyi | 19 + stubs/pika/pika/frame.pyi | 47 + stubs/pika/pika/heartbeat.pyi | 14 + stubs/pika/pika/spec.pyi | 908 ++ stubs/pika/pika/tcp_socket_opts.pyi | 9 + stubs/pika/pika/validators.pyi | 15 + stubs/polib/METADATA.toml | 2 + stubs/polib/polib.pyi | 172 + stubs/pony/@tests/stubtest_allowlist.txt | 14 + stubs/pony/METADATA.toml | 3 + stubs/pony/pony/__init__.pyi | 13 + stubs/pony/pony/converting.pyi | 48 + stubs/pony/pony/flask/__init__.pyi | 18 + stubs/pony/pony/flask/example/__init__.pyi | 0 stubs/pony/pony/flask/example/app.pyi | 8 + stubs/pony/pony/flask/example/config.pyi | 1 + stubs/pony/pony/flask/example/models.pyi | 10 + stubs/pony/pony/flask/example/views.pyi | 4 + stubs/pony/pony/options.pyi | 39 + stubs/pony/pony/orm/__init__.pyi | 1 + stubs/pony/pony/orm/asttranslation.pyi | 139 + stubs/pony/pony/orm/core.pyi | 917 +++ stubs/pony/pony/orm/dbapiprovider.pyi | 216 + stubs/pony/pony/orm/dbproviders/__init__.pyi | 0 stubs/pony/pony/orm/dbproviders/cockroach.pyi | 49 + stubs/pony/pony/orm/dbproviders/mysql.pyi | 102 + stubs/pony/pony/orm/dbproviders/oracle.pyi | 159 + stubs/pony/pony/orm/dbproviders/postgres.pyi | 106 + stubs/pony/pony/orm/dbproviders/sqlite.pyi | 221 + stubs/pony/pony/orm/dbschema.pyi | 86 + stubs/pony/pony/orm/decompiling.pyi | 135 + stubs/pony/pony/orm/examples/__init__.pyi | 0 .../pony/pony/orm/examples/alessandro_bug.pyi | 51 + .../pony/pony/orm/examples/bottle_example.pyi | 6 + stubs/pony/pony/orm/examples/bug_ben.pyi | 19 + .../pony/pony/orm/examples/compositekeys.pyi | 89 + stubs/pony/pony/orm/examples/demo.pyi | 34 + stubs/pony/pony/orm/examples/estore.pyi | 64 + stubs/pony/pony/orm/examples/inheritance1.pyi | 46 + stubs/pony/pony/orm/examples/numbers.pyi | 21 + stubs/pony/pony/orm/examples/session01.pyi | 15 + stubs/pony/pony/orm/examples/university1.pyi | 47 + stubs/pony/pony/orm/examples/university2.pyi | 99 + stubs/pony/pony/orm/integration/__init__.pyi | 0 .../pony/orm/integration/bottle_plugin.pyi | 6 + stubs/pony/pony/orm/ormtypes.pyi | 156 + stubs/pony/pony/orm/serialization.pyi | 32 + stubs/pony/pony/orm/sqlbuilding.pyi | 159 + stubs/pony/pony/orm/sqlsymbols.pyi | 88 + stubs/pony/pony/orm/sqltranslation.pyi | 773 ++ stubs/pony/pony/py23compat.pyi | 13 + stubs/pony/pony/thirdparty/__init__.pyi | 0 stubs/pony/pony/thirdparty/decorator.pyi | 31 + stubs/pony/pony/utils/__init__.pyi | 2 + stubs/pony/pony/utils/properties.pyi | 16 + stubs/pony/pony/utils/utils.pyi | 90 + stubs/portpicker/METADATA.toml | 2 + stubs/portpicker/portpicker.pyi | 21 + stubs/protobuf/@tests/stubtest_allowlist.txt | 34 + .../@tests/test_cases/check_struct.py | 17 + stubs/protobuf/METADATA.toml | 9 + stubs/protobuf/google/_upb/_message.pyi | 334 + stubs/protobuf/google/protobuf/__init__.pyi | 3 + stubs/protobuf/google/protobuf/any.pyi | 13 + stubs/protobuf/google/protobuf/any_pb2.pyi | 172 + stubs/protobuf/google/protobuf/api_pb2.pyi | 336 + .../google/protobuf/compiler/__init__.pyi | 0 .../google/protobuf/compiler/plugin_pb2.pyi | 362 + stubs/protobuf/google/protobuf/descriptor.pyi | 382 + .../google/protobuf/descriptor_database.pyi | 16 + .../google/protobuf/descriptor_pb2.pyi | 2959 +++++++ .../google/protobuf/descriptor_pool.pyi | 36 + stubs/protobuf/google/protobuf/duration.pyi | 16 + .../protobuf/google/protobuf/duration_pb2.pyi | 126 + stubs/protobuf/google/protobuf/empty_pb2.pyi | 57 + .../google/protobuf/field_mask_pb2.pyi | 259 + .../google/protobuf/internal/__init__.pyi | 0 .../protobuf/internal/api_implementation.pyi | 2 + .../google/protobuf/internal/builder.pyi | 9 + .../google/protobuf/internal/containers.pyi | 149 + .../google/protobuf/internal/decoder.pyi | 67 + .../google/protobuf/internal/encoder.pyi | 53 + .../protobuf/internal/enum_type_wrapper.pyi | 23 + .../protobuf/internal/extension_dict.pyi | 28 + .../google/protobuf/internal/field_mask.pyi | 14 + .../protobuf/internal/message_listener.pyi | 5 + .../internal/python_edition_defaults.pyi | 0 .../protobuf/internal/python_message.pyi | 5 + .../protobuf/internal/testing_refleaks.pyi | 21 + .../protobuf/internal/type_checkers.pyi | 55 + .../protobuf/internal/well_known_types.pyi | 106 + .../google/protobuf/internal/wire_format.pyi | 50 + .../protobuf/google/protobuf/json_format.pyi | 43 + stubs/protobuf/google/protobuf/message.pyi | 49 + .../google/protobuf/message_factory.pyi | 15 + stubs/protobuf/google/protobuf/proto.pyi | 14 + .../google/protobuf/proto_builder.pyi | 8 + stubs/protobuf/google/protobuf/proto_json.pyi | 21 + stubs/protobuf/google/protobuf/proto_text.pyi | 31 + stubs/protobuf/google/protobuf/reflection.pyi | 10 + .../google/protobuf/runtime_version.pyi | 23 + .../google/protobuf/service_reflection.pyi | 7 + .../google/protobuf/source_context_pb2.pyi | 59 + stubs/protobuf/google/protobuf/struct_pb2.pyi | 215 + .../google/protobuf/symbol_database.pyi | 17 + .../google/protobuf/text_encoding.pyi | 2 + .../protobuf/google/protobuf/text_format.pyi | 207 + stubs/protobuf/google/protobuf/timestamp.pyi | 16 + .../google/protobuf/timestamp_pb2.pyi | 155 + stubs/protobuf/google/protobuf/type_pb2.pyi | 492 ++ .../google/protobuf/unknown_fields.pyi | 9 + .../google/protobuf/util/__init__.pyi | 0 .../protobuf/google/protobuf/wrappers_pb2.pyi | 238 + stubs/psutil/@tests/stubtest_allowlist.txt | 10 + .../@tests/stubtest_allowlist_darwin.txt | 8 + .../@tests/stubtest_allowlist_linux.txt | 4 + .../@tests/stubtest_allowlist_win32.txt | 4 + .../@tests/test_cases/check_process_iter.py | 16 + stubs/psutil/METADATA.toml | 5 + stubs/psutil/psutil/__init__.pyi | 343 + stubs/psutil/psutil/_common.pyi | 253 + stubs/psutil/psutil/_ntuples.pyi | 384 + stubs/psutil/psutil/_psaix.pyi | 112 + stubs/psutil/psutil/_psbsd.pyi | 213 + stubs/psutil/psutil/_pslinux.pyi | 183 + stubs/psutil/psutil/_psosx.pyi | 89 + stubs/psutil/psutil/_psposix.pyi | 85 + stubs/psutil/psutil/_pssunos.pyi | 151 + stubs/psutil/psutil/_psutil_aix.pyi | 58 + stubs/psutil/psutil/_psutil_bsd.pyi | 145 + stubs/psutil/psutil/_psutil_linux.pyi | 49 + stubs/psutil/psutil/_psutil_osx.pyi | 79 + stubs/psutil/psutil/_psutil_sunos.pyi | 63 + stubs/psutil/psutil/_psutil_windows.pyi | 105 + stubs/psutil/psutil/_pswindows.pyi | 179 + stubs/psycopg2/@tests/stubtest_allowlist.txt | 2 + .../@tests/test_cases/check_connect.py | 40 + .../@tests/test_cases/check_extensions.py | 62 + stubs/psycopg2/METADATA.toml | 3 + stubs/psycopg2/psycopg2/__init__.pyi | 59 + stubs/psycopg2/psycopg2/_ipaddress.pyi | 9 + stubs/psycopg2/psycopg2/_json.pyi | 33 + stubs/psycopg2/psycopg2/_psycopg.pyi | 640 ++ stubs/psycopg2/psycopg2/_range.pyi | 86 + stubs/psycopg2/psycopg2/errorcodes.pyi | 312 + stubs/psycopg2/psycopg2/errors.pyi | 269 + stubs/psycopg2/psycopg2/extensions.pyi | 125 + stubs/psycopg2/psycopg2/extras.pyi | 252 + stubs/psycopg2/psycopg2/pool.pyi | 25 + stubs/psycopg2/psycopg2/sql.pyi | 49 + stubs/psycopg2/psycopg2/tz.pyi | 26 + stubs/punq/@tests/stubtest_allowlist.txt | 2 + stubs/punq/METADATA.toml | 2 + stubs/punq/punq/__init__.pyi | 138 + stubs/pyasn1/METADATA.toml | 2 + stubs/pyasn1/pyasn1/__init__.pyi | 3 + stubs/pyasn1/pyasn1/codec/__init__.pyi | 0 stubs/pyasn1/pyasn1/codec/ber/__init__.pyi | 0 stubs/pyasn1/pyasn1/codec/ber/decoder.pyi | 356 + stubs/pyasn1/pyasn1/codec/ber/encoder.pyi | 84 + stubs/pyasn1/pyasn1/codec/ber/eoo.pyi | 11 + stubs/pyasn1/pyasn1/codec/cer/__init__.pyi | 0 stubs/pyasn1/pyasn1/codec/cer/decoder.pyi | 43 + stubs/pyasn1/pyasn1/codec/cer/encoder.pyi | 55 + stubs/pyasn1/pyasn1/codec/der/__init__.pyi | 0 stubs/pyasn1/pyasn1/codec/der/decoder.pyi | 33 + stubs/pyasn1/pyasn1/codec/der/encoder.pyi | 25 + stubs/pyasn1/pyasn1/codec/native/__init__.pyi | 0 stubs/pyasn1/pyasn1/codec/native/decoder.pyi | 42 + stubs/pyasn1/pyasn1/codec/native/encoder.pyi | 71 + stubs/pyasn1/pyasn1/codec/streaming.pyi | 21 + stubs/pyasn1/pyasn1/compat/__init__.pyi | 0 stubs/pyasn1/pyasn1/compat/integer.pyi | 1 + stubs/pyasn1/pyasn1/debug.pyi | 28 + stubs/pyasn1/pyasn1/error.pyi | 15 + stubs/pyasn1/pyasn1/type/__init__.pyi | 0 stubs/pyasn1/pyasn1/type/base.pyi | 151 + stubs/pyasn1/pyasn1/type/char.pyi | 88 + stubs/pyasn1/pyasn1/type/constraint.pyi | 52 + stubs/pyasn1/pyasn1/type/error.pyi | 3 + stubs/pyasn1/pyasn1/type/namedtype.pyi | 73 + stubs/pyasn1/pyasn1/type/namedval.pyi | 26 + stubs/pyasn1/pyasn1/type/opentype.pyi | 17 + stubs/pyasn1/pyasn1/type/tag.pyi | 64 + stubs/pyasn1/pyasn1/type/tagmap.pyi | 25 + stubs/pyasn1/pyasn1/type/univ.pyi | 398 + stubs/pyasn1/pyasn1/type/useful.pyi | 31 + stubs/pyaudio/METADATA.toml | 9 + stubs/pyaudio/pyaudio.pyi | 178 + stubs/pycocotools/METADATA.toml | 3 + stubs/pycocotools/pycocotools/__init__.pyi | 7 + stubs/pycocotools/pycocotools/coco.pyi | 96 + stubs/pycocotools/pycocotools/cocoeval.pyi | 64 + stubs/pycocotools/pycocotools/mask.pyi | 29 + stubs/pycups/METADATA.toml | 5 + stubs/pycups/cups.pyi | 899 ++ stubs/pycurl/@tests/stubtest_allowlist.txt | 3 + stubs/pycurl/METADATA.toml | 5 + stubs/pycurl/pycurl/__init__.pyi | 2 + stubs/pycurl/pycurl/_pycurl.pyi | 926 +++ stubs/pycurl/pycurl/async_multi.pyi | 22 + stubs/pyfarmhash/METADATA.toml | 2 + stubs/pyfarmhash/farmhash.pyi | 9 + stubs/pyflakes/@tests/stubtest_allowlist.txt | 30 + stubs/pyflakes/METADATA.toml | 2 + stubs/pyflakes/pyflakes/__init__.pyi | 3 + stubs/pyflakes/pyflakes/__main__.pyi | 1 + stubs/pyflakes/pyflakes/api.pyi | 18 + stubs/pyflakes/pyflakes/checker.pyi | 343 + stubs/pyflakes/pyflakes/messages.pyi | 148 + stubs/pyflakes/pyflakes/reporter.pyi | 9 + stubs/pyflakes/pyflakes/scripts/__init__.pyi | 0 stubs/pyflakes/pyflakes/scripts/pyflakes.pyi | 8 + .../pyinstaller/@tests/stubtest_allowlist.txt | 53 + .../@tests/stubtest_allowlist_darwin.txt | 2 + .../@tests/stubtest_allowlist_linux.txt | 2 + .../@tests/stubtest_allowlist_win32.txt | 1 + .../@tests/test_cases/check_versioninfo.py | 63 + stubs/pyinstaller/METADATA.toml | 2 + stubs/pyinstaller/PyInstaller/__init__.pyi | 12 + stubs/pyinstaller/PyInstaller/__main__.pyi | 12 + .../PyInstaller/building/__init__.pyi | 7 + .../pyinstaller/PyInstaller/building/api.pyi | 175 + .../PyInstaller/building/build_main.pyi | 55 + .../PyInstaller/building/datastruct.pyi | 47 + .../PyInstaller/building/splash.pyi | 49 + stubs/pyinstaller/PyInstaller/compat.pyi | 87 + .../PyInstaller/depend/__init__.pyi | 0 .../PyInstaller/depend/analysis.pyi | 27 + .../PyInstaller/depend/imphookapi.pyi | 71 + .../PyInstaller/isolated/__init__.pyi | 2 + .../PyInstaller/isolated/_parent.pyi | 19 + .../pyinstaller/PyInstaller/lib/__init__.pyi | 0 .../PyInstaller/lib/modulegraph/__init__.pyi | 0 .../lib/modulegraph/modulegraph.pyi | 57 + .../PyInstaller/utils/__init__.pyi | 0 .../PyInstaller/utils/hooks/__init__.pyi | 76 + .../PyInstaller/utils/hooks/conda.pyi | 48 + .../PyInstaller/utils/hooks/tcl_tk.pyi | 20 + .../PyInstaller/utils/win32/versioninfo.pyi | 98 + stubs/pyinstaller/pyi_splash/__init__.pyi | 13 + stubs/pyjks/@tests/stubtest_allowlist.txt | 35 + stubs/pyjks/METADATA.toml | 3 + stubs/pyjks/jks/__init__.pyi | 48 + stubs/pyjks/jks/bks.pyi | 125 + stubs/pyjks/jks/jks.pyi | 131 + stubs/pyjks/jks/rfc2898.pyi | 5 + stubs/pyjks/jks/rfc7292.pyi | 28 + stubs/pyjks/jks/sun_crypto.pyi | 8 + stubs/pyjks/jks/util.pyi | 66 + stubs/pyluach/@tests/stubtest_allowlist.txt | 2 + stubs/pyluach/METADATA.toml | 2 + stubs/pyluach/pyluach/__init__.pyi | 3 + stubs/pyluach/pyluach/dates.pyi | 109 + stubs/pyluach/pyluach/hebrewcal.pyi | 147 + stubs/pyluach/pyluach/parshios.pyi | 14 + stubs/pyluach/pyluach/utils.pyi | 32 + stubs/pynput/@tests/stubtest_allowlist.txt | 8 + stubs/pynput/METADATA.toml | 5 + stubs/pynput/pynput/__init__.pyi | 1 + stubs/pynput/pynput/_info.pyi | 2 + stubs/pynput/pynput/_util.pyi | 73 + stubs/pynput/pynput/keyboard/__init__.pyi | 32 + stubs/pynput/pynput/keyboard/_base.pyi | 146 + stubs/pynput/pynput/keyboard/_dummy.pyi | 1 + stubs/pynput/pynput/mouse/__init__.pyi | 32 + stubs/pynput/pynput/mouse/_base.pyi | 118 + stubs/pynput/pynput/mouse/_dummy.pyi | 1 + stubs/pyogrio/@tests/stubtest_allowlist.txt | 2 + stubs/pyogrio/METADATA.toml | 5 + stubs/pyogrio/pyogrio/__init__.pyi | 47 + stubs/pyogrio/pyogrio/_typing.pyi | 28 + stubs/pyogrio/pyogrio/core.pyi | 82 + stubs/pyogrio/pyogrio/errors.pyi | 6 + stubs/pyogrio/pyogrio/geopandas.pyi | 80 + stubs/pyogrio/pyogrio/raw.pyi | 179 + stubs/pyogrio/pyogrio/util.pyi | 11 + stubs/pyperclip/@tests/stubtest_allowlist.txt | 1 + stubs/pyperclip/METADATA.toml | 6 + stubs/pyperclip/pyperclip/__init__.pyi | 23 + stubs/pyphen/METADATA.toml | 2 + stubs/pyphen/pyphen/__init__.pyi | 43 + stubs/pyserial/@tests/stubtest_allowlist.txt | 48 + .../@tests/stubtest_allowlist_darwin.txt | 16 + .../@tests/stubtest_allowlist_linux.txt | 18 + .../@tests/stubtest_allowlist_win32.txt | 16 + stubs/pyserial/METADATA.toml | 6 + stubs/pyserial/serial/__init__.pyi | 30 + stubs/pyserial/serial/__main__.pyi | 1 + stubs/pyserial/serial/rfc2217.pyi | 187 + stubs/pyserial/serial/rs485.pyi | 18 + stubs/pyserial/serial/serialcli.pyi | 25 + stubs/pyserial/serial/serialjava.pyi | 30 + stubs/pyserial/serial/serialposix.pyi | 88 + stubs/pyserial/serial/serialutil.pyi | 169 + stubs/pyserial/serial/serialwin32.pyi | 26 + stubs/pyserial/serial/threaded/__init__.pyi | 51 + stubs/pyserial/serial/tools/__init__.pyi | 0 stubs/pyserial/serial/tools/hexlify_codec.pyi | 23 + stubs/pyserial/serial/tools/list_ports.pyi | 13 + .../serial/tools/list_ports_common.pyi | 33 + .../serial/tools/list_ports_linux.pyi | 11 + .../pyserial/serial/tools/list_ports_osx.pyi | 36 + .../serial/tools/list_ports_posix.pyi | 11 + .../serial/tools/list_ports_windows.pyi | 78 + stubs/pyserial/serial/tools/miniterm.pyi | 122 + stubs/pyserial/serial/urlhandler/__init__.pyi | 0 .../serial/urlhandler/protocol_alt.pyi | 3 + .../serial/urlhandler/protocol_cp2110.pyi | 13 + .../serial/urlhandler/protocol_hwgrep.pyi | 4 + .../serial/urlhandler/protocol_loop.pyi | 32 + .../serial/urlhandler/protocol_rfc2217.pyi | 1 + .../serial/urlhandler/protocol_socket.pyi | 26 + .../serial/urlhandler/protocol_spy.pyi | 35 + stubs/pyserial/serial/win32.pyi | 253 + .../@tests/stubtest_allowlist.txt | 13 + stubs/pytest-lazy-fixture/METADATA.toml | 2 + .../pytest_lazyfixture.pyi | 15 + .../@tests/stubtest_allowlist.txt | 5 + stubs/python-crontab/METADATA.toml | 3 + stubs/python-crontab/cronlog.pyi | 36 + stubs/python-crontab/crontab.pyi | 331 + stubs/python-crontab/crontabs.pyi | 24 + .../@tests/stubtest_allowlist.txt | 7 + .../@tests/stubtest_allowlist_darwin.txt | 3 + .../@tests/stubtest_allowlist_linux.txt | 3 + .../@tests/test_cases/check_inheritance.py | 21 + .../@tests/test_cases/check_relativedelta.py | 9 + .../@tests/test_cases/check_rrule.py | 13 + stubs/python-dateutil/METADATA.toml | 2 + stubs/python-dateutil/dateutil/__init__.pyi | 5 + stubs/python-dateutil/dateutil/_common.pyi | 10 + stubs/python-dateutil/dateutil/_version.pyi | 6 + stubs/python-dateutil/dateutil/easter.pyi | 10 + .../dateutil/parser/__init__.pyi | 12 + .../dateutil/parser/_parser.pyi | 164 + .../dateutil/parser/isoparser.pyi | 17 + .../dateutil/relativedelta.pyi | 97 + stubs/python-dateutil/dateutil/rrule.pyi | 223 + .../python-dateutil/dateutil/tz/__init__.pyi | 68 + stubs/python-dateutil/dateutil/tz/_common.pyi | 33 + stubs/python-dateutil/dateutil/tz/tz.pyi | 139 + stubs/python-dateutil/dateutil/tz/win.pyi | 27 + stubs/python-dateutil/dateutil/tzwin.pyi | 4 + stubs/python-dateutil/dateutil/utils.pyi | 8 + .../dateutil/zoneinfo/__init__.pyi | 46 + .../dateutil/zoneinfo/rebuild.pyi | 12 + .../@tests/stubtest_allowlist.txt | 1 + stubs/python-http-client/METADATA.toml | 2 + .../python_http_client/__init__.pyi | 20 + .../python_http_client/client.pyi | 32 + .../python_http_client/exceptions.pyi | 34 + .../@tests/stubtest_allowlist.txt | 2 + stubs/python-jenkins/METADATA.toml | 3 + stubs/python-jenkins/jenkins/__init__.pyi | 254 + stubs/python-jenkins/jenkins/plugins.pyi | 15 + stubs/python-jenkins/jenkins/version.pyi | 3 + .../python-jose/@tests/stubtest_allowlist.txt | 1 + stubs/python-jose/METADATA.toml | 3 + stubs/python-jose/jose/__init__.pyi | 11 + stubs/python-jose/jose/backends/__init__.pyi | 18 + stubs/python-jose/jose/backends/_asn1.pyi | 17 + stubs/python-jose/jose/backends/base.pyi | 23 + .../jose/backends/cryptography_backend.pyi | 66 + .../jose/backends/ecdsa_backend.pyi | 25 + stubs/python-jose/jose/backends/native.pyi | 21 + .../python-jose/jose/backends/rsa_backend.pyi | 27 + stubs/python-jose/jose/constants.pyi | 75 + stubs/python-jose/jose/exceptions.pyi | 12 + stubs/python-jose/jose/jwe.pyi | 22 + stubs/python-jose/jose/jwk.pyi | 12 + stubs/python-jose/jose/jws.pyi | 24 + stubs/python-jose/jose/jwt.pyi | 29 + stubs/python-jose/jose/utils.pyi | 16 + .../python-nmap/@tests/stubtest_allowlist.txt | 1 + stubs/python-nmap/METADATA.toml | 2 + stubs/python-nmap/nmap/__init__.pyi | 2 + stubs/python-nmap/nmap/nmap.pyi | 142 + .../python-xlib/@tests/stubtest_allowlist.txt | 25 + stubs/python-xlib/METADATA.toml | 2 + stubs/python-xlib/Xlib/X.pyi | 347 + stubs/python-xlib/Xlib/XK.pyi | 7 + stubs/python-xlib/Xlib/Xatom.pyi | 71 + stubs/python-xlib/Xlib/Xcursorfont.pyi | 80 + stubs/python-xlib/Xlib/Xutil.pyi | 59 + stubs/python-xlib/Xlib/__init__.pyi | 14 + stubs/python-xlib/Xlib/_typing.pyi | 8 + stubs/python-xlib/Xlib/display.pyi | 164 + stubs/python-xlib/Xlib/error.pyi | 57 + stubs/python-xlib/Xlib/ext/__init__.pyi | 35 + stubs/python-xlib/Xlib/ext/composite.pyi | 47 + stubs/python-xlib/Xlib/ext/damage.pyi | 41 + stubs/python-xlib/Xlib/ext/dpms.pyi | 48 + stubs/python-xlib/Xlib/ext/ge.pyi | 18 + stubs/python-xlib/Xlib/ext/nvcontrol.pyi | 1065 +++ stubs/python-xlib/Xlib/ext/randr.pyi | 261 + stubs/python-xlib/Xlib/ext/record.pyi | 115 + stubs/python-xlib/Xlib/ext/res.pyi | 62 + stubs/python-xlib/Xlib/ext/screensaver.pyi | 52 + stubs/python-xlib/Xlib/ext/security.pyi | 33 + stubs/python-xlib/Xlib/ext/shape.pyi | 62 + stubs/python-xlib/Xlib/ext/xfixes.pyi | 50 + stubs/python-xlib/Xlib/ext/xinerama.pyi | 37 + stubs/python-xlib/Xlib/ext/xinput.pyi | 249 + stubs/python-xlib/Xlib/ext/xtest.pyi | 28 + stubs/python-xlib/Xlib/keysymdef/__init__.pyi | 43 + stubs/python-xlib/Xlib/keysymdef/apl.pyi | 21 + stubs/python-xlib/Xlib/keysymdef/arabic.pyi | 52 + stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi | 109 + stubs/python-xlib/Xlib/keysymdef/greek.pyi | 76 + stubs/python-xlib/Xlib/keysymdef/hebrew.pyi | 42 + stubs/python-xlib/Xlib/keysymdef/katakana.pyi | 72 + stubs/python-xlib/Xlib/keysymdef/korean.pyi | 109 + stubs/python-xlib/Xlib/keysymdef/latin1.pyi | 197 + stubs/python-xlib/Xlib/keysymdef/latin2.pyi | 59 + stubs/python-xlib/Xlib/keysymdef/latin3.pyi | 24 + stubs/python-xlib/Xlib/keysymdef/latin4.pyi | 38 + .../python-xlib/Xlib/keysymdef/miscellany.pyi | 171 + .../python-xlib/Xlib/keysymdef/publishing.pyi | 85 + stubs/python-xlib/Xlib/keysymdef/special.pyi | 26 + .../python-xlib/Xlib/keysymdef/technical.pyi | 51 + stubs/python-xlib/Xlib/keysymdef/thai.pyi | 86 + stubs/python-xlib/Xlib/keysymdef/xf86.pyi | 186 + stubs/python-xlib/Xlib/keysymdef/xk3270.pyi | 32 + stubs/python-xlib/Xlib/keysymdef/xkb.pyi | 102 + stubs/python-xlib/Xlib/protocol/__init__.pyi | 3 + stubs/python-xlib/Xlib/protocol/display.pyi | 122 + stubs/python-xlib/Xlib/protocol/event.pyi | 82 + stubs/python-xlib/Xlib/protocol/request.pyi | 134 + stubs/python-xlib/Xlib/protocol/rq.pyi | 400 + stubs/python-xlib/Xlib/protocol/structs.pyi | 26 + stubs/python-xlib/Xlib/rdb.pyi | 99 + stubs/python-xlib/Xlib/support/__init__.pyi | 3 + stubs/python-xlib/Xlib/support/connect.pyi | 6 + stubs/python-xlib/Xlib/support/lock.pyi | 8 + .../python-xlib/Xlib/support/unix_connect.pyi | 24 + .../python-xlib/Xlib/support/vms_connect.pyi | 11 + stubs/python-xlib/Xlib/threaded.pyi | 4 + stubs/python-xlib/Xlib/xauth.pyi | 21 + stubs/python-xlib/Xlib/xobject/__init__.pyi | 10 + stubs/python-xlib/Xlib/xobject/colormap.pyi | 25 + stubs/python-xlib/Xlib/xobject/cursor.pyi | 10 + stubs/python-xlib/Xlib/xobject/drawable.pyi | 274 + stubs/python-xlib/Xlib/xobject/fontable.pyi | 33 + stubs/python-xlib/Xlib/xobject/icccm.pyi | 7 + stubs/python-xlib/Xlib/xobject/resource.pyi | 10 + stubs/pytz/@tests/stubtest_allowlist.txt | 3 + stubs/pytz/METADATA.toml | 3 + stubs/pytz/pytz/__init__.pyi | 64 + stubs/pytz/pytz/exceptions.pyi | 7 + stubs/pytz/pytz/lazy.pyi | 20 + stubs/pytz/pytz/reference.pyi | 40 + stubs/pytz/pytz/tzfile.pyi | 5 + stubs/pytz/pytz/tzinfo.pyi | 45 + .../@tests/stubtest_allowlist_win32.txt | 51 + stubs/pywin32/METADATA.toml | 6 + stubs/pywin32/_win32typing.pyi | 6327 ++++++++++++++ stubs/pywin32/commctrl.pyi | 1 + stubs/pywin32/dde.pyi | 1 + stubs/pywin32/isapi/__init__.pyi | 9 + stubs/pywin32/isapi/install.pyi | 101 + stubs/pywin32/isapi/isapicon.pyi | 86 + stubs/pywin32/isapi/simple.pyi | 10 + stubs/pywin32/isapi/threaded_extension.pyi | 29 + stubs/pywin32/mmapfile.pyi | 1 + stubs/pywin32/mmsystem.pyi | 1 + stubs/pywin32/ntsecuritycon.pyi | 1 + stubs/pywin32/odbc.pyi | 1 + stubs/pywin32/perfmon.pyi | 1 + stubs/pywin32/pythoncom.pyi | 500 ++ stubs/pywin32/pythonwin/__init__.pyi | 0 stubs/pywin32/pythonwin/dde.pyi | 33 + stubs/pywin32/pythonwin/win32ui.pyi | 373 + stubs/pywin32/pythonwin/win32uiole.pyi | 27 + stubs/pywin32/pywintypes.pyi | 1 + stubs/pywin32/regutil.pyi | 1 + stubs/pywin32/servicemanager.pyi | 1 + stubs/pywin32/sspicon.pyi | 1 + stubs/pywin32/timer.pyi | 1 + stubs/pywin32/win2kras.pyi | 1 + stubs/pywin32/win32/__init__.pyi | 0 stubs/pywin32/win32/lib/__init__.pyi | 0 stubs/pywin32/win32/lib/commctrl.pyi | 1522 ++++ stubs/pywin32/win32/lib/mmsystem.pyi | 858 ++ stubs/pywin32/win32/lib/ntsecuritycon.pyi | 554 ++ stubs/pywin32/win32/lib/pywintypes.pyi | 51 + stubs/pywin32/win32/lib/regutil.pyi | 26 + stubs/pywin32/win32/lib/sspicon.pyi | 457 ++ stubs/pywin32/win32/lib/win2kras.pyi | 34 + stubs/pywin32/win32/lib/win32con.pyi | 4910 +++++++++++ stubs/pywin32/win32/lib/win32cryptcon.pyi | 1790 ++++ stubs/pywin32/win32/lib/win32evtlogutil.pyi | 25 + stubs/pywin32/win32/lib/win32gui_struct.pyi | 210 + stubs/pywin32/win32/lib/win32inetcon.pyi | 989 +++ stubs/pywin32/win32/lib/win32netcon.pyi | 571 ++ stubs/pywin32/win32/lib/win32pdhquery.pyi | 45 + stubs/pywin32/win32/lib/win32serviceutil.pyi | 81 + stubs/pywin32/win32/lib/win32timezone.pyi | 120 + stubs/pywin32/win32/lib/win32verstamp.pyi | 21 + stubs/pywin32/win32/lib/winerror.pyi | 7270 +++++++++++++++++ stubs/pywin32/win32/lib/winioctlcon.pyi | 661 ++ stubs/pywin32/win32/lib/winnt.pyi | 1134 +++ stubs/pywin32/win32/lib/winperf.pyi | 73 + stubs/pywin32/win32/lib/winxptheme.pyi | 25 + stubs/pywin32/win32/mmapfile.pyi | 6 + stubs/pywin32/win32/odbc.pyi | 32 + stubs/pywin32/win32/perfmon.pyi | 13 + stubs/pywin32/win32/servicemanager.pyi | 34 + stubs/pywin32/win32/timer.pyi | 6 + stubs/pywin32/win32/win32api.pyi | 376 + stubs/pywin32/win32/win32clipboard.pyi | 48 + stubs/pywin32/win32/win32console.pyi | 82 + stubs/pywin32/win32/win32cred.pyi | 91 + stubs/pywin32/win32/win32crypt.pyi | 107 + stubs/pywin32/win32/win32event.pyi | 69 + stubs/pywin32/win32/win32evtlog.pyi | 272 + stubs/pywin32/win32/win32file.pyi | 485 ++ stubs/pywin32/win32/win32gui.pyi | 565 ++ stubs/pywin32/win32/win32help.pyi | 180 + stubs/pywin32/win32/win32inet.pyi | 69 + stubs/pywin32/win32/win32job.pyi | 74 + stubs/pywin32/win32/win32lz.pyi | 9 + stubs/pywin32/win32/win32net.pyi | 94 + stubs/pywin32/win32/win32pdh.pyi | 63 + stubs/pywin32/win32/win32pipe.pyi | 64 + stubs/pywin32/win32/win32print.pyi | 365 + stubs/pywin32/win32/win32process.pyi | 124 + stubs/pywin32/win32/win32profile.pyi | 19 + stubs/pywin32/win32/win32ras.pyi | 56 + stubs/pywin32/win32/win32security.pyi | 606 ++ stubs/pywin32/win32/win32service.pyi | 187 + stubs/pywin32/win32/win32trace.pyi | 13 + stubs/pywin32/win32/win32transaction.pyi | 18 + stubs/pywin32/win32/win32ts.pyi | 97 + stubs/pywin32/win32/win32wnet.pyi | 36 + stubs/pywin32/win32/winxpgui.pyi | 5 + stubs/pywin32/win32api.pyi | 1 + stubs/pywin32/win32clipboard.pyi | 1 + stubs/pywin32/win32com/__init__.pyi | 9 + stubs/pywin32/win32com/adsi/__init__.pyi | 1 + stubs/pywin32/win32com/adsi/adsi.pyi | 1 + stubs/pywin32/win32com/adsi/adsicon.pyi | 1 + .../win32com/authorization/__init__.pyi | 1 + .../win32com/authorization/authorization.pyi | 1 + stubs/pywin32/win32com/axcontrol/__init__.pyi | 1 + .../pywin32/win32com/axcontrol/axcontrol.pyi | 1 + stubs/pywin32/win32com/axdebug/__init__.pyi | 1 + stubs/pywin32/win32com/axdebug/adb.pyi | 1 + stubs/pywin32/win32com/axdebug/axdebug.pyi | 1 + .../win32com/axdebug/codecontainer.pyi | 1 + stubs/pywin32/win32com/axdebug/contexts.pyi | 1 + stubs/pywin32/win32com/axdebug/debugger.pyi | 1 + stubs/pywin32/win32com/axdebug/documents.pyi | 1 + .../pywin32/win32com/axdebug/expressions.pyi | 1 + stubs/pywin32/win32com/axdebug/gateways.pyi | 1 + stubs/pywin32/win32com/axdebug/stackframe.pyi | 1 + stubs/pywin32/win32com/axdebug/util.pyi | 1 + stubs/pywin32/win32com/axscript/__init__.pyi | 1 + stubs/pywin32/win32com/axscript/asputil.pyi | 1 + stubs/pywin32/win32com/axscript/axscript.pyi | 1 + .../win32com/axscript/client/__init__.pyi | 1 + .../win32com/axscript/client/debug.pyi | 1 + .../win32com/axscript/client/error.pyi | 1 + .../win32com/axscript/client/framework.pyi | 1 + .../win32com/axscript/server/__init__.pyi | 1 + .../win32com/axscript/server/axsite.pyi | 1 + stubs/pywin32/win32com/bits/__init__.pyi | 1 + stubs/pywin32/win32com/bits/bits.pyi | 1 + stubs/pywin32/win32com/client/__init__.pyi | 75 + stubs/pywin32/win32com/client/build.pyi | 70 + stubs/pywin32/win32com/client/dynamic.pyi | 69 + stubs/pywin32/win32com/client/gencache.pyi | 64 + .../pywin32/win32com/directsound/__init__.pyi | 1 + .../win32com/directsound/directsound.pyi | 1 + stubs/pywin32/win32com/gen_py/__init__.pyi | 0 stubs/pywin32/win32com/ifilter/__init__.pyi | 1 + stubs/pywin32/win32com/ifilter/ifilter.pyi | 1 + stubs/pywin32/win32com/ifilter/ifiltercon.pyi | 1 + stubs/pywin32/win32com/internet/__init__.pyi | 1 + stubs/pywin32/win32com/internet/inetcon.pyi | 1 + stubs/pywin32/win32com/internet/internet.pyi | 1 + stubs/pywin32/win32com/mapi/__init__.pyi | 1 + stubs/pywin32/win32com/mapi/emsabtags.pyi | 1 + stubs/pywin32/win32com/mapi/exchange.pyi | 1 + stubs/pywin32/win32com/mapi/mapi.pyi | 1 + stubs/pywin32/win32com/mapi/mapitags.pyi | 1 + stubs/pywin32/win32com/mapi/mapiutil.pyi | 1 + stubs/pywin32/win32com/olectl.pyi | 56 + stubs/pywin32/win32com/propsys/__init__.pyi | 1 + stubs/pywin32/win32com/propsys/propsys.pyi | 1 + stubs/pywin32/win32com/propsys/pscon.pyi | 1 + stubs/pywin32/win32com/server/__init__.pyi | 0 stubs/pywin32/win32com/server/connect.pyi | 22 + stubs/pywin32/win32com/server/dispatcher.pyi | 18 + stubs/pywin32/win32com/server/exception.pyi | 21 + stubs/pywin32/win32com/server/factory.pyi | 9 + stubs/pywin32/win32com/server/localserver.pyi | 9 + stubs/pywin32/win32com/server/policy.pyi | 50 + stubs/pywin32/win32com/server/register.pyi | 68 + stubs/pywin32/win32com/server/util.pyi | 49 + stubs/pywin32/win32com/shell/__init__.pyi | 1 + stubs/pywin32/win32com/shell/shell.pyi | 1 + stubs/pywin32/win32com/shell/shellcon.pyi | 1 + stubs/pywin32/win32com/storagecon.pyi | 115 + .../win32com/taskscheduler/__init__.pyi | 1 + .../win32com/taskscheduler/taskscheduler.pyi | 1 + stubs/pywin32/win32com/universal.pyi | 44 + stubs/pywin32/win32com/util.pyi | 1 + stubs/pywin32/win32comext/__init__.pyi | 0 stubs/pywin32/win32comext/adsi/__init__.pyi | 77 + stubs/pywin32/win32comext/adsi/adsi.pyi | 58 + stubs/pywin32/win32comext/adsi/adsicon.pyi | 318 + .../win32comext/authorization/__init__.pyi | 0 .../authorization/authorization.pyi | 5 + .../win32comext/axcontrol/__init__.pyi | 0 .../win32comext/axcontrol/axcontrol.pyi | 61 + .../pywin32/win32comext/axdebug/__init__.pyi | 0 stubs/pywin32/win32comext/axdebug/adb.pyi | 71 + stubs/pywin32/win32comext/axdebug/axdebug.pyi | 122 + .../win32comext/axdebug/codecontainer.pyi | 40 + .../pywin32/win32comext/axdebug/contexts.pyi | 18 + .../pywin32/win32comext/axdebug/debugger.pyi | 56 + .../pywin32/win32comext/axdebug/documents.pyi | 30 + .../win32comext/axdebug/expressions.pyi | 67 + .../pywin32/win32comext/axdebug/gateways.pyi | 114 + .../win32comext/axdebug/stackframe.pyi | 33 + stubs/pywin32/win32comext/axdebug/util.pyi | 11 + .../pywin32/win32comext/axscript/__init__.pyi | 0 .../pywin32/win32comext/axscript/asputil.pyi | 1 + .../pywin32/win32comext/axscript/axscript.pyi | 52 + .../win32comext/axscript/client/__init__.pyi | 0 .../win32comext/axscript/client/debug.pyi | 42 + .../win32comext/axscript/client/error.pyi | 35 + .../win32comext/axscript/client/framework.pyi | 154 + .../win32comext/axscript/server/__init__.pyi | 0 .../win32comext/axscript/server/axsite.pyi | 32 + stubs/pywin32/win32comext/bits/__init__.pyi | 0 stubs/pywin32/win32comext/bits/bits.pyi | 61 + .../win32comext/directsound/__init__.pyi | 0 .../win32comext/directsound/directsound.pyi | 116 + .../pywin32/win32comext/ifilter/__init__.pyi | 0 stubs/pywin32/win32comext/ifilter/ifilter.pyi | 33 + .../win32comext/ifilter/ifiltercon.pyi | 103 + .../pywin32/win32comext/internet/__init__.pyi | 0 .../pywin32/win32comext/internet/inetcon.pyi | 254 + .../pywin32/win32comext/internet/internet.pyi | 51 + stubs/pywin32/win32comext/mapi/__init__.pyi | 0 stubs/pywin32/win32comext/mapi/emsabtags.pyi | 865 ++ stubs/pywin32/win32comext/mapi/exchange.pyi | 9 + stubs/pywin32/win32comext/mapi/mapi.pyi | 342 + stubs/pywin32/win32comext/mapi/mapitags.pyi | 991 +++ stubs/pywin32/win32comext/mapi/mapiutil.pyi | 15 + .../pywin32/win32comext/propsys/__init__.pyi | 0 stubs/pywin32/win32comext/propsys/propsys.pyi | 61 + stubs/pywin32/win32comext/propsys/pscon.pyi | 695 ++ stubs/pywin32/win32comext/shell/__init__.pyi | 0 stubs/pywin32/win32comext/shell/shell.pyi | 447 + stubs/pywin32/win32comext/shell/shellcon.pyi | 1413 ++++ .../win32comext/taskscheduler/__init__.pyi | 0 .../taskscheduler/taskscheduler.pyi | 83 + stubs/pywin32/win32con.pyi | 1 + stubs/pywin32/win32console.pyi | 1 + stubs/pywin32/win32cred.pyi | 1 + stubs/pywin32/win32crypt.pyi | 1 + stubs/pywin32/win32cryptcon.pyi | 1 + stubs/pywin32/win32event.pyi | 1 + stubs/pywin32/win32evtlog.pyi | 1 + stubs/pywin32/win32evtlogutil.pyi | 1 + stubs/pywin32/win32file.pyi | 1 + stubs/pywin32/win32gui.pyi | 1 + stubs/pywin32/win32gui_struct.pyi | 1 + stubs/pywin32/win32help.pyi | 1 + stubs/pywin32/win32inet.pyi | 1 + stubs/pywin32/win32inetcon.pyi | 1 + stubs/pywin32/win32job.pyi | 1 + stubs/pywin32/win32lz.pyi | 1 + stubs/pywin32/win32net.pyi | 1 + stubs/pywin32/win32netcon.pyi | 1 + stubs/pywin32/win32pdh.pyi | 1 + stubs/pywin32/win32pdhquery.pyi | 1 + stubs/pywin32/win32pipe.pyi | 1 + stubs/pywin32/win32print.pyi | 1 + stubs/pywin32/win32process.pyi | 1 + stubs/pywin32/win32profile.pyi | 1 + stubs/pywin32/win32ras.pyi | 1 + stubs/pywin32/win32security.pyi | 1 + stubs/pywin32/win32service.pyi | 1 + stubs/pywin32/win32serviceutil.pyi | 1 + stubs/pywin32/win32timezone.pyi | 1 + stubs/pywin32/win32trace.pyi | 1 + stubs/pywin32/win32transaction.pyi | 1 + stubs/pywin32/win32ts.pyi | 1 + stubs/pywin32/win32ui.pyi | 1 + stubs/pywin32/win32uiole.pyi | 1 + stubs/pywin32/win32verstamp.pyi | 1 + stubs/pywin32/win32wnet.pyi | 1 + stubs/pywin32/winerror.pyi | 1 + stubs/pywin32/winioctlcon.pyi | 1 + stubs/pywin32/winnt.pyi | 1 + stubs/pywin32/winperf.pyi | 1 + stubs/pywin32/winxpgui.pyi | 1 + stubs/pywin32/winxptheme.pyi | 1 + stubs/pyxdg/@tests/stubtest_allowlist.txt | 2 + .../pyxdg/@tests/test_cases/check_IniFile.py | 279 + stubs/pyxdg/METADATA.toml | 2 + stubs/pyxdg/xdg/BaseDirectory.pyi | 18 + stubs/pyxdg/xdg/Config.pyi | 13 + stubs/pyxdg/xdg/DesktopEntry.pyi | 65 + stubs/pyxdg/xdg/Exceptions.pyi | 41 + stubs/pyxdg/xdg/IconTheme.pyi | 55 + stubs/pyxdg/xdg/IniFile.pyi | 256 + stubs/pyxdg/xdg/Locale.pyi | 8 + stubs/pyxdg/xdg/Menu.pyi | 168 + stubs/pyxdg/xdg/MenuEditor.pyi | 152 + stubs/pyxdg/xdg/Mime.pyi | 102 + stubs/pyxdg/xdg/RecentFiles.pyi | 26 + stubs/pyxdg/xdg/__init__.pyi | 15 + stubs/pyxdg/xdg/util.pyi | 6 + stubs/qrbill/@tests/stubtest_allowlist.txt | 6 + stubs/qrbill/METADATA.toml | 3 + stubs/qrbill/qrbill/__init__.pyi | 1 + stubs/qrbill/qrbill/bill.pyi | 193 + stubs/qrcode/@tests/stubtest_allowlist.txt | 22 + stubs/qrcode/METADATA.toml | 7 + stubs/qrcode/qrcode/LUT.pyi | 3 + stubs/qrcode/qrcode/__init__.pyi | 22 + stubs/qrcode/qrcode/_types.pyi | 15 + stubs/qrcode/qrcode/base.pyi | 27 + stubs/qrcode/qrcode/console_scripts.pyi | 12 + stubs/qrcode/qrcode/constants.pyi | 6 + stubs/qrcode/qrcode/exceptions.pyi | 1 + stubs/qrcode/qrcode/image/__init__.pyi | 0 stubs/qrcode/qrcode/image/base.pyi | 66 + stubs/qrcode/qrcode/image/pil.pyi | 30 + stubs/qrcode/qrcode/image/pure.pyi | 22 + stubs/qrcode/qrcode/image/styledpil.pyi | 56 + stubs/qrcode/qrcode/image/styles/__init__.pyi | 0 .../qrcode/qrcode/image/styles/colormasks.pyi | 64 + .../image/styles/moduledrawers/__init__.pyi | 8 + .../image/styles/moduledrawers/base.pyi | 12 + .../qrcode/image/styles/moduledrawers/pil.pyi | 66 + .../qrcode/image/styles/moduledrawers/svg.pyi | 56 + stubs/qrcode/qrcode/image/svg.pyi | 69 + stubs/qrcode/qrcode/main.pyi | 139 + stubs/qrcode/qrcode/release.pyi | 1 + stubs/qrcode/qrcode/util.pyi | 70 + stubs/rasterio/@tests/stubtest_allowlist.txt | 43 + stubs/rasterio/METADATA.toml | 7 + stubs/rasterio/rasterio/__init__.pyi | 132 + stubs/rasterio/rasterio/_affine_types.pyi | 4 + stubs/rasterio/rasterio/_base.pyi | 172 + stubs/rasterio/rasterio/_env.pyi | 43 + stubs/rasterio/rasterio/_err.pyi | 41 + stubs/rasterio/rasterio/_features.pyi | 34 + stubs/rasterio/rasterio/_filepath.pyi | 14 + stubs/rasterio/rasterio/_io.pyi | 177 + stubs/rasterio/rasterio/_path.pyi | 34 + stubs/rasterio/rasterio/_show_versions.pyi | 1 + stubs/rasterio/rasterio/_transform.pyi | 16 + stubs/rasterio/rasterio/_typing.pyi | 58 + stubs/rasterio/rasterio/_version.pyi | 5 + stubs/rasterio/rasterio/_vsiopener.pyi | 36 + stubs/rasterio/rasterio/_warp.pyi | 123 + stubs/rasterio/rasterio/abc.pyi | 1 + stubs/rasterio/rasterio/cache.pyi | 2 + stubs/rasterio/rasterio/control.pyi | 46 + stubs/rasterio/rasterio/coords.pyi | 11 + stubs/rasterio/rasterio/crs.pyi | 69 + stubs/rasterio/rasterio/drivers.pyi | 8 + stubs/rasterio/rasterio/dtypes.pyi | 46 + stubs/rasterio/rasterio/enums.pyi | 126 + stubs/rasterio/rasterio/env.pyi | 102 + stubs/rasterio/rasterio/errors.pyi | 40 + stubs/rasterio/rasterio/features.pyi | 74 + stubs/rasterio/rasterio/fill.pyi | 11 + stubs/rasterio/rasterio/io.pyi | 67 + stubs/rasterio/rasterio/mask.pyi | 34 + stubs/rasterio/rasterio/merge.pyi | 65 + stubs/rasterio/rasterio/path.pyi | 13 + stubs/rasterio/rasterio/plot.pyi | 49 + stubs/rasterio/rasterio/profiles.pyi | 15 + stubs/rasterio/rasterio/rpc.pyi | 44 + stubs/rasterio/rasterio/sample.pyi | 13 + stubs/rasterio/rasterio/session.pyi | 112 + stubs/rasterio/rasterio/shutil.pyi | 16 + stubs/rasterio/rasterio/stack.pyi | 28 + stubs/rasterio/rasterio/tools.pyi | 19 + stubs/rasterio/rasterio/transform.pyi | 112 + stubs/rasterio/rasterio/vrt.pyi | 13 + stubs/rasterio/rasterio/warp.pyi | 84 + stubs/rasterio/rasterio/windows.pyi | 80 + stubs/ratelimit/@tests/stubtest_allowlist.txt | 3 + stubs/ratelimit/METADATA.toml | 2 + stubs/ratelimit/ratelimit/__init__.pyi | 7 + stubs/ratelimit/ratelimit/decorators.pyi | 13 + stubs/ratelimit/ratelimit/exception.pyi | 3 + stubs/regex/@tests/stubtest_allowlist.txt | 15 + .../regex/@tests/test_cases/check_finditer.py | 11 + stubs/regex/METADATA.toml | 2 + stubs/regex/regex/__init__.pyi | 65 + stubs/regex/regex/_main.pyi | 759 ++ stubs/regex/regex/_regex.pyi | 26 + stubs/regex/regex/_regex_core.pyi | 130 + stubs/reportlab/@tests/stubtest_allowlist.txt | 107 + .../@tests/test_cases/check_tables.py | 199 + stubs/reportlab/METADATA.toml | 7 + stubs/reportlab/reportlab/__init__.pyi | 11 + .../reportlab/reportlab/graphics/__init__.pyi | 3 + .../reportlab/graphics/barcode/__init__.pyi | 7 + .../reportlab/graphics/barcode/code128.pyi | 33 + .../reportlab/graphics/barcode/code39.pyi | 32 + .../reportlab/graphics/barcode/code93.pyi | 28 + .../reportlab/graphics/barcode/common.pyi | 127 + .../reportlab/graphics/barcode/dmtx.pyi | 77 + .../reportlab/graphics/barcode/eanbc.pyi | 43 + .../graphics/barcode/ecc200datamatrix.pyi | 24 + .../reportlab/graphics/barcode/fourstate.pyi | 0 .../reportlab/graphics/barcode/lto.pyi | 35 + .../reportlab/graphics/barcode/qr.pyi | 55 + .../reportlab/graphics/barcode/qrencoder.pyi | 202 + .../reportlab/graphics/barcode/usps.pyi | 36 + .../reportlab/graphics/barcode/usps4s.pyi | 103 + .../reportlab/graphics/barcode/widgets.pyi | 80 + .../reportlab/graphics/charts/__init__.pyi | 3 + .../reportlab/graphics/charts/areas.pyi | 19 + .../reportlab/graphics/charts/axes.pyi | 205 + .../reportlab/graphics/charts/barcharts.pyi | 105 + .../reportlab/graphics/charts/dotbox.pyi | 24 + .../reportlab/graphics/charts/doughnut.pyi | 35 + .../reportlab/graphics/charts/legends.pyi | 101 + .../reportlab/graphics/charts/linecharts.pyi | 67 + .../reportlab/graphics/charts/lineplots.pyi | 121 + .../reportlab/graphics/charts/markers.pyi | 10 + .../reportlab/graphics/charts/piecharts.pyi | 183 + .../reportlab/graphics/charts/slidebox.pyi | 38 + .../reportlab/graphics/charts/spider.pyi | 60 + .../reportlab/graphics/charts/textlabels.pyi | 68 + .../reportlab/graphics/charts/utils.pyi | 72 + .../reportlab/graphics/charts/utils3d.pyi | 26 + .../reportlab/graphics/renderPDF.pyi | 39 + .../reportlab/reportlab/graphics/renderPM.pyi | 132 + .../reportlab/reportlab/graphics/renderPS.pyi | 73 + .../reportlab/graphics/renderSVG.pyi | 107 + .../reportlab/graphics/renderbase.pyi | 39 + .../reportlab/graphics/samples/__init__.pyi | 0 .../reportlab/graphics/samples/bubble.pyi | 5 + .../graphics/samples/clustered_bar.pyi | 5 + .../graphics/samples/clustered_column.pyi | 5 + .../graphics/samples/excelcolors.pyi | 33 + .../graphics/samples/exploded_pie.pyi | 8 + .../graphics/samples/filled_radar.pyi | 5 + .../reportlab/graphics/samples/line_chart.pyi | 5 + .../samples/linechart_with_markers.pyi | 5 + .../reportlab/graphics/samples/radar.pyi | 5 + .../reportlab/graphics/samples/runall.pyi | 3 + .../reportlab/graphics/samples/scatter.pyi | 5 + .../graphics/samples/scatter_lines.pyi | 5 + .../samples/scatter_lines_markers.pyi | 5 + .../reportlab/graphics/samples/simple_pie.pyi | 8 + .../graphics/samples/stacked_bar.pyi | 5 + .../graphics/samples/stacked_column.pyi | 5 + stubs/reportlab/reportlab/graphics/shapes.pyi | 381 + .../reportlab/reportlab/graphics/svgpath.pyi | 10 + .../reportlab/graphics/transform.pyi | 29 + stubs/reportlab/reportlab/graphics/utils.pyi | 22 + .../reportlab/graphics/widgetbase.pyi | 111 + .../reportlab/graphics/widgets/__init__.pyi | 3 + .../graphics/widgets/adjustableArrow.pyi | 11 + .../reportlab/graphics/widgets/eventcal.pyi | 29 + .../reportlab/graphics/widgets/flags.pyi | 32 + .../reportlab/graphics/widgets/grids.pyi | 77 + .../reportlab/graphics/widgets/markers.pyi | 21 + .../graphics/widgets/signsandsymbols.pyi | 164 + .../reportlab/graphics/widgets/table.pyi | 32 + stubs/reportlab/reportlab/lib/PyFontify.pyi | 22 + stubs/reportlab/reportlab/lib/__init__.pyi | 4 + stubs/reportlab/reportlab/lib/abag.pyi | 11 + stubs/reportlab/reportlab/lib/arciv.pyi | 9 + stubs/reportlab/reportlab/lib/attrmap.pyi | 26 + stubs/reportlab/reportlab/lib/boxstuff.pyi | 15 + stubs/reportlab/reportlab/lib/codecharts.pyi | 81 + stubs/reportlab/reportlab/lib/colors.pyi | 325 + stubs/reportlab/reportlab/lib/corp.pyi | 81 + stubs/reportlab/reportlab/lib/enums.pyi | 7 + stubs/reportlab/reportlab/lib/extformat.pyi | 9 + stubs/reportlab/reportlab/lib/fontfinder.pyi | 54 + stubs/reportlab/reportlab/lib/fonts.pyi | 9 + stubs/reportlab/reportlab/lib/formatters.pyi | 23 + stubs/reportlab/reportlab/lib/geomutils.pyi | 5 + stubs/reportlab/reportlab/lib/logger.pyi | 24 + stubs/reportlab/reportlab/lib/normalDate.pyi | 83 + stubs/reportlab/reportlab/lib/pagesizes.pyi | 51 + stubs/reportlab/reportlab/lib/pdfencrypt.pyi | 133 + .../reportlab/reportlab/lib/pygments2xpre.pyi | 3 + stubs/reportlab/reportlab/lib/randomtext.pyi | 19 + stubs/reportlab/reportlab/lib/rl_accel.pyi | 28 + .../reportlab/reportlab/lib/rl_safe_eval.pyi | 237 + stubs/reportlab/reportlab/lib/rltempfile.pyi | 4 + stubs/reportlab/reportlab/lib/rparsexml.pyi | 35 + stubs/reportlab/reportlab/lib/sequencer.pyi | 39 + stubs/reportlab/reportlab/lib/styles.pyi | 185 + stubs/reportlab/reportlab/lib/testutils.pyi | 74 + stubs/reportlab/reportlab/lib/textsplit.pyi | 20 + stubs/reportlab/reportlab/lib/units.pyi | 9 + stubs/reportlab/reportlab/lib/utils.pyi | 221 + stubs/reportlab/reportlab/lib/validators.pyi | 169 + stubs/reportlab/reportlab/lib/yaml.pyi | 27 + .../reportlab/reportlab/pdfbase/__init__.pyi | 3 + .../reportlab/reportlab/pdfbase/acroform.pyi | 340 + .../reportlab/reportlab/pdfbase/cidfonts.pyi | 52 + stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi | 633 ++ stubs/reportlab/reportlab/pdfbase/pdfform.pyi | 86 + .../reportlab/pdfbase/pdfmetrics.pyi | 90 + .../reportlab/pdfbase/pdfpattern.pyi | 22 + .../reportlab/reportlab/pdfbase/pdfutils.pyi | 16 + .../reportlab/reportlab/pdfbase/rl_codecs.pyi | 23 + stubs/reportlab/reportlab/pdfbase/ttfonts.pyi | 192 + stubs/reportlab/reportlab/pdfgen/__init__.pyi | 3 + stubs/reportlab/reportlab/pdfgen/canvas.pyi | 297 + .../reportlab/reportlab/pdfgen/pathobject.pyi | 17 + stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi | 8 + .../reportlab/reportlab/pdfgen/pdfimages.pyi | 36 + .../reportlab/reportlab/pdfgen/textobject.pyi | 71 + .../reportlab/reportlab/platypus/__init__.pyi | 12 + .../reportlab/platypus/doctemplate.pyi | 325 + .../reportlab/reportlab/platypus/figures.pyi | 108 + .../reportlab/platypus/flowables.pyi | 472 ++ stubs/reportlab/reportlab/platypus/frames.pyi | 38 + .../reportlab/reportlab/platypus/multicol.pyi | 19 + stubs/reportlab/reportlab/platypus/para.pyi | 276 + .../reportlab/platypus/paragraph.pyi | 40 + .../reportlab/platypus/paraparser.pyi | 117 + .../reportlab/platypus/tableofcontents.pyi | 110 + stubs/reportlab/reportlab/platypus/tables.pyi | 136 + .../reportlab/platypus/xpreformatted.pyi | 32 + stubs/reportlab/reportlab/rl_config.pyi | 77 + stubs/reportlab/reportlab/rl_settings.pyi | 140 + stubs/requests-oauthlib/METADATA.toml | 3 + .../requests_oauthlib/__init__.pyi | 6 + .../compliance_fixes/__init__.pyi | 8 + .../compliance_fixes/douban.pyi | 7 + .../compliance_fixes/ebay.pyi | 7 + .../compliance_fixes/facebook.pyi | 7 + .../compliance_fixes/fitbit.pyi | 3 + .../compliance_fixes/instagram.pyi | 7 + .../compliance_fixes/mailchimp.pyi | 7 + .../compliance_fixes/plentymarkets.pyi | 7 + .../compliance_fixes/slack.pyi | 7 + .../compliance_fixes/weibo.pyi | 7 + .../requests_oauthlib/oauth1_auth.pyi | 35 + .../requests_oauthlib/oauth1_session.pyi | 67 + .../requests_oauthlib/oauth2_auth.pyi | 5 + .../requests_oauthlib/oauth2_session.pyi | 149 + stubs/requests/@tests/stubtest_allowlist.txt | 7 + .../requests/@tests/test_cases/check_post.py | 56 + stubs/requests/METADATA.toml | 14 + stubs/requests/requests/__init__.pyi | 39 + stubs/requests/requests/__version__.pyi | 12 + stubs/requests/requests/adapters.pyi | 137 + stubs/requests/requests/api.pyi | 154 + stubs/requests/requests/auth.pyi | 39 + stubs/requests/requests/certs.pyi | 1 + stubs/requests/requests/compat.pyi | 29 + stubs/requests/requests/cookies.pyi | 62 + stubs/requests/requests/exceptions.pyi | 43 + stubs/requests/requests/help.pyi | 40 + stubs/requests/requests/hooks.pyi | 6 + stubs/requests/requests/models.pyi | 169 + stubs/requests/requests/packages.pyi | 3 + stubs/requests/requests/sessions.pyi | 314 + stubs/requests/requests/status_codes.pyi | 3 + stubs/requests/requests/structures.pyi | 26 + stubs/requests/requests/utils.pyi | 69 + stubs/resampy/@tests/stubtest_allowlist.txt | 2 + stubs/resampy/METADATA.toml | 4 + stubs/resampy/resampy/__init__.pyi | 2 + stubs/resampy/resampy/core.pyi | 35 + stubs/resampy/resampy/filters.pyi | 26 + stubs/resampy/resampy/version.pyi | 4 + stubs/retry/@tests/stubtest_allowlist.txt | 3 + stubs/retry/METADATA.toml | 2 + stubs/retry/retry/__init__.pyi | 3 + stubs/retry/retry/api.pyi | 30 + stubs/rfc3339-validator/METADATA.toml | 2 + stubs/rfc3339-validator/rfc3339_validator.pyi | 10 + .../@tests/stubtest_allowlist.txt | 4 + stubs/s2clientprotocol/METADATA.toml | 7 + .../s2clientprotocol/build.pyi | 5 + .../s2clientprotocol/common_pb2.pyi | 177 + .../s2clientprotocol/data_pb2.pyi | 615 ++ .../s2clientprotocol/debug_pb2.pyi | 501 ++ .../s2clientprotocol/error_pb2.pyi | 459 ++ .../s2clientprotocol/query_pb2.pyi | 228 + .../s2clientprotocol/raw_pb2.pyi | 1024 +++ .../s2clientprotocol/sc2api_pb2.pyi | 2896 +++++++ .../s2clientprotocol/score_pb2.pyi | 406 + .../s2clientprotocol/spatial_pb2.pyi | 712 ++ .../s2clientprotocol/ui_pb2.pyi | 681 ++ stubs/scp/METADATA.toml | 3 + stubs/scp/scp.pyi | 83 + stubs/seaborn/@tests/stubtest_allowlist.txt | 6 + stubs/seaborn/METADATA.toml | 4 + stubs/seaborn/seaborn/__init__.pyi | 13 + stubs/seaborn/seaborn/_core/__init__.pyi | 0 stubs/seaborn/seaborn/_core/data.pyi | 26 + stubs/seaborn/seaborn/_core/exceptions.pyi | 1 + stubs/seaborn/seaborn/_core/groupby.pyi | 32 + stubs/seaborn/seaborn/_core/moves.pyi | 44 + stubs/seaborn/seaborn/_core/plot.pyi | 153 + stubs/seaborn/seaborn/_core/properties.pyi | 97 + stubs/seaborn/seaborn/_core/rules.pyi | 14 + stubs/seaborn/seaborn/_core/scales.pyi | 100 + stubs/seaborn/seaborn/_core/subplots.pyi | 19 + stubs/seaborn/seaborn/_core/typing.pyi | 29 + stubs/seaborn/seaborn/_marks/__init__.pyi | 0 stubs/seaborn/seaborn/_marks/area.pyi | 28 + stubs/seaborn/seaborn/_marks/bar.pyi | 31 + stubs/seaborn/seaborn/_marks/base.pyi | 37 + stubs/seaborn/seaborn/_marks/dot.pyi | 39 + stubs/seaborn/seaborn/_marks/line.pyi | 42 + stubs/seaborn/seaborn/_marks/text.pyi | 14 + stubs/seaborn/seaborn/_stats/__init__.pyi | 0 stubs/seaborn/seaborn/_stats/aggregation.pyi | 19 + stubs/seaborn/seaborn/_stats/base.pyi | 11 + stubs/seaborn/seaborn/_stats/counting.pyi | 19 + stubs/seaborn/seaborn/_stats/density.pyi | 15 + stubs/seaborn/seaborn/_stats/order.pyi | 8 + stubs/seaborn/seaborn/_stats/regression.pyi | 11 + stubs/seaborn/seaborn/algorithms.pyi | 28 + stubs/seaborn/seaborn/axisgrid.pyi | 402 + stubs/seaborn/seaborn/categorical.pyi | 294 + stubs/seaborn/seaborn/cm.pyi | 15 + stubs/seaborn/seaborn/colors/__init__.pyi | 2 + stubs/seaborn/seaborn/colors/crayons.pyi | 1 + stubs/seaborn/seaborn/colors/xkcd_rgb.pyi | 1 + stubs/seaborn/seaborn/distributions.pyi | 171 + stubs/seaborn/seaborn/external/__init__.pyi | 0 stubs/seaborn/seaborn/external/appdirs.pyi | 9 + stubs/seaborn/seaborn/external/docscrape.pyi | 72 + stubs/seaborn/seaborn/external/husl.pyi | 42 + stubs/seaborn/seaborn/external/kde.pyi | 43 + stubs/seaborn/seaborn/external/version.pyi | 45 + stubs/seaborn/seaborn/matrix.pyi | 220 + stubs/seaborn/seaborn/miscplot.pyi | 9 + stubs/seaborn/seaborn/objects.pyi | 21 + stubs/seaborn/seaborn/palettes.pyi | 159 + stubs/seaborn/seaborn/rcmod.pyi | 74 + stubs/seaborn/seaborn/regression.pyi | 163 + stubs/seaborn/seaborn/relational.pyi | 102 + stubs/seaborn/seaborn/utils.pyi | 115 + stubs/seaborn/seaborn/widgets.pyi | 40 + .../setuptools/@tests/stubtest_allowlist.txt | 88 + .../@tests/test_cases/check_distutils.py | 31 + .../@tests/test_cases/check_extension.py | 15 + .../@tests/test_cases/check_protocols.py | 19 + .../@tests/test_cases/check_setup.py | 23 + stubs/setuptools/METADATA.toml | 16 + stubs/setuptools/distutils/__init__.pyi | 3 + stubs/setuptools/distutils/_modified.pyi | 1 + stubs/setuptools/distutils/_msvccompiler.pyi | 1 + stubs/setuptools/distutils/archive_util.pyi | 1 + stubs/setuptools/distutils/ccompiler.pyi | 12 + stubs/setuptools/distutils/cmd.pyi | 1 + .../setuptools/distutils/command/__init__.pyi | 39 + stubs/setuptools/distutils/command/bdist.pyi | 1 + .../distutils/command/bdist_rpm.pyi | 1 + stubs/setuptools/distutils/command/build.pyi | 1 + .../distutils/command/build_clib.pyi | 1 + .../distutils/command/build_ext.pyi | 1 + .../setuptools/distutils/command/build_py.pyi | 1 + .../setuptools/distutils/command/install.pyi | 1 + .../distutils/command/install_data.pyi | 1 + .../distutils/command/install_lib.pyi | 1 + .../distutils/command/install_scripts.pyi | 1 + stubs/setuptools/distutils/command/sdist.pyi | 1 + .../setuptools/distutils/compat/__init__.pyi | 1 + .../setuptools/distutils/compilers/C/base.pyi | 1 + .../distutils/compilers/C/cygwin.pyi | 1 + .../distutils/compilers/C/errors.pyi | 1 + .../setuptools/distutils/compilers/C/msvc.pyi | 1 + .../setuptools/distutils/compilers/C/unix.pyi | 1 + .../setuptools/distutils/compilers/C/zos.pyi | 1 + .../setuptools/distutils/cygwinccompiler.pyi | 1 + stubs/setuptools/distutils/dep_util.pyi | 1 + stubs/setuptools/distutils/dist.pyi | 1 + stubs/setuptools/distutils/errors.pyi | 1 + stubs/setuptools/distutils/extension.pyi | 1 + stubs/setuptools/distutils/filelist.pyi | 1 + stubs/setuptools/distutils/spawn.pyi | 1 + stubs/setuptools/distutils/sysconfig.pyi | 1 + stubs/setuptools/distutils/unixccompiler.pyi | 1 + stubs/setuptools/distutils/util.pyi | 1 + stubs/setuptools/distutils/version.pyi | 1 + stubs/setuptools/distutils/zosccompiler.pyi | 1 + stubs/setuptools/setuptools/__init__.pyi | 279 + .../setuptools/_distutils/__init__.pyi | 3 + .../setuptools/_distutils/_modified.pyi | 17 + .../setuptools/_distutils/_msvccompiler.pyi | 5 + .../setuptools/_distutils/archive_util.pyi | 33 + .../setuptools/_distutils/ccompiler.pyi | 15 + .../setuptools/setuptools/_distutils/cmd.pyi | 127 + .../_distutils/command/__init__.pyi | 39 + .../setuptools/_distutils/command/bdist.pyi | 26 + .../_distutils/command/bdist_rpm.pyi | 53 + .../setuptools/_distutils/command/build.pyi | 30 + .../_distutils/command/build_clib.pyi | 27 + .../_distutils/command/build_ext.pyi | 49 + .../_distutils/command/build_py.pyi | 39 + .../setuptools/_distutils/command/install.pyi | 60 + .../_distutils/command/install_data.pyi | 20 + .../_distutils/command/install_lib.pyi | 24 + .../_distutils/command/install_scripts.pyi | 19 + .../setuptools/_distutils/command/sdist.pyi | 46 + .../setuptools/_distutils/compat/__init__.pyi | 6 + .../_distutils/compilers/C/base.pyi | 217 + .../_distutils/compilers/C/cygwin.pyi | 68 + .../_distutils/compilers/C/errors.pyi | 6 + .../_distutils/compilers/C/msvc.pyi | 23 + .../_distutils/compilers/C/unix.pyi | 16 + .../setuptools/_distutils/compilers/C/zos.pyi | 27 + .../setuptools/_distutils/cygwinccompiler.pyi | 28 + .../setuptools/_distutils/dep_util.pyi | 1 + .../setuptools/setuptools/_distutils/dist.pyi | 179 + .../setuptools/_distutils/errors.pyi | 25 + .../setuptools/_distutils/extension.pyi | 39 + .../setuptools/_distutils/filelist.pyi | 40 + .../setuptools/_distutils/spawn.pyi | 15 + .../setuptools/_distutils/sysconfig.pyi | 24 + .../setuptools/_distutils/unixccompiler.pyi | 3 + .../setuptools/setuptools/_distutils/util.pyi | 34 + .../setuptools/_distutils/version.pyi | 35 + .../setuptools/_distutils/zosccompiler.pyi | 3 + stubs/setuptools/setuptools/archive_util.pyi | 24 + stubs/setuptools/setuptools/build_meta.pyi | 64 + .../setuptools/command/__init__.pyi | 0 stubs/setuptools/setuptools/command/alias.pyi | 19 + .../setuptools/command/bdist_egg.pyi | 56 + .../setuptools/command/bdist_rpm.pyi | 7 + .../setuptools/command/bdist_wheel.pyi | 54 + stubs/setuptools/setuptools/command/build.pyi | 18 + .../setuptools/command/build_clib.pyi | 8 + .../setuptools/command/build_ext.pyi | 51 + .../setuptools/command/build_py.pyi | 43 + .../setuptools/setuptools/command/develop.pyi | 24 + .../setuptools/command/dist_info.pyi | 12 + .../setuptools/command/easy_install.pyi | 11 + .../setuptools/command/editable_wheel.pyi | 78 + .../setuptools/command/egg_info.pyi | 86 + .../setuptools/setuptools/command/install.pyi | 21 + .../setuptools/command/install_egg_info.pyi | 17 + .../setuptools/command/install_lib.pyi | 20 + .../setuptools/command/install_scripts.pyi | 11 + .../setuptools/setuptools/command/rotate.pyi | 15 + .../setuptools/command/saveopts.pyi | 5 + stubs/setuptools/setuptools/command/sdist.pyi | 24 + .../setuptools/setuptools/command/setopt.pyi | 33 + stubs/setuptools/setuptools/command/test.pyi | 15 + .../setuptools/setuptools/config/__init__.pyi | 3 + stubs/setuptools/setuptools/config/expand.pyi | 50 + .../setuptools/config/pyprojecttoml.pyi | 46 + .../setuptools/setuptools/config/setupcfg.pyi | 83 + stubs/setuptools/setuptools/depends.pyi | 20 + stubs/setuptools/setuptools/discovery.pyi | 43 + stubs/setuptools/setuptools/dist.pyi | 199 + stubs/setuptools/setuptools/errors.pyi | 24 + stubs/setuptools/setuptools/extension.pyi | 32 + stubs/setuptools/setuptools/glob.pyi | 5 + stubs/setuptools/setuptools/installer.pyi | 14 + stubs/setuptools/setuptools/launch.pyi | 1 + stubs/setuptools/setuptools/logging.pyi | 2 + stubs/setuptools/setuptools/modified.pyi | 3 + stubs/setuptools/setuptools/monkey.pyi | 16 + stubs/setuptools/setuptools/msvc.pyi | 168 + stubs/setuptools/setuptools/namespaces.pyi | 10 + stubs/setuptools/setuptools/unicode_utils.pyi | 4 + stubs/setuptools/setuptools/version.pyi | 1 + stubs/setuptools/setuptools/warnings.pyi | 19 + stubs/setuptools/setuptools/wheel.pyi | 17 + .../setuptools/setuptools/windows_support.pyi | 2 + stubs/shapely/@tests/stubtest_allowlist.txt | 4 + stubs/shapely/METADATA.toml | 4 + stubs/shapely/shapely/__init__.pyi | 35 + stubs/shapely/shapely/_coverage.pyi | 16 + stubs/shapely/shapely/_enum.pyi | 5 + stubs/shapely/shapely/_geometry.pyi | 209 + stubs/shapely/shapely/_ragged_array.pyi | 14 + stubs/shapely/shapely/_typing.pyi | 75 + stubs/shapely/shapely/_version.pyi | 6 + stubs/shapely/shapely/affinity.pyi | 24 + stubs/shapely/shapely/algorithms/__init__.pyi | 0 stubs/shapely/shapely/algorithms/cga.pyi | 5 + .../shapely/shapely/algorithms/polylabel.pyi | 3 + stubs/shapely/shapely/constructive.pyi | 634 ++ stubs/shapely/shapely/coordinates.pyi | 54 + stubs/shapely/shapely/coords.pyi | 20 + stubs/shapely/shapely/creation.pyi | 331 + stubs/shapely/shapely/decorators.pyi | 12 + stubs/shapely/shapely/errors.pyi | 17 + stubs/shapely/shapely/geometry/__init__.pyi | 25 + stubs/shapely/shapely/geometry/base.pyi | 326 + stubs/shapely/shapely/geometry/collection.pyi | 23 + stubs/shapely/shapely/geometry/geo.pyi | 9 + stubs/shapely/shapely/geometry/linestring.pyi | 48 + .../shapely/geometry/multilinestring.pyi | 19 + stubs/shapely/shapely/geometry/multipoint.pyi | 24 + .../shapely/shapely/geometry/multipolygon.pyi | 26 + stubs/shapely/shapely/geometry/point.pyi | 46 + stubs/shapely/shapely/geometry/polygon.pyi | 52 + stubs/shapely/shapely/geos.pyi | 3 + stubs/shapely/shapely/io.pyi | 176 + stubs/shapely/shapely/lib.pyi | 182 + stubs/shapely/shapely/linear.pyi | 73 + stubs/shapely/shapely/measurement.pyi | 75 + stubs/shapely/shapely/ops.pyi | 104 + stubs/shapely/shapely/plotting.pyi | 79 + stubs/shapely/shapely/predicates.pyi | 303 + stubs/shapely/shapely/prepared.pyi | 20 + stubs/shapely/shapely/set_operations.pyi | 137 + stubs/shapely/shapely/speedups.pyi | 12 + stubs/shapely/shapely/strtree.pyi | 84 + stubs/shapely/shapely/testing.pyi | 14 + stubs/shapely/shapely/validation.pyi | 7 + stubs/shapely/shapely/vectorized/__init__.pyi | 47 + stubs/shapely/shapely/wkb.pyi | 18 + stubs/shapely/shapely/wkt.pyi | 8 + stubs/simple-websocket/METADATA.toml | 3 + .../simple_websocket/__init__.pyi | 3 + .../simple_websocket/aiows.pyi | 130 + .../simple_websocket/asgi.pyi | 44 + .../simple_websocket/errors.pyi | 12 + .../simple-websocket/simple_websocket/ws.pyi | 136 + .../simplejson/@tests/stubtest_allowlist.txt | 16 + .../@tests/test_cases/check_simplejson.py | 16 + stubs/simplejson/METADATA.toml | 2 + stubs/simplejson/simplejson/__init__.pyi | 189 + stubs/simplejson/simplejson/decoder.pyi | 40 + stubs/simplejson/simplejson/encoder.pyi | 61 + stubs/simplejson/simplejson/errors.pyi | 16 + stubs/simplejson/simplejson/raw_json.pyi | 3 + stubs/simplejson/simplejson/scanner.pyi | 17 + stubs/singledispatch/METADATA.toml | 2 + stubs/singledispatch/singledispatch.pyi | 38 + stubs/six/@tests/stubtest_allowlist.txt | 29 + stubs/six/METADATA.toml | 2 + stubs/six/six/__init__.pyi | 112 + stubs/six/six/moves/BaseHTTPServer.pyi | 1 + stubs/six/six/moves/CGIHTTPServer.pyi | 1 + stubs/six/six/moves/SimpleHTTPServer.pyi | 1 + stubs/six/six/moves/__init__.pyi | 65 + stubs/six/six/moves/_dummy_thread.pyi | 1 + stubs/six/six/moves/_thread.pyi | 1 + stubs/six/six/moves/builtins.pyi | 3 + stubs/six/six/moves/cPickle.pyi | 1 + stubs/six/six/moves/collections_abc.pyi | 1 + stubs/six/six/moves/configparser.pyi | 3 + stubs/six/six/moves/copyreg.pyi | 1 + stubs/six/six/moves/email_mime_base.pyi | 1 + stubs/six/six/moves/email_mime_multipart.pyi | 1 + .../six/six/moves/email_mime_nonmultipart.pyi | 1 + stubs/six/six/moves/email_mime_text.pyi | 1 + stubs/six/six/moves/html_entities.pyi | 1 + stubs/six/six/moves/html_parser.pyi | 1 + stubs/six/six/moves/http_client.pyi | 61 + stubs/six/six/moves/http_cookiejar.pyi | 1 + stubs/six/six/moves/http_cookies.pyi | 3 + stubs/six/six/moves/queue.pyi | 1 + stubs/six/six/moves/reprlib.pyi | 1 + stubs/six/six/moves/socketserver.pyi | 1 + stubs/six/six/moves/tkinter.pyi | 1 + stubs/six/six/moves/tkinter_commondialog.pyi | 1 + stubs/six/six/moves/tkinter_constants.pyi | 1 + stubs/six/six/moves/tkinter_dialog.pyi | 1 + stubs/six/six/moves/tkinter_filedialog.pyi | 1 + stubs/six/six/moves/tkinter_tkfiledialog.pyi | 1 + stubs/six/six/moves/tkinter_ttk.pyi | 1 + stubs/six/six/moves/urllib/__init__.pyi | 1 + stubs/six/six/moves/urllib/error.pyi | 1 + stubs/six/six/moves/urllib/parse.pyi | 30 + stubs/six/six/moves/urllib/request.pyi | 44 + stubs/six/six/moves/urllib/response.pyi | 8 + stubs/six/six/moves/urllib/robotparser.pyi | 1 + stubs/six/six/moves/urllib_error.pyi | 1 + stubs/six/six/moves/urllib_parse.pyi | 1 + stubs/six/six/moves/urllib_request.pyi | 1 + stubs/six/six/moves/urllib_response.pyi | 1 + stubs/six/six/moves/urllib_robotparser.pyi | 1 + stubs/slumber/METADATA.toml | 3 + stubs/slumber/slumber/__init__.pyi | 43 + stubs/slumber/slumber/exceptions.pyi | 13 + stubs/slumber/slumber/serialize.pyi | 27 + stubs/slumber/slumber/utils.pyi | 10 + stubs/str2bool/METADATA.toml | 2 + stubs/str2bool/str2bool/__init__.pyi | 8 + stubs/tabulate/METADATA.toml | 2 + stubs/tabulate/tabulate/__init__.pyi | 71 + .../tensorflow/@tests/stubtest_allowlist.txt | 115 + stubs/tensorflow/METADATA.toml | 16 + stubs/tensorflow/tensorflow/__init__.pyi | 523 ++ stubs/tensorflow/tensorflow/_aliases.pyi | 73 + stubs/tensorflow/tensorflow/audio.pyi | 7 + stubs/tensorflow/tensorflow/autodiff.pyi | 65 + .../tensorflow/autograph/__init__.pyi | 17 + .../tensorflow/autograph/experimental.pyi | 30 + stubs/tensorflow/tensorflow/bitwise.pyi | 41 + .../compiler/xla/service/hlo_pb2.pyi | 2113 +++++ .../service/hlo_profile_printer_data_pb2.pyi | 187 + .../compiler/xla/service/metrics_pb2.pyi | 284 + .../test_compilation_environment_pb2.pyi | 59 + .../xla/service/xla_compile_result_pb2.pyi | 167 + .../xla/tsl/protobuf/bfc_memory_map_pb2.pyi | 218 + .../xla/tsl/protobuf/test_log_pb2.pyi | 707 ++ .../tensorflow/compiler/xla/xla_data_pb2.pyi | 2681 ++++++ .../tensorflow/compiler/xla/xla_pb2.pyi | 2558 ++++++ .../tensorflow/tensorflow/config/__init__.pyi | 12 + .../tensorflow/config/experimental.pyi | 17 + .../example_parser_configuration_pb2.pyi | 153 + .../tensorflow/core/example/example_pb2.pyi | 330 + .../tensorflow/core/example/feature_pb2.pyi | 222 + .../framework/allocation_description_pb2.pyi | 64 + .../tensorflow/core/framework/api_def_pb2.pyi | 312 + .../core/framework/attr_value_pb2.pyi | 274 + .../core/framework/cost_graph_pb2.pyi | 229 + .../framework/cpp_shape_inference_pb2.pyi | 110 + .../core/framework/dataset_metadata_pb2.pyi | 25 + .../core/framework/dataset_options_pb2.pyi | 724 ++ .../tensorflow/core/framework/dataset_pb2.pyi | 116 + .../core/framework/device_attributes_pb2.pyi | 140 + .../core/framework/full_type_pb2.pyi | 617 ++ .../core/framework/function_pb2.pyi | 309 + .../core/framework/graph_debug_info_pb2.pyi | 210 + .../tensorflow/core/framework/graph_pb2.pyi | 100 + .../framework/graph_transfer_info_pb2.pyi | 290 + .../core/framework/kernel_def_pb2.pyi | 116 + .../core/framework/log_memory_pb2.pyi | 218 + .../tensorflow/core/framework/model_pb2.pyi | 368 + .../core/framework/node_def_pb2.pyi | 192 + .../tensorflow/core/framework/op_def_pb2.pyi | 391 + .../optimized_function_graph_pb2.pyi | 167 + .../core/framework/reader_base_pb2.pyi | 52 + .../core/framework/resource_handle_pb2.pyi | 104 + .../core/framework/step_stats_pb2.pyi | 332 + .../tensorflow/core/framework/summary_pb2.pyi | 368 + .../core/framework/tensor_description_pb2.pyi | 49 + .../tensorflow/core/framework/tensor_pb2.pyi | 235 + .../core/framework/tensor_shape_pb2.pyi | 74 + .../core/framework/tensor_slice_pb2.pyi | 56 + .../tensorflow/core/framework/types_pb2.pyi | 220 + .../core/framework/variable_pb2.pyi | 229 + .../core/framework/versions_pb2.pyi | 57 + .../tensorflow/core/protobuf/__init__.pyi | 0 .../core/protobuf/bfc_memory_map_pb2.pyi | 15 + .../tensorflow/core/protobuf/cluster_pb2.pyi | 126 + .../protobuf/composite_tensor_variant_pb2.pyi | 33 + .../tensorflow/core/protobuf/config_pb2.pyi | 1867 +++++ .../core/protobuf/control_flow_pb2.pyi | 243 + .../protobuf/core_platform_payloads_pb2.pyi | 66 + .../core/protobuf/data_service_pb2.pyi | 243 + .../core/protobuf/debug_event_pb2.pyi | 746 ++ .../tensorflow/core/protobuf/debug_pb2.pyi | 199 + .../core/protobuf/device_filters_pb2.pyi | 124 + .../core/protobuf/device_properties_pb2.pyi | 154 + .../core/protobuf/error_codes_pb2.pyi | 33 + .../core/protobuf/fingerprint_pb2.pyi | 76 + .../core/protobuf/meta_graph_pb2.pyi | 735 ++ .../core/protobuf/named_tensor_pb2.pyi | 41 + .../core/protobuf/queue_runner_pb2.pyi | 73 + .../protobuf/remote_tensor_handle_pb2.pyi | 96 + .../core/protobuf/rewriter_config_pb2.pyi | 588 ++ .../core/protobuf/rpc_options_pb2.pyi | 9 + .../core/protobuf/saved_model_pb2.pyi | 51 + .../core/protobuf/saved_object_graph_pb2.pyi | 715 ++ .../tensorflow/core/protobuf/saver_pb2.pyi | 113 + .../core/protobuf/service_config_pb2.pyi | 275 + .../tensorflow/core/protobuf/snapshot_pb2.pyi | 164 + .../tensorflow/core/protobuf/status_pb2.pyi | 13 + .../tensorflow/core/protobuf/struct_pb2.pyi | 536 ++ .../core/protobuf/tensor_bundle_pb2.pyi | 160 + .../core/protobuf/tensorflow_server_pb2.pyi | 125 + .../protobuf/tpu/compilation_result_pb2.pyi | 85 + .../core/protobuf/tpu/dynamic_padding_pb2.pyi | 47 + .../tpu/optimization_parameters_pb2.pyi | 1326 +++ .../core/protobuf/tpu/topology_pb2.pyi | 149 + .../tpu/tpu_embedding_configuration_pb2.pyi | 326 + .../protobuf/trackable_object_graph_pb2.pyi | 213 + .../core/protobuf/transport_options_pb2.pyi | 28 + .../core/protobuf/verifier_config_pb2.pyi | 65 + .../tensorflow/core/util/event_pb2.pyi | 419 + .../core/util/memmapped_file_system_pb2.pyi | 65 + .../core/util/saved_tensor_slice_pb2.pyi | 171 + .../tensorflow/core/util/test_log_pb2.pyi | 24 + stubs/tensorflow/tensorflow/data/__init__.pyi | 276 + .../tensorflow/data/experimental.pyi | 32 + stubs/tensorflow/tensorflow/debugging.pyi | 10 + .../tensorflow/distribute/__init__.pyi | 3 + .../tensorflow/distribute/coordinator.pyi | 3 + .../distribute/experimental/coordinator.pyi | 11 + stubs/tensorflow/tensorflow/dtypes.pyi | 58 + .../tensorflow/experimental/__init__.pyi | 10 + .../tensorflow/experimental/dtensor.pyi | 19 + .../tensorflow/feature_column/__init__.pyi | 95 + stubs/tensorflow/tensorflow/image.pyi | 7 + stubs/tensorflow/tensorflow/initializers.pyi | 1 + stubs/tensorflow/tensorflow/io/__init__.pyi | 104 + stubs/tensorflow/tensorflow/io/gfile.pyi | 11 + .../tensorflow/tensorflow/keras/__init__.pyi | 15 + .../tensorflow/keras/activations.pyi | 34 + .../tensorflow/tensorflow/keras/callbacks.pyi | 169 + .../tensorflow/keras/constraints.pyi | 17 + .../tensorflow/keras/initializers.pyi | 51 + .../tensorflow/keras/layers/__init__.pyi | 494 ++ stubs/tensorflow/tensorflow/keras/losses.pyi | 177 + stubs/tensorflow/tensorflow/keras/metrics.pyi | 141 + stubs/tensorflow/tensorflow/keras/models.pyi | 167 + .../tensorflow/keras/optimizers/__init__.pyi | 7 + .../keras/optimizers/legacy/__init__.pyi | 60 + .../tensorflow/keras/optimizers/schedules.pyi | 103 + .../tensorflow/keras/regularizers.pyi | 22 + stubs/tensorflow/tensorflow/linalg.pyi | 56 + stubs/tensorflow/tensorflow/math.pyi | 341 + stubs/tensorflow/tensorflow/nn.pyi | 196 + .../tensorflow/tensorflow/python/__init__.pyi | 1 + .../python/distribute/distribute_lib.pyi | 5 + .../python/feature_column/__init__.pyi | 0 .../feature_column/feature_column_v2.pyi | 273 + .../sequence_feature_column.pyi | 30 + .../tensorflow/python/framework/dtypes.pyi | 7 + .../tensorflow/python/keras/__init__.pyi | 1 + .../keras/protobuf/projector_config_pb2.pyi | 129 + .../keras/protobuf/saved_metadata_pb2.pyi | 89 + .../python/keras/protobuf/versions_pb2.pyi | 63 + .../tensorflow/python/trackable/__init__.pyi | 0 .../python/trackable/autotrackable.pyi | 3 + .../tensorflow/python/trackable/base.pyi | 5 + .../tensorflow/python/trackable/resource.pyi | 9 + .../tensorflow/python/trackable/ressource.pyi | 7 + .../training/tracking/autotrackable.pyi | 3 + stubs/tensorflow/tensorflow/random.pyi | 230 + stubs/tensorflow/tensorflow/raw_ops.pyi | 44 + .../tensorflow/saved_model/__init__.pyi | 131 + .../tensorflow/saved_model/experimental.pyi | 39 + stubs/tensorflow/tensorflow/signal.pyi | 6 + stubs/tensorflow/tensorflow/sparse.pyi | 31 + stubs/tensorflow/tensorflow/strings.pyi | 263 + stubs/tensorflow/tensorflow/summary.pyi | 58 + .../tensorflow/tensorflow/train/__init__.pyi | 85 + .../tensorflow/train/experimental.pyi | 12 + .../tsl/protobuf/coordination_config_pb2.pyi | 156 + .../tsl/protobuf/coordination_service_pb2.pyi | 666 ++ .../distributed_runtime_payloads_pb2.pyi | 69 + .../tensorflow/tsl/protobuf/dnn_pb2.pyi | 620 ++ .../tsl/protobuf/error_codes_pb2.pyi | 291 + .../tensorflow/tsl/protobuf/histogram_pb2.pyi | 78 + .../tsl/protobuf/rpc_options_pb2.pyi | 85 + .../tensorflow/tsl/protobuf/status_pb2.pyi | 34 + .../tensorflow/tensorflow/types/__init__.pyi | 1 + .../tensorflow/types/experimental.pyi | 30 + stubs/tinycss2/METADATA.toml | 3 + stubs/tinycss2/tinycss2/__init__.pyi | 17 + stubs/tinycss2/tinycss2/ast.pyi | 160 + stubs/tinycss2/tinycss2/bytes.pyi | 14 + stubs/tinycss2/tinycss2/color3.pyi | 12 + stubs/tinycss2/tinycss2/color4.pyi | 19 + stubs/tinycss2/tinycss2/color5.pyi | 17 + stubs/tinycss2/tinycss2/nth.pyi | 11 + stubs/tinycss2/tinycss2/parser.pyi | 18 + stubs/tinycss2/tinycss2/serializer.pyi | 11 + stubs/tinycss2/tinycss2/tokenizer.pyi | 3 + stubs/toml/@tests/stubtest_allowlist.txt | 4 + stubs/toml/METADATA.toml | 2 + stubs/toml/toml/__init__.pyi | 18 + stubs/toml/toml/decoder.pyi | 72 + stubs/toml/toml/encoder.pyi | 49 + stubs/toml/toml/ordered.pyi | 11 + stubs/toml/toml/tz.pyi | 10 + stubs/toposort/METADATA.toml | 2 + stubs/toposort/toposort.pyi | 20 + stubs/tqdm/@tests/stubtest_allowlist.txt | 6 + stubs/tqdm/METADATA.toml | 7 + stubs/tqdm/tqdm/__init__.pyi | 41 + stubs/tqdm/tqdm/_main.pyi | 2 + stubs/tqdm/tqdm/_monitor.pyi | 18 + stubs/tqdm/tqdm/_tqdm.pyi | 2 + stubs/tqdm/tqdm/_tqdm_gui.pyi | 2 + stubs/tqdm/tqdm/_tqdm_notebook.pyi | 2 + stubs/tqdm/tqdm/_tqdm_pandas.pyi | 3 + stubs/tqdm/tqdm/_utils.pyi | 10 + stubs/tqdm/tqdm/asyncio.pyi | 212 + stubs/tqdm/tqdm/auto.pyi | 3 + stubs/tqdm/tqdm/autonotebook.pyi | 3 + stubs/tqdm/tqdm/cli.pyi | 5 + stubs/tqdm/tqdm/contrib/__init__.pyi | 15 + stubs/tqdm/tqdm/contrib/bells.pyi | 3 + stubs/tqdm/tqdm/contrib/concurrent.pyi | 225 + stubs/tqdm/tqdm/contrib/discord.pyi | 110 + stubs/tqdm/tqdm/contrib/itertools.pyi | 48 + stubs/tqdm/tqdm/contrib/logging.pyi | 19 + stubs/tqdm/tqdm/contrib/slack.pyi | 100 + stubs/tqdm/tqdm/contrib/telegram.pyi | 106 + stubs/tqdm/tqdm/contrib/utils_worker.pyi | 15 + stubs/tqdm/tqdm/dask.pyi | 30 + stubs/tqdm/tqdm/gui.pyi | 94 + stubs/tqdm/tqdm/keras.pyi | 21 + stubs/tqdm/tqdm/notebook.pyi | 106 + stubs/tqdm/tqdm/rich.pyi | 110 + stubs/tqdm/tqdm/std.pyi | 299 + stubs/tqdm/tqdm/tk.pyi | 95 + stubs/tqdm/tqdm/utils.pyi | 58 + stubs/tqdm/tqdm/version.pyi | 1 + .../@tests/stubtest_allowlist.txt | 14 + stubs/translationstring/METADATA.toml | 2 + .../translationstring/__init__.pyi | 88 + stubs/ttkthemes/@tests/stubtest_allowlist.txt | 3 + stubs/ttkthemes/METADATA.toml | 2 + stubs/ttkthemes/ttkthemes/__init__.pyi | 7 + stubs/ttkthemes/ttkthemes/_imgops.pyi | 6 + stubs/ttkthemes/ttkthemes/_utils.pyi | 8 + stubs/ttkthemes/ttkthemes/_widget.pyi | 26 + stubs/ttkthemes/ttkthemes/themed_style.pyi | 12 + stubs/ttkthemes/ttkthemes/themed_tk.pyi | 76 + stubs/tzdata/@tests/stubtest_allowlist.txt | 2 + stubs/tzdata/METADATA.toml | 2 + stubs/tzdata/tzdata/__init__.pyi | 4 + stubs/uWSGI/@tests/stubtest_allowlist.txt | 7 + .../@tests/stubtest_allowlist_darwin.txt | 16 + stubs/uWSGI/@tests/uwsgi.ini | 7 + stubs/uWSGI/METADATA.toml | 15 + stubs/uWSGI/uwsgi.pyi | 250 + stubs/uWSGI/uwsgidecorators.pyi | 186 + stubs/unidiff/@tests/stubtest_allowlist.txt | 7 + stubs/unidiff/METADATA.toml | 3 + stubs/unidiff/unidiff/__init__.pyi | 12 + stubs/unidiff/unidiff/__version__.pyi | 1 + stubs/unidiff/unidiff/constants.pyi | 24 + stubs/unidiff/unidiff/errors.pyi | 1 + stubs/unidiff/unidiff/patch.pyi | 118 + stubs/untangle/METADATA.toml | 2 + stubs/untangle/untangle.pyi | 37 + .../@tests/stubtest_allowlist.txt | 3 + stubs/usersettings/METADATA.toml | 2 + stubs/usersettings/usersettings.pyi | 14 + stubs/vobject/@tests/stubtest_allowlist.txt | 16 + stubs/vobject/METADATA.toml | 2 + stubs/vobject/vobject/__init__.pyi | 5 + stubs/vobject/vobject/base.pyi | 166 + stubs/vobject/vobject/behavior.pyi | 33 + stubs/vobject/vobject/change_tz.pyi | 20 + stubs/vobject/vobject/hcalendar.pyi | 6 + stubs/vobject/vobject/icalendar.pyi | 237 + stubs/vobject/vobject/ics_diff.pyi | 13 + stubs/vobject/vobject/vcard.pyi | 117 + stubs/vobject/vobject/win32tz.pyi | 44 + stubs/waitress/@tests/stubtest_allowlist.txt | 4 + stubs/waitress/METADATA.toml | 6 + stubs/waitress/waitress/__init__.pyi | 18 + stubs/waitress/waitress/adjustments.pyi | 64 + stubs/waitress/waitress/buffers.pyi | 57 + stubs/waitress/waitress/channel.pyi | 52 + stubs/waitress/waitress/compat.pyi | 7 + stubs/waitress/waitress/parser.pyi | 44 + stubs/waitress/waitress/proxy_headers.pyi | 37 + stubs/waitress/waitress/receiver.pyi | 31 + stubs/waitress/waitress/rfc7230.pyi | 28 + stubs/waitress/waitress/runner.pyi | 10 + stubs/waitress/waitress/server.pyi | 109 + stubs/waitress/waitress/task.pyi | 72 + stubs/waitress/waitress/trigger.pyi | 31 + stubs/waitress/waitress/utilities.pyi | 68 + stubs/waitress/waitress/wasyncore.pyi | 88 + .../watchpoints/@tests/stubtest_allowlist.txt | 1 + stubs/watchpoints/METADATA.toml | 2 + stubs/watchpoints/watchpoints/__init__.pyi | 10 + stubs/watchpoints/watchpoints/ast_monkey.pyi | 3 + stubs/watchpoints/watchpoints/util.pyi | 6 + stubs/watchpoints/watchpoints/watch.pyi | 68 + .../watchpoints/watchpoints/watch_element.pyi | 57 + stubs/watchpoints/watchpoints/watch_print.pyi | 24 + .../@tests/stubtest_allowlist.txt | 2 + stubs/webencodings/METADATA.toml | 2 + stubs/webencodings/webencodings/__init__.pyi | 33 + stubs/webencodings/webencodings/labels.pyi | 3 + stubs/webencodings/webencodings/mklabels.pyi | 5 + .../webencodings/x_user_defined.pyi | 21 + stubs/whatthepatch/METADATA.toml | 2 + stubs/whatthepatch/whatthepatch/__init__.pyi | 4 + stubs/whatthepatch/whatthepatch/apply.pyi | 8 + .../whatthepatch/whatthepatch/exceptions.pyi | 14 + stubs/whatthepatch/whatthepatch/patch.pyi | 90 + stubs/whatthepatch/whatthepatch/snippets.pyi | 7 + .../workalendar/@tests/stubtest_allowlist.txt | 7 + stubs/workalendar/METADATA.toml | 2 + stubs/workalendar/workalendar/__init__.pyi | 0 .../workalendar/africa/__init__.pyi | 25 + .../workalendar/africa/algeria.pyi | 3 + .../workalendar/workalendar/africa/angola.pyi | 6 + .../workalendar/workalendar/africa/benin.pyi | 6 + .../workalendar/africa/ivory_coast.pyi | 6 + .../workalendar/workalendar/africa/kenya.pyi | 8 + .../workalendar/africa/madagascar.pyi | 3 + .../workalendar/africa/mozambique.pyi | 3 + .../workalendar/africa/nigeria.pyi | 6 + .../workalendar/africa/sao_tome.pyi | 3 + .../workalendar/africa/south_africa.pyi | 6 + .../workalendar/africa/tunisia.pyi | 3 + .../workalendar/america/__init__.pyi | 174 + .../workalendar/america/argentina.pyi | 12 + .../workalendar/america/barbados.pyi | 10 + .../workalendar/america/brazil.pyi | 93 + .../workalendar/america/canada.pyi | 45 + .../workalendar/workalendar/america/chile.pyi | 3 + .../workalendar/america/colombia.pyi | 14 + .../workalendar/america/el_salvador.pyi | 3 + .../workalendar/america/mexico.pyi | 3 + .../workalendar/america/panama.pyi | 3 + .../workalendar/america/paraguay.pyi | 8 + .../workalendar/workalendar/asia/__init__.pyi | 27 + stubs/workalendar/workalendar/asia/china.pyi | 11 + .../workalendar/asia/hong_kong.pyi | 4 + stubs/workalendar/workalendar/asia/israel.pyi | 9 + stubs/workalendar/workalendar/asia/japan.pyi | 4 + .../workalendar/asia/kazakhstan.pyi | 3 + .../workalendar/workalendar/asia/malaysia.pyi | 8 + .../workalendar/asia/philippines.pyi | 3 + stubs/workalendar/workalendar/asia/qatar.pyi | 3 + .../workalendar/asia/singapore.pyi | 7 + .../workalendar/asia/south_korea.pyi | 3 + stubs/workalendar/workalendar/asia/taiwan.pyi | 12 + stubs/workalendar/workalendar/astronomy.pyi | 3 + stubs/workalendar/workalendar/core.pyi | 220 + .../workalendar/europe/__init__.pyi | 279 + .../workalendar/europe/austria.pyi | 3 + .../workalendar/europe/belarus.pyi | 6 + .../workalendar/europe/belgium.pyi | 3 + .../workalendar/europe/bulgaria.pyi | 6 + .../workalendar/europe/cayman_islands.pyi | 13 + .../workalendar/europe/croatia.pyi | 3 + .../workalendar/workalendar/europe/cyprus.pyi | 6 + .../workalendar/europe/czech_republic.pyi | 3 + .../workalendar/europe/denmark.pyi | 6 + .../workalendar/europe/estonia.pyi | 3 + .../europe/european_central_bank.pyi | 3 + .../workalendar/europe/finland.pyi | 8 + .../workalendar/workalendar/europe/france.pyi | 4 + .../workalendar/europe/georgia.pyi | 3 + .../workalendar/europe/germany.pyi | 34 + .../workalendar/workalendar/europe/greece.pyi | 3 + .../workalendar/europe/guernsey.pyi | 9 + .../workalendar/europe/hungary.pyi | 3 + .../workalendar/europe/iceland.pyi | 7 + .../workalendar/europe/ireland.pyi | 7 + .../workalendar/workalendar/europe/italy.pyi | 3 + .../workalendar/workalendar/europe/latvia.pyi | 7 + .../workalendar/europe/lithuania.pyi | 7 + .../workalendar/europe/luxembourg.pyi | 3 + .../workalendar/workalendar/europe/malta.pyi | 3 + .../workalendar/workalendar/europe/monaco.pyi | 3 + .../workalendar/europe/netherlands.pyi | 32 + .../workalendar/workalendar/europe/norway.pyi | 3 + .../workalendar/workalendar/europe/poland.pyi | 3 + .../workalendar/europe/portugal.pyi | 3 + .../workalendar/europe/romania.pyi | 7 + .../workalendar/workalendar/europe/russia.pyi | 7 + .../workalendar/europe/scotland/__init__.pyi | 76 + .../europe/scotland/mixins/__init__.pyi | 65 + .../europe/scotland/mixins/autumn_holiday.pyi | 18 + .../europe/scotland/mixins/fair_holiday.pyi | 27 + .../europe/scotland/mixins/spring_holiday.pyi | 20 + .../europe/scotland/mixins/victoria_day.pyi | 15 + .../workalendar/workalendar/europe/serbia.pyi | 3 + .../workalendar/europe/slovakia.pyi | 3 + .../workalendar/europe/slovenia.pyi | 3 + .../workalendar/workalendar/europe/spain.pyi | 20 + .../workalendar/workalendar/europe/sweden.pyi | 8 + .../workalendar/europe/switzerland.pyi | 40 + .../workalendar/workalendar/europe/turkey.pyi | 6 + .../workalendar/europe/ukraine.pyi | 6 + .../workalendar/europe/united_kingdom.pyi | 12 + stubs/workalendar/workalendar/exceptions.pyi | 6 + .../workalendar/oceania/__init__.pyi | 31 + .../workalendar/oceania/australia.pyi | 48 + .../workalendar/oceania/marshall_islands.pyi | 3 + .../workalendar/oceania/new_zealand.pyi | 7 + .../workalendar/precomputed_astronomy.pyi | 15 + stubs/workalendar/workalendar/registry.pyi | 18 + .../workalendar/registry_tools.pyi | 6 + .../workalendar/skyfield_astronomy.pyi | 15 + .../workalendar/workalendar/usa/__init__.pyi | 142 + stubs/workalendar/workalendar/usa/alabama.pyi | 10 + stubs/workalendar/workalendar/usa/alaska.pyi | 3 + .../workalendar/usa/american_samoa.pyi | 6 + stubs/workalendar/workalendar/usa/arizona.pyi | 3 + .../workalendar/workalendar/usa/arkansas.pyi | 3 + .../workalendar/usa/california.pyi | 11 + .../workalendar/workalendar/usa/colorado.pyi | 3 + .../workalendar/usa/connecticut.pyi | 3 + stubs/workalendar/workalendar/usa/core.pyi | 49 + .../workalendar/workalendar/usa/delaware.pyi | 3 + .../workalendar/usa/district_columbia.pyi | 3 + stubs/workalendar/workalendar/usa/florida.pyi | 25 + stubs/workalendar/workalendar/usa/georgia.pyi | 9 + stubs/workalendar/workalendar/usa/guam.pyi | 3 + stubs/workalendar/workalendar/usa/hawaii.pyi | 6 + stubs/workalendar/workalendar/usa/idaho.pyi | 3 + .../workalendar/workalendar/usa/illinois.pyi | 8 + stubs/workalendar/workalendar/usa/indiana.pyi | 9 + stubs/workalendar/workalendar/usa/iowa.pyi | 3 + stubs/workalendar/workalendar/usa/kansas.pyi | 3 + .../workalendar/workalendar/usa/kentucky.pyi | 3 + .../workalendar/workalendar/usa/louisiana.pyi | 3 + stubs/workalendar/workalendar/usa/maine.pyi | 3 + .../workalendar/workalendar/usa/maryland.pyi | 3 + .../workalendar/usa/massachusetts.pyi | 4 + .../workalendar/workalendar/usa/michigan.pyi | 3 + .../workalendar/workalendar/usa/minnesota.pyi | 3 + .../workalendar/usa/mississippi.pyi | 3 + .../workalendar/workalendar/usa/missouri.pyi | 3 + stubs/workalendar/workalendar/usa/montana.pyi | 3 + .../workalendar/workalendar/usa/nebraska.pyi | 3 + stubs/workalendar/workalendar/usa/nevada.pyi | 3 + .../workalendar/usa/new_hampshire.pyi | 3 + .../workalendar/usa/new_jersey.pyi | 3 + .../workalendar/usa/new_mexico.pyi | 3 + .../workalendar/workalendar/usa/new_york.pyi | 3 + .../workalendar/usa/north_carolina.pyi | 6 + .../workalendar/usa/north_dakota.pyi | 3 + stubs/workalendar/workalendar/usa/ohio.pyi | 3 + .../workalendar/workalendar/usa/oklahoma.pyi | 3 + stubs/workalendar/workalendar/usa/oregon.pyi | 3 + .../workalendar/usa/pennsylvania.pyi | 3 + .../workalendar/usa/rhode_island.pyi | 3 + .../workalendar/usa/south_carolina.pyi | 3 + .../workalendar/usa/south_dakota.pyi | 3 + .../workalendar/workalendar/usa/tennessee.pyi | 3 + stubs/workalendar/workalendar/usa/texas.pyi | 12 + stubs/workalendar/workalendar/usa/utah.pyi | 3 + stubs/workalendar/workalendar/usa/vermont.pyi | 3 + .../workalendar/workalendar/usa/virginia.pyi | 6 + .../workalendar/usa/washington.pyi | 3 + .../workalendar/usa/west_virginia.pyi | 7 + .../workalendar/workalendar/usa/wisconsin.pyi | 3 + stubs/workalendar/workalendar/usa/wyoming.pyi | 3 + stubs/wurlitzer/METADATA.toml | 2 + stubs/wurlitzer/wurlitzer.pyi | 150 + stubs/www-authenticate/METADATA.toml | 2 + stubs/www-authenticate/www_authenticate.pyi | 36 + stubs/xdgenvpy/@tests/stubtest_allowlist.txt | 1 + stubs/xdgenvpy/METADATA.toml | 2 + stubs/xdgenvpy/xdgenvpy/__init__.pyi | 0 stubs/xdgenvpy/xdgenvpy/_defaults.pyi | 7 + stubs/xdgenvpy/xdgenvpy/xdgenv.pyi | 35 + stubs/xlrd/METADATA.toml | 2 + stubs/xlrd/xlrd/__init__.pyi | 41 + stubs/xlrd/xlrd/biffh.pyi | 176 + stubs/xlrd/xlrd/book.pyi | 151 + stubs/xlrd/xlrd/compdoc.pyi | 54 + stubs/xlrd/xlrd/formatting.pyi | 111 + stubs/xlrd/xlrd/formula.pyi | 87 + stubs/xlrd/xlrd/info.pyi | 4 + stubs/xlrd/xlrd/sheet.pyi | 178 + stubs/xlrd/xlrd/timemachine.pyi | 19 + stubs/xlrd/xlrd/xldate.pyi | 24 + stubs/xmldiff/METADATA.toml | 2 + stubs/xmldiff/xmldiff/__init__.pyi | 0 stubs/xmldiff/xmldiff/actions.pyi | 60 + stubs/xmldiff/xmldiff/diff.pyi | 36 + stubs/xmldiff/xmldiff/diff_match_patch.pyi | 58 + stubs/xmldiff/xmldiff/formatting.pyi | 80 + stubs/xmldiff/xmldiff/main.pyi | 72 + stubs/xmldiff/xmldiff/patch.pyi | 16 + stubs/xmldiff/xmldiff/utils.pyi | 16 + .../@tests/test_cases/check_namespaces.py | 6 + stubs/xmltodict/METADATA.toml | 2 + stubs/xmltodict/xmltodict.pyi | 122 + stubs/yt-dlp/@tests/stubtest_allowlist.txt | 31 + stubs/yt-dlp/METADATA.toml | 2 + stubs/yt-dlp/yt_dlp/YoutubeDL.pyi | 128 + stubs/yt-dlp/yt_dlp/__init__.pyi | 251 + stubs/yt-dlp/yt_dlp/aes.pyi | 42 + stubs/yt-dlp/yt_dlp/cache.pyi | 21 + stubs/yt-dlp/yt_dlp/compat/__init__.pyi | 14 + stubs/yt-dlp/yt_dlp/compat/compat_utils.pyi | 21 + stubs/yt-dlp/yt_dlp/compat/imghdr.pyi | 3 + stubs/yt-dlp/yt_dlp/cookies.pyi | 105 + stubs/yt-dlp/yt_dlp/downloader/__init__.pyi | 17 + stubs/yt-dlp/yt_dlp/downloader/bunnycdn.pyi | 17 + stubs/yt-dlp/yt_dlp/downloader/common.pyi | 87 + stubs/yt-dlp/yt_dlp/downloader/dash.pyi | 8 + stubs/yt-dlp/yt_dlp/downloader/external.pyi | 59 + stubs/yt-dlp/yt_dlp/downloader/f4m.pyi | 32 + stubs/yt-dlp/yt_dlp/downloader/fc2.pyi | 3 + stubs/yt-dlp/yt_dlp/downloader/fragment.pyi | 37 + stubs/yt-dlp/yt_dlp/downloader/hls.pyi | 7 + stubs/yt-dlp/yt_dlp/downloader/http.pyi | 3 + stubs/yt-dlp/yt_dlp/downloader/ism.pyi | 29 + stubs/yt-dlp/yt_dlp/downloader/mhtml.pyi | 3 + stubs/yt-dlp/yt_dlp/downloader/niconico.pyi | 3 + stubs/yt-dlp/yt_dlp/downloader/rtmp.pyi | 5 + stubs/yt-dlp/yt_dlp/downloader/soop.pyi | 3 + stubs/yt-dlp/yt_dlp/downloader/websocket.pyi | 11 + .../yt_dlp/downloader/youtube_live_chat.pyi | 9 + stubs/yt-dlp/yt_dlp/extractor/__init__.pyi | 8 + stubs/yt-dlp/yt_dlp/extractor/common.pyi | 970 +++ .../yt_dlp/extractor/commonmistakes.pyi | 12 + .../yt_dlp/extractor/commonprotocols.pyi | 9 + stubs/yt-dlp/yt_dlp/globals.pyi | 31 + stubs/yt-dlp/yt_dlp/jsinterp.pyi | 73 + stubs/yt-dlp/yt_dlp/minicurses.pyi | 23 + stubs/yt-dlp/yt_dlp/networking/__init__.pyi | 9 + stubs/yt-dlp/yt_dlp/networking/_helper.pyi | 46 + stubs/yt-dlp/yt_dlp/networking/common.pyi | 167 + stubs/yt-dlp/yt_dlp/networking/exceptions.pyi | 43 + .../yt-dlp/yt_dlp/networking/impersonate.pyi | 35 + stubs/yt-dlp/yt_dlp/networking/websocket.pyi | 11 + stubs/yt-dlp/yt_dlp/options.pyi | 16 + stubs/yt-dlp/yt_dlp/plugins.pyi | 45 + .../yt-dlp/yt_dlp/postprocessor/__init__.pyi | 7 + stubs/yt-dlp/yt_dlp/postprocessor/common.pyi | 31 + stubs/yt-dlp/yt_dlp/socks.pyi | 74 + stubs/yt-dlp/yt_dlp/update.pyi | 34 + stubs/yt-dlp/yt_dlp/utils/__init__.pyi | 3 + stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi | 16 + stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi | 38 + stubs/yt-dlp/yt_dlp/utils/_legacy.pyi | 59 + stubs/yt-dlp/yt_dlp/utils/_utils.pyi | 738 ++ stubs/yt-dlp/yt_dlp/utils/jslib/__init__.pyi | 0 stubs/yt-dlp/yt_dlp/utils/jslib/devalue.pyi | 9 + stubs/yt-dlp/yt_dlp/utils/networking.pyi | 48 + stubs/yt-dlp/yt_dlp/utils/progress.pyi | 24 + stubs/yt-dlp/yt_dlp/utils/traversal.pyi | 91 + stubs/yt-dlp/yt_dlp/version.pyi | 8 + stubs/yt-dlp/yt_dlp/webvtt.pyi | 49 + stubs/zstd/METADATA.toml | 7 + stubs/zstd/zstd.pyi | 45 + stubs/zxcvbn/@tests/stubtest_allowlist.txt | 1 + stubs/zxcvbn/METADATA.toml | 2 + stubs/zxcvbn/zxcvbn/__init__.pyi | 19 + stubs/zxcvbn/zxcvbn/adjacency_graphs.pyi | 5 + stubs/zxcvbn/zxcvbn/feedback.pyi | 13 + stubs/zxcvbn/zxcvbn/frequency_lists.pyi | 1 + stubs/zxcvbn/zxcvbn/matching.pyi | 98 + stubs/zxcvbn/zxcvbn/scoring.pyi | 50 + stubs/zxcvbn/zxcvbn/time_estimates.pyi | 27 + tests/README.md | 247 + tests/REGRESSION.md | 135 + tests/check_typeshed_structure.py | 200 + tests/get_external_stub_requirements.py | 13 + tests/get_stubtest_system_requirements.py | 9 + tests/mypy_test.py | 551 ++ tests/pyrefly_test.py | 80 + tests/pyright_exclude_list.txt | 3 + tests/pyright_test.py | 48 + tests/regr_test.py | 450 + tests/runtests.py | 271 + tests/stubtest_stdlib.py | 59 + tests/stubtest_third_party.py | 432 + tests/ty_test.py | 85 + tests/typecheck_typeshed.py | 105 + ty.toml | 20 + 5855 files changed, 379046 insertions(+) create mode 100644 .editorconfig create mode 100644 .flake8 create mode 100644 .gitattributes create mode 100644 .github/renovate.json5 create mode 100644 .github/workflows/daily.yml create mode 100644 .github/workflows/meta_tests.yml create mode 100644 .github/workflows/mypy_primer.yml create mode 100644 .github/workflows/mypy_primer_comment.yml create mode 100644 .github/workflows/stubsabot.yml create mode 100644 .github/workflows/stubtest_stdlib.yml create mode 100644 .github/workflows/stubtest_third_party.yml create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 .pre-commit-config.yaml create mode 100644 .vscode/extensions.json create mode 100644 .vscode/settings.default.json create mode 100644 AGENTS.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 MAINTAINERS.md create mode 100644 README.md create mode 100644 lib/pyproject.toml create mode 100644 lib/ts_utils/__init__.py create mode 100644 lib/ts_utils/metadata.py create mode 100644 lib/ts_utils/mypy.py create mode 100644 lib/ts_utils/paths.py create mode 100644 lib/ts_utils/py.typed create mode 100644 lib/ts_utils/py315.py create mode 100644 lib/ts_utils/requirements.py create mode 100644 lib/ts_utils/stubs.py create mode 100644 lib/ts_utils/utils.py create mode 100644 pyproject.toml create mode 100644 pyrefly.toml create mode 100644 pyrightconfig.json create mode 100644 pyrightconfig.scripts_and_tests.json create mode 100644 pyrightconfig.stricter.json create mode 100644 pyrightconfig.testcases.json create mode 100644 requirements-tests.txt create mode 100755 scripts/create_baseline_stubs.py create mode 100644 scripts/install_all_third_party_dependencies.py create mode 100755 scripts/stubsabot.py create mode 100644 scripts/sync_protobuf/_utils.py create mode 100755 scripts/sync_protobuf/google_protobuf.py create mode 100755 scripts/sync_protobuf/s2clientprotocol.py create mode 100755 scripts/sync_protobuf/tensorflow.py create mode 100644 stdlib/@tests/stubtest_allowlists/common.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py310.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py311.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py312.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py313.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py314.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin-py315.txt create mode 100644 stdlib/@tests/stubtest_allowlists/darwin.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py310.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py311.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py312.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py313.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py314.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux-py315.txt create mode 100644 stdlib/@tests/stubtest_allowlists/linux.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py310.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py311.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py312.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py313.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py314.txt create mode 100644 stdlib/@tests/stubtest_allowlists/py315.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py310.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py311.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py312.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py313.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py314.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32-py315.txt create mode 100644 stdlib/@tests/stubtest_allowlists/win32.txt create mode 100644 stdlib/@tests/test_cases/asyncio/check_coroutines.py create mode 100644 stdlib/@tests/test_cases/asyncio/check_gather.py create mode 100644 stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py create mode 100644 stdlib/@tests/test_cases/asyncio/check_task.py create mode 100644 stdlib/@tests/test_cases/asyncio/check_task_factory.py create mode 100644 stdlib/@tests/test_cases/builtins/check_dict.py create mode 100644 stdlib/@tests/test_cases/builtins/check_exception_group-py311.py create mode 100644 stdlib/@tests/test_cases/builtins/check_frozendict-py315.py create mode 100644 stdlib/@tests/test_cases/builtins/check_iteration.py create mode 100644 stdlib/@tests/test_cases/builtins/check_list.py create mode 100644 stdlib/@tests/test_cases/builtins/check_memoryview.py create mode 100644 stdlib/@tests/test_cases/builtins/check_min.py create mode 100644 stdlib/@tests/test_cases/builtins/check_object.py create mode 100644 stdlib/@tests/test_cases/builtins/check_pow.py create mode 100644 stdlib/@tests/test_cases/builtins/check_reversed.py create mode 100644 stdlib/@tests/test_cases/builtins/check_round.py create mode 100644 stdlib/@tests/test_cases/builtins/check_set.py create mode 100644 stdlib/@tests/test_cases/builtins/check_slice.py create mode 100644 stdlib/@tests/test_cases/builtins/check_sum.py create mode 100644 stdlib/@tests/test_cases/builtins/check_tuple.py create mode 100644 stdlib/@tests/test_cases/builtins/check_type.py create mode 100644 stdlib/@tests/test_cases/builtins/check_zip.py create mode 100644 stdlib/@tests/test_cases/check_SupportsGetItem.py create mode 100644 stdlib/@tests/test_cases/check_ast.py create mode 100644 stdlib/@tests/test_cases/check_codecs.py create mode 100644 stdlib/@tests/test_cases/check_compression.py create mode 100644 stdlib/@tests/test_cases/check_concurrent_futures.py create mode 100644 stdlib/@tests/test_cases/check_configparser.py create mode 100644 stdlib/@tests/test_cases/check_contextlib.py create mode 100644 stdlib/@tests/test_cases/check_copy.py create mode 100644 stdlib/@tests/test_cases/check_dataclasses.py create mode 100644 stdlib/@tests/test_cases/check_enum.py create mode 100644 stdlib/@tests/test_cases/check_functools.py create mode 100644 stdlib/@tests/test_cases/check_importlib.py create mode 100644 stdlib/@tests/test_cases/check_importlib_metadata.py create mode 100644 stdlib/@tests/test_cases/check_importlib_resources.py create mode 100644 stdlib/@tests/test_cases/check_inspect.py create mode 100644 stdlib/@tests/test_cases/check_io.py create mode 100644 stdlib/@tests/test_cases/check_logging.py create mode 100644 stdlib/@tests/test_cases/check_mailbox.py create mode 100644 stdlib/@tests/test_cases/check_math.py create mode 100644 stdlib/@tests/test_cases/check_os_path.py create mode 100644 stdlib/@tests/test_cases/check_pathlib.py create mode 100644 stdlib/@tests/test_cases/check_platform.py create mode 100644 stdlib/@tests/test_cases/check_re.py create mode 100644 stdlib/@tests/test_cases/check_socket.py create mode 100644 stdlib/@tests/test_cases/check_sqlite3.py create mode 100644 stdlib/@tests/test_cases/check_tarfile.py create mode 100644 stdlib/@tests/test_cases/check_tempfile.py create mode 100644 stdlib/@tests/test_cases/check_threading.py create mode 100644 stdlib/@tests/test_cases/check_tkinter.py create mode 100644 stdlib/@tests/test_cases/check_turtle.py create mode 100644 stdlib/@tests/test_cases/check_types.py create mode 100644 stdlib/@tests/test_cases/check_unittest.py create mode 100644 stdlib/@tests/test_cases/check_xml.py create mode 100644 stdlib/@tests/test_cases/check_zipfile.py create mode 100644 stdlib/@tests/test_cases/collections/check_defaultdict.py create mode 100644 stdlib/@tests/test_cases/ctypes/check_CDLL.py create mode 100644 stdlib/@tests/test_cases/ctypes/check_pointer.py create mode 100644 stdlib/@tests/test_cases/email/check_message.py create mode 100644 stdlib/@tests/test_cases/email/check_mime.py create mode 100644 stdlib/@tests/test_cases/email/check_parser.py create mode 100644 stdlib/@tests/test_cases/itertools/check_batched.py create mode 100644 stdlib/@tests/test_cases/itertools/check_itertools_recipes.py create mode 100644 stdlib/@tests/test_cases/multiprocessing/check_ctypes.py create mode 100644 stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py create mode 100644 stdlib/@tests/test_cases/sys/check_jit.py create mode 100644 stdlib/@tests/test_cases/typing/check_MutableMapping.py create mode 100644 stdlib/@tests/test_cases/typing/check_all.py create mode 100644 stdlib/@tests/test_cases/typing/check_regression_issue_9296.py create mode 100644 stdlib/@tests/test_cases/typing/check_typing_io.py create mode 100644 stdlib/@tests/test_cases/urllib/check_parse.py create mode 100644 stdlib/VERSIONS create mode 100644 stdlib/__future__.pyi create mode 100644 stdlib/__main__.pyi create mode 100644 stdlib/_ast.pyi create mode 100644 stdlib/_asyncio.pyi create mode 100644 stdlib/_bisect.pyi create mode 100644 stdlib/_blake2.pyi create mode 100644 stdlib/_bz2.pyi create mode 100644 stdlib/_codecs.pyi create mode 100644 stdlib/_collections_abc.pyi create mode 100644 stdlib/_compat_pickle.pyi create mode 100644 stdlib/_compression.pyi create mode 100644 stdlib/_contextvars.pyi create mode 100644 stdlib/_csv.pyi create mode 100644 stdlib/_ctypes.pyi create mode 100644 stdlib/_curses.pyi create mode 100644 stdlib/_curses_panel.pyi create mode 100644 stdlib/_dbm.pyi create mode 100644 stdlib/_decimal.pyi create mode 100644 stdlib/_frozen_importlib.pyi create mode 100644 stdlib/_frozen_importlib_external.pyi create mode 100644 stdlib/_gdbm.pyi create mode 100644 stdlib/_hashlib.pyi create mode 100644 stdlib/_heapq.pyi create mode 100644 stdlib/_imp.pyi create mode 100644 stdlib/_interpchannels.pyi create mode 100644 stdlib/_interpqueues.pyi create mode 100644 stdlib/_interpreters.pyi create mode 100644 stdlib/_io.pyi create mode 100644 stdlib/_json.pyi create mode 100644 stdlib/_locale.pyi create mode 100644 stdlib/_lsprof.pyi create mode 100644 stdlib/_lzma.pyi create mode 100644 stdlib/_markupbase.pyi create mode 100644 stdlib/_msi.pyi create mode 100644 stdlib/_multibytecodec.pyi create mode 100644 stdlib/_operator.pyi create mode 100644 stdlib/_osx_support.pyi create mode 100644 stdlib/_pickle.pyi create mode 100644 stdlib/_posixsubprocess.pyi create mode 100644 stdlib/_py_abc.pyi create mode 100644 stdlib/_pydecimal.pyi create mode 100644 stdlib/_queue.pyi create mode 100644 stdlib/_random.pyi create mode 100644 stdlib/_remote_debugging.pyi create mode 100644 stdlib/_sitebuiltins.pyi create mode 100644 stdlib/_socket.pyi create mode 100644 stdlib/_sqlite3.pyi create mode 100644 stdlib/_ssl.pyi create mode 100644 stdlib/_stat.pyi create mode 100644 stdlib/_struct.pyi create mode 100644 stdlib/_thread.pyi create mode 100644 stdlib/_threading_local.pyi create mode 100644 stdlib/_tkinter.pyi create mode 100644 stdlib/_tracemalloc.pyi create mode 100644 stdlib/_typeshed/README.md create mode 100644 stdlib/_typeshed/__init__.pyi create mode 100644 stdlib/_typeshed/_type_checker_internals.pyi create mode 100644 stdlib/_typeshed/dbapi.pyi create mode 100644 stdlib/_typeshed/importlib.pyi create mode 100644 stdlib/_typeshed/wsgi.pyi create mode 100644 stdlib/_typeshed/xml.pyi create mode 100644 stdlib/_warnings.pyi create mode 100644 stdlib/_weakref.pyi create mode 100644 stdlib/_weakrefset.pyi create mode 100644 stdlib/_winapi.pyi create mode 100644 stdlib/_zstd.pyi create mode 100644 stdlib/abc.pyi create mode 100644 stdlib/aifc.pyi create mode 100644 stdlib/annotationlib.pyi create mode 100644 stdlib/antigravity.pyi create mode 100644 stdlib/argparse.pyi create mode 100644 stdlib/array.pyi create mode 100644 stdlib/ast.pyi create mode 100644 stdlib/asynchat.pyi create mode 100644 stdlib/asyncio/__init__.pyi create mode 100644 stdlib/asyncio/base_events.pyi create mode 100644 stdlib/asyncio/base_futures.pyi create mode 100644 stdlib/asyncio/base_subprocess.pyi create mode 100644 stdlib/asyncio/base_tasks.pyi create mode 100644 stdlib/asyncio/constants.pyi create mode 100644 stdlib/asyncio/coroutines.pyi create mode 100644 stdlib/asyncio/events.pyi create mode 100644 stdlib/asyncio/exceptions.pyi create mode 100644 stdlib/asyncio/format_helpers.pyi create mode 100644 stdlib/asyncio/futures.pyi create mode 100644 stdlib/asyncio/graph.pyi create mode 100644 stdlib/asyncio/locks.pyi create mode 100644 stdlib/asyncio/log.pyi create mode 100644 stdlib/asyncio/mixins.pyi create mode 100644 stdlib/asyncio/proactor_events.pyi create mode 100644 stdlib/asyncio/protocols.pyi create mode 100644 stdlib/asyncio/queues.pyi create mode 100644 stdlib/asyncio/runners.pyi create mode 100644 stdlib/asyncio/selector_events.pyi create mode 100644 stdlib/asyncio/sslproto.pyi create mode 100644 stdlib/asyncio/staggered.pyi create mode 100644 stdlib/asyncio/streams.pyi create mode 100644 stdlib/asyncio/subprocess.pyi create mode 100644 stdlib/asyncio/taskgroups.pyi create mode 100644 stdlib/asyncio/tasks.pyi create mode 100644 stdlib/asyncio/threads.pyi create mode 100644 stdlib/asyncio/timeouts.pyi create mode 100644 stdlib/asyncio/tools.pyi create mode 100644 stdlib/asyncio/transports.pyi create mode 100644 stdlib/asyncio/trsock.pyi create mode 100644 stdlib/asyncio/unix_events.pyi create mode 100644 stdlib/asyncio/windows_events.pyi create mode 100644 stdlib/asyncio/windows_utils.pyi create mode 100644 stdlib/asyncore.pyi create mode 100644 stdlib/atexit.pyi create mode 100644 stdlib/audioop.pyi create mode 100644 stdlib/base64.pyi create mode 100644 stdlib/bdb.pyi create mode 100644 stdlib/binascii.pyi create mode 100644 stdlib/binhex.pyi create mode 100644 stdlib/bisect.pyi create mode 100644 stdlib/builtins.pyi create mode 100644 stdlib/bz2.pyi create mode 100644 stdlib/cProfile.pyi create mode 100644 stdlib/calendar.pyi create mode 100644 stdlib/cgi.pyi create mode 100644 stdlib/cgitb.pyi create mode 100644 stdlib/chunk.pyi create mode 100644 stdlib/cmath.pyi create mode 100644 stdlib/cmd.pyi create mode 100644 stdlib/code.pyi create mode 100644 stdlib/codecs.pyi create mode 100644 stdlib/codeop.pyi create mode 100644 stdlib/collections/__init__.pyi create mode 100644 stdlib/collections/abc.pyi create mode 100644 stdlib/colorsys.pyi create mode 100644 stdlib/compileall.pyi create mode 100644 stdlib/compression/__init__.pyi create mode 100644 stdlib/compression/_common/__init__.pyi create mode 100644 stdlib/compression/_common/_streams.pyi create mode 100644 stdlib/compression/bz2.pyi create mode 100644 stdlib/compression/gzip.pyi create mode 100644 stdlib/compression/lzma.pyi create mode 100644 stdlib/compression/zlib.pyi create mode 100644 stdlib/compression/zstd/__init__.pyi create mode 100644 stdlib/compression/zstd/_zstdfile.pyi create mode 100644 stdlib/concurrent/__init__.pyi create mode 100644 stdlib/concurrent/futures/__init__.pyi create mode 100644 stdlib/concurrent/futures/_base.pyi create mode 100644 stdlib/concurrent/futures/interpreter.pyi create mode 100644 stdlib/concurrent/futures/process.pyi create mode 100644 stdlib/concurrent/futures/thread.pyi create mode 100644 stdlib/concurrent/interpreters/__init__.pyi create mode 100644 stdlib/concurrent/interpreters/_crossinterp.pyi create mode 100644 stdlib/concurrent/interpreters/_queues.pyi create mode 100644 stdlib/configparser.pyi create mode 100644 stdlib/contextlib.pyi create mode 100644 stdlib/contextvars.pyi create mode 100644 stdlib/copy.pyi create mode 100644 stdlib/copyreg.pyi create mode 100644 stdlib/crypt.pyi create mode 100644 stdlib/csv.pyi create mode 100644 stdlib/ctypes/__init__.pyi create mode 100644 stdlib/ctypes/_endian.pyi create mode 100644 stdlib/ctypes/macholib/__init__.pyi create mode 100644 stdlib/ctypes/macholib/dyld.pyi create mode 100644 stdlib/ctypes/macholib/dylib.pyi create mode 100644 stdlib/ctypes/macholib/framework.pyi create mode 100644 stdlib/ctypes/util.pyi create mode 100644 stdlib/ctypes/wintypes.pyi create mode 100644 stdlib/curses/__init__.pyi create mode 100644 stdlib/curses/ascii.pyi create mode 100644 stdlib/curses/has_key.pyi create mode 100644 stdlib/curses/panel.pyi create mode 100644 stdlib/curses/textpad.pyi create mode 100644 stdlib/dataclasses.pyi create mode 100644 stdlib/datetime.pyi create mode 100644 stdlib/dbm/__init__.pyi create mode 100644 stdlib/dbm/dumb.pyi create mode 100644 stdlib/dbm/gnu.pyi create mode 100644 stdlib/dbm/ndbm.pyi create mode 100644 stdlib/dbm/sqlite3.pyi create mode 100644 stdlib/decimal.pyi create mode 100644 stdlib/difflib.pyi create mode 100644 stdlib/dis.pyi create mode 100644 stdlib/distutils/__init__.pyi create mode 100644 stdlib/distutils/_msvccompiler.pyi create mode 100644 stdlib/distutils/archive_util.pyi create mode 100644 stdlib/distutils/bcppcompiler.pyi create mode 100644 stdlib/distutils/ccompiler.pyi create mode 100644 stdlib/distutils/cmd.pyi create mode 100644 stdlib/distutils/command/__init__.pyi create mode 100644 stdlib/distutils/command/bdist.pyi create mode 100644 stdlib/distutils/command/bdist_dumb.pyi create mode 100644 stdlib/distutils/command/bdist_msi.pyi create mode 100644 stdlib/distutils/command/bdist_packager.pyi create mode 100644 stdlib/distutils/command/bdist_rpm.pyi create mode 100644 stdlib/distutils/command/build.pyi create mode 100644 stdlib/distutils/command/build_clib.pyi create mode 100644 stdlib/distutils/command/build_ext.pyi create mode 100644 stdlib/distutils/command/build_py.pyi create mode 100644 stdlib/distutils/command/build_scripts.pyi create mode 100644 stdlib/distutils/command/check.pyi create mode 100644 stdlib/distutils/command/clean.pyi create mode 100644 stdlib/distutils/command/config.pyi create mode 100644 stdlib/distutils/command/install.pyi create mode 100644 stdlib/distutils/command/install_data.pyi create mode 100644 stdlib/distutils/command/install_egg_info.pyi create mode 100644 stdlib/distutils/command/install_headers.pyi create mode 100644 stdlib/distutils/command/install_lib.pyi create mode 100644 stdlib/distutils/command/install_scripts.pyi create mode 100644 stdlib/distutils/command/register.pyi create mode 100644 stdlib/distutils/command/sdist.pyi create mode 100644 stdlib/distutils/command/upload.pyi create mode 100644 stdlib/distutils/config.pyi create mode 100644 stdlib/distutils/core.pyi create mode 100644 stdlib/distutils/cygwinccompiler.pyi create mode 100644 stdlib/distutils/debug.pyi create mode 100644 stdlib/distutils/dep_util.pyi create mode 100644 stdlib/distutils/dir_util.pyi create mode 100644 stdlib/distutils/dist.pyi create mode 100644 stdlib/distutils/errors.pyi create mode 100644 stdlib/distutils/extension.pyi create mode 100644 stdlib/distutils/fancy_getopt.pyi create mode 100644 stdlib/distutils/file_util.pyi create mode 100644 stdlib/distutils/filelist.pyi create mode 100644 stdlib/distutils/log.pyi create mode 100644 stdlib/distutils/msvccompiler.pyi create mode 100644 stdlib/distutils/spawn.pyi create mode 100644 stdlib/distutils/sysconfig.pyi create mode 100644 stdlib/distutils/text_file.pyi create mode 100644 stdlib/distutils/unixccompiler.pyi create mode 100644 stdlib/distutils/util.pyi create mode 100644 stdlib/distutils/version.pyi create mode 100644 stdlib/doctest.pyi create mode 100644 stdlib/email/__init__.pyi create mode 100644 stdlib/email/_header_value_parser.pyi create mode 100644 stdlib/email/_policybase.pyi create mode 100644 stdlib/email/base64mime.pyi create mode 100644 stdlib/email/charset.pyi create mode 100644 stdlib/email/contentmanager.pyi create mode 100644 stdlib/email/encoders.pyi create mode 100644 stdlib/email/errors.pyi create mode 100644 stdlib/email/feedparser.pyi create mode 100644 stdlib/email/generator.pyi create mode 100644 stdlib/email/header.pyi create mode 100644 stdlib/email/headerregistry.pyi create mode 100644 stdlib/email/iterators.pyi create mode 100644 stdlib/email/message.pyi create mode 100644 stdlib/email/mime/__init__.pyi create mode 100644 stdlib/email/mime/application.pyi create mode 100644 stdlib/email/mime/audio.pyi create mode 100644 stdlib/email/mime/base.pyi create mode 100644 stdlib/email/mime/image.pyi create mode 100644 stdlib/email/mime/message.pyi create mode 100644 stdlib/email/mime/multipart.pyi create mode 100644 stdlib/email/mime/nonmultipart.pyi create mode 100644 stdlib/email/mime/text.pyi create mode 100644 stdlib/email/parser.pyi create mode 100644 stdlib/email/policy.pyi create mode 100644 stdlib/email/quoprimime.pyi create mode 100644 stdlib/email/utils.pyi create mode 100644 stdlib/encodings/__init__.pyi create mode 100644 stdlib/encodings/aliases.pyi create mode 100644 stdlib/encodings/ascii.pyi create mode 100644 stdlib/encodings/base64_codec.pyi create mode 100644 stdlib/encodings/big5.pyi create mode 100644 stdlib/encodings/big5hkscs.pyi create mode 100644 stdlib/encodings/bz2_codec.pyi create mode 100644 stdlib/encodings/charmap.pyi create mode 100644 stdlib/encodings/cp037.pyi create mode 100644 stdlib/encodings/cp1006.pyi create mode 100644 stdlib/encodings/cp1026.pyi create mode 100644 stdlib/encodings/cp1125.pyi create mode 100644 stdlib/encodings/cp1140.pyi create mode 100644 stdlib/encodings/cp1250.pyi create mode 100644 stdlib/encodings/cp1251.pyi create mode 100644 stdlib/encodings/cp1252.pyi create mode 100644 stdlib/encodings/cp1253.pyi create mode 100644 stdlib/encodings/cp1254.pyi create mode 100644 stdlib/encodings/cp1255.pyi create mode 100644 stdlib/encodings/cp1256.pyi create mode 100644 stdlib/encodings/cp1257.pyi create mode 100644 stdlib/encodings/cp1258.pyi create mode 100644 stdlib/encodings/cp273.pyi create mode 100644 stdlib/encodings/cp424.pyi create mode 100644 stdlib/encodings/cp437.pyi create mode 100644 stdlib/encodings/cp500.pyi create mode 100644 stdlib/encodings/cp720.pyi create mode 100644 stdlib/encodings/cp737.pyi create mode 100644 stdlib/encodings/cp775.pyi create mode 100644 stdlib/encodings/cp850.pyi create mode 100644 stdlib/encodings/cp852.pyi create mode 100644 stdlib/encodings/cp855.pyi create mode 100644 stdlib/encodings/cp856.pyi create mode 100644 stdlib/encodings/cp857.pyi create mode 100644 stdlib/encodings/cp858.pyi create mode 100644 stdlib/encodings/cp860.pyi create mode 100644 stdlib/encodings/cp861.pyi create mode 100644 stdlib/encodings/cp862.pyi create mode 100644 stdlib/encodings/cp863.pyi create mode 100644 stdlib/encodings/cp864.pyi create mode 100644 stdlib/encodings/cp865.pyi create mode 100644 stdlib/encodings/cp866.pyi create mode 100644 stdlib/encodings/cp869.pyi create mode 100644 stdlib/encodings/cp874.pyi create mode 100644 stdlib/encodings/cp875.pyi create mode 100644 stdlib/encodings/cp932.pyi create mode 100644 stdlib/encodings/cp949.pyi create mode 100644 stdlib/encodings/cp950.pyi create mode 100644 stdlib/encodings/euc_jis_2004.pyi create mode 100644 stdlib/encodings/euc_jisx0213.pyi create mode 100644 stdlib/encodings/euc_jp.pyi create mode 100644 stdlib/encodings/euc_kr.pyi create mode 100644 stdlib/encodings/gb18030.pyi create mode 100644 stdlib/encodings/gb2312.pyi create mode 100644 stdlib/encodings/gbk.pyi create mode 100644 stdlib/encodings/hex_codec.pyi create mode 100644 stdlib/encodings/hp_roman8.pyi create mode 100644 stdlib/encodings/hz.pyi create mode 100644 stdlib/encodings/idna.pyi create mode 100644 stdlib/encodings/iso2022_jp.pyi create mode 100644 stdlib/encodings/iso2022_jp_1.pyi create mode 100644 stdlib/encodings/iso2022_jp_2.pyi create mode 100644 stdlib/encodings/iso2022_jp_2004.pyi create mode 100644 stdlib/encodings/iso2022_jp_3.pyi create mode 100644 stdlib/encodings/iso2022_jp_ext.pyi create mode 100644 stdlib/encodings/iso2022_kr.pyi create mode 100644 stdlib/encodings/iso8859_1.pyi create mode 100644 stdlib/encodings/iso8859_10.pyi create mode 100644 stdlib/encodings/iso8859_11.pyi create mode 100644 stdlib/encodings/iso8859_13.pyi create mode 100644 stdlib/encodings/iso8859_14.pyi create mode 100644 stdlib/encodings/iso8859_15.pyi create mode 100644 stdlib/encodings/iso8859_16.pyi create mode 100644 stdlib/encodings/iso8859_2.pyi create mode 100644 stdlib/encodings/iso8859_3.pyi create mode 100644 stdlib/encodings/iso8859_4.pyi create mode 100644 stdlib/encodings/iso8859_5.pyi create mode 100644 stdlib/encodings/iso8859_6.pyi create mode 100644 stdlib/encodings/iso8859_7.pyi create mode 100644 stdlib/encodings/iso8859_8.pyi create mode 100644 stdlib/encodings/iso8859_9.pyi create mode 100644 stdlib/encodings/johab.pyi create mode 100644 stdlib/encodings/koi8_r.pyi create mode 100644 stdlib/encodings/koi8_t.pyi create mode 100644 stdlib/encodings/koi8_u.pyi create mode 100644 stdlib/encodings/kz1048.pyi create mode 100644 stdlib/encodings/latin_1.pyi create mode 100644 stdlib/encodings/mac_arabic.pyi create mode 100644 stdlib/encodings/mac_croatian.pyi create mode 100644 stdlib/encodings/mac_cyrillic.pyi create mode 100644 stdlib/encodings/mac_farsi.pyi create mode 100644 stdlib/encodings/mac_greek.pyi create mode 100644 stdlib/encodings/mac_iceland.pyi create mode 100644 stdlib/encodings/mac_latin2.pyi create mode 100644 stdlib/encodings/mac_roman.pyi create mode 100644 stdlib/encodings/mac_romanian.pyi create mode 100644 stdlib/encodings/mac_turkish.pyi create mode 100644 stdlib/encodings/mbcs.pyi create mode 100644 stdlib/encodings/oem.pyi create mode 100644 stdlib/encodings/palmos.pyi create mode 100644 stdlib/encodings/ptcp154.pyi create mode 100644 stdlib/encodings/punycode.pyi create mode 100644 stdlib/encodings/quopri_codec.pyi create mode 100644 stdlib/encodings/raw_unicode_escape.pyi create mode 100644 stdlib/encodings/rot_13.pyi create mode 100644 stdlib/encodings/shift_jis.pyi create mode 100644 stdlib/encodings/shift_jis_2004.pyi create mode 100644 stdlib/encodings/shift_jisx0213.pyi create mode 100644 stdlib/encodings/tis_620.pyi create mode 100644 stdlib/encodings/undefined.pyi create mode 100644 stdlib/encodings/unicode_escape.pyi create mode 100644 stdlib/encodings/utf_16.pyi create mode 100644 stdlib/encodings/utf_16_be.pyi create mode 100644 stdlib/encodings/utf_16_le.pyi create mode 100644 stdlib/encodings/utf_32.pyi create mode 100644 stdlib/encodings/utf_32_be.pyi create mode 100644 stdlib/encodings/utf_32_le.pyi create mode 100644 stdlib/encodings/utf_7.pyi create mode 100644 stdlib/encodings/utf_8.pyi create mode 100644 stdlib/encodings/utf_8_sig.pyi create mode 100644 stdlib/encodings/uu_codec.pyi create mode 100644 stdlib/encodings/zlib_codec.pyi create mode 100644 stdlib/ensurepip/__init__.pyi create mode 100644 stdlib/enum.pyi create mode 100644 stdlib/errno.pyi create mode 100644 stdlib/faulthandler.pyi create mode 100644 stdlib/fcntl.pyi create mode 100644 stdlib/filecmp.pyi create mode 100644 stdlib/fileinput.pyi create mode 100644 stdlib/fnmatch.pyi create mode 100644 stdlib/fractions.pyi create mode 100644 stdlib/ftplib.pyi create mode 100644 stdlib/functools.pyi create mode 100644 stdlib/gc.pyi create mode 100644 stdlib/genericpath.pyi create mode 100644 stdlib/getopt.pyi create mode 100644 stdlib/getpass.pyi create mode 100644 stdlib/gettext.pyi create mode 100644 stdlib/glob.pyi create mode 100644 stdlib/graphlib.pyi create mode 100644 stdlib/grp.pyi create mode 100644 stdlib/gzip.pyi create mode 100644 stdlib/hashlib.pyi create mode 100644 stdlib/heapq.pyi create mode 100644 stdlib/hmac.pyi create mode 100644 stdlib/html/__init__.pyi create mode 100644 stdlib/html/entities.pyi create mode 100644 stdlib/html/parser.pyi create mode 100644 stdlib/http/__init__.pyi create mode 100644 stdlib/http/client.pyi create mode 100644 stdlib/http/cookiejar.pyi create mode 100644 stdlib/http/cookies.pyi create mode 100644 stdlib/http/server.pyi create mode 100644 stdlib/imaplib.pyi create mode 100644 stdlib/imghdr.pyi create mode 100644 stdlib/imp.pyi create mode 100644 stdlib/importlib/__init__.pyi create mode 100644 stdlib/importlib/_abc.pyi create mode 100644 stdlib/importlib/_bootstrap.pyi create mode 100644 stdlib/importlib/_bootstrap_external.pyi create mode 100644 stdlib/importlib/abc.pyi create mode 100644 stdlib/importlib/machinery.pyi create mode 100644 stdlib/importlib/metadata/__init__.pyi create mode 100644 stdlib/importlib/metadata/_meta.pyi create mode 100644 stdlib/importlib/metadata/diagnose.pyi create mode 100644 stdlib/importlib/readers.pyi create mode 100644 stdlib/importlib/resources/__init__.pyi create mode 100644 stdlib/importlib/resources/_common.pyi create mode 100644 stdlib/importlib/resources/_functional.pyi create mode 100644 stdlib/importlib/resources/abc.pyi create mode 100644 stdlib/importlib/resources/readers.pyi create mode 100644 stdlib/importlib/resources/simple.pyi create mode 100644 stdlib/importlib/simple.pyi create mode 100644 stdlib/importlib/util.pyi create mode 100644 stdlib/inspect.pyi create mode 100644 stdlib/io.pyi create mode 100644 stdlib/ipaddress.pyi create mode 100644 stdlib/itertools.pyi create mode 100644 stdlib/json/__init__.pyi create mode 100644 stdlib/json/decoder.pyi create mode 100644 stdlib/json/encoder.pyi create mode 100644 stdlib/json/scanner.pyi create mode 100644 stdlib/json/tool.pyi create mode 100644 stdlib/keyword.pyi create mode 100644 stdlib/lib2to3/__init__.pyi create mode 100644 stdlib/lib2to3/btm_matcher.pyi create mode 100644 stdlib/lib2to3/fixer_base.pyi create mode 100644 stdlib/lib2to3/fixes/__init__.pyi create mode 100644 stdlib/lib2to3/fixes/fix_apply.pyi create mode 100644 stdlib/lib2to3/fixes/fix_asserts.pyi create mode 100644 stdlib/lib2to3/fixes/fix_basestring.pyi create mode 100644 stdlib/lib2to3/fixes/fix_buffer.pyi create mode 100644 stdlib/lib2to3/fixes/fix_dict.pyi create mode 100644 stdlib/lib2to3/fixes/fix_except.pyi create mode 100644 stdlib/lib2to3/fixes/fix_exec.pyi create mode 100644 stdlib/lib2to3/fixes/fix_execfile.pyi create mode 100644 stdlib/lib2to3/fixes/fix_exitfunc.pyi create mode 100644 stdlib/lib2to3/fixes/fix_filter.pyi create mode 100644 stdlib/lib2to3/fixes/fix_funcattrs.pyi create mode 100644 stdlib/lib2to3/fixes/fix_future.pyi create mode 100644 stdlib/lib2to3/fixes/fix_getcwdu.pyi create mode 100644 stdlib/lib2to3/fixes/fix_has_key.pyi create mode 100644 stdlib/lib2to3/fixes/fix_idioms.pyi create mode 100644 stdlib/lib2to3/fixes/fix_import.pyi create mode 100644 stdlib/lib2to3/fixes/fix_imports.pyi create mode 100644 stdlib/lib2to3/fixes/fix_imports2.pyi create mode 100644 stdlib/lib2to3/fixes/fix_input.pyi create mode 100644 stdlib/lib2to3/fixes/fix_intern.pyi create mode 100644 stdlib/lib2to3/fixes/fix_isinstance.pyi create mode 100644 stdlib/lib2to3/fixes/fix_itertools.pyi create mode 100644 stdlib/lib2to3/fixes/fix_itertools_imports.pyi create mode 100644 stdlib/lib2to3/fixes/fix_long.pyi create mode 100644 stdlib/lib2to3/fixes/fix_map.pyi create mode 100644 stdlib/lib2to3/fixes/fix_metaclass.pyi create mode 100644 stdlib/lib2to3/fixes/fix_methodattrs.pyi create mode 100644 stdlib/lib2to3/fixes/fix_ne.pyi create mode 100644 stdlib/lib2to3/fixes/fix_next.pyi create mode 100644 stdlib/lib2to3/fixes/fix_nonzero.pyi create mode 100644 stdlib/lib2to3/fixes/fix_numliterals.pyi create mode 100644 stdlib/lib2to3/fixes/fix_operator.pyi create mode 100644 stdlib/lib2to3/fixes/fix_paren.pyi create mode 100644 stdlib/lib2to3/fixes/fix_print.pyi create mode 100644 stdlib/lib2to3/fixes/fix_raise.pyi create mode 100644 stdlib/lib2to3/fixes/fix_raw_input.pyi create mode 100644 stdlib/lib2to3/fixes/fix_reduce.pyi create mode 100644 stdlib/lib2to3/fixes/fix_reload.pyi create mode 100644 stdlib/lib2to3/fixes/fix_renames.pyi create mode 100644 stdlib/lib2to3/fixes/fix_repr.pyi create mode 100644 stdlib/lib2to3/fixes/fix_set_literal.pyi create mode 100644 stdlib/lib2to3/fixes/fix_standarderror.pyi create mode 100644 stdlib/lib2to3/fixes/fix_sys_exc.pyi create mode 100644 stdlib/lib2to3/fixes/fix_throw.pyi create mode 100644 stdlib/lib2to3/fixes/fix_tuple_params.pyi create mode 100644 stdlib/lib2to3/fixes/fix_types.pyi create mode 100644 stdlib/lib2to3/fixes/fix_unicode.pyi create mode 100644 stdlib/lib2to3/fixes/fix_urllib.pyi create mode 100644 stdlib/lib2to3/fixes/fix_ws_comma.pyi create mode 100644 stdlib/lib2to3/fixes/fix_xrange.pyi create mode 100644 stdlib/lib2to3/fixes/fix_xreadlines.pyi create mode 100644 stdlib/lib2to3/fixes/fix_zip.pyi create mode 100644 stdlib/lib2to3/main.pyi create mode 100644 stdlib/lib2to3/pgen2/__init__.pyi create mode 100644 stdlib/lib2to3/pgen2/driver.pyi create mode 100644 stdlib/lib2to3/pgen2/grammar.pyi create mode 100644 stdlib/lib2to3/pgen2/literals.pyi create mode 100644 stdlib/lib2to3/pgen2/parse.pyi create mode 100644 stdlib/lib2to3/pgen2/pgen.pyi create mode 100644 stdlib/lib2to3/pgen2/token.pyi create mode 100644 stdlib/lib2to3/pgen2/tokenize.pyi create mode 100644 stdlib/lib2to3/pygram.pyi create mode 100644 stdlib/lib2to3/pytree.pyi create mode 100644 stdlib/lib2to3/refactor.pyi create mode 100644 stdlib/linecache.pyi create mode 100644 stdlib/locale.pyi create mode 100644 stdlib/logging/__init__.pyi create mode 100644 stdlib/logging/config.pyi create mode 100644 stdlib/logging/handlers.pyi create mode 100644 stdlib/lzma.pyi create mode 100644 stdlib/mailbox.pyi create mode 100644 stdlib/mailcap.pyi create mode 100644 stdlib/marshal.pyi create mode 100644 stdlib/math/__init__.pyi create mode 100644 stdlib/math/integer.pyi create mode 100644 stdlib/mimetypes.pyi create mode 100644 stdlib/mmap.pyi create mode 100644 stdlib/modulefinder.pyi create mode 100644 stdlib/msilib/__init__.pyi create mode 100644 stdlib/msilib/schema.pyi create mode 100644 stdlib/msilib/sequence.pyi create mode 100644 stdlib/msilib/text.pyi create mode 100644 stdlib/msvcrt.pyi create mode 100644 stdlib/multiprocessing/__init__.pyi create mode 100644 stdlib/multiprocessing/connection.pyi create mode 100644 stdlib/multiprocessing/context.pyi create mode 100644 stdlib/multiprocessing/dummy/__init__.pyi create mode 100644 stdlib/multiprocessing/dummy/connection.pyi create mode 100644 stdlib/multiprocessing/forkserver.pyi create mode 100644 stdlib/multiprocessing/heap.pyi create mode 100644 stdlib/multiprocessing/managers.pyi create mode 100644 stdlib/multiprocessing/pool.pyi create mode 100644 stdlib/multiprocessing/popen_fork.pyi create mode 100644 stdlib/multiprocessing/popen_forkserver.pyi create mode 100644 stdlib/multiprocessing/popen_spawn_posix.pyi create mode 100644 stdlib/multiprocessing/popen_spawn_win32.pyi create mode 100644 stdlib/multiprocessing/process.pyi create mode 100644 stdlib/multiprocessing/queues.pyi create mode 100644 stdlib/multiprocessing/reduction.pyi create mode 100644 stdlib/multiprocessing/resource_sharer.pyi create mode 100644 stdlib/multiprocessing/resource_tracker.pyi create mode 100644 stdlib/multiprocessing/shared_memory.pyi create mode 100644 stdlib/multiprocessing/sharedctypes.pyi create mode 100644 stdlib/multiprocessing/spawn.pyi create mode 100644 stdlib/multiprocessing/synchronize.pyi create mode 100644 stdlib/multiprocessing/util.pyi create mode 100644 stdlib/netrc.pyi create mode 100644 stdlib/nis.pyi create mode 100644 stdlib/nntplib.pyi create mode 100644 stdlib/nt.pyi create mode 100644 stdlib/ntpath.pyi create mode 100644 stdlib/nturl2path.pyi create mode 100644 stdlib/numbers.pyi create mode 100644 stdlib/opcode.pyi create mode 100644 stdlib/operator.pyi create mode 100644 stdlib/optparse.pyi create mode 100644 stdlib/os/__init__.pyi create mode 100644 stdlib/os/path.pyi create mode 100644 stdlib/ossaudiodev.pyi create mode 100644 stdlib/pathlib/__init__.pyi create mode 100644 stdlib/pathlib/types.pyi create mode 100644 stdlib/pdb.pyi create mode 100644 stdlib/pickle.pyi create mode 100644 stdlib/pickletools.pyi create mode 100644 stdlib/pipes.pyi create mode 100644 stdlib/pkgutil.pyi create mode 100644 stdlib/platform.pyi create mode 100644 stdlib/plistlib.pyi create mode 100644 stdlib/poplib.pyi create mode 100644 stdlib/posix.pyi create mode 100644 stdlib/posixpath.pyi create mode 100644 stdlib/pprint.pyi create mode 100644 stdlib/profile.pyi create mode 100644 stdlib/profiling/__init__.pyi create mode 100644 stdlib/profiling/sampling/__init__.pyi create mode 100644 stdlib/profiling/sampling/collector.pyi create mode 100644 stdlib/profiling/sampling/gecko_collector.pyi create mode 100644 stdlib/profiling/sampling/heatmap_collector.pyi create mode 100644 stdlib/profiling/sampling/jsonl_collector.pyi create mode 100644 stdlib/profiling/sampling/pstats_collector.pyi create mode 100644 stdlib/profiling/sampling/stack_collector.pyi create mode 100644 stdlib/profiling/sampling/string_table.pyi create mode 100644 stdlib/profiling/tracing.pyi create mode 100644 stdlib/pstats.pyi create mode 100644 stdlib/pty.pyi create mode 100644 stdlib/pwd.pyi create mode 100644 stdlib/py_compile.pyi create mode 100644 stdlib/pyclbr.pyi create mode 100644 stdlib/pydoc.pyi create mode 100644 stdlib/pydoc_data/__init__.pyi create mode 100644 stdlib/pydoc_data/module_docs.pyi create mode 100644 stdlib/pydoc_data/topics.pyi create mode 100644 stdlib/pyexpat/__init__.pyi create mode 100644 stdlib/pyexpat/errors.pyi create mode 100644 stdlib/pyexpat/model.pyi create mode 100644 stdlib/queue.pyi create mode 100644 stdlib/quopri.pyi create mode 100644 stdlib/random.pyi create mode 100644 stdlib/re.pyi create mode 100644 stdlib/readline.pyi create mode 100644 stdlib/reprlib.pyi create mode 100644 stdlib/resource.pyi create mode 100644 stdlib/rlcompleter.pyi create mode 100644 stdlib/runpy.pyi create mode 100644 stdlib/sched.pyi create mode 100644 stdlib/secrets.pyi create mode 100644 stdlib/select.pyi create mode 100644 stdlib/selectors.pyi create mode 100644 stdlib/shelve.pyi create mode 100644 stdlib/shlex.pyi create mode 100644 stdlib/shutil.pyi create mode 100644 stdlib/signal.pyi create mode 100644 stdlib/site.pyi create mode 100644 stdlib/smtpd.pyi create mode 100644 stdlib/smtplib.pyi create mode 100644 stdlib/sndhdr.pyi create mode 100644 stdlib/socket.pyi create mode 100644 stdlib/socketserver.pyi create mode 100644 stdlib/spwd.pyi create mode 100644 stdlib/sqlite3/__init__.pyi create mode 100644 stdlib/sqlite3/dbapi2.pyi create mode 100644 stdlib/sqlite3/dump.pyi create mode 100644 stdlib/sre_compile.pyi create mode 100644 stdlib/sre_constants.pyi create mode 100644 stdlib/sre_parse.pyi create mode 100644 stdlib/ssl.pyi create mode 100644 stdlib/stat.pyi create mode 100644 stdlib/statistics.pyi create mode 100644 stdlib/string/__init__.pyi create mode 100644 stdlib/string/templatelib.pyi create mode 100644 stdlib/stringprep.pyi create mode 100644 stdlib/struct.pyi create mode 100644 stdlib/subprocess.pyi create mode 100644 stdlib/sunau.pyi create mode 100644 stdlib/symtable.pyi create mode 100644 stdlib/sys/__init__.pyi create mode 100644 stdlib/sys/__jit.pyi create mode 100644 stdlib/sys/_monitoring.pyi create mode 100644 stdlib/sysconfig.pyi create mode 100644 stdlib/syslog.pyi create mode 100644 stdlib/tabnanny.pyi create mode 100644 stdlib/tarfile.pyi create mode 100644 stdlib/telnetlib.pyi create mode 100644 stdlib/tempfile.pyi create mode 100644 stdlib/termios.pyi create mode 100644 stdlib/textwrap.pyi create mode 100644 stdlib/this.pyi create mode 100644 stdlib/threading.pyi create mode 100644 stdlib/time.pyi create mode 100644 stdlib/timeit.pyi create mode 100644 stdlib/tkinter/__init__.pyi create mode 100644 stdlib/tkinter/colorchooser.pyi create mode 100644 stdlib/tkinter/commondialog.pyi create mode 100644 stdlib/tkinter/constants.pyi create mode 100644 stdlib/tkinter/dialog.pyi create mode 100644 stdlib/tkinter/dnd.pyi create mode 100644 stdlib/tkinter/filedialog.pyi create mode 100644 stdlib/tkinter/font.pyi create mode 100644 stdlib/tkinter/messagebox.pyi create mode 100644 stdlib/tkinter/scrolledtext.pyi create mode 100644 stdlib/tkinter/simpledialog.pyi create mode 100644 stdlib/tkinter/tix.pyi create mode 100644 stdlib/tkinter/ttk.pyi create mode 100644 stdlib/token.pyi create mode 100644 stdlib/tokenize.pyi create mode 100644 stdlib/tomllib.pyi create mode 100644 stdlib/trace.pyi create mode 100644 stdlib/traceback.pyi create mode 100644 stdlib/tracemalloc.pyi create mode 100644 stdlib/tty.pyi create mode 100644 stdlib/turtle.pyi create mode 100644 stdlib/types.pyi create mode 100644 stdlib/typing.pyi create mode 100644 stdlib/typing_extensions.pyi create mode 100644 stdlib/unicodedata.pyi create mode 100644 stdlib/unittest/__init__.pyi create mode 100644 stdlib/unittest/_log.pyi create mode 100644 stdlib/unittest/async_case.pyi create mode 100644 stdlib/unittest/case.pyi create mode 100644 stdlib/unittest/loader.pyi create mode 100644 stdlib/unittest/main.pyi create mode 100644 stdlib/unittest/mock.pyi create mode 100644 stdlib/unittest/result.pyi create mode 100644 stdlib/unittest/runner.pyi create mode 100644 stdlib/unittest/signals.pyi create mode 100644 stdlib/unittest/suite.pyi create mode 100644 stdlib/unittest/util.pyi create mode 100644 stdlib/urllib/__init__.pyi create mode 100644 stdlib/urllib/error.pyi create mode 100644 stdlib/urllib/parse.pyi create mode 100644 stdlib/urllib/request.pyi create mode 100644 stdlib/urllib/response.pyi create mode 100644 stdlib/urllib/robotparser.pyi create mode 100644 stdlib/uu.pyi create mode 100644 stdlib/uuid.pyi create mode 100644 stdlib/venv/__init__.pyi create mode 100644 stdlib/warnings.pyi create mode 100644 stdlib/wave.pyi create mode 100644 stdlib/weakref.pyi create mode 100644 stdlib/webbrowser.pyi create mode 100644 stdlib/winreg.pyi create mode 100644 stdlib/winsound.pyi create mode 100644 stdlib/wsgiref/__init__.pyi create mode 100644 stdlib/wsgiref/handlers.pyi create mode 100644 stdlib/wsgiref/headers.pyi create mode 100644 stdlib/wsgiref/simple_server.pyi create mode 100644 stdlib/wsgiref/types.pyi create mode 100644 stdlib/wsgiref/util.pyi create mode 100644 stdlib/wsgiref/validate.pyi create mode 100644 stdlib/xdrlib.pyi create mode 100644 stdlib/xml/__init__.pyi create mode 100644 stdlib/xml/dom/NodeFilter.pyi create mode 100644 stdlib/xml/dom/__init__.pyi create mode 100644 stdlib/xml/dom/domreg.pyi create mode 100644 stdlib/xml/dom/expatbuilder.pyi create mode 100644 stdlib/xml/dom/minicompat.pyi create mode 100644 stdlib/xml/dom/minidom.pyi create mode 100644 stdlib/xml/dom/pulldom.pyi create mode 100644 stdlib/xml/dom/xmlbuilder.pyi create mode 100644 stdlib/xml/etree/ElementInclude.pyi create mode 100644 stdlib/xml/etree/ElementPath.pyi create mode 100644 stdlib/xml/etree/ElementTree.pyi create mode 100644 stdlib/xml/etree/__init__.pyi create mode 100644 stdlib/xml/etree/cElementTree.pyi create mode 100644 stdlib/xml/parsers/__init__.pyi create mode 100644 stdlib/xml/parsers/expat/__init__.pyi create mode 100644 stdlib/xml/parsers/expat/errors.pyi create mode 100644 stdlib/xml/parsers/expat/model.pyi create mode 100644 stdlib/xml/sax/__init__.pyi create mode 100644 stdlib/xml/sax/_exceptions.pyi create mode 100644 stdlib/xml/sax/expatreader.pyi create mode 100644 stdlib/xml/sax/handler.pyi create mode 100644 stdlib/xml/sax/saxutils.pyi create mode 100644 stdlib/xml/sax/xmlreader.pyi create mode 100644 stdlib/xml/utils.pyi create mode 100644 stdlib/xmlrpc/__init__.pyi create mode 100644 stdlib/xmlrpc/client.pyi create mode 100644 stdlib/xmlrpc/server.pyi create mode 100644 stdlib/xxlimited.pyi create mode 100644 stdlib/zipapp.pyi create mode 100644 stdlib/zipfile/__init__.pyi create mode 100644 stdlib/zipfile/_path/__init__.pyi create mode 100644 stdlib/zipfile/_path/glob.pyi create mode 100644 stdlib/zipimport.pyi create mode 100644 stdlib/zlib.pyi create mode 100644 stdlib/zoneinfo/__init__.pyi create mode 100644 stdlib/zoneinfo/_common.pyi create mode 100644 stdlib/zoneinfo/_tzpath.pyi create mode 100644 stubs/Authlib/@tests/stubtest_allowlist.txt create mode 100644 stubs/Authlib/METADATA.toml create mode 100644 stubs/Authlib/authlib/__init__.pyi create mode 100644 stubs/Authlib/authlib/common/__init__.pyi create mode 100644 stubs/Authlib/authlib/common/encoding.pyi create mode 100644 stubs/Authlib/authlib/common/errors.pyi create mode 100644 stubs/Authlib/authlib/common/language.pyi create mode 100644 stubs/Authlib/authlib/common/security.pyi create mode 100644 stubs/Authlib/authlib/common/urls.pyi create mode 100644 stubs/Authlib/authlib/consts.pyi create mode 100644 stubs/Authlib/authlib/deprecate.pyi create mode 100644 stubs/Authlib/authlib/integrations/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/async_app.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/async_openid.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/errors.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/registry.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/sync_app.pyi create mode 100644 stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_client/apps.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_client/integration.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_client/apps.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_client/integration.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi create mode 100644 stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi create mode 100644 stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi create mode 100644 stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi create mode 100644 stubs/Authlib/authlib/integrations/httpx_client/utils.pyi create mode 100644 stubs/Authlib/authlib/integrations/requests_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi create mode 100644 stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi create mode 100644 stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi create mode 100644 stubs/Authlib/authlib/integrations/requests_client/utils.pyi create mode 100644 stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi create mode 100644 stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi create mode 100644 stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi create mode 100644 stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi create mode 100644 stubs/Authlib/authlib/integrations/starlette_client/apps.pyi create mode 100644 stubs/Authlib/authlib/integrations/starlette_client/integration.pyi create mode 100644 stubs/Authlib/authlib/jose/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/drafts/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi create mode 100644 stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi create mode 100644 stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi create mode 100644 stubs/Authlib/authlib/jose/errors.pyi create mode 100644 stubs/Authlib/authlib/jose/jwk.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7515/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7515/jws.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7515/models.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7516/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7516/jwe.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7516/models.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/base_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/jwk.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7517/key_set.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7518/util.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7519/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7519/claims.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc7519/jwt.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc8037/__init__.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi create mode 100644 stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi create mode 100644 stubs/Authlib/authlib/jose/util.pyi create mode 100644 stubs/Authlib/authlib/oauth1/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth1/client.pyi create mode 100644 stubs/Authlib/authlib/oauth1/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/models.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/util.pyi create mode 100644 stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi create mode 100644 stubs/Authlib/authlib/oauth2/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/auth.pyi create mode 100644 stubs/Authlib/authlib/oauth2/base.pyi create mode 100644 stubs/Authlib/authlib/oauth2/claims.pyi create mode 100644 stubs/Authlib/authlib/oauth2/client.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/models.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/util.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6750/token.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7521/client.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/client.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/token.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7662/models.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8414/models.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8628/models.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc8693/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/token.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi create mode 100644 stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi create mode 100644 stubs/Authlib/authlib/oidc/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/claims.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/errors.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/code.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/implicit.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/grants/util.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/models.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/userinfo.pyi create mode 100644 stubs/Authlib/authlib/oidc/core/util.pyi create mode 100644 stubs/Authlib/authlib/oidc/discovery/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/discovery/models.pyi create mode 100644 stubs/Authlib/authlib/oidc/discovery/well_known.pyi create mode 100644 stubs/Authlib/authlib/oidc/registration/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/registration/claims.pyi create mode 100644 stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi create mode 100644 stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi create mode 100644 stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi create mode 100644 stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi create mode 100644 stubs/Deprecated/METADATA.toml create mode 100644 stubs/Deprecated/deprecated/__init__.pyi create mode 100644 stubs/Deprecated/deprecated/classic.pyi create mode 100644 stubs/Deprecated/deprecated/params.pyi create mode 100644 stubs/Deprecated/deprecated/sphinx.pyi create mode 100644 stubs/Flask-Cors/METADATA.toml create mode 100644 stubs/Flask-Cors/flask_cors/__init__.pyi create mode 100644 stubs/Flask-Cors/flask_cors/core.pyi create mode 100644 stubs/Flask-Cors/flask_cors/decorator.pyi create mode 100644 stubs/Flask-Cors/flask_cors/extension.pyi create mode 100644 stubs/Flask-Migrate/@tests/stubtest_allowlist.txt create mode 100644 stubs/Flask-Migrate/METADATA.toml create mode 100644 stubs/Flask-Migrate/flask_migrate/__init__.pyi create mode 100644 stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt create mode 100644 stubs/Flask-SocketIO/METADATA.toml create mode 100644 stubs/Flask-SocketIO/flask_socketio/__init__.pyi create mode 100644 stubs/Flask-SocketIO/flask_socketio/namespace.pyi create mode 100644 stubs/Flask-SocketIO/flask_socketio/test_client.pyi create mode 100644 stubs/JACK-Client/@tests/stubtest_allowlist.txt create mode 100644 stubs/JACK-Client/METADATA.toml create mode 100644 stubs/JACK-Client/jack/__init__.pyi create mode 100644 stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi create mode 100644 stubs/Jetson.GPIO/Jetson/__init__.pyi create mode 100644 stubs/Jetson.GPIO/METADATA.toml create mode 100644 stubs/Markdown/@tests/stubtest_allowlist.txt create mode 100644 stubs/Markdown/METADATA.toml create mode 100644 stubs/Markdown/markdown/__init__.pyi create mode 100644 stubs/Markdown/markdown/__main__.pyi create mode 100644 stubs/Markdown/markdown/__meta__.pyi create mode 100644 stubs/Markdown/markdown/blockparser.pyi create mode 100644 stubs/Markdown/markdown/blockprocessors.pyi create mode 100644 stubs/Markdown/markdown/core.pyi create mode 100644 stubs/Markdown/markdown/extensions/__init__.pyi create mode 100644 stubs/Markdown/markdown/extensions/abbr.pyi create mode 100644 stubs/Markdown/markdown/extensions/admonition.pyi create mode 100644 stubs/Markdown/markdown/extensions/attr_list.pyi create mode 100644 stubs/Markdown/markdown/extensions/codehilite.pyi create mode 100644 stubs/Markdown/markdown/extensions/def_list.pyi create mode 100644 stubs/Markdown/markdown/extensions/extra.pyi create mode 100644 stubs/Markdown/markdown/extensions/fenced_code.pyi create mode 100644 stubs/Markdown/markdown/extensions/footnotes.pyi create mode 100644 stubs/Markdown/markdown/extensions/legacy_attrs.pyi create mode 100644 stubs/Markdown/markdown/extensions/legacy_em.pyi create mode 100644 stubs/Markdown/markdown/extensions/md_in_html.pyi create mode 100644 stubs/Markdown/markdown/extensions/meta.pyi create mode 100644 stubs/Markdown/markdown/extensions/nl2br.pyi create mode 100644 stubs/Markdown/markdown/extensions/sane_lists.pyi create mode 100644 stubs/Markdown/markdown/extensions/smarty.pyi create mode 100644 stubs/Markdown/markdown/extensions/tables.pyi create mode 100644 stubs/Markdown/markdown/extensions/toc.pyi create mode 100644 stubs/Markdown/markdown/extensions/wikilinks.pyi create mode 100644 stubs/Markdown/markdown/htmlparser.pyi create mode 100644 stubs/Markdown/markdown/inlinepatterns.pyi create mode 100644 stubs/Markdown/markdown/postprocessors.pyi create mode 100644 stubs/Markdown/markdown/preprocessors.pyi create mode 100644 stubs/Markdown/markdown/serializers.pyi create mode 100644 stubs/Markdown/markdown/test_tools.pyi create mode 100644 stubs/Markdown/markdown/treeprocessors.pyi create mode 100644 stubs/Markdown/markdown/util.pyi create mode 100644 stubs/PyAutoGUI/@tests/stubtest_allowlist.txt create mode 100644 stubs/PyAutoGUI/METADATA.toml create mode 100644 stubs/PyAutoGUI/pyautogui/__init__.pyi create mode 100644 stubs/PyMeeus/METADATA.toml create mode 100644 stubs/PyMeeus/pymeeus/Angle.pyi create mode 100644 stubs/PyMeeus/pymeeus/Coordinates.pyi create mode 100644 stubs/PyMeeus/pymeeus/CurveFitting.pyi create mode 100644 stubs/PyMeeus/pymeeus/Earth.pyi create mode 100644 stubs/PyMeeus/pymeeus/Epoch.pyi create mode 100644 stubs/PyMeeus/pymeeus/Interpolation.pyi create mode 100644 stubs/PyMeeus/pymeeus/Jupiter.pyi create mode 100644 stubs/PyMeeus/pymeeus/JupiterMoons.pyi create mode 100644 stubs/PyMeeus/pymeeus/Mars.pyi create mode 100644 stubs/PyMeeus/pymeeus/Mercury.pyi create mode 100644 stubs/PyMeeus/pymeeus/Minor.pyi create mode 100644 stubs/PyMeeus/pymeeus/Moon.pyi create mode 100644 stubs/PyMeeus/pymeeus/Neptune.pyi create mode 100644 stubs/PyMeeus/pymeeus/Pluto.pyi create mode 100644 stubs/PyMeeus/pymeeus/Saturn.pyi create mode 100644 stubs/PyMeeus/pymeeus/Sun.pyi create mode 100644 stubs/PyMeeus/pymeeus/Uranus.pyi create mode 100644 stubs/PyMeeus/pymeeus/Venus.pyi create mode 100644 stubs/PyMeeus/pymeeus/__init__.pyi create mode 100644 stubs/PyMeeus/pymeeus/base.pyi create mode 100644 stubs/PyMySQL/@tests/stubtest_allowlist.txt create mode 100644 stubs/PyMySQL/@tests/test_cases/check_connection.py create mode 100644 stubs/PyMySQL/METADATA.toml create mode 100644 stubs/PyMySQL/pymysql/__init__.pyi create mode 100644 stubs/PyMySQL/pymysql/_auth.pyi create mode 100644 stubs/PyMySQL/pymysql/charset.pyi create mode 100644 stubs/PyMySQL/pymysql/connections.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/CLIENT.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/COMMAND.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/CR.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/ER.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/FLAG.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi create mode 100644 stubs/PyMySQL/pymysql/constants/__init__.pyi create mode 100644 stubs/PyMySQL/pymysql/converters.pyi create mode 100644 stubs/PyMySQL/pymysql/cursors.pyi create mode 100644 stubs/PyMySQL/pymysql/err.pyi create mode 100644 stubs/PyMySQL/pymysql/optionfile.pyi create mode 100644 stubs/PyMySQL/pymysql/protocol.pyi create mode 100644 stubs/PyMySQL/pymysql/times.pyi create mode 100644 stubs/PyScreeze/@tests/stubtest_allowlist.txt create mode 100644 stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/PyScreeze/METADATA.toml create mode 100644 stubs/PyScreeze/pyscreeze/__init__.pyi create mode 100644 stubs/PySocks/@tests/stubtest_allowlist.txt create mode 100644 stubs/PySocks/METADATA.toml create mode 100644 stubs/PySocks/socks.pyi create mode 100644 stubs/PySocks/sockshandler.pyi create mode 100644 stubs/PyYAML/@tests/stubtest_allowlist.txt create mode 100644 stubs/PyYAML/METADATA.toml create mode 100644 stubs/PyYAML/yaml/__init__.pyi create mode 100644 stubs/PyYAML/yaml/_yaml.pyi create mode 100644 stubs/PyYAML/yaml/composer.pyi create mode 100644 stubs/PyYAML/yaml/constructor.pyi create mode 100644 stubs/PyYAML/yaml/cyaml.pyi create mode 100644 stubs/PyYAML/yaml/dumper.pyi create mode 100644 stubs/PyYAML/yaml/emitter.pyi create mode 100644 stubs/PyYAML/yaml/error.pyi create mode 100644 stubs/PyYAML/yaml/events.pyi create mode 100644 stubs/PyYAML/yaml/loader.pyi create mode 100644 stubs/PyYAML/yaml/nodes.pyi create mode 100644 stubs/PyYAML/yaml/parser.pyi create mode 100644 stubs/PyYAML/yaml/reader.pyi create mode 100644 stubs/PyYAML/yaml/representer.pyi create mode 100644 stubs/PyYAML/yaml/resolver.pyi create mode 100644 stubs/PyYAML/yaml/scanner.pyi create mode 100644 stubs/PyYAML/yaml/serializer.pyi create mode 100644 stubs/PyYAML/yaml/tokens.pyi create mode 100644 stubs/Pygments/@tests/stubtest_allowlist.txt create mode 100644 stubs/Pygments/@tests/test_cases/check_pygments.py create mode 100644 stubs/Pygments/METADATA.toml create mode 100644 stubs/Pygments/pygments/__init__.pyi create mode 100644 stubs/Pygments/pygments/cmdline.pyi create mode 100644 stubs/Pygments/pygments/console.pyi create mode 100644 stubs/Pygments/pygments/filter.pyi create mode 100644 stubs/Pygments/pygments/filters/__init__.pyi create mode 100644 stubs/Pygments/pygments/formatter.pyi create mode 100644 stubs/Pygments/pygments/formatters/__init__.pyi create mode 100644 stubs/Pygments/pygments/formatters/_mapping.pyi create mode 100644 stubs/Pygments/pygments/formatters/bbcode.pyi create mode 100644 stubs/Pygments/pygments/formatters/groff.pyi create mode 100644 stubs/Pygments/pygments/formatters/html.pyi create mode 100644 stubs/Pygments/pygments/formatters/img.pyi create mode 100644 stubs/Pygments/pygments/formatters/irc.pyi create mode 100644 stubs/Pygments/pygments/formatters/latex.pyi create mode 100644 stubs/Pygments/pygments/formatters/other.pyi create mode 100644 stubs/Pygments/pygments/formatters/pangomarkup.pyi create mode 100644 stubs/Pygments/pygments/formatters/rtf.pyi create mode 100644 stubs/Pygments/pygments/formatters/svg.pyi create mode 100644 stubs/Pygments/pygments/formatters/terminal.pyi create mode 100644 stubs/Pygments/pygments/formatters/terminal256.pyi create mode 100644 stubs/Pygments/pygments/lexer.pyi create mode 100644 stubs/Pygments/pygments/lexers/__init__.pyi create mode 100644 stubs/Pygments/pygments/lexers/javascript.pyi create mode 100644 stubs/Pygments/pygments/lexers/jsx.pyi create mode 100644 stubs/Pygments/pygments/lexers/kusto.pyi create mode 100644 stubs/Pygments/pygments/lexers/ldap.pyi create mode 100644 stubs/Pygments/pygments/lexers/lean.pyi create mode 100644 stubs/Pygments/pygments/lexers/lisp.pyi create mode 100644 stubs/Pygments/pygments/lexers/prql.pyi create mode 100644 stubs/Pygments/pygments/lexers/vip.pyi create mode 100644 stubs/Pygments/pygments/lexers/vyper.pyi create mode 100644 stubs/Pygments/pygments/modeline.pyi create mode 100644 stubs/Pygments/pygments/plugin.pyi create mode 100644 stubs/Pygments/pygments/regexopt.pyi create mode 100644 stubs/Pygments/pygments/scanner.pyi create mode 100644 stubs/Pygments/pygments/sphinxext.pyi create mode 100644 stubs/Pygments/pygments/style.pyi create mode 100644 stubs/Pygments/pygments/styles/__init__.pyi create mode 100644 stubs/Pygments/pygments/token.pyi create mode 100644 stubs/Pygments/pygments/unistring.pyi create mode 100644 stubs/Pygments/pygments/util.pyi create mode 100644 stubs/RPi.GPIO/METADATA.toml create mode 100644 stubs/RPi.GPIO/RPi/GPIO/__init__.pyi create mode 100644 stubs/RPi.GPIO/RPi/__init__.pyi create mode 100644 stubs/Send2Trash/@tests/stubtest_allowlist.txt create mode 100644 stubs/Send2Trash/METADATA.toml create mode 100644 stubs/Send2Trash/send2trash/__init__.pyi create mode 100644 stubs/Send2Trash/send2trash/__main__.pyi create mode 100644 stubs/Send2Trash/send2trash/exceptions.pyi create mode 100644 stubs/Send2Trash/send2trash/util.pyi create mode 100644 stubs/TgCrypto/@tests/stubtest_allowlist.txt create mode 100644 stubs/TgCrypto/METADATA.toml create mode 100644 stubs/TgCrypto/tgcrypto/__init__.pyi create mode 100644 stubs/WTForms/@tests/stubtest_allowlist.txt create mode 100644 stubs/WTForms/@tests/test_cases/check_choices.py create mode 100644 stubs/WTForms/@tests/test_cases/check_filters.py create mode 100644 stubs/WTForms/@tests/test_cases/check_form.py create mode 100644 stubs/WTForms/@tests/test_cases/check_validators.py create mode 100644 stubs/WTForms/@tests/test_cases/check_widgets.py create mode 100644 stubs/WTForms/METADATA.toml create mode 100644 stubs/WTForms/wtforms/__init__.pyi create mode 100644 stubs/WTForms/wtforms/csrf/__init__.pyi create mode 100644 stubs/WTForms/wtforms/csrf/core.pyi create mode 100644 stubs/WTForms/wtforms/csrf/session.pyi create mode 100644 stubs/WTForms/wtforms/fields/__init__.pyi create mode 100644 stubs/WTForms/wtforms/fields/choices.pyi create mode 100644 stubs/WTForms/wtforms/fields/core.pyi create mode 100644 stubs/WTForms/wtforms/fields/datetime.pyi create mode 100644 stubs/WTForms/wtforms/fields/form.pyi create mode 100644 stubs/WTForms/wtforms/fields/list.pyi create mode 100644 stubs/WTForms/wtforms/fields/numeric.pyi create mode 100644 stubs/WTForms/wtforms/fields/simple.pyi create mode 100644 stubs/WTForms/wtforms/form.pyi create mode 100644 stubs/WTForms/wtforms/i18n.pyi create mode 100644 stubs/WTForms/wtforms/meta.pyi create mode 100644 stubs/WTForms/wtforms/utils.pyi create mode 100644 stubs/WTForms/wtforms/validators.pyi create mode 100644 stubs/WTForms/wtforms/widgets/__init__.pyi create mode 100644 stubs/WTForms/wtforms/widgets/core.pyi create mode 100644 stubs/WebOb/@tests/stubtest_allowlist.txt create mode 100644 stubs/WebOb/@tests/test_cases/check_cachecontrol.py create mode 100644 stubs/WebOb/@tests/test_cases/check_wsgify.py create mode 100644 stubs/WebOb/METADATA.toml create mode 100644 stubs/WebOb/webob/__init__.pyi create mode 100644 stubs/WebOb/webob/_types.pyi create mode 100644 stubs/WebOb/webob/acceptparse.pyi create mode 100644 stubs/WebOb/webob/byterange.pyi create mode 100644 stubs/WebOb/webob/cachecontrol.pyi create mode 100644 stubs/WebOb/webob/client.pyi create mode 100644 stubs/WebOb/webob/compat.pyi create mode 100644 stubs/WebOb/webob/cookies.pyi create mode 100644 stubs/WebOb/webob/datetime_utils.pyi create mode 100644 stubs/WebOb/webob/dec.pyi create mode 100644 stubs/WebOb/webob/descriptors.pyi create mode 100644 stubs/WebOb/webob/etag.pyi create mode 100644 stubs/WebOb/webob/exc.pyi create mode 100644 stubs/WebOb/webob/headers.pyi create mode 100644 stubs/WebOb/webob/multidict.pyi create mode 100644 stubs/WebOb/webob/request.pyi create mode 100644 stubs/WebOb/webob/response.pyi create mode 100644 stubs/WebOb/webob/static.pyi create mode 100644 stubs/WebOb/webob/util.pyi create mode 100644 stubs/WebTest/@tests/stubtest_allowlist.txt create mode 100644 stubs/WebTest/METADATA.toml create mode 100644 stubs/WebTest/webtest/__init__.pyi create mode 100644 stubs/WebTest/webtest/app.pyi create mode 100644 stubs/WebTest/webtest/debugapp.pyi create mode 100644 stubs/WebTest/webtest/forms.pyi create mode 100644 stubs/WebTest/webtest/http.pyi create mode 100644 stubs/WebTest/webtest/response.pyi create mode 100644 stubs/aiofiles/@tests/stubtest_allowlist.txt create mode 100644 stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/aiofiles/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/aiofiles/METADATA.toml create mode 100644 stubs/aiofiles/aiofiles/__init__.pyi create mode 100644 stubs/aiofiles/aiofiles/base.pyi create mode 100644 stubs/aiofiles/aiofiles/os.pyi create mode 100644 stubs/aiofiles/aiofiles/ospath.pyi create mode 100644 stubs/aiofiles/aiofiles/tempfile/__init__.pyi create mode 100644 stubs/aiofiles/aiofiles/tempfile/temptypes.pyi create mode 100644 stubs/aiofiles/aiofiles/threadpool/__init__.pyi create mode 100644 stubs/aiofiles/aiofiles/threadpool/binary.pyi create mode 100644 stubs/aiofiles/aiofiles/threadpool/text.pyi create mode 100644 stubs/aiofiles/aiofiles/threadpool/utils.pyi create mode 100644 stubs/antlr4-python3-runtime/METADATA.toml create mode 100644 stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/FileStream.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/InputStream.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/Lexer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/Parser.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/Token.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/Utils.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/__init__.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/atn/__init__.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/dfa/__init__.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/error/__init__.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/tree/__init__.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi create mode 100644 stubs/antlr4-python3-runtime/antlr4/xpath/__init__.pyi create mode 100644 stubs/assertpy/@tests/stubtest_allowlist.txt create mode 100644 stubs/assertpy/METADATA.toml create mode 100644 stubs/assertpy/assertpy/__init__.pyi create mode 100644 stubs/assertpy/assertpy/assertpy.pyi create mode 100644 stubs/assertpy/assertpy/base.pyi create mode 100644 stubs/assertpy/assertpy/collection.pyi create mode 100644 stubs/assertpy/assertpy/contains.pyi create mode 100644 stubs/assertpy/assertpy/date.pyi create mode 100644 stubs/assertpy/assertpy/dict.pyi create mode 100644 stubs/assertpy/assertpy/dynamic.pyi create mode 100644 stubs/assertpy/assertpy/exception.pyi create mode 100644 stubs/assertpy/assertpy/extracting.pyi create mode 100644 stubs/assertpy/assertpy/file.pyi create mode 100644 stubs/assertpy/assertpy/helpers.pyi create mode 100644 stubs/assertpy/assertpy/numeric.pyi create mode 100644 stubs/assertpy/assertpy/snapshot.pyi create mode 100644 stubs/assertpy/assertpy/string.pyi create mode 100644 stubs/atheris/METADATA.toml create mode 100644 stubs/atheris/atheris/__init__.pyi create mode 100644 stubs/atheris/atheris/function_hooks.pyi create mode 100644 stubs/atheris/atheris/import_hook.pyi create mode 100644 stubs/atheris/atheris/instrument_bytecode.pyi create mode 100644 stubs/atheris/atheris/utils.pyi create mode 100644 stubs/atheris/atheris/version_dependent.pyi create mode 100644 stubs/auth0-python/@tests/stubtest_allowlist.txt create mode 100644 stubs/auth0-python/METADATA.toml create mode 100644 stubs/auth0-python/auth0/__init__.pyi create mode 100644 stubs/auth0-python/auth0/asyncify.pyi create mode 100644 stubs/auth0-python/auth0/authentication/__init__.pyi create mode 100644 stubs/auth0-python/auth0/authentication/async_token_verifier.pyi create mode 100644 stubs/auth0-python/auth0/authentication/back_channel_login.pyi create mode 100644 stubs/auth0-python/auth0/authentication/base.pyi create mode 100644 stubs/auth0-python/auth0/authentication/client_authentication.pyi create mode 100644 stubs/auth0-python/auth0/authentication/database.pyi create mode 100644 stubs/auth0-python/auth0/authentication/delegated.pyi create mode 100644 stubs/auth0-python/auth0/authentication/enterprise.pyi create mode 100644 stubs/auth0-python/auth0/authentication/get_token.pyi create mode 100644 stubs/auth0-python/auth0/authentication/passwordless.pyi create mode 100644 stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi create mode 100644 stubs/auth0-python/auth0/authentication/revoke_token.pyi create mode 100644 stubs/auth0-python/auth0/authentication/social.pyi create mode 100644 stubs/auth0-python/auth0/authentication/token_verifier.pyi create mode 100644 stubs/auth0-python/auth0/authentication/users.pyi create mode 100644 stubs/auth0-python/auth0/exceptions.pyi create mode 100644 stubs/auth0-python/auth0/management/__init__.pyi create mode 100644 stubs/auth0-python/auth0/management/actions.pyi create mode 100644 stubs/auth0-python/auth0/management/async_auth0.pyi create mode 100644 stubs/auth0-python/auth0/management/attack_protection.pyi create mode 100644 stubs/auth0-python/auth0/management/auth0.pyi create mode 100644 stubs/auth0-python/auth0/management/blacklists.pyi create mode 100644 stubs/auth0-python/auth0/management/branding.pyi create mode 100644 stubs/auth0-python/auth0/management/client_credentials.pyi create mode 100644 stubs/auth0-python/auth0/management/client_grants.pyi create mode 100644 stubs/auth0-python/auth0/management/clients.pyi create mode 100644 stubs/auth0-python/auth0/management/connections.pyi create mode 100644 stubs/auth0-python/auth0/management/custom_domains.pyi create mode 100644 stubs/auth0-python/auth0/management/device_credentials.pyi create mode 100644 stubs/auth0-python/auth0/management/email_templates.pyi create mode 100644 stubs/auth0-python/auth0/management/emails.pyi create mode 100644 stubs/auth0-python/auth0/management/grants.pyi create mode 100644 stubs/auth0-python/auth0/management/guardian.pyi create mode 100644 stubs/auth0-python/auth0/management/hooks.pyi create mode 100644 stubs/auth0-python/auth0/management/jobs.pyi create mode 100644 stubs/auth0-python/auth0/management/log_streams.pyi create mode 100644 stubs/auth0-python/auth0/management/logs.pyi create mode 100644 stubs/auth0-python/auth0/management/organizations.pyi create mode 100644 stubs/auth0-python/auth0/management/prompts.pyi create mode 100644 stubs/auth0-python/auth0/management/resource_servers.pyi create mode 100644 stubs/auth0-python/auth0/management/roles.pyi create mode 100644 stubs/auth0-python/auth0/management/rules.pyi create mode 100644 stubs/auth0-python/auth0/management/rules_configs.pyi create mode 100644 stubs/auth0-python/auth0/management/self_service_profiles.pyi create mode 100644 stubs/auth0-python/auth0/management/stats.pyi create mode 100644 stubs/auth0-python/auth0/management/tenants.pyi create mode 100644 stubs/auth0-python/auth0/management/tickets.pyi create mode 100644 stubs/auth0-python/auth0/management/user_blocks.pyi create mode 100644 stubs/auth0-python/auth0/management/users.pyi create mode 100644 stubs/auth0-python/auth0/management/users_by_email.pyi create mode 100644 stubs/auth0-python/auth0/rest.pyi create mode 100644 stubs/auth0-python/auth0/rest_async.pyi create mode 100644 stubs/auth0-python/auth0/types.pyi create mode 100644 stubs/auth0-python/auth0/utils.pyi create mode 100644 stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt create mode 100644 stubs/aws-xray-sdk/METADATA.toml create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/exceptions.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi create mode 100644 stubs/aws-xray-sdk/aws_xray_sdk/version.pyi create mode 100644 stubs/behave/METADATA.toml create mode 100644 stubs/behave/behave/__init__.pyi create mode 100644 stubs/behave/behave/fixture.pyi create mode 100644 stubs/behave/behave/runner.pyi create mode 100644 stubs/behave/behave/step_registry.pyi create mode 100644 stubs/binaryornot/@tests/stubtest_allowlist.txt create mode 100644 stubs/binaryornot/METADATA.toml create mode 100644 stubs/binaryornot/binaryornot/__init__.pyi create mode 100644 stubs/binaryornot/binaryornot/check.pyi create mode 100644 stubs/binaryornot/binaryornot/helpers.pyi create mode 100644 stubs/bleach/@tests/stubtest_allowlist.txt create mode 100644 stubs/bleach/METADATA.toml create mode 100644 stubs/bleach/bleach/__init__.pyi create mode 100644 stubs/bleach/bleach/callbacks.pyi create mode 100644 stubs/bleach/bleach/css_sanitizer.pyi create mode 100644 stubs/bleach/bleach/html5lib_shim.pyi create mode 100644 stubs/bleach/bleach/linkifier.pyi create mode 100644 stubs/bleach/bleach/parse_shim.pyi create mode 100644 stubs/bleach/bleach/sanitizer.pyi create mode 100644 stubs/boltons/@tests/stubtest_allowlist.txt create mode 100644 stubs/boltons/METADATA.toml create mode 100644 stubs/boltons/boltons/__init__.pyi create mode 100644 stubs/boltons/boltons/cacheutils.pyi create mode 100644 stubs/boltons/boltons/debugutils.pyi create mode 100644 stubs/boltons/boltons/deprutils.pyi create mode 100644 stubs/boltons/boltons/dictutils.pyi create mode 100644 stubs/boltons/boltons/easterutils.pyi create mode 100644 stubs/boltons/boltons/ecoutils.pyi create mode 100644 stubs/boltons/boltons/excutils.pyi create mode 100644 stubs/boltons/boltons/fileutils.pyi create mode 100644 stubs/boltons/boltons/formatutils.pyi create mode 100644 stubs/boltons/boltons/funcutils.pyi create mode 100644 stubs/boltons/boltons/gcutils.pyi create mode 100644 stubs/boltons/boltons/ioutils.pyi create mode 100644 stubs/boltons/boltons/iterutils.pyi create mode 100644 stubs/boltons/boltons/jsonutils.pyi create mode 100644 stubs/boltons/boltons/listutils.pyi create mode 100644 stubs/boltons/boltons/mathutils.pyi create mode 100644 stubs/boltons/boltons/mboxutils.pyi create mode 100644 stubs/boltons/boltons/namedutils.pyi create mode 100644 stubs/boltons/boltons/pathutils.pyi create mode 100644 stubs/boltons/boltons/queueutils.pyi create mode 100644 stubs/boltons/boltons/setutils.pyi create mode 100644 stubs/boltons/boltons/socketutils.pyi create mode 100644 stubs/boltons/boltons/statsutils.pyi create mode 100644 stubs/boltons/boltons/strutils.pyi create mode 100644 stubs/boltons/boltons/tableutils.pyi create mode 100644 stubs/boltons/boltons/tbutils.pyi create mode 100644 stubs/boltons/boltons/timeutils.pyi create mode 100644 stubs/boltons/boltons/typeutils.pyi create mode 100644 stubs/boltons/boltons/urlutils.pyi create mode 100644 stubs/braintree/@tests/stubtest_allowlist.txt create mode 100644 stubs/braintree/METADATA.toml create mode 100644 stubs/braintree/braintree/__init__.pyi create mode 100644 stubs/braintree/braintree/account_updater_daily_report.pyi create mode 100644 stubs/braintree/braintree/ach_mandate.pyi create mode 100644 stubs/braintree/braintree/add_on.pyi create mode 100644 stubs/braintree/braintree/add_on_gateway.pyi create mode 100644 stubs/braintree/braintree/address.pyi create mode 100644 stubs/braintree/braintree/address_gateway.pyi create mode 100644 stubs/braintree/braintree/amex_express_checkout_card.pyi create mode 100644 stubs/braintree/braintree/android_pay_card.pyi create mode 100644 stubs/braintree/braintree/apple_pay_card.pyi create mode 100644 stubs/braintree/braintree/apple_pay_gateway.pyi create mode 100644 stubs/braintree/braintree/apple_pay_options.pyi create mode 100644 stubs/braintree/braintree/attribute_getter.pyi create mode 100644 stubs/braintree/braintree/authorization_adjustment.pyi create mode 100644 stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi create mode 100644 stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi create mode 100644 stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi create mode 100644 stubs/braintree/braintree/bin_data.pyi create mode 100644 stubs/braintree/braintree/blik_alias.pyi create mode 100644 stubs/braintree/braintree/braintree_gateway.pyi create mode 100644 stubs/braintree/braintree/client_token.pyi create mode 100644 stubs/braintree/braintree/client_token_gateway.pyi create mode 100644 stubs/braintree/braintree/configuration.pyi create mode 100644 stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi create mode 100644 stubs/braintree/braintree/connected_merchant_status_transitioned.pyi create mode 100644 stubs/braintree/braintree/credentials_parser.pyi create mode 100644 stubs/braintree/braintree/credit_card.pyi create mode 100644 stubs/braintree/braintree/credit_card_gateway.pyi create mode 100644 stubs/braintree/braintree/credit_card_verification.pyi create mode 100644 stubs/braintree/braintree/credit_card_verification_gateway.pyi create mode 100644 stubs/braintree/braintree/credit_card_verification_search.pyi create mode 100644 stubs/braintree/braintree/customer.pyi create mode 100644 stubs/braintree/braintree/customer_gateway.pyi create mode 100644 stubs/braintree/braintree/customer_search.pyi create mode 100644 stubs/braintree/braintree/customer_session_gateway.pyi create mode 100644 stubs/braintree/braintree/descriptor.pyi create mode 100644 stubs/braintree/braintree/disbursement.pyi create mode 100644 stubs/braintree/braintree/disbursement_detail.pyi create mode 100644 stubs/braintree/braintree/discount.pyi create mode 100644 stubs/braintree/braintree/discount_gateway.pyi create mode 100644 stubs/braintree/braintree/dispute.pyi create mode 100644 stubs/braintree/braintree/dispute_details/__init__.pyi create mode 100644 stubs/braintree/braintree/dispute_details/evidence.pyi create mode 100644 stubs/braintree/braintree/dispute_details/paypal_message.pyi create mode 100644 stubs/braintree/braintree/dispute_details/status_history.pyi create mode 100644 stubs/braintree/braintree/dispute_gateway.pyi create mode 100644 stubs/braintree/braintree/dispute_search.pyi create mode 100644 stubs/braintree/braintree/document_upload.pyi create mode 100644 stubs/braintree/braintree/document_upload_gateway.pyi create mode 100644 stubs/braintree/braintree/enriched_customer_data.pyi create mode 100644 stubs/braintree/braintree/environment.pyi create mode 100644 stubs/braintree/braintree/error_codes.pyi create mode 100644 stubs/braintree/braintree/error_result.pyi create mode 100644 stubs/braintree/braintree/errors.pyi create mode 100644 stubs/braintree/braintree/europe_bank_account.pyi create mode 100644 stubs/braintree/braintree/exceptions/__init__.pyi create mode 100644 stubs/braintree/braintree/exceptions/authentication_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/authorization_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/braintree_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/configuration_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/http/__init__.pyi create mode 100644 stubs/braintree/braintree/exceptions/http/connection_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/http/timeout_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/invalid_signature_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/not_found_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/request_timeout_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/server_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/service_unavailable_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/too_many_requests_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/unexpected_error.pyi create mode 100644 stubs/braintree/braintree/exceptions/upgrade_required_error.pyi create mode 100644 stubs/braintree/braintree/exchange_rate_quote.pyi create mode 100644 stubs/braintree/braintree/exchange_rate_quote_gateway.pyi create mode 100644 stubs/braintree/braintree/exchange_rate_quote_input.pyi create mode 100644 stubs/braintree/braintree/exchange_rate_quote_payload.pyi create mode 100644 stubs/braintree/braintree/exchange_rate_quote_request.pyi create mode 100644 stubs/braintree/braintree/facilitated_details.pyi create mode 100644 stubs/braintree/braintree/facilitator_details.pyi create mode 100644 stubs/braintree/braintree/granted_payment_instrument_update.pyi create mode 100644 stubs/braintree/braintree/graphql/__init__.pyi create mode 100644 stubs/braintree/braintree/graphql/enums/__init__.pyi create mode 100644 stubs/braintree/braintree/graphql/enums/recommendations.pyi create mode 100644 stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/__init__.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/phone_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi create mode 100644 stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi create mode 100644 stubs/braintree/braintree/graphql/types/__init__.pyi create mode 100644 stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi create mode 100644 stubs/braintree/braintree/graphql/types/payment_options.pyi create mode 100644 stubs/braintree/braintree/graphql/types/payment_recommendation.pyi create mode 100644 stubs/braintree/braintree/graphql/unions/__init__.pyi create mode 100644 stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi create mode 100644 stubs/braintree/braintree/iban_bank_account.pyi create mode 100644 stubs/braintree/braintree/ids_search.pyi create mode 100644 stubs/braintree/braintree/liability_shift.pyi create mode 100644 stubs/braintree/braintree/local_payment.pyi create mode 100644 stubs/braintree/braintree/local_payment_completed.pyi create mode 100644 stubs/braintree/braintree/local_payment_context.pyi create mode 100644 stubs/braintree/braintree/local_payment_context_gateway.pyi create mode 100644 stubs/braintree/braintree/local_payment_expired.pyi create mode 100644 stubs/braintree/braintree/local_payment_funded.pyi create mode 100644 stubs/braintree/braintree/local_payment_reversed.pyi create mode 100644 stubs/braintree/braintree/local_payment_type.pyi create mode 100644 stubs/braintree/braintree/masterpass_card.pyi create mode 100644 stubs/braintree/braintree/merchant.pyi create mode 100644 stubs/braintree/braintree/merchant_account/__init__.pyi create mode 100644 stubs/braintree/braintree/merchant_account/address_details.pyi create mode 100644 stubs/braintree/braintree/merchant_account/merchant_account.pyi create mode 100644 stubs/braintree/braintree/merchant_account_gateway.pyi create mode 100644 stubs/braintree/braintree/merchant_gateway.pyi create mode 100644 stubs/braintree/braintree/meta_checkout_card.pyi create mode 100644 stubs/braintree/braintree/meta_checkout_token.pyi create mode 100644 stubs/braintree/braintree/modification.pyi create mode 100644 stubs/braintree/braintree/monetary_amount.pyi create mode 100644 stubs/braintree/braintree/oauth_access_revocation.pyi create mode 100644 stubs/braintree/braintree/oauth_credentials.pyi create mode 100644 stubs/braintree/braintree/oauth_gateway.pyi create mode 100644 stubs/braintree/braintree/package_details.pyi create mode 100644 stubs/braintree/braintree/paginated_collection.pyi create mode 100644 stubs/braintree/braintree/paginated_result.pyi create mode 100644 stubs/braintree/braintree/partner_merchant.pyi create mode 100644 stubs/braintree/braintree/payment_facilitator.pyi create mode 100644 stubs/braintree/braintree/payment_instrument_type.pyi create mode 100644 stubs/braintree/braintree/payment_method.pyi create mode 100644 stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi create mode 100644 stubs/braintree/braintree/payment_method_gateway.pyi create mode 100644 stubs/braintree/braintree/payment_method_nonce.pyi create mode 100644 stubs/braintree/braintree/payment_method_nonce_gateway.pyi create mode 100644 stubs/braintree/braintree/payment_method_parser.pyi create mode 100644 stubs/braintree/braintree/paypal_account.pyi create mode 100644 stubs/braintree/braintree/paypal_account_gateway.pyi create mode 100644 stubs/braintree/braintree/paypal_here.pyi create mode 100644 stubs/braintree/braintree/paypal_payment_resource.pyi create mode 100644 stubs/braintree/braintree/paypal_payment_resource_gateway.pyi create mode 100644 stubs/braintree/braintree/plan.pyi create mode 100644 stubs/braintree/braintree/plan_gateway.pyi create mode 100644 stubs/braintree/braintree/processor_response_types.pyi create mode 100644 stubs/braintree/braintree/receiver.pyi create mode 100644 stubs/braintree/braintree/resource.pyi create mode 100644 stubs/braintree/braintree/resource_collection.pyi create mode 100644 stubs/braintree/braintree/revoked_payment_method_metadata.pyi create mode 100644 stubs/braintree/braintree/risk_data.pyi create mode 100644 stubs/braintree/braintree/samsung_pay_card.pyi create mode 100644 stubs/braintree/braintree/search.pyi create mode 100644 stubs/braintree/braintree/sender.pyi create mode 100644 stubs/braintree/braintree/sepa_direct_debit_account.pyi create mode 100644 stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi create mode 100644 stubs/braintree/braintree/settlement_batch_summary.pyi create mode 100644 stubs/braintree/braintree/settlement_batch_summary_gateway.pyi create mode 100644 stubs/braintree/braintree/signature_service.pyi create mode 100644 stubs/braintree/braintree/status_event.pyi create mode 100644 stubs/braintree/braintree/sub_merchant.pyi create mode 100644 stubs/braintree/braintree/subscription.pyi create mode 100644 stubs/braintree/braintree/subscription_details.pyi create mode 100644 stubs/braintree/braintree/subscription_gateway.pyi create mode 100644 stubs/braintree/braintree/subscription_search.pyi create mode 100644 stubs/braintree/braintree/subscription_status_event.pyi create mode 100644 stubs/braintree/braintree/successful_result.pyi create mode 100644 stubs/braintree/braintree/test/__init__.pyi create mode 100644 stubs/braintree/braintree/test/authentication_ids.pyi create mode 100644 stubs/braintree/braintree/test/credit_card_defaults.pyi create mode 100644 stubs/braintree/braintree/test/credit_card_numbers.pyi create mode 100644 stubs/braintree/braintree/test/merchant_account.pyi create mode 100644 stubs/braintree/braintree/test/nonces.pyi create mode 100644 stubs/braintree/braintree/test/venmo_sdk.pyi create mode 100644 stubs/braintree/braintree/testing_gateway.pyi create mode 100644 stubs/braintree/braintree/three_d_secure_info.pyi create mode 100644 stubs/braintree/braintree/transaction.pyi create mode 100644 stubs/braintree/braintree/transaction_amounts.pyi create mode 100644 stubs/braintree/braintree/transaction_details.pyi create mode 100644 stubs/braintree/braintree/transaction_gateway.pyi create mode 100644 stubs/braintree/braintree/transaction_line_item.pyi create mode 100644 stubs/braintree/braintree/transaction_line_item_gateway.pyi create mode 100644 stubs/braintree/braintree/transaction_review.pyi create mode 100644 stubs/braintree/braintree/transaction_search.pyi create mode 100644 stubs/braintree/braintree/transaction_us_bank_account_request.pyi create mode 100644 stubs/braintree/braintree/transfer.pyi create mode 100644 stubs/braintree/braintree/unknown_payment_method.pyi create mode 100644 stubs/braintree/braintree/us_bank_account.pyi create mode 100644 stubs/braintree/braintree/us_bank_account_gateway.pyi create mode 100644 stubs/braintree/braintree/us_bank_account_verification.pyi create mode 100644 stubs/braintree/braintree/us_bank_account_verification_gateway.pyi create mode 100644 stubs/braintree/braintree/us_bank_account_verification_search.pyi create mode 100644 stubs/braintree/braintree/util/__init__.pyi create mode 100644 stubs/braintree/braintree/util/constants.pyi create mode 100644 stubs/braintree/braintree/util/crypto.pyi create mode 100644 stubs/braintree/braintree/util/datetime_parser.pyi create mode 100644 stubs/braintree/braintree/util/experimental.pyi create mode 100644 stubs/braintree/braintree/util/generator.pyi create mode 100644 stubs/braintree/braintree/util/graphql_client.pyi create mode 100644 stubs/braintree/braintree/util/http.pyi create mode 100644 stubs/braintree/braintree/util/parser.pyi create mode 100644 stubs/braintree/braintree/util/xml_util.pyi create mode 100644 stubs/braintree/braintree/validation_error.pyi create mode 100644 stubs/braintree/braintree/validation_error_collection.pyi create mode 100644 stubs/braintree/braintree/venmo_account.pyi create mode 100644 stubs/braintree/braintree/venmo_profile_data.pyi create mode 100644 stubs/braintree/braintree/version.pyi create mode 100644 stubs/braintree/braintree/visa_checkout_card.pyi create mode 100644 stubs/braintree/braintree/webhook_notification.pyi create mode 100644 stubs/braintree/braintree/webhook_notification_gateway.pyi create mode 100644 stubs/braintree/braintree/webhook_testing.pyi create mode 100644 stubs/braintree/braintree/webhook_testing_gateway.pyi create mode 100644 stubs/cachetools/@tests/stubtest_allowlist.txt create mode 100644 stubs/cachetools/@tests/test_cases/check_cachetools.py create mode 100644 stubs/cachetools/METADATA.toml create mode 100644 stubs/cachetools/cachetools/__init__.pyi create mode 100644 stubs/cachetools/cachetools/func.pyi create mode 100644 stubs/cachetools/cachetools/keys.pyi create mode 100644 stubs/capturer/@tests/stubtest_allowlist.txt create mode 100644 stubs/capturer/METADATA.toml create mode 100644 stubs/capturer/capturer.pyi create mode 100644 stubs/cffi/@tests/stubtest_allowlist.txt create mode 100644 stubs/cffi/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/cffi/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/cffi/METADATA.toml create mode 100644 stubs/cffi/_cffi_backend.pyi create mode 100644 stubs/cffi/cffi/__init__.pyi create mode 100644 stubs/cffi/cffi/api.pyi create mode 100644 stubs/cffi/cffi/backend_ctypes.pyi create mode 100644 stubs/cffi/cffi/cffi_opcode.pyi create mode 100644 stubs/cffi/cffi/commontypes.pyi create mode 100644 stubs/cffi/cffi/cparser.pyi create mode 100644 stubs/cffi/cffi/error.pyi create mode 100644 stubs/cffi/cffi/ffiplatform.pyi create mode 100644 stubs/cffi/cffi/lock.pyi create mode 100644 stubs/cffi/cffi/model.pyi create mode 100644 stubs/cffi/cffi/pkgconfig.pyi create mode 100644 stubs/cffi/cffi/recompiler.pyi create mode 100644 stubs/cffi/cffi/setuptools_ext.pyi create mode 100644 stubs/cffi/cffi/vengine_cpy.pyi create mode 100644 stubs/cffi/cffi/vengine_gen.pyi create mode 100644 stubs/cffi/cffi/verifier.pyi create mode 100644 stubs/channels/@tests/django_settings.py create mode 100644 stubs/channels/@tests/stubtest_allowlist.txt create mode 100644 stubs/channels/METADATA.toml create mode 100644 stubs/channels/channels/__init__.pyi create mode 100644 stubs/channels/channels/apps.pyi create mode 100644 stubs/channels/channels/auth.pyi create mode 100644 stubs/channels/channels/consumer.pyi create mode 100644 stubs/channels/channels/db.pyi create mode 100644 stubs/channels/channels/exceptions.pyi create mode 100644 stubs/channels/channels/generic/__init__.pyi create mode 100644 stubs/channels/channels/generic/http.pyi create mode 100644 stubs/channels/channels/generic/websocket.pyi create mode 100644 stubs/channels/channels/layers.pyi create mode 100644 stubs/channels/channels/management/__init__.pyi create mode 100644 stubs/channels/channels/management/commands/__init__.pyi create mode 100644 stubs/channels/channels/management/commands/runworker.pyi create mode 100644 stubs/channels/channels/middleware.pyi create mode 100644 stubs/channels/channels/routing.pyi create mode 100644 stubs/channels/channels/security/__init__.pyi create mode 100644 stubs/channels/channels/security/websocket.pyi create mode 100644 stubs/channels/channels/sessions.pyi create mode 100644 stubs/channels/channels/testing/__init__.pyi create mode 100644 stubs/channels/channels/testing/application.pyi create mode 100644 stubs/channels/channels/testing/http.pyi create mode 100644 stubs/channels/channels/testing/live.pyi create mode 100644 stubs/channels/channels/testing/websocket.pyi create mode 100644 stubs/channels/channels/utils.pyi create mode 100644 stubs/channels/channels/worker.pyi create mode 100755 stubs/chevron/METADATA.toml create mode 100644 stubs/chevron/chevron/__init__.pyi create mode 100644 stubs/chevron/chevron/main.pyi create mode 100644 stubs/chevron/chevron/metadata.pyi create mode 100644 stubs/chevron/chevron/renderer.pyi create mode 100644 stubs/chevron/chevron/tokenizer.pyi create mode 100644 stubs/click-default-group/METADATA.toml create mode 100644 stubs/click-default-group/click_default_group.pyi create mode 100644 stubs/click-log/METADATA.toml create mode 100644 stubs/click-log/click_log/__init__.pyi create mode 100644 stubs/click-log/click_log/core.pyi create mode 100644 stubs/click-log/click_log/options.pyi create mode 100644 stubs/click-shell/METADATA.toml create mode 100644 stubs/click-shell/click_shell/__init__.pyi create mode 100644 stubs/click-shell/click_shell/_cmd.pyi create mode 100644 stubs/click-shell/click_shell/_compat.pyi create mode 100644 stubs/click-shell/click_shell/core.pyi create mode 100644 stubs/click-shell/click_shell/decorators.pyi create mode 100644 stubs/click-spinner/METADATA.toml create mode 100644 stubs/click-spinner/click_spinner/__init__.pyi create mode 100644 stubs/click-web/METADATA.toml create mode 100644 stubs/click-web/click_web/__init__.pyi create mode 100644 stubs/click-web/click_web/exceptions.pyi create mode 100644 stubs/click-web/click_web/resources/__init__.pyi create mode 100644 stubs/click-web/click_web/resources/cmd_exec.pyi create mode 100644 stubs/click-web/click_web/resources/cmd_form.pyi create mode 100644 stubs/click-web/click_web/resources/index.pyi create mode 100644 stubs/click-web/click_web/resources/input_fields.pyi create mode 100644 stubs/click-web/click_web/web_click_types.pyi create mode 100644 stubs/colorama/@tests/stubtest_allowlist.txt create mode 100644 stubs/colorama/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/colorama/METADATA.toml create mode 100644 stubs/colorama/colorama/__init__.pyi create mode 100644 stubs/colorama/colorama/ansi.pyi create mode 100644 stubs/colorama/colorama/ansitowin32.pyi create mode 100644 stubs/colorama/colorama/initialise.pyi create mode 100644 stubs/colorama/colorama/win32.pyi create mode 100644 stubs/colorama/colorama/winterm.pyi create mode 100644 stubs/colorful/METADATA.toml create mode 100644 stubs/colorful/colorful/__init__.pyi create mode 100644 stubs/colorful/colorful/ansi.pyi create mode 100644 stubs/colorful/colorful/colors.pyi create mode 100644 stubs/colorful/colorful/core.pyi create mode 100644 stubs/colorful/colorful/styles.pyi create mode 100644 stubs/colorful/colorful/terminal.pyi create mode 100644 stubs/colorful/colorful/utils.pyi create mode 100644 stubs/console-menu/METADATA.toml create mode 100644 stubs/console-menu/consolemenu/__init__.pyi create mode 100644 stubs/console-menu/consolemenu/console_menu.pyi create mode 100644 stubs/console-menu/consolemenu/format/__init__.pyi create mode 100644 stubs/console-menu/consolemenu/format/menu_borders.pyi create mode 100644 stubs/console-menu/consolemenu/format/menu_margins.pyi create mode 100644 stubs/console-menu/consolemenu/format/menu_padding.pyi create mode 100644 stubs/console-menu/consolemenu/format/menu_style.pyi create mode 100644 stubs/console-menu/consolemenu/items/__init__.pyi create mode 100644 stubs/console-menu/consolemenu/items/command_item.pyi create mode 100644 stubs/console-menu/consolemenu/items/external_item.pyi create mode 100644 stubs/console-menu/consolemenu/items/function_item.pyi create mode 100644 stubs/console-menu/consolemenu/items/selection_item.pyi create mode 100644 stubs/console-menu/consolemenu/items/submenu_item.pyi create mode 100644 stubs/console-menu/consolemenu/menu_component.pyi create mode 100644 stubs/console-menu/consolemenu/menu_formatter.pyi create mode 100644 stubs/console-menu/consolemenu/multiselect_menu.pyi create mode 100644 stubs/console-menu/consolemenu/prompt_utils.pyi create mode 100644 stubs/console-menu/consolemenu/screen.pyi create mode 100644 stubs/console-menu/consolemenu/selection_menu.pyi create mode 100644 stubs/console-menu/consolemenu/validators/__init__.pyi create mode 100644 stubs/console-menu/consolemenu/validators/base.pyi create mode 100644 stubs/console-menu/consolemenu/validators/regex.pyi create mode 100644 stubs/console-menu/consolemenu/validators/url.pyi create mode 100644 stubs/console-menu/consolemenu/version.pyi create mode 100644 stubs/convertdate/METADATA.toml create mode 100644 stubs/convertdate/convertdate/__init__.pyi create mode 100644 stubs/convertdate/convertdate/armenian.pyi create mode 100644 stubs/convertdate/convertdate/bahai.pyi create mode 100644 stubs/convertdate/convertdate/coptic.pyi create mode 100644 stubs/convertdate/convertdate/data/__init__.pyi create mode 100644 stubs/convertdate/convertdate/data/french_republican_days.pyi create mode 100644 stubs/convertdate/convertdate/data/positivist.pyi create mode 100644 stubs/convertdate/convertdate/daycount.pyi create mode 100644 stubs/convertdate/convertdate/dublin.pyi create mode 100644 stubs/convertdate/convertdate/french_republican.pyi create mode 100644 stubs/convertdate/convertdate/gregorian.pyi create mode 100644 stubs/convertdate/convertdate/hebrew.pyi create mode 100644 stubs/convertdate/convertdate/holidays.pyi create mode 100644 stubs/convertdate/convertdate/indian_civil.pyi create mode 100644 stubs/convertdate/convertdate/islamic.pyi create mode 100644 stubs/convertdate/convertdate/iso.pyi create mode 100644 stubs/convertdate/convertdate/julian.pyi create mode 100644 stubs/convertdate/convertdate/julianday.pyi create mode 100644 stubs/convertdate/convertdate/mayan.pyi create mode 100644 stubs/convertdate/convertdate/ordinal.pyi create mode 100644 stubs/convertdate/convertdate/persian.pyi create mode 100644 stubs/convertdate/convertdate/positivist.pyi create mode 100644 stubs/convertdate/convertdate/utils.pyi create mode 100644 stubs/croniter/@tests/stubtest_allowlist.txt create mode 100644 stubs/croniter/METADATA.toml create mode 100644 stubs/croniter/croniter/__init__.pyi create mode 100644 stubs/croniter/croniter/croniter.pyi create mode 100644 stubs/datauri/METADATA.toml create mode 100644 stubs/datauri/datauri/__init__.pyi create mode 100644 stubs/datauri/datauri/datauri.pyi create mode 100644 stubs/dateparser/@tests/stubtest_allowlist.txt create mode 100644 stubs/dateparser/METADATA.toml create mode 100644 stubs/dateparser/dateparser/__init__.pyi create mode 100644 stubs/dateparser/dateparser/calendars/__init__.pyi create mode 100644 stubs/dateparser/dateparser/calendars/hijri.pyi create mode 100644 stubs/dateparser/dateparser/calendars/hijri_parser.pyi create mode 100644 stubs/dateparser/dateparser/calendars/jalali.pyi create mode 100644 stubs/dateparser/dateparser/calendars/jalali_parser.pyi create mode 100644 stubs/dateparser/dateparser/conf.pyi create mode 100644 stubs/dateparser/dateparser/custom_language_detection/__init__.pyi create mode 100644 stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi create mode 100644 stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi create mode 100644 stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi create mode 100644 stubs/dateparser/dateparser/data/__init__.pyi create mode 100644 stubs/dateparser/dateparser/data/languages_info.pyi create mode 100644 stubs/dateparser/dateparser/date.pyi create mode 100644 stubs/dateparser/dateparser/date_parser.pyi create mode 100644 stubs/dateparser/dateparser/freshness_date_parser.pyi create mode 100644 stubs/dateparser/dateparser/languages/__init__.pyi create mode 100644 stubs/dateparser/dateparser/languages/dictionary.pyi create mode 100644 stubs/dateparser/dateparser/languages/loader.pyi create mode 100644 stubs/dateparser/dateparser/languages/locale.pyi create mode 100644 stubs/dateparser/dateparser/languages/validation.pyi create mode 100644 stubs/dateparser/dateparser/parser.pyi create mode 100644 stubs/dateparser/dateparser/search/__init__.pyi create mode 100644 stubs/dateparser/dateparser/search/detection.pyi create mode 100644 stubs/dateparser/dateparser/search/search.pyi create mode 100644 stubs/dateparser/dateparser/search/text_detection.pyi create mode 100644 stubs/dateparser/dateparser/timezone_parser.pyi create mode 100644 stubs/dateparser/dateparser/timezones.pyi create mode 100644 stubs/dateparser/dateparser/utils/__init__.pyi create mode 100644 stubs/dateparser/dateparser/utils/strptime.pyi create mode 100644 stubs/dateparser/dateparser/utils/time_spans.pyi create mode 100644 stubs/dateparser/dateparser_data/__init__.pyi create mode 100644 stubs/dateparser/dateparser_data/settings.pyi create mode 100644 stubs/decorator/@tests/stubtest_allowlist.txt create mode 100644 stubs/decorator/METADATA.toml create mode 100644 stubs/decorator/decorator.pyi create mode 100644 stubs/defusedxml/METADATA.toml create mode 100644 stubs/defusedxml/defusedxml/ElementTree.pyi create mode 100644 stubs/defusedxml/defusedxml/__init__.pyi create mode 100644 stubs/defusedxml/defusedxml/cElementTree.pyi create mode 100644 stubs/defusedxml/defusedxml/common.pyi create mode 100644 stubs/defusedxml/defusedxml/expatbuilder.pyi create mode 100644 stubs/defusedxml/defusedxml/expatreader.pyi create mode 100644 stubs/defusedxml/defusedxml/lxml.pyi create mode 100644 stubs/defusedxml/defusedxml/minidom.pyi create mode 100644 stubs/defusedxml/defusedxml/pulldom.pyi create mode 100644 stubs/defusedxml/defusedxml/sax.pyi create mode 100644 stubs/defusedxml/defusedxml/xmlrpc.pyi create mode 100644 stubs/dirhash/METADATA.toml create mode 100644 stubs/dirhash/dirhash/__init__.pyi create mode 100644 stubs/dirhash/dirhash/cli.pyi create mode 100644 stubs/django-filter/@tests/django_settings.py create mode 100644 stubs/django-filter/@tests/stubtest_allowlist.txt create mode 100644 stubs/django-filter/METADATA.toml create mode 100644 stubs/django-filter/django_filters/__init__.pyi create mode 100644 stubs/django-filter/django_filters/compat.pyi create mode 100644 stubs/django-filter/django_filters/conf.pyi create mode 100644 stubs/django-filter/django_filters/constants.pyi create mode 100644 stubs/django-filter/django_filters/exceptions.pyi create mode 100644 stubs/django-filter/django_filters/fields.pyi create mode 100644 stubs/django-filter/django_filters/filters.pyi create mode 100644 stubs/django-filter/django_filters/filterset.pyi create mode 100644 stubs/django-filter/django_filters/rest_framework/__init__.pyi create mode 100644 stubs/django-filter/django_filters/rest_framework/backends.pyi create mode 100644 stubs/django-filter/django_filters/rest_framework/filters.pyi create mode 100644 stubs/django-filter/django_filters/rest_framework/filterset.pyi create mode 100644 stubs/django-filter/django_filters/utils.pyi create mode 100644 stubs/django-filter/django_filters/views.pyi create mode 100644 stubs/django-filter/django_filters/widgets.pyi create mode 100644 stubs/django-import-export/METADATA.toml create mode 100644 stubs/django-import-export/import_export/__init__.pyi create mode 100644 stubs/django-import-export/import_export/admin.pyi create mode 100644 stubs/django-import-export/import_export/command_utils.pyi create mode 100644 stubs/django-import-export/import_export/declarative.pyi create mode 100644 stubs/django-import-export/import_export/exceptions.pyi create mode 100644 stubs/django-import-export/import_export/fields.pyi create mode 100644 stubs/django-import-export/import_export/formats/__init__.pyi create mode 100644 stubs/django-import-export/import_export/formats/base_formats.pyi create mode 100644 stubs/django-import-export/import_export/forms.pyi create mode 100644 stubs/django-import-export/import_export/instance_loaders.pyi create mode 100644 stubs/django-import-export/import_export/mixins.pyi create mode 100644 stubs/django-import-export/import_export/options.pyi create mode 100644 stubs/django-import-export/import_export/resources.pyi create mode 100644 stubs/django-import-export/import_export/results.pyi create mode 100644 stubs/django-import-export/import_export/signals.pyi create mode 100644 stubs/django-import-export/import_export/templatetags/__init__.pyi create mode 100644 stubs/django-import-export/import_export/templatetags/import_export_tags.pyi create mode 100644 stubs/django-import-export/import_export/tmp_storages.pyi create mode 100644 stubs/django-import-export/import_export/utils.pyi create mode 100644 stubs/django-import-export/import_export/widgets.pyi create mode 100644 stubs/django-import-export/management/__init__.pyi create mode 100644 stubs/django-import-export/management/commands/__init__.pyi create mode 100644 stubs/django-import-export/management/commands/export.pyi create mode 100644 stubs/django-import-export/management/commands/import.pyi create mode 100644 stubs/docker/@tests/stubtest_allowlist.txt create mode 100644 stubs/docker/@tests/test_cases/check_attach.py create mode 100644 stubs/docker/METADATA.toml create mode 100644 stubs/docker/docker/__init__.pyi create mode 100644 stubs/docker/docker/_types.pyi create mode 100644 stubs/docker/docker/api/__init__.pyi create mode 100644 stubs/docker/docker/api/build.pyi create mode 100644 stubs/docker/docker/api/client.pyi create mode 100644 stubs/docker/docker/api/config.pyi create mode 100644 stubs/docker/docker/api/container.pyi create mode 100644 stubs/docker/docker/api/daemon.pyi create mode 100644 stubs/docker/docker/api/exec_api.pyi create mode 100644 stubs/docker/docker/api/image.pyi create mode 100644 stubs/docker/docker/api/network.pyi create mode 100644 stubs/docker/docker/api/plugin.pyi create mode 100644 stubs/docker/docker/api/secret.pyi create mode 100644 stubs/docker/docker/api/service.pyi create mode 100644 stubs/docker/docker/api/swarm.pyi create mode 100644 stubs/docker/docker/api/volume.pyi create mode 100644 stubs/docker/docker/auth.pyi create mode 100644 stubs/docker/docker/client.pyi create mode 100644 stubs/docker/docker/constants.pyi create mode 100644 stubs/docker/docker/context/__init__.pyi create mode 100644 stubs/docker/docker/context/api.pyi create mode 100644 stubs/docker/docker/context/config.pyi create mode 100644 stubs/docker/docker/context/context.pyi create mode 100644 stubs/docker/docker/credentials/__init__.pyi create mode 100644 stubs/docker/docker/credentials/constants.pyi create mode 100644 stubs/docker/docker/credentials/errors.pyi create mode 100644 stubs/docker/docker/credentials/store.pyi create mode 100644 stubs/docker/docker/credentials/utils.pyi create mode 100644 stubs/docker/docker/errors.pyi create mode 100644 stubs/docker/docker/models/__init__.pyi create mode 100644 stubs/docker/docker/models/configs.pyi create mode 100644 stubs/docker/docker/models/containers.pyi create mode 100644 stubs/docker/docker/models/images.pyi create mode 100644 stubs/docker/docker/models/networks.pyi create mode 100644 stubs/docker/docker/models/nodes.pyi create mode 100644 stubs/docker/docker/models/plugins.pyi create mode 100644 stubs/docker/docker/models/resource.pyi create mode 100644 stubs/docker/docker/models/secrets.pyi create mode 100644 stubs/docker/docker/models/services.pyi create mode 100644 stubs/docker/docker/models/swarm.pyi create mode 100644 stubs/docker/docker/models/volumes.pyi create mode 100644 stubs/docker/docker/tls.pyi create mode 100644 stubs/docker/docker/transport/__init__.pyi create mode 100644 stubs/docker/docker/transport/basehttpadapter.pyi create mode 100644 stubs/docker/docker/transport/npipeconn.pyi create mode 100644 stubs/docker/docker/transport/npipesocket.pyi create mode 100644 stubs/docker/docker/transport/sshconn.pyi create mode 100644 stubs/docker/docker/transport/unixconn.pyi create mode 100644 stubs/docker/docker/types/__init__.pyi create mode 100644 stubs/docker/docker/types/base.pyi create mode 100644 stubs/docker/docker/types/containers.pyi create mode 100644 stubs/docker/docker/types/daemon.pyi create mode 100644 stubs/docker/docker/types/healthcheck.pyi create mode 100644 stubs/docker/docker/types/networks.pyi create mode 100644 stubs/docker/docker/types/services.pyi create mode 100644 stubs/docker/docker/types/swarm.pyi create mode 100644 stubs/docker/docker/utils/__init__.pyi create mode 100644 stubs/docker/docker/utils/build.pyi create mode 100644 stubs/docker/docker/utils/config.pyi create mode 100644 stubs/docker/docker/utils/decorators.pyi create mode 100644 stubs/docker/docker/utils/fnmatch.pyi create mode 100644 stubs/docker/docker/utils/json_stream.pyi create mode 100644 stubs/docker/docker/utils/ports.pyi create mode 100644 stubs/docker/docker/utils/proxy.pyi create mode 100644 stubs/docker/docker/utils/socket.pyi create mode 100644 stubs/docker/docker/utils/utils.pyi create mode 100644 stubs/docker/docker/version.pyi create mode 100644 stubs/dockerfile-parse/METADATA.toml create mode 100644 stubs/dockerfile-parse/dockerfile_parse/__init__.pyi create mode 100644 stubs/dockerfile-parse/dockerfile_parse/constants.pyi create mode 100644 stubs/dockerfile-parse/dockerfile_parse/parser.pyi create mode 100644 stubs/dockerfile-parse/dockerfile_parse/util.pyi create mode 100644 stubs/docutils/@tests/stubtest_allowlist.txt create mode 100644 stubs/docutils/METADATA.toml create mode 100644 stubs/docutils/docutils/__init__.pyi create mode 100644 stubs/docutils/docutils/__main__.pyi create mode 100644 stubs/docutils/docutils/core.pyi create mode 100644 stubs/docutils/docutils/examples.pyi create mode 100644 stubs/docutils/docutils/frontend.pyi create mode 100644 stubs/docutils/docutils/io.pyi create mode 100644 stubs/docutils/docutils/languages/__init__.pyi create mode 100644 stubs/docutils/docutils/languages/af.pyi create mode 100644 stubs/docutils/docutils/languages/ar.pyi create mode 100644 stubs/docutils/docutils/languages/ca.pyi create mode 100644 stubs/docutils/docutils/languages/cs.pyi create mode 100644 stubs/docutils/docutils/languages/da.pyi create mode 100644 stubs/docutils/docutils/languages/de.pyi create mode 100644 stubs/docutils/docutils/languages/en.pyi create mode 100644 stubs/docutils/docutils/languages/eo.pyi create mode 100644 stubs/docutils/docutils/languages/es.pyi create mode 100644 stubs/docutils/docutils/languages/fa.pyi create mode 100644 stubs/docutils/docutils/languages/fi.pyi create mode 100644 stubs/docutils/docutils/languages/fr.pyi create mode 100644 stubs/docutils/docutils/languages/gl.pyi create mode 100644 stubs/docutils/docutils/languages/he.pyi create mode 100644 stubs/docutils/docutils/languages/it.pyi create mode 100644 stubs/docutils/docutils/languages/ja.pyi create mode 100644 stubs/docutils/docutils/languages/ka.pyi create mode 100644 stubs/docutils/docutils/languages/ko.pyi create mode 100644 stubs/docutils/docutils/languages/lt.pyi create mode 100644 stubs/docutils/docutils/languages/lv.pyi create mode 100644 stubs/docutils/docutils/languages/nl.pyi create mode 100644 stubs/docutils/docutils/languages/pl.pyi create mode 100644 stubs/docutils/docutils/languages/pt_br.pyi create mode 100644 stubs/docutils/docutils/languages/ru.pyi create mode 100644 stubs/docutils/docutils/languages/sk.pyi create mode 100644 stubs/docutils/docutils/languages/sv.pyi create mode 100644 stubs/docutils/docutils/languages/uk.pyi create mode 100644 stubs/docutils/docutils/languages/zh_cn.pyi create mode 100644 stubs/docutils/docutils/languages/zh_tw.pyi create mode 100644 stubs/docutils/docutils/nodes.pyi create mode 100644 stubs/docutils/docutils/parsers/__init__.pyi create mode 100644 stubs/docutils/docutils/parsers/commonmark_wrapper.pyi create mode 100644 stubs/docutils/docutils/parsers/docutils_xml.pyi create mode 100644 stubs/docutils/docutils/parsers/null.pyi create mode 100644 stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/__init__.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/__init__.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/body.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/html.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/images.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/misc.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/parts.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/references.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/directives/tables.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/__init__.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/af.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ar.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ca.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/cs.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/da.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/de.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/en.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/eo.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/es.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/fa.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/fi.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/fr.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/gl.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/he.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/it.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ja.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ka.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ko.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/lt.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/lv.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/nl.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/pl.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/ru.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/sk.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/sv.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/uk.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/roles.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/states.pyi create mode 100644 stubs/docutils/docutils/parsers/rst/tableparser.pyi create mode 100644 stubs/docutils/docutils/readers/__init__.pyi create mode 100644 stubs/docutils/docutils/readers/doctree.pyi create mode 100644 stubs/docutils/docutils/readers/pep.pyi create mode 100644 stubs/docutils/docutils/readers/standalone.pyi create mode 100644 stubs/docutils/docutils/statemachine.pyi create mode 100644 stubs/docutils/docutils/transforms/__init__.pyi create mode 100644 stubs/docutils/docutils/transforms/components.pyi create mode 100644 stubs/docutils/docutils/transforms/frontmatter.pyi create mode 100644 stubs/docutils/docutils/transforms/misc.pyi create mode 100644 stubs/docutils/docutils/transforms/parts.pyi create mode 100644 stubs/docutils/docutils/transforms/peps.pyi create mode 100644 stubs/docutils/docutils/transforms/references.pyi create mode 100644 stubs/docutils/docutils/transforms/universal.pyi create mode 100644 stubs/docutils/docutils/transforms/writer_aux.pyi create mode 100644 stubs/docutils/docutils/utils/__init__.pyi create mode 100644 stubs/docutils/docutils/utils/_roman_numerals.pyi create mode 100644 stubs/docutils/docutils/utils/code_analyzer.pyi create mode 100644 stubs/docutils/docutils/utils/math/__init__.pyi create mode 100644 stubs/docutils/docutils/utils/math/latex2mathml.pyi create mode 100644 stubs/docutils/docutils/utils/math/math2html.pyi create mode 100644 stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi create mode 100644 stubs/docutils/docutils/utils/math/mathml_elements.pyi create mode 100644 stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi create mode 100644 stubs/docutils/docutils/utils/math/tex2unichar.pyi create mode 100644 stubs/docutils/docutils/utils/math/unichar2tex.pyi create mode 100644 stubs/docutils/docutils/utils/punctuation_chars.pyi create mode 100644 stubs/docutils/docutils/utils/smartquotes.pyi create mode 100644 stubs/docutils/docutils/utils/urischemes.pyi create mode 100644 stubs/docutils/docutils/writers/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/_html_base.pyi create mode 100644 stubs/docutils/docutils/writers/docutils_xml.pyi create mode 100644 stubs/docutils/docutils/writers/html4css1/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/latex2e/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/manpage.pyi create mode 100644 stubs/docutils/docutils/writers/null.pyi create mode 100644 stubs/docutils/docutils/writers/odf_odt/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi create mode 100644 stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi create mode 100644 stubs/docutils/docutils/writers/pep_html/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/pseudoxml.pyi create mode 100644 stubs/docutils/docutils/writers/s5_html/__init__.pyi create mode 100644 stubs/docutils/docutils/writers/xetex/__init__.pyi create mode 100644 stubs/editdistance/@tests/stubtest_allowlist.txt create mode 100644 stubs/editdistance/METADATA.toml create mode 100644 stubs/editdistance/editdistance/__init__.pyi create mode 100644 stubs/entrypoints/@tests/stubtest_allowlist.txt create mode 100644 stubs/entrypoints/METADATA.toml create mode 100644 stubs/entrypoints/entrypoints.pyi create mode 100644 stubs/ephem/@tests/stubtest_allowlist.txt create mode 100644 stubs/ephem/METADATA.toml create mode 100644 stubs/ephem/ephem/__init__.pyi create mode 100644 stubs/ephem/ephem/_libastro.pyi create mode 100644 stubs/ephem/ephem/cities.pyi create mode 100644 stubs/ephem/ephem/stars.pyi create mode 100644 stubs/et_xmlfile/METADATA.toml create mode 100644 stubs/et_xmlfile/et_xmlfile/__init__.pyi create mode 100644 stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi create mode 100644 stubs/et_xmlfile/et_xmlfile/xmlfile.pyi create mode 100644 stubs/fanstatic/@tests/stubtest_allowlist.txt create mode 100644 stubs/fanstatic/METADATA.toml create mode 100644 stubs/fanstatic/fanstatic/__init__.pyi create mode 100644 stubs/fanstatic/fanstatic/checksum.pyi create mode 100644 stubs/fanstatic/fanstatic/compiler.pyi create mode 100644 stubs/fanstatic/fanstatic/config.pyi create mode 100644 stubs/fanstatic/fanstatic/core.pyi create mode 100644 stubs/fanstatic/fanstatic/inclusion.pyi create mode 100644 stubs/fanstatic/fanstatic/injector.pyi create mode 100644 stubs/fanstatic/fanstatic/publisher.pyi create mode 100644 stubs/fanstatic/fanstatic/registry.pyi create mode 100644 stubs/fanstatic/fanstatic/wsgi.pyi create mode 100644 stubs/first/METADATA.toml create mode 100644 stubs/first/first.pyi create mode 100644 stubs/flake8-bugbear/@tests/stubtest_allowlist.txt create mode 100644 stubs/flake8-bugbear/METADATA.toml create mode 100644 stubs/flake8-bugbear/bugbear.pyi create mode 100644 stubs/flake8-builtins/METADATA.toml create mode 100644 stubs/flake8-builtins/flake8_builtins.pyi create mode 100644 stubs/flake8-docstrings/METADATA.toml create mode 100644 stubs/flake8-docstrings/flake8_docstrings.pyi create mode 100644 stubs/flake8-rst-docstrings/METADATA.toml create mode 100644 stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi create mode 100644 stubs/flake8-simplify/METADATA.toml create mode 100644 stubs/flake8-simplify/flake8_simplify/__init__.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/constants.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/__init__.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi create mode 100644 stubs/flake8-simplify/flake8_simplify/utils.pyi create mode 100644 stubs/flake8-typing-imports/METADATA.toml create mode 100644 stubs/flake8-typing-imports/flake8_typing_imports.pyi create mode 100644 stubs/flake8/@tests/stubtest_allowlist.txt create mode 100644 stubs/flake8/METADATA.toml create mode 100644 stubs/flake8/flake8/__init__.pyi create mode 100644 stubs/flake8/flake8/_compat.pyi create mode 100644 stubs/flake8/flake8/api/__init__.pyi create mode 100644 stubs/flake8/flake8/api/legacy.pyi create mode 100644 stubs/flake8/flake8/checker.pyi create mode 100644 stubs/flake8/flake8/defaults.pyi create mode 100644 stubs/flake8/flake8/discover_files.pyi create mode 100644 stubs/flake8/flake8/exceptions.pyi create mode 100644 stubs/flake8/flake8/formatting/__init__.pyi create mode 100644 stubs/flake8/flake8/formatting/_windows_color.pyi create mode 100644 stubs/flake8/flake8/formatting/base.pyi create mode 100644 stubs/flake8/flake8/formatting/default.pyi create mode 100644 stubs/flake8/flake8/main/__init__.pyi create mode 100644 stubs/flake8/flake8/main/application.pyi create mode 100644 stubs/flake8/flake8/main/cli.pyi create mode 100644 stubs/flake8/flake8/main/debug.pyi create mode 100644 stubs/flake8/flake8/main/options.pyi create mode 100644 stubs/flake8/flake8/options/__init__.pyi create mode 100644 stubs/flake8/flake8/options/aggregator.pyi create mode 100644 stubs/flake8/flake8/options/config.pyi create mode 100644 stubs/flake8/flake8/options/manager.pyi create mode 100644 stubs/flake8/flake8/options/parse_args.pyi create mode 100644 stubs/flake8/flake8/plugins/__init__.pyi create mode 100644 stubs/flake8/flake8/plugins/finder.pyi create mode 100644 stubs/flake8/flake8/plugins/pycodestyle.pyi create mode 100644 stubs/flake8/flake8/plugins/pyflakes.pyi create mode 100644 stubs/flake8/flake8/plugins/reporter.pyi create mode 100644 stubs/flake8/flake8/processor.pyi create mode 100644 stubs/flake8/flake8/statistics.pyi create mode 100644 stubs/flake8/flake8/style_guide.pyi create mode 100644 stubs/flake8/flake8/utils.pyi create mode 100644 stubs/flake8/flake8/violation.pyi create mode 100644 stubs/fpdf2/@tests/stubtest_allowlist.txt create mode 100644 stubs/fpdf2/METADATA.toml create mode 100644 stubs/fpdf2/fpdf/__init__.pyi create mode 100644 stubs/fpdf2/fpdf/_fonttools_shims.pyi create mode 100644 stubs/fpdf2/fpdf/actions.pyi create mode 100644 stubs/fpdf2/fpdf/annotations.pyi create mode 100644 stubs/fpdf2/fpdf/bidi.pyi create mode 100644 stubs/fpdf2/fpdf/deprecation.pyi create mode 100644 stubs/fpdf2/fpdf/drawing.pyi create mode 100644 stubs/fpdf2/fpdf/encryption.pyi create mode 100644 stubs/fpdf2/fpdf/enums.pyi create mode 100644 stubs/fpdf2/fpdf/errors.pyi create mode 100644 stubs/fpdf2/fpdf/fonts.pyi create mode 100644 stubs/fpdf2/fpdf/fpdf.pyi create mode 100644 stubs/fpdf2/fpdf/graphics_state.pyi create mode 100644 stubs/fpdf2/fpdf/html.pyi create mode 100644 stubs/fpdf2/fpdf/image_datastructures.pyi create mode 100644 stubs/fpdf2/fpdf/image_parsing.pyi create mode 100644 stubs/fpdf2/fpdf/line_break.pyi create mode 100644 stubs/fpdf2/fpdf/linearization.pyi create mode 100644 stubs/fpdf2/fpdf/outline.pyi create mode 100644 stubs/fpdf2/fpdf/output.pyi create mode 100644 stubs/fpdf2/fpdf/pattern.pyi create mode 100644 stubs/fpdf2/fpdf/prefs.pyi create mode 100644 stubs/fpdf2/fpdf/recorder.pyi create mode 100644 stubs/fpdf2/fpdf/sign.pyi create mode 100644 stubs/fpdf2/fpdf/structure_tree.pyi create mode 100644 stubs/fpdf2/fpdf/svg.pyi create mode 100644 stubs/fpdf2/fpdf/syntax.pyi create mode 100644 stubs/fpdf2/fpdf/table.pyi create mode 100644 stubs/fpdf2/fpdf/template.pyi create mode 100644 stubs/fpdf2/fpdf/text_region.pyi create mode 100644 stubs/fpdf2/fpdf/transitions.pyi create mode 100644 stubs/fpdf2/fpdf/unicode_script.pyi create mode 100644 stubs/fpdf2/fpdf/util.pyi create mode 100644 stubs/gdb/@tests/stubtest_allowlist.txt create mode 100644 stubs/gdb/METADATA.toml create mode 100644 stubs/gdb/gdb/FrameDecorator.pyi create mode 100644 stubs/gdb/gdb/FrameIterator.pyi create mode 100644 stubs/gdb/gdb/__init__.pyi create mode 100644 stubs/gdb/gdb/dap/__init__.pyi create mode 100644 stubs/gdb/gdb/dap/breakpoint.pyi create mode 100644 stubs/gdb/gdb/dap/bt.pyi create mode 100644 stubs/gdb/gdb/dap/disassemble.pyi create mode 100644 stubs/gdb/gdb/dap/evaluate.pyi create mode 100644 stubs/gdb/gdb/dap/events.pyi create mode 100644 stubs/gdb/gdb/dap/frames.pyi create mode 100644 stubs/gdb/gdb/dap/io.pyi create mode 100644 stubs/gdb/gdb/dap/launch.pyi create mode 100644 stubs/gdb/gdb/dap/locations.pyi create mode 100644 stubs/gdb/gdb/dap/memory.pyi create mode 100644 stubs/gdb/gdb/dap/modules.pyi create mode 100644 stubs/gdb/gdb/dap/next.pyi create mode 100644 stubs/gdb/gdb/dap/pause.pyi create mode 100644 stubs/gdb/gdb/dap/scopes.pyi create mode 100644 stubs/gdb/gdb/dap/server.pyi create mode 100644 stubs/gdb/gdb/dap/sources.pyi create mode 100644 stubs/gdb/gdb/dap/startup.pyi create mode 100644 stubs/gdb/gdb/dap/state.pyi create mode 100644 stubs/gdb/gdb/dap/threads.pyi create mode 100644 stubs/gdb/gdb/dap/typecheck.pyi create mode 100644 stubs/gdb/gdb/dap/varref.pyi create mode 100644 stubs/gdb/gdb/disassembler.pyi create mode 100644 stubs/gdb/gdb/events.pyi create mode 100644 stubs/gdb/gdb/missing_debug.pyi create mode 100644 stubs/gdb/gdb/missing_files.pyi create mode 100644 stubs/gdb/gdb/missing_objfile.pyi create mode 100644 stubs/gdb/gdb/printing.pyi create mode 100644 stubs/gdb/gdb/prompt.pyi create mode 100644 stubs/gdb/gdb/types.pyi create mode 100644 stubs/gdb/gdb/unwinder.pyi create mode 100644 stubs/gdb/gdb/xmethod.pyi create mode 100644 stubs/geojson/@tests/stubtest_allowlist.txt create mode 100644 stubs/geojson/METADATA.toml create mode 100644 stubs/geojson/geojson/__init__.pyi create mode 100644 stubs/geojson/geojson/_version.pyi create mode 100644 stubs/geojson/geojson/base.pyi create mode 100644 stubs/geojson/geojson/codec.pyi create mode 100644 stubs/geojson/geojson/feature.pyi create mode 100644 stubs/geojson/geojson/geometry.pyi create mode 100644 stubs/geojson/geojson/mapping.pyi create mode 100644 stubs/geojson/geojson/utils.pyi create mode 100644 stubs/geopandas/@tests/stubtest_allowlist.txt create mode 100644 stubs/geopandas/METADATA.toml create mode 100644 stubs/geopandas/geopandas/__init__.pyi create mode 100644 stubs/geopandas/geopandas/_config.pyi create mode 100644 stubs/geopandas/geopandas/_decorator.pyi create mode 100644 stubs/geopandas/geopandas/_exports.pyi create mode 100644 stubs/geopandas/geopandas/accessors.pyi create mode 100644 stubs/geopandas/geopandas/array.pyi create mode 100644 stubs/geopandas/geopandas/base.pyi create mode 100644 stubs/geopandas/geopandas/explore.pyi create mode 100644 stubs/geopandas/geopandas/geodataframe.pyi create mode 100644 stubs/geopandas/geopandas/geoseries.pyi create mode 100644 stubs/geopandas/geopandas/io/__init__.pyi create mode 100644 stubs/geopandas/geopandas/io/_geoarrow.pyi create mode 100644 stubs/geopandas/geopandas/io/arrow.pyi create mode 100644 stubs/geopandas/geopandas/io/file.pyi create mode 100644 stubs/geopandas/geopandas/io/sql.pyi create mode 100644 stubs/geopandas/geopandas/plotting.pyi create mode 100644 stubs/geopandas/geopandas/sindex.pyi create mode 100644 stubs/geopandas/geopandas/testing.pyi create mode 100644 stubs/geopandas/geopandas/tools/__init__.pyi create mode 100644 stubs/geopandas/geopandas/tools/_show_versions.pyi create mode 100644 stubs/geopandas/geopandas/tools/clip.pyi create mode 100644 stubs/geopandas/geopandas/tools/geocoding.pyi create mode 100644 stubs/geopandas/geopandas/tools/hilbert_curve.pyi create mode 100644 stubs/geopandas/geopandas/tools/overlay.pyi create mode 100644 stubs/geopandas/geopandas/tools/sjoin.pyi create mode 100644 stubs/geopandas/geopandas/tools/util.pyi create mode 100644 stubs/gevent/@tests/stubtest_allowlist.txt create mode 100644 stubs/gevent/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/gevent/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/gevent/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/gevent/METADATA.toml create mode 100644 stubs/gevent/gevent/__init__.pyi create mode 100644 stubs/gevent/gevent/_abstract_linkable.pyi create mode 100644 stubs/gevent/gevent/_config.pyi create mode 100644 stubs/gevent/gevent/_ffi/__init__.pyi create mode 100644 stubs/gevent/gevent/_ffi/loop.pyi create mode 100644 stubs/gevent/gevent/_ffi/watcher.pyi create mode 100644 stubs/gevent/gevent/_fileobjectcommon.pyi create mode 100644 stubs/gevent/gevent/_greenlet_primitives.pyi create mode 100644 stubs/gevent/gevent/_hub_local.pyi create mode 100644 stubs/gevent/gevent/_hub_primitives.pyi create mode 100644 stubs/gevent/gevent/_ident.pyi create mode 100644 stubs/gevent/gevent/_imap.pyi create mode 100644 stubs/gevent/gevent/_monitor.pyi create mode 100644 stubs/gevent/gevent/_threading.pyi create mode 100644 stubs/gevent/gevent/_types.pyi create mode 100644 stubs/gevent/gevent/_util.pyi create mode 100644 stubs/gevent/gevent/_waiter.pyi create mode 100644 stubs/gevent/gevent/ares.pyi create mode 100644 stubs/gevent/gevent/backdoor.pyi create mode 100644 stubs/gevent/gevent/baseserver.pyi create mode 100644 stubs/gevent/gevent/event.pyi create mode 100644 stubs/gevent/gevent/events.pyi create mode 100644 stubs/gevent/gevent/exceptions.pyi create mode 100644 stubs/gevent/gevent/fileobject.pyi create mode 100644 stubs/gevent/gevent/greenlet.pyi create mode 100644 stubs/gevent/gevent/hub.pyi create mode 100644 stubs/gevent/gevent/libev/__init__.pyi create mode 100644 stubs/gevent/gevent/libev/corecext.pyi create mode 100644 stubs/gevent/gevent/libev/corecffi.pyi create mode 100644 stubs/gevent/gevent/libev/watcher.pyi create mode 100644 stubs/gevent/gevent/libuv/__init__.pyi create mode 100644 stubs/gevent/gevent/libuv/loop.pyi create mode 100644 stubs/gevent/gevent/libuv/watcher.pyi create mode 100644 stubs/gevent/gevent/local.pyi create mode 100644 stubs/gevent/gevent/lock.pyi create mode 100644 stubs/gevent/gevent/monkey/__init__.pyi create mode 100644 stubs/gevent/gevent/monkey/api.pyi create mode 100644 stubs/gevent/gevent/os.pyi create mode 100644 stubs/gevent/gevent/pool.pyi create mode 100644 stubs/gevent/gevent/pywsgi.pyi create mode 100644 stubs/gevent/gevent/queue.pyi create mode 100644 stubs/gevent/gevent/resolver/__init__.pyi create mode 100644 stubs/gevent/gevent/resolver/ares.pyi create mode 100644 stubs/gevent/gevent/resolver/blocking.pyi create mode 100644 stubs/gevent/gevent/resolver/cares.pyi create mode 100644 stubs/gevent/gevent/resolver/dnspython.pyi create mode 100644 stubs/gevent/gevent/resolver/thread.pyi create mode 100644 stubs/gevent/gevent/resolver_ares.pyi create mode 100644 stubs/gevent/gevent/resolver_thread.pyi create mode 100644 stubs/gevent/gevent/select.pyi create mode 100644 stubs/gevent/gevent/selectors.pyi create mode 100644 stubs/gevent/gevent/server.pyi create mode 100644 stubs/gevent/gevent/signal.pyi create mode 100644 stubs/gevent/gevent/socket.pyi create mode 100644 stubs/gevent/gevent/ssl.pyi create mode 100644 stubs/gevent/gevent/subprocess.pyi create mode 100644 stubs/gevent/gevent/threadpool.pyi create mode 100644 stubs/gevent/gevent/time.pyi create mode 100644 stubs/gevent/gevent/timeout.pyi create mode 100644 stubs/gevent/gevent/util.pyi create mode 100644 stubs/gevent/gevent/win32util.pyi create mode 100644 stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt create mode 100644 stubs/google-cloud-ndb/METADATA.toml create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/client.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/context.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/django_middleware.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/key.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/model.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/msgprop.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/query.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi create mode 100644 stubs/google-cloud-ndb/google/cloud/ndb/version.pyi create mode 100644 stubs/greenlet/@tests/stubtest_allowlist.txt create mode 100644 stubs/greenlet/@tests/test_cases/check_greenlet.py create mode 100644 stubs/greenlet/METADATA.toml create mode 100644 stubs/greenlet/greenlet/__init__.pyi create mode 100644 stubs/greenlet/greenlet/_greenlet.pyi create mode 100644 stubs/grpcio-channelz/METADATA.toml create mode 100644 stubs/grpcio-channelz/grpc_channelz/__init__.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/__init__.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi create mode 100644 stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi create mode 100644 stubs/grpcio-health-checking/METADATA.toml create mode 100644 stubs/grpcio-health-checking/grpc_health/__init__.pyi create mode 100644 stubs/grpcio-health-checking/grpc_health/v1/__init__.pyi create mode 100644 stubs/grpcio-health-checking/grpc_health/v1/health.pyi create mode 100644 stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi create mode 100644 stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi create mode 100644 stubs/grpcio-reflection/@tests/test_cases/check_reflection.py create mode 100644 stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py create mode 100644 stubs/grpcio-reflection/METADATA.toml create mode 100644 stubs/grpcio-reflection/grpc_reflection/__init__.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/__init__.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi create mode 100644 stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi create mode 100644 stubs/grpcio-status/METADATA.toml create mode 100644 stubs/grpcio-status/grpc_status/__init__.pyi create mode 100644 stubs/grpcio-status/grpc_status/_async.pyi create mode 100644 stubs/grpcio-status/grpc_status/rpc_status.pyi create mode 100644 stubs/grpcio/@tests/stubtest_allowlist.txt create mode 100644 stubs/grpcio/@tests/test_cases/check_aio.py create mode 100644 stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py create mode 100644 stubs/grpcio/@tests/test_cases/check_grpc.py create mode 100644 stubs/grpcio/@tests/test_cases/check_handler_inheritance.py create mode 100644 stubs/grpcio/@tests/test_cases/check_multi_callable.py create mode 100644 stubs/grpcio/@tests/test_cases/check_register.py create mode 100644 stubs/grpcio/@tests/test_cases/check_server_interceptor.py create mode 100644 stubs/grpcio/METADATA.toml create mode 100644 stubs/grpcio/grpc/__init__.pyi create mode 100644 stubs/grpcio/grpc/aio/__init__.pyi create mode 100644 stubs/grpcio/grpc/experimental/gevent.pyi create mode 100644 stubs/gunicorn/@tests/stubtest_allowlist.txt create mode 100644 stubs/gunicorn/METADATA.toml create mode 100644 stubs/gunicorn/gunicorn/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/_types.pyi create mode 100644 stubs/gunicorn/gunicorn/app/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/app/base.pyi create mode 100644 stubs/gunicorn/gunicorn/app/pasterapp.pyi create mode 100644 stubs/gunicorn/gunicorn/app/wsgiapp.pyi create mode 100644 stubs/gunicorn/gunicorn/arbiter.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/lifespan.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/parser.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/protocol.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/unreader.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/uwsgi.pyi create mode 100644 stubs/gunicorn/gunicorn/asgi/websocket.pyi create mode 100644 stubs/gunicorn/gunicorn/config.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/cli.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/client.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/handlers.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/protocol.pyi create mode 100644 stubs/gunicorn/gunicorn/ctl/server.pyi create mode 100644 stubs/gunicorn/gunicorn/debug.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/app.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/arbiter.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/client.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/errors.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/protocol.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/stash.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/tlv.pyi create mode 100644 stubs/gunicorn/gunicorn/dirty/worker.pyi create mode 100644 stubs/gunicorn/gunicorn/errors.pyi create mode 100644 stubs/gunicorn/gunicorn/glogging.pyi create mode 100644 stubs/gunicorn/gunicorn/http/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/http/body.pyi create mode 100644 stubs/gunicorn/gunicorn/http/errors.pyi create mode 100644 stubs/gunicorn/gunicorn/http/message.pyi create mode 100644 stubs/gunicorn/gunicorn/http/parser.pyi create mode 100644 stubs/gunicorn/gunicorn/http/unreader.pyi create mode 100644 stubs/gunicorn/gunicorn/http/wsgi.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/async_connection.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/connection.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/errors.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/request.pyi create mode 100644 stubs/gunicorn/gunicorn/http2/stream.pyi create mode 100644 stubs/gunicorn/gunicorn/instrument/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/instrument/statsd.pyi create mode 100644 stubs/gunicorn/gunicorn/pidfile.pyi create mode 100644 stubs/gunicorn/gunicorn/reloader.pyi create mode 100644 stubs/gunicorn/gunicorn/sock.pyi create mode 100644 stubs/gunicorn/gunicorn/systemd.pyi create mode 100644 stubs/gunicorn/gunicorn/util.pyi create mode 100644 stubs/gunicorn/gunicorn/uwsgi/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/uwsgi/errors.pyi create mode 100644 stubs/gunicorn/gunicorn/uwsgi/message.pyi create mode 100644 stubs/gunicorn/gunicorn/uwsgi/parser.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/__init__.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/base.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/base_async.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/gasgi.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/ggevent.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/gthread.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/gtornado.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/sync.pyi create mode 100644 stubs/gunicorn/gunicorn/workers/workertmp.pyi create mode 100644 stubs/hdbcli/@tests/stubtest_allowlist.txt create mode 100644 stubs/hdbcli/METADATA.toml create mode 100644 stubs/hdbcli/hdbcli/__init__.pyi create mode 100644 stubs/hdbcli/hdbcli/dbapi.pyi create mode 100644 stubs/hdbcli/hdbcli/resultrow.pyi create mode 100644 stubs/hnswlib/@tests/stubtest_allowlist.txt create mode 100644 stubs/hnswlib/METADATA.toml create mode 100644 stubs/hnswlib/hnswlib.pyi create mode 100644 stubs/html5lib/@tests/stubtest_allowlist.txt create mode 100644 stubs/html5lib/METADATA.toml create mode 100644 stubs/html5lib/html5lib/__init__.pyi create mode 100644 stubs/html5lib/html5lib/_ihatexml.pyi create mode 100644 stubs/html5lib/html5lib/_inputstream.pyi create mode 100644 stubs/html5lib/html5lib/_tokenizer.pyi create mode 100644 stubs/html5lib/html5lib/_trie/__init__.pyi create mode 100644 stubs/html5lib/html5lib/_trie/_base.pyi create mode 100644 stubs/html5lib/html5lib/_trie/py.pyi create mode 100644 stubs/html5lib/html5lib/_utils.pyi create mode 100644 stubs/html5lib/html5lib/constants.pyi create mode 100644 stubs/html5lib/html5lib/filters/__init__.pyi create mode 100644 stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi create mode 100644 stubs/html5lib/html5lib/filters/base.pyi create mode 100644 stubs/html5lib/html5lib/filters/inject_meta_charset.pyi create mode 100644 stubs/html5lib/html5lib/filters/lint.pyi create mode 100644 stubs/html5lib/html5lib/filters/optionaltags.pyi create mode 100644 stubs/html5lib/html5lib/filters/sanitizer.pyi create mode 100644 stubs/html5lib/html5lib/filters/whitespace.pyi create mode 100644 stubs/html5lib/html5lib/html5parser.pyi create mode 100644 stubs/html5lib/html5lib/serializer.pyi create mode 100644 stubs/html5lib/html5lib/treeadapters/__init__.pyi create mode 100644 stubs/html5lib/html5lib/treeadapters/genshi.pyi create mode 100644 stubs/html5lib/html5lib/treeadapters/sax.pyi create mode 100644 stubs/html5lib/html5lib/treebuilders/__init__.pyi create mode 100644 stubs/html5lib/html5lib/treebuilders/base.pyi create mode 100644 stubs/html5lib/html5lib/treebuilders/dom.pyi create mode 100644 stubs/html5lib/html5lib/treebuilders/etree.pyi create mode 100644 stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/__init__.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/base.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/dom.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/etree.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi create mode 100644 stubs/html5lib/html5lib/treewalkers/genshi.pyi create mode 100644 stubs/httplib2/@tests/stubtest_allowlist.txt create mode 100644 stubs/httplib2/METADATA.toml create mode 100644 stubs/httplib2/httplib2/__init__.pyi create mode 100644 stubs/httplib2/httplib2/auth.pyi create mode 100644 stubs/httplib2/httplib2/certs.pyi create mode 100644 stubs/httplib2/httplib2/decode.pyi create mode 100644 stubs/httplib2/httplib2/error.pyi create mode 100644 stubs/httplib2/httplib2/iri2uri.pyi create mode 100644 stubs/hvac/METADATA.toml create mode 100644 stubs/hvac/hvac/__init__.pyi create mode 100644 stubs/hvac/hvac/adapters.pyi create mode 100644 stubs/hvac/hvac/api/__init__.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/__init__.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/approle.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/aws.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/azure.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/cert.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/gcp.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/github.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/jwt.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/kubernetes.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/ldap.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/oidc.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/okta.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/radius.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/token.pyi create mode 100644 stubs/hvac/hvac/api/auth_methods/userpass.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/__init__.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/active_directory.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/aws.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/azure.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/consul.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/database.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/gcp.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/identity.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/kv.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/ldap.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/pki.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/ssh.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/transform.pyi create mode 100644 stubs/hvac/hvac/api/secrets_engines/transit.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/__init__.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/audit.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/auth.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/capabilities.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/health.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/init.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/key.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/leader.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/lease.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/mount.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/namespace.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/policies.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/policy.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/quota.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/raft.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/seal.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi create mode 100644 stubs/hvac/hvac/api/system_backend/wrapping.pyi create mode 100644 stubs/hvac/hvac/api/vault_api_base.pyi create mode 100644 stubs/hvac/hvac/api/vault_api_category.pyi create mode 100644 stubs/hvac/hvac/aws_utils.pyi create mode 100644 stubs/hvac/hvac/constants/__init__.pyi create mode 100644 stubs/hvac/hvac/constants/approle.pyi create mode 100644 stubs/hvac/hvac/constants/aws.pyi create mode 100644 stubs/hvac/hvac/constants/azure.pyi create mode 100644 stubs/hvac/hvac/constants/client.pyi create mode 100644 stubs/hvac/hvac/constants/gcp.pyi create mode 100644 stubs/hvac/hvac/constants/identity.pyi create mode 100644 stubs/hvac/hvac/constants/transit.pyi create mode 100644 stubs/hvac/hvac/exceptions.pyi create mode 100644 stubs/hvac/hvac/utils.pyi create mode 100644 stubs/hvac/hvac/v1/__init__.pyi create mode 100644 stubs/ibm-db/METADATA.toml create mode 100644 stubs/ibm-db/ibm_db.pyi create mode 100644 stubs/ibm-db/ibm_db_ctx.pyi create mode 100644 stubs/icalendar/@tests/stubtest_allowlist.txt create mode 100644 stubs/icalendar/@tests/test_cases/check_cal.py create mode 100644 stubs/icalendar/METADATA.toml create mode 100644 stubs/icalendar/icalendar/__init__.pyi create mode 100644 stubs/icalendar/icalendar/alarms.pyi create mode 100644 stubs/icalendar/icalendar/attr.pyi create mode 100644 stubs/icalendar/icalendar/cal.pyi create mode 100644 stubs/icalendar/icalendar/caselessdict.pyi create mode 100644 stubs/icalendar/icalendar/enums.pyi create mode 100644 stubs/icalendar/icalendar/error.pyi create mode 100644 stubs/icalendar/icalendar/param.pyi create mode 100644 stubs/icalendar/icalendar/parser.pyi create mode 100644 stubs/icalendar/icalendar/parser_tools.pyi create mode 100644 stubs/icalendar/icalendar/prop.pyi create mode 100644 stubs/icalendar/icalendar/timezone/__init__.pyi create mode 100644 stubs/icalendar/icalendar/timezone/equivalent_timezone_ids.pyi create mode 100644 stubs/icalendar/icalendar/timezone/equivalent_timezone_ids_result.pyi create mode 100644 stubs/icalendar/icalendar/timezone/provider.pyi create mode 100644 stubs/icalendar/icalendar/timezone/pytz.pyi create mode 100644 stubs/icalendar/icalendar/timezone/tzid.pyi create mode 100644 stubs/icalendar/icalendar/timezone/tzp.pyi create mode 100644 stubs/icalendar/icalendar/timezone/windows_to_olson.pyi create mode 100644 stubs/icalendar/icalendar/timezone/zoneinfo.pyi create mode 100644 stubs/icalendar/icalendar/tools.pyi create mode 100644 stubs/icalendar/icalendar/version.pyi create mode 100644 stubs/inifile/@tests/stubtest_allowlist.txt create mode 100644 stubs/inifile/METADATA.toml create mode 100644 stubs/inifile/inifile.pyi create mode 100644 stubs/jmespath/METADATA.toml create mode 100644 stubs/jmespath/jmespath/__init__.pyi create mode 100644 stubs/jmespath/jmespath/ast.pyi create mode 100644 stubs/jmespath/jmespath/compat.pyi create mode 100644 stubs/jmespath/jmespath/exceptions.pyi create mode 100644 stubs/jmespath/jmespath/functions.pyi create mode 100644 stubs/jmespath/jmespath/lexer.pyi create mode 100644 stubs/jmespath/jmespath/parser.pyi create mode 100644 stubs/jmespath/jmespath/visitor.pyi create mode 100644 stubs/jsonnet/METADATA.toml create mode 100644 stubs/jsonnet/_jsonnet.pyi create mode 100644 stubs/jsonschema/@tests/stubtest_allowlist.txt create mode 100644 stubs/jsonschema/METADATA.toml create mode 100644 stubs/jsonschema/jsonschema/__init__.pyi create mode 100644 stubs/jsonschema/jsonschema/_format.pyi create mode 100644 stubs/jsonschema/jsonschema/_keywords.pyi create mode 100644 stubs/jsonschema/jsonschema/_legacy_keywords.pyi create mode 100644 stubs/jsonschema/jsonschema/_types.pyi create mode 100644 stubs/jsonschema/jsonschema/_typing.pyi create mode 100644 stubs/jsonschema/jsonschema/_utils.pyi create mode 100644 stubs/jsonschema/jsonschema/cli.pyi create mode 100644 stubs/jsonschema/jsonschema/exceptions.pyi create mode 100644 stubs/jsonschema/jsonschema/protocols.pyi create mode 100644 stubs/jsonschema/jsonschema/validators.pyi create mode 100644 stubs/jwcrypto/@tests/stubtest_allowlist.txt create mode 100644 stubs/jwcrypto/METADATA.toml create mode 100644 stubs/jwcrypto/jwcrypto/__init__.pyi create mode 100644 stubs/jwcrypto/jwcrypto/common.pyi create mode 100644 stubs/jwcrypto/jwcrypto/jwa.pyi create mode 100644 stubs/jwcrypto/jwcrypto/jwe.pyi create mode 100644 stubs/jwcrypto/jwcrypto/jwk.pyi create mode 100644 stubs/jwcrypto/jwcrypto/jws.pyi create mode 100644 stubs/jwcrypto/jwcrypto/jwt.pyi create mode 100644 stubs/jwcrypto/jwcrypto/version.pyi create mode 100644 stubs/kafka-python/@tests/stubtest_allowlist.txt create mode 100644 stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/kafka-python/METADATA.toml create mode 100644 stubs/kafka-python/kafka/__init__.pyi create mode 100644 stubs/kafka-python/kafka/admin/__init__.pyi create mode 100644 stubs/kafka-python/kafka/admin/acl_resource.pyi create mode 100644 stubs/kafka-python/kafka/admin/client.pyi create mode 100644 stubs/kafka-python/kafka/admin/config_resource.pyi create mode 100644 stubs/kafka-python/kafka/admin/new_partitions.pyi create mode 100644 stubs/kafka-python/kafka/admin/new_topic.pyi create mode 100644 stubs/kafka-python/kafka/cli/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/configs/describe.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/consumer_groups/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/consumer_groups/delete.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/consumer_groups/describe.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/consumer_groups/list.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/consumer_groups/list_offsets.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/log_dirs/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/log_dirs/describe.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/topics/create.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/topics/delete.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/topics/describe.pyi create mode 100644 stubs/kafka-python/kafka/cli/admin/topics/list.pyi create mode 100644 stubs/kafka-python/kafka/cli/consumer/__init__.pyi create mode 100644 stubs/kafka-python/kafka/cli/producer/__init__.pyi create mode 100644 stubs/kafka-python/kafka/client_async.pyi create mode 100644 stubs/kafka-python/kafka/cluster.pyi create mode 100644 stubs/kafka-python/kafka/codec.pyi create mode 100644 stubs/kafka-python/kafka/conn.pyi create mode 100644 stubs/kafka-python/kafka/consumer/__init__.pyi create mode 100644 stubs/kafka-python/kafka/consumer/fetcher.pyi create mode 100644 stubs/kafka-python/kafka/consumer/group.pyi create mode 100644 stubs/kafka-python/kafka/consumer/subscription_state.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/__init__.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/__init__.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/range.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/sticky/__init__.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/base.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/consumer.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/heartbeat.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/protocol.pyi create mode 100644 stubs/kafka-python/kafka/coordinator/subscription.pyi create mode 100644 stubs/kafka-python/kafka/errors.pyi create mode 100644 stubs/kafka-python/kafka/future.pyi create mode 100644 stubs/kafka-python/kafka/metrics/__init__.pyi create mode 100644 stubs/kafka-python/kafka/metrics/compound_stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/dict_reporter.pyi create mode 100644 stubs/kafka-python/kafka/metrics/kafka_metric.pyi create mode 100644 stubs/kafka-python/kafka/metrics/measurable.pyi create mode 100644 stubs/kafka-python/kafka/metrics/measurable_stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/metric_config.pyi create mode 100644 stubs/kafka-python/kafka/metrics/metric_name.pyi create mode 100644 stubs/kafka-python/kafka/metrics/metrics.pyi create mode 100644 stubs/kafka-python/kafka/metrics/metrics_reporter.pyi create mode 100644 stubs/kafka-python/kafka/metrics/quota.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/__init__.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/avg.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/count.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/histogram.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/max_stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/min_stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/percentile.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/percentiles.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/rate.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/sensor.pyi create mode 100644 stubs/kafka-python/kafka/metrics/stats/total.pyi create mode 100644 stubs/kafka-python/kafka/partitioner/__init__.pyi create mode 100644 stubs/kafka-python/kafka/partitioner/default.pyi create mode 100644 stubs/kafka-python/kafka/producer/__init__.pyi create mode 100644 stubs/kafka-python/kafka/producer/future.pyi create mode 100644 stubs/kafka-python/kafka/producer/kafka.pyi create mode 100644 stubs/kafka-python/kafka/producer/producer_batch.pyi create mode 100644 stubs/kafka-python/kafka/producer/record_accumulator.pyi create mode 100644 stubs/kafka-python/kafka/producer/sender.pyi create mode 100644 stubs/kafka-python/kafka/producer/transaction_manager.pyi create mode 100644 stubs/kafka-python/kafka/protocol/__init__.pyi create mode 100644 stubs/kafka-python/kafka/protocol/abstract.pyi create mode 100644 stubs/kafka-python/kafka/protocol/add_offsets_to_txn.pyi create mode 100644 stubs/kafka-python/kafka/protocol/add_partitions_to_txn.pyi create mode 100644 stubs/kafka-python/kafka/protocol/admin.pyi create mode 100644 stubs/kafka-python/kafka/protocol/api.pyi create mode 100644 stubs/kafka-python/kafka/protocol/api_versions.pyi create mode 100644 stubs/kafka-python/kafka/protocol/broker_api_versions.pyi create mode 100644 stubs/kafka-python/kafka/protocol/commit.pyi create mode 100644 stubs/kafka-python/kafka/protocol/end_txn.pyi create mode 100644 stubs/kafka-python/kafka/protocol/fetch.pyi create mode 100644 stubs/kafka-python/kafka/protocol/find_coordinator.pyi create mode 100644 stubs/kafka-python/kafka/protocol/frame.pyi create mode 100644 stubs/kafka-python/kafka/protocol/group.pyi create mode 100644 stubs/kafka-python/kafka/protocol/init_producer_id.pyi create mode 100644 stubs/kafka-python/kafka/protocol/list_offsets.pyi create mode 100644 stubs/kafka-python/kafka/protocol/message.pyi create mode 100644 stubs/kafka-python/kafka/protocol/metadata.pyi create mode 100644 stubs/kafka-python/kafka/protocol/offset_for_leader_epoch.pyi create mode 100644 stubs/kafka-python/kafka/protocol/parser.pyi create mode 100644 stubs/kafka-python/kafka/protocol/produce.pyi create mode 100644 stubs/kafka-python/kafka/protocol/sasl_authenticate.pyi create mode 100644 stubs/kafka-python/kafka/protocol/sasl_handshake.pyi create mode 100644 stubs/kafka-python/kafka/protocol/struct.pyi create mode 100644 stubs/kafka-python/kafka/protocol/txn_offset_commit.pyi create mode 100644 stubs/kafka-python/kafka/protocol/types.pyi create mode 100644 stubs/kafka-python/kafka/record/__init__.pyi create mode 100644 stubs/kafka-python/kafka/record/_crc32c.pyi create mode 100644 stubs/kafka-python/kafka/record/abc.pyi create mode 100644 stubs/kafka-python/kafka/record/default_records.pyi create mode 100644 stubs/kafka-python/kafka/record/legacy_records.pyi create mode 100644 stubs/kafka-python/kafka/record/memory_records.pyi create mode 100644 stubs/kafka-python/kafka/record/util.pyi create mode 100644 stubs/kafka-python/kafka/sasl/__init__.pyi create mode 100644 stubs/kafka-python/kafka/sasl/abc.pyi create mode 100644 stubs/kafka-python/kafka/sasl/gssapi.pyi create mode 100644 stubs/kafka-python/kafka/sasl/msk.pyi create mode 100644 stubs/kafka-python/kafka/sasl/oauth.pyi create mode 100644 stubs/kafka-python/kafka/sasl/plain.pyi create mode 100644 stubs/kafka-python/kafka/sasl/scram.pyi create mode 100644 stubs/kafka-python/kafka/sasl/sspi.pyi create mode 100644 stubs/kafka-python/kafka/serializer/__init__.pyi create mode 100644 stubs/kafka-python/kafka/serializer/abstract.pyi create mode 100644 stubs/kafka-python/kafka/socks5_wrapper.pyi create mode 100644 stubs/kafka-python/kafka/structs.pyi create mode 100644 stubs/kafka-python/kafka/util.pyi create mode 100644 stubs/kafka-python/kafka/version.pyi create mode 100644 stubs/keyboard/@tests/stubtest_allowlist.txt create mode 100644 stubs/keyboard/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/keyboard/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/keyboard/METADATA.toml create mode 100644 stubs/keyboard/keyboard/__init__.pyi create mode 100644 stubs/keyboard/keyboard/_canonical_names.pyi create mode 100644 stubs/keyboard/keyboard/_generic.pyi create mode 100644 stubs/keyboard/keyboard/_keyboard_event.pyi create mode 100644 stubs/keyboard/keyboard/_mouse_event.pyi create mode 100644 stubs/keyboard/keyboard/mouse.pyi create mode 100644 stubs/ldap3/@tests/stubtest_allowlist.txt create mode 100644 stubs/ldap3/METADATA.toml create mode 100644 stubs/ldap3/ldap3/__init__.pyi create mode 100644 stubs/ldap3/ldap3/abstract/__init__.pyi create mode 100644 stubs/ldap3/ldap3/abstract/attrDef.pyi create mode 100644 stubs/ldap3/ldap3/abstract/attribute.pyi create mode 100644 stubs/ldap3/ldap3/abstract/cursor.pyi create mode 100644 stubs/ldap3/ldap3/abstract/entry.pyi create mode 100644 stubs/ldap3/ldap3/abstract/objectDef.pyi create mode 100644 stubs/ldap3/ldap3/core/__init__.pyi create mode 100644 stubs/ldap3/ldap3/core/connection.pyi create mode 100644 stubs/ldap3/ldap3/core/exceptions.pyi create mode 100644 stubs/ldap3/ldap3/core/pooling.pyi create mode 100644 stubs/ldap3/ldap3/core/rdns.pyi create mode 100644 stubs/ldap3/ldap3/core/results.pyi create mode 100644 stubs/ldap3/ldap3/core/server.pyi create mode 100644 stubs/ldap3/ldap3/core/timezone.pyi create mode 100644 stubs/ldap3/ldap3/core/tls.pyi create mode 100644 stubs/ldap3/ldap3/core/usage.pyi create mode 100644 stubs/ldap3/ldap3/extend/__init__.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/__init__.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi create mode 100644 stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/__init__.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/addMembersToGroups.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/checkGroupsMemberships.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/endTransaction.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/getBindDn.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/listReplicas.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/removeMembersFromGroups.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi create mode 100644 stubs/ldap3/ldap3/extend/novell/startTransaction.pyi create mode 100644 stubs/ldap3/ldap3/extend/operation.pyi create mode 100644 stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi create mode 100644 stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi create mode 100644 stubs/ldap3/ldap3/extend/standard/__init__.pyi create mode 100644 stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi create mode 100644 stubs/ldap3/ldap3/extend/standard/whoAmI.pyi create mode 100644 stubs/ldap3/ldap3/operation/__init__.pyi create mode 100644 stubs/ldap3/ldap3/operation/abandon.pyi create mode 100644 stubs/ldap3/ldap3/operation/add.pyi create mode 100644 stubs/ldap3/ldap3/operation/bind.pyi create mode 100644 stubs/ldap3/ldap3/operation/compare.pyi create mode 100644 stubs/ldap3/ldap3/operation/delete.pyi create mode 100644 stubs/ldap3/ldap3/operation/extended.pyi create mode 100644 stubs/ldap3/ldap3/operation/modify.pyi create mode 100644 stubs/ldap3/ldap3/operation/modifyDn.pyi create mode 100644 stubs/ldap3/ldap3/operation/search.pyi create mode 100644 stubs/ldap3/ldap3/operation/unbind.pyi create mode 100644 stubs/ldap3/ldap3/protocol/__init__.pyi create mode 100644 stubs/ldap3/ldap3/protocol/controls.pyi create mode 100644 stubs/ldap3/ldap3/protocol/convert.pyi create mode 100644 stubs/ldap3/ldap3/protocol/formatters/__init__.pyi create mode 100644 stubs/ldap3/ldap3/protocol/formatters/formatters.pyi create mode 100644 stubs/ldap3/ldap3/protocol/formatters/standard.pyi create mode 100644 stubs/ldap3/ldap3/protocol/formatters/validators.pyi create mode 100644 stubs/ldap3/ldap3/protocol/microsoft.pyi create mode 100644 stubs/ldap3/ldap3/protocol/novell.pyi create mode 100644 stubs/ldap3/ldap3/protocol/oid.pyi create mode 100644 stubs/ldap3/ldap3/protocol/persistentSearch.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc2696.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc2849.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc3062.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc4511.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc4512.pyi create mode 100644 stubs/ldap3/ldap3/protocol/rfc4527.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/__init__.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/digestMd5.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/external.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/kerberos.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/plain.pyi create mode 100644 stubs/ldap3/ldap3/protocol/sasl/sasl.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/__init__.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/ad2012R2.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/ds389.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/edir888.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/edir914.pyi create mode 100644 stubs/ldap3/ldap3/protocol/schemas/slapd24.pyi create mode 100644 stubs/ldap3/ldap3/strategy/__init__.pyi create mode 100644 stubs/ldap3/ldap3/strategy/asyncStream.pyi create mode 100644 stubs/ldap3/ldap3/strategy/asynchronous.pyi create mode 100644 stubs/ldap3/ldap3/strategy/base.pyi create mode 100644 stubs/ldap3/ldap3/strategy/ldifProducer.pyi create mode 100644 stubs/ldap3/ldap3/strategy/mockAsync.pyi create mode 100644 stubs/ldap3/ldap3/strategy/mockBase.pyi create mode 100644 stubs/ldap3/ldap3/strategy/mockSync.pyi create mode 100644 stubs/ldap3/ldap3/strategy/restartable.pyi create mode 100644 stubs/ldap3/ldap3/strategy/reusable.pyi create mode 100644 stubs/ldap3/ldap3/strategy/safeRestartable.pyi create mode 100644 stubs/ldap3/ldap3/strategy/safeSync.pyi create mode 100644 stubs/ldap3/ldap3/strategy/sync.pyi create mode 100644 stubs/ldap3/ldap3/utils/__init__.pyi create mode 100644 stubs/ldap3/ldap3/utils/asn1.pyi create mode 100644 stubs/ldap3/ldap3/utils/ciDict.pyi create mode 100644 stubs/ldap3/ldap3/utils/config.pyi create mode 100644 stubs/ldap3/ldap3/utils/conv.pyi create mode 100644 stubs/ldap3/ldap3/utils/dn.pyi create mode 100644 stubs/ldap3/ldap3/utils/hashed.pyi create mode 100644 stubs/ldap3/ldap3/utils/log.pyi create mode 100644 stubs/ldap3/ldap3/utils/ntlm.pyi create mode 100644 stubs/ldap3/ldap3/utils/port_validators.pyi create mode 100644 stubs/ldap3/ldap3/utils/repr.pyi create mode 100644 stubs/ldap3/ldap3/utils/tls_backport.pyi create mode 100644 stubs/ldap3/ldap3/utils/uri.pyi create mode 100644 stubs/ldap3/ldap3/version.pyi create mode 100644 stubs/lunardate/METADATA.toml create mode 100644 stubs/lunardate/lunardate.pyi create mode 100644 stubs/lupa/METADATA.toml create mode 100644 stubs/lupa/lupa/__init__.pyi create mode 100644 stubs/lupa/lupa/lua51.pyi create mode 100644 stubs/lupa/lupa/lua52.pyi create mode 100644 stubs/lupa/lupa/lua53.pyi create mode 100644 stubs/lupa/lupa/lua54.pyi create mode 100644 stubs/lupa/lupa/luajit20.pyi create mode 100644 stubs/lupa/lupa/luajit21.pyi create mode 100644 stubs/lupa/lupa/version.pyi create mode 100644 stubs/lzstring/@tests/stubtest_allowlist.txt create mode 100644 stubs/lzstring/METADATA.toml create mode 100644 stubs/lzstring/lzstring/__init__.pyi create mode 100644 stubs/m3u8/@tests/stubtest_allowlist.txt create mode 100644 stubs/m3u8/METADATA.toml create mode 100644 stubs/m3u8/m3u8/__init__.pyi create mode 100644 stubs/m3u8/m3u8/httpclient.pyi create mode 100644 stubs/m3u8/m3u8/mixins.pyi create mode 100644 stubs/m3u8/m3u8/model.pyi create mode 100644 stubs/m3u8/m3u8/parser.pyi create mode 100644 stubs/m3u8/m3u8/protocol.pyi create mode 100644 stubs/m3u8/m3u8/version_matching.pyi create mode 100644 stubs/m3u8/m3u8/version_matching_rules.pyi create mode 100644 stubs/mock/@tests/stubtest_allowlist.txt create mode 100644 stubs/mock/METADATA.toml create mode 100644 stubs/mock/mock/__init__.pyi create mode 100644 stubs/mock/mock/backports.pyi create mode 100644 stubs/mock/mock/mock.pyi create mode 100644 stubs/mypy-extensions/@tests/stubtest_allowlist.txt create mode 100644 stubs/mypy-extensions/METADATA.toml create mode 100644 stubs/mypy-extensions/mypy_extensions.pyi create mode 100644 stubs/mysqlclient/METADATA.toml create mode 100644 stubs/mysqlclient/MySQLdb/__init__.pyi create mode 100644 stubs/mysqlclient/MySQLdb/_exceptions.pyi create mode 100644 stubs/mysqlclient/MySQLdb/_mysql.pyi create mode 100644 stubs/mysqlclient/MySQLdb/connections.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/CLIENT.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/CR.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/ER.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/FIELD_TYPE.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/FLAG.pyi create mode 100644 stubs/mysqlclient/MySQLdb/constants/__init__.pyi create mode 100644 stubs/mysqlclient/MySQLdb/converters.pyi create mode 100644 stubs/mysqlclient/MySQLdb/cursors.pyi create mode 100644 stubs/mysqlclient/MySQLdb/release.pyi create mode 100644 stubs/mysqlclient/MySQLdb/times.pyi create mode 100644 stubs/nanoid/METADATA.toml create mode 100644 stubs/nanoid/nanoid/__init__.pyi create mode 100644 stubs/nanoid/nanoid/algorithm.pyi create mode 100644 stubs/nanoid/nanoid/generate.pyi create mode 100644 stubs/nanoid/nanoid/method.pyi create mode 100644 stubs/nanoid/nanoid/non_secure_generate.pyi create mode 100644 stubs/nanoid/nanoid/resources.pyi create mode 100644 stubs/nanoleafapi/@tests/stubtest_allowlist.txt create mode 100644 stubs/nanoleafapi/METADATA.toml create mode 100644 stubs/nanoleafapi/nanoleafapi/__init__.pyi create mode 100644 stubs/nanoleafapi/nanoleafapi/digital_twin.pyi create mode 100644 stubs/nanoleafapi/nanoleafapi/discovery.pyi create mode 100644 stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi create mode 100644 stubs/netaddr/@tests/stubtest_allowlist.txt create mode 100644 stubs/netaddr/METADATA.toml create mode 100644 stubs/netaddr/netaddr/__init__.pyi create mode 100644 stubs/netaddr/netaddr/cli.pyi create mode 100644 stubs/netaddr/netaddr/compat.pyi create mode 100644 stubs/netaddr/netaddr/contrib/__init__.pyi create mode 100644 stubs/netaddr/netaddr/contrib/subnet_splitter.pyi create mode 100644 stubs/netaddr/netaddr/core.pyi create mode 100644 stubs/netaddr/netaddr/eui/__init__.pyi create mode 100644 stubs/netaddr/netaddr/eui/ieee.pyi create mode 100644 stubs/netaddr/netaddr/fbsocket.pyi create mode 100644 stubs/netaddr/netaddr/ip/__init__.pyi create mode 100644 stubs/netaddr/netaddr/ip/glob.pyi create mode 100644 stubs/netaddr/netaddr/ip/iana.pyi create mode 100644 stubs/netaddr/netaddr/ip/nmap.pyi create mode 100644 stubs/netaddr/netaddr/ip/rfc1924.pyi create mode 100644 stubs/netaddr/netaddr/ip/sets.pyi create mode 100644 stubs/netaddr/netaddr/strategy/__init__.pyi create mode 100644 stubs/netaddr/netaddr/strategy/eui48.pyi create mode 100644 stubs/netaddr/netaddr/strategy/eui64.pyi create mode 100644 stubs/netaddr/netaddr/strategy/ipv4.pyi create mode 100644 stubs/netaddr/netaddr/strategy/ipv6.pyi create mode 100644 stubs/netifaces/@tests/stubtest_allowlist.txt create mode 100644 stubs/netifaces/METADATA.toml create mode 100644 stubs/netifaces/netifaces.pyi create mode 100644 stubs/networkx/@tests/stubtest_allowlist.txt create mode 100644 stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py create mode 100644 stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py create mode 100644 stubs/networkx/METADATA.toml create mode 100644 stubs/networkx/networkx/__init__.pyi create mode 100644 stubs/networkx/networkx/_typing.pyi create mode 100644 stubs/networkx/networkx/algorithms/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/clique.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/connectivity.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/density.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/matching.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/maxcut.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/ramsey.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/steinertree.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/treewidth.pyi create mode 100644 stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/correlation.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/mixing.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi create mode 100644 stubs/networkx/networkx/algorithms/assortativity/pairs.pyi create mode 100644 stubs/networkx/networkx/algorithms/asteroidal.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/basic.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/centrality.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/cluster.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/covering.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/extendability.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/generators.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/matching.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/matrix.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/projection.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi create mode 100644 stubs/networkx/networkx/algorithms/bipartite/spectral.pyi create mode 100644 stubs/networkx/networkx/algorithms/boundary.pyi create mode 100644 stubs/networkx/networkx/algorithms/bridges.pyi create mode 100644 stubs/networkx/networkx/algorithms/broadcasting.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/betweenness.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/closeness.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/dispersion.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/group.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/harmonic.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/katz.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/laplacian.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/load.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/percolation.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/reaching.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/second_order.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/trophic.pyi create mode 100644 stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/chains.pyi create mode 100644 stubs/networkx/networkx/algorithms/chordal.pyi create mode 100644 stubs/networkx/networkx/algorithms/clique.pyi create mode 100644 stubs/networkx/networkx/algorithms/cluster.pyi create mode 100644 stubs/networkx/networkx/algorithms/coloring/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi create mode 100644 stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi create mode 100644 stubs/networkx/networkx/algorithms/communicability_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/bipartitions.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/centrality.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/community_utils.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/divisive.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/kclique.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/label_propagation.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/leiden.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/local.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/louvain.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/lukes.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/modularity_max.pyi create mode 100644 stubs/networkx/networkx/algorithms/community/quality.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/attracting.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/biconnected.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/connected.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/semiconnected.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/strongly_connected.pyi create mode 100644 stubs/networkx/networkx/algorithms/components/weakly_connected.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/cuts.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi create mode 100644 stubs/networkx/networkx/algorithms/connectivity/utils.pyi create mode 100644 stubs/networkx/networkx/algorithms/core.pyi create mode 100644 stubs/networkx/networkx/algorithms/covering.pyi create mode 100644 stubs/networkx/networkx/algorithms/cuts.pyi create mode 100644 stubs/networkx/networkx/algorithms/cycles.pyi create mode 100644 stubs/networkx/networkx/algorithms/d_separation.pyi create mode 100644 stubs/networkx/networkx/algorithms/dag.pyi create mode 100644 stubs/networkx/networkx/algorithms/distance_measures.pyi create mode 100644 stubs/networkx/networkx/algorithms/distance_regular.pyi create mode 100644 stubs/networkx/networkx/algorithms/dominance.pyi create mode 100644 stubs/networkx/networkx/algorithms/dominating.pyi create mode 100644 stubs/networkx/networkx/algorithms/efficiency_measures.pyi create mode 100644 stubs/networkx/networkx/algorithms/euler.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/maxflow.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/mincost.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/networksimplex.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/preflowpush.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi create mode 100644 stubs/networkx/networkx/algorithms/flow/utils.pyi create mode 100644 stubs/networkx/networkx/algorithms/graph_hashing.pyi create mode 100644 stubs/networkx/networkx/algorithms/graphical.pyi create mode 100644 stubs/networkx/networkx/algorithms/hierarchy.pyi create mode 100644 stubs/networkx/networkx/algorithms/hybrid.pyi create mode 100644 stubs/networkx/networkx/algorithms/isolate.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi create mode 100644 stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi create mode 100644 stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi create mode 100644 stubs/networkx/networkx/algorithms/link_prediction.pyi create mode 100644 stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi create mode 100644 stubs/networkx/networkx/algorithms/matching.pyi create mode 100644 stubs/networkx/networkx/algorithms/minors/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/minors/contraction.pyi create mode 100644 stubs/networkx/networkx/algorithms/mis.pyi create mode 100644 stubs/networkx/networkx/algorithms/moral.pyi create mode 100644 stubs/networkx/networkx/algorithms/node_classification.pyi create mode 100644 stubs/networkx/networkx/algorithms/non_randomness.pyi create mode 100644 stubs/networkx/networkx/algorithms/operators/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/operators/all.pyi create mode 100644 stubs/networkx/networkx/algorithms/operators/binary.pyi create mode 100644 stubs/networkx/networkx/algorithms/operators/product.pyi create mode 100644 stubs/networkx/networkx/algorithms/operators/unary.pyi create mode 100644 stubs/networkx/networkx/algorithms/perfect_graph.pyi create mode 100644 stubs/networkx/networkx/algorithms/planar_drawing.pyi create mode 100644 stubs/networkx/networkx/algorithms/planarity.pyi create mode 100644 stubs/networkx/networkx/algorithms/polynomials.pyi create mode 100644 stubs/networkx/networkx/algorithms/reciprocity.pyi create mode 100644 stubs/networkx/networkx/algorithms/regular.pyi create mode 100644 stubs/networkx/networkx/algorithms/richclub.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi create mode 100644 stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi create mode 100644 stubs/networkx/networkx/algorithms/similarity.pyi create mode 100644 stubs/networkx/networkx/algorithms/simple_paths.pyi create mode 100644 stubs/networkx/networkx/algorithms/smallworld.pyi create mode 100644 stubs/networkx/networkx/algorithms/smetric.pyi create mode 100644 stubs/networkx/networkx/algorithms/sparsifiers.pyi create mode 100644 stubs/networkx/networkx/algorithms/structuralholes.pyi create mode 100644 stubs/networkx/networkx/algorithms/summarization.pyi create mode 100644 stubs/networkx/networkx/algorithms/swap.pyi create mode 100644 stubs/networkx/networkx/algorithms/threshold.pyi create mode 100644 stubs/networkx/networkx/algorithms/time_dependent.pyi create mode 100644 stubs/networkx/networkx/algorithms/tournament.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi create mode 100644 stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/__init__.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/branchings.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/coding.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/decomposition.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/distance_measures.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/mst.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/operations.pyi create mode 100644 stubs/networkx/networkx/algorithms/tree/recognition.pyi create mode 100644 stubs/networkx/networkx/algorithms/triads.pyi create mode 100644 stubs/networkx/networkx/algorithms/vitality.pyi create mode 100644 stubs/networkx/networkx/algorithms/voronoi.pyi create mode 100644 stubs/networkx/networkx/algorithms/walks.pyi create mode 100644 stubs/networkx/networkx/algorithms/wiener.pyi create mode 100644 stubs/networkx/networkx/classes/__init__.pyi create mode 100644 stubs/networkx/networkx/classes/coreviews.pyi create mode 100644 stubs/networkx/networkx/classes/digraph.pyi create mode 100644 stubs/networkx/networkx/classes/filters.pyi create mode 100644 stubs/networkx/networkx/classes/function.pyi create mode 100644 stubs/networkx/networkx/classes/graph.pyi create mode 100644 stubs/networkx/networkx/classes/graphviews.pyi create mode 100644 stubs/networkx/networkx/classes/multidigraph.pyi create mode 100644 stubs/networkx/networkx/classes/multigraph.pyi create mode 100644 stubs/networkx/networkx/classes/reportviews.pyi create mode 100644 stubs/networkx/networkx/convert.pyi create mode 100644 stubs/networkx/networkx/convert_matrix.pyi create mode 100644 stubs/networkx/networkx/drawing/__init__.pyi create mode 100644 stubs/networkx/networkx/drawing/layout.pyi create mode 100644 stubs/networkx/networkx/drawing/nx_agraph.pyi create mode 100644 stubs/networkx/networkx/drawing/nx_latex.pyi create mode 100644 stubs/networkx/networkx/drawing/nx_pydot.pyi create mode 100644 stubs/networkx/networkx/drawing/nx_pylab.pyi create mode 100644 stubs/networkx/networkx/exception.pyi create mode 100644 stubs/networkx/networkx/generators/__init__.pyi create mode 100644 stubs/networkx/networkx/generators/atlas.pyi create mode 100644 stubs/networkx/networkx/generators/classic.pyi create mode 100644 stubs/networkx/networkx/generators/cographs.pyi create mode 100644 stubs/networkx/networkx/generators/community.pyi create mode 100644 stubs/networkx/networkx/generators/degree_seq.pyi create mode 100644 stubs/networkx/networkx/generators/directed.pyi create mode 100644 stubs/networkx/networkx/generators/duplication.pyi create mode 100644 stubs/networkx/networkx/generators/ego.pyi create mode 100644 stubs/networkx/networkx/generators/expanders.pyi create mode 100644 stubs/networkx/networkx/generators/geometric.pyi create mode 100644 stubs/networkx/networkx/generators/harary_graph.pyi create mode 100644 stubs/networkx/networkx/generators/internet_as_graphs.pyi create mode 100644 stubs/networkx/networkx/generators/intersection.pyi create mode 100644 stubs/networkx/networkx/generators/interval_graph.pyi create mode 100644 stubs/networkx/networkx/generators/joint_degree_seq.pyi create mode 100644 stubs/networkx/networkx/generators/lattice.pyi create mode 100644 stubs/networkx/networkx/generators/line.pyi create mode 100644 stubs/networkx/networkx/generators/mycielski.pyi create mode 100644 stubs/networkx/networkx/generators/nonisomorphic_trees.pyi create mode 100644 stubs/networkx/networkx/generators/random_clustered.pyi create mode 100644 stubs/networkx/networkx/generators/random_graphs.pyi create mode 100644 stubs/networkx/networkx/generators/small.pyi create mode 100644 stubs/networkx/networkx/generators/social.pyi create mode 100644 stubs/networkx/networkx/generators/spectral_graph_forge.pyi create mode 100644 stubs/networkx/networkx/generators/stochastic.pyi create mode 100644 stubs/networkx/networkx/generators/sudoku.pyi create mode 100644 stubs/networkx/networkx/generators/time_series.pyi create mode 100644 stubs/networkx/networkx/generators/trees.pyi create mode 100644 stubs/networkx/networkx/generators/triads.pyi create mode 100644 stubs/networkx/networkx/lazy_imports.pyi create mode 100644 stubs/networkx/networkx/linalg/__init__.pyi create mode 100644 stubs/networkx/networkx/linalg/algebraicconnectivity.pyi create mode 100644 stubs/networkx/networkx/linalg/attrmatrix.pyi create mode 100644 stubs/networkx/networkx/linalg/bethehessianmatrix.pyi create mode 100644 stubs/networkx/networkx/linalg/graphmatrix.pyi create mode 100644 stubs/networkx/networkx/linalg/laplacianmatrix.pyi create mode 100644 stubs/networkx/networkx/linalg/modularitymatrix.pyi create mode 100644 stubs/networkx/networkx/linalg/spectrum.pyi create mode 100644 stubs/networkx/networkx/readwrite/__init__.pyi create mode 100644 stubs/networkx/networkx/readwrite/adjlist.pyi create mode 100644 stubs/networkx/networkx/readwrite/edgelist.pyi create mode 100644 stubs/networkx/networkx/readwrite/gexf.pyi create mode 100644 stubs/networkx/networkx/readwrite/gml.pyi create mode 100644 stubs/networkx/networkx/readwrite/graph6.pyi create mode 100644 stubs/networkx/networkx/readwrite/graphml.pyi create mode 100644 stubs/networkx/networkx/readwrite/json_graph/__init__.pyi create mode 100644 stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi create mode 100644 stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi create mode 100644 stubs/networkx/networkx/readwrite/json_graph/node_link.pyi create mode 100644 stubs/networkx/networkx/readwrite/json_graph/tree.pyi create mode 100644 stubs/networkx/networkx/readwrite/leda.pyi create mode 100644 stubs/networkx/networkx/readwrite/multiline_adjlist.pyi create mode 100644 stubs/networkx/networkx/readwrite/p2g.pyi create mode 100644 stubs/networkx/networkx/readwrite/pajek.pyi create mode 100644 stubs/networkx/networkx/readwrite/sparse6.pyi create mode 100644 stubs/networkx/networkx/readwrite/text.pyi create mode 100644 stubs/networkx/networkx/relabel.pyi create mode 100644 stubs/networkx/networkx/utils/__init__.pyi create mode 100644 stubs/networkx/networkx/utils/backends.pyi create mode 100644 stubs/networkx/networkx/utils/configs.pyi create mode 100644 stubs/networkx/networkx/utils/decorators.pyi create mode 100644 stubs/networkx/networkx/utils/heaps.pyi create mode 100644 stubs/networkx/networkx/utils/mapped_queue.pyi create mode 100644 stubs/networkx/networkx/utils/misc.pyi create mode 100644 stubs/networkx/networkx/utils/random_sequence.pyi create mode 100644 stubs/networkx/networkx/utils/rcm.pyi create mode 100644 stubs/networkx/networkx/utils/union_find.pyi create mode 100644 stubs/oauthlib/METADATA.toml create mode 100644 stubs/oauthlib/oauthlib/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/common.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/pre_configured.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi create mode 100644 stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/endpoints/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi create mode 100644 stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi create mode 100644 stubs/oauthlib/oauthlib/signals.pyi create mode 100644 stubs/oauthlib/oauthlib/uri_validate.pyi create mode 100644 stubs/objgraph/METADATA.toml create mode 100644 stubs/objgraph/objgraph.pyi create mode 100644 stubs/olefile/@tests/stubtest_allowlist.txt create mode 100644 stubs/olefile/METADATA.toml create mode 100644 stubs/olefile/olefile/__init__.pyi create mode 100644 stubs/olefile/olefile/olefile.pyi create mode 100644 stubs/openpyxl/@tests/stubtest_allowlist.txt create mode 100644 stubs/openpyxl/@tests/test_cases/check_base_descriptors.py create mode 100644 stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py create mode 100644 stubs/openpyxl/METADATA.toml create mode 100644 stubs/openpyxl/openpyxl/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/_constants.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/_writer.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/cell.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/read_only.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/rich_text.pyi create mode 100644 stubs/openpyxl/openpyxl/cell/text.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/_3d.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/area_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/axis.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/bar_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/bubble_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/chartspace.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/data_source.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/descriptors.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/error_bar.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/label.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/layout.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/legend.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/line_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/marker.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/picture.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/pie_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/pivot.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/plotarea.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/print_settings.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/radar_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/reader.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/reference.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/scatter_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/series.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/series_factory.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/shapes.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/stock_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/surface_chart.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/text.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/title.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/trendline.pyi create mode 100644 stubs/openpyxl/openpyxl/chart/updown_bars.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/custom.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/properties.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/protection.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/publish.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/relation.pyi create mode 100644 stubs/openpyxl/openpyxl/chartsheet/views.pyi create mode 100644 stubs/openpyxl/openpyxl/comments/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/comments/author.pyi create mode 100644 stubs/openpyxl/openpyxl/comments/comment_sheet.pyi create mode 100644 stubs/openpyxl/openpyxl/comments/comments.pyi create mode 100644 stubs/openpyxl/openpyxl/comments/shape_writer.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/abc.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/numbers.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/product.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/singleton.pyi create mode 100644 stubs/openpyxl/openpyxl/compat/strings.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/base.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/container.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/excel.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/namespace.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/nested.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/sequence.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/serialisable.pyi create mode 100644 stubs/openpyxl/openpyxl/descriptors/slots.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/colors.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/connector.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/drawing.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/effect.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/fill.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/geometry.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/graphic.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/image.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/line.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/picture.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/properties.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/relation.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/text.pyi create mode 100644 stubs/openpyxl/openpyxl/drawing/xdr.pyi create mode 100644 stubs/openpyxl/openpyxl/formatting/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/formatting/formatting.pyi create mode 100644 stubs/openpyxl/openpyxl/formatting/rule.pyi create mode 100644 stubs/openpyxl/openpyxl/formula/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/formula/tokenizer.pyi create mode 100644 stubs/openpyxl/openpyxl/formula/translate.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/core.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/custom.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/extended.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/interface.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/manifest.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/relationship.pyi create mode 100644 stubs/openpyxl/openpyxl/packaging/workbook.pyi create mode 100644 stubs/openpyxl/openpyxl/pivot/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/pivot/cache.pyi create mode 100644 stubs/openpyxl/openpyxl/pivot/fields.pyi create mode 100644 stubs/openpyxl/openpyxl/pivot/record.pyi create mode 100644 stubs/openpyxl/openpyxl/pivot/table.pyi create mode 100644 stubs/openpyxl/openpyxl/reader/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/reader/drawings.pyi create mode 100644 stubs/openpyxl/openpyxl/reader/excel.pyi create mode 100644 stubs/openpyxl/openpyxl/reader/strings.pyi create mode 100644 stubs/openpyxl/openpyxl/reader/workbook.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/alignment.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/borders.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/builtins.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/cell_style.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/colors.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/differential.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/fills.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/fonts.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/named_styles.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/numbers.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/protection.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/proxy.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/styleable.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/stylesheet.pyi create mode 100644 stubs/openpyxl/openpyxl/styles/table.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/cell.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/dataframe.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/datetime.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/escape.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/exceptions.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/formulas.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/indexed_list.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/inference.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/protection.pyi create mode 100644 stubs/openpyxl/openpyxl/utils/units.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/_writer.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/child.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/defined_name.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/external_link/external.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/external_reference.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/function_group.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/properties.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/protection.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/smart_tags.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/views.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/web.pyi create mode 100644 stubs/openpyxl/openpyxl/workbook/workbook.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/_read_only.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/_reader.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/_write_only.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/_writer.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/cell_range.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/controls.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/copier.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/custom.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/dimensions.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/drawing.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/errors.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/filters.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/formula.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/header_footer.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/merge.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/ole.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/page.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/picture.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/print_settings.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/properties.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/protection.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/related.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/scenario.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/table.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/views.pyi create mode 100644 stubs/openpyxl/openpyxl/worksheet/worksheet.pyi create mode 100644 stubs/openpyxl/openpyxl/writer/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/writer/excel.pyi create mode 100644 stubs/openpyxl/openpyxl/writer/theme.pyi create mode 100644 stubs/openpyxl/openpyxl/xml/__init__.pyi create mode 100644 stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi create mode 100644 stubs/openpyxl/openpyxl/xml/constants.pyi create mode 100644 stubs/openpyxl/openpyxl/xml/functions.pyi create mode 100644 stubs/opentracing/@tests/stubtest_allowlist.txt create mode 100644 stubs/opentracing/METADATA.toml create mode 100644 stubs/opentracing/opentracing/__init__.pyi create mode 100644 stubs/opentracing/opentracing/ext/__init__.pyi create mode 100644 stubs/opentracing/opentracing/ext/tags.pyi create mode 100644 stubs/opentracing/opentracing/harness/__init__.pyi create mode 100644 stubs/opentracing/opentracing/harness/api_check.pyi create mode 100644 stubs/opentracing/opentracing/harness/scope_check.pyi create mode 100644 stubs/opentracing/opentracing/logs.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/__init__.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/binary_propagator.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/context.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/propagator.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/span.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/text_propagator.pyi create mode 100644 stubs/opentracing/opentracing/mocktracer/tracer.pyi create mode 100644 stubs/opentracing/opentracing/propagation.pyi create mode 100644 stubs/opentracing/opentracing/scope.pyi create mode 100644 stubs/opentracing/opentracing/scope_manager.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/__init__.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/asyncio.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/constants.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/contextvars.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/gevent.pyi create mode 100644 stubs/opentracing/opentracing/scope_managers/tornado.pyi create mode 100644 stubs/opentracing/opentracing/span.pyi create mode 100644 stubs/opentracing/opentracing/tags.pyi create mode 100644 stubs/opentracing/opentracing/tracer.pyi create mode 100644 stubs/paramiko/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/paramiko/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/paramiko/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/paramiko/METADATA.toml create mode 100644 stubs/paramiko/paramiko/__init__.pyi create mode 100644 stubs/paramiko/paramiko/_winapi.pyi create mode 100644 stubs/paramiko/paramiko/agent.pyi create mode 100644 stubs/paramiko/paramiko/auth_handler.pyi create mode 100644 stubs/paramiko/paramiko/auth_strategy.pyi create mode 100644 stubs/paramiko/paramiko/ber.pyi create mode 100644 stubs/paramiko/paramiko/buffered_pipe.pyi create mode 100644 stubs/paramiko/paramiko/channel.pyi create mode 100644 stubs/paramiko/paramiko/client.pyi create mode 100644 stubs/paramiko/paramiko/common.pyi create mode 100644 stubs/paramiko/paramiko/compress.pyi create mode 100644 stubs/paramiko/paramiko/config.pyi create mode 100644 stubs/paramiko/paramiko/ecdsakey.pyi create mode 100644 stubs/paramiko/paramiko/ed25519key.pyi create mode 100644 stubs/paramiko/paramiko/file.pyi create mode 100644 stubs/paramiko/paramiko/hostkeys.pyi create mode 100644 stubs/paramiko/paramiko/kex_curve25519.pyi create mode 100644 stubs/paramiko/paramiko/kex_ecdh_nist.pyi create mode 100644 stubs/paramiko/paramiko/kex_gex.pyi create mode 100644 stubs/paramiko/paramiko/kex_group14.pyi create mode 100644 stubs/paramiko/paramiko/kex_group16.pyi create mode 100644 stubs/paramiko/paramiko/message.pyi create mode 100644 stubs/paramiko/paramiko/packet.pyi create mode 100644 stubs/paramiko/paramiko/pipe.pyi create mode 100644 stubs/paramiko/paramiko/pkey.pyi create mode 100644 stubs/paramiko/paramiko/primes.pyi create mode 100644 stubs/paramiko/paramiko/proxy.pyi create mode 100644 stubs/paramiko/paramiko/rsakey.pyi create mode 100644 stubs/paramiko/paramiko/server.pyi create mode 100644 stubs/paramiko/paramiko/sftp.pyi create mode 100644 stubs/paramiko/paramiko/sftp_attr.pyi create mode 100644 stubs/paramiko/paramiko/sftp_client.pyi create mode 100644 stubs/paramiko/paramiko/sftp_file.pyi create mode 100644 stubs/paramiko/paramiko/sftp_handle.pyi create mode 100644 stubs/paramiko/paramiko/sftp_server.pyi create mode 100644 stubs/paramiko/paramiko/sftp_si.pyi create mode 100644 stubs/paramiko/paramiko/ssh_exception.pyi create mode 100644 stubs/paramiko/paramiko/transport.pyi create mode 100644 stubs/paramiko/paramiko/util.pyi create mode 100644 stubs/paramiko/paramiko/win_openssh.pyi create mode 100644 stubs/paramiko/paramiko/win_pageant.pyi create mode 100644 stubs/parsimonious/@tests/stubtest_allowlist.txt create mode 100644 stubs/parsimonious/METADATA.toml create mode 100644 stubs/parsimonious/parsimonious/__init__.pyi create mode 100644 stubs/parsimonious/parsimonious/exceptions.pyi create mode 100644 stubs/parsimonious/parsimonious/expressions.pyi create mode 100644 stubs/parsimonious/parsimonious/grammar.pyi create mode 100644 stubs/parsimonious/parsimonious/nodes.pyi create mode 100644 stubs/parsimonious/parsimonious/utils.pyi create mode 100644 stubs/passpy/@tests/stubtest_allowlist.txt create mode 100644 stubs/passpy/METADATA.toml create mode 100644 stubs/passpy/passpy/__init__.pyi create mode 100644 stubs/passpy/passpy/exceptions.pyi create mode 100644 stubs/passpy/passpy/store.pyi create mode 100644 stubs/passpy/passpy/util.pyi create mode 100644 stubs/peewee/@tests/stubtest_allowlist.txt create mode 100644 stubs/peewee/@tests/test_cases/check_fields.py create mode 100644 stubs/peewee/METADATA.toml create mode 100644 stubs/peewee/peewee.pyi create mode 100644 stubs/peewee/playhouse/__init__.pyi create mode 100644 stubs/peewee/playhouse/flask_utils.pyi create mode 100644 stubs/pep8-naming/METADATA.toml create mode 100644 stubs/pep8-naming/pep8ext_naming.pyi create mode 100644 stubs/pexpect/@tests/stubtest_allowlist.txt create mode 100644 stubs/pexpect/METADATA.toml create mode 100644 stubs/pexpect/pexpect/ANSI.pyi create mode 100644 stubs/pexpect/pexpect/FSM.pyi create mode 100644 stubs/pexpect/pexpect/__init__.pyi create mode 100644 stubs/pexpect/pexpect/_async.pyi create mode 100644 stubs/pexpect/pexpect/exceptions.pyi create mode 100644 stubs/pexpect/pexpect/expect.pyi create mode 100644 stubs/pexpect/pexpect/fdpexpect.pyi create mode 100644 stubs/pexpect/pexpect/popen_spawn.pyi create mode 100644 stubs/pexpect/pexpect/pty_spawn.pyi create mode 100644 stubs/pexpect/pexpect/pxssh.pyi create mode 100644 stubs/pexpect/pexpect/replwrap.pyi create mode 100644 stubs/pexpect/pexpect/run.pyi create mode 100644 stubs/pexpect/pexpect/screen.pyi create mode 100644 stubs/pexpect/pexpect/socket_pexpect.pyi create mode 100644 stubs/pexpect/pexpect/spawnbase.pyi create mode 100644 stubs/pexpect/pexpect/utils.pyi create mode 100644 stubs/pika/@tests/stubtest_allowlist.txt create mode 100644 stubs/pika/METADATA.toml create mode 100644 stubs/pika/pika/__init__.pyi create mode 100644 stubs/pika/pika/adapters/__init__.pyi create mode 100644 stubs/pika/pika/adapters/asyncio_connection.pyi create mode 100644 stubs/pika/pika/adapters/base_connection.pyi create mode 100644 stubs/pika/pika/adapters/blocking_connection.pyi create mode 100644 stubs/pika/pika/adapters/gevent_connection.pyi create mode 100644 stubs/pika/pika/adapters/select_connection.pyi create mode 100644 stubs/pika/pika/adapters/tornado_connection.pyi create mode 100644 stubs/pika/pika/adapters/twisted_connection.pyi create mode 100644 stubs/pika/pika/adapters/utils/__init__.pyi create mode 100644 stubs/pika/pika/adapters/utils/connection_workflow.pyi create mode 100644 stubs/pika/pika/adapters/utils/io_services_utils.pyi create mode 100644 stubs/pika/pika/adapters/utils/nbio_interface.pyi create mode 100644 stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi create mode 100644 stubs/pika/pika/amqp_object.pyi create mode 100644 stubs/pika/pika/callback.pyi create mode 100644 stubs/pika/pika/channel.pyi create mode 100644 stubs/pika/pika/compat.pyi create mode 100644 stubs/pika/pika/connection.pyi create mode 100644 stubs/pika/pika/credentials.pyi create mode 100644 stubs/pika/pika/data.pyi create mode 100644 stubs/pika/pika/delivery_mode.pyi create mode 100644 stubs/pika/pika/diagnostic_utils.pyi create mode 100644 stubs/pika/pika/exceptions.pyi create mode 100644 stubs/pika/pika/exchange_type.pyi create mode 100644 stubs/pika/pika/frame.pyi create mode 100644 stubs/pika/pika/heartbeat.pyi create mode 100644 stubs/pika/pika/spec.pyi create mode 100644 stubs/pika/pika/tcp_socket_opts.pyi create mode 100644 stubs/pika/pika/validators.pyi create mode 100644 stubs/polib/METADATA.toml create mode 100644 stubs/polib/polib.pyi create mode 100644 stubs/pony/@tests/stubtest_allowlist.txt create mode 100644 stubs/pony/METADATA.toml create mode 100644 stubs/pony/pony/__init__.pyi create mode 100644 stubs/pony/pony/converting.pyi create mode 100644 stubs/pony/pony/flask/__init__.pyi create mode 100644 stubs/pony/pony/flask/example/__init__.pyi create mode 100644 stubs/pony/pony/flask/example/app.pyi create mode 100644 stubs/pony/pony/flask/example/config.pyi create mode 100644 stubs/pony/pony/flask/example/models.pyi create mode 100644 stubs/pony/pony/flask/example/views.pyi create mode 100644 stubs/pony/pony/options.pyi create mode 100644 stubs/pony/pony/orm/__init__.pyi create mode 100644 stubs/pony/pony/orm/asttranslation.pyi create mode 100644 stubs/pony/pony/orm/core.pyi create mode 100644 stubs/pony/pony/orm/dbapiprovider.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/__init__.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/cockroach.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/mysql.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/oracle.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/postgres.pyi create mode 100644 stubs/pony/pony/orm/dbproviders/sqlite.pyi create mode 100644 stubs/pony/pony/orm/dbschema.pyi create mode 100644 stubs/pony/pony/orm/decompiling.pyi create mode 100644 stubs/pony/pony/orm/examples/__init__.pyi create mode 100644 stubs/pony/pony/orm/examples/alessandro_bug.pyi create mode 100644 stubs/pony/pony/orm/examples/bottle_example.pyi create mode 100644 stubs/pony/pony/orm/examples/bug_ben.pyi create mode 100644 stubs/pony/pony/orm/examples/compositekeys.pyi create mode 100644 stubs/pony/pony/orm/examples/demo.pyi create mode 100644 stubs/pony/pony/orm/examples/estore.pyi create mode 100644 stubs/pony/pony/orm/examples/inheritance1.pyi create mode 100644 stubs/pony/pony/orm/examples/numbers.pyi create mode 100644 stubs/pony/pony/orm/examples/session01.pyi create mode 100644 stubs/pony/pony/orm/examples/university1.pyi create mode 100644 stubs/pony/pony/orm/examples/university2.pyi create mode 100644 stubs/pony/pony/orm/integration/__init__.pyi create mode 100644 stubs/pony/pony/orm/integration/bottle_plugin.pyi create mode 100644 stubs/pony/pony/orm/ormtypes.pyi create mode 100644 stubs/pony/pony/orm/serialization.pyi create mode 100644 stubs/pony/pony/orm/sqlbuilding.pyi create mode 100644 stubs/pony/pony/orm/sqlsymbols.pyi create mode 100644 stubs/pony/pony/orm/sqltranslation.pyi create mode 100644 stubs/pony/pony/py23compat.pyi create mode 100644 stubs/pony/pony/thirdparty/__init__.pyi create mode 100644 stubs/pony/pony/thirdparty/decorator.pyi create mode 100644 stubs/pony/pony/utils/__init__.pyi create mode 100644 stubs/pony/pony/utils/properties.pyi create mode 100644 stubs/pony/pony/utils/utils.pyi create mode 100644 stubs/portpicker/METADATA.toml create mode 100644 stubs/portpicker/portpicker.pyi create mode 100644 stubs/protobuf/@tests/stubtest_allowlist.txt create mode 100644 stubs/protobuf/@tests/test_cases/check_struct.py create mode 100644 stubs/protobuf/METADATA.toml create mode 100644 stubs/protobuf/google/_upb/_message.pyi create mode 100644 stubs/protobuf/google/protobuf/__init__.pyi create mode 100644 stubs/protobuf/google/protobuf/any.pyi create mode 100644 stubs/protobuf/google/protobuf/any_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/api_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/compiler/__init__.pyi create mode 100644 stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/descriptor.pyi create mode 100644 stubs/protobuf/google/protobuf/descriptor_database.pyi create mode 100644 stubs/protobuf/google/protobuf/descriptor_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/descriptor_pool.pyi create mode 100644 stubs/protobuf/google/protobuf/duration.pyi create mode 100644 stubs/protobuf/google/protobuf/duration_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/empty_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/field_mask_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/__init__.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/api_implementation.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/builder.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/containers.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/decoder.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/encoder.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/extension_dict.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/field_mask.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/message_listener.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/python_edition_defaults.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/python_message.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/type_checkers.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/well_known_types.pyi create mode 100644 stubs/protobuf/google/protobuf/internal/wire_format.pyi create mode 100644 stubs/protobuf/google/protobuf/json_format.pyi create mode 100644 stubs/protobuf/google/protobuf/message.pyi create mode 100644 stubs/protobuf/google/protobuf/message_factory.pyi create mode 100644 stubs/protobuf/google/protobuf/proto.pyi create mode 100644 stubs/protobuf/google/protobuf/proto_builder.pyi create mode 100644 stubs/protobuf/google/protobuf/proto_json.pyi create mode 100644 stubs/protobuf/google/protobuf/proto_text.pyi create mode 100644 stubs/protobuf/google/protobuf/reflection.pyi create mode 100644 stubs/protobuf/google/protobuf/runtime_version.pyi create mode 100644 stubs/protobuf/google/protobuf/service_reflection.pyi create mode 100644 stubs/protobuf/google/protobuf/source_context_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/struct_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/symbol_database.pyi create mode 100644 stubs/protobuf/google/protobuf/text_encoding.pyi create mode 100644 stubs/protobuf/google/protobuf/text_format.pyi create mode 100644 stubs/protobuf/google/protobuf/timestamp.pyi create mode 100644 stubs/protobuf/google/protobuf/timestamp_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/type_pb2.pyi create mode 100644 stubs/protobuf/google/protobuf/unknown_fields.pyi create mode 100644 stubs/protobuf/google/protobuf/util/__init__.pyi create mode 100644 stubs/protobuf/google/protobuf/wrappers_pb2.pyi create mode 100644 stubs/psutil/@tests/stubtest_allowlist.txt create mode 100644 stubs/psutil/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/psutil/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/psutil/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/psutil/@tests/test_cases/check_process_iter.py create mode 100644 stubs/psutil/METADATA.toml create mode 100644 stubs/psutil/psutil/__init__.pyi create mode 100644 stubs/psutil/psutil/_common.pyi create mode 100644 stubs/psutil/psutil/_ntuples.pyi create mode 100644 stubs/psutil/psutil/_psaix.pyi create mode 100644 stubs/psutil/psutil/_psbsd.pyi create mode 100644 stubs/psutil/psutil/_pslinux.pyi create mode 100644 stubs/psutil/psutil/_psosx.pyi create mode 100644 stubs/psutil/psutil/_psposix.pyi create mode 100644 stubs/psutil/psutil/_pssunos.pyi create mode 100644 stubs/psutil/psutil/_psutil_aix.pyi create mode 100644 stubs/psutil/psutil/_psutil_bsd.pyi create mode 100644 stubs/psutil/psutil/_psutil_linux.pyi create mode 100644 stubs/psutil/psutil/_psutil_osx.pyi create mode 100644 stubs/psutil/psutil/_psutil_sunos.pyi create mode 100644 stubs/psutil/psutil/_psutil_windows.pyi create mode 100644 stubs/psutil/psutil/_pswindows.pyi create mode 100644 stubs/psycopg2/@tests/stubtest_allowlist.txt create mode 100644 stubs/psycopg2/@tests/test_cases/check_connect.py create mode 100644 stubs/psycopg2/@tests/test_cases/check_extensions.py create mode 100644 stubs/psycopg2/METADATA.toml create mode 100644 stubs/psycopg2/psycopg2/__init__.pyi create mode 100644 stubs/psycopg2/psycopg2/_ipaddress.pyi create mode 100644 stubs/psycopg2/psycopg2/_json.pyi create mode 100644 stubs/psycopg2/psycopg2/_psycopg.pyi create mode 100644 stubs/psycopg2/psycopg2/_range.pyi create mode 100644 stubs/psycopg2/psycopg2/errorcodes.pyi create mode 100644 stubs/psycopg2/psycopg2/errors.pyi create mode 100644 stubs/psycopg2/psycopg2/extensions.pyi create mode 100644 stubs/psycopg2/psycopg2/extras.pyi create mode 100644 stubs/psycopg2/psycopg2/pool.pyi create mode 100644 stubs/psycopg2/psycopg2/sql.pyi create mode 100644 stubs/psycopg2/psycopg2/tz.pyi create mode 100644 stubs/punq/@tests/stubtest_allowlist.txt create mode 100644 stubs/punq/METADATA.toml create mode 100644 stubs/punq/punq/__init__.pyi create mode 100644 stubs/pyasn1/METADATA.toml create mode 100644 stubs/pyasn1/pyasn1/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/ber/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/ber/decoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/ber/encoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/ber/eoo.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/cer/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/cer/decoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/cer/encoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/der/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/der/decoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/der/encoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/native/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/native/decoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/native/encoder.pyi create mode 100644 stubs/pyasn1/pyasn1/codec/streaming.pyi create mode 100644 stubs/pyasn1/pyasn1/compat/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/compat/integer.pyi create mode 100644 stubs/pyasn1/pyasn1/debug.pyi create mode 100644 stubs/pyasn1/pyasn1/error.pyi create mode 100644 stubs/pyasn1/pyasn1/type/__init__.pyi create mode 100644 stubs/pyasn1/pyasn1/type/base.pyi create mode 100644 stubs/pyasn1/pyasn1/type/char.pyi create mode 100644 stubs/pyasn1/pyasn1/type/constraint.pyi create mode 100644 stubs/pyasn1/pyasn1/type/error.pyi create mode 100644 stubs/pyasn1/pyasn1/type/namedtype.pyi create mode 100644 stubs/pyasn1/pyasn1/type/namedval.pyi create mode 100644 stubs/pyasn1/pyasn1/type/opentype.pyi create mode 100644 stubs/pyasn1/pyasn1/type/tag.pyi create mode 100644 stubs/pyasn1/pyasn1/type/tagmap.pyi create mode 100644 stubs/pyasn1/pyasn1/type/univ.pyi create mode 100644 stubs/pyasn1/pyasn1/type/useful.pyi create mode 100644 stubs/pyaudio/METADATA.toml create mode 100644 stubs/pyaudio/pyaudio.pyi create mode 100644 stubs/pycocotools/METADATA.toml create mode 100644 stubs/pycocotools/pycocotools/__init__.pyi create mode 100644 stubs/pycocotools/pycocotools/coco.pyi create mode 100644 stubs/pycocotools/pycocotools/cocoeval.pyi create mode 100644 stubs/pycocotools/pycocotools/mask.pyi create mode 100644 stubs/pycups/METADATA.toml create mode 100644 stubs/pycups/cups.pyi create mode 100644 stubs/pycurl/@tests/stubtest_allowlist.txt create mode 100644 stubs/pycurl/METADATA.toml create mode 100644 stubs/pycurl/pycurl/__init__.pyi create mode 100644 stubs/pycurl/pycurl/_pycurl.pyi create mode 100644 stubs/pycurl/pycurl/async_multi.pyi create mode 100644 stubs/pyfarmhash/METADATA.toml create mode 100644 stubs/pyfarmhash/farmhash.pyi create mode 100644 stubs/pyflakes/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyflakes/METADATA.toml create mode 100644 stubs/pyflakes/pyflakes/__init__.pyi create mode 100644 stubs/pyflakes/pyflakes/__main__.pyi create mode 100644 stubs/pyflakes/pyflakes/api.pyi create mode 100644 stubs/pyflakes/pyflakes/checker.pyi create mode 100644 stubs/pyflakes/pyflakes/messages.pyi create mode 100644 stubs/pyflakes/pyflakes/reporter.pyi create mode 100644 stubs/pyflakes/pyflakes/scripts/__init__.pyi create mode 100644 stubs/pyflakes/pyflakes/scripts/pyflakes.pyi create mode 100644 stubs/pyinstaller/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/pyinstaller/@tests/test_cases/check_versioninfo.py create mode 100644 stubs/pyinstaller/METADATA.toml create mode 100644 stubs/pyinstaller/PyInstaller/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/__main__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/building/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/building/api.pyi create mode 100644 stubs/pyinstaller/PyInstaller/building/build_main.pyi create mode 100644 stubs/pyinstaller/PyInstaller/building/datastruct.pyi create mode 100644 stubs/pyinstaller/PyInstaller/building/splash.pyi create mode 100644 stubs/pyinstaller/PyInstaller/compat.pyi create mode 100644 stubs/pyinstaller/PyInstaller/depend/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/depend/analysis.pyi create mode 100644 stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi create mode 100644 stubs/pyinstaller/PyInstaller/isolated/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/isolated/_parent.pyi create mode 100644 stubs/pyinstaller/PyInstaller/lib/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/lib/modulegraph/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi create mode 100644 stubs/pyinstaller/PyInstaller/utils/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi create mode 100644 stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi create mode 100644 stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi create mode 100644 stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi create mode 100644 stubs/pyinstaller/pyi_splash/__init__.pyi create mode 100644 stubs/pyjks/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyjks/METADATA.toml create mode 100644 stubs/pyjks/jks/__init__.pyi create mode 100644 stubs/pyjks/jks/bks.pyi create mode 100644 stubs/pyjks/jks/jks.pyi create mode 100644 stubs/pyjks/jks/rfc2898.pyi create mode 100644 stubs/pyjks/jks/rfc7292.pyi create mode 100644 stubs/pyjks/jks/sun_crypto.pyi create mode 100644 stubs/pyjks/jks/util.pyi create mode 100644 stubs/pyluach/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyluach/METADATA.toml create mode 100644 stubs/pyluach/pyluach/__init__.pyi create mode 100644 stubs/pyluach/pyluach/dates.pyi create mode 100644 stubs/pyluach/pyluach/hebrewcal.pyi create mode 100644 stubs/pyluach/pyluach/parshios.pyi create mode 100644 stubs/pyluach/pyluach/utils.pyi create mode 100644 stubs/pynput/@tests/stubtest_allowlist.txt create mode 100644 stubs/pynput/METADATA.toml create mode 100644 stubs/pynput/pynput/__init__.pyi create mode 100644 stubs/pynput/pynput/_info.pyi create mode 100644 stubs/pynput/pynput/_util.pyi create mode 100644 stubs/pynput/pynput/keyboard/__init__.pyi create mode 100644 stubs/pynput/pynput/keyboard/_base.pyi create mode 100644 stubs/pynput/pynput/keyboard/_dummy.pyi create mode 100644 stubs/pynput/pynput/mouse/__init__.pyi create mode 100644 stubs/pynput/pynput/mouse/_base.pyi create mode 100644 stubs/pynput/pynput/mouse/_dummy.pyi create mode 100644 stubs/pyogrio/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyogrio/METADATA.toml create mode 100644 stubs/pyogrio/pyogrio/__init__.pyi create mode 100644 stubs/pyogrio/pyogrio/_typing.pyi create mode 100644 stubs/pyogrio/pyogrio/core.pyi create mode 100644 stubs/pyogrio/pyogrio/errors.pyi create mode 100644 stubs/pyogrio/pyogrio/geopandas.pyi create mode 100644 stubs/pyogrio/pyogrio/raw.pyi create mode 100644 stubs/pyogrio/pyogrio/util.pyi create mode 100644 stubs/pyperclip/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyperclip/METADATA.toml create mode 100644 stubs/pyperclip/pyperclip/__init__.pyi create mode 100644 stubs/pyphen/METADATA.toml create mode 100644 stubs/pyphen/pyphen/__init__.pyi create mode 100644 stubs/pyserial/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyserial/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/pyserial/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/pyserial/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/pyserial/METADATA.toml create mode 100644 stubs/pyserial/serial/__init__.pyi create mode 100644 stubs/pyserial/serial/__main__.pyi create mode 100644 stubs/pyserial/serial/rfc2217.pyi create mode 100644 stubs/pyserial/serial/rs485.pyi create mode 100644 stubs/pyserial/serial/serialcli.pyi create mode 100644 stubs/pyserial/serial/serialjava.pyi create mode 100644 stubs/pyserial/serial/serialposix.pyi create mode 100644 stubs/pyserial/serial/serialutil.pyi create mode 100644 stubs/pyserial/serial/serialwin32.pyi create mode 100644 stubs/pyserial/serial/threaded/__init__.pyi create mode 100644 stubs/pyserial/serial/tools/__init__.pyi create mode 100644 stubs/pyserial/serial/tools/hexlify_codec.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports_common.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports_linux.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports_osx.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports_posix.pyi create mode 100644 stubs/pyserial/serial/tools/list_ports_windows.pyi create mode 100644 stubs/pyserial/serial/tools/miniterm.pyi create mode 100644 stubs/pyserial/serial/urlhandler/__init__.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_alt.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_loop.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_socket.pyi create mode 100644 stubs/pyserial/serial/urlhandler/protocol_spy.pyi create mode 100644 stubs/pyserial/serial/win32.pyi create mode 100644 stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt create mode 100644 stubs/pytest-lazy-fixture/METADATA.toml create mode 100644 stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi create mode 100644 stubs/python-crontab/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-crontab/METADATA.toml create mode 100644 stubs/python-crontab/cronlog.pyi create mode 100644 stubs/python-crontab/crontab.pyi create mode 100644 stubs/python-crontab/crontabs.pyi create mode 100644 stubs/python-dateutil/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt create mode 100644 stubs/python-dateutil/@tests/test_cases/check_inheritance.py create mode 100644 stubs/python-dateutil/@tests/test_cases/check_relativedelta.py create mode 100644 stubs/python-dateutil/@tests/test_cases/check_rrule.py create mode 100644 stubs/python-dateutil/METADATA.toml create mode 100644 stubs/python-dateutil/dateutil/__init__.pyi create mode 100644 stubs/python-dateutil/dateutil/_common.pyi create mode 100644 stubs/python-dateutil/dateutil/_version.pyi create mode 100644 stubs/python-dateutil/dateutil/easter.pyi create mode 100644 stubs/python-dateutil/dateutil/parser/__init__.pyi create mode 100644 stubs/python-dateutil/dateutil/parser/_parser.pyi create mode 100644 stubs/python-dateutil/dateutil/parser/isoparser.pyi create mode 100644 stubs/python-dateutil/dateutil/relativedelta.pyi create mode 100644 stubs/python-dateutil/dateutil/rrule.pyi create mode 100644 stubs/python-dateutil/dateutil/tz/__init__.pyi create mode 100644 stubs/python-dateutil/dateutil/tz/_common.pyi create mode 100644 stubs/python-dateutil/dateutil/tz/tz.pyi create mode 100644 stubs/python-dateutil/dateutil/tz/win.pyi create mode 100644 stubs/python-dateutil/dateutil/tzwin.pyi create mode 100644 stubs/python-dateutil/dateutil/utils.pyi create mode 100644 stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi create mode 100644 stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi create mode 100644 stubs/python-http-client/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-http-client/METADATA.toml create mode 100644 stubs/python-http-client/python_http_client/__init__.pyi create mode 100644 stubs/python-http-client/python_http_client/client.pyi create mode 100644 stubs/python-http-client/python_http_client/exceptions.pyi create mode 100644 stubs/python-jenkins/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-jenkins/METADATA.toml create mode 100644 stubs/python-jenkins/jenkins/__init__.pyi create mode 100644 stubs/python-jenkins/jenkins/plugins.pyi create mode 100644 stubs/python-jenkins/jenkins/version.pyi create mode 100644 stubs/python-jose/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-jose/METADATA.toml create mode 100644 stubs/python-jose/jose/__init__.pyi create mode 100644 stubs/python-jose/jose/backends/__init__.pyi create mode 100644 stubs/python-jose/jose/backends/_asn1.pyi create mode 100644 stubs/python-jose/jose/backends/base.pyi create mode 100644 stubs/python-jose/jose/backends/cryptography_backend.pyi create mode 100644 stubs/python-jose/jose/backends/ecdsa_backend.pyi create mode 100644 stubs/python-jose/jose/backends/native.pyi create mode 100644 stubs/python-jose/jose/backends/rsa_backend.pyi create mode 100644 stubs/python-jose/jose/constants.pyi create mode 100644 stubs/python-jose/jose/exceptions.pyi create mode 100644 stubs/python-jose/jose/jwe.pyi create mode 100644 stubs/python-jose/jose/jwk.pyi create mode 100644 stubs/python-jose/jose/jws.pyi create mode 100644 stubs/python-jose/jose/jwt.pyi create mode 100644 stubs/python-jose/jose/utils.pyi create mode 100644 stubs/python-nmap/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-nmap/METADATA.toml create mode 100644 stubs/python-nmap/nmap/__init__.pyi create mode 100644 stubs/python-nmap/nmap/nmap.pyi create mode 100644 stubs/python-xlib/@tests/stubtest_allowlist.txt create mode 100644 stubs/python-xlib/METADATA.toml create mode 100644 stubs/python-xlib/Xlib/X.pyi create mode 100644 stubs/python-xlib/Xlib/XK.pyi create mode 100644 stubs/python-xlib/Xlib/Xatom.pyi create mode 100644 stubs/python-xlib/Xlib/Xcursorfont.pyi create mode 100644 stubs/python-xlib/Xlib/Xutil.pyi create mode 100644 stubs/python-xlib/Xlib/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/_typing.pyi create mode 100644 stubs/python-xlib/Xlib/display.pyi create mode 100644 stubs/python-xlib/Xlib/error.pyi create mode 100644 stubs/python-xlib/Xlib/ext/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/ext/composite.pyi create mode 100644 stubs/python-xlib/Xlib/ext/damage.pyi create mode 100644 stubs/python-xlib/Xlib/ext/dpms.pyi create mode 100644 stubs/python-xlib/Xlib/ext/ge.pyi create mode 100644 stubs/python-xlib/Xlib/ext/nvcontrol.pyi create mode 100644 stubs/python-xlib/Xlib/ext/randr.pyi create mode 100644 stubs/python-xlib/Xlib/ext/record.pyi create mode 100644 stubs/python-xlib/Xlib/ext/res.pyi create mode 100644 stubs/python-xlib/Xlib/ext/screensaver.pyi create mode 100644 stubs/python-xlib/Xlib/ext/security.pyi create mode 100644 stubs/python-xlib/Xlib/ext/shape.pyi create mode 100644 stubs/python-xlib/Xlib/ext/xfixes.pyi create mode 100644 stubs/python-xlib/Xlib/ext/xinerama.pyi create mode 100644 stubs/python-xlib/Xlib/ext/xinput.pyi create mode 100644 stubs/python-xlib/Xlib/ext/xtest.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/apl.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/arabic.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/greek.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/hebrew.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/katakana.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/korean.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/latin1.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/latin2.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/latin3.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/latin4.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/miscellany.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/publishing.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/special.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/technical.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/thai.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/xf86.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/xk3270.pyi create mode 100644 stubs/python-xlib/Xlib/keysymdef/xkb.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/display.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/event.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/request.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/rq.pyi create mode 100644 stubs/python-xlib/Xlib/protocol/structs.pyi create mode 100644 stubs/python-xlib/Xlib/rdb.pyi create mode 100644 stubs/python-xlib/Xlib/support/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/support/connect.pyi create mode 100644 stubs/python-xlib/Xlib/support/lock.pyi create mode 100644 stubs/python-xlib/Xlib/support/unix_connect.pyi create mode 100644 stubs/python-xlib/Xlib/support/vms_connect.pyi create mode 100644 stubs/python-xlib/Xlib/threaded.pyi create mode 100644 stubs/python-xlib/Xlib/xauth.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/__init__.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/colormap.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/cursor.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/drawable.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/fontable.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/icccm.pyi create mode 100644 stubs/python-xlib/Xlib/xobject/resource.pyi create mode 100644 stubs/pytz/@tests/stubtest_allowlist.txt create mode 100644 stubs/pytz/METADATA.toml create mode 100644 stubs/pytz/pytz/__init__.pyi create mode 100644 stubs/pytz/pytz/exceptions.pyi create mode 100644 stubs/pytz/pytz/lazy.pyi create mode 100644 stubs/pytz/pytz/reference.pyi create mode 100644 stubs/pytz/pytz/tzfile.pyi create mode 100644 stubs/pytz/pytz/tzinfo.pyi create mode 100644 stubs/pywin32/@tests/stubtest_allowlist_win32.txt create mode 100644 stubs/pywin32/METADATA.toml create mode 100644 stubs/pywin32/_win32typing.pyi create mode 100644 stubs/pywin32/commctrl.pyi create mode 100644 stubs/pywin32/dde.pyi create mode 100644 stubs/pywin32/isapi/__init__.pyi create mode 100644 stubs/pywin32/isapi/install.pyi create mode 100644 stubs/pywin32/isapi/isapicon.pyi create mode 100644 stubs/pywin32/isapi/simple.pyi create mode 100644 stubs/pywin32/isapi/threaded_extension.pyi create mode 100644 stubs/pywin32/mmapfile.pyi create mode 100644 stubs/pywin32/mmsystem.pyi create mode 100644 stubs/pywin32/ntsecuritycon.pyi create mode 100644 stubs/pywin32/odbc.pyi create mode 100644 stubs/pywin32/perfmon.pyi create mode 100644 stubs/pywin32/pythoncom.pyi create mode 100644 stubs/pywin32/pythonwin/__init__.pyi create mode 100644 stubs/pywin32/pythonwin/dde.pyi create mode 100644 stubs/pywin32/pythonwin/win32ui.pyi create mode 100644 stubs/pywin32/pythonwin/win32uiole.pyi create mode 100644 stubs/pywin32/pywintypes.pyi create mode 100644 stubs/pywin32/regutil.pyi create mode 100644 stubs/pywin32/servicemanager.pyi create mode 100644 stubs/pywin32/sspicon.pyi create mode 100644 stubs/pywin32/timer.pyi create mode 100644 stubs/pywin32/win2kras.pyi create mode 100644 stubs/pywin32/win32/__init__.pyi create mode 100644 stubs/pywin32/win32/lib/__init__.pyi create mode 100644 stubs/pywin32/win32/lib/commctrl.pyi create mode 100644 stubs/pywin32/win32/lib/mmsystem.pyi create mode 100644 stubs/pywin32/win32/lib/ntsecuritycon.pyi create mode 100644 stubs/pywin32/win32/lib/pywintypes.pyi create mode 100644 stubs/pywin32/win32/lib/regutil.pyi create mode 100644 stubs/pywin32/win32/lib/sspicon.pyi create mode 100644 stubs/pywin32/win32/lib/win2kras.pyi create mode 100644 stubs/pywin32/win32/lib/win32con.pyi create mode 100644 stubs/pywin32/win32/lib/win32cryptcon.pyi create mode 100644 stubs/pywin32/win32/lib/win32evtlogutil.pyi create mode 100644 stubs/pywin32/win32/lib/win32gui_struct.pyi create mode 100644 stubs/pywin32/win32/lib/win32inetcon.pyi create mode 100644 stubs/pywin32/win32/lib/win32netcon.pyi create mode 100644 stubs/pywin32/win32/lib/win32pdhquery.pyi create mode 100644 stubs/pywin32/win32/lib/win32serviceutil.pyi create mode 100644 stubs/pywin32/win32/lib/win32timezone.pyi create mode 100644 stubs/pywin32/win32/lib/win32verstamp.pyi create mode 100644 stubs/pywin32/win32/lib/winerror.pyi create mode 100644 stubs/pywin32/win32/lib/winioctlcon.pyi create mode 100644 stubs/pywin32/win32/lib/winnt.pyi create mode 100644 stubs/pywin32/win32/lib/winperf.pyi create mode 100644 stubs/pywin32/win32/lib/winxptheme.pyi create mode 100644 stubs/pywin32/win32/mmapfile.pyi create mode 100644 stubs/pywin32/win32/odbc.pyi create mode 100644 stubs/pywin32/win32/perfmon.pyi create mode 100644 stubs/pywin32/win32/servicemanager.pyi create mode 100644 stubs/pywin32/win32/timer.pyi create mode 100644 stubs/pywin32/win32/win32api.pyi create mode 100644 stubs/pywin32/win32/win32clipboard.pyi create mode 100644 stubs/pywin32/win32/win32console.pyi create mode 100644 stubs/pywin32/win32/win32cred.pyi create mode 100644 stubs/pywin32/win32/win32crypt.pyi create mode 100644 stubs/pywin32/win32/win32event.pyi create mode 100644 stubs/pywin32/win32/win32evtlog.pyi create mode 100644 stubs/pywin32/win32/win32file.pyi create mode 100644 stubs/pywin32/win32/win32gui.pyi create mode 100644 stubs/pywin32/win32/win32help.pyi create mode 100644 stubs/pywin32/win32/win32inet.pyi create mode 100644 stubs/pywin32/win32/win32job.pyi create mode 100644 stubs/pywin32/win32/win32lz.pyi create mode 100644 stubs/pywin32/win32/win32net.pyi create mode 100644 stubs/pywin32/win32/win32pdh.pyi create mode 100644 stubs/pywin32/win32/win32pipe.pyi create mode 100644 stubs/pywin32/win32/win32print.pyi create mode 100644 stubs/pywin32/win32/win32process.pyi create mode 100644 stubs/pywin32/win32/win32profile.pyi create mode 100644 stubs/pywin32/win32/win32ras.pyi create mode 100644 stubs/pywin32/win32/win32security.pyi create mode 100644 stubs/pywin32/win32/win32service.pyi create mode 100644 stubs/pywin32/win32/win32trace.pyi create mode 100644 stubs/pywin32/win32/win32transaction.pyi create mode 100644 stubs/pywin32/win32/win32ts.pyi create mode 100644 stubs/pywin32/win32/win32wnet.pyi create mode 100644 stubs/pywin32/win32/winxpgui.pyi create mode 100644 stubs/pywin32/win32api.pyi create mode 100644 stubs/pywin32/win32clipboard.pyi create mode 100644 stubs/pywin32/win32com/__init__.pyi create mode 100644 stubs/pywin32/win32com/adsi/__init__.pyi create mode 100644 stubs/pywin32/win32com/adsi/adsi.pyi create mode 100644 stubs/pywin32/win32com/adsi/adsicon.pyi create mode 100644 stubs/pywin32/win32com/authorization/__init__.pyi create mode 100644 stubs/pywin32/win32com/authorization/authorization.pyi create mode 100644 stubs/pywin32/win32com/axcontrol/__init__.pyi create mode 100644 stubs/pywin32/win32com/axcontrol/axcontrol.pyi create mode 100644 stubs/pywin32/win32com/axdebug/__init__.pyi create mode 100644 stubs/pywin32/win32com/axdebug/adb.pyi create mode 100644 stubs/pywin32/win32com/axdebug/axdebug.pyi create mode 100644 stubs/pywin32/win32com/axdebug/codecontainer.pyi create mode 100644 stubs/pywin32/win32com/axdebug/contexts.pyi create mode 100644 stubs/pywin32/win32com/axdebug/debugger.pyi create mode 100644 stubs/pywin32/win32com/axdebug/documents.pyi create mode 100644 stubs/pywin32/win32com/axdebug/expressions.pyi create mode 100644 stubs/pywin32/win32com/axdebug/gateways.pyi create mode 100644 stubs/pywin32/win32com/axdebug/stackframe.pyi create mode 100644 stubs/pywin32/win32com/axdebug/util.pyi create mode 100644 stubs/pywin32/win32com/axscript/__init__.pyi create mode 100644 stubs/pywin32/win32com/axscript/asputil.pyi create mode 100644 stubs/pywin32/win32com/axscript/axscript.pyi create mode 100644 stubs/pywin32/win32com/axscript/client/__init__.pyi create mode 100644 stubs/pywin32/win32com/axscript/client/debug.pyi create mode 100644 stubs/pywin32/win32com/axscript/client/error.pyi create mode 100644 stubs/pywin32/win32com/axscript/client/framework.pyi create mode 100644 stubs/pywin32/win32com/axscript/server/__init__.pyi create mode 100644 stubs/pywin32/win32com/axscript/server/axsite.pyi create mode 100644 stubs/pywin32/win32com/bits/__init__.pyi create mode 100644 stubs/pywin32/win32com/bits/bits.pyi create mode 100644 stubs/pywin32/win32com/client/__init__.pyi create mode 100644 stubs/pywin32/win32com/client/build.pyi create mode 100644 stubs/pywin32/win32com/client/dynamic.pyi create mode 100644 stubs/pywin32/win32com/client/gencache.pyi create mode 100644 stubs/pywin32/win32com/directsound/__init__.pyi create mode 100644 stubs/pywin32/win32com/directsound/directsound.pyi create mode 100644 stubs/pywin32/win32com/gen_py/__init__.pyi create mode 100644 stubs/pywin32/win32com/ifilter/__init__.pyi create mode 100644 stubs/pywin32/win32com/ifilter/ifilter.pyi create mode 100644 stubs/pywin32/win32com/ifilter/ifiltercon.pyi create mode 100644 stubs/pywin32/win32com/internet/__init__.pyi create mode 100644 stubs/pywin32/win32com/internet/inetcon.pyi create mode 100644 stubs/pywin32/win32com/internet/internet.pyi create mode 100644 stubs/pywin32/win32com/mapi/__init__.pyi create mode 100644 stubs/pywin32/win32com/mapi/emsabtags.pyi create mode 100644 stubs/pywin32/win32com/mapi/exchange.pyi create mode 100644 stubs/pywin32/win32com/mapi/mapi.pyi create mode 100644 stubs/pywin32/win32com/mapi/mapitags.pyi create mode 100644 stubs/pywin32/win32com/mapi/mapiutil.pyi create mode 100644 stubs/pywin32/win32com/olectl.pyi create mode 100644 stubs/pywin32/win32com/propsys/__init__.pyi create mode 100644 stubs/pywin32/win32com/propsys/propsys.pyi create mode 100644 stubs/pywin32/win32com/propsys/pscon.pyi create mode 100644 stubs/pywin32/win32com/server/__init__.pyi create mode 100644 stubs/pywin32/win32com/server/connect.pyi create mode 100644 stubs/pywin32/win32com/server/dispatcher.pyi create mode 100644 stubs/pywin32/win32com/server/exception.pyi create mode 100644 stubs/pywin32/win32com/server/factory.pyi create mode 100644 stubs/pywin32/win32com/server/localserver.pyi create mode 100644 stubs/pywin32/win32com/server/policy.pyi create mode 100644 stubs/pywin32/win32com/server/register.pyi create mode 100644 stubs/pywin32/win32com/server/util.pyi create mode 100644 stubs/pywin32/win32com/shell/__init__.pyi create mode 100644 stubs/pywin32/win32com/shell/shell.pyi create mode 100644 stubs/pywin32/win32com/shell/shellcon.pyi create mode 100644 stubs/pywin32/win32com/storagecon.pyi create mode 100644 stubs/pywin32/win32com/taskscheduler/__init__.pyi create mode 100644 stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi create mode 100644 stubs/pywin32/win32com/universal.pyi create mode 100644 stubs/pywin32/win32com/util.pyi create mode 100644 stubs/pywin32/win32comext/__init__.pyi create mode 100644 stubs/pywin32/win32comext/adsi/__init__.pyi create mode 100644 stubs/pywin32/win32comext/adsi/adsi.pyi create mode 100644 stubs/pywin32/win32comext/adsi/adsicon.pyi create mode 100644 stubs/pywin32/win32comext/authorization/__init__.pyi create mode 100644 stubs/pywin32/win32comext/authorization/authorization.pyi create mode 100644 stubs/pywin32/win32comext/axcontrol/__init__.pyi create mode 100644 stubs/pywin32/win32comext/axcontrol/axcontrol.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/__init__.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/adb.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/axdebug.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/codecontainer.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/contexts.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/debugger.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/documents.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/expressions.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/gateways.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/stackframe.pyi create mode 100644 stubs/pywin32/win32comext/axdebug/util.pyi create mode 100644 stubs/pywin32/win32comext/axscript/__init__.pyi create mode 100644 stubs/pywin32/win32comext/axscript/asputil.pyi create mode 100644 stubs/pywin32/win32comext/axscript/axscript.pyi create mode 100644 stubs/pywin32/win32comext/axscript/client/__init__.pyi create mode 100644 stubs/pywin32/win32comext/axscript/client/debug.pyi create mode 100644 stubs/pywin32/win32comext/axscript/client/error.pyi create mode 100644 stubs/pywin32/win32comext/axscript/client/framework.pyi create mode 100644 stubs/pywin32/win32comext/axscript/server/__init__.pyi create mode 100644 stubs/pywin32/win32comext/axscript/server/axsite.pyi create mode 100644 stubs/pywin32/win32comext/bits/__init__.pyi create mode 100644 stubs/pywin32/win32comext/bits/bits.pyi create mode 100644 stubs/pywin32/win32comext/directsound/__init__.pyi create mode 100644 stubs/pywin32/win32comext/directsound/directsound.pyi create mode 100644 stubs/pywin32/win32comext/ifilter/__init__.pyi create mode 100644 stubs/pywin32/win32comext/ifilter/ifilter.pyi create mode 100644 stubs/pywin32/win32comext/ifilter/ifiltercon.pyi create mode 100644 stubs/pywin32/win32comext/internet/__init__.pyi create mode 100644 stubs/pywin32/win32comext/internet/inetcon.pyi create mode 100644 stubs/pywin32/win32comext/internet/internet.pyi create mode 100644 stubs/pywin32/win32comext/mapi/__init__.pyi create mode 100644 stubs/pywin32/win32comext/mapi/emsabtags.pyi create mode 100644 stubs/pywin32/win32comext/mapi/exchange.pyi create mode 100644 stubs/pywin32/win32comext/mapi/mapi.pyi create mode 100644 stubs/pywin32/win32comext/mapi/mapitags.pyi create mode 100644 stubs/pywin32/win32comext/mapi/mapiutil.pyi create mode 100644 stubs/pywin32/win32comext/propsys/__init__.pyi create mode 100644 stubs/pywin32/win32comext/propsys/propsys.pyi create mode 100644 stubs/pywin32/win32comext/propsys/pscon.pyi create mode 100644 stubs/pywin32/win32comext/shell/__init__.pyi create mode 100644 stubs/pywin32/win32comext/shell/shell.pyi create mode 100644 stubs/pywin32/win32comext/shell/shellcon.pyi create mode 100644 stubs/pywin32/win32comext/taskscheduler/__init__.pyi create mode 100644 stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi create mode 100644 stubs/pywin32/win32con.pyi create mode 100644 stubs/pywin32/win32console.pyi create mode 100644 stubs/pywin32/win32cred.pyi create mode 100644 stubs/pywin32/win32crypt.pyi create mode 100644 stubs/pywin32/win32cryptcon.pyi create mode 100644 stubs/pywin32/win32event.pyi create mode 100644 stubs/pywin32/win32evtlog.pyi create mode 100644 stubs/pywin32/win32evtlogutil.pyi create mode 100644 stubs/pywin32/win32file.pyi create mode 100644 stubs/pywin32/win32gui.pyi create mode 100644 stubs/pywin32/win32gui_struct.pyi create mode 100644 stubs/pywin32/win32help.pyi create mode 100644 stubs/pywin32/win32inet.pyi create mode 100644 stubs/pywin32/win32inetcon.pyi create mode 100644 stubs/pywin32/win32job.pyi create mode 100644 stubs/pywin32/win32lz.pyi create mode 100644 stubs/pywin32/win32net.pyi create mode 100644 stubs/pywin32/win32netcon.pyi create mode 100644 stubs/pywin32/win32pdh.pyi create mode 100644 stubs/pywin32/win32pdhquery.pyi create mode 100644 stubs/pywin32/win32pipe.pyi create mode 100644 stubs/pywin32/win32print.pyi create mode 100644 stubs/pywin32/win32process.pyi create mode 100644 stubs/pywin32/win32profile.pyi create mode 100644 stubs/pywin32/win32ras.pyi create mode 100644 stubs/pywin32/win32security.pyi create mode 100644 stubs/pywin32/win32service.pyi create mode 100644 stubs/pywin32/win32serviceutil.pyi create mode 100644 stubs/pywin32/win32timezone.pyi create mode 100644 stubs/pywin32/win32trace.pyi create mode 100644 stubs/pywin32/win32transaction.pyi create mode 100644 stubs/pywin32/win32ts.pyi create mode 100644 stubs/pywin32/win32ui.pyi create mode 100644 stubs/pywin32/win32uiole.pyi create mode 100644 stubs/pywin32/win32verstamp.pyi create mode 100644 stubs/pywin32/win32wnet.pyi create mode 100644 stubs/pywin32/winerror.pyi create mode 100644 stubs/pywin32/winioctlcon.pyi create mode 100644 stubs/pywin32/winnt.pyi create mode 100644 stubs/pywin32/winperf.pyi create mode 100644 stubs/pywin32/winxpgui.pyi create mode 100644 stubs/pywin32/winxptheme.pyi create mode 100644 stubs/pyxdg/@tests/stubtest_allowlist.txt create mode 100644 stubs/pyxdg/@tests/test_cases/check_IniFile.py create mode 100644 stubs/pyxdg/METADATA.toml create mode 100644 stubs/pyxdg/xdg/BaseDirectory.pyi create mode 100644 stubs/pyxdg/xdg/Config.pyi create mode 100644 stubs/pyxdg/xdg/DesktopEntry.pyi create mode 100644 stubs/pyxdg/xdg/Exceptions.pyi create mode 100644 stubs/pyxdg/xdg/IconTheme.pyi create mode 100644 stubs/pyxdg/xdg/IniFile.pyi create mode 100644 stubs/pyxdg/xdg/Locale.pyi create mode 100644 stubs/pyxdg/xdg/Menu.pyi create mode 100644 stubs/pyxdg/xdg/MenuEditor.pyi create mode 100644 stubs/pyxdg/xdg/Mime.pyi create mode 100644 stubs/pyxdg/xdg/RecentFiles.pyi create mode 100644 stubs/pyxdg/xdg/__init__.pyi create mode 100644 stubs/pyxdg/xdg/util.pyi create mode 100644 stubs/qrbill/@tests/stubtest_allowlist.txt create mode 100644 stubs/qrbill/METADATA.toml create mode 100644 stubs/qrbill/qrbill/__init__.pyi create mode 100644 stubs/qrbill/qrbill/bill.pyi create mode 100644 stubs/qrcode/@tests/stubtest_allowlist.txt create mode 100644 stubs/qrcode/METADATA.toml create mode 100644 stubs/qrcode/qrcode/LUT.pyi create mode 100644 stubs/qrcode/qrcode/__init__.pyi create mode 100644 stubs/qrcode/qrcode/_types.pyi create mode 100644 stubs/qrcode/qrcode/base.pyi create mode 100644 stubs/qrcode/qrcode/console_scripts.pyi create mode 100644 stubs/qrcode/qrcode/constants.pyi create mode 100644 stubs/qrcode/qrcode/exceptions.pyi create mode 100644 stubs/qrcode/qrcode/image/__init__.pyi create mode 100644 stubs/qrcode/qrcode/image/base.pyi create mode 100644 stubs/qrcode/qrcode/image/pil.pyi create mode 100644 stubs/qrcode/qrcode/image/pure.pyi create mode 100644 stubs/qrcode/qrcode/image/styledpil.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/__init__.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/colormasks.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi create mode 100644 stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi create mode 100644 stubs/qrcode/qrcode/image/svg.pyi create mode 100644 stubs/qrcode/qrcode/main.pyi create mode 100644 stubs/qrcode/qrcode/release.pyi create mode 100644 stubs/qrcode/qrcode/util.pyi create mode 100644 stubs/rasterio/@tests/stubtest_allowlist.txt create mode 100644 stubs/rasterio/METADATA.toml create mode 100644 stubs/rasterio/rasterio/__init__.pyi create mode 100644 stubs/rasterio/rasterio/_affine_types.pyi create mode 100644 stubs/rasterio/rasterio/_base.pyi create mode 100644 stubs/rasterio/rasterio/_env.pyi create mode 100644 stubs/rasterio/rasterio/_err.pyi create mode 100644 stubs/rasterio/rasterio/_features.pyi create mode 100644 stubs/rasterio/rasterio/_filepath.pyi create mode 100644 stubs/rasterio/rasterio/_io.pyi create mode 100644 stubs/rasterio/rasterio/_path.pyi create mode 100644 stubs/rasterio/rasterio/_show_versions.pyi create mode 100644 stubs/rasterio/rasterio/_transform.pyi create mode 100644 stubs/rasterio/rasterio/_typing.pyi create mode 100644 stubs/rasterio/rasterio/_version.pyi create mode 100644 stubs/rasterio/rasterio/_vsiopener.pyi create mode 100644 stubs/rasterio/rasterio/_warp.pyi create mode 100644 stubs/rasterio/rasterio/abc.pyi create mode 100644 stubs/rasterio/rasterio/cache.pyi create mode 100644 stubs/rasterio/rasterio/control.pyi create mode 100644 stubs/rasterio/rasterio/coords.pyi create mode 100644 stubs/rasterio/rasterio/crs.pyi create mode 100644 stubs/rasterio/rasterio/drivers.pyi create mode 100644 stubs/rasterio/rasterio/dtypes.pyi create mode 100644 stubs/rasterio/rasterio/enums.pyi create mode 100644 stubs/rasterio/rasterio/env.pyi create mode 100644 stubs/rasterio/rasterio/errors.pyi create mode 100644 stubs/rasterio/rasterio/features.pyi create mode 100644 stubs/rasterio/rasterio/fill.pyi create mode 100644 stubs/rasterio/rasterio/io.pyi create mode 100644 stubs/rasterio/rasterio/mask.pyi create mode 100644 stubs/rasterio/rasterio/merge.pyi create mode 100644 stubs/rasterio/rasterio/path.pyi create mode 100644 stubs/rasterio/rasterio/plot.pyi create mode 100644 stubs/rasterio/rasterio/profiles.pyi create mode 100644 stubs/rasterio/rasterio/rpc.pyi create mode 100644 stubs/rasterio/rasterio/sample.pyi create mode 100644 stubs/rasterio/rasterio/session.pyi create mode 100644 stubs/rasterio/rasterio/shutil.pyi create mode 100644 stubs/rasterio/rasterio/stack.pyi create mode 100644 stubs/rasterio/rasterio/tools.pyi create mode 100644 stubs/rasterio/rasterio/transform.pyi create mode 100644 stubs/rasterio/rasterio/vrt.pyi create mode 100644 stubs/rasterio/rasterio/warp.pyi create mode 100644 stubs/rasterio/rasterio/windows.pyi create mode 100644 stubs/ratelimit/@tests/stubtest_allowlist.txt create mode 100644 stubs/ratelimit/METADATA.toml create mode 100644 stubs/ratelimit/ratelimit/__init__.pyi create mode 100644 stubs/ratelimit/ratelimit/decorators.pyi create mode 100644 stubs/ratelimit/ratelimit/exception.pyi create mode 100644 stubs/regex/@tests/stubtest_allowlist.txt create mode 100644 stubs/regex/@tests/test_cases/check_finditer.py create mode 100644 stubs/regex/METADATA.toml create mode 100644 stubs/regex/regex/__init__.pyi create mode 100644 stubs/regex/regex/_main.pyi create mode 100644 stubs/regex/regex/_regex.pyi create mode 100644 stubs/regex/regex/_regex_core.pyi create mode 100644 stubs/reportlab/@tests/stubtest_allowlist.txt create mode 100644 stubs/reportlab/@tests/test_cases/check_tables.py create mode 100644 stubs/reportlab/METADATA.toml create mode 100644 stubs/reportlab/reportlab/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/code128.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/code39.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/code93.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/common.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/fourstate.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/lto.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/qr.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/usps.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi create mode 100644 stubs/reportlab/reportlab/graphics/barcode/widgets.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/areas.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/axes.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/barcharts.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/dotbox.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/doughnut.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/legends.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/linecharts.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/lineplots.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/markers.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/piecharts.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/slidebox.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/spider.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/textlabels.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/utils.pyi create mode 100644 stubs/reportlab/reportlab/graphics/charts/utils3d.pyi create mode 100644 stubs/reportlab/reportlab/graphics/renderPDF.pyi create mode 100644 stubs/reportlab/reportlab/graphics/renderPM.pyi create mode 100644 stubs/reportlab/reportlab/graphics/renderPS.pyi create mode 100644 stubs/reportlab/reportlab/graphics/renderSVG.pyi create mode 100644 stubs/reportlab/reportlab/graphics/renderbase.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/bubble.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/line_chart.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/radar.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/runall.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/scatter.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi create mode 100644 stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi create mode 100644 stubs/reportlab/reportlab/graphics/shapes.pyi create mode 100644 stubs/reportlab/reportlab/graphics/svgpath.pyi create mode 100644 stubs/reportlab/reportlab/graphics/transform.pyi create mode 100644 stubs/reportlab/reportlab/graphics/utils.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgetbase.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/__init__.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/flags.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/grids.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/markers.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi create mode 100644 stubs/reportlab/reportlab/graphics/widgets/table.pyi create mode 100644 stubs/reportlab/reportlab/lib/PyFontify.pyi create mode 100644 stubs/reportlab/reportlab/lib/__init__.pyi create mode 100644 stubs/reportlab/reportlab/lib/abag.pyi create mode 100644 stubs/reportlab/reportlab/lib/arciv.pyi create mode 100644 stubs/reportlab/reportlab/lib/attrmap.pyi create mode 100644 stubs/reportlab/reportlab/lib/boxstuff.pyi create mode 100644 stubs/reportlab/reportlab/lib/codecharts.pyi create mode 100644 stubs/reportlab/reportlab/lib/colors.pyi create mode 100644 stubs/reportlab/reportlab/lib/corp.pyi create mode 100644 stubs/reportlab/reportlab/lib/enums.pyi create mode 100644 stubs/reportlab/reportlab/lib/extformat.pyi create mode 100644 stubs/reportlab/reportlab/lib/fontfinder.pyi create mode 100644 stubs/reportlab/reportlab/lib/fonts.pyi create mode 100644 stubs/reportlab/reportlab/lib/formatters.pyi create mode 100644 stubs/reportlab/reportlab/lib/geomutils.pyi create mode 100644 stubs/reportlab/reportlab/lib/logger.pyi create mode 100644 stubs/reportlab/reportlab/lib/normalDate.pyi create mode 100644 stubs/reportlab/reportlab/lib/pagesizes.pyi create mode 100644 stubs/reportlab/reportlab/lib/pdfencrypt.pyi create mode 100644 stubs/reportlab/reportlab/lib/pygments2xpre.pyi create mode 100644 stubs/reportlab/reportlab/lib/randomtext.pyi create mode 100644 stubs/reportlab/reportlab/lib/rl_accel.pyi create mode 100644 stubs/reportlab/reportlab/lib/rl_safe_eval.pyi create mode 100644 stubs/reportlab/reportlab/lib/rltempfile.pyi create mode 100644 stubs/reportlab/reportlab/lib/rparsexml.pyi create mode 100644 stubs/reportlab/reportlab/lib/sequencer.pyi create mode 100644 stubs/reportlab/reportlab/lib/styles.pyi create mode 100644 stubs/reportlab/reportlab/lib/testutils.pyi create mode 100644 stubs/reportlab/reportlab/lib/textsplit.pyi create mode 100644 stubs/reportlab/reportlab/lib/units.pyi create mode 100644 stubs/reportlab/reportlab/lib/utils.pyi create mode 100644 stubs/reportlab/reportlab/lib/validators.pyi create mode 100644 stubs/reportlab/reportlab/lib/yaml.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/__init__.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/acroform.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/cidfonts.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/pdfform.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/pdfutils.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi create mode 100644 stubs/reportlab/reportlab/pdfbase/ttfonts.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/__init__.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/canvas.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/pathobject.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/pdfimages.pyi create mode 100644 stubs/reportlab/reportlab/pdfgen/textobject.pyi create mode 100644 stubs/reportlab/reportlab/platypus/__init__.pyi create mode 100644 stubs/reportlab/reportlab/platypus/doctemplate.pyi create mode 100644 stubs/reportlab/reportlab/platypus/figures.pyi create mode 100644 stubs/reportlab/reportlab/platypus/flowables.pyi create mode 100644 stubs/reportlab/reportlab/platypus/frames.pyi create mode 100644 stubs/reportlab/reportlab/platypus/multicol.pyi create mode 100644 stubs/reportlab/reportlab/platypus/para.pyi create mode 100644 stubs/reportlab/reportlab/platypus/paragraph.pyi create mode 100644 stubs/reportlab/reportlab/platypus/paraparser.pyi create mode 100644 stubs/reportlab/reportlab/platypus/tableofcontents.pyi create mode 100644 stubs/reportlab/reportlab/platypus/tables.pyi create mode 100644 stubs/reportlab/reportlab/platypus/xpreformatted.pyi create mode 100644 stubs/reportlab/reportlab/rl_config.pyi create mode 100644 stubs/reportlab/reportlab/rl_settings.pyi create mode 100644 stubs/requests-oauthlib/METADATA.toml create mode 100644 stubs/requests-oauthlib/requests_oauthlib/__init__.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi create mode 100644 stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi create mode 100644 stubs/requests/@tests/stubtest_allowlist.txt create mode 100644 stubs/requests/@tests/test_cases/check_post.py create mode 100644 stubs/requests/METADATA.toml create mode 100644 stubs/requests/requests/__init__.pyi create mode 100644 stubs/requests/requests/__version__.pyi create mode 100644 stubs/requests/requests/adapters.pyi create mode 100644 stubs/requests/requests/api.pyi create mode 100644 stubs/requests/requests/auth.pyi create mode 100644 stubs/requests/requests/certs.pyi create mode 100644 stubs/requests/requests/compat.pyi create mode 100644 stubs/requests/requests/cookies.pyi create mode 100644 stubs/requests/requests/exceptions.pyi create mode 100644 stubs/requests/requests/help.pyi create mode 100644 stubs/requests/requests/hooks.pyi create mode 100644 stubs/requests/requests/models.pyi create mode 100644 stubs/requests/requests/packages.pyi create mode 100644 stubs/requests/requests/sessions.pyi create mode 100644 stubs/requests/requests/status_codes.pyi create mode 100644 stubs/requests/requests/structures.pyi create mode 100644 stubs/requests/requests/utils.pyi create mode 100644 stubs/resampy/@tests/stubtest_allowlist.txt create mode 100644 stubs/resampy/METADATA.toml create mode 100644 stubs/resampy/resampy/__init__.pyi create mode 100644 stubs/resampy/resampy/core.pyi create mode 100644 stubs/resampy/resampy/filters.pyi create mode 100644 stubs/resampy/resampy/version.pyi create mode 100644 stubs/retry/@tests/stubtest_allowlist.txt create mode 100644 stubs/retry/METADATA.toml create mode 100644 stubs/retry/retry/__init__.pyi create mode 100644 stubs/retry/retry/api.pyi create mode 100644 stubs/rfc3339-validator/METADATA.toml create mode 100644 stubs/rfc3339-validator/rfc3339_validator.pyi create mode 100644 stubs/s2clientprotocol/@tests/stubtest_allowlist.txt create mode 100644 stubs/s2clientprotocol/METADATA.toml create mode 100644 stubs/s2clientprotocol/s2clientprotocol/build.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi create mode 100644 stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi create mode 100644 stubs/scp/METADATA.toml create mode 100644 stubs/scp/scp.pyi create mode 100644 stubs/seaborn/@tests/stubtest_allowlist.txt create mode 100644 stubs/seaborn/METADATA.toml create mode 100644 stubs/seaborn/seaborn/__init__.pyi create mode 100644 stubs/seaborn/seaborn/_core/__init__.pyi create mode 100644 stubs/seaborn/seaborn/_core/data.pyi create mode 100644 stubs/seaborn/seaborn/_core/exceptions.pyi create mode 100644 stubs/seaborn/seaborn/_core/groupby.pyi create mode 100644 stubs/seaborn/seaborn/_core/moves.pyi create mode 100644 stubs/seaborn/seaborn/_core/plot.pyi create mode 100644 stubs/seaborn/seaborn/_core/properties.pyi create mode 100644 stubs/seaborn/seaborn/_core/rules.pyi create mode 100644 stubs/seaborn/seaborn/_core/scales.pyi create mode 100644 stubs/seaborn/seaborn/_core/subplots.pyi create mode 100644 stubs/seaborn/seaborn/_core/typing.pyi create mode 100644 stubs/seaborn/seaborn/_marks/__init__.pyi create mode 100644 stubs/seaborn/seaborn/_marks/area.pyi create mode 100644 stubs/seaborn/seaborn/_marks/bar.pyi create mode 100644 stubs/seaborn/seaborn/_marks/base.pyi create mode 100644 stubs/seaborn/seaborn/_marks/dot.pyi create mode 100644 stubs/seaborn/seaborn/_marks/line.pyi create mode 100644 stubs/seaborn/seaborn/_marks/text.pyi create mode 100644 stubs/seaborn/seaborn/_stats/__init__.pyi create mode 100644 stubs/seaborn/seaborn/_stats/aggregation.pyi create mode 100644 stubs/seaborn/seaborn/_stats/base.pyi create mode 100644 stubs/seaborn/seaborn/_stats/counting.pyi create mode 100644 stubs/seaborn/seaborn/_stats/density.pyi create mode 100644 stubs/seaborn/seaborn/_stats/order.pyi create mode 100644 stubs/seaborn/seaborn/_stats/regression.pyi create mode 100644 stubs/seaborn/seaborn/algorithms.pyi create mode 100644 stubs/seaborn/seaborn/axisgrid.pyi create mode 100644 stubs/seaborn/seaborn/categorical.pyi create mode 100644 stubs/seaborn/seaborn/cm.pyi create mode 100644 stubs/seaborn/seaborn/colors/__init__.pyi create mode 100644 stubs/seaborn/seaborn/colors/crayons.pyi create mode 100644 stubs/seaborn/seaborn/colors/xkcd_rgb.pyi create mode 100644 stubs/seaborn/seaborn/distributions.pyi create mode 100644 stubs/seaborn/seaborn/external/__init__.pyi create mode 100644 stubs/seaborn/seaborn/external/appdirs.pyi create mode 100644 stubs/seaborn/seaborn/external/docscrape.pyi create mode 100644 stubs/seaborn/seaborn/external/husl.pyi create mode 100644 stubs/seaborn/seaborn/external/kde.pyi create mode 100644 stubs/seaborn/seaborn/external/version.pyi create mode 100644 stubs/seaborn/seaborn/matrix.pyi create mode 100644 stubs/seaborn/seaborn/miscplot.pyi create mode 100644 stubs/seaborn/seaborn/objects.pyi create mode 100644 stubs/seaborn/seaborn/palettes.pyi create mode 100644 stubs/seaborn/seaborn/rcmod.pyi create mode 100644 stubs/seaborn/seaborn/regression.pyi create mode 100644 stubs/seaborn/seaborn/relational.pyi create mode 100644 stubs/seaborn/seaborn/utils.pyi create mode 100644 stubs/seaborn/seaborn/widgets.pyi create mode 100644 stubs/setuptools/@tests/stubtest_allowlist.txt create mode 100644 stubs/setuptools/@tests/test_cases/check_distutils.py create mode 100644 stubs/setuptools/@tests/test_cases/check_extension.py create mode 100644 stubs/setuptools/@tests/test_cases/check_protocols.py create mode 100644 stubs/setuptools/@tests/test_cases/check_setup.py create mode 100644 stubs/setuptools/METADATA.toml create mode 100644 stubs/setuptools/distutils/__init__.pyi create mode 100644 stubs/setuptools/distutils/_modified.pyi create mode 100644 stubs/setuptools/distutils/_msvccompiler.pyi create mode 100644 stubs/setuptools/distutils/archive_util.pyi create mode 100644 stubs/setuptools/distutils/ccompiler.pyi create mode 100644 stubs/setuptools/distutils/cmd.pyi create mode 100644 stubs/setuptools/distutils/command/__init__.pyi create mode 100644 stubs/setuptools/distutils/command/bdist.pyi create mode 100644 stubs/setuptools/distutils/command/bdist_rpm.pyi create mode 100644 stubs/setuptools/distutils/command/build.pyi create mode 100644 stubs/setuptools/distutils/command/build_clib.pyi create mode 100644 stubs/setuptools/distutils/command/build_ext.pyi create mode 100644 stubs/setuptools/distutils/command/build_py.pyi create mode 100644 stubs/setuptools/distutils/command/install.pyi create mode 100644 stubs/setuptools/distutils/command/install_data.pyi create mode 100644 stubs/setuptools/distutils/command/install_lib.pyi create mode 100644 stubs/setuptools/distutils/command/install_scripts.pyi create mode 100644 stubs/setuptools/distutils/command/sdist.pyi create mode 100644 stubs/setuptools/distutils/compat/__init__.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/base.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/cygwin.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/errors.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/msvc.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/unix.pyi create mode 100644 stubs/setuptools/distutils/compilers/C/zos.pyi create mode 100644 stubs/setuptools/distutils/cygwinccompiler.pyi create mode 100644 stubs/setuptools/distutils/dep_util.pyi create mode 100644 stubs/setuptools/distutils/dist.pyi create mode 100644 stubs/setuptools/distutils/errors.pyi create mode 100644 stubs/setuptools/distutils/extension.pyi create mode 100644 stubs/setuptools/distutils/filelist.pyi create mode 100644 stubs/setuptools/distutils/spawn.pyi create mode 100644 stubs/setuptools/distutils/sysconfig.pyi create mode 100644 stubs/setuptools/distutils/unixccompiler.pyi create mode 100644 stubs/setuptools/distutils/util.pyi create mode 100644 stubs/setuptools/distutils/version.pyi create mode 100644 stubs/setuptools/distutils/zosccompiler.pyi create mode 100644 stubs/setuptools/setuptools/__init__.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/__init__.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/_modified.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/archive_util.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/ccompiler.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/cmd.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/__init__.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/bdist.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/build.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/build_clib.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/build_ext.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/build_py.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/install.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/install_data.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/install_lib.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/command/sdist.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compat/__init__.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/dep_util.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/dist.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/errors.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/extension.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/filelist.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/spawn.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/sysconfig.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/unixccompiler.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/util.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/version.pyi create mode 100644 stubs/setuptools/setuptools/_distutils/zosccompiler.pyi create mode 100644 stubs/setuptools/setuptools/archive_util.pyi create mode 100644 stubs/setuptools/setuptools/build_meta.pyi create mode 100644 stubs/setuptools/setuptools/command/__init__.pyi create mode 100644 stubs/setuptools/setuptools/command/alias.pyi create mode 100644 stubs/setuptools/setuptools/command/bdist_egg.pyi create mode 100644 stubs/setuptools/setuptools/command/bdist_rpm.pyi create mode 100644 stubs/setuptools/setuptools/command/bdist_wheel.pyi create mode 100644 stubs/setuptools/setuptools/command/build.pyi create mode 100644 stubs/setuptools/setuptools/command/build_clib.pyi create mode 100644 stubs/setuptools/setuptools/command/build_ext.pyi create mode 100644 stubs/setuptools/setuptools/command/build_py.pyi create mode 100644 stubs/setuptools/setuptools/command/develop.pyi create mode 100644 stubs/setuptools/setuptools/command/dist_info.pyi create mode 100644 stubs/setuptools/setuptools/command/easy_install.pyi create mode 100644 stubs/setuptools/setuptools/command/editable_wheel.pyi create mode 100644 stubs/setuptools/setuptools/command/egg_info.pyi create mode 100644 stubs/setuptools/setuptools/command/install.pyi create mode 100644 stubs/setuptools/setuptools/command/install_egg_info.pyi create mode 100644 stubs/setuptools/setuptools/command/install_lib.pyi create mode 100644 stubs/setuptools/setuptools/command/install_scripts.pyi create mode 100644 stubs/setuptools/setuptools/command/rotate.pyi create mode 100644 stubs/setuptools/setuptools/command/saveopts.pyi create mode 100644 stubs/setuptools/setuptools/command/sdist.pyi create mode 100644 stubs/setuptools/setuptools/command/setopt.pyi create mode 100644 stubs/setuptools/setuptools/command/test.pyi create mode 100644 stubs/setuptools/setuptools/config/__init__.pyi create mode 100644 stubs/setuptools/setuptools/config/expand.pyi create mode 100644 stubs/setuptools/setuptools/config/pyprojecttoml.pyi create mode 100644 stubs/setuptools/setuptools/config/setupcfg.pyi create mode 100644 stubs/setuptools/setuptools/depends.pyi create mode 100644 stubs/setuptools/setuptools/discovery.pyi create mode 100644 stubs/setuptools/setuptools/dist.pyi create mode 100644 stubs/setuptools/setuptools/errors.pyi create mode 100644 stubs/setuptools/setuptools/extension.pyi create mode 100644 stubs/setuptools/setuptools/glob.pyi create mode 100644 stubs/setuptools/setuptools/installer.pyi create mode 100644 stubs/setuptools/setuptools/launch.pyi create mode 100644 stubs/setuptools/setuptools/logging.pyi create mode 100644 stubs/setuptools/setuptools/modified.pyi create mode 100644 stubs/setuptools/setuptools/monkey.pyi create mode 100644 stubs/setuptools/setuptools/msvc.pyi create mode 100644 stubs/setuptools/setuptools/namespaces.pyi create mode 100644 stubs/setuptools/setuptools/unicode_utils.pyi create mode 100644 stubs/setuptools/setuptools/version.pyi create mode 100644 stubs/setuptools/setuptools/warnings.pyi create mode 100644 stubs/setuptools/setuptools/wheel.pyi create mode 100644 stubs/setuptools/setuptools/windows_support.pyi create mode 100644 stubs/shapely/@tests/stubtest_allowlist.txt create mode 100644 stubs/shapely/METADATA.toml create mode 100644 stubs/shapely/shapely/__init__.pyi create mode 100644 stubs/shapely/shapely/_coverage.pyi create mode 100644 stubs/shapely/shapely/_enum.pyi create mode 100644 stubs/shapely/shapely/_geometry.pyi create mode 100644 stubs/shapely/shapely/_ragged_array.pyi create mode 100644 stubs/shapely/shapely/_typing.pyi create mode 100644 stubs/shapely/shapely/_version.pyi create mode 100644 stubs/shapely/shapely/affinity.pyi create mode 100644 stubs/shapely/shapely/algorithms/__init__.pyi create mode 100644 stubs/shapely/shapely/algorithms/cga.pyi create mode 100644 stubs/shapely/shapely/algorithms/polylabel.pyi create mode 100644 stubs/shapely/shapely/constructive.pyi create mode 100644 stubs/shapely/shapely/coordinates.pyi create mode 100644 stubs/shapely/shapely/coords.pyi create mode 100644 stubs/shapely/shapely/creation.pyi create mode 100644 stubs/shapely/shapely/decorators.pyi create mode 100644 stubs/shapely/shapely/errors.pyi create mode 100644 stubs/shapely/shapely/geometry/__init__.pyi create mode 100644 stubs/shapely/shapely/geometry/base.pyi create mode 100644 stubs/shapely/shapely/geometry/collection.pyi create mode 100644 stubs/shapely/shapely/geometry/geo.pyi create mode 100644 stubs/shapely/shapely/geometry/linestring.pyi create mode 100644 stubs/shapely/shapely/geometry/multilinestring.pyi create mode 100644 stubs/shapely/shapely/geometry/multipoint.pyi create mode 100644 stubs/shapely/shapely/geometry/multipolygon.pyi create mode 100644 stubs/shapely/shapely/geometry/point.pyi create mode 100644 stubs/shapely/shapely/geometry/polygon.pyi create mode 100644 stubs/shapely/shapely/geos.pyi create mode 100644 stubs/shapely/shapely/io.pyi create mode 100644 stubs/shapely/shapely/lib.pyi create mode 100644 stubs/shapely/shapely/linear.pyi create mode 100644 stubs/shapely/shapely/measurement.pyi create mode 100644 stubs/shapely/shapely/ops.pyi create mode 100644 stubs/shapely/shapely/plotting.pyi create mode 100644 stubs/shapely/shapely/predicates.pyi create mode 100644 stubs/shapely/shapely/prepared.pyi create mode 100644 stubs/shapely/shapely/set_operations.pyi create mode 100644 stubs/shapely/shapely/speedups.pyi create mode 100644 stubs/shapely/shapely/strtree.pyi create mode 100644 stubs/shapely/shapely/testing.pyi create mode 100644 stubs/shapely/shapely/validation.pyi create mode 100644 stubs/shapely/shapely/vectorized/__init__.pyi create mode 100644 stubs/shapely/shapely/wkb.pyi create mode 100644 stubs/shapely/shapely/wkt.pyi create mode 100644 stubs/simple-websocket/METADATA.toml create mode 100644 stubs/simple-websocket/simple_websocket/__init__.pyi create mode 100644 stubs/simple-websocket/simple_websocket/aiows.pyi create mode 100644 stubs/simple-websocket/simple_websocket/asgi.pyi create mode 100644 stubs/simple-websocket/simple_websocket/errors.pyi create mode 100644 stubs/simple-websocket/simple_websocket/ws.pyi create mode 100644 stubs/simplejson/@tests/stubtest_allowlist.txt create mode 100644 stubs/simplejson/@tests/test_cases/check_simplejson.py create mode 100644 stubs/simplejson/METADATA.toml create mode 100644 stubs/simplejson/simplejson/__init__.pyi create mode 100644 stubs/simplejson/simplejson/decoder.pyi create mode 100644 stubs/simplejson/simplejson/encoder.pyi create mode 100644 stubs/simplejson/simplejson/errors.pyi create mode 100644 stubs/simplejson/simplejson/raw_json.pyi create mode 100644 stubs/simplejson/simplejson/scanner.pyi create mode 100644 stubs/singledispatch/METADATA.toml create mode 100644 stubs/singledispatch/singledispatch.pyi create mode 100644 stubs/six/@tests/stubtest_allowlist.txt create mode 100644 stubs/six/METADATA.toml create mode 100644 stubs/six/six/__init__.pyi create mode 100644 stubs/six/six/moves/BaseHTTPServer.pyi create mode 100644 stubs/six/six/moves/CGIHTTPServer.pyi create mode 100644 stubs/six/six/moves/SimpleHTTPServer.pyi create mode 100644 stubs/six/six/moves/__init__.pyi create mode 100644 stubs/six/six/moves/_dummy_thread.pyi create mode 100644 stubs/six/six/moves/_thread.pyi create mode 100644 stubs/six/six/moves/builtins.pyi create mode 100644 stubs/six/six/moves/cPickle.pyi create mode 100644 stubs/six/six/moves/collections_abc.pyi create mode 100644 stubs/six/six/moves/configparser.pyi create mode 100644 stubs/six/six/moves/copyreg.pyi create mode 100644 stubs/six/six/moves/email_mime_base.pyi create mode 100644 stubs/six/six/moves/email_mime_multipart.pyi create mode 100644 stubs/six/six/moves/email_mime_nonmultipart.pyi create mode 100644 stubs/six/six/moves/email_mime_text.pyi create mode 100644 stubs/six/six/moves/html_entities.pyi create mode 100644 stubs/six/six/moves/html_parser.pyi create mode 100644 stubs/six/six/moves/http_client.pyi create mode 100644 stubs/six/six/moves/http_cookiejar.pyi create mode 100644 stubs/six/six/moves/http_cookies.pyi create mode 100644 stubs/six/six/moves/queue.pyi create mode 100644 stubs/six/six/moves/reprlib.pyi create mode 100644 stubs/six/six/moves/socketserver.pyi create mode 100644 stubs/six/six/moves/tkinter.pyi create mode 100644 stubs/six/six/moves/tkinter_commondialog.pyi create mode 100644 stubs/six/six/moves/tkinter_constants.pyi create mode 100644 stubs/six/six/moves/tkinter_dialog.pyi create mode 100644 stubs/six/six/moves/tkinter_filedialog.pyi create mode 100644 stubs/six/six/moves/tkinter_tkfiledialog.pyi create mode 100644 stubs/six/six/moves/tkinter_ttk.pyi create mode 100644 stubs/six/six/moves/urllib/__init__.pyi create mode 100644 stubs/six/six/moves/urllib/error.pyi create mode 100644 stubs/six/six/moves/urllib/parse.pyi create mode 100644 stubs/six/six/moves/urllib/request.pyi create mode 100644 stubs/six/six/moves/urllib/response.pyi create mode 100644 stubs/six/six/moves/urllib/robotparser.pyi create mode 100644 stubs/six/six/moves/urllib_error.pyi create mode 100644 stubs/six/six/moves/urllib_parse.pyi create mode 100644 stubs/six/six/moves/urllib_request.pyi create mode 100644 stubs/six/six/moves/urllib_response.pyi create mode 100644 stubs/six/six/moves/urllib_robotparser.pyi create mode 100644 stubs/slumber/METADATA.toml create mode 100644 stubs/slumber/slumber/__init__.pyi create mode 100644 stubs/slumber/slumber/exceptions.pyi create mode 100644 stubs/slumber/slumber/serialize.pyi create mode 100644 stubs/slumber/slumber/utils.pyi create mode 100644 stubs/str2bool/METADATA.toml create mode 100644 stubs/str2bool/str2bool/__init__.pyi create mode 100644 stubs/tabulate/METADATA.toml create mode 100644 stubs/tabulate/tabulate/__init__.pyi create mode 100644 stubs/tensorflow/@tests/stubtest_allowlist.txt create mode 100644 stubs/tensorflow/METADATA.toml create mode 100644 stubs/tensorflow/tensorflow/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/_aliases.pyi create mode 100644 stubs/tensorflow/tensorflow/audio.pyi create mode 100644 stubs/tensorflow/tensorflow/autodiff.pyi create mode 100644 stubs/tensorflow/tensorflow/autograph/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/autograph/experimental.pyi create mode 100644 stubs/tensorflow/tensorflow/bitwise.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/config/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/config/experimental.pyi create mode 100644 stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/example/example_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/function_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/graph_debug_info_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/graph_transfer_info_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/kernel_def_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/log_memory_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/model_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/node_def_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/op_def_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/optimized_function_graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/reader_base_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/resource_handle_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/step_stats_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/summary_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/tensor_description_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/tensor_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/tensor_shape_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/tensor_slice_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/types_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/variable_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/framework/versions_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/bfc_memory_map_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/cluster_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/composite_tensor_variant_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/control_flow_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/core_platform_payloads_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/data_service_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/debug_event_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/debug_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/device_filters_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/device_properties_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/error_codes_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/fingerprint_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/meta_graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/named_tensor_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/queue_runner_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/remote_tensor_handle_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/rewriter_config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/rpc_options_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/saved_model_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/saved_object_graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/saver_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/service_config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/snapshot_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/status_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/struct_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tensor_bundle_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tensorflow_server_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tpu/compilation_result_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tpu/dynamic_padding_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tpu/optimization_parameters_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tpu/topology_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/tpu/tpu_embedding_configuration_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/trackable_object_graph_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/transport_options_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/protobuf/verifier_config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/util/event_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/util/memmapped_file_system_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/util/saved_tensor_slice_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/core/util/test_log_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/data/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/data/experimental.pyi create mode 100644 stubs/tensorflow/tensorflow/debugging.pyi create mode 100644 stubs/tensorflow/tensorflow/distribute/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/distribute/coordinator.pyi create mode 100644 stubs/tensorflow/tensorflow/distribute/experimental/coordinator.pyi create mode 100644 stubs/tensorflow/tensorflow/dtypes.pyi create mode 100644 stubs/tensorflow/tensorflow/experimental/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/experimental/dtensor.pyi create mode 100644 stubs/tensorflow/tensorflow/feature_column/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/image.pyi create mode 100644 stubs/tensorflow/tensorflow/initializers.pyi create mode 100644 stubs/tensorflow/tensorflow/io/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/io/gfile.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/activations.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/callbacks.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/constraints.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/initializers.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/layers/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/losses.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/metrics.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/models.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/optimizers/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/optimizers/legacy/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/optimizers/schedules.pyi create mode 100644 stubs/tensorflow/tensorflow/keras/regularizers.pyi create mode 100644 stubs/tensorflow/tensorflow/linalg.pyi create mode 100644 stubs/tensorflow/tensorflow/math.pyi create mode 100644 stubs/tensorflow/tensorflow/nn.pyi create mode 100644 stubs/tensorflow/tensorflow/python/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/python/distribute/distribute_lib.pyi create mode 100644 stubs/tensorflow/tensorflow/python/feature_column/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/python/feature_column/feature_column_v2.pyi create mode 100644 stubs/tensorflow/tensorflow/python/feature_column/sequence_feature_column.pyi create mode 100644 stubs/tensorflow/tensorflow/python/framework/dtypes.pyi create mode 100644 stubs/tensorflow/tensorflow/python/keras/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/python/keras/protobuf/projector_config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/python/keras/protobuf/saved_metadata_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/python/keras/protobuf/versions_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/python/trackable/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/python/trackable/autotrackable.pyi create mode 100644 stubs/tensorflow/tensorflow/python/trackable/base.pyi create mode 100644 stubs/tensorflow/tensorflow/python/trackable/resource.pyi create mode 100644 stubs/tensorflow/tensorflow/python/trackable/ressource.pyi create mode 100644 stubs/tensorflow/tensorflow/python/training/tracking/autotrackable.pyi create mode 100644 stubs/tensorflow/tensorflow/random.pyi create mode 100644 stubs/tensorflow/tensorflow/raw_ops.pyi create mode 100644 stubs/tensorflow/tensorflow/saved_model/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/saved_model/experimental.pyi create mode 100644 stubs/tensorflow/tensorflow/signal.pyi create mode 100644 stubs/tensorflow/tensorflow/sparse.pyi create mode 100644 stubs/tensorflow/tensorflow/strings.pyi create mode 100644 stubs/tensorflow/tensorflow/summary.pyi create mode 100644 stubs/tensorflow/tensorflow/train/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/train/experimental.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/coordination_config_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/coordination_service_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/distributed_runtime_payloads_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/dnn_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/error_codes_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/histogram_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/rpc_options_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/tsl/protobuf/status_pb2.pyi create mode 100644 stubs/tensorflow/tensorflow/types/__init__.pyi create mode 100644 stubs/tensorflow/tensorflow/types/experimental.pyi create mode 100644 stubs/tinycss2/METADATA.toml create mode 100644 stubs/tinycss2/tinycss2/__init__.pyi create mode 100644 stubs/tinycss2/tinycss2/ast.pyi create mode 100644 stubs/tinycss2/tinycss2/bytes.pyi create mode 100644 stubs/tinycss2/tinycss2/color3.pyi create mode 100644 stubs/tinycss2/tinycss2/color4.pyi create mode 100644 stubs/tinycss2/tinycss2/color5.pyi create mode 100644 stubs/tinycss2/tinycss2/nth.pyi create mode 100644 stubs/tinycss2/tinycss2/parser.pyi create mode 100644 stubs/tinycss2/tinycss2/serializer.pyi create mode 100644 stubs/tinycss2/tinycss2/tokenizer.pyi create mode 100644 stubs/toml/@tests/stubtest_allowlist.txt create mode 100644 stubs/toml/METADATA.toml create mode 100644 stubs/toml/toml/__init__.pyi create mode 100644 stubs/toml/toml/decoder.pyi create mode 100644 stubs/toml/toml/encoder.pyi create mode 100644 stubs/toml/toml/ordered.pyi create mode 100644 stubs/toml/toml/tz.pyi create mode 100644 stubs/toposort/METADATA.toml create mode 100644 stubs/toposort/toposort.pyi create mode 100644 stubs/tqdm/@tests/stubtest_allowlist.txt create mode 100644 stubs/tqdm/METADATA.toml create mode 100644 stubs/tqdm/tqdm/__init__.pyi create mode 100644 stubs/tqdm/tqdm/_main.pyi create mode 100644 stubs/tqdm/tqdm/_monitor.pyi create mode 100644 stubs/tqdm/tqdm/_tqdm.pyi create mode 100644 stubs/tqdm/tqdm/_tqdm_gui.pyi create mode 100644 stubs/tqdm/tqdm/_tqdm_notebook.pyi create mode 100644 stubs/tqdm/tqdm/_tqdm_pandas.pyi create mode 100644 stubs/tqdm/tqdm/_utils.pyi create mode 100644 stubs/tqdm/tqdm/asyncio.pyi create mode 100644 stubs/tqdm/tqdm/auto.pyi create mode 100644 stubs/tqdm/tqdm/autonotebook.pyi create mode 100644 stubs/tqdm/tqdm/cli.pyi create mode 100644 stubs/tqdm/tqdm/contrib/__init__.pyi create mode 100644 stubs/tqdm/tqdm/contrib/bells.pyi create mode 100644 stubs/tqdm/tqdm/contrib/concurrent.pyi create mode 100644 stubs/tqdm/tqdm/contrib/discord.pyi create mode 100644 stubs/tqdm/tqdm/contrib/itertools.pyi create mode 100644 stubs/tqdm/tqdm/contrib/logging.pyi create mode 100644 stubs/tqdm/tqdm/contrib/slack.pyi create mode 100644 stubs/tqdm/tqdm/contrib/telegram.pyi create mode 100644 stubs/tqdm/tqdm/contrib/utils_worker.pyi create mode 100644 stubs/tqdm/tqdm/dask.pyi create mode 100644 stubs/tqdm/tqdm/gui.pyi create mode 100644 stubs/tqdm/tqdm/keras.pyi create mode 100644 stubs/tqdm/tqdm/notebook.pyi create mode 100644 stubs/tqdm/tqdm/rich.pyi create mode 100644 stubs/tqdm/tqdm/std.pyi create mode 100644 stubs/tqdm/tqdm/tk.pyi create mode 100644 stubs/tqdm/tqdm/utils.pyi create mode 100644 stubs/tqdm/tqdm/version.pyi create mode 100644 stubs/translationstring/@tests/stubtest_allowlist.txt create mode 100644 stubs/translationstring/METADATA.toml create mode 100644 stubs/translationstring/translationstring/__init__.pyi create mode 100644 stubs/ttkthemes/@tests/stubtest_allowlist.txt create mode 100644 stubs/ttkthemes/METADATA.toml create mode 100644 stubs/ttkthemes/ttkthemes/__init__.pyi create mode 100644 stubs/ttkthemes/ttkthemes/_imgops.pyi create mode 100644 stubs/ttkthemes/ttkthemes/_utils.pyi create mode 100644 stubs/ttkthemes/ttkthemes/_widget.pyi create mode 100644 stubs/ttkthemes/ttkthemes/themed_style.pyi create mode 100644 stubs/ttkthemes/ttkthemes/themed_tk.pyi create mode 100644 stubs/tzdata/@tests/stubtest_allowlist.txt create mode 100644 stubs/tzdata/METADATA.toml create mode 100644 stubs/tzdata/tzdata/__init__.pyi create mode 100644 stubs/uWSGI/@tests/stubtest_allowlist.txt create mode 100644 stubs/uWSGI/@tests/stubtest_allowlist_darwin.txt create mode 100644 stubs/uWSGI/@tests/uwsgi.ini create mode 100644 stubs/uWSGI/METADATA.toml create mode 100644 stubs/uWSGI/uwsgi.pyi create mode 100644 stubs/uWSGI/uwsgidecorators.pyi create mode 100644 stubs/unidiff/@tests/stubtest_allowlist.txt create mode 100644 stubs/unidiff/METADATA.toml create mode 100644 stubs/unidiff/unidiff/__init__.pyi create mode 100644 stubs/unidiff/unidiff/__version__.pyi create mode 100644 stubs/unidiff/unidiff/constants.pyi create mode 100644 stubs/unidiff/unidiff/errors.pyi create mode 100644 stubs/unidiff/unidiff/patch.pyi create mode 100644 stubs/untangle/METADATA.toml create mode 100644 stubs/untangle/untangle.pyi create mode 100644 stubs/usersettings/@tests/stubtest_allowlist.txt create mode 100644 stubs/usersettings/METADATA.toml create mode 100644 stubs/usersettings/usersettings.pyi create mode 100644 stubs/vobject/@tests/stubtest_allowlist.txt create mode 100644 stubs/vobject/METADATA.toml create mode 100644 stubs/vobject/vobject/__init__.pyi create mode 100644 stubs/vobject/vobject/base.pyi create mode 100644 stubs/vobject/vobject/behavior.pyi create mode 100644 stubs/vobject/vobject/change_tz.pyi create mode 100644 stubs/vobject/vobject/hcalendar.pyi create mode 100644 stubs/vobject/vobject/icalendar.pyi create mode 100644 stubs/vobject/vobject/ics_diff.pyi create mode 100644 stubs/vobject/vobject/vcard.pyi create mode 100644 stubs/vobject/vobject/win32tz.pyi create mode 100644 stubs/waitress/@tests/stubtest_allowlist.txt create mode 100644 stubs/waitress/METADATA.toml create mode 100644 stubs/waitress/waitress/__init__.pyi create mode 100644 stubs/waitress/waitress/adjustments.pyi create mode 100644 stubs/waitress/waitress/buffers.pyi create mode 100644 stubs/waitress/waitress/channel.pyi create mode 100644 stubs/waitress/waitress/compat.pyi create mode 100644 stubs/waitress/waitress/parser.pyi create mode 100644 stubs/waitress/waitress/proxy_headers.pyi create mode 100644 stubs/waitress/waitress/receiver.pyi create mode 100644 stubs/waitress/waitress/rfc7230.pyi create mode 100644 stubs/waitress/waitress/runner.pyi create mode 100644 stubs/waitress/waitress/server.pyi create mode 100644 stubs/waitress/waitress/task.pyi create mode 100644 stubs/waitress/waitress/trigger.pyi create mode 100644 stubs/waitress/waitress/utilities.pyi create mode 100644 stubs/waitress/waitress/wasyncore.pyi create mode 100644 stubs/watchpoints/@tests/stubtest_allowlist.txt create mode 100644 stubs/watchpoints/METADATA.toml create mode 100644 stubs/watchpoints/watchpoints/__init__.pyi create mode 100644 stubs/watchpoints/watchpoints/ast_monkey.pyi create mode 100644 stubs/watchpoints/watchpoints/util.pyi create mode 100644 stubs/watchpoints/watchpoints/watch.pyi create mode 100644 stubs/watchpoints/watchpoints/watch_element.pyi create mode 100644 stubs/watchpoints/watchpoints/watch_print.pyi create mode 100644 stubs/webencodings/@tests/stubtest_allowlist.txt create mode 100644 stubs/webencodings/METADATA.toml create mode 100644 stubs/webencodings/webencodings/__init__.pyi create mode 100644 stubs/webencodings/webencodings/labels.pyi create mode 100644 stubs/webencodings/webencodings/mklabels.pyi create mode 100644 stubs/webencodings/webencodings/x_user_defined.pyi create mode 100644 stubs/whatthepatch/METADATA.toml create mode 100644 stubs/whatthepatch/whatthepatch/__init__.pyi create mode 100644 stubs/whatthepatch/whatthepatch/apply.pyi create mode 100644 stubs/whatthepatch/whatthepatch/exceptions.pyi create mode 100644 stubs/whatthepatch/whatthepatch/patch.pyi create mode 100644 stubs/whatthepatch/whatthepatch/snippets.pyi create mode 100644 stubs/workalendar/@tests/stubtest_allowlist.txt create mode 100644 stubs/workalendar/METADATA.toml create mode 100644 stubs/workalendar/workalendar/__init__.pyi create mode 100644 stubs/workalendar/workalendar/africa/__init__.pyi create mode 100644 stubs/workalendar/workalendar/africa/algeria.pyi create mode 100644 stubs/workalendar/workalendar/africa/angola.pyi create mode 100644 stubs/workalendar/workalendar/africa/benin.pyi create mode 100644 stubs/workalendar/workalendar/africa/ivory_coast.pyi create mode 100644 stubs/workalendar/workalendar/africa/kenya.pyi create mode 100644 stubs/workalendar/workalendar/africa/madagascar.pyi create mode 100644 stubs/workalendar/workalendar/africa/mozambique.pyi create mode 100644 stubs/workalendar/workalendar/africa/nigeria.pyi create mode 100644 stubs/workalendar/workalendar/africa/sao_tome.pyi create mode 100644 stubs/workalendar/workalendar/africa/south_africa.pyi create mode 100644 stubs/workalendar/workalendar/africa/tunisia.pyi create mode 100644 stubs/workalendar/workalendar/america/__init__.pyi create mode 100644 stubs/workalendar/workalendar/america/argentina.pyi create mode 100644 stubs/workalendar/workalendar/america/barbados.pyi create mode 100644 stubs/workalendar/workalendar/america/brazil.pyi create mode 100644 stubs/workalendar/workalendar/america/canada.pyi create mode 100644 stubs/workalendar/workalendar/america/chile.pyi create mode 100644 stubs/workalendar/workalendar/america/colombia.pyi create mode 100644 stubs/workalendar/workalendar/america/el_salvador.pyi create mode 100644 stubs/workalendar/workalendar/america/mexico.pyi create mode 100644 stubs/workalendar/workalendar/america/panama.pyi create mode 100644 stubs/workalendar/workalendar/america/paraguay.pyi create mode 100644 stubs/workalendar/workalendar/asia/__init__.pyi create mode 100644 stubs/workalendar/workalendar/asia/china.pyi create mode 100644 stubs/workalendar/workalendar/asia/hong_kong.pyi create mode 100644 stubs/workalendar/workalendar/asia/israel.pyi create mode 100644 stubs/workalendar/workalendar/asia/japan.pyi create mode 100644 stubs/workalendar/workalendar/asia/kazakhstan.pyi create mode 100644 stubs/workalendar/workalendar/asia/malaysia.pyi create mode 100644 stubs/workalendar/workalendar/asia/philippines.pyi create mode 100644 stubs/workalendar/workalendar/asia/qatar.pyi create mode 100644 stubs/workalendar/workalendar/asia/singapore.pyi create mode 100644 stubs/workalendar/workalendar/asia/south_korea.pyi create mode 100644 stubs/workalendar/workalendar/asia/taiwan.pyi create mode 100644 stubs/workalendar/workalendar/astronomy.pyi create mode 100644 stubs/workalendar/workalendar/core.pyi create mode 100644 stubs/workalendar/workalendar/europe/__init__.pyi create mode 100644 stubs/workalendar/workalendar/europe/austria.pyi create mode 100644 stubs/workalendar/workalendar/europe/belarus.pyi create mode 100644 stubs/workalendar/workalendar/europe/belgium.pyi create mode 100644 stubs/workalendar/workalendar/europe/bulgaria.pyi create mode 100644 stubs/workalendar/workalendar/europe/cayman_islands.pyi create mode 100644 stubs/workalendar/workalendar/europe/croatia.pyi create mode 100644 stubs/workalendar/workalendar/europe/cyprus.pyi create mode 100644 stubs/workalendar/workalendar/europe/czech_republic.pyi create mode 100644 stubs/workalendar/workalendar/europe/denmark.pyi create mode 100644 stubs/workalendar/workalendar/europe/estonia.pyi create mode 100644 stubs/workalendar/workalendar/europe/european_central_bank.pyi create mode 100644 stubs/workalendar/workalendar/europe/finland.pyi create mode 100644 stubs/workalendar/workalendar/europe/france.pyi create mode 100644 stubs/workalendar/workalendar/europe/georgia.pyi create mode 100644 stubs/workalendar/workalendar/europe/germany.pyi create mode 100644 stubs/workalendar/workalendar/europe/greece.pyi create mode 100644 stubs/workalendar/workalendar/europe/guernsey.pyi create mode 100644 stubs/workalendar/workalendar/europe/hungary.pyi create mode 100644 stubs/workalendar/workalendar/europe/iceland.pyi create mode 100644 stubs/workalendar/workalendar/europe/ireland.pyi create mode 100644 stubs/workalendar/workalendar/europe/italy.pyi create mode 100644 stubs/workalendar/workalendar/europe/latvia.pyi create mode 100644 stubs/workalendar/workalendar/europe/lithuania.pyi create mode 100644 stubs/workalendar/workalendar/europe/luxembourg.pyi create mode 100644 stubs/workalendar/workalendar/europe/malta.pyi create mode 100644 stubs/workalendar/workalendar/europe/monaco.pyi create mode 100644 stubs/workalendar/workalendar/europe/netherlands.pyi create mode 100644 stubs/workalendar/workalendar/europe/norway.pyi create mode 100644 stubs/workalendar/workalendar/europe/poland.pyi create mode 100644 stubs/workalendar/workalendar/europe/portugal.pyi create mode 100644 stubs/workalendar/workalendar/europe/romania.pyi create mode 100644 stubs/workalendar/workalendar/europe/russia.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/__init__.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/mixins/__init__.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/mixins/autumn_holiday.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/mixins/fair_holiday.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/mixins/spring_holiday.pyi create mode 100644 stubs/workalendar/workalendar/europe/scotland/mixins/victoria_day.pyi create mode 100644 stubs/workalendar/workalendar/europe/serbia.pyi create mode 100644 stubs/workalendar/workalendar/europe/slovakia.pyi create mode 100644 stubs/workalendar/workalendar/europe/slovenia.pyi create mode 100644 stubs/workalendar/workalendar/europe/spain.pyi create mode 100644 stubs/workalendar/workalendar/europe/sweden.pyi create mode 100644 stubs/workalendar/workalendar/europe/switzerland.pyi create mode 100644 stubs/workalendar/workalendar/europe/turkey.pyi create mode 100644 stubs/workalendar/workalendar/europe/ukraine.pyi create mode 100644 stubs/workalendar/workalendar/europe/united_kingdom.pyi create mode 100644 stubs/workalendar/workalendar/exceptions.pyi create mode 100644 stubs/workalendar/workalendar/oceania/__init__.pyi create mode 100644 stubs/workalendar/workalendar/oceania/australia.pyi create mode 100644 stubs/workalendar/workalendar/oceania/marshall_islands.pyi create mode 100644 stubs/workalendar/workalendar/oceania/new_zealand.pyi create mode 100644 stubs/workalendar/workalendar/precomputed_astronomy.pyi create mode 100644 stubs/workalendar/workalendar/registry.pyi create mode 100644 stubs/workalendar/workalendar/registry_tools.pyi create mode 100644 stubs/workalendar/workalendar/skyfield_astronomy.pyi create mode 100644 stubs/workalendar/workalendar/usa/__init__.pyi create mode 100644 stubs/workalendar/workalendar/usa/alabama.pyi create mode 100644 stubs/workalendar/workalendar/usa/alaska.pyi create mode 100644 stubs/workalendar/workalendar/usa/american_samoa.pyi create mode 100644 stubs/workalendar/workalendar/usa/arizona.pyi create mode 100644 stubs/workalendar/workalendar/usa/arkansas.pyi create mode 100644 stubs/workalendar/workalendar/usa/california.pyi create mode 100644 stubs/workalendar/workalendar/usa/colorado.pyi create mode 100644 stubs/workalendar/workalendar/usa/connecticut.pyi create mode 100644 stubs/workalendar/workalendar/usa/core.pyi create mode 100644 stubs/workalendar/workalendar/usa/delaware.pyi create mode 100644 stubs/workalendar/workalendar/usa/district_columbia.pyi create mode 100644 stubs/workalendar/workalendar/usa/florida.pyi create mode 100644 stubs/workalendar/workalendar/usa/georgia.pyi create mode 100644 stubs/workalendar/workalendar/usa/guam.pyi create mode 100644 stubs/workalendar/workalendar/usa/hawaii.pyi create mode 100644 stubs/workalendar/workalendar/usa/idaho.pyi create mode 100644 stubs/workalendar/workalendar/usa/illinois.pyi create mode 100644 stubs/workalendar/workalendar/usa/indiana.pyi create mode 100644 stubs/workalendar/workalendar/usa/iowa.pyi create mode 100644 stubs/workalendar/workalendar/usa/kansas.pyi create mode 100644 stubs/workalendar/workalendar/usa/kentucky.pyi create mode 100644 stubs/workalendar/workalendar/usa/louisiana.pyi create mode 100644 stubs/workalendar/workalendar/usa/maine.pyi create mode 100644 stubs/workalendar/workalendar/usa/maryland.pyi create mode 100644 stubs/workalendar/workalendar/usa/massachusetts.pyi create mode 100644 stubs/workalendar/workalendar/usa/michigan.pyi create mode 100644 stubs/workalendar/workalendar/usa/minnesota.pyi create mode 100644 stubs/workalendar/workalendar/usa/mississippi.pyi create mode 100644 stubs/workalendar/workalendar/usa/missouri.pyi create mode 100644 stubs/workalendar/workalendar/usa/montana.pyi create mode 100644 stubs/workalendar/workalendar/usa/nebraska.pyi create mode 100644 stubs/workalendar/workalendar/usa/nevada.pyi create mode 100644 stubs/workalendar/workalendar/usa/new_hampshire.pyi create mode 100644 stubs/workalendar/workalendar/usa/new_jersey.pyi create mode 100644 stubs/workalendar/workalendar/usa/new_mexico.pyi create mode 100644 stubs/workalendar/workalendar/usa/new_york.pyi create mode 100644 stubs/workalendar/workalendar/usa/north_carolina.pyi create mode 100644 stubs/workalendar/workalendar/usa/north_dakota.pyi create mode 100644 stubs/workalendar/workalendar/usa/ohio.pyi create mode 100644 stubs/workalendar/workalendar/usa/oklahoma.pyi create mode 100644 stubs/workalendar/workalendar/usa/oregon.pyi create mode 100644 stubs/workalendar/workalendar/usa/pennsylvania.pyi create mode 100644 stubs/workalendar/workalendar/usa/rhode_island.pyi create mode 100644 stubs/workalendar/workalendar/usa/south_carolina.pyi create mode 100644 stubs/workalendar/workalendar/usa/south_dakota.pyi create mode 100644 stubs/workalendar/workalendar/usa/tennessee.pyi create mode 100644 stubs/workalendar/workalendar/usa/texas.pyi create mode 100644 stubs/workalendar/workalendar/usa/utah.pyi create mode 100644 stubs/workalendar/workalendar/usa/vermont.pyi create mode 100644 stubs/workalendar/workalendar/usa/virginia.pyi create mode 100644 stubs/workalendar/workalendar/usa/washington.pyi create mode 100644 stubs/workalendar/workalendar/usa/west_virginia.pyi create mode 100644 stubs/workalendar/workalendar/usa/wisconsin.pyi create mode 100644 stubs/workalendar/workalendar/usa/wyoming.pyi create mode 100644 stubs/wurlitzer/METADATA.toml create mode 100644 stubs/wurlitzer/wurlitzer.pyi create mode 100644 stubs/www-authenticate/METADATA.toml create mode 100644 stubs/www-authenticate/www_authenticate.pyi create mode 100644 stubs/xdgenvpy/@tests/stubtest_allowlist.txt create mode 100644 stubs/xdgenvpy/METADATA.toml create mode 100644 stubs/xdgenvpy/xdgenvpy/__init__.pyi create mode 100644 stubs/xdgenvpy/xdgenvpy/_defaults.pyi create mode 100644 stubs/xdgenvpy/xdgenvpy/xdgenv.pyi create mode 100644 stubs/xlrd/METADATA.toml create mode 100644 stubs/xlrd/xlrd/__init__.pyi create mode 100644 stubs/xlrd/xlrd/biffh.pyi create mode 100644 stubs/xlrd/xlrd/book.pyi create mode 100644 stubs/xlrd/xlrd/compdoc.pyi create mode 100644 stubs/xlrd/xlrd/formatting.pyi create mode 100644 stubs/xlrd/xlrd/formula.pyi create mode 100644 stubs/xlrd/xlrd/info.pyi create mode 100644 stubs/xlrd/xlrd/sheet.pyi create mode 100644 stubs/xlrd/xlrd/timemachine.pyi create mode 100644 stubs/xlrd/xlrd/xldate.pyi create mode 100644 stubs/xmldiff/METADATA.toml create mode 100644 stubs/xmldiff/xmldiff/__init__.pyi create mode 100644 stubs/xmldiff/xmldiff/actions.pyi create mode 100644 stubs/xmldiff/xmldiff/diff.pyi create mode 100644 stubs/xmldiff/xmldiff/diff_match_patch.pyi create mode 100644 stubs/xmldiff/xmldiff/formatting.pyi create mode 100644 stubs/xmldiff/xmldiff/main.pyi create mode 100644 stubs/xmldiff/xmldiff/patch.pyi create mode 100644 stubs/xmldiff/xmldiff/utils.pyi create mode 100644 stubs/xmltodict/@tests/test_cases/check_namespaces.py create mode 100644 stubs/xmltodict/METADATA.toml create mode 100644 stubs/xmltodict/xmltodict.pyi create mode 100644 stubs/yt-dlp/@tests/stubtest_allowlist.txt create mode 100644 stubs/yt-dlp/METADATA.toml create mode 100644 stubs/yt-dlp/yt_dlp/YoutubeDL.pyi create mode 100644 stubs/yt-dlp/yt_dlp/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/aes.pyi create mode 100644 stubs/yt-dlp/yt_dlp/cache.pyi create mode 100644 stubs/yt-dlp/yt_dlp/compat/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/compat/compat_utils.pyi create mode 100644 stubs/yt-dlp/yt_dlp/compat/imghdr.pyi create mode 100644 stubs/yt-dlp/yt_dlp/cookies.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/bunnycdn.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/common.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/dash.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/external.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/f4m.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/fc2.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/fragment.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/hls.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/http.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/ism.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/mhtml.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/niconico.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/rtmp.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/soop.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/websocket.pyi create mode 100644 stubs/yt-dlp/yt_dlp/downloader/youtube_live_chat.pyi create mode 100644 stubs/yt-dlp/yt_dlp/extractor/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/extractor/common.pyi create mode 100644 stubs/yt-dlp/yt_dlp/extractor/commonmistakes.pyi create mode 100644 stubs/yt-dlp/yt_dlp/extractor/commonprotocols.pyi create mode 100644 stubs/yt-dlp/yt_dlp/globals.pyi create mode 100644 stubs/yt-dlp/yt_dlp/jsinterp.pyi create mode 100644 stubs/yt-dlp/yt_dlp/minicurses.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/_helper.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/common.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/exceptions.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/impersonate.pyi create mode 100644 stubs/yt-dlp/yt_dlp/networking/websocket.pyi create mode 100644 stubs/yt-dlp/yt_dlp/options.pyi create mode 100644 stubs/yt-dlp/yt_dlp/plugins.pyi create mode 100644 stubs/yt-dlp/yt_dlp/postprocessor/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/postprocessor/common.pyi create mode 100644 stubs/yt-dlp/yt_dlp/socks.pyi create mode 100644 stubs/yt-dlp/yt_dlp/update.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/_jsruntime.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/_legacy.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/_utils.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/jslib/__init__.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/jslib/devalue.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/networking.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/progress.pyi create mode 100644 stubs/yt-dlp/yt_dlp/utils/traversal.pyi create mode 100644 stubs/yt-dlp/yt_dlp/version.pyi create mode 100644 stubs/yt-dlp/yt_dlp/webvtt.pyi create mode 100644 stubs/zstd/METADATA.toml create mode 100644 stubs/zstd/zstd.pyi create mode 100644 stubs/zxcvbn/@tests/stubtest_allowlist.txt create mode 100644 stubs/zxcvbn/METADATA.toml create mode 100644 stubs/zxcvbn/zxcvbn/__init__.pyi create mode 100644 stubs/zxcvbn/zxcvbn/adjacency_graphs.pyi create mode 100644 stubs/zxcvbn/zxcvbn/feedback.pyi create mode 100644 stubs/zxcvbn/zxcvbn/frequency_lists.pyi create mode 100644 stubs/zxcvbn/zxcvbn/matching.pyi create mode 100644 stubs/zxcvbn/zxcvbn/scoring.pyi create mode 100644 stubs/zxcvbn/zxcvbn/time_estimates.pyi create mode 100644 tests/README.md create mode 100644 tests/REGRESSION.md create mode 100755 tests/check_typeshed_structure.py create mode 100755 tests/get_external_stub_requirements.py create mode 100755 tests/get_stubtest_system_requirements.py create mode 100755 tests/mypy_test.py create mode 100755 tests/pyrefly_test.py create mode 100644 tests/pyright_exclude_list.txt create mode 100755 tests/pyright_test.py create mode 100755 tests/regr_test.py create mode 100755 tests/runtests.py create mode 100755 tests/stubtest_stdlib.py create mode 100755 tests/stubtest_third_party.py create mode 100755 tests/ty_test.py create mode 100755 tests/typecheck_typeshed.py create mode 100644 ty.toml diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000000..96dc1b77a55d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +end_of_line = lf +indent_size = 2 + +[*.md] +max_line_length = 79 +trim_trailing_whitespace = false + +[*.{py,pyi,toml,json}] +max_line_length = 130 +indent_size = 4 diff --git a/.flake8 b/.flake8 new file mode 100644 index 000000000000..e45a7f11787b --- /dev/null +++ b/.flake8 @@ -0,0 +1,16 @@ +[flake8] +# Y: Flake8 is only used to run flake8-pyi, everything else is in Ruff +select = Y +# Ignore rules normally excluded by default +# Also ignore Y041 (redundant (complex |) float | int), see +# https://github.com/python/typeshed/issues/16059 +extend-ignore = Y041,Y090,Y091 +per-file-ignores = + # Generated protobuf files: + # Y021: Include docstrings + # Y023: Alias typing as typing_extensions + # Y026: Have implicit type aliases + # Y053: have literals >50 characters long + stubs/*_pb2.pyi: Y021, Y023, Y026, Y053 + +exclude = .venv*,.git diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000000..19c9bb2b07f7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,8 @@ +# Normalize EOF +* autocrlf=false +* eol=lf +# Set linguist-language to support comments syntax highlight +**/stubtest_allowlist*.txt linguist-language=ini +**/stubtest_allowlists/*.txt linguist-language=ini +pyrightconfig*.json linguist-language=jsonc +.vscode/*.json linguist-language=jsonc diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 000000000000..4fcaa043d3cb --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,40 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "dependencyDashboard": true, + "suppressNotifications": ["prEditedNotification"], + "extends": ["config:recommended"], + "labels": ["bot: dependencies"], + "rebaseLabel": ["bot: rebase"], + "semanticCommits": "disabled", + "separateMajorMinor": false, + "prHourlyLimit": 10, + // This package rule disables updates for `actions/setup-python` Python versions: + // it's better to do these manually as there's often a reason why we can't use + // the latest Python version in CI for a specific job + ignoreDeps: ["python"], + "pre-commit": { + "enabled": true + }, + "packageRules": [ + { + groupName: "GitHub Actions", + matchManagers: ["github-actions"], + description: "Quarterly update of GitHub Action dependencies", + schedule: ["every 3 months on the first day of the month"] + }, + { + groupName: "most test/lint dependencies", + matchManagers: ["pip_requirements", "pre-commit"], + matchPackageNames: ["!pyright"], + description: "Quarterly update of most test dependencies", + schedule: ["every 3 months on the first day of the month"] + }, + { + "groupName": "pyright", + "matchManagers": ["pip_requirements"], + "matchPackageNames": ["pyright"], + "description": "Daily update of pyright", + "schedule": ["before 4am"] + } + ] +} diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml new file mode 100644 index 000000000000..884303937f60 --- /dev/null +++ b/.github/workflows/daily.yml @@ -0,0 +1,154 @@ +name: Daily test + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + pull_request: + paths: + - "requirements-tests.txt" + - ".github/workflows/daily.yml" + +# Please keep the permissions minimal, as stubtest runs arbitrary code from pypi. +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +env: + # A few env vars to speedup brew install + HOMEBREW_NO_ANALYTICS: 1 + HOMEBREW_NO_AUTOUPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 # Environments are isolated, no need to cleanup old versions + NONINTERACTIVE: 1 # Required for brew install on CI + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +jobs: + stubtest-stdlib: + name: "stubtest: stdlib" + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + exclude: + # https://github.com/python/typeshed/issues/15694 + - os: "windows-latest" + python-version: "3.10" + fail-fast: false + + steps: + - uses: actions/checkout@v7 + - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: requirements-tests.txt + allow-prereleases: true + check-latest: true + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Run stubtest + run: python tests/stubtest_stdlib.py + + stubtest-third-party: + name: "stubtest: third party" + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + shard-index: [0, 1, 2, 3] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: | + requirements-tests.txt + stubs/**/METADATA.toml + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Install required system packages + shell: bash + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + + if [ "${{ runner.os }}" = "Linux" ]; then + if [ -n "$PACKAGES" ]; then + printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + else + if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then + printf "Installing Homebrew packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + brew install -q $PACKAGES + fi + + if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then + printf "Installing Chocolatey packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + choco install -y $PACKAGES + fi + fi + - name: Run stubtest + shell: bash + run: | + if [ "${{ runner.os }}" = "Linux" ]; then + PYTHON_EXECUTABLE="xvfb-run python" + else + PYTHON_EXECUTABLE="python" + fi + + $PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only --num-shards 4 --shard-index ${{ matrix.shard-index }} + + stub-uploader: + name: stub_uploader tests + if: ${{ github.repository == 'python/typeshed' || github.event_name != 'schedule' }} + runs-on: ubuntu-latest + steps: + - name: Checkout typeshed + uses: actions/checkout@v7 + with: + path: typeshed + - name: Checkout stub_uploader + uses: actions/checkout@v7 + with: + repository: typeshed-internal/stub_uploader + path: stub_uploader + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "typeshed/requirements-tests.txt" + - name: Run tests + run: | + cd stub_uploader + # Keep Python version in sync with stub_uploader's check_scripts.yml workflow. + uv run --python=3.13 --no-project --with-requirements=requirements.txt -m pytest tests + + # https://github.community/t/run-github-actions-job-only-if-previous-job-has-failed/174786/2 + create-issue-on-failure: + name: Create issue on failure + runs-on: ubuntu-latest + needs: [stubtest-stdlib, stubtest-third-party, stub-uploader] + if: ${{ github.repository == 'python/typeshed' && always() && github.event_name == 'schedule' && (needs.stubtest-stdlib.result == 'failure' || needs.stubtest-third-party.result == 'failure' || needs.stub-uploader.result == 'failure') }} + permissions: + issues: write + steps: + - uses: actions/github-script@v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.create({ + owner: "python", + repo: "typeshed", + title: `Daily tests failed on ${new Date().toDateString()}`, + body: "Run listed here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}", + labels: ["help wanted"], + }) diff --git a/.github/workflows/meta_tests.yml b/.github/workflows/meta_tests.yml new file mode 100644 index 000000000000..6c6775572834 --- /dev/null +++ b/.github/workflows/meta_tests.yml @@ -0,0 +1,92 @@ +# This workflow is for testing typeshed's scripts and tests themselves +name: Meta-tests + +on: + workflow_dispatch: + push: + branches: + - main + pull_request: + paths: + - "scripts/**" + - "tests/**" + - "lib/**" + - ".github/workflows/meta_tests.yml" + - "requirements-tests.txt" + - "pyproject.toml" + +permissions: + contents: read + +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + mypy: + name: Check scripts and tests with mypy + runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/typecheck_typeshed.py \ + --platform=${{ matrix.platform }} + + pyright: + name: Check scripts and tests with pyright + runs-on: ubuntu-latest + strategy: + matrix: + python-platform: ["Linux", "Windows"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - run: uv pip install -r requirements-tests.txt --system + - name: Run pyright on typeshed + uses: jakebailey/pyright-action@v3 + with: + version: PATH + python-platform: ${{ matrix.python-platform }} + python-version: "3.10" # Oldest version supported for running scripts and tests + project: ./pyrightconfig.scripts_and_tests.json + + stubsabot-dry-run: + name: Stubsabot dry run + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - name: Git config + run: | + git config --global user.name stubsabot + git config --global user.email '<>' + - run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + scripts/stubsabot.py \ + --action-level=local diff --git a/.github/workflows/mypy_primer.yml b/.github/workflows/mypy_primer.yml new file mode 100644 index 000000000000..729b3a8237dd --- /dev/null +++ b/.github/workflows/mypy_primer.yml @@ -0,0 +1,91 @@ +name: Run mypy_primer + +on: + # Only run on PR, since we diff against main + pull_request: + paths: + - "stdlib/**" + - "stubs/**/*.pyi" + - ".github/workflows/mypy_primer.yml" + - ".github/workflows/mypy_primer_comment.yml" + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + mypy_primer: + name: Run + runs-on: ubuntu-latest + strategy: + matrix: + shard-index: [0, 1, 2, 3, 4, 5] + fail-fast: false + steps: + - uses: actions/checkout@v7 + with: + path: typeshed_to_test + fetch-depth: 0 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + - name: Install dependencies + run: pip install git+https://github.com/hauntsaninja/mypy_primer.git + - name: Run mypy_primer + shell: bash + run: | + cd typeshed_to_test + MYPY_VERSION=$(grep mypy== requirements-tests.txt | cut -d = -f 3) + echo "new commit" + git rev-list --format=%s --max-count=1 $GITHUB_SHA + git checkout -b upstream_main origin/main + echo "base commit" + git rev-list --format=%s --max-count=1 upstream_main + echo '' + cd .. + # fail action if exit code isn't zero or one + ( + mypy_primer \ + --new v${MYPY_VERSION} --old v${MYPY_VERSION} \ + --custom-typeshed-repo typeshed_to_test \ + --new-typeshed $GITHUB_SHA --old-typeshed upstream_main \ + --num-shards 6 --shard-index ${{ matrix.shard-index }} \ + --debug \ + --output concise \ + | tee diff_${{ matrix.shard-index }}.txt + ) || [ $? -eq 1 ] + - if: ${{ matrix.shard-index == 0 }} + name: Save PR number + run: | + echo ${{ github.event.pull_request.number }} | tee pr_number.txt + - name: Upload mypy_primer diff + PR number + uses: actions/upload-artifact@v7 + if: ${{ matrix.shard-index == 0 }} + with: + name: mypy_primer_diffs-${{ matrix.shard-index }} + path: | + diff_${{ matrix.shard-index }}.txt + pr_number.txt + - name: Upload mypy_primer diff + uses: actions/upload-artifact@v7 + if: ${{ matrix.shard-index != 0 }} + with: + name: mypy_primer_diffs-${{ matrix.shard-index }} + path: diff_${{ matrix.shard-index }}.txt + + join_artifacts: + name: Join artifacts + runs-on: ubuntu-latest + needs: [mypy_primer] + permissions: + contents: read + steps: + - name: Merge artifacts + uses: actions/upload-artifact/merge@v7 + with: + name: mypy_primer_diffs + pattern: mypy_primer_diffs-* + delete-merged: true diff --git a/.github/workflows/mypy_primer_comment.yml b/.github/workflows/mypy_primer_comment.yml new file mode 100644 index 000000000000..1096653ed4e8 --- /dev/null +++ b/.github/workflows/mypy_primer_comment.yml @@ -0,0 +1,87 @@ +name: Comment with mypy_primer diff + +on: + workflow_run: + workflows: + - Run mypy_primer + types: + - completed + +permissions: + contents: read + pull-requests: write + +jobs: + comment: + name: Comment PR from mypy_primer + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + steps: + - name: Download diffs + uses: actions/github-script@v9 + with: + script: | + const fs = require('fs'); + const artifacts = await github.rest.actions.listWorkflowRunArtifacts({ + owner: context.repo.owner, + repo: context.repo.repo, + run_id: ${{ github.event.workflow_run.id }}, + }); + const [matchArtifact] = artifacts.data.artifacts.filter((artifact) => + artifact.name == "mypy_primer_diffs"); + + const download = await github.rest.actions.downloadArtifact({ + owner: context.repo.owner, + repo: context.repo.repo, + artifact_id: matchArtifact.id, + archive_format: "zip", + }); + fs.writeFileSync("diff.zip", Buffer.from(download.data)); + + - run: unzip diff.zip + - run: | + cat diff_*.txt | tee fulldiff.txt + + - name: Post comment + id: post-comment + uses: actions/github-script@v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const fs = require('fs') + let data = fs.readFileSync('fulldiff.txt', { encoding: 'utf8' }) + + // Maximum comment length is 65536 characters. We need much less than 236 for extra text. + const MAX_LENGTH = 65300 + if (data.length > MAX_LENGTH) { + let truncated_data = data.substring(0, MAX_LENGTH) + let lines_truncated = data.split('\n').length - truncated_data.split('\n').length + data = truncated_data + `\n\n... (truncated ${lines_truncated} lines) ...\n` + } + + console.log("Diff from mypy_primer:") + console.log(data) + + let body + if (data.trim()) { + body = 'Diff from [mypy_primer](https://github.com/hauntsaninja/mypy_primer), showing the effect of this PR on open source code:\n```diff\n' + data + '```' + } else { + body = 'According to [mypy_primer](https://github.com/hauntsaninja/mypy_primer), this change has no effect on the checked open source code. 🤖🎉' + } + + const prNumber = parseInt(fs.readFileSync("pr_number.txt", { encoding: "utf8" })) + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body + }) + return prNumber + + - name: Hide old comments + # v0.4.0 + uses: kanga333/comment-hider@c12bb20b48aeb8fc098e35967de8d4f8018fffdf + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + leave_visible: 1 + issue_number: ${{ steps.post-comment.outputs.result }} diff --git a/.github/workflows/stubsabot.yml b/.github/workflows/stubsabot.yml new file mode 100644 index 000000000000..d42ede654545 --- /dev/null +++ b/.github/workflows/stubsabot.yml @@ -0,0 +1,60 @@ +name: Run stubsabot daily + +on: + workflow_dispatch: + schedule: + - cron: "0 0 * * *" + +permissions: + contents: write + issues: write + pull-requests: write + +env: + FORCE_COLOR: 1 + +jobs: + stubsabot: + name: Upgrade stubs with stubsabot + if: github.repository == 'python/typeshed' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + # use an ssh key so that checks automatically run on stubsabot PRs + ssh-key: ${{ secrets.STUBSABOT_SSH_PRIVATE_KEY }} + fetch-depth: 0 + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - name: git config + run: | + git config --global user.name stubsabot + git config --global user.email '<>' + - name: Run stubsabot + run: | + GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} \ + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + scripts/stubsabot.py \ + --action-level=everything + + # https://github.community/t/run-github-actions-job-only-if-previous-job-has-failed/174786/2 + create-issue-on-failure: + name: Create issue on failure + runs-on: ubuntu-latest + needs: [stubsabot] + if: ${{ github.repository == 'python/typeshed' && always() && (needs.stubsabot.result == 'failure') }} + steps: + - uses: actions/github-script@v9 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + await github.rest.issues.create({ + owner: "python", + repo: "typeshed", + title: `Stubsabot failed on ${new Date().toDateString()}`, + body: "Stubsabot run is listed here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}", + }) diff --git a/.github/workflows/stubtest_stdlib.yml b/.github/workflows/stubtest_stdlib.yml new file mode 100644 index 000000000000..c384324e3d6a --- /dev/null +++ b/.github/workflows/stubtest_stdlib.yml @@ -0,0 +1,54 @@ +name: Stdlib stubtest + +on: + workflow_dispatch: + push: + branches: + - main + pull_request: + paths: + - "stdlib/**" + - ".github/workflows/stubtest_stdlib.yml" + - "tests/**" + # When requirements.txt changes, we run `daily.yml`, which includes stdlib stubtest + +permissions: + contents: read + +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + stubtest-stdlib: + name: "stubtest: stdlib" + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + exclude: + # https://github.com/python/typeshed/issues/15694 + - os: "windows-latest" + python-version: "3.10" + fail-fast: false + + steps: + - uses: actions/checkout@v7 + - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: requirements-tests.txt + allow-prereleases: true + check-latest: true + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Run stubtest + run: python tests/stubtest_stdlib.py diff --git a/.github/workflows/stubtest_third_party.yml b/.github/workflows/stubtest_third_party.yml new file mode 100644 index 000000000000..e3ba59e7006e --- /dev/null +++ b/.github/workflows/stubtest_third_party.yml @@ -0,0 +1,101 @@ +name: Third-party stubtest + +on: + pull_request: + paths: + - "stubs/**" + - ".github/workflows/stubtest_third_party.yml" + - "tests/**" + # When requirements.txt changes, we run `daily.yml`, which includes third-party stubtest + +permissions: + contents: read + +env: + # A few env vars to speedup brew install + HOMEBREW_NO_ANALYTICS: 1 + HOMEBREW_NO_AUTOUPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 # Environments are isolated, no need to cleanup old versions + NONINTERACTIVE: 1 # Required for brew install on CI + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + stubtest-third-party: + name: "stubtest: third party" + + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest", "windows-latest", "macos-latest"] + fail-fast: false + + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + cache: pip + cache-dependency-path: | + requirements-tests.txt + stubs/**/METADATA.toml + - name: Install dependencies + run: pip install -r requirements-tests.txt + - name: Determine changed stubs + shell: bash + run: | + # This only runs stubtest on changed stubs, because it is much faster. + # Use the daily.yml workflow to run stubtest on all third party stubs. + function find_stubs { + git diff --name-only origin/${{ github.base_ref }} HEAD | \ + egrep ^stubs/ | cut -d "/" -f 2 | sort -u | \ + (while read stub; do [ -d "stubs/$stub" ] && echo -n "$stub " || true; done) + } + STUBS=$(find_stubs || echo '') + echo "Changed stubs: $STUBS" + echo "STUBS=$STUBS" >> $GITHUB_ENV + - name: Install required system packages + shell: bash + run: | + if [ -n "$STUBS" ]; then + PACKAGES=$(python tests/get_stubtest_system_requirements.py $STUBS) + if [ "${{ runner.os }}" = "Linux" ]; then + if [ -n "$PACKAGES" ]; then + printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + else + if [ "${{ runner.os }}" = "macOS" ] && [ -n "$PACKAGES" ]; then + printf "Installing Homebrew packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + brew install -q $PACKAGES + fi + + if [ "${{ runner.os }}" = "Windows" ] && [ -n "$PACKAGES" ]; then + printf "Installing Chocolatey packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + choco install -y $PACKAGES + fi + fi + fi + - name: Run stubtest + shell: bash + run: | + if [ -n "$STUBS" ]; then + echo "Testing $STUBS..." + + if [ "${{ runner.os }}" = "Linux" ]; then + PYTHON_EXECUTABLE="xvfb-run python" + else + PYTHON_EXECUTABLE="python" + fi + + $PYTHON_EXECUTABLE tests/stubtest_third_party.py --ci-platforms-only $STUBS + else + echo "Nothing to test" + fi diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 000000000000..af66891790f6 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,235 @@ +name: Test + +on: + workflow_dispatch: + push: + branches: + - main + pull_request: + paths-ignore: + - "**/*.md" + - "scripts/**" + +permissions: + contents: read + +env: + PIP_DISABLE_PIP_VERSION_CHECK: 1 + FORCE_COLOR: 1 + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + typeshed-structure: + name: Check typeshed structure + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - run: | + uv run \ + --python=3.13 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/check_typeshed_structure.py + + mypy: + name: "mypy: Check stubs" + runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32", "darwin"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - run: uv pip install -r requirements-tests.txt --system + - name: Install required APT packages + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + if [ -n "$PACKAGES" ]; then + printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + - name: Run mypy_test.py + run: python ./tests/mypy_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} + + regression-tests: + name: "mypy: Run test cases" + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - run: | + uv run \ + --python=3.14 \ + --no-project \ + --with-requirements=requirements-tests.txt \ + ./tests/regr_test.py \ + --all \ + --verbosity=QUIET + + ty: + name: "ty: Check stubs" + runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32", "darwin"] + # TODO: Add 3.15 once third-party runtime dependencies provide compatible wheels. + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.14" + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + run: uv pip install -r requirements-tests.txt --system + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install third-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + uv pip install --python-version ${{ matrix.python-version }} $PACKAGES + fi + # Published stub packages can shadow the checked-in stubs when ty + # resolves their relative imports. + uv pip uninstall types-PyYAML types-pytz + - name: Run ty on all stubs + run: python tests/ty_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} --python=.venv + + pyrefly: + name: "pyrefly: Check stubs" + runs-on: ubuntu-latest + strategy: + matrix: + platform: ["linux", "win32", "darwin"] + # TODO: Add 3.15 once third-party runtime dependencies provide compatible wheels. + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.14" + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + run: uv pip install -r requirements-tests.txt --system + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install third-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + uv pip install --python-version ${{ matrix.python-version }} $PACKAGES + fi + # Published stub packages can shadow the checked-in stubs when pyrefly + # resolves their relative imports. + uv pip uninstall types-PyYAML types-pytz + - name: Run pyrefly on all stubs + run: python tests/pyrefly_test.py --platform=${{ matrix.platform }} --python-version=${{ matrix.python-version }} --python=.venv/bin/python + + pyright: + name: "pyright: Run test cases" + runs-on: ubuntu-latest + strategy: + matrix: + # TODO: Add 3.15 once pyright CI can avoid installing third-party + # runtime dependency stacks that do not support Python 3.15 yet. + python-platform: ["Linux", "Windows", "Darwin"] + python-version: ["3.11", "3.12", "3.13", "3.14"] + fail-fast: false + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "requirements-tests.txt" + - name: Install typeshed test-suite requirements + # Install these so we can run `get_*_requirements.py` + run: uv pip install -r requirements-tests.txt --system + - name: Install required APT packages + run: | + PACKAGES=$(python tests/get_stubtest_system_requirements.py) + if [ -n "$PACKAGES" ]; then + printf "Installing APT packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + sudo apt-get update -q && sudo apt-get install -qy $PACKAGES + fi + - name: Create an isolated venv for testing + run: uv venv .venv + - name: Install 3rd-party stub dependencies + run: | + PACKAGES=$(python tests/get_external_stub_requirements.py) + if [ -n "$PACKAGES" ]; then + printf "Installing python packages:\n $(echo $PACKAGES | sed 's/ /\n /g')\n" + uv pip install --python-version ${{ matrix.python-version }} $PACKAGES + fi + - name: Activate the isolated venv for the rest of the job + run: echo "$PWD/.venv/bin" >> $GITHUB_PATH + - name: List 3rd-party stub dependencies installed + run: uv pip freeze + - name: Run pyright with basic settings on all the stubs + uses: jakebailey/pyright-action@v3 + with: + version: PATH + python-platform: ${{ matrix.python-platform }} + python-version: ${{ matrix.python-version }} + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + - name: Run pyright with stricter settings on some of the stubs + uses: jakebailey/pyright-action@v3 + with: + version: PATH + python-platform: ${{ matrix.python-platform }} + python-version: ${{ matrix.python-version }} + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + project: ./pyrightconfig.stricter.json + - name: Run pyright on the test cases + uses: jakebailey/pyright-action@v3 + with: + version: PATH + python-platform: ${{ matrix.python-platform }} + python-version: ${{ matrix.python-version }} + annotate: ${{ matrix.python-version == '3.13' && matrix.python-platform == 'Linux' }} # Having each job create the same comment is too noisy. + project: ./pyrightconfig.testcases.json + + stub-uploader: + name: stub_uploader tests + runs-on: ubuntu-latest + steps: + - name: Checkout typeshed + uses: actions/checkout@v7 + with: + path: typeshed + - name: Checkout stub_uploader + uses: actions/checkout@v7 + with: + repository: typeshed-internal/stub_uploader + path: stub_uploader + - uses: astral-sh/setup-uv@v8.2.0 + with: + version-file: "typeshed/requirements-tests.txt" + - name: Run tests + run: | + cd stub_uploader + uv run --python=3.13 --no-project --with-requirements=requirements.txt -m pytest tests diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000000..edd0a9568bc0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,77 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] + +# C extensions +*.so + +# Distribution / packaging +.Python +/env/ +/lib/build/ +/develop-eggs/ +/dist/ +/downloads/ +/eggs/ +/lib64/ +/parts/ +/sdist/ +/var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.cache +nosetests.xml +coverage.xml +stubtest-output* + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Local utility scripts +analyze.py + +# Editor backup files +*~ +.*.sw? +.vscode/* +!.vscode/settings.default.json +!.vscode/extensions.json +.idea/ +.venv*/ + +# Mypy cache +.mypy_cache/ + +# pyenv and uv local python version +.python-version +# we don't use uv's lock as we're not actually a project +uv.lock + +# deliberately local test configuration files +stdlib/@tests/stubtest_allowlists/*.local diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000000..da1708ab17ee --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,51 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-toml + - id: check-merge-conflict + - id: mixed-line-ending + args: [--fix=lf] + - id: check-case-conflict + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.15.20 # must match requirements-tests.txt + hooks: + - id: ruff + name: Run ruff on stubs, tests and scripts + args: ["--exit-non-zero-on-fix"] + - id: ruff + # Very few rules are useful to run on our test cases; + # we explicitly enumerate them here: + name: Run ruff on the test cases + args: + - "--exit-non-zero-on-fix" + - "--select=FA,I,ICN001,RUF100" + - "--no-force-exclude" + - "--unsafe-fixes" + files: '.*test_cases/.+\.py$' + - repo: https://github.com/psf/black-pre-commit-mirror + rev: 26.5.1 + hooks: + - id: black + - repo: https://github.com/pycqa/flake8 + rev: 7.3.0 + hooks: + - id: flake8 + language: python + additional_dependencies: + - "flake8-pyi==26.5.0" + types: [file] + types_or: [python, pyi] + - repo: meta + hooks: + - id: check-hooks-apply + +ci: + autofix_commit_msg: "[pre-commit.ci] auto fixes from pre-commit.com hooks" + autofix_prs: true + autoupdate_commit_msg: "[pre-commit.ci] pre-commit autoupdate" + autoupdate_schedule: quarterly + submodules: false diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000000..01b9ad4369db --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,41 @@ +// ⚠ Disclaimer: The typeshed team doesn't commit to maintaining this file. It exists purely for your ease of use. +// Keep in alphabetical order +{ + "recommendations": [ + "bierner.github-markdown-preview", + "charliermarsh.ruff", + "editorconfig.editorconfig", + "ms-python.black-formatter", + "ms-python.flake8", + "ms-python.mypy-type-checker", + "ms-python.python", + "ms-python.vscode-pylance", + "tamasfe.even-better-toml", + "redhat.vscode-yaml", + ], + "unwantedRecommendations": [ + /* + * Don't recommend by default for this workspace + */ + "christian-kohler.npm-intellisense", + /* + * Must disable in this workspace + * https://github.com/microsoft/vscode/issues/40239 + */ + // even-better-toml has format on save + "bungcip.better-toml", + // Don't use two mypy extensions simultaneously + "matangover.mypy", + // Use Ruff instead + "ms-python.isort", + // We use Black + "ms-python.autopep8", + // Not using pylint + "ms-python.pylint", + // VSCode has implemented an optimized version + "coenraads.bracket-pair-colorizer", + "coenraads.bracket-pair-colorizer-2", + // Obsoleted by Pylance + "ms-pyright.pyright", + ], +} diff --git a/.vscode/settings.default.json b/.vscode/settings.default.json new file mode 100644 index 000000000000..b7005630a4e3 --- /dev/null +++ b/.vscode/settings.default.json @@ -0,0 +1,125 @@ +/* + * Copy this file as `.vscode/settings.json` to configure VSCode for this workspace. + * Unfortunately, VSCode doesn't (yet) offer any way to have "workspace defaults" or "user-worspace settings", + * so offering defaults to copy is the best we can do at the moment. + * + * ⚠ Disclaimer: The typeshed team doesn't commit to maintaining this file. It exists purely for your ease of use. +*/ +{ + // Don't format on save for formatters we don't explicitely control + "editor.formatOnSave": false, + "editor.codeActionsOnSave": { + "source.fixAll": "never" + }, + // Set file associations to support comments syntax highlight + "files.associations": { + "settings.default.json": "jsonc", + "pyrightconfig*.json": "jsonc", + ".flake8": "properties", + "stubtest_allowlist*.txt": "properties", + "**/stubtest_allowlists/*.txt": "properties", + "pytype_exclude_list.txt": "properties" + }, + "files.exclude": { + "**/.*_cache": true, // mypy and Ruff cache + "**/__pycache__": true + }, + "files.eol": "\n", + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "files.trimTrailingWhitespace": true, + "editor.comments.insertSpace": true, + "editor.insertSpaces": true, + "editor.detectIndentation": false, + "editor.tabSize": 2, + "[json][jsonc][python][toml]": { + "editor.tabSize": 4 + }, + "editor.rulers": [ + 90, + 130 + ], + "[git-commit]": { + "editor.rulers": [ + 72 + ] + }, + // Format on save for formatters we explicitely control + "[json][jsonc][yaml][python][toml]": { + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit" + } + }, + "[json][jsonc]": { + "editor.defaultFormatter": "vscode.json-language-features" + }, + "[yaml]": { + "editor.defaultFormatter": "redhat.vscode-yaml" + }, + "[toml]": { + "editor.rulers": [ + 90 + ], + "editor.defaultFormatter": "tamasfe.even-better-toml" + }, + "[python]": { + "editor.rulers": [ + 130 + ], + "editor.defaultFormatter": "ms-python.black-formatter", + "editor.codeActionsOnSave": { + // Let Ruff lint fixes handle imports + "source.organizeImports": "never", + "source.unusedImports": "never" + } + }, + // python.analysis is Pylance (pyright) configurations + "python.analysis.fixAll": [ + // Explicitly omiting "source.convertImportFormat", some stubs use relative imports + // Explicitly omiting "source.unusedImports", Let Ruff lint fixes handle imports + ], + "python.analysis.typeshedPaths": [ + "${workspaceFolder}" + ], + "python.analysis.extraPaths": [ + "tests" + ], + "mypy-type-checker.importStrategy": "fromEnvironment", + "mypy-type-checker.args": [ + "--custom-typeshed-dir=${workspaceFolder}", + // We only guarantee all of our tests can be run if you're on Python 3.9 or higher + "--python-version=3.9", + "--strict", + // Needed because a library stubbed in typeshed won't necessarily be installed in the dev's environment + "--ignore-missing-imports" + ], + // Ensure typeshed's configs are used, and not user's VSCode settings + "flake8.args": [ + "--config=.flake8" + ], + "flake8.importStrategy": "fromEnvironment", + "black-formatter.importStrategy": "fromEnvironment", + // Using Ruff instead of isort + "isort.check": false, + "ruff.importStrategy": "fromEnvironment", + "ruff.fixAll": true, + "ruff.organizeImports": true, + "evenBetterToml.formatter.alignComments": false, + "evenBetterToml.formatter.alignEntries": false, + "evenBetterToml.formatter.allowedBlankLines": 1, + "evenBetterToml.formatter.arrayAutoCollapse": true, + "evenBetterToml.formatter.arrayAutoExpand": true, + "evenBetterToml.formatter.arrayTrailingComma": true, + "evenBetterToml.formatter.columnWidth": 90, + "evenBetterToml.formatter.compactArrays": true, + "evenBetterToml.formatter.compactEntries": false, + "evenBetterToml.formatter.compactInlineTables": false, + "evenBetterToml.formatter.indentEntries": false, + "evenBetterToml.formatter.indentTables": false, + "evenBetterToml.formatter.inlineTableExpand": false, + "evenBetterToml.formatter.reorderArrays": true, + "evenBetterToml.formatter.trailingNewline": true, + // We like keeping TOML keys in a certain non-alphabetical order that feels more natural + "evenBetterToml.formatter.reorderKeys": false +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000000..4a1cf150b627 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,47 @@ +# typeshed - Python type stub repository + +typeshed contains [type stubs](https://typing.python.org/en/latest/spec/distributing.html) +for Python's standard library as well as for some packages available on +[PyPI](https://pypi.org/) (usually called "third-party stubs" in typeshed) +that don't provide their own type annotations. + +The standard library stubs get vendored by type checkers. Each third-party +stub package is distributed as a separate package (usually called +`types-`) on PyPI. + +## Directory Structure + +- `stdlib/` - Python standard library stubs +- `stubs/` - PyPI package stubs, one directory per package +- `scripts`/ - utility scripts +- `tests/` - scripts for various tests, see `tests/README.md` +- `lib/` - utility modules used by multiple scripts + +## Running tests + +To run all tests: + +- Create a new virtual environment (venv), update pip +- Install the dependencies from `requirements-tests.txt` into it +- Run `tests/runtests.py ` from the activated venv + +`` is either: + +- `stdlib/.pyi` +- `stubs/` + +See `tests/README.md` for more information about running tests. + +## Pull Requests + +When opening pull requests, do the following: + +- Follow the guidance from `CONTRIBUTING.md`. +- Run the tests as described above before submitting. +- Don't include tests for .pyi files, unless the situation is complex. See + `tests/REGRESSION.md`. +- Use a concise PR description: + - Either link to an issue or describe the problem briefly, never both. + - Limit the summary of changes to one sentence, unless the PR is complex. + - Don't include a testing plan. +- Add the name of the agent used to the PR description. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000000..232b830135ab --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,493 @@ +# Contributing to typeshed + +Welcome! typeshed is a community project that aims to work for a wide +range of Python users and Python codebases. If you're trying a type +checker on your Python code, your experience and what you can contribute +are important to the project's success. + +## The contribution process at a glance + +1. [Prepare your environment](#preparing-the-environment). +2. Find out [where to make your changes](#where-to-make-changes). +3. [Making your changes](#making-changes): + * Small fixes and additions can be submitted directly as pull requests, + but [contact us](README.md#discussion) before starting significant work. + * Create your stubs, considering [what to include](#what-to-include) and + conforming to the [coding style](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#style-guide). +4. Optionally [format and check your stubs](#stub-content-and-style). +5. Optionally [run the tests](tests/README.md). +6. [Submit your changes](#submitting-changes) by opening a pull request. +7. Make sure that all tests in CI are passing. + +You can expect a reply within a few days, but please be patient when +it takes a bit longer. For more details, read below. + +## Preparing the environment + +### Code away! + +Typeshed runs continuous integration (CI) on all pull requests. This means that +if you file a pull request (PR), our full test suite +-- including our linter, [`flake8-pyi`](https://github.com/pycqa/flake8-pyi) -- +is run on your PR. It also means that bots will automatically apply +changes to your PR (using [Black](https://github.com/psf/black) and +[Ruff](https://github.com/astral-sh/ruff)) to fix any formatting issues. +This frees you up to ignore all local setup on your side, focus on the +code and rely on the CI to fix everything, or point you to the places that +need fixing. + +### ... Or create a local development environment + +If you prefer to run the tests and formatting locally, it's +possible too. Follow platform-specific instructions below. +For more information about our available tests, see +[tests/README.md](tests/README.md). + +Whichever platform you're using, you will need a +virtual environment. If you're not familiar with what it is and how it works, +please refer to this +[documentation](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). + +Note that some tests require extra setup steps to install the required dependencies. + + + + + + + + + + + + + + + + +
Linux / macOS / WSL + + To install the necessary requirements, run the following commands from a + terminal window: + + ```bash + $ python3 -m venv .venv + $ source .venv/bin/activate + (.venv)$ pip install -U pip + (.venv)$ pip install -r requirements-tests.txt + ``` + +
Windows + + Run the following commands from a Windows terminal to install all requirements: + + ```powershell + > py -m venv .venv + > .venv\Scripts\activate + (.venv) > python -m pip install -U pip + (.venv) > pip install -r requirements-tests.txt + ``` + +
Using uv + + If you already have [uv](https://docs.astral.sh/uv/getting-started/installation/) installed, you can simply replace the commands above with: + + ```shell + uv venv + uv pip install -r requirements-tests.txt + ``` + +
+ +## Where to make changes + +### Standard library stubs + +The `stdlib` directory contains stubs for modules in the +Python standard library — which +includes pure Python modules, dynamically loaded extension modules, +hard-linked extension modules, and the builtins. The `VERSIONS` file lists +the versions of Python where the module is available. + +We accept changes for future versions of Python after the first beta for that +version was released. We drop support for a Python version three months +after it reaches [end-of-life](https://devguide.python.org/versions/). This +means that we will no longer actively test the stubs against that version. +After six months, we will remove the stubs for that version and start +to use syntax and typing features not supported by that version. + +### Third-party library stubs + +We accept stubs for third-party packages into typeshed as long as: +* the package is publicly available on the [Python Package Index](https://pypi.org/); +* the package supports any Python version supported by typeshed; and +* the package does not ship with its own stubs or type annotations. + +The fastest way to generate new stubs is to use `scripts/create_baseline_stubs.py` (see below). + +Stubs for third-party packages go into the `stubs` directory. Each subdirectory +there represents a PyPI distribution, and contains the following: +* `METADATA.toml`, describing the package. See below for details. +* Stubs (i.e. `*.pyi` files) for packages and modules that are shipped in the + source distribution. +* (Rarely) some docs specific to a given type stub package in `README` file. + +When a third-party stub is added or +modified, an updated version of the corresponding distribution will be +automatically uploaded to PyPI within a few hours. +Each time this happens the least significant +version level is incremented. For example, if `stubs/foo/METADATA.toml` has +`version = "x.y"` the package on PyPI will be updated from `types-foo-x.y.n` +to `types-foo-x.y.n+1`. + +*Note:* In its current implementation, typeshed cannot contain stubs for +multiple versions of the same third-party library. Prefer to generate +stubs for the latest version released on PyPI at the time of your +stubbing. + +#### The `METADATA.toml` file + +The metadata file describes the stubs package using the +[TOML file format](https://toml.io/en/). Currently, the following keys are +supported: + +* `version`: The versions of the library that the stubs support. Two + formats are supported: + - A concrete version. This is especially suited for libraries that + use [Calendar Versioning](https://calver.org/). + - A version range ending in `.*`. This is suited for libraries that + reflect API changes in the version number only, where the API-independent + part is represented by the asterisk. In the case + of [Semantic Versioning](https://semver.org/), this version could look + like this: `2.7.*`. + When the stubs are updated to a newer version + of the library, the version of the stub should be bumped (note that + previous versions are still available on PyPI). +* `dependencies` (optional): A list of other stub packages or packages with type + information that are imported by the stubs in this package. Only packages + generated by typeshed or required by the upstream package are allowed to + be listed here, for security reasons. See + [this issue](https://github.com/typeshed-internal/stub_uploader/issues/90) + for more information about what external dependencies are allowed. +* `optional-dependencies` (optional): A list of other stub packages or packages + with type information that are imported by some stubs in this package. This + is often used for packages that provide optional features that require extra + dependencies. The same limitations apply to this field as to `dependencies`. +* `extra-description` (optional): Can be used to add a custom description to + the package's long description. It should be a multi-line string in + Markdown format. +* `stub-distribution` (optional): Distribution name to be uploaded to PyPI. + This defaults to `types-` and should only be set in special + cases. +* `upstream-repository` (recommended): The URL of the upstream repository. +* `obsolete-since` (optional): This table is part of our process for + [removing obsolete third-party libraries](#third-party-library-removal-policy). + It contains the first version of the corresponding library that ships + its own `py.typed` file, and the date when that version was released. +* `no-longer-updated` (optional): This field is set to `true` before removing + stubs for other reasons than the upstream library shipping with type + information. +* `upload` (optional): This field is set to `false` to prevent automatic + uploads to PyPI. This should only be used in special cases, e.g. when the stubs + break the upload. +* `partial-stub` (optional): This field marks the type stub package as + [partial](https://typing.python.org/en/latest/spec/distributing.html#partial-stub-packages). + This is for 3rd-party stubs that don't cover the entirety of the package's public API. +* `requires-python` (optional): The minimum version of Python required to install + the type stub package. It must be in the form `>=3.*`. If omitted, the oldest + Python version supported by typeshed is used. + +In addition, we specify configuration for stubtest in the `tool.stubtest` table. +This has the following keys: +* `skip` (default: `false`): Whether stubtest should be run against this + package. Please avoid setting this to `true`, and add a comment if you have + to. +* `ignore-missing-stub`: When set to `true`, this will add the + `--ignore-missing-stub` option to the stubtest call. See + [tests/README.md](./tests/README.md) for more information. In most cases, + this field should be identical to `partial-stub`. +* `stubtest-dependencies` (default: `[]`): A list of Python packages that need + to be installed for stubtest to run successfully. These packages are installed + in addition to the dependencies in the `dependencies` and + `optional-dependencies` fields. +* `apt-dependencies` (default: `[]`): A list of Ubuntu APT packages + that need to be installed for stubtest to run successfully. +* `brew-dependencies` (default: `[]`): A list of MacOS Homebrew packages + that need to be installed for stubtest to run successfully +* `choco-dependencies` (default: `[]`): A list of Windows Chocolatey packages + that need to be installed for stubtest to run successfully +* `supported-platforms` (default: all platforms): A list of OSes on which + stubtest can be run. When a package is not platform-specific, this should + not be set. If the package is platform-specific, this should usually be set + to the supported platforms, unless stubtest is known to fail on a + specific platform. +* `ci-platforms` (default: `["linux"]`): A list of OSes on which to run + stubtest as part of our continuous integration (CI) tests. Can contain + `win32`, `linux`, and `darwin` values. If not specified, stubtest is run + only on `linux`. Only add extra OSes to the test if there are + platform-specific branches in a stubs package. +* `mypy-plugins` (default: `[]`): A list of Python modules to use as mypy plugins +when running stubtest. For example: `mypy-plugins = ["mypy_django_plugin.main"]` +* `mypy-plugins-config` (default: `{}`): A dictionary mapping plugin names to their +configuration dictionaries for use by mypy plugins. For example: +`mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}}` + +`*-dependencies` are usually packages needed to `pip install` the implementation +distribution. + +The format of all `METADATA.toml` files can be checked by running +`python3 ./tests/check_typeshed_structure.py`. + + +## Making Changes + +### Before you begin + +If your change will be a significant amount of work to write, we highly +recommend starting by opening an issue laying out what you want to do. +That lets a conversation happen early in case other contributors disagree +with what you'd like to do or have ideas that will help you do it. + +### Stub Content and Style + +Each Python module is represented by a .pyi "stub file". This is a syntactically valid Python file, where all methods are empty and [type annotations](https://typing.readthedocs.io/en/latest/spec/annotations.html) are used to describe function signatures and variable types. + +Typeshed follows the standard type system guidelines for [stub content](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#stub-content) and [coding style](https://typing.readthedocs.io/en/latest/guides/writing_stubs.html#style-guide). + +The code is formatted using [`Black`](https://github.com/psf/black). +Various other autofixes and lint rules are +also performed by [`Ruff`](https://github.com/astral-sh/ruff) and +[`Flake8`](https://github.com/pycqa/flake8), +with plugin [`flake8-pyi`](https://github.com/pycqa/flake8-pyi). + +The repository is equipped with a [pre-commit.ci](https://pre-commit.ci/) +configuration file. This means that you don't *need* to do anything yourself to +run the code formatters or linters. When you push a commit, a bot will run +those for you right away and add any autofixes to your PR. Anything +that can't be autofixed will show up as a CI failure, hopefully with an error +message that will make it clear what's gone wrong. + +That being said, if you *want* to run the formatters and linters locally +when you commit, you're free to do so. To use the same configuration as we use +in CI, we recommend doing this via pre-commit: + +```bash +(.venv)$ pre-commit run --all-files +``` + +### What to include + +Stubs should include the complete interface (classes, functions, +constants, etc.) of the module they cover, but it is not always +clear exactly what is part of the interface. + +The following should always be included: +- All objects listed in the module's documentation. +- All objects included in ``__all__`` (if present). + +Other objects may be included if they are being used in practice +or if they are not prefixed with an underscore. This means +that typeshed will generally accept contributions that add missing +objects, even if they are undocumented. Undocumented objects should +be marked with a comment of the form ``# undocumented``. + +### Incomplete Annotations + +When submitting new stubs, it is not necessary to annotate all arguments, +return types, and fields. Such items should either be left unannotated or +use `_typeshed.Incomplete` if this is not possible: + +```python +from _typeshed import Incomplete + +field: Incomplete # unannotated + +def foo(x): ... # unannotated argument and return type +``` + +`Incomplete` can also be used for partially known types: + +```python +def foo(x: Incomplete | None) -> list[Incomplete]: ... +``` + +### What to do when a project's documentation and implementation disagree + +Type stubs are meant to be external type annotations for a given +library. While they are useful documentation in their own right, they +augment the project's concrete implementation, not the project's +documentation. Whenever you find them disagreeing, model the type +information after the actual implementation and file an issue on the +project's tracker to fix their documentation. + +### Deprecations (using the `@deprecated` decorator) + +Generally deprecactions using the `@deprecated` decorator are added more +liberally in typeshed than runtime deprecation warnings. Here are some +guidelines that can be deviated from in special cases. + +Use `@deprecated` if and only if + +- a feature is deprecated at runtime (either using `@deprecated` or with a + runtime warning); or +- a feature is documented to be deprecated (e.g. in API documention, + docstrings, or comments). + +For standard library features that are not deprecated in all Python versions +currently supported by typeshed use `@deprecated` for + +- all versions starting with the "Deprecated since" version, plus +- all versions for which an alternative is available. + +### Docstrings + +Typeshed stubs should not include duplicated docstrings from the source code. + +### Auto-generating stub files + +Typeshed includes `scripts/create_baseline_stubs.py`. +It generates stubs automatically using a tool called +[stubgen](https://mypy.readthedocs.io/en/latest/stubgen.html) that comes with mypy. + +To get started, fork typeshed, clone your fork, and then +[create a virtualenv](#-or-create-a-local-development-environment). +You can then install the library with `pip` into the virtualenv and run the script below, +replacing `$INSERT_LIBRARY_NAME_HERE` with the name of the library: + +```bash +(.venv)$ pip install $INSERT_LIBRARY_NAME_HERE +(.venv)$ python3 scripts/create_baseline_stubs.py $INSERT_LIBRARY_NAME_HERE +``` + +When the script has finished running, it will print instructions telling you what to do next. + +If it has been a while since you set up the virtualenv, make sure you have +the latest mypy (`pip install -r requirements-tests.txt`) before running the script. + +### Supported type system features + +Since [PEP 484](https://peps.python.org/pep-0484/) was accepted, there have been +many other PEPs that added new features to the Python type system. In general, +new features can be used in typeshed as soon as the PEP has been accepted and +implemented and most type checkers support the new feature. + +Supported features include: +- [PEP 544](https://peps.python.org/pep-0544/) (`Protocol`) +- [PEP 585](https://peps.python.org/pep-0585/) (builtin generics) +- [PEP 586](https://peps.python.org/pep-0586/) (`Literal`) +- [PEP 591](https://peps.python.org/pep-0591/) (`Final`/`@final`) +- [PEP 589](https://peps.python.org/pep-0589/) (`TypedDict`) +- [PEP 604](https://peps.python.org/pep-0604/) (`Foo | Bar` union syntax) +- [PEP 612](https://peps.python.org/pep-0612/) (`ParamSpec`) +- [PEP 647](https://peps.python.org/pep-0647/) (`TypeGuard`): + see [#5406](https://github.com/python/typeshed/issues/5406) +- [PEP 655](https://peps.python.org/pep-0655/) (`Required` and `NotRequired`) +- [PEP 673](https://peps.python.org/pep-0673/) (`Self`) +- [PEP 675](https://peps.python.org/pep-0675/) (`LiteralString`) +- [PEP 702](https://peps.python.org/pep-0702/) (`@deprecated()`) + +Features from the `typing` module that are not present in all +supported Python versions must be imported from `typing_extensions` +instead in typeshed stubs. This currently affects: + +- `Self` (new in Python 3.11) +- `Never` (new in Python 3.11) +- `LiteralString` (new in Python 3.11) +- `TypeVarTuple` and `Unpack` (new in Python 3.11) +- `Required` and `NotRequired` (new in Python 3.11) +- `Buffer` (new in Python 3.12; in the `collections.abc` module) +- `@deprecated` (new in Python 3.13; in the `warnings` module) + +Some type checkers implicitly promote the `bytearray` and +`memoryview` types to `bytes`. +[PEP 688](https://www.python.org/dev/peps/pep-0688/) removes +this implicit promotion. +Typeshed stubs should be written assuming that these promotions +do not happen, so a parameter that accepts either `bytes` or +`bytearray` should be typed as `bytes | bytearray`. +Often one of the aliases from `_typeshed`, such as +`_typeshed.ReadableBuffer`, can be used instead. + +## Submitting Changes + +Even more excellent than a good bug report is a fix for a bug, or the +implementation of a much-needed stub. We'd love to have +your contributions. + +We use the usual GitHub pull-request flow, which may be familiar to +you if you've contributed to other projects on GitHub. For the +mechanics, see [Mypy's git and GitHub workflow help page](https://github.com/python/mypy/wiki/Using-Git-And-GitHub), +or [GitHub's own documentation](https://help.github.com/articles/using-pull-requests/). + +Anyone interested in type stubs may review your code. One of the +maintainers will merge your pull request when they think it's ready. +For every pull request, we aim to promptly either merge it or say why +it's not yet ready; if you go a few days without a reply, please feel +free to ping the thread by adding a new comment. + +To get your pull request merged sooner, you should explain why you are +making the change. For example, you can point to a code sample that is +processed incorrectly by a type checker. It is also helpful to add +links to online documentation or to the implementation of the code +you are changing. + +As the author of the pull request, it is your responsibility to make +sure all CI tests pass and that any feedback is addressed. The typeshed +maintainers will probably provide some help and may even push changes +to your PR to fix any minor issues, but this is not always possible. +If a PR lingers with unresolved problems for too long, we may close it +([see below](#closing-stale-prs)). + +Also, do not squash your commits or use `git commit --amend` after you have submitted a pull request, as this +erases context during review. We will squash commits when the pull request is merged. +This way, your pull request will appear as a single commit in our git history, even +if it consisted of several smaller commits. + +## Third-party library removal policy + +Third-party stubs are generally removed from typeshed when one of the +following criteria is met: + +* The upstream package ships a `py.typed` file for at least six months, + and the upstream type annotations are of a comparable standard to those in + typeshed, or +* the upstream package was declared or appears to be unmaintained, and + retaining the stubs causes maintenance issues in typeshed. + +Case 1: If a package ships its own `py.typed` file, please follow these steps: + +1. Make sure **stubsabot** open a PR that sets the `obsolete-since` field in the + `METADATA.toml` file to the first version of the package that shipped `py.typed`. +2. After at least six months, make sure **stubsabot** open a PR to remove the stubs. + +Case 2: If third-party stubs should be removed for other reasons, please follow +these steps: + +1. Open an issue explaining why the stubs should be removed. +2. A maintainer will add the + ["stubs: removal" label](https://github.com/python/typeshed/labels/stubs%3A%20removal). +3. Open a PR that sets the `no-longer-updated` field in the `METADATA.toml` + file to `true`. +4. When a new version of the package was automatically uploaded to PyPI (which + can take up to a day), make sure **stubsabot** open a PR to remove the stubs. + +If feeling kindly, please update [mypy](https://github.com/python/mypy/blob/master/mypy/stubinfo.py) +for any stub obsoletions or removals. + +### Marking PRs as "deferred" + +We sometimes use the ["status: deferred" label](https://github.com/python/typeshed/labels/status%3A%20deferred) +to mark PRs and issues that we'd like to accept, but that are blocked by some +external factor. Blockers can include: + +- An unambiguous bug in a type checker (i.e., a case where the + type checker is not implementing [the typing spec](https://typing.readthedocs.io/en/latest/spec/index.html)). +- A dependency on a typing PEP that is still under consideration. +- A pending change in a related project, such as stub-uploader. + +### Closing stale PRs + +To keep the number of open PRs manageable, we may close PRs when they have been +open for too long. Specifically, we close open PRs that either have failures in CI, +serious merge conflicts or unaddressed feedback, and that have not seen any +activity in three months. diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000000..13264487581f --- /dev/null +++ b/LICENSE @@ -0,0 +1,237 @@ +The "typeshed" project is licensed under the terms of the Apache license, as +reproduced below. + += = = = = + +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. + += = = = = + +Parts of typeshed are licensed under different licenses (like the MIT +license), reproduced below. + += = = = = + +The MIT License + +Copyright (c) 2015 Jukka Lehtosalo and contributors + +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/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 000000000000..2048da2064d9 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,105 @@ +At present the active maintainers are (alphabetically): + +* Rebecca Chen (@rchen152) +* Jukka Lehtosalo (@JukkaL) +* Ivan Levkivskyi (@ilevkivskyi) +* Sebastian Rittau (@srittau) +* Guido van Rossum (@gvanrossum) +* Brian Schubert (@brianschubert) +* Shantanu (@hauntsaninja) +* Nikita Sobolev (@sobolevn) +* Samuel Therrien (@Avasam) +* Aku Viljanen (@Akuli) +* Alex Waygood (@AlexWaygood) +* Jelle Zijlstra (@JelleZijlstra) + +Former maintainers include: + +* David Fisher (@ddfisher) +* Matthias Kramm (@matthiaskramm) +* Łukasz Langa (@ambv) +* Greg Price (@gnprice) +* Rune Tynan (@CraftSpider) + +For security reasons, maintainers who haven't been active for twelve months +(no PR reviews or merges, no opened PRs, no significant participation in +issues or typing-related discussion) will have their access rights removed. +They will also be moved to the "former maintainers" section here. + +Former maintainers who want their access rights restored should open +an issue or mail one of the active maintainers. + +## Maintainer guidelines + +The process for preparing and submitting changes as outlined +in the [CONTRIBUTING document](./CONTRIBUTING.md) also applies to +maintainers. This ensures high quality contributions and keeps +everybody on the same page. Do not make direct pushes to the repository. + +### Reviewing and merging pull requests + +When reviewing pull requests, follow these guidelines: + +* Typing is hard. Try to be helpful and explain issues with the PR, + especially to new contributors. +* When reviewing auto-generated stubs, just scan for red flags and obvious + errors. Leave possible manual improvements for separate PRs. +* When reviewing large, hand-crafted PRs, you only need to look for red flags + and general issues, and do a few spot checks. +* Review smaller, hand-crafted PRs thoroughly. + +When merging pull requests, follow these guidelines: + +* Always wait for tests to pass before merging PRs. +* Use "[Squash and merge](https://github.com/blog/2141-squash-your-commits)" to merge PRs. +* Make sure the commit message is meaningful. For example, remove irrelevant + intermediate commit messages. +* The commit message for third-party stubs is used to generate the changelog. + It should be valid Markdown, be comprehensive, read like a changelog entry, + and assume that the reader has no access to the diff. +* Delete branches for merged PRs (by maintainers pushing to the main repo). + +### Marking PRs as "deferred" + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#marking-prs-as-deferred).* + +PRs should only be marked as "deferred" if there is a clear path towards getting +the blocking issue resolved within a reasonable time frame. If a PR depends on +a more amorphous change, such as a type system change that has not yet reached +the PEP stage, it should instead be closed. + +Maintainers who add the "deferred" label should state clearly what exactly the +blocker is, usually with a link to an open issue in another project. + +### Closing stale PRs + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#closing-stale-prs).* + +We want to maintain a welcoming atmosphere for contributors, so use a friendly +message when closing the PR. Example message: + + Thanks for contributing! I'm closing this PR for now, because it still after three months of inactivity. If you are still interested, please feel free to open a new PR (or ping us to reopen this one). + +### Closing PRs for future standard library changes + +*See also the [guidelines in the CONTRIBUTING file](./CONTRIBUTING.md#standard-library-stubs).* + +When rejecting a PR for a change for a future Python version, use a message +like: + + Thanks for contributing! Unfortunately, [as outlined in our CONTRIBUTING document](https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#standard-library-stubs) we only accept pull requests to the standard library for future Python versions after the first beta version has been released. This is in part to prevent churn in the stubs, and in part because the testing infrastructure for the future version is not yet in place. Please feel free to open a new PR when the first beta version has been released. Alternatively, if this PR is still relevant, you can leave a comment here to reopen it. + +### Closing requests for third-party stubs + +We don't keep requests for third-party library stubs open. Close those +requests as "not planned" with an explanation like this: + + We gladly accept type stub contributions for third-party libraries that are published on PyPI in typeshed. To contribute a new library, please follow the steps outlined in [CONTRIBUTING.md](/python/typeshed/blob/main/CONTRIBUTING.md). The `create_baseline_stubs.py` script can be useful to create an initial version, suitable for inclusion in typeshed. + + That said, we don't keep requests for third-party library stubs open, unless there are issues that need to be addressed before a PR can be opened. Therefore, I'm closing this issue. + +### Asking to remove tests + + Please remove the tests. In typeshed, we only add regression tests for functions and classes which are known to have caused complex problems in the past, or where stubs are difficult to get right. 100% test coverage for typeshed is neither necessary nor desirable, as it would lead to code duplication. + + See [`tests/REGRESSION.md`](https://github.com/python/typeshed/blob/main/tests/REGRESSION.md) for more information. diff --git a/README.md b/README.md new file mode 100644 index 000000000000..dae1780a4127 --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ +# typeshed + +[![Tests](https://github.com/python/typeshed/actions/workflows/tests.yml/badge.svg)](https://github.com/python/typeshed/actions/workflows/tests.yml) +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Pull Requests Welcome](https://img.shields.io/badge/pull%20requests-welcome-brightgreen.svg)](https://github.com/python/typeshed/blob/main/CONTRIBUTING.md) + +## About + +Typeshed contains external type annotations for the Python standard library +and Python builtins, as well as third-party packages that are contributed by +people external to those projects. + +This data can, e.g., be used for static analysis, type checking, type inference, +and autocompletion. + +For information on how to use typeshed, read below. Information for +contributors can be found in [CONTRIBUTING.md](CONTRIBUTING.md). **Please read +it before submitting pull requests; do not report issues with annotations to +the project the stubs are for, but instead report them here to typeshed.** + +Further documentation on stub files, typeshed, and Python's typing system in +general, can also be found at https://typing.readthedocs.io/en/latest/. + +Typeshed supports Python versions 3.10 to 3.14. + +## Using + +If you're just using a type checker (e.g. [mypy](https://github.com/python/mypy/), +[pyright](https://github.com/microsoft/pyright), or PyCharm's built-in type +checker), as opposed to +developing it, you don't need to interact with the typeshed repo at +all: a copy of the standard library part of typeshed is bundled with type checkers. +And type stubs for third-party packages and modules you are using can +be installed from PyPI. For example, if you are using `html5lib` and `requests`, +you can install the type stubs using + +```bash +$ pip install types-html5lib types-requests +``` + +These PyPI packages follow [the typing spec standards](https://typing.python.org/en/latest/spec/distributing.html) +and are automatically released (up to once a day) by +[typeshed internal machinery](https://github.com/typeshed-internal/stub_uploader). + +Type checkers should be able to use these stub packages when installed. For more +details, see the documentation for your type checker. + +### Package versioning for third-party stubs + +Version numbers of third-party stub packages consist of at least four parts. +All parts of the stub version, except for the last part, correspond to the +version of the runtime package being stubbed. For example, if the `types-foo` +package has version `1.2.0.20240309`, this guarantees that the `types-foo` package +contains stubs targeted against `foo==1.2.*` and tested against the latest +version of `foo` matching that specifier. In this example, the final element +of the version number (20240309) indicates that the stub package was pushed on +March 9, 2024. + +At typeshed, we try to keep breaking changes to a minimum. However, due to the +nature of stubs, any version bump can introduce changes that might make your +code fail to type check. + +There are several strategies available for specifying the version of a stubs +package you're using, each with its own tradeoffs: + +1. Use the same bounds that you use for the package being stubbed. For example, + if you use `requests>=2.30.0,<2.32`, you can use + `types-requests>=2.30.0,<2.32`. This ensures that the stubs are compatible + with the package you are using, but it carries a small risk of breaking + type checking due to changes in the stubs. + + Another risk of this strategy is that stubs often lag behind + the package that is being stubbed. You might want to force the package being stubbed + to a certain minimum version because it fixes a critical bug, but if + correspondingly updated stubs have not been released, your type + checking results may not be fully accurate. +2. Pin the stubs to a known good version and update the pin from time to time + (either manually, or using a tool such as dependabot or renovate). + + For example, if you use `types-requests==2.31.0.1`, you can have confidence + that upgrading dependencies will not break type checking. However, you will + miss out on improvements in the stubs that could potentially improve type + checking until you update the pin. This strategy also has the risk that the + stubs you are using might become incompatible with the package being stubbed. +3. Don't pin the stubs. This is the option that demands the least work from + you when it comes to updating version pins, and has the advantage that you + will automatically benefit from improved stubs whenever a new version of the + stubs package is released. However, it carries the risk that the stubs + become incompatible with the package being stubbed. + + For example, if a new major version of the package is released, there's a + chance the stubs might be updated to reflect the new version of the runtime + package before you update the package being stubbed. + +You can also switch between the different strategies as needed. For example, +you could default to strategy (1), but fall back to strategy (2) when +a problem arises that can't easily be fixed. + +### The `_typeshed` package + +typeshed includes a package `_typeshed` as part of the standard library. +This package and its submodules contain utility types, but are not +available at runtime. For more information about how to use this package, +[see the `stdlib/_typeshed` directory](https://github.com/python/typeshed/tree/main/stdlib/_typeshed). + +## Discussion + +If you've run into behavior in the type checker that suggests the type +stubs for a given library are incorrect or incomplete, +we want to hear from you! + +Our main forum for discussion is the project's [GitHub issue +tracker](https://github.com/python/typeshed/issues). This is the right +place to start a discussion of any of the above or most any other +topic concerning the project. + +If you have general questions about typing with Python, or you need +a review of your type annotations or stubs outside of typeshed, head over to +[our discussion forum](https://github.com/python/typing/discussions). +For less formal discussion, try the typing chat room on +[gitter.im](https://gitter.im/python/typing). Some typeshed maintainers +are almost always present; feel free to find us there, and we're happy +to chat. Substantive technical discussion will be directed to the +issue tracker. diff --git a/lib/pyproject.toml b/lib/pyproject.toml new file mode 100644 index 000000000000..34720aa9acba --- /dev/null +++ b/lib/pyproject.toml @@ -0,0 +1,9 @@ +# Utilities for typeshed infrastructure scripts. + +[project] +name = "ts_utils" +version = "0.0.0" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" diff --git a/lib/ts_utils/__init__.py b/lib/ts_utils/__init__.py new file mode 100644 index 000000000000..44e839ba3a27 --- /dev/null +++ b/lib/ts_utils/__init__.py @@ -0,0 +1 @@ +"""Utilities for typeshed infrastructure scripts.""" diff --git a/lib/ts_utils/metadata.py b/lib/ts_utils/metadata.py new file mode 100644 index 000000000000..ee911ab5e01f --- /dev/null +++ b/lib/ts_utils/metadata.py @@ -0,0 +1,459 @@ +# This module is made specifically to abstract away those type errors +# pyright: reportUnknownVariableType=false, reportUnknownArgumentType=false + +"""Tools to help parse and validate information stored in METADATA.toml files.""" + +from __future__ import annotations + +import datetime +import functools +import re +import sys +import urllib.parse +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Annotated, Any, Final, NamedTuple, TypeGuard, cast, final + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +import tomlkit +from packaging.requirements import Requirement +from packaging.specifiers import Specifier + +from .paths import PYPROJECT_PATH, STUBS_PATH, distribution_path + +__all__ = [ + "NoSuchStubError", + "PackageDependencies", + "StubMetadata", + "StubtestSettings", + "get_oldest_supported_python", + "get_recursive_requirements", + "read_dependencies", + "read_metadata", + "read_stubtest_settings", +] + +DEFAULT_STUBTEST_PLATFORMS = ["linux"] + +_STUBTEST_PLATFORM_MAPPING: Final = {"linux": "apt_dependencies", "darwin": "brew_dependencies", "win32": "choco_dependencies"} +# Some older websites have a bad pattern of using query params for navigation. +_QUERY_URL_ALLOWLIST = {"sourceware.org"} + + +def _is_list_of_strings(obj: object) -> TypeGuard[list[str]]: + return isinstance(obj, list) and all(isinstance(item, str) for item in obj) + + +def _is_nested_dict(obj: object) -> TypeGuard[dict[str, dict[str, Any]]]: + return isinstance(obj, dict) and all(isinstance(k, str) and isinstance(v, dict) for k, v in obj.items()) + + +@functools.cache +def get_oldest_supported_python() -> str: + with PYPROJECT_PATH.open("rb") as config: + val = tomllib.load(config)["tool"]["typeshed"]["oldest-supported-python"] + assert type(val) is str + return val + + +def metadata_path(distribution: str) -> Path: + """Return the path to the METADATA.toml file of a third-party distribution.""" + return distribution_path(distribution) / "METADATA.toml" + + +@final +@dataclass(frozen=True) +class StubtestSettings: + """The stubtest settings for a single stubs distribution. + + Don't construct instances directly; use the `read_stubtest_settings` function. + """ + + skip: bool + apt_dependencies: list[str] + brew_dependencies: list[str] + choco_dependencies: list[str] + extras: list[str] + ignore_missing_stub: bool + supported_platforms: list[str] | None # None means all platforms + ci_platforms: list[str] + stubtest_dependencies: list[str] + mypy_plugins: list[str] + mypy_plugins_config: dict[str, dict[str, Any]] + + def system_requirements_for_platform(self, platform: str) -> list[str]: + assert platform in _STUBTEST_PLATFORM_MAPPING, f"Unrecognised platform {platform!r}" + ret = getattr(self, _STUBTEST_PLATFORM_MAPPING[platform]) + assert _is_list_of_strings(ret) + return ret + + +@functools.cache +def read_stubtest_settings(distribution: str) -> StubtestSettings: + """Return an object describing the stubtest settings for a single stubs distribution.""" + with metadata_path(distribution).open("rb") as f: + data: dict[str, object] = tomllib.load(f).get("tool", {}).get("stubtest", {}) + + skip: object = data.get("skip", False) + apt_dependencies: object = data.get("apt-dependencies", []) + brew_dependencies: object = data.get("brew-dependencies", []) + choco_dependencies: object = data.get("choco-dependencies", []) + extras: object = data.get("extras", []) + ignore_missing_stub: object = data.get("ignore-missing-stub", False) + supported_platforms: object = data.get("supported-platforms") + ci_platforms: object = data.get("ci-platforms", DEFAULT_STUBTEST_PLATFORMS) + stubtest_dependencies: object = data.get("stubtest-dependencies", []) + mypy_plugins: object = data.get("mypy-plugins", []) + mypy_plugins_config: object = data.get("mypy-plugins-config", {}) + + assert type(skip) is bool + assert type(ignore_missing_stub) is bool + + # It doesn't work for type-narrowing if we use a for loop here... + assert supported_platforms is None or _is_list_of_strings(supported_platforms) + assert _is_list_of_strings(ci_platforms) + assert _is_list_of_strings(apt_dependencies) + assert _is_list_of_strings(brew_dependencies) + assert _is_list_of_strings(choco_dependencies) + assert _is_list_of_strings(extras) + assert _is_list_of_strings(stubtest_dependencies) + assert _is_list_of_strings(mypy_plugins) + assert _is_nested_dict(mypy_plugins_config) + + unrecognised_platforms = set(ci_platforms) - _STUBTEST_PLATFORM_MAPPING.keys() + assert not unrecognised_platforms, f"Unrecognised ci-platforms specified for {distribution!r}: {unrecognised_platforms}" + + if supported_platforms is not None: + assert set(ci_platforms).issubset( + supported_platforms + ), f"ci-platforms must be a subset of supported-platforms for {distribution!r}" + + for platform, dep_key in _STUBTEST_PLATFORM_MAPPING.items(): + if platform not in ci_platforms: + assert dep_key not in data, ( + f"Stubtest is not run on {platform} in CI for {distribution!r}, " + f"but {dep_key!r} are specified in METADATA.toml" + ) + + return StubtestSettings( + skip=skip, + apt_dependencies=apt_dependencies, + brew_dependencies=brew_dependencies, + choco_dependencies=choco_dependencies, + extras=extras, + ignore_missing_stub=ignore_missing_stub, + supported_platforms=supported_platforms, + ci_platforms=ci_platforms, + stubtest_dependencies=stubtest_dependencies, + mypy_plugins=mypy_plugins, + mypy_plugins_config=mypy_plugins_config, + ) + + +@final +@dataclass(frozen=True) +class ObsoleteMetadata: + since_version: Annotated[str, "A string representing a specific version"] + since_date: Annotated[datetime.date, "A date when the package became obsolete"] + + +@final +@dataclass(frozen=True) +class StubMetadata: + """The metadata for a single stubs distribution. + + Don't construct instances directly; use the `read_metadata` function. + """ + + distribution: Annotated[str, "The name of the distribution on PyPI"] + version_spec: Annotated[Specifier, "Upstream versions that the stubs are compatible with"] + dependencies: Annotated[list[Requirement], "The parsed dependencies as listed in METADATA.toml"] + optional_dependencies: Annotated[list[Requirement], "The parsed optional dependencies as listed in METADATA.toml"] + extra_description: str | None + stub_distribution: Annotated[str, "The name under which the distribution is uploaded to PyPI"] + upstream_repository: Annotated[str, "The URL of the upstream repository"] | None + obsolete: Annotated[ObsoleteMetadata, "Metadata indicating when the stubs package became obsolete"] | None + no_longer_updated: bool + uploaded_to_pypi: Annotated[bool, "Whether or not a distribution is uploaded to PyPI"] + partial_stub: Annotated[bool, "Whether this is a partial type stub package as per PEP 561."] + stubtest_settings: StubtestSettings + requires_python: Annotated[Specifier, "Versions of Python supported by the stub package"] + + @property + def is_obsolete(self) -> bool: + return self.obsolete is not None + + @property + def all_dependencies(self) -> list[Requirement]: + """The dependencies and optional dependencies of this stubs package. + + Does not include the stubtest dependencies. + """ + return self.dependencies + self.optional_dependencies + + +_KNOWN_METADATA_FIELDS: Final = frozenset( + { + "version", + "dependencies", + "optional-dependencies", + "extra-description", + "stub-distribution", + "upstream-repository", + "obsolete-since", + "no-longer-updated", + "upload", + "tool", + "partial-stub", + "requires-python", + "mypy-tests", + } +) +_KNOWN_METADATA_TOOL_FIELDS: Final = { + "stubtest": { + "skip", + "apt-dependencies", + "brew-dependencies", + "choco-dependencies", + "extras", + "ignore-missing-stub", + "supported-platforms", + "ci-platforms", + "stubtest-dependencies", + "mypy-plugins", + "mypy-plugins-config", + } +} +_DIST_NAME_RE: Final = re.compile(r"^[a-z0-9]([a-z0-9._-]*[a-z0-9])?$", re.IGNORECASE) + + +class NoSuchStubError(ValueError): + """Raise NoSuchStubError to indicate that a stubs/{distribution} directory doesn't exist.""" + + +@functools.cache +def read_metadata(distribution: str) -> StubMetadata: + """Return an object describing the metadata of a stub as given in the METADATA.toml file. + + This function does some basic validation, + but does no parsing, transforming or normalization of the metadata. + Use `read_dependencies` if you need to parse the dependencies + given in the `dependencies` field, for example. + """ + try: + with metadata_path(distribution).open("rb") as f: + # This cast is necessary for pyright to understand that the + # variable is a dict with object values. Just using + # `data: dict[str, object] = tomlkit.load(f)` doesn't work because + # pyright still infers TOMLDocument which derives from + # dict[Unknown, Unknown]. + data = cast(dict[str, object], tomlkit.load(f)) + except FileNotFoundError: + raise NoSuchStubError(f"Typeshed has no stubs for {distribution!r}!") from None + + unknown_metadata_fields = data.keys() - _KNOWN_METADATA_FIELDS + assert not unknown_metadata_fields, f"Unexpected keys in METADATA.toml for {distribution!r}: {unknown_metadata_fields}" + + assert "version" in data, f"Missing 'version' field in METADATA.toml for {distribution!r}" + version = data.get("version") + assert isinstance(version, str) and len(version) > 0, f"Invalid 'version' field in METADATA.toml for {distribution!r}" + # Check that the version spec parses + if version[0].isdigit(): + version = f"=={version}" + version_spec = Specifier(version) + assert version_spec.operator in {"==", "~="}, f"Invalid 'version' field in METADATA.toml for {distribution!r}" + + dependencies_s = data.get("dependencies", []) + assert isinstance(dependencies_s, list) + dependencies = [parse_dependencies(distribution, dep) for dep in dependencies_s] + + optional_dependencies_s = data.get("optional-dependencies", []) + assert isinstance(optional_dependencies_s, list) + optional_dependencies = [parse_dependencies(distribution, dep) for dep in optional_dependencies_s] + + extra_description = data.get("extra-description") + assert isinstance(extra_description, (str, type(None))) + + if "stub-distribution" in data: + stub_distribution = data["stub-distribution"] + assert isinstance(stub_distribution, str) + assert _DIST_NAME_RE.fullmatch(stub_distribution), f"Invalid 'stub-distribution' value for {distribution!r}" + else: + stub_distribution = f"types-{distribution}" + + upstream_repository = data.get("upstream-repository") + assert isinstance(upstream_repository, (str, type(None))) + if isinstance(upstream_repository, str): + parsed_url = urllib.parse.urlsplit(upstream_repository) + assert parsed_url.scheme == "https", f"{distribution}: URLs in the upstream-repository field should use https" + no_www_please = ( + f"{distribution}: `World Wide Web` subdomain (`www.`) should be removed from URLs in the upstream-repository field" + ) + assert not parsed_url.netloc.startswith("www."), no_www_please + no_query_params_please = ( + f"{distribution}: Query params (`?`) should be removed from URLs in the upstream-repository field" + ) + assert parsed_url.hostname in _QUERY_URL_ALLOWLIST or (not parsed_url.query), no_query_params_please + no_fragments_please = f"{distribution}: Fragments (`#`) should be removed from URLs in the upstream-repository field" + assert not parsed_url.fragment, no_fragments_please + if parsed_url.netloc == "github.com": + cleaned_url_path = parsed_url.path.strip("/") + num_url_path_parts = len(Path(cleaned_url_path).parts) + bad_github_url_msg = ( + f"Invalid upstream-repository for {distribution!r}: " + "URLs for GitHub repositories always have two parts in their paths" + ) + assert num_url_path_parts == 2, bad_github_url_msg + + obsolete_since = data.get("obsolete-since") + assert isinstance(obsolete_since, (dict, type(None))) + if obsolete_since is not None: + obsolete_table: dict[str, object] = obsolete_since + obsolete_since_version = obsolete_table.get("version") + obsolete_since_date = obsolete_table.get("date") + assert isinstance(obsolete_since_version, str) + assert isinstance(obsolete_since_date, str) + since_date = datetime.date.fromisoformat(obsolete_since_date) + obsolete = ObsoleteMetadata(since_version=obsolete_since_version, since_date=since_date) + else: + obsolete = None + no_longer_updated = data.get("no-longer-updated", False) + assert type(no_longer_updated) is bool + uploaded_to_pypi = data.get("upload", True) + assert type(uploaded_to_pypi) is bool + partial_stub = data.get("partial-stub", True) + assert type(partial_stub) is bool + requires_python_str = data.get("requires-python") + oldest_supported_python = get_oldest_supported_python() + oldest_supported_python_specifier = Specifier(f">={oldest_supported_python}") + if requires_python_str is None: + requires_python = oldest_supported_python_specifier + else: + assert isinstance(requires_python_str, str) + requires_python = Specifier(requires_python_str) + assert requires_python != oldest_supported_python_specifier, f'requires-python="{requires_python}" is redundant' + # Check minimum Python version is not less than the oldest version of Python supported by typeshed + assert oldest_supported_python_specifier.contains( + requires_python.version + ), f"'requires-python' contains versions lower than typeshed's oldest supported Python ({oldest_supported_python})" + assert requires_python.operator == ">=", "'requires-python' should be a minimum version specifier, use '>=3.x'" + + empty_tools: dict[object, object] = {} + tools_settings = data.get("tool", empty_tools) + assert isinstance(tools_settings, dict) + assert tools_settings.keys() <= _KNOWN_METADATA_TOOL_FIELDS.keys(), f"Unrecognised tool for {distribution!r}" + for tool, tk in _KNOWN_METADATA_TOOL_FIELDS.items(): + settings_for_tool = cast(dict[str, object], tools_settings).get(tool, {}) + assert isinstance(settings_for_tool, dict) + for key in settings_for_tool: + assert key in tk, f"Unrecognised {tool} key {key!r} for {distribution!r}" + + return StubMetadata( + distribution=distribution, + version_spec=version_spec, + dependencies=dependencies, + optional_dependencies=optional_dependencies, + extra_description=extra_description, + stub_distribution=stub_distribution, + upstream_repository=upstream_repository, + obsolete=obsolete, + no_longer_updated=no_longer_updated, + uploaded_to_pypi=uploaded_to_pypi, + partial_stub=partial_stub, + stubtest_settings=read_stubtest_settings(distribution), + requires_python=requires_python, + ) + + +def update_metadata(distribution: str, **new_values: object) -> dict[str, object]: + """Update a distribution's METADATA.toml. + + Return the updated TOML dictionary for use without having to open the file separately. + """ + path = metadata_path(distribution) + try: + with path.open("rb") as f: + # This cast is necessary for pyright to understand that the + # variable is a dict with object values. Just using + # `data: dict[str, object] = tomlkit.load(f)` doesn't work because + # pyright still infers TOMLDocument which derives from + # dict[Unknown, Unknown]. + data = cast(dict[str, object], tomlkit.load(f)) + except FileNotFoundError: + raise NoSuchStubError(f"Typeshed has no stubs for {distribution!r}!") from None + data.update(new_values) + for key in list(data.keys()): + new_key = key.replace("_", "-") + data[new_key] = data.pop(key) + with path.open("w", encoding="UTF-8") as f: + tomlkit.dump(data, f) + return data + + +def parse_dependencies(distribution: str, req: object) -> Requirement: + assert isinstance(req, str), f"Invalid requirement {req!r} for {distribution!r}" + return Requirement(req) + + +class PackageDependencies(NamedTuple): + typeshed_pkgs: tuple[Requirement, ...] + external_pkgs: tuple[Requirement, ...] + + +@functools.cache +def get_pypi_name_to_typeshed_name_mapping() -> Mapping[str, str]: + return {read_metadata(stub_dir.name).stub_distribution: stub_dir.name for stub_dir in STUBS_PATH.iterdir()} + + +@functools.cache +def read_dependencies(distribution: str) -> PackageDependencies: + """Read the dependencies listed in a METADATA.toml file for a stubs package. + + Once the dependencies have been read, + determine which dependencies are typeshed-internal dependencies, + and which dependencies are external (non-types) dependencies. + For typeshed dependencies, translate the "dependency name" into the "package name"; + for external dependencies, leave them as they are in the METADATA.toml file. + + Note that this function may consider things to be typeshed stubs + even if they haven't yet been uploaded to PyPI. + If a typeshed stub is removed, this function will consider it to be an external dependency. + """ + pypi_name_to_typeshed_name_mapping = get_pypi_name_to_typeshed_name_mapping() + typeshed: list[Requirement] = [] + external: list[Requirement] = [] + for dependency in read_metadata(distribution).all_dependencies: + if dependency.name in pypi_name_to_typeshed_name_mapping: + req = Requirement(str(dependency)) # copy the requirement + req.name = pypi_name_to_typeshed_name_mapping[dependency.name] + typeshed.append(req) + else: + external.append(dependency) + return PackageDependencies(tuple(typeshed), tuple(external)) + + +@functools.cache +def get_recursive_requirements(package_name: str) -> PackageDependencies: + """Recursively gather dependencies for a single stubs package. + + For example, if the stubs for `caldav` + declare a dependency on typeshed's stubs for `requests`, + and the stubs for requests declare a dependency on typeshed's stubs for `urllib3`, + `get_recursive_requirements("caldav")` will determine that the stubs for `caldav` + have both `requests` and `urllib3` as typeshed-internal dependencies. + """ + typeshed: set[Requirement] = set() + external: set[Requirement] = set() + non_recursive_requirements = read_dependencies(package_name) + typeshed.update(non_recursive_requirements.typeshed_pkgs) + external.update(non_recursive_requirements.external_pkgs) + for pkg in non_recursive_requirements.typeshed_pkgs: + reqs = get_recursive_requirements(pkg.name) + typeshed.update(reqs.typeshed_pkgs) + external.update(reqs.external_pkgs) + return PackageDependencies(tuple(typeshed), tuple(external)) diff --git a/lib/ts_utils/mypy.py b/lib/ts_utils/mypy.py new file mode 100644 index 000000000000..17cba6978061 --- /dev/null +++ b/lib/ts_utils/mypy.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +import sys +from collections.abc import Generator, Iterable +from contextlib import contextmanager +from typing import Any, NamedTuple + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +from ts_utils.metadata import StubtestSettings, metadata_path +from ts_utils.utils import NamedTemporaryFile, TemporaryFileWrapper + + +class MypyDistConf(NamedTuple): + module_name: str + values: dict[str, dict[str, Any]] + + +# The configuration section in the metadata file looks like the following, with multiple module sections possible +# [mypy-tests] +# [mypy-tests.yaml] +# module-name = "yaml" +# [mypy-tests.yaml.values] +# disallow_incomplete_defs = true +# disallow_untyped_defs = true + + +def mypy_configuration_from_distribution(distribution: str) -> list[MypyDistConf]: + with metadata_path(distribution).open("rb") as f: + data = tomllib.load(f) + + # TODO: This could be added to ts_utils.metadata + mypy_tests_conf: dict[str, dict[str, Any]] = data.get("mypy-tests", {}) + if not mypy_tests_conf: + return [] + + def validate_configuration(section_name: str, mypy_section: dict[str, Any]) -> MypyDistConf: + assert isinstance(mypy_section, dict), f"{section_name} should be a section" + module_name = mypy_section.get("module-name") + + assert module_name is not None, f"{section_name} should have a module-name key" + assert isinstance(module_name, str), f"{section_name} should be a key-value pair" + + assert "values" in mypy_section, f"{section_name} should have a values section" + values: dict[str, dict[str, Any]] = mypy_section["values"] + assert isinstance(values, dict), "values should be a section" + return MypyDistConf(module_name, values.copy()) + + assert isinstance(mypy_tests_conf, dict), "mypy-tests should be a section" + return [validate_configuration(section_name, mypy_section) for section_name, mypy_section in mypy_tests_conf.items()] + + +@contextmanager +def temporary_mypy_config_file( + configurations: Iterable[MypyDistConf], stubtest_settings: StubtestSettings | None = None +) -> Generator[TemporaryFileWrapper[str]]: + temp = NamedTemporaryFile("w+") + try: + for dist_conf in configurations: + temp.write(f"[mypy-{dist_conf.module_name}]\n") + for k, v in dist_conf.values.items(): + temp.write(f"{k} = {v}\n") + temp.write("[mypy]\n") + + if stubtest_settings: + if stubtest_settings.mypy_plugins: + temp.write(f"plugins = {'.'.join(stubtest_settings.mypy_plugins)}\n") + + if stubtest_settings.mypy_plugins_config: + for plugin_name, plugin_dict in stubtest_settings.mypy_plugins_config.items(): + temp.write(f"[mypy.plugins.{plugin_name}]\n") + for k, v in plugin_dict.items(): + temp.write(f"{k} = {v}\n") + + temp.flush() + yield temp + finally: + temp.close() diff --git a/lib/ts_utils/paths.py b/lib/ts_utils/paths.py new file mode 100644 index 000000000000..3a9a65e32181 --- /dev/null +++ b/lib/ts_utils/paths.py @@ -0,0 +1,41 @@ +from pathlib import Path +from typing import Final + +# TODO: Use base path relative to this file. Currently, ts_utils gets +# installed into the user's virtual env, so we can't determine the path +# to typeshed. Installing ts_utils editable would solve that, see +# https://github.com/python/typeshed/pull/12806. +TS_BASE_PATH: Final = Path() +STDLIB_PATH: Final = TS_BASE_PATH / "stdlib" +STUBS_PATH: Final = TS_BASE_PATH / "stubs" + +PYPROJECT_PATH: Final = TS_BASE_PATH / "pyproject.toml" +REQUIREMENTS_PATH: Final = TS_BASE_PATH / "requirements-tests.txt" +GITIGNORE_PATH: Final = TS_BASE_PATH / ".gitignore" +PYRIGHT_CONFIG: Final = TS_BASE_PATH / "pyrightconfig.stricter.json" + +TESTS_DIR: Final = "@tests" +TEST_CASES_DIR: Final = "test_cases" + + +def distribution_path(distribution_name: str) -> Path: + """Return the path to the directory of a third-party distribution.""" + return STUBS_PATH / distribution_name + + +def tests_path(distribution_name: str) -> Path: + if distribution_name == "stdlib": + return STDLIB_PATH / TESTS_DIR + else: + return STUBS_PATH / distribution_name / TESTS_DIR + + +def test_cases_path(distribution_name: str) -> Path: + return tests_path(distribution_name) / TEST_CASES_DIR + + +def allowlists_path(distribution_name: str) -> Path: + if distribution_name == "stdlib": + return tests_path("stdlib") / "stubtest_allowlists" + else: + return tests_path(distribution_name) diff --git a/lib/ts_utils/py.typed b/lib/ts_utils/py.typed new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/lib/ts_utils/py315.py b/lib/ts_utils/py315.py new file mode 100644 index 000000000000..91eacc100c11 --- /dev/null +++ b/lib/ts_utils/py315.py @@ -0,0 +1,18 @@ +"""Helpers for Python 3.15 test infrastructure.""" + +# These stubs require runtime dependencies that do not install cleanly on Python 3.15 yet. +PY315_INCOMPATIBLE_RUNTIME_DEPENDENCIES = { + # Depend on numpy, which does not provide Python 3.15 wheels yet. + "JACK-Client", + "geopandas", + "hnswlib", + "networkx", + "pycocotools", + "pyogrio", + "resampy", + "shapely", + "tensorflow", + # Depends on matplotlib, which depends on contourpy. contourpy does not + # provide Python 3.15 wheels yet. + "seaborn", +} diff --git a/lib/ts_utils/requirements.py b/lib/ts_utils/requirements.py new file mode 100644 index 000000000000..e592bd73ad54 --- /dev/null +++ b/lib/ts_utils/requirements.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import itertools +import os +import sys +from collections.abc import Iterable + +from packaging.requirements import Requirement + +from ts_utils.metadata import read_dependencies, read_stubtest_settings +from ts_utils.paths import STUBS_PATH + + +def get_external_stub_requirements(distributions: Iterable[str] = ()) -> set[Requirement]: + if not distributions: + distributions = os.listdir(STUBS_PATH) + + return set(itertools.chain.from_iterable([read_dependencies(distribution).external_pkgs for distribution in distributions])) + + +def get_stubtest_system_requirements(distributions: Iterable[str] = (), platform: str = sys.platform) -> set[str]: + if not distributions: + distributions = os.listdir(STUBS_PATH) + + return set( + itertools.chain.from_iterable( + [read_stubtest_settings(distribution).system_requirements_for_platform(platform) for distribution in distributions] + ) + ) diff --git a/lib/ts_utils/stubs.py b/lib/ts_utils/stubs.py new file mode 100644 index 000000000000..ae09ae27c554 --- /dev/null +++ b/lib/ts_utils/stubs.py @@ -0,0 +1,80 @@ +"""Stub file discovery.""" + +from functools import cached_property +from pathlib import Path + +from ts_utils.paths import STDLIB_PATH, STUBS_PATH, TESTS_DIR, distribution_path +from ts_utils.utils import parse_stdlib_versions_file + + +class StubFile: + """Base class for stub files.""" + + def __init__(self, path: Path) -> None: + self.path = path + + def __fspath__(self) -> str: + return self.path.__fspath__() + + def __str__(self) -> str: + return str(self.path) + + @cached_property + def module_name(self) -> str: + return ".".join(self.module_parts) + + @cached_property + def module_parts(self) -> tuple[str, ...]: + raise NotImplementedError + + +class StdlibStubFile(StubFile): + """A stdlib stub file.""" + + @cached_property + def module_parts(self) -> tuple[str, ...]: + relative = self.path.relative_to(STDLIB_PATH) + parts = list(relative.parts[:-1]) + if relative.name != "__init__.pyi": + parts.append(relative.stem) + return tuple(parts) + + +class ThirdPartyStubFile(StubFile): + """A third-party stub file.""" + + @cached_property + def upstream_distribution(self) -> str: + return self.path.relative_to(STUBS_PATH).parts[0] + + @cached_property + def module_parts(self) -> tuple[str, ...]: + relative = self.path.relative_to(STUBS_PATH) + parts = list(relative.parts[1:-1]) + if relative.name != "__init__.pyi": + parts.append(relative.stem) + return tuple(parts) + + +def stdlib_stubs(version: str) -> list[StdlibStubFile]: + """Return the stdlib stubs available for the requested Python version.""" + module_versions = parse_stdlib_versions_file() + stubs = (StdlibStubFile(path) for path in path_stubs(STDLIB_PATH)) + return [stub for stub in stubs if module_versions.is_supported(stub.module_name, version)] + + +def third_party_stubs(distribution: str | None = None) -> list[ThirdPartyStubFile]: + """Return third-party stubs. + + If distribution is None, return all third-party stubs. Otherwise, + return only stubs for the given distribution. + """ + stub_path = distribution_path(distribution) if distribution else STUBS_PATH + return [ThirdPartyStubFile(path) for path in path_stubs(stub_path)] + + +def path_stubs(path: Path) -> list[Path]: + """Return paths to all stub files in a certain path.""" + if path.is_file(): + return [path] if path.suffix == ".pyi" and TESTS_DIR not in path.parts else [] + return sorted(p for p in path.rglob("*.pyi") if TESTS_DIR not in p.parts) diff --git a/lib/ts_utils/utils.py b/lib/ts_utils/utils.py new file mode 100644 index 000000000000..d72f2abefd3c --- /dev/null +++ b/lib/ts_utils/utils.py @@ -0,0 +1,298 @@ +"""Utilities that are imported by multiple scripts in the tests directory.""" + +from __future__ import annotations + +import functools +import re +import sys +import tempfile +from collections.abc import Iterable, Mapping +from pathlib import Path +from types import MethodType +from typing import TYPE_CHECKING, Any, Final, NamedTuple, TypeAlias + +import pathspec +from packaging.requirements import Requirement + +from .paths import GITIGNORE_PATH, REQUIREMENTS_PATH, STDLIB_PATH, STUBS_PATH, TEST_CASES_DIR, allowlists_path, test_cases_path + +if TYPE_CHECKING: + from _typeshed import OpenTextMode + +try: + from termcolor import colored as colored # pyright: ignore[reportAssignmentType] +except ImportError: + + def colored(text: str, color: str | None = None, **kwargs: Any) -> str: # type: ignore[misc] # noqa: ARG001 + return text + + +_REMOVE_COMMENT_RE = re.compile( + r""" + (\"(?:\\.|[^\\\"])*?\") # matches literal strings + | + (\/\*.*?\*\/ | \/\/[^\r\n]*?(?:[\r\n])) # matches single- and multi-line comments + """, + re.DOTALL | re.VERBOSE, +) +_REMOVE_TRAILING_COMMA_RE = re.compile( + r""" + (\"(?:\\.|[^\\\"])*?\") # matches literal strings + | + ,\s*([\]}]) # matches commas before '}' or ']' + """, + re.DOTALL | re.VERBOSE, +) + + +PYTHON_VERSION: Final = f"{sys.version_info.major}.{sys.version_info.minor}" + + +def strip_comments(text: str) -> str: + return text.split("#", maxsplit=1)[0].strip() + + +def jsonc_to_json(text: str) -> str: + """Conversion from JSONC format input to valid JSON.""" + # Remove comments + if not text.endswith("\n"): + text += "\n" + text = _REMOVE_COMMENT_RE.sub(lambda m: m.group(1) or "", text) + + # Remove trailing commas before } or ] + text = _REMOVE_TRAILING_COMMA_RE.sub(lambda m: m.group(1) or m.group(2), text) + return text + + +# ==================================================================== +# Printing utilities +# ==================================================================== + + +def print_command(cmd: str | Iterable[str]) -> None: + if not isinstance(cmd, str): + cmd = " ".join(cmd) + print(colored(f"Running: {cmd}", "blue")) + + +def print_info(message: str) -> None: + print(colored(message, "blue")) + + +def print_warning(message: str) -> None: + print(colored(message, "yellow")) + + +def print_skipped(message: str) -> None: + print(colored(message, "yellow")) + + +def print_error(error: str, end: str = "\n", fix_path: tuple[str, str] = ("", "")) -> None: + error_split = error.split("\n") + old, new = fix_path + for line in error_split[:-1]: + print(colored(line.replace(old, new), "red")) + print(colored(error_split[-1], "red"), end=end) + + +def print_success_msg() -> None: + print(colored("success", "green")) + + +def print_divider() -> None: + """Print a row of * symbols across the screen. + + This can be useful to divide terminal output into separate sections. + """ + print() + print("*" * 70) + print() + + +def print_time(t: float) -> None: + print(f"({t:.2f} s) ", end="") + + +# ==================================================================== +# Dynamic venv creation +# ==================================================================== + + +@functools.cache +def venv_python(venv_dir: Path) -> Path: + if sys.platform == "win32": + return venv_dir / "Scripts" / "python.exe" + return venv_dir / "bin" / "python" + + +# ==================================================================== +# Parsing the requirements file +# ==================================================================== + + +@functools.cache +def parse_requirements() -> Mapping[str, Requirement]: + """Return a dictionary of requirements from the requirements file.""" + with REQUIREMENTS_PATH.open(encoding="UTF-8") as requirements_file: + stripped_lines = map(strip_comments, requirements_file) + stripped_more = [li for li in stripped_lines if not li.startswith("-")] + requirements = map(Requirement, filter(None, stripped_more)) + return {requirement.name: requirement for requirement in requirements} + + +def get_mypy_req() -> str: + return str(parse_requirements()["mypy"]) + + +# ==================================================================== +# Parsing the stdlib/VERSIONS file +# ==================================================================== + +VersionTuple: TypeAlias = tuple[int, int] + +VERSIONS_PATH = STDLIB_PATH / "VERSIONS" +VERSION_LINE_RE = re.compile(r"^([a-zA-Z_][a-zA-Z0-9_.]*): ([23]\.\d{1,2})-([23]\.\d{1,2})?$") +VERSION_RE = re.compile(r"^([23])\.(\d+)$") + + +class SupportedVersions: + def __init__(self, module_versions: dict[str, tuple[VersionTuple, VersionTuple]]) -> None: + self.module_versions = module_versions + + def supported_versions_for_module(self, module_name: str) -> tuple[VersionTuple, VersionTuple]: + while "." in module_name: + if module_name in self.module_versions: + return self.module_versions[module_name] + module_name = ".".join(module_name.split(".")[:-1]) + return self.module_versions[module_name] + + def is_supported(self, module_name: str, version: str) -> bool: + version_tuple = tuple(map(int, version.split("."))) + minimum, maximum = self.supported_versions_for_module(module_name) + return minimum <= version_tuple <= maximum + + +def parse_stdlib_versions_file() -> SupportedVersions: + result: dict[str, tuple[VersionTuple, VersionTuple]] = {} + with VERSIONS_PATH.open(encoding="UTF-8") as f: + for line in f: + stripped_line = strip_comments(line) + if stripped_line == "": + continue + m = VERSION_LINE_RE.match(stripped_line) + assert m, f"invalid VERSIONS line: {stripped_line}" + mod: str = m.group(1) + assert mod not in result, f"Duplicate module {mod} in VERSIONS" + min_version = _parse_version(m.group(2)) + max_version = _parse_version(m.group(3)) if m.group(3) else (99, 99) + result[mod] = min_version, max_version + return SupportedVersions(result) + + +def _parse_version(v_str: str) -> tuple[int, int]: + m = VERSION_RE.match(v_str) + assert m, f"invalid version: {v_str}" + return int(m.group(1)), int(m.group(2)) + + +# ==================================================================== +# Test Directories +# ==================================================================== + + +class DistributionTests(NamedTuple): + name: str + test_cases_path: Path + + @property + def is_stdlib(self) -> bool: + return self.name == "stdlib" + + +def distribution_info(distribution_name: str) -> DistributionTests: + if distribution_name == "stdlib": + return DistributionTests("stdlib", test_cases_path("stdlib")) + test_path = test_cases_path(distribution_name) + if test_path.is_dir(): + if not list(test_path.iterdir()): + raise RuntimeError(f"{distribution_name!r} has a '{TEST_CASES_DIR}' directory but it is empty!") + return DistributionTests(distribution_name, test_path) + raise RuntimeError(f"No test cases found for {distribution_name!r}!") + + +def get_all_testcase_directories() -> list[DistributionTests]: + testcase_directories: list[DistributionTests] = [] + for distribution_path in STUBS_PATH.iterdir(): + try: + pkg_info = distribution_info(distribution_path.name) + except RuntimeError: + continue + testcase_directories.append(pkg_info) + return [distribution_info("stdlib"), *sorted(testcase_directories)] + + +def allowlists(distribution_name: str) -> list[str]: + prefix = "" if distribution_name == "stdlib" else "stubtest_allowlist_" + version_id = f"py{sys.version_info.major}{sys.version_info.minor}" + + platform_allowlist = f"{prefix}{sys.platform}.txt" + version_allowlist = f"{prefix}{version_id}.txt" + combined_allowlist = f"{prefix}{sys.platform}-{version_id}.txt" + local_version_allowlist = version_allowlist + ".local" + + if distribution_name == "stdlib": + return ["common.txt", platform_allowlist, version_allowlist, combined_allowlist, local_version_allowlist] + else: + return ["stubtest_allowlist.txt", platform_allowlist] + + +# Re-exposing as a public name to avoid many pyright reportPrivateUsage +TemporaryFileWrapper = tempfile._TemporaryFileWrapper # pyright: ignore[reportPrivateUsage] + +# We need to work around a limitation of tempfile.NamedTemporaryFile on Windows +# For details, see https://github.com/python/typeshed/pull/13620#discussion_r1990185997 +# Python 3.12 added a cross-platform solution with `tempfile.NamedTemporaryFile("w+", delete_on_close=False)` +if sys.platform != "win32": + NamedTemporaryFile = tempfile.NamedTemporaryFile # noqa: TID251 +else: + + def NamedTemporaryFile(mode: OpenTextMode) -> TemporaryFileWrapper[str]: # noqa: N802 + def close(self: TemporaryFileWrapper[str]) -> None: + TemporaryFileWrapper.close(self) # pyright: ignore[reportUnknownMemberType] + Path(self.name).unlink() + + temp = tempfile.NamedTemporaryFile(mode, delete=False) # noqa: SIM115, TID251 + temp.close = MethodType(close, temp) # type: ignore[method-assign] + return temp + + +# ==================================================================== +# Parsing .gitignore +# ==================================================================== + + +@functools.cache +def get_gitignore_spec() -> pathspec.GitIgnoreSpec: + with GITIGNORE_PATH.open(encoding="UTF-8") as f: + return pathspec.GitIgnoreSpec.from_lines(f) + + +def spec_matches_path(spec: pathspec.PathSpec[Any], path: Path) -> bool: + normalized_path = path.as_posix() + if path.is_dir(): + normalized_path += "/" + return spec.match_file(normalized_path) + + +# ==================================================================== +# stubtest call +# ==================================================================== + + +def allowlist_stubtest_arguments(distribution_name: str) -> list[str]: + stubtest_arguments: list[str] = [] + for allowlist in allowlists(distribution_name): + path = allowlists_path(distribution_name) / allowlist + if path.exists(): + stubtest_arguments.extend(["--allowlist", str(path)]) + return stubtest_arguments diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000000..c3a4fe66b780 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,283 @@ +[project] +# This section is needed to avoid writing --no-project everytime when using "uv run" +# https://github.com/astral-sh/uv/issues/8666 +name = "typeshed" +version = "0" +requires-python = ">=3.10" # Minimum version to run tests, used by uv run + +[tool.black] +line-length = 130 +target-version = ["py310"] +skip-magic-trailing-comma = true +preview = true + +# Override `exclude` so that the `stdlib/venv` directory is not excluded +# if you invoke Black "manually" (not using pre-commit). `venv` is one of +# the directories that Black excludes by default if `tool.black.exclude` +# is not set. See https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#exclude +exclude = ''' +/( + \.env| + \.venv| + env| + \.git| + \.mypy_cache +)/ +''' + +[tool.ruff] +line-length = 130 +fix = true + +# Override `exclude` so that the `stdlib/venv` directory is not excluded +# if you invoke Ruff "manually" (not using pre-commit). `venv` is one of +# the directories that Ruff excludes by default if `tool.ruff.exclude` +# is not set. See https://docs.astral.sh/ruff/configuration/ +exclude = [ + # virtual environment + ".env", + ".venv", + "env", + # cache directories, etc.: + ".git", + ".mypy_cache", +] + +[tool.ruff.lint] +future-annotations = true +# Disable all rules on test cases by default: +# test cases often deliberately contain code +# that might not be considered idiomatic or modern. +# +# Note: some rules that are specifically useful to the test cases +# are invoked via separate runs of ruff in pre-commit: +# see our .pre-commit-config.yaml file for details +exclude = ["**/test_cases/**/*.py"] +# We still use flake8-pyi to check these (see .flake8 config file); +# tell ruff not to flag these as e.g. "unused noqa comments" +external = ["F821", "Y"] +select = [ + "A", # flake8-builtins + "ARG", # flake8-unused-arguments + "B", # flake8-bugbear + "C4", # flake8-comprehensions + "D", # pydocstyle + "DTZ", # flake8-datetimez + "EXE", # flake8-executable + "FA", # flake8-future-annotations + "FBT", # flake8-boolean-trap + "FLY", # flynt + "I", # isort + "N", # pep8-naming + "PGH", # pygrep-hooks + "PIE", # flake8-pie + "PL", # Pylint + "PTH", # flake8-use-pathlib + "RSE", # flake8-raise + "RUF", # Ruff-specific and unused-noqa + "SLOT", # flake8-slots + "T10", # flake8-debugger + "TD", # flake8-todos + "TRY", # tryceratops + "UP", # pyupgrade + "YTT", # flake8-2020 + # Flake8 base rules + "E", # pycodestyle Error + "F", # Pyflakes + "W", # pycodestyle Warning + # Only include flake8-annotations rules that are autofixable. Otherwise leave this to mypy+pyright + "ANN2", + # Most refurb rules are in preview and can be opinionated, + # consider them individually as they come out of preview (last check: 0.13.1) + "FURB105", # Unnecessary empty string passed to `print` + "FURB116", # Replace `{function_name}` call with `{display}` + "FURB122", # Use of `{}.write` in a for loop + "FURB129", # Instead of calling `readlines()`, iterate over file object directly + "FURB132", # Use `{suggestion}` instead of `check` and `remove` + "FURB136", # Replace `if` expression with `{min_max}` call + "FURB157", # Verbose expression in `Decimal` constructor + "FURB162", # Unnecessary timezone replacement with zero offset + "FURB166", # Use of `int` with explicit `base={base}` after removing prefix + "FURB167", # Use of regular expression alias `re.{}` + "FURB168", # Prefer `is` operator over `isinstance` to check if an object is `None` + "FURB169", # Compare the identities of `{object}` and None instead of their respective types + "FURB177", # Prefer `Path.cwd()` over `Path().resolve()` for current-directory lookups + "FURB187", # Use of assignment of `reversed` on list `{name}` + "FURB188", # Prefer `str.removeprefix()` over conditionally replacing with slice. + # Used for lint.flake8-import-conventions.aliases + "ICN001", # `{name}` should be imported as `{asname}` + # PYI: only enable rules that have autofixes and that we always want to fix (even manually), + # avoids duplicate # noqa with flake8-pyi + "PYI009", # Empty body should contain `...`, not pass + "PYI010", # Function body must contain only `...` + "PYI012", # Class bodies must not contain `pass` + "PYI013", # Non-empty class bodies must not contain `...` + "PYI014", # Only simple default values allowed for arguments + "PYI015", # Only simple default values allowed for assignments + "PYI016", # Duplicate union member `{}` + "PYI018", # Private `{type_var_like_kind}` `{type_var_like_name}` is never used + "PYI019", # Methods like `{method_name}` should return `Self` instead of a custom `TypeVar` + "PYI020", # Quoted annotations should not be included in stubs + "PYI025", # Use `from collections.abc import Set as AbstractSet` to avoid confusion with the `set` builtin + # "PYI026", Waiting for this mypy bug to be fixed: https://github.com/python/mypy/issues/16581 + "PYI030", # Multiple literal members in a union. Use a single literal, e.g. `Literal[{}]` + "PYI032", # Prefer `object` to `Any` for the second parameter to `{method_name}` + "PYI036", # Star-args in `{method_name}` should be annotated with `object` + "PYI044", # `from __future__ import annotations` has no effect in stub files, since type checkers automatically treat stubs as having those semantics + "PYI055", # Multiple `type[T]` usages in a union. Combine them into one, e.g., `type[{union_str}]`. + "PYI058", # Use `{return_type}` as the return value for simple `{method}` methods + "PYI059", # Checks for classes inheriting from typing.Generic[] where Generic[] is not the last base class in the bases tuple + "PYI061", # Use `None` rather than `Literal[None]` + "PYI062", # Duplicate literal member `{}` + "PYI064", # `Final[Literal[{literal}]]` can be replaced with a bare Final + # flake8-simplify, excluding rules that can reduce performance or readability due to long line formatting + "SIM101", # Multiple `isinstance` calls for `{name}`, merge into a single call + "SIM103", # Return the condition `{condition}` directly + "SIM107", # Don't use return in `try-except` and `finally` + "SIM109", # Use `{replacement}` instead of multiple equality comparisons + "SIM112", # Use capitalized environment variable `{expected}` instead of `{actual}` + "SIM113", # Use `enumerate()` for index variable `{index}` in `for` loop + "SIM114", # Combine `if` branches using logical `or` operator + "SIM115", # Use a context manager for opening files + "SIM118", # Use key `{operator}` dict instead of key `{operator} dict.keys()` + "SIM201", # Use `{left} != {right}` instead of not `{left} == {right}` + "SIM202", # Use `{left} == {right}` instead of not `{left} != {right}` + "SIM208", # Use `{expr}` instead of `not (not {expr})` + "SIM210", # Remove unnecessary `True if ... else False` + "SIM211", # Use `not ...` instead of `False if ... else True` + "SIM212", # Use `{expr_else} if {expr_else} else {expr_body}` instead of `{expr_body} if not {expr_else} else {expr_else}` + "SIM220", # Use `False` instead of `{name} and not {name}` + "SIM221", # Use `True` instead of `{name} or not {name}` + "SIM222", # Use `{expr}` instead of `{replaced}` + "SIM223", # Use `{expr}` instead of `{replaced}` + "SIM300", # Yoda condition detected + "SIM401", # Use `{contents}` instead of an if block + "SIM905", # Consider using a list literal instead of `str.{}` + "SIM910", # Use `{expected}` instead of `{actual}` (dict-get-with-none-default) + "SIM911", # Use `{expected}` instead of `{actual}` (zip-dict-keys-and-values) + # Don't include TC rules that create a TYPE_CHECKING block or stringifies annotations + "TC004", # Move import `{qualified_name}` out of type-checking block. Import is used for more than type hinting. + "TC005", # Found empty type-checking block + # "TC008", # TODO: Enable when out of preview + "TC010", # Invalid string member in `X | Y`-style union type + # Used for lint.flake8-import-conventions.aliases + "TID251", # `{name}` is banned: {message} +] +extend-safe-fixes = [ + "UP036", # Remove unnecessary `sys.version_info` blocks +] +ignore = [ + ### + # Rules that can conflict with the formatter (Black) + # https://docs.astral.sh/ruff/formatter/#conflicting-lint-rules + ### + "E111", # indentation-with-invalid-multiple + "E114", # indentation-with-invalid-multiple-comment + "E117", # over-indented + "W191", # tab-indentation + ### + # Rules we don't want or don't agree with + ### + # We're not a library, no need to document everything + "D1", # Missing docstring in ... + # Sometimes, an extra blank line is more readable + "D202", # No blank lines allowed after function docstring + # Doesn't support split "summary line" + "D205", # 1 blank line required between summary line and description + # Used for direct, non-subclass type comparison, for example: `type(val) is str` + # see https://github.com/astral-sh/ruff/issues/6465 + "E721", # Do not compare types, use `isinstance()` + # Highly opinionated, and it's often necessary to violate it + "PLC0415", # `import` should be at the top-level of a file + # Leave the size and complexity of tests to human interpretation + "PLR09", # Too many ... + # Too many magic number "2" that are preferable inline. https://github.com/astral-sh/ruff/issues/10009 + "PLR2004", # Magic value used in comparison, consider replacing `{value}` with a constant variable + # Keep codeflow path separation explicit + "PLR5501", # Use `elif` instead of `else` then `if`, to reduce indentation + # Often just leads to redundant more verbose code when needing an actual str + "PTH208", # Use `pathlib.Path.iterdir()` instead. + # Allow FIXME + "TD001", # Invalid TODO tag: `{tag}` + # Git blame is sufficient + "TD002", # Missing author in TODO; + "TD003", # Missing issue link for this TODO + # Mostly from scripts and tests, it's ok to have messages passed directly to exceptions + "TRY003", # Avoid specifying long messages outside the exception class + ### + # False-positives, but already checked by type-checkers + ### + # Ruff doesn't support multi-file analysis yet: https://github.com/astral-sh/ruff/issues/5295 + "RUF013", # PEP 484 prohibits implicit `Optional` +] + +[tool.ruff.lint.per-file-ignores] +"*.pyi" = [ + # A lot of stubs are incomplete on purpose, and that's configured through pyright + # Some ANN204 (special method) are autofixable in stubs, but not all. + "ANN2", # Missing return type annotation for ... + # Ruff 0.8.0 added sorting of __all__ and __slots_. + # There is no consensus on whether we want to apply this to stubs, so keeping the status quo. + # See https://github.com/python/typeshed/pull/13108 + "RUF022", # `__all__` is not sorted + "RUF023", # `{}.__slots__` is not sorted + ### + # Rules that are out of the control of stub authors: + ### + # Names in stubs should match the implementation, even if it's ambiguous. + # https://github.com/astral-sh/ruff/issues/15293 + "A", # flake8-builtins + # Stubs can sometimes re-export entire modules. + # Issues with using a star-imported name will be caught by type-checkers. + "F403", # `from . import *` used; unable to detect undefined names + "F405", # may be undefined, or defined from star imports + # Most pep8-naming rules don't apply for third-party stubs like typeshed. + # N811 to N814 could apply, but we often use them to disambiguate a name whilst making it look like a more common one + "N8", # pep8-naming + # Sometimes __slots__ really is a string at runtime + "PLC0205", # Class `__slots__` should be a non-string iterable + # Stubs are allowed to use private variables (pyright's reportPrivateUsage is also disabled) + "PLC2701", # Private name import from external module + # Names in stubs should match implementation + "PLW0211", # First argument of a static method should not be named `{argument_name}` +] +"lib/ts_utils/**" = [ + # Doesn't affect stubs. The only re-exports we have should be in our local lib ts_utils + "PLC0414", # Import alias does not rename original package +] +"*_pb2.pyi" = [ + # Special autogenerated typing --> typing_extensions aliases + "ICN001", # `{name}` should be imported as `{asname}` + # Leave the docstrings as-is, matching source + "D", # pydocstyle + # See comment on black's force-exclude config above + "E501", # Line too long + "UP036", # Remove unnecessary `sys.version_info` blocks +] + +[tool.ruff.lint.pydocstyle] +convention = "pep257" # https://docs.astral.sh/ruff/settings/#lint_pydocstyle_convention + +[tool.ruff.lint.flake8-import-conventions.aliases] +# Prevent aliasing these, as it causes false-negatives for certain rules +typing_extensions = "typing_extensions" +typing = "typing" + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"tempfile.NamedTemporaryFile".msg = "Use `ts_util.util.NamedTemporaryFile` instead." + +[tool.ruff.lint.isort] +split-on-trailing-comma = false +combine-as-imports = true +extra-standard-library = [ + # Group these with stdlib + "_typeshed", + "typing_extensions", + # Extra modules not recognized by Ruff + # Added in Python 3.14 + "compression", +] +known-first-party = ["_utils", "ts_utils"] + +[tool.typeshed] +oldest-supported-python = "3.10" diff --git a/pyrefly.toml b/pyrefly.toml new file mode 100644 index 000000000000..8db32aa4e3a3 --- /dev/null +++ b/pyrefly.toml @@ -0,0 +1,21 @@ +# typeshed uses `# type: ignore` comments to silence mypy and pyright; pyrefly +# should not treat them as suppressing its own errors. Keep in sync with the +# `respect-type-ignore-comments` setting in ty.toml. +enabled-ignores = ["pyrefly"] + +# These imports are intentionally optional and are also ignored by mypy and pyright. +ignore-missing-imports = [ + "branca", + "folium", + "pydot", + "pygraphviz.*", + "scipy.*", + "twisted.*", + "xyzservices", +] + +[errors] +# Incompatible overrides and deprecations are inherited from the implementation +# and are not actionable in typeshed. Keep in sync with pyrightconfig.json. +deprecated = false +bad-override = false diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 000000000000..74ddb65b85f6 --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,48 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "stdlib", + "stubs", + ], + "exclude": [ + // Stubs that don't work in all Python versions + "stubs/seaborn", + "stubs/shapely", + "stubs/geopandas", + // test cases use a custom config file + "**/@tests/test_cases", + ], + "typeCheckingMode": "strict", + // Allowed in base settings for incomplete stubs, checked in stricter settings + "reportIncompleteStub": "none", + "reportMissingParameterType": "none", + "reportUnknownMemberType": "none", + "reportUnknownParameterType": "none", + "reportUnknownVariableType": "none", + // Extra strict settings + "reportCallInDefaultInitializer": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // No effect in stubs + "reportMissingSuperCall": "none", + "reportUninitializedInstanceVariable": "none", + // Stubs are allowed to use private variables + "reportPrivateUsage": "none", + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible overrides and property type mismatches are out of typeshed's control + // as they are inherited from the implementation. + "reportIncompatibleMethodOverride": "none", + "reportIncompatibleVariableOverride": "none", + "reportPropertyTypeMismatch": "none", + // Overlapping overloads are often necessary in a stub, meaning pyright's check + // (which is stricter than mypy's; see mypy issue #10143 and #10157) + // would cause many false positives and catch few bugs. + "reportOverlappingOverload": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", + // Not actionable in typeshed + "reportDeprecated": "none", +} diff --git a/pyrightconfig.scripts_and_tests.json b/pyrightconfig.scripts_and_tests.json new file mode 100644 index 000000000000..f9b093547281 --- /dev/null +++ b/pyrightconfig.scripts_and_tests.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "lib", + "scripts", + "tests", + ], + "extraPaths": [ + "lib", + ], + "typeCheckingMode": "strict", + // More of a lint. Unwanted for typeshed's own code. + "reportImplicitStringConcatenation": "none", + // Extra strict settings + "reportMissingModuleSource": "error", + "reportCallInDefaultInitializer": "error", + "reportPropertyTypeMismatch": "error", + "reportUninitializedInstanceVariable": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // Too strict + "reportMissingSuperCall": "none", +} diff --git a/pyrightconfig.stricter.json b/pyrightconfig.stricter.json new file mode 100644 index 000000000000..3c170f4fba99 --- /dev/null +++ b/pyrightconfig.stricter.json @@ -0,0 +1,137 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "stdlib", + "stubs", + ], + "exclude": [ + // test cases use a custom pyrightconfig file + "**/@tests/test_cases", + "stdlib/__main__.pyi", + "stdlib/_operator.pyi", + "stdlib/_tkinter.pyi", + "stdlib/distutils/cmd.pyi", + "stdlib/distutils/command", + "stdlib/distutils/dist.pyi", + "stdlib/encodings/__init__.pyi", + "stdlib/lib2to3/fixes/*.pyi", + "stdlib/numbers.pyi", + "stdlib/operator.pyi", + "stdlib/tkinter/__init__.pyi", + "stdlib/tkinter/dialog.pyi", + "stdlib/tkinter/filedialog.pyi", + "stdlib/tkinter/scrolledtext.pyi", + "stdlib/tkinter/tix.pyi", + "stdlib/tkinter/ttk.pyi", + "stubs/antlr4-python3-runtime", + "stubs/auth0-python", + "stubs/Authlib", + "stubs/aws-xray-sdk", + "stubs/behave", + "stubs/boltons", + "stubs/braintree", + "stubs/cffi", + "stubs/colorful", + "stubs/dateparser", + "stubs/defusedxml", + "stubs/docker", + "stubs/docutils", + "stubs/Flask-SocketIO", + "stubs/fpdf2", + "stubs/gdb", + "stubs/geojson", + "stubs/geopandas", + "stubs/google-cloud-ndb", + "stubs/grpcio-channelz/grpc_channelz/v1", + "stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi", + "stubs/grpcio-reflection/grpc_reflection/v1alpha", + "stubs/grpcio-status/grpc_status", + "stubs/grpcio/grpc/__init__.pyi", + "stubs/gunicorn/gunicorn/dirty", + "stubs/hdbcli/hdbcli/dbapi.pyi", + "stubs/html5lib", + "stubs/httplib2", + "stubs/hvac", + "stubs/icalendar/icalendar/prop.pyi", + "stubs/icalendar/icalendar/timezone/provider.pyi", + "stubs/jsonschema", + "stubs/jwcrypto", + "stubs/kafka-python", + "stubs/ldap3", + "stubs/m3u8/m3u8/model.pyi", + "stubs/Markdown", + "stubs/mock/mock/mock.pyi", + "stubs/mysqlclient", + "stubs/netaddr/netaddr/core.pyi", + "stubs/netaddr/netaddr/ip/__init__.pyi", + "stubs/netaddr/netaddr/ip/iana.pyi", + "stubs/networkx", + "stubs/oauthlib", + "stubs/openpyxl", + "stubs/opentracing/opentracing/span.pyi", + "stubs/paramiko/paramiko/_winapi.pyi", + "stubs/parsimonious/parsimonious/nodes.pyi", + "stubs/peewee", + "stubs/pexpect", + "stubs/pika/pika/adapters/twisted_connection.pyi", + "stubs/pika/pika/adapters/utils/connection_workflow.pyi", + "stubs/pika/pika/callback.pyi", + "stubs/pika/pika/channel.pyi", + "stubs/pony", + "stubs/protobuf", + "stubs/psutil/psutil/__init__.pyi", + "stubs/psycopg2", + "stubs/punq", + "stubs/pyasn1", + "stubs/pycups", + "stubs/Pygments", + "stubs/PyMySQL", + "stubs/pyogrio", + "stubs/python-jose", + "stubs/pywin32", + "stubs/PyYAML", + "stubs/reportlab", + "stubs/requests", + "stubs/requests-oauthlib", + "stubs/seaborn", + "stubs/setuptools/setuptools", + "stubs/shapely", + "stubs/simple-websocket", + "stubs/tensorflow", + "stubs/tqdm", + "stubs/vobject", + "stubs/workalendar", + "stubs/xmldiff", + ], + "typeCheckingMode": "strict", + // TODO: Complete incomplete stubs + "reportIncompleteStub": "none", + // Extra strict settings + "reportCallInDefaultInitializer": "error", + // implicit string concatenation is useful for long deprecation messages + "reportImplicitStringConcatenation": "none", + "reportUnnecessaryTypeIgnoreComment": "error", + // Leave "type: ignore" comments to mypy + "enableTypeIgnoreComments": false, + // No effect in stubs + "reportMissingSuperCall": "none", + "reportUninitializedInstanceVariable": "none", + // Stubs are allowed to use private variables + "reportPrivateUsage": "none", + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible overrides and property type mismatches are out of typeshed's control + // as they are inherited from the implementation. + "reportIncompatibleMethodOverride": "none", + "reportIncompatibleVariableOverride": "none", + "reportPropertyTypeMismatch": "none", + // Overlapping overloads are often necessary in a stub, meaning pyright's check + // (which is stricter than mypy's; see mypy issue #10143 and #10157) + // would cause many false positives and catch few bugs. + "reportOverlappingOverload": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", + // Not actionable in typeshed + "reportDeprecated": "none", +} diff --git a/pyrightconfig.testcases.json b/pyrightconfig.testcases.json new file mode 100644 index 000000000000..ab1cb86b9900 --- /dev/null +++ b/pyrightconfig.testcases.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://raw.githubusercontent.com/microsoft/pyright/main/packages/vscode-pyright/schemas/pyrightconfig.schema.json", + "typeshedPath": ".", + "include": [ + "**/@tests/test_cases", + ], + "typeCheckingMode": "strict", + // Extra strict settings + "reportImplicitStringConcatenation": "error", + "reportUninitializedInstanceVariable": "error", + "reportUnnecessaryTypeIgnoreComment": "error", + // Using unspecific `type: ignore` comments in test_cases. + // See https://github.com/python/typeshed/pull/8083 + "enableTypeIgnoreComments": true, + // If a test case uses this anti-pattern, there's likely a reason and annoying to `type: ignore`. + // Let Ruff flag it (B006) + "reportCallInDefaultInitializer": "none", + // Too strict and not needed for type testing + "reportMissingSuperCall": "none", + // Stubs are allowed to use private variables. We may want to test those. + "reportPrivateUsage": "none", + // Stubs don't need the actual modules to be installed + "reportMissingModuleSource": "none", + // Incompatible property type mismatches may be out of typeshed's control + // when they are inherited from the implementation. + "reportPropertyTypeMismatch": "none", + // isinstance checks are still needed when validating inputs outside of typeshed's control + "reportUnnecessaryIsInstance": "none", + // The name of the self/cls parameter is out of typeshed's control. + "reportSelfClsParameterName": "none", +} diff --git a/requirements-tests.txt b/requirements-tests.txt new file mode 100644 index 000000000000..c452aa0a1871 --- /dev/null +++ b/requirements-tests.txt @@ -0,0 +1,26 @@ +# Type checkers that we test our stubs against. These should always +# be pinned to a specific version to make failure reproducible. +mypy==2.3.0 +pyrefly==1.3.0.dev1 +pyright==1.1.411 +ty==0.0.59 + +# Libraries used by our various scripts. +aiohttp==3.14.3 +grpcio-tools>=1.76.0; python_version < "3.15" # For grpc_tools.protoc +mypy-protobuf==5.1.0; python_version < "3.15" +packaging==26.2 +pathspec>=1.1.1 +pre-commit +ruff==0.15.20 +# Required by create_baseline_stubs.py. +# stubdefaulter depends on libcst, which does not yet install cleanly on Python 3.15. +stubdefaulter==0.1.0; python_version < "3.15" +termcolor>=2.3 +tomli==2.4.1; python_version < "3.11" +tomlkit==0.15.0 +typing_extensions>=4.16.0rc2 +uv==0.11.26 + +# Utilities for typeshed infrastructure scripts. +ts_utils @ file:lib diff --git a/scripts/create_baseline_stubs.py b/scripts/create_baseline_stubs.py new file mode 100755 index 000000000000..4d1548e3583e --- /dev/null +++ b/scripts/create_baseline_stubs.py @@ -0,0 +1,255 @@ +#!/usr/bin/env python3 + +"""Script to generate unannotated baseline stubs using stubgen. + +Basic usage: +$ python3 scripts/create_baseline_stubs.py + +Run with -h for more help. +""" + +from __future__ import annotations + +import argparse +import asyncio +import re +import subprocess +import sys +import urllib.parse +from http import HTTPStatus +from importlib.metadata import distribution +from pathlib import Path + +import aiohttp +import termcolor + +from ts_utils.paths import PYRIGHT_CONFIG, STDLIB_PATH, STUBS_PATH + + +def search_pip_freeze_output(project: str, output: str) -> tuple[str, str] | None: + # Look for lines such as "typed-ast==1.4.2". '-' matches '_' and + # '_' matches '-' in project name, so that "typed_ast" matches + # "typed-ast", and vice versa. + regex = "^(" + re.sub(r"[-_]", "[-_]", project) + ")==(.*)" + m = re.search(regex, output, flags=re.IGNORECASE | re.MULTILINE) + if not m: + return None + return m.group(1), m.group(2) + + +def get_installed_package_info(project: str) -> tuple[str, str] | None: + """Find package information from pip freeze output. + + Match project name somewhat fuzzily (case sensitive; '-' matches '_', and + vice versa). + + Return (normalized project name, installed version) if successful. + """ + # Not using "uv pip freeze" because if this is run from a global Python, + # it'll mistakenly list the .venv's packages. + r = subprocess.run(["pip", "freeze"], capture_output=True, text=True, check=True) + return search_pip_freeze_output(project, r.stdout) + + +def run_stubgen(package: str, output: Path) -> None: + print(f"Running stubgen: stubgen -o {output} -p {package}") + subprocess.run(["stubgen", "-o", output, "-p", package, "--export-less"], check=True) + + +def run_stubdefaulter(stub_dir: Path) -> None: + print(f"Running stubdefaulter: stubdefaulter --packages {stub_dir}") + subprocess.run(["stubdefaulter", "--packages", stub_dir], check=False) + + +def run_black(stub_dir: Path) -> None: + print(f"Running Black: black {stub_dir}") + subprocess.run(["pre-commit", "run", "black", "--files", *stub_dir.rglob("*.pyi")], check=False) + + +def run_ruff(stub_dir: Path) -> None: + print(f"Running Ruff: ruff check {stub_dir} --fix-only") + subprocess.run([sys.executable, "-m", "ruff", "check", stub_dir, "--fix-only"], check=False) + + +async def get_project_urls_from_pypi(project: str, session: aiohttp.ClientSession) -> dict[str, str]: + pypi_root = f"https://pypi.org/pypi/{urllib.parse.quote(project)}" + async with session.get(f"{pypi_root}/json") as response: + if response.status != HTTPStatus.OK: + return {} + j: dict[str, dict[str, dict[str, str]]] + j = await response.json() + return j["info"].get("project_urls") or {} + + +async def get_upstream_repo_url(project: str) -> str | None: + # aiohttp is overkill here, but it would also just be silly + # to have both requests and aiohttp in our requirements-tests.txt file. + async with aiohttp.ClientSession() as session: + project_urls = await get_project_urls_from_pypi(project, session) + + if not project_urls: + return None + + # Order the project URLs so that we put the ones + # that are most likely to point to the source code first + urls_to_check: list[str] = [] + url_names_probably_pointing_to_source = ("Source", "Repository", "Homepage") + for url_name in url_names_probably_pointing_to_source: + if url := project_urls.get(url_name): + urls_to_check.append(url) + urls_to_check.extend( + url for url_name, url in project_urls.items() if url_name not in url_names_probably_pointing_to_source + ) + + for url_to_check in urls_to_check: + # Remove `www.`; replace `http://` with `https://` + url = re.sub(r"^(https?://)?(www\.)?", "https://", url_to_check) + netloc = urllib.parse.urlparse(url).netloc + if netloc not in {"gitlab.com", "github.com", "bitbucket.org", "foss.heptapod.net"}: + continue + # truncate to https://site.com/user/repo + upstream_repo_url = "/".join(url.split("/")[:5]) + async with session.get(upstream_repo_url, allow_redirects=True) as response: + if response.status != HTTPStatus.OK: + continue + # final url after redirects + final_url = str(response.url) + # normalize again (in case redirect added extra path) + final_repo_url = "/".join(final_url.split("/")[:5]) + return final_repo_url + return None + + +def create_metadata(project: str, stub_dir: Path, version: str) -> None: + """Create a METADATA.toml file.""" + match = re.match(r"[0-9]+.[0-9]+", version) + if match is None: + sys.exit(f"Error: Cannot parse version number: {version}") + filename = stub_dir / "METADATA.toml" + version = match.group(0) + if filename.exists(): + return + metadata = f'version = "{version}.*"\n' + upstream_repo_url = asyncio.run(get_upstream_repo_url(project)) + if upstream_repo_url is None: + warning = ( + f"\nCould not find a URL pointing to the source code for {project!r}.\n" + f"Please add it as `upstream-repository` to `stubs/{project}/METADATA.toml`, if possible!\n" + ) + print(termcolor.colored(warning, "red")) + else: + metadata += f'upstream-repository = "{upstream_repo_url}"\n' + print(f"Writing {filename}") + filename.write_text(metadata, encoding="UTF-8") + + +def add_pyright_exclusion(stub_dir: Path) -> None: + """Exclude stub_dir from strict pyright checks.""" + with PYRIGHT_CONFIG.open(encoding="UTF-8") as f: + lines = f.readlines() + i = 0 + while i < len(lines) and not lines[i].strip().startswith('"exclude": ['): + i += 1 + assert i < len(lines), f"Error parsing {PYRIGHT_CONFIG}" + while not lines[i].strip().startswith("]"): + i += 1 + end = i + + # We assume that all third-party excludes must be at the end of the list. + # This helps with skipping special entries, such as "stubs/**/@tests/test_cases". + while lines[i - 1].strip().startswith('"stubs/'): + i -= 1 + start = i + + before_third_party_excludes = lines[:start] + third_party_excludes = lines[start:end] + after_third_party_excludes = lines[end:] + + last_line = third_party_excludes[-1].rstrip() + if not last_line.endswith(","): + last_line += "," + third_party_excludes[-1] = last_line + "\n" + + # Must use forward slash in the .json file + line_to_add = f' "{stub_dir.as_posix()}",\n' + + if line_to_add in third_party_excludes: + print(f"{PYRIGHT_CONFIG} already up-to-date") + return + + third_party_excludes.append(line_to_add) + third_party_excludes.sort(key=str.lower) + + print(f"Updating {PYRIGHT_CONFIG}") + with PYRIGHT_CONFIG.open("w", encoding="UTF-8") as f: + f.writelines(before_third_party_excludes) + f.writelines(third_party_excludes) + f.writelines(after_third_party_excludes) + + +def main() -> None: + parser = argparse.ArgumentParser(description="""Generate baseline stubs automatically for an installed pip package + using stubgen. Also run Black and Ruff. If the name of + the project is different from the runtime Python package name, you may + need to use --package (example: --package yaml PyYAML).""") + parser.add_argument("project", help="name of PyPI project for which to generate stubs under stubs/") + parser.add_argument("--package", help="generate stubs for this Python package (default is autodetected)") + args = parser.parse_args() + project = args.project + package: str = args.package + + if not re.match(r"[a-zA-Z0-9-_.]+$", project): + sys.exit(f"Invalid character in project name: {project!r}") + + if not package: + package = project # default + # Try to find which packages are provided by the project + # Use default if that fails or if several packages are found + # + # The importlib.metadata module is used for projects whose name is different + # from the runtime Python package name (example: PyYAML/yaml) + dist = distribution(project).read_text("top_level.txt") + if dist is not None: + packages = [name for name in dist.split() if not name.startswith("_")] + if len(packages) == 1: + package = packages[0] + print(f'Using detected package "{package}" for project "{project}"', file=sys.stderr) + print("Suggestion: Try again with --package argument if that's not what you wanted", file=sys.stderr) + + if not STUBS_PATH.is_dir() or not STDLIB_PATH.is_dir(): + sys.exit("Error: Current working directory must be the root of typeshed repository") + + # Get normalized project name and version of installed package. + info = get_installed_package_info(project) + if info is None: + print(f'Error: "{project}" is not installed', file=sys.stderr) + print(file=sys.stderr) + print(f"Suggestion: Run `{sys.executable} -m pip install {project}` and try again", file=sys.stderr) + sys.exit(1) + project, version = info + + stub_dir = STUBS_PATH / project + package_dir = stub_dir / package + if package_dir.exists(): + sys.exit(f"Error: {package_dir} already exists (delete it first)") + + run_stubgen(package, stub_dir) + run_stubdefaulter(stub_dir) + + run_ruff(stub_dir) + run_black(stub_dir) + + create_metadata(project, stub_dir, version) + + # Since the generated stubs won't have many type annotations, we + # have to exclude them from strict pyright checks. + add_pyright_exclusion(stub_dir) + + print("\nDone!\n\nSuggested next steps:") + print(f" 1. Manually review the generated stubs in {stub_dir}") + print(" 2. Optionally run tests and autofixes (see tests/README.md for details)") + print(" 3. Commit the changes on a new branch and create a typeshed PR (don't force-push!)") + + +if __name__ == "__main__": + main() diff --git a/scripts/install_all_third_party_dependencies.py b/scripts/install_all_third_party_dependencies.py new file mode 100644 index 000000000000..ca1b7075589f --- /dev/null +++ b/scripts/install_all_third_party_dependencies.py @@ -0,0 +1,15 @@ +import subprocess +import sys + +from ts_utils.requirements import get_external_stub_requirements + + +def main() -> None: + requirements = get_external_stub_requirements() + # By forwarding arguments, we naturally allow non-venv (system installs) + # by letting the script's user follow uv's own helpful hint of passing the `--system` flag. + subprocess.check_call(["uv", "pip", "install", *sys.argv[1:], *[str(requirement) for requirement in requirements]]) + + +if __name__ == "__main__": + main() diff --git a/scripts/stubsabot.py b/scripts/stubsabot.py new file mode 100755 index 000000000000..293a6420d09d --- /dev/null +++ b/scripts/stubsabot.py @@ -0,0 +1,1050 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import asyncio +import calendar +import contextlib +import datetime +import enum +import functools +import io +import os +import re +import shutil +import subprocess +import sys +import tarfile +import textwrap +import urllib.parse +import zipfile +from collections.abc import Callable, Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from http import HTTPStatus +from pathlib import Path +from typing import Annotated, Any, ClassVar, Literal, NamedTuple, TypeAlias, TypedDict, TypeVar, cast +from typing_extensions import Self + +if sys.version_info >= (3, 11): + import tomllib +else: + import tomli as tomllib + +import aiohttp +import packaging.version +import tomlkit +from packaging.specifiers import Specifier +from termcolor import colored + +from ts_utils.metadata import ObsoleteMetadata, StubMetadata, read_metadata, update_metadata +from ts_utils.paths import PYRIGHT_CONFIG, STUBS_PATH, distribution_path +from ts_utils.stubs import third_party_stubs + +TYPESHED_OWNER = "python" +TYPESHED_API_URL = f"https://api.github.com/repos/{TYPESHED_OWNER}/typeshed" + +STUBSABOT_LABEL = "bot: stubsabot" + +POLICY_MONTHS_DELTA = 6 + + +class ActionLevel(enum.IntEnum): + def __new__(cls, value: int, doc: str) -> Self: + member = int.__new__(cls, value) + member._value_ = value + member.__doc__ = doc + return member + + @classmethod + def from_cmd_arg(cls, cmd_arg: str) -> ActionLevel: + try: + return cls[cmd_arg] + except KeyError: + raise argparse.ArgumentTypeError(f'Argument must be one of "{list(cls.__members__)}"') from None + + nothing = 0, "make no changes" + local = 1, "make changes that affect local repo" + fork = 2, "make changes that affect remote repo, but won't open PRs against upstream" + everything = 3, "do everything, e.g. open PRs" + + +@dataclass +class PypiReleaseDownload: + distribution: str + url: str + packagetype: Annotated[str, "Should hopefully be either 'bdist_wheel' or 'sdist'"] + filename: str + version: packaging.version.Version + upload_date: datetime.datetime + + +VersionString: TypeAlias = str +ReleaseDownload: TypeAlias = dict[str, Any] + + +def _best_effort_version(version: VersionString) -> packaging.version.Version: + try: + return packaging.version.Version(version) + except packaging.version.InvalidVersion: + # packaging.version.Version no longer parses legacy versions + try: + return packaging.version.Version(version.replace("-", "+")) + except packaging.version.InvalidVersion: + return packaging.version.Version("0") + + +@dataclass +class PypiInfo: + distribution: str + pypi_root: str + releases: dict[VersionString, list[ReleaseDownload]] = field(repr=False) + info: dict[str, Any] = field(repr=False) + + def get_release(self, *, version: VersionString) -> PypiReleaseDownload: + # prefer wheels, since it's what most users will get / it's pretty easy to mess up MANIFEST + release_info = sorted(self.releases[version], key=lambda x: bool(x["packagetype"] == "bdist_wheel"))[-1] + return PypiReleaseDownload( + distribution=self.distribution, + url=release_info["url"], + packagetype=release_info["packagetype"], + filename=release_info["filename"], + version=packaging.version.Version(version), + upload_date=datetime.datetime.fromisoformat(release_info["upload_time"]), + ) + + def get_latest_release(self) -> PypiReleaseDownload: + return self.get_release(version=self.info["version"]) + + def releases_in_descending_order(self) -> Iterator[PypiReleaseDownload]: + for version in sorted(self.releases, key=_best_effort_version, reverse=True): + yield self.get_release(version=version) + + +async def fetch_pypi_info(distribution: str, session: aiohttp.ClientSession) -> PypiInfo: + # Cf. # https://warehouse.pypa.io/api-reference/json.html#get--pypi--project_name--json + pypi_root = f"https://pypi.org/pypi/{urllib.parse.quote(distribution)}" + async with session.get(f"{pypi_root}/json") as response: + response.raise_for_status() + j = await response.json() + return PypiInfo(distribution=distribution, pypi_root=pypi_root, releases=j["releases"], info=j["info"]) + + +@dataclass +class Update: + distribution: str + old_version_spec: Specifier + new_version_spec: Specifier + links: dict[str, str] + diff_analysis: DiffAnalysis | None + + def __str__(self) -> str: + return f"{colored('updating', 'yellow')} from '{self.old_version_spec}' to '{self.new_version_spec}'" + + @property + def new_version(self) -> str: + if self.new_version_spec.operator == "==": + return str(self.new_version_spec)[2:] + else: + return str(self.new_version_spec) + + +@dataclass +class Obsolete: + distribution: str + obsolete_since_version: str + obsolete_since_date: datetime.datetime + links: dict[str, str] + + def __str__(self) -> str: + return f"{colored('marking as obsolete', 'yellow')} since {self.obsolete_since_version!r}" + + +@dataclass +class Remove: + distribution: str + reason: Literal["ships py.typed file", "unmaintained"] + links: dict[str, str] + + def __str__(self) -> str: + return f"{colored('removing', 'yellow')} ({self.reason})" + + +@dataclass +class NoUpdate: + distribution: str + reason: Literal["obsolete", "no longer updated", "up to date"] + + def __str__(self) -> str: + return f"{colored('skipping', 'green')} ({self.reason})" + + +@dataclass +class Error: + distribution: str + message: str + + def __str__(self) -> str: + return f"{colored('error', 'red')} ({self.message})" + + +_T = TypeVar("_T") + + +async def with_extracted_archive( + release_to_download: PypiReleaseDownload, + *, + session: aiohttp.ClientSession, + handler: Callable[[zipfile.ZipFile | tarfile.TarFile], _T], +) -> _T: + async with session.get(release_to_download.url) as response: + body = io.BytesIO(await response.read()) + + packagetype = release_to_download.packagetype + if packagetype == "bdist_wheel": + assert release_to_download.filename.endswith(".whl") + with zipfile.ZipFile(body) as zf: + return handler(zf) + elif packagetype == "sdist": + # sdist defaults to `.tar.gz` on Linux and to `.zip` on Windows: + # https://docs.python.org/3.11/distutils/sourcedist.html + if release_to_download.filename.endswith(".tar.gz"): + with tarfile.open(fileobj=body, mode="r:gz") as zf: + return handler(zf) + elif release_to_download.filename.endswith(".zip"): + with zipfile.ZipFile(body) as zf: + return handler(zf) + else: + raise AssertionError(f"Package file {release_to_download.filename!r} does not end with '.tar.gz' or '.zip'") + else: + raise AssertionError(f"Unknown package type for {release_to_download.distribution}: {packagetype!r}") + + +def all_py_files_in_source_are_in_py_typed_dirs(source: zipfile.ZipFile | tarfile.TarFile) -> bool: + py_typed_dirs: list[Path] = [] + all_python_files: list[Path] = [] + py_file_suffixes = {".py", ".pyi"} + + # Obtain an iterator over all files in the zipfile/tarfile. + # Filter out empty __init__.py files: this reduces false negatives + # in cases like this: + # + # repo_root/ + # ├─ src/ + # | ├─ pkg/ + # | | ├─ __init__.py <-- This file is empty + # | | ├─ subpkg/ + # | | | ├─ __init__.py + # | | | ├─ libraryfile.py + # | | | ├─ libraryfile2.py + # | | | ├─ py.typed + if isinstance(source, zipfile.ZipFile): + path_iter = ( + Path(zip_info.filename) + for zip_info in source.infolist() + if ((not zip_info.is_dir()) and not (Path(zip_info.filename).name == "__init__.py" and zip_info.file_size == 0)) + ) + else: + path_iter = ( + Path(tar_info.path) + for tar_info in source + if (tar_info.isfile() and not (Path(tar_info.name).name == "__init__.py" and tar_info.size == 0)) + ) + + for path in path_iter: + if path.suffix in py_file_suffixes: + all_python_files.append(path) + elif path.name == "py.typed": + py_typed_dirs.append(path.parent) + + if not py_typed_dirs: + return False + if not all_python_files: + return False + + for path in all_python_files: + if not any(py_typed_dir in path.parents for py_typed_dir in py_typed_dirs): + return False + return True + + +async def release_contains_py_typed(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool: + return await with_extracted_archive(release_to_download, session=session, handler=all_py_files_in_source_are_in_py_typed_dirs) + + +async def find_first_release_with_py_typed(pypi_info: PypiInfo, *, session: aiohttp.ClientSession) -> PypiReleaseDownload | None: + """If the latest release is py.typed, return the first release that included a py.typed file. + + If the latest release is not py.typed, return None. + """ + release_iter = (release for release in pypi_info.releases_in_descending_order() if not release.version.is_prerelease) + latest_release = next(release_iter) + # If the latest release is not py.typed, assume none are. + if not (await release_contains_py_typed(latest_release, session=session)): + return None + + first_release_with_py_typed = latest_release + while await release_contains_py_typed(release := next(release_iter), session=session): + first_release_with_py_typed = release + return first_release_with_py_typed + + +def get_updated_version_spec(spec: Specifier, version: packaging.version.Version) -> Specifier: + """ + Given the old specifier and an updated version, returns an updated specifier that has the + specificity of the old specifier, but matches the updated version. + + For example: + spec="1", version="1.2.3" -> "1.2.3" + spec="1.0.1", version="1.2.3" -> "1.2.3" + spec="1.*", version="1.2.3" -> "1.*" + spec="1.*", version="2.3.4" -> "2.*" + spec="1.1.*", version="1.2.3" -> "1.2.*" + spec="1.1.1.*", version="1.2.3" -> "1.2.3.*" + spec="~=1.0.1", version="1.0.3" -> "~=1.0.3" + spec="~=1.0.1", version="1.1.0" -> "~=1.1.0" + """ + if spec.operator == "==" and spec.version.endswith(".*"): + specificity = spec.version.count(".") if spec.version.removesuffix(".*") else 0 + rounded_version = version.base_version.split(".")[:specificity] + rounded_version.extend(["0"] * (specificity - len(rounded_version))) + updated_spec = Specifier("==" + ".".join(rounded_version) + ".*") + elif spec.operator == "==": + updated_spec = Specifier(f"=={version}") + elif spec.operator == "~=": + updated_spec = Specifier(f"~={version}") + else: + raise ValueError(f"Unsupported version operator: {spec.operator}") + assert version in updated_spec, f"{version} not in {updated_spec}" + return updated_spec + + +@functools.cache +def get_github_api_headers() -> Mapping[str, str]: + headers = {"Accept": "application/vnd.github.v3+json"} + secret = os.environ.get("GITHUB_TOKEN") + if secret is not None: + headers["Authorization"] = f"token {secret}" if secret.startswith("ghp") else f"Bearer {secret}" + return headers + + +GitHost: TypeAlias = Literal["github", "gitlab"] + + +@dataclass +class GitHostInfo: + host: GitHost + repo_path: str + tags: list[str] = field(repr=False) + + +async def get_host_repo_info(session: aiohttp.ClientSession, stub_info: StubMetadata) -> GitHostInfo | None: + """ + If the project represented by `stub_info` is publicly hosted (e.g. on GitHub) + return information regarding the project as it exists on the public host. + + Else, return None. + """ + if not stub_info.upstream_repository: + return None + # We have various sanity checks for the upstream_repository field in ts_utils.metadata, + # so no need to repeat all of them here + split_url = urllib.parse.urlsplit(stub_info.upstream_repository) + host = split_url.netloc.removesuffix(".com") + if host not in ("github", "gitlab"): + return None + url_path = split_url.path.strip("/") + assert len(Path(url_path).parts) == 2 + if host == "github": + # https://docs.github.com/en/rest/git/tags + info_url = f"https://api.github.com/repos/{url_path}/tags" + headers = get_github_api_headers() + else: + assert host == "gitlab" + # https://docs.gitlab.com/api/tags/ + project_id = urllib.parse.quote(url_path, safe="") + info_url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/tags" + headers = None + async with session.get(info_url, headers=headers) as response: + if response.status == HTTPStatus.OK: + # Conveniently both GitHub and GitLab use the same key name. + tags = [tag["name"] for tag in await response.json()] + return GitHostInfo(host=host, repo_path=url_path, tags=tags) # type: ignore[arg-type] + return None + + +class GitHostDiffInfo(NamedTuple): + host: GitHost + repo_path: str + old_tag: str + new_tag: str + + @property + def diff_url(self) -> str: + if self.host == "github": + return f"https://github.com/{self.repo_path}/compare/{self.old_tag}...{self.new_tag}" + else: + assert self.host == "gitlab" + return f"https://gitlab.com/{self.repo_path}/-/compare/{self.old_tag}...{self.new_tag}" + + +async def get_diff_info( + session: aiohttp.ClientSession, stub_info: StubMetadata, pypi_version: packaging.version.Version +) -> GitHostDiffInfo | None: + """Return a tuple giving info about the diff between two releases, if possible. + + Return `None` if the project isn't hosted on GitHub, + or if a link pointing to the diff couldn't be found for any other reason. + """ + host_info = await get_host_repo_info(session, stub_info) + if host_info is None: + return None + + versions_to_tags: dict[packaging.version.Version, str] = {} + for tag_name in host_info.tags: + # Some packages in typeshed have tag names + # that are invalid to be passed to the Version() constructor, + # e.g. v.1.4.2 + with contextlib.suppress(packaging.version.InvalidVersion): + versions_to_tags[packaging.version.Version(tag_name)] = tag_name + + try: + new_tag = versions_to_tags[pypi_version] + except KeyError: + return None + + try: + old_version = max(version for version in versions_to_tags if version in stub_info.version_spec and version < pypi_version) + except ValueError: + return None + else: + old_tag = versions_to_tags[old_version] + + return GitHostDiffInfo(host=host_info.host, repo_path=host_info.repo_path, old_tag=old_tag, new_tag=new_tag) + + +FileStatus: TypeAlias = Literal["added", "modified", "removed", "renamed"] + + +class FileInfo(TypedDict): + filename: str + status: FileStatus + additions: int + deletions: int + + +def _plural_s(num: int, /) -> str: + return "s" if num != 1 else "" + + +@dataclass(repr=False) +class DiffAnalysis: + MAXIMUM_NUMBER_OF_FILES_TO_LIST: ClassVar[int] = 7 + py_files: list[FileInfo] + py_files_stubbed_in_typeshed: list[FileInfo] + + @property + def runtime_definitely_has_consistent_directory_structure_with_typeshed(self) -> bool: + """ + If 0 .py files in the GitHub diff exist in typeshed's stubs, + there's a possibility that the .py files might be found + in a different directory at runtime. + + For example: pyopenssl has its .py files in the `src/OpenSSL/` directory at runtime, + but in typeshed the stubs are in the `OpenSSL/` directory. + """ + return bool(self.py_files_stubbed_in_typeshed) + + @functools.cached_property + def public_files_added(self) -> Sequence[str]: + def is_public(path: Path) -> bool: + return not re.match(r"_[^_]", path.name) and not path.name.startswith("test_") + + return [file["filename"] for file in self.py_files if is_public(Path(file["filename"])) and file["status"] == "added"] + + @functools.cached_property + def typeshed_files_deleted(self) -> Sequence[str]: + return [file["filename"] for file in self.py_files_stubbed_in_typeshed if file["status"] == "removed"] + + @functools.cached_property + def typeshed_files_modified(self) -> Sequence[str]: + return [file["filename"] for file in self.py_files_stubbed_in_typeshed if file["status"] in {"modified", "renamed"}] + + @property + def total_lines_added(self) -> int: + return sum(file["additions"] for file in self.py_files) + + @property + def total_lines_deleted(self) -> int: + return sum(file["deletions"] for file in self.py_files) + + def _describe_files(self, *, verb: str, filenames: Sequence[str]) -> str: + num_files = len(filenames) + if num_files > 1: + description = f"have been {verb}" + # Don't list the filenames if there are *loads* of files + if num_files <= self.MAXIMUM_NUMBER_OF_FILES_TO_LIST: + description += ": " + description += ", ".join(f"`{filename}`" for filename in filenames) + description += "." + return description + if num_files == 1: + return f"has been {verb}: `{filenames[0]}`." + return f"have been {verb}." + + def describe_public_files_added(self) -> str: + num_files_added = len(self.public_files_added) + analysis = f"{num_files_added} public Python file{_plural_s(num_files_added)} " + analysis += self._describe_files(verb="added", filenames=self.public_files_added) + return analysis + + def describe_typeshed_files_deleted(self) -> str: + num_files_deleted = len(self.typeshed_files_deleted) + analysis = f"{num_files_deleted} file{_plural_s(num_files_deleted)} included in typeshed's stubs " + analysis += self._describe_files(verb="deleted", filenames=self.typeshed_files_deleted) + return analysis + + def describe_typeshed_files_modified(self) -> str: + num_files_modified = len(self.typeshed_files_modified) + analysis = f"{num_files_modified} file{_plural_s(num_files_modified)} included in typeshed's stubs " + analysis += self._describe_files(verb="modified or renamed", filenames=self.typeshed_files_modified) + return analysis + + def __str__(self) -> str: + data_points: list[str] = [] + if self.runtime_definitely_has_consistent_directory_structure_with_typeshed: + data_points += [ + self.describe_public_files_added(), + self.describe_typeshed_files_deleted(), + self.describe_typeshed_files_modified(), + ] + data_points += [ + f"Total lines of Python code added: {self.total_lines_added}.", + f"Total lines of Python code deleted: {self.total_lines_deleted}.", + ] + return "Stubsabot analysis of the diff between the two releases:\n - " + "\n - ".join(data_points) + + +async def analyze_github_diff( + repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession +) -> DiffAnalysis | None: + url = f"https://api.github.com/repos/{repo_path}/compare/{old_tag}...{new_tag}" + async with session.get(url, headers=get_github_api_headers()) as response: + response.raise_for_status() + json_resp: dict[str, list[FileInfo]] = await response.json() + assert isinstance(json_resp, dict) + # https://docs.github.com/en/rest/commits/commits#compare-two-commits + py_files: list[FileInfo] = [file for file in json_resp["files"] if Path(file["filename"]).suffix == ".py"] + stub_path = distribution_path(distribution) + files_in_typeshed = {stub.path for stub in third_party_stubs(distribution)} + py_files_stubbed_in_typeshed = [file for file in py_files if (stub_path / f"{file['filename']}i") in files_in_typeshed] + return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed) + + +async def analyze_gitlab_diff( + repo_path: str, distribution: str, old_tag: str, new_tag: str, *, session: aiohttp.ClientSession +) -> DiffAnalysis | None: + # https://docs.gitlab.com/api/repositories/#compare-branches-tags-or-commits + project_id = urllib.parse.quote(repo_path, safe="") + url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/compare?from={old_tag}&to={new_tag}" + async with session.get(url) as response: + response.raise_for_status() + json_resp: dict[str, Any] = await response.json() + assert isinstance(json_resp, dict) + + py_files: list[FileInfo] = [] + for file_diff in json_resp["diffs"]: + filename = file_diff["new_path"] + if Path(filename).suffix != ".py": + continue + status: FileStatus + if file_diff["new_file"]: + status = "added" + elif file_diff["renamed_file"]: + status = "renamed" + elif file_diff["deleted_file"]: + status = "removed" + else: + status = "modified" + diff_lines = file_diff["diff"].splitlines() + additions = sum(1 for ln in diff_lines if ln.startswith("+")) + deletions = sum(1 for ln in diff_lines if ln.startswith("-")) + py_files.append(FileInfo(filename=filename, status=status, additions=additions, deletions=deletions)) + + stub_path = distribution_path(distribution) + files_in_typeshed = {stub.path for stub in third_party_stubs(distribution)} + py_files_stubbed_in_typeshed = [file for file in py_files if (stub_path / f"{file['filename']}i") in files_in_typeshed] + return DiffAnalysis(py_files=py_files, py_files_stubbed_in_typeshed=py_files_stubbed_in_typeshed) + + +def _add_months(date: datetime.date, months: int) -> datetime.date: + month = date.month - 1 + months + year = date.year + month // 12 + month = month % 12 + 1 + day = min(date.day, calendar.monthrange(year, month)[1]) + return datetime.date(year, month, day) + + +def obsolete_more_than_n_months(since_date: datetime.date) -> bool: + remove_date = _add_months(since_date, POLICY_MONTHS_DELTA) + today = datetime.datetime.now(tz=datetime.timezone.utc).date() + return remove_date <= today + + +def parse_no_longer_updated_from_archive(source: zipfile.ZipFile | tarfile.TarFile) -> bool: + if isinstance(source, zipfile.ZipFile): + try: + file = source.open("METADATA.toml", "r") + except KeyError: + return False + else: + try: + tarinfo = source.getmember("METADATA.toml") + file = source.extractfile(tarinfo) # type: ignore[assignment] + if file is None: + return False + except KeyError: + return False + + with file as f: + toml_data: dict[str, object] = tomllib.load(f) + + no_longer_updated = toml_data.get("no-longer-updated", False) + assert type(no_longer_updated) is bool + return bool(no_longer_updated) + + +async def has_no_longer_updated_release(release_to_download: PypiReleaseDownload, *, session: aiohttp.ClientSession) -> bool: + """ + Return `True` if the `no_longer_updated` field exists and the value is + `True` in the `METADATA.toml` file of latest `types-{distribution}` pypi release. + """ + return await with_extracted_archive(release_to_download, session=session, handler=parse_no_longer_updated_from_archive) + + +async def determine_action(distribution: str, session: aiohttp.ClientSession) -> Update | NoUpdate | Obsolete | Remove | Error: + try: + return await determine_action_no_error_handling(distribution, session) + except Exception as exc: + return Error(distribution, str(exc)) + + +async def determine_action_no_error_handling( + distribution: str, session: aiohttp.ClientSession +) -> Update | NoUpdate | Obsolete | Remove: + stub_info = read_metadata(distribution) + if stub_info.is_obsolete: + assert type(stub_info.obsolete) is ObsoleteMetadata + since_date = stub_info.obsolete.since_date + + if obsolete_more_than_n_months(since_date): + pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session) + latest_release = pypi_info.get_latest_release() + links = { + "Typeshed release": f"{pypi_info.pypi_root}", + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + } + return Remove(stub_info.distribution, reason="ships py.typed file", links=links) + else: + return NoUpdate(stub_info.distribution, "obsolete") + if stub_info.no_longer_updated: + pypi_info = await fetch_pypi_info(f"types-{stub_info.distribution}", session) + latest_release = pypi_info.get_latest_release() + + if await has_no_longer_updated_release(latest_release, session=session): + links = { + "Typeshed release": f"{pypi_info.pypi_root}", + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + } + return Remove(stub_info.distribution, reason="unmaintained", links=links) + else: + return NoUpdate(stub_info.distribution, "no longer updated") + + pypi_info = await fetch_pypi_info(stub_info.distribution, session) + latest_release = pypi_info.get_latest_release() + latest_version = latest_release.version + obsolete_since = await find_first_release_with_py_typed(pypi_info, session=session) + if obsolete_since is None and latest_version in stub_info.version_spec: + return NoUpdate(stub_info.distribution, "up to date") + + relevant_version = obsolete_since.version if obsolete_since else latest_version + + project_urls: dict[str, str] = pypi_info.info["project_urls"] or {} + maybe_links: dict[str, str | None] = { + "Release": f"{pypi_info.pypi_root}/{relevant_version}", + "Homepage": project_urls.get("Homepage"), + "Repository": stub_info.upstream_repository, + "Typeshed stubs": f"https://github.com/{TYPESHED_OWNER}/typeshed/tree/main/stubs/{stub_info.distribution}", + "Changelog": project_urls.get("Changelog") or project_urls.get("Changes") or project_urls.get("Change Log"), + } + links = {k: v for k, v in maybe_links.items() if v is not None} + + diff_info = await get_diff_info(session, stub_info, relevant_version) + if diff_info is not None: + links["Diff"] = diff_info.diff_url + + if obsolete_since: + return Obsolete( + stub_info.distribution, + obsolete_since_version=str(obsolete_since.version), + obsolete_since_date=obsolete_since.upload_date, + links=links, + ) + + if diff_info is None: + diff_analysis: DiffAnalysis | None = None + else: + analyze_diff = {"github": analyze_github_diff, "gitlab": analyze_gitlab_diff}[diff_info.host] + diff_analysis = await analyze_diff( + repo_path=diff_info.repo_path, + distribution=distribution, + old_tag=diff_info.old_tag, + new_tag=diff_info.new_tag, + session=session, + ) + + return Update( + distribution=stub_info.distribution, + old_version_spec=stub_info.version_spec, + new_version_spec=get_updated_version_spec(stub_info.version_spec, latest_version), + links=links, + diff_analysis=diff_analysis, + ) + + +@functools.lru_cache +def get_origin_owner() -> str: + output = subprocess.check_output(["git", "remote", "get-url", "origin"], text=True).strip() + match = re.match(r"(git@github.com:|https://github.com/)(?P[^/]+)/(?P[^/\s]+)", output) + assert match is not None, f"Couldn't identify origin's owner: {output!r}" + assert match.group("repo").removesuffix(".git") == "typeshed", f"Unexpected repo: {match.group('repo')!r}" + return match.group("owner") + + +async def create_or_update_pull_request(*, title: str, body: str, branch_name: str, session: aiohttp.ClientSession) -> None: + fork_owner = get_origin_owner() + + async with session.post( + f"{TYPESHED_API_URL}/pulls", + json={"title": title, "body": body, "head": f"{fork_owner}:{branch_name}", "base": "main"}, + headers=get_github_api_headers(), + ) as response: + resp_json = await response.json() + if response.status == HTTPStatus.CREATED: + pr_number = resp_json["number"] + assert isinstance(pr_number, int) + elif response.status == HTTPStatus.UNPROCESSABLE_ENTITY and any( + "A pull request already exists" in e.get("message", "") for e in resp_json.get("errors", []) + ): + pr_number = await update_existing_pull_request(title=title, body=body, branch_name=branch_name, session=session) + else: + response.raise_for_status() + raise AssertionError(f"Unexpected response: {response.status}") + await update_pull_request_label(pr_number=pr_number, session=session) + + +async def update_existing_pull_request(*, title: str, body: str, branch_name: str, session: aiohttp.ClientSession) -> int: + fork_owner = get_origin_owner() + + # Find the existing PR + async with session.get( + f"{TYPESHED_API_URL}/pulls", + params={"state": "open", "head": f"{fork_owner}:{branch_name}", "base": "main"}, + headers=get_github_api_headers(), + ) as response: + response.raise_for_status() + resp_json = await response.json() + assert len(resp_json) >= 1 + pr_number = resp_json[0]["number"] + assert isinstance(pr_number, int) + # Update the PR's title and body + async with session.patch( + f"{TYPESHED_API_URL}/pulls/{pr_number}", json={"title": title, "body": body}, headers=get_github_api_headers() + ) as response: + response.raise_for_status() + return pr_number + + +async def update_pull_request_label(*, pr_number: int, session: aiohttp.ClientSession) -> None: + # There is no pulls/.../labels endpoint, which is why we need to use the issues endpoint. + async with session.post( + f"{TYPESHED_API_URL}/issues/{pr_number}/labels", json={"labels": [STUBSABOT_LABEL]}, headers=get_github_api_headers() + ) as response: + response.raise_for_status() + + +def has_non_stubsabot_commits(branch: str) -> bool: + assert not branch.startswith("origin/") + try: + # commits on origin/branch that are not on branch or are + # patch equivalent to a commit on branch + print( + "[debugprint]", + subprocess.check_output( + ["git", "log", "--right-only", "--pretty=%an %s", "--cherry-pick", f"{branch}...origin/{branch}"] + ), + ) + print( + "[debugprint]", + subprocess.check_output( + ["git", "log", "--right-only", "--pretty=%an", "--cherry-pick", f"{branch}...origin/{branch}"] + ), + ) + output = subprocess.check_output( + ["git", "log", "--right-only", "--pretty=%an", "--cherry-pick", f"{branch}...origin/{branch}"], + stderr=subprocess.DEVNULL, + ) + return bool(set(output.splitlines()) - {b"stubsabot"}) + except subprocess.CalledProcessError: + # origin/branch does not exist + return False + + +def latest_commit_is_different_to_last_commit_on_origin(branch: str) -> bool: + assert not branch.startswith("origin/") + try: + # https://www.git-scm.com/docs/git-range-diff + # If the number of lines is >1, + # it indicates that something about our commit is different to the last commit + # (Could be the commit "content", or the commit message). + commit_comparison = subprocess.run( + ["git", "range-diff", f"origin/{branch}~1..origin/{branch}", "HEAD~1..HEAD"], check=True, capture_output=True + ) + return len(commit_comparison.stdout.splitlines()) > 1 + except subprocess.CalledProcessError: + # origin/branch does not exist + return True + + +class RemoteConflictError(Exception): + pass + + +def somewhat_safe_force_push(branch: str) -> None: + if has_non_stubsabot_commits(branch): + raise RemoteConflictError(f"origin/{branch} has non-stubsabot changes that are not on {branch}!") + subprocess.check_call(["git", "push", "origin", branch, "--force"]) + + +def normalize(name: str) -> str: + # PEP 503 normalization + return re.sub(r"[-_.]+", "-", name).lower() + + +# lock should be unnecessary, but can't hurt to enforce mutual exclusion +_repo_lock = asyncio.Lock() + +BRANCH_PREFIX = "stubsabot" + + +def get_update_pr_body(update: Update, metadata: Mapping[str, Any]) -> str: + body = "\n".join(f"{k}: {v}" for k, v in update.links.items()) + + if update.diff_analysis is not None: + body += f"\n\n{update.diff_analysis}" + + stubtest_settings: dict[str, Any] = metadata.get("tool", {}).get("stubtest", {}) + stubtest_will_run = not stubtest_settings.get("skip", False) + if stubtest_will_run: + body += textwrap.dedent(""" + + If stubtest fails for this PR: + - Leave this PR open (as a reminder, and to prevent stubsabot from opening another PR) + - Fix stubtest failures in another PR, then close this PR + + Note that you will need to close and re-open the PR in order to trigger CI + """) + else: + body += textwrap.dedent(f""" + + :warning: Review this PR manually, as stubtest is skipped in CI for {update.distribution}! + Also check whether stubtest can be reenabled. :warning: + """) + return body + + +def remove_stubs(distribution: str) -> None: + stub_path = distribution_path(distribution) + target_path_prefix = f'"stubs/{distribution}' + + if stub_path.exists() and stub_path.is_dir(): + shutil.rmtree(stub_path) + + with PYRIGHT_CONFIG.open("r", encoding="UTF-8") as f: + lines = f.readlines() + + lines = [line for line in lines if not line.lstrip().startswith(target_path_prefix)] + + with PYRIGHT_CONFIG.open("w", encoding="UTF-8") as f: + f.writelines(lines) + + +async def suggest_typeshed_update(update: Update, session: aiohttp.ClientSession, action_level: ActionLevel) -> None: + if action_level <= ActionLevel.nothing: + return + title = f"[stubsabot] Bump {update.distribution} to {update.new_version}" + async with _repo_lock: + branch_name = f"{BRANCH_PREFIX}/{normalize(update.distribution)}" + subprocess.check_call(["git", "checkout", "-B", branch_name, "origin/main"]) + meta = update_metadata(update.distribution, version=update.new_version) + body = get_update_pr_body(update, meta) + subprocess.check_call(["git", "commit", "--all", "-m", f"{title}\n\n{body}"]) + if action_level <= ActionLevel.local: + return + if not latest_commit_is_different_to_last_commit_on_origin(branch_name): + print(f"No pushing to origin required: origin/{branch_name} exists and requires no changes!") + return + somewhat_safe_force_push(branch_name) + if action_level <= ActionLevel.fork: + return + + await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session) + + +async def suggest_typeshed_obsolete(obsolete: Obsolete, session: aiohttp.ClientSession, action_level: ActionLevel) -> None: + if action_level <= ActionLevel.nothing: + return + title = f"[stubsabot] Mark {obsolete.distribution} as obsolete since {obsolete.obsolete_since_version}" + async with _repo_lock: + branch_name = f"{BRANCH_PREFIX}/{normalize(obsolete.distribution)}" + subprocess.check_call(["git", "checkout", "-B", branch_name, "origin/main"]) + obsolete_t = cast(dict[str, object], tomlkit.inline_table()) + obsolete_t.update({"version": obsolete.obsolete_since_version, "date": obsolete.obsolete_since_date.date().isoformat()}) + update_metadata(obsolete.distribution, obsolete_since=obsolete_t) + body = "\n".join(f"{k}: {v}" for k, v in obsolete.links.items()) + subprocess.check_call(["git", "commit", "--all", "-m", f"{title}\n\n{body}"]) + if action_level <= ActionLevel.local: + return + if not latest_commit_is_different_to_last_commit_on_origin(branch_name): + print(f"No PR required: origin/{branch_name} exists and requires no changes!") + return + somewhat_safe_force_push(branch_name) + if action_level <= ActionLevel.fork: + return + + await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session) + + +async def suggest_typeshed_remove(remove: Remove, session: aiohttp.ClientSession, action_level: ActionLevel) -> None: + if action_level <= ActionLevel.nothing: + return + title = f"[stubsabot] Remove {remove.distribution} as {remove.reason}" + async with _repo_lock: + branch_name = f"{BRANCH_PREFIX}/{normalize(remove.distribution)}" + subprocess.check_call(["git", "checkout", "-B", branch_name, "origin/main"]) + remove_stubs(remove.distribution) + body = "\n".join(f"{k}: {v}" for k, v in remove.links.items()) + subprocess.check_call(["git", "commit", "--all", "-m", f"{title}\n\n{body}"]) + if action_level <= ActionLevel.local: + return + if not latest_commit_is_different_to_last_commit_on_origin(branch_name): + print(f"No pushing to origin required: origin/{branch_name} exists and requires no changes!") + return + somewhat_safe_force_push(branch_name) + if action_level <= ActionLevel.fork: + return + + await create_or_update_pull_request(title=title, body=body, branch_name=branch_name, session=session) + + +async def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument( + "--action-level", + type=ActionLevel.from_cmd_arg, + default=ActionLevel.everything, + help="Limit actions performed to achieve dry runs for different levels of dryness", + ) + parser.add_argument( + "--action-count-limit", + type=int, + default=None, + help="Limit number of actions performed and the remainder are logged. Useful for testing", + ) + parser.add_argument("distributions", nargs="*", help="Distributions to update, default = all") + args = parser.parse_args() + + if args.distributions: + dists_to_update = args.distributions + else: + dists_to_update = sorted(path.name for path in STUBS_PATH.iterdir()) + + if args.action_level > ActionLevel.nothing: + subprocess.run(["git", "update-index", "--refresh"], capture_output=True, check=False) + diff_result = subprocess.run(["git", "diff-index", "HEAD", "--name-only"], text=True, capture_output=True, check=False) + if diff_result.returncode: + print("Unexpected exception!") + print(diff_result.stdout) + print(diff_result.stderr) + return diff_result.returncode + if diff_result.stdout: + changed_files = ", ".join(repr(line) for line in diff_result.stdout.split("\n") if line) + print(f"Cannot run stubsabot, as uncommitted changes are present in {changed_files}!") + return 1 + + if args.action_level > ActionLevel.fork: + if os.environ.get("GITHUB_TOKEN") is None: + raise ValueError("GITHUB_TOKEN environment variable must be set") + + denylist = {"gdb"} # gdb is not a pypi distribution + + original_branch = subprocess.run( + ["git", "branch", "--show-current"], text=True, capture_output=True, check=True + ).stdout.strip() + + if args.action_level >= ActionLevel.local: + subprocess.check_call(["git", "fetch", "--prune", "--all"]) + + error = False + + try: + conn = aiohttp.TCPConnector(limit_per_host=10) + async with aiohttp.ClientSession(connector=conn) as session: + tasks = [ + asyncio.create_task(determine_action(distribution, session)) + for distribution in dists_to_update + if distribution not in denylist + ] + + action_count = 0 + for task in asyncio.as_completed(tasks): + update = await task + print(f"{update.distribution}... ", end="") + print(update) + + if isinstance(update, NoUpdate): + continue + if isinstance(update, Error): + error = True + continue + + if args.action_count_limit is not None and action_count >= args.action_count_limit: + print(colored("... but we've reached action count limit", "red")) + continue + action_count += 1 + + try: + if isinstance(update, Update): + await suggest_typeshed_update(update, session, action_level=args.action_level) + continue + if isinstance(update, Obsolete): + await suggest_typeshed_obsolete(update, session, action_level=args.action_level) + continue + # Redundant, but keeping for extra runtime validation + if isinstance(update, Remove): # pyright: ignore[reportUnnecessaryIsInstance] + await suggest_typeshed_remove(update, session, action_level=args.action_level) + continue + except RemoteConflictError as e: + print(colored(f"... but ran into {type(e).__qualname__}: {e}", "red")) + continue + raise AssertionError + finally: + # if you need to cleanup, try: + # git branch -D $(git branch --list 'stubsabot/*') + if args.action_level >= ActionLevel.local and original_branch: + subprocess.check_call(["git", "checkout", original_branch]) + + return 1 if error else 0 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main())) diff --git a/scripts/sync_protobuf/_utils.py b/scripts/sync_protobuf/_utils.py new file mode 100644 index 000000000000..2af94d3d1c79 --- /dev/null +++ b/scripts/sync_protobuf/_utils.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import subprocess +import sys +from collections.abc import Iterable +from http.client import HTTPResponse +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.request import urlopen +from zipfile import ZipFile + +try: + _mypy_protobuf_version = version("mypy-protobuf") +except PackageNotFoundError: + _mypy_protobuf_version = "unavailable" + +if TYPE_CHECKING: + from _typeshed import StrOrBytesPath, StrPath + +MYPY_PROTOBUF_VERSION = _mypy_protobuf_version + + +def download_file(url: str, destination: Path) -> None: + print(f"Downloading '{url}' to '{destination}'") + resp: HTTPResponse + with urlopen(url) as resp: + destination.write_bytes(resp.read()) + + +def extract_archive(archive_path: StrPath, destination: StrPath) -> None: + print(f"Extracting '{archive_path}' to '{destination}'") + with ZipFile(archive_path) as file_in: + file_in.extractall(destination) + + +def run_protoc( + proto_paths: Iterable[StrPath], mypy_out: StrPath, proto_globs: Iterable[str], cwd: StrOrBytesPath | None = None +) -> str: + """TODO: Describe parameters and return.""" + protoc_version = ( + subprocess.run([sys.executable, "-m", "grpc_tools.protoc", "--version"], capture_output=True, check=False) + .stdout.decode() + .strip() + ) + print() + print(protoc_version) + protoc_args = [ + *[f"--proto_path={proto_path}" for proto_path in proto_paths], + "--mypy_out", + f"relax_strict_optional_primitives:{mypy_out}", + *proto_globs, + ] + print("Running: protoc\n " + "\n ".join(protoc_args) + "\n") + subprocess.run((sys.executable, "-m", "grpc_tools.protoc", *protoc_args), cwd=cwd, check=True) + return protoc_version diff --git a/scripts/sync_protobuf/google_protobuf.py b/scripts/sync_protobuf/google_protobuf.py new file mode 100755 index 000000000000..358e5c454e44 --- /dev/null +++ b/scripts/sync_protobuf/google_protobuf.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given protobuf version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import json +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import read_metadata, update_metadata +from ts_utils.paths import distribution_path + +# PyPi version has an extra "major" number that the Git version doesn't have +PACKAGE_VERSION = read_metadata("protobuf").version_spec.version[2:] + +STUBS_FOLDER = distribution_path("protobuf").absolute() +ARCHIVE_FILENAME = f"protobuf-{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/protocolbuffers/protobuf/releases/download/v{PACKAGE_VERSION}/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"protobuf-{PACKAGE_VERSION}" + +VERSION_PATTERN = re.compile(r'def game_version\(\):\n return "(.+?)"') +PROTO_FILE_PATTERN = re.compile(r'"//:(.*)_proto"') + + +def extract_python_version(file_path: Path) -> str: + """Extract the Python version from https://github.com/protocolbuffers/protobuf/blob/main/version.json .""" + with file_path.open() as file: + data: dict[str, Any] = json.load(file) + # The root key will be the protobuf source code version + version = next(iter(data.values()))["languages"]["python"] + assert isinstance(version, str) + return version + + +def extract_proto_file_paths(temp_dir: Path) -> list[str]: + """ + Roughly reproduce the subset of .proto files on the public interface + as described in py_proto_library calls in + https://github.com/protocolbuffers/protobuf/blob/main/python/dist/BUILD.bazel . + """ + with (temp_dir / EXTRACTED_PACKAGE_DIR / "python" / "dist" / "BUILD.bazel").open() as file: + matched_lines = filter(None, (re.search(PROTO_FILE_PATTERN, line) for line in file)) + proto_files = [ + EXTRACTED_PACKAGE_DIR + "/src/google/protobuf/" + match.group(1).replace("compiler_", "compiler/") + ".proto" + for match in matched_lines + ] + return proto_files + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch s2clientprotocol (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=(f"{EXTRACTED_PACKAGE_DIR}/src",), + mypy_out=STUBS_FOLDER, + proto_globs=extract_proto_file_paths(temp_dir), + cwd=temp_dir, + ) + + python_protobuf_version = extract_python_version(temp_dir / EXTRACTED_PACKAGE_DIR / "version.json") + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + update_metadata( + "protobuf", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on \ +[protobuf v{PACKAGE_VERSION}](https://github.com/protocolbuffers/protobuf/releases/tag/v{PACKAGE_VERSION}) \ +(python `protobuf=={python_protobuf_version}`).""", + ) + print("Updated protobuf/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_protobuf/s2clientprotocol.py b/scripts/sync_protobuf/s2clientprotocol.py new file mode 100755 index 000000000000..cee68e1edea9 --- /dev/null +++ b/scripts/sync_protobuf/s2clientprotocol.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given s2clientprotocol version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import update_metadata +from ts_utils.paths import distribution_path + +# Whenever you update PACKAGE_VERSION here, version should be updated +# in stubs/s2clientprotocol/METADATA.toml and vice-versa. +PACKAGE_VERSION = "c04df4adbe274858a4eb8417175ee32ad02fd609" + +STUBS_FOLDER = distribution_path("s2clientprotocol").absolute() +ARCHIVE_FILENAME = f"{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/Blizzard/s2client-proto/archive/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"s2client-proto-{PACKAGE_VERSION}" + +VERSION_PATTERN = re.compile(r'def game_version\(\):\n return "(.+?)"') + + +def extract_python_version(file_path: Path) -> str: + """Extract Python version from s2clientprotocol's build file.""" + match = re.search(VERSION_PATTERN, file_path.read_text()) + assert match + return match.group(1) + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch s2clientprotocol (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=(EXTRACTED_PACKAGE_DIR,), + mypy_out=STUBS_FOLDER, + proto_globs=(f"{EXTRACTED_PACKAGE_DIR}/s2clientprotocol/*.proto",), + cwd=temp_dir, + ) + + python_s2_client_proto_version = extract_python_version(temp_dir / EXTRACTED_PACKAGE_DIR / "s2clientprotocol" / "build.py") + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + update_metadata( + "s2clientprotocol", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on \ +[s2client-proto {python_s2_client_proto_version}](https://github.com/Blizzard/s2client-proto/tree/{PACKAGE_VERSION}).""", + ) + print("Updated s2clientprotocol/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/scripts/sync_protobuf/tensorflow.py b/scripts/sync_protobuf/tensorflow.py new file mode 100755 index 000000000000..fcb53226636e --- /dev/null +++ b/scripts/sync_protobuf/tensorflow.py @@ -0,0 +1,141 @@ +#!/usr/bin/env python3 +""" +Generates the protobuf stubs for the given tensorflow version using mypy-protobuf. +Generally, new minor versions are a good time to update the stubs. +""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from _utils import MYPY_PROTOBUF_VERSION, download_file, extract_archive, run_protoc +from ts_utils.metadata import read_metadata, update_metadata +from ts_utils.paths import distribution_path + +PACKAGE_VERSION = read_metadata("tensorflow").version_spec.version + +STUBS_FOLDER = distribution_path("tensorflow").absolute() +ARCHIVE_FILENAME = f"v{PACKAGE_VERSION}.zip" +ARCHIVE_URL = f"https://github.com/tensorflow/tensorflow/archive/refs/tags/{ARCHIVE_FILENAME}" +EXTRACTED_PACKAGE_DIR = f"tensorflow-{PACKAGE_VERSION}" + +PROTOS_TO_REMOVE = ( + "compiler/xla/autotune_results_pb2.pyi", + "compiler/xla/autotuning_pb2.pyi", + "compiler/xla/service/buffer_assignment_pb2.pyi", + "compiler/xla/service/hlo_execution_profile_data_pb2.pyi", + "core/protobuf/autotuning_pb2.pyi", + "core/protobuf/conv_autotuning_pb2.pyi", + "core/protobuf/critical_section_pb2.pyi", + "core/protobuf/eager_service_pb2.pyi", + "core/protobuf/master_pb2.pyi", + "core/protobuf/master_service_pb2.pyi", + "core/protobuf/replay_log_pb2.pyi", + "core/protobuf/tpu/compile_metadata_pb2.pyi", + "core/protobuf/worker_pb2.pyi", + "core/protobuf/worker_service_pb2.pyi", + "core/util/example_proto_fast_parsing_test_pb2.pyi", +) +""" +These protos exist in a folder with protos used in python, +but are not included in the python wheel. +They are likely only used for other language builds. +stubtest was used to identify them by looking for ModuleNotFoundError. +(comment out ".*_pb2.*" from the allowlist) +""" + +TSL_IMPORT_PATTERN = re.compile(r"(\[|\s)tsl\.") +XLA_IMPORT_PATTERN = re.compile(r"(\[|\s)xla\.") + + +def move_tree(source: Path, destination: Path) -> None: + """Move directory and merge if destination already exists. + + Can't use shutil.move because it can't merge existing directories. + """ + print(f"Moving '{source}' to '{destination}'") + shutil.copytree(source, destination, dirs_exist_ok=True) + shutil.rmtree(source) + + +def post_creation() -> None: + """Move third-party and fix imports.""" + print() + move_tree(STUBS_FOLDER / "tsl", STUBS_FOLDER / "tensorflow" / "tsl") + move_tree(STUBS_FOLDER / "xla", STUBS_FOLDER / "tensorflow" / "compiler" / "xla") + + for path in STUBS_FOLDER.rglob("*_pb2.pyi"): + print(f"Fixing imports in '{path}'") + filedata = path.read_text(encoding="utf-8") + + # Replace the target string + filedata = re.sub(TSL_IMPORT_PATTERN, "\\1tensorflow.tsl.", filedata) + filedata = re.sub(XLA_IMPORT_PATTERN, "\\1tensorflow.compiler.xla.", filedata) + + # Write the file out again + path.write_text(filedata, encoding="utf-8") + + print() + for to_remove in PROTOS_TO_REMOVE: + file_path = STUBS_FOLDER / "tensorflow" / to_remove + file_path.unlink() + print(f"Removed '{file_path}'") + + +def main() -> None: + temp_dir = Path(tempfile.mkdtemp()) + # Fetch tensorflow (which contains all the .proto files) + archive_path = temp_dir / ARCHIVE_FILENAME + download_file(ARCHIVE_URL, archive_path) + extract_archive(archive_path, temp_dir) + + # Remove existing pyi + for old_stub in STUBS_FOLDER.rglob("*_pb2.pyi"): + old_stub.unlink() + + protoc_version = run_protoc( + proto_paths=( + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/third_party/tsl", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla", + f"{EXTRACTED_PACKAGE_DIR}", + ), + mypy_out=STUBS_FOLDER, + proto_globs=( + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/service/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/xla/tsl/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/example/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/framework/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/protobuf/tpu/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/core/util/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/tensorflow/python/keras/protobuf/*.proto", + f"{EXTRACTED_PACKAGE_DIR}/third_party/xla/third_party/tsl/tsl/protobuf/*.proto", + ), + cwd=temp_dir, + ) + + # Cleanup after ourselves, this is a temp dir, but it can still grow fast if run multiple times + shutil.rmtree(temp_dir) + + post_creation() + + update_metadata( + "tensorflow", + extra_description=f"""Partially generated using \ +[mypy-protobuf=={MYPY_PROTOBUF_VERSION}](https://github.com/nipunn1313/mypy-protobuf/tree/v{MYPY_PROTOBUF_VERSION}) \ +and {protoc_version} on `tensorflow=={PACKAGE_VERSION}`.""", + ) + print("Updated tensorflow/METADATA.toml") + + # Run pre-commit to cleanup the stubs + subprocess.run((sys.executable, "-m", "pre_commit", "run", "--files", *STUBS_FOLDER.rglob("*_pb2.pyi")), check=False) + + +if __name__ == "__main__": + main() diff --git a/stdlib/@tests/stubtest_allowlists/common.txt b/stdlib/@tests/stubtest_allowlists/common.txt new file mode 100644 index 000000000000..29d91719c50c --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/common.txt @@ -0,0 +1,486 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +# Please keep sorted alphabetically + +importlib.abc.MetaPathFinder.find_spec # Not defined on the actual class, but expected to exist. +importlib.abc.PathEntryFinder.find_spec # Not defined on the actual class, but expected to exist. +tarfile.TarInfo.__slots__ # it's a big dictionary at runtime and the dictionary values are a bit long + + +# =============================================================== +# TODO: Modules that exist at runtime, but are missing from stubs +# =============================================================== + +turtledemo +turtledemo\..+ + + +# ====================================================================== +# Modules that exist at runtime, but are deliberately missing from stubs +# ====================================================================== + +idlelib + + +# ============================================================================= +# Module members that exist at runtime, but are deliberately missing from stubs +# ============================================================================= + +# Undocumented implementation details of a deprecated class +_frozen_importlib_external.WindowsRegistryFinder.DEBUG_BUILD +_frozen_importlib_external.WindowsRegistryFinder.REGISTRY_KEY +_frozen_importlib_external.WindowsRegistryFinder.REGISTRY_KEY_DEBUG + +builtins.OSError.characters_written # GetSetDescriptor that always raises AttributeError +builtins.ellipsis # does not exist at runtime, see https://github.com/python/typeshed/issues/7580 +builtins.float.__getformat__ # Internal method for CPython test suite + +# These super() dunders don't seem to be particularly useful, +# and having them pop up on autocomplete suggestions would be annoying +builtins.super.__self__ +builtins.super.__self_class__ +builtins.super.__thisclass__ + +# Undocumented implementation details +email.contentmanager.get_and_fixup_unknown_message_content +email.contentmanager.get_message_content +email.contentmanager.get_non_text_content +email.contentmanager.get_text_content +email.contentmanager.set_bytes_content +email.contentmanager.set_message_content +email.contentmanager.set_text_content + +ftplib.FTP.trust_server_pasv_ipv4_address # Dangerous to use, intentionally undocumented #6154 +hmac.HMAC.blocksize # use block_size instead + +# Undocumented implementation details +profile.Profile.dispatch +profile.Profile.fake_code +profile.Profile.fake_frame +profile.Profile.trace_dispatch +profile.Profile.trace_dispatch_c_call +profile.Profile.trace_dispatch_call +profile.Profile.trace_dispatch_exception +profile.Profile.trace_dispatch_i +profile.Profile.trace_dispatch_l +profile.Profile.trace_dispatch_mac +profile.Profile.trace_dispatch_return + +re.Pattern.scanner # Undocumented and not useful. #6405 + +# Missing aliases to existing methods that not many people seem to use. +# Complicated multiple inheritance, confuses type checkers. +tkinter.Grid.bbox +tkinter.Grid.columnconfigure +tkinter.Grid.config +tkinter.Grid.configure +tkinter.Grid.forget +tkinter.Grid.grid_bbox +tkinter.Grid.grid_columnconfigure +tkinter.Grid.grid_location +tkinter.Grid.grid_propagate +tkinter.Grid.grid_rowconfigure +tkinter.Grid.grid_size +tkinter.Grid.grid_slaves +tkinter.Grid.info +tkinter.Grid.propagate +tkinter.Grid.rowconfigure +tkinter.Grid.slaves +tkinter.Pack.config +tkinter.Pack.configure +tkinter.Pack.info +tkinter.Pack.pack_propagate +tkinter.Pack.pack_slaves +tkinter.Pack.slaves +tkinter.Place.config +tkinter.Place.configure +tkinter.Place.forget +tkinter.Place.place_slaves +tkinter.Place.slaves + +turtle.ScrolledCanvas.adjustScrolls # Undocumented implementation detail +turtle.ScrolledCanvas.onResize # Undocumented implementation detail +uuid.bytes_ # Attributes that are intended to be private +uuid.int_ # Attributes that are intended to be private +wave.Wave_read.initfp # Undocumented implementation detail +wave.Wave_write.initfp # Undocumented implementation detail +_?weakref\.ProxyType\.__bytes__ # Doesn't actually exist + +# Undocumented and have a comment in the source code saying "State variables (don't mess with these)" +wsgiref.handlers.BaseHandler.bytes_sent +wsgiref.handlers.BaseHandler.headers +wsgiref.handlers.BaseHandler.headers_sent +wsgiref.handlers.BaseHandler.result +wsgiref.handlers.BaseHandler.status + + +# ===================================== +# Platform and installation differences +# ===================================== + +# LC_MESSAGES is sometimes present in __all__, sometimes not, +# so stubtest will sometimes complain about exported names being different at runtime to the exported names in the stub +(locale.__all__)? + +# Loadable SQLite extensions are disabled on GitHub runners +(sqlite3(.dbapi2)?.Connection.enable_load_extension)? +(sqlite3(.dbapi2)?.Connection.load_extension)? + +# sys attributes that are not always defined +sys.gettotalrefcount # Available on python debug builds +sys.last_traceback # Available after an unhandled error has occured +sys.last_type # Available after an unhandled error has occured +sys.last_value # Available after an unhandled error has occured +sys.ps1 # Available in interactive mode +sys.ps2 # Available in interactive mode +sys.tracebacklimit # Must be set first + +# This is only present if Python was built with zlib-ng. +(zlib\.ZLIBNG_VERSION)? +(compression\.zlib\.ZLIBNG_VERSION)? + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +# Pretend typing.ByteString is a Union, to better match its documented semantics. +# As a side effect, this changes the definition of collections.abc.ByteString, which is okay, +# because it's not an ABC that makes any sense and was deprecated in 3.12 +typing\.ByteString + +_ctypes.CFuncPtr # stubtest erroneously thinks it can't be subclassed + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +_frozen_importlib_external.ExtensionFileLoader.get_filename +_frozen_importlib_external.FileLoader.get_filename +_frozen_importlib_external.FileLoader.get_resource_reader +_frozen_importlib_external.FileLoader.load_module + +# Mismatch of default values of `report` parameter: +_markupbase.ParserBase.parse_comment +_markupbase.ParserBase.parse_marked_section + +_typeshed.* # Utility types for typeshed, doesn't exist at runtime +argparse.Namespace.__getattr__ # The whole point of this class is its attributes are dynamic + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.AST.__init__ +_?ast.excepthandler.__init__ +_?ast.expr.__init__ +_?ast.pattern.__init__ +_?ast.stmt.__init__ + +argparse.Namespace.__setattr__ # should allow setting any attribute + +ast.ImportFrom.level # None on the class, but never None on instances +ast.NodeVisitor.visit_\w+ # Methods are discovered dynamically, see #3796 + +# Condition functions are exported in __init__ +asyncio.locks.Condition.acquire +asyncio.locks.Condition.locked +asyncio.locks.Condition.release + +builtins.memoryview.__contains__ # C type that implements __getitem__ +builtins.property.__set_name__ # Doesn't actually exist +builtins.reveal_locals # Builtins that type checkers pretends exist +builtins.reveal_type # Builtins that type checkers pretends exist + +# The following CodecInfo properties are added in __new__ +codecs.CodecInfo.decode +codecs.CodecInfo.encode +codecs.CodecInfo.incrementaldecoder +codecs.CodecInfo.incrementalencoder +codecs.CodecInfo.streamreader +codecs.CodecInfo.streamwriter + +# See comments in file. List out methods that are delegated by __getattr__ at runtime. +# Used to make the relevant class satisfy BinaryIO interface. +codecs.StreamReaderWriter.\w+ +codecs.StreamRecoder.\w+ + +collections.UserList.index # ignoring pos-or-keyword parameter +collections.UserList.sort # Runtime has *args but will error if any are supplied +configparser.SectionProxy.__getattr__ # SectionProxy can have arbitrary attributes when custom converters are used +configparser.SectionProxy.getboolean # SectionProxy get functions are set in __init__ +configparser.SectionProxy.getfloat # SectionProxy get functions are set in __init__ +configparser.SectionProxy.getint # SectionProxy get functions are set in __init__ + +# Treated an alias of a typing class in the stubs, +# they are generic to type checkers anyway. +contextlib.AbstractAsyncContextManager.__class_getitem__ +contextlib.AbstractContextManager.__class_getitem__ + +copy.PyStringMap # defined only in Jython + +# The Dialect properties are initialized as None in Dialect but their values are enforced in _Dialect +csv.Dialect.delimiter +csv.Dialect.doublequote +csv.Dialect.lineterminator +csv.Dialect.quoting +csv.Dialect.skipinitialspace + +csv.DictReader.__init__ # runtime sig has *args but will error if more than 5 positional args are supplied +csv.DictWriter.__init__ # runtime sig has *args but will error if more than 5 positional args are supplied +_?ctypes.Array._type_ # _type_ is abstract, https://github.com/python/typeshed/pull/6361 +_?ctypes.Array._length_ # _length_ is abstract, https://github.com/python/typeshed/pull/6361 +_?ctypes.Array.raw # exists but stubtest can't see it; only available if _CT == c_char +ctypes.CDLL._FuncPtr # None at class level but initialized in __init__ to this value +_?ctypes.Structure.__getattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Structure.__setattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Union.__getattr__ # doesn't exist, but makes things easy if we pretend it does +_?ctypes.Union.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers. +# See https://github.com/python/mypy/issues/2220 and https://github.com/python/typeshed/issues/7813 +_?ctypes.Array.__iter__ +calendar._localized_day.__iter__ +calendar._localized_month.__iter__ + +dataclasses.KW_ONLY # white lies around defaults + +# __all__-related weirdness (see #6523) +email.__all__ +email.base64mime +email.charset +email.encoders +email.errors +email.feedparser +email.generator +email.header +email.iterators +email.message +email.mime +email.parser +email.quoprimime +email.utils + +enum.auto.__or__ # enum.auto is magic, see comments +enum.auto.__and__ # enum.auto is magic, see comments +enum.auto.__xor__ # enum.auto is magic, see comments + +functools._lru_cache_wrapper.cache_parameters # Cannot be detected statically +functools.cached_property.__set__ # doesn't exist, but cached_property is settable by another mechanism + +hmac.new # Raises TypeError if optional argument digestmod is not provided +html.parser.HTMLParser.parse_bogus_comment # default values mismatch +http.HTTPStatus.description # set in __new__; work-around for enum wierdness +http.HTTPStatus.phrase # set in __new__; work-around for enum wierdness +imaplib.IMAP4_SSL.ssl # Depends on the existence and flags of SSL + +importlib._abc.Loader.exec_module # See Lib/importlib/_abc.py. Might be defined for backwards compatibility + +# runtime is *args, **kwargs due to a wrapper; we have more accurate signatures in the stubs +importlib.abc.FileLoader.get_filename +importlib.abc.FileLoader.load_module + +importlib.metadata._meta.SimplePath.joinpath # Runtime definition of protocol is incorrect + +# We can't distinguish not having a default value from having a default value of inspect.Parameter.empty +inspect.Parameter.__init__ +inspect.Signature.__init__ + +logging.LogRecord.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +mmap.mmap.__iter__ +mmap.mmap.__contains__ + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.BaseListProxy.__len__ +multiprocessing.managers.BaseListProxy.__reversed__ +multiprocessing.managers.BaseListProxy.reverse +multiprocessing.managers.BaseListProxy.sort + +# runtime is *args, **kwargs due to a wrapper, but we have more accurate signatures in the stubs +multiprocessing.managers.SyncManager.Event +multiprocessing.managers.SyncManager.Lock +multiprocessing.managers.SyncManager.Namespace +multiprocessing.managers.SyncManager.RLock + +multiprocessing.(dummy|managers).Namespace.__[gs]etattr__ # Any field can be set on Namespace +multiprocessing.pool.Pool.__del__ # Non-private parameter on __del__ + +# These are because the ctx argument has a default value in the stubs but not +# at runtime. This is a compromise between the runtime signatures of (for example) +# multiprocessing.Queue and multiprocessing.queues.Queue, which typeshed +# treats as the same object. +multiprocessing.queues.JoinableQueue.__init__ +multiprocessing.queues.Queue.__init__ +multiprocessing.queues.SimpleQueue.__init__ + +# These methods are dynamically created after object initialization, +# copied from a wrapped lock object. Stubtest doesn't think they exist +# because of that. +multiprocessing.synchronize.Condition.acquire +multiprocessing.synchronize.Condition.release +multiprocessing.synchronize.SemLock.acquire +multiprocessing.synchronize.SemLock.release + +numbers.Number.__hash__ # typeshed marks this as abstract but code just sets this as None + +optparse.Values.__getattr__ # Some attributes are set in __init__ using setattr +optparse.Values.__setattr__ # doesn't exist, but makes things easy if we pretend it does + +os._wrap_close.read # Methods that come from __getattr__() at runtime +os._wrap_close.readable # Methods that come from __getattr__() at runtime +os._wrap_close.readline # Methods that come from __getattr__() at runtime +os._wrap_close.readlines # Methods that come from __getattr__() at runtime +os._wrap_close.writable # Methods that come from __getattr__() at runtime +os._wrap_close.write # Methods that come from __getattr__() at runtime +os._wrap_close.writelines # Methods that come from __getattr__() at runtime +os.PathLike.__class_getitem__ # PathLike is a protocol; we don't expect all PathLike classes to implement class_getitem + +_pickle.Pickler.reducer_override # Can be added by subclasses +pickle._Pickler\..* # Best effort typing for undocumented internals +pickle._Unpickler\..* # Best effort typing for undocumented internals + +socketserver.BaseServer.get_request # Not implemented, but expected to exist on subclasses. +ssl.PROTOCOL_SSLv2 # Depends on the existence and flags of SSL +ssl.PROTOCOL_SSLv3 # Depends on the existence and flags of SSL +tarfile.TarFile.errors # errors is initialized for some reason as None even though it really only accepts str +tempfile._TemporaryFileWrapper.[\w_]+ # Dynamically specified by __getattr__, and thus don't exist on the class +threading.Condition.acquire # Condition functions are exported in __init__ +threading.Condition.release # Condition functions are exported in __init__ + +# A factory function that returns 'most efficient lock'. +# Marking it as a function will make it impossible for users to use the Lock type as an annotation. +threading.RLock + +tkinter.Misc.after # we intentionally don't allow everything that "works" at runtime + +# Methods that come from __getattr__() at runtime +tkinter.Tk.adderrorinfo +tkinter.Tk.call +tkinter.Tk.createcommand +tkinter.Tk.createtimerhandler +tkinter.Tk.dooneevent +tkinter.Tk.eval +tkinter.Tk.evalfile +tkinter.Tk.exprboolean +tkinter.Tk.exprdouble +tkinter.Tk.exprlong +tkinter.Tk.exprstring +tkinter.Tk.globalgetvar +tkinter.Tk.globalsetvar +tkinter.Tk.globalunsetvar +tkinter.Tk.interpaddr +tkinter.Tk.record +tkinter.Tk.splitlist +tkinter.Tk.unsetvar +tkinter.Tk.wantobjects +tkinter.Tk.willdispatch + +tkinter.Misc.grid_propagate # The noarg placeholder is a set value list +tkinter.Misc.pack_propagate # The noarg placeholder is a set value list +tkinter.Tk.report_callback_exception # A bit of a lie, since it's actually a method, but typing it as an attribute allows it to be assigned to +tkinter.Wm.wm_iconphoto # Default value of argument can't be used without runtime error +tkinter.font.Font.__getitem__ # Argument name differs (doesn't matter for __dunder__ methods) +traceback.TracebackException.from_exception # explicitly expanding arguments going into TracebackException __init__ +turtle.ScrolledCanvas.find_all # Dynamically created, has unnecessary *args +turtle.ScrolledCanvas.select_clear # Dynamically created, has unnecessary *args +turtle.ScrolledCanvas.select_item # Dynamically created, has unnecessary *args +# this is implemented with *args having a minimum size so arguments before it must be positional (but stubtest doesn't see that) +tkinter.ttk.Style.element_create + +types.GenericAlias.__call__ # Would be complicated to fix properly, Any could silence problems. #6392 +types.GenericAlias.__getattr__ + +typing.type_check_only # typing decorator that is not available at runtime + +# Details of runtime definition don't need to be in stubs +typing._Final +typing._Final.__init_subclass__ +typing\.Protocol +typing(_extensions)?\._TypedDict +typing(_extensions)?\.Any.* +typing(_extensions)?\.TypedDict + +# Special primitives +typing(_extensions)?\.AbstractSet +typing(_extensions)?\.AsyncGenerator +typing(_extensions)?\.AsyncIterable +typing(_extensions)?\.AsyncIterator +typing(_extensions)?\.Awaitable +typing(_extensions)?\.Collection +typing(_extensions)?\.Container +typing(_extensions)?\.Coroutine +typing(_extensions)?\.Generator +typing(_extensions)?\.Hashable +typing(_extensions)?\.ItemsView +typing(_extensions)?\.Iterable +typing(_extensions)?\.Iterator +typing(_extensions)?\.KeysView +typing(_extensions)?\.Mapping +typing(_extensions)?\.MappingView +typing(_extensions)?\.MutableMapping +typing(_extensions)?\.MutableSequence +typing(_extensions)?\.MutableSet +typing(_extensions)?\.NamedTuple +typing(_extensions)?\.Reversible +typing(_extensions)?\.Sequence +typing(_extensions)?\.Sized +typing(_extensions)?\.ValuesView + +# Typing-related weirdness +typing._SpecialForm.__call__ +typing._SpecialForm.__init__ + +# These are abstract properties at runtime, +# but marking them as such in the stub breaks half the the typed-Python ecosystem (see #8726) +typing(_extensions)?\.IO\.closed +typing(_extensions)?\.IO\.mode +typing(_extensions)?\.IO\.name +typing(_extensions)?\.TextIO\.buffer +typing(_extensions)?\.TextIO\.encoding +typing(_extensions)?\.TextIO\.errors +typing(_extensions)?\.TextIO\.line_buffering +typing(_extensions)?\.TextIO\.newlines + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +# See https://github.com/python/typeshed/commit/97bc450acd60c1bcdafef3ce8fbe3b95a9c0cac3 +typing(_extensions)?\.IO\.__iter__ +typing(_extensions)?\.IO\.__next__ + +types.MethodType.__closure__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.MethodType.__code__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.MethodType.__defaults__ # read-only but not actually a property; stubtest thinks it doesn't exist. +types.ModuleType.__dict__ # read-only but not actually a property; stubtest thinks it's a mutable attribute. +types.ModuleType.__getattr__ # this doesn't exist at runtime +unittest.runner._WritelnDecorator.flush # Methods that come from __getattr__() at runtime +unittest.runner._WritelnDecorator.write # Methods that come from __getattr__() at runtime +urllib.response.addbase.write # Methods that come from __getattr__() at runtime +urllib.response.addbase.writelines # Methods that come from __getattr__() at runtime + +(hashlib.__all__)? # scrypt depends on how OpenSSL was built. +(pydoc.Doc.getdocloc)? # Runtime default is an installation-specific stdlib path. + +_?weakref\.CallableProxyType\.__getattr__ # Should have all attributes of proxy +_?weakref\.(ref|ReferenceType)\.__init__ # C implementation has incorrect signature +_?weakref\.(ref|ReferenceType)\.__call__ # C function default annotation is wrong +_?weakref\.ProxyType\.__getattr__ # Should have all attributes of proxy +_?weakref\.ProxyType\.__reversed__ # Doesn't really exist +weakref.WeakValueDictionary.setdefault # has a default value for the "default" argument, but always errors out if no value is supplied for the parameter by the user + +webbrowser.UnixBrowser.remote_action # Always overridden in inheriting class +webbrowser.UnixBrowser.remote_action_newtab # Always overridden in inheriting class +webbrowser.UnixBrowser.remote_action_newwin # Always overridden in inheriting class +xml.__all__ # __all__-related weirdness (see #6523) +xml.dom # __all__-related weirdness (see #6523) +xml.etree # __all__-related weirdness (see #6523) +xml.parsers # __all__-related weirdness (see #6523) +xml.sax # __all__-related weirdness (see #6523) +xml.dom.minidom.StringTypes # Unnecessary re-export +xml.etree.ElementTree.XMLParser.__init__ # Defined in C so has general signature + +# Iterable classes that don't define __iter__ at runtime (usually iterable via __getitem__) +# These would ideally be special-cased by type checkers; see https://github.com/python/mypy/issues/2220 +xml.etree.ElementTree.Element.__iter__ diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py310.txt b/stdlib/@tests/stubtest_allowlists/darwin-py310.txt new file mode 100644 index 000000000000..86b8608f39eb --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py310.txt @@ -0,0 +1,77 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.10.12 +# (Remove once 3.10.12 becomes available for GitHub Actions) +shutil.unpack_archive +tarfile.AbsoluteLinkError +tarfile.AbsolutePathError +tarfile.FilterError +tarfile.LinkOutsideDestinationError +tarfile.OutsideDestinationError +tarfile.SpecialFileError +tarfile.TarFile.extract +tarfile.TarFile.extractall +tarfile.TarInfo.replace +tarfile.data_filter +tarfile.fully_trusted_filter +tarfile.tar_filter + +# Incompatible changes introduced in Python 3.10.14 +# (Remove once 3.10.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.GetReparseDeferralEnabled +pyexpat.XMLParserType.SetReparseDeferralEnabled +xml.etree.ElementTree.XMLParser.flush +xml.etree.ElementTree.XMLPullParser.flush +xml.sax.expatreader.ExpatParser.flush +zipfile.ZipInfo.__slots__ + +# Incompatible changes introduced in Python 3.10.15 +# (Remove once 3.10.15 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.10.17 +# (Remove once 3.10.17 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.10.18 +# (Remove once 3.10.18 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.10.20 +# (Remove once 3.10.20 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py311.txt b/stdlib/@tests/stubtest_allowlists/darwin-py311.txt new file mode 100644 index 000000000000..24b7d5d8ceca --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py311.txt @@ -0,0 +1,70 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.11.10 +# (Remove once 3.11.10 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.11.12 +# (Remove once 3.11.12 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.11.13 +# (Remove once 3.11.13 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.11.15 +# (Remove once 3.11.15 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============ +# 3.11 to 3.12 +# ============ + +# Not present on all MacOS versions +fcntl.F_OFD_GETLK +fcntl.F_OFD_SETLK +fcntl.F_OFD_SETLKW + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd + + +# ================ +# Unclear problems +# ================ + +# Added in 3.11.1, flagged by stubtest on Python < 3.14 for unknown reasons +errno.ENOTCAPABLE diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py312.txt b/stdlib/@tests/stubtest_allowlists/darwin-py312.txt new file mode 100644 index 000000000000..003efdd5b489 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py312.txt @@ -0,0 +1,57 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.12.11 +# (Remove once 3.12.11 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.12.13 +# (Remove once 3.12.13 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============ +# 3.11 to 3.12 +# ============ + +# Not present on all MacOS versions +fcntl.F_OFD_GETLK +fcntl.F_OFD_SETLK +fcntl.F_OFD_SETLKW + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Doesn't exist on macos: +_msi +msilib(.[a-z]+)? +ossaudiodev +spwd + + +# ================ +# Unclear problems +# ================ + +# Added in 3.11.1, flagged by stubtest on Python < 3.14 for unknown reasons +errno.ENOTCAPABLE diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py313.txt b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt new file mode 100644 index 000000000000..681f65781662 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py313.txt @@ -0,0 +1,15 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.13.13, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ======= +# >= 3.13 +# ======= + +(mmap.MAP_32BIT)? # Exists locally on MacOS but not on GitHub diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py314.txt b/stdlib/@tests/stubtest_allowlists/darwin-py314.txt new file mode 100644 index 000000000000..b651b2826e49 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py314.txt @@ -0,0 +1,23 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.14.4, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ========= +# 3.14 only +# ========= + +# Starting with Python 3.14.1, these methods accept None for some of their +# parameters, but would raise a TypeError with Python 3.14.0. +mmap.mmap.madvise + +# ======= +# >= 3.13 +# ======= + +(mmap.MAP_32BIT)? # Exists locally on MacOS but not on GitHub diff --git a/stdlib/@tests/stubtest_allowlists/darwin-py315.txt b/stdlib/@tests/stubtest_allowlists/darwin-py315.txt new file mode 100644 index 000000000000..66aaf8d21845 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin-py315.txt @@ -0,0 +1,25 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# Depends on the ncurses version used to build Python. +(_curses.BUTTON5_CLICKED)? +(_curses.BUTTON5_DOUBLE_CLICKED)? +(_curses.BUTTON5_PRESSED)? +(_curses.BUTTON5_RELEASED)? +(_curses.BUTTON5_TRIPLE_CLICKED)? + +# Platform/build availability differs across Darwin builds. +(_socket.SO_BINDTODEVICE)? +(errno.ENOTCAPABLE)? + +# Depends on how readline was built. +readline.get_pre_input_hook + +# Internal implementation details of the sampling profiler. +profiling.sampling.live_collector +profiling.sampling.live_collector.collector +profiling.sampling.live_collector.constants +profiling.sampling.live_collector.display +profiling.sampling.live_collector.trend_tracker +profiling.sampling.live_collector.widgets diff --git a/stdlib/@tests/stubtest_allowlists/darwin.txt b/stdlib/@tests/stubtest_allowlists/darwin.txt new file mode 100644 index 000000000000..f1eb01ce62a5 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/darwin.txt @@ -0,0 +1,53 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +(os|posix).sched_param # system dependent. Unclear if macos has it. + +# Sometimes these seem to exist on darwin, sometimes not +(_?curses.A_ITALIC)? # ncurses extension +(fcntl.F_GETLEASE)? # GNU extension +(fcntl.F_SETLEASE)? # GNU extension + + +# ========================================== +# Modules that do not exist on MacOS systems +# ========================================== + +_winapi +asyncio.windows_events +asyncio.windows_utils +encodings.oem +encodings.mbcs +msvcrt +nt +winreg +winsound + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +_gdbm # Only available if compiled with libgdbm + +_?curses.ACS_.* # ACS codes are initialized only after initscr call +curses.COLORS # Initialized after start_color +curses.COLOR_PAIRS # Initialized after start_color +curses.COLS # Initialized only after initscr call +curses.LINES # Initialized only after initscr call +multiprocessing.popen_spawn_win32 # exists on Darwin but fails to import +readline.append_history_file # Only available if compiled with GNU readline, not editline +select.poll # Actually a function; we have a class so it can be used as a type + +tkinter.Tk.createfilehandler # Methods that come from __getattr__() at runtime +tkinter.Tk.deletefilehandler # Methods that come from __getattr__() at runtime + +# These entries looks like a `setup-python` bug: +(dbm.gnu)? +(_?locale.bind_textdomain_codeset)? +(_?locale.bindtextdomain)? +(_?locale.dcgettext)? +(_?locale.dgettext)? +(_?locale.gettext)? +(_?locale.textdomain)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py310.txt b/stdlib/@tests/stubtest_allowlists/linux-py310.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py310.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py311.txt b/stdlib/@tests/stubtest_allowlists/linux-py311.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py311.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py312.txt b/stdlib/@tests/stubtest_allowlists/linux-py312.txt new file mode 100644 index 000000000000..a4083aa22ed7 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py312.txt @@ -0,0 +1,10 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# doesn't exist on linux +_msi +msilib(.[a-z]+)? + +# doesn't exist in all installations +(nis)? diff --git a/stdlib/@tests/stubtest_allowlists/linux-py313.txt b/stdlib/@tests/stubtest_allowlists/linux-py313.txt new file mode 100644 index 000000000000..4fccdd15a0b5 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py313.txt @@ -0,0 +1,9 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.13.13, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp diff --git a/stdlib/@tests/stubtest_allowlists/linux-py314.txt b/stdlib/@tests/stubtest_allowlists/linux-py314.txt new file mode 100644 index 000000000000..cf414e9a9b3b --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py314.txt @@ -0,0 +1,17 @@ +# ============= +# 3.13 and 3.14 +# ============= + +# Starting with Python 3.14.4, these methods accept None for the "scheduler" +# and "setpgroup" parameters, but would raise a TypeError with Python 3.13.12 +# and earlier. For compatibility reasons, we don't allow None in the stubs. +os.posix_spawn +os.posix_spawnp + +# ========= +# 3.14 only +# ========= + +# Starting with Python 3.14.1, these methods accept None for some of their +# parameters, but would raise a TypeError with Python 3.14.0. +mmap.mmap.madvise diff --git a/stdlib/@tests/stubtest_allowlists/linux-py315.txt b/stdlib/@tests/stubtest_allowlists/linux-py315.txt new file mode 100644 index 000000000000..c2c4eb6ab13d --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux-py315.txt @@ -0,0 +1,19 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# GitHub Actions' Python 3.15 Linux build currently lacks _decimal, so +# decimal falls back to _pydecimal with different runtime signatures. +_decimal +decimal\..* + +# Depends on how readline was built. +readline.get_pre_input_hook + +# Internal implementation details of the sampling profiler. +profiling.sampling.live_collector +profiling.sampling.live_collector.collector +profiling.sampling.live_collector.constants +profiling.sampling.live_collector.display +profiling.sampling.live_collector.trend_tracker +profiling.sampling.live_collector.widgets diff --git a/stdlib/@tests/stubtest_allowlists/linux.txt b/stdlib/@tests/stubtest_allowlists/linux.txt new file mode 100644 index 000000000000..df86aeeb40a9 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/linux.txt @@ -0,0 +1,137 @@ +# ========================================== +# Modules that do not exist on Linux systems +# ========================================== + +_winapi +asyncio.windows_events +asyncio.windows_utils +encodings.oem +encodings.mbcs +msvcrt +nt +winreg +winsound + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +_?curses.ACS_.* # ACS codes are initialized only after initscr call +curses.COLORS # Initialized after start_color +curses.COLOR_PAIRS # Initialized after start_color +curses.COLS # Initialized only after initscr call +curses.LINES # Initialized only after initscr call +fcntl.I_[A-Z0-9_]+ # Platform differences that cannot be captured by the type system +multiprocessing.popen_spawn_win32 # exists on Linux but fails to import +select.poll # Actually a function; we have a class so it can be used as a type + +# Bluetooth constants which aren't on the GitHub Actions runners, see #15207 +(_?socket\.AF_BLUETOOTH)? +(_?socket\.BDADDR_ANY)? +(_?socket\.BDADDR_BREDR)? +(_?socket\.BDADDR_LE_PUBLIC)? +(_?socket\.BDADDR_LE_RANDOM)? +(_?socket\.BDADDR_LOCAL)? +(_?socket\.BT_CHANNEL_POLICY)? +(_?socket\.BT_CHANNEL_POLICY_BREDR_ONLY)? +(_?socket\.BT_CHANNEL_POLICY_BREDR_PREFERRED)? +(_?socket\.BT_CODEC)? +(_?socket\.BT_DEFER_SETUP)? +(_?socket\.BT_FLUSHABLE)? +(_?socket\.BT_FLUSHABLE_OFF)? +(_?socket\.BT_FLUSHABLE_ON)? +(_?socket\.BT_ISO_QOS)? +(_?socket\.BT_MODE)? +(_?socket\.BT_MODE_BASIC)? +(_?socket\.BT_MODE_ERTM)? +(_?socket\.BT_MODE_EXT_FLOWCTL)? +(_?socket\.BT_MODE_LE_FLOWCTL)? +(_?socket\.BT_MODE_STREAMING)? +(_?socket\.BT_PHY)? +(_?socket\.BT_PHY_BR_1M_1SLOT)? +(_?socket\.BT_PHY_BR_1M_3SLOT)? +(_?socket\.BT_PHY_BR_1M_5SLOT)? +(_?socket\.BT_PHY_EDR_2M_1SLOT)? +(_?socket\.BT_PHY_EDR_2M_3SLOT)? +(_?socket\.BT_PHY_EDR_2M_5SLOT)? +(_?socket\.BT_PHY_EDR_3M_1SLOT)? +(_?socket\.BT_PHY_EDR_3M_3SLOT)? +(_?socket\.BT_PHY_EDR_3M_5SLOT)? +(_?socket\.BT_PHY_LE_1M_RX)? +(_?socket\.BT_PHY_LE_1M_TX)? +(_?socket\.BT_PHY_LE_2M_RX)? +(_?socket\.BT_PHY_LE_2M_TX)? +(_?socket\.BT_PHY_LE_CODED_RX)? +(_?socket\.BT_PHY_LE_CODED_TX)? +(_?socket\.BT_PKT_STATUS)? +(_?socket\.BT_POWER)? +(_?socket\.BT_POWER_FORCE_ACTIVE_OFF)? +(_?socket\.BT_POWER_FORCE_ACTIVE_ON)? +(_?socket\.BT_RCVMTU)? +(_?socket\.BT_SECURITY)? +(_?socket\.BT_SECURITY_FIPS)? +(_?socket\.BT_SECURITY_HIGH)? +(_?socket\.BT_SECURITY_LOW)? +(_?socket\.BT_SECURITY_MEDIUM)? +(_?socket\.BT_SECURITY_SDP)? +(_?socket\.BT_SNDMTU)? +(_?socket\.BT_VOICE)? +(_?socket\.BT_VOICE_CVSD_16BIT)? +(_?socket\.BT_VOICE_TRANSPARENT)? +(_?socket\.BT_VOICE_TRANSPARENT_16BIT)? +(_?socket\.BTPROTO_HCI)? +(_?socket\.BTPROTO_L2CAP)? +(_?socket\.BTPROTO_RFCOMM)? +(_?socket\.BTPROTO_SCO)? +(_?socket\.HCI_CHANNEL_CONTROL)? +(_?socket\.HCI_CHANNEL_LOGGING)? +(_?socket\.HCI_CHANNEL_MONITOR)? +(_?socket\.HCI_CHANNEL_RAW)? +(_?socket\.HCI_CHANNEL_USER)? +(_?socket\.HCI_DEV_NONE)? +(_?socket\.L2CAP_LM)? +(_?socket\.L2CAP_LM_AUTH)? +(_?socket\.L2CAP_LM_ENCRYPT)? +(_?socket\.L2CAP_LM_MASTER)? +(_?socket\.L2CAP_LM_RELIABLE)? +(_?socket\.L2CAP_LM_SECURE)? +(_?socket\.L2CAP_LM_TRUSTED)? +(_?socket\.SOL_BLUETOOTH)? +(_?socket\.SOL_L2CAP)? +(_?socket\.SOL_RFCOMM)? +(_?socket\.SOL_SCO)? + +# These seem like they should be available on Linux, but they're not +# on GitHub Actions runners for some reason. +_?socket.IPX_TYPE +_?socket.RDS_CANCEL_SENT_TO +_?socket.RDS_CMSG_RDMA_ARGS +_?socket.RDS_CMSG_RDMA_DEST +_?socket.RDS_CMSG_RDMA_MAP +_?socket.RDS_CMSG_RDMA_STATUS +_?socket.RDS_CONG_MONITOR +_?socket.RDS_FREE_MR +_?socket.RDS_GET_MR +_?socket.RDS_GET_MR_FOR_DEST +_?socket.RDS_RDMA_DONTWAIT +_?socket.RDS_RDMA_FENCE +_?socket.RDS_RDMA_INVALIDATE +_?socket.RDS_RDMA_NOTIFY_ME +_?socket.RDS_RDMA_READWRITE +_?socket.RDS_RDMA_SILENT +_?socket.RDS_RDMA_USE_ONCE +_?socket.RDS_RECVERR +_?socket.SOL_ATALK +_?socket.SOL_AX25 +_?socket.SOL_HCI +_?socket.SOL_IPX +_?socket.SOL_NETROM +_?socket.SOL_ROSE + +# This is available on Linux, but it's documented as for kernel debugging and +# not present on GitHub Actions runners. +termios.TIOCTTYGSTRUCT + +tkinter.Tk.createfilehandler # Methods that come from __getattr__() at runtime +tkinter.Tk.deletefilehandler # Methods that come from __getattr__() at runtime diff --git a/stdlib/@tests/stubtest_allowlists/py310.txt b/stdlib/@tests/stubtest_allowlists/py310.txt new file mode 100644 index 000000000000..4f1fe3bae1fd --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py310.txt @@ -0,0 +1,287 @@ +# ========================= +# New errors in Python 3.10 +# ========================= + +# ========= +# 3.10 only +# ========= + +# The "loop" argument exists at runtime, but raises TypeError if you try to provide any value for it +asyncio.locks.BoundedSemaphore.__init__ +asyncio.locks.Condition.__init__ +asyncio.locks.Event.__init__ +asyncio.locks.Lock.__init__ +asyncio.locks.Semaphore.__init__ +asyncio.queues.Queue.__init__ + +_random.Random.__init__ # Issues with __new__/__init__ correspondence + +bdb.Breakpoint.clearBreakpoints # Exists at runtime, but missing from stubs + +# Only exists for an error message. +typing_extensions.NewType.__mro_entries__ + + +# ============ +# 3.10 to 3.11 +# ============ + +importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protocol is incorrect + + +# ======= +# <= 3.10 +# ======= + +builtins.float.__setformat__ # Internal method for CPython test suite +email.contentmanager.typ +gettext.install # codeset default value is ['unspecified'] so can't be specified +gettext.translation # codeset default value is ['unspecified'] so can't be specified +inspect.Signature.from_builtin # Removed in 3.11, can add if someone needs this +inspect.Signature.from_function # Removed in 3.11, can add if someone needs this + +# SpooledTemporaryFile implements IO except these methods before Python 3.11 +# See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918 +tempfile.SpooledTemporaryFile.__next__ +tempfile.SpooledTemporaryFile.readable +tempfile.SpooledTemporaryFile.seekable +tempfile.SpooledTemporaryFile.writable + +tkinter.Tk.split # Exists at runtime, but missing from stubs +typing._SpecialForm.__mro_entries__ # Exists at runtime, but missing from stubs + +typing_extensions.LiteralString + +# Will always raise. Not included to avoid type checkers inferring that +# Sentinel instances are callable. +typing_extensions.sentinel.__call__ + + +# ======= +# <= 3.11 +# ======= + +enum.Enum._generate_next_value_ +importlib.abc.Finder.find_module +urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified +xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +importlib.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 only +# =============================================================== + +importlib.abc.Traversable.joinpath # Problematic protocol signatures at runtime, see source code comments. + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 to 3.11 +# ================================================================== + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedList.reverse +importlib.metadata.DeprecatedList.sort + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing.ParamSpec(Args|Kwargs).__origin__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.10 +# ============================================================= + +# Side effects from module initialization +_compat_pickle.excname +email.contentmanager.maintype +email.contentmanager.subtype +inspect.k +inspect.mod_dict +inspect.v +json.encoder.i +lib2to3.pgen2.grammar.line +lib2to3.pgen2.grammar.name +lib2to3.pgen2.grammar.op + +pstats.SortKey.__new__ # Derives from (str, Enum) +pydoc.Helper.symbol # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +pydoc.Helper.symbols_ # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +pydoc.Helper.topic # Loop variable in class https://github.com/python/typeshed/issues/6401#issuecomment-981178522 +sqlite3.test # Modules that exist at runtime, but shouldn't be added to typeshed +sqlite3\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter.EventType.__new__ # Derives from (str, Enum) +types.CodeType.replace # stubtest thinks default values are None but None doesn't work at runtime + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.11 +# ============================================================= + +.*.__buffer__ # We lie about the existence of these methods +.*.__release_buffer__ # We lie about the existence of these methods +asynchat.async_chat.encoding # Removed in 3.12 +asynchat.async_chat.use_encoding # Removed in 3.12 +asynchat.find_prefix_at_end # Removed in 3.12 +asyncore.dispatcher.addr # Removed in 3.12 +asyncore.dispatcher.handle_accepted # Removed in 3.12 +ctypes.test # Modules that exist at runtime, but shouldn't be added to typeshed +ctypes\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +distutils\..* # Removed in 3.12 +lib2to3.tests # Modules that exist at runtime, but shouldn't be added to typeshed +lib2to3\.tests\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +pkgutil.ImpImporter\..* # Removed in 3.12 +pkgutil.ImpLoader\..* # Removed in 3.12 +platform.platform # runtime default is 0, we pretend it's a bool +poplib.POP3_SSL.stls # bad declaration of inherited function. See poplib.pyi +tkinter.test # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + +# We call them read-only properties, runtime implementation is slightly different +typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__ + +unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed +unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py311.txt b/stdlib/@tests/stubtest_allowlists/py311.txt new file mode 100644 index 000000000000..69f314e576ab --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py311.txt @@ -0,0 +1,268 @@ +# ========================= +# New errors in Python 3.11 +# ========================= + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ========= +# 3.11 only +# ========= + +# Not strictly speaking a staticmethod on 3.11, but it acts like one: +enum.StrEnum._generate_next_value_ + + +# ==================================== +# Pre-existing errors from Python 3.10 +# ==================================== + + +# ============ +# 3.10 to 3.11 +# ============ + +importlib.metadata._meta.SimplePath.__truediv__ # Runtime definition of protocol is incorrect + + +# ======= +# <= 3.11 +# ======= + +enum.Enum._generate_next_value_ +importlib.abc.Finder.find_module +urllib.request.HTTPPasswordMgrWithPriorAuth.__init__ # Args are passed as is to super, so super args are specified +xml.etree.ElementTree.Element.__bool__ # Doesn't really exist; see comments in stub + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 only +# =============================================================== + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing\.TypeVar\.__.*__ +typing\.ParamSpec\.__.*__ + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.12 +# ================================================================== + +configparser.LegacyInterpolation.__init__ # runtime is *args, **kwargs, but it's just a passthrough + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.10 to 3.11 +# ================================================================== + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedList.reverse +importlib.metadata.DeprecatedList.sort + +# We pretend it's a read-only property for forward compatibility with 3.12 +typing.ParamSpec(Args|Kwargs).__origin__ + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.11 +# ============================================================= + +.*.__buffer__ # We lie about the existence of these methods +.*.__release_buffer__ # We lie about the existence of these methods +asynchat.async_chat.encoding # Removed in 3.12 +asynchat.async_chat.use_encoding # Removed in 3.12 +asynchat.find_prefix_at_end # Removed in 3.12 +asyncore.dispatcher.addr # Removed in 3.12 +asyncore.dispatcher.handle_accepted # Removed in 3.12 +ctypes.test # Modules that exist at runtime, but shouldn't be added to typeshed +ctypes\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +distutils\..* # Removed in 3.12 +lib2to3.tests # Modules that exist at runtime, but shouldn't be added to typeshed +lib2to3\.tests\..+ # Modules that exist at runtime, but shouldn't be added to typeshed +pkgutil.ImpImporter\..* # Removed in 3.12 +pkgutil.ImpLoader\..* # Removed in 3.12 +platform.platform # runtime default is 0, we pretend it's a bool +poplib.POP3_SSL.stls # bad declaration of inherited function. See poplib.pyi +tkinter.test # Modules that exist at runtime, but shouldn't be added to typeshed +tkinter\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + +# We call them read-only properties, runtime implementation is slightly different +typing_extensions\.TypeAliasType\.__(parameters|type_params|name|module|value)__ + +unittest.test # Modules that exist at runtime, but shouldn't be added to typeshed +unittest\.test\..+ # Modules that exist at runtime, but shouldn't be added to typeshed + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py312.txt b/stdlib/@tests/stubtest_allowlists/py312.txt new file mode 100644 index 000000000000..28f037fe9099 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py312.txt @@ -0,0 +1,248 @@ +# ========================= +# New errors in Python 3.12 +# ========================= + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ============ +# 3.12 to 3.13 +# ============ + +# Initialized at runtime +typing_extensions.TypeAliasType.__parameters__ +typing_extensions.TypeAliasType.__value__ + + +# ==================================== +# Pre-existing errors from Python 3.11 +# ==================================== + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ======= +# <= 3.12 +# ======= + +# Exists at runtime, but missing from stubs +lib2to3.btm_utils +lib2to3.fixer_util +lib2to3.patcomp +lib2to3.pgen2.grammar.Grammar.loads +lib2to3.pygram.pattern_symbols +lib2to3.pygram.python_symbols +lib2to3.pytree.Base.__new__ +lib2to3.pytree.Base.children +lib2to3.pytree.Base.type +lib2to3.pytree.BasePattern.__new__ +lib2to3.pytree.BasePattern.type +lib2to3.pytree.NegatedPattern.match +lib2to3.pytree.NegatedPattern.match_seq +tkinter.tix.[A-Z_]+ +tkinter.tix.CObjView +tkinter.tix.DialogShell +tkinter.tix.ExFileSelectDialog +tkinter.tix.FileSelectDialog +tkinter.tix.FileTypeList +tkinter.tix.Grid +tkinter.tix.NoteBookFrame +tkinter.tix.OptionName +tkinter.tix.ResizeHandle +tkinter.tix.ScrolledGrid +tkinter.tix.ScrolledHList +tkinter.tix.ScrolledListBox +tkinter.tix.ScrolledTList +tkinter.tix.ScrolledText +tkinter.tix.ScrolledWindow +tkinter.tix.Shell +tkinter.tix.TclVersion +tkinter.tix.TkVersion + +# Details of runtime definition don't need to be in stubs +typing_extensions\.ParamSpec.* +typing_extensions\.TypeVar.* + +# These are typing._SpecialGenericAlias at runtime, which is not a real type, but it +# behaves like one in most cases +typing(_extensions)?\.(Async)?ContextManager + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super + + +# =============================================================== +# Allowlist entries that cannot or should not be fixed; 3.12 only +# =============================================================== + +concurrent.futures.__all__ # Incompatible changes introduced in Python 3.12.5 +ctypes._endian.SIZEOF_TIME_T # Incorrectly star import. + + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.12 +# ================================================================== + +configparser.LegacyInterpolation.__init__ # runtime is *args, **kwargs, but it's just a passthrough + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Undocumented implementation details +cgi.FieldStorage.bufsize +cgi.FieldStorage.read_binary +cgi.FieldStorage.read_lines +cgi.FieldStorage.read_lines_to_eof +cgi.FieldStorage.read_lines_to_outerboundary +cgi.FieldStorage.read_multi +cgi.FieldStorage.read_single +cgi.FieldStorage.read_urlencoded +cgi.FieldStorage.skip_lines + +ctypes._endian.DEFAULT_MODE # Incorrectly star import. +ctypes._endian.RTLD_GLOBAL # Incorrectly star import. +ctypes._endian.RTLD_LOCAL # Incorrectly star import. + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers.DictProxy.__iter__ +multiprocessing.managers.DictProxy.__len__ +multiprocessing.managers.DictProxy.copy +multiprocessing.managers.DictProxy.items +multiprocessing.managers.DictProxy.keys +multiprocessing.managers.DictProxy.values + +# Runtime signature is incorrect (https://github.com/python/cpython/issues/93021) +multiprocessing.managers.DictProxy.clear +multiprocessing.managers.DictProxy.popitem + +# Undocumented implementation details +pipes.Template.makepipeline +pipes.Template.open_r +pipes.Template.open_w +sunau.Au_read.initfp +sunau.Au_write.initfp + +threading.Lock # Factory function at runtime, but that wouldn't let us use it in type hints +types.SimpleNamespace.__init__ # class doesn't accept positional arguments but has default C signature +typing_extensions\.Annotated # Undocumented implementation details +typing\.Annotated # Super-special typing primitive + +# These methods have no default implementation for Python < 3.13. +_pickle.Pickler.persistent_id +_pickle.Unpickler.persistent_load diff --git a/stdlib/@tests/stubtest_allowlists/py313.txt b/stdlib/@tests/stubtest_allowlists/py313.txt new file mode 100644 index 000000000000..22dcac6f46ca --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py313.txt @@ -0,0 +1,170 @@ +# ========================= +# New errors in Python 3.13 +# ========================= + +# ==================================== +# Pre-existing errors from Python 3.12 +# ==================================== + + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ============ +# 3.12 to 3.13 +# ============ + +# Initialized at runtime +typing_extensions.TypeAliasType.__parameters__ +typing_extensions.TypeAliasType.__value__ + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ============ +# 3.11 to 3.13 +# ============ + +enum.Enum.__init__ + + +# ======= +# <= 3.13 +# ======= + +ast.Ellipsis.__new__ # Implementation has *args, but shouldn't allow any + +_?hashlib.scrypt # Raises TypeError if salt, n, r or p are None + +# Will always raise. Not included to avoid type checkers inferring that +# TypeAliasType instances are callable. +typing_extensions.TypeAliasType.__call__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + +# TypeVarTuple is a wrapper class that returns typing.TypeVarTuple instances. +# Keep __new__ checked because it is the wrapper's public constructor. +typing_extensions\.TypeVarTuple +typing_extensions\.TypeVarTuple\.(?!__new__).* + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior +types.MappingProxyType.get + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive + +# Don't always exist at runtime +(pdb.Pdb.curframe_locals)? + +# ================================================================== +# Allowlist entries that cannot or should not be fixed; 3.11 to 3.13 +# ================================================================== + +argparse._MutuallyExclusiveGroup.add_mutually_exclusive_group # deprecated, forwards arguments to super diff --git a/stdlib/@tests/stubtest_allowlists/py314.txt b/stdlib/@tests/stubtest_allowlists/py314.txt new file mode 100644 index 000000000000..b76fa29cd7d2 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py314.txt @@ -0,0 +1,199 @@ +# ========================= +# New errors in Python 3.14 +# ========================= + +# Union and UnionType are aliases in 3.14 but type checkers need some changes +typing.Union +types.UnionType.__class_getitem__ +types.UnionType.__mro_entries__ +types.UnionType.__name__ +types.UnionType.__qualname__ + +# Assigning `__new__` causes `func` not to get recognized. +functools.partialmethod.__new__ + +# Decorator approximated by classmethod +concurrent.interpreters._crossinterp.classonly.* +# Method using this decorator +concurrent.interpreters._crossinterp.UnboundItem.singleton + +# object() sentinels at runtime represented by NewTypes in the stubs +concurrent.interpreters._crossinterp.UNBOUND_ERROR +concurrent.interpreters._crossinterp.UNBOUND_REMOVE + +# Condition functions are exported in __init__ +threading.Condition.locked + +# Starting with Python 3.14.1, these methods accept None for some of their +# parameters, but would raise a TypeError with Python 3.14.0. +mmap.mmap.find +mmap.mmap.flush +mmap.mmap.rfind +multiprocessing.process.BaseProcess.__init__ + +# ==================================== +# Pre-existing errors from Python 3.13 +# ==================================== + + +# ======= +# >= 3.12 +# ======= + +# Types that require `__setattr__` and `__delattr__` for typing purposes: +types.SimpleNamespace.__setattr__ +types.SimpleNamespace.__delattr__ + + +# ======= +# >= 3.11 +# ======= + +# Only exists for an error message. +typing.NewType.__mro_entries__ + + +# ===== +# <3.15 +# ===== + +tkinter.simpledialog.[A-Z_]+ +tkinter.simpledialog.TclVersion +tkinter.simpledialog.TkVersion + +# The runtime does some hacks to deprecate passing various parameters +# positionally or by keyword. We just present a signature in the stub +# that describes the way users are supposed to call the constructor. +typing_extensions.sentinel.__init__ + +# TypeVarTuple is a wrapper class that returns typing.TypeVarTuple instances. +# Keep __new__ checked because it is the wrapper's public constructor. +typing_extensions\.TypeVarTuple +typing_extensions\.TypeVarTuple\.(?!__new__).* + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <3.15 +# ============================================================= + +# typing.IO uses positional-or-keyword arguments, but in the stubs we prefer +# to mark these as positional-only for compatibility with existing sub-classes. +typing(_extensions)?\.BinaryIO\.write +typing(_extensions)?\.IO\.read +typing(_extensions)?\.IO\.readline +typing(_extensions)?\.IO\.readlines +typing(_extensions)?\.IO\.seek +typing(_extensions)?\.IO\.truncate +typing(_extensions)?\.IO\.write +typing(_extensions)?\.IO\.writelines + +# These have a pos-or-keyword first parameter at runtime, but deliberately have a pos-only first parameter in the stub. #6812 +posixpath.join +ntpath.join + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.14 +# ============================================================= + +# Undocumented private attributes +.*\.ForwardRef\.__arg__ +.*\.ForwardRef\.__ast_node__ +.*\.ForwardRef\.__cell__ +.*\.ForwardRef\.__code__ +.*\.ForwardRef\.__extra_names__ +.*\.ForwardRef\.__globals__ +.*\.ForwardRef\.__init_subclass__ +.*\.ForwardRef\.__owner__ +.*\.ForwardRef\.__stringifier_dict__ + +# These protocols use ABC hackery at runtime. +(io|typing_extensions)\.Reader\.__class_getitem__ +(io|typing_extensions)\.Reader\.read +(io|typing_extensions)\.Writer\.__class_getitem__ +(io|typing_extensions)\.Writer\.write + + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseSetProxy.__iter__ +multiprocessing.managers._BaseSetProxy.__len__ +multiprocessing.managers._BaseSetProxy.clear +multiprocessing.managers._BaseSetProxy.copy +multiprocessing.managers._BaseSetProxy.pop +multiprocessing.managers.BaseListProxy.clear +multiprocessing.managers.BaseListProxy.copy +multiprocessing.managers._BaseDictProxy.__reversed__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# But have more precise (accurate) signatures in the stub +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior +types.MappingProxyType.get + +typing_extensions.Protocol # Super-special typing primitive + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858) +_?ast.type_param.__init__ + +# Deprecation wrapper classes; their methods are just pass-through, so we can ignore them. +importlib.metadata.DeprecatedNonAbstract.__new__ + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.__jit # Similar to sys._monitoring +sys.last_exc # not always defined + +# These only exist to give a better error message if you try to subclass an instance +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP-695 syntax in CPython +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing\._SpecialForm.* # Super-special typing primitive +typing\.LiteralString # Super-special typing primitive diff --git a/stdlib/@tests/stubtest_allowlists/py315.txt b/stdlib/@tests/stubtest_allowlists/py315.txt new file mode 100644 index 000000000000..fcd88edaf791 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/py315.txt @@ -0,0 +1,192 @@ +# ============================================ +# TODO: Allowlist entries that should be fixed +# ============================================ + +_frozen_importlib.BuiltinImporter.load_module +_frozen_importlib.FrozenImporter.load_module +_frozen_importlib_external.FileFinder.discover +_frozen_importlib_external.NamespaceLoader.load_module +_frozen_importlib_external.NamespacePath +_frozen_importlib_external.PathFinder.discover +_frozen_importlib_external.SourceFileLoader.source_to_code +_frozen_importlib_external.SourceLoader.source_to_code +_frozen_importlib_external._LoaderBasics.load_module +_frozen_importlib_external.cache_from_source +_struct.Struct.pack_into +_struct.pack +_struct.pack_into +_thread.RLock.__exit__ +_thread.lock.__exit__ +dataclasses.MISSING +dataclasses._MISSING_TYPE +dataclasses.field +importlib._abc.Loader.load_module +importlib._bootstrap_external.NamespacePath +importlib.abc.InspectLoader.source_to_code +importlib.abc.MetaPathFinder.discover +importlib.abc.PathEntryFinder.discover +importlib.resources._common.package_to_anchor +mailbox._ProxyFile.__class_getitem__ +multiprocessing.process.BaseProcess.__init__ +threading.Condition.locked +tkinter.Image.__iter__ +tkinter.Misc.__iter__ +tkinter.font.Font.__iter__ + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# runtime default is a list object used as a sentinel +base64.b64decode +urllib.parse.urlunparse +urllib.parse.urlunsplit + +# Internal implementation details of the sampling profiler. +profiling.sampling.binary_collector +profiling.sampling.binary_reader +profiling.sampling.cli +profiling.sampling.constants +profiling.sampling.dump +profiling.sampling.errors +profiling.sampling.heatmap_collector.FileStats +profiling.sampling.heatmap_collector.TreeNode +profiling.sampling.module_utils +profiling.sampling.opcode_utils +profiling.sampling.sample + +# These aliases are just like the aliases named "slaves" instead of "content". +# See common.txt. +tkinter.Grid.content +tkinter.Grid.grid_content +tkinter.Pack.content +tkinter.Pack.pack_content +tkinter.Place.content +tkinter.Place.place_content + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.14 +# ============================================================= + +# Undocumented private attributes +.*\.ForwardRef\.__arg__ +.*\.ForwardRef\.__ast_node__ +.*\.ForwardRef\.__cell__ +.*\.ForwardRef\.__code__ +.*\.ForwardRef\.__extra_names__ +.*\.ForwardRef\.__globals__ +.*\.ForwardRef\.__init_subclass__ +.*\.ForwardRef\.__owner__ +.*\.ForwardRef\.__stringifier_dict__ + +# Runtime AST node runtime constructor behaviour is too loose. +# For static typing, the loose behaviour is undesirable (https://github.com/python/typeshed/issues/8378). +# For the runtime, the loose behaviour is deprecated in Python 3.13 (https://github.com/python/cpython/issues/105858). +_?ast.type_param.__init__ + +# Decorator approximated by classmethod +concurrent.interpreters._crossinterp.classonly.* +# Method using this decorator +concurrent.interpreters._crossinterp.UnboundItem.singleton + +# object() sentinels at runtime represented by NewTypes in the stubs +concurrent.interpreters._crossinterp.UNBOUND_ERROR +concurrent.interpreters._crossinterp.UNBOUND_REMOVE + +# Assigning `__new__` causes `func` not to get recognized. +functools.partialmethod.__new__ + +# These protocols use ABC hackery at runtime. +(io|typing_extensions)\.Reader\.__class_getitem__ +(io|typing_extensions)\.Reader\.read +(io|typing_extensions)\.Writer\.__class_getitem__ +(io|typing_extensions)\.Writer\.write + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# but have more precise (accurate) signatures in the stub. +multiprocessing.managers.BaseListProxy.clear +multiprocessing.managers.BaseListProxy.copy +multiprocessing.managers._BaseDictProxy.__reversed__ +multiprocessing.managers._BaseSetProxy.__iter__ +multiprocessing.managers._BaseSetProxy.__len__ +multiprocessing.managers._BaseSetProxy.clear +multiprocessing.managers._BaseSetProxy.copy +multiprocessing.managers._BaseSetProxy.pop + +# Union and UnionType are aliases in 3.14 but type checkers need some changes. +typing.Union +types.UnionType.__class_getitem__ +types.UnionType.__mro_entries__ +types.UnionType.__name__ +types.UnionType.__qualname__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.13 +# ============================================================= + +_pyrepl\..+ # The internal implementation of the REPL on py313+; not for public consumption +codecs.backslashreplace_errors # Runtime incorrectly has `self` +codecs.ignore_errors # Runtime incorrectly has `self` +codecs.namereplace_errors # Runtime incorrectly has `self` +codecs.replace_errors # Runtime incorrectly has `self` +codecs.strict_errors # Runtime incorrectly has `self` +codecs.xmlcharrefreplace_errors # Runtime incorrectly has `self` + +# These multiprocessing proxy methods have *args, **kwargs signatures at runtime, +# but have more precise (accurate) signatures in the stub. +multiprocessing.managers._BaseDictProxy.__iter__ +multiprocessing.managers._BaseDictProxy.__len__ +multiprocessing.managers._BaseDictProxy.clear +multiprocessing.managers._BaseDictProxy.copy +multiprocessing.managers._BaseDictProxy.items +multiprocessing.managers._BaseDictProxy.keys +multiprocessing.managers._BaseDictProxy.popitem +multiprocessing.managers._BaseDictProxy.values + +# To match `dict`, we lie about the runtime, but use overloads to match the correct behavior. +types.MappingProxyType.get + +typing_extensions.Protocol # Super-special typing primitive + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.12 +# ============================================================= + +# Deprecated argument is supported at runtime by renaming it through a decorator. +importlib.resources._common.files + +sys._monitoring # Doesn't really exist. See comments in the stub. +sys.__jit # Similar to sys._monitoring +sys.last_exc # Not always defined. + +# Types that require `__setattr__` and `__delattr__` for typing purposes. +types.SimpleNamespace.__delattr__ +types.SimpleNamespace.__setattr__ + +# These only exist to give a better error message if you try to subclass an instance. +typing.ParamSpec.__mro_entries__ +typing.ParamSpecArgs.__mro_entries__ +typing.ParamSpecKwargs.__mro_entries__ +typing.TypeVar.__mro_entries__ +typing.TypeVarTuple.__mro_entries__ + +# These exist at runtime because the protocol uses PEP 695 syntax in CPython. +typing.SupportsAbs.__type_params__ +typing.SupportsRound.__type_params__ + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.11 +# ============================================================= + +enum.auto.__init__ # The stub for enum.auto is nothing like the implementation +enum.auto.value # The stub for enum.auto is nothing like the implementation +http.HTTPMethod.description # Mutable instance attribute at runtime but we pretend it's a property +importlib.resources.abc.Traversable.open # Problematic protocol signature at runtime, see source code comments. +inspect._ParameterKind.description # Still exists, but stubtest can't see it +typing.LiteralString # Super-special typing primitive +typing.NewType.__mro_entries__ # Only exists for an error message. +typing._SpecialForm.__mro_entries__ # Super-special typing primitive diff --git a/stdlib/@tests/stubtest_allowlists/win32-py310.txt b/stdlib/@tests/stubtest_allowlists/win32-py310.txt new file mode 100644 index 000000000000..304b21a96405 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py310.txt @@ -0,0 +1,77 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.10.12 +# (Remove once 3.10.12 becomes available for GitHub Actions) +shutil.unpack_archive +tarfile.AbsoluteLinkError +tarfile.AbsolutePathError +tarfile.FilterError +tarfile.LinkOutsideDestinationError +tarfile.OutsideDestinationError +tarfile.SpecialFileError +tarfile.TarFile.extract +tarfile.TarFile.extractall +tarfile.TarInfo.replace +tarfile.data_filter +tarfile.fully_trusted_filter +tarfile.tar_filter + +# Incompatible changes introduced in Python 3.10.14 +# (Remove once 3.10.14 becomes available for GitHub Actions) +pyexpat.XMLParserType.GetReparseDeferralEnabled +pyexpat.XMLParserType.SetReparseDeferralEnabled +xml.etree.ElementTree.XMLParser.flush +xml.etree.ElementTree.XMLPullParser.flush +xml.sax.expatreader.ExpatParser.flush +zipfile.ZipInfo.__slots__ + +# Incompatible changes introduced in Python 3.10.15 +# (Remove once 3.10.15 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.10.17 +# (Remove once 3.10.17 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.10.18 +# (Remove once 3.10.18 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.10.20 +# (Remove once 3.10.20 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py311.txt b/stdlib/@tests/stubtest_allowlists/win32-py311.txt new file mode 100644 index 000000000000..1499d0da2abe --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py311.txt @@ -0,0 +1,52 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.11.10 +# (Remove once 3.11.10 becomes available for GitHub Actions) +email._header_value_parser.NLSET +email._header_value_parser.SPECIALSNL +email.errors.HeaderWriteError +email.utils.getaddresses +email.utils.parseaddr + +# Incompatible changes introduced in Python 3.11.12 +# (Remove once 3.11.12 becomes available for GitHub Actions) +email._header_value_parser.get_encoded_word +email._header_value_parser.make_quoted_pairs + +# Incompatible changes introduced in Python 3.11.13 +# (Remove once 3.11.13 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.11.15 +# (Remove once 3.11.15 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py312.txt b/stdlib/@tests/stubtest_allowlists/win32-py312.txt new file mode 100644 index 000000000000..eb780c0d569a --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py312.txt @@ -0,0 +1,56 @@ +# ========= +# Temporary +# ========= + +# Incompatible changes introduced in Python 3.12.11 +# (Remove once 3.12.11 becomes available for GitHub Actions) +html.parser.HTMLParser.set_cdata_mode # parameter `escapable` +genericpath.__all__ +genericpath.ALLOW_MISSING +(ntpath.__all__)? +(ntpath.ALLOW_MISSING)? +(ntpath.realpath)? +(os.path.__all__)? +(os.path.ALLOW_MISSING)? +(os.path.realpath)? +(posixpath.__all__)? +(posixpath.ALLOW_MISSING)? +(posixpath.realpath)? +tarfile.LinkFallbackError +tarfile.TarFile._extract_member +tarfile.TarFile.makelink_with_filter + +# Incompatible changes introduced in Python 3.12.13 +# (Remove once 3.12.13 becomes available for GitHub Actions) +email._header_value_parser.make_parenthesis_pairs +html.parser.HTMLParser.__init__ # parameter `scripting` +pyexpat.XMLParserType.SetAllocTrackerActivationThreshold +pyexpat.XMLParserType.SetAllocTrackerMaximumAmplification + + +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func + + +# ========= +# 3.12 only +# ========= + +_winapi.GetLongPathName +_winapi.GetShortPathName + + +# ============================================================= +# Allowlist entries that cannot or should not be fixed; <= 3.12 +# ============================================================= + +# Modules that don't exist on Windows +crypt +nis +ossaudiodev +spwd diff --git a/stdlib/@tests/stubtest_allowlists/win32-py313.txt b/stdlib/@tests/stubtest_allowlists/win32-py313.txt new file mode 100644 index 000000000000..7fba48d7067a --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py313.txt @@ -0,0 +1,7 @@ +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32-py314.txt b/stdlib/@tests/stubtest_allowlists/win32-py314.txt new file mode 100644 index 000000000000..7fba48d7067a --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py314.txt @@ -0,0 +1,7 @@ +# ======= +# >= 3.12 +# ======= + +# Undocumented internal method, not really for public consumption. +# (Hard to add types for unless we add stubs for the undocumented _overlapped module...) +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32-py315.txt b/stdlib/@tests/stubtest_allowlists/win32-py315.txt new file mode 100644 index 000000000000..a3e4da3f7873 --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32-py315.txt @@ -0,0 +1,11 @@ +# ============================================================= +# Allowlist entries that cannot or should not be fixed; >= 3.15 +# ============================================================= + +# Depends on whether the C _decimal extension or pure-Python fallback is used. +(_decimal.SPEC_VERSION)? +(decimal.SPEC_VERSION)? + +# Undocumented internal method, not really for public consumption. +# Hard to add types for unless we add stubs for the undocumented _overlapped module. +asyncio.windows_events.IocpProactor.finish_socket_func diff --git a/stdlib/@tests/stubtest_allowlists/win32.txt b/stdlib/@tests/stubtest_allowlists/win32.txt new file mode 100644 index 000000000000..b56fe5a2042e --- /dev/null +++ b/stdlib/@tests/stubtest_allowlists/win32.txt @@ -0,0 +1,41 @@ +# ============================================ +# Modules that do not exist on Windows systems +# ============================================ + +_curses +_dbm +_gdbm +_posixsubprocess +asyncio.unix_events +dbm.gnu +dbm.ndbm +fcntl +grp +posix +pwd +readline +resource +syslog +termios +xxlimited + +# Modules that rely on _curses +_curses_panel +curses +curses.ascii +curses.has_key +curses.panel +curses.textpad + +# Modules that rely on termios +pty +tty + + +# ========================================================== +# Other allowlist entries that cannot or should not be fixed +# ========================================================== + +multiprocessing.popen_fork # exists on Windows but fails to import +multiprocessing.popen_forkserver # exists on Windows but fails to import +multiprocessing.popen_spawn_posix # exists on Windows but fails to import diff --git a/stdlib/@tests/test_cases/asyncio/check_coroutines.py b/stdlib/@tests/test_cases/asyncio/check_coroutines.py new file mode 100644 index 000000000000..6062ca55146a --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_coroutines.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import sys +from asyncio import iscoroutinefunction +from collections.abc import Awaitable, Callable, Coroutine +from typing import Any +from typing_extensions import assert_type + + +def test_iscoroutinefunction_asyncio( + x: Callable[[str, int], Coroutine[str, int, bytes]], + y: Callable[[str, int], Awaitable[bytes]], + z: Callable[[str, int], str | Awaitable[bytes]], + xx: object, +) -> None: + # asyncio.iscoroutinefunction is deprecated >= 3.11, expecting a warning. + if sys.version_info >= (3, 11): + if iscoroutinefunction(x): # pyright: ignore + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if iscoroutinefunction(y): # pyright: ignore + assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) + + if iscoroutinefunction(z): # pyright: ignore + assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) + + if iscoroutinefunction(xx): # pyright: ignore + assert_type(xx, Callable[..., Coroutine[Any, Any, Any]]) + else: + if iscoroutinefunction(x): + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if iscoroutinefunction(y): + assert_type(y, Callable[[str, int], Coroutine[Any, Any, bytes]]) + + if iscoroutinefunction(z): + assert_type(z, Callable[[str, int], Coroutine[Any, Any, Any]]) + + if iscoroutinefunction(xx): + assert_type(xx, Callable[..., Coroutine[Any, Any, Any]]) diff --git a/stdlib/@tests/test_cases/asyncio/check_gather.py b/stdlib/@tests/test_cases/asyncio/check_gather.py new file mode 100644 index 000000000000..02a01e39731a --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_gather.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import asyncio +from typing import Awaitable, List, Tuple, Union +from typing_extensions import assert_type + + +async def coro1() -> int: + return 42 + + +async def coro2() -> str: + return "spam" + + +async def test_gather(awaitable1: Awaitable[int], awaitable2: Awaitable[str]) -> None: + a = await asyncio.gather(awaitable1) + assert_type(a, Tuple[int]) + + b = await asyncio.gather(awaitable1, awaitable2, return_exceptions=True) + assert_type(b, Tuple[Union[int, BaseException], Union[str, BaseException]]) + + c = await asyncio.gather(awaitable1, awaitable2, awaitable1, awaitable1, awaitable1, awaitable1) + assert_type(c, Tuple[int, str, int, int, int, int]) + + d = await asyncio.gather(awaitable1, awaitable1, awaitable1, awaitable1, awaitable1, awaitable1, awaitable1) + assert_type(d, List[int]) + + awaitables_list: list[Awaitable[int]] = [awaitable1] + e = await asyncio.gather(*awaitables_list) + assert_type(e, List[int]) + + # this case isn't reliable between typecheckers, no one would ever call it with no args anyway + # f = await asyncio.gather() + # assert_type(f, list[Any]) + + +asyncio.run(test_gather(coro1(), coro2())) diff --git a/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py b/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py new file mode 100644 index 000000000000..7ab8e9d814b1 --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_getaddrinfo.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +import asyncio +from socket import AddressFamily +from typing_extensions import assert_type + + +async def check_getaddrinfo(loop: asyncio.AbstractEventLoop, base_loop: asyncio.BaseEventLoop) -> None: + # The address family (item 0) is a tag that discriminates the sockaddr (item 4). + for info in await loop.getaddrinfo("localhost", 80): + if info[0] == AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") + + for info in await base_loop.getaddrinfo("localhost", 80): + if info[0] == AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") diff --git a/stdlib/@tests/test_cases/asyncio/check_task.py b/stdlib/@tests/test_cases/asyncio/check_task.py new file mode 100644 index 000000000000..69bcf8f782aa --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_task.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +import asyncio + + +class Waiter: + def __init__(self) -> None: + self.tasks: list[asyncio.Task[object]] = [] + + def add(self, t: asyncio.Task[object]) -> None: + self.tasks.append(t) + + async def join(self) -> None: + await asyncio.wait(self.tasks) + + +async def foo() -> int: + return 42 + + +async def main() -> None: + # asyncio.Task is covariant in its type argument, which is unusual since its parent class + # asyncio.Future is invariant in its type argument. This is only sound because asyncio.Task + # is not actually Liskov substitutable for asyncio.Future: it does not implement set_result. + w = Waiter() + t: asyncio.Task[int] = asyncio.create_task(foo()) + w.add(t) + await w.join() diff --git a/stdlib/@tests/test_cases/asyncio/check_task_factory.py b/stdlib/@tests/test_cases/asyncio/check_task_factory.py new file mode 100644 index 000000000000..30b587d9ccba --- /dev/null +++ b/stdlib/@tests/test_cases/asyncio/check_task_factory.py @@ -0,0 +1,13 @@ +import asyncio +import sys + + +def get_set(loop: asyncio.BaseEventLoop) -> None: + loop.set_task_factory(loop.get_task_factory()) + + +if sys.version_info >= (3, 12): + + def eager(loop: asyncio.BaseEventLoop) -> None: + loop.set_task_factory(asyncio.eager_task_factory) + loop.set_task_factory(asyncio.create_eager_task_factory(asyncio.Task)) diff --git a/stdlib/@tests/test_cases/builtins/check_dict.py b/stdlib/@tests/test_cases/builtins/check_dict.py new file mode 100644 index 000000000000..fe74ad49408e --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_dict.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import os +from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, Union +from typing_extensions import Self, assert_type + +################################################################### +# Note: tests for `dict.update()` are in `check_MutableMapping.py`. +################################################################### + +# These do follow `__init__` overloads order: +# mypy and pyright have different opinions about this one: +# mypy raises: 'Need type annotation for "bad"' +# pyright is fine with it. +# https://github.com/python/mypy/issues/12358 +# bad = dict() +good: dict[str, str] = dict() +assert_type(good, Dict[str, str]) + +assert_type(dict(arg=1), Dict[str, int]) + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +class KeysAndGetItem(Generic[_KT, _VT]): + data: dict[_KT, _VT] + + def __init__(self, data: dict[_KT, _VT]) -> None: + self.data = data + + def keys(self) -> Iterable[_KT]: + return self.data.keys() + + def __getitem__(self, __k: _KT) -> _VT: + return self.data[__k] + + +kt1: KeysAndGetItem[int, str] = KeysAndGetItem({0: ""}) +assert_type(dict(kt1), Dict[int, str]) +dict(kt1, arg="a") # type: ignore + +kt2: KeysAndGetItem[str, int] = KeysAndGetItem({"": 0}) +assert_type(dict(kt2, arg=1), Dict[str, int]) + + +def test_iterable_tuple_overload(x: Iterable[tuple[int, str]]) -> dict[int, str]: + return dict(x) + + +i1: Iterable[tuple[int, str]] = [(1, "a"), (2, "b")] +test_iterable_tuple_overload(i1) +dict(i1, arg="a") # type: ignore + +i2: Iterable[tuple[str, int]] = [("a", 1), ("b", 2)] +assert_type(dict(i2, arg=1), Dict[str, int]) + +i3: Iterable[str] = ["a.b"] +i4: Iterable[bytes] = [b"a.b"] +assert_type(dict(string.split(".") for string in i3), Dict[str, str]) +assert_type(dict(string.split(b".") for string in i4), Dict[bytes, bytes]) + +dict(["foo", "bar", "baz"]) # type: ignore +dict([b"foo", b"bar", b"baz"]) # type: ignore + +# Exploring corner cases of dict.get() +d_any: dict[str, Any] = {} +d_str: dict[str, str] = {} +any_value: Any = None +str_value = "value" +int_value = 1 + +assert_type(d_any["key"], Any) +assert_type(d_any.get("key"), Union[Any, None]) +assert_type(d_any.get("key", None), Union[Any, None]) +assert_type(d_any.get("key", any_value), Any) +assert_type(d_any.get("key", str_value), Any) +assert_type(d_any.get("key", int_value), Any) + +assert_type(d_str["key"], str) +assert_type(d_str.get("key"), Union[str, None]) +assert_type(d_str.get("key", None), Union[str, None]) +# Pyright has str instead of Any here +assert_type(d_str.get("key", any_value), Any) # pyright: ignore[reportAssertTypeFailure] +assert_type(d_str.get("key", str_value), str) +assert_type(d_str.get("key", int_value), Union[str, int]) + +# Now with context! +result: str +result = d_any["key"] +result = d_any.get("key") # type: ignore[assignment] +result = d_any.get("key", None) # type: ignore[assignment] +result = d_any.get("key", any_value) +result = d_any.get("key", str_value) +result = d_any.get("key", int_value) + +result = d_str["key"] +result = d_str.get("key") # type: ignore[assignment] +result = d_str.get("key", None) # type: ignore[assignment] +# Pyright has str | None here, see https://github.com/microsoft/pyright/discussions/9570 +result = d_str.get("key", any_value) # pyright: ignore[reportAssignmentType] +result = d_str.get("key", str_value) +result = d_str.get("key", int_value) # type: ignore[arg-type] + + +# Return values also make things weird + +# Pyright doesn't have a version of no-any-return, +# and mypy doesn't have a type: ignore that pyright will ignore. +# def test1() -> str: +# return d_any["key"] # mypy: ignore[no-any-return] + + +def test2() -> str: + return d_any.get("key") # type: ignore[return-value] + + +# def test3() -> str: +# return d_any.get("key", None) # mypy: ignore[no-any-return] +# +# +# def test4() -> str: +# return d_any.get("key", any_value) # mypy: ignore[no-any-return] +# +# +# def test5() -> str: +# return d_any.get("key", str_value) # mypy: ignore[no-any-return] +# +# +# def test6() -> str: +# return d_any.get("key", int_value) # mypy: ignore[no-any-return] + + +def test7() -> str: + return d_str["key"] + + +def test8() -> str: + return d_str.get("key") # type: ignore[return-value] + + +def test9() -> str: + return d_str.get("key", None) # type: ignore[return-value] + + +def test10() -> str: + return d_str.get("key", any_value) # type: ignore[no-any-return] + + +def test11() -> str: + return d_str.get("key", str_value) + + +def test12() -> str: + return d_str.get("key", int_value) # type: ignore[arg-type] + + +# Tests for `dict.__(r)or__`. + + +class CustomDictSubclass(dict[_KT, _VT]): + pass + + +class CustomMappingWithDunderOr(Mapping[_KT, _VT]): + def __or__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ror__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ior__(self, other: Mapping[_KT, _VT]) -> Self: + return self + + +def test_dict_dot_or( + a: dict[int, int], + b: CustomDictSubclass[int, int], + c: dict[str, str], + d: Mapping[int, int], + e: CustomMappingWithDunderOr[str, str], +) -> None: + # dict.__(r)or__ always returns a dict, even if called on a subclass of dict: + assert_type(a | b, dict[int, int]) + assert_type(b | a, dict[int, int]) + + assert_type(a | c, dict[Union[int, str], Union[int, str]]) + + # arbitrary mappings are not accepted by `dict.__or__`; + # it has to be a subclass of `dict` + a | d # type: ignore + + # but Mappings such as `os._Environ` or `CustomMappingWithDunderOr`, + # which define `__ror__` methods that accept `dict`, are fine: + assert_type(a | os.environ, dict[Union[str, int], Union[str, int]]) + assert_type(os.environ | a, dict[Union[str, int], Union[str, int]]) + + assert_type(c | os.environ, dict[str, str]) + assert_type(c | e, dict[str, str]) + + assert_type(os.environ | c, dict[str, str]) + assert_type(e | c, dict[str, str]) + + # store "untainted" `CustomMappingWithDunderOr[str, str]` to test `__ior__` against ` dict[str, str]` later + # Invalid `e |= a` causes pyright to join `Unknown` to `e`'s type + f = e + + e |= c + e |= a # type: ignore + + c |= f + + c |= a # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py b/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py new file mode 100644 index 000000000000..b1bf701c4b8c --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_exception_group-py311.py @@ -0,0 +1,354 @@ +from __future__ import annotations + +import sys +from typing import TypeVar +from typing_extensions import assert_type + +if sys.version_info >= (3, 11): + # This can be removed later, but right now Flake8 does not know + # about these two classes: + from builtins import BaseExceptionGroup, ExceptionGroup + + # BaseExceptionGroup + # ================== + # `BaseExceptionGroup` can work with `BaseException`: + beg = BaseExceptionGroup("x", [SystemExit(), SystemExit()]) + assert_type(beg, BaseExceptionGroup[SystemExit]) + assert_type(beg.exceptions, tuple[SystemExit | BaseExceptionGroup[SystemExit], ...]) + + # Covariance works: + _beg1: BaseExceptionGroup[BaseException] = beg + + # `BaseExceptionGroup` can work with `Exception`: + beg2 = BaseExceptionGroup("x", [ValueError()]) + # FIXME: this is not right, runtime returns `ExceptionGroup` instance instead, + # but I am unable to represent this with types right now. + assert_type(beg2, BaseExceptionGroup[ValueError]) + + # .subgroup() + # ----------- + + assert_type(beg.subgroup(KeyboardInterrupt), BaseExceptionGroup[KeyboardInterrupt] | None) + assert_type(beg.subgroup((KeyboardInterrupt,)), BaseExceptionGroup[KeyboardInterrupt] | None) + + def is_base_exc(exc: BaseException) -> bool: + return isinstance(exc, BaseException) + + def is_specific(exc: SystemExit | BaseExceptionGroup[SystemExit]) -> bool: + return isinstance(exc, SystemExit) + + # This one does not have `BaseExceptionGroup` part, + # this is why we treat as an error. + def is_system_exit(exc: SystemExit) -> bool: + return isinstance(exc, SystemExit) + + def unrelated_subgroup(exc: KeyboardInterrupt) -> bool: + return False + + assert_type(beg.subgroup(is_base_exc), BaseExceptionGroup[SystemExit] | None) + assert_type(beg.subgroup(is_specific), BaseExceptionGroup[SystemExit] | None) + beg.subgroup(is_system_exit) # type: ignore + beg.subgroup(unrelated_subgroup) # type: ignore + + # `Exception`` subgroup returns `ExceptionGroup`: + assert_type(beg.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(beg.subgroup((ValueError,)), ExceptionGroup[ValueError] | None) + + # Callable are harder, we don't support cast to `ExceptionGroup` here. + # Because callables might return `True` the first time. And `BaseExceptionGroup` + # will stick, no matter what arguments are. + + def is_exception(exc: Exception) -> bool: + return isinstance(exc, Exception) + + def is_exception_or_beg(exc: Exception | BaseExceptionGroup[SystemExit]) -> bool: + return isinstance(exc, Exception) + + # This is an error because of the `Exception` argument type, + # while `SystemExit` is needed instead. + beg.subgroup(is_exception_or_beg) # type: ignore + + # This is an error, because `BaseExceptionGroup` is not an `Exception` + # subclass. It is required. + beg.subgroup(is_exception) # type: ignore + + # .split() + # -------- + + assert_type( + beg.split(KeyboardInterrupt), tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None] + ) + assert_type( + beg.split((KeyboardInterrupt,)), + tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None], + ) + assert_type( + beg.split(ValueError), # there are no `ValueError` items in there, but anyway + tuple[ExceptionGroup[ValueError] | None, BaseExceptionGroup[SystemExit] | None], + ) + + excs_to_split: list[ValueError | KeyError | SystemExit] = [ValueError(), KeyError(), SystemExit()] + to_split = BaseExceptionGroup("x", excs_to_split) + assert_type(to_split, BaseExceptionGroup[ValueError | KeyError | SystemExit]) + + # Ideally the first part should be `ExceptionGroup[ValueError]` (done) + # and the second part should be `BaseExceptionGroup[KeyError | SystemExit]`, + # but we cannot subtract type from a union. + # We also cannot change `BaseExceptionGroup` to `ExceptionGroup` even if needed + # in the second part here because of that. + assert_type( + to_split.split(ValueError), + tuple[ExceptionGroup[ValueError] | None, BaseExceptionGroup[ValueError | KeyError | SystemExit] | None], + ) + + def split_callable1(exc: ValueError | KeyError | SystemExit | BaseExceptionGroup[ValueError | KeyError | SystemExit]) -> bool: + return True + + assert_type( + to_split.split(split_callable1), # Concrete type is ok + tuple[ + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + ], + ) + assert_type( + to_split.split(is_base_exc), # Base class is ok + tuple[ + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + BaseExceptionGroup[ValueError | KeyError | SystemExit] | None, + ], + ) + # `Exception` cannot be used: `BaseExceptionGroup` is not a subtype of it. + to_split.split(is_exception) # type: ignore + + # .derive() + # --------- + + assert_type(beg.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(beg.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # ExceptionGroup + # ============== + + # `ExceptionGroup` can work with `Exception`: + excs: list[ValueError | KeyError] = [ValueError(), KeyError()] + eg = ExceptionGroup("x", excs) + assert_type(eg, ExceptionGroup[ValueError | KeyError]) + assert_type(eg.exceptions, tuple[ValueError | KeyError | ExceptionGroup[ValueError | KeyError], ...]) + + # Covariance works: + _eg1: ExceptionGroup[Exception] = eg + + # `ExceptionGroup` cannot work with `BaseException`: + ExceptionGroup("x", [SystemExit()]) # type: ignore + + # .subgroup() + # ----------- + + # Our decision is to ban cases like:: + # + # >>> eg = ExceptionGroup('x', [ValueError()]) + # >>> eg.subgroup(BaseException) + # ExceptionGroup('e', [ValueError()]) + # + # are possible in runtime. + # We do it because, it does not make sense for all other base exception types. + # Supporting just `BaseException` looks like an overkill. + eg.subgroup(BaseException) # type: ignore + eg.subgroup((KeyboardInterrupt, SystemExit)) # type: ignore + + assert_type(eg.subgroup(Exception), ExceptionGroup[Exception] | None) + assert_type(eg.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(eg.subgroup((ValueError,)), ExceptionGroup[ValueError] | None) + + def subgroup_eg1(exc: ValueError | KeyError | ExceptionGroup[ValueError | KeyError]) -> bool: + return True + + def subgroup_eg2(exc: ValueError | KeyError) -> bool: + return True + + assert_type(eg.subgroup(subgroup_eg1), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_exception), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_base_exc), ExceptionGroup[ValueError | KeyError] | None) + assert_type(eg.subgroup(is_base_exc), ExceptionGroup[ValueError | KeyError] | None) + + # Does not have `ExceptionGroup` part: + eg.subgroup(subgroup_eg2) # type: ignore + + # .split() + # -------- + + assert_type(eg.split(TypeError), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError | KeyError] | None]) + assert_type(eg.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError | KeyError] | None]) + assert_type( + eg.split(is_exception), tuple[ExceptionGroup[ValueError | KeyError] | None, ExceptionGroup[ValueError | KeyError] | None] + ) + assert_type( + eg.split(is_base_exc), + # is not converted, because `ExceptionGroup` cannot have + # direct `BaseException` subclasses inside. + tuple[ExceptionGroup[ValueError | KeyError] | None, ExceptionGroup[ValueError | KeyError] | None], + ) + + # It does not include `ExceptionGroup` itself, so it will fail: + def value_or_key_error(exc: ValueError | KeyError) -> bool: + return isinstance(exc, (ValueError, KeyError)) + + eg.split(value_or_key_error) # type: ignore + + # `ExceptionGroup` cannot have direct `BaseException` subclasses inside. + eg.split(BaseException) # type: ignore + eg.split((SystemExit, GeneratorExit)) # type: ignore + + # .derive() + # --------- + + assert_type(eg.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(eg.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # BaseExceptionGroup Custom Subclass + # ================================== + # In some cases `Self` type can be preserved in runtime, + # but it is impossible to express. That's why we always fallback to + # `BaseExceptionGroup` and `ExceptionGroup`. + + _BE = TypeVar("_BE", bound=BaseException) + + class CustomBaseGroup(BaseExceptionGroup[_BE]): ... + + cb1 = CustomBaseGroup("x", [SystemExit()]) + assert_type(cb1, CustomBaseGroup[SystemExit]) + cb2 = CustomBaseGroup("x", [ValueError()]) + assert_type(cb2, CustomBaseGroup[ValueError]) + + # .subgroup() + # ----------- + + assert_type(cb1.subgroup(KeyboardInterrupt), BaseExceptionGroup[KeyboardInterrupt] | None) + assert_type(cb2.subgroup((KeyboardInterrupt,)), BaseExceptionGroup[KeyboardInterrupt] | None) + + assert_type(cb1.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(cb2.subgroup((KeyError,)), ExceptionGroup[KeyError] | None) + + def cb_subgroup1(exc: SystemExit | CustomBaseGroup[SystemExit]) -> bool: + return True + + def cb_subgroup2(exc: ValueError | CustomBaseGroup[ValueError]) -> bool: + return True + + assert_type(cb1.subgroup(cb_subgroup1), BaseExceptionGroup[SystemExit] | None) + assert_type(cb2.subgroup(cb_subgroup2), BaseExceptionGroup[ValueError] | None) + cb1.subgroup(cb_subgroup2) # type: ignore + cb2.subgroup(cb_subgroup1) # type: ignore + + # .split() + # -------- + + assert_type( + cb1.split(KeyboardInterrupt), tuple[BaseExceptionGroup[KeyboardInterrupt] | None, BaseExceptionGroup[SystemExit] | None] + ) + assert_type(cb1.split(TypeError), tuple[ExceptionGroup[TypeError] | None, BaseExceptionGroup[SystemExit] | None]) + assert_type(cb2.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, BaseExceptionGroup[ValueError] | None]) + + def cb_split1(exc: SystemExit | CustomBaseGroup[SystemExit]) -> bool: + return True + + def cb_split2(exc: ValueError | CustomBaseGroup[ValueError]) -> bool: + return True + + assert_type(cb1.split(cb_split1), tuple[BaseExceptionGroup[SystemExit] | None, BaseExceptionGroup[SystemExit] | None]) + assert_type(cb2.split(cb_split2), tuple[BaseExceptionGroup[ValueError] | None, BaseExceptionGroup[ValueError] | None]) + cb1.split(cb_split2) # type: ignore + cb2.split(cb_split1) # type: ignore + + # .derive() + # --------- + + # Note, that `Self` type is not preserved in runtime. + assert_type(cb1.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cb1.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + assert_type(cb2.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cb2.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # ExceptionGroup Custom Subclass + # ============================== + + _E = TypeVar("_E", bound=Exception) + + class CustomGroup(ExceptionGroup[_E]): ... + + CustomGroup("x", [SystemExit()]) # type: ignore + cg1 = CustomGroup("x", [ValueError()]) + assert_type(cg1, CustomGroup[ValueError]) + + # .subgroup() + # ----------- + + cg1.subgroup(BaseException) # type: ignore + cg1.subgroup((KeyboardInterrupt, SystemExit)) # type: ignore + + assert_type(cg1.subgroup(ValueError), ExceptionGroup[ValueError] | None) + assert_type(cg1.subgroup((KeyError,)), ExceptionGroup[KeyError] | None) + + def cg_subgroup1(exc: ValueError | CustomGroup[ValueError]) -> bool: + return True + + def cg_subgroup2(exc: ValueError) -> bool: + return True + + assert_type(cg1.subgroup(cg_subgroup1), ExceptionGroup[ValueError] | None) + cg1.subgroup(cb_subgroup2) # type: ignore + + # .split() + # -------- + + assert_type(cg1.split(TypeError), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError] | None]) + assert_type(cg1.split((TypeError,)), tuple[ExceptionGroup[TypeError] | None, ExceptionGroup[ValueError] | None]) + cg1.split(BaseException) # type: ignore + + def cg_split1(exc: ValueError | CustomGroup[ValueError]) -> bool: + return True + + def cg_split2(exc: ValueError) -> bool: + return True + + assert_type(cg1.split(cg_split1), tuple[ExceptionGroup[ValueError] | None, ExceptionGroup[ValueError] | None]) + cg1.split(cg_split2) # type: ignore + + # .derive() + # --------- + + # Note, that `Self` type is not preserved in runtime. + assert_type(cg1.derive([ValueError()]), ExceptionGroup[ValueError]) + assert_type(cg1.derive([KeyboardInterrupt()]), BaseExceptionGroup[KeyboardInterrupt]) + + # Additional tests + # ============================== + + def test_exception_group_default_type() -> None: + try: + ex: ExceptionGroup = ExceptionGroup("", [ValueError("a"), ValueError("b")]) + raise ex + except ExceptionGroup as e: + assert all(isinstance(exc, ValueError) for exc in e.exceptions) + + def test_exception_group_with_specific_type() -> None: + try: + ex: ExceptionGroup[ValueError] = ExceptionGroup("", [ValueError("a"), ValueError("b")]) + raise ex + except ExceptionGroup as e: + assert all(isinstance(exc, ValueError) for exc in e.exceptions) + + def test_base_exception_group_default_type() -> None: + try: + ex: BaseExceptionGroup = BaseExceptionGroup("", [SystemExit("a"), SystemExit("b")]) + raise ex + except BaseExceptionGroup as e: + assert all(isinstance(exc, SystemExit) for exc in e.exceptions) + + def test_base_exception_group_with_specific_type() -> None: + try: + ex: BaseExceptionGroup[SystemExit] = BaseExceptionGroup("", [SystemExit("a"), SystemExit("b")]) + raise ex + except BaseExceptionGroup as e: + assert all(isinstance(exc, SystemExit) for exc in e.exceptions) diff --git a/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py b/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py new file mode 100644 index 000000000000..dd222a4c796f --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_frozendict-py315.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import sys +from typing import Any +from typing_extensions import assert_type + +if sys.version_info >= (3, 15): + # Regression test for gh-15985: ``frozendict`` can be constructed from + # keyword arguments, a mapping, or an iterable of pairs (not just with no + # arguments). + assert_type(frozendict(), frozendict[Any, Any]) + assert_type(frozendict(a=1), frozendict[str, int]) + assert_type(frozendict({"x": 1}), frozendict[str, int]) + assert_type(frozendict([("k", 2)]), frozendict[str, int]) + assert_type(frozendict({"x": 1}, y=2), frozendict[str, int]) diff --git a/stdlib/@tests/test_cases/builtins/check_iteration.py b/stdlib/@tests/test_cases/builtins/check_iteration.py new file mode 100644 index 000000000000..3d609635377e --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_iteration.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import Iterator +from typing_extensions import assert_type + + +class OldStyleIter: + def __getitem__(self, index: int) -> str: + return str(index) + + +for x in iter(OldStyleIter()): + assert_type(x, str) + +assert_type(iter(OldStyleIter()), Iterator[str]) +assert_type(next(iter(OldStyleIter())), str) diff --git a/stdlib/@tests/test_cases/builtins/check_list.py b/stdlib/@tests/test_cases/builtins/check_list.py new file mode 100644 index 000000000000..4113f5c66182 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_list.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from typing import List, Union +from typing_extensions import assert_type + + +# list.__add__ example from #8292 +class Foo: + def asd(self) -> int: + return 1 + + +class Bar: + def asd(self) -> int: + return 2 + + +combined = [Foo()] + [Bar()] +assert_type(combined, List[Union[Foo, Bar]]) +for item in combined: + assert_type(item.asd(), int) diff --git a/stdlib/@tests/test_cases/builtins/check_memoryview.py b/stdlib/@tests/test_cases/builtins/check_memoryview.py new file mode 100644 index 000000000000..1ece6e6b850b --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_memoryview.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +import array +import sys +from typing_extensions import assert_type + +# Casting to bytes. +buf = b"abcdefg" +view = memoryview(buf).cast("c") +elm = view[0] +assert_type(elm, bytes) +assert_type(view[0:2], memoryview[bytes]) + +# Casting to a bool. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +bool_mv = mv.cast("?") +assert_type(bool_mv[0], bool) +assert_type(bool_mv[0:2], memoryview[bool]) + + +# Casting to a signed char. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("b") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed short. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("h") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed int. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("i") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a signed long. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +signed_mv = mv.cast("l") +assert_type(signed_mv[0], int) +assert_type(signed_mv[0:2], memoryview[int]) + +# Casting to a float. +a = array.array("B", [0, 1, 2, 3]) +mv = memoryview(a) +float_mv = mv.cast("f") +assert_type(float_mv[0], float) +assert_type(float_mv[0:2], memoryview[float]) + +# An invalid literal should raise an error. +mv = memoryview(b"abc") +mv.cast("abc") # type: ignore + +if sys.version_info >= (3, 14): + mv.index(42) + mv.count(42) +else: + mv.index(42) # type: ignore + mv.count(42) # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_min.py b/stdlib/@tests/test_cases/builtins/check_min.py new file mode 100644 index 000000000000..a300ad45c482 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_min.py @@ -0,0 +1,94 @@ +from typing_extensions import assert_type + + +def test_min_builtin() -> None: + # legal comparisons that succeed at runtime + b1, b2 = bool(True), bool(False) + i1, i2 = int(1), int(2) + s1, s2 = str("a"), str("b") + f1, f2 = float(0.5), float(2.3) + l1, l2 = list[int]([1, 2]), list[int]([3, 4]) + t1, t2 = tuple[str, str](("A", "B")), tuple[str, str](("C", "D")) + tN = tuple[str, ...](["A", "B", "C"]) + + assert_type(min(b1, b2), bool) + assert_type(min(i1, i2), int) + assert_type(min(s1, s2), str) + assert_type(min(f1, f2), float) + + # mixed numerical types (note: float = int or float) + assert_type(min(b1, i1), int) + assert_type(min(i1, b1), int) + + assert_type(min(b1, f1), float) + assert_type(min(f1, b1), float) + + assert_type(min(i1, f1), float) + assert_type(min(f1, i1), float) + + # comparisons with lists and tuples + assert_type(min(l1, l2), list[int]) + assert_type(min(t1, t2), tuple[str, str]) + assert_type(min(tN, t2), tuple[str, ...]) + + +def test_min_bad_builtin() -> None: + # illegal comparisons that fail at runtime + i1 = int(1) + s1 = str("a") + f1 = float(1.0) + c1, c2 = complex(1.0, 2.0), complex(3.0, 4.0) + list_str = list[str](["A", "B"]) + list_int = list[int]([2, 3]) + tup_str = tuple[str, str](("A", "B")) + tup_int = tuple[int, int]((2, 3)) + + # True negatives. + min(c1, c2) # type: ignore + + # FIXME: False negatives. + min(i1, s1) + min(s1, f1) + min(f1, list_str) + min(list_str, list_int) + min(tup_str, tup_int) + + +def test_min_custom_comparison() -> None: + class BoolScalar: + def __bool__(self) -> bool: ... + + class FloatScalar: + def __float__(self) -> float: ... + def __ge__(self, other: "FloatScalar") -> BoolScalar: ... + def __gt__(self, other: "FloatScalar") -> BoolScalar: ... + def __lt__(self, other: "FloatScalar") -> BoolScalar: ... + def __le__(self, other: "FloatScalar") -> BoolScalar: ... + + f1 = FloatScalar() + f2 = FloatScalar() + + assert_type(min(f1, f2), FloatScalar) + + +def test_min_bad_custom_type() -> None: + class FloatScalar: + def __float__(self) -> float: ... + def __ge__(self, other: "FloatScalar") -> object: + return object() + + def __gt__(self, other: "FloatScalar") -> object: + return object() + + def __lt__(self, other: "FloatScalar") -> object: + return object() + + def __le__(self, other: "FloatScalar") -> object: + return object() + + f1 = FloatScalar() + f2 = FloatScalar() + + # Note: min(f1, f2) works at runtime, but always returns the second argument. + # therefore, we require returning a boolean-like type for comparisons. + min(f1, f2) # type: ignore diff --git a/stdlib/@tests/test_cases/builtins/check_object.py b/stdlib/@tests/test_cases/builtins/check_object.py new file mode 100644 index 000000000000..60df1143f727 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_object.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import Any + + +# The following should pass without error (see #6661): +class Diagnostic: + def __reduce__(self) -> str | tuple[Any, ...]: + res = super().__reduce__() + if isinstance(res, tuple) and len(res) >= 3: + res[2]["_info"] = 42 + + return res diff --git a/stdlib/@tests/test_cases/builtins/check_pow.py b/stdlib/@tests/test_cases/builtins/check_pow.py new file mode 100644 index 000000000000..01de2eb5fc8b --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_pow.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import sys +from decimal import Decimal +from fractions import Fraction +from typing import Any, Literal +from typing_extensions import assert_type + +# See #7163 +assert_type(pow(1, 0), Literal[1]) +assert_type(1**0, Literal[1]) +assert_type(pow(1, 0, None), Literal[1]) + +# TODO: We don't have a good way of expressing the fact +# that passing 0 for the third argument will lead to an exception being raised +# (see discussion in #8566) +# +# assert_type(pow(2, 4, 0), Never) + +assert_type(pow(2, 4), int) +# pyright infers a literal type here, but mypy does not. +# Unfortunately, there is no way to ignore an error only for mypy, +# whilst getting both pyright and mypy to respect `type: ignore`. +# So we can't check pyright's handling (https://github.com/python/mypy/issues/12358). +assert_type(2**4, int) # pyright: ignore[reportAssertTypeFailure] +# pyright version: assert_type(2**4, Literal[16]) +assert_type(pow(4, 6, None), int) + +assert_type(pow(5, -7), float) +assert_type(5**-7, float) + +assert_type(pow(2, 4, 5), int) # pow(, , ) +assert_type(pow(2, 35, 3), int) # pow(, , ) + +assert_type(pow(2, 8.5), float) +assert_type(2**8.6, float) +assert_type(pow(2, 8.6, None), float) + +assert_type((-2) ** 0.5, complex) + +assert_type(pow((-5), 8.42, None), complex) + +assert_type(pow(4.6, 8), float) +assert_type(4.6**8, float) +assert_type(pow(5.1, 4, None), float) + +assert_type(pow(complex(6), 6.2), complex) +assert_type(complex(6) ** 6.2, complex) +assert_type(pow(complex(9), 7.3, None), complex) + +assert_type(Fraction() ** 4, Fraction) + +assert_type(pow(Fraction(3, 7), complex(1, 8)), complex) +assert_type(Fraction(3, 7) ** complex(1, 8), complex) + +assert_type(pow(complex(4, -8), Fraction(2, 3)), complex) +assert_type(complex(4, -8) ** Fraction(2, 3), complex) + +assert_type(pow(Decimal("1.0"), Decimal("1.6")), Decimal) +assert_type(Decimal("1.0") ** Decimal("1.6"), Decimal) + +assert_type(pow(Decimal("1.0"), Decimal("1.0"), Decimal("1.0")), Decimal) +assert_type(pow(Decimal("4.6"), 7, None), Decimal) +assert_type(Decimal("4.6") ** 7, Decimal) + +# These would ideally be more precise, but `Any` is acceptable +# They have to be `Any` due to the fact that type-checkers can't distinguish +# between positive and negative numbers for the second argument to `pow()` +# +# int for positive 2nd-arg, float otherwise +assert_type(pow(4, 65), Any) +assert_type(pow(2, -45), Any) +assert_type(pow(3, 57, None), Any) +assert_type(pow(67, 0.98, None), Any) +assert_type(87**7.32, Any) +# pow(, ) -> float +# pow(, ) -> complex +assert_type(pow(4.7, 7.4), Any) +assert_type(pow(-9.8, 8.3), Any) +assert_type(pow(-9.3, -88.2), Any) +assert_type(pow(8.2, -9.8), Any) +assert_type(pow(4.7, 9.2, None), Any) +# See #7046 -- float for a positive 1st arg, complex otherwise +assert_type((-95) ** 8.42, Any) + +# Fraction.__pow__/__rpow__ with modulo parameter +# With the None parameter, we get the correct type, but with a non-None parameter, we receive TypeError +if sys.version_info >= (3, 14): + assert_type(pow(Fraction(3, 4), 2, None), Fraction) + # Non-none modulo should fail + pow(Fraction(3, 4), 2, 1) # type: ignore[misc] +else: + pow(Fraction(), 5, 8) # type: ignore + +# All of the following cases should fail a type-checker. +pow(1.9, 4, 6) # type: ignore +pow(4, 7, 4.32) # type: ignore +pow(6.2, 5.9, 73) # type: ignore +pow(complex(6), 6.2, 7) # type: ignore +Decimal("8.7") ** 3.14 # type: ignore + +# TODO: This fails at runtime, but currently passes mypy and pyright: +pow(Decimal("8.5"), 3.21) diff --git a/stdlib/@tests/test_cases/builtins/check_reversed.py b/stdlib/@tests/test_cases/builtins/check_reversed.py new file mode 100644 index 000000000000..d89ebf3a0ca7 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_reversed.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from collections.abc import Iterator +from typing import Generic, TypeVar +from typing_extensions import assert_type + +x: list[int] = [] +assert_type(list(reversed(x)), "list[int]") + + +class MyReversible: + def __iter__(self) -> Iterator[str]: + yield "blah" + + def __reversed__(self) -> Iterator[str]: + yield "blah" + + +assert_type(list(reversed(MyReversible())), "list[str]") + + +_T = TypeVar("_T") + + +class MyLenAndGetItem(Generic[_T]): + def __len__(self) -> int: + return 0 + + def __getitem__(self, item: int) -> _T: + raise KeyError + + +len_and_get_item: MyLenAndGetItem[int] = MyLenAndGetItem() +assert_type(reversed(len_and_get_item), "reversed[int]") + + +class UnTrue: + def __reversed__(self) -> UnFalse: + return UnFalse() + + +class UnFalse: + def __reversed__(self) -> UnTrue: + return UnTrue() + + +assert_type(reversed(UnTrue()), "UnFalse") +assert_type(reversed(reversed(UnTrue())), "UnTrue") diff --git a/stdlib/@tests/test_cases/builtins/check_round.py b/stdlib/@tests/test_cases/builtins/check_round.py new file mode 100644 index 000000000000..84081f3665b9 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_round.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import overload +from typing_extensions import assert_type + + +class CustomIndex: + def __index__(self) -> int: + return 1 + + +# float: + +assert_type(round(5.5), int) +assert_type(round(5.5, None), int) +assert_type(round(5.5, 0), float) +assert_type(round(5.5, 1), float) +assert_type(round(5.5, 5), float) +assert_type(round(5.5, CustomIndex()), float) + +# int: + +assert_type(round(1), int) +assert_type(round(1, 1), int) +assert_type(round(1, None), int) +assert_type(round(1, CustomIndex()), int) + +# Protocols: + + +class WithCustomRound1: + def __round__(self) -> str: + return "a" + + +assert_type(round(WithCustomRound1()), str) +assert_type(round(WithCustomRound1(), None), str) +# Errors: +round(WithCustomRound1(), 1) # type: ignore +round(WithCustomRound1(), CustomIndex()) # type: ignore + + +class WithCustomRound2: + def __round__(self, digits: int) -> str: + return "a" + + +assert_type(round(WithCustomRound2(), 1), str) +assert_type(round(WithCustomRound2(), CustomIndex()), str) +# Errors: +round(WithCustomRound2(), None) # type: ignore +round(WithCustomRound2()) # type: ignore + + +class WithOverloadedRound: + @overload + def __round__(self, ndigits: None = ...) -> str: ... + + @overload + def __round__(self, ndigits: int) -> bytes: ... + + def __round__(self, ndigits: int | None = None) -> str | bytes: + return b"" if ndigits is None else "" + + +assert_type(round(WithOverloadedRound()), str) +assert_type(round(WithOverloadedRound(), None), str) +assert_type(round(WithOverloadedRound(), 1), bytes) diff --git a/stdlib/@tests/test_cases/builtins/check_set.py b/stdlib/@tests/test_cases/builtins/check_set.py new file mode 100644 index 000000000000..89cb8683bfe1 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_set.py @@ -0,0 +1,57 @@ +from typing_extensions import Literal, assert_type + + +# Note: type checkers / linters are free to point out that the set difference +# below is redundant. But typeshed should allow it, as its job is to describe +# what is legal in Python, not what is sensible. +# For instance, set[Literal] - set[str] should be legal. +def test_set_difference(x: set[Literal["foo", "bar"]], y: set[str], z: set[int]) -> None: + assert_type(x - y, set[Literal["foo", "bar"]]) + assert_type(y - x, set[str]) + assert_type(x - z, set[Literal["foo", "bar"]]) + assert_type(z - x, set[int]) + assert_type(y - z, set[str]) + assert_type(z - y, set[int]) + + +def test_set_interface_overlapping_type(s: set[Literal["foo", "bar"]], y: set[str], key: str) -> None: + s.add(key) # type: ignore + s.discard(key) + s.remove(key) # type: ignore + s.difference_update(y) + s.intersection_update(y) + s.symmetric_difference_update(y) # type: ignore + s.update(y) # type: ignore + + assert_type(s.difference(y), set[Literal["foo", "bar"]]) + assert_type(s.intersection(y), set[Literal["foo", "bar"]]) + assert_type(s.isdisjoint(y), bool) + assert_type(s.issubset(y), bool) + assert_type(s.issuperset(y), bool) + assert_type(s.symmetric_difference(y), set[str]) + assert_type(s.union(y), set[str]) + + assert_type(s - y, set[Literal["foo", "bar"]]) + assert_type(s & y, set[Literal["foo", "bar"]]) + assert_type(s | y, set[str]) + assert_type(s ^ y, set[str]) + + s -= y + s &= y + s |= y # type: ignore + s ^= y # type: ignore + + +def test_frozenset_interface(s: frozenset[Literal["foo", "bar"]], y: frozenset[str]) -> None: + assert_type(s.difference(y), frozenset[Literal["foo", "bar"]]) + assert_type(s.intersection(y), frozenset[Literal["foo", "bar"]]) + assert_type(s.isdisjoint(y), bool) + assert_type(s.issubset(y), bool) + assert_type(s.issuperset(y), bool) + assert_type(s.symmetric_difference(y), frozenset[str]) + assert_type(s.union(y), frozenset[str]) + + assert_type(s - y, frozenset[Literal["foo", "bar"]]) + assert_type(s & y, frozenset[Literal["foo", "bar"]]) + assert_type(s | y, frozenset[str]) + assert_type(s ^ y, frozenset[str]) diff --git a/stdlib/@tests/test_cases/builtins/check_slice.py b/stdlib/@tests/test_cases/builtins/check_slice.py new file mode 100644 index 000000000000..596d8c63c1c5 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_slice.py @@ -0,0 +1,251 @@ +""" +Assuming X, Y and Z are types other than None, the following rules apply to the slice type: + +- The type hint `slice` should be compatible with all slices, including: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)`. (⟿ `slice[?, ?, ?]`) +- The type hint `slice[T]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)` (⟿ `slice[?, ?, ?]`) + - `slice(t)`, `slice(None, t)` and `slice(None, t, None)`. (⟿ `slice[?, T, ?]`) + - `slice(t, None)` and `slice(t, None, None)`. (⟿ `slice[T, ?, ?]`) + - `slice(t, t)` and `slice(t, t, None)`. (⟿ `slice[T, T, ?]`) +- The type hint `slice[X, Y]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)` (⟿ `slice[?, ?, ?]`) + - `slice(y)`, `slice(None, y)` and `slice(None, y, None)`. (⟿ `slice[?, Y, ?]`) + - `slice(x, None)` and `slice(x, None, None)` (⟿ `slice[X, ?, ?]`) + - `slice(x, y)` and `slice(x, y, None)`. (⟿ `slice[X, Y, ?]`) +- The type hint `slice[X, Y, Z]` should be compatible with: + - `slice(None)`, `slice(None, None)` and `slice(None, None, None)`. (⟿ `slice[?, ?, ?]`) + - `slice(y)`, `slice(None, y)` and `slice(None, y, None)`. (⟿ `slice[?, Y, ?]`) + - `slice(x, None)` and `slice(x, None, None)` (⟿ `slice[X, ?, ?]`) + - `slice(x, y)` and `slice(x, y, None)`. (⟿ `slice[X, Y, ?]`) + - `slice(None, None, z)` (⟿ `slice[?, ?, Z]`) + - `slice(None, y, z)` (⟿ `slice[?, Y, Z]`) + - `slice(x, None, z)` (⟿ `slice[X, ?, Z]`) + - `slice(x, y, z)` (⟿ `slice[X, Y, Z]`) + +Consistency criterion: Assuming now X, Y, Z can potentially be None, the following rules apply: + +- `slice(x)` must be compatible with `slice[None, X, None]`, even if X is None. +- `slice(x, y)` must be compatible with `slice[X,Y,None]`, even if X is None or Y is None. +- `slice(x, y, z)` must be compatible with `slice[X, Y, Z]`, even if X, Y, or Z are `None`. +""" + +from __future__ import annotations + +from datetime import date, datetime as DT, timedelta as TD +from typing import Any, SupportsIndex, cast +from typing_extensions import assert_type + +# region Tests for slice constructor overloads ----------------------------------------- +assert_type(slice(None), "slice[Any, Any, Any]") +assert_type(slice(1234), "slice[Any, int, Any]") + +assert_type(slice(None, None), "slice[Any, Any, Any]") +assert_type(slice(None, 5678), "slice[Any, int, Any]") +assert_type(slice(1234, None), "slice[int, Any, Any]") +assert_type(slice(1234, 5678), "slice[int, int, Any]") + +assert_type(slice(None, None, None), "slice[Any, Any, Any]") +assert_type(slice(None, 5678, None), "slice[Any, int, Any]") +assert_type(slice(1234, None, None), "slice[int, Any, Any]") +assert_type(slice(1234, 5678, None), "slice[int, int, Any]") +assert_type(slice(1234, 5678, 9012), "slice[int, int, int]") +# endregion Tests for slice constructor overloads -------------------------------------- + +# region Test parameter defaults for slice constructor --------------------------------- +# Note: need to cast, because pyright specializes regardless of type annotations +slc1 = cast("slice[SupportsIndex | None]", slice(1)) +slc2 = cast("slice[int | None, int | None]", slice(1, 2)) +fake_key_val = cast("slice[str, int]", slice("1", 2)) +assert_type(slc1, "slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None]") +assert_type(slc2, "slice[int | None, int | None, int | None]") +assert_type(fake_key_val, "slice[str, int, str | int]") +# endregion Test parameter defaults for slice constructor ------------------------------ + +# region Tests for slice properties ---------------------------------------------------- +# Note: if an argument is not None, we should get precisely the same type back +assert_type(slice(1234).stop, int) + +assert_type(slice(1234, None).start, int) +assert_type(slice(None, 5678).stop, int) + +assert_type(slice(1234, None, None).start, int) +assert_type(slice(None, 5678, None).stop, int) +assert_type(slice(None, None, 9012).step, int) +# endregion Tests for slice properties ------------------------------------------------- + + +# region Test for slice assignments ---------------------------------------------------- +# exhaustively test all possible assignments: miss (X), None (N), int (I), and str (S) +rXNX: slice = slice(None) +rXIX: slice = slice(1234) +rXSX: slice = slice("70") + +rNNX: slice = slice(None, None) +rINX: slice = slice(1234, None) +rSNX: slice = slice("70", None) + +rNIX: slice = slice(None, 5678) +rIIX: slice = slice(1234, 5678) +rSIX: slice = slice("70", 9012) + +rNSX: slice = slice(None, "71") +rISX: slice = slice(1234, "71") +rSSX: slice = slice("70", "71") + +rNNN: slice = slice(None, None, None) +rINN: slice = slice(1234, None, None) +rSNN: slice = slice("70", None, None) +rNIN: slice = slice(None, 5678, None) +rIIN: slice = slice(1234, 5678, None) +rSIN: slice = slice("70", 5678, None) +rNSN: slice = slice(None, "71", None) +rISN: slice = slice(1234, "71", None) +rSSN: slice = slice("70", "71", None) + +rNNI: slice = slice(None, None, 9012) +rINI: slice = slice(1234, None, 9012) +rSNI: slice = slice("70", None, 9012) +rNII: slice = slice(None, 5678, 9012) +rIII: slice = slice(1234, 5678, 9012) +rSII: slice = slice("70", 5678, 9012) +rNSI: slice = slice(None, "71", 9012) +rISI: slice = slice(1234, "71", 9012) +rSSI: slice = slice("70", "71", 9012) + +rNNS: slice = slice(None, None, "1d") +rINS: slice = slice(1234, None, "1d") +rSNS: slice = slice("70", None, "1d") +rNIS: slice = slice(None, 5678, "1d") +rIIS: slice = slice(1234, 5678, "1d") +rSIS: slice = slice("70", 5678, "1d") +rNSS: slice = slice(None, "71", "1d") +rISS: slice = slice(1234, "71", "1d") +rSSS: slice = slice("70", "71", "1d") +# endregion Test for slice assignments ------------------------------------------------- + + +# region Tests for slice[T] assignments ------------------------------------------------ +sXNX: "slice[int]" = slice(None) +sXIX: "slice[int]" = slice(1234) + +sNNX: "slice[int]" = slice(None, None) +sNIX: "slice[int]" = slice(None, 5678) +sINX: "slice[int]" = slice(1234, None) +sIIX: "slice[int]" = slice(1234, 5678) + +sNNN: "slice[int]" = slice(None, None, None) +sNIN: "slice[int]" = slice(None, 5678, None) +sNNS: "slice[int]" = slice(None, None, 9012) +sINN: "slice[int]" = slice(1234, None, None) +sINS: "slice[int]" = slice(1234, None, 9012) +sIIN: "slice[int]" = slice(1234, 5678, None) +sIIS: "slice[int]" = slice(1234, 5678, 9012) +# endregion Tests for slice[T] assignments --------------------------------------------- + + +# region Tests for slice[X, Y] assignments --------------------------------------------- +# Note: start=int is illegal and hence we add an explicit "type: ignore" comment. +tXNX: "slice[None, int]" = slice(None) # since slice(None) is slice[Any, Any, Any] +tXIX: "slice[None, int]" = slice(1234) + +tNNX: "slice[None, int]" = slice(None, None) +tNIX: "slice[None, int]" = slice(None, 5678) +tINX: "slice[None, int]" = slice(1234, None) # type: ignore +tIIX: "slice[None, int]" = slice(1234, 5678) # type: ignore + +tNNN: "slice[None, int]" = slice(None, None, None) +tNIN: "slice[None, int]" = slice(None, 5678, None) +tINN: "slice[None, int]" = slice(1234, None, None) # type: ignore +tIIN: "slice[None, int]" = slice(1234, 5678, None) # type: ignore +tNNS: "slice[None, int]" = slice(None, None, 9012) +tINS: "slice[None, int]" = slice(None, 5678, 9012) +tNIS: "slice[None, int]" = slice(1234, None, 9012) # type: ignore +tIIS: "slice[None, int]" = slice(1234, 5678, 9012) # type: ignore +# endregion Tests for slice[X, Y] assignments ------------------------------------------ + + +# region Tests for slice[X, Y, Z] assignments ------------------------------------------ +uXNX: "slice[int, int, int]" = slice(None) +uXIX: "slice[int, int, int]" = slice(1234) + +uNNX: "slice[int, int, int]" = slice(None, None) +uNIX: "slice[int, int, int]" = slice(None, 5678) +uINX: "slice[int, int, int]" = slice(1234, None) +uIIX: "slice[int, int, int]" = slice(1234, 5678) + +uNNN: "slice[int, int, int]" = slice(None, None, None) +uNNI: "slice[int, int, int]" = slice(None, None, 9012) +uNIN: "slice[int, int, int]" = slice(None, 5678, None) +uNII: "slice[int, int, int]" = slice(None, 5678, 9012) +uINN: "slice[int, int, int]" = slice(1234, None, None) +uINI: "slice[int, int, int]" = slice(1234, None, 9012) +uIIN: "slice[int, int, int]" = slice(1234, 5678, None) +uIII: "slice[int, int, int]" = slice(1234, 5678, 9012) +# endregion Tests for slice[X, Y, Z] assignments --------------------------------------- + + +# region Test for slice consistency criterion ------------------------------------------ +year = date(2021, 1, 1) +vXNX: "slice[None, None, None]" = slice(None) +vXIX: "slice[None, date, None]" = slice(year) + +vNNX: "slice[None, None, None]" = slice(None, None) +vNIX: "slice[None, date, None]" = slice(None, year) +vINX: "slice[date, None, None]" = slice(year, None) +vIIX: "slice[date, date, None]" = slice(year, year) + +vNNN: "slice[None, None, None]" = slice(None, None, None) +vNIN: "slice[None, date, None]" = slice(None, year, None) +vINN: "slice[date, None, None]" = slice(year, None, None) +vIIN: "slice[date, date, None]" = slice(year, year, None) +vNNI: "slice[None, None, str]" = slice(None, None, "1d") +vNII: "slice[None, date, str]" = slice(None, year, "1d") +vINI: "slice[date, None, str]" = slice(year, None, "1d") +vIII: "slice[date, date, str]" = slice(year, year, "1d") +# endregion Test for slice consistency criterion --------------------------------------- + + +# region Integration tests for slices with datetimes ----------------------------------- +class TimeSeries: # similar to pandas.Series with datetime index + def __getitem__(self, key: "slice[DT | str | None, DT | str | None]") -> Any: + """Subsample the time series at the given dates.""" + ... + + +class TimeSeriesInterpolator: # similar to pandas.Series with datetime index + def __getitem__(self, key: "slice[DT, DT, TD | None]") -> Any: + """Subsample the time series at the given dates.""" + ... + + +# tests slices as an argument +start = DT(1970, 1, 1) +stop = DT(1971, 1, 10) +step = TD(days=1) +# see: https://pandas.pydata.org/docs/user_guide/timeseries.html#partial-string-indexing +# FIXME: https://github.com/python/mypy/issues/2410 (use literal slices) +series = TimeSeries() +_ = series[slice(None, "1970-01-10")] +_ = series[slice("1970-01-01", None)] +_ = series[slice("1970-01-01", "1971-01-10")] +_ = series[slice(None, stop)] +_ = series[slice(start, None)] +_ = series[slice(start, stop)] +_ = series[slice(None)] + +model = TimeSeriesInterpolator() +_ = model[slice(start, stop)] +_ = model[slice(start, stop, step)] +_ = model[slice(start, stop, None)] + + +# test slices as a return type +def foo(flag: bool, value: DT) -> "slice[DT, None] | slice[None, DT]": + if flag: + return slice(value, None) # slice[DT, DT|Any, Any] incompatible + else: + return slice(None, value) # slice[DT|Any, DT, Any] incompatible + + +# endregion Integration tests for slices with datetimes -------------------------------- diff --git a/stdlib/@tests/test_cases/builtins/check_sum.py b/stdlib/@tests/test_cases/builtins/check_sum.py new file mode 100644 index 000000000000..ec9cd335c685 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_sum.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import Any, List, Literal, Union +from typing_extensions import assert_type + + +class Foo: + def __add__(self, other: Any) -> Foo: + return Foo() + + +class Bar: + def __radd__(self, other: Any) -> Bar: + return Bar() + + +class Baz: + def __add__(self, other: Any) -> Baz: + return Baz() + + def __radd__(self, other: Any) -> Baz: + return Baz() + + +literal_list: list[Literal[0, 1]] = [0, 1, 1] + +assert_type(sum([2, 4]), int) +assert_type(sum([3, 5], 4), int) + +assert_type(sum([True, False]), int) +assert_type(sum([True, False], True), int) +assert_type(sum(literal_list), int) + +assert_type(sum([["foo"], ["bar"]], ["baz"]), List[str]) + +assert_type(sum([Foo(), Foo()], Foo()), Foo) +assert_type(sum([Baz(), Baz()]), Union[Baz, Literal[0]]) + +# mypy and pyright infer the types differently for these, so we can't use assert_type +# Just test that no error is emitted for any of these +sum([("foo",), ("bar", "baz")], ()) # mypy: `tuple[str, ...]`; pyright: `tuple[str] | tuple[str, str] | tuple[()]` +sum([5.6, 3.2]) # mypy: `float`; pyright: `float | Literal[0]` +sum([2.5, 5.8], 5) # mypy: `float`; pyright: `float | int` + +# These all fail at runtime +sum("abcde") # type: ignore +sum([["foo"], ["bar"]]) # type: ignore +sum([("foo",), ("bar", "baz")]) # type: ignore +sum([Foo(), Foo()]) # type: ignore +sum([Bar(), Bar()], Bar()) # type: ignore +sum([Bar(), Bar()]) # type: ignore + +# TODO: these pass pyright with the current stubs, but mypy erroneously emits an error: +# sum([3, Fraction(7, 22), complex(8, 0), 9.83]) +# sum([3, Decimal("0.98")]) diff --git a/stdlib/@tests/test_cases/builtins/check_tuple.py b/stdlib/@tests/test_cases/builtins/check_tuple.py new file mode 100644 index 000000000000..bc0d8db28389 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_tuple.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from typing import Tuple +from typing_extensions import assert_type + + +# Empty tuples, see #8275 +class TupleSub(Tuple[int, ...]): + pass + + +assert_type(TupleSub(), TupleSub) +assert_type(TupleSub([1, 2, 3]), TupleSub) diff --git a/stdlib/@tests/test_cases/builtins/check_type.py b/stdlib/@tests/test_cases/builtins/check_type.py new file mode 100644 index 000000000000..1eafcf482fb6 --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_type.py @@ -0,0 +1,4 @@ +class Meta(type): ... + + +call = Meta.__dict__["__call__"] diff --git a/stdlib/@tests/test_cases/builtins/check_zip.py b/stdlib/@tests/test_cases/builtins/check_zip.py new file mode 100644 index 000000000000..fa6fcc7eae0f --- /dev/null +++ b/stdlib/@tests/test_cases/builtins/check_zip.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import Sequence, Tuple +from typing_extensions import assert_type + +ints: Sequence[int] = [1, 2, 3] +strs: Sequence[str] = ["one", "two", "three"] +floats: Sequence[float] = [1.0, 2.0, 3.0] +str_tuples: Sequence[Tuple[str]] = list((x,) for x in strs) + +assert_type(zip(ints), zip[Tuple[int]]) +assert_type(zip(ints, strs), zip[Tuple[int, str]]) +assert_type(zip(ints, strs, floats), zip[Tuple[int, str, float]]) +assert_type(zip(strs, ints, floats, ints), zip[Tuple[str, int, float, int]]) +assert_type(zip(strs, ints, floats, ints, str_tuples), zip[Tuple[str, int, float, int, Tuple[str]]]) diff --git a/stdlib/@tests/test_cases/check_SupportsGetItem.py b/stdlib/@tests/test_cases/check_SupportsGetItem.py new file mode 100644 index 000000000000..feb140438b2c --- /dev/null +++ b/stdlib/@tests/test_cases/check_SupportsGetItem.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from _typeshed import SupportsDunderGT, SupportsDunderLT, SupportsGetItem +from collections.abc import Callable +from operator import itemgetter +from typing import Any, TypeVar +from typing_extensions import assert_type + +_T = TypeVar("_T") + + +# This should be equivalent to itemgetter().__call__ +def standalone_call(obj: SupportsGetItem[Any, _T]) -> _T: ... + + +# Expected type of itemgetter(1).__call__ +expected_type_itemgetter_call: Callable[[SupportsGetItem[int, _T]], _T] # pyright: ignore[reportGeneralTypeIssues] + +# Expecting itemgetter(1) to be assignable to this +# based on the example below: min({"first": 1, "second": 2}.items(), key=itemgetter(1)) +# That example and assigning to this variable are what failed in https://github.com/python/mypy/issues/14032 +expected_assignable_to: Callable[[tuple[str, int]], SupportsDunderLT[Any] | SupportsDunderGT[Any]] + + +# Regression tests for https://github.com/python/mypy/issues/14032 +# assert_type(itemgetter("first")({"first": 1, "second": 2}), int) # See comment on itemgetter.__call__ +assert_type(min({"first": 1, "second": 2}, key=itemgetter(1)), str) +assert_type(min({"first": 1, "second": 2}.items(), key=itemgetter(1)), tuple[str, int]) +assert_type(standalone_call({"first": 1, "second": 2}), int) +assert_type(min({"first": 1, "second": 2}, key=standalone_call), str) +assert_type(min({"first": 1, "second": 2}.items(), key=standalone_call), tuple[str, int]) + +expected_itemgetter_call_type = itemgetter(1).__call__ +expected_itemgetter_call_type = itemgetter(1) +expected_assignable_to = itemgetter(1) + +expected_itemgetter_call_type = standalone_call +expected_assignable_to = standalone_call diff --git a/stdlib/@tests/test_cases/check_ast.py b/stdlib/@tests/test_cases/check_ast.py new file mode 100644 index 000000000000..4e99d00d6ccb --- /dev/null +++ b/stdlib/@tests/test_cases/check_ast.py @@ -0,0 +1,44 @@ +import ast +from typing_extensions import assert_type + +# Test with source code strings +assert_type(ast.parse("x = 1"), ast.Module) +assert_type(ast.parse("x = 1", mode="exec"), ast.Module) +assert_type(ast.parse("1 + 1", mode="eval"), ast.Expression) +assert_type(ast.parse("x = 1", mode="single"), ast.Interactive) +assert_type(ast.parse("(int, str) -> None", mode="func_type"), ast.FunctionType) + +# Test with mod objects - Module +mod1: ast.Module = ast.Module([], []) +assert_type(ast.parse(mod1), ast.Module) +assert_type(ast.parse(mod1, mode="exec"), ast.Module) +mod2: ast.Module = ast.Module(body=[ast.Expr(value=ast.Constant(value=42))], type_ignores=[]) +assert_type(ast.parse(mod2), ast.Module) + +# Test with mod objects - Expression +expr1: ast.Expression = ast.Expression(body=ast.Constant(value=42)) +assert_type(ast.parse(expr1, mode="eval"), ast.Expression) + +# Test with mod objects - Interactive +inter1: ast.Interactive = ast.Interactive(body=[]) +assert_type(ast.parse(inter1, mode="single"), ast.Interactive) + +# Test with mod objects - FunctionType +func1: ast.FunctionType = ast.FunctionType(argtypes=[], returns=ast.Constant(value=None)) +assert_type(ast.parse(func1, mode="func_type"), ast.FunctionType) + +# Test that any AST node can be passed and returns the same type +binop: ast.BinOp = ast.BinOp(left=ast.Constant(1), op=ast.Add(), right=ast.Constant(2)) +assert_type(ast.parse(binop), ast.BinOp) + +constant: ast.Constant = ast.Constant(value=42) +assert_type(ast.parse(constant), ast.Constant) + +expr_stmt: ast.Expr = ast.Expr(value=ast.Constant(value=42)) +assert_type(ast.parse(expr_stmt), ast.Expr) + +# Test with additional parameters +assert_type(ast.parse(mod1, filename="test.py"), ast.Module) +assert_type(ast.parse(mod1, type_comments=True), ast.Module) +assert_type(ast.parse(mod1, feature_version=(3, 10)), ast.Module) +assert_type(ast.parse(binop, filename="test.py"), ast.BinOp) diff --git a/stdlib/@tests/test_cases/check_codecs.py b/stdlib/@tests/test_cases/check_codecs.py new file mode 100644 index 000000000000..19e663ceeaaf --- /dev/null +++ b/stdlib/@tests/test_cases/check_codecs.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import codecs +from typing_extensions import assert_type + +assert_type(codecs.decode("x", "unicode-escape"), str) +assert_type(codecs.decode(b"x", "unicode-escape"), str) + +assert_type(codecs.decode(b"x", "utf-8"), str) +codecs.decode("x", "utf-8") # type: ignore + +assert_type(codecs.decode("ab", "hex"), bytes) +assert_type(codecs.decode(b"ab", "hex"), bytes) diff --git a/stdlib/@tests/test_cases/check_compression.py b/stdlib/@tests/test_cases/check_compression.py new file mode 100644 index 000000000000..7fc106f125c7 --- /dev/null +++ b/stdlib/@tests/test_cases/check_compression.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import io +import sys +from _typeshed import ReadableBuffer +from bz2 import BZ2Decompressor +from lzma import LZMADecompressor +from typing import cast +from typing_extensions import assert_type +from zlib import decompressobj + +if sys.version_info >= (3, 14): + from compression._common._streams import DecompressReader, _Decompressor, _Reader + from compression.zstd import ZstdDecompressor +else: + from _compression import DecompressReader, _Decompressor, _Reader + +### +# Tests for DecompressReader/_Decompressor +### + + +class CustomDecompressor: + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: + return b"" + + @property + def unused_data(self) -> bytes: + return b"" + + @property + def eof(self) -> bool: + return False + + @property + def needs_input(self) -> bool: + return False + + +def accept_decompressor(d: _Decompressor) -> None: + d.decompress(b"random bytes", 0) + assert_type(d.eof, bool) + assert_type(d.unused_data, bytes) + + +fp = cast(_Reader, io.BytesIO(b"hello world")) +DecompressReader(fp, decompressobj) +DecompressReader(fp, BZ2Decompressor) +DecompressReader(fp, LZMADecompressor) +DecompressReader(fp, CustomDecompressor) +accept_decompressor(decompressobj()) +accept_decompressor(BZ2Decompressor()) +accept_decompressor(LZMADecompressor()) +accept_decompressor(CustomDecompressor()) + +if sys.version_info >= (3, 14): + DecompressReader(fp, ZstdDecompressor) + accept_decompressor(ZstdDecompressor()) diff --git a/stdlib/@tests/test_cases/check_concurrent_futures.py b/stdlib/@tests/test_cases/check_concurrent_futures.py new file mode 100644 index 000000000000..51a94b09d386 --- /dev/null +++ b/stdlib/@tests/test_cases/check_concurrent_futures.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +import sys +from collections.abc import Callable, Iterator +from concurrent.futures import Future, ThreadPoolExecutor, as_completed +from typing import Literal +from typing_extensions import assert_type + + +class Parent: ... + + +class Child(Parent): ... + + +def check_as_completed_covariance() -> None: + with ThreadPoolExecutor() as executor: + f1 = executor.submit(lambda: Parent()) + f2 = executor.submit(lambda: Child()) + fs: list[Future[Parent] | Future[Child]] = [f1, f2] + assert_type(as_completed(fs), Iterator[Future[Parent]]) + for future in as_completed(fs): + assert_type(future.result(), Parent) + + +def check_future_invariance() -> None: + def execute_callback(callback: Callable[[], Parent], future: Future[Parent]) -> None: + future.set_result(callback()) + + fut: Future[Child] = Future() + execute_callback(lambda: Parent(), fut) # type: ignore + assert isinstance(fut.result(), Child) + + +if sys.version_info >= (3, 14): + + def _initializer(x: int) -> None: + pass + + def check_interpreter_pool_executor() -> None: + import concurrent.futures.interpreter + from concurrent.futures import InterpreterPoolExecutor + + with InterpreterPoolExecutor(initializer=_initializer, initargs=(1,)): + ... + + with InterpreterPoolExecutor(initializer=_initializer, initargs=("x",)): # type: ignore + ... + + context = InterpreterPoolExecutor.prepare_context(initializer=_initializer, initargs=(1,)) + worker_context = context[0]() + assert_type(worker_context, concurrent.futures.interpreter.WorkerContext) + resolve_task = context[1] + # Function should enforce that the arguments are correct. + res = resolve_task(_initializer, 1) + assert_type(res, tuple[bytes, Literal["function"]]) + # When the function is a script, the arguments should be a string. + str_res = resolve_task("print('Hello, world!')") + assert_type(str_res, tuple[bytes, Literal["script"]]) + # When a script is passed, no arguments should be provided. + resolve_task("print('Hello, world!')", 1) # type: ignore + + # `WorkerContext.__init__` should accept the result of a resolved task. + concurrent.futures.interpreter.WorkerContext(initdata=res) + + # Run should also accept the result of a resolved task. + worker_context.run(res) + + def check_thread_worker_context() -> None: + import concurrent.futures.thread + + context = concurrent.futures.thread.WorkerContext.prepare(initializer=_initializer, initargs=(1,)) + worker_context = context[0]() + assert_type(worker_context, concurrent.futures.thread.WorkerContext) + resolve_task = context[1] + res = resolve_task(_initializer, (1,), {"test": 1}) + assert_type(res[1], tuple[int]) + assert_type(res[2], dict[str, int]) diff --git a/stdlib/@tests/test_cases/check_configparser.py b/stdlib/@tests/test_cases/check_configparser.py new file mode 100644 index 000000000000..28c355f385ff --- /dev/null +++ b/stdlib/@tests/test_cases/check_configparser.py @@ -0,0 +1,5 @@ +from configparser import RawConfigParser, SectionProxy +from typing_extensions import assert_type + +sp = SectionProxy(RawConfigParser(), "") +assert_type(sp.get("foo", fallback="hi"), str) diff --git a/stdlib/@tests/test_cases/check_contextlib.py b/stdlib/@tests/test_cases/check_contextlib.py new file mode 100644 index 000000000000..648661bca856 --- /dev/null +++ b/stdlib/@tests/test_cases/check_contextlib.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from contextlib import ExitStack +from typing_extensions import assert_type + + +# See issue #7961 +class Thing(ExitStack): + pass + + +stack = ExitStack() +thing = Thing() +assert_type(stack.enter_context(Thing()), Thing) +assert_type(thing.enter_context(ExitStack()), ExitStack) + +with stack as cm: + assert_type(cm, ExitStack) +with thing as cm2: + assert_type(cm2, Thing) diff --git a/stdlib/@tests/test_cases/check_copy.py b/stdlib/@tests/test_cases/check_copy.py new file mode 100644 index 000000000000..c9d4fa877e91 --- /dev/null +++ b/stdlib/@tests/test_cases/check_copy.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import copy +import sys +from typing import Generic, TypeVar +from typing_extensions import Self, assert_type + + +class ReplaceableClass: + def __init__(self, val: int) -> None: + self.val = val + + def __replace__(self, val: int) -> Self: + cpy = copy.copy(self) + cpy.val = val + return cpy + + +if sys.version_info >= (3, 13): + obj = ReplaceableClass(42) + cpy = copy.replace(obj, val=23) + assert_type(cpy, ReplaceableClass) + + +_T_co = TypeVar("_T_co", covariant=True) + + +class Box(Generic[_T_co]): + def __init__(self, value: _T_co, /) -> None: + self.value = value + + def __replace__(self, value: str) -> Box[str]: + return Box(value) + + +if sys.version_info >= (3, 13): + box1: Box[int] = Box(42) + box2 = copy.replace(box1, val="spam") + assert_type(box2, Box[str]) diff --git a/stdlib/@tests/test_cases/check_dataclasses.py b/stdlib/@tests/test_cases/check_dataclasses.py new file mode 100644 index 000000000000..1594400e44fe --- /dev/null +++ b/stdlib/@tests/test_cases/check_dataclasses.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import dataclasses as dc +import sys +from typing import TYPE_CHECKING, Any, Dict, FrozenSet, Tuple, Type, Union +from typing_extensions import Annotated, assert_type + +if TYPE_CHECKING: + from _typeshed import DataclassInstance + + +@dc.dataclass +class Foo: + attr: str + + +assert_type(dc.fields(Foo), Tuple[dc.Field[Any], ...]) + +dc.asdict(Foo) # type: ignore +dc.astuple(Foo) # type: ignore +dc.replace(Foo) # type: ignore + +# See #9723 for why we can't make this assertion +# if dc.is_dataclass(Foo): +# assert_type(Foo, Type[Foo]) + +f = Foo(attr="attr") + +assert_type(dc.fields(f), Tuple[dc.Field[Any], ...]) +assert_type(dc.asdict(f), Dict[str, Any]) +assert_type(dc.astuple(f), Tuple[Any, ...]) +assert_type(dc.replace(f, attr="new"), Foo) + +if dc.is_dataclass(f): + # The inferred type doesn't change + # if it's already known to be a subtype of _DataclassInstance + assert_type(f, Foo) + + +def is_dataclass_any(arg: Any) -> None: + if dc.is_dataclass(arg): + assert_type(arg, Union["DataclassInstance", Type["DataclassInstance"]]) + + +def is_dataclass_object(arg: object) -> None: + if dc.is_dataclass(arg): + assert_type(arg, Union["DataclassInstance", Type["DataclassInstance"]]) + + +def is_dataclass_type(arg: type) -> None: + if dc.is_dataclass(arg): + assert_type(arg, Type["DataclassInstance"]) + + +def check_other_isdataclass_overloads(x: type, y: object) -> None: + # TODO: neither pyright nor mypy emit error on this -- why? + # dc.fields(x) + + dc.fields(y) # type: ignore + + dc.asdict(x) # type: ignore + dc.asdict(y) # type: ignore + + dc.astuple(x) # type: ignore + dc.astuple(y) # type: ignore + + dc.replace(x) # type: ignore + dc.replace(y) # type: ignore + + if dc.is_dataclass(x): + assert_type(x, Type["DataclassInstance"]) + assert_type(dc.fields(x), Tuple[dc.Field[Any], ...]) + + dc.asdict(x) # type: ignore + dc.astuple(x) # type: ignore + dc.replace(x) # type: ignore + + if dc.is_dataclass(y): + assert_type(y, Union["DataclassInstance", Type["DataclassInstance"]]) + assert_type(dc.fields(y), Tuple[dc.Field[Any], ...]) + + dc.asdict(y) # type: ignore + dc.astuple(y) # type: ignore + dc.replace(y) # type: ignore + + if dc.is_dataclass(y) and not isinstance(y, type): + assert_type(y, "DataclassInstance") + assert_type(dc.fields(y), Tuple[dc.Field[Any], ...]) + assert_type(dc.asdict(y), Dict[str, Any]) + assert_type(dc.astuple(y), Tuple[Any, ...]) + dc.replace(y) + + +class _D: ... + + +custom_dc = dc.dataclass(_D, init=True) +assert_type(custom_dc, type[_D]) + +custom_dc_2 = dc.dataclass(None, init=True)(_D) +assert_type(custom_dc_2, type[_D]) + + +# Regression test for #11653 +D = dc.make_dataclass( + "D", [("a", Union[int, None]), "y", ("z", Annotated[FrozenSet[bytes], "metadata"], dc.field(default=frozenset({b"foo"})))] +) +# Check that it's inferred by the type checker as a class object of some kind +# (but don't assert the exact type that `D` is inferred as, +# in case a type checker decides to add some special-casing for +# `make_dataclass` in the future) +assert_type(D.__mro__, Tuple[type, ...]) + + +if sys.version_info >= (3, 14): + from typing import TypeVar + + _T = TypeVar("_T") + + def custom_dataclass( + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: + custom_dc_maker = dc.dataclass( + init=init, + repr=repr, + eq=eq, + order=order, + unsafe_hash=unsafe_hash, + frozen=frozen, + match_args=match_args, + kw_only=kw_only, + slots=slots, + weakref_slot=weakref_slot, + ) + return custom_dc_maker(cls) + + dc.make_dataclass( + "D", + [("a", Union[int, None]), "y", ("z", Annotated[FrozenSet[bytes], "metadata"], dc.field(default=frozenset({b"foo"})))], + decorator=custom_dataclass, + ) diff --git a/stdlib/@tests/test_cases/check_enum.py b/stdlib/@tests/test_cases/check_enum.py new file mode 100644 index 000000000000..6de68a560263 --- /dev/null +++ b/stdlib/@tests/test_cases/check_enum.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import enum +import sys +from typing import Literal, Type +from typing_extensions import assert_type + +A = enum.Enum("A", "spam eggs bacon") +B = enum.Enum("B", ["spam", "eggs", "bacon"]) +C = enum.Enum("C", [("spam", 1), ("eggs", 2), ("bacon", 3)]) +D = enum.Enum("D", {"spam": 1, "eggs": 2}) + +assert_type(A, Type[A]) +assert_type(B, Type[B]) +assert_type(C, Type[C]) +assert_type(D, Type[D]) + + +class EnumOfTuples(enum.Enum): + X = 1, 2, 3 + Y = 4, 5, 6 + + +assert_type(EnumOfTuples((1, 2, 3)), EnumOfTuples) + +# TODO: ideally this test would pass: +# +# if sys.version_info >= (3, 12): +# assert_type(EnumOfTuples(1, 2, 3), EnumOfTuples) + + +if sys.version_info >= (3, 11): + + class Foo(enum.StrEnum): + X = enum.auto() + + assert_type(Foo.X, Literal[Foo.X]) + assert_type(Foo.X.value, str) diff --git a/stdlib/@tests/test_cases/check_functools.py b/stdlib/@tests/test_cases/check_functools.py new file mode 100644 index 000000000000..93b8fe1cf3bc --- /dev/null +++ b/stdlib/@tests/test_cases/check_functools.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +from functools import cache, cached_property, lru_cache, wraps +from typing import Callable, ParamSpec, TypeVar +from typing_extensions import assert_type + +P = ParamSpec("P") +T_co = TypeVar("T_co", covariant=True) + +# +# Tests for @wraps +# + + +def my_decorator(func: Callable[P, T_co]) -> Callable[P, T_co]: + @wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> T_co: + print(args) + return func(*args, **kwargs) + + # verify that the wrapped function has all these attributes + wrapper.__annotations__ = func.__annotations__ + wrapper.__doc__ = func.__doc__ + wrapper.__module__ = func.__module__ + wrapper.__name__ = func.__name__ + wrapper.__qualname__ = func.__qualname__ + return wrapper + + +def check_wraps_function() -> None: + def wrapped(x: int) -> None: ... + @wraps(wrapped) + def identical_wrapper(x: int) -> None: ... + @wraps(wrapped) + def other_signature_wrapper(x: str, y: float) -> None: ... + + identical_wrapper(3) + other_signature_wrapper("parrot", 42.0) + + +def check_wraps_method() -> None: + class Wrapped: + def wrapped(self, x: int) -> None: ... + @wraps(wrapped) + def wrapper(self, x: int) -> None: ... + + class Wrapper: # pyright: ignore[reportUnusedClass] + @wraps(Wrapped.wrapped) + def method(self, x: int) -> None: ... + + @wraps(Wrapped.wrapped) + def func_wrapper(x: int) -> None: ... + + # TODO: The following should work, but currently don't. + # https://github.com/python/typeshed/issues/10653 + # Wrapped().wrapper(3) + # Wrapper().method(3) + func_wrapper(3) + + +# +# Tests for @cache +# + + +@cache +def check_cache(x: int) -> int: + return x * 2 + + +assert_type(check_cache(3), int) +# Type checkers should check the argument type, but this is currently not +# possible. See https://github.com/python/typeshed/issues/6347 and +# https://github.com/python/typeshed/issues/11280. +# check_cached("invalid") # xtype: ignore + +assert_type(check_cache.cache_info().misses, int) + + +# +# Tests for @lru_cache +# + + +@lru_cache +def check_lru_cache(x: int) -> int: + return x * 2 + + +@lru_cache(maxsize=32) +def check_lru_cache_with_maxsize(x: int) -> int: + return x * 2 + + +assert_type(check_lru_cache(3), int) +assert_type(check_lru_cache_with_maxsize(3), int) +# Type checkers should check the argument type, but this is currently not +# possible. See https://github.com/python/typeshed/issues/6347 and +# https://github.com/python/typeshed/issues/11280. +# check_lru_cache("invalid") # xtype: ignore +# check_lru_cache_with_maxsize("invalid") # xtype: ignore + +assert_type(check_lru_cache.cache_info().misses, int) +assert_type(check_lru_cache_with_maxsize.cache_info().misses, int) + + +# +# Tests for @cached_property +# + + +class A: + def __init__(self, x: int): + self.x = x + + @cached_property + def x(self) -> int: + return 0 + + +assert_type(A(x=1).x, int) + + +class B: + @cached_property + def x(self) -> int: + return 0 + + +def check_cached_property_settable(x: int) -> None: + b = B() + assert_type(b.x, int) + b.x = x + assert_type(b.x, int) + + +# https://github.com/python/typeshed/issues/10048 +class Parent: ... + + +class Child(Parent): ... + + +class X: + @cached_property + def some(self) -> Parent: + return Parent() + + +class Y(X): + @cached_property + def some(self) -> Child: # safe override + return Child() + + +class CachedParent: + @cache + def method(self) -> Parent: + return Parent() + + +class CachedChild(CachedParent): + @cache + def method(self) -> Child: + return Child() diff --git a/stdlib/@tests/test_cases/check_importlib.py b/stdlib/@tests/test_cases/check_importlib.py new file mode 100644 index 000000000000..3f226b5dbe8f --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import importlib.util +import pathlib +import sys +import zipfile +from collections.abc import Sequence +from importlib.machinery import ModuleSpec +from types import ModuleType +from typing_extensions import Self + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + + +# Assert that some Path classes are Traversable. +def traverse(t: Traversable) -> None: + pass + + +traverse(pathlib.Path()) +traverse(zipfile.Path("")) + + +class MetaFinder: + @classmethod + def find_spec(cls, fullname: str, path: Sequence[str] | None, target: ModuleType | None = None) -> ModuleSpec | None: + return None # simplified mock for demonstration purposes only + + +class PathFinder: + @classmethod + def path_hook(cls, path_entry: str) -> type[Self]: + return cls # simplified mock for demonstration purposes only + + @classmethod + def find_spec(cls, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: + return None # simplified mock for demonstration purposes only + + +class Loader: + @classmethod + def load_module(cls, fullname: str) -> ModuleType: + return ModuleType(fullname) + + +sys.meta_path.append(MetaFinder) +sys.path_hooks.append(PathFinder.path_hook) +importlib.util.spec_from_loader("xxxx42xxxx", Loader) diff --git a/stdlib/@tests/test_cases/check_importlib_metadata.py b/stdlib/@tests/test_cases/check_importlib_metadata.py new file mode 100644 index 000000000000..8f50496cbd69 --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib_metadata.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from _typeshed import StrPath +from importlib.metadata._meta import SimplePath +from os import PathLike +from pathlib import Path +from zipfile import Path as ZipPath + + +# Simplified version of zipfile.Path +class MyPath: + @property + def parent(self) -> PathLike[str]: ... # undocumented + + def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> MyPath: ... + def __truediv__(self, add: StrPath) -> MyPath: ... + def exists(self) -> bool: ... + + +def takes_simple_path(p: SimplePath) -> None: ... + + +takes_simple_path(Path()) +takes_simple_path(ZipPath("")) +takes_simple_path(MyPath()) +takes_simple_path("some string") # type: ignore diff --git a/stdlib/@tests/test_cases/check_importlib_resources.py b/stdlib/@tests/test_cases/check_importlib_resources.py new file mode 100644 index 000000000000..862456a017e9 --- /dev/null +++ b/stdlib/@tests/test_cases/check_importlib_resources.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import sys + + +class _CustomPathLike: + def __fspath__(self) -> str: + return "" + + +if sys.version_info >= (3, 13): + import importlib.resources + import pathlib + + def f(pth: pathlib.Path | str | _CustomPathLike) -> None: + importlib.resources.open_binary("pkg", pth) + # Encoding defaults to "utf-8" for one arg. + importlib.resources.open_text("pkg", pth) + # Otherwise, it must be specified. + importlib.resources.open_text("pkg", pth, pth) # type: ignore + importlib.resources.open_text("pkg", pth, pth, encoding="utf-8") + + # Encoding defaults to "utf-8" for one arg. + importlib.resources.read_text("pkg", pth) + # Otherwise, it must be specified. + importlib.resources.read_text("pkg", pth, pth) # type: ignore + importlib.resources.read_text("pkg", pth, pth, encoding="utf-8") + + importlib.resources.read_binary("pkg", pth) + importlib.resources.path("pkg", pth) + importlib.resources.is_resource("pkg", pth) + importlib.resources.contents("pkg", pth) # pyright: ignore[reportDeprecated] diff --git a/stdlib/@tests/test_cases/check_inspect.py b/stdlib/@tests/test_cases/check_inspect.py new file mode 100644 index 000000000000..e7ef3d25cf6e --- /dev/null +++ b/stdlib/@tests/test_cases/check_inspect.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import inspect +from collections.abc import Awaitable, Callable, Coroutine +from types import CoroutineType +from typing import Any +from typing_extensions import assert_type + + +def test_iscoroutinefunction_inspect( + x: Callable[[str, int], Coroutine[str, int, bytes]], + y: Callable[[str, int], Awaitable[bytes]], + z: Callable[[str, int], str | Awaitable[bytes]], + xx: object, +) -> None: + if inspect.iscoroutinefunction(x): + assert_type(x, Callable[[str, int], Coroutine[str, int, bytes]]) + + if inspect.iscoroutinefunction(y): + assert_type(y, Callable[[str, int], CoroutineType[Any, Any, bytes]]) + + if inspect.iscoroutinefunction(z): + assert_type(z, Callable[[str, int], CoroutineType[Any, Any, Any]]) + + if inspect.iscoroutinefunction(xx): + assert_type(xx, Callable[..., CoroutineType[Any, Any, Any]]) diff --git a/stdlib/@tests/test_cases/check_io.py b/stdlib/@tests/test_cases/check_io.py new file mode 100644 index 000000000000..c3ee5aa4c6c0 --- /dev/null +++ b/stdlib/@tests/test_cases/check_io.py @@ -0,0 +1,18 @@ +from _io import BufferedReader, BufferedRWPair, BufferedWriter +from gzip import GzipFile +from io import FileIO, RawIOBase, TextIOWrapper +from socket import SocketIO +from typing import Any +from typing_extensions import assert_type + +socket: Any = None + +BufferedReader(RawIOBase()) +BufferedWriter(RawIOBase()) +BufferedWriter(SocketIO(socket, "r")) + +BufferedRWPair(open("", "rb"), open("", "wb")) + +assert_type(TextIOWrapper(FileIO("")).buffer, FileIO) +assert_type(TextIOWrapper(FileIO(13)).detach(), FileIO) +assert_type(TextIOWrapper(GzipFile("")).buffer, GzipFile) diff --git a/stdlib/@tests/test_cases/check_logging.py b/stdlib/@tests/test_cases/check_logging.py new file mode 100644 index 000000000000..a7d57cbda132 --- /dev/null +++ b/stdlib/@tests/test_cases/check_logging.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import logging +import logging.handlers +import multiprocessing +import queue +from typing import Any + +# This pattern comes from the logging docs, and should therefore pass a type checker +# See https://docs.python.org/3/library/logging.html#logrecord-objects + +old_factory = logging.getLogRecordFactory() + + +def record_factory(*args: Any, **kwargs: Any) -> logging.LogRecord: + record = old_factory(*args, **kwargs) + record.custom_attribute = 0xDECAFBAD + return record + + +logging.setLogRecordFactory(record_factory) + +# The logging docs say that QueueHandler and QueueListener can take "any queue-like object" +# We test that here (regression test for #10168) +logging.handlers.QueueHandler(queue.Queue()) +logging.handlers.QueueHandler(queue.SimpleQueue()) +logging.handlers.QueueHandler(multiprocessing.Queue()) +logging.handlers.QueueListener(queue.Queue()) +logging.handlers.QueueListener(queue.SimpleQueue()) +logging.handlers.QueueListener(multiprocessing.Queue()) + +# These all raise at runtime. +logging.basicConfig(filename="foo.log", handlers=[]) # type: ignore +logging.basicConfig(filemode="w", handlers=[]) # type: ignore +logging.basicConfig(stream=None, handlers=[]) # type: ignore +logging.basicConfig(filename="foo.log", stream=None) # type: ignore +logging.basicConfig(filename=None, stream=None) # type: ignore +# These are ok. +logging.basicConfig() +logging.basicConfig(handlers=[]) +logging.basicConfig(filename="foo.log", filemode="w") +logging.basicConfig(filename="foo.log", filemode="w", handlers=None) +logging.basicConfig(stream=None) +logging.basicConfig(stream=None, handlers=None) +# dubious but accepted, has same meaning as 'stream=None'. +logging.basicConfig(filename=None) +# These are technically accepted at runtime, but are forbidden in the stubs to help +# prevent user mistakes. Passing 'filemode' / 'encoding' / 'errors' does nothing +# if 'filename' is not specified. +logging.basicConfig(stream=None, filemode="w") # type: ignore +logging.basicConfig(stream=None, encoding="utf-8") # type: ignore +logging.basicConfig(stream=None, errors="strict") # type: ignore +logging.basicConfig(handlers=[], encoding="utf-8") # type: ignore +logging.basicConfig(handlers=[], errors="strict") # type: ignore diff --git a/stdlib/@tests/test_cases/check_mailbox.py b/stdlib/@tests/test_cases/check_mailbox.py new file mode 100644 index 000000000000..03efe9520dd3 --- /dev/null +++ b/stdlib/@tests/test_cases/check_mailbox.py @@ -0,0 +1,13 @@ +import mailbox + + +def mbox1() -> mailbox.Mailbox: + return mailbox.mbox("") + + +def mbox2() -> mailbox.Mailbox[mailbox.mboxMessage]: + return mailbox.mbox("") + + +def mbox3() -> mailbox.Mailbox[mailbox.Message]: + return mailbox.mbox("") diff --git a/stdlib/@tests/test_cases/check_math.py b/stdlib/@tests/test_cases/check_math.py new file mode 100644 index 000000000000..d637c15ff178 --- /dev/null +++ b/stdlib/@tests/test_cases/check_math.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from decimal import Decimal +from fractions import Fraction +from math import prod +from typing import Any, Literal, Union +from typing_extensions import assert_type + + +class SupportsMul: + def __mul__(self, other: Any) -> SupportsMul: + return SupportsMul() + + +class SupportsRMul: + def __rmul__(self, other: Any) -> SupportsRMul: + return SupportsRMul() + + +class SupportsMulAndRMul: + def __mul__(self, other: Any) -> SupportsMulAndRMul: + return SupportsMulAndRMul() + + def __rmul__(self, other: Any) -> SupportsMulAndRMul: + return SupportsMulAndRMul() + + +literal_list: list[Literal[0, 1]] = [0, 1, 1] + +assert_type(prod([2, 4]), int) +assert_type(prod([3, 5], start=4), int) + +assert_type(prod([True, False]), int) +assert_type(prod([True, False], start=True), int) +assert_type(prod(literal_list), int) + +assert_type(prod([SupportsMul(), SupportsMul()], start=SupportsMul()), SupportsMul) +assert_type(prod([SupportsMulAndRMul(), SupportsMulAndRMul()]), Union[SupportsMulAndRMul, Literal[1]]) + +assert_type(prod([5.6, 3.2]), Union[float, Literal[1]]) +assert_type(prod([5.6, 3.2], start=3), Union[float, int]) + +assert_type(prod([Fraction(7, 2), Fraction(3, 5)]), Union[Fraction, Literal[1]]) +assert_type(prod([Fraction(7, 2), Fraction(3, 5)], start=Fraction(1)), Fraction) +assert_type(prod([Decimal("3.14"), Decimal("2.71")]), Union[Decimal, Literal[1]]) +assert_type(prod([Decimal("3.14"), Decimal("2.71")], start=Decimal("1.00")), Decimal) +assert_type(prod([complex(7, 2), complex(3, 5)]), Union[complex, Literal[1]]) +assert_type(prod([complex(7, 2), complex(3, 5)], start=complex(1, 0)), complex) + + +# mypy and pyright infer the types differently for these, so we can't use assert_type +# Just test that no error is emitted for any of these +prod([5.6, 3.2]) # mypy: `float`; pyright: `float | Literal[0]` +prod([2.5, 5.8], start=5) # mypy: `float`; pyright: `float | int` + +# These all fail at runtime +prod([SupportsMul(), SupportsMul()]) # type: ignore +prod([SupportsRMul(), SupportsRMul()], start=SupportsRMul()) # type: ignore +prod([SupportsRMul(), SupportsRMul()]) # type: ignore + +# TODO: these pass pyright with the current stubs, but mypy erroneously emits an error: +# prod([3, Fraction(7, 22), complex(8, 0), 9.83]) +# prod([3, Decimal("0.98")]) diff --git a/stdlib/@tests/test_cases/check_os_path.py b/stdlib/@tests/test_cases/check_os_path.py new file mode 100644 index 000000000000..bd6911ed3cc9 --- /dev/null +++ b/stdlib/@tests/test_cases/check_os_path.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from _typeshed import StrOrBytesPath +from os import PathLike +from os.path import abspath, expanduser, expandvars +from typing import AnyStr, Union +from typing_extensions import assert_type + + +def test_str_path(str_path: StrOrBytesPath) -> None: + # These methods are currently overloaded to work around python/mypy#17952 & python/mypy#11880 + # Let's ensure that they'll still work with a StrOrBytesPath if the workaround is removed + + assert_type(abspath(str_path), Union[str, bytes]) + assert_type(expanduser(str_path), Union[str, bytes]) + assert_type(expandvars(str_path), Union[str, bytes]) + + +# See python/mypy#17952 +class MyPathMissingGeneric(PathLike): # type: ignore # Explicitly testing w/ missing type argument + def __init__(self, path: str | bytes) -> None: + super().__init__() + self.path = path + + def __fspath__(self) -> str | bytes: + return self.path + + +# MyPathMissingGeneric could also be fixed by users by adding the missing generic annotation +class MyPathGeneric(PathLike[AnyStr]): + def __init__(self, path: AnyStr) -> None: + super().__init__() + self.path: AnyStr = path + + def __fspath__(self) -> AnyStr: + return self.path + + +class MyPathStr(PathLike[str]): + def __init__(self, path: str) -> None: + super().__init__() + self.path = path + + def __fspath__(self) -> str: + return self.path + + +abspath(MyPathMissingGeneric(".")) +expanduser(MyPathMissingGeneric(".")) +expandvars(MyPathMissingGeneric(".")) + +abspath(MyPathGeneric(".")) +expanduser(MyPathGeneric(".")) +expandvars(MyPathGeneric(".")) + +abspath(MyPathStr(".")) +expanduser(MyPathStr(".")) +expandvars(MyPathStr(".")) diff --git a/stdlib/@tests/test_cases/check_pathlib.py b/stdlib/@tests/test_cases/check_pathlib.py new file mode 100644 index 000000000000..d3e85188b97b --- /dev/null +++ b/stdlib/@tests/test_cases/check_pathlib.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import sys +from pathlib import Path, PureWindowsPath +from typing_extensions import assert_type + + +class MyCustomPath(Path): ... + + +if Path("asdf") == Path("asdf"): + ... + +# https://github.com/python/typeshed/issues/10661 +# Provide a true positive error when comparing Path to str +# mypy should report a comparison-overlap error with --strict-equality, +# and pyright should report a reportUnnecessaryComparison error +if Path("asdf") == "asdf": # type: ignore + ... + +# Errors on comparison here are technically false positives. However, this comparison is a little +# interesting: it can never hold true on Posix, but could hold true on Windows. We should experiment +# with more accurate __new__, such that we only get an error for such comparisons on platforms +# where they can never hold true. +if PureWindowsPath("asdf") == Path("asdf"): # type: ignore + ... + + +if sys.version_info >= (3, 13): + pth = MyCustomPath.from_uri("file:///tmp/abc.txt") + assert_type(pth, MyCustomPath) + + +if sys.version_info >= (3, 14): + pth = MyCustomPath("asdf") + # With text path, type should be preserved. + assert_type(pth.move_into("asdf"), MyCustomPath) + assert_type(pth.move("asdf"), MyCustomPath) + assert_type(pth.copy("asdf"), MyCustomPath) + assert_type(pth.copy_into("asdf"), MyCustomPath) + + # With an actual path type, that type should be preserved. + assert_type(pth.move_into(Path("asdf")), Path) + assert_type(pth.move(Path("asdf")), Path) + assert_type(pth.copy(Path("asdf")), Path) + assert_type(pth.copy_into(Path("asdf")), Path) diff --git a/stdlib/@tests/test_cases/check_platform.py b/stdlib/@tests/test_cases/check_platform.py new file mode 100644 index 000000000000..9d2c83ce2815 --- /dev/null +++ b/stdlib/@tests/test_cases/check_platform.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import platform +from typing_extensions import assert_type + +# platform.uname_result emulates a 6 field named tuple, but on 3.9+ the processor +# field is lazily evaluated, which results in it being a little funky. +uname = platform.uname() +myuname = platform.uname_result("Darwin", "local", "22.5.0", "Darwin Kernel Version 22.5.0", "arm64") + +assert_type(uname, platform.uname_result) +assert_type(myuname, platform.uname_result) + +assert_type(uname[5], str) +assert_type(myuname[5], str) diff --git a/stdlib/@tests/test_cases/check_re.py b/stdlib/@tests/test_cases/check_re.py new file mode 100644 index 000000000000..dee87b474fe2 --- /dev/null +++ b/stdlib/@tests/test_cases/check_re.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import mmap +import re +from typing import AnyStr, Match, Optional +from typing_extensions import assert_type + + +def check_search(str_pat: re.Pattern[str], bytes_pat: re.Pattern[bytes]) -> None: + assert_type(str_pat.search("x"), Optional[Match[str]]) + assert_type(bytes_pat.search(b"x"), Optional[Match[bytes]]) + assert_type(bytes_pat.search(bytearray(b"x")), Optional[Match[bytes]]) + assert_type(bytes_pat.search(mmap.mmap(0, 10)), Optional[Match[bytes]]) + + +def check_search_with_AnyStr(pattern: re.Pattern[AnyStr], string: AnyStr) -> re.Match[AnyStr]: + """See issue #9591""" + match = pattern.search(string) + if match is None: + raise ValueError(f"'{string!r}' does not match {pattern!r}") + return match + + +def check_no_ReadableBuffer_false_negatives() -> None: + re.compile("foo").search(bytearray(b"foo")) # type: ignore + re.compile("foo").search(mmap.mmap(0, 10)) # type: ignore diff --git a/stdlib/@tests/test_cases/check_socket.py b/stdlib/@tests/test_cases/check_socket.py new file mode 100644 index 000000000000..096bc23c1431 --- /dev/null +++ b/stdlib/@tests/test_cases/check_socket.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +import socket +from typing_extensions import assert_type + + +def check_getaddrinfo() -> None: + # The address family (item 0) is a tag that discriminates the sockaddr (item 4). + for info in socket.getaddrinfo("localhost", 80): + if info[0] == socket.AddressFamily.AF_INET: + assert_type(info[4], "tuple[str, int]") + elif info[0] == socket.AddressFamily.AF_INET6: + assert_type(info[4], "tuple[str, int, int, int] | tuple[int, bytes]") diff --git a/stdlib/@tests/test_cases/check_sqlite3.py b/stdlib/@tests/test_cases/check_sqlite3.py new file mode 100644 index 000000000000..3ec47ceccb90 --- /dev/null +++ b/stdlib/@tests/test_cases/check_sqlite3.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +import sqlite3 +from typing_extensions import assert_type + + +class MyConnection(sqlite3.Connection): + pass + + +# Default return-type is Connection. +assert_type(sqlite3.connect(":memory:"), sqlite3.Connection) + +# Providing an alternate factory changes the return-type. +assert_type(sqlite3.connect(":memory:", factory=MyConnection), MyConnection) + +# Provides a true positive error. When checking the connect() function, +# mypy should report an arg-type error for the factory argument. +with sqlite3.connect(":memory:", factory=None) as con: # type: ignore + pass + +# The Connection class also accepts a `factory` arg but it does not affect +# the return-type. This use case is not idiomatic--connections should be +# established using the `connect()` function, not directly (as shown here). +assert_type(sqlite3.Connection(":memory:", factory=None), sqlite3.Connection) +assert_type(sqlite3.Connection(":memory:", factory=MyConnection), sqlite3.Connection) diff --git a/stdlib/@tests/test_cases/check_tarfile.py b/stdlib/@tests/test_cases/check_tarfile.py new file mode 100644 index 000000000000..815a6350c837 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tarfile.py @@ -0,0 +1,17 @@ +import tarfile + +with tarfile.open("test.tar.xz", "w:xz") as tar: + pass + +# Test with valid preset values +tarfile.open("test.tar.xz", "w:xz", preset=0) +tarfile.open("test.tar.xz", "w:xz", preset=5) +tarfile.open("test.tar.xz", "w:xz", preset=9) + +# Test with invalid preset values +tarfile.open("test.tar.xz", "w:xz", preset=-1) # type: ignore +tarfile.open("test.tar.xz", "w:xz", preset=10) # type: ignore + +# Test pipe modes +tarfile.open("test.tar.xz", "r|*") +tarfile.open("test.tar.xz", mode="r|*") diff --git a/stdlib/@tests/test_cases/check_tempfile.py b/stdlib/@tests/test_cases/check_tempfile.py new file mode 100644 index 000000000000..c259c192a140 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tempfile.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import io +import sys +from tempfile import TemporaryFile, _TemporaryFileWrapper +from typing_extensions import assert_type + +if sys.platform == "win32": + assert_type(TemporaryFile(), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("w+"), _TemporaryFileWrapper[str]) + assert_type(TemporaryFile("w+b"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("wb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("rb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile("wb", 0), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="w+"), _TemporaryFileWrapper[str]) + assert_type(TemporaryFile(mode="w+b"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="wb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(mode="rb"), _TemporaryFileWrapper[bytes]) + assert_type(TemporaryFile(buffering=0), _TemporaryFileWrapper[bytes]) +else: + assert_type(TemporaryFile(), io.BufferedRandom) + assert_type(TemporaryFile("w+"), io.TextIOWrapper) + assert_type(TemporaryFile("w+b"), io.BufferedRandom) + assert_type(TemporaryFile("wb"), io.BufferedWriter) + assert_type(TemporaryFile("rb"), io.BufferedReader) + assert_type(TemporaryFile("wb", 0), io.FileIO) + assert_type(TemporaryFile(mode="w+"), io.TextIOWrapper) + assert_type(TemporaryFile(mode="w+b"), io.BufferedRandom) + assert_type(TemporaryFile(mode="wb"), io.BufferedWriter) + assert_type(TemporaryFile(mode="rb"), io.BufferedReader) + assert_type(TemporaryFile(buffering=0), io.FileIO) diff --git a/stdlib/@tests/test_cases/check_threading.py b/stdlib/@tests/test_cases/check_threading.py new file mode 100644 index 000000000000..eddfc2549a64 --- /dev/null +++ b/stdlib/@tests/test_cases/check_threading.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +import _threading_local +import threading + +loc = threading.local() +loc.foo = 42 +del loc.foo +loc.baz = ["spam", "eggs"] +del loc.baz + +l2 = _threading_local.local() +l2.asdfasdf = 56 +del l2.asdfasdf diff --git a/stdlib/@tests/test_cases/check_tkinter.py b/stdlib/@tests/test_cases/check_tkinter.py new file mode 100644 index 000000000000..acb9a24ec5b1 --- /dev/null +++ b/stdlib/@tests/test_cases/check_tkinter.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +import sys +import tkinter +import traceback +import types +from typing import Optional, Tuple +from typing_extensions import assert_type + + +def custom_handler(exc: type[BaseException], val: BaseException, tb: types.TracebackType | None) -> None: + print("oh no") + + +root = tkinter.Tk() +root.report_callback_exception = traceback.print_exception +root.report_callback_exception = custom_handler + + +def foo(x: int, y: str) -> None: + pass + + +root.after(1000, foo, 10, "lol") +root.after(1000, foo, 10, 10) # type: ignore + +# Font size must be integer +label = tkinter.Label() +label.config(font=("", 12)) +label.config(font=("", 12.34)) # type: ignore +label.config(font=("", 12, "bold")) +label.config(font=("", 12.34, "bold")) # type: ignore + + +# Test the `.count()` method. Comments show values that are returned at runtime. +t = tkinter.Text() +t.insert("end", "asd asd asd\nasd asd") + +assert_type(t.count("1.0", "2.3"), Optional[Tuple[int]]) # (15,) +assert_type(t.count("2.3", "2.3"), Optional[Tuple[int]]) # None +assert_type(t.count("1.0", "2.3", "indices"), Optional[Tuple[int]]) # (15,) +assert_type(t.count("2.3", "2.3", "indices"), Optional[Tuple[int]]) # None +assert_type(t.count("1.0", "2.3", "indices", "update"), Optional[int]) # 15 +assert_type(t.count("2.3", "2.3", "indices", "update"), Optional[int]) # None +assert_type(t.count("1.0", "2.3", "indices", "lines"), Tuple[int, int]) # (15, 1) +assert_type(t.count("2.3", "2.3", "indices", "lines"), Tuple[int, int]) # (0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "update"), Tuple[int, ...]) # (15, 1) +assert_type(t.count("2.3", "2.3", "indices", "lines", "update"), Tuple[int, ...]) # (0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars"), Tuple[int, ...]) # (15, 1, 15) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars"), Tuple[int, ...]) # (0, 0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "update"), Tuple[int, ...]) # (15, 1, 15) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "update"), Tuple[int, ...]) # (0, 0, 0) +assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "ypixels"), Tuple[int, ...]) # (15, 1, 15, 19) +assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "ypixels"), Tuple[int, ...]) # (0, 0, 0, 0) + +if sys.version_info >= (3, 13): + assert_type(t.count("1.0", "2.3", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", "indices", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", "update", return_ints=True), int) # 15 + assert_type(t.count("2.3", "2.3", "indices", "update", return_ints=True), int) # 0 + assert_type(t.count("1.0", "2.3", "indices", "lines", return_ints=True), Tuple[int, int]) # (15, 1) + assert_type(t.count("2.3", "2.3", "indices", "lines", return_ints=True), Tuple[int, int]) # (0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "update", return_ints=True), Tuple[int, ...]) # (15, 1) + assert_type(t.count("2.3", "2.3", "indices", "lines", "update", return_ints=True), Tuple[int, ...]) # (0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", return_ints=True), Tuple[int, ...]) # (15, 1, 15) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", return_ints=True), Tuple[int, ...]) # (0, 0, 0) + assert_type(t.count("1.0", "2.3", "indices", "lines", "chars", "update", return_ints=True), Tuple[int, ...]) # (15, 1, 15) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "update", return_ints=True), Tuple[int, ...]) # (0, 0, 0) + assert_type( + t.count("1.0", "2.3", "indices", "lines", "chars", "ypixels", return_ints=True), Tuple[int, ...] + ) # (15, 1, 15, 19) + assert_type(t.count("2.3", "2.3", "indices", "lines", "chars", "ypixels", return_ints=True), Tuple[int, ...]) # (0, 0, 0, 0) diff --git a/stdlib/@tests/test_cases/check_turtle.py b/stdlib/@tests/test_cases/check_turtle.py new file mode 100644 index 000000000000..6be64ea5da30 --- /dev/null +++ b/stdlib/@tests/test_cases/check_turtle.py @@ -0,0 +1,35 @@ +from turtle import Turtle, dot + +Turtle().dot() +Turtle().dot(10) +Turtle().dot(size=10) +Turtle().dot((0, 0, 0)) +Turtle().dot(size=(0, 0, 0)) +Turtle().dot("blue") +Turtle().dot("") +Turtle().dot(size="blue") +Turtle().dot(20, "blue") +Turtle().dot(20, "blue") +Turtle().dot(20, (0, 0, 0)) +Turtle().dot(20, 0, 0, 0) + +Turtle().dot(size=10, color="blue") # type: ignore +Turtle().dot(10, color="blue") # type: ignore +Turtle().dot(color="blue") # type: ignore + +dot() +dot(10) +dot(size=10) +dot((0, 0, 0)) +dot(size=(0, 0, 0)) +dot("blue") +dot("") +dot(size="blue") +dot(20, "blue") +dot(20, "blue") +dot(20, (0, 0, 0)) +dot(20, 0, 0, 0) + +dot(size=10, color="blue") # type: ignore +dot(10, color="blue") # type: ignore +dot(color="blue") # type: ignore diff --git a/stdlib/@tests/test_cases/check_types.py b/stdlib/@tests/test_cases/check_types.py new file mode 100644 index 000000000000..d17a8b176fc8 --- /dev/null +++ b/stdlib/@tests/test_cases/check_types.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import sys +import types +from collections import UserDict +from typing import Any, Literal, TypeVar, Union +from typing_extensions import assert_type + +_T = TypeVar("_T") + +# test `types.SimpleNamespace` + +# Valid: +types.SimpleNamespace() +types.SimpleNamespace(x=1, y=2) + +if sys.version_info >= (3, 13): + types.SimpleNamespace(()) + types.SimpleNamespace([]) + types.SimpleNamespace([("x", "y"), ("z", 1)]) + types.SimpleNamespace({}) + types.SimpleNamespace(UserDict({"x": 1, "y": 2})) + + +# Invalid: +types.SimpleNamespace(1) # type: ignore +types.SimpleNamespace([1]) # type: ignore +types.SimpleNamespace([["x"]]) # type: ignore +types.SimpleNamespace(**{1: 2}) # type: ignore +types.SimpleNamespace({1: 2}) # type: ignore +types.SimpleNamespace([[1, 2]]) # type: ignore +types.SimpleNamespace(UserDict({1: 2})) # type: ignore +types.SimpleNamespace([[[], 2]]) # type: ignore + +# test: `types.MappingProxyType` +mp = types.MappingProxyType({1: 2, 3: 4}) +mp.get("x") # type: ignore +item = mp.get(1) +assert_type(item, Union[int, None]) +item_2 = mp.get(2, 0) +assert_type(item_2, int) +item_3 = mp.get(3, "default") +assert_type(item_3, Union[int, str]) +# Default isn't accepted as a keyword argument. +mp.get(4, default="default") # type: ignore + + +# test: `types.DynamicClassAttribute` +class DCAtest: + _value: int | None = None + + @types.DynamicClassAttribute + def foo(self) -> int | None: + return self._value + + @foo.setter + def foo(self, value: int) -> None: + self._value = value + + @foo.deleter + def foo(self) -> None: + self._value = None + + +# check that NotImplemented is treated as an "Any" +x: int = NotImplemented + +# test NotImplementedType usage +assert_type(NotImplemented, types.NotImplementedType) +assert_type(types.NotImplementedType(), types.NotImplementedType) +# test EllipsisType usage +assert_type(Ellipsis, types.EllipsisType) +assert_type(types.EllipsisType(), types.EllipsisType) +# test NoneType usage (disabled, passes with pyright, but mypy errors +# assert_type(None, types.NoneType) +# assert_type(types.NoneType(), types.NoneType) + +if sys.version_info >= (3, 11): + union_type = int | list[_T] + + # ideally this would be `_SpecialForm` (Union) + assert_type(union_type | Literal[1], types.UnionType | Any) + # Both mypy and pyright special-case this operation, + # but in different ways, so we just check that no error is emitted: + _ = union_type[int] diff --git a/stdlib/@tests/test_cases/check_unittest.py b/stdlib/@tests/test_cases/check_unittest.py new file mode 100644 index 000000000000..bbc2a2ba4843 --- /dev/null +++ b/stdlib/@tests/test_cases/check_unittest.py @@ -0,0 +1,255 @@ +from __future__ import annotations + +import unittest +from collections.abc import Iterator, Mapping +from datetime import datetime, timedelta +from decimal import Decimal +from fractions import Fraction +from typing import TypedDict, Union +from typing_extensions import assert_type +from unittest.mock import _ANY, ANY, AsyncMock, MagicMock, Mock, patch + +case = unittest.TestCase() + +### +# Tests for assertAlmostEqual +### + +case.assertAlmostEqual(1, 2.4) +case.assertAlmostEqual(2.4, 2.41) +case.assertAlmostEqual(Fraction(49, 50), Fraction(48, 50)) +case.assertAlmostEqual(3.14, complex(5, 6)) +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), delta=timedelta(hours=1)) +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), None, "foo", timedelta(hours=1)) +case.assertAlmostEqual(Decimal("1.1"), Decimal("1.11")) +case.assertAlmostEqual(2.4, 2.41, places=8) +case.assertAlmostEqual(2.4, 2.41, delta=0.02) +case.assertAlmostEqual(2.4, 2.41, None, "foo", 0.02) + +case.assertAlmostEqual(2.4, 2.41, places=9, delta=0.02) # type: ignore +case.assertAlmostEqual("foo", "bar") # type: ignore +case.assertAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1)) # type: ignore +case.assertAlmostEqual(Decimal("0.4"), Fraction(1, 2)) # type: ignore +case.assertAlmostEqual(complex(2, 3), Decimal("0.9")) # type: ignore + +### +# Tests for assertNotAlmostEqual +### + +case.assertAlmostEqual(1, 2.4) +case.assertNotAlmostEqual(Fraction(49, 50), Fraction(48, 50)) +case.assertAlmostEqual(3.14, complex(5, 6)) +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), delta=timedelta(hours=1)) +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1), None, "foo", timedelta(hours=1)) + +case.assertNotAlmostEqual(2.4, 2.41, places=9, delta=0.02) # type: ignore +case.assertNotAlmostEqual("foo", "bar") # type: ignore +case.assertNotAlmostEqual(datetime(1999, 1, 2), datetime(1999, 1, 2, microsecond=1)) # type: ignore +case.assertNotAlmostEqual(Decimal("0.4"), Fraction(1, 2)) # type: ignore +case.assertNotAlmostEqual(complex(2, 3), Decimal("0.9")) # type: ignore + +### +# Tests for assertGreater +### + + +class Spam: + def __lt__(self, other: object) -> bool: + return True + + +class Eggs: + def __gt__(self, other: object) -> bool: + return True + + +class Ham: + def __lt__(self, other: Ham) -> bool: + if not isinstance(other, Ham): + return NotImplemented + return True + + +class Bacon: + def __gt__(self, other: Bacon) -> bool: + if not isinstance(other, Bacon): + return NotImplemented + return True + + +case.assertGreater(5.8, 3) +case.assertGreater(Decimal("4.5"), Fraction(3, 2)) +case.assertGreater(Fraction(3, 2), 0.9) +case.assertGreater(Eggs(), object()) +case.assertGreater(object(), Spam()) +case.assertGreater(Ham(), Ham()) +case.assertGreater(Bacon(), Bacon()) + +case.assertGreater(object(), object()) # type: ignore +case.assertGreater(datetime(1999, 1, 2), 1) # type: ignore +case.assertGreater(Spam(), Eggs()) # type: ignore +case.assertGreater(Ham(), Bacon()) # type: ignore +case.assertGreater(Bacon(), Ham()) # type: ignore + + +### +# Tests for assertDictEqual +### + + +class TD1(TypedDict): + x: int + y: str + + +class TD2(TypedDict): + a: bool + b: bool + + +class MyMapping(Mapping[str, int]): + def __getitem__(self, __key: str) -> int: + return 42 + + def __iter__(self) -> Iterator[str]: + return iter([]) + + def __len__(self) -> int: + return 0 + + +td1: TD1 = {"x": 1, "y": "foo"} +td2: TD2 = {"a": True, "b": False} +m = MyMapping() + +case.assertDictEqual({}, {}) +case.assertDictEqual({"x": 1, "y": 2}, {"x": 1, "y": 2}) +case.assertDictEqual({"x": 1, "y": "foo"}, {"y": "foo", "x": 1}) +case.assertDictEqual({"x": 1}, {}) +case.assertDictEqual({}, {"x": 1}) +case.assertDictEqual({1: "x"}, {"y": 222}) +case.assertDictEqual({1: "x"}, td1) +case.assertDictEqual(td1, {1: "x"}) +case.assertDictEqual(td1, td2) + +case.assertDictEqual(1, {}) # type: ignore +case.assertDictEqual({}, 1) # type: ignore + +# These should fail, but don't due to TypedDict limitations: +# case.assertDictEqual(m, {"": 0}) # xtype: ignore +# case.assertDictEqual({"": 0}, m) # xtype: ignore + +### +# Tests for mock.patch +### + + +@patch("sys.exit") +def f_default_new(i: int, mock: MagicMock) -> str: + return "asdf" + + +@patch("sys.exit", new=42) +def f_explicit_new(i: int) -> str: + return "asdf" + + +@patch("sys.exit", new_callable=lambda: 42) +def f_explicit_new_callable(i: int, new_callable_ret: int) -> str: + return "asdf" + + +assert_type(f_default_new(1), str) +f_default_new("a") # Not an error due to ParamSpec limitations +assert_type(f_explicit_new(1), str) +f_explicit_new("a") # type: ignore[arg-type] +assert_type(f_explicit_new_callable(1), str) +f_explicit_new_callable("a") # Same as default new + + +@patch("sys.exit", new=Mock()) +class TestXYZ(unittest.TestCase): + attr: int = 5 + + @staticmethod + def method() -> int: + return 123 + + +assert_type(TestXYZ.attr, int) +assert_type(TestXYZ.method(), int) + + +with patch("sys.exit") as default_new_enter: + assert_type(default_new_enter, Union[MagicMock, AsyncMock]) + +with patch("sys.exit", new=42) as explicit_new_enter: + assert_type(explicit_new_enter, int) + +with patch("sys.exit", new_callable=lambda: 42) as explicit_new_callable_enter: + assert_type(explicit_new_callable_enter, int) + + +### +# Tests for mock.patch.object +### + + +@patch.object(Decimal, "exp") +def obj_f_default_new(i: int, mock: MagicMock) -> str: + return "asdf" + + +@patch.object(Decimal, "exp", new=42) +def obj_f_explicit_new(i: int) -> str: + return "asdf" + + +@patch.object(Decimal, "exp", new_callable=lambda: 42) +def obj_f_explicit_new_callable(i: int, new_callable_ret: int) -> str: + return "asdf" + + +assert_type(obj_f_default_new(1), str) +obj_f_default_new("a") # Not an error due to ParamSpec limitations +assert_type(obj_f_explicit_new(1), str) +obj_f_explicit_new("a") # type: ignore[arg-type] +assert_type(obj_f_explicit_new_callable(1), str) +obj_f_explicit_new_callable("a") # Same as default new + + +with patch.object(Decimal, "exp") as obj_default_new_enter: + assert_type(obj_default_new_enter, Union[MagicMock, AsyncMock]) + +with patch.object(Decimal, "exp", new=42) as obj_explicit_new_enter: + assert_type(obj_explicit_new_enter, int) + +with patch.object(Decimal, "exp", new_callable=lambda: 42) as obj_explicit_new_callable_enter: + assert_type(obj_explicit_new_callable_enter, int) + + +### +# Tests for mock.ANY +### + + +assert_type(ANY, _ANY) # Make sure ANY has runtime type + + +# Regression tests. See https://github.com/python/typeshed/issues/14701 +class TD(TypedDict): + x: str + y: float + + +td: TD = {"x": "1", "y": ANY} + + +def test_as_param(x: str) -> None: ... + + +test_as_param(ANY) + + +def test_as_return_value(x: int) -> TD: + return {"x": str(x), "y": ANY} diff --git a/stdlib/@tests/test_cases/check_xml.py b/stdlib/@tests/test_cases/check_xml.py new file mode 100644 index 000000000000..31a4fa243eaa --- /dev/null +++ b/stdlib/@tests/test_cases/check_xml.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing_extensions import assert_type +from xml.dom.minidom import Document + +document = Document() + +assert_type(document.toxml(), str) +assert_type(document.toxml(encoding=None), str) +assert_type(document.toxml(encoding="UTF8"), bytes) +assert_type(document.toxml("UTF8"), bytes) +assert_type(document.toxml(standalone=True), str) +assert_type(document.toxml("UTF8", True), bytes) +assert_type(document.toxml(encoding="UTF8", standalone=True), bytes) + + +# Because toprettyxml can mix positional and keyword variants of the "encoding" argument, which +# determines the return type, the proper stub typing isn't immediately obvious. This is a basic +# brute-force sanity check. +# Test cases like toxml +assert_type(document.toprettyxml(), str) +assert_type(document.toprettyxml(encoding=None), str) +assert_type(document.toprettyxml(encoding="UTF8"), bytes) +assert_type(document.toprettyxml(standalone=True), str) +assert_type(document.toprettyxml(encoding="UTF8", standalone=True), bytes) +# Test cases unique to toprettyxml +assert_type(document.toprettyxml(" "), str) +assert_type(document.toprettyxml(" ", "\r\n"), str) +assert_type(document.toprettyxml(" ", "\r\n", "UTF8"), bytes) +assert_type(document.toprettyxml(" ", "\r\n", "UTF8", True), bytes) +assert_type(document.toprettyxml(" ", "\r\n", standalone=True), str) diff --git a/stdlib/@tests/test_cases/check_zipfile.py b/stdlib/@tests/test_cases/check_zipfile.py new file mode 100644 index 000000000000..3012271ccd8b --- /dev/null +++ b/stdlib/@tests/test_cases/check_zipfile.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +import io +import pathlib +import zipfile +from typing import Literal + +### +# Tests for `zipfile.ZipFile` +### + +p = pathlib.Path("test.zip") + + +class CustomPathObj: + def __init__(self, path: str) -> None: + self.path = path + + def __fspath__(self) -> str: + return self.path + + +class NonPathObj: + def __init__(self, path: str) -> None: + self.path = path + + +class ReadableObj: + def seek(self, offset: int, whence: int = 0) -> int: + return 0 + + def read(self, n: int | None = -1) -> bytes: + return b"test" + + +class TellableObj: + def tell(self) -> int: + return 0 + + +class WriteableObj: + def close(self) -> None: + pass + + def write(self, b: bytes) -> int: + return len(b) + + def flush(self) -> None: + pass + + +class ReadTellableObj(ReadableObj): + def tell(self) -> int: + return 0 + + +class SeekTellObj: + def seek(self, offset: int, whence: int = 0) -> int: + return 0 + + def tell(self) -> int: + return 0 + + +def write_zip(mode: Literal["r", "w", "x", "a"]) -> None: + # Test any mode with `pathlib.Path` + with zipfile.ZipFile(p, mode) as z: + z.writestr("test.txt", "test") + + # Test any mode with `str` path + with zipfile.ZipFile("test.zip", mode) as z: + z.writestr("test.txt", "test") + + # Test any mode with `os.PathLike` object + with zipfile.ZipFile(CustomPathObj("test.zip"), mode) as z: + z.writestr("test.txt", "test") + + # Non-PathLike object should raise an error + with zipfile.ZipFile(NonPathObj("test.zip"), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # IO[bytes] like-obj should work for any mode. + io_obj = io.BytesIO(b"This is a test") + with zipfile.ZipFile(io_obj, mode) as z: + z.writestr("test.txt", "test") + + # Readable object should not work for any mode. + with zipfile.ZipFile(ReadableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Readable object should work for "r" mode. + with zipfile.ZipFile(ReadableObj(), "r") as z: + z.writestr("test.txt", "test") + + # Readable/tellable object should work for "a" mode. + with zipfile.ZipFile(ReadTellableObj(), "a") as z: + z.writestr("test.txt", "test") + + # If it doesn't have 'tell' method, it should raise an error. + with zipfile.ZipFile(ReadableObj(), "a") as z: # type: ignore + z.writestr("test.txt", "test") + + # Readable object should not work for "w" mode. + with zipfile.ZipFile(ReadableObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") + + # Tellable object should not work for any mode. + with zipfile.ZipFile(TellableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Tellable object shouldn't work for "w" mode. + # As `__del__` will call close. + with zipfile.ZipFile(TellableObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") + + # Writeable object should not work for any mode. + with zipfile.ZipFile(WriteableObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Writeable object should work for "w" mode. + with zipfile.ZipFile(WriteableObj(), "w") as z: + z.writestr("test.txt", "test") + + # Seekable and Tellable object should not work for any mode. + with zipfile.ZipFile(SeekTellObj(), mode) as z: # type: ignore + z.writestr("test.txt", "test") + + # Seekable and Tellable object shouldn't work for "w" mode. + # Cause `__del__` will call close. + with zipfile.ZipFile(SeekTellObj(), "w") as z: # type: ignore + z.writestr("test.txt", "test") diff --git a/stdlib/@tests/test_cases/collections/check_defaultdict.py b/stdlib/@tests/test_cases/collections/check_defaultdict.py new file mode 100644 index 000000000000..f608f3f3062e --- /dev/null +++ b/stdlib/@tests/test_cases/collections/check_defaultdict.py @@ -0,0 +1,70 @@ +""" +Tests for `defaultdict.__or__` and `defaultdict.__ror__`. +""" + +from __future__ import annotations + +import os +from collections import defaultdict +from typing import Mapping, TypeVar, Union +from typing_extensions import Self, assert_type + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +class CustomDefaultDictSubclass(defaultdict[_KT, _VT]): + pass + + +class CustomMappingWithDunderOr(Mapping[_KT, _VT]): + def __or__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ror__(self, other: Mapping[_KT, _VT]) -> dict[_KT, _VT]: + return {} + + def __ior__(self, other: Mapping[_KT, _VT]) -> Self: + return self + + +def test_defaultdict_dot_or( + a: defaultdict[int, int], + b: CustomDefaultDictSubclass[int, int], + c: defaultdict[str, str], + d: Mapping[int, int], + e: CustomMappingWithDunderOr[str, str], +) -> None: + assert_type(a | b, defaultdict[int, int]) + + # In contrast to `dict.__or__`, `defaultdict.__or__` returns `Self` if called on a subclass of `defaultdict`: + assert_type(b | a, CustomDefaultDictSubclass[int, int]) + + assert_type(a | c, defaultdict[Union[int, str], Union[int, str]]) + + # arbitrary mappings are not accepted by `defaultdict.__or__`; + # it has to be a subclass of `dict` + a | d # type: ignore + + # but Mappings such as `os._Environ` or `CustomMappingWithDunderOr`, + # which define `__ror__` methods that accept `dict`, are fine + # (`os._Environ.__(r)or__` always returns `dict`, even if a `defaultdict` is passed): + assert_type(a | os.environ, dict[Union[str, int], Union[str, int]]) + assert_type(os.environ | a, dict[Union[str, int], Union[str, int]]) + + assert_type(c | os.environ, dict[str, str]) + assert_type(c | e, dict[str, str]) + + assert_type(os.environ | c, dict[str, str]) + assert_type(e | c, dict[str, str]) + + # store "untainted" `CustomMappingWithDunderOr[str, str]` to test `__ior__` against ` defaultdict[str, str]` later + # Invalid `e |= a` causes pyright to join `Unknown` to `e`'s type + f = e + + e |= c + e |= a # type: ignore + + c |= f + + c |= a # type: ignore diff --git a/stdlib/@tests/test_cases/ctypes/check_CDLL.py b/stdlib/@tests/test_cases/ctypes/check_CDLL.py new file mode 100644 index 000000000000..ca7dc248160b --- /dev/null +++ b/stdlib/@tests/test_cases/ctypes/check_CDLL.py @@ -0,0 +1,11 @@ +import ctypes +import sys +from pathlib import Path +from typing_extensions import assert_type + +assert_type(ctypes.CDLL(None), ctypes.CDLL) +assert_type(ctypes.CDLL("."), ctypes.CDLL) + +# https://github.com/python/cpython/pull/7032 +if sys.version_info >= (3, 12): + assert_type(ctypes.CDLL(Path(".")), ctypes.CDLL) diff --git a/stdlib/@tests/test_cases/ctypes/check_pointer.py b/stdlib/@tests/test_cases/ctypes/check_pointer.py new file mode 100644 index 000000000000..55f6e1365e57 --- /dev/null +++ b/stdlib/@tests/test_cases/ctypes/check_pointer.py @@ -0,0 +1,8 @@ +from __future__ import annotations + +import ctypes +from typing import Type +from typing_extensions import assert_type + +assert_type(ctypes.POINTER(None), Type[ctypes.c_void_p]) +assert_type(ctypes.POINTER(ctypes.c_int), Type[ctypes._Pointer[ctypes.c_int]]) diff --git a/stdlib/@tests/test_cases/email/check_message.py b/stdlib/@tests/test_cases/email/check_message.py new file mode 100644 index 000000000000..7939f2981708 --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_message.py @@ -0,0 +1,18 @@ +from email.headerregistry import Address, BaseHeader +from email.message import EmailMessage, MIMEPart +from typing_extensions import assert_type + +msg = EmailMessage() +msg["To"] = "receiver@example.com" +msg["From"] = Address("Sender Name", "sender", "example.com") + +for a in msg.iter_attachments(): + assert_type(a, EmailMessage) + +generic_msg: EmailMessage[BaseHeader, str] = EmailMessage() +assert_type(generic_msg.get("To"), BaseHeader | None) +assert_type(generic_msg.get_body(), MIMEPart[BaseHeader, str] | None) +for a in generic_msg.iter_attachments(): + assert_type(a, EmailMessage[BaseHeader, str]) +for p in generic_msg.iter_parts(): + assert_type(p, MIMEPart[BaseHeader, str]) diff --git a/stdlib/@tests/test_cases/email/check_mime.py b/stdlib/@tests/test_cases/email/check_mime.py new file mode 100644 index 000000000000..e49d2bfacc21 --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_mime.py @@ -0,0 +1,4 @@ +from email.mime.text import MIMEText +from email.policy import SMTP + +msg = MIMEText("", policy=SMTP) diff --git a/stdlib/@tests/test_cases/email/check_parser.py b/stdlib/@tests/test_cases/email/check_parser.py new file mode 100644 index 000000000000..fd5c24a9f6de --- /dev/null +++ b/stdlib/@tests/test_cases/email/check_parser.py @@ -0,0 +1,16 @@ +import email.policy +from email.message import EmailMessage, Message +from email.parser import BytesParser, Parser +from typing_extensions import assert_type + +p1 = Parser() +p2 = Parser(policy=email.policy.default) + +assert_type(p1, Parser[Message[str, str]]) +assert_type(p2, Parser[EmailMessage]) + +bp1 = BytesParser() +bp2 = BytesParser(policy=email.policy.default) + +assert_type(bp1, BytesParser[Message[str, str]]) +assert_type(bp2, BytesParser[EmailMessage]) diff --git a/stdlib/@tests/test_cases/itertools/check_batched.py b/stdlib/@tests/test_cases/itertools/check_batched.py new file mode 100644 index 000000000000..5e0e2ae77320 --- /dev/null +++ b/stdlib/@tests/test_cases/itertools/check_batched.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import sys +from typing_extensions import assert_type + +if sys.version_info >= (3, 13): + from itertools import batched + + assert_type(batched([0], 1, strict=True), batched[tuple[int]]) + assert_type(batched([0, 0], 2, strict=True), batched[tuple[int, int]]) + assert_type(batched([0, 0, 0], 3, strict=True), batched[tuple[int, int, int]]) + assert_type(batched([0, 0, 0, 0], 4, strict=True), batched[tuple[int, int, int, int]]) + assert_type(batched([0, 0, 0, 0, 0], 5, strict=True), batched[tuple[int, int, int, int, int]]) + + assert_type(batched([0], 2), batched[tuple[int, ...]]) + assert_type(batched([0], 2, strict=False), batched[tuple[int, ...]]) + + def f() -> int: + return 3 + + assert_type(batched([0, 0, 0], f(), strict=True), batched[tuple[int, ...]]) diff --git a/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py b/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py new file mode 100644 index 000000000000..84f4bca5c868 --- /dev/null +++ b/stdlib/@tests/test_cases/itertools/check_itertools_recipes.py @@ -0,0 +1,415 @@ +"""Type-annotated versions of the recipes from the itertools docs. + +These are all meant to be examples of idiomatic itertools usage, +so they should all type-check without error. +""" + +from __future__ import annotations + +import collections +import math +import operator +import sys +from itertools import chain, combinations, count, cycle, filterfalse, groupby, islice, product, repeat, starmap, tee, zip_longest +from typing import ( + Any, + Callable, + Collection, + Hashable, + Iterable, + Iterator, + Literal, + Sequence, + Tuple, + Type, + TypeAlias, + TypeVar, + Union, + overload, +) +from typing_extensions import TypeVarTuple, Unpack + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_HashableT = TypeVar("_HashableT", bound=Hashable) +_Ts = TypeVarTuple("_Ts") + + +def take(n: int, iterable: Iterable[_T]) -> list[_T]: + "Return first n items of the iterable as a list" + return list(islice(iterable, n)) + + +# Note: the itertools docs uses the parameter name "iterator", +# but the function actually accepts any iterable +# as its second argument +def prepend(value: _T1, iterator: Iterable[_T2]) -> Iterator[_T1 | _T2]: + "Prepend a single value in front of an iterator" + # prepend(1, [2, 3, 4]) --> 1 2 3 4 + return chain([value], iterator) + + +def tabulate(function: Callable[[int], _T], start: int = 0) -> Iterator[_T]: + "Return function(0), function(1), ..." + return map(function, count(start)) + + +def repeatfunc(func: Callable[[Unpack[_Ts]], _T], times: int | None = None, *args: Unpack[_Ts]) -> Iterator[_T]: + """Repeat calls to func with specified arguments. + + Example: repeatfunc(random.random) + """ + if times is None: + return starmap(func, repeat(args)) + return starmap(func, repeat(args, times)) + + +def flatten(list_of_lists: Iterable[Iterable[_T]]) -> Iterator[_T]: + "Flatten one level of nesting" + return chain.from_iterable(list_of_lists) + + +def ncycles(iterable: Iterable[_T], n: int) -> Iterator[_T]: + "Returns the sequence elements n times" + return chain.from_iterable(repeat(tuple(iterable), n)) + + +def tail(n: int, iterable: Iterable[_T]) -> Iterator[_T]: + "Return an iterator over the last n items" + # tail(3, 'ABCDEFG') --> E F G + return iter(collections.deque(iterable, maxlen=n)) + + +# This function *accepts* any iterable, +# but it only *makes sense* to use it with an iterator +def consume(iterator: Iterator[object], n: int | None = None) -> None: + "Advance the iterator n-steps ahead. If n is None, consume entirely." + # Use functions that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + collections.deque(iterator, maxlen=0) + else: + # advance to the empty slice starting at position n + next(islice(iterator, n, n), None) + + +@overload +def nth(iterable: Iterable[_T], n: int, default: None = None) -> _T | None: ... + + +@overload +def nth(iterable: Iterable[_T], n: int, default: _T1) -> _T | _T1: ... + + +def nth(iterable: Iterable[object], n: int, default: object = None) -> object: + "Returns the nth item or a default value" + return next(islice(iterable, n, None), default) + + +@overload +def quantify(iterable: Iterable[object]) -> int: ... + + +@overload +def quantify(iterable: Iterable[_T], pred: Callable[[_T], bool]) -> int: ... + + +def quantify(iterable: Iterable[object], pred: Callable[[Any], bool] = bool) -> int: + "Given a predicate that returns True or False, count the True results." + return sum(map(pred, iterable)) + + +@overload +def first_true( + iterable: Iterable[_T], default: Literal[False] = False, pred: Callable[[_T], bool] | None = None +) -> _T | Literal[False]: ... + + +@overload +def first_true(iterable: Iterable[_T], default: _T1, pred: Callable[[_T], bool] | None = None) -> _T | _T1: ... + + +def first_true(iterable: Iterable[object], default: object = False, pred: Callable[[Any], bool] | None = None) -> object: + """Returns the first true value in the iterable. + If no true value is found, returns *default* + If *pred* is not None, returns the first item + for which pred(item) is true. + """ + # first_true([a,b,c], x) --> a or b or c or x + # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x + return next(filter(pred, iterable), default) + + +_ExceptionOrExceptionTuple: TypeAlias = Union[Type[BaseException], Tuple[Type[BaseException], ...]] + + +@overload +def iter_except(func: Callable[[], _T], exception: _ExceptionOrExceptionTuple, first: None = None) -> Iterator[_T]: ... + + +@overload +def iter_except( + func: Callable[[], _T], exception: _ExceptionOrExceptionTuple, first: Callable[[], _T1] +) -> Iterator[_T | _T1]: ... + + +def iter_except( + func: Callable[[], object], exception: _ExceptionOrExceptionTuple, first: Callable[[], object] | None = None +) -> Iterator[object]: + """Call a function repeatedly until an exception is raised. + Converts a call-until-exception interface to an iterator interface. + Like builtins.iter(func, sentinel) but uses an exception instead + of a sentinel to end the loop. + Examples: + iter_except(functools.partial(heappop, h), IndexError) # priority queue iterator + iter_except(d.popitem, KeyError) # non-blocking dict iterator + iter_except(d.popleft, IndexError) # non-blocking deque iterator + iter_except(q.get_nowait, Queue.Empty) # loop over a producer Queue + iter_except(s.pop, KeyError) # non-blocking set iterator + """ + try: + if first is not None: + yield first() # For database APIs needing an initial cast to db.first() + while True: + yield func() + except exception: + pass + + +def sliding_window(iterable: Iterable[_T], n: int) -> Iterator[tuple[_T, ...]]: + # sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFG + it = iter(iterable) + window = collections.deque(islice(it, n - 1), maxlen=n) + for x in it: + window.append(x) + yield tuple(window) + + +def roundrobin(*iterables: Iterable[_T]) -> Iterator[_T]: + "roundrobin('ABC', 'D', 'EF') --> A D E B F C" + # Recipe credited to George Sakkis + num_active = len(iterables) + nexts: Iterator[Callable[[], _T]] = cycle(iter(it).__next__ for it in iterables) + while num_active: + try: + for next in nexts: + yield next() + except StopIteration: + # Remove the iterator we just exhausted from the cycle. + num_active -= 1 + nexts = cycle(islice(nexts, num_active)) + + +def partition(pred: Callable[[_T], bool], iterable: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]: + """Partition entries into false entries and true entries. + If *pred* is slow, consider wrapping it with functools.lru_cache(). + """ + # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 + t1, t2 = tee(iterable) + return filterfalse(pred, t1), filter(pred, t2) + + +def subslices(seq: Sequence[_T]) -> Iterator[Sequence[_T]]: + "Return all contiguous non-empty subslices of a sequence" + # subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D + slices = starmap(slice, combinations(range(len(seq) + 1), 2)) + return map(operator.getitem, repeat(seq), slices) + + +def before_and_after(predicate: Callable[[_T], bool], it: Iterable[_T]) -> tuple[Iterator[_T], Iterator[_T]]: + """Variant of takewhile() that allows complete + access to the remainder of the iterator. + >>> it = iter('ABCdEfGhI') + >>> all_upper, remainder = before_and_after(str.isupper, it) + >>> ''.join(all_upper) + 'ABC' + >>> ''.join(remainder) # takewhile() would lose the 'd' + 'dEfGhI' + Note that the first iterator must be fully + consumed before the second iterator can + generate valid results. + """ + it = iter(it) + transition: list[_T] = [] + + def true_iterator() -> Iterator[_T]: + for elem in it: + if predicate(elem): + yield elem + else: + transition.append(elem) + return + + def remainder_iterator() -> Iterator[_T]: + yield from transition + yield from it + + return true_iterator(), remainder_iterator() + + +@overload +def unique_everseen(iterable: Iterable[_HashableT], key: None = None) -> Iterator[_HashableT]: ... + + +@overload +def unique_everseen(iterable: Iterable[_T], key: Callable[[_T], Hashable]) -> Iterator[_T]: ... + + +def unique_everseen(iterable: Iterable[_T], key: Callable[[_T], Hashable] | None = None) -> Iterator[_T]: + "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[Hashable] = set() + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen.add(element) + yield element + # For order preserving deduplication, + # a faster but non-lazy solution is: + # yield from dict.fromkeys(iterable) + else: + for element in iterable: + k = key(element) + if k not in seen: + seen.add(k) + yield element + # For use cases that allow the last matching element to be returned, + # a faster but non-lazy solution is: + # t1, t2 = tee(iterable) + # yield from dict(zip(map(key, t1), t2)).values() + + +# Slightly adapted from the docs recipe; a one-liner was a bit much for pyright +def unique_justseen(iterable: Iterable[_T], key: Callable[[_T], bool] | None = None) -> Iterator[_T]: + "List unique elements, preserving order. Remember only the element just seen." + # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B + # unique_justseen('ABBcCAD', str.lower) --> A B c A D + if key is None: + return map(operator.itemgetter(0), groupby(iterable)) + g: groupby[_T | bool, _T] = groupby(iterable, key) + return map(next, map(operator.itemgetter(1), g)) + + +def powerset(iterable: Iterable[_T]) -> Iterator[tuple[_T, ...]]: + "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" + s = list(iterable) + return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) + + +def polynomial_derivative(coefficients: Sequence[float]) -> list[float]: + """Compute the first derivative of a polynomial. + f(x) = x³ -4x² -17x + 60 + f'(x) = 3x² -8x -17 + """ + # polynomial_derivative([1, -4, -17, 60]) -> [3, -8, -17] + n = len(coefficients) + powers = reversed(range(1, n)) + return list(map(operator.mul, coefficients, powers)) + + +def nth_combination(iterable: Iterable[_T], r: int, index: int) -> tuple[_T, ...]: + "Equivalent to list(combinations(iterable, r))[index]" + pool = tuple(iterable) + n = len(pool) + c = math.comb(n, r) + if index < 0: + index += c + if index < 0 or index >= c: + raise IndexError + result: list[_T] = [] + while r: + c, n, r = c * r // n, n - 1, r - 1 + while index >= c: + index -= c + c, n = c * (n - r) // n, n - 1 + result.append(pool[-1 - n]) + return tuple(result) + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["fill"] = "fill", fillvalue: None = None +) -> Iterator[tuple[_T | None, ...]]: ... + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["fill"] = "fill", fillvalue: _T1 +) -> Iterator[tuple[_T | _T1, ...]]: ... + + +@overload +def grouper( + iterable: Iterable[_T], n: int, *, incomplete: Literal["strict", "ignore"], fillvalue: None = None +) -> Iterator[tuple[_T, ...]]: ... + + +def grouper( + iterable: Iterable[object], n: int, *, incomplete: Literal["fill", "strict", "ignore"] = "fill", fillvalue: object = None +) -> Iterator[tuple[object, ...]]: + "Collect data into non-overlapping fixed-length chunks or blocks" + # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx + # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError + # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF + args = [iter(iterable)] * n + if incomplete == "fill": + return zip_longest(*args, fillvalue=fillvalue) + if incomplete == "strict": + return zip(*args, strict=True) + if incomplete == "ignore": + return zip(*args) + else: + raise ValueError("Expected fill, strict, or ignore") + + +def transpose(it: Iterable[Iterable[_T]]) -> Iterator[tuple[_T, ...]]: + "Swap the rows and columns of the input." + # transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33) + return zip(*it, strict=True) + + +if sys.version_info >= (3, 12): + from itertools import batched + + def sum_of_squares(it: Iterable[float]) -> float: + "Add up the squares of the input values." + # sum_of_squares([10, 20, 30]) -> 1400 + return math.sumprod(*tee(it)) + + def convolve(signal: Iterable[float], kernel: Iterable[float]) -> Iterator[float]: + """Discrete linear convolution of two iterables. + The kernel is fully consumed before the calculations begin. + The signal is consumed lazily and can be infinite. + Convolutions are mathematically commutative. + If the signal and kernel are swapped, + the output will be the same. + Article: https://betterexplained.com/articles/intuitive-convolution/ + Video: https://www.youtube.com/watch?v=KuXjwB4LzSA + """ + # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur) + # convolve(data, [1/2, 0, -1/2]) --> 1st derivative estimate + # convolve(data, [1, -2, 1]) --> 2nd derivative estimate + kernel = tuple(kernel)[::-1] + n = len(kernel) + padded_signal = chain(repeat(0, n - 1), signal, repeat(0, n - 1)) + windowed_signal = sliding_window(padded_signal, n) + return map(math.sumprod, repeat(kernel), windowed_signal) + + def polynomial_eval(coefficients: Sequence[float], x: float) -> float: + """Evaluate a polynomial at a specific value. + Computes with better numeric stability than Horner's method. + """ + # Evaluate x³ -4x² -17x + 60 at x = 2.5 + # polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125 + n = len(coefficients) + if not n: + return type(x)(0) + powers = map(pow, repeat(x), reversed(range(n))) + return math.sumprod(coefficients, powers) + + def matmul(m1: Sequence[Collection[float]], m2: Sequence[Collection[float]]) -> Iterator[tuple[float, ...]]: + "Multiply two matrices." + # matmul([(7, 5), (3, 5)], [(2, 5), (7, 9)]) --> (49, 80), (41, 60) + n = len(m2[0]) + return batched(starmap(math.sumprod, product(m1, transpose(m2))), n) diff --git a/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py b/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py new file mode 100644 index 000000000000..42da0a66fa60 --- /dev/null +++ b/stdlib/@tests/test_cases/multiprocessing/check_ctypes.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from ctypes import c_char, c_float, c_int +from multiprocessing import Array, Value +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString +from typing_extensions import assert_type + +string = Array(c_char, 12) +assert_type(string, SynchronizedString) +assert_type(string.value, bytes) + +numbers = Array(c_int, 3) +assert_type(numbers, SynchronizedArray[int]) +numbers[0] = 3 +numbers[:] = [0, 1, 2] + +field = Value(c_float, 0.0) +assert_type(field, Synchronized[float]) +field.value = 1.2 diff --git a/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py b/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py new file mode 100644 index 000000000000..1d6266a0aabb --- /dev/null +++ b/stdlib/@tests/test_cases/multiprocessing/check_pipe_connections.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import sys +from multiprocessing.connection import Pipe + +if sys.platform != "win32": + from multiprocessing.connection import Connection +else: + from multiprocessing.connection import PipeConnection as Connection + + +# Unfortunately, we cannot validate that both connections have the same, but inverted generic types, +# since TypeVars scoped entirely within a return annotation is unspecified in the spec. +# Pipe[str, int]() -> tuple[Connection[str, int], Connection[int, str]] + +a: Connection[str, int] +b: Connection[int, str] +a, b = Pipe() + +connections: tuple[Connection[str, int], Connection[int, str]] = Pipe() +a, b = connections + +a.send("test") +a.send(0) # type: ignore +test1: str = b.recv() +test2: int = b.recv() # type: ignore + +b.send("test") # type: ignore +b.send(0) +test3: str = a.recv() # type: ignore +test4: int = a.recv() diff --git a/stdlib/@tests/test_cases/sys/check_jit.py b/stdlib/@tests/test_cases/sys/check_jit.py new file mode 100644 index 000000000000..7916218ceda4 --- /dev/null +++ b/stdlib/@tests/test_cases/sys/check_jit.py @@ -0,0 +1,12 @@ +import sys +from typing_extensions import assert_type + +if sys.version_info >= (3, 14): + assert_type(sys._jit.is_available(), bool) + assert_type(sys._jit.is_enabled(), bool) + assert_type(sys._jit.is_active(), bool) + + def sys_is_not_a_package() -> None: + # This has to be put into a function, because otherwise the presence + # of this import statement causes errors on the above usages of `sys._jit`. + import sys._jit # type: ignore diff --git a/stdlib/@tests/test_cases/typing/check_MutableMapping.py b/stdlib/@tests/test_cases/typing/check_MutableMapping.py new file mode 100644 index 000000000000..1e9d747fc8f6 --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_MutableMapping.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import Any, Hashable, Sequence, Union +from typing_extensions import assert_type + + +def check_update_method__int_key() -> None: + d: dict[int, int] = {} + d.update({1: 2}) + d.update([(1, 2)]) + d.update(a=3) # type: ignore + d.update({1: 2}, a=3) # type: ignore + d.update([(1, 2)], a=3) # type: ignore + d.update({"": 3}) # type: ignore + d.update({1: ""}) # type: ignore + d.update([("", 3)]) # type: ignore + d.update([(3, "")]) # type: ignore + + +def check_update_method__str_key() -> None: + d: dict[str, int] = {} + d.update({"": 2}) + d.update([("", 2)]) + d.update(a=3) + d.update({"": 2}, a=3) + d.update([("", 2)], a=3) + d.update({1: 3}) # type: ignore + d.update({"": ""}) # type: ignore + d.update([(1, 3)]) # type: ignore + d.update([("", "")]) # type: ignore + + +def test_keywords_allowed_on_dict_update_where_key_type_is_str_supertype( + a: dict[object, Any], b: dict[Hashable, Any], c: dict[Sequence[str], Any], d: dict[str, Any] +) -> None: + a.update(keyword_args_are_accepted="whatever") + b.update(here_too="whooo") + c.update(and_here="hooray") + d.update(also_here="yay") + + +def check_setdefault_method() -> None: + d: dict[int, str] = {} + d2: dict[int, str | None] = {} + d3: dict[int, Any] = {} + + d.setdefault(1) # type: ignore + assert_type(d.setdefault(1, "x"), str) + assert_type(d2.setdefault(1), Union[str, None]) + assert_type(d2.setdefault(1, None), Union[str, None]) + assert_type(d2.setdefault(1, "x"), Union[str, None]) + assert_type(d3.setdefault(1), Union[Any, None]) + assert_type(d3.setdefault(1, "x"), Any) diff --git a/stdlib/@tests/test_cases/typing/check_all.py b/stdlib/@tests/test_cases/typing/check_all.py new file mode 100644 index 000000000000..7e48fd4351cf --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_all.py @@ -0,0 +1,13 @@ +# pyright: reportWildcardImportFromLibrary=false +""" +This tests that star imports work when using "all += " syntax. +""" + +from __future__ import annotations + +from typing import * +from zipfile import * + +x: Annotated[int, 42] + +p: Path diff --git a/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py b/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py new file mode 100644 index 000000000000..23beaa87ae05 --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_regression_issue_9296.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing import Any, KeysView, TypeVar + +KT = TypeVar("KT") + + +class MyKeysView(KeysView[KT]): + pass + + +d: dict[Any, Any] = {} +dict_keys = type(d.keys()) + +# This should not cause an error like `Member "register" is unknown`: +MyKeysView.register(dict_keys) diff --git a/stdlib/@tests/test_cases/typing/check_typing_io.py b/stdlib/@tests/test_cases/typing/check_typing_io.py new file mode 100644 index 000000000000..67f16dc91765 --- /dev/null +++ b/stdlib/@tests/test_cases/typing/check_typing_io.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +import mmap +from typing import IO, AnyStr + + +def check_write(io_bytes: IO[bytes], io_str: IO[str], io_anystr: IO[AnyStr], any_str: AnyStr, buf: mmap.mmap) -> None: + io_bytes.write(b"") + io_bytes.write(buf) + io_bytes.write("") # type: ignore + io_bytes.write(any_str) # type: ignore + + io_str.write(b"") # type: ignore + io_str.write(buf) # type: ignore + io_str.write("") + io_str.write(any_str) # type: ignore + + io_anystr.write(b"") # type: ignore + io_anystr.write(buf) # type: ignore + io_anystr.write("") # type: ignore + io_anystr.write(any_str) diff --git a/stdlib/@tests/test_cases/urllib/check_parse.py b/stdlib/@tests/test_cases/urllib/check_parse.py new file mode 100644 index 000000000000..f464f6341fdc --- /dev/null +++ b/stdlib/@tests/test_cases/urllib/check_parse.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from urllib.parse import quote, quote_plus, urlencode + +urlencode({"a": "b"}, quote_via=quote) +urlencode({b"a": b"b"}, quote_via=quote) +urlencode({"a": b"b"}, quote_via=quote) +urlencode({b"a": "b"}, quote_via=quote) +mixed_dict: dict[str | bytes, str | bytes] = {} +urlencode(mixed_dict, quote_via=quote) + +urlencode({"a": "b"}, quote_via=quote_plus) diff --git a/stdlib/VERSIONS b/stdlib/VERSIONS new file mode 100644 index 000000000000..96eb98131db6 --- /dev/null +++ b/stdlib/VERSIONS @@ -0,0 +1,349 @@ +# The structure of this file is as follows: +# - Blank lines and comments starting with `#` are ignored. +# - Lines contain the name of a module, followed by a colon, +# a space, and a version range (for example: `symbol: 3.0-3.9`). +# +# Version ranges may be of the form "X.Y-A.B" or "X.Y-". The +# first form means that a module was introduced in version X.Y and last +# available in version A.B. The second form means that the module was +# introduced in version X.Y and is still available in the latest +# version of Python. +# +# If a submodule is not listed separately, it has the same lifetime as +# its parent module. +# +# Python versions before 3.0 are ignored, so any module that was already +# present in 3.0 will have "3.0" as its minimum version. Version ranges +# for unsupported versions of Python 3 are generally accurate but we do +# not guarantee their correctness. + +__future__: 3.0- +__main__: 3.0- +_ast: 3.0- +_asyncio: 3.0- +_bisect: 3.0- +_blake2: 3.6- +_bz2: 3.3- +_codecs: 3.0- +_collections_abc: 3.3- +_compat_pickle: 3.1- +_compression: 3.5-3.13 +_contextvars: 3.7- +_csv: 3.0- +_ctypes: 3.0- +_curses: 3.0- +_curses_panel: 3.0- +_dbm: 3.0- +_decimal: 3.3- +_frozen_importlib: 3.0- +_frozen_importlib_external: 3.5- +_gdbm: 3.0- +_hashlib: 3.0- +_heapq: 3.0- +_imp: 3.0- +_interpchannels: 3.13- +_interpqueues: 3.13- +_interpreters: 3.13- +_io: 3.0- +_json: 3.0- +_locale: 3.0- +_lsprof: 3.0- +_lzma: 3.3- +_markupbase: 3.0- +_msi: 3.0-3.12 +_multibytecodec: 3.0- +_operator: 3.4- +_osx_support: 3.0- +_pickle: 3.0- +_posixsubprocess: 3.2- +_py_abc: 3.7- +_pydecimal: 3.5- +_queue: 3.7- +_random: 3.0- +_remote_debugging: 3.15- +_sitebuiltins: 3.4- +_socket: 3.0- # present in 3.0 at runtime, but not in typeshed +_sqlite3: 3.0- +_ssl: 3.0- +_stat: 3.4- +_struct: 3.0- +_thread: 3.0- +_threading_local: 3.0- +_tkinter: 3.0- +_tracemalloc: 3.4- +_typeshed: 3.0- # not present at runtime, only for type checking +_warnings: 3.0- +_weakref: 3.0- +_weakrefset: 3.0- +_winapi: 3.3- +_zstd: 3.14- +abc: 3.0- +aifc: 3.0-3.12 +annotationlib: 3.14- +antigravity: 3.0- +argparse: 3.0- +array: 3.0- +ast: 3.0- +asynchat: 3.0-3.11 +asyncio: 3.4- +asyncio.exceptions: 3.8- +asyncio.format_helpers: 3.7- +asyncio.graph: 3.14- +asyncio.mixins: 3.10- +asyncio.runners: 3.7- +asyncio.staggered: 3.8- +asyncio.taskgroups: 3.11- +asyncio.threads: 3.9- +asyncio.timeouts: 3.11- +asyncio.tools: 3.14- +asyncio.trsock: 3.8- +asyncore: 3.0-3.11 +atexit: 3.0- +audioop: 3.0-3.12 +base64: 3.0- +bdb: 3.0- +binascii: 3.0- +binhex: 3.0-3.10 +bisect: 3.0- +builtins: 3.0- +bz2: 3.0- +cProfile: 3.0- +calendar: 3.0- +cgi: 3.0-3.12 +cgitb: 3.0-3.12 +chunk: 3.0-3.12 +cmath: 3.0- +cmd: 3.0- +code: 3.0- +codecs: 3.0- +codeop: 3.0- +collections: 3.0- +collections.abc: 3.3- +colorsys: 3.0- +compileall: 3.0- +compression: 3.14- +concurrent: 3.2- +concurrent.futures.interpreter: 3.14- +concurrent.interpreters: 3.14- +configparser: 3.0- +contextlib: 3.0- +contextvars: 3.7- +copy: 3.0- +copyreg: 3.0- +crypt: 3.0-3.12 +csv: 3.0- +ctypes: 3.0- +curses: 3.0- +dataclasses: 3.7- +datetime: 3.0- +dbm: 3.0- +dbm.sqlite3: 3.13- +decimal: 3.0- +difflib: 3.0- +dis: 3.0- +distutils: 3.0-3.11 +distutils.command.bdist_msi: 3.0-3.10 +doctest: 3.0- +email: 3.0- +encodings: 3.0- +encodings.cp1125: 3.4- +encodings.cp273: 3.4- +encodings.cp858: 3.2- +encodings.koi8_t: 3.5- +encodings.kz1048: 3.5- +ensurepip: 3.0- +enum: 3.4- +errno: 3.0- +faulthandler: 3.3- +fcntl: 3.0- +filecmp: 3.0- +fileinput: 3.0- +fnmatch: 3.0- +fractions: 3.0- +ftplib: 3.0- +functools: 3.0- +gc: 3.0- +genericpath: 3.0- +getopt: 3.0- +getpass: 3.0- +gettext: 3.0- +glob: 3.0- +graphlib: 3.9- +grp: 3.0- +gzip: 3.0- +hashlib: 3.0- +heapq: 3.0- +hmac: 3.0- +html: 3.0- +http: 3.0- +imaplib: 3.0- +imghdr: 3.0-3.12 +imp: 3.0-3.11 +importlib: 3.0- +importlib._abc: 3.10- +importlib._bootstrap: 3.0- +importlib._bootstrap_external: 3.5- +importlib.metadata: 3.8- +importlib.metadata._meta: 3.10- +importlib.metadata.diagnose: 3.13- +importlib.readers: 3.10- +importlib.resources: 3.7- +importlib.resources._common: 3.11- +importlib.resources._functional: 3.13- +importlib.resources.abc: 3.11- +importlib.resources.readers: 3.11- +importlib.resources.simple: 3.11- +importlib.simple: 3.11- +inspect: 3.0- +io: 3.0- +ipaddress: 3.3- +itertools: 3.0- +json: 3.0- +keyword: 3.0- +lib2to3: 3.0-3.12 +linecache: 3.0- +locale: 3.0- +logging: 3.0- +lzma: 3.3- +mailbox: 3.0- +mailcap: 3.0-3.12 +marshal: 3.0- +math: 3.0- +math.integer: 3.15- +mimetypes: 3.0- +mmap: 3.0- +modulefinder: 3.0- +msilib: 3.0-3.12 +msvcrt: 3.0- +multiprocessing: 3.0- +multiprocessing.resource_tracker: 3.8- +multiprocessing.shared_memory: 3.8- +netrc: 3.0- +nis: 3.0-3.12 +nntplib: 3.0-3.12 +nt: 3.0- +ntpath: 3.0- +nturl2path: 3.0- +numbers: 3.0- +opcode: 3.0- +operator: 3.0- +optparse: 3.0- +os: 3.0- +ossaudiodev: 3.0-3.12 +pathlib: 3.4- +pathlib.types: 3.14- +pdb: 3.0- +pickle: 3.0- +pickletools: 3.0- +pipes: 3.0-3.12 +pkgutil: 3.0- +platform: 3.0- +plistlib: 3.0- +poplib: 3.0- +posix: 3.0- +posixpath: 3.0- +pprint: 3.0- +profile: 3.0- +profiling: 3.15- +pstats: 3.0- +pty: 3.0- +pwd: 3.0- +py_compile: 3.0- +pyclbr: 3.0- +pydoc: 3.0- +pydoc_data: 3.0- +pydoc_data.module_docs: 3.13- +pyexpat: 3.0- +queue: 3.0- +quopri: 3.0- +random: 3.0- +re: 3.0- +readline: 3.0- +reprlib: 3.0- +resource: 3.0- +rlcompleter: 3.0- +runpy: 3.0- +sched: 3.0- +secrets: 3.6- +select: 3.0- +selectors: 3.4- +shelve: 3.0- +shlex: 3.0- +shutil: 3.0- +signal: 3.0- +site: 3.0- +smtpd: 3.0-3.11 +smtplib: 3.0- +sndhdr: 3.0-3.12 +socket: 3.0- +socketserver: 3.0- +spwd: 3.0-3.12 +sqlite3: 3.0- +sre_compile: 3.0-3.14 +sre_constants: 3.0-3.14 +sre_parse: 3.0-3.14 +ssl: 3.0- +stat: 3.0- +statistics: 3.4- +string: 3.0- +string.templatelib: 3.14- +stringprep: 3.0- +struct: 3.0- +subprocess: 3.0- +sunau: 3.0-3.12 +symtable: 3.0- +sys: 3.0- +sys.__jit: 3.14- # Similar to sys._monitoring +sys._monitoring: 3.12- # Doesn't actually exist. See comments in the stub. +sysconfig: 3.0- +syslog: 3.0- +tabnanny: 3.0- +tarfile: 3.0- +telnetlib: 3.0-3.12 +tempfile: 3.0- +termios: 3.0- +textwrap: 3.0- +this: 3.0- +threading: 3.0- +time: 3.0- +timeit: 3.0- +tkinter: 3.0- +tkinter.tix: 3.0-3.12 +token: 3.0- +tokenize: 3.0- +tomllib: 3.11- +trace: 3.0- +traceback: 3.0- +tracemalloc: 3.4- +tty: 3.0- +turtle: 3.0- +types: 3.0- +typing: 3.5- +typing_extensions: 3.0- +unicodedata: 3.0- +unittest: 3.0- +unittest._log: 3.9- +unittest.async_case: 3.8- +urllib: 3.0- +uu: 3.0-3.12 +uuid: 3.0- +venv: 3.3- +warnings: 3.0- +wave: 3.0- +weakref: 3.0- +webbrowser: 3.0- +winreg: 3.0- +winsound: 3.0- +wsgiref: 3.0- +wsgiref.types: 3.11- +xdrlib: 3.0-3.12 +xml: 3.0- +xml.utils: 3.15- +xmlrpc: 3.0- +xxlimited: 3.2- +zipapp: 3.5- +zipfile: 3.0- +zipfile._path: 3.12- +zipimport: 3.0- +zlib: 3.0- +zoneinfo: 3.9- diff --git a/stdlib/__future__.pyi b/stdlib/__future__.pyi new file mode 100644 index 000000000000..aa445d22bd20 --- /dev/null +++ b/stdlib/__future__.pyi @@ -0,0 +1,36 @@ +from typing import TypeAlias + +_VersionInfo: TypeAlias = tuple[int, int, int, str, int] + +class _Feature: + def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ... + def getOptionalRelease(self) -> _VersionInfo: ... + def getMandatoryRelease(self) -> _VersionInfo | None: ... + compiler_flag: int + +absolute_import: _Feature +division: _Feature +generators: _Feature +nested_scopes: _Feature +print_function: _Feature +unicode_literals: _Feature +with_statement: _Feature +barry_as_FLUFL: _Feature +generator_stop: _Feature +annotations: _Feature + +all_feature_names: list[str] # undocumented + +__all__ = [ + "all_feature_names", + "absolute_import", + "division", + "generators", + "nested_scopes", + "print_function", + "unicode_literals", + "with_statement", + "barry_as_FLUFL", + "generator_stop", + "annotations", +] diff --git a/stdlib/__main__.pyi b/stdlib/__main__.pyi new file mode 100644 index 000000000000..3536a6f021c5 --- /dev/null +++ b/stdlib/__main__.pyi @@ -0,0 +1 @@ +def __getattr__(name: str, /): ... # incomplete module diff --git a/stdlib/_ast.pyi b/stdlib/_ast.pyi new file mode 100644 index 000000000000..fd89973aefe6 --- /dev/null +++ b/stdlib/_ast.pyi @@ -0,0 +1,141 @@ +import sys +from ast import ( + AST as AST, + Add as Add, + And as And, + AnnAssign as AnnAssign, + Assert as Assert, + Assign as Assign, + AsyncFor as AsyncFor, + AsyncFunctionDef as AsyncFunctionDef, + AsyncWith as AsyncWith, + Attribute as Attribute, + AugAssign as AugAssign, + Await as Await, + BinOp as BinOp, + BitAnd as BitAnd, + BitOr as BitOr, + BitXor as BitXor, + BoolOp as BoolOp, + Break as Break, + Call as Call, + ClassDef as ClassDef, + Compare as Compare, + Constant as Constant, + Continue as Continue, + Del as Del, + Delete as Delete, + Dict as Dict, + DictComp as DictComp, + Div as Div, + Eq as Eq, + ExceptHandler as ExceptHandler, + Expr as Expr, + Expression as Expression, + FloorDiv as FloorDiv, + For as For, + FormattedValue as FormattedValue, + FunctionDef as FunctionDef, + FunctionType as FunctionType, + GeneratorExp as GeneratorExp, + Global as Global, + Gt as Gt, + GtE as GtE, + If as If, + IfExp as IfExp, + Import as Import, + ImportFrom as ImportFrom, + In as In, + Interactive as Interactive, + Invert as Invert, + Is as Is, + IsNot as IsNot, + JoinedStr as JoinedStr, + Lambda as Lambda, + List as List, + ListComp as ListComp, + Load as Load, + LShift as LShift, + Lt as Lt, + LtE as LtE, + Match as Match, + MatchAs as MatchAs, + MatchClass as MatchClass, + MatchMapping as MatchMapping, + MatchOr as MatchOr, + MatchSequence as MatchSequence, + MatchSingleton as MatchSingleton, + MatchStar as MatchStar, + MatchValue as MatchValue, + MatMult as MatMult, + Mod as Mod, + Module as Module, + Mult as Mult, + Name as Name, + NamedExpr as NamedExpr, + Nonlocal as Nonlocal, + Not as Not, + NotEq as NotEq, + NotIn as NotIn, + Or as Or, + Pass as Pass, + Pow as Pow, + Raise as Raise, + Return as Return, + RShift as RShift, + Set as Set, + SetComp as SetComp, + Slice as Slice, + Starred as Starred, + Store as Store, + Sub as Sub, + Subscript as Subscript, + Try as Try, + Tuple as Tuple, + TypeIgnore as TypeIgnore, + UAdd as UAdd, + UnaryOp as UnaryOp, + USub as USub, + While as While, + With as With, + Yield as Yield, + YieldFrom as YieldFrom, + alias as alias, + arg as arg, + arguments as arguments, + boolop as boolop, + cmpop as cmpop, + comprehension as comprehension, + excepthandler as excepthandler, + expr as expr, + expr_context as expr_context, + keyword as keyword, + match_case as match_case, + mod as mod, + operator as operator, + pattern as pattern, + stmt as stmt, + type_ignore as type_ignore, + unaryop as unaryop, + withitem as withitem, +) +from typing import Final + +if sys.version_info >= (3, 12): + from ast import ( + ParamSpec as ParamSpec, + TypeAlias as TypeAlias, + TypeVar as TypeVar, + TypeVarTuple as TypeVarTuple, + type_param as type_param, + ) + +if sys.version_info >= (3, 11): + from ast import TryStar as TryStar + +PyCF_ALLOW_TOP_LEVEL_AWAIT: Final = 8192 +PyCF_ONLY_AST: Final = 1024 +PyCF_TYPE_COMMENTS: Final = 4096 + +if sys.version_info >= (3, 13): + PyCF_OPTIMIZED_AST: Final = 33792 diff --git a/stdlib/_asyncio.pyi b/stdlib/_asyncio.pyi new file mode 100644 index 000000000000..641c152d985b --- /dev/null +++ b/stdlib/_asyncio.pyi @@ -0,0 +1,114 @@ +import sys +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable, Coroutine, Generator +from contextvars import Context +from types import FrameType, GenericAlias +from typing import Any, Literal, TextIO, TypeAlias, TypeVar +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_TaskYieldType: TypeAlias = Future[object] | None + +@disjoint_base +class Future(Awaitable[_T]): + _state: str + @property + def _exception(self) -> BaseException | None: ... + _blocking: bool + + @property + def _log_traceback(self) -> bool: ... + @_log_traceback.setter + def _log_traceback(self, val: Literal[False]) -> None: ... + + _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` + def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... + def __del__(self) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + @property + def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... + def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: ... + def cancel(self, msg: Any | None = None) -> bool: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def result(self) -> _T: ... + def exception(self) -> BaseException | None: ... + def remove_done_callback(self, fn: Callable[[Self], object], /) -> int: ... + def set_result(self, result: _T, /) -> None: ... + def set_exception(self, exception: type | BaseException, /) -> None: ... + def __iter__(self) -> Generator[Any, None, _T]: ... + def __await__(self) -> Generator[Any, None, _T]: ... + @property + def _loop(self) -> AbstractEventLoop: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 12): + _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] +else: + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] + +# mypy and pyright complain that a subclass of an invariant class shouldn't be covariant. +# While this is true in general, here it's sort-of okay to have a covariant subclass, +# since the only reason why `asyncio.Future` is invariant is the `set_result()` method, +# and `asyncio.Task.set_result()` always raises. +@disjoint_base +class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] # pyrefly: ignore [invalid-variance] + if sys.version_info >= (3, 12): + def __init__( + self, + coro: _TaskCompatibleCoro[_T_co], + *, + loop: AbstractEventLoop | None = None, + name: str | None = None, + context: Context | None = None, + eager_start: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + coro: _TaskCompatibleCoro[_T_co], + *, + loop: AbstractEventLoop | None = None, + name: str | None = None, + context: Context | None = None, + ) -> None: ... + else: + def __init__( + self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | None = None + ) -> None: ... + + if sys.version_info >= (3, 12): + def get_coro(self) -> _TaskCompatibleCoro[_T_co] | None: ... + else: + def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ... + + def get_name(self) -> str: ... + def set_name(self, value: object, /) -> None: ... + if sys.version_info >= (3, 12): + def get_context(self) -> Context: ... + + def get_stack(self, *, limit: int | None = None) -> list[FrameType]: ... + def print_stack(self, *, limit: int | None = None, file: TextIO | None = None) -> None: ... + if sys.version_info >= (3, 11): + def cancelling(self) -> int: ... + def uncancel(self) -> int: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def get_event_loop() -> AbstractEventLoop: ... +def get_running_loop() -> AbstractEventLoop: ... +def _set_running_loop(loop: AbstractEventLoop | None, /) -> None: ... +def _get_running_loop() -> AbstractEventLoop | None: ... +def _register_task(task: Task[Any]) -> None: ... +def _unregister_task(task: Task[Any]) -> None: ... +def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... +def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... + +if sys.version_info >= (3, 12): + def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... + +if sys.version_info >= (3, 14): + def future_discard_from_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... + def future_add_to_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ... + def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... diff --git a/stdlib/_bisect.pyi b/stdlib/_bisect.pyi new file mode 100644 index 000000000000..b87dd8f3fb87 --- /dev/null +++ b/stdlib/_bisect.pyi @@ -0,0 +1,103 @@ +from _typeshed import SupportsGetItem, SupportsLenAndGetItem, SupportsRichComparisonT +from collections.abc import Callable, MutableSequence +from typing import TypeVar, overload + +_T = TypeVar("_T") + +@overload +def bisect_left( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... + +@overload +def bisect_right( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... + +@overload +def insort_left( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_left( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... + +@overload +def insort_right( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_right( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... diff --git a/stdlib/_blake2.pyi b/stdlib/_blake2.pyi new file mode 100644 index 000000000000..a6c3869fb851 --- /dev/null +++ b/stdlib/_blake2.pyi @@ -0,0 +1,119 @@ +import sys +from _typeshed import ReadableBuffer +from typing import ClassVar, Final, final +from typing_extensions import Self + +BLAKE2B_MAX_DIGEST_SIZE: Final = 64 +BLAKE2B_MAX_KEY_SIZE: Final = 64 +BLAKE2B_PERSON_SIZE: Final = 16 +BLAKE2B_SALT_SIZE: Final = 16 +BLAKE2S_MAX_DIGEST_SIZE: Final = 32 +BLAKE2S_MAX_KEY_SIZE: Final = 32 +BLAKE2S_PERSON_SIZE: Final = 8 +BLAKE2S_SALT_SIZE: Final = 8 + +@final +class blake2b: + MAX_DIGEST_SIZE: ClassVar[int] = 64 + MAX_KEY_SIZE: ClassVar[int] = 64 + PERSON_SIZE: ClassVar[int] = 16 + SALT_SIZE: ClassVar[int] = 16 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 13): + def __new__( + cls, + data: ReadableBuffer = b"", + *, + digest_size: int = 64, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + string: ReadableBuffer | None = None, + ) -> Self: ... + else: + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 64, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... + +@final +class blake2s: + MAX_DIGEST_SIZE: ClassVar[int] = 32 + MAX_KEY_SIZE: ClassVar[int] = 32 + PERSON_SIZE: ClassVar[int] = 8 + SALT_SIZE: ClassVar[int] = 8 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 13): + def __new__( + cls, + data: ReadableBuffer = b"", + *, + digest_size: int = 32, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + string: ReadableBuffer | None = None, + ) -> Self: ... + else: + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 32, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... diff --git a/stdlib/_bz2.pyi b/stdlib/_bz2.pyi new file mode 100644 index 000000000000..fdad932ca22e --- /dev/null +++ b/stdlib/_bz2.pyi @@ -0,0 +1,24 @@ +import sys +from _typeshed import ReadableBuffer +from typing import final +from typing_extensions import Self + +@final +class BZ2Compressor: + if sys.version_info >= (3, 12): + def __new__(cls, compresslevel: int = 9, /) -> Self: ... + else: + def __init__(self, compresslevel: int = 9, /) -> None: ... + + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self) -> bytes: ... + +@final +class BZ2Decompressor: + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def eof(self) -> bool: ... + @property + def needs_input(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... diff --git a/stdlib/_codecs.pyi b/stdlib/_codecs.pyi new file mode 100644 index 000000000000..38cf857d0569 --- /dev/null +++ b/stdlib/_codecs.pyi @@ -0,0 +1,122 @@ +import codecs +import sys +from _typeshed import ReadableBuffer +from collections.abc import Callable +from typing import Literal, TypeAlias, final, overload, type_check_only + +# This type is not exposed; it is defined in unicodeobject.c +# At runtime it calls itself builtins.EncodingMap +@final +@type_check_only +class _EncodingMap: + def size(self) -> int: ... + +_CharMap: TypeAlias = dict[int, int] | _EncodingMap +_Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] +_SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] + +def register(search_function: _SearchFunction, /) -> None: ... +def unregister(search_function: _SearchFunction, /) -> None: ... +def register_error(errors: str, handler: _Handler, /) -> None: ... +def lookup_error(name: str, /) -> _Handler: ... + +# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 +# https://docs.python.org/3/library/codecs.html#binary-transforms +_BytesToBytesEncoding: TypeAlias = Literal[ + "base64", + "base_64", + "base64_codec", + "bz2", + "bz2_codec", + "hex", + "hex_codec", + "quopri", + "quotedprintable", + "quoted_printable", + "quopri_codec", + "uu", + "uu_codec", + "zip", + "zlib", + "zlib_codec", +] +# https://docs.python.org/3/library/codecs.html#text-transforms +_StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] + +@overload +def encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: ... +@overload +def encode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str: ... # type: ignore[overload-overlap] +@overload +def encode(obj: str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... + +@overload +def decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: ... # type: ignore[overload-overlap] +@overload +def decode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str: ... + +# these are documented as text encodings but in practice they also accept str as input +@overload +def decode( + obj: str, + encoding: Literal["unicode_escape", "unicode-escape", "raw_unicode_escape", "raw-unicode-escape"], + errors: str = "strict", +) -> str: ... + +# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str +@overload +def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = "strict") -> bytes: ... +@overload +def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... + +def lookup(encoding: str, /) -> codecs.CodecInfo: ... +def charmap_build(map: str, /) -> _CharMap: ... +def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def ascii_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def charmap_decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ... +def charmap_encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ... + +# Docs say this accepts a bytes-like object, but in practice it also accepts str. +def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... +def escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ... +def latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... +def latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def raw_unicode_escape_decode( + data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / +) -> tuple[str, int]: ... +def raw_unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def readbuffer_encode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... +def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... +def unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_16_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... +def utf_16_ex_decode( + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / +) -> tuple[str, int, int]: ... +def utf_16_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_16_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_32_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ... +def utf_32_ex_decode( + data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, / +) -> tuple[str, int, int]: ... +def utf_32_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_32_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_7_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_7_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... +def utf_8_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... +def utf_8_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +if sys.platform == "win32": + def mbcs_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def mbcs_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + def code_page_decode( + codepage: int, data: ReadableBuffer, errors: str | None = None, final: bool = False, / + ) -> tuple[str, int]: ... + def code_page_encode(code_page: int, str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + def oem_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + def oem_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... diff --git a/stdlib/_collections_abc.pyi b/stdlib/_collections_abc.pyi new file mode 100644 index 000000000000..6fc32078532e --- /dev/null +++ b/stdlib/_collections_abc.pyi @@ -0,0 +1,105 @@ +import sys +from abc import abstractmethod +from types import MappingProxyType +from typing import ( # noqa: Y022,Y038,UP035,Y057 + AbstractSet as Set, + AsyncGenerator as AsyncGenerator, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + ByteString as ByteString, + Callable as Callable, + ClassVar, + Collection as Collection, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Generic, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Protocol, + Reversible as Reversible, + Sequence as Sequence, + Sized as Sized, + TypeVar, + ValuesView as ValuesView, + final, + runtime_checkable, +) + +__all__ = [ + "Awaitable", + "Coroutine", + "AsyncIterable", + "AsyncIterator", + "AsyncGenerator", + "Hashable", + "Iterable", + "Iterator", + "Generator", + "Reversible", + "Sized", + "Container", + "Callable", + "Collection", + "Set", + "MutableSet", + "Mapping", + "MutableMapping", + "MappingView", + "KeysView", + "ItemsView", + "ValuesView", + "Sequence", + "MutableSequence", +] +if sys.version_info < (3, 15): + __all__ += ["ByteString"] +if sys.version_info >= (3, 12): + __all__ += ["Buffer"] + +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. + +@final +class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[_KT_co]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + +@final +class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented + def __reversed__(self) -> Iterator[_VT_co]: ... + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + +@final +class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + +if sys.version_info >= (3, 12): + @runtime_checkable + class Buffer(Protocol): + __slots__ = () + @abstractmethod + def __buffer__(self, flags: int, /) -> memoryview: ... diff --git a/stdlib/_compat_pickle.pyi b/stdlib/_compat_pickle.pyi new file mode 100644 index 000000000000..32c0b542d991 --- /dev/null +++ b/stdlib/_compat_pickle.pyi @@ -0,0 +1,10 @@ +from typing import Final + +IMPORT_MAPPING: Final[dict[str, str]] +NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]] +PYTHON2_EXCEPTIONS: Final[tuple[str, ...]] +MULTIPROCESSING_EXCEPTIONS: Final[tuple[str, ...]] +REVERSE_IMPORT_MAPPING: Final[dict[str, str]] +REVERSE_NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]] +PYTHON3_OSERROR_EXCEPTIONS: Final[tuple[str, ...]] +PYTHON3_IMPORTERROR_EXCEPTIONS: Final[tuple[str, ...]] diff --git a/stdlib/_compression.pyi b/stdlib/_compression.pyi new file mode 100644 index 000000000000..6015bcb13f1c --- /dev/null +++ b/stdlib/_compression.pyi @@ -0,0 +1,39 @@ +# _compression is replaced by compression._common._streams on Python 3.14+ (PEP-784) + +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Protocol, type_check_only + +BUFFER_SIZE = DEFAULT_BUFFER_SIZE + +@type_check_only +class _Reader(Protocol): + def read(self, n: int, /) -> bytes: ... + def seekable(self) -> bool: ... + def seek(self, n: int, /) -> Any: ... + +@type_check_only +class _Decompressor(Protocol): + def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def eof(self) -> bool: ... + # `zlib._Decompress` does not have next property, but `DecompressReader` calls it: + # @property + # def needs_input(self) -> bool: ... + +class BaseStream(BufferedIOBase): ... + +class DecompressReader(RawIOBase): + def __init__( + self, + fp: _Reader, + decomp_factory: Callable[..., _Decompressor], + trailing_error: type[Exception] | tuple[type[Exception], ...] = (), + **decomp_args: Any, # These are passed to decomp_factory. + ) -> None: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... diff --git a/stdlib/_contextvars.pyi b/stdlib/_contextvars.pyi new file mode 100644 index 000000000000..56440884a150 --- /dev/null +++ b/stdlib/_contextvars.pyi @@ -0,0 +1,69 @@ +import sys +from collections.abc import Callable, Iterator, Mapping +from types import GenericAlias, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self + +_T = TypeVar("_T") +_D = TypeVar("_D") +_P = ParamSpec("_P") + +@final +class ContextVar(Generic[_T]): + @overload + def __new__(cls, name: str) -> Self: ... + @overload + def __new__(cls, name: str, *, default: _T) -> Self: ... + + def __hash__(self) -> int: ... + @property + def name(self) -> str: ... + + @overload + def get(self) -> _T: ... + @overload + def get(self, default: _T, /) -> _T: ... + @overload + def get(self, default: _D, /) -> _D | _T: ... + + def set(self, value: _T, /) -> Token[_T]: ... + def reset(self, token: Token[_T], /) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Token(Generic[_T]): + @property + def var(self) -> ContextVar[_T]: ... + @property + def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express + MISSING: ClassVar[object] + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 14): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +def copy_context() -> Context: ... + +# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have +# a different value. +@final +class Context(Mapping[ContextVar[Any], Any]): + def __init__(self) -> None: ... + + @overload + def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ... + @overload + def get(self, key: ContextVar[_T], default: _T, /) -> _T: ... + @overload + def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... + + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... + def copy(self) -> Context: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __getitem__(self, key: ContextVar[_T], /) -> _T: ... + def __iter__(self) -> Iterator[ContextVar[Any]]: ... + def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... diff --git a/stdlib/_csv.pyi b/stdlib/_csv.pyi new file mode 100644 index 000000000000..d3702be78c3d --- /dev/null +++ b/stdlib/_csv.pyi @@ -0,0 +1,116 @@ +import csv +import sys +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import Any, Final, Literal, TypeAlias +from typing_extensions import Self, disjoint_base + +__version__: Final[str] + +QUOTE_ALL: Final = 1 +QUOTE_MINIMAL: Final = 0 +QUOTE_NONE: Final = 3 +QUOTE_NONNUMERIC: Final = 2 +if sys.version_info >= (3, 12): + QUOTE_STRINGS: Final = 4 + QUOTE_NOTNULL: Final = 5 + +if sys.version_info >= (3, 12): + _QuotingType: TypeAlias = Literal[0, 1, 2, 3, 4, 5] +else: + _QuotingType: TypeAlias = Literal[0, 1, 2, 3] + +class Error(Exception): ... + +_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect] + +@disjoint_base +class Dialect: + delimiter: str + quotechar: str | None + escapechar: str | None + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: _QuotingType + strict: bool + def __new__( + cls, + dialect: _DialectLike | None = None, + delimiter: str = ",", + doublequote: bool = True, + escapechar: str | None = None, + lineterminator: str = "\r\n", + quotechar: str | None = '"', + quoting: _QuotingType = 0, + skipinitialspace: bool = False, + strict: bool = False, + ) -> Self: ... + +# This class calls itself _csv.reader. +@disjoint_base +class Reader: + @property + def dialect(self) -> Dialect: ... + line_num: int + def __iter__(self) -> Self: ... + def __next__(self) -> list[str]: ... + +# This class calls itself _csv.writer. +@disjoint_base +class Writer: + @property + def dialect(self) -> Dialect: ... + if sys.version_info >= (3, 13): + def writerow(self, row: Iterable[Any], /) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: ... + else: + def writerow(self, row: Iterable[Any]) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... + +def writer( + fileobj: SupportsWrite[str], + /, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> Writer: ... +def reader( + iterable: Iterable[str], + /, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> Reader: ... +def register_dialect( + name: str, + /, + dialect: type[Dialect | csv.Dialect] | str = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, +) -> None: ... +def unregister_dialect(name: str) -> None: ... +def get_dialect(name: str) -> Dialect: ... +def list_dialects() -> list[str]: ... +def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/stdlib/_ctypes.pyi b/stdlib/_ctypes.pyi new file mode 100644 index 000000000000..83ac60fd0d42 --- /dev/null +++ b/stdlib/_ctypes.pyi @@ -0,0 +1,380 @@ +import _typeshed +import builtins +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from abc import abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from ctypes import CDLL, ArgumentError as ArgumentError, c_void_p +from types import GenericAlias +from typing import Any, ClassVar, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self + +_T = TypeVar("_T") +_CT = TypeVar("_CT", bound=_CData) + +FUNCFLAG_CDECL: Final = 0x1 +FUNCFLAG_PYTHONAPI: Final = 0x4 +FUNCFLAG_USE_ERRNO: Final = 0x8 +FUNCFLAG_USE_LASTERROR: Final = 0x10 +RTLD_GLOBAL: Final[int] +RTLD_LOCAL: Final[int] + +if sys.version_info >= (3, 11): + CTYPES_MAX_ARGCOUNT: Final[int] + +if sys.version_info >= (3, 12): + SIZEOF_TIME_T: Final[int] + +if sys.platform == "win32": + # Description, Source, HelpFile, HelpContext, scode + _COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None] + + class COMError(Exception): + hresult: int + text: str | None + details: _COMError_Details + + def __init__(self, hresult: int, text: str | None, details: _COMError_Details) -> None: ... + + def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: ... + + FUNCFLAG_HRESULT: Final = 0x2 + FUNCFLAG_STDCALL: Final = 0x0 + + def FormatError(code: int = ...) -> str: ... + def get_last_error() -> int: ... + def set_last_error(value: int) -> int: ... + def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ... + def FreeLibrary(handle: int, /) -> None: ... + +else: + def dlclose(handle: int, /) -> None: ... + # The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent. + def dlopen(name: StrOrBytesPath, flag: int = ..., /) -> int: ... + def dlsym(handle: int, name: str, /) -> int: ... + +if sys.version_info >= (3, 13): + # This class is not exposed. It calls itself _ctypes.CType_Type. + @type_check_only + class _CType_Type(type): + # By default mypy complains about the following two methods, because strictly speaking cls + # might not be a Type[_CT]. However this doesn't happen because this is only a + # metaclass for subclasses of _CData. + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + + _CTypeBaseType = _CType_Type + +else: + _CTypeBaseType = type + +# This class is not exposed. +@type_check_only +class _CData: + _b_base_: int + _b_needsfree_: bool + _objects: Mapping[Any, int] | None + def __buffer__(self, flags: int, /) -> memoryview: ... + def __ctypes_from_outparam__(self, /) -> Self: ... + if sys.version_info >= (3, 14): + __pointer_type__: type + +# this is a union of all the subclasses of _CData, which is useful because of +# the methods that are present on each of those subclasses which are not present +# on _CData itself. +_CDataType: TypeAlias = _SimpleCData[Any] | _Pointer[Any] | CFuncPtr | Union | Structure | Array[Any] + +# This class is not exposed. It calls itself _ctypes.PyCSimpleType. +@type_check_only +class _PyCSimpleType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType): + value: _T + # The TypeVar can be unsolved here, + # but we can't use overloads without creating many, many mypy false-positive errors + def __init__(self, value: _T = ...) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] + def __ctypes_from_outparam__(self, /) -> _T: ... # type: ignore[override] + +@type_check_only +class _CanCastTo(_CData): ... + +@type_check_only +class _PointerLike(_CanCastTo): ... + +# This type is not exposed. It calls itself _ctypes.PyCPointerType. +@type_check_only +class _PyCPointerType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + def set_type(self, type: _CTypeBaseType, /) -> None: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): + _type_: type[_CT] + contents: _CT + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, arg: _CT) -> None: ... + + @overload + def __getitem__(self, key: int, /) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + + def __setitem__(self, key: int, value: Any, /) -> None: ... + +if sys.version_info < (3, 14): + @overload + def POINTER(type: None, /) -> type[c_void_p]: ... + @overload + def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ... + + def pointer(obj: _CT, /) -> _Pointer[_CT]: ... + +# This class is not exposed. It calls itself _ctypes.CArgObject. +@final +@type_check_only +class _CArgObject: ... + +if sys.version_info >= (3, 14): + def byref(obj: _CData | _CDataType, offset: int = 0, /) -> _CArgObject: ... + +else: + def byref(obj: _CData | _CDataType, offset: int = 0) -> _CArgObject: ... + +_ECT: TypeAlias = Callable[[_CData | _CDataType | None, CFuncPtr, tuple[_CData | _CDataType, ...]], _CDataType] +_PF: TypeAlias = tuple[int] | tuple[int, str | None] | tuple[int, str | None, Any] + +# This class is not exposed. It calls itself _ctypes.PyCFuncPtrType. +@type_check_only +class _PyCFuncPtrType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): + restype: type[_CDataType] | Callable[[int], Any] | None + argtypes: Sequence[type[_CDataType]] + errcheck: _ECT + # Abstract attribute that must be defined on subclasses + _flags_: ClassVar[int] + + @overload + def __new__(cls) -> Self: ... + @overload + def __new__(cls, address: int, /) -> Self: ... + @overload + def __new__(cls, callable: Callable[..., Any], /) -> Self: ... + @overload + def __new__(cls, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] | None = ..., /) -> Self: ... + if sys.platform == "win32": + @overload + def __new__( + cls, vtbl_index: int, name: str, paramflags: tuple[_PF, ...] | None = ..., iid: _CData | _CDataType | None = ..., / + ) -> Self: ... + + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +_GetT = TypeVar("_GetT") +_SetT = TypeVar("_SetT") + +if sys.version_info >= (3, 14): + @final + class CField(Generic[_CT, _GetT, _SetT]): + offset: int + size: int + name: str + type: builtins.type[_CT] + byte_offset: int + byte_size: int + is_bitfield: bool + bit_offset: int + bit_size: int + is_anonymous: bool + + @overload + def __get__(self, instance: None, owner: builtins.type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: builtins.type[Any] | None = None, /) -> _GetT: ... + + def __set__(self, instance: Any, value: _SetT, /) -> None: ... + + _CField = CField + +else: + @final + @type_check_only + class _CField(Generic[_CT, _GetT, _SetT]): + offset: int + size: int + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ... + + def __set__(self, instance: Any, value: _SetT, /) -> None: ... + +# This class is not exposed. It calls itself _ctypes.UnionType. +@type_check_only +class _UnionType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + # At runtime, various attributes are created on a Union subclass based + # on its _fields_. This method doesn't exist, but represents those + # dynamically created attributes. + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Union(_CData, metaclass=_UnionType): + _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] + _pack_: ClassVar[int] + _anonymous_: ClassVar[Sequence[str]] + if sys.version_info >= (3, 13): + _align_: ClassVar[int] + + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +# This class is not exposed. It calls itself _ctypes.PyCStructType. +@type_check_only +class _PyCStructType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + # At runtime, various attributes are created on a Structure subclass based + # on its _fields_. This method doesn't exist, but represents those + # dynamically created attributes. + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Structure(_CData, metaclass=_PyCStructType): + _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]] + _pack_: ClassVar[int] + _anonymous_: ClassVar[Sequence[str]] + if sys.version_info >= (3, 13): + _align_: ClassVar[int] + + if sys.version_info >= (3, 14): + # _layout_ can be defined by the user, but is not always present. + _layout_: ClassVar[Literal["ms", "gcc-sysv"]] + + def __init__(self, *args: Any, **kw: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +# This class is not exposed. It calls itself _ctypes.PyCArrayType. +@type_check_only +class _PyCArrayType(_CTypeBaseType): + def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ... + def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ... + def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ... + def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ... + if sys.version_info < (3, 13): + # Inherited from CType_Type starting on 3.13 + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + +class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): + @property + @abstractmethod + def _length_(self) -> int: ... + @_length_.setter + def _length_(self, value: int) -> None: ... + + @property + @abstractmethod + def _type_(self) -> type[_CT]: ... + @_type_.setter + def _type_(self, value: type[_CT]) -> None: ... + + # Note: only available if _CT == c_char + @property + def raw(self) -> bytes: ... + @raw.setter + def raw(self, value: ReadableBuffer) -> None: ... + + value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise + # TODO: These methods cannot be annotated correctly at the moment. + # All of these "Any"s stand for the array's element type, but it's not possible to use _CT + # here, because of a special feature of ctypes. + # By default, when accessing an element of an Array[_CT], the returned object has type _CT. + # However, when _CT is a "simple type" like c_int, ctypes automatically "unboxes" the object + # and converts it to the corresponding Python primitive. For example, when accessing an element + # of an Array[c_int], a Python int object is returned, not a c_int. + # This behavior does *not* apply to subclasses of "simple types". + # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns + # a MyInt, not an int. + # This special behavior is not easy to model in a stub, so for now all places where + # the array element type would belong are annotated with Any instead. + def __init__(self, *args: Any) -> None: ... + + @overload + def __getitem__(self, key: int, /) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + + @overload + def __setitem__(self, key: int, value: Any, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Any], /) -> None: ... + + def __iter__(self) -> Iterator[Any]: ... + # Can't inherit from Sized because the metaclass conflict between + # Sized and _CData prevents using _CDataMeta. + def __len__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def addressof(obj: _CData | _CDataType, /) -> int: ... +def alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ... +def get_errno() -> int: ... +def resize(obj: _CData | _CDataType, size: int, /) -> None: ... +def set_errno(value: int, /) -> int: ... +def sizeof(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ... +def PyObj_FromPtr(address: int, /) -> Any: ... +def Py_DECREF(o: _T, /) -> _T: ... +def Py_INCREF(o: _T, /) -> _T: ... +def buffer_info(o: _CData | _CDataType | type[_CData | _CDataType], /) -> tuple[str, int, tuple[int, ...]]: ... +def call_cdeclfunction(address: int, arguments: tuple[Any, ...], /) -> Any: ... +def call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ... + +# dllist() is available on Linux and other platforms like NetBSD +if sys.version_info >= (3, 14) and sys.platform != "win32" and sys.platform != "darwin": + # Added in Python 3.14.7 + def dllist() -> list[str]: ... diff --git a/stdlib/_curses.pyi b/stdlib/_curses.pyi new file mode 100644 index 000000000000..fcd0da4c465c --- /dev/null +++ b/stdlib/_curses.pyi @@ -0,0 +1,583 @@ +import sys +from _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite +from curses import _ncurses_version +from typing import Any, Final, TypeAlias, final, overload + +# NOTE: This module is ordinarily only available on Unix, but the windows-curses +# package makes it available on Windows as well with the same contents. + +# Handled by PyCurses_ConvertToChtype in _cursesmodule.c. +_ChType: TypeAlias = str | bytes | int + +# ACS codes are only initialized after initscr is called +ACS_BBSS: Final[int] +ACS_BLOCK: Final[int] +ACS_BOARD: Final[int] +ACS_BSBS: Final[int] +ACS_BSSB: Final[int] +ACS_BSSS: Final[int] +ACS_BTEE: Final[int] +ACS_BULLET: Final[int] +ACS_CKBOARD: Final[int] +ACS_DARROW: Final[int] +ACS_DEGREE: Final[int] +ACS_DIAMOND: Final[int] +ACS_GEQUAL: Final[int] +ACS_HLINE: Final[int] +ACS_LANTERN: Final[int] +ACS_LARROW: Final[int] +ACS_LEQUAL: Final[int] +ACS_LLCORNER: Final[int] +ACS_LRCORNER: Final[int] +ACS_LTEE: Final[int] +ACS_NEQUAL: Final[int] +ACS_PI: Final[int] +ACS_PLMINUS: Final[int] +ACS_PLUS: Final[int] +ACS_RARROW: Final[int] +ACS_RTEE: Final[int] +ACS_S1: Final[int] +ACS_S3: Final[int] +ACS_S7: Final[int] +ACS_S9: Final[int] +ACS_SBBS: Final[int] +ACS_SBSB: Final[int] +ACS_SBSS: Final[int] +ACS_SSBB: Final[int] +ACS_SSBS: Final[int] +ACS_SSSB: Final[int] +ACS_SSSS: Final[int] +ACS_STERLING: Final[int] +ACS_TTEE: Final[int] +ACS_UARROW: Final[int] +ACS_ULCORNER: Final[int] +ACS_URCORNER: Final[int] +ACS_VLINE: Final[int] +ALL_MOUSE_EVENTS: Final[int] +A_ALTCHARSET: Final[int] +A_ATTRIBUTES: Final[int] +A_BLINK: Final[int] +A_BOLD: Final[int] +A_CHARTEXT: Final[int] +A_COLOR: Final[int] +A_DIM: Final[int] +A_HORIZONTAL: Final[int] +A_INVIS: Final[int] +A_ITALIC: Final[int] +A_LEFT: Final[int] +A_LOW: Final[int] +A_NORMAL: Final[int] +A_PROTECT: Final[int] +A_REVERSE: Final[int] +A_RIGHT: Final[int] +A_STANDOUT: Final[int] +A_TOP: Final[int] +A_UNDERLINE: Final[int] +A_VERTICAL: Final[int] +BUTTON1_CLICKED: Final[int] +BUTTON1_DOUBLE_CLICKED: Final[int] +BUTTON1_PRESSED: Final[int] +BUTTON1_RELEASED: Final[int] +BUTTON1_TRIPLE_CLICKED: Final[int] +BUTTON2_CLICKED: Final[int] +BUTTON2_DOUBLE_CLICKED: Final[int] +BUTTON2_PRESSED: Final[int] +BUTTON2_RELEASED: Final[int] +BUTTON2_TRIPLE_CLICKED: Final[int] +BUTTON3_CLICKED: Final[int] +BUTTON3_DOUBLE_CLICKED: Final[int] +BUTTON3_PRESSED: Final[int] +BUTTON3_RELEASED: Final[int] +BUTTON3_TRIPLE_CLICKED: Final[int] +BUTTON4_CLICKED: Final[int] +BUTTON4_DOUBLE_CLICKED: Final[int] +BUTTON4_PRESSED: Final[int] +BUTTON4_RELEASED: Final[int] +BUTTON4_TRIPLE_CLICKED: Final[int] +# Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3 +if sys.version_info >= (3, 12) or sys.platform != "darwin": + BUTTON5_PRESSED: Final[int] + BUTTON5_RELEASED: Final[int] + BUTTON5_CLICKED: Final[int] + BUTTON5_DOUBLE_CLICKED: Final[int] + BUTTON5_TRIPLE_CLICKED: Final[int] +BUTTON_ALT: Final[int] +BUTTON_CTRL: Final[int] +BUTTON_SHIFT: Final[int] +COLOR_BLACK: Final[int] +COLOR_BLUE: Final[int] +COLOR_CYAN: Final[int] +COLOR_GREEN: Final[int] +COLOR_MAGENTA: Final[int] +COLOR_RED: Final[int] +COLOR_WHITE: Final[int] +COLOR_YELLOW: Final[int] +ERR: Final[int] +KEY_A1: Final[int] +KEY_A3: Final[int] +KEY_B2: Final[int] +KEY_BACKSPACE: Final[int] +KEY_BEG: Final[int] +KEY_BREAK: Final[int] +KEY_BTAB: Final[int] +KEY_C1: Final[int] +KEY_C3: Final[int] +KEY_CANCEL: Final[int] +KEY_CATAB: Final[int] +KEY_CLEAR: Final[int] +KEY_CLOSE: Final[int] +KEY_COMMAND: Final[int] +KEY_COPY: Final[int] +KEY_CREATE: Final[int] +KEY_CTAB: Final[int] +KEY_DC: Final[int] +KEY_DL: Final[int] +KEY_DOWN: Final[int] +KEY_EIC: Final[int] +KEY_END: Final[int] +KEY_ENTER: Final[int] +KEY_EOL: Final[int] +KEY_EOS: Final[int] +KEY_EXIT: Final[int] +KEY_F0: Final[int] +KEY_F1: Final[int] +KEY_F10: Final[int] +KEY_F11: Final[int] +KEY_F12: Final[int] +KEY_F13: Final[int] +KEY_F14: Final[int] +KEY_F15: Final[int] +KEY_F16: Final[int] +KEY_F17: Final[int] +KEY_F18: Final[int] +KEY_F19: Final[int] +KEY_F2: Final[int] +KEY_F20: Final[int] +KEY_F21: Final[int] +KEY_F22: Final[int] +KEY_F23: Final[int] +KEY_F24: Final[int] +KEY_F25: Final[int] +KEY_F26: Final[int] +KEY_F27: Final[int] +KEY_F28: Final[int] +KEY_F29: Final[int] +KEY_F3: Final[int] +KEY_F30: Final[int] +KEY_F31: Final[int] +KEY_F32: Final[int] +KEY_F33: Final[int] +KEY_F34: Final[int] +KEY_F35: Final[int] +KEY_F36: Final[int] +KEY_F37: Final[int] +KEY_F38: Final[int] +KEY_F39: Final[int] +KEY_F4: Final[int] +KEY_F40: Final[int] +KEY_F41: Final[int] +KEY_F42: Final[int] +KEY_F43: Final[int] +KEY_F44: Final[int] +KEY_F45: Final[int] +KEY_F46: Final[int] +KEY_F47: Final[int] +KEY_F48: Final[int] +KEY_F49: Final[int] +KEY_F5: Final[int] +KEY_F50: Final[int] +KEY_F51: Final[int] +KEY_F52: Final[int] +KEY_F53: Final[int] +KEY_F54: Final[int] +KEY_F55: Final[int] +KEY_F56: Final[int] +KEY_F57: Final[int] +KEY_F58: Final[int] +KEY_F59: Final[int] +KEY_F6: Final[int] +KEY_F60: Final[int] +KEY_F61: Final[int] +KEY_F62: Final[int] +KEY_F63: Final[int] +KEY_F7: Final[int] +KEY_F8: Final[int] +KEY_F9: Final[int] +KEY_FIND: Final[int] +KEY_HELP: Final[int] +KEY_HOME: Final[int] +KEY_IC: Final[int] +KEY_IL: Final[int] +KEY_LEFT: Final[int] +KEY_LL: Final[int] +KEY_MARK: Final[int] +KEY_MAX: Final[int] +KEY_MESSAGE: Final[int] +KEY_MIN: Final[int] +KEY_MOUSE: Final[int] +KEY_MOVE: Final[int] +KEY_NEXT: Final[int] +KEY_NPAGE: Final[int] +KEY_OPEN: Final[int] +KEY_OPTIONS: Final[int] +KEY_PPAGE: Final[int] +KEY_PREVIOUS: Final[int] +KEY_PRINT: Final[int] +KEY_REDO: Final[int] +KEY_REFERENCE: Final[int] +KEY_REFRESH: Final[int] +KEY_REPLACE: Final[int] +KEY_RESET: Final[int] +KEY_RESIZE: Final[int] +KEY_RESTART: Final[int] +KEY_RESUME: Final[int] +KEY_RIGHT: Final[int] +KEY_SAVE: Final[int] +KEY_SBEG: Final[int] +KEY_SCANCEL: Final[int] +KEY_SCOMMAND: Final[int] +KEY_SCOPY: Final[int] +KEY_SCREATE: Final[int] +KEY_SDC: Final[int] +KEY_SDL: Final[int] +KEY_SELECT: Final[int] +KEY_SEND: Final[int] +KEY_SEOL: Final[int] +KEY_SEXIT: Final[int] +KEY_SF: Final[int] +KEY_SFIND: Final[int] +KEY_SHELP: Final[int] +KEY_SHOME: Final[int] +KEY_SIC: Final[int] +KEY_SLEFT: Final[int] +KEY_SMESSAGE: Final[int] +KEY_SMOVE: Final[int] +KEY_SNEXT: Final[int] +KEY_SOPTIONS: Final[int] +KEY_SPREVIOUS: Final[int] +KEY_SPRINT: Final[int] +KEY_SR: Final[int] +KEY_SREDO: Final[int] +KEY_SREPLACE: Final[int] +KEY_SRESET: Final[int] +KEY_SRIGHT: Final[int] +KEY_SRSUME: Final[int] +KEY_SSAVE: Final[int] +KEY_SSUSPEND: Final[int] +KEY_STAB: Final[int] +KEY_SUNDO: Final[int] +KEY_SUSPEND: Final[int] +KEY_UNDO: Final[int] +KEY_UP: Final[int] +OK: Final[int] +REPORT_MOUSE_POSITION: Final[int] +_C_API: Any +version: Final[bytes] + +def baudrate() -> int: ... +def beep() -> None: ... +def can_change_color() -> bool: ... +def cbreak(flag: bool = True, /) -> None: ... +def color_content(color_number: int, /) -> tuple[int, int, int]: ... +def color_pair(pair_number: int, /) -> int: ... +def curs_set(visibility: int, /) -> int: ... +def def_prog_mode() -> None: ... +def def_shell_mode() -> None: ... +def delay_output(ms: int, /) -> None: ... +def doupdate() -> None: ... +def echo(flag: bool = True, /) -> None: ... +def endwin() -> None: ... +def erasechar() -> bytes: ... +def filter() -> None: ... +def flash() -> None: ... +def flushinp() -> None: ... +def get_escdelay() -> int: ... +def get_tabsize() -> int: ... +def getmouse() -> tuple[int, int, int, int, int]: ... +def getsyx() -> tuple[int, int]: ... +def getwin(file: SupportsRead[bytes], /) -> window: ... +def halfdelay(tenths: int, /) -> None: ... +def has_colors() -> bool: ... +def has_extended_color_support() -> bool: ... + +if sys.version_info >= (3, 14): + def assume_default_colors(fg: int, bg: int, /) -> None: ... + +def has_ic() -> bool: ... +def has_il() -> bool: ... +def has_key(key: int, /) -> bool: ... +def init_color(color_number: int, r: int, g: int, b: int, /) -> None: ... +def init_pair(pair_number: int, fg: int, bg: int, /) -> None: ... +def initscr() -> window: ... +def intrflush(flag: bool, /) -> None: ... +def is_term_resized(nlines: int, ncols: int, /) -> bool: ... +def isendwin() -> bool: ... +def keyname(key: int, /) -> bytes: ... +def killchar() -> bytes: ... +def longname() -> bytes: ... +def meta(yes: bool, /) -> None: ... +def mouseinterval(interval: int, /) -> None: ... +def mousemask(newmask: int, /) -> tuple[int, int]: ... +def napms(ms: int, /) -> int: ... +def newpad(nlines: int, ncols: int, /) -> window: ... +def newwin(nlines: int, ncols: int, begin_y: int = 0, begin_x: int = 0, /) -> window: ... +def nl(flag: bool = True, /) -> None: ... +def nocbreak() -> None: ... +def noecho() -> None: ... +def nonl() -> None: ... +def noqiflush() -> None: ... +def noraw() -> None: ... +def pair_content(pair_number: int, /) -> tuple[int, int]: ... +def pair_number(attr: int, /) -> int: ... +def putp(string: ReadOnlyBuffer, /) -> None: ... +def qiflush(flag: bool = True, /) -> None: ... +def raw(flag: bool = True, /) -> None: ... +def reset_prog_mode() -> None: ... +def reset_shell_mode() -> None: ... +def resetty() -> None: ... +def resize_term(nlines: int, ncols: int, /) -> None: ... +def resizeterm(nlines: int, ncols: int, /) -> None: ... +def savetty() -> None: ... +def set_escdelay(ms: int, /) -> None: ... +def set_tabsize(size: int, /) -> None: ... +def setsyx(y: int, x: int, /) -> None: ... +def setupterm(term: str | None = None, fd: int = -1) -> None: ... +def start_color() -> None: ... +def termattrs() -> int: ... +def termname() -> bytes: ... +def tigetflag(capname: str, /) -> int: ... +def tigetnum(capname: str, /) -> int: ... +def tigetstr(capname: str, /) -> bytes | None: ... +def tparm( + str: ReadOnlyBuffer, + i1: int = 0, + i2: int = 0, + i3: int = 0, + i4: int = 0, + i5: int = 0, + i6: int = 0, + i7: int = 0, + i8: int = 0, + i9: int = 0, + /, +) -> bytes: ... +def typeahead(fd: int, /) -> None: ... +def unctrl(ch: _ChType, /) -> bytes: ... +def unget_wch(ch: int | str, /) -> None: ... +def ungetch(ch: _ChType, /) -> None: ... +def ungetmouse(id: int, x: int, y: int, z: int, bstate: int, /) -> None: ... +def update_lines_cols() -> None: ... +def use_default_colors() -> None: ... +def use_env(flag: bool, /) -> None: ... + +class error(Exception): ... + +@final +class window: # undocumented + encoding: str + + @overload + def addch(self, ch: _ChType, attr: int = ...) -> None: ... + @overload + def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + + @overload + def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + + @overload + def addstr(self, str: str, attr: int = ...) -> None: ... + @overload + def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + + def attroff(self, attr: int, /) -> None: ... + def attron(self, attr: int, /) -> None: ... + def attrset(self, attr: int, /) -> None: ... + def bkgd(self, ch: _ChType, attr: int = 0, /) -> None: ... + def bkgdset(self, ch: _ChType, attr: int = 0, /) -> None: ... + def border( + self, + ls: _ChType = ..., + rs: _ChType = ..., + ts: _ChType = ..., + bs: _ChType = ..., + tl: _ChType = ..., + tr: _ChType = ..., + bl: _ChType = ..., + br: _ChType = ..., + ) -> None: ... + + @overload + def box(self) -> None: ... + @overload + def box(self, vertch: _ChType = 0, horch: _ChType = 0) -> None: ... + + @overload + def chgat(self, attr: int) -> None: ... + @overload + def chgat(self, num: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + + def clear(self) -> None: ... + def clearok(self, flag: bool, /) -> None: ... + def clrtobot(self) -> None: ... + def clrtoeol(self) -> None: ... + def cursyncup(self) -> None: ... + + @overload + def delch(self) -> None: ... + @overload + def delch(self, y: int, x: int) -> None: ... + + def deleteln(self) -> None: ... + + @overload + def derwin(self, begin_y: int, begin_x: int) -> window: ... + @overload + def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + + def echochar(self, ch: _ChType, attr: int = 0, /) -> None: ... + def enclose(self, y: int, x: int, /) -> bool: ... + def erase(self) -> None: ... + def getbegyx(self) -> tuple[int, int]: ... + def getbkgd(self) -> tuple[int, int]: ... + + @overload + def getch(self) -> int: ... + @overload + def getch(self, y: int, x: int) -> int: ... + + @overload + def get_wch(self) -> int | str: ... + @overload + def get_wch(self, y: int, x: int) -> int | str: ... + + @overload + def getkey(self) -> str: ... + @overload + def getkey(self, y: int, x: int) -> str: ... + + def getmaxyx(self) -> tuple[int, int]: ... + def getparyx(self) -> tuple[int, int]: ... + + @overload + def getstr(self) -> bytes: ... + @overload + def getstr(self, n: int) -> bytes: ... + @overload + def getstr(self, y: int, x: int) -> bytes: ... + @overload + def getstr(self, y: int, x: int, n: int) -> bytes: ... + + def getyx(self) -> tuple[int, int]: ... + + @overload + def hline(self, ch: _ChType, n: int) -> None: ... + @overload + def hline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... + + def idcok(self, flag: bool, /) -> None: ... + def idlok(self, flag: bool, /) -> None: ... + def immedok(self, flag: bool, /) -> None: ... + + @overload + def inch(self) -> int: ... + @overload + def inch(self, y: int, x: int) -> int: ... + + @overload + def insch(self, ch: _ChType, attr: int = ...) -> None: ... + @overload + def insch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + + def insdelln(self, nlines: int, /) -> None: ... + def insertln(self) -> None: ... + + @overload + def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + + @overload + def insstr(self, str: str, attr: int = ...) -> None: ... + @overload + def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + + @overload + def instr(self, n: int = 2047) -> bytes: ... + @overload + def instr(self, y: int, x: int, n: int = 2047) -> bytes: ... + + def is_linetouched(self, line: int, /) -> bool: ... + def is_wintouched(self) -> bool: ... + def keypad(self, flag: bool, /) -> None: ... + def leaveok(self, flag: bool, /) -> None: ... + def move(self, new_y: int, new_x: int, /) -> None: ... + def mvderwin(self, y: int, x: int, /) -> None: ... + def mvwin(self, new_y: int, new_x: int, /) -> None: ... + def nodelay(self, flag: bool, /) -> None: ... + def notimeout(self, flag: bool, /) -> None: ... + + @overload + def noutrefresh(self) -> None: ... + @overload + def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + + @overload + def overlay(self, destwin: window) -> None: ... + @overload + def overlay( + self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + + @overload + def overwrite(self, destwin: window) -> None: ... + @overload + def overwrite( + self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + + def putwin(self, file: SupportsWrite[bytes], /) -> None: ... + def redrawln(self, beg: int, num: int, /) -> None: ... + def redrawwin(self) -> None: ... + + @overload + def refresh(self) -> None: ... + @overload + def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + + def resize(self, nlines: int, ncols: int, /) -> None: ... + def scroll(self, lines: int = 1) -> None: ... + def scrollok(self, flag: bool, /) -> None: ... + def setscrreg(self, top: int, bottom: int, /) -> None: ... + def standend(self) -> None: ... + def standout(self) -> None: ... + + @overload + def subpad(self, begin_y: int, begin_x: int) -> window: ... + @overload + def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + + @overload + def subwin(self, begin_y: int, begin_x: int) -> window: ... + @overload + def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + + def syncdown(self) -> None: ... + def syncok(self, flag: bool, /) -> None: ... + def syncup(self) -> None: ... + def timeout(self, delay: int, /) -> None: ... + def touchline(self, start: int, count: int, changed: bool = True) -> None: ... + def touchwin(self) -> None: ... + def untouchwin(self) -> None: ... + + @overload + def vline(self, ch: _ChType, n: int) -> None: ... + @overload + def vline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... + +ncurses_version: _ncurses_version diff --git a/stdlib/_curses_panel.pyi b/stdlib/_curses_panel.pyi new file mode 100644 index 000000000000..64205618bf41 --- /dev/null +++ b/stdlib/_curses_panel.pyi @@ -0,0 +1,27 @@ +from _curses import window as _window +from typing import Final, final + +__version__: Final[str] +version: Final[str] + +class error(Exception): ... + +@final +class panel: + def above(self) -> panel: ... + def below(self) -> panel: ... + def bottom(self) -> None: ... + def hidden(self) -> bool: ... + def hide(self) -> None: ... + def move(self, y: int, x: int, /) -> None: ... + def replace(self, win: _window, /) -> None: ... + def set_userptr(self, obj: object, /) -> None: ... + def show(self) -> None: ... + def top(self) -> None: ... + def userptr(self) -> object: ... + def window(self) -> _window: ... + +def bottom_panel() -> panel: ... +def new_panel(win: _window, /) -> panel: ... +def top_panel() -> panel: ... +def update_panels() -> panel: ... diff --git a/stdlib/_dbm.pyi b/stdlib/_dbm.pyi new file mode 100644 index 000000000000..29d9b4c2fadc --- /dev/null +++ b/stdlib/_dbm.pyi @@ -0,0 +1,46 @@ +import sys +from _typeshed import ReadOnlyBuffer, StrOrBytesPath +from types import TracebackType +from typing import Final, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self + +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType: TypeAlias = str | ReadOnlyBuffer + _ValueType: TypeAlias = str | ReadOnlyBuffer + + class error(OSError): ... + library: Final[str] + + # Actual typename dbm, not exposed by the implementation + @final + @type_check_only + class _dbm: + def close(self) -> None: ... + if sys.version_info >= (3, 13): + def clear(self) -> None: ... + + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + @overload + def get(self, k: _KeyType, /) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ... + + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = b"", /) -> bytes: ... + # This isn't true, but the class can't be instantiated. See #13024 + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + if sys.version_info >= (3, 11): + def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _dbm: ... + else: + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _dbm: ... diff --git a/stdlib/_decimal.pyi b/stdlib/_decimal.pyi new file mode 100644 index 000000000000..75d5be277f95 --- /dev/null +++ b/stdlib/_decimal.pyi @@ -0,0 +1,73 @@ +import sys +from decimal import ( + Clamped as Clamped, + Context as Context, + ConversionSyntax as ConversionSyntax, + Decimal as Decimal, + DecimalException as DecimalException, + DecimalTuple as DecimalTuple, + DivisionByZero as DivisionByZero, + DivisionImpossible as DivisionImpossible, + DivisionUndefined as DivisionUndefined, + FloatOperation as FloatOperation, + Inexact as Inexact, + InvalidContext as InvalidContext, + InvalidOperation as InvalidOperation, + Overflow as Overflow, + Rounded as Rounded, + Subnormal as Subnormal, + Underflow as Underflow, + _ContextManager, +) +from typing import Final, TypeAlias + +_TrapType: TypeAlias = type[DecimalException] + +__version__: Final[str] +__libmpdec_version__: Final[str] +if sys.version_info >= (3, 15): + SPEC_VERSION: Final[str] + +ROUND_DOWN: Final = "ROUND_DOWN" +ROUND_HALF_UP: Final = "ROUND_HALF_UP" +ROUND_HALF_EVEN: Final = "ROUND_HALF_EVEN" +ROUND_CEILING: Final = "ROUND_CEILING" +ROUND_FLOOR: Final = "ROUND_FLOOR" +ROUND_UP: Final = "ROUND_UP" +ROUND_HALF_DOWN: Final = "ROUND_HALF_DOWN" +ROUND_05UP: Final = "ROUND_05UP" +HAVE_CONTEXTVAR: Final[bool] +HAVE_THREADS: Final[bool] +MAX_EMAX: Final[int] +MAX_PREC: Final[int] +MIN_EMIN: Final[int] +MIN_ETINY: Final[int] +if sys.version_info >= (3, 14): + IEEE_CONTEXT_MAX_BITS: Final[int] + +def setcontext(context: Context, /) -> None: ... +def getcontext() -> Context: ... + +if sys.version_info >= (3, 11): + def localcontext( + ctx: Context | None = None, + *, + prec: int | None = None, + rounding: str | None = None, + Emin: int | None = None, + Emax: int | None = None, + capitals: int | None = None, + clamp: int | None = None, + traps: dict[_TrapType, bool] | None = None, + flags: dict[_TrapType, bool] | None = None, + ) -> _ContextManager: ... + +else: + def localcontext(ctx: Context | None = None) -> _ContextManager: ... + +if sys.version_info >= (3, 14): + def IEEEContext(bits: int, /) -> Context: ... + +DefaultContext: Context +BasicContext: Context +ExtendedContext: Context diff --git a/stdlib/_frozen_importlib.pyi b/stdlib/_frozen_importlib.pyi new file mode 100644 index 000000000000..172da4522d8f --- /dev/null +++ b/stdlib/_frozen_importlib.pyi @@ -0,0 +1,115 @@ +import importlib.abc +import importlib.machinery +import sys +import types +from _typeshed.importlib import LoaderProtocol +from collections.abc import Mapping, Sequence +from types import ModuleType +from typing import Any, ClassVar +from typing_extensions import deprecated + +# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` +def __import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, +) -> ModuleType: ... +def spec_from_loader( + name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None +) -> importlib.machinery.ModuleSpec | None: ... +def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... +def _init_module_attrs( + spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False +) -> types.ModuleType: ... + +class ModuleSpec: + def __init__( + self, + name: str, + loader: importlib.abc.Loader | None, + *, + origin: str | None = None, + loader_state: Any = None, + is_package: bool | None = None, + ) -> None: ... + name: str + loader: importlib.abc.Loader | None + origin: str | None + submodule_search_locations: list[str] | None + loader_state: Any + cached: str | None + @property + def parent(self) -> str | None: ... + has_location: bool + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... + +class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): + # MetaPathFinder + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + # InspectLoader + @classmethod + def is_package(cls, fullname: str) -> bool: ... + @classmethod + def load_module(cls, fullname: str) -> types.ModuleType: ... + @classmethod + def get_code(cls, fullname: str) -> None: ... + @classmethod + def get_source(cls, fullname: str) -> None: ... + # Loader + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(m: types.ModuleType) -> str: ... + + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... diff --git a/stdlib/_frozen_importlib_external.pyi b/stdlib/_frozen_importlib_external.pyi new file mode 100644 index 000000000000..907e8def9380 --- /dev/null +++ b/stdlib/_frozen_importlib_external.pyi @@ -0,0 +1,180 @@ +import _ast +import importlib.abc +import importlib.machinery +import importlib.readers +import sys +import types +from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath +from _typeshed.importlib import LoaderProtocol +from collections.abc import Callable, Iterable, Mapping, MutableSequence, Sequence +from importlib.machinery import ModuleSpec +from importlib.metadata import DistributionFinder, PathDistribution +from typing import Any, Final, Literal, overload +from typing_extensions import deprecated + +if sys.platform == "win32": + path_separators: Literal["\\/"] + path_sep: Literal["\\"] + path_sep_tuple: tuple[Literal["\\"], Literal["/"]] +else: + path_separators: Literal["/"] + path_sep: Literal["/"] + path_sep_tuple: tuple[Literal["/"]] + +MAGIC_NUMBER: Final[bytes] + +@overload +@deprecated( + "The `debug_override` parameter is deprecated since Python 3.5; will be removed in Python 3.15. Use `optimization` instead." +) +def cache_from_source(path: StrPath, debug_override: bool, *, optimization: None = None) -> str: ... +@overload +def cache_from_source(path: StrPath, debug_override: None = None, *, optimization: Any | None = None) -> str: ... + +def source_from_cache(path: StrPath) -> str: ... +def decode_source(source_bytes: ReadableBuffer) -> str: ... +def spec_from_file_location( + name: str, + location: StrOrBytesPath | None = None, + *, + loader: LoaderProtocol | None = None, + submodule_search_locations: list[str] | None = ..., +) -> importlib.machinery.ModuleSpec | None: ... + +@deprecated( + "Deprecated since Python 3.6. Use site configuration instead. " + "Future versions of Python may not enable this finder by default." +) +class WindowsRegistryFinder(importlib.abc.MetaPathFinder): + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + +class PathFinder(importlib.abc.MetaPathFinder): + @staticmethod + def invalidate_caches() -> None: ... + @staticmethod + def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + @classmethod + def find_spec( + cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None + ) -> ModuleSpec | None: ... + if sys.version_info < (3, 12): + @classmethod + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ... + +SOURCE_SUFFIXES: Final[list[str]] +DEBUG_BYTECODE_SUFFIXES: Final = [".pyc"] +OPTIMIZED_BYTECODE_SUFFIXES: Final = [".pyc"] +BYTECODE_SUFFIXES: Final = [".pyc"] +EXTENSION_SUFFIXES: Final[list[str]] + +class FileFinder(importlib.abc.PathEntryFinder): + path: str + def __init__(self, path: str, *loader_details: tuple[type[importlib.abc.Loader], list[str]]) -> None: ... + @classmethod + def path_hook( + cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]] + ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... + +class _LoaderBasics: + def is_package(self, fullname: str) -> bool: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + def load_module(self, fullname: str) -> types.ModuleType: ... + +class SourceLoader(_LoaderBasics): + def path_mtime(self, path: str) -> float: ... + def set_data(self, path: str, data: bytes) -> None: ... + def get_source(self, fullname: str) -> str | None: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + def source_to_code( + self, data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: bytes | StrPath + ) -> types.CodeType: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + +class FileLoader: + name: str + path: str + def __init__(self, fullname: str, path: str) -> None: ... + def get_data(self, path: str) -> bytes: ... + def get_filename(self, fullname: str | None = None) -> str: ... + def load_module(self, fullname: str | None = None) -> types.ModuleType: ... + def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ... + +class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader): # type: ignore[misc] # incompatible method arguments in base classes + def set_data(self, path: str, data: ReadableBuffer, *, _mode: int = 0o666) -> None: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + def source_to_code( # type: ignore[override] # incompatible with InspectLoader.source_to_code + self, + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, + path: bytes | StrPath, + *, + _optimize: int = -1, + ) -> types.CodeType: ... + +class SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics): + def get_code(self, fullname: str) -> types.CodeType | None: ... + def get_source(self, fullname: str) -> None: ... + +class ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoader): + def __init__(self, name: str, path: str) -> None: ... + def get_filename(self, fullname: str | None = None) -> str: ... + def get_source(self, fullname: str) -> None: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType: ... + def exec_module(self, module: types.ModuleType) -> None: ... + def get_code(self, fullname: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 11): + class NamespaceLoader(importlib.abc.InspectLoader): + def __init__( + self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec] + ) -> None: ... + def is_package(self, fullname: str) -> Literal[True]: ... + def get_source(self, fullname: str) -> Literal[""]: ... + def get_code(self, fullname: str) -> types.CodeType: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... + if sys.version_info < (3, 12): + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + + _NamespaceLoader = NamespaceLoader +else: + class _NamespaceLoader: + def __init__( + self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec] + ) -> None: ... + def is_package(self, fullname: str) -> Literal[True]: ... + def get_source(self, fullname: str) -> Literal[""]: ... + def get_code(self, fullname: str) -> types.CodeType: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... + +if sys.version_info >= (3, 13): + class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ... diff --git a/stdlib/_gdbm.pyi b/stdlib/_gdbm.pyi new file mode 100644 index 000000000000..b7a01a453120 --- /dev/null +++ b/stdlib/_gdbm.pyi @@ -0,0 +1,50 @@ +import sys +from _typeshed import ReadOnlyBuffer, StrOrBytesPath +from types import TracebackType +from typing import TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +if sys.platform != "win32": + _T = TypeVar("_T") + _KeyType: TypeAlias = str | ReadOnlyBuffer + _ValueType: TypeAlias = str | ReadOnlyBuffer + + open_flags: str + + class error(OSError): ... + # Actual typename gdbm, not exposed by the implementation + @type_check_only + class _gdbm: + def firstkey(self) -> bytes | None: ... + def nextkey(self, key: _KeyType) -> bytes | None: ... + def reorganize(self) -> None: ... + def sync(self) -> None: ... + def close(self) -> None: ... + if sys.version_info >= (3, 13): + def clear(self) -> None: ... + + def __getitem__(self, item: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __contains__(self, key: _KeyType) -> bool: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + @overload + def get(self, k: _KeyType) -> bytes | None: ... + @overload + def get(self, k: _KeyType, default: _T) -> bytes | _T: ... + + def keys(self) -> list[bytes]: ... + def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + if sys.version_info >= (3, 11): + def open(filename: StrOrBytesPath, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ... + else: + def open(filename: str, flags: str = "r", mode: int = 0o666, /) -> _gdbm: ... diff --git a/stdlib/_hashlib.pyi b/stdlib/_hashlib.pyi new file mode 100644 index 000000000000..b98edc5757c3 --- /dev/null +++ b/stdlib/_hashlib.pyi @@ -0,0 +1,127 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Callable +from types import ModuleType +from typing import AnyStr, Protocol, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None + +openssl_md_meth_names: frozenset[str] + +@type_check_only +class _HashObject(Protocol): + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, obj: ReadableBuffer, /) -> None: ... + +@disjoint_base +class HASH: + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, obj: ReadableBuffer, /) -> None: ... + +class UnsupportedDigestmodError(ValueError): ... + +class HASHXOF(HASH): + def digest(self, length: int) -> bytes: ... # type: ignore[override] + def hexdigest(self, length: int) -> str: ... # type: ignore[override] + +@final +class HMAC: + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, msg: ReadableBuffer) -> None: ... + +@overload +def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... +@overload +def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... + +def get_fips_mode() -> int: ... +def hmac_new(key: ReadableBuffer, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ... + +if sys.version_info >= (3, 13): + def new( + name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_md5( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha1( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha224( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha384( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha512( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_224( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_384( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_sha3_512( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASH: ... + def openssl_shake_128( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... + def openssl_shake_256( + data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... + +else: + def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha1(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + def openssl_shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + def openssl_shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + +def hmac_digest(key: ReadableBuffer, msg: ReadableBuffer, digest: str) -> bytes: ... +def pbkdf2_hmac( + hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None +) -> bytes: ... +def scrypt( + password: ReadableBuffer, *, salt: ReadableBuffer, n: int, r: int, p: int, maxmem: int = 0, dklen: int = 64 +) -> bytes: ... diff --git a/stdlib/_heapq.pyi b/stdlib/_heapq.pyi new file mode 100644 index 000000000000..7664b826ae0b --- /dev/null +++ b/stdlib/_heapq.pyi @@ -0,0 +1,18 @@ +import sys +from _typeshed import SupportsRichComparisonT as _T # All type variable use in this module requires comparability. +from typing import Final + +__about__: Final[str] + +def heapify(heap: list[_T], /) -> None: ... # To work around the fact that list is invariant +def heappop(heap: list[_T], /) -> _T: ... +def heappush(heap: list[_T], item: _T, /) -> None: ... +def heappushpop(heap: list[_T], item: _T, /) -> _T: ... +def heapreplace(heap: list[_T], item: _T, /) -> _T: ... + +if sys.version_info >= (3, 14): + def heapify_max(heap: list[_T], /) -> None: ... + def heappop_max(heap: list[_T], /) -> _T: ... + def heappush_max(heap: list[_T], item: _T, /) -> None: ... + def heappushpop_max(heap: list[_T], item: _T, /) -> _T: ... + def heapreplace_max(heap: list[_T], item: _T, /) -> _T: ... diff --git a/stdlib/_imp.pyi b/stdlib/_imp.pyi new file mode 100644 index 000000000000..c12c26d08ba2 --- /dev/null +++ b/stdlib/_imp.pyi @@ -0,0 +1,30 @@ +import sys +import types +from _typeshed import ReadableBuffer +from importlib.machinery import ModuleSpec +from typing import Any + +check_hash_based_pycs: str +if sys.version_info >= (3, 14): + pyc_magic_number_token: int + +def source_hash(key: int, source: ReadableBuffer) -> bytes: ... +def create_builtin(spec: ModuleSpec, /) -> types.ModuleType: ... +def create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType: ... +def acquire_lock() -> None: ... +def exec_builtin(mod: types.ModuleType, /) -> int: ... +def exec_dynamic(mod: types.ModuleType, /) -> int: ... +def extension_suffixes() -> list[str]: ... +def init_frozen(name: str, /) -> types.ModuleType: ... +def is_builtin(name: str, /) -> int: ... +def is_frozen(name: str, /) -> bool: ... +def is_frozen_package(name: str, /) -> bool: ... +def lock_held() -> bool: ... +def release_lock() -> None: ... + +if sys.version_info >= (3, 11): + def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: ... + def get_frozen_object(name: str, data: ReadableBuffer | None = None, /) -> types.CodeType: ... + +else: + def get_frozen_object(name: str, /) -> types.CodeType: ... diff --git a/stdlib/_interpchannels.pyi b/stdlib/_interpchannels.pyi new file mode 100644 index 000000000000..a631a6f16616 --- /dev/null +++ b/stdlib/_interpchannels.pyi @@ -0,0 +1,86 @@ +from _typeshed import structseq +from typing import Any, Final, Literal, SupportsIndex, final +from typing_extensions import Buffer, Self + +class ChannelError(RuntimeError): ... +class ChannelClosedError(ChannelError): ... +class ChannelEmptyError(ChannelError): ... +class ChannelNotEmptyError(ChannelError): ... +class ChannelNotFoundError(ChannelError): ... + +# Mark as final, since instantiating ChannelID is not supported. +@final +class ChannelID: + @property + def end(self) -> Literal["send", "recv", "both"]: ... + @property + def send(self) -> Self: ... + @property + def recv(self) -> Self: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: ChannelID, /) -> bool: ... + def __gt__(self, other: ChannelID, /) -> bool: ... + def __hash__(self) -> int: ... + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __le__(self, other: ChannelID, /) -> bool: ... + def __lt__(self, other: ChannelID, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + +@final +class ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]): + __match_args__: Final = ( + "open", + "closing", + "closed", + "count", + "num_interp_send", + "num_interp_send_released", + "num_interp_recv", + "num_interp_recv_released", + ) + @property + def open(self) -> bool: ... + @property + def closing(self) -> bool: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... # type: ignore[override] + @property + def num_interp_send(self) -> int: ... + @property + def num_interp_send_released(self) -> int: ... + @property + def num_interp_recv(self) -> int: ... + @property + def num_interp_recv_released(self) -> int: ... + @property + def num_interp_both(self) -> int: ... + @property + def num_interp_both_recv_released(self) -> int: ... + @property + def num_interp_both_send_released(self) -> int: ... + @property + def num_interp_both_released(self) -> int: ... + @property + def recv_associated(self) -> bool: ... + @property + def recv_released(self) -> bool: ... + @property + def send_associated(self) -> bool: ... + @property + def send_released(self) -> bool: ... + +def create(unboundop: Literal[1, 2, 3]) -> ChannelID: ... +def destroy(cid: SupportsIndex) -> None: ... +def list_all() -> list[ChannelID]: ... +def list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: ... +def send(cid: SupportsIndex, obj: object, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def send_buffer(cid: SupportsIndex, obj: Buffer, *, blocking: bool = True, timeout: float | None = None) -> None: ... +def recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, 3]]: ... +def close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None: ... +def get_count(cid: SupportsIndex) -> int: ... +def get_info(cid: SupportsIndex) -> ChannelInfo: ... +def get_channel_defaults(cid: SupportsIndex) -> Literal[1, 2, 3]: ... +def release(cid: SupportsIndex, *, send: bool = False, recv: bool = False, force: bool = False) -> None: ... diff --git a/stdlib/_interpqueues.pyi b/stdlib/_interpqueues.pyi new file mode 100644 index 000000000000..94605e4c0dda --- /dev/null +++ b/stdlib/_interpqueues.pyi @@ -0,0 +1,31 @@ +import sys +from typing import Any, Literal, SupportsIndex, TypeAlias + +_UnboundOp: TypeAlias = Literal[1, 2, 3] + +class QueueError(RuntimeError): ... +class QueueNotFoundError(QueueError): ... + +def bind(qid: SupportsIndex) -> None: ... + +if sys.version_info >= (3, 15): + def create(maxsize: SupportsIndex, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> int: ... + +else: + def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: ... + +def destroy(qid: SupportsIndex) -> None: ... +def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: ... +def get_count(qid: SupportsIndex) -> int: ... +def get_maxsize(qid: SupportsIndex) -> int: ... +def get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: ... +def is_full(qid: SupportsIndex) -> bool: ... +def list_all() -> list[tuple[int, int, _UnboundOp]]: ... + +if sys.version_info >= (3, 15): + def put(qid: SupportsIndex, obj: Any, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> None: ... + +else: + def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ... + +def release(qid: SupportsIndex) -> None: ... diff --git a/stdlib/_interpreters.pyi b/stdlib/_interpreters.pyi new file mode 100644 index 000000000000..3885669278f5 --- /dev/null +++ b/stdlib/_interpreters.pyi @@ -0,0 +1,62 @@ +import types +from collections.abc import Callable +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import disjoint_base + +_R = TypeVar("_R") + +_Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""] +_SharedDict: TypeAlias = dict[str, Any] # many objects can be shared + +class InterpreterError(Exception): ... +class InterpreterNotFoundError(InterpreterError): ... +class NotShareableError(ValueError): ... + +@disjoint_base +class CrossInterpreterBufferView: + def __buffer__(self, flags: int, /) -> memoryview: ... + +def new_config(name: _Configs = "isolated", /, **overides: object) -> types.SimpleNamespace: ... +def create(config: types.SimpleNamespace | _Configs | None = "isolated", *, reqrefs: bool = False) -> int: ... +def destroy(id: SupportsIndex, *, restrict: bool = False) -> None: ... +def list_all(*, require_ready: bool = False) -> list[tuple[int, _Whence]]: ... +def get_current() -> tuple[int, _Whence]: ... +def get_main() -> tuple[int, _Whence]: ... +def is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ... +def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ... +def whence(id: SupportsIndex) -> _Whence: ... +def exec( + id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> None | types.SimpleNamespace: ... +def call( + id: SupportsIndex, + callable: Callable[..., _R], + args: tuple[Any, ...] = (), + kwargs: dict[str, Any] = {}, + *, + preserve_exc: bool = False, + restrict: bool = False, +) -> tuple[_R, types.SimpleNamespace]: ... +def run_string( + id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> None: ... +def run_func( + id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False +) -> None: ... +def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: bool = False) -> None: ... +def incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ... +def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ... +def is_shareable(obj: object) -> bool: ... + +@overload +def capture_exception(exc: BaseException) -> types.SimpleNamespace: ... +@overload +def capture_exception(exc: None = None) -> types.SimpleNamespace | None: ... + +_Whence: TypeAlias = Literal[0, 1, 2, 3, 4, 5] +WHENCE_UNKNOWN: Final = 0 +WHENCE_RUNTIME: Final = 1 +WHENCE_LEGACY_CAPI: Final = 2 +WHENCE_CAPI: Final = 3 +WHENCE_XI: Final = 4 +WHENCE_STDLIB: Final = 5 diff --git a/stdlib/_io.pyi b/stdlib/_io.pyi new file mode 100644 index 000000000000..5e216123be98 --- /dev/null +++ b/stdlib/_io.pyi @@ -0,0 +1,330 @@ +import builtins +import codecs +import sys +from _typeshed import FileDescriptorOrPath, MaybeNone, ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator +from io import BufferedIOBase, RawIOBase, TextIOBase, UnsupportedOperation as UnsupportedOperation +from os import _Opener +from types import TracebackType +from typing import IO, Any, BinaryIO, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_S = TypeVar("_S", bound=str) + +if sys.version_info >= (3, 14): + DEFAULT_BUFFER_SIZE: Final = 131072 +else: + DEFAULT_BUFFER_SIZE: Final = 8192 + +open = builtins.open + +def open_code(path: str) -> IO[bytes]: ... + +BlockingIOError = builtins.BlockingIOError + +if sys.version_info >= (3, 12): + @disjoint_base + class _IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + read: Callable[..., Any] + def readlines(self, hint: int = -1, /) -> list[bytes]: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... + def writable(self) -> bool: ... + write: Callable[..., Any] + def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def readline(self, size: int | None = -1, /) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... # undocumented + +else: + class _IOBase: + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + read: Callable[..., Any] + def readlines(self, hint: int = -1, /) -> list[bytes]: ... + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: int | None = None, /) -> int: ... + def writable(self) -> bool: ... + write: Callable[..., Any] + def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def readline(self, size: int | None = -1, /) -> bytes: ... + def __del__(self) -> None: ... + @property + def closed(self) -> bool: ... + def _checkClosed(self) -> None: ... # undocumented + +class _RawIOBase(_IOBase): + def readall(self) -> bytes: ... + # The following methods can return None if the file is in non-blocking mode + # and no data is available. + def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ... + def write(self, b: ReadableBuffer, /) -> int | MaybeNone: ... + def read(self, size: int = -1, /) -> bytes | MaybeNone: ... + +class _BufferedIOBase(_IOBase): + def detach(self) -> RawIOBase: ... + def readinto(self, buffer: WriteableBuffer, /) -> int: ... + def write(self, buffer: ReadableBuffer, /) -> int: ... + def readinto1(self, buffer: WriteableBuffer, /) -> int: ... + def read(self, size: int | None = -1, /) -> bytes: ... + def read1(self, size: int = -1, /) -> bytes: ... + +@disjoint_base +class FileIO(RawIOBase, _RawIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes + mode: str + # The type of "name" equals the argument passed in to the constructor, + # but that can make FileIO incompatible with other I/O types that assume + # "name" is a str. In the future, making FileIO generic might help. + name: Any + def __init__( + self, file: FileDescriptorOrPath, mode: str = "r", closefd: bool = True, opener: _Opener | None = None + ) -> None: ... + @property + def closefd(self) -> bool: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + def read(self, size: int | None = -1, /) -> bytes | MaybeNone: ... + +@disjoint_base +class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes + def __init__(self, initial_bytes: ReadableBuffer = b"") -> None: ... + # BytesIO does not contain a "name" field. This workaround is necessary + # to allow BytesIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> bytes: ... + def getbuffer(self) -> memoryview: ... + def read1(self, size: int | None = -1, /) -> bytes: ... + def readlines(self, size: int | None = None, /) -> list[bytes]: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + +@type_check_only +class _BufferedReaderStream(Protocol): + def read(self, n: int = ..., /) -> bytes: ... + # Optional: def readall(self) -> bytes: ... + def readinto(self, b: memoryview, /) -> int | None: ... + def seek(self, pos: int, whence: int, /) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: int, /) -> int: ... + def flush(self) -> object: ... + def close(self) -> object: ... + @property + def closed(self) -> bool: ... + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + + # The following methods just pass through to the underlying stream. Since + # not all streams support them, they are marked as optional here, and will + # raise an AttributeError if called on a stream that does not support them. + + # @property + # def name(self) -> Any: ... # Type is inconsistent between the various I/O types. + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + # def isatty(self) -> bool: ... + +_BufferedReaderStreamT = TypeVar("_BufferedReaderStreamT", bound=_BufferedReaderStream, default=_BufferedReaderStream) + +@disjoint_base +class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]): # type: ignore[misc] # incompatible definitions of methods in the base classes + raw: _BufferedReaderStreamT + if sys.version_info >= (3, 14): + def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ... + + def peek(self, size: int = 0, /) -> bytes: ... + def seek(self, target: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@type_check_only +class _BufferedWriterStream(Protocol): + def write(self, b: WriteableBuffer, /) -> int | None: ... + def seek(self, pos: int, whence: int, /) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: int, /) -> int: ... + def flush(self) -> object: ... + def close(self) -> object: ... + @property + def closed(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + + # The following methods just pass through to the underlying stream. Since + # not all streams support them, they are marked as optional here, and will + # raise an AttributeError if called on a stream that does not support them. + + # @property + # def name(self) -> Any: ... # Type is inconsistent between the various I/O types. + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + # def isatty(self) -> bool: ... + +_BufferedWriterStreamT = TypeVar("_BufferedWriterStreamT", bound=_BufferedWriterStream, default=_BufferedWriterStream) + +@disjoint_base +class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedWriterStreamT]): # type: ignore[misc] # incompatible definitions of writelines in the base classes + raw: _BufferedWriterStreamT + if sys.version_info >= (3, 14): + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 8192) -> None: ... + + def write(self, buffer: ReadableBuffer, /) -> int: ... + def seek(self, target: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes + mode: str + name: Any + raw: RawIOBase + if sys.version_info >= (3, 14): + def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ... + else: + def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... + + def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this + def peek(self, size: int = 0, /) -> bytes: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT, _BufferedWriterStreamT]): + if sys.version_info >= (3, 14): + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 131072, / + ) -> None: ... + else: + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 8192, / + ) -> None: ... + + def peek(self, size: int = 0, /) -> bytes: ... + +class _TextIOBase(_IOBase): + encoding: str + errors: str | None + newlines: str | tuple[str, ...] | None + def __iter__(self) -> Iterator[str]: ... # type: ignore[override] + def __next__(self) -> str: ... # type: ignore[override] + def detach(self) -> BinaryIO: ... + def write(self, s: str, /) -> int: ... + def writelines(self, lines: Iterable[str], /) -> None: ... # type: ignore[override] + def readline(self, size: int = -1, /) -> str: ... # type: ignore[override] + def readlines(self, hint: int = -1, /) -> list[str]: ... # type: ignore[override] + def read(self, size: int | None = -1, /) -> str: ... + +@type_check_only +class _WrappedBuffer(Protocol): + # "name" is wrapped by TextIOWrapper. Its type is inconsistent between + # the various I/O types. + @property + def name(self) -> Any: ... + @property + def closed(self) -> bool: ... + def read(self, size: int = ..., /) -> ReadableBuffer: ... + # Optional: def read1(self, size: int, /) -> ReadableBuffer: ... + def write(self, b: bytes, /) -> object: ... + def flush(self) -> object: ... + def close(self) -> object: ... + def seekable(self) -> bool: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def truncate(self, size: int, /) -> int: ... + def fileno(self) -> int: ... + def isatty(self) -> bool: ... + # Optional: Only needs to be present if seekable() returns True. + # def seek(self, offset: Literal[0], whence: Literal[2]) -> int: ... + # def tell(self) -> int: ... + +_BufferT_co = TypeVar("_BufferT_co", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True) + +@disjoint_base +class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # type: ignore[misc] # incompatible definitions of write in the base classes + def __init__( + self, + buffer: _BufferT_co, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> None: ... + # Equals the "buffer" argument passed in to the constructor. + @property + def buffer(self) -> _BufferT_co: ... # type: ignore[override] + @property + def line_buffering(self) -> bool: ... + @property + def write_through(self) -> bool: ... + def reconfigure( + self, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool | None = None, + write_through: bool | None = None, + ) -> None: ... + def readline(self, size: int = -1, /) -> str: ... # type: ignore[override] + # Equals the "buffer" argument passed in to the constructor. + def detach(self) -> _BufferT_co: ... # type: ignore[override] + # TextIOWrapper's version of seek only supports a limited subset of + # operations. + def seek(self, cookie: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes + def __init__(self, initial_value: str | None = "", newline: str | None = "\n") -> None: ... + # StringIO does not contain a "name" field. This workaround is necessary + # to allow StringIO sub-classes to add this field, as it is defined + # as a read-only property on IO[]. + name: Any + def getvalue(self) -> str: ... + @property + def line_buffering(self) -> bool: ... + def seek(self, pos: int, whence: int = 0, /) -> int: ... + def truncate(self, pos: int | None = None, /) -> int: ... + +@disjoint_base +class IncrementalNewlineDecoder: + def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = "strict") -> None: ... + def decode(self, input: ReadableBuffer | str, final: bool = False) -> str: ... + @property + def newlines(self) -> str | tuple[str, ...] | None: ... + def getstate(self) -> tuple[bytes, int]: ... + def reset(self) -> None: ... + def setstate(self, state: tuple[bytes, int], /) -> None: ... + +@overload +def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ... +@overload +def text_encoding(encoding: _S, stacklevel: int = 2, /) -> _S: ... diff --git a/stdlib/_json.pyi b/stdlib/_json.pyi new file mode 100644 index 000000000000..c6c2c97e83aa --- /dev/null +++ b/stdlib/_json.pyi @@ -0,0 +1,59 @@ +import sys +from collections.abc import Callable +from typing import Any, final +from typing_extensions import Self + +@final +class make_encoder: + @property + def sort_keys(self) -> bool: ... + @property + def skipkeys(self) -> bool: ... + @property + def key_separator(self) -> str: ... + @property + def indent(self) -> str | None: ... + @property + def markers(self) -> dict[int, Any] | None: ... + @property + def default(self) -> Callable[[Any], Any]: ... + @property + def encoder(self) -> Callable[[str], str]: ... + @property + def item_separator(self) -> str: ... + def __new__( + cls, + markers: dict[int, Any] | None, + default: Callable[[Any], Any], + encoder: Callable[[str], str], + indent: str | None, + key_separator: str, + item_separator: str, + sort_keys: bool, + skipkeys: bool, + allow_nan: bool, + ) -> Self: ... + def __call__(self, obj: object, _current_indent_level: int) -> Any: ... + +@final +class make_scanner: + if sys.version_info >= (3, 15): + array_hook: Any + object_hook: Any + object_pairs_hook: Any + parse_int: Any + parse_constant: Any + parse_float: Any + strict: bool + # TODO: 'context' needs the attrs above (ducktype), but not __call__. + def __new__(cls, context: make_scanner) -> Self: ... + def __call__(self, string: str, index: int) -> tuple[Any, int]: ... + +def encode_basestring(s: str, /) -> str: ... +def encode_basestring_ascii(s: str, /) -> str: ... + +if sys.version_info >= (3, 15): + def scanstring(pystr: str, end: int, strict: bool = True, /) -> tuple[str, int]: ... + +else: + def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ... diff --git a/stdlib/_locale.pyi b/stdlib/_locale.pyi new file mode 100644 index 000000000000..ccce7a0d9d70 --- /dev/null +++ b/stdlib/_locale.pyi @@ -0,0 +1,121 @@ +import sys +from _typeshed import StrPath +from typing import Final, Literal, TypedDict, type_check_only + +@type_check_only +class _LocaleConv(TypedDict): + decimal_point: str + grouping: list[int] + thousands_sep: str + int_curr_symbol: str + currency_symbol: str + p_cs_precedes: Literal[0, 1, 127] + n_cs_precedes: Literal[0, 1, 127] + p_sep_by_space: Literal[0, 1, 127] + n_sep_by_space: Literal[0, 1, 127] + mon_decimal_point: str + frac_digits: int + int_frac_digits: int + mon_thousands_sep: str + mon_grouping: list[int] + positive_sign: str + negative_sign: str + p_sign_posn: Literal[0, 1, 2, 3, 4, 127] + n_sign_posn: Literal[0, 1, 2, 3, 4, 127] + +LC_CTYPE: Final[int] +LC_COLLATE: Final[int] +LC_TIME: Final[int] +LC_MONETARY: Final[int] +LC_NUMERIC: Final[int] +LC_ALL: Final[int] +CHAR_MAX: Final = 127 + +def setlocale(category: int, locale: str | None = None, /) -> str: ... +def localeconv() -> _LocaleConv: ... + +if sys.version_info >= (3, 11): + def getencoding() -> str: ... + +def strcoll(os1: str, os2: str, /) -> int: ... +def strxfrm(string: str, /) -> str: ... + +# native gettext functions +# https://docs.python.org/3/library/locale.html#access-to-message-catalogs +# https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Modules/_localemodule.c#L626 +if sys.platform != "win32": + LC_MESSAGES: int + + ABDAY_1: Final[int] + ABDAY_2: Final[int] + ABDAY_3: Final[int] + ABDAY_4: Final[int] + ABDAY_5: Final[int] + ABDAY_6: Final[int] + ABDAY_7: Final[int] + + ABMON_1: Final[int] + ABMON_2: Final[int] + ABMON_3: Final[int] + ABMON_4: Final[int] + ABMON_5: Final[int] + ABMON_6: Final[int] + ABMON_7: Final[int] + ABMON_8: Final[int] + ABMON_9: Final[int] + ABMON_10: Final[int] + ABMON_11: Final[int] + ABMON_12: Final[int] + + DAY_1: Final[int] + DAY_2: Final[int] + DAY_3: Final[int] + DAY_4: Final[int] + DAY_5: Final[int] + DAY_6: Final[int] + DAY_7: Final[int] + + ERA: Final[int] + ERA_D_T_FMT: Final[int] + ERA_D_FMT: Final[int] + ERA_T_FMT: Final[int] + + MON_1: Final[int] + MON_2: Final[int] + MON_3: Final[int] + MON_4: Final[int] + MON_5: Final[int] + MON_6: Final[int] + MON_7: Final[int] + MON_8: Final[int] + MON_9: Final[int] + MON_10: Final[int] + MON_11: Final[int] + MON_12: Final[int] + + CODESET: Final[int] + D_T_FMT: Final[int] + D_FMT: Final[int] + T_FMT: Final[int] + T_FMT_AMPM: Final[int] + AM_STR: Final[int] + PM_STR: Final[int] + + RADIXCHAR: Final[int] + THOUSEP: Final[int] + YESEXPR: Final[int] + NOEXPR: Final[int] + CRNCYSTR: Final[int] + ALT_DIGITS: Final[int] + + def nl_langinfo(key: int, /) -> str: ... + + # This is dependent on `libintl.h` which is a part of `gettext` + # system dependency. These functions might be missing. + # But, we always say that they are present. + def gettext(msg: str, /) -> str: ... + def dgettext(domain: str | None, msg: str, /) -> str: ... + def dcgettext(domain: str | None, msg: str, category: int, /) -> str: ... + def textdomain(domain: str | None, /) -> str: ... + def bindtextdomain(domain: str, dir: StrPath | None, /) -> str: ... + def bind_textdomain_codeset(domain: str, codeset: str | None, /) -> str | None: ... diff --git a/stdlib/_lsprof.pyi b/stdlib/_lsprof.pyi new file mode 100644 index 000000000000..d04c2a74ee07 --- /dev/null +++ b/stdlib/_lsprof.pyi @@ -0,0 +1,34 @@ +from _typeshed import structseq +from collections.abc import Callable +from types import CodeType +from typing import Any, Final, final +from typing_extensions import disjoint_base + +@disjoint_base +class Profiler: + def __init__( + self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True + ) -> None: ... + def getstats(self) -> list[profiler_entry]: ... + def enable(self, subcalls: bool = True, builtins: bool = True) -> None: ... + def disable(self) -> None: ... + def clear(self) -> None: ... + +@final +class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float + calls: list[profiler_subentry] + +@final +class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]): + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime") + code: CodeType | str + callcount: int + reccallcount: int + totaltime: float + inlinetime: float diff --git a/stdlib/_lzma.pyi b/stdlib/_lzma.pyi new file mode 100644 index 000000000000..83cd8fd756b9 --- /dev/null +++ b/stdlib/_lzma.pyi @@ -0,0 +1,71 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping, Sequence +from typing import Any, Final, TypeAlias, final +from typing_extensions import Self + +_FilterChain: TypeAlias = Sequence[Mapping[str, Any]] + +FORMAT_AUTO: Final = 0 +FORMAT_XZ: Final = 1 +FORMAT_ALONE: Final = 2 +FORMAT_RAW: Final = 3 +CHECK_NONE: Final = 0 +CHECK_CRC32: Final = 1 +CHECK_CRC64: Final = 4 +CHECK_SHA256: Final = 10 +CHECK_ID_MAX: Final = 15 +CHECK_UNKNOWN: Final = 16 +FILTER_LZMA1: Final[int] # v big number +FILTER_LZMA2: Final = 33 +FILTER_DELTA: Final = 3 +FILTER_X86: Final = 4 +FILTER_IA64: Final = 6 +FILTER_ARM: Final = 7 +FILTER_ARMTHUMB: Final = 8 +FILTER_SPARC: Final = 9 +FILTER_POWERPC: Final = 5 +MF_HC3: Final = 3 +MF_HC4: Final = 4 +MF_BT2: Final = 18 +MF_BT3: Final = 19 +MF_BT4: Final = 20 +MODE_FAST: Final = 1 +MODE_NORMAL: Final = 2 +PRESET_DEFAULT: Final = 6 +PRESET_EXTREME: Final[int] # v big number + +@final +class LZMADecompressor: + if sys.version_info >= (3, 12): + def __new__(cls, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> Self: ... + else: + def __init__(self, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> None: ... + + def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def check(self) -> int: ... + @property + def eof(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + @property + def needs_input(self) -> bool: ... + +@final +class LZMACompressor: + if sys.version_info >= (3, 12): + def __new__( + cls, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None + ) -> Self: ... + else: + def __init__( + self, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None + ) -> None: ... + + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self) -> bytes: ... + +class LZMAError(Exception): ... + +def is_check_supported(check_id: int, /) -> bool: ... diff --git a/stdlib/_markupbase.pyi b/stdlib/_markupbase.pyi new file mode 100644 index 000000000000..acc3ccac7188 --- /dev/null +++ b/stdlib/_markupbase.pyi @@ -0,0 +1,10 @@ +class ParserBase: + def reset(self) -> None: ... + def getpos(self) -> tuple[int, int]: ... + def unknown_decl(self, data: str) -> None: ... + def parse_comment(self, i: int, report: bool = True) -> int: ... # undocumented + def parse_declaration(self, i: int) -> int: ... # undocumented + def parse_marked_section(self, i: int, report: bool = True) -> int: ... # undocumented + def updatepos(self, i: int, j: int) -> int: ... # undocumented + lineno: int # undocumented + offset: int # undocumented diff --git a/stdlib/_msi.pyi b/stdlib/_msi.pyi new file mode 100644 index 000000000000..e5b408811ee7 --- /dev/null +++ b/stdlib/_msi.pyi @@ -0,0 +1,97 @@ +import sys +from typing import Final, type_check_only + +if sys.platform == "win32": + class MSIError(Exception): ... + # Actual typename View, not exposed by the implementation + @type_check_only + class _View: + def Execute(self, params: _Record | None = ...) -> None: ... + def GetColumnInfo(self, kind: int) -> _Record: ... + def Fetch(self) -> _Record: ... + def Modify(self, mode: int, record: _Record) -> None: ... + def Close(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + # Actual typename SummaryInformation, not exposed by the implementation + @type_check_only + class _SummaryInformation: + def GetProperty(self, field: int) -> int | bytes | None: ... + def GetPropertyCount(self) -> int: ... + def SetProperty(self, field: int, value: int | str) -> None: ... + def Persist(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + # Actual typename Database, not exposed by the implementation + @type_check_only + class _Database: + def OpenView(self, sql: str) -> _View: ... + def Commit(self) -> None: ... + def GetSummaryInformation(self, updateCount: int) -> _SummaryInformation: ... + def Close(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + # Actual typename Record, not exposed by the implementation + @type_check_only + class _Record: + def GetFieldCount(self) -> int: ... + def GetInteger(self, field: int) -> int: ... + def GetString(self, field: int) -> str: ... + def SetString(self, field: int, str: str) -> None: ... + def SetStream(self, field: int, stream: str) -> None: ... + def SetInteger(self, field: int, int: int) -> None: ... + def ClearData(self) -> None: ... + # Don't exist at runtime + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] + + def UuidCreate() -> str: ... + def FCICreate(cabname: str, files: list[tuple[str, str]], /) -> None: ... + def OpenDatabase(path: str, persist: int, /) -> _Database: ... + def CreateRecord(count: int, /) -> _Record: ... + + MSICOLINFO_NAMES: Final[int] + MSICOLINFO_TYPES: Final[int] + MSIDBOPEN_CREATE: Final[int] + MSIDBOPEN_CREATEDIRECT: Final[int] + MSIDBOPEN_DIRECT: Final[int] + MSIDBOPEN_PATCHFILE: Final[int] + MSIDBOPEN_READONLY: Final[int] + MSIDBOPEN_TRANSACT: Final[int] + MSIMODIFY_ASSIGN: Final[int] + MSIMODIFY_DELETE: Final[int] + MSIMODIFY_INSERT: Final[int] + MSIMODIFY_INSERT_TEMPORARY: Final[int] + MSIMODIFY_MERGE: Final[int] + MSIMODIFY_REFRESH: Final[int] + MSIMODIFY_REPLACE: Final[int] + MSIMODIFY_SEEK: Final[int] + MSIMODIFY_UPDATE: Final[int] + MSIMODIFY_VALIDATE: Final[int] + MSIMODIFY_VALIDATE_DELETE: Final[int] + MSIMODIFY_VALIDATE_FIELD: Final[int] + MSIMODIFY_VALIDATE_NEW: Final[int] + + PID_APPNAME: Final[int] + PID_AUTHOR: Final[int] + PID_CHARCOUNT: Final[int] + PID_CODEPAGE: Final[int] + PID_COMMENTS: Final[int] + PID_CREATE_DTM: Final[int] + PID_KEYWORDS: Final[int] + PID_LASTAUTHOR: Final[int] + PID_LASTPRINTED: Final[int] + PID_LASTSAVE_DTM: Final[int] + PID_PAGECOUNT: Final[int] + PID_REVNUMBER: Final[int] + PID_SECURITY: Final[int] + PID_SUBJECT: Final[int] + PID_TEMPLATE: Final[int] + PID_TITLE: Final[int] + PID_WORDCOUNT: Final[int] diff --git a/stdlib/_multibytecodec.pyi b/stdlib/_multibytecodec.pyi new file mode 100644 index 000000000000..abe58cb64f31 --- /dev/null +++ b/stdlib/_multibytecodec.pyi @@ -0,0 +1,49 @@ +from _typeshed import ReadableBuffer +from codecs import _ReadableStream, _WritableStream +from collections.abc import Iterable +from typing import final, type_check_only +from typing_extensions import disjoint_base + +# This class is not exposed. It calls itself _multibytecodec.MultibyteCodec. +@final +@type_check_only +class _MultibyteCodec: + def decode(self, input: ReadableBuffer, errors: str | None = None) -> str: ... + def encode(self, input: str, errors: str | None = None) -> bytes: ... + +@disjoint_base +class MultibyteIncrementalDecoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + def getstate(self) -> tuple[bytes, int]: ... + def reset(self) -> None: ... + def setstate(self, state: tuple[bytes, int], /) -> None: ... + +@disjoint_base +class MultibyteIncrementalEncoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + def getstate(self) -> int: ... + def reset(self) -> None: ... + def setstate(self, state: int, /) -> None: ... + +@disjoint_base +class MultibyteStreamReader: + errors: str + stream: _ReadableStream + def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: ... + def read(self, sizeobj: int | None = None, /) -> str: ... + def readline(self, sizeobj: int | None = None, /) -> str: ... + def readlines(self, sizehintobj: int | None = None, /) -> list[str]: ... + def reset(self) -> None: ... + +@disjoint_base +class MultibyteStreamWriter: + errors: str + stream: _WritableStream + def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: ... + def reset(self) -> None: ... + def write(self, strobj: str, /) -> None: ... + def writelines(self, lines: Iterable[str], /) -> None: ... diff --git a/stdlib/_operator.pyi b/stdlib/_operator.pyi new file mode 100644 index 000000000000..04dae79dcd52 --- /dev/null +++ b/stdlib/_operator.pyi @@ -0,0 +1,157 @@ +import sys +from _typeshed import ( + SupportsAdd, + SupportsGetItem, + SupportsMod, + SupportsMul, + SupportsRAdd, + SupportsRMod, + SupportsRMul, + SupportsRSub, + SupportsSub, +) +from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence +from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller +from typing import Any, AnyStr, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import TypeIs + +_R = TypeVar("_R") +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) +_K = TypeVar("_K") +_V = TypeVar("_V") +_P = ParamSpec("_P") + +# The following protocols return "Any" instead of bool, since the comparison +# operators can be overloaded to return an arbitrary object. For example, +# the numpy.array comparison dunders return another numpy.array. + +@type_check_only +class _SupportsDunderLT(Protocol): + def __lt__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderGT(Protocol): + def __gt__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderLE(Protocol): + def __le__(self, other: Any, /) -> Any: ... + +@type_check_only +class _SupportsDunderGE(Protocol): + def __ge__(self, other: Any, /) -> Any: ... + +_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT + +@type_check_only +class _SupportsInversion(Protocol[_T_co]): + def __invert__(self) -> _T_co: ... + +@type_check_only +class _SupportsNeg(Protocol[_T_co]): + def __neg__(self) -> _T_co: ... + +@type_check_only +class _SupportsPos(Protocol[_T_co]): + def __pos__(self) -> _T_co: ... + +# All four comparison functions must have the same signature, or we get false-positive errors +def lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def eq(a: object, b: object, /) -> Any: ... +def ne(a: object, b: object, /) -> Any: ... +def ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ... +def not_(a: object, /) -> bool: ... +def truth(a: object, /) -> bool: ... +def is_(a: object, b: object, /) -> bool: ... +def is_not(a: object, b: object, /) -> bool: ... +def abs(a: SupportsAbs[_T], /) -> _T: ... + +@overload +def add(a: SupportsAdd[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def add(a: _T_contra, b: SupportsRAdd[_T_contra, _T_co], /) -> _T_co: ... + +def and_(a, b, /): ... +def floordiv(a, b, /): ... +def index(a: SupportsIndex, /) -> int: ... +def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ... +def lshift(a, b, /): ... + +@overload +def mod(a: SupportsMod[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mod(a: _T_contra, b: SupportsRMod[_T_contra, _T_co], /) -> _T_co: ... + +@overload +def mul(a: SupportsMul[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mul(a: _T_contra, b: SupportsRMul[_T_contra, _T_co], /) -> _T_co: ... + +def matmul(a, b, /): ... +def neg(a: _SupportsNeg[_T_co], /) -> _T_co: ... +def or_(a, b, /): ... +def pos(a: _SupportsPos[_T_co], /) -> _T_co: ... +def pow(a, b, /): ... +def rshift(a, b, /): ... + +@overload +def sub(a: SupportsSub[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def sub(a: _T_contra, b: SupportsRSub[_T_contra, _T_co], /) -> _T_co: ... + +def truediv(a, b, /): ... +def xor(a, b, /): ... +def concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: ... +def contains(a: Container[object], b: object, /) -> bool: ... +def countOf(a: Iterable[object], b: object, /) -> int: ... + +@overload +def delitem(a: MutableSequence[Any], b: int, /) -> None: ... +@overload +def delitem(a: MutableSequence[Any], b: slice[int | None], /) -> None: ... +@overload +def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ... + +@overload +def getitem(a: Sequence[_T], b: slice[int | None], /) -> Sequence[_T]: ... +@overload +def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... + +def indexOf(a: Iterable[_T], b: _T, /) -> int: ... + +@overload +def setitem(a: MutableSequence[_T], b: int, c: _T, /) -> None: ... +@overload +def setitem(a: MutableSequence[_T], b: slice[int | None], c: Sequence[_T], /) -> None: ... +@overload +def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... + +def length_hint(obj: object, default: int = 0, /) -> int: ... +def iadd(a, b, /): ... +def iand(a, b, /): ... +def iconcat(a, b, /): ... +def ifloordiv(a, b, /): ... +def ilshift(a, b, /): ... +def imod(a, b, /): ... +def imul(a, b, /): ... +def imatmul(a, b, /): ... +def ior(a, b, /): ... +def ipow(a, b, /): ... +def irshift(a, b, /): ... +def isub(a, b, /): ... +def itruediv(a, b, /): ... +def ixor(a, b, /): ... + +if sys.version_info >= (3, 11): + def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + +def _compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... + +if sys.version_info >= (3, 14): + def is_none(a: object, /) -> TypeIs[None]: ... + def is_not_none(a: _T | None, /) -> TypeIs[_T]: ... diff --git a/stdlib/_osx_support.pyi b/stdlib/_osx_support.pyi new file mode 100644 index 000000000000..fb00e6986dd0 --- /dev/null +++ b/stdlib/_osx_support.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterable, Sequence +from typing import Final, TypeVar + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +__all__ = ["compiler_fixup", "customize_config_vars", "customize_compiler", "get_platform_osx"] + +_UNIVERSAL_CONFIG_VARS: Final[tuple[str, ...]] # undocumented +_COMPILER_CONFIG_VARS: Final[tuple[str, ...]] # undocumented +_INITPRE: Final[str] # undocumented + +def _find_executable(executable: str, path: str | None = None) -> str | None: ... # undocumented +def _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: ... # undocumented +def _find_build_tool(toolname: str) -> str: ... # undocumented + +_SYSTEM_VERSION: Final[str | None] # undocumented + +def _get_system_version() -> str: ... # undocumented +def _remove_original_values(_config_vars: dict[str, str]) -> None: ... # undocumented +def _save_modified_value(_config_vars: dict[str, str], cv: str, newvalue: str) -> None: ... # undocumented +def _supports_universal_builds() -> bool: ... # undocumented +def _find_appropriate_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _remove_universal_flags(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _remove_unsupported_archs(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _override_all_archs(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _check_for_unavailable_sdk(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[str]: ... +def customize_config_vars(_config_vars: dict[str, str]) -> dict[str, str]: ... +def customize_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ... +def get_platform_osx( + _config_vars: dict[str, str], osname: _T, release: _K, machine: _V +) -> tuple[str | _T, str | _K, str | _V]: ... diff --git a/stdlib/_pickle.pyi b/stdlib/_pickle.pyi new file mode 100644 index 000000000000..f8411c6abc4b --- /dev/null +++ b/stdlib/_pickle.pyi @@ -0,0 +1,114 @@ +from _typeshed import ReadableBuffer, SupportsWrite +from collections.abc import Callable, Iterable, Iterator, Mapping +from pickle import PickleBuffer as PickleBuffer +from typing import Any, Protocol, TypeAlias, type_check_only +from typing_extensions import disjoint_base + +@type_check_only +class _ReadableFileobj(Protocol): + def read(self, n: int, /) -> bytes: ... + def readline(self) -> bytes: ... + +_BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None + +_ReducedType: TypeAlias = ( + str + | tuple[Callable[..., Any], tuple[Any, ...]] + | tuple[Callable[..., Any], tuple[Any, ...], Any] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None] + | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None] +) + +def dump( + obj: Any, + file: SupportsWrite[bytes], + protocol: int | None = None, + *, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, +) -> None: ... +def dumps( + obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None +) -> bytes: ... +def load( + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... +def loads( + data: ReadableBuffer, + /, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), +) -> Any: ... + +class PickleError(Exception): ... +class PicklingError(PickleError): ... +class UnpicklingError(PickleError): ... + +@type_check_only +class PicklerMemoProxy: + def clear(self, /) -> None: ... + def copy(self, /) -> dict[int, tuple[int, Any]]: ... + +@disjoint_base +class Pickler: + fast: bool + dispatch_table: Mapping[type, Callable[[Any], _ReducedType]] + bin: bool # undocumented + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + ) -> None: ... + + @property + def memo(self) -> PicklerMemoProxy: ... + @memo.setter + def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + + def dump(self, obj: Any, /) -> None: ... + def clear_memo(self) -> None: ... + + # this method has no default implementation for Python < 3.13 + def persistent_id(self, obj: Any, /) -> Any: ... + # The following method is not defined on _Pickler, but can be defined on + # sub-classes. Should return `NotImplemented` if pickling the supplied + # object is not supported and returns the same types as `__reduce__()`. + def reducer_override(self, obj: object, /) -> _ReducedType: ... + +@type_check_only +class UnpicklerMemoProxy: + def clear(self, /) -> None: ... + def copy(self, /) -> dict[int, tuple[int, Any]]: ... + +@disjoint_base +class Unpickler: + def __init__( + self, + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = (), + ) -> None: ... + + @property + def memo(self) -> UnpicklerMemoProxy: ... + @memo.setter + def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + + def load(self) -> Any: ... + def find_class(self, module_name: str, global_name: str, /) -> Any: ... + + # this method has no default implementation for Python < 3.13 + def persistent_load(self, pid: Any, /) -> Any: ... diff --git a/stdlib/_posixsubprocess.pyi b/stdlib/_posixsubprocess.pyi new file mode 100644 index 000000000000..dd74e316e899 --- /dev/null +++ b/stdlib/_posixsubprocess.pyi @@ -0,0 +1,59 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Sequence +from typing import SupportsIndex + +if sys.platform != "win32": + if sys.version_info >= (3, 14): + def fork_exec( + args: Sequence[StrOrBytesPath] | None, + executable_list: Sequence[bytes], + close_fds: bool, + pass_fds: tuple[int, ...], + cwd: str, + env: Sequence[bytes] | None, + p2cread: int, + p2cwrite: int, + c2pread: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: int, + call_setsid: int, + pgid_to_set: int, + gid: SupportsIndex | None, + extra_groups: list[int] | None, + uid: SupportsIndex | None, + child_umask: int, + preexec_fn: Callable[[], None], + /, + ) -> int: ... + else: + def fork_exec( + args: Sequence[StrOrBytesPath] | None, + executable_list: Sequence[bytes], + close_fds: bool, + pass_fds: tuple[int, ...], + cwd: str, + env: Sequence[bytes] | None, + p2cread: int, + p2cwrite: int, + c2pread: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: bool, + call_setsid: bool, + pgid_to_set: int, + gid: SupportsIndex | None, + extra_groups: list[int] | None, + uid: SupportsIndex | None, + child_umask: int, + preexec_fn: Callable[[], None], + allow_vfork: bool, + /, + ) -> int: ... diff --git a/stdlib/_py_abc.pyi b/stdlib/_py_abc.pyi new file mode 100644 index 000000000000..1260717489e4 --- /dev/null +++ b/stdlib/_py_abc.pyi @@ -0,0 +1,14 @@ +import _typeshed +from typing import Any, NewType, TypeVar + +_T = TypeVar("_T") + +_CacheToken = NewType("_CacheToken", int) + +def get_cache_token() -> _CacheToken: ... + +class ABCMeta(type): + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], / + ) -> _typeshed.Self: ... + def register(cls, subclass: type[_T]) -> type[_T]: ... diff --git a/stdlib/_pydecimal.pyi b/stdlib/_pydecimal.pyi new file mode 100644 index 000000000000..9fabcc640096 --- /dev/null +++ b/stdlib/_pydecimal.pyi @@ -0,0 +1,50 @@ +# This is a slight lie, the implementations aren't exactly identical +# However, in all likelihood, the differences are inconsequential +import sys +from _decimal import * + +__all__ = [ + "Decimal", + "Context", + "DecimalTuple", + "DefaultContext", + "BasicContext", + "ExtendedContext", + "DecimalException", + "Clamped", + "InvalidOperation", + "DivisionByZero", + "Inexact", + "Rounded", + "Subnormal", + "Overflow", + "Underflow", + "FloatOperation", + "DivisionImpossible", + "InvalidContext", + "ConversionSyntax", + "DivisionUndefined", + "ROUND_DOWN", + "ROUND_HALF_UP", + "ROUND_HALF_EVEN", + "ROUND_CEILING", + "ROUND_FLOOR", + "ROUND_UP", + "ROUND_HALF_DOWN", + "ROUND_05UP", + "setcontext", + "getcontext", + "localcontext", + "MAX_PREC", + "MAX_EMAX", + "MIN_EMIN", + "MIN_ETINY", + "HAVE_THREADS", + "HAVE_CONTEXTVAR", +] + +if sys.version_info >= (3, 14): + __all__ += ["IEEEContext", "IEEE_CONTEXT_MAX_BITS"] + +if sys.version_info >= (3, 15): + __all__ += ["SPEC_VERSION"] diff --git a/stdlib/_queue.pyi b/stdlib/_queue.pyi new file mode 100644 index 000000000000..edd484a9a71a --- /dev/null +++ b/stdlib/_queue.pyi @@ -0,0 +1,18 @@ +from types import GenericAlias +from typing import Any, Generic, TypeVar +from typing_extensions import disjoint_base + +_T = TypeVar("_T") + +class Empty(Exception): ... + +@disjoint_base +class SimpleQueue(Generic[_T]): + def __init__(self) -> None: ... + def empty(self) -> bool: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def qsize(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/_random.pyi b/stdlib/_random.pyi new file mode 100644 index 000000000000..e333b00d1084 --- /dev/null +++ b/stdlib/_random.pyi @@ -0,0 +1,14 @@ +from typing import TypeAlias +from typing_extensions import disjoint_base + +# Actually Tuple[(int,) * 625] +_State: TypeAlias = tuple[int, ...] + +@disjoint_base +class Random: + def __init__(self, seed: object = ..., /) -> None: ... + def seed(self, n: object = None, /) -> None: ... + def getstate(self) -> _State: ... + def setstate(self, state: _State, /) -> None: ... + def random(self) -> float: ... + def getrandbits(self, k: int, /) -> int: ... diff --git a/stdlib/_remote_debugging.pyi b/stdlib/_remote_debugging.pyi new file mode 100644 index 000000000000..b001962aad7b --- /dev/null +++ b/stdlib/_remote_debugging.pyi @@ -0,0 +1,183 @@ +from _typeshed import StrOrBytesPath, structseq +from collections.abc import Callable +from typing import Final, TypeAlias, final +from typing_extensions import Self + +_Location: TypeAlias = tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = tuple[str, _Location, str, int | None] | FrameInfo +_Stats: TypeAlias = dict[str, int | float] + +PROCESS_VM_READV_SUPPORTED: Final[int] +THREAD_STATUS_GIL_REQUESTED: Final[int] +THREAD_STATUS_HAS_EXCEPTION: Final[int] +THREAD_STATUS_HAS_GIL: Final[int] +THREAD_STATUS_MAIN_THREAD: Final[int] +THREAD_STATUS_ON_CPU: Final[int] +THREAD_STATUS_UNKNOWN: Final[int] + +@final +class LocationInfo(structseq[int], tuple[int, int, int, int]): + __match_args__: Final = ("lineno", "end_lineno", "col_offset", "end_col_offset") + @property + def lineno(self) -> int: ... + @property + def end_lineno(self) -> int: ... + @property + def col_offset(self) -> int: ... + @property + def end_col_offset(self) -> int: ... + +@final +class FrameInfo(structseq[object], tuple[str, _Location, str, int | None]): + __match_args__: Final = ("filename", "location", "funcname", "opcode") + @property + def filename(self) -> str: ... + @property + def location(self) -> _Location: ... + @property + def funcname(self) -> str: ... + @property + def opcode(self) -> int | None: ... + +@final +class CoroInfo(structseq[object], tuple[list[_Frame], int | str]): + __match_args__: Final = ("call_stack", "task_name") + @property + def call_stack(self) -> list[_Frame]: ... + @property + def task_name(self) -> int | str: ... + +@final +class TaskInfo(structseq[object], tuple[int, str, list[CoroInfo], list[CoroInfo]]): + __match_args__: Final = ("task_id", "task_name", "coroutine_stack", "awaited_by") + @property + def task_id(self) -> int: ... + @property + def task_name(self) -> str: ... + @property + def coroutine_stack(self) -> list[CoroInfo]: ... + @property + def awaited_by(self) -> list[CoroInfo]: ... + +@final +class ThreadInfo(structseq[object], tuple[int, int, list[_Frame]]): + __match_args__: Final = ("thread_id", "status", "frame_info") + @property + def thread_id(self) -> int: ... + @property + def status(self) -> int: ... + @property + def frame_info(self) -> list[_Frame]: ... + +@final +class InterpreterInfo(structseq[object], tuple[int, list[ThreadInfo]]): + __match_args__: Final = ("interpreter_id", "threads") + @property + def interpreter_id(self) -> int: ... + @property + def threads(self) -> list[ThreadInfo]: ... + +@final +class AwaitedInfo(structseq[object], tuple[int, list[TaskInfo]]): + __match_args__: Final = ("thread_id", "awaited_by") + @property + def thread_id(self) -> int: ... + @property + def awaited_by(self) -> list[TaskInfo]: ... + +@final +class GCStatsInfo(structseq[object], tuple[int, int, int, int, int, int, int, int, int, float]): + __match_args__: Final = ( + "gen", + "iid", + "ts_start", + "ts_stop", + "collections", + "collected", + "uncollectable", + "candidates", + "heap_size", + "duration", + ) + @property + def gen(self) -> int: ... + @property + def iid(self) -> int: ... + @property + def ts_start(self) -> int: ... + @property + def ts_stop(self) -> int: ... + @property + def collections(self) -> int: ... + @property + def collected(self) -> int: ... + @property + def uncollectable(self) -> int: ... + @property + def candidates(self) -> int: ... + @property + def heap_size(self) -> int: ... + @property + def duration(self) -> float: ... + +@final +class RemoteUnwinder: + def __init__( + self, + pid: int, + *, + all_threads: bool = False, + only_active_thread: bool = False, + mode: int = 0, + debug: bool = False, + skip_non_matching_threads: bool = True, + native: bool = False, + gc: bool = False, + opcodes: bool = False, + cache_frames: bool = False, + stats: bool = False, + ) -> None: ... + def get_stack_trace(self) -> list[InterpreterInfo]: ... + def get_all_awaited_by(self) -> list[AwaitedInfo]: ... + def get_async_stack_trace(self) -> list[AwaitedInfo]: ... + def get_stats(self) -> _Stats: ... + def pause_threads(self) -> bool: ... + def resume_threads(self) -> bool: ... + +@final +class GCMonitor: + def __init__(self, pid: int, *, debug: bool = False) -> None: ... + def get_gc_stats(self, all_interpreters: bool = False) -> list[GCStatsInfo]: ... + +@final +class BinaryWriter: + def __init__( + self, filename: StrOrBytesPath, sample_interval_us: int, start_time_us: int, *, compression: int = 0 + ) -> None: ... + @property + def total_samples(self) -> int: ... + def write_sample(self, stack_frames: list[InterpreterInfo], timestamp_us: int) -> None: ... + def finalize(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + def get_stats(self) -> _Stats: ... + +@final +class BinaryReader: + def __init__(self, filename: StrOrBytesPath) -> None: ... + @property + def sample_count(self) -> int: ... + @property + def sample_interval_us(self) -> int: ... + def replay(self, collector: object, progress_callback: Callable[[int, int], object] | None = None) -> int: ... + def get_info(self) -> dict[str, object]: ... + def get_stats(self) -> _Stats: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + +def zstd_available() -> bool: ... +def get_child_pids(pid: int, *, recursive: bool = True) -> list[int]: ... +def is_python_process(pid: int) -> bool: ... +def get_gc_stats(pid: int, *, all_interpreters: bool = False) -> list[GCStatsInfo]: ... diff --git a/stdlib/_sitebuiltins.pyi b/stdlib/_sitebuiltins.pyi new file mode 100644 index 000000000000..99abd02386b2 --- /dev/null +++ b/stdlib/_sitebuiltins.pyi @@ -0,0 +1,18 @@ +import sys +from collections.abc import Iterable +from typing import ClassVar, Literal +from typing_extensions import Never + +class Quitter: + name: str + eof: str + def __init__(self, name: str, eof: str) -> None: ... + def __call__(self, code: sys._ExitCode = None) -> Never: ... + +class _Printer: + MAXLINES: ClassVar[Literal[23]] + def __init__(self, name: str, data: str, files: Iterable[str] = (), dirs: Iterable[str] = ()) -> None: ... + def __call__(self) -> None: ... + +class _Helper: + def __call__(self, request: object = ...) -> None: ... diff --git a/stdlib/_socket.pyi b/stdlib/_socket.pyi new file mode 100644 index 000000000000..4450d46e6027 --- /dev/null +++ b/stdlib/_socket.pyi @@ -0,0 +1,966 @@ +import sys +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Iterable +from socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout +from typing import Any, Final, SupportsIndex, TypeAlias, overload +from typing_extensions import CapsuleType, disjoint_base + +_CMSG: TypeAlias = tuple[int, int, bytes] +_CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] + +# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, +# AF_NETLINK, AF_TIPC) or strings/buffers (AF_UNIX). +# See getsockaddrarg() in socketmodule.c. +if sys.version_info >= (3, 14): + # A bare int is accepted for Bluetooth HCI device IDs. + _Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer | int +else: + _Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer +_RetAddress: TypeAlias = Any + +# ===== Constants ===== +# This matches the order in the CPython documentation +# https://docs.python.org/3/library/socket.html#constants + +if sys.platform != "win32": + AF_UNIX: Final[int] + +AF_INET: Final[int] +AF_INET6: Final[int] + +AF_UNSPEC: Final[int] + +SOCK_STREAM: Final[int] +SOCK_DGRAM: Final[int] +SOCK_RAW: Final[int] +SOCK_RDM: Final[int] +SOCK_SEQPACKET: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.27 + SOCK_CLOEXEC: Final[int] + SOCK_NONBLOCK: Final[int] + +# -------------------- +# Many constants of these forms, documented in the Unix documentation on +# sockets and/or the IP protocol, are also defined in the socket module. +# SO_* +# socket.SOMAXCONN +# MSG_* +# SOL_* +# SCM_* +# IPPROTO_* +# IPPORT_* +# INADDR_* +# IP_* +# IPV6_* +# EAI_* +# AI_* +# NI_* +# TCP_* +# -------------------- + +SO_ACCEPTCONN: Final[int] +SO_BROADCAST: Final[int] +SO_DEBUG: Final[int] +SO_DONTROUTE: Final[int] +SO_ERROR: Final[int] +SO_KEEPALIVE: Final[int] +SO_LINGER: Final[int] +SO_OOBINLINE: Final[int] +SO_RCVBUF: Final[int] +SO_RCVLOWAT: Final[int] +SO_RCVTIMEO: Final[int] +SO_REUSEADDR: Final[int] +SO_SNDBUF: Final[int] +SO_SNDLOWAT: Final[int] +SO_SNDTIMEO: Final[int] +SO_TYPE: Final[int] +if sys.platform != "linux": + SO_USELOOPBACK: Final[int] +if sys.platform == "win32": + SO_EXCLUSIVEADDRUSE: Final[int] +if sys.platform != "win32": + SO_REUSEPORT: Final[int] + if sys.platform != "darwin" or sys.version_info >= (3, 13): + SO_BINDTODEVICE: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + SO_DOMAIN: Final[int] + SO_MARK: Final[int] + SO_PASSCRED: Final[int] + SO_PASSSEC: Final[int] + SO_PEERCRED: Final[int] + SO_PEERSEC: Final[int] + SO_PRIORITY: Final[int] + SO_PROTOCOL: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + SO_SETFIB: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 13): + SO_BINDTOIFINDEX: Final[int] + +SOMAXCONN: Final[int] + +MSG_CTRUNC: Final[int] +MSG_DONTROUTE: Final[int] +MSG_OOB: Final[int] +MSG_PEEK: Final[int] +MSG_TRUNC: Final[int] +MSG_WAITALL: Final[int] +if sys.platform != "win32": + MSG_DONTWAIT: Final[int] + MSG_EOR: Final[int] + MSG_NOSIGNAL: Final[int] # Sometimes this exists on darwin, sometimes not +if sys.platform != "darwin": + MSG_ERRQUEUE: Final[int] +if sys.platform == "win32": + MSG_BCAST: Final[int] + MSG_MCAST: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC: Final[int] + MSG_CONFIRM: Final[int] + MSG_FASTOPEN: Final[int] + MSG_MORE: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF: Final[int] +if sys.platform != "win32" and sys.platform != "linux" and sys.platform != "darwin": + MSG_NOTIFICATION: Final[int] + MSG_BTAG: Final[int] # Not FreeBSD either + MSG_ETAG: Final[int] # Not FreeBSD either + +SOL_IP: Final[int] +SOL_SOCKET: Final[int] +SOL_TCP: Final[int] +SOL_UDP: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + # Defined in socket.h for Linux, but these aren't always present for + # some reason. + SOL_ATALK: Final[int] + SOL_AX25: Final[int] + SOL_HCI: Final[int] + SOL_IPX: Final[int] + SOL_NETROM: Final[int] + SOL_ROSE: Final[int] + +if sys.platform != "win32": + SCM_RIGHTS: Final[int] +if sys.platform != "win32" and sys.platform != "darwin": + SCM_CREDENTIALS: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + SCM_CREDS: Final[int] + +IPPROTO_ICMP: Final[int] +IPPROTO_IP: Final[int] +IPPROTO_RAW: Final[int] +IPPROTO_TCP: Final[int] +IPPROTO_UDP: Final[int] +IPPROTO_AH: Final[int] +IPPROTO_DSTOPTS: Final[int] +IPPROTO_EGP: Final[int] +IPPROTO_ESP: Final[int] +IPPROTO_FRAGMENT: Final[int] +IPPROTO_HOPOPTS: Final[int] +IPPROTO_ICMPV6: Final[int] +IPPROTO_IDP: Final[int] +IPPROTO_IGMP: Final[int] +IPPROTO_IPV6: Final[int] +IPPROTO_NONE: Final[int] +IPPROTO_PIM: Final[int] +IPPROTO_PUP: Final[int] +IPPROTO_ROUTING: Final[int] +IPPROTO_SCTP: Final[int] +if sys.platform != "linux": + IPPROTO_GGP: Final[int] + IPPROTO_IPV4: Final[int] + IPPROTO_MAX: Final[int] + IPPROTO_ND: Final[int] +if sys.platform == "win32": + IPPROTO_CBT: Final[int] + IPPROTO_ICLFXBM: Final[int] + IPPROTO_IGP: Final[int] + IPPROTO_L2TP: Final[int] + IPPROTO_PGM: Final[int] + IPPROTO_RDP: Final[int] + IPPROTO_ST: Final[int] +if sys.platform != "win32": + IPPROTO_GRE: Final[int] + IPPROTO_IPIP: Final[int] + IPPROTO_RSVP: Final[int] + IPPROTO_TP: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + IPPROTO_EON: Final[int] + IPPROTO_HELLO: Final[int] + IPPROTO_IPCOMP: Final[int] + IPPROTO_XTP: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + IPPROTO_BIP: Final[int] # Not FreeBSD either + IPPROTO_MOBILE: Final[int] # Not FreeBSD either + IPPROTO_VRRP: Final[int] # Not FreeBSD either +if sys.platform == "linux": + # Availability: Linux >= 2.6.20, FreeBSD >= 10.1 + IPPROTO_UDPLITE: Final[int] +if sys.platform == "linux": + IPPROTO_MPTCP: Final[int] + +IPPORT_RESERVED: Final[int] +IPPORT_USERRESERVED: Final[int] + +INADDR_ALLHOSTS_GROUP: Final[int] +INADDR_ANY: Final[int] +INADDR_BROADCAST: Final[int] +INADDR_LOOPBACK: Final[int] +INADDR_MAX_LOCAL_GROUP: Final[int] +INADDR_NONE: Final[int] +INADDR_UNSPEC_GROUP: Final[int] + +IP_ADD_MEMBERSHIP: Final[int] +IP_DROP_MEMBERSHIP: Final[int] +IP_HDRINCL: Final[int] +IP_MULTICAST_IF: Final[int] +IP_MULTICAST_LOOP: Final[int] +IP_MULTICAST_TTL: Final[int] +IP_OPTIONS: Final[int] +if sys.platform != "linux": + IP_RECVDSTADDR: Final[int] +IP_RECVTOS: Final[int] +IP_TOS: Final[int] +IP_TTL: Final[int] +if sys.platform != "win32": + IP_DEFAULT_MULTICAST_LOOP: Final[int] + IP_DEFAULT_MULTICAST_TTL: Final[int] + IP_MAX_MEMBERSHIPS: Final[int] + IP_RECVOPTS: Final[int] + IP_RECVRETOPTS: Final[int] + IP_RETOPTS: Final[int] +if sys.version_info >= (3, 13) and sys.platform == "linux": + CAN_RAW_ERR_FILTER: Final[int] +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + IPV6_HDRINCL: Final[int] +if sys.version_info >= (3, 14): + IP_RECVTTL: Final[int] + + if sys.platform == "win32" or sys.platform == "linux": + IPV6_RECVERR: Final[int] + IP_RECVERR: Final[int] + SO_ORIGINAL_DST: Final[int] + + if sys.platform == "win32": + SOL_RFCOMM: Final[int] + SO_BTH_ENCRYPT: Final[int] + SO_BTH_MTU: Final[int] + SO_BTH_MTU_MAX: Final[int] + SO_BTH_MTU_MIN: Final[int] + TCP_QUICKACK: Final[int] + + if sys.platform == "linux": + BDADDR_BREDR: Final[int] + BDADDR_LE_PUBLIC: Final[int] + BDADDR_LE_RANDOM: Final[int] + BT_CHANNEL_POLICY: Final[int] + BT_CHANNEL_POLICY_BREDR_ONLY: Final[int] + BT_CHANNEL_POLICY_BREDR_PREFERRED: Final[int] + BT_CODEC: Final[int] + BT_DEFER_SETUP: Final[int] + BT_FLUSHABLE: Final[int] + BT_FLUSHABLE_OFF: Final[int] + BT_FLUSHABLE_ON: Final[int] + BT_ISO_QOS: Final[int] + BT_MODE: Final[int] + BT_MODE_BASIC: Final[int] + BT_MODE_ERTM: Final[int] + BT_MODE_EXT_FLOWCTL: Final[int] + BT_MODE_LE_FLOWCTL: Final[int] + BT_MODE_STREAMING: Final[int] + BT_PHY: Final[int] + BT_PHY_BR_1M_1SLOT: Final[int] + BT_PHY_BR_1M_3SLOT: Final[int] + BT_PHY_BR_1M_5SLOT: Final[int] + BT_PHY_EDR_2M_1SLOT: Final[int] + BT_PHY_EDR_2M_3SLOT: Final[int] + BT_PHY_EDR_2M_5SLOT: Final[int] + BT_PHY_EDR_3M_1SLOT: Final[int] + BT_PHY_EDR_3M_3SLOT: Final[int] + BT_PHY_EDR_3M_5SLOT: Final[int] + BT_PHY_LE_1M_RX: Final[int] + BT_PHY_LE_1M_TX: Final[int] + BT_PHY_LE_2M_RX: Final[int] + BT_PHY_LE_2M_TX: Final[int] + BT_PHY_LE_CODED_RX: Final[int] + BT_PHY_LE_CODED_TX: Final[int] + BT_PKT_STATUS: Final[int] + BT_POWER: Final[int] + BT_POWER_FORCE_ACTIVE_OFF: Final[int] + BT_POWER_FORCE_ACTIVE_ON: Final[int] + BT_RCVMTU: Final[int] + BT_SECURITY: Final[int] + BT_SECURITY_FIPS: Final[int] + BT_SECURITY_HIGH: Final[int] + BT_SECURITY_LOW: Final[int] + BT_SECURITY_MEDIUM: Final[int] + BT_SECURITY_SDP: Final[int] + BT_SNDMTU: Final[int] + BT_VOICE: Final[int] + BT_VOICE_CVSD_16BIT: Final[int] + BT_VOICE_TRANSPARENT: Final[int] + BT_VOICE_TRANSPARENT_16BIT: Final[int] + HCI_CHANNEL_CONTROL: Final[int] + HCI_CHANNEL_LOGGING: Final[int] + HCI_CHANNEL_MONITOR: Final[int] + HCI_CHANNEL_RAW: Final[int] + HCI_CHANNEL_USER: Final[int] + HCI_DEV_NONE: Final[int] + IP_FREEBIND: Final[int] + IP_RECVORIGDSTADDR: Final[int] + L2CAP_LM: Final[int] + L2CAP_LM_AUTH: Final[int] + L2CAP_LM_ENCRYPT: Final[int] + L2CAP_LM_MASTER: Final[int] + L2CAP_LM_RELIABLE: Final[int] + L2CAP_LM_SECURE: Final[int] + L2CAP_LM_TRUSTED: Final[int] + SOL_BLUETOOTH: Final[int] + SOL_L2CAP: Final[int] + SOL_RFCOMM: Final[int] + SOL_SCO: Final[int] + VMADDR_CID_LOCAL: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + IP_TRANSPARENT: Final[int] +if sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 11): + IP_BIND_ADDRESS_NO_PORT: Final[int] +if sys.version_info >= (3, 12): + IP_ADD_SOURCE_MEMBERSHIP: Final[int] + IP_BLOCK_SOURCE: Final[int] + IP_DROP_SOURCE_MEMBERSHIP: Final[int] + IP_PKTINFO: Final[int] + IP_UNBLOCK_SOURCE: Final[int] + +IPV6_CHECKSUM: Final[int] +IPV6_JOIN_GROUP: Final[int] +IPV6_LEAVE_GROUP: Final[int] +IPV6_MULTICAST_HOPS: Final[int] +IPV6_MULTICAST_IF: Final[int] +IPV6_MULTICAST_LOOP: Final[int] +IPV6_RECVTCLASS: Final[int] +IPV6_TCLASS: Final[int] +IPV6_UNICAST_HOPS: Final[int] +IPV6_V6ONLY: Final[int] +IPV6_DONTFRAG: Final[int] +IPV6_HOPLIMIT: Final[int] +IPV6_HOPOPTS: Final[int] +IPV6_PKTINFO: Final[int] +IPV6_RECVRTHDR: Final[int] +IPV6_RTHDR: Final[int] +if sys.platform != "win32": + IPV6_RTHDR_TYPE_0: Final[int] + IPV6_DSTOPTS: Final[int] + IPV6_NEXTHOP: Final[int] + IPV6_PATHMTU: Final[int] + IPV6_RECVDSTOPTS: Final[int] + IPV6_RECVHOPLIMIT: Final[int] + IPV6_RECVHOPOPTS: Final[int] + IPV6_RECVPATHMTU: Final[int] + IPV6_RECVPKTINFO: Final[int] + IPV6_RTHDRDSTOPTS: Final[int] + +if sys.platform != "win32" and sys.platform != "linux": + IPV6_USE_MIN_MTU: Final[int] + +EAI_AGAIN: Final[int] +EAI_BADFLAGS: Final[int] +EAI_FAIL: Final[int] +EAI_FAMILY: Final[int] +EAI_MEMORY: Final[int] +EAI_NODATA: Final[int] +EAI_NONAME: Final[int] +EAI_SERVICE: Final[int] +EAI_SOCKTYPE: Final[int] +if sys.platform != "win32": + EAI_ADDRFAMILY: Final[int] + EAI_OVERFLOW: Final[int] + EAI_SYSTEM: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + EAI_BADHINTS: Final[int] + EAI_MAX: Final[int] + EAI_PROTOCOL: Final[int] + +AI_ADDRCONFIG: Final[int] +AI_ALL: Final[int] +AI_CANONNAME: Final[int] +AI_NUMERICHOST: Final[int] +AI_NUMERICSERV: Final[int] +AI_PASSIVE: Final[int] +AI_V4MAPPED: Final[int] +if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT: Final[int] + AI_MASK: Final[int] + AI_V4MAPPED_CFG: Final[int] + +NI_DGRAM: Final[int] +NI_MAXHOST: Final[int] +NI_MAXSERV: Final[int] +NI_NAMEREQD: Final[int] +NI_NOFQDN: Final[int] +NI_NUMERICHOST: Final[int] +NI_NUMERICSERV: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 13): + NI_IDN: Final[int] + +TCP_FASTOPEN: Final[int] +TCP_KEEPCNT: Final[int] +TCP_KEEPINTVL: Final[int] +TCP_MAXSEG: Final[int] +TCP_NODELAY: Final[int] +if sys.platform != "win32": + TCP_NOTSENT_LOWAT: Final[int] +if sys.platform != "darwin": + TCP_KEEPIDLE: Final[int] +if sys.platform == "darwin": + TCP_KEEPALIVE: Final[int] +if sys.version_info >= (3, 11) and sys.platform == "darwin": + TCP_CONNECTION_INFO: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + TCP_CONGESTION: Final[int] + TCP_CORK: Final[int] + TCP_DEFER_ACCEPT: Final[int] + TCP_INFO: Final[int] + TCP_LINGER2: Final[int] + TCP_QUICKACK: Final[int] + TCP_SYNCNT: Final[int] + TCP_USER_TIMEOUT: Final[int] + TCP_WINDOW_CLAMP: Final[int] +if sys.platform == "linux" and sys.version_info >= (3, 12): + TCP_CC_INFO: Final[int] + TCP_FASTOPEN_CONNECT: Final[int] + TCP_FASTOPEN_KEY: Final[int] + TCP_FASTOPEN_NO_COOKIE: Final[int] + TCP_INQ: Final[int] + TCP_MD5SIG: Final[int] + TCP_MD5SIG_EXT: Final[int] + TCP_QUEUE_SEQ: Final[int] + TCP_REPAIR: Final[int] + TCP_REPAIR_OPTIONS: Final[int] + TCP_REPAIR_QUEUE: Final[int] + TCP_REPAIR_WINDOW: Final[int] + TCP_SAVED_SYN: Final[int] + TCP_SAVE_SYN: Final[int] + TCP_THIN_DUPACK: Final[int] + TCP_THIN_LINEAR_TIMEOUTS: Final[int] + TCP_TIMESTAMP: Final[int] + TCP_TX_DELAY: Final[int] + TCP_ULP: Final[int] + TCP_ZEROCOPY_RECEIVE: Final[int] + +# -------------------- +# Specifically documented constants +# -------------------- + +if sys.platform == "linux": + # Availability: Linux >= 2.6.25, NetBSD >= 8 + AF_CAN: Final[int] + PF_CAN: Final[int] + SOL_CAN_BASE: Final[int] + SOL_CAN_RAW: Final[int] + CAN_EFF_FLAG: Final[int] + CAN_EFF_MASK: Final[int] + CAN_ERR_FLAG: Final[int] + CAN_ERR_MASK: Final[int] + CAN_RAW: Final[int] + CAN_RAW_FILTER: Final[int] + CAN_RAW_LOOPBACK: Final[int] + CAN_RAW_RECV_OWN_MSGS: Final[int] + CAN_RTR_FLAG: Final[int] + CAN_SFF_MASK: Final[int] + if sys.version_info < (3, 11): + CAN_RAW_ERR_FILTER: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.25 + CAN_BCM: Final[int] + CAN_BCM_TX_SETUP: Final[int] + CAN_BCM_TX_DELETE: Final[int] + CAN_BCM_TX_READ: Final[int] + CAN_BCM_TX_SEND: Final[int] + CAN_BCM_RX_SETUP: Final[int] + CAN_BCM_RX_DELETE: Final[int] + CAN_BCM_RX_READ: Final[int] + CAN_BCM_TX_STATUS: Final[int] + CAN_BCM_TX_EXPIRED: Final[int] + CAN_BCM_RX_STATUS: Final[int] + CAN_BCM_RX_TIMEOUT: Final[int] + CAN_BCM_RX_CHANGED: Final[int] + CAN_BCM_SETTIMER: Final[int] + CAN_BCM_STARTTIMER: Final[int] + CAN_BCM_TX_COUNTEVT: Final[int] + CAN_BCM_TX_ANNOUNCE: Final[int] + CAN_BCM_TX_CP_CAN_ID: Final[int] + CAN_BCM_RX_FILTER_ID: Final[int] + CAN_BCM_RX_CHECK_DLC: Final[int] + CAN_BCM_RX_NO_AUTOTIMER: Final[int] + CAN_BCM_RX_ANNOUNCE_RESUME: Final[int] + CAN_BCM_TX_RESET_MULTI_IDX: Final[int] + CAN_BCM_RX_RTR_FRAME: Final[int] + CAN_BCM_CAN_FD_FRAME: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 3.6 + CAN_RAW_FD_FRAMES: Final[int] + # Availability: Linux >= 4.1 + CAN_RAW_JOIN_FILTERS: Final[int] + # Availability: Linux >= 2.6.25 + CAN_ISOTP: Final[int] + if sys.version_info >= (3, 15): + CAN_ISOTP_CHK_PAD_DATA: Final[int] + CAN_ISOTP_CHK_PAD_LEN: Final[int] + CAN_ISOTP_DEFAULT_EXT_ADDRESS: Final[int] + CAN_ISOTP_DEFAULT_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_FRAME_TXTIME: Final[int] + CAN_ISOTP_DEFAULT_LL_MTU: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_DL: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_PAD_CONTENT: Final[int] + CAN_ISOTP_DEFAULT_RECV_BS: Final[int] + CAN_ISOTP_DEFAULT_RECV_STMIN: Final[int] + CAN_ISOTP_DEFAULT_RECV_WFTMAX: Final[int] + CAN_ISOTP_EXTEND_ADDR: Final[int] + CAN_ISOTP_FORCE_RXSTMIN: Final[int] + CAN_ISOTP_FORCE_TXSTMIN: Final[int] + CAN_ISOTP_HALF_DUPLEX: Final[int] + CAN_ISOTP_LL_OPTS: Final[int] + CAN_ISOTP_LISTEN_MODE: Final[int] + CAN_ISOTP_OPTS: Final[int] + CAN_ISOTP_RECV_FC: Final[int] + CAN_ISOTP_RX_EXT_ADDR: Final[int] + CAN_ISOTP_RX_PADDING: Final[int] + CAN_ISOTP_RX_STMIN: Final[int] + CAN_ISOTP_SF_BROADCAST: Final[int] + CAN_ISOTP_TX_PADDING: Final[int] + CAN_ISOTP_TX_STMIN: Final[int] + CAN_ISOTP_WAIT_TX_DONE: Final[int] + SOL_CAN_ISOTP: Final[int] + # Availability: Linux >= 5.4 + CAN_J1939: Final[int] + + J1939_MAX_UNICAST_ADDR: Final[int] + J1939_IDLE_ADDR: Final[int] + J1939_NO_ADDR: Final[int] + J1939_NO_NAME: Final[int] + J1939_PGN_REQUEST: Final[int] + J1939_PGN_ADDRESS_CLAIMED: Final[int] + J1939_PGN_ADDRESS_COMMANDED: Final[int] + J1939_PGN_PDU1_MAX: Final[int] + J1939_PGN_MAX: Final[int] + J1939_NO_PGN: Final[int] + + SO_J1939_FILTER: Final[int] + SO_J1939_PROMISC: Final[int] + SO_J1939_SEND_PRIO: Final[int] + SO_J1939_ERRQUEUE: Final[int] + + SCM_J1939_DEST_ADDR: Final[int] + SCM_J1939_DEST_NAME: Final[int] + SCM_J1939_PRIO: Final[int] + SCM_J1939_ERRQUEUE: Final[int] + + J1939_NLA_PAD: Final[int] + J1939_NLA_BYTES_ACKED: Final[int] + J1939_EE_INFO_NONE: Final[int] + J1939_EE_INFO_TX_ABORT: Final[int] + J1939_FILTER_MAX: Final[int] + +if sys.version_info >= (3, 12) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # Availability: FreeBSD >= 14.0 + AF_DIVERT: Final[int] + PF_DIVERT: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.2 + AF_PACKET: Final[int] + PF_PACKET: Final[int] + PACKET_BROADCAST: Final[int] + PACKET_FASTROUTE: Final[int] + PACKET_HOST: Final[int] + PACKET_LOOPBACK: Final[int] + PACKET_MULTICAST: Final[int] + PACKET_OTHERHOST: Final[int] + PACKET_OUTGOING: Final[int] + +if sys.version_info >= (3, 12) and sys.platform == "linux": + ETH_P_ALL: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.30 + AF_RDS: Final[int] + PF_RDS: Final[int] + SOL_RDS: Final[int] + # These are present in include/linux/rds.h but don't always show up + # here. + RDS_CANCEL_SENT_TO: Final[int] + RDS_CMSG_RDMA_ARGS: Final[int] + RDS_CMSG_RDMA_DEST: Final[int] + RDS_CMSG_RDMA_MAP: Final[int] + RDS_CMSG_RDMA_STATUS: Final[int] + RDS_CONG_MONITOR: Final[int] + RDS_FREE_MR: Final[int] + RDS_GET_MR: Final[int] + RDS_GET_MR_FOR_DEST: Final[int] + RDS_RDMA_DONTWAIT: Final[int] + RDS_RDMA_FENCE: Final[int] + RDS_RDMA_INVALIDATE: Final[int] + RDS_RDMA_NOTIFY_ME: Final[int] + RDS_RDMA_READWRITE: Final[int] + RDS_RDMA_SILENT: Final[int] + RDS_RDMA_USE_ONCE: Final[int] + RDS_RECVERR: Final[int] + + # This is supported by CPython but doesn't seem to be a real thing. + # The closest existing constant in rds.h is RDS_CMSG_CONG_UPDATE + # RDS_CMSG_RDMA_UPDATE: Final[int] + +if sys.platform == "win32": + SIO_RCVALL: Final[int] + SIO_KEEPALIVE_VALS: Final[int] + SIO_LOOPBACK_FAST_PATH: Final[int] + RCVALL_MAX: Final[int] + RCVALL_OFF: Final[int] + RCVALL_ON: Final[int] + RCVALL_SOCKETLEVELONLY: Final[int] + +if sys.platform == "linux": + AF_TIPC: Final[int] + SOL_TIPC: Final[int] + TIPC_ADDR_ID: Final[int] + TIPC_ADDR_NAME: Final[int] + TIPC_ADDR_NAMESEQ: Final[int] + TIPC_CFG_SRV: Final[int] + TIPC_CLUSTER_SCOPE: Final[int] + TIPC_CONN_TIMEOUT: Final[int] + TIPC_CRITICAL_IMPORTANCE: Final[int] + TIPC_DEST_DROPPABLE: Final[int] + TIPC_HIGH_IMPORTANCE: Final[int] + TIPC_IMPORTANCE: Final[int] + TIPC_LOW_IMPORTANCE: Final[int] + TIPC_MEDIUM_IMPORTANCE: Final[int] + TIPC_NODE_SCOPE: Final[int] + TIPC_PUBLISHED: Final[int] + TIPC_SRC_DROPPABLE: Final[int] + TIPC_SUBSCR_TIMEOUT: Final[int] + TIPC_SUB_CANCEL: Final[int] + TIPC_SUB_PORTS: Final[int] + TIPC_SUB_SERVICE: Final[int] + TIPC_TOP_SRV: Final[int] + TIPC_WAIT_FOREVER: Final[int] + TIPC_WITHDRAWN: Final[int] + TIPC_ZONE_SCOPE: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 2.6.38 + AF_ALG: Final[int] + SOL_ALG: Final[int] + ALG_OP_DECRYPT: Final[int] + ALG_OP_ENCRYPT: Final[int] + ALG_OP_SIGN: Final[int] + ALG_OP_VERIFY: Final[int] + ALG_SET_AEAD_ASSOCLEN: Final[int] + ALG_SET_AEAD_AUTHSIZE: Final[int] + ALG_SET_IV: Final[int] + ALG_SET_KEY: Final[int] + ALG_SET_OP: Final[int] + ALG_SET_PUBKEY: Final[int] + +if sys.platform == "linux": + # Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing) + AF_VSOCK: Final[int] + IOCTL_VM_SOCKETS_GET_LOCAL_CID: Final = 0x7B9 + VMADDR_CID_ANY: Final = 0xFFFFFFFF + VMADDR_CID_HOST: Final = 2 + VMADDR_PORT_ANY: Final = 0xFFFFFFFF + SO_VM_SOCKETS_BUFFER_MAX_SIZE: Final = 2 + SO_VM_SOCKETS_BUFFER_SIZE: Final = 0 + SO_VM_SOCKETS_BUFFER_MIN_SIZE: Final = 1 + VM_SOCKETS_INVALID_VERSION: Final = 0xFFFFFFFF # undocumented + +# Documented as only available on BSD, macOS, but empirically sometimes +# available on Windows +if sys.platform != "linux": + AF_LINK: Final[int] + +has_ipv6: bool + +if sys.platform != "darwin": + BDADDR_ANY: Final = "00:00:00:00:00:00" + BDADDR_LOCAL: Final = "00:00:00:FF:FF:FF" + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + HCI_FILTER: Final[int] # not in NetBSD or DragonFlyBSD + HCI_TIME_STAMP: Final[int] # not in FreeBSD, NetBSD, or DragonFlyBSD + HCI_DATA_DIR: Final[int] # not in FreeBSD, NetBSD, or DragonFlyBSD + +if sys.platform == "linux": + AF_QIPCRTR: Final[int] # Availability: Linux >= 4.7 + +if sys.version_info >= (3, 11) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # FreeBSD + SCM_CREDS2: Final[int] + LOCAL_CREDS: Final[int] + LOCAL_CREDS_PERSISTENT: Final[int] + +if sys.version_info >= (3, 11) and sys.platform == "linux": + SO_INCOMING_CPU: Final[int] # Availability: Linux >= 3.9 + +if sys.version_info >= (3, 12) and sys.platform == "win32": + # Availability: Windows + AF_HYPERV: Final[int] + HV_PROTOCOL_RAW: Final[int] + HVSOCKET_CONNECT_TIMEOUT: Final[int] + HVSOCKET_CONNECT_TIMEOUT_MAX: Final[int] + HVSOCKET_CONNECTED_SUSPEND: Final[int] + HVSOCKET_ADDRESS_FLAG_PASSTHRU: Final[int] + HV_GUID_ZERO: Final = "00000000-0000-0000-0000-000000000000" + HV_GUID_WILDCARD: Final = "00000000-0000-0000-0000-000000000000" + HV_GUID_BROADCAST: Final = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF" + HV_GUID_CHILDREN: Final = "90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD" + HV_GUID_LOOPBACK: Final = "E0E16197-DD56-4A10-9195-5EE7A155A838" + HV_GUID_PARENT: Final = "A42E7CDA-D03F-480C-9CC2-A4DE20ABB878" + +if sys.version_info >= (3, 12): + if sys.platform != "win32": + # Availability: Linux, FreeBSD, macOS + ETHERTYPE_ARP: Final[int] + ETHERTYPE_IP: Final[int] + ETHERTYPE_IPV6: Final[int] + ETHERTYPE_VLAN: Final[int] + +# -------------------- +# Semi-documented constants +# These are alluded to under the "Socket families" section in the docs +# https://docs.python.org/3/library/socket.html#socket-families +# -------------------- + +if sys.platform == "linux": + # Netlink is defined by Linux + AF_NETLINK: Final[int] + NETLINK_CRYPTO: Final[int] + NETLINK_DNRTMSG: Final[int] + NETLINK_FIREWALL: Final[int] + NETLINK_IP6_FW: Final[int] + NETLINK_NFLOG: Final[int] + NETLINK_ROUTE: Final[int] + NETLINK_USERSOCK: Final[int] + NETLINK_XFRM: Final[int] + # Technically still supported by CPython + # NETLINK_ARPD: Final[int] # linux 2.0 to 2.6.12 (EOL August 2005) + # NETLINK_ROUTE6: Final[int] # linux 2.2 to 2.6.12 (EOL August 2005) + # NETLINK_SKIP: Final[int] # linux 2.0 to 2.6.12 (EOL August 2005) + # NETLINK_TAPBASE: Final[int] # linux 2.2 to 2.6.12 (EOL August 2005) + # NETLINK_TCPDIAG: Final[int] # linux 2.6.0 to 2.6.13 (EOL December 2005) + # NETLINK_W1: Final[int] # linux 2.6.13 to 2.6.17 (EOL October 2006) + +if sys.platform == "darwin": + PF_SYSTEM: Final[int] + SYSPROTO_CONTROL: Final[int] + +if sys.platform != "darwin": + AF_BLUETOOTH: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + # Linux and some BSD support is explicit in the docs + # Windows and macOS do not support in practice + BTPROTO_HCI: Final[int] + BTPROTO_L2CAP: Final[int] + BTPROTO_SCO: Final[int] # not in FreeBSD +if sys.platform != "darwin": + BTPROTO_RFCOMM: Final[int] + +if sys.platform == "linux": + UDPLITE_RECV_CSCOV: Final[int] + UDPLITE_SEND_CSCOV: Final[int] + +# -------------------- +# Documented under socket.shutdown +# -------------------- +SHUT_RD: Final[int] +SHUT_RDWR: Final[int] +SHUT_WR: Final[int] + +# -------------------- +# Undocumented constants +# -------------------- + +# Undocumented address families +AF_APPLETALK: Final[int] +AF_DECnet: Final[int] +AF_IPX: Final[int] +AF_SNA: Final[int] + +if sys.platform != "win32": + AF_ROUTE: Final[int] + +if sys.platform == "darwin": + AF_SYSTEM: Final[int] + +if sys.platform != "darwin": + AF_IRDA: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + AF_ASH: Final[int] + AF_ATMPVC: Final[int] + AF_ATMSVC: Final[int] + AF_AX25: Final[int] + AF_BRIDGE: Final[int] + AF_ECONET: Final[int] + AF_KEY: Final[int] + AF_LLC: Final[int] + AF_NETBEUI: Final[int] + AF_NETROM: Final[int] + AF_PPPOX: Final[int] + AF_ROSE: Final[int] + AF_SECURITY: Final[int] + AF_WANPIPE: Final[int] + AF_X25: Final[int] + +# Miscellaneous undocumented + +if sys.platform != "win32" and sys.platform != "linux": + LOCAL_PEERCRED: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + # Defined in linux socket.h, but this isn't always present for + # some reason. + IPX_TYPE: Final[int] + +# ===== Classes ===== + +@disjoint_base +class socket: + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + # F811: "Redefinition of unused `timeout`" + @property + def timeout(self) -> float | None: ... + if sys.platform == "win32": + def __init__( + self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = None + ) -> None: ... + else: + def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = None) -> None: ... + + def bind(self, address: _Address, /) -> None: ... + def close(self) -> None: ... + def connect(self, address: _Address, /) -> None: ... + def connect_ex(self, address: _Address, /) -> int: ... + def detach(self) -> int: ... + def fileno(self) -> int: ... + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + + @overload + def getsockopt(self, level: int, optname: int, /) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... + + def getblocking(self) -> bool: ... + def gettimeout(self) -> float | None: ... + if sys.platform == "win32": + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ... + + def listen(self, backlog: int = ..., /) -> None: ... + def recv(self, bufsize: int, flags: int = 0, /) -> bytes: ... + def recvfrom(self, bufsize: int, flags: int = 0, /) -> tuple[bytes, _RetAddress]: ... + if sys.platform != "win32": + def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvmsg_into( + self, buffers: Iterable[WriteableBuffer], ancbufsize: int = 0, flags: int = 0, / + ) -> tuple[int, list[_CMSG], int, Any]: ... + + def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> int: ... + def send(self, data: ReadableBuffer, flags: int = 0, /) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = 0, /) -> None: ... + + @overload + def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: ... + @overload + def sendto(self, data: ReadableBuffer, flags: int, address: _Address, /) -> int: ... + + if sys.platform != "win32": + def sendmsg( + self, + buffers: Iterable[ReadableBuffer], + ancdata: Iterable[_CMSGArg] = ..., + flags: int = 0, + address: _Address | None = None, + /, + ) -> int: ... + if sys.platform == "linux": + def sendmsg_afalg( + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 + ) -> int: ... + + def setblocking(self, flag: bool, /) -> None: ... + def settimeout(self, value: float | None, /) -> None: ... + + @overload + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: None, optlen: int, /) -> None: ... + + if sys.platform == "win32": + def share(self, process_id: int, /) -> bytes: ... + + def shutdown(self, how: int, /) -> None: ... + +SocketType = socket + +# ===== Functions ===== + +def close(fd: SupportsIndex, /) -> None: ... +def dup(fd: SupportsIndex, /) -> int: ... + +# the 5th tuple item is an address +def getaddrinfo( + host: bytes | str | None, port: bytes | str | int | None, family: int = ..., type: int = 0, proto: int = 0, flags: int = 0 +) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ... +def gethostbyname(hostname: str, /) -> str: ... +def gethostbyname_ex(hostname: str, /) -> tuple[str, list[str], list[str]]: ... +def gethostname() -> str: ... +def gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], flags: int, /) -> tuple[str, str]: ... +def getprotobyname(protocolname: str, /) -> int: ... +def getservbyname(servicename: str, protocolname: str = ..., /) -> int: ... +def getservbyport(port: int, protocolname: str = ..., /) -> str: ... +def ntohl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def ntohs(x: int, /) -> int: ... # param & ret val are 16-bit ints +def htonl(x: int, /) -> int: ... # param & ret val are 32-bit ints +def htons(x: int, /) -> int: ... # param & ret val are 16-bit ints +def inet_aton(ip_addr: str, /) -> bytes: ... # ret val 4 bytes in length +def inet_ntoa(packed_ip: ReadableBuffer, /) -> str: ... +def inet_pton(address_family: int, ip_string: str, /) -> bytes: ... +def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: ... +def getdefaulttimeout() -> float | None: ... + +# F811: "Redefinition of unused `timeout`" +def setdefaulttimeout(timeout: float | None, /) -> None: ... + +if sys.platform != "win32": + def sethostname(name: str, /) -> None: ... + def CMSG_LEN(length: int, /) -> int: ... + def CMSG_SPACE(length: int, /) -> int: ... + def socketpair(family: int = ..., type: int = ..., proto: int = 0, /) -> tuple[socket, socket]: ... + +def if_nameindex() -> list[tuple[int, str]]: ... +def if_nametoindex(oname: str, /) -> int: ... + +if sys.version_info >= (3, 14): + def if_indextoname(if_index: int, /) -> str: ... + +else: + def if_indextoname(index: int, /) -> str: ... + +CAPI: CapsuleType diff --git a/stdlib/_sqlite3.pyi b/stdlib/_sqlite3.pyi new file mode 100644 index 000000000000..b6d96121afa9 --- /dev/null +++ b/stdlib/_sqlite3.pyi @@ -0,0 +1,311 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from sqlite3 import ( + Connection as Connection, + Cursor as Cursor, + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + PrepareProtocol as PrepareProtocol, + ProgrammingError as ProgrammingError, + Row as Row, + Warning as Warning, + _IsolationLevel, +) +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + from sqlite3 import Blob as Blob + +_T = TypeVar("_T") +_ConnectionT = TypeVar("_ConnectionT", bound=Connection) +_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None +_Adapter: TypeAlias = Callable[[_T], _SqliteData] +_Converter: TypeAlias = Callable[[bytes], Any] + +PARSE_COLNAMES: Final = 2 +PARSE_DECLTYPES: Final = 1 +SQLITE_ALTER_TABLE: Final = 26 +SQLITE_ANALYZE: Final = 28 +SQLITE_ATTACH: Final = 24 +SQLITE_CREATE_INDEX: Final = 1 +SQLITE_CREATE_TABLE: Final = 2 +SQLITE_CREATE_TEMP_INDEX: Final = 3 +SQLITE_CREATE_TEMP_TABLE: Final = 4 +SQLITE_CREATE_TEMP_TRIGGER: Final = 5 +SQLITE_CREATE_TEMP_VIEW: Final = 6 +SQLITE_CREATE_TRIGGER: Final = 7 +SQLITE_CREATE_VIEW: Final = 8 +SQLITE_CREATE_VTABLE: Final = 29 +SQLITE_DELETE: Final = 9 +SQLITE_DENY: Final = 1 +SQLITE_DETACH: Final = 25 +SQLITE_DONE: Final = 101 +SQLITE_DROP_INDEX: Final = 10 +SQLITE_DROP_TABLE: Final = 11 +SQLITE_DROP_TEMP_INDEX: Final = 12 +SQLITE_DROP_TEMP_TABLE: Final = 13 +SQLITE_DROP_TEMP_TRIGGER: Final = 14 +SQLITE_DROP_TEMP_VIEW: Final = 15 +SQLITE_DROP_TRIGGER: Final = 16 +SQLITE_DROP_VIEW: Final = 17 +SQLITE_DROP_VTABLE: Final = 30 +SQLITE_FUNCTION: Final = 31 +SQLITE_IGNORE: Final = 2 +SQLITE_INSERT: Final = 18 +SQLITE_OK: Final = 0 +SQLITE_PRAGMA: Final = 19 +SQLITE_READ: Final = 20 +SQLITE_RECURSIVE: Final = 33 +SQLITE_REINDEX: Final = 27 +SQLITE_SAVEPOINT: Final = 32 +SQLITE_SELECT: Final = 21 +SQLITE_TRANSACTION: Final = 22 +SQLITE_UPDATE: Final = 23 +if sys.version_info >= (3, 15): + SQLITE_KEYWORDS: tuple[str, ...] +adapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]] +converters: dict[str, _Converter] +sqlite_version: str + +if sys.version_info < (3, 12): + version: str + +if sys.version_info >= (3, 12): + LEGACY_TRANSACTION_CONTROL: Final = -1 + SQLITE_DBCONFIG_DEFENSIVE: Final = 1010 + SQLITE_DBCONFIG_DQS_DDL: Final = 1014 + SQLITE_DBCONFIG_DQS_DML: Final = 1013 + SQLITE_DBCONFIG_ENABLE_FKEY: Final = 1002 + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final = 1004 + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final = 1005 + SQLITE_DBCONFIG_ENABLE_QPSG: Final = 1007 + SQLITE_DBCONFIG_ENABLE_TRIGGER: Final = 1003 + SQLITE_DBCONFIG_ENABLE_VIEW: Final = 1015 + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final = 1012 + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final = 1016 + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final = 1006 + SQLITE_DBCONFIG_RESET_DATABASE: Final = 1009 + SQLITE_DBCONFIG_TRIGGER_EQP: Final = 1008 + SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final = 1017 + SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final = 1011 + +if sys.version_info >= (3, 11): + SQLITE_ABORT: Final = 4 + SQLITE_ABORT_ROLLBACK: Final = 516 + SQLITE_AUTH: Final = 23 + SQLITE_AUTH_USER: Final = 279 + SQLITE_BUSY: Final = 5 + SQLITE_BUSY_RECOVERY: Final = 261 + SQLITE_BUSY_SNAPSHOT: Final = 517 + SQLITE_BUSY_TIMEOUT: Final = 773 + SQLITE_CANTOPEN: Final = 14 + SQLITE_CANTOPEN_CONVPATH: Final = 1038 + SQLITE_CANTOPEN_DIRTYWAL: Final = 1294 + SQLITE_CANTOPEN_FULLPATH: Final = 782 + SQLITE_CANTOPEN_ISDIR: Final = 526 + SQLITE_CANTOPEN_NOTEMPDIR: Final = 270 + SQLITE_CANTOPEN_SYMLINK: Final = 1550 + SQLITE_CONSTRAINT: Final = 19 + SQLITE_CONSTRAINT_CHECK: Final = 275 + SQLITE_CONSTRAINT_COMMITHOOK: Final = 531 + SQLITE_CONSTRAINT_FOREIGNKEY: Final = 787 + SQLITE_CONSTRAINT_FUNCTION: Final = 1043 + SQLITE_CONSTRAINT_NOTNULL: Final = 1299 + SQLITE_CONSTRAINT_PINNED: Final = 2835 + SQLITE_CONSTRAINT_PRIMARYKEY: Final = 1555 + SQLITE_CONSTRAINT_ROWID: Final = 2579 + SQLITE_CONSTRAINT_TRIGGER: Final = 1811 + SQLITE_CONSTRAINT_UNIQUE: Final = 2067 + SQLITE_CONSTRAINT_VTAB: Final = 2323 + SQLITE_CORRUPT: Final = 11 + SQLITE_CORRUPT_INDEX: Final = 779 + SQLITE_CORRUPT_SEQUENCE: Final = 523 + SQLITE_CORRUPT_VTAB: Final = 267 + SQLITE_EMPTY: Final = 16 + SQLITE_ERROR: Final = 1 + SQLITE_ERROR_MISSING_COLLSEQ: Final = 257 + SQLITE_ERROR_RETRY: Final = 513 + SQLITE_ERROR_SNAPSHOT: Final = 769 + SQLITE_FORMAT: Final = 24 + SQLITE_FULL: Final = 13 + SQLITE_INTERNAL: Final = 2 + SQLITE_INTERRUPT: Final = 9 + SQLITE_IOERR: Final = 10 + SQLITE_IOERR_ACCESS: Final = 3338 + SQLITE_IOERR_AUTH: Final = 7178 + SQLITE_IOERR_BEGIN_ATOMIC: Final = 7434 + SQLITE_IOERR_BLOCKED: Final = 2826 + SQLITE_IOERR_CHECKRESERVEDLOCK: Final = 3594 + SQLITE_IOERR_CLOSE: Final = 4106 + SQLITE_IOERR_COMMIT_ATOMIC: Final = 7690 + SQLITE_IOERR_CONVPATH: Final = 6666 + SQLITE_IOERR_CORRUPTFS: Final = 8458 + SQLITE_IOERR_DATA: Final = 8202 + SQLITE_IOERR_DELETE: Final = 2570 + SQLITE_IOERR_DELETE_NOENT: Final = 5898 + SQLITE_IOERR_DIR_CLOSE: Final = 4362 + SQLITE_IOERR_DIR_FSYNC: Final = 1290 + SQLITE_IOERR_FSTAT: Final = 1802 + SQLITE_IOERR_FSYNC: Final = 1034 + SQLITE_IOERR_GETTEMPPATH: Final = 6410 + SQLITE_IOERR_LOCK: Final = 3850 + SQLITE_IOERR_MMAP: Final = 6154 + SQLITE_IOERR_NOMEM: Final = 3082 + SQLITE_IOERR_RDLOCK: Final = 2314 + SQLITE_IOERR_READ: Final = 266 + SQLITE_IOERR_ROLLBACK_ATOMIC: Final = 7946 + SQLITE_IOERR_SEEK: Final = 5642 + SQLITE_IOERR_SHMLOCK: Final = 5130 + SQLITE_IOERR_SHMMAP: Final = 5386 + SQLITE_IOERR_SHMOPEN: Final = 4618 + SQLITE_IOERR_SHMSIZE: Final = 4874 + SQLITE_IOERR_SHORT_READ: Final = 522 + SQLITE_IOERR_TRUNCATE: Final = 1546 + SQLITE_IOERR_UNLOCK: Final = 2058 + SQLITE_IOERR_VNODE: Final = 6922 + SQLITE_IOERR_WRITE: Final = 778 + SQLITE_LIMIT_ATTACHED: Final = 7 + SQLITE_LIMIT_COLUMN: Final = 2 + SQLITE_LIMIT_COMPOUND_SELECT: Final = 4 + SQLITE_LIMIT_EXPR_DEPTH: Final = 3 + SQLITE_LIMIT_FUNCTION_ARG: Final = 6 + SQLITE_LIMIT_LENGTH: Final = 0 + SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final = 8 + SQLITE_LIMIT_SQL_LENGTH: Final = 1 + SQLITE_LIMIT_TRIGGER_DEPTH: Final = 10 + SQLITE_LIMIT_VARIABLE_NUMBER: Final = 9 + SQLITE_LIMIT_VDBE_OP: Final = 5 + SQLITE_LIMIT_WORKER_THREADS: Final = 11 + SQLITE_LOCKED: Final = 6 + SQLITE_LOCKED_SHAREDCACHE: Final = 262 + SQLITE_LOCKED_VTAB: Final = 518 + SQLITE_MISMATCH: Final = 20 + SQLITE_MISUSE: Final = 21 + SQLITE_NOLFS: Final = 22 + SQLITE_NOMEM: Final = 7 + SQLITE_NOTADB: Final = 26 + SQLITE_NOTFOUND: Final = 12 + SQLITE_NOTICE: Final = 27 + SQLITE_NOTICE_RECOVER_ROLLBACK: Final = 539 + SQLITE_NOTICE_RECOVER_WAL: Final = 283 + SQLITE_OK_LOAD_PERMANENTLY: Final = 256 + SQLITE_OK_SYMLINK: Final = 512 + SQLITE_PERM: Final = 3 + SQLITE_PROTOCOL: Final = 15 + SQLITE_RANGE: Final = 25 + SQLITE_READONLY: Final = 8 + SQLITE_READONLY_CANTINIT: Final = 1288 + SQLITE_READONLY_CANTLOCK: Final = 520 + SQLITE_READONLY_DBMOVED: Final = 1032 + SQLITE_READONLY_DIRECTORY: Final = 1544 + SQLITE_READONLY_RECOVERY: Final = 264 + SQLITE_READONLY_ROLLBACK: Final = 776 + SQLITE_ROW: Final = 100 + SQLITE_SCHEMA: Final = 17 + SQLITE_TOOBIG: Final = 18 + SQLITE_WARNING: Final = 28 + SQLITE_WARNING_AUTOINDEX: Final = 284 + threadsafety: Literal[0, 1, 3] + +# Can take or return anything depending on what's in the registry. +@overload +def adapt(obj: Any, proto: Any, /) -> Any: ... +@overload +def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... + +def complete_statement(statement: str) -> bool: ... + +if sys.version_info >= (3, 12): + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, + *, + autocommit: bool = ..., + ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: _IsolationLevel, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + *, + autocommit: bool = ..., + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> _ConnectionT: ... +else: + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + cached_statements: int = 128, + uri: bool = False, + ) -> Connection: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float, + detect_types: int, + isolation_level: _IsolationLevel, + check_same_thread: bool, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... + @overload + def connect( + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + *, + factory: type[_ConnectionT], + cached_statements: int = 128, + uri: bool = False, + ) -> _ConnectionT: ... + +def enable_callback_tracebacks(enable: bool, /) -> None: ... + +if sys.version_info < (3, 12): + # takes a pos-or-keyword argument because there is a C wrapper + @deprecated( + "Deprecated since Python 3.10; removed in Python 3.12. " + "Open database in URI mode using `cache=shared` parameter instead." + ) + def enable_shared_cache(do_enable: int) -> None: ... # undocumented + +def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ... +def register_converter(typename: str, converter: _Converter, /) -> None: ... diff --git a/stdlib/_ssl.pyi b/stdlib/_ssl.pyi new file mode 100644 index 000000000000..87023d90e13b --- /dev/null +++ b/stdlib/_ssl.pyi @@ -0,0 +1,303 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from ssl import ( + SSLCertVerificationError as SSLCertVerificationError, + SSLContext, + SSLEOFError as SSLEOFError, + SSLError as SSLError, + SSLObject, + SSLSyscallError as SSLSyscallError, + SSLWantReadError as SSLWantReadError, + SSLWantWriteError as SSLWantWriteError, + SSLZeroReturnError as SSLZeroReturnError, +) +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, final, overload, type_check_only +from typing_extensions import NotRequired, Self, deprecated, disjoint_base + +_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] +_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] + +@type_check_only +class _Cipher(TypedDict): + aead: bool + alg_bits: int + auth: str + description: str + digest: str | None + id: int + kea: str + name: str + protocol: str + strength_bits: int + symmetric: str + +@type_check_only +class _CertInfo(TypedDict): + subject: tuple[tuple[tuple[str, str], ...], ...] + issuer: tuple[tuple[tuple[str, str], ...], ...] + version: int + serialNumber: str + notBefore: str + notAfter: str + subjectAltName: NotRequired[tuple[tuple[str, str], ...] | None] + OCSP: NotRequired[tuple[str, ...] | None] + caIssuers: NotRequired[tuple[str, ...] | None] + crlDistributionPoints: NotRequired[tuple[str, ...] | None] + +def RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: ... +def RAND_bytes(n: int, /) -> bytes: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.6; removed in Python 3.12. Use `ssl.RAND_bytes()` instead.") + def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ... + +def RAND_status() -> bool: ... +def get_default_verify_paths() -> tuple[str, str, str, str]: ... + +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + +if sys.platform == "win32": + _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] + def enum_certificates(store_name: str) -> _EnumRetType: ... + def enum_crls(store_name: str) -> _EnumRetType: ... + +def txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]: ... +def nid2obj(nid: int, /) -> tuple[int, str, str, str]: ... + +@disjoint_base +class _SSLContext: + check_hostname: bool + keylog_filename: str | None + maximum_version: int + minimum_version: int + num_tickets: int + options: int + post_handshake_auth: bool + protocol: int + security_level: int + sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None + verify_flags: int + verify_mode: int + def __new__(cls, protocol: int, /) -> Self: ... + def cert_store_stats(self) -> dict[str, int]: ... + + @overload + def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = False) -> Any: ... + + def get_ciphers(self) -> list[_Cipher]: ... + def load_cert_chain( + self, certfile: StrOrBytesPath, keyfile: StrOrBytesPath | None = None, password: _PasswordType | None = None + ) -> None: ... + def load_dh_params(self, path: str, /) -> None: ... + def load_verify_locations( + self, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, + ) -> None: ... + def session_stats(self) -> dict[str, int]: ... + def set_ciphers(self, cipherlist: str, /) -> None: ... + def set_default_verify_paths(self) -> None: ... + def set_ecdh_curve(self, name: str, /) -> None: ... + if sys.version_info >= (3, 15): + def get_groups(self, *, include_aliases: bool = False) -> list[str]: ... + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def set_client_sigalgs(self, sigalgslist: str, /) -> None: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_server_sigalgs(self, sigalgslist: str, /) -> None: ... + if sys.version_info >= (3, 13): + def set_psk_client_callback(self, callback: Callable[[str | None], tuple[str | None, bytes]] | None) -> None: ... + def set_psk_server_callback( + self, callback: Callable[[str | None], bytes] | None, identity_hint: str | None = None + ) -> None: ... + +@final +class MemoryBIO: + eof: bool + pending: int + def __new__(self) -> Self: ... + def read(self, size: int = -1, /) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int: ... + def write_eof(self) -> None: ... + +@final +class SSLSession: + __hash__: ClassVar[None] # type: ignore[assignment] + @property + def has_ticket(self) -> bool: ... + @property + def id(self) -> bytes: ... + @property + def ticket_lifetime_hint(self) -> int: ... + @property + def time(self) -> int: ... + @property + def timeout(self) -> int: ... + +# _ssl.Certificate is weird: it can't be instantiated or subclassed. +# Instances can only be created via methods of the private _ssl._SSLSocket class, +# for which the relevant method signatures are: +# +# class _SSLSocket: +# def get_unverified_chain(self) -> list[Certificate] | None: ... +# def get_verified_chain(self) -> list[Certificate] | None: ... +# +# You can find a _ssl._SSLSocket object as the _sslobj attribute of a ssl.SSLSocket object + +@final +class Certificate: + def get_info(self) -> _CertInfo: ... + + @overload + def public_bytes(self) -> str: ... + @overload + def public_bytes(self, format: Literal[1] = 1, /) -> str: ... # ENCODING_PEM + @overload + def public_bytes(self, format: Literal[2], /) -> bytes: ... # ENCODING_DER + @overload + def public_bytes(self, format: int, /) -> str | bytes: ... + +if sys.version_info < (3, 12): + err_codes_to_names: dict[tuple[int, int], str] + err_names_to_codes: dict[str, tuple[int, int]] + lib_codes_to_names: dict[int, str] + +_DEFAULT_CIPHERS: Final[str] + +# SSL error numbers +SSL_ERROR_ZERO_RETURN: Final = 6 +SSL_ERROR_WANT_READ: Final = 2 +SSL_ERROR_WANT_WRITE: Final = 3 +SSL_ERROR_WANT_X509_LOOKUP: Final = 4 +SSL_ERROR_SYSCALL: Final = 5 +SSL_ERROR_SSL: Final = 1 +SSL_ERROR_WANT_CONNECT: Final = 7 +SSL_ERROR_EOF: Final = 8 +SSL_ERROR_INVALID_ERROR_CODE: Final = 10 + +# verify modes +CERT_NONE: Final = 0 +CERT_OPTIONAL: Final = 1 +CERT_REQUIRED: Final = 2 + +# verify flags +VERIFY_DEFAULT: Final = 0 +VERIFY_CRL_CHECK_LEAF: Final = 0x04 +VERIFY_CRL_CHECK_CHAIN: Final = 0x0C +VERIFY_X509_STRICT: Final = 0x20 +VERIFY_X509_TRUSTED_FIRST: Final = 0x8000 +VERIFY_ALLOW_PROXY_CERTS: Final = 0x40 +VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000 + +# alert descriptions +ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = 0 +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = 10 +ALERT_DESCRIPTION_BAD_RECORD_MAC: Final = 20 +ALERT_DESCRIPTION_RECORD_OVERFLOW: Final = 22 +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = 30 +ALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = 40 +ALERT_DESCRIPTION_BAD_CERTIFICATE: Final = 42 +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = 43 +ALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = 44 +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = 45 +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = 46 +ALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = 47 +ALERT_DESCRIPTION_UNKNOWN_CA: Final = 48 +ALERT_DESCRIPTION_ACCESS_DENIED: Final = 49 +ALERT_DESCRIPTION_DECODE_ERROR: Final = 50 +ALERT_DESCRIPTION_DECRYPT_ERROR: Final = 51 +ALERT_DESCRIPTION_PROTOCOL_VERSION: Final = 70 +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = 71 +ALERT_DESCRIPTION_INTERNAL_ERROR: Final = 80 +ALERT_DESCRIPTION_USER_CANCELLED: Final = 90 +ALERT_DESCRIPTION_NO_RENEGOTIATION: Final = 100 +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = 110 +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = 111 +ALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = 112 +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = 113 +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = 114 +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = 115 + +# protocol versions +PROTOCOL_SSLv23: Final = 2 +PROTOCOL_TLS: Final = 2 +PROTOCOL_TLS_CLIENT: Final = 16 +PROTOCOL_TLS_SERVER: Final = 17 +PROTOCOL_TLSv1: Final = 3 +PROTOCOL_TLSv1_1: Final = 4 +PROTOCOL_TLSv1_2: Final = 5 + +# protocol options +OP_ALL: Final[int] +OP_NO_SSLv2: Final = 0x0 +OP_NO_SSLv3: Final = 0x2000000 +OP_NO_TLSv1: Final = 0x4000000 +OP_NO_TLSv1_1: Final = 0x10000000 +OP_NO_TLSv1_2: Final = 0x8000000 +OP_NO_TLSv1_3: Final = 0x20000000 +OP_CIPHER_SERVER_PREFERENCE: Final = 0x400000 +OP_SINGLE_DH_USE: Final = 0x0 +OP_NO_TICKET: Final = 0x4000 +OP_SINGLE_ECDH_USE: Final = 0x0 +OP_NO_COMPRESSION: Final = 0x20000 +OP_ENABLE_MIDDLEBOX_COMPAT: Final = 0x100000 +OP_NO_RENEGOTIATION: Final = 0x40000000 +if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF: Final = 0x80 +if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT: Final = 0x4 + OP_ENABLE_KTLS: Final = 0x8 + +# host flags +HOSTFLAG_ALWAYS_CHECK_SUBJECT: Final = 0x1 +HOSTFLAG_NEVER_CHECK_SUBJECT: Final = 0x20 +HOSTFLAG_NO_WILDCARDS: Final = 0x2 +HOSTFLAG_NO_PARTIAL_WILDCARDS: Final = 0x4 +HOSTFLAG_MULTI_LABEL_WILDCARDS: Final = 0x8 +HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: Final = 0x10 + +# certificate file types +ENCODING_PEM: Final = 1 +ENCODING_DER: Final = 2 + +# protocol versions +PROTO_MINIMUM_SUPPORTED: Final = -2 +PROTO_MAXIMUM_SUPPORTED: Final = -1 +PROTO_SSLv3: Final[int] +PROTO_TLSv1: Final[int] +PROTO_TLSv1_1: Final[int] +PROTO_TLSv1_2: Final[int] +PROTO_TLSv1_3: Final[int] + +# feature support +HAS_SNI: Final[bool] +HAS_TLS_UNIQUE: Final[bool] +HAS_ECDH: Final[bool] +HAS_NPN: Final[bool] +if sys.version_info >= (3, 13): + HAS_PSK: Final[bool] +if sys.version_info >= (3, 15): + HAS_PSK_TLS13: Final[bool] +HAS_ALPN: Final[bool] +HAS_SSLv2: Final[bool] +HAS_SSLv3: Final[bool] +HAS_TLSv1: Final[bool] +HAS_TLSv1_1: Final[bool] +HAS_TLSv1_2: Final[bool] +HAS_TLSv1_3: Final[bool] +if sys.version_info >= (3, 14): + HAS_PHA: Final[bool] + +# version info +OPENSSL_VERSION_NUMBER: Final[int] +OPENSSL_VERSION_INFO: Final[tuple[int, int, int, int, int]] +OPENSSL_VERSION: Final[str] +_OPENSSL_API_VERSION: Final[tuple[int, int, int, int, int]] diff --git a/stdlib/_stat.pyi b/stdlib/_stat.pyi new file mode 100644 index 000000000000..7129a282b574 --- /dev/null +++ b/stdlib/_stat.pyi @@ -0,0 +1,119 @@ +import sys +from typing import Final + +SF_APPEND: Final = 0x00040000 +SF_ARCHIVED: Final = 0x00010000 +SF_IMMUTABLE: Final = 0x00020000 +SF_NOUNLINK: Final = 0x00100000 +SF_SNAPSHOT: Final = 0x00200000 + +ST_MODE: Final = 0 +ST_INO: Final = 1 +ST_DEV: Final = 2 +ST_NLINK: Final = 3 +ST_UID: Final = 4 +ST_GID: Final = 5 +ST_SIZE: Final = 6 +ST_ATIME: Final = 7 +ST_MTIME: Final = 8 +ST_CTIME: Final = 9 + +S_IFIFO: Final = 0o010000 +S_IFLNK: Final = 0o120000 +S_IFREG: Final = 0o100000 +S_IFSOCK: Final = 0o140000 +S_IFBLK: Final = 0o060000 +S_IFCHR: Final = 0o020000 +S_IFDIR: Final = 0o040000 + +# These are 0 on systems that don't support the specific kind of file. +# Example: Linux doesn't support door files, so S_IFDOOR is 0 on linux. +S_IFDOOR: Final[int] +S_IFPORT: Final[int] +S_IFWHT: Final[int] + +S_ISUID: Final = 0o4000 +S_ISGID: Final = 0o2000 +S_ISVTX: Final = 0o1000 + +S_IRWXU: Final = 0o0700 +S_IRUSR: Final = 0o0400 +S_IWUSR: Final = 0o0200 +S_IXUSR: Final = 0o0100 + +S_IRWXG: Final = 0o0070 +S_IRGRP: Final = 0o0040 +S_IWGRP: Final = 0o0020 +S_IXGRP: Final = 0o0010 + +S_IRWXO: Final = 0o0007 +S_IROTH: Final = 0o0004 +S_IWOTH: Final = 0o0002 +S_IXOTH: Final = 0o0001 + +S_ENFMT: Final = 0o2000 +S_IREAD: Final = 0o0400 +S_IWRITE: Final = 0o0200 +S_IEXEC: Final = 0o0100 + +UF_APPEND: Final = 0x00000004 +UF_COMPRESSED: Final = 0x00000020 # OS X 10.6+ only +UF_HIDDEN: Final = 0x00008000 # OX X 10.5+ only +UF_IMMUTABLE: Final = 0x00000002 +UF_NODUMP: Final = 0x00000001 +UF_NOUNLINK: Final = 0x00000010 +UF_OPAQUE: Final = 0x00000008 + +def S_IMODE(mode: int, /) -> int: ... +def S_IFMT(mode: int, /) -> int: ... +def S_ISBLK(mode: int, /) -> bool: ... +def S_ISCHR(mode: int, /) -> bool: ... +def S_ISDIR(mode: int, /) -> bool: ... +def S_ISDOOR(mode: int, /) -> bool: ... +def S_ISFIFO(mode: int, /) -> bool: ... +def S_ISLNK(mode: int, /) -> bool: ... +def S_ISPORT(mode: int, /) -> bool: ... +def S_ISREG(mode: int, /) -> bool: ... +def S_ISSOCK(mode: int, /) -> bool: ... +def S_ISWHT(mode: int, /) -> bool: ... +def filemode(mode: int, /) -> str: ... + +if sys.platform == "win32": + IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C + IO_REPARSE_TAG_MOUNT_POINT: Final = 0xA0000003 + IO_REPARSE_TAG_APPEXECLINK: Final = 0x8000001B + +if sys.platform == "win32": + FILE_ATTRIBUTE_ARCHIVE: Final = 32 + FILE_ATTRIBUTE_COMPRESSED: Final = 2048 + FILE_ATTRIBUTE_DEVICE: Final = 64 + FILE_ATTRIBUTE_DIRECTORY: Final = 16 + FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 + FILE_ATTRIBUTE_HIDDEN: Final = 2 + FILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768 + FILE_ATTRIBUTE_NORMAL: Final = 128 + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 + FILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072 + FILE_ATTRIBUTE_OFFLINE: Final = 4096 + FILE_ATTRIBUTE_READONLY: Final = 1 + FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 + FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 + FILE_ATTRIBUTE_SYSTEM: Final = 4 + FILE_ATTRIBUTE_TEMPORARY: Final = 256 + FILE_ATTRIBUTE_VIRTUAL: Final = 65536 + +if sys.version_info >= (3, 13): + # Varies by platform. + SF_SETTABLE: Final[int] + # https://github.com/python/cpython/issues/114081#issuecomment-2119017790 + # SF_RESTRICTED: Literal[0x00080000] + SF_FIRMLINK: Final = 0x00800000 + SF_DATALESS: Final = 0x40000000 + + if sys.platform == "darwin": + SF_SUPPORTED: Final = 0x9F0000 + SF_SYNTHETIC: Final = 0xC0000000 + + UF_TRACKED: Final = 0x00000040 + UF_DATAVAULT: Final = 0x00000080 + UF_SETTABLE: Final = 0x0000FFFF diff --git a/stdlib/_struct.pyi b/stdlib/_struct.pyi new file mode 100644 index 000000000000..c13e440e10aa --- /dev/null +++ b/stdlib/_struct.pyi @@ -0,0 +1,24 @@ +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Iterator +from typing import Any +from typing_extensions import disjoint_base + +def pack(fmt: str | bytes, /, *v: Any) -> bytes: ... +def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, /, *v: Any) -> None: ... +def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... +def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... +def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... +def calcsize(format: str | bytes, /) -> int: ... + +@disjoint_base +class Struct: + @property + def format(self) -> str: ... + @property + def size(self) -> int: ... + def __init__(self, format: str | bytes) -> None: ... + def pack(self, *v: Any) -> bytes: ... + def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... + def unpack(self, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... + def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... diff --git a/stdlib/_thread.pyi b/stdlib/_thread.pyi new file mode 100644 index 000000000000..57622e936a3b --- /dev/null +++ b/stdlib/_thread.pyi @@ -0,0 +1,123 @@ +import signal +import sys +from _typeshed import structseq +from collections.abc import Callable +from threading import Thread +from types import TracebackType +from typing import Any, Final, final, overload +from typing_extensions import Never, TypeVarTuple, Unpack, deprecated, disjoint_base + +_Ts = TypeVarTuple("_Ts") + +error = RuntimeError + +def _count() -> int: ... + +@final +class RLock: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + __enter__ = acquire + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + +if sys.version_info >= (3, 13): + @final + class _ThreadHandle: + ident: int + + def join(self, timeout: float | None = None, /) -> None: ... + def is_done(self) -> bool: ... + def _set_done(self) -> None: ... + + def start_joinable_thread( + function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True + ) -> _ThreadHandle: ... + + @final + class lock: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + @deprecated("Obsolete synonym. Use `acquire()` instead.") + def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ... # undocumented + @deprecated("Obsolete synonym. Use `release()` instead.") + def release_lock(self) -> None: ... # undocumented + @deprecated("Obsolete synonym. Use `locked()` instead.") + def locked_lock(self) -> bool: ... # undocumented + def __enter__(self) -> bool: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + + LockType = lock +else: + @final + class LockType: + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + def locked(self) -> bool: ... + @deprecated("Obsolete synonym. Use `acquire()` instead.") + def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ... # undocumented + @deprecated("Obsolete synonym. Use `release()` instead.") + def release_lock(self) -> None: ... # undocumented + @deprecated("Obsolete synonym. Use `locked()` instead.") + def locked_lock(self) -> bool: ... # undocumented + def __enter__(self) -> bool: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +@overload +def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... +@overload +def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... + +@overload +@deprecated("Obsolete synonym. Use `start_new_thread()` instead.") +def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... # undocumented +@overload +@deprecated("Obsolete synonym. Use `start_new_thread()` instead.") +def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... # undocumented + +def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ... +def exit() -> Never: ... +@deprecated("Obsolete synonym. Use `exit()` instead.") +def exit_thread() -> Never: ... # undocumented +def allocate_lock() -> LockType: ... +@deprecated("Obsolete synonym. Use `allocate_lock()` instead.") +def allocate() -> LockType: ... # undocumented +def get_ident() -> int: ... +def stack_size(size: int = 0, /) -> int: ... + +TIMEOUT_MAX: Final[float] + +def get_native_id() -> int: ... # only available on some platforms + +@final +class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): + __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") + + @property + def exc_type(self) -> type[BaseException]: ... + @property + def exc_value(self) -> BaseException | None: ... + @property + def exc_traceback(self) -> TracebackType | None: ... + @property + def thread(self) -> Thread | None: ... + +_excepthook: Callable[[_ExceptHookArgs], Any] + +if sys.version_info >= (3, 12): + def daemon_threads_allowed() -> bool: ... + +if sys.version_info >= (3, 14): + def set_name(name: str) -> None: ... + +@disjoint_base +class _local: + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... diff --git a/stdlib/_threading_local.pyi b/stdlib/_threading_local.pyi new file mode 100644 index 000000000000..7d4e61c6f2ec --- /dev/null +++ b/stdlib/_threading_local.pyi @@ -0,0 +1,24 @@ +from threading import RLock +from typing import Any, TypeAlias +from typing_extensions import Self +from weakref import ReferenceType + +__all__ = ["local"] +_LocalDict: TypeAlias = dict[Any, Any] + +class _localimpl: + __slots__ = ("key", "dicts", "localargs", "locallock", "__weakref__") + key: str + dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]] + # Keep localargs in sync with the *args, **kwargs annotation on local.__new__ + localargs: tuple[list[Any], dict[str, Any]] + locallock: RLock + def get_dict(self) -> _LocalDict: ... + def create_dict(self) -> _LocalDict: ... + +class local: + __slots__ = ("_local__impl", "__dict__") + def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... + def __getattribute__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __delattr__(self, name: str) -> None: ... diff --git a/stdlib/_tkinter.pyi b/stdlib/_tkinter.pyi new file mode 100644 index 000000000000..500345f91e06 --- /dev/null +++ b/stdlib/_tkinter.pyi @@ -0,0 +1,156 @@ +import sys +from _typeshed import FileDescriptorLike, Incomplete +from collections.abc import Callable +from typing import Any, ClassVar, Final, Literal, TypeAlias, final, overload +from typing_extensions import deprecated + +# _tkinter is meant to be only used internally by tkinter, but some tkinter +# functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl +# object that hasn't been converted to a string. +# +# There are not many ways to get Tcl_Objs from tkinter, and I'm not sure if the +# only existing ways are supposed to return Tcl_Objs as opposed to returning +# strings. Here's one of these things that return Tcl_Objs: +# +# >>> import tkinter +# >>> text = tkinter.Text() +# >>> text.tag_add('foo', '1.0', 'end') +# >>> text.tag_ranges('foo') +# (, ) +@final +class Tcl_Obj: + @property + def string(self) -> str: ... + @property + def typename(self) -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, value, /): ... + def __ge__(self, value, /): ... + def __gt__(self, value, /): ... + def __le__(self, value, /): ... + def __lt__(self, value, /): ... + def __ne__(self, value, /): ... + +class TclError(Exception): ... + +_TkinterTraceFunc: TypeAlias = Callable[[tuple[str, ...]], object] + +# This class allows running Tcl code. Tkinter uses it internally a lot, and +# it's often handy to drop a piece of Tcl code into a tkinter program. Example: +# +# >>> import tkinter, _tkinter +# >>> tkapp = tkinter.Tk().tk +# >>> isinstance(tkapp, _tkinter.TkappType) +# True +# >>> tkapp.call('set', 'foo', (1,2,3)) +# (1, 2, 3) +# >>> tkapp.eval('return $foo') +# '1 2 3' +# >>> +# +# call args can be pretty much anything. Also, call(some_tuple) is same as call(*some_tuple). +# +# eval always returns str because _tkinter_tkapp_eval_impl in _tkinter.c calls +# Tkapp_UnicodeResult, and it returns a string when it succeeds. +@final +class TkappType: + # Please keep in sync with tkinter.Tk + def adderrorinfo(self, msg: str, /) -> None: ... + def call(self, command: Any, /, *args: Any) -> Any: ... + # TODO: Figure out what arguments the following `func` callbacks should accept + def createcommand(self, name: str, func: Callable[..., object], /) -> None: ... + if sys.platform != "win32": + def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ... + def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ... + + def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ... + def deletecommand(self, name: str, /) -> None: ... + def dooneevent(self, flags: int = 0, /) -> int: ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName: str, /) -> str: ... + def exprboolean(self, s: str, /) -> Literal[0, 1]: ... + def exprdouble(self, s: str, /) -> float: ... + def exprlong(self, s: str, /) -> int: ... + def exprstring(self, s: str, /) -> str: ... + def getboolean(self, arg, /) -> bool: ... + def getdouble(self, arg, /) -> float: ... + def getint(self, arg, /) -> int: ... + def getvar(self, *args, **kwargs): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self) -> int: ... + def loadtk(self) -> None: ... + def mainloop(self, threshold: int = 0, /) -> None: ... + def quit(self) -> None: ... + def record(self, script: str, /) -> str: ... + def setvar(self, *ags, **kwargs): ... + if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.") + def split(self, arg, /): ... + + def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... + def unsetvar(self, *args, **kwargs): ... + + if sys.version_info >= (3, 14): + @overload + def wantobjects(self) -> Literal[0, 1]: ... + else: + @overload + def wantobjects(self) -> bool: ... + + @overload + def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + + def willdispatch(self) -> None: ... + if sys.version_info >= (3, 12): + def gettrace(self, /) -> _TkinterTraceFunc | None: ... + def settrace(self, func: _TkinterTraceFunc | None, /) -> None: ... + +# These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS +ALL_EVENTS: Final = -3 +FILE_EVENTS: Final = 8 +IDLE_EVENTS: Final = 32 +TIMER_EVENTS: Final = 16 +WINDOW_EVENTS: Final = 4 + +DONT_WAIT: Final = 2 +EXCEPTION: Final = 8 +READABLE: Final = 2 +WRITABLE: Final = 4 + +TCL_VERSION: Final[str] +TK_VERSION: Final[str] + +@final +class TkttType: + def deletetimerhandler(self) -> None: ... + +if sys.version_info >= (3, 13): + def create( + screenName: str | None = None, + baseName: str = "", + className: str = "Tk", + interactive: bool = False, + wantobjects: int = 0, + wantTk: bool = True, + sync: bool = False, + use: str | None = None, + /, + ) -> TkappType: ... + +else: + def create( + screenName: str | None = None, + baseName: str = "", + className: str = "Tk", + interactive: bool = False, + wantobjects: bool = False, + wantTk: bool = True, + sync: bool = False, + use: str | None = None, + /, + ) -> TkappType: ... + +def getbusywaitinterval() -> int: ... +def setbusywaitinterval(new_val: int, /) -> None: ... diff --git a/stdlib/_tracemalloc.pyi b/stdlib/_tracemalloc.pyi new file mode 100644 index 000000000000..e9720f46692c --- /dev/null +++ b/stdlib/_tracemalloc.pyi @@ -0,0 +1,13 @@ +from collections.abc import Sequence +from tracemalloc import _FrameTuple, _TraceTuple + +def _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: ... +def _get_traces() -> Sequence[_TraceTuple]: ... +def clear_traces() -> None: ... +def get_traceback_limit() -> int: ... +def get_traced_memory() -> tuple[int, int]: ... +def get_tracemalloc_memory() -> int: ... +def is_tracing() -> bool: ... +def reset_peak() -> None: ... +def start(nframe: int = 1, /) -> None: ... +def stop() -> None: ... diff --git a/stdlib/_typeshed/README.md b/stdlib/_typeshed/README.md new file mode 100644 index 000000000000..3e4f3cb5cd48 --- /dev/null +++ b/stdlib/_typeshed/README.md @@ -0,0 +1,34 @@ +# Utility types for typeshed + +This package and its submodules contain various common types used by +typeshed. It can also be used by packages outside typeshed, but beware +the API stability guarantees below. + +## Usage + +The `_typeshed` package and its types do not exist at runtime, but can be +used freely in stubs (`.pyi`) files. To import the types from this package in +implementation (`.py`) files, use the following construct: + +```python +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from _typeshed import ... +``` + +Types can then be used in annotations by either quoting them or +using: + +```python +from __future__ import annotations +``` + +## API Stability + +You can use this package and its submodules outside of typeshed, but we +guarantee only limited API stability. Items marked as "stable" will not be +removed or changed in an incompatible way for at least one year. +Before making such a change, the "stable" moniker will be removed +and we will mark the type in question as deprecated. No guarantees +are made about unmarked types. diff --git a/stdlib/_typeshed/__init__.pyi b/stdlib/_typeshed/__init__.pyi new file mode 100644 index 000000000000..5b2d7f7c549f --- /dev/null +++ b/stdlib/_typeshed/__init__.pyi @@ -0,0 +1,401 @@ +# Utility types for typeshed +# +# See the README.md file in this directory for more information. + +import sys +from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence, Set as AbstractSet, Sized +from dataclasses import Field +from os import PathLike +from types import FrameType, NoneType as NoneType, TracebackType +from typing import ( + Any, + AnyStr, + ClassVar, + Final, + Generic, + Literal, + Protocol, + SupportsFloat, + SupportsIndex, + SupportsInt, + TypeAlias, + TypeVar, + overload, +) +from typing_extensions import Buffer, LiteralString, Self as _Self + +_KT = TypeVar("_KT") +_KT_co = TypeVar("_KT_co", covariant=True) +_KT_contra = TypeVar("_KT_contra", contravariant=True) +_VT = TypeVar("_VT") +_VT_co = TypeVar("_VT_co", covariant=True) +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) + +# Alternative to `typing_extensions.Self`, exclusively for use with `__new__` +# in metaclasses: +# def __new__(cls: type[Self], ...) -> Self: ... +# In other cases, use `typing_extensions.Self`. +Self = TypeVar("Self") # noqa: Y001 + +# covariant version of typing.AnyStr, useful for protocols +AnyStr_co = TypeVar("AnyStr_co", str, bytes, covariant=True) # noqa: Y001 + +# For partially known annotations. Usually, fields where type annotations +# haven't been added are left unannotated, but in some situations this +# isn't possible or a type is already partially known. In cases like these, +# use Incomplete instead of Any as a marker. For example, use +# "Incomplete | None" instead of "Any | None". +Incomplete: TypeAlias = Any # stable + +# To describe a function parameter that is unused and will work with anything. +Unused: TypeAlias = object # stable + +# Marker for return types that include None, but where forcing the user to +# check for None can be detrimental. Sometimes called "the Any trick". See +# https://typing.python.org/en/latest/guides/writing_stubs.html#the-any-trick +# for more information. +MaybeNone: TypeAlias = Any # stable + +# typeshed-internal type aliases to facilitate transition from +# `float` to either `float | int` or `float` (and similar for `complex`). +# When you encounter one of these type aliases, you are encouraged to +# replace them with the correct type. Please don't use them outside typeshed. +# See https://github.com/python/typeshed/issues/16059 for details. +FloatInt: TypeAlias = float | int +ComplexInt: TypeAlias = complex | float | int + +# Used to mark arguments that default to a sentinel value. This prevents +# stubtest from complaining about the default value not matching. +# +# def foo(x: int | None = sentinel) -> None: ... +# +# In cases where the sentinel object is exported and can be used by user code, +# a construct like this is better: +# +# _SentinelType = NewType("_SentinelType", object) # does not exist at runtime +# sentinel: Final[_SentinelType] +# def foo(x: int | None | _SentinelType = ...) -> None: ... +sentinel: Any # stable + +# stable +class IdentityFunction(Protocol): + def __call__(self, x: _T, /) -> _T: ... + +# stable +class SupportsNext(Protocol[_T_co]): + def __next__(self) -> _T_co: ... + +# stable +class SupportsAnext(Protocol[_T_co]): + def __anext__(self) -> Awaitable[_T_co]: ... + +class SupportsBool(Protocol): + def __bool__(self) -> bool: ... + +# Comparison protocols +class SupportsDunderLT(Protocol[_T_contra]): + def __lt__(self, other: _T_contra, /) -> SupportsBool: ... + +class SupportsDunderGT(Protocol[_T_contra]): + def __gt__(self, other: _T_contra, /) -> SupportsBool: ... + +class SupportsDunderLE(Protocol[_T_contra]): + def __le__(self, other: _T_contra, /) -> SupportsBool: ... + +class SupportsDunderGE(Protocol[_T_contra]): + def __ge__(self, other: _T_contra, /) -> SupportsBool: ... + +class SupportsAllComparisons( + SupportsDunderLT[Any], SupportsDunderGT[Any], SupportsDunderLE[Any], SupportsDunderGE[Any], Protocol +): ... + +SupportsRichComparison: TypeAlias = SupportsDunderLT[Any] | SupportsDunderGT[Any] +SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichComparison) # noqa: Y001 + +# Dunder protocols + +class SupportsAdd(Protocol[_T_contra, _T_co]): + def __add__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRAdd(Protocol[_T_contra, _T_co]): + def __radd__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsSub(Protocol[_T_contra, _T_co]): + def __sub__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRSub(Protocol[_T_contra, _T_co]): + def __rsub__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsMul(Protocol[_T_contra, _T_co]): + def __mul__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsRMul(Protocol[_T_contra, _T_co]): + def __rmul__(self, x: _T_contra, /) -> _T_co: ... + +class SupportsMod(Protocol[_T_contra, _T_co]): + def __mod__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsRMod(Protocol[_T_contra, _T_co]): + def __rmod__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsDivMod(Protocol[_T_contra, _T_co]): + def __divmod__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsRDivMod(Protocol[_T_contra, _T_co]): + def __rdivmod__(self, other: _T_contra, /) -> _T_co: ... + +# This protocol is generic over the iterator type, while Iterable is +# generic over the type that is iterated over. +class SupportsIter(Protocol[_T_co]): + def __iter__(self) -> _T_co: ... + +# This protocol is generic over the iterator type, while AsyncIterable is +# generic over the type that is iterated over. +class SupportsAiter(Protocol[_T_co]): + def __aiter__(self) -> _T_co: ... + +class SupportsLen(Protocol): + def __len__(self) -> int: ... + +class SupportsLenAndGetItem(Protocol[_T_co]): + def __len__(self) -> int: ... + def __getitem__(self, k: int, /) -> _T_co: ... + +class SupportsTrunc(Protocol): + def __trunc__(self) -> int: ... + +# Mapping-like protocols + +# stable +class SupportsItems(Protocol[_KT_co, _VT_co]): + def items(self) -> AbstractSet[tuple[_KT_co, _VT_co]]: ... + +# stable +class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): + def keys(self) -> Iterable[_KT]: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + +# stable +class SupportsGetItem(Protocol[_KT_contra, _VT_co]): + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... + +# stable +class SupportsContainsAndGetItem(Protocol[_KT_contra, _VT_co]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... + +# stable +class SupportsItemAccess(Protocol[_KT_contra, _VT]): + def __contains__(self, x: Any, /) -> bool: ... + def __getitem__(self, key: _KT_contra, /) -> _VT: ... + def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT_contra, /) -> None: ... + +StrPath: TypeAlias = str | PathLike[str] # stable +BytesPath: TypeAlias = bytes | PathLike[bytes] # stable +GenericPath: TypeAlias = AnyStr | PathLike[AnyStr] +StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable + +OpenTextModeUpdating: TypeAlias = Literal[ + "r+", + "+r", + "rt+", + "r+t", + "+rt", + "tr+", + "t+r", + "+tr", + "w+", + "+w", + "wt+", + "w+t", + "+wt", + "tw+", + "t+w", + "+tw", + "a+", + "+a", + "at+", + "a+t", + "+at", + "ta+", + "t+a", + "+ta", + "x+", + "+x", + "xt+", + "x+t", + "+xt", + "tx+", + "t+x", + "+tx", +] +OpenTextModeWriting: TypeAlias = Literal["w", "wt", "tw", "a", "at", "ta", "x", "xt", "tx"] +OpenTextModeReading: TypeAlias = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] +OpenTextMode: TypeAlias = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading +OpenBinaryModeUpdating: TypeAlias = Literal[ + "rb+", + "r+b", + "+rb", + "br+", + "b+r", + "+br", + "wb+", + "w+b", + "+wb", + "bw+", + "b+w", + "+bw", + "ab+", + "a+b", + "+ab", + "ba+", + "b+a", + "+ba", + "xb+", + "x+b", + "+xb", + "bx+", + "b+x", + "+bx", +] +OpenBinaryModeWriting: TypeAlias = Literal["wb", "bw", "ab", "ba", "xb", "bx"] +OpenBinaryModeReading: TypeAlias = Literal["rb", "br", "rbU", "rUb", "Urb", "brU", "bUr", "Ubr"] +OpenBinaryMode: TypeAlias = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting + +# stable +class HasFileno(Protocol): + def fileno(self) -> int: ... + +FileDescriptor: TypeAlias = int # stable +FileDescriptorLike: TypeAlias = int | HasFileno # stable +FileDescriptorOrPath: TypeAlias = int | StrOrBytesPath + +# stable +class SupportsRead(Protocol[_T_co]): + def read(self, length: int = ..., /) -> _T_co: ... + +# stable +class SupportsReadline(Protocol[_T_co]): + def readline(self, length: int = ..., /) -> _T_co: ... + +# stable +class SupportsNoArgReadline(Protocol[_T_co]): + def readline(self) -> _T_co: ... + +# stable +class SupportsWrite(Protocol[_T_contra]): + def write(self, s: _T_contra, /) -> object: ... + +# stable +class SupportsFlush(Protocol): + def flush(self) -> object: ... + +# Suitable for dictionary view objects +class Viewable(Protocol[_T_co]): + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T_co]: ... + +class SupportsGetItemViewable(Protocol[_KT, _VT_co]): + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_KT]: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + +# Unfortunately PEP 688 does not allow us to distinguish read-only +# from writable buffers. We use these aliases for readability for now. +# Perhaps a future extension of the buffer protocol will allow us to +# distinguish these cases in the type system. +ReadOnlyBuffer: TypeAlias = Buffer # stable +# Anything that implements the read-write buffer interface. +WriteableBuffer: TypeAlias = Buffer +# Same as WriteableBuffer, but also includes read-only buffer types (like bytes). +ReadableBuffer: TypeAlias = Buffer # stable + +class SliceableBuffer(Buffer, Protocol): + def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ... + +class IndexableBuffer(Buffer, Protocol): + def __getitem__(self, i: int, /) -> int: ... + +class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol): + def __contains__(self, x: Any, /) -> bool: ... + + @overload + def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ... + @overload + def __getitem__(self, i: int, /) -> int: ... + +class SizedBuffer(Sized, Buffer, Protocol): ... + +ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType] +OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None] + +# This is an internal CPython type that is like, but subtly different from, a NamedTuple +# Subclasses of this type are found in multiple modules. +# In typeshed, `structseq` is only ever used as a mixin in combination with a fixed-length `Tuple` +# See discussion at #6546 & #6560 +# `structseq` classes are unsubclassable, so are all decorated with `@final`. +class structseq(Generic[_T_co]): + n_fields: Final[int] + n_unnamed_fields: Final[int] + n_sequence_fields: Final[int] + # The first parameter will generally only take an iterable of a specific length. + # E.g. `os.uname_result` takes any iterable of length exactly 5. + # + # The second parameter will accept a dict of any kind without raising an exception, + # but only has any meaning if you supply it a dict where the keys are strings. + # https://github.com/python/typeshed/pull/6560#discussion_r767149830 + def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _Self: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> _Self: ... + +# Superset of typing.AnyStr that also includes LiteralString +AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001 + +# Represents when str or LiteralStr is acceptable. Useful for string processing +# APIs where literalness of return value depends on literalness of inputs +StrOrLiteralStr = TypeVar("StrOrLiteralStr", LiteralString, str) # noqa: Y001 + +# Objects suitable to be passed to sys.setprofile, threading.setprofile, and similar +ProfileFunction: TypeAlias = Callable[[FrameType, Literal["call", "return", "c_call", "c_return", "c_exception"], Any], object] + +# Objects suitable to be passed to sys.settrace, threading.settrace, and similar +TraceFunction: TypeAlias = Callable[ + [FrameType, Literal["call", "line", "return", "exception", "opcode"], Any], TraceFunction | None +] + +# experimental +# Might not work as expected for pyright, see +# https://github.com/python/typeshed/pull/9362 +# https://github.com/microsoft/pyright/issues/4339 +class DataclassInstance(Protocol): + __dataclass_fields__: ClassVar[dict[str, Field[Any]]] + +# Anything that can be passed to the int/float constructors +if sys.version_info >= (3, 14): + ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex +else: + ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc +ConvertibleToFloat: TypeAlias = str | ReadableBuffer | SupportsFloat | SupportsIndex + +# A few classes updated from Foo(str, Enum) to Foo(StrEnum). This is a convenience so these +# can be accurate on all python versions without getting too wordy +if sys.version_info >= (3, 11): + from enum import StrEnum as StrEnum +else: + from enum import Enum + + class StrEnum(str, Enum): ... + +# Objects that appear in annotations or in type expressions. +# Similar to PEP 747's TypeForm but a little broader. +AnnotationForm: TypeAlias = Any + +if sys.version_info >= (3, 14): + from annotationlib import Format + + # These return annotations, which can be arbitrary objects + AnnotateFunc: TypeAlias = Callable[[Format], dict[str, AnnotationForm]] + EvaluateFunc: TypeAlias = Callable[[Format], AnnotationForm] diff --git a/stdlib/_typeshed/_type_checker_internals.pyi b/stdlib/_typeshed/_type_checker_internals.pyi new file mode 100644 index 000000000000..a8411192a898 --- /dev/null +++ b/stdlib/_typeshed/_type_checker_internals.pyi @@ -0,0 +1,99 @@ +# Internals used by some type checkers. +# +# Don't use this module directly. It is only for type checkers to use. + +import sys +import typing_extensions +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import AnnotationForm +from abc import ABCMeta +from collections.abc import Awaitable, Generator, Iterable, Mapping +from typing import Any, ClassVar, Generic, TypeVar, overload +from typing_extensions import Never + +_T = TypeVar("_T") + +# Used for an undocumented mypy feature. Does not exist at runtime. +promote = object() + +# Fallback type providing methods and attributes that appear on all `TypedDict` types. +# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict +class TypedDictFallback(Mapping[str, object], metaclass=ABCMeta): + __total__: ClassVar[bool] + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + # __orig_bases__ sometimes exists on <3.12, but not consistently, + # so we only add it to the stub on 3.12+ + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + if sys.version_info >= (3, 13): + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + if sys.version_info >= (3, 15): + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[AnnotationForm] + + def copy(self) -> typing_extensions.Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: Never, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: typing_extensions.Self, /) -> None: ... + def __delitem__(self, k: Never) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + + @overload + def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of __or__ and __ior__ + def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] + +# Fallback type providing methods and attributes that appear on all `NamedTuple` types. +class NamedTupleFallback(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __match_args__: ClassVar[tuple[str, ...]] = ... + # __orig_bases__ sometimes exists on <3.12, but not consistently + # So we only add it to the stub on 3.12+. + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... + @overload + @typing_extensions.deprecated( + "Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15" + ) + def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + + @classmethod + def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... + def _asdict(self) -> dict[str, Any]: ... + def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... + +# Non-default variations to accommodate couroutines, and `AwaitableGenerator` having a 4th type parameter. +_S = TypeVar("_S") +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) + +# The parameters correspond to Generator, but the 4th is the original type. +class AwaitableGenerator( + Awaitable[_ReturnT_nd_co], + Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co], + Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S], + metaclass=ABCMeta, +): ... diff --git a/stdlib/_typeshed/dbapi.pyi b/stdlib/_typeshed/dbapi.pyi new file mode 100644 index 000000000000..e08a84553dfc --- /dev/null +++ b/stdlib/_typeshed/dbapi.pyi @@ -0,0 +1,36 @@ +# PEP 249 Database API 2.0 Types +# https://www.python.org/dev/peps/pep-0249/ + +from collections.abc import Mapping, Sequence +from typing import Any, Protocol, TypeAlias + +DBAPITypeCode: TypeAlias = Any | None +# Strictly speaking, this should be a Sequence, but the type system does +# not support fixed-length sequences. +DBAPIColumnDescription: TypeAlias = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] + +class DBAPIConnection(Protocol): + def close(self) -> object: ... + def commit(self) -> object: ... + # optional: + # def rollback(self) -> Any: ... + def cursor(self) -> DBAPICursor: ... + +class DBAPICursor(Protocol): + @property + def description(self) -> Sequence[DBAPIColumnDescription] | None: ... + @property + def rowcount(self) -> int: ... + # optional: + # def callproc(self, procname: str, parameters: Sequence[Any] = ..., /) -> Sequence[Any]: ... + def close(self) -> object: ... + def execute(self, operation: str, parameters: Sequence[Any] | Mapping[str, Any] = ..., /) -> object: ... + def executemany(self, operation: str, seq_of_parameters: Sequence[Sequence[Any]], /) -> object: ... + def fetchone(self) -> Sequence[Any] | None: ... + def fetchmany(self, size: int = ..., /) -> Sequence[Sequence[Any]]: ... + def fetchall(self) -> Sequence[Sequence[Any]]: ... + # optional: + # def nextset(self) -> None | Literal[True]: ... + arraysize: int + def setinputsizes(self, sizes: Sequence[DBAPITypeCode | int | None], /) -> object: ... + def setoutputsize(self, size: int, column: int = ..., /) -> object: ... diff --git a/stdlib/_typeshed/importlib.pyi b/stdlib/_typeshed/importlib.pyi new file mode 100644 index 000000000000..a4e56cdaff62 --- /dev/null +++ b/stdlib/_typeshed/importlib.pyi @@ -0,0 +1,18 @@ +# Implicit protocols used in importlib. +# We intentionally omit deprecated and optional methods. + +from collections.abc import Sequence +from importlib.machinery import ModuleSpec +from types import ModuleType +from typing import Protocol + +__all__ = ["LoaderProtocol", "MetaPathFinderProtocol", "PathEntryFinderProtocol"] + +class LoaderProtocol(Protocol): + def load_module(self, fullname: str, /) -> ModuleType: ... + +class MetaPathFinderProtocol(Protocol): + def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ..., /) -> ModuleSpec | None: ... + +class PathEntryFinderProtocol(Protocol): + def find_spec(self, fullname: str, target: ModuleType | None = ..., /) -> ModuleSpec | None: ... diff --git a/stdlib/_typeshed/wsgi.pyi b/stdlib/_typeshed/wsgi.pyi new file mode 100644 index 000000000000..980a24122252 --- /dev/null +++ b/stdlib/_typeshed/wsgi.pyi @@ -0,0 +1,43 @@ +# Types to support PEP 3333 (WSGI) +# +# Obsolete since Python 3.11: Use wsgiref.types instead. +# +# See the README.md file in this directory for more information. + +import sys +from _typeshed import OptExcInfo +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Protocol, TypeAlias + +class _Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + # Optional: def close(self) -> object: ... + +if sys.version_info >= (3, 11): + from wsgiref.types import * +else: + # stable + class StartResponse(Protocol): + def __call__( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / + ) -> Callable[[bytes], object]: ... + + WSGIEnvironment: TypeAlias = dict[str, Any] # stable + WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable + + # WSGI input streams per PEP 3333, stable + class InputStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + + # WSGI error streams per PEP 3333, stable + class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... + + # Optional file wrapper in wsgi.file_wrapper + class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/stdlib/_typeshed/xml.pyi b/stdlib/_typeshed/xml.pyi new file mode 100644 index 000000000000..6cd1b39af628 --- /dev/null +++ b/stdlib/_typeshed/xml.pyi @@ -0,0 +1,9 @@ +# See the README.md file in this directory for more information. + +from typing import Any, Protocol + +# As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects +class DOMImplementation(Protocol): + def hasFeature(self, feature: str, version: str | None, /) -> bool: ... + def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None, /) -> Any: ... + def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str, /) -> Any: ... diff --git a/stdlib/_warnings.pyi b/stdlib/_warnings.pyi new file mode 100644 index 000000000000..5f4648259025 --- /dev/null +++ b/stdlib/_warnings.pyi @@ -0,0 +1,54 @@ +import sys +from typing import Any, overload + +_defaultaction: str +_onceregistry: dict[Any, Any] +filters: list[tuple[str, str | None, type[Warning], str | None, int]] + +if sys.version_info >= (3, 12): + @overload + def warn( + message: str, + category: type[Warning] | None = None, + stacklevel: int = 1, + source: Any | None = None, + *, + skip_file_prefixes: tuple[str, ...] = (), + ) -> None: ... + @overload + def warn( + message: Warning, + category: Any = None, + stacklevel: int = 1, + source: Any | None = None, + *, + skip_file_prefixes: tuple[str, ...] = (), + ) -> None: ... +else: + @overload + def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ... + @overload + def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ... + +@overload +def warn_explicit( + message: str, + category: type[Warning], + filename: str, + lineno: int, + module: str | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = None, + module_globals: dict[str, Any] | None = None, + source: Any | None = None, +) -> None: ... +@overload +def warn_explicit( + message: Warning, + category: Any, + filename: str, + lineno: int, + module: str | None = None, + registry: dict[str | tuple[str, type[Warning], int], int] | None = None, + module_globals: dict[str, Any] | None = None, + source: Any | None = None, +) -> None: ... diff --git a/stdlib/_weakref.pyi b/stdlib/_weakref.pyi new file mode 100644 index 000000000000..a744340afaab --- /dev/null +++ b/stdlib/_weakref.pyi @@ -0,0 +1,15 @@ +from collections.abc import Callable +from typing import Any, TypeVar, overload +from weakref import CallableProxyType as CallableProxyType, ProxyType as ProxyType, ReferenceType as ReferenceType, ref as ref + +_C = TypeVar("_C", bound=Callable[..., Any]) +_T = TypeVar("_T") + +def getweakrefcount(object: Any, /) -> int: ... +def getweakrefs(object: Any, /) -> list[Any]: ... + +# Return CallableProxyType if object is callable, ProxyType otherwise +@overload +def proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: ... +@overload +def proxy(object: _T, callback: Callable[[_T], Any] | None = None, /) -> Any: ... diff --git a/stdlib/_weakrefset.pyi b/stdlib/_weakrefset.pyi new file mode 100644 index 000000000000..82ffa4463f48 --- /dev/null +++ b/stdlib/_weakrefset.pyi @@ -0,0 +1,49 @@ +from collections.abc import Iterable, Iterator, MutableSet +from types import GenericAlias +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import Self + +__all__ = ["WeakSet"] + +_S = TypeVar("_S") +_T = TypeVar("_T") + +class WeakSet(MutableSet[_T]): + @overload + def __init__(self, data: None = None) -> None: ... + @overload + def __init__(self, data: Iterable[_T]) -> None: ... + + def add(self, item: _T) -> None: ... + def discard(self, item: _T) -> None: ... + def copy(self) -> Self: ... + def remove(self, item: _T) -> None: ... + def update(self, other: Iterable[_T]) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __ior__(self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] + def difference(self, other: Iterable[_T]) -> Self: ... + def __sub__(self, other: Iterable[Any]) -> Self: ... + def difference_update(self, other: Iterable[Any]) -> None: ... + def __isub__(self, other: Iterable[Any]) -> Self: ... + def intersection(self, other: Iterable[_T]) -> Self: ... + def __and__(self, other: Iterable[Any]) -> Self: ... + def intersection_update(self, other: Iterable[Any]) -> None: ... + def __iand__(self, other: Iterable[Any]) -> Self: ... + def issubset(self, other: Iterable[_T]) -> bool: ... + def __le__(self, other: Iterable[_T]) -> bool: ... + def __lt__(self, other: Iterable[_T]) -> bool: ... + def issuperset(self, other: Iterable[_T]) -> bool: ... + def __ge__(self, other: Iterable[_T]) -> bool: ... + def __gt__(self, other: Iterable[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def symmetric_difference_update(self, other: Iterable[_T]) -> None: ... + def __ixor__(self, other: Iterable[_T]) -> Self: ... # type: ignore[override,misc] + def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... + def isdisjoint(self, other: Iterable[_T]) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/_winapi.pyi b/stdlib/_winapi.pyi new file mode 100644 index 000000000000..3c520028e9c6 --- /dev/null +++ b/stdlib/_winapi.pyi @@ -0,0 +1,319 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Sequence +from typing import Any, Final, Literal, final, overload +from typing_extensions import Never + +if sys.platform == "win32": + ABOVE_NORMAL_PRIORITY_CLASS: Final = 0x8000 + BELOW_NORMAL_PRIORITY_CLASS: Final = 0x4000 + + CREATE_BREAKAWAY_FROM_JOB: Final = 0x1000000 + CREATE_DEFAULT_ERROR_MODE: Final = 0x4000000 + CREATE_NO_WINDOW: Final = 0x8000000 + CREATE_NEW_CONSOLE: Final = 0x10 + CREATE_NEW_PROCESS_GROUP: Final = 0x200 + + DETACHED_PROCESS: Final = 8 + DUPLICATE_CLOSE_SOURCE: Final = 1 + DUPLICATE_SAME_ACCESS: Final = 2 + + ERROR_ALREADY_EXISTS: Final = 183 + ERROR_BROKEN_PIPE: Final = 109 + ERROR_IO_PENDING: Final = 997 + ERROR_MORE_DATA: Final = 234 + ERROR_NETNAME_DELETED: Final = 64 + ERROR_NO_DATA: Final = 232 + ERROR_NO_SYSTEM_RESOURCES: Final = 1450 + ERROR_OPERATION_ABORTED: Final = 995 + ERROR_PIPE_BUSY: Final = 231 + ERROR_PIPE_CONNECTED: Final = 535 + ERROR_SEM_TIMEOUT: Final = 121 + + if sys.version_info >= (3, 15): + EVENTLOG_AUDIT_FAILURE: Final = 16 + EVENTLOG_AUDIT_SUCCESS: Final = 8 + EVENTLOG_ERROR_TYPE: Final = 1 + EVENTLOG_INFORMATION_TYPE: Final = 4 + EVENTLOG_SUCCESS: Final = 0 + EVENTLOG_WARNING_TYPE: Final = 2 + + FILE_FLAG_FIRST_PIPE_INSTANCE: Final = 0x80000 + FILE_FLAG_OVERLAPPED: Final = 0x40000000 + + FILE_GENERIC_READ: Final = 1179785 + FILE_GENERIC_WRITE: Final = 1179926 + + FILE_MAP_ALL_ACCESS: Final = 983071 + FILE_MAP_COPY: Final = 1 + FILE_MAP_EXECUTE: Final = 32 + FILE_MAP_READ: Final = 4 + FILE_MAP_WRITE: Final = 2 + + FILE_TYPE_CHAR: Final = 2 + FILE_TYPE_DISK: Final = 1 + FILE_TYPE_PIPE: Final = 3 + FILE_TYPE_REMOTE: Final = 32768 + FILE_TYPE_UNKNOWN: Final = 0 + + GENERIC_READ: Final = 0x80000000 + GENERIC_WRITE: Final = 0x40000000 + HIGH_PRIORITY_CLASS: Final = 0x80 + INFINITE: Final = 0xFFFFFFFF + # Ignore the Flake8 error -- flake8-pyi assumes + # most numbers this long will be implementation details, + # but here we can see that it's a power of 2 + INVALID_HANDLE_VALUE: Final = 0xFFFFFFFFFFFFFFFF # noqa: Y054 + IDLE_PRIORITY_CLASS: Final = 0x40 + NORMAL_PRIORITY_CLASS: Final = 0x20 + REALTIME_PRIORITY_CLASS: Final = 0x100 + NMPWAIT_WAIT_FOREVER: Final = 0xFFFFFFFF + + MEM_COMMIT: Final = 0x1000 + MEM_FREE: Final = 0x10000 + MEM_IMAGE: Final = 0x1000000 + MEM_MAPPED: Final = 0x40000 + MEM_PRIVATE: Final = 0x20000 + MEM_RESERVE: Final = 0x2000 + + NULL: Final = 0 + OPEN_EXISTING: Final = 3 + + PIPE_ACCESS_DUPLEX: Final = 3 + PIPE_ACCESS_INBOUND: Final = 1 + PIPE_READMODE_MESSAGE: Final = 2 + PIPE_TYPE_MESSAGE: Final = 4 + PIPE_UNLIMITED_INSTANCES: Final = 255 + PIPE_WAIT: Final = 0 + + PAGE_EXECUTE: Final = 0x10 + PAGE_EXECUTE_READ: Final = 0x20 + PAGE_EXECUTE_READWRITE: Final = 0x40 + PAGE_EXECUTE_WRITECOPY: Final = 0x80 + PAGE_GUARD: Final = 0x100 + PAGE_NOACCESS: Final = 0x1 + PAGE_NOCACHE: Final = 0x200 + PAGE_READONLY: Final = 0x2 + PAGE_READWRITE: Final = 0x4 + PAGE_WRITECOMBINE: Final = 0x400 + PAGE_WRITECOPY: Final = 0x8 + + PROCESS_ALL_ACCESS: Final = 0x1FFFFF + PROCESS_DUP_HANDLE: Final = 0x40 + + SEC_COMMIT: Final = 0x8000000 + SEC_IMAGE: Final = 0x1000000 + SEC_LARGE_PAGES: Final = 0x80000000 + SEC_NOCACHE: Final = 0x10000000 + SEC_RESERVE: Final = 0x4000000 + SEC_WRITECOMBINE: Final = 0x40000000 + + if sys.version_info >= (3, 13): + STARTF_FORCEOFFFEEDBACK: Final = 0x80 + STARTF_FORCEONFEEDBACK: Final = 0x40 + STARTF_PREVENTPINNING: Final = 0x2000 + STARTF_RUNFULLSCREEN: Final = 0x20 + STARTF_TITLEISAPPID: Final = 0x1000 + STARTF_TITLEISLINKNAME: Final = 0x800 + STARTF_UNTRUSTEDSOURCE: Final = 0x8000 + STARTF_USECOUNTCHARS: Final = 0x8 + STARTF_USEFILLATTRIBUTE: Final = 0x10 + STARTF_USEHOTKEY: Final = 0x200 + STARTF_USEPOSITION: Final = 0x4 + STARTF_USESIZE: Final = 0x2 + + STARTF_USESHOWWINDOW: Final = 0x1 + STARTF_USESTDHANDLES: Final = 0x100 + + STD_ERROR_HANDLE: Final = 0xFFFFFFF4 + STD_OUTPUT_HANDLE: Final = 0xFFFFFFF5 + STD_INPUT_HANDLE: Final = 0xFFFFFFF6 + + STILL_ACTIVE: Final = 259 + SW_HIDE: Final = 0 + SYNCHRONIZE: Final = 0x100000 + WAIT_ABANDONED_0: Final = 128 + WAIT_OBJECT_0: Final = 0 + WAIT_TIMEOUT: Final = 258 + + LOCALE_NAME_INVARIANT: Final[str] + LOCALE_NAME_MAX_LENGTH: Final[int] + LOCALE_NAME_SYSTEM_DEFAULT: Final[str] + LOCALE_NAME_USER_DEFAULT: Final[str | None] + + LCMAP_FULLWIDTH: Final[int] + LCMAP_HALFWIDTH: Final[int] + LCMAP_HIRAGANA: Final[int] + LCMAP_KATAKANA: Final[int] + LCMAP_LINGUISTIC_CASING: Final[int] + LCMAP_LOWERCASE: Final[int] + LCMAP_SIMPLIFIED_CHINESE: Final[int] + LCMAP_TITLECASE: Final[int] + LCMAP_TRADITIONAL_CHINESE: Final[int] + LCMAP_UPPERCASE: Final[int] + + if sys.version_info >= (3, 12): + COPYFILE2_CALLBACK_CHUNK_STARTED: Final = 1 + COPYFILE2_CALLBACK_CHUNK_FINISHED: Final = 2 + COPYFILE2_CALLBACK_STREAM_STARTED: Final = 3 + COPYFILE2_CALLBACK_STREAM_FINISHED: Final = 4 + COPYFILE2_CALLBACK_POLL_CONTINUE: Final = 5 + COPYFILE2_CALLBACK_ERROR: Final = 6 + + COPYFILE2_PROGRESS_CONTINUE: Final = 0 + COPYFILE2_PROGRESS_CANCEL: Final = 1 + COPYFILE2_PROGRESS_STOP: Final = 2 + COPYFILE2_PROGRESS_QUIET: Final = 3 + COPYFILE2_PROGRESS_PAUSE: Final = 4 + + COPY_FILE_FAIL_IF_EXISTS: Final = 0x1 + COPY_FILE_RESTARTABLE: Final = 0x2 + COPY_FILE_OPEN_SOURCE_FOR_WRITE: Final = 0x4 + COPY_FILE_ALLOW_DECRYPTED_DESTINATION: Final = 0x8 + COPY_FILE_COPY_SYMLINK: Final = 0x800 + COPY_FILE_NO_BUFFERING: Final = 0x1000 + COPY_FILE_REQUEST_SECURITY_PRIVILEGES: Final = 0x2000 + COPY_FILE_RESUME_FROM_PAUSE: Final = 0x4000 + COPY_FILE_NO_OFFLOAD: Final = 0x40000 + COPY_FILE_REQUEST_COMPRESSED_TRAFFIC: Final = 0x10000000 + + ERROR_ACCESS_DENIED: Final = 5 + ERROR_PRIVILEGE_NOT_HELD: Final = 1314 + + if sys.version_info >= (3, 14): + COPY_FILE_DIRECTORY: Final = 0x00000080 + + def CloseHandle(handle: int, /) -> None: ... + + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[False] = False) -> None: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... + + def CreateFile( + file_name: str, + desired_access: int, + share_mode: int, + security_attributes: int, + creation_disposition: int, + flags_and_attributes: int, + template_file: int, + /, + ) -> int: ... + def CreateFileMapping( + file_handle: int, security_attributes: int, protect: int, max_size_high: int, max_size_low: int, name: str, / + ) -> int: ... + def CreateJunction(src_path: str, dst_path: str, /) -> None: ... + def CreateNamedPipe( + name: str, + open_mode: int, + pipe_mode: int, + max_instances: int, + out_buffer_size: int, + in_buffer_size: int, + default_timeout: int, + security_attributes: int, + /, + ) -> int: ... + def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: ... + def CreateProcess( + application_name: str | None, + command_line: str | None, + proc_attrs: Any, + thread_attrs: Any, + inherit_handles: bool, + creation_flags: int, + env_mapping: dict[str, str], + current_directory: str | None, + startup_info: Any, + /, + ) -> tuple[int, int, int, int]: ... + def DuplicateHandle( + source_process_handle: int, + source_handle: int, + target_process_handle: int, + desired_access: int, + inherit_handle: bool, + options: int = 0, + /, + ) -> int: ... + def ExitProcess(ExitCode: int, /) -> Never: ... + def GetACP() -> int: ... + if sys.version_info >= (3, 15): + def DeregisterEventSource(handle: int, /) -> None: ... + def GetOEMCP() -> int: ... + + def GetFileType(handle: int) -> int: ... + def GetCurrentProcess() -> int: ... + def GetExitCodeProcess(process: int, /) -> int: ... + def GetLastError() -> int: ... + def GetModuleFileName(module_handle: int, /) -> str: ... + def GetStdHandle(std_handle: int, /) -> int: ... + def GetVersion() -> int: ... + def MapViewOfFile( + file_map: int, desired_access: int, file_offset_high: int, file_offset_low: int, number_bytes: int, / + ) -> int: ... + def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ... + def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ... + def LCMapStringEx(locale: str, flags: int, src: str) -> str: ... + if sys.version_info >= (3, 15): + def RegisterEventSource(unc_server_name: str | None, source_name: str, /) -> int: ... + def ReportEvent(handle: int, type: int, category: int, event_id: int, string: str, /) -> None: ... + + def UnmapViewOfFile(address: int, /) -> None: ... + + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[False] = False) -> tuple[bytes, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... + + def SetNamedPipeHandleState( + named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / + ) -> None: ... + def TerminateProcess(handle: int, exit_code: int, /) -> None: ... + def VirtualQuerySize(address: int, /) -> int: ... + def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ... + def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ... + def WaitNamedPipe(name: str, timeout: int, /) -> None: ... + + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[False] = False) -> tuple[int, int]: ... + @overload + def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ... + + @final + class Overlapped: + event: int + def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> bytes | None: ... + + if sys.version_info >= (3, 13): + def BatchedWaitForMultipleObjects( + handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF + ) -> list[int]: ... + def CreateEventW(security_attributes: int, manual_reset: bool, initial_state: bool, name: str | None) -> int: ... + def CreateMutexW(security_attributes: int, initial_owner: bool, name: str) -> int: ... + def GetLongPathName(path: str) -> str: ... + def GetShortPathName(path: str) -> str: ... + def OpenEventW(desired_access: int, inherit_handle: bool, name: str) -> int: ... + def OpenMutexW(desired_access: int, inherit_handle: bool, name: str) -> int: ... + def ReleaseMutex(mutex: int) -> None: ... + def ResetEvent(event: int) -> None: ... + def SetEvent(event: int) -> None: ... + + def OpenFileMapping(desired_access: int, inherit_handle: bool, name: str, /) -> int: ... + + if sys.version_info >= (3, 12): + def CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: ... + def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ... + + if sys.version_info >= (3, 13): + # Added in Python 3.13.15, 3.14.7 + def GetTickCount64() -> int: ... diff --git a/stdlib/_zstd.pyi b/stdlib/_zstd.pyi new file mode 100644 index 000000000000..34b619f9b0b6 --- /dev/null +++ b/stdlib/_zstd.pyi @@ -0,0 +1,102 @@ +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from compression.zstd import CompressionParameter, DecompressionParameter +from typing import Final, Literal, TypeAlias, final +from typing_extensions import Self + +ZSTD_CLEVEL_DEFAULT: Final = 3 +ZSTD_DStreamOutSize: Final = 131072 +ZSTD_btlazy2: Final = 6 +ZSTD_btopt: Final = 7 +ZSTD_btultra: Final = 8 +ZSTD_btultra2: Final = 9 +ZSTD_c_chainLog: Final = 103 +ZSTD_c_checksumFlag: Final = 201 +ZSTD_c_compressionLevel: Final = 100 +ZSTD_c_contentSizeFlag: Final = 200 +ZSTD_c_dictIDFlag: Final = 202 +ZSTD_c_enableLongDistanceMatching: Final = 160 +ZSTD_c_hashLog: Final = 102 +ZSTD_c_jobSize: Final = 401 +ZSTD_c_ldmBucketSizeLog: Final = 163 +ZSTD_c_ldmHashLog: Final = 161 +ZSTD_c_ldmHashRateLog: Final = 164 +ZSTD_c_ldmMinMatch: Final = 162 +ZSTD_c_minMatch: Final = 105 +ZSTD_c_nbWorkers: Final = 400 +ZSTD_c_overlapLog: Final = 402 +ZSTD_c_searchLog: Final = 104 +ZSTD_c_strategy: Final = 107 +ZSTD_c_targetLength: Final = 106 +ZSTD_c_windowLog: Final = 101 +ZSTD_d_windowLogMax: Final = 100 +ZSTD_dfast: Final = 2 +ZSTD_fast: Final = 1 +ZSTD_greedy: Final = 3 +ZSTD_lazy: Final = 4 +ZSTD_lazy2: Final = 5 + +_ZstdCompressorContinue: TypeAlias = Literal[0] +_ZstdCompressorFlushBlock: TypeAlias = Literal[1] +_ZstdCompressorFlushFrame: TypeAlias = Literal[2] + +@final +class ZstdCompressor: + CONTINUE: Final = 0 + FLUSH_BLOCK: Final = 1 + FLUSH_FRAME: Final = 2 + def __new__( + cls, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + def compress( + self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0 + ) -> bytes: ... + def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: ... + def set_pledged_input_size(self, size: int | None, /) -> None: ... + @property + def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: ... + +@final +class ZstdDecompressor: + def __new__( + cls, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None + ) -> Self: ... + def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: ... + @property + def eof(self) -> bool: ... + @property + def needs_input(self) -> bool: ... + @property + def unused_data(self) -> bytes: ... + +@final +class ZstdDict: + def __new__(cls, dict_content: ReadableBuffer, /, *, is_raw: bool = False) -> Self: ... + def __len__(self, /) -> int: ... + @property + def as_digested_dict(self) -> tuple[Self, int]: ... + @property + def as_prefix(self) -> tuple[Self, int]: ... + @property + def as_undigested_dict(self) -> tuple[Self, int]: ... + @property + def dict_content(self) -> bytes: ... + @property + def dict_id(self) -> int: ... + +class ZstdError(Exception): ... + +def finalize_dict( + custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, / +) -> bytes: ... +def get_frame_info(frame_buffer: ReadableBuffer) -> tuple[int, int]: ... +def get_frame_size(frame_buffer: ReadableBuffer) -> int: ... +def get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]: ... +def set_parameter_types(c_parameter_type: type[CompressionParameter], d_parameter_type: type[DecompressionParameter]) -> None: ... +def train_dict(samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, /) -> bytes: ... + +zstd_version: Final[str] +zstd_version_number: Final[int] diff --git a/stdlib/abc.pyi b/stdlib/abc.pyi new file mode 100644 index 000000000000..a43a641489a4 --- /dev/null +++ b/stdlib/abc.pyi @@ -0,0 +1,50 @@ +import _typeshed +import sys +from _typeshed import SupportsWrite +from collections.abc import Callable +from typing import Any, Concatenate, Literal, ParamSpec, TypeVar +from typing_extensions import deprecated + +_T = TypeVar("_T") +_R_co = TypeVar("_R_co", covariant=True) +_FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +# These definitions have special processing in mypy +class ABCMeta(type): + __abstractmethods__: frozenset[str] + if sys.version_info >= (3, 11): + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwargs: Any + ) -> _typeshed.Self: ... + else: + def __new__( + mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any + ) -> _typeshed.Self: ... + + def __instancecheck__(cls: ABCMeta, instance: Any, /) -> bool: ... + def __subclasscheck__(cls: ABCMeta, subclass: type, /) -> bool: ... + def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = None) -> None: ... + def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... + +def abstractmethod(funcobj: _FuncT) -> _FuncT: ... + +@deprecated("Deprecated since Python 3.3. Use `@classmethod` stacked on top of `@abstractmethod` instead.") +class abstractclassmethod(classmethod[_T, _P, _R_co]): + __isabstractmethod__: Literal[True] + def __init__(self, callable: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ... + +@deprecated("Deprecated since Python 3.3. Use `@staticmethod` stacked on top of `@abstractmethod` instead.") +class abstractstaticmethod(staticmethod[_P, _R_co]): + __isabstractmethod__: Literal[True] + def __init__(self, callable: Callable[_P, _R_co]) -> None: ... + +@deprecated("Deprecated since Python 3.3. Use `@property` stacked on top of `@abstractmethod` instead.") +class abstractproperty(property): + __isabstractmethod__: Literal[True] + +class ABC(metaclass=ABCMeta): + __slots__ = () + +def get_cache_token() -> object: ... +def update_abstractmethods(cls: type[_T]) -> type[_T]: ... diff --git a/stdlib/aifc.pyi b/stdlib/aifc.pyi new file mode 100644 index 000000000000..afb9029f710e --- /dev/null +++ b/stdlib/aifc.pyi @@ -0,0 +1,79 @@ +from types import TracebackType +from typing import IO, Any, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Self + +__all__ = ["Error", "open"] + +class Error(Exception): ... + +class _aifc_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: bytes + compname: bytes + +_File: TypeAlias = str | IO[bytes] +_Marker: TypeAlias = tuple[int, int, bytes] + +class Aifc_read: + def __init__(self, f: _File) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def initfp(self, file: IO[bytes]) -> None: ... + def getfp(self) -> IO[bytes]: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> bytes: ... + def getcompname(self) -> bytes: ... + def getparams(self) -> _aifc_params: ... + def getmarkers(self) -> list[_Marker] | None: ... + def getmark(self, id: int) -> _Marker: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes: ... + +class Aifc_write: + def __init__(self, f: _File) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def initfp(self, file: IO[bytes]) -> None: ... + def aiff(self) -> None: ... + def aifc(self) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: int) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: bytes, compname: bytes) -> None: ... + def getcomptype(self) -> bytes: ... + def getcompname(self) -> bytes: ... + def setparams(self, params: tuple[int, int, int, int, bytes, bytes]) -> None: ... + def getparams(self) -> _aifc_params: ... + def setmark(self, id: int, pos: int, name: bytes) -> None: ... + def getmark(self, id: int) -> _Marker: ... + def getmarkers(self) -> list[_Marker] | None: ... + def tell(self) -> int: ... + def writeframesraw(self, data: Any) -> None: ... # Actual type for data is Buffer Protocol + def writeframes(self, data: Any) -> None: ... + def close(self) -> None: ... + +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... +@overload +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/annotationlib.pyi b/stdlib/annotationlib.pyi new file mode 100644 index 000000000000..c3e843d95d9a --- /dev/null +++ b/stdlib/annotationlib.pyi @@ -0,0 +1,156 @@ +import sys +from typing import Literal + +if sys.version_info >= (3, 14): + import enum + import types + from _typeshed import AnnotateFunc, AnnotationForm, EvaluateFunc, SupportsItems + from collections.abc import Mapping + from typing import Any, ParamSpec, TypeVar, TypeVarTuple, final, overload + from warnings import deprecated + + __all__ = [ + "Format", + "ForwardRef", + "call_annotate_function", + "call_evaluate_function", + "get_annotate_from_class_namespace", + "get_annotations", + "annotations_to_string", + "type_repr", + ] + + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + @final + class ForwardRef: + __slots__ = ( + "__forward_is_argument__", + "__forward_is_class__", + "__forward_module__", + "__weakref__", + "__arg__", + "__globals__", + "__extra_names__", + "__code__", + "__ast_node__", + "__cell__", + "__owner__", + "__stringifier_dict__", + "__resolved_str_cache__", + ) + __forward_is_argument__: bool + __forward_is_class__: bool + __forward_module__: str | None + __resolved_str_cache__: str | None + def __init__( + self, arg: str, *, module: str | None = None, owner: object = None, is_argument: bool = True, is_class: bool = False + ) -> None: ... + + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Literal[Format.STRING], + ) -> str: ... + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Literal[Format.FORWARDREF], + ) -> AnnotationForm | ForwardRef: ... + @overload + def evaluate( + self, + *, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + owner: object = None, + format: Format = Format.VALUE, # noqa: Y011 + ) -> AnnotationForm: ... + + @deprecated("Use `ForwardRef.evaluate()` or `typing.evaluate_forward_ref()` instead.") + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ..., + *, + recursive_guard: frozenset[str], + ) -> AnnotationForm: ... + @property + def __forward_arg__(self) -> str: ... + @property + def __forward_code__(self) -> types.CodeType: ... + @property + def __resolved_str__(self) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __or__(self, other: Any) -> types.UnionType: ... + def __ror__(self, other: Any) -> types.UnionType: ... + + @overload + def call_evaluate_function(evaluate: EvaluateFunc, format: Literal[Format.STRING], *, owner: object = None) -> str: ... + @overload + def call_evaluate_function( + evaluate: EvaluateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None + ) -> AnnotationForm | ForwardRef: ... + @overload + def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ... + + @overload + def call_annotate_function( + annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None + ) -> dict[str, str]: ... + @overload + def call_annotate_function( + annotate: AnnotateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ... + + def get_annotate_from_class_namespace(obj: Mapping[str, object]) -> AnnotateFunc | None: ... + + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Literal[Format.STRING], + ) -> dict[str, str]: ... + @overload + def get_annotations( + obj: Any, + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Literal[Format.FORWARDREF], + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def get_annotations( + obj: Any, + *, + globals: dict[str, object] | None = None, + locals: Mapping[str, object] | None = None, + eval_str: bool = False, + format: Format = Format.VALUE, # noqa: Y011 + ) -> dict[str, AnnotationForm]: ... + + def type_repr(value: object) -> str: ... + def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]: ... diff --git a/stdlib/antigravity.pyi b/stdlib/antigravity.pyi new file mode 100644 index 000000000000..3986e7d1c9f2 --- /dev/null +++ b/stdlib/antigravity.pyi @@ -0,0 +1,3 @@ +from _typeshed import ReadableBuffer + +def geohash(latitude: float, longitude: float, datedow: ReadableBuffer) -> None: ... diff --git a/stdlib/argparse.pyi b/stdlib/argparse.pyi new file mode 100644 index 000000000000..9377497c0766 --- /dev/null +++ b/stdlib/argparse.pyi @@ -0,0 +1,864 @@ +import sys +from _typeshed import SupportsWrite, sentinel +from collections.abc import Callable, Generator, Iterable, Sequence +from re import Pattern +from typing import IO, Any, ClassVar, Final, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, deprecated + +__all__ = [ + "ArgumentParser", + "ArgumentError", + "ArgumentTypeError", + "FileType", + "HelpFormatter", + "ArgumentDefaultsHelpFormatter", + "RawDescriptionHelpFormatter", + "RawTextHelpFormatter", + "MetavarTypeHelpFormatter", + "Namespace", + "Action", + "BooleanOptionalAction", + "ONE_OR_MORE", + "OPTIONAL", + "PARSER", + "REMAINDER", + "SUPPRESS", + "ZERO_OR_MORE", +] + +_T = TypeVar("_T") +_ActionT = TypeVar("_ActionT", bound=Action) +_ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser) +_N = TypeVar("_N") +_ActionType: TypeAlias = Callable[[str], Any] | FileType | str + +ONE_OR_MORE: Final = "+" +OPTIONAL: Final = "?" +PARSER: Final = "A..." +REMAINDER: Final = "..." +SUPPRESS: Final = "==SUPPRESS==" +ZERO_OR_MORE: Final = "*" +_UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented + +class ArgumentError(Exception): + argument_name: str | None + message: str + def __init__(self, argument: Action | None, message: str) -> None: ... + +# undocumented +class _AttributeHolder: + def _get_kwargs(self) -> list[tuple[str, Any]]: ... + def _get_args(self) -> list[Any]: ... + +# undocumented +class _ActionsContainer: + description: str | None + prefix_chars: str + argument_default: Any + conflict_handler: str + + _registries: dict[str, dict[Any, Any]] + _actions: list[Action] + _option_string_actions: dict[str, Action] + _action_groups: list[_ArgumentGroup] + _mutually_exclusive_groups: list[_MutuallyExclusiveGroup] + _defaults: dict[str, Any] + _negative_number_matcher: Pattern[str] + _has_negative_number_optionals: list[bool] + def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ... + def register(self, registry_name: str, value: Any, object: Any) -> None: ... + def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any: ... + def set_defaults(self, **kwargs: Any) -> None: ... + def get_default(self, dest: str) -> Any: ... + def add_argument( + self, + *name_or_flags: str, + # str covers predefined actions ("store_true", "count", etc.) + # and user registered actions via the `register` method. + action: str | type[Action] = ..., + # more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="], + # but using this would make it hard to annotate callers that don't use a + # literal argument and for subclasses to override this method. + nargs: int | str | None = None, + const: Any = ..., + default: Any = ..., + type: _ActionType = ..., + choices: Iterable[Any] | None = ..., # choices must match the type specified + required: bool = ..., + help: str | None = ..., + metavar: str | tuple[str, ...] | None = ..., + dest: str | None = ..., + version: str = ..., + **kwargs: Any, + ) -> Action: ... + + @overload + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + # argument_default's type must be valid for the arguments in the group + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... + @overload + @deprecated("The `prefix_chars` parameter is deprecated.") + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... + + def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ... + def _add_action(self, action: _ActionT) -> _ActionT: ... + def _remove_action(self, action: Action) -> None: ... + def _add_container_actions(self, container: _ActionsContainer) -> None: ... + def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ... + def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... + def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ... + def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ... + def _check_conflict(self, action: Action) -> None: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> Never: ... + def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ... + +@type_check_only +class _FormatterClass(Protocol): + def __call__(self, *, prog: str) -> HelpFormatter: ... + +class ArgumentParser(_AttributeHolder, _ActionsContainer): + prog: str + usage: str | None + epilog: str | None + formatter_class: _FormatterClass + fromfile_prefix_chars: str | None + add_help: bool + allow_abbrev: bool + exit_on_error: bool + + if sys.version_info >= (3, 14): + suggest_on_error: bool + color: bool + + # undocumented + _positionals: _ArgumentGroup + _optionals: _ArgumentGroup + _subparsers: _ArgumentGroup | None + + # Note: the constructor arguments are also used in _SubParsersAction.add_parser. + if sys.version_info >= (3, 15): + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], + formatter_class: _FormatterClass = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + *, + suggest_on_error: bool = True, + color: bool = True, + ) -> None: ... + + elif sys.version_info >= (3, 14): + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], + formatter_class: _FormatterClass = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + *, + suggest_on_error: bool = False, + color: bool = True, + ) -> None: ... + else: + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], + formatter_class: _FormatterClass = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + ) -> None: ... + + @overload + def parse_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... + @overload + def parse_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... + @overload + def parse_args(self, *, namespace: _N) -> _N: ... + + @overload + def add_subparsers( + self: _ArgumentParserT, + *, + title: str = "subcommands", + description: str | None = None, + prog: str | None = None, + action: type[Action] = ..., + option_string: str = ..., + dest: str | None = None, + required: bool = False, + help: str | None = None, + metavar: str | None = None, + ) -> _SubParsersAction[_ArgumentParserT]: ... + @overload + def add_subparsers( + self, + *, + title: str = "subcommands", + description: str | None = None, + prog: str | None = None, + parser_class: type[_ArgumentParserT], + action: type[Action] = ..., + option_string: str = ..., + dest: str | None = None, + required: bool = False, + help: str | None = None, + metavar: str | None = None, + ) -> _SubParsersAction[_ArgumentParserT]: ... + + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_help(self, file: SupportsWrite[str] | None = None) -> None: ... + if sys.version_info >= (3, 15): + def format_usage(self, formatter: HelpFormatter | None = None) -> str: ... + def format_help(self, formatter: HelpFormatter | None = None) -> str: ... + + else: + def format_usage(self) -> str: ... + def format_help(self) -> str: ... + + @overload + def parse_known_args(self, args: Iterable[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ... + @overload + def parse_known_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + @overload + def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + + def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ... + def exit(self, status: int = 0, message: str | None = None) -> Never: ... + def error(self, message: str) -> Never: ... + + @overload + def parse_intermixed_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... + @overload + def parse_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... + @overload + def parse_intermixed_args(self, *, namespace: _N) -> _N: ... + + @overload + def parse_known_intermixed_args( + self, args: Iterable[str] | None = None, namespace: None = None + ) -> tuple[Namespace, list[str]]: ... + @overload + def parse_known_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + @overload + def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + + # undocumented + def _get_optional_actions(self) -> list[Action]: ... + def _get_positional_actions(self) -> list[Action]: ... + if sys.version_info >= (3, 12): + def _parse_known_args( + self, arg_strings: list[str], namespace: Namespace, intermixed: bool + ) -> tuple[Namespace, list[str]]: ... + else: + def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ... + + def _read_args_from_files(self, arg_strings: list[str]) -> list[str]: ... + def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]: ... + if sys.version_info >= (3, 12): + def _parse_optional(self, arg_string: str) -> list[tuple[Action | None, str, str | None, str | None]] | None: ... + else: + def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ... + + def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]: ... + def _get_nargs_pattern(self, action: Action) -> str: ... + def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ... + def _get_value(self, action: Action, arg_string: str) -> Any: ... + def _check_value(self, action: Action, value: Any) -> None: ... + if sys.version_info >= (3, 15): + def _get_formatter(self, file: SupportsWrite[str] | None = None) -> HelpFormatter: ... + else: + def _get_formatter(self) -> HelpFormatter: ... + + def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ... + +class HelpFormatter: + # undocumented + _prog: str + _indent_increment: int + _max_help_position: int + _width: int + _current_indent: int + _level: int + _action_max_length: int + _root_section: _Section # pyrefly: ignore [unknown-name] + _current_section: _Section # pyrefly: ignore [unknown-name] + _whitespace_matcher: Pattern[str] + _long_break_matcher: Pattern[str] + + class _Section: + formatter: HelpFormatter + heading: str | None + parent: Self | None + items: list[tuple[Callable[..., str], Iterable[Any]]] + def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ... + def format_help(self) -> str: ... + + if sys.version_info >= (3, 15): + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None + ) -> None: ... + + elif sys.version_info >= (3, 14): + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True + ) -> None: ... + else: + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None + ) -> None: ... + + def _indent(self) -> None: ... + def _dedent(self) -> None: ... + def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ... + def start_section(self, heading: str | None) -> None: ... + def end_section(self) -> None: ... + def add_text(self, text: str | None) -> None: ... + def add_usage( + self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None + ) -> None: ... + def add_argument(self, action: Action) -> None: ... + def add_arguments(self, actions: Iterable[Action]) -> None: ... + def format_help(self) -> str: ... + def _join_parts(self, part_strings: Iterable[str]) -> str: ... + def _format_usage( + self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None + ) -> str: ... + if sys.version_info < (3, 14): + # Removed in Python 3.14.3 + def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ... + + def _format_text(self, text: str) -> str: ... + def _format_action(self, action: Action) -> str: ... + def _format_action_invocation(self, action: Action) -> str: ... + def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ... + def _format_args(self, action: Action, default_metavar: str) -> str: ... + def _expand_help(self, action: Action) -> str: ... + def _iter_indented_subactions(self, action: Action) -> Generator[Action]: ... + def _split_lines(self, text: str, width: int) -> list[str]: ... + def _fill_text(self, text: str, width: int, indent: str) -> str: ... + def _get_help_string(self, action: Action) -> str | None: ... + def _get_default_metavar_for_optional(self, action: Action) -> str: ... + def _get_default_metavar_for_positional(self, action: Action) -> str: ... + +class RawDescriptionHelpFormatter(HelpFormatter): ... +class RawTextHelpFormatter(RawDescriptionHelpFormatter): ... +class ArgumentDefaultsHelpFormatter(HelpFormatter): ... +class MetavarTypeHelpFormatter(HelpFormatter): ... + +class Action(_AttributeHolder): + option_strings: Sequence[str] + dest: str + nargs: int | str | None + const: Any + default: Any + type: _ActionType | None + choices: Iterable[Any] | None + required: bool + help: str | None + metavar: str | tuple[str, ...] | None + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + nargs: int | str | None = None, + const: _T | None = None, + default: _T | str | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + nargs: int | str | None = None, + const: _T | None = None, + default: _T | str | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + + def __call__( + self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None + ) -> None: ... + def format_usage(self) -> str: ... + +if sys.version_info >= (3, 12): + class BooleanOptionalAction(Action): + if sys.version_info >= (3, 14): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 13): + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = sentinel, + choices: Iterable[_T] | None = sentinel, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = sentinel, + deprecated: bool = False, + ) -> None: ... + else: + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = sentinel, + choices: Iterable[_T] | None = sentinel, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = sentinel, + ) -> None: ... + +else: + class BooleanOptionalAction(Action): + @overload + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool | None = None, + *, + required: bool = False, + help: str | None = None, + ) -> None: ... + @overload + @deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.") + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: _T | bool | None = None, + type: Callable[[str], _T] | FileType | None = None, + choices: Iterable[_T] | None = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + +class Namespace(_AttributeHolder): + def __init__(self, **kwargs: Any) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __contains__(self, key: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@deprecated("Deprecated; may leave files open. Open files after parsing arguments instead.") +class FileType: + # undocumented + _mode: str + _bufsize: int + _encoding: str | None + _errors: str | None + def __init__(self, mode: str = "r", bufsize: int = -1, encoding: str | None = None, errors: str | None = None) -> None: ... + def __call__(self, string: str) -> IO[Any]: ... + +# undocumented +class _ArgumentGroup(_ActionsContainer): + title: str | None + _group_actions: list[Action] + + @overload + def __init__( + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> None: ... + @overload + @deprecated("Undocumented `prefix_chars` parameter is deprecated.") + def __init__( + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> None: ... + +# undocumented +class _MutuallyExclusiveGroup(_ArgumentGroup): + required: bool + _container: _ActionsContainer + def __init__(self, container: _ActionsContainer, required: bool = False) -> None: ... + +# undocumented +class _StoreAction(Action): ... + +# undocumented +class _StoreConstAction(Action): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + +# undocumented +class _StoreTrueAction(_StoreConstAction): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool = False, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: bool = False, required: bool = False, help: str | None = None + ) -> None: ... + +# undocumented +class _StoreFalseAction(_StoreConstAction): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: bool = True, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: bool = True, required: bool = False, help: str | None = None + ) -> None: ... + +# undocumented +class _AppendAction(Action): ... + +# undocumented +class _ExtendAction(_AppendAction): ... + +# undocumented +class _AppendConstAction(Action): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = None, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = None, + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + +# undocumented +class _CountAction(Action): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + default: Any = None, + required: bool = False, + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, option_strings: Sequence[str], dest: str, default: Any = None, required: bool = False, help: str | None = None + ) -> None: ... + +# undocumented +class _HelpAction(Action): + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + ) -> None: ... + +# undocumented +class _VersionAction(Action): + version: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + deprecated: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str | None = None, + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + version: str | None = None, + dest: str = "==SUPPRESS==", + default: str = "==SUPPRESS==", + help: str = "show program's version number and exit", + ) -> None: ... + +# undocumented +class _SubParsersAction(Action, Generic[_ArgumentParserT]): + _ChoicesPseudoAction: type[Any] # nested class + _prog_prefix: str + _parser_class: type[_ArgumentParserT] + _name_parser_map: dict[str, _ArgumentParserT] + choices: dict[str, _ArgumentParserT] + _choices_actions: list[Action] + def __init__( + self, + option_strings: Sequence[str], + prog: str, + parser_class: type[_ArgumentParserT], + dest: str = "==SUPPRESS==", + required: bool = False, + help: str | None = None, + metavar: str | tuple[str, ...] | None = None, + ) -> None: ... + + # Note: `add_parser` accepts all kwargs of `ArgumentParser.__init__`. It also + # accepts its own `help` and `aliases` kwargs. + if sys.version_info >= (3, 14): + def add_parser( + self, + name: str, + *, + deprecated: bool = False, + help: str | None = ..., + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + suggest_on_error: bool = False, + color: bool = False, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... + elif sys.version_info >= (3, 13): + def add_parser( + self, + name: str, + *, + deprecated: bool = False, + help: str | None = ..., + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... + else: + def add_parser( + self, + name: str, + *, + help: str | None = ..., + aliases: Iterable[str] = ..., + # Kwargs from ArgumentParser constructor + prog: str | None = ..., + usage: str | None = ..., + description: str | None = ..., + epilog: str | None = ..., + parents: Iterable[_ArgumentParserT] = ..., + formatter_class: _FormatterClass = ..., + prefix_chars: str = ..., + fromfile_prefix_chars: str | None = ..., + argument_default: Any = ..., + conflict_handler: str = ..., + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + **kwargs: Any, # Accepting any additional kwargs for custom parser classes + ) -> _ArgumentParserT: ... + + def _get_subactions(self) -> list[Action]: ... + +# undocumented +class ArgumentTypeError(Exception): ... + +# undocumented +def _get_action_name(argument: Action | None) -> str | None: ... diff --git a/stdlib/array.pyi b/stdlib/array.pyi new file mode 100644 index 000000000000..2c83146edbf0 --- /dev/null +++ b/stdlib/array.pyi @@ -0,0 +1,113 @@ +import sys +from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Iterable, MutableSequence +from types import GenericAlias +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated, disjoint_base + +_IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] +if sys.version_info >= (3, 15): + _FloatTypeCode: TypeAlias = Literal["f", "d", "e", "Zf", "Zd"] +else: + _FloatTypeCode: TypeAlias = Literal["f", "d"] +if sys.version_info >= (3, 13): + _UnicodeTypeCode: TypeAlias = Literal["u", "w"] +else: + _UnicodeTypeCode: TypeAlias = Literal["u"] +_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode + +_T = TypeVar("_T", int, float, str) + +if sys.version_info >= (3, 15): + typecodes: tuple[str, ...] +else: + typecodes: str + +@disjoint_base +class array(MutableSequence[_T]): + @property + def typecode(self) -> _TypeCode: ... + @property + def itemsize(self) -> int: ... + + @overload + def __new__( + cls: type[array[int]], typecode: _IntTypeCode, initializer: bytes | bytearray | Iterable[int] = ..., / + ) -> array[int]: ... + @overload + def __new__( + cls: type[array[float]], typecode: _FloatTypeCode, initializer: bytes | bytearray | Iterable[float] = ..., / + ) -> array[float]: ... + if sys.version_info >= (3, 13): + @overload + def __new__( + cls: type[array[str]], typecode: Literal["w"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + @overload + @deprecated("Deprecated since Python 3.3; will be removed in Python 3.16. Use 'w' typecode instead.") + def __new__( + cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + else: + @overload + @deprecated("Deprecated since Python 3.3; will be removed in Python 3.16.") + def __new__( + cls: type[array[str]], typecode: Literal["u"], initializer: bytes | bytearray | Iterable[str] = ..., / + ) -> array[str]: ... + + @overload + def __new__(cls, typecode: str, initializer: Iterable[_T], /) -> Self: ... + @overload + def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ... + + def append(self, v: _T, /) -> None: ... + def buffer_info(self) -> tuple[int, int]: ... + def byteswap(self) -> None: ... + def count(self, v: _T, /) -> int: ... + def extend(self, bb: Iterable[_T], /) -> None: ... + def frombytes(self, buffer: ReadableBuffer, /) -> None: ... + def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: ... + def fromlist(self, list: list[_T], /) -> None: ... + def fromunicode(self, ustr: str, /) -> None: ... + def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ... + def insert(self, i: int, v: _T, /) -> None: ... + def pop(self, i: int = -1, /) -> _T: ... + def remove(self, v: _T, /) -> None: ... + def tobytes(self) -> bytes: ... + def tofile(self, f: SupportsWrite[bytes], /) -> None: ... + def tolist(self) -> list[_T]: ... + def tounicode(self) -> str: ... + + __hash__: ClassVar[None] # type: ignore[assignment] + def __contains__(self, value: object, /) -> bool: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> _T: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> array[_T]: ... + + @overload # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: array[_T], /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + def __add__(self, value: array[_T], /) -> array[_T]: ... + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: array[_T], /) -> bool: ... + def __gt__(self, value: array[_T], /) -> bool: ... + def __iadd__(self, value: array[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: int, /) -> Self: ... + def __le__(self, value: array[_T], /) -> bool: ... + def __lt__(self, value: array[_T], /) -> bool: ... + def __mul__(self, value: int, /) -> array[_T]: ... + def __rmul__(self, value: int, /) -> array[_T]: ... + def __copy__(self) -> array[_T]: ... + def __deepcopy__(self, unused: Any, /) -> array[_T]: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +ArrayType = array diff --git a/stdlib/ast.pyi b/stdlib/ast.pyi new file mode 100644 index 000000000000..a1993773ee25 --- /dev/null +++ b/stdlib/ast.pyi @@ -0,0 +1,2199 @@ +import ast +import builtins +import os +import sys +import typing_extensions +from _ast import ( + PyCF_ALLOW_TOP_LEVEL_AWAIT as PyCF_ALLOW_TOP_LEVEL_AWAIT, + PyCF_ONLY_AST as PyCF_ONLY_AST, + PyCF_TYPE_COMMENTS as PyCF_TYPE_COMMENTS, +) +from _typeshed import ReadableBuffer, Unused +from collections.abc import Iterable, Iterator, Sequence +from types import EllipsisType +from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only +from typing_extensions import Self, Unpack, deprecated, disjoint_base + +if sys.version_info >= (3, 13): + from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST + +# Used for node end positions in constructor keyword arguments +_EndPositionT = typing_extensions.TypeVar("_EndPositionT", int, int | None, default=int | None) + +# Corresponds to the names in the `_attributes` class variable which is non-empty in certain AST nodes +@type_check_only +class _Attributes(TypedDict, Generic[_EndPositionT], total=False): + lineno: int + col_offset: int + end_lineno: _EndPositionT + end_col_offset: _EndPositionT + +# The various AST classes are implemented in C, and imported from _ast at runtime, +# but they consider themselves to live in the ast module, +# so we'll define the stubs in this file. +if sys.version_info >= (3, 12): + @disjoint_base + class AST: + __match_args__ = () + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] + if sys.version_info >= (3, 13): + _field_types: ClassVar[dict[str, Any]] + + if sys.version_info >= (3, 14): + def __replace__(self) -> Self: ... + +else: + class AST: + __match_args__ = () + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] + +class mod(AST): ... + +class Module(mod): + __match_args__ = ("body", "type_ignores") + body: list[stmt] + type_ignores: list[TypeIgnore] + if sys.version_info >= (3, 13): + def __init__(self, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> None: ... + else: + def __init__(self, body: list[stmt], type_ignores: list[TypeIgnore]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> Self: ... + +class Interactive(mod): + __match_args__ = ("body",) + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__(self, body: list[stmt] = ...) -> None: ... + else: + def __init__(self, body: list[stmt]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: list[stmt] = ...) -> Self: ... + +class Expression(mod): + __match_args__ = ("body",) + body: expr + def __init__(self, body: expr) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, body: expr = ...) -> Self: ... + +class FunctionType(mod): + __match_args__ = ("argtypes", "returns") + argtypes: list[expr] + returns: expr + if sys.version_info >= (3, 13): + @overload + def __init__(self, argtypes: list[expr], returns: expr) -> None: ... + @overload + def __init__(self, argtypes: list[expr] = ..., *, returns: expr) -> None: ... + else: + def __init__(self, argtypes: list[expr], returns: expr) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, argtypes: list[expr] = ..., returns: expr = ...) -> Self: ... + +class stmt(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ... + +class FunctionDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") + else: + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") + name: str + args: arguments + body: list[stmt] + decorator_list: list[expr] + returns: expr | None + type_comment: str | None + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + args: arguments, + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = None, + type_comment: str | None = None, + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None, + type_comment: str | None, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + *, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + args: arguments = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = ..., + type_comment: str | None = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncFunctionDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") + else: + __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") + name: str + args: arguments + body: list[stmt] + decorator_list: list[expr] + returns: expr | None + type_comment: str | None + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + args: arguments, + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = None, + type_comment: str | None = None, + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None, + type_comment: str | None, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + *, + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + args: arguments, + body: list[stmt], + decorator_list: list[expr], + returns: expr | None = None, + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + args: arguments = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + returns: expr | None = ..., + type_comment: str | None = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class ClassDef(stmt): + if sys.version_info >= (3, 12): + __match_args__ = ("name", "bases", "keywords", "body", "decorator_list", "type_params") + else: + __match_args__ = ("name", "bases", "keywords", "body", "decorator_list") + name: str + bases: list[expr] + keywords: list[keyword] + body: list[stmt] + decorator_list: list[expr] + if sys.version_info >= (3, 12): + type_params: list[type_param] + if sys.version_info >= (3, 13): + def __init__( + self, + name: str, + bases: list[expr] = ..., + keywords: list[keyword] = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 12): + def __init__( + self, + name: str, + bases: list[expr], + keywords: list[keyword], + body: list[stmt], + decorator_list: list[expr], + type_params: list[type_param], + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + name: str, + bases: list[expr], + keywords: list[keyword], + body: list[stmt], + decorator_list: list[expr], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + bases: list[expr] = ..., + keywords: list[keyword] = ..., + body: list[stmt] = ..., + decorator_list: list[expr] = ..., + type_params: list[type_param] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Return(stmt): + __match_args__ = ("value",) + value: expr | None + def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Delete(stmt): + __match_args__ = ("targets",) + targets: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, targets: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Assign(stmt): + __match_args__ = ("targets", "value", "type_comment") + targets: list[expr] + value: expr + type_comment: str | None + if sys.version_info >= (3, 13): + @overload + def __init__( + self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + @overload + def __init__( + self, targets: list[expr] = ..., *, value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__( + self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, targets: list[expr] = ..., value: expr = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +if sys.version_info >= (3, 12): + class TypeAlias(stmt): + __match_args__ = ("name", "type_params", "value") + name: Name + type_params: list[type_param] + value: expr + if sys.version_info >= (3, 13): + @overload + def __init__( + self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + @overload + def __init__( + self, name: Name, type_params: list[type_param] = ..., *, value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + else: + def __init__( + self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( # type: ignore[override] + self, + *, + name: Name = ..., + type_params: list[type_param] = ..., + value: expr = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class AugAssign(stmt): + __match_args__ = ("target", "op", "value") + target: Name | Attribute | Subscript + op: operator + value: expr + def __init__( + self, target: Name | Attribute | Subscript, op: operator, value: expr, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: Name | Attribute | Subscript = ..., + op: operator = ..., + value: expr = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AnnAssign(stmt): + __match_args__ = ("target", "annotation", "value", "simple") + target: Name | Attribute | Subscript + annotation: expr + value: expr | None + simple: int + + @overload + def __init__( + self, + target: Name | Attribute | Subscript, + annotation: expr, + value: expr | None, + simple: int, + **kwargs: Unpack[_Attributes], + ) -> None: ... + @overload + def __init__( + self, + target: Name | Attribute | Subscript, + annotation: expr, + value: expr | None = None, + *, + simple: int, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: Name | Attribute | Subscript = ..., + annotation: expr = ..., + value: expr | None = ..., + simple: int = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class For(stmt): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + target: expr + iter: expr + body: list[stmt] + orelse: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt], + orelse: list[stmt], + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: expr = ..., + iter: expr = ..., + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncFor(stmt): + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + target: expr + iter: expr + body: list[stmt] + orelse: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + target: expr, + iter: expr, + body: list[stmt], + orelse: list[stmt], + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + target: expr = ..., + iter: expr = ..., + body: list[stmt] = ..., + orelse: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class While(stmt): + __match_args__ = ("test", "body", "orelse") + test: expr + body: list[stmt] + orelse: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class If(stmt): + __match_args__ = ("test", "body", "orelse") + test: expr + body: list[stmt] + orelse: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class With(stmt): + __match_args__ = ("items", "body", "type_comment") + items: list[withitem] + body: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class AsyncWith(stmt): + __match_args__ = ("items", "body", "type_comment") + items: list[withitem] + body: list[stmt] + type_comment: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + items: list[withitem] = ..., + body: list[stmt] = ..., + type_comment: str | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Raise(stmt): + __match_args__ = ("exc", "cause") + exc: expr | None + cause: expr | None + def __init__(self, exc: expr | None = None, cause: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, exc: expr | None = ..., cause: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Try(stmt): + __match_args__ = ("body", "handlers", "orelse", "finalbody") + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] + finalbody: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + body: list[stmt], + handlers: list[ExceptHandler], + orelse: list[stmt], + finalbody: list[stmt], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +if sys.version_info >= (3, 11): + class TryStar(stmt): + __match_args__ = ("body", "handlers", "orelse", "finalbody") + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] + finalbody: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + else: + def __init__( + self, + body: list[stmt], + handlers: list[ExceptHandler], + orelse: list[stmt], + finalbody: list[stmt], + **kwargs: Unpack[_Attributes], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + body: list[stmt] = ..., + handlers: list[ExceptHandler] = ..., + orelse: list[stmt] = ..., + finalbody: list[stmt] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +class Assert(stmt): + __match_args__ = ("test", "msg") + test: expr + msg: expr | None + def __init__(self, test: expr, msg: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, test: expr = ..., msg: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Import(stmt): + if sys.version_info >= (3, 15): + __match_args__ = ("names", "is_lazy") + else: + __match_args__ = ("names",) + names: list[alias] + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + def __init__(self, names: list[alias] = ..., is_lazy: bool | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + elif sys.version_info >= (3, 13): + def __init__(self, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[alias], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__(self, *, names: list[alias] = ..., is_lazy: bool | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + + elif sys.version_info >= (3, 14): + def __replace__(self, *, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class ImportFrom(stmt): + if sys.version_info >= (3, 15): + __match_args__ = ("module", "names", "level", "is_lazy") + else: + __match_args__ = ("module", "names", "level") + module: str | None + names: list[alias] + level: int + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + @overload + def __init__( + self, module: str | None, names: list[alias], level: int, is_lazy: bool | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + @overload + def __init__( + self, + module: str | None = None, + names: list[alias] = ..., + *, + level: int, + is_lazy: bool | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 13): + @overload + def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, module: str | None = None, names: list[alias] = ..., *, level: int, **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + @overload + def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, module: str | None = None, *, names: list[alias], level: int, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__( + self, + *, + module: str | None = ..., + names: list[alias] = ..., + level: int = ..., + is_lazy: bool | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + + elif sys.version_info >= (3, 14): + def __replace__( + self, *, module: str | None = ..., names: list[alias] = ..., level: int = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Global(stmt): + __match_args__ = ("names",) + names: list[str] + if sys.version_info >= (3, 13): + def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Nonlocal(stmt): + __match_args__ = ("names",) + names: list[str] + if sys.version_info >= (3, 13): + def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Expr(stmt): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Pass(stmt): ... +class Break(stmt): ... +class Continue(stmt): ... + +class expr(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ... + +class BoolOp(expr): + __match_args__ = ("op", "values") + op: boolop + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, op: boolop, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, op: boolop, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, op: boolop = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class NamedExpr(expr): + __match_args__ = ("target", "value") + target: Name + value: expr + def __init__(self, target: Name, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, target: Name = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class BinOp(expr): + __match_args__ = ("left", "op", "right") + left: expr + op: operator + right: expr + def __init__(self, left: expr, op: operator, right: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, left: expr = ..., op: operator = ..., right: expr = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class UnaryOp(expr): + __match_args__ = ("op", "operand") + op: unaryop + operand: expr + def __init__(self, op: unaryop, operand: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, op: unaryop = ..., operand: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Lambda(expr): + __match_args__ = ("args", "body") + args: arguments + body: expr + def __init__(self, args: arguments, body: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, args: arguments = ..., body: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class IfExp(expr): + __match_args__ = ("test", "body", "orelse") + test: expr + body: expr + orelse: expr + def __init__(self, test: expr, body: expr, orelse: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, test: expr = ..., body: expr = ..., orelse: expr = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Dict(expr): + __match_args__ = ("keys", "values") + keys: list[expr | None] + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, keys: list[expr | None], values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Set(expr): + __match_args__ = ("elts",) + elts: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class ListComp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class SetComp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class DictComp(expr): + __match_args__ = ("key", "value", "generators") + key: expr + if sys.version_info >= (3, 15): + value: expr | None + else: + value: expr + generators: list[comprehension] + if sys.version_info >= (3, 15): + def __init__( + self, key: expr, value: expr | None = None, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + elif sys.version_info >= (3, 13): + def __init__( + self, key: expr, value: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, key: expr, value: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 15): + def __replace__( + self, + *, + key: expr = ..., + value: expr | None = ..., + generators: list[comprehension] = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + elif sys.version_info >= (3, 14): + def __replace__( + self, *, key: expr = ..., value: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class GeneratorExp(expr): + __match_args__ = ("elt", "generators") + elt: expr + generators: list[comprehension] + if sys.version_info >= (3, 13): + def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Await(expr): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Yield(expr): + __match_args__ = ("value",) + value: expr | None + def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class YieldFrom(expr): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Compare(expr): + __match_args__ = ("left", "ops", "comparators") + left: expr + ops: list[cmpop] + comparators: list[expr] + if sys.version_info >= (3, 13): + def __init__( + self, left: expr, ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, left: expr, ops: list[cmpop], comparators: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, left: expr = ..., ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Call(expr): + __match_args__ = ("func", "args", "keywords") + func: expr + args: list[expr] + keywords: list[keyword] + if sys.version_info >= (3, 13): + def __init__( + self, func: expr, args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + def __init__(self, func: expr, args: list[expr], keywords: list[keyword], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, func: expr = ..., args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class FormattedValue(expr): + __match_args__ = ("value", "conversion", "format_spec") + value: expr + conversion: int + format_spec: expr | None + def __init__(self, value: expr, conversion: int, format_spec: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., conversion: int = ..., format_spec: expr | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class JoinedStr(expr): + __match_args__ = ("values",) + values: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +if sys.version_info >= (3, 14): + class TemplateStr(expr): + __match_args__ = ("values",) + values: list[expr] + def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + + class Interpolation(expr): + __match_args__ = ("value", "str", "conversion", "format_spec") + value: expr + str: builtins.str + conversion: int + format_spec: expr | None = None + def __init__( + self, + value: expr = ..., + str: builtins.str = ..., + conversion: int = ..., + format_spec: expr | None = ..., + **kwargs: Unpack[_Attributes], + ) -> None: ... + def __replace__( + self, + *, + value: expr = ..., + str: builtins.str = ..., + conversion: int = ..., + format_spec: expr | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + +_ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | EllipsisType + +class Constant(expr): + __match_args__ = ("value", "kind") + value: _ConstantValue + kind: str | None + if sys.version_info < (3, 14): + # Aliases for value, for backwards compatibility + @property + @deprecated("Removed in Python 3.14. Use `value` instead.") + def n(self) -> _ConstantValue: ... + @n.setter + @deprecated("Removed in Python 3.14. Use `value` instead.") + def n(self, value: _ConstantValue) -> None: ... + + @property + @deprecated("Removed in Python 3.14. Use `value` instead.") + def s(self) -> _ConstantValue: ... + @s.setter + @deprecated("Removed in Python 3.14. Use `value` instead.") + def s(self, value: _ConstantValue) -> None: ... + + def __init__(self, value: _ConstantValue, kind: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: _ConstantValue = ..., kind: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Attribute(expr): + __match_args__ = ("value", "attr", "ctx") + value: expr + attr: str + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, attr: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., attr: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Subscript(expr): + __match_args__ = ("value", "slice", "ctx") + value: expr + slice: expr + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, slice: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, value: expr = ..., slice: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class Starred(expr): + __match_args__ = ("value", "ctx") + value: expr + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, value: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Name(expr): + __match_args__ = ("id", "ctx") + id: str + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + def __init__(self, id: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, id: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class List(expr): + __match_args__ = ("elts", "ctx") + elts: list[expr] + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class Tuple(expr): + __match_args__ = ("elts", "ctx") + elts: list[expr] + ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` + dims: list[expr] + if sys.version_info >= (3, 13): + def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +@deprecated("Deprecated since Python 3.9.") +class slice(AST): ... + +class Slice(expr): + __match_args__ = ("lower", "upper", "step") + lower: expr | None + upper: expr | None + step: expr | None + def __init__( + self, lower: expr | None = None, upper: expr | None = None, step: expr | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lower: expr | None = ..., upper: expr | None = ..., step: expr | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +@deprecated("Deprecated since Python 3.9. Use `ast.Tuple` instead.") +class ExtSlice(slice): + def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_Attributes]) -> Tuple: ... # type: ignore[misc] + +@deprecated("Deprecated since Python 3.9. Use the index value directly instead.") +class Index(slice): + def __new__(cls, value: expr, **kwargs: Unpack[_Attributes]) -> expr: ... # type: ignore[misc] + +class expr_context(AST): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class AugLoad(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class AugStore(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class Param(expr_context): ... + +@deprecated("Deprecated since Python 3.9. Unused in Python 3.") +class Suite(mod): ... + +class Load(expr_context): ... +class Store(expr_context): ... +class Del(expr_context): ... +class boolop(AST): ... +class And(boolop): ... +class Or(boolop): ... +class operator(AST): ... +class Add(operator): ... +class Sub(operator): ... +class Mult(operator): ... +class MatMult(operator): ... +class Div(operator): ... +class Mod(operator): ... +class Pow(operator): ... +class LShift(operator): ... +class RShift(operator): ... +class BitOr(operator): ... +class BitXor(operator): ... +class BitAnd(operator): ... +class FloorDiv(operator): ... +class unaryop(AST): ... +class Invert(unaryop): ... +class Not(unaryop): ... +class UAdd(unaryop): ... +class USub(unaryop): ... +class cmpop(AST): ... +class Eq(cmpop): ... +class NotEq(cmpop): ... +class Lt(cmpop): ... +class LtE(cmpop): ... +class Gt(cmpop): ... +class GtE(cmpop): ... +class Is(cmpop): ... +class IsNot(cmpop): ... +class In(cmpop): ... +class NotIn(cmpop): ... + +class comprehension(AST): + __match_args__ = ("target", "iter", "ifs", "is_async") + target: expr + iter: expr + ifs: list[expr] + is_async: int + if sys.version_info >= (3, 13): + @overload + def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ... + @overload + def __init__(self, target: expr, iter: expr, ifs: list[expr] = ..., *, is_async: int) -> None: ... + else: + def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, target: expr = ..., iter: expr = ..., ifs: list[expr] = ..., is_async: int = ...) -> Self: ... + +class excepthandler(AST): + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int | None = ..., end_col_offset: int | None = ... + ) -> Self: ... + +class ExceptHandler(excepthandler): + __match_args__ = ("type", "name", "body") + type: expr | None + name: str | None + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__( + self, type: expr | None = None, name: str | None = None, body: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> None: ... + else: + @overload + def __init__(self, type: expr | None, name: str | None, body: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__( + self, type: expr | None = None, name: str | None = None, *, body: list[stmt], **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, type: expr | None = ..., name: str | None = ..., body: list[stmt] = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class arguments(AST): + __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") + posonlyargs: list[arg] + args: list[arg] + vararg: arg | None + kwonlyargs: list[arg] + kw_defaults: list[expr | None] + kwarg: arg | None + defaults: list[expr] + if sys.version_info >= (3, 13): + def __init__( + self, + posonlyargs: list[arg] = ..., + args: list[arg] = ..., + vararg: arg | None = None, + kwonlyargs: list[arg] = ..., + kw_defaults: list[expr | None] = ..., + kwarg: arg | None = None, + defaults: list[expr] = ..., + ) -> None: ... + else: + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None, + defaults: list[expr], + ) -> None: ... + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None = None, + *, + defaults: list[expr], + ) -> None: ... + @overload + def __init__( + self, + posonlyargs: list[arg], + args: list[arg], + vararg: arg | None = None, + *, + kwonlyargs: list[arg], + kw_defaults: list[expr | None], + kwarg: arg | None = None, + defaults: list[expr], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + posonlyargs: list[arg] = ..., + args: list[arg] = ..., + vararg: arg | None = ..., + kwonlyargs: list[arg] = ..., + kw_defaults: list[expr | None] = ..., + kwarg: arg | None = ..., + defaults: list[expr] = ..., + ) -> Self: ... + +class arg(AST): + __match_args__ = ("arg", "annotation", "type_comment") + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + arg: str + annotation: expr | None + type_comment: str | None + def __init__( + self, arg: str, annotation: expr | None = None, type_comment: str | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, arg: str = ..., annotation: expr | None = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes] + ) -> Self: ... + +class keyword(AST): + __match_args__ = ("arg", "value") + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + arg: str | None + value: expr + + @overload + def __init__(self, arg: str | None, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + @overload + def __init__(self, arg: str | None = None, *, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, arg: str | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class alias(AST): + __match_args__ = ("name", "asname") + name: str + asname: str | None + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, name: str, asname: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, name: str = ..., asname: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class withitem(AST): + __match_args__ = ("context_expr", "optional_vars") + context_expr: expr + optional_vars: expr | None + def __init__(self, context_expr: expr, optional_vars: expr | None = None) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: ... + +class pattern(AST): + lineno: int + col_offset: int + end_lineno: int + end_col_offset: int + def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ... + ) -> Self: ... + +class match_case(AST): + __match_args__ = ("pattern", "guard", "body") + pattern: ast.pattern + guard: expr | None + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ... + else: + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ... + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ... + +class Match(stmt): + __match_args__ = ("subject", "cases") + subject: expr + cases: list[match_case] + if sys.version_info >= (3, 13): + def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + +class MatchValue(pattern): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchSingleton(pattern): + __match_args__ = ("value",) + value: bool | None + def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchSequence(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchMapping(pattern): + __match_args__ = ("keys", "patterns", "rest") + keys: list[expr] + patterns: list[pattern] + rest: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = None, + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, keys: list[expr], patterns: list[pattern], rest: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class MatchClass(pattern): + __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") + cls: expr + patterns: list[pattern] + kwd_attrs: list[str] + kwd_patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__( + self, + cls: expr, + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, + cls: expr, + patterns: list[pattern], + kwd_attrs: list[str], + kwd_patterns: list[pattern], + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + cls: expr = ..., + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + +class MatchStar(pattern): + __match_args__ = ("name",) + name: str | None + def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class MatchAs(pattern): + __match_args__ = ("pattern", "name") + pattern: ast.pattern | None + name: str | None + def __init__( + self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + +class MatchOr(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + +class type_ignore(AST): ... + +class TypeIgnore(type_ignore): + __match_args__ = ("lineno", "tag") + lineno: int + tag: str + def __init__(self, lineno: int, tag: str) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, *, lineno: int = ..., tag: str = ...) -> Self: ... + +if sys.version_info >= (3, 12): + class type_param(AST): + lineno: int + col_offset: int + end_lineno: int + end_col_offset: int + def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__(self, **kwargs: Unpack[_Attributes[int]]) -> Self: ... + + class TypeVar(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "bound", "default_value") + else: + __match_args__ = ("name", "bound") + name: str + bound: expr | None + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__( + self, name: str, bound: expr | None = None, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... + else: + def __init__(self, name: str, bound: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + name: str = ..., + bound: expr | None = ..., + default_value: expr | None = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... + + class ParamSpec(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "default_value") + else: + __match_args__ = ("name",) + name: str + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + + class TypeVarTuple(type_param): + if sys.version_info >= (3, 13): + __match_args__ = ("name", "default_value") + else: + __match_args__ = ("name",) + name: str + if sys.version_info >= (3, 13): + default_value: expr | None + def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ... + + if sys.version_info >= (3, 14): + def __replace__( + self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... + +if sys.version_info >= (3, 14): + @type_check_only + class _ABC(type): + def __init__(cls, *args: Unused) -> None: ... + +else: + class _ABC(type): + def __init__(cls, *args: Unused) -> None: ... + +if sys.version_info < (3, 14): + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Num(Constant, metaclass=_ABC): + def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Str(Constant, metaclass=_ABC): + def __new__(cls, s: str, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Bytes(Constant, metaclass=_ABC): + def __new__(cls, s: bytes, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class NameConstant(Constant, metaclass=_ABC): + def __new__(cls, value: _ConstantValue, kind: str | None, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + + @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") + class Ellipsis(Constant, metaclass=_ABC): + def __new__(cls, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + +# everything below here is defined in ast.py + +_T = _TypeVar("_T", bound=AST) + +if sys.version_info >= (3, 15): + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> mod: ... +elif sys.version_info >= (3, 13): + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + ) -> mod: ... +else: + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + ) -> mod: ... + +def literal_eval(node_or_string: str | AST) -> Any: ... + +if sys.version_info >= (3, 15): + def dump( + node: AST, + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: int | str | None = None, + show_empty: bool = False, + color: bool = False, + ) -> str: ... + +elif sys.version_info >= (3, 13): + def dump( + node: AST, + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: int | str | None = None, + show_empty: bool = False, + ) -> str: ... + +else: + def dump( + node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None + ) -> str: ... + +def copy_location(new_node: _T, old_node: AST) -> _T: ... +def fix_missing_locations(node: _T) -> _T: ... +def increment_lineno(node: _T, n: int = 1) -> _T: ... +def iter_fields(node: AST) -> Iterator[tuple[str, Any]]: ... +def iter_child_nodes(node: AST) -> Iterator[AST]: ... +def get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clean: bool = True) -> str | None: ... +def get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: ... +def walk(node: AST) -> Iterator[AST]: ... + +if sys.version_info >= (3, 14): + def compare(left: AST, right: AST, /, *, compare_attributes: bool = False) -> bool: ... + +class NodeVisitor: + # All visit methods below can be overwritten by subclasses and return an + # arbitrary value, which is passed to the caller. + def visit(self, node: AST) -> Any: ... + def generic_visit(self, node: AST) -> Any: ... + # The following visit methods are not defined on NodeVisitor, but can + # be implemented by subclasses and are called during a visit if defined. + def visit_Module(self, node: Module) -> Any: ... + def visit_Interactive(self, node: Interactive) -> Any: ... + def visit_Expression(self, node: Expression) -> Any: ... + def visit_FunctionDef(self, node: FunctionDef) -> Any: ... + def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any: ... + def visit_ClassDef(self, node: ClassDef) -> Any: ... + def visit_Return(self, node: Return) -> Any: ... + def visit_Delete(self, node: Delete) -> Any: ... + def visit_Assign(self, node: Assign) -> Any: ... + def visit_AugAssign(self, node: AugAssign) -> Any: ... + def visit_AnnAssign(self, node: AnnAssign) -> Any: ... + def visit_For(self, node: For) -> Any: ... + def visit_AsyncFor(self, node: AsyncFor) -> Any: ... + def visit_While(self, node: While) -> Any: ... + def visit_If(self, node: If) -> Any: ... + def visit_With(self, node: With) -> Any: ... + def visit_AsyncWith(self, node: AsyncWith) -> Any: ... + def visit_Raise(self, node: Raise) -> Any: ... + def visit_Try(self, node: Try) -> Any: ... + def visit_Assert(self, node: Assert) -> Any: ... + def visit_Import(self, node: Import) -> Any: ... + def visit_ImportFrom(self, node: ImportFrom) -> Any: ... + def visit_Global(self, node: Global) -> Any: ... + def visit_Nonlocal(self, node: Nonlocal) -> Any: ... + def visit_Expr(self, node: Expr) -> Any: ... + def visit_Pass(self, node: Pass) -> Any: ... + def visit_Break(self, node: Break) -> Any: ... + def visit_Continue(self, node: Continue) -> Any: ... + def visit_Slice(self, node: Slice) -> Any: ... + def visit_BoolOp(self, node: BoolOp) -> Any: ... + def visit_BinOp(self, node: BinOp) -> Any: ... + def visit_UnaryOp(self, node: UnaryOp) -> Any: ... + def visit_Lambda(self, node: Lambda) -> Any: ... + def visit_IfExp(self, node: IfExp) -> Any: ... + def visit_Dict(self, node: Dict) -> Any: ... + def visit_Set(self, node: Set) -> Any: ... + def visit_ListComp(self, node: ListComp) -> Any: ... + def visit_SetComp(self, node: SetComp) -> Any: ... + def visit_DictComp(self, node: DictComp) -> Any: ... + def visit_GeneratorExp(self, node: GeneratorExp) -> Any: ... + def visit_Await(self, node: Await) -> Any: ... + def visit_Yield(self, node: Yield) -> Any: ... + def visit_YieldFrom(self, node: YieldFrom) -> Any: ... + def visit_Compare(self, node: Compare) -> Any: ... + def visit_Call(self, node: Call) -> Any: ... + def visit_FormattedValue(self, node: FormattedValue) -> Any: ... + def visit_JoinedStr(self, node: JoinedStr) -> Any: ... + def visit_Constant(self, node: Constant) -> Any: ... + def visit_NamedExpr(self, node: NamedExpr) -> Any: ... + def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ... + def visit_Attribute(self, node: Attribute) -> Any: ... + def visit_Subscript(self, node: Subscript) -> Any: ... + def visit_Starred(self, node: Starred) -> Any: ... + def visit_Name(self, node: Name) -> Any: ... + def visit_List(self, node: List) -> Any: ... + def visit_Tuple(self, node: Tuple) -> Any: ... + def visit_Del(self, node: Del) -> Any: ... + def visit_Load(self, node: Load) -> Any: ... + def visit_Store(self, node: Store) -> Any: ... + def visit_And(self, node: And) -> Any: ... + def visit_Or(self, node: Or) -> Any: ... + def visit_Add(self, node: Add) -> Any: ... + def visit_BitAnd(self, node: BitAnd) -> Any: ... + def visit_BitOr(self, node: BitOr) -> Any: ... + def visit_BitXor(self, node: BitXor) -> Any: ... + def visit_Div(self, node: Div) -> Any: ... + def visit_FloorDiv(self, node: FloorDiv) -> Any: ... + def visit_LShift(self, node: LShift) -> Any: ... + def visit_Mod(self, node: Mod) -> Any: ... + def visit_Mult(self, node: Mult) -> Any: ... + def visit_MatMult(self, node: MatMult) -> Any: ... + def visit_Pow(self, node: Pow) -> Any: ... + def visit_RShift(self, node: RShift) -> Any: ... + def visit_Sub(self, node: Sub) -> Any: ... + def visit_Invert(self, node: Invert) -> Any: ... + def visit_Not(self, node: Not) -> Any: ... + def visit_UAdd(self, node: UAdd) -> Any: ... + def visit_USub(self, node: USub) -> Any: ... + def visit_Eq(self, node: Eq) -> Any: ... + def visit_Gt(self, node: Gt) -> Any: ... + def visit_GtE(self, node: GtE) -> Any: ... + def visit_In(self, node: In) -> Any: ... + def visit_Is(self, node: Is) -> Any: ... + def visit_IsNot(self, node: IsNot) -> Any: ... + def visit_Lt(self, node: Lt) -> Any: ... + def visit_LtE(self, node: LtE) -> Any: ... + def visit_NotEq(self, node: NotEq) -> Any: ... + def visit_NotIn(self, node: NotIn) -> Any: ... + def visit_comprehension(self, node: comprehension) -> Any: ... + def visit_ExceptHandler(self, node: ExceptHandler) -> Any: ... + def visit_arguments(self, node: arguments) -> Any: ... + def visit_arg(self, node: arg) -> Any: ... + def visit_keyword(self, node: keyword) -> Any: ... + def visit_alias(self, node: alias) -> Any: ... + def visit_withitem(self, node: withitem) -> Any: ... + def visit_Match(self, node: Match) -> Any: ... + def visit_match_case(self, node: match_case) -> Any: ... + def visit_MatchValue(self, node: MatchValue) -> Any: ... + def visit_MatchSequence(self, node: MatchSequence) -> Any: ... + def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ... + def visit_MatchStar(self, node: MatchStar) -> Any: ... + def visit_MatchMapping(self, node: MatchMapping) -> Any: ... + def visit_MatchClass(self, node: MatchClass) -> Any: ... + def visit_MatchAs(self, node: MatchAs) -> Any: ... + def visit_MatchOr(self, node: MatchOr) -> Any: ... + + if sys.version_info >= (3, 11): + def visit_TryStar(self, node: TryStar) -> Any: ... + + if sys.version_info >= (3, 12): + def visit_TypeVar(self, node: TypeVar) -> Any: ... + def visit_ParamSpec(self, node: ParamSpec) -> Any: ... + def visit_TypeVarTuple(self, node: TypeVarTuple) -> Any: ... + def visit_TypeAlias(self, node: TypeAlias) -> Any: ... + + if sys.version_info >= (3, 14): + def visit_TemplateStr(self, node: TemplateStr) -> Any: ... + def visit_Interpolation(self, node: Interpolation) -> Any: ... + + # visit methods for deprecated nodes + def visit_ExtSlice(self, node: ExtSlice) -> Any: ... + def visit_Index(self, node: Index) -> Any: ... + def visit_Suite(self, node: Suite) -> Any: ... + def visit_AugLoad(self, node: AugLoad) -> Any: ... + def visit_AugStore(self, node: AugStore) -> Any: ... + def visit_Param(self, node: Param) -> Any: ... + + if sys.version_info < (3, 14): + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Num(self, node: Num) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Str(self, node: Str) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Bytes(self, node: Bytes) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_NameConstant(self, node: NameConstant) -> Any: ... # type: ignore[deprecated] + @deprecated("Removed in Python 3.14. Use `visit_Constant` instead.") + def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated] + +class NodeTransformer(NodeVisitor): + def generic_visit(self, node: AST) -> AST: ... + # TODO: Override the visit_* methods with better return types. + # The usual return type is AST | None, but Iterable[AST] + # is also allowed in some cases -- this needs to be mapped. + +def unparse(ast_obj: AST) -> str: ... + +if sys.version_info >= (3, 14): + def main(args: Sequence[str] | None = None) -> None: ... + +else: + def main() -> None: ... diff --git a/stdlib/asynchat.pyi b/stdlib/asynchat.pyi new file mode 100644 index 000000000000..79a70d1c1ec8 --- /dev/null +++ b/stdlib/asynchat.pyi @@ -0,0 +1,21 @@ +import asyncore +from abc import abstractmethod + +class simple_producer: + def __init__(self, data: bytes, buffer_size: int = 512) -> None: ... + def more(self) -> bytes: ... + +class async_chat(asyncore.dispatcher): + ac_in_buffer_size: int + ac_out_buffer_size: int + @abstractmethod + def collect_incoming_data(self, data: bytes) -> None: ... + @abstractmethod + def found_terminator(self) -> None: ... + def set_terminator(self, term: bytes | int | None) -> None: ... + def get_terminator(self) -> bytes | int | None: ... + def push(self, data: bytes) -> None: ... + def push_with_producer(self, producer: simple_producer) -> None: ... + def close_when_done(self) -> None: ... + def initiate_send(self) -> None: ... + def discard_buffers(self) -> None: ... diff --git a/stdlib/asyncio/__init__.pyi b/stdlib/asyncio/__init__.pyi new file mode 100644 index 000000000000..5748c85af4c6 --- /dev/null +++ b/stdlib/asyncio/__init__.pyi @@ -0,0 +1,1022 @@ +# This condition is so big, it's clearer to keep to platform condition in two blocks +# Can't NOQA on a specific line: https://github.com/plinss/flake8-noqa/issues/22 +import sys +from collections.abc import Awaitable, Coroutine, Generator +from typing import Any, TypeAlias, TypeVar + +# As at runtime, this depends on all submodules defining __all__ accurately. +from .base_events import * +from .coroutines import * +from .events import * +from .exceptions import * +from .futures import * +from .locks import * +from .protocols import * +from .queues import * +from .runners import * +from .streams import * +from .subprocess import * +from .tasks import * +from .threads import * +from .transports import * + +if sys.version_info >= (3, 14): + from .graph import * + +if sys.version_info >= (3, 11): + from .taskgroups import * + from .timeouts import * + +if sys.platform == "win32": + from .windows_events import * +else: + from .unix_events import * + +if sys.version_info >= (3, 14): + from .events import _AbstractEventLoopPolicy + + AbstractEventLoopPolicy = _AbstractEventLoopPolicy + +if sys.platform == "win32": + if sys.version_info >= (3, 14): + from .windows_events import _DefaultEventLoopPolicy, _WindowsProactorEventLoopPolicy, _WindowsSelectorEventLoopPolicy + + DefaultEventLoopPolicy = _DefaultEventLoopPolicy + WindowsProactorEventLoopPolicy = _WindowsProactorEventLoopPolicy + WindowsSelectorEventLoopPolicy = _WindowsSelectorEventLoopPolicy +else: + if sys.version_info >= (3, 14): + from .unix_events import _DefaultEventLoopPolicy + + DefaultEventLoopPolicy = _DefaultEventLoopPolicy + +if sys.platform == "win32": + if sys.version_info >= (3, 14): + + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "future_discard_from_awaited_by", # from futures + "future_add_to_awaited_by", # from futures + "capture_call_graph", # from graph + "format_call_graph", # from graph + "print_call_graph", # from graph + "FrameCallGraphEntry", # from graph + "FutureCallGraph", # from graph + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "_DefaultEventLoopPolicy", # from windows_events + "_WindowsSelectorEventLoopPolicy", # from windows_events + "_WindowsProactorEventLoopPolicy", # from windows_events + "EventLoop", # from windows_events + ) + elif sys.version_info >= (3, 13): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + "EventLoop", # from windows_events + ) + elif sys.version_info >= (3, 12): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) + elif sys.version_info >= (3, 11): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) + else: + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "coroutine", # from coroutines + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from windows_events + "ProactorEventLoop", # from windows_events + "IocpProactor", # from windows_events + "DefaultEventLoopPolicy", # from windows_events + "WindowsSelectorEventLoopPolicy", # from windows_events + "WindowsProactorEventLoopPolicy", # from windows_events + ) +else: + if sys.version_info >= (3, 14): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "future_discard_from_awaited_by", # from futures + "future_add_to_awaited_by", # from futures + "capture_call_graph", # from graph + "format_call_graph", # from graph + "print_call_graph", # from graph + "FrameCallGraphEntry", # from graph + "FutureCallGraph", # from graph + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "EventLoop", # from unix_events + ) + elif sys.version_info >= (3, 13): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "QueueShutDown", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + "EventLoop", # from unix_events + ) + elif sys.version_info >= (3, 12): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "create_eager_task_factory", # from tasks + "eager_task_factory", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "TaskGroup", # from taskgroups + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) + elif sys.version_info >= (3, 11): + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "BrokenBarrierError", # from exceptions + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "Barrier", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "Runner", # from runners + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "Timeout", # from timeouts + "timeout", # from timeouts + "timeout_at", # from timeouts + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) + else: + __all__ = ( + "BaseEventLoop", # from base_events + "Server", # from base_events + "coroutine", # from coroutines + "iscoroutinefunction", # from coroutines + "iscoroutine", # from coroutines + "AbstractEventLoopPolicy", # from events + "AbstractEventLoop", # from events + "AbstractServer", # from events + "Handle", # from events + "TimerHandle", # from events + "get_event_loop_policy", # from events + "set_event_loop_policy", # from events + "get_event_loop", # from events + "set_event_loop", # from events + "new_event_loop", # from events + "get_child_watcher", # from events + "set_child_watcher", # from events + "_set_running_loop", # from events + "get_running_loop", # from events + "_get_running_loop", # from events + "CancelledError", # from exceptions + "InvalidStateError", # from exceptions + "TimeoutError", # from exceptions + "IncompleteReadError", # from exceptions + "LimitOverrunError", # from exceptions + "SendfileNotAvailableError", # from exceptions + "Future", # from futures + "wrap_future", # from futures + "isfuture", # from futures + "Lock", # from locks + "Event", # from locks + "Condition", # from locks + "Semaphore", # from locks + "BoundedSemaphore", # from locks + "BaseProtocol", # from protocols + "Protocol", # from protocols + "DatagramProtocol", # from protocols + "SubprocessProtocol", # from protocols + "BufferedProtocol", # from protocols + "run", # from runners + "Queue", # from queues + "PriorityQueue", # from queues + "LifoQueue", # from queues + "QueueFull", # from queues + "QueueEmpty", # from queues + "StreamReader", # from streams + "StreamWriter", # from streams + "StreamReaderProtocol", # from streams + "open_connection", # from streams + "start_server", # from streams + "open_unix_connection", # from streams + "start_unix_server", # from streams + "create_subprocess_exec", # from subprocess + "create_subprocess_shell", # from subprocess + "Task", # from tasks + "create_task", # from tasks + "FIRST_COMPLETED", # from tasks + "FIRST_EXCEPTION", # from tasks + "ALL_COMPLETED", # from tasks + "wait", # from tasks + "wait_for", # from tasks + "as_completed", # from tasks + "sleep", # from tasks + "gather", # from tasks + "shield", # from tasks + "ensure_future", # from tasks + "run_coroutine_threadsafe", # from tasks + "current_task", # from tasks + "all_tasks", # from tasks + "_register_task", # from tasks + "_unregister_task", # from tasks + "_enter_task", # from tasks + "_leave_task", # from tasks + "to_thread", # from threads + "BaseTransport", # from transports + "ReadTransport", # from transports + "WriteTransport", # from transports + "Transport", # from transports + "DatagramTransport", # from transports + "SubprocessTransport", # from transports + "SelectorEventLoop", # from unix_events + "AbstractChildWatcher", # from unix_events + "SafeChildWatcher", # from unix_events + "FastChildWatcher", # from unix_events + "PidfdChildWatcher", # from unix_events + "MultiLoopChildWatcher", # from unix_events + "ThreadedChildWatcher", # from unix_events + "DefaultEventLoopPolicy", # from unix_events + ) + +_T_co = TypeVar("_T_co", covariant=True) + +# Aliases imported by multiple submodules in typeshed +if sys.version_info >= (3, 12): + _AwaitableLike: TypeAlias = Awaitable[_T_co] # noqa: Y047 + _CoroutineLike: TypeAlias = Coroutine[Any, Any, _T_co] # noqa: Y047 +else: + _AwaitableLike: TypeAlias = Generator[Any, None, _T_co] | Awaitable[_T_co] + _CoroutineLike: TypeAlias = Generator[Any, None, _T_co] | Coroutine[Any, Any, _T_co] diff --git a/stdlib/asyncio/base_events.pyi b/stdlib/asyncio/base_events.pyi new file mode 100644 index 000000000000..056d9a2d36c9 --- /dev/null +++ b/stdlib/asyncio/base_events.pyi @@ -0,0 +1,499 @@ +import ssl +import sys +from _typeshed import FileDescriptorLike, ReadableBuffer, WriteableBuffer +from asyncio import _AwaitableLike, _CoroutineLike +from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle, _TaskFactory +from asyncio.futures import Future +from asyncio.protocols import BaseProtocol +from asyncio.tasks import Task +from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport +from collections.abc import Callable, Iterable, Sequence +from concurrent.futures import Executor, ThreadPoolExecutor +from contextvars import Context +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket +from typing import IO, Any, Literal, TypeAlias, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseEventLoop", "Server") + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | None | ssl.SSLContext + +class Server(AbstractServer): + if sys.version_info >= (3, 11): + def __init__( + self, + loop: AbstractEventLoop, + sockets: Iterable[socket], + protocol_factory: _ProtocolFactory, + ssl_context: _SSLContext, + backlog: int, + ssl_handshake_timeout: float | None, + ssl_shutdown_timeout: float | None = None, + ) -> None: ... + else: + def __init__( + self, + loop: AbstractEventLoop, + sockets: Iterable[socket], + protocol_factory: _ProtocolFactory, + ssl_context: _SSLContext, + backlog: int, + ssl_handshake_timeout: float | None, + ) -> None: ... + + if sys.version_info >= (3, 13): + def close_clients(self) -> None: ... + def abort_clients(self) -> None: ... + + def get_loop(self) -> AbstractEventLoop: ... + def is_serving(self) -> bool: ... + async def start_serving(self) -> None: ... + async def serve_forever(self) -> None: ... + @property + def sockets(self) -> tuple[socket, ...]: ... + def close(self) -> None: ... + async def wait_closed(self) -> None: ... + +class BaseEventLoop(AbstractEventLoop): + def run_forever(self) -> None: ... + def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ... + def stop(self) -> None: ... + def is_running(self) -> bool: ... + def is_closed(self) -> bool: ... + def close(self) -> None: ... + async def shutdown_asyncgens(self) -> None: ... + # Methods scheduling callbacks. All these return Handles. + def call_soon( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + def call_later( + self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + def call_at( + self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + def time(self) -> float: ... + # Future methods + def create_future(self) -> Future[Any]: ... + # Tasks methods + # `eager_start` is supported as an arbitrary kwarg starting in 3.13.3. + if sys.version_info >= (3, 13): + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: object = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + elif sys.version_info >= (3, 11): + def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: ... + else: + def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: ... + + def set_task_factory(self, factory: _TaskFactory | None) -> None: ... + def get_task_factory(self) -> _TaskFactory | None: ... + # Methods for interacting with threads + def call_soon_threadsafe( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... + def set_default_executor(self, executor: ThreadPoolExecutor) -> None: ... # type: ignore[override] + # Network I/O methods returning Futures. + async def getaddrinfo( + self, + host: bytes | str | None, + port: bytes | str | int | None, + *, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> _GetAddrInfoResult: ... + async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + + if sys.version_info >= (3, 12): + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + all_errors: bool = False, + ) -> tuple[Transport, _ProtocolT]: ... + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: socket, + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + all_errors: bool = False, + ) -> tuple[Transport, _ProtocolT]: ... + elif sys.version_info >= (3, 11): + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: socket, + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: socket, + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + if sys.version_info >= (3, 13): + # 3.13 added `keep_alive`. + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = 0, + flags: int = 1, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = 0, + flags: int = 1, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + elif sys.version_info >= (3, 11): + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + else: + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + + if sys.version_info >= (3, 11): + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> Transport | None: ... + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> Transport | None: ... + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = True + ) -> int: ... + async def sendfile( + self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True + ) -> int: ... + if sys.version_info >= (3, 11): + async def create_datagram_endpoint( # type: ignore[override] + self, + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, + *, + family: int = 0, + proto: int = 0, + flags: int = 0, + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... + else: + async def create_datagram_endpoint( + self, + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, + *, + family: int = 0, + proto: int = 0, + flags: int = 0, + reuse_address: bool | None = ..., + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... + # Pipes and subprocesses. + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... + async def subprocess_shell( + self, + protocol_factory: Callable[[], _ProtocolT], + cmd: bytes | str, + *, + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + **kwargs: Any, + ) -> tuple[SubprocessTransport, _ProtocolT]: ... + async def subprocess_exec( + self, + protocol_factory: Callable[[], _ProtocolT], + program: Any, + *args: Any, + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + **kwargs: Any, + ) -> tuple[SubprocessTransport, _ProtocolT]: ... + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... + # The sock_* methods (and probably some others) are not actually implemented on + # BaseEventLoop, only on subclasses. We list them here for now for convenience. + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... + async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ... + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... + if sys.version_info >= (3, 11): + async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ... + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ... + async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ... + # Signal handling. + def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def remove_signal_handler(self, sig: int) -> bool: ... + # Error handlers. + def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ... + def get_exception_handler(self) -> _ExceptionHandler | None: ... + def default_exception_handler(self, context: _Context) -> None: ... + def call_exception_handler(self, context: _Context) -> None: ... + # Debug flag management. + def get_debug(self) -> bool: ... + def set_debug(self, enabled: bool) -> None: ... + if sys.version_info >= (3, 12): + async def shutdown_default_executor(self, timeout: float | None = None) -> None: ... + else: + async def shutdown_default_executor(self) -> None: ... + + def __del__(self) -> None: ... diff --git a/stdlib/asyncio/base_futures.pyi b/stdlib/asyncio/base_futures.pyi new file mode 100644 index 000000000000..2cd0f2e3a7e4 --- /dev/null +++ b/stdlib/asyncio/base_futures.pyi @@ -0,0 +1,17 @@ +from _asyncio import Future +from collections.abc import Callable, Sequence +from contextvars import Context +from typing import Any, Final +from typing_extensions import TypeIs + +from . import futures + +__all__ = () + +_PENDING: Final = "PENDING" # undocumented +_CANCELLED: Final = "CANCELLED" # undocumented +_FINISHED: Final = "FINISHED" # undocumented + +def isfuture(obj: object) -> TypeIs[Future[Any]]: ... +def _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ... # undocumented +def _future_repr_info(future: futures.Future[Any]) -> list[str]: ... # undocumented diff --git a/stdlib/asyncio/base_subprocess.pyi b/stdlib/asyncio/base_subprocess.pyi new file mode 100644 index 000000000000..36f0f6099cbc --- /dev/null +++ b/stdlib/asyncio/base_subprocess.pyi @@ -0,0 +1,62 @@ +import subprocess +from collections import deque +from collections.abc import Callable, Sequence +from typing import IO, Any, TypeAlias + +from . import events, futures, protocols, transports + +_File: TypeAlias = int | IO[Any] | None + +class BaseSubprocessTransport(transports.SubprocessTransport): + _closed: bool # undocumented + _protocol: protocols.SubprocessProtocol # undocumented + _loop: events.AbstractEventLoop # undocumented + _proc: subprocess.Popen[Any] | None # undocumented + _pid: int | None # undocumented + _returncode: int | None # undocumented + _exit_waiters: list[futures.Future[Any]] # undocumented + _pending_calls: deque[tuple[Callable[..., Any], tuple[Any, ...]]] # undocumented + _pipes: dict[int, _File] # undocumented + _finished: bool # undocumented + def __init__( + self, + loop: events.AbstractEventLoop, + protocol: protocols.SubprocessProtocol, + args: str | bytes | Sequence[str | bytes], + shell: bool, + stdin: _File, + stdout: _File, + stderr: _File, + bufsize: int, + waiter: futures.Future[Any] | None = None, + extra: Any | None = None, + **kwargs: Any, + ) -> None: ... + def _start( + self, + args: str | bytes | Sequence[str | bytes], + shell: bool, + stdin: _File, + stdout: _File, + stderr: _File, + bufsize: int, + **kwargs: Any, + ) -> None: ... # undocumented + def get_pid(self) -> int | None: ... # type: ignore[override] + def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore[override] + def _check_proc(self) -> None: ... # undocumented + def send_signal(self, signal: int) -> None: ... + async def _connect_pipes(self, waiter: futures.Future[Any] | None) -> None: ... # undocumented + def _call(self, cb: Callable[..., object], *data: Any) -> None: ... # undocumented + def _pipe_connection_lost(self, fd: int, exc: BaseException | None) -> None: ... # undocumented + def _pipe_data_received(self, fd: int, data: bytes) -> None: ... # undocumented + def _process_exited(self, returncode: int) -> None: ... # undocumented + async def _wait(self) -> int: ... # undocumented + def _try_finish(self) -> None: ... # undocumented + def _call_connection_lost(self, exc: BaseException | None) -> None: ... # undocumented + def __del__(self) -> None: ... + +class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented + def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ... + +class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): ... # undocumented diff --git a/stdlib/asyncio/base_tasks.pyi b/stdlib/asyncio/base_tasks.pyi new file mode 100644 index 000000000000..5b010a9efe3d --- /dev/null +++ b/stdlib/asyncio/base_tasks.pyi @@ -0,0 +1,17 @@ +import sys +from _typeshed import StrOrBytesPath +from types import FrameType +from typing import Any + +from .tasks import Task + +def _task_repr_info(task: Task[Any]) -> list[str]: ... # undocumented + +if sys.version_info >= (3, 13): + def _task_repr(task: Task[Any]) -> str: ... # undocumented + +elif sys.version_info >= (3, 11): + def _task_repr(self: Task[Any]) -> str: ... # undocumented + +def _task_get_stack(task: Task[Any], limit: int | None) -> list[FrameType]: ... # undocumented +def _task_print_stack(task: Task[Any], limit: int | None, file: StrOrBytesPath) -> None: ... # undocumented diff --git a/stdlib/asyncio/constants.pyi b/stdlib/asyncio/constants.pyi new file mode 100644 index 000000000000..5c6456b0e9c0 --- /dev/null +++ b/stdlib/asyncio/constants.pyi @@ -0,0 +1,20 @@ +import enum +import sys +from typing import Final + +LOG_THRESHOLD_FOR_CONNLOST_WRITES: Final = 5 +ACCEPT_RETRY_DELAY: Final = 1 +DEBUG_STACK_DEPTH: Final = 10 +SSL_HANDSHAKE_TIMEOUT: float +SENDFILE_FALLBACK_READBUFFER_SIZE: Final = 262144 +if sys.version_info >= (3, 11): + SSL_SHUTDOWN_TIMEOUT: float + FLOW_CONTROL_HIGH_WATER_SSL_READ: Final = 256 + FLOW_CONTROL_HIGH_WATER_SSL_WRITE: Final = 512 +if sys.version_info >= (3, 12): + THREAD_JOIN_TIMEOUT: Final = 300 + +class _SendfileMode(enum.Enum): + UNSUPPORTED = 1 + TRY_NATIVE = 2 + FALLBACK = 3 diff --git a/stdlib/asyncio/coroutines.pyi b/stdlib/asyncio/coroutines.pyi new file mode 100644 index 000000000000..8fafa2e75716 --- /dev/null +++ b/stdlib/asyncio/coroutines.pyi @@ -0,0 +1,45 @@ +import sys +from collections.abc import Awaitable, Callable, Coroutine +from typing import Any, ParamSpec, TypeGuard, TypeVar, overload +from typing_extensions import TypeIs, deprecated + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("iscoroutinefunction", "iscoroutine") +else: + __all__ = ("coroutine", "iscoroutinefunction", "iscoroutine") + +_T = TypeVar("_T") +_FunctionT = TypeVar("_FunctionT", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `async def` instead.") + def coroutine(func: _FunctionT) -> _FunctionT: ... + +def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ... + +if sys.version_info >= (3, 11): + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... + @overload + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") + def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... +else: + # Sometimes needed in Python < 3.11 due to the fact that it supports @coroutine + # which was removed in 3.11 which the inspect version doesn't support. + @overload + def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... + @overload + def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... + @overload + def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... + @overload + def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... diff --git a/stdlib/asyncio/events.pyi b/stdlib/asyncio/events.pyi new file mode 100644 index 000000000000..12978a97679f --- /dev/null +++ b/stdlib/asyncio/events.pyi @@ -0,0 +1,672 @@ +import ssl +import sys +from _asyncio import ( + _get_running_loop as _get_running_loop, + _set_running_loop as _set_running_loop, + get_event_loop as get_event_loop, + get_running_loop as get_running_loop, +) +from _typeshed import FileDescriptorLike, ReadableBuffer, StrPath, Unused, WriteableBuffer +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Sequence +from concurrent.futures import Executor +from contextvars import Context +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket +from typing import IO, Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated + +from . import _AwaitableLike, _CoroutineLike +from .base_events import Server +from .futures import Future +from .protocols import BaseProtocol +from .tasks import Task +from .transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport + +if sys.version_info < (3, 14): + from .unix_events import AbstractChildWatcher + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 14): + __all__ = ( + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) +else: + __all__ = ( + "AbstractEventLoopPolicy", + "AbstractEventLoop", + "AbstractServer", + "Handle", + "TimerHandle", + "get_event_loop_policy", + "set_event_loop_policy", + "get_event_loop", + "set_event_loop", + "new_event_loop", + "get_child_watcher", + "set_child_watcher", + "_set_running_loop", + "get_running_loop", + "_get_running_loop", + ) + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context: TypeAlias = dict[str, Any] +_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] +_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] +_SSLContext: TypeAlias = bool | None | ssl.SSLContext + +@type_check_only +class _TaskFactory(Protocol): + def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ... + +class Handle: + __slots__ = ("_callback", "_args", "_cancelled", "_loop", "_source_traceback", "_repr", "__weakref__", "_context") + _cancelled: bool + _args: Sequence[Any] + def __init__( + self, callback: Callable[..., object], args: Sequence[Any], loop: AbstractEventLoop, context: Context | None = None + ) -> None: ... + def cancel(self) -> None: ... + def _run(self) -> None: ... + def cancelled(self) -> bool: ... + if sys.version_info >= (3, 12): + def get_context(self) -> Context: ... + +class TimerHandle(Handle): + __slots__ = ["_scheduled", "_when"] + def __init__( + self, + when: float, + callback: Callable[..., object], + args: Sequence[Any], + loop: AbstractEventLoop, + context: Context | None = None, + ) -> None: ... + def __hash__(self) -> int: ... + def when(self) -> float: ... + def __lt__(self, other: TimerHandle) -> bool: ... + def __le__(self, other: TimerHandle) -> bool: ... + def __gt__(self, other: TimerHandle) -> bool: ... + def __ge__(self, other: TimerHandle) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class AbstractServer: + @abstractmethod + def close(self) -> None: ... + if sys.version_info >= (3, 13): + @abstractmethod + def close_clients(self) -> None: ... + @abstractmethod + def abort_clients(self) -> None: ... + + async def __aenter__(self) -> Self: ... + async def __aexit__(self, *exc: Unused) -> None: ... + @abstractmethod + def get_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def is_serving(self) -> bool: ... + @abstractmethod + async def start_serving(self) -> None: ... + @abstractmethod + async def serve_forever(self) -> None: ... + @abstractmethod + async def wait_closed(self) -> None: ... + +class AbstractEventLoop: + slow_callback_duration: float + @abstractmethod + def run_forever(self) -> None: ... + @abstractmethod + def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ... + @abstractmethod + def stop(self) -> None: ... + @abstractmethod + def is_running(self) -> bool: ... + @abstractmethod + def is_closed(self) -> bool: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + async def shutdown_asyncgens(self) -> None: ... + # Methods scheduling callbacks. All these return Handles. + # "context" added in 3.9.10/3.10.2 for call_* + @abstractmethod + def call_soon( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + @abstractmethod + def call_later( + self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + @abstractmethod + def call_at( + self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + @abstractmethod + def time(self) -> float: ... + # Future methods + @abstractmethod + def create_future(self) -> Future[Any]: ... + # Tasks methods + # `eager_start` is supported as an arbitrary kwarg starting in 3.13.3. + if sys.version_info >= (3, 13): + @abstractmethod + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + elif sys.version_info >= (3, 11): + @abstractmethod + def create_task( + self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None + ) -> Task[_T]: ... + else: + @abstractmethod + def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... + + @abstractmethod + def set_task_factory(self, factory: _TaskFactory | None) -> None: ... + @abstractmethod + def get_task_factory(self) -> _TaskFactory | None: ... + # Methods for interacting with threads + # "context" added in 3.9.10/3.10.2 + @abstractmethod + def call_soon_threadsafe( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + @abstractmethod + def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... + @abstractmethod + def set_default_executor(self, executor: Executor) -> None: ... + # Network I/O methods returning Futures. + @abstractmethod + async def getaddrinfo( + self, + host: bytes | str | None, + port: bytes | str | int | None, + *, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> _GetAddrInfoResult: ... + @abstractmethod + async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + + if sys.version_info >= (3, 11): + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: socket, + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: None = None, + local_addr: tuple[str, int] | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = None, + port: None = None, + *, + ssl: _SSLContext = None, + family: int = 0, + proto: int = 0, + flags: int = 0, + sock: socket, + local_addr: None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + happy_eyeballs_delay: float | None = None, + interleave: int | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + if sys.version_info >= (3, 13): + # 3.13 added `keep_alive`. + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + keep_alive: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + elif sys.version_info >= (3, 11): + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + else: + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = None, + port: int = ..., + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: None = None, + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = None, + port: None = None, + *, + family: int = AddressFamily.AF_UNSPEC, + flags: int = AddressInfo.AI_PASSIVE, + sock: socket = ..., + backlog: int = 100, + ssl: _SSLContext = None, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + + if sys.version_info >= (3, 11): + @abstractmethod + async def start_tls( + self, + transport: WriteTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> Transport | None: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: StrPath | None = None, + *, + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + else: + @abstractmethod + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = False, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> Transport | None: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: StrPath | None = None, + *, + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + start_serving: bool = True, + ) -> Server: ... + + if sys.version_info >= (3, 11): + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + if sys.version_info >= (3, 11): + async def create_unix_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + path: str | None = None, + *, + ssl: _SSLContext = None, + sock: socket | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + else: + async def create_unix_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + path: str | None = None, + *, + ssl: _SSLContext = None, + sock: socket | None = None, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ) -> tuple[Transport, _ProtocolT]: ... + + @abstractmethod + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = None + ) -> int: ... + @abstractmethod + async def sendfile( + self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True + ) -> int: ... + @abstractmethod + async def create_datagram_endpoint( + self, + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | str | None = None, + remote_addr: tuple[str, int] | str | None = None, + *, + family: int = 0, + proto: int = 0, + flags: int = 0, + reuse_address: bool | None = None, + reuse_port: bool | None = None, + allow_broadcast: bool | None = None, + sock: socket | None = None, + ) -> tuple[DatagramTransport, _ProtocolT]: ... + # Pipes and subprocesses. + @abstractmethod + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[ReadTransport, _ProtocolT]: ... + @abstractmethod + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[WriteTransport, _ProtocolT]: ... + @abstractmethod + async def subprocess_shell( + self, + protocol_factory: Callable[[], _ProtocolT], + cmd: bytes | str, + *, + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + **kwargs: Any, + ) -> tuple[SubprocessTransport, _ProtocolT]: ... + @abstractmethod + async def subprocess_exec( + self, + protocol_factory: Callable[[], _ProtocolT], + program: Any, + *args: Any, + stdin: int | IO[Any] | None = -1, + stdout: int | IO[Any] | None = -1, + stderr: int | IO[Any] | None = -1, + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + **kwargs: Any, + ) -> tuple[SubprocessTransport, _ProtocolT]: ... + @abstractmethod + def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + @abstractmethod + def remove_reader(self, fd: FileDescriptorLike) -> bool: ... + @abstractmethod + def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + @abstractmethod + def remove_writer(self, fd: FileDescriptorLike) -> bool: ... + @abstractmethod + async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... + @abstractmethod + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... + @abstractmethod + async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ... + @abstractmethod + async def sock_connect(self, sock: socket, address: _Address) -> None: ... + @abstractmethod + async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... + if sys.version_info >= (3, 11): + @abstractmethod + async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ... + @abstractmethod + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ... + @abstractmethod + async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ... + # Signal handling. + @abstractmethod + def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + @abstractmethod + def remove_signal_handler(self, sig: int) -> bool: ... + # Error handlers. + @abstractmethod + def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ... + @abstractmethod + def get_exception_handler(self) -> _ExceptionHandler | None: ... + @abstractmethod + def default_exception_handler(self, context: _Context) -> None: ... + @abstractmethod + def call_exception_handler(self, context: _Context) -> None: ... + # Debug flag management. + @abstractmethod + def get_debug(self) -> bool: ... + @abstractmethod + def set_debug(self, enabled: bool) -> None: ... + @abstractmethod + async def shutdown_default_executor(self) -> None: ... + +if sys.version_info >= (3, 14): + class _AbstractEventLoopPolicy: + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... + +else: + @type_check_only + class _AbstractEventLoopPolicy: + @abstractmethod + def get_event_loop(self) -> AbstractEventLoop: ... + @abstractmethod + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + @abstractmethod + def new_event_loop(self) -> AbstractEventLoop: ... + # Child processes handling (Unix only). + @abstractmethod + @deprecated("Deprecated; removed in Python 3.14.") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + @deprecated("Deprecated; removed in Python 3.14.") + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + + AbstractEventLoopPolicy = _AbstractEventLoopPolicy + +if sys.version_info >= (3, 14): + class _BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... + +else: + class BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta): + def get_event_loop(self) -> AbstractEventLoop: ... + def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... + def new_event_loop(self) -> AbstractEventLoop: ... + +if sys.version_info >= (3, 14): + def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ... + def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... + +@deprecated("Deprecated; will be removed in Python 3.16.") +def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... +@deprecated("Deprecated; will be removed in Python 3.16.") +def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... +def set_event_loop(loop: AbstractEventLoop | None) -> None: ... +def new_event_loop() -> AbstractEventLoop: ... + +if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14.") + def get_child_watcher() -> AbstractChildWatcher: ... + @deprecated("Deprecated; removed in Python 3.14.") + def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... diff --git a/stdlib/asyncio/exceptions.pyi b/stdlib/asyncio/exceptions.pyi new file mode 100644 index 000000000000..759838f45de4 --- /dev/null +++ b/stdlib/asyncio/exceptions.pyi @@ -0,0 +1,44 @@ +import sys + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ( + "BrokenBarrierError", + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) +else: + __all__ = ( + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) + +class CancelledError(BaseException): ... + +if sys.version_info >= (3, 11): + from builtins import TimeoutError as TimeoutError +else: + class TimeoutError(Exception): ... + +class InvalidStateError(Exception): ... +class SendfileNotAvailableError(RuntimeError): ... + +class IncompleteReadError(EOFError): + expected: int | None + partial: bytes + def __init__(self, partial: bytes, expected: int | None) -> None: ... + +class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... + +if sys.version_info >= (3, 11): + class BrokenBarrierError(RuntimeError): ... diff --git a/stdlib/asyncio/format_helpers.pyi b/stdlib/asyncio/format_helpers.pyi new file mode 100644 index 000000000000..ff830a3b73d4 --- /dev/null +++ b/stdlib/asyncio/format_helpers.pyi @@ -0,0 +1,31 @@ +import functools +import sys +import traceback +from collections.abc import Iterable +from types import FrameType, FunctionType +from typing import Any, TypeAlias, overload, type_check_only + +@type_check_only +class _HasWrapper: + __wrapper__: _HasWrapper | FunctionType + +_FuncType: TypeAlias = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any] + +@overload +def _get_function_source(func: _FuncType) -> tuple[str, int]: ... +@overload +def _get_function_source(func: object) -> tuple[str, int] | None: ... + +if sys.version_info >= (3, 13): + def _format_callback_source(func: object, args: Iterable[Any], *, debug: bool = False) -> str: ... + def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False) -> str: ... + def _format_callback( + func: object, args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False, suffix: str = "" + ) -> str: ... + +else: + def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... + def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: ... + def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = "") -> str: ... + +def extract_stack(f: FrameType | None = None, limit: int | None = None) -> traceback.StackSummary: ... diff --git a/stdlib/asyncio/futures.pyi b/stdlib/asyncio/futures.pyi new file mode 100644 index 000000000000..c907c7036b04 --- /dev/null +++ b/stdlib/asyncio/futures.pyi @@ -0,0 +1,19 @@ +import sys +from _asyncio import Future as Future +from concurrent.futures._base import Future as _ConcurrentFuture +from typing import TypeVar + +from .base_futures import isfuture as isfuture +from .events import AbstractEventLoop + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 14): + from _asyncio import future_add_to_awaited_by, future_discard_from_awaited_by + + __all__ = ("Future", "wrap_future", "isfuture", "future_discard_from_awaited_by", "future_add_to_awaited_by") +else: + __all__ = ("Future", "wrap_future", "isfuture") + +_T = TypeVar("_T") + +def wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ... diff --git a/stdlib/asyncio/graph.pyi b/stdlib/asyncio/graph.pyi new file mode 100644 index 000000000000..2f89de71b16b --- /dev/null +++ b/stdlib/asyncio/graph.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import SupportsWrite +from asyncio import Future +from dataclasses import dataclass +from types import FrameType +from typing import Any, overload + +if sys.version_info >= (3, 14): + __all__ = ("capture_call_graph", "format_call_graph", "print_call_graph", "FrameCallGraphEntry", "FutureCallGraph") + + @dataclass(frozen=True, slots=True) + class FrameCallGraphEntry: + frame: FrameType + + @dataclass(frozen=True, slots=True) + class FutureCallGraph: + future: Future[Any] + call_stack: tuple[FrameCallGraphEntry, ...] + awaited_by: tuple[FutureCallGraph, ...] + + @overload + def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... + @overload + def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... + + def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: ... + def print_call_graph( + future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None + ) -> None: ... diff --git a/stdlib/asyncio/locks.pyi b/stdlib/asyncio/locks.pyi new file mode 100644 index 000000000000..4420d02fcd26 --- /dev/null +++ b/stdlib/asyncio/locks.pyi @@ -0,0 +1,83 @@ +import enum +import sys +from _typeshed import Unused +from collections import deque +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, TypeVar +from typing_extensions import Self + +from .futures import Future +from .mixins import _LoopBoundMixin + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore", "Barrier") +else: + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore") + +_T = TypeVar("_T") + +class _ContextManagerMixin: + async def __aenter__(self) -> None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... + +class Lock(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] | None + def __init__(self) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... + def release(self) -> None: ... + +class Event(_LoopBoundMixin): + _waiters: deque[Future[Any]] + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + async def wait(self) -> Literal[True]: ... + +class Condition(_ContextManagerMixin, _LoopBoundMixin): + _waiters: deque[Future[Any]] + def __init__(self, lock: Lock | None = None) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... + def release(self) -> None: ... + async def wait(self) -> Literal[True]: ... + async def wait_for(self, predicate: Callable[[], _T]) -> _T: ... + def notify(self, n: int = 1) -> None: ... + def notify_all(self) -> None: ... + +class Semaphore(_ContextManagerMixin, _LoopBoundMixin): + _value: int + _waiters: deque[Future[Any]] | None + def __init__(self, value: int = 1) -> None: ... + def locked(self) -> bool: ... + async def acquire(self) -> Literal[True]: ... + def release(self) -> None: ... + def _wake_up_next(self) -> None: ... + +class BoundedSemaphore(Semaphore): ... + +if sys.version_info >= (3, 11): + class _BarrierState(enum.Enum): # undocumented + FILLING = "filling" + DRAINING = "draining" + RESETTING = "resetting" + BROKEN = "broken" + + class Barrier(_LoopBoundMixin): + def __init__(self, parties: int) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__(self, *args: Unused) -> None: ... + async def wait(self) -> int: ... + async def abort(self) -> None: ... + async def reset(self) -> None: ... + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... diff --git a/stdlib/asyncio/log.pyi b/stdlib/asyncio/log.pyi new file mode 100644 index 000000000000..e1de0b3bb845 --- /dev/null +++ b/stdlib/asyncio/log.pyi @@ -0,0 +1,3 @@ +import logging + +logger: logging.Logger diff --git a/stdlib/asyncio/mixins.pyi b/stdlib/asyncio/mixins.pyi new file mode 100644 index 000000000000..6ebcf543e6b9 --- /dev/null +++ b/stdlib/asyncio/mixins.pyi @@ -0,0 +1,9 @@ +import sys +import threading +from typing_extensions import Never + +_global_lock: threading.Lock + +class _LoopBoundMixin: + if sys.version_info < (3, 11): + def __init__(self, *, loop: Never = ...) -> None: ... diff --git a/stdlib/asyncio/proactor_events.pyi b/stdlib/asyncio/proactor_events.pyi new file mode 100644 index 000000000000..09c096d40f04 --- /dev/null +++ b/stdlib/asyncio/proactor_events.pyi @@ -0,0 +1,53 @@ +from collections.abc import Mapping +from socket import socket +from typing import Any, ClassVar, Literal + +from . import base_events, constants, events, futures, streams, transports + +__all__ = ("BaseProactorEventLoop",) + +class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, + ) -> None: ... + def __del__(self) -> None: ... + +class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, + buffer_size: int = 65536, + ) -> None: ... + +class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): ... +class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... +class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ... + +class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): + _sendfile_compatible: ClassVar[constants._SendfileMode] + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, + ) -> None: ... + def _set_extra(self, sock: socket) -> None: ... + def can_write_eof(self) -> Literal[True]: ... + +class BaseProactorEventLoop(base_events.BaseEventLoop): + def __init__(self, proactor: Any) -> None: ... + async def sock_recv(self, sock: socket, n: int) -> bytes: ... diff --git a/stdlib/asyncio/protocols.pyi b/stdlib/asyncio/protocols.pyi new file mode 100644 index 000000000000..f63b9e084382 --- /dev/null +++ b/stdlib/asyncio/protocols.pyi @@ -0,0 +1,39 @@ +from _typeshed import ReadableBuffer +from asyncio import transports +from typing import Any + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseProtocol", "Protocol", "DatagramProtocol", "SubprocessProtocol", "BufferedProtocol") + +class BaseProtocol: + __slots__ = () + def connection_made(self, transport: transports.BaseTransport) -> None: ... + def connection_lost(self, exc: Exception | None) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class Protocol(BaseProtocol): + # Need annotation or mypy will complain about 'Cannot determine type of "__slots__" in base class' + __slots__: tuple[str, ...] = () + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> bool | None: ... + +class BufferedProtocol(BaseProtocol): + __slots__ = () + def get_buffer(self, sizehint: int) -> ReadableBuffer: ... + def buffer_updated(self, nbytes: int) -> None: ... + def eof_received(self) -> bool | None: ... + +class DatagramProtocol(BaseProtocol): + __slots__ = () + def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override] + # addr is a tuple[str, int] for IPv4 or tuple[str, int, int, int] for IPv6. + # It can also be a tuple[int, int] for unusual protocols like socket.AF_NETLINK. + def datagram_received(self, data: bytes, addr: tuple[Any, ...]) -> None: ... + def error_received(self, exc: Exception) -> None: ... + +class SubprocessProtocol(BaseProtocol): + __slots__: tuple[str, ...] = () + def pipe_data_received(self, fd: int, data: bytes) -> None: ... + def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ... + def process_exited(self) -> None: ... diff --git a/stdlib/asyncio/queues.pyi b/stdlib/asyncio/queues.pyi new file mode 100644 index 000000000000..de7c4879d348 --- /dev/null +++ b/stdlib/asyncio/queues.pyi @@ -0,0 +1,45 @@ +import sys +from _typeshed import SupportsRichComparisonT +from types import GenericAlias +from typing import Any, Generic, TypeVar + +from .mixins import _LoopBoundMixin + +class QueueEmpty(Exception): ... +class QueueFull(Exception): ... + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 13): + __all__ = ("Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty", "QueueShutDown") + +else: + __all__ = ("Queue", "PriorityQueue", "LifoQueue", "QueueFull", "QueueEmpty") + +_T = TypeVar("_T") + +if sys.version_info >= (3, 13): + class QueueShutDown(Exception): ... + +class Queue(_LoopBoundMixin, Generic[_T]): + def __init__(self, maxsize: int = 0) -> None: ... + def _init(self, maxsize: int) -> None: ... + def _get(self) -> _T: ... + def _put(self, item: _T) -> None: ... + def _format(self) -> str: ... + def qsize(self) -> int: ... + @property + def maxsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + async def put(self, item: _T) -> None: ... + def put_nowait(self, item: _T) -> None: ... + async def get(self) -> _T: ... + def get_nowait(self) -> _T: ... + async def join(self) -> None: ... + def task_done(self) -> None: ... + def __class_getitem__(cls, type: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 13): + def shutdown(self, immediate: bool = False) -> None: ... + +class PriorityQueue(Queue[SupportsRichComparisonT]): ... +class LifoQueue(Queue[_T]): ... diff --git a/stdlib/asyncio/runners.pyi b/stdlib/asyncio/runners.pyi new file mode 100644 index 000000000000..3a1e33aac689 --- /dev/null +++ b/stdlib/asyncio/runners.pyi @@ -0,0 +1,41 @@ +import sys +from _typeshed import Unused +from collections.abc import Awaitable, Callable, Coroutine +from contextvars import Context +from typing import Any, TypeVar, final +from typing_extensions import Self + +from .events import AbstractEventLoop + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 11): + __all__ = ("Runner", "run") +else: + __all__ = ("run",) +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + @final + class Runner: + def __init__(self, *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ... + def close(self) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + if sys.version_info >= (3, 14): + def run(self, coro: Awaitable[_T], *, context: Context | None = None) -> _T: ... + else: + def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = None) -> _T: ... + +if sys.version_info >= (3, 14): + def run( + main: Awaitable[_T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None + ) -> _T: ... + +elif sys.version_info >= (3, 12): + def run( + main: Coroutine[Any, Any, _T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None + ) -> _T: ... + +else: + def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ... diff --git a/stdlib/asyncio/selector_events.pyi b/stdlib/asyncio/selector_events.pyi new file mode 100644 index 000000000000..18c5df033e2f --- /dev/null +++ b/stdlib/asyncio/selector_events.pyi @@ -0,0 +1,10 @@ +import selectors +from socket import socket + +from . import base_events + +__all__ = ("BaseSelectorEventLoop",) + +class BaseSelectorEventLoop(base_events.BaseEventLoop): + def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ... + async def sock_recv(self, sock: socket, n: int) -> bytes: ... diff --git a/stdlib/asyncio/sslproto.pyi b/stdlib/asyncio/sslproto.pyi new file mode 100644 index 000000000000..72b4ea449e86 --- /dev/null +++ b/stdlib/asyncio/sslproto.pyi @@ -0,0 +1,164 @@ +import ssl +import sys +from collections import deque +from collections.abc import Callable +from enum import Enum +from typing import Any, ClassVar, Final, Literal, TypeAlias + +from . import constants, events, futures, protocols, transports + +def _create_transport_context(server_side: bool, server_hostname: str | None) -> ssl.SSLContext: ... + +if sys.version_info >= (3, 11): + SSLAgainErrors: tuple[type[ssl.SSLWantReadError], type[ssl.SSLSyscallError]] + + class SSLProtocolState(Enum): + UNWRAPPED = "UNWRAPPED" + DO_HANDSHAKE = "DO_HANDSHAKE" + WRAPPED = "WRAPPED" + FLUSHING = "FLUSHING" + SHUTDOWN = "SHUTDOWN" + + class AppProtocolState(Enum): + STATE_INIT = "STATE_INIT" + STATE_CON_MADE = "STATE_CON_MADE" + STATE_EOF = "STATE_EOF" + STATE_CON_LOST = "STATE_CON_LOST" + + def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ... + +else: + _UNWRAPPED: Final = "UNWRAPPED" + _DO_HANDSHAKE: Final = "DO_HANDSHAKE" + _WRAPPED: Final = "WRAPPED" + _SHUTDOWN: Final = "SHUTDOWN" + +if sys.version_info < (3, 11): + class _SSLPipe: + max_size: ClassVar[int] + + _context: ssl.SSLContext + _server_side: bool + _server_hostname: str | None + _state: str + _incoming: ssl.MemoryBIO + _outgoing: ssl.MemoryBIO + _sslobj: ssl.SSLObject | None + _need_ssldata: bool + _handshake_cb: Callable[[BaseException | None], None] | None + _shutdown_cb: Callable[[], None] | None + def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = None) -> None: ... + @property + def context(self) -> ssl.SSLContext: ... + @property + def ssl_object(self) -> ssl.SSLObject | None: ... + @property + def need_ssldata(self) -> bool: ... + @property + def wrapped(self) -> bool: ... + def do_handshake(self, callback: Callable[[BaseException | None], object] | None = None) -> list[bytes]: ... + def shutdown(self, callback: Callable[[], object] | None = None) -> list[bytes]: ... + def feed_eof(self) -> None: ... + def feed_ssldata(self, data: bytes, only_handshake: bool = False) -> tuple[list[bytes], list[bytes]]: ... + def feed_appdata(self, data: bytes, offset: int = 0) -> tuple[list[bytes], int]: ... + +class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): + _sendfile_compatible: ClassVar[constants._SendfileMode] + + _loop: events.AbstractEventLoop + if sys.version_info >= (3, 11): + _ssl_protocol: SSLProtocol | None + else: + _ssl_protocol: SSLProtocol + _closed: bool + def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... + def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: ... + @property + def _protocol_paused(self) -> bool: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape + def can_write_eof(self) -> Literal[False]: ... + if sys.version_info >= (3, 11): + def get_write_buffer_limits(self) -> tuple[int, int]: ... + def get_read_buffer_limits(self) -> tuple[int, int]: ... + def set_read_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ... + def get_read_buffer_size(self) -> int: ... + + def __del__(self) -> None: ... + +if sys.version_info >= (3, 11): + _SSLProtocolBase: TypeAlias = protocols.BufferedProtocol +else: + _SSLProtocolBase: TypeAlias = protocols.Protocol + +class SSLProtocol(_SSLProtocolBase): + _server_side: bool + _server_hostname: str | None + _sslcontext: ssl.SSLContext + _extra: dict[str, Any] + _write_backlog: deque[tuple[bytes, int]] + _write_buffer_size: int + _waiter: futures.Future[Any] + _loop: events.AbstractEventLoop + _app_transport: _SSLProtocolTransport + _transport: transports.BaseTransport | None + _ssl_handshake_timeout: int | None + _app_protocol: protocols.BaseProtocol + _app_protocol_is_buffer: bool + + if sys.version_info >= (3, 11): + max_size: ClassVar[int] + else: + _sslpipe: _SSLPipe | None + _session_established: bool + _call_connection_made: bool + _in_handshake: bool + _in_shutdown: bool + + if sys.version_info >= (3, 11): + def __init__( + self, + loop: events.AbstractEventLoop, + app_protocol: protocols.BaseProtocol, + sslcontext: ssl.SSLContext, + waiter: futures.Future[Any], + server_side: bool = False, + server_hostname: str | None = None, + call_connection_made: bool = True, + ssl_handshake_timeout: int | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> None: ... + else: + def __init__( + self, + loop: events.AbstractEventLoop, + app_protocol: protocols.BaseProtocol, + sslcontext: ssl.SSLContext, + waiter: futures.Future[Any], + server_side: bool = False, + server_hostname: str | None = None, + call_connection_made: bool = True, + ssl_handshake_timeout: int | None = None, + ) -> None: ... + + def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... + def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ... + def connection_lost(self, exc: BaseException | None) -> None: ... + def eof_received(self) -> None: ... + def _get_extra_info(self, name: str, default: Any | None = None) -> Any: ... + def _start_shutdown(self) -> None: ... + if sys.version_info >= (3, 11): + def _write_appdata(self, list_of_data: list[bytes]) -> None: ... + else: + def _write_appdata(self, data: bytes) -> None: ... + + def _start_handshake(self) -> None: ... + def _check_handshake_timeout(self) -> None: ... + def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ... + def _fatal_error(self, exc: BaseException, message: str = "Fatal error on transport") -> None: ... + if sys.version_info >= (3, 11): + def _abort(self, exc: BaseException | None) -> None: ... + def get_buffer(self, n: int) -> memoryview: ... + else: + def _abort(self) -> None: ... + def _finalize(self) -> None: ... + def _process_write_backlog(self) -> None: ... diff --git a/stdlib/asyncio/staggered.pyi b/stdlib/asyncio/staggered.pyi new file mode 100644 index 000000000000..3324777f4168 --- /dev/null +++ b/stdlib/asyncio/staggered.pyi @@ -0,0 +1,10 @@ +from collections.abc import Awaitable, Callable, Iterable +from typing import Any + +from . import events + +__all__ = ("staggered_race",) + +async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None +) -> tuple[Any, int | None, list[Exception | None]]: ... diff --git a/stdlib/asyncio/streams.pyi b/stdlib/asyncio/streams.pyi new file mode 100644 index 000000000000..9e76c69d8732 --- /dev/null +++ b/stdlib/asyncio/streams.pyi @@ -0,0 +1,124 @@ +import ssl +import sys +from _typeshed import ReadableBuffer, StrPath +from collections.abc import Awaitable, Callable, Iterable, Sequence, Sized +from types import ModuleType +from typing import Any, Protocol, SupportsIndex, TypeAlias, type_check_only +from typing_extensions import Self + +from . import events, protocols, transports +from .base_events import Server + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform == "win32": + __all__ = ("StreamReader", "StreamWriter", "StreamReaderProtocol", "open_connection", "start_server") +else: + __all__ = ( + "StreamReader", + "StreamWriter", + "StreamReaderProtocol", + "open_connection", + "start_server", + "open_unix_connection", + "start_unix_server", + ) + +_ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None] + +@type_check_only +class _ReaduntilBuffer(ReadableBuffer, Sized, Protocol): ... + +async def open_connection( + host: str | None = None, + port: int | str | None = None, + *, + limit: int = 65536, + ssl_handshake_timeout: float | None = None, + **kwds: Any, +) -> tuple[StreamReader, StreamWriter]: ... +async def start_server( + client_connected_cb: _ClientConnectedCallback, + host: str | Sequence[str] | None = None, + port: int | str | None = None, + *, + limit: int = 65536, + ssl_handshake_timeout: float | None = None, + **kwds: Any, +) -> Server: ... + +if sys.platform != "win32": + async def open_unix_connection( + path: StrPath | None = None, *, limit: int = 65536, **kwds: Any + ) -> tuple[StreamReader, StreamWriter]: ... + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any + ) -> Server: ... + +class FlowControlMixin(protocols.Protocol): + def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ... + +class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): + def __init__( + self, + stream_reader: StreamReader, + client_connected_cb: _ClientConnectedCallback | None = None, + loop: events.AbstractEventLoop | None = None, + ) -> None: ... + def __del__(self) -> None: ... + +class StreamWriter: + def __init__( + self, + transport: transports.WriteTransport, + protocol: protocols.BaseProtocol, + reader: StreamReader | None, + loop: events.AbstractEventLoop, + ) -> None: ... + @property + def transport(self) -> transports.WriteTransport: ... + def write(self, data: bytes | bytearray | memoryview) -> None: ... + def writelines(self, data: Iterable[bytes | bytearray | memoryview]) -> None: ... + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def close(self) -> None: ... + def is_closing(self) -> bool: ... + async def wait_closed(self) -> None: ... + def get_extra_info(self, name: str, default: Any = None) -> Any: ... + async def drain(self) -> None: ... + if sys.version_info >= (3, 12): + async def start_tls( + self, + sslcontext: ssl.SSLContext, + *, + server_hostname: str | None = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + ) -> None: ... + elif sys.version_info >= (3, 11): + async def start_tls( + self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None + ) -> None: ... + + if sys.version_info >= (3, 13): + def __del__(self, warnings: ModuleType = ...) -> None: ... + elif sys.version_info >= (3, 11): + def __del__(self) -> None: ... + +class StreamReader: + def __init__(self, limit: int = 65536, loop: events.AbstractEventLoop | None = None) -> None: ... + def exception(self) -> Exception | None: ... + def set_exception(self, exc: Exception) -> None: ... + def set_transport(self, transport: transports.BaseTransport) -> None: ... + def feed_eof(self) -> None: ... + def at_eof(self) -> bool: ... + def feed_data(self, data: Iterable[SupportsIndex]) -> None: ... + async def readline(self) -> bytes: ... + if sys.version_info >= (3, 13): + async def readuntil(self, separator: _ReaduntilBuffer | tuple[_ReaduntilBuffer, ...] = b"\n") -> bytes: ... + else: + async def readuntil(self, separator: _ReaduntilBuffer = b"\n") -> bytes: ... + + async def read(self, n: int = -1) -> bytes: ... + async def readexactly(self, n: int) -> bytes: ... + def __aiter__(self) -> Self: ... + async def __anext__(self) -> bytes: ... diff --git a/stdlib/asyncio/subprocess.pyi b/stdlib/asyncio/subprocess.pyi new file mode 100644 index 000000000000..6405e5ae1474 --- /dev/null +++ b/stdlib/asyncio/subprocess.pyi @@ -0,0 +1,166 @@ +import subprocess +import sys +from _typeshed import StrOrBytesPath +from asyncio import events, protocols, streams, transports +from collections.abc import Callable, Collection +from typing import IO, Any, Literal + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("create_subprocess_exec", "create_subprocess_shell") + +PIPE: int +STDOUT: int +DEVNULL: int + +class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol): + stdin: streams.StreamWriter | None + stdout: streams.StreamReader | None + stderr: streams.StreamReader | None + def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ... + def pipe_data_received(self, fd: int, data: bytes | str) -> None: ... + +class Process: + stdin: streams.StreamWriter | None + stdout: streams.StreamReader | None + stderr: streams.StreamReader | None + pid: int + def __init__( + self, transport: transports.BaseTransport, protocol: protocols.BaseProtocol, loop: events.AbstractEventLoop + ) -> None: ... + @property + def returncode(self) -> int | None: ... + async def wait(self) -> int: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + async def communicate(self, input: bytes | bytearray | memoryview | None = None) -> tuple[bytes, bytes]: ... + +if sys.version_info >= (3, 11): + async def create_subprocess_shell( + cmd: str | bytes, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + *, + # These parameters are forced to these values by BaseEventLoop.subprocess_shell + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + # These parameters are taken by subprocess.Popen, which this ultimately delegates to + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: None | str | int = None, + extra_groups: None | Collection[str | int] = None, + user: None | str | int = None, + umask: int = -1, + process_group: int | None = None, + pipesize: int = -1, + ) -> Process: ... + async def create_subprocess_exec( + program: StrOrBytesPath, + *args: StrOrBytesPath, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + # These parameters are forced to these values by BaseEventLoop.subprocess_exec + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + # These parameters are taken by subprocess.Popen, which this ultimately delegates to + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: None | str | int = None, + extra_groups: None | Collection[str | int] = None, + user: None | str | int = None, + umask: int = -1, + process_group: int | None = None, + pipesize: int = -1, + ) -> Process: ... + +else: + async def create_subprocess_shell( + cmd: str | bytes, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + *, + # These parameters are forced to these values by BaseEventLoop.subprocess_shell + universal_newlines: Literal[False] = False, + shell: Literal[True] = True, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + # These parameters are taken by subprocess.Popen, which this ultimately delegates to + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: None | str | int = None, + extra_groups: None | Collection[str | int] = None, + user: None | str | int = None, + umask: int = -1, + pipesize: int = -1, + ) -> Process: ... + async def create_subprocess_exec( + program: StrOrBytesPath, + *args: StrOrBytesPath, + stdin: int | IO[Any] | None = None, + stdout: int | IO[Any] | None = None, + stderr: int | IO[Any] | None = None, + limit: int = 65536, + # These parameters are forced to these values by BaseEventLoop.subprocess_exec + universal_newlines: Literal[False] = False, + shell: Literal[False] = False, + bufsize: Literal[0] = 0, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + # These parameters are taken by subprocess.Popen, which this ultimately delegates to + executable: StrOrBytesPath | None = None, + preexec_fn: Callable[[], Any] | None = None, + close_fds: bool = True, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + group: None | str | int = None, + extra_groups: None | Collection[str | int] = None, + user: None | str | int = None, + umask: int = -1, + pipesize: int = -1, + ) -> Process: ... diff --git a/stdlib/asyncio/taskgroups.pyi b/stdlib/asyncio/taskgroups.pyi new file mode 100644 index 000000000000..886a79c4beb5 --- /dev/null +++ b/stdlib/asyncio/taskgroups.pyi @@ -0,0 +1,41 @@ +import sys +from contextvars import Context +from types import TracebackType +from typing import Any, TypeVar +from typing_extensions import Self + +from . import _CoroutineLike +from .events import AbstractEventLoop +from .tasks import Task + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 12): + __all__ = ("TaskGroup",) +else: + __all__ = ["TaskGroup"] + +_T = TypeVar("_T") + +class TaskGroup: + _loop: AbstractEventLoop | None + _tasks: set[Task[Any]] + + async def __aenter__(self) -> Self: ... + async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + if sys.version_info >= (3, 14): + def create_task( + self, + coro: _CoroutineLike[_T], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool | None = None, + ) -> Task[_T]: ... + else: + def create_task( + self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None + ) -> Task[_T]: ... + + def _on_task_done(self, task: Task[object]) -> None: ... + if sys.version_info >= (3, 15): + def cancel(self) -> None: ... diff --git a/stdlib/asyncio/tasks.pyi b/stdlib/asyncio/tasks.pyi new file mode 100644 index 000000000000..66c31f15e6fb --- /dev/null +++ b/stdlib/asyncio/tasks.pyi @@ -0,0 +1,315 @@ +import concurrent.futures +import sys +from _asyncio import ( + Task as Task, + _enter_task as _enter_task, + _leave_task as _leave_task, + _register_task as _register_task, + _unregister_task as _unregister_task, +) +from collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from . import _CoroutineLike +from .events import AbstractEventLoop +from .futures import Future + +if sys.version_info >= (3, 11): + from contextvars import Context + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.version_info >= (3, 12): + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "create_eager_task_factory", + "eager_task_factory", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) +else: + __all__ = ( + "Task", + "create_task", + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "wait", + "wait_for", + "as_completed", + "sleep", + "gather", + "shield", + "ensure_future", + "run_coroutine_threadsafe", + "current_task", + "all_tasks", + "_register_task", + "_unregister_task", + "_enter_task", + "_leave_task", + ) + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") +_FT = TypeVar("_FT", bound=Future[Any]) +if sys.version_info >= (3, 12): + _FutureLike: TypeAlias = Future[_T] | Awaitable[_T] +else: + _FutureLike: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T] + +_TaskYieldType: TypeAlias = Future[object] | None + +FIRST_COMPLETED: Final = concurrent.futures.FIRST_COMPLETED +FIRST_EXCEPTION: Final = concurrent.futures.FIRST_EXCEPTION +ALL_COMPLETED: Final = concurrent.futures.ALL_COMPLETED + +if sys.version_info >= (3, 13): + @type_check_only + class _SyncAndAsyncIterator(Iterator[Coroutine[Any, Any, _T]], AsyncIterator[Future[_T]], Protocol[_T]): ... + + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[_T]: ... + +else: + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ... + +@overload +def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: ... # type: ignore[overload-overlap] +@overload +def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | None = None) -> Task[_T]: ... + +# `gather()` actually returns a list with length equal to the number +# of tasks passed; however, Tuple is used similar to the annotation for +# zip() because typing does not support variadic type variables. See +# typing PR #1550 for discussion. +# +# N.B. Having overlapping overloads is the only way to get acceptable type inference in all edge cases. +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False +) -> Future[tuple[_T1, _T2]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ... # type: ignore[overload-overlap] +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: bool, +) -> Future[ + tuple[ + _T1 | BaseException, + _T2 | BaseException, + _T3 | BaseException, + _T4 | BaseException, + _T5 | BaseException, + _T6 | BaseException, + ] +]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: bool) -> Future[list[_T | BaseException]]: ... + +# unlike some asyncio apis, This does strict runtime checking of actually being a coroutine, not of any future-like. +def run_coroutine_threadsafe(coro: Coroutine[Any, Any, _T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureLike[_T]) -> Future[_T]: ... + +@overload +async def sleep(delay: float) -> None: ... +@overload +async def sleep(delay: float, result: _T) -> _T: ... + +async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ... + +if sys.version_info >= (3, 11): + async def wait( + fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[_FT], set[_FT]]: ... + +else: + @overload + async def wait( # type: ignore[overload-overlap] + fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[_FT], set[_FT]]: ... + @overload + async def wait( + fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... + +if sys.version_info >= (3, 12): + _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] +else: + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] + +def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... + +if sys.version_info >= (3, 14): + def create_task( + coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None, eager_start: bool | None = None + ) -> Task[_T]: ... + +elif sys.version_info >= (3, 11): + def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ... + +else: + def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ... + +if sys.version_info >= (3, 12): + from _asyncio import current_task as current_task +else: + def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... + +if sys.version_info >= (3, 14): + def eager_task_factory( + loop: AbstractEventLoop | None, + coro: _TaskCompatibleCoro[_T_co], + *, + name: str | None = None, + context: Context | None = None, + eager_start: bool = True, + ) -> Task[_T_co]: ... + +elif sys.version_info >= (3, 12): + def eager_task_factory( + loop: AbstractEventLoop | None, + coro: _TaskCompatibleCoro[_T_co], + *, + name: str | None = None, + context: Context | None = None, + ) -> Task[_T_co]: ... + +if sys.version_info >= (3, 12): + _TaskT_co = TypeVar("_TaskT_co", bound=Task[Any], covariant=True) + + @type_check_only + class _CustomTaskConstructor(Protocol[_TaskT_co]): + def __call__( + self, + coro: _TaskCompatibleCoro[Any], + /, + *, + loop: AbstractEventLoop, + name: str | None, + context: Context | None, + eager_start: bool, + ) -> _TaskT_co: ... + + @type_check_only + class _EagerTaskFactoryType(Protocol[_TaskT_co]): + def __call__( + self, + loop: AbstractEventLoop, + coro: _TaskCompatibleCoro[Any], + *, + name: str | None = None, + context: Context | None = None, + ) -> _TaskT_co: ... + + def create_eager_task_factory( + custom_task_constructor: _CustomTaskConstructor[_TaskT_co], + ) -> _EagerTaskFactoryType[_TaskT_co]: ... diff --git a/stdlib/asyncio/threads.pyi b/stdlib/asyncio/threads.pyi new file mode 100644 index 000000000000..f1d882918098 --- /dev/null +++ b/stdlib/asyncio/threads.pyi @@ -0,0 +1,9 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("to_thread",) +_P = ParamSpec("_P") +_R = TypeVar("_R") + +async def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/stdlib/asyncio/timeouts.pyi b/stdlib/asyncio/timeouts.pyi new file mode 100644 index 000000000000..668cccbfe8b1 --- /dev/null +++ b/stdlib/asyncio/timeouts.pyi @@ -0,0 +1,20 @@ +from types import TracebackType +from typing import final +from typing_extensions import Self + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("Timeout", "timeout", "timeout_at") + +@final +class Timeout: + def __init__(self, when: float | None) -> None: ... + def when(self) -> float | None: ... + def reschedule(self, when: float | None) -> None: ... + def expired(self) -> bool: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +def timeout(delay: float | None) -> Timeout: ... +def timeout_at(when: float | None) -> Timeout: ... diff --git a/stdlib/asyncio/tools.pyi b/stdlib/asyncio/tools.pyi new file mode 100644 index 000000000000..36c65541c9cd --- /dev/null +++ b/stdlib/asyncio/tools.pyi @@ -0,0 +1,51 @@ +import sys +from collections.abc import Iterable +from enum import Enum +from typing import NamedTuple, SupportsIndex, type_check_only + +@type_check_only +class _AwaitedInfo(NamedTuple): # AwaitedInfo_Type from _remote_debugging + thread_id: int + awaited_by: list[_TaskInfo] + +@type_check_only +class _TaskInfo(NamedTuple): # TaskInfo_Type from _remote_debugging + task_id: int + task_name: str + coroutine_stack: list[_CoroInfo] + awaited_by: list[_CoroInfo] + +@type_check_only +class _CoroInfo(NamedTuple): # CoroInfo_Type from _remote_debugging + call_stack: list[_FrameInfo] + task_name: int | str + +@type_check_only +class _FrameInfo(NamedTuple): # FrameInfo_Type from _remote_debugging + filename: str + lineno: int + funcname: str + +class NodeType(Enum): + COROUTINE = 1 + TASK = 2 + +class CycleFoundException(Exception): + cycles: list[list[int]] + id2name: dict[int, str] + def __init__(self, cycles: list[list[int]], id2name: dict[int, str]) -> None: ... + +def get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ... +def build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = "(T)", cor_emoji: str = "") -> list[list[str]]: ... +def build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ... + +if sys.version_info >= (3, 14): + def exit_with_permission_help_text() -> None: ... + +if sys.version_info >= (3, 15): + def display_awaited_by_tasks_table(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + +else: + def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ... diff --git a/stdlib/asyncio/transports.pyi b/stdlib/asyncio/transports.pyi new file mode 100644 index 000000000000..cc870d5e0b9a --- /dev/null +++ b/stdlib/asyncio/transports.pyi @@ -0,0 +1,57 @@ +from asyncio.events import AbstractEventLoop +from asyncio.protocols import BaseProtocol +from collections.abc import Iterable, Mapping +from socket import _Address +from typing import Any + +# Keep asyncio.__all__ updated with any changes to __all__ here +__all__ = ("BaseTransport", "ReadTransport", "WriteTransport", "Transport", "DatagramTransport", "SubprocessTransport") + +class BaseTransport: + __slots__ = ("_extra",) + def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ... + def get_extra_info(self, name: str, default: Any = None) -> Any: ... + def is_closing(self) -> bool: ... + def close(self) -> None: ... + def set_protocol(self, protocol: BaseProtocol) -> None: ... + def get_protocol(self) -> BaseProtocol: ... + +class ReadTransport(BaseTransport): + __slots__ = () + def is_reading(self) -> bool: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + +class WriteTransport(BaseTransport): + __slots__ = () + def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ... + def get_write_buffer_size(self) -> int: ... + def get_write_buffer_limits(self) -> tuple[int, int]: ... + def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ... # any memoryview format or shape + def writelines( + self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]] + ) -> None: ... # any memoryview format or shape + def write_eof(self) -> None: ... + def can_write_eof(self) -> bool: ... + def abort(self) -> None: ... + +class Transport(ReadTransport, WriteTransport): + __slots__ = () + +class DatagramTransport(BaseTransport): + __slots__ = () + def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: ... + def abort(self) -> None: ... + +class SubprocessTransport(BaseTransport): + __slots__ = () + def get_pid(self) -> int: ... + def get_returncode(self) -> int | None: ... + def get_pipe_transport(self, fd: int) -> BaseTransport | None: ... + def send_signal(self, signal: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + +class _FlowControlMixin(Transport): + __slots__ = ("_loop", "_protocol_paused", "_high_water", "_low_water") + def __init__(self, extra: Mapping[str, Any] | None = None, loop: AbstractEventLoop | None = None) -> None: ... diff --git a/stdlib/asyncio/trsock.pyi b/stdlib/asyncio/trsock.pyi new file mode 100644 index 000000000000..d2e972fee49c --- /dev/null +++ b/stdlib/asyncio/trsock.pyi @@ -0,0 +1,137 @@ +import socket +import sys +from _typeshed import ReadableBuffer +from builtins import type as Type # alias to avoid name clashes with property named "type" +from collections.abc import Iterable +from types import TracebackType +from typing import Any, BinaryIO, TypeAlias, overload +from typing_extensions import Never, deprecated + +# These are based in socket, maybe move them out into _typeshed.pyi or such +_Address: TypeAlias = socket._Address +_RetAddress: TypeAlias = Any +_WriteBuffer: TypeAlias = bytearray | memoryview +_CMSG: TypeAlias = tuple[int, int, bytes] + +class TransportSocket: + __slots__ = ("_sock",) + def __init__(self, sock: socket.socket) -> None: ... + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + def __getstate__(self) -> Never: ... + def fileno(self) -> int: ... + def dup(self) -> socket.socket: ... + def get_inheritable(self) -> bool: ... + def shutdown(self, how: int) -> None: ... + + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + @overload + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... + + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + def getsockbyname(self) -> Never: ... # This method doesn't exist on socket, yet is passed through? + def settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, flag: bool) -> None: ... + if sys.version_info < (3, 11): + def _na(self, what: str) -> None: ... + @deprecated("Removed in Python 3.11") + def accept(self) -> tuple[socket.socket, _RetAddress]: ... + @deprecated("Removed in Python 3.11") + def connect(self, address: _Address) -> None: ... + @deprecated("Removed in Python 3.11") + def connect_ex(self, address: _Address) -> int: ... + @deprecated("Removed in Python 3.11") + def bind(self, address: _Address) -> None: ... + + if sys.platform == "win32": + @deprecated("Removed in Python 3.11") + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... + else: + @deprecated("Removed in Python 3.11") + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> Never: ... + + @deprecated("Removed in Python 3.11") + def listen(self, backlog: int = ..., /) -> None: ... + @deprecated("Removed in Python 3.11") + def makefile(self) -> BinaryIO: ... + @deprecated("Removed in Python 3.11") + def sendfile(self, file: BinaryIO, offset: int = 0, count: int | None = None) -> int: ... + @deprecated("Removed in Python 3.11") + def close(self) -> None: ... + @deprecated("Removed in Python 3.11") + def detach(self) -> int: ... + + if sys.platform == "linux": + @deprecated("Removed in Python 3.11") + def sendmsg_afalg( + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 + ) -> int: ... + else: + @deprecated("Removed in Python 3.11.") + def sendmsg_afalg( + self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 + ) -> Never: ... + + @deprecated("Removed in Python 3.11.") + def sendmsg( + self, + buffers: Iterable[ReadableBuffer], + ancdata: Iterable[_CMSG] = ..., + flags: int = 0, + address: _Address | None = None, + /, + ) -> int: ... + + @overload + @deprecated("Removed in Python 3.11.") + def sendto(self, data: ReadableBuffer, address: _Address) -> int: ... + @overload + @deprecated("Removed in Python 3.11.") + def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ... + + @deprecated("Removed in Python 3.11.") + def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... + @deprecated("Removed in Python 3.11.") + def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... + @deprecated("Removed in Python 3.11.") + def set_inheritable(self, inheritable: bool) -> None: ... + + if sys.platform == "win32": + @deprecated("Removed in Python 3.11.") + def share(self, process_id: int) -> bytes: ... + else: + @deprecated("Removed in Python 3.11.") + def share(self, process_id: int) -> Never: ... + + @deprecated("Removed in Python 3.11.") + def recv_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> int: ... + @deprecated("Removed in Python 3.11.") + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ... + @deprecated("Removed in Python 3.11.") + def recvmsg_into( + self, buffers: Iterable[_WriteBuffer], ancbufsize: int = 0, flags: int = 0, / + ) -> tuple[int, list[_CMSG], int, Any]: ... + @deprecated("Removed in Python 3.11.") + def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ... + @deprecated("Removed in Python 3.11.") + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _RetAddress]: ... + @deprecated("Removed in Python 3.11.") + def recv(self, bufsize: int, flags: int = 0) -> bytes: ... + @deprecated("Removed in Python 3.11.") + def __enter__(self) -> socket.socket: ... + @deprecated("Removed in Python 3.11.") + def __exit__( + self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... diff --git a/stdlib/asyncio/unix_events.pyi b/stdlib/asyncio/unix_events.pyi new file mode 100644 index 000000000000..368cac38302f --- /dev/null +++ b/stdlib/asyncio/unix_events.pyi @@ -0,0 +1,277 @@ +import sys +import types +from _typeshed import StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import Callable +from socket import socket +from typing import Literal +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated + +from . import events +from .base_events import Server, _ProtocolFactory, _SSLContext +from .selector_events import BaseSelectorEventLoop + +_Ts = TypeVarTuple("_Ts") + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform != "win32": + if sys.version_info >= (3, 14): + __all__ = ("SelectorEventLoop", "EventLoop") + elif sys.version_info >= (3, 13): + # Adds EventLoop + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "PidfdChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + "EventLoop", + ) + else: + # adds PidfdChildWatcher + __all__ = ( + "SelectorEventLoop", + "AbstractChildWatcher", + "SafeChildWatcher", + "FastChildWatcher", + "PidfdChildWatcher", + "MultiLoopChildWatcher", + "ThreadedChildWatcher", + "DefaultEventLoopPolicy", + ) + +# This is also technically not available on Win, +# but other parts of typeshed need this definition. +# So, it is special cased. +if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... + + else: + class AbstractChildWatcher: + @abstractmethod + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + @abstractmethod + def remove_child_handler(self, pid: int) -> bool: ... + @abstractmethod + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + @abstractmethod + def close(self) -> None: ... + @abstractmethod + def __enter__(self) -> Self: ... + @abstractmethod + def __exit__( + self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None + ) -> None: ... + @abstractmethod + def is_active(self) -> bool: ... + +if sys.platform != "win32": + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + else: + # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. + # See discussion in #7412 + class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): + def close(self) -> None: ... + def is_active(self) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class SafeChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + class FastChildWatcher(BaseChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + class _UnixSelectorEventLoop(BaseSelectorEventLoop): + if sys.version_info >= (3, 13): + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: StrPath | None = None, + *, + sock: socket | None = None, + backlog: int = 100, + ssl: _SSLContext = None, + ssl_handshake_timeout: float | None = None, + ssl_shutdown_timeout: float | None = None, + start_serving: bool = True, + cleanup_socket: bool = True, + ) -> Server: ... + + if sys.version_info >= (3, 14): + class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy): ... + else: + class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + else: + def get_child_watcher(self) -> AbstractChildWatcher: ... + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + + SelectorEventLoop = _UnixSelectorEventLoop + + if sys.version_info >= (3, 14): + _DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + else: + DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + + if sys.version_info >= (3, 13): + EventLoop = SelectorEventLoop + + if sys.version_info < (3, 14): + if sys.version_info >= (3, 12): + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + + else: + class MultiLoopChildWatcher(AbstractChildWatcher): + def is_active(self) -> bool: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class ThreadedChildWatcher(AbstractChildWatcher): + def is_active(self) -> Literal[True]: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... diff --git a/stdlib/asyncio/windows_events.pyi b/stdlib/asyncio/windows_events.pyi new file mode 100644 index 000000000000..a2428e425f2f --- /dev/null +++ b/stdlib/asyncio/windows_events.pyi @@ -0,0 +1,122 @@ +import socket +import sys +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from typing import IO, Any, ClassVar, Final +from typing_extensions import Never + +from . import events, futures, proactor_events, selector_events, streams, windows_utils + +# Keep asyncio.__all__ updated with any changes to __all__ here +if sys.platform == "win32": + if sys.version_info >= (3, 14): + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "_DefaultEventLoopPolicy", + "_WindowsSelectorEventLoopPolicy", + "_WindowsProactorEventLoopPolicy", + "EventLoop", + ) + elif sys.version_info >= (3, 13): + # 3.13 added `EventLoop`. + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", + "EventLoop", + ) + else: + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", + ) + + NULL: Final = 0 + INFINITE: Final = 0xFFFFFFFF + ERROR_CONNECTION_REFUSED: Final = 1225 + ERROR_CONNECTION_ABORTED: Final = 1236 + CONNECT_PIPE_INIT_DELAY: float + CONNECT_PIPE_MAX_DELAY: float + + class PipeServer: + def __init__(self, address: str) -> None: ... + def __del__(self) -> None: ... + def closed(self) -> bool: ... + def close(self) -> None: ... + + class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + + class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + def __init__(self, proactor: IocpProactor | None = None) -> None: ... + async def create_pipe_connection( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... + async def start_serving_pipe( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> list[PipeServer]: ... + + class IocpProactor: + def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ... + def __del__(self) -> None: ... + def set_loop(self, loop: events.AbstractEventLoop) -> None: ... + def select(self, timeout: int | None = None) -> list[futures.Future[Any]]: ... + def recv(self, conn: socket.socket, nbytes: int, flags: int = 0) -> futures.Future[bytes]: ... + def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ... + def recvfrom( + self, conn: socket.socket, nbytes: int, flags: int = 0 + ) -> futures.Future[tuple[bytes, socket._RetAddress]]: ... + def sendto( + self, conn: socket.socket, buf: ReadableBuffer, flags: int = 0, addr: socket._Address | None = None + ) -> futures.Future[int]: ... + def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ... + def accept(self, listener: socket.socket) -> futures.Future[Any]: ... + def connect( + self, + conn: socket.socket, + address: tuple[Incomplete, Incomplete] | tuple[Incomplete, Incomplete, Incomplete, Incomplete], + ) -> futures.Future[Any]: ... + def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... + def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... + async def connect_pipe(self, address: str) -> windows_utils.PipeHandle: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = None) -> bool: ... + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def recvfrom_into( + self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0 + ) -> futures.Future[tuple[int, socket._RetAddress]]: ... + + SelectorEventLoop = _WindowsSelectorEventLoop + + if sys.version_info >= (3, 14): + class _WindowsSelectorEventLoopPolicy(events._BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + + class _WindowsProactorEventLoopPolicy(events._BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[ProactorEventLoop]] + + else: + class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... + + class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[ProactorEventLoop]] + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... + + if sys.version_info >= (3, 14): + _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy + else: + DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy + if sys.version_info >= (3, 13): + EventLoop = ProactorEventLoop diff --git a/stdlib/asyncio/windows_utils.pyi b/stdlib/asyncio/windows_utils.pyi new file mode 100644 index 000000000000..5cedd61b5f4a --- /dev/null +++ b/stdlib/asyncio/windows_utils.pyi @@ -0,0 +1,49 @@ +import subprocess +import sys +from collections.abc import Callable +from types import TracebackType +from typing import Any, AnyStr, Final +from typing_extensions import Self + +if sys.platform == "win32": + __all__ = ("pipe", "Popen", "PIPE", "PipeHandle") + + BUFSIZE: Final = 8192 + PIPE: Final = subprocess.PIPE + STDOUT: Final = subprocess.STDOUT + def pipe(*, duplex: bool = False, overlapped: tuple[bool, bool] = (True, True), bufsize: int = 8192) -> tuple[int, int]: ... + + class PipeHandle: + def __init__(self, handle: int) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + @property + def handle(self) -> int: ... + def fileno(self) -> int: ... + def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ... + + class Popen(subprocess.Popen[AnyStr]): + stdin: PipeHandle | None # type: ignore[assignment] + stdout: PipeHandle | None # type: ignore[assignment] + stderr: PipeHandle | None # type: ignore[assignment] + # For simplicity we omit the full overloaded __new__ signature of + # subprocess.Popen. The arguments are mostly the same, but + # subprocess.Popen takes other positional-or-keyword arguments before + # stdin. + def __new__( + cls, + args: subprocess._CMD, + stdin: subprocess._FILE | None = None, + stdout: subprocess._FILE | None = None, + stderr: subprocess._FILE | None = None, + **kwds: Any, + ) -> Self: ... + def __init__( + self, + args: subprocess._CMD, + stdin: subprocess._FILE | None = None, + stdout: subprocess._FILE | None = None, + stderr: subprocess._FILE | None = None, + **kwds: Any, + ) -> None: ... diff --git a/stdlib/asyncore.pyi b/stdlib/asyncore.pyi new file mode 100644 index 000000000000..96f9f637c733 --- /dev/null +++ b/stdlib/asyncore.pyi @@ -0,0 +1,91 @@ +import sys +from _typeshed import FileDescriptorLike, ReadableBuffer +from socket import socket +from typing import Any, TypeAlias, overload + +# cyclic dependence with asynchat +_MapType: TypeAlias = dict[int, Any] +_Socket: TypeAlias = socket + +socket_map: _MapType # undocumented + +class ExitNow(Exception): ... + +def read(obj: Any) -> None: ... +def write(obj: Any) -> None: ... +def readwrite(obj: Any, flags: int) -> None: ... +def poll(timeout: float = 0.0, map: _MapType | None = None) -> None: ... +def poll2(timeout: float = 0.0, map: _MapType | None = None) -> None: ... + +poll3 = poll2 + +def loop(timeout: float = 30.0, use_poll: bool = False, map: _MapType | None = None, count: int | None = None) -> None: ... + +# Not really subclass of socket.socket; it's only delegation. +# It is not covariant to it. +class dispatcher: + debug: bool + connected: bool + accepting: bool + connecting: bool + closing: bool + ignore_log_types: frozenset[str] + socket: _Socket | None + def __init__(self, sock: _Socket | None = None, map: _MapType | None = None) -> None: ... + def add_channel(self, map: _MapType | None = None) -> None: ... + def del_channel(self, map: _MapType | None = None) -> None: ... + def create_socket(self, family: int = ..., type: int = ...) -> None: ... + def set_socket(self, sock: _Socket, map: _MapType | None = None) -> None: ... + def set_reuse_addr(self) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def listen(self, num: int) -> None: ... + def bind(self, addr: tuple[Any, ...] | str) -> None: ... + def connect(self, address: tuple[Any, ...] | str) -> None: ... + def accept(self) -> tuple[_Socket, Any] | None: ... + def send(self, data: ReadableBuffer) -> int: ... + def recv(self, buffer_size: int) -> bytes: ... + def close(self) -> None: ... + def log(self, message: Any) -> None: ... + def log_info(self, message: Any, type: str = "info") -> None: ... + def handle_read_event(self) -> None: ... + def handle_connect_event(self) -> None: ... + def handle_write_event(self) -> None: ... + def handle_expt_event(self) -> None: ... + def handle_error(self) -> None: ... + def handle_expt(self) -> None: ... + def handle_read(self) -> None: ... + def handle_write(self) -> None: ... + def handle_connect(self) -> None: ... + def handle_accept(self) -> None: ... + def handle_close(self) -> None: ... + +class dispatcher_with_send(dispatcher): + def initiate_send(self) -> None: ... + # incompatible signature: + # def send(self, data: bytes) -> int | None: ... + +def compact_traceback() -> tuple[tuple[str, str, str], type, type, str]: ... +def close_all(map: _MapType | None = None, ignore_all: bool = False) -> None: ... + +if sys.platform != "win32": + class file_wrapper: + fd: int + def __init__(self, fd: int) -> None: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + + @overload + def getsockopt(self, level: int, optname: int, buflen: None = None) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + + def read(self, bufsize: int, flags: int = ...) -> bytes: ... + def write(self, data: bytes, flags: int = ...) -> int: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def __del__(self) -> None: ... + + class file_dispatcher(dispatcher): + def __init__(self, fd: FileDescriptorLike, map: _MapType | None = None) -> None: ... + def set_file(self, fd: int) -> None: ... diff --git a/stdlib/atexit.pyi b/stdlib/atexit.pyi new file mode 100644 index 000000000000..9177d80169be --- /dev/null +++ b/stdlib/atexit.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +def _clear() -> None: ... +def _ncallbacks() -> int: ... +def _run_exitfuncs() -> None: ... +def register(func: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ... +def unregister(func: Callable[..., object], /) -> None: ... diff --git a/stdlib/audioop.pyi b/stdlib/audioop.pyi new file mode 100644 index 000000000000..a7d5e8adb7a5 --- /dev/null +++ b/stdlib/audioop.pyi @@ -0,0 +1,44 @@ +from typing import TypeAlias +from typing_extensions import Buffer + +_AdpcmState: TypeAlias = tuple[int, int] +_RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] + +class error(Exception): ... + +def add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: ... +def adpcm2lin(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def alaw2lin(fragment: Buffer, width: int, /) -> bytes: ... +def avg(fragment: Buffer, width: int, /) -> int: ... +def avgpp(fragment: Buffer, width: int, /) -> int: ... +def bias(fragment: Buffer, width: int, bias: int, /) -> bytes: ... +def byteswap(fragment: Buffer, width: int, /) -> bytes: ... +def cross(fragment: Buffer, width: int, /) -> int: ... +def findfactor(fragment: Buffer, reference: Buffer, /) -> float: ... +def findfit(fragment: Buffer, reference: Buffer, /) -> tuple[int, float]: ... +def findmax(fragment: Buffer, length: int, /) -> int: ... +def getsample(fragment: Buffer, width: int, index: int, /) -> int: ... +def lin2adpcm(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ... +def lin2alaw(fragment: Buffer, width: int, /) -> bytes: ... +def lin2lin(fragment: Buffer, width: int, newwidth: int, /) -> bytes: ... +def lin2ulaw(fragment: Buffer, width: int, /) -> bytes: ... +def max(fragment: Buffer, width: int, /) -> int: ... +def maxpp(fragment: Buffer, width: int, /) -> int: ... +def minmax(fragment: Buffer, width: int, /) -> tuple[int, int]: ... +def mul(fragment: Buffer, width: int, factor: float, /) -> bytes: ... +def ratecv( + fragment: Buffer, + width: int, + nchannels: int, + inrate: int, + outrate: int, + state: _RatecvState | None, + weightA: int = 1, + weightB: int = 0, + /, +) -> tuple[bytes, _RatecvState]: ... +def reverse(fragment: Buffer, width: int, /) -> bytes: ... +def rms(fragment: Buffer, width: int, /) -> int: ... +def tomono(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def tostereo(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ... +def ulaw2lin(fragment: Buffer, width: int, /) -> bytes: ... diff --git a/stdlib/base64.pyi b/stdlib/base64.pyi new file mode 100644 index 000000000000..dd4782142852 --- /dev/null +++ b/stdlib/base64.pyi @@ -0,0 +1,124 @@ +import sys +from _typeshed import ReadableBuffer, SupportsNoArgReadline, SupportsRead, SupportsWrite + +__all__ = [ + "encode", + "decode", + "encodebytes", + "decodebytes", + "b64encode", + "b64decode", + "b32encode", + "b32decode", + "b16encode", + "b16decode", + "b32hexencode", + "b32hexdecode", + "b85encode", + "b85decode", + "a85encode", + "a85decode", + "standard_b64encode", + "standard_b64decode", + "urlsafe_b64encode", + "urlsafe_b64decode", +] + +if sys.version_info >= (3, 13): + __all__ += ["z85decode", "z85encode"] + +if sys.version_info >= (3, 15): + def b64encode( + s: ReadableBuffer, altchars: ReadableBuffer | None = None, *, padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b64decode( + s: str | ReadableBuffer, + altchars: str | ReadableBuffer | None = None, + validate: bool = ..., + *, + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + +else: + def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ... + def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: ... + +def standard_b64encode(s: ReadableBuffer) -> bytes: ... +def standard_b64decode(s: str | ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 15): + def urlsafe_b64encode(s: ReadableBuffer, *, padded: bool = True) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer, *, padded: bool = False) -> bytes: ... + def b32encode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32decode( + s: str | ReadableBuffer, + casefold: bool = False, + map01: str | ReadableBuffer | None = None, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b16encode(s: ReadableBuffer, *, wrapcol: int = 0) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + +else: + def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: ... + def b32encode(s: ReadableBuffer) -> bytes: ... + def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: ... + def b16encode(s: ReadableBuffer) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... + +if sys.version_info >= (3, 15): + def b32hexencode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32hexdecode( + s: str | ReadableBuffer, + casefold: bool = False, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + +else: + def b32hexencode(s: ReadableBuffer) -> bytes: ... + def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... + +def a85encode( + b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False +) -> bytes: ... + +if sys.version_info >= (3, 15): + def a85decode( + b: str | ReadableBuffer, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: bytearray | bytes = b" \t\n\r\x0b", + canonical: bool = False, + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def b85decode(b: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + +else: + def a85decode( + b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: ... + def b85decode(b: str | ReadableBuffer) -> bytes: ... + +def decode(input: SupportsNoArgReadline[bytes], output: SupportsWrite[bytes]) -> None: ... +def encode(input: SupportsRead[bytes], output: SupportsWrite[bytes]) -> None: ... +def encodebytes(s: ReadableBuffer) -> bytes: ... +def decodebytes(s: ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + def z85encode(s: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def z85decode(s: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + else: + def z85encode(s: ReadableBuffer) -> bytes: ... + def z85decode(s: str | ReadableBuffer) -> bytes: ... diff --git a/stdlib/bdb.pyi b/stdlib/bdb.pyi new file mode 100644 index 000000000000..c2c45e2684b4 --- /dev/null +++ b/stdlib/bdb.pyi @@ -0,0 +1,139 @@ +import sys +from _typeshed import ExcInfo, ReadableBuffer, TraceFunction, Unused +from collections.abc import Callable, Iterable, Iterator, Mapping +from contextlib import contextmanager +from types import CodeType, FrameType, TracebackType +from typing import IO, Any, Final, Literal, ParamSpec, SupportsInt, TypeAlias, TypeVar + +__all__ = ["BdbQuit", "Bdb", "Breakpoint"] + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_Backend: TypeAlias = Literal["settrace", "monitoring"] + +# A union of code-object flags at runtime. +# The exact values of code-object flags are implementation details, +# so we don't include the value of this constant in the stubs. +GENERATOR_AND_COROUTINE_FLAGS: Final[int] + +class BdbQuit(Exception): ... + +class Bdb: + skip: set[str] | None + breaks: dict[str, list[int]] + fncache: dict[str, str] + frame_returning: FrameType | None + botframe: FrameType | None + quitting: bool + stopframe: FrameType | None + returnframe: FrameType | None + stoplineno: int + if sys.version_info >= (3, 14): + backend: _Backend + def __init__(self, skip: Iterable[str] | None = None, backend: _Backend = "settrace") -> None: ... + else: + def __init__(self, skip: Iterable[str] | None = None) -> None: ... + + def canonic(self, filename: str) -> str: ... + def reset(self) -> None: ... + if sys.version_info >= (3, 12): + @contextmanager + def set_enterframe(self, frame: FrameType) -> Iterator[None]: ... + + def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> TraceFunction: ... + def dispatch_line(self, frame: FrameType) -> TraceFunction: ... + def dispatch_call(self, frame: FrameType, arg: None) -> TraceFunction: ... + def dispatch_return(self, frame: FrameType, arg: Any) -> TraceFunction: ... + def dispatch_exception(self, frame: FrameType, arg: ExcInfo) -> TraceFunction: ... + if sys.version_info >= (3, 13): + def dispatch_opcode(self, frame: FrameType, arg: Unused) -> Callable[[FrameType, str, Any], TraceFunction]: ... + + def is_skipped_module(self, module_name: str) -> bool: ... + def stop_here(self, frame: FrameType) -> bool: ... + def break_here(self, frame: FrameType) -> bool: ... + def do_clear(self, arg: Any) -> bool | None: ... + def break_anywhere(self, frame: FrameType) -> bool: ... + def user_call(self, frame: FrameType, argument_list: None) -> None: ... + def user_line(self, frame: FrameType) -> None: ... + def user_return(self, frame: FrameType, return_value: Any) -> None: ... + def user_exception(self, frame: FrameType, exc_info: ExcInfo) -> None: ... + def set_until(self, frame: FrameType, lineno: int | None = None) -> None: ... + if sys.version_info >= (3, 13): + def user_opcode(self, frame: FrameType) -> None: ... # undocumented + + def set_step(self) -> None: ... + if sys.version_info >= (3, 13): + def set_stepinstr(self) -> None: ... # undocumented + + def set_next(self, frame: FrameType) -> None: ... + def set_return(self, frame: FrameType) -> None: ... + def set_trace(self, frame: FrameType | None = None) -> None: ... + def set_continue(self) -> None: ... + def set_quit(self) -> None: ... + def set_break( + self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None + ) -> str | None: ... + def clear_break(self, filename: str, lineno: int) -> str | None: ... + def clear_bpbynumber(self, arg: SupportsInt) -> str | None: ... + def clear_all_file_breaks(self, filename: str) -> str | None: ... + def clear_all_breaks(self) -> str | None: ... + def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... + def get_break(self, filename: str, lineno: int) -> bool: ... + def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: ... + def get_file_breaks(self, filename: str) -> list[int]: ... + def get_all_breaks(self) -> dict[str, list[int]]: ... + def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ... + def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = ": ") -> str: ... + def run( # matches `builtins.exec` + self, + cmd: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> None: ... + def runctx( # matches `builtins.exec` + self, cmd: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, object] | None + ) -> None: ... + def runeval( # matches `builtins.eval` + self, + expr: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... + if sys.version_info >= (3, 14): + def start_trace(self) -> None: ... + def stop_trace(self) -> None: ... + def disable_current_event(self) -> None: ... + def restart_events(self) -> None: ... + +class Breakpoint: + next: int + bplist: dict[tuple[str, int], list[Breakpoint]] + bpbynumber: list[Breakpoint | None] + + funcname: str | None + func_first_executable_line: int | None + file: str + line: int + temporary: bool + cond: str | None + enabled: bool + ignore: int + hits: int + number: int + def __init__( + self, file: str, line: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None + ) -> None: ... + if sys.version_info >= (3, 11): + @staticmethod + def clearBreakpoints() -> None: ... + + def deleteMe(self) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def bpprint(self, out: IO[str] | None = None) -> None: ... + def bpformat(self) -> str: ... + +def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... +def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... +def set_trace() -> None: ... diff --git a/stdlib/binascii.pyi b/stdlib/binascii.pyi new file mode 100644 index 000000000000..6840c6883811 --- /dev/null +++ b/stdlib/binascii.pyi @@ -0,0 +1,102 @@ +import sys +from _typeshed import ReadableBuffer +from typing import TypeAlias +from typing_extensions import deprecated + +# Many functions in binascii accept buffer objects +# or ASCII-only strings. +_AsciiBuffer: TypeAlias = str | ReadableBuffer + +def a2b_uu(data: _AsciiBuffer, /) -> bytes: ... +def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: ... + +if sys.version_info >= (3, 15): + ASCII85_ALPHABET: bytes + BINHEX_ALPHABET: bytes + CRYPT_ALPHABET: bytes + UU_ALPHABET: bytes + BASE64_ALPHABET: bytes + URLSAFE_BASE64_ALPHABET: bytes + BASE32_ALPHABET: bytes + BASE32HEX_ALPHABET: bytes + BASE85_ALPHABET: bytes + Z85_ALPHABET: bytes + def a2b_base64( + data: _AsciiBuffer, + /, + *, + strict_mode: bool = False, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + def b2a_base64( + data: ReadableBuffer, /, *, newline: bool = True, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b2a_base32( + data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def a2b_base32( + data: _AsciiBuffer, + /, + *, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_ascii85( + data: ReadableBuffer, /, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False + ) -> bytes: ... + def a2b_ascii85( + data: _AsciiBuffer, + /, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_base85(data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., pad: bool = False, wrapcol: int = 0) -> bytes: ... + def a2b_base85( + data: _AsciiBuffer, /, *, alphabet: bytes = ..., ignorechars: ReadableBuffer = b"", canonical: bool = False + ) -> bytes: ... + +elif sys.version_info >= (3, 11): + def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: ... + +else: + def a2b_base64(data: _AsciiBuffer, /) -> bytes: ... + +if sys.version_info < (3, 15): + def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ... + +def a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: ... +def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: ... + +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def a2b_hqx(data: _AsciiBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def rledecode_hqx(data: ReadableBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def rlecode_hqx(data: ReadableBuffer, /) -> bytes: ... + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + def b2a_hqx(data: ReadableBuffer, /) -> bytes: ... + +def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: ... +def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: ... +def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... +def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... + +if sys.version_info >= (3, 15): + def a2b_hex(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + +else: + def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ... + +class Error(ValueError): ... +class Incomplete(Exception): ... diff --git a/stdlib/binhex.pyi b/stdlib/binhex.pyi new file mode 100644 index 000000000000..f309f4e026a5 --- /dev/null +++ b/stdlib/binhex.pyi @@ -0,0 +1,44 @@ +from _typeshed import SizedBuffer +from typing import IO, Any, Final, TypeAlias + +__all__ = ["binhex", "hexbin", "Error"] + +class Error(Exception): ... + +REASONABLY_LARGE: Final = 32768 +LINELEN: Final = 64 +RUNCHAR: Final = b"\x90" + +class FInfo: + Type: str + Creator: str + Flags: int + +_FileInfoTuple: TypeAlias = tuple[str, FInfo, int, int] +_FileHandleUnion: TypeAlias = str | IO[bytes] + +def getfileinfo(name: str) -> _FileInfoTuple: ... + +class openrsrc: + def __init__(self, *args: Any) -> None: ... + def read(self, *args: Any) -> bytes: ... + def write(self, *args: Any) -> None: ... + def close(self) -> None: ... + +class BinHex: + def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ... + def write(self, data: SizedBuffer) -> None: ... + def close_data(self) -> None: ... + def write_rsrc(self, data: SizedBuffer) -> None: ... + def close(self) -> None: ... + +def binhex(inp: str, out: str) -> None: ... + +class HexBin: + def __init__(self, ifp: _FileHandleUnion) -> None: ... + def read(self, *n: int) -> bytes: ... + def close_data(self) -> None: ... + def read_rsrc(self, *n: int) -> bytes: ... + def close(self) -> None: ... + +def hexbin(inp: str, out: str) -> None: ... diff --git a/stdlib/bisect.pyi b/stdlib/bisect.pyi new file mode 100644 index 000000000000..60dfc48d69bd --- /dev/null +++ b/stdlib/bisect.pyi @@ -0,0 +1,4 @@ +from _bisect import * + +bisect = bisect_right +insort = insort_right diff --git a/stdlib/builtins.pyi b/stdlib/builtins.pyi new file mode 100644 index 000000000000..3c549d97316c --- /dev/null +++ b/stdlib/builtins.pyi @@ -0,0 +1,2575 @@ +import _ast +import _sitebuiltins +import _typeshed +import sys +import types +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import ( + AnnotationForm, + ConvertibleToFloat, + ConvertibleToInt, + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + SupportsAdd, + SupportsAiter, + SupportsAnext, + SupportsDivMod, + SupportsFlush, + SupportsIter, + SupportsKeysAndGetItem, + SupportsLenAndGetItem, + SupportsNext, + SupportsRAdd, + SupportsRDivMod, + SupportsRichComparison, + SupportsRichComparisonT, + SupportsWrite, +) +from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from os import PathLike +from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType, UnionType + +# mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} +# are imported from collections.abc in builtins.pyi +from typing import ( # noqa: Y022,UP035 + IO, + Any, + BinaryIO, + ClassVar, + Concatenate, + Final, + Generic, + Mapping, + MutableMapping, + MutableSequence, + ParamSpec, + Protocol, + Sequence, + SupportsAbs, + SupportsBytes, + SupportsComplex, + SupportsFloat, + SupportsIndex, + TypeAlias, + TypeGuard, + TypeVar, + final, + overload, + type_check_only, +) + +# we can't import `Literal` from typing or mypy crashes: see #11247 +from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 + +if sys.version_info >= (3, 14): + from _typeshed import AnnotateFunc + +_T = TypeVar("_T") +_I = TypeVar("_I", default=int) +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) +_R_co = TypeVar("_R_co", covariant=True) +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_SupportsNextT_co = TypeVar("_SupportsNextT_co", bound=SupportsNext[Any], covariant=True) +_SupportsAnextT_co = TypeVar("_SupportsAnextT_co", bound=SupportsAnext[Any], covariant=True) +_AwaitableT = TypeVar("_AwaitableT", bound=Awaitable[Any]) +_AwaitableT_co = TypeVar("_AwaitableT_co", bound=Awaitable[Any], covariant=True) +_P = ParamSpec("_P") + +# Type variables for slice +_StartT_co = TypeVar("_StartT_co", covariant=True, default=Any) # slice -> slice[Any, Any, Any] +_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] +# NOTE: step could differ from start and stop, (e.g. datetime/timedelta)l +# the default (start|stop) is chosen to cater to the most common case of int/index slices. +# FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop) +_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] + +@disjoint_base +class object: + __doc__: str | None + __dict__: dict[str, Any] + __module__: str + __annotations__: dict[str, Any] + + @property + def __class__(self) -> type[Self]: ... + @__class__.setter + def __class__(self, type: type[Self], /) -> None: ... + + def __init__(self) -> None: ... + def __new__(cls) -> Self: ... + # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers. + # Overriding them in subclasses has different semantics, even if the override has an identical signature. + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 + def __hash__(self) -> int: ... + def __format__(self, format_spec: str, /) -> str: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __sizeof__(self) -> int: ... + # return type of pickle methods is rather hard to express in the current type system + # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ... + if sys.version_info >= (3, 11): + def __getstate__(self) -> object: ... + + def __dir__(self) -> Iterable[str]: ... + def __init_subclass__(cls) -> None: ... + @classmethod + def __subclasshook__(cls, subclass: type, /) -> bool: ... + +@disjoint_base +class staticmethod(Generic[_P, _R_co]): + __name__: str + __qualname__: str + @property + def __func__(self) -> Callable[_P, _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self, f: Callable[_P, _R_co], /) -> None: ... + + @overload + def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: ... + @overload + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... + + @property + def __wrapped__(self) -> Callable[_P, _R_co]: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + __annotate__: AnnotateFunc | None + +@disjoint_base +class classmethod(Generic[_T, _P, _R_co]): + __name__: str + __qualname__: str + @property + def __func__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ... + + @overload + def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... + @overload + def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ... + + @property + def __wrapped__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + __annotate__: AnnotateFunc | None + +@disjoint_base +class type: + # object.__base__ is None. Otherwise, it would be a type. + @property + def __base__(self) -> type | None: ... + __bases__: tuple[type, ...] + @property + def __basicsize__(self) -> int: ... + # type.__dict__ is read-only at runtime, but that can't be expressed currently. + # See https://github.com/python/typeshed/issues/11033 for a discussion. + __dict__: Final[types.MappingProxyType[str, Any]] # type: ignore[assignment] + @property + def __dictoffset__(self) -> int: ... + @property + def __flags__(self) -> int: ... + @property + def __itemsize__(self) -> int: ... + __module__: str + @property + def __mro__(self) -> tuple[type, ...]: ... + __name__: str + __qualname__: str + @property + def __text_signature__(self) -> str | None: ... + @property + def __weakrefoffset__(self) -> int: ... + + @overload + def __init__(self, o: object, /) -> None: ... + @overload + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + + @overload + def __new__(cls, o: object, /) -> type: ... + @overload + def __new__( + cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any + ) -> _typeshed.Self: ... + + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ... + # Note: the documentation doesn't specify what the return type is, the standard + # implementation seems to be returning a list. + def mro(self) -> list[type]: ... + def __instancecheck__(self, instance: Any, /) -> bool: ... + def __subclasscheck__(self, subclass: type, /) -> bool: ... + @classmethod + def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ... + # `int | str` produces an instance of `UnionType`, but `int | int` produces an instance of `type`, + # and `abc.ABC | abc.ABC` produces an instance of `abc.ABCMeta`. + def __or__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + def __ror__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + +@disjoint_base +class super: + @overload + def __init__(self, t: Any, obj: Any, /) -> None: ... + @overload + def __init__(self, t: Any, /) -> None: ... + @overload + def __init__(self) -> None: ... + +_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + +@disjoint_base +class int: + @overload + def __new__(cls, x: ConvertibleToInt = 0, /) -> Self: ... + @overload + def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ... + + def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... + @property + def real(self) -> int: ... + @property + def imag(self) -> Literal[0]: ... + @property + def numerator(self) -> int: ... + @property + def denominator(self) -> Literal[1]: ... + def conjugate(self) -> int: ... + def bit_length(self) -> int: ... + def bit_count(self) -> int: ... + + if sys.version_info >= (3, 11): + def to_bytes( + self, length: SupportsIndex = 1, byteorder: Literal["little", "big"] = "big", *, signed: bool = False + ) -> bytes: ... + @classmethod + def from_bytes( + cls, + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"] = "big", + *, + signed: bool = False, + ) -> Self: ... + + else: + def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: ... + @classmethod + def from_bytes( + cls, + bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer, + byteorder: Literal["little", "big"], + *, + signed: bool = False, + ) -> Self: ... + + if sys.version_info >= (3, 12): + def is_integer(self) -> Literal[True]: ... + + def __add__(self, value: int, /) -> int: ... + def __sub__(self, value: int, /) -> int: ... + def __mul__(self, value: int, /) -> int: ... + def __floordiv__(self, value: int, /) -> int: ... + def __truediv__(self, value: int, /) -> float: ... + def __mod__(self, value: int, /) -> int: ... + def __divmod__(self, value: int, /) -> tuple[int, int]: ... + def __radd__(self, value: int, /) -> int: ... + def __rsub__(self, value: int, /) -> int: ... + def __rmul__(self, value: int, /) -> int: ... + def __rfloordiv__(self, value: int, /) -> int: ... + def __rtruediv__(self, value: int, /) -> float: ... + def __rmod__(self, value: int, /) -> int: ... + def __rdivmod__(self, value: int, /) -> tuple[int, int]: ... + + @overload + def __pow__(self, x: Literal[0], /) -> Literal[1]: ... + @overload + def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ... + @overload + def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ... + @overload + def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ... + # positive __value -> int; negative __value -> float + # return type must be Any as `int | float` causes too many false-positive errors + @overload + def __pow__(self, value: int, mod: None = None, /) -> Any: ... + @overload + def __pow__(self, value: int, mod: int, /) -> int: ... + + def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ... + def __and__(self, value: int, /) -> int: ... + def __or__(self, value: int, /) -> int: ... + def __xor__(self, value: int, /) -> int: ... + def __lshift__(self, value: int, /) -> int: ... + def __rshift__(self, value: int, /) -> int: ... + def __rand__(self, value: int, /) -> int: ... + def __ror__(self, value: int, /) -> int: ... + def __rxor__(self, value: int, /) -> int: ... + def __rlshift__(self, value: int, /) -> int: ... + def __rrshift__(self, value: int, /) -> int: ... + def __neg__(self) -> int: ... + def __pos__(self) -> int: ... + def __invert__(self) -> int: ... + def __trunc__(self) -> int: ... + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + if sys.version_info >= (3, 14): + def __round__(self, ndigits: SupportsIndex | None = None, /) -> int: ... + + else: + def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ... + + def __getnewargs__(self) -> tuple[int]: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: int, /) -> bool: ... + def __le__(self, value: int, /) -> bool: ... + def __gt__(self, value: int, /) -> bool: ... + def __ge__(self, value: int, /) -> bool: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __abs__(self) -> int: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + def __index__(self) -> int: ... + def __format__(self, format_spec: str, /) -> str: ... + +@disjoint_base +class float: + def __new__(cls, x: ConvertibleToFloat = 0, /) -> Self: ... + def as_integer_ratio(self) -> tuple[int, int]: ... + def hex(self) -> str: ... + def is_integer(self) -> bool: ... + @classmethod + def fromhex(cls, string: str, /) -> Self: ... + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> float: ... + def __add__(self, value: float, /) -> float: ... + def __sub__(self, value: float, /) -> float: ... + def __mul__(self, value: float, /) -> float: ... + def __floordiv__(self, value: float, /) -> float: ... + def __truediv__(self, value: float, /) -> float: ... + def __mod__(self, value: float, /) -> float: ... + def __divmod__(self, value: float, /) -> tuple[float, float]: ... + + @overload + def __pow__(self, value: int, mod: None = None, /) -> float: ... + # positive __value -> float; negative __value -> complex + # return type must be Any as `float | complex` causes too many false-positive errors + @overload + def __pow__(self, value: float, mod: None = None, /) -> Any: ... + + def __radd__(self, value: float, /) -> float: ... + def __rsub__(self, value: float, /) -> float: ... + def __rmul__(self, value: float, /) -> float: ... + def __rfloordiv__(self, value: float, /) -> float: ... + def __rtruediv__(self, value: float, /) -> float: ... + def __rmod__(self, value: float, /) -> float: ... + def __rdivmod__(self, value: float, /) -> tuple[float, float]: ... + + @overload + def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: ... + @overload + def __rpow__(self, value: _NegativeInteger, mod: None = None, /) -> complex: ... + # Returning `complex` for the general case gives too many false-positive errors. + @overload + def __rpow__(self, value: float, mod: None = None, /) -> Any: ... + + def __getnewargs__(self) -> tuple[float]: ... + def __trunc__(self) -> int: ... + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... + + @overload + def __round__(self, ndigits: None = None, /) -> int: ... + @overload + def __round__(self, ndigits: SupportsIndex, /) -> float: ... + + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: float, /) -> bool: ... + def __le__(self, value: float, /) -> bool: ... + def __gt__(self, value: float, /) -> bool: ... + def __ge__(self, value: float, /) -> bool: ... + def __neg__(self) -> float: ... + def __pos__(self) -> float: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + def __format__(self, format_spec: str, /) -> str: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: ... + +@disjoint_base +class complex: + # Python doesn't currently accept SupportsComplex for the second argument + @overload + def __new__( + cls, + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = 0, + imag: complex | SupportsFloat | SupportsIndex = 0, + ) -> Self: ... + @overload + def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... + + @property + def real(self) -> float: ... + @property + def imag(self) -> float: ... + def conjugate(self) -> complex: ... + def __add__(self, value: complex, /) -> complex: ... + def __sub__(self, value: complex, /) -> complex: ... + def __mul__(self, value: complex, /) -> complex: ... + def __pow__(self, value: complex, mod: None = None, /) -> complex: ... + def __truediv__(self, value: complex, /) -> complex: ... + def __radd__(self, value: complex, /) -> complex: ... + def __rsub__(self, value: complex, /) -> complex: ... + def __rmul__(self, value: complex, /) -> complex: ... + def __rpow__(self, value: complex, mod: None = None, /) -> complex: ... + def __rtruediv__(self, value: complex, /) -> complex: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __neg__(self) -> complex: ... + def __pos__(self) -> complex: ... + def __abs__(self) -> float: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + def __format__(self, format_spec: str, /) -> str: ... + if sys.version_info >= (3, 11): + def __complex__(self) -> complex: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: ... + +@type_check_only +class _FormatMapMapping(Protocol): + def __getitem__(self, key: str, /) -> Any: ... + +@type_check_only +class _TranslateTable(Protocol): + def __getitem__(self, key: int, /) -> str | int | None: ... + +@disjoint_base +class str(Sequence[str]): + @overload + def __new__(cls, object: object = "") -> Self: ... + @overload + def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... + + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload + def capitalize(self) -> str: ... # type: ignore[misc] + + @overload + def casefold(self: LiteralString) -> LiteralString: ... + @overload + def casefold(self) -> str: ... # type: ignore[misc] + + @overload + def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... + def endswith( + self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> bool: ... + + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + @overload + def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] + + def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload + def format(self, *args: object, **kwargs: object) -> str: ... + + def format_map(self, mapping: _FormatMapMapping, /) -> str: ... + def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isascii(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + + @overload + def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... + @overload + def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] + + @overload + def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload + def lower(self) -> str: ... # type: ignore[misc] + + @overload + def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + + if sys.version_info >= (3, 13): + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1 + ) -> LiteralString: ... + @overload + def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] + else: + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, / + ) -> LiteralString: ... + @overload + def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] + + @overload + def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... + @overload + def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] + + @overload + def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... + @overload + def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] + + def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + + @overload + def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload + def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + + @overload + def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload + def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + + @overload + def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload + def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + + @overload + def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... + @overload + def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] + + def startswith( + self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> bool: ... + + @overload + def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload + def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload + def swapcase(self) -> str: ... # type: ignore[misc] + + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload + def title(self) -> str: ... # type: ignore[misc] + + def translate(self, table: _TranslateTable, /) -> str: ... + + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload + def upper(self) -> str: ... # type: ignore[misc] + + @overload + def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... + @overload + def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] + + if sys.version_info >= (3, 15): + @staticmethod + @overload + def maketrans( + x: ( + dict[int, _T] + | dict[str, _T] + | dict[str | int, _T] + | frozendict[int, _T] + | frozendict[str, _T] + | frozendict[str | int, _T] + ), + /, + ) -> dict[int, _T]: ... + else: + @staticmethod + @overload + def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ... + + @staticmethod + @overload + def maketrans(x: str, y: str, /) -> dict[int, int]: ... + @staticmethod + @overload + def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... + + @overload + def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... + @overload + def __add__(self, value: str, /) -> str: ... # type: ignore[misc] + + # Incompatible with Sequence.__contains__ + def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: str, /) -> bool: ... + + @overload + def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ... + @overload + def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] + + def __gt__(self, value: str, /) -> bool: ... + def __hash__(self) -> int: ... + + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload + def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] + + def __le__(self, value: str, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, value: str, /) -> bool: ... + + @overload + def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... + @overload + def __mod__(self, value: Any, /) -> str: ... + + @overload + def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload + def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + + def __ne__(self, value: object, /) -> bool: ... + + @overload + def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload + def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + + def __getnewargs__(self) -> tuple[str]: ... + def __format__(self, format_spec: str, /) -> str: ... + +@disjoint_base +class bytes(Sequence[int]): + @overload + def __new__(cls, o: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, /) -> Self: ... + @overload + def __new__(cls, string: str, /, encoding: str, errors: str = "strict") -> Self: ... + @overload + def __new__(cls) -> Self: ... + + def capitalize(self) -> bytes: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytes: ... + def count( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... + def endswith( + self, + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ... + def find( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... + def index( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytes: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... + def lower(self) -> bytes: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytes: ... + + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... + + def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... + def rfind( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def rindex( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytes: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... + def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ... + def splitlines(self, keepends: bool = False) -> list[bytes]: ... + def startswith( + self, + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... + def swapcase(self) -> bytes: ... + def title(self) -> bytes: ... + def translate(self, table: ReadableBuffer | None, /, delete: ReadableBuffer = b"") -> bytes: ... + def upper(self) -> bytes: ... + def zfill(self, width: SupportsIndex, /) -> bytes: ... + + if sys.version_info >= (3, 14): + @classmethod + def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... + else: + @classmethod + def fromhex(cls, string: str, /) -> Self: ... + + @staticmethod + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __hash__(self) -> int: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> int: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + + def __add__(self, value: ReadableBuffer, /) -> bytes: ... + def __mul__(self, value: SupportsIndex, /) -> bytes: ... + def __rmul__(self, value: SupportsIndex, /) -> bytes: ... + def __mod__(self, value: Any, /) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: bytes, /) -> bool: ... + def __le__(self, value: bytes, /) -> bool: ... + def __gt__(self, value: bytes, /) -> bool: ... + def __ge__(self, value: bytes, /) -> bool: ... + def __getnewargs__(self) -> tuple[bytes]: ... + if sys.version_info >= (3, 11): + def __bytes__(self) -> bytes: ... + + def __buffer__(self, flags: int, /) -> memoryview: ... + +@disjoint_base +class bytearray(MutableSequence[int]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer, /) -> None: ... + @overload + def __init__(self, string: str, /, encoding: str, errors: str = "strict") -> None: ... + + def append(self, item: SupportsIndex, /) -> None: ... + def capitalize(self) -> bytearray: ... + def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytearray: ... + def count( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def copy(self) -> bytearray: ... + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: ... + def endswith( + self, + suffix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ... + def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: ... + def find( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... + def index( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: ... + def isalnum(self) -> bool: ... + def isalpha(self) -> bool: ... + def isascii(self) -> bool: ... + def isdigit(self) -> bool: ... + def islower(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytearray: ... + def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... + def lower(self) -> bytearray: ... + def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... + def pop(self, index: int = -1, /) -> int: ... + def remove(self, value: int, /) -> None: ... + def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytearray: ... + + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... + + def rfind( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def rindex( + self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / + ) -> int: ... + def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b" ", /) -> bytearray: ... + def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... + def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ... + def splitlines(self, keepends: bool = False) -> list[bytearray]: ... + def startswith( + self, + prefix: ReadableBuffer | tuple[ReadableBuffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: ... + def strip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ... + def swapcase(self) -> bytearray: ... + def title(self) -> bytearray: ... + def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytearray: ... + if sys.version_info >= (3, 15): + def take_bytes(self, n: int | None = None, /) -> bytes: ... + + def upper(self) -> bytearray: ... + def zfill(self, width: SupportsIndex, /) -> bytearray: ... + + if sys.version_info >= (3, 14): + @classmethod + def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... + else: + @classmethod + def fromhex(cls, string: str, /) -> Self: ... + + @staticmethod + def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[int]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + + @overload + def __getitem__(self, key: SupportsIndex, /) -> int: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytearray: ... + + @overload + def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[SupportsIndex] | bytes, /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + def __add__(self, value: ReadableBuffer, /) -> bytearray: ... + # The superclass wants us to accept Iterable[int], but that fails at runtime. + def __iadd__(self, value: ReadableBuffer, /) -> Self: ... # type: ignore[override] + def __mul__(self, value: SupportsIndex, /) -> bytearray: ... + def __rmul__(self, value: SupportsIndex, /) -> bytearray: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __mod__(self, value: Any, /) -> bytes: ... + # Incompatible with Sequence.__contains__ + def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __lt__(self, value: ReadableBuffer, /) -> bool: ... + def __le__(self, value: ReadableBuffer, /) -> bool: ... + def __gt__(self, value: ReadableBuffer, /) -> bool: ... + def __ge__(self, value: ReadableBuffer, /) -> bool: ... + def __alloc__(self) -> int: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 14): + def resize(self, size: int, /) -> None: ... + +_IntegerFormats: TypeAlias = Literal[ + "b", "B", "@b", "@B", "h", "H", "@h", "@H", "i", "I", "@i", "@I", "l", "L", "@l", "@L", "q", "Q", "@q", "@Q", "P", "@P" +] + +@final +class memoryview(Sequence[_I]): + @property + def format(self) -> str: ... + @property + def itemsize(self) -> int: ... + @property + def shape(self) -> tuple[int, ...] | None: ... + @property + def strides(self) -> tuple[int, ...] | None: ... + @property + def suboffsets(self) -> tuple[int, ...] | None: ... + @property + def readonly(self) -> bool: ... + @property + def ndim(self) -> int: ... + @property + def obj(self) -> ReadableBuffer: ... + @property + def c_contiguous(self) -> bool: ... + @property + def f_contiguous(self) -> bool: ... + @property + def contiguous(self) -> bool: ... + @property + def nbytes(self) -> int: ... + def __new__(cls, obj: ReadableBuffer) -> Self: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None, # noqa: PYI036 # This is the module declaring BaseException + exc_val: BaseException | None, + exc_tb: TracebackType | None, + /, + ) -> None: ... + + @overload + def cast(self, format: Literal["c", "@c"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bytes]: ... + @overload + def cast(self, format: Literal["f", "@f", "d", "@d"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[float]: ... + @overload + def cast(self, format: Literal["?"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bool]: ... + @overload + def cast(self, format: _IntegerFormats, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... + + @overload + def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> _I: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> memoryview[_I]: ... + + def __contains__(self, x: object, /) -> bool: ... + def __iter__(self) -> Iterator[_I]: ... + def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... + @overload + def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ... + + def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... + def tolist(self) -> list[int]: ... + def toreadonly(self) -> memoryview: ... + def release(self) -> None: ... + def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 14): + def index(self, value: object, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def count(self, value: object, /) -> int: ... + + else: + # These are inherited from the Sequence ABC, but don't actually exist on memoryview. + # See https://github.com/python/cpython/issues/125420 + index: ClassVar[None] # type: ignore[assignment] + count: ClassVar[None] # type: ignore[assignment] + + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class bool(int): + def __new__(cls, o: object = False, /) -> Self: ... + + # The following overloads could be represented more elegantly with a TypeVar("_B", bool, int), + # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). + @overload + def __and__(self, value: bool, /) -> bool: ... + @overload + def __and__(self, value: int, /) -> int: ... + + @overload + def __or__(self, value: bool, /) -> bool: ... + @overload + def __or__(self, value: int, /) -> int: ... + + @overload + def __xor__(self, value: bool, /) -> bool: ... + @overload + def __xor__(self, value: int, /) -> int: ... + + @overload + def __rand__(self, value: bool, /) -> bool: ... + @overload + def __rand__(self, value: int, /) -> int: ... + + @overload + def __ror__(self, value: bool, /) -> bool: ... + @overload + def __ror__(self, value: int, /) -> int: ... + + @overload + def __rxor__(self, value: bool, /) -> bool: ... + @overload + def __rxor__(self, value: int, /) -> int: ... + + def __getnewargs__(self) -> tuple[int]: ... + @deprecated("Will throw an error in Python 3.16. Use `not` for logical negation of bools instead.") + def __invert__(self) -> int: ... + +@final +class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): + @property + def start(self) -> _StartT_co: ... + @property + def step(self) -> _StepT_co: ... + @property + def stop(self) -> _StopT_co: ... + + # Note: __new__ overloads map `None` to `Any`, since users expect slice(x, None) + # to be compatible with slice(None, x). + # generic slice -------------------------------------------------------------------- + @overload + def __new__(cls, start: None, stop: None = None, step: None = None, /) -> slice[Any, Any, Any]: ... + # unary overloads ------------------------------------------------------------------ + @overload + def __new__(cls, stop: _T2, /) -> slice[Any, _T2, Any]: ... + # binary overloads ----------------------------------------------------------------- + @overload + def __new__(cls, start: _T1, stop: None, step: None = None, /) -> slice[_T1, Any, Any]: ... + @overload + def __new__(cls, start: None, stop: _T2, step: None = None, /) -> slice[Any, _T2, Any]: ... + @overload + def __new__(cls, start: _T1, stop: _T2, step: None = None, /) -> slice[_T1, _T2, Any]: ... + # ternary overloads ---------------------------------------------------------------- + @overload + def __new__(cls, start: None, stop: None, step: _T3, /) -> slice[Any, Any, _T3]: ... + @overload + def __new__(cls, start: _T1, stop: None, step: _T3, /) -> slice[_T1, Any, _T3]: ... + @overload + def __new__(cls, start: None, stop: _T2, step: _T3, /) -> slice[Any, _T2, _T3]: ... + @overload + def __new__(cls, start: _T1, stop: _T2, step: _T3, /) -> slice[_T1, _T2, _T3]: ... + + def __eq__(self, value: object, /) -> bool: ... + if sys.version_info >= (3, 12): + def __hash__(self) -> int: ... + + else: + __hash__: ClassVar[None] # type: ignore[assignment] + + def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ... + if sys.version_info >= (3, 15): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class tuple(Sequence[_T_co]): + def __new__(cls, iterable: Iterable[_T_co] = (), /) -> Self: ... + def __len__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> _T_co: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[_T_co, ...]: ... + + def __iter__(self) -> Iterator[_T_co]: ... + def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __le__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + + @overload + def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ... + @overload + def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ... + + def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... + def count(self, value: Any, /) -> int: ... + def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# Doesn't exist at runtime, but deleting this breaks mypy and pyright. See: +# https://github.com/python/typeshed/issues/7580 +# https://github.com/python/mypy/issues/8240 +# Obsolete, use types.FunctionType instead. +@final +@type_check_only +class function: + # Make sure this class definition stays roughly in line with `types.FunctionType` + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... + __code__: CodeType + __defaults__: tuple[Any, ...] | None + __dict__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... + __name__: str + __qualname__: str + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + __kwdefaults__: dict[str, Any] | None + @property + def __builtins__(self) -> dict[str, Any]: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] + + __module__: str + if sys.version_info >= (3, 13): + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + kwdefaults: dict[str, object] | None = None, + ) -> Self: ... + + else: + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + ) -> Self: ... + + # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. + def __get__(self, instance: object, owner: type | None = None, /) -> Any: ... + +@disjoint_base +class list(MutableSequence[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], /) -> None: ... + + def copy(self) -> list[_T]: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = -1, /) -> _T: ... + # Signature of `list.index` should be kept in line with `collections.UserList.index()` + # and multiprocessing.managers.ListProxy.index() + def index(self, value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... + + # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` + # and multiprocessing.managers.ListProxy.sort() + # + # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance + @overload + def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + + @overload + def __getitem__(self, i: SupportsIndex, /) -> _T: ... + @overload + def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + + @overload + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[_T], /) -> None: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + + # Overloading looks unnecessary, but is needed to work around complex mypy problems + @overload + def __add__(self, value: list[_T], /) -> list[_T]: ... + @overload + def __add__(self, value: list[_S], /) -> list[_S | _T]: ... + + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[misc] + def __mul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __contains__(self, key: object, /) -> bool: ... + def __reversed__(self) -> Iterator[_T]: ... + def __gt__(self, value: list[_T], /) -> bool: ... + def __ge__(self, value: list[_T], /) -> bool: ... + def __lt__(self, value: list[_T], /) -> bool: ... + def __le__(self, value: list[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class dict(MutableMapping[_KT, _VT]): + # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics + # Also multiprocessing.managers.SyncManager.dict() + @overload + def __init__(self, /) -> None: ... + @overload + def __init__(self: dict[str, _VT], /, **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + @overload + def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + map: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: dict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + # Next two overloads are for dict(string.split(sep) for string in iterable) + # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error + @overload + def __init__(self: dict[str, str], iterable: Iterable[list[str]], /) -> None: ... + @overload + def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ... + def copy(self) -> dict[_KT, _VT]: ... + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + def items(self) -> dict_items[_KT, _VT]: ... + + # Signature of `dict.fromkeys` should be kept identical to + # `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` + # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + + # Positional-only in dict, but not in MutableMapping + @overload # type: ignore[override] + def get(self, key: _KT, default: None = None, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __eq__(self, value: object, /) -> bool: ... + def __reversed__(self) -> Iterator[_KT]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 15): + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + else: + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + # dict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... + @overload + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... + +if sys.version_info >= (3, 15): + @disjoint_base + class frozendict(Mapping[_KT, _VT]): + @overload + def __new__(cls, /) -> frozendict[Any, Any]: ... + @overload + def __new__(cls: type[frozendict[str, _VT]], /, **kwargs: _VT) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, map: SupportsKeysAndGetItem[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, iterable: Iterable[tuple[_KT, _VT]], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + + def copy(self) -> frozendict[_KT, _VT]: ... + + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> frozendict[_T, Any | None]: ... + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> frozendict[_T, _S]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, default: None = None, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + def items(self) -> dict_items[_KT, _VT]: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __reversed__(self) -> Iterator[_KT]: ... + def __iter__(self) -> Iterator[_KT]: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + +@disjoint_base +class set(MutableSet[_T]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], /) -> None: ... + + def add(self, element: _T, /) -> None: ... + def copy(self) -> set[_T]: ... + def difference(self, *s: Iterable[object]) -> set[_T]: ... + def difference_update(self, *s: Iterable[object]) -> None: ... + def discard(self, element: object, /) -> None: ... + def intersection(self, *s: Iterable[object]) -> set[_T]: ... + def intersection_update(self, *s: Iterable[object]) -> None: ... + def isdisjoint(self, s: Iterable[object], /) -> bool: ... + def issubset(self, s: Iterable[object], /) -> bool: ... + def issuperset(self, s: Iterable[object], /) -> bool: ... + def remove(self, element: _T, /) -> None: ... + def symmetric_difference(self, s: Iterable[_S], /) -> set[_T | _S]: ... + def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ... + def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object, /) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __sub__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class frozenset(AbstractSet[_T_co]): + @overload + def __new__(cls) -> Self: ... + @overload + def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ... + + def copy(self) -> frozenset[_T_co]: ... + def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... + def isdisjoint(self, s: Iterable[object], /) -> bool: ... + def issubset(self, s: Iterable[object], /) -> bool: ... + def issuperset(self, s: Iterable[object], /) -> bool: ... + def symmetric_difference(self, s: Iterable[_S], /) -> frozenset[_T_co | _S]: ... + def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: ... + def __len__(self) -> int: ... + def __contains__(self, o: object, /) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __and__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + def __sub__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class enumerate(Generic[_T]): + def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[int, _T]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class range(Sequence[int]): + @property + def start(self) -> int: ... + @property + def stop(self) -> int: ... + @property + def step(self) -> int: ... + + @overload + def __new__(cls, stop: SupportsIndex, /) -> Self: ... + @overload + def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = 1, /) -> Self: ... + + def count(self, value: int, /) -> int: ... + def index(self, value: int, /) -> int: ... # type: ignore[override] + def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... + def __iter__(self) -> Iterator[int]: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> int: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> range: ... + + def __reversed__(self) -> Iterator[int]: ... + +@disjoint_base +class property: + fget: Callable[[Any], Any] | None + fset: Callable[[Any, Any], None] | None + fdel: Callable[[Any], None] | None + __isabstractmethod__: bool + if sys.version_info >= (3, 13): + __name__: str + + def __init__( + self, + fget: Callable[[Any], Any] | None = None, + fset: Callable[[Any, Any], None] | None = None, + fdel: Callable[[Any], None] | None = None, + doc: str | None = None, + ) -> None: ... + def getter(self, fget: Callable[[Any], Any], /) -> property: ... + def setter(self, fset: Callable[[Any, Any], None], /) -> property: ... + def deleter(self, fdel: Callable[[Any], None], /) -> property: ... + + @overload + def __get__(self, instance: None, owner: type, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... + +def abs(x: SupportsAbs[_T], /) -> _T: ... +def all(iterable: Iterable[object], /) -> bool: ... +def any(iterable: Iterable[object], /) -> bool: ... +def ascii(obj: object, /) -> str: ... + +if sys.version_info >= (3, 15): + def bin(integer: SupportsIndex, /) -> str: ... + +else: + def bin(number: SupportsIndex, /) -> str: ... + +def breakpoint(*args: Any, **kws: Any) -> None: ... +def callable(obj: object, /) -> TypeIs[Callable[..., object]]: ... +def chr(i: SupportsIndex, /) -> str: ... +def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: ... + +@type_check_only +class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): + def __anext__(self) -> _AwaitableT_co: ... + +@overload +# `anext` is not, in fact, an async function. When default is not provided +# `anext` is just a passthrough for `obj.__anext__` +# See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 +def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ... +@overload +async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ... + +# compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024), +# in which case it returns ast.AST. We have overloads for flag 0 (the default) and for +# explicitly passing PyCF_ONLY_AST. We fall back to Any for other values of flags. +if sys.version_info >= (3, 15): + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> Any: ... +else: + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> Any: ... + +copyright: _sitebuiltins._Printer +credits: _sitebuiltins._Printer + +def delattr(obj: object, name: str, /) -> None: ... +def dir(o: object = ..., /) -> list[str]: ... + +@overload +def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ... +@overload +def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ... + +# The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. +# (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) +if sys.version_info >= (3, 15): + def eval( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + +elif sys.version_info >= (3, 13): + def eval( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + +else: + def eval( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + ) -> Any: ... + +# Comment above regarding `eval` applies to `exec` as well +if sys.version_info >= (3, 15): + def exec( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 13): + def exec( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 11): + def exec( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +else: + def exec( + source: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + /, + ) -> None: ... + +exit: _sitebuiltins.Quitter + +@disjoint_base +class filter(Generic[_T]): + @overload + def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... + @overload + def __new__(cls, function: Callable[[_S], TypeGuard[_T]], iterable: Iterable[_S], /) -> Self: ... + @overload + def __new__(cls, function: Callable[[_S], TypeIs[_T]], iterable: Iterable[_S], /) -> Self: ... + @overload + def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +def format(value: object, format_spec: str = "", /) -> str: ... + +@overload +def getattr(o: object, name: str, /) -> Any: ... + +# While technically covered by the last overload, spelling out the types for None, bool +# and basic containers help mypy out in some tricky situations involving type context +# (aka bidirectional inference) +@overload +def getattr(o: object, name: str, default: None, /) -> Any | None: ... +@overload +def getattr(o: object, name: str, default: bool, /) -> Any | bool: ... +@overload +def getattr(o: object, name: str, default: list[Any], /) -> Any | list[Any]: ... +@overload +def getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, Any]: ... +@overload +def getattr(o: object, name: str, default: _T, /) -> Any | _T: ... + +def globals() -> dict[str, Any]: ... +def hasattr(obj: object, name: str, /) -> bool: ... +def hash(obj: object, /) -> int: ... + +help: _sitebuiltins._Helper + +if sys.version_info >= (3, 15): + def hex(integer: SupportsIndex, /) -> str: ... + +else: + def hex(number: SupportsIndex, /) -> str: ... + +def id(obj: object, /) -> int: ... +def input(prompt: object = "", /) -> str: ... + +@type_check_only +class _GetItemIterable(Protocol[_T_co]): + def __getitem__(self, i: int, /) -> _T_co: ... + +@overload +def iter(object: SupportsIter[_SupportsNextT_co], /) -> _SupportsNextT_co: ... +@overload +def iter(object: _GetItemIterable[_T], /) -> Iterator[_T]: ... +@overload +def iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ... +@overload +def iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ... + +_ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...] + +def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ... +def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ... +def len(obj: Sized, /) -> int: ... + +license: _sitebuiltins._Printer + +def locals() -> dict[str, Any]: ... + +@disjoint_base +class map(Generic[_S]): + # 3.14 adds `strict` argument. + if sys.version_info >= (3, 14): + @overload + def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /, *, strict: bool = False) -> Self: ... + @overload + def __new__( + cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + strict: bool = False, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[..., _S], + iterable: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + strict: bool = False, + ) -> Self: ... + else: + @overload + def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /) -> Self: ... + @overload + def __new__(cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /) -> Self: ... + @overload + def __new__( + cls, func: Callable[[_T1, _T2, _T3], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iterable: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + ) -> Self: ... + @overload + def __new__( + cls, + func: Callable[..., _S], + iterable: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + ) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _S: ... + +@overload +def max( + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None +) -> SupportsRichComparisonT: ... +@overload +def max(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +@overload +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... +@overload +def max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +@overload +def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... +@overload +def max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + +@overload +def min( + arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None +) -> SupportsRichComparisonT: ... +@overload +def min(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +@overload +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ... +@overload +def min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ... +@overload +def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... +@overload +def min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + +@overload +def next(i: SupportsNext[_T], /) -> _T: ... +@overload +def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ... + +if sys.version_info >= (3, 15): + def oct(integer: SupportsIndex, /) -> str: ... + +else: + def oct(number: SupportsIndex, /) -> str: ... + +_Opener: TypeAlias = Callable[[str, int], int] + +# Text mode: always returns a TextIOWrapper +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> TextIOWrapper: ... + +# Unbuffered binary mode: returns a FileIO +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> FileIO: ... + +# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedRandom: ... +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedWriter: ... +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedReader: ... + +# Buffering cannot be determined: fall back to BinaryIO +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryMode, + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BinaryIO: ... + +# Fallback if mode is not specified +@overload +def open( + file: FileDescriptorOrPath, + mode: str, + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> IO[Any]: ... + +def ord(c: str | bytes | bytearray, /) -> int: ... + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ... + +@overload +def print( + *values: object, + sep: str | None = " ", + end: str | None = "\n", + file: SupportsWrite[str] | None = None, + flush: Literal[False] = False, +) -> None: ... +@overload +def print( + *values: object, sep: str | None = " ", end: str | None = "\n", file: _SupportsWriteAndFlush[str] | None = None, flush: bool +) -> None: ... + +_E_contra = TypeVar("_E_contra", contravariant=True) +_M_contra = TypeVar("_M_contra", contravariant=True) + +@type_check_only +class _SupportsPow2(Protocol[_E_contra, _T_co]): + def __pow__(self, other: _E_contra, /) -> _T_co: ... + +@type_check_only +class _SupportsPow3NoneOnly(Protocol[_E_contra, _T_co]): + def __pow__(self, other: _E_contra, modulo: None = None, /) -> _T_co: ... + +@type_check_only +class _SupportsPow3(Protocol[_E_contra, _M_contra, _T_co]): + def __pow__(self, other: _E_contra, modulo: _M_contra, /) -> _T_co: ... + +_SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any] +) + +# TODO: `pow(int, int, Literal[0])` fails at runtime, +# but adding a `Never` overload isn't a good solution for expressing that (see #8566). +@overload +def pow(base: int, exp: int, mod: int) -> int: ... +@overload +def pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ... +@overload +def pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ... +@overload +def pow(base: int, exp: _NegativeInteger, mod: None = None) -> float: ... + +# int base & positive-int exp -> int; int base & negative-int exp -> float +# return type must be Any as `int | float` causes too many false-positive errors +@overload +def pow(base: int, exp: int, mod: None = None) -> Any: ... +@overload +def pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ... +@overload +def pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ... +@overload +def pow(base: float, exp: int, mod: None = None) -> float: ... + +# float base & float exp could return float or complex +# return type must be Any (same as complex base, complex exp), +# as `float | complex` causes too many false-positive errors +@overload +def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... +@overload +def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... +@overload +def pow(base: _SupportsPow2[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] +@overload +def pow(base: _SupportsPow3NoneOnly[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] +@overload +def pow(base: _SupportsPow3[_E_contra, _M_contra, _T_co], exp: _E_contra, mod: _M_contra) -> _T_co: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... +@overload +def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... + +quit: _sitebuiltins.Quitter + +@type_check_only +class _SupportsReversed(Protocol[_T_co]): + def __reversed__(self) -> _T_co: ... + +@disjoint_base +class reversed(Generic[_T_co]): + @overload + def __new__(cls, sequence: _SupportsReversed[_T], /) -> _T: ... # type: ignore[misc] + @overload + def __new__(cls, sequence: SupportsLenAndGetItem[_T_co], /) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + def __length_hint__(self) -> int: ... + +def repr(obj: object, /) -> str: ... + +# See https://github.com/python/typeshed/pull/9141 +# and https://github.com/python/typeshed/pull/9151 +# on why we don't use `SupportsRound` from `typing.pyi` + +@type_check_only +class _SupportsRound1(Protocol[_T_co]): + def __round__(self) -> _T_co: ... + +@type_check_only +class _SupportsRound2(Protocol[_T_co]): + def __round__(self, ndigits: int, /) -> _T_co: ... + +@overload +def round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: ... +@overload +def round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ... + +# See https://github.com/python/typeshed/pull/6292#discussion_r748875189 +# for why arg 3 of `setattr` should be annotated with `Any` and not `object` +def setattr(obj: object, name: str, value: Any, /) -> None: ... + +if sys.version_info >= (3, 15): + @final + class sentinel: + __name__: str + __module__: str + def __new__(cls, name: str, /, *, repr: str | None = None) -> sentinel: ... + def __copy__(self, /) -> sentinel: ... + def __deepcopy__(self, memo: Any, /) -> sentinel: ... + # `other` can be any legal form for unions. + # `x | x` creates a `sentinel` instance if `x` is a sentinel, not a `UnionType` instance. + def __or__(self, other: Any, /) -> UnionType | sentinel: ... + def __ror__(self, other: Any, /) -> UnionType | sentinel: ... + +@overload +def sorted( + iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False +) -> list[SupportsRichComparisonT]: ... +@overload +def sorted(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ... + +_AddableT1 = TypeVar("_AddableT1", bound=SupportsAdd[Any, Any]) +_AddableT2 = TypeVar("_AddableT2", bound=SupportsAdd[Any, Any]) + +@type_check_only +class _SupportsSumWithNoDefaultGiven(SupportsAdd[Any, Any], SupportsRAdd[int, Any], Protocol): ... + +_SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWithNoDefaultGiven) + +# In general, the return type of `x + x` is *not* guaranteed to be the same type as x. +# However, we can't express that in the stub for `sum()` +# without creating many false-positive errors (see #7578). +# Instead, we special-case the most common examples of this: bool and literal integers. +@overload +def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... +@overload +def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... +@overload +def sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _AddableT2: ... + +# The argument to `vars()` has to have a `__dict__` attribute, so the second overload can't be annotated with `object` +# (A "SupportsDunderDict" protocol doesn't work) +@overload +def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... +@overload +def vars(object: Any = ..., /) -> dict[str, Any]: ... + +@disjoint_base +class zip(Generic[_T_co]): + @overload + def __new__(cls, *, strict: bool = False) -> zip[Any]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = False) -> zip[tuple[_T1]]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False) -> zip[tuple[_T1, _T2]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + strict: bool = False, + ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + strict: bool = False, + ) -> zip[tuple[Any, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` +# Return type of `__import__` should be kept the same as return type of `importlib.import_module` +def __import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, +) -> types.ModuleType: ... + +if sys.version_info >= (3, 15): + def __lazy_import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, + ) -> Any: ... + +def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... + +# Backwards compatibility hack for folks who relied on the ellipsis type +# existing in typeshed in Python 3.9 and earlier. +ellipsis = EllipsisType + +Ellipsis: EllipsisType +NotImplemented: NotImplementedType + +@disjoint_base +class BaseException: + args: tuple[Any, ...] + __cause__: BaseException | None + __context__: BaseException | None + __suppress_context__: bool + __traceback__: TracebackType | None + def __init__(self, *args: object) -> None: ... + def __new__(cls, /, *args: Any, **kwds: Any) -> Self: ... + def __setstate__(self, state: dict[str, Any] | None, /) -> None: ... + def with_traceback(self, tb: TracebackType | None, /) -> Self: ... + # Necessary for security-focused static analyzers (e.g, pysa) + # See https://github.com/python/typeshed/pull/14900 + def __str__(self) -> str: ... # noqa: Y029 + def __repr__(self) -> str: ... # noqa: Y029 + if sys.version_info >= (3, 11): + # only present after add_note() is called + __notes__: list[str] + def add_note(self, note: str, /) -> None: ... + +class GeneratorExit(BaseException): ... +class KeyboardInterrupt(BaseException): ... + +@disjoint_base +class SystemExit(BaseException): + code: sys._ExitCode + +class Exception(BaseException): ... + +@disjoint_base +class StopIteration(Exception): + value: Any + +@disjoint_base +class OSError(Exception): + errno: int | None + strerror: str | None + # filename, filename2 are actually str | bytes | None + filename: Any + filename2: Any + if sys.platform == "win32": + winerror: int + +EnvironmentError = OSError +IOError = OSError +if sys.platform == "win32": + WindowsError = OSError + +class ArithmeticError(Exception): ... +class AssertionError(Exception): ... + +@disjoint_base +class AttributeError(Exception): + def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ... + name: str | None + obj: object + +class BufferError(Exception): ... +class EOFError(Exception): ... + +@disjoint_base +class ImportError(Exception): + def __init__(self, *args: object, name: str | None = None, path: str | None = None) -> None: ... + name: str | None + path: str | None + msg: str # undocumented + if sys.version_info >= (3, 12): + name_from: str | None # undocumented + +if sys.version_info >= (3, 15): + class ImportCycleError(ImportError): ... + +class LookupError(Exception): ... +class MemoryError(Exception): ... + +@disjoint_base +class NameError(Exception): + def __init__(self, *args: object, name: str | None = None) -> None: ... + name: str | None + +class ReferenceError(Exception): ... +class RuntimeError(Exception): ... +class StopAsyncIteration(Exception): ... + +@disjoint_base +class SyntaxError(Exception): + msg: str + filename: str | None + lineno: int | None + offset: int | None + text: str | None + # Errors are displayed differently if this attribute exists on the exception. + # The value is always None. + print_file_and_line: None + end_lineno: int | None + end_offset: int | None + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, msg: object, /) -> None: ... + # Second argument is the tuple (filename, lineno, offset, text) + @overload + def __init__(self, msg: str, info: tuple[str | None, int | None, int | None, str | None], /) -> None: ... + # end_lineno and end_offset must both be provided if one is. + @overload + def __init__( + self, msg: str, info: tuple[str | None, int | None, int | None, str | None, int | None, int | None], / + ) -> None: ... + # If you provide more than two arguments, it still creates the SyntaxError, but + # the arguments from the info tuple are not parsed. This form is omitted. + +class SystemError(Exception): ... +class TypeError(Exception): ... +class ValueError(Exception): ... +class FloatingPointError(ArithmeticError): ... +class OverflowError(ArithmeticError): ... +class ZeroDivisionError(ArithmeticError): ... +class ModuleNotFoundError(ImportError): ... +class IndexError(LookupError): ... +class KeyError(LookupError): ... +class UnboundLocalError(NameError): ... + +class BlockingIOError(OSError): + characters_written: int + +class ChildProcessError(OSError): ... +class ConnectionError(OSError): ... +class BrokenPipeError(ConnectionError): ... +class ConnectionAbortedError(ConnectionError): ... +class ConnectionRefusedError(ConnectionError): ... +class ConnectionResetError(ConnectionError): ... +class FileExistsError(OSError): ... +class FileNotFoundError(OSError): ... +class InterruptedError(OSError): ... +class IsADirectoryError(OSError): ... +class NotADirectoryError(OSError): ... +class PermissionError(OSError): ... +class ProcessLookupError(OSError): ... +class TimeoutError(OSError): ... +class NotImplementedError(RuntimeError): ... +class RecursionError(RuntimeError): ... +class IndentationError(SyntaxError): ... +class TabError(IndentationError): ... +class UnicodeError(ValueError): ... + +@disjoint_base +class UnicodeDecodeError(UnicodeError): + encoding: str + object: bytes + start: int + end: int + reason: str + def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ... + +@disjoint_base +class UnicodeEncodeError(UnicodeError): + encoding: str + object: str + start: int + end: int + reason: str + def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ... + +@disjoint_base +class UnicodeTranslateError(UnicodeError): + encoding: None + object: str + start: int + end: int + reason: str + def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ... + +class Warning(Exception): ... +class UserWarning(Warning): ... +class DeprecationWarning(Warning): ... +class SyntaxWarning(Warning): ... +class RuntimeWarning(Warning): ... +class FutureWarning(Warning): ... +class PendingDeprecationWarning(Warning): ... +class ImportWarning(Warning): ... +class UnicodeWarning(Warning): ... +class BytesWarning(Warning): ... +class ResourceWarning(Warning): ... +class EncodingWarning(Warning): ... + +if sys.version_info >= (3, 11): + _BaseExceptionT_co = TypeVar("_BaseExceptionT_co", bound=BaseException, covariant=True, default=BaseException) + _BaseExceptionT = TypeVar("_BaseExceptionT", bound=BaseException) + _ExceptionT_co = TypeVar("_ExceptionT_co", bound=Exception, covariant=True, default=Exception) + _ExceptionT = TypeVar("_ExceptionT", bound=Exception) + + # See `check_exception_group.py` for use-cases and comments. + @disjoint_base + class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): + def __new__(cls, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> None: ... + @property + def message(self) -> str: ... + @property + def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ... + + @overload + def subgroup( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> ExceptionGroup[_ExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / + ) -> BaseExceptionGroup[_BaseExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / + ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ... + + @overload + def split( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], / + ) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / + ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + + # In reality it is `NonEmptySequence`: + @overload + def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... + @overload + def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): + def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ... + def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ... + @property + def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: ... + + # We accept a narrower type, but that's OK. + @overload # type: ignore[override] + def subgroup( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> ExceptionGroup[_ExceptionT] | None: ... + @overload + def subgroup( + self, matcher_value: Callable[[_ExceptionT_co | Self], bool], / + ) -> ExceptionGroup[_ExceptionT_co] | None: ... + + @overload # type: ignore[override] + def split( + self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / + ) -> tuple[ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None]: ... + @overload + def split( + self, matcher_value: Callable[[_ExceptionT_co | Self], bool], / + ) -> tuple[ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None]: ... + +if sys.version_info >= (3, 13): + class PythonFinalizationError(RuntimeError): ... diff --git a/stdlib/bz2.pyi b/stdlib/bz2.pyi new file mode 100644 index 000000000000..fec6b30af2f5 --- /dev/null +++ b/stdlib/bz2.pyi @@ -0,0 +1,121 @@ +import sys +from _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompressor +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from collections.abc import Iterable +from io import TextIOWrapper +from typing import IO, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream, _Reader +else: + from _compression import BaseStream, _Reader + +__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] + +# The following attributes and methods are optional: +# def fileno(self) -> int: ... +# def close(self) -> object: ... +@type_check_only +class _ReadableFileobj(_Reader, Protocol): ... + +@type_check_only +class _WritableFileobj(Protocol): + def write(self, b: bytes, /) -> object: ... + # The following attributes and methods are optional: + # def fileno(self) -> int: ... + # def close(self) -> object: ... + +def compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: ... +def decompress(data: ReadableBuffer) -> bytes: ... + +_ReadBinaryMode: TypeAlias = Literal["", "r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode: TypeAlias = Literal["rt"] +_WriteTextMode: TypeAlias = Literal["wt", "xt", "at"] + +@overload +def open( + filename: _ReadableFileobj, + mode: _ReadBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> BZ2File: ... +@overload +def open( + filename: _ReadableFileobj, + mode: _ReadTextMode, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: _WritableFileobj, + mode: _WriteBinaryMode, + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> BZ2File: ... +@overload +def open( + filename: _WritableFileobj, + mode: _WriteTextMode, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: StrOrBytesPath, + mode: _ReadBinaryMode | _WriteBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> BZ2File: ... +@overload +def open( + filename: StrOrBytesPath, + mode: _ReadTextMode | _WriteTextMode, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, + mode: str, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> BZ2File | TextIOWrapper: ... + +class BZ2File(BaseStream, IO[bytes]): + def __enter__(self) -> Self: ... + + @overload + def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ... + @overload + def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = "r", *, compresslevel: int = 9) -> None: ... + @overload + def __init__( + self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9 + ) -> None: ... + + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... + def readline(self, size: SupportsIndex = -1) -> bytes: ... # type: ignore[override] + def readinto(self, b: WriteableBuffer) -> int: ... + def readlines(self, size: SupportsIndex = -1) -> list[bytes]: ... + def peek(self, n: int = 0) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def write(self, data: ReadableBuffer) -> int: ... + def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... diff --git a/stdlib/cProfile.pyi b/stdlib/cProfile.pyi new file mode 100644 index 000000000000..0e414206f515 --- /dev/null +++ b/stdlib/cProfile.pyi @@ -0,0 +1,33 @@ +import _lsprof +import sys +from _typeshed import StrOrBytesPath, Unused +from collections.abc import Callable, Mapping +from types import CodeType +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self + +__all__ = ["run", "runctx", "Profile"] + +def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ... +def runctx( + statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 +) -> None: ... + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_Label: TypeAlias = tuple[str, int, str] + +class Profile(_lsprof.Profiler): + stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented + def print_stats(self, sort: str | int = -1) -> None: ... + def dump_stats(self, file: StrOrBytesPath) -> None: ... + def create_stats(self) -> None: ... + def snapshot_stats(self) -> None: ... + def run(self, cmd: str) -> Self: ... + def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: Unused) -> None: ... + +if sys.version_info < (3, 15): + def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/stdlib/calendar.pyi b/stdlib/calendar.pyi new file mode 100644 index 000000000000..fb75d9559e97 --- /dev/null +++ b/stdlib/calendar.pyi @@ -0,0 +1,249 @@ +import datetime +import enum +import sys +from _typeshed import Unused +from collections.abc import Iterable, Iterator +from time import struct_time +from typing import ClassVar, Final, TypeAlias, overload + +__all__ = [ + "FRIDAY", + "MONDAY", + "SATURDAY", + "SUNDAY", + "THURSDAY", + "TUESDAY", + "WEDNESDAY", + "IllegalMonthError", + "IllegalWeekdayError", + "setfirstweekday", + "firstweekday", + "isleap", + "leapdays", + "weekday", + "monthrange", + "monthcalendar", + "prmonth", + "month", + "prcal", + "calendar", + "timegm", + "month_name", + "month_abbr", + "day_name", + "day_abbr", + "Calendar", + "TextCalendar", + "HTMLCalendar", + "LocaleTextCalendar", + "LocaleHTMLCalendar", + "weekheader", +] + +if sys.version_info >= (3, 12): + __all__ += [ + "Day", + "Month", + "JANUARY", + "FEBRUARY", + "MARCH", + "APRIL", + "MAY", + "JUNE", + "JULY", + "AUGUST", + "SEPTEMBER", + "OCTOBER", + "NOVEMBER", + "DECEMBER", + ] +if sys.version_info >= (3, 15): + __all__ += ["standalone_month_name", "standalone_month_abbr"] + +_LocaleType: TypeAlias = tuple[str | None, str | None] + +class IllegalMonthError(ValueError, IndexError): + month: int + def __init__(self, month: int) -> None: ... + +class IllegalWeekdayError(ValueError): + weekday: int + def __init__(self, weekday: int) -> None: ... + +def isleap(year: int) -> bool: ... +def leapdays(y1: int, y2: int) -> int: ... +def weekday(year: int, month: int, day: int) -> int: ... +def monthrange(year: int, month: int) -> tuple[int, int]: ... + +class Calendar: + firstweekday: int + def __init__(self, firstweekday: int = 0) -> None: ... + def getfirstweekday(self) -> int: ... + def setfirstweekday(self, firstweekday: int) -> None: ... + def iterweekdays(self) -> Iterator[int]: ... + def itermonthdates(self, year: int, month: int) -> Iterator[datetime.date]: ... + def itermonthdays2(self, year: int, month: int) -> Iterator[tuple[int, int]]: ... + def itermonthdays(self, year: int, month: int) -> Iterator[int]: ... + def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ... + def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ... + def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ... + def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[datetime.date]]]]: ... + def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: ... + def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: ... + def itermonthdays3(self, year: int, month: int) -> Iterator[tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Iterator[tuple[int, int, int, int]]: ... + +class TextCalendar(Calendar): + def prweek(self, theweek: Iterable[tuple[int, int]], width: int) -> None: ... + def formatday(self, day: int, weekday: int, width: int) -> str: ... + def formatweek(self, theweek: Iterable[tuple[int, int]], width: int) -> str: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatweekheader(self, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: ... + def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... + def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... + def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... + def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... + +def firstweekday() -> int: ... +def monthcalendar(year: int, month: int) -> list[list[int]]: ... +def prweek(theweek: int, width: int) -> None: ... +def week(theweek: int, width: int) -> str: ... +def weekheader(width: int) -> str: ... +def prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ... +def month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ... +def calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... +def prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ... + +class HTMLCalendar(Calendar): + cssclasses: ClassVar[list[str]] + cssclass_noday: ClassVar[str] + cssclasses_weekday_head: ClassVar[list[str]] + cssclass_month_head: ClassVar[str] + cssclass_month: ClassVar[str] + cssclass_year: ClassVar[str] + cssclass_year_head: ClassVar[str] + def formatday(self, day: int, weekday: int) -> str: ... + def formatweek(self, theweek: int) -> str: ... + def formatweekday(self, day: int) -> str: ... + def formatweekheader(self) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + if sys.version_info >= (3, 15): + def formatmonthpage( + self, theyear: int, themonth: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None + ) -> bytes: ... + + def formatyear(self, theyear: int, width: int = 3) -> str: ... + def formatyearpage( + self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None + ) -> bytes: ... + +class different_locale: + def __init__(self, locale: _LocaleType) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *args: Unused) -> None: ... + +class LocaleTextCalendar(TextCalendar): + def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... + +class LocaleHTMLCalendar(HTMLCalendar): + def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ... + def formatweekday(self, day: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + +c: TextCalendar + +def setfirstweekday(firstweekday: int) -> None: ... +def format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... +def formatstring(cols: Iterable[str], colwidth: int = 20, spacing: int = 6) -> str: ... +def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... + +# Data attributes +class _localized_month: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + +class _localized_day: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + +day_name: _localized_day +day_abbr: _localized_day +month_name: _localized_month +month_abbr: _localized_month + +if sys.version_info >= (3, 12): + class Month(enum.IntEnum): + JANUARY = 1 + FEBRUARY = 2 + MARCH = 3 + APRIL = 4 + MAY = 5 + JUNE = 6 + JULY = 7 + AUGUST = 8 + SEPTEMBER = 9 + OCTOBER = 10 + NOVEMBER = 11 + DECEMBER = 12 + + JANUARY: Final = Month.JANUARY + FEBRUARY: Final = Month.FEBRUARY + MARCH: Final = Month.MARCH + APRIL: Final = Month.APRIL + MAY: Final = Month.MAY + JUNE: Final = Month.JUNE + JULY: Final = Month.JULY + AUGUST: Final = Month.AUGUST + SEPTEMBER: Final = Month.SEPTEMBER + OCTOBER: Final = Month.OCTOBER + NOVEMBER: Final = Month.NOVEMBER + DECEMBER: Final = Month.DECEMBER + + class Day(enum.IntEnum): + MONDAY = 0 + TUESDAY = 1 + WEDNESDAY = 2 + THURSDAY = 3 + FRIDAY = 4 + SATURDAY = 5 + SUNDAY = 6 + + MONDAY: Final = Day.MONDAY + TUESDAY: Final = Day.TUESDAY + WEDNESDAY: Final = Day.WEDNESDAY + THURSDAY: Final = Day.THURSDAY + FRIDAY: Final = Day.FRIDAY + SATURDAY: Final = Day.SATURDAY + SUNDAY: Final = Day.SUNDAY +else: + MONDAY: Final = 0 + TUESDAY: Final = 1 + WEDNESDAY: Final = 2 + THURSDAY: Final = 3 + FRIDAY: Final = 4 + SATURDAY: Final = 5 + SUNDAY: Final = 6 + +EPOCH: Final = 1970 + +if sys.version_info >= (3, 15): + standalone_month_name: _localized_month + standalone_month_abbr: _localized_month diff --git a/stdlib/cgi.pyi b/stdlib/cgi.pyi new file mode 100644 index 000000000000..b7f88ded315f --- /dev/null +++ b/stdlib/cgi.pyi @@ -0,0 +1,120 @@ +import os +from _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused +from builtins import list as _list, type as _type +from collections.abc import Iterable, Iterator, Mapping +from email.message import Message +from types import TracebackType +from typing import IO, Any, Protocol, type_check_only +from typing_extensions import Self + +__all__ = [ + "MiniFieldStorage", + "FieldStorage", + "parse", + "parse_multipart", + "parse_header", + "test", + "print_exception", + "print_environ", + "print_form", + "print_directory", + "print_arguments", + "print_environ_usage", +] + +def parse( + fp: IO[Any] | None = None, + environ: SupportsItemAccess[str, str] = os.environ, + keep_blank_values: bool = ..., + strict_parsing: bool = ..., + separator: str = "&", +) -> dict[str, list[str]]: ... +def parse_multipart( + fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = "utf-8", errors: str = "replace", separator: str = "&" +) -> dict[str, list[Any]]: ... + +@type_check_only +class _Environ(Protocol): + def __getitem__(self, k: str, /) -> str: ... + def keys(self) -> Iterable[str]: ... + +def parse_header(line: str) -> tuple[str, dict[str, str]]: ... +def test(environ: _Environ = os.environ) -> None: ... +def print_environ(environ: _Environ = os.environ) -> None: ... +def print_form(form: dict[str, Any]) -> None: ... +def print_directory() -> None: ... +def print_environ_usage() -> None: ... + +class MiniFieldStorage: + # The first five "Any" attributes here are always None, but mypy doesn't support that + filename: Any + list: Any + type: Any + file: IO[bytes] | None + type_options: dict[Any, Any] + disposition: Any + disposition_options: dict[Any, Any] + headers: dict[Any, Any] + name: Any + value: Any + def __init__(self, name: Any, value: Any) -> None: ... + +class FieldStorage: + FieldStorageClass: _type | None + keep_blank_values: int + strict_parsing: int + qs_on_post: str | None + headers: Mapping[str, str] | Message + fp: IO[bytes] + encoding: str + errors: str + outerboundary: bytes + bytes_read: int + limit: int | None + disposition: str + disposition_options: dict[str, str] + filename: str | None + file: IO[bytes] | None + type: str + type_options: dict[str, str] + innerboundary: bytes + length: int + done: int + list: _list[Any] | None + value: None | bytes | _list[Any] + def __init__( + self, + fp: IO[Any] | None = None, + headers: Mapping[str, str] | Message | None = None, + outerboundary: bytes = b"", + environ: SupportsContainsAndGetItem[str, str] = os.environ, + keep_blank_values: int = 0, + strict_parsing: int = 0, + limit: int | None = None, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __getitem__(self, key: str) -> Any: ... + def getvalue(self, key: str, default: Any = None) -> Any: ... + def getfirst(self, key: str, default: Any = None) -> Any: ... + def getlist(self, key: str) -> _list[Any]: ... + def keys(self) -> _list[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __del__(self) -> None: ... + # Returns bytes or str IO depending on an internal flag + def make_file(self) -> IO[Any]: ... + +def print_exception( + type: type[BaseException] | None = None, + value: BaseException | None = None, + tb: TracebackType | None = None, + limit: int | None = None, +) -> None: ... +def print_arguments() -> None: ... diff --git a/stdlib/cgitb.pyi b/stdlib/cgitb.pyi new file mode 100644 index 000000000000..565725801159 --- /dev/null +++ b/stdlib/cgitb.pyi @@ -0,0 +1,32 @@ +from _typeshed import OptExcInfo, StrOrBytesPath +from collections.abc import Callable +from types import FrameType, TracebackType +from typing import IO, Any, Final + +__UNDEF__: Final[object] # undocumented sentinel + +def reset() -> str: ... # undocumented +def small(text: str) -> str: ... # undocumented +def strong(text: str) -> str: ... # undocumented +def grey(text: str) -> str: ... # undocumented +def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | None, Any]: ... # undocumented +def scanvars( + reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] +) -> list[tuple[str, str | None, Any]]: ... # undocumented +def html(einfo: OptExcInfo, context: int = 5) -> str: ... +def text(einfo: OptExcInfo, context: int = 5) -> str: ... + +class Hook: # undocumented + def __init__( + self, + display: int = 1, + logdir: StrOrBytesPath | None = None, + context: int = 5, + file: IO[str] | None = None, + format: str = "html", + ) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def handle(self, info: OptExcInfo | None = None) -> None: ... + +def handler(info: OptExcInfo | None = None) -> None: ... +def enable(display: int = 1, logdir: StrOrBytesPath | None = None, context: int = 5, format: str = "html") -> None: ... diff --git a/stdlib/chunk.pyi b/stdlib/chunk.pyi new file mode 100644 index 000000000000..9788d35f680c --- /dev/null +++ b/stdlib/chunk.pyi @@ -0,0 +1,20 @@ +from typing import IO + +class Chunk: + closed: bool + align: bool + file: IO[bytes] + chunkname: bytes + chunksize: int + size_read: int + offset: int + seekable: bool + def __init__(self, file: IO[bytes], align: bool = True, bigendian: bool = True, inclheader: bool = False) -> None: ... + def getname(self) -> bytes: ... + def getsize(self) -> int: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + def seek(self, pos: int, whence: int = 0) -> None: ... + def tell(self) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def skip(self) -> None: ... diff --git a/stdlib/cmath.pyi b/stdlib/cmath.pyi new file mode 100644 index 000000000000..554eb54e2e4c --- /dev/null +++ b/stdlib/cmath.pyi @@ -0,0 +1,36 @@ +from typing import Final, SupportsComplex, SupportsFloat, SupportsIndex, TypeAlias + +e: Final[float] +pi: Final[float] +inf: Final[float] +infj: Final[complex] +nan: Final[float] +nanj: Final[complex] +tau: Final[float] + +_F: TypeAlias = SupportsFloat | SupportsIndex +_C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex + +def acos(z: _C, /) -> complex: ... +def acosh(z: _C, /) -> complex: ... +def asin(z: _C, /) -> complex: ... +def asinh(z: _C, /) -> complex: ... +def atan(z: _C, /) -> complex: ... +def atanh(z: _C, /) -> complex: ... +def cos(z: _C, /) -> complex: ... +def cosh(z: _C, /) -> complex: ... +def exp(z: _C, /) -> complex: ... +def isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFloat = 0.0) -> bool: ... +def isinf(z: _C, /) -> bool: ... +def isnan(z: _C, /) -> bool: ... +def log(z: _C, base: _C = ..., /) -> complex: ... +def log10(z: _C, /) -> complex: ... +def phase(z: _C, /) -> float: ... +def polar(z: _C, /) -> tuple[float, float]: ... +def rect(r: _F, phi: _F, /) -> complex: ... +def sin(z: _C, /) -> complex: ... +def sinh(z: _C, /) -> complex: ... +def sqrt(z: _C, /) -> complex: ... +def tan(z: _C, /) -> complex: ... +def tanh(z: _C, /) -> complex: ... +def isfinite(z: _C, /) -> bool: ... diff --git a/stdlib/cmd.pyi b/stdlib/cmd.pyi new file mode 100644 index 000000000000..6e84133572bf --- /dev/null +++ b/stdlib/cmd.pyi @@ -0,0 +1,46 @@ +from collections.abc import Callable +from typing import IO, Any, Final +from typing_extensions import LiteralString + +__all__ = ["Cmd"] + +PROMPT: Final = "(Cmd) " +IDENTCHARS: Final[LiteralString] # Too big to be `Literal` + +class Cmd: + prompt: str + identchars: str + ruler: str + lastcmd: str + intro: Any | None + doc_leader: str + doc_header: str + misc_header: str + undoc_header: str + nohelp: str + use_rawinput: bool + stdin: IO[str] + stdout: IO[str] + cmdqueue: list[str] + completekey: str + def __init__(self, completekey: str = "tab", stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None: ... + old_completer: Callable[[str, int], str | None] | None + def cmdloop(self, intro: Any | None = None) -> None: ... + def precmd(self, line: str) -> str: ... + def postcmd(self, stop: bool, line: str) -> bool: ... + def preloop(self) -> None: ... + def postloop(self) -> None: ... + def parseline(self, line: str) -> tuple[str | None, str | None, str]: ... + def onecmd(self, line: str) -> bool: ... + def emptyline(self) -> bool: ... + def default(self, line: str) -> None: ... + def completedefault(self, *ignored: Any) -> list[str]: ... + def completenames(self, text: str, *ignored: Any) -> list[str]: ... + completion_matches: list[str] | None + def complete(self, text: str, state: int) -> list[str] | None: ... + def get_names(self) -> list[str]: ... + # Only the first element of args matters. + def complete_help(self, *args: Any) -> list[str]: ... + def do_help(self, arg: str) -> bool | None: ... + def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ... + def columnize(self, list: list[str] | None, displaywidth: int = 80) -> None: ... diff --git a/stdlib/code.pyi b/stdlib/code.pyi new file mode 100644 index 000000000000..478d5aaa320f --- /dev/null +++ b/stdlib/code.pyi @@ -0,0 +1,55 @@ +import sys +from codeop import CommandCompiler, compile_command as compile_command +from collections.abc import Callable +from types import CodeType +from typing import Any + +__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] + +class InteractiveInterpreter: + locals: dict[str, Any] # undocumented + compile: CommandCompiler # undocumented + def __init__(self, locals: dict[str, Any] | None = None) -> None: ... + def runsource(self, source: str, filename: str = "", symbol: str = "single") -> bool: ... + def runcode(self, code: CodeType) -> None: ... + if sys.version_info >= (3, 13): + def showsyntaxerror(self, filename: str | None = None, *, source: str = "") -> None: ... + else: + def showsyntaxerror(self, filename: str | None = None) -> None: ... + + def showtraceback(self) -> None: ... + def write(self, data: str) -> None: ... + +class InteractiveConsole(InteractiveInterpreter): + buffer: list[str] # undocumented + filename: str # undocumented + if sys.version_info >= (3, 13): + local_exit: bool # undocumented + def __init__( + self, locals: dict[str, Any] | None = None, filename: str = "", *, local_exit: bool = False + ) -> None: ... + def push(self, line: str, filename: str | None = None) -> bool: ... + else: + def __init__(self, locals: dict[str, Any] | None = None, filename: str = "") -> None: ... + def push(self, line: str) -> bool: ... + + def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None: ... + def resetbuffer(self) -> None: ... + def raw_input(self, prompt: str = "") -> str: ... + +if sys.version_info >= (3, 13): + def interact( + banner: str | None = None, + readfunc: Callable[[str], str] | None = None, + local: dict[str, Any] | None = None, + exitmsg: str | None = None, + local_exit: bool = False, + ) -> None: ... + +else: + def interact( + banner: str | None = None, + readfunc: Callable[[str], str] | None = None, + local: dict[str, Any] | None = None, + exitmsg: str | None = None, + ) -> None: ... diff --git a/stdlib/codecs.pyi b/stdlib/codecs.pyi new file mode 100644 index 000000000000..ee1ab25bac47 --- /dev/null +++ b/stdlib/codecs.pyi @@ -0,0 +1,357 @@ +import sys +import types +from _codecs import * +from _typeshed import ReadableBuffer +from abc import abstractmethod +from collections.abc import Callable, Generator, Iterable +from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base + +__all__ = [ + "register", + "lookup", + "open", + "EncodedFile", + "BOM", + "BOM_BE", + "BOM_LE", + "BOM32_BE", + "BOM32_LE", + "BOM64_BE", + "BOM64_LE", + "BOM_UTF8", + "BOM_UTF16", + "BOM_UTF16_LE", + "BOM_UTF16_BE", + "BOM_UTF32", + "BOM_UTF32_LE", + "BOM_UTF32_BE", + "CodecInfo", + "Codec", + "IncrementalEncoder", + "IncrementalDecoder", + "StreamReader", + "StreamWriter", + "StreamReaderWriter", + "StreamRecoder", + "getencoder", + "getdecoder", + "getincrementalencoder", + "getincrementaldecoder", + "getreader", + "getwriter", + "encode", + "decode", + "iterencode", + "iterdecode", + "strict_errors", + "ignore_errors", + "replace_errors", + "xmlcharrefreplace_errors", + "backslashreplace_errors", + "namereplace_errors", + "register_error", + "lookup_error", +] + +BOM32_BE: Final = b"\xfe\xff" +BOM32_LE: Final = b"\xff\xfe" +BOM64_BE: Final = b"\x00\x00\xfe\xff" +BOM64_LE: Final = b"\xff\xfe\x00\x00" + +_BufferedEncoding: TypeAlias = Literal[ + "idna", + "raw-unicode-escape", + "unicode-escape", + "utf-16", + "utf-16-be", + "utf-16-le", + "utf-32", + "utf-32-be", + "utf-32-le", + "utf-7", + "utf-8", + "utf-8-sig", +] + +@type_check_only +class _WritableStream(Protocol): + def write(self, data: bytes, /) -> object: ... + def seek(self, offset: int, whence: int, /) -> object: ... + def close(self) -> object: ... + +@type_check_only +class _ReadableStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def seek(self, offset: int, whence: int, /) -> object: ... + def close(self) -> object: ... + +@type_check_only +class _Stream(_WritableStream, _ReadableStream, Protocol): ... + +# TODO: this only satisfies the most common interface, where +# bytes is the raw form and str is the cooked form. +# In the long run, both should become template parameters maybe? +# There *are* bytes->bytes and str->str encodings in the standard library. +# They were much more common in Python 2 than in Python 3. + +@type_check_only +class _Encoder(Protocol): + def __call__(self, input: str, errors: str = ..., /) -> tuple[bytes, int]: ... # signature of Codec().encode + +@type_check_only +class _Decoder(Protocol): + def __call__(self, input: ReadableBuffer, errors: str = ..., /) -> tuple[str, int]: ... # signature of Codec().decode + +@type_check_only +class _StreamReader(Protocol): + def __call__(self, stream: _ReadableStream, errors: str = ..., /) -> StreamReader: ... + +@type_check_only +class _StreamWriter(Protocol): + def __call__(self, stream: _WritableStream, errors: str = ..., /) -> StreamWriter: ... + +@type_check_only +class _IncrementalEncoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalEncoder: ... + +@type_check_only +class _IncrementalDecoder(Protocol): + def __call__(self, errors: str = ...) -> IncrementalDecoder: ... + +@type_check_only +class _BufferedIncrementalDecoder(Protocol): + def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ... + +if sys.version_info >= (3, 12): + class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + _is_text_encoding: bool + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __new__( + cls, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader | None = None, + streamwriter: _StreamWriter | None = None, + incrementalencoder: _IncrementalEncoder | None = None, + incrementaldecoder: _IncrementalDecoder | None = None, + name: str | None = None, + *, + _is_text_encoding: bool | None = None, + ) -> Self: ... + +else: + @disjoint_base + class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): + _is_text_encoding: bool + @property + def encode(self) -> _Encoder: ... + @property + def decode(self) -> _Decoder: ... + @property + def streamreader(self) -> _StreamReader: ... + @property + def streamwriter(self) -> _StreamWriter: ... + @property + def incrementalencoder(self) -> _IncrementalEncoder: ... + @property + def incrementaldecoder(self) -> _IncrementalDecoder: ... + name: str + def __new__( + cls, + encode: _Encoder, + decode: _Decoder, + streamreader: _StreamReader | None = None, + streamwriter: _StreamWriter | None = None, + incrementalencoder: _IncrementalEncoder | None = None, + incrementaldecoder: _IncrementalDecoder | None = None, + name: str | None = None, + *, + _is_text_encoding: bool | None = None, + ) -> Self: ... + +def getencoder(encoding: str) -> _Encoder: ... +def getdecoder(encoding: str) -> _Decoder: ... +def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... + +@overload +def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDecoder: ... +@overload +def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... + +def getreader(encoding: str) -> _StreamReader: ... +def getwriter(encoding: str) -> _StreamWriter: ... +@deprecated("Deprecated. Use `open()` instead.") +def open( + filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 +) -> StreamReaderWriter: ... +def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = "strict") -> StreamRecoder: ... +def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes]: ... +def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str]: ... + +BOM: Final[Literal[b"\xff\xfe", b"\xfe\xff"]] # depends on `sys.byteorder` +BOM_BE: Final = b"\xfe\xff" +BOM_LE: Final = b"\xff\xfe" +BOM_UTF8: Final = b"\xef\xbb\xbf" +BOM_UTF16: Final[Literal[b"\xff\xfe", b"\xfe\xff"]] # depends on `sys.byteorder` +BOM_UTF16_BE: Final = b"\xfe\xff" +BOM_UTF16_LE: Final = b"\xff\xfe" +BOM_UTF32: Final[Literal[b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff"]] # depends on `sys.byteorder` +BOM_UTF32_BE: Final = b"\x00\x00\xfe\xff" +BOM_UTF32_LE: Final = b"\xff\xfe\x00\x00" + +def strict_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def replace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def ignore_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def backslashreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... +def namereplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ... + +class Codec: + # These are sort of @abstractmethod but sort of not. + # The StreamReader and StreamWriter subclasses only implement one. + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + @abstractmethod + def encode(self, input: str, final: bool = False) -> bytes: ... + def reset(self) -> None: ... + # documentation says int but str is needed for the subclass. + def getstate(self) -> int | str: ... + def setstate(self, state: int | str) -> None: ... + +class IncrementalDecoder: + errors: str + def __init__(self, errors: str = "strict") -> None: ... + @abstractmethod + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + def reset(self) -> None: ... + def getstate(self) -> tuple[bytes, int]: ... + def setstate(self, state: tuple[bytes, int]) -> None: ... + +# These are not documented but used in encodings/*.py implementations. +class BufferedIncrementalEncoder(IncrementalEncoder): + buffer: str + def __init__(self, errors: str = "strict") -> None: ... + @abstractmethod + def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + +class BufferedIncrementalDecoder(IncrementalDecoder): + buffer: bytes + def __init__(self, errors: str = "strict") -> None: ... + @abstractmethod + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +# TODO: it is not possible to specify the requirement that all other +# attributes and methods are passed-through from the stream. +class StreamWriter(Codec): + stream: _WritableStream + errors: str + def __init__(self, stream: _WritableStream, errors: str = "strict") -> None: ... + def write(self, object: str) -> None: ... + def writelines(self, list: Iterable[str]) -> None: ... + def reset(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ... + +class StreamReader(Codec): + stream: _ReadableStream + errors: str + # This is set to str, but some subclasses set to bytes instead. + charbuffertype: ClassVar[type] = ... + def __init__(self, stream: _ReadableStream, errors: str = "strict") -> None: ... + def read(self, size: int = -1, chars: int = -1, firstline: bool = False) -> str: ... + def readline(self, size: int | None = None, keepends: bool = True) -> str: ... + def readlines(self, sizehint: int | None = None, keepends: bool = True) -> list[str]: ... + def reset(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> str: ... + def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ... + +# Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing +# and delegates attributes to the underlying binary stream with __getattr__. +class StreamReaderWriter(TextIO): + stream: _Stream + def __init__(self, stream: _Stream, Reader: _StreamReader, Writer: _StreamWriter, errors: str = "strict") -> None: ... + def read(self, size: int = -1) -> str: ... + def readline(self, size: int | None = None) -> str: ... + def readlines(self, sizehint: int | None = None) -> list[str]: ... + def __next__(self) -> str: ... + def __iter__(self) -> Self: ... + def write(self, data: str) -> None: ... # type: ignore[override] + def writelines(self, list: Iterable[str]) -> None: ... + def reset(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... # type: ignore[override] + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + # These methods don't actually exist directly, but they are needed to satisfy the TextIO + # interface. At runtime, they are delegated through __getattr__. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: int | None = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... + +class StreamRecoder(BinaryIO): + data_encoding: str + file_encoding: str + def __init__( + self, + stream: _Stream, + encode: _Encoder, + decode: _Decoder, + Reader: _StreamReader, + Writer: _StreamWriter, + errors: str = "strict", + ) -> None: ... + def read(self, size: int = -1) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, sizehint: int | None = None) -> list[bytes]: ... + def __next__(self) -> bytes: ... + def __iter__(self) -> Self: ... + # Base class accepts more types than just bytes + def write(self, data: bytes) -> None: ... # type: ignore[override] + def writelines(self, list: Iterable[bytes]) -> None: ... # type: ignore[override] + def reset(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def seek(self, offset: int, whence: int = 0) -> None: ... # type: ignore[override] + # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO + # interface. At runtime, they are delegated through __getattr__. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def readable(self) -> bool: ... + def truncate(self, size: int | None = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def writable(self) -> bool: ... diff --git a/stdlib/codeop.pyi b/stdlib/codeop.pyi new file mode 100644 index 000000000000..8e311343eb89 --- /dev/null +++ b/stdlib/codeop.pyi @@ -0,0 +1,21 @@ +import sys +from types import CodeType + +__all__ = ["compile_command", "Compile", "CommandCompiler"] + +if sys.version_info >= (3, 14): + def compile_command(source: str, filename: str = "", symbol: str = "single", flags: int = 0) -> CodeType | None: ... + +else: + def compile_command(source: str, filename: str = "", symbol: str = "single") -> CodeType | None: ... + +class Compile: + flags: int + if sys.version_info >= (3, 13): + def __call__(self, source: str, filename: str, symbol: str, flags: int = 0) -> CodeType: ... + else: + def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ... + +class CommandCompiler: + compiler: Compile + def __call__(self, source: str, filename: str = "", symbol: str = "single") -> CodeType | None: ... diff --git a/stdlib/collections/__init__.pyi b/stdlib/collections/__init__.pyi new file mode 100644 index 000000000000..3e2e838eaa26 --- /dev/null +++ b/stdlib/collections/__init__.pyi @@ -0,0 +1,565 @@ +import sys +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import ( + Callable, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + ValuesView, +) +from types import GenericAlias +from typing import Any, ClassVar, Generic, SupportsIndex, TypeVar, final, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base + +if sys.version_info >= (3, 15): + from builtins import frozendict + +__all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] + +_S = TypeVar("_S") +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + +# namedtuple is special-cased in the type checker; the initializer is ignored. +def namedtuple( + typename: str, + field_names: str | Iterable[str], + *, + rename: bool = False, + module: str | None = None, + defaults: Iterable[Any] | None = None, +) -> type[tuple[Any, ...]]: ... + +class UserDict(MutableMapping[_KT, _VT]): + data: dict[_KT, _VT] + + # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics + @overload + def __init__(self, dict: None = None, /) -> None: ... + @overload + def __init__( + self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... + @overload + def __init__(self, dict: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + dict: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: UserDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ... + @overload + def __init__(self: UserDict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, item: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __contains__(self, key: object) -> bool: ... + def copy(self) -> Self: ... + def __copy__(self) -> Self: ... + + # `UserDict.fromkeys` has the same semantics as `dict.fromkeys`, so should be kept in line with `dict.fromkeys`. + # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> UserDict[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... + + @overload + def __or__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... + @overload + def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... + @overload + def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + + # UserDict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + + if sys.version_info >= (3, 12): + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + +class UserList(MutableSequence[_T]): + data: list[_T] + + @overload + def __init__(self, initlist: None = None) -> None: ... + @overload + def __init__(self, initlist: Iterable[_T]) -> None: ... + + __hash__: ClassVar[None] # type: ignore[assignment] + def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __ge__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __contains__(self, item: object) -> bool: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, i: SupportsIndex) -> _T: ... + @overload + def __getitem__(self, i: slice[SupportsIndex | None]) -> Self: ... + + @overload + def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... + @overload + def __setitem__(self, i: slice[SupportsIndex | None], item: Iterable[_T]) -> None: ... + + def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None]) -> None: ... + def __add__(self, other: Iterable[_T]) -> Self: ... + def __radd__(self, other: Iterable[_T]) -> Self: ... + def __iadd__(self, other: Iterable[_T]) -> Self: ... + def __mul__(self, n: int) -> Self: ... + def __rmul__(self, n: int) -> Self: ... + def __imul__(self, n: int) -> Self: ... + def append(self, item: _T) -> None: ... + def insert(self, i: int, item: _T) -> None: ... + def pop(self, i: int = -1) -> _T: ... + def remove(self, item: _T) -> None: ... + def copy(self) -> Self: ... + def __copy__(self) -> Self: ... + def count(self, item: _T) -> int: ... + # The runtime signature is "item, *args", and the arguments are then passed + # to `list.index`. In order to give more precise types, we pretend that the + # `item` argument is positional-only. + def index(self, item: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + + # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`. + @overload + def sort(self: UserList[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... + + def extend(self, other: Iterable[_T]) -> None: ... + +class UserString(Sequence[UserString]): + data: str + def __init__(self, seq: object) -> None: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __complex__(self) -> complex: ... + def __getnewargs__(self) -> tuple[str]: ... + def __lt__(self, string: str | UserString) -> bool: ... + def __le__(self, string: str | UserString) -> bool: ... + def __gt__(self, string: str | UserString) -> bool: ... + def __ge__(self, string: str | UserString) -> bool: ... + def __eq__(self, string: object) -> bool: ... + def __hash__(self) -> int: ... + def __contains__(self, char: object) -> bool: ... + def __len__(self) -> int: ... + def __getitem__(self, index: SupportsIndex | slice[SupportsIndex | None]) -> Self: ... + def __iter__(self) -> Iterator[Self]: ... + def __reversed__(self) -> Iterator[Self]: ... + def __add__(self, other: object) -> Self: ... + def __radd__(self, other: object) -> Self: ... + def __mul__(self, n: int) -> Self: ... + def __rmul__(self, n: int) -> Self: ... + def __mod__(self, args: Any) -> Self: ... + def __rmod__(self, template: object) -> Self: ... + def capitalize(self) -> Self: ... + def casefold(self) -> Self: ... + def center(self, width: int, *args: Any) -> Self: ... + def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def encode(self: UserString, encoding: str | None = "utf-8", errors: str | None = "strict") -> bytes: ... + def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ... + def expandtabs(self, tabsize: int = 8) -> Self: ... + def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def format(self, *args: Any, **kwds: Any) -> str: ... + def format_map(self, mapping: Mapping[str, Any]) -> str: ... + def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int: ... + def isalpha(self) -> bool: ... + def isalnum(self) -> bool: ... + def isdecimal(self) -> bool: ... + def isdigit(self) -> bool: ... + def isidentifier(self) -> bool: ... + def islower(self) -> bool: ... + def isnumeric(self) -> bool: ... + def isprintable(self) -> bool: ... + def isspace(self) -> bool: ... + def istitle(self) -> bool: ... + def isupper(self) -> bool: ... + def isascii(self) -> bool: ... + def join(self, seq: Iterable[str]) -> str: ... + def ljust(self, width: int, *args: Any) -> Self: ... + def lower(self) -> Self: ... + def lstrip(self, chars: str | None = None) -> Self: ... + maketrans = str.maketrans + def partition(self, sep: str) -> tuple[str, str, str]: ... + def removeprefix(self, prefix: str | UserString, /) -> Self: ... + def removesuffix(self, suffix: str | UserString, /) -> Self: ... + def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ... + def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def rjust(self, width: int, *args: Any) -> Self: ... + def rpartition(self, sep: str) -> tuple[str, str, str]: ... + def rstrip(self, chars: str | None = None) -> Self: ... + def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ... + def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ... + def splitlines(self, keepends: bool = False) -> list[str]: ... + def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ... + def strip(self, chars: str | None = None) -> Self: ... + def swapcase(self) -> Self: ... + def title(self) -> Self: ... + def translate(self, *args: Any) -> Self: ... + def upper(self) -> Self: ... + def zfill(self, width: int) -> Self: ... + +@disjoint_base +class deque(MutableSequence[_T]): + @property + def maxlen(self) -> int | None: ... + + @overload + def __init__(self, *, maxlen: int | None = None) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ... + + def append(self, x: _T, /) -> None: ... + def appendleft(self, x: _T, /) -> None: ... + def copy(self) -> Self: ... + def count(self, x: _T, /) -> int: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def extendleft(self, iterable: Iterable[_T], /) -> None: ... + def insert(self, i: int, x: _T, /) -> None: ... + def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ... + def pop(self) -> _T: ... # type: ignore[override] + def popleft(self) -> _T: ... + def remove(self, value: _T, /) -> None: ... + def rotate(self, n: int = 1, /) -> None: ... + def __copy__(self) -> Self: ... + def __len__(self) -> int: ... + __hash__: ClassVar[None] # type: ignore[assignment] + # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores + def __getitem__(self, key: SupportsIndex, /) -> _T: ... # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... # type: ignore[override] + def __delitem__(self, key: SupportsIndex, /) -> None: ... # type: ignore[override] + def __contains__(self, key: object, /) -> bool: ... + def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... + def __iadd__(self, value: Iterable[_T], /) -> Self: ... + def __add__(self, value: Self, /) -> Self: ... + def __mul__(self, value: int, /) -> Self: ... + def __rmul__(self, value: int, /) -> Self: ... + def __imul__(self, value: int, /) -> Self: ... + def __lt__(self, value: deque[_T], /) -> bool: ... + def __le__(self, value: deque[_T], /) -> bool: ... + def __gt__(self, value: deque[_T], /) -> bool: ... + def __ge__(self, value: deque[_T], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class Counter(dict[_T, int], Generic[_T]): + @overload + def __init__(self, iterable: None = None, /) -> None: ... + @overload + def __init__(self: Counter[str], iterable: None = None, /, **kwargs: int) -> None: ... + @overload + def __init__(self, mapping: SupportsKeysAndGetItem[_T, int], /) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], /) -> None: ... + + def copy(self) -> Self: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... + @classmethod + def fromkeys(cls, iterable: Any, v: int | None = None) -> Never: ... # type: ignore[override] + + @overload + def subtract(self, iterable: None = None, /) -> None: ... + @overload + def subtract(self, mapping: Mapping[_T, int], /) -> None: ... + @overload + def subtract(self, iterable: Iterable[_T], /) -> None: ... + + # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload + # (source code does an `isinstance(other, Mapping)` check) + # + # The second overload is also deliberately different to dict.update() + # (if it were `Iterable[_T] | Iterable[tuple[_T, int]]`, + # the tuples would be added as keys, breaking type safety) + @overload # type: ignore[override] + def update(self, m: Mapping[_T, int], /, **kwargs: int) -> None: ... + @overload + def update(self, iterable: Iterable[_T], /, **kwargs: int) -> None: ... + @overload + def update(self, iterable: None = None, /, **kwargs: int) -> None: ... + + def total(self) -> int: ... + def __missing__(self, key: _T) -> int: ... + def __delitem__(self, elem: object) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __le__(self, other: Counter[Any]) -> bool: ... + def __lt__(self, other: Counter[Any]) -> bool: ... + def __ge__(self, other: Counter[Any]) -> bool: ... + def __gt__(self, other: Counter[Any]) -> bool: ... + def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: ... + def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... + def __and__(self, other: Counter[_T]) -> Counter[_T]: ... + def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + if sys.version_info >= (3, 15): + def __xor__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + + def __pos__(self) -> Counter[_T]: ... + def __neg__(self) -> Counter[_T]: ... + # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc. + def __iadd__(self, other: SupportsItems[_T, int]) -> Self: ... # type: ignore[misc] + def __isub__(self, other: SupportsItems[_T, int]) -> Self: ... + def __iand__(self, other: SupportsItems[_T, int]) -> Self: ... + def __ior__(self, other: SupportsItems[_T, int]) -> Self: ... # type: ignore[override,misc] + if sys.version_info >= (3, 15): + def __ixor__(self, other: Counter[_T]) -> Self: ... # type: ignore[misc] + +# The pure-Python implementations of the "views" classes +# These are exposed at runtime in `collections/__init__.py` +class _OrderedDictKeysView(KeysView[_KT_co]): + def __reversed__(self) -> Iterator[_KT_co]: ... + +class _OrderedDictItemsView(ItemsView[_KT_co, _VT_co]): + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... + +class _OrderedDictValuesView(ValuesView[_VT_co]): + def __reversed__(self) -> Iterator[_VT_co]: ... + +# The C implementations of the "views" classes +# (At runtime, these are called `odict_keys`, `odict_items` and `odict_values`, +# but they are not exposed anywhere) +# pyright doesn't have a specific error code for subclassing error! +@final +@type_check_only +class _odict_keys(dict_keys[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] + def __reversed__(self) -> Iterator[_KT_co]: ... + +@final +@type_check_only +class _odict_items(dict_items[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] + def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... + +@final +@type_check_only +class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] + def __reversed__(self) -> Iterator[_VT_co]: ... + +@disjoint_base +class OrderedDict(dict[_KT, _VT]): + def popitem(self, last: bool = True) -> tuple[_KT, _VT]: ... + def move_to_end(self, key: _KT, last: bool = True) -> None: ... + def copy(self) -> Self: ... + def __reversed__(self) -> Iterator[_KT]: ... + def keys(self) -> _odict_keys[_KT, _VT]: ... + def items(self) -> _odict_items[_KT, _VT]: ... + def values(self) -> _odict_values[_KT, _VT]: ... + + # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences. + # Like dict.fromkeys, its true signature is not expressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ... + + # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + # Same as dict.pop, but accepts keyword arguments + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def __eq__(self, value: object, /) -> bool: ... + + if sys.version_info >= (3, 15): + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[override] + def __ror__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... # type: ignore[override,misc] + @overload + def __ror__( # type: ignore[misc] + self, value: dict[_T1, _T2] | frozendict[_T1, _T2], / + ) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + else: + @overload + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + +@disjoint_base +class defaultdict(dict[_KT, _VT]): + default_factory: Callable[[], _VT] | None + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + @overload + def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ... + @overload + def __init__( + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + map: SupportsKeysAndGetItem[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: defaultdict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + default_factory: Callable[[], _VT] | None, + iterable: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + + def __missing__(self, key: _KT, /) -> _VT: ... + def __copy__(self) -> Self: ... + def copy(self) -> Self: ... + + # defaultdict rejects frozendict in its direct __or__/__ror__ methods, even though dict accepts it. + # See https://github.com/python/cpython/issues/149534. + @overload # type: ignore[override] + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[override] + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + +class ChainMap(MutableMapping[_KT, _VT]): + maps: list[MutableMapping[_KT, _VT]] + def __init__(self, *maps: MutableMapping[_KT, _VT]) -> None: ... + def new_child(self, m: MutableMapping[_KT, _VT] | None = None) -> Self: ... + @property + def parents(self) -> Self: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def __contains__(self, key: object) -> bool: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + + def __missing__(self, key: _KT) -> _VT: ... # undocumented + def __bool__(self) -> bool: ... + + # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. + @overload + def setdefault(self: ChainMap[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def copy(self) -> Self: ... + __copy__ = copy + # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, + # so the signature should be kept in line with `dict.fromkeys`. + if sys.version_info >= (3, 13): + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], /) -> ChainMap[_T, Any | None]: ... + else: + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: ... + + @classmethod + @overload + # Special-case None: the user probably wants to add non-None values later. + def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... + + @overload + def __or__(self, other: Mapping[_KT, _VT]) -> Self: ... + @overload + def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, other: Mapping[_KT, _VT]) -> Self: ... + @overload + def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + + # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... diff --git a/stdlib/collections/abc.pyi b/stdlib/collections/abc.pyi new file mode 100644 index 000000000000..3df2a1d9eb9b --- /dev/null +++ b/stdlib/collections/abc.pyi @@ -0,0 +1,2 @@ +from _collections_abc import * +from _collections_abc import __all__ as __all__ diff --git a/stdlib/colorsys.pyi b/stdlib/colorsys.pyi new file mode 100644 index 000000000000..d4edab12ecc7 --- /dev/null +++ b/stdlib/colorsys.pyi @@ -0,0 +1,15 @@ +from typing import Final + +__all__ = ["rgb_to_yiq", "yiq_to_rgb", "rgb_to_hls", "hls_to_rgb", "rgb_to_hsv", "hsv_to_rgb"] + +def rgb_to_yiq(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def yiq_to_rgb(y: float, i: float, q: float) -> tuple[float, float, float]: ... +def rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def hls_to_rgb(h: float, l: float, s: float) -> tuple[float, float, float]: ... +def rgb_to_hsv(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: ... + +# undocumented +ONE_SIXTH: Final[float] +ONE_THIRD: Final[float] +TWO_THIRD: Final[float] diff --git a/stdlib/compileall.pyi b/stdlib/compileall.pyi new file mode 100644 index 000000000000..49a4c69dd3fb --- /dev/null +++ b/stdlib/compileall.pyi @@ -0,0 +1,51 @@ +from _typeshed import StrPath +from py_compile import PycInvalidationMode +from typing import Any, Protocol, type_check_only + +__all__ = ["compile_dir", "compile_file", "compile_path"] + +@type_check_only +class _SupportsSearch(Protocol): + def search(self, string: str, /) -> Any: ... + +def compile_dir( + dir: StrPath, + maxlevels: int | None = None, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + workers: int = 1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... +def compile_file( + fullname: StrPath, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... +def compile_path( + skip_curdir: bool = ..., + maxlevels: int = 0, + force: bool = False, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, +) -> bool: ... diff --git a/stdlib/compression/__init__.pyi b/stdlib/compression/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/compression/_common/__init__.pyi b/stdlib/compression/_common/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/compression/_common/_streams.pyi b/stdlib/compression/_common/_streams.pyi new file mode 100644 index 000000000000..96aec24d1c2d --- /dev/null +++ b/stdlib/compression/_common/_streams.pyi @@ -0,0 +1,37 @@ +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Protocol, type_check_only + +BUFFER_SIZE = DEFAULT_BUFFER_SIZE + +@type_check_only +class _Reader(Protocol): + def read(self, n: int, /) -> bytes: ... + def seekable(self) -> bool: ... + def seek(self, n: int, /) -> Any: ... + +@type_check_only +class _Decompressor(Protocol): + def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ... + @property + def unused_data(self) -> bytes: ... + @property + def eof(self) -> bool: ... + # `zlib._Decompress` does not have next property, but `DecompressReader` calls it: + # @property + # def needs_input(self) -> bool: ... + +class BaseStream(BufferedIOBase): ... + +class DecompressReader(RawIOBase): + def __init__( + self, + fp: _Reader, + decomp_factory: Callable[..., _Decompressor], # Consider backporting changes to _compression + trailing_error: type[Exception] | tuple[type[Exception], ...] = (), + **decomp_args: Any, # These are passed to decomp_factory. + ) -> None: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... diff --git a/stdlib/compression/bz2.pyi b/stdlib/compression/bz2.pyi new file mode 100644 index 000000000000..9ddc39f27c28 --- /dev/null +++ b/stdlib/compression/bz2.pyi @@ -0,0 +1 @@ +from bz2 import * diff --git a/stdlib/compression/gzip.pyi b/stdlib/compression/gzip.pyi new file mode 100644 index 000000000000..9422a735c590 --- /dev/null +++ b/stdlib/compression/gzip.pyi @@ -0,0 +1 @@ +from gzip import * diff --git a/stdlib/compression/lzma.pyi b/stdlib/compression/lzma.pyi new file mode 100644 index 000000000000..936c3813db4f --- /dev/null +++ b/stdlib/compression/lzma.pyi @@ -0,0 +1 @@ +from lzma import * diff --git a/stdlib/compression/zlib.pyi b/stdlib/compression/zlib.pyi new file mode 100644 index 000000000000..78d176c03ee8 --- /dev/null +++ b/stdlib/compression/zlib.pyi @@ -0,0 +1 @@ +from zlib import * diff --git a/stdlib/compression/zstd/__init__.pyi b/stdlib/compression/zstd/__init__.pyi new file mode 100644 index 000000000000..8673c59a41c2 --- /dev/null +++ b/stdlib/compression/zstd/__init__.pyi @@ -0,0 +1,94 @@ +import enum +from _typeshed import ReadableBuffer +from collections.abc import Iterable, Mapping +from compression.zstd._zstdfile import ZstdFile, open +from typing import Final, final + +import _zstd +from _zstd import ZstdCompressor, ZstdDecompressor, ZstdDict, ZstdError, get_frame_size, zstd_version + +__all__ = ( + # compression.zstd + "COMPRESSION_LEVEL_DEFAULT", + "compress", + "CompressionParameter", + "decompress", + "DecompressionParameter", + "finalize_dict", + "get_frame_info", + "Strategy", + "train_dict", + # compression.zstd._zstdfile + "open", + "ZstdFile", + # _zstd + "get_frame_size", + "zstd_version", + "zstd_version_info", + "ZstdCompressor", + "ZstdDecompressor", + "ZstdDict", + "ZstdError", +) + +zstd_version_info: Final[tuple[int, int, int]] +COMPRESSION_LEVEL_DEFAULT: Final = _zstd.ZSTD_CLEVEL_DEFAULT + +class FrameInfo: + __slots__ = ("decompressed_size", "dictionary_id") + decompressed_size: int + dictionary_id: int + def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ... + +def get_frame_info(frame_buffer: ReadableBuffer) -> FrameInfo: ... +def train_dict(samples: Iterable[ReadableBuffer], dict_size: int) -> ZstdDict: ... +def finalize_dict(zstd_dict: ZstdDict, /, samples: Iterable[ReadableBuffer], dict_size: int, level: int) -> ZstdDict: ... +def compress( + data: ReadableBuffer, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, +) -> bytes: ... +def decompress( + data: ReadableBuffer, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None +) -> bytes: ... + +@final +class CompressionParameter(enum.IntEnum): + compression_level = _zstd.ZSTD_c_compressionLevel + window_log = _zstd.ZSTD_c_windowLog + hash_log = _zstd.ZSTD_c_hashLog + chain_log = _zstd.ZSTD_c_chainLog + search_log = _zstd.ZSTD_c_searchLog + min_match = _zstd.ZSTD_c_minMatch + target_length = _zstd.ZSTD_c_targetLength + strategy = _zstd.ZSTD_c_strategy + enable_long_distance_matching = _zstd.ZSTD_c_enableLongDistanceMatching + ldm_hash_log = _zstd.ZSTD_c_ldmHashLog + ldm_min_match = _zstd.ZSTD_c_ldmMinMatch + ldm_bucket_size_log = _zstd.ZSTD_c_ldmBucketSizeLog + ldm_hash_rate_log = _zstd.ZSTD_c_ldmHashRateLog + content_size_flag = _zstd.ZSTD_c_contentSizeFlag + checksum_flag = _zstd.ZSTD_c_checksumFlag + dict_id_flag = _zstd.ZSTD_c_dictIDFlag + nb_workers = _zstd.ZSTD_c_nbWorkers + job_size = _zstd.ZSTD_c_jobSize + overlap_log = _zstd.ZSTD_c_overlapLog + def bounds(self) -> tuple[int, int]: ... + +@final +class DecompressionParameter(enum.IntEnum): + window_log_max = _zstd.ZSTD_d_windowLogMax + def bounds(self) -> tuple[int, int]: ... + +@final +class Strategy(enum.IntEnum): + fast = _zstd.ZSTD_fast + dfast = _zstd.ZSTD_dfast + greedy = _zstd.ZSTD_greedy + lazy = _zstd.ZSTD_lazy + lazy2 = _zstd.ZSTD_lazy2 + btlazy2 = _zstd.ZSTD_btlazy2 + btopt = _zstd.ZSTD_btopt + btultra = _zstd.ZSTD_btultra + btultra2 = _zstd.ZSTD_btultra2 diff --git a/stdlib/compression/zstd/_zstdfile.pyi b/stdlib/compression/zstd/_zstdfile.pyi new file mode 100644 index 000000000000..b16b43c1da0a --- /dev/null +++ b/stdlib/compression/zstd/_zstdfile.pyi @@ -0,0 +1,117 @@ +from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsWrite, WriteableBuffer +from collections.abc import Mapping +from compression._common import _streams +from compression.zstd import ZstdDict +from io import TextIOWrapper, _WrappedBuffer +from typing import Literal, Protocol, TypeAlias, overload, type_check_only + +from _zstd import ZstdCompressor, _ZstdCompressorFlushBlock, _ZstdCompressorFlushFrame + +__all__ = ("ZstdFile", "open") + +_ReadBinaryMode: TypeAlias = Literal["r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_ReadTextMode: TypeAlias = Literal["rt"] +_WriteTextMode: TypeAlias = Literal["wt", "xt", "at"] + +@type_check_only +class _FileBinaryRead(_streams._Reader, Protocol): + def close(self) -> None: ... + +@type_check_only +class _FileBinaryWrite(SupportsWrite[bytes], Protocol): + def close(self) -> None: ... + +class ZstdFile(_streams.BaseStream): + FLUSH_BLOCK = ZstdCompressor.FLUSH_BLOCK + FLUSH_FRAME = ZstdCompressor.FLUSH_FRAME + + @overload + def __init__( + self, + file: StrOrBytesPath | _FileBinaryRead, + /, + mode: _ReadBinaryMode = "r", + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrOrBytesPath | _FileBinaryWrite, + /, + mode: _WriteBinaryMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> None: ... + + def write(self, data: ReadableBuffer, /) -> int: ... + def flush(self, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 1) -> bytes: ... # type: ignore[override] + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int | None = -1) -> bytes: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + def readline(self, size: int | None = -1) -> bytes: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def peek(self, size: int = -1) -> bytes: ... + @property + def name(self) -> str | bytes: ... + @property + def mode(self) -> Literal["rb", "wb"]: ... + +@overload +def open( + file: StrOrBytesPath | _FileBinaryRead, + /, + mode: _ReadBinaryMode = "rb", + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> ZstdFile: ... +@overload +def open( + file: StrOrBytesPath | _FileBinaryWrite, + /, + mode: _WriteBinaryMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> ZstdFile: ... +@overload +def open( + file: StrOrBytesPath | _WrappedBuffer, + /, + mode: _ReadTextMode, + *, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + file: StrOrBytesPath | _WrappedBuffer, + /, + mode: _WriteTextMode, + *, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... diff --git a/stdlib/concurrent/__init__.pyi b/stdlib/concurrent/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/concurrent/futures/__init__.pyi b/stdlib/concurrent/futures/__init__.pyi new file mode 100644 index 000000000000..ad4d20ea5445 --- /dev/null +++ b/stdlib/concurrent/futures/__init__.pyi @@ -0,0 +1,71 @@ +import sys + +from ._base import ( + ALL_COMPLETED as ALL_COMPLETED, + FIRST_COMPLETED as FIRST_COMPLETED, + FIRST_EXCEPTION as FIRST_EXCEPTION, + BrokenExecutor as BrokenExecutor, + CancelledError as CancelledError, + Executor as Executor, + Future as Future, + InvalidStateError as InvalidStateError, + TimeoutError as TimeoutError, + as_completed as as_completed, + wait as wait, +) +from .process import ProcessPoolExecutor as ProcessPoolExecutor +from .thread import ThreadPoolExecutor as ThreadPoolExecutor + +if sys.version_info >= (3, 14): + from .interpreter import InterpreterPoolExecutor as InterpreterPoolExecutor + + __all__ = [ + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "InvalidStateError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + "InterpreterPoolExecutor", + ] + +elif sys.version_info >= (3, 13): + __all__ = ( + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "InvalidStateError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + ) +else: + __all__ = ( + "FIRST_COMPLETED", + "FIRST_EXCEPTION", + "ALL_COMPLETED", + "CancelledError", + "TimeoutError", + "BrokenExecutor", + "Future", + "Executor", + "wait", + "as_completed", + "ProcessPoolExecutor", + "ThreadPoolExecutor", + ) + +def __dir__() -> tuple[str, ...]: ... diff --git a/stdlib/concurrent/futures/_base.pyi b/stdlib/concurrent/futures/_base.pyi new file mode 100644 index 000000000000..05680b5de461 --- /dev/null +++ b/stdlib/concurrent/futures/_base.pyi @@ -0,0 +1,119 @@ +import sys +import threading +from _typeshed import Unused +from collections.abc import Callable, Iterable, Iterator +from logging import Logger +from types import GenericAlias, TracebackType +from typing import Any, Final, Generic, NamedTuple, ParamSpec, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +FIRST_COMPLETED: Final = "FIRST_COMPLETED" +FIRST_EXCEPTION: Final = "FIRST_EXCEPTION" +ALL_COMPLETED: Final = "ALL_COMPLETED" +PENDING: Final = "PENDING" +RUNNING: Final = "RUNNING" +CANCELLED: Final = "CANCELLED" +CANCELLED_AND_NOTIFIED: Final = "CANCELLED_AND_NOTIFIED" +FINISHED: Final = "FINISHED" +_STATE_TO_DESCRIPTION_MAP: Final[dict[str, str]] +LOGGER: Logger + +class Error(Exception): ... +class CancelledError(Error): ... + +if sys.version_info >= (3, 11): + from builtins import TimeoutError as TimeoutError +else: + class TimeoutError(Error): ... + +class InvalidStateError(Error): ... +class BrokenExecutor(RuntimeError): ... + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_P = ParamSpec("_P") + +class Future(Generic[_T]): + _condition: threading.Condition + _state: str + _result: _T | None + _exception: BaseException | None + _waiters: list[_Waiter] + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def running(self) -> bool: ... + def done(self) -> bool: ... + def add_done_callback(self, fn: Callable[[Future[_T]], object]) -> None: ... + def result(self, timeout: float | None = None) -> _T: ... + def set_running_or_notify_cancel(self) -> bool: ... + def set_result(self, result: _T) -> None: ... + def exception(self, timeout: float | None = None) -> BaseException | None: ... + def set_exception(self, exception: BaseException | None) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class Executor: + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... + if sys.version_info >= (3, 14): + def map( + self, + fn: Callable[..., _T], + *iterables: Iterable[Any], + timeout: float | None = None, + chunksize: int = 1, + buffersize: int | None = None, + ) -> Iterator[_T]: ... + else: + def map( + self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1 + ) -> Iterator[_T]: ... + + def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + +@type_check_only +class _AsCompletedFuture(Protocol[_T_co]): + # as_completed only mutates non-generic aspects of passed Futures and does not do any nominal + # checks. Therefore, we can use a Protocol here to allow as_completed to act covariantly. + # See the tests for concurrent.futures + _condition: threading.Condition + _state: str + _waiters: list[_Waiter] + # Not used by as_completed, but needed to propagate the generic type + def result(self, timeout: float | None = None) -> _T_co: ... + +def as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: ... + +class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): + done: set[Future[_T]] + not_done: set[Future[_T]] + +def wait( + fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" +) -> DoneAndNotDoneFutures[_T]: ... + +class _Waiter: + event: threading.Event + finished_futures: list[Future[Any]] + def add_result(self, future: Future[Any]) -> None: ... + def add_exception(self, future: Future[Any]) -> None: ... + def add_cancelled(self, future: Future[Any]) -> None: ... + +class _AsCompletedWaiter(_Waiter): + lock: threading.Lock + +class _FirstCompletedWaiter(_Waiter): ... + +class _AllCompletedWaiter(_Waiter): + num_pending_calls: int + stop_on_exception: bool + lock: threading.Lock + def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ... + +class _AcquireFutures: + futures: Iterable[Future[Any]] + def __init__(self, futures: Iterable[Future[Any]]) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *args: Unused) -> None: ... diff --git a/stdlib/concurrent/futures/interpreter.pyi b/stdlib/concurrent/futures/interpreter.pyi new file mode 100644 index 000000000000..f6925806a5eb --- /dev/null +++ b/stdlib/concurrent/futures/interpreter.pyi @@ -0,0 +1,82 @@ +import sys +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from typing import Any, Literal, ParamSpec, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, TypeVar, TypeVarTuple, Unpack + +_Task: TypeAlias = tuple[bytes, Literal["function", "script"]] +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") +_R = TypeVar("_R") + +@type_check_only +class _TaskFunc(Protocol): + @overload + def __call__(self, fn: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> tuple[bytes, Literal["function"]]: ... + @overload + def __call__(self, fn: str) -> tuple[bytes, Literal["script"]]: ... + +if sys.version_info >= (3, 14): + from concurrent.futures.thread import BrokenThreadPool, WorkerContext as ThreadWorkerContext + from concurrent.interpreters import Interpreter, Queue + + def do_call(results: Queue, func: Callable[..., _R], args: tuple[Any, ...], kwargs: dict[str, Any]) -> _R: ... + + class WorkerContext(ThreadWorkerContext): + interp: Interpreter | None + results: Queue | None + + @overload # type: ignore[override] + @classmethod + def prepare( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], Self], _TaskFunc]: ... + @overload + @classmethod + def prepare(cls, initializer: Callable[[], object], initargs: tuple[()]) -> tuple[Callable[[], Self], _TaskFunc]: ... + + def __init__(self, initdata: _Task) -> None: ... + def __del__(self) -> None: ... + def run(self, task: _Task) -> None: ... # type: ignore[override] + + class BrokenInterpreterPool(BrokenThreadPool): ... + + class InterpreterPoolExecutor(ThreadPoolExecutor): + BROKEN: type[BrokenInterpreterPool] + + @overload # type: ignore[override] + @classmethod + def prepare_context( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ... + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ... + + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + thread_name_prefix: str, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... diff --git a/stdlib/concurrent/futures/process.pyi b/stdlib/concurrent/futures/process.pyi new file mode 100644 index 000000000000..4dfe17afdc7f --- /dev/null +++ b/stdlib/concurrent/futures/process.pyi @@ -0,0 +1,248 @@ +import sys +from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping, MutableSequence +from multiprocessing.connection import Connection +from multiprocessing.context import BaseContext, Process +from multiprocessing.queues import Queue, SimpleQueue +from threading import Lock, Semaphore, Thread +from types import TracebackType +from typing import Any, Final, Generic, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack +from weakref import ref + +from ._base import BrokenExecutor, Executor, Future + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") + +_threads_wakeups: MutableMapping[Any, Any] +_global_shutdown: bool + +class _ThreadWakeup: + _closed: bool + # Any: Unused send and recv methods + _reader: Connection[Any, Any] + _writer: Connection[Any, Any] + def close(self) -> None: ... + def wakeup(self) -> None: ... + def clear(self) -> None: ... + +def _python_exit() -> None: ... + +EXTRA_QUEUED_CALLS: Final = 1 + +_MAX_WINDOWS_WORKERS: Final = 61 + +class _RemoteTraceback(Exception): + tb: str + def __init__(self, tb: TracebackType) -> None: ... + +class _ExceptionWithTraceback: + exc: BaseException + tb: TracebackType + def __init__(self, exc: BaseException, tb: TracebackType) -> None: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + +def _rebuild_exc(exc: Exception, tb: str) -> Exception: ... + +class _WorkItem(Generic[_T]): + future: Future[_T] + fn: Callable[..., _T] + args: Iterable[Any] + kwargs: Mapping[str, Any] + def __init__(self, future: Future[_T], fn: Callable[..., _T], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + +class _ResultItem: + work_id: int + exception: Exception + result: Any + if sys.version_info >= (3, 11): + exit_pid: int | None + def __init__( + self, work_id: int, exception: Exception | None = None, result: Any | None = None, exit_pid: int | None = None + ) -> None: ... + else: + def __init__(self, work_id: int, exception: Exception | None = None, result: Any | None = None) -> None: ... + +class _CallItem: + work_id: int + fn: Callable[..., Any] + args: Iterable[Any] + kwargs: Mapping[str, Any] + def __init__(self, work_id: int, fn: Callable[..., Any], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + +class _SafeQueue(Queue[Future[Any]]): + pending_work_items: dict[int, _WorkItem[Any]] + if sys.version_info < (3, 12): + shutdown_lock: Lock + thread_wakeup: _ThreadWakeup + if sys.version_info >= (3, 12): + def __init__( + self, + max_size: int | None = 0, + *, + ctx: BaseContext, + pending_work_items: dict[int, _WorkItem[Any]], + thread_wakeup: _ThreadWakeup, + ) -> None: ... + else: + def __init__( + self, + max_size: int | None = 0, + *, + ctx: BaseContext, + pending_work_items: dict[int, _WorkItem[Any]], + shutdown_lock: Lock, + thread_wakeup: _ThreadWakeup, + ) -> None: ... + + def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... + +def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...]]: ... +def _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> list[_T]: ... + +if sys.version_info >= (3, 11): + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], + work_id: int, + result: Any | None = None, + exception: Exception | None = None, + exit_pid: int | None = None, + ) -> None: ... + +else: + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = None, exception: Exception | None = None + ) -> None: ... + +if sys.version_info >= (3, 11): + def _process_worker( + call_queue: Queue[_CallItem], + result_queue: SimpleQueue[_ResultItem], + initializer: Callable[[Unpack[_Ts]], object] | None, + initargs: tuple[Unpack[_Ts]], + max_tasks: int | None = None, + ) -> None: ... + +else: + def _process_worker( + call_queue: Queue[_CallItem], + result_queue: SimpleQueue[_ResultItem], + initializer: Callable[[Unpack[_Ts]], object] | None, + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + +class _ExecutorManagerThread(Thread): + thread_wakeup: _ThreadWakeup + shutdown_lock: Lock + executor_reference: ref[Any] + processes: MutableMapping[int, Process] + call_queue: Queue[_CallItem] + result_queue: SimpleQueue[_ResultItem] + work_ids_queue: Queue[int] + pending_work_items: dict[int, _WorkItem[Any]] + def __init__(self, executor: ProcessPoolExecutor) -> None: ... + def run(self) -> None: ... + def add_call_item_to_queue(self) -> None: ... + def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... + def process_result_item(self, result_item: int | _ResultItem) -> None: ... + def is_shutting_down(self) -> bool: ... + + if sys.version_info >= (3, 14): + # bpe_message parameter added in 3.14.7 + def terminate_broken(self, cause: str, bpe_message: str | None = None) -> None: ... + else: + def terminate_broken(self, cause: str) -> None: ... + + def flag_executor_shutting_down(self) -> None: ... + def shutdown_workers(self) -> None: ... + def join_executor_internals(self) -> None: ... + def get_n_children_alive(self) -> int: ... + +_system_limits_checked: bool +_system_limited: bool | None + +def _check_system_limits() -> None: ... +def _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> Any: ... + +class BrokenProcessPool(BrokenExecutor): ... + +class ProcessPoolExecutor(Executor): + _mp_context: BaseContext | None + _initializer: Callable[..., None] | None + _initargs: tuple[Any, ...] + _executor_manager_thread: _ThreadWakeup + _processes: MutableMapping[int, Process] + _shutdown_thread: bool + _shutdown_lock: Lock + _idle_worker_semaphore: Semaphore + _broken: bool + _queue_count: int + _pending_work_items: dict[int, _WorkItem[Any]] + _cancel_pending_futures: bool + _executor_manager_thread_wakeup: _ThreadWakeup + _result_queue: SimpleQueue[Any] + _work_ids: Queue[Any] + if sys.version_info >= (3, 11): + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + *, + max_tasks_per_child: int | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + max_tasks_per_child: int | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + mp_context: BaseContext | None, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + *, + max_tasks_per_child: int | None = None, + ) -> None: ... + else: + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + mp_context: BaseContext | None = None, + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + mp_context: BaseContext | None, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + + def _start_executor_manager_thread(self) -> None: ... + def _adjust_process_count(self) -> None: ... + + if sys.version_info >= (3, 14): + def kill_workers(self) -> None: ... + def terminate_workers(self) -> None: ... diff --git a/stdlib/concurrent/futures/thread.pyi b/stdlib/concurrent/futures/thread.pyi new file mode 100644 index 000000000000..685bf1cfc104 --- /dev/null +++ b/stdlib/concurrent/futures/thread.pyi @@ -0,0 +1,143 @@ +import queue +import sys +from collections.abc import Callable, Iterable, Mapping, Set as AbstractSet +from threading import Lock, Semaphore, Thread +from types import GenericAlias +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack +from weakref import ref + +from ._base import BrokenExecutor, Executor, Future + +_Ts = TypeVarTuple("_Ts") + +_threads_queues: Mapping[Any, Any] +_shutdown: bool +_global_shutdown_lock: Lock + +def _python_exit() -> None: ... + +_S = TypeVar("_S") + +_Task: TypeAlias = tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]] + +_C = TypeVar("_C", bound=Callable[..., object]) +_KT = TypeVar("_KT", bound=str) +_VT = TypeVar("_VT") + +@type_check_only +class _ResolveTaskFunc(Protocol): + def __call__( + self, func: _C, args: tuple[Unpack[_Ts]], kwargs: dict[_KT, _VT] + ) -> tuple[_C, tuple[Unpack[_Ts]], dict[_KT, _VT]]: ... + +if sys.version_info >= (3, 14): + class WorkerContext: + @overload + @classmethod + def prepare( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ... + @overload + @classmethod + def prepare( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ... + + @overload + def __init__(self, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]) -> None: ... + @overload + def __init__(self, initializer: Callable[[], object], initargs: tuple[()]) -> None: ... + + def initialize(self) -> None: ... + def finalize(self) -> None: ... + def run(self, task: _Task) -> None: ... + +if sys.version_info >= (3, 14): + class _WorkItem(Generic[_S]): + future: Future[Any] + task: _Task + def __init__(self, future: Future[Any], task: _Task) -> None: ... + def run(self, ctx: WorkerContext) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def _worker(executor_reference: ref[Any], ctx: WorkerContext, work_queue: queue.SimpleQueue[Any]) -> None: ... + +else: + class _WorkItem(Generic[_S]): + future: Future[_S] + fn: Callable[..., _S] + args: Iterable[Any] + kwargs: Mapping[str, Any] + def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... + def run(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def _worker( + executor_reference: ref[Any], + work_queue: queue.SimpleQueue[Any], + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + +class BrokenThreadPool(BrokenExecutor): ... + +class ThreadPoolExecutor(Executor): + if sys.version_info >= (3, 14): + BROKEN: type[BrokenThreadPool] + + _max_workers: int + _idle_semaphore: Semaphore + _threads: AbstractSet[Thread] + _broken: bool + _shutdown: bool + _shutdown_lock: Lock + _thread_name_prefix: str | None + if sys.version_info >= (3, 14): + _create_worker_context: Callable[[], WorkerContext] + _resolve_work_item_task: _ResolveTaskFunc + else: + _initializer: Callable[..., None] | None + _initargs: tuple[Any, ...] + _work_queue: queue.SimpleQueue[_WorkItem[Any]] + + if sys.version_info >= (3, 14): + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[], object], initargs: tuple[()] + ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ... + @overload + @classmethod + def prepare_context( + cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] + ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ... + + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + initializer: Callable[[], object] | None = None, + initargs: tuple[()] = (), + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None = None, + thread_name_prefix: str = "", + *, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + @overload + def __init__( + self, + max_workers: int | None, + thread_name_prefix: str, + initializer: Callable[[Unpack[_Ts]], object], + initargs: tuple[Unpack[_Ts]], + ) -> None: ... + + def _adjust_thread_count(self) -> None: ... + def _initializer_failed(self) -> None: ... diff --git a/stdlib/concurrent/interpreters/__init__.pyi b/stdlib/concurrent/interpreters/__init__.pyi new file mode 100644 index 000000000000..d19db0964260 --- /dev/null +++ b/stdlib/concurrent/interpreters/__init__.pyi @@ -0,0 +1,68 @@ +import sys +import threading +import types +from collections.abc import Callable +from typing import Any, Literal, ParamSpec, TypeVar +from typing_extensions import Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpreters import ( + InterpreterError as InterpreterError, + InterpreterNotFoundError as InterpreterNotFoundError, + NotShareableError as NotShareableError, + _SharedDict, + _Whence, + is_shareable as is_shareable, + ) + + from ._queues import Queue as Queue, QueueEmpty as QueueEmpty, QueueFull as QueueFull, create as create_queue + + __all__ = [ + "ExecutionFailed", + "Interpreter", + "InterpreterError", + "InterpreterNotFoundError", + "NotShareableError", + "Queue", + "QueueEmpty", + "QueueFull", + "create", + "create_queue", + "get_current", + "get_main", + "is_shareable", + "list_all", + ] + + _R = TypeVar("_R") + _P = ParamSpec("_P") + + class ExecutionFailed(InterpreterError): + excinfo: types.SimpleNamespace + + def __init__(self, excinfo: types.SimpleNamespace) -> None: ... + + def create() -> Interpreter: ... + def list_all() -> list[Interpreter]: ... + def get_current() -> Interpreter: ... + def get_main() -> Interpreter: ... + + class Interpreter: + def __new__(cls, id: int, /, _whence: _Whence | None = None, _ownsref: bool | None = None) -> Self: ... + def __reduce__(self) -> tuple[type[Self], int]: ... + def __hash__(self) -> int: ... + def __del__(self) -> None: ... + @property + def id(self) -> int: ... + @property + def whence( + self, + ) -> Literal["unknown", "runtime init", "legacy C-API", "C-API", "cross-interpreter C-API", "_interpreters module"]: ... + def is_running(self) -> bool: ... + def close(self) -> None: ... + def prepare_main( + self, ns: _SharedDict | None = None, /, **kwargs: Any + ) -> None: ... # kwargs has same value restrictions as _SharedDict + def exec(self, code: str | types.CodeType | Callable[[], object], /) -> None: ... + def call(self, callable: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + def call_in_thread(self, callable: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> threading.Thread: ... diff --git a/stdlib/concurrent/interpreters/_crossinterp.pyi b/stdlib/concurrent/interpreters/_crossinterp.pyi new file mode 100644 index 000000000000..c8e29aaafa18 --- /dev/null +++ b/stdlib/concurrent/interpreters/_crossinterp.pyi @@ -0,0 +1,30 @@ +import sys +from collections.abc import Callable +from typing import Final, NewType, TypeAlias +from typing_extensions import Never, Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpqueues import _UnboundOp + + class ItemInterpreterDestroyed(Exception): ... + # Actually a descriptor that behaves similarly to classmethod but prevents + # access from instances. + classonly = classmethod + + class UnboundItem: + __slots__ = () + def __new__(cls) -> Never: ... + @classonly + def singleton(cls, kind: str, module: str, name: str = "UNBOUND") -> Self: ... + + # Sentinel types and alias that don't exist at runtime. + _UnboundErrorType = NewType("_UnboundErrorType", object) + _UnboundRemoveType = NewType("_UnboundRemoveType", object) + _AnyUnbound: TypeAlias = _UnboundErrorType | _UnboundRemoveType | UnboundItem + + UNBOUND_ERROR: Final[_UnboundErrorType] + UNBOUND_REMOVE: Final[_UnboundRemoveType] + UNBOUND: Final[UnboundItem] # analogous to UNBOUND_REPLACE in C + + def serialize_unbound(unbound: _AnyUnbound) -> tuple[_UnboundOp]: ... + def resolve_unbound(flag: _UnboundOp, exctype_destroyed: Callable[[str], BaseException]) -> UnboundItem: ... diff --git a/stdlib/concurrent/interpreters/_queues.pyi b/stdlib/concurrent/interpreters/_queues.pyi new file mode 100644 index 000000000000..b4a4fd56dd45 --- /dev/null +++ b/stdlib/concurrent/interpreters/_queues.pyi @@ -0,0 +1,74 @@ +import queue +import sys +from typing import Final, SupportsIndex +from typing_extensions import Self + +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 + from _interpqueues import QueueError as QueueError, QueueNotFoundError as QueueNotFoundError + + from . import _crossinterp + from ._crossinterp import UNBOUND_ERROR as UNBOUND_ERROR, UNBOUND_REMOVE as UNBOUND_REMOVE, UnboundItem, _AnyUnbound + + __all__ = [ + "UNBOUND", + "UNBOUND_ERROR", + "UNBOUND_REMOVE", + "ItemInterpreterDestroyed", + "Queue", + "QueueEmpty", + "QueueError", + "QueueFull", + "QueueNotFoundError", + "create", + "list_all", + ] + + class QueueEmpty(QueueError, queue.Empty): ... + class QueueFull(QueueError, queue.Full): ... + class ItemInterpreterDestroyed(QueueError, _crossinterp.ItemInterpreterDestroyed): ... + UNBOUND: Final[UnboundItem] + + def create(maxsize: int = 0, *, unbounditems: _AnyUnbound = ...) -> Queue: ... + def list_all() -> list[Queue]: ... + + class Queue: + def __new__(cls, id: int, /) -> Self: ... + def __del__(self) -> None: ... + def __hash__(self) -> int: ... + def __reduce__(self) -> tuple[type[Self], int]: ... + @property + def id(self) -> int: ... + @property + def unbounditems(self) -> _AnyUnbound: ... + @property + def maxsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def qsize(self) -> int: ... + if sys.version_info >= (3, 14): + def put( + self, + obj: object, + block: bool = True, + timeout: SupportsIndex | None = None, + *, + unbounditems: _AnyUnbound | None = None, + _delay: float = 0.01, + ) -> None: ... + else: + def put( + self, + obj: object, + timeout: SupportsIndex | None = None, + *, + unbounditems: _AnyUnbound | None = None, + _delay: float = 0.01, + ) -> None: ... + + def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ... + if sys.version_info >= (3, 14): + def get(self, block: bool = True, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ... + else: + def get(self, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ... + + def get_nowait(self) -> object: ... diff --git a/stdlib/configparser.pyi b/stdlib/configparser.pyi new file mode 100644 index 000000000000..385336ec154a --- /dev/null +++ b/stdlib/configparser.pyi @@ -0,0 +1,507 @@ +import sys +from _typeshed import BytesPath, GenericPath, MaybeNone, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence +from re import Pattern +from typing import Any, AnyStr, ClassVar, Final, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import deprecated + +if sys.version_info >= (3, 14): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "MultilineContinuationError", + "UnnamedSectionDisabledError", + "InvalidWriteError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + "UNNAMED_SECTION", + ) +elif sys.version_info >= (3, 13): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + "UNNAMED_SECTION", + "MultilineContinuationError", + ) +elif sys.version_info >= (3, 12): + __all__ = ( + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ) +else: + __all__ = [ + "NoSectionError", + "DuplicateOptionError", + "DuplicateSectionError", + "NoOptionError", + "InterpolationError", + "InterpolationDepthError", + "InterpolationMissingOptionError", + "InterpolationSyntaxError", + "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", + "SafeConfigParser", + "RawConfigParser", + "Interpolation", + "BasicInterpolation", + "ExtendedInterpolation", + "LegacyInterpolation", + "SectionProxy", + "ConverterMapping", + "DEFAULTSECT", + "MAX_INTERPOLATION_DEPTH", + ] + +if sys.version_info >= (3, 13): + @type_check_only + class _UNNAMED_SECTION: ... + + UNNAMED_SECTION: _UNNAMED_SECTION + + _SectionName: TypeAlias = str | _UNNAMED_SECTION + # A list of sections can only include an unnamed section if the parser was initialized with + # allow_unnamed_section=True. Any prevents users from having to use explicit + # type checks if allow_unnamed_section is False (the default). + _SectionNameList: TypeAlias = list[Any] +else: + _SectionName: TypeAlias = str + _SectionNameList: TypeAlias = list[str] + +_Section: TypeAlias = Mapping[str, str] +_Parser: TypeAlias = MutableMapping[str, _Section] +_ConverterCallback: TypeAlias = Callable[[str], Any] +_ConvertersMap: TypeAlias = dict[str, _ConverterCallback] +_T = TypeVar("_T") + +DEFAULTSECT: Final = "DEFAULT" +MAX_INTERPOLATION_DEPTH: Final = 10 + +class Interpolation: + def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, defaults: _Section) -> str: ... + def before_set(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... + def before_read(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... + def before_write(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ... + +class BasicInterpolation(Interpolation): ... +class ExtendedInterpolation(Interpolation): ... + +if sys.version_info < (3, 13): + @deprecated( + "Deprecated since Python 3.2; removed in Python 3.13. Use `BasicInterpolation` or `ExtendedInterpolation` instead." + ) + class LegacyInterpolation(Interpolation): + def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, vars: _Section) -> str: ... + +class RawConfigParser(_Parser): + _SECT_TMPL: ClassVar[str] # undocumented + _OPT_TMPL: ClassVar[str] # undocumented + _OPT_NV_TMPL: ClassVar[str] # undocumented + + SECTCRE: Pattern[str] + OPTCRE: ClassVar[Pattern[str]] + OPTCRE_NV: ClassVar[Pattern[str]] # undocumented + NONSPACECRE: ClassVar[Pattern[str]] # undocumented + + BOOLEAN_STATES: ClassVar[Mapping[str, bool]] # undocumented + default_section: str + if sys.version_info >= (3, 13): + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None = None, + dict_type: type[Mapping[str, str]] = ..., + *, + allow_no_value: Literal[True], + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None, + dict_type: type[Mapping[str, str]], + allow_no_value: Literal[True], + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + @overload + def __init__( + self, + defaults: _Section | None = None, + dict_type: type[Mapping[str, str]] = ..., + allow_no_value: bool = False, + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + else: + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None = None, + dict_type: type[Mapping[str, str]] = ..., + *, + allow_no_value: Literal[True], + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + @overload + def __init__( + self, + defaults: Mapping[str, str | None] | None, + dict_type: type[Mapping[str, str]], + allow_no_value: Literal[True], + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + @overload + def __init__( + self, + defaults: _Section | None = None, + dict_type: type[Mapping[str, str]] = ..., + allow_no_value: bool = False, + *, + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: Interpolation | None = ..., + converters: _ConvertersMap = ..., + ) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, key: _SectionName) -> SectionProxy: ... + def __setitem__(self, key: _SectionName, value: _Section) -> None: ... + def __delitem__(self, key: _SectionName) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __contains__(self, key: object) -> bool: ... + def defaults(self) -> _Section: ... + def sections(self) -> _SectionNameList: ... + def add_section(self, section: _SectionName) -> None: ... + def has_section(self, section: _SectionName) -> bool: ... + def options(self, section: _SectionName) -> list[str]: ... + def has_option(self, section: _SectionName, option: str) -> bool: ... + + @overload + def read(self, filenames: GenericPath[AnyStr], encoding: str | None = None) -> list[AnyStr]: ... + @overload + def read(self, filenames: Iterable[StrPath], encoding: str | None = None) -> list[str]: ... + @overload + def read(self, filenames: Iterable[BytesPath], encoding: str | None = None) -> list[bytes]: ... + @overload + def read(self, filenames: Iterable[StrOrBytesPath], encoding: str | None = None) -> list[str | bytes]: ... + + def read_file(self, f: Iterable[str], source: str | None = None) -> None: ... + def read_string(self, string: str, source: str = "") -> None: ... + def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = "") -> None: ... + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `parser.read_file()` instead.") + def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ... + + # These get* methods are partially applied (with the same names) in + # SectionProxy; the stubs should be kept updated together + @overload + def getint(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> int: ... + @overload + def getint( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> int | _T: ... + + @overload + def getfloat(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ... + @overload + def getfloat( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> float | _T: ... + + @overload + def getboolean(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ... + @overload + def getboolean( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> bool | _T: ... + + def _get_conv( + self, + section: _SectionName, + option: str, + conv: Callable[[str], _T], + *, + raw: bool = False, + vars: _Section | None = None, + fallback: _T = ..., + ) -> _T: ... + + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore[override] + def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: ... + @overload + def get( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> str | _T | MaybeNone: ... + + @overload + def items(self, *, raw: bool = False, vars: _Section | None = None) -> ItemsView[str, SectionProxy]: ... + @overload + def items(self, section: _SectionName, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ... + + def set(self, section: _SectionName, option: str, value: str | None = None) -> None: ... + def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = True) -> None: ... + def remove_option(self, section: _SectionName, option: str) -> bool: ... + def remove_section(self, section: _SectionName) -> bool: ... + def optionxform(self, optionstr: str) -> str: ... + @property + def converters(self) -> ConverterMapping: ... + +class ConfigParser(RawConfigParser): + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore[override] + def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str: ... + @overload + def get( + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T + ) -> str | _T: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `ConfigParser` instead.") + class SafeConfigParser(ConfigParser): ... + +class SectionProxy(MutableMapping[str, str]): + def __init__(self, parser: RawConfigParser, name: str) -> None: ... + def __getitem__(self, key: str) -> str: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + @property + def parser(self) -> RawConfigParser: ... + @property + def name(self) -> str: ... + + # This is incompatible with MutableMapping so we ignore the type + @overload # type: ignore[override] + def get( + self, + option: str, + fallback: None = None, + *, + raw: bool = False, + vars: _Section | None = None, + _impl: Any | None = None, + **kwargs: Any, # passed to the underlying parser's get() method + ) -> str | None: ... + @overload + def get( + self, + option: str, + fallback: _T, + *, + raw: bool = False, + vars: _Section | None = None, + _impl: Any | None = None, + **kwargs: Any, # passed to the underlying parser's get() method + ) -> str | _T: ... + + # These are partially-applied version of the methods with the same names in + # RawConfigParser; the stubs should be kept updated together + @overload + def getint(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> int | None: ... + @overload + def getint(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> int | _T: ... + + @overload + def getfloat(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> float | None: ... + @overload + def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> float | _T: ... + + @overload + def getboolean(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool | None: ... + @overload + def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> bool | _T: ... + + # SectionProxy can have arbitrary attributes when custom converters are used + def __getattr__(self, key: str) -> Callable[..., Any]: ... + +class ConverterMapping(MutableMapping[str, _ConverterCallback | None]): + GETTERCRE: ClassVar[Pattern[Any]] + def __init__(self, parser: RawConfigParser) -> None: ... + def __getitem__(self, key: str) -> _ConverterCallback: ... + def __setitem__(self, key: str, value: _ConverterCallback | None) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class Error(Exception): + message: str + def __init__(self, msg: str = "") -> None: ... + +class NoSectionError(Error): + section: _SectionName + def __init__(self, section: _SectionName) -> None: ... + +class DuplicateSectionError(Error): + section: _SectionName + source: str | None + lineno: int | None + def __init__(self, section: _SectionName, source: str | None = None, lineno: int | None = None) -> None: ... + +class DuplicateOptionError(Error): + section: _SectionName + option: str + source: str | None + lineno: int | None + def __init__(self, section: _SectionName, option: str, source: str | None = None, lineno: int | None = None) -> None: ... + +class NoOptionError(Error): + section: _SectionName + option: str + def __init__(self, option: str, section: _SectionName) -> None: ... + +class InterpolationError(Error): + section: _SectionName + option: str + def __init__(self, option: str, section: _SectionName, msg: str) -> None: ... + +class InterpolationDepthError(InterpolationError): + def __init__(self, option: str, section: _SectionName, rawval: object) -> None: ... + +class InterpolationMissingOptionError(InterpolationError): + reference: str + def __init__(self, option: str, section: _SectionName, rawval: object, reference: str) -> None: ... + +class InterpolationSyntaxError(InterpolationError): ... + +class ParsingError(Error): + source: str + errors: list[tuple[int, str]] + if sys.version_info >= (3, 13): + def __init__(self, source: str, *args: object) -> None: ... + def combine(self, others: Iterable[ParsingError]) -> ParsingError: ... + elif sys.version_info >= (3, 12): + def __init__(self, source: str) -> None: ... + else: + @overload + def __init__(self, source: str) -> None: ... + @overload + @deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.") + def __init__(self, source: None, filename: str | None) -> None: ... + @overload + @deprecated("The `filename` parameter removed in Python 3.12. Use `source` instead.") + def __init__(self, source: None = None, *, filename: str | None) -> None: ... + + def append(self, lineno: int, line: str) -> None: ... + + if sys.version_info < (3, 12): + @property + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.") + def filename(self) -> str: ... + @filename.setter + @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.") + def filename(self, value: str) -> None: ... + +class MissingSectionHeaderError(ParsingError): + lineno: int + line: str + def __init__(self, filename: str, lineno: int, line: str) -> None: ... + +if sys.version_info >= (3, 13): + class MultilineContinuationError(ParsingError): + lineno: int + line: str + def __init__(self, filename: str, lineno: int, line: str) -> None: ... + +if sys.version_info >= (3, 14): + class UnnamedSectionDisabledError(Error): + msg: Final = "Support for UNNAMED_SECTION is disabled." + def __init__(self) -> None: ... + + class InvalidWriteError(Error): ... diff --git a/stdlib/contextlib.pyi b/stdlib/contextlib.pyi new file mode 100644 index 000000000000..c286514af229 --- /dev/null +++ b/stdlib/contextlib.pyi @@ -0,0 +1,224 @@ +import abc +import sys +from _typeshed import FileDescriptorOrPath, Unused +from abc import ABC, abstractmethod +from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator +from types import TracebackType +from typing import Any, Generic, ParamSpec, Protocol, TypeAlias, TypeVar, overload, runtime_checkable, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "aclosing", + "contextmanager", + "closing", + "AbstractContextManager", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", + "AbstractAsyncContextManager", + "AsyncExitStack", + "asynccontextmanager", + "nullcontext", +] + +if sys.version_info >= (3, 11): + __all__ += ["chdir"] + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_ExitT_co = TypeVar("_ExitT_co", covariant=True, bound=bool | None, default=bool | None) +_F = TypeVar("_F", bound=Callable[..., Any]) +_G_co = TypeVar("_G_co", bound=Generator[Any, Any, Any] | AsyncGenerator[Any, Any], covariant=True) +_P = ParamSpec("_P") + +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) + +_ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] +_CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc) + +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it is on the +# allowlist for use as a Protocol. +@runtime_checkable +class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + def __enter__(self) -> _T_co: ... + @abstractmethod + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it is on the +# allowlist for use as a Protocol. +@runtime_checkable +class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + async def __aenter__(self) -> _T_co: ... + @abstractmethod + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +class ContextDecorator: + def _recreate_cm(self) -> Self: ... + def __call__(self, func: _F) -> _F: ... + +class _GeneratorContextManagerBase(Generic[_G_co]): + # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676 + def __init__(self, func: Callable[..., _G_co], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... + gen: _G_co + func: Callable[..., _G_co] + args: tuple[Any, ...] + kwds: dict[str, Any] + +class _GeneratorContextManager( + _GeneratorContextManagerBase[Generator[_T_co, _SendT_contra, _ReturnT_co]], + AbstractContextManager[_T_co, bool | None], + ContextDecorator, +): + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +@overload +def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead." +) +def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... + +_AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + +class AsyncContextDecorator: + def _recreate_cm(self) -> Self: ... + def __call__(self, func: _AF) -> _AF: ... + +class _AsyncGeneratorContextManager( + _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], + AbstractAsyncContextManager[_T_co, bool | None], + AsyncContextDecorator, +): + async def __aexit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +@overload +def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. " + "Use `-> AsyncGenerator[Foo]` instead." +) +def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... + +@type_check_only +class _SupportsClose(Protocol): + def close(self) -> object: ... + +_SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) + +class closing(AbstractContextManager[_SupportsCloseT, None]): + def __init__(self, thing: _SupportsCloseT) -> None: ... + def __exit__(self, *exc_info: Unused) -> None: ... + +@type_check_only +class _SupportsAclose(Protocol): + def aclose(self) -> Awaitable[object]: ... + +_SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) + +class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): + def __init__(self, thing: _SupportsAcloseT) -> None: ... + async def __aexit__(self, *exc_info: Unused) -> None: ... + +class suppress(AbstractContextManager[None, bool]): + def __init__(self, *exceptions: type[BaseException]) -> None: ... + def __exit__( + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + ) -> bool: ... + +# This is trying to describe what is needed for (most?) uses +# of `redirect_stdout` and `redirect_stderr`. +# https://github.com/python/typeshed/issues/14903 +@type_check_only +class _SupportsRedirect(Protocol): + def write(self, s: str, /) -> int: ... + def flush(self) -> None: ... + +_SupportsRedirectT = TypeVar("_SupportsRedirectT", bound=_SupportsRedirect | None) + +class _RedirectStream(AbstractContextManager[_SupportsRedirectT, None]): + def __init__(self, new_target: _SupportsRedirectT) -> None: ... + def __exit__( + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + ) -> None: ... + +class redirect_stdout(_RedirectStream[_SupportsRedirectT]): ... +class redirect_stderr(_RedirectStream[_SupportsRedirectT]): ... + +class _BaseExitStack(Generic[_ExitT_co]): + def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ... + def push(self, exit: _CM_EF) -> _CM_EF: ... + def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... + def pop_all(self) -> Self: ... + +# this class is to avoid putting `metaclass=abc.ABCMeta` on the implementations directly, as this would make them +# appear explicitly abstract to some tools. this is due to the implementations not subclassing `AbstractContextManager` +# see note on the subclasses +@type_check_only +class _BaseExitStackAbstract(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): ... + +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class ExitStack(_BaseExitStackAbstract[_ExitT_co]): + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +_ExitCoroFunc: TypeAlias = Callable[ + [type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool | None] +] +_ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc) + +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class AsyncExitStack(_BaseExitStackAbstract[_ExitT_co]): + async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ... + def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... + def push_async_callback( + self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs + ) -> Callable[_P, Awaitable[_T]]: ... + async def aclose(self) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> _ExitT_co: ... + +class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): + enter_result: _T + + @overload + def __init__(self: nullcontext[None]) -> None: ... + @overload + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + + def __enter__(self) -> _T: ... + def __exit__(self, *exctype: Unused) -> None: ... + async def __aenter__(self) -> _T: ... + async def __aexit__(self, *exctype: Unused) -> None: ... + +if sys.version_info >= (3, 11): + _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath) + + class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]): + path: _T_fd_or_any_path + def __init__(self, path: _T_fd_or_any_path) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *excinfo: Unused) -> None: ... diff --git a/stdlib/contextvars.pyi b/stdlib/contextvars.pyi new file mode 100644 index 000000000000..22dc33006e9d --- /dev/null +++ b/stdlib/contextvars.pyi @@ -0,0 +1,3 @@ +from _contextvars import Context as Context, ContextVar as ContextVar, Token as Token, copy_context as copy_context + +__all__ = ("Context", "ContextVar", "Token", "copy_context") diff --git a/stdlib/copy.pyi b/stdlib/copy.pyi new file mode 100644 index 000000000000..925bed1aada2 --- /dev/null +++ b/stdlib/copy.pyi @@ -0,0 +1,33 @@ +import sys +from typing import Any, Protocol, TypeVar, type_check_only + +__all__ = ["Error", "copy", "deepcopy"] + +_T = TypeVar("_T") +_RT_co = TypeVar("_RT_co", covariant=True) + +@type_check_only +class _SupportsReplace(Protocol[_RT_co]): + # In reality doesn't support args, but there's no great way to express this. + def __replace__(self, /, *_: Any, **changes: Any) -> _RT_co: ... + +# None in CPython but non-None in Jython +PyStringMap: Any + +def copy(x: _T) -> _T: ... + +if sys.version_info >= (3, 15): + def deepcopy(x: _T, memo: dict[int, Any] | None = None) -> _T: ... + +else: + # Note: memo and _nil are internal kwargs. + def deepcopy(x: _T, memo: dict[int, Any] | None = None, _nil: Any = []) -> _T: ... + +if sys.version_info >= (3, 13): + __all__ += ["replace"] + # The types accepted by `**changes` match those of `obj.__replace__`. + def replace(obj: _SupportsReplace[_RT_co], /, **changes: Any) -> _RT_co: ... + +class Error(Exception): ... + +error = Error diff --git a/stdlib/copyreg.pyi b/stdlib/copyreg.pyi new file mode 100644 index 000000000000..3bfc0de8158f --- /dev/null +++ b/stdlib/copyreg.pyi @@ -0,0 +1,20 @@ +from collections.abc import Callable, Hashable +from typing import Any, SupportsInt, TypeAlias, TypeVar + +_T = TypeVar("_T") +_Reduce: TypeAlias = tuple[Callable[..., _T], tuple[Any, ...]] | tuple[Callable[..., _T], tuple[Any, ...], Any | None] + +__all__ = ["pickle", "constructor", "add_extension", "remove_extension", "clear_extension_cache"] + +def pickle( + ob_type: type[_T], + pickle_function: Callable[[_T], str | _Reduce[_T]], + constructor_ob: Callable[[_Reduce[_T]], _T] | None = None, +) -> None: ... +def constructor(object: Callable[[_Reduce[_T]], _T]) -> None: ... +def add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ... +def remove_extension(module: Hashable, name: Hashable, code: int) -> None: ... +def clear_extension_cache() -> None: ... + +_DispatchTableType: TypeAlias = dict[type, Callable[[Any], str | _Reduce[Any]]] # imported by multiprocessing.reduction +dispatch_table: _DispatchTableType # undocumented diff --git a/stdlib/crypt.pyi b/stdlib/crypt.pyi new file mode 100644 index 000000000000..f92632196989 --- /dev/null +++ b/stdlib/crypt.pyi @@ -0,0 +1,26 @@ +import sys +from typing import Final, NamedTuple, type_check_only +from typing_extensions import disjoint_base + +if sys.platform != "win32": + @type_check_only + class _MethodBase(NamedTuple): + name: str + ident: str | None + salt_chars: int + total_size: int + + if sys.version_info >= (3, 12): + class _Method(_MethodBase): ... + else: + @disjoint_base + class _Method(_MethodBase): ... + + METHOD_CRYPT: Final[_Method] + METHOD_MD5: Final[_Method] + METHOD_SHA256: Final[_Method] + METHOD_SHA512: Final[_Method] + METHOD_BLOWFISH: Final[_Method] + methods: list[_Method] + def mksalt(method: _Method | None = None, *, rounds: int | None = None) -> str: ... + def crypt(word: str, salt: str | _Method | None = None) -> str: ... diff --git a/stdlib/csv.pyi b/stdlib/csv.pyi new file mode 100644 index 000000000000..f8ab5f000a04 --- /dev/null +++ b/stdlib/csv.pyi @@ -0,0 +1,153 @@ +import sys +from _csv import ( + QUOTE_ALL as QUOTE_ALL, + QUOTE_MINIMAL as QUOTE_MINIMAL, + QUOTE_NONE as QUOTE_NONE, + QUOTE_NONNUMERIC as QUOTE_NONNUMERIC, + Error as Error, + __version__ as __version__, + _DialectLike, + _QuotingType, + field_size_limit as field_size_limit, + get_dialect as get_dialect, + list_dialects as list_dialects, + reader as reader, + register_dialect as register_dialect, + unregister_dialect as unregister_dialect, + writer as writer, +) + +if sys.version_info >= (3, 12): + from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS +from _csv import Reader, Writer +from _typeshed import SupportsWrite +from collections.abc import Collection, Iterable, Mapping, Sequence +from types import GenericAlias +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +__all__ = [ + "QUOTE_MINIMAL", + "QUOTE_ALL", + "QUOTE_NONNUMERIC", + "QUOTE_NONE", + "Error", + "Dialect", + "excel", + "excel_tab", + "field_size_limit", + "reader", + "writer", + "register_dialect", + "get_dialect", + "list_dialects", + "Sniffer", + "unregister_dialect", + "DictReader", + "DictWriter", + "unix_dialect", +] +if sys.version_info >= (3, 12): + __all__ += ["QUOTE_STRINGS", "QUOTE_NOTNULL"] +if sys.version_info < (3, 13): + __all__ += ["__doc__", "__version__"] + +_T = TypeVar("_T") + +class Dialect: + delimiter: str + quotechar: str | None + escapechar: str | None + doublequote: bool + skipinitialspace: bool + lineterminator: str + quoting: _QuotingType + strict: bool + def __init__(self) -> None: ... + +class excel(Dialect): ... +class excel_tab(excel): ... +class unix_dialect(Dialect): ... + +class DictReader(Generic[_T]): + fieldnames: Sequence[_T] | None + restkey: _T | None + restval: str | Any | None + reader: Reader + dialect: _DialectLike + line_num: int + + @overload + def __init__( + self, + f: Iterable[str], + fieldnames: Sequence[_T], + restkey: _T | None = None, + restval: str | Any | None = None, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, + ) -> None: ... + @overload + def __init__( + self: DictReader[str], + f: Iterable[str], + fieldnames: Sequence[str] | None = None, + restkey: str | None = None, + restval: str | None = None, + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, + ) -> None: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> dict[_T | Any, str | Any]: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class DictWriter(Generic[_T]): + fieldnames: Collection[_T] + restval: Any | None + extrasaction: Literal["raise", "ignore"] + writer: Writer + def __init__( + self, + f: SupportsWrite[str], + fieldnames: Collection[_T], + restval: Any | None = "", + extrasaction: Literal["raise", "ignore"] = "raise", + dialect: _DialectLike = "excel", + *, + delimiter: str = ",", + quotechar: str | None = '"', + escapechar: str | None = None, + doublequote: bool = True, + skipinitialspace: bool = False, + lineterminator: str = "\r\n", + quoting: _QuotingType = 0, + strict: bool = False, + ) -> None: ... + def writeheader(self) -> Any: ... + def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... + def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class Sniffer: + preferred: list[str] + def sniff(self, sample: str, delimiters: str | None = None) -> type[Dialect]: ... + def has_header(self, sample: str) -> bool: ... diff --git a/stdlib/ctypes/__init__.pyi b/stdlib/ctypes/__init__.pyi new file mode 100644 index 000000000000..7760ddf9d8cb --- /dev/null +++ b/stdlib/ctypes/__init__.pyi @@ -0,0 +1,394 @@ +import sys +from _ctypes import ( + RTLD_GLOBAL as RTLD_GLOBAL, + RTLD_LOCAL as RTLD_LOCAL, + Array as Array, + CFuncPtr as _CFuncPtr, + Structure as Structure, + Union as Union, + _CanCastTo as _CanCastTo, + _CArgObject as _CArgObject, + _CData as _CData, + _CDataType as _CDataType, + _CField as _CField, + _CTypeBaseType, + _Pointer as _Pointer, + _PointerLike as _PointerLike, + _SimpleCData as _SimpleCData, + addressof as addressof, + alignment as alignment, + byref as byref, + get_errno as get_errno, + resize as resize, + set_errno as set_errno, + sizeof as sizeof, +) +from _typeshed import StrPath, SupportsBool, SupportsLen +from ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure +from types import GenericAlias +from typing import Any, ClassVar, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated + +if sys.platform == "win32": + from _ctypes import FormatError as FormatError, get_last_error as get_last_error, set_last_error as set_last_error + + if sys.version_info >= (3, 14): + from _ctypes import COMError as COMError, CopyComPointer as CopyComPointer + +if sys.version_info >= (3, 11): + from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion + +_CT = TypeVar("_CT", bound=_CData) +_T = TypeVar("_T", default=Any) +_DLLT = TypeVar("_DLLT", bound=CDLL) + +if sys.version_info >= (3, 14): + @overload + @deprecated("ctypes.POINTER with string") + def POINTER(cls: str) -> type[Any]: ... + @overload + def POINTER(cls: None) -> type[c_void_p]: ... + @overload + def POINTER(cls: type[_CT]) -> type[_Pointer[_CT]]: ... + + def pointer(obj: _CT) -> _Pointer[_CT]: ... + +else: + from _ctypes import POINTER as POINTER, pointer as pointer + +if sys.version_info >= (3, 14): + CField = _CField + +DEFAULT_MODE: Final[int] + +class ArgumentError(Exception): ... + +# defined within CDLL.__init__ +# Runtime name is ctypes.CDLL.__init__.._FuncPtr +@type_check_only +class _CDLLFuncPointer(_CFuncPtr): + _flags_: ClassVar[int] + _restype_: ClassVar[type[_CDataType]] + +# Not a real class; _CDLLFuncPointer with a __name__ set on it. +@type_check_only +class _NamedFuncPointer(_CDLLFuncPointer): + __name__: str + +if sys.version_info >= (3, 12): + _NameTypes: TypeAlias = StrPath | None +else: + _NameTypes: TypeAlias = str | None + +class CDLL: + _func_flags_: ClassVar[int] + _func_restype_: ClassVar[type[_CDataType]] + _name: str + _handle: int + _FuncPtr: type[_CDLLFuncPointer] + def __init__( + self, + name: _NameTypes, + mode: int = ..., + handle: int | None = None, + use_errno: bool = False, + use_last_error: bool = False, + winmode: int | None = None, + ) -> None: ... + def __getattr__(self, name: str) -> _NamedFuncPointer: ... + def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ... + +if sys.platform == "win32": + class OleDLL(CDLL): ... + class WinDLL(CDLL): ... + +class PyDLL(CDLL): ... + +class LibraryLoader(Generic[_DLLT]): + def __init__(self, dlltype: type[_DLLT]) -> None: ... + def __getattr__(self, name: str) -> _DLLT: ... + def __getitem__(self, name: str) -> _DLLT: ... + def LoadLibrary(self, name: str) -> _DLLT: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +cdll: LibraryLoader[CDLL] +if sys.platform == "win32": + windll: LibraryLoader[WinDLL] + oledll: LibraryLoader[OleDLL] +pydll: LibraryLoader[PyDLL] +pythonapi: PyDLL + +# Class definition within CFUNCTYPE / WINFUNCTYPE / PYFUNCTYPE +# Names at runtime are +# ctypes.CFUNCTYPE..CFunctionType +# ctypes.WINFUNCTYPE..WinFunctionType +# ctypes.PYFUNCTYPE..CFunctionType +@type_check_only +class _CFunctionType(_CFuncPtr): + _argtypes_: ClassVar[list[type[_CData | _CDataType]]] + _restype_: ClassVar[type[_CData | _CDataType] | None] + _flags_: ClassVar[int] + +# Alias for either function pointer type +_FuncPointer: TypeAlias = _CDLLFuncPointer | _CFunctionType # noqa: Y047 # not used here + +def CFUNCTYPE( + restype: type[_CData | _CDataType] | None, + *argtypes: type[_CData | _CDataType], + use_errno: bool = False, + use_last_error: bool = False, +) -> type[_CFunctionType]: ... + +if sys.platform == "win32": + def WINFUNCTYPE( + restype: type[_CData | _CDataType] | None, + *argtypes: type[_CData | _CDataType], + use_errno: bool = False, + use_last_error: bool = False, + ) -> type[_CFunctionType]: ... + +def PYFUNCTYPE(restype: type[_CData | _CDataType] | None, *argtypes: type[_CData | _CDataType]) -> type[_CFunctionType]: ... + +# Any type that can be implicitly converted to c_void_p when passed as a C function argument. +# (bytes is not included here, see below.) +_CVoidPLike: TypeAlias = _PointerLike | Array[Any] | _CArgObject | int +# Same as above, but including types known to be read-only (i. e. bytes). +# This distinction is not strictly necessary (ctypes doesn't differentiate between const +# and non-const pointers), but it catches errors like memmove(b'foo', buf, 4) +# when memmove(buf, b'foo', 4) was intended. +_CVoidConstPLike: TypeAlias = _CVoidPLike | bytes + +_CastT = TypeVar("_CastT", bound=_CanCastTo) + +def cast(obj: _CData | _CDataType | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... +def create_string_buffer(init: int | bytes, size: int | None = None) -> Array[c_char]: ... + +c_buffer = create_string_buffer + +def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ... + +if sys.version_info < (3, 15): + @deprecated("Deprecated; will be removed in Python 3.15.") + def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ... + +@deprecated("Soft deprecated. Use multiplication instead.") +def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... + +if sys.platform == "win32": + def DllCanUnloadNow() -> int: ... + def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO: not documented + + # Actually just an instance of _NamedFuncPointer (aka _CDLLFuncPointer), + # but we want to set a more specific __call__ + @type_check_only + class _GetLastErrorFunctionType(_NamedFuncPointer): + def __call__(self) -> int: ... + + GetLastError: _GetLastErrorFunctionType + +# Actually just an instance of _CFunctionType, but we want to set a more +# specific __call__. +@type_check_only +class _MemmoveFunctionType(_CFunctionType): + def __call__(self, dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> int: ... + +memmove: _MemmoveFunctionType + +# Actually just an instance of _CFunctionType, but we want to set a more +# specific __call__. +@type_check_only +class _MemsetFunctionType(_CFunctionType): + def __call__(self, dst: _CVoidPLike, c: int, count: int) -> int: ... + +memset: _MemsetFunctionType + +def string_at(ptr: _CVoidConstPLike, size: int = -1) -> bytes: ... + +if sys.platform == "win32": + def WinError(code: int | None = None, descr: str | None = None) -> OSError: ... + +def wstring_at(ptr: _CVoidConstPLike, size: int = -1) -> str: ... + +if sys.version_info >= (3, 14): + def memoryview_at(ptr: _CVoidConstPLike, size: int, readonly: bool = False) -> memoryview: ... + +class py_object(_CanCastTo, _SimpleCData[_T]): + _type_: ClassVar[Literal["O"]] + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class c_bool(_SimpleCData[bool]): + _type_: ClassVar[Literal["?"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + def __init__(self, value: SupportsBool | SupportsLen | None = ...) -> None: ... + +class c_byte(_SimpleCData[int]): + _type_: ClassVar[Literal["b"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ubyte(_SimpleCData[int]): + _type_: ClassVar[Literal["B"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_short(_SimpleCData[int]): + _type_: ClassVar[Literal["h"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ushort(_SimpleCData[int]): + _type_: ClassVar[Literal["H"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_long(_SimpleCData[int]): + _type_: ClassVar[Literal["l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ulong(_SimpleCData[int]): + _type_: ClassVar[Literal["L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_longlong(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["q", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ulonglong(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["Q", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +c_int8 = c_byte +c_uint8 = c_ubyte + +class c_int16(_SimpleCData[int]): # can be an alias for c_short or c_int + _type_: ClassVar[Literal["h", "i"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint16(_SimpleCData[int]): # can be an alias for c_ushort or c_uint + _type_: ClassVar[Literal["H", "I"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int32(_SimpleCData[int]): # can be an alias for c_int or c_long + _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint32(_SimpleCData[int]): # can be an alias for c_uint or c_ulong + _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_int64(_SimpleCData[int]): # can be an alias for c_long or c_longlong + _type_: ClassVar[Literal["l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_uint64(_SimpleCData[int]): # can be an alias for c_ulong or c_ulonglong + _type_: ClassVar[Literal["L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_ssize_t(_SimpleCData[int]): # alias for c_int, c_long, or c_longlong + _type_: ClassVar[Literal["i", "l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_size_t(_SimpleCData[int]): # alias for c_uint, c_ulong, or c_ulonglong + _type_: ClassVar[Literal["I", "L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_float(_SimpleCData[float]): + _type_: ClassVar[Literal["f"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_double(_SimpleCData[float]): + _type_: ClassVar[Literal["d"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + +class c_longdouble(_SimpleCData[float]): # can be an alias for c_double + _type_: ClassVar[Literal["d", "g"]] + +if sys.version_info >= (3, 14) and sys.platform != "win32": + # NOTE: currently (3.14.4) the `__ctype_{be,le}__` attributes of these complex types are missing at runtime: + # https://github.com/python/cpython/issues/148464 + + class c_double_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zd"]] + else: + _type_: ClassVar[Literal["D"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + + class c_float_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zf"]] + else: + _type_: ClassVar[Literal["F"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + + class c_longdouble_complex(_SimpleCData[complex]): + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zg"]] + else: + _type_: ClassVar[Literal["G"]] + +class c_char(_SimpleCData[bytes]): + _type_: ClassVar[Literal["c"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] + def __init__(self, value: int | bytes | bytearray = ...) -> None: ... + +class c_char_p(_PointerLike, _SimpleCData[bytes | None]): + _type_: ClassVar[Literal["z"]] + def __init__(self, value: int | bytes | None = ...) -> None: ... + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +class c_void_p(_PointerLike, _SimpleCData[int | None]): + _type_: ClassVar[Literal["P"]] + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +c_voidp = c_void_p # backwards compatibility (to a bug) + +class c_wchar(_SimpleCData[str]): + _type_: ClassVar[Literal["u"]] + +class c_wchar_p(_PointerLike, _SimpleCData[str | None]): + _type_: ClassVar[Literal["Z"]] + def __init__(self, value: int | str | None = ...) -> None: ... + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +if sys.platform == "win32": + class HRESULT(_SimpleCData[int]): # TODO: undocumented + _type_: ClassVar[Literal["l"]] + +if sys.version_info >= (3, 12): + # At runtime, this is an alias for either c_int32 or c_int64, + # which are themselves an alias for one of c_int, c_long, or c_longlong + # This covers all our bases. + c_time_t: type[c_int32 | c_int64 | c_int | c_long | c_longlong] diff --git a/stdlib/ctypes/_endian.pyi b/stdlib/ctypes/_endian.pyi new file mode 100644 index 000000000000..97852f67aa6e --- /dev/null +++ b/stdlib/ctypes/_endian.pyi @@ -0,0 +1,16 @@ +import sys +from ctypes import Structure, Union + +# At runtime, the native endianness is an alias for Structure, +# while the other is a subclass with a metaclass added in. +class BigEndianStructure(Structure): + __slots__ = () + +class LittleEndianStructure(Structure): ... + +# Same thing for these: one is an alias of Union at runtime +if sys.version_info >= (3, 11): + class BigEndianUnion(Union): + __slots__ = () + + class LittleEndianUnion(Union): ... diff --git a/stdlib/ctypes/macholib/__init__.pyi b/stdlib/ctypes/macholib/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stdlib/ctypes/macholib/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stdlib/ctypes/macholib/dyld.pyi b/stdlib/ctypes/macholib/dyld.pyi new file mode 100644 index 000000000000..c7e94daa2149 --- /dev/null +++ b/stdlib/ctypes/macholib/dyld.pyi @@ -0,0 +1,8 @@ +from collections.abc import Mapping +from ctypes.macholib.dylib import dylib_info as dylib_info +from ctypes.macholib.framework import framework_info as framework_info + +__all__ = ["dyld_find", "framework_find", "framework_info", "dylib_info"] + +def dyld_find(name: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ... +def framework_find(fn: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ... diff --git a/stdlib/ctypes/macholib/dylib.pyi b/stdlib/ctypes/macholib/dylib.pyi new file mode 100644 index 000000000000..95945edfd155 --- /dev/null +++ b/stdlib/ctypes/macholib/dylib.pyi @@ -0,0 +1,14 @@ +from typing import TypedDict, type_check_only + +__all__ = ["dylib_info"] + +# Actual result is produced by re.match.groupdict() +@type_check_only +class _DylibInfo(TypedDict): + location: str + name: str + shortname: str + version: str | None + suffix: str | None + +def dylib_info(filename: str) -> _DylibInfo | None: ... diff --git a/stdlib/ctypes/macholib/framework.pyi b/stdlib/ctypes/macholib/framework.pyi new file mode 100644 index 000000000000..e92bf3700e84 --- /dev/null +++ b/stdlib/ctypes/macholib/framework.pyi @@ -0,0 +1,14 @@ +from typing import TypedDict, type_check_only + +__all__ = ["framework_info"] + +# Actual result is produced by re.match.groupdict() +@type_check_only +class _FrameworkInfo(TypedDict): + location: str + name: str + shortname: str + version: str | None + suffix: str | None + +def framework_info(filename: str) -> _FrameworkInfo | None: ... diff --git a/stdlib/ctypes/util.pyi b/stdlib/ctypes/util.pyi new file mode 100644 index 000000000000..4f18c1d8db34 --- /dev/null +++ b/stdlib/ctypes/util.pyi @@ -0,0 +1,11 @@ +import sys + +def find_library(name: str) -> str | None: ... + +if sys.platform == "win32": + def find_msvcrt() -> str | None: ... + +if sys.version_info >= (3, 14): + def dllist() -> list[str]: ... + +def test() -> None: ... diff --git a/stdlib/ctypes/wintypes.pyi b/stdlib/ctypes/wintypes.pyi new file mode 100644 index 000000000000..b94c5e74148a --- /dev/null +++ b/stdlib/ctypes/wintypes.pyi @@ -0,0 +1,321 @@ +import sys +from _ctypes import _CArgObject, _CField +from ctypes import ( + Array, + Structure, + _Pointer, + _SimpleCData, + c_char, + c_char_p, + c_double, + c_float, + c_int, + c_long, + c_longlong, + c_short, + c_uint, + c_ulong, + c_ulonglong, + c_ushort, + c_void_p, + c_wchar, + c_wchar_p, +) +from typing import Any, Final, TypeAlias, TypeVar +from typing_extensions import Self + +if sys.version_info >= (3, 12): + from ctypes import c_ubyte + + BYTE = c_ubyte +else: + from ctypes import c_byte + + BYTE = c_byte + +WORD = c_ushort +DWORD = c_ulong +CHAR = c_char +WCHAR = c_wchar +UINT = c_uint +INT = c_int +DOUBLE = c_double +FLOAT = c_float +BOOLEAN = BYTE +BOOL = c_long + +class VARIANT_BOOL(_SimpleCData[bool]): ... + +ULONG = c_ulong +LONG = c_long +USHORT = c_ushort +SHORT = c_short +LARGE_INTEGER = c_longlong +_LARGE_INTEGER = c_longlong +ULARGE_INTEGER = c_ulonglong +_ULARGE_INTEGER = c_ulonglong + +OLESTR = c_wchar_p +LPOLESTR = c_wchar_p +LPCOLESTR = c_wchar_p +LPWSTR = c_wchar_p +LPCWSTR = c_wchar_p +LPSTR = c_char_p +LPCSTR = c_char_p +LPVOID = c_void_p +LPCVOID = c_void_p + +# These two types are pointer-sized unsigned and signed ints, respectively. +# At runtime, they are either c_[u]long or c_[u]longlong, depending on the host's pointer size +# (they are not really separate classes). +class WPARAM(_SimpleCData[int]): ... +class LPARAM(_SimpleCData[int]): ... + +ATOM = WORD +LANGID = WORD +COLORREF = DWORD +LGRPID = DWORD +LCTYPE = DWORD +LCID = DWORD + +HANDLE = c_void_p +HACCEL = HANDLE +HBITMAP = HANDLE +HBRUSH = HANDLE +HCOLORSPACE = HANDLE +if sys.version_info >= (3, 14): + HCONV = HANDLE + HCONVLIST = HANDLE + HCURSOR = HANDLE + HDDEDATA = HANDLE + HDROP = HANDLE + HFILE = INT + HRESULT = LONG + HSZ = HANDLE +HDC = HANDLE +HDESK = HANDLE +HDWP = HANDLE +HENHMETAFILE = HANDLE +HFONT = HANDLE +HGDIOBJ = HANDLE +HGLOBAL = HANDLE +HHOOK = HANDLE +HICON = HANDLE +HINSTANCE = HANDLE +HKEY = HANDLE +HKL = HANDLE +HLOCAL = HANDLE +HMENU = HANDLE +HMETAFILE = HANDLE +HMODULE = HANDLE +HMONITOR = HANDLE +HPALETTE = HANDLE +HPEN = HANDLE +HRGN = HANDLE +HRSRC = HANDLE +HSTR = HANDLE +HTASK = HANDLE +HWINSTA = HANDLE +HWND = HANDLE +SC_HANDLE = HANDLE +SERVICE_STATUS_HANDLE = HANDLE + +_CIntLikeT = TypeVar("_CIntLikeT", bound=_SimpleCData[int]) +_CIntLikeField: TypeAlias = _CField[_CIntLikeT, int, _CIntLikeT | int] + +class RECT(Structure): + left: _CIntLikeField[LONG] + top: _CIntLikeField[LONG] + right: _CIntLikeField[LONG] + bottom: _CIntLikeField[LONG] + +RECTL = RECT +_RECTL = RECT +tagRECT = RECT + +class _SMALL_RECT(Structure): + Left: _CIntLikeField[SHORT] + Top: _CIntLikeField[SHORT] + Right: _CIntLikeField[SHORT] + Bottom: _CIntLikeField[SHORT] + +SMALL_RECT = _SMALL_RECT + +class _COORD(Structure): + X: _CIntLikeField[SHORT] + Y: _CIntLikeField[SHORT] + +class POINT(Structure): + x: _CIntLikeField[LONG] + y: _CIntLikeField[LONG] + +POINTL = POINT +_POINTL = POINT +tagPOINT = POINT + +class SIZE(Structure): + cx: _CIntLikeField[LONG] + cy: _CIntLikeField[LONG] + +SIZEL = SIZE +tagSIZE = SIZE + +def RGB(red: int, green: int, blue: int) -> int: ... + +class FILETIME(Structure): + dwLowDateTime: _CIntLikeField[DWORD] + dwHighDateTime: _CIntLikeField[DWORD] + +_FILETIME = FILETIME + +class MSG(Structure): + hWnd: _CField[HWND, int | None, HWND | int | None] + message: _CIntLikeField[UINT] + wParam: _CIntLikeField[WPARAM] + lParam: _CIntLikeField[LPARAM] + time: _CIntLikeField[DWORD] + pt: _CField[POINT, POINT, POINT] + +tagMSG = MSG +MAX_PATH: Final = 260 + +class WIN32_FIND_DATAA(Structure): + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[CHAR], bytes, bytes] + cAlternateFileName: _CField[Array[CHAR], bytes, bytes] + +class WIN32_FIND_DATAW(Structure): + dwFileAttributes: _CIntLikeField[DWORD] + ftCreationTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME] + ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME] + nFileSizeHigh: _CIntLikeField[DWORD] + nFileSizeLow: _CIntLikeField[DWORD] + dwReserved0: _CIntLikeField[DWORD] + dwReserved1: _CIntLikeField[DWORD] + cFileName: _CField[Array[WCHAR], str, str] + cAlternateFileName: _CField[Array[WCHAR], str, str] + +# These are all defined with the POINTER() function, which keeps a cache and will +# return a previously created class if it can. The self-reported __name__ +# of these classes is f"LP_{typ.__name__}", where typ is the original class +# passed in to the POINTER() function. + +# LP_c_short +class PSHORT(_Pointer[SHORT]): ... + +# LP_c_ushort +class PUSHORT(_Pointer[USHORT]): ... + +PWORD = PUSHORT +LPWORD = PUSHORT + +# LP_c_long +class PLONG(_Pointer[LONG]): ... + +LPLONG = PLONG +PBOOL = PLONG +LPBOOL = PLONG + +# LP_c_ulong +class PULONG(_Pointer[ULONG]): ... + +PDWORD = PULONG +LPDWORD = PDWORD +LPCOLORREF = PDWORD +PLCID = PDWORD + +# LP_c_int (or LP_c_long if int and long have the same size) +class PINT(_Pointer[INT]): ... + +LPINT = PINT + +# LP_c_uint (or LP_c_ulong if int and long have the same size) +class PUINT(_Pointer[UINT]): ... + +LPUINT = PUINT + +# LP_c_float +class PFLOAT(_Pointer[FLOAT]): ... + +# LP_c_longlong (or LP_c_long if long and long long have the same size) +class PLARGE_INTEGER(_Pointer[LARGE_INTEGER]): ... + +# LP_c_ulonglong (or LP_c_ulong if long and long long have the same size) +class PULARGE_INTEGER(_Pointer[ULARGE_INTEGER]): ... + +# LP_c_byte types +class PBYTE(_Pointer[BYTE]): ... + +LPBYTE = PBYTE +PBOOLEAN = PBYTE + +# LP_c_char +class PCHAR(_Pointer[CHAR]): + # this is inherited from ctypes.c_char_p, kind of. + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +# LP_c_wchar +class PWCHAR(_Pointer[WCHAR]): + # inherited from ctypes.c_wchar_p, kind of + @classmethod + def from_param(cls, value: Any, /) -> Self | _CArgObject: ... + +# LP_c_void_p +class PHANDLE(_Pointer[HANDLE]): ... + +LPHANDLE = PHANDLE +PHKEY = PHANDLE +LPHKL = PHANDLE +LPSC_HANDLE = PHANDLE + +# LP_FILETIME +class PFILETIME(_Pointer[FILETIME]): ... + +LPFILETIME = PFILETIME + +# LP_MSG +class PMSG(_Pointer[MSG]): ... + +LPMSG = PMSG + +# LP_POINT +class PPOINT(_Pointer[POINT]): ... + +LPPOINT = PPOINT +PPOINTL = PPOINT + +# LP_RECT +class PRECT(_Pointer[RECT]): ... + +LPRECT = PRECT +PRECTL = PRECT +LPRECTL = PRECT + +# LP_SIZE +class PSIZE(_Pointer[SIZE]): ... + +LPSIZE = PSIZE +PSIZEL = PSIZE +LPSIZEL = PSIZE + +# LP__SMALL_RECT +class PSMALL_RECT(_Pointer[SMALL_RECT]): ... + +# LP_WIN32_FIND_DATAA +class PWIN32_FIND_DATAA(_Pointer[WIN32_FIND_DATAA]): ... + +LPWIN32_FIND_DATAA = PWIN32_FIND_DATAA + +# LP_WIN32_FIND_DATAW +class PWIN32_FIND_DATAW(_Pointer[WIN32_FIND_DATAW]): ... + +LPWIN32_FIND_DATAW = PWIN32_FIND_DATAW diff --git a/stdlib/curses/__init__.pyi b/stdlib/curses/__init__.pyi new file mode 100644 index 000000000000..cf5048110878 --- /dev/null +++ b/stdlib/curses/__init__.pyi @@ -0,0 +1,38 @@ +from _curses import * +from _curses import window as window +from _typeshed import structseq +from collections.abc import Callable +from typing import Concatenate, Final, ParamSpec, TypeVar, final, type_check_only + +# NOTE: The _curses module is ordinarily only available on Unix, but the +# windows-curses package makes it available on Windows as well with the same +# contents. + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# available after calling `curses.initscr()` +# not `Final` as it can change during the terminal resize: +LINES: int +COLS: int + +# available after calling `curses.start_color()` +COLORS: Final[int] +COLOR_PAIRS: Final[int] + +def wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ... + +# At runtime this class is unexposed and calls itself curses.ncurses_version. +# That name would conflict with the actual curses.ncurses_version, which is +# an instance of this class. +@final +@type_check_only +class _ncurses_version(structseq[int], tuple[int, int, int]): + __match_args__: Final = ("major", "minor", "patch") + + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def patch(self) -> int: ... diff --git a/stdlib/curses/ascii.pyi b/stdlib/curses/ascii.pyi new file mode 100644 index 000000000000..0234434b8c3d --- /dev/null +++ b/stdlib/curses/ascii.pyi @@ -0,0 +1,62 @@ +from typing import Final, TypeVar + +_CharT = TypeVar("_CharT", str, int) + +NUL: Final = 0x00 +SOH: Final = 0x01 +STX: Final = 0x02 +ETX: Final = 0x03 +EOT: Final = 0x04 +ENQ: Final = 0x05 +ACK: Final = 0x06 +BEL: Final = 0x07 +BS: Final = 0x08 +TAB: Final = 0x09 +HT: Final = 0x09 +LF: Final = 0x0A +NL: Final = 0x0A +VT: Final = 0x0B +FF: Final = 0x0C +CR: Final = 0x0D +SO: Final = 0x0E +SI: Final = 0x0F +DLE: Final = 0x10 +DC1: Final = 0x11 +DC2: Final = 0x12 +DC3: Final = 0x13 +DC4: Final = 0x14 +NAK: Final = 0x15 +SYN: Final = 0x16 +ETB: Final = 0x17 +CAN: Final = 0x18 +EM: Final = 0x19 +SUB: Final = 0x1A +ESC: Final = 0x1B +FS: Final = 0x1C +GS: Final = 0x1D +RS: Final = 0x1E +US: Final = 0x1F +SP: Final = 0x20 +DEL: Final = 0x7F + +controlnames: Final[list[int]] + +def isalnum(c: str | int) -> bool: ... +def isalpha(c: str | int) -> bool: ... +def isascii(c: str | int) -> bool: ... +def isblank(c: str | int) -> bool: ... +def iscntrl(c: str | int) -> bool: ... +def isdigit(c: str | int) -> bool: ... +def isgraph(c: str | int) -> bool: ... +def islower(c: str | int) -> bool: ... +def isprint(c: str | int) -> bool: ... +def ispunct(c: str | int) -> bool: ... +def isspace(c: str | int) -> bool: ... +def isupper(c: str | int) -> bool: ... +def isxdigit(c: str | int) -> bool: ... +def isctrl(c: str | int) -> bool: ... +def ismeta(c: str | int) -> bool: ... +def ascii(c: _CharT) -> _CharT: ... +def ctrl(c: _CharT) -> _CharT: ... +def alt(c: _CharT) -> _CharT: ... +def unctrl(c: str | int) -> str: ... diff --git a/stdlib/curses/has_key.pyi b/stdlib/curses/has_key.pyi new file mode 100644 index 000000000000..3811060b916a --- /dev/null +++ b/stdlib/curses/has_key.pyi @@ -0,0 +1 @@ +def has_key(ch: int | str) -> bool: ... diff --git a/stdlib/curses/panel.pyi b/stdlib/curses/panel.pyi new file mode 100644 index 000000000000..861559d38bc5 --- /dev/null +++ b/stdlib/curses/panel.pyi @@ -0,0 +1 @@ +from _curses_panel import * diff --git a/stdlib/curses/textpad.pyi b/stdlib/curses/textpad.pyi new file mode 100644 index 000000000000..48ef67c9d85f --- /dev/null +++ b/stdlib/curses/textpad.pyi @@ -0,0 +1,11 @@ +from _curses import window +from collections.abc import Callable + +def rectangle(win: window, uly: int, ulx: int, lry: int, lrx: int) -> None: ... + +class Textbox: + stripspaces: bool + def __init__(self, win: window, insert_mode: bool = False) -> None: ... + def edit(self, validate: Callable[[int], int] | None = None) -> str: ... + def do_command(self, ch: str | int) -> None: ... + def gather(self) -> str: ... diff --git a/stdlib/dataclasses.pyi b/stdlib/dataclasses.pyi new file mode 100644 index 000000000000..abe1f8457434 --- /dev/null +++ b/stdlib/dataclasses.pyi @@ -0,0 +1,401 @@ +import enum +import sys +import types +from _typeshed import DataclassInstance +from builtins import type as Type # alias to avoid name clashes with fields named "type" +from collections.abc import Callable, Iterable, Mapping +from types import GenericAlias +from typing import Any, Final, Generic, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Never, TypeIs + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +__all__ = [ + "dataclass", + "field", + "Field", + "FrozenInstanceError", + "InitVar", + "KW_ONLY", + "MISSING", + "fields", + "asdict", + "astuple", + "make_dataclass", + "replace", + "is_dataclass", +] + +_DataclassT = TypeVar("_DataclassT", bound=DataclassInstance) + +@type_check_only +class _DataclassFactory(Protocol): + def __call__( + self, + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: ... + +# define _MISSING_TYPE as an enum within the type stubs, +# even though that is not really its type at runtime +# this allows us to use Literal[_MISSING_TYPE.MISSING] +# for background, see: +# https://github.com/python/typeshed/pull/5900#issuecomment-895513797 +class _MISSING_TYPE(enum.Enum): + MISSING = enum.auto() + +MISSING: Final = _MISSING_TYPE.MISSING + +class KW_ONLY: ... + +@overload +def asdict(obj: DataclassInstance) -> dict[str, Any]: ... +@overload +def asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... + +@overload +def astuple(obj: DataclassInstance) -> tuple[Any, ...]: ... +@overload +def astuple(obj: DataclassInstance, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... + +if sys.version_info >= (3, 11): + @overload + def dataclass( + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type[_T]: ... + @overload + def dataclass( + cls: None = None, + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> Callable[[type[_T]], type[_T]]: ... +else: + @overload + def dataclass( + cls: type[_T], + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + ) -> type[_T]: ... + @overload + def dataclass( + cls: None = None, + /, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + ) -> Callable[[type[_T]], type[_T]]: ... + +# See https://github.com/python/mypy/issues/10750 +@type_check_only +class _DefaultFactory(Protocol[_T_co]): + def __call__(self) -> _T_co: ... + +class Field(Generic[_T]): + if sys.version_info >= (3, 14): + __slots__ = ( + "name", + "type", + "default", + "default_factory", + "repr", + "hash", + "init", + "compare", + "metadata", + "kw_only", + "doc", + "_field_type", + ) + else: + __slots__ = ( + "name", + "type", + "default", + "default_factory", + "repr", + "hash", + "init", + "compare", + "metadata", + "kw_only", + "_field_type", + ) + name: str + type: Type[_T] | str | Any + default: _T | Literal[_MISSING_TYPE.MISSING] + default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING] + repr: bool + hash: bool | None + init: bool + compare: bool + metadata: types.MappingProxyType[Any, Any] + + if sys.version_info >= (3, 14): + doc: str | None + + kw_only: bool | Literal[_MISSING_TYPE.MISSING] + + if sys.version_info >= (3, 14): + def __init__( + self, + default: _T, + default_factory: Callable[[], _T], + init: bool, + repr: bool, + hash: bool | None, + compare: bool, + metadata: Mapping[Any, Any], + kw_only: bool, + doc: str | None, + ) -> None: ... + else: + def __init__( + self, + default: _T, + default_factory: Callable[[], _T], + init: bool, + repr: bool, + hash: bool | None, + compare: bool, + metadata: Mapping[Any, Any], + kw_only: bool, + ) -> None: ... + + def __set_name__(self, owner: Type[Any], name: str) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# NOTE: Actual return type is 'Field[_T]', but we want to help type checkers +# to understand the magic that happens at runtime. +if sys.version_info >= (3, 14): + @overload # `default` and `default_factory` are optional and mutually exclusive. + def field( + *, + default: _T, + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, + ) -> _T: ... + @overload + def field( + *, + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Callable[[], _T], + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, + ) -> _T: ... + @overload + def field( + *, + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + doc: str | None = None, + ) -> Any: ... +else: + @overload # `default` and `default_factory` are optional and mutually exclusive. + def field( + *, + default: _T, + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + ) -> _T: ... + @overload + def field( + *, + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Callable[[], _T], + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + ) -> _T: ... + @overload + def field( + *, + default: Literal[_MISSING_TYPE.MISSING] = ..., + default_factory: Literal[_MISSING_TYPE.MISSING] = ..., + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: Mapping[Any, Any] | None = None, + kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., + ) -> Any: ... + +def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ... + +# HACK: `obj: Never` typing matches if object argument is using `Any` type. +@overload +def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-type-guard-definition] # pyrefly: ignore [bad-function-definition] +@overload +def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ... +@overload +def is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... + +class FrozenInstanceError(AttributeError): ... + +class InitVar(Generic[_T]): + __slots__ = ("type",) + type: Type[_T] # ty:ignore[unbound-type-variable] + def __init__(self, type: Type[_T]) -> None: ... + + @overload + def __class_getitem__( + cls, type: Type[_T] + ) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] + @overload + def __class_getitem__( + cls, type: Any + ) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] + +if sys.version_info >= (3, 14): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + module: str | None = None, + decorator: _DataclassFactory = ..., + ) -> type: ... + +elif sys.version_info >= (3, 12): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + module: str | None = None, + ) -> type: ... + +elif sys.version_info >= (3, 11): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + weakref_slot: bool = False, + ) -> type: ... + +else: + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], + *, + bases: tuple[type, ...] = (), + namespace: dict[str, Any] | None = None, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + match_args: bool = True, + kw_only: bool = False, + slots: bool = False, + ) -> type: ... + +def replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: ... diff --git a/stdlib/datetime.pyi b/stdlib/datetime.pyi new file mode 100644 index 000000000000..0a21f72b09de --- /dev/null +++ b/stdlib/datetime.pyi @@ -0,0 +1,381 @@ +import sys +from abc import abstractmethod +from time import struct_time +from typing import ClassVar, Final, SupportsIndex, TypeAlias, final, overload, type_check_only +from typing_extensions import CapsuleType, Never, Self, deprecated, disjoint_base + +if sys.version_info >= (3, 11): + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") +else: + __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") + +MINYEAR: Final = 1 +MAXYEAR: Final = 9999 + +class tzinfo: + @abstractmethod + def tzname(self, dt: datetime | None, /) -> str | None: ... + @abstractmethod + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + @abstractmethod + def dst(self, dt: datetime | None, /) -> timedelta | None: ... + def fromutc(self, dt: datetime, /) -> datetime: ... + +# Alias required to avoid name conflicts with date(time).tzinfo. +_TzInfo: TypeAlias = tzinfo + +@final +class timezone(tzinfo): + utc: ClassVar[timezone] + min: ClassVar[timezone] + max: ClassVar[timezone] + def __new__(cls, offset: timedelta, name: str = ...) -> Self: ... + def tzname(self, dt: datetime | None, /) -> str: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta: ... + def dst(self, dt: datetime | None, /) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... + +if sys.version_info >= (3, 11): + UTC: timezone + +# This class calls itself datetime.IsoCalendarDate. It's neither +# NamedTuple nor structseq. +@final +@type_check_only +class _IsoCalendarDate(tuple[int, int, int]): + @property + def year(self) -> int: ... + @property + def week(self) -> int: ... + @property + def weekday(self) -> int: ... + +@disjoint_base +class date: + min: ClassVar[date] + max: ClassVar[date] + resolution: ClassVar[timedelta] + def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ... + @classmethod + def fromtimestamp(cls, timestamp: float, /) -> Self: ... + @classmethod + def today(cls) -> Self: ... + @classmethod + def fromordinal(cls, n: int, /) -> Self: ... + + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> Self: ... + else: + @classmethod + def fromisoformat(cls, date_string: str, /) -> Self: ... + + @classmethod + def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... + @property + def year(self) -> int: ... + @property + def month(self) -> int: ... + @property + def day(self) -> int: ... + def ctime(self) -> str: ... + + if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + + # On <3.12, the name of the parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): + def strftime(self, format: str) -> str: ... + else: + def strftime(self, format: str, /) -> str: ... + + def __format__(self, fmt: str, /) -> str: ... + def isoformat(self) -> str: ... + def timetuple(self) -> struct_time: ... + def toordinal(self) -> int: ... + if sys.version_info >= (3, 13): + def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... + + def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ... + def __le__(self, value: date, /) -> bool: ... + def __lt__(self, value: date, /) -> bool: ... + def __ge__(self, value: date, /) -> bool: ... + def __gt__(self, value: date, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __add__(self, value: timedelta, /) -> Self: ... + def __radd__(self, value: timedelta, /) -> Self: ... + + @overload + def __sub__(self, value: datetime, /) -> Never: ... + @overload + def __sub__(self, value: Self, /) -> timedelta: ... + @overload + def __sub__(self, value: timedelta, /) -> Self: ... + + def __hash__(self) -> int: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def isocalendar(self) -> _IsoCalendarDate: ... + +@disjoint_base +class time: + min: ClassVar[time] + max: ClassVar[time] + resolution: ClassVar[timedelta] + def __new__( + cls, + hour: SupportsIndex = 0, + minute: SupportsIndex = 0, + second: SupportsIndex = 0, + microsecond: SupportsIndex = 0, + tzinfo: _TzInfo | None = None, + *, + fold: int = 0, + ) -> Self: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> _TzInfo | None: ... + @property + def fold(self) -> int: ... + def __le__(self, value: time, /) -> bool: ... + def __lt__(self, value: time, /) -> bool: ... + def __ge__(self, value: time, /) -> bool: ... + def __gt__(self, value: time, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def isoformat(self, timespec: str = "auto") -> str: ... + + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> Self: ... + else: + @classmethod + def fromisoformat(cls, time_string: str, /) -> Self: ... + + if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + + # On <3.12, the name of the parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): + def strftime(self, format: str) -> str: ... + else: + def strftime(self, format: str, /) -> str: ... + + def __format__(self, fmt: str, /) -> str: ... + def utcoffset(self) -> timedelta | None: ... + def tzname(self) -> str | None: ... + def dst(self) -> timedelta | None: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + + def replace( + self, + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + *, + fold: int = ..., + ) -> Self: ... + +_Date: TypeAlias = date +_Time: TypeAlias = time + +@disjoint_base +class timedelta: + min: ClassVar[timedelta] + max: ClassVar[timedelta] + resolution: ClassVar[timedelta] + def __new__( + cls, + days: float = 0, + seconds: float = 0, + microseconds: float = 0, + milliseconds: float = 0, + minutes: float = 0, + hours: float = 0, + weeks: float = 0, + ) -> Self: ... + @property + def days(self) -> int: ... + @property + def seconds(self) -> int: ... + @property + def microseconds(self) -> int: ... + def total_seconds(self) -> float: ... + def __add__(self, value: timedelta, /) -> timedelta: ... + def __radd__(self, value: timedelta, /) -> timedelta: ... + def __sub__(self, value: timedelta, /) -> timedelta: ... + def __rsub__(self, value: timedelta, /) -> timedelta: ... + def __neg__(self) -> timedelta: ... + def __pos__(self) -> timedelta: ... + def __abs__(self) -> timedelta: ... + def __mul__(self, value: float, /) -> timedelta: ... + def __rmul__(self, value: float, /) -> timedelta: ... + + @overload + def __floordiv__(self, value: timedelta, /) -> int: ... + @overload + def __floordiv__(self, value: int, /) -> timedelta: ... + + @overload + def __truediv__(self, value: timedelta, /) -> float: ... + @overload + def __truediv__(self, value: float, /) -> timedelta: ... + + def __mod__(self, value: timedelta, /) -> timedelta: ... + def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ... + def __le__(self, value: timedelta, /) -> bool: ... + def __lt__(self, value: timedelta, /) -> bool: ... + def __ge__(self, value: timedelta, /) -> bool: ... + def __gt__(self, value: timedelta, /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __bool__(self) -> bool: ... + def __hash__(self) -> int: ... + +@disjoint_base +class datetime(date): + min: ClassVar[datetime] + max: ClassVar[datetime] + def __new__( + cls, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex = 0, + minute: SupportsIndex = 0, + second: SupportsIndex = 0, + microsecond: SupportsIndex = 0, + tzinfo: _TzInfo | None = None, + *, + fold: int = 0, + ) -> Self: ... + @property + def hour(self) -> int: ... + @property + def minute(self) -> int: ... + @property + def second(self) -> int: ... + @property + def microsecond(self) -> int: ... + @property + def tzinfo(self) -> _TzInfo | None: ... + @property + def fold(self) -> int: ... + # On <3.12, the name of the first parameter in the pure-Python implementation + # didn't match the name in the C implementation, + # meaning it is only *safe* to pass it as a keyword argument on 3.12+ + if sys.version_info >= (3, 12): + @classmethod + def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self: ... + else: + @classmethod + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self: ... + + @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)") + def utcfromtimestamp(cls, t: float, /) -> Self: ... + @classmethod + def now(cls, tz: _TzInfo | None = None) -> Self: ... + @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)") + def utcnow(cls) -> Self: ... + @classmethod + def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ... + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> Self: ... + + def timestamp(self) -> float: ... + def utctimetuple(self) -> struct_time: ... + def date(self) -> _Date: ... + def time(self) -> _Time: ... + def timetz(self) -> _Time: ... + if sys.version_info >= (3, 13): + def __replace__( + self, + /, + *, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + fold: int = ..., + ) -> Self: ... + + def replace( + self, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., + *, + fold: int = ..., + ) -> Self: ... + def astimezone(self, tz: _TzInfo | None = None) -> Self: ... + def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: ... + + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + + def utcoffset(self) -> timedelta | None: ... + def tzname(self) -> str | None: ... + def dst(self) -> timedelta | None: ... + def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + + @overload # type: ignore[override] + def __sub__(self, value: Self, /) -> timedelta: ... + @overload + def __sub__(self, value: timedelta, /) -> Self: ... + +datetime_CAPI: CapsuleType diff --git a/stdlib/dbm/__init__.pyi b/stdlib/dbm/__init__.pyi new file mode 100644 index 000000000000..0871381e8ec0 --- /dev/null +++ b/stdlib/dbm/__init__.pyi @@ -0,0 +1,105 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterator, MutableMapping +from types import TracebackType +from typing import Literal, TypeAlias, type_check_only +from typing_extensions import Self + +__all__ = ["open", "whichdb", "error"] + +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes | bytearray +_TFlags: TypeAlias = Literal[ + "r", + "w", + "c", + "n", + "rf", + "wf", + "cf", + "nf", + "rs", + "ws", + "cs", + "ns", + "ru", + "wu", + "cu", + "nu", + "rfs", + "wfs", + "cfs", + "nfs", + "rfu", + "wfu", + "cfu", + "nfu", + "rsf", + "wsf", + "csf", + "nsf", + "rsu", + "wsu", + "csu", + "nsu", + "ruf", + "wuf", + "cuf", + "nuf", + "rus", + "wus", + "cus", + "nus", + "rfsu", + "wfsu", + "cfsu", + "nfsu", + "rfus", + "wfus", + "cfus", + "nfus", + "rsfu", + "wsfu", + "csfu", + "nsfu", + "rsuf", + "wsuf", + "csuf", + "nsuf", + "rufs", + "wufs", + "cufs", + "nufs", + "rusf", + "wusf", + "cusf", + "nusf", +] + +@type_check_only +class _Database(MutableMapping[_KeyType, bytes]): + def close(self) -> None: ... + def __getitem__(self, key: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +# This class is not exposed. It calls itself dbm.error. +@type_check_only +class _error(Exception): ... + +error: tuple[type[_error], type[OSError]] + +if sys.version_info >= (3, 11): + def whichdb(filename: StrOrBytesPath) -> str | None: ... + def open(file: StrOrBytesPath, flag: _TFlags = "r", mode: int = 0o666) -> _Database: ... + +else: + def whichdb(filename: str) -> str | None: ... + def open(file: str, flag: _TFlags = "r", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/dbm/dumb.pyi b/stdlib/dbm/dumb.pyi new file mode 100644 index 000000000000..d5a769e6a1c2 --- /dev/null +++ b/stdlib/dbm/dumb.pyi @@ -0,0 +1,41 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterator, MutableMapping +from types import TracebackType +from typing import TypeAlias +from typing_extensions import Self + +__all__ = ["error", "open"] + +_KeyType: TypeAlias = str | bytes +_ValueType: TypeAlias = str | bytes + +error = OSError + +# This class doesn't exist at runtime. open() can return an instance of +# any of the three implementations of dbm (dumb, gnu, ndbm), and this +# class is intended to represent the common interface supported by all three. +class _Database(MutableMapping[_KeyType, bytes]): + def __init__(self, filebasename: str, mode: str, flag: str = "c") -> None: ... + def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + + def iterkeys(self) -> Iterator[bytes]: ... # undocumented + def close(self) -> None: ... + def __getitem__(self, key: _KeyType) -> bytes: ... + def __setitem__(self, key: _KeyType, val: _ValueType) -> None: ... + def __delitem__(self, key: _KeyType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +if sys.version_info >= (3, 11): + def open(file: StrOrBytesPath, flag: str = "c", mode: int = 0o666) -> _Database: ... + +else: + def open(file: str, flag: str = "c", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/dbm/gnu.pyi b/stdlib/dbm/gnu.pyi new file mode 100644 index 000000000000..2dac3d12b0ca --- /dev/null +++ b/stdlib/dbm/gnu.pyi @@ -0,0 +1 @@ +from _gdbm import * diff --git a/stdlib/dbm/ndbm.pyi b/stdlib/dbm/ndbm.pyi new file mode 100644 index 000000000000..66c943ab640b --- /dev/null +++ b/stdlib/dbm/ndbm.pyi @@ -0,0 +1 @@ +from _dbm import * diff --git a/stdlib/dbm/sqlite3.pyi b/stdlib/dbm/sqlite3.pyi new file mode 100644 index 000000000000..e7034cfde50d --- /dev/null +++ b/stdlib/dbm/sqlite3.pyi @@ -0,0 +1,34 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, Unused +from collections.abc import Generator, MutableMapping +from typing import Final, Literal, TypeAlias +from typing_extensions import LiteralString, Self + +BUILD_TABLE: Final[LiteralString] +GET_SIZE: Final[LiteralString] +LOOKUP_KEY: Final[LiteralString] +STORE_KV: Final[LiteralString] +DELETE_KEY: Final[LiteralString] +ITER_KEYS: Final[LiteralString] +if sys.version_info >= (3, 15): + REORGANIZE: Final[LiteralString] + +_SqliteData: TypeAlias = str | ReadableBuffer | int | float + +class error(OSError): ... + +class _Database(MutableMapping[bytes, bytes]): + def __init__(self, path: StrOrBytesPath, /, *, flag: Literal["r", "w", "c", "n"], mode: int) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _SqliteData) -> bytes: ... + def __setitem__(self, key: _SqliteData, value: _SqliteData) -> None: ... + def __delitem__(self, key: _SqliteData) -> None: ... + def __iter__(self) -> Generator[bytes]: ... + def close(self) -> None: ... + def keys(self) -> list[bytes]: ... # type: ignore[override] + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + +def open(filename: StrOrBytesPath, /, flag: Literal["r", "w", "c", "n"] = "r", mode: int = 0o666) -> _Database: ... diff --git a/stdlib/decimal.pyi b/stdlib/decimal.pyi new file mode 100644 index 000000000000..f116603cf0f2 --- /dev/null +++ b/stdlib/decimal.pyi @@ -0,0 +1,278 @@ +import numbers +import sys +from _decimal import ( + HAVE_CONTEXTVAR as HAVE_CONTEXTVAR, + HAVE_THREADS as HAVE_THREADS, + MAX_EMAX as MAX_EMAX, + MAX_PREC as MAX_PREC, + MIN_EMIN as MIN_EMIN, + MIN_ETINY as MIN_ETINY, + ROUND_05UP as ROUND_05UP, + ROUND_CEILING as ROUND_CEILING, + ROUND_DOWN as ROUND_DOWN, + ROUND_FLOOR as ROUND_FLOOR, + ROUND_HALF_DOWN as ROUND_HALF_DOWN, + ROUND_HALF_EVEN as ROUND_HALF_EVEN, + ROUND_HALF_UP as ROUND_HALF_UP, + ROUND_UP as ROUND_UP, + BasicContext as BasicContext, + DefaultContext as DefaultContext, + ExtendedContext as ExtendedContext, + __libmpdec_version__ as __libmpdec_version__, + __version__ as __version__, + getcontext as getcontext, + localcontext as localcontext, + setcontext as setcontext, +) +from collections.abc import Container, Sequence +from types import TracebackType +from typing import Any, ClassVar, Literal, NamedTuple, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +if sys.version_info >= (3, 14): + from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext +if sys.version_info >= (3, 15): + from _decimal import SPEC_VERSION as SPEC_VERSION + +_Decimal: TypeAlias = Decimal | int +_DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int] +_ComparableNum: TypeAlias = Decimal | float | numbers.Rational +_TrapType: TypeAlias = type[DecimalException] + +# At runtime, these classes are implemented in C as part of "_decimal". +# However, they consider themselves to live in "decimal", so we'll put them here. + +# This type isn't exposed at runtime. It calls itself decimal.ContextManager +@final +@type_check_only +class _ContextManager: + def __init__(self, new_context: Context) -> None: ... + def __enter__(self) -> Context: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +class DecimalTuple(NamedTuple): + sign: int + digits: tuple[int, ...] + exponent: int | Literal["n", "N", "F"] + +class DecimalException(ArithmeticError): ... +class Clamped(DecimalException): ... +class InvalidOperation(DecimalException): ... +class ConversionSyntax(InvalidOperation): ... +class DivisionByZero(DecimalException, ZeroDivisionError): ... +class DivisionImpossible(InvalidOperation): ... +class DivisionUndefined(InvalidOperation, ZeroDivisionError): ... +class Inexact(DecimalException): ... +class InvalidContext(InvalidOperation): ... +class Rounded(DecimalException): ... +class Subnormal(DecimalException): ... +class Overflow(Inexact, Rounded): ... +class Underflow(Inexact, Rounded, Subnormal): ... +class FloatOperation(DecimalException, TypeError): ... + +@disjoint_base +class Decimal: + def __new__(cls, value: _DecimalNew = "0", context: Context | None = None) -> Self: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: Decimal | float, /) -> Self: ... + + @classmethod + def from_float(cls, f: float, /) -> Self: ... + def __bool__(self) -> bool: ... + def compare(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def __hash__(self) -> int: ... + def as_tuple(self) -> DecimalTuple: ... + def as_integer_ratio(self) -> tuple[int, int]: ... + def to_eng_string(self, context: Context | None = None) -> str: ... + def __abs__(self) -> Decimal: ... + def __add__(self, value: _Decimal, /) -> Decimal: ... + def __divmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __eq__(self, value: object, /) -> bool: ... + def __floordiv__(self, value: _Decimal, /) -> Decimal: ... + def __ge__(self, value: _ComparableNum, /) -> bool: ... + def __gt__(self, value: _ComparableNum, /) -> bool: ... + def __le__(self, value: _ComparableNum, /) -> bool: ... + def __lt__(self, value: _ComparableNum, /) -> bool: ... + def __mod__(self, value: _Decimal, /) -> Decimal: ... + def __mul__(self, value: _Decimal, /) -> Decimal: ... + def __neg__(self) -> Decimal: ... + def __pos__(self) -> Decimal: ... + def __pow__(self, value: _Decimal, mod: _Decimal | None = None, /) -> Decimal: ... + def __radd__(self, value: _Decimal, /) -> Decimal: ... + def __rdivmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, value: _Decimal, /) -> Decimal: ... + def __rmod__(self, value: _Decimal, /) -> Decimal: ... + def __rmul__(self, value: _Decimal, /) -> Decimal: ... + def __rsub__(self, value: _Decimal, /) -> Decimal: ... + def __rtruediv__(self, value: _Decimal, /) -> Decimal: ... + def __sub__(self, value: _Decimal, /) -> Decimal: ... + def __truediv__(self, value: _Decimal, /) -> Decimal: ... + def remainder_near(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __trunc__(self) -> int: ... + @property + def real(self) -> Decimal: ... + @property + def imag(self) -> Decimal: ... + def conjugate(self) -> Decimal: ... + def __complex__(self) -> complex: ... + + @overload + def __round__(self) -> int: ... + @overload + def __round__(self, ndigits: int, /) -> Decimal: ... + + def __floor__(self) -> int: ... + def __ceil__(self) -> int: ... + def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: ... + def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal: ... + def normalize(self, context: Context | None = None) -> Decimal: ... + def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool: ... + def to_integral_exact(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def to_integral_value(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def to_integral(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ... + def sqrt(self, context: Context | None = None) -> Decimal: ... + def max(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def min(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def adjusted(self) -> int: ... + def canonical(self) -> Decimal: ... + def compare_signal(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def compare_total(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def compare_total_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def copy_abs(self) -> Decimal: ... + def copy_negate(self) -> Decimal: ... + def copy_sign(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def exp(self, context: Context | None = None) -> Decimal: ... + def is_canonical(self) -> bool: ... + def is_finite(self) -> bool: ... + def is_infinite(self) -> bool: ... + def is_nan(self) -> bool: ... + def is_normal(self, context: Context | None = None) -> bool: ... + def is_qnan(self) -> bool: ... + def is_signed(self) -> bool: ... + def is_snan(self) -> bool: ... + def is_subnormal(self, context: Context | None = None) -> bool: ... + def is_zero(self) -> bool: ... + def ln(self, context: Context | None = None) -> Decimal: ... + def log10(self, context: Context | None = None) -> Decimal: ... + def logb(self, context: Context | None = None) -> Decimal: ... + def logical_and(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def logical_invert(self, context: Context | None = None) -> Decimal: ... + def logical_or(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def logical_xor(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def max_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def min_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def next_minus(self, context: Context | None = None) -> Decimal: ... + def next_plus(self, context: Context | None = None) -> Decimal: ... + def next_toward(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def number_class(self, context: Context | None = None) -> str: ... + def radix(self) -> Decimal: ... + def rotate(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def scaleb(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def shift(self, other: _Decimal, context: Context | None = None) -> Decimal: ... + def __reduce__(self) -> tuple[type[Self], tuple[str]]: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def __format__(self, specifier: str, context: Context | None = None, /) -> str: ... + +@disjoint_base +class Context: + # TODO: Context doesn't allow you to delete *any* attributes from instances of the class at runtime, + # even settable attributes like `prec` and `rounding`, + # but that's inexpressible in the stub. + # Type checkers either ignore it or misinterpret it + # if you add a `def __delattr__(self, name: str, /) -> Never` method to the stub + prec: int + rounding: str + Emin: int + Emax: int + capitals: int + clamp: int + traps: dict[_TrapType, bool] + flags: dict[_TrapType, bool] + def __init__( + self, + prec: int | None = None, + rounding: str | None = None, + Emin: int | None = None, + Emax: int | None = None, + capitals: int | None = None, + clamp: int | None = None, + flags: dict[_TrapType, bool] | Container[_TrapType] | None = None, + traps: dict[_TrapType, bool] | Container[_TrapType] | None = None, + ) -> None: ... + def __reduce__(self) -> tuple[type[Self], tuple[Any, ...]]: ... + def clear_flags(self) -> None: ... + def clear_traps(self) -> None: ... + def copy(self) -> Context: ... + def __copy__(self) -> Context: ... + # see https://github.com/python/cpython/issues/94107 + __hash__: ClassVar[None] # type: ignore[assignment] + def Etiny(self) -> int: ... + def Etop(self) -> int: ... + def create_decimal(self, num: _DecimalNew = "0", /) -> Decimal: ... + def create_decimal_from_float(self, f: float, /) -> Decimal: ... + def abs(self, x: _Decimal, /) -> Decimal: ... + def add(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def canonical(self, x: Decimal, /) -> Decimal: ... + def compare(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_signal(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def compare_total_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def copy_abs(self, x: _Decimal, /) -> Decimal: ... + def copy_decimal(self, x: _Decimal, /) -> Decimal: ... + def copy_negate(self, x: _Decimal, /) -> Decimal: ... + def copy_sign(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divide_int(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def divmod(self, x: _Decimal, y: _Decimal, /) -> tuple[Decimal, Decimal]: ... + def exp(self, x: _Decimal, /) -> Decimal: ... + def fma(self, x: _Decimal, y: _Decimal, z: _Decimal, /) -> Decimal: ... + def is_canonical(self, x: _Decimal, /) -> bool: ... + def is_finite(self, x: _Decimal, /) -> bool: ... + def is_infinite(self, x: _Decimal, /) -> bool: ... + def is_nan(self, x: _Decimal, /) -> bool: ... + def is_normal(self, x: _Decimal, /) -> bool: ... + def is_qnan(self, x: _Decimal, /) -> bool: ... + def is_signed(self, x: _Decimal, /) -> bool: ... + def is_snan(self, x: _Decimal, /) -> bool: ... + def is_subnormal(self, x: _Decimal, /) -> bool: ... + def is_zero(self, x: _Decimal, /) -> bool: ... + def ln(self, x: _Decimal, /) -> Decimal: ... + def log10(self, x: _Decimal, /) -> Decimal: ... + def logb(self, x: _Decimal, /) -> Decimal: ... + def logical_and(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_invert(self, x: _Decimal, /) -> Decimal: ... + def logical_or(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def logical_xor(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def max_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def min_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def minus(self, x: _Decimal, /) -> Decimal: ... + def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def next_minus(self, x: _Decimal, /) -> Decimal: ... + def next_plus(self, x: _Decimal, /) -> Decimal: ... + def next_toward(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def normalize(self, x: _Decimal, /) -> Decimal: ... + def number_class(self, x: _Decimal, /) -> str: ... + def plus(self, x: _Decimal, /) -> Decimal: ... + def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal: ... + def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def radix(self) -> Decimal: ... + def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def same_quantum(self, x: _Decimal, y: _Decimal, /) -> bool: ... + def scaleb(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def shift(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def sqrt(self, x: _Decimal, /) -> Decimal: ... + def subtract(self, x: _Decimal, y: _Decimal, /) -> Decimal: ... + def to_eng_string(self, x: _Decimal, /) -> str: ... + def to_sci_string(self, x: _Decimal, /) -> str: ... + def to_integral_exact(self, x: _Decimal, /) -> Decimal: ... + def to_integral_value(self, x: _Decimal, /) -> Decimal: ... + def to_integral(self, x: _Decimal, /) -> Decimal: ... diff --git a/stdlib/difflib.pyi b/stdlib/difflib.pyi new file mode 100644 index 000000000000..a3bda7f9b2d0 --- /dev/null +++ b/stdlib/difflib.pyi @@ -0,0 +1,157 @@ +import re +import sys +from collections.abc import Callable, Iterable, Iterator, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload + +__all__ = [ + "get_close_matches", + "ndiff", + "restore", + "SequenceMatcher", + "Differ", + "IS_CHARACTER_JUNK", + "IS_LINE_JUNK", + "context_diff", + "unified_diff", + "diff_bytes", + "HtmlDiff", + "Match", +] + +_T = TypeVar("_T") + +class Match(NamedTuple): + a: int + b: int + size: int + +class SequenceMatcher(Generic[_T]): + @overload + def __init__(self, isjunk: Callable[[_T], bool] | None, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ... + @overload + def __init__(self, *, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ... + @overload + def __init__( + self: SequenceMatcher[str], + isjunk: Callable[[str], bool] | None = None, + a: Sequence[str] = "", + b: Sequence[str] = "", + autojunk: bool = True, + ) -> None: ... + + def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... + def set_seq1(self, a: Sequence[_T]) -> None: ... + def set_seq2(self, b: Sequence[_T]) -> None: ... + def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ... + def get_matching_blocks(self) -> list[Match]: ... + def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: ... + def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ... + def ratio(self) -> float: ... + def quick_ratio(self) -> float: ... + def real_quick_ratio(self) -> float: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@overload +def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = 3, cutoff: float = 0.6) -> list[AnyStr]: ... +@overload +def get_close_matches( + word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = 3, cutoff: float = 0.6 +) -> list[Sequence[_T]]: ... + +class Differ: + def __init__(self, linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = None) -> None: ... + def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ... + +if sys.version_info >= (3, 14): + def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] | None = None) -> bool: ... + +else: + def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] = ...) -> bool: ... + +def IS_CHARACTER_JUNK(ch: str, ws: str = " \t") -> bool: ... # ws is undocumented + +if sys.version_info >= (3, 15): + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + *, + color: bool = False, + ) -> Iterator[str]: ... + +else: + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + ) -> Iterator[str]: ... + +def context_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", +) -> Iterator[str]: ... +def ndiff( + a: Sequence[str], + b: Sequence[str], + linejunk: Callable[[str], bool] | None = None, + charjunk: Callable[[str], bool] | None = ..., +) -> Iterator[str]: ... + +class HtmlDiff: + def __init__( + self, + tabsize: int = 8, + wrapcolumn: int | None = None, + linejunk: Callable[[str], bool] | None = None, + charjunk: Callable[[str], bool] | None = ..., + ) -> None: ... + def make_file( + self, + fromlines: Sequence[str], + tolines: Sequence[str], + fromdesc: str = "", + todesc: str = "", + context: bool = False, + numlines: int = 5, + *, + charset: str = "utf-8", + ) -> str: ... + def make_table( + self, + fromlines: Sequence[str], + tolines: Sequence[str], + fromdesc: str = "", + todesc: str = "", + context: bool = False, + numlines: int = 5, + ) -> str: ... + +def restore(delta: Iterable[str], which: int) -> Iterator[str]: ... +def diff_bytes( + dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]], + a: Iterable[bytes | bytearray], + b: Iterable[bytes | bytearray], + fromfile: bytes | bytearray = b"", + tofile: bytes | bytearray = b"", + fromfiledate: bytes | bytearray = b"", + tofiledate: bytes | bytearray = b"", + n: int = 3, + lineterm: bytes | bytearray = b"\n", +) -> Iterator[bytes]: ... diff --git a/stdlib/dis.pyi b/stdlib/dis.pyi new file mode 100644 index 000000000000..984f932e3311 --- /dev/null +++ b/stdlib/dis.pyi @@ -0,0 +1,302 @@ +import sys +import types +from collections.abc import Callable, Iterator +from opcode import * # `dis` re-exports it as a part of public API +from typing import IO, Any, Final, NamedTuple, TypeAlias, overload +from typing_extensions import Self, deprecated, disjoint_base + +__all__ = [ + "code_info", + "dis", + "disassemble", + "distb", + "disco", + "findlinestarts", + "findlabels", + "show_code", + "get_instructions", + "Instruction", + "Bytecode", + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "stack_effect", +] +if sys.version_info >= (3, 13): + __all__ += ["hasjump"] + +if sys.version_info >= (3, 12): + __all__ += ["hasarg", "hasexc"] +else: + __all__ += ["hasnargs"] + +# Strictly this should not have to include Callable, but mypy doesn't use FunctionType +# for functions (python/mypy#3171) +_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] + +if sys.version_info >= (3, 11): + class Positions(NamedTuple): + lineno: int | None = None + end_lineno: int | None = None + col_offset: int | None = None + end_col_offset: int | None = None + +if sys.version_info >= (3, 13): + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + start_offset: int + starts_line: bool + line_number: int | None + label: int | None = None + positions: Positions | None = None + cache_info: list[tuple[str, int, Any]] | None = None + +elif sys.version_info >= (3, 11): + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool + positions: Positions | None = None + +else: + class _Instruction(NamedTuple): + opname: str + opcode: int + arg: int | None + argval: Any + argrepr: str + offset: int + starts_line: int | None + is_jump_target: bool + +if sys.version_info >= (3, 12): + class Instruction(_Instruction): + if sys.version_info < (3, 13): + def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ... + if sys.version_info >= (3, 13): + @property + def oparg(self) -> int: ... + @property + def baseopcode(self) -> int: ... + @property + def baseopname(self) -> str: ... + @property + def cache_offset(self) -> int: ... + @property + def end_offset(self) -> int: ... + @property + def jump_target(self) -> int: ... + @property + def is_jump_target(self) -> bool: ... + if sys.version_info >= (3, 14): + @staticmethod + def make( + opname: str, + arg: int | None, + argval: Any, + argrepr: str, + offset: int, + start_offset: int, + starts_line: bool, + line_number: int | None, + label: int | None = None, + positions: Positions | None = None, + cache_info: list[tuple[str, int, Any]] | None = None, + ) -> Instruction: ... + +else: + @disjoint_base + class Instruction(_Instruction): + def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ... + +class Bytecode: + codeobj: types.CodeType + first_line: int + if sys.version_info >= (3, 14): + show_positions: bool + # 3.14 added `show_positions` + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 13): + show_offsets: bool + # 3.13 added `show_offsets` + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + x: _HaveCodeType | str, + *, + first_line: int | None = None, + current_offset: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + ) -> None: ... + else: + def __init__( + self, x: _HaveCodeType | str, *, first_line: int | None = None, current_offset: int | None = None + ) -> None: ... + + if sys.version_info >= (3, 11): + @classmethod + def from_traceback(cls, tb: types.TracebackType, *, show_caches: bool = False, adaptive: bool = False) -> Self: ... + else: + @classmethod + def from_traceback(cls, tb: types.TracebackType) -> Self: ... + + def __iter__(self) -> Iterator[Instruction]: ... + def info(self) -> str: ... + def dis(self) -> str: ... + +COMPILER_FLAG_NAMES: Final[dict[int, str]] + +def findlabels(code: _HaveCodeType) -> list[int]: ... +def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: ... +def pretty_flags(flags: int) -> str: ... +def code_info(x: _HaveCodeType | str) -> str: ... + +if sys.version_info >= (3, 14): + # 3.14 added `show_positions` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, + lasti: int = -1, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + show_positions: bool = False, + ) -> None: ... + +elif sys.version_info >= (3, 13): + # 3.13 added `show_offsets` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, + lasti: int = -1, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, + *, + file: IO[str] | None = None, + show_caches: bool = False, + adaptive: bool = False, + show_offsets: bool = False, + ) -> None: ... + +elif sys.version_info >= (3, 11): + # 3.11 added `show_caches` and `adaptive` + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, + *, + file: IO[str] | None = None, + depth: int | None = None, + show_caches: bool = False, + adaptive: bool = False, + ) -> None: ... + def disassemble( + co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False + ) -> None: ... + def distb( + tb: types.TracebackType | None = None, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False + ) -> None: ... + +else: + def dis( + x: _HaveCodeType | str | bytes | bytearray | None = None, *, file: IO[str] | None = None, depth: int | None = None + ) -> None: ... + def disassemble(co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None) -> None: ... + def distb(tb: types.TracebackType | None = None, *, file: IO[str] | None = None) -> None: ... + +if sys.version_info >= (3, 13): + # 3.13 made `show_caches` `None` by default and has no effect + @overload + def get_instructions(x: _HaveCodeType, *, first_line: int | None = None, adaptive: bool = False) -> Iterator[Instruction]: ... + @overload + @deprecated( + "The `show_caches` parameter is deprecated since Python 3.13. " + "The iterator generates the `Instruction` instances with the `cache_info` field populated." + ) + def get_instructions( + x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool | None = None, adaptive: bool = False + ) -> Iterator[Instruction]: ... + +elif sys.version_info >= (3, 11): + def get_instructions( + x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool = False, adaptive: bool = False + ) -> Iterator[Instruction]: ... + +else: + def get_instructions(x: _HaveCodeType, *, first_line: int | None = None) -> Iterator[Instruction]: ... + +def show_code(co: _HaveCodeType, *, file: IO[str] | None = None) -> None: ... + +disco = disassemble diff --git a/stdlib/distutils/__init__.pyi b/stdlib/distutils/__init__.pyi new file mode 100644 index 000000000000..328a5b783441 --- /dev/null +++ b/stdlib/distutils/__init__.pyi @@ -0,0 +1,5 @@ +# Attempts to improve these stubs are probably not the best use of time: +# - distutils is deleted in Python 3.12 and newer +# - Most users already do not use stdlib distutils, due to setuptools monkeypatching +# - We have very little quality assurance on these stubs, since due to the two above issues +# we allowlist all distutils errors in stubtest. diff --git a/stdlib/distutils/_msvccompiler.pyi b/stdlib/distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..bba9373b72db --- /dev/null +++ b/stdlib/distutils/_msvccompiler.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from distutils.ccompiler import CCompiler +from typing import ClassVar, Final + +PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] +PLAT_TO_VCVARS: Final[dict[str, str]] + +class MSVCCompiler(CCompiler): + compiler_type: ClassVar[str] + executables: ClassVar[dict[Incomplete, Incomplete]] + res_extension: ClassVar[str] + initialized: bool + def initialize(self, plat_name: str | None = None) -> None: ... diff --git a/stdlib/distutils/archive_util.pyi b/stdlib/distutils/archive_util.pyi new file mode 100644 index 000000000000..5de23bad6bdb --- /dev/null +++ b/stdlib/distutils/archive_util.pyi @@ -0,0 +1,36 @@ +from _typeshed import StrOrBytesPath, StrPath +from typing import Literal, overload + +@overload +def make_archive( + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, +) -> str: ... +@overload +def make_archive( + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, +) -> str: ... + +def make_tarball( + base_name: str, + base_dir: StrPath, + compress: str | None = "gzip", + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + owner: str | None = None, + group: str | None = None, +) -> str: ... +def make_zipfile(base_name: str, base_dir: str, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0) -> str: ... diff --git a/stdlib/distutils/bcppcompiler.pyi b/stdlib/distutils/bcppcompiler.pyi new file mode 100644 index 000000000000..3e432f94b525 --- /dev/null +++ b/stdlib/distutils/bcppcompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class BCPPCompiler(CCompiler): ... diff --git a/stdlib/distutils/ccompiler.pyi b/stdlib/distutils/ccompiler.pyi new file mode 100644 index 000000000000..83bbada6c4c4 --- /dev/null +++ b/stdlib/distutils/ccompiler.pyi @@ -0,0 +1,182 @@ +from _typeshed import BytesPath, StrPath, Unused +from collections.abc import Callable, Iterable, Sequence +from distutils.file_util import _BytesPathT, _StrPathT +from typing import Literal, TypeAlias, overload +from typing_extensions import TypeVarTuple, Unpack + +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] +_Ts = TypeVarTuple("_Ts") + +def gen_lib_options( + compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] +) -> list[str]: ... +def gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> list[str]: ... +def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: ... +def new_compiler( + plat: str | None = None, + compiler: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, + force: bool | Literal[0, 1] = 0, +) -> CCompiler: ... +def show_compilers() -> None: ... + +class CCompiler: + dry_run: bool + force: bool + verbose: bool + output_dir: str | None + macros: list[_Macro] + include_dirs: list[str] + libraries: list[str] + library_dirs: list[str] + runtime_library_dirs: list[str] + objects: list[str] + def __init__( + self, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, force: bool | Literal[0, 1] = 0 + ) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: list[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: list[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: list[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: list[str]) -> None: ... + def define_macro(self, name: str, value: str | None = None) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: list[str]) -> None: ... + def detect_language(self, sources: str | list[str]) -> str | None: ... + def find_library_file(self, dirs: list[str], lib: str, debug: bool | Literal[0, 1] = 0) -> str | None: ... + def has_function( + self, + funcname: str, + includes: list[str] | None = None, + include_dirs: list[str] | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + ) -> bool: ... + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def set_executables(self, **args: str) -> None: ... + def compile( + self, + sources: Sequence[StrPath], + output_dir: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + depends: list[str] | None = None, + ) -> list[str]: ... + def create_static_lib( + self, + objects: list[str], + output_libname: str, + output_dir: str | None = None, + debug: bool | Literal[0, 1] = 0, + target_lang: str | None = None, + ) -> None: ... + def link( + self, + target_desc: str, + objects: list[str], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_executable( + self, + objects: list[str], + output_progname: str, + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_lib( + self, + objects: list[str], + output_libname: str, + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_object( + self, + objects: list[str], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + export_symbols: list[str] | None = None, + debug: bool | Literal[0, 1] = 0, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: str | None = None, + target_lang: str | None = None, + ) -> None: ... + def preprocess( + self, + source: str, + output_file: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + ) -> None: ... + + @overload + def executable_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... + @overload + def executable_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + + def library_filename( + self, libname: str, lib_type: str = "static", strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath = "" + ) -> str: ... + def object_filenames( + self, source_filenames: Iterable[StrPath], strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath | None = "" + ) -> list[str]: ... + + @overload + def shared_object_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... + @overload + def shared_object_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def spawn(self, cmd: Iterable[str]) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ... + + def announce(self, msg: str, level: int = 1) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... diff --git a/stdlib/distutils/cmd.pyi b/stdlib/distutils/cmd.pyi new file mode 100644 index 000000000000..35b991aba088 --- /dev/null +++ b/stdlib/distutils/cmd.pyi @@ -0,0 +1,238 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath, Unused +from abc import abstractmethod +from collections.abc import Callable, Iterable +from distutils.command.bdist import bdist +from distutils.command.bdist_dumb import bdist_dumb +from distutils.command.bdist_rpm import bdist_rpm +from distutils.command.build import build +from distutils.command.build_clib import build_clib +from distutils.command.build_ext import build_ext +from distutils.command.build_py import build_py +from distutils.command.build_scripts import build_scripts +from distutils.command.check import check +from distutils.command.clean import clean +from distutils.command.config import config +from distutils.command.install import install +from distutils.command.install_data import install_data +from distutils.command.install_egg_info import install_egg_info +from distutils.command.install_headers import install_headers +from distutils.command.install_lib import install_lib +from distutils.command.install_scripts import install_scripts +from distutils.command.register import register +from distutils.command.sdist import sdist +from distutils.command.upload import upload +from distutils.dist import Distribution +from distutils.file_util import _BytesPathT, _StrPathT +from typing import Any, ClassVar, Literal, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack + +_CommandT = TypeVar("_CommandT", bound=Command) +_Ts = TypeVarTuple("_Ts") + +class Command: + dry_run: bool | Literal[0, 1] # Exposed from __getattr_. Same as Distribution.dry_run + distribution: Distribution + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + def __init__(self, dist: Distribution) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + def announce(self, msg: str, level: int = 1) -> None: ... + def debug_print(self, msg: str) -> None: ... + def ensure_string(self, option: str, default: str | None = None) -> None: ... + def ensure_string_list(self, option: str) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ... + + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. + @overload + def get_finalized_command(self, command: Literal["bdist"], create: bool | Literal[0, 1] = 1) -> bdist: ... + @overload + def get_finalized_command(self, command: Literal["bdist_dumb"], create: bool | Literal[0, 1] = 1) -> bdist_dumb: ... + @overload + def get_finalized_command(self, command: Literal["bdist_rpm"], create: bool | Literal[0, 1] = 1) -> bdist_rpm: ... + @overload + def get_finalized_command(self, command: Literal["build"], create: bool | Literal[0, 1] = 1) -> build: ... + @overload + def get_finalized_command(self, command: Literal["build_clib"], create: bool | Literal[0, 1] = 1) -> build_clib: ... + @overload + def get_finalized_command(self, command: Literal["build_ext"], create: bool | Literal[0, 1] = 1) -> build_ext: ... + @overload + def get_finalized_command(self, command: Literal["build_py"], create: bool | Literal[0, 1] = 1) -> build_py: ... + @overload + def get_finalized_command(self, command: Literal["build_scripts"], create: bool | Literal[0, 1] = 1) -> build_scripts: ... + @overload + def get_finalized_command(self, command: Literal["check"], create: bool | Literal[0, 1] = 1) -> check: ... + @overload + def get_finalized_command(self, command: Literal["clean"], create: bool | Literal[0, 1] = 1) -> clean: ... + @overload + def get_finalized_command(self, command: Literal["config"], create: bool | Literal[0, 1] = 1) -> config: ... + @overload + def get_finalized_command(self, command: Literal["install"], create: bool | Literal[0, 1] = 1) -> install: ... + @overload + def get_finalized_command(self, command: Literal["install_data"], create: bool | Literal[0, 1] = 1) -> install_data: ... + @overload + def get_finalized_command( + self, command: Literal["install_egg_info"], create: bool | Literal[0, 1] = 1 + ) -> install_egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install_headers"], create: bool | Literal[0, 1] = 1) -> install_headers: ... + @overload + def get_finalized_command(self, command: Literal["install_lib"], create: bool | Literal[0, 1] = 1) -> install_lib: ... + @overload + def get_finalized_command(self, command: Literal["install_scripts"], create: bool | Literal[0, 1] = 1) -> install_scripts: ... + @overload + def get_finalized_command(self, command: Literal["register"], create: bool | Literal[0, 1] = 1) -> register: ... + @overload + def get_finalized_command(self, command: Literal["sdist"], create: bool | Literal[0, 1] = 1) -> sdist: ... + @overload + def get_finalized_command(self, command: Literal["upload"], create: bool | Literal[0, 1] = 1) -> upload: ... + @overload + def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ... + + @overload + def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist: ... + @overload + def reinitialize_command( + self, command: Literal["bdist_dumb"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> bdist_dumb: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build: ... + @overload + def reinitialize_command( + self, command: Literal["build_clib"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_py: ... + @overload + def reinitialize_command( + self, command: Literal["build_scripts"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> build_scripts: ... + @overload + def reinitialize_command(self, command: Literal["check"], reinit_subcommands: bool | Literal[0, 1] = 0) -> check: ... + @overload + def reinitialize_command(self, command: Literal["clean"], reinit_subcommands: bool | Literal[0, 1] = 0) -> clean: ... + @overload + def reinitialize_command(self, command: Literal["config"], reinit_subcommands: bool | Literal[0, 1] = 0) -> config: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool | Literal[0, 1] = 0) -> install: ... + @overload + def reinitialize_command( + self, command: Literal["install_data"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_data: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_egg_info: ... + @overload + def reinitialize_command( + self, command: Literal["install_headers"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_headers: ... + @overload + def reinitialize_command( + self, command: Literal["install_lib"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_lib: ... + @overload + def reinitialize_command( + self, command: Literal["install_scripts"], reinit_subcommands: bool | Literal[0, 1] = 0 + ) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["register"], reinit_subcommands: bool | Literal[0, 1] = 0) -> register: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool | Literal[0, 1] = 0) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["upload"], reinit_subcommands: bool | Literal[0, 1] = 0) -> upload: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool | Literal[0, 1] = 0) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool | Literal[0, 1] = 0) -> _CommandT: ... + + def run_command(self, command: str) -> None: ... + def get_sub_commands(self) -> list[str]: ... + def warn(self, msg: str) -> None: ... + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def copy_file( + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... + @overload + def copy_file( + self, + infile: BytesPath, + outfile: _BytesPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_BytesPathT | bytes, bool]: ... + + def copy_tree( + self, + infile: StrPath, + outfile: str, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + preserve_symlinks: bool | Literal[0, 1] = 0, + level: Unused = 1, + ) -> list[str]: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... + + def spawn(self, cmd: Iterable[str], search_path: bool | Literal[0, 1] = 1, level: Unused = 1) -> None: ... + + @overload + def make_archive( + self, + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + @overload + def make_archive( + self, + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + + def make_file( + self, + infiles: str | list[str] | tuple[str, ...], + outfile: StrOrBytesPath, + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + exec_msg: str | None = None, + skip_msg: str | None = None, + level: Unused = 1, + ) -> None: ... + def ensure_finalized(self) -> None: ... + def dump_options(self, header=None, indent: str = "") -> None: ... diff --git a/stdlib/distutils/command/__init__.pyi b/stdlib/distutils/command/__init__.pyi new file mode 100644 index 000000000000..856c5eb8b44a --- /dev/null +++ b/stdlib/distutils/command/__init__.pyi @@ -0,0 +1,41 @@ +from . import ( + bdist, + bdist_dumb, + bdist_rpm, + build, + build_clib, + build_ext, + build_py, + build_scripts, + check, + clean, + install, + install_data, + install_headers, + install_lib, + install_scripts, + register, + sdist, + upload, +) + +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + "build_scripts", + "clean", + "install", + "install_lib", + "install_headers", + "install_scripts", + "install_data", + "sdist", + "register", + "bdist", + "bdist_dumb", + "bdist_rpm", + "check", + "upload", +] diff --git a/stdlib/distutils/command/bdist.pyi b/stdlib/distutils/command/bdist.pyi new file mode 100644 index 000000000000..6f996207077e --- /dev/null +++ b/stdlib/distutils/command/bdist.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +def show_formats() -> None: ... + +class bdist(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + no_format_option: ClassVar[tuple[str, ...]] + default_format: ClassVar[dict[str, str]] + format_commands: ClassVar[list[str]] + format_command: ClassVar[dict[str, tuple[str, str]]] + bdist_base: Incomplete + plat_name: Incomplete + formats: Incomplete + dist_dir: Incomplete + skip_build: int + group: Incomplete + owner: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stdlib/distutils/command/bdist_dumb.pyi b/stdlib/distutils/command/bdist_dumb.pyi new file mode 100644 index 000000000000..297a0c39ed43 --- /dev/null +++ b/stdlib/distutils/command/bdist_dumb.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class bdist_dumb(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + default_format: ClassVar[dict[str, str]] + bdist_dir: Incomplete + plat_name: Incomplete + format: Incomplete + keep_temp: int + dist_dir: Incomplete + skip_build: Incomplete + relative: int + owner: Incomplete + group: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stdlib/distutils/command/bdist_msi.pyi b/stdlib/distutils/command/bdist_msi.pyi new file mode 100644 index 000000000000..d677f81d1425 --- /dev/null +++ b/stdlib/distutils/command/bdist_msi.pyi @@ -0,0 +1,45 @@ +import sys +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from ..cmd import Command + +if sys.platform == "win32": + from msilib import Control, Dialog + + class PyDialog(Dialog): + def __init__(self, *args, **kw) -> None: ... + def title(self, title) -> None: ... + def back(self, title, next, name: str = "Back", active: bool | Literal[0, 1] = 1) -> Control: ... + def cancel(self, title, next, name: str = "Cancel", active: bool | Literal[0, 1] = 1) -> Control: ... + def next(self, title, next, name: str = "Next", active: bool | Literal[0, 1] = 1) -> Control: ... + def xbutton(self, name, title, next, xpos) -> Control: ... + + class bdist_msi(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + all_versions: Incomplete + other_version: str + def __init__(self, *args, **kw) -> None: ... + bdist_dir: Incomplete + plat_name: Incomplete + keep_temp: int + no_target_compile: int + no_target_optimize: int + target_version: Incomplete + dist_dir: Incomplete + skip_build: Incomplete + install_script: Incomplete + pre_install_script: Incomplete + versions: Incomplete + def initialize_options(self) -> None: ... + install_script_key: Incomplete + def finalize_options(self) -> None: ... + db: Incomplete + def run(self) -> None: ... + def add_files(self) -> None: ... + def add_find_python(self) -> None: ... + def add_scripts(self) -> None: ... + def add_ui(self) -> None: ... + def get_installer_filename(self, fullname): ... diff --git a/stdlib/distutils/command/bdist_packager.pyi b/stdlib/distutils/command/bdist_packager.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/distutils/command/bdist_rpm.pyi b/stdlib/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..83b4161094c5 --- /dev/null +++ b/stdlib/distutils/command/bdist_rpm.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class bdist_rpm(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + bdist_base: Incomplete + rpm_base: Incomplete + dist_dir: Incomplete + python: Incomplete + fix_python: Incomplete + spec_only: Incomplete + binary_only: Incomplete + source_only: Incomplete + use_bzip2: Incomplete + distribution_name: Incomplete + group: Incomplete + release: Incomplete + serial: Incomplete + vendor: Incomplete + packager: Incomplete + doc_files: Incomplete + changelog: Incomplete + icon: Incomplete + prep_script: Incomplete + build_script: Incomplete + install_script: Incomplete + clean_script: Incomplete + verify_script: Incomplete + pre_install: Incomplete + post_install: Incomplete + pre_uninstall: Incomplete + post_uninstall: Incomplete + prep: Incomplete + provides: Incomplete + requires: Incomplete + conflicts: Incomplete + build_requires: Incomplete + obsoletes: Incomplete + keep_temp: int + use_rpm_opt_flags: int + rpm3_mode: int + no_autoreq: int + force_arch: Incomplete + quiet: int + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def finalize_package_data(self) -> None: ... + def run(self) -> None: ... diff --git a/stdlib/distutils/command/build.pyi b/stdlib/distutils/command/build.pyi new file mode 100644 index 000000000000..3ec0c9614d62 --- /dev/null +++ b/stdlib/distutils/command/build.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Any, ClassVar + +from ..cmd import Command + +def show_compilers() -> None: ... + +class build(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_base: str + build_purelib: Incomplete + build_platlib: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + compiler: Incomplete + plat_name: Incomplete + debug: Incomplete + force: int + executable: Incomplete + parallel: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def has_pure_modules(self): ... + def has_c_libraries(self): ... + def has_ext_modules(self): ... + def has_scripts(self): ... + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] diff --git a/stdlib/distutils/command/build_clib.pyi b/stdlib/distutils/command/build_clib.pyi new file mode 100644 index 000000000000..69cfbe7120d8 --- /dev/null +++ b/stdlib/distutils/command/build_clib.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +def show_compilers() -> None: ... + +class build_clib(Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_clib: Incomplete + build_temp: Incomplete + libraries: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + debug: Incomplete + force: int + compiler: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_library_list(self, libraries) -> None: ... + def get_library_names(self): ... + def get_source_files(self): ... + def build_libraries(self, libraries) -> None: ... diff --git a/stdlib/distutils/command/build_ext.pyi b/stdlib/distutils/command/build_ext.pyi new file mode 100644 index 000000000000..c5a9b5d508f0 --- /dev/null +++ b/stdlib/distutils/command/build_ext.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +extension_name_re: Incomplete + +def show_compilers() -> None: ... + +class build_ext(Command): + description: str + sep_by: Incomplete + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + extensions: Incomplete + build_lib: Incomplete + plat_name: Incomplete + build_temp: Incomplete + inplace: int + package: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + libraries: Incomplete + library_dirs: Incomplete + rpath: Incomplete + link_objects: Incomplete + debug: Incomplete + force: Incomplete + compiler: Incomplete + swig: Incomplete + swig_cpp: Incomplete + swig_opts: Incomplete + user: Incomplete + parallel: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_extensions_list(self, extensions) -> None: ... + def get_source_files(self): ... + def get_outputs(self): ... + def build_extensions(self) -> None: ... + def build_extension(self, ext) -> None: ... + def swig_sources(self, sources, extension): ... + def find_swig(self): ... + def get_ext_fullpath(self, ext_name: str) -> str: ... + def get_ext_fullname(self, ext_name: str) -> str: ... + def get_ext_filename(self, ext_name: str) -> str: ... + def get_export_symbols(self, ext): ... + def get_libraries(self, ext): ... diff --git a/stdlib/distutils/command/build_py.pyi b/stdlib/distutils/command/build_py.pyi new file mode 100644 index 000000000000..23ed230bb2d8 --- /dev/null +++ b/stdlib/distutils/command/build_py.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from ..cmd import Command +from ..util import Mixin2to3 as Mixin2to3 + +class build_py(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + build_lib: Incomplete + py_modules: Incomplete + package: Incomplete + package_data: Incomplete + package_dir: Incomplete + compile: int + optimize: int + force: Incomplete + def initialize_options(self) -> None: ... + packages: Incomplete + data_files: Incomplete + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_data_files(self): ... + def find_data_files(self, package, src_dir): ... + def build_package_data(self) -> None: ... + def get_package_dir(self, package): ... + def check_package(self, package, package_dir): ... + def check_module(self, module, module_file): ... + def find_package_modules(self, package, package_dir): ... + def find_modules(self): ... + def find_all_modules(self): ... + def get_source_files(self): ... + def get_module_outfile(self, build_dir, package, module): ... + def get_outputs(self, include_bytecode: bool | Literal[0, 1] = 1) -> list[str]: ... + def build_module(self, module, module_file, package): ... + def build_modules(self) -> None: ... + def build_packages(self) -> None: ... + def byte_compile(self, files) -> None: ... + +class build_py_2to3(build_py, Mixin2to3): + updated_files: Incomplete + def run(self) -> None: ... + def build_module(self, module, module_file, package): ... diff --git a/stdlib/distutils/command/build_scripts.pyi b/stdlib/distutils/command/build_scripts.pyi new file mode 100644 index 000000000000..8372919bbd53 --- /dev/null +++ b/stdlib/distutils/command/build_scripts.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command +from ..util import Mixin2to3 as Mixin2to3 + +first_line_re: Incomplete + +class build_scripts(Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + build_dir: Incomplete + scripts: Incomplete + force: Incomplete + executable: Incomplete + outfiles: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def get_source_files(self): ... + def run(self) -> None: ... + def copy_scripts(self): ... + +class build_scripts_2to3(build_scripts, Mixin2to3): + def copy_scripts(self): ... diff --git a/stdlib/distutils/command/check.pyi b/stdlib/distutils/command/check.pyi new file mode 100644 index 000000000000..f2034e6555fc --- /dev/null +++ b/stdlib/distutils/command/check.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import Any, ClassVar, Final, Literal, TypeAlias + +from ..cmd import Command + +_Reporter: TypeAlias = Any # really docutils.utils.Reporter + +# Only defined if docutils is installed. +# Depends on a third-party stub. Since distutils is deprecated anyway, +# it's easier to just suppress the "any subclassing" error. +class SilentReporter(_Reporter): + messages: Incomplete + def __init__( + self, + source, + report_level, + halt_level, + stream: Incomplete | None = ..., + debug: bool | Literal[0, 1] = 0, + encoding: str = ..., + error_handler: str = ..., + ) -> None: ... + def system_message(self, level, message, *children, **kwargs): ... + +HAS_DOCUTILS: Final[bool] + +class check(Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + restructuredtext: int + metadata: int + strict: int + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def warn(self, msg): ... + def run(self) -> None: ... + def check_metadata(self) -> None: ... + def check_restructuredtext(self) -> None: ... diff --git a/stdlib/distutils/command/clean.pyi b/stdlib/distutils/command/clean.pyi new file mode 100644 index 000000000000..0f3768d6dcf4 --- /dev/null +++ b/stdlib/distutils/command/clean.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class clean(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + build_base: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + bdist_base: Incomplete + all: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stdlib/distutils/command/config.pyi b/stdlib/distutils/command/config.pyi new file mode 100644 index 000000000000..381e8e466bf1 --- /dev/null +++ b/stdlib/distutils/command/config.pyi @@ -0,0 +1,84 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence +from re import Pattern +from typing import ClassVar, Final, Literal + +from ..ccompiler import CCompiler +from ..cmd import Command + +LANG_EXT: Final[dict[str, str]] + +class config(Command): + description: str + # Tuple is full name, short name, description + user_options: ClassVar[list[tuple[str, str | None, str]]] + compiler: str | CCompiler + cc: str | None + include_dirs: Sequence[str] | None + libraries: Sequence[str] | None + library_dirs: Sequence[str] | None + noisy: int + dump_source: int + temp_files: Sequence[str] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def try_cpp( + self, + body: str | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + lang: str = "c", + ) -> bool: ... + def search_cpp( + self, + pattern: Pattern[str] | str, + body: str | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + lang: str = "c", + ) -> bool: ... + def try_compile( + self, body: str, headers: Sequence[str] | None = None, include_dirs: Sequence[str] | None = None, lang: str = "c" + ) -> bool: ... + def try_link( + self, + body: str, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + lang: str = "c", + ) -> bool: ... + def try_run( + self, + body: str, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + lang: str = "c", + ) -> bool: ... + def check_func( + self, + func: str, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + libraries: Sequence[str] | None = None, + library_dirs: Sequence[str] | None = None, + decl: bool | Literal[0, 1] = 0, + call: bool | Literal[0, 1] = 0, + ) -> bool: ... + def check_lib( + self, + library: str, + library_dirs: Sequence[str] | None = None, + headers: Sequence[str] | None = None, + include_dirs: Sequence[str] | None = None, + other_libraries: list[str] = [], + ) -> bool: ... + def check_header( + self, header: str, include_dirs: Sequence[str] | None = None, library_dirs: Sequence[str] | None = None, lang: str = "c" + ) -> bool: ... + +def dump_file(filename: StrOrBytesPath, head=None) -> None: ... diff --git a/stdlib/distutils/command/install.pyi b/stdlib/distutils/command/install.pyi new file mode 100644 index 000000000000..7e11cf257c2c --- /dev/null +++ b/stdlib/distutils/command/install.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, ClassVar, Final, Literal + +from ..cmd import Command + +HAS_USER_SITE: Final[bool] + +SCHEME_KEYS: Final[tuple[Literal["purelib"], Literal["platlib"], Literal["headers"], Literal["scripts"], Literal["data"]]] +INSTALL_SCHEMES: Final[dict[str, dict[str, str]]] + +class install(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + prefix: str | None + exec_prefix: Incomplete + home: str | None + user: bool + install_base: Incomplete + install_platbase: Incomplete + root: str | None + install_purelib: Incomplete + install_platlib: Incomplete + install_headers: Incomplete + install_lib: str | None + install_scripts: Incomplete + install_data: Incomplete + install_userbase: Incomplete + install_usersite: Incomplete + compile: Incomplete + optimize: Incomplete + extra_path: Incomplete + install_path_file: int + force: int + skip_build: int + warn_dir: int + build_base: Incomplete + build_lib: Incomplete + record: Incomplete + def initialize_options(self) -> None: ... + config_vars: Incomplete + install_libbase: Incomplete + def finalize_options(self) -> None: ... + def dump_dirs(self, msg) -> None: ... + def finalize_unix(self) -> None: ... + def finalize_other(self) -> None: ... + def select_scheme(self, name) -> None: ... + def expand_basedirs(self) -> None: ... + def expand_dirs(self) -> None: ... + def convert_paths(self, *names) -> None: ... + path_file: Incomplete + extra_dirs: Incomplete + def handle_extra_path(self) -> None: ... + def change_roots(self, *names) -> None: ... + def create_home_path(self) -> None: ... + def run(self) -> None: ... + def create_path_file(self) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... + def has_lib(self): ... + def has_headers(self): ... + def has_scripts(self): ... + def has_data(self): ... + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] diff --git a/stdlib/distutils/command/install_data.pyi b/stdlib/distutils/command/install_data.pyi new file mode 100644 index 000000000000..609de62b04b5 --- /dev/null +++ b/stdlib/distutils/command/install_data.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_data(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + outfiles: Incomplete + root: Incomplete + force: int + data_files: Incomplete + warn_dir: int + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stdlib/distutils/command/install_egg_info.pyi b/stdlib/distutils/command/install_egg_info.pyi new file mode 100644 index 000000000000..75bb906ce582 --- /dev/null +++ b/stdlib/distutils/command/install_egg_info.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_egg_info(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str, str]]] + install_dir: Incomplete + def initialize_options(self) -> None: ... + target: Incomplete + outputs: Incomplete + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_outputs(self) -> list[str]: ... + +def safe_name(name): ... +def safe_version(version): ... +def to_filename(name): ... diff --git a/stdlib/distutils/command/install_headers.pyi b/stdlib/distutils/command/install_headers.pyi new file mode 100644 index 000000000000..3caad8a07dca --- /dev/null +++ b/stdlib/distutils/command/install_headers.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_headers(Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + force: int + outfiles: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stdlib/distutils/command/install_lib.pyi b/stdlib/distutils/command/install_lib.pyi new file mode 100644 index 000000000000..a537e254904a --- /dev/null +++ b/stdlib/distutils/command/install_lib.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final + +from ..cmd import Command + +PYTHON_SOURCE_EXTENSION: Final = ".py" + +class install_lib(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + install_dir: Incomplete + build_dir: Incomplete + force: int + compile: Incomplete + optimize: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def build(self) -> None: ... + def install(self): ... + def byte_compile(self, files) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... diff --git a/stdlib/distutils/command/install_scripts.pyi b/stdlib/distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..658594f32e43 --- /dev/null +++ b/stdlib/distutils/command/install_scripts.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_scripts(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + force: int + build_dir: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + outfiles: Incomplete + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stdlib/distutils/command/register.pyi b/stdlib/distutils/command/register.pyi new file mode 100644 index 000000000000..c3bd62aaa7aa --- /dev/null +++ b/stdlib/distutils/command/register.pyi @@ -0,0 +1,20 @@ +from collections.abc import Callable +from typing import Any, ClassVar + +from ..config import PyPIRCCommand + +class register(PyPIRCCommand): + description: str + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + list_classifiers: int + strict: int + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_metadata(self) -> None: ... + def classifiers(self) -> None: ... + def verify_metadata(self) -> None: ... + def send_metadata(self) -> None: ... + def build_post_data(self, action): ... + def post_to_server(self, data, auth=None): ... diff --git a/stdlib/distutils/command/sdist.pyi b/stdlib/distutils/command/sdist.pyi new file mode 100644 index 000000000000..48a140714dda --- /dev/null +++ b/stdlib/distutils/command/sdist.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Any, ClassVar + +from ..cmd import Command + +def show_formats() -> None: ... + +class sdist(Command): + description: str + def checking_metadata(self): ... + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + negative_opt: ClassVar[dict[str, str]] + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + READMES: ClassVar[tuple[str, ...]] + template: Incomplete + manifest: Incomplete + use_defaults: int + prune: int + manifest_only: int + force_manifest: int + formats: Incomplete + keep_temp: int + dist_dir: Incomplete + archive_files: Incomplete + metadata_check: int + owner: Incomplete + group: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + filelist: Incomplete + def run(self) -> None: ... + def check_metadata(self) -> None: ... + def get_file_list(self) -> None: ... + def add_defaults(self) -> None: ... + def read_template(self) -> None: ... + def prune_file_list(self) -> None: ... + def write_manifest(self) -> None: ... + def read_manifest(self) -> None: ... + def make_release_tree(self, base_dir, files) -> None: ... + def make_distribution(self) -> None: ... + def get_archive_files(self): ... diff --git a/stdlib/distutils/command/upload.pyi b/stdlib/distutils/command/upload.pyi new file mode 100644 index 000000000000..afcfbaf48677 --- /dev/null +++ b/stdlib/distutils/command/upload.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..config import PyPIRCCommand + +class upload(PyPIRCCommand): + description: ClassVar[str] + username: str + password: str + show_response: int + sign: bool + identity: Incomplete + def initialize_options(self) -> None: ... + repository: Incomplete + realm: Incomplete + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def upload_file(self, command: str, pyversion: str, filename: str) -> None: ... diff --git a/stdlib/distutils/config.pyi b/stdlib/distutils/config.pyi new file mode 100644 index 000000000000..5814a82841cc --- /dev/null +++ b/stdlib/distutils/config.pyi @@ -0,0 +1,17 @@ +from abc import abstractmethod +from distutils.cmd import Command +from typing import ClassVar + +DEFAULT_PYPIRC: str + +class PyPIRCCommand(Command): + DEFAULT_REPOSITORY: ClassVar[str] + DEFAULT_REALM: ClassVar[str] + repository: None + realm: None + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... diff --git a/stdlib/distutils/core.pyi b/stdlib/distutils/core.pyi new file mode 100644 index 000000000000..174f24991351 --- /dev/null +++ b/stdlib/distutils/core.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete, StrOrBytesPath +from collections.abc import Mapping +from distutils.cmd import Command as Command +from distutils.dist import Distribution as Distribution +from distutils.extension import Extension as Extension +from typing import Any, Final, Literal + +USAGE: Final[str] + +def gen_usage(script_name: StrOrBytesPath) -> str: ... + +setup_keywords: tuple[str, ...] +extension_keywords: tuple[str, ...] + +def setup( + *, + name: str = ..., + version: str = ..., + description: str = ..., + long_description: str = ..., + author: str = ..., + author_email: str = ..., + maintainer: str = ..., + maintainer_email: str = ..., + url: str = ..., + download_url: str = ..., + packages: list[str] = ..., + py_modules: list[str] = ..., + scripts: list[str] = ..., + ext_modules: list[Extension] = ..., + classifiers: list[str] = ..., + distclass: type[Distribution] = ..., + script_name: str = ..., + script_args: list[str] = ..., + options: Mapping[str, Incomplete] = ..., + license: str = ..., + keywords: list[str] | str = ..., + platforms: list[str] | str = ..., + cmdclass: Mapping[str, type[Command]] = ..., + data_files: list[tuple[str, list[str]]] = ..., + package_dir: Mapping[str, str] = ..., + obsoletes: list[str] = ..., + provides: list[str] = ..., + requires: list[str] = ..., + command_packages: list[str] = ..., + command_options: Mapping[str, Mapping[str, tuple[Incomplete, Incomplete]]] = ..., + package_data: Mapping[str, list[str]] = ..., + include_package_data: bool | Literal[0, 1] = ..., + libraries: list[str] = ..., + headers: list[str] = ..., + ext_package: str = ..., + include_dirs: list[str] = ..., + password: str = ..., + fullname: str = ..., + # Custom Distributions could accept more params + **attrs: Any, +) -> Distribution: ... +def run_setup(script_name: str, script_args: list[str] | None = None, stop_after: str = "run") -> Distribution: ... diff --git a/stdlib/distutils/cygwinccompiler.pyi b/stdlib/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..80924d63e471 --- /dev/null +++ b/stdlib/distutils/cygwinccompiler.pyi @@ -0,0 +1,20 @@ +from distutils.unixccompiler import UnixCCompiler +from distutils.version import LooseVersion +from re import Pattern +from typing import Final, Literal + +def get_msvcr() -> list[str] | None: ... + +class CygwinCCompiler(UnixCCompiler): ... +class Mingw32CCompiler(CygwinCCompiler): ... + +CONFIG_H_OK: Final = "ok" +CONFIG_H_NOTOK: Final = "not ok" +CONFIG_H_UNCERTAIN: Final = "uncertain" + +def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: ... + +RE_VERSION: Final[Pattern[bytes]] + +def get_versions() -> tuple[LooseVersion | None, ...]: ... +def is_cygwingcc() -> bool: ... diff --git a/stdlib/distutils/debug.pyi b/stdlib/distutils/debug.pyi new file mode 100644 index 000000000000..30095883b064 --- /dev/null +++ b/stdlib/distutils/debug.pyi @@ -0,0 +1,3 @@ +from typing import Final + +DEBUG: Final[str | None] diff --git a/stdlib/distutils/dep_util.pyi b/stdlib/distutils/dep_util.pyi new file mode 100644 index 000000000000..058377accabc --- /dev/null +++ b/stdlib/distutils/dep_util.pyi @@ -0,0 +1,14 @@ +from _typeshed import StrOrBytesPath, SupportsLenAndGetItem +from collections.abc import Iterable +from typing import Literal, TypeVar + +_SourcesT = TypeVar("_SourcesT", bound=StrOrBytesPath) +_TargetsT = TypeVar("_TargetsT", bound=StrOrBytesPath) + +def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool | Literal[1]: ... +def newer_pairwise( + sources: SupportsLenAndGetItem[_SourcesT], targets: SupportsLenAndGetItem[_TargetsT] +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... +def newer_group( + sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal["error", "ignore", "newer"] = "error" +) -> Literal[0, 1]: ... diff --git a/stdlib/distutils/dir_util.pyi b/stdlib/distutils/dir_util.pyi new file mode 100644 index 000000000000..23e2c3bc28b9 --- /dev/null +++ b/stdlib/distutils/dir_util.pyi @@ -0,0 +1,23 @@ +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Iterable +from typing import Literal + +def mkpath(name: str, mode: int = 0o777, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> list[str]: ... +def create_tree( + base_dir: StrPath, + files: Iterable[StrPath], + mode: int = 0o777, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> None: ... +def copy_tree( + src: StrPath, + dst: str, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + preserve_symlinks: bool | Literal[0, 1] = 0, + update: bool | Literal[0, 1] = 0, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> list[str]: ... +def remove_tree(directory: StrOrBytesPath, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> None: ... diff --git a/stdlib/distutils/dist.pyi b/stdlib/distutils/dist.pyi new file mode 100644 index 000000000000..58650e853cce --- /dev/null +++ b/stdlib/distutils/dist.pyi @@ -0,0 +1,318 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Iterable, MutableMapping +from distutils.cmd import Command +from distutils.command.bdist import bdist +from distutils.command.bdist_dumb import bdist_dumb +from distutils.command.bdist_rpm import bdist_rpm +from distutils.command.build import build +from distutils.command.build_clib import build_clib +from distutils.command.build_ext import build_ext +from distutils.command.build_py import build_py +from distutils.command.build_scripts import build_scripts +from distutils.command.check import check +from distutils.command.clean import clean +from distutils.command.config import config +from distutils.command.install import install +from distutils.command.install_data import install_data +from distutils.command.install_egg_info import install_egg_info +from distutils.command.install_headers import install_headers +from distutils.command.install_lib import install_lib +from distutils.command.install_scripts import install_scripts +from distutils.command.register import register +from distutils.command.sdist import sdist +from distutils.command.upload import upload +from re import Pattern +from typing import IO, ClassVar, Literal, TypeAlias, TypeVar, overload + +command_re: Pattern[str] + +_OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str | None, str]] +_CommandT = TypeVar("_CommandT", bound=Command) + +class DistributionMetadata: + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... + name: str | None + version: str | None + author: str | None + author_email: str | None + maintainer: str | None + maintainer_email: str | None + url: str | None + license: str | None + description: str | None + long_description: str | None + keywords: str | list[str] | None + platforms: str | list[str] | None + classifiers: str | list[str] | None + download_url: str | None + provides: list[str] | None + requires: list[str] | None + obsoletes: list[str] | None + def read_pkg_file(self, file: IO[str]) -> None: ... + def write_pkg_info(self, base_dir: StrPath) -> None: ... + def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> str | list[str]: ... + def get_platforms(self) -> str | list[str]: ... + def get_classifiers(self) -> str | list[str]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> list[str]: ... + def set_requires(self, value: Iterable[str]) -> None: ... + def get_provides(self) -> list[str]: ... + def set_provides(self, value: Iterable[str]) -> None: ... + def get_obsoletes(self) -> list[str]: ... + def set_obsoletes(self, value: Iterable[str]) -> None: ... + +class Distribution: + cmdclass: dict[str, type[Command]] + metadata: DistributionMetadata + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... + def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... + def parse_config_files(self, filenames: Iterable[str] | None = None) -> None: ... + global_options: ClassVar[_OptionsList] + common_usage: ClassVar[str] + display_options: ClassVar[_OptionsList] + display_option_names: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + verbose: bool | Literal[0, 1] + dry_run: bool | Literal[0, 1] + help: bool | Literal[0, 1] + command_packages: list[str] | None + script_name: str | None + script_args: list[str] | None + command_options: dict[str, dict[str, tuple[str, str]]] + dist_files: list[tuple[str, str, str]] + packages: Incomplete + package_data: dict[str, list[str]] + package_dir: Incomplete + py_modules: Incomplete + libraries: Incomplete + headers: Incomplete + ext_modules: Incomplete + ext_package: Incomplete + include_dirs: Incomplete + extra_path: Incomplete + scripts: Incomplete + data_files: Incomplete + password: str + command_obj: Incomplete + have_run: Incomplete + want_user_cfg: bool + def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: ... + def find_config_files(self): ... + commands: Incomplete + def parse_command_line(self): ... + def finalize_options(self) -> None: ... + def handle_display_options(self, option_order): ... + def print_command_list(self, commands, header, max_length) -> None: ... + def print_commands(self) -> None: ... + def get_command_list(self): ... + def get_command_packages(self): ... + + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. + @overload + def get_command_obj(self, command: Literal["bdist"], create: Literal[1, True] = 1) -> bdist: ... + @overload + def get_command_obj(self, command: Literal["bdist_dumb"], create: Literal[1, True] = 1) -> bdist_dumb: ... + @overload + def get_command_obj(self, command: Literal["bdist_rpm"], create: Literal[1, True] = 1) -> bdist_rpm: ... + @overload + def get_command_obj(self, command: Literal["build"], create: Literal[1, True] = 1) -> build: ... + @overload + def get_command_obj(self, command: Literal["build_clib"], create: Literal[1, True] = 1) -> build_clib: ... + @overload + def get_command_obj(self, command: Literal["build_ext"], create: Literal[1, True] = 1) -> build_ext: ... + @overload + def get_command_obj(self, command: Literal["build_py"], create: Literal[1, True] = 1) -> build_py: ... + @overload + def get_command_obj(self, command: Literal["build_scripts"], create: Literal[1, True] = 1) -> build_scripts: ... + @overload + def get_command_obj(self, command: Literal["check"], create: Literal[1, True] = 1) -> check: ... + @overload + def get_command_obj(self, command: Literal["clean"], create: Literal[1, True] = 1) -> clean: ... + @overload + def get_command_obj(self, command: Literal["config"], create: Literal[1, True] = 1) -> config: ... + @overload + def get_command_obj(self, command: Literal["install"], create: Literal[1, True] = 1) -> install: ... + @overload + def get_command_obj(self, command: Literal["install_data"], create: Literal[1, True] = 1) -> install_data: ... + @overload + def get_command_obj(self, command: Literal["install_egg_info"], create: Literal[1, True] = 1) -> install_egg_info: ... + @overload + def get_command_obj(self, command: Literal["install_headers"], create: Literal[1, True] = 1) -> install_headers: ... + @overload + def get_command_obj(self, command: Literal["install_lib"], create: Literal[1, True] = 1) -> install_lib: ... + @overload + def get_command_obj(self, command: Literal["install_scripts"], create: Literal[1, True] = 1) -> install_scripts: ... + @overload + def get_command_obj(self, command: Literal["register"], create: Literal[1, True] = 1) -> register: ... + @overload + def get_command_obj(self, command: Literal["sdist"], create: Literal[1, True] = 1) -> sdist: ... + @overload + def get_command_obj(self, command: Literal["upload"], create: Literal[1, True] = 1) -> upload: ... + @overload + def get_command_obj(self, command: str, create: Literal[1, True] = 1) -> Command: ... + # Not replicating the overloads for "Command | None", user may use "isinstance" + @overload + def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... + + @overload + def get_command_class(self, command: Literal["bdist"]) -> type[bdist]: ... + @overload + def get_command_class(self, command: Literal["bdist_dumb"]) -> type[bdist_dumb]: ... + @overload + def get_command_class(self, command: Literal["bdist_rpm"]) -> type[bdist_rpm]: ... + @overload + def get_command_class(self, command: Literal["build"]) -> type[build]: ... + @overload + def get_command_class(self, command: Literal["build_clib"]) -> type[build_clib]: ... + @overload + def get_command_class(self, command: Literal["build_ext"]) -> type[build_ext]: ... + @overload + def get_command_class(self, command: Literal["build_py"]) -> type[build_py]: ... + @overload + def get_command_class(self, command: Literal["build_scripts"]) -> type[build_scripts]: ... + @overload + def get_command_class(self, command: Literal["check"]) -> type[check]: ... + @overload + def get_command_class(self, command: Literal["clean"]) -> type[clean]: ... + @overload + def get_command_class(self, command: Literal["config"]) -> type[config]: ... + @overload + def get_command_class(self, command: Literal["install"]) -> type[install]: ... + @overload + def get_command_class(self, command: Literal["install_data"]) -> type[install_data]: ... + @overload + def get_command_class(self, command: Literal["install_egg_info"]) -> type[install_egg_info]: ... + @overload + def get_command_class(self, command: Literal["install_headers"]) -> type[install_headers]: ... + @overload + def get_command_class(self, command: Literal["install_lib"]) -> type[install_lib]: ... + @overload + def get_command_class(self, command: Literal["install_scripts"]) -> type[install_scripts]: ... + @overload + def get_command_class(self, command: Literal["register"]) -> type[register]: ... + @overload + def get_command_class(self, command: Literal["sdist"]) -> type[sdist]: ... + @overload + def get_command_class(self, command: Literal["upload"]) -> type[upload]: ... + @overload + def get_command_class(self, command: str) -> type[Command]: ... + + @overload + def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool = False) -> bdist: ... + @overload + def reinitialize_command(self, command: Literal["bdist_dumb"], reinit_subcommands: bool = False) -> bdist_dumb: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False) -> build: ... + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False) -> build_py: ... + @overload + def reinitialize_command(self, command: Literal["build_scripts"], reinit_subcommands: bool = False) -> build_scripts: ... + @overload + def reinitialize_command(self, command: Literal["check"], reinit_subcommands: bool = False) -> check: ... + @overload + def reinitialize_command(self, command: Literal["clean"], reinit_subcommands: bool = False) -> clean: ... + @overload + def reinitialize_command(self, command: Literal["config"], reinit_subcommands: bool = False) -> config: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False) -> install: ... + @overload + def reinitialize_command(self, command: Literal["install_data"], reinit_subcommands: bool = False) -> install_data: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_headers"], reinit_subcommands: bool = False) -> install_headers: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False) -> install_lib: ... + @overload + def reinitialize_command(self, command: Literal["install_scripts"], reinit_subcommands: bool = False) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["register"], reinit_subcommands: bool = False) -> register: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["upload"], reinit_subcommands: bool = False) -> upload: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def announce(self, msg, level: int = 2) -> None: ... + def run_commands(self) -> None: ... + def run_command(self, command: str) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_modules(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data_files(self) -> bool: ... + def is_pure(self) -> bool: ... + + # Default getter methods generated in __init__ from self.metadata._METHOD_BASENAMES + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> str | list[str]: ... + def get_platforms(self) -> str | list[str]: ... + def get_classifiers(self) -> str | list[str]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> list[str]: ... + def get_provides(self) -> list[str]: ... + def get_obsoletes(self) -> list[str]: ... + + # Default attributes generated in __init__ from self.display_option_names + help_commands: bool | Literal[0] + name: str | Literal[0] + version: str | Literal[0] + fullname: str | Literal[0] + author: str | Literal[0] + author_email: str | Literal[0] + maintainer: str | Literal[0] + maintainer_email: str | Literal[0] + contact: str | Literal[0] + contact_email: str | Literal[0] + url: str | Literal[0] + license: str | Literal[0] + licence: str | Literal[0] + description: str | Literal[0] + long_description: str | Literal[0] + platforms: str | list[str] | Literal[0] + classifiers: str | list[str] | Literal[0] + keywords: str | list[str] | Literal[0] + provides: list[str] | Literal[0] + requires: list[str] | Literal[0] + obsoletes: list[str] | Literal[0] diff --git a/stdlib/distutils/errors.pyi b/stdlib/distutils/errors.pyi new file mode 100644 index 000000000000..e483362bfbf1 --- /dev/null +++ b/stdlib/distutils/errors.pyi @@ -0,0 +1,19 @@ +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... +class CCompilerError(Exception): ... +class PreprocessError(CCompilerError): ... +class CompileError(CCompilerError): ... +class LibError(CCompilerError): ... +class LinkError(CCompilerError): ... +class UnknownFileError(CCompilerError): ... diff --git a/stdlib/distutils/extension.pyi b/stdlib/distutils/extension.pyi new file mode 100644 index 000000000000..789bbf6ec3d1 --- /dev/null +++ b/stdlib/distutils/extension.pyi @@ -0,0 +1,36 @@ +class Extension: + name: str + sources: list[str] + include_dirs: list[str] + define_macros: list[tuple[str, str | None]] + undef_macros: list[str] + library_dirs: list[str] + libraries: list[str] + runtime_library_dirs: list[str] + extra_objects: list[str] + extra_compile_args: list[str] + extra_link_args: list[str] + export_symbols: list[str] + swig_opts: list[str] + depends: list[str] + language: str | None + optional: bool | None + def __init__( + self, + name: str, + sources: list[str], + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, + ) -> None: ... diff --git a/stdlib/distutils/fancy_getopt.pyi b/stdlib/distutils/fancy_getopt.pyi new file mode 100644 index 000000000000..676ce1bea313 --- /dev/null +++ b/stdlib/distutils/fancy_getopt.pyi @@ -0,0 +1,45 @@ +from collections.abc import Iterable, Mapping +from getopt import _SliceableT, _StrSequenceT_co +from re import Pattern +from typing import Any, Final, TypeAlias, overload + +_Option: TypeAlias = tuple[str, str | None, str] + +longopt_pat: Final = r"[a-zA-Z](?:[a-zA-Z0-9-]*)" +longopt_re: Final[Pattern[str]] +neg_alias_re: Final[Pattern[str]] +longopt_xlate: Final[dict[int, int]] + +class FancyGetopt: + def __init__(self, option_table: list[_Option] | None = None) -> None: ... + + # TODO: kinda wrong, `getopt(object=object())` is invalid + @overload + def getopt( + self, args: _SliceableT[_StrSequenceT_co] | None = None, object: None = None + ) -> tuple[_StrSequenceT_co, OptionDummy]: ... + @overload + def getopt( + self, args: _SliceableT[_StrSequenceT_co] | None, object: Any + ) -> _StrSequenceT_co: ... # object is an arbitrary non-slotted object + + def get_option_order(self) -> list[tuple[str, str]]: ... + def generate_help(self, header: str | None = None) -> list[str]: ... + +# Same note as FancyGetopt.getopt +@overload +def fancy_getopt( + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: None, args: _SliceableT[_StrSequenceT_co] | None +) -> tuple[_StrSequenceT_co, OptionDummy]: ... +@overload +def fancy_getopt( + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: _SliceableT[_StrSequenceT_co] | None +) -> _StrSequenceT_co: ... + +WS_TRANS: Final[dict[int, str]] + +def wrap_text(text: str, width: int) -> list[str]: ... +def translate_longopt(opt: str) -> str: ... + +class OptionDummy: + def __init__(self, options: Iterable[str] = []) -> None: ... diff --git a/stdlib/distutils/file_util.pyi b/stdlib/distutils/file_util.pyi new file mode 100644 index 000000000000..9d5bf5080b05 --- /dev/null +++ b/stdlib/distutils/file_util.pyi @@ -0,0 +1,40 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath +from collections.abc import Iterable +from typing import Literal, TypeVar, overload + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) + +@overload +def copy_file( + src: StrPath, + dst: _StrPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + update: bool | Literal[0, 1] = 0, + link: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> tuple[_StrPathT | str, bool]: ... +@overload +def copy_file( + src: BytesPath, + dst: _BytesPathT, + preserve_mode: bool | Literal[0, 1] = 1, + preserve_times: bool | Literal[0, 1] = 1, + update: bool | Literal[0, 1] = 0, + link: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, +) -> tuple[_BytesPathT | bytes, bool]: ... + +@overload +def move_file( + src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 +) -> _StrPathT | str: ... +@overload +def move_file( + src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 +) -> _BytesPathT | bytes: ... + +def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: ... diff --git a/stdlib/distutils/filelist.pyi b/stdlib/distutils/filelist.pyi new file mode 100644 index 000000000000..c3347fe7d1d2 --- /dev/null +++ b/stdlib/distutils/filelist.pyi @@ -0,0 +1,61 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Literal, overload + +# class is entirely undocumented +class FileList: + allfiles: Iterable[str] | None + files: list[str] + def __init__(self, warn: None = None, debug_print: None = None) -> None: ... + def set_allfiles(self, allfiles: Iterable[str]) -> None: ... + def findall(self, dir: str = ".") -> None: ... + def debug_print(self, msg: str) -> None: ... + def append(self, item: str) -> None: ... + def extend(self, items: Iterable[str]) -> None: ... + def sort(self) -> None: ... + def remove_duplicates(self) -> None: ... + def process_template_line(self, line: str) -> None: ... + + @overload + def include_pattern( + self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 + ) -> bool: ... + @overload + def include_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ... + @overload + def include_pattern( + self, + pattern: str | Pattern[str], + anchor: bool | Literal[0, 1] = 1, + prefix: str | None = None, + is_regex: bool | Literal[0, 1] = 0, + ) -> bool: ... + + @overload + def exclude_pattern( + self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 + ) -> bool: ... + @overload + def exclude_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ... + @overload + def exclude_pattern( + self, + pattern: str | Pattern[str], + anchor: bool | Literal[0, 1] = 1, + prefix: str | None = None, + is_regex: bool | Literal[0, 1] = 0, + ) -> bool: ... + +def findall(dir: str = ".") -> list[str]: ... +def glob_to_re(pattern: str) -> str: ... + +@overload +def translate_pattern( + pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[False, 0] = 0 +) -> Pattern[str]: ... +@overload +def translate_pattern(pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> Pattern[str]: ... +@overload +def translate_pattern( + pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: bool | Literal[0, 1] = 0 +) -> Pattern[str]: ... diff --git a/stdlib/distutils/log.pyi b/stdlib/distutils/log.pyi new file mode 100644 index 000000000000..7246dd6be0cd --- /dev/null +++ b/stdlib/distutils/log.pyi @@ -0,0 +1,26 @@ +from typing import Any, Final + +DEBUG: Final = 1 +INFO: Final = 2 +WARN: Final = 3 +ERROR: Final = 4 +FATAL: Final = 5 + +class Log: + def __init__(self, threshold: int = 3) -> None: ... + # Arbitrary msg args' type depends on the format method + def log(self, level: int, msg: str, *args: Any) -> None: ... + def debug(self, msg: str, *args: Any) -> None: ... + def info(self, msg: str, *args: Any) -> None: ... + def warn(self, msg: str, *args: Any) -> None: ... + def error(self, msg: str, *args: Any) -> None: ... + def fatal(self, msg: str, *args: Any) -> None: ... + +def log(level: int, msg: str, *args: Any) -> None: ... +def debug(msg: str, *args: Any) -> None: ... +def info(msg: str, *args: Any) -> None: ... +def warn(msg: str, *args: Any) -> None: ... +def error(msg: str, *args: Any) -> None: ... +def fatal(msg: str, *args: Any) -> None: ... +def set_threshold(level: int) -> int: ... +def set_verbosity(v: int) -> None: ... diff --git a/stdlib/distutils/msvccompiler.pyi b/stdlib/distutils/msvccompiler.pyi new file mode 100644 index 000000000000..80872a6b739f --- /dev/null +++ b/stdlib/distutils/msvccompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class MSVCCompiler(CCompiler): ... diff --git a/stdlib/distutils/spawn.pyi b/stdlib/distutils/spawn.pyi new file mode 100644 index 000000000000..ae07a49504fe --- /dev/null +++ b/stdlib/distutils/spawn.pyi @@ -0,0 +1,10 @@ +from collections.abc import Iterable +from typing import Literal + +def spawn( + cmd: Iterable[str], + search_path: bool | Literal[0, 1] = 1, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, +) -> None: ... +def find_executable(executable: str, path: str | None = None) -> str | None: ... diff --git a/stdlib/distutils/sysconfig.pyi b/stdlib/distutils/sysconfig.pyi new file mode 100644 index 000000000000..7c8e0e7b149e --- /dev/null +++ b/stdlib/distutils/sysconfig.pyi @@ -0,0 +1,32 @@ +from collections.abc import Mapping +from distutils.ccompiler import CCompiler +from typing import Final, Literal, overload +from typing_extensions import deprecated + +PREFIX: Final[str] +EXEC_PREFIX: Final[str] +BASE_PREFIX: Final[str] +BASE_EXEC_PREFIX: Final[str] +project_base: Final[str] +python_build: Final[bool] + +def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: ... + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload +def get_config_var(name: str) -> int | str | None: ... + +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... + +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = None) -> str: ... +def get_python_lib( + plat_specific: bool | Literal[0, 1] = 0, standard_lib: bool | Literal[0, 1] = 0, prefix: str | None = None +) -> str: ... +def customize_compiler(compiler: CCompiler) -> None: ... diff --git a/stdlib/distutils/text_file.pyi b/stdlib/distutils/text_file.pyi new file mode 100644 index 000000000000..54951af7e55d --- /dev/null +++ b/stdlib/distutils/text_file.pyi @@ -0,0 +1,21 @@ +from typing import IO, Literal + +class TextFile: + def __init__( + self, + filename: str | None = None, + file: IO[str] | None = None, + *, + strip_comments: bool | Literal[0, 1] = ..., + lstrip_ws: bool | Literal[0, 1] = ..., + rstrip_ws: bool | Literal[0, 1] = ..., + skip_blanks: bool | Literal[0, 1] = ..., + join_lines: bool | Literal[0, 1] = ..., + collapse_join: bool | Literal[0, 1] = ..., + ) -> None: ... + def open(self, filename: str) -> None: ... + def close(self) -> None: ... + def warn(self, msg: str, line: list[int] | tuple[int, int] | int | None = None) -> None: ... + def readline(self) -> str | None: ... + def readlines(self) -> list[str]: ... + def unreadline(self, line: str) -> str: ... diff --git a/stdlib/distutils/unixccompiler.pyi b/stdlib/distutils/unixccompiler.pyi new file mode 100644 index 000000000000..e1d443471af3 --- /dev/null +++ b/stdlib/distutils/unixccompiler.pyi @@ -0,0 +1,3 @@ +from distutils.ccompiler import CCompiler + +class UnixCCompiler(CCompiler): ... diff --git a/stdlib/distutils/util.pyi b/stdlib/distutils/util.pyi new file mode 100644 index 000000000000..0e1bb4165d99 --- /dev/null +++ b/stdlib/distutils/util.pyi @@ -0,0 +1,53 @@ +from _typeshed import StrPath, Unused +from collections.abc import Callable, Container, Iterable, Mapping +from typing import Any, Literal +from typing_extensions import TypeVarTuple, Unpack + +_Ts = TypeVarTuple("_Ts") + +def get_host_platform() -> str: ... +def get_platform() -> str: ... +def convert_path(pathname: str) -> str: ... +def change_root(new_root: StrPath, pathname: StrPath) -> str: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... +def split_quoted(s: str) -> list[str]: ... +def execute( + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + msg: str | None = None, + verbose: bool | Literal[0, 1] = 0, + dry_run: bool | Literal[0, 1] = 0, +) -> None: ... +def strtobool(val: str) -> Literal[0, 1]: ... +def byte_compile( + py_files: list[str], + optimize: int = 0, + force: bool | Literal[0, 1] = 0, + prefix: str | None = None, + base_dir: str | None = None, + verbose: bool | Literal[0, 1] = 1, + dry_run: bool | Literal[0, 1] = 0, + direct: bool | None = None, +) -> None: ... +def rfc822_escape(header: str) -> str: ... +def run_2to3( + files: Iterable[str], + fixer_names: Iterable[str] | None = None, + options: Mapping[str, Any] | None = None, + explicit: Unused = None, +) -> None: ... +def copydir_run_2to3( + src: StrPath, + dest: StrPath, + template: str | None = None, + fixer_names: Iterable[str] | None = None, + options: Mapping[str, Any] | None = None, + explicit: Container[str] | None = None, +) -> list[str]: ... + +class Mixin2to3: + fixer_names: Iterable[str] | None + options: Mapping[str, Any] | None + explicit: Container[str] | None + def run_2to3(self, files: Iterable[str]) -> None: ... diff --git a/stdlib/distutils/version.pyi b/stdlib/distutils/version.pyi new file mode 100644 index 000000000000..47da65ef87aa --- /dev/null +++ b/stdlib/distutils/version.pyi @@ -0,0 +1,36 @@ +from abc import abstractmethod +from re import Pattern +from typing_extensions import Self + +class Version: + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Self | str) -> bool: ... + def __le__(self, other: Self | str) -> bool: ... + def __gt__(self, other: Self | str) -> bool: ... + def __ge__(self, other: Self | str) -> bool: ... + @abstractmethod + def __init__(self, vstring: str | None = None) -> None: ... + @abstractmethod + def parse(self, vstring: str) -> Self: ... + @abstractmethod + def __str__(self) -> str: ... + @abstractmethod + def _cmp(self, other: Self | str) -> bool: ... + +class StrictVersion(Version): + version_re: Pattern[str] + version: tuple[int, int, int] + prerelease: tuple[str, int] | None + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa: Y029 + def _cmp(self, other: Self | str) -> bool: ... + +class LooseVersion(Version): + component_re: Pattern[str] + vstring: str + version: tuple[str | int, ...] + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa: Y029 + def _cmp(self, other: Self | str) -> bool: ... diff --git a/stdlib/doctest.pyi b/stdlib/doctest.pyi new file mode 100644 index 000000000000..7d1dfe6d8a92 --- /dev/null +++ b/stdlib/doctest.pyi @@ -0,0 +1,265 @@ +import sys +import types +import unittest +from _typeshed import ExcInfo +from collections.abc import Callable +from typing import Any, Final, NamedTuple, TypeAlias, type_check_only +from typing_extensions import Self + +__all__ = [ + "register_optionflag", + "DONT_ACCEPT_TRUE_FOR_1", + "DONT_ACCEPT_BLANKLINE", + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "SKIP", + "IGNORE_EXCEPTION_DETAIL", + "COMPARISON_FLAGS", + "REPORT_UDIFF", + "REPORT_CDIFF", + "REPORT_NDIFF", + "REPORT_ONLY_FIRST_FAILURE", + "REPORTING_FLAGS", + "FAIL_FAST", + "Example", + "DocTest", + "DocTestParser", + "DocTestFinder", + "DocTestRunner", + "OutputChecker", + "DocTestFailure", + "UnexpectedException", + "DebugRunner", + "testmod", + "testfile", + "run_docstring_examples", + "DocTestSuite", + "DocFileSuite", + "set_unittest_reportflags", + "script_from_examples", + "testsource", + "debug_src", + "debug", +] + +if sys.version_info >= (3, 13): + @type_check_only + class _TestResultsBase(NamedTuple): + failed: int + attempted: int + + class TestResults(_TestResultsBase): + def __new__(cls, failed: int, attempted: int, *, skipped: int = 0) -> Self: ... + skipped: int + +else: + class TestResults(NamedTuple): + failed: int + attempted: int + +OPTIONFLAGS_BY_NAME: Final[dict[str, int]] + +def register_optionflag(name: str) -> int: ... + +DONT_ACCEPT_TRUE_FOR_1: Final = 1 +DONT_ACCEPT_BLANKLINE: Final = 2 +NORMALIZE_WHITESPACE: Final = 4 +ELLIPSIS: Final = 8 +SKIP: Final = 16 +IGNORE_EXCEPTION_DETAIL: Final = 32 + +COMPARISON_FLAGS: Final = 63 + +REPORT_UDIFF: Final = 64 +REPORT_CDIFF: Final = 128 +REPORT_NDIFF: Final = 256 +REPORT_ONLY_FIRST_FAILURE: Final = 512 +FAIL_FAST: Final = 1024 + +REPORTING_FLAGS: Final = 1984 + +BLANKLINE_MARKER: Final = "" +ELLIPSIS_MARKER: Final = "..." + +class Example: + source: str + want: str + exc_msg: str | None + lineno: int + indent: int + options: dict[int, bool] + def __init__( + self, + source: str, + want: str, + exc_msg: str | None = None, + lineno: int = 0, + indent: int = 0, + options: dict[int, bool] | None = None, + ) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class DocTest: + examples: list[Example] + globs: dict[str, Any] + name: str + filename: str | None + lineno: int | None + docstring: str | None + def __init__( + self, + examples: list[Example], + globs: dict[str, Any], + name: str, + filename: str | None, + lineno: int | None, + docstring: str | None, + ) -> None: ... + def __hash__(self) -> int: ... + def __lt__(self, other: DocTest) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class DocTestParser: + def parse(self, string: str, name: str = "") -> list[str | Example]: ... + def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... + def get_examples(self, string: str, name: str = "") -> list[Example]: ... + +class DocTestFinder: + def __init__( + self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True + ) -> None: ... + def find( + self, + obj: object, + name: str | None = None, + module: None | bool | types.ModuleType = None, + globs: dict[str, Any] | None = None, + extraglobs: dict[str, Any] | None = None, + ) -> list[DocTest]: ... + +_Out: TypeAlias = Callable[[str], object] + +class DocTestRunner: + DIVIDER: str + optionflags: int + original_optionflags: int + tries: int + failures: int + if sys.version_info >= (3, 13): + skips: int + test: DocTest + def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ... + if sys.version_info >= (3, 15): + def report_skip(self, out: _Out, test: DocTest, example: Example) -> None: ... + + def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ... + def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ... + def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... + def run( + self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True + ) -> TestResults: ... + def summarize(self, verbose: bool | None = None) -> TestResults: ... + def merge(self, other: DocTestRunner) -> None: ... + +class OutputChecker: + def check_output(self, want: str, got: str, optionflags: int) -> bool: ... + def output_difference(self, example: Example, got: str, optionflags: int) -> str: ... + +class DocTestFailure(Exception): + test: DocTest + example: Example + got: str + def __init__(self, test: DocTest, example: Example, got: str) -> None: ... + +class UnexpectedException(Exception): + test: DocTest + example: Example + exc_info: ExcInfo + def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ... + +class DebugRunner(DocTestRunner): ... + +master: DocTestRunner | None + +def testmod( + m: types.ModuleType | None = None, + name: str | None = None, + globs: dict[str, Any] | None = None, + verbose: bool | None = None, + report: bool = True, + optionflags: int = 0, + extraglobs: dict[str, Any] | None = None, + raise_on_error: bool = False, + exclude_empty: bool = False, +) -> TestResults: ... +def testfile( + filename: str, + module_relative: bool = True, + name: str | None = None, + package: None | str | types.ModuleType = None, + globs: dict[str, Any] | None = None, + verbose: bool | None = None, + report: bool = True, + optionflags: int = 0, + extraglobs: dict[str, Any] | None = None, + raise_on_error: bool = False, + parser: DocTestParser = ..., + encoding: str | None = None, +) -> TestResults: ... +def run_docstring_examples( + f: object, + globs: dict[str, Any], + verbose: bool = False, + name: str = "NoName", + compileflags: int | None = None, + optionflags: int = 0, +) -> None: ... +def set_unittest_reportflags(flags: int) -> int: ... + +class DocTestCase(unittest.TestCase): + def __init__( + self, + test: DocTest, + optionflags: int = 0, + setUp: Callable[[DocTest], object] | None = None, + tearDown: Callable[[DocTest], object] | None = None, + checker: OutputChecker | None = None, + ) -> None: ... + def runTest(self) -> None: ... + def format_failure(self, err: str) -> str: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class SkipDocTestCase(DocTestCase): + def __init__(self, module: types.ModuleType) -> None: ... + def test_skip(self) -> None: ... + +class _DocTestSuite(unittest.TestSuite): ... + +def DocTestSuite( + module: None | str | types.ModuleType = None, + globs: dict[str, Any] | None = None, + extraglobs: dict[str, Any] | None = None, + test_finder: DocTestFinder | None = None, + **options: Any, +) -> _DocTestSuite: ... + +class DocFileCase(DocTestCase): ... + +def DocFileTest( + path: str, + module_relative: bool = True, + package: None | str | types.ModuleType = None, + globs: dict[str, Any] | None = None, + parser: DocTestParser = ..., + encoding: str | None = None, + **options: Any, +) -> DocFileCase: ... +def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... +def script_from_examples(s: str) -> str: ... +def testsource(module: None | str | types.ModuleType, name: str) -> str: ... +def debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... +def debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... +def debug(module: None | str | types.ModuleType, name: str, pm: bool = False) -> None: ... diff --git a/stdlib/email/__init__.pyi b/stdlib/email/__init__.pyi new file mode 100644 index 000000000000..aabdca32d506 --- /dev/null +++ b/stdlib/email/__init__.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable +from email._policybase import _MessageT +from email.message import Message +from email.policy import Policy +from typing import IO, TypeAlias, overload + +# At runtime, listing submodules in __all__ without them being imported is +# valid, and causes them to be included in a star import. See #6523 + +__all__ = [ # noqa: F822 # Undefined names in __all__ + "base64mime", # pyright: ignore[reportUnsupportedDunderAll] + "charset", # pyright: ignore[reportUnsupportedDunderAll] + "encoders", # pyright: ignore[reportUnsupportedDunderAll] + "errors", # pyright: ignore[reportUnsupportedDunderAll] + "feedparser", # pyright: ignore[reportUnsupportedDunderAll] + "generator", # pyright: ignore[reportUnsupportedDunderAll] + "header", # pyright: ignore[reportUnsupportedDunderAll] + "iterators", # pyright: ignore[reportUnsupportedDunderAll] + "message", # pyright: ignore[reportUnsupportedDunderAll] + "message_from_file", + "message_from_binary_file", + "message_from_string", + "message_from_bytes", + "mime", # pyright: ignore[reportUnsupportedDunderAll] + "parser", # pyright: ignore[reportUnsupportedDunderAll] + "quoprimime", # pyright: ignore[reportUnsupportedDunderAll] + "utils", # pyright: ignore[reportUnsupportedDunderAll] +] + +# Definitions imported by multiple submodules in typeshed +_ParamType: TypeAlias = str | tuple[str | None, str | None, str] # noqa: Y047 +_ParamsType: TypeAlias = str | None | tuple[str, str | None, str] # noqa: Y047 + +@overload +def message_from_string(s: str) -> Message: ... +@overload +def message_from_string(s: str, _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_string(s: str, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... + +@overload +def message_from_bytes(s: bytes | bytearray) -> Message: ... +@overload +def message_from_bytes(s: bytes | bytearray, _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_bytes( + s: bytes | bytearray, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT] +) -> _MessageT: ... + +@overload +def message_from_file(fp: IO[str]) -> Message: ... +@overload +def message_from_file(fp: IO[str], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_file(fp: IO[str], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... + +@overload +def message_from_binary_file(fp: IO[bytes]) -> Message: ... +@overload +def message_from_binary_file(fp: IO[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def message_from_binary_file(fp: IO[bytes], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... diff --git a/stdlib/email/_header_value_parser.pyi b/stdlib/email/_header_value_parser.pyi new file mode 100644 index 000000000000..e75e7ba1cf06 --- /dev/null +++ b/stdlib/email/_header_value_parser.pyi @@ -0,0 +1,414 @@ +import sys +from collections.abc import Iterable, Iterator +from email.errors import HeaderParseError, MessageDefect +from email.policy import Policy +from re import Pattern +from typing import Any, Final +from typing_extensions import Self + +WSP: Final[set[str]] +CFWS_LEADER: Final[set[str]] +SPECIALS: Final[set[str]] +ATOM_ENDS: Final[set[str]] +DOT_ATOM_ENDS: Final[set[str]] +PHRASE_ENDS: Final[set[str]] +TSPECIALS: Final[set[str]] +TOKEN_ENDS: Final[set[str]] +ASPECIALS: Final[set[str]] +ATTRIBUTE_ENDS: Final[set[str]] +EXTENDED_ATTRIBUTE_ENDS: Final[set[str]] +# Added in Python 3.10.15, 3.11.10, 3.12.5 +NLSET: Final[set[str]] +# Added in Python 3.10.15, 3.11.10, 3.12.5 +SPECIALSNL: Final[set[str]] + +# Added in Python 3.10.17, 3.11.12, 3.12.9, 3.13.2 +def make_quoted_pairs(value: Any) -> str: ... +def quote_string(value: Any) -> str: ... + +# Added in Python 3.10.20, 3.11.15, 3.12.13, 3.13.12, 3.14.3 +def make_parenthesis_pairs(value: Any) -> str: ... + +rfc2047_matcher: Final[Pattern[str]] + +class TokenList(list[TokenList | Terminal]): + token_type: str | None + syntactic_break: bool + ew_combine_allowed: bool + defects: list[MessageDefect] + def __init__(self, *args: Any, **kw: Any) -> None: ... + @property + def value(self) -> str: ... + @property + def all_defects(self) -> list[MessageDefect]: ... + def startswith_fws(self) -> bool: ... + @property + def as_ew_allowed(self) -> bool: ... + @property + def comments(self) -> list[str]: ... + def fold(self, *, policy: Policy) -> str: ... + def pprint(self, indent: str = "") -> None: ... + def ppstr(self, indent: str = "") -> str: ... + +class WhiteSpaceTokenList(TokenList): ... + +class UnstructuredTokenList(TokenList): + token_type: str + +class Phrase(TokenList): + token_type: str + +class Word(TokenList): + token_type: str + +class CFWSList(WhiteSpaceTokenList): + token_type: str + +class Atom(TokenList): + token_type: str + +class Token(TokenList): + token_type: str + encode_as_ew: bool + +class EncodedWord(TokenList): + token_type: str + cte: str | None + charset: str | None + lang: str | None + +class QuotedString(TokenList): + token_type: str + @property + def content(self) -> str: ... + @property + def quoted_value(self) -> str: ... + @property + def stripped_value(self) -> str: ... + +class BareQuotedString(QuotedString): + token_type: str + +class Comment(WhiteSpaceTokenList): + token_type: str + def quote(self, value: Any) -> str: ... + @property + def content(self) -> str: ... + +class AddressList(TokenList): + token_type: str + @property + def addresses(self) -> list[Address]: ... + @property + def mailboxes(self) -> list[Mailbox]: ... + @property + def all_mailboxes(self) -> list[Mailbox]: ... + +class Address(TokenList): + token_type: str + @property + def display_name(self) -> str: ... + @property + def mailboxes(self) -> list[Mailbox]: ... + @property + def all_mailboxes(self) -> list[Mailbox]: ... + +class MailboxList(TokenList): + token_type: str + @property + def mailboxes(self) -> list[Mailbox]: ... + @property + def all_mailboxes(self) -> list[Mailbox]: ... + +class GroupList(TokenList): + token_type: str + @property + def mailboxes(self) -> list[Mailbox]: ... + @property + def all_mailboxes(self) -> list[Mailbox]: ... + +class Group(TokenList): + token_type: str + @property + def mailboxes(self) -> list[Mailbox]: ... + @property + def all_mailboxes(self) -> list[Mailbox]: ... + @property + def display_name(self) -> str: ... + +class NameAddr(TokenList): + token_type: str + @property + def display_name(self) -> str: ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> list[Domain] | None: ... + @property + def addr_spec(self) -> str: ... + +class AngleAddr(TokenList): + token_type: str + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> list[Domain] | None: ... + @property + def addr_spec(self) -> str: ... + +class ObsRoute(TokenList): + token_type: str + @property + def domains(self) -> list[Domain]: ... + +class Mailbox(TokenList): + token_type: str + @property + def display_name(self) -> str: ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> list[str]: ... + @property + def addr_spec(self) -> str: ... + +class InvalidMailbox(TokenList): + token_type: str + @property + def display_name(self) -> None: ... + @property + def local_part(self) -> None: ... + @property + def domain(self) -> None: ... + @property + def route(self) -> None: ... + @property + def addr_spec(self) -> None: ... + +class Domain(TokenList): + token_type: str + as_ew_allowed: bool + @property + def domain(self) -> str: ... + +class DotAtom(TokenList): + token_type: str + +class DotAtomText(TokenList): + token_type: str + as_ew_allowed: bool + +class NoFoldLiteral(TokenList): + token_type: str + as_ew_allowed: bool + +class AddrSpec(TokenList): + token_type: str + as_ew_allowed: bool + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def addr_spec(self) -> str: ... + +class ObsLocalPart(TokenList): + token_type: str + as_ew_allowed: bool + +class DisplayName(Phrase): + token_type: str + @property + def display_name(self) -> str: ... + +class LocalPart(TokenList): + token_type: str + as_ew_allowed: bool + @property + def local_part(self) -> str: ... + +class DomainLiteral(TokenList): + token_type: str + as_ew_allowed: bool + @property + def domain(self) -> str: ... + @property + def ip(self) -> str: ... + +class MIMEVersion(TokenList): + token_type: str + major: int | None + minor: int | None + +class Parameter(TokenList): + token_type: str + sectioned: bool + extended: bool + charset: str + @property + def section_number(self) -> int: ... + @property + def param_value(self) -> str: ... + +class InvalidParameter(Parameter): + token_type: str + +class Attribute(TokenList): + token_type: str + @property + def stripped_value(self) -> str: ... + +class Section(TokenList): + token_type: str + number: int | None + +class Value(TokenList): + token_type: str + @property + def stripped_value(self) -> str: ... + +class MimeParameters(TokenList): + token_type: str + syntactic_break: bool + @property + def params(self) -> Iterator[tuple[str, str]]: ... + +class ParameterizedHeaderValue(TokenList): + syntactic_break: bool + @property + def params(self) -> Iterable[tuple[str, str]]: ... + +class ContentType(ParameterizedHeaderValue): + token_type: str + as_ew_allowed: bool + maintype: str + subtype: str + +class ContentDisposition(ParameterizedHeaderValue): + token_type: str + as_ew_allowed: bool + content_disposition: Any + +class ContentTransferEncoding(TokenList): + token_type: str + as_ew_allowed: bool + cte: str + +class HeaderLabel(TokenList): + token_type: str + as_ew_allowed: bool + +class MsgID(TokenList): + token_type: str + as_ew_allowed: bool + def fold(self, policy: Policy) -> str: ... + +class MessageID(MsgID): + token_type: str + +class InvalidMessageID(MessageID): + token_type: str + +if sys.version_info >= (3, 13): + # Added in Python 3.13.12, 3.14.3 + class MessageIDList(TokenList): + token_type: str + @property + def message_ids(self) -> list[MsgID | Terminal]: ... + +class Header(TokenList): + token_type: str + +class Terminal(str): + as_ew_allowed: bool + ew_combine_allowed: bool + syntactic_break: bool + token_type: str + defects: list[MessageDefect] + def __new__(cls, value: str, token_type: str) -> Self: ... + def pprint(self) -> None: ... + @property + def all_defects(self) -> list[MessageDefect]: ... + def pop_trailing_ws(self) -> None: ... + @property + def comments(self) -> list[str]: ... + def __getnewargs__(self) -> tuple[str, str]: ... # type: ignore[override] + +class WhiteSpaceTerminal(Terminal): + @property + def value(self) -> str: ... + def startswith_fws(self) -> bool: ... + +class ValueTerminal(Terminal): + @property + def value(self) -> ValueTerminal: ... + def startswith_fws(self) -> bool: ... + +class EWWhiteSpaceTerminal(WhiteSpaceTerminal): ... +class _InvalidEwError(HeaderParseError): ... + +DOT: Final[ValueTerminal] +ListSeparator: Final[ValueTerminal] +RouteComponentMarker: Final[ValueTerminal] + +def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: ... +def get_encoded_word(value: str, terminal_type: str = "vtext") -> tuple[EncodedWord, str]: ... +def get_unstructured(value: str) -> UnstructuredTokenList: ... +def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: ... +def get_qcontent(value: str) -> tuple[ValueTerminal, str]: ... +def get_atext(value: str) -> tuple[ValueTerminal, str]: ... +def get_bare_quoted_string(value: str) -> tuple[BareQuotedString, str]: ... +def get_comment(value: str) -> tuple[Comment, str]: ... +def get_cfws(value: str) -> tuple[CFWSList, str]: ... +def get_quoted_string(value: str) -> tuple[QuotedString, str]: ... +def get_atom(value: str) -> tuple[Atom, str]: ... +def get_dot_atom_text(value: str) -> tuple[DotAtomText, str]: ... +def get_dot_atom(value: str) -> tuple[DotAtom, str]: ... +def get_word(value: str) -> tuple[Any, str]: ... +def get_phrase(value: str) -> tuple[Phrase, str]: ... +def get_local_part(value: str) -> tuple[LocalPart, str]: ... +def get_obs_local_part(value: str) -> tuple[ObsLocalPart, str]: ... +def get_dtext(value: str) -> tuple[ValueTerminal, str]: ... +def get_domain_literal(value: str) -> tuple[DomainLiteral, str]: ... +def get_domain(value: str) -> tuple[Domain, str]: ... +def get_addr_spec(value: str) -> tuple[AddrSpec, str]: ... +def get_obs_route(value: str) -> tuple[ObsRoute, str]: ... +def get_angle_addr(value: str) -> tuple[AngleAddr, str]: ... +def get_display_name(value: str) -> tuple[DisplayName, str]: ... +def get_name_addr(value: str) -> tuple[NameAddr, str]: ... +def get_mailbox(value: str) -> tuple[Mailbox, str]: ... +def get_invalid_mailbox(value: str, endchars: str) -> tuple[InvalidMailbox, str]: ... +def get_mailbox_list(value: str) -> tuple[MailboxList, str]: ... +def get_group_list(value: str) -> tuple[GroupList, str]: ... +def get_group(value: str) -> tuple[Group, str]: ... +def get_address(value: str) -> tuple[Address, str]: ... +def get_address_list(value: str) -> tuple[AddressList, str]: ... +def get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ... +def get_msg_id(value: str) -> tuple[MsgID, str]: ... +def parse_message_id(value: str) -> MessageID: ... + +if sys.version_info >= (3, 13): + # Added in Python 3.13.12, 3.14.3 + def parse_message_ids(value: str) -> MessageIDList: ... + +def parse_mime_version(value: str) -> MIMEVersion: ... +def get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]: ... +def get_ttext(value: str) -> tuple[ValueTerminal, str]: ... +def get_token(value: str) -> tuple[Token, str]: ... +def get_attrtext(value: str) -> tuple[ValueTerminal, str]: ... +def get_attribute(value: str) -> tuple[Attribute, str]: ... +def get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]: ... +def get_extended_attribute(value: str) -> tuple[Attribute, str]: ... +def get_section(value: str) -> tuple[Section, str]: ... +def get_value(value: str) -> tuple[Value, str]: ... +def get_parameter(value: str) -> tuple[Parameter, str]: ... +def parse_mime_parameters(value: str) -> MimeParameters: ... +def parse_content_type_header(value: str) -> ContentType: ... +def parse_content_disposition_header(value: str) -> ContentDisposition: ... +def parse_content_transfer_encoding_header(value: str) -> ContentTransferEncoding: ... diff --git a/stdlib/email/_policybase.pyi b/stdlib/email/_policybase.pyi new file mode 100644 index 000000000000..0fb890d424b1 --- /dev/null +++ b/stdlib/email/_policybase.pyi @@ -0,0 +1,80 @@ +from abc import ABCMeta, abstractmethod +from email.errors import MessageDefect +from email.header import Header +from email.message import Message +from typing import Any, Generic, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +__all__ = ["Policy", "Compat32", "compat32"] + +_MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Message[str, str]) +_MessageT_co = TypeVar("_MessageT_co", covariant=True, bound=Message[Any, Any], default=Message[str, str]) + +@type_check_only +class _MessageFactory(Protocol[_MessageT]): + def __call__(self, policy: Policy[_MessageT]) -> _MessageT: ... + +# Policy below is the only known direct subclass of _PolicyBase. We therefore +# assume that the __init__ arguments and attributes of _PolicyBase are +# the same as those of Policy. +class _PolicyBase(Generic[_MessageT_co]): + max_line_length: int | None + linesep: str + cte_type: str + raise_on_defect: bool + mangle_from_: bool + message_factory: _MessageFactory[_MessageT_co] | None + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool + + def __init__( + self, + *, + max_line_length: int | None = 78, + linesep: str = "\n", + cte_type: str = "8bit", + raise_on_defect: bool = False, + mangle_from_: bool = ..., # default depends on sub-class + message_factory: _MessageFactory[_MessageT_co] | None = None, + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = True, + ) -> None: ... + def clone( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: _MessageFactory[_MessageT_co] | None = ..., + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., + ) -> Self: ... + def __add__(self, other: Policy) -> Self: ... + +class Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta): + # Every Message object has a `defects` attribute, so the following + # methods will work for any Message object. + def handle_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ... + def register_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ... + def header_max_count(self, name: str) -> int | None: ... + @abstractmethod + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... + @abstractmethod + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... + @abstractmethod + def header_fetch_parse(self, name: str, value: str) -> str: ... + @abstractmethod + def fold(self, name: str, value: str) -> str: ... + @abstractmethod + def fold_binary(self, name: str, value: str) -> bytes: ... + +class Compat32(Policy[_MessageT_co]): + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... + def header_fetch_parse(self, name: str, value: str) -> str | Header: ... # type: ignore[override] + def fold(self, name: str, value: str) -> str: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + +compat32: Compat32[Message[str, str]] diff --git a/stdlib/email/base64mime.pyi b/stdlib/email/base64mime.pyi new file mode 100644 index 000000000000..563cd7f669a2 --- /dev/null +++ b/stdlib/email/base64mime.pyi @@ -0,0 +1,13 @@ +__all__ = ["body_decode", "body_encode", "decode", "decodestring", "header_encode", "header_length"] + +from _typeshed import ReadableBuffer + +def header_length(bytearray: str | bytes | bytearray) -> int: ... +def header_encode(header_bytes: str | ReadableBuffer, charset: str = "iso-8859-1") -> str: ... + +# First argument should be a buffer that supports slicing and len(). +def body_encode(s: bytes | bytearray, maxlinelen: int = 76, eol: str = "\n") -> str: ... +def decode(string: str | ReadableBuffer) -> bytes: ... + +body_decode = decode +decodestring = decode diff --git a/stdlib/email/charset.pyi b/stdlib/email/charset.pyi new file mode 100644 index 000000000000..353cdeb0b9dd --- /dev/null +++ b/stdlib/email/charset.pyi @@ -0,0 +1,44 @@ +from collections.abc import Callable, Iterator +from email.message import Message +from typing import ClassVar, Final, overload + +__all__ = ["Charset", "add_alias", "add_charset", "add_codec"] + +QP: Final = 1 # undocumented +BASE64: Final = 2 # undocumented +SHORTEST: Final = 3 # undocumented +RFC2047_CHROME_LEN: Final = 7 # undocumented +DEFAULT_CHARSET: Final = "us-ascii" # undocumented +UNKNOWN8BIT: Final = "unknown-8bit" # undocumented +EMPTYSTRING: Final = "" # undocumented +CHARSETS: Final[dict[str, tuple[int | None, int | None, str | None]]] +ALIASES: Final[dict[str, str]] +CODEC_MAP: Final[dict[str, str | None]] # undocumented + +class Charset: + input_charset: str + header_encoding: int + body_encoding: int + output_charset: str | None + input_codec: str | None + output_codec: str | None + def __init__(self, input_charset: str = "us-ascii") -> None: ... + def get_body_encoding(self) -> str | Callable[[Message], None]: ... + def get_output_charset(self) -> str | None: ... + def header_encode(self, string: str) -> str: ... + def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str | None]: ... + + @overload + def body_encode(self, string: None) -> None: ... + @overload + def body_encode(self, string: str | bytes) -> str: ... + + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + +def add_charset( + charset: str, header_enc: int | None = None, body_enc: int | None = None, output_charset: str | None = None +) -> None: ... +def add_alias(alias: str, canonical: str) -> None: ... +def add_codec(charset: str, codecname: str) -> None: ... diff --git a/stdlib/email/contentmanager.pyi b/stdlib/email/contentmanager.pyi new file mode 100644 index 000000000000..3214f1a4781d --- /dev/null +++ b/stdlib/email/contentmanager.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable +from email.message import Message +from typing import Any + +class ContentManager: + def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ... + def set_content(self, msg: Message, obj: Any, *args: Any, **kw: Any) -> Any: ... + def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ... + def add_set_handler(self, typekey: type, handler: Callable[..., Any]) -> None: ... + +raw_data_manager: ContentManager diff --git a/stdlib/email/encoders.pyi b/stdlib/email/encoders.pyi new file mode 100644 index 000000000000..55223bdc0762 --- /dev/null +++ b/stdlib/email/encoders.pyi @@ -0,0 +1,8 @@ +from email.message import Message + +__all__ = ["encode_7or8bit", "encode_base64", "encode_noop", "encode_quopri"] + +def encode_base64(msg: Message) -> None: ... +def encode_quopri(msg: Message) -> None: ... +def encode_7or8bit(msg: Message) -> None: ... +def encode_noop(msg: Message) -> None: ... diff --git a/stdlib/email/errors.pyi b/stdlib/email/errors.pyi new file mode 100644 index 000000000000..4da60250965e --- /dev/null +++ b/stdlib/email/errors.pyi @@ -0,0 +1,38 @@ +class MessageError(Exception): ... +class MessageParseError(MessageError): ... +class HeaderParseError(MessageParseError): ... +class BoundaryError(MessageParseError): ... +class MultipartConversionError(MessageError, TypeError): ... +class CharsetError(MessageError): ... + +# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +class HeaderWriteError(MessageError): ... + +class MessageDefect(ValueError): + def __init__(self, line: str | None = None) -> None: ... + +class NoBoundaryInMultipartDefect(MessageDefect): ... +class StartBoundaryNotFoundDefect(MessageDefect): ... +class FirstHeaderLineIsContinuationDefect(MessageDefect): ... +class MisplacedEnvelopeHeaderDefect(MessageDefect): ... +class MultipartInvariantViolationDefect(MessageDefect): ... +class InvalidMultipartContentTransferEncodingDefect(MessageDefect): ... +class UndecodableBytesDefect(MessageDefect): ... +class InvalidBase64PaddingDefect(MessageDefect): ... +class InvalidBase64CharactersDefect(MessageDefect): ... +class InvalidBase64LengthDefect(MessageDefect): ... +class CloseBoundaryNotFoundDefect(MessageDefect): ... +class MissingHeaderBodySeparatorDefect(MessageDefect): ... + +MalformedHeaderDefect = MissingHeaderBodySeparatorDefect + +class HeaderDefect(MessageDefect): ... +class InvalidHeaderDefect(HeaderDefect): ... +class HeaderMissingRequiredValue(HeaderDefect): ... + +class NonPrintableDefect(HeaderDefect): + def __init__(self, non_printables: str | None) -> None: ... + +class ObsoleteHeaderDefect(HeaderDefect): ... +class NonASCIILocalPartDefect(HeaderDefect): ... +class InvalidDateDefect(HeaderDefect): ... diff --git a/stdlib/email/feedparser.pyi b/stdlib/email/feedparser.pyi new file mode 100644 index 000000000000..ec92eef67886 --- /dev/null +++ b/stdlib/email/feedparser.pyi @@ -0,0 +1,24 @@ +from collections.abc import Callable +from email._policybase import _MessageT +from email.message import Message +from email.policy import Policy +from typing import Generic, overload + +__all__ = ["FeedParser", "BytesFeedParser"] + +class FeedParser(Generic[_MessageT]): + @overload + def __init__(self: FeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... + @overload + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + + def feed(self, data: str) -> None: ... + def close(self) -> _MessageT: ... + +class BytesFeedParser(FeedParser[_MessageT]): + @overload + def __init__(self: BytesFeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... + @overload + def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + + def feed(self, data: bytes | bytearray) -> None: ... # type: ignore[override] diff --git a/stdlib/email/generator.pyi b/stdlib/email/generator.pyi new file mode 100644 index 000000000000..c2a9bb0921d7 --- /dev/null +++ b/stdlib/email/generator.pyi @@ -0,0 +1,79 @@ +from _typeshed import SupportsWrite +from email.message import Message +from email.policy import Policy +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +__all__ = ["Generator", "DecodedGenerator", "BytesGenerator"] + +# By default, generators do not have a message policy. +_MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Any) + +class Generator(Generic[_MessageT]): + maxheaderlen: int | None + policy: Policy[_MessageT] | None + + @overload + def __init__( + self: Generator[Any], # The Policy of the message is used. + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: None = None, + ) -> None: ... + @overload + def __init__( + self, + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: Policy[_MessageT], + ) -> None: ... + + def write(self, s: str) -> None: ... + def flatten(self, msg: _MessageT, unixfrom: bool = False, linesep: str | None = None) -> None: ... + def clone(self, fp: SupportsWrite[str]) -> Self: ... + +class BytesGenerator(Generator[_MessageT]): + @overload + def __init__( + self: BytesGenerator[Any], # The Policy of the message is used. + outfp: SupportsWrite[bytes], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: None = None, + ) -> None: ... + @overload + def __init__( + self, + outfp: SupportsWrite[bytes], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + *, + policy: Policy[_MessageT], + ) -> None: ... + +class DecodedGenerator(Generator[_MessageT]): + @overload + def __init__( + self: DecodedGenerator[Any], # The Policy of the message is used. + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + fmt: str | None = None, + *, + policy: None = None, + ) -> None: ... + @overload + def __init__( + self, + outfp: SupportsWrite[str], + mangle_from_: bool | None = None, + maxheaderlen: int | None = None, + fmt: str | None = None, + *, + policy: Policy[_MessageT], + ) -> None: ... diff --git a/stdlib/email/header.pyi b/stdlib/email/header.pyi new file mode 100644 index 000000000000..a26bbb516e09 --- /dev/null +++ b/stdlib/email/header.pyi @@ -0,0 +1,32 @@ +from collections.abc import Iterable +from email.charset import Charset +from typing import Any, ClassVar + +__all__ = ["Header", "decode_header", "make_header"] + +class Header: + def __init__( + self, + s: bytes | bytearray | str | None = None, + charset: Charset | str | None = None, + maxlinelen: int | None = None, + header_name: str | None = None, + continuation_ws: str = " ", + errors: str = "strict", + ) -> None: ... + def append(self, s: bytes | bytearray | str, charset: Charset | str | None = None, errors: str = "strict") -> None: ... + def encode(self, splitchars: str = ";, \t", maxlinelen: int | None = None, linesep: str = "\n") -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + +# decode_header() either returns list[tuple[str, None]] if the header +# contains no encoded parts, or list[tuple[bytes, str | None]] if the header +# contains at least one encoded part. +def decode_header(header: Header | str) -> list[tuple[Any, Any | None]]: ... +def make_header( + decoded_seq: Iterable[tuple[bytes | bytearray | str, str | None]], + maxlinelen: int | None = None, + header_name: str | None = None, + continuation_ws: str = " ", +) -> Header: ... diff --git a/stdlib/email/headerregistry.pyi b/stdlib/email/headerregistry.pyi new file mode 100644 index 000000000000..8033f0ab4356 --- /dev/null +++ b/stdlib/email/headerregistry.pyi @@ -0,0 +1,193 @@ +import sys +import types +from collections.abc import Iterable, Mapping +from datetime import datetime as _datetime +from email._header_value_parser import ( + AddressList, + ContentDisposition, + ContentTransferEncoding, + ContentType, + MessageID, + MIMEVersion, + TokenList, + UnstructuredTokenList, +) +from email.errors import MessageDefect +from email.policy import Policy +from typing import Any, ClassVar, Literal, Protocol, type_check_only +from typing_extensions import Self + +class BaseHeader(str): + # max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses) + max_count: ClassVar[Literal[1] | None] + @property + def name(self) -> str: ... + @property + def defects(self) -> tuple[MessageDefect, ...]: ... + def __new__(cls, name: str, value: Any) -> Self: ... + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... + def fold(self, *, policy: Policy) -> str: ... + +class UnstructuredHeader: + max_count: ClassVar[Literal[1] | None] + @staticmethod + def value_parser(value: str) -> UnstructuredTokenList: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + +class UniqueUnstructuredHeader(UnstructuredHeader): + max_count: ClassVar[Literal[1]] + +class DateHeader: + max_count: ClassVar[Literal[1] | None] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], datetime: _datetime) -> None: ... + @property + def datetime(self) -> _datetime | None: ... + @staticmethod + def value_parser(value: str) -> UnstructuredTokenList: ... + @classmethod + def parse(cls, value: str | _datetime, kwds: dict[str, Any]) -> None: ... + +class UniqueDateHeader(DateHeader): + max_count: ClassVar[Literal[1]] + +class AddressHeader: + max_count: ClassVar[Literal[1] | None] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], groups: Iterable[Group]) -> None: ... + @property + def groups(self) -> tuple[Group, ...]: ... + @property + def addresses(self) -> tuple[Address, ...]: ... + @staticmethod + def value_parser(value: str) -> AddressList: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + +class UniqueAddressHeader(AddressHeader): + max_count: ClassVar[Literal[1]] + +class SingleAddressHeader(AddressHeader): + @property + def address(self) -> Address: ... + +class UniqueSingleAddressHeader(SingleAddressHeader): + max_count: ClassVar[Literal[1]] + +class MIMEVersionHeader: + max_count: ClassVar[Literal[1]] + def init( + self, + name: str, + *, + parse_tree: TokenList, + defects: Iterable[MessageDefect], + version: str | None, + major: int | None, + minor: int | None, + ) -> None: ... + @property + def version(self) -> str | None: ... + @property + def major(self) -> int | None: ... + @property + def minor(self) -> int | None: ... + @staticmethod + def value_parser(value: str) -> MIMEVersion: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + +class ParameterizedMIMEHeader: + max_count: ClassVar[Literal[1]] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], params: Mapping[str, Any]) -> None: ... + @property + def params(self) -> types.MappingProxyType[str, Any]: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + +class ContentTypeHeader(ParameterizedMIMEHeader): + @property + def content_type(self) -> str: ... + @property + def maintype(self) -> str: ... + @property + def subtype(self) -> str: ... + @staticmethod + def value_parser(value: str) -> ContentType: ... + +class ContentDispositionHeader(ParameterizedMIMEHeader): + # init is redefined but has the same signature as parent class, so is omitted from the stub + @property + def content_disposition(self) -> str | None: ... + @staticmethod + def value_parser(value: str) -> ContentDisposition: ... + +class ContentTransferEncodingHeader: + max_count: ClassVar[Literal[1]] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... + @property + def cte(self) -> str: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> ContentTransferEncoding: ... + +class MessageIDHeader: + max_count: ClassVar[Literal[1]] + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> MessageID: ... + +if sys.version_info >= (3, 13): + from email._header_value_parser import MessageIDList + + # Added in Python 3.13.12, 3.14.3 + class ReferencesHeader: + max_count: ClassVar[Literal[1]] + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> MessageIDList: ... + +@type_check_only +class _HeaderParser(Protocol): + max_count: ClassVar[Literal[1] | None] + @staticmethod + def value_parser(value: str, /) -> TokenList: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any], /) -> None: ... + +class HeaderRegistry: + registry: dict[str, type[_HeaderParser]] + base_class: type[BaseHeader] + default_class: type[_HeaderParser] + def __init__( + self, base_class: type[BaseHeader] = ..., default_class: type[_HeaderParser] = ..., use_default_map: bool = True + ) -> None: ... + def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ... + def __getitem__(self, name: str) -> type[BaseHeader]: ... + def __call__(self, name: str, value: Any) -> BaseHeader: ... + +class Address: + @property + def display_name(self) -> str: ... + @property + def username(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def addr_spec(self) -> str: ... + def __init__( + self, display_name: str = "", username: str | None = "", domain: str | None = "", addr_spec: str | None = None + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + +class Group: + @property + def display_name(self) -> str | None: ... + @property + def addresses(self) -> tuple[Address, ...]: ... + def __init__(self, display_name: str | None = None, addresses: Iterable[Address] | None = None) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... diff --git a/stdlib/email/iterators.pyi b/stdlib/email/iterators.pyi new file mode 100644 index 000000000000..b9a8de835401 --- /dev/null +++ b/stdlib/email/iterators.pyi @@ -0,0 +1,15 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterator +from email.message import Message +from typing import TypeVar + +_T = TypeVar("_T", bound=Message) + +__all__ = ["body_line_iterator", "typed_subpart_iterator", "walk"] + +def body_line_iterator(msg: Message, decode: bool = False) -> Iterator[str]: ... +def typed_subpart_iterator(msg: _T, maintype: str = "text", subtype: str | None = None) -> Iterator[_T]: ... +def walk(self: Message) -> Iterator[Message]: ... + +# We include the seemingly private function because it is documented in the stdlib documentation. +def _structure(msg: Message, fp: SupportsWrite[str] | None = None, level: int = 0, include_default: bool = False) -> None: ... diff --git a/stdlib/email/message.pyi b/stdlib/email/message.pyi new file mode 100644 index 000000000000..784c2cace425 --- /dev/null +++ b/stdlib/email/message.pyi @@ -0,0 +1,191 @@ +from _typeshed import MaybeNone +from collections.abc import Generator, Iterator, Sequence +from email import _ParamsType, _ParamType +from email.charset import Charset +from email.contentmanager import ContentManager +from email.errors import MessageDefect +from email.policy import Policy +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +__all__ = ["Message", "EmailMessage"] + +_T = TypeVar("_T") +# Type returned by Policy.header_fetch_parse, often str or Header. +_HeaderT_co = TypeVar("_HeaderT_co", covariant=True, default=str) +_HeaderParamT_contra = TypeVar("_HeaderParamT_contra", contravariant=True, default=str) +# Represents headers constructed by HeaderRegistry. Those are sub-classes +# of BaseHeader and another header type. +_HeaderRegistryT_co = TypeVar("_HeaderRegistryT_co", covariant=True, default=Any) +_HeaderRegistryParamT_contra = TypeVar("_HeaderRegistryParamT_contra", contravariant=True, default=Any) + +_PayloadType: TypeAlias = Message | str +_EncodedPayloadType: TypeAlias = Message | bytes +_MultipartPayloadType: TypeAlias = list[_PayloadType] +_CharsetType: TypeAlias = Charset | str | None + +@type_check_only +class _SupportsEncodeToPayload(Protocol): + def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ... + +@type_check_only +class _SupportsDecodeToPayload(Protocol): + def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ... + +class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): + # The policy attributes and arguments in this class and its subclasses + # would ideally use Policy[Self], but this is not possible. + policy: Policy[Any] # undocumented + preamble: str | None + epilogue: str | None + defects: list[MessageDefect] + def __init__(self, policy: Policy[Any] = ...) -> None: ... + def is_multipart(self) -> bool: ... + def set_unixfrom(self, unixfrom: str) -> None: ... + def get_unixfrom(self) -> str | None: ... + def attach(self, payload: _PayloadType) -> None: ... + + # `i: int` without a multipart payload results in an error + # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check + @overload # multipart + def get_payload(self, i: int, decode: Literal[True]) -> None: ... + @overload # multipart + def get_payload(self, i: int, decode: Literal[False] = False) -> _PayloadType | MaybeNone: ... + @overload # either + def get_payload(self, i: None = None, decode: Literal[False] = False) -> _PayloadType | _MultipartPayloadType | MaybeNone: ... + @overload # not multipart + def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... + @overload # not multipart, IDEM but w/o kwarg + def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... + + # If `charset=None` and payload supports both `encode` AND `decode`, + # then an invalid payload could be passed, but this is unlikely + # Not[_SupportsEncodeToPayload] + @overload + def set_payload( + self, payload: _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, charset: None = None + ) -> None: ... + @overload + def set_payload( + self, + payload: _SupportsEncodeToPayload | _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, + charset: Charset | str, + ) -> None: ... + + def set_charset(self, charset: _CharsetType) -> None: ... + def get_charset(self) -> _CharsetType: ... + def __len__(self) -> int: ... + def __contains__(self, name: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + # Same as `get` with `failobj=None`, but with the expectation that it won't return None in most scenarios + # This is important for protocols using __getitem__, like SupportsKeysAndGetItem + # Morally, the return type should be `AnyOf[_HeaderType, None]`, + # so using "the Any trick" instead. + def __getitem__(self, name: str) -> _HeaderT_co | MaybeNone: ... + def __setitem__(self, name: str, val: _HeaderParamT_contra) -> None: ... + def __delitem__(self, name: str) -> None: ... + def keys(self) -> list[str]: ... + def values(self) -> list[_HeaderT_co]: ... + def items(self) -> list[tuple[str, _HeaderT_co]]: ... + + @overload + def get(self, name: str, failobj: None = None) -> _HeaderT_co | None: ... + @overload + def get(self, name: str, failobj: _T) -> _HeaderT_co | _T: ... + + @overload + def get_all(self, name: str, failobj: None = None) -> list[_HeaderT_co] | None: ... + @overload + def get_all(self, name: str, failobj: _T) -> list[_HeaderT_co] | _T: ... + + def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... + def replace_header(self, _name: str, _value: _HeaderParamT_contra) -> None: ... + def get_content_type(self) -> str: ... + def get_content_maintype(self) -> str: ... + def get_content_subtype(self) -> str: ... + def get_default_type(self) -> str: ... + def set_default_type(self, ctype: str) -> None: ... + + @overload + def get_params( + self, failobj: None = None, header: str = "content-type", unquote: bool = True + ) -> list[tuple[str, str]] | None: ... + @overload + def get_params(self, failobj: _T, header: str = "content-type", unquote: bool = True) -> list[tuple[str, str]] | _T: ... + + @overload + def get_param( + self, param: str, failobj: None = None, header: str = "content-type", unquote: bool = True + ) -> _ParamType | None: ... + @overload + def get_param(self, param: str, failobj: _T, header: str = "content-type", unquote: bool = True) -> _ParamType | _T: ... + + def del_param(self, param: str, header: str = "content-type", requote: bool = True) -> None: ... + def set_type(self, type: str, header: str = "Content-Type", requote: bool = True) -> None: ... + + @overload + def get_filename(self, failobj: None = None) -> str | None: ... + @overload + def get_filename(self, failobj: _T) -> str | _T: ... + + @overload + def get_boundary(self, failobj: None = None) -> str | None: ... + @overload + def get_boundary(self, failobj: _T) -> str | _T: ... + + def set_boundary(self, boundary: str) -> None: ... + + @overload + def get_content_charset(self) -> str | None: ... + @overload + def get_content_charset(self, failobj: _T) -> str | _T: ... + + @overload + def get_charsets(self, failobj: None = None) -> list[str | None]: ... + @overload + def get_charsets(self, failobj: _T) -> list[str | _T]: ... + + def walk(self) -> Generator[Self]: ... + def get_content_disposition(self) -> str | None: ... + def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: ... + def as_bytes(self, unixfrom: bool = False, policy: Policy[Any] | None = None) -> bytes: ... + def __bytes__(self) -> bytes: ... + def set_param( + self, + param: str, + value: str, + header: str = "Content-Type", + requote: bool = True, + charset: str | None = None, + language: str = "", + replace: bool = False, + ) -> None: ... + # The following two methods are undocumented, but a source code comment states that they are public API + def set_raw(self, name: str, value: _HeaderParamT_contra) -> None: ... + def raw_items(self) -> Iterator[tuple[str, _HeaderT_co]]: ... + +class MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): + def __init__(self, policy: Policy[Any] | None = None) -> None: ... + def get_body( + self, preferencelist: Sequence[str] = ("related", "html", "plain") + ) -> MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra] | None: ... + def attach(self, payload: Self) -> None: ... # type: ignore[override] + # The attachments are created via type(self) in the attach method. It's theoretically + # possible to sneak other attachment types into a MIMEPart instance, but could cause + # cause unforseen consequences. + def iter_attachments(self) -> Iterator[Self]: ... + def iter_parts(self) -> Iterator[MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]]: ... + def get_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> Any: ... + def set_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> None: ... + def make_related(self, boundary: str | None = None) -> None: ... + def make_alternative(self, boundary: str | None = None) -> None: ... + def make_mixed(self, boundary: str | None = None) -> None: ... + def add_related(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... + def add_alternative(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... + def add_attachment(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ... + def clear(self) -> None: ... + def clear_content(self) -> None: ... + def as_string(self, unixfrom: bool = False, maxheaderlen: int | None = None, policy: Policy[Any] | None = None) -> str: ... + def is_attachment(self) -> bool: ... + +class EmailMessage(MIMEPart[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]): ... diff --git a/stdlib/email/mime/__init__.pyi b/stdlib/email/mime/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/email/mime/application.pyi b/stdlib/email/mime/application.pyi new file mode 100644 index 000000000000..a7ab9dc75ce2 --- /dev/null +++ b/stdlib/email/mime/application.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy + +__all__ = ["MIMEApplication"] + +class MIMEApplication(MIMENonMultipart): + def __init__( + self, + _data: str | bytes | bytearray, + _subtype: str = "octet-stream", + _encoder: Callable[[MIMEApplication], object] = ..., + *, + policy: Policy | None = None, + **_params: _ParamsType, + ) -> None: ... diff --git a/stdlib/email/mime/audio.pyi b/stdlib/email/mime/audio.pyi new file mode 100644 index 000000000000..090dfb960db6 --- /dev/null +++ b/stdlib/email/mime/audio.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy + +__all__ = ["MIMEAudio"] + +class MIMEAudio(MIMENonMultipart): + def __init__( + self, + _audiodata: str | bytes | bytearray, + _subtype: str | None = None, + _encoder: Callable[[MIMEAudio], object] = ..., + *, + policy: Policy | None = None, + **_params: _ParamsType, + ) -> None: ... diff --git a/stdlib/email/mime/base.pyi b/stdlib/email/mime/base.pyi new file mode 100644 index 000000000000..b733709f1b5a --- /dev/null +++ b/stdlib/email/mime/base.pyi @@ -0,0 +1,8 @@ +import email.message +from email import _ParamsType +from email.policy import Policy + +__all__ = ["MIMEBase"] + +class MIMEBase(email.message.Message): + def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = None, **_params: _ParamsType) -> None: ... diff --git a/stdlib/email/mime/image.pyi b/stdlib/email/mime/image.pyi new file mode 100644 index 000000000000..b47afa6ce592 --- /dev/null +++ b/stdlib/email/mime/image.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from email import _ParamsType +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy + +__all__ = ["MIMEImage"] + +class MIMEImage(MIMENonMultipart): + def __init__( + self, + _imagedata: str | bytes | bytearray, + _subtype: str | None = None, + _encoder: Callable[[MIMEImage], object] = ..., + *, + policy: Policy | None = None, + **_params: _ParamsType, + ) -> None: ... diff --git a/stdlib/email/mime/message.pyi b/stdlib/email/mime/message.pyi new file mode 100644 index 000000000000..a1e370e2eab5 --- /dev/null +++ b/stdlib/email/mime/message.pyi @@ -0,0 +1,8 @@ +from email._policybase import _MessageT +from email.mime.nonmultipart import MIMENonMultipart +from email.policy import Policy + +__all__ = ["MIMEMessage"] + +class MIMEMessage(MIMENonMultipart): + def __init__(self, _msg: _MessageT, _subtype: str = "rfc822", *, policy: Policy[_MessageT] | None = None) -> None: ... diff --git a/stdlib/email/mime/multipart.pyi b/stdlib/email/mime/multipart.pyi new file mode 100644 index 000000000000..fb9599edbcb8 --- /dev/null +++ b/stdlib/email/mime/multipart.pyi @@ -0,0 +1,18 @@ +from collections.abc import Sequence +from email import _ParamsType +from email._policybase import _MessageT +from email.mime.base import MIMEBase +from email.policy import Policy + +__all__ = ["MIMEMultipart"] + +class MIMEMultipart(MIMEBase): + def __init__( + self, + _subtype: str = "mixed", + boundary: str | None = None, + _subparts: Sequence[_MessageT] | None = None, + *, + policy: Policy[_MessageT] | None = None, + **_params: _ParamsType, + ) -> None: ... diff --git a/stdlib/email/mime/nonmultipart.pyi b/stdlib/email/mime/nonmultipart.pyi new file mode 100644 index 000000000000..5497d89b1072 --- /dev/null +++ b/stdlib/email/mime/nonmultipart.pyi @@ -0,0 +1,5 @@ +from email.mime.base import MIMEBase + +__all__ = ["MIMENonMultipart"] + +class MIMENonMultipart(MIMEBase): ... diff --git a/stdlib/email/mime/text.pyi b/stdlib/email/mime/text.pyi new file mode 100644 index 000000000000..edfa67a09242 --- /dev/null +++ b/stdlib/email/mime/text.pyi @@ -0,0 +1,9 @@ +from email._policybase import Policy +from email.mime.nonmultipart import MIMENonMultipart + +__all__ = ["MIMEText"] + +class MIMEText(MIMENonMultipart): + def __init__( + self, _text: str, _subtype: str = "plain", _charset: str | None = None, *, policy: Policy | None = None + ) -> None: ... diff --git a/stdlib/email/parser.pyi b/stdlib/email/parser.pyi new file mode 100644 index 000000000000..f1b418ee30a0 --- /dev/null +++ b/stdlib/email/parser.pyi @@ -0,0 +1,42 @@ +from _typeshed import SupportsRead +from collections.abc import Callable +from email._policybase import _MessageT +from email.feedparser import BytesFeedParser as BytesFeedParser, FeedParser as FeedParser +from email.message import Message +from email.policy import Policy +from io import _WrappedBuffer +from typing import Generic, overload + +__all__ = ["Parser", "HeaderParser", "BytesParser", "BytesHeaderParser", "FeedParser", "BytesFeedParser"] + +class Parser(Generic[_MessageT]): + @overload + def __init__(self: Parser[Message[str, str]], _class: None = None) -> None: ... + @overload + def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT] | None, *, policy: Policy[_MessageT] = ...) -> None: ... + + def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: ... + +class HeaderParser(Parser[_MessageT]): + def parse(self, fp: SupportsRead[str], headersonly: bool = True) -> _MessageT: ... + def parsestr(self, text: str, headersonly: bool = True) -> _MessageT: ... + +class BytesParser(Generic[_MessageT]): + parser: Parser[_MessageT] + + @overload + def __init__(self: BytesParser[Message[str, str]], _class: None = None) -> None: ... + @overload + def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... + @overload + def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + + def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: ... + +class BytesHeaderParser(BytesParser[_MessageT]): + def parse(self, fp: _WrappedBuffer, headersonly: bool = True) -> _MessageT: ... + def parsebytes(self, text: bytes | bytearray, headersonly: bool = True) -> _MessageT: ... diff --git a/stdlib/email/policy.pyi b/stdlib/email/policy.pyi new file mode 100644 index 000000000000..6b719f3c93fa --- /dev/null +++ b/stdlib/email/policy.pyi @@ -0,0 +1,77 @@ +from collections.abc import Callable +from email._policybase import Compat32 as Compat32, Policy as Policy, _MessageFactory, _MessageT, compat32 as compat32 +from email.contentmanager import ContentManager +from email.message import EmailMessage +from typing import Any, overload +from typing_extensions import Self + +__all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] + +class EmailPolicy(Policy[_MessageT]): + utf8: bool + refold_source: str + header_factory: Callable[[str, Any], Any] + content_manager: ContentManager + + @overload + def __init__( + self: EmailPolicy[EmailMessage], + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: None = None, + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., + utf8: bool = ..., + refold_source: str = ..., + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: _MessageFactory[_MessageT] | None = ..., + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., + utf8: bool = ..., + refold_source: str = ..., + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> None: ... + + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... + def header_store_parse(self, name: str, value: Any) -> tuple[str, Any]: ... + def header_fetch_parse(self, name: str, value: str) -> Any: ... + def fold(self, name: str, value: str) -> Any: ... + def fold_binary(self, name: str, value: str) -> bytes: ... + def clone( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: _MessageFactory[_MessageT] | None = ..., + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 + verify_generated_headers: bool = ..., + utf8: bool = ..., + refold_source: str = ..., + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> Self: ... + +default: EmailPolicy[EmailMessage] +SMTP: EmailPolicy[EmailMessage] +SMTPUTF8: EmailPolicy[EmailMessage] +HTTP: EmailPolicy[EmailMessage] +strict: EmailPolicy[EmailMessage] diff --git a/stdlib/email/quoprimime.pyi b/stdlib/email/quoprimime.pyi new file mode 100644 index 000000000000..87d08eecc70c --- /dev/null +++ b/stdlib/email/quoprimime.pyi @@ -0,0 +1,28 @@ +from collections.abc import Iterable + +__all__ = [ + "body_decode", + "body_encode", + "body_length", + "decode", + "decodestring", + "header_decode", + "header_encode", + "header_length", + "quote", + "unquote", +] + +def header_check(octet: int) -> bool: ... +def body_check(octet: int) -> bool: ... +def header_length(bytearray: Iterable[int]) -> int: ... +def body_length(bytearray: Iterable[int]) -> int: ... +def unquote(s: str | bytes | bytearray) -> str: ... +def quote(c: str | bytes | bytearray) -> str: ... +def header_encode(header_bytes: bytes | bytearray, charset: str = "iso-8859-1") -> str: ... +def body_encode(body: str, maxlinelen: int = 76, eol: str = "\n") -> str: ... +def decode(encoded: str, eol: str = "\n") -> str: ... +def header_decode(s: str) -> str: ... + +body_decode = decode +decodestring = decode diff --git a/stdlib/email/utils.pyi b/stdlib/email/utils.pyi new file mode 100644 index 000000000000..6b47950a2ef8 --- /dev/null +++ b/stdlib/email/utils.pyi @@ -0,0 +1,72 @@ +import datetime +import sys +from _typeshed import Unused +from collections.abc import Iterable +from email import _ParamType +from email.charset import Charset +from typing import TypeAlias, overload +from typing_extensions import deprecated + +__all__ = [ + "collapse_rfc2231_value", + "decode_params", + "decode_rfc2231", + "encode_rfc2231", + "formataddr", + "formatdate", + "format_datetime", + "getaddresses", + "make_msgid", + "mktime_tz", + "parseaddr", + "parsedate", + "parsedate_tz", + "parsedate_to_datetime", + "unquote", +] + +_PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None] + +def quote(str: str) -> str: ... +def unquote(str: str) -> str: ... + +# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: ... +def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") -> str: ... + +# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +def getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tuple[str, str]]: ... + +@overload +def parsedate(data: None) -> None: ... +@overload +def parsedate(data: str) -> tuple[int, int, int, int, int, int, int, int, int] | None: ... + +@overload +def parsedate_tz(data: None) -> None: ... +@overload +def parsedate_tz(data: str) -> _PDTZ | None: ... + +def parsedate_to_datetime(data: str) -> datetime.datetime: ... +def mktime_tz(data: _PDTZ) -> int: ... +def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bool = False) -> str: ... +def format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: ... + +if sys.version_info >= (3, 14): + def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ... + +elif sys.version_info >= (3, 12): + @overload + def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ... + @overload + @deprecated("The `isdst` parameter does nothing and will be removed in Python 3.14.") + def localtime(dt: datetime.datetime | None = None, isdst: Unused = None) -> datetime.datetime: ... + +else: + def localtime(dt: datetime.datetime | None = None, isdst: int = -1) -> datetime.datetime: ... + +def make_msgid(idstring: str | None = None, domain: str | None = None) -> str: ... +def decode_rfc2231(s: str) -> tuple[str | None, str | None, str]: ... # May return list[str]. See issue #10431 for details. +def encode_rfc2231(s: str, charset: str | None = None, language: str | None = None) -> str: ... +def collapse_rfc2231_value(value: _ParamType, errors: str = "replace", fallback_charset: str = "us-ascii") -> str: ... +def decode_params(params: list[tuple[str, str]]) -> list[tuple[str, _ParamType]]: ... diff --git a/stdlib/encodings/__init__.pyi b/stdlib/encodings/__init__.pyi new file mode 100644 index 000000000000..e03758ce59a0 --- /dev/null +++ b/stdlib/encodings/__init__.pyi @@ -0,0 +1,15 @@ +import sys +from codecs import CodecInfo + +from . import aliases as aliases + +class CodecRegistryError(LookupError, SystemError): ... + +def normalize_encoding(encoding: str | bytes) -> str: ... +def search_function(encoding: str) -> CodecInfo | None: ... + +if sys.version_info >= (3, 14) and sys.platform == "win32": + def win32_code_page_search_function(encoding: str) -> CodecInfo | None: ... + +# Needed for submodules +def __getattr__(name: str): ... # incomplete module diff --git a/stdlib/encodings/aliases.pyi b/stdlib/encodings/aliases.pyi new file mode 100644 index 000000000000..079af85d51ee --- /dev/null +++ b/stdlib/encodings/aliases.pyi @@ -0,0 +1 @@ +aliases: dict[str, str] diff --git a/stdlib/encodings/ascii.pyi b/stdlib/encodings/ascii.pyi new file mode 100644 index 000000000000..a85585af32ed --- /dev/null +++ b/stdlib/encodings/ascii.pyi @@ -0,0 +1,30 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.ascii_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.ascii_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +# Note: encode being a decode function and decode being an encode function is accurate to runtime. +class StreamConverter(StreamWriter, StreamReader): # type: ignore[misc] # incompatible methods in base classes + # At runtime, this is codecs.ascii_decode + @staticmethod + def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... # type: ignore[override] + # At runtime, this is codecs.ascii_encode + @staticmethod + def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/base64_codec.pyi b/stdlib/encodings/base64_codec.pyi new file mode 100644 index 000000000000..0c4f1cb1fe59 --- /dev/null +++ b/stdlib/encodings/base64_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def base64_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def base64_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/big5.pyi b/stdlib/encodings/big5.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/big5.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/big5hkscs.pyi b/stdlib/encodings/big5hkscs.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/big5hkscs.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/bz2_codec.pyi b/stdlib/encodings/bz2_codec.pyi new file mode 100644 index 000000000000..468346a93da9 --- /dev/null +++ b/stdlib/encodings/bz2_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def bz2_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def bz2_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/charmap.pyi b/stdlib/encodings/charmap.pyi new file mode 100644 index 000000000000..a971a15860b5 --- /dev/null +++ b/stdlib/encodings/charmap.pyi @@ -0,0 +1,33 @@ +import codecs +from _codecs import _CharMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.charmap_encode + @staticmethod + def encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.charmap_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + mapping: _CharMap | None + def __init__(self, errors: str = "strict", mapping: _CharMap | None = None) -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + mapping: _CharMap | None + def __init__(self, errors: str = "strict", mapping: _CharMap | None = None) -> None: ... + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): + mapping: _CharMap | None + def __init__(self, stream: codecs._WritableStream, errors: str = "strict", mapping: _CharMap | None = None) -> None: ... + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class StreamReader(Codec, codecs.StreamReader): + mapping: _CharMap | None + def __init__(self, stream: codecs._ReadableStream, errors: str = "strict", mapping: _CharMap | None = None) -> None: ... + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp037.pyi b/stdlib/encodings/cp037.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp037.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1006.pyi b/stdlib/encodings/cp1006.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1006.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1026.pyi b/stdlib/encodings/cp1026.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1026.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1125.pyi b/stdlib/encodings/cp1125.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp1125.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp1140.pyi b/stdlib/encodings/cp1140.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1140.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1250.pyi b/stdlib/encodings/cp1250.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1250.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1251.pyi b/stdlib/encodings/cp1251.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1251.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1252.pyi b/stdlib/encodings/cp1252.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1252.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1253.pyi b/stdlib/encodings/cp1253.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1253.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1254.pyi b/stdlib/encodings/cp1254.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1254.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1255.pyi b/stdlib/encodings/cp1255.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1255.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1256.pyi b/stdlib/encodings/cp1256.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1256.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1257.pyi b/stdlib/encodings/cp1257.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1257.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp1258.pyi b/stdlib/encodings/cp1258.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp1258.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp273.pyi b/stdlib/encodings/cp273.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp273.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp424.pyi b/stdlib/encodings/cp424.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp424.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp437.pyi b/stdlib/encodings/cp437.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp437.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp500.pyi b/stdlib/encodings/cp500.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp500.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp720.pyi b/stdlib/encodings/cp720.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp720.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp737.pyi b/stdlib/encodings/cp737.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp737.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp775.pyi b/stdlib/encodings/cp775.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp775.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp850.pyi b/stdlib/encodings/cp850.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp850.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp852.pyi b/stdlib/encodings/cp852.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp852.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp855.pyi b/stdlib/encodings/cp855.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp855.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp856.pyi b/stdlib/encodings/cp856.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp856.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp857.pyi b/stdlib/encodings/cp857.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp857.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp858.pyi b/stdlib/encodings/cp858.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp858.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp860.pyi b/stdlib/encodings/cp860.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp860.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp861.pyi b/stdlib/encodings/cp861.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp861.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp862.pyi b/stdlib/encodings/cp862.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp862.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp863.pyi b/stdlib/encodings/cp863.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp863.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp864.pyi b/stdlib/encodings/cp864.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp864.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp865.pyi b/stdlib/encodings/cp865.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp865.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp866.pyi b/stdlib/encodings/cp866.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp866.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp869.pyi b/stdlib/encodings/cp869.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/cp869.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/cp874.pyi b/stdlib/encodings/cp874.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp874.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp875.pyi b/stdlib/encodings/cp875.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/cp875.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/cp932.pyi b/stdlib/encodings/cp932.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp932.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp949.pyi b/stdlib/encodings/cp949.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp949.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/cp950.pyi b/stdlib/encodings/cp950.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/cp950.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jis_2004.pyi b/stdlib/encodings/euc_jis_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jis_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jisx0213.pyi b/stdlib/encodings/euc_jisx0213.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jisx0213.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_jp.pyi b/stdlib/encodings/euc_jp.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_jp.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/euc_kr.pyi b/stdlib/encodings/euc_kr.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/euc_kr.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gb18030.pyi b/stdlib/encodings/gb18030.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gb18030.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gb2312.pyi b/stdlib/encodings/gb2312.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gb2312.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/gbk.pyi b/stdlib/encodings/gbk.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/gbk.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/hex_codec.pyi b/stdlib/encodings/hex_codec.pyi new file mode 100644 index 000000000000..3fd4fe38898a --- /dev/null +++ b/stdlib/encodings/hex_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def hex_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def hex_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/hp_roman8.pyi b/stdlib/encodings/hp_roman8.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/hp_roman8.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/hz.pyi b/stdlib/encodings/hz.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/hz.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/idna.pyi b/stdlib/encodings/idna.pyi new file mode 100644 index 000000000000..3e2c8baf1cb2 --- /dev/null +++ b/stdlib/encodings/idna.pyi @@ -0,0 +1,26 @@ +import codecs +import re +from _typeshed import ReadableBuffer + +dots: re.Pattern[str] +ace_prefix: bytes +sace_prefix: str + +def nameprep(label: str) -> str: ... +def ToASCII(label: str) -> bytes: ... +def ToUnicode(label: bytes | str) -> str: ... + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: ReadableBuffer | str, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer | str, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp.pyi b/stdlib/encodings/iso2022_jp.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_1.pyi b/stdlib/encodings/iso2022_jp_1.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_1.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_2.pyi b/stdlib/encodings/iso2022_jp_2.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_2.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_2004.pyi b/stdlib/encodings/iso2022_jp_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_3.pyi b/stdlib/encodings/iso2022_jp_3.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_3.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_jp_ext.pyi b/stdlib/encodings/iso2022_jp_ext.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_jp_ext.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso2022_kr.pyi b/stdlib/encodings/iso2022_kr.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/iso2022_kr.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/iso8859_1.pyi b/stdlib/encodings/iso8859_1.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_1.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_10.pyi b/stdlib/encodings/iso8859_10.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_10.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_11.pyi b/stdlib/encodings/iso8859_11.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_11.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_13.pyi b/stdlib/encodings/iso8859_13.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_13.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_14.pyi b/stdlib/encodings/iso8859_14.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_14.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_15.pyi b/stdlib/encodings/iso8859_15.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_15.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_16.pyi b/stdlib/encodings/iso8859_16.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_16.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_2.pyi b/stdlib/encodings/iso8859_2.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_2.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_3.pyi b/stdlib/encodings/iso8859_3.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_3.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_4.pyi b/stdlib/encodings/iso8859_4.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_4.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_5.pyi b/stdlib/encodings/iso8859_5.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_5.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_6.pyi b/stdlib/encodings/iso8859_6.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_6.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_7.pyi b/stdlib/encodings/iso8859_7.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_7.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_8.pyi b/stdlib/encodings/iso8859_8.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_8.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/iso8859_9.pyi b/stdlib/encodings/iso8859_9.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/iso8859_9.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/johab.pyi b/stdlib/encodings/johab.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/johab.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/koi8_r.pyi b/stdlib/encodings/koi8_r.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_r.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/koi8_t.pyi b/stdlib/encodings/koi8_t.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_t.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/koi8_u.pyi b/stdlib/encodings/koi8_u.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/koi8_u.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/kz1048.pyi b/stdlib/encodings/kz1048.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/kz1048.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/latin_1.pyi b/stdlib/encodings/latin_1.pyi new file mode 100644 index 000000000000..3b06773eac03 --- /dev/null +++ b/stdlib/encodings/latin_1.pyi @@ -0,0 +1,30 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.latin_1_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.latin_1_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +# Note: encode being a decode function and decode being an encode function is accurate to runtime. +class StreamConverter(StreamWriter, StreamReader): # type: ignore[misc] # incompatible methods in base classes + # At runtime, this is codecs.latin_1_decode + @staticmethod + def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... # type: ignore[override] + # At runtime, this is codecs.latin_1_encode + @staticmethod + def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/mac_arabic.pyi b/stdlib/encodings/mac_arabic.pyi new file mode 100644 index 000000000000..42781b489298 --- /dev/null +++ b/stdlib/encodings/mac_arabic.pyi @@ -0,0 +1,21 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_map: dict[int, int | None] +decoding_table: str +encoding_map: dict[int, int] diff --git a/stdlib/encodings/mac_croatian.pyi b/stdlib/encodings/mac_croatian.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_croatian.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_cyrillic.pyi b/stdlib/encodings/mac_cyrillic.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_cyrillic.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_farsi.pyi b/stdlib/encodings/mac_farsi.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_farsi.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_greek.pyi b/stdlib/encodings/mac_greek.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_greek.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_iceland.pyi b/stdlib/encodings/mac_iceland.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_iceland.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_latin2.pyi b/stdlib/encodings/mac_latin2.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_latin2.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_roman.pyi b/stdlib/encodings/mac_roman.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_roman.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_romanian.pyi b/stdlib/encodings/mac_romanian.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_romanian.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mac_turkish.pyi b/stdlib/encodings/mac_turkish.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/mac_turkish.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/mbcs.pyi b/stdlib/encodings/mbcs.pyi new file mode 100644 index 000000000000..2c2917d63f6d --- /dev/null +++ b/stdlib/encodings/mbcs.pyi @@ -0,0 +1,28 @@ +import codecs +import sys +from _typeshed import ReadableBuffer + +if sys.platform == "win32": + encode = codecs.mbcs_encode + + def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + + class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + + class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.mbcs_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.mbcs_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + + class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.mbcs_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/oem.pyi b/stdlib/encodings/oem.pyi new file mode 100644 index 000000000000..376c12c445f4 --- /dev/null +++ b/stdlib/encodings/oem.pyi @@ -0,0 +1,28 @@ +import codecs +import sys +from _typeshed import ReadableBuffer + +if sys.platform == "win32": + encode = codecs.oem_encode + + def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + + class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + + class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.oem_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.oem_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + + class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.oem_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + + def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/palmos.pyi b/stdlib/encodings/palmos.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/palmos.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/ptcp154.pyi b/stdlib/encodings/ptcp154.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/ptcp154.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/punycode.pyi b/stdlib/encodings/punycode.pyi new file mode 100644 index 000000000000..eb99e667b416 --- /dev/null +++ b/stdlib/encodings/punycode.pyi @@ -0,0 +1,33 @@ +import codecs +from typing import Literal + +def segregate(str: str) -> tuple[bytes, list[int]]: ... +def selective_len(str: str, max: int) -> int: ... +def selective_find(str: str, char: str, index: int, pos: int) -> tuple[int, int]: ... +def insertion_unsort(str: str, extended: list[int]) -> list[int]: ... +def T(j: int, bias: int) -> int: ... + +digits: Literal[b"abcdefghijklmnopqrstuvwxyz0123456789"] + +def generate_generalized_integer(N: int, bias: int) -> bytes: ... +def adapt(delta: int, first: bool, numchars: int) -> int: ... +def generate_integers(baselen: int, deltas: list[int]) -> bytes: ... +def punycode_encode(text: str) -> bytes: ... +def decode_generalized_number(extended: bytes, extpos: int, bias: int, errors: str) -> tuple[int, int | None]: ... +def insertion_sort(base: str, extended: bytes, errors: str) -> str: ... +def punycode_decode(text: memoryview | bytes | bytearray | str, errors: str) -> str: ... + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: memoryview | bytes | bytearray | str, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: memoryview | bytes | bytearray | str, final: bool = False) -> str: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/quopri_codec.pyi b/stdlib/encodings/quopri_codec.pyi new file mode 100644 index 000000000000..e9deadd8d463 --- /dev/null +++ b/stdlib/encodings/quopri_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def quopri_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def quopri_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/raw_unicode_escape.pyi b/stdlib/encodings/raw_unicode_escape.pyi new file mode 100644 index 000000000000..2887739468f2 --- /dev/null +++ b/stdlib/encodings/raw_unicode_escape.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.raw_unicode_escape_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.raw_unicode_escape_decode + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... + +class StreamReader(Codec, codecs.StreamReader): + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/rot_13.pyi b/stdlib/encodings/rot_13.pyi new file mode 100644 index 000000000000..8d71bc957594 --- /dev/null +++ b/stdlib/encodings/rot_13.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import SupportsRead, SupportsWrite + +# This codec is string to string. + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + def decode(self, input: str, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> str: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: str, final: bool = False) -> str: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +rot13_map: dict[int, int] + +def rot13(infile: SupportsRead[str], outfile: SupportsWrite[str]) -> None: ... diff --git a/stdlib/encodings/shift_jis.pyi b/stdlib/encodings/shift_jis.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jis.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/shift_jis_2004.pyi b/stdlib/encodings/shift_jis_2004.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jis_2004.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/shift_jisx0213.pyi b/stdlib/encodings/shift_jisx0213.pyi new file mode 100644 index 000000000000..be96a1ba3ad8 --- /dev/null +++ b/stdlib/encodings/shift_jisx0213.pyi @@ -0,0 +1,23 @@ +import _multibytecodec as mbc +import codecs +from typing import ClassVar + +codec: mbc._MultibyteCodec + +class Codec(codecs.Codec): + encode = codec.encode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + decode = codec.decode # type: ignore[assignment] # pyright: ignore[reportAssignmentType] + +class IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder): # type: ignore[misc] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder): + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + codec: ClassVar[mbc._MultibyteCodec] = ... + +class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): + codec: ClassVar[mbc._MultibyteCodec] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/tis_620.pyi b/stdlib/encodings/tis_620.pyi new file mode 100644 index 000000000000..f62195662ce9 --- /dev/null +++ b/stdlib/encodings/tis_620.pyi @@ -0,0 +1,21 @@ +import codecs +from _codecs import _EncodingMap +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... + +decoding_table: str +encoding_table: _EncodingMap diff --git a/stdlib/encodings/undefined.pyi b/stdlib/encodings/undefined.pyi new file mode 100644 index 000000000000..4775dac752f2 --- /dev/null +++ b/stdlib/encodings/undefined.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +# These return types are just to match the base types. In reality, these always +# raise an error. + +class Codec(codecs.Codec): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/unicode_escape.pyi b/stdlib/encodings/unicode_escape.pyi new file mode 100644 index 000000000000..ceaa39a3859a --- /dev/null +++ b/stdlib/encodings/unicode_escape.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +class Codec(codecs.Codec): + # At runtime, this is codecs.unicode_escape_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + # At runtime, this is codecs.unicode_escape_decode + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... + +class StreamReader(Codec, codecs.StreamReader): + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16.pyi b/stdlib/encodings/utf_16.pyi new file mode 100644 index 000000000000..3b712cde420a --- /dev/null +++ b/stdlib/encodings/utf_16.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16_be.pyi b/stdlib/encodings/utf_16_be.pyi new file mode 100644 index 000000000000..cc7d1534fc69 --- /dev/null +++ b/stdlib/encodings/utf_16_be.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_be_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_16_be_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_16_be_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_16_be_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_16_le.pyi b/stdlib/encodings/utf_16_le.pyi new file mode 100644 index 000000000000..ba103eb088e3 --- /dev/null +++ b/stdlib/encodings/utf_16_le.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_16_le_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_16_le_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_16_le_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_16_le_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32.pyi b/stdlib/encodings/utf_32.pyi new file mode 100644 index 000000000000..c925be712c72 --- /dev/null +++ b/stdlib/encodings/utf_32.pyi @@ -0,0 +1,20 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32_be.pyi b/stdlib/encodings/utf_32_be.pyi new file mode 100644 index 000000000000..9d28f5199c50 --- /dev/null +++ b/stdlib/encodings/utf_32_be.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_be_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_32_be_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_32_be_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_32_be_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_32_le.pyi b/stdlib/encodings/utf_32_le.pyi new file mode 100644 index 000000000000..5be14a91a3e6 --- /dev/null +++ b/stdlib/encodings/utf_32_le.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_32_le_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_32_le_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_32_le_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_32_le_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_7.pyi b/stdlib/encodings/utf_7.pyi new file mode 100644 index 000000000000..dc1162f34c28 --- /dev/null +++ b/stdlib/encodings/utf_7.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_7_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_7_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_7_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_7_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_8.pyi b/stdlib/encodings/utf_8.pyi new file mode 100644 index 000000000000..918712d80473 --- /dev/null +++ b/stdlib/encodings/utf_8.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer + +encode = codecs.utf_8_encode + +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + # At runtime, this is codecs.utf_8_decode + @staticmethod + def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + # At runtime, this is codecs.utf_8_encode + @staticmethod + def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + # At runtime, this is codecs.utf_8_decode + @staticmethod + def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/utf_8_sig.pyi b/stdlib/encodings/utf_8_sig.pyi new file mode 100644 index 000000000000..af69217d6732 --- /dev/null +++ b/stdlib/encodings/utf_8_sig.pyi @@ -0,0 +1,22 @@ +import codecs +from _typeshed import ReadableBuffer + +class IncrementalEncoder(codecs.IncrementalEncoder): + def __init__(self, errors: str = "strict") -> None: ... + def encode(self, input: str, final: bool = False) -> bytes: ... + def getstate(self) -> int: ... + def setstate(self, state: int) -> None: ... # type: ignore[override] + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def __init__(self, errors: str = "strict") -> None: ... + def _buffer_decode(self, input: ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... + +class StreamWriter(codecs.StreamWriter): + def encode(self, input: str, errors: str | None = "strict") -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def decode(self, input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: str, errors: str | None = "strict") -> tuple[bytes, int]: ... +def decode(input: ReadableBuffer, errors: str | None = "strict") -> tuple[str, int]: ... diff --git a/stdlib/encodings/uu_codec.pyi b/stdlib/encodings/uu_codec.pyi new file mode 100644 index 000000000000..e32ba8ac0a1a --- /dev/null +++ b/stdlib/encodings/uu_codec.pyi @@ -0,0 +1,28 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def uu_encode( + input: ReadableBuffer, errors: str = "strict", filename: str = "", mode: int = 0o666 +) -> tuple[bytes, int]: ... +def uu_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/encodings/zlib_codec.pyi b/stdlib/encodings/zlib_codec.pyi new file mode 100644 index 000000000000..0f13d0e810e9 --- /dev/null +++ b/stdlib/encodings/zlib_codec.pyi @@ -0,0 +1,26 @@ +import codecs +from _typeshed import ReadableBuffer +from typing import ClassVar + +# This codec is bytes to bytes. + +def zlib_encode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... +def zlib_decode(input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... + +class Codec(codecs.Codec): + def encode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + def decode(self, input: ReadableBuffer, errors: str = "strict") -> tuple[bytes, int]: ... # type: ignore[override] + +class IncrementalEncoder(codecs.IncrementalEncoder): + def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ... # type: ignore[override] + +class StreamWriter(Codec, codecs.StreamWriter): + charbuffertype: ClassVar[type] = ... + +class StreamReader(Codec, codecs.StreamReader): + charbuffertype: ClassVar[type] = ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stdlib/ensurepip/__init__.pyi b/stdlib/ensurepip/__init__.pyi new file mode 100644 index 000000000000..332fb1845917 --- /dev/null +++ b/stdlib/ensurepip/__init__.pyi @@ -0,0 +1,12 @@ +__all__ = ["version", "bootstrap"] + +def version() -> str: ... +def bootstrap( + *, + root: str | None = None, + upgrade: bool = False, + user: bool = False, + altinstall: bool = False, + default_pip: bool = False, + verbosity: int = 0, +) -> None: ... diff --git a/stdlib/enum.pyi b/stdlib/enum.pyi new file mode 100644 index 000000000000..1d216b90b6b7 --- /dev/null +++ b/stdlib/enum.pyi @@ -0,0 +1,374 @@ +import _typeshed +import sys +import types +from _typeshed import SupportsKeysAndGetItem, Unused +from builtins import property as _builtins_property +from collections.abc import Callable, Iterable, Iterator, Mapping +from typing import Any, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base + +__all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] + +if sys.version_info >= (3, 11): + __all__ += [ + "CONFORM", + "CONTINUOUS", + "EJECT", + "EnumCheck", + "EnumType", + "FlagBoundary", + "KEEP", + "NAMED_FLAGS", + "ReprEnum", + "STRICT", + "StrEnum", + "UNIQUE", + "global_enum", + "global_enum_repr", + "global_flag_repr", + "global_str", + "member", + "nonmember", + "property", + "verify", + "pickle_by_enum_name", + "pickle_by_global_name", + ] + +if sys.version_info >= (3, 13): + __all__ += ["EnumDict"] +if sys.version_info >= (3, 15): + __all__ += ["show_flag_values", "bin"] + +_EnumMemberT = TypeVar("_EnumMemberT") +_EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) + +# The following all work: +# >>> from enum import Enum +# >>> from string import ascii_lowercase +# >>> Enum('Foo', names='RED YELLOW GREEN') +# +# >>> Enum('Foo', names=[('RED', 1), ('YELLOW, 2)]) +# +# >>> Enum('Foo', names=((x for x in (ascii_lowercase[i], i)) for i in range(5))) +# +# >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) +# +_EnumNames: TypeAlias = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any] +_Signature: TypeAlias = Any # TODO: Unable to import Signature from inspect module + +if sys.version_info >= (3, 11): + class nonmember(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + + class member(Generic[_EnumMemberT]): + value: _EnumMemberT + def __init__(self, value: _EnumMemberT) -> None: ... + +class _EnumDict(dict[str, Any]): + if sys.version_info >= (3, 13): + def __init__(self, cls_name: str | None = None) -> None: ... + else: + def __init__(self) -> None: ... + + def __setitem__(self, key: str, value: Any) -> None: ... + if sys.version_info >= (3, 11): + # See comment above `typing.MutableMapping.update` + # for why overloads are preferable to a Union here + # + # Unlike with MutableMapping.update(), the first argument is required, + # hence the type: ignore + @overload # type: ignore[override] + def update(self, members: SupportsKeysAndGetItem[str, Any], **more_members: Any) -> None: ... + @overload + def update(self, members: Iterable[tuple[str, Any]], **more_members: Any) -> None: ... + + if sys.version_info >= (3, 13): + @property + def member_names(self) -> list[str]: ... + +if sys.version_info >= (3, 13): + EnumDict = _EnumDict + +# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself +class EnumMeta(type): + if sys.version_info >= (3, 11): + def __new__( + metacls: type[_typeshed.Self], + cls: str, + bases: tuple[type, ...], + classdict: _EnumDict, + *, + boundary: FlagBoundary | None = None, + _simple: bool = False, + **kwds: Any, + ) -> _typeshed.Self: ... + else: + def __new__( + metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any + ) -> _typeshed.Self: ... + + @classmethod + def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] + def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... + if sys.version_info >= (3, 12): + def __contains__(self: type[Any], value: object) -> bool: ... + elif sys.version_info >= (3, 11): + def __contains__(self: type[Any], member: object) -> bool: ... + else: + def __contains__(self: type[Any], obj: object) -> bool: ... + + def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: ... + @_builtins_property + def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ... + def __len__(self) -> int: ... + def __bool__(self) -> Literal[True]: ... + def __dir__(self) -> list[str]: ... + + # Overload 1: Value lookup on an already existing enum class (simple case) + @overload + def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT: ... + + # Overload 2: Functional API for constructing new enum classes. + if sys.version_info >= (3, 11): + @overload + def __call__( + cls, + value: str, + names: _EnumNames, + *, + module: str | None = None, + qualname: str | None = None, + type: type | None = None, + start: int = 1, + boundary: FlagBoundary | None = None, + ) -> type[Enum]: ... + else: + @overload + def __call__( + cls, + value: str, + names: _EnumNames, + *, + module: str | None = None, + qualname: str | None = None, + type: type | None = None, + start: int = 1, + ) -> type[Enum]: ... + + # Overload 3 (py312+ only): Value lookup on an already existing enum class (complex case) + # + # >>> class Foo(enum.Enum): + # ... X = 1, 2, 3 + # >>> Foo(1, 2, 3) + # + # + if sys.version_info >= (3, 12): + @overload + def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT: ... + if sys.version_info >= (3, 14): + @property + def __signature__(cls) -> _Signature: ... + + _member_names_: list[str] # undocumented + _member_map_: dict[str, Enum] # undocumented + _value2member_map_: dict[Any, Enum] # undocumented + +if sys.version_info >= (3, 11): + # In 3.11 `EnumMeta` metaclass is renamed to `EnumType`, but old name also exists. + EnumType = EnumMeta + + class property(types.DynamicClassAttribute): + def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ... + name: str + clsname: str + member: Enum | None + + _magic_enum_attr = property +else: + _magic_enum_attr = types.DynamicClassAttribute + +class Enum(metaclass=EnumMeta): + @_magic_enum_attr + def name(self) -> str: ... + @_magic_enum_attr + def value(self) -> Any: ... + _name_: str + _value_: Any + _ignore_: str | list[str] + _order_: str + __order__: str + @classmethod + def _missing_(cls, value: object) -> Any: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ... + # It's not true that `__new__` will accept any argument type, + # so ideally we'd use `Any` to indicate that the argument type is inexpressible. + # However, using `Any` causes too many false-positives for those using mypy's `--disallow-any-expr` + # (see #7752, #2539, mypy/#5788), + # and in practice using `object` here has the same effect as using `Any`. + def __new__(cls, value: object) -> Self: ... + def __dir__(self) -> list[str]: ... + def __hash__(self) -> int: ... + def __format__(self, format_spec: str) -> str: ... + def __reduce_ex__(self, proto: Unused) -> tuple[Any, ...]: ... + if sys.version_info >= (3, 11): + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... + if sys.version_info >= (3, 12) and sys.version_info < (3, 14): + @classmethod + def __signature__(cls) -> str: ... + if sys.version_info >= (3, 13): + # Value may be any type, even in special enums. Enabling Enum parsing from + # multiple value types + def _add_value_alias_(self, value: Any) -> None: ... + def _add_alias_(self, name: str) -> None: ... + +if sys.version_info >= (3, 11): + class ReprEnum(Enum): ... + +if sys.version_info >= (3, 12): + class IntEnum(int, ReprEnum): + _value_: int + @_magic_enum_attr + def value(self) -> int: ... + def __new__(cls, value: int) -> Self: ... + +else: + if sys.version_info >= (3, 11): + _IntEnumBase = ReprEnum + else: + _IntEnumBase = Enum + + @disjoint_base + class IntEnum(int, _IntEnumBase): + _value_: int + @_magic_enum_attr + def value(self) -> int: ... + def __new__(cls, value: int) -> Self: ... + +def unique(enumeration: _EnumerationT) -> _EnumerationT: ... + +_auto_null: Any + +class Flag(Enum): + _name_: str | None # type: ignore[assignment] + _value_: int + _numeric_repr_: Callable[[int], str] + @_magic_enum_attr + def name(self) -> str | None: ... # type: ignore[override] + @_magic_enum_attr + def value(self) -> int: ... + def __contains__(self, other: Self) -> bool: ... + def __bool__(self) -> bool: ... + def __or__(self, other: Self) -> Self: ... + def __and__(self, other: Self) -> Self: ... + def __xor__(self, other: Self) -> Self: ... + def __invert__(self) -> Self: ... + if sys.version_info >= (3, 11): + def __iter__(self) -> Iterator[Self]: ... + def __len__(self) -> int: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +if sys.version_info >= (3, 11): + class StrEnum(str, ReprEnum): + def __new__(cls, value: str) -> Self: ... + _value_: str + @_magic_enum_attr + def value(self) -> str: ... + @staticmethod + def _generate_next_value_(name: str, start: int, count: int, last_values: list[str]) -> str: ... + + class EnumCheck(StrEnum): + CONTINUOUS = "no skipped integer values" + NAMED_FLAGS = "multi-flag aliases may not contain unnamed flags" + UNIQUE = "one name per value" + + CONTINUOUS: Final = EnumCheck.CONTINUOUS + NAMED_FLAGS: Final = EnumCheck.NAMED_FLAGS + UNIQUE: Final = EnumCheck.UNIQUE + + class verify: + def __init__(self, *checks: EnumCheck) -> None: ... + def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ... + + class FlagBoundary(StrEnum): + STRICT = "strict" + CONFORM = "conform" + EJECT = "eject" + KEEP = "keep" + + STRICT: Final = FlagBoundary.STRICT + CONFORM: Final = FlagBoundary.CONFORM + EJECT: Final = FlagBoundary.EJECT + KEEP: Final = FlagBoundary.KEEP + + def global_str(self: Enum) -> str: ... + def global_enum(cls: _EnumerationT, update_str: bool = False) -> _EnumerationT: ... + def global_enum_repr(self: Enum) -> str: ... + def global_flag_repr(self: Flag) -> str: ... + def show_flag_values(value: int) -> list[int]: ... + def bin(num: SupportsIndex, max_bits: int | None = None) -> str: ... + +if sys.version_info >= (3, 12): + # The body of the class is the same, but the base classes are different. + class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +elif sys.version_info >= (3, 11): + # The body of the class is the same, but the base classes are different. + @disjoint_base + class IntFlag(int, ReprEnum, Flag, boundary=KEEP): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +else: + @disjoint_base + class IntFlag(int, Flag): # type: ignore[misc] # complaints about incompatible bases + def __new__(cls, value: int) -> Self: ... + def __or__(self, other: int) -> Self: ... + def __and__(self, other: int) -> Self: ... + def __xor__(self, other: int) -> Self: ... + def __invert__(self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +class auto: + _value_: Any + @_magic_enum_attr + def value(self) -> Any: ... + def __new__(cls) -> Self: ... + + # These don't exist, but auto is basically immediately replaced with + # either an int or a str depending on the type of the enum. StrEnum's auto + # shouldn't have these, but they're needed for int versions of auto (mostly the __or__). + # Ideally type checkers would special case auto enough to handle this, + # but until then this is a slightly inaccurate helping hand. + def __or__(self, other: int | Self) -> Self: ... + def __and__(self, other: int | Self) -> Self: ... + def __xor__(self, other: int | Self) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ + +if sys.version_info >= (3, 11): + def pickle_by_global_name(self: Enum, proto: int) -> str: ... + def pickle_by_enum_name(self: _EnumMemberT, proto: int) -> tuple[Callable[..., Any], tuple[type[_EnumMemberT], str]]: ... diff --git a/stdlib/errno.pyi b/stdlib/errno.pyi new file mode 100644 index 000000000000..e025e1fd13b9 --- /dev/null +++ b/stdlib/errno.pyi @@ -0,0 +1,227 @@ +import sys +from collections.abc import Mapping +from typing import Final + +errorcode: Mapping[int, str] + +EPERM: Final[int] +ENOENT: Final[int] +ESRCH: Final[int] +EINTR: Final[int] +EIO: Final[int] +ENXIO: Final[int] +E2BIG: Final[int] +ENOEXEC: Final[int] +EBADF: Final[int] +ECHILD: Final[int] +EAGAIN: Final[int] +ENOMEM: Final[int] +EACCES: Final[int] +EFAULT: Final[int] +EBUSY: Final[int] +EEXIST: Final[int] +EXDEV: Final[int] +ENODEV: Final[int] +ENOTDIR: Final[int] +EISDIR: Final[int] +EINVAL: Final[int] +ENFILE: Final[int] +EMFILE: Final[int] +ENOTTY: Final[int] +ETXTBSY: Final[int] +EFBIG: Final[int] +ENOSPC: Final[int] +ESPIPE: Final[int] +EROFS: Final[int] +EMLINK: Final[int] +EPIPE: Final[int] +EDOM: Final[int] +ERANGE: Final[int] +EDEADLK: Final[int] +ENAMETOOLONG: Final[int] +ENOLCK: Final[int] +ENOSYS: Final[int] +ENOTEMPTY: Final[int] +ELOOP: Final[int] +EWOULDBLOCK: Final[int] +ENOMSG: Final[int] +EIDRM: Final[int] +ENOSTR: Final[int] +ENODATA: Final[int] +ETIME: Final[int] +ENOSR: Final[int] +EREMOTE: Final[int] +ENOLINK: Final[int] +EPROTO: Final[int] +EBADMSG: Final[int] +EOVERFLOW: Final[int] +EILSEQ: Final[int] +EUSERS: Final[int] +ENOTSOCK: Final[int] +EDESTADDRREQ: Final[int] +EMSGSIZE: Final[int] +EPROTOTYPE: Final[int] +ENOPROTOOPT: Final[int] +EPROTONOSUPPORT: Final[int] +ESOCKTNOSUPPORT: Final[int] +ENOTSUP: Final[int] +EOPNOTSUPP: Final[int] +EPFNOSUPPORT: Final[int] +EAFNOSUPPORT: Final[int] +EADDRINUSE: Final[int] +EADDRNOTAVAIL: Final[int] +ENETDOWN: Final[int] +ENETUNREACH: Final[int] +ENETRESET: Final[int] +ECONNABORTED: Final[int] +ECONNRESET: Final[int] +ENOBUFS: Final[int] +EISCONN: Final[int] +ENOTCONN: Final[int] +ESHUTDOWN: Final[int] +ETOOMANYREFS: Final[int] +ETIMEDOUT: Final[int] +ECONNREFUSED: Final[int] +EHOSTDOWN: Final[int] +EHOSTUNREACH: Final[int] +EALREADY: Final[int] +EINPROGRESS: Final[int] +ESTALE: Final[int] +EDQUOT: Final[int] +ECANCELED: Final[int] # undocumented +ENOTRECOVERABLE: Final[int] # undocumented +EOWNERDEAD: Final[int] # undocumented + +if sys.platform == "sunos5" or sys.platform == "solaris": # noqa: Y008 + ELOCKUNMAPPED: Final[int] + ENOTACTIVE: Final[int] + +if sys.platform != "win32": + ENOTBLK: Final[int] + EMULTIHOP: Final[int] + +if sys.platform == "darwin": + # All of the below are undocumented + EAUTH: Final[int] + EBADARCH: Final[int] + EBADEXEC: Final[int] + EBADMACHO: Final[int] + EBADRPC: Final[int] + EDEVERR: Final[int] + EFTYPE: Final[int] + ENEEDAUTH: Final[int] + ENOATTR: Final[int] + ENOPOLICY: Final[int] + EPROCLIM: Final[int] + EPROCUNAVAIL: Final[int] + EPROGMISMATCH: Final[int] + EPROGUNAVAIL: Final[int] + EPWROFF: Final[int] + ERPCMISMATCH: Final[int] + ESHLIBVERS: Final[int] + if sys.version_info >= (3, 11): + EQFULL: Final[int] + ENOTCAPABLE: Final[int] # available starting with 3.11.1 + +if sys.platform != "darwin": + EDEADLOCK: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + ECHRNG: Final[int] + EL2NSYNC: Final[int] + EL3HLT: Final[int] + EL3RST: Final[int] + ELNRNG: Final[int] + EUNATCH: Final[int] + ENOCSI: Final[int] + EL2HLT: Final[int] + EBADE: Final[int] + EBADR: Final[int] + EXFULL: Final[int] + ENOANO: Final[int] + EBADRQC: Final[int] + EBADSLT: Final[int] + EBFONT: Final[int] + ENONET: Final[int] + ENOPKG: Final[int] + EADV: Final[int] + ESRMNT: Final[int] + ECOMM: Final[int] + EDOTDOT: Final[int] + ENOTUNIQ: Final[int] + EBADFD: Final[int] + EREMCHG: Final[int] + ELIBACC: Final[int] + ELIBBAD: Final[int] + ELIBSCN: Final[int] + ELIBMAX: Final[int] + ELIBEXEC: Final[int] + ERESTART: Final[int] + ESTRPIPE: Final[int] + EUCLEAN: Final[int] + ENOTNAM: Final[int] + ENAVAIL: Final[int] + EISNAM: Final[int] + EREMOTEIO: Final[int] + # All of the below are undocumented + EKEYEXPIRED: Final[int] + EKEYREJECTED: Final[int] + EKEYREVOKED: Final[int] + EMEDIUMTYPE: Final[int] + ENOKEY: Final[int] + ENOMEDIUM: Final[int] + ERFKILL: Final[int] + + if sys.version_info >= (3, 14): + EHWPOISON: Final[int] + +if sys.platform == "win32": + # All of these are undocumented + WSABASEERR: Final[int] + WSAEACCES: Final[int] + WSAEADDRINUSE: Final[int] + WSAEADDRNOTAVAIL: Final[int] + WSAEAFNOSUPPORT: Final[int] + WSAEALREADY: Final[int] + WSAEBADF: Final[int] + WSAECONNABORTED: Final[int] + WSAECONNREFUSED: Final[int] + WSAECONNRESET: Final[int] + WSAEDESTADDRREQ: Final[int] + WSAEDISCON: Final[int] + WSAEDQUOT: Final[int] + WSAEFAULT: Final[int] + WSAEHOSTDOWN: Final[int] + WSAEHOSTUNREACH: Final[int] + WSAEINPROGRESS: Final[int] + WSAEINTR: Final[int] + WSAEINVAL: Final[int] + WSAEISCONN: Final[int] + WSAELOOP: Final[int] + WSAEMFILE: Final[int] + WSAEMSGSIZE: Final[int] + WSAENAMETOOLONG: Final[int] + WSAENETDOWN: Final[int] + WSAENETRESET: Final[int] + WSAENETUNREACH: Final[int] + WSAENOBUFS: Final[int] + WSAENOPROTOOPT: Final[int] + WSAENOTCONN: Final[int] + WSAENOTEMPTY: Final[int] + WSAENOTSOCK: Final[int] + WSAEOPNOTSUPP: Final[int] + WSAEPFNOSUPPORT: Final[int] + WSAEPROCLIM: Final[int] + WSAEPROTONOSUPPORT: Final[int] + WSAEPROTOTYPE: Final[int] + WSAEREMOTE: Final[int] + WSAESHUTDOWN: Final[int] + WSAESOCKTNOSUPPORT: Final[int] + WSAESTALE: Final[int] + WSAETIMEDOUT: Final[int] + WSAETOOMANYREFS: Final[int] + WSAEUSERS: Final[int] + WSAEWOULDBLOCK: Final[int] + WSANOTINITIALISED: Final[int] + WSASYSNOTREADY: Final[int] + WSAVERNOTSUPPORTED: Final[int] diff --git a/stdlib/faulthandler.pyi b/stdlib/faulthandler.pyi new file mode 100644 index 000000000000..6999933c43b9 --- /dev/null +++ b/stdlib/faulthandler.pyi @@ -0,0 +1,61 @@ +import sys +from _typeshed import FileDescriptorLike + +def cancel_dump_traceback_later() -> None: ... +def disable() -> None: ... + +if sys.version_info >= (3, 15): + def dump_traceback( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, *, max_threads: int | None = None + ) -> None: ... + +else: + def dump_traceback(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... + +if sys.version_info >= (3, 14): + def dump_c_stack(file: FileDescriptorLike = sys.stderr) -> None: ... + +if sys.version_info >= (3, 15): + def dump_traceback_later( + timeout: float, + repeat: bool = False, + file: FileDescriptorLike = sys.stderr, + exit: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... + +else: + def dump_traceback_later( + timeout: float, repeat: bool = False, file: FileDescriptorLike = sys.stderr, exit: bool = False + ) -> None: ... + +if sys.version_info >= (3, 15): + def enable( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True, *, max_threads: int | None = None + ) -> None: ... + +elif sys.version_info >= (3, 14): + def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True) -> None: ... + +else: + def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... + +def is_enabled() -> bool: ... + +if sys.platform != "win32": + if sys.version_info >= (3, 15): + def register( + signum: int, + file: FileDescriptorLike = sys.stderr, + all_threads: bool = True, + chain: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... + else: + def register( + signum: int, file: FileDescriptorLike = sys.stderr, all_threads: bool = True, chain: bool = False + ) -> None: ... + + def unregister(signum: int, /) -> None: ... diff --git a/stdlib/fcntl.pyi b/stdlib/fcntl.pyi new file mode 100644 index 000000000000..c17f31c4bebe --- /dev/null +++ b/stdlib/fcntl.pyi @@ -0,0 +1,157 @@ +import sys +from _typeshed import FileDescriptorLike, ReadOnlyBuffer, WriteableBuffer +from typing import Any, Final, Literal, overload +from typing_extensions import Buffer + +if sys.platform != "win32": + FASYNC: Final[int] + FD_CLOEXEC: Final[int] + F_DUPFD: Final[int] + F_DUPFD_CLOEXEC: Final[int] + F_GETFD: Final[int] + F_GETFL: Final[int] + F_GETLK: Final[int] + F_GETOWN: Final[int] + F_RDLCK: Final[int] + F_SETFD: Final[int] + F_SETFL: Final[int] + F_SETLK: Final[int] + F_SETLKW: Final[int] + F_SETOWN: Final[int] + F_UNLCK: Final[int] + F_WRLCK: Final[int] + + F_GETLEASE: Final[int] + F_SETLEASE: Final[int] + if sys.platform == "darwin": + F_FULLFSYNC: Final[int] + F_NOCACHE: Final[int] + F_GETPATH: Final[int] + if sys.platform == "linux": + F_SETLKW64: Final[int] + F_SETSIG: Final[int] + F_SHLCK: Final[int] + F_SETLK64: Final[int] + F_GETSIG: Final[int] + F_NOTIFY: Final[int] + F_EXLCK: Final[int] + F_GETLK64: Final[int] + F_ADD_SEALS: Final[int] + F_GET_SEALS: Final[int] + F_SEAL_GROW: Final[int] + F_SEAL_SEAL: Final[int] + F_SEAL_SHRINK: Final[int] + F_SEAL_WRITE: Final[int] + F_OFD_GETLK: Final[int] + F_OFD_SETLK: Final[int] + F_OFD_SETLKW: Final[int] + F_GETPIPE_SZ: Final[int] + F_SETPIPE_SZ: Final[int] + DN_ACCESS: Final[int] + DN_ATTRIB: Final[int] + DN_CREATE: Final[int] + DN_DELETE: Final[int] + DN_MODIFY: Final[int] + DN_MULTISHOT: Final[int] + DN_RENAME: Final[int] + + LOCK_EX: Final[int] + LOCK_NB: Final[int] + LOCK_SH: Final[int] + LOCK_UN: Final[int] + if sys.platform == "linux": + LOCK_MAND: Final[int] + LOCK_READ: Final[int] + LOCK_RW: Final[int] + LOCK_WRITE: Final[int] + + if sys.platform == "linux": + # Constants for the POSIX STREAMS interface. Present in glibc until 2.29 (released February 2019). + # Never implemented on BSD, and considered "obsolescent" starting in POSIX 2008. + # Probably still used on Solaris. + I_ATMARK: Final[int] + I_CANPUT: Final[int] + I_CKBAND: Final[int] + I_FDINSERT: Final[int] + I_FIND: Final[int] + I_FLUSH: Final[int] + I_FLUSHBAND: Final[int] + I_GETBAND: Final[int] + I_GETCLTIME: Final[int] + I_GETSIG: Final[int] + I_GRDOPT: Final[int] + I_GWROPT: Final[int] + I_LINK: Final[int] + I_LIST: Final[int] + I_LOOK: Final[int] + I_NREAD: Final[int] + I_PEEK: Final[int] + I_PLINK: Final[int] + I_POP: Final[int] + I_PUNLINK: Final[int] + I_PUSH: Final[int] + I_RECVFD: Final[int] + I_SENDFD: Final[int] + I_SETCLTIME: Final[int] + I_SETSIG: Final[int] + I_SRDOPT: Final[int] + I_STR: Final[int] + I_SWROPT: Final[int] + I_UNLINK: Final[int] + + if sys.version_info >= (3, 12) and sys.platform == "linux": + FICLONE: Final[int] + FICLONERANGE: Final[int] + + if sys.version_info >= (3, 13) and sys.platform == "linux": + F_OWNER_TID: Final = 0 + F_OWNER_PID: Final = 1 + F_OWNER_PGRP: Final = 2 + F_SETOWN_EX: Final = 15 + F_GETOWN_EX: Final = 16 + F_SEAL_FUTURE_WRITE: Final = 16 + F_GET_RW_HINT: Final = 1035 + F_SET_RW_HINT: Final = 1036 + F_GET_FILE_RW_HINT: Final = 1037 + F_SET_FILE_RW_HINT: Final = 1038 + RWH_WRITE_LIFE_NOT_SET: Final = 0 + RWH_WRITE_LIFE_NONE: Final = 1 + RWH_WRITE_LIFE_SHORT: Final = 2 + RWH_WRITE_LIFE_MEDIUM: Final = 3 + RWH_WRITE_LIFE_LONG: Final = 4 + RWH_WRITE_LIFE_EXTREME: Final = 5 + + if sys.version_info >= (3, 11) and sys.platform == "darwin": + F_OFD_SETLK: Final = 90 + F_OFD_SETLKW: Final = 91 + F_OFD_GETLK: Final = 92 + + if sys.version_info >= (3, 13) and sys.platform != "linux": + # OSx and NetBSD + F_GETNOSIGPIPE: Final[int] + F_SETNOSIGPIPE: Final[int] + # OSx and FreeBSD + F_RDAHEAD: Final[int] + + @overload + def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: ... + @overload + def fcntl(fd: FileDescriptorLike, cmd: int, arg: str | ReadOnlyBuffer, /) -> bytes: ... + + # If arg is an int, return int + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: ... + # The return type works as follows: + # - If arg is a read-write buffer, return int if mutate_flag is True, otherwise bytes + # - If arg is a read-only buffer, return bytes (and ignore the value of mutate_flag) + # We can't represent that precisely as we can't distinguish between read-write and read-only + # buffers, so we add overloads for a few unambiguous cases and use Any for the rest. + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: bytes, mutate_flag: bool = True, /) -> bytes: ... + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: WriteableBuffer, mutate_flag: Literal[False], /) -> bytes: ... + @overload + def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ... + + def flock(fd: FileDescriptorLike, operation: int, /) -> None: ... + def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: ... diff --git a/stdlib/filecmp.pyi b/stdlib/filecmp.pyi new file mode 100644 index 000000000000..620cc177a415 --- /dev/null +++ b/stdlib/filecmp.pyi @@ -0,0 +1,65 @@ +import sys +from _typeshed import GenericPath, StrOrBytesPath +from collections.abc import Callable, Iterable, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal + +__all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] + +DEFAULT_IGNORES: Final[list[str]] +BUFSIZE: Final = 8192 + +def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = True) -> bool: ... +def cmpfiles( + a: GenericPath[AnyStr], b: GenericPath[AnyStr], common: Iterable[GenericPath[AnyStr]], shallow: bool | Literal[0, 1] = True +) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... + +class dircmp(Generic[AnyStr]): + if sys.version_info >= (3, 13): + def __init__( + self, + a: GenericPath[AnyStr], + b: GenericPath[AnyStr], + ignore: Sequence[AnyStr] | None = None, + hide: Sequence[AnyStr] | None = None, + *, + shallow: bool = True, + ) -> None: ... + else: + def __init__( + self, + a: GenericPath[AnyStr], + b: GenericPath[AnyStr], + ignore: Sequence[AnyStr] | None = None, + hide: Sequence[AnyStr] | None = None, + ) -> None: ... + left: AnyStr + right: AnyStr + hide: Sequence[AnyStr] + ignore: Sequence[AnyStr] + # These properties are created at runtime by __getattr__ + subdirs: dict[AnyStr, dircmp[AnyStr]] + same_files: list[AnyStr] + diff_files: list[AnyStr] + funny_files: list[AnyStr] + common_dirs: list[AnyStr] + common_files: list[AnyStr] + common_funny: list[AnyStr] + common: list[AnyStr] + left_only: list[AnyStr] + right_only: list[AnyStr] + left_list: list[AnyStr] + right_list: list[AnyStr] + def report(self) -> None: ... + def report_partial_closure(self) -> None: ... + def report_full_closure(self) -> None: ... + methodmap: dict[str, Callable[[], None]] + def phase0(self) -> None: ... + def phase1(self) -> None: ... + def phase2(self) -> None: ... + def phase3(self) -> None: ... + def phase4(self) -> None: ... + def phase4_closure(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def clear_cache() -> None: ... diff --git a/stdlib/fileinput.pyi b/stdlib/fileinput.pyi new file mode 100644 index 000000000000..37783254c70f --- /dev/null +++ b/stdlib/fileinput.pyi @@ -0,0 +1,141 @@ +import sys +from _typeshed import AnyStr_co, StrOrBytesPath +from collections.abc import Callable, Iterable +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "input", + "close", + "nextfile", + "filename", + "lineno", + "filelineno", + "fileno", + "isfirstline", + "isstdin", + "FileInput", + "hook_compressed", + "hook_encoded", +] + +if sys.version_info >= (3, 11): + _TextMode: TypeAlias = Literal["r"] +else: + _TextMode: TypeAlias = Literal["r", "rU", "U"] + +@type_check_only +class _HasReadlineAndFileno(Protocol[AnyStr_co]): + def readline(self) -> AnyStr_co: ... + def fileno(self) -> int: ... + +# encoding and errors are added +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: _TextMode = "r", + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[str]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, + encoding: None = None, + errors: None = None, +) -> FileInput[bytes]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[Any]: ... + +def close() -> None: ... +def nextfile() -> None: ... +def filename() -> str: ... +def lineno() -> int: ... +def filelineno() -> int: ... +def fileno() -> int: ... +def isfirstline() -> bool: ... +def isstdin() -> bool: ... + +class FileInput(Generic[AnyStr]): + # encoding and errors are added + @overload + def __init__( + self: FileInput[str], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: _TextMode = "r", + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, + encoding: str | None = None, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, + encoding: None = None, + errors: None = None, + ) -> None: ... + @overload + def __init__( + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, + encoding: str | None = None, + errors: str | None = None, + ) -> None: ... + + def __del__(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> AnyStr: ... + if sys.version_info < (3, 11): + def __getitem__(self, i: int) -> AnyStr: ... + + def nextfile(self) -> None: ... + def readline(self) -> AnyStr: ... + def filename(self) -> str: ... + def lineno(self) -> int: ... + def filelineno(self) -> int: ... + def fileno(self) -> int: ... + def isfirstline(self) -> bool: ... + def isstdin(self) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def hook_compressed( + filename: StrOrBytesPath, mode: str, *, encoding: str | None = None, errors: str | None = None +) -> IO[Any]: ... +@deprecated("Deprecated since Python 3.10. Use `fileinput.input` or `fileinput.FileInput` instead.") +def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... diff --git a/stdlib/fnmatch.pyi b/stdlib/fnmatch.pyi new file mode 100644 index 000000000000..018139dc482b --- /dev/null +++ b/stdlib/fnmatch.pyi @@ -0,0 +1,16 @@ +import sys +from collections.abc import Iterable +from os import PathLike +from typing import AnyStr + +__all__ = ["filter", "fnmatch", "fnmatchcase", "translate"] +if sys.version_info >= (3, 14): + __all__ += ["filterfalse"] + +def fnmatch(name: AnyStr | PathLike[AnyStr], pat: AnyStr | PathLike[AnyStr]) -> bool: ... +def fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ... +def filter(names: Iterable[AnyStr | PathLike[AnyStr]], pat: AnyStr | PathLike[AnyStr]) -> list[AnyStr]: ... +def translate(pat: str) -> str: ... + +if sys.version_info >= (3, 14): + def filterfalse(names: Iterable[AnyStr | PathLike[AnyStr]], pat: AnyStr | PathLike[AnyStr]) -> list[AnyStr]: ... diff --git a/stdlib/fractions.pyi b/stdlib/fractions.pyi new file mode 100644 index 000000000000..42947f2e2266 --- /dev/null +++ b/stdlib/fractions.pyi @@ -0,0 +1,185 @@ +import sys +from collections.abc import Callable +from decimal import Decimal +from numbers import Rational, Real +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +_ComparableNum: TypeAlias = int | float | Decimal | Real + +__all__ = ["Fraction"] + +@type_check_only +class _ConvertibleToIntegerRatio(Protocol): + def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ... + +class Fraction(Rational): + __slots__ = ("_numerator", "_denominator") + + @overload + def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ... + @overload + def __new__(cls, numerator: float | Decimal | str) -> Self: ... + if sys.version_info >= (3, 14): + @overload + def __new__(cls, numerator: _ConvertibleToIntegerRatio) -> Self: ... + + @classmethod + def from_float(cls, f: float) -> Self: ... + @classmethod + def from_decimal(cls, dec: Decimal) -> Self: ... + def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ... + def as_integer_ratio(self) -> tuple[int, int]: ... + if sys.version_info >= (3, 12): + def is_integer(self) -> bool: ... + + @property + def numerator(a) -> int: ... + @property + def denominator(a) -> int: ... + + @overload + def __add__(a, b: int | Fraction) -> Fraction: ... + @overload + def __add__(a, b: float) -> float: ... + @overload + def __add__(a, b: complex) -> complex: ... + + @overload + def __radd__(b, a: int | Fraction) -> Fraction: ... + @overload + def __radd__(b, a: float) -> float: ... + @overload + def __radd__(b, a: complex) -> complex: ... + + @overload + def __sub__(a, b: int | Fraction) -> Fraction: ... + @overload + def __sub__(a, b: float) -> float: ... + @overload + def __sub__(a, b: complex) -> complex: ... + + @overload + def __rsub__(b, a: int | Fraction) -> Fraction: ... + @overload + def __rsub__(b, a: float) -> float: ... + @overload + def __rsub__(b, a: complex) -> complex: ... + + @overload + def __mul__(a, b: int | Fraction) -> Fraction: ... + @overload + def __mul__(a, b: float) -> float: ... + @overload + def __mul__(a, b: complex) -> complex: ... + + @overload + def __rmul__(b, a: int | Fraction) -> Fraction: ... + @overload + def __rmul__(b, a: float) -> float: ... + @overload + def __rmul__(b, a: complex) -> complex: ... + + @overload + def __truediv__(a, b: int | Fraction) -> Fraction: ... + @overload + def __truediv__(a, b: float) -> float: ... + @overload + def __truediv__(a, b: complex) -> complex: ... + + @overload + def __rtruediv__(b, a: int | Fraction) -> Fraction: ... + @overload + def __rtruediv__(b, a: float) -> float: ... + @overload + def __rtruediv__(b, a: complex) -> complex: ... + + @overload + def __floordiv__(a, b: int | Fraction) -> int: ... + @overload + def __floordiv__(a, b: float) -> float: ... + + @overload + def __rfloordiv__(b, a: int | Fraction) -> int: ... + @overload + def __rfloordiv__(b, a: float) -> float: ... + + @overload + def __mod__(a, b: int | Fraction) -> Fraction: ... + @overload + def __mod__(a, b: float) -> float: ... + + @overload + def __rmod__(b, a: int | Fraction) -> Fraction: ... + @overload + def __rmod__(b, a: float) -> float: ... + + @overload + def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... + @overload + def __divmod__(a, b: float) -> tuple[float, Fraction]: ... + + @overload + def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... + @overload + def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... + + if sys.version_info >= (3, 14): + @overload + def __pow__(a, b: int, modulo: None = None) -> Fraction: ... + @overload + def __pow__(a, b: float | Fraction, modulo: None = None) -> float: ... + @overload + def __pow__(a, b: complex, modulo: None = None) -> complex: ... + else: + @overload + def __pow__(a, b: int) -> Fraction: ... + @overload + def __pow__(a, b: float | Fraction) -> float: ... + @overload + def __pow__(a, b: complex) -> complex: ... + + if sys.version_info >= (3, 14): + @overload + def __rpow__(b, a: float | Fraction, modulo: None = None) -> float: ... + @overload + def __rpow__(b, a: complex, modulo: None = None) -> complex: ... + else: + @overload + def __rpow__(b, a: float | Fraction) -> float: ... + @overload + def __rpow__(b, a: complex) -> complex: ... + + def __pos__(a) -> Fraction: ... + def __neg__(a) -> Fraction: ... + def __abs__(a) -> Fraction: ... + def __trunc__(a) -> int: ... + def __floor__(a) -> int: ... + def __ceil__(a) -> int: ... + + @overload + def __round__(self, ndigits: None = None) -> int: ... + @overload + def __round__(self, ndigits: int) -> Fraction: ... + + def __hash__(self) -> int: ... # type: ignore[override] + def __eq__(a, b: object) -> bool: ... + def __lt__(a, b: _ComparableNum) -> bool: ... + def __gt__(a, b: _ComparableNum) -> bool: ... + def __le__(a, b: _ComparableNum) -> bool: ... + def __ge__(a, b: _ComparableNum) -> bool: ... + def __bool__(a) -> bool: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... + if sys.version_info >= (3, 11): + def __int__(a, _index: Callable[[SupportsIndex], int] = ...) -> int: ... + # Not actually defined within fractions.py, but provides more useful + # overrides + @property + def real(self) -> Fraction: ... + @property + def imag(self) -> Literal[0]: ... + def conjugate(self) -> Fraction: ... + if sys.version_info >= (3, 14): + @classmethod + def from_number(cls, number: float | Rational | _ConvertibleToIntegerRatio) -> Self: ... diff --git a/stdlib/ftplib.pyi b/stdlib/ftplib.pyi new file mode 100644 index 000000000000..1b7222fc94f7 --- /dev/null +++ b/stdlib/ftplib.pyi @@ -0,0 +1,174 @@ +import sys +from _typeshed import StrOrBytesPath, SupportsRead, SupportsReadline +from collections.abc import Callable, Iterable, Iterator +from socket import socket +from ssl import SSLContext +from types import TracebackType +from typing import Any, Final, Literal, TextIO, overload +from typing_extensions import Self, deprecated + +__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors", "FTP_TLS"] + +MSG_OOB: Final = 1 +FTP_PORT: Final = 21 +MAXLINE: Final = 8192 +CRLF: Final = "\r\n" +B_CRLF: Final = b"\r\n" + +class Error(Exception): ... +class error_reply(Error): ... +class error_temp(Error): ... +class error_perm(Error): ... +class error_proto(Error): ... + +all_errors: tuple[type[Exception], ...] + +class FTP: + debugging: int + host: str + port: int + maxline: int + sock: socket | None + welcome: str | None + passiveserver: int + timeout: float | None + af: int + lastresp: str + file: TextIO | None + encoding: str + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + source_address: tuple[str, int] | None + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... + def connect( + self, host: str = "", port: int = 0, timeout: float = -999, source_address: tuple[str, int] | None = None + ) -> str: ... + def getwelcome(self) -> str: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def set_pasv(self, val: bool | Literal[0, 1]) -> None: ... + def sanitize(self, s: str) -> str: ... + def putline(self, line: str) -> None: ... + def putcmd(self, line: str) -> None: ... + def getline(self) -> str: ... + def getmultiline(self) -> str: ... + def getresp(self) -> str: ... + def voidresp(self) -> str: ... + def abort(self) -> str: ... + def sendcmd(self, cmd: str) -> str: ... + def voidcmd(self, cmd: str) -> str: ... + def sendport(self, host: str, port: int) -> str: ... + def sendeprt(self, host: str, port: int) -> str: ... + def makeport(self) -> socket: ... + def makepasv(self) -> tuple[str, int]: ... + def login(self, user: str = "", passwd: str = "", acct: str = "") -> str: ... + # In practice, `rest` can actually be anything whose str() is an integer sequence, so to make it simple we allow integers + def ntransfercmd(self, cmd: str, rest: int | str | None = None) -> tuple[socket, int | None]: ... + def transfercmd(self, cmd: str, rest: int | str | None = None) -> socket: ... + def retrbinary( + self, cmd: str, callback: Callable[[bytes], object], blocksize: int = 8192, rest: int | str | None = None + ) -> str: ... + def storbinary( + self, + cmd: str, + fp: SupportsRead[bytes], + blocksize: int = 8192, + callback: Callable[[bytes], object] | None = None, + rest: int | str | None = None, + ) -> str: ... + def retrlines(self, cmd: str, callback: Callable[[str], object] | None = None) -> str: ... + def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Callable[[bytes], object] | None = None) -> str: ... + def acct(self, password: str) -> str: ... + def nlst(self, *args: str) -> list[str]: ... + # Technically only the last arg can be a Callable but ... + def dir(self, *args: str | Callable[[str], object]) -> None: ... + def mlsd(self, path: str = "", facts: Iterable[str] = []) -> Iterator[tuple[str, dict[str, str]]]: ... + def rename(self, fromname: str, toname: str) -> str: ... + def delete(self, filename: str) -> str: ... + def cwd(self, dirname: str) -> str: ... + def size(self, filename: str) -> int | None: ... + def mkd(self, dirname: str) -> str: ... + def rmd(self, dirname: str) -> str: ... + def pwd(self) -> str: ... + def quit(self) -> str: ... + def close(self) -> None: ... + +class FTP_TLS(FTP): + if sys.version_info >= (3, 12): + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + *, + context: SSLContext | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + encoding: str = "utf-8", + ) -> None: ... + else: + @overload + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + keyfile: None = None, + certfile: None = None, + context: SSLContext | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + context: None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... + + ssl_version: int + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + context: SSLContext + def login(self, user: str = "", passwd: str = "", acct: str = "", secure: bool = True) -> str: ... + def auth(self) -> str: ... + def prot_p(self) -> str: ... + def prot_c(self) -> str: ... + def ccc(self) -> str: ... + +def parse150(resp: str) -> int | None: ... # undocumented +def parse227(resp: str) -> tuple[str, int]: ... # undocumented +def parse229(resp: str, peer: Any) -> tuple[str, int]: ... # undocumented +def parse257(resp: str) -> str: ... # undocumented +def ftpcp( + source: FTP, sourcename: str, target: FTP, targetname: str = "", type: Literal["A", "I"] = "I" +) -> None: ... # undocumented diff --git a/stdlib/functools.pyi b/stdlib/functools.pyi new file mode 100644 index 000000000000..c1d31dd18d20 --- /dev/null +++ b/stdlib/functools.pyi @@ -0,0 +1,281 @@ +import sys +import types +from _typeshed import SupportsAllComparisons, SupportsItems +from collections.abc import Callable, Hashable, Iterable, Sized +from types import GenericAlias +from typing import ( + Any, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + TypeAlias, + TypedDict, + TypeVar, + final, + overload, + type_check_only, +) +from typing_extensions import Self, disjoint_base + +__all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", + "cached_property", + "singledispatchmethod", + "cache", +] + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_S = TypeVar("_S") +_PWrapped = ParamSpec("_PWrapped") +_RWrapped = TypeVar("_RWrapped") +_PWrapper = ParamSpec("_PWrapper") +_RWrapper = TypeVar("_RWrapper") + +if sys.version_info >= (3, 14): + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], /, initial: _T) -> _T: ... +else: + @overload + def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initial: _T, /) -> _T: ... + +@overload +def reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T], /) -> _T: ... + +class _CacheInfo(NamedTuple): + hits: int + misses: int + maxsize: int | None + currsize: int + +@type_check_only +class _CacheParameters(TypedDict): + maxsize: int + typed: bool + +@final +class _lru_cache_wrapper(Generic[_T_co]): + __wrapped__: Callable[..., _T_co] + def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T_co: ... + def cache_info(self) -> _CacheInfo: ... + def cache_clear(self) -> None: ... + def cache_parameters(self) -> _CacheParameters: ... + def __copy__(self) -> _lru_cache_wrapper[_T_co]: ... + def __deepcopy__(self, memo: Any, /) -> _lru_cache_wrapper[_T_co]: ... + + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str + +@overload +def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... +@overload +def lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ... + +if sys.version_info >= (3, 14): + WRAPPER_ASSIGNMENTS: Final[ + tuple[ + Literal["__module__"], + Literal["__name__"], + Literal["__qualname__"], + Literal["__doc__"], + Literal["__annotate__"], + Literal["__type_params__"], + ] + ] +elif sys.version_info >= (3, 12): + WRAPPER_ASSIGNMENTS: Final[ + tuple[ + Literal["__module__"], + Literal["__name__"], + Literal["__qualname__"], + Literal["__doc__"], + Literal["__annotations__"], + Literal["__type_params__"], + ] + ] +else: + WRAPPER_ASSIGNMENTS: Final[ + tuple[Literal["__module__"], Literal["__name__"], Literal["__qualname__"], Literal["__doc__"], Literal["__annotations__"]] + ] + +WRAPPER_UPDATES: Final[tuple[Literal["__dict__"]]] + +@type_check_only +class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): + __wrapped__: Callable[_PWrapped, _RWrapped] + def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... + # as with ``Callable``, we'll assume that these attributes exist + __name__: str + __qualname__: str + +@type_check_only +class _Wrapper(Generic[_PWrapped, _RWrapped]): + def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + +if sys.version_info >= (3, 14): + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotate__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +elif sys.version_info >= (3, 12): + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__", "__type_params__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +else: + def update_wrapper( + wrapper: Callable[_PWrapper, _RWrapper], + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... + def wraps( + wrapped: Callable[_PWrapped, _RWrapped], + assigned: Iterable[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Iterable[str] = ("__dict__",), + ) -> _Wrapper[_PWrapped, _RWrapped]: ... + +def total_ordering(cls: type[_T]) -> type[_T]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... + +@disjoint_base +class partial(Generic[_T]): + @property + def func(self) -> Callable[..., _T]: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def keywords(self) -> dict[str, Any]: ... + def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# With protocols, this could change into a generic protocol that defines __get__ and returns _T +_Descriptor: TypeAlias = Any + +class partialmethod(Generic[_T]): + func: Callable[..., _T] | _Descriptor + args: tuple[Any, ...] + keywords: dict[str, Any] + if sys.version_info >= (3, 14): + @overload + def __new__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> Self: ... + @overload + def __new__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> Self: ... + else: + @overload + def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ... + @overload + def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ... + + def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... + @property + def __isabstractmethod__(self) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 11): + _RegType: TypeAlias = type[Any] | types.UnionType +else: + _RegType: TypeAlias = type[Any] + +@type_check_only +class _SingleDispatchCallable(Generic[_T]): + registry: types.MappingProxyType[Any, Callable[..., _T]] + def dispatch(self, cls: Any) -> Callable[..., _T]: ... + + # @fun.register(complex) + # def _(arg, verbose=False): ... + @overload + def register(self, cls: _RegType, func: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + # @fun.register + # def _(arg: int, verbose=False): + @overload + def register(self, cls: Callable[..., _T], func: None = None) -> Callable[..., _T]: ... + # fun.register(int, lambda x: x) + @overload + def register(self, cls: _RegType, func: Callable[..., _T]) -> Callable[..., _T]: ... + + def _clear_cache(self) -> None: ... + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... + +def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... + +class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... + + @overload + def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... + @overload + def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ... + + def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... + +class cached_property(Generic[_T_co]): + func: Callable[[Any], _T_co] + attrname: str | None + def __init__(self, func: Callable[[Any], _T_co]) -> None: ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... + @overload + def __get__(self, instance: object, owner: type[Any] | None = None) -> _T_co: ... + + def __set_name__(self, owner: type[Any], name: str) -> None: ... + # __set__ is not defined at runtime, but @cached_property is designed to be settable + def __set__(self, instance: object, value: _T_co) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-variance] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ... +def _make_key( + args: tuple[Hashable, ...], + kwds: SupportsItems[Any, Any], + typed: bool, + kwd_mark: tuple[object, ...] = ..., + fasttypes: set[type] = ..., + tuple: type = ..., + type: Any = ..., + len: Callable[[Sized], int] = ..., +) -> Hashable: ... + +if sys.version_info >= (3, 14): + @final + class _PlaceholderType: ... + + Placeholder: Final[_PlaceholderType] + + __all__ += ["Placeholder"] diff --git a/stdlib/gc.pyi b/stdlib/gc.pyi new file mode 100644 index 000000000000..dc20a570cc89 --- /dev/null +++ b/stdlib/gc.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable +from typing import Any, Final, Literal, TypeAlias + +DEBUG_COLLECTABLE: Final = 2 +DEBUG_LEAK: Final = 38 +DEBUG_SAVEALL: Final = 32 +DEBUG_STATS: Final = 1 +DEBUG_UNCOLLECTABLE: Final = 4 + +_CallbackType: TypeAlias = Callable[[Literal["start", "stop"], dict[str, int]], object] + +callbacks: list[_CallbackType] +garbage: list[Any] + +def collect(generation: int = 2) -> int: ... +def disable() -> None: ... +def enable() -> None: ... +def get_count() -> tuple[int, int, int]: ... +def get_debug() -> int: ... +def get_objects(generation: int | None = None) -> list[Any]: ... +def freeze() -> None: ... +def unfreeze() -> None: ... +def get_freeze_count() -> int: ... +def get_referents(*objs: Any) -> list[Any]: ... +def get_referrers(*objs: Any) -> list[Any]: ... +def get_stats() -> list[dict[str, Any]]: ... +def get_threshold() -> tuple[int, int, int]: ... +def is_tracked(obj: Any, /) -> bool: ... +def is_finalized(obj: Any, /) -> bool: ... +def isenabled() -> bool: ... +def set_debug(flags: int, /) -> None: ... +def set_threshold(threshold0: int, threshold1: int = 0, threshold2: int = 0, /) -> None: ... diff --git a/stdlib/genericpath.pyi b/stdlib/genericpath.pyi new file mode 100644 index 000000000000..07c58cc496b6 --- /dev/null +++ b/stdlib/genericpath.pyi @@ -0,0 +1,98 @@ +import os +import sys +from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT +from collections.abc import Sequence +from typing import Literal, NewType, overload +from typing_extensions import LiteralString, deprecated + +__all__ = [ + "commonprefix", + "exists", + "getatime", + "getctime", + "getmtime", + "getsize", + "isdir", + "isfile", + "samefile", + "sameopenfile", + "samestat", + "ALLOW_MISSING", +] +if sys.version_info >= (3, 12): + __all__ += ["islink"] +if sys.version_info >= (3, 13): + __all__ += ["isjunction", "isdevdrive", "lexists"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] + +# All overloads can return empty string. Ideally, Literal[""] would be a valid +# Iterable[T], so that list[T] | Literal[""] could be used as a return +# type. But because this only works when T is str, we need Sequence[T] instead. +if sys.version_info >= (3, 15): + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[LiteralString], /) -> LiteralString: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[StrPath], /) -> str: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[BytesPath], /) -> bytes | Literal[""]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[list[SupportsRichComparisonT]], /) -> Sequence[SupportsRichComparisonT]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]], /) -> Sequence[SupportsRichComparisonT]: ... +else: + @overload + def commonprefix(m: Sequence[LiteralString]) -> LiteralString: ... + @overload + def commonprefix(m: Sequence[StrPath]) -> str: ... + @overload + def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... + @overload + def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... + @overload + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... + +def exists(path: FileDescriptorOrPath) -> bool: ... +def isfile(path: FileDescriptorOrPath) -> bool: ... +def isdir(s: FileDescriptorOrPath) -> bool: ... + +if sys.version_info >= (3, 12): + def islink(path: StrOrBytesPath) -> bool: ... + +# These return float if os.stat_float_times() == True, +# but int is a subclass of float. +def sameopenfile(fp1: int, fp2: int) -> bool: ... + +if sys.version_info >= (3, 15): + def getsize(filename: FileDescriptorOrPath, /) -> int: ... + def getatime(filename: FileDescriptorOrPath, /) -> float: ... + def getmtime(filename: FileDescriptorOrPath, /) -> float: ... + def getctime(filename: FileDescriptorOrPath, /) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, /) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result, /) -> bool: ... + +else: + def getsize(filename: FileDescriptorOrPath) -> int: ... + def getatime(filename: FileDescriptorOrPath) -> float: ... + def getmtime(filename: FileDescriptorOrPath) -> float: ... + def getctime(filename: FileDescriptorOrPath) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 13): + def isjunction(path: StrOrBytesPath) -> bool: ... + def isdevdrive(path: StrOrBytesPath) -> bool: ... + def lexists(path: StrOrBytesPath) -> bool: ... + +# Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 +_AllowMissingType = NewType("_AllowMissingType", object) +ALLOW_MISSING: _AllowMissingType + +if sys.version_info >= (3, 15): + _AllButLastType = NewType("_AllButLastType", object) + ALL_BUT_LAST: _AllButLastType diff --git a/stdlib/getopt.pyi b/stdlib/getopt.pyi new file mode 100644 index 000000000000..c15db8122cfc --- /dev/null +++ b/stdlib/getopt.pyi @@ -0,0 +1,27 @@ +from collections.abc import Iterable, Sequence +from typing import Protocol, TypeVar, overload, type_check_only + +_StrSequenceT_co = TypeVar("_StrSequenceT_co", covariant=True, bound=Sequence[str]) + +@type_check_only +class _SliceableT(Protocol[_StrSequenceT_co]): + @overload + def __getitem__(self, key: int, /) -> str: ... + @overload + def __getitem__(self, key: slice, /) -> _StrSequenceT_co: ... + +__all__ = ["GetoptError", "error", "getopt", "gnu_getopt"] + +def getopt( + args: _SliceableT[_StrSequenceT_co], shortopts: str, longopts: Iterable[str] | str = [] +) -> tuple[list[tuple[str, str]], _StrSequenceT_co]: ... +def gnu_getopt( + args: Sequence[str], shortopts: str, longopts: Iterable[str] | str = [] +) -> tuple[list[tuple[str, str]], list[str]]: ... + +class GetoptError(Exception): + msg: str + opt: str + def __init__(self, msg: str, opt: str = "") -> None: ... + +error = GetoptError diff --git a/stdlib/getpass.pyi b/stdlib/getpass.pyi new file mode 100644 index 000000000000..bb3013dfbf39 --- /dev/null +++ b/stdlib/getpass.pyi @@ -0,0 +1,14 @@ +import sys +from typing import TextIO + +__all__ = ["getpass", "getuser", "GetPassWarning"] + +if sys.version_info >= (3, 14): + def getpass(prompt: str = "Password: ", stream: TextIO | None = None, *, echo_char: str | None = None) -> str: ... + +else: + def getpass(prompt: str = "Password: ", stream: TextIO | None = None) -> str: ... + +def getuser() -> str: ... + +class GetPassWarning(UserWarning): ... diff --git a/stdlib/gettext.pyi b/stdlib/gettext.pyi new file mode 100644 index 000000000000..aac2d3edf7d9 --- /dev/null +++ b/stdlib/gettext.pyi @@ -0,0 +1,190 @@ +import io +import sys +from _typeshed import StrPath +from collections.abc import Callable, Container, Iterable, Sequence +from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import deprecated + +__all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "find", + "translation", + "install", + "textdomain", + "bindtextdomain", + "dgettext", + "dngettext", + "gettext", + "ngettext", + "dnpgettext", + "dpgettext", + "npgettext", + "pgettext", +] + +if sys.version_info < (3, 11): + __all__ += ["bind_textdomain_codeset", "ldgettext", "ldngettext", "lgettext", "lngettext"] + +@type_check_only +class _TranslationsReader(Protocol): + def read(self) -> bytes: ... + # optional: + # name: str + +class NullTranslations: + def __init__(self, fp: _TranslationsReader | None = None) -> None: ... + def _parse(self, fp: _TranslationsReader) -> None: ... + def add_fallback(self, fallback: NullTranslations) -> None: ... + def gettext(self, message: str) -> str: ... + def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... + def pgettext(self, context: str, message: str) -> str: ... + def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... + def info(self) -> dict[str, str]: ... + def charset(self) -> str | None: ... + if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.8; removed in Python 3.11.") + def output_charset(self) -> str | None: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11.") + def set_output_charset(self, charset: str) -> None: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.") + def lgettext(self, message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.") + def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... + + def install(self, names: Container[str] | None = None) -> None: ... + +class GNUTranslations(NullTranslations): + LE_MAGIC: Final[int] + BE_MAGIC: Final[int] + CONTEXT: str + VERSIONS: Sequence[int] + +@overload +def find( + domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: Literal[False] = False +) -> str | None: ... +@overload +def find( + domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, *, all: Literal[True] +) -> list[str]: ... +@overload +def find(domain: str, localedir: StrPath | None, languages: Iterable[str] | None, all: Literal[True]) -> list[str]: ... +@overload +def find(domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: bool = False) -> Any: ... + +_NullTranslationsT = TypeVar("_NullTranslationsT", bound=NullTranslations) + +if sys.version_info >= (3, 11): + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: None = None, + fallback: Literal[False] = False, + ) -> GNUTranslations: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: Callable[[io.BufferedReader], NullTranslations] | None = None, + fallback: bool = False, + ) -> NullTranslations: ... + + def install(domain: str, localedir: StrPath | None = None, *, names: Container[str] | None = None) -> None: ... +else: + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: None = None, + fallback: Literal[False] = False, + codeset: str | None = ..., + ) -> GNUTranslations: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + codeset: str | None = ..., + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = False, + codeset: str | None = ..., + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = None, + languages: Iterable[str] | None = None, + class_: Callable[[io.BufferedReader], NullTranslations] | None = None, + fallback: bool = False, + codeset: str | None = ..., + ) -> NullTranslations: ... + + @overload + def install(domain: str, localedir: StrPath | None = None, names: Container[str] | None = None) -> None: ... + @overload + @deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.") + def install(domain: str, localedir: StrPath | None, codeset: str | None, /, names: Container[str] | None = None) -> None: ... + @overload + @deprecated("The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.") + def install( + domain: str, localedir: StrPath | None = None, *, codeset: str | None, names: Container[str] | None = None + ) -> None: ... + +def textdomain(domain: str | None = None) -> str: ... +def bindtextdomain(domain: str, localedir: StrPath | None = None) -> str: ... +def dgettext(domain: str, message: str) -> str: ... +def dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... +def gettext(message: str) -> str: ... +def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... +def pgettext(context: str, message: str) -> str: ... +def dpgettext(domain: str, context: str, message: str) -> str: ... +def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... +def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... + +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.") + def lgettext(message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `dgettext()` instead.") + def ldgettext(domain: str, message: str) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.") + def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `dngettext()` instead.") + def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... + @deprecated("Deprecated since Python 3.8; removed in Python 3.11. Use `bindtextdomain()` instead.") + def bind_textdomain_codeset(domain: str, codeset: str | None = None) -> str: ... + +Catalog = translation + +def c2py(plural: str) -> Callable[[int], int]: ... diff --git a/stdlib/glob.pyi b/stdlib/glob.pyi new file mode 100644 index 000000000000..bdfb2cfbcfed --- /dev/null +++ b/stdlib/glob.pyi @@ -0,0 +1,54 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterator, Sequence +from typing import AnyStr +from typing_extensions import deprecated + +__all__ = ["escape", "glob", "iglob"] + +if sys.version_info >= (3, 13): + __all__ += ["translate"] + +if sys.version_info < (3, 15): + @deprecated( + "Deprecated since Python 3.10; will be removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead." + ) + def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... + @deprecated( + "Deprecated since Python 3.10; will be removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead." + ) + def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... + +if sys.version_info >= (3, 11): + def glob( + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = None, + dir_fd: int | None = None, + recursive: bool = False, + include_hidden: bool = False, + ) -> list[AnyStr]: ... + def iglob( + pathname: AnyStr, + *, + root_dir: StrOrBytesPath | None = None, + dir_fd: int | None = None, + recursive: bool = False, + include_hidden: bool = False, + ) -> Iterator[AnyStr]: ... + +else: + def glob( + pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False + ) -> list[AnyStr]: ... + def iglob( + pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False + ) -> Iterator[AnyStr]: ... + +def escape(pathname: AnyStr) -> AnyStr: ... +def has_magic(s: str | bytes) -> bool: ... # undocumented + +if sys.version_info >= (3, 13): + def translate( + pat: str, *, recursive: bool = False, include_hidden: bool = False, seps: Sequence[str] | None = None + ) -> str: ... diff --git a/stdlib/graphlib.pyi b/stdlib/graphlib.pyi new file mode 100644 index 000000000000..f0ac72b6135e --- /dev/null +++ b/stdlib/graphlib.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import SupportsItems +from collections.abc import Iterable +from typing import Any, Generic, TypeVar, overload + +__all__ = ["TopologicalSorter", "CycleError"] + +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + from types import GenericAlias + +class TopologicalSorter(Generic[_T]): + @overload + def __init__(self, graph: None = None) -> None: ... + @overload + def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ... + + def add(self, node: _T, *predecessors: _T) -> None: ... + def prepare(self) -> None: ... + def is_active(self) -> bool: ... + def __bool__(self) -> bool: ... + def done(self, *nodes: _T) -> None: ... + def get_ready(self) -> tuple[_T, ...]: ... + def static_order(self) -> Iterable[_T]: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class CycleError(ValueError): ... diff --git a/stdlib/grp.pyi b/stdlib/grp.pyi new file mode 100644 index 000000000000..9f372b4d63dc --- /dev/null +++ b/stdlib/grp.pyi @@ -0,0 +1,21 @@ +import sys +from _typeshed import structseq +from typing import Any, Final, final + +if sys.platform != "win32": + @final + class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): + __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") + + @property + def gr_name(self) -> str: ... + @property + def gr_passwd(self) -> str | None: ... + @property + def gr_gid(self) -> int: ... + @property + def gr_mem(self) -> list[str]: ... + + def getgrall() -> list[struct_group]: ... + def getgrgid(id: int) -> struct_group: ... + def getgrnam(name: str) -> struct_group: ... diff --git a/stdlib/gzip.pyi b/stdlib/gzip.pyi new file mode 100644 index 000000000000..4322e6c84c90 --- /dev/null +++ b/stdlib/gzip.pyi @@ -0,0 +1,181 @@ +import sys +import zlib +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, WriteableBuffer +from io import FileIO, TextIOWrapper +from typing import Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import deprecated + +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream, DecompressReader +else: + from _compression import BaseStream, DecompressReader + +__all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] + +_ReadBinaryMode: TypeAlias = Literal["r", "rb"] +_WriteBinaryMode: TypeAlias = Literal["a", "ab", "w", "wb", "x", "xb"] +_OpenTextMode: TypeAlias = Literal["rt", "at", "wt", "xt"] + +READ: Final[object] # undocumented +WRITE: Final[object] # undocumented + +FTEXT: Final[int] # actually Literal[1] # undocumented +FHCRC: Final[int] # actually Literal[2] # undocumented +FEXTRA: Final[int] # actually Literal[4] # undocumented +FNAME: Final[int] # actually Literal[8] # undocumented +FCOMMENT: Final[int] # actually Literal[16] # undocumented + +@type_check_only +class _ReadableFileobj(Protocol): + def read(self, n: int, /) -> bytes: ... + def seek(self, n: int, /) -> object: ... + # The following attributes and methods are optional: + # name: str + # mode: str + # def fileno() -> int: ... + +@type_check_only +class _WritableFileobj(Protocol): + def write(self, b: bytes, /) -> object: ... + def flush(self) -> object: ... + # The following attributes and methods are optional: + # name: str + # mode: str + # def fileno() -> int: ... + +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj, + mode: _ReadBinaryMode = "rb", + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> GzipFile: ... +@overload +def open( + filename: StrOrBytesPath | _WritableFileobj, + mode: _WriteBinaryMode, + compresslevel: int = 9, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> GzipFile: ... +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, + mode: _OpenTextMode, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, + mode: str, + compresslevel: int = 9, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> GzipFile | TextIOWrapper: ... + +class _PaddedFile: + file: _ReadableFileobj + def __init__(self, f: _ReadableFileobj, prepend: bytes = b"") -> None: ... + def read(self, size: int) -> bytes: ... + def prepend(self, prepend: bytes = b"") -> None: ... + def seek(self, off: int) -> int: ... + def seekable(self) -> bool: ... + +class BadGzipFile(OSError): ... + +class GzipFile(BaseStream): + myfileobj: FileIO | None + mode: object + name: str + compress: zlib._Compress + fileobj: _ReadableFileobj | _WritableFileobj + + @overload + def __init__( + self, + filename: StrOrBytesPath | None, + mode: _ReadBinaryMode, + compresslevel: int = 9, + fileobj: _ReadableFileobj | None = None, + mtime: float | None = None, + ) -> None: ... + @overload + def __init__( + self, + *, + mode: _ReadBinaryMode, + compresslevel: int = 9, + fileobj: _ReadableFileobj | None = None, + mtime: float | None = None, + ) -> None: ... + @overload + def __init__( + self, + filename: StrOrBytesPath | None, + mode: _WriteBinaryMode, + compresslevel: int = 9, + fileobj: _WritableFileobj | None = None, + mtime: float | None = None, + ) -> None: ... + @overload + def __init__( + self, + *, + mode: _WriteBinaryMode, + compresslevel: int = 9, + fileobj: _WritableFileobj | None = None, + mtime: float | None = None, + ) -> None: ... + @overload + def __init__( + self, + filename: StrOrBytesPath | None = None, + mode: str | None = None, + compresslevel: int = 9, + fileobj: _ReadableFileobj | _WritableFileobj | None = None, + mtime: float | None = None, + ) -> None: ... + + if sys.version_info < (3, 12): + @property + @deprecated("Deprecated since Python 2.6; removed in Python 3.12. Use `name` attribute instead.") + def filename(self) -> str: ... + + @property + def mtime(self) -> int | None: ... + crc: int + def write(self, data: ReadableBuffer) -> int: ... + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... + def peek(self, n: int) -> bytes: ... + def close(self) -> None: ... + def flush(self, zlib_mode: int = 2) -> None: ... + def fileno(self) -> int: ... + def rewind(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def readline(self, size: int | None = -1) -> bytes: ... + + if sys.version_info >= (3, 14): + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + +class _GzipReader(DecompressReader): + def __init__(self, fp: _ReadableFileobj) -> None: ... + +if sys.version_info >= (3, 15): + def compress(data: SizedBuffer, compresslevel: int = 6, *, mtime: float = 0) -> bytes: ... + +elif sys.version_info >= (3, 14): + def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float = 0) -> bytes: ... + +else: + def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ... + +def decompress(data: ReadableBuffer) -> bytes: ... diff --git a/stdlib/hashlib.pyi b/stdlib/hashlib.pyi new file mode 100644 index 000000000000..50bc8e21f1d5 --- /dev/null +++ b/stdlib/hashlib.pyi @@ -0,0 +1,112 @@ +import sys +from _blake2 import blake2b as blake2b, blake2s as blake2s +from _hashlib import ( + HASH, + _HashObject, + openssl_md5 as md5, + openssl_sha1 as sha1, + openssl_sha3_224 as sha3_224, + openssl_sha3_256 as sha3_256, + openssl_sha3_384 as sha3_384, + openssl_sha3_512 as sha3_512, + openssl_sha224 as sha224, + openssl_sha256 as sha256, + openssl_sha384 as sha384, + openssl_sha512 as sha512, + openssl_shake_128 as shake_128, + openssl_shake_256 as shake_256, + pbkdf2_hmac as pbkdf2_hmac, + scrypt as scrypt, +) +from _typeshed import ReadableBuffer +from collections.abc import Callable, Set as AbstractSet +from typing import Protocol, type_check_only + +if sys.version_info >= (3, 15): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "file_digest", + "pbkdf2_hmac", + "scrypt", + ) +elif sys.version_info >= (3, 11): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "file_digest", + "pbkdf2_hmac", + ) +else: + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", + "pbkdf2_hmac", + ) + +def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + +algorithms_guaranteed: AbstractSet[str] +algorithms_available: AbstractSet[str] + +if sys.version_info >= (3, 11): + @type_check_only + class _BytesIOLike(Protocol): + def getbuffer(self) -> ReadableBuffer: ... + + @type_check_only + class _FileDigestFileObj(Protocol): + def readinto(self, buf: bytearray, /) -> int: ... + def readable(self) -> bool: ... + + def file_digest( + fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _HashObject], /, *, _bufsize: int = 262144 + ) -> HASH: ... + +# Legacy typing-only alias +_Hash = HASH diff --git a/stdlib/heapq.pyi b/stdlib/heapq.pyi new file mode 100644 index 000000000000..7969aa4e0015 --- /dev/null +++ b/stdlib/heapq.pyi @@ -0,0 +1,32 @@ +import sys +from _heapq import * +from _typeshed import SupportsRichComparison, SupportsRichComparisonT as _T +from collections.abc import Callable, Generator, Iterable +from typing import Final, TypeVar, overload + +__all__ = ["heappush", "heappop", "heapify", "heapreplace", "merge", "nlargest", "nsmallest", "heappushpop"] + +if sys.version_info >= (3, 14): + # Added to __all__ in 3.14.1 + __all__ += ["heapify_max", "heappop_max", "heappush_max", "heappushpop_max", "heapreplace_max"] + +_S = TypeVar("_S") + +__about__: Final[str] + +@overload +def merge(*iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison], reverse: bool = False) -> Generator[_S]: ... +@overload +def merge(*iterables: Iterable[_T], key: None = None, reverse: bool = False) -> Generator[_T]: ... + +@overload +def nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ... +@overload +def nlargest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ... + +@overload +def nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison]) -> list[_S]: ... +@overload +def nsmallest(n: int, iterable: Iterable[_T], key: None = None) -> list[_T]: ... + +def _heapify_max(heap: list[SupportsRichComparison], /) -> None: ... # undocumented diff --git a/stdlib/hmac.pyi b/stdlib/hmac.pyi new file mode 100644 index 000000000000..9beabcc4dd92 --- /dev/null +++ b/stdlib/hmac.pyi @@ -0,0 +1,33 @@ +from _hashlib import _HashObject, compare_digest as compare_digest +from _typeshed import ReadableBuffer, SizedBuffer +from collections.abc import Callable +from types import ModuleType +from typing import TypeAlias, overload + +_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType + +trans_5C: bytes +trans_36: bytes + +digest_size: None + +# In reality digestmod has a default value, but the function always throws an error +# if the argument is not given, so we pretend it is a required argument. +@overload +def new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ... +@overload +def new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ... + +class HMAC: + __slots__ = ("_hmac", "_inner", "_outer", "block_size", "digest_size") + digest_size: int + block_size: int + @property + def name(self) -> str: ... + def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = "") -> None: ... + def update(self, msg: ReadableBuffer) -> None: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def copy(self) -> HMAC: ... + +def digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ... diff --git a/stdlib/html/__init__.pyi b/stdlib/html/__init__.pyi new file mode 100644 index 000000000000..71e971d15044 --- /dev/null +++ b/stdlib/html/__init__.pyi @@ -0,0 +1,7 @@ +import re + +__all__ = ["escape", "unescape"] + +def escape(s: str, quote: bool = True) -> str: ... +def unescape(s: str) -> str: ... +def _replace_charref(s: re.Match[str]) -> str: ... diff --git a/stdlib/html/entities.pyi b/stdlib/html/entities.pyi new file mode 100644 index 000000000000..e5890d1ecfbd --- /dev/null +++ b/stdlib/html/entities.pyi @@ -0,0 +1,8 @@ +from typing import Final + +__all__ = ["html5", "name2codepoint", "codepoint2name", "entitydefs"] + +name2codepoint: Final[dict[str, int]] +html5: Final[dict[str, str]] +codepoint2name: Final[dict[int, str]] +entitydefs: Final[dict[str, str]] diff --git a/stdlib/html/parser.pyi b/stdlib/html/parser.pyi new file mode 100644 index 000000000000..08dc7b936922 --- /dev/null +++ b/stdlib/html/parser.pyi @@ -0,0 +1,40 @@ +from _markupbase import ParserBase +from re import Pattern +from typing import Final + +__all__ = ["HTMLParser"] + +class HTMLParser(ParserBase): + CDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]] + # Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6 + RCDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]] + + # `scripting` parameter added in Python 3.9.25, 3.10.20, 3.11.15, 3.12.13, 3.13.10, 3.14.1 + def __init__(self, *, convert_charrefs: bool = True, scripting: bool = False) -> None: ... + def feed(self, data: str) -> None: ... + def close(self) -> None: ... + def get_starttag_text(self) -> str | None: ... + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ... + def handle_endtag(self, tag: str) -> None: ... + def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ... + def handle_data(self, data: str) -> None: ... + def handle_entityref(self, name: str) -> None: ... + def handle_charref(self, name: str) -> None: ... + def handle_comment(self, data: str) -> None: ... + def handle_decl(self, decl: str) -> None: ... + def handle_pi(self, data: str) -> None: ... + def check_for_whole_start_tag(self, i: int) -> int: ... # undocumented + def clear_cdata_mode(self) -> None: ... # undocumented + def goahead(self, end: bool) -> None: ... # undocumented + def parse_bogus_comment(self, i: int, report: bool = True) -> int: ... # undocumented + def parse_endtag(self, i: int) -> int: ... # undocumented + def parse_html_declaration(self, i: int) -> int: ... # undocumented + def parse_pi(self, i: int) -> int: ... # undocumented + def parse_starttag(self, i: int) -> int: ... # undocumented + # `escapable` parameter added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6 + def set_cdata_mode(self, elem: str, *, escapable: bool = False) -> None: ... # undocumented + rawdata: str # undocumented + cdata_elem: str | None # undocumented + convert_charrefs: bool # undocumented + interesting: Pattern[str] # undocumented + lasttag: str # undocumented diff --git a/stdlib/http/__init__.pyi b/stdlib/http/__init__.pyi new file mode 100644 index 000000000000..f60c3909736d --- /dev/null +++ b/stdlib/http/__init__.pyi @@ -0,0 +1,118 @@ +import sys +from enum import IntEnum + +if sys.version_info >= (3, 11): + from enum import StrEnum + +if sys.version_info >= (3, 11): + __all__ = ["HTTPStatus", "HTTPMethod"] +else: + __all__ = ["HTTPStatus"] + +class HTTPStatus(IntEnum): + @property + def phrase(self) -> str: ... + @property + def description(self) -> str: ... + + # Keep these synced with the global constants in http/client.pyi. + CONTINUE = 100 + SWITCHING_PROTOCOLS = 101 + PROCESSING = 102 + EARLY_HINTS = 103 + + OK = 200 + CREATED = 201 + ACCEPTED = 202 + NON_AUTHORITATIVE_INFORMATION = 203 + NO_CONTENT = 204 + RESET_CONTENT = 205 + PARTIAL_CONTENT = 206 + MULTI_STATUS = 207 + ALREADY_REPORTED = 208 + IM_USED = 226 + + MULTIPLE_CHOICES = 300 + MOVED_PERMANENTLY = 301 + FOUND = 302 + SEE_OTHER = 303 + NOT_MODIFIED = 304 + USE_PROXY = 305 + TEMPORARY_REDIRECT = 307 + PERMANENT_REDIRECT = 308 + + BAD_REQUEST = 400 + UNAUTHORIZED = 401 + PAYMENT_REQUIRED = 402 + FORBIDDEN = 403 + NOT_FOUND = 404 + METHOD_NOT_ALLOWED = 405 + NOT_ACCEPTABLE = 406 + PROXY_AUTHENTICATION_REQUIRED = 407 + REQUEST_TIMEOUT = 408 + CONFLICT = 409 + GONE = 410 + LENGTH_REQUIRED = 411 + PRECONDITION_FAILED = 412 + if sys.version_info >= (3, 13): + CONTENT_TOO_LARGE = 413 + REQUEST_ENTITY_TOO_LARGE = 413 + if sys.version_info >= (3, 13): + URI_TOO_LONG = 414 + REQUEST_URI_TOO_LONG = 414 + UNSUPPORTED_MEDIA_TYPE = 415 + if sys.version_info >= (3, 13): + RANGE_NOT_SATISFIABLE = 416 + REQUESTED_RANGE_NOT_SATISFIABLE = 416 + EXPECTATION_FAILED = 417 + IM_A_TEAPOT = 418 + MISDIRECTED_REQUEST = 421 + if sys.version_info >= (3, 13): + UNPROCESSABLE_CONTENT = 422 + UNPROCESSABLE_ENTITY = 422 + LOCKED = 423 + FAILED_DEPENDENCY = 424 + TOO_EARLY = 425 + UPGRADE_REQUIRED = 426 + PRECONDITION_REQUIRED = 428 + TOO_MANY_REQUESTS = 429 + REQUEST_HEADER_FIELDS_TOO_LARGE = 431 + UNAVAILABLE_FOR_LEGAL_REASONS = 451 + + INTERNAL_SERVER_ERROR = 500 + NOT_IMPLEMENTED = 501 + BAD_GATEWAY = 502 + SERVICE_UNAVAILABLE = 503 + GATEWAY_TIMEOUT = 504 + HTTP_VERSION_NOT_SUPPORTED = 505 + VARIANT_ALSO_NEGOTIATES = 506 + INSUFFICIENT_STORAGE = 507 + LOOP_DETECTED = 508 + NOT_EXTENDED = 510 + NETWORK_AUTHENTICATION_REQUIRED = 511 + + if sys.version_info >= (3, 12): + @property + def is_informational(self) -> bool: ... + @property + def is_success(self) -> bool: ... + @property + def is_redirection(self) -> bool: ... + @property + def is_client_error(self) -> bool: ... + @property + def is_server_error(self) -> bool: ... + +if sys.version_info >= (3, 11): + class HTTPMethod(StrEnum): + @property + def description(self) -> str: ... + CONNECT = "CONNECT" + DELETE = "DELETE" + GET = "GET" + HEAD = "HEAD" + OPTIONS = "OPTIONS" + PATCH = "PATCH" + POST = "POST" + PUT = "PUT" + TRACE = "TRACE" diff --git a/stdlib/http/client.pyi b/stdlib/http/client.pyi new file mode 100644 index 000000000000..d22335b56c54 --- /dev/null +++ b/stdlib/http/client.pyi @@ -0,0 +1,318 @@ +import email.message +import io +import ssl +import sys +import types +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsRead, SupportsReadline, WriteableBuffer +from collections.abc import Callable, Iterable, Iterator, Mapping +from email._policybase import _MessageT +from socket import socket +from typing import BinaryIO, Final, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated + +__all__ = [ + "HTTPResponse", + "HTTPConnection", + "HTTPException", + "NotConnected", + "UnknownProtocol", + "UnknownTransferEncoding", + "UnimplementedFileMode", + "IncompleteRead", + "InvalidURL", + "ImproperConnectionState", + "CannotSendRequest", + "CannotSendHeader", + "ResponseNotReady", + "BadStatusLine", + "LineTooLong", + "RemoteDisconnected", + "error", + "responses", + "HTTPSConnection", +] + +_DataType: TypeAlias = SupportsRead[bytes] | Iterable[ReadableBuffer] | ReadableBuffer +_T = TypeVar("_T") +_HeaderValue: TypeAlias = ReadableBuffer | str | int + +HTTP_PORT: Final = 80 +HTTPS_PORT: Final = 443 + +# Keep these global constants in sync with http.HTTPStatus (http/__init__.pyi). +# They are present for backward compatibility reasons. +CONTINUE: Final = 100 +SWITCHING_PROTOCOLS: Final = 101 +PROCESSING: Final = 102 +EARLY_HINTS: Final = 103 + +OK: Final = 200 +CREATED: Final = 201 +ACCEPTED: Final = 202 +NON_AUTHORITATIVE_INFORMATION: Final = 203 +NO_CONTENT: Final = 204 +RESET_CONTENT: Final = 205 +PARTIAL_CONTENT: Final = 206 +MULTI_STATUS: Final = 207 +ALREADY_REPORTED: Final = 208 +IM_USED: Final = 226 + +MULTIPLE_CHOICES: Final = 300 +MOVED_PERMANENTLY: Final = 301 +FOUND: Final = 302 +SEE_OTHER: Final = 303 +NOT_MODIFIED: Final = 304 +USE_PROXY: Final = 305 +TEMPORARY_REDIRECT: Final = 307 +PERMANENT_REDIRECT: Final = 308 + +BAD_REQUEST: Final = 400 +UNAUTHORIZED: Final = 401 +PAYMENT_REQUIRED: Final = 402 +FORBIDDEN: Final = 403 +NOT_FOUND: Final = 404 +METHOD_NOT_ALLOWED: Final = 405 +NOT_ACCEPTABLE: Final = 406 +PROXY_AUTHENTICATION_REQUIRED: Final = 407 +REQUEST_TIMEOUT: Final = 408 +CONFLICT: Final = 409 +GONE: Final = 410 +LENGTH_REQUIRED: Final = 411 +PRECONDITION_FAILED: Final = 412 +if sys.version_info >= (3, 13): + CONTENT_TOO_LARGE: Final = 413 +REQUEST_ENTITY_TOO_LARGE: Final = 413 +if sys.version_info >= (3, 13): + URI_TOO_LONG: Final = 414 +REQUEST_URI_TOO_LONG: Final = 414 +UNSUPPORTED_MEDIA_TYPE: Final = 415 +if sys.version_info >= (3, 13): + RANGE_NOT_SATISFIABLE: Final = 416 +REQUESTED_RANGE_NOT_SATISFIABLE: Final = 416 +EXPECTATION_FAILED: Final = 417 +IM_A_TEAPOT: Final = 418 +MISDIRECTED_REQUEST: Final = 421 +if sys.version_info >= (3, 13): + UNPROCESSABLE_CONTENT: Final = 422 +UNPROCESSABLE_ENTITY: Final = 422 +LOCKED: Final = 423 +FAILED_DEPENDENCY: Final = 424 +TOO_EARLY: Final = 425 +UPGRADE_REQUIRED: Final = 426 +PRECONDITION_REQUIRED: Final = 428 +TOO_MANY_REQUESTS: Final = 429 +REQUEST_HEADER_FIELDS_TOO_LARGE: Final = 431 +UNAVAILABLE_FOR_LEGAL_REASONS: Final = 451 + +INTERNAL_SERVER_ERROR: Final = 500 +NOT_IMPLEMENTED: Final = 501 +BAD_GATEWAY: Final = 502 +SERVICE_UNAVAILABLE: Final = 503 +GATEWAY_TIMEOUT: Final = 504 +HTTP_VERSION_NOT_SUPPORTED: Final = 505 +VARIANT_ALSO_NEGOTIATES: Final = 506 +INSUFFICIENT_STORAGE: Final = 507 +LOOP_DETECTED: Final = 508 +NOT_EXTENDED: Final = 510 +NETWORK_AUTHENTICATION_REQUIRED: Final = 511 + +responses: dict[int, str] + +class HTTPMessage(email.message.Message[str, str]): + def getallmatchingheaders(self, name: str) -> list[str]: ... # undocumented + +@overload +def parse_headers(fp: SupportsReadline[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ... +@overload +def parse_headers(fp: SupportsReadline[bytes]) -> HTTPMessage: ... + +class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible method definitions in the base classes + msg: HTTPMessage + headers: HTTPMessage + version: int + debuglevel: int + fp: io.BufferedReader + closed: bool + status: int + reason: str + chunked: bool + chunk_left: int | None + length: int | None + will_close: bool + # url is set on instances of the class in urllib.request.AbstractHTTPHandler.do_open + # to match urllib.response.addinfourl's interface. + # It's not set in HTTPResponse.__init__ or any other method on the class + url: str + def __init__(self, sock: socket, debuglevel: int = 0, method: str | None = None, url: str | None = None) -> None: ... + def peek(self, n: int = -1) -> bytes: ... + def read(self, amt: int | None = None) -> bytes: ... + def read1(self, n: int = -1) -> bytes: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] + + @overload + def getheader(self, name: str) -> str | None: ... + @overload + def getheader(self, name: str, default: _T) -> str | _T: ... + + def getheaders(self) -> list[tuple[str, str]]: ... + def isclosed(self) -> bool: ... + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.headers` attribute instead.") + def info(self) -> HTTPMessage: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.url` attribute instead.") + def geturl(self) -> str: ... + @deprecated("Deprecated since Python 3.9. Use `HTTPResponse.status` attribute instead.") + def getcode(self) -> int: ... + def begin(self) -> None: ... + +class HTTPConnection: + blocksize: int + auto_open: int # undocumented + debuglevel: int + default_port: int # undocumented + response_class: type[HTTPResponse] # undocumented + timeout: float | None + host: str + port: int + sock: socket | MaybeNone # can be `None` if `.connect()` was not called + if sys.version_info >= (3, 15): + def __init__( + self, + host: str, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + *, + max_response_headers: int | None = None, + ) -> None: ... + else: + def __init__( + self, + host: str, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + ) -> None: ... + + def request( + self, + method: str, + url: str, + body: _DataType | str | None = None, + headers: Mapping[str, _HeaderValue] = {}, + *, + encode_chunked: bool = False, + ) -> None: ... + def getresponse(self) -> HTTPResponse: ... + def set_debuglevel(self, level: int) -> None: ... + if sys.version_info >= (3, 12): + def get_proxy_response_headers(self) -> HTTPMessage | None: ... + + def set_tunnel(self, host: str, port: int | None = None, headers: Mapping[str, str] | None = None) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def putrequest(self, method: str, url: str, skip_host: bool = False, skip_accept_encoding: bool = False) -> None: ... + def putheader(self, header: str | bytes, *values: _HeaderValue) -> None: ... + def endheaders(self, message_body: _DataType | None = None, *, encode_chunked: bool = False) -> None: ... + def send(self, data: _DataType | str) -> None: ... + +class HTTPSConnection(HTTPConnection): + # Can be `None` if `.connect()` was not called: + sock: ssl.SSLSocket | MaybeNone + if sys.version_info >= (3, 15): + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + max_response_headers: int | None = None, + ) -> None: ... + elif sys.version_info >= (3, 12): + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + ) -> None: ... + else: + @overload + def __init__( + self, + host: str, + port: int | None = None, + key_file: None = None, + cert_file: None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + context: ssl.SSLContext | None = None, + check_hostname: None = None, + blocksize: int = 8192, + ) -> None: ... + @overload + @deprecated( + "The `key_file`, `cert_file`, `check_hostname` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str, + port: int | None = None, + key_file: StrOrBytesPath | None = None, + cert_file: StrOrBytesPath | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + context: ssl.SSLContext | None = None, + check_hostname: bool | None = None, + blocksize: int = 8192, + ) -> None: ... + + key_file: StrOrBytesPath | None + cert_file: StrOrBytesPath | None + +class HTTPException(Exception): ... + +error = HTTPException + +class NotConnected(HTTPException): ... +class InvalidURL(HTTPException): ... + +class UnknownProtocol(HTTPException): + def __init__(self, version: str) -> None: ... + +class UnknownTransferEncoding(HTTPException): ... +class UnimplementedFileMode(HTTPException): ... + +class IncompleteRead(HTTPException): + def __init__(self, partial: bytes, expected: int | None = None) -> None: ... + partial: bytes + expected: int | None + +class ImproperConnectionState(HTTPException): ... +class CannotSendRequest(ImproperConnectionState): ... +class CannotSendHeader(ImproperConnectionState): ... +class ResponseNotReady(ImproperConnectionState): ... + +class BadStatusLine(HTTPException): + def __init__(self, line: str) -> None: ... + +class LineTooLong(HTTPException): + def __init__(self, line_type: str) -> None: ... + +class RemoteDisconnected(ConnectionResetError, BadStatusLine): ... diff --git a/stdlib/http/cookiejar.pyi b/stdlib/http/cookiejar.pyi new file mode 100644 index 000000000000..1bd2fbcbd75d --- /dev/null +++ b/stdlib/http/cookiejar.pyi @@ -0,0 +1,158 @@ +from _typeshed import StrPath +from collections.abc import Iterator, Sequence +from http.client import HTTPResponse +from re import Pattern +from typing import ClassVar, TypeVar, overload +from urllib.request import Request + +__all__ = [ + "Cookie", + "CookieJar", + "CookiePolicy", + "DefaultCookiePolicy", + "FileCookieJar", + "LWPCookieJar", + "LoadError", + "MozillaCookieJar", +] + +_T = TypeVar("_T") + +class LoadError(OSError): ... + +class CookieJar: + non_word_re: ClassVar[Pattern[str]] # undocumented + quote_re: ClassVar[Pattern[str]] # undocumented + strict_domain_re: ClassVar[Pattern[str]] # undocumented + domain_re: ClassVar[Pattern[str]] # undocumented + dots_re: ClassVar[Pattern[str]] # undocumented + magic_re: ClassVar[Pattern[str]] # undocumented + def __init__(self, policy: CookiePolicy | None = None) -> None: ... + def add_cookie_header(self, request: Request) -> None: ... + def extract_cookies(self, response: HTTPResponse, request: Request) -> None: ... + def set_policy(self, policy: CookiePolicy) -> None: ... + def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: ... + def set_cookie(self, cookie: Cookie) -> None: ... + def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ... + def clear(self, domain: str | None = None, path: str | None = None, name: str | None = None) -> None: ... + def clear_session_cookies(self) -> None: ... + def clear_expired_cookies(self) -> None: ... # undocumented + def __iter__(self) -> Iterator[Cookie]: ... + def __len__(self) -> int: ... + +class FileCookieJar(CookieJar): + filename: str | None + delayload: bool + def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: ... + def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... + def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... + def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... + +class MozillaCookieJar(FileCookieJar): ... + +class LWPCookieJar(FileCookieJar): + def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: ... # undocumented + +class CookiePolicy: + netscape: bool + rfc2965: bool + hide_cookie2: bool + def set_ok(self, cookie: Cookie, request: Request) -> bool: ... + def return_ok(self, cookie: Cookie, request: Request) -> bool: ... + def domain_return_ok(self, domain: str, request: Request) -> bool: ... + def path_return_ok(self, path: str, request: Request) -> bool: ... + +class DefaultCookiePolicy(CookiePolicy): + rfc2109_as_netscape: bool + strict_domain: bool + strict_rfc2965_unverifiable: bool + strict_ns_unverifiable: bool + strict_ns_domain: int + strict_ns_set_initial_dollar: bool + strict_ns_set_path: bool + DomainStrictNoDots: ClassVar[int] + DomainStrictNonDomain: ClassVar[int] + DomainRFC2965Match: ClassVar[int] + DomainLiberal: ClassVar[int] + DomainStrict: ClassVar[int] + def __init__( + self, + blocked_domains: Sequence[str] | None = None, + allowed_domains: Sequence[str] | None = None, + netscape: bool = True, + rfc2965: bool = False, + rfc2109_as_netscape: bool | None = None, + hide_cookie2: bool = False, + strict_domain: bool = False, + strict_rfc2965_unverifiable: bool = True, + strict_ns_unverifiable: bool = False, + strict_ns_domain: int = 0, + strict_ns_set_initial_dollar: bool = False, + strict_ns_set_path: bool = False, + secure_protocols: Sequence[str] = ("https", "wss"), + ) -> None: ... + def blocked_domains(self) -> tuple[str, ...]: ... + def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... + def is_blocked(self, domain: str) -> bool: ... + def allowed_domains(self) -> tuple[str, ...] | None: ... + def set_allowed_domains(self, allowed_domains: Sequence[str] | None) -> None: ... + def is_not_allowed(self, domain: str) -> bool: ... + def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_name(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_path(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_domain(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def set_ok_port(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_secure(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_expires(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_port(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + def return_ok_domain(self, cookie: Cookie, request: Request) -> bool: ... # undocumented + +class Cookie: + version: int | None + name: str + value: str | None + port: str | None + path: str + path_specified: bool + secure: bool + expires: int | None + discard: bool + comment: str | None + comment_url: str | None + rfc2109: bool + port_specified: bool + domain: str # undocumented + domain_specified: bool + domain_initial_dot: bool + def __init__( + self, + version: int | str | None, + name: str, + value: str | None, # undocumented + port: str | None, + port_specified: bool, + domain: str, + domain_specified: bool, + domain_initial_dot: bool, + path: str, + path_specified: bool, + secure: bool, + expires: float | str | None, + discard: bool, + comment: str | None, + comment_url: str | None, + rest: dict[str, str], + rfc2109: bool = False, + ) -> None: ... + def has_nonstandard_attr(self, name: str) -> bool: ... + + @overload + def get_nonstandard_attr(self, name: str) -> str | None: ... + @overload + def get_nonstandard_attr(self, name: str, default: _T) -> str | _T: ... + + def set_nonstandard_attr(self, name: str, value: str) -> None: ... + def is_expired(self, now: int | None = None) -> bool: ... diff --git a/stdlib/http/cookies.pyi b/stdlib/http/cookies.pyi new file mode 100644 index 000000000000..bdec1068b5ea --- /dev/null +++ b/stdlib/http/cookies.pyi @@ -0,0 +1,53 @@ +from _typeshed import MaybeNone, SupportsItems, SupportsKeysAndGetItem +from collections.abc import Container, Iterable +from types import GenericAlias +from typing import Any, Generic, TypeVar, overload + +__all__ = ["CookieError", "BaseCookie", "SimpleCookie"] + +_T = TypeVar("_T") + +@overload +def _quote(str: None) -> None: ... +@overload +def _quote(str: str) -> str: ... + +@overload +def _unquote(str: None) -> None: ... +@overload +def _unquote(str: str) -> str: ... + +class CookieError(Exception): ... + +class Morsel(dict[str, Any], Generic[_T]): + @property + def value(self) -> str | MaybeNone: ... + @property + def coded_value(self) -> _T | MaybeNone: ... + @property + def key(self) -> str | MaybeNone: ... + def __init__(self) -> None: ... + def set(self, key: str, val: str, coded_val: _T) -> None: ... + def setdefault(self, key: str, val: str | None = None) -> str: ... + # The dict update can also get a keywords argument so this is incompatible + def update(self, values: Iterable[tuple[str, str]] | SupportsKeysAndGetItem[str, str]) -> None: ... # type: ignore[override] + def isReservedKey(self, K: str) -> bool: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:") -> str: ... + __str__ = output + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def OutputString(self, attrs: Container[str] | None = None) -> str: ... + def __eq__(self, morsel: object) -> bool: ... + def __setitem__(self, K: str, V: Any) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): + def __init__(self, input: str | SupportsItems[str, str | Morsel[Any]] | None = None) -> None: ... + def value_decode(self, val: str) -> tuple[_T, str]: ... + def value_encode(self, val: _T) -> tuple[str, str]: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: ... + __str__ = output + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def load(self, rawdata: str | SupportsItems[str, str | Morsel[Any]]) -> None: ... + def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ... + +class SimpleCookie(BaseCookie[str]): ... diff --git a/stdlib/http/server.pyi b/stdlib/http/server.pyi new file mode 100644 index 000000000000..6bab228f2ce7 --- /dev/null +++ b/stdlib/http/server.pyi @@ -0,0 +1,139 @@ +import _socket +import email.message +import io +import socketserver +import sys +from _ssl import _PasswordType +from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, Sequence +from ssl import Purpose, SSLContext +from typing import Any, AnyStr, BinaryIO, ClassVar, Protocol, type_check_only +from typing_extensions import Self, deprecated + +__all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler"] +if sys.version_info < (3, 15): + __all__ += ["CGIHTTPRequestHandler"] +if sys.version_info >= (3, 14): + __all__ = ["HTTPSServer", "ThreadingHTTPSServer"] + +class HTTPServer(socketserver.TCPServer): + server_name: str + server_port: int + +class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): ... + +if sys.version_info >= (3, 14): + @type_check_only + class _SSLModule(Protocol): + @staticmethod + def create_default_context( + purpose: Purpose = ..., + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, + ) -> SSLContext: ... + + class HTTPSServer(HTTPServer): + ssl: _SSLModule + certfile: StrOrBytesPath + keyfile: StrOrBytesPath | None + password: _PasswordType | None + alpn_protocols: Iterable[str] + def __init__( + self, + server_address: socketserver._AfInetAddress, + RequestHandlerClass: Callable[[Any, _socket._RetAddress, Self], socketserver.BaseRequestHandler], + bind_and_activate: bool = True, + *, + certfile: StrOrBytesPath, + keyfile: StrOrBytesPath | None = None, + password: _PasswordType | None = None, + alpn_protocols: Iterable[str] | None = None, + ) -> None: ... + def server_activate(self) -> None: ... + + class ThreadingHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer): ... + +class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): + client_address: tuple[str, int] + close_connection: bool + requestline: str + command: str + path: str + request_version: str + headers: email.message.Message + server_version: str + sys_version: str + error_message_format: str + error_content_type: str + protocol_version: str + MessageClass: type + responses: Mapping[int, tuple[str, str]] + if sys.version_info >= (3, 15): + default_content_type: str + default_request_version: str # undocumented + weekdayname: ClassVar[Sequence[str]] # undocumented + monthname: ClassVar[Sequence[str | None]] # undocumented + def handle_one_request(self) -> None: ... + def handle_expect_100(self) -> bool: ... + def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: ... + def send_response(self, code: int, message: str | None = None) -> None: ... + def send_header(self, keyword: str, value: str) -> None: ... + def send_response_only(self, code: int, message: str | None = None) -> None: ... + def end_headers(self) -> None: ... + def flush_headers(self) -> None: ... + def log_request(self, code: int | str = "-", size: int | str = "-") -> None: ... + def log_error(self, format: str, *args: Any) -> None: ... + def log_message(self, format: str, *args: Any) -> None: ... + def version_string(self) -> str: ... + def date_time_string(self, timestamp: float | None = None) -> str: ... + def log_date_time_string(self) -> str: ... + def address_string(self) -> str: ... + def parse_request(self) -> bool: ... # undocumented + +class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): + extensions_map: dict[str, str] + if sys.version_info >= (3, 12): + index_pages: ClassVar[tuple[str, ...]] + directory: str + if sys.version_info >= (3, 15): + def __init__( + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + extra_response_headers: Mapping[str, str] | None = None, + ) -> None: ... + else: + def __init__( + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + ) -> None: ... + + def do_GET(self) -> None: ... + def do_HEAD(self) -> None: ... + def send_head(self) -> io.BytesIO | BinaryIO | None: ... # undocumented + def list_directory(self, path: StrPath) -> io.BytesIO | None: ... # undocumented + def translate_path(self, path: str) -> str: ... # undocumented + def copyfile(self, source: SupportsRead[AnyStr], outputfile: SupportsWrite[AnyStr]) -> None: ... # undocumented + def guess_type(self, path: StrPath) -> str: ... # undocumented + +def executable(path: StrPath) -> bool: ... # undocumented + +if sys.version_info < (3, 15): + @deprecated("Deprecated and unsafe; will be removed in Python 3.15.") + class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): + cgi_directories: list[str] + have_fork: bool # undocumented + def do_POST(self) -> None: ... + def is_cgi(self) -> bool: ... # undocumented + def is_executable(self, path: StrPath) -> bool: ... # undocumented + def is_python(self, path: StrPath) -> bool: ... # undocumented + def run_cgi(self) -> None: ... # undocumented diff --git a/stdlib/imaplib.pyi b/stdlib/imaplib.pyi new file mode 100644 index 000000000000..bb58d29099e5 --- /dev/null +++ b/stdlib/imaplib.pyi @@ -0,0 +1,212 @@ +import subprocess +import sys +import time +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, Unused +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Callable, Generator +from datetime import datetime +from re import Pattern +from socket import socket as _socket +from ssl import SSLContext, SSLSocket +from types import TracebackType +from typing import IO, Any, Literal, SupportsAbs, SupportsInt, TypeAlias, overload +from typing_extensions import Self, deprecated + +__all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] + +# TODO: Commands should use their actual return types, not this type alias. +# E.g. Tuple[Literal["OK"], List[bytes]] +_CommandResults: TypeAlias = tuple[str, list[Any]] + +_AnyResponseData: TypeAlias = list[None] | list[bytes | tuple[bytes, bytes]] + +Commands: dict[str, tuple[str, ...]] + +class IMAP4: + class error(Exception): ... + class abort(error): ... + class readonly(abort): ... + utf8_enabled: bool + mustquote: Pattern[str] + debug: int + state: str + literal: str | None + tagged_commands: dict[bytes, _list[bytes] | None] + untagged_responses: dict[str, _list[bytes | tuple[bytes, bytes]]] + continuation_response: str + is_readonly: bool + tagnum: int + tagpre: str + tagre: Pattern[str] + welcome: bytes + capabilities: tuple[str, ...] + PROTOCOL_VERSION: str + def __init__(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... + def open(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[str] | IO[bytes]: ... + else: + file: IO[str] | IO[bytes] + + def __getattr__(self, attr: str) -> Any: ... + host: str + port: int + sock: _socket + def read(self, size: int) -> bytes: ... + def readline(self) -> bytes: ... + def send(self, data: ReadableBuffer) -> None: ... + def shutdown(self) -> None: ... + def socket(self) -> _socket: ... + def recent(self) -> _CommandResults: ... + def response(self, code: str) -> _CommandResults: ... + def append( + self, mailbox: str | None, flags: str | None, date_time: _TimeLike | None, message: ReadableBuffer + ) -> tuple[str, _list[bytes]]: ... + def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: ... + def capability(self) -> _CommandResults: ... + def check(self) -> _CommandResults: ... + def close(self) -> _CommandResults: ... + def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: ... + def create(self, mailbox: str) -> _CommandResults: ... + def delete(self, mailbox: str) -> _CommandResults: ... + def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... + def enable(self, capability: str) -> _CommandResults: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def expunge(self) -> _CommandResults: ... + def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ... + def getacl(self, mailbox: str) -> _CommandResults: ... + def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... + def getquota(self, root: str) -> _CommandResults: ... + def getquotaroot(self, mailbox: str) -> _CommandResults: ... + if sys.version_info >= (3, 14): + def idle(self, duration: float | None = None) -> Idler: ... + + if sys.version_info >= (3, 13): + # Default was fixed in Python 3.13.15, 3.14.7 + def list(self, directory: str = "", pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + else: + def list(self, directory: str = '""', pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + + def login(self, user: str, password: str) -> tuple[Literal["OK"], _list[bytes]]: ... + def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... + def logout(self) -> tuple[str, _AnyResponseData]: ... + + if sys.version_info >= (3, 13): + # Default was fixed in Python 3.13.15, 3.14.7 + def lsub(self, directory: str = "", pattern: str = "*") -> _CommandResults: ... + else: + def lsub(self, directory: str = '""', pattern: str = "*") -> _CommandResults: ... + + def myrights(self, mailbox: str) -> _CommandResults: ... + def namespace(self) -> _CommandResults: ... + def noop(self) -> tuple[str, _list[bytes]]: ... + def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ... + def proxyauth(self, user: str) -> _CommandResults: ... + def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... + def search(self, charset: str | None, *criteria: str) -> _CommandResults: ... + def select(self, mailbox: str = "INBOX", readonly: bool = False) -> tuple[str, _list[bytes | None]]: ... + def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... + + if sys.version_info >= (3, 13): + # Parameter "mailbox" was added in Python 3.13.15, 3.14.7 + def setannotation(self, mailbox: str | bytes, *args: str) -> _CommandResults: ... + else: + def setannotation(self, *args: str) -> _CommandResults: ... + + def setquota(self, root: str, limits: str) -> _CommandResults: ... + def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... + def starttls(self, ssl_context: Any | None = None) -> tuple[Literal["OK"], _list[None]]: ... + def status(self, mailbox: str, names: str) -> _CommandResults: ... + def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ... + def subscribe(self, mailbox: str) -> _CommandResults: ... + def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... + def uid(self, command: str, *args: str) -> _CommandResults: ... + def unsubscribe(self, mailbox: str) -> _CommandResults: ... + def unselect(self) -> _CommandResults: ... + def xatom(self, name: str, *args: str) -> _CommandResults: ... + def print_log(self) -> None: ... + +if sys.version_info >= (3, 14): + class Idler: + def __init__(self, imap: IMAP4, duration: float | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: Unused, exc_tb: Unused) -> Literal[False]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[str, float | None]: ... + def burst(self, interval: float = 0.1) -> Generator[tuple[str, float | None]]: ... + +class IMAP4_SSL(IMAP4): + if sys.version_info >= (3, 12): + def __init__( + self, host: str = "", port: int = 993, *, ssl_context: SSLContext | None = None, timeout: float | None = None + ) -> None: ... + else: + @overload + def __init__( + self, + host: str = "", + port: int = 993, + keyfile: None = None, + certfile: None = None, + ssl_context: SSLContext | None = None, + timeout: float | None = None, + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `ssl_context` parameter instead." + ) + def __init__( + self, + host: str = "", + port: int = 993, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + ssl_context: None = None, + timeout: float | None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + sslobj: SSLSocket + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4_SSL.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[Any]: ... + else: + file: IO[Any] + + def open(self, host: str = "", port: int | None = 993, timeout: float | None = None) -> None: ... + def ssl(self) -> SSLSocket: ... + +class IMAP4_stream(IMAP4): + command: str + def __init__(self, command: str) -> None: ... + if sys.version_info >= (3, 14): + @property + @deprecated("IMAP4_stream.file is unsupported, can cause errors, and may be removed.") + def file(self) -> IO[Any]: ... + else: + file: IO[Any] + process: subprocess.Popen[bytes] + writefile: IO[Any] + readfile: IO[Any] + def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ... + +class _Authenticator: + mech: Callable[[bytes], bytes | bytearray | memoryview | str | None] + def __init__(self, mechinst: Callable[[bytes], bytes | bytearray | memoryview | str | None]) -> None: ... + def process(self, data: str) -> str: ... + def encode(self, inp: bytes | bytearray | memoryview) -> str: ... + def decode(self, inp: str | SizedBuffer) -> bytes: ... + +def Internaldate2tuple(resp: ReadableBuffer) -> time.struct_time | None: ... +def Int2AP(num: SupportsAbs[SupportsInt]) -> bytes: ... +def ParseFlags(resp: ReadableBuffer) -> tuple[bytes, ...]: ... + +_TimeLike: TypeAlias = float | time.struct_time | time._TimeTuple | datetime | str + +def Time2Internaldate(date_time: _TimeLike) -> str: ... diff --git a/stdlib/imghdr.pyi b/stdlib/imghdr.pyi new file mode 100644 index 000000000000..e45ca3eb5bdb --- /dev/null +++ b/stdlib/imghdr.pyi @@ -0,0 +1,18 @@ +from _typeshed import StrPath +from collections.abc import Callable +from typing import Any, BinaryIO, Protocol, overload, type_check_only + +__all__ = ["what"] + +@type_check_only +class _ReadableBinary(Protocol): + def tell(self) -> int: ... + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> Any: ... + +@overload +def what(file: StrPath | _ReadableBinary, h: None = None) -> str | None: ... +@overload +def what(file: Any, h: bytes) -> str | None: ... + +tests: list[Callable[[bytes, BinaryIO | None], str | None]] diff --git a/stdlib/imp.pyi b/stdlib/imp.pyi new file mode 100644 index 000000000000..b5b4223aa58e --- /dev/null +++ b/stdlib/imp.pyi @@ -0,0 +1,63 @@ +import types +from _imp import ( + acquire_lock as acquire_lock, + create_dynamic as create_dynamic, + get_frozen_object as get_frozen_object, + init_frozen as init_frozen, + is_builtin as is_builtin, + is_frozen as is_frozen, + is_frozen_package as is_frozen_package, + lock_held as lock_held, + release_lock as release_lock, +) +from _typeshed import StrPath +from os import PathLike +from types import TracebackType +from typing import IO, Any, Final, Protocol, type_check_only + +SEARCH_ERROR: Final = 0 +PY_SOURCE: Final = 1 +PY_COMPILED: Final = 2 +C_EXTENSION: Final = 3 +PY_RESOURCE: Final = 4 +PKG_DIRECTORY: Final = 5 +C_BUILTIN: Final = 6 +PY_FROZEN: Final = 7 +PY_CODERESOURCE: Final = 8 +IMP_HOOK: Final = 9 + +def new_module(name: str) -> types.ModuleType: ... +def get_magic() -> bytes: ... +def get_tag() -> str: ... +def cache_from_source(path: StrPath, debug_override: bool | None = None) -> str: ... +def source_from_cache(path: StrPath) -> str: ... +def get_suffixes() -> list[tuple[str, str, int]]: ... + +class NullImporter: + def __init__(self, path: StrPath) -> None: ... + def find_module(self, fullname: Any) -> None: ... + +# Technically, a text file has to support a slightly different set of operations than a binary file, +# but we ignore that here. +@type_check_only +class _FileLike(Protocol): + closed: bool + mode: str + def read(self) -> str | bytes: ... + def close(self) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, /) -> Any: ... + +# PathLike doesn't work for the pathname argument here +def load_source(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... +def load_compiled(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ... +def load_package(name: str, path: StrPath) -> types.ModuleType: ... +def load_module(name: str, file: _FileLike | None, filename: str, details: tuple[str, str, int]) -> types.ModuleType: ... + +# IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise. +def find_module( + name: str, path: None | list[str] | list[PathLike[str]] | list[StrPath] = None +) -> tuple[IO[Any], str, tuple[str, str, int]]: ... +def reload(module: types.ModuleType) -> types.ModuleType: ... +def init_builtin(name: str) -> types.ModuleType | None: ... +def load_dynamic(name: str, path: str, file: Any = None) -> types.ModuleType: ... # file argument is ignored diff --git a/stdlib/importlib/__init__.pyi b/stdlib/importlib/__init__.pyi new file mode 100644 index 000000000000..d60f90adee19 --- /dev/null +++ b/stdlib/importlib/__init__.pyi @@ -0,0 +1,17 @@ +import sys +from importlib._bootstrap import __import__ as __import__ +from importlib.abc import Loader +from types import ModuleType +from typing_extensions import deprecated + +__all__ = ["__import__", "import_module", "invalidate_caches", "reload"] + +# `importlib.import_module` return type should be kept the same as `builtins.__import__` +def import_module(name: str, package: str | None = None) -> ModuleType: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `importlib.util.find_spec()` instead.") + def find_loader(name: str, path: str | None = None) -> Loader | None: ... + +def invalidate_caches() -> None: ... +def reload(module: ModuleType) -> ModuleType: ... diff --git a/stdlib/importlib/_abc.pyi b/stdlib/importlib/_abc.pyi new file mode 100644 index 000000000000..e8c80c0447ae --- /dev/null +++ b/stdlib/importlib/_abc.pyi @@ -0,0 +1,19 @@ +import sys +import types +from abc import ABCMeta +from importlib.machinery import ModuleSpec +from typing_extensions import deprecated + +class Loader(metaclass=ABCMeta): + def load_module(self, fullname: str) -> types.ModuleType: ... + if sys.version_info < (3, 12): + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(self, module: types.ModuleType) -> str: ... + + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... + # Not defined on the actual class for backwards-compatibility reasons, + # but expected in new code. + def exec_module(self, module: types.ModuleType) -> None: ... diff --git a/stdlib/importlib/_bootstrap.pyi b/stdlib/importlib/_bootstrap.pyi new file mode 100644 index 000000000000..02427ff42062 --- /dev/null +++ b/stdlib/importlib/_bootstrap.pyi @@ -0,0 +1,2 @@ +from _frozen_importlib import * +from _frozen_importlib import __import__ as __import__, _init_module_attrs as _init_module_attrs diff --git a/stdlib/importlib/_bootstrap_external.pyi b/stdlib/importlib/_bootstrap_external.pyi new file mode 100644 index 000000000000..6210ce7083af --- /dev/null +++ b/stdlib/importlib/_bootstrap_external.pyi @@ -0,0 +1,2 @@ +from _frozen_importlib_external import * +from _frozen_importlib_external import _NamespaceLoader as _NamespaceLoader diff --git a/stdlib/importlib/abc.pyi b/stdlib/importlib/abc.pyi new file mode 100644 index 000000000000..945b8d2080d1 --- /dev/null +++ b/stdlib/importlib/abc.pyi @@ -0,0 +1,150 @@ +import _ast +import sys +import types +from _typeshed import ReadableBuffer, StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import Iterator, Mapping, Sequence +from importlib import _bootstrap_external +from importlib._abc import Loader as Loader +from importlib.machinery import ModuleSpec +from io import BufferedReader +from typing import IO, Any, Literal, Protocol, overload, runtime_checkable +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + __all__ = [ + "Loader", + "MetaPathFinder", + "PathEntryFinder", + "ResourceLoader", + "InspectLoader", + "ExecutionLoader", + "FileLoader", + "SourceLoader", + ] + + if sys.version_info < (3, 12): + __all__ += ["Finder", "ResourceReader", "Traversable", "TraversableResources"] + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use `MetaPathFinder` or `PathEntryFinder` instead.") + class Finder(metaclass=ABCMeta): ... + +@deprecated("Deprecated since Python 3.7. Use `importlib.resources.abc.TraversableResources` instead.") +class ResourceLoader(Loader): + @abstractmethod + def get_data(self, path: str) -> bytes: ... + +class InspectLoader(Loader): + def is_package(self, fullname: str) -> bool: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + @abstractmethod + def get_source(self, fullname: str) -> str | None: ... + def exec_module(self, module: types.ModuleType) -> None: ... + @staticmethod + def source_to_code( + data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: bytes | StrPath = "" + ) -> types.CodeType: ... + +class ExecutionLoader(InspectLoader): + @abstractmethod + def get_filename(self, fullname: str) -> str: ... + +class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): # type: ignore[misc] # incompatible definitions of source_to_code in the base classes + @deprecated("Deprecated since Python 3.3. Use `importlib.resources.abc.SourceLoader.path_stats` instead.") + def path_mtime(self, path: str) -> float: ... + def set_data(self, path: str, data: bytes) -> None: ... + def get_source(self, fullname: str) -> str | None: ... + def path_stats(self, path: str) -> Mapping[str, Any]: ... + +# Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol +class MetaPathFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `MetaPathFinder.find_spec()` instead.") + def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... + + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / + ) -> ModuleSpec | None: ... + +class PathEntryFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `PathEntryFinder.find_spec()` instead.") + def find_module(self, fullname: str) -> Loader | None: ... + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") + def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... + + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... + +class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): + name: str + path: str + def __init__(self, fullname: str, path: str) -> None: ... + def get_data(self, path: str) -> bytes: ... + def get_filename(self, fullname: str | None = None) -> str: ... + def load_module(self, fullname: str | None = None) -> types.ModuleType: ... + +if sys.version_info < (3, 11): + class ResourceReader(metaclass=ABCMeta): + @abstractmethod + def open_resource(self, resource: str) -> IO[bytes]: ... + @abstractmethod + def resource_path(self, resource: str) -> str: ... + @abstractmethod + def is_resource(self, path: str) -> bool: ... + @abstractmethod + def contents(self) -> Iterator[str]: ... + + @runtime_checkable + class Traversable(Protocol): + @abstractmethod + def is_dir(self) -> bool: ... + @abstractmethod + def is_file(self) -> bool: ... + @abstractmethod + def iterdir(self) -> Iterator[Traversable]: ... + + if sys.version_info >= (3, 11): + @abstractmethod + def joinpath(self, *descendants: str) -> Traversable: ... + else: + @abstractmethod + def joinpath(self, child: str, /) -> Traversable: ... + + # The documentation and runtime protocol allows *args, **kwargs arguments, + # but this would mean that all implementers would have to support them, + # which is not the case. + @overload + @abstractmethod + def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... + @overload + @abstractmethod + def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + + @property + @abstractmethod + def name(self) -> str: ... + def __truediv__(self, child: str, /) -> Traversable: ... + @abstractmethod + def read_bytes(self) -> bytes: ... + @abstractmethod + def read_text(self, encoding: str | None = None) -> str: ... + + class TraversableResources(ResourceReader): + @abstractmethod + def files(self) -> Traversable: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def resource_path(self, resource: Any) -> str: ... + def is_resource(self, path: str) -> bool: ... + def contents(self) -> Iterator[str]: ... + +elif sys.version_info < (3, 14): + from importlib.resources.abc import ( + ResourceReader as ResourceReader, + Traversable as Traversable, + TraversableResources as TraversableResources, + ) diff --git a/stdlib/importlib/machinery.pyi b/stdlib/importlib/machinery.pyi new file mode 100644 index 000000000000..767046b70a3d --- /dev/null +++ b/stdlib/importlib/machinery.pyi @@ -0,0 +1,43 @@ +import sys +from importlib._bootstrap import BuiltinImporter as BuiltinImporter, FrozenImporter as FrozenImporter, ModuleSpec as ModuleSpec +from importlib._bootstrap_external import ( + BYTECODE_SUFFIXES as BYTECODE_SUFFIXES, + DEBUG_BYTECODE_SUFFIXES as DEBUG_BYTECODE_SUFFIXES, + EXTENSION_SUFFIXES as EXTENSION_SUFFIXES, + OPTIMIZED_BYTECODE_SUFFIXES as OPTIMIZED_BYTECODE_SUFFIXES, + SOURCE_SUFFIXES as SOURCE_SUFFIXES, + ExtensionFileLoader as ExtensionFileLoader, + FileFinder as FileFinder, + PathFinder as PathFinder, + SourceFileLoader as SourceFileLoader, + SourcelessFileLoader as SourcelessFileLoader, + WindowsRegistryFinder as WindowsRegistryFinder, +) + +if sys.version_info >= (3, 11): + from importlib._bootstrap_external import NamespaceLoader as NamespaceLoader +if sys.version_info >= (3, 14): + from importlib._bootstrap_external import AppleFrameworkLoader as AppleFrameworkLoader + +def all_suffixes() -> list[str]: ... + +if sys.version_info >= (3, 14): + __all__ = [ + "AppleFrameworkLoader", + "BYTECODE_SUFFIXES", + "BuiltinImporter", + "DEBUG_BYTECODE_SUFFIXES", + "EXTENSION_SUFFIXES", + "ExtensionFileLoader", + "FileFinder", + "FrozenImporter", + "ModuleSpec", + "NamespaceLoader", + "OPTIMIZED_BYTECODE_SUFFIXES", + "PathFinder", + "SOURCE_SUFFIXES", + "SourceFileLoader", + "SourcelessFileLoader", + "WindowsRegistryFinder", + "all_suffixes", + ] diff --git a/stdlib/importlib/metadata/__init__.pyi b/stdlib/importlib/metadata/__init__.pyi new file mode 100644 index 000000000000..866fd969e2fe --- /dev/null +++ b/stdlib/importlib/metadata/__init__.pyi @@ -0,0 +1,310 @@ +import abc +import pathlib +import sys +import types +from _collections_abc import dict_keys, dict_values +from _typeshed import StrPath +from collections.abc import Iterable, Iterator, Mapping +from importlib.abc import MetaPathFinder +from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath +from os import PathLike +from re import Pattern +from typing import Any, ClassVar, Generic, NamedTuple, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +__all__ = [ + "Distribution", + "DistributionFinder", + "PackageMetadata", + "PackageNotFoundError", + "distribution", + "distributions", + "entry_points", + "files", + "metadata", + "packages_distributions", + "requires", + "version", +] + +if sys.version_info >= (3, 15): + __all__ += ["PackagePath", "MetadataNotFound", "SimplePath"] + +_SimplePath: TypeAlias = SimplePath + +def packages_distributions() -> Mapping[str, list[str]]: ... + +class PackageNotFoundError(ModuleNotFoundError): + @property + def name(self) -> str: ... # type: ignore[override] + +if sys.version_info >= (3, 15): + class MetadataNotFound(FileNotFoundError): ... + +if sys.version_info >= (3, 13): + _EntryPointBase = object +elif sys.version_info >= (3, 11): + class DeprecatedTuple: + def __getitem__(self, item: int) -> str: ... + + _EntryPointBase = DeprecatedTuple +else: + @type_check_only + class _EntryPointBase(NamedTuple): + name: str + value: str + group: str + +if sys.version_info >= (3, 11): + class EntryPoint(_EntryPointBase): + pattern: ClassVar[Pattern[str]] + name: str + value: str + group: str + + def __init__(self, name: str, value: str, group: str) -> None: ... + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> list[str]: ... + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + if sys.version_info < (3, 12): + def __iter__(self) -> Iterator[Any]: ... # result of iter((str, Self)), really + +else: + @disjoint_base + class EntryPoint(_EntryPointBase): + pattern: ClassVar[Pattern[str]] + + def load(self) -> Any: ... # Callable[[], Any] or an importable module + @property + def extras(self) -> list[str]: ... + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... # result of iter((str, Self)), really + +if sys.version_info >= (3, 12): + class EntryPoints(tuple[EntryPoint, ...]): + __slots__ = () + def __getitem__(self, name: str) -> EntryPoint: ... # type: ignore[override] + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + @property + def names(self) -> set[str]: ... + @property + def groups(self) -> set[str]: ... + +else: + class DeprecatedList(list[_T]): + __slots__ = () + + class EntryPoints(DeprecatedList[EntryPoint]): # use as list is deprecated since 3.10 + # int argument is deprecated since 3.10 + __slots__ = () + def __getitem__(self, name: int | str) -> EntryPoint: ... # type: ignore[override] + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + @property + def names(self) -> set[str]: ... + @property + def groups(self) -> set[str]: ... + +if sys.version_info < (3, 12): + class Deprecated(Generic[_KT, _VT]): + def __getitem__(self, name: _KT) -> _VT: ... + + @overload + def get(self, name: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, name: _KT, default: _VT) -> _VT: ... + @overload + def get(self, name: _KT, default: _T) -> _VT | _T: ... + + def __iter__(self) -> Iterator[_KT]: ... + def __contains__(self, *args: object) -> bool: ... + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `select` instead.") + class SelectableGroups(Deprecated[str, EntryPoints], dict[str, EntryPoints]): # use as dict is deprecated since 3.10 + @classmethod + def load(cls, eps: Iterable[EntryPoint]) -> Self: ... + @property + def groups(self) -> set[str]: ... + @property + def names(self) -> set[str]: ... + + @overload + def select(self) -> Self: ... + @overload + def select( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> EntryPoints: ... + +class PackagePath(pathlib.PurePosixPath): + def read_text(self, encoding: str = "utf-8") -> str: ... + def read_binary(self) -> bytes: ... + def locate(self) -> PathLike[str]: ... + # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files: + hash: FileHash | None + size: int | None + dist: Distribution + +class FileHash: + mode: str + value: str + def __init__(self, spec: str) -> None: ... + +if sys.version_info >= (3, 15): + _distribution_parent = abc.ABC +elif sys.version_info >= (3, 12): + class DeprecatedNonAbstract: ... + _distribution_parent = DeprecatedNonAbstract +else: + _distribution_parent = object + +class Distribution(_distribution_parent): + @abc.abstractmethod + def read_text(self, filename: str) -> str | None: ... + @abc.abstractmethod + def locate_file(self, path: StrPath) -> _SimplePath: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + + @overload + @classmethod + def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... + @overload + @classmethod + def discover( + cls, *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any + ) -> Iterable[Distribution]: ... + + @staticmethod + def at(path: StrPath) -> PathDistribution: ... + @property + def metadata(self) -> PackageMetadata: ... + @property + def entry_points(self) -> EntryPoints: ... + @property + def version(self) -> str: ... + @property + def files(self) -> list[PackagePath] | None: ... + @property + def requires(self) -> list[str] | None: ... + @property + def name(self) -> str: ... + if sys.version_info >= (3, 13): + @property + def origin(self) -> types.SimpleNamespace | None: ... + +class DistributionFinder(MetaPathFinder): + class Context: + name: str | None + def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ... + @property + def path(self) -> list[str]: ... + + @abc.abstractmethod + def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... + +class MetadataPathFinder(DistributionFinder): + @classmethod + def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + if sys.version_info >= (3, 11): + @classmethod + def invalidate_caches(cls) -> None: ... + else: + # Yes, this is an instance method that has a parameter named "cls" + def invalidate_caches(cls) -> None: ... + +class PathDistribution(Distribution): + _path: _SimplePath + def __init__(self, path: _SimplePath) -> None: ... + def read_text(self, filename: StrPath) -> str | None: ... + def locate_file(self, path: StrPath) -> _SimplePath: ... + +def distribution(distribution_name: str) -> Distribution: ... + +@overload +def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... +@overload +def distributions( + *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any +) -> Iterable[Distribution]: ... + +def metadata(distribution_name: str) -> PackageMetadata: ... + +if sys.version_info >= (3, 12): + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +else: + @overload + def entry_points() -> SelectableGroups: ... + @overload + def entry_points( + *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... + ) -> EntryPoints: ... + +def version(distribution_name: str) -> str: ... +def files(distribution_name: str) -> list[PackagePath] | None: ... +def requires(distribution_name: str) -> list[str] | None: ... diff --git a/stdlib/importlib/metadata/_meta.pyi b/stdlib/importlib/metadata/_meta.pyi new file mode 100644 index 000000000000..b9bad7b8a6b0 --- /dev/null +++ b/stdlib/importlib/metadata/_meta.pyi @@ -0,0 +1,65 @@ +import sys +from _typeshed import StrPath +from collections.abc import Iterator +from os import PathLike +from typing import Any, Protocol, overload +from typing_extensions import TypeVar + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True, default=Any) + +class PackageMetadata(Protocol): + def __len__(self) -> int: ... + def __contains__(self, item: str) -> bool: ... + def __getitem__(self, key: str) -> str: ... + def __iter__(self) -> Iterator[str]: ... + @property + def json(self) -> dict[str, str | list[str]]: ... + + @overload + def get_all(self, name: str, failobj: None = None) -> list[Any] | None: ... + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ... + + if sys.version_info >= (3, 12): + @overload + def get(self, name: str, failobj: None = None) -> str | None: ... + @overload + def get(self, name: str, failobj: _T) -> _T | str: ... + +if sys.version_info >= (3, 13): + class SimplePath(Protocol): + def joinpath(self, other: StrPath, /) -> SimplePath: ... + def __truediv__(self, other: StrPath, /) -> SimplePath: ... + # Incorrect at runtime + @property + def parent(self) -> PathLike[str]: ... + def read_text(self, encoding: str | None = None) -> str: ... + def read_bytes(self) -> bytes: ... + def exists(self) -> bool: ... + +elif sys.version_info >= (3, 12): + class SimplePath(Protocol[_T_co]): + # At runtime this is defined as taking `str | _T`, but that causes trouble. + # See #11436. + def joinpath(self, other: str, /) -> _T_co: ... + @property + def parent(self) -> _T_co: ... + def read_text(self) -> str: ... + # As with joinpath(), this is annotated as taking `str | _T` at runtime. + def __truediv__(self, other: str, /) -> _T_co: ... + +else: + class SimplePath(Protocol): + # Actually takes only self at runtime, but that's clearly wrong + def joinpath(self, other: Any, /) -> SimplePath: ... + # Not defined as a property at runtime, but it should be + @property + def parent(self) -> Any: ... + def read_text(self) -> str: ... + # There was a bug in `SimplePath` definition in cpython, see #8451 + # Strictly speaking `__div__` was defined in 3.10, not __truediv__, + # but it should have always been `__truediv__`. + # Also, the runtime defines this method as taking no arguments, + # which is obviously wrong. + def __truediv__(self, other: Any, /) -> SimplePath: ... diff --git a/stdlib/importlib/metadata/diagnose.pyi b/stdlib/importlib/metadata/diagnose.pyi new file mode 100644 index 000000000000..565872fd976f --- /dev/null +++ b/stdlib/importlib/metadata/diagnose.pyi @@ -0,0 +1,2 @@ +def inspect(path: str) -> None: ... +def run() -> None: ... diff --git a/stdlib/importlib/readers.pyi b/stdlib/importlib/readers.pyi new file mode 100644 index 000000000000..c02f29d0a722 --- /dev/null +++ b/stdlib/importlib/readers.pyi @@ -0,0 +1,69 @@ +# On py311+, things are actually defined in importlib.resources.readers, +# and re-exported here, +# but doing it this way leads to less code duplication for us + +import pathlib +import sys +import zipfile +from _typeshed import StrPath +from collections.abc import Iterable, Iterator +from importlib._bootstrap_external import FileLoader +from io import BufferedReader +from typing import Literal, TypeVar +from typing_extensions import Never +from zipimport import zipimporter + +if sys.version_info >= (3, 11): + from importlib.resources import abc +else: + from importlib import abc + +if sys.version_info >= (3, 11): + __all__ = ["FileReader", "ZipReader", "MultiplexedPath", "NamespaceReader"] + +if sys.version_info < (3, 11): + _T = TypeVar("_T") + + def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... + +class FileReader(abc.TraversableResources): + path: pathlib.Path + def __init__(self, loader: FileLoader) -> None: ... + def resource_path(self, resource: StrPath) -> str: ... + def files(self) -> pathlib.Path: ... + +class ZipReader(abc.TraversableResources): + prefix: str + archive: str + def __init__(self, loader: zipimporter, module: str) -> None: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def is_resource(self, path: StrPath) -> bool: ... + def files(self) -> zipfile.Path: ... + +class MultiplexedPath(abc.Traversable): + def __init__(self, *paths: abc.Traversable) -> None: ... + def iterdir(self) -> Iterator[abc.Traversable]: ... + def read_bytes(self) -> Never: ... + def read_text(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def is_dir(self) -> Literal[True]: ... + def is_file(self) -> Literal[False]: ... + + if sys.version_info >= (3, 12): + def joinpath(self, *descendants: StrPath) -> abc.Traversable: ... + elif sys.version_info >= (3, 11): + def joinpath(self, child: StrPath) -> abc.Traversable: ... # type: ignore[override] + else: + def joinpath(self, child: str) -> abc.Traversable: ... + + if sys.version_info < (3, 12): + __truediv__ = joinpath + + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + @property + def name(self) -> str: ... + +class NamespaceReader(abc.TraversableResources): + path: MultiplexedPath + def __init__(self, namespace_path: Iterable[str]) -> None: ... + def resource_path(self, resource: str) -> str: ... + def files(self) -> MultiplexedPath: ... diff --git a/stdlib/importlib/resources/__init__.pyi b/stdlib/importlib/resources/__init__.pyi new file mode 100644 index 000000000000..4d3072ffe854 --- /dev/null +++ b/stdlib/importlib/resources/__init__.pyi @@ -0,0 +1,81 @@ +import os +import sys +from collections.abc import Iterator +from contextlib import AbstractContextManager +from pathlib import Path +from types import ModuleType +from typing import Any, BinaryIO, Literal, TextIO, TypeAlias +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + +if sys.version_info >= (3, 11): + from importlib.resources._common import Package as Package +else: + Package: TypeAlias = str | ModuleType + +__all__ = [ + "Package", + "ResourceReader", + "as_file", + "contents", + "files", + "is_resource", + "open_binary", + "open_text", + "path", + "read_binary", + "read_text", +] + +if sys.version_info < (3, 13): + __all__ += ["Resource"] + +if sys.version_info < (3, 11): + Resource: TypeAlias = str | os.PathLike[Any] +elif sys.version_info < (3, 13): + Resource: TypeAlias = str + +if sys.version_info >= (3, 12): + from importlib.resources._common import Anchor as Anchor + + __all__ += ["Anchor"] + +if sys.version_info >= (3, 13): + from importlib.resources._functional import ( + contents as contents, + is_resource as is_resource, + open_binary as open_binary, + open_text as open_text, + path as path, + read_binary as read_binary, + read_text as read_text, + ) + +else: + def open_binary(package: Package, resource: Resource) -> BinaryIO: ... + def open_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> TextIO: ... + def read_binary(package: Package, resource: Resource) -> bytes: ... + def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: ... + def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ... + def is_resource(package: Package, name: str) -> bool: ... + @deprecated("Deprecated; limited resource support. Use `files(anchor).iterdir()`.") + def contents(package: Package) -> Iterator[str]: ... + +if sys.version_info >= (3, 11): + from importlib.resources._common import as_file as as_file +else: + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... + +if sys.version_info >= (3, 11): + from importlib.resources._common import files as files +else: + def files(package: Package) -> Traversable: ... + +if sys.version_info >= (3, 11): + from importlib.resources.abc import ResourceReader as ResourceReader +else: + from importlib.abc import ResourceReader as ResourceReader diff --git a/stdlib/importlib/resources/_common.pyi b/stdlib/importlib/resources/_common.pyi new file mode 100644 index 000000000000..447cc1ea33b8 --- /dev/null +++ b/stdlib/importlib/resources/_common.pyi @@ -0,0 +1,43 @@ +import sys + +# Even though this file is 3.11+ only, Pyright will complain in stubtest for older versions. +if sys.version_info >= (3, 11): + import types + from collections.abc import Callable + from contextlib import AbstractContextManager + from importlib.resources.abc import ResourceReader, Traversable + from pathlib import Path + from typing import Literal, TypeAlias, overload + from typing_extensions import deprecated + + Package: TypeAlias = str | types.ModuleType + + if sys.version_info >= (3, 12): + Anchor: TypeAlias = Package + + def package_to_anchor( + func: Callable[[Anchor | None], Traversable], + ) -> Callable[[Anchor | None, Anchor | None], Traversable]: ... + + @overload + def files(anchor: Anchor | None = None) -> Traversable: ... + @overload + @deprecated("Deprecated since Python 3.12; will be removed in Python 3.15. Use `anchor` parameter instead.") + def files(package: Anchor | None = None) -> Traversable: ... + + else: + def files(package: Package) -> Traversable: ... + + def get_resource_reader(package: types.ModuleType) -> ResourceReader | None: ... + + if sys.version_info >= (3, 12): + def resolve(cand: Anchor | None) -> types.ModuleType: ... + + else: + def resolve(cand: Package) -> types.ModuleType: ... + + if sys.version_info < (3, 12): + def get_package(package: Package) -> types.ModuleType: ... + + def from_package(package: types.ModuleType) -> Traversable: ... + def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... diff --git a/stdlib/importlib/resources/_functional.pyi b/stdlib/importlib/resources/_functional.pyi new file mode 100644 index 000000000000..cfd15dc87ce8 --- /dev/null +++ b/stdlib/importlib/resources/_functional.pyi @@ -0,0 +1,35 @@ +import sys + +# Even though this file is 3.13+ only, Pyright will complain in stubtest for older versions. +if sys.version_info >= (3, 13): + from _typeshed import StrPath + from collections.abc import Iterator + from contextlib import AbstractContextManager + from importlib.resources._common import Anchor + from io import TextIOWrapper + from pathlib import Path + from typing import BinaryIO, Literal, overload + from typing_extensions import Unpack, deprecated + + def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: ... + + @overload + def open_text( + anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" + ) -> TextIOWrapper: ... + @overload + def open_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> TextIOWrapper: ... + + def read_binary(anchor: Anchor, *path_names: StrPath) -> bytes: ... + + @overload + def read_text( + anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" + ) -> str: ... + @overload + def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> str: ... + + def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: ... + def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ... + @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") + def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: ... diff --git a/stdlib/importlib/resources/abc.pyi b/stdlib/importlib/resources/abc.pyi new file mode 100644 index 000000000000..fd604997ff4a --- /dev/null +++ b/stdlib/importlib/resources/abc.pyi @@ -0,0 +1,64 @@ +import sys +from _typeshed import StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import Iterator +from io import BufferedReader +from typing import IO, Any, Literal, Protocol, overload, runtime_checkable +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + @deprecated("Deprecated. Use `importlib.resources.abc.TraversableResources` instead.") + class ResourceReader(metaclass=ABCMeta): + @abstractmethod + def open_resource(self, resource: str) -> IO[bytes]: ... + @abstractmethod + def resource_path(self, resource: str) -> str: ... + @abstractmethod + def is_resource(self, path: str) -> bool: ... + @abstractmethod + def contents(self) -> Iterator[str]: ... + + @runtime_checkable + class Traversable(Protocol): + @abstractmethod + def is_dir(self) -> bool: ... + @abstractmethod + def is_file(self) -> bool: ... + @abstractmethod + def iterdir(self) -> Iterator[Traversable]: ... + @abstractmethod + def joinpath(self, *descendants: StrPath) -> Traversable: ... + + # The documentation and runtime protocol allows *args, **kwargs arguments, + # but this would mean that all implementers would have to support them, + # which is not the case. + @overload + @abstractmethod + def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... + @overload + @abstractmethod + def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + + @property + @abstractmethod + def name(self) -> str: ... + def __truediv__(self, child: StrPath, /) -> Traversable: ... + @abstractmethod + def read_bytes(self) -> bytes: ... + + if sys.version_info >= (3, 15): + @abstractmethod + def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ... + else: + @abstractmethod + def read_text(self, encoding: str | None = None) -> str: ... + + class TraversableResources(ResourceReader): + @abstractmethod + def files(self) -> Traversable: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def resource_path(self, resource: Any) -> str: ... + def is_resource(self, path: str) -> bool: ... + def contents(self) -> Iterator[str]: ... + + __all__ = ["ResourceReader", "Traversable", "TraversableResources"] diff --git a/stdlib/importlib/resources/readers.pyi b/stdlib/importlib/resources/readers.pyi new file mode 100644 index 000000000000..0ab21fd29114 --- /dev/null +++ b/stdlib/importlib/resources/readers.pyi @@ -0,0 +1,14 @@ +# On py311+, things are actually defined here +# and re-exported from importlib.readers, +# but doing it this way leads to less code duplication for us + +import sys +from collections.abc import Iterable, Iterator +from typing import TypeVar + +if sys.version_info >= (3, 11): + from importlib.readers import * + + _T = TypeVar("_T") + + def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... diff --git a/stdlib/importlib/resources/simple.pyi b/stdlib/importlib/resources/simple.pyi new file mode 100644 index 000000000000..933a6ff164df --- /dev/null +++ b/stdlib/importlib/resources/simple.pyi @@ -0,0 +1,59 @@ +import abc +import sys +from _typeshed import StrPath +from collections.abc import Iterator +from io import TextIOWrapper +from typing import IO, Any, BinaryIO, Literal, overload +from typing_extensions import Never + +if sys.version_info >= (3, 11): + from .abc import Traversable, TraversableResources + + class SimpleReader(abc.ABC): + @property + @abc.abstractmethod + def package(self) -> str: ... + @abc.abstractmethod + def children(self) -> list[SimpleReader]: ... + @abc.abstractmethod + def resources(self) -> list[str]: ... + @abc.abstractmethod + def open_binary(self, resource: str) -> BinaryIO: ... + @property + def name(self) -> str: ... + + class ResourceHandle(Traversable, metaclass=abc.ABCMeta): + parent: ResourceContainer + def __init__(self, parent: ResourceContainer, name: str) -> None: ... + def is_file(self) -> Literal[True]: ... + def is_dir(self) -> Literal[False]: ... + + @overload + def open( + self, + mode: Literal["r"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb"]) -> BinaryIO: ... + @overload + def open(self, mode: str) -> IO[Any]: ... + + def joinpath(self, name: Never) -> Never: ... # type: ignore[override] + + class ResourceContainer(Traversable, metaclass=abc.ABCMeta): + reader: SimpleReader + def __init__(self, reader: SimpleReader) -> None: ... + def is_dir(self) -> Literal[True]: ... + def is_file(self) -> Literal[False]: ... + def iterdir(self) -> Iterator[ResourceHandle | ResourceContainer]: ... + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + if sys.version_info < (3, 12): + def joinpath(self, *descendants: StrPath) -> Traversable: ... + + class TraversableReader(TraversableResources, SimpleReader, metaclass=abc.ABCMeta): + def files(self) -> ResourceContainer: ... diff --git a/stdlib/importlib/simple.pyi b/stdlib/importlib/simple.pyi new file mode 100644 index 000000000000..58d8c6617082 --- /dev/null +++ b/stdlib/importlib/simple.pyi @@ -0,0 +1,11 @@ +import sys + +if sys.version_info >= (3, 11): + from .resources.simple import ( + ResourceContainer as ResourceContainer, + ResourceHandle as ResourceHandle, + SimpleReader as SimpleReader, + TraversableReader as TraversableReader, + ) + + __all__ = ["SimpleReader", "ResourceHandle", "ResourceContainer", "TraversableReader"] diff --git a/stdlib/importlib/util.pyi b/stdlib/importlib/util.pyi new file mode 100644 index 000000000000..785ba6b9a08f --- /dev/null +++ b/stdlib/importlib/util.pyi @@ -0,0 +1,75 @@ +import importlib.machinery +import sys +import types +from _typeshed import ReadableBuffer +from collections.abc import Callable +from importlib._bootstrap import module_from_spec as module_from_spec, spec_from_loader as spec_from_loader +from importlib._bootstrap_external import ( + MAGIC_NUMBER as MAGIC_NUMBER, + cache_from_source as cache_from_source, + decode_source as decode_source, + source_from_cache as source_from_cache, + spec_from_file_location as spec_from_file_location, +) +from importlib.abc import Loader +from types import TracebackType +from typing import Literal, ParamSpec +from typing_extensions import Self, deprecated + +_P = ParamSpec("_P") + +if sys.version_info < (3, 12): + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "`__name__`, `__package__` and `__loader__` are now set automatically." + ) + def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... + +def resolve_name(name: str, package: str | None) -> str: ... +def find_spec(name: str, package: str | None = None) -> importlib.machinery.ModuleSpec | None: ... + +class LazyLoader(Loader): + def __init__(self, loader: Loader) -> None: ... + @classmethod + def factory(cls, loader: Loader) -> Callable[..., LazyLoader]: ... + def exec_module(self, module: types.ModuleType) -> None: ... + +def source_hash(source_bytes: ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 12): + class _incompatible_extension_module_restrictions: + def __init__(self, *, disable_check: bool) -> None: ... + disable_check: bool + old: Literal[-1, 0, 1] # exists only while entered + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @property + def override(self) -> Literal[-1, 1]: ... # undocumented + +if sys.version_info >= (3, 14): + __all__ = [ + "LazyLoader", + "Loader", + "MAGIC_NUMBER", + "cache_from_source", + "decode_source", + "find_spec", + "module_from_spec", + "resolve_name", + "source_from_cache", + "source_hash", + "spec_from_file_location", + "spec_from_loader", + ] diff --git a/stdlib/inspect.pyi b/stdlib/inspect.pyi new file mode 100644 index 000000000000..c3110ce28d8e --- /dev/null +++ b/stdlib/inspect.pyi @@ -0,0 +1,749 @@ +import dis +import enum +import sys +import types +from _typeshed import AnnotationForm, StrPath +from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Generator, Mapping, Sequence, Set as AbstractSet +from types import ( + AsyncGeneratorType, + BuiltinFunctionType, + BuiltinMethodType, + ClassMethodDescriptorType, + CodeType, + CoroutineType, + FrameType, + FunctionType, + GeneratorType, + GetSetDescriptorType, + LambdaType, + MemberDescriptorType, + MethodDescriptorType, + MethodType, + MethodWrapperType, + ModuleType, + TracebackType, + WrapperDescriptorType, +) +from typing import ( + Any, + ClassVar, + Final, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypeGuard, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Never, Self, TypeIs, deprecated, disjoint_base + +if sys.version_info >= (3, 14): + from annotationlib import Format + +if sys.version_info >= (3, 11): + __all__ = [ + "ArgInfo", + "Arguments", + "Attribute", + "BlockFinder", + "BoundArguments", + "CORO_CLOSED", + "CORO_CREATED", + "CORO_RUNNING", + "CORO_SUSPENDED", + "CO_ASYNC_GENERATOR", + "CO_COROUTINE", + "CO_GENERATOR", + "CO_ITERABLE_COROUTINE", + "CO_NESTED", + "CO_NEWLOCALS", + "CO_NOFREE", + "CO_OPTIMIZED", + "CO_VARARGS", + "CO_VARKEYWORDS", + "ClassFoundException", + "ClosureVars", + "EndOfBlock", + "FrameInfo", + "FullArgSpec", + "GEN_CLOSED", + "GEN_CREATED", + "GEN_RUNNING", + "GEN_SUSPENDED", + "Parameter", + "Signature", + "TPFLAGS_IS_ABSTRACT", + "Traceback", + "classify_class_attrs", + "cleandoc", + "currentframe", + "findsource", + "formatannotation", + "formatannotationrelativeto", + "formatargvalues", + "get_annotations", + "getabsfile", + "getargs", + "getargvalues", + "getattr_static", + "getblock", + "getcallargs", + "getclasstree", + "getclosurevars", + "getcomments", + "getcoroutinelocals", + "getcoroutinestate", + "getdoc", + "getfile", + "getframeinfo", + "getfullargspec", + "getgeneratorlocals", + "getgeneratorstate", + "getinnerframes", + "getlineno", + "getmembers", + "getmembers_static", + "getmodule", + "getmodulename", + "getmro", + "getouterframes", + "getsource", + "getsourcefile", + "getsourcelines", + "indentsize", + "isabstract", + "isasyncgen", + "isasyncgenfunction", + "isawaitable", + "isbuiltin", + "isclass", + "iscode", + "iscoroutine", + "iscoroutinefunction", + "isdatadescriptor", + "isframe", + "isfunction", + "isgenerator", + "isgeneratorfunction", + "isgetsetdescriptor", + "ismemberdescriptor", + "ismethod", + "ismethoddescriptor", + "ismethodwrapper", + "ismodule", + "isroutine", + "istraceback", + "signature", + "stack", + "trace", + "unwrap", + "walktree", + ] + + if sys.version_info >= (3, 12): + __all__ += [ + "markcoroutinefunction", + "AGEN_CLOSED", + "AGEN_CREATED", + "AGEN_RUNNING", + "AGEN_SUSPENDED", + "getasyncgenlocals", + "getasyncgenstate", + "BufferFlags", + ] + if sys.version_info >= (3, 14): + __all__ += ["CO_HAS_DOCSTRING", "CO_METHOD", "ispackage"] + +_P = ParamSpec("_P") +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_T_contra = TypeVar("_T_contra", contravariant=True) +_V_contra = TypeVar("_V_contra", contravariant=True) + +# +# Types and members +# +class EndOfBlock(Exception): ... + +class BlockFinder: + indent: int + islambda: bool + started: bool + passline: bool + indecorator: bool + decoratorhasargs: bool + last: int + def tokeneater(self, type: int, token: str, srowcol: tuple[int, int], erowcol: tuple[int, int], line: str) -> None: ... + +CO_OPTIMIZED: Final = 1 +CO_NEWLOCALS: Final = 2 +CO_VARARGS: Final = 4 +CO_VARKEYWORDS: Final = 8 +CO_NESTED: Final = 16 +CO_GENERATOR: Final = 32 +CO_NOFREE: Final = 64 +CO_COROUTINE: Final = 128 +CO_ITERABLE_COROUTINE: Final = 256 +CO_ASYNC_GENERATOR: Final = 512 +TPFLAGS_IS_ABSTRACT: Final = 1048576 +if sys.version_info >= (3, 14): + CO_HAS_DOCSTRING: Final = 67108864 + CO_METHOD: Final = 134217728 + +modulesbyfile: dict[str, Any] + +_GetMembersPredicateTypeGuard: TypeAlias = Callable[[Any], TypeGuard[_T]] +_GetMembersPredicateTypeIs: TypeAlias = Callable[[Any], TypeIs[_T]] +_GetMembersPredicate: TypeAlias = Callable[[Any], bool] +_GetMembersReturn: TypeAlias = list[tuple[str, _T]] + +@overload +def getmembers(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ... +@overload +def getmembers(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ... +@overload +def getmembers(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ... + +if sys.version_info >= (3, 11): + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ... + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ... + @overload + def getmembers_static(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ... + +def getmodulename(path: StrPath) -> str | None: ... +def ismodule(object: object) -> TypeIs[ModuleType]: ... +def isclass(object: object) -> TypeIs[type[object]]: ... +def ismethod(object: object) -> TypeIs[MethodType]: ... + +if sys.version_info >= (3, 14): + # Not TypeIs because it does not return True for all modules + def ispackage(object: object) -> TypeGuard[ModuleType]: ... + +def isfunction(object: object) -> TypeIs[FunctionType]: ... + +if sys.version_info >= (3, 12): + def markcoroutinefunction(func: _F) -> _F: ... + +@overload +def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: ... +@overload +def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ... +@overload +def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... + +@overload +def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... +@overload +def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, _T]]]: ... +@overload +def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... +@overload +def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... + +def isgenerator(object: object) -> TypeIs[GeneratorType[object, Never, object]]: ... +def iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: ... +def isawaitable(object: object) -> TypeIs[Awaitable[Any]]: ... + +@overload +def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... +@overload +def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ... +@overload +def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... + +@type_check_only +class _SupportsSet(Protocol[_T_contra, _V_contra]): + def __set__(self, instance: _T_contra, value: _V_contra, /) -> None: ... + +@type_check_only +class _SupportsDelete(Protocol[_T_contra]): + def __delete__(self, instance: _T_contra, /) -> None: ... + +def isasyncgen(object: object) -> TypeIs[AsyncGeneratorType[object, Never]]: ... +def istraceback(object: object) -> TypeIs[TracebackType]: ... +def isframe(object: object) -> TypeIs[FrameType]: ... +def iscode(object: object) -> TypeIs[CodeType]: ... +def isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: ... + +if sys.version_info >= (3, 11): + def ismethodwrapper(object: object) -> TypeIs[MethodWrapperType]: ... + +def isroutine( + object: object, +) -> TypeIs[ + FunctionType + | LambdaType + | MethodType + | BuiltinFunctionType + | BuiltinMethodType + | WrapperDescriptorType + | MethodDescriptorType + | ClassMethodDescriptorType +]: ... +def ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: ... +def ismemberdescriptor(object: object) -> TypeIs[MemberDescriptorType]: ... +def isabstract(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> TypeIs[GetSetDescriptorType]: ... +def isdatadescriptor(object: object) -> TypeIs[_SupportsSet[Never, Never] | _SupportsDelete[Never]]: ... + +# +# Retrieving source code +# +_SourceObjectType: TypeAlias = ( + ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any] +) + +def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... +def getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: ... + +# Special-case the two most common input types here +# to avoid the annoyingly vague `Sequence[str]` return type +@overload +def getblock(lines: list[str]) -> list[str]: ... +@overload +def getblock(lines: tuple[str, ...]) -> tuple[str, ...]: ... +@overload +def getblock(lines: Sequence[str]) -> Sequence[str]: ... + +if sys.version_info >= (3, 15): + def getdoc(object: object, *, inherit_class_doc: bool = True, fallback_to_class_doc: bool = True) -> str | None: ... + +else: + def getdoc(object: object) -> str | None: ... + +def getcomments(object: object) -> str | None: ... +def getfile(object: _SourceObjectType) -> str: ... +def getmodule(object: object, _filename: str | None = None) -> ModuleType | None: ... +def getsourcefile(object: _SourceObjectType) -> str | None: ... +def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ... +def getsource(object: _SourceObjectType) -> str: ... +def cleandoc(doc: str) -> str: ... +def indentsize(line: str) -> int: ... + +_IntrospectableCallable: TypeAlias = Callable[..., Any] + +# +# Introspecting callables with the Signature object +# +if sys.version_info >= (3, 14): + def signature( + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + annotation_format: Format = Format.VALUE, # noqa: Y011 + ) -> Signature: ... + +else: + def signature( + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + ) -> Signature: ... + +class _void: ... +class _empty: ... + +class Signature: + __slots__ = ("_return_annotation", "_parameters") + def __init__( + self, parameters: Sequence[Parameter] | None = None, *, return_annotation: Any = ..., __validate_parameters__: bool = True + ) -> None: ... + empty = _empty + @property + def parameters(self) -> types.MappingProxyType[str, Parameter]: ... + @property + def return_annotation(self) -> Any: ... + def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... + def replace(self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ...) -> Self: ... + __replace__ = replace + if sys.version_info >= (3, 14): + @classmethod + def from_callable( + cls, + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + annotation_format: Format = Format.VALUE, # noqa: Y011 + ) -> Self: ... + else: + @classmethod + def from_callable( + cls, + obj: _IntrospectableCallable, + *, + follow_wrapped: bool = True, + globals: Mapping[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + eval_str: bool = False, + ) -> Self: ... + + if sys.version_info >= (3, 14): + def format(self, *, max_width: int | None = None, quote_annotation_strings: bool = True) -> str: ... + elif sys.version_info >= (3, 13): + def format(self, *, max_width: int | None = None) -> str: ... + + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 14): + from annotationlib import get_annotations as get_annotations +else: + def get_annotations( + obj: Callable[..., object] | type[object] | ModuleType, # any callable, class, or module + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + ) -> dict[str, AnnotationForm]: ... # values are type expressions + +# The name is the same as the enum's name in CPython +class _ParameterKind(enum.IntEnum): + POSITIONAL_ONLY = 0 + POSITIONAL_OR_KEYWORD = 1 + VAR_POSITIONAL = 2 + KEYWORD_ONLY = 3 + VAR_KEYWORD = 4 + + @property + def description(self) -> str: ... + +if sys.version_info >= (3, 12): + AGEN_CREATED: Final = "AGEN_CREATED" + AGEN_RUNNING: Final = "AGEN_RUNNING" + AGEN_SUSPENDED: Final = "AGEN_SUSPENDED" + AGEN_CLOSED: Final = "AGEN_CLOSED" + + def getasyncgenstate( + agen: AsyncGenerator[Any, Any], + ) -> Literal["AGEN_CREATED", "AGEN_RUNNING", "AGEN_SUSPENDED", "AGEN_CLOSED"]: ... + def getasyncgenlocals(agen: AsyncGeneratorType[Any, Any]) -> dict[str, Any]: ... + +class Parameter: + __slots__ = ("_name", "_kind", "_default", "_annotation") + def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ... + empty = _empty + + POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]] + POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] + VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]] + KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] + VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] + @property + def name(self) -> str: ... + @property + def default(self) -> Any: ... + @property + def kind(self) -> _ParameterKind: ... + @property + def annotation(self) -> Any: ... + def replace( + self, + *, + name: str | type[_void] = ..., + kind: _ParameterKind | type[_void] = ..., + default: Any = ..., + annotation: Any = ..., + ) -> Self: ... + if sys.version_info >= (3, 13): + __replace__ = replace + + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class BoundArguments: + __slots__ = ("arguments", "_signature", "__weakref__") + arguments: dict[str, Any] + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> dict[str, Any]: ... + @property + def signature(self) -> Signature: ... + def __init__(self, signature: Signature, arguments: dict[str, Any]) -> None: ... + def apply_defaults(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +# +# Classes and functions +# + +_ClassTreeItem: TypeAlias = list[tuple[type, ...]] | list[_ClassTreeItem] + +def getclasstree(classes: list[type], unique: bool = False) -> _ClassTreeItem: ... +def walktree(classes: list[type], children: Mapping[type[Any], list[type]], parent: type[Any] | None) -> _ClassTreeItem: ... + +class Arguments(NamedTuple): + args: list[str] + varargs: str | None + varkw: str | None + +def getargs(co: CodeType) -> Arguments: ... + +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.0; removed in Python 3.11.") + class ArgSpec(NamedTuple): + args: list[str] + varargs: str | None + keywords: str | None + defaults: tuple[Any, ...] + + @deprecated("Deprecated since Python 3.0; removed in Python 3.11. Use `inspect.signature()` instead.") + def getargspec(func: object) -> ArgSpec: ... + +class FullArgSpec(NamedTuple): + args: list[str] + varargs: str | None + varkw: str | None + defaults: tuple[Any, ...] | None + kwonlyargs: list[str] + kwonlydefaults: dict[str, Any] | None + annotations: dict[str, Any] + +if sys.version_info >= (3, 15): + def getfullargspec(func: object, *, annotation_format: Format = Format.VALUE) -> FullArgSpec: ... # noqa: Y011 + +else: + def getfullargspec(func: object) -> FullArgSpec: ... + +class ArgInfo(NamedTuple): + args: list[str] + varargs: str | None + keywords: str | None + locals: dict[str, Any] + +def getargvalues(frame: FrameType) -> ArgInfo: ... + +if sys.version_info >= (3, 14): + def formatannotation(annotation: object, base_module: str | None = None, *, quote_annotation_strings: bool = True) -> str: ... + +else: + def formatannotation(annotation: object, base_module: str | None = None) -> str: ... + +def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... + +if sys.version_info < (3, 11): + @deprecated( + "Deprecated since Python 3.5; removed in Python 3.11. Use `inspect.signature()` and the `Signature` class instead." + ) + def formatargspec( + args: list[str], + varargs: str | None = None, + varkw: str | None = None, + defaults: tuple[Any, ...] | None = None, + kwonlyargs: Sequence[str] | None = (), + kwonlydefaults: Mapping[str, Any] | None = {}, + annotations: Mapping[str, Any] = {}, + formatarg: Callable[[str], str] = ..., + formatvarargs: Callable[[str], str] = ..., + formatvarkw: Callable[[str], str] = ..., + formatvalue: Callable[[Any], str] = ..., + formatreturns: Callable[[Any], str] = ..., + formatannotation: Callable[[Any], str] = ..., + ) -> str: ... + +def formatargvalues( + args: list[str], + varargs: str | None, + varkw: str | None, + locals: Mapping[str, Any] | None, + formatarg: Callable[[str], str] | None = ..., + formatvarargs: Callable[[str], str] | None = ..., + formatvarkw: Callable[[str], str] | None = ..., + formatvalue: Callable[[Any], str] | None = ..., +) -> str: ... +def getmro(cls: type) -> tuple[type, ...]: ... +@deprecated("Deprecated since Python 3.5. Use `Signature.bind` and `Signature.bind_partial` instead.") +def getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ... + +class ClosureVars(NamedTuple): + nonlocals: Mapping[str, Any] + globals: Mapping[str, Any] + builtins: Mapping[str, Any] + unbound: AbstractSet[str] + +def getclosurevars(func: _IntrospectableCallable) -> ClosureVars: ... +def unwrap(func: Callable[..., Any], *, stop: Callable[[Callable[..., Any]], Any] | None = None) -> Any: ... + +# +# The interpreter stack +# + +if sys.version_info >= (3, 11): + class _Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class _FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + if sys.version_info >= (3, 12): + class Traceback(_Traceback): + positions: dis.Positions | None + def __new__( + cls, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + class FrameInfo(_FrameInfo): + positions: dis.Positions | None + def __new__( + cls, + frame: FrameType, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + else: + @disjoint_base + class Traceback(_Traceback): + positions: dis.Positions | None + def __new__( + cls, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + + @disjoint_base + class FrameInfo(_FrameInfo): + positions: dis.Positions | None + def __new__( + cls, + frame: FrameType, + filename: str, + lineno: int, + function: str, + code_context: list[str] | None, + index: int | None, + *, + positions: dis.Positions | None = None, + ) -> Self: ... + +else: + class Traceback(NamedTuple): + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + + class FrameInfo(NamedTuple): + frame: FrameType + filename: str + lineno: int + function: str + code_context: list[str] | None + index: int | None # type: ignore[assignment] + +def getframeinfo(frame: FrameType | TracebackType, context: int = 1) -> Traceback: ... +def getouterframes(frame: Any, context: int = 1) -> list[FrameInfo]: ... +def getinnerframes(tb: TracebackType, context: int = 1) -> list[FrameInfo]: ... +def getlineno(frame: FrameType) -> int: ... +def currentframe() -> FrameType | None: ... +def stack(context: int = 1) -> list[FrameInfo]: ... +def trace(context: int = 1) -> list[FrameInfo]: ... + +# +# Fetching attributes statically +# + +def getattr_static(obj: object, attr: str, default: Any | None = ...) -> Any: ... + +# +# Current State of Generators and Coroutines +# + +GEN_CREATED: Final = "GEN_CREATED" +GEN_RUNNING: Final = "GEN_RUNNING" +GEN_SUSPENDED: Final = "GEN_SUSPENDED" +GEN_CLOSED: Final = "GEN_CLOSED" + +def getgeneratorstate( + generator: Generator[Any, Any, Any], +) -> Literal["GEN_CREATED", "GEN_RUNNING", "GEN_SUSPENDED", "GEN_CLOSED"]: ... + +CORO_CREATED: Final = "CORO_CREATED" +CORO_RUNNING: Final = "CORO_RUNNING" +CORO_SUSPENDED: Final = "CORO_SUSPENDED" +CORO_CLOSED: Final = "CORO_CLOSED" + +def getcoroutinestate( + coroutine: Coroutine[Any, Any, Any], +) -> Literal["CORO_CREATED", "CORO_RUNNING", "CORO_SUSPENDED", "CORO_CLOSED"]: ... +def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ... +def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: ... + +# Create private type alias to avoid conflict with symbol of same +# name created in Attribute class. +_Object: TypeAlias = object + +class Attribute(NamedTuple): + name: str + kind: Literal["class method", "static method", "property", "method", "data"] + defining_class: type + object: _Object + +def classify_class_attrs(cls: type) -> list[Attribute]: ... + +class ClassFoundException(Exception): ... + +if sys.version_info >= (3, 12): + class BufferFlags(enum.IntFlag): + SIMPLE = 0 + WRITABLE = 1 + FORMAT = 4 + ND = 8 + STRIDES = 24 + C_CONTIGUOUS = 56 + F_CONTIGUOUS = 88 + ANY_CONTIGUOUS = 152 + INDIRECT = 280 + CONTIG = 9 + CONTIG_RO = 8 + STRIDED = 25 + STRIDED_RO = 24 + RECORDS = 29 + RECORDS_RO = 28 + FULL = 285 + FULL_RO = 284 + READ = 256 + WRITE = 512 diff --git a/stdlib/io.pyi b/stdlib/io.pyi new file mode 100644 index 000000000000..d301d700e9d0 --- /dev/null +++ b/stdlib/io.pyi @@ -0,0 +1,75 @@ +import abc +import sys +from _io import ( + DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE, + BlockingIOError as BlockingIOError, + BufferedRandom as BufferedRandom, + BufferedReader as BufferedReader, + BufferedRWPair as BufferedRWPair, + BufferedWriter as BufferedWriter, + BytesIO as BytesIO, + FileIO as FileIO, + IncrementalNewlineDecoder as IncrementalNewlineDecoder, + StringIO as StringIO, + TextIOWrapper as TextIOWrapper, + _BufferedIOBase, + _IOBase, + _RawIOBase, + _TextIOBase, + _WrappedBuffer as _WrappedBuffer, # used elsewhere in typeshed + open as open, + open_code as open_code, +) +from typing import Final, Protocol, TypeVar + +__all__ = [ + "BlockingIOError", + "open", + "open_code", + "IOBase", + "RawIOBase", + "FileIO", + "BytesIO", + "StringIO", + "BufferedIOBase", + "BufferedReader", + "BufferedWriter", + "BufferedRWPair", + "BufferedRandom", + "TextIOBase", + "TextIOWrapper", + "UnsupportedOperation", + "SEEK_SET", + "SEEK_CUR", + "SEEK_END", +] + +if sys.version_info >= (3, 14): + __all__ += ["Reader", "Writer"] + +if sys.version_info >= (3, 11): + from _io import text_encoding as text_encoding + + __all__ += ["DEFAULT_BUFFER_SIZE", "IncrementalNewlineDecoder", "text_encoding"] + +_T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) + +SEEK_SET: Final = 0 +SEEK_CUR: Final = 1 +SEEK_END: Final = 2 + +class UnsupportedOperation(OSError, ValueError): ... +class IOBase(_IOBase, metaclass=abc.ABCMeta): ... +class RawIOBase(_RawIOBase, IOBase): ... +class BufferedIOBase(_BufferedIOBase, IOBase): ... +class TextIOBase(_TextIOBase, IOBase): ... + +if sys.version_info >= (3, 14): + class Reader(Protocol[_T_co]): + __slots__ = () + def read(self, size: int = ..., /) -> _T_co: ... + + class Writer(Protocol[_T_contra]): + __slots__ = () + def write(self, data: _T_contra, /) -> int: ... diff --git a/stdlib/ipaddress.pyi b/stdlib/ipaddress.pyi new file mode 100644 index 000000000000..c514abfa569f --- /dev/null +++ b/stdlib/ipaddress.pyi @@ -0,0 +1,249 @@ +import sys +from collections.abc import Iterable, Iterator +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +# Undocumented length constants +IPV4LENGTH: Final = 32 +IPV6LENGTH: Final = 128 + +_A = TypeVar("_A", IPv4Address, IPv6Address) +_N = TypeVar("_N", IPv4Network, IPv6Network) + +_RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address +_RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface + +def ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: ... +def ip_network( + address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], strict: bool = True +) -> IPv4Network | IPv6Network: ... +def ip_interface( + address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], +) -> IPv4Interface | IPv6Interface: ... + +class _IPAddressBase: + __slots__ = () + @property + def compressed(self) -> str: ... + @property + def exploded(self) -> str: ... + @property + def reverse_pointer(self) -> str: ... + if sys.version_info < (3, 14): + @property + def version(self) -> int: ... + +class _BaseAddress(_IPAddressBase): + __slots__ = () + def __add__(self, other: int) -> Self: ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def __sub__(self, other: int) -> Self: ... + def __format__(self, fmt: str) -> str: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __le__(self, other: Self) -> bool: ... + else: + def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + +class _BaseNetwork(_IPAddressBase, Generic[_A]): + network_address: _A + netmask: _A + def __contains__(self, other: Any) -> bool: ... + def __getitem__(self, n: int) -> _A: ... + def __iter__(self) -> Iterator[_A]: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Self) -> bool: ... + if sys.version_info >= (3, 11): + def __ge__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __le__(self, other: Self) -> bool: ... + else: + def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ... + + def address_exclude(self, other: Self) -> Iterator[Self]: ... + @property + def broadcast_address(self) -> _A: ... + def compare_networks(self, other: Self) -> int: ... + def hosts(self) -> Iterator[_A]: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def num_addresses(self) -> int: ... + def overlaps(self, other: _BaseNetwork[IPv4Address] | _BaseNetwork[IPv6Address]) -> bool: ... + @property + def prefixlen(self) -> int: ... + def subnet_of(self, other: Self) -> bool: ... + def supernet_of(self, other: Self) -> bool: ... + def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[Self]: ... + def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Self: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... + @property + def hostmask(self) -> _A: ... + +class _BaseV4: + __slots__ = () + if sys.version_info >= (3, 14): + version: Final = 4 + max_prefixlen: Final = 32 + else: + @property + def version(self) -> Literal[4]: ... + @property + def max_prefixlen(self) -> Literal[32]: ... + +class IPv4Address(_BaseV4, _BaseAddress): + __slots__ = ("_ip", "__weakref__") + def __init__(self, address: object) -> None: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def packed(self) -> bytes: ... + if sys.version_info >= (3, 13): + @property + def ipv6_mapped(self) -> IPv6Address: ... + +class IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]): + def __init__(self, address: object, strict: bool = True) -> None: ... + +class IPv4Interface(IPv4Address): + netmask: IPv4Address + network: IPv4Network + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + @property + def hostmask(self) -> IPv4Address: ... + @property + def ip(self) -> IPv4Address: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... + +class _BaseV6: + __slots__ = () + if sys.version_info >= (3, 14): + version: Final = 6 + max_prefixlen: Final = 128 + else: + @property + def version(self) -> Literal[6]: ... + @property + def max_prefixlen(self) -> Literal[128]: ... + +class IPv6Address(_BaseV6, _BaseAddress): + __slots__ = ("_ip", "_scope_id", "__weakref__") + def __init__(self, address: object) -> None: ... + @property + def is_global(self) -> bool: ... + @property + def is_link_local(self) -> bool: ... + @property + def is_loopback(self) -> bool: ... + @property + def is_multicast(self) -> bool: ... + @property + def is_private(self) -> bool: ... + @property + def is_reserved(self) -> bool: ... + @property + def is_unspecified(self) -> bool: ... + @property + def packed(self) -> bytes: ... + @property + def ipv4_mapped(self) -> IPv4Address | None: ... + @property + def is_site_local(self) -> bool: ... + @property + def sixtofour(self) -> IPv4Address | None: ... + @property + def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: ... + @property + def scope_id(self) -> str | None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]): + def __init__(self, address: object, strict: bool = True) -> None: ... + @property + def is_site_local(self) -> bool: ... + +class IPv6Interface(IPv6Address): + netmask: IPv6Address + network: IPv6Network + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + @property + def hostmask(self) -> IPv6Address: ... + @property + def ip(self) -> IPv6Address: ... + @property + def with_hostmask(self) -> str: ... + @property + def with_netmask(self) -> str: ... + @property + def with_prefixlen(self) -> str: ... + +def v4_int_to_packed(address: int) -> bytes: ... +def v6_int_to_packed(address: int) -> bytes: ... + +# Third overload is technically incorrect, but convenient when first and last are return values of ip_address() +@overload +def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ... +@overload +def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ... +@overload +def summarize_address_range( + first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address +) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ... + +def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... + +@overload +def get_mixed_type_key(obj: _A) -> tuple[int, _A]: ... +@overload +def get_mixed_type_key(obj: IPv4Network) -> tuple[int, IPv4Address, IPv4Address]: ... +@overload +def get_mixed_type_key(obj: IPv6Network) -> tuple[int, IPv6Address, IPv6Address]: ... + +class AddressValueError(ValueError): ... +class NetmaskValueError(ValueError): ... diff --git a/stdlib/itertools.pyi b/stdlib/itertools.pyi new file mode 100644 index 000000000000..d26a4e1da21e --- /dev/null +++ b/stdlib/itertools.pyi @@ -0,0 +1,376 @@ +import sys +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable, Iterator +from types import GenericAlias +from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") +_S = TypeVar("_S") +_N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) +_T_co = TypeVar("_T_co", covariant=True) +_S_co = TypeVar("_S_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_T6 = TypeVar("_T6") +_T7 = TypeVar("_T7") +_T8 = TypeVar("_T8") +_T9 = TypeVar("_T9") +_T10 = TypeVar("_T10") + +_Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex + +_Predicate: TypeAlias = Callable[[_T], object] + +# Technically count can take anything that implements a number protocol and has an add method +# but we can't enforce the add method +@disjoint_base +class count(Generic[_N]): + @overload + def __new__(cls) -> count[int]: ... + @overload + def __new__(cls, start: _N, step: _Step = 1) -> count[_N]: ... + @overload + def __new__(cls, *, step: _N) -> count[_N]: ... + + def __next__(self) -> _N: ... + def __iter__(self) -> Self: ... + +@disjoint_base +class cycle(Generic[_T]): + def __new__(cls, iterable: Iterable[_T], /) -> Self: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Self: ... + +@disjoint_base +class repeat(Generic[_T]): + @overload + def __new__(cls, object: _T) -> Self: ... + @overload + def __new__(cls, object: _T, times: int) -> Self: ... + + def __next__(self) -> _T: ... + def __iter__(self) -> Self: ... + def __length_hint__(self) -> int: ... + +@disjoint_base +class accumulate(Generic[_T]): + @overload + def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... + @overload + def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = None) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class chain(Generic[_T]): + def __new__(cls, *iterables: Iterable[_T]) -> Self: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Self: ... + @classmethod + # We use type[Any] and not type[_S] to not lose the type inference from __iterable + def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@disjoint_base +class compress(Generic[_T]): + def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class dropwhile(Generic[_T]): + def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class filterfalse(Generic[_T]): + def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class groupby(Generic[_T_co, _S_co]): + @overload + def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... + @overload + def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... + +@disjoint_base +class islice(Generic[_T]): + @overload + def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... + @overload + def __new__(cls, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = 1, /) -> Self: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class starmap(Generic[_T_co]): + def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class takewhile(Generic[_T]): + def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... + +@disjoint_base +class zip_longest(Generic[_T_co]): + # one iterable (fillvalue doesn't matter) + @overload + def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ... + # two iterables + @overload + # In the overloads without fillvalue, all of the tuple members could theoretically be None, + # but we return Any instead to avoid false positives for code where we know one of the iterables + # is longer. + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T]]: ... + # three iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T]]: ... + # four iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, fillvalue: _T + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T]]: ... + # five iterables + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone, _T5 | MaybeNone]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + fillvalue: _T, + ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T, _T5 | _T]]: ... + # six or more iterables + @overload + def __new__( + cls, + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, + *iterables: Iterable[_T], + ) -> zip_longest[tuple[_T | MaybeNone, ...]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T], + iter2: Iterable[_T], + iter3: Iterable[_T], + iter4: Iterable[_T], + iter5: Iterable[_T], + iter6: Iterable[_T], + /, + *iterables: Iterable[_T], + fillvalue: _T, + ) -> zip_longest[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class product(Generic[_T_co]): + @overload + def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / + ) -> product[tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + iter9: Iterable[_T9], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + iter6: Iterable[_T6], + iter7: Iterable[_T7], + iter8: Iterable[_T8], + iter9: Iterable[_T9], + iter10: Iterable[_T10], + /, + ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ... + @overload + def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class permutations(Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> permutations[tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> permutations[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> permutations[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: int | None = None) -> permutations[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class combinations(Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations[tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class combinations_with_replacement(Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations_with_replacement[tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations_with_replacement[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations_with_replacement[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: int) -> combinations_with_replacement[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +@disjoint_base +class pairwise(Generic[_T_co]): + def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + +if sys.version_info >= (3, 12): + @disjoint_base + class batched(Generic[_T_co]): + if sys.version_info >= (3, 13): + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[2], *, strict: Literal[True]) -> batched[tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: Literal[3], *, strict: Literal[True]) -> batched[tuple[_T, _T, _T]]: ... + @overload + def __new__( + cls, iterable: Iterable[_T], n: Literal[4], *, strict: Literal[True] + ) -> batched[tuple[_T, _T, _T, _T]]: ... + @overload + def __new__( + cls, iterable: Iterable[_T], n: Literal[5], *, strict: Literal[True] + ) -> batched[tuple[_T, _T, _T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], n: int, *, strict: bool = False) -> batched[tuple[_T, ...]]: ... + else: + def __new__(cls, iterable: Iterable[_T], n: int) -> batched[tuple[_T, ...]]: ... + + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... diff --git a/stdlib/json/__init__.pyi b/stdlib/json/__init__.pyi new file mode 100644 index 000000000000..2342b29cb0c8 --- /dev/null +++ b/stdlib/json/__init__.pyi @@ -0,0 +1,93 @@ +import sys +from _typeshed import SupportsRead, SupportsWrite +from collections.abc import Callable +from typing import Any, Literal + +from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder +from .encoder import JSONEncoder as JSONEncoder + +__all__ = ["dump", "dumps", "load", "loads", "JSONDecoder", "JSONDecodeError", "JSONEncoder"] + +def dumps( + obj: Any, + *, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: None | int | str = None, + separators: tuple[str, str] | None = None, + default: Callable[[Any], Any] | None = None, + sort_keys: bool = False, + **kwds: Any, +) -> str: ... +def dump( + obj: Any, + fp: SupportsWrite[str], + *, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: None | int | str = None, + separators: tuple[str, str] | None = None, + default: Callable[[Any], Any] | None = None, + sort_keys: bool = False, + **kwds: Any, +) -> None: ... + +if sys.version_info >= (3, 15): + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + +else: + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + +def detect_encoding( + b: bytes | bytearray, +) -> Literal["utf-8", "utf-8-sig", "utf-16", "utf-16-be", "utf-16-le", "utf-32", "utf-32-be", "utf-32-le"]: ... # undocumented diff --git a/stdlib/json/decoder.pyi b/stdlib/json/decoder.pyi new file mode 100644 index 000000000000..1b09579fb0c4 --- /dev/null +++ b/stdlib/json/decoder.pyi @@ -0,0 +1,50 @@ +import sys +from collections.abc import Callable +from typing import Any + +__all__ = ["JSONDecoder", "JSONDecodeError"] + +class JSONDecodeError(ValueError): + msg: str + doc: str + pos: int + lineno: int + colno: int + def __init__(self, msg: str, doc: str, pos: int) -> None: ... + +class JSONDecoder: + if sys.version_info >= (3, 15): + array_hook: Callable[[list[Any]], Any] | None + object_hook: Callable[[dict[str, Any]], Any] + parse_float: Callable[[str], Any] + parse_int: Callable[[str], Any] + parse_constant: Callable[[str], Any] + strict: bool + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] + if sys.version_info >= (3, 15): + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + ) -> None: ... + + def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ... # _w is undocumented + def raw_decode(self, s: str, idx: int = 0) -> tuple[Any, int]: ... diff --git a/stdlib/json/encoder.pyi b/stdlib/json/encoder.pyi new file mode 100644 index 000000000000..83b78666d4a7 --- /dev/null +++ b/stdlib/json/encoder.pyi @@ -0,0 +1,40 @@ +from collections.abc import Callable, Iterator +from re import Pattern +from typing import Any, Final + +ESCAPE: Final[Pattern[str]] # undocumented +ESCAPE_ASCII: Final[Pattern[str]] # undocumented +HAS_UTF8: Final[Pattern[bytes]] # undocumented +ESCAPE_DCT: Final[dict[str, str]] # undocumented +INFINITY: Final[float] # undocumented + +def py_encode_basestring(s: str) -> str: ... # undocumented +def py_encode_basestring_ascii(s: str) -> str: ... # undocumented +def encode_basestring(s: str, /) -> str: ... # undocumented +def encode_basestring_ascii(s: str, /) -> str: ... # undocumented + +class JSONEncoder: + item_separator: str + key_separator: str + + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: int | str + def __init__( + self, + *, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + sort_keys: bool = False, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, + ) -> None: ... + def default(self, o: Any) -> Any: ... + def encode(self, o: Any) -> str: ... + def iterencode(self, o: Any, _one_shot: bool = False) -> Iterator[str]: ... diff --git a/stdlib/json/scanner.pyi b/stdlib/json/scanner.pyi new file mode 100644 index 000000000000..68b42e92d295 --- /dev/null +++ b/stdlib/json/scanner.pyi @@ -0,0 +1,7 @@ +from _json import make_scanner as make_scanner +from re import Pattern +from typing import Final + +__all__ = ["make_scanner"] + +NUMBER_RE: Final[Pattern[str]] # undocumented diff --git a/stdlib/json/tool.pyi b/stdlib/json/tool.pyi new file mode 100644 index 000000000000..7e7363e797f3 --- /dev/null +++ b/stdlib/json/tool.pyi @@ -0,0 +1 @@ +def main() -> None: ... diff --git a/stdlib/keyword.pyi b/stdlib/keyword.pyi new file mode 100644 index 000000000000..6b8bdad6beb6 --- /dev/null +++ b/stdlib/keyword.pyi @@ -0,0 +1,16 @@ +from collections.abc import Sequence +from typing import Final + +__all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] + +def iskeyword(s: str, /) -> bool: ... + +# a list at runtime, but you're not meant to mutate it; +# type it as a sequence +kwlist: Final[Sequence[str]] + +def issoftkeyword(s: str, /) -> bool: ... + +# a list at runtime, but you're not meant to mutate it; +# type it as a sequence +softkwlist: Final[Sequence[str]] diff --git a/stdlib/lib2to3/__init__.pyi b/stdlib/lib2to3/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/lib2to3/btm_matcher.pyi b/stdlib/lib2to3/btm_matcher.pyi new file mode 100644 index 000000000000..4c87b664eb20 --- /dev/null +++ b/stdlib/lib2to3/btm_matcher.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections import defaultdict +from collections.abc import Iterable + +from .fixer_base import BaseFix +from .pytree import Leaf, Node + +class BMNode: + count: Incomplete + transition_table: Incomplete + fixers: Incomplete + id: Incomplete + content: str + def __init__(self) -> None: ... + +class BottomMatcher: + match: Incomplete + root: Incomplete + nodes: Incomplete + fixers: Incomplete + logger: Incomplete + def __init__(self) -> None: ... + def add_fixer(self, fixer: BaseFix) -> None: ... + def add(self, pattern: SupportsGetItem[int | slice, Incomplete] | None, start: BMNode) -> list[BMNode]: ... + def run(self, leaves: Iterable[Leaf]) -> defaultdict[BaseFix, list[Node | Leaf]]: ... + def print_ac(self) -> None: ... + +def type_repr(type_num: int) -> str | int: ... diff --git a/stdlib/lib2to3/fixer_base.pyi b/stdlib/lib2to3/fixer_base.pyi new file mode 100644 index 000000000000..06813c94308a --- /dev/null +++ b/stdlib/lib2to3/fixer_base.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, StrPath +from abc import ABCMeta, abstractmethod +from collections.abc import MutableMapping +from typing import ClassVar, Literal, TypeVar + +from .pytree import Base, Leaf, Node + +_N = TypeVar("_N", bound=Base) + +class BaseFix: + PATTERN: ClassVar[str | None] + pattern: Incomplete | None + pattern_tree: Incomplete | None + options: Incomplete | None + filename: Incomplete | None + numbers: Incomplete + used_names: Incomplete + order: ClassVar[Literal["post", "pre"]] + explicit: ClassVar[bool] + run_order: ClassVar[int] + keep_line_order: ClassVar[bool] + BM_compatible: ClassVar[bool] + syms: Incomplete + log: Incomplete + def __init__(self, options: MutableMapping[str, Incomplete], log: list[str]) -> None: ... + def compile_pattern(self) -> None: ... + def set_filename(self, filename: StrPath) -> None: ... + def match(self, node: _N) -> Literal[False] | dict[str, _N]: ... + @abstractmethod + def transform(self, node: Base, results: dict[str, Base]) -> Node | Leaf | None: ... + def new_name(self, template: str = "xxx_todo_changeme") -> str: ... + first_log: bool + def log_message(self, message: str) -> None: ... + def cannot_convert(self, node: Base, reason: str | None = None) -> None: ... + def warning(self, node: Base, reason: str) -> None: ... + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def finish_tree(self, tree: Node, filename: StrPath) -> None: ... + +class ConditionalFix(BaseFix, metaclass=ABCMeta): + skip_on: ClassVar[str | None] + def start_tree(self, tree: Node, filename: StrPath, /) -> None: ... + def should_skip(self, node: Base) -> bool: ... diff --git a/stdlib/lib2to3/fixes/__init__.pyi b/stdlib/lib2to3/fixes/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/lib2to3/fixes/fix_apply.pyi b/stdlib/lib2to3/fixes/fix_apply.pyi new file mode 100644 index 000000000000..e53e3dd86457 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_apply.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixApply(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_asserts.pyi b/stdlib/lib2to3/fixes/fix_asserts.pyi new file mode 100644 index 000000000000..1bf7db2f76e9 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_asserts.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Final, Literal + +from ..fixer_base import BaseFix + +NAMES: Final[dict[str, str]] + +class FixAsserts(BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_basestring.pyi b/stdlib/lib2to3/fixes/fix_basestring.pyi new file mode 100644 index 000000000000..8ed5ccaa7fd3 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_basestring.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixBasestring(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[Literal["'basestring'"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_buffer.pyi b/stdlib/lib2to3/fixes/fix_buffer.pyi new file mode 100644 index 000000000000..1efca6228ea2 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_buffer.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixBuffer(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_dict.pyi b/stdlib/lib2to3/fixes/fix_dict.pyi new file mode 100644 index 000000000000..08c54c3bc376 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_dict.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +iter_exempt: set[str] + +class FixDict(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + P1: ClassVar[str] + p1: ClassVar[Incomplete] + P2: ClassVar[str] + p2: ClassVar[Incomplete] + def in_special_context(self, node, isiter): ... diff --git a/stdlib/lib2to3/fixes/fix_except.pyi b/stdlib/lib2to3/fixes/fix_except.pyi new file mode 100644 index 000000000000..0d856e6b0b7d --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_except.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator, Iterable +from typing import ClassVar, Literal, TypeVar + +from .. import fixer_base +from ..pytree import Base + +_N = TypeVar("_N", bound=Base) + +def find_excepts(nodes: Iterable[_N]) -> Generator[tuple[_N, _N]]: ... + +class FixExcept(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_exec.pyi b/stdlib/lib2to3/fixes/fix_exec.pyi new file mode 100644 index 000000000000..71e2a820a564 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_exec.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixExec(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_execfile.pyi b/stdlib/lib2to3/fixes/fix_execfile.pyi new file mode 100644 index 000000000000..8122a6389b12 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_execfile.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixExecfile(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_exitfunc.pyi b/stdlib/lib2to3/fixes/fix_exitfunc.pyi new file mode 100644 index 000000000000..7fc910c0a1bc --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_exitfunc.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete, StrPath +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +from ..pytree import Node + +class FixExitfunc(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def __init__(self, *args) -> None: ... + sys_import: Incomplete | None + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_filter.pyi b/stdlib/lib2to3/fixes/fix_filter.pyi new file mode 100644 index 000000000000..638889be8b65 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_filter.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFilter(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.filter"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_funcattrs.pyi b/stdlib/lib2to3/fixes/fix_funcattrs.pyi new file mode 100644 index 000000000000..60487bb1f2a6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_funcattrs.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFuncattrs(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_future.pyi b/stdlib/lib2to3/fixes/fix_future.pyi new file mode 100644 index 000000000000..12ed93f21223 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_future.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixFuture(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_getcwdu.pyi b/stdlib/lib2to3/fixes/fix_getcwdu.pyi new file mode 100644 index 000000000000..aa3ccf50be9e --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_getcwdu.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixGetcwdu(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_has_key.pyi b/stdlib/lib2to3/fixes/fix_has_key.pyi new file mode 100644 index 000000000000..f6f5a072e21b --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_has_key.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixHasKey(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_idioms.pyi b/stdlib/lib2to3/fixes/fix_idioms.pyi new file mode 100644 index 000000000000..6b2723d09d43 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_idioms.pyi @@ -0,0 +1,15 @@ +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +CMP: Final[str] +TYPE: Final[str] + +class FixIdioms(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + def match(self, node): ... + def transform(self, node, results): ... + def transform_isinstance(self, node, results): ... + def transform_while(self, node, results) -> None: ... + def transform_sort(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_import.pyi b/stdlib/lib2to3/fixes/fix_import.pyi new file mode 100644 index 000000000000..2daa18327ec0 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_import.pyi @@ -0,0 +1,16 @@ +from _typeshed import StrPath +from collections.abc import Generator +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +def traverse_imports(names) -> Generator[str]: ... + +class FixImport(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip: bool + def start_tree(self, tree: Node, name: StrPath) -> None: ... + def transform(self, node, results): ... + def probably_a_local_import(self, imp_name): ... diff --git a/stdlib/lib2to3/fixes/fix_imports.pyi b/stdlib/lib2to3/fixes/fix_imports.pyi new file mode 100644 index 000000000000..d86ebbe215a1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_imports.pyi @@ -0,0 +1,21 @@ +from _typeshed import StrPath +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from .. import fixer_base +from ..pytree import Node + +MAPPING: Final[dict[str, str]] + +def alternates(members): ... +def build_pattern(mapping=...) -> Generator[str]: ... + +class FixImports(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + mapping = MAPPING + def build_pattern(self): ... + def compile_pattern(self) -> None: ... + def match(self, node): ... + replace: dict[str, str] + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_imports2.pyi b/stdlib/lib2to3/fixes/fix_imports2.pyi new file mode 100644 index 000000000000..618ecd0424d8 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_imports2.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from . import fix_imports + +MAPPING: Final[dict[str, str]] + +class FixImports2(fix_imports.FixImports): + mapping = MAPPING diff --git a/stdlib/lib2to3/fixes/fix_input.pyi b/stdlib/lib2to3/fixes/fix_input.pyi new file mode 100644 index 000000000000..fc1279535bed --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_input.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +context: Incomplete + +class FixInput(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_intern.pyi b/stdlib/lib2to3/fixes/fix_intern.pyi new file mode 100644 index 000000000000..804b7b2517a5 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_intern.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixIntern(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_isinstance.pyi b/stdlib/lib2to3/fixes/fix_isinstance.pyi new file mode 100644 index 000000000000..31eefd625317 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_isinstance.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixIsinstance(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_itertools.pyi b/stdlib/lib2to3/fixes/fix_itertools.pyi new file mode 100644 index 000000000000..229d86ee71bb --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_itertools.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixItertools(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + it_funcs: str + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_itertools_imports.pyi b/stdlib/lib2to3/fixes/fix_itertools_imports.pyi new file mode 100644 index 000000000000..39a4da506867 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_itertools_imports.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixItertoolsImports(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_long.pyi b/stdlib/lib2to3/fixes/fix_long.pyi new file mode 100644 index 000000000000..9ccf2711d7d1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_long.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixLong(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[Literal["'long'"]] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_map.pyi b/stdlib/lib2to3/fixes/fix_map.pyi new file mode 100644 index 000000000000..6e60282cf0be --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_map.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixMap(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.map"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_metaclass.pyi b/stdlib/lib2to3/fixes/fix_metaclass.pyi new file mode 100644 index 000000000000..6ad25e9aac36 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_metaclass.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Base + +def has_metaclass(parent): ... +def fixup_parse_tree(cls_node) -> None: ... +def fixup_simple_stmt(parent, i, stmt_node) -> None: ... +def remove_trailing_newline(node) -> None: ... +def find_metas(cls_node) -> Generator[tuple[Base, int, Base]]: ... +def fixup_indent(suite) -> None: ... + +class FixMetaclass(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_methodattrs.pyi b/stdlib/lib2to3/fixes/fix_methodattrs.pyi new file mode 100644 index 000000000000..ca9b71e43f85 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_methodattrs.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +MAP: Final[dict[str, str]] + +class FixMethodattrs(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_ne.pyi b/stdlib/lib2to3/fixes/fix_ne.pyi new file mode 100644 index 000000000000..6ff1220b0472 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_ne.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNe(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + def match(self, node): ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_next.pyi b/stdlib/lib2to3/fixes/fix_next.pyi new file mode 100644 index 000000000000..b13914ae8c01 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_next.pyi @@ -0,0 +1,19 @@ +from _typeshed import StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +bind_warning: str + +class FixNext(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + order: ClassVar[Literal["pre"]] + shadowed_next: bool + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results) -> None: ... + +def is_assign_target(node): ... +def find_assign(node): ... +def is_subtree(root, node): ... diff --git a/stdlib/lib2to3/fixes/fix_nonzero.pyi b/stdlib/lib2to3/fixes/fix_nonzero.pyi new file mode 100644 index 000000000000..5c37fc12ef08 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_nonzero.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNonzero(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_numliterals.pyi b/stdlib/lib2to3/fixes/fix_numliterals.pyi new file mode 100644 index 000000000000..113145e395f6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_numliterals.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixNumliterals(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + def match(self, node): ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_operator.pyi b/stdlib/lib2to3/fixes/fix_operator.pyi new file mode 100644 index 000000000000..b9863d38347b --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_operator.pyi @@ -0,0 +1,12 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +def invocation(s): ... + +class FixOperator(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + methods: str + obj: str + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_paren.pyi b/stdlib/lib2to3/fixes/fix_paren.pyi new file mode 100644 index 000000000000..237df6c5ff2c --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_paren.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixParen(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_print.pyi b/stdlib/lib2to3/fixes/fix_print.pyi new file mode 100644 index 000000000000..e9564b04ac75 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_print.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from .. import fixer_base + +parend_expr: Incomplete + +class FixPrint(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + def add_kwarg(self, l_nodes, s_kwd, n_expr) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_raise.pyi b/stdlib/lib2to3/fixes/fix_raise.pyi new file mode 100644 index 000000000000..e02c3080f409 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_raise.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRaise(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_raw_input.pyi b/stdlib/lib2to3/fixes/fix_raw_input.pyi new file mode 100644 index 000000000000..d1a0eb0e0a7e --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_raw_input.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRawInput(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_reduce.pyi b/stdlib/lib2to3/fixes/fix_reduce.pyi new file mode 100644 index 000000000000..f8ad876c21a6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_reduce.pyi @@ -0,0 +1,8 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixReduce(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_reload.pyi b/stdlib/lib2to3/fixes/fix_reload.pyi new file mode 100644 index 000000000000..820075438eca --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_reload.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixReload(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_renames.pyi b/stdlib/lib2to3/fixes/fix_renames.pyi new file mode 100644 index 000000000000..f095b3083ba8 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_renames.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from .. import fixer_base + +MAPPING: Final[dict[str, dict[str, str]]] +LOOKUP: Final[dict[tuple[str, str], str]] + +def alternates(members): ... +def build_pattern() -> Generator[str]: ... + +class FixRenames(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + order: ClassVar[Literal["pre"]] + PATTERN: ClassVar[str] + def match(self, node): ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_repr.pyi b/stdlib/lib2to3/fixes/fix_repr.pyi new file mode 100644 index 000000000000..3b192d396dd6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_repr.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixRepr(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_set_literal.pyi b/stdlib/lib2to3/fixes/fix_set_literal.pyi new file mode 100644 index 000000000000..6962ff326f56 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_set_literal.pyi @@ -0,0 +1,7 @@ +from lib2to3 import fixer_base +from typing import ClassVar, Literal + +class FixSetLiteral(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_standarderror.pyi b/stdlib/lib2to3/fixes/fix_standarderror.pyi new file mode 100644 index 000000000000..ba914bcab5d6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_standarderror.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixStandarderror(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_sys_exc.pyi b/stdlib/lib2to3/fixes/fix_sys_exc.pyi new file mode 100644 index 000000000000..0fa1a4787087 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_sys_exc.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixSysExc(fixer_base.BaseFix): + exc_info: ClassVar[list[str]] + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_throw.pyi b/stdlib/lib2to3/fixes/fix_throw.pyi new file mode 100644 index 000000000000..4c99855e5c37 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_throw.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixThrow(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_tuple_params.pyi b/stdlib/lib2to3/fixes/fix_tuple_params.pyi new file mode 100644 index 000000000000..7f4f7f4e8656 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_tuple_params.pyi @@ -0,0 +1,16 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +def is_docstring(stmt): ... + +class FixTupleParams(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... + def transform_lambda(self, node, results) -> None: ... + +def simplify_args(node): ... +def find_params(node): ... +def map_to_index(param_list, prefix=[], d=None): ... +def tuple_name(param_list): ... diff --git a/stdlib/lib2to3/fixes/fix_types.pyi b/stdlib/lib2to3/fixes/fix_types.pyi new file mode 100644 index 000000000000..e26dbec71a97 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_types.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixTypes(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_unicode.pyi b/stdlib/lib2to3/fixes/fix_unicode.pyi new file mode 100644 index 000000000000..85d1315213b9 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_unicode.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +class FixUnicode(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + unicode_literals: bool + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_urllib.pyi b/stdlib/lib2to3/fixes/fix_urllib.pyi new file mode 100644 index 000000000000..ab84114f90ea --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_urllib.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator +from typing import Final, Literal + +from .fix_imports import FixImports + +MAPPING: Final[dict[str, list[tuple[Literal["urllib.request", "urllib.parse", "urllib.error"], list[str]]]]] + +def build_pattern() -> Generator[str]: ... + +class FixUrllib(FixImports): + def build_pattern(self): ... + def transform_import(self, node, results) -> None: ... + def transform_member(self, node, results): ... + def transform_dot(self, node, results) -> None: ... + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_ws_comma.pyi b/stdlib/lib2to3/fixes/fix_ws_comma.pyi new file mode 100644 index 000000000000..4ce5cb2c4ac1 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_ws_comma.pyi @@ -0,0 +1,12 @@ +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Leaf + +class FixWsComma(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[False]] + PATTERN: ClassVar[str] + COMMA: Leaf + COLON: Leaf + SEPS: tuple[Leaf, Leaf] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/fixes/fix_xrange.pyi b/stdlib/lib2to3/fixes/fix_xrange.pyi new file mode 100644 index 000000000000..71318b7660b6 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_xrange.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete, StrPath +from typing import ClassVar, Literal + +from .. import fixer_base +from ..pytree import Node + +class FixXrange(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + transformed_xranges: set[Incomplete] | None + def start_tree(self, tree: Node, filename: StrPath) -> None: ... + def finish_tree(self, tree: Node, filename: StrPath) -> None: ... + def transform(self, node, results): ... + def transform_xrange(self, node, results) -> None: ... + def transform_range(self, node, results): ... + P1: ClassVar[str] + p1: ClassVar[Incomplete] + P2: ClassVar[str] + p2: ClassVar[Incomplete] + def in_special_context(self, node): ... diff --git a/stdlib/lib2to3/fixes/fix_xreadlines.pyi b/stdlib/lib2to3/fixes/fix_xreadlines.pyi new file mode 100644 index 000000000000..b4794143a003 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_xreadlines.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixXreadlines(fixer_base.BaseFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + def transform(self, node, results) -> None: ... diff --git a/stdlib/lib2to3/fixes/fix_zip.pyi b/stdlib/lib2to3/fixes/fix_zip.pyi new file mode 100644 index 000000000000..805886ee3180 --- /dev/null +++ b/stdlib/lib2to3/fixes/fix_zip.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Literal + +from .. import fixer_base + +class FixZip(fixer_base.ConditionalFix): + BM_compatible: ClassVar[Literal[True]] + PATTERN: ClassVar[str] + skip_on: ClassVar[Literal["future_builtins.zip"]] + def transform(self, node, results): ... diff --git a/stdlib/lib2to3/main.pyi b/stdlib/lib2to3/main.pyi new file mode 100644 index 000000000000..5b7fdfca5d65 --- /dev/null +++ b/stdlib/lib2to3/main.pyi @@ -0,0 +1,42 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Container, Iterable, Iterator, Mapping, Sequence +from logging import _ExcInfoType +from typing import AnyStr, Literal + +from . import refactor as refactor + +def diff_texts(a: str, b: str, filename: str) -> Iterator[str]: ... + +class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): + nobackups: bool + show_diffs: bool + def __init__( + self, + fixers: Iterable[str], + options: Mapping[str, object] | None, + explicit: Container[str] | None, + nobackups: bool, + show_diffs: bool, + input_base_dir: str = "", + output_dir: str = "", + append_suffix: str = "", + ) -> None: ... + # Same as super.log_error and Logger.error + def log_error( # type: ignore[override] + self, + msg: str, + *args: Iterable[str], + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + # Same as super.write_file but without default values + def write_file( # type: ignore[override] + self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None + ) -> None: ... + # filename has to be str + def print_output(self, old: str, new: str, filename: str, equal: bool) -> None: ... # type: ignore[override] + +def warn(msg: object) -> None: ... +def main(fixer_pkg: str, args: Sequence[AnyStr] | None = None) -> Literal[0, 1, 2]: ... diff --git a/stdlib/lib2to3/pgen2/__init__.pyi b/stdlib/lib2to3/pgen2/__init__.pyi new file mode 100644 index 000000000000..3b1cbef7727d --- /dev/null +++ b/stdlib/lib2to3/pgen2/__init__.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import Any, TypeAlias + +from ..pytree import _RawNode +from .grammar import Grammar + +# This is imported in several lib2to3/pgen2 submodules +_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any] # noqa: Y047 diff --git a/stdlib/lib2to3/pgen2/driver.pyi b/stdlib/lib2to3/pgen2/driver.pyi new file mode 100644 index 000000000000..dea13fb9d0f8 --- /dev/null +++ b/stdlib/lib2to3/pgen2/driver.pyi @@ -0,0 +1,27 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from logging import Logger +from typing import IO + +from ..pytree import _NL +from . import _Convert +from .grammar import Grammar + +__all__ = ["Driver", "load_grammar"] + +class Driver: + grammar: Grammar + logger: Logger + convert: _Convert + def __init__(self, grammar: Grammar, convert: _Convert | None = None, logger: Logger | None = None) -> None: ... + def parse_tokens( + self, tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]], debug: bool = False + ) -> _NL: ... + def parse_stream_raw(self, stream: IO[str], debug: bool = False) -> _NL: ... + def parse_stream(self, stream: IO[str], debug: bool = False) -> _NL: ... + def parse_file(self, filename: StrPath, encoding: str | None = None, debug: bool = False) -> _NL: ... + def parse_string(self, text: str, debug: bool = False) -> _NL: ... + +def load_grammar( + gt: str = "Grammar.txt", gp: str | None = None, save: bool = True, force: bool = False, logger: Logger | None = None +) -> Grammar: ... diff --git a/stdlib/lib2to3/pgen2/grammar.pyi b/stdlib/lib2to3/pgen2/grammar.pyi new file mode 100644 index 000000000000..5093422ae236 --- /dev/null +++ b/stdlib/lib2to3/pgen2/grammar.pyi @@ -0,0 +1,25 @@ +from _typeshed import StrPath +from typing import TypeAlias +from typing_extensions import Self + +_Label: TypeAlias = tuple[int, str | None] +_DFA: TypeAlias = list[list[tuple[int, int]]] +_DFAS: TypeAlias = tuple[_DFA, dict[int, int]] + +class Grammar: + symbol2number: dict[str, int] + number2symbol: dict[int, str] + states: list[_DFA] + dfas: dict[int, _DFAS] + labels: list[_Label] + keywords: dict[str, int] + tokens: dict[int, int] + symbol2label: dict[str, int] + start: int + def dump(self, filename: StrPath) -> None: ... + def load(self, filename: StrPath) -> None: ... + def copy(self) -> Self: ... + def report(self) -> None: ... + +opmap_raw: str +opmap: dict[str, str] diff --git a/stdlib/lib2to3/pgen2/literals.pyi b/stdlib/lib2to3/pgen2/literals.pyi new file mode 100644 index 000000000000..c3fabe8a5177 --- /dev/null +++ b/stdlib/lib2to3/pgen2/literals.pyi @@ -0,0 +1,7 @@ +from re import Match + +simple_escapes: dict[str, str] + +def escape(m: Match[str]) -> str: ... +def evalString(s: str) -> str: ... +def test() -> None: ... diff --git a/stdlib/lib2to3/pgen2/parse.pyi b/stdlib/lib2to3/pgen2/parse.pyi new file mode 100644 index 000000000000..9befe9bf879d --- /dev/null +++ b/stdlib/lib2to3/pgen2/parse.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import TypeAlias + +from ..pytree import _NL, _RawNode +from . import _Convert +from .grammar import _DFAS, Grammar + +_Context: TypeAlias = Sequence[Incomplete] + +class ParseError(Exception): + msg: str + type: int + value: str | None + context: _Context + def __init__(self, msg: str, type: int, value: str | None, context: _Context) -> None: ... + +class Parser: + grammar: Grammar + convert: _Convert + stack: list[tuple[_DFAS, int, _RawNode]] + rootnode: _NL | None + used_names: set[str] + def __init__(self, grammar: Grammar, convert: _Convert | None = None) -> None: ... + def setup(self, start: int | None = None) -> None: ... + def addtoken(self, type: int, value: str | None, context: _Context) -> bool: ... + def classify(self, type: int, value: str | None, context: _Context) -> int: ... + def shift(self, type: int, value: str | None, newstate: int, context: _Context) -> None: ... + def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ... + def pop(self) -> None: ... diff --git a/stdlib/lib2to3/pgen2/pgen.pyi b/stdlib/lib2to3/pgen2/pgen.pyi new file mode 100644 index 000000000000..e0e2b8593a34 --- /dev/null +++ b/stdlib/lib2to3/pgen2/pgen.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Iterator +from typing import IO, ClassVar, overload +from typing_extensions import Never + +from . import grammar +from .tokenize import _TokenInfo + +class PgenGrammar(grammar.Grammar): ... + +class ParserGenerator: + filename: StrPath + stream: IO[str] + generator: Iterator[_TokenInfo] + first: dict[str, dict[str, int]] + def __init__(self, filename: StrPath, stream: IO[str] | None = None) -> None: ... + def make_grammar(self) -> PgenGrammar: ... + def make_first(self, c: PgenGrammar, name: str) -> dict[int, int]: ... + def make_label(self, c: PgenGrammar, label: str) -> int: ... + def addfirstsets(self) -> None: ... + def calcfirst(self, name: str) -> None: ... + def parse(self) -> tuple[dict[str, list[DFAState]], str]: ... + def make_dfa(self, start: NFAState, finish: NFAState) -> list[DFAState]: ... + def dump_nfa(self, name: str, start: NFAState, finish: NFAState) -> list[DFAState]: ... + def dump_dfa(self, name: str, dfa: Iterable[DFAState]) -> None: ... + def simplify_dfa(self, dfa: list[DFAState]) -> None: ... + def parse_rhs(self) -> tuple[NFAState, NFAState]: ... + def parse_alt(self) -> tuple[NFAState, NFAState]: ... + def parse_item(self) -> tuple[NFAState, NFAState]: ... + def parse_atom(self) -> tuple[NFAState, NFAState]: ... + def expect(self, type: int, value: str | None = None) -> str: ... + def gettoken(self) -> None: ... + + @overload + def raise_error(self, msg: object) -> Never: ... + @overload + def raise_error(self, msg: str, *args: object) -> Never: ... + +class NFAState: + arcs: list[tuple[str | None, NFAState]] + def addarc(self, next: NFAState, label: str | None = None) -> None: ... + +class DFAState: + nfaset: dict[NFAState, Incomplete] + isfinal: bool + arcs: dict[str, DFAState] + def __init__(self, nfaset: dict[NFAState, Incomplete], final: NFAState) -> None: ... + def addarc(self, next: DFAState, label: str) -> None: ... + def unifystate(self, old: DFAState, new: DFAState) -> None: ... + def __eq__(self, other: DFAState) -> bool: ... # type: ignore[override] + __hash__: ClassVar[None] # type: ignore[assignment] + +def generate_grammar(filename: StrPath = "Grammar.txt") -> PgenGrammar: ... diff --git a/stdlib/lib2to3/pgen2/token.pyi b/stdlib/lib2to3/pgen2/token.pyi new file mode 100644 index 000000000000..6898517acee6 --- /dev/null +++ b/stdlib/lib2to3/pgen2/token.pyi @@ -0,0 +1,69 @@ +from typing import Final + +ENDMARKER: Final[int] +NAME: Final[int] +NUMBER: Final[int] +STRING: Final[int] +NEWLINE: Final[int] +INDENT: Final[int] +DEDENT: Final[int] +LPAR: Final[int] +RPAR: Final[int] +LSQB: Final[int] +RSQB: Final[int] +COLON: Final[int] +COMMA: Final[int] +SEMI: Final[int] +PLUS: Final[int] +MINUS: Final[int] +STAR: Final[int] +SLASH: Final[int] +VBAR: Final[int] +AMPER: Final[int] +LESS: Final[int] +GREATER: Final[int] +EQUAL: Final[int] +DOT: Final[int] +PERCENT: Final[int] +BACKQUOTE: Final[int] +LBRACE: Final[int] +RBRACE: Final[int] +EQEQUAL: Final[int] +NOTEQUAL: Final[int] +LESSEQUAL: Final[int] +GREATEREQUAL: Final[int] +TILDE: Final[int] +CIRCUMFLEX: Final[int] +LEFTSHIFT: Final[int] +RIGHTSHIFT: Final[int] +DOUBLESTAR: Final[int] +PLUSEQUAL: Final[int] +MINEQUAL: Final[int] +STAREQUAL: Final[int] +SLASHEQUAL: Final[int] +PERCENTEQUAL: Final[int] +AMPEREQUAL: Final[int] +VBAREQUAL: Final[int] +CIRCUMFLEXEQUAL: Final[int] +LEFTSHIFTEQUAL: Final[int] +RIGHTSHIFTEQUAL: Final[int] +DOUBLESTAREQUAL: Final[int] +DOUBLESLASH: Final[int] +DOUBLESLASHEQUAL: Final[int] +OP: Final[int] +COMMENT: Final[int] +NL: Final[int] +RARROW: Final[int] +AT: Final[int] +ATEQUAL: Final[int] +AWAIT: Final[int] +ASYNC: Final[int] +ERRORTOKEN: Final[int] +COLONEQUAL: Final[int] +N_TOKENS: Final[int] +NT_OFFSET: Final[int] +tok_name: dict[int, str] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/stdlib/lib2to3/pgen2/tokenize.pyi b/stdlib/lib2to3/pgen2/tokenize.pyi new file mode 100644 index 000000000000..76ff733163af --- /dev/null +++ b/stdlib/lib2to3/pgen2/tokenize.pyi @@ -0,0 +1,96 @@ +from collections.abc import Callable, Iterable, Iterator +from typing import TypeAlias + +from .token import * + +__all__ = [ + "AMPER", + "AMPEREQUAL", + "ASYNC", + "AT", + "ATEQUAL", + "AWAIT", + "BACKQUOTE", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", + "tokenize", + "generate_tokens", + "untokenize", + "COLONEQUAL", +] + +_Coord: TypeAlias = tuple[int, int] +_TokenEater: TypeAlias = Callable[[int, str, _Coord, _Coord, str], object] +_TokenInfo: TypeAlias = tuple[int, str, _Coord, _Coord, str] + +class TokenError(Exception): ... +class StopTokenizing(Exception): ... + +def tokenize(readline: Callable[[], str], tokeneater: _TokenEater = ...) -> None: ... + +class Untokenizer: + tokens: list[str] + prev_row: int + prev_col: int + def add_whitespace(self, start: _Coord) -> None: ... + def untokenize(self, iterable: Iterable[_TokenInfo]) -> str: ... + def compat(self, token: tuple[int, str], iterable: Iterable[_TokenInfo]) -> None: ... + +def untokenize(iterable: Iterable[_TokenInfo]) -> str: ... +def generate_tokens(readline: Callable[[], str]) -> Iterator[_TokenInfo]: ... diff --git a/stdlib/lib2to3/pygram.pyi b/stdlib/lib2to3/pygram.pyi new file mode 100644 index 000000000000..86c74b54888a --- /dev/null +++ b/stdlib/lib2to3/pygram.pyi @@ -0,0 +1,114 @@ +from .pgen2.grammar import Grammar + +class Symbols: + def __init__(self, grammar: Grammar) -> None: ... + +class python_symbols(Symbols): + and_expr: int + and_test: int + annassign: int + arglist: int + argument: int + arith_expr: int + assert_stmt: int + async_funcdef: int + async_stmt: int + atom: int + augassign: int + break_stmt: int + classdef: int + comp_for: int + comp_if: int + comp_iter: int + comp_op: int + comparison: int + compound_stmt: int + continue_stmt: int + decorated: int + decorator: int + decorators: int + del_stmt: int + dictsetmaker: int + dotted_as_name: int + dotted_as_names: int + dotted_name: int + encoding_decl: int + eval_input: int + except_clause: int + exec_stmt: int + expr: int + expr_stmt: int + exprlist: int + factor: int + file_input: int + flow_stmt: int + for_stmt: int + funcdef: int + global_stmt: int + if_stmt: int + import_as_name: int + import_as_names: int + import_from: int + import_name: int + import_stmt: int + lambdef: int + listmaker: int + not_test: int + old_lambdef: int + old_test: int + or_test: int + parameters: int + pass_stmt: int + power: int + print_stmt: int + raise_stmt: int + return_stmt: int + shift_expr: int + simple_stmt: int + single_input: int + sliceop: int + small_stmt: int + star_expr: int + stmt: int + subscript: int + subscriptlist: int + suite: int + term: int + test: int + testlist: int + testlist1: int + testlist_gexp: int + testlist_safe: int + testlist_star_expr: int + tfpdef: int + tfplist: int + tname: int + trailer: int + try_stmt: int + typedargslist: int + varargslist: int + vfpdef: int + vfplist: int + vname: int + while_stmt: int + with_item: int + with_stmt: int + with_var: int + xor_expr: int + yield_arg: int + yield_expr: int + yield_stmt: int + +class pattern_symbols(Symbols): + Alternative: int + Alternatives: int + Details: int + Matcher: int + NegatedUnit: int + Repeater: int + Unit: int + +python_grammar: Grammar +python_grammar_no_print_statement: Grammar +python_grammar_no_print_and_exec_statement: Grammar +pattern_grammar: Grammar diff --git a/stdlib/lib2to3/pytree.pyi b/stdlib/lib2to3/pytree.pyi new file mode 100644 index 000000000000..f634f5065c0e --- /dev/null +++ b/stdlib/lib2to3/pytree.pyi @@ -0,0 +1,118 @@ +from _typeshed import SupportsGetItem, SupportsLenAndGetItem, Unused +from abc import abstractmethod +from collections.abc import Iterable, Iterator, MutableSequence +from typing import ClassVar, Final, TypeAlias +from typing_extensions import Self + +from .fixer_base import BaseFix +from .pgen2.grammar import Grammar + +_NL: TypeAlias = Node | Leaf +_Context: TypeAlias = tuple[str, int, int] +_Results: TypeAlias = dict[str, _NL] +_RawNode: TypeAlias = tuple[int, str, _Context, list[_NL] | None] + +HUGE: Final = 0x7FFFFFFF + +def type_repr(type_num: int) -> str | int: ... + +class Base: + type: int + parent: Node | None + prefix: str + children: list[_NL] + was_changed: bool + was_checked: bool + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + @abstractmethod + def _eq(self, other: Base) -> bool: ... + @abstractmethod + def clone(self) -> Self: ... + @abstractmethod + def post_order(self) -> Iterator[Self]: ... + @abstractmethod + def pre_order(self) -> Iterator[Self]: ... + def replace(self, new: _NL | list[_NL]) -> None: ... + def get_lineno(self) -> int: ... + def changed(self) -> None: ... + def remove(self) -> int | None: ... + @property + def next_sibling(self) -> _NL | None: ... + @property + def prev_sibling(self) -> _NL | None: ... + def leaves(self) -> Iterator[Leaf]: ... + def depth(self) -> int: ... + def get_suffix(self) -> str: ... + +class Node(Base): + fixers_applied: MutableSequence[BaseFix] | None + # Is Unbound until set in refactor.RefactoringTool + future_features: frozenset[str] + # Is Unbound until set in pgen2.parse.Parser.pop + used_names: set[str] + def __init__( + self, + type: int, + children: Iterable[_NL], + context: Unused = None, + prefix: str | None = None, + fixers_applied: MutableSequence[BaseFix] | None = None, + ) -> None: ... + def _eq(self, other: Base) -> bool: ... + def clone(self) -> Node: ... + def post_order(self) -> Iterator[Self]: ... + def pre_order(self) -> Iterator[Self]: ... + def set_child(self, i: int, child: _NL) -> None: ... + def insert_child(self, i: int, child: _NL) -> None: ... + def append_child(self, child: _NL) -> None: ... + def __unicode__(self) -> str: ... + +class Leaf(Base): + lineno: int + column: int + value: str + fixers_applied: MutableSequence[BaseFix] + def __init__( + self, + type: int, + value: str, + context: _Context | None = None, + prefix: str | None = None, + fixers_applied: MutableSequence[BaseFix] = [], + ) -> None: ... + def _eq(self, other: Base) -> bool: ... + def clone(self) -> Leaf: ... + def post_order(self) -> Iterator[Self]: ... + def pre_order(self) -> Iterator[Self]: ... + def __unicode__(self) -> str: ... + +def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... + +class BasePattern: + type: int + content: str | None + name: str | None + def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns + def match(self, node: _NL, results: _Results | None = None) -> bool: ... + def match_seq(self, nodes: SupportsLenAndGetItem[_NL], results: _Results | None = None) -> bool: ... + def generate_matches(self, nodes: SupportsGetItem[int, _NL]) -> Iterator[tuple[int, _Results]]: ... + +class LeafPattern(BasePattern): + def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ... + +class NodePattern(BasePattern): + wildcards: bool + def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ... + +class WildcardPattern(BasePattern): + min: int + max: int + def __init__(self, content: str | None = None, min: int = 0, max: int = 0x7FFFFFFF, name: str | None = None) -> None: ... + +class NegatedPattern(BasePattern): + def __init__(self, content: str | None = None) -> None: ... + +def generate_matches( + patterns: SupportsGetItem[int | slice, BasePattern] | None, nodes: SupportsGetItem[int | slice, _NL] +) -> Iterator[tuple[int, _Results]]: ... diff --git a/stdlib/lib2to3/refactor.pyi b/stdlib/lib2to3/refactor.pyi new file mode 100644 index 000000000000..b365d64a1de1 --- /dev/null +++ b/stdlib/lib2to3/refactor.pyi @@ -0,0 +1,86 @@ +from _typeshed import FileDescriptorOrPath, StrPath, SupportsGetItem +from collections.abc import Container, Generator, Iterable, Mapping +from logging import Logger, _ExcInfoType +from multiprocessing import JoinableQueue +from multiprocessing.synchronize import Lock +from typing import Any, ClassVar, Final, overload +from typing_extensions import Never + +from .btm_matcher import BottomMatcher +from .fixer_base import BaseFix +from .pgen2.driver import Driver +from .pgen2.grammar import Grammar +from .pytree import Node + +def get_all_fix_names(fixer_pkg: str, remove_prefix: bool = True) -> list[str]: ... +def get_fixers_from_package(pkg_name: str) -> list[str]: ... + +class FixerError(Exception): ... + +class RefactoringTool: + CLASS_PREFIX: ClassVar[str] + FILE_PREFIX: ClassVar[str] + fixers: Iterable[str] + explicit: Container[str] + options: dict[str, Any] + grammar: Grammar + write_unchanged_files: bool + errors: list[tuple[str, Iterable[str], dict[str, _ExcInfoType]]] + logger: Logger + fixer_log: list[str] + wrote: bool + driver: Driver + pre_order: list[BaseFix] + post_order: list[BaseFix] + files: list[StrPath] + BM: BottomMatcher + bmi_pre_order: list[BaseFix] + bmi_post_order: list[BaseFix] + def __init__( + self, fixer_names: Iterable[str], options: Mapping[str, object] | None = None, explicit: Container[str] | None = None + ) -> None: ... + def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: ... + def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> Never: ... + + @overload + def log_message(self, msg: object) -> None: ... + @overload + def log_message(self, msg: str, *args: object) -> None: ... + + @overload + def log_debug(self, msg: object) -> None: ... + @overload + def log_debug(self, msg: str, *args: object) -> None: ... + + def print_output(self, old_text: str, new_text: str, filename: StrPath, equal: bool) -> None: ... + def refactor(self, items: Iterable[str], write: bool = False, doctests_only: bool = False) -> None: ... + def refactor_dir(self, dir_name: str, write: bool = False, doctests_only: bool = False) -> None: ... + def _read_python_source(self, filename: FileDescriptorOrPath) -> tuple[str, str]: ... + def refactor_file(self, filename: StrPath, write: bool = False, doctests_only: bool = False) -> None: ... + def refactor_string(self, data: str, name: str) -> Node | None: ... + def refactor_stdin(self, doctests_only: bool = False) -> None: ... + def refactor_tree(self, tree: Node, name: str) -> bool: ... + def traverse_by(self, fixers: SupportsGetItem[int, Iterable[BaseFix]] | None, traversal: Iterable[Node]) -> None: ... + def processed_file( + self, new_text: str, filename: StrPath, old_text: str | None = None, write: bool = False, encoding: str | None = None + ) -> None: ... + def write_file(self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None = None) -> None: ... + PS1: Final = ">>> " + PS2: Final = "... " + def refactor_docstring(self, input: str, filename: StrPath) -> str: ... + def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: StrPath) -> list[str]: ... + def summarize(self) -> None: ... + def parse_block(self, block: Iterable[str], lineno: int, indent: int) -> Node: ... + def wrap_toks( + self, block: Iterable[str], lineno: int, indent: int + ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str]]: ... + def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str]: ... + +class MultiprocessingUnsupported(Exception): ... + +class MultiprocessRefactoringTool(RefactoringTool): + queue: JoinableQueue[None | tuple[Iterable[str], bool | int]] | None + output_lock: Lock | None + def refactor( + self, items: Iterable[str], write: bool = False, doctests_only: bool = False, num_processes: int = 1 + ) -> None: ... diff --git a/stdlib/linecache.pyi b/stdlib/linecache.pyi new file mode 100644 index 000000000000..f527e7084ced --- /dev/null +++ b/stdlib/linecache.pyi @@ -0,0 +1,18 @@ +from collections.abc import Callable +from typing import Any, TypeAlias + +__all__ = ["getline", "clearcache", "checkcache", "lazycache"] + +_ModuleGlobals: TypeAlias = dict[str, Any] +_ModuleMetadata: TypeAlias = tuple[int, float | None, list[str], str] + +_SourceLoader: TypeAlias = tuple[Callable[[], str | None]] + +cache: dict[str, _SourceLoader | _ModuleMetadata] # undocumented + +def getline(filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> str: ... +def clearcache() -> None: ... +def getlines(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ... +def checkcache(filename: str | None = None) -> None: ... +def updatecache(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ... +def lazycache(filename: str, module_globals: _ModuleGlobals) -> bool: ... diff --git a/stdlib/locale.pyi b/stdlib/locale.pyi new file mode 100644 index 000000000000..d234a08d779c --- /dev/null +++ b/stdlib/locale.pyi @@ -0,0 +1,160 @@ +import sys +from _locale import ( + CHAR_MAX as CHAR_MAX, + LC_ALL as LC_ALL, + LC_COLLATE as LC_COLLATE, + LC_CTYPE as LC_CTYPE, + LC_MONETARY as LC_MONETARY, + LC_NUMERIC as LC_NUMERIC, + LC_TIME as LC_TIME, + localeconv as localeconv, + strcoll as strcoll, + strxfrm as strxfrm, +) + +# This module defines a function "str()", which is why "str" can't be used +# as a type annotation or type alias. +from builtins import str as _str +from collections.abc import Callable, Iterable +from decimal import Decimal +from typing import Any +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + from _locale import getencoding as getencoding + +# Some parts of the `_locale` module are platform-specific: +if sys.platform != "win32": + from _locale import ( + ABDAY_1 as ABDAY_1, + ABDAY_2 as ABDAY_2, + ABDAY_3 as ABDAY_3, + ABDAY_4 as ABDAY_4, + ABDAY_5 as ABDAY_5, + ABDAY_6 as ABDAY_6, + ABDAY_7 as ABDAY_7, + ABMON_1 as ABMON_1, + ABMON_2 as ABMON_2, + ABMON_3 as ABMON_3, + ABMON_4 as ABMON_4, + ABMON_5 as ABMON_5, + ABMON_6 as ABMON_6, + ABMON_7 as ABMON_7, + ABMON_8 as ABMON_8, + ABMON_9 as ABMON_9, + ABMON_10 as ABMON_10, + ABMON_11 as ABMON_11, + ABMON_12 as ABMON_12, + ALT_DIGITS as ALT_DIGITS, + AM_STR as AM_STR, + CODESET as CODESET, + CRNCYSTR as CRNCYSTR, + D_FMT as D_FMT, + D_T_FMT as D_T_FMT, + DAY_1 as DAY_1, + DAY_2 as DAY_2, + DAY_3 as DAY_3, + DAY_4 as DAY_4, + DAY_5 as DAY_5, + DAY_6 as DAY_6, + DAY_7 as DAY_7, + ERA as ERA, + ERA_D_FMT as ERA_D_FMT, + ERA_D_T_FMT as ERA_D_T_FMT, + ERA_T_FMT as ERA_T_FMT, + LC_MESSAGES as LC_MESSAGES, + MON_1 as MON_1, + MON_2 as MON_2, + MON_3 as MON_3, + MON_4 as MON_4, + MON_5 as MON_5, + MON_6 as MON_6, + MON_7 as MON_7, + MON_8 as MON_8, + MON_9 as MON_9, + MON_10 as MON_10, + MON_11 as MON_11, + MON_12 as MON_12, + NOEXPR as NOEXPR, + PM_STR as PM_STR, + RADIXCHAR as RADIXCHAR, + T_FMT as T_FMT, + T_FMT_AMPM as T_FMT_AMPM, + THOUSEP as THOUSEP, + YESEXPR as YESEXPR, + bind_textdomain_codeset as bind_textdomain_codeset, + bindtextdomain as bindtextdomain, + dcgettext as dcgettext, + dgettext as dgettext, + gettext as gettext, + nl_langinfo as nl_langinfo, + textdomain as textdomain, + ) + +__all__ = [ + "getlocale", + "getdefaultlocale", + "getpreferredencoding", + "Error", + "setlocale", + "localeconv", + "strcoll", + "strxfrm", + "str", + "atof", + "atoi", + "format_string", + "currency", + "normalize", + "LC_CTYPE", + "LC_COLLATE", + "LC_TIME", + "LC_MONETARY", + "LC_NUMERIC", + "LC_ALL", + "CHAR_MAX", +] + +if sys.version_info >= (3, 11): + __all__ += ["getencoding"] + +if sys.version_info < (3, 12): + __all__ += ["format"] + +if sys.version_info < (3, 13): + __all__ += ["resetlocale"] + +if sys.platform != "win32": + __all__ += ["LC_MESSAGES"] + +class Error(Exception): ... + +def getdefaultlocale( + envvars: tuple[_str, ...] = ("LC_ALL", "LC_CTYPE", "LANG", "LANGUAGE") +) -> tuple[_str | None, _str | None]: ... +def getlocale(category: int = ...) -> tuple[_str | None, _str | None]: ... +def setlocale(category: int, locale: _str | Iterable[_str | None] | None = None) -> _str: ... +def getpreferredencoding(do_setlocale: bool = True) -> _str: ... +def normalize(localename: _str) -> _str: ... + +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") + def resetlocale(category: int = ...) -> None: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.7; removed in Python 3.12. Use `locale.format_string()` instead.") + def format( + percent: _str, value: float | Decimal, grouping: bool = False, monetary: bool = False, *additional: Any + ) -> _str: ... + +def format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = False) -> _str: ... +def currency(val: float | Decimal, symbol: bool = True, grouping: bool = False, international: bool = False) -> _str: ... +def delocalize(string: _str) -> _str: ... +def localize(string: _str, grouping: bool = False, monetary: bool = False) -> _str: ... +def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... +def atoi(string: _str) -> int: ... +def str(val: float) -> _str: ... + +locale_alias: dict[_str, _str] # undocumented +locale_encoding_alias: dict[_str, _str] # undocumented +windows_locale: dict[int, _str] # undocumented diff --git a/stdlib/logging/__init__.pyi b/stdlib/logging/__init__.pyi new file mode 100644 index 000000000000..39bd64694a1e --- /dev/null +++ b/stdlib/logging/__init__.pyi @@ -0,0 +1,674 @@ +import sys +import threading +from _typeshed import StrPath, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from io import TextIOWrapper +from re import Pattern +from string import Template +from time import struct_time +from types import FrameType, GenericAlias, TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "BASIC_FORMAT", + "BufferingFormatter", + "CRITICAL", + "DEBUG", + "ERROR", + "FATAL", + "FileHandler", + "Filter", + "Formatter", + "Handler", + "INFO", + "LogRecord", + "Logger", + "LoggerAdapter", + "NOTSET", + "NullHandler", + "StreamHandler", + "WARN", + "WARNING", + "addLevelName", + "basicConfig", + "captureWarnings", + "critical", + "debug", + "disable", + "error", + "exception", + "fatal", + "getLevelName", + "getLogger", + "getLoggerClass", + "info", + "log", + "makeLogRecord", + "setLoggerClass", + "shutdown", + "warning", + "getLogRecordFactory", + "setLogRecordFactory", + "lastResort", + "raiseExceptions", + "warn", +] + +if sys.version_info >= (3, 11): + __all__ += ["getLevelNamesMapping"] +if sys.version_info >= (3, 12): + __all__ += ["getHandlerByName", "getHandlerNames"] + +_SysExcInfoType: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] | tuple[None, None, None] +_ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException +_ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] +_Level: TypeAlias = int | str +_FormatStyle: TypeAlias = Literal["%", "{", "$"] + +if sys.version_info >= (3, 12): + @type_check_only + class _SupportsFilter(Protocol): + def filter(self, record: LogRecord, /) -> bool | LogRecord: ... + + _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool | LogRecord] | _SupportsFilter +else: + @type_check_only + class _SupportsFilter(Protocol): + def filter(self, record: LogRecord, /) -> bool: ... + + _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool] | _SupportsFilter + +raiseExceptions: bool +logThreads: bool +logMultiprocessing: bool +logProcesses: bool +_srcfile: str | None + +def currentframe() -> FrameType: ... + +_levelToName: dict[int, str] +_nameToLevel: dict[str, int] + +class Filterer: + filters: list[_FilterType] + def addFilter(self, filter: _FilterType) -> None: ... + def removeFilter(self, filter: _FilterType) -> None: ... + if sys.version_info >= (3, 12): + def filter(self, record: LogRecord) -> bool | LogRecord: ... + else: + def filter(self, record: LogRecord) -> bool: ... + +class Manager: # undocumented + root: RootLogger + disable: int + emittedNoHandlerWarning: bool + loggerDict: dict[str, Logger | PlaceHolder] + loggerClass: type[Logger] | None + logRecordFactory: Callable[..., LogRecord] | None + def __init__(self, rootnode: RootLogger) -> None: ... + def getLogger(self, name: str) -> Logger: ... + def setLoggerClass(self, klass: type[Logger]) -> None: ... + def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ... + +class Logger(Filterer): + name: str # undocumented + level: int # undocumented + parent: Logger | None # undocumented + propagate: bool + handlers: list[Handler] # undocumented + disabled: bool # undocumented + root: ClassVar[RootLogger] # undocumented + manager: Manager # undocumented + def __init__(self, name: str, level: _Level = 0) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def getChild(self, suffix: str) -> Self: ... # see python/typing#980 + if sys.version_info >= (3, 12): + def getChildren(self) -> set[Logger]: ... + + def debug( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + @deprecated("Deprecated since Python 3.3. Use `Logger.warning()` instead.") + def warn( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + stacklevel: int = 1, + ) -> None: ... # undocumented + fatal = critical + def addHandler(self, hdlr: Handler) -> None: ... + def removeHandler(self, hdlr: Handler) -> None: ... + def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: ... + def handle(self, record: LogRecord) -> None: ... + def makeRecord( + self, + name: str, + level: int, + fn: str, + lno: int, + msg: object, + args: _ArgsType, + exc_info: _SysExcInfoType | None, + func: str | None = None, + extra: Mapping[str, object] | None = None, + sinfo: str | None = None, + ) -> LogRecord: ... + def hasHandlers(self) -> bool: ... + def callHandlers(self, record: LogRecord) -> None: ... # undocumented + +CRITICAL: Final = 50 +FATAL: Final = CRITICAL +ERROR: Final = 40 +WARNING: Final = 30 +WARN: Final = WARNING +INFO: Final = 20 +DEBUG: Final = 10 +NOTSET: Final = 0 + +class Handler(Filterer): + level: int # undocumented + formatter: Formatter | None # undocumented + lock: threading.RLock | None # undocumented + name: str | None # undocumented + def __init__(self, level: _Level = 0) -> None: ... + def get_name(self) -> str: ... # undocumented + def set_name(self, name: str) -> None: ... # undocumented + def createLock(self) -> None: ... + def acquire(self) -> None: ... + def release(self) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def setFormatter(self, fmt: Formatter | None) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def handle(self, record: LogRecord) -> bool: ... + def handleError(self, record: LogRecord) -> None: ... + def format(self, record: LogRecord) -> str: ... + def emit(self, record: LogRecord) -> None: ... + +if sys.version_info >= (3, 12): + def getHandlerByName(name: str) -> Handler | None: ... + def getHandlerNames() -> frozenset[str]: ... + +class Formatter: + converter: Callable[[float | None], struct_time] + _fmt: str | None # undocumented + datefmt: str | None # undocumented + _style: PercentStyle # undocumented + default_time_format: str + default_msec_format: str | None + + def __init__( + self, + fmt: str | None = None, + datefmt: str | None = None, + style: _FormatStyle = "%", + validate: bool = True, + *, + defaults: Mapping[str, Any] | None = None, + ) -> None: ... + def format(self, record: LogRecord) -> str: ... + def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ... + def formatException(self, ei: _SysExcInfoType) -> str: ... + def formatMessage(self, record: LogRecord) -> str: ... # undocumented + def formatStack(self, stack_info: str) -> str: ... + def usesTime(self) -> bool: ... # undocumented + +class BufferingFormatter: + linefmt: Formatter + def __init__(self, linefmt: Formatter | None = None) -> None: ... + def formatHeader(self, records: Sequence[LogRecord]) -> str: ... + def formatFooter(self, records: Sequence[LogRecord]) -> str: ... + def format(self, records: Sequence[LogRecord]) -> str: ... + +class Filter: + name: str # undocumented + nlen: int # undocumented + def __init__(self, name: str = "") -> None: ... + if sys.version_info >= (3, 12): + def filter(self, record: LogRecord) -> bool | LogRecord: ... + else: + def filter(self, record: LogRecord) -> bool: ... + +class LogRecord: + # args can be set to None by logging.handlers.QueueHandler + # (see https://bugs.python.org/issue44473) + args: _ArgsType | None + asctime: str + created: float + exc_info: _SysExcInfoType | None + exc_text: str | None + filename: str + funcName: str + levelname: str + levelno: int + lineno: int + module: str + msecs: float + # Only created when logging.Formatter.format is called. See #6132. + message: str + msg: str | Any # The runtime accepts any object, but will be a str in 99% of cases + name: str + pathname: str + process: int | None + processName: str | None + relativeCreated: float + stack_info: str | None + thread: int | None + threadName: str | None + if sys.version_info >= (3, 12): + taskName: str | None + + def __init__( + self, + name: str, + level: int, + pathname: str, + lineno: int, + msg: object, + args: _ArgsType | None, + exc_info: _SysExcInfoType | None, + func: str | None = None, + sinfo: str | None = None, + ) -> None: ... + def getMessage(self) -> str: ... + # Allows setting contextual information on LogRecord objects as per the docs, see #7833 + def __setattr__(self, name: str, value: Any, /) -> None: ... + +_L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) + +class LoggerAdapter(Generic[_L]): + logger: _L + manager: Manager # undocumented + extra: Mapping[str, object] | None + + if sys.version_info >= (3, 13): + def __init__(self, logger: _L, extra: Mapping[str, object] | None = None, merge_extra: bool = False) -> None: ... + else: + def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: ... + + if sys.version_info >= (3, 13): + merge_extra: bool + + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ... + def debug( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + @deprecated("Deprecated since Python 3.3. Use `LoggerAdapter.warning()` instead.") + def warn( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + **kwargs: object, + ) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def setLevel(self, level: _Level) -> None: ... + def hasHandlers(self) -> bool: ... + if sys.version_info >= (3, 11): + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + *, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + ) -> None: ... # undocumented + else: + def _log( + self, + level: int, + msg: object, + args: _ArgsType, + exc_info: _ExcInfoType | None = None, + extra: Mapping[str, object] | None = None, + stack_info: bool = False, + ) -> None: ... # undocumented + + @property + def name(self) -> str: ... # undocumented + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def getLogger(name: str | None = None) -> Logger: ... +def getLoggerClass() -> type[Logger]: ... +def getLogRecordFactory() -> Callable[..., LogRecord]: ... +def debug( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def info( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def warning( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +@deprecated("Deprecated since Python 3.3. Use `warning()` instead.") +def warn( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def error( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def critical( + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def exception( + msg: object, + *args: object, + exc_info: _ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... +def log( + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, +) -> None: ... + +fatal = critical + +def disable(level: int = 50) -> None: ... +def addLevelName(level: int, levelName: str) -> None: ... + +@overload +def getLevelName(level: int) -> str: ... +@overload +@deprecated("The str -> int case is considered a mistake.") +def getLevelName(level: str) -> Any: ... + +if sys.version_info >= (3, 11): + def getLevelNamesMapping() -> dict[str, int]: ... + +def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... + +@overload # handlers is non-None +def basicConfig( + *, + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + handlers: Iterable[Handler], + force: bool | None = False, +) -> None: ... +@overload # handlers is None, filename is passed (but possibly None) +def basicConfig( + *, + filename: StrPath | None, + filemode: str = "a", + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + handlers: None = None, + force: bool | None = False, + encoding: str | None = None, + errors: str | None = "backslashreplace", +) -> None: ... +@overload # handlers is None, filename is not passed +def basicConfig( + *, + format: str = ..., # default value depends on the value of `style` + datefmt: str | None = None, + style: _FormatStyle = "%", + level: _Level | None = None, + stream: SupportsWrite[str] | None = None, + handlers: None = None, + force: bool | None = False, +) -> None: ... + +def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented +def setLoggerClass(klass: type[Logger]) -> None: ... +def captureWarnings(capture: bool) -> None: ... +def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... + +lastResort: Handler | None + +_StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) + +class StreamHandler(Handler, Generic[_StreamT]): + stream: _StreamT # undocumented + terminator: str + + @overload + def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ... + @overload + def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + + def setStream(self, stream: _StreamT) -> _StreamT | None: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class FileHandler(StreamHandler[TextIOWrapper]): + baseFilename: str # undocumented + mode: str # undocumented + encoding: str | None # undocumented + delay: bool # undocumented + errors: str | None # undocumented + stream: TextIOWrapper | None # type: ignore[assignment] # None when delay=True or after close() + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... + def _open(self) -> TextIOWrapper: ... # undocumented + +class NullHandler(Handler): ... + +class PlaceHolder: # undocumented + loggerMap: dict[Logger, None] + def __init__(self, alogger: Logger) -> None: ... + def append(self, alogger: Logger) -> None: ... + +# Below aren't in module docs but still visible + +class RootLogger(Logger): + def __init__(self, level: int) -> None: ... + +root: RootLogger + +class PercentStyle: # undocumented + default_format: str + asctime_format: str + asctime_search: str + validation_pattern: Pattern[str] + _fmt: str + + def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ... + def usesTime(self) -> bool: ... + def validate(self) -> None: ... + def format(self, record: Any) -> str: ... + +class StrFormatStyle(PercentStyle): # undocumented + fmt_spec: Pattern[str] + field_spec: Pattern[str] + +class StringTemplateStyle(PercentStyle): # undocumented + _tpl: Template + +_STYLES: Final[dict[str, tuple[PercentStyle, str]]] + +BASIC_FORMAT: Final = "%(levelname)s:%(name)s:%(message)s" diff --git a/stdlib/logging/config.pyi b/stdlib/logging/config.pyi new file mode 100644 index 000000000000..1c870edc80f8 --- /dev/null +++ b/stdlib/logging/config.pyi @@ -0,0 +1,141 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence +from configparser import RawConfigParser +from re import Pattern +from threading import Thread +from typing import IO, Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Required, disjoint_base + +from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level + +DEFAULT_LOGGING_CONFIG_PORT: Final = 9030 +RESET_ERROR: Final[int] # undocumented +IDENTIFIER: Final[Pattern[str]] # undocumented + +if sys.version_info >= (3, 11): + @type_check_only + class _RootLoggerConfiguration(TypedDict, total=False): + level: _Level + filters: Sequence[str | _FilterType] + handlers: Sequence[str] + +else: + @type_check_only + class _RootLoggerConfiguration(TypedDict, total=False): + level: _Level + filters: Sequence[str] + handlers: Sequence[str] + +@type_check_only +class _LoggerConfiguration(_RootLoggerConfiguration, TypedDict, total=False): + propagate: bool + +_FormatterConfigurationTypedDict = TypedDict( + "_FormatterConfigurationTypedDict", {"class": str, "format": str, "datefmt": str, "style": _FormatStyle}, total=False +) + +@type_check_only +class _FilterConfigurationTypedDict(TypedDict): + name: str + +# Formatter and filter configs can specify custom factories via the special `()` key. +# If that is the case, the dictionary can contain any additional keys +# https://docs.python.org/3/library/logging.config.html#user-defined-objects +_FormatterConfiguration: TypeAlias = _FormatterConfigurationTypedDict | dict[str, Any] +_FilterConfiguration: TypeAlias = _FilterConfigurationTypedDict | dict[str, Any] +# Handler config can have additional keys even when not providing a custom factory so we just use `dict`. +_HandlerConfiguration: TypeAlias = dict[str, Any] + +@type_check_only +class _DictConfigArgs(TypedDict, total=False): + version: Required[Literal[1]] + formatters: dict[str, _FormatterConfiguration] + filters: dict[str, _FilterConfiguration] + handlers: dict[str, _HandlerConfiguration] + loggers: dict[str, _LoggerConfiguration] + root: _RootLoggerConfiguration + incremental: bool + disable_existing_loggers: bool + +# Accept dict[str, Any] to avoid false positives if called with a dict +# type, since dict types are not compatible with TypedDicts. +# +# Also accept a TypedDict type, to allow callers to use TypedDict +# types, and for somewhat stricter type checking of dict literals. +def dictConfig(config: _DictConfigArgs | dict[str, Any]) -> None: ... +def fileConfig( + fname: StrOrBytesPath | IO[str] | RawConfigParser, + defaults: Mapping[str, str] | None = None, + disable_existing_loggers: bool = True, + encoding: str | None = None, +) -> None: ... +def valid_ident(s: str) -> Literal[True]: ... # undocumented +def listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = None) -> Thread: ... +def stopListening() -> None: ... + +class ConvertingMixin: # undocumented + def convert_with_key(self, key: Any, value: Any, replace: bool = True) -> Any: ... + def convert(self, value: Any) -> Any: ... + +class ConvertingDict(dict[Hashable, Any], ConvertingMixin): # undocumented + def __getitem__(self, key: Hashable) -> Any: ... + def get(self, key: Hashable, default: Any = None) -> Any: ... + def pop(self, key: Hashable, default: Any = None) -> Any: ... + +class ConvertingList(list[Any], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... + + def pop(self, idx: SupportsIndex = -1) -> Any: ... + +if sys.version_info >= (3, 12): + class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... + +else: + @disjoint_base + class ConvertingTuple(tuple[Any, ...], ConvertingMixin): # undocumented + @overload + def __getitem__(self, key: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... + +class BaseConfigurator: + CONVERT_PATTERN: Pattern[str] + WORD_PATTERN: Pattern[str] + DOT_PATTERN: Pattern[str] + INDEX_PATTERN: Pattern[str] + DIGIT_PATTERN: Pattern[str] + value_converters: dict[str, str] + importer: Callable[..., Any] + + config: dict[str, Any] # undocumented + + def __init__(self, config: _DictConfigArgs | dict[str, Any]) -> None: ... + def resolve(self, s: str) -> Any: ... + def ext_convert(self, value: str) -> Any: ... + def cfg_convert(self, value: str) -> Any: ... + def convert(self, value: Any) -> Any: ... + def configure_custom(self, config: dict[str, Any]) -> Any: ... + def as_tuple(self, value: list[Any] | tuple[Any, ...]) -> tuple[Any, ...]: ... + +class DictConfigurator(BaseConfigurator): + def configure(self) -> None: ... # undocumented + def configure_formatter(self, config: _FormatterConfiguration) -> Formatter | Any: ... # undocumented + def configure_filter(self, config: _FilterConfiguration) -> Filter | Any: ... # undocumented + def add_filters(self, filterer: Filterer, filters: Iterable[_FilterType]) -> None: ... # undocumented + def configure_handler(self, config: _HandlerConfiguration) -> Handler | Any: ... # undocumented + def add_handlers(self, logger: Logger, handlers: Iterable[str]) -> None: ... # undocumented + def common_logger_config( + self, logger: Logger, config: _LoggerConfiguration, incremental: bool = False + ) -> None: ... # undocumented + def configure_logger(self, name: str, config: _LoggerConfiguration, incremental: bool = False) -> None: ... # undocumented + def configure_root(self, config: _LoggerConfiguration, incremental: bool = False) -> None: ... # undocumented + +dictConfigClass = DictConfigurator diff --git a/stdlib/logging/handlers.pyi b/stdlib/logging/handlers.pyi new file mode 100644 index 000000000000..535f1c685183 --- /dev/null +++ b/stdlib/logging/handlers.pyi @@ -0,0 +1,258 @@ +import datetime +import http.client +import ssl +import sys +from _typeshed import ReadableBuffer, StrPath +from collections.abc import Callable +from logging import FileHandler, Handler, LogRecord +from re import Pattern +from socket import SocketKind, socket +from threading import Thread +from types import TracebackType +from typing import Any, ClassVar, Final, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +_T = TypeVar("_T") + +DEFAULT_TCP_LOGGING_PORT: Final = 9020 +DEFAULT_UDP_LOGGING_PORT: Final = 9021 +DEFAULT_HTTP_LOGGING_PORT: Final = 9022 +DEFAULT_SOAP_LOGGING_PORT: Final = 9023 +SYSLOG_UDP_PORT: Final = 514 +SYSLOG_TCP_PORT: Final = 514 + +class WatchedFileHandler(FileHandler): + dev: int # undocumented + ino: int # undocumented + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... + def _statstream(self) -> None: ... # undocumented + def reopenIfNeeded(self) -> None: ... + +class BaseRotatingHandler(FileHandler): + namer: Callable[[str], str] | None + rotator: Callable[[str, str], None] | None + def __init__( + self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... + def rotation_filename(self, default_name: str) -> str: ... + def rotate(self, source: str, dest: str) -> None: ... + +class RotatingFileHandler(BaseRotatingHandler): + maxBytes: int # undocumented + backupCount: int # undocumented + def __init__( + self, + filename: StrPath, + mode: str = "a", + maxBytes: int = 0, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + errors: str | None = None, + ) -> None: ... + def doRollover(self) -> None: ... + def shouldRollover(self, record: LogRecord) -> int: ... # undocumented + +class TimedRotatingFileHandler(BaseRotatingHandler): + when: str # undocumented + backupCount: int # undocumented + utc: bool # undocumented + atTime: datetime.time | None # undocumented + interval: int # undocumented + suffix: str # undocumented + dayOfWeek: int # undocumented + rolloverAt: int # undocumented + extMatch: Pattern[str] # undocumented + def __init__( + self, + filename: StrPath, + when: str = "h", + interval: int = 1, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + utc: bool = False, + atTime: datetime.time | None = None, + errors: str | None = None, + ) -> None: ... + def doRollover(self) -> None: ... + def shouldRollover(self, record: LogRecord) -> int: ... # undocumented + def computeRollover(self, currentTime: int) -> int: ... # undocumented + def getFilesToDelete(self) -> list[str]: ... # undocumented + +class SocketHandler(Handler): + host: str # undocumented + port: int | None # undocumented + address: tuple[str, int] | str # undocumented + sock: socket | None # undocumented + closeOnError: bool # undocumented + retryTime: float | None # undocumented + retryStart: float # undocumented + retryFactor: float # undocumented + retryMax: float # undocumented + def __init__(self, host: str, port: int | None) -> None: ... + def makeSocket(self, timeout: float = 1) -> socket: ... # timeout is undocumented + def makePickle(self, record: LogRecord) -> bytes: ... + def send(self, s: ReadableBuffer) -> None: ... + def createSocket(self) -> None: ... + +class DatagramHandler(SocketHandler): + def makeSocket(self) -> socket: ... # type: ignore[override] + +class SysLogHandler(Handler): + LOG_EMERG: int + LOG_ALERT: int + LOG_CRIT: int + LOG_ERR: int + LOG_WARNING: int + LOG_NOTICE: int + LOG_INFO: int + LOG_DEBUG: int + + LOG_KERN: int + LOG_USER: int + LOG_MAIL: int + LOG_DAEMON: int + LOG_AUTH: int + LOG_SYSLOG: int + LOG_LPR: int + LOG_NEWS: int + LOG_UUCP: int + LOG_CRON: int + LOG_AUTHPRIV: int + LOG_FTP: int + LOG_NTP: int + LOG_SECURITY: int + LOG_CONSOLE: int + LOG_SOLCRON: int + LOG_LOCAL0: int + LOG_LOCAL1: int + LOG_LOCAL2: int + LOG_LOCAL3: int + LOG_LOCAL4: int + LOG_LOCAL5: int + LOG_LOCAL6: int + LOG_LOCAL7: int + address: tuple[str, int] | str # undocumented + unixsocket: bool # undocumented + socktype: SocketKind # undocumented + ident: str # undocumented + append_nul: bool # undocumented + facility: int # undocumented + priority_names: ClassVar[dict[str, int]] # undocumented + facility_names: ClassVar[dict[str, int]] # undocumented + priority_map: ClassVar[dict[str, str]] # undocumented + if sys.version_info >= (3, 14): + timeout: float | None + def __init__( + self, + address: tuple[str, int] | str = ("localhost", 514), + facility: str | int = 1, + socktype: SocketKind | None = None, + timeout: float | None = None, + ) -> None: ... + else: + def __init__( + self, address: tuple[str, int] | str = ("localhost", 514), facility: str | int = 1, socktype: SocketKind | None = None + ) -> None: ... + if sys.version_info >= (3, 11): + def createSocket(self) -> None: ... + + def encodePriority(self, facility: int | str, priority: int | str) -> int: ... + def mapPriority(self, levelName: str) -> str: ... + +class NTEventLogHandler(Handler): + def __init__(self, appname: str, dllname: str | None = None, logtype: str = "Application") -> None: ... + def getEventCategory(self, record: LogRecord) -> int: ... + # TODO: correct return value? + def getEventType(self, record: LogRecord) -> int: ... + def getMessageID(self, record: LogRecord) -> int: ... + +class SMTPHandler(Handler): + mailhost: str # undocumented + mailport: int | None # undocumented + username: str | None # undocumented + # password only exists as an attribute if passed credentials is a tuple or list + password: str # undocumented + fromaddr: str # undocumented + toaddrs: list[str] # undocumented + subject: str # undocumented + secure: tuple[()] | tuple[str] | tuple[str, str] | None # undocumented + timeout: float # undocumented + def __init__( + self, + mailhost: str | tuple[str, int], + fromaddr: str, + toaddrs: str | list[str], + subject: str, + credentials: tuple[str, str] | None = None, + secure: tuple[()] | tuple[str] | tuple[str, str] | None = None, + timeout: float = 5.0, + ) -> None: ... + def getSubject(self, record: LogRecord) -> str: ... + +class BufferingHandler(Handler): + capacity: int # undocumented + buffer: list[LogRecord] # undocumented + def __init__(self, capacity: int) -> None: ... + def shouldFlush(self, record: LogRecord) -> bool: ... + +class MemoryHandler(BufferingHandler): + flushLevel: int # undocumented + target: Handler | None # undocumented + flushOnClose: bool # undocumented + def __init__(self, capacity: int, flushLevel: int = 40, target: Handler | None = None, flushOnClose: bool = True) -> None: ... + def setTarget(self, target: Handler | None) -> None: ... + +class HTTPHandler(Handler): + host: str # undocumented + url: str # undocumented + method: str # undocumented + secure: bool # undocumented + credentials: tuple[str, str] | None # undocumented + context: ssl.SSLContext | None # undocumented + def __init__( + self, + host: str, + url: str, + method: str = "GET", + secure: bool = False, + credentials: tuple[str, str] | None = None, + context: ssl.SSLContext | None = None, + ) -> None: ... + def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... + def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ... # undocumented + +@type_check_only +class _QueueLike(Protocol[_T]): + def get(self) -> _T: ... + def put_nowait(self, item: _T, /) -> None: ... + +class QueueHandler(Handler): + queue: _QueueLike[Any] + def __init__(self, queue: _QueueLike[Any]) -> None: ... + def prepare(self, record: LogRecord) -> Any: ... + def enqueue(self, record: LogRecord) -> None: ... + if sys.version_info >= (3, 12): + listener: QueueListener | None + +class QueueListener: + handlers: tuple[Handler, ...] # undocumented + respect_handler_level: bool # undocumented + queue: _QueueLike[Any] # undocumented + _thread: Thread | None # undocumented + def __init__(self, queue: _QueueLike[Any], *handlers: Handler, respect_handler_level: bool = False) -> None: ... + def dequeue(self, block: bool) -> LogRecord: ... + def prepare(self, record: LogRecord) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def enqueue_sentinel(self) -> None: ... + def handle(self, record: LogRecord) -> None: ... + + if sys.version_info >= (3, 14): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... diff --git a/stdlib/lzma.pyi b/stdlib/lzma.pyi new file mode 100644 index 000000000000..656ecb168c95 --- /dev/null +++ b/stdlib/lzma.pyi @@ -0,0 +1,181 @@ +import sys +from _lzma import ( + CHECK_CRC32 as CHECK_CRC32, + CHECK_CRC64 as CHECK_CRC64, + CHECK_ID_MAX as CHECK_ID_MAX, + CHECK_NONE as CHECK_NONE, + CHECK_SHA256 as CHECK_SHA256, + CHECK_UNKNOWN as CHECK_UNKNOWN, + FILTER_ARM as FILTER_ARM, + FILTER_ARMTHUMB as FILTER_ARMTHUMB, + FILTER_DELTA as FILTER_DELTA, + FILTER_IA64 as FILTER_IA64, + FILTER_LZMA1 as FILTER_LZMA1, + FILTER_LZMA2 as FILTER_LZMA2, + FILTER_POWERPC as FILTER_POWERPC, + FILTER_SPARC as FILTER_SPARC, + FILTER_X86 as FILTER_X86, + FORMAT_ALONE as FORMAT_ALONE, + FORMAT_AUTO as FORMAT_AUTO, + FORMAT_RAW as FORMAT_RAW, + FORMAT_XZ as FORMAT_XZ, + MF_BT2 as MF_BT2, + MF_BT3 as MF_BT3, + MF_BT4 as MF_BT4, + MF_HC3 as MF_HC3, + MF_HC4 as MF_HC4, + MODE_FAST as MODE_FAST, + MODE_NORMAL as MODE_NORMAL, + PRESET_DEFAULT as PRESET_DEFAULT, + PRESET_EXTREME as PRESET_EXTREME, + LZMACompressor as LZMACompressor, + LZMADecompressor as LZMADecompressor, + LZMAError as LZMAError, + _FilterChain, + is_check_supported as is_check_supported, +) +from _typeshed import ReadableBuffer, StrOrBytesPath +from io import TextIOWrapper +from typing import IO, Literal, TypeAlias, overload +from typing_extensions import Self + +if sys.version_info >= (3, 14): + from compression._common._streams import BaseStream +else: + from _compression import BaseStream + +__all__ = [ + "CHECK_NONE", + "CHECK_CRC32", + "CHECK_CRC64", + "CHECK_SHA256", + "CHECK_ID_MAX", + "CHECK_UNKNOWN", + "FILTER_LZMA1", + "FILTER_LZMA2", + "FILTER_DELTA", + "FILTER_X86", + "FILTER_IA64", + "FILTER_ARM", + "FILTER_ARMTHUMB", + "FILTER_POWERPC", + "FILTER_SPARC", + "FORMAT_AUTO", + "FORMAT_XZ", + "FORMAT_ALONE", + "FORMAT_RAW", + "MF_HC3", + "MF_HC4", + "MF_BT2", + "MF_BT3", + "MF_BT4", + "MODE_FAST", + "MODE_NORMAL", + "PRESET_DEFAULT", + "PRESET_EXTREME", + "LZMACompressor", + "LZMADecompressor", + "LZMAFile", + "LZMAError", + "open", + "compress", + "decompress", + "is_check_supported", +] + +_OpenBinaryWritingMode: TypeAlias = Literal["w", "wb", "x", "xb", "a", "ab"] +_OpenTextWritingMode: TypeAlias = Literal["wt", "xt", "at"] + +_PathOrFile: TypeAlias = StrOrBytesPath | IO[bytes] + +class LZMAFile(BaseStream, IO[bytes]): # type: ignore[misc] # incompatible definitions of writelines in the base classes + def __init__( + self, + filename: _PathOrFile | None = None, + mode: str = "r", + *, + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def peek(self, size: int = -1) -> bytes: ... + def read(self, size: int | None = -1) -> bytes: ... + def read1(self, size: int = -1) -> bytes: ... + def readline(self, size: int | None = -1) -> bytes: ... + def write(self, data: ReadableBuffer) -> int: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + +@overload +def open( + filename: _PathOrFile, + mode: Literal["r", "rb"] = "rb", + *, + format: int | None = None, + check: Literal[-1] = -1, + preset: None = None, + filters: _FilterChain | None = None, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> LZMAFile: ... +@overload +def open( + filename: _PathOrFile, + mode: _OpenBinaryWritingMode, + *, + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: None = None, + errors: None = None, + newline: None = None, +) -> LZMAFile: ... +@overload +def open( + filename: StrOrBytesPath, + mode: Literal["rt"], + *, + format: int | None = None, + check: Literal[-1] = -1, + preset: None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: StrOrBytesPath, + mode: _OpenTextWritingMode, + *, + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> TextIOWrapper: ... +@overload +def open( + filename: _PathOrFile, + mode: str, + *, + format: int | None = None, + check: int = -1, + preset: int | None = None, + filters: _FilterChain | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, +) -> LZMAFile | TextIOWrapper: ... + +def compress( + data: ReadableBuffer, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None +) -> bytes: ... +def decompress( + data: ReadableBuffer, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None +) -> bytes: ... diff --git a/stdlib/mailbox.pyi b/stdlib/mailbox.pyi new file mode 100644 index 000000000000..4215120a5753 --- /dev/null +++ b/stdlib/mailbox.pyi @@ -0,0 +1,306 @@ +import email.message +import io +import sys +from _typeshed import StrPath, SupportsItems, SupportsNoArgReadline, SupportsRead, SupportsWrite, Unused +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from types import GenericAlias, TracebackType +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "Mailbox", + "Maildir", + "mbox", + "MH", + "Babyl", + "MMDF", + "Message", + "MaildirMessage", + "mboxMessage", + "MHMessage", + "BabylMessage", + "MMDFMessage", + "Error", + "NoSuchMailboxError", + "NotEmptyError", + "ExternalClashError", + "FormatError", +] + +_T = TypeVar("_T") + +@type_check_only +class _SupportsReadAndReadline(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... + +# As opposed to _MessageT_co in email._policybase, this type is bound to +# mailbox.Message instead of email.message.Message. +_MessageT_co = TypeVar("_MessageT_co", bound=Message, default=Message, covariant=True) + +_MessageData: TypeAlias = email.message.Message | bytes | str | io.StringIO | _SupportsReadAndReadline + +@type_check_only +class _HasIteritems(Protocol): + def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... + +linesep: bytes + +# Common interface for get_file() return types. +@type_check_only +class _GetFileReturn(Protocol): + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, / + ) -> bool | None: ... + def read(self, size: int | None = None, /) -> bytes: ... + def read1(self, size: int | None = None, /) -> bytes: ... + def readline(self, size: int | None = None, /) -> bytes: ... + def readlines(self, sizehint: int | None = None, /) -> list[bytes]: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: int = 0, /) -> object: ... + def close(self) -> object: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def flush(self) -> object: ... + @property + def closed(self) -> bool: ... + +class Mailbox(Generic[_MessageT_co]): + _path: str # undocumented + _factory: Callable[[_GetFileReturn], _MessageT_co] | None # undocumented + + @overload + def __init__(self, path: StrPath, factory: Callable[[_GetFileReturn], _MessageT_co], create: bool = True) -> None: ... + @overload + def __init__(self, path: StrPath, factory: None = None, create: bool = True) -> None: ... + + @abstractmethod + def add(self, message: _MessageData) -> str: ... + @abstractmethod + def remove(self, key: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def discard(self, key: str) -> None: ... + @abstractmethod + def __setitem__(self, key: str, message: _MessageData) -> None: ... + + @overload + def get(self, key: str, default: None = None) -> _MessageT_co | None: ... + @overload + def get(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def __getitem__(self, key: str) -> _MessageT_co: ... + @abstractmethod + def get_message(self, key: str) -> _MessageT_co: ... + def get_string(self, key: str) -> str: ... + @abstractmethod + def get_bytes(self, key: str) -> bytes: ... + @abstractmethod + def get_file(self, key: str) -> _GetFileReturn: ... + @abstractmethod + def iterkeys(self) -> Iterator[str]: ... + def keys(self) -> list[str]: ... + def itervalues(self) -> Iterator[_MessageT_co]: ... + def __iter__(self) -> Iterator[_MessageT_co]: ... + def values(self) -> list[_MessageT_co]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageT_co]]: ... + def items(self) -> list[tuple[str, _MessageT_co]]: ... + @abstractmethod + def __contains__(self, key: str) -> bool: ... + @abstractmethod + def __len__(self) -> int: ... + def clear(self) -> None: ... + + @overload + def pop(self, key: str, default: None = None) -> _MessageT_co | None: ... + @overload + def pop(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def popitem(self) -> tuple[str, _MessageT_co]: ... + def update( + self, arg: _HasIteritems | SupportsItems[str, _MessageData] | Iterable[tuple[str, _MessageData]] | None = None + ) -> None: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def lock(self) -> None: ... + @abstractmethod + def unlock(self) -> None: ... + @abstractmethod + def close(self) -> None: ... + if sys.version_info >= (3, 15): + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + # Undocumented, called by subclasses to parse added messages. + def _dump_message(self, message: _MessageData, target: SupportsWrite[bytes], mangle_from_: bool = False) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class Maildir(Mailbox[MaildirMessage]): + colon: str + def __init__( + self, dirname: StrPath, factory: Callable[[_GetFileReturn], MaildirMessage] | None = None, create: bool = True + ) -> None: ... + def add(self, message: _MessageData | MaildirMessage) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData | MaildirMessage) -> None: ... + def get_message(self, key: str) -> MaildirMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> _ProxyFile: ... + if sys.version_info >= (3, 13): + def get_info(self, key: str) -> str: ... + def set_info(self, key: str, info: str) -> None: ... + def get_flags(self, key: str) -> str: ... + def set_flags(self, key: str, flags: str) -> None: ... + def add_flag(self, key: str, flag: str) -> None: ... + def remove_flag(self, key: str, flag: str) -> None: ... + + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... + def list_folders(self) -> list[str]: ... + def get_folder(self, folder: str) -> Maildir: ... + def add_folder(self, folder: str) -> Maildir: ... + def remove_folder(self, folder: str) -> None: ... + def clean(self) -> None: ... + def next(self) -> str | None: ... + +class _singlefileMailbox(Mailbox[_MessageT_co], metaclass=ABCMeta): + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + +class _mboxMMDF(_singlefileMailbox[_MessageT_co]): + def get_message(self, key: str) -> _MessageT_co: ... + def get_file(self, key: str, from_: bool = False) -> _PartialFile: ... + def get_bytes(self, key: str, from_: bool = False) -> bytes: ... + def get_string(self, key: str, from_: bool = False) -> str: ... + +class mbox(_mboxMMDF[mboxMessage]): + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], mboxMessage] | None = None, create: bool = True + ) -> None: ... + +class MMDF(_mboxMMDF[MMDFMessage]): + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], MMDFMessage] | None = None, create: bool = True + ) -> None: ... + +class MH(Mailbox[MHMessage]): + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], MHMessage] | None = None, create: bool = True + ) -> None: ... + def add(self, message: _MessageData) -> str: ... + def remove(self, key: str) -> None: ... + def __setitem__(self, key: str, message: _MessageData) -> None: ... + def get_message(self, key: str) -> MHMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> _ProxyFile: ... + def iterkeys(self) -> Iterator[str]: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def flush(self) -> None: ... + def lock(self) -> None: ... + def unlock(self) -> None: ... + def close(self) -> None: ... + def list_folders(self) -> list[str]: ... + def get_folder(self, folder: StrPath) -> MH: ... + def add_folder(self, folder: StrPath) -> MH: ... + def remove_folder(self, folder: StrPath) -> None: ... + def get_sequences(self) -> dict[str, list[int]]: ... + def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... + def pack(self) -> None: ... + +class Babyl(_singlefileMailbox[BabylMessage]): + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], BabylMessage] | None = None, create: bool = True + ) -> None: ... + def get_message(self, key: str) -> BabylMessage: ... + def get_bytes(self, key: str) -> bytes: ... + def get_file(self, key: str) -> io.BytesIO: ... + def get_labels(self) -> list[str]: ... + +class Message(email.message.Message[str, str]): + def __init__(self, message: _MessageData | None = None) -> None: ... + +class MaildirMessage(Message): + def get_subdir(self) -> str: ... + def set_subdir(self, subdir: Literal["new", "cur"]) -> None: ... + def get_flags(self) -> str: ... + def set_flags(self, flags: Iterable[str]) -> None: ... + def add_flag(self, flag: str) -> None: ... + def remove_flag(self, flag: str) -> None: ... + def get_date(self) -> int: ... + def set_date(self, date: float) -> None: ... + def get_info(self) -> str: ... + def set_info(self, info: str) -> None: ... + +class _mboxMMDFMessage(Message): + def get_from(self) -> str: ... + def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = None) -> None: ... + def get_flags(self) -> str: ... + def set_flags(self, flags: Iterable[str]) -> None: ... + def add_flag(self, flag: str) -> None: ... + def remove_flag(self, flag: str) -> None: ... + +class mboxMessage(_mboxMMDFMessage): ... + +class MHMessage(Message): + def get_sequences(self) -> list[str]: ... + def set_sequences(self, sequences: Iterable[str]) -> None: ... + def add_sequence(self, sequence: str) -> None: ... + def remove_sequence(self, sequence: str) -> None: ... + +class BabylMessage(Message): + def get_labels(self) -> list[str]: ... + def set_labels(self, labels: Iterable[str]) -> None: ... + def add_label(self, label: str) -> None: ... + def remove_label(self, label: str) -> None: ... + def get_visible(self) -> Message: ... + def set_visible(self, visible: _MessageData) -> None: ... + def update_visible(self) -> None: ... + +class MMDFMessage(_mboxMMDFMessage): ... + +# Until Python 3.14, this class was technically - but unnecessarily - generic at runtime. +class _ProxyFile: + def __init__(self, f: _GetFileReturn, pos: int | None = None) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def read1(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, sizehint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc: Unused) -> None: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def flush(self) -> None: ... + @property + def closed(self) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class _PartialFile(_ProxyFile): + def __init__(self, f: _GetFileReturn, start: int | None = None, stop: int | None = None) -> None: ... + +class Error(Exception): ... +class NoSuchMailboxError(Error): ... +class NotEmptyError(Error): ... +class ExternalClashError(Error): ... +class FormatError(Error): ... diff --git a/stdlib/mailcap.pyi b/stdlib/mailcap.pyi new file mode 100644 index 000000000000..74c32694a7f9 --- /dev/null +++ b/stdlib/mailcap.pyi @@ -0,0 +1,11 @@ +from collections.abc import Mapping, Sequence +from typing import TypeAlias + +_Cap: TypeAlias = dict[str, str | int] + +__all__ = ["getcaps", "findmatch"] + +def findmatch( + caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = "view", filename: str = "/dev/null", plist: Sequence[str] = [] +) -> tuple[str | None, _Cap | None]: ... +def getcaps() -> dict[str, list[_Cap]]: ... diff --git a/stdlib/marshal.pyi b/stdlib/marshal.pyi new file mode 100644 index 000000000000..d72abe7758b7 --- /dev/null +++ b/stdlib/marshal.pyi @@ -0,0 +1,52 @@ +import builtins +import sys +import types +from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite +from typing import Any, Final, TypeAlias + +version: Final[int] + +_Marshallable: TypeAlias = ( + # handled in w_object() in marshal.c + None + | type[StopIteration] + | builtins.ellipsis + | bool + # handled in w_complex_object() in marshal.c + | int + | float + | complex + | bytes + | str + | tuple[_Marshallable, ...] + | list[Any] + | dict[Any, Any] + | set[Any] + | frozenset[_Marshallable] + | types.CodeType + | ReadableBuffer +) + +if sys.version_info >= (3, 15): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 6, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 6, /, *, allow_code: bool = True) -> bytes: ... + +elif sys.version_info >= (3, 14): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 5, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 5, /, *, allow_code: bool = True) -> bytes: ... + +elif sys.version_info >= (3, 13): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 4, /, *, allow_code: bool = True) -> bytes: ... + +else: + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: ... + def dumps(value: _Marshallable, version: int = 4, /) -> bytes: ... + +if sys.version_info >= (3, 13): + def load(file: SupportsRead[bytes], /, *, allow_code: bool = True) -> Any: ... + def loads(bytes: ReadableBuffer, /, *, allow_code: bool = True) -> Any: ... + +else: + def load(file: SupportsRead[bytes], /) -> Any: ... + def loads(bytes: ReadableBuffer, /) -> Any: ... diff --git a/stdlib/math/__init__.pyi b/stdlib/math/__init__.pyi new file mode 100644 index 000000000000..b11324c4ae9a --- /dev/null +++ b/stdlib/math/__init__.pyi @@ -0,0 +1,157 @@ +import sys +from _typeshed import SupportsMul, SupportsRMul +from collections.abc import Iterable +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +_SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex + +e: Final[float] +pi: Final[float] +inf: Final[float] +nan: Final[float] +tau: Final[float] + +def acos(x: _SupportsFloatOrIndex, /) -> float: ... +def acosh(x: _SupportsFloatOrIndex, /) -> float: ... +def asin(x: _SupportsFloatOrIndex, /) -> float: ... +def asinh(x: _SupportsFloatOrIndex, /) -> float: ... +def atan(x: _SupportsFloatOrIndex, /) -> float: ... +def atan2(y: _SupportsFloatOrIndex, x: _SupportsFloatOrIndex, /) -> float: ... +def atanh(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 11): + def cbrt(x: _SupportsFloatOrIndex, /) -> float: ... + +@type_check_only +class _SupportsCeil(Protocol[_T_co]): + def __ceil__(self) -> _T_co: ... + +@overload +def ceil(x: _SupportsCeil[_T], /) -> _T: ... +@overload +def ceil(x: _SupportsFloatOrIndex, /) -> int: ... + +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def cos(x: _SupportsFloatOrIndex, /) -> float: ... +def cosh(x: _SupportsFloatOrIndex, /) -> float: ... +def degrees(x: _SupportsFloatOrIndex, /) -> float: ... +def dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def erf(x: _SupportsFloatOrIndex, /) -> float: ... +def erfc(x: _SupportsFloatOrIndex, /) -> float: ... +def exp(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 11): + def exp2(x: _SupportsFloatOrIndex, /) -> float: ... + +def expm1(x: _SupportsFloatOrIndex, /) -> float: ... +def fabs(x: _SupportsFloatOrIndex, /) -> float: ... +def factorial(x: SupportsIndex, /) -> int: ... + +@type_check_only +class _SupportsFloor(Protocol[_T_co]): + def __floor__(self) -> _T_co: ... + +@overload +def floor(x: _SupportsFloor[_T], /) -> _T: ... +@overload +def floor(x: _SupportsFloatOrIndex, /) -> int: ... + +def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def fmax(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + def fmin(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ... +def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ... +def gamma(x: _SupportsFloatOrIndex, /) -> float: ... +def gcd(*integers: SupportsIndex) -> int: ... +def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... +def isclose( + a: _SupportsFloatOrIndex, + b: _SupportsFloatOrIndex, + *, + rel_tol: _SupportsFloatOrIndex = 1e-09, + abs_tol: _SupportsFloatOrIndex = 0.0, +) -> bool: ... +def isinf(x: _SupportsFloatOrIndex, /) -> bool: ... +def isfinite(x: _SupportsFloatOrIndex, /) -> bool: ... +def isnan(x: _SupportsFloatOrIndex, /) -> bool: ... + +if sys.version_info >= (3, 15): + def isnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + def issubnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + +def isqrt(n: SupportsIndex, /) -> int: ... +def lcm(*integers: SupportsIndex) -> int: ... +def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ... +def lgamma(x: _SupportsFloatOrIndex, /) -> float: ... +def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ..., /) -> float: ... +def log10(x: _SupportsFloatOrIndex, /) -> float: ... +def log1p(x: _SupportsFloatOrIndex, /) -> float: ... +def log2(x: _SupportsFloatOrIndex, /) -> float: ... +def modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: ... + +if sys.version_info >= (3, 12): + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: ... + +else: + def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... +def pow(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] +_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0] # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed + +_MultiplicableT1 = TypeVar("_MultiplicableT1", bound=SupportsMul[Any, Any]) +_MultiplicableT2 = TypeVar("_MultiplicableT2", bound=SupportsMul[Any, Any]) + +@type_check_only +class _SupportsProdWithNoDefaultGiven(SupportsMul[Any, Any], SupportsRMul[int, Any], Protocol): ... + +_SupportsProdNoDefaultT = TypeVar("_SupportsProdNoDefaultT", bound=_SupportsProdWithNoDefaultGiven) + +# This stub is based on the type stub for `builtins.sum`. +# Like `builtins.sum`, it cannot be precisely represented in a type stub +# without introducing many false positives. +# For more details on its limitations and false positives, see #13572. +# Instead, just like `builtins.sum`, we explicitly handle several useful cases. +@overload +def prod(iterable: Iterable[bool | _LiteralInteger], /, *, start: int = 1) -> int: ... # type: ignore[overload-overlap] +@overload +def prod(iterable: Iterable[_SupportsProdNoDefaultT], /) -> _SupportsProdNoDefaultT | Literal[1]: ... +@overload +def prod(iterable: Iterable[_MultiplicableT1], /, *, start: _MultiplicableT2) -> _MultiplicableT1 | _MultiplicableT2: ... + +def radians(x: _SupportsFloatOrIndex, /) -> float: ... +def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... +def sin(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def signbit(x: _SupportsFloatOrIndex, /) -> bool: ... + +def sinh(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 12): + def sumprod(p: Iterable[float], q: Iterable[float], /) -> float: ... + +def sqrt(x: _SupportsFloatOrIndex, /) -> float: ... +def tan(x: _SupportsFloatOrIndex, /) -> float: ... +def tanh(x: _SupportsFloatOrIndex, /) -> float: ... + +# Is different from `_typeshed.SupportsTrunc`, which is not generic +@type_check_only +class _SupportsTrunc(Protocol[_T_co]): + def __trunc__(self) -> _T_co: ... + +def trunc(x: _SupportsTrunc[_T], /) -> _T: ... +def ulp(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 13): + def fma(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, z: _SupportsFloatOrIndex, /) -> float: ... diff --git a/stdlib/math/integer.pyi b/stdlib/math/integer.pyi new file mode 100644 index 000000000000..6d6d6b3e82dc --- /dev/null +++ b/stdlib/math/integer.pyi @@ -0,0 +1,8 @@ +from typing import SupportsIndex + +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def factorial(n: SupportsIndex, /) -> int: ... +def gcd(*integers: SupportsIndex) -> int: ... +def isqrt(n: SupportsIndex, /) -> int: ... +def lcm(*integers: SupportsIndex) -> int: ... +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... diff --git a/stdlib/mimetypes.pyi b/stdlib/mimetypes.pyi new file mode 100644 index 000000000000..2390b2ce39f8 --- /dev/null +++ b/stdlib/mimetypes.pyi @@ -0,0 +1,56 @@ +import sys +from _typeshed import StrPath +from collections.abc import Iterable +from typing import IO + +__all__ = [ + "knownfiles", + "inited", + "MimeTypes", + "guess_type", + "guess_all_extensions", + "guess_extension", + "add_type", + "init", + "read_mime_types", + "suffix_map", + "encodings_map", + "types_map", + "common_types", +] + +if sys.version_info >= (3, 13): + __all__ += ["guess_file_type"] + +def guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... +def guess_all_extensions(type: str, strict: bool = True) -> list[str]: ... +def guess_extension(type: str, strict: bool = True) -> str | None: ... +def init(files: Iterable[StrPath] | None = None) -> None: ... +def read_mime_types(file: StrPath) -> dict[str, str] | None: ... +def add_type(type: str, ext: str, strict: bool = True) -> None: ... + +if sys.version_info >= (3, 13): + def guess_file_type(path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ... + +inited: bool +knownfiles: list[StrPath] +suffix_map: dict[str, str] +encodings_map: dict[str, str] +types_map: dict[str, str] +common_types: dict[str, str] + +class MimeTypes: + suffix_map: dict[str, str] + encodings_map: dict[str, str] + types_map: tuple[dict[str, str], dict[str, str]] + types_map_inv: tuple[dict[str, str], dict[str, str]] + def __init__(self, filenames: Iterable[StrPath] = (), strict: bool = True) -> None: ... + def add_type(self, type: str, ext: str, strict: bool = True) -> None: ... + def guess_extension(self, type: str, strict: bool = True) -> str | None: ... + def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ... + def guess_all_extensions(self, type: str, strict: bool = True) -> list[str]: ... + def read(self, filename: StrPath, strict: bool = True) -> None: ... + def readfp(self, fp: IO[str], strict: bool = True) -> None: ... + def read_windows_registry(self, strict: bool = True) -> None: ... + if sys.version_info >= (3, 13): + def guess_file_type(self, path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ... diff --git a/stdlib/mmap.pyi b/stdlib/mmap.pyi new file mode 100644 index 000000000000..7aedd6711b01 --- /dev/null +++ b/stdlib/mmap.pyi @@ -0,0 +1,187 @@ +import os +import sys +from _typeshed import ReadableBuffer, Unused +from collections.abc import Iterator +from typing import Final, Literal, SupportsIndex, overload +from typing_extensions import Never, Self, disjoint_base + +ACCESS_DEFAULT: Final = 0 +ACCESS_READ: Final = 1 +ACCESS_WRITE: Final = 2 +ACCESS_COPY: Final = 3 + +ALLOCATIONGRANULARITY: Final[int] + +if sys.platform == "linux": + MAP_DENYWRITE: Final[int] + MAP_EXECUTABLE: Final[int] + MAP_POPULATE: Final[int] +if sys.version_info >= (3, 11) and sys.platform != "win32" and sys.platform != "darwin": + MAP_STACK: Final[int] + +if sys.platform != "win32": + MAP_ANON: Final[int] + MAP_ANONYMOUS: Final[int] + MAP_PRIVATE: Final[int] + MAP_SHARED: Final[int] + PROT_EXEC: Final[int] + PROT_READ: Final[int] + PROT_WRITE: Final[int] + if sys.version_info >= (3, 15): + MS_ASYNC: Final[int] + MS_INVALIDATE: Final[int] + MS_SYNC: Final[int] + +PAGESIZE: Final[int] + +@disjoint_base +class mmap: + if sys.platform == "win32": + if sys.version_info >= (3, 15): + def __new__( + cls, + fileno: int, + length: int, + tagname: str | None = None, + access: int = 0, + offset: int = 0, + *, + trackfd: bool = True, + ) -> Self: ... + else: + def __new__(cls, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ... + else: + if sys.version_info >= (3, 13): + def __new__( + cls, + fileno: int, + length: int, + flags: int = ..., + prot: int = ..., + access: int = 0, + offset: int = 0, + *, + trackfd: bool = True, + ) -> Self: ... + else: + def __new__( + cls, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = 0, offset: int = 0 + ) -> Self: ... + + def close(self) -> None: ... + if sys.version_info >= (3, 15): + def flush(self, offset: int = 0, size: int = ..., /, *, flags: int = 0) -> None: ... + else: + def flush(self, offset: int = 0, size: int = ..., /) -> None: ... + + def move(self, dest: int, src: int, count: int, /) -> None: ... + def read_byte(self) -> int: ... + def readline(self) -> bytes: ... + if sys.version_info < (3, 15) or sys.platform != "darwin": + def resize(self, newsize: int, /) -> None: ... + if sys.platform != "win32": + def seek(self, pos: int, whence: Literal[0, 1, 2, 3, 4] = os.SEEK_SET, /) -> None: ... + else: + def seek(self, pos: int, whence: Literal[0, 1, 2] = os.SEEK_SET, /) -> None: ... + + def size(self) -> int: ... + def tell(self) -> int: ... + def write_byte(self, byte: int, /) -> None: ... + def __len__(self) -> int: ... + closed: bool + if sys.platform != "win32": + if sys.version_info >= (3, 15): + def madvise(self, option: int, start: int = 0, length: int | None = None, /) -> None: ... + else: + def madvise(self, option: int, start: int = 0, length: int = ..., /) -> None: ... + + if sys.version_info >= (3, 15): + def find(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + + else: + def find(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... + + def read(self, n: int | None = None, /) -> bytes: ... + def write(self, bytes: ReadableBuffer, /) -> int: ... + if sys.version_info >= (3, 15): + def set_name(self, name: str, /) -> None: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> int: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> Never: ... + + @overload + def __setitem__(self, key: SupportsIndex, value: int, /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... + + # Doesn't actually exist, but the object actually supports "in" because it has __getitem__, + # so we claim that there is also a __contains__ to help type checkers. + def __contains__(self, o: object, /) -> bool: ... + # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and __len__, + # so we claim that there is also an __iter__ to help type checkers. + def __iter__(self) -> Iterator[int]: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: Unused, exc_value: Unused, traceback: Unused, /) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + if sys.version_info >= (3, 13): + def seekable(self) -> Literal[True]: ... + +if sys.platform != "win32": + MADV_NORMAL: Final[int] + MADV_RANDOM: Final[int] + MADV_SEQUENTIAL: Final[int] + MADV_WILLNEED: Final[int] + MADV_DONTNEED: Final[int] + MADV_FREE: Final[int] + +if sys.platform == "linux": + MADV_REMOVE: Final[int] + MADV_DONTFORK: Final[int] + MADV_DOFORK: Final[int] + MADV_HWPOISON: Final[int] + MADV_MERGEABLE: Final[int] + MADV_UNMERGEABLE: Final[int] + # Seems like this constant is not defined in glibc. + # See https://github.com/python/typeshed/pull/5360 for details + # MADV_SOFT_OFFLINE: Final[int] + MADV_HUGEPAGE: Final[int] + MADV_NOHUGEPAGE: Final[int] + MADV_DONTDUMP: Final[int] + MADV_DODUMP: Final[int] + +# This Values are defined for FreeBSD but type checkers do not support conditions for these +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + MADV_NOSYNC: Final[int] + MADV_AUTOSYNC: Final[int] + MADV_NOCORE: Final[int] + MADV_CORE: Final[int] + MADV_PROTECT: Final[int] + +if sys.platform == "darwin": + MADV_FREE_REUSABLE: Final[int] + MADV_FREE_REUSE: Final[int] + +if sys.version_info >= (3, 13) and sys.platform != "win32": + MAP_32BIT: Final[int] + +if sys.version_info >= (3, 13) and sys.platform == "darwin": + MAP_NORESERVE: Final = 64 + MAP_NOEXTEND: Final = 256 + MAP_HASSEMAPHORE: Final = 512 + MAP_NOCACHE: Final = 1024 + MAP_JIT: Final = 2048 + MAP_RESILIENT_CODESIGN: Final = 8192 + MAP_RESILIENT_MEDIA: Final = 16384 + MAP_TRANSLATED_ALLOW_EXECUTE: Final = 131072 + MAP_UNIX03: Final = 262144 + MAP_TPRO: Final = 524288 + +if sys.version_info >= (3, 13) and sys.platform == "linux": + MAP_NORESERVE: Final = 16384 diff --git a/stdlib/modulefinder.pyi b/stdlib/modulefinder.pyi new file mode 100644 index 000000000000..6db665a18e69 --- /dev/null +++ b/stdlib/modulefinder.pyi @@ -0,0 +1,68 @@ +import sys +from collections.abc import Container, Iterable, Iterator, Sequence +from types import CodeType +from typing import IO, Any, Final + +if sys.version_info < (3, 11): + LOAD_CONST: Final[int] # undocumented + IMPORT_NAME: Final[int] # undocumented + STORE_NAME: Final[int] # undocumented + STORE_GLOBAL: Final[int] # undocumented + STORE_OPS: Final[tuple[int, int]] # undocumented + EXTENDED_ARG: Final[int] # undocumented + +packagePathMap: dict[str, list[str]] # undocumented + +def AddPackagePath(packagename: str, path: str) -> None: ... + +replacePackageMap: dict[str, str] # undocumented + +def ReplacePackage(oldname: str, newname: str) -> None: ... + +class Module: # undocumented + def __init__(self, name: str, file: str | None = None, path: str | None = None) -> None: ... + +class ModuleFinder: + modules: dict[str, Module] + path: list[str] # undocumented + badmodules: dict[str, dict[str, int]] # undocumented + debug: int # undocumented + indent: int # undocumented + excludes: Container[str] # undocumented + replace_paths: Sequence[tuple[str, str]] # undocumented + + def __init__( + self, + path: list[str] | None = None, + debug: int = 0, + excludes: Container[str] | None = None, + replace_paths: Sequence[tuple[str, str]] | None = None, + ) -> None: ... + def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented + def msgin(self, *args: Any) -> None: ... # undocumented + def msgout(self, *args: Any) -> None: ... # undocumented + def run_script(self, pathname: str) -> None: ... + def load_file(self, pathname: str) -> None: ... # undocumented + def import_hook( + self, name: str, caller: Module | None = None, fromlist: list[str] | None = None, level: int = -1 + ) -> Module | None: ... # undocumented + def determine_parent(self, caller: Module | None, level: int = -1) -> Module | None: ... # undocumented + def find_head_package(self, parent: Module, name: str) -> tuple[Module, str]: ... # undocumented + def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented + def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = 0) -> None: ... # undocumented + def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented + def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ... # undocumented + def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ... # undocumented + def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, tuple[Any, ...]]]: ... # undocumented + def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented + def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented + def add_module(self, fqname: str) -> Module: ... # undocumented + def find_module( + self, name: str, path: str | None, parent: Module | None = None + ) -> tuple[IO[Any] | None, str | None, tuple[str, str, int]]: ... # undocumented + def report(self) -> None: ... + def any_missing(self) -> list[str]: ... # undocumented + def any_missing_maybe(self) -> tuple[list[str], list[str]]: ... # undocumented + def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented + +def test() -> ModuleFinder | None: ... # undocumented diff --git a/stdlib/msilib/__init__.pyi b/stdlib/msilib/__init__.pyi new file mode 100644 index 000000000000..565a52d53499 --- /dev/null +++ b/stdlib/msilib/__init__.pyi @@ -0,0 +1,177 @@ +import sys +from _typeshed import MaybeNone +from collections.abc import Container, Iterable +from types import ModuleType +from typing import Any, Final + +if sys.platform == "win32": + from _msi import * + from _msi import _Database + + from .sequence import _SequenceType + + AMD64: Final[bool] + Win64: Final[bool] + + datasizemask: Final = 0x00FF + type_valid: Final = 0x0100 + type_localizable: Final = 0x0200 + typemask: Final = 0x0C00 + type_long: Final = 0x0000 + type_short: Final = 0x0400 + type_string: Final = 0x0C00 + type_binary: Final = 0x0800 + type_nullable: Final = 0x1000 + type_key: Final = 0x2000 + knownbits: Final = 0x3FFF + + class Table: + name: str + fields: list[tuple[int, str, int]] + def __init__(self, name: str) -> None: ... + def add_field(self, index: int, name: str, type: int) -> None: ... + def sql(self) -> str: ... + def create(self, db: _Database) -> None: ... + + class _Unspecified: ... + + def change_sequence( + seq: _SequenceType, action: str, seqno: int | type[_Unspecified] = ..., cond: str | type[_Unspecified] = ... + ) -> None: ... + def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ... + def add_stream(db: _Database, name: str, path: str) -> None: ... + def init_database( + name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str + ) -> _Database: ... + def add_tables(db: _Database, module: ModuleType) -> None: ... + def make_id(str: str) -> str: ... + def gen_uuid() -> str: ... + + class CAB: + name: str + files: list[tuple[str, str]] + filenames: set[str] + index: int + def __init__(self, name: str) -> None: ... + def gen_id(self, file: str) -> str: ... + def append(self, full: str, file: str, logical: str | None) -> tuple[int, str] | MaybeNone: ... + def commit(self, db: _Database) -> None: ... + + _directories: set[str] + + class Directory: + db: _Database + cab: CAB + basedir: Directory | None + physical: str + logical: str + component: str | None + short_names: set[str] + ids: set[str] + keyfiles: dict[str, str] + componentflags: int | None + absolute: str + def __init__( + self, + db: _Database, + cab: CAB, + basedir: Directory | None, + physical: str, + _logical: str, + default: str, + componentflags: int | None = None, + ) -> None: ... + def start_component( + self, + component: str | None = None, + feature: Feature | None = None, + flags: int | None = None, + keyfile: str | None = None, + uuid: str | None = None, + ) -> None: ... + def make_short(self, file: str) -> str: ... + def add_file(self, file: str, src: str | None = None, version: str | None = None, language: str | None = None) -> str: ... + def glob(self, pattern: str, exclude: Container[str] | None = None) -> list[str]: ... + def remove_pyc(self) -> None: ... + + class Binary: + name: str + def __init__(self, fname: str) -> None: ... + + class Feature: + id: str + def __init__( + self, + db: _Database, + id: str, + title: str, + desc: str, + display: int, + level: int = 1, + parent: Feature | None = None, + directory: str | None = None, + attributes: int = 0, + ) -> None: ... + def set_current(self) -> None: ... + + class Control: + dlg: Dialog + name: str + def __init__(self, dlg: Dialog, name: str) -> None: ... + def event(self, event: str, argument: str, condition: str = "1", ordering: int | None = None) -> None: ... + def mapping(self, event: str, attribute: str) -> None: ... + def condition(self, action: str, condition: str) -> None: ... + + class RadioButtonGroup(Control): + property: str + index: int + def __init__(self, dlg: Dialog, name: str, property: str) -> None: ... + def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: str | None = None) -> None: ... + + class Dialog: + db: _Database + name: str + x: int + y: int + w: int + h: int + def __init__( + self, + db: _Database, + name: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + title: str, + first: str, + default: str | None, + cancel: str | None, + ) -> None: ... + def control( + self, + name: str, + type: str, + x: int, + y: int, + w: int, + h: int, + attr: int, + prop: str | None, + text: str | None, + next: str | None, + help: str | None, + ) -> Control: ... + def text(self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None) -> Control: ... + def bitmap(self, name: str, x: int, y: int, w: int, h: int, text: str | None) -> Control: ... + def line(self, name: str, x: int, y: int, w: int, h: int) -> Control: ... + def pushbutton( + self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None, next: str | None + ) -> Control: ... + def radiogroup( + self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None + ) -> RadioButtonGroup: ... + def checkbox( + self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None + ) -> Control: ... diff --git a/stdlib/msilib/schema.pyi b/stdlib/msilib/schema.pyi new file mode 100644 index 000000000000..3bbdc41a1e8e --- /dev/null +++ b/stdlib/msilib/schema.pyi @@ -0,0 +1,95 @@ +import sys +from typing import Final + +if sys.platform == "win32": + from . import Table + + _Validation: Table + ActionText: Table + AdminExecuteSequence: Table + Condition: Table + AdminUISequence: Table + AdvtExecuteSequence: Table + AdvtUISequence: Table + AppId: Table + AppSearch: Table + Property: Table + BBControl: Table + Billboard: Table + Feature: Table + Binary: Table + BindImage: Table + File: Table + CCPSearch: Table + CheckBox: Table + Class: Table + Component: Table + Icon: Table + ProgId: Table + ComboBox: Table + CompLocator: Table + Complus: Table + Directory: Table + Control: Table + Dialog: Table + ControlCondition: Table + ControlEvent: Table + CreateFolder: Table + CustomAction: Table + DrLocator: Table + DuplicateFile: Table + Environment: Table + Error: Table + EventMapping: Table + Extension: Table + MIME: Table + FeatureComponents: Table + FileSFPCatalog: Table + SFPCatalog: Table + Font: Table + IniFile: Table + IniLocator: Table + InstallExecuteSequence: Table + InstallUISequence: Table + IsolatedComponent: Table + LaunchCondition: Table + ListBox: Table + ListView: Table + LockPermissions: Table + Media: Table + MoveFile: Table + MsiAssembly: Table + MsiAssemblyName: Table + MsiDigitalCertificate: Table + MsiDigitalSignature: Table + MsiFileHash: Table + MsiPatchHeaders: Table + ODBCAttribute: Table + ODBCDriver: Table + ODBCDataSource: Table + ODBCSourceAttribute: Table + ODBCTranslator: Table + Patch: Table + PatchPackage: Table + PublishComponent: Table + RadioButton: Table + Registry: Table + RegLocator: Table + RemoveFile: Table + RemoveIniFile: Table + RemoveRegistry: Table + ReserveCost: Table + SelfReg: Table + ServiceControl: Table + ServiceInstall: Table + Shortcut: Table + Signature: Table + TextStyle: Table + TypeLib: Table + UIText: Table + Upgrade: Table + Verb: Table + + tables: Final[list[Table]] + + _Validation_records: list[tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] diff --git a/stdlib/msilib/sequence.pyi b/stdlib/msilib/sequence.pyi new file mode 100644 index 000000000000..9b01c416f1d6 --- /dev/null +++ b/stdlib/msilib/sequence.pyi @@ -0,0 +1,13 @@ +import sys +from typing import Final, TypeAlias + +if sys.platform == "win32": + _SequenceType: TypeAlias = list[tuple[str, str | None, int]] + + AdminExecuteSequence: Final[_SequenceType] + AdminUISequence: Final[_SequenceType] + AdvtExecuteSequence: Final[_SequenceType] + InstallExecuteSequence: Final[_SequenceType] + InstallUISequence: Final[_SequenceType] + + tables: Final[list[str]] diff --git a/stdlib/msilib/text.pyi b/stdlib/msilib/text.pyi new file mode 100644 index 000000000000..da3c5fd0fb7a --- /dev/null +++ b/stdlib/msilib/text.pyi @@ -0,0 +1,8 @@ +import sys +from typing import Final + +if sys.platform == "win32": + ActionText: Final[list[tuple[str, str, str | None]]] + UIText: Final[list[tuple[str, str | None]]] + dirname: str + tables: Final[list[str]] diff --git a/stdlib/msvcrt.pyi b/stdlib/msvcrt.pyi new file mode 100644 index 000000000000..1518f7974de7 --- /dev/null +++ b/stdlib/msvcrt.pyi @@ -0,0 +1,31 @@ +import sys +from typing import Final + +# This module is only available on Windows +if sys.platform == "win32": + CRT_ASSEMBLY_VERSION: Final[str] + LK_UNLCK: Final = 0 + LK_LOCK: Final = 1 + LK_NBLCK: Final = 2 + LK_RLCK: Final = 3 + LK_NBRLCK: Final = 4 + SEM_FAILCRITICALERRORS: Final = 0x0001 + SEM_NOALIGNMENTFAULTEXCEPT: Final = 0x0004 + SEM_NOGPFAULTERRORBOX: Final = 0x0002 + SEM_NOOPENFILEERRORBOX: Final = 0x8000 + def locking(fd: int, mode: int, nbytes: int, /) -> None: ... + def setmode(fd: int, mode: int, /) -> int: ... + def open_osfhandle(handle: int, flags: int, /) -> int: ... + def get_osfhandle(fd: int, /) -> int: ... + def kbhit() -> bool: ... + def getch() -> bytes: ... + def getwch() -> str: ... + def getche() -> bytes: ... + def getwche() -> str: ... + def putch(char: bytes | bytearray, /) -> None: ... + def putwch(unicode_char: str, /) -> None: ... + def ungetch(char: bytes | bytearray, /) -> None: ... + def ungetwch(unicode_char: str, /) -> None: ... + def heapmin() -> None: ... + def SetErrorMode(mode: int, /) -> int: ... + def GetErrorMode() -> int: ... # undocumented diff --git a/stdlib/multiprocessing/__init__.pyi b/stdlib/multiprocessing/__init__.pyi new file mode 100644 index 000000000000..2bd6e2883ddb --- /dev/null +++ b/stdlib/multiprocessing/__init__.pyi @@ -0,0 +1,90 @@ +from multiprocessing import context, reduction as reducer +from multiprocessing.context import ( + AuthenticationError as AuthenticationError, + BufferTooShort as BufferTooShort, + Process as Process, + ProcessError as ProcessError, + TimeoutError as TimeoutError, +) +from multiprocessing.process import ( + active_children as active_children, + current_process as current_process, + parent_process as parent_process, +) + +# These are technically functions that return instances of these Queue classes. +# The stub here doesn't reflect reality exactly -- +# while e.g. `multiprocessing.queues.Queue` is a class, +# `multiprocessing.Queue` is actually a function at runtime. +# Avoid using `multiprocessing.Queue` as a type annotation; +# use imports from multiprocessing.queues instead. +# See #4266 and #8450 for discussion. +from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue +from multiprocessing.spawn import freeze_support as freeze_support + +__all__ = [ + "Array", + "AuthenticationError", + "Barrier", + "BoundedSemaphore", + "BufferTooShort", + "Condition", + "Event", + "JoinableQueue", + "Lock", + "Manager", + "Pipe", + "Pool", + "Process", + "ProcessError", + "Queue", + "RLock", + "RawArray", + "RawValue", + "Semaphore", + "SimpleQueue", + "TimeoutError", + "Value", + "active_children", + "allow_connection_pickling", + "cpu_count", + "current_process", + "freeze_support", + "get_all_start_methods", + "get_context", + "get_logger", + "get_start_method", + "log_to_stderr", + "parent_process", + "reducer", + "set_executable", + "set_forkserver_preload", + "set_start_method", +] + +# These functions (really bound methods) +# are all autogenerated at runtime here: https://github.com/python/cpython/blob/600c65c094b0b48704d8ec2416930648052ba715/Lib/multiprocessing/__init__.py#L23 +RawValue = context._default_context.RawValue +RawArray = context._default_context.RawArray +Value = context._default_context.Value +Array = context._default_context.Array +Barrier = context._default_context.Barrier +BoundedSemaphore = context._default_context.BoundedSemaphore +Condition = context._default_context.Condition +Event = context._default_context.Event +Lock = context._default_context.Lock +RLock = context._default_context.RLock +Semaphore = context._default_context.Semaphore +Pipe = context._default_context.Pipe +Pool = context._default_context.Pool +allow_connection_pickling = context._default_context.allow_connection_pickling +cpu_count = context._default_context.cpu_count +get_logger = context._default_context.get_logger +log_to_stderr = context._default_context.log_to_stderr +Manager = context._default_context.Manager +set_executable = context._default_context.set_executable +set_forkserver_preload = context._default_context.set_forkserver_preload +get_all_start_methods = context._default_context.get_all_start_methods +get_start_method = context._default_context.get_start_method +set_start_method = context._default_context.set_start_method +get_context = context._default_context.get_context diff --git a/stdlib/multiprocessing/connection.pyi b/stdlib/multiprocessing/connection.pyi new file mode 100644 index 000000000000..e8366e9a8ba5 --- /dev/null +++ b/stdlib/multiprocessing/connection.pyi @@ -0,0 +1,94 @@ +import socket +import sys +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from types import TracebackType +from typing import Any, Generic, SupportsIndex, TypeAlias, TypeVar +from typing_extensions import Self + +__all__ = ["Client", "Listener", "Pipe", "wait"] + +# https://docs.python.org/3/library/multiprocessing.html#address-formats +_Address: TypeAlias = str | tuple[str, int] + +# Defaulting to Any to avoid forcing generics on a lot of pre-existing code +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=Any) +_RecvT_co = TypeVar("_RecvT_co", covariant=True, default=Any) + +class _ConnectionBase(Generic[_SendT_contra, _RecvT_co]): + def __init__(self, handle: SupportsIndex, readable: bool = True, writable: bool = True) -> None: ... + @property + def closed(self) -> bool: ... # undocumented + @property + def readable(self) -> bool: ... # undocumented + @property + def writable(self) -> bool: ... # undocumented + def fileno(self) -> int: ... + def close(self) -> None: ... + def send_bytes(self, buf: ReadableBuffer, offset: int = 0, size: int | None = None) -> None: ... + def send(self, obj: _SendT_contra) -> None: ... + def recv_bytes(self, maxlength: int | None = None) -> bytes: ... + def recv_bytes_into(self, buf: Any, offset: int = 0) -> int: ... + def recv(self) -> _RecvT_co: ... + def poll(self, timeout: float | None = 0.0) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + +class Connection(_ConnectionBase[_SendT_contra, _RecvT_co]): ... + +if sys.platform == "win32": + class PipeConnection(_ConnectionBase[_SendT_contra, _RecvT_co]): ... + +class Listener: + def __init__( + self, address: _Address | None = None, family: str | None = None, backlog: int = 1, authkey: bytes | None = None + ) -> None: ... + if sys.platform != "win32": + def accept(self) -> Connection[Incomplete, Incomplete]: ... + else: + def accept(self) -> Connection[Incomplete, Incomplete] | PipeConnection[Incomplete, Incomplete]: ... + + def close(self) -> None: ... + @property + def address(self) -> _Address: ... + @property + def last_accepted(self) -> _Address | None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +# Any: send and recv methods unused +if sys.version_info >= (3, 12): + def deliver_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes, digest_name: str = "sha256") -> None: ... + +else: + def deliver_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes) -> None: ... + +def answer_challenge(connection: _ConnectionBase[Any, Any], authkey: bytes) -> None: ... +def wait( + object_list: Iterable[_ConnectionBase[_SendT_contra, _RecvT_co] | socket.socket | int], timeout: float | None = None +) -> list[_ConnectionBase[_SendT_contra, _RecvT_co] | socket.socket | int]: ... + +if sys.platform != "win32": + def Client(address: _Address, family: str | None = None, authkey: bytes | None = None) -> Connection[Any, Any]: ... + +else: + def Client( + address: _Address, family: str | None = None, authkey: bytes | None = None + ) -> Connection[Any, Any] | PipeConnection[Any, Any]: ... + +# N.B. Keep this in sync with multiprocessing.context.BaseContext.Pipe. +# _ConnectionBase is the common base class of Connection and PipeConnection +# and can be used in cross-platform code. +# +# The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]). +# However, TypeVars scoped entirely within a return annotation is unspecified in the spec. +if sys.platform != "win32": + def Pipe(duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ... + +else: + def Pipe(duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ... diff --git a/stdlib/multiprocessing/context.pyi b/stdlib/multiprocessing/context.pyi new file mode 100644 index 000000000000..13fd967515d0 --- /dev/null +++ b/stdlib/multiprocessing/context.pyi @@ -0,0 +1,220 @@ +import ctypes +import sys +from _ctypes import _CData +from collections.abc import Callable, Iterable, Sequence +from ctypes import _SimpleCData, c_char +from logging import Logger, _Level as _LoggingLevel +from multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, synchronize +from multiprocessing.managers import SyncManager +from multiprocessing.pool import Pool as _Pool +from multiprocessing.process import BaseProcess +from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString +from typing import Any, ClassVar, Literal, TypeAlias, TypeVar, overload + +if sys.platform != "win32": + from multiprocessing.connection import Connection +else: + from multiprocessing.connection import PipeConnection + +__all__ = () + +_LockLike: TypeAlias = synchronize.Lock | synchronize.RLock +_T = TypeVar("_T") +_CT = TypeVar("_CT", bound=_CData) + +class ProcessError(Exception): ... +class BufferTooShort(ProcessError): ... +class TimeoutError(ProcessError): ... +class AuthenticationError(ProcessError): ... + +class BaseContext: + ProcessError: ClassVar[type[ProcessError]] + BufferTooShort: ClassVar[type[BufferTooShort]] + TimeoutError: ClassVar[type[TimeoutError]] + AuthenticationError: ClassVar[type[AuthenticationError]] + + # N.B. The methods below are applied at runtime to generate + # multiprocessing.*, so the signatures should be identical (modulo self). + @staticmethod + def current_process() -> BaseProcess: ... + @staticmethod + def parent_process() -> BaseProcess | None: ... + @staticmethod + def active_children() -> list[BaseProcess]: ... + def cpu_count(self) -> int: ... + def Manager(self) -> SyncManager: ... + + # N.B. Keep this in sync with multiprocessing.connection.Pipe. + # _ConnectionBase is the common base class of Connection and PipeConnection + # and can be used in cross-platform code. + # + # The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]). + # However, TypeVars scoped entirely within a return annotation is unspecified in the spec. + if sys.platform != "win32": + def Pipe(self, duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ... + else: + def Pipe(self, duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ... + + def Barrier( + self, parties: int, action: Callable[..., object] | None = None, timeout: float | None = None + ) -> synchronize.Barrier: ... + def BoundedSemaphore(self, value: int = 1) -> synchronize.BoundedSemaphore: ... + def Condition(self, lock: _LockLike | None = None) -> synchronize.Condition: ... + def Event(self) -> synchronize.Event: ... + def Lock(self) -> synchronize.Lock: ... + def RLock(self) -> synchronize.RLock: ... + def Semaphore(self, value: int = 1) -> synchronize.Semaphore: ... + def Queue(self, maxsize: int = 0) -> queues.Queue[Any]: ... + def JoinableQueue(self, maxsize: int = 0) -> queues.JoinableQueue[Any]: ... + def SimpleQueue(self) -> queues.SimpleQueue[Any]: ... + def Pool( + self, + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, + ) -> _Pool: ... + + @overload + def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ... + @overload + def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... + + @overload + def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... + @overload + def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + + @overload + def Value( + self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True + ) -> Synchronized[_T]: ... + @overload + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ... + @overload + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[_CT]: ... + @overload + def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[Any]: ... + @overload + def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... + + @overload + def Array( + self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] + ) -> SynchronizedArray[_T]: ... + @overload + def Array( + self, typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True + ) -> SynchronizedString: ... + @overload + def Array( + self, + typecode_or_type: type[_SimpleCData[_T]], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ) -> SynchronizedArray[_T]: ... + @overload + def Array( + self, typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True + ) -> SynchronizedArray[Any]: ... + @overload + def Array( + self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = True + ) -> Any: ... + + def freeze_support(self) -> None: ... + def get_logger(self) -> Logger: ... + def log_to_stderr(self, level: _LoggingLevel | None = None) -> Logger: ... + def allow_connection_pickling(self) -> None: ... + def set_executable(self, executable: str) -> None: ... + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, module_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, module_names: list[str]) -> None: ... + + @overload + def get_context(self, method: None = None) -> DefaultContext: ... + @overload + def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... + if sys.platform != "win32": + @overload + def get_context(self, method: Literal["fork"]) -> ForkContext: ... + @overload + def get_context(self, method: Literal["forkserver"]) -> ForkServerContext: ... + + @overload + def get_context(self, method: str) -> BaseContext: ... + + @overload + def get_start_method(self, allow_none: Literal[False] = False) -> str: ... + @overload + def get_start_method(self, allow_none: bool) -> str | None: ... + + def set_start_method(self, method: str | None, force: bool = False) -> None: ... + + @property + def reducer(self) -> str: ... + @reducer.setter + def reducer(self, reduction: str) -> None: ... + + def _check_available(self) -> None: ... + +class Process(BaseProcess): + _start_method: str | None + @staticmethod + def _Popen(process_obj: BaseProcess) -> DefaultContext: ... + +class DefaultContext(BaseContext): + Process: ClassVar[type[Process]] + def __init__(self, context: BaseContext) -> None: ... + def get_start_method(self, allow_none: bool = False) -> str: ... + def get_all_start_methods(self) -> list[str]: ... + +_default_context: DefaultContext + +class SpawnProcess(BaseProcess): + _start_method: str + if sys.platform != "win32": + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_spawn_posix.Popen: ... + else: + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_spawn_win32.Popen: ... + +class SpawnContext(BaseContext): + _name: str + Process: ClassVar[type[SpawnProcess]] + +if sys.platform != "win32": + class ForkProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_fork.Popen: ... + + class ForkServerProcess(BaseProcess): + _start_method: str + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_forkserver.Popen: ... + + class ForkContext(BaseContext): + _name: str + Process: ClassVar[type[ForkProcess]] + + class ForkServerContext(BaseContext): + _name: str + Process: ClassVar[type[ForkServerProcess]] + +def _force_start_method(method: str) -> None: ... + +if sys.platform != "win32": + def get_spawning_popen() -> popen_forkserver.Popen | popen_spawn_posix.Popen | None: ... + def set_spawning_popen(popen: popen_forkserver.Popen | popen_spawn_posix.Popen | None) -> None: ... + +else: + def get_spawning_popen() -> popen_spawn_win32.Popen | None: ... + def set_spawning_popen(popen: popen_spawn_win32.Popen | None) -> None: ... + +def assert_spawning(obj: Any) -> None: ... diff --git a/stdlib/multiprocessing/dummy/__init__.pyi b/stdlib/multiprocessing/dummy/__init__.pyi new file mode 100644 index 000000000000..62fef2b080f2 --- /dev/null +++ b/stdlib/multiprocessing/dummy/__init__.pyi @@ -0,0 +1,89 @@ +import array +import sys +import threading +import weakref +from collections.abc import Callable, Iterable, Mapping, Sequence +from queue import Queue as Queue +from threading import ( + Barrier as Barrier, + BoundedSemaphore as BoundedSemaphore, + Condition as Condition, + Event as Event, + Lock as Lock, + RLock as RLock, + Semaphore as Semaphore, +) +from typing import Any, Literal + +from .connection import Pipe as Pipe + +__all__ = [ + "Process", + "current_process", + "active_children", + "freeze_support", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Condition", + "Event", + "Barrier", + "Queue", + "Manager", + "Pipe", + "Pool", + "JoinableQueue", +] + +JoinableQueue = Queue + +class DummyProcess(threading.Thread): + _children: weakref.WeakKeyDictionary[Any, Any] + _parent: threading.Thread + _pid: None + _start_called: int + @property + def exitcode(self) -> Literal[0] | None: ... + if sys.version_info >= (3, 14): + # Default changed in Python 3.14.1 + def __init__( + self, + group: Any = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + ) -> None: ... + else: + def __init__( + self, + group: Any = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = {}, + ) -> None: ... + +Process = DummyProcess + +class Namespace: + def __init__(self, **kwds: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +class Value: + _typecode: Any + _value: Any + value: Any + def __init__(self, typecode: Any, value: Any, lock: Any = True) -> None: ... + +def Array(typecode: Any, sequence: Sequence[Any], lock: Any = True) -> array.array[Any]: ... +def Manager() -> Any: ... +def Pool(processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> Any: ... +def active_children() -> list[Any]: ... + +current_process = threading.current_thread + +def freeze_support() -> None: ... +def shutdown() -> None: ... diff --git a/stdlib/multiprocessing/dummy/connection.pyi b/stdlib/multiprocessing/dummy/connection.pyi new file mode 100644 index 000000000000..d7e982129466 --- /dev/null +++ b/stdlib/multiprocessing/dummy/connection.pyi @@ -0,0 +1,39 @@ +from multiprocessing.connection import _Address +from queue import Queue +from types import TracebackType +from typing import Any +from typing_extensions import Self + +__all__ = ["Client", "Listener", "Pipe"] + +families: list[None] + +class Connection: + _in: Any + _out: Any + recv: Any + recv_bytes: Any + send: Any + send_bytes: Any + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __init__(self, _in: Any, _out: Any) -> None: ... + def close(self) -> None: ... + def poll(self, timeout: float = 0.0) -> bool: ... + +class Listener: + _backlog_queue: Queue[Any] | None + @property + def address(self) -> Queue[Any] | None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __init__(self, address: _Address | None = None, family: int | None = None, backlog: int = 1) -> None: ... + def accept(self) -> Connection: ... + def close(self) -> None: ... + +def Client(address: _Address) -> Connection: ... +def Pipe(duplex: bool = True) -> tuple[Connection, Connection]: ... diff --git a/stdlib/multiprocessing/forkserver.pyi b/stdlib/multiprocessing/forkserver.pyi new file mode 100644 index 000000000000..e48be5f07949 --- /dev/null +++ b/stdlib/multiprocessing/forkserver.pyi @@ -0,0 +1,78 @@ +import sys +from _typeshed import FileDescriptorLike, Unused +from collections.abc import Sequence +from struct import Struct +from typing import Any, Final, Literal + +__all__ = ["ensure_running", "get_inherited_fds", "connect_to_new_process", "set_forkserver_preload"] + +MAXFDS_TO_SEND: Final = 256 +SIGNED_STRUCT: Final[Struct] + +class ForkServer: + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, modules_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, modules_names: list[str]) -> None: ... + + def get_inherited_fds(self) -> list[int] | None: ... + def connect_to_new_process(self, fds: Sequence[int]) -> tuple[int, int]: ... + def ensure_running(self) -> None: ... + +if sys.version_info >= (3, 15): + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + authkey_r: int | None = None, + on_error: str = "ignore", + ) -> None: ... + +elif sys.version_info >= (3, 14): + # `sys_argv` parameter added in Python 3.14.3 + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + authkey_r: int | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 13): + # `sys_argv` parameter added in Python 3.13.12 + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + ) -> None: ... + +else: + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: Unused = None, + ) -> None: ... + +def read_signed(fd: int) -> Any: ... +def write_signed(fd: int, n: int) -> None: ... + +_forkserver: ForkServer +ensure_running = _forkserver.ensure_running +get_inherited_fds = _forkserver.get_inherited_fds +connect_to_new_process = _forkserver.connect_to_new_process +set_forkserver_preload = _forkserver.set_forkserver_preload diff --git a/stdlib/multiprocessing/heap.pyi b/stdlib/multiprocessing/heap.pyi new file mode 100644 index 000000000000..bf6f853a9760 --- /dev/null +++ b/stdlib/multiprocessing/heap.pyi @@ -0,0 +1,41 @@ +import sys +from collections.abc import Callable +from mmap import mmap +from multiprocessing import popen_forkserver, popen_spawn_posix, resource_sharer +from typing import Protocol, TypeAlias, type_check_only + +__all__ = ["BufferWrapper"] + +class Arena: + size: int + buffer: mmap + if sys.platform == "win32": + name: str + def __init__(self, size: int) -> None: ... + else: + fd: int + def __init__(self, size: int, fd: int = -1) -> None: ... + +_Block: TypeAlias = tuple[Arena, int, int] + +if sys.platform != "win32": + @type_check_only + class _SupportsDetach(Protocol): + def detach(self) -> int: ... + + def reduce_arena( + a: Arena, + ) -> tuple[ + Callable[[int, _SupportsDetach], Arena], + tuple[int, popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd], + ]: ... + def rebuild_arena(size: int, dupfd: _SupportsDetach) -> Arena: ... + +class Heap: + def __init__(self, size: int = ...) -> None: ... + def free(self, block: _Block) -> None: ... + def malloc(self, size: int) -> _Block: ... + +class BufferWrapper: + def __init__(self, size: int) -> None: ... + def create_memoryview(self) -> memoryview: ... diff --git a/stdlib/multiprocessing/managers.pyi b/stdlib/multiprocessing/managers.pyi new file mode 100644 index 000000000000..0f1d4e87b0dc --- /dev/null +++ b/stdlib/multiprocessing/managers.pyi @@ -0,0 +1,390 @@ +import builtins +import queue +import sys +import threading +from _typeshed import SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + MutableMapping, + MutableSequence, + MutableSet, + Sequence, + Set as AbstractSet, +) +from types import GenericAlias, TracebackType +from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from . import pool +from .connection import Connection, _Address +from .context import BaseContext +from .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory +from .util import Finalize as _Finalize + +__all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_S = TypeVar("_S") + +class Namespace: + def __init__(self, **kwds: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +_Namespace: TypeAlias = Namespace + +class Token: + __slots__ = ("typeid", "address", "id") + typeid: str | bytes | None + address: _Address | None + id: str | bytes | int | None + def __init__(self, typeid: bytes | str | None, address: _Address | None, id: str | bytes | int | None) -> None: ... + def __getstate__(self) -> tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]: ... + def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ... + +class BaseProxy: + _address_to_local: dict[_Address, Any] + _mutex: Any + def __init__( + self, + token: Any, + serializer: str, + manager: Any = None, + authkey: AnyStr | None = None, + exposed: Any = None, + incref: bool = True, + manager_owned: bool = False, + ) -> None: ... + def __deepcopy__(self, memo: Any | None) -> Any: ... + def _callmethod(self, methodname: str, args: tuple[Any, ...] = (), kwds: dict[Any, Any] = {}) -> None: ... + def _getvalue(self) -> Any: ... + def __reduce__(self) -> tuple[Any, tuple[Any, Any, str, dict[Any, Any]]]: ... + +class ValueProxy(BaseProxy, Generic[_T]): + def get(self) -> _T: ... + def set(self, value: _T) -> None: ... + value: _T + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 13): + class _BaseDictProxy(BaseProxy, MutableMapping[_KT, _VT]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> dict[_KT, _VT]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> list[_KT]: ... # type: ignore[override] + def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> list[_VT]: ... # type: ignore[override] + if sys.version_info >= (3, 14): + # Next methods are copied from builtins.dict + @overload + def fromkeys(self, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... + @overload + def fromkeys(self, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + + def __reversed__(self) -> Iterator[_KT]: ... + + @overload + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[misc] + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... + @overload + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... + + class DictProxy(_BaseDictProxy[_KT, _VT]): + def __class_getitem__(cls, args: Any, /) -> GenericAlias: ... + +else: + class DictProxy(BaseProxy, MutableMapping[_KT, _VT]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + def __delitem__(self, key: _KT, /) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> dict[_KT, _VT]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> list[_KT]: ... # type: ignore[override] + def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> list[_VT]: ... # type: ignore[override] + +if sys.version_info >= (3, 14): + class _BaseSetProxy(BaseProxy, MutableSet[_T]): + __builtins__: ClassVar[dict[str, Any]] + # Copied from builtins.set + def add(self, element: _T, /) -> None: ... + def copy(self) -> set[_T]: ... + def clear(self) -> None: ... + def difference(self, *s: Iterable[Any]) -> set[_T]: ... + def difference_update(self, *s: Iterable[Any]) -> None: ... + def discard(self, element: _T, /) -> None: ... + def intersection(self, *s: Iterable[Any]) -> set[_T]: ... + def intersection_update(self, *s: Iterable[Any]) -> None: ... + def isdisjoint(self, s: Iterable[Any], /) -> bool: ... + def issubset(self, s: Iterable[Any], /) -> bool: ... + def issuperset(self, s: Iterable[Any], /) -> bool: ... + def pop(self) -> _T: ... + def remove(self, element: _T, /) -> None: ... + def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: ... + def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ... + def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... + def update(self, *s: Iterable[_T]) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, o: object, /) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... + def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __le__(self, value: AbstractSet[object], /) -> bool: ... + def __lt__(self, value: AbstractSet[object], /) -> bool: ... + def __ge__(self, value: AbstractSet[object], /) -> bool: ... + def __gt__(self, value: AbstractSet[object], /) -> bool: ... + def __eq__(self, value: object, /) -> bool: ... + def __rand__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __ror__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[misc] + def __rsub__(self, value: AbstractSet[_T], /) -> set[_T]: ... + def __rxor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[misc] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + class SetProxy(_BaseSetProxy[_T]): ... + +class BaseListProxy(BaseProxy, MutableSequence[_T]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __add__(self, x: list[_T], /) -> list[_T]: ... + def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + + @overload + def __getitem__(self, i: SupportsIndex, /) -> _T: ... + @overload + def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + + @overload + def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ... + @overload + def __setitem__(self, s: slice[SupportsIndex | None], o: Iterable[_T], /) -> None: ... + + def __mul__(self, n: SupportsIndex, /) -> list[_T]: ... + def __rmul__(self, n: SupportsIndex, /) -> list[_T]: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... + def __reversed__(self) -> Iterator[_T]: ... + def append(self, object: _T, /) -> None: ... + def extend(self, iterable: Iterable[_T], /) -> None: ... + def pop(self, index: SupportsIndex = ..., /) -> _T: ... + def index(self, value: _T, start: SupportsIndex = ..., stop: SupportsIndex = ..., /) -> int: ... + def count(self, value: _T, /) -> int: ... + def insert(self, index: SupportsIndex, object: _T, /) -> None: ... + def remove(self, value: _T, /) -> None: ... + if sys.version_info >= (3, 14): + # Next methods are copied from builtins.list + def clear(self) -> None: ... + def copy(self) -> list[_T]: ... + + # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance + @overload + def sort(self: BaseListProxy[SupportsRichComparisonT], *, key: None = None, reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... + +class ListProxy(BaseListProxy[_T]): + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[override] + def __imul__(self, value: SupportsIndex, /) -> Self: ... # type: ignore[override] + if sys.version_info >= (3, 13): + def __class_getitem__(cls, args: Any, /) -> Any: ... + +# Send is (kind, result) +# Receive is (id, methodname, args, kwds) +_ServerConnection: TypeAlias = Connection[tuple[str, Any], tuple[str, str, Iterable[Any], Mapping[str, Any]]] + +# Returned by BaseManager.get_server() +class Server: + address: _Address | None + id_to_obj: dict[str, tuple[Any, set[str], dict[str, str]]] + fallback_mapping: dict[str, Callable[[_ServerConnection, str, Any], Any]] + public: list[str] + # Registry values are (callable, exposed, method_to_typeid, proxytype) + def __init__( + self, + registry: dict[str, tuple[Callable[..., Any], Iterable[str], dict[str, str], Any]], + address: _Address | None, + authkey: bytes, + serializer: str, + ) -> None: ... + def serve_forever(self) -> None: ... + def accepter(self) -> None: ... + def handle_request(self, conn: _ServerConnection) -> None: ... + def serve_client(self, conn: _ServerConnection) -> None: ... + def fallback_getvalue(self, conn: _ServerConnection, ident: str, obj: _T) -> _T: ... + def fallback_str(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... + def fallback_repr(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... + def dummy(self, c: _ServerConnection) -> None: ... + def debug_info(self, c: _ServerConnection) -> str: ... + def number_of_objects(self, c: _ServerConnection) -> int: ... + def shutdown(self, c: _ServerConnection) -> None: ... + def create(self, c: _ServerConnection, typeid: str, /, *args: Any, **kwds: Any) -> tuple[str, tuple[str, ...]]: ... + def get_methods(self, c: _ServerConnection, token: Token) -> set[str]: ... + def accept_connection(self, c: _ServerConnection, name: str) -> None: ... + def incref(self, c: _ServerConnection, ident: str) -> None: ... + def decref(self, c: _ServerConnection, ident: str) -> None: ... + +class BaseManager: + if sys.version_info >= (3, 11): + def __init__( + self, + address: _Address | None = None, + authkey: bytes | None = None, + serializer: str = "pickle", + ctx: BaseContext | None = None, + *, + shutdown_timeout: float = 1.0, + ) -> None: ... + else: + def __init__( + self, + address: _Address | None = None, + authkey: bytes | None = None, + serializer: str = "pickle", + ctx: BaseContext | None = None, + ) -> None: ... + + def get_server(self) -> Server: ... + def connect(self) -> None: ... + def start(self, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> None: ... + shutdown: _Finalize # only available after start() was called + def join(self, timeout: float | None = None) -> None: ... # undocumented + @property + def address(self) -> _Address | None: ... + @classmethod + def register( + cls, + typeid: str, + callable: Callable[..., object] | None = None, + proxytype: Any = None, + exposed: Sequence[str] | None = None, + method_to_typeid: Mapping[str, str] | None = None, + create_method: bool = True, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class SyncManager(BaseManager): + def Barrier( + self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None + ) -> threading.Barrier: ... + def BoundedSemaphore(self, value: int = 1) -> threading.BoundedSemaphore: ... + def Condition(self, lock: threading.Lock | threading._RLock | None = None) -> threading.Condition: ... + def Event(self) -> threading.Event: ... + def Lock(self) -> threading.Lock: ... + def Namespace(self) -> _Namespace: ... + def Pool( + self, + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, + context: Any | None = None, + ) -> pool.Pool: ... + def Queue(self, maxsize: int = ...) -> queue.Queue[Any]: ... + def JoinableQueue(self, maxsize: int = ...) -> queue.Queue[Any]: ... + def RLock(self) -> threading.RLock: ... + def Semaphore(self, value: int = 1) -> threading.Semaphore: ... + def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... + def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ... + + # Overloads are copied from builtins.dict.__init__ + @overload + def dict(self) -> DictProxy[Any, Any]: ... + @overload + def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, iterable: Iterable[tuple[_KT, _VT]], /) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, iterable: Iterable[builtins.list[str]], /) -> DictProxy[str, str]: ... + @overload + def dict(self, iterable: Iterable[builtins.list[bytes]], /) -> DictProxy[bytes, bytes]: ... + + # Overloads are copied from builtins.list.__init__ + @overload + def list(self, iterable: Iterable[_T], /) -> ListProxy[_T]: ... + @overload + def list(self) -> ListProxy[Any]: ... + + if sys.version_info >= (3, 14): + @overload + def set(self, iterable: Iterable[_T], /) -> SetProxy[_T]: ... + @overload + def set(self) -> SetProxy[Any]: ... + +class RemoteError(Exception): ... + +class SharedMemoryServer(Server): + def track_segment(self, c: _ServerConnection, segment_name: str) -> None: ... + def release_segment(self, c: _ServerConnection, segment_name: str) -> None: ... + def list_segments(self, c: _ServerConnection) -> list[str]: ... + +class SharedMemoryManager(BaseManager): + def get_server(self) -> SharedMemoryServer: ... + def SharedMemory(self, size: int) -> _SharedMemory: ... + def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ... + def __del__(self) -> None: ... diff --git a/stdlib/multiprocessing/pool.pyi b/stdlib/multiprocessing/pool.pyi new file mode 100644 index 000000000000..5642e50d0e76 --- /dev/null +++ b/stdlib/multiprocessing/pool.pyi @@ -0,0 +1,101 @@ +from collections.abc import Callable, Iterable, Mapping +from multiprocessing.context import DefaultContext, Process as _Process +from types import GenericAlias, TracebackType +from typing import Any, Final, Generic, TypeVar +from typing_extensions import Self + +__all__ = ["Pool", "ThreadPool"] + +_S = TypeVar("_S") +_T = TypeVar("_T") + +class ApplyResult(Generic[_T]): + def __init__( + self, pool: Pool, callback: Callable[[_T], object] | None, error_callback: Callable[[BaseException], object] | None + ) -> None: ... + def get(self, timeout: float | None = None) -> _T: ... + def wait(self, timeout: float | None = None) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# alias created during issue #17805 +AsyncResult = ApplyResult + +class MapResult(ApplyResult[list[_T]]): + def __init__( + self, + pool: Pool, + chunksize: int, + length: int, + callback: Callable[[list[_T]], object] | None, + error_callback: Callable[[BaseException], object] | None, + ) -> None: ... + +class IMapIterator(Generic[_T]): + def __init__(self, pool: Pool) -> None: ... + def __iter__(self) -> Self: ... + def next(self, timeout: float | None = None) -> _T: ... + def __next__(self, timeout: float | None = None) -> _T: ... + +class IMapUnorderedIterator(IMapIterator[_T]): ... + +class Pool: + def __init__( + self, + processes: int | None = None, + initializer: Callable[..., object] | None = None, + initargs: Iterable[Any] = (), + maxtasksperchild: int | None = None, + context: Any | None = None, + ) -> None: ... + @staticmethod + def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> _Process: ... + def apply(self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Mapping[str, Any] = {}) -> _T: ... + def apply_async( + self, + func: Callable[..., _T], + args: Iterable[Any] = (), + kwds: Mapping[str, Any] = {}, + callback: Callable[[_T], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, + ) -> AsyncResult[_T]: ... + def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = None) -> list[_T]: ... + def map_async( + self, + func: Callable[[_S], _T], + iterable: Iterable[_S], + chunksize: int | None = None, + callback: Callable[[list[_T]], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, + ) -> MapResult[_T]: ... + def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ... + def imap_unordered(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ... + def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: int | None = None) -> list[_T]: ... + def starmap_async( + self, + func: Callable[..., _T], + iterable: Iterable[Iterable[Any]], + chunksize: int | None = None, + callback: Callable[[list[_T]], object] | None = None, + error_callback: Callable[[BaseException], object] | None = None, + ) -> AsyncResult[list[_T]]: ... + def close(self) -> None: ... + def terminate(self) -> None: ... + def join(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + +class ThreadPool(Pool): + def __init__( + self, processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = () + ) -> None: ... + +# undocumented +INIT: Final = "INIT" +RUN: Final = "RUN" +CLOSE: Final = "CLOSE" +TERMINATE: Final = "TERMINATE" diff --git a/stdlib/multiprocessing/popen_fork.pyi b/stdlib/multiprocessing/popen_fork.pyi new file mode 100644 index 000000000000..5e53b055cc79 --- /dev/null +++ b/stdlib/multiprocessing/popen_fork.pyi @@ -0,0 +1,26 @@ +import sys +from typing import ClassVar + +from .process import BaseProcess +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class Popen: + finalizer: Finalize | None + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int # doesn't exist if os.fork in _launch returns 0 + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, fd: int) -> int: ... + def poll(self, flag: int = 1) -> int | None: ... + def wait(self, timeout: float | None = None) -> int | None: ... + if sys.version_info >= (3, 14): + def interrupt(self) -> None: ... + + def terminate(self) -> None: ... + def kill(self) -> None: ... + def close(self) -> None: ... diff --git a/stdlib/multiprocessing/popen_forkserver.pyi b/stdlib/multiprocessing/popen_forkserver.pyi new file mode 100644 index 000000000000..f7d53bbb3e41 --- /dev/null +++ b/stdlib/multiprocessing/popen_forkserver.pyi @@ -0,0 +1,16 @@ +import sys +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + def __init__(self, ind: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize diff --git a/stdlib/multiprocessing/popen_spawn_posix.pyi b/stdlib/multiprocessing/popen_spawn_posix.pyi new file mode 100644 index 000000000000..7e81d39600ad --- /dev/null +++ b/stdlib/multiprocessing/popen_spawn_posix.pyi @@ -0,0 +1,20 @@ +import sys +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + fd: int + + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize + pid: int # may not exist if _launch raises in second try / except + sentinel: int # may not exist if _launch raises in second try / except diff --git a/stdlib/multiprocessing/popen_spawn_win32.pyi b/stdlib/multiprocessing/popen_spawn_win32.pyi new file mode 100644 index 000000000000..481b9eec5a37 --- /dev/null +++ b/stdlib/multiprocessing/popen_spawn_win32.pyi @@ -0,0 +1,30 @@ +import sys +from multiprocessing.process import BaseProcess +from typing import ClassVar, Final + +from .util import Finalize + +if sys.platform == "win32": + __all__ = ["Popen"] + + TERMINATE: Final[int] + WINEXE: Final[bool] + WINSERVICE: Final[bool] + WINENV: Final[bool] + + class Popen: + finalizer: Finalize + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, handle: int) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def poll(self) -> int | None: ... + def terminate(self) -> None: ... + + kill = terminate + + def close(self) -> None: ... diff --git a/stdlib/multiprocessing/process.pyi b/stdlib/multiprocessing/process.pyi new file mode 100644 index 000000000000..c7d13b318a44 --- /dev/null +++ b/stdlib/multiprocessing/process.pyi @@ -0,0 +1,43 @@ +import sys +from collections.abc import Callable, Iterable, Mapping +from typing import Any + +__all__ = ["BaseProcess", "current_process", "active_children", "parent_process"] + +class BaseProcess: + name: str + daemon: bool + authkey: bytes + _identity: tuple[int, ...] # undocumented + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] = {}, + *, + daemon: bool | None = None, + ) -> None: ... + def run(self) -> None: ... + def start(self) -> None: ... + if sys.version_info >= (3, 14): + def interrupt(self) -> None: ... + + def terminate(self) -> None: ... + def kill(self) -> None: ... + def close(self) -> None: ... + def join(self, timeout: float | None = None) -> None: ... + def is_alive(self) -> bool: ... + @property + def exitcode(self) -> int | None: ... + @property + def ident(self) -> int | None: ... + @property + def pid(self) -> int | None: ... + @property + def sentinel(self) -> int: ... + +def current_process() -> BaseProcess: ... +def active_children() -> list[BaseProcess]: ... +def parent_process() -> BaseProcess | None: ... diff --git a/stdlib/multiprocessing/queues.pyi b/stdlib/multiprocessing/queues.pyi new file mode 100644 index 000000000000..8f0feb834619 --- /dev/null +++ b/stdlib/multiprocessing/queues.pyi @@ -0,0 +1,46 @@ +import sys +from types import GenericAlias +from typing import Any, Generic, NewType, TypeVar + +__all__ = ["Queue", "SimpleQueue", "JoinableQueue"] + +_T = TypeVar("_T") + +_QueueState = NewType("_QueueState", object) +_JoinableQueueState = NewType("_JoinableQueueState", object) +_SimpleQueueState = NewType("_SimpleQueueState", object) + +class Queue(Generic[_T]): + # FIXME: `ctx` is a circular dependency and it's not actually optional. + # It's marked as such to be able to use the generic Queue in __init__.pyi. + def __init__(self, maxsize: int = 0, *, ctx: Any = ...) -> None: ... + def __getstate__(self) -> _QueueState: ... + def __setstate__(self, state: _QueueState) -> None: ... + def put(self, obj: _T, block: bool = True, timeout: float | None = None) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get_nowait(self) -> _T: ... + def put_nowait(self, obj: _T) -> None: ... + def close(self) -> None: ... + def join_thread(self) -> None: ... + def cancel_join_thread(self) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class JoinableQueue(Queue[_T]): + def __getstate__(self) -> _JoinableQueueState: ... # type: ignore[override] + def __setstate__(self, state: _JoinableQueueState) -> None: ... # type: ignore[override] + def task_done(self) -> None: ... + def join(self) -> None: ... + +class SimpleQueue(Generic[_T]): + def __init__(self, *, ctx: Any = ...) -> None: ... + def close(self) -> None: ... + def empty(self) -> bool: ... + def __getstate__(self) -> _SimpleQueueState: ... + def __setstate__(self, state: _SimpleQueueState) -> None: ... + def get(self) -> _T: ... + def put(self, obj: _T) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/multiprocessing/reduction.pyi b/stdlib/multiprocessing/reduction.pyi new file mode 100644 index 000000000000..476cf9b26f71 --- /dev/null +++ b/stdlib/multiprocessing/reduction.pyi @@ -0,0 +1,95 @@ +import pickle +import sys +from _pickle import _BufferCallback, _ReducedType +from _typeshed import HasFileno, SupportsWrite, Unused +from abc import ABCMeta +from builtins import type as Type # alias to avoid name clash +from collections.abc import Callable +from copyreg import _DispatchTableType +from multiprocessing import connection, popen_forkserver, popen_spawn_posix, resource_sharer +from socket import socket +from typing import Any, Final + +if sys.platform == "win32": + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupHandle", "duplicate", "steal_handle"] +else: + __all__ = ["send_handle", "recv_handle", "ForkingPickler", "register", "dump", "DupFd", "sendfds", "recvfds"] + +HAVE_SEND_HANDLE: Final[bool] + +class ForkingPickler(pickle.Pickler): + dispatch_table: _DispatchTableType + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + /, + ) -> None: ... + @classmethod + def register(cls, type: Type, reduce: Callable[[Any], _ReducedType]) -> None: ... + @classmethod + def dumps(cls, obj: Any, protocol: int | None = None) -> memoryview: ... + loads = pickle.loads + +register = ForkingPickler.register + +def dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None) -> None: ... + +if sys.platform == "win32": + def duplicate( + handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None + ) -> int: ... + def steal_handle(source_pid: int, handle: int) -> int: ... + def send_handle(conn: connection.PipeConnection[DupHandle, Any], handle: int, destination_pid: int) -> None: ... + def recv_handle(conn: connection.PipeConnection[Any, DupHandle]) -> int: ... + + class DupHandle: + def __init__(self, handle: int, access: int, pid: int | None = None) -> None: ... + def detach(self) -> int: ... + +else: + if sys.version_info < (3, 14): + ACKNOWLEDGE: Final[bool] + + def recvfds(sock: socket, size: int) -> list[int]: ... + def send_handle(conn: HasFileno, handle: int, destination_pid: Unused) -> None: ... + def recv_handle(conn: HasFileno) -> int: ... + def sendfds(sock: socket, fds: list[int]) -> None: ... + def DupFd(fd: int) -> popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd: ... + +# These aliases are to work around pyright complaints. +# Pyright doesn't like it when a class object is defined as an alias +# of a global object with the same name. +_ForkingPickler = ForkingPickler +_register = register +_dump = dump +_send_handle = send_handle +_recv_handle = recv_handle + +if sys.platform == "win32": + _steal_handle = steal_handle + _duplicate = duplicate + _DupHandle = DupHandle +else: + _sendfds = sendfds + _recvfds = recvfds + _DupFd = DupFd + +class AbstractReducer(metaclass=ABCMeta): + ForkingPickler = _ForkingPickler + register = _register + dump = _dump + send_handle = _send_handle + recv_handle = _recv_handle + if sys.platform == "win32": + steal_handle = _steal_handle + duplicate = _duplicate + DupHandle = _DupHandle + else: + sendfds = _sendfds + recvfds = _recvfds + DupFd = _DupFd + + def __init__(self, *args: Unused) -> None: ... diff --git a/stdlib/multiprocessing/resource_sharer.pyi b/stdlib/multiprocessing/resource_sharer.pyi new file mode 100644 index 000000000000..5fee7cf31e17 --- /dev/null +++ b/stdlib/multiprocessing/resource_sharer.pyi @@ -0,0 +1,20 @@ +import sys +from socket import socket + +__all__ = ["stop"] + +if sys.platform == "win32": + __all__ += ["DupSocket"] + + class DupSocket: + def __init__(self, sock: socket) -> None: ... + def detach(self) -> socket: ... + +else: + __all__ += ["DupFd"] + + class DupFd: + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + +def stop(timeout: float | None = None) -> None: ... diff --git a/stdlib/multiprocessing/resource_tracker.pyi b/stdlib/multiprocessing/resource_tracker.pyi new file mode 100644 index 000000000000..cb2f27a62861 --- /dev/null +++ b/stdlib/multiprocessing/resource_tracker.pyi @@ -0,0 +1,21 @@ +import sys +from _typeshed import FileDescriptorOrPath +from collections.abc import Sized + +__all__ = ["ensure_running", "register", "unregister"] + +class ResourceTracker: + def getfd(self) -> int | None: ... + def ensure_running(self) -> None: ... + def register(self, name: Sized, rtype: str) -> None: ... + def unregister(self, name: Sized, rtype: str) -> None: ... + if sys.version_info >= (3, 12): + def __del__(self) -> None: ... + +_resource_tracker: ResourceTracker +ensure_running = _resource_tracker.ensure_running +register = _resource_tracker.register +unregister = _resource_tracker.unregister +getfd = _resource_tracker.getfd + +def main(fd: FileDescriptorOrPath) -> None: ... diff --git a/stdlib/multiprocessing/shared_memory.pyi b/stdlib/multiprocessing/shared_memory.pyi new file mode 100644 index 000000000000..90777a4e771b --- /dev/null +++ b/stdlib/multiprocessing/shared_memory.pyi @@ -0,0 +1,43 @@ +import sys +from collections.abc import Iterable +from types import GenericAlias +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +__all__ = ["SharedMemory", "ShareableList"] + +_SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) + +class SharedMemory: + if sys.version_info >= (3, 13): + def __init__(self, name: str | None = None, create: bool = False, size: int = 0, *, track: bool = True) -> None: ... + else: + def __init__(self, name: str | None = None, create: bool = False, size: int = 0) -> None: ... + + @property + def buf(self) -> memoryview | None: ... + @property + def name(self) -> str: ... + @property + def size(self) -> int: ... + def close(self) -> None: ... + def unlink(self) -> None: ... + def __del__(self) -> None: ... + +class ShareableList(Generic[_SLT]): + shm: SharedMemory + + @overload + def __init__(self, sequence: None = None, *, name: str | None = None) -> None: ... + @overload + def __init__(self, sequence: Iterable[_SLT], *, name: str | None = None) -> None: ... + + def __getitem__(self, position: int) -> _SLT: ... + def __setitem__(self, position: int, value: _SLT) -> None: ... + def __reduce__(self) -> tuple[Self, tuple[_SLT, ...]]: ... + def __len__(self) -> int: ... + @property + def format(self) -> str: ... + def count(self, value: _SLT) -> int: ... + def index(self, value: _SLT) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stdlib/multiprocessing/sharedctypes.pyi b/stdlib/multiprocessing/sharedctypes.pyi new file mode 100644 index 000000000000..693fd2f70139 --- /dev/null +++ b/stdlib/multiprocessing/sharedctypes.pyi @@ -0,0 +1,140 @@ +import ctypes +from _ctypes import _CData +from collections.abc import Callable, Iterable, Sequence +from ctypes import _SimpleCData, c_char +from multiprocessing.context import BaseContext +from multiprocessing.synchronize import _LockLike +from types import TracebackType +from typing import Any, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only + +__all__ = ["RawValue", "RawArray", "Value", "Array", "copy", "synchronized"] + +_T = TypeVar("_T") +_CT = TypeVar("_CT", bound=_CData) + +@overload +def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ... +@overload +def RawValue(typecode_or_type: str, *args: Any) -> Any: ... + +@overload +def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... +@overload +def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + +@overload +def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = None) -> _CT: ... +@overload +def Value( + typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None +) -> SynchronizedBase[_CT]: ... +@overload +def Value( + typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None +) -> SynchronizedBase[Any]: ... +@overload +def Value( + typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True, ctx: BaseContext | None = None +) -> Any: ... + +@overload +def Array( + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = None +) -> _CT: ... +@overload +def Array( + typecode_or_type: type[c_char], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedString: ... +@overload +def Array( + typecode_or_type: type[_SimpleCData[_T]], + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedArray[_T]: ... +@overload +def Array( + typecode_or_type: str, + size_or_initializer: int | Sequence[Any], + *, + lock: Literal[True] | _LockLike = True, + ctx: BaseContext | None = None, +) -> SynchronizedArray[Any]: ... +@overload +def Array( + typecode_or_type: str | type[_CData], + size_or_initializer: int | Sequence[Any], + *, + lock: bool | _LockLike = True, + ctx: BaseContext | None = None, +) -> Any: ... + +def copy(obj: _CT) -> _CT: ... + +@overload +def synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = None, ctx: Any | None = None) -> Synchronized[_T]: ... +@overload +def synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedString: ... +@overload +def synchronized( + obj: ctypes.Array[_SimpleCData[_T]], lock: _LockLike | None = None, ctx: Any | None = None +) -> SynchronizedArray[_T]: ... +@overload +def synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ... + +@type_check_only +class _AcquireFunc(Protocol): + def __call__(self, block: bool = ..., timeout: float | None = ..., /) -> bool: ... + +class SynchronizedBase(Generic[_CT]): + acquire: _AcquireFunc + release: Callable[[], None] + def __init__(self, obj: Any, lock: _LockLike | None = None, ctx: Any | None = None) -> None: ... + def __reduce__(self) -> tuple[Callable[[Any, _LockLike], SynchronizedBase[Any]], tuple[Any, _LockLike]]: ... + def get_obj(self) -> _CT: ... + def get_lock(self) -> _LockLike: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + +class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): + value: _T + +class SynchronizedArray(SynchronizedBase[ctypes.Array[_SimpleCData[_T]]], Generic[_T]): + def __len__(self) -> int: ... + + @overload + def __getitem__(self, i: slice[SupportsIndex | None]) -> list[_T]: ... + @overload + def __getitem__(self, i: SupportsIndex) -> _T: ... + + @overload + def __setitem__(self, i: slice[SupportsIndex | None], value: Iterable[_T]) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, value: _T) -> None: ... + + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> list[_T]: ... + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: Iterable[_T]) -> None: ... + +class SynchronizedString(SynchronizedArray[bytes]): + @overload # type: ignore[override] + def __getitem__(self, i: slice[SupportsIndex | None]) -> bytes: ... + @overload + def __getitem__(self, i: SupportsIndex) -> bytes: ... + + @overload # type: ignore[override] + def __setitem__(self, i: slice[SupportsIndex | None], value: bytes) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, value: bytes) -> None: ... + + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> bytes: ... # type: ignore[override] + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: bytes) -> None: ... # type: ignore[override] + + value: bytes + raw: bytes diff --git a/stdlib/multiprocessing/spawn.pyi b/stdlib/multiprocessing/spawn.pyi new file mode 100644 index 000000000000..4a9753222897 --- /dev/null +++ b/stdlib/multiprocessing/spawn.pyi @@ -0,0 +1,32 @@ +from collections.abc import Mapping, Sequence +from types import ModuleType +from typing import Any, Final + +__all__ = [ + "_main", + "freeze_support", + "set_executable", + "get_executable", + "get_preparation_data", + "get_command_line", + "import_main_path", +] + +WINEXE: Final[bool] +WINSERVICE: Final[bool] + +def set_executable(exe: str) -> None: ... +def get_executable() -> str: ... +def is_forking(argv: Sequence[str]) -> bool: ... +def freeze_support() -> None: ... +def get_command_line(**kwds: Any) -> list[str]: ... +def spawn_main(pipe_handle: int, parent_pid: int | None = None, tracker_fd: int | None = None) -> None: ... + +# undocumented +def _main(fd: int, parent_sentinel: int) -> int: ... +def get_preparation_data(name: str) -> dict[str, Any]: ... + +old_main_modules: list[ModuleType] + +def prepare(data: Mapping[str, Any]) -> None: ... +def import_main_path(main_path: str) -> None: ... diff --git a/stdlib/multiprocessing/synchronize.pyi b/stdlib/multiprocessing/synchronize.pyi new file mode 100644 index 000000000000..889e71c061e1 --- /dev/null +++ b/stdlib/multiprocessing/synchronize.pyi @@ -0,0 +1,63 @@ +import sys +import threading +from collections.abc import Callable +from multiprocessing.context import BaseContext +from types import TracebackType +from typing import TypeAlias + +__all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] + +_LockLike: TypeAlias = Lock | RLock + +class Barrier(threading.Barrier): + def __init__( + self, parties: int, action: Callable[[], object] | None = None, timeout: float | None = None, *, ctx: BaseContext + ) -> None: ... + +class Condition: + def __init__(self, lock: _LockLike | None = None, *, ctx: BaseContext) -> None: ... + def notify(self, n: int = 1) -> None: ... + def notify_all(self) -> None: ... + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], bool], timeout: float | None = None) -> bool: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + # These methods are copied from the lock passed to the constructor, or an + # instance of ctx.RLock() if lock was None. + def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ... + def release(self) -> None: ... + +class Event: + def __init__(self, *, ctx: BaseContext) -> None: ... + def is_set(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: float | None = None) -> bool: ... + +# Not part of public API +class SemLock: + def __init__(self, kind: int, value: int, maxvalue: int, *, ctx: BaseContext | None) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... + # These methods are copied from the wrapped _multiprocessing.SemLock object + def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ... + def release(self) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + +class Lock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class RLock(SemLock): + def __init__(self, *, ctx: BaseContext) -> None: ... + +class Semaphore(SemLock): + def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ... + def get_value(self) -> int: ... + +class BoundedSemaphore(Semaphore): + def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ... diff --git a/stdlib/multiprocessing/util.pyi b/stdlib/multiprocessing/util.pyi new file mode 100644 index 000000000000..5eb31de77f0f --- /dev/null +++ b/stdlib/multiprocessing/util.pyi @@ -0,0 +1,109 @@ +import sys +import threading +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from logging import Logger, _Level as _LoggingLevel +from typing import Any, Final, Generic, TypeVar, overload + +__all__ = [ + "sub_debug", + "debug", + "info", + "sub_warning", + "get_logger", + "log_to_stderr", + "get_temp_dir", + "register_after_fork", + "is_exiting", + "Finalize", + "ForkAwareThreadLock", + "ForkAwareLocal", + "close_all_fds_except", + "SUBDEBUG", + "SUBWARNING", +] + +if sys.version_info >= (3, 14): + __all__ += ["warn"] + +_T = TypeVar("_T") +_R_co = TypeVar("_R_co", default=Any, covariant=True) + +NOTSET: Final = 0 +SUBDEBUG: Final = 5 +DEBUG: Final = 10 +INFO: Final = 20 +SUBWARNING: Final = 25 +if sys.version_info >= (3, 14): + WARNING: Final = 30 + +LOGGER_NAME: Final[str] +DEFAULT_LOGGING_FORMAT: Final[str] + +def sub_debug(msg: object, *args: object) -> None: ... +def debug(msg: object, *args: object) -> None: ... +def info(msg: object, *args: object) -> None: ... + +if sys.version_info >= (3, 14): + def warn(msg: object, *args: object) -> None: ... + +def sub_warning(msg: object, *args: object) -> None: ... +def get_logger() -> Logger: ... +def log_to_stderr(level: _LoggingLevel | None = None) -> Logger: ... +def is_abstract_socket_namespace(address: str | bytes | None) -> bool: ... + +abstract_sockets_supported: Final[bool] + +def get_temp_dir() -> str: ... +def register_after_fork(obj: _T, func: Callable[[_T], object]) -> None: ... + +class Finalize(Generic[_R_co]): + # "args" and "kwargs" are passed as arguments to "callback". + @overload + def __init__( + self, + obj: None, + callback: Callable[..., _R_co], + *, + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + exitpriority: int, + ) -> None: ... + @overload + def __init__( + self, obj: None, callback: Callable[..., _R_co], args: Sequence[Any], kwargs: Mapping[str, Any] | None, exitpriority: int + ) -> None: ... + @overload + def __init__( + self, + obj: Any, + callback: Callable[..., _R_co], + args: Sequence[Any] = (), + kwargs: Mapping[str, Any] | None = None, + exitpriority: int | None = None, + ) -> None: ... + + def __call__( + self, + wr: Unused = None, + _finalizer_registry: MutableMapping[Incomplete, Incomplete] = {}, + sub_debug: Callable[..., object] = ..., + getpid: Callable[[], int] = ..., + ) -> _R_co: ... + def cancel(self) -> None: ... + def still_active(self) -> bool: ... + +def is_exiting() -> bool: ... + +class ForkAwareThreadLock: + acquire: Callable[[bool, float], bool] + release: Callable[[], None] + def __enter__(self) -> bool: ... + def __exit__(self, *args: Unused) -> None: ... + +class ForkAwareLocal(threading.local): ... + +MAXFD: Final[int] + +def close_all_fds_except(fds: Iterable[int]) -> None: ... +def spawnv_passfds(path: bytes, args: Sequence[ConvertibleToInt], passfds: Sequence[int]) -> int: ... diff --git a/stdlib/netrc.pyi b/stdlib/netrc.pyi new file mode 100644 index 000000000000..4b7035c3e565 --- /dev/null +++ b/stdlib/netrc.pyi @@ -0,0 +1,23 @@ +import sys +from _typeshed import StrOrBytesPath +from typing import TypeAlias + +__all__ = ["netrc", "NetrcParseError"] + +class NetrcParseError(Exception): + filename: str | None + lineno: int | None + msg: str + def __init__(self, msg: str, filename: StrOrBytesPath | None = None, lineno: int | None = None) -> None: ... + +# (login, account, password) tuple +if sys.version_info >= (3, 11): + _NetrcTuple: TypeAlias = tuple[str, str, str] +else: + _NetrcTuple: TypeAlias = tuple[str, str | None, str | None] + +class netrc: + hosts: dict[str, _NetrcTuple] + macros: dict[str, list[str]] + def __init__(self, file: StrOrBytesPath | None = None) -> None: ... + def authenticators(self, host: str) -> _NetrcTuple | None: ... diff --git a/stdlib/nis.pyi b/stdlib/nis.pyi new file mode 100644 index 000000000000..10eef2336a83 --- /dev/null +++ b/stdlib/nis.pyi @@ -0,0 +1,9 @@ +import sys + +if sys.platform != "win32": + def cat(map: str, domain: str = ...) -> dict[str, str]: ... + def get_default_domain() -> str: ... + def maps(domain: str = ...) -> list[str]: ... + def match(key: str, map: str, domain: str = ...) -> str: ... + + class error(Exception): ... diff --git a/stdlib/nntplib.pyi b/stdlib/nntplib.pyi new file mode 100644 index 000000000000..50b633ce1ad1 --- /dev/null +++ b/stdlib/nntplib.pyi @@ -0,0 +1,120 @@ +import datetime +import socket +import ssl +from _typeshed import Unused +from builtins import list as _list # conflicts with a method named "list" +from collections.abc import Iterable +from typing import IO, Any, Final, NamedTuple, TypeAlias +from typing_extensions import Self + +__all__ = [ + "NNTP", + "NNTPError", + "NNTPReplyError", + "NNTPTemporaryError", + "NNTPPermanentError", + "NNTPProtocolError", + "NNTPDataError", + "decode_header", + "NNTP_SSL", +] + +_File: TypeAlias = IO[bytes] | bytes | str | None + +class NNTPError(Exception): + response: str + +class NNTPReplyError(NNTPError): ... +class NNTPTemporaryError(NNTPError): ... +class NNTPPermanentError(NNTPError): ... +class NNTPProtocolError(NNTPError): ... +class NNTPDataError(NNTPError): ... + +NNTP_PORT: Final = 119 +NNTP_SSL_PORT: Final = 563 + +class GroupInfo(NamedTuple): + group: str + last: str + first: str + flag: str + +class ArticleInfo(NamedTuple): + number: int + message_id: str + lines: list[bytes] + +def decode_header(header_str: str) -> str: ... + +class NNTP: + encoding: str + errors: str + + host: str + port: int + sock: socket.socket + file: IO[bytes] + debugging: int + welcome: str + readermode_afterauth: bool + tls_on: bool + authenticated: bool + nntp_implementation: str + nntp_version: int + def __init__( + self, + host: str, + port: int = 119, + user: str | None = None, + password: str | None = None, + readermode: bool | None = None, + usenetrc: bool = False, + timeout: float = ..., + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def getwelcome(self) -> str: ... + def getcapabilities(self) -> dict[str, _list[str]]: ... + def set_debuglevel(self, level: int) -> None: ... + def debug(self, level: int) -> None: ... + def capabilities(self) -> tuple[str, dict[str, _list[str]]]: ... + def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ... + def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ... + def list(self, group_pattern: str | None = None, *, file: _File = None) -> tuple[str, _list[str]]: ... + def description(self, group: str) -> str: ... + def descriptions(self, group_pattern: str) -> tuple[str, dict[str, str]]: ... + def group(self, name: str) -> tuple[str, int, int, int, str]: ... + def help(self, *, file: _File = None) -> tuple[str, _list[str]]: ... + def stat(self, message_spec: Any = None) -> tuple[str, int, str]: ... + def next(self) -> tuple[str, int, str]: ... + def last(self) -> tuple[str, int, str]: ... + def head(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... + def body(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... + def article(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ... + def slave(self) -> str: ... + def xhdr(self, hdr: str, str: Any, *, file: _File = None) -> tuple[str, _list[str]]: ... + def xover(self, start: int, end: int, *, file: _File = None) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... + def over( + self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = None + ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... + def date(self) -> tuple[str, datetime.datetime]: ... + def post(self, data: bytes | Iterable[bytes]) -> str: ... + def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... + def quit(self) -> str: ... + def login(self, user: str | None = None, password: str | None = None, usenetrc: bool = True) -> None: ... + def starttls(self, context: ssl.SSLContext | None = None) -> None: ... + +class NNTP_SSL(NNTP): + ssl_context: ssl.SSLContext | None + sock: ssl.SSLSocket + def __init__( + self, + host: str, + port: int = 563, + user: str | None = None, + password: str | None = None, + ssl_context: ssl.SSLContext | None = None, + readermode: bool | None = None, + usenetrc: bool = False, + timeout: float = ..., + ) -> None: ... diff --git a/stdlib/nt.pyi b/stdlib/nt.pyi new file mode 100644 index 000000000000..0c87444d18f4 --- /dev/null +++ b/stdlib/nt.pyi @@ -0,0 +1,116 @@ +import sys + +if sys.platform == "win32": + # Actually defined here and re-exported from os at runtime, + # but this leads to less code duplication + from os import ( + F_OK as F_OK, + O_APPEND as O_APPEND, + O_BINARY as O_BINARY, + O_CREAT as O_CREAT, + O_EXCL as O_EXCL, + O_NOINHERIT as O_NOINHERIT, + O_RANDOM as O_RANDOM, + O_RDONLY as O_RDONLY, + O_RDWR as O_RDWR, + O_SEQUENTIAL as O_SEQUENTIAL, + O_SHORT_LIVED as O_SHORT_LIVED, + O_TEMPORARY as O_TEMPORARY, + O_TEXT as O_TEXT, + O_TRUNC as O_TRUNC, + O_WRONLY as O_WRONLY, + P_DETACH as P_DETACH, + P_NOWAIT as P_NOWAIT, + P_NOWAITO as P_NOWAITO, + P_OVERLAY as P_OVERLAY, + P_WAIT as P_WAIT, + R_OK as R_OK, + TMP_MAX as TMP_MAX, + W_OK as W_OK, + X_OK as X_OK, + DirEntry as DirEntry, + abort as abort, + access as access, + chdir as chdir, + chmod as chmod, + close as close, + closerange as closerange, + cpu_count as cpu_count, + device_encoding as device_encoding, + dup as dup, + dup2 as dup2, + error as error, + execv as execv, + execve as execve, + fspath as fspath, + fstat as fstat, + fsync as fsync, + ftruncate as ftruncate, + get_handle_inheritable as get_handle_inheritable, + get_inheritable as get_inheritable, + get_terminal_size as get_terminal_size, + getcwd as getcwd, + getcwdb as getcwdb, + getlogin as getlogin, + getpid as getpid, + getppid as getppid, + isatty as isatty, + kill as kill, + link as link, + listdir as listdir, + lseek as lseek, + lstat as lstat, + mkdir as mkdir, + open as open, + pipe as pipe, + putenv as putenv, + read as read, + readlink as readlink, + remove as remove, + rename as rename, + replace as replace, + rmdir as rmdir, + scandir as scandir, + set_handle_inheritable as set_handle_inheritable, + set_inheritable as set_inheritable, + spawnv as spawnv, + spawnve as spawnve, + startfile as startfile, + stat as stat, + stat_result as stat_result, + statvfs_result as statvfs_result, + strerror as strerror, + symlink as symlink, + system as system, + terminal_size as terminal_size, + times as times, + times_result as times_result, + truncate as truncate, + umask as umask, + uname_result as uname_result, + unlink as unlink, + unsetenv as unsetenv, + urandom as urandom, + utime as utime, + waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, + write as write, + ) + + if sys.version_info >= (3, 11): + from os import EX_OK as EX_OK + if sys.version_info >= (3, 12): + from os import ( + get_blocking as get_blocking, + listdrives as listdrives, + listmounts as listmounts, + listvolumes as listvolumes, + set_blocking as set_blocking, + ) + if sys.version_info >= (3, 13): + from os import fchmod as fchmod, lchmod as lchmod + + if sys.version_info >= (3, 14): + from os import readinto as readinto + + environ: dict[str, str] diff --git a/stdlib/ntpath.pyi b/stdlib/ntpath.pyi new file mode 100644 index 000000000000..c912d77158ec --- /dev/null +++ b/stdlib/ntpath.pyi @@ -0,0 +1,134 @@ +import sys +from _typeshed import BytesPath, StrOrBytesPath, StrPath +from genericpath import ( + ALLOW_MISSING as ALLOW_MISSING, + _AllowMissingType, + commonprefix as commonprefix, + exists as exists, + getatime as getatime, + getctime as getctime, + getmtime as getmtime, + getsize as getsize, + isdir as isdir, + isfile as isfile, + samefile as samefile, + sameopenfile as sameopenfile, + samestat as samestat, +) +from os import PathLike + +# Re-export common definitions from posixpath to reduce duplication +from posixpath import ( + abspath as abspath, + basename as basename, + commonpath as commonpath, + curdir as curdir, + defpath as defpath, + devnull as devnull, + dirname as dirname, + expanduser as expanduser, + expandvars as expandvars, + extsep as extsep, + isabs as isabs, + islink as islink, + ismount as ismount, + lexists as lexists, + normcase as normcase, + normpath as normpath, + pardir as pardir, + pathsep as pathsep, + relpath as relpath, + sep as sep, + split as split, + splitdrive as splitdrive, + splitext as splitext, + supports_unicode_filenames as supports_unicode_filenames, +) +from typing import AnyStr, overload +from typing_extensions import LiteralString + +if sys.version_info >= (3, 12): + from posixpath import isjunction as isjunction, splitroot as splitroot +if sys.version_info >= (3, 13): + from genericpath import isdevdrive as isdevdrive +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST + +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "samefile", + "sameopenfile", + "samestat", + "commonpath", + "ALLOW_MISSING", +] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] +if sys.version_info >= (3, 13): + __all__ += ["isdevdrive", "isreserved"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] + +altsep: LiteralString + +# First parameter is not actually pos-only, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in posixpath.join() +@overload +def join(path: LiteralString, /, *paths: LiteralString) -> LiteralString: ... +@overload +def join(path: StrPath, /, *paths: StrPath) -> str: ... +@overload +def join(path: BytesPath, /, *paths: BytesPath) -> bytes: ... + +if sys.version_info >= (3, 15): + @overload + def realpath(path: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(path: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + +else: + if sys.platform == "win32": + @overload + def realpath(path: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(path: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + + else: + realpath = abspath + +if sys.version_info >= (3, 13): + def isreserved(path: StrOrBytesPath) -> bool: ... diff --git a/stdlib/nturl2path.pyi b/stdlib/nturl2path.pyi new file mode 100644 index 000000000000..3871f263f4e3 --- /dev/null +++ b/stdlib/nturl2path.pyi @@ -0,0 +1,6 @@ +from typing_extensions import deprecated + +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") +def url2pathname(url: str) -> str: ... +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") +def pathname2url(p: str) -> str: ... diff --git a/stdlib/numbers.pyi b/stdlib/numbers.pyi new file mode 100644 index 000000000000..434e52c4cac8 --- /dev/null +++ b/stdlib/numbers.pyi @@ -0,0 +1,220 @@ +# Note: these stubs are incomplete. The more complex type +# signatures are currently omitted. +# +# Use _ComplexLike, _RealLike and _IntegralLike for return types in this module +# rather than `numbers.Complex`, `numbers.Real` and `numbers.Integral`, +# to avoid an excessive number of `type: ignore`s in subclasses of these ABCs +# (since type checkers don't see `complex` as a subtype of `numbers.Complex`, +# nor `float` as a subtype of `numbers.Real`, etc.) + +from abc import ABCMeta, abstractmethod +from typing import ClassVar, Literal, Protocol, overload, type_check_only + +__all__ = ["Number", "Complex", "Real", "Rational", "Integral"] + +############################ +# Protocols for return types +############################ + +# `_ComplexLike` is a structural-typing approximation +# of the `Complex` ABC, which is not (and cannot be) a protocol +# +# NOTE: We can't include `__complex__` here, +# as we want `int` to be seen as a subtype of `_ComplexLike`, +# and `int.__complex__` does not exist :( +@type_check_only +class _ComplexLike(Protocol): + def __neg__(self) -> _ComplexLike: ... + def __pos__(self) -> _ComplexLike: ... + def __abs__(self) -> _RealLike: ... + +# _RealLike is a structural-typing approximation +# of the `Real` ABC, which is not (and cannot be) a protocol +@type_check_only +class _RealLike(_ComplexLike, Protocol): + def __trunc__(self) -> _IntegralLike: ... + def __floor__(self) -> _IntegralLike: ... + def __ceil__(self) -> _IntegralLike: ... + def __float__(self) -> float: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __neg__(self) -> _RealLike: ... + def __pos__(self) -> _RealLike: ... + +# _IntegralLike is a structural-typing approximation +# of the `Integral` ABC, which is not (and cannot be) a protocol +@type_check_only +class _IntegralLike(_RealLike, Protocol): + def __invert__(self) -> _IntegralLike: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + # Overridden from `_ComplexLike` + # for a more precise return type: + def __abs__(self) -> _IntegralLike: ... + # Overridden from `RealLike` + # for a more precise return type: + def __neg__(self) -> _IntegralLike: ... + def __pos__(self) -> _IntegralLike: ... + +################# +# Module "proper" +################# + +class Number(metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __hash__(self) -> int: ... + +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Complex(Number, _ComplexLike): + __slots__ = () + @abstractmethod + def __complex__(self) -> complex: ... + def __bool__(self) -> bool: ... + @property + @abstractmethod + def real(self) -> _RealLike: ... + @property + @abstractmethod + def imag(self) -> _RealLike: ... + @abstractmethod + def __add__(self, other) -> _ComplexLike: ... + @abstractmethod + def __radd__(self, other) -> _ComplexLike: ... + @abstractmethod + def __neg__(self) -> _ComplexLike: ... + @abstractmethod + def __pos__(self) -> _ComplexLike: ... + def __sub__(self, other) -> _ComplexLike: ... + def __rsub__(self, other) -> _ComplexLike: ... + @abstractmethod + def __mul__(self, other) -> _ComplexLike: ... + @abstractmethod + def __rmul__(self, other) -> _ComplexLike: ... + @abstractmethod + def __truediv__(self, other) -> _ComplexLike: ... + @abstractmethod + def __rtruediv__(self, other) -> _ComplexLike: ... + @abstractmethod + def __pow__(self, exponent) -> _ComplexLike: ... + @abstractmethod + def __rpow__(self, base) -> _ComplexLike: ... + @abstractmethod + def __abs__(self) -> _RealLike: ... + @abstractmethod + def conjugate(self) -> _ComplexLike: ... + @abstractmethod + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Real(Complex, _RealLike): + __slots__ = () + @abstractmethod + def __float__(self) -> float: ... + @abstractmethod + def __trunc__(self) -> _IntegralLike: ... + @abstractmethod + def __floor__(self) -> _IntegralLike: ... + @abstractmethod + def __ceil__(self) -> _IntegralLike: ... + + @abstractmethod + @overload + def __round__(self, ndigits: None = None) -> _IntegralLike: ... + @abstractmethod + @overload + def __round__(self, ndigits: int) -> _RealLike: ... + + def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ... + def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ... + @abstractmethod + def __floordiv__(self, other) -> _RealLike: ... + @abstractmethod + def __rfloordiv__(self, other) -> _RealLike: ... + @abstractmethod + def __mod__(self, other) -> _RealLike: ... + @abstractmethod + def __rmod__(self, other) -> _RealLike: ... + @abstractmethod + def __lt__(self, other) -> bool: ... + @abstractmethod + def __le__(self, other) -> bool: ... + def __complex__(self) -> complex: ... + @property + def real(self) -> _RealLike: ... + @property + def imag(self) -> Literal[0]: ... + def conjugate(self) -> _RealLike: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _RealLike: ... + @abstractmethod + def __neg__(self) -> _RealLike: ... + +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Rational(Real): + __slots__ = () + @property + @abstractmethod + def numerator(self) -> _IntegralLike: ... + @property + @abstractmethod + def denominator(self) -> _IntegralLike: ... + def __float__(self) -> float: ... + +# See comment at the top of the file +# for why some of these return types are purposefully vague +class Integral(Rational, _IntegralLike): + __slots__ = () + @abstractmethod + def __int__(self) -> int: ... + def __index__(self) -> int: ... + @abstractmethod + def __pow__(self, exponent, modulus=None) -> _IntegralLike: ... + @abstractmethod + def __lshift__(self, other) -> _IntegralLike: ... + @abstractmethod + def __rlshift__(self, other) -> _IntegralLike: ... + @abstractmethod + def __rshift__(self, other) -> _IntegralLike: ... + @abstractmethod + def __rrshift__(self, other) -> _IntegralLike: ... + @abstractmethod + def __and__(self, other) -> _IntegralLike: ... + @abstractmethod + def __rand__(self, other) -> _IntegralLike: ... + @abstractmethod + def __xor__(self, other) -> _IntegralLike: ... + @abstractmethod + def __rxor__(self, other) -> _IntegralLike: ... + @abstractmethod + def __or__(self, other) -> _IntegralLike: ... + @abstractmethod + def __ror__(self, other) -> _IntegralLike: ... + @abstractmethod + def __invert__(self) -> _IntegralLike: ... + def __float__(self) -> float: ... + @property + def numerator(self) -> _IntegralLike: ... + @property + def denominator(self) -> Literal[1]: ... + # Not actually overridden at runtime, + # but we override these in the stub to give them more precise return types: + @abstractmethod + def __pos__(self) -> _IntegralLike: ... + @abstractmethod + def __neg__(self) -> _IntegralLike: ... + @abstractmethod + def __abs__(self) -> _IntegralLike: ... + + @abstractmethod + @overload + def __round__(self, ndigits: None = None) -> _IntegralLike: ... + @abstractmethod + @overload + def __round__(self, ndigits: int) -> _IntegralLike: ... diff --git a/stdlib/opcode.pyi b/stdlib/opcode.pyi new file mode 100644 index 000000000000..3bc41db42bb6 --- /dev/null +++ b/stdlib/opcode.pyi @@ -0,0 +1,53 @@ +import sys +from typing import Final, Literal + +if sys.version_info >= (3, 15): + from builtins import frozendict + +__all__ = [ + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "stack_effect", +] +if sys.version_info >= (3, 12): + __all__ += ["hasarg", "hasexc"] +else: + __all__ += ["hasnargs"] +if sys.version_info >= (3, 13): + __all__ += ["hasjump"] + +cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] +hasconst: Final[list[int]] +hasname: Final[list[int]] +hasjrel: Final[list[int]] +hasjabs: Final[list[int]] +haslocal: Final[list[int]] +hascompare: Final[list[int]] +hasfree: Final[list[int]] +if sys.version_info >= (3, 12): + hasarg: Final[list[int]] + hasexc: Final[list[int]] +else: + hasnargs: Final[list[int]] +if sys.version_info >= (3, 13): + hasjump: Final[list[int]] +opname: Final[list[str]] + +if sys.version_info >= (3, 15): + opmap: Final[frozendict[str, int]] +else: + opmap: Final[dict[str, int]] +HAVE_ARGUMENT: Final[int] +EXTENDED_ARG: Final[int] + +def stack_effect(opcode: int, oparg: int | None = None, /, *, jump: bool | None = None) -> int: ... diff --git a/stdlib/operator.pyi b/stdlib/operator.pyi new file mode 100644 index 000000000000..5998d6d16e98 --- /dev/null +++ b/stdlib/operator.pyi @@ -0,0 +1,219 @@ +import sys +from _operator import ( + abs as abs, + add as add, + and_ as and_, + concat as concat, + contains as contains, + countOf as countOf, + delitem as delitem, + eq as eq, + floordiv as floordiv, + ge as ge, + getitem as getitem, + gt as gt, + iadd as iadd, + iand as iand, + iconcat as iconcat, + ifloordiv as ifloordiv, + ilshift as ilshift, + imatmul as imatmul, + imod as imod, + imul as imul, + index as index, + indexOf as indexOf, + inv as inv, + invert as invert, + ior as ior, + ipow as ipow, + irshift as irshift, + is_ as is_, + is_not as is_not, + isub as isub, + itruediv as itruediv, + ixor as ixor, + le as le, + length_hint as length_hint, + lshift as lshift, + lt as lt, + matmul as matmul, + mod as mod, + mul as mul, + ne as ne, + neg as neg, + not_ as not_, + or_ as or_, + pos as pos, + pow as pow, + rshift as rshift, + setitem as setitem, + sub as sub, + truediv as truediv, + truth as truth, + xor as xor, +) +from _typeshed import SupportsGetItem +from typing import Any, Generic, TypeVar, final, overload +from typing_extensions import Self, TypeVarTuple, Unpack + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_Ts = TypeVarTuple("_Ts") + +__all__ = [ + "abs", + "add", + "and_", + "attrgetter", + "concat", + "contains", + "countOf", + "delitem", + "eq", + "floordiv", + "ge", + "getitem", + "gt", + "iadd", + "iand", + "iconcat", + "ifloordiv", + "ilshift", + "imatmul", + "imod", + "imul", + "index", + "indexOf", + "inv", + "invert", + "ior", + "ipow", + "irshift", + "is_", + "is_not", + "isub", + "itemgetter", + "itruediv", + "ixor", + "le", + "length_hint", + "lshift", + "lt", + "matmul", + "methodcaller", + "mod", + "mul", + "ne", + "neg", + "not_", + "or_", + "pos", + "pow", + "rshift", + "setitem", + "sub", + "truediv", + "truth", + "xor", +] + +if sys.version_info >= (3, 11): + from _operator import call as call + + __all__ += ["call"] + +if sys.version_info >= (3, 14): + from _operator import is_none as is_none, is_not_none as is_not_none + + __all__ += ["is_none", "is_not_none"] + +__lt__ = lt +__le__ = le +__eq__ = eq +__ne__ = ne +__ge__ = ge +__gt__ = gt +__not__ = not_ +__abs__ = abs +__add__ = add +__and__ = and_ +__floordiv__ = floordiv +__index__ = index +__inv__ = inv +__invert__ = invert +__lshift__ = lshift +__mod__ = mod +__mul__ = mul +__matmul__ = matmul +__neg__ = neg +__or__ = or_ +__pos__ = pos +__pow__ = pow +__rshift__ = rshift +__sub__ = sub +__truediv__ = truediv +__xor__ = xor +__concat__ = concat +__contains__ = contains +__delitem__ = delitem +__getitem__ = getitem +__setitem__ = setitem +__iadd__ = iadd +__iand__ = iand +__iconcat__ = iconcat +__ifloordiv__ = ifloordiv +__ilshift__ = ilshift +__imod__ = imod +__imul__ = imul +__imatmul__ = imatmul +__ior__ = ior +__ipow__ = ipow +__irshift__ = irshift +__isub__ = isub +__itruediv__ = itruediv +__ixor__ = ixor +if sys.version_info >= (3, 11): + __call__ = call + +# At runtime, these classes are implemented in C as part of the _operator module +# However, they consider themselves to live in the operator module, so we'll put +# them here. +@final +class attrgetter(Generic[_T_co]): + @overload + def __new__(cls, attr: str, /) -> attrgetter[Any]: ... + @overload + def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[Any, Any]]: ... + @overload + def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... + + def __call__(self, obj: Any, /) -> _T_co: ... + +@final +class itemgetter(Generic[_T_co]): + @overload + def __new__(cls, item: _T, /) -> itemgetter[_T]: ... + @overload + def __new__(cls, item1: _T1, item2: _T2, /, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ... + + # __key: _KT_contra in SupportsGetItem seems to be causing variance issues, ie: + # TypeVar "_KT_contra@SupportsGetItem" is contravariant + # "tuple[int, int]" is incompatible with protocol "SupportsIndex" + # preventing [_T_co, ...] instead of [Any, ...] + # + # If we can't infer a literal key from __new__ (ie: `itemgetter[Literal[0]]` for `itemgetter(0)`), + # then we can't annotate __call__'s return type or it'll break on tuples + # + # These issues are best demonstrated by the `itertools.check_itertools_recipes.unique_justseen` test. + def __call__(self, obj: SupportsGetItem[Any, Any]) -> Any: ... + +@final +class methodcaller: + def __new__(cls, name: str, /, *args: Any, **kwargs: Any) -> Self: ... + def __call__(self, obj: Any) -> Any: ... diff --git a/stdlib/optparse.pyi b/stdlib/optparse.pyi new file mode 100644 index 000000000000..35dfc54a9d49 --- /dev/null +++ b/stdlib/optparse.pyi @@ -0,0 +1,312 @@ +import builtins +from _typeshed import MaybeNone, SupportsWrite +from abc import abstractmethod +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ClassVar, Final, Literal, overload +from typing_extensions import Never, Self + +__all__ = [ + "Option", + "make_option", + "SUPPRESS_HELP", + "SUPPRESS_USAGE", + "Values", + "OptionContainer", + "OptionGroup", + "OptionParser", + "HelpFormatter", + "IndentedHelpFormatter", + "TitledHelpFormatter", + "OptParseError", + "OptionError", + "OptionConflictError", + "OptionValueError", + "BadOptionError", + "check_choice", +] +NO_DEFAULT: Final = ("NO", "DEFAULT") +SUPPRESS_HELP: Final = "SUPPRESSHELP" +SUPPRESS_USAGE: Final = "SUPPRESSUSAGE" + +# Can return complex, float, or int depending on the option's type +def check_builtin(option: Option, opt: str, value: str) -> complex: ... +def check_choice(option: Option, opt: str, value: str) -> str: ... + +class OptParseError(Exception): + msg: str + def __init__(self, msg: str) -> None: ... + +class BadOptionError(OptParseError): + opt_str: str + def __init__(self, opt_str: str) -> None: ... + +class AmbiguousOptionError(BadOptionError): + possibilities: Iterable[str] + def __init__(self, opt_str: str, possibilities: Sequence[str]) -> None: ... + +class OptionError(OptParseError): + option_id: str + def __init__(self, msg: str, option: Option) -> None: ... + +class OptionConflictError(OptionError): ... +class OptionValueError(OptParseError): ... + +class HelpFormatter: + NO_DEFAULT_VALUE: str + _long_opt_fmt: str + _short_opt_fmt: str + current_indent: int + default_tag: str + help_position: int + help_width: int | MaybeNone # initialized as None and computed later as int when storing option strings + indent_increment: int + level: int + max_help_position: int + option_strings: dict[Option, str] + parser: OptionParser + short_first: bool | Literal[0, 1] + width: int + def __init__( + self, indent_increment: int, max_help_position: int, width: int | None, short_first: bool | Literal[0, 1] + ) -> None: ... + def dedent(self) -> None: ... + def expand_default(self, option: Option) -> str: ... + def format_description(self, description: str | None) -> str: ... + def format_epilog(self, epilog: str | None) -> str: ... + @abstractmethod + def format_heading(self, heading: str) -> str: ... + def format_option(self, option: Option) -> str: ... + def format_option_strings(self, option: Option) -> str: ... + @abstractmethod + def format_usage(self, usage: str) -> str: ... + def indent(self) -> None: ... + def set_long_opt_delimiter(self, delim: str) -> None: ... + def set_parser(self, parser: OptionParser) -> None: ... + def set_short_opt_delimiter(self, delim: str) -> None: ... + def store_option_strings(self, parser: OptionParser) -> None: ... + +class IndentedHelpFormatter(HelpFormatter): + def __init__( + self, + indent_increment: int = 2, + max_help_position: int = 24, + width: int | None = None, + short_first: bool | Literal[0, 1] = 1, + ) -> None: ... + def format_heading(self, heading: str) -> str: ... + def format_usage(self, usage: str) -> str: ... + +class TitledHelpFormatter(HelpFormatter): + def __init__( + self, + indent_increment: int = 0, + max_help_position: int = 24, + width: int | None = None, + short_first: bool | Literal[0, 1] = 0, + ) -> None: ... + def format_heading(self, heading: str) -> str: ... + def format_usage(self, usage: str) -> str: ... + +class Option: + ACTIONS: tuple[str, ...] + ALWAYS_TYPED_ACTIONS: tuple[str, ...] + ATTRS: list[str] + CHECK_METHODS: list[Callable[[Self], object]] | None + CONST_ACTIONS: tuple[str, ...] + STORE_ACTIONS: tuple[str, ...] + TYPED_ACTIONS: tuple[str, ...] + TYPES: tuple[str, ...] + TYPE_CHECKER: dict[str, Callable[[Option, str, str], object]] + _long_opts: list[str] + _short_opts: list[str] + action: str + type: str | None + dest: str | None + default: Any # default can be "any" type + nargs: int + const: Any | None # const can be "any" type + choices: list[str] | tuple[str, ...] | None + # Callback args and kwargs cannot be expressed in Python's type system. + # Revisit if ParamSpec is ever changed to work with packed args/kwargs. + callback: Callable[..., object] | None + callback_args: tuple[Any, ...] | None + callback_kwargs: dict[str, Any] | None + help: str | None + metavar: str | None + def __init__( + self, + *opts: str | None, + # The following keywords are handled by the _set_attrs method. All default to + # `None` except for `default`, which defaults to `NO_DEFAULT`. + action: str | None = None, + type: str | builtins.type | None = None, + dest: str | None = None, + default: Any = ..., # = NO_DEFAULT + nargs: int | None = None, + const: Any | None = None, + choices: list[str] | tuple[str, ...] | None = None, + callback: Callable[..., object] | None = None, + callback_args: tuple[Any, ...] | None = None, + callback_kwargs: dict[str, Any] | None = None, + help: str | None = None, + metavar: str | None = None, + ) -> None: ... + def _check_action(self) -> None: ... + def _check_callback(self) -> None: ... + def _check_choice(self) -> None: ... + def _check_const(self) -> None: ... + def _check_dest(self) -> None: ... + def _check_nargs(self) -> None: ... + def _check_opt_strings(self, opts: Iterable[str | None]) -> list[str]: ... + def _check_type(self) -> None: ... + def _set_attrs(self, attrs: dict[str, Any]) -> None: ... # accepted attrs depend on the ATTRS attribute + def _set_opt_strings(self, opts: Iterable[str]) -> None: ... + def check_value(self, opt: str, value: str) -> Any: ... # return type cannot be known statically + def convert_value(self, opt: str, value: str | tuple[str, ...] | None) -> Any: ... # return type cannot be known statically + def get_opt_string(self) -> str: ... + def process(self, opt: str, value: str | tuple[str, ...] | None, values: Values, parser: OptionParser) -> int: ... + # value of take_action can be "any" type + def take_action(self, action: str, dest: str, opt: str, value: Any, values: Values, parser: OptionParser) -> int: ... + def takes_value(self) -> bool: ... + +make_option = Option + +class OptionContainer: + _long_opt: dict[str, Option] + _short_opt: dict[str, Option] + conflict_handler: str + defaults: dict[str, Any] # default values can be "any" type + description: str | None + option_class: type[Option] + def __init__( + self, option_class: type[Option], conflict_handler: Literal["error", "resolve"], description: str | None + ) -> None: ... + def _check_conflict(self, option: Option) -> None: ... + def _create_option_mappings(self) -> None: ... + def _share_option_mappings(self, parser: OptionParser) -> None: ... + + @overload + def add_option(self, opt: Option, /) -> Option: ... + @overload + def add_option( + self, + opt_str: str, + /, + *opts: str | None, + action: str | None = None, + type: str | builtins.type | None = None, + dest: str | None = None, + default: Any = ..., # = NO_DEFAULT + nargs: int | None = None, + const: Any | None = None, + choices: list[str] | tuple[str, ...] | None = None, + callback: Callable[..., object] | None = None, + callback_args: tuple[Any, ...] | None = None, + callback_kwargs: dict[str, Any] | None = None, + help: str | None = None, + metavar: str | None = None, + **kwargs: Any, # Allow arbitrary keyword arguments for user defined option_class + ) -> Option: ... + + def add_options(self, option_list: Iterable[Option]) -> None: ... + def destroy(self) -> None: ... + def format_option_help(self, formatter: HelpFormatter) -> str: ... + def format_description(self, formatter: HelpFormatter) -> str: ... + def format_help(self, formatter: HelpFormatter) -> str: ... + def get_description(self) -> str | None: ... + def get_option(self, opt_str: str) -> Option | None: ... + def has_option(self, opt_str: str) -> bool: ... + def remove_option(self, opt_str: str) -> None: ... + def set_conflict_handler(self, handler: Literal["error", "resolve"]) -> None: ... + def set_description(self, description: str | None) -> None: ... + +class OptionGroup(OptionContainer): + option_list: list[Option] + parser: OptionParser + title: str + def __init__(self, parser: OptionParser, title: str, description: str | None = None) -> None: ... + def _create_option_list(self) -> None: ... + def set_title(self, title: str) -> None: ... + +class Values: + def __init__(self, defaults: Mapping[str, object] | None = None) -> None: ... + def _update(self, dict: Mapping[str, object], mode: Literal["careful", "loose"]) -> None: ... + def _update_careful(self, dict: Mapping[str, object]) -> None: ... + def _update_loose(self, dict: Mapping[str, object]) -> None: ... + def ensure_value(self, attr: str, value: object) -> Any: ... # return type cannot be known statically + def read_file(self, filename: str, mode: Literal["careful", "loose"] = "careful") -> None: ... + def read_module(self, modname: str, mode: Literal["careful", "loose"] = "careful") -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + # __getattr__ doesn't exist, but anything passed as a default to __init__ + # is set on the instance. + def __getattr__(self, name: str) -> Any: ... + # TODO: mypy infers -> object for __getattr__ if __setattr__ has `value: object` + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class OptionParser(OptionContainer): + allow_interspersed_args: bool + epilog: str | None + formatter: HelpFormatter + largs: list[str] | None + option_groups: list[OptionGroup] + option_list: list[Option] + process_default_values: bool + prog: str | None + rargs: list[str] | None + standard_option_list: list[Option] + usage: str | None + values: Values | None + version: str + def __init__( + self, + usage: str | None = None, + option_list: Iterable[Option] | None = None, + option_class: type[Option] = ..., + version: str | None = None, + conflict_handler: str = "error", + description: str | None = None, + formatter: HelpFormatter | None = None, + add_help_option: bool = True, + prog: str | None = None, + epilog: str | None = None, + ) -> None: ... + def _add_help_option(self) -> None: ... + def _add_version_option(self) -> None: ... + def _create_option_list(self) -> None: ... + def _get_all_options(self) -> list[Option]: ... + def _get_args(self, args: list[str] | None) -> list[str]: ... + def _init_parsing_state(self) -> None: ... + def _match_long_opt(self, opt: str) -> str: ... + def _populate_option_list(self, option_list: Iterable[Option] | None, add_help: bool = True) -> None: ... + def _process_args(self, largs: list[str], rargs: list[str], values: Values) -> None: ... + def _process_long_opt(self, rargs: list[str], values: Values) -> None: ... + def _process_short_opts(self, rargs: list[str], values: Values) -> None: ... + + @overload + def add_option_group(self, opt_group: OptionGroup, /) -> OptionGroup: ... + @overload + def add_option_group(self, title: str, /, description: str | None = None) -> OptionGroup: ... + + def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ... + def disable_interspersed_args(self) -> None: ... + def enable_interspersed_args(self) -> None: ... + def error(self, msg: str) -> Never: ... + def exit(self, status: int = 0, msg: str | None = None) -> Never: ... + def expand_prog_name(self, s: str) -> str: ... + def format_epilog(self, formatter: HelpFormatter) -> str: ... + def format_help(self, formatter: HelpFormatter | None = None) -> str: ... + def format_option_help(self, formatter: HelpFormatter | None = None) -> str: ... + def get_default_values(self) -> Values: ... + def get_option_group(self, opt_str: str) -> OptionGroup | None: ... + def get_prog_name(self) -> str: ... + def get_usage(self) -> str: ... + def get_version(self) -> str: ... + def parse_args(self, args: list[str] | None = None, values: Values | None = None) -> tuple[Values, list[str]]: ... + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_help(self, file: SupportsWrite[str] | None = None) -> None: ... + def print_version(self, file: SupportsWrite[str] | None = None) -> None: ... + def set_default(self, dest: str, value: Any) -> None: ... # default value can be "any" type + def set_defaults(self, **kwargs: Any) -> None: ... # default values can be "any" type + def set_process_default_values(self, process: bool) -> None: ... + def set_usage(self, usage: str | None) -> None: ... diff --git a/stdlib/os/__init__.pyi b/stdlib/os/__init__.pyi new file mode 100644 index 000000000000..63af29cccff8 --- /dev/null +++ b/stdlib/os/__init__.pyi @@ -0,0 +1,1879 @@ +import sys +from _typeshed import ( + AnyStr_co, + BytesPath, + FileDescriptor, + FileDescriptorLike, + FileDescriptorOrPath, + GenericPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + StrOrBytesPath, + StrPath, + SupportsLenAndGetItem, + Unused, + WriteableBuffer, + structseq, +) +from abc import ABC, abstractmethod +from builtins import OSError +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from subprocess import Popen +from types import GenericAlias, TracebackType +from typing import ( + IO, + Any, + AnyStr, + BinaryIO, + Final, + Generic, + Literal, + Protocol, + TypeAlias, + TypeVar, + final, + overload, + runtime_checkable, + type_check_only, +) +from typing_extensions import LiteralString, Never, Self, Unpack, deprecated + +from . import path as _path + +# Re-export common definitions from os.path to reduce duplication +from .path import ( + altsep as altsep, + curdir as curdir, + defpath as defpath, + devnull as devnull, + extsep as extsep, + pardir as pardir, + pathsep as pathsep, + sep as sep, +) + +__all__ = [ + "F_OK", + "O_APPEND", + "O_CREAT", + "O_EXCL", + "O_RDONLY", + "O_RDWR", + "O_TRUNC", + "O_WRONLY", + "P_NOWAIT", + "P_NOWAITO", + "P_WAIT", + "R_OK", + "SEEK_CUR", + "SEEK_END", + "SEEK_SET", + "TMP_MAX", + "W_OK", + "X_OK", + "DirEntry", + "_exit", + "abort", + "access", + "altsep", + "chdir", + "chmod", + "close", + "closerange", + "cpu_count", + "curdir", + "defpath", + "device_encoding", + "devnull", + "dup", + "dup2", + "environ", + "error", + "execl", + "execle", + "execlp", + "execlpe", + "execv", + "execve", + "execvp", + "execvpe", + "extsep", + "fdopen", + "fsdecode", + "fsencode", + "fspath", + "fstat", + "fsync", + "ftruncate", + "get_exec_path", + "get_inheritable", + "get_terminal_size", + "getcwd", + "getcwdb", + "getenv", + "getlogin", + "getpid", + "getppid", + "isatty", + "kill", + "linesep", + "link", + "listdir", + "lseek", + "lstat", + "makedirs", + "mkdir", + "name", + "open", + "pardir", + "path", + "pathsep", + "pipe", + "popen", + "putenv", + "read", + "readlink", + "remove", + "removedirs", + "rename", + "renames", + "replace", + "rmdir", + "scandir", + "sep", + "set_inheritable", + "spawnl", + "spawnle", + "spawnv", + "spawnve", + "stat", + "stat_result", + "statvfs_result", + "strerror", + "supports_bytes_environ", + "symlink", + "system", + "terminal_size", + "times", + "times_result", + "truncate", + "umask", + "uname_result", + "unlink", + "unsetenv", + "urandom", + "utime", + "waitpid", + "waitstatus_to_exitcode", + "walk", + "write", +] +if sys.version_info >= (3, 14): + # reload_environ was added to __all__ in Python 3.14.1 + __all__ += ["readinto", "reload_environ"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += ["_clearenv"] +if sys.platform == "darwin" and sys.version_info >= (3, 12): + __all__ += ["PRIO_DARWIN_BG", "PRIO_DARWIN_NONUI", "PRIO_DARWIN_PROCESS", "PRIO_DARWIN_THREAD"] +if sys.platform == "darwin": + __all__ += ["O_EVTONLY", "O_NOFOLLOW_ANY", "O_SYMLINK"] +if sys.platform == "linux": + __all__ += [ + "GRND_NONBLOCK", + "GRND_RANDOM", + "MFD_ALLOW_SEALING", + "MFD_CLOEXEC", + "MFD_HUGETLB", + "MFD_HUGE_16GB", + "MFD_HUGE_16MB", + "MFD_HUGE_1GB", + "MFD_HUGE_1MB", + "MFD_HUGE_256MB", + "MFD_HUGE_2GB", + "MFD_HUGE_2MB", + "MFD_HUGE_32MB", + "MFD_HUGE_512KB", + "MFD_HUGE_512MB", + "MFD_HUGE_64KB", + "MFD_HUGE_8MB", + "MFD_HUGE_MASK", + "MFD_HUGE_SHIFT", + "O_DIRECT", + "O_LARGEFILE", + "O_NOATIME", + "O_PATH", + "O_RSYNC", + "O_TMPFILE", + "P_PIDFD", + "RTLD_DEEPBIND", + "SCHED_BATCH", + "SCHED_IDLE", + "SCHED_RESET_ON_FORK", + "XATTR_CREATE", + "XATTR_REPLACE", + "XATTR_SIZE_MAX", + "copy_file_range", + "getrandom", + "getxattr", + "listxattr", + "memfd_create", + "pidfd_open", + "removexattr", + "setxattr", + ] +if sys.platform == "linux" and sys.version_info >= (3, 14): + __all__ += ["SCHED_DEADLINE", "SCHED_NORMAL"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += [ + "AT_NO_AUTOMOUNT", + "AT_STATX_DONT_SYNC", + "AT_STATX_FORCE_SYNC", + "AT_STATX_SYNC_AS_STAT", + "STATX_ATIME", + "STATX_BASIC_STATS", + "STATX_BLOCKS", + "STATX_BTIME", + "STATX_CTIME", + "STATX_DIOALIGN", + "STATX_GID", + "STATX_INO", + "STATX_MNT_ID", + "STATX_MNT_ID_UNIQUE", + "STATX_MODE", + "STATX_MTIME", + "STATX_NLINK", + "STATX_SIZE", + "STATX_TYPE", + "STATX_UID", + "statx", + "statx_result", + ] +if sys.platform == "linux" and sys.version_info >= (3, 13): + __all__ += [ + "POSIX_SPAWN_CLOSEFROM", + "TFD_CLOEXEC", + "TFD_NONBLOCK", + "TFD_TIMER_ABSTIME", + "TFD_TIMER_CANCEL_ON_SET", + "timerfd_create", + "timerfd_gettime", + "timerfd_gettime_ns", + "timerfd_settime", + "timerfd_settime_ns", + ] +if sys.platform == "linux" and sys.version_info >= (3, 12): + __all__ += [ + "CLONE_FILES", + "CLONE_FS", + "CLONE_NEWCGROUP", + "CLONE_NEWIPC", + "CLONE_NEWNET", + "CLONE_NEWNS", + "CLONE_NEWPID", + "CLONE_NEWTIME", + "CLONE_NEWUSER", + "CLONE_NEWUTS", + "CLONE_SIGHAND", + "CLONE_SYSVSEM", + "CLONE_THREAD", + "CLONE_VM", + "setns", + "unshare", + "PIDFD_NONBLOCK", + ] +if sys.platform == "linux": + __all__ += [ + "EFD_CLOEXEC", + "EFD_NONBLOCK", + "EFD_SEMAPHORE", + "RWF_APPEND", + "SPLICE_F_MORE", + "SPLICE_F_MOVE", + "SPLICE_F_NONBLOCK", + "eventfd", + "eventfd_read", + "eventfd_write", + "splice", + ] +if sys.platform == "win32": + __all__ += [ + "O_BINARY", + "O_NOINHERIT", + "O_RANDOM", + "O_SEQUENTIAL", + "O_SHORT_LIVED", + "O_TEMPORARY", + "O_TEXT", + "P_DETACH", + "P_OVERLAY", + "get_handle_inheritable", + "set_handle_inheritable", + "startfile", + ] +if sys.platform == "win32" and sys.version_info >= (3, 12): + __all__ += ["listdrives", "listmounts", "listvolumes"] +if sys.platform != "win32": + __all__ += [ + "CLD_CONTINUED", + "CLD_DUMPED", + "CLD_EXITED", + "CLD_KILLED", + "CLD_STOPPED", + "CLD_TRAPPED", + "EX_CANTCREAT", + "EX_CONFIG", + "EX_DATAERR", + "EX_IOERR", + "EX_NOHOST", + "EX_NOINPUT", + "EX_NOPERM", + "EX_NOUSER", + "EX_OSERR", + "EX_OSFILE", + "EX_PROTOCOL", + "EX_SOFTWARE", + "EX_TEMPFAIL", + "EX_UNAVAILABLE", + "EX_USAGE", + "F_LOCK", + "F_TEST", + "F_TLOCK", + "F_ULOCK", + "NGROUPS_MAX", + "O_ACCMODE", + "O_ASYNC", + "O_CLOEXEC", + "O_DIRECTORY", + "O_DSYNC", + "O_NDELAY", + "O_NOCTTY", + "O_NOFOLLOW", + "O_NONBLOCK", + "O_SYNC", + "POSIX_SPAWN_CLOSE", + "POSIX_SPAWN_DUP2", + "POSIX_SPAWN_OPEN", + "PRIO_PGRP", + "PRIO_PROCESS", + "PRIO_USER", + "P_ALL", + "P_PGID", + "P_PID", + "RTLD_GLOBAL", + "RTLD_LAZY", + "RTLD_LOCAL", + "RTLD_NODELETE", + "RTLD_NOLOAD", + "RTLD_NOW", + "SCHED_FIFO", + "SCHED_OTHER", + "SCHED_RR", + "SEEK_DATA", + "SEEK_HOLE", + "ST_NOSUID", + "ST_RDONLY", + "WCONTINUED", + "WCOREDUMP", + "WEXITED", + "WEXITSTATUS", + "WIFCONTINUED", + "WIFEXITED", + "WIFSIGNALED", + "WIFSTOPPED", + "WNOHANG", + "WNOWAIT", + "WSTOPPED", + "WSTOPSIG", + "WTERMSIG", + "WUNTRACED", + "chown", + "chroot", + "confstr", + "confstr_names", + "ctermid", + "environb", + "fchdir", + "fchown", + "fork", + "forkpty", + "fpathconf", + "fstatvfs", + "fwalk", + "getegid", + "getenvb", + "geteuid", + "getgid", + "getgrouplist", + "getgroups", + "getloadavg", + "getpgid", + "getpgrp", + "getpriority", + "getsid", + "getuid", + "initgroups", + "killpg", + "lchown", + "lockf", + "major", + "makedev", + "minor", + "mkfifo", + "mknod", + "nice", + "openpty", + "pathconf", + "pathconf_names", + "posix_spawn", + "posix_spawnp", + "pread", + "preadv", + "pwrite", + "pwritev", + "readv", + "register_at_fork", + "sched_get_priority_max", + "sched_get_priority_min", + "sched_yield", + "sendfile", + "setegid", + "seteuid", + "setgid", + "setgroups", + "setpgid", + "setpgrp", + "setpriority", + "setregid", + "setreuid", + "setsid", + "setuid", + "spawnlp", + "spawnlpe", + "spawnvp", + "spawnvpe", + "statvfs", + "sync", + "sysconf", + "sysconf_names", + "tcgetpgrp", + "tcsetpgrp", + "ttyname", + "uname", + "wait", + "wait3", + "wait4", + "writev", + ] +if sys.platform != "win32" and sys.version_info >= (3, 13): + __all__ += ["grantpt", "posix_openpt", "ptsname", "unlockpt"] +if sys.platform != "win32" and sys.version_info >= (3, 11): + __all__ += ["login_tty"] +if sys.platform != "win32" and sys.version_info >= (3, 15): + __all__ += ["NODEV", "O_FSYNC"] +elif sys.platform != "win32": + __all__ += ["O_FSYNC"] +if sys.platform != "darwin" and sys.platform != "win32": + __all__ += [ + "POSIX_FADV_DONTNEED", + "POSIX_FADV_NOREUSE", + "POSIX_FADV_NORMAL", + "POSIX_FADV_RANDOM", + "POSIX_FADV_SEQUENTIAL", + "POSIX_FADV_WILLNEED", + "RWF_DSYNC", + "RWF_HIPRI", + "RWF_NOWAIT", + "RWF_SYNC", + "ST_APPEND", + "ST_MANDLOCK", + "ST_NOATIME", + "ST_NODEV", + "ST_NODIRATIME", + "ST_NOEXEC", + "ST_RELATIME", + "ST_SYNCHRONOUS", + "ST_WRITE", + "fdatasync", + "getresgid", + "getresuid", + "pipe2", + "posix_fadvise", + "posix_fallocate", + "sched_getaffinity", + "sched_getparam", + "sched_getscheduler", + "sched_param", + "sched_rr_get_interval", + "sched_setaffinity", + "sched_setparam", + "sched_setscheduler", + "setresgid", + "setresuid", + ] +if sys.platform != "linux" and sys.platform != "win32": + __all__ += ["O_EXLOCK", "O_SHLOCK", "chflags", "lchflags"] +if sys.platform != "linux" and sys.platform != "win32" and sys.version_info >= (3, 13): + __all__ += ["O_EXEC", "O_SEARCH"] +if sys.platform != "darwin" or sys.version_info >= (3, 13): + if sys.platform != "win32": + __all__ += ["waitid", "waitid_result"] +if sys.platform != "win32" or sys.version_info >= (3, 13): + __all__ += ["fchmod"] + if sys.platform != "linux": + __all__ += ["lchmod"] +if sys.platform != "win32" or sys.version_info >= (3, 12): + __all__ += ["get_blocking", "set_blocking"] +if sys.platform != "win32" or sys.version_info >= (3, 11): + __all__ += ["EX_OK"] + +# This unnecessary alias is to work around various errors +path = _path + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") + +# ----- os variables ----- + +error = OSError + +supports_bytes_environ: bool + +supports_dir_fd: set[Callable[..., Any]] +supports_fd: set[Callable[..., Any]] +supports_effective_ids: set[Callable[..., Any]] +supports_follow_symlinks: set[Callable[..., Any]] + +if sys.platform != "win32": + # Unix only + PRIO_PROCESS: Final[int] + PRIO_PGRP: Final[int] + PRIO_USER: Final[int] + + F_LOCK: Final[int] + F_TLOCK: Final[int] + F_ULOCK: Final[int] + F_TEST: Final[int] + + if sys.platform != "darwin": + POSIX_FADV_NORMAL: Final[int] + POSIX_FADV_SEQUENTIAL: Final[int] + POSIX_FADV_RANDOM: Final[int] + POSIX_FADV_NOREUSE: Final[int] + POSIX_FADV_WILLNEED: Final[int] + POSIX_FADV_DONTNEED: Final[int] + + if sys.platform != "linux" and sys.platform != "darwin": + # In the os-module docs, these are marked as being available + # on "Unix, not Emscripten, not WASI." + # However, in the source code, a comment indicates they're "FreeBSD constants". + # sys.platform could have one of many values on a FreeBSD Python build, + # so the sys-module docs recommend doing `if sys.platform.startswith('freebsd')` + # to detect FreeBSD builds. Unfortunately that would be too dynamic + # for type checkers, however. + SF_NODISKIO: Final[int] + SF_MNOWAIT: Final[int] + SF_SYNC: Final[int] + + if sys.version_info >= (3, 11): + SF_NOCACHE: Final[int] + + if sys.platform == "linux": + XATTR_SIZE_MAX: Final[int] + XATTR_CREATE: Final[int] + XATTR_REPLACE: Final[int] + + P_PID: Final[int] + P_PGID: Final[int] + P_ALL: Final[int] + + if sys.platform == "linux": + P_PIDFD: Final[int] + + WEXITED: Final[int] + WSTOPPED: Final[int] + WNOWAIT: Final[int] + + CLD_EXITED: Final[int] + CLD_DUMPED: Final[int] + CLD_TRAPPED: Final[int] + CLD_CONTINUED: Final[int] + CLD_KILLED: Final[int] + CLD_STOPPED: Final[int] + + SCHED_OTHER: Final[int] + SCHED_FIFO: Final[int] + SCHED_RR: Final[int] + if sys.platform != "darwin" and sys.platform != "linux": + SCHED_SPORADIC: Final[int] + +if sys.platform == "linux": + SCHED_BATCH: Final[int] + SCHED_IDLE: Final[int] + SCHED_RESET_ON_FORK: Final[int] + +if sys.version_info >= (3, 14) and sys.platform == "linux": + SCHED_DEADLINE: Final[int] + SCHED_NORMAL: Final[int] + +if sys.platform != "win32": + RTLD_LAZY: Final[int] + RTLD_NOW: Final[int] + RTLD_GLOBAL: Final[int] + RTLD_LOCAL: Final[int] + RTLD_NODELETE: Final[int] + RTLD_NOLOAD: Final[int] + +if sys.platform == "linux": + RTLD_DEEPBIND: Final[int] + GRND_NONBLOCK: Final[int] + GRND_RANDOM: Final[int] + +if sys.platform == "darwin" and sys.version_info >= (3, 12): + PRIO_DARWIN_BG: Final[int] + PRIO_DARWIN_NONUI: Final[int] + PRIO_DARWIN_PROCESS: Final[int] + PRIO_DARWIN_THREAD: Final[int] + +SEEK_SET: Final = 0 +SEEK_CUR: Final = 1 +SEEK_END: Final = 2 +if sys.platform == "linux": + SEEK_DATA: Final = 3 + SEEK_HOLE: Final = 4 +elif sys.platform == "darwin": + SEEK_HOLE: Final = 3 + SEEK_DATA: Final = 4 + +O_RDONLY: Final[int] +O_WRONLY: Final[int] +O_RDWR: Final[int] +O_APPEND: Final[int] +O_CREAT: Final[int] +O_EXCL: Final[int] +O_TRUNC: Final[int] +if sys.platform == "win32": + O_BINARY: Final[int] + O_NOINHERIT: Final[int] + O_SHORT_LIVED: Final[int] + O_TEMPORARY: Final[int] + O_RANDOM: Final[int] + O_SEQUENTIAL: Final[int] + O_TEXT: Final[int] + +if sys.platform != "win32": + O_DSYNC: Final[int] + O_SYNC: Final[int] + O_NDELAY: Final[int] + O_NONBLOCK: Final[int] + O_NOCTTY: Final[int] + O_CLOEXEC: Final[int] + O_ASYNC: Final[int] # Gnu extension if in C library + O_DIRECTORY: Final[int] # Gnu extension if in C library + O_NOFOLLOW: Final[int] # Gnu extension if in C library + O_ACCMODE: Final[int] # TODO: when does this exist? + +if sys.platform == "linux": + O_RSYNC: Final[int] + O_DIRECT: Final[int] # Gnu extension if in C library + O_NOATIME: Final[int] # Gnu extension if in C library + O_PATH: Final[int] # Gnu extension if in C library + O_TMPFILE: Final[int] # Gnu extension if in C library + O_LARGEFILE: Final[int] # Gnu extension if in C library + +if sys.platform != "linux" and sys.platform != "win32": + O_SHLOCK: Final[int] + O_EXLOCK: Final[int] + +if sys.platform == "darwin": + O_EVTONLY: Final[int] + O_NOFOLLOW_ANY: Final[int] + O_SYMLINK: Final[int] + +if sys.platform != "win32" and sys.version_info >= (3, 15): + NODEV: Final[int] + +if sys.platform == "linux" and sys.version_info >= (3, 15): + AT_NO_AUTOMOUNT: Final[int] + AT_STATX_DONT_SYNC: Final[int] + AT_STATX_FORCE_SYNC: Final[int] + AT_STATX_SYNC_AS_STAT: Final[int] + STATX_ATIME: Final[int] + STATX_BASIC_STATS: Final[int] + STATX_BLOCKS: Final[int] + STATX_BTIME: Final[int] + STATX_CTIME: Final[int] + STATX_DIOALIGN: Final[int] + STATX_GID: Final[int] + STATX_INO: Final[int] + STATX_MNT_ID: Final[int] + STATX_MNT_ID_UNIQUE: Final[int] + STATX_MODE: Final[int] + STATX_MTIME: Final[int] + STATX_NLINK: Final[int] + STATX_SIZE: Final[int] + STATX_TYPE: Final[int] + STATX_UID: Final[int] + +if sys.platform != "win32": + O_FSYNC: Final[int] + +if sys.platform != "linux" and sys.platform != "win32" and sys.version_info >= (3, 13): + O_EXEC: Final[int] + O_SEARCH: Final[int] + +if sys.platform != "win32" and sys.platform != "darwin": + # posix, but apparently missing on macos + ST_APPEND: Final[int] + ST_MANDLOCK: Final[int] + ST_NOATIME: Final[int] + ST_NODEV: Final[int] + ST_NODIRATIME: Final[int] + ST_NOEXEC: Final[int] + ST_RELATIME: Final[int] + ST_SYNCHRONOUS: Final[int] + ST_WRITE: Final[int] + +if sys.platform != "win32": + NGROUPS_MAX: Final[int] + ST_NOSUID: Final[int] + ST_RDONLY: Final[int] + +linesep: Literal["\n", "\r\n"] +name: LiteralString + +F_OK: Final = 0 +R_OK: Final = 4 +W_OK: Final = 2 +X_OK: Final = 1 + +_EnvironCodeFunc: TypeAlias = Callable[[AnyStr], AnyStr] + +class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + encodekey: _EnvironCodeFunc[AnyStr] + decodekey: _EnvironCodeFunc[AnyStr] + encodevalue: _EnvironCodeFunc[AnyStr] + decodevalue: _EnvironCodeFunc[AnyStr] + def __init__( + self, + data: MutableMapping[AnyStr, AnyStr], + encodekey: _EnvironCodeFunc[AnyStr], + decodekey: _EnvironCodeFunc[AnyStr], + encodevalue: _EnvironCodeFunc[AnyStr], + decodevalue: _EnvironCodeFunc[AnyStr], + ) -> None: ... + + @overload + def get(self, key: AnyStr, default: None = None) -> AnyStr | None: ... + @overload + def get(self, key: AnyStr, default: AnyStr) -> AnyStr: ... + @overload + def get(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + + @overload + def pop(self, key: AnyStr) -> AnyStr: ... + @overload + def pop(self, key: AnyStr, default: AnyStr) -> AnyStr: ... + @overload + def pop(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... + def copy(self) -> dict[AnyStr, AnyStr]: ... + def __delitem__(self, key: AnyStr) -> None: ... + def __getitem__(self, key: AnyStr) -> AnyStr: ... + def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... + def __len__(self) -> int: ... + def __or__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + + # We use @overload instead of a Union for reasons similar to those given for + # overloading MutableMapping.update in stdlib/typing.pyi + # The type: ignore is needed due to incompatible __or__/__ior__ signatures + @overload # type: ignore[misc] + def __ior__(self, other: Mapping[AnyStr, AnyStr]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... + +environ: _Environ[str] +if sys.platform != "win32": + environb: _Environ[bytes] + +if sys.version_info >= (3, 14): + def reload_environ() -> None: ... + +if sys.platform == "linux" and sys.version_info >= (3, 15): + def _clearenv() -> None: ... + +if sys.version_info >= (3, 11) or sys.platform != "win32": + EX_OK: Final[int] + +if sys.platform != "win32": + confstr_names: dict[str, int] + pathconf_names: dict[str, int] + sysconf_names: dict[str, int] + + EX_USAGE: Final[int] + EX_DATAERR: Final[int] + EX_NOINPUT: Final[int] + EX_NOUSER: Final[int] + EX_NOHOST: Final[int] + EX_UNAVAILABLE: Final[int] + EX_SOFTWARE: Final[int] + EX_OSERR: Final[int] + EX_OSFILE: Final[int] + EX_CANTCREAT: Final[int] + EX_IOERR: Final[int] + EX_TEMPFAIL: Final[int] + EX_PROTOCOL: Final[int] + EX_NOPERM: Final[int] + EX_CONFIG: Final[int] + +# Exists on some Unix platforms, e.g. Solaris. +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + EX_NOTFOUND: Final[int] + +P_NOWAIT: Final[int] +P_NOWAITO: Final[int] +P_WAIT: Final[int] +if sys.platform == "win32": + P_DETACH: Final[int] + P_OVERLAY: Final[int] + +# wait()/waitpid() options +if sys.platform != "win32": + WNOHANG: Final[int] # Unix only + WCONTINUED: Final[int] # some Unix systems + WUNTRACED: Final[int] # Unix only + +TMP_MAX: Final[int] # Undocumented, but used by tempfile + +# ----- os classes (structures) ----- +@final +class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]): + # The constructor of this class takes an iterable of variable length (though it must be at least 10). + # + # However, this class behaves like a tuple of 10 elements, + # no matter how long the iterable supplied to the constructor is. + # https://github.com/python/typeshed/pull/6560#discussion_r767162532 + # + # The 10 elements always present are st_mode, st_ino, st_dev, st_nlink, + # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. + # + # More items may be added at the end by some implementations. + __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") + + @property + def st_mode(self) -> int: ... # protection bits, + @property + def st_ino(self) -> int: ... # inode number, + @property + def st_dev(self) -> int: ... # device, + @property + def st_nlink(self) -> int: ... # number of hard links, + @property + def st_uid(self) -> int: ... # user id of owner, + @property + def st_gid(self) -> int: ... # group id of owner, + @property + def st_size(self) -> int: ... # size of file, in bytes, + @property + def st_atime(self) -> float: ... # time of most recent access, + @property + def st_mtime(self) -> float: ... # time of most recent content modification, + # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) + if sys.version_info >= (3, 12) and sys.platform == "win32": + @property + @deprecated("""\ +Use st_birthtime instead to retrieve the file creation time. \ +In the future, this property will contain the last metadata change time.""") + def st_ctime(self) -> float: ... + else: + @property + def st_ctime(self) -> float: ... + + @property + def st_atime_ns(self) -> int: ... # time of most recent access, in nanoseconds + @property + def st_mtime_ns(self) -> int: ... # time of most recent content modification in nanoseconds + # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds + @property + def st_ctime_ns(self) -> int: ... + if sys.platform == "win32": + @property + def st_file_attributes(self) -> int: ... + @property + def st_reparse_tag(self) -> int: ... + if sys.version_info >= (3, 12): + @property + def st_birthtime(self) -> float: ... # time of file creation in seconds + @property + def st_birthtime_ns(self) -> int: ... # time of file creation in nanoseconds + else: + @property + def st_blocks(self) -> int: ... # number of blocks allocated for file + @property + def st_blksize(self) -> int: ... # filesystem blocksize + @property + def st_rdev(self) -> int: ... # type of device if an inode device + if sys.platform != "linux": + # These properties are available on MacOS, but not Ubuntu. + # On other Unix systems (such as FreeBSD), the following attributes may be + # available (but may be only filled out if root tries to use them): + @property + def st_gen(self) -> int: ... # file generation number + @property + def st_birthtime(self) -> float: ... # time of file creation in seconds + if sys.platform == "darwin": + @property + def st_flags(self) -> int: ... # user defined flags for file + # Attributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. + # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327 + +# mypy and pyright object to this being both ABC and Protocol. +# At runtime it inherits from ABC and is not a Protocol, but it will be +# on the allowlist for use as a Protocol starting in 3.14. +@runtime_checkable +class PathLike(ABC, Protocol[AnyStr_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + __slots__ = () + @abstractmethod + def __fspath__(self) -> AnyStr_co: ... + +@overload +def listdir(path: StrPath | None = None) -> list[str]: ... +@overload +def listdir(path: BytesPath) -> list[bytes]: ... +@overload +def listdir(path: int) -> list[str]: ... + +@final +class DirEntry(Generic[AnyStr]): + # This is what the scandir iterator yields + # The constructor is hidden + + @property + def name(self) -> AnyStr: ... + @property + def path(self) -> AnyStr: ... + def inode(self) -> int: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... + def is_symlink(self) -> bool: ... + def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... + def __fspath__(self) -> AnyStr: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + if sys.version_info >= (3, 12): + def is_junction(self) -> bool: ... + +@final +class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): + __match_args__: Final = ( + "f_bsize", + "f_frsize", + "f_blocks", + "f_bfree", + "f_bavail", + "f_files", + "f_ffree", + "f_favail", + "f_flag", + "f_namemax", + ) + + @property + def f_bsize(self) -> int: ... + @property + def f_frsize(self) -> int: ... + @property + def f_blocks(self) -> int: ... + @property + def f_bfree(self) -> int: ... + @property + def f_bavail(self) -> int: ... + @property + def f_files(self) -> int: ... + @property + def f_ffree(self) -> int: ... + @property + def f_favail(self) -> int: ... + @property + def f_flag(self) -> int: ... + @property + def f_namemax(self) -> int: ... + @property + def f_fsid(self) -> int: ... + +# ----- os function stubs ----- +def fsencode(filename: StrOrBytesPath) -> bytes: ... +def fsdecode(filename: StrOrBytesPath) -> str: ... + +@overload +def fspath(path: str) -> str: ... +@overload +def fspath(path: bytes) -> bytes: ... +@overload +def fspath(path: PathLike[AnyStr]) -> AnyStr: ... + +def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: ... +def getlogin() -> str: ... +def getpid() -> int: ... +def getppid() -> int: ... +def strerror(code: int, /) -> str: ... +def umask(mask: int, /) -> int: ... + +@final +class uname_result(structseq[str], tuple[str, str, str, str, str]): + __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") + + @property + def sysname(self) -> str: ... + @property + def nodename(self) -> str: ... + @property + def release(self) -> str: ... + @property + def version(self) -> str: ... + @property + def machine(self) -> str: ... + +if sys.platform != "win32": + def ctermid() -> str: ... + def getegid() -> int: ... + def geteuid() -> int: ... + def getgid() -> int: ... + def getgrouplist(user: str, group: int, /) -> list[int]: ... + def getgroups() -> list[int]: ... # Unix only, behaves differently on Mac + def initgroups(username: str, gid: int, /) -> None: ... + def getpgid(pid: int) -> int: ... + def getpgrp() -> int: ... + def getpriority(which: int, who: int) -> int: ... + def setpriority(which: int, who: int, priority: int) -> None: ... + if sys.platform != "darwin": + def getresuid() -> tuple[int, int, int]: ... + def getresgid() -> tuple[int, int, int]: ... + + def getuid() -> int: ... + def setegid(egid: int, /) -> None: ... + def seteuid(euid: int, /) -> None: ... + def setgid(gid: int, /) -> None: ... + def setgroups(groups: Sequence[int], /) -> None: ... + def setpgrp() -> None: ... + def setpgid(pid: int, pgrp: int, /) -> None: ... + def setregid(rgid: int, egid: int, /) -> None: ... + if sys.platform != "darwin": + def setresgid(rgid: int, egid: int, sgid: int, /) -> None: ... + def setresuid(ruid: int, euid: int, suid: int, /) -> None: ... + + def setreuid(ruid: int, euid: int, /) -> None: ... + def getsid(pid: int, /) -> int: ... + def setsid() -> None: ... + def setuid(uid: int, /) -> None: ... + def uname() -> uname_result: ... + +@overload +def getenv(key: str) -> str | None: ... +@overload +def getenv(key: str, default: _T) -> str | _T: ... + +if sys.platform != "win32": + @overload + def getenvb(key: bytes) -> bytes | None: ... + @overload + def getenvb(key: bytes, default: _T) -> bytes | _T: ... + + def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: ... + def unsetenv(name: StrOrBytesPath, /) -> None: ... + +else: + def putenv(name: str, value: str, /) -> None: ... + def unsetenv(name: str, /) -> None: ... + +_Opener: TypeAlias = Callable[[str, int], int] + +@overload +def fdopen( + fd: int, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> TextIOWrapper: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> FileIO: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedRandom: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedWriter: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BufferedReader: ... +@overload +def fdopen( + fd: int, + mode: OpenBinaryMode, + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> BinaryIO: ... +@overload +def fdopen( + fd: int, + mode: str, + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, +) -> IO[Any]: ... + +def close(fd: int) -> None: ... +def closerange(fd_low: int, fd_high: int, /) -> None: ... +def device_encoding(fd: int) -> str | None: ... +def dup(fd: int, /) -> int: ... +def dup2(fd: int, fd2: int, inheritable: bool = True) -> int: ... +def fstat(fd: int) -> stat_result: ... +def ftruncate(fd: int, length: int, /) -> None: ... +def fsync(fd: FileDescriptorLike) -> None: ... +def isatty(fd: int, /) -> bool: ... + +if sys.platform != "win32" and sys.version_info >= (3, 11): + def login_tty(fd: int, /) -> None: ... + +if sys.version_info >= (3, 11): + def lseek(fd: int, position: int, whence: int, /) -> int: ... + +else: + def lseek(fd: int, position: int, how: int, /) -> int: ... + +def open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: ... +def pipe() -> tuple[int, int]: ... +def read(fd: int, length: int, /) -> bytes: ... + +if sys.version_info >= (3, 12) or sys.platform != "win32": + def get_blocking(fd: int, /) -> bool: ... + def set_blocking(fd: int, blocking: bool, /) -> None: ... + +if sys.platform != "win32": + def fchown(fd: int, uid: int, gid: int) -> None: ... + def fpathconf(fd: int, name: str | int, /) -> int: ... + def fstatvfs(fd: int, /) -> statvfs_result: ... + def lockf(fd: int, command: int, length: int, /) -> None: ... + def openpty() -> tuple[int, int]: ... # some flavors of Unix + if sys.platform != "darwin": + def fdatasync(fd: FileDescriptorLike) -> None: ... + def pipe2(flags: int, /) -> tuple[int, int]: ... # some flavors of Unix + def posix_fallocate(fd: int, offset: int, length: int, /) -> None: ... + def posix_fadvise(fd: int, offset: int, length: int, advice: int, /) -> None: ... + + def pread(fd: int, length: int, offset: int, /) -> bytes: ... + def pwrite(fd: int, buffer: ReadableBuffer, offset: int, /) -> int: ... + # In CI, stubtest sometimes reports that these are available on MacOS, sometimes not + def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: ... + def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: ... + if sys.platform != "darwin": + RWF_APPEND: Final[int] + RWF_DSYNC: Final[int] + RWF_SYNC: Final[int] + RWF_HIPRI: Final[int] + RWF_NOWAIT: Final[int] + + if sys.platform == "linux": + def sendfile(out_fd: FileDescriptor, in_fd: FileDescriptor, offset: int | None, count: int) -> int: ... + else: + def sendfile( + out_fd: FileDescriptor, + in_fd: FileDescriptor, + offset: int, + count: int, + headers: Sequence[ReadableBuffer] = (), + trailers: Sequence[ReadableBuffer] = (), + flags: int = 0, + ) -> int: ... # FreeBSD and Mac OS X only + + def readv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], /) -> int: ... + def writev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], /) -> int: ... + +if sys.version_info >= (3, 14): + def readinto(fd: int, buffer: ReadableBuffer, /) -> int: ... + +@final +class terminal_size(structseq[int], tuple[int, int]): + __match_args__: Final = ("columns", "lines") + + @property + def columns(self) -> int: ... + @property + def lines(self) -> int: ... + +def get_terminal_size(fd: int = ..., /) -> terminal_size: ... +def get_inheritable(fd: int, /) -> bool: ... +def set_inheritable(fd: int, inheritable: bool, /) -> None: ... + +if sys.platform == "win32": + def get_handle_inheritable(handle: int, /) -> bool: ... + def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: ... + +if sys.platform != "win32": + # Unix only + def tcgetpgrp(fd: int, /) -> int: ... + def tcsetpgrp(fd: int, pgid: int, /) -> None: ... + def ttyname(fd: int, /) -> str: ... + +def write(fd: int, data: ReadableBuffer, /) -> int: ... +def access( + path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True +) -> bool: ... +def chdir(path: FileDescriptorOrPath) -> None: ... + +if sys.platform != "win32": + def fchdir(fd: FileDescriptorLike) -> None: ... + +def getcwd() -> str: ... +def getcwdb() -> bytes: ... +def chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None: ... + +if sys.platform != "win32" and sys.platform != "linux": + def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: ... # some flavors of Unix + def lchflags(path: StrOrBytesPath, flags: int) -> None: ... + +if sys.platform != "win32": + def chroot(path: StrOrBytesPath) -> None: ... + def chown( + path: FileDescriptorOrPath, uid: int, gid: int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... + def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: ... + +def link( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + follow_symlinks: bool = True, +) -> None: ... +def lstat(path: StrOrBytesPath, *, dir_fd: int | None = None) -> stat_result: ... +def mkdir(path: StrOrBytesPath, mode: int = 0o777, *, dir_fd: int | None = None) -> None: ... + +if sys.platform != "win32": + def mkfifo(path: StrOrBytesPath, mode: int = 0o666, *, dir_fd: int | None = None) -> None: ... # Unix only + +if sys.version_info >= (3, 15): + def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False, *, parent_mode: int | None = None) -> None: ... + +else: + def makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> None: ... + +if sys.platform != "win32": + def mknod(path: StrOrBytesPath, mode: int = 0o600, device: int = 0, *, dir_fd: int | None = None) -> None: ... + def major(device: int, /) -> int: ... + def minor(device: int, /) -> int: ... + def makedev(major: int, minor: int, /) -> int: ... + def pathconf(path: FileDescriptorOrPath, name: str | int) -> int: ... # Unix only + +def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: ... +def remove(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... +def removedirs(name: StrOrBytesPath) -> None: ... +def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None) -> None: ... +def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: ... +def replace( + src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None +) -> None: ... +def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... + +@final +@type_check_only +class _ScandirIterator(Generic[AnyStr]): + def __del__(self) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> DirEntry[AnyStr]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def close(self) -> None: ... + +@overload +def scandir(path: None = None) -> _ScandirIterator[str]: ... +@overload +def scandir(path: int) -> _ScandirIterator[str]: ... +@overload +def scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ... + +def stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> stat_result: ... + +if sys.platform != "win32": + def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ... # Unix only + +if sys.platform == "linux" and sys.version_info >= (3, 15): + @final + class statx_result: + @property + def stx_mask(self) -> int: ... + @property + def stx_blksize(self) -> int: ... + @property + def stx_attributes(self) -> int: ... + @property + def stx_attributes_mask(self) -> int: ... + @property + def stx_rdev_major(self) -> int: ... + @property + def stx_rdev_minor(self) -> int: ... + @property + def stx_rdev(self) -> int: ... + @property + def stx_dev_major(self) -> int: ... + @property + def stx_dev_minor(self) -> int: ... + @property + def stx_dev(self) -> int: ... + @property + def stx_mode(self) -> int | None: ... + @property + def stx_nlink(self) -> int | None: ... + @property + def stx_uid(self) -> int | None: ... + @property + def stx_gid(self) -> int | None: ... + @property + def stx_ino(self) -> int | None: ... + @property + def stx_size(self) -> int | None: ... + @property + def stx_blocks(self) -> int | None: ... + @property + def stx_atime(self) -> float | None: ... + @property + def stx_atime_ns(self) -> int | None: ... + @property + def stx_btime(self) -> float | None: ... + @property + def stx_btime_ns(self) -> int | None: ... + @property + def stx_ctime(self) -> float | None: ... + @property + def stx_ctime_ns(self) -> int | None: ... + @property + def stx_mtime(self) -> float | None: ... + @property + def stx_mtime_ns(self) -> int | None: ... + @property + def stx_mnt_id(self) -> int | None: ... + @property + def stx_dio_mem_align(self) -> int | None: ... + @property + def stx_dio_offset_align(self) -> int | None: ... + + def statx( + path: FileDescriptorOrPath, mask: int, *, flags: int = 0, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> statx_result: ... + +def symlink( + src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = False, *, dir_fd: int | None = None +) -> None: ... + +if sys.platform != "win32": + def sync() -> None: ... # Unix only + +def truncate(path: FileDescriptorOrPath, length: int) -> None: ... # Unix only up to version 3.4 +def unlink(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... +def utime( + path: FileDescriptorOrPath, + times: tuple[int, int] | tuple[float, float] | None = None, + *, + ns: tuple[int, int] = ..., + dir_fd: int | None = None, + follow_symlinks: bool = True, +) -> None: ... + +_OnError: TypeAlias = Callable[[OSError], object] + +def walk( + top: GenericPath[AnyStr], topdown: bool = True, onerror: _OnError | None = None, followlinks: bool = False +) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... + +if sys.platform != "win32": + @overload + def fwalk( + top: StrPath = ".", + topdown: bool = True, + onerror: _OnError | None = None, + *, + follow_symlinks: bool = False, + dir_fd: int | None = None, + ) -> Iterator[tuple[str, list[str], list[str], int]]: ... + @overload + def fwalk( + top: BytesPath, + topdown: bool = True, + onerror: _OnError | None = None, + *, + follow_symlinks: bool = False, + dir_fd: int | None = None, + ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ... + + if sys.platform == "linux": + def getxattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> bytes: ... + def listxattr(path: FileDescriptorOrPath | None = None, *, follow_symlinks: bool = True) -> list[str]: ... + def removexattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... + def setxattr( + path: FileDescriptorOrPath, + attribute: StrOrBytesPath, + value: ReadableBuffer, + flags: int = 0, + *, + follow_symlinks: bool = True, + ) -> None: ... + +def abort() -> Never: ... + +# These are defined as execl(file, *args) but the first *arg is mandatory. +def execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... +def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... + +# These are: execle(file, *args, env) but env is pulled from the last element of the args. +def execle(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]) -> Never: ... +def execlpe( + file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]] +) -> Never: ... + +# The docs say `args: tuple or list of strings` +# The implementation enforces tuple or list so we can't use Sequence. +# Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference +# in practice, and doing so would explode the number of combinations in this already long union. +# All these combinations are necessary due to list being invariant. +_ExecVArgs: TypeAlias = ( + tuple[StrOrBytesPath, ...] + | list[bytes] + | list[str] + | list[PathLike[Any]] + | list[bytes | str] + | list[bytes | PathLike[Any]] + | list[str | PathLike[Any]] + | list[bytes | str | PathLike[Any]] +) +# Depending on the OS, the keys and values are passed either to +# PyUnicode_FSDecoder (which accepts str | ReadableBuffer) or to +# PyUnicode_FSConverter (which accepts StrOrBytesPath). For simplicity, +# we limit to str | bytes. +_ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] + +def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> Never: ... +def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> Never: ... +def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> Never: ... +def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> Never: ... +def _exit(status: int) -> Never: ... +def kill(pid: int, signal: int, /) -> None: ... + +if sys.platform != "win32": + # Unix only + def fork() -> int: ... + def forkpty() -> tuple[int, int]: ... # some flavors of Unix + def killpg(pgid: int, signal: int, /) -> None: ... + def nice(increment: int, /) -> int: ... + if sys.platform != "darwin" and sys.platform != "linux": + def plock(op: int, /) -> None: ... + +class _wrap_close: + def __init__(self, stream: TextIOWrapper, proc: Popen[str]) -> None: ... + def close(self) -> int | None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + # Methods below here don't exist directly on the _wrap_close object, but + # are copied from the wrapped TextIOWrapper object via __getattr__. + # The full set of TextIOWrapper methods are technically available this way, + # but undocumented. Only a subset are currently included here. + def read(self, size: int | None = -1, /) -> str: ... + def readable(self) -> bool: ... + def readline(self, size: int = -1, /) -> str: ... + def readlines(self, hint: int = -1, /) -> list[str]: ... + def writable(self) -> bool: ... + def write(self, s: str, /) -> int: ... + def writelines(self, lines: Iterable[str], /) -> None: ... + +@deprecated("Soft deprecated. Use the subprocess module instead.") +def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") +def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") +def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig + +if sys.platform != "win32": + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... +else: + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... + +@deprecated("Soft deprecated. Use the subprocess module instead.") +def system(command: StrOrBytesPath) -> int: ... + +@final +class times_result(structseq[float], tuple[float, float, float, float, float]): + __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") + + @property + def user(self) -> float: ... + @property + def system(self) -> float: ... + @property + def children_user(self) -> float: ... + @property + def children_system(self) -> float: ... + @property + def elapsed(self) -> float: ... + +def times() -> times_result: ... +def waitpid(pid: int, options: int, /) -> tuple[int, int]: ... + +if sys.platform == "win32": + def startfile( + filepath: StrOrBytesPath, operation: str = ..., arguments: str = "", cwd: StrOrBytesPath | None = None, show_cmd: int = 1 + ) -> None: ... + +else: + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... + def wait() -> tuple[int, int]: ... # Unix only + # Added to MacOS in 3.13 + if sys.platform != "darwin" or sys.version_info >= (3, 13): + @final + class waitid_result(structseq[int], tuple[int, int, int, int, int]): + __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") + + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_signo(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_code(self) -> int: ... + + def waitid(idtype: int, ident: int, options: int, /) -> waitid_result | None: ... + + from resource import struct_rusage + + def wait3(options: int) -> tuple[int, int, struct_rusage]: ... + def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: ... + def WCOREDUMP(status: int, /) -> bool: ... + def WIFCONTINUED(status: int) -> bool: ... + def WIFSTOPPED(status: int) -> bool: ... + def WIFSIGNALED(status: int) -> bool: ... + def WIFEXITED(status: int) -> bool: ... + def WEXITSTATUS(status: int) -> int: ... + def WSTOPSIG(status: int) -> int: ... + def WTERMSIG(status: int) -> int: ... + + if sys.version_info >= (3, 15): + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + elif sys.version_info >= (3, 13): + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, # None allowed starting in 3.13 + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, # None allowed starting in 3.13 + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + else: + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int = ..., + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] = ..., + ) -> int: ... + + POSIX_SPAWN_OPEN: Final = 0 + POSIX_SPAWN_CLOSE: Final = 1 + POSIX_SPAWN_DUP2: Final = 2 + +if sys.platform != "win32": + @final + class sched_param(structseq[int], tuple[int]): + __match_args__: Final = ("sched_priority",) + + def __new__(cls, sched_priority: int) -> Self: ... + @property + def sched_priority(self) -> int: ... + + def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix + def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix + def sched_yield() -> None: ... # some flavors of Unix + if sys.platform != "darwin": + def sched_setscheduler(pid: int, policy: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getscheduler(pid: int, /) -> int: ... # some flavors of Unix + def sched_rr_get_interval(pid: int, /) -> float: ... # some flavors of Unix + def sched_setparam(pid: int, param: sched_param, /) -> None: ... # some flavors of Unix + def sched_getparam(pid: int, /) -> sched_param: ... # some flavors of Unix + def sched_setaffinity(pid: int, mask: Iterable[int], /) -> None: ... # some flavors of Unix + def sched_getaffinity(pid: int, /) -> set[int]: ... # some flavors of Unix + +def cpu_count() -> int | None: ... + +if sys.version_info >= (3, 13): + # Documented to return `int | None`, but falls back to `len(sched_getaffinity(0))` when + # available. See https://github.com/python/cpython/blob/417c130/Lib/os.py#L1175-L1186. + if sys.platform != "win32" and sys.platform != "darwin": + def process_cpu_count() -> int: ... + else: + def process_cpu_count() -> int | None: ... + +if sys.platform != "win32": + # Unix only + def confstr(name: str | int, /) -> str | None: ... + def getloadavg() -> tuple[float, float, float]: ... + def sysconf(name: str | int, /) -> int: ... + +if sys.platform == "linux": + def getrandom(size: int, flags: int = 0) -> bytes: ... + +def urandom(size: int, /) -> bytes: ... + +if sys.platform != "win32": + def register_at_fork( + *, + before: Callable[..., Any] | None = ..., + after_in_parent: Callable[..., Any] | None = ..., + after_in_child: Callable[..., Any] | None = ..., + ) -> None: ... + +if sys.platform == "win32": + class _AddedDllDirectory: + path: str | None + def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], object]) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + + def add_dll_directory(path: str) -> _AddedDllDirectory: ... + +if sys.platform == "linux": + MFD_CLOEXEC: Final[int] + MFD_ALLOW_SEALING: Final[int] + MFD_HUGETLB: Final[int] + MFD_HUGE_SHIFT: Final[int] + MFD_HUGE_MASK: Final[int] + MFD_HUGE_64KB: Final[int] + MFD_HUGE_512KB: Final[int] + MFD_HUGE_1MB: Final[int] + MFD_HUGE_2MB: Final[int] + MFD_HUGE_8MB: Final[int] + MFD_HUGE_16MB: Final[int] + MFD_HUGE_32MB: Final[int] + MFD_HUGE_256MB: Final[int] + MFD_HUGE_512MB: Final[int] + MFD_HUGE_1GB: Final[int] + MFD_HUGE_2GB: Final[int] + MFD_HUGE_16GB: Final[int] + def memfd_create(name: str, flags: int = ...) -> int: ... + def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = None, offset_dst: int | None = None) -> int: ... + +def waitstatus_to_exitcode(status: int) -> int: ... + +if sys.platform == "linux": + def pidfd_open(pid: int, flags: int = 0) -> int: ... + +if sys.version_info >= (3, 12) and sys.platform == "linux": + PIDFD_NONBLOCK: Final = 2048 + +if sys.version_info >= (3, 12) and sys.platform == "win32": + def listdrives() -> list[str]: ... + def listmounts(volume: str) -> list[str]: ... + def listvolumes() -> list[str]: ... + +if sys.platform == "linux": + EFD_CLOEXEC: Final[int] + EFD_NONBLOCK: Final[int] + EFD_SEMAPHORE: Final[int] + SPLICE_F_MORE: Final[int] + SPLICE_F_MOVE: Final[int] + SPLICE_F_NONBLOCK: Final[int] + def eventfd(initval: int, flags: int = 524288) -> FileDescriptor: ... + def eventfd_read(fd: FileDescriptor) -> int: ... + def eventfd_write(fd: FileDescriptor, value: int) -> None: ... + def splice( + src: FileDescriptor, + dst: FileDescriptor, + count: int, + offset_src: int | None = None, + offset_dst: int | None = None, + flags: int = 0, + ) -> int: ... + +if sys.version_info >= (3, 12) and sys.platform == "linux": + CLONE_FILES: Final[int] + CLONE_FS: Final[int] + CLONE_NEWCGROUP: Final[int] # Linux 4.6+ + CLONE_NEWIPC: Final[int] # Linux 2.6.19+ + CLONE_NEWNET: Final[int] # Linux 2.6.24+ + CLONE_NEWNS: Final[int] + CLONE_NEWPID: Final[int] # Linux 3.8+ + CLONE_NEWTIME: Final[int] # Linux 5.6+ + CLONE_NEWUSER: Final[int] # Linux 3.8+ + CLONE_NEWUTS: Final[int] # Linux 2.6.19+ + CLONE_SIGHAND: Final[int] + CLONE_SYSVSEM: Final[int] # Linux 2.6.26+ + CLONE_THREAD: Final[int] + CLONE_VM: Final[int] + def unshare(flags: int) -> None: ... + def setns(fd: FileDescriptorLike, nstype: int = 0) -> None: ... + +if sys.version_info >= (3, 13) and sys.platform != "win32": + def posix_openpt(oflag: int, /) -> int: ... + def grantpt(fd: FileDescriptorLike, /) -> None: ... + def unlockpt(fd: FileDescriptorLike, /) -> None: ... + def ptsname(fd: FileDescriptorLike, /) -> str: ... + +if sys.version_info >= (3, 13) and sys.platform == "linux": + TFD_TIMER_ABSTIME: Final = 1 + TFD_TIMER_CANCEL_ON_SET: Final = 2 + TFD_NONBLOCK: Final[int] + TFD_CLOEXEC: Final[int] + POSIX_SPAWN_CLOSEFROM: Final[int] + + def timerfd_create(clockid: int, /, *, flags: int = 0) -> int: ... + def timerfd_settime( + fd: FileDescriptor, /, *, flags: int = 0, initial: float = 0.0, interval: float = 0.0 + ) -> tuple[float, float]: ... + def timerfd_settime_ns(fd: FileDescriptor, /, *, flags: int = 0, initial: int = 0, interval: int = 0) -> tuple[int, int]: ... + def timerfd_gettime(fd: FileDescriptor, /) -> tuple[float, float]: ... + def timerfd_gettime_ns(fd: FileDescriptor, /) -> tuple[int, int]: ... + +if sys.version_info >= (3, 13) or sys.platform != "win32": + # Added to Windows in 3.13. + def fchmod(fd: int, mode: int) -> None: ... + +if sys.platform != "linux": + if sys.version_info >= (3, 13) or sys.platform != "win32": + # Added to Windows in 3.13. + def lchmod(path: StrOrBytesPath, mode: int) -> None: ... diff --git a/stdlib/os/path.pyi b/stdlib/os/path.pyi new file mode 100644 index 000000000000..dc688a9f877f --- /dev/null +++ b/stdlib/os/path.pyi @@ -0,0 +1,8 @@ +import sys + +if sys.platform == "win32": + from ntpath import * + from ntpath import __all__ as __all__ +else: + from posixpath import * + from posixpath import __all__ as __all__ diff --git a/stdlib/ossaudiodev.pyi b/stdlib/ossaudiodev.pyi new file mode 100644 index 000000000000..f8230b4f0212 --- /dev/null +++ b/stdlib/ossaudiodev.pyi @@ -0,0 +1,132 @@ +import sys +from typing import Any, Final, Literal, overload + +if sys.platform != "win32" and sys.platform != "darwin": + # Depends on soundcard.h + AFMT_AC3: Final[int] + AFMT_A_LAW: Final[int] + AFMT_IMA_ADPCM: Final[int] + AFMT_MPEG: Final[int] + AFMT_MU_LAW: Final[int] + AFMT_QUERY: Final[int] + AFMT_S16_BE: Final[int] + AFMT_S16_LE: Final[int] + AFMT_S16_NE: Final[int] + AFMT_S8: Final[int] + AFMT_U16_BE: Final[int] + AFMT_U16_LE: Final[int] + AFMT_U8: Final[int] + SNDCTL_COPR_HALT: Final[int] + SNDCTL_COPR_LOAD: Final[int] + SNDCTL_COPR_RCODE: Final[int] + SNDCTL_COPR_RCVMSG: Final[int] + SNDCTL_COPR_RDATA: Final[int] + SNDCTL_COPR_RESET: Final[int] + SNDCTL_COPR_RUN: Final[int] + SNDCTL_COPR_SENDMSG: Final[int] + SNDCTL_COPR_WCODE: Final[int] + SNDCTL_COPR_WDATA: Final[int] + SNDCTL_DSP_BIND_CHANNEL: Final[int] + SNDCTL_DSP_CHANNELS: Final[int] + SNDCTL_DSP_GETBLKSIZE: Final[int] + SNDCTL_DSP_GETCAPS: Final[int] + SNDCTL_DSP_GETCHANNELMASK: Final[int] + SNDCTL_DSP_GETFMTS: Final[int] + SNDCTL_DSP_GETIPTR: Final[int] + SNDCTL_DSP_GETISPACE: Final[int] + SNDCTL_DSP_GETODELAY: Final[int] + SNDCTL_DSP_GETOPTR: Final[int] + SNDCTL_DSP_GETOSPACE: Final[int] + SNDCTL_DSP_GETSPDIF: Final[int] + SNDCTL_DSP_GETTRIGGER: Final[int] + SNDCTL_DSP_MAPINBUF: Final[int] + SNDCTL_DSP_MAPOUTBUF: Final[int] + SNDCTL_DSP_NONBLOCK: Final[int] + SNDCTL_DSP_POST: Final[int] + SNDCTL_DSP_PROFILE: Final[int] + SNDCTL_DSP_RESET: Final[int] + SNDCTL_DSP_SAMPLESIZE: Final[int] + SNDCTL_DSP_SETDUPLEX: Final[int] + SNDCTL_DSP_SETFMT: Final[int] + SNDCTL_DSP_SETFRAGMENT: Final[int] + SNDCTL_DSP_SETSPDIF: Final[int] + SNDCTL_DSP_SETSYNCRO: Final[int] + SNDCTL_DSP_SETTRIGGER: Final[int] + SNDCTL_DSP_SPEED: Final[int] + SNDCTL_DSP_STEREO: Final[int] + SNDCTL_DSP_SUBDIVIDE: Final[int] + SNDCTL_DSP_SYNC: Final[int] + SNDCTL_FM_4OP_ENABLE: Final[int] + SNDCTL_FM_LOAD_INSTR: Final[int] + SNDCTL_MIDI_INFO: Final[int] + SNDCTL_MIDI_MPUCMD: Final[int] + SNDCTL_MIDI_MPUMODE: Final[int] + SNDCTL_MIDI_PRETIME: Final[int] + SNDCTL_SEQ_CTRLRATE: Final[int] + SNDCTL_SEQ_GETINCOUNT: Final[int] + SNDCTL_SEQ_GETOUTCOUNT: Final[int] + SNDCTL_SEQ_GETTIME: Final[int] + SNDCTL_SEQ_NRMIDIS: Final[int] + SNDCTL_SEQ_NRSYNTHS: Final[int] + SNDCTL_SEQ_OUTOFBAND: Final[int] + SNDCTL_SEQ_PANIC: Final[int] + SNDCTL_SEQ_PERCMODE: Final[int] + SNDCTL_SEQ_RESET: Final[int] + SNDCTL_SEQ_RESETSAMPLES: Final[int] + SNDCTL_SEQ_SYNC: Final[int] + SNDCTL_SEQ_TESTMIDI: Final[int] + SNDCTL_SEQ_THRESHOLD: Final[int] + SNDCTL_SYNTH_CONTROL: Final[int] + SNDCTL_SYNTH_ID: Final[int] + SNDCTL_SYNTH_INFO: Final[int] + SNDCTL_SYNTH_MEMAVL: Final[int] + SNDCTL_SYNTH_REMOVESAMPLE: Final[int] + SNDCTL_TMR_CONTINUE: Final[int] + SNDCTL_TMR_METRONOME: Final[int] + SNDCTL_TMR_SELECT: Final[int] + SNDCTL_TMR_SOURCE: Final[int] + SNDCTL_TMR_START: Final[int] + SNDCTL_TMR_STOP: Final[int] + SNDCTL_TMR_TEMPO: Final[int] + SNDCTL_TMR_TIMEBASE: Final[int] + SOUND_MIXER_ALTPCM: Final[int] + SOUND_MIXER_BASS: Final[int] + SOUND_MIXER_CD: Final[int] + SOUND_MIXER_DIGITAL1: Final[int] + SOUND_MIXER_DIGITAL2: Final[int] + SOUND_MIXER_DIGITAL3: Final[int] + SOUND_MIXER_IGAIN: Final[int] + SOUND_MIXER_IMIX: Final[int] + SOUND_MIXER_LINE: Final[int] + SOUND_MIXER_LINE1: Final[int] + SOUND_MIXER_LINE2: Final[int] + SOUND_MIXER_LINE3: Final[int] + SOUND_MIXER_MIC: Final[int] + SOUND_MIXER_MONITOR: Final[int] + SOUND_MIXER_NRDEVICES: Final[int] + SOUND_MIXER_OGAIN: Final[int] + SOUND_MIXER_PCM: Final[int] + SOUND_MIXER_PHONEIN: Final[int] + SOUND_MIXER_PHONEOUT: Final[int] + SOUND_MIXER_RADIO: Final[int] + SOUND_MIXER_RECLEV: Final[int] + SOUND_MIXER_SPEAKER: Final[int] + SOUND_MIXER_SYNTH: Final[int] + SOUND_MIXER_TREBLE: Final[int] + SOUND_MIXER_VIDEO: Final[int] + SOUND_MIXER_VOLUME: Final[int] + + control_labels: list[str] + control_names: list[str] + + # TODO: oss_audio_device return type + @overload + def open(mode: Literal["r", "w", "rw"]) -> Any: ... + @overload + def open(device: str, mode: Literal["r", "w", "rw"]) -> Any: ... + + # TODO: oss_mixer_device return type + def openmixer(device: str = ...) -> Any: ... + + class OSSAudioError(Exception): ... + error = OSSAudioError diff --git a/stdlib/pathlib/__init__.pyi b/stdlib/pathlib/__init__.pyi new file mode 100644 index 000000000000..fa011e6097a4 --- /dev/null +++ b/stdlib/pathlib/__init__.pyi @@ -0,0 +1,358 @@ +import sys +import types +from _typeshed import ( + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + StrOrBytesPath, + StrPath, + Unused, +) +from collections.abc import Callable, Generator, Iterator, Sequence +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper +from os import PathLike, stat_result +from types import GenericAlias, TracebackType +from typing import IO, Any, BinaryIO, ClassVar, Literal, TypeVar, overload +from typing_extensions import Never, Self, deprecated + +_PathT = TypeVar("_PathT", bound=PurePath) + +__all__ = ["PurePath", "PurePosixPath", "PureWindowsPath", "Path", "PosixPath", "WindowsPath"] + +if sys.version_info >= (3, 14): + from pathlib.types import PathInfo + +if sys.version_info >= (3, 13): + __all__ += ["UnsupportedOperation"] + +class PurePath(PathLike[str]): + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_hash", + ) + elif sys.version_info >= (3, 12): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_lines_cached", + "_hash", + ) + else: + __slots__ = ("_drv", "_root", "_parts", "_str", "_hash", "_pparts", "_cached_cparts") + if sys.version_info >= (3, 13): + parser: ClassVar[types.ModuleType] + def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ... + + @property + def parts(self) -> tuple[str, ...]: ... + @property + def drive(self) -> str: ... + @property + def root(self) -> str: ... + @property + def anchor(self) -> str: ... + @property + def name(self) -> str: ... + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + if sys.version_info >= (3, 12): + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... + def __init__(self, *args: StrPath) -> None: ... # pyright: ignore[reportInconsistentConstructor] + else: + def __new__(cls, *args: StrPath) -> Self: ... + + def __hash__(self) -> int: ... + def __fspath__(self) -> str: ... + if sys.version_info >= (3, 15): + def __vfspath__(self) -> str: ... + + def __lt__(self, other: PurePath) -> bool: ... + def __le__(self, other: PurePath) -> bool: ... + def __gt__(self, other: PurePath) -> bool: ... + def __ge__(self, other: PurePath) -> bool: ... + def __truediv__(self, key: StrPath) -> Self: ... + def __rtruediv__(self, key: StrPath) -> Self: ... + def __bytes__(self) -> bytes: ... + def as_posix(self) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.19. Use `Path.as_uri()` instead.") + def as_uri(self) -> str: ... + def is_absolute(self) -> bool: ... + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + @deprecated( + "Deprecated since Python 3.13; will be removed in Python 3.15. " + "Use `os.path.isreserved()` to detect reserved paths on Windows." + ) + def is_reserved(self) -> bool: ... + else: + def is_reserved(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_relative_to(self, other: StrPath) -> bool: ... + else: + @overload + def is_relative_to(self, other: StrPath, /) -> bool: ... + @overload + @deprecated("Passing additional arguments is deprecated; removed in Python 3.14.") + def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... + + if sys.version_info >= (3, 12): + def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ... + else: + def match(self, path_pattern: str) -> bool: ... + + if sys.version_info >= (3, 14): + def relative_to(self, other: StrPath, *, walk_up: bool = False) -> Self: ... + elif sys.version_info >= (3, 12): + @overload + def relative_to(self, other: StrPath, /, *, walk_up: bool = False) -> Self: ... + @overload + @deprecated("Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.") + def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ... + else: + def relative_to(self, *other: StrPath) -> Self: ... + + def with_name(self, name: str) -> Self: ... + def with_stem(self, stem: str) -> Self: ... + def with_suffix(self, suffix: str) -> Self: ... + def joinpath(self, *other: StrPath) -> Self: ... + @property + def parents(self) -> Sequence[Self]: ... + @property + def parent(self) -> Self: ... + if sys.version_info < (3, 11): + def __class_getitem__(cls, type: Any) -> GenericAlias: ... + + if sys.version_info >= (3, 12): + def with_segments(self, *args: StrPath) -> Self: ... + +class PurePosixPath(PurePath): + __slots__ = () + +class PureWindowsPath(PurePath): + __slots__ = () + +class Path(PurePath): + if sys.version_info >= (3, 14): + __slots__ = ("_info",) + else: + __slots__ = () + + if sys.version_info >= (3, 12): + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor] + else: + def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... + + @classmethod + def cwd(cls) -> Self: ... + def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... + def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ... + + if sys.version_info >= (3, 13): + @classmethod + def from_uri(cls, uri: str) -> Self: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... + def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: ... + else: + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ... + + if sys.version_info >= (3, 13): + def glob(self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False) -> Iterator[Self]: ... + def rglob( + self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False + ) -> Iterator[Self]: ... + elif sys.version_info >= (3, 12): + def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... + def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... + else: + def glob(self, pattern: str) -> Generator[Self]: ... + def rglob(self, pattern: str) -> Generator[Self]: ... + + if sys.version_info >= (3, 12): + def exists(self, *, follow_symlinks: bool = True) -> bool: ... + else: + def exists(self) -> bool: ... + + def is_symlink(self) -> bool: ... + def is_socket(self) -> bool: ... + def is_fifo(self) -> bool: ... + def is_block_device(self) -> bool: ... + def is_char_device(self) -> bool: ... + if sys.version_info >= (3, 12): + def is_junction(self) -> bool: ... + + def iterdir(self) -> Generator[Self]: ... + def lchmod(self, mode: int) -> None: ... + def lstat(self) -> stat_result: ... + if sys.version_info >= (3, 15): + def mkdir( + self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False, *, parent_mode: int | None = None + ) -> None: ... + else: + def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ... + + if sys.version_info >= (3, 14): + @property + def info(self) -> PathInfo: ... + + @overload + def move_into(self, target_dir: _PathT) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def move_into(self, target_dir: StrPath) -> Self: ... # type: ignore[overload-overlap] + + @overload + def move(self, target: _PathT) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def move(self, target: StrPath) -> Self: ... # type: ignore[overload-overlap] + + @overload + def copy_into(self, target_dir: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def copy_into(self, target_dir: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] + + @overload + def copy(self, target: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] + @overload + def copy(self, target: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] + + # Adapted from builtins.open + # Text mode: always returns a TextIOWrapper + # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this. + @overload + def open( + self, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> TextIOWrapper: ... + # Unbuffered binary mode: returns a FileIO + @overload + def open( + self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None + ) -> FileIO: ... + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def open( + self, + mode: OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedRandom: ... + @overload + def open( + self, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedWriter: ... + @overload + def open( + self, + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + ) -> BufferedReader: ... + # Buffering cannot be determined: fall back to BinaryIO + @overload + def open( + self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None + ) -> BinaryIO: ... + # Fallback if mode is not specified + @overload + def open( + self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None + ) -> IO[Any]: ... + + # These methods do "exist" on Windows, but they always raise NotImplementedError. + if sys.platform == "win32": + if sys.version_info >= (3, 13): + # raises UnsupportedOperation: + def owner(self: Never, *, follow_symlinks: bool = True) -> str: ... # type: ignore[misc] + def group(self: Never, *, follow_symlinks: bool = True) -> str: ... # type: ignore[misc] + else: + def owner(self: Never) -> str: ... # type: ignore[misc] + def group(self: Never) -> str: ... # type: ignore[misc] + else: + if sys.version_info >= (3, 13): + def owner(self, *, follow_symlinks: bool = True) -> str: ... + def group(self, *, follow_symlinks: bool = True) -> str: ... + else: + def owner(self) -> str: ... + def group(self) -> str: ... + + # This method does "exist" on Windows on <3.12, but always raises NotImplementedError + # On py312+, it works properly on Windows, as with all other platforms + if sys.platform == "win32" and sys.version_info < (3, 12): + def is_mount(self: Never) -> bool: ... # type: ignore[misc] + else: + def is_mount(self) -> bool: ... + + def readlink(self) -> Self: ... + def rename(self, target: StrPath) -> Self: ... + def replace(self, target: StrPath) -> Self: ... + def resolve(self, strict: bool = False) -> Self: ... + def rmdir(self) -> None: ... + def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ... + def hardlink_to(self, target: StrOrBytesPath) -> None: ... + def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ... + def unlink(self, missing_ok: bool = False) -> None: ... + @classmethod + def home(cls) -> Self: ... + def absolute(self) -> Self: ... + def expanduser(self) -> Self: ... + def read_bytes(self) -> bytes: ... + def samefile(self, other_path: StrPath) -> bool: ... + def write_bytes(self, data: ReadableBuffer) -> int: ... + def write_text( + self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None + ) -> int: ... + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `hardlink_to()` instead.") + def link_to(self, target: StrOrBytesPath) -> None: ... + if sys.version_info >= (3, 12): + def walk( + self, top_down: bool = True, on_error: Callable[[OSError], object] | None = None, follow_symlinks: bool = False + ) -> Iterator[tuple[Self, list[str], list[str]]]: ... + + def as_uri(self) -> str: ... + +class PosixPath(Path, PurePosixPath): + __slots__ = () + +class WindowsPath(Path, PureWindowsPath): + __slots__ = () + +if sys.version_info >= (3, 13): + class UnsupportedOperation(NotImplementedError): ... diff --git a/stdlib/pathlib/types.pyi b/stdlib/pathlib/types.pyi new file mode 100644 index 000000000000..9f9a650846de --- /dev/null +++ b/stdlib/pathlib/types.pyi @@ -0,0 +1,8 @@ +from typing import Protocol, runtime_checkable + +@runtime_checkable +class PathInfo(Protocol): + def exists(self, *, follow_symlinks: bool = True) -> bool: ... + def is_dir(self, *, follow_symlinks: bool = True) -> bool: ... + def is_file(self, *, follow_symlinks: bool = True) -> bool: ... + def is_symlink(self) -> bool: ... diff --git a/stdlib/pdb.pyi b/stdlib/pdb.pyi new file mode 100644 index 000000000000..289637cb5f04 --- /dev/null +++ b/stdlib/pdb.pyi @@ -0,0 +1,275 @@ +import signal +import sys +from _typeshed import ReadableBuffer +from bdb import Bdb, _Backend +from cmd import Cmd +from collections.abc import Callable, Iterable, Mapping, Sequence +from linecache import _ModuleGlobals +from rlcompleter import Completer +from types import CodeType, FrameType, TracebackType +from typing import IO, Any, ClassVar, Final, Literal, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self, deprecated + +__all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] +if sys.version_info >= (3, 14): + __all__ += ["set_default_backend", "get_default_backend"] + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_Mode: TypeAlias = Literal["inline", "cli"] + +line_prefix: Final[str] # undocumented + +class Restart(Exception): ... + +def run( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> None: ... +def runctx( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any], locals: Mapping[str, object] +) -> None: ... +def runeval( # matches `builtins.eval` + expression: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> Any: ... +def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... + +if sys.version_info >= (3, 14): + def set_default_backend(backend: _Backend) -> None: ... + def get_default_backend() -> _Backend: ... + def set_trace(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ... + async def set_trace_async(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ... + +else: + def set_trace(*, header: str | None = None) -> None: ... + +def post_mortem(t: TracebackType | None = None) -> None: ... +def pm() -> None: ... + +class Pdb(Bdb, Cmd): + # Everything here is undocumented, except for __init__ + + commands_resuming: ClassVar[list[str]] + + if sys.version_info >= (3, 13): + MAX_CHAINED_EXCEPTION_DEPTH: Final = 999 + + aliases: dict[str, str] + mainpyfile: str + _wait_for_mainpyfile: bool + rcLines: list[str] + commands: dict[int, list[str]] + commands_doprompt: dict[int, bool] + commands_silent: dict[int, bool] + commands_defining: bool + commands_bnum: int | None + lineno: int | None + stack: list[tuple[FrameType, int]] + curindex: int + curframe: FrameType | None + if sys.version_info >= (3, 13): + @property + @deprecated("The frame locals reference is no longer cached. Use 'curframe.f_locals' instead.") + def curframe_locals(self) -> Mapping[str, Any]: ... + @curframe_locals.setter + @deprecated( + "Setting 'curframe_locals' no longer has any effect as of 3.14. Update the contents of 'curframe.f_locals' instead." + ) + def curframe_locals(self, value: Mapping[str, Any]) -> None: ... + else: + curframe_locals: Mapping[str, Any] + if sys.version_info >= (3, 14): + mode: _Mode | None + colorize: bool + def __init__( + self, + completekey: str = "tab", + stdin: IO[str] | None = None, + stdout: IO[str] | None = None, + skip: Iterable[str] | None = None, + nosigint: bool = False, + readrc: bool = True, + mode: _Mode | None = None, + backend: _Backend | None = None, + colorize: bool = False, + ) -> None: ... + else: + def __init__( + self, + completekey: str = "tab", + stdin: IO[str] | None = None, + stdout: IO[str] | None = None, + skip: Iterable[str] | None = None, + nosigint: bool = False, + readrc: bool = True, + ) -> None: ... + if sys.version_info >= (3, 14): + def set_trace(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ... + async def set_trace_async(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ... + + def forget(self) -> None: ... + def setup(self, f: FrameType | None, tb: TracebackType | None) -> None: ... + if sys.version_info < (3, 11): + def execRcLines(self) -> None: ... + + if sys.version_info >= (3, 13): + user_opcode = Bdb.user_line + + def bp_commands(self, frame: FrameType) -> bool: ... + + if sys.version_info >= (3, 13): + def interaction(self, frame: FrameType | None, tb_or_exc: TracebackType | BaseException | None) -> None: ... + else: + def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ... + + def displayhook(self, obj: object) -> None: ... + def handle_command_def(self, line: str) -> bool: ... + def defaultFile(self) -> str: ... + def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ... + if sys.version_info >= (3, 14): + def checkline(self, filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> int: ... + else: + def checkline(self, filename: str, lineno: int) -> int: ... + + def _getval(self, arg: str) -> object: ... + if sys.version_info >= (3, 14): + def print_stack_trace(self, count: int | None = None) -> None: ... + else: + def print_stack_trace(self) -> None: ... + + if sys.version_info >= (3, 15): + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str | None = None) -> None: ... + else: + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... + + def lookupmodule(self, filename: str) -> str | None: ... + if sys.version_info < (3, 11): + def _runscript(self, filename: str) -> None: ... + + if sys.version_info >= (3, 14): + def complete_multiline_names(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + + if sys.version_info >= (3, 13): + def completedefault(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + + def do_commands(self, arg: str) -> bool | None: ... + if sys.version_info >= (3, 14): + def do_break(self, arg: str, temporary: bool = False) -> bool | None: ... + else: + def do_break(self, arg: str, temporary: bool | Literal[0, 1] = 0) -> bool | None: ... + + def do_tbreak(self, arg: str) -> bool | None: ... + def do_enable(self, arg: str) -> bool | None: ... + def do_disable(self, arg: str) -> bool | None: ... + def do_condition(self, arg: str) -> bool | None: ... + def do_ignore(self, arg: str) -> bool | None: ... + def do_clear(self, arg: str) -> bool | None: ... + def do_where(self, arg: str) -> bool | None: ... + if sys.version_info >= (3, 13): + def do_exceptions(self, arg: str) -> bool | None: ... + + def do_up(self, arg: str) -> bool | None: ... + def do_down(self, arg: str) -> bool | None: ... + def do_until(self, arg: str) -> bool | None: ... + def do_step(self, arg: str) -> bool | None: ... + def do_next(self, arg: str) -> bool | None: ... + def do_run(self, arg: str) -> bool | None: ... + def do_return(self, arg: str) -> bool | None: ... + def do_continue(self, arg: str) -> bool | None: ... + def do_jump(self, arg: str) -> bool | None: ... + def do_debug(self, arg: str) -> bool | None: ... + def do_quit(self, arg: str) -> bool | None: ... + def do_EOF(self, arg: str) -> bool | None: ... + def do_args(self, arg: str) -> bool | None: ... + def do_retval(self, arg: str) -> bool | None: ... + def do_p(self, arg: str) -> bool | None: ... + def do_pp(self, arg: str) -> bool | None: ... + def do_list(self, arg: str) -> bool | None: ... + def do_whatis(self, arg: str) -> bool | None: ... + def do_alias(self, arg: str) -> bool | None: ... + def do_unalias(self, arg: str) -> bool | None: ... + def do_help(self, arg: str) -> bool | None: ... + do_b = do_break + do_cl = do_clear + do_w = do_where + do_bt = do_where + do_u = do_up + do_d = do_down + do_unt = do_until + do_s = do_step + do_n = do_next + do_restart = do_run + do_r = do_return + do_c = do_continue + do_cont = do_continue + do_j = do_jump + do_q = do_quit + do_exit = do_quit + do_a = do_args + do_rv = do_retval + do_l = do_list + do_h = do_help + def help_exec(self) -> None: ... + def help_pdb(self) -> None: ... + def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ... + if sys.version_info >= (3, 13): + def message(self, msg: str, end: str = "\n") -> None: ... + else: + def message(self, msg: str) -> None: ... + + def error(self, msg: str) -> None: ... + if sys.version_info >= (3, 13): + def completenames(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... # type: ignore[override] + if sys.version_info >= (3, 12): + def set_convenience_variable(self, frame: FrameType, name: str, value: Any) -> None: ... + if sys.version_info >= (3, 13): + # Added in 3.13.8 and 3.14.1 + @property + def rlcompleter(self) -> type[Completer]: ... + + def _select_frame(self, number: int) -> None: ... + def _getval_except(self, arg: str, frame: FrameType | None = None) -> object: ... + def _print_lines( + self, lines: Sequence[str], start: int, breaks: Sequence[int] = (), frame: FrameType | None = None + ) -> None: ... + def _cmdloop(self) -> None: ... + def do_display(self, arg: str) -> bool | None: ... + def do_interact(self, arg: str) -> bool | None: ... + def do_longlist(self, arg: str) -> bool | None: ... + def do_source(self, arg: str) -> bool | None: ... + def do_undisplay(self, arg: str) -> bool | None: ... + do_ll = do_longlist + def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ... + complete_commands = _complete_bpnumber + complete_break = _complete_location + complete_b = _complete_location + complete_tbreak = _complete_location + complete_enable = _complete_bpnumber + complete_disable = _complete_bpnumber + complete_condition = _complete_bpnumber + complete_ignore = _complete_bpnumber + complete_clear = _complete_location + complete_cl = _complete_location + complete_debug = _complete_expression + complete_print = _complete_expression + complete_p = _complete_expression + complete_pp = _complete_expression + complete_source = _complete_expression + complete_whatis = _complete_expression + complete_display = _complete_expression + + if sys.version_info < (3, 11): + def _runmodule(self, module_name: str) -> None: ... + +# undocumented + +def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... +def main() -> None: ... +def help() -> None: ... +def lasti2lineno(code: CodeType, lasti: int) -> int: ... + +class _rstr(str): + def __repr__(self) -> Self: ... diff --git a/stdlib/pickle.pyi b/stdlib/pickle.pyi new file mode 100644 index 000000000000..03ba6c12cd4a --- /dev/null +++ b/stdlib/pickle.pyi @@ -0,0 +1,240 @@ +import sys +from _pickle import ( + PickleError as PickleError, + Pickler as Pickler, + PicklingError as PicklingError, + Unpickler as Unpickler, + UnpicklingError as UnpicklingError, + _BufferCallback, + _ReadableFileobj, + _ReducedType, + dump as dump, + dumps as dumps, + load as load, + loads as loads, +) +from _typeshed import ReadableBuffer, SupportsWrite +from collections.abc import Callable, Iterable, Mapping +from typing import Any, ClassVar, Final, SupportsBytes, SupportsIndex, final +from typing_extensions import Self + +__all__ = [ + "PickleBuffer", + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "dump", + "dumps", + "load", + "loads", + "ADDITEMS", + "APPEND", + "APPENDS", + "BINBYTES", + "BINBYTES8", + "BINFLOAT", + "BINGET", + "BININT", + "BININT1", + "BININT2", + "BINPERSID", + "BINPUT", + "BINSTRING", + "BINUNICODE", + "BINUNICODE8", + "BUILD", + "BYTEARRAY8", + "DEFAULT_PROTOCOL", + "DICT", + "DUP", + "EMPTY_DICT", + "EMPTY_LIST", + "EMPTY_SET", + "EMPTY_TUPLE", + "EXT1", + "EXT2", + "EXT4", + "FALSE", + "FLOAT", + "FRAME", + "FROZENSET", + "GET", + "GLOBAL", + "HIGHEST_PROTOCOL", + "INST", + "INT", + "LIST", + "LONG", + "LONG1", + "LONG4", + "LONG_BINGET", + "LONG_BINPUT", + "MARK", + "MEMOIZE", + "NEWFALSE", + "NEWOBJ", + "NEWOBJ_EX", + "NEWTRUE", + "NEXT_BUFFER", + "NONE", + "OBJ", + "PERSID", + "POP", + "POP_MARK", + "PROTO", + "PUT", + "READONLY_BUFFER", + "REDUCE", + "SETITEM", + "SETITEMS", + "SHORT_BINBYTES", + "SHORT_BINSTRING", + "SHORT_BINUNICODE", + "STACK_GLOBAL", + "STOP", + "STRING", + "TRUE", + "TUPLE", + "TUPLE1", + "TUPLE2", + "TUPLE3", + "UNICODE", +] + +HIGHEST_PROTOCOL: Final = 5 +if sys.version_info >= (3, 14): + DEFAULT_PROTOCOL: Final = 5 +else: + DEFAULT_PROTOCOL: Final = 4 + +bytes_types: tuple[type[Any], ...] # undocumented + +@final +class PickleBuffer: + def __new__(cls, buffer: ReadableBuffer) -> Self: ... + def raw(self) -> memoryview: ... + def release(self) -> None: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __release_buffer__(self, buffer: memoryview, /) -> None: ... + +MARK: Final = b"(" +STOP: Final = b"." +POP: Final = b"0" +POP_MARK: Final = b"1" +DUP: Final = b"2" +FLOAT: Final = b"F" +INT: Final = b"I" +BININT: Final = b"J" +BININT1: Final = b"K" +LONG: Final = b"L" +BININT2: Final = b"M" +NONE: Final = b"N" +PERSID: Final = b"P" +BINPERSID: Final = b"Q" +REDUCE: Final = b"R" +STRING: Final = b"S" +BINSTRING: Final = b"T" +SHORT_BINSTRING: Final = b"U" +UNICODE: Final = b"V" +BINUNICODE: Final = b"X" +APPEND: Final = b"a" +BUILD: Final = b"b" +GLOBAL: Final = b"c" +DICT: Final = b"d" +EMPTY_DICT: Final = b"}" +APPENDS: Final = b"e" +GET: Final = b"g" +BINGET: Final = b"h" +INST: Final = b"i" +LONG_BINGET: Final = b"j" +LIST: Final = b"l" +EMPTY_LIST: Final = b"]" +OBJ: Final = b"o" +PUT: Final = b"p" +BINPUT: Final = b"q" +LONG_BINPUT: Final = b"r" +SETITEM: Final = b"s" +TUPLE: Final = b"t" +EMPTY_TUPLE: Final = b")" +SETITEMS: Final = b"u" +BINFLOAT: Final = b"G" + +TRUE: Final = b"I01\n" +FALSE: Final = b"I00\n" + +# protocol 2 +PROTO: Final = b"\x80" +NEWOBJ: Final = b"\x81" +EXT1: Final = b"\x82" +EXT2: Final = b"\x83" +EXT4: Final = b"\x84" +TUPLE1: Final = b"\x85" +TUPLE2: Final = b"\x86" +TUPLE3: Final = b"\x87" +NEWTRUE: Final = b"\x88" +NEWFALSE: Final = b"\x89" +LONG1: Final = b"\x8a" +LONG4: Final = b"\x8b" + +# protocol 3 +BINBYTES: Final = b"B" +SHORT_BINBYTES: Final = b"C" + +# protocol 4 +SHORT_BINUNICODE: Final = b"\x8c" +BINUNICODE8: Final = b"\x8d" +BINBYTES8: Final = b"\x8e" +EMPTY_SET: Final = b"\x8f" +ADDITEMS: Final = b"\x90" +FROZENSET: Final = b"\x91" +NEWOBJ_EX: Final = b"\x92" +STACK_GLOBAL: Final = b"\x93" +MEMOIZE: Final = b"\x94" +FRAME: Final = b"\x95" + +# protocol 5 +BYTEARRAY8: Final = b"\x96" +NEXT_BUFFER: Final = b"\x97" +READONLY_BUFFER: Final = b"\x98" + +def encode_long(x: int) -> bytes: ... # undocumented +def decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: ... # undocumented + +# undocumented pure-Python implementations +class _Pickler: + fast: bool + dispatch_table: Mapping[type, Callable[[Any], _ReducedType]] + bin: bool # undocumented + dispatch: ClassVar[dict[type, Callable[[Unpickler, Any], None]]] # undocumented, _Pickler only + def __init__( + self, + file: SupportsWrite[bytes], + protocol: int | None = None, + *, + fix_imports: bool = True, + buffer_callback: _BufferCallback = None, + ) -> None: ... + def dump(self, obj: Any) -> None: ... + def clear_memo(self) -> None: ... + def persistent_id(self, obj: Any) -> Any: ... + # The following method is not defined on _Pickler, but can be defined on + # sub-classes. Should return `NotImplemented` if pickling the supplied + # object is not supported and returns the same types as `__reduce__()`. + def reducer_override(self, obj: object, /) -> _ReducedType: ... + +class _Unpickler: + dispatch: ClassVar[dict[int, Callable[[Unpickler], None]]] # undocumented, _Unpickler only + def __init__( + self, + file: _ReadableFileobj, + *, + fix_imports: bool = True, + encoding: str = "ASCII", + errors: str = "strict", + buffers: Iterable[Any] | None = None, + ) -> None: ... + def load(self) -> Any: ... + def find_class(self, module: str, name: str) -> Any: ... + def persistent_load(self, pid: Any) -> Any: ... diff --git a/stdlib/pickletools.pyi b/stdlib/pickletools.pyi new file mode 100644 index 000000000000..98353d960888 --- /dev/null +++ b/stdlib/pickletools.pyi @@ -0,0 +1,176 @@ +import sys +from collections.abc import Callable, Iterator, MutableMapping +from typing import IO, Any, Final, TypeAlias + +__all__ = ["dis", "genops", "optimize"] + +_Reader: TypeAlias = Callable[[IO[bytes]], Any] +bytes_types: tuple[type[Any], ...] + +UP_TO_NEWLINE: Final = -1 +TAKEN_FROM_ARGUMENT1: Final = -2 +TAKEN_FROM_ARGUMENT4: Final = -3 +TAKEN_FROM_ARGUMENT4U: Final = -4 +TAKEN_FROM_ARGUMENT8U: Final = -5 + +class ArgumentDescriptor: + __slots__ = ("name", "n", "reader", "doc") + name: str + n: int + reader: _Reader + doc: str + def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ... + +def read_uint1(f: IO[bytes]) -> int: ... + +uint1: ArgumentDescriptor + +def read_uint2(f: IO[bytes]) -> int: ... + +uint2: ArgumentDescriptor + +def read_int4(f: IO[bytes]) -> int: ... + +int4: ArgumentDescriptor + +def read_uint4(f: IO[bytes]) -> int: ... + +uint4: ArgumentDescriptor + +def read_uint8(f: IO[bytes]) -> int: ... + +uint8: ArgumentDescriptor + +if sys.version_info >= (3, 12): + def read_stringnl( + f: IO[bytes], decode: bool = True, stripquotes: bool = True, *, encoding: str = "latin-1" + ) -> bytes | str: ... + +else: + def read_stringnl(f: IO[bytes], decode: bool = True, stripquotes: bool = True) -> bytes | str: ... + +stringnl: ArgumentDescriptor + +def read_stringnl_noescape(f: IO[bytes]) -> str: ... + +stringnl_noescape: ArgumentDescriptor + +def read_stringnl_noescape_pair(f: IO[bytes]) -> str: ... + +stringnl_noescape_pair: ArgumentDescriptor + +def read_string1(f: IO[bytes]) -> str: ... + +string1: ArgumentDescriptor + +def read_string4(f: IO[bytes]) -> str: ... + +string4: ArgumentDescriptor + +def read_bytes1(f: IO[bytes]) -> bytes: ... + +bytes1: ArgumentDescriptor + +def read_bytes4(f: IO[bytes]) -> bytes: ... + +bytes4: ArgumentDescriptor + +def read_bytes8(f: IO[bytes]) -> bytes: ... + +bytes8: ArgumentDescriptor + +def read_unicodestringnl(f: IO[bytes]) -> str: ... + +unicodestringnl: ArgumentDescriptor + +def read_unicodestring1(f: IO[bytes]) -> str: ... + +unicodestring1: ArgumentDescriptor + +def read_unicodestring4(f: IO[bytes]) -> str: ... + +unicodestring4: ArgumentDescriptor + +def read_unicodestring8(f: IO[bytes]) -> str: ... + +unicodestring8: ArgumentDescriptor + +def read_decimalnl_short(f: IO[bytes]) -> int: ... +def read_decimalnl_long(f: IO[bytes]) -> int: ... + +decimalnl_short: ArgumentDescriptor +decimalnl_long: ArgumentDescriptor + +def read_floatnl(f: IO[bytes]) -> float: ... + +floatnl: ArgumentDescriptor + +def read_float8(f: IO[bytes]) -> float: ... + +float8: ArgumentDescriptor + +def read_long1(f: IO[bytes]) -> int: ... + +long1: ArgumentDescriptor + +def read_long4(f: IO[bytes]) -> int: ... + +long4: ArgumentDescriptor + +class StackObject: + __slots__ = ("name", "obtype", "doc") + name: str + obtype: type[Any] | tuple[type[Any], ...] + doc: str + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... + +pyint: StackObject +pylong: StackObject +pyinteger_or_bool: StackObject +pybool: StackObject +pyfloat: StackObject +pybytes_or_str: StackObject +pystring: StackObject +pybytes: StackObject +pyunicode: StackObject +pynone: StackObject +pytuple: StackObject +pylist: StackObject +pydict: StackObject +pyset: StackObject +pyfrozenset: StackObject +anyobject: StackObject +markobject: StackObject +stackslice: StackObject + +class OpcodeInfo: + __slots__ = ("name", "code", "arg", "stack_before", "stack_after", "proto", "doc") + name: str + code: str + arg: ArgumentDescriptor | None + stack_before: list[StackObject] + stack_after: list[StackObject] + proto: int + doc: str + def __init__( + self, + name: str, + code: str, + arg: ArgumentDescriptor | None, + stack_before: list[StackObject], + stack_after: list[StackObject], + proto: int, + doc: str, + ) -> None: ... + +opcodes: list[OpcodeInfo] + +def genops(pickle: bytes | bytearray | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ... +def optimize(p: bytes | bytearray | IO[bytes]) -> bytes: ... +def dis( + pickle: bytes | bytearray | IO[bytes], + out: IO[str] | None = None, + memo: MutableMapping[int, Any] | None = None, + indentlevel: int = 4, + annotate: int = 0, +) -> None: ... diff --git a/stdlib/pipes.pyi b/stdlib/pipes.pyi new file mode 100644 index 000000000000..fe680bfddf5f --- /dev/null +++ b/stdlib/pipes.pyi @@ -0,0 +1,16 @@ +import os + +__all__ = ["Template"] + +class Template: + def reset(self) -> None: ... + def clone(self) -> Template: ... + def debug(self, flag: bool) -> None: ... + def append(self, cmd: str, kind: str) -> None: ... + def prepend(self, cmd: str, kind: str) -> None: ... + def open(self, file: str, rw: str) -> os._wrap_close: ... + def copy(self, infile: str, outfile: str) -> int: ... + +# Not documented, but widely used. +# Documented as shlex.quote since 3.3. +def quote(s: str) -> str: ... diff --git a/stdlib/pkgutil.pyi b/stdlib/pkgutil.pyi new file mode 100644 index 000000000000..6fdb01e728f4 --- /dev/null +++ b/stdlib/pkgutil.pyi @@ -0,0 +1,60 @@ +import sys +from _typeshed import StrOrBytesPath, SupportsRead +from _typeshed.importlib import LoaderProtocol, MetaPathFinderProtocol, PathEntryFinderProtocol +from collections.abc import Callable, Iterable, Iterator +from typing import IO, Any, NamedTuple, TypeVar +from typing_extensions import deprecated + +__all__ = [ + "get_importer", + "iter_importers", + "walk_packages", + "iter_modules", + "get_data", + "read_code", + "extend_path", + "ModuleInfo", +] +if sys.version_info < (3, 14): + __all__ += ["get_loader", "find_loader"] +if sys.version_info < (3, 12): + __all__ += ["ImpImporter", "ImpLoader"] + +_PathT = TypeVar("_PathT", bound=Iterable[str]) + +class ModuleInfo(NamedTuple): + module_finder: MetaPathFinderProtocol | PathEntryFinderProtocol + name: str + ispkg: bool + +def extend_path(path: _PathT, name: str) -> _PathT: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.") + class ImpImporter: + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... + + @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.") + class ImpLoader: + def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... + +if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def find_loader(fullname: str) -> LoaderProtocol | None: ... + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def get_loader(module_or_name: str) -> LoaderProtocol | None: ... + +def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ... +def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ... +def iter_modules(path: Iterable[StrOrBytesPath] | None = None, prefix: str = "") -> Iterator[ModuleInfo]: ... +def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented +def walk_packages( + path: Iterable[StrOrBytesPath] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None +) -> Iterator[ModuleInfo]: ... +def get_data(package: str, resource: str) -> bytes | None: ... + +if sys.version_info >= (3, 15): + def resolve_name(name: str, *, strict: bool = False) -> Any: ... + +else: + def resolve_name(name: str) -> Any: ... diff --git a/stdlib/platform.pyi b/stdlib/platform.pyi new file mode 100644 index 000000000000..b262186a68e4 --- /dev/null +++ b/stdlib/platform.pyi @@ -0,0 +1,100 @@ +import sys +from typing import NamedTuple, type_check_only +from typing_extensions import Self, deprecated, disjoint_base + +def libc_ver(executable: str | None = None, lib: str = "", version: str = "", chunksize: int = 16384) -> tuple[str, str]: ... +def win32_ver(release: str = "", version: str = "", csd: str = "", ptype: str = "") -> tuple[str, str, str, str]: ... +def win32_edition() -> str: ... +def win32_is_iot() -> bool: ... +def mac_ver( + release: str = "", versioninfo: tuple[str, str, str] = ("", "", ""), machine: str = "" +) -> tuple[str, tuple[str, str, str], str]: ... + +if sys.version_info < (3, 15): + @deprecated("Deprecated; will be removed in Python 3.15.") + def java_ver( + release: str = "", + vendor: str = "", + vminfo: tuple[str, str, str] = ("", "", ""), + osinfo: tuple[str, str, str] = ("", "", ""), + ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... + +def system_alias(system: str, release: str, version: str) -> tuple[str, str, str]: ... +def architecture(executable: str = sys.executable, bits: str = "", linkage: str = "") -> tuple[str, str]: ... + +# This class is not exposed. It calls itself platform.uname_result_base. +# At runtime it only has 5 fields. +@type_check_only +class _uname_result_base(NamedTuple): + system: str + node: str + release: str + version: str + machine: str + # This base class doesn't have this field at runtime, but claiming it + # does is the least bad way to handle the situation. Nobody really + # sees this class anyway. See #13068 + processor: str + +# uname_result emulates a 6-field named tuple, but the processor field +# is lazily evaluated rather than being passed in to the constructor. +if sys.version_info >= (3, 12): + class uname_result(_uname_result_base): + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] + + def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... + @property + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] + +else: + @disjoint_base + class uname_result(_uname_result_base): + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] + def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... + @property + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] + +def uname() -> uname_result: ... +def system() -> str: ... +def node() -> str: ... +def release() -> str: ... +def version() -> str: ... +def machine() -> str: ... +def processor() -> str: ... +def python_implementation() -> str: ... +def python_version() -> str: ... +def python_version_tuple() -> tuple[str, str, str]: ... +def python_branch() -> str: ... +def python_revision() -> str: ... +def python_build() -> tuple[str, str]: ... +def python_compiler() -> str: ... +def platform(aliased: bool = False, terse: bool = False) -> str: ... +def freedesktop_os_release() -> dict[str, str]: ... + +if sys.version_info >= (3, 13): + class AndroidVer(NamedTuple): + release: str + api_level: int + manufacturer: str + model: str + device: str + is_emulator: bool + + class IOSVersionInfo(NamedTuple): + system: str + release: str + model: str + is_simulator: bool + + def android_ver( + release: str = "", + api_level: int = 0, + manufacturer: str = "", + model: str = "", + device: str = "", + is_emulator: bool = False, + ) -> AndroidVer: ... + def ios_ver(system: str = "", release: str = "", model: str = "", is_simulator: bool = False) -> IOSVersionInfo: ... + +if sys.version_info >= (3, 14): + def invalidate_caches() -> None: ... diff --git a/stdlib/plistlib.pyi b/stdlib/plistlib.pyi new file mode 100644 index 000000000000..dc3247ee47fb --- /dev/null +++ b/stdlib/plistlib.pyi @@ -0,0 +1,84 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping, MutableMapping +from datetime import datetime +from enum import Enum +from typing import IO, Any, Final +from typing_extensions import Self + +__all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] + +class PlistFormat(Enum): + FMT_XML = 1 + FMT_BINARY = 2 + +FMT_XML: Final = PlistFormat.FMT_XML +FMT_BINARY: Final = PlistFormat.FMT_BINARY +if sys.version_info >= (3, 13): + def load( + fp: IO[bytes], + *, + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, + ) -> Any: ... + def loads( + value: ReadableBuffer | str, + *, + fmt: PlistFormat | None = None, + dict_type: type[MutableMapping[str, Any]] = ..., + aware_datetime: bool = False, + ) -> Any: ... + +else: + def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... + def loads( + value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ... + ) -> Any: ... + +if sys.version_info >= (3, 13): + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + aware_datetime: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + aware_datetime: bool = False, + ) -> bytes: ... + +else: + def dump( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + fp: IO[bytes], + *, + fmt: PlistFormat = ..., + sort_keys: bool = True, + skipkeys: bool = False, + ) -> None: ... + def dumps( + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, + *, + fmt: PlistFormat = ..., + skipkeys: bool = False, + sort_keys: bool = True, + ) -> bytes: ... + +class UID: + data: int + def __init__(self, data: int) -> None: ... + def __index__(self) -> int: ... + def __reduce__(self) -> tuple[type[Self], tuple[int]]: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class InvalidFileException(ValueError): + def __init__(self, message: str = "Invalid file") -> None: ... diff --git a/stdlib/poplib.pyi b/stdlib/poplib.pyi new file mode 100644 index 000000000000..59d95c0882f1 --- /dev/null +++ b/stdlib/poplib.pyi @@ -0,0 +1,93 @@ +import socket +import ssl +import sys +from _typeshed import StrOrBytesPath +from builtins import list as _list # conflicts with a method named "list" +from re import Pattern +from typing import Any, BinaryIO, Final, TypeAlias, overload +from typing_extensions import Never, deprecated + +__all__ = ["POP3", "error_proto", "POP3_SSL"] + +_LongResp: TypeAlias = tuple[bytes, list[bytes], int] + +class error_proto(Exception): ... + +POP3_PORT: Final = 110 +POP3_SSL_PORT: Final = 995 +CR: Final = b"\r" +LF: Final = b"\n" +CRLF: Final = b"\r\n" +HAVE_SSL: Final[bool] + +class POP3: + encoding: str + host: str + port: int + sock: socket.socket + file: BinaryIO + welcome: bytes + def __init__(self, host: str, port: int = 110, timeout: float = ...) -> None: ... + def getwelcome(self) -> bytes: ... + def set_debuglevel(self, level: int) -> None: ... + def user(self, user: str) -> bytes: ... + def pass_(self, pswd: str) -> bytes: ... + def stat(self) -> tuple[int, int]: ... + def list(self, which: Any | None = None) -> _LongResp: ... + def retr(self, which: Any) -> _LongResp: ... + def dele(self, which: Any) -> bytes: ... + def noop(self) -> bytes: ... + def rset(self) -> bytes: ... + def quit(self) -> bytes: ... + def close(self) -> None: ... + def rpop(self, user: str) -> bytes: ... + timestamp: Pattern[str] + def apop(self, user: str, password: str) -> bytes: ... + def top(self, which: Any, howmuch: int) -> _LongResp: ... + + @overload + def uidl(self) -> _LongResp: ... + @overload + def uidl(self, which: Any) -> bytes: ... + + def utf8(self) -> bytes: ... + def capa(self) -> dict[str, _list[str]]: ... + def stls(self, context: ssl.SSLContext | None = None) -> bytes: ... + +class POP3_SSL(POP3): + if sys.version_info >= (3, 12): + def __init__( + self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None + ) -> None: ... + def stls(self, context: Any = None) -> Never: ... + else: + @overload + def __init__( + self, + host: str, + port: int = 995, + keyfile: None = None, + certfile: None = None, + timeout: float = ..., + context: ssl.SSLContext | None = None, + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str, + port: int = 995, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + timeout: float = ..., + context: None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + # "context" is actually the last argument, + # but that breaks LSP and it doesn't really matter because all the arguments are ignored + def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> Never: ... diff --git a/stdlib/posix.pyi b/stdlib/posix.pyi new file mode 100644 index 000000000000..36bb5be18e88 --- /dev/null +++ b/stdlib/posix.pyi @@ -0,0 +1,427 @@ +import sys + +if sys.platform != "win32": + # Actually defined here, but defining in os allows sharing code with windows + from os import ( + CLD_CONTINUED as CLD_CONTINUED, + CLD_DUMPED as CLD_DUMPED, + CLD_EXITED as CLD_EXITED, + CLD_KILLED as CLD_KILLED, + CLD_STOPPED as CLD_STOPPED, + CLD_TRAPPED as CLD_TRAPPED, + EX_CANTCREAT as EX_CANTCREAT, + EX_CONFIG as EX_CONFIG, + EX_DATAERR as EX_DATAERR, + EX_IOERR as EX_IOERR, + EX_NOHOST as EX_NOHOST, + EX_NOINPUT as EX_NOINPUT, + EX_NOPERM as EX_NOPERM, + EX_NOUSER as EX_NOUSER, + EX_OK as EX_OK, + EX_OSERR as EX_OSERR, + EX_OSFILE as EX_OSFILE, + EX_PROTOCOL as EX_PROTOCOL, + EX_SOFTWARE as EX_SOFTWARE, + EX_TEMPFAIL as EX_TEMPFAIL, + EX_UNAVAILABLE as EX_UNAVAILABLE, + EX_USAGE as EX_USAGE, + F_LOCK as F_LOCK, + F_OK as F_OK, + F_TEST as F_TEST, + F_TLOCK as F_TLOCK, + F_ULOCK as F_ULOCK, + NGROUPS_MAX as NGROUPS_MAX, + O_ACCMODE as O_ACCMODE, + O_APPEND as O_APPEND, + O_ASYNC as O_ASYNC, + O_CLOEXEC as O_CLOEXEC, + O_CREAT as O_CREAT, + O_DIRECTORY as O_DIRECTORY, + O_DSYNC as O_DSYNC, + O_EXCL as O_EXCL, + O_FSYNC as O_FSYNC, + O_NDELAY as O_NDELAY, + O_NOCTTY as O_NOCTTY, + O_NOFOLLOW as O_NOFOLLOW, + O_NONBLOCK as O_NONBLOCK, + O_RDONLY as O_RDONLY, + O_RDWR as O_RDWR, + O_SYNC as O_SYNC, + O_TRUNC as O_TRUNC, + O_WRONLY as O_WRONLY, + P_ALL as P_ALL, + P_PGID as P_PGID, + P_PID as P_PID, + POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, + POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2, + POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN, + PRIO_PGRP as PRIO_PGRP, + PRIO_PROCESS as PRIO_PROCESS, + PRIO_USER as PRIO_USER, + R_OK as R_OK, + RTLD_GLOBAL as RTLD_GLOBAL, + RTLD_LAZY as RTLD_LAZY, + RTLD_LOCAL as RTLD_LOCAL, + RTLD_NODELETE as RTLD_NODELETE, + RTLD_NOLOAD as RTLD_NOLOAD, + RTLD_NOW as RTLD_NOW, + SCHED_FIFO as SCHED_FIFO, + SCHED_OTHER as SCHED_OTHER, + SCHED_RR as SCHED_RR, + SEEK_DATA as SEEK_DATA, + SEEK_HOLE as SEEK_HOLE, + ST_NOSUID as ST_NOSUID, + ST_RDONLY as ST_RDONLY, + TMP_MAX as TMP_MAX, + W_OK as W_OK, + WCONTINUED as WCONTINUED, + WCOREDUMP as WCOREDUMP, + WEXITED as WEXITED, + WEXITSTATUS as WEXITSTATUS, + WIFCONTINUED as WIFCONTINUED, + WIFEXITED as WIFEXITED, + WIFSIGNALED as WIFSIGNALED, + WIFSTOPPED as WIFSTOPPED, + WNOHANG as WNOHANG, + WNOWAIT as WNOWAIT, + WSTOPPED as WSTOPPED, + WSTOPSIG as WSTOPSIG, + WTERMSIG as WTERMSIG, + WUNTRACED as WUNTRACED, + X_OK as X_OK, + DirEntry as DirEntry, + _exit as _exit, + abort as abort, + access as access, + chdir as chdir, + chmod as chmod, + chown as chown, + chroot as chroot, + close as close, + closerange as closerange, + confstr as confstr, + confstr_names as confstr_names, + cpu_count as cpu_count, + ctermid as ctermid, + device_encoding as device_encoding, + dup as dup, + dup2 as dup2, + error as error, + execv as execv, + execve as execve, + fchdir as fchdir, + fchmod as fchmod, + fchown as fchown, + fork as fork, + forkpty as forkpty, + fpathconf as fpathconf, + fspath as fspath, + fstat as fstat, + fstatvfs as fstatvfs, + fsync as fsync, + ftruncate as ftruncate, + get_blocking as get_blocking, + get_inheritable as get_inheritable, + get_terminal_size as get_terminal_size, + getcwd as getcwd, + getcwdb as getcwdb, + getegid as getegid, + geteuid as geteuid, + getgid as getgid, + getgrouplist as getgrouplist, + getgroups as getgroups, + getloadavg as getloadavg, + getlogin as getlogin, + getpgid as getpgid, + getpgrp as getpgrp, + getpid as getpid, + getppid as getppid, + getpriority as getpriority, + getsid as getsid, + getuid as getuid, + initgroups as initgroups, + isatty as isatty, + kill as kill, + killpg as killpg, + lchown as lchown, + link as link, + listdir as listdir, + lockf as lockf, + lseek as lseek, + lstat as lstat, + major as major, + makedev as makedev, + minor as minor, + mkdir as mkdir, + mkfifo as mkfifo, + mknod as mknod, + nice as nice, + open as open, + openpty as openpty, + pathconf as pathconf, + pathconf_names as pathconf_names, + pipe as pipe, + posix_spawn as posix_spawn, + posix_spawnp as posix_spawnp, + pread as pread, + preadv as preadv, + putenv as putenv, + pwrite as pwrite, + pwritev as pwritev, + read as read, + readlink as readlink, + readv as readv, + register_at_fork as register_at_fork, + remove as remove, + rename as rename, + replace as replace, + rmdir as rmdir, + scandir as scandir, + sched_get_priority_max as sched_get_priority_max, + sched_get_priority_min as sched_get_priority_min, + sched_param as sched_param, + sched_yield as sched_yield, + sendfile as sendfile, + set_blocking as set_blocking, + set_inheritable as set_inheritable, + setegid as setegid, + seteuid as seteuid, + setgid as setgid, + setgroups as setgroups, + setpgid as setpgid, + setpgrp as setpgrp, + setpriority as setpriority, + setregid as setregid, + setreuid as setreuid, + setsid as setsid, + setuid as setuid, + stat as stat, + stat_result as stat_result, + statvfs as statvfs, + statvfs_result as statvfs_result, + strerror as strerror, + symlink as symlink, + sync as sync, + sysconf as sysconf, + sysconf_names as sysconf_names, + system as system, + tcgetpgrp as tcgetpgrp, + tcsetpgrp as tcsetpgrp, + terminal_size as terminal_size, + times as times, + times_result as times_result, + truncate as truncate, + ttyname as ttyname, + umask as umask, + uname as uname, + uname_result as uname_result, + unlink as unlink, + unsetenv as unsetenv, + urandom as urandom, + utime as utime, + wait as wait, + wait3 as wait3, + wait4 as wait4, + waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, + write as write, + writev as writev, + ) + + if sys.version_info >= (3, 11): + from os import login_tty as login_tty + + if sys.version_info >= (3, 13): + from os import grantpt as grantpt, posix_openpt as posix_openpt, ptsname as ptsname, unlockpt as unlockpt + + if sys.version_info >= (3, 13) and sys.platform == "linux": + from os import ( + POSIX_SPAWN_CLOSEFROM as POSIX_SPAWN_CLOSEFROM, + TFD_CLOEXEC as TFD_CLOEXEC, + TFD_NONBLOCK as TFD_NONBLOCK, + TFD_TIMER_ABSTIME as TFD_TIMER_ABSTIME, + TFD_TIMER_CANCEL_ON_SET as TFD_TIMER_CANCEL_ON_SET, + timerfd_create as timerfd_create, + timerfd_gettime as timerfd_gettime, + timerfd_gettime_ns as timerfd_gettime_ns, + timerfd_settime as timerfd_settime, + timerfd_settime_ns as timerfd_settime_ns, + ) + + if sys.version_info >= (3, 14): + from os import readinto as readinto + + if sys.version_info >= (3, 14) and sys.platform == "linux": + from os import SCHED_DEADLINE as SCHED_DEADLINE, SCHED_NORMAL as SCHED_NORMAL + + if sys.platform != "linux": + from os import O_EXLOCK as O_EXLOCK, O_SHLOCK as O_SHLOCK, chflags as chflags, lchflags as lchflags, lchmod as lchmod + + if sys.platform != "linux" and sys.platform != "darwin": + from os import EX_NOTFOUND as EX_NOTFOUND, SCHED_SPORADIC as SCHED_SPORADIC + + if sys.platform != "linux" and sys.version_info >= (3, 13): + from os import O_EXEC as O_EXEC, O_SEARCH as O_SEARCH + + if sys.version_info >= (3, 15): + from os import NODEV as NODEV + + if sys.version_info >= (3, 15) and sys.platform == "linux": + from os import ( + AT_NO_AUTOMOUNT as AT_NO_AUTOMOUNT, + AT_STATX_DONT_SYNC as AT_STATX_DONT_SYNC, + AT_STATX_FORCE_SYNC as AT_STATX_FORCE_SYNC, + AT_STATX_SYNC_AS_STAT as AT_STATX_SYNC_AS_STAT, + STATX_ATIME as STATX_ATIME, + STATX_BASIC_STATS as STATX_BASIC_STATS, + STATX_BLOCKS as STATX_BLOCKS, + STATX_BTIME as STATX_BTIME, + STATX_CTIME as STATX_CTIME, + STATX_DIOALIGN as STATX_DIOALIGN, + STATX_GID as STATX_GID, + STATX_INO as STATX_INO, + STATX_MNT_ID as STATX_MNT_ID, + STATX_MNT_ID_UNIQUE as STATX_MNT_ID_UNIQUE, + STATX_MODE as STATX_MODE, + STATX_MTIME as STATX_MTIME, + STATX_NLINK as STATX_NLINK, + STATX_SIZE as STATX_SIZE, + STATX_TYPE as STATX_TYPE, + STATX_UID as STATX_UID, + _clearenv as _clearenv, + statx as statx, + statx_result as statx_result, + ) + + if sys.platform != "darwin": + from os import ( + POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED, + POSIX_FADV_NOREUSE as POSIX_FADV_NOREUSE, + POSIX_FADV_NORMAL as POSIX_FADV_NORMAL, + POSIX_FADV_RANDOM as POSIX_FADV_RANDOM, + POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL, + POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED, + RWF_APPEND as RWF_APPEND, + RWF_DSYNC as RWF_DSYNC, + RWF_HIPRI as RWF_HIPRI, + RWF_NOWAIT as RWF_NOWAIT, + RWF_SYNC as RWF_SYNC, + ST_APPEND as ST_APPEND, + ST_MANDLOCK as ST_MANDLOCK, + ST_NOATIME as ST_NOATIME, + ST_NODEV as ST_NODEV, + ST_NODIRATIME as ST_NODIRATIME, + ST_NOEXEC as ST_NOEXEC, + ST_RELATIME as ST_RELATIME, + ST_SYNCHRONOUS as ST_SYNCHRONOUS, + ST_WRITE as ST_WRITE, + fdatasync as fdatasync, + getresgid as getresgid, + getresuid as getresuid, + pipe2 as pipe2, + posix_fadvise as posix_fadvise, + posix_fallocate as posix_fallocate, + sched_getaffinity as sched_getaffinity, + sched_getparam as sched_getparam, + sched_getscheduler as sched_getscheduler, + sched_rr_get_interval as sched_rr_get_interval, + sched_setaffinity as sched_setaffinity, + sched_setparam as sched_setparam, + sched_setscheduler as sched_setscheduler, + setresgid as setresgid, + setresuid as setresuid, + ) + + if sys.platform != "darwin" or sys.version_info >= (3, 13): + from os import waitid as waitid, waitid_result as waitid_result + + if sys.platform == "linux": + from os import ( + EFD_CLOEXEC as EFD_CLOEXEC, + EFD_NONBLOCK as EFD_NONBLOCK, + EFD_SEMAPHORE as EFD_SEMAPHORE, + GRND_NONBLOCK as GRND_NONBLOCK, + GRND_RANDOM as GRND_RANDOM, + MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, + MFD_CLOEXEC as MFD_CLOEXEC, + MFD_HUGE_1GB as MFD_HUGE_1GB, + MFD_HUGE_1MB as MFD_HUGE_1MB, + MFD_HUGE_2GB as MFD_HUGE_2GB, + MFD_HUGE_2MB as MFD_HUGE_2MB, + MFD_HUGE_8MB as MFD_HUGE_8MB, + MFD_HUGE_16GB as MFD_HUGE_16GB, + MFD_HUGE_16MB as MFD_HUGE_16MB, + MFD_HUGE_32MB as MFD_HUGE_32MB, + MFD_HUGE_64KB as MFD_HUGE_64KB, + MFD_HUGE_256MB as MFD_HUGE_256MB, + MFD_HUGE_512KB as MFD_HUGE_512KB, + MFD_HUGE_512MB as MFD_HUGE_512MB, + MFD_HUGE_MASK as MFD_HUGE_MASK, + MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, + MFD_HUGETLB as MFD_HUGETLB, + O_DIRECT as O_DIRECT, + O_LARGEFILE as O_LARGEFILE, + O_NOATIME as O_NOATIME, + O_PATH as O_PATH, + O_RSYNC as O_RSYNC, + O_TMPFILE as O_TMPFILE, + P_PIDFD as P_PIDFD, + RTLD_DEEPBIND as RTLD_DEEPBIND, + SCHED_BATCH as SCHED_BATCH, + SCHED_IDLE as SCHED_IDLE, + SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK, + SPLICE_F_MORE as SPLICE_F_MORE, + SPLICE_F_MOVE as SPLICE_F_MOVE, + SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, + XATTR_CREATE as XATTR_CREATE, + XATTR_REPLACE as XATTR_REPLACE, + XATTR_SIZE_MAX as XATTR_SIZE_MAX, + copy_file_range as copy_file_range, + eventfd as eventfd, + eventfd_read as eventfd_read, + eventfd_write as eventfd_write, + getrandom as getrandom, + getxattr as getxattr, + listxattr as listxattr, + memfd_create as memfd_create, + pidfd_open as pidfd_open, + removexattr as removexattr, + setxattr as setxattr, + splice as splice, + ) + + if sys.version_info >= (3, 12): + from os import ( + CLONE_FILES as CLONE_FILES, + CLONE_FS as CLONE_FS, + CLONE_NEWCGROUP as CLONE_NEWCGROUP, + CLONE_NEWIPC as CLONE_NEWIPC, + CLONE_NEWNET as CLONE_NEWNET, + CLONE_NEWNS as CLONE_NEWNS, + CLONE_NEWPID as CLONE_NEWPID, + CLONE_NEWTIME as CLONE_NEWTIME, + CLONE_NEWUSER as CLONE_NEWUSER, + CLONE_NEWUTS as CLONE_NEWUTS, + CLONE_SIGHAND as CLONE_SIGHAND, + CLONE_SYSVSEM as CLONE_SYSVSEM, + CLONE_THREAD as CLONE_THREAD, + CLONE_VM as CLONE_VM, + PIDFD_NONBLOCK as PIDFD_NONBLOCK, + setns as setns, + unshare as unshare, + ) + + if sys.platform == "darwin": + from os import O_EVTONLY as O_EVTONLY, O_NOFOLLOW_ANY as O_NOFOLLOW_ANY, O_SYMLINK as O_SYMLINK + + if sys.version_info >= (3, 12): + from os import ( + PRIO_DARWIN_BG as PRIO_DARWIN_BG, + PRIO_DARWIN_NONUI as PRIO_DARWIN_NONUI, + PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS, + PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD, + ) + + # Not same as os.environ or os.environb + # Because of this variable, we can't do "from posix import *" in os/__init__.pyi + environ: dict[bytes, bytes] diff --git a/stdlib/posixpath.pyi b/stdlib/posixpath.pyi new file mode 100644 index 000000000000..b4068629b698 --- /dev/null +++ b/stdlib/posixpath.pyi @@ -0,0 +1,230 @@ +import sys +from _typeshed import AnyOrLiteralStr, BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath +from collections.abc import Iterable +from genericpath import ( + ALLOW_MISSING as ALLOW_MISSING, + _AllowMissingType, + commonprefix as commonprefix, + exists as exists, + getatime as getatime, + getctime as getctime, + getmtime as getmtime, + getsize as getsize, + isdir as isdir, + isfile as isfile, + samefile as samefile, + sameopenfile as sameopenfile, + samestat as samestat, +) + +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST + +if sys.version_info >= (3, 13): + from genericpath import isdevdrive as isdevdrive +from os import PathLike +from typing import AnyStr, overload +from typing_extensions import LiteralString + +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "samefile", + "sameopenfile", + "samestat", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "commonpath", +] +__all__ += ["ALLOW_MISSING"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] +if sys.version_info >= (3, 12): + __all__ += ["isjunction", "splitroot"] +if sys.version_info >= (3, 13): + __all__ += ["isdevdrive"] + +supports_unicode_filenames: bool +# aliases (also in os) +curdir: LiteralString +pardir: LiteralString +sep: LiteralString +altsep: LiteralString | None +extsep: LiteralString +pathsep: LiteralString +defpath: LiteralString +devnull: LiteralString + +# Overloads are necessary to work around python/mypy#17952 & python/mypy#11880 +@overload +def abspath(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def abspath(path: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 15): + @overload + def basename(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def basename(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + +@overload +def expanduser(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def expanduser(path: AnyStr) -> AnyStr: ... + +@overload +def expandvars(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def expandvars(path: AnyStr) -> AnyStr: ... + +if sys.version_info >= (3, 15): + @overload + def normcase(s: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def normcase(s: PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + +@overload +def normpath(path: PathLike[AnyStr]) -> AnyStr: ... +@overload +def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + +@overload +def commonpath(paths: Iterable[LiteralString]) -> LiteralString: ... +@overload +def commonpath(paths: Iterable[StrPath]) -> str: ... +@overload +def commonpath(paths: Iterable[BytesPath]) -> bytes: ... + +# First parameter is not actually pos-only before Python 3.15, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in ntpath.join() +@overload +def join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: ... +@overload +def join(a: StrPath, /, *paths: StrPath) -> str: ... +@overload +def join(a: BytesPath, /, *paths: BytesPath) -> bytes: ... + +if sys.version_info >= (3, 15): + @overload + def realpath(filename: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(filename: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... +else: + @overload + def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + +@overload +def relpath(path: LiteralString, start: LiteralString | None = None) -> LiteralString: ... +@overload +def relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ... +@overload +def relpath(path: StrPath, start: StrPath | None = None) -> str: ... + +if sys.version_info >= (3, 15): + @overload + def split(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + @overload + def splitext(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + def isabs(s: StrOrBytesPath, /) -> bool: ... + +else: + def isabs(s: StrOrBytesPath) -> bool: ... + +def islink(path: FileDescriptorOrPath) -> bool: ... +def ismount(path: FileDescriptorOrPath) -> bool: ... +def lexists(path: FileDescriptorOrPath) -> bool: ... + +if sys.version_info >= (3, 12): + def isjunction(path: StrOrBytesPath) -> bool: ... + + if sys.version_info >= (3, 15): + @overload + def splitroot(path: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(path: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr, AnyStr]: ... + else: + @overload + def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ... diff --git a/stdlib/pprint.pyi b/stdlib/pprint.pyi new file mode 100644 index 000000000000..dd2902021657 --- /dev/null +++ b/stdlib/pprint.pyi @@ -0,0 +1,170 @@ +import sys +from _typeshed import SupportsWrite +from collections import deque +from typing import IO + +__all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] + +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. + def pformat( + object: object, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> str: ... + +else: + def pformat( + object: object, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> str: ... + +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. + def pp( + object: object, + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + expand: bool = False, + sort_dicts: bool = False, + underscore_numbers: bool = False, + ) -> None: ... + +else: + def pp( + object: object, + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + sort_dicts: bool = False, + underscore_numbers: bool = False, + ) -> None: ... + +if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. + def pprint( + object: object, + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> None: ... + +else: + def pprint( + object: object, + stream: IO[str] | None = None, + indent: int = 1, + width: int = 80, + depth: int | None = None, + *, + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> None: ... + +def isreadable(object: object) -> bool: ... +def isrecursive(object: object) -> bool: ... +def saferepr(object: object) -> str: ... + +class PrettyPrinter: + if sys.version_info >= (3, 15): + # The `expand` parameter was added in Python 3.15. + def __init__( + self, + indent: int = 1, + width: int = 80, + depth: int | None = None, + stream: IO[str] | None = None, + *, + compact: bool = False, + expand: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> None: ... + else: + def __init__( + self, + indent: int = 1, + width: int = 80, + depth: int | None = None, + stream: IO[str] | None = None, + *, + compact: bool = False, + sort_dicts: bool = True, + underscore_numbers: bool = False, + ) -> None: ... + + def pformat(self, object: object) -> str: ... + def pprint(self, object: object) -> None: ... + def isreadable(self, object: object) -> bool: ... + def isrecursive(self, object: object) -> bool: ... + def format(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... + def _format( + self, object: object, stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_dict( + self, + object: dict[object, object], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _pprint_list( + self, object: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_tuple( + self, + object: tuple[object, ...], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _pprint_set( + self, object: set[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _pprint_deque( + self, object: deque[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _format_dict_items( + self, + items: list[tuple[object, object]], + stream: SupportsWrite[str], + indent: int, + allowance: int, + context: dict[int, int], + level: int, + ) -> None: ... + def _format_items( + self, items: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int + ) -> None: ... + def _repr(self, object: object, context: dict[int, int], level: int) -> str: ... + def _safe_repr(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... diff --git a/stdlib/profile.pyi b/stdlib/profile.pyi new file mode 100644 index 000000000000..06ce9a0e44c8 --- /dev/null +++ b/stdlib/profile.pyi @@ -0,0 +1,31 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Mapping +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self + +__all__ = ["run", "runctx", "Profile"] + +def run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ... +def runctx( + statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1 +) -> None: ... + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_Label: TypeAlias = tuple[str, int, str] + +class Profile: + bias: int + stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented + def __init__(self, timer: Callable[[], float] | None = None, bias: int | None = None) -> None: ... + def set_cmd(self, cmd: str) -> None: ... + def simulate_call(self, name: str) -> None: ... + def simulate_cmd_complete(self) -> None: ... + def print_stats(self, sort: str | int = -1) -> None: ... + def dump_stats(self, file: StrOrBytesPath) -> None: ... + def create_stats(self) -> None: ... + def snapshot_stats(self) -> None: ... + def run(self, cmd: str) -> Self: ... + def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ... + def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def calibrate(self, m: int, verbose: int = 0) -> float: ... diff --git a/stdlib/profiling/__init__.pyi b/stdlib/profiling/__init__.pyi new file mode 100644 index 000000000000..435f5a6cc66c --- /dev/null +++ b/stdlib/profiling/__init__.pyi @@ -0,0 +1,3 @@ +from . import sampling as sampling, tracing as tracing + +__all__ = ("tracing", "sampling") diff --git a/stdlib/profiling/sampling/__init__.pyi b/stdlib/profiling/sampling/__init__.pyi new file mode 100644 index 000000000000..1f8b3f7d98fe --- /dev/null +++ b/stdlib/profiling/sampling/__init__.pyi @@ -0,0 +1,17 @@ +from .collector import Collector as Collector +from .gecko_collector import GeckoCollector as GeckoCollector +from .heatmap_collector import HeatmapCollector as HeatmapCollector +from .jsonl_collector import JsonlCollector as JsonlCollector +from .pstats_collector import PstatsCollector as PstatsCollector +from .stack_collector import CollapsedStackCollector as CollapsedStackCollector +from .string_table import StringTable as StringTable + +__all__ = ( + "Collector", + "PstatsCollector", + "CollapsedStackCollector", + "HeatmapCollector", + "GeckoCollector", + "JsonlCollector", + "StringTable", +) diff --git a/stdlib/profiling/sampling/collector.pyi b/stdlib/profiling/sampling/collector.pyi new file mode 100644 index 000000000000..a72a185a2fb7 --- /dev/null +++ b/stdlib/profiling/sampling/collector.pyi @@ -0,0 +1,25 @@ +from _typeshed import StrOrBytesPath +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import ClassVar, TypeAlias + +from _remote_debugging import AwaitedInfo, FrameInfo, InterpreterInfo, LocationInfo + +_Location: TypeAlias = int | tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = FrameInfo | tuple[str, _Location, str, int | None] +_Timestamps: TypeAlias = Sequence[int] | None + +def normalize_location(location: _Location) -> tuple[int, int, int, int]: ... +def extract_lineno(location: _Location) -> int: ... +def filter_internal_frames(frames: Sequence[_Frame]) -> list[_Frame]: ... +def iter_async_frames(awaited_info_list: Sequence[AwaitedInfo]) -> object: ... + +class Collector(ABC): + aggregating: ClassVar[bool] # undocumented + @abstractmethod + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def collect_failed_sample(self) -> None: ... + @abstractmethod + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/stdlib/profiling/sampling/gecko_collector.pyi b/stdlib/profiling/sampling/gecko_collector.pyi new file mode 100644 index 000000000000..666fd42c3ea5 --- /dev/null +++ b/stdlib/profiling/sampling/gecko_collector.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath +from collections.abc import Generator, Sequence +from tempfile import TemporaryDirectory +from typing import Any, ClassVar, Final, TypedDict, type_check_only + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +@type_check_only +class _GeckoCategory(TypedDict): + name: str + color: str + subcategories: list[str] + +THREAD_STATUS_HAS_GIL: Final[int] +THREAD_STATUS_ON_CPU: Final[int] +THREAD_STATUS_UNKNOWN: Final[int] +THREAD_STATUS_GIL_REQUESTED: Final[int] +THREAD_STATUS_HAS_EXCEPTION: Final[int] +THREAD_STATUS_MAIN_THREAD: Final[int] + +GECKO_CATEGORIES: Final[list[_GeckoCategory]] + +CATEGORY_OTHER: Final = 0 +CATEGORY_PYTHON: Final = 1 +CATEGORY_NATIVE: Final = 2 +CATEGORY_GC: Final = 3 +CATEGORY_GIL: Final = 4 +CATEGORY_CPU: Final = 5 +CATEGORY_CODE_TYPE: Final = 6 +CATEGORY_OPCODES: Final = 7 +CATEGORY_EXCEPTION: Final = 8 + +DEFAULT_SUBCATEGORY: Final = 0 + +GECKO_FORMAT_VERSION: Final = 32 +GECKO_PREPROCESSED_VERSION: Final = 57 + +RESOURCE_TYPE_LIBRARY: Final = 1 + +FRAME_ADDRESS_NONE: Final = -1 +FRAME_INLINE_DEPTH_ROOT: Final = 0 + +PROCESS_TYPE_MAIN: Final = 0 +STACKWALK_DISABLED: Final = 0 + +DEFAULT_SPILL_BUFFER_BYTES: Final[int] + +class SpillColumn: + path: str + buffer: bytearray + + def __init__(self, directory: StrPath, basename: StrPath, *, buffer_bytes: int | None = None) -> None: ... + # "value" accepts the same types as json.JSONEncoder.encode() + def append(self, value: Any) -> None: ... + def flush(self) -> None: ... + def iter_tokens(self) -> Generator[str]: ... + +class GeckoThreadSpill: + sample_count: int + marker_count: int + def __init__(self, directory: StrPath, tid: int) -> None: ... + def append_sample(self, stack_index: int, time_ms: float) -> None: ... + def append_marker( + self, name_idx: int, start_time: float, end_time: float, phase: int, category: int, data: dict[str, Any] + ) -> None: ... + def prepare_read(self) -> None: ... + +class GeckoCollector(Collector): + aggregating: ClassVar[bool] + + sample_interval_usec: int + skip_idle: bool + opcodes_enabled: bool + start_time: float + + global_strings: list[str] + global_string_map: dict[str, int] + + threads: dict[int, dict[str, Any]] + spill_dir: TemporaryDirectory[str] | None + exported: bool + + libs: list[Incomplete] + + sample_count: int + last_sample_time: float + interval: float + + has_gil_start: dict[Incomplete, Incomplete] + no_gil_start: dict[Incomplete, Incomplete] + on_cpu_start: dict[Incomplete, Incomplete] + off_cpu_start: dict[Incomplete, Incomplete] + python_code_start: dict[Incomplete, Incomplete] + native_code_start: dict[Incomplete, Incomplete] + gil_wait_start: dict[Incomplete, Incomplete] + exception_start: dict[Incomplete, Incomplete] + no_exception_start: dict[Incomplete, Incomplete] + + gc_start_per_thread: dict[int, float] + + initialized_threads: set[Incomplete] + + opcode_state: dict[int, tuple[Incomplete, int, int, str, str, float]] + + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, opcodes: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/stdlib/profiling/sampling/heatmap_collector.pyi b/stdlib/profiling/sampling/heatmap_collector.pyi new file mode 100644 index 000000000000..bd523bc38245 --- /dev/null +++ b/stdlib/profiling/sampling/heatmap_collector.pyi @@ -0,0 +1,24 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Timestamps + +class HeatmapCollector(Collector): + FILE_INDEX_FORMAT: str + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, output_path: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + **kwargs: object, + ) -> None: ... diff --git a/stdlib/profiling/sampling/jsonl_collector.pyi b/stdlib/profiling/sampling/jsonl_collector.pyi new file mode 100644 index 000000000000..3bdc4b81c01d --- /dev/null +++ b/stdlib/profiling/sampling/jsonl_collector.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import _Frame, _Timestamps +from .stack_collector import StackTraceCollector + +class JsonlCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, mode: int | None = None) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], _thread_id: int, weight: int = 1) -> None: ... diff --git a/stdlib/profiling/sampling/pstats_collector.pyi b/stdlib/profiling/sampling/pstats_collector.pyi new file mode 100644 index 000000000000..178d55a7af8e --- /dev/null +++ b/stdlib/profiling/sampling/pstats_collector.pyi @@ -0,0 +1,17 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +class PstatsCollector(Collector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def create_stats(self) -> None: ... + def print_stats( + self, sort: int = -1, limit: int | None = None, show_summary: bool = True, mode: int | None = None + ) -> None: ... diff --git a/stdlib/profiling/sampling/stack_collector.pyi b/stdlib/profiling/sampling/stack_collector.pyi new file mode 100644 index 000000000000..0788e08295ad --- /dev/null +++ b/stdlib/profiling/sampling/stack_collector.pyi @@ -0,0 +1,39 @@ +from _typeshed import StrOrBytesPath +from abc import ABCMeta +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Timestamps + +class StackTraceCollector(Collector, metaclass=ABCMeta): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class CollapsedStackCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + +class FlamegraphCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + mode: int | None = None, + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class DiffFlamegraphCollector(FlamegraphCollector): + def __init__(self, sample_interval_usec: int, *, baseline_binary_path: StrOrBytesPath, skip_idle: bool = False) -> None: ... diff --git a/stdlib/profiling/sampling/string_table.pyi b/stdlib/profiling/sampling/string_table.pyi new file mode 100644 index 000000000000..cb71e82ec036 --- /dev/null +++ b/stdlib/profiling/sampling/string_table.pyi @@ -0,0 +1,5 @@ +class StringTable: + def intern(self, string: object) -> int: ... + def get_string(self, index: int) -> str: ... + def get_strings(self) -> list[str]: ... + def __len__(self) -> int: ... diff --git a/stdlib/profiling/tracing.pyi b/stdlib/profiling/tracing.pyi new file mode 100644 index 000000000000..af4ab508406a --- /dev/null +++ b/stdlib/profiling/tracing.pyi @@ -0,0 +1,9 @@ +from cProfile import Profile as Profile, run as run, runctx as runctx +from types import CodeType +from typing import TypeAlias + +__all__ = ("run", "runctx", "Profile") + +_Label: TypeAlias = tuple[str, int, str] + +def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/stdlib/pstats.pyi b/stdlib/pstats.pyi new file mode 100644 index 000000000000..19eb683df166 --- /dev/null +++ b/stdlib/pstats.pyi @@ -0,0 +1,96 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterable +from cProfile import Profile as _cProfile +from dataclasses import dataclass +from profile import Profile +from typing import IO, Any, Literal, TypeAlias, overload +from typing_extensions import Self + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + from enum import Enum + +__all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] + +_Selector: TypeAlias = str | float | int + +if sys.version_info >= (3, 11): + class SortKey(StrEnum): + CALLS = "calls" + CUMULATIVE = "cumulative" + FILENAME = "filename" + LINE = "line" + NAME = "name" + NFL = "nfl" + PCALLS = "pcalls" + STDNAME = "stdname" + TIME = "time" + +else: + class SortKey(str, Enum): + CALLS = "calls" + CUMULATIVE = "cumulative" + FILENAME = "filename" + LINE = "line" + NAME = "name" + NFL = "nfl" + PCALLS = "pcalls" + STDNAME = "stdname" + TIME = "time" + +@dataclass(unsafe_hash=True) +class FunctionProfile: + ncalls: str + tottime: float + percall_tottime: float + cumtime: float + percall_cumtime: float + file_name: str + line_number: int + +@dataclass(unsafe_hash=True) +class StatsProfile: + total_tt: float + func_profiles: dict[str, FunctionProfile] + +_SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]] + +class Stats: + sort_arg_dict_default: _SortArgDict + def __init__( + self, + arg: None | str | Profile | _cProfile = None, + /, + *args: None | str | Profile | _cProfile | Self, + stream: IO[Any] | None = None, + ) -> None: ... + def init(self, arg: None | str | Profile | _cProfile) -> None: ... + def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... + def get_top_level_stats(self) -> None: ... + def add(self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... + def dump_stats(self, filename: StrOrBytesPath) -> None: ... + def get_sort_arg_defs(self) -> _SortArgDict: ... + + @overload + def sort_stats(self, field: Literal[-1, 0, 1, 2]) -> Self: ... + @overload + def sort_stats(self, *field: str) -> Self: ... + + def reverse_order(self) -> Self: ... + def strip_dirs(self) -> Self: ... + def calc_callees(self) -> None: ... + def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... + def get_stats_profile(self) -> StatsProfile: ... + def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... + def print_stats(self, *amount: _Selector) -> Self: ... + def print_callees(self, *amount: _Selector) -> Self: ... + def print_callers(self, *amount: _Selector) -> Self: ... + def print_call_heading(self, name_size: int, column_title: str) -> None: ... + if sys.version_info >= (3, 15): + def print_call_subheading(self, name_size: int) -> None: ... + + def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = "->") -> None: ... + def print_title(self) -> None: ... + def print_line(self, func: str) -> None: ... diff --git a/stdlib/pty.pyi b/stdlib/pty.pyi new file mode 100644 index 000000000000..2bb48d782de6 --- /dev/null +++ b/stdlib/pty.pyi @@ -0,0 +1,24 @@ +import sys +from collections.abc import Callable, Iterable +from typing import Final, TypeAlias +from typing_extensions import deprecated + +if sys.platform != "win32": + __all__ = ["openpty", "fork", "spawn"] + _Reader: TypeAlias = Callable[[int], bytes] + + STDIN_FILENO: Final = 0 + STDOUT_FILENO: Final = 1 + STDERR_FILENO: Final = 2 + + CHILD: Final = 0 + def openpty() -> tuple[int, int]: ... + + if sys.version_info < (3, 14): + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") + def master_open() -> tuple[int, str]: ... + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") + def slave_open(tty_name: str) -> int: ... + + def fork() -> tuple[int, int]: ... + def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... diff --git a/stdlib/pwd.pyi b/stdlib/pwd.pyi new file mode 100644 index 000000000000..6a7e24f78125 --- /dev/null +++ b/stdlib/pwd.pyi @@ -0,0 +1,27 @@ +import sys +from _typeshed import structseq +from typing import Any, Final, final + +if sys.platform != "win32": + @final + class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): + __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") + + @property + def pw_name(self) -> str: ... + @property + def pw_passwd(self) -> str: ... + @property + def pw_uid(self) -> int: ... + @property + def pw_gid(self) -> int: ... + @property + def pw_gecos(self) -> str: ... + @property + def pw_dir(self) -> str: ... + @property + def pw_shell(self) -> str: ... + + def getpwall() -> list[struct_passwd]: ... + def getpwuid(uid: int, /) -> struct_passwd: ... + def getpwnam(name: str, /) -> struct_passwd: ... diff --git a/stdlib/py_compile.pyi b/stdlib/py_compile.pyi new file mode 100644 index 000000000000..e0ee67c5e93f --- /dev/null +++ b/stdlib/py_compile.pyi @@ -0,0 +1,28 @@ +import enum +from typing import AnyStr + +__all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"] + +class PyCompileError(Exception): + exc_type_name: str + exc_value: BaseException + file: str + msg: str + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = "") -> None: ... + +class PycInvalidationMode(enum.Enum): + TIMESTAMP = 1 + CHECKED_HASH = 2 + UNCHECKED_HASH = 3 + +def _get_default_invalidation_mode() -> PycInvalidationMode: ... +def compile( + file: AnyStr, + cfile: AnyStr | None = None, + dfile: AnyStr | None = None, + doraise: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + quiet: int = 0, +) -> AnyStr | None: ... +def main() -> None: ... diff --git a/stdlib/pyclbr.pyi b/stdlib/pyclbr.pyi new file mode 100644 index 000000000000..541f962d33e1 --- /dev/null +++ b/stdlib/pyclbr.pyi @@ -0,0 +1,57 @@ +from collections.abc import Mapping, Sequence + +__all__ = ["readmodule", "readmodule_ex", "Class", "Function"] + +class _Object: + module: str + name: str + file: int + lineno: int + end_lineno: int | None + parent: _Object | None + + # This is a dict at runtime, but we're typing it as Mapping to + # avoid variance issues in the subclasses + children: Mapping[str, _Object] + + def __init__( + self, module: str, name: str, file: str, lineno: int, end_lineno: int | None, parent: _Object | None + ) -> None: ... + +class Function(_Object): + is_async: bool + parent: Function | Class | None + children: dict[str, Class | Function] + + def __init__( + self, + module: str, + name: str, + file: str, + lineno: int, + parent: Function | Class | None = None, + is_async: bool = False, + *, + end_lineno: int | None = None, + ) -> None: ... + +class Class(_Object): + super: list[Class | str] | None + methods: dict[str, int] + parent: Class | None + children: dict[str, Class | Function] + + def __init__( + self, + module: str, + name: str, + super_: list[Class | str] | None, + file: str, + lineno: int, + parent: Class | None = None, + *, + end_lineno: int | None = None, + ) -> None: ... + +def readmodule(module: str, path: Sequence[str] | None = None) -> dict[str, Class]: ... +def readmodule_ex(module: str, path: Sequence[str] | None = None) -> dict[str, Class | Function | list[str]]: ... diff --git a/stdlib/pydoc.pyi b/stdlib/pydoc.pyi new file mode 100644 index 000000000000..dd9a365dff0b --- /dev/null +++ b/stdlib/pydoc.pyi @@ -0,0 +1,348 @@ +import sys +from _typeshed import OptExcInfo, StrPath, SupportsWrite, Unused +from abc import abstractmethod +from builtins import list as _list # "list" conflicts with method name +from collections.abc import Callable, Container, Mapping, MutableMapping +from reprlib import Repr +from types import MethodType, ModuleType, TracebackType +from typing import IO, Any, AnyStr, Final, Protocol, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated + +__all__ = ["help"] + +_T = TypeVar("_T") + +__author__: Final[str] +__date__: Final[str] +__version__: Final[str] +__credits__: Final[str] + +@type_check_only +class _Pager(Protocol): + def __call__(self, text: str, title: str = "") -> None: ... + +def pathdirs() -> list[str]: ... +def getdoc(object: object) -> str: ... +def splitdoc(doc: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def classname(object: object, modname: str) -> str: ... +def isdata(object: object) -> bool: ... +def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... +def cram(text: str, maxlen: int) -> str: ... +def stripid(text: str) -> str: ... +def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... +def visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: ... +def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... +@deprecated("Deprecated.") +def ispackage(path: StrPath) -> bool: ... # undocumented +def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... +def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: ... + +class ErrorDuringImport(Exception): + filename: str + exc: type[BaseException] | None + value: BaseException | None + tb: TracebackType | None + if sys.version_info >= (3, 12): + @overload + def __init__(self, filename: str, exc_info: BaseException) -> None: ... + @overload + @deprecated("A tuple value for `exc_info` parameter is deprecated since Python 3.12. Use an exception instance.") + def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... + else: + def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ... + +def importfile(path: str) -> ModuleType: ... +def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = {}) -> ModuleType | None: ... + +class Doc: + PYTHONDOCS: str + if sys.version_info >= (3, 15): + STDLIB_DIR: str + + def document(self, object: object, name: str | None = None, *args: Any) -> str: ... + def fail(self, object: object, name: str | None = None, *args: Any) -> Never: ... + @abstractmethod + def docmodule(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docclass(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docroutine(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docother(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docproperty(self, object: object, name: str | None = None, *args: Any) -> str: ... + @abstractmethod + def docdata(self, object: object, name: str | None = None, *args: Any) -> str: ... + if sys.version_info >= (3, 15): + def getdocloc(self, object: object, basedir: str | None = None) -> str | None: ... + else: + def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... + +class HTMLRepr(Repr): + def __init__(self) -> None: ... + def escape(self, text: str) -> str: ... + def repr(self, object: object) -> str: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: str, level: complex) -> str: ... + def repr_str(self, x: str, level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + def repr_unicode(self, x: AnyStr, level: complex) -> str: ... + +class HTMLDoc(Doc): + _repr_instance: HTMLRepr + repr = _repr_instance.repr # pyrefly: ignore [unknown-name] + escape = _repr_instance.escape # pyrefly: ignore [unknown-name] + def page(self, title: str, contents: str) -> str: ... + if sys.version_info >= (3, 11): + def heading(self, title: str, extras: str = "") -> str: ... + def section( + self, + title: str, + cls: str, + contents: str, + width: int = 6, + prelude: str = "", + marginalia: str | None = None, + gap: str = " ", + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str]) -> str: ... + else: + def heading(self, title: str, fgcol: str, bgcol: str, extras: str = "") -> str: ... + def section( + self, + title: str, + fgcol: str, + bgcol: str, + contents: str, + width: int = 6, + prelude: str = "", + marginalia: str | None = None, + gap: str = " ", + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = 4) -> str: ... + + def bigsection(self, title: str, *args: Any) -> str: ... + def preformat(self, text: str) -> str: ... + def grey(self, text: str) -> str: ... + def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... + def classlink(self, object: object, modname: str) -> str: ... + def modulelink(self, object: object) -> str: ... + def modpkglink(self, modpkginfo: tuple[str, str, bool, bool]) -> str: ... + def markup( + self, + text: str, + escape: Callable[[str], str] | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + ) -> str: ... + def formattree( + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None + ) -> str: ... + def docmodule(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ... + def docclass( + self, + object: object, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + *ignored: Unused, + ) -> str: ... + def formatvalue(self, object: object) -> str: ... + def docother(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ... + if sys.version_info >= (3, 11): + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, + homecls: type | None = None, + ) -> str: ... + def docproperty( + self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docdata( + self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + else: + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, + ) -> str: ... + def docproperty(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docdata(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + if sys.version_info >= (3, 11): + def parentlink(self, object: type | ModuleType, modname: str) -> str: ... + + def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = None) -> str: ... + def filelink(self, url: str, path: str) -> str: ... + +class TextRepr(Repr): + def __init__(self) -> None: ... + def repr1(self, x: object, level: complex) -> str: ... + def repr_string(self, x: str, level: complex) -> str: ... + def repr_str(self, x: str, level: complex) -> str: ... + def repr_instance(self, x: object, level: complex) -> str: ... + +class TextDoc(Doc): + _repr_instance: TextRepr + repr = _repr_instance.repr # pyrefly: ignore [unknown-name] + def bold(self, text: str) -> str: ... + def indent(self, text: str, prefix: str = " ") -> str: ... + def section(self, title: str, contents: str) -> str: ... + def formattree( + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None, prefix: str = "" + ) -> str: ... + def docclass(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ... + def formatvalue(self, object: object) -> str: ... + if sys.version_info >= (3, 11): + def docroutine( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + cl: Any | None = None, + homecls: Any | None = None, + ) -> str: ... + def docmodule(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ... + def docproperty( + self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docdata( + self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused + ) -> str: ... + def docother( + self, + object: object, + name: str | None = None, + mod: str | None = None, + parent: str | None = None, + *ignored: Unused, + maxlen: int | None = None, + doc: Any | None = None, + ) -> str: ... + else: + def docroutine(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docmodule(self, object: object, name: str | None = None, mod: Any | None = None) -> str: ... # type: ignore[override] + def docproperty(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docdata(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ... # type: ignore[override] + def docother( # type: ignore[override] + self, + object: object, + name: str | None = None, + mod: str | None = None, + parent: str | None = None, + maxlen: int | None = None, + doc: Any | None = None, + ) -> str: ... + +if sys.version_info >= (3, 13): + def pager(text: str, title: str = "") -> None: ... + +else: + def pager(text: str) -> None: ... + +def plain(text: str) -> str: ... +def describe(thing: Any) -> str: ... +def locate(path: str, forceload: bool = ...) -> object: ... + +if sys.version_info >= (3, 13): + def get_pager() -> _Pager: ... + def pipe_pager(text: str, cmd: str, title: str = "") -> None: ... + def tempfile_pager(text: str, cmd: str, title: str = "") -> None: ... + def tty_pager(text: str, title: str = "") -> None: ... + def plain_pager(text: str, title: str = "") -> None: ... + + # For backwards compatibility. + getpager = get_pager + pipepager = pipe_pager + tempfilepager = tempfile_pager + ttypager = tty_pager + plainpager = plain_pager +else: + def getpager() -> Callable[[str], None]: ... + def pipepager(text: str, cmd: str) -> None: ... + def tempfilepager(text: str, cmd: str) -> None: ... + def ttypager(text: str) -> None: ... + def plainpager(text: str) -> None: ... + +text: TextDoc +html: HTMLDoc + +def resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: ... +def render_doc( + thing: str | object, title: str = "Python Library Documentation: %s", forceload: bool = ..., renderer: Doc | None = None +) -> str: ... + +if sys.version_info >= (3, 11): + def doc( + thing: str | object, + title: str = "Python Library Documentation: %s", + forceload: bool = ..., + output: SupportsWrite[str] | None = None, + is_cli: bool = False, + ) -> None: ... + +else: + def doc( + thing: str | object, + title: str = "Python Library Documentation: %s", + forceload: bool = ..., + output: SupportsWrite[str] | None = None, + ) -> None: ... + +def writedoc(thing: str | object, forceload: bool = ...) -> None: ... +def writedocs(dir: str, pkgpath: str = "", done: Any | None = None) -> None: ... + +class Helper: + keywords: dict[str, str | tuple[str, str]] + symbols: dict[str, str] + topics: dict[str, str | tuple[str, ...]] + def __init__(self, input: IO[str] | None = None, output: IO[str] | None = None) -> None: ... + @property + def input(self) -> IO[str]: ... + @property + def output(self) -> IO[str]: ... + def __call__(self, request: str | Helper | object = ...) -> None: ... + def interact(self) -> None: ... + def getline(self, prompt: str) -> str: ... + if sys.version_info >= (3, 11): + def help(self, request: Any, is_cli: bool = False) -> None: ... + else: + def help(self, request: Any) -> None: ... + + def intro(self) -> None: ... + def list(self, items: _list[str], columns: int = 4, width: int = 80) -> None: ... + def listkeywords(self) -> None: ... + def listsymbols(self) -> None: ... + def listtopics(self) -> None: ... + def showtopic(self, topic: str, more_xrefs: str = "") -> None: ... + def showsymbol(self, symbol: str) -> None: ... + def listmodules(self, key: str = "") -> None: ... + +help: Helper + +class ModuleScanner: + quit: bool + def run( + self, + callback: Callable[[str | None, str, str], object], + key: str | None = None, + completer: Callable[[], object] | None = None, + onerror: Callable[[str], object] | None = None, + ) -> None: ... + +def apropos(key: str) -> None: ... +def ispath(x: object) -> TypeGuard[str]: ... +def cli() -> None: ... diff --git a/stdlib/pydoc_data/__init__.pyi b/stdlib/pydoc_data/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/pydoc_data/module_docs.pyi b/stdlib/pydoc_data/module_docs.pyi new file mode 100644 index 000000000000..e3f716c0b292 --- /dev/null +++ b/stdlib/pydoc_data/module_docs.pyi @@ -0,0 +1,3 @@ +from typing import Final + +module_docs: Final[dict[str, str]] diff --git a/stdlib/pydoc_data/topics.pyi b/stdlib/pydoc_data/topics.pyi new file mode 100644 index 000000000000..ce907a41c005 --- /dev/null +++ b/stdlib/pydoc_data/topics.pyi @@ -0,0 +1,3 @@ +from typing import Final + +topics: Final[dict[str, str]] diff --git a/stdlib/pyexpat/__init__.pyi b/stdlib/pyexpat/__init__.pyi new file mode 100644 index 000000000000..83841a226a53 --- /dev/null +++ b/stdlib/pyexpat/__init__.pyi @@ -0,0 +1,91 @@ +import sys +from _typeshed import ReadableBuffer, SupportsRead +from collections.abc import Callable +from pyexpat import errors as errors, model as model +from typing import Any, Final, TypeAlias, final +from typing_extensions import CapsuleType +from xml.parsers.expat import ExpatError as ExpatError + +EXPAT_VERSION: Final[str] # undocumented +version_info: tuple[int, int, int] # undocumented +native_encoding: str # undocumented +features: list[tuple[str, int]] # undocumented + +error = ExpatError +XML_PARAM_ENTITY_PARSING_NEVER: Final = 0 +XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: Final = 1 +XML_PARAM_ENTITY_PARSING_ALWAYS: Final = 2 + +_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] + +@final +class XMLParserType: + def Parse(self, data: str | ReadableBuffer, isfinal: bool = False, /) -> int: ... + def ParseFile(self, file: SupportsRead[bytes], /) -> int: ... + def SetBase(self, base: str, /) -> None: ... + def GetBase(self) -> str | None: ... + def GetInputContext(self) -> bytes | None: ... + def ExternalEntityParserCreate(self, context: str | None, encoding: str = ..., /) -> XMLParserType: ... + def SetParamEntityParsing(self, flag: int, /) -> int: ... + def UseForeignDTD(self, flag: bool = True, /) -> None: ... + def GetReparseDeferralEnabled(self) -> bool: ... + def SetReparseDeferralEnabled(self, enabled: bool, /) -> None: ... + # Added in Python 3.10.20, 3.11.15, 3.12.3, 3.13.10, 3.14.1 + def SetAllocTrackerActivationThreshold(self, threshold: int, /) -> None: ... + def SetAllocTrackerMaximumAmplification(self, max_factor: float, /) -> None: ... + if sys.version_info >= (3, 13): + # Added in Python 3.13.4, 3.14.6 + def SetBillionLaughsAttackProtectionActivationThreshold(self, threshold: int, /) -> None: ... + def SetBillionLaughsAttackProtectionMaximumAmplification(self, max_factor: float, /) -> None: ... + + @property + def intern(self) -> dict[str, str]: ... + buffer_size: int + buffer_text: bool + buffer_used: int + namespace_prefixes: bool # undocumented + ordered_attributes: bool + specified_attributes: bool + ErrorByteIndex: int + ErrorCode: int + ErrorColumnNumber: int + ErrorLineNumber: int + CurrentByteIndex: int + CurrentColumnNumber: int + CurrentLineNumber: int + XmlDeclHandler: Callable[[str, str | None, int], Any] | None + StartDoctypeDeclHandler: Callable[[str, str | None, str | None, bool], Any] | None + EndDoctypeDeclHandler: Callable[[], Any] | None + ElementDeclHandler: Callable[[str, _Model], Any] | None + AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None + StartElementHandler: ( + Callable[[str, dict[str, str]], Any] + | Callable[[str, list[str]], Any] + | Callable[[str, dict[str, str], list[str]], Any] + | None + ) + EndElementHandler: Callable[[str], Any] | None + ProcessingInstructionHandler: Callable[[str, str], Any] | None + CharacterDataHandler: Callable[[str], Any] | None + UnparsedEntityDeclHandler: Callable[[str, str | None, str, str | None, str], Any] | None + EntityDeclHandler: Callable[[str, bool, str | None, str | None, str, str | None, str | None], Any] | None + NotationDeclHandler: Callable[[str, str | None, str, str | None], Any] | None + StartNamespaceDeclHandler: Callable[[str, str], Any] | None + EndNamespaceDeclHandler: Callable[[str], Any] | None + CommentHandler: Callable[[str], Any] | None + StartCdataSectionHandler: Callable[[], Any] | None + EndCdataSectionHandler: Callable[[], Any] | None + DefaultHandler: Callable[[str], Any] | None + DefaultHandlerExpand: Callable[[str], Any] | None + NotStandaloneHandler: Callable[[], int] | None + ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None + SkippedEntityHandler: Callable[[str, bool], Any] | None + +def ErrorString(code: int, /) -> str: ... + +# intern is undocumented +def ParserCreate( + encoding: str | None = None, namespace_separator: str | None = None, intern: dict[str, Any] | None = None +) -> XMLParserType: ... + +expat_CAPI: CapsuleType diff --git a/stdlib/pyexpat/errors.pyi b/stdlib/pyexpat/errors.pyi new file mode 100644 index 000000000000..493ae0345604 --- /dev/null +++ b/stdlib/pyexpat/errors.pyi @@ -0,0 +1,53 @@ +import sys +from typing import Final +from typing_extensions import LiteralString + +codes: dict[str, int] +messages: dict[int, str] + +XML_ERROR_ABORTED: Final[LiteralString] +XML_ERROR_ASYNC_ENTITY: Final[LiteralString] +XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: Final[LiteralString] +XML_ERROR_BAD_CHAR_REF: Final[LiteralString] +XML_ERROR_BINARY_ENTITY_REF: Final[LiteralString] +XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: Final[LiteralString] +XML_ERROR_DUPLICATE_ATTRIBUTE: Final[LiteralString] +XML_ERROR_ENTITY_DECLARED_IN_PE: Final[LiteralString] +XML_ERROR_EXTERNAL_ENTITY_HANDLING: Final[LiteralString] +XML_ERROR_FEATURE_REQUIRES_XML_DTD: Final[LiteralString] +XML_ERROR_FINISHED: Final[LiteralString] +XML_ERROR_INCOMPLETE_PE: Final[LiteralString] +XML_ERROR_INCORRECT_ENCODING: Final[LiteralString] +XML_ERROR_INVALID_TOKEN: Final[LiteralString] +XML_ERROR_JUNK_AFTER_DOC_ELEMENT: Final[LiteralString] +XML_ERROR_MISPLACED_XML_PI: Final[LiteralString] +XML_ERROR_NOT_STANDALONE: Final[LiteralString] +XML_ERROR_NOT_SUSPENDED: Final[LiteralString] +XML_ERROR_NO_ELEMENTS: Final[LiteralString] +XML_ERROR_NO_MEMORY: Final[LiteralString] +XML_ERROR_PARAM_ENTITY_REF: Final[LiteralString] +XML_ERROR_PARTIAL_CHAR: Final[LiteralString] +XML_ERROR_PUBLICID: Final[LiteralString] +XML_ERROR_RECURSIVE_ENTITY_REF: Final[LiteralString] +XML_ERROR_SUSPENDED: Final[LiteralString] +XML_ERROR_SUSPEND_PE: Final[LiteralString] +XML_ERROR_SYNTAX: Final[LiteralString] +XML_ERROR_TAG_MISMATCH: Final[LiteralString] +XML_ERROR_TEXT_DECL: Final[LiteralString] +XML_ERROR_UNBOUND_PREFIX: Final[LiteralString] +XML_ERROR_UNCLOSED_CDATA_SECTION: Final[LiteralString] +XML_ERROR_UNCLOSED_TOKEN: Final[LiteralString] +XML_ERROR_UNDECLARING_PREFIX: Final[LiteralString] +XML_ERROR_UNDEFINED_ENTITY: Final[LiteralString] +XML_ERROR_UNEXPECTED_STATE: Final[LiteralString] +XML_ERROR_UNKNOWN_ENCODING: Final[LiteralString] +XML_ERROR_XML_DECL: Final[LiteralString] +if sys.version_info >= (3, 11): + XML_ERROR_RESERVED_PREFIX_XML: Final[LiteralString] + XML_ERROR_RESERVED_PREFIX_XMLNS: Final[LiteralString] + XML_ERROR_RESERVED_NAMESPACE_URI: Final[LiteralString] + XML_ERROR_INVALID_ARGUMENT: Final[LiteralString] + XML_ERROR_NO_BUFFER: Final[LiteralString] + XML_ERROR_AMPLIFICATION_LIMIT_BREACH: Final[LiteralString] +if sys.version_info >= (3, 14): + XML_ERROR_NOT_STARTED: Final[LiteralString] diff --git a/stdlib/pyexpat/model.pyi b/stdlib/pyexpat/model.pyi new file mode 100644 index 000000000000..bac8f3692ce5 --- /dev/null +++ b/stdlib/pyexpat/model.pyi @@ -0,0 +1,13 @@ +from typing import Final + +XML_CTYPE_ANY: Final = 2 +XML_CTYPE_EMPTY: Final = 1 +XML_CTYPE_MIXED: Final = 3 +XML_CTYPE_NAME: Final = 4 +XML_CTYPE_CHOICE: Final = 5 +XML_CTYPE_SEQ: Final = 6 + +XML_CQUANT_NONE: Final = 0 +XML_CQUANT_OPT: Final = 1 +XML_CQUANT_REP: Final = 2 +XML_CQUANT_PLUS: Final = 3 diff --git a/stdlib/queue.pyi b/stdlib/queue.pyi new file mode 100644 index 000000000000..65e2ac1559ad --- /dev/null +++ b/stdlib/queue.pyi @@ -0,0 +1,55 @@ +import sys +from _queue import Empty as Empty, SimpleQueue as SimpleQueue +from _typeshed import SupportsRichComparisonT +from threading import Condition, Lock +from types import GenericAlias +from typing import Any, Generic, TypeVar + +__all__ = ["Empty", "Full", "Queue", "PriorityQueue", "LifoQueue", "SimpleQueue"] +if sys.version_info >= (3, 13): + __all__ += ["ShutDown"] + +_T = TypeVar("_T") + +class Full(Exception): ... + +if sys.version_info >= (3, 13): + class ShutDown(Exception): ... + +class Queue(Generic[_T]): + maxsize: int + + mutex: Lock # undocumented + not_empty: Condition # undocumented + not_full: Condition # undocumented + all_tasks_done: Condition # undocumented + unfinished_tasks: int # undocumented + if sys.version_info >= (3, 13): + is_shutdown: bool # undocumented + # Despite the fact that `queue` has `deque` type, + # we treat it as `Any` to allow different implementations in subtypes. + queue: Any # undocumented + def __init__(self, maxsize: int = 0) -> None: ... + def _init(self, maxsize: int) -> None: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + if sys.version_info >= (3, 13): + def shutdown(self, immediate: bool = False) -> None: ... + + def _get(self) -> _T: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def _put(self, item: _T) -> None: ... + def join(self) -> None: ... + def qsize(self) -> int: ... + def _qsize(self) -> int: ... + def task_done(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class PriorityQueue(Queue[SupportsRichComparisonT]): + queue: list[SupportsRichComparisonT] + +class LifoQueue(Queue[_T]): + queue: list[_T] diff --git a/stdlib/quopri.pyi b/stdlib/quopri.pyi new file mode 100644 index 000000000000..be6892fcbcd7 --- /dev/null +++ b/stdlib/quopri.pyi @@ -0,0 +1,12 @@ +from _typeshed import ReadableBuffer, SupportsNoArgReadline, SupportsRead, SupportsWrite +from typing import Protocol, type_check_only + +__all__ = ["encode", "decode", "encodestring", "decodestring"] + +@type_check_only +class _Input(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... + +def encode(input: _Input, output: SupportsWrite[bytes], quotetabs: int, header: bool = False) -> None: ... +def encodestring(s: ReadableBuffer, quotetabs: bool = False, header: bool = False) -> bytes: ... +def decode(input: _Input, output: SupportsWrite[bytes], header: bool = False) -> None: ... +def decodestring(s: str | ReadableBuffer, header: bool = False) -> bytes: ... diff --git a/stdlib/random.pyi b/stdlib/random.pyi new file mode 100644 index 000000000000..c70c8364684c --- /dev/null +++ b/stdlib/random.pyi @@ -0,0 +1,135 @@ +import _random +import sys +from _typeshed import SupportsLenAndGetItem +from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet +from fractions import Fraction +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import Never, deprecated + +__all__ = [ + "Random", + "seed", + "random", + "uniform", + "randint", + "choice", + "sample", + "randrange", + "shuffle", + "normalvariate", + "lognormvariate", + "expovariate", + "vonmisesvariate", + "gammavariate", + "triangular", + "gauss", + "betavariate", + "paretovariate", + "weibullvariate", + "getstate", + "setstate", + "getrandbits", + "choices", + "SystemRandom", + "randbytes", +] + +if sys.version_info >= (3, 12): + __all__ += ["binomialvariate"] + +_T = TypeVar("_T") + +class Random(_random.Random): + VERSION: ClassVar[int] + def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ... # noqa: Y041 + # Using other `seed` types is deprecated since 3.9 and removed in 3.11 + # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit + # int better documents conventional usage of random.seed. + + def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ... # type: ignore[override] # noqa: Y041 + def getstate(self) -> tuple[Any, ...]: ... + def setstate(self, state: tuple[Any, ...]) -> None: ... + def randrange(self, start: int, stop: int | None = None, step: int = 1) -> int: ... + def randint(self, a: int, b: int) -> int: ... + def randbytes(self, n: int) -> bytes: ... + def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ... + def choices( + self, + population: SupportsLenAndGetItem[_T], + weights: Sequence[float | Fraction] | None = None, + *, + cum_weights: Sequence[float | Fraction] | None = None, + k: int = 1, + ) -> list[_T]: ... + if sys.version_info >= (3, 11): + def shuffle(self, x: MutableSequence[Any]) -> None: ... + else: + @overload + def shuffle(self, x: MutableSequence[Any]) -> None: ... + @overload + @deprecated("The `random` parameter is deprecated since Python 3.9; removed in Python 3.11.") + def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = None) -> None: ... + + if sys.version_info >= (3, 11): + def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: ... + else: + def sample( + self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None + ) -> list[_T]: ... + + def uniform(self, a: float, b: float) -> float: ... + def triangular(self, low: float = 0.0, high: float = 1.0, mode: float | None = None) -> float: ... + if sys.version_info >= (3, 12): + def binomialvariate(self, n: int = 1, p: float = 0.5) -> int: ... + + def betavariate(self, alpha: float, beta: float) -> float: ... + if sys.version_info >= (3, 12): + def expovariate(self, lambd: float = 1.0) -> float: ... + else: + def expovariate(self, lambd: float) -> float: ... + + def gammavariate(self, alpha: float, beta: float) -> float: ... + if sys.version_info >= (3, 11): + def gauss(self, mu: float = 0.0, sigma: float = 1.0) -> float: ... + def normalvariate(self, mu: float = 0.0, sigma: float = 1.0) -> float: ... + else: + def gauss(self, mu: float, sigma: float) -> float: ... + def normalvariate(self, mu: float, sigma: float) -> float: ... + + def lognormvariate(self, mu: float, sigma: float) -> float: ... + def vonmisesvariate(self, mu: float, kappa: float) -> float: ... + def paretovariate(self, alpha: float) -> float: ... + def weibullvariate(self, alpha: float, beta: float) -> float: ... + +# SystemRandom is not implemented for all OS's; good on Windows & Linux +class SystemRandom(Random): + def getrandbits(self, k: int) -> int: ... # k can be passed by keyword + def getstate(self, *args: Any, **kwds: Any) -> Never: ... + def setstate(self, *args: Any, **kwds: Any) -> Never: ... + +_inst: Random +seed = _inst.seed +random = _inst.random +uniform = _inst.uniform +triangular = _inst.triangular +randint = _inst.randint +choice = _inst.choice +randrange = _inst.randrange +sample = _inst.sample +shuffle = _inst.shuffle +choices = _inst.choices +normalvariate = _inst.normalvariate +lognormvariate = _inst.lognormvariate +expovariate = _inst.expovariate +vonmisesvariate = _inst.vonmisesvariate +gammavariate = _inst.gammavariate +gauss = _inst.gauss +if sys.version_info >= (3, 12): + binomialvariate = _inst.binomialvariate +betavariate = _inst.betavariate +paretovariate = _inst.paretovariate +weibullvariate = _inst.weibullvariate +getstate = _inst.getstate +setstate = _inst.setstate +getrandbits = _inst.getrandbits +randbytes = _inst.randbytes diff --git a/stdlib/re.pyi b/stdlib/re.pyi new file mode 100644 index 000000000000..f0a892c797e9 --- /dev/null +++ b/stdlib/re.pyi @@ -0,0 +1,347 @@ +import enum +import sys +from _typeshed import MaybeNone, ReadableBuffer +from collections.abc import Callable, Iterator, Mapping +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, final, overload +from typing_extensions import deprecated + +__all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "escape", + "error", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", + "Match", + "Pattern", +] +if sys.version_info >= (3, 15): + __all__ += ["prefixmatch"] +if sys.version_info < (3, 13): + __all__ += ["template"] + +if sys.version_info >= (3, 11): + __all__ += ["NOFLAG", "RegexFlag"] + +if sys.version_info >= (3, 13): + __all__ += ["PatternError"] + +_T = TypeVar("_T") + +# The implementation defines this in re._constants (version_info >= 3, 11) or +# sre_constants. Typeshed has it here because its __module__ attribute is set to "re". +class error(Exception): + msg: str + pattern: str | bytes | None + pos: int | None + lineno: int + colno: int + def __init__(self, msg: str, pattern: str | bytes | None = None, pos: int | None = None) -> None: ... + +if sys.version_info >= (3, 13): + PatternError = error + +@final +class Match(Generic[AnyStr]): + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... + + # The regular expression object whose match() or search() method produced + # this match instance. + @property + def re(self) -> Pattern[AnyStr]: ... + + @overload + def expand(self: Match[str], template: str) -> str: ... + @overload + def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... + @overload + def expand(self, template: AnyStr) -> AnyStr: ... + + # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def group(self, group: Literal[0] = 0, /) -> AnyStr: ... + @overload + def group(self, group: str | int, /) -> AnyStr | MaybeNone: ... + @overload + def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | MaybeNone, ...]: ... + + # Each item of groups()'s return tuple is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groups(self) -> tuple[AnyStr | MaybeNone, ...]: ... + @overload + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + + # Each value in groupdict()'s return dict is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groupdict(self) -> dict[str, AnyStr | MaybeNone]: ... + @overload + def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + + def start(self, group: int | str = 0, /) -> int: ... + def end(self, group: int | str = 0, /) -> int: ... + def span(self, group: int | str = 0, /) -> tuple[int, int]: ... + @property + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented + + # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def __getitem__(self, key: Literal[0], /) -> AnyStr: ... + @overload + def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ... + + def __copy__(self) -> Match[AnyStr]: ... + def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Pattern(Generic[AnyStr]): + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... + + @overload + def search(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... + @overload + def search(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + @overload + def match(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... + @overload + def match(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + if sys.version_info >= (3, 15): + prefixmatch = match + + @overload + def fullmatch(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... + @overload + def fullmatch( + self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize + ) -> Match[bytes] | None: ... + @overload + def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + @overload + def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: ... + @overload + def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ... + @overload + def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ... + + # return type is either list[str/bytes] or list[tuple[str/bytes, ...]] + @overload + def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... + @overload + def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... + @overload + def findall(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> list[AnyStr]: ... + + @overload + def finditer(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[str]]: ... + @overload + def finditer( + self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize + ) -> Iterator[Match[bytes]]: ... + @overload + def finditer(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[AnyStr]]: ... + + @overload + def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> str: ... + @overload + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + ) -> bytes: ... + @overload + def sub(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> AnyStr: ... + + @overload + def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> tuple[str, int]: ... + @overload + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + ) -> tuple[bytes, int]: ... + @overload + def subn(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> tuple[AnyStr, int]: ... + + def __copy__(self) -> Pattern[AnyStr]: ... + def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# ----- re variables and constants ----- + +class RegexFlag(enum.IntFlag): + A = 256 + ASCII = A + DEBUG = 128 + I = 2 + IGNORECASE = I + L = 4 + LOCALE = L + M = 8 + MULTILINE = M + S = 16 + DOTALL = S + X = 64 + VERBOSE = X + U = 32 + UNICODE = U + if sys.version_info < (3, 13): + T = 1 + TEMPLATE = T + if sys.version_info >= (3, 11): + NOFLAG = 0 + +A: Final = RegexFlag.A +ASCII: Final = RegexFlag.ASCII +DEBUG: Final = RegexFlag.DEBUG +I: Final = RegexFlag.I +IGNORECASE: Final = RegexFlag.IGNORECASE +L: Final = RegexFlag.L +LOCALE: Final = RegexFlag.LOCALE +M: Final = RegexFlag.M +MULTILINE: Final = RegexFlag.MULTILINE +S: Final = RegexFlag.S +DOTALL: Final = RegexFlag.DOTALL +X: Final = RegexFlag.X +VERBOSE: Final = RegexFlag.VERBOSE +U: Final = RegexFlag.U +UNICODE: Final = RegexFlag.UNICODE +if sys.version_info < (3, 13): + T: Final = RegexFlag.T + TEMPLATE: Final = RegexFlag.TEMPLATE +if sys.version_info >= (3, 11): + NOFLAG: Final = RegexFlag.NOFLAG +_FlagsType: TypeAlias = int | RegexFlag + +# Type-wise the compile() overloads are unnecessary, they could also be modeled using +# unions in the parameter types. However mypy has a bug regarding TypeVar +# constraints (https://github.com/python/mypy/issues/11880), +# which limits us here because AnyStr is a constrained TypeVar. + +# pattern arguments do *not* accept arbitrary buffers such as bytearray, +# because the pattern must be hashable. +@overload +def compile(pattern: AnyStr, flags: _FlagsType = 0) -> Pattern[AnyStr]: ... +@overload +def compile(pattern: Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... + +@overload +def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... +@overload +def search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +@overload +def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... +@overload +def match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +if sys.version_info >= (3, 15): + @overload + def prefixmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... + @overload + def prefixmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +@overload +def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... +@overload +def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +@overload +def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: ... +@overload +def split( + pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0 +) -> list[bytes | MaybeNone]: ... + +# return type is either list[str/bytes] or list[tuple[str/bytes, ...]] +@overload +def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ... +@overload +def findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[Any]: ... + +@overload +def finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Iterator[Match[str]]: ... +@overload +def finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Iterator[Match[bytes]]: ... + +@overload +def sub( + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 +) -> str: ... +@overload +def sub( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: _FlagsType = 0, +) -> bytes: ... + +@overload +def subn( + pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 +) -> tuple[str, int]: ... +@overload +def subn( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: _FlagsType = 0, +) -> tuple[bytes, int]: ... + +def escape(pattern: AnyStr) -> AnyStr: ... +def purge() -> None: ... + +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13. Use `re.compile()` instead.") + def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented diff --git a/stdlib/readline.pyi b/stdlib/readline.pyi new file mode 100644 index 000000000000..aff1e504a174 --- /dev/null +++ b/stdlib/readline.pyi @@ -0,0 +1,39 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Sequence +from typing import Literal, TypeAlias + +if sys.platform != "win32": + _Completer: TypeAlias = Callable[[str, int], str | None] + _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None] + + def parse_and_bind(string: str, /) -> None: ... + def read_init_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def get_line_buffer() -> str: ... + def insert_text(string: str, /) -> None: ... + def redisplay() -> None: ... + def read_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def write_history_file(filename: StrOrBytesPath | None = None, /) -> None: ... + def append_history_file(nelements: int, filename: StrOrBytesPath | None = None, /) -> None: ... + def get_history_length() -> int: ... + def set_history_length(length: int, /) -> None: ... + def clear_history() -> None: ... + def get_current_history_length() -> int: ... + def get_history_item(index: int, /) -> str: ... + def remove_history_item(pos: int, /) -> None: ... + def replace_history_item(pos: int, line: str, /) -> None: ... + def add_history(string: str, /) -> None: ... + def set_auto_history(enabled: bool, /) -> None: ... + def set_startup_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_pre_input_hook(function: Callable[[], object] | None = None, /) -> None: ... + def set_completer(function: _Completer | None = None, /) -> None: ... + def get_completer() -> _Completer | None: ... + def get_completion_type() -> int: ... + def get_begidx() -> int: ... + def get_endidx() -> int: ... + def set_completer_delims(string: str, /) -> None: ... + def get_completer_delims() -> str: ... + def set_completion_display_matches_hook(function: _CompDisp | None = None, /) -> None: ... + + if sys.version_info >= (3, 13): + backend: Literal["readline", "editline"] diff --git a/stdlib/reprlib.pyi b/stdlib/reprlib.pyi new file mode 100644 index 000000000000..d990c2708ae9 --- /dev/null +++ b/stdlib/reprlib.pyi @@ -0,0 +1,64 @@ +import sys +from array import array +from collections import deque +from collections.abc import Callable +from typing import Any, TypeAlias + +__all__ = ["Repr", "repr", "recursive_repr"] + +_ReprFunc: TypeAlias = Callable[[Any], str] + +def recursive_repr(fillvalue: str = "...") -> Callable[[_ReprFunc], _ReprFunc]: ... + +class Repr: + maxlevel: int + maxdict: int + maxlist: int + maxtuple: int + maxset: int + maxfrozenset: int + maxdeque: int + maxarray: int + maxlong: int + maxstring: int + maxother: int + if sys.version_info >= (3, 11): + fillvalue: str + if sys.version_info >= (3, 12): + indent: str | int | None + + if sys.version_info >= (3, 12): + def __init__( + self, + *, + maxlevel: int = 6, + maxtuple: int = 6, + maxlist: int = 6, + maxarray: int = 5, + maxdict: int = 4, + maxset: int = 6, + maxfrozenset: int = 6, + maxdeque: int = 6, + maxstring: int = 30, + maxlong: int = 40, + maxother: int = 30, + fillvalue: str = "...", + indent: str | int | None = None, + ) -> None: ... + + def repr(self, x: Any) -> str: ... + def repr1(self, x: Any, level: int) -> str: ... + def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ... + def repr_list(self, x: list[Any], level: int) -> str: ... + def repr_array(self, x: array[Any], level: int) -> str: ... + def repr_set(self, x: set[Any], level: int) -> str: ... + def repr_frozenset(self, x: frozenset[Any], level: int) -> str: ... + def repr_deque(self, x: deque[Any], level: int) -> str: ... + def repr_dict(self, x: dict[Any, Any], level: int) -> str: ... + def repr_str(self, x: str, level: int) -> str: ... + def repr_int(self, x: int, level: int) -> str: ... + def repr_instance(self, x: Any, level: int) -> str: ... + +aRepr: Repr + +def repr(x: object) -> str: ... diff --git a/stdlib/resource.pyi b/stdlib/resource.pyi new file mode 100644 index 000000000000..7e72b28cc6dd --- /dev/null +++ b/stdlib/resource.pyi @@ -0,0 +1,102 @@ +import sys +from _typeshed import structseq +from typing import Final, final + +if sys.platform != "win32": + # Depends on resource.h + RLIMIT_AS: Final[int] + RLIMIT_CORE: Final[int] + RLIMIT_CPU: Final[int] + RLIMIT_DATA: Final[int] + RLIMIT_FSIZE: Final[int] + RLIMIT_MEMLOCK: Final[int] + RLIMIT_NOFILE: Final[int] + RLIMIT_NPROC: Final[int] + RLIMIT_RSS: Final[int] + RLIMIT_STACK: Final[int] + RLIM_INFINITY: Final[int] + if sys.version_info >= (3, 15): + RLIM_SAVED_CUR: Final[int] + RLIM_SAVED_MAX: Final[int] + RUSAGE_CHILDREN: Final[int] + RUSAGE_SELF: Final[int] + if sys.platform == "linux": + RLIMIT_MSGQUEUE: Final[int] + RLIMIT_NICE: Final[int] + RLIMIT_OFILE: Final[int] + RLIMIT_RTPRIO: Final[int] + RLIMIT_RTTIME: Final[int] + RLIMIT_SIGPENDING: Final[int] + RUSAGE_THREAD: Final[int] + if sys.version_info >= (3, 15) and sys.platform != "linux" and sys.platform != "darwin": + RLIMIT_NTHR: Final[int] + RLIMIT_PIPEBUF: Final[int] + RLIMIT_THREADS: Final[int] + RLIMIT_UMTXP: Final[int] + + @final + class struct_rusage( + structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] + ): + __match_args__: Final = ( + "ru_utime", + "ru_stime", + "ru_maxrss", + "ru_ixrss", + "ru_idrss", + "ru_isrss", + "ru_minflt", + "ru_majflt", + "ru_nswap", + "ru_inblock", + "ru_oublock", + "ru_msgsnd", + "ru_msgrcv", + "ru_nsignals", + "ru_nvcsw", + "ru_nivcsw", + ) + + @property + def ru_utime(self) -> float: ... + @property + def ru_stime(self) -> float: ... + @property + def ru_maxrss(self) -> int: ... + @property + def ru_ixrss(self) -> int: ... + @property + def ru_idrss(self) -> int: ... + @property + def ru_isrss(self) -> int: ... + @property + def ru_minflt(self) -> int: ... + @property + def ru_majflt(self) -> int: ... + @property + def ru_nswap(self) -> int: ... + @property + def ru_inblock(self) -> int: ... + @property + def ru_oublock(self) -> int: ... + @property + def ru_msgsnd(self) -> int: ... + @property + def ru_msgrcv(self) -> int: ... + @property + def ru_nsignals(self) -> int: ... + @property + def ru_nvcsw(self) -> int: ... + @property + def ru_nivcsw(self) -> int: ... + + def getpagesize() -> int: ... + def getrlimit(resource: int, /) -> tuple[int, int]: ... + def getrusage(who: int, /) -> struct_rusage: ... + def setrlimit(resource: int, limits: tuple[int, int], /) -> None: ... + if sys.platform == "linux": + if sys.version_info >= (3, 12): + def prlimit(pid: int, resource: int, limits: tuple[int, int] | None = None, /) -> tuple[int, int]: ... + else: + def prlimit(pid: int, resource: int, limits: tuple[int, int] = ..., /) -> tuple[int, int]: ... + error = OSError diff --git a/stdlib/rlcompleter.pyi b/stdlib/rlcompleter.pyi new file mode 100644 index 000000000000..8d9477e3ee45 --- /dev/null +++ b/stdlib/rlcompleter.pyi @@ -0,0 +1,9 @@ +from typing import Any + +__all__ = ["Completer"] + +class Completer: + def __init__(self, namespace: dict[str, Any] | None = None) -> None: ... + def complete(self, text: str, state: int) -> str | None: ... + def attr_matches(self, text: str) -> list[str]: ... + def global_matches(self, text: str) -> list[str]: ... diff --git a/stdlib/runpy.pyi b/stdlib/runpy.pyi new file mode 100644 index 000000000000..d4406ea4ac41 --- /dev/null +++ b/stdlib/runpy.pyi @@ -0,0 +1,24 @@ +from _typeshed import Unused +from types import ModuleType +from typing import Any +from typing_extensions import Self + +__all__ = ["run_module", "run_path"] + +class _TempModule: + mod_name: str + module: ModuleType + def __init__(self, mod_name: str) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + +class _ModifiedArgv0: + value: Any + def __init__(self, value: Any) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *args: Unused) -> None: ... + +def run_module( + mod_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None, alter_sys: bool = False +) -> dict[str, Any]: ... +def run_path(path_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None) -> dict[str, Any]: ... diff --git a/stdlib/sched.pyi b/stdlib/sched.pyi new file mode 100644 index 000000000000..54eb6ed0cd53 --- /dev/null +++ b/stdlib/sched.pyi @@ -0,0 +1,34 @@ +import time +from collections.abc import Callable +from typing import Any, NamedTuple, TypeAlias + +__all__ = ["scheduler"] + +_ActionCallback: TypeAlias = Callable[..., Any] + +class Event(NamedTuple): + time: float + priority: Any + sequence: int + action: _ActionCallback + argument: tuple[Any, ...] + kwargs: dict[str, Any] + +class scheduler: + timefunc: Callable[[], float] + delayfunc: Callable[[float], object] + + def __init__( + self, timefunc: Callable[[], float] = time.monotonic, delayfunc: Callable[[float], object] = time.sleep + ) -> None: ... + def enterabs( + self, time: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... + ) -> Event: ... + def enter( + self, delay: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ... + ) -> Event: ... + def run(self, blocking: bool = True) -> float | None: ... + def cancel(self, event: Event) -> None: ... + def empty(self) -> bool: ... + @property + def queue(self) -> list[Event]: ... diff --git a/stdlib/secrets.pyi b/stdlib/secrets.pyi new file mode 100644 index 000000000000..76479af97a07 --- /dev/null +++ b/stdlib/secrets.pyi @@ -0,0 +1,17 @@ +from _typeshed import SupportsLenAndGetItem +from hmac import compare_digest as compare_digest +from random import SystemRandom as SystemRandom +from typing import Final, TypeVar + +__all__ = ["choice", "randbelow", "randbits", "SystemRandom", "token_bytes", "token_hex", "token_urlsafe", "compare_digest"] + +_T = TypeVar("_T") + +DEFAULT_ENTROPY: Final[int] + +def randbelow(exclusive_upper_bound: int) -> int: ... +def randbits(k: int) -> int: ... +def choice(seq: SupportsLenAndGetItem[_T]) -> _T: ... +def token_bytes(nbytes: int | None = None) -> bytes: ... +def token_hex(nbytes: int | None = None) -> str: ... +def token_urlsafe(nbytes: int | None = None) -> str: ... diff --git a/stdlib/select.pyi b/stdlib/select.pyi new file mode 100644 index 000000000000..ad93cb0b7055 --- /dev/null +++ b/stdlib/select.pyi @@ -0,0 +1,171 @@ +import sys +from _typeshed import FileDescriptorLike +from collections.abc import Iterable +from types import TracebackType +from typing import Any, ClassVar, Final, TypeVar, final, overload +from typing_extensions import Never, Self, deprecated + +if sys.platform != "win32": + PIPE_BUF: Final[int] + POLLERR: Final[int] + POLLHUP: Final[int] + POLLIN: Final[int] + if sys.platform == "linux": + POLLMSG: Final[int] + POLLNVAL: Final[int] + POLLOUT: Final[int] + POLLPRI: Final[int] + POLLRDBAND: Final[int] + if sys.platform == "linux": + POLLRDHUP: Final[int] + POLLRDNORM: Final[int] + POLLWRBAND: Final[int] + POLLWRNORM: Final[int] + + # This is actually a function that returns an instance of a class. + # The class is not accessible directly, and also calls itself select.poll. + @final + class poll: + # default value is select.POLLIN | select.POLLPRI | select.POLLOUT + def register(self, fd: FileDescriptorLike, eventmask: int = 7, /) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int, /) -> None: ... + def unregister(self, fd: FileDescriptorLike, /) -> None: ... + def poll(self, timeout: float | None = None, /) -> list[tuple[int, int]]: ... + +_R = TypeVar("_R", default=Never, bound=FileDescriptorLike) +_W = TypeVar("_W", default=Never, bound=FileDescriptorLike) +_X = TypeVar("_X", default=Never, bound=FileDescriptorLike) + +def select( + rlist: Iterable[_R], wlist: Iterable[_W], xlist: Iterable[_X], timeout: float | None = None, / +) -> tuple[list[_R], list[_W], list[_X]]: ... + +error = OSError + +if sys.platform != "linux" and sys.platform != "win32": + # BSD only + @final + class kevent: + data: Any + fflags: int + filter: int + flags: int + ident: int + udata: Any + def __init__( + self, ident: FileDescriptorLike, filter: int = ..., flags: int = ..., fflags: int = 0, data: Any = 0, udata: Any = 0 + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + + # BSD only + @final + class kqueue: + closed: bool + def __init__(self) -> None: ... + def close(self) -> None: ... + def control( + self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, / + ) -> list[kevent]: ... + def fileno(self) -> int: ... + @classmethod + def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: ... + + KQ_EV_ADD: Final[int] + KQ_EV_CLEAR: Final[int] + KQ_EV_DELETE: Final[int] + KQ_EV_DISABLE: Final[int] + KQ_EV_ENABLE: Final[int] + KQ_EV_EOF: Final[int] + KQ_EV_ERROR: Final[int] + KQ_EV_FLAG1: Final[int] + KQ_EV_ONESHOT: Final[int] + KQ_EV_SYSFLAGS: Final[int] + KQ_FILTER_AIO: Final[int] + if sys.platform != "darwin": + KQ_FILTER_NETDEV: Final[int] + KQ_FILTER_PROC: Final[int] + KQ_FILTER_READ: Final[int] + KQ_FILTER_SIGNAL: Final[int] + KQ_FILTER_TIMER: Final[int] + KQ_FILTER_VNODE: Final[int] + KQ_FILTER_WRITE: Final[int] + KQ_NOTE_ATTRIB: Final[int] + KQ_NOTE_CHILD: Final[int] + KQ_NOTE_DELETE: Final[int] + KQ_NOTE_EXEC: Final[int] + KQ_NOTE_EXIT: Final[int] + KQ_NOTE_EXTEND: Final[int] + KQ_NOTE_FORK: Final[int] + KQ_NOTE_LINK: Final[int] + if sys.platform != "darwin": + KQ_NOTE_LINKDOWN: Final[int] + KQ_NOTE_LINKINV: Final[int] + KQ_NOTE_LINKUP: Final[int] + KQ_NOTE_LOWAT: Final[int] + KQ_NOTE_PCTRLMASK: Final[int] + KQ_NOTE_PDATAMASK: Final[int] + KQ_NOTE_RENAME: Final[int] + KQ_NOTE_REVOKE: Final[int] + KQ_NOTE_TRACK: Final[int] + KQ_NOTE_TRACKERR: Final[int] + KQ_NOTE_WRITE: Final[int] + +if sys.platform == "linux": + @final + class epoll: + @overload + def __new__(self, sizehint: int = -1) -> Self: ... + @overload + @deprecated( + "The `flags` parameter is deprecated since Python 3.4. " + "Use `os.set_inheritable()` to make the file descriptor inheritable." + ) + def __new__(self, sizehint: int = -1, flags: int = 0) -> Self: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + exc_tb: TracebackType | None = None, + /, + ) -> None: ... + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... + def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: ... + @classmethod + def fromfd(cls, fd: FileDescriptorLike, /) -> epoll: ... + + EPOLLERR: Final[int] + EPOLLEXCLUSIVE: Final[int] + EPOLLET: Final[int] + EPOLLHUP: Final[int] + EPOLLIN: Final[int] + EPOLLMSG: Final[int] + EPOLLONESHOT: Final[int] + EPOLLOUT: Final[int] + EPOLLPRI: Final[int] + EPOLLRDBAND: Final[int] + EPOLLRDHUP: Final[int] + EPOLLRDNORM: Final[int] + EPOLLWRBAND: Final[int] + EPOLLWRNORM: Final[int] + EPOLL_CLOEXEC: Final[int] + if sys.version_info >= (3, 14): + EPOLLWAKEUP: Final[int] + +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + # Solaris only + @final + class devpoll: + def close(self) -> None: ... + closed: bool + def fileno(self) -> int: ... + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... + def poll(self, timeout: float | None = None) -> list[tuple[int, int]]: ... diff --git a/stdlib/selectors.pyi b/stdlib/selectors.pyi new file mode 100644 index 000000000000..4a3478a67552 --- /dev/null +++ b/stdlib/selectors.pyi @@ -0,0 +1,67 @@ +import sys +from _typeshed import FileDescriptor, FileDescriptorLike, Unused +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from typing import Any, Final, NamedTuple +from typing_extensions import Self + +EVENT_READ: Final = 1 +EVENT_WRITE: Final = 2 + +class SelectorKey(NamedTuple): + fileobj: FileDescriptorLike + fd: FileDescriptor + events: int + data: Any + +class BaseSelector(metaclass=ABCMeta): + @abstractmethod + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + @abstractmethod + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + @abstractmethod + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + def close(self) -> None: ... + def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + @abstractmethod + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + +class _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta): + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +class SelectSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + +class _PollLikeSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + +if sys.platform != "win32": + class PollSelector(_PollLikeSelector): ... + +if sys.platform == "linux": + class EpollSelector(_PollLikeSelector): + def fileno(self) -> int: ... + +if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": + # Solaris only + class DevpollSelector(_PollLikeSelector): + def fileno(self) -> int: ... + +if sys.platform != "win32" and sys.platform != "linux": + class KqueueSelector(_BaseSelectorImpl): + def fileno(self) -> int: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + +# Not a real class at runtime, it is just a conditional alias to other real selectors. +# The runtime logic is more fine-grained than a `sys.platform` check; +# not really expressible in the stubs +class DefaultSelector(_BaseSelectorImpl): + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + if sys.platform != "win32": + def fileno(self) -> int: ... diff --git a/stdlib/shelve.pyi b/stdlib/shelve.pyi new file mode 100644 index 000000000000..c599b0af6138 --- /dev/null +++ b/stdlib/shelve.pyi @@ -0,0 +1,110 @@ +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterator, MutableMapping +from dbm import _TFlags +from types import TracebackType +from typing import Any, TypeVar, overload +from typing_extensions import Self + +__all__ = ["Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] +if sys.version_info >= (3, 15): + __all__ += ["ShelveError"] + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +if sys.version_info >= (3, 15): + class ShelveError(Exception): ... + +class Shelf(MutableMapping[str, _VT]): + if sys.version_info >= (3, 15): + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + ) -> None: ... + + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + + @overload # type: ignore[override] + def get(self, key: str, default: None = None) -> _VT | None: ... + @overload + def get(self, key: str, default: _VT) -> _VT: ... + @overload + def get(self, key: str, default: _T) -> _VT | _T: ... + + def __getitem__(self, key: str) -> _VT: ... + def __setitem__(self, key: str, value: _VT) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: str) -> bool: ... # type: ignore[override] + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def close(self) -> None: ... + def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + +class BsdDbShelf(Shelf[_VT]): + def set_location(self, key: str) -> tuple[str, _VT]: ... + def next(self) -> tuple[str, _VT]: ... + def previous(self) -> tuple[str, _VT]: ... + def first(self) -> tuple[str, _VT]: ... + def last(self) -> tuple[str, _VT]: ... + +class DbfilenameShelf(Shelf[_VT]): + if sys.version_info >= (3, 15): + def __init__( + self, + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + elif sys.version_info >= (3, 11): + def __init__( + self, filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False + ) -> None: ... + + else: + def __init__(self, filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> None: ... + +if sys.version_info >= (3, 15): + def open( + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> Shelf[Any]: ... + +elif sys.version_info >= (3, 11): + def open( + filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False + ) -> Shelf[Any]: ... + +else: + def open(filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> Shelf[Any]: ... diff --git a/stdlib/shlex.pyi b/stdlib/shlex.pyi new file mode 100644 index 000000000000..1c27483782fb --- /dev/null +++ b/stdlib/shlex.pyi @@ -0,0 +1,63 @@ +import sys +from collections import deque +from collections.abc import Iterable +from io import TextIOWrapper +from typing import Literal, Protocol, overload, type_check_only +from typing_extensions import Self, deprecated + +__all__ = ["shlex", "split", "quote", "join"] + +@type_check_only +class _ShlexInstream(Protocol): + def read(self, size: Literal[1], /) -> str: ... + def readline(self) -> object: ... + def close(self) -> object: ... + +if sys.version_info >= (3, 12): + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + +else: + @overload + def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ... + @overload + @deprecated("Passing None for 's' to shlex.split() is deprecated and will raise an error in Python 3.12.") + def split(s: None, comments: bool = False, posix: bool = True) -> list[str]: ... + +def join(split_command: Iterable[str]) -> str: ... +def quote(s: str) -> str: ... + +# TODO: Make generic over infile once PEP 696 is implemented. +class shlex: + commenters: str + wordchars: str + whitespace: str + escape: str + quotes: str + escapedquotes: str + whitespace_split: bool + infile: str | None + instream: _ShlexInstream + source: str + debug: int + lineno: int + token: str + filestack: deque[tuple[str | None, _ShlexInstream, int]] + eof: str | None + @property + def punctuation_chars(self) -> str: ... + def __init__( + self, + instream: str | _ShlexInstream | None = None, + infile: str | None = None, + posix: bool = False, + punctuation_chars: bool | str = False, + ) -> None: ... + def get_token(self) -> str | None: ... + def push_token(self, tok: str) -> None: ... + def read_token(self) -> str | None: ... + def sourcehook(self, newfile: str) -> tuple[str, TextIOWrapper] | None: ... + def push_source(self, newstream: str | _ShlexInstream, newfile: str | None = None) -> None: ... + def pop_source(self) -> None: ... + def error_leader(self, infile: str | None = None, lineno: int | None = None) -> str: ... + def __iter__(self) -> Self: ... + def __next__(self) -> str: ... diff --git a/stdlib/shutil.pyi b/stdlib/shutil.pyi new file mode 100644 index 000000000000..5919106f3ed9 --- /dev/null +++ b/stdlib/shutil.pyi @@ -0,0 +1,243 @@ +import os +import sys +from _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, MaybeNone, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Sequence +from tarfile import _TarfileFilter +from typing import Any, AnyStr, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated + +__all__ = [ + "copyfileobj", + "copyfile", + "copymode", + "copystat", + "copy", + "copy2", + "copytree", + "move", + "rmtree", + "Error", + "SpecialFileError", + "make_archive", + "get_archive_formats", + "register_archive_format", + "unregister_archive_format", + "get_unpack_formats", + "register_unpack_format", + "unregister_unpack_format", + "unpack_archive", + "ignore_patterns", + "chown", + "which", + "get_terminal_size", + "SameFileError", + "disk_usage", +] +if sys.version_info < (3, 14): + __all__ += ["ExecError"] + +_StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) + +class Error(OSError): ... +class SameFileError(Error): ... +class SpecialFileError(OSError): ... + +if sys.version_info >= (3, 14): + ExecError = RuntimeError # Deprecated in Python 3.14; removal scheduled for Python 3.16 + +else: + class ExecError(OSError): ... + +class ReadError(OSError): ... +class RegistryError(Exception): ... + +def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: ... +def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: ... +def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... +def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... + +@overload +def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... +@overload +def copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... + +@overload +def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... +@overload +def copy2(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... + +def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... +def copytree( + src: StrPath, + dst: _StrPathT, + symlinks: bool = False, + ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, + copy_function: Callable[[str, str], object] = ..., + ignore_dangling_symlinks: bool = False, + dirs_exist_ok: bool = False, +) -> _StrPathT: ... + +_OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, ExcInfo], object] +_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object] + +@type_check_only +class _RmtreeType(Protocol): + avoids_symlink_attacks: bool + if sys.version_info >= (3, 12): + @overload + @deprecated("The `onerror` parameter is deprecated. Use `onexc` instead.") + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool, + onerror: _OnErrorCallback | None, + *, + onexc: None = None, + dir_fd: int | None = None, + ) -> None: ... + @overload + @deprecated("The `onerror` parameter is deprecated. Use `onexc` instead.") + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + *, + onerror: _OnErrorCallback | None, + onexc: None = None, + dir_fd: int | None = None, + ) -> None: ... + @overload + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + *, + onexc: _OnExcCallback | None = None, + dir_fd: int | None = None, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __call__( + self, + path: StrOrBytesPath, + ignore_errors: bool = False, + onerror: _OnErrorCallback | None = None, + *, + dir_fd: int | None = None, + ) -> None: ... + + else: + def __call__( + self, path: StrOrBytesPath, ignore_errors: bool = False, onerror: _OnErrorCallback | None = None + ) -> None: ... + +rmtree: _RmtreeType + +_CopyFn: TypeAlias = Callable[[str, str], object] | Callable[[StrPath, StrPath], object] + +# N.B. shutil.move appears to take bytes arguments, however, +# this does not work when dst is (or is within) an existing directory. +# (#6832) +def move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPathT | str | MaybeNone: ... + +class _ntuple_diskusage(NamedTuple): + total: int + used: int + free: int + +def disk_usage(path: FileDescriptorOrPath) -> _ntuple_diskusage: ... + +# While chown can be imported on Windows, it doesn't actually work; +# see https://bugs.python.org/issue33140. We keep it here because it's +# in __all__. +if sys.version_info >= (3, 13): + @overload + def chown( + path: FileDescriptorOrPath, + user: str | int, + group: None = None, + *, + dir_fd: int | None = None, + follow_symlinks: bool = True, + ) -> None: ... + @overload + def chown( + path: FileDescriptorOrPath, + user: None = None, + *, + group: str | int, + dir_fd: int | None = None, + follow_symlinks: bool = True, + ) -> None: ... + @overload + def chown( + path: FileDescriptorOrPath, user: None, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... + @overload + def chown( + path: FileDescriptorOrPath, user: str | int, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> None: ... +else: + @overload + def chown(path: FileDescriptorOrPath, user: str | int, group: None = None) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: None = None, *, group: str | int) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: None, group: str | int) -> None: ... + @overload + def chown(path: FileDescriptorOrPath, user: str | int, group: str | int) -> None: ... + +if sys.platform == "win32" and sys.version_info < (3, 12): + @overload + @deprecated("On Windows before Python 3.12, using a PathLike as `cmd` would always fail or return `None`.") + def which(cmd: os.PathLike[str], mode: int = 1, path: StrPath | None = None) -> Never: ... + +@overload +def which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: ... +@overload +def which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ... + +def make_archive( + base_name: str, + format: str, + root_dir: StrPath | None = None, + base_dir: StrPath | None = None, + verbose: bool = ..., + dry_run: bool = ..., + owner: str | None = None, + group: str | None = None, + logger: Any | None = None, +) -> str: ... +def get_archive_formats() -> list[tuple[str, str]]: ... + +@overload +def register_archive_format( + name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = "" +) -> None: ... +@overload +def register_archive_format( + name: str, function: Callable[[str, str], object], extra_args: None = None, description: str = "" +) -> None: ... + +def unregister_archive_format(name: str) -> None: ... +def unpack_archive( + filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None +) -> None: ... + +@overload +def register_unpack_format( + name: str, + extensions: list[str], + function: Callable[..., object], + extra_args: Sequence[tuple[str, Any]], + description: str = "", +) -> None: ... +@overload +def register_unpack_format( + name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = None, description: str = "" +) -> None: ... + +def unregister_unpack_format(name: str) -> None: ... +def get_unpack_formats() -> list[tuple[str, list[str], str]]: ... +def get_terminal_size(fallback: tuple[int, int] = (80, 24)) -> os.terminal_size: ... diff --git a/stdlib/signal.pyi b/stdlib/signal.pyi new file mode 100644 index 000000000000..a6a8853671e2 --- /dev/null +++ b/stdlib/signal.pyi @@ -0,0 +1,174 @@ +import sys +from _typeshed import structseq +from collections.abc import Callable, Iterable +from enum import IntEnum +from types import FrameType +from typing import Any, Final, TypeAlias, final +from typing_extensions import Never + +NSIG: int + +class Signals(IntEnum): + SIGFPE = 8 + SIGILL = 4 + SIGINT = 2 + SIGSEGV = 11 + SIGTERM = 15 + + if sys.platform == "win32": + SIGABRT = 22 + SIGBREAK = 21 + CTRL_C_EVENT = 0 + CTRL_BREAK_EVENT = 1 + else: + SIGABRT = 6 + SIGALRM = 14 + SIGBUS = 7 + SIGCHLD = 17 + SIGCONT = 18 + SIGHUP = 1 + SIGIO = 29 + SIGIOT = 6 + SIGKILL = 9 + SIGPIPE = 13 + SIGPROF = 27 + SIGQUIT = 3 + SIGSTOP = 19 + SIGSYS = 31 + SIGTRAP = 5 + SIGTSTP = 20 + SIGTTIN = 21 + SIGTTOU = 22 + SIGURG = 23 + SIGUSR1 = 10 + SIGUSR2 = 12 + SIGVTALRM = 26 + SIGWINCH = 28 + SIGXCPU = 24 + SIGXFSZ = 25 + if sys.platform != "linux": + SIGEMT = 7 + SIGINFO = 29 + if sys.platform != "darwin": + SIGCLD = 17 + SIGPOLL = 29 + SIGPWR = 30 + SIGRTMAX = 64 + SIGRTMIN = 34 + if sys.version_info >= (3, 11): + SIGSTKFLT = 16 + +class Handlers(IntEnum): + SIG_DFL = 0 + SIG_IGN = 1 + +SIG_DFL: Final = Handlers.SIG_DFL +SIG_IGN: Final = Handlers.SIG_IGN + +_SIGNUM: TypeAlias = int | Signals +_HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None + +def default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: ... +def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... +def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... + +SIGABRT: Final = Signals.SIGABRT +SIGFPE: Final = Signals.SIGFPE +SIGILL: Final = Signals.SIGILL +SIGINT: Final = Signals.SIGINT +SIGSEGV: Final = Signals.SIGSEGV +SIGTERM: Final = Signals.SIGTERM + +if sys.platform == "win32": + SIGBREAK: Final = Signals.SIGBREAK + CTRL_C_EVENT: Final = Signals.CTRL_C_EVENT + CTRL_BREAK_EVENT: Final = Signals.CTRL_BREAK_EVENT +else: + if sys.platform != "linux": + SIGINFO: Final = Signals.SIGINFO + SIGEMT: Final = Signals.SIGEMT + SIGALRM: Final = Signals.SIGALRM + SIGBUS: Final = Signals.SIGBUS + SIGCHLD: Final = Signals.SIGCHLD + SIGCONT: Final = Signals.SIGCONT + SIGHUP: Final = Signals.SIGHUP + SIGIO: Final = Signals.SIGIO + SIGIOT: Final = Signals.SIGABRT # alias + SIGKILL: Final = Signals.SIGKILL + SIGPIPE: Final = Signals.SIGPIPE + SIGPROF: Final = Signals.SIGPROF + SIGQUIT: Final = Signals.SIGQUIT + SIGSTOP: Final = Signals.SIGSTOP + SIGSYS: Final = Signals.SIGSYS + SIGTRAP: Final = Signals.SIGTRAP + SIGTSTP: Final = Signals.SIGTSTP + SIGTTIN: Final = Signals.SIGTTIN + SIGTTOU: Final = Signals.SIGTTOU + SIGURG: Final = Signals.SIGURG + SIGUSR1: Final = Signals.SIGUSR1 + SIGUSR2: Final = Signals.SIGUSR2 + SIGVTALRM: Final = Signals.SIGVTALRM + SIGWINCH: Final = Signals.SIGWINCH + SIGXCPU: Final = Signals.SIGXCPU + SIGXFSZ: Final = Signals.SIGXFSZ + + class ItimerError(OSError): ... + ITIMER_PROF: int + ITIMER_REAL: int + ITIMER_VIRTUAL: int + + class Sigmasks(IntEnum): + SIG_BLOCK = 0 + SIG_UNBLOCK = 1 + SIG_SETMASK = 2 + + SIG_BLOCK: Final = Sigmasks.SIG_BLOCK + SIG_UNBLOCK: Final = Sigmasks.SIG_UNBLOCK + SIG_SETMASK: Final = Sigmasks.SIG_SETMASK + def alarm(seconds: int, /) -> int: ... + def getitimer(which: int, /) -> tuple[float, float]: ... + def pause() -> None: ... + def pthread_kill(thread_id: int, signalnum: int, /) -> None: ... + def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... + def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: ... + def siginterrupt(signalnum: int, flag: bool, /) -> None: ... + def sigpending() -> Any: ... + def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... + if sys.platform != "darwin": + SIGCLD: Final = Signals.SIGCHLD # alias + SIGPOLL: Final = Signals.SIGIO # alias + SIGPWR: Final = Signals.SIGPWR + SIGRTMAX: Final = Signals.SIGRTMAX + SIGRTMIN: Final = Signals.SIGRTMIN + if sys.version_info >= (3, 11): + SIGSTKFLT: Final = Signals.SIGSTKFLT + + @final + class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): + __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") + + @property + def si_signo(self) -> int: ... + @property + def si_code(self) -> int: ... + @property + def si_errno(self) -> int: ... + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_band(self) -> int: ... + + def sigtimedwait(sigset: Iterable[int], timeout: float, /) -> struct_siginfo | None: ... + def sigwaitinfo(sigset: Iterable[int], /) -> struct_siginfo: ... + +def strsignal(signalnum: _SIGNUM, /) -> str | None: ... +def valid_signals() -> set[Signals]: ... +def raise_signal(signalnum: _SIGNUM, /) -> None: ... +def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = True) -> int: ... + +if sys.platform == "linux": + def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = 0, /) -> None: ... diff --git a/stdlib/site.pyi b/stdlib/site.pyi new file mode 100644 index 000000000000..46e82b0655c1 --- /dev/null +++ b/stdlib/site.pyi @@ -0,0 +1,46 @@ +import sys +from _typeshed import StrPath +from collections.abc import Iterable + +PREFIXES: list[str] +ENABLE_USER_SITE: bool | None +USER_SITE: str | None +USER_BASE: str | None + +def main() -> None: ... +def abs_paths() -> None: ... # undocumented +def addpackage(sitedir: StrPath, name: StrPath, known_paths: set[str] | None) -> set[str] | None: ... # undocumented + +if sys.version_info >= (3, 15): + class StartupState: + __slots__ = ("_known_paths", "_processed_sitedirs", "_path_entries", "_importexecs", "_entrypoints") + def __init__(self, known_paths: set[str] | None = None) -> None: ... + def addsitedir(self, sitedir: str) -> None: ... + def addusersitepackages(self) -> None: ... + def addsitepackages(self, prefixes: Iterable[str] | None = None) -> None: ... + def process(self) -> None: ... + +def addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: ... +def addsitepackages(known_paths: set[str] | None, prefixes: Iterable[str] | None = None) -> set[str] | None: ... # undocumented +def addusersitepackages(known_paths: set[str] | None) -> set[str] | None: ... # undocumented +def check_enableusersite() -> bool | None: ... # undocumented + +if sys.version_info >= (3, 13): + def gethistoryfile() -> str: ... # undocumented + +def enablerlcompleter() -> None: ... # undocumented + +if sys.version_info >= (3, 13): + def register_readline() -> None: ... # undocumented + +def execsitecustomize() -> None: ... # undocumented +def execusercustomize() -> None: ... # undocumented +def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ... +def getuserbase() -> str: ... +def getusersitepackages() -> str: ... +def makepath(*paths: StrPath) -> tuple[str, str]: ... # undocumented +def removeduppaths() -> set[str]: ... # undocumented +def setcopyright() -> None: ... # undocumented +def sethelper() -> None: ... # undocumented +def setquit() -> None: ... # undocumented +def venv(known_paths: set[str] | None) -> set[str] | None: ... # undocumented diff --git a/stdlib/smtpd.pyi b/stdlib/smtpd.pyi new file mode 100644 index 000000000000..cc9ac391a441 --- /dev/null +++ b/stdlib/smtpd.pyi @@ -0,0 +1,92 @@ +import asynchat +import asyncore +import socket +import sys +from collections import defaultdict +from typing import Any, TypeAlias +from typing_extensions import deprecated + +if sys.version_info >= (3, 11): + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy"] +else: + __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy", "MailmanProxy"] + +_Address: TypeAlias = tuple[str, int] # (host, port) + +class SMTPChannel(asynchat.async_chat): + COMMAND: int + DATA: int + + command_size_limits: defaultdict[str, int] + smtp_server: SMTPServer + conn: socket.socket + addr: Any + received_lines: list[str] + smtp_state: int + seen_greeting: str + mailfrom: str + rcpttos: list[str] + received_data: str + fqdn: str + peer: str + + command_size_limit: int + data_size_limit: int + + enable_SMTPUTF8: bool + @property + def max_command_size_limit(self) -> int: ... + def __init__( + self, + server: SMTPServer, + conn: socket.socket, + addr: Any, + data_size_limit: int = 33554432, + map: asyncore._MapType | None = None, + enable_SMTPUTF8: bool = False, + decode_data: bool = False, + ) -> None: ... + # base asynchat.async_chat.push() accepts bytes + def push(self, msg: str) -> None: ... # type: ignore[override] + def collect_incoming_data(self, data: bytes) -> None: ... + def found_terminator(self) -> None: ... + def smtp_HELO(self, arg: str) -> None: ... + def smtp_NOOP(self, arg: str) -> None: ... + def smtp_QUIT(self, arg: str) -> None: ... + def smtp_MAIL(self, arg: str) -> None: ... + def smtp_RCPT(self, arg: str) -> None: ... + def smtp_RSET(self, arg: str) -> None: ... + def smtp_DATA(self, arg: str) -> None: ... + def smtp_EHLO(self, arg: str) -> None: ... + def smtp_HELP(self, arg: str) -> None: ... + def smtp_VRFY(self, arg: str) -> None: ... + def smtp_EXPN(self, arg: str) -> None: ... + +class SMTPServer(asyncore.dispatcher): + channel_class: type[SMTPChannel] + + data_size_limit: int + enable_SMTPUTF8: bool + def __init__( + self, + localaddr: _Address, + remoteaddr: _Address, + data_size_limit: int = 33554432, + map: asyncore._MapType | None = None, + enable_SMTPUTF8: bool = False, + decode_data: bool = False, + ) -> None: ... + def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... + def process_message( + self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str, **kwargs: Any + ) -> str | None: ... + +class DebuggingServer(SMTPServer): ... + +class PureProxy(SMTPServer): + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] + +if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") + class MailmanProxy(PureProxy): + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] diff --git a/stdlib/smtplib.pyi b/stdlib/smtplib.pyi new file mode 100644 index 000000000000..1aaa5b49664b --- /dev/null +++ b/stdlib/smtplib.pyi @@ -0,0 +1,223 @@ +import sys +from _socket import _Address as _SourceAddress +from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath +from collections.abc import Sequence +from email.message import Message as _Message +from re import Pattern +from socket import socket +from ssl import SSLContext +from types import TracebackType +from typing import Any, Final, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +__all__ = [ + "SMTPException", + "SMTPServerDisconnected", + "SMTPResponseException", + "SMTPSenderRefused", + "SMTPRecipientsRefused", + "SMTPDataError", + "SMTPConnectError", + "SMTPHeloError", + "SMTPAuthenticationError", + "quoteaddr", + "quotedata", + "SMTP", + "SMTP_SSL", + "SMTPNotSupportedError", +] + +_Reply: TypeAlias = tuple[int, bytes] +_SendErrs: TypeAlias = dict[str, _Reply] + +SMTP_PORT: Final = 25 +SMTP_SSL_PORT: Final = 465 +CRLF: Final[str] +bCRLF: Final[bytes] + +OLDSTYLE_AUTH: Final[Pattern[str]] + +class SMTPException(OSError): ... +class SMTPNotSupportedError(SMTPException): ... +class SMTPServerDisconnected(SMTPException): ... + +class SMTPResponseException(SMTPException): + smtp_code: int + smtp_error: bytes | str + args: tuple[int, bytes | str] | tuple[int, bytes, str] + def __init__(self, code: int, msg: bytes | str) -> None: ... + +class SMTPSenderRefused(SMTPResponseException): + smtp_error: bytes + sender: str + args: tuple[int, bytes, str] + def __init__(self, code: int, msg: bytes, sender: str) -> None: ... + +class SMTPRecipientsRefused(SMTPException): + recipients: _SendErrs + args: tuple[_SendErrs] + def __init__(self, recipients: _SendErrs) -> None: ... + +class SMTPDataError(SMTPResponseException): ... +class SMTPConnectError(SMTPResponseException): ... +class SMTPHeloError(SMTPResponseException): ... +class SMTPAuthenticationError(SMTPResponseException): ... + +def quoteaddr(addrstring: str) -> str: ... +def quotedata(data: str) -> str: ... + +@type_check_only +class _AuthObject(Protocol): + @overload + def __call__(self, challenge: None = None, /) -> str | None: ... + @overload + def __call__(self, challenge: bytes, /) -> str: ... + +class SMTP: + debuglevel: int + sock: socket | None + # Type of file should match what socket.makefile() returns + file: Any | None + helo_resp: bytes | None + ehlo_msg: str + ehlo_resp: bytes | None + does_esmtp: bool + default_port: int + timeout: float + esmtp_features: dict[str, str] + command_encoding: str + source_address: _SourceAddress | None + local_hostname: str + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + def connect(self, host: str = "localhost", port: int = 0, source_address: _SourceAddress | None = None) -> _Reply: ... + def send(self, s: ReadableBuffer | str) -> None: ... + def putcmd(self, cmd: str, args: str = "") -> None: ... + def getreply(self) -> _Reply: ... + def docmd(self, cmd: str, args: str = "") -> _Reply: ... + def helo(self, name: str = "") -> _Reply: ... + def ehlo(self, name: str = "") -> _Reply: ... + def has_extn(self, opt: str) -> bool: ... + def help(self, args: str = "") -> bytes: ... + def rset(self) -> _Reply: ... + def noop(self) -> _Reply: ... + def mail(self, sender: str, options: Sequence[str] = ()) -> _Reply: ... + def rcpt(self, recip: str, options: Sequence[str] = ()) -> _Reply: ... + def data(self, msg: ReadableBuffer | str) -> _Reply: ... + def verify(self, address: str) -> _Reply: ... + vrfy = verify + def expn(self, address: str) -> _Reply: ... + def ehlo_or_helo_if_needed(self) -> None: ... + user: str + password: str + def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = True) -> _Reply: ... + + @overload + def auth_cram_md5(self, challenge: None = None) -> None: ... + @overload + def auth_cram_md5(self, challenge: ReadableBuffer) -> str: ... + + def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: ... + def auth_login(self, challenge: ReadableBuffer | None = None) -> str: ... + def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: ... + if sys.version_info >= (3, 12): + def starttls(self, *, context: SSLContext | None = None) -> _Reply: ... + else: + @overload + def starttls(self, keyfile: None = None, certfile: None = None, context: SSLContext | None = None) -> _Reply: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def starttls( + self, keyfile: StrOrBytesPath | None = None, certfile: StrOrBytesPath | None = None, context: None = None + ) -> _Reply: ... + + def sendmail( + self, + from_addr: str, + to_addrs: str | Sequence[str], + msg: SizedBuffer | str, + mail_options: Sequence[str] = (), + rcpt_options: Sequence[str] = (), + ) -> _SendErrs: ... + def send_message( + self, + msg: _Message, + from_addr: str | None = None, + to_addrs: str | Sequence[str] | None = None, + mail_options: Sequence[str] = (), + rcpt_options: Sequence[str] = (), + ) -> _SendErrs: ... + def close(self) -> None: ... + def quit(self) -> _Reply: ... + +class SMTP_SSL(SMTP): + context: SSLContext + if sys.version_info >= (3, 12): + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + *, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, + ) -> None: ... + else: + @overload + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + keyfile: None = None, + certfile: None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: SSLContext | None = None, + ) -> None: ... + @overload + @deprecated( + "The `keyfile`, `certfile` parameters are deprecated since Python 3.6; " + "removed in Python 3.12. Use `context` parameter instead." + ) + def __init__( + self, + host: str = "", + port: int = 0, + local_hostname: str | None = None, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + timeout: float = ..., + source_address: _SourceAddress | None = None, + context: None = None, + ) -> None: ... + + keyfile: StrOrBytesPath | None + certfile: StrOrBytesPath | None + +LMTP_PORT: Final = 2003 + +class LMTP(SMTP): + def __init__( + self, + host: str = "", + port: int = 2003, + local_hostname: str | None = None, + source_address: _SourceAddress | None = None, + timeout: float = ..., + ) -> None: ... diff --git a/stdlib/sndhdr.pyi b/stdlib/sndhdr.pyi new file mode 100644 index 000000000000..f4d487607fbb --- /dev/null +++ b/stdlib/sndhdr.pyi @@ -0,0 +1,14 @@ +from _typeshed import StrOrBytesPath +from typing import NamedTuple + +__all__ = ["what", "whathdr"] + +class SndHeaders(NamedTuple): + filetype: str + framerate: int + nchannels: int + nframes: int + sampwidth: int | str + +def what(filename: StrOrBytesPath) -> SndHeaders | None: ... +def whathdr(filename: StrOrBytesPath) -> SndHeaders | None: ... diff --git a/stdlib/socket.pyi b/stdlib/socket.pyi new file mode 100644 index 000000000000..ed2873726ff1 --- /dev/null +++ b/stdlib/socket.pyi @@ -0,0 +1,1586 @@ +# Ideally, we'd just do "from _socket import *". Unfortunately, socket +# overrides some definitions from _socket incompatibly. mypy incorrectly +# prefers the definitions from _socket over those defined here. +import _socket +import sys +from _socket import ( + CAPI as CAPI, + EAI_AGAIN as EAI_AGAIN, + EAI_BADFLAGS as EAI_BADFLAGS, + EAI_FAIL as EAI_FAIL, + EAI_FAMILY as EAI_FAMILY, + EAI_MEMORY as EAI_MEMORY, + EAI_NODATA as EAI_NODATA, + EAI_NONAME as EAI_NONAME, + EAI_SERVICE as EAI_SERVICE, + EAI_SOCKTYPE as EAI_SOCKTYPE, + INADDR_ALLHOSTS_GROUP as INADDR_ALLHOSTS_GROUP, + INADDR_ANY as INADDR_ANY, + INADDR_BROADCAST as INADDR_BROADCAST, + INADDR_LOOPBACK as INADDR_LOOPBACK, + INADDR_MAX_LOCAL_GROUP as INADDR_MAX_LOCAL_GROUP, + INADDR_NONE as INADDR_NONE, + INADDR_UNSPEC_GROUP as INADDR_UNSPEC_GROUP, + IP_ADD_MEMBERSHIP as IP_ADD_MEMBERSHIP, + IP_DROP_MEMBERSHIP as IP_DROP_MEMBERSHIP, + IP_HDRINCL as IP_HDRINCL, + IP_MULTICAST_IF as IP_MULTICAST_IF, + IP_MULTICAST_LOOP as IP_MULTICAST_LOOP, + IP_MULTICAST_TTL as IP_MULTICAST_TTL, + IP_OPTIONS as IP_OPTIONS, + IP_RECVTOS as IP_RECVTOS, + IP_TOS as IP_TOS, + IP_TTL as IP_TTL, + IPPORT_RESERVED as IPPORT_RESERVED, + IPPORT_USERRESERVED as IPPORT_USERRESERVED, + IPPROTO_AH as IPPROTO_AH, + IPPROTO_DSTOPTS as IPPROTO_DSTOPTS, + IPPROTO_EGP as IPPROTO_EGP, + IPPROTO_ESP as IPPROTO_ESP, + IPPROTO_FRAGMENT as IPPROTO_FRAGMENT, + IPPROTO_HOPOPTS as IPPROTO_HOPOPTS, + IPPROTO_ICMP as IPPROTO_ICMP, + IPPROTO_ICMPV6 as IPPROTO_ICMPV6, + IPPROTO_IDP as IPPROTO_IDP, + IPPROTO_IGMP as IPPROTO_IGMP, + IPPROTO_IP as IPPROTO_IP, + IPPROTO_IPV6 as IPPROTO_IPV6, + IPPROTO_NONE as IPPROTO_NONE, + IPPROTO_PIM as IPPROTO_PIM, + IPPROTO_PUP as IPPROTO_PUP, + IPPROTO_RAW as IPPROTO_RAW, + IPPROTO_ROUTING as IPPROTO_ROUTING, + IPPROTO_SCTP as IPPROTO_SCTP, + IPPROTO_TCP as IPPROTO_TCP, + IPPROTO_UDP as IPPROTO_UDP, + IPV6_CHECKSUM as IPV6_CHECKSUM, + IPV6_DONTFRAG as IPV6_DONTFRAG, + IPV6_HOPLIMIT as IPV6_HOPLIMIT, + IPV6_HOPOPTS as IPV6_HOPOPTS, + IPV6_JOIN_GROUP as IPV6_JOIN_GROUP, + IPV6_LEAVE_GROUP as IPV6_LEAVE_GROUP, + IPV6_MULTICAST_HOPS as IPV6_MULTICAST_HOPS, + IPV6_MULTICAST_IF as IPV6_MULTICAST_IF, + IPV6_MULTICAST_LOOP as IPV6_MULTICAST_LOOP, + IPV6_PKTINFO as IPV6_PKTINFO, + IPV6_RECVRTHDR as IPV6_RECVRTHDR, + IPV6_RECVTCLASS as IPV6_RECVTCLASS, + IPV6_RTHDR as IPV6_RTHDR, + IPV6_TCLASS as IPV6_TCLASS, + IPV6_UNICAST_HOPS as IPV6_UNICAST_HOPS, + IPV6_V6ONLY as IPV6_V6ONLY, + NI_DGRAM as NI_DGRAM, + NI_MAXHOST as NI_MAXHOST, + NI_MAXSERV as NI_MAXSERV, + NI_NAMEREQD as NI_NAMEREQD, + NI_NOFQDN as NI_NOFQDN, + NI_NUMERICHOST as NI_NUMERICHOST, + NI_NUMERICSERV as NI_NUMERICSERV, + SHUT_RD as SHUT_RD, + SHUT_RDWR as SHUT_RDWR, + SHUT_WR as SHUT_WR, + SO_ACCEPTCONN as SO_ACCEPTCONN, + SO_BROADCAST as SO_BROADCAST, + SO_DEBUG as SO_DEBUG, + SO_DONTROUTE as SO_DONTROUTE, + SO_ERROR as SO_ERROR, + SO_KEEPALIVE as SO_KEEPALIVE, + SO_LINGER as SO_LINGER, + SO_OOBINLINE as SO_OOBINLINE, + SO_RCVBUF as SO_RCVBUF, + SO_RCVLOWAT as SO_RCVLOWAT, + SO_RCVTIMEO as SO_RCVTIMEO, + SO_REUSEADDR as SO_REUSEADDR, + SO_SNDBUF as SO_SNDBUF, + SO_SNDLOWAT as SO_SNDLOWAT, + SO_SNDTIMEO as SO_SNDTIMEO, + SO_TYPE as SO_TYPE, + SOL_IP as SOL_IP, + SOL_SOCKET as SOL_SOCKET, + SOL_TCP as SOL_TCP, + SOL_UDP as SOL_UDP, + SOMAXCONN as SOMAXCONN, + TCP_FASTOPEN as TCP_FASTOPEN, + TCP_KEEPCNT as TCP_KEEPCNT, + TCP_KEEPINTVL as TCP_KEEPINTVL, + TCP_MAXSEG as TCP_MAXSEG, + TCP_NODELAY as TCP_NODELAY, + SocketType as SocketType, + _Address as _Address, + _RetAddress as _RetAddress, + close as close, + dup as dup, + getdefaulttimeout as getdefaulttimeout, + gethostbyaddr as gethostbyaddr, + gethostbyname as gethostbyname, + gethostbyname_ex as gethostbyname_ex, + gethostname as gethostname, + getnameinfo as getnameinfo, + getprotobyname as getprotobyname, + getservbyname as getservbyname, + getservbyport as getservbyport, + has_ipv6 as has_ipv6, + htonl as htonl, + htons as htons, + if_indextoname as if_indextoname, + if_nameindex as if_nameindex, + if_nametoindex as if_nametoindex, + inet_aton as inet_aton, + inet_ntoa as inet_ntoa, + inet_ntop as inet_ntop, + inet_pton as inet_pton, + ntohl as ntohl, + ntohs as ntohs, + setdefaulttimeout as setdefaulttimeout, +) +from _typeshed import ReadableBuffer, Unused, WriteableBuffer +from collections.abc import Iterable +from enum import IntEnum, IntFlag +from io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper +from typing import Any, Final, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "fromfd", + "getfqdn", + "create_connection", + "create_server", + "has_dualstack_ipv6", + "AddressFamily", + "SocketKind", + "AF_APPLETALK", + "AF_DECnet", + "AF_INET", + "AF_INET6", + "AF_IPX", + "AF_SNA", + "AF_UNSPEC", + "AI_ADDRCONFIG", + "AI_ALL", + "AI_CANONNAME", + "AI_NUMERICHOST", + "AI_NUMERICSERV", + "AI_PASSIVE", + "AI_V4MAPPED", + "CAPI", + "EAI_AGAIN", + "EAI_BADFLAGS", + "EAI_FAIL", + "EAI_FAMILY", + "EAI_MEMORY", + "EAI_NODATA", + "EAI_NONAME", + "EAI_SERVICE", + "EAI_SOCKTYPE", + "INADDR_ALLHOSTS_GROUP", + "INADDR_ANY", + "INADDR_BROADCAST", + "INADDR_LOOPBACK", + "INADDR_MAX_LOCAL_GROUP", + "INADDR_NONE", + "INADDR_UNSPEC_GROUP", + "IPPORT_RESERVED", + "IPPORT_USERRESERVED", + "IPPROTO_AH", + "IPPROTO_DSTOPTS", + "IPPROTO_EGP", + "IPPROTO_ESP", + "IPPROTO_FRAGMENT", + "IPPROTO_HOPOPTS", + "IPPROTO_ICMP", + "IPPROTO_ICMPV6", + "IPPROTO_IDP", + "IPPROTO_IGMP", + "IPPROTO_IP", + "IPPROTO_IPV6", + "IPPROTO_NONE", + "IPPROTO_PIM", + "IPPROTO_PUP", + "IPPROTO_RAW", + "IPPROTO_ROUTING", + "IPPROTO_SCTP", + "IPPROTO_TCP", + "IPPROTO_UDP", + "IPV6_CHECKSUM", + "IPV6_DONTFRAG", + "IPV6_HOPLIMIT", + "IPV6_HOPOPTS", + "IPV6_JOIN_GROUP", + "IPV6_LEAVE_GROUP", + "IPV6_MULTICAST_HOPS", + "IPV6_MULTICAST_IF", + "IPV6_MULTICAST_LOOP", + "IPV6_PKTINFO", + "IPV6_RECVRTHDR", + "IPV6_RECVTCLASS", + "IPV6_RTHDR", + "IPV6_TCLASS", + "IPV6_UNICAST_HOPS", + "IPV6_V6ONLY", + "IP_ADD_MEMBERSHIP", + "IP_DROP_MEMBERSHIP", + "IP_HDRINCL", + "IP_MULTICAST_IF", + "IP_MULTICAST_LOOP", + "IP_MULTICAST_TTL", + "IP_OPTIONS", + "IP_RECVTOS", + "IP_TOS", + "IP_TTL", + "MSG_CTRUNC", + "MSG_DONTROUTE", + "MSG_OOB", + "MSG_PEEK", + "MSG_TRUNC", + "MSG_WAITALL", + "NI_DGRAM", + "NI_MAXHOST", + "NI_MAXSERV", + "NI_NAMEREQD", + "NI_NOFQDN", + "NI_NUMERICHOST", + "NI_NUMERICSERV", + "SHUT_RD", + "SHUT_RDWR", + "SHUT_WR", + "SOCK_DGRAM", + "SOCK_RAW", + "SOCK_RDM", + "SOCK_SEQPACKET", + "SOCK_STREAM", + "SOL_IP", + "SOL_SOCKET", + "SOL_TCP", + "SOL_UDP", + "SOMAXCONN", + "SO_ACCEPTCONN", + "SO_BROADCAST", + "SO_DEBUG", + "SO_DONTROUTE", + "SO_ERROR", + "SO_KEEPALIVE", + "SO_LINGER", + "SO_OOBINLINE", + "SO_RCVBUF", + "SO_RCVLOWAT", + "SO_RCVTIMEO", + "SO_REUSEADDR", + "SO_SNDBUF", + "SO_SNDLOWAT", + "SO_SNDTIMEO", + "SO_TYPE", + "SocketType", + "TCP_FASTOPEN", + "TCP_KEEPCNT", + "TCP_KEEPINTVL", + "TCP_MAXSEG", + "TCP_NODELAY", + "close", + "dup", + "error", + "gaierror", + "getaddrinfo", + "getdefaulttimeout", + "gethostbyaddr", + "gethostbyname", + "gethostbyname_ex", + "gethostname", + "getnameinfo", + "getprotobyname", + "getservbyname", + "getservbyport", + "has_ipv6", + "herror", + "htonl", + "htons", + "if_indextoname", + "if_nameindex", + "if_nametoindex", + "inet_aton", + "inet_ntoa", + "inet_ntop", + "inet_pton", + "ntohl", + "ntohs", + "setdefaulttimeout", + "socket", + "socketpair", + "timeout", +] + +if sys.platform == "win32": + from _socket import ( + IPPROTO_CBT as IPPROTO_CBT, + IPPROTO_ICLFXBM as IPPROTO_ICLFXBM, + IPPROTO_IGP as IPPROTO_IGP, + IPPROTO_L2TP as IPPROTO_L2TP, + IPPROTO_PGM as IPPROTO_PGM, + IPPROTO_RDP as IPPROTO_RDP, + IPPROTO_ST as IPPROTO_ST, + RCVALL_MAX as RCVALL_MAX, + RCVALL_OFF as RCVALL_OFF, + RCVALL_ON as RCVALL_ON, + RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY, + SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS, + SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH, + SIO_RCVALL as SIO_RCVALL, + SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE, + ) + + __all__ += [ + "IPPROTO_CBT", + "IPPROTO_ICLFXBM", + "IPPROTO_IGP", + "IPPROTO_L2TP", + "IPPROTO_PGM", + "IPPROTO_RDP", + "IPPROTO_ST", + "RCVALL_MAX", + "RCVALL_OFF", + "RCVALL_ON", + "RCVALL_SOCKETLEVELONLY", + "SIO_KEEPALIVE_VALS", + "SIO_LOOPBACK_FAST_PATH", + "SIO_RCVALL", + "SO_EXCLUSIVEADDRUSE", + "fromshare", + "errorTab", + "MSG_BCAST", + "MSG_MCAST", + ] + +if sys.platform == "darwin": + from _socket import PF_SYSTEM as PF_SYSTEM, SYSPROTO_CONTROL as SYSPROTO_CONTROL + + __all__ += ["PF_SYSTEM", "SYSPROTO_CONTROL", "AF_SYSTEM"] + +if sys.platform != "darwin": + from _socket import TCP_KEEPIDLE as TCP_KEEPIDLE + + __all__ += ["TCP_KEEPIDLE", "AF_IRDA", "MSG_ERRQUEUE"] + +if sys.platform != "win32" and sys.platform != "darwin": + from _socket import ( + IP_TRANSPARENT as IP_TRANSPARENT, + IPX_TYPE as IPX_TYPE, + SCM_CREDENTIALS as SCM_CREDENTIALS, + SO_DOMAIN as SO_DOMAIN, + SO_MARK as SO_MARK, + SO_PASSCRED as SO_PASSCRED, + SO_PASSSEC as SO_PASSSEC, + SO_PEERCRED as SO_PEERCRED, + SO_PEERSEC as SO_PEERSEC, + SO_PRIORITY as SO_PRIORITY, + SO_PROTOCOL as SO_PROTOCOL, + SOL_ATALK as SOL_ATALK, + SOL_AX25 as SOL_AX25, + SOL_HCI as SOL_HCI, + SOL_IPX as SOL_IPX, + SOL_NETROM as SOL_NETROM, + SOL_ROSE as SOL_ROSE, + TCP_CONGESTION as TCP_CONGESTION, + TCP_CORK as TCP_CORK, + TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT, + TCP_INFO as TCP_INFO, + TCP_LINGER2 as TCP_LINGER2, + TCP_QUICKACK as TCP_QUICKACK, + TCP_SYNCNT as TCP_SYNCNT, + TCP_USER_TIMEOUT as TCP_USER_TIMEOUT, + TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP, + ) + + __all__ += [ + "IP_TRANSPARENT", + "SCM_CREDENTIALS", + "SO_DOMAIN", + "SO_MARK", + "SO_PASSCRED", + "SO_PASSSEC", + "SO_PEERCRED", + "SO_PEERSEC", + "SO_PRIORITY", + "SO_PROTOCOL", + "TCP_CONGESTION", + "TCP_CORK", + "TCP_DEFER_ACCEPT", + "TCP_INFO", + "TCP_LINGER2", + "TCP_QUICKACK", + "TCP_SYNCNT", + "TCP_USER_TIMEOUT", + "TCP_WINDOW_CLAMP", + "AF_ASH", + "AF_ATMPVC", + "AF_ATMSVC", + "AF_AX25", + "AF_BRIDGE", + "AF_ECONET", + "AF_KEY", + "AF_LLC", + "AF_NETBEUI", + "AF_NETROM", + "AF_PPPOX", + "AF_ROSE", + "AF_SECURITY", + "AF_WANPIPE", + "AF_X25", + "MSG_CMSG_CLOEXEC", + "MSG_CONFIRM", + "MSG_FASTOPEN", + "MSG_MORE", + ] + +if sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 11): + from _socket import IP_BIND_ADDRESS_NO_PORT as IP_BIND_ADDRESS_NO_PORT + + __all__ += ["IP_BIND_ADDRESS_NO_PORT"] + +if sys.platform != "win32": + from _socket import ( + CMSG_LEN as CMSG_LEN, + CMSG_SPACE as CMSG_SPACE, + EAI_ADDRFAMILY as EAI_ADDRFAMILY, + EAI_OVERFLOW as EAI_OVERFLOW, + EAI_SYSTEM as EAI_SYSTEM, + IP_DEFAULT_MULTICAST_LOOP as IP_DEFAULT_MULTICAST_LOOP, + IP_DEFAULT_MULTICAST_TTL as IP_DEFAULT_MULTICAST_TTL, + IP_MAX_MEMBERSHIPS as IP_MAX_MEMBERSHIPS, + IP_RECVOPTS as IP_RECVOPTS, + IP_RECVRETOPTS as IP_RECVRETOPTS, + IP_RETOPTS as IP_RETOPTS, + IPPROTO_GRE as IPPROTO_GRE, + IPPROTO_IPIP as IPPROTO_IPIP, + IPPROTO_RSVP as IPPROTO_RSVP, + IPPROTO_TP as IPPROTO_TP, + IPV6_RTHDR_TYPE_0 as IPV6_RTHDR_TYPE_0, + SCM_RIGHTS as SCM_RIGHTS, + SO_REUSEPORT as SO_REUSEPORT, + TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT, + sethostname as sethostname, + ) + + __all__ += [ + "CMSG_LEN", + "CMSG_SPACE", + "EAI_ADDRFAMILY", + "EAI_OVERFLOW", + "EAI_SYSTEM", + "IP_DEFAULT_MULTICAST_LOOP", + "IP_DEFAULT_MULTICAST_TTL", + "IP_MAX_MEMBERSHIPS", + "IP_RECVOPTS", + "IP_RECVRETOPTS", + "IP_RETOPTS", + "IPPROTO_GRE", + "IPPROTO_IPIP", + "IPPROTO_RSVP", + "IPPROTO_TP", + "IPV6_RTHDR_TYPE_0", + "SCM_RIGHTS", + "SO_REUSEPORT", + "TCP_NOTSENT_LOWAT", + "sethostname", + "AF_ROUTE", + "AF_UNIX", + "MSG_DONTWAIT", + "MSG_EOR", + "MSG_NOSIGNAL", + ] + + from _socket import ( + IPV6_DSTOPTS as IPV6_DSTOPTS, + IPV6_NEXTHOP as IPV6_NEXTHOP, + IPV6_PATHMTU as IPV6_PATHMTU, + IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, + IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, + IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, + IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, + IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, + IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, + ) + + __all__ += [ + "IPV6_DSTOPTS", + "IPV6_NEXTHOP", + "IPV6_PATHMTU", + "IPV6_RECVDSTOPTS", + "IPV6_RECVHOPLIMIT", + "IPV6_RECVHOPOPTS", + "IPV6_RECVPATHMTU", + "IPV6_RECVPKTINFO", + "IPV6_RTHDRDSTOPTS", + ] + + if sys.platform != "darwin" or sys.version_info >= (3, 13): + from _socket import SO_BINDTODEVICE as SO_BINDTODEVICE + + __all__ += ["SO_BINDTODEVICE"] + +if sys.platform != "darwin": + from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM + +if sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["BDADDR_ANY", "BDADDR_LOCAL", "BTPROTO_RFCOMM"] + +if sys.platform == "darwin": + from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE + + __all__ += ["TCP_KEEPALIVE"] + +if sys.platform == "darwin" and sys.version_info >= (3, 11): + from _socket import TCP_CONNECTION_INFO as TCP_CONNECTION_INFO + + __all__ += ["TCP_CONNECTION_INFO"] + +if sys.platform == "linux": + from _socket import ( + ALG_OP_DECRYPT as ALG_OP_DECRYPT, + ALG_OP_ENCRYPT as ALG_OP_ENCRYPT, + ALG_OP_SIGN as ALG_OP_SIGN, + ALG_OP_VERIFY as ALG_OP_VERIFY, + ALG_SET_AEAD_ASSOCLEN as ALG_SET_AEAD_ASSOCLEN, + ALG_SET_AEAD_AUTHSIZE as ALG_SET_AEAD_AUTHSIZE, + ALG_SET_IV as ALG_SET_IV, + ALG_SET_KEY as ALG_SET_KEY, + ALG_SET_OP as ALG_SET_OP, + ALG_SET_PUBKEY as ALG_SET_PUBKEY, + CAN_BCM as CAN_BCM, + CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME, + CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME, + CAN_BCM_RX_CHANGED as CAN_BCM_RX_CHANGED, + CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC, + CAN_BCM_RX_DELETE as CAN_BCM_RX_DELETE, + CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID, + CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER, + CAN_BCM_RX_READ as CAN_BCM_RX_READ, + CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME, + CAN_BCM_RX_SETUP as CAN_BCM_RX_SETUP, + CAN_BCM_RX_STATUS as CAN_BCM_RX_STATUS, + CAN_BCM_RX_TIMEOUT as CAN_BCM_RX_TIMEOUT, + CAN_BCM_SETTIMER as CAN_BCM_SETTIMER, + CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER, + CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE, + CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT, + CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID, + CAN_BCM_TX_DELETE as CAN_BCM_TX_DELETE, + CAN_BCM_TX_EXPIRED as CAN_BCM_TX_EXPIRED, + CAN_BCM_TX_READ as CAN_BCM_TX_READ, + CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX, + CAN_BCM_TX_SEND as CAN_BCM_TX_SEND, + CAN_BCM_TX_SETUP as CAN_BCM_TX_SETUP, + CAN_BCM_TX_STATUS as CAN_BCM_TX_STATUS, + CAN_EFF_FLAG as CAN_EFF_FLAG, + CAN_EFF_MASK as CAN_EFF_MASK, + CAN_ERR_FLAG as CAN_ERR_FLAG, + CAN_ERR_MASK as CAN_ERR_MASK, + CAN_ISOTP as CAN_ISOTP, + CAN_RAW as CAN_RAW, + CAN_RAW_FD_FRAMES as CAN_RAW_FD_FRAMES, + CAN_RAW_FILTER as CAN_RAW_FILTER, + CAN_RAW_LOOPBACK as CAN_RAW_LOOPBACK, + CAN_RAW_RECV_OWN_MSGS as CAN_RAW_RECV_OWN_MSGS, + CAN_RTR_FLAG as CAN_RTR_FLAG, + CAN_SFF_MASK as CAN_SFF_MASK, + IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID, + NETLINK_CRYPTO as NETLINK_CRYPTO, + NETLINK_DNRTMSG as NETLINK_DNRTMSG, + NETLINK_FIREWALL as NETLINK_FIREWALL, + NETLINK_IP6_FW as NETLINK_IP6_FW, + NETLINK_NFLOG as NETLINK_NFLOG, + NETLINK_ROUTE as NETLINK_ROUTE, + NETLINK_USERSOCK as NETLINK_USERSOCK, + NETLINK_XFRM as NETLINK_XFRM, + PACKET_BROADCAST as PACKET_BROADCAST, + PACKET_FASTROUTE as PACKET_FASTROUTE, + PACKET_HOST as PACKET_HOST, + PACKET_LOOPBACK as PACKET_LOOPBACK, + PACKET_MULTICAST as PACKET_MULTICAST, + PACKET_OTHERHOST as PACKET_OTHERHOST, + PACKET_OUTGOING as PACKET_OUTGOING, + PF_CAN as PF_CAN, + PF_PACKET as PF_PACKET, + PF_RDS as PF_RDS, + RDS_CANCEL_SENT_TO as RDS_CANCEL_SENT_TO, + RDS_CMSG_RDMA_ARGS as RDS_CMSG_RDMA_ARGS, + RDS_CMSG_RDMA_DEST as RDS_CMSG_RDMA_DEST, + RDS_CMSG_RDMA_MAP as RDS_CMSG_RDMA_MAP, + RDS_CMSG_RDMA_STATUS as RDS_CMSG_RDMA_STATUS, + RDS_CONG_MONITOR as RDS_CONG_MONITOR, + RDS_FREE_MR as RDS_FREE_MR, + RDS_GET_MR as RDS_GET_MR, + RDS_GET_MR_FOR_DEST as RDS_GET_MR_FOR_DEST, + RDS_RDMA_DONTWAIT as RDS_RDMA_DONTWAIT, + RDS_RDMA_FENCE as RDS_RDMA_FENCE, + RDS_RDMA_INVALIDATE as RDS_RDMA_INVALIDATE, + RDS_RDMA_NOTIFY_ME as RDS_RDMA_NOTIFY_ME, + RDS_RDMA_READWRITE as RDS_RDMA_READWRITE, + RDS_RDMA_SILENT as RDS_RDMA_SILENT, + RDS_RDMA_USE_ONCE as RDS_RDMA_USE_ONCE, + RDS_RECVERR as RDS_RECVERR, + SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE, + SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE, + SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE, + SOL_ALG as SOL_ALG, + SOL_CAN_BASE as SOL_CAN_BASE, + SOL_CAN_RAW as SOL_CAN_RAW, + SOL_RDS as SOL_RDS, + SOL_TIPC as SOL_TIPC, + TIPC_ADDR_ID as TIPC_ADDR_ID, + TIPC_ADDR_NAME as TIPC_ADDR_NAME, + TIPC_ADDR_NAMESEQ as TIPC_ADDR_NAMESEQ, + TIPC_CFG_SRV as TIPC_CFG_SRV, + TIPC_CLUSTER_SCOPE as TIPC_CLUSTER_SCOPE, + TIPC_CONN_TIMEOUT as TIPC_CONN_TIMEOUT, + TIPC_CRITICAL_IMPORTANCE as TIPC_CRITICAL_IMPORTANCE, + TIPC_DEST_DROPPABLE as TIPC_DEST_DROPPABLE, + TIPC_HIGH_IMPORTANCE as TIPC_HIGH_IMPORTANCE, + TIPC_IMPORTANCE as TIPC_IMPORTANCE, + TIPC_LOW_IMPORTANCE as TIPC_LOW_IMPORTANCE, + TIPC_MEDIUM_IMPORTANCE as TIPC_MEDIUM_IMPORTANCE, + TIPC_NODE_SCOPE as TIPC_NODE_SCOPE, + TIPC_PUBLISHED as TIPC_PUBLISHED, + TIPC_SRC_DROPPABLE as TIPC_SRC_DROPPABLE, + TIPC_SUB_CANCEL as TIPC_SUB_CANCEL, + TIPC_SUB_PORTS as TIPC_SUB_PORTS, + TIPC_SUB_SERVICE as TIPC_SUB_SERVICE, + TIPC_SUBSCR_TIMEOUT as TIPC_SUBSCR_TIMEOUT, + TIPC_TOP_SRV as TIPC_TOP_SRV, + TIPC_WAIT_FOREVER as TIPC_WAIT_FOREVER, + TIPC_WITHDRAWN as TIPC_WITHDRAWN, + TIPC_ZONE_SCOPE as TIPC_ZONE_SCOPE, + VM_SOCKETS_INVALID_VERSION as VM_SOCKETS_INVALID_VERSION, + VMADDR_CID_ANY as VMADDR_CID_ANY, + VMADDR_CID_HOST as VMADDR_CID_HOST, + VMADDR_PORT_ANY as VMADDR_PORT_ANY, + ) + + __all__ += [ + "ALG_OP_DECRYPT", + "ALG_OP_ENCRYPT", + "ALG_OP_SIGN", + "ALG_OP_VERIFY", + "ALG_SET_AEAD_ASSOCLEN", + "ALG_SET_AEAD_AUTHSIZE", + "ALG_SET_IV", + "ALG_SET_KEY", + "ALG_SET_OP", + "ALG_SET_PUBKEY", + "CAN_BCM", + "CAN_BCM_CAN_FD_FRAME", + "CAN_BCM_RX_ANNOUNCE_RESUME", + "CAN_BCM_RX_CHANGED", + "CAN_BCM_RX_CHECK_DLC", + "CAN_BCM_RX_DELETE", + "CAN_BCM_RX_FILTER_ID", + "CAN_BCM_RX_NO_AUTOTIMER", + "CAN_BCM_RX_READ", + "CAN_BCM_RX_RTR_FRAME", + "CAN_BCM_RX_SETUP", + "CAN_BCM_RX_STATUS", + "CAN_BCM_RX_TIMEOUT", + "CAN_BCM_SETTIMER", + "CAN_BCM_STARTTIMER", + "CAN_BCM_TX_ANNOUNCE", + "CAN_BCM_TX_COUNTEVT", + "CAN_BCM_TX_CP_CAN_ID", + "CAN_BCM_TX_DELETE", + "CAN_BCM_TX_EXPIRED", + "CAN_BCM_TX_READ", + "CAN_BCM_TX_RESET_MULTI_IDX", + "CAN_BCM_TX_SEND", + "CAN_BCM_TX_SETUP", + "CAN_BCM_TX_STATUS", + "CAN_EFF_FLAG", + "CAN_EFF_MASK", + "CAN_ERR_FLAG", + "CAN_ERR_MASK", + "CAN_ISOTP", + "CAN_RAW", + "CAN_RAW_FD_FRAMES", + "CAN_RAW_FILTER", + "CAN_RAW_LOOPBACK", + "CAN_RAW_RECV_OWN_MSGS", + "CAN_RTR_FLAG", + "CAN_SFF_MASK", + "IOCTL_VM_SOCKETS_GET_LOCAL_CID", + "NETLINK_CRYPTO", + "NETLINK_DNRTMSG", + "NETLINK_FIREWALL", + "NETLINK_IP6_FW", + "NETLINK_NFLOG", + "NETLINK_ROUTE", + "NETLINK_USERSOCK", + "NETLINK_XFRM", + "PACKET_BROADCAST", + "PACKET_FASTROUTE", + "PACKET_HOST", + "PACKET_LOOPBACK", + "PACKET_MULTICAST", + "PACKET_OTHERHOST", + "PACKET_OUTGOING", + "PF_CAN", + "PF_PACKET", + "PF_RDS", + "SO_VM_SOCKETS_BUFFER_MAX_SIZE", + "SO_VM_SOCKETS_BUFFER_MIN_SIZE", + "SO_VM_SOCKETS_BUFFER_SIZE", + "SOL_ALG", + "SOL_CAN_BASE", + "SOL_CAN_RAW", + "SOL_RDS", + "SOL_TIPC", + "TIPC_ADDR_ID", + "TIPC_ADDR_NAME", + "TIPC_ADDR_NAMESEQ", + "TIPC_CFG_SRV", + "TIPC_CLUSTER_SCOPE", + "TIPC_CONN_TIMEOUT", + "TIPC_CRITICAL_IMPORTANCE", + "TIPC_DEST_DROPPABLE", + "TIPC_HIGH_IMPORTANCE", + "TIPC_IMPORTANCE", + "TIPC_LOW_IMPORTANCE", + "TIPC_MEDIUM_IMPORTANCE", + "TIPC_NODE_SCOPE", + "TIPC_PUBLISHED", + "TIPC_SRC_DROPPABLE", + "TIPC_SUB_CANCEL", + "TIPC_SUB_PORTS", + "TIPC_SUB_SERVICE", + "TIPC_SUBSCR_TIMEOUT", + "TIPC_TOP_SRV", + "TIPC_WAIT_FOREVER", + "TIPC_WITHDRAWN", + "TIPC_ZONE_SCOPE", + "VM_SOCKETS_INVALID_VERSION", + "VMADDR_CID_ANY", + "VMADDR_CID_HOST", + "VMADDR_PORT_ANY", + "AF_CAN", + "AF_PACKET", + "AF_RDS", + "AF_TIPC", + "AF_ALG", + "AF_NETLINK", + "AF_VSOCK", + "AF_QIPCRTR", + "SOCK_CLOEXEC", + "SOCK_NONBLOCK", + ] + + if sys.version_info < (3, 11): + from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER + + __all__ += ["CAN_RAW_ERR_FILTER"] + if sys.version_info >= (3, 13): + from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER + + __all__ += ["CAN_RAW_ERR_FILTER"] + if sys.version_info >= (3, 15): + from _socket import ( + CAN_ISOTP_CHK_PAD_DATA as CAN_ISOTP_CHK_PAD_DATA, + CAN_ISOTP_CHK_PAD_LEN as CAN_ISOTP_CHK_PAD_LEN, + CAN_ISOTP_DEFAULT_EXT_ADDRESS as CAN_ISOTP_DEFAULT_EXT_ADDRESS, + CAN_ISOTP_DEFAULT_FLAGS as CAN_ISOTP_DEFAULT_FLAGS, + CAN_ISOTP_DEFAULT_FRAME_TXTIME as CAN_ISOTP_DEFAULT_FRAME_TXTIME, + CAN_ISOTP_DEFAULT_LL_MTU as CAN_ISOTP_DEFAULT_LL_MTU, + CAN_ISOTP_DEFAULT_LL_TX_DL as CAN_ISOTP_DEFAULT_LL_TX_DL, + CAN_ISOTP_DEFAULT_LL_TX_FLAGS as CAN_ISOTP_DEFAULT_LL_TX_FLAGS, + CAN_ISOTP_DEFAULT_PAD_CONTENT as CAN_ISOTP_DEFAULT_PAD_CONTENT, + CAN_ISOTP_DEFAULT_RECV_BS as CAN_ISOTP_DEFAULT_RECV_BS, + CAN_ISOTP_DEFAULT_RECV_STMIN as CAN_ISOTP_DEFAULT_RECV_STMIN, + CAN_ISOTP_DEFAULT_RECV_WFTMAX as CAN_ISOTP_DEFAULT_RECV_WFTMAX, + CAN_ISOTP_EXTEND_ADDR as CAN_ISOTP_EXTEND_ADDR, + CAN_ISOTP_FORCE_RXSTMIN as CAN_ISOTP_FORCE_RXSTMIN, + CAN_ISOTP_FORCE_TXSTMIN as CAN_ISOTP_FORCE_TXSTMIN, + CAN_ISOTP_HALF_DUPLEX as CAN_ISOTP_HALF_DUPLEX, + CAN_ISOTP_LISTEN_MODE as CAN_ISOTP_LISTEN_MODE, + CAN_ISOTP_LL_OPTS as CAN_ISOTP_LL_OPTS, + CAN_ISOTP_OPTS as CAN_ISOTP_OPTS, + CAN_ISOTP_RECV_FC as CAN_ISOTP_RECV_FC, + CAN_ISOTP_RX_EXT_ADDR as CAN_ISOTP_RX_EXT_ADDR, + CAN_ISOTP_RX_PADDING as CAN_ISOTP_RX_PADDING, + CAN_ISOTP_RX_STMIN as CAN_ISOTP_RX_STMIN, + CAN_ISOTP_SF_BROADCAST as CAN_ISOTP_SF_BROADCAST, + CAN_ISOTP_TX_PADDING as CAN_ISOTP_TX_PADDING, + CAN_ISOTP_TX_STMIN as CAN_ISOTP_TX_STMIN, + CAN_ISOTP_WAIT_TX_DONE as CAN_ISOTP_WAIT_TX_DONE, + SOL_CAN_ISOTP as SOL_CAN_ISOTP, + ) + + __all__ += [ + "CAN_ISOTP_CHK_PAD_DATA", + "CAN_ISOTP_CHK_PAD_LEN", + "CAN_ISOTP_DEFAULT_EXT_ADDRESS", + "CAN_ISOTP_DEFAULT_FLAGS", + "CAN_ISOTP_DEFAULT_FRAME_TXTIME", + "CAN_ISOTP_DEFAULT_LL_MTU", + "CAN_ISOTP_DEFAULT_LL_TX_DL", + "CAN_ISOTP_DEFAULT_LL_TX_FLAGS", + "CAN_ISOTP_DEFAULT_PAD_CONTENT", + "CAN_ISOTP_DEFAULT_RECV_BS", + "CAN_ISOTP_DEFAULT_RECV_STMIN", + "CAN_ISOTP_DEFAULT_RECV_WFTMAX", + "CAN_ISOTP_EXTEND_ADDR", + "CAN_ISOTP_FORCE_RXSTMIN", + "CAN_ISOTP_FORCE_TXSTMIN", + "CAN_ISOTP_HALF_DUPLEX", + "CAN_ISOTP_LL_OPTS", + "CAN_ISOTP_LISTEN_MODE", + "CAN_ISOTP_OPTS", + "CAN_ISOTP_RECV_FC", + "CAN_ISOTP_RX_EXT_ADDR", + "CAN_ISOTP_RX_PADDING", + "CAN_ISOTP_RX_STMIN", + "CAN_ISOTP_SF_BROADCAST", + "CAN_ISOTP_TX_PADDING", + "CAN_ISOTP_TX_STMIN", + "CAN_ISOTP_WAIT_TX_DONE", + "SOL_CAN_ISOTP", + ] + +if sys.platform == "linux": + from _socket import ( + CAN_J1939 as CAN_J1939, + CAN_RAW_JOIN_FILTERS as CAN_RAW_JOIN_FILTERS, + IPPROTO_UDPLITE as IPPROTO_UDPLITE, + J1939_EE_INFO_NONE as J1939_EE_INFO_NONE, + J1939_EE_INFO_TX_ABORT as J1939_EE_INFO_TX_ABORT, + J1939_FILTER_MAX as J1939_FILTER_MAX, + J1939_IDLE_ADDR as J1939_IDLE_ADDR, + J1939_MAX_UNICAST_ADDR as J1939_MAX_UNICAST_ADDR, + J1939_NLA_BYTES_ACKED as J1939_NLA_BYTES_ACKED, + J1939_NLA_PAD as J1939_NLA_PAD, + J1939_NO_ADDR as J1939_NO_ADDR, + J1939_NO_NAME as J1939_NO_NAME, + J1939_NO_PGN as J1939_NO_PGN, + J1939_PGN_ADDRESS_CLAIMED as J1939_PGN_ADDRESS_CLAIMED, + J1939_PGN_ADDRESS_COMMANDED as J1939_PGN_ADDRESS_COMMANDED, + J1939_PGN_MAX as J1939_PGN_MAX, + J1939_PGN_PDU1_MAX as J1939_PGN_PDU1_MAX, + J1939_PGN_REQUEST as J1939_PGN_REQUEST, + SCM_J1939_DEST_ADDR as SCM_J1939_DEST_ADDR, + SCM_J1939_DEST_NAME as SCM_J1939_DEST_NAME, + SCM_J1939_ERRQUEUE as SCM_J1939_ERRQUEUE, + SCM_J1939_PRIO as SCM_J1939_PRIO, + SO_J1939_ERRQUEUE as SO_J1939_ERRQUEUE, + SO_J1939_FILTER as SO_J1939_FILTER, + SO_J1939_PROMISC as SO_J1939_PROMISC, + SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, + UDPLITE_RECV_CSCOV as UDPLITE_RECV_CSCOV, + UDPLITE_SEND_CSCOV as UDPLITE_SEND_CSCOV, + ) + + __all__ += [ + "CAN_J1939", + "CAN_RAW_JOIN_FILTERS", + "IPPROTO_UDPLITE", + "J1939_EE_INFO_NONE", + "J1939_EE_INFO_TX_ABORT", + "J1939_FILTER_MAX", + "J1939_IDLE_ADDR", + "J1939_MAX_UNICAST_ADDR", + "J1939_NLA_BYTES_ACKED", + "J1939_NLA_PAD", + "J1939_NO_ADDR", + "J1939_NO_NAME", + "J1939_NO_PGN", + "J1939_PGN_ADDRESS_CLAIMED", + "J1939_PGN_ADDRESS_COMMANDED", + "J1939_PGN_MAX", + "J1939_PGN_PDU1_MAX", + "J1939_PGN_REQUEST", + "SCM_J1939_DEST_ADDR", + "SCM_J1939_DEST_NAME", + "SCM_J1939_ERRQUEUE", + "SCM_J1939_PRIO", + "SO_J1939_ERRQUEUE", + "SO_J1939_FILTER", + "SO_J1939_PROMISC", + "SO_J1939_SEND_PRIO", + "UDPLITE_RECV_CSCOV", + "UDPLITE_SEND_CSCOV", + ] +if sys.platform == "linux": + from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP + + __all__ += ["IPPROTO_MPTCP"] +if sys.platform == "linux" and sys.version_info >= (3, 11): + from _socket import SO_INCOMING_CPU as SO_INCOMING_CPU + + __all__ += ["SO_INCOMING_CPU"] +if sys.platform == "linux" and sys.version_info >= (3, 12): + from _socket import ( + TCP_CC_INFO as TCP_CC_INFO, + TCP_FASTOPEN_CONNECT as TCP_FASTOPEN_CONNECT, + TCP_FASTOPEN_KEY as TCP_FASTOPEN_KEY, + TCP_FASTOPEN_NO_COOKIE as TCP_FASTOPEN_NO_COOKIE, + TCP_INQ as TCP_INQ, + TCP_MD5SIG as TCP_MD5SIG, + TCP_MD5SIG_EXT as TCP_MD5SIG_EXT, + TCP_QUEUE_SEQ as TCP_QUEUE_SEQ, + TCP_REPAIR as TCP_REPAIR, + TCP_REPAIR_OPTIONS as TCP_REPAIR_OPTIONS, + TCP_REPAIR_QUEUE as TCP_REPAIR_QUEUE, + TCP_REPAIR_WINDOW as TCP_REPAIR_WINDOW, + TCP_SAVE_SYN as TCP_SAVE_SYN, + TCP_SAVED_SYN as TCP_SAVED_SYN, + TCP_THIN_DUPACK as TCP_THIN_DUPACK, + TCP_THIN_LINEAR_TIMEOUTS as TCP_THIN_LINEAR_TIMEOUTS, + TCP_TIMESTAMP as TCP_TIMESTAMP, + TCP_TX_DELAY as TCP_TX_DELAY, + TCP_ULP as TCP_ULP, + TCP_ZEROCOPY_RECEIVE as TCP_ZEROCOPY_RECEIVE, + ) + + __all__ += [ + "TCP_CC_INFO", + "TCP_FASTOPEN_CONNECT", + "TCP_FASTOPEN_KEY", + "TCP_FASTOPEN_NO_COOKIE", + "TCP_INQ", + "TCP_MD5SIG", + "TCP_MD5SIG_EXT", + "TCP_QUEUE_SEQ", + "TCP_REPAIR", + "TCP_REPAIR_OPTIONS", + "TCP_REPAIR_QUEUE", + "TCP_REPAIR_WINDOW", + "TCP_SAVED_SYN", + "TCP_SAVE_SYN", + "TCP_THIN_DUPACK", + "TCP_THIN_LINEAR_TIMEOUTS", + "TCP_TIMESTAMP", + "TCP_TX_DELAY", + "TCP_ULP", + "TCP_ZEROCOPY_RECEIVE", + ] + +if sys.platform == "linux" and sys.version_info >= (3, 13): + from _socket import NI_IDN as NI_IDN, SO_BINDTOIFINDEX as SO_BINDTOIFINDEX + + __all__ += ["NI_IDN", "SO_BINDTOIFINDEX"] + +if sys.version_info >= (3, 12): + from _socket import ( + IP_ADD_SOURCE_MEMBERSHIP as IP_ADD_SOURCE_MEMBERSHIP, + IP_BLOCK_SOURCE as IP_BLOCK_SOURCE, + IP_DROP_SOURCE_MEMBERSHIP as IP_DROP_SOURCE_MEMBERSHIP, + IP_PKTINFO as IP_PKTINFO, + IP_UNBLOCK_SOURCE as IP_UNBLOCK_SOURCE, + ) + + __all__ += ["IP_ADD_SOURCE_MEMBERSHIP", "IP_BLOCK_SOURCE", "IP_DROP_SOURCE_MEMBERSHIP", "IP_PKTINFO", "IP_UNBLOCK_SOURCE"] + + if sys.platform == "win32": + from _socket import ( + HV_GUID_BROADCAST as HV_GUID_BROADCAST, + HV_GUID_CHILDREN as HV_GUID_CHILDREN, + HV_GUID_LOOPBACK as HV_GUID_LOOPBACK, + HV_GUID_PARENT as HV_GUID_PARENT, + HV_GUID_WILDCARD as HV_GUID_WILDCARD, + HV_GUID_ZERO as HV_GUID_ZERO, + HV_PROTOCOL_RAW as HV_PROTOCOL_RAW, + HVSOCKET_ADDRESS_FLAG_PASSTHRU as HVSOCKET_ADDRESS_FLAG_PASSTHRU, + HVSOCKET_CONNECT_TIMEOUT as HVSOCKET_CONNECT_TIMEOUT, + HVSOCKET_CONNECT_TIMEOUT_MAX as HVSOCKET_CONNECT_TIMEOUT_MAX, + HVSOCKET_CONNECTED_SUSPEND as HVSOCKET_CONNECTED_SUSPEND, + ) + + __all__ += [ + "HV_GUID_BROADCAST", + "HV_GUID_CHILDREN", + "HV_GUID_LOOPBACK", + "HV_GUID_PARENT", + "HV_GUID_WILDCARD", + "HV_GUID_ZERO", + "HV_PROTOCOL_RAW", + "HVSOCKET_ADDRESS_FLAG_PASSTHRU", + "HVSOCKET_CONNECT_TIMEOUT", + "HVSOCKET_CONNECT_TIMEOUT_MAX", + "HVSOCKET_CONNECTED_SUSPEND", + ] + else: + from _socket import ( + ETHERTYPE_ARP as ETHERTYPE_ARP, + ETHERTYPE_IP as ETHERTYPE_IP, + ETHERTYPE_IPV6 as ETHERTYPE_IPV6, + ETHERTYPE_VLAN as ETHERTYPE_VLAN, + ) + + __all__ += ["ETHERTYPE_ARP", "ETHERTYPE_IP", "ETHERTYPE_IPV6", "ETHERTYPE_VLAN"] + + if sys.platform == "linux": + from _socket import ETH_P_ALL as ETH_P_ALL + + __all__ += ["ETH_P_ALL"] + + if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + # FreeBSD >= 14.0 + from _socket import PF_DIVERT as PF_DIVERT + + __all__ += ["PF_DIVERT", "AF_DIVERT"] + +if sys.platform != "win32": + __all__ += ["send_fds", "recv_fds"] + +if sys.platform != "linux": + __all__ += ["AF_LINK"] +if sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["AF_BLUETOOTH"] + +if sys.platform != "win32" and sys.platform != "darwin": + from _socket import BTPROTO_HCI as BTPROTO_HCI, BTPROTO_L2CAP as BTPROTO_L2CAP, BTPROTO_SCO as BTPROTO_SCO + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["BTPROTO_HCI", "BTPROTO_L2CAP", "BTPROTO_SCO"] + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + from _socket import HCI_DATA_DIR as HCI_DATA_DIR, HCI_FILTER as HCI_FILTER, HCI_TIME_STAMP as HCI_TIME_STAMP + + __all__ += ["HCI_FILTER", "HCI_TIME_STAMP", "HCI_DATA_DIR"] + +if sys.version_info >= (3, 11) and sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _socket import LOCAL_CREDS as LOCAL_CREDS, LOCAL_CREDS_PERSISTENT as LOCAL_CREDS_PERSISTENT, SCM_CREDS2 as SCM_CREDS2 + + __all__ += ["SCM_CREDS2", "LOCAL_CREDS", "LOCAL_CREDS_PERSISTENT"] + +if sys.platform == "win32" and sys.version_info >= (3, 12): + __all__ += ["AF_HYPERV"] + +if sys.platform != "win32" and sys.platform != "linux": + from _socket import ( + EAI_BADHINTS as EAI_BADHINTS, + EAI_MAX as EAI_MAX, + EAI_PROTOCOL as EAI_PROTOCOL, + IPPROTO_EON as IPPROTO_EON, + IPPROTO_HELLO as IPPROTO_HELLO, + IPPROTO_IPCOMP as IPPROTO_IPCOMP, + IPPROTO_XTP as IPPROTO_XTP, + IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, + LOCAL_PEERCRED as LOCAL_PEERCRED, + SCM_CREDS as SCM_CREDS, + ) + + __all__ += [ + "EAI_BADHINTS", + "EAI_MAX", + "EAI_PROTOCOL", + "IPPROTO_EON", + "IPPROTO_HELLO", + "IPPROTO_IPCOMP", + "IPPROTO_XTP", + "IPV6_USE_MIN_MTU", + "LOCAL_PEERCRED", + "SCM_CREDS", + "AI_DEFAULT", + "AI_MASK", + "AI_V4MAPPED_CFG", + "MSG_EOF", + ] + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + from _socket import ( + IPPROTO_BIP as IPPROTO_BIP, + IPPROTO_MOBILE as IPPROTO_MOBILE, + IPPROTO_VRRP as IPPROTO_VRRP, + MSG_BTAG as MSG_BTAG, + MSG_ETAG as MSG_ETAG, + SO_SETFIB as SO_SETFIB, + ) + + __all__ += ["SO_SETFIB", "MSG_BTAG", "MSG_ETAG", "IPPROTO_BIP", "IPPROTO_MOBILE", "IPPROTO_VRRP", "MSG_NOTIFICATION"] + +if sys.platform != "linux": + from _socket import ( + IP_RECVDSTADDR as IP_RECVDSTADDR, + IPPROTO_GGP as IPPROTO_GGP, + IPPROTO_IPV4 as IPPROTO_IPV4, + IPPROTO_MAX as IPPROTO_MAX, + IPPROTO_ND as IPPROTO_ND, + SO_USELOOPBACK as SO_USELOOPBACK, + ) + + __all__ += ["IPPROTO_GGP", "IPPROTO_IPV4", "IPPROTO_MAX", "IPPROTO_ND", "IP_RECVDSTADDR", "SO_USELOOPBACK"] + +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + from _socket import IPV6_HDRINCL as IPV6_HDRINCL + + __all__ += ["IPV6_HDRINCL"] + +if sys.version_info >= (3, 14): + from _socket import IP_RECVTTL as IP_RECVTTL + + __all__ += ["IP_RECVTTL"] + + if sys.platform == "win32" or sys.platform == "linux": + from _socket import IP_RECVERR as IP_RECVERR, IPV6_RECVERR as IPV6_RECVERR, SO_ORIGINAL_DST as SO_ORIGINAL_DST + + __all__ += ["IP_RECVERR", "IPV6_RECVERR", "SO_ORIGINAL_DST"] + + if sys.platform == "win32": + from _socket import ( + SO_BTH_ENCRYPT as SO_BTH_ENCRYPT, + SO_BTH_MTU as SO_BTH_MTU, + SO_BTH_MTU_MAX as SO_BTH_MTU_MAX, + SO_BTH_MTU_MIN as SO_BTH_MTU_MIN, + SOL_RFCOMM as SOL_RFCOMM, + TCP_QUICKACK as TCP_QUICKACK, + ) + + __all__ += ["SOL_RFCOMM", "SO_BTH_ENCRYPT", "SO_BTH_MTU", "SO_BTH_MTU_MAX", "SO_BTH_MTU_MIN", "TCP_QUICKACK"] + + if sys.platform == "linux": + from _socket import ( + BDADDR_BREDR as BDADDR_BREDR, + BDADDR_LE_PUBLIC as BDADDR_LE_PUBLIC, + BDADDR_LE_RANDOM as BDADDR_LE_RANDOM, + BT_CHANNEL_POLICY as BT_CHANNEL_POLICY, + BT_CHANNEL_POLICY_BREDR_ONLY as BT_CHANNEL_POLICY_BREDR_ONLY, + BT_CHANNEL_POLICY_BREDR_PREFERRED as BT_CHANNEL_POLICY_BREDR_PREFERRED, + BT_CODEC as BT_CODEC, + BT_DEFER_SETUP as BT_DEFER_SETUP, + BT_FLUSHABLE as BT_FLUSHABLE, + BT_FLUSHABLE_OFF as BT_FLUSHABLE_OFF, + BT_FLUSHABLE_ON as BT_FLUSHABLE_ON, + BT_ISO_QOS as BT_ISO_QOS, + BT_MODE as BT_MODE, + BT_MODE_BASIC as BT_MODE_BASIC, + BT_MODE_ERTM as BT_MODE_ERTM, + BT_MODE_EXT_FLOWCTL as BT_MODE_EXT_FLOWCTL, + BT_MODE_LE_FLOWCTL as BT_MODE_LE_FLOWCTL, + BT_MODE_STREAMING as BT_MODE_STREAMING, + BT_PHY as BT_PHY, + BT_PHY_BR_1M_1SLOT as BT_PHY_BR_1M_1SLOT, + BT_PHY_BR_1M_3SLOT as BT_PHY_BR_1M_3SLOT, + BT_PHY_BR_1M_5SLOT as BT_PHY_BR_1M_5SLOT, + BT_PHY_EDR_2M_1SLOT as BT_PHY_EDR_2M_1SLOT, + BT_PHY_EDR_2M_3SLOT as BT_PHY_EDR_2M_3SLOT, + BT_PHY_EDR_2M_5SLOT as BT_PHY_EDR_2M_5SLOT, + BT_PHY_EDR_3M_1SLOT as BT_PHY_EDR_3M_1SLOT, + BT_PHY_EDR_3M_3SLOT as BT_PHY_EDR_3M_3SLOT, + BT_PHY_EDR_3M_5SLOT as BT_PHY_EDR_3M_5SLOT, + BT_PHY_LE_1M_RX as BT_PHY_LE_1M_RX, + BT_PHY_LE_1M_TX as BT_PHY_LE_1M_TX, + BT_PHY_LE_2M_RX as BT_PHY_LE_2M_RX, + BT_PHY_LE_2M_TX as BT_PHY_LE_2M_TX, + BT_PHY_LE_CODED_RX as BT_PHY_LE_CODED_RX, + BT_PHY_LE_CODED_TX as BT_PHY_LE_CODED_TX, + BT_PKT_STATUS as BT_PKT_STATUS, + BT_POWER as BT_POWER, + BT_POWER_FORCE_ACTIVE_OFF as BT_POWER_FORCE_ACTIVE_OFF, + BT_POWER_FORCE_ACTIVE_ON as BT_POWER_FORCE_ACTIVE_ON, + BT_RCVMTU as BT_RCVMTU, + BT_SECURITY as BT_SECURITY, + BT_SECURITY_FIPS as BT_SECURITY_FIPS, + BT_SECURITY_HIGH as BT_SECURITY_HIGH, + BT_SECURITY_LOW as BT_SECURITY_LOW, + BT_SECURITY_MEDIUM as BT_SECURITY_MEDIUM, + BT_SECURITY_SDP as BT_SECURITY_SDP, + BT_SNDMTU as BT_SNDMTU, + BT_VOICE as BT_VOICE, + BT_VOICE_CVSD_16BIT as BT_VOICE_CVSD_16BIT, + BT_VOICE_TRANSPARENT as BT_VOICE_TRANSPARENT, + BT_VOICE_TRANSPARENT_16BIT as BT_VOICE_TRANSPARENT_16BIT, + HCI_CHANNEL_CONTROL as HCI_CHANNEL_CONTROL, + HCI_CHANNEL_LOGGING as HCI_CHANNEL_LOGGING, + HCI_CHANNEL_MONITOR as HCI_CHANNEL_MONITOR, + HCI_CHANNEL_RAW as HCI_CHANNEL_RAW, + HCI_CHANNEL_USER as HCI_CHANNEL_USER, + HCI_DEV_NONE as HCI_DEV_NONE, + IP_FREEBIND as IP_FREEBIND, + IP_RECVORIGDSTADDR as IP_RECVORIGDSTADDR, + L2CAP_LM as L2CAP_LM, + L2CAP_LM_AUTH as L2CAP_LM_AUTH, + L2CAP_LM_ENCRYPT as L2CAP_LM_ENCRYPT, + L2CAP_LM_MASTER as L2CAP_LM_MASTER, + L2CAP_LM_RELIABLE as L2CAP_LM_RELIABLE, + L2CAP_LM_SECURE as L2CAP_LM_SECURE, + L2CAP_LM_TRUSTED as L2CAP_LM_TRUSTED, + SOL_BLUETOOTH as SOL_BLUETOOTH, + SOL_L2CAP as SOL_L2CAP, + SOL_RFCOMM as SOL_RFCOMM, + SOL_SCO as SOL_SCO, + VMADDR_CID_LOCAL as VMADDR_CID_LOCAL, + ) + + __all__ += ["IP_FREEBIND", "IP_RECVORIGDSTADDR", "VMADDR_CID_LOCAL"] + +# Re-exported from errno +EBADF: Final[int] +EAGAIN: Final[int] +EWOULDBLOCK: Final[int] + +# These errors are implemented in _socket at runtime +# but they consider themselves to live in socket so we'll put them here. +error = OSError + +class herror(error): ... +class gaierror(error): ... + +timeout = TimeoutError + +class AddressFamily(IntEnum): + AF_INET = 2 + AF_INET6 = 10 + AF_APPLETALK = 5 + AF_IPX = 4 + AF_SNA = 22 + AF_UNSPEC = 0 + if sys.platform != "darwin": + AF_IRDA = 23 + if sys.platform != "win32": + AF_ROUTE = 16 + AF_UNIX = 1 + if sys.platform == "darwin": + AF_SYSTEM = 32 + if sys.platform != "win32" and sys.platform != "darwin": + AF_ASH = 18 + AF_ATMPVC = 8 + AF_ATMSVC = 20 + AF_AX25 = 3 + AF_BRIDGE = 7 + AF_ECONET = 19 + AF_KEY = 15 + AF_LLC = 26 + AF_NETBEUI = 13 + AF_NETROM = 6 + AF_PPPOX = 24 + AF_ROSE = 11 + AF_SECURITY = 14 + AF_WANPIPE = 25 + AF_X25 = 9 + if sys.platform == "linux": + AF_CAN = 29 + AF_PACKET = 17 + AF_RDS = 21 + AF_TIPC = 30 + AF_ALG = 38 + AF_NETLINK = 16 + AF_VSOCK = 40 + AF_QIPCRTR = 42 + if sys.platform != "linux": + AF_LINK = 33 + if sys.platform != "darwin": + AF_BLUETOOTH = 32 + if sys.platform == "win32" and sys.version_info >= (3, 12): + AF_HYPERV = 34 + if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): + # FreeBSD >= 14.0 + AF_DIVERT = 44 + +AF_INET: Final = AddressFamily.AF_INET +AF_INET6: Final = AddressFamily.AF_INET6 +AF_APPLETALK: Final = AddressFamily.AF_APPLETALK +AF_DECnet: Final = 12 +AF_IPX: Final = AddressFamily.AF_IPX +AF_SNA: Final = AddressFamily.AF_SNA +AF_UNSPEC: Final = AddressFamily.AF_UNSPEC + +if sys.platform != "darwin": + AF_IRDA: Final = AddressFamily.AF_IRDA + +if sys.platform != "win32": + AF_ROUTE: Final = AddressFamily.AF_ROUTE + AF_UNIX: Final = AddressFamily.AF_UNIX + +if sys.platform == "darwin": + AF_SYSTEM: Final = AddressFamily.AF_SYSTEM + +if sys.platform != "win32" and sys.platform != "darwin": + AF_ASH: Final = AddressFamily.AF_ASH + AF_ATMPVC: Final = AddressFamily.AF_ATMPVC + AF_ATMSVC: Final = AddressFamily.AF_ATMSVC + AF_AX25: Final = AddressFamily.AF_AX25 + AF_BRIDGE: Final = AddressFamily.AF_BRIDGE + AF_ECONET: Final = AddressFamily.AF_ECONET + AF_KEY: Final = AddressFamily.AF_KEY + AF_LLC: Final = AddressFamily.AF_LLC + AF_NETBEUI: Final = AddressFamily.AF_NETBEUI + AF_NETROM: Final = AddressFamily.AF_NETROM + AF_PPPOX: Final = AddressFamily.AF_PPPOX + AF_ROSE: Final = AddressFamily.AF_ROSE + AF_SECURITY: Final = AddressFamily.AF_SECURITY + AF_WANPIPE: Final = AddressFamily.AF_WANPIPE + AF_X25: Final = AddressFamily.AF_X25 + +if sys.platform == "linux": + AF_CAN: Final = AddressFamily.AF_CAN + AF_PACKET: Final = AddressFamily.AF_PACKET + AF_RDS: Final = AddressFamily.AF_RDS + AF_TIPC: Final = AddressFamily.AF_TIPC + AF_ALG: Final = AddressFamily.AF_ALG + AF_NETLINK: Final = AddressFamily.AF_NETLINK + AF_VSOCK: Final = AddressFamily.AF_VSOCK + AF_QIPCRTR: Final = AddressFamily.AF_QIPCRTR + +if sys.platform != "linux": + AF_LINK: Final = AddressFamily.AF_LINK +if sys.platform != "darwin": + AF_BLUETOOTH: Final = AddressFamily.AF_BLUETOOTH +if sys.platform == "win32" and sys.version_info >= (3, 12): + AF_HYPERV: Final = AddressFamily.AF_HYPERV +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): + # FreeBSD >= 14.0 + AF_DIVERT: Final = AddressFamily.AF_DIVERT + +class SocketKind(IntEnum): + SOCK_STREAM = 1 + SOCK_DGRAM = 2 + SOCK_RAW = 3 + SOCK_RDM = 4 + SOCK_SEQPACKET = 5 + if sys.platform == "linux": + SOCK_CLOEXEC = 524288 + SOCK_NONBLOCK = 2048 + +SOCK_STREAM: Final = SocketKind.SOCK_STREAM +SOCK_DGRAM: Final = SocketKind.SOCK_DGRAM +SOCK_RAW: Final = SocketKind.SOCK_RAW +SOCK_RDM: Final = SocketKind.SOCK_RDM +SOCK_SEQPACKET: Final = SocketKind.SOCK_SEQPACKET +if sys.platform == "linux": + SOCK_CLOEXEC: Final = SocketKind.SOCK_CLOEXEC + SOCK_NONBLOCK: Final = SocketKind.SOCK_NONBLOCK + +class MsgFlag(IntFlag): + MSG_CTRUNC = 8 + MSG_DONTROUTE = 4 + MSG_OOB = 1 + MSG_PEEK = 2 + MSG_TRUNC = 32 + MSG_WAITALL = 256 + if sys.platform == "win32": + MSG_BCAST = 1024 + MSG_MCAST = 2048 + + if sys.platform != "darwin": + MSG_ERRQUEUE = 8192 + + if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC = 1073741821 + MSG_CONFIRM = 2048 + MSG_FASTOPEN = 536870912 + MSG_MORE = 32768 + + if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + MSG_NOTIFICATION = 8192 + + if sys.platform != "win32": + MSG_DONTWAIT = 64 + MSG_EOR = 128 + MSG_NOSIGNAL = 16384 # sometimes this exists on darwin, sometimes not + if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF = 256 + +MSG_CTRUNC: Final = MsgFlag.MSG_CTRUNC +MSG_DONTROUTE: Final = MsgFlag.MSG_DONTROUTE +MSG_OOB: Final = MsgFlag.MSG_OOB +MSG_PEEK: Final = MsgFlag.MSG_PEEK +MSG_TRUNC: Final = MsgFlag.MSG_TRUNC +MSG_WAITALL: Final = MsgFlag.MSG_WAITALL + +if sys.platform == "win32": + MSG_BCAST: Final = MsgFlag.MSG_BCAST + MSG_MCAST: Final = MsgFlag.MSG_MCAST + +if sys.platform != "darwin": + MSG_ERRQUEUE: Final = MsgFlag.MSG_ERRQUEUE + +if sys.platform != "win32": + MSG_DONTWAIT: Final = MsgFlag.MSG_DONTWAIT + MSG_EOR: Final = MsgFlag.MSG_EOR + MSG_NOSIGNAL: Final = MsgFlag.MSG_NOSIGNAL # Sometimes this exists on darwin, sometimes not + +if sys.platform != "win32" and sys.platform != "darwin": + MSG_CMSG_CLOEXEC: Final = MsgFlag.MSG_CMSG_CLOEXEC + MSG_CONFIRM: Final = MsgFlag.MSG_CONFIRM + MSG_FASTOPEN: Final = MsgFlag.MSG_FASTOPEN + MSG_MORE: Final = MsgFlag.MSG_MORE + +if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": + MSG_NOTIFICATION: Final = MsgFlag.MSG_NOTIFICATION + +if sys.platform != "win32" and sys.platform != "linux": + MSG_EOF: Final = MsgFlag.MSG_EOF + +class AddressInfo(IntFlag): + AI_ADDRCONFIG = 32 + AI_ALL = 16 + AI_CANONNAME = 2 + AI_NUMERICHOST = 4 + AI_NUMERICSERV = 1024 + AI_PASSIVE = 1 + AI_V4MAPPED = 8 + if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT = 1536 + AI_MASK = 5127 + AI_V4MAPPED_CFG = 512 + +AI_ADDRCONFIG: Final = AddressInfo.AI_ADDRCONFIG +AI_ALL: Final = AddressInfo.AI_ALL +AI_CANONNAME: Final = AddressInfo.AI_CANONNAME +AI_NUMERICHOST: Final = AddressInfo.AI_NUMERICHOST +AI_NUMERICSERV: Final = AddressInfo.AI_NUMERICSERV +AI_PASSIVE: Final = AddressInfo.AI_PASSIVE +AI_V4MAPPED: Final = AddressInfo.AI_V4MAPPED + +if sys.platform != "win32" and sys.platform != "linux": + AI_DEFAULT: Final = AddressInfo.AI_DEFAULT + AI_MASK: Final = AddressInfo.AI_MASK + AI_V4MAPPED_CFG: Final = AddressInfo.AI_V4MAPPED_CFG + +if sys.platform == "win32": + errorTab: dict[int, str] # undocumented + +@type_check_only +class _SendableFile(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> object: ... + + # optional fields: + # + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + +class socket(_socket.socket): + __slots__ = ["__weakref__", "_io_refs", "_closed"] + def __init__( + self, family: AddressFamily | int = -1, type: SocketKind | int = -1, proto: int = -1, fileno: int | None = None + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def dup(self) -> Self: ... + def accept(self) -> tuple[socket, _RetAddress]: ... + + # Note that the makefile's documented windows-specific behavior is not represented + # mode strings with duplicates are intentionally excluded + @overload + def makefile( + self, + mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[0], + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> SocketIO: ... + @overload + def makefile( + self, + mode: Literal["rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[-1, 1] | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedRWPair: ... + @overload + def makefile( + self, + mode: Literal["rb", "br"], + buffering: Literal[-1, 1] | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedReader: ... + @overload + def makefile( + self, + mode: Literal["wb", "bw"], + buffering: Literal[-1, 1] | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> BufferedWriter: ... + @overload + def makefile( + self, + mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: int, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> IOBase: ... + @overload + def makefile( + self, + mode: Literal["r", "w", "rw", "wr", ""] = "r", + buffering: int | None = None, + *, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + ) -> TextIOWrapper: ... + + def sendfile(self, file: _SendableFile, offset: int = 0, count: int | None = None) -> int: ... + @property + def family(self) -> AddressFamily: ... + @property + def type(self) -> SocketKind: ... + def get_inheritable(self) -> bool: ... + def set_inheritable(self, inheritable: bool) -> None: ... + +def fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ... + +if sys.platform != "win32": + def send_fds( + sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None + ) -> int: ... + def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: ... + +if sys.platform == "win32": + def fromshare(info: bytes) -> socket: ... + +if sys.platform == "win32": + def socketpair(family: int = ..., type: int = ..., proto: int = 0) -> tuple[socket, socket]: ... + +else: + def socketpair( + family: int | AddressFamily | None = None, type: SocketKind | int = ..., proto: int = 0 + ) -> tuple[socket, socket]: ... + +class SocketIO(RawIOBase): + def __init__(self, sock: socket, mode: Literal["r", "w", "rw", "rb", "wb", "rwb"]) -> None: ... + def readinto(self, b: WriteableBuffer) -> int | None: ... + def write(self, b: ReadableBuffer) -> int | None: ... + @property + def name(self) -> int: ... # return value is really "int" + @property + def mode(self) -> Literal["rb", "wb", "rwb"]: ... + +def getfqdn(name: str = "") -> str: ... + +if sys.version_info >= (3, 11): + def create_connection( + address: tuple[str | None, bytes | str | int | None], + timeout: float | None = ..., + source_address: _Address | None = None, + *, + all_errors: bool = False, + ) -> socket: ... + +else: + def create_connection( + address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None + ) -> socket: ... + +def has_dualstack_ipv6() -> bool: ... +def create_server( + address: _Address, *, family: int = ..., backlog: int | None = None, reuse_port: bool = False, dualstack_ipv6: bool = False +) -> socket: ... + +# The 5th tuple item is the socket address, for IP4, IP6, or IP6 if Python is compiled with --disable-ipv6, respectively. +_GetAddrInfoResult: TypeAlias = list[ + tuple[Literal[AddressFamily.AF_INET], SocketKind, int, str, tuple[str, int]] + | tuple[Literal[AddressFamily.AF_INET6], SocketKind, int, str, tuple[str, int, int, int] | tuple[int, bytes]] +] + +def getaddrinfo( + host: bytes | str | None, port: bytes | str | int | None, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0 +) -> _GetAddrInfoResult: ... diff --git a/stdlib/socketserver.pyi b/stdlib/socketserver.pyi new file mode 100644 index 000000000000..05e0025d6a15 --- /dev/null +++ b/stdlib/socketserver.pyi @@ -0,0 +1,170 @@ +import sys +import types +from _socket import _Address, _RetAddress +from _typeshed import ReadableBuffer +from collections.abc import Callable +from io import BufferedIOBase +from socket import socket as _socket +from typing import Any, ClassVar, TypeAlias +from typing_extensions import Self + +__all__ = [ + "BaseServer", + "TCPServer", + "UDPServer", + "ThreadingUDPServer", + "ThreadingTCPServer", + "BaseRequestHandler", + "StreamRequestHandler", + "DatagramRequestHandler", + "ThreadingMixIn", +] +if sys.platform != "win32": + __all__ += [ + "ForkingMixIn", + "ForkingTCPServer", + "ForkingUDPServer", + "ThreadingUnixDatagramServer", + "ThreadingUnixStreamServer", + "UnixDatagramServer", + "UnixStreamServer", + ] + if sys.version_info >= (3, 12): + __all__ += ["ForkingUnixStreamServer", "ForkingUnixDatagramServer"] + +_RequestType: TypeAlias = _socket | tuple[bytes, _socket] +_AfUnixAddress: TypeAlias = str | ReadableBuffer # address acceptable for an AF_UNIX socket +_AfInetAddress: TypeAlias = tuple[str | bytes | bytearray, int] # address acceptable for an AF_INET socket +_AfInet6Address: TypeAlias = tuple[str | bytes | bytearray, int, int, int] # address acceptable for an AF_INET6 socket + +# This can possibly be generic at some point: +class BaseServer: + server_address: _Address + timeout: float | None + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler] + def __init__( + self, server_address: _Address, RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler] + ) -> None: ... + def handle_request(self) -> None: ... + def serve_forever(self, poll_interval: float = 0.5) -> None: ... + def shutdown(self) -> None: ... + def server_close(self) -> None: ... + def finish_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def get_request(self) -> tuple[Any, Any]: ... # Not implemented here, but expected to exist on subclasses + def handle_error(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def handle_timeout(self) -> None: ... + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def server_activate(self) -> None: ... + def verify_request(self, request: _RequestType, client_address: _RetAddress) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def service_actions(self) -> None: ... + def shutdown_request(self, request: _RequestType) -> None: ... # undocumented + def close_request(self, request: _RequestType) -> None: ... # undocumented + +class TCPServer(BaseServer): + address_family: int + socket: _socket + allow_reuse_address: bool + request_queue_size: int + socket_type: int + if sys.version_info >= (3, 11): + allow_reuse_port: bool + server_address: _AfInetAddress | _AfInet6Address + def __init__( + self, + server_address: _AfInetAddress | _AfInet6Address, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, + ) -> None: ... + def fileno(self) -> int: ... + def get_request(self) -> tuple[_socket, _RetAddress]: ... + def server_bind(self) -> None: ... + +class UDPServer(TCPServer): + max_packet_size: ClassVar[int] + def get_request(self) -> tuple[tuple[bytes, _socket], _RetAddress]: ... # type: ignore[override] + +if sys.platform != "win32": + class UnixStreamServer(TCPServer): + server_address: _AfUnixAddress # type: ignore[assignment] + def __init__( + self, + server_address: _AfUnixAddress, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, + ) -> None: ... + + class UnixDatagramServer(UDPServer): + server_address: _AfUnixAddress # type: ignore[assignment] + def __init__( + self, + server_address: _AfUnixAddress, + RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler], + bind_and_activate: bool = True, + ) -> None: ... + +if sys.platform != "win32": + class ForkingMixIn: + timeout: float | None # undocumented + active_children: set[int] | None # undocumented + max_children: int # undocumented + block_on_close: bool + def collect_children(self, *, blocking: bool = False) -> None: ... # undocumented + def handle_timeout(self) -> None: ... # undocumented + def service_actions(self) -> None: ... # undocumented + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def server_close(self) -> None: ... + +class ThreadingMixIn: + daemon_threads: bool + block_on_close: bool + def process_request_thread(self, request: _RequestType, client_address: _RetAddress) -> None: ... # undocumented + def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ... + def server_close(self) -> None: ... + +if sys.platform != "win32": + class ForkingTCPServer(ForkingMixIn, TCPServer): ... + class ForkingUDPServer(ForkingMixIn, UDPServer): ... + if sys.version_info >= (3, 12): + class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): ... + class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): ... + +class ThreadingTCPServer(ThreadingMixIn, TCPServer): ... +class ThreadingUDPServer(ThreadingMixIn, UDPServer): ... + +if sys.platform != "win32": + class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ... + class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ... + +class BaseRequestHandler: + # `request` is technically of type _RequestType, + # but there are some concerns that having a union here would cause + # too much inconvenience to people using it (see + # https://github.com/python/typeshed/pull/384#issuecomment-234649696) + # + # Note also that _RetAddress is also just an alias for `Any` + request: Any + client_address: _RetAddress + server: BaseServer + def __init__(self, request: _RequestType, client_address: _RetAddress, server: BaseServer) -> None: ... + def setup(self) -> None: ... + def handle(self) -> None: ... + def finish(self) -> None: ... + +class StreamRequestHandler(BaseRequestHandler): + rbufsize: ClassVar[int] # undocumented + wbufsize: ClassVar[int] # undocumented + timeout: ClassVar[float | None] # undocumented + disable_nagle_algorithm: ClassVar[bool] # undocumented + connection: Any # undocumented + rfile: BufferedIOBase + wfile: BufferedIOBase + +class DatagramRequestHandler(BaseRequestHandler): + packet: bytes # undocumented + socket: _socket # undocumented + rfile: BufferedIOBase + wfile: BufferedIOBase diff --git a/stdlib/spwd.pyi b/stdlib/spwd.pyi new file mode 100644 index 000000000000..0a06cdfeef64 --- /dev/null +++ b/stdlib/spwd.pyi @@ -0,0 +1,45 @@ +import sys +from _typeshed import structseq +from typing import Any, Final, final + +if sys.platform != "win32": + @final + class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): + __match_args__: Final = ( + "sp_namp", + "sp_pwdp", + "sp_lstchg", + "sp_min", + "sp_max", + "sp_warn", + "sp_inact", + "sp_expire", + "sp_flag", + ) + + @property + def sp_namp(self) -> str: ... + @property + def sp_pwdp(self) -> str: ... + @property + def sp_lstchg(self) -> int: ... + @property + def sp_min(self) -> int: ... + @property + def sp_max(self) -> int: ... + @property + def sp_warn(self) -> int: ... + @property + def sp_inact(self) -> int: ... + @property + def sp_expire(self) -> int: ... + @property + def sp_flag(self) -> int: ... + # Deprecated aliases below. + @property + def sp_nam(self) -> str: ... + @property + def sp_pwd(self) -> str: ... + + def getspall() -> list[struct_spwd]: ... + def getspnam(arg: str, /) -> struct_spwd: ... diff --git a/stdlib/sqlite3/__init__.pyi b/stdlib/sqlite3/__init__.pyi new file mode 100644 index 000000000000..80a02079dd05 --- /dev/null +++ b/stdlib/sqlite3/__init__.pyi @@ -0,0 +1,510 @@ +import sys +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from sqlite3.dbapi2 import ( + PARSE_COLNAMES as PARSE_COLNAMES, + PARSE_DECLTYPES as PARSE_DECLTYPES, + SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE, + SQLITE_ANALYZE as SQLITE_ANALYZE, + SQLITE_ATTACH as SQLITE_ATTACH, + SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX, + SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX, + SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER, + SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER, + SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW, + SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE, + SQLITE_DELETE as SQLITE_DELETE, + SQLITE_DENY as SQLITE_DENY, + SQLITE_DETACH as SQLITE_DETACH, + SQLITE_DONE as SQLITE_DONE, + SQLITE_DROP_INDEX as SQLITE_DROP_INDEX, + SQLITE_DROP_TABLE as SQLITE_DROP_TABLE, + SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE, + SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER, + SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER, + SQLITE_DROP_VIEW as SQLITE_DROP_VIEW, + SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE, + SQLITE_FUNCTION as SQLITE_FUNCTION, + SQLITE_IGNORE as SQLITE_IGNORE, + SQLITE_INSERT as SQLITE_INSERT, + SQLITE_OK as SQLITE_OK, + SQLITE_PRAGMA as SQLITE_PRAGMA, + SQLITE_READ as SQLITE_READ, + SQLITE_RECURSIVE as SQLITE_RECURSIVE, + SQLITE_REINDEX as SQLITE_REINDEX, + SQLITE_SAVEPOINT as SQLITE_SAVEPOINT, + SQLITE_SELECT as SQLITE_SELECT, + SQLITE_TRANSACTION as SQLITE_TRANSACTION, + SQLITE_UPDATE as SQLITE_UPDATE, + Binary as Binary, + Date as Date, + DateFromTicks as DateFromTicks, + Time as Time, + TimeFromTicks as TimeFromTicks, + TimestampFromTicks as TimestampFromTicks, + adapt as adapt, + adapters as adapters, + apilevel as apilevel, + complete_statement as complete_statement, + connect as connect, + converters as converters, + enable_callback_tracebacks as enable_callback_tracebacks, + paramstyle as paramstyle, + register_adapter as register_adapter, + register_converter as register_converter, + sqlite_version as sqlite_version, + sqlite_version_info as sqlite_version_info, + threadsafety as threadsafety, +) +from types import TracebackType +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +if sys.version_info < (3, 14): + from sqlite3.dbapi2 import version_info as version_info + +if sys.version_info >= (3, 15): + from sqlite3.dbapi2 import SQLITE_KEYWORDS as SQLITE_KEYWORDS + +if sys.version_info >= (3, 12): + from sqlite3.dbapi2 import ( + LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL, + SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE, + SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL, + SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML, + SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY, + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, + SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG, + SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER, + SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW, + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, + SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE, + SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP, + SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA, + SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA, + ) + +if sys.version_info >= (3, 11): + from sqlite3.dbapi2 import ( + SQLITE_ABORT as SQLITE_ABORT, + SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK, + SQLITE_AUTH as SQLITE_AUTH, + SQLITE_AUTH_USER as SQLITE_AUTH_USER, + SQLITE_BUSY as SQLITE_BUSY, + SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY, + SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT, + SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT, + SQLITE_CANTOPEN as SQLITE_CANTOPEN, + SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH, + SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL, + SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH, + SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR, + SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR, + SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK, + SQLITE_CONSTRAINT as SQLITE_CONSTRAINT, + SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK, + SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK, + SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY, + SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION, + SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL, + SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED, + SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY, + SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID, + SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER, + SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE, + SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB, + SQLITE_CORRUPT as SQLITE_CORRUPT, + SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX, + SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE, + SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB, + SQLITE_EMPTY as SQLITE_EMPTY, + SQLITE_ERROR as SQLITE_ERROR, + SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ, + SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY, + SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT, + SQLITE_FORMAT as SQLITE_FORMAT, + SQLITE_FULL as SQLITE_FULL, + SQLITE_INTERNAL as SQLITE_INTERNAL, + SQLITE_INTERRUPT as SQLITE_INTERRUPT, + SQLITE_IOERR as SQLITE_IOERR, + SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS, + SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH, + SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC, + SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED, + SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK, + SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE, + SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC, + SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH, + SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS, + SQLITE_IOERR_DATA as SQLITE_IOERR_DATA, + SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE, + SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT, + SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE, + SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC, + SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT, + SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC, + SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH, + SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK, + SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP, + SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM, + SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK, + SQLITE_IOERR_READ as SQLITE_IOERR_READ, + SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC, + SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK, + SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK, + SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP, + SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN, + SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE, + SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ, + SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE, + SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK, + SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE, + SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE, + SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED, + SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN, + SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT, + SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH, + SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG, + SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH, + SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH, + SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH, + SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH, + SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER, + SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP, + SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS, + SQLITE_LOCKED as SQLITE_LOCKED, + SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE, + SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB, + SQLITE_MISMATCH as SQLITE_MISMATCH, + SQLITE_MISUSE as SQLITE_MISUSE, + SQLITE_NOLFS as SQLITE_NOLFS, + SQLITE_NOMEM as SQLITE_NOMEM, + SQLITE_NOTADB as SQLITE_NOTADB, + SQLITE_NOTFOUND as SQLITE_NOTFOUND, + SQLITE_NOTICE as SQLITE_NOTICE, + SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK, + SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL, + SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY, + SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK, + SQLITE_PERM as SQLITE_PERM, + SQLITE_PROTOCOL as SQLITE_PROTOCOL, + SQLITE_RANGE as SQLITE_RANGE, + SQLITE_READONLY as SQLITE_READONLY, + SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT, + SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK, + SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED, + SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY, + SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY, + SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK, + SQLITE_ROW as SQLITE_ROW, + SQLITE_SCHEMA as SQLITE_SCHEMA, + SQLITE_TOOBIG as SQLITE_TOOBIG, + SQLITE_WARNING as SQLITE_WARNING, + SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX, + ) + +if sys.version_info < (3, 12): + from sqlite3.dbapi2 import enable_shared_cache as enable_shared_cache, version as version + +_CursorT = TypeVar("_CursorT", bound=Cursor) +_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None +# Data that is passed through adapters can be of any type accepted by an adapter. +_AdaptedInputData: TypeAlias = _SqliteData | Any +# The Mapping must really be a dict, but making it invariant is too annoying. +_Parameters: TypeAlias = SupportsLenAndGetItem[_AdaptedInputData] | Mapping[str, _AdaptedInputData] +# Controls the legacy transaction handling mode of sqlite3. +_IsolationLevel: TypeAlias = Literal["DEFERRED", "EXCLUSIVE", "IMMEDIATE"] | None +_RowFactoryOptions: TypeAlias = type[Row] | Callable[[Cursor, tuple[Any, ...]], object] | None + +@type_check_only +class _AnyParamWindowAggregateClass(Protocol): + def step(self, *args: Any) -> object: ... + def inverse(self, *args: Any) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +@type_check_only +class _WindowAggregateClass(Protocol): + step: Callable[..., object] + inverse: Callable[..., object] + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +@type_check_only +class _AggregateProtocol(Protocol): + def step(self, value: int, /) -> object: ... + def finalize(self) -> int: ... + +@type_check_only +class _SingleParamWindowAggregateClass(Protocol): + def step(self, param: Any, /) -> object: ... + def inverse(self, param: Any, /) -> object: ... + def value(self) -> _SqliteData: ... + def finalize(self) -> _SqliteData: ... + +# These classes are implemented in the C module _sqlite3. At runtime, they're imported +# from there into sqlite3.dbapi2 and from that module to here. However, they +# consider themselves to live in the sqlite3.* namespace, so we'll define them here. + +class Error(Exception): + if sys.version_info >= (3, 11): + sqlite_errorcode: int + sqlite_errorname: str + +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(Error): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class Warning(Exception): ... + +_DataError: TypeAlias = DataError +_DatabaseError: TypeAlias = DatabaseError +_Error: TypeAlias = Error +_IntegrityError: TypeAlias = IntegrityError +_InterfaceError: TypeAlias = InterfaceError +_InternalError: TypeAlias = InternalError +_NotSupportedError: TypeAlias = NotSupportedError +_OperationalError: TypeAlias = OperationalError +_ProgrammingError: TypeAlias = ProgrammingError +_Warning: TypeAlias = Warning + +@disjoint_base +class Connection: + @property + def DataError(self) -> type[_DataError]: ... + @property + def DatabaseError(self) -> type[_DatabaseError]: ... + @property + def Error(self) -> type[_Error]: ... + @property + def IntegrityError(self) -> type[_IntegrityError]: ... + @property + def InterfaceError(self) -> type[_InterfaceError]: ... + @property + def InternalError(self) -> type[_InternalError]: ... + @property + def NotSupportedError(self) -> type[_NotSupportedError]: ... + @property + def OperationalError(self) -> type[_OperationalError]: ... + @property + def ProgrammingError(self) -> type[_ProgrammingError]: ... + @property + def Warning(self) -> type[_Warning]: ... + @property + def in_transaction(self) -> bool: ... + isolation_level: _IsolationLevel + @property + def total_changes(self) -> int: ... + if sys.version_info >= (3, 12): + @property + def autocommit(self) -> int: ... + @autocommit.setter + def autocommit(self, val: int) -> None: ... + + row_factory: _RowFactoryOptions + text_factory: Any + if sys.version_info >= (3, 12): + def __init__( + self, + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + factory: type[Connection] | None = ..., + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> None: ... + else: + def __init__( + self, + database: StrOrBytesPath, + timeout: float = 5.0, + detect_types: int = 0, + isolation_level: _IsolationLevel = "DEFERRED", + check_same_thread: bool = True, + factory: type[Connection] | None = ..., + cached_statements: int = 128, + uri: bool = False, + ) -> None: ... + + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = "main") -> Blob: ... + + def commit(self) -> None: ... + if sys.version_info >= (3, 15): + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol], /) -> None: ... + else: + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... + if sys.version_info >= (3, 11): + # num_params determines how many params will be passed to the aggregate class. We provide an overload + # for the case where num_params = 1, which is expected to be the common case. + @overload + def create_window_function( + self, name: str, num_params: Literal[1], aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None, / + ) -> None: ... + # And for num_params = -1, which means the aggregate must accept any number of parameters. + @overload + def create_window_function( + self, name: str, num_params: Literal[-1], aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None, / + ) -> None: ... + @overload + def create_window_function( + self, name: str, num_params: int, aggregate_class: Callable[[], _WindowAggregateClass] | None, / + ) -> None: ... + + def create_collation(self, name: str, callback: Callable[[str, str], SupportsIndex] | None, /) -> None: ... + if sys.version_info >= (3, 15): + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, /, *, deterministic: bool = False + ) -> None: ... + else: + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False + ) -> None: ... + + @overload + def cursor(self, factory: None = None) -> Cursor: ... + @overload + def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ... + + def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: ... + def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: ... + def executescript(self, sql_script: str, /) -> Cursor: ... + def interrupt(self) -> None: ... + if sys.version_info >= (3, 13): + def iterdump(self, *, filter: str | None = None) -> Generator[str]: ... + else: + def iterdump(self) -> Generator[str]: ... + + def rollback(self) -> None: ... + if sys.version_info >= (3, 15): + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None, / + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, /, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None, /) -> None: ... + else: + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... + # enable_load_extension and load_extension is not available on python distributions compiled + # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 + def enable_load_extension(self, enable: bool, /) -> None: ... + if sys.version_info >= (3, 12): + def load_extension(self, name: str, /, *, entrypoint: str | None = None) -> None: ... + else: + def load_extension(self, name: str, /) -> None: ... + + def backup( + self, + target: Connection, + *, + pages: int = -1, + progress: Callable[[int, int, int], object] | None = None, + name: str = "main", + sleep: float = 0.25, + ) -> None: ... + if sys.version_info >= (3, 11): + def setlimit(self, category: int, limit: int, /) -> int: ... + def getlimit(self, category: int, /) -> int: ... + def serialize(self, *, name: str = "main") -> bytes: ... + def deserialize(self, data: ReadableBuffer, /, *, name: str = "main") -> None: ... + if sys.version_info >= (3, 12): + def getconfig(self, op: int, /) -> bool: ... + def setconfig(self, op: int, enable: bool = True, /) -> bool: ... + + def __call__(self, sql: str, /) -> _Statement: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / + ) -> Literal[False]: ... + +@disjoint_base +class Cursor: + arraysize: int + @property + def connection(self) -> Connection: ... + # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives. + @property + def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | MaybeNone: ... + @property + def lastrowid(self) -> int | None: ... + row_factory: _RowFactoryOptions + @property + def rowcount(self) -> int: ... + def __init__(self, cursor: Connection, /) -> None: ... + def close(self) -> None: ... + def execute(self, sql: str, parameters: _Parameters = (), /) -> Self: ... + def executemany(self, sql: str, seq_of_parameters: Iterable[_Parameters], /) -> Self: ... + def executescript(self, sql_script: str, /) -> Cursor: ... + def fetchall(self) -> list[Any]: ... + def fetchmany(self, size: int | None = 1) -> list[Any]: ... + # Returns either a row (as created by the row_factory) or None, but + # putting None in the return annotation causes annoying false positives. + def fetchone(self) -> Any: ... + def setinputsizes(self, sizes: Unused, /) -> None: ... # does nothing + def setoutputsize(self, size: Unused, column: Unused = None, /) -> None: ... # does nothing + def __iter__(self) -> Self: ... + def __next__(self) -> Any: ... + +@final +class PrepareProtocol: + def __init__(self, *args: object, **kwargs: object) -> None: ... + +@disjoint_base +class Row(Sequence[Any]): + def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ... + def keys(self) -> list[str]: ... + + @overload # Note: really needs int instead of SupportsIndex + def __getitem__(self, key: int | str, /) -> Any: ... + @overload # Note: SupportsIndex does work within slices. + def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[Any, ...]: ... + + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... + def __len__(self) -> int: ... + # These return NotImplemented for anything that is not a Row. + def __eq__(self, value: object, /) -> bool: ... + def __ge__(self, value: object, /) -> bool: ... + def __gt__(self, value: object, /) -> bool: ... + def __le__(self, value: object, /) -> bool: ... + def __lt__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + +# This class is not exposed. It calls itself sqlite3.Statement. +@final +@type_check_only +class _Statement: ... + +if sys.version_info >= (3, 11): + @final + class Blob: + def close(self) -> None: ... + def read(self, length: int = -1, /) -> bytes: ... + def write(self, data: ReadableBuffer, /) -> None: ... + def tell(self) -> int: ... + # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END + def seek(self, offset: int, origin: int = 0, /) -> None: ... + def __len__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: object, val: object, tb: object, /) -> Literal[False]: ... + def __getitem__(self, key: SupportsIndex | slice, /) -> int: ... + def __setitem__(self, key: SupportsIndex | slice, value: int, /) -> None: ... diff --git a/stdlib/sqlite3/dbapi2.pyi b/stdlib/sqlite3/dbapi2.pyi new file mode 100644 index 000000000000..0cd676f9bfc8 --- /dev/null +++ b/stdlib/sqlite3/dbapi2.pyi @@ -0,0 +1,244 @@ +import sys +from _sqlite3 import ( + PARSE_COLNAMES as PARSE_COLNAMES, + PARSE_DECLTYPES as PARSE_DECLTYPES, + SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE, + SQLITE_ANALYZE as SQLITE_ANALYZE, + SQLITE_ATTACH as SQLITE_ATTACH, + SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX, + SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE, + SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX, + SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE, + SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER, + SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW, + SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER, + SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW, + SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE, + SQLITE_DELETE as SQLITE_DELETE, + SQLITE_DENY as SQLITE_DENY, + SQLITE_DETACH as SQLITE_DETACH, + SQLITE_DONE as SQLITE_DONE, + SQLITE_DROP_INDEX as SQLITE_DROP_INDEX, + SQLITE_DROP_TABLE as SQLITE_DROP_TABLE, + SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX, + SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE, + SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER, + SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW, + SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER, + SQLITE_DROP_VIEW as SQLITE_DROP_VIEW, + SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE, + SQLITE_FUNCTION as SQLITE_FUNCTION, + SQLITE_IGNORE as SQLITE_IGNORE, + SQLITE_INSERT as SQLITE_INSERT, + SQLITE_OK as SQLITE_OK, + SQLITE_PRAGMA as SQLITE_PRAGMA, + SQLITE_READ as SQLITE_READ, + SQLITE_RECURSIVE as SQLITE_RECURSIVE, + SQLITE_REINDEX as SQLITE_REINDEX, + SQLITE_SAVEPOINT as SQLITE_SAVEPOINT, + SQLITE_SELECT as SQLITE_SELECT, + SQLITE_TRANSACTION as SQLITE_TRANSACTION, + SQLITE_UPDATE as SQLITE_UPDATE, + adapt as adapt, + adapters as adapters, + complete_statement as complete_statement, + connect as connect, + converters as converters, + enable_callback_tracebacks as enable_callback_tracebacks, + register_adapter as register_adapter, + register_converter as register_converter, + sqlite_version as sqlite_version, +) +from datetime import date, datetime, time +from sqlite3 import ( + Connection as Connection, + Cursor as Cursor, + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + PrepareProtocol as PrepareProtocol, + ProgrammingError as ProgrammingError, + Row as Row, + Warning as Warning, +) +from typing import Final, Literal +from typing_extensions import deprecated + +if sys.version_info >= (3, 12): + from _sqlite3 import ( + LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL, + SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE, + SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL, + SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML, + SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY, + SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, + SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, + SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG, + SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER, + SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW, + SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, + SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, + SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, + SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE, + SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP, + SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA, + SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA, + ) + +if sys.version_info >= (3, 15): + from _sqlite3 import SQLITE_KEYWORDS as SQLITE_KEYWORDS + +if sys.version_info >= (3, 11): + from _sqlite3 import ( + SQLITE_ABORT as SQLITE_ABORT, + SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK, + SQLITE_AUTH as SQLITE_AUTH, + SQLITE_AUTH_USER as SQLITE_AUTH_USER, + SQLITE_BUSY as SQLITE_BUSY, + SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY, + SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT, + SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT, + SQLITE_CANTOPEN as SQLITE_CANTOPEN, + SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH, + SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL, + SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH, + SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR, + SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR, + SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK, + SQLITE_CONSTRAINT as SQLITE_CONSTRAINT, + SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK, + SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK, + SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY, + SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION, + SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL, + SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED, + SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY, + SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID, + SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER, + SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE, + SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB, + SQLITE_CORRUPT as SQLITE_CORRUPT, + SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX, + SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE, + SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB, + SQLITE_EMPTY as SQLITE_EMPTY, + SQLITE_ERROR as SQLITE_ERROR, + SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ, + SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY, + SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT, + SQLITE_FORMAT as SQLITE_FORMAT, + SQLITE_FULL as SQLITE_FULL, + SQLITE_INTERNAL as SQLITE_INTERNAL, + SQLITE_INTERRUPT as SQLITE_INTERRUPT, + SQLITE_IOERR as SQLITE_IOERR, + SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS, + SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH, + SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC, + SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED, + SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK, + SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE, + SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC, + SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH, + SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS, + SQLITE_IOERR_DATA as SQLITE_IOERR_DATA, + SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE, + SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT, + SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE, + SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC, + SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT, + SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC, + SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH, + SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK, + SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP, + SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM, + SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK, + SQLITE_IOERR_READ as SQLITE_IOERR_READ, + SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC, + SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK, + SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK, + SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP, + SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN, + SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE, + SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ, + SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE, + SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK, + SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE, + SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE, + SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED, + SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN, + SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT, + SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH, + SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG, + SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH, + SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH, + SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH, + SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH, + SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER, + SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP, + SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS, + SQLITE_LOCKED as SQLITE_LOCKED, + SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE, + SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB, + SQLITE_MISMATCH as SQLITE_MISMATCH, + SQLITE_MISUSE as SQLITE_MISUSE, + SQLITE_NOLFS as SQLITE_NOLFS, + SQLITE_NOMEM as SQLITE_NOMEM, + SQLITE_NOTADB as SQLITE_NOTADB, + SQLITE_NOTFOUND as SQLITE_NOTFOUND, + SQLITE_NOTICE as SQLITE_NOTICE, + SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK, + SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL, + SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY, + SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK, + SQLITE_PERM as SQLITE_PERM, + SQLITE_PROTOCOL as SQLITE_PROTOCOL, + SQLITE_RANGE as SQLITE_RANGE, + SQLITE_READONLY as SQLITE_READONLY, + SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT, + SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK, + SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED, + SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY, + SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY, + SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK, + SQLITE_ROW as SQLITE_ROW, + SQLITE_SCHEMA as SQLITE_SCHEMA, + SQLITE_TOOBIG as SQLITE_TOOBIG, + SQLITE_WARNING as SQLITE_WARNING, + SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX, + ) + from sqlite3 import Blob as Blob + +if sys.version_info < (3, 14): + # Deprecated and removed from _sqlite3 in 3.12, but removed from here in 3.14. + version: Final[str] + +if sys.version_info < (3, 12): + # deprecation wrapper that has a different name for the argument... + @deprecated( + "Deprecated since Python 3.10; removed in Python 3.12. " + "Open database in URI mode using `cache=shared` parameter instead." + ) + def enable_shared_cache(enable: int) -> None: ... + +paramstyle: Final = "qmark" +threadsafety: Literal[0, 1, 3] +apilevel: Final[str] +Date = date +Time = time +Timestamp = datetime + +def DateFromTicks(ticks: float) -> Date: ... +def TimeFromTicks(ticks: float) -> Time: ... +def TimestampFromTicks(ticks: float) -> Timestamp: ... + +if sys.version_info < (3, 14): + # Deprecated in 3.12, removed in 3.14. + version_info: Final[tuple[int, int, int]] + +sqlite_version_info: Final[tuple[int, int, int]] +Binary = memoryview diff --git a/stdlib/sqlite3/dump.pyi b/stdlib/sqlite3/dump.pyi new file mode 100644 index 000000000000..ed95fa46e1c7 --- /dev/null +++ b/stdlib/sqlite3/dump.pyi @@ -0,0 +1,2 @@ +# This file is intentionally empty. The runtime module contains only +# private functions. diff --git a/stdlib/sre_compile.pyi b/stdlib/sre_compile.pyi new file mode 100644 index 000000000000..486b2f743eeb --- /dev/null +++ b/stdlib/sre_compile.pyi @@ -0,0 +1,12 @@ +from re import Pattern +from sre_constants import * +from sre_constants import _NamedIntConstant +from sre_parse import SubPattern +from typing import Any, Final +from typing_extensions import TypeIs + +MAXCODE: Final[int] + +def dis(code: list[_NamedIntConstant]) -> None: ... +def isstring(obj: object) -> TypeIs[str | bytes]: ... +def compile(p: str | bytes | SubPattern, flags: int = 0) -> Pattern[Any]: ... diff --git a/stdlib/sre_constants.pyi b/stdlib/sre_constants.pyi new file mode 100644 index 000000000000..9a1da4ac89e7 --- /dev/null +++ b/stdlib/sre_constants.pyi @@ -0,0 +1,135 @@ +import sys +from re import error as error +from typing import Final +from typing_extensions import Self, disjoint_base + +MAXGROUPS: Final[int] + +MAGIC: Final[int] + +if sys.version_info >= (3, 12): + class _NamedIntConstant(int): + name: str + def __new__(cls, value: int, name: str) -> Self: ... + +else: + @disjoint_base + class _NamedIntConstant(int): + name: str + def __new__(cls, value: int, name: str) -> Self: ... + +MAXREPEAT: Final[_NamedIntConstant] +OPCODES: list[_NamedIntConstant] +ATCODES: list[_NamedIntConstant] +CHCODES: list[_NamedIntConstant] +OP_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +OP_LOCALE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +OP_UNICODE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +AT_MULTILINE: dict[_NamedIntConstant, _NamedIntConstant] +AT_LOCALE: dict[_NamedIntConstant, _NamedIntConstant] +AT_UNICODE: dict[_NamedIntConstant, _NamedIntConstant] +CH_LOCALE: dict[_NamedIntConstant, _NamedIntConstant] +CH_UNICODE: dict[_NamedIntConstant, _NamedIntConstant] +if sys.version_info >= (3, 14): + CH_NEGATE: dict[_NamedIntConstant, _NamedIntConstant] +# flags +if sys.version_info < (3, 13): + SRE_FLAG_TEMPLATE: Final = 1 +SRE_FLAG_IGNORECASE: Final = 2 +SRE_FLAG_LOCALE: Final = 4 +SRE_FLAG_MULTILINE: Final = 8 +SRE_FLAG_DOTALL: Final = 16 +SRE_FLAG_UNICODE: Final = 32 +SRE_FLAG_VERBOSE: Final = 64 +SRE_FLAG_DEBUG: Final = 128 +SRE_FLAG_ASCII: Final = 256 +# flags for INFO primitive +SRE_INFO_PREFIX: Final = 1 +SRE_INFO_LITERAL: Final = 2 +SRE_INFO_CHARSET: Final = 4 + +# Stubgen above; manually defined constants below (dynamic at runtime) + +# from OPCODES +FAILURE: Final[_NamedIntConstant] +SUCCESS: Final[_NamedIntConstant] +ANY: Final[_NamedIntConstant] +ANY_ALL: Final[_NamedIntConstant] +ASSERT: Final[_NamedIntConstant] +ASSERT_NOT: Final[_NamedIntConstant] +AT: Final[_NamedIntConstant] +BRANCH: Final[_NamedIntConstant] +if sys.version_info < (3, 11): + CALL: Final[_NamedIntConstant] +CATEGORY: Final[_NamedIntConstant] +CHARSET: Final[_NamedIntConstant] +BIGCHARSET: Final[_NamedIntConstant] +GROUPREF: Final[_NamedIntConstant] +GROUPREF_EXISTS: Final[_NamedIntConstant] +GROUPREF_IGNORE: Final[_NamedIntConstant] +IN: Final[_NamedIntConstant] +IN_IGNORE: Final[_NamedIntConstant] +INFO: Final[_NamedIntConstant] +JUMP: Final[_NamedIntConstant] +LITERAL: Final[_NamedIntConstant] +LITERAL_IGNORE: Final[_NamedIntConstant] +MARK: Final[_NamedIntConstant] +MAX_UNTIL: Final[_NamedIntConstant] +MIN_UNTIL: Final[_NamedIntConstant] +NOT_LITERAL: Final[_NamedIntConstant] +NOT_LITERAL_IGNORE: Final[_NamedIntConstant] +NEGATE: Final[_NamedIntConstant] +RANGE: Final[_NamedIntConstant] +REPEAT: Final[_NamedIntConstant] +REPEAT_ONE: Final[_NamedIntConstant] +SUBPATTERN: Final[_NamedIntConstant] +MIN_REPEAT_ONE: Final[_NamedIntConstant] +if sys.version_info >= (3, 11): + ATOMIC_GROUP: Final[_NamedIntConstant] + POSSESSIVE_REPEAT: Final[_NamedIntConstant] + POSSESSIVE_REPEAT_ONE: Final[_NamedIntConstant] +RANGE_UNI_IGNORE: Final[_NamedIntConstant] +GROUPREF_LOC_IGNORE: Final[_NamedIntConstant] +GROUPREF_UNI_IGNORE: Final[_NamedIntConstant] +IN_LOC_IGNORE: Final[_NamedIntConstant] +IN_UNI_IGNORE: Final[_NamedIntConstant] +LITERAL_LOC_IGNORE: Final[_NamedIntConstant] +LITERAL_UNI_IGNORE: Final[_NamedIntConstant] +NOT_LITERAL_LOC_IGNORE: Final[_NamedIntConstant] +NOT_LITERAL_UNI_IGNORE: Final[_NamedIntConstant] +MIN_REPEAT: Final[_NamedIntConstant] +MAX_REPEAT: Final[_NamedIntConstant] + +# from ATCODES +AT_BEGINNING: Final[_NamedIntConstant] +AT_BEGINNING_LINE: Final[_NamedIntConstant] +AT_BEGINNING_STRING: Final[_NamedIntConstant] +AT_BOUNDARY: Final[_NamedIntConstant] +AT_NON_BOUNDARY: Final[_NamedIntConstant] +AT_END: Final[_NamedIntConstant] +AT_END_LINE: Final[_NamedIntConstant] +AT_END_STRING: Final[_NamedIntConstant] +AT_LOC_BOUNDARY: Final[_NamedIntConstant] +AT_LOC_NON_BOUNDARY: Final[_NamedIntConstant] +AT_UNI_BOUNDARY: Final[_NamedIntConstant] +AT_UNI_NON_BOUNDARY: Final[_NamedIntConstant] + +# from CHCODES +CATEGORY_DIGIT: Final[_NamedIntConstant] +CATEGORY_NOT_DIGIT: Final[_NamedIntConstant] +CATEGORY_SPACE: Final[_NamedIntConstant] +CATEGORY_NOT_SPACE: Final[_NamedIntConstant] +CATEGORY_WORD: Final[_NamedIntConstant] +CATEGORY_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_NOT_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_LOC_WORD: Final[_NamedIntConstant] +CATEGORY_LOC_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_DIGIT: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_DIGIT: Final[_NamedIntConstant] +CATEGORY_UNI_SPACE: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_SPACE: Final[_NamedIntConstant] +CATEGORY_UNI_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_WORD: Final[_NamedIntConstant] +CATEGORY_UNI_LINEBREAK: Final[_NamedIntConstant] +CATEGORY_UNI_NOT_LINEBREAK: Final[_NamedIntConstant] diff --git a/stdlib/sre_parse.pyi b/stdlib/sre_parse.pyi new file mode 100644 index 000000000000..6b873f4043b0 --- /dev/null +++ b/stdlib/sre_parse.pyi @@ -0,0 +1,102 @@ +import sys +from collections.abc import Iterable +from re import Match, Pattern as _Pattern +from sre_constants import * +from sre_constants import _NamedIntConstant as _NIC, error as _Error +from typing import Any, Final, TypeAlias, overload + +SPECIAL_CHARS: Final = ".\\[{()*+?^$|" +REPEAT_CHARS: Final = "*+?{" +DIGITS: Final[frozenset[str]] +OCTDIGITS: Final[frozenset[str]] +HEXDIGITS: Final[frozenset[str]] +ASCIILETTERS: Final[frozenset[str]] +WHITESPACE: Final[frozenset[str]] +ESCAPES: Final[dict[str, tuple[_NIC, int]]] +CATEGORIES: Final[dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]]] +FLAGS: Final[dict[str, int]] +TYPE_FLAGS: Final[int] +GLOBAL_FLAGS: Final[int] + +if sys.version_info >= (3, 11): + MAXWIDTH: Final[int] + +if sys.version_info < (3, 11): + class Verbose(Exception): ... + +_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern] +_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern] +_OpInType: TypeAlias = list[tuple[_NIC, int]] +_OpBranchType: TypeAlias = tuple[None, list[SubPattern]] +_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType +_CodeType: TypeAlias = tuple[_NIC, _AvType] + +class State: + flags: int + groupdict: dict[str, int] + groupwidths: list[int | None] + lookbehindgroups: int | None + @property + def groups(self) -> int: ... + def opengroup(self, name: str | None = None) -> int: ... + def closegroup(self, gid: int, p: SubPattern) -> None: ... + def checkgroup(self, gid: int) -> bool: ... + def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... + +class SubPattern: + data: list[_CodeType] + width: int | None + state: State + + def __init__(self, state: State, data: list[_CodeType] | None = None) -> None: ... + def dump(self, level: int = 0) -> None: ... + def __len__(self) -> int: ... + def __delitem__(self, index: int | slice) -> None: ... + def __getitem__(self, index: int | slice) -> SubPattern | _CodeType: ... + def __setitem__(self, index: int | slice, code: _CodeType) -> None: ... + def insert(self, index: int, code: _CodeType) -> None: ... + def append(self, code: _CodeType) -> None: ... + def getwidth(self) -> tuple[int, int]: ... + +class Tokenizer: + istext: bool + string: Any + decoded_string: str + index: int + next: str | None + def __init__(self, string: Any) -> None: ... + def match(self, char: str) -> bool: ... + def get(self) -> str | None: ... + def getwhile(self, n: int, charset: Iterable[str]) -> str: ... + def getuntil(self, terminator: str, name: str) -> str: ... + @property + def pos(self) -> int: ... + def tell(self) -> int: ... + def seek(self, index: int) -> None: ... + def error(self, msg: str, offset: int = 0) -> _Error: ... + + if sys.version_info >= (3, 12): + def checkgroupname(self, name: str, offset: int) -> None: ... + elif sys.version_info >= (3, 11): + def checkgroupname(self, name: str, offset: int, nested: int) -> None: ... + +def fix_flags(src: str | bytes, flags: int) -> int: ... + +_TemplateType: TypeAlias = tuple[list[tuple[int, int]], list[str | None]] +_TemplateByteType: TypeAlias = tuple[list[tuple[int, int]], list[bytes | None]] + +if sys.version_info >= (3, 12): + @overload + def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... + @overload + def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... +else: + @overload + def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... + @overload + def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ... + +def parse(str: str, flags: int = 0, state: State | None = None) -> SubPattern: ... + +if sys.version_info < (3, 12): + def expand_template(template: _TemplateType, match: Match[Any]) -> str: ... diff --git a/stdlib/ssl.pyi b/stdlib/ssl.pyi new file mode 100644 index 000000000000..8d71e4763959 --- /dev/null +++ b/stdlib/ssl.pyi @@ -0,0 +1,540 @@ +import enum +import socket +import sys +from _ssl import ( + _DEFAULT_CIPHERS as _DEFAULT_CIPHERS, + _OPENSSL_API_VERSION as _OPENSSL_API_VERSION, + HAS_ALPN as HAS_ALPN, + HAS_ECDH as HAS_ECDH, + HAS_NPN as HAS_NPN, + HAS_SNI as HAS_SNI, + OPENSSL_VERSION as OPENSSL_VERSION, + OPENSSL_VERSION_INFO as OPENSSL_VERSION_INFO, + OPENSSL_VERSION_NUMBER as OPENSSL_VERSION_NUMBER, + HAS_SSLv2 as HAS_SSLv2, + HAS_SSLv3 as HAS_SSLv3, + HAS_TLSv1 as HAS_TLSv1, + HAS_TLSv1_1 as HAS_TLSv1_1, + HAS_TLSv1_2 as HAS_TLSv1_2, + HAS_TLSv1_3 as HAS_TLSv1_3, + MemoryBIO as MemoryBIO, + RAND_add as RAND_add, + RAND_bytes as RAND_bytes, + RAND_status as RAND_status, + SSLSession as SSLSession, + _PasswordType as _PasswordType, # typeshed only, but re-export for other type stubs to use + _SSLContext, +) +from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer +from collections.abc import Callable, Iterable +from typing import Any, Final, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated + +if sys.version_info >= (3, 13): + from _ssl import HAS_PSK as HAS_PSK + +if sys.version_info >= (3, 15): + from _ssl import HAS_PSK_TLS13 as HAS_PSK_TLS13 + +if sys.version_info >= (3, 14): + from _ssl import HAS_PHA as HAS_PHA + +if sys.version_info < (3, 12): + from _ssl import RAND_pseudo_bytes as RAND_pseudo_bytes + +if sys.platform == "win32": + from _ssl import enum_certificates as enum_certificates, enum_crls as enum_crls + +_PCTRTT: TypeAlias = tuple[tuple[str, str], ...] +_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...] +_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT] +_PeerCertRetType: TypeAlias = _PeerCertRetDictType | bytes | None +_SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None] + +socket_error = OSError + +@type_check_only +class _Cipher(TypedDict): + aead: bool + alg_bits: int + auth: str + description: str + digest: str | None + id: int + kea: str + name: str + protocol: str + strength_bits: int + symmetric: str + +class SSLError(OSError): + library: str + reason: str + +class SSLZeroReturnError(SSLError): ... +class SSLWantReadError(SSLError): ... +class SSLWantWriteError(SSLError): ... +class SSLSyscallError(SSLError): ... +class SSLEOFError(SSLError): ... + +class SSLCertVerificationError(SSLError, ValueError): + verify_code: int + verify_message: str + +CertificateError = SSLCertVerificationError + +class DefaultVerifyPaths(NamedTuple): + cafile: str + capath: str + openssl_cafile_env: str + openssl_cafile: str + openssl_capath_env: str + openssl_capath: str + +def get_default_verify_paths() -> DefaultVerifyPaths: ... + +class VerifyMode(enum.IntEnum): + CERT_NONE = 0 + CERT_OPTIONAL = 1 + CERT_REQUIRED = 2 + +CERT_NONE: Final = VerifyMode.CERT_NONE +CERT_OPTIONAL: Final = VerifyMode.CERT_OPTIONAL +CERT_REQUIRED: Final = VerifyMode.CERT_REQUIRED + +class VerifyFlags(enum.IntFlag): + VERIFY_DEFAULT = 0x00 + VERIFY_CRL_CHECK_LEAF = 0x04 + VERIFY_CRL_CHECK_CHAIN = 0x0C + VERIFY_X509_STRICT = 0x20 + VERIFY_X509_TRUSTED_FIRST = 0x8000 + VERIFY_ALLOW_PROXY_CERTS = 0x40 + VERIFY_X509_PARTIAL_CHAIN = 0x80000 + +VERIFY_DEFAULT: Final = VerifyFlags.VERIFY_DEFAULT +VERIFY_CRL_CHECK_LEAF: Final = VerifyFlags.VERIFY_CRL_CHECK_LEAF +VERIFY_CRL_CHECK_CHAIN: Final = VerifyFlags.VERIFY_CRL_CHECK_CHAIN +VERIFY_X509_STRICT: Final = VerifyFlags.VERIFY_X509_STRICT +VERIFY_X509_TRUSTED_FIRST: Final = VerifyFlags.VERIFY_X509_TRUSTED_FIRST +VERIFY_ALLOW_PROXY_CERTS: Final = VerifyFlags.VERIFY_ALLOW_PROXY_CERTS +VERIFY_X509_PARTIAL_CHAIN: Final = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN + +class _SSLMethod(enum.IntEnum): + PROTOCOL_SSLv23 = 2 + PROTOCOL_SSLv2 = ... + PROTOCOL_SSLv3 = ... + PROTOCOL_TLSv1 = 3 + PROTOCOL_TLSv1_1 = 4 + PROTOCOL_TLSv1_2 = 5 + PROTOCOL_TLS = 2 + PROTOCOL_TLS_CLIENT = 16 + PROTOCOL_TLS_SERVER = 17 + +PROTOCOL_SSLv23: Final = _SSLMethod.PROTOCOL_SSLv23 +PROTOCOL_SSLv2: Final = _SSLMethod.PROTOCOL_SSLv2 +PROTOCOL_SSLv3: Final = _SSLMethod.PROTOCOL_SSLv3 +PROTOCOL_TLSv1: Final = _SSLMethod.PROTOCOL_TLSv1 +PROTOCOL_TLSv1_1: Final = _SSLMethod.PROTOCOL_TLSv1_1 +PROTOCOL_TLSv1_2: Final = _SSLMethod.PROTOCOL_TLSv1_2 +PROTOCOL_TLS: Final = _SSLMethod.PROTOCOL_TLS +PROTOCOL_TLS_CLIENT: Final = _SSLMethod.PROTOCOL_TLS_CLIENT +PROTOCOL_TLS_SERVER: Final = _SSLMethod.PROTOCOL_TLS_SERVER + +class Options(enum.IntFlag): + OP_ALL: int + OP_NO_SSLv2 = 0 + OP_NO_SSLv3 = 33554432 + OP_NO_TLSv1 = 67108864 + OP_NO_TLSv1_1 = 268435456 + OP_NO_TLSv1_2 = 134217728 + OP_NO_TLSv1_3 = 536870912 + OP_CIPHER_SERVER_PREFERENCE = 4194304 + OP_SINGLE_DH_USE = 0 + OP_SINGLE_ECDH_USE = 0 + OP_NO_COMPRESSION = 131072 + OP_NO_TICKET = 16384 + OP_NO_RENEGOTIATION = 1073741824 + OP_ENABLE_MIDDLEBOX_COMPAT = 1048576 + if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT = 4 + OP_ENABLE_KTLS = 8 + if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF = 128 + +OP_ALL: Final = Options.OP_ALL +OP_NO_SSLv2: Final = Options.OP_NO_SSLv2 +OP_NO_SSLv3: Final = Options.OP_NO_SSLv3 +OP_NO_TLSv1: Final = Options.OP_NO_TLSv1 +OP_NO_TLSv1_1: Final = Options.OP_NO_TLSv1_1 +OP_NO_TLSv1_2: Final = Options.OP_NO_TLSv1_2 +OP_NO_TLSv1_3: Final = Options.OP_NO_TLSv1_3 +OP_CIPHER_SERVER_PREFERENCE: Final = Options.OP_CIPHER_SERVER_PREFERENCE +OP_SINGLE_DH_USE: Final = Options.OP_SINGLE_DH_USE +OP_SINGLE_ECDH_USE: Final = Options.OP_SINGLE_ECDH_USE +OP_NO_COMPRESSION: Final = Options.OP_NO_COMPRESSION +OP_NO_TICKET: Final = Options.OP_NO_TICKET +OP_NO_RENEGOTIATION: Final = Options.OP_NO_RENEGOTIATION +OP_ENABLE_MIDDLEBOX_COMPAT: Final = Options.OP_ENABLE_MIDDLEBOX_COMPAT +if sys.version_info >= (3, 12): + OP_LEGACY_SERVER_CONNECT: Final = Options.OP_LEGACY_SERVER_CONNECT + OP_ENABLE_KTLS: Final = Options.OP_ENABLE_KTLS +if sys.version_info >= (3, 11) or sys.platform == "linux": + OP_IGNORE_UNEXPECTED_EOF: Final = Options.OP_IGNORE_UNEXPECTED_EOF + +HAS_NEVER_CHECK_COMMON_NAME: Final[bool] + +CHANNEL_BINDING_TYPES: Final[list[str]] + +class AlertDescription(enum.IntEnum): + ALERT_DESCRIPTION_ACCESS_DENIED = 49 + ALERT_DESCRIPTION_BAD_CERTIFICATE = 42 + ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = 114 + ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = 113 + ALERT_DESCRIPTION_BAD_RECORD_MAC = 20 + ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = 45 + ALERT_DESCRIPTION_CERTIFICATE_REVOKED = 44 + ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = 46 + ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = 111 + ALERT_DESCRIPTION_CLOSE_NOTIFY = 0 + ALERT_DESCRIPTION_DECODE_ERROR = 50 + ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = 30 + ALERT_DESCRIPTION_DECRYPT_ERROR = 51 + ALERT_DESCRIPTION_HANDSHAKE_FAILURE = 40 + ALERT_DESCRIPTION_ILLEGAL_PARAMETER = 47 + ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = 71 + ALERT_DESCRIPTION_INTERNAL_ERROR = 80 + ALERT_DESCRIPTION_NO_RENEGOTIATION = 100 + ALERT_DESCRIPTION_PROTOCOL_VERSION = 70 + ALERT_DESCRIPTION_RECORD_OVERFLOW = 22 + ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = 10 + ALERT_DESCRIPTION_UNKNOWN_CA = 48 + ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = 115 + ALERT_DESCRIPTION_UNRECOGNIZED_NAME = 112 + ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = 43 + ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = 110 + ALERT_DESCRIPTION_USER_CANCELLED = 90 + +ALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_HANDSHAKE_FAILURE +ALERT_DESCRIPTION_INTERNAL_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_INTERNAL_ERROR +ALERT_DESCRIPTION_ACCESS_DENIED: Final = AlertDescription.ALERT_DESCRIPTION_ACCESS_DENIED +ALERT_DESCRIPTION_BAD_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE +ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE +ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE +ALERT_DESCRIPTION_BAD_RECORD_MAC: Final = AlertDescription.ALERT_DESCRIPTION_BAD_RECORD_MAC +ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_EXPIRED +ALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_REVOKED +ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN +ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE +ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = AlertDescription.ALERT_DESCRIPTION_CLOSE_NOTIFY +ALERT_DESCRIPTION_DECODE_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECODE_ERROR +ALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_DECOMPRESSION_FAILURE +ALERT_DESCRIPTION_DECRYPT_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECRYPT_ERROR +ALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = AlertDescription.ALERT_DESCRIPTION_ILLEGAL_PARAMETER +ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = AlertDescription.ALERT_DESCRIPTION_INSUFFICIENT_SECURITY +ALERT_DESCRIPTION_NO_RENEGOTIATION: Final = AlertDescription.ALERT_DESCRIPTION_NO_RENEGOTIATION +ALERT_DESCRIPTION_PROTOCOL_VERSION: Final = AlertDescription.ALERT_DESCRIPTION_PROTOCOL_VERSION +ALERT_DESCRIPTION_RECORD_OVERFLOW: Final = AlertDescription.ALERT_DESCRIPTION_RECORD_OVERFLOW +ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = AlertDescription.ALERT_DESCRIPTION_UNEXPECTED_MESSAGE +ALERT_DESCRIPTION_UNKNOWN_CA: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_CA +ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY +ALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = AlertDescription.ALERT_DESCRIPTION_UNRECOGNIZED_NAME +ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE +ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION +ALERT_DESCRIPTION_USER_CANCELLED: Final = AlertDescription.ALERT_DESCRIPTION_USER_CANCELLED + +# This class is not exposed. It calls itself ssl._ASN1Object. +@type_check_only +class _ASN1ObjectBase(NamedTuple): + nid: int + shortname: str + longname: str + oid: str + +class _ASN1Object(_ASN1ObjectBase): + def __new__(cls, oid: str) -> Self: ... + @classmethod + def fromnid(cls, nid: int) -> Self: ... + @classmethod + def fromname(cls, name: str) -> Self: ... + +class Purpose(_ASN1Object, enum.Enum): + # Normally this class would inherit __new__ from _ASN1Object, but + # because this is an enum, the inherited __new__ is replaced at runtime with + # Enum.__new__. + def __new__(cls, value: object) -> Self: ... + SERVER_AUTH = ( # ty:ignore[invalid-assignment] + 129, + "serverAuth", + "TLS Web Server Authentication", + "1.3.6.1.5.5.7.3.2", + ) # pyright: ignore[reportCallIssue] + CLIENT_AUTH = ( # ty:ignore[invalid-assignment] + 130, + "clientAuth", + "TLS Web Client Authentication", + "1.3.6.1.5.5.7.3.1", + ) # pyright: ignore[reportCallIssue] + +class SSLSocket(socket.socket): + context: SSLContext + server_side: bool + server_hostname: str | None + session: SSLSession | None + @property + def session_reused(self) -> bool | None: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def connect(self, addr: socket._Address) -> None: ... + def connect_ex(self, addr: socket._Address) -> int: ... + def recv(self, buflen: int = 1024, flags: int = 0) -> bytes: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0) -> int: ... + def recvfrom(self, buflen: int = 1024, flags: int = 0) -> tuple[bytes, socket._RetAddress]: ... + def recvfrom_into( + self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0 + ) -> tuple[int, socket._RetAddress]: ... + def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... + def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... + + @overload + def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address, addr: None = None) -> int: ... + @overload + def sendto(self, data: ReadableBuffer, flags_or_addr: int, addr: socket._Address) -> int: ... + + def shutdown(self, how: int) -> None: ... + @deprecated("Deprecated since Python 3.6. Use `SSLSocket.recv` method instead.") + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... + @deprecated("Deprecated since Python 3.6. Use `SSLSocket.send` method instead.") + def write(self, data: ReadableBuffer) -> int: ... + def do_handshake(self, block: bool = False) -> None: ... # block is undocumented + + @overload + def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... + @overload + def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... + @overload + def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + + def cipher(self) -> tuple[str, str, int] | None: ... + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... + def compression(self) -> str | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + + def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... + def selected_alpn_protocol(self) -> str | None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... + def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... + def unwrap(self) -> socket.socket: ... + def version(self) -> str | None: ... + def pending(self) -> int: ... + def verify_client_post_handshake(self) -> None: ... + # These methods always raise `NotImplementedError`: + def recvmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def recvmsg_into(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + def sendmsg(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] + if sys.version_info >= (3, 13): + def get_verified_chain(self) -> list[bytes]: ... + def get_unverified_chain(self) -> list[bytes]: ... + +if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.7; removed in Python 3.12. Use `SSLContext.wrap_socket()` instead.") + def wrap_socket( + sock: socket.socket, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + server_side: bool = False, + cert_reqs: int = VerifyMode.CERT_NONE, + ssl_version: int = _SSLMethod.PROTOCOL_TLS, + ca_certs: str | None = None, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str | None = None, + ) -> SSLSocket: ... + @deprecated("Deprecated since Python 3.7; removed in Python 3.12.") + def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: ... + +def cert_time_to_seconds(cert_time: str) -> int: ... +def DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: ... +def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... +def get_server_certificate( + addr: tuple[str, int], ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, ca_certs: str | None = None, timeout: float = ... +) -> str: ... + +class TLSVersion(enum.IntEnum): + MINIMUM_SUPPORTED = -2 + MAXIMUM_SUPPORTED = -1 + SSLv3 = 768 + TLSv1 = 769 + TLSv1_1 = 770 + TLSv1_2 = 771 + TLSv1_3 = 772 + +class SSLContext(_SSLContext): + options: Options + verify_flags: VerifyFlags + verify_mode: VerifyMode + @property + def protocol(self) -> _SSLMethod: ... # type: ignore[override] + hostname_checks_common_name: bool + maximum_version: TLSVersion + minimum_version: TLSVersion + # The following two attributes have class-level defaults. + # However, the docs explicitly state that it's OK to override these attributes on instances, + # so making these ClassVars wouldn't be appropriate + sslobject_class: type[SSLObject] + sslsocket_class: type[SSLSocket] + keylog_filename: str + post_handshake_auth: bool + security_level: int + + @overload + def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ... + @overload + @deprecated("Deprecated since Python 3.10. Use a specific version of the SSL protocol.") + def __new__(cls, protocol: None = None, *args: Any, **kwargs: Any) -> Self: ... + + def load_default_certs(self, purpose: Purpose = Purpose.SERVER_AUTH) -> None: ... + def load_verify_locations( + self, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, + ) -> None: ... + + @overload + def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = False) -> Any: ... + + def get_ciphers(self) -> list[_Cipher]: ... + if sys.version_info >= (3, 15): + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def get_groups(self, /, *, include_aliases: bool = False) -> list[str]: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_client_sigalgs(self, sigalgs: str, /) -> None: ... + def set_server_sigalgs(self, sigalgs: str, /) -> None: ... + + def set_default_verify_paths(self) -> None: ... + def set_ciphers(self, cipherlist: str, /) -> None: ... + def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... + def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... + def load_dh_params(self, path: str, /) -> None: ... + def set_ecdh_curve(self, name: str, /) -> None: ... + def wrap_socket( + self, + sock: socket.socket, + server_side: bool = False, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + server_hostname: str | bytes | None = None, + session: SSLSession | None = None, + ) -> SSLSocket: ... + def wrap_bio( + self, + incoming: MemoryBIO, + outgoing: MemoryBIO, + server_side: bool = False, + server_hostname: str | bytes | None = None, + session: SSLSession | None = None, + ) -> SSLObject: ... + +def create_default_context( + purpose: Purpose = Purpose.SERVER_AUTH, + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, +) -> SSLContext: ... +def _create_unverified_context( + protocol: int | None = None, + *, + cert_reqs: int = VerifyMode.CERT_NONE, + check_hostname: bool = False, + purpose: Purpose = Purpose.SERVER_AUTH, + certfile: StrOrBytesPath | None = None, + keyfile: StrOrBytesPath | None = None, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, +) -> SSLContext: ... + +_create_default_https_context = create_default_context + +class SSLObject: + context: SSLContext + @property + def server_side(self) -> bool: ... + @property + def server_hostname(self) -> str | None: ... + session: SSLSession | None + @property + def session_reused(self) -> bool: ... + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... + def write(self, data: ReadableBuffer) -> int: ... + + @overload + def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... + @overload + def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... + @overload + def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + + def selected_alpn_protocol(self) -> str | None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... + def cipher(self) -> tuple[str, str, int] | None: ... + def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... + def compression(self) -> str | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + + def pending(self) -> int: ... + def do_handshake(self) -> None: ... + def unwrap(self) -> None: ... + def version(self) -> str | None: ... + def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... + def verify_client_post_handshake(self) -> None: ... + if sys.version_info >= (3, 13): + def get_verified_chain(self) -> list[bytes]: ... + def get_unverified_chain(self) -> list[bytes]: ... + +class SSLErrorNumber(enum.IntEnum): + SSL_ERROR_EOF = 8 + SSL_ERROR_INVALID_ERROR_CODE = 10 + SSL_ERROR_SSL = 1 + SSL_ERROR_SYSCALL = 5 + SSL_ERROR_WANT_CONNECT = 7 + SSL_ERROR_WANT_READ = 2 + SSL_ERROR_WANT_WRITE = 3 + SSL_ERROR_WANT_X509_LOOKUP = 4 + SSL_ERROR_ZERO_RETURN = 6 + +SSL_ERROR_EOF: Final = SSLErrorNumber.SSL_ERROR_EOF # undocumented +SSL_ERROR_INVALID_ERROR_CODE: Final = SSLErrorNumber.SSL_ERROR_INVALID_ERROR_CODE # undocumented +SSL_ERROR_SSL: Final = SSLErrorNumber.SSL_ERROR_SSL # undocumented +SSL_ERROR_SYSCALL: Final = SSLErrorNumber.SSL_ERROR_SYSCALL # undocumented +SSL_ERROR_WANT_CONNECT: Final = SSLErrorNumber.SSL_ERROR_WANT_CONNECT # undocumented +SSL_ERROR_WANT_READ: Final = SSLErrorNumber.SSL_ERROR_WANT_READ # undocumented +SSL_ERROR_WANT_WRITE: Final = SSLErrorNumber.SSL_ERROR_WANT_WRITE # undocumented +SSL_ERROR_WANT_X509_LOOKUP: Final = SSLErrorNumber.SSL_ERROR_WANT_X509_LOOKUP # undocumented +SSL_ERROR_ZERO_RETURN: Final = SSLErrorNumber.SSL_ERROR_ZERO_RETURN # undocumented + +def get_protocol_name(protocol_code: int) -> str: ... + +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + +PEM_FOOTER: Final[str] +PEM_HEADER: Final[str] +SOCK_STREAM: Final = socket.SOCK_STREAM +SOL_SOCKET: Final = socket.SOL_SOCKET +SO_TYPE: Final = socket.SO_TYPE diff --git a/stdlib/stat.pyi b/stdlib/stat.pyi new file mode 100644 index 000000000000..155d765d2b16 --- /dev/null +++ b/stdlib/stat.pyi @@ -0,0 +1,126 @@ +import sys +from _stat import ( + S_ENFMT as S_ENFMT, + S_IEXEC as S_IEXEC, + S_IFBLK as S_IFBLK, + S_IFCHR as S_IFCHR, + S_IFDIR as S_IFDIR, + S_IFDOOR as S_IFDOOR, + S_IFIFO as S_IFIFO, + S_IFLNK as S_IFLNK, + S_IFMT as S_IFMT, + S_IFPORT as S_IFPORT, + S_IFREG as S_IFREG, + S_IFSOCK as S_IFSOCK, + S_IFWHT as S_IFWHT, + S_IMODE as S_IMODE, + S_IREAD as S_IREAD, + S_IRGRP as S_IRGRP, + S_IROTH as S_IROTH, + S_IRUSR as S_IRUSR, + S_IRWXG as S_IRWXG, + S_IRWXO as S_IRWXO, + S_IRWXU as S_IRWXU, + S_ISBLK as S_ISBLK, + S_ISCHR as S_ISCHR, + S_ISDIR as S_ISDIR, + S_ISDOOR as S_ISDOOR, + S_ISFIFO as S_ISFIFO, + S_ISGID as S_ISGID, + S_ISLNK as S_ISLNK, + S_ISPORT as S_ISPORT, + S_ISREG as S_ISREG, + S_ISSOCK as S_ISSOCK, + S_ISUID as S_ISUID, + S_ISVTX as S_ISVTX, + S_ISWHT as S_ISWHT, + S_IWGRP as S_IWGRP, + S_IWOTH as S_IWOTH, + S_IWRITE as S_IWRITE, + S_IWUSR as S_IWUSR, + S_IXGRP as S_IXGRP, + S_IXOTH as S_IXOTH, + S_IXUSR as S_IXUSR, + SF_APPEND as SF_APPEND, + SF_ARCHIVED as SF_ARCHIVED, + SF_IMMUTABLE as SF_IMMUTABLE, + SF_NOUNLINK as SF_NOUNLINK, + SF_SNAPSHOT as SF_SNAPSHOT, + ST_ATIME as ST_ATIME, + ST_CTIME as ST_CTIME, + ST_DEV as ST_DEV, + ST_GID as ST_GID, + ST_INO as ST_INO, + ST_MODE as ST_MODE, + ST_MTIME as ST_MTIME, + ST_NLINK as ST_NLINK, + ST_SIZE as ST_SIZE, + ST_UID as ST_UID, + UF_APPEND as UF_APPEND, + UF_COMPRESSED as UF_COMPRESSED, + UF_HIDDEN as UF_HIDDEN, + UF_IMMUTABLE as UF_IMMUTABLE, + UF_NODUMP as UF_NODUMP, + UF_NOUNLINK as UF_NOUNLINK, + UF_OPAQUE as UF_OPAQUE, + filemode as filemode, +) +from typing import Final + +if sys.platform == "win32": + from _stat import ( + IO_REPARSE_TAG_APPEXECLINK as IO_REPARSE_TAG_APPEXECLINK, + IO_REPARSE_TAG_MOUNT_POINT as IO_REPARSE_TAG_MOUNT_POINT, + IO_REPARSE_TAG_SYMLINK as IO_REPARSE_TAG_SYMLINK, + ) + +if sys.version_info >= (3, 13): + from _stat import ( + SF_DATALESS as SF_DATALESS, + SF_FIRMLINK as SF_FIRMLINK, + SF_SETTABLE as SF_SETTABLE, + UF_DATAVAULT as UF_DATAVAULT, + UF_SETTABLE as UF_SETTABLE, + UF_TRACKED as UF_TRACKED, + ) + + if sys.platform == "darwin": + from _stat import SF_SUPPORTED as SF_SUPPORTED, SF_SYNTHETIC as SF_SYNTHETIC + +# _stat.c defines FILE_ATTRIBUTE_* constants conditionally, +# making them available only at runtime on Windows. +# stat.py unconditionally redefines the same FILE_ATTRIBUTE_* constants +# on all platforms. +FILE_ATTRIBUTE_ARCHIVE: Final = 32 +FILE_ATTRIBUTE_COMPRESSED: Final = 2048 +FILE_ATTRIBUTE_DEVICE: Final = 64 +FILE_ATTRIBUTE_DIRECTORY: Final = 16 +FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 +FILE_ATTRIBUTE_HIDDEN: Final = 2 +FILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768 +FILE_ATTRIBUTE_NORMAL: Final = 128 +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 +FILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072 +FILE_ATTRIBUTE_OFFLINE: Final = 4096 +FILE_ATTRIBUTE_READONLY: Final = 1 +FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 +FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 +FILE_ATTRIBUTE_SYSTEM: Final = 4 +FILE_ATTRIBUTE_TEMPORARY: Final = 256 +FILE_ATTRIBUTE_VIRTUAL: Final = 65536 + +if sys.version_info >= (3, 13): + # https://github.com/python/cpython/issues/114081#issuecomment-2119017790 + SF_RESTRICTED: Final = 0x00080000 + +if sys.version_info >= (3, 15): + STATX_ATTR_COMPRESSED: Final = 0x00000004 + STATX_ATTR_IMMUTABLE: Final = 0x00000010 + STATX_ATTR_APPEND: Final = 0x00000020 + STATX_ATTR_NODUMP: Final = 0x00000040 + STATX_ATTR_ENCRYPTED: Final = 0x00000800 + STATX_ATTR_AUTOMOUNT: Final = 0x00001000 + STATX_ATTR_MOUNT_ROOT: Final = 0x00002000 + STATX_ATTR_VERITY: Final = 0x00100000 + STATX_ATTR_DAX: Final = 0x00200000 + STATX_ATTR_WRITE_ATOMIC: Final = 0x00400000 diff --git a/stdlib/statistics.pyi b/stdlib/statistics.pyi new file mode 100644 index 000000000000..8cae237f7e0b --- /dev/null +++ b/stdlib/statistics.pyi @@ -0,0 +1,161 @@ +import sys +from _typeshed import SupportsRichComparisonT +from collections.abc import Callable, Hashable, Iterable, Sequence, Sized +from decimal import Decimal +from fractions import Fraction +from typing import Literal, NamedTuple, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self + +__all__ = [ + "StatisticsError", + "covariance", + "correlation", + "fmean", + "geometric_mean", + "linear_regression", + "mean", + "harmonic_mean", + "pstdev", + "pvariance", + "stdev", + "variance", + "median", + "median_low", + "median_high", + "median_grouped", + "mode", + "multimode", + "NormalDist", + "quantiles", +] + +if sys.version_info >= (3, 13): + __all__ += ["kde", "kde_random"] + +# Most functions in this module accept homogeneous collections of one of these types +_Number: TypeAlias = float | Decimal | Fraction +_NumberT = TypeVar("_NumberT", float, Decimal, Fraction) + +# Used in mode, multimode +_HashableT = TypeVar("_HashableT", bound=Hashable) + +# Used in NormalDist.samples and kde_random +_Seed: TypeAlias = int | float | str | bytes | bytearray # noqa: Y041 + +# Used in linear_regression +_T_co = TypeVar("_T_co", covariant=True) + +@type_check_only +class _SizedIterable(Iterable[_T_co], Sized, Protocol[_T_co]): ... + +class StatisticsError(ValueError): ... + +if sys.version_info >= (3, 11): + def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = None) -> float: ... + +else: + def fmean(data: Iterable[SupportsFloat]) -> float: ... + +def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... +def mean(data: Iterable[_NumberT]) -> _NumberT: ... +def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: ... +def median(data: Iterable[_NumberT]) -> _NumberT: ... +def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... +def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... + +if sys.version_info >= (3, 11): + def median_grouped(data: Iterable[SupportsFloat], interval: SupportsFloat = 1.0) -> float: ... + +else: + def median_grouped(data: Iterable[_NumberT], interval: _NumberT | float = 1) -> _NumberT | float: ... + +def mode(data: Iterable[_HashableT]) -> _HashableT: ... +def multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ... +def pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... +def pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ... +def quantiles( + data: Iterable[_NumberT], *, n: int = 4, method: Literal["inclusive", "exclusive"] = "exclusive" +) -> list[_NumberT]: ... +def stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... +def variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ... + +class NormalDist: + __slots__ = {"_mu": "Arithmetic mean of a normal distribution", "_sigma": "Standard deviation of a normal distribution"} + def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: ... + @property + def mean(self) -> float: ... + @property + def median(self) -> float: ... + @property + def mode(self) -> float: ... + @property + def stdev(self) -> float: ... + @property + def variance(self) -> float: ... + @classmethod + def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ... + def samples(self, n: SupportsIndex, *, seed: _Seed | None = None) -> list[float]: ... + def pdf(self, x: float) -> float: ... + def cdf(self, x: float) -> float: ... + def inv_cdf(self, p: float) -> float: ... + def overlap(self, other: NormalDist) -> float: ... + def quantiles(self, n: int = 4) -> list[float]: ... + def zscore(self, x: float) -> float: ... + def __eq__(x1, x2: object) -> bool: ... + def __add__(x1, x2: float | NormalDist) -> NormalDist: ... + def __sub__(x1, x2: float | NormalDist) -> NormalDist: ... + def __mul__(x1, x2: float) -> NormalDist: ... + def __truediv__(x1, x2: float) -> NormalDist: ... + def __pos__(x1) -> NormalDist: ... + def __neg__(x1) -> NormalDist: ... + __radd__ = __add__ + def __rsub__(x1, x2: float | NormalDist) -> NormalDist: ... + __rmul__ = __mul__ + def __hash__(self) -> int: ... + +if sys.version_info >= (3, 12): + def correlation( + x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal["linear", "ranked"] = "linear" + ) -> float: ... + +else: + def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... + +def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... + +class LinearRegression(NamedTuple): + slope: float + intercept: float + +if sys.version_info >= (3, 11): + def linear_regression( + regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], /, *, proportional: bool = False + ) -> LinearRegression: ... + +else: + def linear_regression( + regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], / + ) -> LinearRegression: ... + +if sys.version_info >= (3, 13): + _Kernel: TypeAlias = Literal[ + "normal", + "gauss", + "logistic", + "sigmoid", + "rectangular", + "uniform", + "triangular", + "parabolic", + "epanechnikov", + "quartic", + "biweight", + "triweight", + "cosine", + ] + def kde( + data: Sequence[float], h: float, kernel: _Kernel = "normal", *, cumulative: bool = False + ) -> Callable[[float], float]: ... + def kde_random( + data: Sequence[float], h: float, kernel: _Kernel = "normal", *, seed: _Seed | None = None + ) -> Callable[[], float]: ... diff --git a/stdlib/string/__init__.pyi b/stdlib/string/__init__.pyi new file mode 100644 index 000000000000..df70cdc6b21c --- /dev/null +++ b/stdlib/string/__init__.pyi @@ -0,0 +1,81 @@ +import sys +from _typeshed import StrOrLiteralStr +from collections.abc import Iterable, Mapping, Sequence +from re import Pattern, RegexFlag +from typing import Any, ClassVar, Final, overload +from typing_extensions import LiteralString + +__all__ = [ + "ascii_letters", + "ascii_lowercase", + "ascii_uppercase", + "capwords", + "digits", + "hexdigits", + "octdigits", + "printable", + "punctuation", + "whitespace", + "Formatter", + "Template", +] + +whitespace: Final = " \t\n\r\v\f" +ascii_lowercase: Final = "abcdefghijklmnopqrstuvwxyz" +ascii_uppercase: Final = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +ascii_letters: Final[LiteralString] # string too long +digits: Final = "0123456789" +hexdigits: Final = "0123456789abcdefABCDEF" +octdigits: Final = "01234567" +punctuation: Final = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" +printable: Final[LiteralString] # string too long + +def capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: ... + +class Template: + template: str + delimiter: ClassVar[str] + idpattern: ClassVar[str] + braceidpattern: ClassVar[str | None] + if sys.version_info >= (3, 14): + flags: ClassVar[RegexFlag | None] + else: + flags: ClassVar[RegexFlag] + pattern: ClassVar[Pattern[str]] + def __init__(self, template: str) -> None: ... + def substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... + def safe_substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ... + if sys.version_info >= (3, 11): + def get_identifiers(self) -> list[str]: ... + def is_valid(self) -> bool: ... + +class Formatter: + @overload + def format(self, format_string: LiteralString, /, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload + def format(self, format_string: str, /, *args: Any, **kwargs: Any) -> str: ... + + @overload + def vformat( + self, format_string: LiteralString, args: Sequence[LiteralString], kwargs: Mapping[LiteralString, LiteralString] + ) -> LiteralString: ... + @overload + def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... + + def _vformat( # undocumented + self, + format_string: str, + args: Sequence[Any], + kwargs: Mapping[str, Any], + used_args: set[int | str], + recursion_depth: int, + auto_arg_index: int = 0, + ) -> tuple[str, int]: ... + def parse( + self, format_string: StrOrLiteralStr + ) -> Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]: ... + def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... + def check_unused_args(self, used_args: set[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... + def format_field(self, value: Any, format_spec: str) -> Any: ... + def convert_field(self, value: Any, conversion: str | None) -> Any: ... diff --git a/stdlib/string/templatelib.pyi b/stdlib/string/templatelib.pyi new file mode 100644 index 000000000000..ee901cdc43b8 --- /dev/null +++ b/stdlib/string/templatelib.pyi @@ -0,0 +1,36 @@ +from collections.abc import Iterator +from types import GenericAlias +from typing import Any, Generic, Literal, TypeVar, final, overload + +_T = TypeVar("_T") + +@final +class Template: # TODO: consider making `Template` generic on `TypeVarTuple` + strings: tuple[str, ...] + interpolations: tuple[Interpolation[Any], ...] + + def __new__(cls, *args: str | Interpolation[Any]) -> Template: ... + def __iter__(self) -> Iterator[str | Interpolation[Any]]: ... + def __add__(self, other: Template, /) -> Template: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @property + def values(self) -> tuple[Any, ...]: ... # Tuple of interpolation values, which can have any type + +@final +class Interpolation(Generic[_T]): + value: _T + expression: str + conversion: Literal["a", "r", "s"] | None + format_spec: str + + __match_args__ = ("value", "expression", "conversion", "format_spec") + + def __new__( + cls, value: _T, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = "" + ) -> Interpolation[_T]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@overload +def convert(obj: _T, /, conversion: None) -> _T: ... +@overload +def convert(obj: object, /, conversion: Literal["r", "s", "a"]) -> str: ... diff --git a/stdlib/stringprep.pyi b/stdlib/stringprep.pyi new file mode 100644 index 000000000000..d67955e499c8 --- /dev/null +++ b/stdlib/stringprep.pyi @@ -0,0 +1,29 @@ +from typing import Final + +b1_set: Final[set[int]] +b3_exceptions: Final[dict[int, str]] +c22_specials: Final[set[int]] +c6_set: Final[set[int]] +c7_set: Final[set[int]] +c8_set: Final[set[int]] +c9_set: Final[set[int]] + +def in_table_a1(code: str) -> bool: ... +def in_table_b1(code: str) -> bool: ... +def map_table_b3(code: str) -> str: ... +def map_table_b2(a: str) -> str: ... +def in_table_c11(code: str) -> bool: ... +def in_table_c12(code: str) -> bool: ... +def in_table_c11_c12(code: str) -> bool: ... +def in_table_c21(code: str) -> bool: ... +def in_table_c22(code: str) -> bool: ... +def in_table_c21_c22(code: str) -> bool: ... +def in_table_c3(code: str) -> bool: ... +def in_table_c4(code: str) -> bool: ... +def in_table_c5(code: str) -> bool: ... +def in_table_c6(code: str) -> bool: ... +def in_table_c7(code: str) -> bool: ... +def in_table_c8(code: str) -> bool: ... +def in_table_c9(code: str) -> bool: ... +def in_table_d1(code: str) -> bool: ... +def in_table_d2(code: str) -> bool: ... diff --git a/stdlib/struct.pyi b/stdlib/struct.pyi new file mode 100644 index 000000000000..2c26908746ec --- /dev/null +++ b/stdlib/struct.pyi @@ -0,0 +1,5 @@ +from _struct import * + +__all__ = ["calcsize", "pack", "pack_into", "unpack", "unpack_from", "iter_unpack", "Struct", "error"] + +class error(Exception): ... diff --git a/stdlib/subprocess.pyi b/stdlib/subprocess.pyi new file mode 100644 index 000000000000..c191f0e35de9 --- /dev/null +++ b/stdlib/subprocess.pyi @@ -0,0 +1,1484 @@ +import sys +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +__all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", +] + +if sys.platform == "win32": + __all__ += [ + "CREATE_NEW_CONSOLE", + "CREATE_NEW_PROCESS_GROUP", + "STARTF_USESHOWWINDOW", + "STARTF_USESTDHANDLES", + "STARTUPINFO", + "STD_ERROR_HANDLE", + "STD_INPUT_HANDLE", + "STD_OUTPUT_HANDLE", + "SW_HIDE", + "ABOVE_NORMAL_PRIORITY_CLASS", + "BELOW_NORMAL_PRIORITY_CLASS", + "CREATE_BREAKAWAY_FROM_JOB", + "CREATE_DEFAULT_ERROR_MODE", + "CREATE_NO_WINDOW", + "DETACHED_PROCESS", + "HIGH_PRIORITY_CLASS", + "IDLE_PRIORITY_CLASS", + "NORMAL_PRIORITY_CLASS", + "REALTIME_PRIORITY_CLASS", + ] + +# We prefer to annotate inputs to methods (eg subprocess.check_call) with these +# union types. +# For outputs we use laborious literal based overloads to try to determine +# which specific return types to use, and prefer to fall back to Any when +# this does not work, so the caller does not have to use an assertion to confirm +# which type. +# +# For example: +# +# try: +# x = subprocess.check_output(["ls", "-l"]) +# reveal_type(x) # bytes, based on the overloads +# except TimeoutError as e: +# reveal_type(e.cmd) # Any, but morally is _CMD +_FILE: TypeAlias = None | int | IO[Any] +_InputString: TypeAlias = ReadableBuffer | str +_CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] +if sys.platform == "win32": + _ENV: TypeAlias = Mapping[str, str] +else: + _ENV: TypeAlias = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath] + +_T = TypeVar("_T") + +# These two are private but documented +if sys.version_info >= (3, 11): + _USE_VFORK: Final[bool] +_USE_POSIX_SPAWN: Final[bool] + +class CompletedProcess(Generic[_T]): + # morally: _CMD + args: Any + returncode: int + # These can both be None, but requiring checks for None would be tedious + # and writing all the overloads would be horrific. + stdout: _T + stderr: _T + def __init__(self, args: _CMD, returncode: int, stdout: _T | None = None, stderr: _T | None = None) -> None: ... + def check_returncode(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + @overload # text is True + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True], + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[str]: ... + @overload # encoding is str + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str, + errors: str | None = None, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[str]: ... + @overload # errors is str + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[str]: ... + @overload # universal_newlines is True + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the *real* keyword only args start + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[str]: ... + @overload # universal_newlines and text are False, None, or missing + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: None = None, + errors: None = None, + input: ReadableBuffer | None = None, + text: Literal[False] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[bytes]: ... + @overload # fallback + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: _InputString | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> CompletedProcess[Any]: ... +else: + # 3.10 adds "pipesize" argument + @overload # text is True + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True], + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[str]: ... + @overload # encoding is str + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str, + errors: str | None = None, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[str]: ... + @overload # errors is str + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str, + input: str | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[str]: ... + @overload # universal_newlines is True + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the *real* keyword only args start + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: str | None = None, + text: Literal[True] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[str]: ... + @overload # universal_newlines and text are False, None, or missing + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: None = None, + errors: None = None, + input: ReadableBuffer | None = None, + text: Literal[False] | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[bytes]: ... + @overload # fallback + def run( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + capture_output: bool = False, + check: bool = False, + encoding: str | None = None, + errors: str | None = None, + input: _InputString | None = None, + text: bool | None = None, + timeout: float | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> CompletedProcess[Any]: ... + +# Same args as Popen.__init__ +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + encoding: str | None = None, + timeout: float | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> int: ... + +else: + # 3.10 adds "pipesize" argument + def call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + encoding: str | None = None, + timeout: float | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> int: ... + +# Same args as Popen.__init__ +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def check_call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + timeout: float | None = None, + *, + encoding: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> int: ... + +else: + # 3.10 adds "pipesize" argument + def check_call( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stdout: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + timeout: float | None = None, + *, + encoding: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> int: ... + +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + @overload # text is True + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True], + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> str: ... + @overload # encoding is str + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> str: ... + @overload # errors is str + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> str: ... + @overload # universal_newlines is True + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the real keyword only ones start + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> str: ... + @overload # universal_newlines and text are False, None, or missing + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> bytes: ... + @overload # fallback + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> Any: ... # morally: -> str | bytes +else: + # 3.10 adds "pipesize" argument + @overload # text is True + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True], + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> str: ... + @overload # encoding is str + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> str: ... + @overload # errors is str + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> str: ... + @overload # universal_newlines is True + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the real keyword only ones start + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: Literal[True] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> str: ... + @overload # universal_newlines and text are False, None, or missing + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: None = None, + errors: None = None, + text: Literal[False] | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> bytes: ... + @overload # fallback + def check_output( + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE = None, + stderr: _FILE = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + timeout: float | None = None, + input: _InputString | None = None, + encoding: str | None = None, + errors: str | None = None, + text: bool | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> Any: ... # morally: -> str | bytes + +PIPE: Final[int] +STDOUT: Final[int] +DEVNULL: Final[int] + +class SubprocessError(Exception): ... + +class TimeoutExpired(SubprocessError): + def __init__( + self, cmd: _CMD, timeout: float, output: str | bytes | None = None, stderr: str | bytes | None = None + ) -> None: ... + # morally: _CMD + cmd: Any + timeout: float + # morally: str | bytes | None + output: Any + stdout: bytes | None + stderr: bytes | None + +class CalledProcessError(SubprocessError): + returncode: int + # morally: _CMD + cmd: Any + # morally: str | bytes | None + output: Any + + # morally: str | bytes | None + stdout: Any + stderr: Any + def __init__( + self, returncode: int, cmd: _CMD, output: str | bytes | None = None, stderr: str | bytes | None = None + ) -> None: ... + +class Popen(Generic[AnyStr]): + args: _CMD + stdin: IO[Any] | None + stdout: IO[Any] | None + stderr: IO[Any] | None + pid: int + returncode: int | MaybeNone + universal_newlines: bool + + if sys.version_info >= (3, 11): + # process_group is added in 3.11 + @overload # encoding is str + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # errors is str + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # universal_newlines is True + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the *real* keyword only args start + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # text is True + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: Literal[True], + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # universal_newlines and text are False, None, or missing + def __init__( + self: Popen[bytes], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: Literal[False] | None = None, + encoding: None = None, + errors: None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + @overload # fallback + def __init__( + self: Popen[Any], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + else: + # pipesize is added in 3.10 + @overload # encoding is str + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # errors is str + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # universal_newlines is True + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + *, + universal_newlines: Literal[True], + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + # where the *real* keyword only args start + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # text is True + def __init__( + self: Popen[str], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[True] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: Literal[True], + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # universal_newlines and text are False, None, or missing + def __init__( + self: Popen[bytes], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: Literal[False] | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: Literal[False] | None = None, + encoding: None = None, + errors: None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + @overload # fallback + def __init__( + self: Popen[Any], + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + + def poll(self) -> int | None: ... + def wait(self, timeout: float | None = None) -> int: ... + # morally the members of the returned tuple should be optional + # TODO: this should allow ReadableBuffer for Popen[bytes], but adding + # overloads for that runs into a mypy bug (python/mypy#14070). + def communicate(self, input: AnyStr | None = None, timeout: float | None = None) -> tuple[AnyStr, AnyStr]: ... + def send_signal(self, sig: int) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# The result really is always a str. +if sys.version_info >= (3, 11): + def getstatusoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: ... + def getoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> str: ... + +else: + def getstatusoutput(cmd: _CMD) -> tuple[int, str]: ... + def getoutput(cmd: _CMD) -> str: ... + +def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented + +if sys.platform == "win32": + if sys.version_info >= (3, 13): + from _winapi import STARTF_FORCEOFFFEEDBACK, STARTF_FORCEONFEEDBACK + + __all__ += ["STARTF_FORCEOFFFEEDBACK", "STARTF_FORCEONFEEDBACK"] + + class STARTUPINFO: + def __init__( + self, + *, + dwFlags: int = 0, + hStdInput: Any | None = None, + hStdOutput: Any | None = None, + hStdError: Any | None = None, + wShowWindow: int = 0, + lpAttributeList: Mapping[str, Any] | None = None, + ) -> None: ... + dwFlags: int + hStdInput: Any | None + hStdOutput: Any | None + hStdError: Any | None + wShowWindow: int + lpAttributeList: Mapping[str, Any] + def copy(self) -> STARTUPINFO: ... + + from _winapi import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + CREATE_BREAKAWAY_FROM_JOB as CREATE_BREAKAWAY_FROM_JOB, + CREATE_DEFAULT_ERROR_MODE as CREATE_DEFAULT_ERROR_MODE, + CREATE_NEW_CONSOLE as CREATE_NEW_CONSOLE, + CREATE_NEW_PROCESS_GROUP as CREATE_NEW_PROCESS_GROUP, + CREATE_NO_WINDOW as CREATE_NO_WINDOW, + DETACHED_PROCESS as DETACHED_PROCESS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + STARTF_USESHOWWINDOW as STARTF_USESHOWWINDOW, + STARTF_USESTDHANDLES as STARTF_USESTDHANDLES, + STD_ERROR_HANDLE as STD_ERROR_HANDLE, + STD_INPUT_HANDLE as STD_INPUT_HANDLE, + STD_OUTPUT_HANDLE as STD_OUTPUT_HANDLE, + SW_HIDE as SW_HIDE, + ) diff --git a/stdlib/sunau.pyi b/stdlib/sunau.pyi new file mode 100644 index 000000000000..e4b9fcb6b8ca --- /dev/null +++ b/stdlib/sunau.pyi @@ -0,0 +1,82 @@ +from _typeshed import Unused +from typing import IO, Any, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self + +_File: TypeAlias = str | IO[bytes] + +class Error(Exception): ... + +AUDIO_FILE_MAGIC: Final = 0x2E736E64 +AUDIO_FILE_ENCODING_MULAW_8: Final = 1 +AUDIO_FILE_ENCODING_LINEAR_8: Final = 2 +AUDIO_FILE_ENCODING_LINEAR_16: Final = 3 +AUDIO_FILE_ENCODING_LINEAR_24: Final = 4 +AUDIO_FILE_ENCODING_LINEAR_32: Final = 5 +AUDIO_FILE_ENCODING_FLOAT: Final = 6 +AUDIO_FILE_ENCODING_DOUBLE: Final = 7 +AUDIO_FILE_ENCODING_ADPCM_G721: Final = 23 +AUDIO_FILE_ENCODING_ADPCM_G722: Final = 24 +AUDIO_FILE_ENCODING_ADPCM_G723_3: Final = 25 +AUDIO_FILE_ENCODING_ADPCM_G723_5: Final = 26 +AUDIO_FILE_ENCODING_ALAW_8: Final = 27 +AUDIO_UNKNOWN_SIZE: Final = 0xFFFFFFFF + +class _sunau_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: str + compname: str + +class Au_read: + def __init__(self, f: _File) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... + def getfp(self) -> IO[bytes] | None: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _sunau_params: ... + def getmarkers(self) -> None: ... + def getmark(self, id: Any) -> Never: ... + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes | None: ... + +class Au_write: + def __init__(self, f: _File) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, type: str, name: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def setparams(self, params: _sunau_params) -> None: ... + def getparams(self) -> _sunau_params: ... + def tell(self) -> int: ... + # should be any bytes-like object after 3.4, but we don't have a type for that + def writeframesraw(self, data: bytes) -> None: ... + def writeframes(self, data: bytes) -> None: ... + def close(self) -> None: ... + +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Au_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Au_write: ... +@overload +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/symtable.pyi b/stdlib/symtable.pyi new file mode 100644 index 000000000000..3c6a828fad2a --- /dev/null +++ b/stdlib/symtable.pyi @@ -0,0 +1,95 @@ +import sys +from _collections_abc import dict_keys +from collections.abc import Sequence +from typing import Any +from typing_extensions import deprecated + +__all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"] + +if sys.version_info >= (3, 13): + __all__ += ["SymbolTableType"] + +if sys.version_info >= (3, 15): + def symtable(code: str, filename: str, compile_type: str, *, module: str | None = None) -> SymbolTable: ... + +else: + def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... + +if sys.version_info >= (3, 13): + from enum import StrEnum + + class SymbolTableType(StrEnum): + MODULE = "module" + FUNCTION = "function" + CLASS = "class" + ANNOTATION = "annotation" + TYPE_ALIAS = "type alias" + TYPE_PARAMETERS = "type parameters" + TYPE_VARIABLE = "type variable" + +class SymbolTable: + def __init__(self, raw_table: Any, filename: str) -> None: ... + if sys.version_info >= (3, 13): + def get_type(self) -> SymbolTableType: ... + else: + def get_type(self) -> str: ... + + def get_id(self) -> int: ... + def get_name(self) -> str: ... + def get_lineno(self) -> int: ... + def is_optimized(self) -> bool: ... + def is_nested(self) -> bool: ... + def has_children(self) -> bool: ... + def get_identifiers(self) -> dict_keys[str, int]: ... + def lookup(self, name: str) -> Symbol: ... + def get_symbols(self) -> list[Symbol]: ... + def get_children(self) -> list[SymbolTable]: ... + +class Function(SymbolTable): + def get_parameters(self) -> tuple[str, ...]: ... + def get_locals(self) -> tuple[str, ...]: ... + def get_globals(self) -> tuple[str, ...]: ... + def get_frees(self) -> tuple[str, ...]: ... + if sys.version_info >= (3, 15): + def get_cells(self) -> tuple[str, ...]: ... + + def get_nonlocals(self) -> tuple[str, ...]: ... + +class Class(SymbolTable): + @deprecated("Deprecated; will be removed in Python 3.16.") + def get_methods(self) -> tuple[str, ...]: ... + +class Symbol: + def __init__( + self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False + ) -> None: ... + def is_nonlocal(self) -> bool: ... + def get_name(self) -> str: ... + def is_referenced(self) -> bool: ... + def is_parameter(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_type_parameter(self) -> bool: ... + + def is_global(self) -> bool: ... + def is_declared_global(self) -> bool: ... + def is_local(self) -> bool: ... + def is_annotated(self) -> bool: ... + def is_free(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_free_class(self) -> bool: ... + + def is_imported(self) -> bool: ... + def is_assigned(self) -> bool: ... + if sys.version_info >= (3, 14): + def is_comp_iter(self) -> bool: ... + def is_comp_cell(self) -> bool: ... + if sys.version_info >= (3, 15): + def is_cell(self) -> bool: ... + + def is_namespace(self) -> bool: ... + def get_namespaces(self) -> Sequence[SymbolTable]: ... + def get_namespace(self) -> SymbolTable: ... + +class SymbolTableFactory: + def new(self, table: Any, filename: str) -> SymbolTable: ... + def __call__(self, table: Any, filename: str) -> SymbolTable: ... diff --git a/stdlib/sys/__init__.pyi b/stdlib/sys/__init__.pyi new file mode 100644 index 000000000000..11c78b73af5b --- /dev/null +++ b/stdlib/sys/__init__.pyi @@ -0,0 +1,537 @@ +import sys +from _typeshed import MaybeNone, OptExcInfo, ProfileFunction, StrOrBytesPath, TraceFunction, structseq +from _typeshed.importlib import MetaPathFinderProtocol, PathEntryFinderProtocol +from builtins import object as _object +from collections.abc import AsyncGenerator, Callable, Sequence +from io import TextIOWrapper +from types import FrameType, ModuleType, SimpleNamespace, TracebackType +from typing import Any, Final, Literal, Protocol, TextIO, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import LiteralString, Never, deprecated + +_T = TypeVar("_T") +_LazyImportMode: TypeAlias = Literal["normal", "all", "none"] +_LazyImportFilter: TypeAlias = Callable[[str | None, str, tuple[str, ...] | None], bool] + +# see https://github.com/python/typeshed/issues/8513#issue-1333671093 for the rationale behind this alias +_ExitCode: TypeAlias = str | int | None + +if sys.version_info >= (3, 15): + @type_check_only + class _AbiInfo(SimpleNamespace): + pointer_bits: int + free_threaded: bool + debug: bool + byteorder: Literal["little", "big"] + +# ----- sys variables ----- +if sys.platform != "win32": + abiflags: str +if sys.version_info >= (3, 15): + abi_info: _AbiInfo +argv: list[str] +base_exec_prefix: str +base_prefix: str +byteorder: Literal["little", "big"] +builtin_module_names: Sequence[str] # actually a tuple of strings +copyright: str +if sys.platform == "win32": + dllhandle: int +dont_write_bytecode: bool +displayhook: Callable[[object], Any] +excepthook: Callable[[type[BaseException], BaseException, TracebackType | None], Any] +exec_prefix: str +executable: str +float_repr_style: Literal["short", "legacy"] +hexversion: int +last_type: type[BaseException] | None +last_value: BaseException | None +last_traceback: TracebackType | None +if sys.version_info >= (3, 12): + last_exc: BaseException # or undefined. +maxsize: int +maxunicode: int +meta_path: list[MetaPathFinderProtocol] +modules: dict[str, ModuleType] +if sys.version_info >= (3, 15): + lazy_modules: set[str] +orig_argv: list[str] +path: list[str] +path_hooks: list[Callable[[str], PathEntryFinderProtocol]] +path_importer_cache: dict[str, PathEntryFinderProtocol | None] +platform: LiteralString +platlibdir: str +prefix: str +pycache_prefix: str | None +ps1: object +ps2: object + +# TextIO is used instead of more specific types for the standard streams, +# since they are often monkeypatched at runtime. At startup, the objects +# are initialized to instances of TextIOWrapper, but can also be None under +# some circumstances. +# +# To use methods from TextIOWrapper, use an isinstance check to ensure that +# the streams have not been overridden: +# +# if isinstance(sys.stdout, io.TextIOWrapper): +# sys.stdout.reconfigure(...) +stdin: TextIO | MaybeNone +stdout: TextIO | MaybeNone +stderr: TextIO | MaybeNone +stdlib_module_names: frozenset[str] + +__stdin__: Final[TextIOWrapper | None] # Contains the original value of stdin +__stdout__: Final[TextIOWrapper | None] # Contains the original value of stdout +__stderr__: Final[TextIOWrapper | None] # Contains the original value of stderr +tracebacklimit: int | None +version: str +api_version: int +warnoptions: Any +# Each entry is a tuple of the form (action, message, category, module, +# lineno) +if sys.platform == "win32": + winver: str +_xoptions: dict[Any, Any] + +# Type alias used as a mixin for structseq classes that cannot be instantiated at runtime +# This can't be represented in the type system, so we just use `structseq[Any]` +_UninstantiableStructseq: TypeAlias = structseq[Any] + +flags: _flags + +# This class is not exposed at runtime. It calls itself sys.flags. +# As a tuple, it can have a length between 15 and 18. We don't model +# the exact length here because that varies by patch version due to +# the backported security fix int_max_str_digits. The exact length shouldn't +# be relied upon. See #13031 +# This can be re-visited when typeshed drops support for 3.10, +# at which point all supported versions will include int_max_str_digits +# in all patch versions. +# 3.9 is 15 or 16-tuple +# 3.10 is 16 or 17-tuple +# 3.11+ is an 18-tuple. +@final +@type_check_only +class _flags(_UninstantiableStructseq, tuple[int, ...]): + # `safe_path` was added in py311 + if sys.version_info >= (3, 11): + __match_args__: Final = ( + "debug", + "inspect", + "interactive", + "optimize", + "dont_write_bytecode", + "no_user_site", + "no_site", + "ignore_environment", + "verbose", + "bytes_warning", + "quiet", + "hash_randomization", + "isolated", + "dev_mode", + "utf8_mode", + "warn_default_encoding", + "safe_path", + "int_max_str_digits", + ) + else: + __match_args__: Final = ( + "debug", + "inspect", + "interactive", + "optimize", + "dont_write_bytecode", + "no_user_site", + "no_site", + "ignore_environment", + "verbose", + "bytes_warning", + "quiet", + "hash_randomization", + "isolated", + "dev_mode", + "utf8_mode", + "warn_default_encoding", + "int_max_str_digits", + ) + + @property + def debug(self) -> int: ... + @property + def inspect(self) -> int: ... + @property + def interactive(self) -> int: ... + @property + def optimize(self) -> int: ... + @property + def dont_write_bytecode(self) -> int: ... + @property + def no_user_site(self) -> int: ... + @property + def no_site(self) -> int: ... + @property + def ignore_environment(self) -> int: ... + @property + def verbose(self) -> int: ... + @property + def bytes_warning(self) -> int: ... + @property + def quiet(self) -> int: ... + @property + def hash_randomization(self) -> int: ... + @property + def isolated(self) -> int: ... + @property + def dev_mode(self) -> bool: ... + @property + def utf8_mode(self) -> int: ... + @property + def warn_default_encoding(self) -> int: ... + if sys.version_info >= (3, 11): + @property + def safe_path(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def gil(self) -> Literal[0, 1]: ... + if sys.version_info >= (3, 14): + @property + def thread_inherit_context(self) -> Literal[0, 1]: ... + @property + def context_aware_warnings(self) -> Literal[0, 1]: ... + # Whether or not this exists on lower versions of Python + # may depend on which patch release you're using + # (it was backported to all Python versions on 3.8+ as a security fix) + # Added in: 3.9.14, 3.10.7 + # and present in all versions of 3.11 and later. + @property + def int_max_str_digits(self) -> int: ... + +float_info: _float_info + +# This class is not exposed at runtime. It calls itself sys.float_info. +@final +@type_check_only +class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): + __match_args__: Final = ( + "max", + "max_exp", + "max_10_exp", + "min", + "min_exp", + "min_10_exp", + "dig", + "mant_dig", + "epsilon", + "radix", + "rounds", + ) + + @property + def max(self) -> float: ... # DBL_MAX + @property + def max_exp(self) -> int: ... # DBL_MAX_EXP + @property + def max_10_exp(self) -> int: ... # DBL_MAX_10_EXP + @property + def min(self) -> float: ... # DBL_MIN + @property + def min_exp(self) -> int: ... # DBL_MIN_EXP + @property + def min_10_exp(self) -> int: ... # DBL_MIN_10_EXP + @property + def dig(self) -> int: ... # DBL_DIG + @property + def mant_dig(self) -> int: ... # DBL_MANT_DIG + @property + def epsilon(self) -> float: ... # DBL_EPSILON + @property + def radix(self) -> int: ... # FLT_RADIX + @property + def rounds(self) -> int: ... # FLT_ROUNDS + +hash_info: _hash_info + +# This class is not exposed at runtime. It calls itself sys.hash_info. +@final +@type_check_only +class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): + __match_args__: Final = ("width", "modulus", "inf", "nan", "imag", "algorithm", "hash_bits", "seed_bits", "cutoff") + + @property + def width(self) -> int: ... + @property + def modulus(self) -> int: ... + @property + def inf(self) -> int: ... + @property + def nan(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def algorithm(self) -> str: ... + @property + def hash_bits(self) -> int: ... + @property + def seed_bits(self) -> int: ... + @property + def cutoff(self) -> int: ... # undocumented + +implementation: _implementation + +# This class isn't really a thing. At runtime, implementation is an instance +# of types.SimpleNamespace. This allows for better typing. +@type_check_only +class _implementation: + name: str + version: _version_info + hexversion: int + cache_tag: str + # Define __getattr__, as the documentation states: + # > sys.implementation may contain additional attributes specific to the Python implementation. + # > These non-standard attributes must start with an underscore, and are not described here. + def __getattr__(self, name: str) -> Any: ... + +int_info: _int_info + +# This class is not exposed at runtime. It calls itself sys.int_info. +@final +@type_check_only +class _int_info(structseq[int], tuple[int, int, int, int]): + __match_args__: Final = ("bits_per_digit", "sizeof_digit", "default_max_str_digits", "str_digits_check_threshold") + + @property + def bits_per_digit(self) -> int: ... + @property + def sizeof_digit(self) -> int: ... + @property + def default_max_str_digits(self) -> int: ... + @property + def str_digits_check_threshold(self) -> int: ... + +_ThreadInfoName: TypeAlias = Literal["nt", "pthread", "pthread-stubs", "solaris"] +_ThreadInfoLock: TypeAlias = Literal["semaphore", "mutex+cond"] | None + +# This class is not exposed at runtime. It calls itself sys.thread_info. +@final +@type_check_only +class _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoLock, str | None]): + __match_args__: Final = ("name", "lock", "version") + + @property + def name(self) -> _ThreadInfoName: ... + @property + def lock(self) -> _ThreadInfoLock: ... + @property + def version(self) -> str | None: ... + +thread_info: _thread_info +_ReleaseLevel: TypeAlias = Literal["alpha", "beta", "candidate", "final"] + +# This class is not exposed at runtime. It calls itself sys.version_info. +@final +@type_check_only +class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel, int]): + __match_args__: Final = ("major", "minor", "micro", "releaselevel", "serial") + + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> _ReleaseLevel: ... + @property + def serial(self) -> int: ... + +version_info: _version_info + +def call_tracing(func: Callable[..., _T], args: Any, /) -> _T: ... + +if sys.version_info >= (3, 13): + @deprecated("Deprecated since Python 3.13. Use `_clear_internal_caches()` instead.") + def _clear_type_cache() -> None: ... + +else: + def _clear_type_cache() -> None: ... + +def _current_frames() -> dict[int, FrameType]: ... +def _getframe(depth: int = 0, /) -> FrameType: ... + +# documented -- see https://docs.python.org/3/library/sys.html#sys._current_exceptions +if sys.version_info >= (3, 12): + def _current_exceptions() -> dict[int, BaseException | None]: ... + +else: + def _current_exceptions() -> dict[int, OptExcInfo]: ... + +if sys.version_info >= (3, 12): + def _getframemodulename(depth: int = 0) -> str | None: ... + +def _debugmallocstats() -> None: ... +def __displayhook__(object: object, /) -> None: ... +def __excepthook__(exctype: type[BaseException], value: BaseException, traceback: TracebackType | None, /) -> None: ... +def exc_info() -> OptExcInfo: ... + +if sys.version_info >= (3, 11): + def exception() -> BaseException | None: ... + +def exit(status: _ExitCode = None, /) -> Never: ... + +if sys.platform == "android": # noqa: Y008 + def getandroidapilevel() -> int: ... + +def getallocatedblocks() -> int: ... +def getdefaultencoding() -> Literal["utf-8"]: ... + +if sys.platform != "win32": + def getdlopenflags() -> int: ... + +def getfilesystemencoding() -> LiteralString: ... +def getfilesystemencodeerrors() -> LiteralString: ... + +if sys.version_info >= (3, 15): + def get_lazy_imports() -> _LazyImportMode: ... + def get_lazy_imports_filter() -> _LazyImportFilter | None: ... + +def getrefcount(object: Any, /) -> int: ... +def getrecursionlimit() -> int: ... +def getsizeof(obj: object, default: int = ...) -> int: ... +def getswitchinterval() -> float: ... +def getprofile() -> ProfileFunction | None: ... +def setprofile(function: ProfileFunction | None, /) -> None: ... +def gettrace() -> TraceFunction | None: ... +def settrace(function: TraceFunction | None, /) -> None: ... + +if sys.platform == "win32": + # A tuple of length 5, even though it has more than 5 attributes. + @final + @type_check_only + class _WinVersion(_UninstantiableStructseq, tuple[int, int, int, int, str]): + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def build(self) -> int: ... + @property + def platform(self) -> int: ... + @property + def service_pack(self) -> str: ... + @property + def service_pack_minor(self) -> int: ... + @property + def service_pack_major(self) -> int: ... + @property + def suite_mask(self) -> int: ... + @property + def product_type(self) -> int: ... + @property + def platform_version(self) -> tuple[int, int, int]: ... + + def getwindowsversion() -> _WinVersion: ... + +@overload +def intern(string: LiteralString, /) -> LiteralString: ... +@overload +def intern(string: str, /) -> str: ... # type: ignore[misc] + +__interactivehook__: Callable[[], object] + +if sys.version_info >= (3, 13): + def _is_gil_enabled() -> bool: ... + def _clear_internal_caches() -> None: ... + def _is_interned(string: str, /) -> bool: ... + +def is_finalizing() -> bool: ... +def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... + +__breakpointhook__ = breakpointhook # Contains the original value of breakpointhook + +if sys.platform != "win32": + def setdlopenflags(flags: int, /) -> None: ... + +def setrecursionlimit(limit: int, /) -> None: ... +def setswitchinterval(interval: float, /) -> None: ... +def gettotalrefcount() -> int: ... # Debug builds only + +# Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. +@type_check_only +class UnraisableHookArgs(Protocol): + exc_type: type[BaseException] + exc_value: BaseException | None + exc_traceback: TracebackType | None + err_msg: str | None + object: _object + +unraisablehook: Callable[[UnraisableHookArgs], Any] + +def __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: ... +def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... +def audit(event: str, /, *args: Any) -> None: ... + +_AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None + +# This class is not exposed at runtime. It calls itself builtins.asyncgen_hooks. +@final +@type_check_only +class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): + __match_args__: Final = ("firstiter", "finalizer") + + @property + def firstiter(self) -> _AsyncgenHook: ... + @property + def finalizer(self) -> _AsyncgenHook: ... + +def get_asyncgen_hooks() -> _asyncgen_hooks: ... +def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... + +if sys.platform == "win32": + if sys.version_info >= (3, 13): + @deprecated( + "Deprecated since Python 3.13; will be removed in Python 3.16. " + "Use the `PYTHONLEGACYWINDOWSFSENCODING` environment variable instead." + ) + def _enablelegacywindowsfsencoding() -> None: ... + else: + def _enablelegacywindowsfsencoding() -> None: ... + +def get_coroutine_origin_tracking_depth() -> int: ... +def set_coroutine_origin_tracking_depth(depth: int) -> None: ... + +# The following two functions were added in 3.11.0, 3.10.7, and 3.9.14, +# as part of the response to CVE-2020-10735 +def set_int_max_str_digits(maxdigits: int) -> None: ... +def get_int_max_str_digits() -> int: ... + +if sys.version_info >= (3, 15): + def set_lazy_imports(mode: _LazyImportMode) -> None: ... + def set_lazy_imports_filter(filter: _LazyImportFilter | None) -> None: ... + +if sys.version_info >= (3, 12): + if sys.version_info >= (3, 13): + def getunicodeinternedsize(*, _only_immortal: bool = False) -> int: ... + else: + def getunicodeinternedsize() -> int: ... + + def deactivate_stack_trampoline() -> None: ... + def is_stack_trampoline_active() -> bool: ... + # It always exists, but raises on non-linux platforms: + if sys.platform == "linux": + def activate_stack_trampoline(backend: str, /) -> None: ... + else: + def activate_stack_trampoline(backend: str, /) -> Never: ... + + from . import _monitoring + + monitoring = _monitoring + +if sys.version_info >= (3, 14): + def is_remote_debug_enabled() -> bool: ... + def remote_exec(pid: int, script: StrOrBytesPath) -> None: ... + def _is_immortal(op: object, /) -> bool: ... + + from . import __jit + + _jit = __jit diff --git a/stdlib/sys/__jit.pyi b/stdlib/sys/__jit.pyi new file mode 100644 index 000000000000..90fb65c1d9ef --- /dev/null +++ b/stdlib/sys/__jit.pyi @@ -0,0 +1,11 @@ +# This py314+ module provides annotations for `sys._jit`. +# It's named `sys.__jit` in typeshed, +# because trying to import `sys._jit` will fail at runtime! +# At runtime, `sys._jit` has the unusual status +# of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys.monitoring) +# and exists in the `sys`-module namespace despite `sys` not being a package. + +def is_available() -> bool: ... +def is_enabled() -> bool: ... +def is_active() -> bool: ... diff --git a/stdlib/sys/_monitoring.pyi b/stdlib/sys/_monitoring.pyi new file mode 100644 index 000000000000..b999d63f6470 --- /dev/null +++ b/stdlib/sys/_monitoring.pyi @@ -0,0 +1,69 @@ +# This py312+ module provides annotations for `sys.monitoring`. +# It's named `sys._monitoring` in typeshed, +# because trying to import `sys.monitoring` will fail at runtime! +# At runtime, `sys.monitoring` has the unusual status +# of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys._jit) +# and exists in the `sys`-module namespace despite `sys` not being a package. + +import sys +from collections.abc import Callable +from types import CodeType +from typing import Any, Final, type_check_only +from typing_extensions import deprecated + +DEBUGGER_ID: Final = 0 +COVERAGE_ID: Final = 1 +PROFILER_ID: Final = 2 +OPTIMIZER_ID: Final = 5 + +def use_tool_id(tool_id: int, name: str, /) -> None: ... + +if sys.version_info >= (3, 14): + def clear_tool_id(tool_id: int, /) -> None: ... + +def free_tool_id(tool_id: int, /) -> None: ... +def get_tool(tool_id: int, /) -> str | None: ... + +events: Final[_events] + +@type_check_only +class _events: + CALL: Final[int] + C_RAISE: Final[int] + C_RETURN: Final[int] + EXCEPTION_HANDLED: Final[int] + INSTRUCTION: Final[int] + JUMP: Final[int] + LINE: Final[int] + NO_EVENTS: Final[int] + PY_RESUME: Final[int] + PY_RETURN: Final[int] + PY_START: Final[int] + PY_THROW: Final[int] + PY_UNWIND: Final[int] + PY_YIELD: Final[int] + RAISE: Final[int] + RERAISE: Final[int] + STOP_ITERATION: Final[int] + if sys.version_info >= (3, 14): + BRANCH_LEFT: Final[int] + BRANCH_RIGHT: Final[int] + + @property + @deprecated("Deprecated since Python 3.14. Use `BRANCH_LEFT` or `BRANCH_RIGHT` instead.") + def BRANCH(self) -> int: ... + + else: + BRANCH: Final[int] + +def get_events(tool_id: int, /) -> int: ... +def set_events(tool_id: int, event_set: int, /) -> None: ... +def get_local_events(tool_id: int, code: CodeType, /) -> int: ... +def set_local_events(tool_id: int, code: CodeType, event_set: int, /) -> None: ... +def restart_events() -> None: ... + +DISABLE: Final[object] +MISSING: Final[object] + +def register_callback(tool_id: int, event: int, func: Callable[..., object] | None, /) -> Callable[..., Any] | None: ... diff --git a/stdlib/sysconfig.pyi b/stdlib/sysconfig.pyi new file mode 100644 index 000000000000..bd20113e9df5 --- /dev/null +++ b/stdlib/sysconfig.pyi @@ -0,0 +1,59 @@ +import sys +from typing import IO, Any, Literal, overload +from typing_extensions import LiteralString, deprecated + +__all__ = [ + "get_config_h_filename", + "get_config_var", + "get_config_vars", + "get_makefile_filename", + "get_path", + "get_path_names", + "get_paths", + "get_platform", + "get_python_version", + "get_scheme_names", + "parse_config_h", +] + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") +def get_config_var(name: Literal["SO"]) -> Any: ... +@overload +def get_config_var(name: str) -> Any: ... + +@overload +def get_config_vars() -> dict[str, Any]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[Any]: ... + +def get_scheme_names() -> tuple[str, ...]: ... +def get_default_scheme() -> LiteralString: ... +def get_preferred_scheme(key: Literal["prefix", "home", "user"]) -> LiteralString: ... + +# Documented -- see https://docs.python.org/3/library/sysconfig.html#sysconfig._get_preferred_schemes +def _get_preferred_schemes() -> dict[Literal["prefix", "home", "user"], LiteralString]: ... +def get_path_names() -> tuple[str, ...]: ... +def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> str: ... +def get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> dict[str, str]: ... +def get_python_version() -> str: ... +def get_platform() -> str: ... + +if sys.version_info >= (3, 15): + def is_python_build() -> bool: ... +elif sys.version_info >= (3, 11): + @overload + def is_python_build() -> bool: ... + @overload + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") + def is_python_build(check_home: object = None) -> bool: ... +else: + @overload + def is_python_build() -> bool: ... + @overload + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") + def is_python_build(check_home: bool = False) -> bool: ... + +def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, Any]: ... +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... diff --git a/stdlib/syslog.pyi b/stdlib/syslog.pyi new file mode 100644 index 000000000000..0cb97dcd3ca7 --- /dev/null +++ b/stdlib/syslog.pyi @@ -0,0 +1,58 @@ +import sys +from typing import Final, overload + +if sys.platform != "win32": + LOG_ALERT: Final = 1 + LOG_AUTH: Final = 32 + LOG_AUTHPRIV: Final = 80 + LOG_CONS: Final = 2 + LOG_CRIT: Final = 2 + LOG_CRON: Final = 72 + LOG_DAEMON: Final = 24 + LOG_DEBUG: Final = 7 + LOG_EMERG: Final = 0 + LOG_ERR: Final = 3 + LOG_INFO: Final = 6 + LOG_KERN: Final = 0 + LOG_LOCAL0: Final = 128 + LOG_LOCAL1: Final = 136 + LOG_LOCAL2: Final = 144 + LOG_LOCAL3: Final = 152 + LOG_LOCAL4: Final = 160 + LOG_LOCAL5: Final = 168 + LOG_LOCAL6: Final = 176 + LOG_LOCAL7: Final = 184 + LOG_LPR: Final = 48 + LOG_MAIL: Final = 16 + LOG_NDELAY: Final = 8 + LOG_NEWS: Final = 56 + LOG_NOTICE: Final = 5 + LOG_NOWAIT: Final = 16 + LOG_ODELAY: Final = 4 + LOG_PERROR: Final = 32 + LOG_PID: Final = 1 + LOG_SYSLOG: Final = 40 + LOG_USER: Final = 8 + LOG_UUCP: Final = 64 + LOG_WARNING: Final = 4 + + if sys.version_info >= (3, 13): + LOG_FTP: Final = 88 + + if sys.platform == "darwin": + LOG_INSTALL: Final = 112 + LOG_LAUNCHD: Final = 192 + LOG_NETINFO: Final = 96 + LOG_RAS: Final = 120 + LOG_REMOTEAUTH: Final = 104 + + def LOG_MASK(pri: int, /) -> int: ... + def LOG_UPTO(pri: int, /) -> int: ... + def closelog() -> None: ... + def openlog(ident: str = ..., logoption: int = 0, facility: int = ...) -> None: ... + def setlogmask(maskpri: int, /) -> int: ... + + @overload + def syslog(priority: int, message: str) -> None: ... + @overload + def syslog(message: str) -> None: ... diff --git a/stdlib/tabnanny.pyi b/stdlib/tabnanny.pyi new file mode 100644 index 000000000000..8a8592f44124 --- /dev/null +++ b/stdlib/tabnanny.pyi @@ -0,0 +1,16 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Iterable + +__all__ = ["check", "NannyNag", "process_tokens"] + +verbose: int +filename_only: int + +class NannyNag(Exception): + def __init__(self, lineno: int, msg: str, line: str) -> None: ... + def get_lineno(self) -> int: ... + def get_msg(self) -> str: ... + def get_line(self) -> str: ... + +def check(file: StrOrBytesPath) -> None: ... +def process_tokens(tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]]) -> None: ... diff --git a/stdlib/tarfile.pyi b/stdlib/tarfile.pyi new file mode 100644 index 000000000000..7cfa098bb4f8 --- /dev/null +++ b/stdlib/tarfile.pyi @@ -0,0 +1,864 @@ +import bz2 +import io +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, WriteableBuffer +from builtins import list as _list # aliases to avoid name clashes with fields named "type" or "list" +from collections.abc import Callable, Iterable, Iterator, Mapping +from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj +from types import TracebackType +from typing import IO, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +if sys.version_info >= (3, 14): + from compression.zstd import ZstdDict + +__all__ = [ + "TarFile", + "TarInfo", + "is_tarfile", + "TarError", + "ReadError", + "CompressionError", + "StreamError", + "ExtractError", + "HeaderError", + "ENCODING", + "USTAR_FORMAT", + "GNU_FORMAT", + "PAX_FORMAT", + "DEFAULT_FORMAT", + "open", +] +if sys.version_info >= (3, 12): + __all__ += [ + "fully_trusted_filter", + "data_filter", + "tar_filter", + "FilterError", + "AbsoluteLinkError", + "OutsideDestinationError", + "SpecialFileError", + "AbsolutePathError", + "LinkOutsideDestinationError", + ] +if sys.version_info >= (3, 13): + __all__ += ["LinkFallbackError"] + +_FilterFunction: TypeAlias = Callable[[TarInfo, str], TarInfo | None] +_TarfileFilter: TypeAlias = Literal["fully_trusted", "tar", "data"] | _FilterFunction + +@type_check_only +class _Fileobj(Protocol): + def read(self, size: int, /) -> bytes: ... + def write(self, b: bytes, /) -> object: ... + def tell(self) -> int: ... + def seek(self, pos: int, /) -> object: ... + def close(self) -> object: ... + # Optional fields: + # name: str | bytes + # mode: Literal["rb", "r+b", "wb", "xb"] + +@type_check_only +class _Bz2ReadableFileobj(bz2._ReadableFileobj): + def close(self) -> object: ... + +@type_check_only +class _Bz2WritableFileobj(bz2._WritableFileobj): + def close(self) -> object: ... + +# tar constants +NUL: Final = b"\0" +BLOCKSIZE: Final = 512 +RECORDSIZE: Final = 10240 +GNU_MAGIC: Final = b"ustar \0" +POSIX_MAGIC: Final = b"ustar\x0000" + +LENGTH_NAME: Final = 100 +LENGTH_LINK: Final = 100 +LENGTH_PREFIX: Final = 155 + +REGTYPE: Final = b"0" +AREGTYPE: Final = b"\0" +LNKTYPE: Final = b"1" +SYMTYPE: Final = b"2" +CHRTYPE: Final = b"3" +BLKTYPE: Final = b"4" +DIRTYPE: Final = b"5" +FIFOTYPE: Final = b"6" +CONTTYPE: Final = b"7" + +GNUTYPE_LONGNAME: Final = b"L" +GNUTYPE_LONGLINK: Final = b"K" +GNUTYPE_SPARSE: Final = b"S" + +XHDTYPE: Final = b"x" +XGLTYPE: Final = b"g" +SOLARIS_XHDTYPE: Final = b"X" + +_TarFormat: TypeAlias = Literal[0, 1, 2] # does not exist at runtime +USTAR_FORMAT: Final = 0 +GNU_FORMAT: Final = 1 +PAX_FORMAT: Final = 2 +DEFAULT_FORMAT: Final = PAX_FORMAT + +# tarfile constants + +SUPPORTED_TYPES: Final[tuple[bytes, ...]] +REGULAR_TYPES: Final[tuple[bytes, ...]] +GNU_TYPES: Final[tuple[bytes, ...]] +PAX_FIELDS: Final[tuple[str, ...]] +PAX_NUMBER_FIELDS: Final[dict[str, type]] +PAX_NAME_FIELDS: Final[set[str]] + +ENCODING: Final[str] + +class ExFileObject(io.BufferedReader): # undocumented + def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... + +class TarFile: + OPEN_METH: ClassVar[Mapping[str, str]] + name: StrOrBytesPath | None + mode: Literal["r", "a", "w", "x"] + fileobj: _Fileobj + format: _TarFormat + tarinfo: type[TarInfo] + dereference: bool + ignore_zeros: bool + encoding: str + errors: str + fileobject: type[ExFileObject] # undocumented + pax_headers: Mapping[str, str] + debug: Literal[0, 1, 2, 3] + errorlevel: Literal[0, 1, 2] + offset: int # undocumented + extraction_filter: _FilterFunction | None + if sys.version_info >= (3, 13): + stream: bool + if sys.version_info >= (3, 15): + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + stream: bool = False, + mtime: float | None = None, + ) -> None: ... + elif sys.version_info >= (3, 13): + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + stream: bool = False, + ) -> None: ... + else: + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[TarInfo]: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + mode: Literal["r", "r:*", "r:", "r:gz", "r:bz2", "r:xz"] = "r", + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + if sys.version_info >= (3, 14): + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["r:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x", "x:", "a", "a:", "w", "w:", "w:tar"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x", "x:", "a", "a:", "w", "w:", "w:tar"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:gz", "x:bz2", "w:gz", "w:bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:gz", "x:bz2", "w:gz", "w:bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:xz", "w:xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ..., + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:xz", "w:xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ..., + ) -> Self: ... + if sys.version_info >= (3, 14): + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None, + mode: Literal["x:zst", "w:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | None = None, + *, + mode: Literal["x:zst", "w:zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + ) -> Self: ... + + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | ReadableBuffer | None, + mode: Literal["r|*", "r|", "r|gz", "r|bz2", "r|xz", "r|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | ReadableBuffer | None = None, + *, + mode: Literal["r|*", "r|", "r|gz", "r|bz2", "r|xz", "r|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|", "w|xz", "w|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None = None, + *, + mode: Literal["w|", "w|xz", "w|zst"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|gz", "w|bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None = None, + *, + mode: Literal["w|gz", "w|bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + compresslevel: int = 9, + ) -> Self: ... + + @classmethod + def taropen( + cls, + name: StrOrBytesPath | None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + *, + compresslevel: int = ..., + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + @overload + @classmethod + def gzopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["r"] = "r", + fileobj: _GzipReadableFileobj | None = None, + compresslevel: int = 9, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def gzopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["w", "x"], + fileobj: _GzipWritableFileobj | None = None, + compresslevel: int = 9, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + @overload + @classmethod + def bz2open( + cls, + name: StrOrBytesPath | None, + mode: Literal["w", "x"], + fileobj: _Bz2WritableFileobj | None = None, + compresslevel: int = 9, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def bz2open( + cls, + name: StrOrBytesPath | None, + mode: Literal["r"] = "r", + fileobj: _Bz2ReadableFileobj | None = None, + compresslevel: int = 9, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + @classmethod + def xzopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["r", "w", "x"] = "r", + fileobj: IO[bytes] | None = None, + preset: int | None = None, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + if sys.version_info >= (3, 14): + @overload + @classmethod + def zstopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["r"] = "r", + fileobj: IO[bytes] | None = None, + level: None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + @overload + @classmethod + def zstopen( + cls, + name: StrOrBytesPath | None, + mode: Literal["w", "x"], + fileobj: IO[bytes] | None = None, + level: int | None = None, + options: Mapping[int, int] | None = None, + zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + ) -> Self: ... + + def getmember(self, name: str) -> TarInfo: ... + def getmembers(self) -> _list[TarInfo]: ... + def getnames(self) -> _list[str]: ... + def list(self, verbose: bool = True, *, members: Iterable[TarInfo] | None = None) -> None: ... + def next(self) -> TarInfo | None: ... + # Calling this method without `filter` is deprecated, but it may be set either on the class or in an + # individual call, so we can't mark it as @deprecated here. + def extractall( + self, + path: StrOrBytesPath = ".", + members: Iterable[TarInfo] | None = None, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = None, + ) -> None: ... + # Same situation as for `extractall`. + def extract( + self, + member: str | TarInfo, + path: StrOrBytesPath = "", + set_attrs: bool = True, + *, + numeric_owner: bool = False, + filter: _TarfileFilter | None = None, + ) -> None: ... + def _extract_member( + self, + tarinfo: TarInfo, + targetpath: str, + set_attrs: bool = True, + numeric_owner: bool = False, + *, + filter_function: _FilterFunction | None = None, + extraction_root: str | None = None, + ) -> None: ... # undocumented + def extractfile(self, member: str | TarInfo) -> IO[bytes] | None: ... + def makedir(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makefile(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makeunknown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makefifo(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makedev(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makelink(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def makelink_with_filter( + self, tarinfo: TarInfo, targetpath: StrOrBytesPath, filter_function: _FilterFunction, extraction_root: str + ) -> None: ... # undocumented + def chown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath, numeric_owner: bool) -> None: ... # undocumented + def chmod(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def utime(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ... # undocumented + def add( + self, + name: StrPath, + arcname: StrPath | None = None, + recursive: bool = True, + *, + filter: Callable[[TarInfo], TarInfo | None] | None = None, + ) -> None: ... + def addfile(self, tarinfo: TarInfo, fileobj: SupportsRead[bytes] | None = None) -> None: ... + def gettarinfo( + self, name: StrOrBytesPath | None = None, arcname: str | None = None, fileobj: IO[bytes] | None = None + ) -> TarInfo: ... + def close(self) -> None: ... + +open = TarFile.open + +def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ... + +class TarError(Exception): ... +class ReadError(TarError): ... +class CompressionError(TarError): ... +class StreamError(TarError): ... +class ExtractError(TarError): ... +class HeaderError(TarError): ... + +class FilterError(TarError): + # This attribute is only set directly on the subclasses, but the documentation guarantees + # that it is always present on FilterError. + tarinfo: TarInfo + +class AbsolutePathError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class OutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +class SpecialFileError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class AbsoluteLinkError(FilterError): + def __init__(self, tarinfo: TarInfo) -> None: ... + +class LinkOutsideDestinationError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +class LinkFallbackError(FilterError): + def __init__(self, tarinfo: TarInfo, path: str) -> None: ... + +def fully_trusted_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ... +def data_filter(member: TarInfo, dest_path: str) -> TarInfo: ... + +class TarInfo: + __slots__ = ( + "name", + "mode", + "uid", + "gid", + "size", + "mtime", + "chksum", + "type", + "linkname", + "uname", + "gname", + "devmajor", + "devminor", + "offset", + "offset_data", + "pax_headers", + "sparse", + "_tarfile", + "_sparse_structs", + "_link_target", + ) + name: str + path: str + size: int + mtime: int | float + chksum: int + devmajor: int + devminor: int + offset: int + offset_data: int + sparse: bytes | None + mode: int + type: bytes # usually one of the TYPE constants, but could be an arbitrary byte + linkname: str + uid: int + gid: int + uname: str + gname: str + pax_headers: Mapping[str, str] + def __init__(self, name: str = "") -> None: ... + + @property + @deprecated("Deprecated; will be removed in Python 3.16.") + def tarfile(self) -> TarFile | None: ... + @tarfile.setter + @deprecated("Deprecated; will be removed in Python 3.16.") + def tarfile(self, tarfile: TarFile | None) -> None: ... + + @classmethod + def frombuf(cls, buf: bytes | bytearray, encoding: str, errors: str) -> Self: ... + @classmethod + def fromtarfile(cls, tarfile: TarFile) -> Self: ... + + @property + def linkpath(self) -> str: ... + @linkpath.setter + def linkpath(self, linkname: str) -> None: ... + + def replace( + self, + *, + name: str = ..., + mtime: float = ..., + mode: int = ..., + linkname: str = ..., + uid: int = ..., + gid: int = ..., + uname: str = ..., + gname: str = ..., + deep: bool = True, + ) -> Self: ... + def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: ... + def tobuf(self, format: _TarFormat | None = 2, encoding: str | None = "utf-8", errors: str = "surrogateescape") -> bytes: ... + def create_ustar_header( + self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str + ) -> bytes: ... + def create_gnu_header( + self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str + ) -> bytes: ... + def create_pax_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str) -> bytes: ... + @classmethod + def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: ... + def isfile(self) -> bool: ... + def isreg(self) -> bool: ... + def issparse(self) -> bool: ... + def isdir(self) -> bool: ... + def issym(self) -> bool: ... + def islnk(self) -> bool: ... + def ischr(self) -> bool: ... + def isblk(self) -> bool: ... + def isfifo(self) -> bool: ... + def isdev(self) -> bool: ... diff --git a/stdlib/telnetlib.pyi b/stdlib/telnetlib.pyi new file mode 100644 index 000000000000..88aa43d24899 --- /dev/null +++ b/stdlib/telnetlib.pyi @@ -0,0 +1,123 @@ +import socket +from collections.abc import Callable, MutableSequence, Sequence +from re import Match, Pattern +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self + +__all__ = ["Telnet"] + +DEBUGLEVEL: Final = 0 +TELNET_PORT: Final = 23 + +IAC: Final = b"\xff" +DONT: Final = b"\xfe" +DO: Final = b"\xfd" +WONT: Final = b"\xfc" +WILL: Final = b"\xfb" +theNULL: Final = b"\x00" + +SE: Final = b"\xf0" +NOP: Final = b"\xf1" +DM: Final = b"\xf2" +BRK: Final = b"\xf3" +IP: Final = b"\xf4" +AO: Final = b"\xf5" +AYT: Final = b"\xf6" +EC: Final = b"\xf7" +EL: Final = b"\xf8" +GA: Final = b"\xf9" +SB: Final = b"\xfa" + +BINARY: Final = b"\x00" +ECHO: Final = b"\x01" +RCP: Final = b"\x02" +SGA: Final = b"\x03" +NAMS: Final = b"\x04" +STATUS: Final = b"\x05" +TM: Final = b"\x06" +RCTE: Final = b"\x07" +NAOL: Final = b"\x08" +NAOP: Final = b"\t" +NAOCRD: Final = b"\n" +NAOHTS: Final = b"\x0b" +NAOHTD: Final = b"\x0c" +NAOFFD: Final = b"\r" +NAOVTS: Final = b"\x0e" +NAOVTD: Final = b"\x0f" +NAOLFD: Final = b"\x10" +XASCII: Final = b"\x11" +LOGOUT: Final = b"\x12" +BM: Final = b"\x13" +DET: Final = b"\x14" +SUPDUP: Final = b"\x15" +SUPDUPOUTPUT: Final = b"\x16" +SNDLOC: Final = b"\x17" +TTYPE: Final = b"\x18" +EOR: Final = b"\x19" +TUID: Final = b"\x1a" +OUTMRK: Final = b"\x1b" +TTYLOC: Final = b"\x1c" +VT3270REGIME: Final = b"\x1d" +X3PAD: Final = b"\x1e" +NAWS: Final = b"\x1f" +TSPEED: Final = b" " +LFLOW: Final = b"!" +LINEMODE: Final = b'"' +XDISPLOC: Final = b"#" +OLD_ENVIRON: Final = b"$" +AUTHENTICATION: Final = b"%" +ENCRYPT: Final = b"&" +NEW_ENVIRON: Final = b"'" + +TN3270E: Final = b"(" +XAUTH: Final = b")" +CHARSET: Final = b"*" +RSP: Final = b"+" +COM_PORT_OPTION: Final = b"," +SUPPRESS_LOCAL_ECHO: Final = b"-" +TLS: Final = b"." +KERMIT: Final = b"/" +SEND_URL: Final = b"0" +FORWARD_X: Final = b"1" +PRAGMA_LOGON: Final = b"\x8a" +SSPI_LOGON: Final = b"\x8b" +PRAGMA_HEARTBEAT: Final = b"\x8c" +EXOPL: Final = b"\xff" +NOOPT: Final = b"\x00" + +class Telnet: + host: str | None # undocumented + sock: socket.socket | None # undocumented + def __init__(self, host: str | None = None, port: int = 0, timeout: float = ...) -> None: ... + def open(self, host: str, port: int = 0, timeout: float = ...) -> None: ... + def msg(self, msg: str, *args: Any) -> None: ... + def set_debuglevel(self, debuglevel: int) -> None: ... + def close(self) -> None: ... + def get_socket(self) -> socket.socket: ... + def fileno(self) -> int: ... + def write(self, buffer: bytes) -> None: ... + def read_until(self, match: bytes, timeout: float | None = None) -> bytes: ... + def read_all(self) -> bytes: ... + def read_some(self) -> bytes: ... + def read_very_eager(self) -> bytes: ... + def read_eager(self) -> bytes: ... + def read_lazy(self) -> bytes: ... + def read_very_lazy(self) -> bytes: ... + def read_sb_data(self) -> bytes: ... + def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], object] | None) -> None: ... + def process_rawq(self) -> None: ... + def rawq_getchar(self) -> bytes: ... + def fill_rawq(self) -> None: ... + def sock_avail(self) -> bool: ... + def interact(self) -> None: ... + def mt_interact(self) -> None: ... + def listener(self) -> None: ... + def expect( + self, list: MutableSequence[Pattern[bytes] | bytes] | Sequence[Pattern[bytes]], timeout: float | None = None + ) -> tuple[int, Match[bytes] | None, bytes]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... diff --git a/stdlib/tempfile.pyi b/stdlib/tempfile.pyi new file mode 100644 index 000000000000..1df04a3d3667 --- /dev/null +++ b/stdlib/tempfile.pyi @@ -0,0 +1,474 @@ +import io +import sys +from _typeshed import ( + BytesPath, + GenericPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, + StrPath, + WriteableBuffer, +) +from collections.abc import Iterable, Iterator +from types import GenericAlias, TracebackType +from typing import IO, Any, AnyStr, Final, Generic, Literal, overload +from typing_extensions import Self, deprecated + +__all__ = [ + "NamedTemporaryFile", + "TemporaryFile", + "SpooledTemporaryFile", + "TemporaryDirectory", + "mkstemp", + "mkdtemp", + "mktemp", + "TMP_MAX", + "gettempprefix", + "tempdir", + "gettempdir", + "gettempprefixb", + "gettempdirb", +] + +# global variables +TMP_MAX: Final[int] +tempdir: str | None +template: str + +if sys.version_info >= (3, 12): + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> _TemporaryFileWrapper[str]: ... + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> _TemporaryFileWrapper[bytes]: ... + @overload + def NamedTemporaryFile( + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + delete_on_close: bool = True, + ) -> _TemporaryFileWrapper[Any]: ... +else: + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + ) -> _TemporaryFileWrapper[str]: ... + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + ) -> _TemporaryFileWrapper[bytes]: ... + @overload + def NamedTemporaryFile( + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + delete: bool = True, + *, + errors: str | None = None, + ) -> _TemporaryFileWrapper[Any]: ... + +if sys.platform == "win32": + TemporaryFile = NamedTemporaryFile +else: + # See the comments for builtins.open() for an explanation of the overloads. + @overload + def TemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.TextIOWrapper: ... + @overload + def TemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.FileIO: ... + @overload + def TemporaryFile( + *, + buffering: Literal[0], + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + errors: str | None = None, + ) -> io.FileIO: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedWriter: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeReading, + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedReader: ... + @overload + def TemporaryFile( + mode: OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> io.BufferedRandom: ... + @overload + def TemporaryFile( + mode: str = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: GenericPath[AnyStr] | None = None, + *, + errors: str | None = None, + ) -> IO[Any]: ... + +class _TemporaryFileWrapper(IO[AnyStr]): + file: IO[AnyStr] # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter + name: str + delete: bool + if sys.version_info >= (3, 12): + def __init__(self, file: IO[AnyStr], name: str, delete: bool = True, delete_on_close: bool = True) -> None: ... + else: + def __init__(self, file: IO[AnyStr], name: str, delete: bool = True) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def close(self) -> None: ... + # These methods don't exist directly on this object, but + # are delegated to the underlying IO object through __getattr__. + # We need to add them here so that this class is concrete. + def __iter__(self) -> Iterator[AnyStr]: ... + # FIXME: __next__ doesn't actually exist on this class and should be removed: + # see also https://github.com/python/typeshed/pull/5456#discussion_r633068648 + # >>> import tempfile + # >>> ntf=tempfile.NamedTemporaryFile() + # >>> next(ntf) + # Traceback (most recent call last): + # File "", line 1, in + # TypeError: '_TemporaryFileWrapper' object is not an iterator + def __next__(self) -> AnyStr: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def read(self, n: int = ...) -> AnyStr: ... + def readable(self) -> bool: ... + def readline(self, limit: int = ...) -> AnyStr: ... + def readlines(self, hint: int = ...) -> list[AnyStr]: ... + def seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: int | None = ...) -> int: ... + def writable(self) -> bool: ... + + @overload + def write(self: _TemporaryFileWrapper[str], s: str, /) -> int: ... + @overload + def write(self: _TemporaryFileWrapper[bytes], s: ReadableBuffer, /) -> int: ... + @overload + def write(self, s: AnyStr, /) -> int: ... + + @overload + def writelines(self: _TemporaryFileWrapper[str], lines: Iterable[str]) -> None: ... + @overload + def writelines(self: _TemporaryFileWrapper[bytes], lines: Iterable[ReadableBuffer]) -> None: ... + @overload + def writelines(self, lines: Iterable[AnyStr]) -> None: ... + + @property + def closed(self) -> bool: ... + +if sys.version_info >= (3, 11): + _SpooledTemporaryFileBase = io.IOBase +else: + _SpooledTemporaryFileBase = object + +# It does not actually derive from IO[AnyStr], but it does mostly behave +# like one. +class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): + _file: IO[AnyStr] + @property + def encoding(self) -> str: ... # undocumented + @property + def newlines(self) -> str | tuple[str, ...] | None: ... # undocumented + + # bytes needs to go first, as default mode is to open as bytes + @overload + def __init__( + self: SpooledTemporaryFile[bytes], + max_size: int = 0, + mode: OpenBinaryMode = "w+b", + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self: SpooledTemporaryFile[str], + max_size: int = 0, + *, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + *, + errors: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + max_size: int = 0, + *, + mode: str, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: str | None = None, + prefix: str | None = None, + dir: str | None = None, + errors: str | None = None, + ) -> None: ... + + @property + def errors(self) -> str | None: ... + def rollover(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + # These methods are copied from the abstract methods of IO, because + # SpooledTemporaryFile implements IO. + # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918. + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + if sys.version_info >= (3, 11): + # These three work only if the SpooledTemporaryFile is opened in binary mode, + # because the underlying object in text mode does not have these methods. + def read1(self, size: int = ..., /) -> AnyStr: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + def detach(self) -> io.RawIOBase: ... + + def read(self, n: int = ..., /) -> AnyStr: ... + def readline(self, limit: int | None = ..., /) -> AnyStr: ... # type: ignore[override] + def readlines(self, hint: int = ..., /) -> list[AnyStr]: ... # type: ignore[override] + def seek(self, offset: int, whence: int = ...) -> int: ... + def tell(self) -> int: ... + if sys.version_info >= (3, 11): + def truncate(self, size: int | None = None) -> int: ... + else: + def truncate(self, size: int | None = None) -> None: ... # type: ignore[override] + + @overload + def write(self: SpooledTemporaryFile[str], s: str) -> int: ... + @overload + def write(self: SpooledTemporaryFile[bytes], s: ReadableBuffer) -> int: ... + @overload + def write(self, s: AnyStr) -> int: ... + + @overload # type: ignore[override] + def writelines(self: SpooledTemporaryFile[str], iterable: Iterable[str]) -> None: ... + @overload + def writelines(self: SpooledTemporaryFile[bytes], iterable: Iterable[ReadableBuffer]) -> None: ... + @overload + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + + def __iter__(self) -> Iterator[AnyStr]: ... # type: ignore[override] + # These exist at runtime only on 3.11+. + def readable(self) -> bool: ... + def seekable(self) -> bool: ... + def writable(self) -> bool: ... + def __next__(self) -> AnyStr: ... # type: ignore[override] + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class TemporaryDirectory(Generic[AnyStr]): + name: AnyStr + if sys.version_info >= (3, 12): + @overload + def __init__( + self: TemporaryDirectory[str], + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + ignore_cleanup_errors: bool = False, + *, + delete: bool = True, + ) -> None: ... + @overload + def __init__( + self: TemporaryDirectory[bytes], + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + ignore_cleanup_errors: bool = False, + *, + delete: bool = True, + ) -> None: ... + else: + @overload + def __init__( + self: TemporaryDirectory[str], + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + ignore_cleanup_errors: bool = False, + ) -> None: ... + @overload + def __init__( + self: TemporaryDirectory[bytes], + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + ignore_cleanup_errors: bool = False, + ) -> None: ... + + def cleanup(self) -> None: ... + def __enter__(self) -> AnyStr: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# The overloads overlap, but they should still work fine. +@overload +def mkstemp( + suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None, text: bool = False +) -> tuple[int, str]: ... +@overload +def mkstemp( + suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None, text: bool = False +) -> tuple[int, bytes]: ... + +# The overloads overlap, but they should still work fine. +@overload +def mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None) -> str: ... +@overload +def mkdtemp(suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None) -> bytes: ... + +@deprecated("Deprecated since Python 2.3. Use `mkstemp()` or `NamedTemporaryFile(delete=False)` instead.") +def mktemp(suffix: str = "", prefix: str = "tmp", dir: StrPath | None = None) -> str: ... +def gettempdirb() -> bytes: ... +def gettempprefixb() -> bytes: ... +def gettempdir() -> str: ... +def gettempprefix() -> str: ... diff --git a/stdlib/termios.pyi b/stdlib/termios.pyi new file mode 100644 index 000000000000..971c9ad46bf4 --- /dev/null +++ b/stdlib/termios.pyi @@ -0,0 +1,303 @@ +import sys +from _typeshed import FileDescriptorLike +from typing import Any, Final, TypeAlias + +# Must be a list of length 7, containing 6 ints and a list of NCCS 1-character bytes or ints. +_Attr: TypeAlias = list[int | list[bytes | int]] | list[int | list[bytes]] | list[int | list[int]] +# Same as _Attr for return types; we use Any to avoid a union. +_AttrReturn: TypeAlias = list[Any] + +if sys.platform != "win32": + # Values depends on the platform + B0: Final[int] + B110: Final[int] + B115200: Final[int] + B1200: Final[int] + B134: Final[int] + B150: Final[int] + B1800: Final[int] + B19200: Final[int] + B200: Final[int] + B230400: Final[int] + B2400: Final[int] + B300: Final[int] + B38400: Final[int] + B4800: Final[int] + B50: Final[int] + B57600: Final[int] + B600: Final[int] + B75: Final[int] + B9600: Final[int] + BRKINT: Final[int] + BS0: Final[int] + BS1: Final[int] + BSDLY: Final[int] + CDSUSP: Final[int] + CEOF: Final[int] + CEOL: Final[int] + CEOT: Final[int] + CERASE: Final[int] + CFLUSH: Final[int] + CINTR: Final[int] + CKILL: Final[int] + CLNEXT: Final[int] + CLOCAL: Final[int] + CQUIT: Final[int] + CR0: Final[int] + CR1: Final[int] + CR2: Final[int] + CR3: Final[int] + CRDLY: Final[int] + CREAD: Final[int] + CRPRNT: Final[int] + CRTSCTS: Final[int] + CS5: Final[int] + CS6: Final[int] + CS7: Final[int] + CS8: Final[int] + CSIZE: Final[int] + CSTART: Final[int] + CSTOP: Final[int] + CSTOPB: Final[int] + CSUSP: Final[int] + CWERASE: Final[int] + ECHO: Final[int] + ECHOCTL: Final[int] + ECHOE: Final[int] + ECHOK: Final[int] + ECHOKE: Final[int] + ECHONL: Final[int] + ECHOPRT: Final[int] + EXTA: Final[int] + EXTB: Final[int] + FF0: Final[int] + FF1: Final[int] + FFDLY: Final[int] + FIOASYNC: Final[int] + FIOCLEX: Final[int] + FIONBIO: Final[int] + FIONCLEX: Final[int] + FIONREAD: Final[int] + FLUSHO: Final[int] + HUPCL: Final[int] + ICANON: Final[int] + ICRNL: Final[int] + IEXTEN: Final[int] + IGNBRK: Final[int] + IGNCR: Final[int] + IGNPAR: Final[int] + IMAXBEL: Final[int] + INLCR: Final[int] + INPCK: Final[int] + ISIG: Final[int] + ISTRIP: Final[int] + IXANY: Final[int] + IXOFF: Final[int] + IXON: Final[int] + NCCS: Final[int] + NL0: Final[int] + NL1: Final[int] + NLDLY: Final[int] + NOFLSH: Final[int] + OCRNL: Final[int] + OFDEL: Final[int] + OFILL: Final[int] + ONLCR: Final[int] + ONLRET: Final[int] + ONOCR: Final[int] + OPOST: Final[int] + PARENB: Final[int] + PARMRK: Final[int] + PARODD: Final[int] + PENDIN: Final[int] + TAB0: Final[int] + TAB1: Final[int] + TAB2: Final[int] + TAB3: Final[int] + TABDLY: Final[int] + TCIFLUSH: Final[int] + TCIOFF: Final[int] + TCIOFLUSH: Final[int] + TCION: Final[int] + TCOFLUSH: Final[int] + TCOOFF: Final[int] + TCOON: Final[int] + TCSADRAIN: Final[int] + TCSAFLUSH: Final[int] + TCSANOW: Final[int] + TIOCCONS: Final[int] + TIOCEXCL: Final[int] + TIOCGETD: Final[int] + TIOCGPGRP: Final[int] + TIOCGWINSZ: Final[int] + TIOCM_CAR: Final[int] + TIOCM_CD: Final[int] + TIOCM_CTS: Final[int] + TIOCM_DSR: Final[int] + TIOCM_DTR: Final[int] + TIOCM_LE: Final[int] + TIOCM_RI: Final[int] + TIOCM_RNG: Final[int] + TIOCM_RTS: Final[int] + TIOCM_SR: Final[int] + TIOCM_ST: Final[int] + TIOCMBIC: Final[int] + TIOCMBIS: Final[int] + TIOCMGET: Final[int] + TIOCMSET: Final[int] + TIOCNOTTY: Final[int] + TIOCNXCL: Final[int] + TIOCOUTQ: Final[int] + TIOCPKT_DATA: Final[int] + TIOCPKT_DOSTOP: Final[int] + TIOCPKT_FLUSHREAD: Final[int] + TIOCPKT_FLUSHWRITE: Final[int] + TIOCPKT_NOSTOP: Final[int] + TIOCPKT_START: Final[int] + TIOCPKT_STOP: Final[int] + TIOCPKT: Final[int] + TIOCSCTTY: Final[int] + TIOCSETD: Final[int] + TIOCSPGRP: Final[int] + TIOCSTI: Final[int] + TIOCSWINSZ: Final[int] + TOSTOP: Final[int] + VDISCARD: Final[int] + VEOF: Final[int] + VEOL: Final[int] + VEOL2: Final[int] + VERASE: Final[int] + VINTR: Final[int] + VKILL: Final[int] + VLNEXT: Final[int] + VMIN: Final[int] + VQUIT: Final[int] + VREPRINT: Final[int] + VSTART: Final[int] + VSTOP: Final[int] + VSUSP: Final[int] + VT0: Final[int] + VT1: Final[int] + VTDLY: Final[int] + VTIME: Final[int] + VWERASE: Final[int] + + if sys.version_info >= (3, 13): + EXTPROC: Final[int] + IUTF8: Final[int] + + if sys.platform == "darwin" and sys.version_info >= (3, 13): + ALTWERASE: Final[int] + B14400: Final[int] + B28800: Final[int] + B7200: Final[int] + B76800: Final[int] + CCAR_OFLOW: Final[int] + CCTS_OFLOW: Final[int] + CDSR_OFLOW: Final[int] + CDTR_IFLOW: Final[int] + CIGNORE: Final[int] + CRTS_IFLOW: Final[int] + MDMBUF: Final[int] + NL2: Final[int] + NL3: Final[int] + NOKERNINFO: Final[int] + ONOEOT: Final[int] + OXTABS: Final[int] + VDSUSP: Final[int] + VSTATUS: Final[int] + + if sys.platform == "darwin" and sys.version_info >= (3, 11): + TIOCGSIZE: Final[int] + TIOCSSIZE: Final[int] + + if sys.platform == "linux": + B1152000: Final[int] + B576000: Final[int] + CBAUD: Final[int] + CBAUDEX: Final[int] + CIBAUD: Final[int] + IOCSIZE_MASK: Final[int] + IOCSIZE_SHIFT: Final[int] + IUCLC: Final[int] + N_MOUSE: Final[int] + N_PPP: Final[int] + N_SLIP: Final[int] + N_STRIP: Final[int] + N_TTY: Final[int] + NCC: Final[int] + OLCUC: Final[int] + TCFLSH: Final[int] + TCGETA: Final[int] + TCGETS: Final[int] + TCSBRK: Final[int] + TCSBRKP: Final[int] + TCSETA: Final[int] + TCSETAF: Final[int] + TCSETAW: Final[int] + TCSETS: Final[int] + TCSETSF: Final[int] + TCSETSW: Final[int] + TCXONC: Final[int] + TIOCGICOUNT: Final[int] + TIOCGLCKTRMIOS: Final[int] + TIOCGSERIAL: Final[int] + TIOCGSOFTCAR: Final[int] + TIOCINQ: Final[int] + TIOCLINUX: Final[int] + TIOCMIWAIT: Final[int] + TIOCTTYGSTRUCT: Final[int] + TIOCSER_TEMT: Final[int] + TIOCSERCONFIG: Final[int] + TIOCSERGETLSR: Final[int] + TIOCSERGETMULTI: Final[int] + TIOCSERGSTRUCT: Final[int] + TIOCSERGWILD: Final[int] + TIOCSERSETMULTI: Final[int] + TIOCSERSWILD: Final[int] + TIOCSLCKTRMIOS: Final[int] + TIOCSSERIAL: Final[int] + TIOCSSOFTCAR: Final[int] + VSWTC: Final[int] + VSWTCH: Final[int] + XCASE: Final[int] + XTABS: Final[int] + + if sys.platform != "darwin": + B1000000: Final[int] + B1500000: Final[int] + B2000000: Final[int] + B2500000: Final[int] + B3000000: Final[int] + B3500000: Final[int] + B4000000: Final[int] + B460800: Final[int] + B500000: Final[int] + B921600: Final[int] + + if sys.platform != "linux": + TCSASOFT: Final[int] + + if sys.platform != "darwin" and sys.platform != "linux": + # not available on FreeBSD either. + CDEL: Final[int] + CEOL2: Final[int] + CESC: Final[int] + CNUL: Final[int] + COMMON: Final[int] + CSWTCH: Final[int] + IBSHIFT: Final[int] + INIT_C_CC: Final[int] + NSWTCH: Final[int] + + def tcgetattr(fd: FileDescriptorLike, /) -> _AttrReturn: ... + def tcsetattr(fd: FileDescriptorLike, when: int, attributes: _Attr, /) -> None: ... + def tcsendbreak(fd: FileDescriptorLike, duration: int, /) -> None: ... + def tcdrain(fd: FileDescriptorLike, /) -> None: ... + def tcflush(fd: FileDescriptorLike, queue: int, /) -> None: ... + def tcflow(fd: FileDescriptorLike, action: int, /) -> None: ... + if sys.version_info >= (3, 11): + def tcgetwinsize(fd: FileDescriptorLike, /) -> tuple[int, int]: ... + def tcsetwinsize(fd: FileDescriptorLike, winsize: tuple[int, int], /) -> None: ... + + class error(Exception): ... diff --git a/stdlib/textwrap.pyi b/stdlib/textwrap.pyi new file mode 100644 index 000000000000..c00cce3c2d57 --- /dev/null +++ b/stdlib/textwrap.pyi @@ -0,0 +1,103 @@ +from collections.abc import Callable +from re import Pattern + +__all__ = ["TextWrapper", "wrap", "fill", "dedent", "indent", "shorten"] + +class TextWrapper: + width: int + initial_indent: str + subsequent_indent: str + expand_tabs: bool + replace_whitespace: bool + fix_sentence_endings: bool + drop_whitespace: bool + break_long_words: bool + break_on_hyphens: bool + tabsize: int + max_lines: int | None + placeholder: str + + # Attributes not present in documentation + sentence_end_re: Pattern[str] + wordsep_re: Pattern[str] + wordsep_simple_re: Pattern[str] + whitespace_trans: str + unicode_whitespace_trans: dict[int, int] + uspace: int + x: str # leaked loop variable + def __init__( + self, + width: int = 70, + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + drop_whitespace: bool = True, + break_on_hyphens: bool = True, + tabsize: int = 8, + *, + max_lines: int | None = None, + placeholder: str = " [...]", + ) -> None: ... + # Private methods *are* part of the documented API for subclasses. + def _munge_whitespace(self, text: str) -> str: ... + def _split(self, text: str) -> list[str]: ... + def _fix_sentence_endings(self, chunks: list[str]) -> None: ... + def _handle_long_word(self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int) -> None: ... + def _wrap_chunks(self, chunks: list[str]) -> list[str]: ... + def _split_chunks(self, text: str) -> list[str]: ... + def wrap(self, text: str) -> list[str]: ... + def fill(self, text: str) -> str: ... + +def wrap( + text: str, + width: int = 70, + *, + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + max_lines: int | None = None, + placeholder: str = " [...]", +) -> list[str]: ... +def fill( + text: str, + width: int = 70, + *, + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + max_lines: int | None = None, + placeholder: str = " [...]", +) -> str: ... +def shorten( + text: str, + width: int, + *, + initial_indent: str = "", + subsequent_indent: str = "", + expand_tabs: bool = True, + tabsize: int = 8, + replace_whitespace: bool = True, + fix_sentence_endings: bool = False, + break_long_words: bool = True, + break_on_hyphens: bool = True, + drop_whitespace: bool = True, + # Omit `max_lines: int = None`, it is forced to 1 here. + placeholder: str = " [...]", +) -> str: ... +def dedent(text: str) -> str: ... +def indent(text: str, prefix: str, predicate: Callable[[str], bool] | None = None) -> str: ... diff --git a/stdlib/this.pyi b/stdlib/this.pyi new file mode 100644 index 000000000000..8de996b04aec --- /dev/null +++ b/stdlib/this.pyi @@ -0,0 +1,2 @@ +s: str +d: dict[str, str] diff --git a/stdlib/threading.pyi b/stdlib/threading.pyi new file mode 100644 index 000000000000..6b51b424cee6 --- /dev/null +++ b/stdlib/threading.pyi @@ -0,0 +1,221 @@ +import _thread +import sys +from _thread import _ExceptHookArgs, get_native_id as get_native_id +from _typeshed import ProfileFunction, TraceFunction +from collections.abc import Callable, Iterable, Iterator, Mapping +from contextvars import Context +from types import TracebackType +from typing import Any, Final, TypeVar, final +from typing_extensions import Self, deprecated + +_T = TypeVar("_T") + +__all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "ExceptHookArgs", + "getprofile", + "gettrace", + "setprofile", + "settrace", + "local", + "stack_size", + "excepthook", + "get_native_id", +] + +if sys.version_info >= (3, 12): + __all__ += ["setprofile_all_threads", "settrace_all_threads"] + +if sys.version_info >= (3, 15): + __all__ += ["concurrent_tee", "serialize_iterator", "synchronized_iterator"] + +_profile_hook: ProfileFunction | None + +def active_count() -> int: ... +@deprecated("Deprecated since Python 3.10. Use `active_count()` instead.") +def activeCount() -> int: ... +def current_thread() -> Thread: ... +@deprecated("Deprecated since Python 3.10. Use `current_thread()` instead.") +def currentThread() -> Thread: ... +def get_ident() -> int: ... +def enumerate() -> list[Thread]: ... +def main_thread() -> Thread: ... +def settrace(func: TraceFunction | None) -> None: ... +def setprofile(func: ProfileFunction | None) -> None: ... + +if sys.version_info >= (3, 12): + def setprofile_all_threads(func: ProfileFunction | None) -> None: ... + def settrace_all_threads(func: TraceFunction | None) -> None: ... + +def gettrace() -> TraceFunction | None: ... +def getprofile() -> ProfileFunction | None: ... + +if sys.version_info >= (3, 15): + @final + class serialize_iterator(Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + def send(self, value: Any, /) -> _T: ... + def throw(self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ...) -> _T: ... + def close(self) -> None: ... + + def synchronized_iterator(func: Callable[..., Iterable[_T]]) -> Callable[..., Iterator[_T]]: ... + def concurrent_tee(iterable: Iterable[_T], n: int = 2) -> tuple[Iterator[_T], ...]: ... + +def stack_size(size: int = 0, /) -> int: ... + +TIMEOUT_MAX: Final[float] + +ThreadError = _thread.error +local = _thread._local + +class Thread: + name: str + @property + def ident(self) -> int | None: ... + daemon: bool + if sys.version_info >= (3, 14): + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + *, + daemon: bool | None = None, + context: Context | None = None, + ) -> None: ... + else: + def __init__( + self, + group: None = None, + target: Callable[..., object] | None = None, + name: str | None = None, + args: Iterable[Any] = (), + kwargs: Mapping[str, Any] | None = None, + *, + daemon: bool | None = None, + ) -> None: ... + + def start(self) -> None: ... + def run(self) -> None: ... + def join(self, timeout: float | None = None) -> None: ... + @property + def native_id(self) -> int | None: ... # only available on some platforms + def is_alive(self) -> bool: ... + @deprecated("Deprecated since Python 3.10. Read the `daemon` attribute instead.") + def isDaemon(self) -> bool: ... + @deprecated("Deprecated since Python 3.10. Set the `daemon` attribute instead.") + def setDaemon(self, daemonic: bool) -> None: ... + @deprecated("Deprecated since Python 3.10. Read the `name` attribute instead.") + def getName(self) -> str: ... + @deprecated("Deprecated since Python 3.10. Set the `name` attribute instead.") + def setName(self, name: str) -> None: ... + +class _DummyThread(Thread): + def __init__(self) -> None: ... + +# This is actually the function _thread.allocate_lock for <= 3.12 +Lock = _thread.LockType + +# Python implementation of RLock. +@final +class _RLock: + _count: int + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + __enter__ = acquire + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + +RLock = _thread.RLock # Actually a function at runtime. + +class Condition: + def __init__(self, lock: Lock | _RLock | RLock | None = None) -> None: ... + def __enter__(self) -> bool: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... + def release(self) -> None: ... + if sys.version_info >= (3, 14): + def locked(self) -> bool: ... + + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: ... + def notify(self, n: int = 1) -> None: ... + def notify_all(self) -> None: ... + @deprecated("Deprecated since Python 3.10. Use `notify_all()` instead.") + def notifyAll(self) -> None: ... + +class Semaphore: + _value: int + def __init__(self, value: int = 1) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def __enter__(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def release(self, n: int = 1) -> None: ... + +class BoundedSemaphore(Semaphore): ... + +class Event: + def is_set(self) -> bool: ... + @deprecated("Deprecated since Python 3.10. Use `is_set()` instead.") + def isSet(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + def wait(self, timeout: float | None = None) -> bool: ... + +excepthook: Callable[[_ExceptHookArgs], object] +__excepthook__: Callable[[_ExceptHookArgs], object] +ExceptHookArgs = _ExceptHookArgs + +class Timer(Thread): + args: Iterable[Any] # undocumented + finished: Event # undocumented + function: Callable[..., Any] # undocumented + interval: float # undocumented + kwargs: Mapping[str, Any] # undocumented + + def __init__( + self, + interval: float, + function: Callable[..., object], + args: Iterable[Any] | None = None, + kwargs: Mapping[str, Any] | None = None, + ) -> None: ... + def cancel(self) -> None: ... + +class Barrier: + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... + def __init__(self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None) -> None: ... + def wait(self, timeout: float | None = None) -> int: ... + def reset(self) -> None: ... + def abort(self) -> None: ... + +class BrokenBarrierError(RuntimeError): ... diff --git a/stdlib/time.pyi b/stdlib/time.pyi new file mode 100644 index 000000000000..ac53089b8d82 --- /dev/null +++ b/stdlib/time.pyi @@ -0,0 +1,117 @@ +import sys +from _typeshed import structseq +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, final, type_check_only + +_TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] + +if sys.version_info >= (3, 15): + # anticipate on https://github.com/python/cpython/pull/139224 + _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex +else: + # before, time functions only accept (subclass of) float, *not* SupportsFloat + _SupportsFloatOrIndex: TypeAlias = float | SupportsIndex + +altzone: int +daylight: int +timezone: int +tzname: tuple[str, str] + +if sys.platform == "linux": + CLOCK_BOOTTIME: Final[int] +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + CLOCK_PROF: Final[int] # FreeBSD, NetBSD, OpenBSD + CLOCK_UPTIME: Final[int] # FreeBSD, OpenBSD + +if sys.platform != "win32": + CLOCK_MONOTONIC: Final[int] + CLOCK_MONOTONIC_RAW: Final[int] + CLOCK_PROCESS_CPUTIME_ID: Final[int] + CLOCK_REALTIME: Final[int] + CLOCK_THREAD_CPUTIME_ID: Final[int] + if sys.platform != "linux" and sys.platform != "darwin": + CLOCK_HIGHRES: Final[int] # Solaris only + +if sys.platform == "darwin": + CLOCK_UPTIME_RAW: Final[int] + if sys.version_info >= (3, 13): + CLOCK_UPTIME_RAW_APPROX: Final[int] + CLOCK_MONOTONIC_RAW_APPROX: Final[int] + +if sys.platform == "linux": + CLOCK_TAI: Final[int] + +# Constructor takes an iterable of any type, of length between 9 and 11 elements. +# However, it always *behaves* like a tuple of 9 elements, +# even if an iterable with length >9 is passed. +# https://github.com/python/typeshed/pull/6560#discussion_r767162532 +@final +class struct_time(structseq[Any | int], _TimeTuple): + __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") + + @property + def tm_year(self) -> int: ... + @property + def tm_mon(self) -> int: ... + @property + def tm_mday(self) -> int: ... + @property + def tm_hour(self) -> int: ... + @property + def tm_min(self) -> int: ... + @property + def tm_sec(self) -> int: ... + @property + def tm_wday(self) -> int: ... + @property + def tm_yday(self) -> int: ... + @property + def tm_isdst(self) -> int: ... + # These final two properties only exist if a 10- or 11-item sequence was passed to the constructor. + @property + def tm_zone(self) -> str: ... + @property + def tm_gmtoff(self) -> int: ... + +def asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def ctime(seconds: _SupportsFloatOrIndex | None = None, /) -> str: ... +def gmtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ... +def localtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ... +def mktime(time_tuple: _TimeTuple | struct_time, /) -> float: ... +def sleep(seconds: _SupportsFloatOrIndex, /) -> None: ... +def strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: ... +def strptime(data_string: str, format: str = "%a %b %d %H:%M:%S %Y", /) -> struct_time: ... +def time() -> float: ... + +if sys.platform != "win32": + def tzset() -> None: ... # Unix only + +@type_check_only +class _ClockInfo(Protocol): + adjustable: bool + implementation: str + monotonic: bool + resolution: float + +def get_clock_info(name: Literal["monotonic", "perf_counter", "process_time", "time", "thread_time"], /) -> _ClockInfo: ... +def monotonic() -> float: ... +def perf_counter() -> float: ... +def process_time() -> float: ... + +if sys.platform != "win32": + def clock_getres(clk_id: int, /) -> float: ... # Unix only + def clock_gettime(clk_id: int, /) -> float: ... # Unix only + def clock_settime(clk_id: int, time: float, /) -> None: ... # Unix only + +if sys.platform != "win32": + def clock_gettime_ns(clk_id: int, /) -> int: ... + def clock_settime_ns(clock_id: int, time: int, /) -> int: ... + +if sys.platform == "linux": + def pthread_getcpuclockid(thread_id: int, /) -> int: ... + +def monotonic_ns() -> int: ... +def perf_counter_ns() -> int: ... +def process_time_ns() -> int: ... +def time_ns() -> int: ... +def thread_time() -> float: ... +def thread_time_ns() -> int: ... diff --git a/stdlib/timeit.pyi b/stdlib/timeit.pyi new file mode 100644 index 000000000000..cc2b2027a820 --- /dev/null +++ b/stdlib/timeit.pyi @@ -0,0 +1,46 @@ +import sys +import time +from collections.abc import Callable, Sequence +from typing import IO, Any, TypeAlias + +__all__ = ["Timer", "timeit", "repeat", "default_timer"] + +_Timer: TypeAlias = Callable[[], float] +_Stmt: TypeAlias = str | Callable[[], object] + +default_timer: _Timer + +class Timer: + def __init__( + self, + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + globals: dict[str, Any] | None = None, + ) -> None: ... + def print_exc(self, file: IO[str] | None = None) -> None: ... + def timeit(self, number: int = 1000000) -> float: ... + def repeat(self, repeat: int = 5, number: int = 1000000) -> list[float]: ... + if sys.version_info >= (3, 15): + def autorange( + self, callback: Callable[[int, float], object] | None = None, target_time: float = 0.2 + ) -> tuple[int, float]: ... + else: + def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: ... + +def timeit( + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + number: int = 1000000, + globals: dict[str, Any] | None = None, +) -> float: ... +def repeat( + stmt: _Stmt = "pass", + setup: _Stmt = "pass", + timer: _Timer = time.perf_counter, + repeat: int = 5, + number: int = 1000000, + globals: dict[str, Any] | None = None, +) -> list[float]: ... +def main(args: Sequence[str] | None = None, *, _wrap_timer: Callable[[_Timer], _Timer] | None = None) -> None: ... diff --git a/stdlib/tkinter/__init__.pyi b/stdlib/tkinter/__init__.pyi new file mode 100644 index 000000000000..681c6ddba546 --- /dev/null +++ b/stdlib/tkinter/__init__.pyi @@ -0,0 +1,4370 @@ +import _tkinter +import sys +from _typeshed import FileDescriptorLike, Incomplete, MaybeNone, StrOrBytesPath +from collections.abc import Callable, Iterable, Mapping, Sequence +from tkinter.constants import * +from tkinter.font import _FontDescription +from types import GenericAlias, TracebackType +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypedDict, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import TypeVarTuple, Unpack, deprecated, disjoint_base + +if sys.version_info >= (3, 11): + from enum import StrEnum +else: + from enum import Enum + +__all__ = [ + "TclError", + "NO", + "FALSE", + "OFF", + "YES", + "TRUE", + "ON", + "N", + "S", + "W", + "E", + "NW", + "SW", + "NE", + "SE", + "NS", + "EW", + "NSEW", + "CENTER", + "NONE", + "X", + "Y", + "BOTH", + "LEFT", + "TOP", + "RIGHT", + "BOTTOM", + "RAISED", + "SUNKEN", + "FLAT", + "RIDGE", + "GROOVE", + "SOLID", + "HORIZONTAL", + "VERTICAL", + "NUMERIC", + "CHAR", + "WORD", + "BASELINE", + "INSIDE", + "OUTSIDE", + "SEL", + "SEL_FIRST", + "SEL_LAST", + "END", + "INSERT", + "CURRENT", + "ANCHOR", + "ALL", + "NORMAL", + "DISABLED", + "ACTIVE", + "HIDDEN", + "CASCADE", + "CHECKBUTTON", + "COMMAND", + "RADIOBUTTON", + "SEPARATOR", + "SINGLE", + "BROWSE", + "MULTIPLE", + "EXTENDED", + "DOTBOX", + "UNDERLINE", + "PIESLICE", + "CHORD", + "ARC", + "FIRST", + "LAST", + "BUTT", + "PROJECTING", + "ROUND", + "BEVEL", + "MITER", + "MOVETO", + "SCROLL", + "UNITS", + "PAGES", + "TkVersion", + "TclVersion", + "READABLE", + "WRITABLE", + "EXCEPTION", + "EventType", + "Event", + "NoDefaultRoot", + "Variable", + "StringVar", + "IntVar", + "DoubleVar", + "BooleanVar", + "mainloop", + "getint", + "getdouble", + "getboolean", + "Misc", + "CallWrapper", + "XView", + "YView", + "Wm", + "Tk", + "Tcl", + "Pack", + "Place", + "Grid", + "BaseWidget", + "Widget", + "Toplevel", + "Button", + "Canvas", + "Checkbutton", + "Entry", + "Frame", + "Label", + "Listbox", + "Menu", + "Menubutton", + "Message", + "Radiobutton", + "Scale", + "Scrollbar", + "Text", + "OptionMenu", + "Image", + "PhotoImage", + "BitmapImage", + "image_names", + "image_types", + "Spinbox", + "LabelFrame", + "PanedWindow", +] + +# Using anything from tkinter.font in this file means that 'import tkinter' +# seems to also load tkinter.font. That's not how it actually works, but +# unfortunately not much can be done about it. https://github.com/python/typeshed/pull/4346 + +TclError = _tkinter.TclError +wantobjects: int +TkVersion: Final[float] +TclVersion: Final[float] +READABLE: Final = _tkinter.READABLE +WRITABLE: Final = _tkinter.WRITABLE +EXCEPTION: Final = _tkinter.EXCEPTION + +# Quick guide for figuring out which widget class to choose: +# - Misc: any widget (don't use BaseWidget because Tk doesn't inherit from BaseWidget) +# - Widget: anything that is meant to be put into another widget with e.g. pack or grid +# +# Don't trust tkinter's docstrings, because they have been created by copy/pasting from +# Tk's manual pages more than 10 years ago. Use the latest manual pages instead: +# +# $ sudo apt install tk-doc tcl-doc +# $ man 3tk label # tkinter.Label +# $ man 3tk ttk_label # tkinter.ttk.Label +# $ man 3tcl after # tkinter.Misc.after +# +# You can also read the manual pages online: https://www.tcl.tk/doc/ + +# manual page: Tk_GetCursor +_Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str] + +if sys.version_info >= (3, 11): + @type_check_only + class _VersionInfoTypeBase(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + + if sys.version_info >= (3, 12): + class _VersionInfoType(_VersionInfoTypeBase): ... + else: + @disjoint_base + class _VersionInfoType(_VersionInfoTypeBase): ... + +if sys.version_info >= (3, 11): + class EventType(StrEnum): + Activate = "36" + ButtonPress = "4" + Button = ButtonPress + ButtonRelease = "5" + Circulate = "26" + CirculateRequest = "27" + ClientMessage = "33" + Colormap = "32" + Configure = "22" + ConfigureRequest = "23" + Create = "16" + Deactivate = "37" + Destroy = "17" + Enter = "7" + Expose = "12" + FocusIn = "9" + FocusOut = "10" + GraphicsExpose = "13" + Gravity = "24" + KeyPress = "2" + Key = "2" + KeyRelease = "3" + Keymap = "11" + Leave = "8" + Map = "19" + MapRequest = "20" + Mapping = "34" + Motion = "6" + MouseWheel = "38" + NoExpose = "14" + Property = "28" + Reparent = "21" + ResizeRequest = "25" + Selection = "31" + SelectionClear = "29" + SelectionRequest = "30" + Unmap = "18" + VirtualEvent = "35" + Visibility = "15" + +else: + class EventType(str, Enum): + Activate = "36" + ButtonPress = "4" + Button = ButtonPress + ButtonRelease = "5" + Circulate = "26" + CirculateRequest = "27" + ClientMessage = "33" + Colormap = "32" + Configure = "22" + ConfigureRequest = "23" + Create = "16" + Deactivate = "37" + Destroy = "17" + Enter = "7" + Expose = "12" + FocusIn = "9" + FocusOut = "10" + GraphicsExpose = "13" + Gravity = "24" + KeyPress = "2" + Key = KeyPress + KeyRelease = "3" + Keymap = "11" + Leave = "8" + Map = "19" + MapRequest = "20" + Mapping = "34" + Motion = "6" + MouseWheel = "38" + NoExpose = "14" + Property = "28" + Reparent = "21" + ResizeRequest = "25" + Selection = "31" + SelectionClear = "29" + SelectionRequest = "30" + Unmap = "18" + VirtualEvent = "35" + Visibility = "15" + +_W = TypeVar("_W", bound=Misc) +# Events considered covariant because you should never assign to event.widget. +_W_co = TypeVar("_W_co", covariant=True, bound=Misc, default=Misc) + +class Event(Generic[_W_co]): + serial: int + num: int + focus: bool + height: int + width: int + keycode: int + state: int | str + time: int + x: int + y: int + x_root: int + y_root: int + char: str + send_event: bool + keysym: str + keysym_num: int + type: EventType + widget: _W_co + delta: int + if sys.version_info >= (3, 15): + detail: str + user_data: str + if sys.version_info >= (3, 14): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +def NoDefaultRoot() -> None: ... + +class Variable: + def __init__(self, master: Misc | None = None, value=None, name: str | None = None) -> None: ... + def set(self, value) -> None: ... + initialize = set + def get(self): ... + def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: ... + def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: ... + def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") + def trace(self, mode, callback) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") + def trace_variable(self, mode, callback) -> str: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_remove()` instead.") + def trace_vdelete(self, mode, cbname) -> None: ... + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_info()` instead.") + def trace_vinfo(self) -> list[Incomplete]: ... + def __eq__(self, other: object) -> bool: ... + def __del__(self) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +class StringVar(Variable): + def __init__(self, master: Misc | None = None, value: str | None = None, name: str | None = None) -> None: ... + def set(self, value: str) -> None: ... + initialize = set + def get(self) -> str: ... + +class IntVar(Variable): + def __init__(self, master: Misc | None = None, value: int | None = None, name: str | None = None) -> None: ... + def set(self, value: int) -> None: ... + initialize = set + def get(self) -> int: ... + +class DoubleVar(Variable): + def __init__(self, master: Misc | None = None, value: float | None = None, name: str | None = None) -> None: ... + def set(self, value: float) -> None: ... + initialize = set + def get(self) -> float: ... + +class BooleanVar(Variable): + def __init__(self, master: Misc | None = None, value: bool | None = None, name: str | None = None) -> None: ... + def set(self, value: bool) -> None: ... + initialize = set + def get(self) -> bool: ... + +def mainloop(n: int = 0) -> None: ... + +getint = int +getdouble = float + +def getboolean(s) -> bool: ... + +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") + +@type_check_only +class _GridIndexInfo(TypedDict, total=False): + minsize: float | str + pad: float | str + uniform: str | None + weight: int + +@type_check_only +class _BusyInfo(TypedDict): + cursor: _Cursor + +class Misc: + master: Misc | None + tk: _tkinter.TkappType + children: dict[str, Widget] + def destroy(self) -> None: ... + def deletecommand(self, name: str) -> None: ... + def tk_strictMotif(self, boolean=None): ... + def tk_bisque(self) -> None: ... + def tk_setPalette(self, *args, **kw) -> None: ... + def wait_variable(self, name: str | Variable = "PY_VAR") -> None: ... + waitvar = wait_variable + def wait_window(self, window: Misc | None = None) -> None: ... + def wait_visibility(self, window: Misc | None = None) -> None: ... + def setvar(self, name: str = "PY_VAR", value: str = "1") -> None: ... + def getvar(self, name: str = "PY_VAR"): ... + def getint(self, s) -> int: ... + def getdouble(self, s) -> float: ... + def getboolean(self, s) -> bool: ... + def focus_set(self) -> None: ... + focus = focus_set + def focus_force(self) -> None: ... + def focus_get(self) -> Misc | None: ... + def focus_displayof(self) -> Misc | None: ... + def focus_lastfor(self) -> Misc | None: ... + def tk_focusFollowsMouse(self) -> None: ... + def tk_focusNext(self) -> Misc | None: ... + def tk_focusPrev(self) -> Misc | None: ... + if sys.version_info >= (3, 14): + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + else: + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + + def after_cancel(self, id: str) -> None: ... + if sys.version_info >= (3, 13): + def after_info(self, id: str | None = None) -> tuple[str, ...]: ... + + def bell(self, displayof: Literal[0] | Misc | None = 0) -> None: ... + if sys.version_info >= (3, 13): + # Supports options from `_BusyInfo`` + def tk_busy_cget(self, option: Literal["cursor"]) -> _Cursor: ... + busy_cget = tk_busy_cget + def tk_busy_configure(self, cnf: Any = None, **kw: Any) -> Any: ... + tk_busy_config = tk_busy_configure + busy_configure = tk_busy_configure + busy_config = tk_busy_configure + def tk_busy_current(self, pattern: str | None = None) -> list[Misc]: ... + busy_current = tk_busy_current + def tk_busy_forget(self) -> None: ... + busy_forget = tk_busy_forget + def tk_busy_hold(self, **kw: Unpack[_BusyInfo]) -> None: ... + tk_busy = tk_busy_hold + busy_hold = tk_busy_hold + busy = tk_busy_hold + def tk_busy_status(self) -> bool: ... + busy_status = tk_busy_status + + def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: ... + def clipboard_clear(self, *, displayof: Misc = ...) -> None: ... + def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...) -> None: ... + def grab_current(self): ... + def grab_release(self) -> None: ... + def grab_set(self) -> None: ... + def grab_set_global(self) -> None: ... + def grab_status(self) -> Literal["local", "global"] | None: ... + def option_add( + self, pattern, value, priority: int | Literal["widgetDefault", "startupFile", "userDefault", "interactive"] | None = None + ) -> None: ... + def option_clear(self) -> None: ... + def option_get(self, name, className): ... + def option_readfile(self, fileName, priority=None) -> None: ... + def selection_clear(self, **kw) -> None: ... + def selection_get(self, **kw): ... + def selection_handle(self, command, **kw) -> None: ... + def selection_own(self, **kw) -> None: ... + def selection_own_get(self, **kw): ... + def send(self, interp, cmd, *args): ... + def lower(self, belowThis=None) -> None: ... + def tkraise(self, aboveThis=None) -> None: ... + lift = tkraise + if sys.version_info >= (3, 11): + def info_patchlevel(self) -> _VersionInfoType: ... + + def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = 0) -> int: ... + def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = 0) -> str: ... + def winfo_cells(self) -> int: ... + def winfo_children(self) -> list[Widget | Toplevel]: ... + def winfo_class(self) -> str: ... + def winfo_colormapfull(self) -> bool: ... + def winfo_containing(self, rootX: int, rootY: int, displayof: Literal[0] | Misc | None = 0) -> Misc | None: ... + def winfo_depth(self) -> int: ... + def winfo_exists(self) -> bool: ... + def winfo_fpixels(self, number: float | str) -> float: ... + def winfo_geometry(self) -> str: ... + def winfo_height(self) -> int: ... + def winfo_id(self) -> int: ... + def winfo_interps(self, displayof: Literal[0] | Misc | None = 0) -> tuple[str, ...]: ... + def winfo_ismapped(self) -> bool: ... + def winfo_manager(self) -> str: ... + def winfo_name(self) -> str: ... + def winfo_parent(self) -> str: ... # return value needs nametowidget() + def winfo_pathname(self, id: int, displayof: Literal[0] | Misc | None = 0): ... + def winfo_pixels(self, number: float | str) -> int: ... + def winfo_pointerx(self) -> int: ... + def winfo_pointerxy(self) -> tuple[int, int]: ... + def winfo_pointery(self) -> int: ... + def winfo_reqheight(self) -> int: ... + def winfo_reqwidth(self) -> int: ... + def winfo_rgb(self, color: str) -> tuple[int, int, int]: ... + def winfo_rootx(self) -> int: ... + def winfo_rooty(self) -> int: ... + def winfo_screen(self) -> str: ... + def winfo_screencells(self) -> int: ... + def winfo_screendepth(self) -> int: ... + def winfo_screenheight(self) -> int: ... + def winfo_screenmmheight(self) -> int: ... + def winfo_screenmmwidth(self) -> int: ... + def winfo_screenvisual(self) -> str: ... + def winfo_screenwidth(self) -> int: ... + def winfo_server(self) -> str: ... + def winfo_toplevel(self) -> Tk | Toplevel: ... + def winfo_viewable(self) -> bool: ... + def winfo_visual(self) -> str: ... + def winfo_visualid(self) -> str: ... + def winfo_visualsavailable(self, includeids: bool = False) -> list[tuple[str, int]]: ... + def winfo_vrootheight(self) -> int: ... + def winfo_vrootwidth(self) -> int: ... + def winfo_vrootx(self) -> int: ... + def winfo_vrooty(self) -> int: ... + def winfo_width(self) -> int: ... + def winfo_x(self) -> int: ... + def winfo_y(self) -> int: ... + def update(self) -> None: ... + def update_idletasks(self) -> None: ... + + @overload + def bindtags(self, tagList: None = None) -> tuple[str, ...]: ... + @overload + def bindtags(self, tagList: list[str] | tuple[str, ...]) -> None: ... + + # bind with isinstance(func, str) doesn't return anything, but all other + # binds do. The default value of func is not str. + @overload + def bind( + self, + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + # There's no way to know what type of widget bind_all and bind_class + # callbacks will get, so those are Misc. + @overload + def bind_all( + self, + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def bind_all(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload + def bind_all(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + @overload + def bind_class( + self, + className: str, + sequence: str | None = None, + func: Callable[[Event[Misc]], object] | None = None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def bind_class(self, className: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload + def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def unbind(self, sequence: str, funcid: str | None = None) -> None: ... + def unbind_all(self, sequence: str) -> None: ... + def unbind_class(self, className: str, sequence: str) -> None: ... + def mainloop(self, n: int = 0) -> None: ... + def quit(self) -> None: ... + @property + def _windowingsystem(self) -> Literal["win32", "aqua", "x11"]: ... + def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ... + def register( + self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = None, needcleanup: int = 1 + ) -> str: ... + def keys(self) -> list[str]: ... + + @overload + def pack_propagate(self, flag: bool) -> bool | None: ... + @overload + def pack_propagate(self) -> None: ... + + propagate = pack_propagate + def grid_anchor(self, anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] | None = None) -> None: ... + anchor = grid_anchor + + @overload + def grid_bbox( + self, column: None = None, row: None = None, col2: None = None, row2: None = None + ) -> tuple[int, int, int, int] | None: ... + @overload + def grid_bbox(self, column: int, row: int, col2: None = None, row2: None = None) -> tuple[int, int, int, int] | None: ... + @overload + def grid_bbox(self, column: int, row: int, col2: int, row2: int) -> tuple[int, int, int, int] | None: ... + + bbox = grid_bbox + def grid_columnconfigure( + self, + index: int | str | list[int] | tuple[int, ...], + cnf: _GridIndexInfo = {}, + *, + minsize: float | str = ..., + pad: float | str = ..., + uniform: str = ..., + weight: int = ..., + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check + def grid_rowconfigure( + self, + index: int | str | list[int] | tuple[int, ...], + cnf: _GridIndexInfo = {}, + *, + minsize: float | str = ..., + pad: float | str = ..., + uniform: str = ..., + weight: int = ..., + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check + columnconfigure = grid_columnconfigure + rowconfigure = grid_rowconfigure + def grid_location(self, x: float | str, y: float | str) -> tuple[int, int]: ... + + @overload + def grid_propagate(self, flag: bool) -> None: ... + @overload + def grid_propagate(self) -> bool: ... + + def grid_size(self) -> tuple[int, int]: ... + size = grid_size + # Widget because Toplevel or Tk is never a slave + def pack_slaves(self) -> list[Widget]: ... + def grid_slaves(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... + def place_slaves(self) -> list[Widget]: ... + slaves = pack_slaves + if sys.version_info >= (3, 15): + def pack_content(self) -> list[Widget]: ... + def grid_content(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... + def place_content(self) -> list[Widget]: ... + content = pack_content + + def event_add(self, virtual: str, *sequences: str) -> None: ... + def event_delete(self, virtual: str, *sequences: str) -> None: ... + def event_generate( + self, + sequence: str, + *, + above: Misc | int = ..., + borderwidth: float | str = ..., + button: int = ..., + count: int = ..., + data: Any = ..., # anything with usable str() value + delta: int = ..., + detail: str = ..., + focus: bool = ..., + height: float | str = ..., + keycode: int = ..., + keysym: str = ..., + mode: str = ..., + override: bool = ..., + place: Literal["PlaceOnTop", "PlaceOnBottom"] = ..., + root: Misc | int = ..., + rootx: float | str = ..., + rooty: float | str = ..., + sendevent: bool = ..., + serial: int = ..., + state: int | str = ..., + subwindow: Misc | int = ..., + time: int = ..., + warp: bool = ..., + width: float | str = ..., + when: Literal["now", "tail", "head", "mark"] = ..., + x: float | str = ..., + y: float | str = ..., + ) -> None: ... + def event_info(self, virtual: str | None = None) -> tuple[str, ...]: ... + def image_names(self) -> tuple[str, ...]: ... + def image_types(self) -> tuple[str, ...]: ... + # See #4363 and #4891 + def __setitem__(self, key: str, value: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def cget(self, key: str) -> Any: ... + def configure(self, cnf: Any = None) -> Any: ... + config = configure + +class CallWrapper: + func: Incomplete + subst: Incomplete + widget: Incomplete + def __init__(self, func, subst, widget) -> None: ... + def __call__(self, *args): ... + +class XView: + @overload + def xview(self) -> tuple[float, float]: ... + @overload + def xview(self, *args) -> None: ... + + def xview_moveto(self, fraction: float) -> None: ... + + @overload + def xview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... + @overload + def xview_scroll(self, number: float | str, what: Literal["pixels"]) -> None: ... + +class YView: + @overload + def yview(self) -> tuple[float, float]: ... + @overload + def yview(self, *args) -> None: ... + + def yview_moveto(self, fraction: float) -> None: ... + + @overload + def yview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... + @overload + def yview_scroll(self, number: float | str, what: Literal["pixels"]) -> None: ... + +if sys.platform == "darwin": + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + fullscreen: bool + modified: bool + notify: bool + titlepath: str + topmost: bool + transparent: bool + type: str # Present, but not actually used on darwin + +elif sys.platform == "win32": + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + transparentcolor: str + disabled: bool + fullscreen: bool + toolwindow: bool + topmost: bool + +else: + # X11 + @type_check_only + class _WmAttributes(TypedDict): + alpha: float + topmost: bool + zoomed: bool + fullscreen: bool + type: str + +class Wm: + @overload + def wm_aspect(self, minNumer: int, minDenom: int, maxNumer: int, maxDenom: int) -> None: ... + @overload + def wm_aspect( + self, minNumer: None = None, minDenom: None = None, maxNumer: None = None, maxDenom: None = None + ) -> tuple[int, int, int, int] | None: ... + + aspect = wm_aspect + + # wm_attributes: Get all attributes + if sys.version_info >= (3, 13): + @overload + def wm_attributes(self, *, return_python_dict: Literal[False] = False) -> tuple[Any, ...]: ... + @overload + def wm_attributes(self, *, return_python_dict: Literal[True]) -> _WmAttributes: ... + else: + @overload + def wm_attributes(self) -> tuple[Any, ...]: ... + + # wm_attributes: Get one attribute (old variant using string that starts with "-") + @overload + def wm_attributes(self, option: Literal["-alpha"], /) -> float: ... + @overload + def wm_attributes(self, option: Literal["-fullscreen"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-topmost"], /) -> bool: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["-modified"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-notify"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-titlepath"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["-transparent"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-type"], /) -> str: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["-transparentcolor"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["-disabled"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-toolwindow"], /) -> bool: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["-zoomed"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["-type"], /) -> str: ... + if sys.version_info >= (3, 13): + # wm_attributes: Get one attribute (new variant without "-") + @overload + def wm_attributes(self, option: Literal["alpha"], /) -> float: ... + @overload + def wm_attributes(self, option: Literal["fullscreen"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["topmost"], /) -> bool: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["modified"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["notify"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["titlepath"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["transparent"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["type"], /) -> str: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["transparentcolor"], /) -> str: ... + @overload + def wm_attributes(self, option: Literal["disabled"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["toolwindow"], /) -> bool: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["zoomed"], /) -> bool: ... + @overload + def wm_attributes(self, option: Literal["type"], /) -> str: ... + + # wm_attributes: Set an attribute (old variant using string that starts with "-") + @overload + def wm_attributes(self, option: str, /): ... + @overload + def wm_attributes(self, option: Literal["-alpha"], value: float, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-fullscreen"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-topmost"], value: bool, /) -> Literal[""]: ... + if sys.platform == "darwin": + @overload + def wm_attributes(self, option: Literal["-modified"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-notify"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-titlepath"], value: str, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-transparent"], value: bool, /) -> Literal[""]: ... + elif sys.platform == "win32": + @overload + def wm_attributes(self, option: Literal["-transparentcolor"], value: str, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-disabled"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-toolwindow"], value: bool, /) -> Literal[""]: ... + else: + # X11 + @overload + def wm_attributes(self, option: Literal["-zoomed"], value: bool, /) -> Literal[""]: ... + @overload + def wm_attributes(self, option: Literal["-type"], value: str, /) -> Literal[""]: ... + + # wm_attributes: Set multiple attributes (old variant using strings that start with "-") + @overload + def wm_attributes(self, option: str, value, /, *__other_option_value_pairs: Any) -> Literal[""]: ... + + # wm_attributes: Set an attribute (new variant with kwarg instead of string) + if sys.version_info >= (3, 13): + if sys.platform == "darwin": + @overload + def wm_attributes( + self, + *, + alpha: float = ..., + fullscreen: bool = ..., + modified: bool = ..., + notify: bool = ..., + titlepath: str = ..., + topmost: bool = ..., + transparent: bool = ..., + ) -> None: ... + elif sys.platform == "win32": + @overload + def wm_attributes( + self, + *, + alpha: float = ..., + transparentcolor: str = ..., + disabled: bool = ..., + fullscreen: bool = ..., + toolwindow: bool = ..., + topmost: bool = ..., + ) -> None: ... + else: + # X11 + @overload + def wm_attributes( + self, *, alpha: float = ..., topmost: bool = ..., zoomed: bool = ..., fullscreen: bool = ..., type: str = ... + ) -> None: ... + + attributes = wm_attributes + def wm_client(self, name: str | None = None) -> str: ... + client = wm_client + + @overload + def wm_colormapwindows(self) -> list[Misc]: ... + @overload + def wm_colormapwindows(self, wlist: list[Misc] | tuple[Misc, ...], /) -> None: ... + @overload + def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ... + + colormapwindows = wm_colormapwindows + def wm_command(self, value: str | None = None) -> str: ... + command = wm_command + # Some of these always return empty string, but return type is set to None to prevent accidentally using it + def wm_deiconify(self) -> None: ... + deiconify = wm_deiconify + def wm_focusmodel(self, model: Literal["active", "passive"] | None = None) -> Literal["active", "passive", ""]: ... + focusmodel = wm_focusmodel + def wm_forget(self, window: Wm) -> None: ... + forget = wm_forget + def wm_frame(self) -> str: ... + frame = wm_frame + + @overload + def wm_geometry(self, newGeometry: None = None) -> str: ... + @overload + def wm_geometry(self, newGeometry: str) -> None: ... + + geometry = wm_geometry + def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): ... + grid = wm_grid + def wm_group(self, pathName=None): ... + group = wm_group + def wm_iconbitmap(self, bitmap=None, default=None): ... + iconbitmap = wm_iconbitmap + def wm_iconify(self) -> None: ... + iconify = wm_iconify + def wm_iconmask(self, bitmap=None): ... + iconmask = wm_iconmask + def wm_iconname(self, newName=None) -> str: ... + iconname = wm_iconname + def wm_iconphoto(self, default: bool, image1: _PhotoImageLike | str, /, *args: _PhotoImageLike | str) -> None: ... + iconphoto = wm_iconphoto + def wm_iconposition(self, x: int | None = None, y: int | None = None) -> tuple[int, int] | None: ... + iconposition = wm_iconposition + def wm_iconwindow(self, pathName=None): ... + iconwindow = wm_iconwindow + def wm_manage(self, widget) -> None: ... + manage = wm_manage + + @overload + def wm_maxsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... + @overload + def wm_maxsize(self, width: int, height: int) -> None: ... + + maxsize = wm_maxsize + + @overload + def wm_minsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... + @overload + def wm_minsize(self, width: int, height: int) -> None: ... + + minsize = wm_minsize + + @overload + def wm_overrideredirect(self, boolean: None = None) -> bool | None: ... # returns True or None + @overload + def wm_overrideredirect(self, boolean: bool) -> None: ... + + overrideredirect = wm_overrideredirect + def wm_positionfrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... + positionfrom = wm_positionfrom + + @overload + def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: ... + @overload + def wm_protocol(self, name: str, func: None = None) -> str: ... + @overload + def wm_protocol(self, name: None = None, func: None = None) -> tuple[str, ...]: ... + + protocol = wm_protocol + + @overload + def wm_resizable(self, width: None = None, height: None = None) -> tuple[bool, bool]: ... + @overload + def wm_resizable(self, width: bool, height: bool) -> None: ... + + resizable = wm_resizable + def wm_sizefrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... + sizefrom = wm_sizefrom + + @overload + def wm_state(self, newstate: None = None) -> str: ... + @overload + def wm_state(self, newstate: str) -> None: ... + + state = wm_state + + @overload + def wm_title(self, string: None = None) -> str: ... + @overload + def wm_title(self, string: str) -> None: ... + + title = wm_title + + @overload + def wm_transient(self, master: None = None) -> _tkinter.Tcl_Obj: ... + @overload + def wm_transient(self, master: Wm | _tkinter.Tcl_Obj) -> None: ... + + transient = wm_transient + def wm_withdraw(self) -> None: ... + withdraw = wm_withdraw + +class Tk(Misc, Wm): + master: None + def __init__( + # Make sure to keep in sync with other functions that use the same + # args. + # use `git grep screenName` to find them + self, + screenName: str | None = None, + baseName: str | None = None, + className: str = "Tk", + useTk: bool = True, + sync: bool = False, + use: str | None = None, + ) -> None: ... + + # Keep this in sync with ttktheme.ThemedTk. See issue #13858 + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + menu: Menu = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def destroy(self) -> None: ... + def readprofile(self, baseName: str, className: str) -> None: ... + report_callback_exception: Callable[[type[BaseException], BaseException, TracebackType | None], object] + # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo + # Please keep in sync with _tkinter.TkappType. + # Some methods are intentionally missing because they are inherited from Misc instead. + def adderrorinfo(self, msg: str, /) -> None: ... + def call(self, command: Any, /, *args: Any) -> Any: ... + # TODO: Figure out what arguments the following `func` callbacks should accept + def createcommand(self, name: str, func: Callable[..., object], /) -> None: ... + if sys.platform != "win32": + def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ... + def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ... + + def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ... + def dooneevent(self, flags: int = 0, /) -> int: ... + def eval(self, script: str, /) -> str: ... + def evalfile(self, fileName: str, /) -> str: ... + def exprboolean(self, s: str, /) -> Literal[0, 1]: ... + def exprdouble(self, s: str, /) -> float: ... + def exprlong(self, s: str, /) -> int: ... + def exprstring(self, s: str, /) -> str: ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self) -> int: ... + def loadtk(self) -> None: ... + def record(self, script: str, /) -> str: ... + if sys.version_info < (3, 11): + @deprecated("Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.") + def split(self, arg, /): ... + + def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... + def unsetvar(self, *args, **kwargs): ... + + if sys.version_info >= (3, 14): + @overload + def wantobjects(self) -> Literal[0, 1]: ... + else: + @overload + def wantobjects(self) -> bool: ... + + @overload + def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + + def willdispatch(self) -> None: ... + +def Tcl(screenName: str | None = None, baseName: str | None = None, className: str = "Tk", useTk: bool = False) -> Tk: ... + +_InMiscTotal = TypedDict("_InMiscTotal", {"in": Misc}) +_InMiscNonTotal = TypedDict("_InMiscNonTotal", {"in": Misc}, total=False) + +@type_check_only +class _PackInfo(_InMiscTotal): + # 'before' and 'after' never appear in _PackInfo + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] + expand: bool + fill: Literal["none", "x", "y", "both"] + side: Literal["left", "right", "top", "bottom"] + # Paddings come out as int or tuple of int, even though any screen units + # can be specified in pack(). + ipadx: int + ipady: int + padx: int | tuple[int, int] + pady: int | tuple[int, int] + +class Pack: + # _PackInfo is not the valid type for cnf because pad stuff accepts any + # screen units instead of int only. I didn't bother to create another + # TypedDict for cnf because it appears to be a legacy thing that was + # replaced by **kwargs. + def pack_configure( + self, + cnf: Mapping[str, Any] | None = {}, + *, + after: Misc = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + before: Misc = ..., + expand: bool | Literal[0, 1] = 0, + fill: Literal["none", "x", "y", "both"] = ..., + side: Literal["left", "right", "top", "bottom"] = ..., + ipadx: float | str = ..., + ipady: float | str = ..., + padx: float | str | tuple[float | str, float | str] = ..., + pady: float | str | tuple[float | str, float | str] = ..., + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def pack_forget(self) -> None: ... + def pack_info(self) -> _PackInfo: ... # errors if widget hasn't been packed + pack = pack_configure + forget = pack_forget + propagate = Misc.pack_propagate + +@type_check_only +class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] + bordermode: Literal["inside", "outside", "ignore"] + width: str # can be int()ed (even after e.g. widget.place(height='2.3c') or similar) + height: str # can be int()ed + x: str # can be int()ed + y: str # can be int()ed + relheight: str # can be float()ed if not empty string + relwidth: str # can be float()ed if not empty string + relx: str # can be float()ed if not empty string + rely: str # can be float()ed if not empty string + +class Place: + def place_configure( + self, + cnf: Mapping[str, Any] | None = {}, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + bordermode: Literal["inside", "outside", "ignore"] = ..., + width: float | str = ..., + height: float | str = ..., + x: float | str = ..., + y: float | str = ..., + # str allowed for compatibility with place_info() + relheight: str | float = ..., + relwidth: str | float = ..., + relx: str | float = ..., + rely: str | float = ..., + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def place_forget(self) -> None: ... + def place_info(self) -> _PlaceInfo: ... + place = place_configure + info = place_info + +@type_check_only +class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded + column: int + columnspan: int + row: int + rowspan: int + ipadx: int + ipady: int + padx: int | tuple[int, int] + pady: int | tuple[int, int] + sticky: str # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty + +class Grid: + def grid_configure( + self, + cnf: Mapping[str, Any] | None = {}, + *, + column: int = ..., + columnspan: int = ..., + row: int = ..., + rowspan: int = ..., + ipadx: float | str = ..., + ipady: float | str = ..., + padx: float | str | tuple[float | str, float | str] = ..., + pady: float | str | tuple[float | str, float | str] = ..., + sticky: ( + str | list[str] | tuple[str, ...] + ) = ..., # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty + in_: Misc = ..., + **kw: Any, # allow keyword argument named 'in', see #4836 + ) -> None: ... + def grid_forget(self) -> None: ... + def grid_remove(self) -> None: ... + def grid_info(self) -> _GridInfo: ... + grid = grid_configure + location = Misc.grid_location + size = Misc.grid_size + +class BaseWidget(Misc): + master: Misc + widgetName: str + def __init__(self, master, widgetName: str, cnf={}, kw={}, extra=()) -> None: ... + def destroy(self) -> None: ... + +# This class represents any widget except Toplevel or Tk. +class Widget(BaseWidget, Pack, Place, Grid): + # Allow bind callbacks to take e.g. Event[Label] instead of Event[Misc]. + # Tk and Toplevel get notified for their child widgets' events, but other + # widgets don't. + @overload + def bind( + self: _W, + sequence: str | None = None, + func: Callable[[Event[_W]], object] | None = None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + +class Toplevel(BaseWidget, Wm): + # Toplevel and Tk have the same options because they correspond to the same + # Tcl/Tk toplevel widget. For some reason, config and configure must be + # copy/pasted here instead of aliasing as 'config = Tk.config'. + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + class_: str = "Toplevel", + colormap: Literal["new", ""] | Misc = "", + container: bool = False, + cursor: _Cursor = "", + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + menu: Menu = ..., + name: str = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + screen: str = "", # can't be changed after creating widget + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + use: int = ..., + visual: str | tuple[str, int] = "", + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + menu: Menu = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Button(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., # same as borderwidth + bg: str = ..., # same as background + bitmap: str = "", + border: float | str = ..., # same as borderwidth + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + default: Literal["normal", "active", "disabled"] = "disabled", + disabledforeground: str = ..., + fg: str = ..., # same as foreground + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + # width and height must be int for buttons containing just text, but + # buttons with an image accept any screen units. + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + justify: Literal["left", "center", "right"] = "center", + name: str = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + # We allow the textvariable to be any Variable, not necessarily + # StringVar. This is useful for e.g. a button that displays the value + # of an IntVar. + textvariable: Variable = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + cursor: _Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., + justify: Literal["left", "center", "right"] = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: float | str = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def flash(self) -> None: ... + def invoke(self) -> Any: ... + +class Canvas(Widget, XView, YView): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + closeenough: float = 1.0, + confine: bool = True, + cursor: _Cursor = "", + height: float | str = ..., # see COORDINATES in canvas manual page + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = 2, + name: str = ..., + offset=..., # undocumented + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + # Setting scrollregion to None doesn't reset it back to empty, + # but setting it to () does. + scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = (), + selectbackground: str = ..., + selectborderwidth: float | str = 1, + selectforeground: str = ..., + # man page says that state can be 'hidden', but it can't + state: Literal["normal", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = ..., + xscrollcommand: str | Callable[[float, float], object] = "", + xscrollincrement: float | str = 0, + yscrollcommand: str | Callable[[float, float], object] = "", + yscrollincrement: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + closeenough: float = ..., + confine: bool = ..., + cursor: _Cursor = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: float | str = ..., + offset=..., # undocumented + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + state: Literal["normal", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + xscrollincrement: float | str = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., + yscrollincrement: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def addtag(self, *args): ... # internal method + def addtag_above(self, newtag: str, tagOrId: str | int) -> None: ... + def addtag_all(self, newtag: str) -> None: ... + def addtag_below(self, newtag: str, tagOrId: str | int) -> None: ... + def addtag_closest( + self, newtag: str, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None + ) -> None: ... + def addtag_enclosed(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ... + def addtag_overlapping(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ... + def addtag_withtag(self, newtag: str, tagOrId: str | int) -> None: ... + def find(self, *args): ... # internal method + def find_above(self, tagOrId: str | int) -> tuple[int, ...]: ... + def find_all(self) -> tuple[int, ...]: ... + def find_below(self, tagOrId: str | int) -> tuple[int, ...]: ... + def find_closest( + self, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None + ) -> tuple[int, ...]: ... + def find_enclosed(self, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> tuple[int, ...]: ... + def find_overlapping(self, x1: float | str, y1: float | str, x2: float | str, y2: float) -> tuple[int, ...]: ... + def find_withtag(self, tagOrId: str | int) -> tuple[int, ...]: ... + # Incompatible with Misc.bbox(), tkinter violates LSP + def bbox(self, *args: str | int) -> tuple[int, int, int, int]: ... # type: ignore[override] + + @overload + def tag_bind( + self, + tagOrId: str | int, + sequence: str | None = None, + func: Callable[[Event[Canvas]], object] | None = None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def tag_bind( + self, tagOrId: str | int, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None + ) -> None: ... + @overload + def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = None) -> None: ... + def canvasx(self, screenx: float | str, gridspacing: float | str | None = None) -> float: ... + def canvasy(self, screeny: float | str, gridspacing: float | str | None = None) -> float: ... + + @overload + def coords(self, tagOrId: str | int, /) -> list[float]: ... + @overload + def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ... + @overload + def coords(self, tagOrId: str | int, x1: float, y1: float, /, *args: float) -> None: ... + + # create_foo() methods accept coords as a list or tuple, or as separate arguments. + # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. + # Keyword arguments should be the same in all overloads of each method. + def create_arc(self, *args, **kw) -> int: ... + def create_bitmap(self, *args, **kw) -> int: ... + def create_image(self, *args, **kw) -> int: ... + + @overload + def create_line( + self, + x0: float, + y0: float, + x1: float, + y1: float, + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + arrow: Literal["first", "last", "both"] = ..., + arrowshape: tuple[float, float, float] = ..., + capstyle: Literal["round", "projecting", "butt"] = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_line( + self, + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + arrow: Literal["first", "last", "both"] = ..., + arrowshape: tuple[float, float, float] = ..., + capstyle: Literal["round", "projecting", "butt"] = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_line( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + arrow: Literal["first", "last", "both"] = ..., + arrowshape: tuple[float, float, float] = ..., + capstyle: Literal["round", "projecting", "butt"] = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + + @overload + def create_oval( + self, + x0: float, + y0: float, + x1: float, + y1: float, + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_oval( + self, + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_oval( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + + @overload + def create_polygon( + self, + x0: float, + y0: float, + x1: float, + y1: float, + /, + *xy_pairs: float, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_polygon( + self, + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, + *xy_pairs: tuple[float, float], + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_polygon( + self, + coords: ( + tuple[float, ...] + | tuple[tuple[float, float], ...] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + joinstyle: Literal["round", "bevel", "miter"] = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + smooth: bool = ..., + splinesteps: float = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + + @overload + def create_rectangle( + self, + x0: float, + y0: float, + x1: float, + y1: float, + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_rectangle( + self, + xy_pair_0: tuple[float, float], + xy_pair_1: tuple[float, float], + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_rectangle( + self, + coords: ( + tuple[float, float, float, float] + | tuple[tuple[float, float], tuple[float, float]] + | list[int] + | list[float] + | list[tuple[int, int]] + | list[tuple[float, float]] + ), + /, + *, + activedash: str | int | list[int] | tuple[int, ...] = ..., + activefill: str = ..., + activeoutline: str = ..., + activeoutlinestipple: str = ..., + activestipple: str = ..., + activewidth: float | str = ..., + dash: str | int | list[int] | tuple[int, ...] = ..., + dashoffset: float | str = ..., + disableddash: str | int | list[int] | tuple[int, ...] = ..., + disabledfill: str = ..., + disabledoutline: str = ..., + disabledoutlinestipple: str = ..., + disabledstipple: str = ..., + disabledwidth: float | str = ..., + fill: str = ..., + offset: float | str = ..., + outline: str = ..., + outlineoffset: float | str = ..., + outlinestipple: str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + ) -> int: ... + + @overload + def create_text( + self, + x: float, + y: float, + /, + *, + activefill: str = ..., + activestipple: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + angle: float | str = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + fill: str = ..., + font: _FontDescription = ..., + justify: Literal["left", "center", "right"] = ..., + offset: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + text: float | str = ..., + width: float | str = ..., + ) -> int: ... + @overload + def create_text( + self, + coords: tuple[float, float] | list[int] | list[float], + /, + *, + activefill: str = ..., + activestipple: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + angle: float | str = ..., + disabledfill: str = ..., + disabledstipple: str = ..., + fill: str = ..., + font: _FontDescription = ..., + justify: Literal["left", "center", "right"] = ..., + offset: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + stipple: str = ..., + tags: str | list[str] | tuple[str, ...] = ..., + text: float | str = ..., + width: float | str = ..., + ) -> int: ... + + @overload + def create_window( + self, + x: float, + y: float, + /, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + height: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + window: Widget = ..., + ) -> int: ... + @overload + def create_window( + self, + coords: tuple[float, float] | list[int] | list[float], + /, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + height: float | str = ..., + state: Literal["normal", "hidden", "disabled"] = ..., + tags: str | list[str] | tuple[str, ...] = ..., + width: float | str = ..., + window: Widget = ..., + ) -> int: ... + + def dchars(self, *args) -> None: ... + def delete(self, *tagsOrCanvasIds: str | int) -> None: ... + + @overload + def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: ... + @overload + def dtag(self, id: int, tag_to_delete: str, /) -> None: ... + + def focus(self, *args): ... + def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: ... + def icursor(self, *args) -> None: ... + def index(self, *args): ... + def insert(self, *args) -> None: ... + def itemcget(self, tagOrId, option): ... + # itemconfigure kwargs depend on item type, which is not known when type checking + def itemconfigure( + self, tagOrId: str | int, cnf: dict[str, Any] | None = None, **kw: Any + ) -> dict[str, tuple[str, str, str, str, str]] | None: ... + itemconfig = itemconfigure + def move(self, *args) -> None: ... + def moveto(self, tagOrId: str | int, x: Literal[""] | float = "", y: Literal[""] | float = "") -> None: ... + def postscript(self, cnf={}, **kw): ... + # tkinter does: + # lower = tag_lower + # lift = tkraise = tag_raise + # + # But mypy doesn't like aliasing here (maybe because Misc defines the same names) + def tag_lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def lower(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def tag_raise(self, first: str | int, second: str | int | None = ..., /) -> None: ... + def tkraise(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def lift(self, first: str | int, second: str | int | None = ..., /) -> None: ... # type: ignore[override] + def scale(self, tagOrId: str | int, xOrigin: float | str, yOrigin: float | str, xScale: float, yScale: float, /) -> None: ... + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y, gain: int = 10) -> None: ... + def select_adjust(self, tagOrId, index) -> None: ... + def select_clear(self) -> None: ... + def select_from(self, tagOrId, index) -> None: ... + def select_item(self): ... + def select_to(self, tagOrId, index) -> None: ... + def type(self, tagOrId: str | int) -> int | None: ... + +class Checkbutton(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", + name: str = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + # The checkbutton puts a value to its variable when it's checked or + # unchecked. We don't restrict the type of that value here, so + # Any-typing is fine. + # + # I think Checkbutton shouldn't be generic, because then specifying + # "any checkbutton regardless of what variable it uses" would be + # difficult, and we might run into issues just like how list[float] + # and list[int] are incompatible. Also, we would need a way to + # specify "Checkbutton not associated with any variable", which is + # done by setting variable to empty string (the default). + offvalue: Any = 0, + onvalue: Any = 1, + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + selectcolor: str = ..., + selectimage: _Image | str = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + textvariable: Variable = ..., + tristateimage: _Image | str = "", + tristatevalue: Any = "", + underline: int = -1, + variable: Variable | Literal[""] = ..., + width: float | str = 0, + wraplength: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + cursor: _Cursor = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + offvalue: Any = ..., + onvalue: Any = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + tristateimage: _Image | str = ..., + tristatevalue: Any = ..., + underline: int = ..., + variable: Variable | Literal[""] = ..., + width: float | str = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def deselect(self) -> None: ... + def flash(self) -> None: ... + def invoke(self) -> Any: ... + def select(self) -> None: ... + def toggle(self) -> None: ... + +class Entry(Widget, XView): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "xterm", + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkTextFont", + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", # same as invalidcommand + justify: Literal["left", "center", "right"] = "left", + name: str = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "sunken", + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + show: str = "", + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + textvariable: Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", # same as validatecommand + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + show: str = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def delete(self, first: str | int, last: str | int | None = None) -> None: ... + def get(self) -> str: ... + def icursor(self, index: str | int) -> None: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, string: str) -> None: ... + def scan_mark(self, x) -> None: ... + def scan_dragto(self, x) -> None: ... + def selection_adjust(self, index: str | int) -> None: ... + def selection_clear(self) -> None: ... # type: ignore[override] + def selection_from(self, index: str | int) -> None: ... + def selection_present(self) -> bool: ... + def selection_range(self, start: str | int, end: str | int) -> None: ... + def selection_to(self, index: str | int) -> None: ... + select_adjust = selection_adjust + select_clear = selection_clear + select_from = selection_from + select_present = selection_present + select_range = selection_range + select_to = selection_to + +class Frame(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 0, + bg: str = ..., + border: float | str = 0, + borderwidth: float | str = 0, + class_: str = "Frame", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # can't be changed with configure() + cursor: _Cursor = "", + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + name: str = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Label(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + image: _Image | str = "", + justify: Literal["left", "center", "right"] = "center", + name: str = ..., + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", + textvariable: Variable = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + cursor: _Cursor = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., + justify: Literal["left", "center", "right"] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: float | str = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Listbox(Widget, XView, YView): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activestyle: Literal["dotbox", "none", "underline"] = ..., + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + disabledforeground: str = ..., + exportselection: bool | Literal[0, 1] = 1, + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: int = 10, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + justify: Literal["left", "center", "right"] = "left", + # There's no tkinter.ListVar, but seems like bare tkinter.Variable + # actually works for this: + # + # >>> import tkinter + # >>> lb = tkinter.Listbox() + # >>> var = lb['listvariable'] = tkinter.Variable() + # >>> var.set(['foo', 'bar', 'baz']) + # >>> lb.get(0, 'end') + # ('foo', 'bar', 'baz') + listvariable: Variable = ..., + name: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = 0, + selectforeground: str = ..., + # from listbox man page: "The value of the [selectmode] option may be + # arbitrary, but the default bindings expect it to be either single, + # browse, multiple, or extended" + # + # I have never seen anyone setting this to something else than what + # "the default bindings expect", but let's support it anyway. + selectmode: str | Literal["single", "browse", "multiple", "extended"] = "browse", # noqa: Y051 + setgrid: bool = False, + state: Literal["normal", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activestyle: Literal["dotbox", "none", "underline"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + disabledforeground: str = ..., + exportselection: bool = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: int = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + justify: Literal["left", "center", "right"] = ..., + listvariable: Variable = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + selectmode: str | Literal["single", "browse", "multiple", "extended"] = ..., # noqa: Y051 + setgrid: bool = ..., + state: Literal["normal", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def activate(self, index: str | int) -> None: ... + def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def curselection(self): ... + def delete(self, first: str | int, last: str | int | None = None) -> None: ... + def get(self, first: str | int, last: str | int | None = None): ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, *elements: str | float) -> None: ... + def nearest(self, y): ... + def scan_mark(self, x, y) -> None: ... + def scan_dragto(self, x, y) -> None: ... + def see(self, index: str | int) -> None: ... + def selection_anchor(self, index: str | int) -> None: ... + select_anchor = selection_anchor + def selection_clear(self, first: str | int, last: str | int | None = None) -> None: ... # type: ignore[override] + select_clear = selection_clear + def selection_includes(self, index: str | int): ... + select_includes = selection_includes + def selection_set(self, first: str | int, last: str | int | None = None) -> None: ... + select_set = selection_set + def size(self) -> int: ... # type: ignore[override] + def itemcget(self, index: str | int, option): ... + def itemconfigure(self, index: str | int, cnf=None, **kw): ... + itemconfig = itemconfigure + +class Menu(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeborderwidth: float | str = ..., + activeforeground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "arrow", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + name: str = ..., + postcommand: Callable[[], object] | str = "", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + tearoff: bool | Literal[0, 1] = 1, + # I guess tearoffcommand arguments are supposed to be widget objects, + # but they are widget name strings. Use nametowidget() to handle the + # arguments of tearoffcommand. + tearoffcommand: Callable[[str, str], object] | str = "", + title: str = "", + type: Literal["menubar", "tearoff", "normal"] = "normal", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeborderwidth: float | str = ..., + activeforeground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + postcommand: Callable[[], object] | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + tearoff: bool = ..., + tearoffcommand: Callable[[str, str], object] | str = ..., + title: str = ..., + type: Literal["menubar", "tearoff", "normal"] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def tk_popup(self, x: int, y: int, entry: str | int = "") -> None: ... + def activate(self, index: str | int) -> None: ... + def add(self, itemType, cnf={}, **kw): ... # docstring says "Internal function." + def insert(self, index, itemType, cnf={}, **kw): ... # docstring says "Internal function." + def add_cascade( + self, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + label: str = ..., + menu: Menu = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def add_checkbutton( + self, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + label: str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + variable: Variable = ..., + ) -> None: ... + def add_command( + self, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + label: str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def add_radiobutton( + self, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + label: str = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + value: Any = ..., + variable: Variable = ..., + ) -> None: ... + def add_separator(self, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ... + def insert_cascade( + self, + index: str | int, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + label: str = ..., + menu: Menu = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def insert_checkbutton( + self, + index: str | int, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + label: str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + variable: Variable = ..., + ) -> None: ... + def insert_command( + self, + index: str | int, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + label: str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + ) -> None: ... + def insert_radiobutton( + self, + index: str | int, + cnf: dict[str, Any] | None = {}, + *, + accelerator: str = ..., + activebackground: str = ..., + activeforeground: str = ..., + background: str = ..., + bitmap: str = ..., + columnbreak: int = ..., + command: Callable[[], object] | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + font: _FontDescription = ..., + foreground: str = ..., + hidemargin: bool = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + label: str = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + underline: int = ..., + value: Any = ..., + variable: Variable = ..., + ) -> None: ... + def insert_separator(self, index: str | int, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ... + def delete(self, index1: str | int, index2: str | int | None = None) -> None: ... + def entrycget(self, index: str | int, option: str) -> Any: ... + def entryconfigure( + self, index: str | int, cnf: dict[str, Any] | None = None, **kw: Any + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + entryconfig = entryconfigure + def index(self, index: str | int) -> int | None: ... + def invoke(self, index: str | int) -> Any: ... + def post(self, x: int, y: int) -> None: ... + def type(self, index: str | int) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... + def unpost(self) -> None: ... + def xposition(self, index: str | int) -> int: ... + def yposition(self, index: str | int) -> int: ... + +class Menubutton(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + image: _Image | str = "", + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + menu: Menu = ..., + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", + textvariable: Variable = ..., + underline: int = -1, + width: float | str = 0, + wraplength: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + cursor: _Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + menu: Menu = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + underline: int = ..., + width: float | str = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Message(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + aspect: int = 150, + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + justify: Literal["left", "center", "right"] = "left", + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", + textvariable: Variable = ..., + # there's width but no height + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + aspect: int = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + justify: Literal["left", "center", "right"] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Radiobutton(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = "center", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = "", + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = "", + compound: Literal["top", "left", "center", "right", "bottom", "none"] = "none", + cursor: _Cursor = "", + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 1, + image: _Image | str = "", + indicatoron: bool = True, + justify: Literal["left", "center", "right"] = "center", + name: str = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = "", + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + selectcolor: str = ..., + selectimage: _Image | str = "", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + textvariable: Variable = ..., + tristateimage: _Image | str = "", + tristatevalue: Any = "", + underline: int = -1, + value: Any = "", + variable: Variable | Literal[""] = ..., + width: float | str = 0, + wraplength: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activeforeground: str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bitmap: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[], Any] = ..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + cursor: _Cursor = ..., + disabledforeground: str = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + image: _Image | str = ..., + indicatoron: bool = ..., + justify: Literal["left", "center", "right"] = ..., + offrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + overrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove", ""] = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectcolor: str = ..., + selectimage: _Image | str = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: Variable = ..., + tristateimage: _Image | str = ..., + tristatevalue: Any = ..., + underline: int = ..., + value: Any = ..., + variable: Variable | Literal[""] = ..., + width: float | str = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def deselect(self) -> None: ... + def flash(self) -> None: ... + def invoke(self) -> Any: ... + def select(self) -> None: ... + +class Scale(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + background: str = ..., + bd: float | str = 1, + bg: str = ..., + bigincrement: float = 0.0, + border: float | str = 1, + borderwidth: float | str = 1, + # don't know why the callback gets string instead of float + command: str | Callable[[str], object] = "", + cursor: _Cursor = "", + digits: int = 0, + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + from_: float = 0.0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + label: str = "", + length: float | str = 100, + name: str = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + repeatdelay: int = 300, + repeatinterval: int = 100, + resolution: float = 1.0, + showvalue: bool = True, + sliderlength: float | str = 30, + sliderrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "raised", + state: Literal["normal", "active", "disabled"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + tickinterval: float = 0.0, + to: float = 100.0, + troughcolor: str = ..., + variable: IntVar | DoubleVar = ..., + width: float | str = 15, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + bigincrement: float = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: str | Callable[[str], object] = ..., + cursor: _Cursor = ..., + digits: int = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + from_: float = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + label: str = ..., + length: float | str = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + resolution: float = ..., + showvalue: bool = ..., + sliderlength: float | str = ..., + sliderrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: Literal["normal", "active", "disabled"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + tickinterval: float = ..., + to: float = ..., + troughcolor: str = ..., + variable: IntVar | DoubleVar = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def get(self) -> float: ... + def set(self, value) -> None: ... + def coords(self, value: float | None = None) -> tuple[int, int]: ... + def identify(self, x, y) -> Literal["", "slider", "trough1", "trough2"]: ... + +class Scrollbar(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + activerelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "raised", + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + # There are many ways how the command may get called. Search for + # 'SCROLLING COMMANDS' in scrollbar man page. There doesn't seem to + # be any way to specify an overloaded callback function, so we say + # that it can take any args while it can't in reality. + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: _Cursor = "", + elementborderwidth: float | str = -1, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + jump: bool = False, + name: str = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = 300, + repeatinterval: int = 100, + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + troughcolor: str = ..., + width: float | str = ..., + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + activerelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + command: Callable[..., tuple[float, float] | None] | str = ..., + cursor: _Cursor = ..., + elementborderwidth: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + jump: bool = ..., + orient: Literal["horizontal", "vertical"] = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + troughcolor: str = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def activate(self, index=None): ... + def delta(self, deltax: int, deltay: int) -> float: ... + def fraction(self, x: int, y: int) -> float: ... + def identify(self, x: int, y: int) -> Literal["arrow1", "arrow2", "slider", "trough1", "trough2", ""]: ... + def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ... + def set(self, first: float | str, last: float | str) -> None: ... + +_WhatToCount: TypeAlias = Literal[ + "chars", "displaychars", "displayindices", "displaylines", "indices", "lines", "xpixels", "ypixels" +] + +class Text(Widget, XView, YView): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + autoseparators: bool = True, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + blockcursor: bool = False, + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = "xterm", + endline: int | Literal[""] = "", + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkFixedFont", + foreground: str = ..., + # width is always int, but height is allowed to be screen units. + # This doesn't make any sense to me, and this isn't documented. + # The docs seem to say that both should be integers. + height: float | str = 24, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + inactiveselectbackground: str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertunfocussed: Literal["none", "hollow", "solid"] = "none", + insertwidth: float | str = ..., + maxundo: int = 0, + name: str = ..., + padx: float | str = 1, + pady: float | str = 1, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + setgrid: bool = False, + spacing1: float | str = 0, + spacing2: float | str = 0, + spacing3: float | str = 0, + startline: int | Literal[""] = "", + state: Literal["normal", "disabled"] = "normal", + # Literal inside Tuple doesn't actually work + tabs: float | str | tuple[float | str, ...] = "", + tabstyle: Literal["tabular", "wordprocessor"] = "tabular", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + undo: bool = False, + width: int = 80, + wrap: Literal["none", "char", "word"] = "char", + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + autoseparators: bool = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + blockcursor: bool = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + endline: int | Literal[""] = ..., + exportselection: bool = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + inactiveselectbackground: str = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertunfocussed: Literal["none", "hollow", "solid"] = ..., + insertwidth: float | str = ..., + maxundo: int = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + setgrid: bool = ..., + spacing1: float | str = ..., + spacing2: float | str = ..., + spacing3: float | str = ..., + startline: int | Literal[""] = ..., + state: Literal["normal", "disabled"] = ..., + tabs: float | str | tuple[float | str, ...] = ..., + tabstyle: Literal["tabular", "wordprocessor"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + undo: bool = ..., + width: int = ..., + wrap: Literal["none", "char", "word"] = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def bbox(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def compare( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + op: Literal["<", "<=", "==", ">=", ">", "!="], + index2: str | float | _tkinter.Tcl_Obj | Widget, + ) -> bool: ... + + if sys.version_info >= (3, 13): + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + *, + return_ints: Literal[True], + ) -> int: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + *, + return_ints: Literal[True], + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + return_ints: Literal[True], + ) -> tuple[int, ...]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + *, + return_ints: Literal[False] = False, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + *, + return_ints: Literal[False] = False, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + *, + return_ints: Literal[False] = False, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + *, + return_ints: Literal[False] = False, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + *, + return_ints: Literal[False] = False, + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + return_ints: Literal[False] = False, + ) -> tuple[int, ...]: ... + else: + @overload + def count( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg: _WhatToCount | Literal["update"], + /, + ) -> tuple[int] | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: Literal["update"], + arg2: _WhatToCount, + /, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: Literal["update"], + /, + ) -> int | None: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount, + arg2: _WhatToCount, + /, + ) -> tuple[int, int]: ... + @overload + def count( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + arg1: _WhatToCount | Literal["update"], + arg2: _WhatToCount | Literal["update"], + arg3: _WhatToCount | Literal["update"], + /, + *args: _WhatToCount | Literal["update"], + ) -> tuple[int, ...]: ... + + @overload + def debug(self, boolean: None = None) -> bool: ... + @overload + def debug(self, boolean: bool) -> None: ... + + def delete( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None + ) -> None: ... + def dlineinfo(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int, int] | None: ... + + @overload + def dump( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + command: None = None, + *, + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> list[tuple[str, str, str]]: ... + @overload + def dump( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None, + command: Callable[[str, str, str], object] | str, + *, + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> None: ... + @overload + def dump( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + *, + command: Callable[[str, str, str], object] | str, + all: bool = ..., + image: bool = ..., + mark: bool = ..., + tag: bool = ..., + text: bool = ..., + window: bool = ..., + ) -> None: ... + + def edit(self, *args): ... # docstring says "Internal method" + + @overload + def edit_modified(self, arg: None = None) -> bool: ... # actually returns Literal[0, 1] + @overload + def edit_modified(self, arg: bool) -> None: ... # actually returns empty string + + def edit_redo(self) -> None: ... # actually returns empty string + def edit_reset(self) -> None: ... # actually returns empty string + def edit_separator(self) -> None: ... # actually returns empty string + def edit_undo(self) -> None: ... # actually returns empty string + def get( + self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None + ) -> str: ... + + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["image", "name"]) -> str: ... + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["padx", "pady"]) -> int: ... + @overload + def image_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["align"] + ) -> Literal["baseline", "bottom", "center", "top"]: ... + @overload + def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + + @overload + def image_configure( + self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str + ) -> tuple[str, str, str, str, str | int]: ... + @overload + def image_configure( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = None, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + image: _Image | str = ..., + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + + def image_create( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = {}, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + image: _Image | str = ..., + name: str = ..., + padx: float | str = ..., + pady: float | str = ..., + ) -> str: ... + def image_names(self) -> tuple[str, ...]: ... + def index(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str: ... + def insert( + self, index: str | float | _tkinter.Tcl_Obj | Widget, chars: str, *args: str | list[str] | tuple[str, ...] + ) -> None: ... + + @overload + def mark_gravity(self, markName: str, direction: None = None) -> Literal["left", "right"]: ... + @overload + def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string + + def mark_names(self) -> tuple[str, ...]: ... + def mark_set(self, markName: str, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... + def mark_unset(self, *markNames: str) -> None: ... + def mark_next(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ... + def mark_previous(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ... + # **kw of peer_create is same as the kwargs of Text.__init__ + def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = {}, **kw) -> None: ... + def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: ... + def replace( + self, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget, + chars: str, + *args: str | list[str] | tuple[str, ...], + ) -> None: ... + def scan_mark(self, x: int, y: int) -> None: ... + def scan_dragto(self, x: int, y: int) -> None: ... + if sys.version_info >= (3, 15): + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + *, + nolinestop: bool | None = None, + strictlimits: bool | None = None, + ) -> str: ... # returns empty string for not found + def search_all( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + *, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + nolinestop: bool | None = None, + overlap: bool | None = None, + strictlimits: bool | None = None, + ) -> tuple[_tkinter.Tcl_Obj, ...]: ... + else: + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + ) -> str: ... # returns empty string for not found + + def see(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... + def tag_add( + self, tagName: str, index1: str | float | _tkinter.Tcl_Obj | Widget, *args: str | float | _tkinter.Tcl_Obj | Widget + ) -> None: ... + + # tag_bind stuff is very similar to Canvas + @overload + def tag_bind( + self, + tagName: str, + sequence: str | None, + func: Callable[[Event[Text]], object] | None, + add: Literal["", "+"] | bool | None = None, + ) -> str: ... + @overload + def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + + def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = None) -> None: ... + # allowing any string for cget instead of just Literals because there's no other way to look up tag options + def tag_cget(self, tagName: str, option: str): ... + + @overload + def tag_configure( + self, + tagName: str, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bgstipple: str = ..., + borderwidth: float | str = ..., + border: float | str = ..., # alias for borderwidth + elide: bool = ..., + fgstipple: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + justify: Literal["left", "right", "center"] = ..., + lmargin1: float | str = ..., + lmargin2: float | str = ..., + lmargincolor: str = ..., + offset: float | str = ..., + overstrike: bool = ..., + overstrikefg: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + rmargin: float | str = ..., + rmargincolor: str = ..., + selectbackground: str = ..., + selectforeground: str = ..., + spacing1: float | str = ..., + spacing2: float | str = ..., + spacing3: float | str = ..., + tabs: Any = ..., # the exact type is kind of complicated, see manual page + tabstyle: Literal["tabular", "wordprocessor"] = ..., + underline: bool = ..., + underlinefg: str = ..., + wrap: Literal["none", "char", "word"] = ..., # be careful with "none" vs None + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + tag_config = tag_configure + def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: ... # error if no tag names given + def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: ... + def tag_names(self, index: str | float | _tkinter.Tcl_Obj | Widget | None = None) -> tuple[str, ...]: ... + def tag_nextrange( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> tuple[str, str] | tuple[()]: ... + def tag_prevrange( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> tuple[str, str] | tuple[()]: ... + def tag_raise(self, tagName: str, aboveThis: str | None = None) -> None: ... + def tag_ranges(self, tagName: str) -> tuple[_tkinter.Tcl_Obj, ...]: ... + # tag_remove and tag_delete are different + def tag_remove( + self, + tagName: str, + index1: str | float | _tkinter.Tcl_Obj | Widget, + index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, + ) -> None: ... + + @overload + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["padx", "pady"]) -> int: ... + @overload + def window_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["stretch"] + ) -> bool: ... # actually returns Literal[0, 1] + @overload + def window_cget( + self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["align"] + ) -> Literal["baseline", "bottom", "center", "top"]: ... + @overload # window is set to a widget, but read as the string name. + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["create", "window"]) -> str: ... + @overload + def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + + @overload + def window_configure( + self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str + ) -> tuple[str, str, str, str, str | int]: ... + @overload + def window_configure( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = None, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + create: str = ..., + padx: float | str = ..., + pady: float | str = ..., + stretch: bool | Literal[0, 1] = ..., + window: Misc | str = ..., + ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + + window_config = window_configure + def window_create( + self, + index: str | float | _tkinter.Tcl_Obj | Widget, + cnf: dict[str, Any] | None = {}, + *, + align: Literal["baseline", "bottom", "center", "top"] = ..., + create: str = ..., + padx: float | str = ..., + pady: float | str = ..., + stretch: bool | Literal[0, 1] = ..., + window: Misc | str = ..., + ) -> None: ... + def window_names(self) -> tuple[str, ...]: ... + def yview_pickplace(self, *what): ... # deprecated + +class _setit: + def __init__(self, var, value, callback=None) -> None: ... + def __call__(self, *args) -> None: ... + +# manual page: tk_optionMenu +class OptionMenu(Menubutton): + menuname: Incomplete + if sys.version_info >= (3, 14): + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[str], object] | None = ..., + name: str | None = None, + ) -> None: ... + else: + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[str], object] | None = ..., + ) -> None: ... + # configure, config, cget are inherited from Menubutton + # destroy and __getitem__ are overridden, signature does not change + +# This matches tkinter's image classes (PhotoImage and BitmapImage) +# and PIL's tkinter-compatible class (PIL.ImageTk.PhotoImage), +# but not a plain PIL image that isn't tkinter compatible. +# The reason is that PIL has width and height attributes, not methods. +@type_check_only +class _Image(Protocol): + def width(self) -> int: ... + def height(self) -> int: ... + +@type_check_only +class _BitmapImageLike(_Image): ... + +@type_check_only +class _PhotoImageLike(_Image): ... + +class Image(_Image): + name: Incomplete + tk: _tkinter.TkappType + def __init__(self, imgtype, name=None, cnf={}, master: Misc | _tkinter.TkappType | None = None, **kw) -> None: ... + def __del__(self) -> None: ... + def __setitem__(self, key, value) -> None: ... + def __getitem__(self, key): ... + configure: Incomplete + config: Incomplete + def type(self): ... + +class PhotoImage(Image, _PhotoImageLike): + # This should be kept in sync with PIL.ImageTK.PhotoImage.__init__() + def __init__( + self, + name: str | None = None, + cnf: dict[str, Any] = {}, + master: Misc | _tkinter.TkappType | None = None, + *, + data: str | bytes = ..., # not same as data argument of put() + format: str = ..., + file: StrOrBytesPath = ..., + gamma: float = ..., + height: int = ..., + palette: int | str = ..., + width: int = ..., + ) -> None: ... + def configure( + self, + *, + data: str | bytes = ..., + format: str = ..., + file: StrOrBytesPath = ..., + gamma: float = ..., + height: int = ..., + palette: int | str = ..., + width: int = ..., + ) -> None: ... + config = configure + def blank(self) -> None: ... + def cget(self, option: str) -> str: ... + def __getitem__(self, key: str) -> str: ... # always string: image['height'] can be '0' + if sys.version_info >= (3, 13): + def copy( + self, + *, + from_coords: Iterable[int] | None = None, + zoom: int | tuple[int, int] | list[int] | None = None, + subsample: int | tuple[int, int] | list[int] | None = None, + ) -> PhotoImage: ... + def subsample(self, x: int, y: int | Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ... + def zoom(self, x: int, y: int | Literal[""] = "", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ... + def copy_replace( + self, + sourceImage: PhotoImage | str, + *, + from_coords: Iterable[int] | None = None, + to: Iterable[int] | None = None, + shrink: bool = False, + zoom: int | tuple[int, int] | list[int] | None = None, + subsample: int | tuple[int, int] | list[int] | None = None, + # `None` defaults to overlay. + compositingrule: Literal["overlay", "set"] | None = None, + ) -> None: ... + else: + def copy(self) -> PhotoImage: ... + def zoom(self, x: int, y: int | Literal[""] = "") -> PhotoImage: ... + def subsample(self, x: int, y: int | Literal[""] = "") -> PhotoImage: ... + + def get(self, x: int, y: int) -> tuple[int, int, int]: ... + def put( + self, + data: ( + str + | bytes + | list[str] + | list[list[str]] + | list[tuple[str, ...]] + | tuple[str, ...] + | tuple[list[str], ...] + | tuple[tuple[str, ...], ...] + ), + to: tuple[int, int] | tuple[int, int, int, int] | None = None, + ) -> None: ... + if sys.version_info >= (3, 13): + def read( + self, + filename: StrOrBytesPath, + format: str | None = None, + *, + from_coords: Iterable[int] | None = None, + to: Iterable[int] | None = None, + shrink: bool = False, + ) -> None: ... + def write( + self, + filename: StrOrBytesPath, + format: str | None = None, + from_coords: Iterable[int] | None = None, + *, + background: str | None = None, + grayscale: bool = False, + ) -> None: ... + + @overload + def data( + self, format: str, *, from_coords: Iterable[int] | None = None, background: str | None = None, grayscale: bool = False + ) -> bytes: ... + @overload + def data( + self, + format: None = None, + *, + from_coords: Iterable[int] | None = None, + background: str | None = None, + grayscale: bool = False, + ) -> tuple[str, ...]: ... + + else: + def write( + self, filename: StrOrBytesPath, format: str | None = None, from_coords: tuple[int, int] | None = None + ) -> None: ... + + def transparency_get(self, x: int, y: int) -> bool: ... + def transparency_set(self, x: int, y: int, boolean: bool) -> None: ... + +class BitmapImage(Image, _BitmapImageLike): + # This should be kept in sync with PIL.ImageTK.BitmapImage.__init__() + def __init__( + self, + name=None, + cnf: dict[str, Any] = {}, + master: Misc | _tkinter.TkappType | None = None, + *, + background: str = ..., + data: str | bytes = ..., + file: StrOrBytesPath = ..., + foreground: str = ..., + maskdata: str = ..., + maskfile: StrOrBytesPath = ..., + ) -> None: ... + +def image_names() -> tuple[str, ...]: ... +def image_types() -> tuple[str, ...]: ... + +class Spinbox(Widget, XView): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + buttonbackground: str = ..., + buttoncursor: _Cursor = "", + buttondownrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + buttonuprelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: _Cursor = "xterm", + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = True, + fg: str = ..., + font: _FontDescription = "TkTextFont", + foreground: str = ..., + format: str = "", + from_: float = 0.0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + increment: float = 1.0, + insertbackground: str = ..., + insertborderwidth: float | str = 0, + insertofftime: int = 300, + insertontime: int = 600, + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + justify: Literal["left", "center", "right"] = "left", + name: str = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "sunken", + repeatdelay: int = 400, + repeatinterval: int = 100, + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + state: Literal["normal", "disabled", "readonly"] = "normal", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + textvariable: Variable = ..., + to: float = 0.0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + values: list[str] | tuple[str, ...] = ..., + width: int = 20, + wrap: bool = False, + xscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + activebackground: str = ..., + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + buttonbackground: str = ..., + buttoncursor: _Cursor = ..., + buttondownrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + buttonuprelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., + cursor: _Cursor = ..., + disabledbackground: str = ..., + disabledforeground: str = ..., + exportselection: bool = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + format: str = ..., + from_: float = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + increment: float = ..., + insertbackground: str = ..., + insertborderwidth: float | str = ..., + insertofftime: int = ..., + insertontime: int = ..., + insertwidth: float | str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + readonlybackground: str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + repeatdelay: int = ..., + repeatinterval: int = ..., + selectbackground: str = ..., + selectborderwidth: float | str = ..., + selectforeground: str = ..., + state: Literal["normal", "disabled", "readonly"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def delete(self, first, last=None) -> Literal[""]: ... + def get(self) -> str: ... + def icursor(self, index): ... + def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, s: str) -> Literal[""]: ... + # spinbox.invoke("asdf") gives error mentioning .invoke("none"), but it's not documented + def invoke(self, element: Literal["none", "buttonup", "buttondown"]) -> Literal[""]: ... + def scan(self, *args): ... + def scan_mark(self, x): ... + def scan_dragto(self, x): ... + def selection(self, *args) -> tuple[int, ...]: ... + def selection_adjust(self, index): ... + def selection_clear(self): ... # type: ignore[override] + def selection_element(self, element=None): ... + def selection_from(self, index: int) -> None: ... + def selection_present(self) -> None: ... + def selection_range(self, start: int, end: int) -> None: ... + def selection_to(self, index: int) -> None: ... + +class LabelFrame(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 2, + bg: str = ..., + border: float | str = 2, + borderwidth: float | str = 2, + class_: str = "Labelframe", # can't be changed with configure() + colormap: Literal["new", ""] | Misc = "", # can't be changed with configure() + container: bool = False, # undocumented, can't be changed with configure() + cursor: _Cursor = "", + fg: str = ..., + font: _FontDescription = "TkDefaultFont", + foreground: str = ..., + height: float | str = 0, + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = 0, + # 'ne' and 'en' are valid labelanchors, but only 'ne' is a valid _Anchor. + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = "nw", + labelwidget: Misc = ..., + name: str = ..., + padx: float | str = 0, + pady: float | str = 0, + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "groove", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = 0, + text: float | str = "", + visual: str | tuple[str, int] = "", # can't be changed with configure() + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + fg: str = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: float | str = ..., + highlightbackground: str = ..., + highlightcolor: str = ..., + highlightthickness: float | str = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: Misc = ..., + padx: float | str = ..., + pady: float | str = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class PanedWindow(Widget): + def __init__( + self, + master: Misc | None = None, + cnf: dict[str, Any] | None = {}, + *, + background: str = ..., + bd: float | str = 1, + bg: str = ..., + border: float | str = 1, + borderwidth: float | str = 1, + cursor: _Cursor = "", + handlepad: float | str = 8, + handlesize: float | str = 8, + height: float | str = "", + name: str = ..., + opaqueresize: bool = True, + orient: Literal["horizontal", "vertical"] = "horizontal", + proxybackground: str = "", + proxyborderwidth: float | str = 2, + proxyrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + sashcursor: _Cursor = "", + sashpad: float | str = 0, + sashrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = "flat", + sashwidth: float | str = 3, + showhandle: bool = False, + width: float | str = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + bd: float | str = ..., + bg: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + cursor: _Cursor = ..., + handlepad: float | str = ..., + handlesize: float | str = ..., + height: float | str = ..., + opaqueresize: bool = ..., + orient: Literal["horizontal", "vertical"] = ..., + proxybackground: str = ..., + proxyborderwidth: float | str = ..., + proxyrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + sashcursor: _Cursor = ..., + sashpad: float | str = ..., + sashrelief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + sashwidth: float | str = ..., + showhandle: bool = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def add(self, child: Widget, **kw) -> None: ... + def remove(self, child) -> None: ... + forget = remove # type: ignore[assignment] + def identify(self, x: int, y: int): ... + def proxy(self, *args) -> tuple[Incomplete, ...]: ... + def proxy_coord(self) -> tuple[Incomplete, ...]: ... + def proxy_forget(self) -> tuple[Incomplete, ...]: ... + def proxy_place(self, x, y) -> tuple[Incomplete, ...]: ... + def sash(self, *args) -> tuple[Incomplete, ...]: ... + def sash_coord(self, index) -> tuple[Incomplete, ...]: ... + def sash_mark(self, index) -> tuple[Incomplete, ...]: ... + def sash_place(self, index, x, y) -> tuple[Incomplete, ...]: ... + def panecget(self, child, option): ... + def paneconfigure(self, tagOrId, cnf=None, **kw): ... + paneconfig = paneconfigure + def panes(self): ... + +def _test() -> None: ... diff --git a/stdlib/tkinter/colorchooser.pyi b/stdlib/tkinter/colorchooser.pyi new file mode 100644 index 000000000000..d0d6de842656 --- /dev/null +++ b/stdlib/tkinter/colorchooser.pyi @@ -0,0 +1,12 @@ +from tkinter import Misc +from tkinter.commondialog import Dialog +from typing import ClassVar + +__all__ = ["Chooser", "askcolor"] + +class Chooser(Dialog): + command: ClassVar[str] + +def askcolor( + color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... +) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ... diff --git a/stdlib/tkinter/commondialog.pyi b/stdlib/tkinter/commondialog.pyi new file mode 100644 index 000000000000..6dba6bd60928 --- /dev/null +++ b/stdlib/tkinter/commondialog.pyi @@ -0,0 +1,14 @@ +from collections.abc import Mapping +from tkinter import Misc +from typing import Any, ClassVar + +__all__ = ["Dialog"] + +class Dialog: + command: ClassVar[str | None] + master: Misc | None + # Types of options are very dynamic. They depend on the command and are + # sometimes changed to a different type. + options: Mapping[str, Any] + def __init__(self, master: Misc | None = None, **options: Any) -> None: ... + def show(self, **options: Any) -> Any: ... diff --git a/stdlib/tkinter/constants.pyi b/stdlib/tkinter/constants.pyi new file mode 100644 index 000000000000..eb1ef446cf22 --- /dev/null +++ b/stdlib/tkinter/constants.pyi @@ -0,0 +1,80 @@ +from typing import Final + +# These are not actually bools. See #4669 +YES: Final = True +NO: Final = False +TRUE: Final = True +FALSE: Final = False +ON: Final = True +OFF: Final = False +N: Final = "n" +S: Final = "s" +W: Final = "w" +E: Final = "e" +NW: Final = "nw" +SW: Final = "sw" +NE: Final = "ne" +SE: Final = "se" +NS: Final = "ns" +EW: Final = "ew" +NSEW: Final = "nsew" +CENTER: Final = "center" +NONE: Final = "none" +X: Final = "x" +Y: Final = "y" +BOTH: Final = "both" +LEFT: Final = "left" +TOP: Final = "top" +RIGHT: Final = "right" +BOTTOM: Final = "bottom" +RAISED: Final = "raised" +SUNKEN: Final = "sunken" +FLAT: Final = "flat" +RIDGE: Final = "ridge" +GROOVE: Final = "groove" +SOLID: Final = "solid" +HORIZONTAL: Final = "horizontal" +VERTICAL: Final = "vertical" +NUMERIC: Final = "numeric" +CHAR: Final = "char" +WORD: Final = "word" +BASELINE: Final = "baseline" +INSIDE: Final = "inside" +OUTSIDE: Final = "outside" +SEL: Final = "sel" +SEL_FIRST: Final = "sel.first" +SEL_LAST: Final = "sel.last" +END: Final = "end" +INSERT: Final = "insert" +CURRENT: Final = "current" +ANCHOR: Final = "anchor" +ALL: Final = "all" +NORMAL: Final = "normal" +DISABLED: Final = "disabled" +ACTIVE: Final = "active" +HIDDEN: Final = "hidden" +CASCADE: Final = "cascade" +CHECKBUTTON: Final = "checkbutton" +COMMAND: Final = "command" +RADIOBUTTON: Final = "radiobutton" +SEPARATOR: Final = "separator" +SINGLE: Final = "single" +BROWSE: Final = "browse" +MULTIPLE: Final = "multiple" +EXTENDED: Final = "extended" +DOTBOX: Final = "dotbox" +UNDERLINE: Final = "underline" +PIESLICE: Final = "pieslice" +CHORD: Final = "chord" +ARC: Final = "arc" +FIRST: Final = "first" +LAST: Final = "last" +BUTT: Final = "butt" +PROJECTING: Final = "projecting" +ROUND: Final = "round" +BEVEL: Final = "bevel" +MITER: Final = "miter" +MOVETO: Final = "moveto" +SCROLL: Final = "scroll" +UNITS: Final = "units" +PAGES: Final = "pages" diff --git a/stdlib/tkinter/dialog.pyi b/stdlib/tkinter/dialog.pyi new file mode 100644 index 000000000000..971b64f09125 --- /dev/null +++ b/stdlib/tkinter/dialog.pyi @@ -0,0 +1,13 @@ +from collections.abc import Mapping +from tkinter import Widget +from typing import Any, Final + +__all__ = ["Dialog"] + +DIALOG_ICON: Final = "questhead" + +class Dialog(Widget): + widgetName: str + num: int + def __init__(self, master=None, cnf: Mapping[str, Any] = {}, **kw) -> None: ... + def destroy(self) -> None: ... diff --git a/stdlib/tkinter/dnd.pyi b/stdlib/tkinter/dnd.pyi new file mode 100644 index 000000000000..521f451a9b2c --- /dev/null +++ b/stdlib/tkinter/dnd.pyi @@ -0,0 +1,19 @@ +from tkinter import Event, Misc, Tk, Widget +from typing import ClassVar, Protocol, type_check_only + +__all__ = ["dnd_start", "DndHandler"] + +@type_check_only +class _DndSource(Protocol): + def dnd_end(self, target: Widget | None, event: Event[Misc] | None, /) -> None: ... + +class DndHandler: + root: ClassVar[Tk | None] + def __init__(self, source: _DndSource, event: Event[Misc]) -> None: ... + def cancel(self, event: Event[Misc] | None = None) -> None: ... + def finish(self, event: Event[Misc] | None, commit: int = 0) -> None: ... + def on_motion(self, event: Event[Misc]) -> None: ... + def on_release(self, event: Event[Misc]) -> None: ... + def __del__(self) -> None: ... + +def dnd_start(source: _DndSource, event: Event[Misc]) -> DndHandler | None: ... diff --git a/stdlib/tkinter/filedialog.pyi b/stdlib/tkinter/filedialog.pyi new file mode 100644 index 000000000000..b6ef8f45d035 --- /dev/null +++ b/stdlib/tkinter/filedialog.pyi @@ -0,0 +1,149 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath +from collections.abc import Hashable, Iterable +from tkinter import Button, Entry, Event, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog +from typing import IO, ClassVar, Literal + +__all__ = [ + "FileDialog", + "LoadFileDialog", + "SaveFileDialog", + "Open", + "SaveAs", + "Directory", + "askopenfilename", + "asksaveasfilename", + "askopenfilenames", + "askopenfile", + "askopenfiles", + "asksaveasfile", + "askdirectory", +] + +dialogstates: dict[Hashable, tuple[str, str]] + +class FileDialog: + title: str + master: Misc + directory: str | None + top: Toplevel + botframe: Frame + selection: Entry + filter: Entry + midframe: Entry + filesbar: Scrollbar + files: Listbox + dirsbar: Scrollbar + dirs: Listbox + ok_button: Button + filter_button: Button + cancel_button: Button + def __init__( + self, master: Misc, title: str | None = None + ) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either + how: str | None + def go(self, dir_or_file: StrPath = ".", pattern: StrPath = "*", default: StrPath = "", key: Hashable | None = None): ... + def quit(self, how: str | None = None) -> None: ... + def dirs_double_event(self, event: Event) -> None: ... + def dirs_select_event(self, event: Event) -> None: ... + def files_double_event(self, event: Event) -> None: ... + def files_select_event(self, event: Event) -> None: ... + def ok_event(self, event: Event) -> None: ... + def ok_command(self) -> None: ... + def filter_command(self, event: Event | None = None) -> None: ... + def get_filter(self) -> tuple[str, str]: ... + def get_selection(self) -> str: ... + def cancel_command(self, event: Event | None = None) -> None: ... + def set_filter(self, dir: StrPath, pat: StrPath) -> None: ... + def set_selection(self, file: StrPath) -> None: ... + +class LoadFileDialog(FileDialog): + title: str + def ok_command(self) -> None: ... + +class SaveFileDialog(FileDialog): + title: str + def ok_command(self) -> None: ... + +class _Dialog(commondialog.Dialog): ... + +class Open(_Dialog): + command: ClassVar[str] + +class SaveAs(_Dialog): + command: ClassVar[str] + +class Directory(commondialog.Dialog): + command: ClassVar[str] + +# TODO: command kwarg available on macos +def asksaveasfilename( + *, + confirmoverwrite: bool | None = True, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> str: ... # can be empty string +def askopenfilename( + *, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> str: ... # can be empty string +def askopenfilenames( + *, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> Literal[""] | tuple[str, ...]: ... +def askdirectory( + *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = False, parent: Misc | None = ..., title: str | None = ... +) -> str: ... # can be empty string + +# TODO: If someone actually uses these, overload to have the actual return type of open(..., mode) +def asksaveasfile( + mode: str = "w", + *, + confirmoverwrite: bool | None = True, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> IO[Incomplete] | None: ... +def askopenfile( + mode: str = "r", + *, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> IO[Incomplete] | None: ... +def askopenfiles( + mode: str = "r", + *, + defaultextension: str | None = "", + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., + initialdir: StrOrBytesPath | None = ..., + initialfile: StrOrBytesPath | None = ..., + parent: Misc | None = ..., + title: str | None = ..., + typevariable: StringVar | str | None = ..., +) -> tuple[IO[Incomplete], ...]: ... # can be empty tuple +def test() -> None: ... diff --git a/stdlib/tkinter/font.pyi b/stdlib/tkinter/font.pyi new file mode 100644 index 000000000000..d9e0b1315590 --- /dev/null +++ b/stdlib/tkinter/font.pyi @@ -0,0 +1,120 @@ +import _tkinter +import itertools +import tkinter +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Unpack + +__all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] + +NORMAL: Final = "normal" +ROMAN: Final = "roman" +BOLD: Final = "bold" +ITALIC: Final = "italic" + +_FontDescription: TypeAlias = ( + str # "Helvetica 12" + | Font # A font object constructed in Python + | list[Any] # ["Helvetica", 12, BOLD] + | tuple[str] # ("Liberation Sans",) needs wrapping in tuple/list to handle spaces + # ("Liberation Sans", 12) or ("Liberation Sans", 12, "bold", "italic", "underline") + | tuple[str, int, Unpack[tuple[str, ...]]] # Any number of trailing options is permitted + | tuple[str, int, list[str] | tuple[str, ...]] # Options can also be passed as list/tuple + | _tkinter.Tcl_Obj # A font object constructed in Tcl +) + +@type_check_only +class _FontDict(TypedDict): + family: str + size: int + weight: Literal["normal", "bold"] + slant: Literal["roman", "italic"] + underline: bool + overstrike: bool + +@type_check_only +class _MetricsDict(TypedDict): + ascent: int + descent: int + linespace: int + fixed: bool + +class Font: + name: str + delete_font: bool + counter: ClassVar[itertools.count[int]] # undocumented + def __init__( + self, + # In tkinter, 'root' refers to tkinter.Tk by convention, but the code + # actually works with any tkinter widget so we use tkinter.Misc. + root: tkinter.Misc | None = None, + font: _FontDescription | None = None, + name: str | None = None, + exists: bool = False, + *, + family: str = ..., + size: int = ..., + weight: Literal["normal", "bold"] = ..., + slant: Literal["roman", "italic"] = ..., + underline: bool = ..., + overstrike: bool = ..., + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __setitem__(self, key: str, value: Any) -> None: ... + + @overload + def cget(self, option: Literal["family"]) -> str: ... + @overload + def cget(self, option: Literal["size"]) -> int: ... + @overload + def cget(self, option: Literal["weight"]) -> Literal["normal", "bold"]: ... + @overload + def cget(self, option: Literal["slant"]) -> Literal["roman", "italic"]: ... + @overload + def cget(self, option: Literal["underline", "overstrike"]) -> bool: ... + @overload + def cget(self, option: str) -> Any: ... + + __getitem__ = cget + + @overload + def actual(self, option: Literal["family"], displayof: tkinter.Misc | None = None) -> str: ... + @overload + def actual(self, option: Literal["size"], displayof: tkinter.Misc | None = None) -> int: ... + @overload + def actual(self, option: Literal["weight"], displayof: tkinter.Misc | None = None) -> Literal["normal", "bold"]: ... + @overload + def actual(self, option: Literal["slant"], displayof: tkinter.Misc | None = None) -> Literal["roman", "italic"]: ... + @overload + def actual(self, option: Literal["underline", "overstrike"], displayof: tkinter.Misc | None = None) -> bool: ... + @overload + def actual(self, option: None, displayof: tkinter.Misc | None = None) -> _FontDict: ... + @overload + def actual(self, *, displayof: tkinter.Misc | None = None) -> _FontDict: ... + + def config( + self, + *, + family: str = ..., + size: int = ..., + weight: Literal["normal", "bold"] = ..., + slant: Literal["roman", "italic"] = ..., + underline: bool = ..., + overstrike: bool = ..., + ) -> _FontDict | None: ... + configure = config + def copy(self) -> Font: ... + + @overload + def metrics(self, option: Literal["ascent", "descent", "linespace"], /, *, displayof: tkinter.Misc | None = ...) -> int: ... + @overload + def metrics(self, option: Literal["fixed"], /, *, displayof: tkinter.Misc | None = ...) -> bool: ... + @overload + def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... + + def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __del__(self) -> None: ... + +def families(root: tkinter.Misc | None = None, displayof: tkinter.Misc | None = None) -> tuple[str, ...]: ... +def names(root: tkinter.Misc | None = None) -> tuple[str, ...]: ... +def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: ... diff --git a/stdlib/tkinter/messagebox.pyi b/stdlib/tkinter/messagebox.pyi new file mode 100644 index 000000000000..cd95f0de5f80 --- /dev/null +++ b/stdlib/tkinter/messagebox.pyi @@ -0,0 +1,98 @@ +from tkinter import Misc +from tkinter.commondialog import Dialog +from typing import ClassVar, Final, Literal + +__all__ = ["showinfo", "showwarning", "showerror", "askquestion", "askokcancel", "askyesno", "askyesnocancel", "askretrycancel"] + +ERROR: Final = "error" +INFO: Final = "info" +QUESTION: Final = "question" +WARNING: Final = "warning" +ABORTRETRYIGNORE: Final = "abortretryignore" +OK: Final = "ok" +OKCANCEL: Final = "okcancel" +RETRYCANCEL: Final = "retrycancel" +YESNO: Final = "yesno" +YESNOCANCEL: Final = "yesnocancel" +ABORT: Final = "abort" +RETRY: Final = "retry" +IGNORE: Final = "ignore" +CANCEL: Final = "cancel" +YES: Final = "yes" +NO: Final = "no" + +class Message(Dialog): + command: ClassVar[str] + +def showinfo( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def showwarning( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def showerror( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok"] = "ok", + parent: Misc = ..., +) -> str: ... +def askquestion( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["yes", "no"] = ..., + parent: Misc = ..., +) -> str: ... +def askokcancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["ok", "cancel"] = ..., + parent: Misc = ..., +) -> bool: ... +def askyesno( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["yes", "no"] = ..., + parent: Misc = ..., +) -> bool: ... +def askyesnocancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["cancel", "yes", "no"] = ..., + parent: Misc = ..., +) -> bool | None: ... +def askretrycancel( + title: str | None = None, + message: str | None = None, + *, + detail: str = ..., + icon: Literal["error", "info", "question", "warning"] = ..., + default: Literal["retry", "cancel"] = ..., + parent: Misc = ..., +) -> bool: ... diff --git a/stdlib/tkinter/scrolledtext.pyi b/stdlib/tkinter/scrolledtext.pyi new file mode 100644 index 000000000000..6f1abc714487 --- /dev/null +++ b/stdlib/tkinter/scrolledtext.pyi @@ -0,0 +1,9 @@ +from tkinter import Frame, Misc, Scrollbar, Text + +__all__ = ["ScrolledText"] + +# The methods from Pack, Place, and Grid are dynamically added over the parent's impls +class ScrolledText(Text): + frame: Frame + vbar: Scrollbar + def __init__(self, master: Misc | None = None, **kwargs) -> None: ... diff --git a/stdlib/tkinter/simpledialog.pyi b/stdlib/tkinter/simpledialog.pyi new file mode 100644 index 000000000000..6f66f0237b45 --- /dev/null +++ b/stdlib/tkinter/simpledialog.pyi @@ -0,0 +1,58 @@ +import sys +from tkinter import Event, Frame, Misc, Toplevel + +if sys.version_info >= (3, 15): + __all__ = ["SimpleDialog", "Dialog", "askinteger", "askfloat", "askstring"] + +class Dialog(Toplevel): + def __init__(self, parent: Misc | None, title: str | None = None) -> None: ... + def body(self, master: Frame) -> Misc | None: ... + def buttonbox(self) -> None: ... + def ok(self, event: Event[Misc] | None = None) -> None: ... + def cancel(self, event: Event[Misc] | None = None) -> None: ... + def validate(self) -> bool: ... + def apply(self) -> None: ... + +class SimpleDialog: + def __init__( + self, + master: Misc | None, + text: str = "", + buttons: list[str] = [], + default: int | None = None, + cancel: int | None = None, + title: str | None = None, + class_: str | None = None, + ) -> None: ... + def go(self) -> int | None: ... + def return_event(self, event: Event[Misc]) -> None: ... + def wm_delete_window(self) -> None: ... + def done(self, num: int) -> None: ... + +def askfloat( + title: str | None, + prompt: str, + *, + initialvalue: float | None = ..., + minvalue: float | None = ..., + maxvalue: float | None = ..., + parent: Misc | None = ..., +) -> float | None: ... +def askinteger( + title: str | None, + prompt: str, + *, + initialvalue: int | None = ..., + minvalue: int | None = ..., + maxvalue: int | None = ..., + parent: Misc | None = ..., +) -> int | None: ... +def askstring( + title: str | None, + prompt: str, + *, + initialvalue: str | None = ..., + show: str | None = ..., + # minvalue/maxvalue is accepted but not useful. + parent: Misc | None = ..., +) -> str | None: ... diff --git a/stdlib/tkinter/tix.pyi b/stdlib/tkinter/tix.pyi new file mode 100644 index 000000000000..7891364fa02c --- /dev/null +++ b/stdlib/tkinter/tix.pyi @@ -0,0 +1,299 @@ +import tkinter +from _typeshed import Incomplete +from typing import Any, Final + +WINDOW: Final = "window" +TEXT: Final = "text" +STATUS: Final = "status" +IMMEDIATE: Final = "immediate" +IMAGE: Final = "image" +IMAGETEXT: Final = "imagetext" +BALLOON: Final = "balloon" +AUTO: Final = "auto" +ACROSSTOP: Final = "acrosstop" + +ASCII: Final = "ascii" +CELL: Final = "cell" +COLUMN: Final = "column" +DECREASING: Final = "decreasing" +INCREASING: Final = "increasing" +INTEGER: Final = "integer" +MAIN: Final = "main" +MAX: Final = "max" +REAL: Final = "real" +ROW: Final = "row" +S_REGION: Final = "s-region" +X_REGION: Final = "x-region" +Y_REGION: Final = "y-region" + +# These should be kept in sync with _tkinter constants, except TCL_ALL_EVENTS which doesn't match ALL_EVENTS +TCL_DONT_WAIT: Final = 2 +TCL_WINDOW_EVENTS: Final = 4 +TCL_FILE_EVENTS: Final = 8 +TCL_TIMER_EVENTS: Final = 16 +TCL_IDLE_EVENTS: Final = 32 +TCL_ALL_EVENTS: Final = 0 + +class tixCommand: + def tix_addbitmapdir(self, directory: str) -> None: ... + def tix_cget(self, option: str) -> Any: ... + def tix_configure(self, cnf: dict[str, Any] | None = None, **kw: Any) -> Any: ... + def tix_filedialog(self, dlgclass: str | None = None) -> str: ... + def tix_getbitmap(self, name: str) -> str: ... + def tix_getimage(self, name: str) -> str: ... + def tix_option_get(self, name: str) -> Any: ... + def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = None) -> None: ... + +class Tk(tkinter.Tk, tixCommand): + def __init__(self, screenName: str | None = None, baseName: str | None = None, className: str = "Tix") -> None: ... + +class TixWidget(tkinter.Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + widgetName: str | None = None, + static_options: list[str] | None = None, + cnf: dict[str, Any] = {}, + kw: dict[str, Any] = {}, + ) -> None: ... + def __getattr__(self, name: str): ... + def set_silent(self, value: str) -> None: ... + def subwidget(self, name: str) -> tkinter.Widget: ... + def subwidgets_all(self) -> list[tkinter.Widget]: ... + def config_all(self, option: Any, value: Any) -> None: ... + def image_create(self, imgtype: str, cnf: dict[str, Any] = {}, master: tkinter.Widget | None = None, **kw) -> None: ... + def image_delete(self, imgname: str) -> None: ... + +class TixSubWidget(TixWidget): + def __init__(self, master: tkinter.Widget, name: str, destroy_physically: int = 1, check_intermediate: int = 1) -> None: ... + +class DisplayStyle: + def __init__(self, itemtype: str, cnf: dict[str, Any] = {}, *, master: tkinter.Widget | None = None, **kw) -> None: ... + def __getitem__(self, key: str): ... + def __setitem__(self, key: str, value: Any) -> None: ... + def delete(self) -> None: ... + def config(self, cnf: dict[str, Any] = {}, **kw): ... + +class Balloon(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = {}, **kw) -> None: ... + def unbind_widget(self, widget: tkinter.Widget) -> None: ... + +class ButtonBox(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... + def invoke(self, name: str) -> None: ... + +class ComboBox(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add_history(self, str: str) -> None: ... + def append_history(self, str: str) -> None: ... + def insert(self, index: int, str: str) -> None: ... + def pick(self, index: int) -> None: ... + +class Control(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def decrement(self) -> None: ... + def increment(self) -> None: ... + def invoke(self) -> None: ... + +class LabelEntry(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + +class LabelFrame(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + +class Meter(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + +class OptionMenu(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add_command(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add_separator(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def delete(self, name: str) -> None: ... + def disable(self, name: str) -> None: ... + def enable(self, name: str) -> None: ... + +class PopupMenu(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def bind_widget(self, widget: tkinter.Widget) -> None: ... + def unbind_widget(self, widget: tkinter.Widget) -> None: ... + def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ... + +class Select(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... + def invoke(self, name: str) -> None: ... + +class StdButtonBox(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def invoke(self, name: str) -> None: ... + +class DirList(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def chdir(self, dir: str) -> None: ... + +class DirTree(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def chdir(self, dir: str) -> None: ... + +class DirSelectDialog(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def popup(self) -> None: ... + def popdown(self) -> None: ... + +class DirSelectBox(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + +class ExFileSelectBox(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def filter(self) -> None: ... + def invoke(self) -> None: ... + +class FileSelectBox(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def apply_filter(self) -> None: ... + def invoke(self) -> None: ... + +class FileEntry(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def invoke(self) -> None: ... + def file_dialog(self) -> None: ... + +class HList(TixWidget, tkinter.XView, tkinter.YView): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... + def add_child(self, parent: str | None = None, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ... + def anchor_set(self, entry: str) -> None: ... + def anchor_clear(self) -> None: ... + # FIXME: Overload, certain combos return, others don't + def column_width(self, col: int = 0, width: int | None = None, chars: int | None = None) -> int | None: ... + def delete_all(self) -> None: ... + def delete_entry(self, entry: str) -> None: ... + def delete_offsprings(self, entry: str) -> None: ... + def delete_siblings(self, entry: str) -> None: ... + def dragsite_set(self, index: int) -> None: ... + def dragsite_clear(self) -> None: ... + def dropsite_set(self, index: int) -> None: ... + def dropsite_clear(self) -> None: ... + def header_create(self, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ... + def header_configure(self, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def header_cget(self, col: int, opt): ... + def header_exists(self, col: int) -> bool: ... + def header_exist(self, col: int) -> bool: ... + def header_delete(self, col: int) -> None: ... + def header_size(self, col: int) -> int: ... + def hide_entry(self, entry: str) -> None: ... + def indicator_create(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def indicator_configure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def indicator_cget(self, entry: str, opt): ... + def indicator_exists(self, entry: str) -> bool: ... + def indicator_delete(self, entry: str) -> None: ... + def indicator_size(self, entry: str) -> int: ... + def info_anchor(self) -> str: ... + def info_bbox(self, entry: str) -> tuple[int, int, int, int]: ... + def info_children(self, entry: str | None = None) -> tuple[str, ...]: ... + def info_data(self, entry: str) -> Any: ... + def info_dragsite(self) -> str: ... + def info_dropsite(self) -> str: ... + def info_exists(self, entry: str) -> bool: ... + def info_hidden(self, entry: str) -> bool: ... + def info_next(self, entry: str) -> str: ... + def info_parent(self, entry: str) -> str: ... + def info_prev(self, entry: str) -> str: ... + def info_selection(self) -> tuple[str, ...]: ... + def item_cget(self, entry: str, col: int, opt): ... + def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def item_create(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ... + def item_exists(self, entry: str, col: int) -> bool: ... + def item_delete(self, entry: str, col: int) -> None: ... + def entrycget(self, entry: str, opt): ... + def entryconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def nearest(self, y: int) -> str: ... + def see(self, entry: str) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ... + def selection_includes(self, entry: str) -> bool: ... + def selection_set(self, first: str, last: str | None = None) -> None: ... + def show_entry(self, entry: str) -> None: ... + +class CheckList(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def autosetmode(self) -> None: ... + def close(self, entrypath: str) -> None: ... + def getmode(self, entrypath: str) -> str: ... + def open(self, entrypath: str) -> None: ... + def getselection(self, mode: str = "on") -> tuple[str, ...]: ... + def getstatus(self, entrypath: str) -> str: ... + def setstatus(self, entrypath: str, mode: str = "on") -> None: ... + +class Tree(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def autosetmode(self) -> None: ... + def close(self, entrypath: str) -> None: ... + def getmode(self, entrypath: str) -> str: ... + def open(self, entrypath: str) -> None: ... + def setmode(self, entrypath: str, mode: str = "none") -> None: ... + +class TList(TixWidget, tkinter.XView, tkinter.YView): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def active_set(self, index: int) -> None: ... + def active_clear(self) -> None: ... + def anchor_set(self, index: int) -> None: ... + def anchor_clear(self) -> None: ... + def delete(self, from_: int, to: int | None = None) -> None: ... + def dragsite_set(self, index: int) -> None: ... + def dragsite_clear(self) -> None: ... + def dropsite_set(self, index: int) -> None: ... + def dropsite_clear(self) -> None: ... + def insert(self, index: int, cnf: dict[str, Any] = {}, **kw) -> None: ... + def info_active(self) -> int: ... + def info_anchor(self) -> int: ... + def info_down(self, index: int) -> int: ... + def info_left(self, index: int) -> int: ... + def info_right(self, index: int) -> int: ... + def info_selection(self) -> tuple[int, ...]: ... + def info_size(self) -> int: ... + def info_up(self, index: int) -> int: ... + def nearest(self, x: int, y: int) -> int: ... + def see(self, index: int) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ... + def selection_includes(self, index: int) -> bool: ... + def selection_set(self, first: int, last: int | None = None) -> None: ... + +class PanedWindow(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def delete(self, name: str) -> None: ... + def forget(self, name: str) -> None: ... # type: ignore[override] + def panecget(self, entry: str, opt): ... + def paneconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ... + def panes(self) -> list[tkinter.Widget]: ... + +class ListNoteBook(TixWidget): + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def page(self, name: str) -> tkinter.Widget: ... + def pages(self) -> list[tkinter.Widget]: ... + def raise_page(self, name: str) -> None: ... + +class NoteBook(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ... + def delete(self, name: str) -> None: ... + def page(self, name: str) -> tkinter.Widget: ... + def pages(self) -> list[tkinter.Widget]: ... + def raise_page(self, name: str) -> None: ... + def raised(self) -> bool: ... + +class InputOnly(TixWidget): + def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ... + +class Form: + def __setitem__(self, key: str, value: Any) -> None: ... + def config(self, cnf: dict[str, Any] = {}, **kw) -> None: ... + def form(self, cnf: dict[str, Any] = {}, **kw) -> None: ... + def check(self) -> bool: ... + def forget(self) -> None: ... + def grid(self, xsize: int = 0, ysize: int = 0) -> tuple[int, int] | None: ... + def info(self, option: str | None = None): ... + def slaves(self) -> list[tkinter.Widget]: ... diff --git a/stdlib/tkinter/ttk.pyi b/stdlib/tkinter/ttk.pyi new file mode 100644 index 000000000000..06d2be13dc28 --- /dev/null +++ b/stdlib/tkinter/ttk.pyi @@ -0,0 +1,1434 @@ +import _tkinter +import sys +import tkinter +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable, Sequence +from tkinter.font import _FontDescription +from typing import Any, Literal, ParamSpec, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, Unpack + +__all__ = [ + "Button", + "Checkbutton", + "Combobox", + "Entry", + "Frame", + "Label", + "Labelframe", + "LabelFrame", + "Menubutton", + "Notebook", + "Panedwindow", + "PanedWindow", + "Progressbar", + "Radiobutton", + "Scale", + "Scrollbar", + "Separator", + "Sizegrip", + "Style", + "Treeview", + "LabeledScale", + "OptionMenu", + "tclobjs_to_py", + "setup_master", + "Spinbox", +] + +def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... +def setup_master(master: tkinter.Misc | None = None): ... + +_Padding: TypeAlias = ( + float + | str + | tuple[float | str] + | tuple[float | str, float | str] + | tuple[float | str, float | str, float | str] + | tuple[float | str, float | str, float | str, float | str] +) + +# Last item (option value to apply) varies between different options so use Any. +# It could also be any iterable with items matching the tuple, but that case +# hasn't been added here for consistency with _Padding above. +_Statespec: TypeAlias = tuple[Unpack[tuple[str, ...]], Any] +_ImageStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], tkinter._Image | str] +_VsapiStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], int] + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +@type_check_only +class _Layout(TypedDict, total=False): + side: Literal["left", "right", "top", "bottom"] + sticky: str # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty + unit: Literal[0, 1] | bool + children: _LayoutSpec + # Note: there seem to be some other undocumented keys sometimes + +# This could be any sequence when passed as a parameter but will always be a list when returned. +_LayoutSpec: TypeAlias = list[tuple[str, _Layout | None]] + +# Keep these in sync with the appropriate methods in Style +@type_check_only +class _ElementCreateImageKwargs(TypedDict, total=False): + border: _Padding + height: float | str + padding: _Padding + sticky: str + width: float | str + +_ElementCreateArgsCrossPlatform: TypeAlias = ( + # Could be any sequence here but types are not homogenous so just type it as tuple + tuple[Literal["image"], tkinter._Image | str, Unpack[tuple[_ImageStatespec, ...]], _ElementCreateImageKwargs] + | tuple[Literal["from"], str, str] + | tuple[Literal["from"], str] # (fromelement is optional) +) +if sys.platform == "win32" and sys.version_info >= (3, 13): + @type_check_only + class _ElementCreateVsapiKwargsPadding(TypedDict, total=False): + padding: _Padding + + @type_check_only + class _ElementCreateVsapiKwargsMargin(TypedDict, total=False): + padding: _Padding + + @type_check_only + class _ElementCreateVsapiKwargsSize(TypedDict): + width: float | str + height: float | str + + _ElementCreateVsapiKwargsDict: TypeAlias = ( + _ElementCreateVsapiKwargsPadding | _ElementCreateVsapiKwargsMargin | _ElementCreateVsapiKwargsSize + ) + _ElementCreateArgs: TypeAlias = ( # noqa: Y047 # It doesn't recognise the usage below for whatever reason + _ElementCreateArgsCrossPlatform + | tuple[Literal["vsapi"], str, int, _ElementCreateVsapiKwargsDict] + | tuple[Literal["vsapi"], str, int, _VsapiStatespec, _ElementCreateVsapiKwargsDict] + ) +else: + _ElementCreateArgs: TypeAlias = _ElementCreateArgsCrossPlatform +_ThemeSettingsValue = TypedDict( + "_ThemeSettingsValue", + { + "configure": dict[str, Any], + "map": dict[str, Iterable[_Statespec]], + "layout": _LayoutSpec, + "element create": _ElementCreateArgs, + }, + total=False, +) +_ThemeSettings: TypeAlias = dict[str, _ThemeSettingsValue] + +class Style: + master: tkinter.Misc + tk: _tkinter.TkappType + def __init__(self, master: tkinter.Misc | None = None) -> None: ... + + # For these methods, values given vary between options. Returned values + # seem to be str, but this might not always be the case. + @overload + def configure(self, style: str) -> dict[str, Any] | None: ... # Returns None if no configuration. + @overload + def configure(self, style: str, query_opt: str, **kw: Any) -> Any: ... + @overload + def configure(self, style: str, query_opt: None = None, **kw: Any) -> None: ... + + @overload + def map(self, style: str, query_opt: str) -> _Statespec: ... + @overload + def map(self, style: str, query_opt: None = None, **kw: Iterable[_Statespec]) -> dict[str, _Statespec]: ... + + def lookup(self, style: str, option: str, state: Iterable[str] | None = None, default: Any | None = None) -> Any: ... + + @overload + def layout(self, style: str, layoutspec: _LayoutSpec) -> list[Never]: ... # Always seems to return an empty list + @overload + def layout(self, style: str, layoutspec: None = None) -> _LayoutSpec: ... + + @overload + def element_create( + self, + elementname: str, + etype: Literal["image"], + default_image: tkinter._Image | str, + /, + *imagespec: _ImageStatespec, + border: _Padding = ..., + height: float | str = ..., + padding: _Padding = ..., + sticky: str = ..., + width: float | str = ..., + ) -> None: ... + @overload + def element_create(self, elementname: str, etype: Literal["from"], themename: str, fromelement: str = ..., /) -> None: ... + if sys.platform == "win32" and sys.version_info >= (3, 13): # and tk version >= 8.6 + # margin, padding, and (width + height) are mutually exclusive. width + # and height must either both be present or not present at all. Note: + # There are other undocumented options if you look at ttk's source code. + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + padding: _Padding = ..., + ) -> None: ... + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + margin: _Padding = ..., + ) -> None: ... + @overload + def element_create( + self, + elementname: str, + etype: Literal["vsapi"], + class_: str, + part: int, + vs_statespec: _VsapiStatespec = ..., + /, + *, + width: float | str, + height: float | str, + ) -> None: ... + + def element_names(self) -> tuple[str, ...]: ... + def element_options(self, elementname: str) -> tuple[str, ...]: ... + def theme_create(self, themename: str, parent: str | None = None, settings: _ThemeSettings | None = None) -> None: ... + def theme_settings(self, themename: str, settings: _ThemeSettings) -> None: ... + def theme_names(self) -> tuple[str, ...]: ... + + @overload + def theme_use(self, themename: str) -> None: ... + @overload + def theme_use(self, themename: None = None) -> str: ... + +class Widget(tkinter.Widget): + def __init__(self, master: tkinter.Misc | None, widgetname: str | None, kw: dict[str, Any] | None = None) -> None: ... + def identify(self, x: int, y: int) -> str: ... + + @overload + def instate(self, statespec: Sequence[str], callback: None = None) -> bool: ... + @overload + def instate( + self, statespec: Sequence[str], callback: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs + ) -> Literal[False] | _T: ... + + def state(self, statespec: Sequence[str] | None = None) -> tuple[str, ...]: ... + +class Button(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + default: Literal["normal", "active", "disabled"] = "normal", + image: tkinter._Image | str = "", + name: str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", + textvariable: tkinter.Variable = ..., + underline: int = -1, + width: int | Literal[""] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., + cursor: tkinter._Cursor = ..., + default: Literal["normal", "active", "disabled"] = ..., + image: tkinter._Image | str = ..., + padding=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: int | Literal[""] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def invoke(self) -> Any: ... + +class Checkbutton(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + image: tkinter._Image | str = "", + name: str = ..., + offvalue: Any = 0, + onvalue: Any = 1, + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", + textvariable: tkinter.Variable = ..., + underline: int = -1, + # Seems like variable can be empty string, but actually setting it to + # empty string segfaults before Tcl 8.6.9. Search for ttk::checkbutton + # here: https://sourceforge.net/projects/tcl/files/Tcl/8.6.9/tcltk-release-notes-8.6.9.txt/view + variable: tkinter.Variable = ..., + width: int | Literal[""] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._Image | str = ..., + offvalue: Any = ..., + onvalue: Any = ..., + padding=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + variable: tkinter.Variable = ..., + width: int | Literal[""] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def invoke(self) -> Any: ... + +class Entry(Widget, tkinter.Entry): + def __init__( + self, + master: tkinter.Misc | None = None, + widget: str | None = None, + *, + background: str = ..., # undocumented + class_: str = "", + cursor: tkinter._Cursor = ..., + exportselection: bool = True, + font: _FontDescription = "TkTextFont", + foreground: str = "", + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + justify: Literal["left", "center", "right"] = "left", + name: str = ..., + show: str = "", + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + show: str = ..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why) + @overload # type: ignore[override] + def config( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + show: str = ..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + def bbox(self, index) -> tuple[int, int, int, int]: ... # type: ignore[override] + def identify(self, x: int, y: int) -> str: ... + def validate(self): ... + +class Combobox(Entry): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + background: str = ..., # undocumented + class_: str = "", + cursor: tkinter._Cursor = "", + exportselection: bool = True, + font: _FontDescription = ..., # undocumented + foreground: str = ..., # undocumented + height: int = 10, + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., # undocumented + justify: Literal["left", "center", "right"] = "left", + name: str = ..., + postcommand: Callable[[], object] | str = "", + show=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., # undocumented + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., # undocumented + values: list[str] | tuple[str, ...] = ..., + width: int = 20, + xscrollcommand: str | Callable[[float, float], object] = ..., # undocumented + ) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: int = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + postcommand: Callable[[], object] | str = ..., + show=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why) + @overload # type: ignore[override] + def config( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + height: int = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + postcommand: Callable[[], object] | str = ..., + show=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., + width: int = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + def current(self, newindex: int | None = None) -> int: ... + def set(self, value: Any) -> None: ... + +class Frame(Widget): + # This should be kept in sync with tkinter.ttk.LabeledScale.__init__() + # (all of these keyword-only arguments are also present there) + def __init__( + self, + master: tkinter.Misc | None = None, + *, + border: float | str = ..., + borderwidth: float | str = ..., + class_: str = "", + cursor: tkinter._Cursor = "", + height: float | str = 0, + name: str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + border: float | str = ..., + borderwidth: float | str = ..., + cursor: tkinter._Cursor = ..., + height: float | str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Label(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = "", + border: float | str = ..., # alias for borderwidth + borderwidth: float | str = ..., # undocumented + class_: str = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + font: _FontDescription = ..., + foreground: str = "", + image: tkinter._Image | str = "", + justify: Literal["left", "center", "right"] = ..., + name: str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + textvariable: tkinter.Variable = ..., + underline: int = -1, + width: int | Literal[""] = "", + wraplength: float | str = ..., + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + background: str = ..., + border: float | str = ..., + borderwidth: float | str = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., + cursor: tkinter._Cursor = ..., + font: _FontDescription = ..., + foreground: str = ..., + image: tkinter._Image | str = ..., + justify: Literal["left", "center", "right"] = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: int | Literal[""] = ..., + wraplength: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Labelframe(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + border: float | str = ..., + borderwidth: float | str = ..., # undocumented + class_: str = "", + cursor: tkinter._Cursor = "", + height: float | str = 0, + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: tkinter.Misc = ..., + name: str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., # undocumented + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + text: float | str = "", + underline: int = -1, + width: float | str = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + border: float | str = ..., + borderwidth: float | str = ..., + cursor: tkinter._Cursor = ..., + height: float | str = ..., + labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., + labelwidget: tkinter.Misc = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + underline: int = ..., + width: float | str = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +LabelFrame = Labelframe + +class Menubutton(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + image: tkinter._Image | str = "", + menu: tkinter.Menu = ..., + name: str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", + textvariable: tkinter.Variable = ..., + underline: int = -1, + width: int | Literal[""] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., + cursor: tkinter._Cursor = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., + image: tkinter._Image | str = ..., + menu: tkinter.Menu = ..., + padding=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + width: int | Literal[""] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Notebook(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + cursor: tkinter._Cursor = "", + height: int = 0, + name: str = ..., + padding: _Padding = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = 0, + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + padding: _Padding = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def add( + self, + child: tkinter.Widget, + *, + state: Literal["normal", "disabled", "hidden"] = ..., + sticky: str = ..., # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty + padding: _Padding = ..., + text: str = ..., + # `image` is a sequence of an image name, followed by zero or more + # (sequences of one or more state names followed by an image name) + image=..., + compound: Literal["top", "left", "center", "right", "bottom", "none"] = ..., + underline: int = ..., + ) -> None: ... + def forget(self, tab_id) -> None: ... # type: ignore[override] + def hide(self, tab_id) -> None: ... + def identify(self, x: int, y: int) -> str: ... + def index(self, tab_id): ... + def insert(self, pos, child, **kw) -> None: ... + def select(self, tab_id=None): ... + def tab(self, tab_id, option=None, **kw): ... + def tabs(self): ... + def enable_traversal(self) -> None: ... + +class Panedwindow(Widget, tkinter.PanedWindow): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + cursor: tkinter._Cursor = "", + # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units + height: int = 0, + name: str = ..., + orient: Literal["vertical", "horizontal"] = "vertical", # can't be changed with configure() + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: int = 0, + ) -> None: ... + def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why) + @overload # type: ignore[override] + def config( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + height: int = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + width: int = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + forget = tkinter.PanedWindow.forget + def insert(self, pos, child, **kw) -> None: ... + def pane(self, pane, option=None, **kw): ... + def sashpos(self, index, newpos=None): ... + +PanedWindow = Panedwindow + +class Progressbar(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + cursor: tkinter._Cursor = "", + length: float | str = 100, + maximum: float = 100, + mode: Literal["determinate", "indeterminate"] = "determinate", + name: str = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + phase: int = 0, # docs say read-only but assigning int to this works + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + value: float = 0.0, + variable: tkinter.IntVar | tkinter.DoubleVar = ..., + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + length: float | str = ..., + maximum: float = ..., + mode: Literal["determinate", "indeterminate"] = ..., + orient: Literal["horizontal", "vertical"] = ..., + phase: int = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + value: float = ..., + variable: tkinter.IntVar | tkinter.DoubleVar = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def start(self, interval: Literal["idle"] | int | None = None) -> None: ... + def step(self, amount: float | None = None) -> None: ... + def stop(self) -> None: ... + +class Radiobutton(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + command: str | Callable[[], Any] = "", + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = "", + cursor: tkinter._Cursor = "", + image: tkinter._Image | str = "", + name: str = ..., + padding=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = "", + textvariable: tkinter.Variable = ..., + underline: int = -1, + value: Any = "1", + variable: tkinter.Variable | Literal[""] = ..., + width: int | Literal[""] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + command: str | Callable[[], Any] = ..., + compound: Literal["", "text", "image", "top", "left", "center", "right", "bottom", "none"] = ..., + cursor: tkinter._Cursor = ..., + image: tkinter._Image | str = ..., + padding=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + text: float | str = ..., + textvariable: tkinter.Variable = ..., + underline: int = ..., + value: Any = ..., + variable: tkinter.Variable | Literal[""] = ..., + width: int | Literal[""] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def invoke(self) -> Any: ... + +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scale(Widget, tkinter.Scale): # type: ignore[misc] + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + command: str | Callable[[str], object] = "", + cursor: tkinter._Cursor = "", + from_: float = 0, + length: float | str = 100, + name: str = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + state: str = ..., # undocumented + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + to: float = 1.0, + value: float = 0, + variable: tkinter.IntVar | tkinter.DoubleVar = ..., + ) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + command: str | Callable[[str], object] = ..., + cursor: tkinter._Cursor = ..., + from_: float = ..., + length: float | str = ..., + orient: Literal["horizontal", "vertical"] = ..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + to: float = ..., + value: float = ..., + variable: tkinter.IntVar | tkinter.DoubleVar = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why) + @overload # type: ignore[override] + def config( + self, + cnf: dict[str, Any] | None = None, + *, + command: str | Callable[[str], object] = ..., + cursor: tkinter._Cursor = ..., + from_: float = ..., + length: float | str = ..., + orient: Literal["horizontal", "vertical"] = ..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + to: float = ..., + value: float = ..., + variable: tkinter.IntVar | tkinter.DoubleVar = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + def get(self, x: int | None = None, y: int | None = None) -> float: ... + +# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible +class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + command: Callable[..., tuple[float, float] | None] | str = "", + cursor: tkinter._Cursor = "", + name: str = ..., + orient: Literal["horizontal", "vertical"] = "vertical", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + ) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + command: Callable[..., tuple[float, float] | None] | str = ..., + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why) + @overload # type: ignore[override] + def config( + self, + cnf: dict[str, Any] | None = None, + *, + command: Callable[..., tuple[float, float] | None] | str = ..., + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + +class Separator(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + cursor: tkinter._Cursor = "", + name: str = ..., + orient: Literal["horizontal", "vertical"] = "horizontal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + orient: Literal["horizontal", "vertical"] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Sizegrip(Widget): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + cursor: tkinter._Cursor = ..., + name: str = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + cursor: tkinter._Cursor = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + +class Spinbox(Entry): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + background: str = ..., # undocumented + class_: str = "", + command: Callable[[], object] | str | list[str] | tuple[str, ...] = "", + cursor: tkinter._Cursor = "", + exportselection: bool = ..., # undocumented + font: _FontDescription = ..., # undocumented + foreground: str = ..., # undocumented + format: str = "", + from_: float = 0, + increment: float = 1, + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., # undocumented + justify: Literal["left", "center", "right"] = ..., # undocumented + name: str = ..., + show=..., # undocumented + state: str = "normal", + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., # undocumented + to: float = 0, + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = "none", + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = "", + values: list[str] | tuple[str, ...] = ..., + width: int = ..., # undocumented + wrap: bool = False, + xscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload # type: ignore[override] + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + background: str = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., + cursor: tkinter._Cursor = ..., + exportselection: bool = ..., + font: _FontDescription = ..., + foreground: str = ..., + format: str = ..., + from_: float = ..., + increment: float = ..., + invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + justify: Literal["left", "center", "right"] = ..., + show=..., + state: str = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + textvariable: tkinter.Variable = ..., + to: float = ..., + validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., + validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ..., + values: list[str] | tuple[str, ...] = ..., + width: int = ..., + wrap: bool = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure # type: ignore[assignment] + def set(self, value: Any) -> None: ... + +@type_check_only +class _TreeviewItemDict(TypedDict): + text: str + image: list[str] | Literal[""] # no idea why it's wrapped in list + values: list[Any] | Literal[""] + open: bool # actually 0 or 1 + tags: list[str] | Literal[""] + +@type_check_only +class _TreeviewTagDict(TypedDict): + # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug + foreground: str + background: str + font: _FontDescription + image: str # not wrapped in list :D + +@type_check_only +class _TreeviewHeaderDict(TypedDict): + text: str + image: list[str] | Literal[""] + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] + command: str + state: str # Doesn't seem to appear anywhere else than in these dicts + +@type_check_only +class _TreeviewColumnDict(TypedDict): + width: int + minwidth: int + stretch: bool # actually 0 or 1 + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] + id: str + +class Treeview(Widget, tkinter.XView, tkinter.YView): + def __init__( + self, + master: tkinter.Misc | None = None, + *, + class_: str = "", + columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = "", + cursor: tkinter._Cursor = "", + displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ("#all",), + height: int = 10, + name: str = ..., + padding: _Padding = ..., + selectmode: Literal["extended", "browse", "none"] = "extended", + # list/tuple of Literal don't actually work in mypy + # + # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be + # surprised if someone is using it. + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ("tree", "headings"), + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + xscrollcommand: str | Callable[[float, float], object] = "", + yscrollcommand: str | Callable[[float, float], object] = "", + ) -> None: ... + + @overload + def configure( + self, + cnf: dict[str, Any] | None = None, + *, + columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = ..., + cursor: tkinter._Cursor = ..., + displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ..., + height: int = ..., + padding: _Padding = ..., + selectmode: Literal["extended", "browse", "none"] = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., + style: str = ..., + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., + xscrollcommand: str | Callable[[float, float], object] = ..., + yscrollcommand: str | Callable[[float, float], object] = ..., + ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... + @overload + def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + + config = configure + def bbox(self, item: str | int, column: str | int | None = None) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore[override] + def get_children(self, item: str | int | None = None) -> tuple[str, ...]: ... + def set_children(self, item: str | int, *newchildren: str | int) -> None: ... + + @overload + def column(self, column: str | int, option: Literal["width", "minwidth"]) -> int: ... + @overload + def column(self, column: str | int, option: Literal["stretch"]) -> bool: ... # actually 0 or 1 + @overload + def column(self, column: str | int, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + @overload + def column(self, column: str | int, option: Literal["id"]) -> str: ... + @overload + def column(self, column: str | int, option: str) -> Any: ... + @overload + def column( + self, + column: str | int, + option: None = None, + *, + width: int = ..., + minwidth: int = ..., + stretch: bool = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + # id is read-only + ) -> _TreeviewColumnDict | None: ... + + def delete(self, *items: str | int) -> None: ... + def detach(self, *items: str | int) -> None: ... + def exists(self, item: str | int) -> bool: ... + + @overload # type: ignore[override] + def focus(self, item: None = None) -> str: ... # can return empty string + @overload + def focus(self, item: str | int) -> Literal[""]: ... + + @overload + def heading(self, column: str | int, option: Literal["text"]) -> str: ... + @overload + def heading(self, column: str | int, option: Literal["image"]) -> tuple[str] | str: ... + @overload + def heading(self, column: str | int, option: Literal["anchor"]) -> _tkinter.Tcl_Obj: ... + @overload + def heading(self, column: str | int, option: Literal["command"]) -> str: ... + @overload + def heading(self, column: str | int, option: str) -> Any: ... + @overload + def heading(self, column: str | int, option: None = None) -> _TreeviewHeaderDict: ... + @overload + def heading( + self, + column: str | int, + option: None = None, + *, + text: str = ..., + image: tkinter._Image | str = ..., + anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., + command: str | Callable[[], object] = ..., + ) -> None: ... + + # Internal Method. Leave untyped: + def identify(self, component, x, y): ... # type: ignore[override] + def identify_row(self, y: int) -> str: ... + def identify_column(self, x: int) -> str: ... + def identify_region(self, x: int, y: int) -> Literal["heading", "separator", "tree", "cell", "nothing"]: ... + def identify_element(self, x: int, y: int) -> str: ... # don't know what possible return values are + def index(self, item: str | int) -> int: ... + def insert( + self, + parent: str, + index: int | Literal["end"], + iid: str | int | None = None, + *, + id: str | int = ..., # same as iid + text: str = ..., + image: tkinter._Image | str = ..., + values: list[Any] | tuple[Any, ...] = ..., + open: bool = ..., + tags: str | list[str] | tuple[str, ...] = ..., + ) -> str: ... + + @overload + def item(self, item: str | int, option: Literal["text"]) -> str: ... + @overload + def item(self, item: str | int, option: Literal["image"]) -> tuple[str] | Literal[""]: ... + @overload + def item(self, item: str | int, option: Literal["values"]) -> tuple[Any, ...] | Literal[""]: ... + @overload + def item(self, item: str | int, option: Literal["open"]) -> bool: ... # actually 0 or 1 + @overload + def item(self, item: str | int, option: Literal["tags"]) -> tuple[str, ...] | Literal[""]: ... + @overload + def item(self, item: str | int, option: str) -> Any: ... + @overload + def item(self, item: str | int, option: None = None) -> _TreeviewItemDict: ... + @overload + def item( + self, + item: str | int, + option: None = None, + *, + text: str = ..., + image: tkinter._Image | str = ..., + values: list[Any] | tuple[Any, ...] | Literal[""] = ..., + open: bool = ..., + tags: str | list[str] | tuple[str, ...] = ..., + ) -> None: ... + + def move(self, item: str | int, parent: str, index: int | Literal["end"]) -> None: ... + reattach = move + def next(self, item: str | int) -> str: ... # returning empty string means last item + def parent(self, item: str | int) -> str: ... + def prev(self, item: str | int) -> str: ... # returning empty string means first item + def see(self, item: str | int) -> None: ... + def selection(self) -> tuple[str, ...]: ... + + @overload + def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_set(self, *items: str | int) -> None: ... + + @overload + def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_add(self, *items: str | int) -> None: ... + + @overload + def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_remove(self, *items: str | int) -> None: ... + + @overload + def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... + @overload + def selection_toggle(self, *items: str | int) -> None: ... + + @overload + def set(self, item: str | int, column: None = None, value: None = None) -> dict[str, Any]: ... + @overload + def set(self, item: str | int, column: str | int, value: None = None) -> Any: ... + @overload + def set(self, item: str | int, column: str | int, value: Any) -> Literal[""]: ... + + # There's no tag_unbind() or 'add' argument for whatever reason. + # Also, it's 'callback' instead of 'func' here. + @overload + def tag_bind( + self, tagname: str, sequence: str | None = None, callback: Callable[[tkinter.Event[Treeview]], object] | None = None + ) -> str: ... + @overload + def tag_bind(self, tagname: str, sequence: str | None, callback: str) -> None: ... + @overload + def tag_bind(self, tagname: str, *, callback: str) -> None: ... + + @overload + def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> str: ... + @overload + def tag_configure(self, tagname: str, option: Literal["font"]) -> _FontDescription: ... + @overload + def tag_configure(self, tagname: str, option: Literal["image"]) -> str: ... + @overload + def tag_configure( + self, + tagname: str, + option: None = None, + *, + # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug + foreground: str = ..., + background: str = ..., + font: _FontDescription = ..., + image: tkinter._Image | str = ..., + ) -> _TreeviewTagDict | MaybeNone: ... # can be None but annoying to check + + @overload + def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: ... + @overload + def tag_has(self, tagname: str, item: str | int) -> bool: ... + +class LabeledScale(Frame): + label: Label + scale: Scale + # This should be kept in sync with tkinter.ttk.Frame.__init__() + # (all the keyword-only args except compound are from there) + def __init__( + self, + master: tkinter.Misc | None = None, + variable: tkinter.IntVar | tkinter.DoubleVar | None = None, + from_: float = 0, + to: float = 10, + *, + border: float | str = ..., + borderwidth: float | str = ..., + class_: str = "", + compound: Literal["top", "bottom"] = "top", + cursor: tkinter._Cursor = "", + height: float | str = 0, + name: str = ..., + padding: _Padding = ..., + relief: Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] = ..., + style: str = "", + takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", + width: float | str = 0, + ) -> None: ... + # destroy is overridden, signature does not change + value: Any + +class OptionMenu(Menubutton): + if sys.version_info >= (3, 14): + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + name: str | None = None, + ) -> None: ... + else: + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + ) -> None: ... + # configure, config, cget, destroy are inherited from Menubutton + # destroy and __setitem__ are overridden, signature does not change + def set_menu(self, default: str | None = None, *values: str) -> None: ... diff --git a/stdlib/token.pyi b/stdlib/token.pyi new file mode 100644 index 000000000000..23b43250d60f --- /dev/null +++ b/stdlib/token.pyi @@ -0,0 +1,166 @@ +import sys +from typing import Final + +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COLONEQUAL", + "COMMA", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "SOFT_KEYWORD", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", + "VBAR", + "VBAREQUAL", + "tok_name", + "ENCODING", + "NL", + "COMMENT", +] +if sys.version_info < (3, 13): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 12): + __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] + +if sys.version_info >= (3, 14): + __all__ += ["TSTRING_START", "TSTRING_MIDDLE", "TSTRING_END"] + +ENDMARKER: Final[int] +NAME: Final[int] +NUMBER: Final[int] +STRING: Final[int] +NEWLINE: Final[int] +INDENT: Final[int] +DEDENT: Final[int] +LPAR: Final[int] +RPAR: Final[int] +LSQB: Final[int] +RSQB: Final[int] +COLON: Final[int] +COMMA: Final[int] +SEMI: Final[int] +PLUS: Final[int] +MINUS: Final[int] +STAR: Final[int] +SLASH: Final[int] +VBAR: Final[int] +AMPER: Final[int] +LESS: Final[int] +GREATER: Final[int] +EQUAL: Final[int] +DOT: Final[int] +PERCENT: Final[int] +LBRACE: Final[int] +RBRACE: Final[int] +EQEQUAL: Final[int] +NOTEQUAL: Final[int] +LESSEQUAL: Final[int] +GREATEREQUAL: Final[int] +TILDE: Final[int] +CIRCUMFLEX: Final[int] +LEFTSHIFT: Final[int] +RIGHTSHIFT: Final[int] +DOUBLESTAR: Final[int] +PLUSEQUAL: Final[int] +MINEQUAL: Final[int] +STAREQUAL: Final[int] +SLASHEQUAL: Final[int] +PERCENTEQUAL: Final[int] +AMPEREQUAL: Final[int] +VBAREQUAL: Final[int] +CIRCUMFLEXEQUAL: Final[int] +LEFTSHIFTEQUAL: Final[int] +RIGHTSHIFTEQUAL: Final[int] +DOUBLESTAREQUAL: Final[int] +DOUBLESLASH: Final[int] +DOUBLESLASHEQUAL: Final[int] +AT: Final[int] +RARROW: Final[int] +ELLIPSIS: Final[int] +ATEQUAL: Final[int] +if sys.version_info < (3, 13): + AWAIT: Final[int] + ASYNC: Final[int] +OP: Final[int] +ERRORTOKEN: Final[int] +N_TOKENS: Final[int] +NT_OFFSET: Final[int] +tok_name: Final[dict[int, str]] +COMMENT: Final[int] +NL: Final[int] +ENCODING: Final[int] +TYPE_COMMENT: Final[int] +TYPE_IGNORE: Final[int] +COLONEQUAL: Final[int] +EXACT_TOKEN_TYPES: Final[dict[str, int]] +SOFT_KEYWORD: Final[int] + +if sys.version_info >= (3, 12): + EXCLAMATION: Final[int] + FSTRING_END: Final[int] + FSTRING_MIDDLE: Final[int] + FSTRING_START: Final[int] + +if sys.version_info >= (3, 14): + TSTRING_START: Final[int] + TSTRING_MIDDLE: Final[int] + TSTRING_END: Final[int] + +def ISTERMINAL(x: int) -> bool: ... +def ISNONTERMINAL(x: int) -> bool: ... +def ISEOF(x: int) -> bool: ... diff --git a/stdlib/tokenize.pyi b/stdlib/tokenize.pyi new file mode 100644 index 000000000000..0aa3947a178d --- /dev/null +++ b/stdlib/tokenize.pyi @@ -0,0 +1,201 @@ +import sys +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Generator, Iterable, Sequence +from re import Pattern +from token import * +from typing import Any, Final, NamedTuple, TextIO, TypeAlias, type_check_only +from typing_extensions import disjoint_base + +if sys.version_info < (3, 12): + # Avoid double assignment to Final name by imports, which pyright objects to. + # EXACT_TOKEN_TYPES is already defined by 'from token import *' above + # in Python 3.12+. + from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES + +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COLONEQUAL", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENCODING", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "SOFT_KEYWORD", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "TYPE_COMMENT", + "TYPE_IGNORE", + "TokenInfo", + "VBAR", + "VBAREQUAL", + "detect_encoding", + "generate_tokens", + "tok_name", + "tokenize", + "untokenize", +] +if sys.version_info < (3, 13): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 12): + __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] + +if sys.version_info >= (3, 13): + __all__ += ["TokenError", "open"] + +if sys.version_info >= (3, 14): + __all__ += ["TSTRING_START", "TSTRING_MIDDLE", "TSTRING_END"] + +cookie_re: Final[Pattern[str]] +blank_re: Final[Pattern[bytes]] + +_Position: TypeAlias = tuple[int, int] + +# This class is not exposed. It calls itself tokenize.TokenInfo. +@type_check_only +class _TokenInfo(NamedTuple): + type: int + string: str + start: _Position + end: _Position + line: str + +if sys.version_info >= (3, 12): + class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... + +else: + @disjoint_base + class TokenInfo(_TokenInfo): + @property + def exact_type(self) -> int: ... + +# Backwards compatible tokens can be sequences of a shorter length too +_Token: TypeAlias = TokenInfo | Sequence[int | str | _Position] + +class TokenError(Exception): ... + +if sys.version_info < (3, 13): + class StopTokenizing(Exception): ... # undocumented + +class Untokenizer: + tokens: list[str] + prev_row: int + prev_col: int + encoding: str | None + def add_whitespace(self, start: _Position) -> None: ... + if sys.version_info >= (3, 12): + def add_backslash_continuation(self, start: _Position) -> None: ... + + def untokenize(self, iterable: Iterable[_Token]) -> str: ... + def compat(self, token: Sequence[int | str], iterable: Iterable[_Token]) -> None: ... + if sys.version_info >= (3, 12): + def escape_brackets(self, token: str) -> str: ... + +# Returns str, unless the ENCODING token is present, in which case it returns bytes. +def untokenize(iterable: Iterable[_Token]) -> str | Any: ... +def detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Sequence[bytes]]: ... +def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo]: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo]: ... +def open(filename: FileDescriptorOrPath) -> TextIO: ... +def group(*choices: str) -> str: ... # undocumented +def any(*choices: str) -> str: ... # undocumented +def maybe(*choices: str) -> str: ... # undocumented + +Whitespace: Final[str] # undocumented +Comment: Final[str] # undocumented +Ignore: Final[str] # undocumented +Name: Final[str] # undocumented + +Hexnumber: Final[str] # undocumented +Binnumber: Final[str] # undocumented +Octnumber: Final[str] # undocumented +Decnumber: Final[str] # undocumented +Intnumber: Final[str] # undocumented +Exponent: Final[str] # undocumented +Pointfloat: Final[str] # undocumented +Expfloat: Final[str] # undocumented +Floatnumber: Final[str] # undocumented +Imagnumber: Final[str] # undocumented +Number: Final[str] # undocumented + +def _all_string_prefixes() -> set[str]: ... # undocumented + +StringPrefix: Final[str] # undocumented + +Single: Final[str] # undocumented +Double: Final[str] # undocumented +Single3: Final[str] # undocumented +Double3: Final[str] # undocumented +Triple: Final[str] # undocumented +String: Final[str] # undocumented + +Special: Final[str] # undocumented +Funny: Final[str] # undocumented + +PlainToken: Final[str] # undocumented +Token: Final[str] # undocumented + +ContStr: Final[str] # undocumented +PseudoExtras: Final[str] # undocumented +PseudoToken: Final[str] # undocumented + +endpats: Final[dict[str, str]] # undocumented +single_quoted: Final[set[str]] # undocumented +triple_quoted: Final[set[str]] # undocumented + +tabsize: Final = 8 # undocumented diff --git a/stdlib/tomllib.pyi b/stdlib/tomllib.pyi new file mode 100644 index 000000000000..7f6df1d9380c --- /dev/null +++ b/stdlib/tomllib.pyi @@ -0,0 +1,27 @@ +import sys +from _typeshed import SupportsRead +from collections.abc import Callable +from typing import Any, overload +from typing_extensions import deprecated + +__all__ = ("loads", "load", "TOMLDecodeError") + +if sys.version_info >= (3, 14): + class TOMLDecodeError(ValueError): + msg: str + doc: str + pos: int + lineno: int + colno: int + + @overload + def __init__(self, msg: str, doc: str, pos: int) -> None: ... + @overload + @deprecated("Deprecated since Python 3.14. Set the 'msg', 'doc' and 'pos' arguments only.") + def __init__(self, msg: str | type = ..., doc: str | type = ..., pos: int | type = ..., *args: Any) -> None: ... + +else: + class TOMLDecodeError(ValueError): ... + +def load(fp: SupportsRead[bytes], /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... +def loads(s: str, /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ... diff --git a/stdlib/trace.pyi b/stdlib/trace.pyi new file mode 100644 index 000000000000..708233efe3e6 --- /dev/null +++ b/stdlib/trace.pyi @@ -0,0 +1,85 @@ +import sys +import types +from _typeshed import Incomplete, StrPath, TraceFunction +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ParamSpec, TypeAlias, TypeVar + +__all__ = ["Trace", "CoverageResults"] + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_FileModuleFunction: TypeAlias = tuple[str, str | None, str] + +class CoverageResults: + counts: dict[tuple[str, int], int] + counter: dict[tuple[str, int], int] + calledfuncs: dict[_FileModuleFunction, int] + callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int] + inifile: StrPath | None + outfile: StrPath | None + def __init__( + self, + counts: dict[tuple[str, int], int] | None = None, + calledfuncs: dict[_FileModuleFunction, int] | None = None, + infile: StrPath | None = None, + callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int] | None = None, + outfile: StrPath | None = None, + ) -> None: ... # undocumented + def update(self, other: CoverageResults) -> None: ... + if sys.version_info >= (3, 13): + def write_results( + self, + show_missing: bool = True, + summary: bool = False, + coverdir: StrPath | None = None, + *, + ignore_missing_files: bool = False, + ) -> None: ... + else: + def write_results(self, show_missing: bool = True, summary: bool = False, coverdir: StrPath | None = None) -> None: ... + + def write_results_file( + self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = None + ) -> tuple[int, int]: ... + def is_ignored_filename(self, filename: str) -> bool: ... # undocumented + +class _Ignore: + def __init__(self, modules: Iterable[str] | None = None, dirs: Iterable[StrPath] | None = None) -> None: ... + def names(self, filename: str, modulename: str) -> int: ... + +class Trace: + inifile: StrPath | None + outfile: StrPath | None + ignore: _Ignore + counts: dict[str, int] + pathtobasename: dict[Incomplete, Incomplete] + donothing: int + trace: int + start_time: int | None + globaltrace: TraceFunction + localtrace: TraceFunction + def __init__( + self, + count: int = 1, + trace: int = 1, + countfuncs: int = 0, + countcallers: int = 0, + ignoremods: Sequence[str] = (), + ignoredirs: Sequence[str] = (), + infile: StrPath | None = None, + outfile: StrPath | None = None, + timing: bool = False, + ) -> None: ... + def run(self, cmd: str | types.CodeType) -> None: ... + def runctx( + self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = None, locals: Mapping[str, Any] | None = None + ) -> None: ... + def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... + def file_module_function_of(self, frame: types.FrameType) -> _FileModuleFunction: ... + def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... + def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... + def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... + def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ... + def results(self) -> CoverageResults: ... diff --git a/stdlib/traceback.pyi b/stdlib/traceback.pyi new file mode 100644 index 000000000000..e5b410afdcbc --- /dev/null +++ b/stdlib/traceback.pyi @@ -0,0 +1,293 @@ +import sys +from _typeshed import SupportsWrite, Unused +from collections.abc import Generator, Iterable, Iterator, Mapping +from types import FrameType, TracebackType +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, overload +from typing_extensions import Self, deprecated + +__all__ = [ + "extract_stack", + "extract_tb", + "format_exception", + "format_exception_only", + "format_list", + "format_stack", + "format_tb", + "print_exc", + "format_exc", + "print_exception", + "print_last", + "print_stack", + "print_tb", + "clear_frames", + "FrameSummary", + "StackSummary", + "TracebackException", + "walk_stack", + "walk_tb", +] + +if sys.version_info >= (3, 14): + __all__ += ["print_list"] + +_FrameSummaryTuple: TypeAlias = tuple[str, int, str, str | None] + +def print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ... + +@overload +def print_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + file: SupportsWrite[str] | None = None, + chain: bool = True, +) -> None: ... +@overload +def print_exception( + exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True +) -> None: ... + +@overload +def format_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + chain: bool = True, +) -> list[str]: ... +@overload +def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ... + +def print_exc(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... +def print_last(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... +def print_stack(f: FrameType | None = None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ... +def extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: ... +def extract_stack(f: FrameType | None = None, limit: int | None = None) -> StackSummary: ... +def format_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> list[str]: ... +def print_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple], file: SupportsWrite[str] | None = None) -> None: ... + +if sys.version_info >= (3, 13): + @overload + def format_exception_only(exc: BaseException | None, /, *, show_group: bool = False) -> list[str]: ... + @overload + def format_exception_only(exc: Unused, /, value: BaseException | None, *, show_group: bool = False) -> list[str]: ... +else: + @overload + def format_exception_only(exc: BaseException | None, /) -> list[str]: ... + @overload + def format_exception_only(exc: Unused, /, value: BaseException | None) -> list[str]: ... + +def format_exc(limit: int | None = None, chain: bool = True) -> str: ... +def format_tb(tb: TracebackType | None, limit: int | None = None) -> list[str]: ... +def format_stack(f: FrameType | None = None, limit: int | None = None) -> list[str]: ... +def clear_frames(tb: TracebackType | None) -> None: ... +def walk_stack(f: FrameType | None) -> Iterator[tuple[FrameType, int]]: ... +def walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: ... + +if sys.version_info >= (3, 11): + class _ExceptionPrintContext: + def indent(self) -> str: ... + def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str]: ... + +class TracebackException: + __cause__: TracebackException | None + __context__: TracebackException | None + if sys.version_info >= (3, 11): + exceptions: list[TracebackException] | None + __suppress_context__: bool + if sys.version_info >= (3, 11): + __notes__: list[str] | None + stack: StackSummary + + # These fields only exist for `SyntaxError`s, but there is no way to express that in the type system. + filename: str + lineno: str | None + end_lineno: str | None + text: str + offset: int + end_offset: int | None + msg: str + + if sys.version_info >= (3, 13): + @property + def exc_type_str(self) -> str: ... + @property + @deprecated("Deprecated since Python 3.13. Use `exc_type_str` instead.") + def exc_type(self) -> type[BaseException] | None: ... + else: + exc_type: type[BaseException] + if sys.version_info >= (3, 13): + def __init__( + self, + exc_type: type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType | None, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + save_exc_type: bool = True, + _seen: set[int] | None = None, + ) -> None: ... + elif sys.version_info >= (3, 11): + def __init__( + self, + exc_type: type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType | None, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + _seen: set[int] | None = None, + ) -> None: ... + else: + def __init__( + self, + exc_type: type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType | None, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + _seen: set[int] | None = None, + ) -> None: ... + + if sys.version_info >= (3, 11): + @classmethod + def from_exception( + cls, + exc: BaseException, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + max_group_width: int = 15, + max_group_depth: int = 10, + ) -> Self: ... + else: + @classmethod + def from_exception( + cls, + exc: BaseException, + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + compact: bool = False, + ) -> Self: ... + + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 11): + def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str]: ... + else: + def format(self, *, chain: bool = True) -> Generator[str]: ... + + if sys.version_info >= (3, 13): + def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str]: ... + else: + def format_exception_only(self) -> Generator[str]: ... + + if sys.version_info >= (3, 11): + def print(self, *, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... + +class FrameSummary: + if sys.version_info >= (3, 13): + __slots__ = ( + "filename", + "lineno", + "end_lineno", + "colno", + "end_colno", + "name", + "_lines", + "_lines_dedented", + "locals", + "_code", + ) + elif sys.version_info >= (3, 11): + __slots__ = ("filename", "lineno", "end_lineno", "colno", "end_colno", "name", "_line", "locals") + else: + __slots__ = ("filename", "lineno", "name", "_line", "locals") + if sys.version_info >= (3, 11): + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = True, + locals: Mapping[str, str] | None = None, + line: str | None = None, + end_lineno: int | None = None, + colno: int | None = None, + end_colno: int | None = None, + ) -> None: ... + end_lineno: int | None + colno: int | None + end_colno: int | None + else: + def __init__( + self, + filename: str, + lineno: int | None, + name: str, + *, + lookup_line: bool = True, + locals: Mapping[str, str] | None = None, + line: str | None = None, + ) -> None: ... + filename: str + lineno: int | None + name: str + locals: dict[str, str] | None + @property + def line(self) -> str | None: ... + + @overload + def __getitem__(self, pos: Literal[0]) -> str: ... + @overload + def __getitem__(self, pos: Literal[1]) -> int: ... + @overload + def __getitem__(self, pos: Literal[2]) -> str: ... + @overload + def __getitem__(self, pos: Literal[3]) -> str | None: ... + @overload + def __getitem__(self, pos: SupportsIndex) -> Any: ... + @overload + def __getitem__(self, pos: slice[SupportsIndex | None]) -> tuple[Any, ...]: ... + + def __iter__(self) -> Iterator[Any]: ... + def __eq__(self, other: object) -> bool: ... + def __len__(self) -> Literal[4]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +class StackSummary(list[FrameSummary]): + @classmethod + def extract( + cls, + frame_gen: Iterable[tuple[FrameType, int]], + *, + limit: int | None = None, + lookup_lines: bool = True, + capture_locals: bool = False, + ) -> StackSummary: ... + @classmethod + def from_list(cls, a_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> StackSummary: ... + if sys.version_info >= (3, 11): + def format_frame_summary(self, frame_summary: FrameSummary) -> str: ... + + def format(self) -> list[str]: ... diff --git a/stdlib/tracemalloc.pyi b/stdlib/tracemalloc.pyi new file mode 100644 index 000000000000..e56aa19240fd --- /dev/null +++ b/stdlib/tracemalloc.pyi @@ -0,0 +1,123 @@ +import sys +from _tracemalloc import * +from collections.abc import Sequence +from typing import Any, SupportsIndex, TypeAlias, overload + +def get_object_traceback(obj: object) -> Traceback | None: ... +def take_snapshot() -> Snapshot: ... + +class BaseFilter: + inclusive: bool + def __init__(self, inclusive: bool) -> None: ... + +class DomainFilter(BaseFilter): + @property + def domain(self) -> int: ... + def __init__(self, inclusive: bool, domain: int) -> None: ... + +class Filter(BaseFilter): + domain: int | None + lineno: int | None + @property + def filename_pattern(self) -> str: ... + all_frames: bool + def __init__( + self, + inclusive: bool, + filename_pattern: str, + lineno: int | None = None, + all_frames: bool = False, + domain: int | None = None, + ) -> None: ... + +class Statistic: + __slots__ = ("traceback", "size", "count") + count: int + size: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, count: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class StatisticDiff: + __slots__ = ("traceback", "size", "size_diff", "count", "count_diff") + count: int + count_diff: int + size: int + size_diff: int + traceback: Traceback + def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +_FrameTuple: TypeAlias = tuple[str, int] + +class Frame: + __slots__ = ("_frame",) + @property + def filename(self) -> str: ... + @property + def lineno(self) -> int: ... + def __init__(self, frame: _FrameTuple) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Frame) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Frame) -> bool: ... + def __ge__(self, other: Frame) -> bool: ... + def __le__(self, other: Frame) -> bool: ... + else: + def __gt__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... + +_TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] + +class Trace: + __slots__ = ("_trace",) + @property + def domain(self) -> int: ... + @property + def size(self) -> int: ... + @property + def traceback(self) -> Traceback: ... + def __init__(self, trace: _TraceTuple) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class Traceback(Sequence[Frame]): + __slots__ = ("_frames", "_total_nframe") + @property + def total_nframe(self) -> int | None: ... + def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ... + def format(self, limit: int | None = None, most_recent_first: bool = False) -> list[str]: ... + + @overload + def __getitem__(self, index: SupportsIndex) -> Frame: ... + @overload + def __getitem__(self, index: slice[SupportsIndex | None]) -> Sequence[Frame]: ... + + def __contains__(self, frame: Frame) -> bool: ... # type: ignore[override] + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Traceback) -> bool: ... + if sys.version_info >= (3, 11): + def __gt__(self, other: Traceback) -> bool: ... + def __ge__(self, other: Traceback) -> bool: ... + def __le__(self, other: Traceback) -> bool: ... + else: + def __gt__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __ge__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + def __le__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ... + +class Snapshot: + def __init__(self, traces: Sequence[_TraceTuple], traceback_limit: int) -> None: ... + def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = False) -> list[StatisticDiff]: ... + def dump(self, filename: str) -> None: ... + def filter_traces(self, filters: Sequence[DomainFilter | Filter]) -> Snapshot: ... + @staticmethod + def load(filename: str) -> Snapshot: ... + def statistics(self, key_type: str, cumulative: bool = False) -> list[Statistic]: ... + traceback_limit: int + traces: Sequence[Trace] diff --git a/stdlib/tty.pyi b/stdlib/tty.pyi new file mode 100644 index 000000000000..a0478335a3f3 --- /dev/null +++ b/stdlib/tty.pyi @@ -0,0 +1,29 @@ +import sys +import termios +from typing import IO, Final, TypeAlias + +if sys.platform != "win32": + __all__ = ["setraw", "setcbreak"] + if sys.version_info >= (3, 12): + __all__ += ["cfmakeraw", "cfmakecbreak"] + + _ModeSetterReturn: TypeAlias = termios._AttrReturn + else: + _ModeSetterReturn: TypeAlias = None + + _FD: TypeAlias = int | IO[str] + + # XXX: Undocumented integer constants + IFLAG: Final = 0 + OFLAG: Final = 1 + CFLAG: Final = 2 + LFLAG: Final = 3 + ISPEED: Final = 4 + OSPEED: Final = 5 + CC: Final = 6 + def setraw(fd: _FD, when: int = 2) -> _ModeSetterReturn: ... + def setcbreak(fd: _FD, when: int = 2) -> _ModeSetterReturn: ... + + if sys.version_info >= (3, 12): + def cfmakeraw(mode: termios._Attr) -> None: ... + def cfmakecbreak(mode: termios._Attr) -> None: ... diff --git a/stdlib/turtle.pyi b/stdlib/turtle.pyi new file mode 100644 index 000000000000..1152e9603335 --- /dev/null +++ b/stdlib/turtle.pyi @@ -0,0 +1,856 @@ +import sys +from _typeshed import StrPath +from collections.abc import Callable, Generator, Sequence +from contextlib import contextmanager +from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base + +__all__ = [ + "ScrolledCanvas", + "TurtleScreen", + "Screen", + "RawTurtle", + "Turtle", + "RawPen", + "Pen", + "Shape", + "Vec2D", + "addshape", + "bgcolor", + "bgpic", + "bye", + "clearscreen", + "colormode", + "delay", + "exitonclick", + "getcanvas", + "getshapes", + "listen", + "mainloop", + "mode", + "numinput", + "onkey", + "onkeypress", + "onkeyrelease", + "onscreenclick", + "ontimer", + "register_shape", + "resetscreen", + "screensize", + "setup", + "setworldcoordinates", + "textinput", + "title", + "tracer", + "turtles", + "update", + "window_height", + "window_width", + "back", + "backward", + "begin_fill", + "begin_poly", + "bk", + "circle", + "clear", + "clearstamp", + "clearstamps", + "clone", + "color", + "degrees", + "distance", + "dot", + "down", + "end_fill", + "end_poly", + "fd", + "fillcolor", + "filling", + "forward", + "get_poly", + "getpen", + "getscreen", + "get_shapepoly", + "getturtle", + "goto", + "heading", + "hideturtle", + "home", + "ht", + "isdown", + "isvisible", + "left", + "lt", + "onclick", + "ondrag", + "onrelease", + "pd", + "pen", + "pencolor", + "pendown", + "pensize", + "penup", + "pos", + "position", + "pu", + "radians", + "right", + "reset", + "resizemode", + "rt", + "seth", + "setheading", + "setpos", + "setposition", + "setundobuffer", + "setx", + "sety", + "shape", + "shapesize", + "shapetransform", + "shearfactor", + "showturtle", + "speed", + "st", + "stamp", + "tilt", + "tiltangle", + "towards", + "turtlesize", + "undo", + "undobufferentries", + "up", + "width", + "write", + "xcor", + "ycor", + "write_docstringdict", + "done", + "Terminator", +] + +if sys.version_info >= (3, 14): + __all__ += ["fill", "no_animation", "poly", "save"] + +if sys.version_info >= (3, 12): + __all__ += ["teleport"] + +if sys.version_info < (3, 13): + __all__ += ["settiltangle"] + +# Note: '_Color' is the alias we use for arguments and _AnyColor is the +# alias we use for return types. Really, these two aliases should be the +# same, but as per the "no union returns" typeshed policy, we'll return +# Any instead. +_Color: TypeAlias = str | tuple[float, float, float] +_AnyColor: TypeAlias = Any + +@type_check_only +class _PenState(TypedDict): + shown: bool + pendown: bool + pencolor: _Color + fillcolor: _Color + pensize: int + speed: int + resizemode: Literal["auto", "user", "noresize"] + stretchfactor: tuple[float, float] + shearfactor: float + outline: int + tilt: float + +_Speed: TypeAlias = str | float +_PolygonCoords: TypeAlias = Sequence[tuple[float, float]] + +if sys.version_info >= (3, 12): + class Vec2D(tuple[float, float]): + def __new__(cls, x: float, y: float) -> Self: ... + def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: Vec2D) -> float: ... + @overload + def __mul__(self, other: float) -> Vec2D: ... + + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] + def __sub__(self, other: tuple[float, float]) -> Vec2D: ... + def __neg__(self) -> Vec2D: ... + def __abs__(self) -> float: ... + def rotate(self, angle: float) -> Vec2D: ... + +else: + @disjoint_base + class Vec2D(tuple[float, float]): + def __new__(cls, x: float, y: float) -> Self: ... + def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + + @overload # type: ignore[override] + def __mul__(self, other: Vec2D) -> float: ... + @overload + def __mul__(self, other: float) -> Vec2D: ... + + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] + def __sub__(self, other: tuple[float, float]) -> Vec2D: ... + def __neg__(self) -> Vec2D: ... + def __abs__(self) -> float: ... + def rotate(self, angle: float) -> Vec2D: ... + +# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas +class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + bg: str + hscroll: Scrollbar + vscroll: Scrollbar + def __init__( + self, master: Misc | None, width: int = 500, height: int = 350, canvwidth: int = 600, canvheight: int = 500 + ) -> None: ... + canvwidth: int + canvheight: int + def reset(self, canvwidth: int | None = None, canvheight: int | None = None, bg: str | None = None) -> None: ... + +class TurtleScreenBase: + cv: Canvas + canvwidth: int + canvheight: int + xscale: float + yscale: float + def __init__(self, cv: Canvas) -> None: ... + def mainloop(self) -> None: ... + def textinput(self, title: str, prompt: str) -> str | None: ... + def numinput( + self, title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None + ) -> float | None: ... + +class Terminator(Exception): ... +class TurtleGraphicsError(Exception): ... + +class Shape: + def __init__( + self, type_: Literal["polygon", "image", "compound"], data: _PolygonCoords | PhotoImage | None = None + ) -> None: ... + def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = None) -> None: ... + +class TurtleScreen(TurtleScreenBase): + def __init__( + self, cv: Canvas, mode: Literal["standard", "logo", "world"] = "standard", colormode: float = 1.0, delay: int = 10 + ) -> None: ... + def clear(self) -> None: ... + + @overload + def mode(self, mode: None = None) -> str: ... + @overload + def mode(self, mode: Literal["standard", "logo", "world"]) -> None: ... + + def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ... + def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + + @overload + def colormode(self, cmode: None = None) -> float: ... + @overload + def colormode(self, cmode: float) -> None: ... + + def reset(self) -> None: ... + def turtles(self) -> list[Turtle]: ... + + @overload + def bgcolor(self) -> _AnyColor: ... + @overload + def bgcolor(self, color: _Color) -> None: ... + @overload + def bgcolor(self, r: float, g: float, b: float) -> None: ... + + @overload + def tracer(self, n: None = None) -> int: ... + @overload + def tracer(self, n: int, delay: int | None = None) -> None: ... + + @overload + def delay(self, delay: None = None) -> int: ... + @overload + def delay(self, delay: int) -> None: ... + + if sys.version_info >= (3, 14): + @contextmanager + def no_animation(self) -> Generator[None]: ... + + def update(self) -> None: ... + def window_width(self) -> int: ... + def window_height(self) -> int: ... + def getcanvas(self) -> Canvas: ... + def getshapes(self) -> list[str]: ... + def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def onkey(self, fun: Callable[[], object], key: str) -> None: ... + def listen(self, xdummy: float | None = None, ydummy: float | None = None) -> None: ... + def ontimer(self, fun: Callable[[], object], t: int = 0) -> None: ... + + @overload + def bgpic(self, picname: None = None) -> str: ... + @overload + def bgpic(self, picname: str) -> None: ... + + @overload + def screensize(self, canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... + # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well + @overload + def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... + + if sys.version_info >= (3, 14): + def save(self, filename: StrPath, *, overwrite: bool = False) -> None: ... + onscreenclick = onclick + resetscreen = reset + clearscreen = clear + addshape = register_shape + def onkeypress(self, fun: Callable[[], object], key: str | None = None) -> None: ... + onkeyrelease = onkey + +class TNavigator: + START_ORIENTATION: dict[str, Vec2D] + DEFAULT_MODE: str + DEFAULT_ANGLEOFFSET: int + DEFAULT_ANGLEORIENT: int + def __init__(self, mode: Literal["standard", "logo", "world"] = "standard") -> None: ... + def reset(self) -> None: ... + def degrees(self, fullcircle: float = 360.0) -> None: ... + def radians(self) -> None: ... + if sys.version_info >= (3, 12): + def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + + def forward(self, distance: float) -> None: ... + def back(self, distance: float) -> None: ... + def right(self, angle: float) -> None: ... + def left(self, angle: float) -> None: ... + def pos(self) -> Vec2D: ... + def xcor(self) -> float: ... + def ycor(self) -> float: ... + + @overload + def goto(self, x: tuple[float, float], y: None = None) -> None: ... + @overload + def goto(self, x: float, y: float) -> None: ... + + def home(self) -> None: ... + def setx(self, x: float) -> None: ... + def sety(self, y: float) -> None: ... + + @overload + def distance(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... + @overload + def distance(self, x: float, y: float) -> float: ... + + @overload + def towards(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... + @overload + def towards(self, x: float, y: float) -> float: ... + + def heading(self) -> float: ... + def setheading(self, to_angle: float) -> None: ... + def circle(self, radius: float, extent: float | None = None, steps: int | None = None) -> None: ... + def speed(self, s: int | None = 0) -> int | None: ... + fd = forward + bk = back + backward = back + rt = right + lt = left + position = pos + setpos = goto + setposition = goto + seth = setheading + +class TPen: + def __init__(self, resizemode: Literal["auto", "user", "noresize"] = "noresize") -> None: ... + + @overload + def resizemode(self, rmode: None = None) -> str: ... + @overload + def resizemode(self, rmode: Literal["auto", "user", "noresize"]) -> None: ... + + @overload + def pensize(self, width: None = None) -> int: ... + @overload + def pensize(self, width: int) -> None: ... + + def penup(self) -> None: ... + def pendown(self) -> None: ... + def isdown(self) -> bool: ... + + @overload + def speed(self, speed: None = None) -> int: ... + @overload + def speed(self, speed: _Speed) -> None: ... + + @overload + def pencolor(self) -> _AnyColor: ... + @overload + def pencolor(self, color: _Color) -> None: ... + @overload + def pencolor(self, r: float, g: float, b: float) -> None: ... + + @overload + def fillcolor(self) -> _AnyColor: ... + @overload + def fillcolor(self, color: _Color) -> None: ... + @overload + def fillcolor(self, r: float, g: float, b: float) -> None: ... + + @overload + def color(self) -> tuple[_AnyColor, _AnyColor]: ... + @overload + def color(self, color: _Color) -> None: ... + @overload + def color(self, r: float, g: float, b: float) -> None: ... + @overload + def color(self, color1: _Color, color2: _Color) -> None: ... + + if sys.version_info >= (3, 12): + def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + + def showturtle(self) -> None: ... + def hideturtle(self) -> None: ... + def isvisible(self) -> bool: ... + + # Note: signatures 1 and 2 overlap unsafely when no arguments are provided + @overload + def pen(self) -> _PenState: ... + @overload + def pen( + self, + pen: _PenState | None = None, + *, + shown: bool = ..., + pendown: bool = ..., + pencolor: _Color = ..., + fillcolor: _Color = ..., + pensize: int = ..., + speed: int = ..., + resizemode: Literal["auto", "user", "noresize"] = ..., + stretchfactor: tuple[float, float] = ..., + outline: int = ..., + tilt: float = ..., + ) -> None: ... + + width = pensize + up = penup + pu = penup + pd = pendown + down = pendown + st = showturtle + ht = hideturtle + +class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods in base classes # pyrefly: ignore [inconsistent-inheritance] + screen: TurtleScreen + screens: ClassVar[list[TurtleScreen]] + def __init__( + self, + canvas: Canvas | TurtleScreen | None = None, + shape: str = "classic", + undobuffersize: int = 1000, + visible: bool = True, + ) -> None: ... + def reset(self) -> None: ... + def setundobuffer(self, size: int | None) -> None: ... + def undobufferentries(self) -> int: ... + def clear(self) -> None: ... + def clone(self) -> Self: ... + + @overload + def shape(self, name: None = None) -> str: ... + @overload + def shape(self, name: str) -> None: ... + + # Unsafely overlaps when no arguments are provided + @overload + def shapesize(self) -> tuple[float, float, float]: ... + @overload + def shapesize( + self, stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None + ) -> None: ... + + @overload + def shearfactor(self, shear: None = None) -> float: ... + @overload + def shearfactor(self, shear: float) -> None: ... + + # Unsafely overlaps when no arguments are provided + @overload + def shapetransform(self) -> tuple[float, float, float, float]: ... + @overload + def shapetransform( + self, t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None + ) -> None: ... + + def get_shapepoly(self) -> _PolygonCoords | None: ... + + if sys.version_info < (3, 13): + @deprecated("Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.") + def settiltangle(self, angle: float) -> None: ... + + @overload + def tiltangle(self, angle: None = None) -> float: ... + @overload + def tiltangle(self, angle: float) -> None: ... + + def tilt(self, angle: float) -> None: ... + # Can return either 'int' or Tuple[int, ...] based on if the stamp is + # a compound stamp or not. So, as per the "no Union return" policy, + # we return Any. + def stamp(self) -> Any: ... + def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ... + def clearstamps(self, n: int | None = None) -> None: ... + def filling(self) -> bool: ... + if sys.version_info >= (3, 14): + @contextmanager + def fill(self) -> Generator[None]: ... + + def begin_fill(self) -> None: ... + def end_fill(self) -> None: ... + + @overload + def dot(self, size: int | _Color | None = None) -> None: ... + @overload + def dot(self, size: int | None, color: _Color, /) -> None: ... + @overload + def dot(self, size: int | None, r: float, g: float, b: float, /) -> None: ... + + def write( + self, arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal") + ) -> None: ... + if sys.version_info >= (3, 14): + @contextmanager + def poly(self) -> Generator[None]: ... + + def begin_poly(self) -> None: ... + def end_poly(self) -> None: ... + def get_poly(self) -> _PolygonCoords | None: ... + def getscreen(self) -> TurtleScreen: ... + def getturtle(self) -> Self: ... + getpen = getturtle + def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def onrelease(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def ondrag(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... + def undo(self) -> None: ... + turtlesize = shapesize + +class _Screen(TurtleScreen): + def __init__(self) -> None: ... + # Note int and float are interpreted differently, hence the Union instead of just float + def setup( + self, + width: int | float = 0.5, # noqa: Y041 + height: int | float = 0.75, # noqa: Y041 + startx: int | None = None, + starty: int | None = None, + ) -> None: ... + def title(self, titlestring: str) -> None: ... + def bye(self) -> None: ... + def exitonclick(self) -> None: ... + +class Turtle(RawTurtle): + def __init__(self, shape: str = "classic", undobuffersize: int = 1000, visible: bool = True) -> None: ... + +RawPen = RawTurtle +Pen = Turtle + +def write_docstringdict(filename: str = "turtle_docstringdict") -> None: ... + +# Functions copied from TurtleScreenBase: + +def mainloop() -> None: ... +def textinput(title: str, prompt: str) -> str | None: ... +def numinput( + title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None +) -> float | None: ... + +# Functions copied from TurtleScreen: + +def clear() -> None: ... + +@overload +def mode(mode: None = None) -> str: ... +@overload +def mode(mode: Literal["standard", "logo", "world"]) -> None: ... + +def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ... +def register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + +@overload +def colormode(cmode: None = None) -> float: ... +@overload +def colormode(cmode: float) -> None: ... + +def reset() -> None: ... +def turtles() -> list[Turtle]: ... + +@overload +def bgcolor() -> _AnyColor: ... +@overload +def bgcolor(color: _Color) -> None: ... +@overload +def bgcolor(r: float, g: float, b: float) -> None: ... + +@overload +def tracer(n: None = None) -> int: ... +@overload +def tracer(n: int, delay: int | None = None) -> None: ... + +@overload +def delay(delay: None = None) -> int: ... +@overload +def delay(delay: int) -> None: ... + +if sys.version_info >= (3, 14): + @contextmanager + def no_animation() -> Generator[None]: ... + +def update() -> None: ... +def window_width() -> int: ... +def window_height() -> int: ... +def getcanvas() -> Canvas: ... +def getshapes() -> list[str]: ... +def onclick(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... +def onkey(fun: Callable[[], object], key: str) -> None: ... +def listen(xdummy: float | None = None, ydummy: float | None = None) -> None: ... +def ontimer(fun: Callable[[], object], t: int = 0) -> None: ... + +@overload +def bgpic(picname: None = None) -> str: ... +@overload +def bgpic(picname: str) -> None: ... + +@overload +def screensize(canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... +@overload +def screensize(canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... + +if sys.version_info >= (3, 14): + def save(filename: StrPath, *, overwrite: bool = False) -> None: ... + +onscreenclick = onclick +resetscreen = reset +clearscreen = clear +addshape = register_shape + +def onkeypress(fun: Callable[[], object], key: str | None = None) -> None: ... + +onkeyrelease = onkey + +# Functions copied from _Screen: + +def setup(width: float = 0.5, height: float = 0.75, startx: int | None = None, starty: int | None = None) -> None: ... +def title(titlestring: str) -> None: ... +def bye() -> None: ... +def exitonclick() -> None: ... +def Screen() -> _Screen: ... + +# Functions copied from TNavigator: + +def degrees(fullcircle: float = 360.0) -> None: ... +def radians() -> None: ... +def forward(distance: float) -> None: ... +def back(distance: float) -> None: ... +def right(angle: float) -> None: ... +def left(angle: float) -> None: ... +def pos() -> Vec2D: ... +def xcor() -> float: ... +def ycor() -> float: ... + +@overload +def goto(x: tuple[float, float], y: None = None) -> None: ... +@overload +def goto(x: float, y: float) -> None: ... + +def home() -> None: ... +def setx(x: float) -> None: ... +def sety(y: float) -> None: ... + +@overload +def distance(x: TNavigator | tuple[float, float], y: None = None) -> float: ... +@overload +def distance(x: float, y: float) -> float: ... + +@overload +def towards(x: TNavigator | tuple[float, float], y: None = None) -> float: ... +@overload +def towards(x: float, y: float) -> float: ... + +def heading() -> float: ... +def setheading(to_angle: float) -> None: ... +def circle(radius: float, extent: float | None = None, steps: int | None = None) -> None: ... + +fd = forward +bk = back +backward = back +rt = right +lt = left +position = pos +setpos = goto +setposition = goto +seth = setheading + +# Functions copied from TPen: +@overload +def resizemode(rmode: None = None) -> str: ... +@overload +def resizemode(rmode: Literal["auto", "user", "noresize"]) -> None: ... + +@overload +def pensize(width: None = None) -> int: ... +@overload +def pensize(width: int) -> None: ... + +def penup() -> None: ... +def pendown() -> None: ... +def isdown() -> bool: ... + +@overload +def speed(speed: None = None) -> int: ... +@overload +def speed(speed: _Speed) -> None: ... + +@overload +def pencolor() -> _AnyColor: ... +@overload +def pencolor(color: _Color) -> None: ... +@overload +def pencolor(r: float, g: float, b: float) -> None: ... + +@overload +def fillcolor() -> _AnyColor: ... +@overload +def fillcolor(color: _Color) -> None: ... +@overload +def fillcolor(r: float, g: float, b: float) -> None: ... + +@overload +def color() -> tuple[_AnyColor, _AnyColor]: ... +@overload +def color(color: _Color) -> None: ... +@overload +def color(r: float, g: float, b: float) -> None: ... +@overload +def color(color1: _Color, color2: _Color) -> None: ... + +def showturtle() -> None: ... +def hideturtle() -> None: ... +def isvisible() -> bool: ... + +# Note: signatures 1 and 2 overlap unsafely when no arguments are provided +@overload +def pen() -> _PenState: ... +@overload +def pen( + pen: _PenState | None = None, + *, + shown: bool = ..., + pendown: bool = ..., + pencolor: _Color = ..., + fillcolor: _Color = ..., + pensize: int = ..., + speed: int = ..., + resizemode: Literal["auto", "user", "noresize"] = ..., + stretchfactor: tuple[float, float] = ..., + outline: int = ..., + tilt: float = ..., +) -> None: ... + +width = pensize +up = penup +pu = penup +pd = pendown +down = pendown +st = showturtle +ht = hideturtle + +# Functions copied from RawTurtle: + +def setundobuffer(size: int | None) -> None: ... +def undobufferentries() -> int: ... + +@overload +def shape(name: None = None) -> str: ... +@overload +def shape(name: str) -> None: ... + +if sys.version_info >= (3, 12): + def teleport(x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... + +# Unsafely overlaps when no arguments are provided +@overload +def shapesize() -> tuple[float, float, float]: ... +@overload +def shapesize(stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None) -> None: ... + +@overload +def shearfactor(shear: None = None) -> float: ... +@overload +def shearfactor(shear: float) -> None: ... + +# Unsafely overlaps when no arguments are provided +@overload +def shapetransform() -> tuple[float, float, float, float]: ... +@overload +def shapetransform( + t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None +) -> None: ... + +def get_shapepoly() -> _PolygonCoords | None: ... + +if sys.version_info < (3, 13): + @deprecated("Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.") + def settiltangle(angle: float) -> None: ... + +@overload +def tiltangle(angle: None = None) -> float: ... +@overload +def tiltangle(angle: float) -> None: ... + +def tilt(angle: float) -> None: ... + +# Can return either 'int' or Tuple[int, ...] based on if the stamp is +# a compound stamp or not. So, as per the "no Union return" policy, +# we return Any. +def stamp() -> Any: ... +def clearstamp(stampid: int | tuple[int, ...]) -> None: ... +def clearstamps(n: int | None = None) -> None: ... +def filling() -> bool: ... + +if sys.version_info >= (3, 14): + @contextmanager + def fill() -> Generator[None]: ... + +def begin_fill() -> None: ... +def end_fill() -> None: ... + +@overload +def dot(size: int | _Color | None = None) -> None: ... +@overload +def dot(size: int | None, color: _Color, /) -> None: ... +@overload +def dot(size: int | None, r: float, g: float, b: float, /) -> None: ... + +def write(arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal")) -> None: ... + +if sys.version_info >= (3, 14): + @contextmanager + def poly() -> Generator[None]: ... + +def begin_poly() -> None: ... +def end_poly() -> None: ... +def get_poly() -> _PolygonCoords | None: ... +def getscreen() -> TurtleScreen: ... +def getturtle() -> Turtle: ... + +getpen = getturtle + +def onrelease(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... +def ondrag(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ... +def undo() -> None: ... + +turtlesize = shapesize + +# Functions copied from RawTurtle with a few tweaks: + +def clone() -> Turtle: ... + +# Extra functions present only in the global scope: + +done = mainloop diff --git a/stdlib/types.pyi b/stdlib/types.pyi new file mode 100644 index 000000000000..ccd0d5930cdd --- /dev/null +++ b/stdlib/types.pyi @@ -0,0 +1,746 @@ +import sys +from _typeshed import AnnotationForm, MaybeNone, SupportsKeysAndGetItem +from _typeshed.importlib import LoaderProtocol +from collections.abc import ( + AsyncGenerator, + Awaitable, + Callable, + Coroutine, + Generator, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + MutableMapping, + MutableSequence, + ValuesView, +) +from importlib.machinery import ModuleSpec +from typing import Any, ClassVar, Literal, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base + +if sys.version_info >= (3, 14): + from _typeshed import AnnotateFunc + +__all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + "BuiltinMethodType", + "ClassMethodDescriptorType", + "MethodDescriptorType", + "MethodWrapperType", + "WrapperDescriptorType", + "resolve_bases", + "CellType", + "GenericAlias", + "EllipsisType", + "NoneType", + "NotImplementedType", + "UnionType", +] + +if sys.version_info >= (3, 12): + __all__ += ["get_original_bases"] + +if sys.version_info >= (3, 13): + __all__ += ["CapsuleType"] + +if sys.version_info >= (3, 15): + __all__ += ["FrameLocalsProxyType", "LazyImportType"] + +# Note, all classes "defined" here require special handling. + +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + +# Make sure this class definition stays roughly in line with `builtins.function` +@final +class FunctionType: + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... + __code__: CodeType + __defaults__: tuple[Any, ...] | None + __dict__: dict[str, Any] + @property + def __globals__(self) -> dict[str, Any]: ... + __name__: str + __qualname__: str + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + __kwdefaults__: dict[str, Any] | None + @property + def __builtins__(self) -> dict[str, Any]: ... + if sys.version_info >= (3, 12): + __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] + + __module__: str + if sys.version_info >= (3, 13): + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + kwdefaults: dict[str, object] | None = None, + ) -> Self: ... + else: + def __new__( + cls, + code: CodeType, + globals: dict[str, Any], + name: str | None = None, + argdefs: tuple[object, ...] | None = None, + closure: tuple[CellType, ...] | None = None, + ) -> Self: ... + + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + + @overload + def __get__(self, instance: None, owner: type, /) -> FunctionType: ... + @overload + def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ... + +LambdaType = FunctionType + +@final +class CodeType: + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + @property + def co_argcount(self) -> int: ... + @property + def co_posonlyargcount(self) -> int: ... + @property + def co_kwonlyargcount(self) -> int: ... + @property + def co_nlocals(self) -> int: ... + @property + def co_stacksize(self) -> int: ... + @property + def co_flags(self) -> int: ... + @property + def co_code(self) -> bytes: ... + @property + def co_consts(self) -> tuple[Any, ...]: ... + @property + def co_names(self) -> tuple[str, ...]: ... + @property + def co_varnames(self) -> tuple[str, ...]: ... + @property + def co_filename(self) -> str: ... + @property + def co_name(self) -> str: ... + @property + def co_firstlineno(self) -> int: ... + if sys.version_info < (3, 15): + @property + @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `CodeType.co_lines()` instead.") + def co_lnotab(self) -> bytes: ... + + @property + def co_freevars(self) -> tuple[str, ...]: ... + @property + def co_cellvars(self) -> tuple[str, ...]: ... + @property + def co_linetable(self) -> bytes: ... + def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... + if sys.version_info >= (3, 11): + @property + def co_exceptiontable(self) -> bytes: ... + @property + def co_qualname(self) -> str: ... + def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... + if sys.version_info >= (3, 14): + def co_branches(self) -> Iterator[tuple[int, int, int]]: ... + + if sys.version_info >= (3, 11): + def __new__( + cls, + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], + filename: str, + name: str, + qualname: str, + firstlineno: int, + linetable: bytes, + exceptiontable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, + ) -> Self: ... + else: + def __new__( + cls, + argcount: int, + posonlyargcount: int, + kwonlyargcount: int, + nlocals: int, + stacksize: int, + flags: int, + codestring: bytes, + constants: tuple[object, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], + filename: str, + name: str, + firstlineno: int, + linetable: bytes, + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., + /, + ) -> Self: ... + if sys.version_info >= (3, 11): + def replace( + self, + *, + co_argcount: int = -1, + co_posonlyargcount: int = -1, + co_kwonlyargcount: int = -1, + co_nlocals: int = -1, + co_stacksize: int = -1, + co_flags: int = -1, + co_firstlineno: int = -1, + co_code: bytes = ..., + co_consts: tuple[object, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., + co_filename: str = ..., + co_name: str = ..., + co_qualname: str = ..., + co_linetable: bytes = ..., + co_exceptiontable: bytes = ..., + ) -> Self: ... + else: + def replace( + self, + *, + co_argcount: int = -1, + co_posonlyargcount: int = -1, + co_kwonlyargcount: int = -1, + co_nlocals: int = -1, + co_stacksize: int = -1, + co_flags: int = -1, + co_firstlineno: int = -1, + co_code: bytes = ..., + co_consts: tuple[object, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., + co_filename: str = ..., + co_name: str = ..., + co_linetable: bytes = ..., + ) -> Self: ... + + if sys.version_info >= (3, 13): + __replace__ = replace + +@final +class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] # pyrefly: ignore [invalid-variance] + __hash__: ClassVar[None] # type: ignore[assignment] + def __new__(cls, mapping: SupportsKeysAndGetItem[_KT_co, _VT_co]) -> Self: ... + def __getitem__(self, key: _KT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-variance] + def __iter__(self) -> Iterator[_KT_co]: ... + def __len__(self) -> int: ... + def __eq__(self, value: object, /) -> bool: ... + def copy(self) -> dict[_KT_co, _VT_co]: ... + def keys(self) -> KeysView[_KT_co]: ... + def values(self) -> ValuesView[_VT_co]: ... + def items(self) -> ItemsView[_KT_co, _VT_co]: ... + + @overload + def get(self, key: _KT_co, /) -> _VT_co | None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT_co, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT_co, default: _T2, /) -> _VT_co | _T2: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __reversed__(self) -> Iterator[_KT_co]: ... + def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ... + def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ... + +if sys.version_info >= (3, 12): + @disjoint_base + class SimpleNamespace: + __hash__: ClassVar[None] # type: ignore[assignment] + if sys.version_info >= (3, 13): + def __init__( + self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any + ) -> None: ... + else: + def __init__(self, **kwargs: Any) -> None: ... + + def __eq__(self, value: object, /) -> bool: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> Self: ... + +else: + class SimpleNamespace: + __hash__: ClassVar[None] # type: ignore[assignment] + def __init__(self, **kwargs: Any) -> None: ... + def __eq__(self, value: object, /) -> bool: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + def __delattr__(self, name: str, /) -> None: ... + +@disjoint_base +class ModuleType: + __name__: str + __file__: str | None + @property + def __dict__(self) -> dict[str, Any]: ... # type: ignore[override] + __loader__: LoaderProtocol | None + __package__: str | None + __path__: MutableSequence[str] + __spec__: ModuleSpec | None + # N.B. Although this is the same type as `builtins.object.__doc__`, + # it is deliberately redeclared here. Most symbols declared in the namespace + # of `types.ModuleType` are available as "implicit globals" within a module's + # namespace, but this is not true for symbols declared in the namespace of `builtins.object`. + # Redeclaring `__doc__` here helps some type checkers understand that `__doc__` is available + # as an implicit global in all modules, similar to `__name__`, `__file__`, `__spec__`, etc. + __doc__: str | None + __annotations__: dict[str, AnnotationForm] + if sys.version_info >= (3, 14): + __annotate__: AnnotateFunc | None + + def __init__(self, name: str, doc: str | None = ...) -> None: ... + # __getattr__ doesn't exist at runtime, + # but having it here in typeshed makes dynamic imports + # using `builtins.__import__` or `importlib.import_module` less painful + def __getattr__(self, name: str) -> Any: ... + +@final +class CellType: + def __new__(cls, contents: object = ..., /) -> Self: ... + __hash__: ClassVar[None] # type: ignore[assignment] + cell_contents: Any + +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) + +@final +class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): + @property + def gi_code(self) -> CodeType: ... + @property + def gi_frame(self) -> FrameType | None: ... + @property + def gi_running(self) -> bool: ... + @property + def gi_yieldfrom(self) -> Iterator[_YieldT_co] | None: ... + if sys.version_info >= (3, 11): + @property + def gi_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def gi_state(self) -> Literal["GEN_CREATED", "GEN_SUSPENDED", "GEN_RUNNING", "GEN_CLOSED"]: ... + __name__: str + __qualname__: str + def __iter__(self) -> Self: ... + def __next__(self) -> _YieldT_co: ... + def send(self, arg: _SendT_contra, /) -> _YieldT_co: ... + + @overload + def throw( + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... + @overload + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + + if sys.version_info >= (3, 13): + def __class_getitem__(cls, item: Any, /) -> Any: ... + +@final +class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): + @property + def ag_await(self) -> Awaitable[Any] | None: ... + @property + def ag_code(self) -> CodeType: ... + @property + def ag_frame(self) -> FrameType | None: ... + @property + def ag_running(self) -> bool: ... + __name__: str + __qualname__: str + if sys.version_info >= (3, 12): + @property + def ag_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def ag_state(self) -> Literal["AGEN_CREATED", "AGEN_SUSPENDED", "AGEN_RUNNING", "AGEN_CLOSED"]: ... + + def __aiter__(self) -> Self: ... + def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... + def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + + @overload + async def athrow( + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... + @overload + async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + + def aclose(self) -> Coroutine[Any, Any, None]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +# Non-default variations to accommodate coroutines +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) + +@final +class CoroutineType(Coroutine[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]): + __name__: str + __qualname__: str + @property + def cr_await(self) -> Any | None: ... + @property + def cr_code(self) -> CodeType: ... + @property + def cr_frame(self) -> FrameType | None: ... + @property + def cr_running(self) -> bool: ... + @property + def cr_origin(self) -> tuple[tuple[str, int, str], ...] | None: ... + if sys.version_info >= (3, 11): + @property + def cr_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def cr_state(self) -> Literal["CORO_CREATED", "CORO_SUSPENDED", "CORO_RUNNING", "CORO_CLOSED"]: ... + + def close(self) -> None: ... + def __await__(self) -> Generator[Any, None, _ReturnT_nd_co]: ... + def send(self, arg: _SendT_nd_contra, /) -> _YieldT_co: ... + + @overload + def throw( + self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / + ) -> _YieldT_co: ... + @overload + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + + if sys.version_info >= (3, 13): + def __class_getitem__(cls, item: Any, /) -> Any: ... + +@final +class MethodType: + @property + def __closure__(self) -> tuple[CellType, ...] | None: ... # inherited from the added function + @property + def __code__(self) -> CodeType: ... # inherited from the added function + @property + def __defaults__(self) -> tuple[Any, ...] | None: ... # inherited from the added function + @property + def __func__(self) -> Callable[..., Any]: ... + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... # inherited from the added function + @property + def __qualname__(self) -> str: ... # inherited from the added function + def __new__(cls, func: Callable[..., Any], instance: object, /) -> Self: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + + if sys.version_info >= (3, 13): + def __get__(self, instance: object, owner: type | None = None, /) -> Self: ... + + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class BuiltinFunctionType: + @property + def __self__(self) -> object | ModuleType: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + +BuiltinMethodType = BuiltinFunctionType + +@final +class WrapperDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + +@final +class MethodWrapperType: + @property + def __self__(self) -> object: ... + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + +@final +class MethodDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + +@final +class ClassMethodDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + +@final +class TracebackType: + def __new__(cls, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> Self: ... + tb_next: TracebackType | None + # the rest are read-only + @property + def tb_frame(self) -> FrameType: ... + @property + def tb_lasti(self) -> int: ... + @property + def tb_lineno(self) -> int: ... + +@final +class FrameType: + @property + def f_back(self) -> FrameType | None: ... + @property + def f_builtins(self) -> dict[str, Any]: ... + @property + def f_code(self) -> CodeType: ... + @property + def f_globals(self) -> dict[str, Any]: ... + @property + def f_lasti(self) -> int: ... + # see discussion in #6769: f_lineno *can* sometimes be None, + # but you should probably file a bug report with CPython if you encounter it being None in the wild. + # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`. + @property + def f_lineno(self) -> int | MaybeNone: ... + + if sys.version_info >= (3, 15): + @property + def f_locals(self) -> FrameLocalsProxyType | dict[str, Any]: ... + else: + @property + def f_locals(self) -> dict[str, Any]: ... + + f_trace: Callable[[FrameType, str, Any], Any] | None + f_trace_lines: bool + f_trace_opcodes: bool + def clear(self) -> None: ... + if sys.version_info >= (3, 14): + @property + def f_generator(self) -> GeneratorType[Any, Any, Any] | CoroutineType[Any, Any, Any] | None: ... + +if sys.version_info >= (3, 15): + @final + class FrameLocalsProxyType(MutableMapping[str, Any]): + def __new__(cls, frame: FrameType, /) -> Self: ... + def __getitem__(self, key: str, /) -> Any: ... + def __setitem__(self, key: str, value: Any, /) -> None: ... + def __delitem__(self, key: str, /) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... + def __reversed__(self) -> Iterator[str]: ... + def copy(self) -> dict[str, Any]: ... + def pop(self, key: str, default: Any = ..., /) -> Any: ... + def setdefault(self, key: str, default: Any = ..., /) -> Any: ... + def update(self, object: SupportsKeysAndGetItem[str, Any] | Iterable[tuple[str, Any]], /) -> None: ... # type: ignore[override] + + @final + class LazyImportType: + @property + def __name__(self) -> str: ... + def resolve(self) -> Any: ... + +@final +class GetSetDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... + +@final +class MemberDescriptorType: + @property + def __name__(self) -> str: ... + @property + def __qualname__(self) -> str: ... + @property + def __objclass__(self) -> type: ... + def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... + def __delete__(self, instance: Any, /) -> None: ... + +def new_class( + name: str, + bases: Iterable[object] = (), + kwds: dict[str, Any] | None = None, + exec_body: Callable[[dict[str, Any]], object] | None = None, +) -> type: ... +def resolve_bases(bases: Iterable[object]) -> tuple[Any, ...]: ... +def prepare_class( + name: str, bases: tuple[type, ...] = (), kwds: dict[str, Any] | None = None +) -> tuple[type, dict[str, Any], dict[str, Any]]: ... + +if sys.version_info >= (3, 12): + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... + +# Does not actually inherit from property, but saying it does makes sure that +# pyright handles this class correctly. +class DynamicClassAttribute(property): + fget: Callable[[Any], Any] | None + fset: Callable[[Any, Any], object] | None # type: ignore[assignment] + fdel: Callable[[Any], object] | None # type: ignore[assignment] + overwrite_doc: bool + __isabstractmethod__: bool + def __init__( + self, + fget: Callable[[Any], Any] | None = None, + fset: Callable[[Any, Any], object] | None = None, + fdel: Callable[[Any], object] | None = None, + doc: str | None = None, + ) -> None: ... + def __get__(self, instance: Any, ownerclass: type | None = None) -> Any: ... + def __set__(self, instance: Any, value: Any) -> None: ... + def __delete__(self, instance: Any) -> None: ... + def getter(self, fget: Callable[[Any], Any]) -> DynamicClassAttribute: ... + def setter(self, fset: Callable[[Any, Any], object]) -> DynamicClassAttribute: ... + def deleter(self, fdel: Callable[[Any], object]) -> DynamicClassAttribute: ... + +_Fn = TypeVar("_Fn", bound=Callable[..., object]) +_R = TypeVar("_R") +_P = ParamSpec("_P") + +# it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable +@overload +def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Awaitable[_R]]: ... +@overload +def coroutine(func: _Fn) -> _Fn: ... + +@disjoint_base +class GenericAlias: + @property + def __origin__(self) -> type | TypeAliasType: ... + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + def __new__(cls, origin: type, args: Any, /) -> Self: ... + def __getitem__(self, typeargs: Any, /) -> GenericAlias: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __mro_entries__(self, bases: Iterable[object], /) -> tuple[type, ...]: ... + if sys.version_info >= (3, 11): + @property + def __unpacked__(self) -> bool: ... + @property + def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ... + + # `other` can be any legal form for unions. + # `list[int] | list[int]` creates a `GenericAlias` instance, not a `UnionType` instance + def __or__(self, value: Any, /) -> UnionType | GenericAlias: ... + def __ror__(self, value: Any, /) -> UnionType | GenericAlias: ... + + # GenericAlias delegates attr access to `__origin__` + def __getattr__(self, name: str) -> Any: ... + +@final +class NoneType: + def __bool__(self) -> Literal[False]: ... + +@final +class EllipsisType: ... + +@final +class NotImplementedType(Any): ... + +@final +class UnionType: + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + # `(int | str) | Literal["foo"]` returns a generic alias to an instance of `_SpecialForm` (`Union`). + # Normally we'd express this using the return type of `_SpecialForm.__ror__`, + # but because `UnionType.__or__` accepts `Any`, type checkers will use + # the return type of `UnionType.__or__` to infer the result of this operation + # rather than `_SpecialForm.__ror__`. To mitigate this, we use `| Any` + # in the return type of `UnionType.__(r)or__`. + def __or__(self, value: Any, /) -> UnionType | Any: ... + def __ror__(self, value: Any, /) -> UnionType | Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + # you can only subscript a `UnionType` instance if at least one of the elements + # in the union is a generic alias instance that has a non-empty `__parameters__` + def __getitem__(self, parameters: Any, /) -> object: ... + +if sys.version_info >= (3, 13): + @final + class CapsuleType: ... diff --git a/stdlib/typing.pyi b/stdlib/typing.pyi new file mode 100644 index 000000000000..14f3df9b59d2 --- /dev/null +++ b/stdlib/typing.pyi @@ -0,0 +1,1243 @@ +# Since this module defines "overload" it is not recognized by Ruff as typing.overload +# TODO: The collections import is required, otherwise mypy crashes. +# https://github.com/python/mypy/issues/16744 +import collections # noqa: F401 # pyright: ignore[reportUnusedImport] +import sys +import typing_extensions +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import IdentityFunction, ReadableBuffer, SupportsGetItem, SupportsGetItemViewable, SupportsKeysAndGetItem, Viewable +from abc import ABCMeta, abstractmethod +from re import Match as Match, Pattern as Pattern +from types import ( + BuiltinFunctionType, + CodeType, + FunctionType, + GenericAlias, + MethodDescriptorType, + MethodType, + MethodWrapperType, + ModuleType, + TracebackType, + UnionType, + WrapperDescriptorType, +) +from typing_extensions import Never as _Never, deprecated + +if sys.version_info >= (3, 14): + from _typeshed import EvaluateFunc + + from annotationlib import Format + +__all__ = [ + "AbstractSet", + "Annotated", + "Any", + "AnyStr", + "AsyncContextManager", + "AsyncGenerator", + "AsyncIterable", + "AsyncIterator", + "Awaitable", + "BinaryIO", + "Callable", + "ChainMap", + "ClassVar", + "Collection", + "Concatenate", + "Container", + "ContextManager", + "Coroutine", + "Counter", + "DefaultDict", + "Deque", + "Dict", + "Final", + "ForwardRef", + "FrozenSet", + "Generator", + "Generic", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Literal", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "NamedTuple", + "NewType", + "NoReturn", + "Optional", + "OrderedDict", + "ParamSpec", + "ParamSpecArgs", + "ParamSpecKwargs", + "Pattern", + "Protocol", + "Reversible", + "Sequence", + "Set", + "Sized", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "Text", + "TextIO", + "Tuple", + "Type", + "TypeAlias", + "TypeGuard", + "TypeVar", + "TypedDict", + "Union", + "ValuesView", + "TYPE_CHECKING", + "cast", + "final", + "get_args", + "get_origin", + "get_type_hints", + "is_typeddict", + "no_type_check", + "overload", + "runtime_checkable", +] + +if sys.version_info < (3, 15): + __all__ += ["ByteString", "no_type_check_decorator"] + +if sys.version_info >= (3, 14): + __all__ += ["evaluate_forward_ref"] + +if sys.version_info >= (3, 15): + __all__ += ["NoExtraItems", "TypeForm", "disjoint_base"] + +if sys.version_info >= (3, 11): + __all__ += [ + "LiteralString", + "Never", + "NotRequired", + "Required", + "Self", + "TypeVarTuple", + "Unpack", + "assert_never", + "assert_type", + "clear_overloads", + "dataclass_transform", + "get_overloads", + "reveal_type", + ] + +if sys.version_info >= (3, 12): + __all__ += ["TypeAliasType", "override"] + +if sys.version_info >= (3, 13): + __all__ += ["get_protocol_members", "is_protocol", "NoDefault", "TypeIs", "ReadOnly"] + +# We can't use this name here because it leads to issues with mypy, likely +# due to an import cycle. Below instead we use Any with a comment. +# from _typeshed import AnnotationForm + +class Any: ... + +class _Final: + __slots__ = ("__weakref__",) + +def final(f: _T) -> _T: ... + +@final +class TypeVar: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __constraints__(self) -> tuple[Any, ...]: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + if sys.version_info >= (3, 12): + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + if sys.version_info >= (3, 13): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + default: Any = ..., # AnnotationForm + ) -> Self: ... + elif sys.version_info >= (3, 12): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 11): + def __new__( + cls, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + ) -> Self: ... + else: + def __init__( + self, + name: str, + *constraints: Any, # AnnotationForm + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + ) -> None: ... + + def __or__(self, right: Any, /) -> _SpecialForm: ... # AnnotationForm + def __ror__(self, left: Any, /) -> _SpecialForm: ... # AnnotationForm + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any, /) -> Any: ... + if sys.version_info >= (3, 13): + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + def has_default(self) -> bool: ... + if sys.version_info >= (3, 14): + @property + def evaluate_bound(self) -> EvaluateFunc | None: ... + @property + def evaluate_constraints(self) -> EvaluateFunc | None: ... + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +# N.B. Keep this definition in sync with typing_extensions._SpecialForm +@final +class _SpecialForm(_Final): + __slots__ = ("_name", "__doc__", "_getitem") + def __getitem__(self, parameters: Any) -> object: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +Union: _SpecialForm +Protocol: _SpecialForm +Callable: _SpecialForm +Type: _SpecialForm +NoReturn: _SpecialForm +ClassVar: _SpecialForm + +Optional: _SpecialForm +Tuple: _SpecialForm +Final: _SpecialForm + +Literal: _SpecialForm +TypedDict: _SpecialForm + +if sys.version_info >= (3, 11): + Self: _SpecialForm + Never: _SpecialForm + Unpack: _SpecialForm + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm + + @final + class TypeVarTuple: + @property + def __name__(self) -> str: ... + if sys.version_info >= (3, 15): + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + def has_default(self) -> bool: ... + if sys.version_info >= (3, 15): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + default: Any = ..., # AnnotationForm + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 13): + def __new__(cls, name: str, *, default: Any = ...) -> Self: ... # AnnotationForm + elif sys.version_info >= (3, 12): + def __new__(cls, name: str) -> Self: ... + else: + def __init__(self, name: str) -> None: ... + + def __iter__(self) -> Any: ... + def __typing_subst__(self, arg: Never, /) -> Never: ... + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +@final +class ParamSpecArgs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: + def __init__(self, origin: ParamSpec) -> None: ... + + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ParamSpecKwargs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: + def __init__(self, origin: ParamSpec) -> None: ... + + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ParamSpec: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + if sys.version_info >= (3, 12): + @property + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): + @property + def __default__(self) -> Any: ... # AnnotationForm + if sys.version_info >= (3, 13): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + default: Any = ..., # AnnotationForm + ) -> Self: ... + elif sys.version_info >= (3, 12): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 11): + def __new__( + cls, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm + ) -> Self: ... + else: + def __init__( + self, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm + ) -> None: ... + + @property + def args(self) -> ParamSpecArgs: ... + @property + def kwargs(self) -> ParamSpecKwargs: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any, /) -> Any: ... + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + if sys.version_info >= (3, 13): + def has_default(self) -> bool: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +Concatenate: _SpecialForm +TypeAlias: _SpecialForm +TypeGuard: _SpecialForm + +class NewType: + def __init__(self, name: str, tp: Any) -> None: ... # AnnotationForm + if sys.version_info >= (3, 11): + @staticmethod + def __call__(x: _T, /) -> _T: ... + else: + def __call__(self, x: _T) -> _T: ... + + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type | NewType + __name__: str + +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") +_T = TypeVar("_T") + +_FT = TypeVar("_FT", bound=Callable[..., Any] | type) + +# These type variables are used by the container types. +_S = TypeVar("_S") +_KT = TypeVar("_KT") # Key type. +_VT = TypeVar("_VT") # Value type. +_T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. +_TC = TypeVar("_TC", bound=type[object]) + +def overload(func: _F) -> _F: ... +def no_type_check(arg: _F) -> _F: ... + +if sys.version_info < (3, 15): + @deprecated("Deprecated; removed in Python 3.15.") + def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... + +if sys.version_info >= (3, 15): + def disjoint_base(cls: _TC) -> _TC: ... + +# This itself is only available during type checking +def type_check_only(func_or_cls: _FT) -> _FT: ... + +# Type aliases and type constructors + +@type_check_only +class _Alias: + # Class for defining generic aliases for library types. + def __getitem__(self, typeargs: Any) -> Any: ... + +List = _Alias() +Dict = _Alias() +DefaultDict = _Alias() +Set = _Alias() +FrozenSet = _Alias() +Counter = _Alias() +Deque = _Alias() +ChainMap = _Alias() + +OrderedDict = _Alias() + +Annotated: _SpecialForm +if sys.version_info >= (3, 15): + @type_check_only + class _NoExtraItemsType: ... + + NoExtraItems: _NoExtraItemsType + + TypeForm: _SpecialForm + +# Predefined type variables. +AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 + +@type_check_only +class _Generic: + if sys.version_info < (3, 12): + __slots__ = () + + @classmethod + def __class_getitem__(cls, args: TypeVar | ParamSpec | tuple[TypeVar | ParamSpec, ...]) -> _Final: ... + +Generic: type[_Generic] + +class _ProtocolMeta(ABCMeta): + if sys.version_info >= (3, 12): + def __init__(cls, *args: Any, **kwargs: Any) -> None: ... + +# Abstract base classes. + +def runtime_checkable(cls: _TC) -> _TC: ... + +@runtime_checkable +class SupportsInt(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __int__(self) -> int: ... + +@runtime_checkable +class SupportsFloat(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __float__(self) -> float: ... + +@runtime_checkable +class SupportsComplex(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __complex__(self) -> complex: ... + +@runtime_checkable +class SupportsBytes(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __bytes__(self) -> bytes: ... + +@runtime_checkable +class SupportsIndex(Protocol, metaclass=ABCMeta): + __slots__ = () + @abstractmethod + def __index__(self) -> int: ... + +@runtime_checkable +class SupportsAbs(Protocol[_T_co]): + __slots__ = () + @abstractmethod + def __abs__(self) -> _T_co: ... + +@runtime_checkable +class SupportsRound(Protocol[_T_co]): + __slots__ = () + + @overload + @abstractmethod + def __round__(self) -> int: ... + @overload + @abstractmethod + def __round__(self, ndigits: int, /) -> _T_co: ... + +@runtime_checkable +class Sized(Protocol, metaclass=ABCMeta): + @abstractmethod + def __len__(self) -> int: ... + +@runtime_checkable +class Hashable(Protocol, metaclass=ABCMeta): + # TODO: This is special, in that a subclass of a hashable class may not be hashable + # (for example, list vs. object). It's not obvious how to represent this. This class + # is currently mostly useless for static checking. + @abstractmethod + def __hash__(self) -> int: ... + +@runtime_checkable +class Iterable(Protocol[_T_co]): + @abstractmethod + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Iterator(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def __next__(self) -> _T_co: ... + def __iter__(self) -> Iterator[_T_co]: ... + +@runtime_checkable +class Reversible(Iterable[_T_co], Protocol[_T_co]): + @abstractmethod + def __reversed__(self) -> Iterator[_T_co]: ... + +_YieldT_co = TypeVar("_YieldT_co", covariant=True) +_SendT_contra = TypeVar("_SendT_contra", contravariant=True, default=None) +_ReturnT_co = TypeVar("_ReturnT_co", covariant=True, default=None) + +@runtime_checkable +class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _ReturnT_co]): + def __next__(self) -> _YieldT_co: ... + @abstractmethod + def send(self, value: _SendT_contra, /) -> _YieldT_co: ... + + @overload + @abstractmethod + def throw( + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> _YieldT_co: ... + @overload + @abstractmethod + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + + if sys.version_info >= (3, 13): + def close(self) -> _ReturnT_co | None: ... + else: + def close(self) -> None: ... + + def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ... + +# NOTE: Prior to Python 3.13 these aliases are lacking the second _ExitT_co parameter +if sys.version_info >= (3, 13): + from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager +else: + from contextlib import AbstractAsyncContextManager, AbstractContextManager + + @runtime_checkable + class ContextManager(AbstractContextManager[_T_co, bool | None], Protocol[_T_co]): ... + + @runtime_checkable + class AsyncContextManager(AbstractAsyncContextManager[_T_co, bool | None], Protocol[_T_co]): ... + +@runtime_checkable +class Awaitable(Protocol[_T_co]): + @abstractmethod + def __await__(self) -> Generator[Any, Any, _T_co]: ... + +# Non-default variations to accommodate coroutines, and `AwaitableGenerator` having a 4th type parameter. +_SendT_nd_contra = TypeVar("_SendT_nd_contra", contravariant=True) +_ReturnT_nd_co = TypeVar("_ReturnT_nd_co", covariant=True) + +class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]): + __name__: str + __qualname__: str + + @abstractmethod + def send(self, value: _SendT_nd_contra, /) -> _YieldT_co: ... + + @overload + @abstractmethod + def throw( + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> _YieldT_co: ... + @overload + @abstractmethod + def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + + @abstractmethod + def close(self) -> None: ... + +# NOTE: This type does not exist in typing.py or PEP 484 but mypy needs it to exist. +# The parameters correspond to Generator, but the 4th is the original type. +# Obsolete, use _typeshed._type_checker_internals.AwaitableGenerator instead. +@type_check_only +class AwaitableGenerator( + Awaitable[_ReturnT_nd_co], + Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co], + Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S], + metaclass=ABCMeta, +): ... + +@runtime_checkable +class AsyncIterable(Protocol[_T_co]): + @abstractmethod + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +@runtime_checkable +class AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]): + @abstractmethod + def __anext__(self) -> Awaitable[_T_co]: ... + def __aiter__(self) -> AsyncIterator[_T_co]: ... + +@runtime_checkable +class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra]): + def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... + @abstractmethod + def asend(self, value: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + + @overload + @abstractmethod + def athrow( + self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> Coroutine[Any, Any, _YieldT_co]: ... + @overload + @abstractmethod + def athrow( + self, typ: BaseException, val: None = None, tb: TracebackType | None = None, / + ) -> Coroutine[Any, Any, _YieldT_co]: ... + + def aclose(self) -> Coroutine[Any, Any, None]: ... + +_ContainerT_contra = TypeVar("_ContainerT_contra", contravariant=True, default=Any) + +@runtime_checkable +class Container(Protocol[_ContainerT_contra]): + # This is generic more on vibes than anything else + @abstractmethod + def __contains__(self, x: _ContainerT_contra, /) -> bool: ... + +@runtime_checkable +class Collection(Iterable[_T_co], Container[Any], Protocol[_T_co]): + # Note: need to use Container[Any] instead of Container[_T_co] to ensure covariance. + # Implement Sized (but don't have it as a base class). + @abstractmethod + def __len__(self) -> int: ... + +class Sequence(Reversible[_T_co], Collection[_T_co]): + @overload + @abstractmethod + def __getitem__(self, index: int, /) -> _T_co: ... + @overload + @abstractmethod + def __getitem__(self, index: slice[int | None], /) -> Sequence[_T_co]: ... + + # Mixin methods + def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ... + def count(self, value: Any, /) -> int: ... + def __contains__(self, value: object, /) -> bool: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __reversed__(self) -> Iterator[_T_co]: ... + +class MutableSequence(Sequence[_T]): + @abstractmethod + def insert(self, index: int, value: _T, /) -> None: ... + + @overload + @abstractmethod + def __getitem__(self, index: int, /) -> _T: ... + @overload + @abstractmethod + def __getitem__(self, index: slice[int | None], /) -> MutableSequence[_T]: ... + + @overload + @abstractmethod + def __setitem__(self, index: int, value: _T, /) -> None: ... + @overload + @abstractmethod + def __setitem__(self, index: slice[int | None], value: Iterable[_T], /) -> None: ... + + @overload + @abstractmethod + def __delitem__(self, index: int, /) -> None: ... + @overload + @abstractmethod + def __delitem__(self, index: slice[int | None], /) -> None: ... + + # Mixin methods + def append(self, value: _T, /) -> None: ... + def clear(self) -> None: ... + def extend(self, values: Iterable[_T], /) -> None: ... + def reverse(self) -> None: ... + def pop(self, index: int = -1, /) -> _T: ... + def remove(self, value: _T, /) -> None: ... + def __iadd__(self, values: Iterable[_T], /) -> typing_extensions.Self: ... + +class AbstractSet(Collection[_T_co]): + @abstractmethod + def __contains__(self, x: object, /) -> bool: ... + def _hash(self) -> int: ... + # Mixin methods + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> AbstractSet[_S]: ... + def __le__(self, other: AbstractSet[Any], /) -> bool: ... + def __lt__(self, other: AbstractSet[Any], /) -> bool: ... + def __gt__(self, other: AbstractSet[Any], /) -> bool: ... + def __ge__(self, other: AbstractSet[Any], /) -> bool: ... + def __and__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... + def __or__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... + def __sub__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... + def __xor__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... + def __eq__(self, other: object, /) -> bool: ... + def isdisjoint(self, other: Iterable[Any], /) -> bool: ... + +class MutableSet(AbstractSet[_T]): + @abstractmethod + def add(self, value: _T, /) -> None: ... + @abstractmethod + def discard(self, value: _T, /) -> None: ... + # Mixin methods + def clear(self) -> None: ... + def pop(self) -> _T: ... + def remove(self, value: _T, /) -> None: ... + def __ior__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] + def __iand__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... + def __ixor__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] + def __isub__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... + +class MappingView(Sized): + __slots__ = ("_mapping",) + def __init__(self, mapping: Sized) -> None: ... # undocumented + def __len__(self) -> int: ... + +class ItemsView(MappingView, AbstractSet[tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): + def __init__(self, mapping: SupportsGetItemViewable[_KT_co, _VT_co]) -> None: ... # undocumented + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ... + def __and__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ... + def __rand__(self, other: Iterable[_T], /) -> set[_T]: ... + def __contains__(self, item: tuple[object, object], /) -> bool: ... # type: ignore[override] + def __iter__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... + def __or__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __ror__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __sub__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ... + def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ... + def __xor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __rxor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ... + +class KeysView(MappingView, AbstractSet[_KT_co]): + def __init__(self, mapping: Viewable[_KT_co]) -> None: ... # undocumented + @classmethod + def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ... + def __and__(self, other: Iterable[Any], /) -> set[_KT_co]: ... + def __rand__(self, other: Iterable[_T], /) -> set[_T]: ... + def __contains__(self, key: object, /) -> bool: ... + def __iter__(self) -> Iterator[_KT_co]: ... + def __or__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __ror__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __sub__(self, other: Iterable[Any], /) -> set[_KT_co]: ... + def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ... + def __xor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + def __rxor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ... + +class ValuesView(MappingView, Collection[_VT_co]): + def __init__(self, mapping: SupportsGetItemViewable[Any, _VT_co]) -> None: ... # undocumented + def __contains__(self, value: object, /) -> bool: ... + def __iter__(self) -> Iterator[_VT_co]: ... + +# note for Mapping.get and MutableMapping.pop and MutableMapping.setdefault +# In _collections_abc.py the parameters are positional-or-keyword, +# but dict and types.MappingProxyType (the vast majority of Mapping types) +# don't allow keyword arguments. + +class Mapping(Collection[_KT], Generic[_KT, _VT_co]): + # TODO: We wish the key type could also be covariant, but that doesn't work, + # see discussion in https://github.com/python/typing/pull/273. + @abstractmethod + def __getitem__(self, key: _KT, /) -> _VT_co: ... + + # Mixin methods + @overload + def get(self, key: _KT, /) -> _VT_co | None: ... + @overload + def get(self, key: _KT, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter # pyrefly: ignore [invalid-variance] + @overload + def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ... + + def items(self) -> ItemsView[_KT, _VT_co]: ... + def keys(self) -> KeysView[_KT]: ... + def values(self) -> ValuesView[_VT_co]: ... + def __contains__(self, key: object, /) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... + +class MutableMapping(Mapping[_KT, _VT]): + @abstractmethod + def __setitem__(self, key: _KT, value: _VT, /) -> None: ... + @abstractmethod + def __delitem__(self, key: _KT, /) -> None: ... + def clear(self) -> None: ... + + @overload + def pop(self, key: _KT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def popitem(self) -> tuple[_KT, _VT]: ... + + # This overload should be allowed only if the value type is compatible with None. + # + # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences: + # -- collections.OrderedDict.setdefault + # -- collections.ChainMap.setdefault + # -- weakref.WeakKeyDictionary.setdefault + @overload + def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ... + @overload + def setdefault(self, key: _KT, default: _VT, /) -> _VT: ... + + # 'update' used to take a Union, but using overloading is better. + # The second overloaded type here is a bit too general, because + # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]], + # but will always have the behavior of the first overloaded type + # at runtime, leading to keys of a mix of types _KT and tuple[_KT, _VT]. + # We don't currently have any way of forcing all Mappings to use + # the first overload, but by using overloading rather than a Union, + # mypy will commit to using the first overload when the argument is + # known to be a Mapping with unknown type parameters, which is closer + # to the behavior we want. See mypy issue #1430. + # + # Various mapping classes have __ior__ methods that should be kept roughly in line with .update(): + # -- dict.__ior__ + # -- os._Environ.__ior__ + # -- collections.UserDict.__ior__ + # -- collections.ChainMap.__ior__ + # -- peewee.attrdict.__add__ + # -- peewee.attrdict.__iadd__ + # -- weakref.WeakValueDictionary.__ior__ + # -- weakref.WeakKeyDictionary.__ior__ + @overload + def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], m: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ... + @overload + def update(self, m: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], m: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], /, **kwargs: _VT) -> None: ... + +Text = str + +TYPE_CHECKING: Final[bool] + +# In stubs, the arguments of the IO class are marked as positional-only. +# This differs from runtime, but better reflects the fact that in reality +# classes deriving from IO use different names for the arguments. +class IO(Generic[AnyStr]): + # At runtime these are all abstract properties, + # but making them abstract in the stub is hugely disruptive, for not much gain. + # See #8726 + __slots__ = () + @property + def mode(self) -> str: ... + # Usually str, but may be bytes if a bytes path was passed to open(). See #10737. + # If PEP 696 becomes available, we may want to use a defaulted TypeVar here. + @property + def name(self) -> str | Any: ... + @abstractmethod + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @abstractmethod + def fileno(self) -> int: ... + @abstractmethod + def flush(self) -> None: ... + @abstractmethod + def isatty(self) -> bool: ... + @abstractmethod + def read(self, n: int = -1, /) -> AnyStr: ... + @abstractmethod + def readable(self) -> bool: ... + @abstractmethod + def readline(self, limit: int = -1, /) -> AnyStr: ... + @abstractmethod + def readlines(self, hint: int = -1, /) -> list[AnyStr]: ... + @abstractmethod + def seek(self, offset: int, whence: int = 0, /) -> int: ... + @abstractmethod + def seekable(self) -> bool: ... + @abstractmethod + def tell(self) -> int: ... + @abstractmethod + def truncate(self, size: int | None = None, /) -> int: ... + @abstractmethod + def writable(self) -> bool: ... + + @abstractmethod + @overload + def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ... + @abstractmethod + @overload + def write(self, s: AnyStr, /) -> int: ... + + @abstractmethod + @overload + def writelines(self: IO[bytes], lines: Iterable[ReadableBuffer], /) -> None: ... + @abstractmethod + @overload + def writelines(self, lines: Iterable[AnyStr], /) -> None: ... + + @abstractmethod + def __next__(self) -> AnyStr: ... + @abstractmethod + def __iter__(self) -> Iterator[AnyStr]: ... + @abstractmethod + def __enter__(self) -> IO[AnyStr]: ... + @abstractmethod + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +class BinaryIO(IO[bytes]): + __slots__ = () + @abstractmethod + def __enter__(self) -> BinaryIO: ... + +class TextIO(IO[str]): + # See comment regarding the @properties in the `IO` class + __slots__ = () + @property + def buffer(self) -> BinaryIO: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> str | None: ... + @property + def line_buffering(self) -> int: ... # int on PyPy, bool on CPython + @property + def newlines(self) -> Any: ... # None, str or tuple + @abstractmethod + def __enter__(self) -> TextIO: ... + +ByteString: typing_extensions.TypeAlias = bytes | bytearray | memoryview + +# Functions + +_get_type_hints_obj_allowed_types: typing_extensions.TypeAlias = ( # noqa: Y042 + object + | Callable[..., Any] + | FunctionType + | BuiltinFunctionType + | MethodType + | ModuleType + | WrapperDescriptorType + | MethodWrapperType + | MethodDescriptorType +) + +if sys.version_info >= (3, 14): + def get_type_hints( + obj: _get_type_hints_obj_allowed_types, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, + *, + format: Format | None = None, # Default: Format.VALUE + ) -> dict[str, Any]: ... # AnnotationForm + +else: + def get_type_hints( + obj: _get_type_hints_obj_allowed_types, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, + ) -> dict[str, Any]: ... # AnnotationForm + +def get_args(tp: Any) -> tuple[Any, ...]: ... # AnnotationForm + +@overload +def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... +@overload +def get_origin(tp: GenericAlias) -> type: ... +@overload +def get_origin(tp: Any) -> Any | None: ... # AnnotationForm + +@overload +def cast(typ: type[_T], val: Any) -> _T: ... +@overload +def cast(typ: str, val: Any) -> Any: ... +@overload +def cast(typ: object, val: Any) -> Any: ... + +if sys.version_info >= (3, 11): + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: Any, /) -> _T: ... # AnnotationForm + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, # on 3.11, runtime accepts it as part of kwargs + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), + **kwargs: Any, + ) -> IdentityFunction: ... + +# Type constructors + +# Obsolete, will be changed to a function. Use _typeshed._type_checker_internals.NamedTupleFallback instead. +class NamedTuple(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __match_args__: ClassVar[tuple[str, ...]] = ... + # __orig_bases__ sometimes exists on <3.12, but not consistently + # So we only add it to the stub on 3.12+. + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ... + @overload + @deprecated("Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15") + def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + + @final + @classmethod + def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] + @final + def _asdict(self) -> dict[str, Any]: ... + @final + def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] + if sys.version_info >= (3, 13): + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict +# Obsolete, use _typeshed._type_checker_internals.TypedDictFallback instead. +@type_check_only +class _TypedDict(Mapping[str, object], metaclass=ABCMeta): + __total__: ClassVar[bool] + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + # __orig_bases__ sometimes exists on <3.12, but not consistently, + # so we only add it to the stub on 3.12+ + if sys.version_info >= (3, 12): + __orig_bases__: ClassVar[tuple[Any, ...]] + if sys.version_info >= (3, 13): + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + if sys.version_info >= (3, 15): + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[Any] # AnnotationForm + + def copy(self) -> typing_extensions.Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: _Never, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: _Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: typing_extensions.Self, /) -> None: ... + def __delitem__(self, k: _Never) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + + @overload + def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of __or__ and __ior__ + def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] + +if sys.version_info >= (3, 14): + from annotationlib import ForwardRef as ForwardRef + + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: object = None, + globals: dict[str, Any] | None = None, + locals: Mapping[str, Any] | None = None, + type_params: tuple[TypeVar, ParamSpec, TypeVarTuple] | None = None, + format: Format | None = None, + ) -> Any: ... # AnnotationForm + +else: + @final + class ForwardRef(_Final): + __slots__ = ( + "__forward_arg__", + "__forward_code__", + "__forward_evaluated__", + "__forward_value__", + "__forward_is_argument__", + "__forward_is_class__", + "__forward_module__", + ) + __forward_arg__: str + __forward_code__: CodeType + __forward_evaluated__: bool + __forward_value__: Any | None # AnnotationForm + __forward_is_argument__: bool + __forward_is_class__: bool + __forward_module__: Any | None + + def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ... + + if sys.version_info >= (3, 13): + @overload + @deprecated( + "Failing to pass a value to the 'type_params' parameter of ForwardRef._evaluate() is deprecated, " + "as it leads to incorrect behaviour when evaluating a stringified annotation " + "that references a PEP 695 type parameter. It will be disallowed in Python 3.15." + ) + def _evaluate( + self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, *, recursive_guard: frozenset[str] + ) -> Any | None: ... # AnnotationForm + @overload + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...], + *, + recursive_guard: frozenset[str], + ) -> Any | None: ... # AnnotationForm + elif sys.version_info >= (3, 12): + def _evaluate( + self, + globalns: dict[str, Any] | None, + localns: Mapping[str, Any] | None, + type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None, + *, + recursive_guard: frozenset[str], + ) -> Any | None: ... # AnnotationForm + else: + def _evaluate( + self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, recursive_guard: frozenset[str] + ) -> Any | None: ... # AnnotationForm + + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + if sys.version_info >= (3, 11): + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +def is_typeddict(tp: object) -> bool: ... +def _type_repr(obj: object) -> str: ... + +if sys.version_info >= (3, 12): + _TypeParameter: typing_extensions.TypeAlias = ( + TypeVar + | typing_extensions.TypeVar + | ParamSpec + | typing_extensions.ParamSpec + | TypeVarTuple + | typing_extensions.TypeVarTuple + ) + + def override(method: _F, /) -> _F: ... + + @final + class TypeAliasType: + def __new__(cls, name: str, value: Any, *, type_params: tuple[_TypeParameter, ...] = ()) -> Self: ... + @property + def __value__(self) -> Any: ... # AnnotationForm + @property + def __type_params__(self) -> tuple[_TypeParameter, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... # AnnotationForm + @property + def __name__(self) -> str: ... + if sys.version_info >= (3, 15): + @property + def __qualname__(self) -> str: ... + # It's writable on types, but not on instances of TypeAliasType. + @property + def __module__(self) -> str | None: ... # type: ignore[override] + def __getitem__(self, parameters: Any, /) -> GenericAlias: ... # AnnotationForm + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + if sys.version_info >= (3, 14): + def __iter__(self) -> Any: ... # Unpack[Self] + @property + def evaluate_value(self) -> EvaluateFunc: ... + +if sys.version_info >= (3, 13): + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... + + @final + @type_check_only + class _NoDefaultType: ... + + NoDefault: _NoDefaultType + TypeIs: _SpecialForm + ReadOnly: _SpecialForm diff --git a/stdlib/typing_extensions.pyi b/stdlib/typing_extensions.pyi new file mode 100644 index 000000000000..d1f27b8e6fe5 --- /dev/null +++ b/stdlib/typing_extensions.pyi @@ -0,0 +1,746 @@ +import abc +import enum +import sys +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import AnnotationForm, IdentityFunction, Incomplete, Unused +from collections.abc import ( + AsyncGenerator as AsyncGenerator, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + Collection as Collection, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Reversible as Reversible, + Sequence as Sequence, + Sized as Sized, + ValuesView as ValuesView, +) +from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager +from re import Match as Match, Pattern as Pattern +from types import GenericAlias, ModuleType, UnionType +from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035 + IO as IO, + TYPE_CHECKING as TYPE_CHECKING, + AbstractSet as AbstractSet, + Any as Any, + AnyStr as AnyStr, + BinaryIO as BinaryIO, + Callable as Callable, + ChainMap as ChainMap, + ClassVar as ClassVar, + Concatenate as Concatenate, + Counter as Counter, + DefaultDict as DefaultDict, + Deque as Deque, + Dict as Dict, + ForwardRef as ForwardRef, + FrozenSet as FrozenSet, + Generic as Generic, + List as List, + NoReturn as NoReturn, + Optional as Optional, + ParamSpecArgs as ParamSpecArgs, + ParamSpecKwargs as ParamSpecKwargs, + Set as Set, + Text as Text, + TextIO as TextIO, + Tuple as Tuple, + Type as Type, + TypeAlias as TypeAlias, + TypeGuard as TypeGuard, + TypeVar as _TypeVar, + Union as Union, + _Alias, + _SpecialForm, + cast as cast, + is_typeddict as is_typeddict, + no_type_check as no_type_check, + overload as overload, + type_check_only, +) + +if sys.version_info >= (3, 14): + from _typeshed import EvaluateFunc + +# Please keep order the same as at runtime. +__all__ = [ + # Super-special typing primitives. + "Any", + "ClassVar", + "Concatenate", + "Final", + "LiteralString", + "ParamSpec", + "ParamSpecArgs", + "ParamSpecKwargs", + "Self", + "Type", + "TypeVar", + "TypeVarTuple", + "Unpack", + # ABCs (from collections.abc). + "Awaitable", + "AsyncIterator", + "AsyncIterable", + "Coroutine", + "AsyncGenerator", + "AsyncContextManager", + "Buffer", + "ChainMap", + # Concrete collection types. + "ContextManager", + "Counter", + "Deque", + "DefaultDict", + "NamedTuple", + "OrderedDict", + "TypedDict", + # Structural checks, a.k.a. protocols. + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsIndex", + "SupportsInt", + "SupportsRound", + "Reader", + "Writer", + # One-off things. + "Annotated", + "assert_never", + "assert_type", + "clear_overloads", + "dataclass_transform", + "deprecated", + "disjoint_base", + "Doc", + "evaluate_forward_ref", + "get_overloads", + "final", + "Format", + "get_annotations", + "get_args", + "get_origin", + "get_original_bases", + "get_protocol_members", + "get_type_hints", + "IntVar", + "is_protocol", + "is_typeddict", + "Literal", + "NewType", + "overload", + "override", + "Protocol", + "Sentinel", + "sentinel", + "reveal_type", + "runtime", + "runtime_checkable", + "Text", + "TypeAlias", + "TypeAliasType", + "TypeForm", + "TypeGuard", + "TypeIs", + "TYPE_CHECKING", + "type_repr", + "Never", + "NoReturn", + "ReadOnly", + "Required", + "NotRequired", + "NoDefault", + "NoExtraItems", + # Pure aliases, have always been in typing + "AbstractSet", + "AnyStr", + "BinaryIO", + "Callable", + "Collection", + "Container", + "Dict", + "ForwardRef", + "FrozenSet", + "Generator", + "Generic", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Optional", + "Pattern", + "Reversible", + "Sequence", + "Set", + "Sized", + "TextIO", + "Tuple", + "Union", + "ValuesView", + "cast", + "no_type_check", + "no_type_check_decorator", + # Added dynamically + "CapsuleType", +] + +_T = _TypeVar("_T") +_F = _TypeVar("_F", bound=Callable[..., Any]) +_TC = _TypeVar("_TC", bound=type[object]) +_T_co = _TypeVar("_T_co", covariant=True) # Any type covariant containers. +_T_contra = _TypeVar("_T_contra", contravariant=True) + +if sys.version_info < (3, 15): + def no_type_check_decorator(decorator: _F) -> _F: ... + +# Do not import (and re-export) Protocol or runtime_checkable from +# typing module because type checkers need to be able to distinguish +# typing.Protocol and typing_extensions.Protocol so they can properly +# warn users about potential runtime exceptions when using typing.Protocol +# on older versions of Python. +Protocol: _SpecialForm + +def runtime_checkable(cls: _TC) -> _TC: ... + +# This alias for above is kept here for backwards compatibility. +runtime = runtime_checkable +Final: _SpecialForm + +def final(f: _T) -> _T: ... +def disjoint_base(cls: _TC) -> _TC: ... + +Literal: _SpecialForm + +def IntVar(name: str) -> Any: ... # returns a new TypeVar + +# Kept as a distinct symbol to `typing.TypedDict` so that type checkers can more easily +# distinguish between the two on Python 3.14, on which `typing_extensions.TypedDict` +# exposes `__closed__` and `__extra_items__` but `typing.TypedDict` does not +TypedDict: _SpecialForm + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing._TypedDict/mypy_extensions._TypedDict +@type_check_only +class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + __total__: ClassVar[bool] + __orig_bases__: ClassVar[tuple[Any, ...]] + # PEP 705 + __readonly_keys__: ClassVar[frozenset[str]] + __mutable_keys__: ClassVar[frozenset[str]] + # PEP 728 + __closed__: ClassVar[bool | None] + __extra_items__: ClassVar[AnnotationForm] + def copy(self) -> Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: Never, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: Self, /) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + def __delitem__(self, k: Never) -> None: ... + + @overload + def __or__(self, value: Self, /) -> Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: Self, /) -> Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of `__ior__` and `__or__`: + # Since this module defines "Self" it is not recognized by Ruff as typing_extensions.Self + def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] + +OrderedDict = _Alias() + +if sys.version_info >= (3, 13): + from typing import get_type_hints as get_type_hints +else: + def get_type_hints( + obj: Any, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None, include_extras: bool = False + ) -> dict[str, AnnotationForm]: ... + +def get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: ... + +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... +@overload +def get_origin(tp: GenericAlias) -> type: ... +@overload +def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... +@overload +def get_origin(tp: AnnotationForm) -> AnnotationForm | None: ... + +Annotated: _SpecialForm +_AnnotatedAlias: Any # undocumented + +# New and changed things in 3.11 +if sys.version_info >= (3, 11): + from typing import ( + LiteralString as LiteralString, + NamedTuple as NamedTuple, + Never as Never, + NewType as NewType, + NotRequired as NotRequired, + Required as Required, + Self as Self, + Unpack as Unpack, + assert_never as assert_never, + assert_type as assert_type, + clear_overloads as clear_overloads, + dataclass_transform as dataclass_transform, + get_overloads as get_overloads, + reveal_type as reveal_type, + ) +else: + Self: _SpecialForm + Never: _SpecialForm + def reveal_type(obj: _T, /) -> _T: ... + def assert_never(arg: Never, /) -> Never: ... + def assert_type(val: _T, typ: AnnotationForm, /) -> _T: ... + def clear_overloads() -> None: ... + def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ... + + Required: _SpecialForm + NotRequired: _SpecialForm + LiteralString: _SpecialForm + Unpack: _SpecialForm + + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (), + **kwargs: object, + ) -> IdentityFunction: ... + + class NamedTuple(tuple[Any, ...]): + _field_defaults: ClassVar[dict[str, Any]] + _fields: ClassVar[tuple[str, ...]] + __orig_bases__: ClassVar[tuple[Any, ...]] + + @overload + def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ... + @overload + def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ... + + @classmethod + def _make(cls, iterable: Iterable[Any]) -> Self: ... # ty:ignore[invalid-type-form] + def _asdict(self) -> dict[str, Any]: ... + def _replace(self, **kwargs: Any) -> Self: ... # ty:ignore[invalid-type-form] + + class NewType: + def __init__(self, name: str, tp: AnnotationForm) -> None: ... + def __call__(self, obj: _T, /) -> _T: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type | NewType + __name__: str + +if sys.version_info >= (3, 12): + from collections.abc import Buffer as Buffer + from types import get_original_bases as get_original_bases + from typing import ( + SupportsAbs as SupportsAbs, + SupportsBytes as SupportsBytes, + SupportsComplex as SupportsComplex, + SupportsFloat as SupportsFloat, + SupportsIndex as SupportsIndex, + SupportsInt as SupportsInt, + SupportsRound as SupportsRound, + override as override, + ) +else: + def override(arg: _F, /) -> _F: ... + def get_original_bases(cls: type, /) -> tuple[Any, ...]: ... + + # mypy and pyright object to this being both ABC and Protocol. + # At runtime it inherits from ABC and is not a Protocol, but it is on the + # allowlist for use as a Protocol. + @runtime_checkable + class Buffer(Protocol, abc.ABC): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # pyrefly: ignore [invalid-inheritance] + # Not actually a Protocol at runtime; see + # https://github.com/python/typeshed/issues/10224 for why we're defining it this way + def __buffer__(self, flags: int, /) -> memoryview: ... + + @runtime_checkable + class SupportsInt(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __int__(self) -> int: ... + + @runtime_checkable + class SupportsFloat(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __float__(self) -> float: ... + + @runtime_checkable + class SupportsComplex(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __complex__(self) -> complex: ... + + @runtime_checkable + class SupportsBytes(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __bytes__(self) -> bytes: ... + + @runtime_checkable + class SupportsIndex(Protocol, metaclass=abc.ABCMeta): + __slots__ = () + @abc.abstractmethod + def __index__(self) -> int: ... + + @runtime_checkable + class SupportsAbs(Protocol[_T_co]): + __slots__ = () + @abc.abstractmethod + def __abs__(self) -> _T_co: ... + + @runtime_checkable + class SupportsRound(Protocol[_T_co]): + __slots__ = () + + @overload + @abc.abstractmethod + def __round__(self) -> int: ... + @overload + @abc.abstractmethod + def __round__(self, ndigits: int, /) -> _T_co: ... + +if sys.version_info >= (3, 14): + from io import Reader as Reader, Writer as Writer +else: + @runtime_checkable + class Reader(Protocol[_T_co]): + __slots__ = () + @abc.abstractmethod + def read(self, size: int = ..., /) -> _T_co: ... + + @runtime_checkable + class Writer(Protocol[_T_contra]): + __slots__ = () + @abc.abstractmethod + def write(self, data: _T_contra, /) -> int: ... + +if sys.version_info >= (3, 13): + from types import CapsuleType as CapsuleType + from typing import ( + NoDefault as NoDefault, + ParamSpec as ParamSpec, + ReadOnly as ReadOnly, + TypeIs as TypeIs, + TypeVar as TypeVar, + get_protocol_members as get_protocol_members, + is_protocol as is_protocol, + ) + from warnings import deprecated as deprecated +else: + def is_protocol(tp: type, /) -> bool: ... + def get_protocol_members(tp: type, /) -> frozenset[str]: ... + + @final + @type_check_only + class _NoDefaultType: ... + + NoDefault: _NoDefaultType + @final + class CapsuleType: ... + + class deprecated: + message: LiteralString + category: type[Warning] | None + stacklevel: int + def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... + def __call__(self, arg: _T, /) -> _T: ... + + @final + class TypeVar: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __constraints__(self) -> tuple[AnnotationForm, ...]: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... + def __init__( + self, + name: str, + *constraints: AnnotationForm, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + default: AnnotationForm = ..., + infer_variance: bool = False, + ) -> None: ... + def has_default(self) -> bool: ... + def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any) -> Any: ... + + @final + class ParamSpec: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... + def __init__( + self, + name: str, + *, + bound: None | AnnotationForm | str = None, + contravariant: bool = False, + covariant: bool = False, + default: AnnotationForm = ..., + ) -> None: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... + @property + def args(self) -> ParamSpecArgs: ... + @property + def kwargs(self) -> ParamSpecKwargs: ... + def has_default(self) -> bool: ... + def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... + + ReadOnly: _SpecialForm + TypeIs: _SpecialForm + +if sys.version_info >= (3, 15): + from typing import TypeVarTuple as TypeVarTuple +else: + @final + class TypeVarTuple: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> AnnotationForm | None: ... + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... + @property + def __default__(self) -> AnnotationForm: ... + if sys.version_info >= (3, 11): + def __new__( + cls, + name: str, + *, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + default: AnnotationForm = ..., + ) -> Self: ... + else: + def __init__( + self, + name: str, + *, + bound: AnnotationForm | None = None, + covariant: bool = False, + contravariant: bool = False, + infer_variance: bool = False, + default: AnnotationForm = ..., + ) -> None: ... + + def __iter__(self) -> Any: ... # Unpack[Self] + def has_default(self) -> bool: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Never, /) -> Never: ... + + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... + +# TypeAliasType was added in Python 3.12, but had significant changes in 3.14. +if sys.version_info >= (3, 14): + from typing import TypeAliasType as TypeAliasType +else: + @final + class TypeAliasType: + def __init__( + self, name: str, value: AnnotationForm, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = () + ) -> None: ... + @property + def __value__(self) -> AnnotationForm: ... + @property + def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ... + @property + # `__parameters__` can include special forms if a `TypeVarTuple` was + # passed as a `type_params` element to the constructor method. + def __parameters__(self) -> tuple[TypeVar | ParamSpec | AnnotationForm, ...]: ... + @property + def __name__(self) -> str: ... + # It's writable on types, but not on instances of TypeAliasType. + @property + def __module__(self) -> str | None: ... # type: ignore[override] + # Returns typing._GenericAlias, which isn't stubbed. + def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> AnnotationForm: ... + def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> Never: ... + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + +# PEP 727 +class Doc: + documentation: str + def __init__(self, documentation: str, /) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +# PEP 728 +@type_check_only +class _NoExtraItemsType: ... + +NoExtraItems: _NoExtraItemsType + +# PEP 747 +TypeForm: _SpecialForm + +# PEP 649/749 +if sys.version_info >= (3, 14): + from typing import evaluate_forward_ref as evaluate_forward_ref + + from annotationlib import Format as Format, get_annotations as get_annotations, type_repr as type_repr +else: + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Literal[Format.STRING], + ) -> dict[str, str]: ... + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Literal[Format.FORWARDREF], + ) -> dict[str, AnnotationForm | ForwardRef]: ... + @overload + def get_annotations( + obj: Any, # any object with __annotations__ or __annotate__ + *, + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + eval_str: bool = False, + format: Format = Format.VALUE, # noqa: Y011 + ) -> dict[str, AnnotationForm]: ... + + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Literal[Format.STRING], + _recursive_guard: Container[str] = ..., + ) -> str: ... + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Literal[Format.FORWARDREF], + _recursive_guard: Container[str] = ..., + ) -> AnnotationForm | ForwardRef: ... + @overload + def evaluate_forward_ref( + forward_ref: ForwardRef, + *, + owner: Callable[..., object] | type[object] | ModuleType | None = None, # any callable, class, or module + globals: Mapping[str, Any] | None = None, # value types depend on the key + locals: Mapping[str, Any] | None = None, # value types depend on the key + type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None, + format: Format | None = None, + _recursive_guard: Container[str] = ..., + ) -> AnnotationForm: ... + + def type_repr(value: object) -> str: ... + +# PEP 661 +if sys.version_info >= (3, 15): + from builtins import sentinel as sentinel +else: + class sentinel: + def __init__(self, name: str, /, *, repr: str | None = None) -> None: ... + __name__: str + __module__: str + if sys.version_info >= (3, 14): + # `other`` can be any type form legal for unions. + # `x | x` creates a `sentinel` instance if `x` is a sentinel, not a `UnionType` instance + def __or__(self, other: Any) -> UnionType | sentinel: ... + def __ror__(self, other: Any) -> UnionType | sentinel: ... + else: + # other can be any type form legal for unions + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + +Sentinel = sentinel diff --git a/stdlib/unicodedata.pyi b/stdlib/unicodedata.pyi new file mode 100644 index 000000000000..82a73181eed3 --- /dev/null +++ b/stdlib/unicodedata.pyi @@ -0,0 +1,94 @@ +import sys +from _typeshed import ReadOnlyBuffer +from collections.abc import Iterator +from typing import Final, Literal, TypeAlias, TypeVar, final, overload + +ucd_3_2_0: UCD +unidata_version: Final[str] + +_T = TypeVar("_T") + +_NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] + +def bidirectional(chr: str, /) -> str: ... +def category(chr: str, /) -> str: ... +def combining(chr: str, /) -> int: ... + +@overload +def decimal(chr: str, /) -> int: ... +@overload +def decimal(chr: str, default: _T, /) -> int | _T: ... + +def decomposition(chr: str, /) -> str: ... + +@overload +def digit(chr: str, /) -> int: ... +@overload +def digit(chr: str, default: _T, /) -> int | _T: ... + +_EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] + +def east_asian_width(chr: str, /) -> _EastAsianWidth: ... +def is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: ... + +if sys.version_info >= (3, 15): + def block(chr: str, /) -> str: ... + def extended_pictographic(chr: str, /) -> bool: ... + def grapheme_cluster_break(chr: str, /) -> str: ... + def indic_conjunct_break(chr: str, /) -> str: ... + def isxidstart(chr: str, /) -> bool: ... + def isxidcontinue(chr: str, /) -> bool: ... + def iter_graphemes(unistr: str, start: int = 0, end: int = sys.maxsize, /) -> Iterator[str]: ... + +def lookup(name: str | ReadOnlyBuffer, /) -> str: ... +def mirrored(chr: str, /) -> int: ... + +@overload +def name(chr: str, /) -> str: ... +@overload +def name(chr: str, default: _T, /) -> str | _T: ... + +def normalize(form: _NormalizationForm, unistr: str, /) -> str: ... + +@overload +def numeric(chr: str, /) -> float: ... +@overload +def numeric(chr: str, default: _T, /) -> float | _T: ... + +@final +class UCD: + # The methods below are constructed from the same array in C + # (unicodedata_functions) and hence identical to the functions above. + unidata_version: str + def bidirectional(self, chr: str, /) -> str: ... + def category(self, chr: str, /) -> str: ... + def combining(self, chr: str, /) -> int: ... + + @overload + def decimal(self, chr: str, /) -> int: ... + @overload + def decimal(self, chr: str, default: _T, /) -> int | _T: ... + + def decomposition(self, chr: str, /) -> str: ... + + @overload + def digit(self, chr: str, /) -> int: ... + @overload + def digit(self, chr: str, default: _T, /) -> int | _T: ... + + def east_asian_width(self, chr: str, /) -> _EastAsianWidth: ... + def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: ... + def lookup(self, name: str | ReadOnlyBuffer, /) -> str: ... + def mirrored(self, chr: str, /) -> int: ... + + @overload + def name(self, chr: str, /) -> str: ... + @overload + def name(self, chr: str, default: _T, /) -> str | _T: ... + + def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: ... + + @overload + def numeric(self, chr: str, /) -> float: ... + @overload + def numeric(self, chr: str, default: _T, /) -> float | _T: ... diff --git a/stdlib/unittest/__init__.pyi b/stdlib/unittest/__init__.pyi new file mode 100644 index 000000000000..546ea77bb4ca --- /dev/null +++ b/stdlib/unittest/__init__.pyi @@ -0,0 +1,63 @@ +import sys +from unittest.async_case import * + +from .case import ( + FunctionTestCase as FunctionTestCase, + SkipTest as SkipTest, + TestCase as TestCase, + addModuleCleanup as addModuleCleanup, + expectedFailure as expectedFailure, + skip as skip, + skipIf as skipIf, + skipUnless as skipUnless, +) +from .loader import TestLoader as TestLoader, defaultTestLoader as defaultTestLoader +from .main import TestProgram as TestProgram, main as main +from .result import TestResult as TestResult +from .runner import TextTestResult as TextTestResult, TextTestRunner as TextTestRunner +from .signals import ( + installHandler as installHandler, + registerResult as registerResult, + removeHandler as removeHandler, + removeResult as removeResult, +) +from .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite + +if sys.version_info >= (3, 11): + from .case import doModuleCleanups as doModuleCleanups, enterModuleContext as enterModuleContext + +__all__ = [ + "IsolatedAsyncioTestCase", + "TestResult", + "TestCase", + "TestSuite", + "TextTestRunner", + "TestLoader", + "FunctionTestCase", + "main", + "defaultTestLoader", + "SkipTest", + "skip", + "skipIf", + "skipUnless", + "expectedFailure", + "TextTestResult", + "installHandler", + "registerResult", + "removeResult", + "removeHandler", + "addModuleCleanup", +] + +if sys.version_info < (3, 13): + from .loader import findTestCases as findTestCases, getTestCaseNames as getTestCaseNames, makeSuite as makeSuite + + __all__ += ["getTestCaseNames", "makeSuite", "findTestCases"] + +if sys.version_info >= (3, 11): + __all__ += ["enterModuleContext", "doModuleCleanups"] + +if sys.version_info < (3, 12): + def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... + +def __dir__() -> set[str]: ... diff --git a/stdlib/unittest/_log.pyi b/stdlib/unittest/_log.pyi new file mode 100644 index 000000000000..da6ce5a5ac7a --- /dev/null +++ b/stdlib/unittest/_log.pyi @@ -0,0 +1,29 @@ +import logging +import sys +from types import TracebackType +from typing import ClassVar, Generic, NamedTuple, TypeVar +from unittest.case import TestCase, _BaseTestCaseContext + +_L = TypeVar("_L", None, _LoggingWatcher) + +class _LoggingWatcher(NamedTuple): + records: list[logging.LogRecord] + output: list[str] + +class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): + LOGGING_FORMAT: ClassVar[str] + logger_name: str + level: int + msg: None + no_logs: bool + if sys.version_info >= (3, 15): + def __init__( + self, test_case: TestCase, logger_name: str, level: int, no_logs: bool, formatter: logging.Formatter | None = None + ) -> None: ... + else: + def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... + + def __enter__(self) -> _L: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + ) -> bool | None: ... diff --git a/stdlib/unittest/async_case.pyi b/stdlib/unittest/async_case.pyi new file mode 100644 index 000000000000..77627a85ef19 --- /dev/null +++ b/stdlib/unittest/async_case.pyi @@ -0,0 +1,24 @@ +import sys +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable +from typing import ParamSpec, TypeVar + +from .case import TestCase + +if sys.version_info >= (3, 11): + from contextlib import AbstractAsyncContextManager + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +class IsolatedAsyncioTestCase(TestCase): + if sys.version_info >= (3, 13): + loop_factory: Callable[[], AbstractEventLoop] | None = None + + async def asyncSetUp(self) -> None: ... + async def asyncTearDown(self) -> None: ... + def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + if sys.version_info >= (3, 11): + async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... + + def __del__(self) -> None: ... diff --git a/stdlib/unittest/case.pyi b/stdlib/unittest/case.pyi new file mode 100644 index 000000000000..1d1206b7fc36 --- /dev/null +++ b/stdlib/unittest/case.pyi @@ -0,0 +1,352 @@ +import logging +import sys +import unittest.result +from _typeshed import SupportsDunderGE, SupportsDunderGT, SupportsDunderLE, SupportsDunderLT, SupportsRSub, SupportsSub +from builtins import _ClassInfo +from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet +from contextlib import AbstractContextManager +from re import Pattern +from types import GenericAlias, TracebackType +from typing import ( + Any, + AnyStr, + Final, + Generic, + ParamSpec, + Protocol, + SupportsAbs, + SupportsRound, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Never, Self +from unittest._log import _AssertLogsContext, _LoggingWatcher +from warnings import WarningMessage + +_T = TypeVar("_T") +_S = TypeVar("_S", bound=SupportsSub[Any, Any]) +_E = TypeVar("_E", bound=BaseException) +_FT = TypeVar("_FT", bound=Callable[..., Any]) +_SB = TypeVar("_SB", str, bytes, bytearray) +_P = ParamSpec("_P") + +DIFF_OMITTED: Final[str] + +class _BaseTestCaseContext: + test_case: TestCase + def __init__(self, test_case: TestCase) -> None: ... + +class _AssertRaisesBaseContext(_BaseTestCaseContext): + expected: type[BaseException] | tuple[type[BaseException], ...] + expected_regex: Pattern[str] | None + obj_name: str | None + msg: str | None + + def __init__( + self, + expected: type[BaseException] | tuple[type[BaseException], ...], + test_case: TestCase, + expected_regex: str | Pattern[str] | None = None, + ) -> None: ... + + # This returns Self if args is the empty list, and None otherwise. + # but it's not possible to construct an overload which expresses that + def handle(self, name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: ... + +def addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... +def doModuleCleanups() -> None: ... + +if sys.version_info >= (3, 11): + def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: ... + +def expectedFailure(test_item: _FT) -> _FT: ... +def skip(reason: str) -> Callable[[_FT], _FT]: ... +def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... +def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... + +class SkipTest(Exception): + def __init__(self, reason: str, /) -> None: ... + +@type_check_only +class _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ... + +class TestCase: + failureException: type[BaseException] + longMessage: bool + maxDiff: int | None + # undocumented + _testMethodName: str + # undocumented + _testMethodDoc: str + def __init__(self, methodName: str = "runTest") -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + @classmethod + def setUpClass(cls) -> None: ... + @classmethod + def tearDownClass(cls) -> None: ... + def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ... + def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... + def skipTest(self, reason: Any) -> Never: ... + def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ... + def debug(self) -> None: ... + if sys.version_info < (3, 11): + def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... + + def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: ... + def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: ... + def assertTrue(self, expr: Any, msg: Any = None) -> None: ... + def assertFalse(self, expr: Any, msg: Any = None) -> None: ... + def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: ... + def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: ... + def assertIsNone(self, obj: object, msg: Any = None) -> None: ... + def assertIsNotNone(self, obj: object, msg: Any = None) -> None: ... + def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ... + def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ... + def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... + def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... + + @overload + def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ... + + @overload + def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ... + + @overload + def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ... + + @overload + def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ... + @overload + def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ... + + # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp` + # are not using `ParamSpec` intentionally, + # because they might be used with explicitly wrong arg types to raise some error in tests. + @overload + def assertRaises( + self, + expected_exception: type[BaseException] | tuple[type[BaseException], ...], + callable: Callable[..., object], + *args: Any, + **kwargs: Any, + ) -> None: ... + @overload + def assertRaises( + self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ... + ) -> _AssertRaisesContext[_E]: ... + + @overload + def assertRaisesRegex( + self, + expected_exception: type[BaseException] | tuple[type[BaseException], ...], + expected_regex: str | Pattern[str], + callable: Callable[..., object], + *args: Any, + **kwargs: Any, + ) -> None: ... + @overload + def assertRaisesRegex( + self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ... + ) -> _AssertRaisesContext[_E]: ... + + @overload + def assertWarns( + self, + expected_warning: type[Warning] | tuple[type[Warning], ...], + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> None: ... + @overload + def assertWarns( + self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ... + ) -> _AssertWarnsContext: ... + + @overload + def assertWarnsRegex( + self, + expected_warning: type[Warning] | tuple[type[Warning], ...], + expected_regex: str | Pattern[str], + callable: Callable[_P, object], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> None: ... + @overload + def assertWarnsRegex( + self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ... + ) -> _AssertWarnsContext: ... + + if sys.version_info >= (3, 15): + def assertLogs( + self, + logger: str | logging.Logger | None = None, + level: int | str | None = None, + formatter: logging.Formatter | None = None, + ) -> _AssertLogsContext[_LoggingWatcher]: ... + else: + def assertLogs( + self, logger: str | logging.Logger | None = None, level: int | str | None = None + ) -> _AssertLogsContext[_LoggingWatcher]: ... + + def assertNoLogs( + self, logger: str | logging.Logger | None = None, level: int | str | None = None + ) -> _AssertLogsContext[None]: ... + + @overload + def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... + @overload + def assertAlmostEqual( + self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE + ) -> None: ... + @overload + def assertAlmostEqual( + self, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, + places: int | None = None, + msg: Any = None, + delta: None = None, + ) -> None: ... + @overload + def assertAlmostEqual( + self, + first: _T, + second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]], + places: int | None = None, + msg: Any = None, + delta: None = None, + ) -> None: ... + + @overload + def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... + @overload + def assertNotAlmostEqual( + self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE + ) -> None: ... + @overload + def assertNotAlmostEqual( + self, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, + places: int | None = None, + msg: Any = None, + delta: None = None, + ) -> None: ... + @overload + def assertNotAlmostEqual( + self, + first: _T, + second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]], + places: int | None = None, + msg: Any = None, + delta: None = None, + ) -> None: ... + + def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... + def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... + def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ... + def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ... + def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: ... + def assertSequenceEqual( + self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None + ) -> None: ... + def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: ... + def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: ... + def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: ... + # assertDictEqual accepts only true dict instances. We can't use that here, since that would make + # assertDictEqual incompatible with TypedDict. + def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ... + def fail(self, msg: Any = None) -> Never: ... + def countTestCases(self) -> int: ... + def defaultTestResult(self) -> unittest.result.TestResult: ... + def id(self) -> str: ... + def shortDescription(self) -> str | None: ... + def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + + if sys.version_info >= (3, 11): + def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ... + + def doCleanups(self) -> None: ... + @classmethod + def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + @classmethod + def doClassCleanups(cls) -> None: ... + + if sys.version_info >= (3, 11): + @classmethod + def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: ... + + def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented + def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented + if sys.version_info < (3, 12): + failUnlessEqual = assertEqual + assertEquals = assertEqual + failIfEqual = assertNotEqual + assertNotEquals = assertNotEqual + failUnless = assertTrue + assert_ = assertTrue + failIf = assertFalse + failUnlessRaises = assertRaises + failUnlessAlmostEqual = assertAlmostEqual + assertAlmostEquals = assertAlmostEqual + failIfAlmostEqual = assertNotAlmostEqual + assertNotAlmostEquals = assertNotAlmostEqual + assertRegexpMatches = assertRegex + assertNotRegexpMatches = assertNotRegex + assertRaisesRegexp = assertRaisesRegex + def assertDictContainsSubset( + self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None + ) -> None: ... + + # Runtime has *args, **kwargs, but will error if any are supplied + def __init_subclass__(cls, *args: Never, **kwargs: Never) -> None: ... + + if sys.version_info >= (3, 14): + def assertIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ... + def assertNotIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ... + def assertHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ... + def assertNotHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ... + def assertStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertNotStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + def assertNotEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ... + +class FunctionTestCase(TestCase): + def __init__( + self, + testFunc: Callable[[], object], + setUp: Callable[[], object] | None = None, + tearDown: Callable[[], object] | None = None, + description: str | None = None, + ) -> None: ... + def runTest(self) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + +class _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]): + exception: _E + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + ) -> bool: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class _AssertWarnsContext(_AssertRaisesBaseContext): + warning: WarningMessage + filename: str + lineno: int + warnings: list[WarningMessage] + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + ) -> None: ... diff --git a/stdlib/unittest/loader.pyi b/stdlib/unittest/loader.pyi new file mode 100644 index 000000000000..106004fadcc2 --- /dev/null +++ b/stdlib/unittest/loader.pyi @@ -0,0 +1,55 @@ +import sys +import unittest.case +import unittest.suite +from collections.abc import Callable, Sequence +from re import Pattern +from types import ModuleType +from typing import Any, Final, TypeAlias +from typing_extensions import deprecated + +_SortComparisonMethod: TypeAlias = Callable[[str, str], int] +_SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] + +VALID_MODULE_NAME: Final[Pattern[str]] + +class TestLoader: + errors: list[type[BaseException]] + testMethodPrefix: str + sortTestMethodsUsing: _SortComparisonMethod + testNamePatterns: list[str] | None + suiteClass: _SuiteClass + def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... + if sys.version_info >= (3, 12): + def loadTestsFromModule(self, module: ModuleType, *, pattern: str | None = None) -> unittest.suite.TestSuite: ... + else: + def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: str | None = None) -> unittest.suite.TestSuite: ... + + def loadTestsFromName(self, name: str, module: ModuleType | None = None) -> unittest.suite.TestSuite: ... + def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = None) -> unittest.suite.TestSuite: ... + def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ... + def discover( + self, start_dir: str, pattern: str = "test*.py", top_level_dir: str | None = None + ) -> unittest.suite.TestSuite: ... + def _match_path(self, path: str, full_path: str, pattern: str) -> bool: ... + +defaultTestLoader: TestLoader + +if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13.") + def getTestCaseNames( + testCaseClass: type[unittest.case.TestCase], + prefix: str, + sortUsing: _SortComparisonMethod = ..., + testNamePatterns: list[str] | None = None, + ) -> Sequence[str]: ... + @deprecated("Deprecated; removed in Python 3.13.") + def makeSuite( + testCaseClass: type[unittest.case.TestCase], + prefix: str = "test", + sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ..., + ) -> unittest.suite.TestSuite: ... + @deprecated("Deprecated; removed in Python 3.13.") + def findTestCases( + module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... + ) -> unittest.suite.TestSuite: ... diff --git a/stdlib/unittest/main.pyi b/stdlib/unittest/main.pyi new file mode 100644 index 000000000000..09b547cd1cd6 --- /dev/null +++ b/stdlib/unittest/main.pyi @@ -0,0 +1,74 @@ +import sys +import unittest.case +import unittest.loader +import unittest.result +import unittest.suite +from collections.abc import Iterable +from types import ModuleType +from typing import Any, Final, Protocol, type_check_only +from typing_extensions import deprecated + +MAIN_EXAMPLES: Final[str] +MODULE_EXAMPLES: Final[str] + +@type_check_only +class _TestRunner(Protocol): + def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase, /) -> unittest.result.TestResult: ... + +# not really documented +class TestProgram: + result: unittest.result.TestResult + module: ModuleType | None + verbosity: int + failfast: bool | None + catchbreak: bool | None + buffer: bool | None + progName: str | None + warnings: str | None + testNamePatterns: list[str] | None + if sys.version_info >= (3, 12): + durations: unittest.result._DurationsType | None + def __init__( + self, + module: ModuleType | str | None = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + durations: unittest.result._DurationsType | None = None, + ) -> None: ... + else: + def __init__( + self, + module: None | str | ModuleType = "__main__", + defaultTest: str | Iterable[str] | None = None, + argv: list[str] | None = None, + testRunner: type[_TestRunner] | _TestRunner | None = None, + testLoader: unittest.loader.TestLoader = ..., + exit: bool = True, + verbosity: int = 1, + failfast: bool | None = None, + catchbreak: bool | None = None, + buffer: bool | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + + if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13.") + def usageExit(self, msg: Any = None) -> None: ... + + def parseArgs(self, argv: list[str]) -> None: ... + def createTests(self, from_discovery: bool = False, Loader: unittest.loader.TestLoader | None = None) -> None: ... + def runTests(self) -> None: ... # undocumented + +main = TestProgram diff --git a/stdlib/unittest/mock.pyi b/stdlib/unittest/mock.pyi new file mode 100644 index 000000000000..1b6ab756d253 --- /dev/null +++ b/stdlib/unittest/mock.pyi @@ -0,0 +1,555 @@ +import sys +from _typeshed import MaybeNone +from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence +from contextlib import _GeneratorContextManager +from types import TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, ParamSpec, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") +_TT = TypeVar("_TT", bound=type[Any]) +_R = TypeVar("_R") +_F = TypeVar("_F", bound=Callable[..., Any]) +_AF = TypeVar("_AF", bound=Callable[..., Coroutine[Any, Any, Any]]) +_P = ParamSpec("_P") + +if sys.version_info >= (3, 13): + # ThreadingMock added in 3.13 + __all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "ThreadingMock", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", + ) +else: + __all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", + ) + +FILTER_DIR: bool # controls the way mock objects respond to `dir` function + +class _SentinelObject: + name: Any + def __init__(self, name: Any) -> None: ... + +class _Sentinel: + def __getattr__(self, name: str) -> Any: ... + +sentinel: _Sentinel +DEFAULT: Any + +_ArgsKwargs: TypeAlias = tuple[tuple[Any, ...], Mapping[str, Any]] +_NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]] +_CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs + +if sys.version_info >= (3, 12): + class _Call(tuple[Any, ...]): + def __new__( + cls, + value: _CallValue = (), + name: str | None = "", + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> Self: ... + def __init__( + self, + value: _CallValue = (), + name: str | None = None, + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: str) -> Any: ... + def __getattribute__(self, attr: str) -> Any: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> Mapping[str, Any]: ... + def call_list(self) -> Any: ... + +else: + @disjoint_base + class _Call(tuple[Any, ...]): + def __new__( + cls, + value: _CallValue = (), + name: str | None = "", + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> Self: ... + def __init__( + self, + value: _CallValue = (), + name: str | None = None, + parent: _Call | None = None, + two: bool = False, + from_kall: bool = True, + ) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __eq__(self, other: object) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: str) -> Any: ... + def __getattribute__(self, attr: str) -> Any: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> Mapping[str, Any]: ... + def call_list(self) -> Any: ... + +call: _Call + +class _CallList(list[_Call]): + def __contains__(self, value: Any) -> bool: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +# We subclass with "Any" because mocks are explicitly designed to stand in for other types, +# something that can't be expressed with our static type system. +class NonCallableMock(Base, Any): + if sys.version_info >= (3, 12): + def __new__( + cls, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state: Any | None = None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> Self: ... + else: + def __new__(cls, /, *args: Any, **kw: Any) -> Self: ... + + def __init__( + self, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state: Any | None = None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __delattr__(self, name: str) -> None: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def __dir__(self) -> list[str]: ... + def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(self) -> None: ... + def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... + def assert_called(self) -> None: ... + def assert_called_once(self) -> None: ... + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + def _extract_mock_name(self) -> str: ... + def _get_call_signature_from_name(self, name: str) -> Any: ... + def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ... + def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... + def configure_mock(self, **kwargs: Any) -> None: ... + return_value: Any + side_effect: Any + called: bool + call_count: int + call_args: _Call | MaybeNone + call_args_list: _CallList + method_calls: _CallList + mock_calls: _CallList + def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... + def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: ... + def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + if sys.version_info >= (3, 13): + def _calls_repr(self) -> str: ... + else: + def _calls_repr(self, prefix: str = "Calls") -> str: ... + +class CallableMixin(Base): + side_effect: Any + def __init__( + self, + spec: Any | None = None, + side_effect: Any | None = None, + return_value: Any = ..., + wraps: Any | None = None, + name: Any | None = None, + spec_set: Any | None = None, + parent: Any | None = None, + _spec_state: Any | None = None, + _new_name: Any = "", + _new_parent: Any | None = None, + **kwargs: Any, + ) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +class Mock(CallableMixin, NonCallableMock): ... + +class _patch(Generic[_T]): + attribute_name: Any + getter: Callable[[], Any] + attribute: str + new: _T + new_callable: Any + spec: Any + create: bool + has_local: Any + spec_set: Any + autospec: Any + kwargs: Mapping[str, Any] + additional_patchers: Any + # If new==DEFAULT, self is _patch[Any]. Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], + # but that's impossible with the current type system. + def __init__( + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Any | None, + create: bool, + spec_set: Any | None, + autospec: Any | None, + new_callable: Any | None, + kwargs: Mapping[str, Any], + *, + unsafe: bool = False, + ) -> None: ... + def copy(self) -> _patch[_T]: ... + + @overload + def __call__(self, func: _TT) -> _TT: ... + # If new==DEFAULT, this should add a MagicMock parameter to the function + # arguments. See the _patch_default_new class below for this functionality. + @overload + def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + + def decoration_helper( + self, patched: _patch[Any], args: Sequence[Any], keywargs: Any + ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... + def decorate_class(self, klass: _TT) -> _TT: ... + def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... + def get_original(self) -> tuple[Any, bool]: ... + target: Any + temp_original: Any + is_local: bool + def __enter__(self) -> _T: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + def start(self) -> _T: ... + def stop(self) -> None: ... + +# This class does not exist at runtime, it's a hack to make this work: +# @patch("foo") +# def bar(..., mock: MagicMock) -> None: ... +@type_check_only +class _patch_pass_arg(_patch[_T]): + @overload + def __call__(self, func: _TT) -> _TT: ... + # Can't use the following as ParamSpec is only allowed as last parameter: + # def __call__(self, func: Callable[_P, _R]) -> Callable[Concatenate[_P, MagicMock], _R]: ... + @overload + def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + +class _patch_dict: + in_dict: Any + values: Any + clear: Any + def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: object) -> Any: ... + def decorate_callable(self, f: _F) -> _F: ... + def decorate_async_callable(self, f: _AF) -> _AF: ... + def decorate_class(self, klass: Any) -> Any: ... + start: Any + stop: Any + +# This class does not exist at runtime, it's a hack to add methods to the +# patch() function. +@type_check_only +class _patcher: + TEST_PREFIX: str + dict: type[_patch_dict] + + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( # type: ignore[overload-overlap] + self, + target: str, + new: _T, + spec: Literal[False] | None = None, + create: bool = False, + spec_set: Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: None = None, + *, + unsafe: bool = False, + ) -> _patch[_T]: ... + @overload + def __call__( + self, + target: str, + *, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: Callable[..., _T], + unsafe: bool = False, + # kwargs are passed to new_callable + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + def __call__( + self, + target: str, + *, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + unsafe: bool = False, + # kwargs are passed to the MagicMock/AsyncMock constructor + **kwargs: Any, + ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + @staticmethod + def object( + target: Any, + attribute: str, + new: _T, + spec: Literal[False] | None = None, + create: bool = False, + spec_set: Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: None = None, + *, + unsafe: bool = False, + ) -> _patch[_T]: ... + @overload + @staticmethod + def object( + target: Any, + attribute: str, + *, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + new_callable: Callable[..., _T], + unsafe: bool = False, + # kwargs are passed to new_callable + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def object( + target: Any, + attribute: str, + *, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + unsafe: bool = False, + # kwargs are passed to the MagicMock/AsyncMock constructor + **kwargs: Any, + ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + + @overload + @staticmethod + def multiple( + target: Any | str, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None = None, + create: bool = False, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None = None, + autospec: Literal[False] | None = None, + *, + new_callable: Callable[..., _T], + # The kwargs must be DEFAULT + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def multiple( + target: Any | str, + # If not False or None, this is passed to new_callable + spec: Any | Literal[False] | None, + create: bool, + # If not False or None, this is passed to new_callable + spec_set: Any | Literal[False] | None, + autospec: Literal[False] | None, + new_callable: Callable[..., _T], + # The kwargs must be DEFAULT + **kwargs: Any, + ) -> _patch_pass_arg[_T]: ... + @overload + @staticmethod + def multiple( + target: Any | str, + spec: Any | bool | None = None, + create: bool = False, + spec_set: Any | bool | None = None, + autospec: Any | bool | None = None, + new_callable: None = None, + # The kwargs are the mock objects or DEFAULT + **kwargs: Any, + ) -> _patch[Any]: ... + + @staticmethod + def stopall() -> None: ... + +patch: _patcher + +class MagicMixin(Base): + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class NonCallableMagicMock(MagicMixin, NonCallableMock): ... +class MagicMock(MagicMixin, Mock): ... + +class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ... + def assert_awaited(self) -> None: ... + def assert_awaited_once(self) -> None: ... + def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: ... + def assert_not_awaited(self) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + await_count: int + await_args: _Call | None + await_args_list: _CallList + +class AsyncMagicMixin(MagicMixin): + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + +class MagicProxy(Base): + name: str + parent: Any + def __init__(self, name: str, parent: Any) -> None: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type: Any | None = None) -> Any: ... + +# See https://github.com/python/typeshed/issues/14701 +class _ANY(Any): + def __eq__(self, other: object) -> Literal[True]: ... + def __ne__(self, other: object) -> Literal[False]: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +ANY: _ANY + +def create_autospec( + spec: Any, + spec_set: Any = False, + instance: Any = False, + _parent: Any | None = None, + _name: Any | None = None, + *, + unsafe: bool = False, + **kwargs: Any, +) -> Any: ... + +class _SpecState: + spec: Any + ids: Any + spec_set: Any + parent: Any + instance: Any + name: Any + def __init__( + self, + spec: Any, + spec_set: Any = False, + parent: Any | None = None, + name: Any | None = None, + ids: Any | None = None, + instance: Any = False, + ) -> None: ... + +def mock_open(mock: Any | None = None, read_data: Any = "") -> Any: ... + +class PropertyMock(Mock): + def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... + def __set__(self, obj: Any, val: Any) -> None: ... + +if sys.version_info >= (3, 13): + class ThreadingMixin(Base): + DEFAULT_TIMEOUT: Final[float | None] = None + + def __init__(self, /, *args: Any, timeout: float | None | _SentinelObject = ..., **kwargs: Any) -> None: ... + # Same as `NonCallableMock.reset_mock.` + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + def wait_until_called(self, *, timeout: float | None | _SentinelObject = ...) -> None: ... + def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ... + + class ThreadingMock(ThreadingMixin, MagicMixin, Mock): ... + +def seal(mock: Any) -> None: ... diff --git a/stdlib/unittest/result.pyi b/stdlib/unittest/result.pyi new file mode 100644 index 000000000000..081f6e1328e4 --- /dev/null +++ b/stdlib/unittest/result.pyi @@ -0,0 +1,46 @@ +import sys +import unittest.case +from _typeshed import OptExcInfo +from collections.abc import Callable +from typing import Any, Final, TextIO, TypeAlias, TypeVar + +_F = TypeVar("_F", bound=Callable[..., Any]) +_DurationsType: TypeAlias = list[tuple[str, float]] + +STDOUT_LINE: Final[str] +STDERR_LINE: Final[str] + +# undocumented +def failfast(method: _F) -> _F: ... + +class TestResult: + errors: list[tuple[unittest.case.TestCase, str]] + failures: list[tuple[unittest.case.TestCase, str]] + skipped: list[tuple[unittest.case.TestCase, str]] + expectedFailures: list[tuple[unittest.case.TestCase, str]] + unexpectedSuccesses: list[unittest.case.TestCase] + shouldStop: bool + testsRun: int + buffer: bool + failfast: bool + tb_locals: bool + if sys.version_info >= (3, 12): + collectedDurations: _DurationsType + + def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ... + def printErrors(self) -> None: ... + def wasSuccessful(self) -> bool: ... + def stop(self) -> None: ... + def startTest(self, test: unittest.case.TestCase) -> None: ... + def stopTest(self, test: unittest.case.TestCase) -> None: ... + def startTestRun(self) -> None: ... + def stopTestRun(self) -> None: ... + def addError(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... + def addFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... + def addSuccess(self, test: unittest.case.TestCase) -> None: ... + def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ... + def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ... + def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ... + def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: ... + if sys.version_info >= (3, 12): + def addDuration(self, test: unittest.case.TestCase, elapsed: float) -> None: ... diff --git a/stdlib/unittest/runner.pyi b/stdlib/unittest/runner.pyi new file mode 100644 index 000000000000..3a2e08749e9b --- /dev/null +++ b/stdlib/unittest/runner.pyi @@ -0,0 +1,93 @@ +import sys +import unittest.case +import unittest.result +import unittest.suite +from _typeshed import SupportsFlush, SupportsWrite +from collections.abc import Callable, Iterable +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Never +from warnings import _ActionKind + +_ResultClassType: TypeAlias = Callable[[_TextTestStream, bool, int], TextTestResult[Any]] + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[str], SupportsFlush, Protocol): ... + +# All methods used by unittest.runner.TextTestResult's stream +@type_check_only +class _TextTestStream(_SupportsWriteAndFlush, Protocol): + def writeln(self, arg: str | None = None, /) -> None: ... + +# _WritelnDecorator should have all the same attrs as its stream param. +# But that's not feasible to do Generically +# We can expand the attributes if requested +class _WritelnDecorator: + def __init__(self, stream: _SupportsWriteAndFlush) -> None: ... + def writeln(self, arg: str | None = None) -> None: ... + def __getattr__(self, attr: str) -> Any: ... # Any attribute from the stream type passed to __init__ + # These attributes are prevented by __getattr__ + stream: Never + __getstate__: Never + # Methods proxied from the wrapped stream object via __getattr__ + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + +_StreamT = TypeVar("_StreamT", bound=_TextTestStream, default=_WritelnDecorator) + +class TextTestResult(unittest.result.TestResult, Generic[_StreamT]): + descriptions: bool # undocumented + dots: bool # undocumented + separator1: str + separator2: str + showAll: bool # undocumented + stream: _StreamT # undocumented + if sys.version_info >= (3, 12): + durations: int | None + def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int, *, durations: int | None = None) -> None: ... + else: + def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int) -> None: ... + + def getDescription(self, test: unittest.case.TestCase) -> str: ... + def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ... + +class TextTestRunner: + resultclass: _ResultClassType + stream: _WritelnDecorator + descriptions: bool + verbosity: int + failfast: bool + buffer: bool + warnings: _ActionKind | None + tb_locals: bool + + if sys.version_info >= (3, 12): + durations: int | None + def __init__( + self, + stream: _SupportsWriteAndFlush | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: _ActionKind | None = None, + *, + tb_locals: bool = False, + durations: int | None = None, + ) -> None: ... + else: + def __init__( + self, + stream: _SupportsWriteAndFlush | None = None, + descriptions: bool = True, + verbosity: int = 1, + failfast: bool = False, + buffer: bool = False, + resultclass: _ResultClassType | None = None, + warnings: str | None = None, + *, + tb_locals: bool = False, + ) -> None: ... + + def _makeResult(self) -> TextTestResult: ... + def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> TextTestResult: ... diff --git a/stdlib/unittest/signals.pyi b/stdlib/unittest/signals.pyi new file mode 100644 index 000000000000..928ab68ae65d --- /dev/null +++ b/stdlib/unittest/signals.pyi @@ -0,0 +1,15 @@ +import unittest.result +from collections.abc import Callable +from typing import ParamSpec, TypeVar, overload + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +def installHandler() -> None: ... +def registerResult(result: unittest.result.TestResult) -> None: ... +def removeResult(result: unittest.result.TestResult) -> bool: ... + +@overload +def removeHandler(method: None = None) -> None: ... +@overload +def removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/stdlib/unittest/suite.pyi b/stdlib/unittest/suite.pyi new file mode 100644 index 000000000000..b7cf75c68271 --- /dev/null +++ b/stdlib/unittest/suite.pyi @@ -0,0 +1,23 @@ +import unittest.case +import unittest.result +from collections.abc import Iterable, Iterator +from typing import ClassVar, TypeAlias + +_TestType: TypeAlias = unittest.case.TestCase | TestSuite + +class BaseTestSuite: + _tests: list[unittest.case.TestCase] + _removed_tests: int + def __init__(self, tests: Iterable[_TestType] = ()) -> None: ... + def __call__(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... + def addTest(self, test: _TestType) -> None: ... + def addTests(self, tests: Iterable[_TestType]) -> None: ... + def run(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ... + def debug(self) -> None: ... + def countTestCases(self) -> int: ... + def __iter__(self) -> Iterator[_TestType]: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +class TestSuite(BaseTestSuite): + def run(self, result: unittest.result.TestResult, debug: bool = False) -> unittest.result.TestResult: ... diff --git a/stdlib/unittest/util.pyi b/stdlib/unittest/util.pyi new file mode 100644 index 000000000000..11a6f903932f --- /dev/null +++ b/stdlib/unittest/util.pyi @@ -0,0 +1,39 @@ +from collections.abc import MutableSequence, Sequence +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, type_check_only + +@type_check_only +class _SupportsDunderLT(Protocol): + def __lt__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderGT(Protocol): + def __gt__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderLE(Protocol): + def __le__(self, other: Any, /) -> bool: ... + +@type_check_only +class _SupportsDunderGE(Protocol): + def __ge__(self, other: Any, /) -> bool: ... + +_T = TypeVar("_T") +_Mismatch: TypeAlias = tuple[_T, _T, int] +_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT + +_MAX_LENGTH: Final = 80 +_PLACEHOLDER_LEN: Final = 12 +_MIN_BEGIN_LEN: Final = 5 +_MIN_END_LEN: Final = 5 +_MIN_COMMON_LEN: Final = 5 +_MIN_DIFF_LEN: Final = 41 + +def _shorten(s: str, prefixlen: int, suffixlen: int) -> str: ... +def _common_shorten_repr(*args: str) -> tuple[str, ...]: ... +def safe_repr(obj: object, short: bool = False) -> str: ... +def strclass(cls: type) -> str: ... +def sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tuple[list[_T], list[_T]]: ... +def unorderable_list_difference(expected: MutableSequence[_T], actual: MutableSequence[_T]) -> tuple[list[_T], list[_T]]: ... +def three_way_cmp(x: _SupportsComparison, y: _SupportsComparison) -> Literal[-1, 0, 1]: ... +def _count_diff_all_purpose(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ... +def _count_diff_hashable(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ... diff --git a/stdlib/urllib/__init__.pyi b/stdlib/urllib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/urllib/error.pyi b/stdlib/urllib/error.pyi new file mode 100644 index 000000000000..6255f1ae7db0 --- /dev/null +++ b/stdlib/urllib/error.pyi @@ -0,0 +1,29 @@ +from email.message import Message +from typing import IO +from urllib.response import addinfourl + +__all__ = ["URLError", "HTTPError", "ContentTooShortError"] + +class URLError(OSError): + reason: str | BaseException + # The `filename` attribute only exists if it was provided to `__init__` and wasn't `None`. + filename: str + def __init__(self, reason: str | BaseException, filename: str | None = None) -> None: ... + +class HTTPError(URLError, addinfourl): + @property + def headers(self) -> Message: ... + @headers.setter + def headers(self, headers: Message) -> None: ... + + @property + def reason(self) -> str: ... # type: ignore[override] + code: int + msg: str + hdrs: Message + fp: IO[bytes] + def __init__(self, url: str, code: int, msg: str, hdrs: Message, fp: IO[bytes] | None) -> None: ... + +class ContentTooShortError(URLError): + content: tuple[str, Message] + def __init__(self, message: str, content: tuple[str, Message]) -> None: ... diff --git a/stdlib/urllib/parse.pyi b/stdlib/urllib/parse.pyi new file mode 100644 index 000000000000..b83a0f4e8678 --- /dev/null +++ b/stdlib/urllib/parse.pyi @@ -0,0 +1,354 @@ +import sys +from collections.abc import Iterable, Mapping, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Final, Generic, Literal, NamedTuple, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVar + +__all__ = [ + "urlparse", + "urlunparse", + "urljoin", + "urldefrag", + "urlsplit", + "urlunsplit", + "urlencode", + "parse_qs", + "parse_qsl", + "quote", + "quote_plus", + "quote_from_bytes", + "unquote", + "unquote_plus", + "unquote_to_bytes", + "DefragResult", + "ParseResult", + "SplitResult", + "DefragResultBytes", + "ParseResultBytes", + "SplitResultBytes", +] + +uses_relative: Final[list[str]] +uses_netloc: Final[list[str]] +uses_params: Final[list[str]] +non_hierarchical: Final[list[str]] +uses_query: Final[list[str]] +uses_fragment: Final[list[str]] +scheme_chars: Final[str] +if sys.version_info < (3, 11): + MAX_CACHE_SIZE: Final[int] + +_ResultStrT = TypeVar("_ResultStrT", str, bytes) +_ResultComponentT = TypeVar("_ResultComponentT", str, bytes, str | None, bytes | None) +_StrComponentT = TypeVar("_StrComponentT", str, str | None, default=str) +_BytesComponentT = TypeVar("_BytesComponentT", bytes, bytes | None, default=bytes) + +class _ResultMixinStr: + __slots__ = () + def encode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinBytes: ... + +class _ResultMixinBytes: + __slots__ = () + def decode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinStr: ... + +class _NetlocResultMixinBase(Generic[AnyStr]): + __slots__ = () + @property + def username(self) -> AnyStr | None: ... + @property + def password(self) -> AnyStr | None: ... + @property + def hostname(self) -> AnyStr | None: ... + @property + def port(self) -> int | None: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): + __slots__ = () + +class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): + __slots__ = () + +# Need to duplicate the whole class because mypy rejects version-specific +# branches in namedtuple bodies. +if sys.version_info >= (3, 15): + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, _StrComponentT], _ResultMixinStr, Generic[_StrComponentT]): ... + class SplitResult(_SplitResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + class ParseResult(_ParseResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, _BytesComponentT], _ResultMixinBytes, Generic[_BytesComponentT]): ... + class SplitResultBytes(_SplitResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... + class ParseResultBytes(_ParseResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... + +else: + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, str], _ResultMixinStr): + def geturl(self) -> str: ... + + class SplitResult(_SplitResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... + + class ParseResult(_ParseResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... + + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, bytes], _ResultMixinBytes): + def geturl(self) -> bytes: ... + + class SplitResultBytes(_SplitResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... + + class ParseResultBytes(_ParseResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... + +def parse_qs( + qs: AnyStr | None, + keep_blank_values: bool = False, + strict_parsing: bool = False, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", +) -> dict[AnyStr, list[AnyStr]]: ... +def parse_qsl( + qs: AnyStr | None, + keep_blank_values: bool = False, + strict_parsing: bool = False, + encoding: str = "utf-8", + errors: str = "replace", + max_num_fields: int | None = None, + separator: str = "&", +) -> list[tuple[AnyStr, AnyStr]]: ... + +@overload +def quote(string: str, safe: str | Iterable[int] = "/", encoding: str | None = None, errors: str | None = None) -> str: ... +@overload +def quote(string: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + +def quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + +@overload +def quote_plus(string: str, safe: str | Iterable[int] = "", encoding: str | None = None, errors: str | None = None) -> str: ... +@overload +def quote_plus(string: bytes | bytearray, safe: str | Iterable[int] = "") -> str: ... + +def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace") -> str: ... +def unquote_to_bytes(string: str | bytes | bytearray) -> bytes: ... +def unquote_plus(string: str, encoding: str = "utf-8", errors: str = "replace") -> str: ... + +@overload +def urldefrag(url: str) -> DefragResult: ... +@overload +def urldefrag(url: bytes | bytearray | None) -> DefragResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urldefrag(url: str, *, missing_as_none: Literal[True]) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: str, *, missing_as_none: Literal[False] = False) -> DefragResult[str]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[True]) -> DefragResultBytes[bytes | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[False] = False) -> DefragResultBytes[bytes]: ... + @overload + def urldefrag(url: str, *, missing_as_none: bool) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: bool) -> DefragResultBytes[bytes | None]: ... + +# The values are passed through `str()` (unless they are bytes), so anything is valid. +_QueryType: TypeAlias = ( + Mapping[str, object] + | Mapping[bytes, object] + | Mapping[str | bytes, object] + | Mapping[str, Sequence[object]] + | Mapping[bytes, Sequence[object]] + | Mapping[str | bytes, Sequence[object]] + | Sequence[tuple[str | bytes, object]] + | Sequence[tuple[str | bytes, Sequence[object]]] +) + +@type_check_only +class _QuoteVia(Protocol): + @overload + def __call__(self, string: str, safe: str | bytes, encoding: str, errors: str, /) -> str: ... + @overload + def __call__(self, string: bytes, safe: str | bytes, /) -> str: ... + +def urlencode( + query: _QueryType, + doseq: bool = False, + safe: str | bytes = "", + encoding: str | None = None, + errors: str | None = None, + quote_via: _QuoteVia = ..., +) -> str: ... +def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: ... + +@overload +def urlparse(url: str, scheme: str = "", allow_fragments: bool = True) -> ParseResult: ... +@overload +def urlparse( + url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True +) -> ParseResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> ParseResult[str]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> ParseResultBytes[bytes | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> ParseResultBytes[bytes]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: bool, + ) -> ParseResultBytes[bytes | None]: ... + +@overload +def urlsplit(url: str, scheme: str = "", allow_fragments: bool = True) -> SplitResult: ... + +if sys.version_info >= (3, 11): + @overload + def urlsplit( + url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True + ) -> SplitResultBytes: ... +else: + @overload + def urlsplit( + url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True + ) -> SplitResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> SplitResult[str]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> SplitResultBytes[bytes | None]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> SplitResultBytes[bytes]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResultBytes[bytes | None]: ... + +if sys.version_info >= (3, 15): + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ... + +if sys.version_info >= (3, 15): + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ... + +def unwrap(url: str) -> str: ... diff --git a/stdlib/urllib/request.pyi b/stdlib/urllib/request.pyi new file mode 100644 index 000000000000..17a283321df4 --- /dev/null +++ b/stdlib/urllib/request.pyi @@ -0,0 +1,443 @@ +import ssl +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsRead +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from email.message import Message +from http.client import HTTPConnection, HTTPMessage, HTTPResponse +from http.cookiejar import CookieJar +from re import Pattern +from typing import IO, Any, ClassVar, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated +from urllib.error import HTTPError as HTTPError +from urllib.response import addclosehook, addinfourl + +__all__ = [ + "Request", + "OpenerDirector", + "BaseHandler", + "HTTPDefaultErrorHandler", + "HTTPRedirectHandler", + "HTTPCookieProcessor", + "ProxyHandler", + "HTTPPasswordMgr", + "HTTPPasswordMgrWithDefaultRealm", + "HTTPPasswordMgrWithPriorAuth", + "AbstractBasicAuthHandler", + "HTTPBasicAuthHandler", + "ProxyBasicAuthHandler", + "AbstractDigestAuthHandler", + "HTTPDigestAuthHandler", + "ProxyDigestAuthHandler", + "HTTPHandler", + "FileHandler", + "FTPHandler", + "CacheFTPHandler", + "DataHandler", + "UnknownHandler", + "HTTPErrorProcessor", + "urlopen", + "install_opener", + "build_opener", + "pathname2url", + "url2pathname", + "getproxies", + "urlretrieve", + "urlcleanup", + "HTTPSHandler", +] +if sys.version_info < (3, 14): + __all__ += ["URLopener", "FancyURLopener"] + +_T = TypeVar("_T") + +# The actual type is `addinfourl | HTTPResponse`, but users would need to use `typing.cast` or `isinstance` to narrow the type, +# so we use `Any` instead. +# See +# - https://github.com/python/typeshed/pull/15042 +# - https://github.com/python/typing/issues/566 +_UrlopenRet: TypeAlias = Any + +_DataType: TypeAlias = ReadableBuffer | SupportsRead[bytes] | Iterable[bytes] | None + +if sys.version_info >= (3, 13): + def urlopen( + url: str | Request, data: _DataType | None = None, timeout: float | None = ..., *, context: ssl.SSLContext | None = None + ) -> _UrlopenRet: ... + +else: + @overload + def urlopen( + url: str | Request, + data: _DataType | None = None, + timeout: float | None = ..., + *, + cafile: None = None, + capath: None = None, + cadefault: Literal[False] = False, + context: ssl.SSLContext | None = None, + ) -> _UrlopenRet: ... + @overload + @deprecated( + "The `cafile`, `capath`, `cadefault` parameters are deprecated since Python 3.6; " + "removed in Python 3.13. Use `context` parameter instead." + ) + def urlopen( + url: str | Request, + data: _DataType | None = None, + timeout: float | None = ..., + *, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadefault: bool = False, + context: None = None, + ) -> _UrlopenRet: ... + +def install_opener(opener: OpenerDirector | None) -> None: ... +def build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDirector: ... + +if sys.version_info >= (3, 14): + def url2pathname(url: str, *, require_scheme: bool = False, resolve_host: bool = False) -> str: ... + def pathname2url(pathname: str, *, add_scheme: bool = False) -> str: ... + +else: + if sys.platform == "win32": + from nturl2path import pathname2url as pathname2url, url2pathname as url2pathname + else: + def url2pathname(pathname: str) -> str: ... + def pathname2url(pathname: str) -> str: ... + +def getproxies() -> dict[str, str]: ... +def getproxies_environment() -> dict[str, str]: ... +def parse_http_list(s: str) -> list[str]: ... +def parse_keqv_list(l: list[str]) -> dict[str, str]: ... + +if sys.platform == "win32" or sys.platform == "darwin": + def proxy_bypass(host: str) -> Any: ... # undocumented + +else: + def proxy_bypass(host: str, proxies: Mapping[str, str] | None = None) -> Any: ... # undocumented + +class Request: + @property + def full_url(self) -> str: ... + @full_url.setter + def full_url(self, value: str) -> None: ... + @full_url.deleter + def full_url(self) -> None: ... + + type: str + host: str + origin_req_host: str + selector: str + data: _DataType + headers: MutableMapping[str, str] + unredirected_hdrs: dict[str, str] + unverifiable: bool + method: str | None + timeout: float | None # Undocumented, only set after __init__() by OpenerDirector.open() + def __init__( + self, + url: str, + data: _DataType = None, + headers: MutableMapping[str, str] = {}, + origin_req_host: str | None = None, + unverifiable: bool = False, + method: str | None = None, + ) -> None: ... + def get_method(self) -> str: ... + def add_header(self, key: str, val: str) -> None: ... + def add_unredirected_header(self, key: str, val: str) -> None: ... + def has_header(self, header_name: str) -> bool: ... + def remove_header(self, header_name: str) -> None: ... + def get_full_url(self) -> str: ... + def set_proxy(self, host: str, type: str) -> None: ... + + @overload + def get_header(self, header_name: str) -> str | None: ... + @overload + def get_header(self, header_name: str, default: _T) -> str | _T: ... + + def header_items(self) -> list[tuple[str, str]]: ... + def has_proxy(self) -> bool: ... + +class OpenerDirector: + addheaders: list[tuple[str, str]] + def add_handler(self, handler: BaseHandler) -> None: ... + def open(self, fullurl: str | Request, data: _DataType = None, timeout: float | None = ...) -> _UrlopenRet: ... + def error(self, proto: str, *args: Any) -> _UrlopenRet: ... + def close(self) -> None: ... + +class BaseHandler: + handler_order: ClassVar[int] + parent: OpenerDirector + def add_parent(self, parent: OpenerDirector) -> None: ... + def close(self) -> None: ... + def __lt__(self, other: object) -> bool: ... + +class HTTPDefaultErrorHandler(BaseHandler): + def http_error_default( + self, req: Request, fp: IO[bytes], code: int, msg: str, hdrs: HTTPMessage + ) -> HTTPError: ... # undocumented + +class HTTPRedirectHandler(BaseHandler): + max_redirections: ClassVar[int] # undocumented + max_repeats: ClassVar[int] # undocumented + inf_msg: ClassVar[str] # undocumented + def redirect_request( + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage, newurl: str + ) -> Request | None: ... + def http_error_301(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + def http_error_302(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + def http_error_303(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + def http_error_307(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + if sys.version_info >= (3, 11): + def http_error_308( + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage + ) -> _UrlopenRet | None: ... + +class HTTPCookieProcessor(BaseHandler): + cookiejar: CookieJar + def __init__(self, cookiejar: CookieJar | None = None) -> None: ... + def http_request(self, request: Request) -> Request: ... # undocumented + def http_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def https_request(self, request: Request) -> Request: ... # undocumented + def https_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + +class ProxyHandler(BaseHandler): + def __init__(self, proxies: dict[str, str] | None = None) -> None: ... + def proxy_open(self, req: Request, proxy: str, type: str) -> _UrlopenRet | None: ... # undocumented + # TODO: add a method for every (common) proxy protocol + +class HTTPPasswordMgr: + def add_password(self, realm: str, uri: str | Sequence[str], user: str, passwd: str) -> None: ... + def find_user_password(self, realm: str, authuri: str) -> tuple[str | None, str | None]: ... + def is_suburi(self, base: str, test: str) -> bool: ... # undocumented + def reduce_uri(self, uri: str, default_port: bool = True) -> tuple[str, str]: ... # undocumented + +class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): + def add_password(self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str) -> None: ... + def find_user_password(self, realm: str | None, authuri: str) -> tuple[str | None, str | None]: ... + +class HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm): + def add_password( + self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str, is_authenticated: bool = False + ) -> None: ... + def update_authenticated(self, uri: str | Sequence[str], is_authenticated: bool = False) -> None: ... + def is_authenticated(self, authuri: str) -> bool | None: ... + +class AbstractBasicAuthHandler: + rx: ClassVar[Pattern[str]] # undocumented + passwd: HTTPPasswordMgr + add_password: Callable[[str, str | Sequence[str], str, str], None] + def __init__(self, password_mgr: HTTPPasswordMgr | None = None) -> None: ... + def http_error_auth_reqed(self, authreq: str, host: str, req: Request, headers: HTTPMessage) -> None: ... + def http_request(self, req: Request) -> Request: ... # undocumented + def http_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def https_request(self, req: Request) -> Request: ... # undocumented + def https_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ... # undocumented + def retry_http_basic_auth(self, host: str, req: Request, realm: str) -> _UrlopenRet | None: ... # undocumented + +class HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: ClassVar[str] # undocumented + def http_error_401(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + +class ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler): + auth_header: ClassVar[str] + def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + +class AbstractDigestAuthHandler: + def __init__(self, passwd: HTTPPasswordMgr | None = None) -> None: ... + def reset_retry_count(self) -> None: ... + def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: HTTPMessage) -> None: ... + def retry_http_digest_auth(self, req: Request, auth: str) -> _UrlopenRet | None: ... + def get_cnonce(self, nonce: str) -> str: ... + def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str | None: ... + def get_algorithm_impls(self, algorithm: str) -> tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_entity_digest(self, data: ReadableBuffer | None, chal: Mapping[str, str]) -> str | None: ... + +class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: ClassVar[str] # undocumented + def http_error_401(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + +class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): + auth_header: ClassVar[str] # undocumented + def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + +@type_check_only +class _HTTPConnectionProtocol(Protocol): + def __call__( + self, + host: str, + /, + *, + port: int | None = ..., + timeout: float = ..., + source_address: tuple[str, int] | None = ..., + blocksize: int = ..., + ) -> HTTPConnection: ... + +class AbstractHTTPHandler(BaseHandler): # undocumented + if sys.version_info >= (3, 12): + def __init__(self, debuglevel: int | None = None) -> None: ... + else: + def __init__(self, debuglevel: int = 0) -> None: ... + + def set_http_debuglevel(self, level: int) -> None: ... + def do_request_(self, request: Request) -> Request: ... + def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: ... + +class HTTPHandler(AbstractHTTPHandler): + def http_open(self, req: Request) -> HTTPResponse: ... + def http_request(self, request: Request) -> Request: ... # undocumented + +class HTTPSHandler(AbstractHTTPHandler): + if sys.version_info >= (3, 12): + def __init__( + self, debuglevel: int | None = None, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + else: + def __init__( + self, debuglevel: int = 0, context: ssl.SSLContext | None = None, check_hostname: bool | None = None + ) -> None: ... + + def https_open(self, req: Request) -> HTTPResponse: ... + def https_request(self, request: Request) -> Request: ... # undocumented + +class FileHandler(BaseHandler): + names: ClassVar[tuple[str, ...] | None] # undocumented + def file_open(self, req: Request) -> addinfourl: ... + def get_names(self) -> tuple[str, ...]: ... # undocumented + def open_local_file(self, req: Request) -> addinfourl: ... # undocumented + +class DataHandler(BaseHandler): + def data_open(self, req: Request) -> addinfourl: ... + +class ftpwrapper: # undocumented + def __init__( + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float | None = None, persistent: bool = True + ) -> None: ... + def close(self) -> None: ... + def endtransfer(self) -> None: ... + def file_close(self) -> None: ... + def init(self) -> None: ... + def real_close(self) -> None: ... + def retrfile(self, file: str, type: str) -> tuple[addclosehook, int | None]: ... + +class FTPHandler(BaseHandler): + def ftp_open(self, req: Request) -> addinfourl: ... + def connect_ftp( + self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float + ) -> ftpwrapper: ... # undocumented + +class CacheFTPHandler(FTPHandler): + def setTimeout(self, t: float) -> None: ... + def setMaxConns(self, m: int) -> None: ... + def check_cache(self) -> None: ... # undocumented + def clear_cache(self) -> None: ... # undocumented + +class UnknownHandler(BaseHandler): + def unknown_open(self, req: Request) -> Never: ... + +class HTTPErrorProcessor(BaseHandler): + def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... + def https_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... + +def urlretrieve( + url: str, + filename: StrOrBytesPath | None = None, + reporthook: Callable[[int, int, int], object] | None = None, + data: _DataType = None, +) -> tuple[str, HTTPMessage]: ... +def urlcleanup() -> None: ... + +if sys.version_info < (3, 14): + @deprecated("Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.") + class URLopener: + version: ClassVar[str] + def __init__(self, proxies: dict[str, str] | None = None, **x509: str) -> None: ... + def open(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... + def open_unknown(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... + def retrieve( + self, + url: str, + filename: str | None = None, + reporthook: Callable[[int, int, int], object] | None = None, + data: ReadableBuffer | None = None, + ) -> tuple[str, Message | None]: ... + def addheader(self, *args: tuple[str, str]) -> None: ... # undocumented + def cleanup(self) -> None: ... # undocumented + def close(self) -> None: ... # undocumented + def http_error( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = None + ) -> _UrlopenRet: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage + ) -> _UrlopenRet: ... # undocumented + def open_data(self, url: str, data: ReadableBuffer | None = None) -> addinfourl: ... # undocumented + def open_file(self, url: str) -> addinfourl: ... # undocumented + def open_ftp(self, url: str) -> addinfourl: ... # undocumented + def open_http(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... # undocumented + def open_https(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ... # undocumented + def open_local_file(self, url: str) -> addinfourl: ... # undocumented + def open_unknown_proxy(self, proxy: str, fullurl: str, data: ReadableBuffer | None = None) -> None: ... # undocumented + def __del__(self) -> None: ... + + @deprecated("Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.") + class FancyURLopener(URLopener): + def prompt_user_passwd(self, host: str, realm: str) -> tuple[str, str]: ... + def get_user_passwd(self, host: str, realm: str, clear_cache: int = 0) -> tuple[str, str]: ... # undocumented + def http_error_301( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_302( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_303( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_307( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + if sys.version_info >= (3, 11): + def http_error_308( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + + def http_error_401( + self, + url: str, + fp: IO[bytes], + errcode: int, + errmsg: str, + headers: HTTPMessage, + data: ReadableBuffer | None = None, + retry: bool = False, + ) -> _UrlopenRet | None: ... # undocumented + def http_error_407( + self, + url: str, + fp: IO[bytes], + errcode: int, + errmsg: str, + headers: HTTPMessage, + data: ReadableBuffer | None = None, + retry: bool = False, + ) -> _UrlopenRet | None: ... # undocumented + def http_error_default( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage + ) -> addinfourl: ... # undocumented + def redirect_internal( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None + ) -> _UrlopenRet | None: ... # undocumented + def retry_http_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_https_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_proxy_http_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented + def retry_proxy_https_basic_auth( + self, url: str, realm: str, data: ReadableBuffer | None = None + ) -> _UrlopenRet | None: ... # undocumented diff --git a/stdlib/urllib/response.pyi b/stdlib/urllib/response.pyi new file mode 100644 index 000000000000..459b9d1bbdda --- /dev/null +++ b/stdlib/urllib/response.pyi @@ -0,0 +1,45 @@ +import tempfile +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable +from email.message import Message +from types import TracebackType +from typing import IO, Any +from typing_extensions import deprecated + +__all__ = ["addbase", "addclosehook", "addinfo", "addinfourl"] + +class addbase(tempfile._TemporaryFileWrapper[bytes]): + fp: IO[bytes] + def __init__(self, fp: IO[bytes]) -> None: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + # These methods don't actually exist, but the class inherits at runtime from + # tempfile._TemporaryFileWrapper, which uses __getattr__ to delegate to the + # underlying file object. To satisfy the BinaryIO interface, we pretend that this + # class has these additional methods. + def write(self, s: ReadableBuffer) -> int: ... + def writelines(self, lines: Iterable[ReadableBuffer]) -> None: ... + +class addclosehook(addbase): + closehook: Callable[..., object] + hookargs: tuple[Any, ...] + def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ... + +class addinfo(addbase): + headers: Message + def __init__(self, fp: IO[bytes], headers: Message) -> None: ... + def info(self) -> Message: ... + +class addinfourl(addinfo): + url: str + code: int | None # Deprecated since Python 3.9. Use `addinfourl.status` attribute instead. + @property + def status(self) -> int | None: ... + def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = None) -> None: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.url` attribute instead.") + def geturl(self) -> str: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.headers` attribute instead.") + def info(self) -> Message: ... + @deprecated("Deprecated since Python 3.9. Use `addinfourl.status` attribute instead.") + def getcode(self) -> int | None: ... diff --git a/stdlib/urllib/robotparser.pyi b/stdlib/urllib/robotparser.pyi new file mode 100644 index 000000000000..14ceef550dab --- /dev/null +++ b/stdlib/urllib/robotparser.pyi @@ -0,0 +1,20 @@ +from collections.abc import Iterable +from typing import NamedTuple + +__all__ = ["RobotFileParser"] + +class RequestRate(NamedTuple): + requests: int + seconds: int + +class RobotFileParser: + def __init__(self, url: str = "") -> None: ... + def set_url(self, url: str) -> None: ... + def read(self) -> None: ... + def parse(self, lines: Iterable[str]) -> None: ... + def can_fetch(self, useragent: str, url: str) -> bool: ... + def mtime(self) -> int: ... + def modified(self) -> None: ... + def crawl_delay(self, useragent: str) -> str | None: ... + def request_rate(self, useragent: str) -> RequestRate | None: ... + def site_maps(self) -> list[str] | None: ... diff --git a/stdlib/uu.pyi b/stdlib/uu.pyi new file mode 100644 index 000000000000..62bf6cb05f59 --- /dev/null +++ b/stdlib/uu.pyi @@ -0,0 +1,12 @@ +from typing import BinaryIO, TypeAlias + +__all__ = ["Error", "encode", "decode"] + +_File: TypeAlias = str | BinaryIO + +class Error(Exception): ... + +def encode( + in_file: _File, out_file: _File, name: str | None = None, mode: int | None = None, *, backtick: bool = False +) -> None: ... +def decode(in_file: _File, out_file: _File | None = None, mode: int | None = None, quiet: bool = False) -> None: ... diff --git a/stdlib/uuid.pyi b/stdlib/uuid.pyi new file mode 100644 index 000000000000..1b5d0c1fbf5a --- /dev/null +++ b/stdlib/uuid.pyi @@ -0,0 +1,106 @@ +import builtins +import sys +from _typeshed import Unused +from enum import Enum +from typing import Final, TypeAlias +from typing_extensions import LiteralString, Never + +_FieldsType: TypeAlias = tuple[int, int, int, int, int, int] + +class SafeUUID(Enum): + safe = 0 + unsafe = -1 + unknown = None + +class UUID: + __slots__ = ("int", "is_safe", "__weakref__") + is_safe: Final[SafeUUID] + int: Final[builtins.int] + + def __init__( + self, + hex: str | None = None, + bytes: builtins.bytes | None = None, + bytes_le: builtins.bytes | None = None, + fields: _FieldsType | None = None, + int: builtins.int | None = None, + version: builtins.int | None = None, + *, + is_safe: SafeUUID = SafeUUID.unknown, + ) -> None: ... + @property + def bytes(self) -> builtins.bytes: ... + @property + def bytes_le(self) -> builtins.bytes: ... + @property + def clock_seq(self) -> builtins.int: ... + @property + def clock_seq_hi_variant(self) -> builtins.int: ... + @property + def clock_seq_low(self) -> builtins.int: ... + @property + def fields(self) -> _FieldsType: ... + @property + def hex(self) -> str: ... + @property + def node(self) -> builtins.int: ... + @property + def time(self) -> builtins.int: ... + @property + def time_hi_version(self) -> builtins.int: ... + @property + def time_low(self) -> builtins.int: ... + @property + def time_mid(self) -> builtins.int: ... + @property + def urn(self) -> str: ... + @property + def variant(self) -> str: ... + @property + def version(self) -> builtins.int | None: ... + def __int__(self) -> builtins.int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: UUID) -> bool: ... + def __le__(self, other: UUID) -> bool: ... + def __gt__(self, other: UUID) -> bool: ... + def __ge__(self, other: UUID) -> bool: ... + def __hash__(self) -> builtins.int: ... + def __setattr__(self, name: Unused, value: Unused) -> Never: ... + +def getnode() -> int: ... +def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: ... + +if sys.version_info >= (3, 14): + def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID: ... + def uuid7() -> UUID: ... + def uuid8(a: int | None = None, b: int | None = None, c: int | None = None) -> UUID: ... + +if sys.version_info >= (3, 12): + def uuid3(namespace: UUID, name: str | bytes) -> UUID: ... + +else: + def uuid3(namespace: UUID, name: str) -> UUID: ... + +def uuid4() -> UUID: ... + +if sys.version_info >= (3, 12): + def uuid5(namespace: UUID, name: str | bytes) -> UUID: ... + +else: + def uuid5(namespace: UUID, name: str) -> UUID: ... + +if sys.version_info >= (3, 14): + NIL: Final[UUID] + MAX: Final[UUID] + +NAMESPACE_DNS: Final[UUID] +NAMESPACE_URL: Final[UUID] +NAMESPACE_OID: Final[UUID] +NAMESPACE_X500: Final[UUID] +RESERVED_NCS: Final[LiteralString] +RFC_4122: Final[LiteralString] +RESERVED_MICROSOFT: Final[LiteralString] +RESERVED_FUTURE: Final[LiteralString] + +if sys.version_info >= (3, 12): + def main() -> None: ... diff --git a/stdlib/venv/__init__.pyi b/stdlib/venv/__init__.pyi new file mode 100644 index 000000000000..14db88523dba --- /dev/null +++ b/stdlib/venv/__init__.pyi @@ -0,0 +1,86 @@ +import logging +import sys +from _typeshed import StrOrBytesPath +from collections.abc import Iterable, Sequence +from types import SimpleNamespace +from typing import Final + +logger: logging.Logger + +CORE_VENV_DEPS: Final[tuple[str, ...]] + +class EnvBuilder: + system_site_packages: bool + clear: bool + symlinks: bool + upgrade: bool + with_pip: bool + prompt: str | None + + if sys.version_info >= (3, 13): + def __init__( + self, + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + upgrade: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + *, + scm_ignore_files: Iterable[str] = ..., + ) -> None: ... + else: + def __init__( + self, + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + upgrade: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + ) -> None: ... + + def create(self, env_dir: StrOrBytesPath) -> None: ... + def clear_directory(self, path: StrOrBytesPath) -> None: ... # undocumented + def ensure_directories(self, env_dir: StrOrBytesPath) -> SimpleNamespace: ... + def create_configuration(self, context: SimpleNamespace) -> None: ... + def symlink_or_copy( + self, src: StrOrBytesPath, dst: StrOrBytesPath, relative_symlinks_ok: bool = False + ) -> None: ... # undocumented + def setup_python(self, context: SimpleNamespace) -> None: ... + def _setup_pip(self, context: SimpleNamespace) -> None: ... # undocumented + def setup_scripts(self, context: SimpleNamespace) -> None: ... + def post_setup(self, context: SimpleNamespace) -> None: ... + def replace_variables(self, text: str, context: SimpleNamespace) -> str: ... # undocumented + def install_scripts(self, context: SimpleNamespace, path: str) -> None: ... + def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... + if sys.version_info >= (3, 13): + def create_git_ignore_file(self, context: SimpleNamespace) -> None: ... + +if sys.version_info >= (3, 13): + def create( + env_dir: StrOrBytesPath, + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + *, + scm_ignore_files: Iterable[str] = ..., + ) -> None: ... + +else: + def create( + env_dir: StrOrBytesPath, + system_site_packages: bool = False, + clear: bool = False, + symlinks: bool = False, + with_pip: bool = False, + prompt: str | None = None, + upgrade_deps: bool = False, + ) -> None: ... + +def main(args: Sequence[str] | None = None) -> None: ... diff --git a/stdlib/warnings.pyi b/stdlib/warnings.pyi new file mode 100644 index 000000000000..e17b6e3a25b3 --- /dev/null +++ b/stdlib/warnings.pyi @@ -0,0 +1,146 @@ +import re +import sys +from _warnings import warn as warn, warn_explicit as warn_explicit +from collections.abc import Sequence +from types import ModuleType, TracebackType +from typing import Any, Generic, Literal, TextIO, TypeAlias, overload +from typing_extensions import LiteralString, TypeVar + +__all__ = [ + "warn", + "warn_explicit", + "showwarning", + "formatwarning", + "filterwarnings", + "simplefilter", + "resetwarnings", + "catch_warnings", +] + +if sys.version_info >= (3, 13): + __all__ += ["deprecated"] + +_T = TypeVar("_T") +_W_co = TypeVar("_W_co", bound=list[WarningMessage] | None, default=list[WarningMessage] | None, covariant=True) + +if sys.version_info >= (3, 14): + _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] +else: + _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "all", "module", "once"] +filters: Sequence[ + tuple[str, re.Pattern[str] | None, type[Warning] | tuple[type[Warning], ...], re.Pattern[str] | None, int] +] # undocumented, do not mutate + +def showwarning( + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, +) -> None: ... +def formatwarning( + message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = None +) -> str: ... +def filterwarnings( + action: _ActionKind, message: str = "", category: type[Warning] = ..., module: str = "", lineno: int = 0, append: bool = False +) -> None: ... +def simplefilter( + action: _ActionKind, category: type[Warning] | tuple[type[Warning], ...] = ..., lineno: int = 0, append: bool = False +) -> None: ... +def resetwarnings() -> None: ... + +class _OptionError(Exception): ... + +class WarningMessage: + message: Warning | str + category: type[Warning] + filename: str + lineno: int + file: TextIO | None + line: str | None + source: Any | None + if sys.version_info >= (3, 15): + module: str | None + if sys.version_info >= (3, 15): + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + module: str | None = None, + ) -> None: ... + + else: + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + ) -> None: ... + +class catch_warnings(Generic[_W_co]): + if sys.version_info >= (3, 11): + @overload + def __init__( + self: catch_warnings[None], + *, + record: Literal[False] = False, + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + @overload + def __init__( + self: catch_warnings[list[WarningMessage]], + *, + record: Literal[True], + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + @overload + def __init__( + self, + *, + record: bool, + module: ModuleType | None = None, + action: _ActionKind | None = None, + category: type[Warning] | tuple[type[Warning], ...] = ..., + lineno: int = 0, + append: bool = False, + ) -> None: ... + else: + @overload + def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: ... + @overload + def __init__( + self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None + ) -> None: ... + @overload + def __init__(self, *, record: bool, module: ModuleType | None = None) -> None: ... + + def __enter__(self) -> _W_co: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +if sys.version_info >= (3, 13): + class deprecated: + message: LiteralString + category: type[Warning] | None + stacklevel: int + def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ... + def __call__(self, arg: _T, /) -> _T: ... diff --git a/stdlib/wave.pyi b/stdlib/wave.pyi new file mode 100644 index 000000000000..70bf87281550 --- /dev/null +++ b/stdlib/wave.pyi @@ -0,0 +1,105 @@ +import sys +from _typeshed import ReadableBuffer, StrOrBytesPath, Unused +from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self, deprecated + +__all__ = ["open", "Error", "Wave_read", "Wave_write"] +if sys.version_info >= (3, 15): + __all__ += ["WAVE_FORMAT_PCM", "WAVE_FORMAT_IEEE_FLOAT", "WAVE_FORMAT_EXTENSIBLE"] + +if sys.version_info >= (3, 15): + _File: TypeAlias = StrOrBytesPath | IO[bytes] +else: + _File: TypeAlias = str | IO[bytes] + +class Error(Exception): ... + +WAVE_FORMAT_PCM: Final = 0x0001 +if sys.version_info >= (3, 15): + WAVE_FORMAT_IEEE_FLOAT: Final = 0x0003 + WAVE_FORMAT_EXTENSIBLE: Final = 0xFFFE + +class _wave_params(NamedTuple): + nchannels: int + sampwidth: int + framerate: int + nframes: int + comptype: str + compname: str + +class Wave_read: + def __init__(self, f: _File) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... + def getfp(self) -> BinaryIO | None: ... + def rewind(self) -> None: ... + def close(self) -> None: ... + def tell(self) -> int: ... + def getnchannels(self) -> int: ... + def getnframes(self) -> int: ... + def getsampwidth(self) -> int: ... + def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def getformat(self) -> int: ... + + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + def getparams(self) -> _wave_params: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmarkers(self) -> None: ... + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... + + def setpos(self, pos: int) -> None: ... + def readframes(self, nframes: int) -> bytes: ... + +class Wave_write: + def __init__(self, f: _File) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... + def setnchannels(self, nchannels: int) -> None: ... + def getnchannels(self) -> int: ... + def setsampwidth(self, sampwidth: int) -> None: ... + def getsampwidth(self) -> int: ... + def setframerate(self, framerate: float) -> None: ... + def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def setformat(self, format: int) -> None: ... + def getformat(self) -> int: ... + + def setnframes(self, nframes: int) -> None: ... + def getnframes(self) -> int: ... + def setcomptype(self, comptype: str, compname: str) -> None: ... + def getcomptype(self) -> str: ... + def getcompname(self) -> str: ... + if sys.version_info >= (3, 15): + def setparams( + self, params: _wave_params | tuple[int, int, int, int, str, str] | tuple[int, int, int, int, str, str, int] + ) -> None: ... + else: + def setparams(self, params: _wave_params | tuple[int, int, int, int, str, str]) -> None: ... + + def getparams(self) -> _wave_params: ... + + if sys.version_info < (3, 15): + @deprecated("Deprecated; will be removed in Python 3.15.") + def setmark(self, id: Any, pos: Any, name: Any) -> Never: ... + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmarkers(self) -> None: ... + + def tell(self) -> int: ... + def writeframesraw(self, data: ReadableBuffer) -> None: ... + def writeframes(self, data: ReadableBuffer) -> None: ... + def close(self) -> None: ... + +@overload +def open(f: _File, mode: Literal["r", "rb"]) -> Wave_read: ... +@overload +def open(f: _File, mode: Literal["w", "wb"]) -> Wave_write: ... +@overload +def open(f: _File, mode: str | None = None) -> Any: ... diff --git a/stdlib/weakref.pyi b/stdlib/weakref.pyi new file mode 100644 index 000000000000..3308ae42e1cf --- /dev/null +++ b/stdlib/weakref.pyi @@ -0,0 +1,213 @@ +from _typeshed import SupportsKeysAndGetItem +from _weakref import getweakrefcount as getweakrefcount, getweakrefs as getweakrefs, proxy as proxy +from _weakrefset import WeakSet as WeakSet +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping +from types import GenericAlias +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, disjoint_base + +__all__ = [ + "ref", + "proxy", + "getweakrefcount", + "getweakrefs", + "WeakKeyDictionary", + "ReferenceType", + "ProxyType", + "CallableProxyType", + "ProxyTypes", + "WeakValueDictionary", + "WeakSet", + "WeakMethod", + "finalize", +] + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +ProxyTypes: tuple[type[Any], ...] + +# These classes are implemented in C and imported from _weakref at runtime. However, +# they consider themselves to live in the weakref module for sys.version_info >= (3, 11), +# so defining their stubs here means we match their __module__ value. +# Prior to 3.11 they did not declare a module for themselves and ended up looking like they +# came from the builtin module at runtime, which was just wrong, and we won't attempt to +# duplicate that. + +@final +class CallableProxyType(Generic[_CallableT]): # "weakcallableproxy" + def __eq__(self, value: object, /) -> bool: ... + def __getattr__(self, attr: str) -> Any: ... + __call__: _CallableT + __hash__: ClassVar[None] # type: ignore[assignment] + +@final +class ProxyType(Generic[_T]): # "weakproxy" + def __eq__(self, value: object, /) -> bool: ... + def __getattr__(self, attr: str) -> Any: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +@disjoint_base +class ReferenceType(Generic[_T]): # "weakref" + __callback__: Callable[[Self], Any] + def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ... + def __call__(self) -> _T | None: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +ref = ReferenceType + +# everything below here is implemented in weakref.py + +class WeakMethod(ref[_CallableT]): + __slots__ = ("_func_ref", "_meth_type", "_alive", "__weakref__") + def __new__(cls, meth: _CallableT, callback: Callable[[Self], Any] | None = None) -> Self: ... + def __call__(self) -> _CallableT | None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class WeakValueDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self: WeakValueDictionary[_KT, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], + /, + ) -> None: ... + @overload + def __init__( + self: WeakValueDictionary[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (), + /, + **kwargs: _VT, + ) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> WeakValueDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self, memo: Any) -> Self: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... + def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + @overload + def update(self, other: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... + @overload + def update(self, other: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... + @overload + def update(self, other: None = None, /, **kwargs: _VT) -> None: ... + + def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + + # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + +class KeyedRef(ref[_T], Generic[_KT, _T]): + __slots__ = ("key",) + key: _KT + def __new__(type, ob: _T, callback: Callable[[Self], Any], key: _KT) -> Self: ... + def __init__(self, ob: _T, callback: Callable[[Self], Any], key: _KT) -> None: ... + +class WeakKeyDictionary(MutableMapping[_KT, _VT]): + @overload + def __init__(self, dict: None = None) -> None: ... + @overload + def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + + def __len__(self) -> int: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... + __copy__ = copy + def __deepcopy__(self, memo: Any) -> Self: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + + # These are incompatible with Mapping + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def keyrefs(self) -> list[ref[_KT]]: ... + + # Keep WeakKeyDictionary.setdefault in line with MutableMapping.setdefault, modulo positional-only differences + @overload + def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + @overload + def update(self, dict: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... + @overload + def update(self, dict: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... + @overload + def update(self, dict: None = None, /, **kwargs: _VT) -> None: ... + + def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + + # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + +class finalize(Generic[_P, _T]): + __slots__ = () + def __init__(self, obj: _T, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def __call__(self, _: Any = None) -> Any | None: ... + def detach(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ... + def peek(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ... + @property + def alive(self) -> bool: ... + atexit: bool diff --git a/stdlib/webbrowser.pyi b/stdlib/webbrowser.pyi new file mode 100644 index 000000000000..8ed7f919c78f --- /dev/null +++ b/stdlib/webbrowser.pyi @@ -0,0 +1,79 @@ +import sys +from abc import abstractmethod +from collections.abc import Callable, Sequence +from typing import Literal +from typing_extensions import deprecated + +__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"] + +class Error(Exception): ... + +def register( + name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = None, *, preferred: bool = False +) -> None: ... +def get(using: str | None = None) -> BaseBrowser: ... +def open(url: str, new: int = 0, autoraise: bool = True) -> bool: ... +def open_new(url: str) -> bool: ... +def open_new_tab(url: str) -> bool: ... +def register_standard_browsers() -> None: ... + +class BaseBrowser: + args: list[str] + name: str + basename: str + def __init__(self, name: str = "") -> None: ... + @abstractmethod + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + def open_new(self, url: str) -> bool: ... + def open_new_tab(self, url: str) -> bool: ... + +class GenericBrowser(BaseBrowser): + def __init__(self, name: str | Sequence[str]) -> None: ... + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + +class BackgroundBrowser(GenericBrowser): ... + +class UnixBrowser(BaseBrowser): + def open(self, url: str, new: Literal[0, 1, 2] = 0, autoraise: bool = True) -> bool: ... # type: ignore[override] + raise_opts: list[str] | None + background: bool + redirect_stdout: bool + remote_args: list[str] + remote_action: str + remote_action_newwin: str + remote_action_newtab: str + +class Mozilla(UnixBrowser): ... + +if sys.version_info < (3, 12): + class Galeon(UnixBrowser): + raise_opts: list[str] + + class Grail(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + +class Chrome(UnixBrowser): ... +class Opera(UnixBrowser): ... +class Elinks(UnixBrowser): ... + +class Konqueror(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + +if sys.platform == "win32": + class WindowsDefault(BaseBrowser): + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + +if sys.platform == "darwin": + if sys.version_info < (3, 13): + @deprecated("Deprecated; removed in Python 3.13.") + class MacOSX(BaseBrowser): + def __init__(self, name: str) -> None: ... + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + + class MacOSXOSAScript(BaseBrowser): # In runtime this class does not have `name` and `basename` + if sys.version_info >= (3, 11): + def __init__(self, name: str = "default") -> None: ... + else: + def __init__(self, name: str) -> None: ... + + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... diff --git a/stdlib/winreg.pyi b/stdlib/winreg.pyi new file mode 100644 index 000000000000..8a886112f8a1 --- /dev/null +++ b/stdlib/winreg.pyi @@ -0,0 +1,137 @@ +import sys +from _typeshed import ReadableBuffer, Unused +from types import TracebackType +from typing import Any, Final, Literal, TypeAlias, final, overload +from typing_extensions import Self + +if sys.platform == "win32": + _KeyType: TypeAlias = HKEYType | int + def CloseKey(hkey: _KeyType, /) -> None: ... + def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: ... + def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: ... + def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ... + def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ... + def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ... + if sys.version_info >= (3, 15): + def DeleteTree(key: _KeyType, sub_key: str | None = None, /) -> None: ... + + def DeleteValue(key: _KeyType, value: str, /) -> None: ... + def EnumKey(key: _KeyType, index: int, /) -> str: ... + def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ... + def ExpandEnvironmentStrings(string: str, /) -> str: ... + def FlushKey(key: _KeyType, /) -> None: ... + def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: ... + def OpenKey(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ... + def OpenKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ... + def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: ... + def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: ... + def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ... + def SaveKey(key: _KeyType, file_name: str, /) -> None: ... + def SetValue(key: _KeyType, sub_key: str | None, type: int, value: str, /) -> None: ... + + @overload # type=REG_DWORD|REG_QWORD + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, / + ) -> None: ... + @overload # type=REG_SZ|REG_EXPAND_SZ + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[1, 2], value: str | None, / + ) -> None: ... + @overload # type=REG_MULTI_SZ + def SetValueEx( + key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[7], value: list[str] | None, / + ) -> None: ... + @overload # type=REG_BINARY and everything else + def SetValueEx( + key: _KeyType, + value_name: str | None, + reserved: Unused, + type: Literal[0, 3, 8, 9, 10, 11], + value: ReadableBuffer | None, + /, + ) -> None: ... + @overload # Unknown or undocumented + def SetValueEx( + key: _KeyType, + value_name: str | None, + reserved: Unused, + type: int, + value: int | str | list[str] | ReadableBuffer | None, + /, + ) -> None: ... + + def DisableReflectionKey(key: _KeyType, /) -> None: ... + def EnableReflectionKey(key: _KeyType, /) -> None: ... + def QueryReflectionKey(key: _KeyType, /) -> bool: ... + + HKEY_CLASSES_ROOT: Final[int] + HKEY_CURRENT_USER: Final[int] + HKEY_LOCAL_MACHINE: Final[int] + HKEY_USERS: Final[int] + HKEY_PERFORMANCE_DATA: Final[int] + HKEY_CURRENT_CONFIG: Final[int] + HKEY_DYN_DATA: Final[int] + + KEY_ALL_ACCESS: Final = 983103 + KEY_WRITE: Final = 131078 + KEY_READ: Final = 131097 + KEY_EXECUTE: Final = 131097 + KEY_QUERY_VALUE: Final = 1 + KEY_SET_VALUE: Final = 2 + KEY_CREATE_SUB_KEY: Final = 4 + KEY_ENUMERATE_SUB_KEYS: Final = 8 + KEY_NOTIFY: Final = 16 + KEY_CREATE_LINK: Final = 32 + + KEY_WOW64_64KEY: Final = 256 + KEY_WOW64_32KEY: Final = 512 + + REG_BINARY: Final = 3 + REG_DWORD: Final = 4 + REG_DWORD_LITTLE_ENDIAN: Final = 4 + REG_DWORD_BIG_ENDIAN: Final = 5 + REG_EXPAND_SZ: Final = 2 + REG_LINK: Final = 6 + REG_MULTI_SZ: Final = 7 + REG_NONE: Final = 0 + REG_QWORD: Final = 11 + REG_QWORD_LITTLE_ENDIAN: Final = 11 + REG_RESOURCE_LIST: Final = 8 + REG_FULL_RESOURCE_DESCRIPTOR: Final = 9 + REG_RESOURCE_REQUIREMENTS_LIST: Final = 10 + REG_SZ: Final = 1 + + REG_CREATED_NEW_KEY: Final = 1 # undocumented + REG_LEGAL_CHANGE_FILTER: Final = 268435471 # undocumented + REG_LEGAL_OPTION: Final = 31 # undocumented + REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2 # undocumented + REG_NOTIFY_CHANGE_LAST_SET: Final = 4 # undocumented + REG_NOTIFY_CHANGE_NAME: Final = 1 # undocumented + REG_NOTIFY_CHANGE_SECURITY: Final = 8 # undocumented + REG_NO_LAZY_FLUSH: Final = 4 # undocumented + REG_OPENED_EXISTING_KEY: Final = 2 # undocumented + REG_OPTION_BACKUP_RESTORE: Final = 4 # undocumented + REG_OPTION_CREATE_LINK: Final = 2 # undocumented + REG_OPTION_NON_VOLATILE: Final = 0 # undocumented + REG_OPTION_OPEN_LINK: Final = 8 # undocumented + REG_OPTION_RESERVED: Final = 0 # undocumented + REG_OPTION_VOLATILE: Final = 1 # undocumented + REG_REFRESH_HIVE: Final = 2 # undocumented + REG_WHOLE_HIVE_VOLATILE: Final = 1 # undocumented + + error = OSError + + # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason + @final + class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> bool | None: ... + def Close(self) -> None: ... + def Detach(self) -> int: ... + def __hash__(self) -> int: ... + @property + def handle(self) -> int: ... diff --git a/stdlib/winsound.pyi b/stdlib/winsound.pyi new file mode 100644 index 000000000000..9c7f314fd6ca --- /dev/null +++ b/stdlib/winsound.pyi @@ -0,0 +1,40 @@ +import sys +from _typeshed import ReadableBuffer +from typing import Final, Literal, overload + +if sys.platform == "win32": + SND_APPLICATION: Final = 128 + SND_FILENAME: Final = 131072 + SND_ALIAS: Final = 65536 + SND_LOOP: Final = 8 + SND_MEMORY: Final = 4 + SND_PURGE: Final = 64 + SND_ASYNC: Final = 1 + SND_NODEFAULT: Final = 2 + SND_NOSTOP: Final = 16 + SND_NOWAIT: Final = 8192 + if sys.version_info >= (3, 14): + SND_SENTRY: Final = 524288 + SND_SYNC: Final = 0 + SND_SYSTEM: Final = 2097152 + + MB_ICONASTERISK: Final = 64 + MB_ICONEXCLAMATION: Final = 48 + MB_ICONHAND: Final = 16 + MB_ICONQUESTION: Final = 32 + MB_OK: Final = 0 + if sys.version_info >= (3, 14): + MB_ICONERROR: Final = 16 + MB_ICONINFORMATION: Final = 64 + MB_ICONSTOP: Final = 16 + MB_ICONWARNING: Final = 48 + + def Beep(frequency: int, duration: int) -> None: ... + + # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible + @overload + def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: ... + @overload + def PlaySound(sound: str | ReadableBuffer | None, flags: int) -> None: ... + + def MessageBeep(type: int = 0) -> None: ... diff --git a/stdlib/wsgiref/__init__.pyi b/stdlib/wsgiref/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/wsgiref/handlers.pyi b/stdlib/wsgiref/handlers.pyi new file mode 100644 index 000000000000..ebead540018e --- /dev/null +++ b/stdlib/wsgiref/handlers.pyi @@ -0,0 +1,91 @@ +from _typeshed import OptExcInfo +from _typeshed.wsgi import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment +from abc import abstractmethod +from collections.abc import Callable, MutableMapping +from typing import IO + +from .headers import Headers +from .util import FileWrapper + +__all__ = ["BaseHandler", "SimpleHandler", "BaseCGIHandler", "CGIHandler", "IISCGIHandler", "read_environ"] + +def format_date_time(timestamp: float | None) -> str: ... # undocumented +def read_environ() -> dict[str, str]: ... + +class BaseHandler: + wsgi_version: tuple[int, int] # undocumented + wsgi_multithread: bool + wsgi_multiprocess: bool + wsgi_run_once: bool + + origin_server: bool + http_version: str + server_software: str | None + + os_environ: MutableMapping[str, str] + + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented + + traceback_limit: int | None + error_status: str + error_headers: list[tuple[str, str]] + error_body: bytes + def run(self, application: WSGIApplication) -> None: ... + def setup_environ(self) -> None: ... + def finish_response(self) -> None: ... + def get_scheme(self) -> str: ... + def set_content_length(self) -> None: ... + def cleanup_headers(self) -> None: ... + def start_response( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None + ) -> Callable[[bytes], None]: ... + def send_preamble(self) -> None: ... + def write(self, data: bytes) -> None: ... + def sendfile(self) -> bool: ... + def finish_content(self) -> None: ... + def close(self) -> None: ... + def send_headers(self) -> None: ... + def result_is_file(self) -> bool: ... + def client_is_modern(self) -> bool: ... + def log_exception(self, exc_info: OptExcInfo) -> None: ... + def handle_error(self) -> None: ... + def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... + @abstractmethod + def _write(self, data: bytes) -> None: ... + @abstractmethod + def _flush(self) -> None: ... + @abstractmethod + def get_stdin(self) -> InputStream: ... + @abstractmethod + def get_stderr(self) -> ErrorStream: ... + @abstractmethod + def add_cgi_vars(self) -> None: ... + +class SimpleHandler(BaseHandler): + stdin: InputStream + stdout: IO[bytes] + stderr: ErrorStream + base_env: MutableMapping[str, str] + def __init__( + self, + stdin: InputStream, + stdout: IO[bytes], + stderr: ErrorStream, + environ: MutableMapping[str, str], + multithread: bool = True, + multiprocess: bool = False, + ) -> None: ... + def get_stdin(self) -> InputStream: ... + def get_stderr(self) -> ErrorStream: ... + def add_cgi_vars(self) -> None: ... + def _write(self, data: bytes) -> None: ... + def _flush(self) -> None: ... + +class BaseCGIHandler(SimpleHandler): ... + +class CGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... + +class IISCGIHandler(BaseCGIHandler): + def __init__(self) -> None: ... diff --git a/stdlib/wsgiref/headers.pyi b/stdlib/wsgiref/headers.pyi new file mode 100644 index 000000000000..6a0fb571a0d0 --- /dev/null +++ b/stdlib/wsgiref/headers.pyi @@ -0,0 +1,27 @@ +from re import Pattern +from typing import Final, TypeAlias, overload + +_HeaderList: TypeAlias = list[tuple[str, str]] + +tspecials: Final[Pattern[str]] # undocumented + +class Headers: + def __init__(self, headers: _HeaderList | None = None) -> None: ... + def __len__(self) -> int: ... + def __setitem__(self, name: str, val: str) -> None: ... + def __delitem__(self, name: str) -> None: ... + def __getitem__(self, name: str) -> str | None: ... + def __contains__(self, name: str) -> bool: ... + def get_all(self, name: str) -> list[str]: ... + + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: str | None = None) -> str | None: ... + + def keys(self) -> list[str]: ... + def values(self) -> list[str]: ... + def items(self) -> _HeaderList: ... + def __bytes__(self) -> bytes: ... + def setdefault(self, name: str, value: str) -> str: ... + def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: ... diff --git a/stdlib/wsgiref/simple_server.pyi b/stdlib/wsgiref/simple_server.pyi new file mode 100644 index 000000000000..bdf58719c828 --- /dev/null +++ b/stdlib/wsgiref/simple_server.pyi @@ -0,0 +1,37 @@ +from _typeshed.wsgi import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment +from http.server import BaseHTTPRequestHandler, HTTPServer +from typing import Final, TypeVar, overload + +from .handlers import SimpleHandler + +__all__ = ["WSGIServer", "WSGIRequestHandler", "demo_app", "make_server"] + +server_version: Final[str] # undocumented +sys_version: Final[str] # undocumented +software_version: Final[str] # undocumented + +class ServerHandler(SimpleHandler): # undocumented + server_software: str + +class WSGIServer(HTTPServer): + application: WSGIApplication | None + base_environ: WSGIEnvironment # only available after call to setup_environ() + def setup_environ(self) -> None: ... + def get_app(self) -> WSGIApplication | None: ... + def set_app(self, application: WSGIApplication | None) -> None: ... + +class WSGIRequestHandler(BaseHTTPRequestHandler): + server_version: str + def get_environ(self) -> WSGIEnvironment: ... + def get_stderr(self) -> ErrorStream: ... + +def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... + +_S = TypeVar("_S", bound=WSGIServer) + +@overload +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: ... +@overload +def make_server( + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... +) -> _S: ... diff --git a/stdlib/wsgiref/types.pyi b/stdlib/wsgiref/types.pyi new file mode 100644 index 000000000000..b7fd99809856 --- /dev/null +++ b/stdlib/wsgiref/types.pyi @@ -0,0 +1,31 @@ +from _typeshed import OptExcInfo +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Protocol, TypeAlias + +__all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", "ErrorStream", "FileWrapper"] + +class StartResponse(Protocol): + def __call__( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., / + ) -> Callable[[bytes], object]: ... + +WSGIEnvironment: TypeAlias = dict[str, Any] +WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] + +class InputStream(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + def readline(self, size: int = ..., /) -> bytes: ... + def readlines(self, hint: int = ..., /) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + +class ErrorStream(Protocol): + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... + def writelines(self, seq: list[str], /) -> object: ... + +class _Readable(Protocol): + def read(self, size: int = ..., /) -> bytes: ... + # Optional: def close(self) -> object: ... + +class FileWrapper(Protocol): + def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ... diff --git a/stdlib/wsgiref/util.pyi b/stdlib/wsgiref/util.pyi new file mode 100644 index 000000000000..3966e17b0d28 --- /dev/null +++ b/stdlib/wsgiref/util.pyi @@ -0,0 +1,26 @@ +import sys +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Callable +from typing import IO, Any + +__all__ = ["FileWrapper", "guess_scheme", "application_uri", "request_uri", "shift_path_info", "setup_testing_defaults"] +if sys.version_info >= (3, 13): + __all__ += ["is_hop_by_hop"] + +class FileWrapper: + filelike: IO[bytes] + blksize: int + close: Callable[[], None] # only exists if filelike.close exists + def __init__(self, filelike: IO[bytes], blksize: int = 8192) -> None: ... + if sys.version_info < (3, 11): + def __getitem__(self, key: Any) -> bytes: ... + + def __iter__(self) -> FileWrapper: ... + def __next__(self) -> bytes: ... + +def guess_scheme(environ: WSGIEnvironment) -> str: ... +def application_uri(environ: WSGIEnvironment) -> str: ... +def request_uri(environ: WSGIEnvironment, include_query: bool = True) -> str: ... +def shift_path_info(environ: WSGIEnvironment) -> str | None: ... +def setup_testing_defaults(environ: WSGIEnvironment) -> None: ... +def is_hop_by_hop(header_name: str) -> bool: ... diff --git a/stdlib/wsgiref/validate.pyi b/stdlib/wsgiref/validate.pyi new file mode 100644 index 000000000000..ce3e79f341f9 --- /dev/null +++ b/stdlib/wsgiref/validate.pyi @@ -0,0 +1,50 @@ +from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication +from collections.abc import Callable, Iterable, Iterator +from typing import Any, TypeAlias +from typing_extensions import Never + +__all__ = ["validator"] + +class WSGIWarning(Warning): ... + +def validator(application: WSGIApplication) -> WSGIApplication: ... + +class InputWrapper: + input: InputStream + def __init__(self, wsgi_input: InputStream) -> None: ... + def read(self, size: int) -> bytes: ... + def readline(self, size: int = ...) -> bytes: ... + def readlines(self, hint: int = ...) -> bytes: ... + def __iter__(self) -> Iterator[bytes]: ... + def close(self) -> Never: ... + +class ErrorWrapper: + errors: ErrorStream + def __init__(self, wsgi_errors: ErrorStream) -> None: ... + def write(self, s: str) -> None: ... + def flush(self) -> None: ... + def writelines(self, seq: Iterable[str]) -> None: ... + def close(self) -> Never: ... + +_WriterCallback: TypeAlias = Callable[[bytes], Any] + +class WriteWrapper: + writer: _WriterCallback + def __init__(self, wsgi_writer: _WriterCallback) -> None: ... + def __call__(self, s: bytes) -> None: ... + +class PartialIteratorWrapper: + iterator: Iterator[bytes] + def __init__(self, wsgi_iterator: Iterator[bytes]) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + +class IteratorWrapper: + original_iterator: Iterator[bytes] + iterator: Iterator[bytes] + closed: bool + check_start_response: bool | None + def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: bool | None) -> None: ... + def __iter__(self) -> IteratorWrapper: ... + def __next__(self) -> bytes: ... + def close(self) -> None: ... + def __del__(self) -> None: ... diff --git a/stdlib/xdrlib.pyi b/stdlib/xdrlib.pyi new file mode 100644 index 000000000000..78f3ecec8d78 --- /dev/null +++ b/stdlib/xdrlib.pyi @@ -0,0 +1,57 @@ +from collections.abc import Callable, Sequence +from typing import TypeVar + +__all__ = ["Error", "Packer", "Unpacker", "ConversionError"] + +_T = TypeVar("_T") + +class Error(Exception): + msg: str + def __init__(self, msg: str) -> None: ... + +class ConversionError(Error): ... + +class Packer: + def reset(self) -> None: ... + def get_buffer(self) -> bytes: ... + def get_buf(self) -> bytes: ... + def pack_uint(self, x: int) -> None: ... + def pack_int(self, x: int) -> None: ... + def pack_enum(self, x: int) -> None: ... + def pack_bool(self, x: bool) -> None: ... + def pack_uhyper(self, x: int) -> None: ... + def pack_hyper(self, x: int) -> None: ... + def pack_float(self, x: float) -> None: ... + def pack_double(self, x: float) -> None: ... + def pack_fstring(self, n: int, s: bytes) -> None: ... + def pack_fopaque(self, n: int, s: bytes) -> None: ... + def pack_string(self, s: bytes) -> None: ... + def pack_opaque(self, s: bytes) -> None: ... + def pack_bytes(self, s: bytes) -> None: ... + def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... + def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... + def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ... + +class Unpacker: + def __init__(self, data: bytes) -> None: ... + def reset(self, data: bytes) -> None: ... + def get_position(self) -> int: ... + def set_position(self, position: int) -> None: ... + def get_buffer(self) -> bytes: ... + def done(self) -> None: ... + def unpack_uint(self) -> int: ... + def unpack_int(self) -> int: ... + def unpack_enum(self) -> int: ... + def unpack_bool(self) -> bool: ... + def unpack_uhyper(self) -> int: ... + def unpack_hyper(self) -> int: ... + def unpack_float(self) -> float: ... + def unpack_double(self) -> float: ... + def unpack_fstring(self, n: int) -> bytes: ... + def unpack_fopaque(self, n: int) -> bytes: ... + def unpack_string(self) -> bytes: ... + def unpack_opaque(self) -> bytes: ... + def unpack_bytes(self) -> bytes: ... + def unpack_list(self, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_array(self, unpack_item: Callable[[], _T]) -> list[_T]: ... diff --git a/stdlib/xml/__init__.pyi b/stdlib/xml/__init__.pyi new file mode 100644 index 000000000000..555d9b8f90a9 --- /dev/null +++ b/stdlib/xml/__init__.pyi @@ -0,0 +1,9 @@ +# At runtime, listing submodules in __all__ without them being imported is +# valid, and causes them to be included in a star import. See #6523 +import sys + +__all__ = ["dom", "parsers", "sax", "etree"] # noqa: F822 # pyright: ignore[reportUnsupportedDunderAll] + +if sys.version_info >= (3, 15): + __all__ += ["is_valid_name"] # pyright: ignore[reportUnsupportedDunderAll] + from xml.utils import is_valid_name as is_valid_name, is_valid_text as is_valid_text diff --git a/stdlib/xml/dom/NodeFilter.pyi b/stdlib/xml/dom/NodeFilter.pyi new file mode 100644 index 000000000000..7b301373f528 --- /dev/null +++ b/stdlib/xml/dom/NodeFilter.pyi @@ -0,0 +1,22 @@ +from typing import Final +from xml.dom.minidom import Node + +class NodeFilter: + FILTER_ACCEPT: Final = 1 + FILTER_REJECT: Final = 2 + FILTER_SKIP: Final = 3 + + SHOW_ALL: Final = 0xFFFFFFFF + SHOW_ELEMENT: Final = 0x00000001 + SHOW_ATTRIBUTE: Final = 0x00000002 + SHOW_TEXT: Final = 0x00000004 + SHOW_CDATA_SECTION: Final = 0x00000008 + SHOW_ENTITY_REFERENCE: Final = 0x00000010 + SHOW_ENTITY: Final = 0x00000020 + SHOW_PROCESSING_INSTRUCTION: Final = 0x00000040 + SHOW_COMMENT: Final = 0x00000080 + SHOW_DOCUMENT: Final = 0x00000100 + SHOW_DOCUMENT_TYPE: Final = 0x00000200 + SHOW_DOCUMENT_FRAGMENT: Final = 0x00000400 + SHOW_NOTATION: Final = 0x00000800 + def acceptNode(self, node: Node) -> int: ... diff --git a/stdlib/xml/dom/__init__.pyi b/stdlib/xml/dom/__init__.pyi new file mode 100644 index 000000000000..5dbb6c536f61 --- /dev/null +++ b/stdlib/xml/dom/__init__.pyi @@ -0,0 +1,101 @@ +from typing import Any, Final, Literal + +from .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation + +class Node: + __slots__ = () + ELEMENT_NODE: Final = 1 + ATTRIBUTE_NODE: Final = 2 + TEXT_NODE: Final = 3 + CDATA_SECTION_NODE: Final = 4 + ENTITY_REFERENCE_NODE: Final = 5 + ENTITY_NODE: Final = 6 + PROCESSING_INSTRUCTION_NODE: Final = 7 + COMMENT_NODE: Final = 8 + DOCUMENT_NODE: Final = 9 + DOCUMENT_TYPE_NODE: Final = 10 + DOCUMENT_FRAGMENT_NODE: Final = 11 + NOTATION_NODE: Final = 12 + +# ExceptionCode +INDEX_SIZE_ERR: Final = 1 +DOMSTRING_SIZE_ERR: Final = 2 +HIERARCHY_REQUEST_ERR: Final = 3 +WRONG_DOCUMENT_ERR: Final = 4 +INVALID_CHARACTER_ERR: Final = 5 +NO_DATA_ALLOWED_ERR: Final = 6 +NO_MODIFICATION_ALLOWED_ERR: Final = 7 +NOT_FOUND_ERR: Final = 8 +NOT_SUPPORTED_ERR: Final = 9 +INUSE_ATTRIBUTE_ERR: Final = 10 +INVALID_STATE_ERR: Final = 11 +SYNTAX_ERR: Final = 12 +INVALID_MODIFICATION_ERR: Final = 13 +NAMESPACE_ERR: Final = 14 +INVALID_ACCESS_ERR: Final = 15 +VALIDATION_ERR: Final = 16 + +class DOMException(Exception): + code: int + def __init__(self, *args: Any, **kw: Any) -> None: ... + def _get_code(self) -> int: ... + +class IndexSizeErr(DOMException): + code: Literal[1] + +class DomstringSizeErr(DOMException): + code: Literal[2] + +class HierarchyRequestErr(DOMException): + code: Literal[3] + +class WrongDocumentErr(DOMException): + code: Literal[4] + +class InvalidCharacterErr(DOMException): + code: Literal[5] + +class NoDataAllowedErr(DOMException): + code: Literal[6] + +class NoModificationAllowedErr(DOMException): + code: Literal[7] + +class NotFoundErr(DOMException): + code: Literal[8] + +class NotSupportedErr(DOMException): + code: Literal[9] + +class InuseAttributeErr(DOMException): + code: Literal[10] + +class InvalidStateErr(DOMException): + code: Literal[11] + +class SyntaxErr(DOMException): + code: Literal[12] + +class InvalidModificationErr(DOMException): + code: Literal[13] + +class NamespaceErr(DOMException): + code: Literal[14] + +class InvalidAccessErr(DOMException): + code: Literal[15] + +class ValidationErr(DOMException): + code: Literal[16] + +class UserDataHandler: + NODE_CLONED: Final = 1 + NODE_IMPORTED: Final = 2 + NODE_DELETED: Final = 3 + NODE_RENAMED: Final = 4 + +XML_NAMESPACE: Final = "http://www.w3.org/XML/1998/namespace" +XMLNS_NAMESPACE: Final = "http://www.w3.org/2000/xmlns/" +XHTML_NAMESPACE: Final = "http://www.w3.org/1999/xhtml" +EMPTY_NAMESPACE: Final[None] +EMPTY_PREFIX: Final[None] diff --git a/stdlib/xml/dom/domreg.pyi b/stdlib/xml/dom/domreg.pyi new file mode 100644 index 000000000000..346a4bf63bd4 --- /dev/null +++ b/stdlib/xml/dom/domreg.pyi @@ -0,0 +1,8 @@ +from _typeshed.xml import DOMImplementation +from collections.abc import Callable, Iterable + +well_known_implementations: dict[str, str] +registered: dict[str, Callable[[], DOMImplementation]] + +def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... +def getDOMImplementation(name: str | None = None, features: str | Iterable[tuple[str, str | None]] = ()) -> DOMImplementation: ... diff --git a/stdlib/xml/dom/expatbuilder.pyi b/stdlib/xml/dom/expatbuilder.pyi new file mode 100644 index 000000000000..5aef384ff0f2 --- /dev/null +++ b/stdlib/xml/dom/expatbuilder.pyi @@ -0,0 +1,126 @@ +from _typeshed import ReadableBuffer, SupportsRead +from typing import Any, Final, TypeAlias +from typing_extensions import Never +from xml.dom.minidom import Document, DocumentFragment, DOMImplementation, Element, Node, TypeInfo +from xml.dom.xmlbuilder import DOMBuilderFilter, Options +from xml.parsers.expat import XMLParserType + +_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]] # same as in pyexpat + +TEXT_NODE: Final = Node.TEXT_NODE +CDATA_SECTION_NODE: Final = Node.CDATA_SECTION_NODE +DOCUMENT_NODE: Final = Node.DOCUMENT_NODE +FILTER_ACCEPT: Final = DOMBuilderFilter.FILTER_ACCEPT +FILTER_REJECT: Final = DOMBuilderFilter.FILTER_REJECT +FILTER_SKIP: Final = DOMBuilderFilter.FILTER_SKIP +FILTER_INTERRUPT: Final = DOMBuilderFilter.FILTER_INTERRUPT +theDOMImplementation: DOMImplementation + +class ElementInfo: + __slots__ = ("_attr_info", "_model", "tagName") + tagName: str + def __init__(self, tagName: str, model: _Model | None = None) -> None: ... + def getAttributeType(self, aname: str) -> TypeInfo: ... + def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ... + def isElementContent(self) -> bool: ... + def isEmpty(self) -> bool: ... + def isId(self, aname: str) -> bool: ... + def isIdNS(self, euri: str, ename: str, auri: str, aname: str) -> bool: ... + +class ExpatBuilder: + document: Document # Created in self.reset() + curNode: DocumentFragment | Element | Document # Created in self.reset() + def __init__(self, options: Options | None = None) -> None: ... + def createParser(self) -> XMLParserType: ... + def getParser(self) -> XMLParserType: ... + def reset(self) -> None: ... + def install(self, parser: XMLParserType) -> None: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> Document: ... + def parseString(self, string: str | ReadableBuffer) -> Document: ... + def start_doctype_decl_handler( + self, doctypeName: str, systemId: str | None, publicId: str | None, has_internal_subset: bool + ) -> None: ... + def end_doctype_decl_handler(self) -> None: ... + def pi_handler(self, target: str, data: str) -> None: ... + def character_data_handler_cdata(self, data: str) -> None: ... + def character_data_handler(self, data: str) -> None: ... + def start_cdata_section_handler(self) -> None: ... + def end_cdata_section_handler(self) -> None: ... + def entity_decl_handler( + self, + entityName: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + systemId: str, + publicId: str | None, + notationName: str | None, + ) -> None: ... + def notation_decl_handler(self, notationName: str, base: str | None, systemId: str, publicId: str | None) -> None: ... + def comment_handler(self, data: str) -> None: ... + def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ... + def first_element_handler(self, name: str, attributes: list[str]) -> None: ... + def start_element_handler(self, name: str, attributes: list[str]) -> None: ... + def end_element_handler(self, name: str) -> None: ... + def element_decl_handler(self, name: str, model: _Model) -> None: ... + def attlist_decl_handler(self, elem: str, name: str, type: str, default: str | None, required: bool) -> None: ... + def xml_decl_handler(self, version: str, encoding: str | None, standalone: int) -> None: ... + +class FilterVisibilityController: + __slots__ = ("filter",) + filter: DOMBuilderFilter + def __init__(self, filter: DOMBuilderFilter) -> None: ... + def startContainer(self, node: Node) -> int: ... + def acceptNode(self, node: Node) -> int: ... + +class FilterCrutch: + __slots__ = ("_builder", "_level", "_old_start", "_old_end") + def __init__(self, builder: ExpatBuilder) -> None: ... + +class Rejecter(FilterCrutch): + __slots__ = () + def start_element_handler(self, *args: Any) -> None: ... + def end_element_handler(self, *args: Any) -> None: ... + +class Skipper(FilterCrutch): + __slots__ = () + def start_element_handler(self, *args: Any) -> None: ... + def end_element_handler(self, *args: Any) -> None: ... + +class FragmentBuilder(ExpatBuilder): + fragment: DocumentFragment | None + originalDocument: Document + context: Node + def __init__(self, context: Node, options: Options | None = None) -> None: ... + def reset(self) -> None: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> DocumentFragment: ... # type: ignore[override] + def parseString(self, string: ReadableBuffer | str) -> DocumentFragment: ... # type: ignore[override] + def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ... + +class Namespaces: + def createParser(self) -> XMLParserType: ... + def install(self, parser: XMLParserType) -> None: ... + def start_namespace_decl_handler(self, prefix: str | None, uri: str) -> None: ... + def start_element_handler(self, name: str, attributes: list[str]) -> None: ... + def end_element_handler(self, name: str) -> None: ... # only exists if __debug__ + +class ExpatBuilderNS(Namespaces, ExpatBuilder): ... +class FragmentBuilderNS(Namespaces, FragmentBuilder): ... +class ParseEscape(Exception): ... + +class InternalSubsetExtractor(ExpatBuilder): + subset: str | list[str] | None = None + def getSubset(self) -> str: ... + def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> None: ... # type: ignore[override] + def parseString(self, string: str | ReadableBuffer) -> None: ... # type: ignore[override] + def start_doctype_decl_handler( # type: ignore[override] + self, name: str, publicId: str | None, systemId: str | None, has_internal_subset: bool + ) -> None: ... + def end_doctype_decl_handler(self) -> Never: ... + def start_element_handler(self, name: str, attrs: list[str]) -> Never: ... + +def parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True) -> Document: ... +def parseString(string: str | ReadableBuffer, namespaces: bool = True) -> Document: ... +def parseFragment(file: str | SupportsRead[ReadableBuffer | str], context: Node, namespaces: bool = True) -> DocumentFragment: ... +def parseFragmentString(string: str | ReadableBuffer, context: Node, namespaces: bool = True) -> DocumentFragment: ... +def makeBuilder(options: Options) -> ExpatBuilderNS | ExpatBuilder: ... diff --git a/stdlib/xml/dom/minicompat.pyi b/stdlib/xml/dom/minicompat.pyi new file mode 100644 index 000000000000..6fcaee019dc2 --- /dev/null +++ b/stdlib/xml/dom/minicompat.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterable +from typing import Any, Literal, TypeVar + +__all__ = ["NodeList", "EmptyNodeList", "StringTypes", "defproperty"] + +_T = TypeVar("_T") + +StringTypes: tuple[type[str]] + +class NodeList(list[_T]): + __slots__ = () + @property + def length(self) -> int: ... + def item(self, index: int) -> _T | None: ... + +class EmptyNodeList(tuple[()]): + __slots__ = () + @property + def length(self) -> Literal[0]: ... + def item(self, index: int) -> None: ... + def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] + def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... + +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/stdlib/xml/dom/minidom.pyi b/stdlib/xml/dom/minidom.pyi new file mode 100644 index 000000000000..7d287a6c9b60 --- /dev/null +++ b/stdlib/xml/dom/minidom.pyi @@ -0,0 +1,693 @@ +import xml.dom +from _collections_abc import dict_keys, dict_values +from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, ClassVar, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self +from xml.dom.minicompat import EmptyNodeList, NodeList +from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS +from xml.sax.xmlreader import XMLReader + +_NSName: TypeAlias = tuple[str | None, str] + +# Entity can also have children, but it's not implemented the same way as the +# others, so is deliberately omitted here. +_NodesWithChildren: TypeAlias = DocumentFragment | Attr | Element | Document +_NodesThatAreChildren: TypeAlias = CDATASection | Comment | DocumentType | Element | Notation | ProcessingInstruction | Text + +_AttrChildren: TypeAlias = Text # Also EntityReference, but we don't implement it +_ElementChildren: TypeAlias = Element | ProcessingInstruction | Comment | Text | CDATASection +_EntityChildren: TypeAlias = Text # I think; documentation is a little unclear +_DocumentFragmentChildren: TypeAlias = Element | Text | CDATASection | ProcessingInstruction | Comment | Notation +_DocumentChildren: TypeAlias = Comment | DocumentType | Element | ProcessingInstruction + +_N = TypeVar("_N", bound=Node) +_ChildNodeVar = TypeVar("_ChildNodeVar", bound=_NodesThatAreChildren) +_ChildNodePlusFragmentVar = TypeVar("_ChildNodePlusFragmentVar", bound=_NodesThatAreChildren | DocumentFragment) +_DocumentChildrenVar = TypeVar("_DocumentChildrenVar", bound=_DocumentChildren) +_ImportableNodeVar = TypeVar( + "_ImportableNodeVar", + bound=DocumentFragment + | Attr + | Element + | ProcessingInstruction + | CharacterData + | Text + | Comment + | CDATASection + | Entity + | Notation, +) + +@type_check_only +class _DOMErrorHandler(Protocol): + def handleError(self, error: Exception) -> bool: ... + +@type_check_only +class _UserDataHandler(Protocol): + def handle(self, operation: int, key: str, data: Any, src: Node, dst: Node) -> None: ... + +def parse( + file: str | SupportsRead[ReadableBuffer | str], parser: XMLReader | None = None, bufsize: int | None = None +) -> Document: ... +def parseString(string: str | ReadableBuffer, parser: XMLReader | None = None) -> Document: ... + +@overload +def getDOMImplementation(features: None = None) -> DOMImplementation: ... +@overload +def getDOMImplementation(features: str | Iterable[tuple[str, str | None]]) -> DOMImplementation | None: ... + +class Node(xml.dom.Node): + parentNode: _NodesWithChildren | Entity | None + ownerDocument: Document | None + nextSibling: _NodesThatAreChildren | None + previousSibling: _NodesThatAreChildren | None + namespaceURI: str | None # non-null only for Element and Attr + prefix: str | None # non-null only for NS Element and Attr + + # These aren't defined on Node, but they exist on all Node subclasses + # and various methods of Node require them to exist. + childNodes: ( + NodeList[_DocumentFragmentChildren] + | NodeList[_AttrChildren] + | NodeList[_ElementChildren] + | NodeList[_DocumentChildren] + | NodeList[_EntityChildren] + | EmptyNodeList + ) + nodeType: ClassVar[Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]] + nodeName: str | None # only possibly None on DocumentType + + # Not defined on Node, but exist on all Node subclasses. + nodeValue: str | None # non-null for Attr, ProcessingInstruction, Text, Comment, and CDATASection + attributes: NamedNodeMap | None # non-null only for Element + + @property + def firstChild(self) -> _NodesThatAreChildren | None: ... + @property + def lastChild(self) -> _NodesThatAreChildren | None: ... + @property + def localName(self) -> str | None: ... # non-null only for Element and Attr + def __bool__(self) -> Literal[True]: ... + + @overload + def toxml(self, encoding: str, standalone: bool | None = None) -> bytes: ... + @overload + def toxml(self, encoding: None = None, standalone: bool | None = None) -> str: ... + + @overload + def toprettyxml( + self, + indent: str = "\t", + newl: str = "\n", + # Handle any case where encoding is not provided or where it is passed with None + encoding: None = None, + standalone: bool | None = None, + ) -> str: ... + @overload + def toprettyxml( + self, + indent: str, + newl: str, + # Handle cases where encoding is passed as str *positionally* + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... + @overload + def toprettyxml( + self, + indent: str = "\t", + newl: str = "\n", + # Handle all cases where encoding is passed as a keyword argument; because standalone + # comes after, it will also have to be a keyword arg if encoding is + *, + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... + + def hasChildNodes(self) -> bool: ... + def insertBefore( # type: ignore[misc] + self: _NodesWithChildren, # pyright: ignore[reportGeneralTypeIssues] + newChild: _ChildNodePlusFragmentVar, + refChild: _NodesThatAreChildren | None, + ) -> _ChildNodePlusFragmentVar: ... + def appendChild( # type: ignore[misc] + self: _NodesWithChildren, node: _ChildNodePlusFragmentVar # pyright: ignore[reportGeneralTypeIssues] + ) -> _ChildNodePlusFragmentVar: ... + + @overload + def replaceChild( # type: ignore[misc] + self: _NodesWithChildren, newChild: DocumentFragment, oldChild: _ChildNodeVar + ) -> _ChildNodeVar | DocumentFragment: ... + @overload + def replaceChild( # type: ignore[misc] + self: _NodesWithChildren, newChild: _NodesThatAreChildren, oldChild: _ChildNodeVar + ) -> _ChildNodeVar | None: ... + + def removeChild(self: _NodesWithChildren, oldChild: _ChildNodeVar) -> _ChildNodeVar: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def normalize(self: _NodesWithChildren) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + def cloneNode(self, deep: bool) -> Self | None: ... + def isSupported(self, feature: str, version: str | None) -> bool: ... + def isSameNode(self, other: Node) -> bool: ... + def getInterface(self, feature: str) -> Self | None: ... + def getUserData(self, key: str) -> Any | None: ... + def setUserData(self, key: str, data: Any, handler: _UserDataHandler) -> Any: ... + def unlink(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, et: type[BaseException] | None, ev: BaseException | None, tb: TracebackType | None) -> None: ... + +_DFChildrenVar = TypeVar("_DFChildrenVar", bound=_DocumentFragmentChildren) +_DFChildrenPlusFragment = TypeVar("_DFChildrenPlusFragment", bound=_DocumentFragmentChildren | DocumentFragment) + +class DocumentFragment(Node): + nodeType: ClassVar[Literal[11]] + nodeName: Literal["#document-fragment"] + nodeValue: None + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_DocumentFragmentChildren] + @property + def firstChild(self) -> _DocumentFragmentChildren | None: ... + @property + def lastChild(self) -> _DocumentFragmentChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + def __init__(self) -> None: ... + def insertBefore( # type: ignore[override] + self, newChild: _DFChildrenPlusFragment, refChild: _DocumentFragmentChildren | None + ) -> _DFChildrenPlusFragment: ... + def appendChild(self, node: _DFChildrenPlusFragment) -> _DFChildrenPlusFragment: ... # type: ignore[override] + + @overload # type: ignore[override] + def replaceChild(self, newChild: DocumentFragment, oldChild: _DFChildrenVar) -> _DFChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _DocumentFragmentChildren, oldChild: _DFChildrenVar) -> _DFChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _DFChildrenVar) -> _DFChildrenVar: ... # type: ignore[override] + +_AttrChildrenVar = TypeVar("_AttrChildrenVar", bound=_AttrChildren) +_AttrChildrenPlusFragment = TypeVar("_AttrChildrenPlusFragment", bound=_AttrChildren | DocumentFragment) + +class Attr(Node): + __slots__ = ("_name", "_value", "namespaceURI", "_prefix", "childNodes", "_localName", "ownerDocument", "ownerElement") + nodeType: ClassVar[Literal[2]] + nodeName: str # same as Attr.name + nodeValue: str # same as Attr.value + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_AttrChildren] + @property + def firstChild(self) -> _AttrChildren | None: ... + @property + def lastChild(self) -> _AttrChildren | None: ... + + namespaceURI: str | None + prefix: str | None + @property + def localName(self) -> str: ... + + name: str + value: str + specified: bool + ownerElement: Element | None + + def __init__( + self, qName: str, namespaceURI: str | None = None, localName: str | None = None, prefix: str | None = None + ) -> None: ... + def unlink(self) -> None: ... + @property + def isId(self) -> bool: ... + @property + def schemaType(self) -> TypeInfo: ... + def insertBefore(self, newChild: _AttrChildrenPlusFragment, refChild: _AttrChildren | None) -> _AttrChildrenPlusFragment: ... # type: ignore[override] + def appendChild(self, node: _AttrChildrenPlusFragment) -> _AttrChildrenPlusFragment: ... # type: ignore[override] + + @overload # type: ignore[override] + def replaceChild(self, newChild: DocumentFragment, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _AttrChildren, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _AttrChildrenVar) -> _AttrChildrenVar: ... # type: ignore[override] + +# In the DOM, this interface isn't specific to Attr, but our implementation is +# because that's the only place we use it. +class NamedNodeMap: + __slots__ = ("_attrs", "_attrsNS", "_ownerElement") + def __init__(self, attrs: dict[str, Attr], attrsNS: dict[_NSName, Attr], ownerElement: Element) -> None: ... + @property + def length(self) -> int: ... + def item(self, index: int) -> Node | None: ... + def items(self) -> list[tuple[str, str]]: ... + def itemsNS(self) -> list[tuple[_NSName, str]]: ... + def __contains__(self, key: str | _NSName) -> bool: ... + def keys(self) -> dict_keys[str, Attr]: ... + def keysNS(self) -> dict_keys[_NSName, Attr]: ... + def values(self) -> dict_values[str, Attr]: ... + def get(self, name: str, value: Attr | None = None) -> Attr | None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ge__(self, other: NamedNodeMap) -> bool: ... + def __gt__(self, other: NamedNodeMap) -> bool: ... + def __le__(self, other: NamedNodeMap) -> bool: ... + def __lt__(self, other: NamedNodeMap) -> bool: ... + def __getitem__(self, attname_or_tuple: _NSName | str) -> Attr: ... + def __setitem__(self, attname: str, value: Attr | str) -> None: ... + def getNamedItem(self, name: str) -> Attr | None: ... + def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ... + def removeNamedItem(self, name: str) -> Attr: ... + def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr: ... + def setNamedItem(self, node: Attr) -> Attr | None: ... + def setNamedItemNS(self, node: Attr) -> Attr | None: ... + def __delitem__(self, attname_or_tuple: _NSName | str) -> None: ... + +AttributeList = NamedNodeMap + +class TypeInfo: + __slots__ = ("namespace", "name") + namespace: str | None + name: str | None + def __init__(self, namespace: Incomplete | None, name: str | None) -> None: ... + +_ElementChildrenVar = TypeVar("_ElementChildrenVar", bound=_ElementChildren) +_ElementChildrenPlusFragment = TypeVar("_ElementChildrenPlusFragment", bound=_ElementChildren | DocumentFragment) + +class Element(Node): + __slots__ = ( + "ownerDocument", + "parentNode", + "tagName", + "nodeName", + "prefix", + "namespaceURI", + "_localName", + "childNodes", + "_attrs", + "_attrsNS", + "nextSibling", + "previousSibling", + ) + nodeType: ClassVar[Literal[1]] + nodeName: str # same as Element.tagName + nodeValue: None + @property + def attributes(self) -> NamedNodeMap: ... # type: ignore[override] + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: NodeList[_ElementChildren] + @property + def firstChild(self) -> _ElementChildren | None: ... + @property + def lastChild(self) -> _ElementChildren | None: ... + + namespaceURI: str | None + prefix: str | None + @property + def localName(self) -> str: ... + + schemaType: TypeInfo + tagName: str + + def __init__( + self, tagName: str, namespaceURI: str | None = None, prefix: str | None = None, localName: str | None = None + ) -> None: ... + def unlink(self) -> None: ... + def getAttribute(self, attname: str) -> str: ... + def getAttributeNS(self, namespaceURI: str | None, localName: str) -> str: ... + def setAttribute(self, attname: str, value: str) -> None: ... + def setAttributeNS(self, namespaceURI: str | None, qualifiedName: str, value: str) -> None: ... + def getAttributeNode(self, attrname: str) -> Attr | None: ... + def getAttributeNodeNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ... + def setAttributeNode(self, attr: Attr) -> Attr | None: ... + setAttributeNodeNS = setAttributeNode + def removeAttribute(self, name: str) -> None: ... + def removeAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ... + def removeAttributeNode(self, node: Attr) -> Attr: ... + removeAttributeNodeNS = removeAttributeNode + def hasAttribute(self, name: str) -> bool: ... + def hasAttributeNS(self, namespaceURI: str | None, localName: str) -> bool: ... + def getElementsByTagName(self, name: str) -> NodeList[Element]: ... + def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + def hasAttributes(self) -> bool: ... + def setIdAttribute(self, name: str) -> None: ... + def setIdAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ... + def setIdAttributeNode(self, idAttr: Attr) -> None: ... + def insertBefore( # type: ignore[override] + self, newChild: _ElementChildrenPlusFragment, refChild: _ElementChildren | None + ) -> _ElementChildrenPlusFragment: ... + def appendChild(self, node: _ElementChildrenPlusFragment) -> _ElementChildrenPlusFragment: ... # type: ignore[override] + + @overload # type: ignore[override] + def replaceChild( + self, newChild: DocumentFragment, oldChild: _ElementChildrenVar + ) -> _ElementChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _ElementChildren, oldChild: _ElementChildrenVar) -> _ElementChildrenVar | None: ... # type: ignore[override] + + def removeChild(self, oldChild: _ElementChildrenVar) -> _ElementChildrenVar: ... # type: ignore[override] + +class Childless: + __slots__ = () + attributes: None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> Never: ... + def hasChildNodes(self) -> Literal[False]: ... + def insertBefore( + self, newChild: _NodesThatAreChildren | DocumentFragment, refChild: _NodesThatAreChildren | None + ) -> Never: ... + def removeChild(self, oldChild: _NodesThatAreChildren) -> Never: ... + def normalize(self) -> None: ... + def replaceChild(self, newChild: _NodesThatAreChildren | DocumentFragment, oldChild: _NodesThatAreChildren) -> Never: ... + +class ProcessingInstruction(Childless, Node): + __slots__ = ("target", "data") + nodeType: ClassVar[Literal[7]] + nodeName: str # same as ProcessingInstruction.target + nodeValue: str # same as ProcessingInstruction.data + attributes: None + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + target: str + data: str + + def __init__(self, target: str, data: str) -> None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + +class CharacterData(Childless, Node): + __slots__ = ("_data", "ownerDocument", "parentNode", "previousSibling", "nextSibling") + nodeValue: str + attributes: None + + childNodes: EmptyNodeList + nextSibling: _NodesThatAreChildren | None + previousSibling: _NodesThatAreChildren | None + + @property + def localName(self) -> None: ... + + ownerDocument: Document | None + data: str + + def __init__(self) -> None: ... + @property + def length(self) -> int: ... + def __len__(self) -> int: ... + def substringData(self, offset: int, count: int) -> str: ... + def appendData(self, arg: str) -> None: ... + def insertData(self, offset: int, arg: str) -> None: ... + def deleteData(self, offset: int, count: int) -> None: ... + def replaceData(self, offset: int, count: int, arg: str) -> None: ... + +class Text(CharacterData): + __slots__ = () + nodeType: ClassVar[Literal[3]] + nodeName: Literal["#text"] + nodeValue: str # same as CharacterData.data, the content of the text node + attributes: None + + parentNode: Attr | Element | DocumentFragment | None + nextSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None + previousSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + data: str + def splitText(self, offset: int) -> Self: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + def replaceWholeText(self, content: str) -> Self | None: ... + @property + def isWhitespaceInElementContent(self) -> bool: ... + @property + def wholeText(self) -> str: ... + +class Comment(CharacterData): + nodeType: ClassVar[Literal[8]] + nodeName: Literal["#comment"] + nodeValue: str # same as CharacterData.data, the content of the comment + attributes: None + + parentNode: Document | Element | DocumentFragment | None + nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + def __init__(self, data: str) -> None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + +class CDATASection(Text): + __slots__ = () + nodeType: ClassVar[Literal[4]] # type: ignore[assignment] + nodeName: Literal["#cdata-section"] # type: ignore[assignment] + nodeValue: str # same as CharacterData.data, the content of the CDATA Section + attributes: None + + parentNode: Element | DocumentFragment | None + nextSibling: _DocumentFragmentChildren | _ElementChildren | None + previousSibling: _DocumentFragmentChildren | _ElementChildren | None + + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + +class ReadOnlySequentialNamedNodeMap(Generic[_N]): + __slots__ = ("_seq",) + def __init__(self, seq: Sequence[_N] = ()) -> None: ... + def __len__(self) -> int: ... + def getNamedItem(self, name: str) -> _N | None: ... + def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> _N | None: ... + def __getitem__(self, name_or_tuple: str | _NSName) -> _N | None: ... + def item(self, index: int) -> _N | None: ... + def removeNamedItem(self, name: str) -> Never: ... + def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Never: ... + def setNamedItem(self, node: Node) -> Never: ... + def setNamedItemNS(self, node: Node) -> Never: ... + @property + def length(self) -> int: ... + +class Identified: + __slots__ = ("publicId", "systemId") + publicId: str | None + systemId: str | None + +class DocumentType(Identified, Childless, Node): + nodeType: ClassVar[Literal[10]] + nodeName: str | None # same as DocumentType.name + nodeValue: None + attributes: None + + parentNode: Document | None + nextSibling: _DocumentChildren | None + previousSibling: _DocumentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + name: str | None + internalSubset: str | None + entities: ReadOnlySequentialNamedNodeMap[Entity] + notations: ReadOnlySequentialNamedNodeMap[Notation] + + def __init__(self, qualifiedName: str | None) -> None: ... + def cloneNode(self, deep: bool) -> DocumentType | None: ... + def writexml(self, writer: SupportsWrite[str], indent: str = "", addindent: str = "", newl: str = "") -> None: ... + +class Entity(Identified, Node): + nodeType: ClassVar[Literal[6]] + nodeName: str # entity name + nodeValue: None + attributes: None + + parentNode: None + nextSibling: None + previousSibling: None + childNodes: NodeList[_EntityChildren] + @property + def firstChild(self) -> _EntityChildren | None: ... + @property + def lastChild(self) -> _EntityChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + actualEncoding: str | None + encoding: str | None + version: str | None + notationName: str | None + + def __init__(self, name: str, publicId: str | None, systemId: str | None, notation: str | None) -> None: ... + def appendChild(self, newChild: _EntityChildren) -> Never: ... # type: ignore[override] + def insertBefore(self, newChild: _EntityChildren, refChild: _EntityChildren | None) -> Never: ... # type: ignore[override] + def removeChild(self, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] + def replaceChild(self, newChild: _EntityChildren, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] + +class Notation(Identified, Childless, Node): + nodeType: ClassVar[Literal[12]] + nodeName: str # notation name + nodeValue: None + attributes: None + + parentNode: DocumentFragment | None + nextSibling: _DocumentFragmentChildren | None + previousSibling: _DocumentFragmentChildren | None + childNodes: EmptyNodeList + @property + def firstChild(self) -> None: ... + @property + def lastChild(self) -> None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + def __init__(self, name: str, publicId: str | None, systemId: str | None) -> None: ... + +class DOMImplementation(DOMImplementationLS): + def hasFeature(self, feature: str, version: str | None) -> bool: ... + def createDocument(self, namespaceURI: str | None, qualifiedName: str | None, doctype: DocumentType | None) -> Document: ... + def createDocumentType(self, qualifiedName: str | None, publicId: str | None, systemId: str | None) -> DocumentType: ... + def getInterface(self, feature: str) -> Self | None: ... + +class ElementInfo: + __slots__ = ("tagName",) + tagName: str + def __init__(self, name: str) -> None: ... + def getAttributeType(self, aname: str) -> TypeInfo: ... + def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ... + def isElementContent(self) -> bool: ... + def isEmpty(self) -> bool: ... + def isId(self, aname: str) -> bool: ... + def isIdNS(self, namespaceURI: str | None, localName: str) -> bool: ... + +_DocumentChildrenPlusFragment = TypeVar("_DocumentChildrenPlusFragment", bound=_DocumentChildren | DocumentFragment) + +class Document(Node, DocumentLS): + __slots__ = ("_elem_info", "doctype", "_id_search_stack", "childNodes", "_id_cache") + nodeType: ClassVar[Literal[9]] + nodeName: Literal["#document"] + nodeValue: None + attributes: None + + parentNode: None + previousSibling: None + nextSibling: None + childNodes: NodeList[_DocumentChildren] + @property + def firstChild(self) -> _DocumentChildren | None: ... + @property + def lastChild(self) -> _DocumentChildren | None: ... + + namespaceURI: None + prefix: None + @property + def localName(self) -> None: ... + + implementation: DOMImplementation + actualEncoding: str | None + encoding: str | None + standalone: bool | None + version: str | None + strictErrorChecking: bool + errorHandler: _DOMErrorHandler | None + documentURI: str | None + doctype: DocumentType | None + documentElement: Element | None + + def __init__(self) -> None: ... + def appendChild(self, node: _DocumentChildrenVar) -> _DocumentChildrenVar: ... # type: ignore[override] + def removeChild(self, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar: ... # type: ignore[override] + def unlink(self) -> None: ... + def cloneNode(self, deep: bool) -> Document | None: ... + def createDocumentFragment(self) -> DocumentFragment: ... + def createElement(self, tagName: str) -> Element: ... + def createTextNode(self, data: str) -> Text: ... + def createCDATASection(self, data: str) -> CDATASection: ... + def createComment(self, data: str) -> Comment: ... + def createProcessingInstruction(self, target: str, data: str) -> ProcessingInstruction: ... + def createAttribute(self, qName: str) -> Attr: ... + def createElementNS(self, namespaceURI: str | None, qualifiedName: str) -> Element: ... + def createAttributeNS(self, namespaceURI: str | None, qualifiedName: str) -> Attr: ... + def getElementById(self, id: str) -> Element | None: ... + def getElementsByTagName(self, name: str) -> NodeList[Element]: ... + def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... + def isSupported(self, feature: str, version: str | None) -> bool: ... + def importNode(self, node: _ImportableNodeVar, deep: bool) -> _ImportableNodeVar: ... + def writexml( + self, + writer: SupportsWrite[str], + indent: str = "", + addindent: str = "", + newl: str = "", + encoding: str | None = None, + standalone: bool | None = None, + ) -> None: ... + + @overload + def renameNode(self, n: Element, namespaceURI: str, name: str) -> Element: ... + @overload + def renameNode(self, n: Attr, namespaceURI: str, name: str) -> Attr: ... + @overload + def renameNode(self, n: Element | Attr, namespaceURI: str, name: str) -> Element | Attr: ... + + def insertBefore( + self, newChild: _DocumentChildrenPlusFragment, refChild: _DocumentChildren | None # type: ignore[override] + ) -> _DocumentChildrenPlusFragment: ... + + @overload # type: ignore[override] + def replaceChild( + self, newChild: DocumentFragment, oldChild: _DocumentChildrenVar + ) -> _DocumentChildrenVar | DocumentFragment: ... + @overload + def replaceChild(self, newChild: _DocumentChildren, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar | None: ... diff --git a/stdlib/xml/dom/pulldom.pyi b/stdlib/xml/dom/pulldom.pyi new file mode 100644 index 000000000000..7014c865bcdd --- /dev/null +++ b/stdlib/xml/dom/pulldom.pyi @@ -0,0 +1,109 @@ +import sys +from _typeshed import Incomplete, Unused +from collections.abc import MutableSequence, Sequence +from typing import Final, Literal, TypeAlias +from typing_extensions import Never, Self +from xml.dom.minidom import Comment, Document, DOMImplementation, Element, ProcessingInstruction, Text +from xml.sax import _SupportsReadClose +from xml.sax.handler import ContentHandler +from xml.sax.xmlreader import AttributesImpl, AttributesNSImpl, Locator, XMLReader + +START_ELEMENT: Final = "START_ELEMENT" +END_ELEMENT: Final = "END_ELEMENT" +COMMENT: Final = "COMMENT" +START_DOCUMENT: Final = "START_DOCUMENT" +END_DOCUMENT: Final = "END_DOCUMENT" +PROCESSING_INSTRUCTION: Final = "PROCESSING_INSTRUCTION" +IGNORABLE_WHITESPACE: Final = "IGNORABLE_WHITESPACE" +CHARACTERS: Final = "CHARACTERS" + +_NSName: TypeAlias = tuple[str | None, str] +_DocumentFactory: TypeAlias = DOMImplementation | None + +_Event: TypeAlias = ( + tuple[Literal["START_ELEMENT"], Element] + | tuple[Literal["END_ELEMENT"], Element] + | tuple[Literal["COMMENT"], Comment] + | tuple[Literal["START_DOCUMENT"], Document] + | tuple[Literal["END_DOCUMENT"], Document] + | tuple[Literal["PROCESSING_INSTRUCTION"], ProcessingInstruction] + | tuple[Literal["IGNORABLE_WHITESPACE"], Text] + | tuple[Literal["CHARACTERS"], Text] +) + +class PullDOM(ContentHandler): + document: Document | None + documentFactory: _DocumentFactory + + # firstEvent is a list of length 2 + # firstEvent[0] is always None + # firstEvent[1] is None prior to any events, after which it's a + # list of length 2, where the first item is of type _Event + # and the second item is None. + firstEvent: list[Incomplete] + + # lastEvent is also a list of length 2. The second item is always None, + # and the first item is of type _Event + # This is a slight lie: The second item is sometimes temporarily what was just + # described for the type of lastEvent, after which lastEvent is always updated + # with `self.lastEvent = self.lastEvent[1]`. + lastEvent: list[Incomplete] + + elementStack: MutableSequence[Element | Document] + pending_events: ( + list[Sequence[tuple[Literal["COMMENT"], str] | tuple[Literal["PROCESSING_INSTRUCTION"], str, str] | None]] | None + ) + def __init__(self, documentFactory: _DocumentFactory = None) -> None: ... + def pop(self) -> Element | Document: ... + def setDocumentLocator(self, locator: Locator) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ... + def endElementNS(self, name: _NSName, tagName: str | None) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def comment(self, s: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def characters(self, chars: str) -> None: ... + def startDocument(self) -> None: ... + def buildDocument(self, uri: str | None, tagname: str | None) -> Element: ... + def endDocument(self) -> None: ... + def clear(self) -> None: ... + +class ErrorHandler: + def warning(self, exception: BaseException) -> None: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + +class DOMEventStream: + stream: _SupportsReadClose[bytes] | _SupportsReadClose[str] + parser: XMLReader # Set to none after .clear() is called + bufsize: int + pulldom: PullDOM + def __init__(self, stream: _SupportsReadClose[bytes] | _SupportsReadClose[str], parser: XMLReader, bufsize: int) -> None: ... + if sys.version_info < (3, 11): + def __getitem__(self, pos: Unused) -> _Event: ... + + def __next__(self) -> _Event: ... + def __iter__(self) -> Self: ... + def getEvent(self) -> _Event | None: ... + def expandNode(self, node: Document) -> None: ... + def reset(self) -> None: ... + def clear(self) -> None: ... + +class SAX2DOM(PullDOM): + def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def characters(self, chars: str) -> None: ... + +default_bufsize: Final[int] + +def parse( + stream_or_string: str | _SupportsReadClose[bytes] | _SupportsReadClose[str], + parser: XMLReader | None = None, + bufsize: int | None = None, +) -> DOMEventStream: ... +def parseString(string: str, parser: XMLReader | None = None) -> DOMEventStream: ... diff --git a/stdlib/xml/dom/xmlbuilder.pyi b/stdlib/xml/dom/xmlbuilder.pyi new file mode 100644 index 000000000000..686c9d8efe8f --- /dev/null +++ b/stdlib/xml/dom/xmlbuilder.pyi @@ -0,0 +1,82 @@ +from _typeshed import SupportsRead +from typing import Any, Final, Literal +from typing_extensions import Never +from xml.dom.minidom import Document, Node, _DOMErrorHandler + +__all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] + +class Options: + namespaces: int + namespace_declarations: bool + validation: bool + external_parameter_entities: bool + external_general_entities: bool + external_dtd_subset: bool + validate_if_schema: bool + validate: bool + datatype_normalization: bool + create_entity_ref_nodes: bool + entities: bool + whitespace_in_element_content: bool + cdata_sections: bool + comments: bool + charset_overrides_xml_encoding: bool + infoset: bool + supported_mediatypes_only: bool + errorHandler: _DOMErrorHandler | None + filter: DOMBuilderFilter | None + +class DOMBuilder: + entityResolver: DOMEntityResolver | None + errorHandler: _DOMErrorHandler | None + filter: DOMBuilderFilter | None + ACTION_REPLACE: Final = 1 + ACTION_APPEND_AS_CHILDREN: Final = 2 + ACTION_INSERT_AFTER: Final = 3 + ACTION_INSERT_BEFORE: Final = 4 + def __init__(self) -> None: ... + def setFeature(self, name: str, state: int) -> None: ... + def supportsFeature(self, name: str) -> bool: ... + def canSetFeature(self, name: str, state: Literal[1, 0]) -> bool: ... + # getFeature could return any attribute from an instance of `Options` + def getFeature(self, name: str) -> Any: ... + def parseURI(self, uri: str) -> Document: ... + def parse(self, input: DOMInputSource) -> Document: ... + def parseWithContext(self, input: DOMInputSource, cnode: Node, action: Literal[1, 2, 3, 4]) -> Never: ... + +class DOMEntityResolver: + __slots__ = ("_opener",) + def resolveEntity(self, publicId: str | None, systemId: str) -> DOMInputSource: ... + +class DOMInputSource: + __slots__ = ("byteStream", "characterStream", "stringData", "encoding", "publicId", "systemId", "baseURI") + byteStream: SupportsRead[bytes] | None + characterStream: SupportsRead[str] | None + stringData: str | None + encoding: str | None + publicId: str | None + systemId: str | None + baseURI: str | None + +class DOMBuilderFilter: + FILTER_ACCEPT: Final = 1 + FILTER_REJECT: Final = 2 + FILTER_SKIP: Final = 3 + FILTER_INTERRUPT: Final = 4 + whatToShow: int + def acceptNode(self, element: Node) -> Literal[1, 2, 3, 4]: ... + def startContainer(self, element: Node) -> Literal[1, 2, 3, 4]: ... + +class DocumentLS: + async_: bool + def abort(self) -> Never: ... + def load(self, uri: str) -> Never: ... + def loadXML(self, source: str) -> Never: ... + def saveXML(self, snode: Node | None) -> str: ... + +class DOMImplementationLS: + MODE_SYNCHRONOUS: Final = 1 + MODE_ASYNCHRONOUS: Final = 2 + def createDOMBuilder(self, mode: Literal[1], schemaType: None) -> DOMBuilder: ... + def createDOMWriter(self) -> Never: ... + def createDOMInputSource(self) -> DOMInputSource: ... diff --git a/stdlib/xml/etree/ElementInclude.pyi b/stdlib/xml/etree/ElementInclude.pyi new file mode 100644 index 000000000000..5db08fb0df05 --- /dev/null +++ b/stdlib/xml/etree/ElementInclude.pyi @@ -0,0 +1,28 @@ +from _typeshed import FileDescriptorOrPath +from typing import Final, Literal, Protocol, overload, type_check_only +from xml.etree.ElementTree import Element + +@type_check_only +class _Loader(Protocol): + @overload + def __call__(self, href: FileDescriptorOrPath, parse: Literal["xml"], encoding: str | None = None) -> Element: ... + @overload + def __call__(self, href: FileDescriptorOrPath, parse: Literal["text"], encoding: str | None = None) -> str: ... + +XINCLUDE: Final = "{http://www.w3.org/2001/XInclude}" + +XINCLUDE_INCLUDE: Final = "{http://www.w3.org/2001/XInclude}include" +XINCLUDE_FALLBACK: Final = "{http://www.w3.org/2001/XInclude}fallback" + +DEFAULT_MAX_INCLUSION_DEPTH: Final = 6 + +class FatalIncludeError(SyntaxError): ... + +@overload +def default_loader(href: FileDescriptorOrPath, parse: Literal["xml"], encoding: str | None = None) -> Element: ... +@overload +def default_loader(href: FileDescriptorOrPath, parse: Literal["text"], encoding: str | None = None) -> str: ... + +def include(elem: Element, loader: _Loader | None = None, base_url: str | None = None, max_depth: int | None = 6) -> None: ... + +class LimitedRecursiveIncludeError(FatalIncludeError): ... diff --git a/stdlib/xml/etree/ElementPath.pyi b/stdlib/xml/etree/ElementPath.pyi new file mode 100644 index 000000000000..1dd6f86cead6 --- /dev/null +++ b/stdlib/xml/etree/ElementPath.pyi @@ -0,0 +1,42 @@ +from collections.abc import Callable, Generator, Iterable +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload +from xml.etree.ElementTree import Element + +xpath_tokenizer_re: Final[Pattern[str]] + +_Token: TypeAlias = tuple[str, str] +_Next: TypeAlias = Callable[[], _Token] +_Callback: TypeAlias = Callable[[_SelectorContext, Iterable[Element]], Generator[Element]] +_T = TypeVar("_T") + +def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = None) -> Generator[_Token]: ... +def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... +def prepare_child(next: _Next, token: _Token) -> _Callback: ... +def prepare_star(next: _Next, token: _Token) -> _Callback: ... +def prepare_self(next: _Next, token: _Token) -> _Callback: ... +def prepare_descendant(next: _Next, token: _Token) -> _Callback | None: ... +def prepare_parent(next: _Next, token: _Token) -> _Callback: ... +def prepare_predicate(next: _Next, token: _Token) -> _Callback | None: ... + +ops: Final[dict[str, Callable[[_Next, _Token], _Callback | None]]] + +class _SelectorContext: + parent_map: dict[Element, Element] | None + root: Element + def __init__(self, root: Element) -> None: ... + +@overload +def iterfind( # type: ignore[overload-overlap] + elem: Element[Any], path: Literal[""], namespaces: dict[str, str] | None = None +) -> None: ... +@overload +def iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + +def find(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... +def findall(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + +@overload +def findtext(elem: Element[Any], path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... +@overload +def findtext(elem: Element[Any], path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... diff --git a/stdlib/xml/etree/ElementTree.pyi b/stdlib/xml/etree/ElementTree.pyi new file mode 100644 index 000000000000..c77af2cb4dd1 --- /dev/null +++ b/stdlib/xml/etree/ElementTree.pyi @@ -0,0 +1,402 @@ +import sys +from _collections_abc import dict_keys +from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite +from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence +from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeAlias, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import deprecated, disjoint_base +from xml.parsers.expat import XMLParserType + +__all__ = [ + "C14NWriterTarget", + "Comment", + "dump", + "Element", + "ElementTree", + "canonicalize", + "fromstring", + "fromstringlist", + "indent", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", +] +if sys.version_info < (3, 15): + __all__ += ["VERSION"] + +_T = TypeVar("_T") +_FileRead: TypeAlias = FileDescriptorOrPath | SupportsRead[bytes] | SupportsRead[str] +_FileWriteC14N: TypeAlias = FileDescriptorOrPath | SupportsWrite[bytes] +_FileWrite: TypeAlias = _FileWriteC14N | SupportsWrite[str] + +VERSION: Final[str] + +class ParseError(SyntaxError): + code: int + position: tuple[int, int] + +# In reality it works based on `.tag` attribute duck typing. +def iselement(element: object) -> TypeGuard[Element]: ... + +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: None = None, + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> str: ... +@overload +def canonicalize( + xml_data: str | ReadableBuffer | None = None, + *, + out: SupportsWrite[str], + from_file: _FileRead | None = None, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, +) -> None: ... + +# The tag for Element can be set to the Comment or ProcessingInstruction +# functions defined in this module. +_ElementCallable: TypeAlias = Callable[..., Element[_ElementCallable]] + +_Tag = TypeVar("_Tag", default=str, bound=str | _ElementCallable) +_OtherTag = TypeVar("_OtherTag", default=str, bound=str | _ElementCallable) + +@disjoint_base +class Element(Generic[_Tag]): + tag: _Tag + attrib: dict[str, str] + text: str | None + tail: str | None + def __init__(self, tag: _Tag, attrib: dict[str, str] = {}, **extra: str) -> None: ... + def append(self, subelement: Element[Any], /) -> None: ... + def clear(self) -> None: ... + def extend(self, elements: Iterable[Element[Any]], /) -> None: ... + def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... + def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + + @overload + def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... + @overload + def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + + @overload + def get(self, key: str, default: None = None) -> str | None: ... + @overload + def get(self, key: str, default: _T) -> str | _T: ... + + def insert(self, index: int, subelement: Element[Any], /) -> None: ... + def items(self) -> ItemsView[str, str]: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... + + @overload + def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] + @overload + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + + def itertext(self) -> Generator[str]: ... + def keys(self) -> dict_keys[str, str]: ... + # makeelement returns the type of self in Python impl, but not in C impl + def makeelement(self, tag: _OtherTag, attrib: dict[str, str], /) -> Element[_OtherTag]: ... + def remove(self, subelement: Element[Any], /) -> None: ... + def set(self, key: str, value: str, /) -> None: ... + def __copy__(self) -> Element[_Tag]: ... # returns the type of self in Python impl, but not in C impl + def __deepcopy__(self, memo: Any, /) -> Element: ... # Only exists in C impl + def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... + + @overload + def __getitem__(self, key: SupportsIndex, /) -> Element: ... + @overload + def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Element]: ... + + def __len__(self) -> int: ... + # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. + def __iter__(self) -> Iterator[Element]: ... + + @overload + def __setitem__(self, key: SupportsIndex, value: Element[Any], /) -> None: ... + @overload + def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Element[Any]], /) -> None: ... + + # Doesn't really exist in earlier versions, where __len__ is called implicitly instead + @deprecated("Testing an element's truth value is deprecated.") + def __bool__(self) -> bool: ... + +def SubElement(parent: Element[Any], tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ... +def Comment(text: str | None = None) -> Element[_ElementCallable]: ... +def ProcessingInstruction(target: str, text: str | None = None) -> Element[_ElementCallable]: ... + +PI = ProcessingInstruction + +class QName: + text: str + def __init__(self, text_or_uri: str, tag: str | None = None) -> None: ... + def __lt__(self, other: QName | str) -> bool: ... + def __le__(self, other: QName | str) -> bool: ... + def __gt__(self, other: QName | str) -> bool: ... + def __ge__(self, other: QName | str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +_Root = TypeVar("_Root", Element, Element | None, default=Element | None) + +class ElementTree(Generic[_Root]): + def __init__(self, element: Element[Any] | None = None, file: _FileRead | None = None) -> None: ... + def getroot(self) -> _Root: ... + def _setroot(self, element: Element[Any]) -> None: ... + def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... + def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... + + @overload + def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... + @overload + def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + + def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + + @overload + def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] + @overload + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + + def write( + self, + file_or_filename: _FileWrite, + encoding: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + short_empty_elements: bool = True, + ) -> None: ... + def write_c14n(self, file: _FileWriteC14N) -> None: ... + +HTML_EMPTY: Final[set[str]] + +def register_namespace(prefix: str, uri: str) -> None: ... + +@overload +def tostring( + element: Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> bytes: ... +@overload +def tostring( + element: Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> str: ... +@overload +def tostring( + element: Element[Any], + encoding: str, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> Any: ... + +@overload +def tostringlist( + element: Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[bytes]: ... +@overload +def tostringlist( + element: Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[str]: ... +@overload +def tostringlist( + element: Element[Any], + encoding: str, + method: Literal["xml", "html", "text", "c14n"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, +) -> list[Any]: ... + +def dump(elem: Element[Any] | ElementTree[Any]) -> None: ... +def indent(tree: Element[Any] | ElementTree[Any], space: str = " ", level: int = 0) -> None: ... +def parse(source: _FileRead, parser: XMLParser[Any] | None = None) -> ElementTree[Element]: ... + +# The type of the second element of the tuple yielded by iterparse depends +# on the event type in the first element of the tuple: +# * start, end: Element[str] +# * comment, pi: Element[_ElementCallable] +# * start-ns: tuple[str, str] (prefix, uri) +# * end-ns: None +_EventT_co = TypeVar("_EventT_co", bound=Element[str] | Element[_ElementCallable] | tuple[str, str] | None, covariant=True) +_EventType: TypeAlias = Literal["start", "end", "comment", "pi", "start-ns", "end-ns"] + +# This class is defined inside the body of iterparse. +@type_check_only +class _IterParseIterator(Iterator[tuple[_EventType, _EventT_co]], Protocol[_EventT_co]): + if sys.version_info >= (3, 13): + def close(self) -> None: ... + if sys.version_info >= (3, 11): + def __del__(self) -> None: ... + +# See the comment for _EventT_co above for possible iterator types. +@overload +def iterparse(source: _FileRead, events: Iterable[_EventType]) -> _IterParseIterator[Any]: ... +@overload +def iterparse(source: _FileRead, events: None = None) -> _IterParseIterator[Element[str]]: ... + +# In case a custom parser is passed, the type of the second element of the tuple +# yielded by iterparse depends on the parser. +@overload +@deprecated("The `parser` parameter is deprecated since Python 3.4.") +def iterparse(source: _FileRead, events: Iterable[_EventType], parser: XMLParser | None = None) -> _IterParseIterator[Any]: ... + +_EventQueue: TypeAlias = tuple[str] | tuple[str, tuple[str, str]] | tuple[str, None] + +class XMLPullParser(Generic[_EventT_co]): + def __init__(self, events: Iterable[_EventType] | None = None, *, _parser: XMLParser[_EventT_co] | None = None) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... + def close(self) -> None: ... + def read_events(self) -> Iterator[_EventQueue | tuple[_EventType, _EventT_co]]: ... + def flush(self) -> None: ... + +def XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ... +def XMLID(text: str | ReadableBuffer, parser: XMLParser | None = None) -> tuple[Element, dict[str, Element]]: ... + +# This is aliased to XML in the source. +fromstring = XML + +def fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser | None = None) -> Element: ... + +# This type is both not precise enough and too precise. The TreeBuilder +# requires the elementfactory to accept tag and attrs in its args and produce +# some kind of object that has .text and .tail properties. +# I've chosen to constrain the ElementFactory to always produce an Element +# because that is how almost everyone will use it. +# Unfortunately, the type of the factory arguments is dependent on how +# TreeBuilder is called by client code (they could pass strs, bytes or whatever); +# but we don't want to use a too-broad type, or it would be too hard to write +# elementfactories. +_ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element] + +@disjoint_base +class TreeBuilder: + # comment_factory can take None because passing None to Comment is not an error + def __init__( + self, + element_factory: _ElementFactory | None = None, + *, + comment_factory: Callable[[str | None], Element[Any]] | None = None, + pi_factory: Callable[[str, str | None], Element[Any]] | None = None, + insert_comments: bool = False, + insert_pis: bool = False, + ) -> None: ... + insert_comments: bool + insert_pis: bool + + def close(self) -> Element: ... + def data(self, data: str, /) -> None: ... + # tag and attrs are passed to the element_factory, so they could be anything + # depending on what the particular factory supports. + def start(self, tag: Any, attrs: dict[Any, Any], /) -> Element: ... + def end(self, tag: str, /) -> Element: ... + # These two methods have pos-only parameters in the C implementation + def comment(self, text: str | None, /) -> Element[Any]: ... + def pi(self, target: str, text: str | None = None, /) -> Element[Any]: ... + +class C14NWriterTarget: + def __init__( + self, + write: Callable[[str], object], + *, + with_comments: bool = False, + strip_text: bool = False, + rewrite_prefixes: bool = False, + qname_aware_tags: Iterable[str] | None = None, + qname_aware_attrs: Iterable[str] | None = None, + exclude_attrs: Iterable[str] | None = None, + exclude_tags: Iterable[str] | None = None, + ) -> None: ... + def data(self, data: str) -> None: ... + def start_ns(self, prefix: str, uri: str) -> None: ... + def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... + def end(self, tag: str) -> None: ... + def comment(self, text: str) -> None: ... + def pi(self, target: str, data: str) -> None: ... + +# The target type is tricky, because the implementation doesn't +# require any particular attribute to be present. This documents the attributes +# that can be present, but uncommenting any of them would require them. +@type_check_only +class _Target(Protocol): + # start: Callable[str, dict[str, str], Any] | None + # end: Callable[[str], Any] | None + # start_ns: Callable[[str, str], Any] | None + # end_ns: Callable[[str], Any] | None + # data: Callable[[str], Any] | None + # comment: Callable[[str], Any] + # pi: Callable[[str, str], Any] | None + # close: Callable[[], Any] | None + ... + +_E = TypeVar("_E", default=Element) + +# This is generic because the return type of close() depends on the target. +# The default target is TreeBuilder, which returns Element. +# C14NWriterTarget does not implement a close method, so using it results +# in a type of XMLParser[None]. +@disjoint_base +class XMLParser(Generic[_E]): + parser: XMLParserType + target: _Target + # TODO: what is entity used for??? + entity: dict[str, str] + version: str + def __init__(self, *, target: _Target | None = None, encoding: str | None = None) -> None: ... + def close(self) -> _E: ... + def feed(self, data: str | ReadableBuffer, /) -> None: ... + def flush(self) -> None: ... diff --git a/stdlib/xml/etree/__init__.pyi b/stdlib/xml/etree/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/xml/etree/cElementTree.pyi b/stdlib/xml/etree/cElementTree.pyi new file mode 100644 index 000000000000..02272d803c18 --- /dev/null +++ b/stdlib/xml/etree/cElementTree.pyi @@ -0,0 +1 @@ +from xml.etree.ElementTree import * diff --git a/stdlib/xml/parsers/__init__.pyi b/stdlib/xml/parsers/__init__.pyi new file mode 100644 index 000000000000..cebdb6a30014 --- /dev/null +++ b/stdlib/xml/parsers/__init__.pyi @@ -0,0 +1 @@ +from xml.parsers import expat as expat diff --git a/stdlib/xml/parsers/expat/__init__.pyi b/stdlib/xml/parsers/expat/__init__.pyi new file mode 100644 index 000000000000..d9b7ea536999 --- /dev/null +++ b/stdlib/xml/parsers/expat/__init__.pyi @@ -0,0 +1,7 @@ +from pyexpat import * + +# This is actually implemented in the C module pyexpat, but considers itself to live here. +class ExpatError(Exception): + code: int + lineno: int + offset: int diff --git a/stdlib/xml/parsers/expat/errors.pyi b/stdlib/xml/parsers/expat/errors.pyi new file mode 100644 index 000000000000..e22d769ec340 --- /dev/null +++ b/stdlib/xml/parsers/expat/errors.pyi @@ -0,0 +1 @@ +from pyexpat.errors import * diff --git a/stdlib/xml/parsers/expat/model.pyi b/stdlib/xml/parsers/expat/model.pyi new file mode 100644 index 000000000000..d8f44b47c51b --- /dev/null +++ b/stdlib/xml/parsers/expat/model.pyi @@ -0,0 +1 @@ +from pyexpat.model import * diff --git a/stdlib/xml/sax/__init__.pyi b/stdlib/xml/sax/__init__.pyi new file mode 100644 index 000000000000..9b5c3bf4ddea --- /dev/null +++ b/stdlib/xml/sax/__init__.pyi @@ -0,0 +1,42 @@ +import sys +from _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co +from collections.abc import Iterable +from typing import Final, Protocol, TypeAlias, type_check_only +from xml.sax._exceptions import ( + SAXException as SAXException, + SAXNotRecognizedException as SAXNotRecognizedException, + SAXNotSupportedException as SAXNotSupportedException, + SAXParseException as SAXParseException, + SAXReaderNotAvailable as SAXReaderNotAvailable, +) +from xml.sax.handler import ContentHandler as ContentHandler, ErrorHandler as ErrorHandler +from xml.sax.xmlreader import InputSource as InputSource, XMLReader + +@type_check_only +class _SupportsReadClose(SupportsRead[_T_co], Protocol[_T_co]): + def close(self) -> None: ... + +_Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[str] + +default_parser_list: Final[list[str]] + +def make_parser(parser_list: Iterable[str] = ()) -> XMLReader: ... +def parse(source: _Source, handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... +def parseString(string: ReadableBuffer | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... +def _create_parser(parser_name: str) -> XMLReader: ... + +if sys.version_info >= (3, 14): + __all__ = [ + "ContentHandler", + "ErrorHandler", + "InputSource", + "SAXException", + "SAXNotRecognizedException", + "SAXNotSupportedException", + "SAXParseException", + "SAXReaderNotAvailable", + "default_parser_list", + "make_parser", + "parse", + "parseString", + ] diff --git a/stdlib/xml/sax/_exceptions.pyi b/stdlib/xml/sax/_exceptions.pyi new file mode 100644 index 000000000000..8f5e3a827185 --- /dev/null +++ b/stdlib/xml/sax/_exceptions.pyi @@ -0,0 +1,19 @@ +from typing_extensions import Never +from xml.sax.xmlreader import Locator + +class SAXException(Exception): + def __init__(self, msg: str, exception: Exception | None = None) -> None: ... + def getMessage(self) -> str: ... + def getException(self) -> Exception | None: ... + def __getitem__(self, ix: object) -> Never: ... + +class SAXParseException(SAXException): + def __init__(self, msg: str, exception: Exception | None, locator: Locator) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int | None: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + +class SAXNotRecognizedException(SAXException): ... +class SAXNotSupportedException(SAXException): ... +class SAXReaderNotAvailable(SAXNotSupportedException): ... diff --git a/stdlib/xml/sax/expatreader.pyi b/stdlib/xml/sax/expatreader.pyi new file mode 100644 index 000000000000..e29853ebc3fe --- /dev/null +++ b/stdlib/xml/sax/expatreader.pyi @@ -0,0 +1,72 @@ +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from typing import Any, Final, Literal, TypeAlias, overload +from xml.sax import _Source, xmlreader +from xml.sax.handler import LexicalHandler, _ContentHandlerProtocol + +_BoolType: TypeAlias = Literal[0, 1] | bool + +version: Final[str] +AttributesImpl = xmlreader.AttributesImpl +AttributesNSImpl = xmlreader.AttributesNSImpl + +class _ClosedParser: + ErrorColumnNumber: int + ErrorLineNumber: int + +class ExpatLocator(xmlreader.Locator): + def __init__(self, parser: ExpatParser) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + +class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): + def __init__(self, namespaceHandling: _BoolType = 0, bufsize: int = 65516) -> None: ... + def parse(self, source: xmlreader.InputSource | _Source) -> None: ... + def prepareParser(self, source: xmlreader.InputSource) -> None: ... + def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... + def getFeature(self, name: str) -> _BoolType: ... + def setFeature(self, name: str, state: _BoolType) -> None: ... + + @overload + def getProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"]) -> LexicalHandler | None: ... + @overload + def getProperty(self, name: Literal["http://www.python.org/sax/properties/interning-dict"]) -> dict[str, Any] | None: ... + @overload + def getProperty(self, name: Literal["http://xml.org/sax/properties/xml-string"]) -> bytes | None: ... + @overload + def getProperty(self, name: str) -> object: ... + + @overload + def setProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"], value: LexicalHandler) -> None: ... + @overload + def setProperty( + self, name: Literal["http://www.python.org/sax/properties/interning-dict"], value: dict[str, Any] + ) -> None: ... + @overload + def setProperty(self, name: str, value: object) -> None: ... + + def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + def start_element(self, name: str, attrs: Mapping[str, str]) -> None: ... + def end_element(self, name: str) -> None: ... + def start_element_ns(self, name: str, attrs: Mapping[str, str]) -> None: ... + def end_element_ns(self, name: str) -> None: ... + def processing_instruction(self, target: str, data: str) -> None: ... + def character_data(self, data: str) -> None: ... + def start_namespace_decl(self, prefix: str | None, uri: str) -> None: ... + def end_namespace_decl(self, prefix: str | None) -> None: ... + def start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def unparsed_entity_decl(self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str) -> None: ... + def notation_decl(self, name: str, base: str | None, sysid: str, pubid: str | None) -> None: ... + def external_entity_ref(self, context: str, base: str | None, sysid: str, pubid: str | None) -> int: ... + def skipped_entity_handler(self, name: str, is_pe: bool) -> None: ... + +def create_parser(namespaceHandling: int = 0, bufsize: int = 65516) -> ExpatParser: ... diff --git a/stdlib/xml/sax/handler.pyi b/stdlib/xml/sax/handler.pyi new file mode 100644 index 000000000000..654c98866cfb --- /dev/null +++ b/stdlib/xml/sax/handler.pyi @@ -0,0 +1,85 @@ +from typing import Final, Protocol, type_check_only +from typing_extensions import Never +from xml.sax import xmlreader + +version: Final[str] + +@type_check_only +class _ErrorHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... + +class ErrorHandler: + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... + +@type_check_only +class _ContentHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, whitespace: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... + +class ContentHandler: + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, whitespace: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... + +@type_check_only +class _DTDHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... + +class DTDHandler: + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... + +@type_check_only +class _EntityResolverProtocol(Protocol): # noqa: Y046 # Protocol is not used + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... + +class EntityResolver: + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... + +feature_namespaces: Final = "http://xml.org/sax/features/namespaces" +feature_namespace_prefixes: Final = "http://xml.org/sax/features/namespace-prefixes" +feature_string_interning: Final = "http://xml.org/sax/features/string-interning" +feature_validation: Final = "http://xml.org/sax/features/validation" +feature_external_ges: Final[str] # too long string +feature_external_pes: Final[str] # too long string +all_features: Final[list[str]] +property_lexical_handler: Final = "http://xml.org/sax/properties/lexical-handler" +property_declaration_handler: Final = "http://xml.org/sax/properties/declaration-handler" +property_dom_node: Final = "http://xml.org/sax/properties/dom-node" +property_xml_string: Final = "http://xml.org/sax/properties/xml-string" +property_encoding: Final = "http://www.python.org/sax/properties/encoding" +property_interning_dict: Final[str] # too long string +all_properties: Final[list[str]] + +class LexicalHandler: + def comment(self, content: str) -> None: ... + def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: ... + def endDTD(self) -> None: ... + def startCDATA(self) -> None: ... + def endCDATA(self) -> None: ... diff --git a/stdlib/xml/sax/saxutils.pyi b/stdlib/xml/sax/saxutils.pyi new file mode 100644 index 000000000000..0f5251def6b0 --- /dev/null +++ b/stdlib/xml/sax/saxutils.pyi @@ -0,0 +1,69 @@ +from _typeshed import SupportsWrite +from codecs import StreamReaderWriter, StreamWriter +from collections.abc import Mapping +from io import RawIOBase, TextIOBase +from typing import Literal +from typing_extensions import Never +from xml.sax import _Source, handler, xmlreader + +def escape(data: str, entities: Mapping[str, str] = {}) -> str: ... +def unescape(data: str, entities: Mapping[str, str] = {}) -> str: ... +def quoteattr(data: str, entities: Mapping[str, str] = {}) -> str: ... + +class XMLGenerator(handler.ContentHandler): + def __init__( + self, + out: TextIOBase | RawIOBase | StreamWriter | StreamReaderWriter | SupportsWrite[bytes] | None = None, + encoding: str = "iso-8859-1", + short_empty_elements: bool = False, + ) -> None: ... + def _qname(self, name: tuple[str | None, str]) -> str: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, content: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + +class XMLFilterBase(xmlreader.XMLReader): + def __init__(self, parent: xmlreader.XMLReader | None = None) -> None: ... + # ErrorHandler methods + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... + def warning(self, exception: BaseException) -> None: ... + # ContentHandler methods + def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... + def startDocument(self) -> None: ... + def endDocument(self) -> None: ... + def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ... + def endPrefixMapping(self, prefix: str | None) -> None: ... + def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ... + def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ... + def characters(self, content: str) -> None: ... + def ignorableWhitespace(self, chars: str) -> None: ... + def processingInstruction(self, target: str, data: str) -> None: ... + def skippedEntity(self, name: str) -> None: ... + # DTDHandler methods + def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ... + def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ... + # EntityResolver methods + def resolveEntity(self, publicId: str | None, systemId: str) -> str: ... + # XMLReader methods + def parse(self, source: xmlreader.InputSource | _Source) -> None: ... + def setLocale(self, locale: str) -> None: ... + def getFeature(self, name: str) -> Literal[1, 0] | bool: ... + def setFeature(self, name: str, state: Literal[1, 0] | bool) -> None: ... + def getProperty(self, name: str) -> object: ... + def setProperty(self, name: str, value: object) -> None: ... + # XMLFilter methods + def getParent(self) -> xmlreader.XMLReader | None: ... + def setParent(self, parent: xmlreader.XMLReader) -> None: ... + +def prepare_input_source(source: xmlreader.InputSource | _Source, base: str = "") -> xmlreader.InputSource: ... diff --git a/stdlib/xml/sax/xmlreader.pyi b/stdlib/xml/sax/xmlreader.pyi new file mode 100644 index 000000000000..a7ae5edc55d3 --- /dev/null +++ b/stdlib/xml/sax/xmlreader.pyi @@ -0,0 +1,94 @@ +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from typing import Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self +from xml.sax import _Source, _SupportsReadClose +from xml.sax.handler import _ContentHandlerProtocol, _DTDHandlerProtocol, _EntityResolverProtocol, _ErrorHandlerProtocol + +class XMLReader: + def parse(self, source: InputSource | _Source) -> None: ... + def getContentHandler(self) -> _ContentHandlerProtocol: ... + def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... + def getDTDHandler(self) -> _DTDHandlerProtocol: ... + def setDTDHandler(self, handler: _DTDHandlerProtocol) -> None: ... + def getEntityResolver(self) -> _EntityResolverProtocol: ... + def setEntityResolver(self, resolver: _EntityResolverProtocol) -> None: ... + def getErrorHandler(self) -> _ErrorHandlerProtocol: ... + def setErrorHandler(self, handler: _ErrorHandlerProtocol) -> None: ... + def setLocale(self, locale: str) -> None: ... + def getFeature(self, name: str) -> Literal[0, 1] | bool: ... + def setFeature(self, name: str, state: Literal[0, 1] | bool) -> None: ... + def getProperty(self, name: str) -> object: ... + def setProperty(self, name: str, value: object) -> None: ... + +class IncrementalParser(XMLReader): + def __init__(self, bufsize: int = 65536) -> None: ... + def parse(self, source: InputSource | _Source) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... + def prepareParser(self, source: InputSource) -> None: ... + def close(self) -> None: ... + def reset(self) -> None: ... + +class Locator: + def getColumnNumber(self) -> int | None: ... + def getLineNumber(self) -> int | None: ... + def getPublicId(self) -> str | None: ... + def getSystemId(self) -> str | None: ... + +class InputSource: + def __init__(self, system_id: str | None = None) -> None: ... + def setPublicId(self, public_id: str | None) -> None: ... + def getPublicId(self) -> str | None: ... + def setSystemId(self, system_id: str | None) -> None: ... + def getSystemId(self) -> str | None: ... + def setEncoding(self, encoding: str | None) -> None: ... + def getEncoding(self) -> str | None: ... + def setByteStream(self, bytefile: _SupportsReadClose[bytes] | None) -> None: ... + def getByteStream(self) -> _SupportsReadClose[bytes] | None: ... + def setCharacterStream(self, charfile: _SupportsReadClose[str] | None) -> None: ... + def getCharacterStream(self) -> _SupportsReadClose[str] | None: ... + +_AttrKey = TypeVar("_AttrKey", default=str) + +class AttributesImpl(Generic[_AttrKey]): + def __init__(self, attrs: Mapping[_AttrKey, str]) -> None: ... + def getLength(self) -> int: ... + def getType(self, name: str) -> str: ... + def getValue(self, name: _AttrKey) -> str: ... + def getValueByQName(self, name: str) -> str: ... + def getNameByQName(self, name: str) -> _AttrKey: ... + def getQNameByName(self, name: _AttrKey) -> str: ... + def getNames(self) -> list[_AttrKey]: ... + def getQNames(self) -> list[str]: ... + def __len__(self) -> int: ... + def __getitem__(self, name: _AttrKey) -> str: ... + def keys(self) -> list[_AttrKey]: ... + def __contains__(self, name: _AttrKey) -> bool: ... + + @overload + def get(self, name: _AttrKey, alternative: None = None) -> str | None: ... + @overload + def get(self, name: _AttrKey, alternative: str) -> str: ... + + def copy(self) -> Self: ... + def items(self) -> list[tuple[_AttrKey, str]]: ... + def values(self) -> list[str]: ... + +_NSName: TypeAlias = tuple[str | None, str] + +class AttributesNSImpl(AttributesImpl[_NSName]): + def __init__(self, attrs: Mapping[_NSName, str], qnames: Mapping[_NSName, str]) -> None: ... + def getValue(self, name: _NSName) -> str: ... + def getNameByQName(self, name: str) -> _NSName: ... + def getQNameByName(self, name: _NSName) -> str: ... + def getNames(self) -> list[_NSName]: ... + def __getitem__(self, name: _NSName) -> str: ... + def keys(self) -> list[_NSName]: ... + def __contains__(self, name: _NSName) -> bool: ... + + @overload + def get(self, name: _NSName, alternative: None = None) -> str | None: ... + @overload + def get(self, name: _NSName, alternative: str) -> str: ... + + def items(self) -> list[tuple[_NSName, str]]: ... diff --git a/stdlib/xml/utils.pyi b/stdlib/xml/utils.pyi new file mode 100644 index 000000000000..1c3bb877a7cc --- /dev/null +++ b/stdlib/xml/utils.pyi @@ -0,0 +1,2 @@ +def is_valid_name(name: str) -> bool: ... +def is_valid_text(data: str) -> bool: ... diff --git a/stdlib/xmlrpc/__init__.pyi b/stdlib/xmlrpc/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stdlib/xmlrpc/client.pyi b/stdlib/xmlrpc/client.pyi new file mode 100644 index 000000000000..573401f18d08 --- /dev/null +++ b/stdlib/xmlrpc/client.pyi @@ -0,0 +1,300 @@ +import gzip +import http.client +import time +from _typeshed import ReadableBuffer, SizedBuffer, SupportsRead, SupportsWrite +from collections.abc import Callable, Iterable, Mapping +from datetime import datetime +from io import BytesIO +from types import TracebackType +from typing import Any, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self + +@type_check_only +class _SupportsTimeTuple(Protocol): + def timetuple(self) -> time.struct_time: ... + +_DateTimeComparable: TypeAlias = DateTime | datetime | str | _SupportsTimeTuple +_Marshallable: TypeAlias = ( + bool + | int + | float + | str + | bytes + | bytearray + | None + | tuple[_Marshallable, ...] + # Ideally we'd use _Marshallable for list and dict, but invariance makes that impractical + | list[Any] + | dict[str, Any] + | datetime + | DateTime + | Binary +) +_XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time +_HostType: TypeAlias = tuple[str, dict[str, str]] | str + +def escape(s: str) -> str: ... # undocumented + +MAXINT: Final[int] # undocumented +MININT: Final[int] # undocumented + +PARSE_ERROR: Final[int] # undocumented +SERVER_ERROR: Final[int] # undocumented +APPLICATION_ERROR: Final[int] # undocumented +SYSTEM_ERROR: Final[int] # undocumented +TRANSPORT_ERROR: Final[int] # undocumented + +NOT_WELLFORMED_ERROR: Final[int] # undocumented +UNSUPPORTED_ENCODING: Final[int] # undocumented +INVALID_ENCODING_CHAR: Final[int] # undocumented +INVALID_XMLRPC: Final[int] # undocumented +METHOD_NOT_FOUND: Final[int] # undocumented +INVALID_METHOD_PARAMS: Final[int] # undocumented +INTERNAL_ERROR: Final[int] # undocumented + +class Error(Exception): ... + +class ProtocolError(Error): + url: str + errcode: int + errmsg: str + headers: dict[str, str] + def __init__(self, url: str, errcode: int, errmsg: str, headers: dict[str, str]) -> None: ... + +class ResponseError(Error): ... + +class Fault(Error): + faultCode: int + faultString: str + def __init__(self, faultCode: int, faultString: str, **extra: Any) -> None: ... + +boolean = bool +Boolean = bool + +def _iso8601_format(value: datetime) -> str: ... # undocumented +def _strftime(value: _XMLDate) -> str: ... # undocumented + +class DateTime: + value: str # undocumented + def __init__(self, value: int | str | datetime | time.struct_time | tuple[int, ...] = 0) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __lt__(self, other: _DateTimeComparable) -> bool: ... + def __le__(self, other: _DateTimeComparable) -> bool: ... + def __gt__(self, other: _DateTimeComparable) -> bool: ... + def __ge__(self, other: _DateTimeComparable) -> bool: ... + def __eq__(self, other: _DateTimeComparable) -> bool: ... # type: ignore[override] + def make_comparable(self, other: _DateTimeComparable) -> tuple[str, str]: ... # undocumented + def timetuple(self) -> time.struct_time: ... # undocumented + def decode(self, data: Any) -> None: ... + def encode(self, out: SupportsWrite[str]) -> None: ... + +def _datetime(data: Any) -> DateTime: ... # undocumented +def _datetime_type(data: str) -> datetime: ... # undocumented + +class Binary: + data: bytes + def __init__(self, data: bytes | bytearray | None = None) -> None: ... + def decode(self, data: ReadableBuffer) -> None: ... + def encode(self, out: SupportsWrite[str]) -> None: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + +def _binary(data: ReadableBuffer) -> Binary: ... # undocumented + +WRAPPERS: Final[tuple[type[DateTime], type[Binary]]] # undocumented + +class ExpatParser: # undocumented + def __init__(self, target: Unmarshaller) -> None: ... + def feed(self, data: str | ReadableBuffer) -> None: ... + def close(self) -> None: ... + +_WriteCallback: TypeAlias = Callable[[str], object] + +class Marshaller: + dispatch: dict[type[_Marshallable] | Literal["_arbitrary_instance"], Callable[[Marshaller, Any, _WriteCallback], None]] + memo: dict[Any, None] + data: None + encoding: str | None + allow_none: bool + def __init__(self, encoding: str | None = None, allow_none: bool = False) -> None: ... + def dumps(self, values: Fault | Iterable[_Marshallable]) -> str: ... + def __dump(self, value: _Marshallable, write: _WriteCallback) -> None: ... # undocumented + def dump_nil(self, value: None, write: _WriteCallback) -> None: ... + def dump_bool(self, value: bool, write: _WriteCallback) -> None: ... + def dump_long(self, value: int, write: _WriteCallback) -> None: ... + def dump_int(self, value: int, write: _WriteCallback) -> None: ... + def dump_double(self, value: float, write: _WriteCallback) -> None: ... + def dump_unicode(self, value: str, write: _WriteCallback, escape: Callable[[str], str] = ...) -> None: ... + def dump_bytes(self, value: ReadableBuffer, write: _WriteCallback) -> None: ... + def dump_array(self, value: Iterable[_Marshallable], write: _WriteCallback) -> None: ... + def dump_struct( + self, value: Mapping[str, _Marshallable], write: _WriteCallback, escape: Callable[[str], str] = ... + ) -> None: ... + def dump_datetime(self, value: _XMLDate, write: _WriteCallback) -> None: ... + def dump_instance(self, value: object, write: _WriteCallback) -> None: ... + +class Unmarshaller: + dispatch: dict[str, Callable[[Unmarshaller, str], None]] + + _type: str | None + _stack: list[_Marshallable] + _marks: list[int] + _data: list[str] + _value: bool + _methodname: str | None + _encoding: str + append: Callable[[Any], None] + _use_datetime: bool + _use_builtin_types: bool + def __init__(self, use_datetime: bool = False, use_builtin_types: bool = False) -> None: ... + def close(self) -> tuple[_Marshallable, ...]: ... + def getmethodname(self) -> str | None: ... + def xml(self, encoding: str, standalone: Any) -> None: ... # Standalone is ignored + def start(self, tag: str, attrs: dict[str, str]) -> None: ... + def data(self, text: str) -> None: ... + def end(self, tag: str) -> None: ... + def end_dispatch(self, tag: str, data: str) -> None: ... + def end_nil(self, data: str) -> None: ... + def end_boolean(self, data: str) -> None: ... + def end_int(self, data: str) -> None: ... + def end_double(self, data: str) -> None: ... + def end_bigdecimal(self, data: str) -> None: ... + def end_string(self, data: str) -> None: ... + def end_array(self, data: str) -> None: ... + def end_struct(self, data: str) -> None: ... + def end_base64(self, data: str) -> None: ... + def end_dateTime(self, data: str) -> None: ... + def end_value(self, data: str) -> None: ... + def end_params(self, data: str) -> None: ... + def end_fault(self, data: str) -> None: ... + def end_methodName(self, data: str) -> None: ... + +class _MultiCallMethod: # undocumented + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] + __name: str + def __init__(self, call_list: list[tuple[str, _Marshallable]], name: str) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self, *args: _Marshallable) -> None: ... + +class MultiCallIterator: # undocumented + results: list[list[_Marshallable]] + def __init__(self, results: list[list[_Marshallable]]) -> None: ... + def __getitem__(self, i: int) -> _Marshallable: ... + +class MultiCall: + __server: ServerProxy + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] + def __init__(self, server: ServerProxy) -> None: ... + def __getattr__(self, name: str) -> _MultiCallMethod: ... + def __call__(self) -> MultiCallIterator: ... + +# A little white lie +FastMarshaller: Marshaller | None +FastParser: ExpatParser | None +FastUnmarshaller: Unmarshaller | None + +def getparser(use_datetime: bool = False, use_builtin_types: bool = False) -> tuple[ExpatParser, Unmarshaller]: ... +def dumps( + params: Fault | tuple[_Marshallable, ...], + methodname: str | None = None, + methodresponse: bool | None = None, + encoding: str | None = None, + allow_none: bool = False, +) -> str: ... +def loads( + data: str | ReadableBuffer, use_datetime: bool = False, use_builtin_types: bool = False +) -> tuple[tuple[_Marshallable, ...], str | None]: ... +def gzip_encode(data: ReadableBuffer) -> bytes: ... # undocumented +def gzip_decode(data: ReadableBuffer, max_decode: int = 20971520) -> bytes: ... # undocumented + +class GzipDecodedResponse(gzip.GzipFile): # undocumented + io: BytesIO + def __init__(self, response: SupportsRead[ReadableBuffer]) -> None: ... + +class _Method: # undocumented + __send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable] + __name: str + def __init__(self, send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + def __call__(self, *args: _Marshallable) -> _Marshallable: ... + +class Transport: + user_agent: str + accept_gzip_encoding: bool + encode_threshold: int | None + + _use_datetime: bool + _use_builtin_types: bool + _connection: tuple[_HostType | None, http.client.HTTPConnection | None] + _headers: list[tuple[str, str]] + _extra_headers: list[tuple[str, str]] + + def __init__( + self, use_datetime: bool = False, use_builtin_types: bool = False, *, headers: Iterable[tuple[str, str]] = () + ) -> None: ... + def request( + self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False + ) -> tuple[_Marshallable, ...]: ... + def single_request( + self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False + ) -> tuple[_Marshallable, ...]: ... + def getparser(self) -> tuple[ExpatParser, Unmarshaller]: ... + def get_host_info(self, host: _HostType) -> tuple[str, list[tuple[str, str]], dict[str, str]]: ... + def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ... + def close(self) -> None: ... + def send_request( + self, host: _HostType, handler: str, request_body: SizedBuffer, debug: bool + ) -> http.client.HTTPConnection: ... + def send_headers(self, connection: http.client.HTTPConnection, headers: list[tuple[str, str]]) -> None: ... + def send_content(self, connection: http.client.HTTPConnection, request_body: SizedBuffer) -> None: ... + def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ... + +class SafeTransport(Transport): + def __init__( + self, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... + def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ... + +class ServerProxy: + __host: str + __handler: str + __transport: Transport + __encoding: str + __verbose: bool + __allow_none: bool + + def __init__( + self, + uri: str, + transport: Transport | None = None, + encoding: str | None = None, + verbose: bool = False, + allow_none: bool = False, + use_datetime: bool = False, + use_builtin_types: bool = False, + *, + headers: Iterable[tuple[str, str]] = (), + context: Any | None = None, + ) -> None: ... + def __getattr__(self, name: str) -> _Method: ... + + @overload + def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... + @overload + def __call__(self, attr: Literal["transport"]) -> Transport: ... + @overload + def __call__(self, attr: str) -> Callable[[], None] | Transport: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __close(self) -> None: ... # undocumented + def __request(self, methodname: str, params: tuple[_Marshallable, ...]) -> tuple[_Marshallable, ...]: ... # undocumented + +Server = ServerProxy diff --git a/stdlib/xmlrpc/server.pyi b/stdlib/xmlrpc/server.pyi new file mode 100644 index 000000000000..7bf397d2b1a4 --- /dev/null +++ b/stdlib/xmlrpc/server.pyi @@ -0,0 +1,149 @@ +import http.server +import pydoc +import socketserver +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable, Mapping +from re import Pattern +from typing import Any, ClassVar, Protocol, TypeAlias, type_check_only +from xmlrpc.client import Fault, _Marshallable + +# The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy +@type_check_only +class _DispatchArity0(Protocol): + def __call__(self) -> _Marshallable: ... + +@type_check_only +class _DispatchArity1(Protocol): + def __call__(self, arg1: _Marshallable, /) -> _Marshallable: ... + +@type_check_only +class _DispatchArity2(Protocol): + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, /) -> _Marshallable: ... + +@type_check_only +class _DispatchArity3(Protocol): + def __call__(self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, /) -> _Marshallable: ... + +@type_check_only +class _DispatchArity4(Protocol): + def __call__( + self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, arg4: _Marshallable, / + ) -> _Marshallable: ... + +@type_check_only +class _DispatchArityN(Protocol): + def __call__(self, *args: _Marshallable) -> _Marshallable: ... + +_DispatchProtocol: TypeAlias = ( + _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN +) + +def resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = True) -> Any: ... # undocumented +def list_public_methods(obj: Any) -> list[str]: ... # undocumented + +class SimpleXMLRPCDispatcher: # undocumented + funcs: dict[str, _DispatchProtocol] + instance: Any | None + allow_none: bool + encoding: str + use_builtin_types: bool + def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... + def register_instance(self, instance: Any, allow_dotted_names: bool = False) -> None: ... + def register_function(self, function: _DispatchProtocol | None = None, name: str | None = None) -> Callable[..., Any]: ... + def register_introspection_functions(self) -> None: ... + def register_multicall_functions(self) -> None: ... + def _marshaled_dispatch( + self, + data: str | ReadableBuffer, + dispatch_method: Callable[[str, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = None, + path: Any | None = None, + ) -> str: ... # undocumented + def system_listMethods(self) -> list[str]: ... # undocumented + def system_methodSignature(self, method_name: str) -> str: ... # undocumented + def system_methodHelp(self, method_name: str) -> str: ... # undocumented + def system_multicall(self, call_list: list[dict[str, _Marshallable]]) -> list[_Marshallable]: ... # undocumented + def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ... # undocumented + +class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): + rpc_paths: ClassVar[tuple[str, ...]] + encode_threshold: int # undocumented + aepattern: Pattern[str] # undocumented + def accept_encodings(self) -> dict[str, float]: ... + def is_rpc_path_valid(self) -> bool: ... + def do_POST(self) -> None: ... + def decode_request_content(self, data: bytes) -> bytes | None: ... + def report_404(self) -> None: ... + +class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): + _send_traceback_handler: bool + def __init__( + self, + addr: tuple[str, int], + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, + ) -> None: ... + +class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented + dispatchers: dict[str, SimpleXMLRPCDispatcher] + def __init__( + self, + addr: tuple[str, int], + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, + ) -> None: ... + def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ... + def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ... + +class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): + def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ... + def handle_xmlrpc(self, request_text: str) -> None: ... + def handle_get(self) -> None: ... + def handle_request(self, request_text: str | None = None) -> None: ... + +class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented + def docroutine( # type: ignore[override] + self, + object: object, + name: str, + mod: str | None = None, + funcs: Mapping[str, str] = {}, + classes: Mapping[str, str] = {}, + methods: Mapping[str, str] = {}, + cl: type | None = None, + ) -> str: ... + def docserver(self, server_name: str, package_documentation: str, methods: dict[str, str]) -> str: ... + +class XMLRPCDocGenerator: # undocumented + server_name: str + server_documentation: str + server_title: str + def set_server_title(self, server_title: str) -> None: ... + def set_server_name(self, server_name: str) -> None: ... + def set_server_documentation(self, server_documentation: str) -> None: ... + def generate_html_documentation(self) -> str: ... + +class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): + def do_GET(self) -> None: ... + +class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): + def __init__( + self, + addr: tuple[str, int], + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., + logRequests: bool = True, + allow_none: bool = False, + encoding: str | None = None, + bind_and_activate: bool = True, + use_builtin_types: bool = False, + ) -> None: ... + +class DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator): + def __init__(self) -> None: ... diff --git a/stdlib/xxlimited.pyi b/stdlib/xxlimited.pyi new file mode 100644 index 000000000000..503caf0183f3 --- /dev/null +++ b/stdlib/xxlimited.pyi @@ -0,0 +1,15 @@ +import sys +from typing import Any, final + +class Str(str): ... + +@final +class Xxo: + def demo(self) -> None: ... + if sys.version_info >= (3, 11) and sys.platform != "win32": + x_exports: int + +def foo(i: int, j: int, /) -> Any: ... +def new() -> Xxo: ... + +class Error(Exception): ... diff --git a/stdlib/zipapp.pyi b/stdlib/zipapp.pyi new file mode 100644 index 000000000000..48713bced892 --- /dev/null +++ b/stdlib/zipapp.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable +from pathlib import Path +from typing import BinaryIO, TypeAlias + +__all__ = ["ZipAppError", "create_archive", "get_interpreter"] + +_Path: TypeAlias = str | Path | BinaryIO + +class ZipAppError(ValueError): ... + +def create_archive( + source: _Path, + target: _Path | None = None, + interpreter: str | None = None, + main: str | None = None, + filter: Callable[[Path], bool] | None = None, + compressed: bool = False, +) -> None: ... +def get_interpreter(archive: _Path) -> str: ... diff --git a/stdlib/zipfile/__init__.pyi b/stdlib/zipfile/__init__.pyi new file mode 100644 index 000000000000..0039a05b5d6f --- /dev/null +++ b/stdlib/zipfile/__init__.pyi @@ -0,0 +1,411 @@ +import io +import sys +from _typeshed import SizedBuffer, StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable, Iterator +from io import TextIOWrapper +from os import PathLike +from types import TracebackType +from typing import IO, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self + +__all__ = [ + "BadZipFile", + "BadZipfile", + "Path", + "error", + "ZIP_STORED", + "ZIP_DEFLATED", + "ZIP_BZIP2", + "ZIP_LZMA", + "is_zipfile", + "ZipInfo", + "ZipFile", + "PyZipFile", + "LargeZipFile", +] + +if sys.version_info >= (3, 14): + __all__ += ["ZIP_ZSTANDARD"] + +# TODO: use TypeAlias for these two when mypy bugs are fixed +# https://github.com/python/mypy/issues/16581 +_DateTuple = tuple[int, int, int, int, int, int] # noqa: Y026 +_ZipFileMode = Literal["r", "w", "x", "a"] # noqa: Y026 + +_ReadWriteMode: TypeAlias = Literal["r", "w"] + +class BadZipFile(Exception): ... + +BadZipfile = BadZipFile +error = BadZipfile + +class LargeZipFile(Exception): ... + +@type_check_only +class _ZipStream(Protocol): + def read(self, n: int, /) -> bytes: ... + # The following methods are optional: + # def seekable(self) -> bool: ... + # def tell(self) -> int: ... + # def seek(self, n: int, /) -> object: ... + +# Stream shape as required by _EndRecData() and _EndRecData64(). +@type_check_only +class _SupportsReadSeekTell(Protocol): + def read(self, n: int = ..., /) -> bytes: ... + def seek(self, cookie: int, whence: int, /) -> object: ... + def tell(self) -> int: ... + +@type_check_only +class _ClosableZipStream(_ZipStream, Protocol): + def close(self) -> object: ... + +class ZipExtFile(io.BufferedIOBase): + MAX_N: int + MIN_READ_SIZE: int + MAX_SEEK_READ: int + newlines: list[bytes] | None + mode: _ReadWriteMode + name: str + + @overload + def __init__( + self, fileobj: _ClosableZipStream, mode: _ReadWriteMode, zipinfo: ZipInfo, pwd: bytes | None, close_fileobj: Literal[True] + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ClosableZipStream, + mode: _ReadWriteMode, + zipinfo: ZipInfo, + pwd: bytes | None = None, + *, + close_fileobj: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + fileobj: _ZipStream, + mode: _ReadWriteMode, + zipinfo: ZipInfo, + pwd: bytes | None = None, + close_fileobj: Literal[False] = False, + ) -> None: ... + + def read(self, n: int | None = -1) -> bytes: ... + def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] + def peek(self, n: int = 1) -> bytes: ... + def read1(self, n: int | None) -> bytes: ... # type: ignore[override] + def seek(self, offset: int, whence: int = 0) -> int: ... + +@type_check_only +class _Writer(Protocol): + def write(self, s: str, /) -> object: ... + +@type_check_only +class _ZipReadable(Protocol): + def seek(self, offset: int, whence: int = 0, /) -> int: ... + def read(self, n: int = -1, /) -> bytes: ... + +@type_check_only +class _ZipTellable(Protocol): + def tell(self) -> int: ... + +@type_check_only +class _ZipReadableTellable(_ZipReadable, _ZipTellable, Protocol): ... + +@type_check_only +class _ZipWritable(Protocol): + def flush(self) -> None: ... + def close(self) -> None: ... + def write(self, b: bytes, /) -> int: ... + +class ZipFile: + filename: str | None + debug: int + comment: bytes + filelist: list[ZipInfo] + fp: IO[bytes] | None + NameToInfo: dict[str, ZipInfo] + start_dir: int # undocumented + compression: int # undocumented + compresslevel: int | None # undocumented + mode: _ZipFileMode # undocumented + pwd: bytes | None # undocumented + # metadata_encoding is new in 3.11 + if sys.version_info >= (3, 11): + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: _ZipFileMode = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: str | None = None, + ) -> None: ... + # metadata_encoding is only allowed for read mode + @overload + def __init__( + self, + file: StrPath | _ZipReadable, + mode: Literal["r"] = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipWritable, + mode: Literal["w", "x"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: None = None, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadableTellable, + mode: Literal["a"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + metadata_encoding: None = None, + ) -> None: ... + else: + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: _ZipFileMode = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadable, + mode: Literal["r"] = "r", + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipWritable, + mode: Literal["w", "x"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | _ZipReadableTellable, + mode: Literal["a"], + compression: int = 0, + allowZip64: bool = True, + compresslevel: int | None = None, + *, + strict_timestamps: bool = True, + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def close(self) -> None: ... + def getinfo(self, name: str) -> ZipInfo: ... + def infolist(self) -> list[ZipInfo]: ... + def namelist(self) -> list[str]: ... + def open( + self, name: str | ZipInfo, mode: _ReadWriteMode = "r", pwd: bytes | None = None, *, force_zip64: bool = False + ) -> IO[bytes]: ... + def extract(self, member: str | ZipInfo, path: StrPath | None = None, pwd: bytes | None = None) -> str: ... + def extractall( + self, path: StrPath | None = None, members: Iterable[str | ZipInfo] | None = None, pwd: bytes | None = None + ) -> None: ... + def printdir(self, file: _Writer | None = None) -> None: ... + def setpassword(self, pwd: bytes) -> None: ... + def read(self, name: str | ZipInfo, pwd: bytes | None = None) -> bytes: ... + def testzip(self) -> str | None: ... + def write( + self, + filename: StrPath, + arcname: StrPath | None = None, + compress_type: int | None = None, + compresslevel: int | None = None, + ) -> None: ... + def writestr( + self, + zinfo_or_arcname: str | ZipInfo, + data: SizedBuffer | str, + compress_type: int | None = None, + compresslevel: int | None = None, + ) -> None: ... + if sys.version_info >= (3, 11): + def mkdir(self, zinfo_or_directory_name: str | ZipInfo, mode: int = 0o777) -> None: ... + + def __del__(self) -> None: ... + +class PyZipFile(ZipFile): + def __init__( + self, file: str | IO[bytes], mode: _ZipFileMode = "r", compression: int = 0, allowZip64: bool = True, optimize: int = -1 + ) -> None: ... + def writepy(self, pathname: str, basename: str = "", filterfunc: Callable[[str], bool] | None = None) -> None: ... + +class ZipInfo: + __slots__ = ( + "orig_filename", + "filename", + "date_time", + "compress_type", + "compress_level", + "comment", + "extra", + "create_system", + "create_version", + "extract_version", + "reserved", + "flag_bits", + "volume", + "internal_attr", + "external_attr", + "header_offset", + "CRC", + "compress_size", + "file_size", + "_raw_time", + "_end_offset", + ) + filename: str + date_time: _DateTuple + compress_type: int + comment: bytes + extra: bytes + create_system: int + create_version: int + extract_version: int + reserved: int + flag_bits: int + volume: int + internal_attr: int + external_attr: int + header_offset: int + CRC: int + compress_size: int + file_size: int + orig_filename: str # undocumented + if sys.version_info >= (3, 13): + compress_level: int | None + + def __init__(self, filename: str = "NoName", date_time: _DateTuple = (1980, 1, 1, 0, 0, 0)) -> None: ... + @classmethod + def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: ... + def is_dir(self) -> bool: ... + def FileHeader(self, zip64: bool | None = None) -> bytes: ... + if sys.version_info >= (3, 14): + def _for_archive(self, archive: ZipFile) -> Self: ... + +if sys.version_info >= (3, 12): + from zipfile._path import CompleteDirs as CompleteDirs, Path as Path + +else: + class CompleteDirs(ZipFile): + def resolve_dir(self, name: str) -> str: ... + + @overload + @classmethod + def make(cls, source: ZipFile) -> CompleteDirs: ... + @overload + @classmethod + def make(cls, source: StrPath | IO[bytes]) -> Self: ... + + class Path: + root: CompleteDirs + at: str + def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: ... + @property + def name(self) -> str: ... + @property + def parent(self) -> PathLike[str]: ... # undocumented + @property + def filename(self) -> PathLike[str]: ... # undocumented + if sys.version_info >= (3, 11): + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + + @overload + def open( + self, + mode: Literal["r", "w"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + *, + pwd: bytes | None = None, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... + + def iterdir(self) -> Iterator[Self]: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def exists(self) -> bool: ... + def read_text( + self, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> Path: ... + def __truediv__(self, add: StrPath) -> Path: ... + +def is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: ... + +ZIP64_LIMIT: Final[int] +ZIP_FILECOUNT_LIMIT: Final[int] +ZIP_MAX_COMMENT: Final[int] + +ZIP_STORED: Final = 0 +ZIP_DEFLATED: Final = 8 +ZIP_BZIP2: Final = 12 +ZIP_LZMA: Final = 14 +if sys.version_info >= (3, 14): + ZIP_ZSTANDARD: Final = 93 + +DEFAULT_VERSION: Final[int] +ZIP64_VERSION: Final[int] +BZIP2_VERSION: Final[int] +LZMA_VERSION: Final[int] +if sys.version_info >= (3, 14): + ZSTANDARD_VERSION: Final[int] +MAX_EXTRACT_VERSION: Final[int] diff --git a/stdlib/zipfile/_path/__init__.pyi b/stdlib/zipfile/_path/__init__.pyi new file mode 100644 index 000000000000..e1449dc681ad --- /dev/null +++ b/stdlib/zipfile/_path/__init__.pyi @@ -0,0 +1,87 @@ +import sys +from _typeshed import StrPath +from collections.abc import Iterator, Sequence +from io import TextIOWrapper +from os import PathLike +from typing import IO, Literal, TypeVar, overload +from typing_extensions import Self +from zipfile import ZipFile + +_ZF = TypeVar("_ZF", bound=ZipFile) + +if sys.version_info >= (3, 12): + __all__ = ["Path"] + + class InitializedState: + def __init__(self, *args: object, **kwargs: object) -> None: ... + def __getstate__(self) -> tuple[list[object], dict[object, object]]: ... + def __setstate__(self, state: Sequence[tuple[list[object], dict[object, object]]]) -> None: ... + + class CompleteDirs(InitializedState, ZipFile): + def resolve_dir(self, name: str) -> str: ... + + @overload + @classmethod + def make(cls, source: ZipFile) -> CompleteDirs: ... + @overload + @classmethod + def make(cls, source: StrPath | IO[bytes]) -> Self: ... + + if sys.version_info >= (3, 13): + @classmethod + def inject(cls, zf: _ZF) -> _ZF: ... + + class Path: + root: CompleteDirs + at: str + def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = "") -> None: ... + @property + def name(self) -> str: ... + @property + def parent(self) -> PathLike[str]: ... # undocumented + @property + def filename(self) -> PathLike[str]: ... # undocumented + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... + + @overload + def open( + self, + mode: Literal["r", "w"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + *, + pwd: bytes | None = None, + ) -> TextIOWrapper: ... + @overload + def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... + + def iterdir(self) -> Iterator[Self]: ... + def is_dir(self) -> bool: ... + def is_file(self) -> bool: ... + def exists(self) -> bool: ... + def read_text( + self, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = False, + write_through: bool = False, + ) -> str: ... + def read_bytes(self) -> bytes: ... + def joinpath(self, *other: StrPath) -> Path: ... + def glob(self, pattern: str) -> Iterator[Self]: ... + def rglob(self, pattern: str) -> Iterator[Self]: ... + def is_symlink(self) -> Literal[False]: ... + def relative_to(self, other: Path, *extra: StrPath) -> str: ... + def match(self, path_pattern: str) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __truediv__(self, add: StrPath) -> Path: ... diff --git a/stdlib/zipfile/_path/glob.pyi b/stdlib/zipfile/_path/glob.pyi new file mode 100644 index 000000000000..f6a661be8cdf --- /dev/null +++ b/stdlib/zipfile/_path/glob.pyi @@ -0,0 +1,26 @@ +import sys +from collections.abc import Iterator +from re import Match + +if sys.version_info >= (3, 13): + class Translator: + if sys.platform == "win32": + def __init__(self, seps: str = "\\/") -> None: ... + else: + def __init__(self, seps: str = "/") -> None: ... + + def translate(self, pattern: str) -> str: ... + def extend(self, pattern: str) -> str: ... + def match_dirs(self, pattern: str) -> str: ... + def translate_core(self, pattern: str) -> str: ... + def replace(self, match: Match[str]) -> str: ... + def restrict_rglob(self, pattern: str) -> None: ... + def star_not_empty(self, pattern: str) -> str: ... + +else: + def translate(pattern: str) -> str: ... + def match_dirs(pattern: str) -> str: ... + def translate_core(pattern: str) -> str: ... + def replace(match: Match[str]) -> str: ... + +def separate(pattern: str) -> Iterator[Match[str]]: ... diff --git a/stdlib/zipimport.pyi b/stdlib/zipimport.pyi new file mode 100644 index 000000000000..4b34f1f2ad3e --- /dev/null +++ b/stdlib/zipimport.pyi @@ -0,0 +1,44 @@ +import sys +from _frozen_importlib_external import _LoaderBasics +from _typeshed import StrOrBytesPath +from importlib.machinery import ModuleSpec +from importlib.readers import ZipReader +from types import CodeType, ModuleType +from typing_extensions import deprecated + +__all__ = ["ZipImportError", "zipimporter"] + +class ZipImportError(ImportError): ... + +class zipimporter(_LoaderBasics): + archive: str + prefix: str + if sys.version_info >= (3, 11): + def __init__(self, path: str) -> None: ... + else: + def __init__(self, path: StrOrBytesPath) -> None: ... + + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... + + def get_code(self, fullname: str) -> CodeType: ... + def get_data(self, pathname: str) -> bytes: ... + def get_filename(self, fullname: str) -> str: ... + if sys.version_info >= (3, 14): + def get_resource_reader(self, fullname: str) -> ZipReader: ... # undocumented + else: + def get_resource_reader(self, fullname: str) -> ZipReader | None: ... # undocumented + + def get_source(self, fullname: str) -> str | None: ... + def is_package(self, fullname: str) -> bool: ... + if sys.version_info < (3, 15): + @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> ModuleType: ... + + def exec_module(self, module: ModuleType) -> None: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... diff --git a/stdlib/zlib.pyi b/stdlib/zlib.pyi new file mode 100644 index 000000000000..557fa761feeb --- /dev/null +++ b/stdlib/zlib.pyi @@ -0,0 +1,81 @@ +import sys +from _typeshed import ReadableBuffer +from typing import Any, Final, final, type_check_only +from typing_extensions import Self + +DEFLATED: Final = 8 +DEF_MEM_LEVEL: Final[int] +DEF_BUF_SIZE: Final = 16384 +MAX_WBITS: Final[int] +ZLIB_VERSION: Final[str] +ZLIB_RUNTIME_VERSION: Final[str] +Z_NO_COMPRESSION: Final = 0 +Z_PARTIAL_FLUSH: Final = 1 +Z_BEST_COMPRESSION: Final = 9 +Z_BEST_SPEED: Final = 1 +Z_BLOCK: Final = 5 +Z_DEFAULT_COMPRESSION: Final = -1 +Z_DEFAULT_STRATEGY: Final = 0 +Z_FILTERED: Final = 1 +Z_FINISH: Final = 4 +Z_FIXED: Final = 4 +Z_FULL_FLUSH: Final = 3 +Z_HUFFMAN_ONLY: Final = 2 +Z_NO_FLUSH: Final = 0 +Z_RLE: Final = 3 +Z_SYNC_FLUSH: Final = 2 +Z_TREES: Final = 6 + +if sys.version_info >= (3, 14): + # Available when zlib was built with zlib-ng + ZLIBNG_VERSION: Final[str] + +class error(Exception): ... + +# This class is not exposed at runtime. It calls itself zlib.Compress. +@final +@type_check_only +class _Compress: + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def compress(self, data: ReadableBuffer, /) -> bytes: ... + def flush(self, mode: int = 4, /) -> bytes: ... + def copy(self) -> _Compress: ... + +# This class is not exposed at runtime. It calls itself zlib.Decompress. +@final +@type_check_only +class _Decompress: + @property + def unused_data(self) -> bytes: ... + @property + def unconsumed_tail(self) -> bytes: ... + @property + def eof(self) -> bool: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def decompress(self, data: ReadableBuffer, /, max_length: int = 0) -> bytes: ... + def flush(self, length: int = 16384, /) -> bytes: ... + def copy(self) -> _Decompress: ... + +def adler32(data: ReadableBuffer, value: int = 1, /) -> int: ... + +if sys.version_info >= (3, 15): + def adler32_combine(adler1: int, adler2: int, len2: int, /) -> int: ... + +if sys.version_info >= (3, 11): + def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: ... + +else: + def compress(data: ReadableBuffer, /, level: int = -1) -> bytes: ... + +def compressobj( + level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None +) -> _Compress: ... +def crc32(data: ReadableBuffer, value: int = 0, /) -> int: ... + +if sys.version_info >= (3, 15): + def crc32_combine(crc1: int, crc2: int, len2: int, /) -> int: ... + +def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: ... +def decompressobj(wbits: int = 15, zdict: ReadableBuffer = b"") -> _Decompress: ... diff --git a/stdlib/zoneinfo/__init__.pyi b/stdlib/zoneinfo/__init__.pyi new file mode 100644 index 000000000000..def31546becb --- /dev/null +++ b/stdlib/zoneinfo/__init__.pyi @@ -0,0 +1,36 @@ +import sys +from collections.abc import Iterable +from datetime import datetime, timedelta, tzinfo +from typing_extensions import Self, disjoint_base +from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes +from zoneinfo._tzpath import ( + TZPATH as TZPATH, + InvalidTZPathWarning as InvalidTZPathWarning, + available_timezones as available_timezones, + reset_tzpath as reset_tzpath, +) + +__all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] + +@disjoint_base +class ZoneInfo(tzinfo): + @property + def key(self) -> str: ... + def __new__(cls, key: str) -> Self: ... + @classmethod + def no_cache(cls, key: str) -> Self: ... + + if sys.version_info >= (3, 12): + @classmethod + def from_file(cls, file_obj: _IOBytes, /, key: str | None = None) -> Self: ... + else: + @classmethod + def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ... + + @classmethod + def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ... + def tzname(self, dt: datetime | None, /) -> str | None: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + def dst(self, dt: datetime | None, /) -> timedelta | None: ... + +def __dir__() -> list[str]: ... diff --git a/stdlib/zoneinfo/_common.pyi b/stdlib/zoneinfo/_common.pyi new file mode 100644 index 000000000000..e6d2d83caac1 --- /dev/null +++ b/stdlib/zoneinfo/_common.pyi @@ -0,0 +1,14 @@ +import io +from typing import Any, Protocol, type_check_only + +@type_check_only +class _IOBytes(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, size: int, whence: int = ..., /) -> Any: ... + +def load_tzdata(key: str) -> io.BufferedReader: ... +def load_data( + fobj: _IOBytes, +) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[str, ...], bytes | None]: ... + +class ZoneInfoNotFoundError(KeyError): ... diff --git a/stdlib/zoneinfo/_tzpath.pyi b/stdlib/zoneinfo/_tzpath.pyi new file mode 100644 index 000000000000..0ef78d03e5f4 --- /dev/null +++ b/stdlib/zoneinfo/_tzpath.pyi @@ -0,0 +1,13 @@ +from _typeshed import StrPath +from collections.abc import Sequence + +# Note: Both here and in clear_cache, the types allow the use of `str` where +# a sequence of strings is required. This should be remedied if a solution +# to this typing bug is found: https://github.com/python/typing/issues/256 +def reset_tzpath(to: Sequence[StrPath] | None = None) -> None: ... +def find_tzfile(key: str) -> str | None: ... +def available_timezones() -> set[str]: ... + +TZPATH: tuple[str, ...] + +class InvalidTZPathWarning(RuntimeWarning): ... diff --git a/stubs/Authlib/@tests/stubtest_allowlist.txt b/stubs/Authlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..42440a12d667 --- /dev/null +++ b/stubs/Authlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,54 @@ +# TODO: check these entries +authlib.jose.drafts._jwe_enc_cryptodome + +# Are set to `None` by default, initialized later: +authlib.jose.drafts._jwe_algorithms.ECDH1PUAlgorithm.description +authlib.jose.drafts._jwe_algorithms.ECDH1PUAlgorithm.name +authlib.jose.drafts._jwe_enc_cryptography.C20PEncAlgorithm.description +authlib.jose.drafts._jwe_enc_cryptography.C20PEncAlgorithm.name +authlib.jose.rfc7518.jwe_algs.AESAlgorithm.description +authlib.jose.rfc7518.jwe_algs.AESAlgorithm.name +authlib.jose.rfc7518.jwe_algs.AESGCMAlgorithm.description +authlib.jose.rfc7518.jwe_algs.AESGCMAlgorithm.name +authlib.jose.rfc7518.jwe_algs.ECDHESAlgorithm.description +authlib.jose.rfc7518.jwe_algs.ECDHESAlgorithm.name +authlib.jose.rfc7518.jwe_algs.RSAAlgorithm.description +authlib.jose.rfc7518.jwe_algs.RSAAlgorithm.name +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.CEK_SIZE +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.description +authlib.jose.rfc7518.jwe_encs.CBCHS2EncAlgorithm.name +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.CEK_SIZE +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.description +authlib.jose.rfc7518.jwe_encs.GCMEncAlgorithm.name +authlib.jose.rfc7518.jws_algs.ECAlgorithm.description +authlib.jose.rfc7518.jws_algs.ECAlgorithm.name +authlib.jose.rfc7518.jws_algs.HMACAlgorithm.description +authlib.jose.rfc7518.jws_algs.HMACAlgorithm.name +authlib.jose.rfc7518.jws_algs.RSAAlgorithm.description +authlib.jose.rfc7518.jws_algs.RSAAlgorithm.name +authlib.jose.rfc7518.jws_algs.RSAPSSAlgorithm.description +authlib.jose.rfc7518.jws_algs.RSAPSSAlgorithm.name + +# Methods whose *args and **kwargs arguments are added dynamically due to the @hooked decorator: +authlib.oauth2.rfc6749.grants.authorization_code.AuthorizationCodeGrant.create_token_response +authlib.oauth2.rfc6749.grants.authorization_code.AuthorizationCodeGrant.validate_token_request +authlib.oauth2.rfc6749.grants.base.AuthorizationEndpointMixin.validate_consent_request +authlib.oauth2.rfc6749.grants.client_credentials.ClientCredentialsGrant.create_token_response +authlib.oauth2.rfc6749.grants.implicit.ImplicitGrant.validate_authorization_request +authlib.oauth2.rfc6749.grants.refresh_token.RefreshTokenGrant.create_token_response +authlib.oauth2.rfc6749.grants.resource_owner_password_credentials.ResourceOwnerPasswordCredentialsGrant.create_token_response +authlib.oauth2.rfc8628.device_code.DeviceCodeGrant.create_token_response +authlib.oidc.core.grants.implicit.OpenIDImplicitGrant.validate_consent_request + +# Exclude integrations dirs +# Failed to import, getting ModuleNotFoundError for third-party libs: +authlib.integrations.django_client.* +authlib.integrations.django_oauth1.* +authlib.integrations.django_oauth2.* +authlib.integrations.flask_client.* +authlib.integrations.flask_oauth1.* +authlib.integrations.flask_oauth2.* +authlib.integrations.httpx_client.* +authlib.integrations.requests_client.* +authlib.integrations.sqla_oauth2.* +authlib.integrations.starlette_client.* diff --git a/stubs/Authlib/METADATA.toml b/stubs/Authlib/METADATA.toml new file mode 100644 index 000000000000..6a322fd7f4d3 --- /dev/null +++ b/stubs/Authlib/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.7.2" +upstream-repository = "https://github.com/authlib/authlib" +dependencies = ["cryptography"] diff --git a/stubs/Authlib/authlib/__init__.pyi b/stubs/Authlib/authlib/__init__.pyi new file mode 100644 index 000000000000..a254fc53981c --- /dev/null +++ b/stubs/Authlib/authlib/__init__.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from .consts import author, homepage, version + +__version__: Final = version +__homepage__: Final = homepage +__author__: Final = author +__license__: Final = "BSD-3-Clause" diff --git a/stubs/Authlib/authlib/common/__init__.pyi b/stubs/Authlib/authlib/common/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Authlib/authlib/common/encoding.pyi b/stubs/Authlib/authlib/common/encoding.pyi new file mode 100644 index 000000000000..571136fb6db1 --- /dev/null +++ b/stubs/Authlib/authlib/common/encoding.pyi @@ -0,0 +1,28 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Any, SupportsBytes, SupportsIndex, overload + +@overload +def to_bytes(x: None, charset: str = "utf-8", errors: str = "strict") -> None: ... +@overload +def to_bytes( + x: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + charset: str = "utf-8", + errors: str = "strict", +) -> bytes: ... + +@overload +def to_unicode(x: None, charset: str = "utf-8", errors: str = "strict") -> None: ... +@overload +def to_unicode(x: object, charset: str = "utf-8", errors: str = "strict") -> str: ... + +def to_native(x: str | bytes, encoding: str = "ascii") -> str: ... +def json_loads(s: str | bytes | bytearray) -> Any: ... # returns json.loads() +def json_dumps(data: Any, ensure_ascii: bool = False) -> str: ... # data pass to json.dumps() +def urlsafe_b64decode(s: bytes) -> bytes: ... +def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... +def base64_to_int(s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer) -> int: ... +def int_to_base64(num: int) -> str: ... +def json_b64encode( + text: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, +) -> bytes: ... diff --git a/stubs/Authlib/authlib/common/errors.pyi b/stubs/Authlib/authlib/common/errors.pyi new file mode 100644 index 000000000000..c6b1276d2571 --- /dev/null +++ b/stubs/Authlib/authlib/common/errors.pyi @@ -0,0 +1,21 @@ +from typing import Literal + +class AuthlibBaseError(Exception): + error: str | None + description: str + uri: str | None + def __init__(self, error: str | None = None, description: str | None = None, uri: str | None = None) -> None: ... + +class AuthlibHTTPError(AuthlibBaseError): + status_code: int + def __init__( + self, error: str | None = None, description: str | None = None, uri: str | None = None, status_code: int | None = None + ) -> None: ... + def get_error_description(self) -> str: ... + def get_body(self) -> list[tuple[Literal["error", "error_description", "error_uri"], str | None]]: ... + def get_headers(self) -> list[tuple[str, str]]: ... + def __call__( + self, uri: str | None = None + ) -> tuple[int, dict[Literal["error", "error_description", "error_uri"], str | None], list[tuple[str, str]]]: ... + +class ContinueIteration(AuthlibBaseError): ... diff --git a/stubs/Authlib/authlib/common/language.pyi b/stubs/Authlib/authlib/common/language.pyi new file mode 100644 index 000000000000..34b1ecf943aa --- /dev/null +++ b/stubs/Authlib/authlib/common/language.pyi @@ -0,0 +1 @@ +def is_valid_language_tag(tag: object) -> bool: ... diff --git a/stubs/Authlib/authlib/common/security.pyi b/stubs/Authlib/authlib/common/security.pyi new file mode 100644 index 000000000000..e57814e44167 --- /dev/null +++ b/stubs/Authlib/authlib/common/security.pyi @@ -0,0 +1,6 @@ +from typing import Final + +UNICODE_ASCII_CHARACTER_SET: Final[str] + +def generate_token(length: int = 30, chars: str = UNICODE_ASCII_CHARACTER_SET) -> str: ... # noqa: Y011 +def is_secure_transport(uri: str) -> bool: ... diff --git a/stubs/Authlib/authlib/common/urls.pyi b/stubs/Authlib/authlib/common/urls.pyi new file mode 100644 index 000000000000..2fdea02e0ff4 --- /dev/null +++ b/stubs/Authlib/authlib/common/urls.pyi @@ -0,0 +1,25 @@ +from re import Pattern +from typing import Final, TypeAlias, overload + +always_safe: Final[str] +urlencoded: Final[set[str]] +INVALID_HEX_PATTERN: Final[Pattern[str]] + +_ExplodedQueryString: TypeAlias = list[tuple[str, str]] + +def url_encode(params: _ExplodedQueryString) -> str: ... +def url_decode(query: str) -> _ExplodedQueryString: ... +def add_params_to_qs(query: str, params: _ExplodedQueryString | dict[str, str]) -> str: ... +def add_params_to_uri(uri: str, params: _ExplodedQueryString, fragment: bool = False) -> str: ... +def quote(s: str, safe: bytes = b"/") -> str: ... +def unquote(s: str | bytes) -> str: ... +def quote_url(s: str) -> str: ... + +@overload +def extract_params(raw: None) -> None: ... +@overload +def extract_params(raw: dict[str, str]) -> _ExplodedQueryString: ... +@overload +def extract_params(raw: _ExplodedQueryString | tuple[tuple[str, str], ...] | str) -> _ExplodedQueryString | None: ... + +def is_valid_url(url: str, fragments_allowed: bool = True) -> bool: ... diff --git a/stubs/Authlib/authlib/consts.pyi b/stubs/Authlib/authlib/consts.pyi new file mode 100644 index 000000000000..f8ec0e9e5e3b --- /dev/null +++ b/stubs/Authlib/authlib/consts.pyi @@ -0,0 +1,8 @@ +from typing import Final + +name: Final = "Authlib" +version: Final[str] +author: Final[str] +homepage: Final[str] +default_user_agent: Final[str] +default_json_headers: Final[list[tuple[str, str]]] diff --git a/stubs/Authlib/authlib/deprecate.pyi b/stubs/Authlib/authlib/deprecate.pyi new file mode 100644 index 000000000000..cb8b6991a7d8 --- /dev/null +++ b/stubs/Authlib/authlib/deprecate.pyi @@ -0,0 +1,3 @@ +class AuthlibDeprecationWarning(DeprecationWarning): ... + +def deprecate(message: str, version: str | None = None, stacklevel: int = 3) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/__init__.pyi b/stubs/Authlib/authlib/integrations/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Authlib/authlib/integrations/base_client/__init__.pyi b/stubs/Authlib/authlib/integrations/base_client/__init__.pyi new file mode 100644 index 000000000000..424bfdf05f60 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/__init__.pyi @@ -0,0 +1,29 @@ +from .errors import ( + InvalidTokenError as InvalidTokenError, + MismatchingStateError as MismatchingStateError, + MissingRequestTokenError as MissingRequestTokenError, + MissingTokenError as MissingTokenError, + OAuthError as OAuthError, + TokenExpiredError as TokenExpiredError, + UnsupportedTokenTypeError as UnsupportedTokenTypeError, +) +from .framework_integration import FrameworkIntegration as FrameworkIntegration +from .registry import BaseOAuth as BaseOAuth +from .sync_app import BaseApp as BaseApp, OAuth1Mixin as OAuth1Mixin, OAuth2Mixin as OAuth2Mixin +from .sync_openid import OpenIDMixin as OpenIDMixin + +__all__ = [ + "BaseOAuth", + "BaseApp", + "OAuth1Mixin", + "OAuth2Mixin", + "OpenIDMixin", + "FrameworkIntegration", + "OAuthError", + "MissingRequestTokenError", + "MissingTokenError", + "TokenExpiredError", + "InvalidTokenError", + "UnsupportedTokenTypeError", + "MismatchingStateError", +] diff --git a/stubs/Authlib/authlib/integrations/base_client/async_app.pyi b/stubs/Authlib/authlib/integrations/base_client/async_app.pyi new file mode 100644 index 000000000000..352fd5815b8e --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/async_app.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.integrations.base_client.sync_app import OAuth1Base, OAuth2Base + +log: Logger + +__all__ = ["AsyncOAuth1Mixin", "AsyncOAuth2Mixin"] + +class AsyncOAuth1Mixin(OAuth1Base): + async def request(self, method, url, token=None, **kwargs): ... + async def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + async def fetch_access_token(self, request_token=None, **kwargs): ... + +class AsyncOAuth2Mixin(OAuth2Base): + async def load_server_metadata(self) -> dict[Incomplete, Incomplete]: ... + async def request(self, method, url, token=None, **kwargs): ... + async def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + async def fetch_access_token(self, redirect_uri=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi b/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi new file mode 100644 index 000000000000..3213ac6631b0 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi @@ -0,0 +1,12 @@ +from authlib.integrations.base_client.sync_openid import _LogoutData +from authlib.oidc.core.claims import UserInfo + +__all__ = ["AsyncOpenIDMixin"] + +class AsyncOpenIDMixin: + async def fetch_jwk_set(self, force: bool = False): ... + async def userinfo(self, **kwargs) -> UserInfo: ... + async def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo: ... + async def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/stubs/Authlib/authlib/integrations/base_client/errors.pyi b/stubs/Authlib/authlib/integrations/base_client/errors.pyi new file mode 100644 index 000000000000..0b5cfd7db6d3 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/errors.pyi @@ -0,0 +1,23 @@ +from authlib.common.errors import AuthlibBaseError + +class OAuthError(AuthlibBaseError): + error: str + +class MissingRequestTokenError(OAuthError): + error: str + +class MissingTokenError(OAuthError): + error: str + +class TokenExpiredError(OAuthError): + error: str + +class InvalidTokenError(OAuthError): + error: str + +class UnsupportedTokenTypeError(OAuthError): + error: str + +class MismatchingStateError(OAuthError): + error: str + description: str diff --git a/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi b/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi new file mode 100644 index 000000000000..2c3c871ad658 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/framework_integration.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class FrameworkIntegration: + expires_in: int + name: Incomplete + cache: Incomplete + def __init__(self, name, cache=None) -> None: ... + def get_state_data(self, session, state): ... + def set_state_data(self, session, state, data): ... + def clear_state_data(self, session, state): ... + def update_token(self, token, refresh_token=None, access_token=None): ... + @staticmethod + def load_config(oauth, name, params): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/registry.pyi b/stubs/Authlib/authlib/integrations/base_client/registry.pyi new file mode 100644 index 000000000000..657eefe452b9 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/registry.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from authlib.integrations.base_client import FrameworkIntegration + +__all__ = ["BaseOAuth"] + +class BaseOAuth: + oauth1_client_cls: Incomplete + oauth2_client_cls: Incomplete + framework_integration_cls: type[FrameworkIntegration] = ... + cache: Incomplete + fetch_token: Incomplete + update_token: Incomplete + def __init__(self, cache=None, fetch_token=None, update_token=None) -> None: ... + def create_client(self, name): ... + def register(self, name, overwrite: bool = False, **kwargs): ... + def generate_client_kwargs(self, name, overwrite, **kwargs) -> dict[Incomplete, Incomplete]: ... + def load_config(self, name, params): ... + def __getattr__(self, key): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi b/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi new file mode 100644 index 000000000000..8263f9975674 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/sync_app.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete +from logging import Logger + +log: Logger + +class BaseApp: + client_cls: Incomplete + OAUTH_APP_CONFIG: Incomplete + def request(self, method, url, token=None, **kwargs): ... + def get(self, url, **kwargs): ... + def post(self, url, **kwargs): ... + def patch(self, url, **kwargs): ... + def put(self, url, **kwargs): ... + def delete(self, url, **kwargs): ... + +class _RequestMixin: ... + +class OAuth1Base: + client_cls: Incomplete + framework: Incomplete + name: Incomplete + client_id: Incomplete + client_secret: Incomplete + request_token_url: Incomplete + request_token_params: Incomplete + access_token_url: Incomplete + access_token_params: Incomplete + authorize_url: Incomplete + authorize_params: Incomplete + api_base_url: Incomplete + client_kwargs: Incomplete + def __init__( + self, + framework, + name=None, + fetch_token=None, + client_id=None, + client_secret=None, + request_token_url=None, + request_token_params=None, + access_token_url=None, + access_token_params=None, + authorize_url=None, + authorize_params=None, + api_base_url=None, + client_kwargs=None, + user_agent=None, + **kwargs, + ) -> None: ... + +class OAuth1Mixin(_RequestMixin, OAuth1Base): + def request(self, method, url, token=None, **kwargs): ... + def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + def fetch_access_token(self, request_token=None, **kwargs): ... + +class OAuth2Base: + client_cls: Incomplete + framework: Incomplete + name: Incomplete + client_id: Incomplete + client_secret: Incomplete + access_token_url: Incomplete + access_token_params: Incomplete + authorize_url: Incomplete + authorize_params: Incomplete + api_base_url: Incomplete + client_kwargs: Incomplete + compliance_fix: Incomplete + client_auth_methods: Incomplete + server_metadata: Incomplete + def __init__( + self, + framework, + name=None, + fetch_token=None, + update_token=None, + client_id=None, + client_secret=None, + access_token_url=None, + access_token_params=None, + authorize_url=None, + authorize_params=None, + api_base_url=None, + client_kwargs=None, + server_metadata_url=None, + compliance_fix=None, + client_auth_methods=None, + user_agent=None, + **kwargs, + ) -> None: ... + +class OAuth2Mixin(_RequestMixin, OAuth2Base): + def request(self, method, url, token=None, **kwargs): ... + def load_server_metadata(self) -> dict[Incomplete, Incomplete]: ... + def create_authorization_url(self, redirect_uri=None, **kwargs) -> dict[Incomplete, Incomplete]: ... + def fetch_access_token(self, redirect_uri=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi b/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi new file mode 100644 index 000000000000..5bd8eb1de7da --- /dev/null +++ b/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from authlib.oidc.core.claims import UserInfo + +@type_check_only +class _LogoutData(TypedDict): + url: str + state: Incomplete + +class OpenIDMixin: + def fetch_jwk_set(self, force: bool = False): ... + def userinfo(self, **kwargs) -> UserInfo: ... + def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo | None: ... + def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/stubs/Authlib/authlib/integrations/django_client/__init__.pyi b/stubs/Authlib/authlib/integrations/django_client/__init__.pyi new file mode 100644 index 000000000000..c5c48e4777c5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/__init__.pyi @@ -0,0 +1,10 @@ +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import DjangoOAuth1App as DjangoOAuth1App, DjangoOAuth2App as DjangoOAuth2App +from .integration import DjangoIntegration as DjangoIntegration, token_update as token_update + +class OAuth(BaseOAuth): + oauth1_client_cls = DjangoOAuth1App + oauth2_client_cls = DjangoOAuth2App + framework_integration_cls = DjangoIntegration + +__all__ = ["OAuth", "DjangoOAuth1App", "DjangoOAuth2App", "DjangoIntegration", "token_update", "OAuthError"] diff --git a/stubs/Authlib/authlib/integrations/django_client/apps.pyi b/stubs/Authlib/authlib/integrations/django_client/apps.pyi new file mode 100644 index 000000000000..1325168c1fc4 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/apps.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin +from ..requests_client import OAuth1Session, OAuth2Session + +_HttpResponseRedirect: TypeAlias = Incomplete # actual type is django.http.response.HttpResponseRedirect + +class DjangoAppMixin: + def save_authorize_data(self, request, **kwargs) -> None: ... + def authorize_redirect(self, request, redirect_uri=None, **kwargs): ... + +class DjangoOAuth1App(DjangoAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + def authorize_access_token(self, request, **kwargs): ... + +class DjangoOAuth2App(DjangoAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _HttpResponseRedirect: ... + def validate_logout_response(self, request): ... + def authorize_access_token(self, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/django_client/integration.pyi b/stubs/Authlib/authlib/integrations/django_client/integration.pyi new file mode 100644 index 000000000000..91469e1953da --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_client/integration.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from ..base_client import FrameworkIntegration + +# actual type is django.dispatch.Signal +token_update: Incomplete + +class DjangoIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi new file mode 100644 index 000000000000..3c684184a795 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/__init__.pyi @@ -0,0 +1,4 @@ +from .authorization_server import BaseServer as BaseServer, CacheAuthorizationServer as CacheAuthorizationServer +from .resource_protector import ResourceProtector as ResourceProtector + +__all__ = ["BaseServer", "CacheAuthorizationServer", "ResourceProtector"] diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi new file mode 100644 index 000000000000..2d4b0bacaca5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/authorization_server.pyi @@ -0,0 +1,26 @@ +import logging +from _typeshed import Incomplete + +from authlib.oauth1 import AuthorizationServer as _AuthorizationServer, OAuth1Request, TemporaryCredential + +log: logging.Logger + +class BaseServer(_AuthorizationServer): + token_generator: Incomplete + client_model: Incomplete + token_model: Incomplete + SUPPORTED_SIGNATURE_METHODS: Incomplete + def __init__(self, client_model, token_model, token_generator=None) -> None: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request) -> bool: ... + def create_token_credential(self, request): ... + def check_authorization_request(self, request) -> OAuth1Request: ... + def create_oauth1_request(self, request) -> OAuth1Request: ... + def handle_response(self, status_code, payload, headers): ... + +class CacheAuthorizationServer(BaseServer): + def __init__(self, client_model, token_model, token_generator=None) -> None: ... + def create_temporary_credential(self, request) -> TemporaryCredential: ... + def get_temporary_credential(self, request) -> TemporaryCredential | None: ... + def delete_temporary_credential(self, request) -> None: ... + def create_authorization_verifier(self, request) -> str: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi new file mode 100644 index 000000000000..b4d93191444c --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/nonce.pyi @@ -0,0 +1 @@ +def exists_nonce_in_cache(nonce, request, timeout) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi b/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi new file mode 100644 index 000000000000..d3e3f568d21b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth1/resource_protector.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from authlib.oauth1 import ResourceProtector as _ResourceProtector + +class ResourceProtector(_ResourceProtector): + client_model: Incomplete + token_model: Incomplete + SUPPORTED_SIGNATURE_METHODS: Incomplete + def __init__(self, client_model, token_model) -> None: ... + def get_client_by_id(self, client_id): ... + def get_token_credential(self, request): ... + def exists_nonce(self, nonce, request) -> bool: ... + def acquire_credential(self, request): ... + def __call__(self, realm=None): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi new file mode 100644 index 000000000000..d627f322cf4d --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/__init__.pyi @@ -0,0 +1,8 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .endpoints import RevocationEndpoint as RevocationEndpoint +from .resource_protector import BearerTokenValidator as BearerTokenValidator, ResourceProtector as ResourceProtector +from .signals import ( + client_authenticated as client_authenticated, + token_authenticated as token_authenticated, + token_revoked as token_revoked, +) diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi new file mode 100644 index 000000000000..cecb3d9ae968 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/authorization_server.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import AuthorizationServer as _AuthorizationServer +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +from .requests import DjangoJsonRequest, DjangoOAuth2Request + +class AuthorizationServer(_AuthorizationServer): + client_model: Incomplete + token_model: Incomplete + def __init__(self, client_model, token_model) -> None: ... + config: Incomplete + scopes_supported: Incomplete + def load_config(self, config) -> None: ... + def query_client(self, client_id): ... + def save_token(self, token, request): ... + def create_oauth2_request(self, request) -> DjangoOAuth2Request: ... + def create_json_request(self, request) -> DjangoJsonRequest: ... + def handle_response(self, status_code, payload, headers): ... + def send_signal(self, name, *args, **kwargs) -> None: ... + def create_bearer_token_generator(self) -> BearerTokenGenerator: ... + +def create_token_generator(token_generator_conf, length: int = 42): ... +def create_token_expires_in_generator(expires_in_conf=None): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi new file mode 100644 index 000000000000..9eb7a277a46b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/endpoints.pyi @@ -0,0 +1,5 @@ +from authlib.oauth2.rfc7009 import RevocationEndpoint as _RevocationEndpoint + +class RevocationEndpoint(_RevocationEndpoint): + def query_token(self, token, token_type_hint): ... + def revoke_token(self, token, request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi new file mode 100644 index 000000000000..05006392b374 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/requests.pyi @@ -0,0 +1,20 @@ +from authlib.oauth2.rfc6749 import JsonPayload, JsonRequest, OAuth2Payload, OAuth2Request + +class DjangoOAuth2Payload(OAuth2Payload): + def __init__(self, request) -> None: ... + +class DjangoOAuth2Request(OAuth2Request): + payload: DjangoOAuth2Payload + def __init__(self, request) -> None: ... + @property + def args(self): ... + @property + def form(self): ... + +class DjangoJsonPayload(JsonPayload): + def __init__(self, request) -> None: ... + def data(self): ... + +class DjangoJsonRequest(JsonRequest): + payload: DjangoJsonPayload + def __init__(self, request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi new file mode 100644 index 000000000000..1538f368ca44 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/resource_protector.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import ResourceProtector as _ResourceProtector +from authlib.oauth2.rfc6750 import BearerTokenValidator as _BearerTokenValidator + +class ResourceProtector(_ResourceProtector): + def acquire_token(self, request, scopes=None, **kwargs): ... + def __call__(self, scopes=None, optional=False, **kwargs): ... + +class BearerTokenValidator(_BearerTokenValidator): + token_model: Incomplete + def __init__(self, token_model, realm=None, **extra_attributes): ... + def authenticate_token(self, token_string): ... + +def return_error_response(error): ... diff --git a/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi b/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi new file mode 100644 index 000000000000..c5e48ddef194 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/django_oauth2/signals.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +# actual types is django.dispatch.Signal +client_authenticated: Incomplete +token_revoked: Incomplete +token_authenticated: Incomplete diff --git a/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi new file mode 100644 index 000000000000..575d8ae26f86 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/__init__.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import FlaskOAuth1App as FlaskOAuth1App, FlaskOAuth2App as FlaskOAuth2App +from .integration import FlaskIntegration as FlaskIntegration, token_update as token_update + +class OAuth(BaseOAuth): + oauth1_client_cls = FlaskOAuth1App + oauth2_client_cls = FlaskOAuth2App + framework_integration_cls = FlaskIntegration + app: Incomplete + def __init__(self, app=None, cache=None, fetch_token=None, update_token=None): ... + cache: Incomplete + fetch_token: Incomplete + update_token: Incomplete + def init_app(self, app, cache=None, fetch_token=None, update_token=None): ... + def create_client(self, name): ... + def register(self, name, overwrite=False, **kwargs): ... + +__all__ = ["OAuth", "FlaskIntegration", "FlaskOAuth1App", "FlaskOAuth2App", "token_update", "OAuthError"] diff --git a/stubs/Authlib/authlib/integrations/flask_client/apps.pyi b/stubs/Authlib/authlib/integrations/flask_client/apps.pyi new file mode 100644 index 000000000000..f11d6d1b7e74 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/apps.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin +from ..requests_client import OAuth1Session, OAuth2Session + +_Response: TypeAlias = Incomplete # actual type is werkzeug.wrappers.Response + +class FlaskAppMixin: + @property + def token(self): ... + @token.setter + def token(self, token): ... + + def save_authorize_data(self, **kwargs) -> None: ... + def authorize_redirect(self, redirect_uri=None, **kwargs): ... + +class FlaskOAuth1App(FlaskAppMixin, OAuth1Mixin, BaseApp): + client_cls = OAuth1Session + def authorize_access_token(self, **kwargs): ... + +class FlaskOAuth2App(FlaskAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): + client_cls = OAuth2Session + def logout_redirect( + self, post_logout_redirect_uri=None, id_token_hint=None, *, state=None, client_id=None, logout_hint=None, ui_locales=None + ) -> _Response: ... + def validate_logout_response(self): ... + def authorize_access_token(self, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/flask_client/integration.pyi b/stubs/Authlib/authlib/integrations/flask_client/integration.pyi new file mode 100644 index 000000000000..7bcacdd47d99 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_client/integration.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from ..base_client import FrameworkIntegration + +token_update: Incomplete + +class FlaskIntegration(FrameworkIntegration): + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi new file mode 100644 index 000000000000..fbe0b2b0ad44 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/__init__.pyi @@ -0,0 +1,7 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .cache import ( + create_exists_nonce_func as create_exists_nonce_func, + register_nonce_hooks as register_nonce_hooks, + register_temporary_credential_hooks as register_temporary_credential_hooks, +) +from .resource_protector import ResourceProtector as ResourceProtector, current_credential as current_credential diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi new file mode 100644 index 000000000000..1a4f39d999a9 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/authorization_server.pyi @@ -0,0 +1,29 @@ +import logging +from _typeshed import Incomplete +from collections.abc import Callable + +from authlib.oauth1 import AuthorizationServer as _AuthorizationServer, OAuth1Request + +log: logging.Logger + +class AuthorizationServer(_AuthorizationServer): + app: Incomplete + query_client: Incomplete + token_generator: Incomplete + def __init__(self, app=None, query_client=None, token_generator=None): ... + SUPPORTED_SIGNATURE_METHODS: Incomplete + def init_app(self, app, query_client=None, token_generator=None): ... + def register_hook(self, name, func) -> None: ... + def create_token_generator(self, app) -> Callable[[], dict[str, str]]: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request): ... + def create_temporary_credential(self, request): ... + def get_temporary_credential(self, request): ... + def delete_temporary_credential(self, request): ... + def create_authorization_verifier(self, request): ... + def create_token_credential(self, request): ... + def check_authorization_request(self) -> OAuth1Request: ... + def create_authorization_response(self, request=None, grant_user=None): ... + def create_token_response(self, request=None): ... + def create_oauth1_request(self, request) -> OAuth1Request: ... + def handle_response(self, status_code, payload, headers): ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi new file mode 100644 index 000000000000..a88e4f9bcd6f --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/cache.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +def register_temporary_credential_hooks(authorization_server, cache, key_prefix: str = "temporary_credential:") -> None: ... +def create_exists_nonce_func( + cache, key_prefix="nonce:", expires=86400 +) -> Callable[[Incomplete, Incomplete, Incomplete, Incomplete], Incomplete]: ... +def register_nonce_hooks(authorization_server, cache, key_prefix: str = "nonce:", expires=86400) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi b/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi new file mode 100644 index 000000000000..dec0175c3059 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth1/resource_protector.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from authlib.oauth1 import ResourceProtector as _ResourceProtector + +class ResourceProtector(_ResourceProtector): + app: Incomplete + query_client: Incomplete + query_token: Incomplete + def __init__(self, app=None, query_client=None, query_token=None, exists_nonce=None) -> None: ... + SUPPORTED_SIGNATURE_METHODS: Incomplete + def init_app(self, app, query_client=None, query_token=None, exists_nonce=None): ... + def get_client_by_id(self, client_id): ... + def get_token_credential(self, request): ... + def exists_nonce(self, nonce, request): ... + def acquire_credential(self): ... + def __call__(self, scope=None): ... + +current_credential: Incomplete diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi new file mode 100644 index 000000000000..ba510bf3a322 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/__init__.pyi @@ -0,0 +1,7 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .resource_protector import ResourceProtector as ResourceProtector, current_token as current_token +from .signals import ( + client_authenticated as client_authenticated, + token_authenticated as token_authenticated, + token_revoked as token_revoked, +) diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi new file mode 100644 index 000000000000..3856935af6cf --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/authorization_server.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import AuthorizationServer as _AuthorizationServer +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +from .requests import FlaskJsonRequest, FlaskOAuth2Request + +class AuthorizationServer(_AuthorizationServer): + def __init__(self, app=None, query_client=None, save_token=None) -> None: ... + def init_app(self, app, query_client=None, save_token=None) -> None: ... + scopes_supported: Incomplete + def load_config(self, config) -> None: ... + def query_client(self, client_id): ... + def save_token(self, token, request): ... + def get_error_uri(self, request, error): ... + def create_oauth2_request(self, request) -> FlaskOAuth2Request: ... + def create_json_request(self, request) -> FlaskJsonRequest: ... + def handle_response(self, status_code, payload, headers): ... + def send_signal(self, name, *args, **kwargs) -> None: ... + def create_bearer_token_generator(self, config) -> BearerTokenGenerator: ... + +def create_token_expires_in_generator(expires_in_conf=None): ... +def create_token_generator(token_generator_conf, length: int = 42): ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi new file mode 100644 index 000000000000..63389264ebcc --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +# Inherits from werkzeug.exceptions.HTTPException +class _HTTPException: + code: Incomplete + body: Incomplete + headers: Incomplete + def __init__(self, code, body, headers, response=None) -> None: ... + # Params depends on `werkzeug` package version + def get_body(self, environ=None, scope=None): ... + def get_headers(self, environ=None, scope=None): ... + +def raise_http_exception(status, body, headers) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi new file mode 100644 index 000000000000..f2e657d31aa6 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/requests.pyi @@ -0,0 +1,27 @@ +from functools import cached_property + +from authlib.oauth2.rfc6749 import JsonPayload, JsonRequest, OAuth2Payload, OAuth2Request + +class FlaskOAuth2Payload(OAuth2Payload): + def __init__(self, request) -> None: ... + @property + def data(self): ... + @cached_property + def datalist(self): ... + +class FlaskOAuth2Request(OAuth2Request): + payload: FlaskOAuth2Payload + def __init__(self, request) -> None: ... + @property + def args(self): ... + @property + def form(self): ... + +class FlaskJsonPayload(JsonPayload): + def __init__(self, request) -> None: ... + @property + def data(self): ... + +class FlaskJsonRequest(JsonRequest): + payload: FlaskJsonPayload + def __init__(self, request) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi new file mode 100644 index 000000000000..c0b262f8faf7 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from contextlib import contextmanager +from typing_extensions import Never + +from authlib.oauth2 import ResourceProtector as _ResourceProtector + +class ResourceProtector(_ResourceProtector): + def raise_error_response(self, error) -> Never: ... + def acquire_token(self, scopes=None, **kwargs): ... + @contextmanager + def acquire(self, scopes=None) -> Generator[Incomplete]: ... + def __call__(self, scopes=None, optional=False, **kwargs): ... + +current_token: Incomplete diff --git a/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi b/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi new file mode 100644 index 000000000000..f64d46c1d023 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/flask_oauth2/signals.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +client_authenticated: Incomplete +token_revoked: Incomplete +token_authenticated: Incomplete diff --git a/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi b/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi new file mode 100644 index 000000000000..58b88a90fb2d --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/__init__.pyi @@ -0,0 +1,37 @@ +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) + +from ..base_client import OAuthError as OAuthError +from .assertion_client import AssertionClient as AssertionClient, AsyncAssertionClient as AsyncAssertionClient +from .oauth1_client import AsyncOAuth1Client as AsyncOAuth1Client, OAuth1Auth as OAuth1Auth, OAuth1Client as OAuth1Client +from .oauth2_client import ( + AsyncOAuth2Client as AsyncOAuth2Client, + OAuth2Auth as OAuth2Auth, + OAuth2Client as OAuth2Client, + OAuth2ClientAuth as OAuth2ClientAuth, +) + +__all__ = [ + "OAuthError", + "OAuth1Auth", + "AsyncOAuth1Client", + "OAuth1Client", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "OAuth2Auth", + "OAuth2ClientAuth", + "OAuth2Client", + "AsyncOAuth2Client", + "AssertionClient", + "AsyncAssertionClient", +] diff --git a/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi new file mode 100644 index 000000000000..f2061d98aedf --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/assertion_client.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc7521 import AssertionClient as _AssertionClient + +from ..base_client import OAuthError +from .oauth2_client import OAuth2Auth + +__all__ = ["AsyncAssertionClient"] + +# Inherits from httpx.AsyncClient +class AsyncAssertionClient(_AssertionClient): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + **kwargs, + ) -> None: ... + async def request(self, method, url, withhold_token=False, auth=..., **kwargs): ... + +# Inherits from httpx.Client +class AssertionClient(_AssertionClient): + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + **kwargs, + ) -> None: ... + def request(self, method, url, withhold_token=False, auth=..., **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi new file mode 100644 index 000000000000..423172e9913e --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import TypeAlias +from typing_extensions import Never + +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client as _OAuth1Client + +_Response: TypeAlias = Incomplete # actual type is httpx.Response +_Request: TypeAlias = Incomplete # actual type is httpx.Request + +# Inherits from httpx.Auth +class OAuth1Auth(ClientAuth): + requires_request_body: bool + def auth_flow(self, request: _Request) -> Generator[_Request, _Response]: ... + +# Inherits from httpx.AsyncClient +class AsyncOAuth1Client(_OAuth1Client): + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method=..., + signature_type=..., + force_include_body=False, + **kwargs, + ) -> None: ... + async def fetch_access_token(self, url, verifier=None, **kwargs): ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... + +# Inherits from httpx.Client +class OAuth1Client(_OAuth1Client): + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method=..., + signature_type=..., + force_include_body=False, + **kwargs, + ) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi b/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi new file mode 100644 index 000000000000..2fc9facabeb5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import TypeAlias +from typing_extensions import Never + +from authlib.oauth2.auth import ClientAuth, TokenAuth +from authlib.oauth2.client import OAuth2Client as _OAuth2Client + +from ..base_client import OAuthError + +__all__ = ["OAuth2Auth", "OAuth2ClientAuth", "AsyncOAuth2Client", "OAuth2Client"] + +_Response: TypeAlias = Incomplete # actual type is httpx.Response +_Request: TypeAlias = Incomplete # actual type is httpx.Request + +# Inherits from httpx.Auth +class OAuth2Auth(TokenAuth): + requires_request_body: bool + def auth_flow(self, request: _Request) -> Generator[_Request, _Response]: ... + +# Inherits from httpx.Auth +class OAuth2ClientAuth(ClientAuth): + requires_request_body: bool + def auth_flow(self, request: _Request) -> Generator[_Request, _Response]: ... + +# Inherits from httpx.AsyncClient +class AsyncOAuth2Client(_OAuth2Client): + SESSION_REQUEST_PARAMS: list[str] + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + leeway=60, + **kwargs, + ) -> None: ... + async def request(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... + async def stream(self, method, url, withhold_token: bool = False, auth=..., **kwargs) -> Generator[Incomplete]: ... + async def ensure_active_token(self, token): ... # type: ignore[override] + +# Inherits from httpx.Client +class OAuth2Client(_OAuth2Client): + SESSION_REQUEST_PARAMS: list[str] + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + **kwargs, + ) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... + def request(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... + def stream(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi b/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi new file mode 100644 index 000000000000..d4e4547e4470 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/httpx_client/utils.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete +from typing import Final + +HTTPX_CLIENT_KWARGS: Final[list[str]] + +def extract_client_kwargs(kwargs) -> dict[str, Incomplete]: ... +def build_request(url, headers, body, initial_request): ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi b/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi new file mode 100644 index 000000000000..fc7b705e0ce0 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/__init__.pyi @@ -0,0 +1,28 @@ +from authlib.oauth1 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) + +from ..base_client import OAuthError as OAuthError +from .assertion_session import AssertionSession as AssertionSession +from .oauth1_session import OAuth1Auth as OAuth1Auth, OAuth1Session as OAuth1Session +from .oauth2_session import OAuth2Auth as OAuth2Auth, OAuth2Session as OAuth2Session + +__all__ = [ + "OAuthError", + "OAuth1Session", + "OAuth1Auth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "OAuth2Session", + "OAuth2Auth", + "AssertionSession", +] diff --git a/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi new file mode 100644 index 000000000000..87f9ae004384 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/assertion_session.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc7521 import AssertionClient + +from .oauth2_session import OAuth2Auth + +class AssertionAuth(OAuth2Auth): + def ensure_active_token(self): ... + +# Inherits from requests.Session +class AssertionSession(AssertionClient): + token_auth_class = AssertionAuth + JWT_BEARER_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + DEFAULT_GRANT_TYPE: Incomplete + default_timeout: Incomplete + def __init__( + self, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement="header", + scope=None, + default_timeout=None, + leeway=60, + **kwargs, + ) -> None: ... + def request(self, method, url, withhold_token=False, auth=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi new file mode 100644 index 000000000000..d197f07f7e9e --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi @@ -0,0 +1,29 @@ +from typing_extensions import Never + +from authlib.oauth1 import ClientAuth +from authlib.oauth1.client import OAuth1Client + +# Inherits from requests.auth.AuthBase +class OAuth1Auth(ClientAuth): + def __call__(self, req): ... + +# Inherits from requests.Session +class OAuth1Session(OAuth1Client): + auth_class = OAuth1Auth + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method=..., + signature_type=..., + force_include_body=False, + **kwargs, + ) -> None: ... + def rebuild_auth(self, prepared_request, response) -> None: ... + @staticmethod + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi b/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi new file mode 100644 index 000000000000..f358acc47ca5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/oauth2_session.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from authlib.oauth2.auth import ClientAuth, TokenAuth +from authlib.oauth2.client import OAuth2Client + +from ..base_client import OAuthError + +__all__ = ["OAuth2Session", "OAuth2Auth"] + +# Inherits from requests.auth.AuthBase +class OAuth2Auth(TokenAuth): + def ensure_active_token(self) -> None: ... + def __call__(self, req): ... + +# Inherits from requests.auth.AuthBase +class OAuth2ClientAuth(ClientAuth): + def __call__(self, req): ... + +# Inherits from requests.Session +class OAuth2Session(OAuth2Client): + client_auth_class = OAuth2ClientAuth + token_auth_class = OAuth2Auth + oauth_error_class = OAuthError # type: ignore[assignment] + SESSION_REQUEST_PARAMS: tuple[str, ...] # type: ignore[assignment] + default_timeout: Incomplete + def __init__( + self, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + state=None, + redirect_uri=None, + token=None, + token_placement="header", + update_token=None, + leeway=60, + default_timeout=None, + **kwargs, + ) -> None: ... + def fetch_access_token(self, url=None, **kwargs): ... + def request(self, method, url, withhold_token=False, auth=None, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/requests_client/utils.pyi b/stubs/Authlib/authlib/integrations/requests_client/utils.pyi new file mode 100644 index 000000000000..f93f9a06f07b --- /dev/null +++ b/stubs/Authlib/authlib/integrations/requests_client/utils.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete +from typing import Final + +REQUESTS_SESSION_KWARGS: Final = ["proxies", "hooks", "stream", "verify", "cert", "max_redirects", "trust_env"] + +def update_session_configure(session, kwargs: dict[str, Incomplete]) -> None: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi new file mode 100644 index 000000000000..364a0a9fb2eb --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/__init__.pyi @@ -0,0 +1,20 @@ +from .client_mixin import OAuth2ClientMixin as OAuth2ClientMixin +from .functions import ( + create_bearer_token_validator as create_bearer_token_validator, + create_query_client_func as create_query_client_func, + create_query_token_func as create_query_token_func, + create_revocation_endpoint as create_revocation_endpoint, + create_save_token_func as create_save_token_func, +) +from .tokens_mixins import OAuth2AuthorizationCodeMixin as OAuth2AuthorizationCodeMixin, OAuth2TokenMixin as OAuth2TokenMixin + +__all__ = [ + "OAuth2ClientMixin", + "OAuth2AuthorizationCodeMixin", + "OAuth2TokenMixin", + "create_query_client_func", + "create_save_token_func", + "create_query_token_func", + "create_revocation_endpoint", + "create_bearer_token_validator", +] diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi new file mode 100644 index 000000000000..94606b7d19e5 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/client_mixin.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import ClientMixin + +class OAuth2ClientMixin(ClientMixin): + client_id: Incomplete + client_secret: Incomplete + client_id_issued_at: Incomplete + client_secret_expires_at: Incomplete + _client_metadata: Incomplete + @property + def client_info(self) -> dict[str, Incomplete]: ... + @property + def client_metadata(self): ... + def set_client_metadata(self, value) -> None: ... + @property + def redirect_uris(self): ... + @property + def token_endpoint_auth_method(self): ... + @property + def grant_types(self): ... + @property + def response_types(self): ... + @property + def client_name(self): ... + @property + def client_uri(self): ... + @property + def logo_uri(self): ... + @property + def scope(self): ... + @property + def contacts(self): ... + @property + def tos_uri(self): ... + @property + def policy_uri(self): ... + @property + def jwks_uri(self): ... + @property + def jwks(self): ... + @property + def software_id(self): ... + @property + def software_version(self): ... + @property + def id_token_signed_response_alg(self): ... + def get_client_id(self): ... + def get_default_redirect_uri(self): ... + def get_allowed_scope(self, scope) -> str: ... + def check_redirect_uri(self, redirect_uri) -> bool: ... + def check_client_secret(self, client_secret) -> bool: ... + def check_endpoint_auth_method(self, method, endpoint) -> bool: ... + def check_response_type(self, response_type) -> bool: ... + def check_grant_type(self, grant_type) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi new file mode 100644 index 000000000000..0590b36eda08 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/functions.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import type_check_only + +from authlib.oauth2.rfc6750 import BearerTokenValidator +from authlib.oauth2.rfc7009 import RevocationEndpoint + +@type_check_only +class _RevocationEndpoint(RevocationEndpoint): + def query_token(self, token, token_type_hint): ... + def revoke_token(self, token, request) -> None: ... + +@type_check_only +class _BearerTokenValidator(BearerTokenValidator): + def authenticate_token(self, token_string): ... + +def create_query_client_func(session, client_model) -> Callable[[Incomplete], Incomplete]: ... +def create_save_token_func(session, token_model) -> Callable[[Incomplete, Incomplete], None]: ... +def create_query_token_func(session, token_model) -> Callable[[Incomplete, Incomplete], Incomplete]: ... +def create_revocation_endpoint(session, token_model) -> type[_RevocationEndpoint]: ... +def create_bearer_token_validator(session, token_model) -> type[_BearerTokenValidator]: ... diff --git a/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi b/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi new file mode 100644 index 000000000000..25166d5f0f4c --- /dev/null +++ b/stubs/Authlib/authlib/integrations/sqla_oauth2/tokens_mixins.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import AuthorizationCodeMixin, TokenMixin + +class OAuth2AuthorizationCodeMixin(AuthorizationCodeMixin): + code: Incomplete + client_id: Incomplete + redirect_uri: Incomplete + response_type: Incomplete + scope: Incomplete + nonce: Incomplete + auth_time: Incomplete + acr: Incomplete + amr: Incomplete + code_challenge: Incomplete + code_challenge_method: Incomplete + def is_expired(self) -> bool: ... + def get_redirect_uri(self): ... + def get_scope(self): ... + def get_auth_time(self): ... + def get_acr(self): ... + def get_amr(self): ... + def get_nonce(self): ... + +class OAuth2TokenMixin(TokenMixin): + client_id: Incomplete + token_type: Incomplete + access_token: Incomplete + refresh_token: Incomplete + scope: Incomplete + issued_at: Incomplete + access_token_revoked_at: Incomplete + refresh_token_revoked_at: Incomplete + expires_in: Incomplete + def check_client(self, client) -> bool: ... + def get_scope(self): ... + def get_expires_in(self): ... + def is_revoked(self): ... + def is_expired(self) -> bool: ... diff --git a/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi b/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi new file mode 100644 index 000000000000..ea654f6f55bd --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/__init__.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from ..base_client import BaseOAuth, OAuthError as OAuthError +from .apps import StarletteOAuth1App as StarletteOAuth1App, StarletteOAuth2App as StarletteOAuth2App +from .integration import StarletteIntegration as StarletteIntegration + +class OAuth(BaseOAuth): + oauth1_client_cls = StarletteOAuth1App + oauth2_client_cls = StarletteOAuth2App + framework_integration_cls = StarletteIntegration + config: Incomplete + def __init__(self, config=None, cache=None, fetch_token=None, update_token=None) -> None: ... + +__all__ = ["OAuth", "OAuthError", "StarletteIntegration", "StarletteOAuth1App", "StarletteOAuth2App"] diff --git a/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi b/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi new file mode 100644 index 000000000000..47b6267c4430 --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +from ..base_client import BaseApp +from ..base_client.async_app import AsyncOAuth1Mixin, AsyncOAuth2Mixin +from ..base_client.async_openid import AsyncOpenIDMixin +from ..httpx_client import AsyncOAuth1Client, AsyncOAuth2Client + +_RedirectResponse: TypeAlias = Incomplete # actual type is starlette.responses.RedirectResponse + +class StarletteAppMixin: + async def save_authorize_data(self, request, **kwargs) -> None: ... + async def authorize_redirect(self, request, redirect_uri=None, **kwargs) -> _RedirectResponse: ... + +class StarletteOAuth1App(StarletteAppMixin, AsyncOAuth1Mixin, BaseApp): + client_cls = AsyncOAuth1Client + async def authorize_access_token(self, request, **kwargs): ... + +class StarletteOAuth2App(StarletteAppMixin, AsyncOAuth2Mixin, AsyncOpenIDMixin, BaseApp): + client_cls = AsyncOAuth2Client + async def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _RedirectResponse: ... + async def validate_logout_response(self, request): ... + async def authorize_access_token(self, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi b/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi new file mode 100644 index 000000000000..6848c50141ee --- /dev/null +++ b/stubs/Authlib/authlib/integrations/starlette_client/integration.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from typing import Any + +from ..base_client import FrameworkIntegration + +class StarletteIntegration(FrameworkIntegration): + # annotated by source code + async def get_state_data(self, session: dict[str, Any] | None, state: str) -> dict[str, Any]: ... + async def set_state_data(self, session: dict[str, Any] | None, state: str, data: Any) -> None: ... + async def clear_state_data(self, session: dict[str, Any] | None, state: str) -> None: ... + def update_token(self, token, refresh_token=None, access_token=None) -> None: ... + @staticmethod + def load_config(oauth, name, params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/jose/__init__.pyi b/stubs/Authlib/authlib/jose/__init__.pyi new file mode 100644 index 000000000000..3377c3dbdef7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/__init__.pyi @@ -0,0 +1,42 @@ +from .errors import JoseError as JoseError +from .rfc7515 import ( + JsonWebSignature as JsonWebSignature, + JWSAlgorithm as JWSAlgorithm, + JWSHeader as JWSHeader, + JWSObject as JWSObject, +) +from .rfc7516 import ( + JsonWebEncryption as JsonWebEncryption, + JWEAlgorithm as JWEAlgorithm, + JWEEncAlgorithm as JWEEncAlgorithm, + JWEZipAlgorithm as JWEZipAlgorithm, +) +from .rfc7517 import JsonWebKey as JsonWebKey, Key as Key, KeySet as KeySet +from .rfc7518 import ECKey as ECKey, OctKey as OctKey, RSAKey as RSAKey +from .rfc7519 import BaseClaims as BaseClaims, JsonWebToken as JsonWebToken, JWTClaims as JWTClaims +from .rfc8037 import OKPKey as OKPKey + +jwt: JsonWebToken + +__all__ = [ + "JoseError", + "JsonWebSignature", + "JWSAlgorithm", + "JWSHeader", + "JWSObject", + "JsonWebEncryption", + "JWEAlgorithm", + "JWEEncAlgorithm", + "JWEZipAlgorithm", + "JsonWebKey", + "Key", + "KeySet", + "OctKey", + "RSAKey", + "ECKey", + "OKPKey", + "JsonWebToken", + "BaseClaims", + "JWTClaims", + "jwt", +] diff --git a/stubs/Authlib/authlib/jose/drafts/__init__.pyi b/stubs/Authlib/authlib/jose/drafts/__init__.pyi new file mode 100644 index 000000000000..05af39634dfd --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/__init__.pyi @@ -0,0 +1,3 @@ +__all__ = ["register_jwe_draft"] + +def register_jwe_draft(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi new file mode 100644 index 000000000000..8e6b423d1bcb --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_algorithms.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final + +from authlib.jose.rfc7516 import JWEAlgorithmWithTagAwareKeyAgreement +from authlib.jose.rfc7518 import AESAlgorithm, ECKey +from authlib.jose.rfc8037 import OKPKey + +class ECDH1PUAlgorithm(JWEAlgorithmWithTagAwareKeyAgreement): + EXTRA_HEADERS: ClassVar[Iterable[str]] + ALLOWED_KEY_CLS: tuple[type, ...] + name: str + description: str + key_size: Incomplete + aeskw: AESAlgorithm + def __init__(self, key_size=None) -> None: ... + def prepare_key(self, raw_data) -> ECKey | OKPKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def compute_shared_key(self, shared_key_e, shared_key_s): ... + def compute_fixed_info(self, headers, bit_size, tag) -> bytes: ... + def compute_derived_key(self, shared_key, fixed_info, bit_size) -> bytes: ... + def deliver_at_sender(self, sender_static_key, sender_ephemeral_key, recipient_pubkey, headers, bit_size, tag) -> bytes: ... + def deliver_at_recipient( + self, recipient_key, sender_static_pubkey, sender_ephemeral_pubkey, headers, bit_size, tag + ) -> bytes: ... + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None) -> dict[str, Incomplete]: ... + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, sender_key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None) -> bytes: ... + +JWE_DRAFT_ALG_ALGORITHMS: Final[list[ECDH1PUAlgorithm]] + +def register_jwe_alg_draft(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi new file mode 100644 index 000000000000..594739d28a22 --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptodome.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class XC20PEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: Incomplete + CEK_SIZE: Incomplete + def __init__(self, key_size) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... diff --git a/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi new file mode 100644 index 000000000000..ab85a51a5233 --- /dev/null +++ b/stubs/Authlib/authlib/jose/drafts/_jwe_enc_cryptography.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class C20PEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: Incomplete + CEK_SIZE: Incomplete + def __init__(self, key_size) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... diff --git a/stubs/Authlib/authlib/jose/errors.pyi b/stubs/Authlib/authlib/jose/errors.pyi new file mode 100644 index 000000000000..29c29a3a9861 --- /dev/null +++ b/stubs/Authlib/authlib/jose/errors.pyi @@ -0,0 +1,76 @@ +from _typeshed import Incomplete + +from authlib.common.errors import AuthlibBaseError + +class JoseError(AuthlibBaseError): ... + +class DecodeError(JoseError): + error: str + +class MissingAlgorithmError(JoseError): + error: str + +class UnsupportedAlgorithmError(JoseError): + error: str + +class BadSignatureError(JoseError): + error: str + result: Incomplete + def __init__(self, result) -> None: ... + +class InvalidHeaderParameterNameError(JoseError): + error: str + def __init__(self, name) -> None: ... + +class InvalidCritHeaderParameterNameError(JoseError): + error: str + def __init__(self, name: str) -> None: ... + +class InvalidEncryptionAlgorithmForECDH1PUWithKeyWrappingError(JoseError): + error: str + def __init__(self) -> None: ... + +class InvalidAlgorithmForMultipleRecipientsMode(JoseError): + error: str + def __init__(self, alg) -> None: ... + +class KeyMismatchError(JoseError): + error: str + description: str + +class MissingEncryptionAlgorithmError(JoseError): + error: str + description: str + +class UnsupportedEncryptionAlgorithmError(JoseError): + error: str + description: str + +class UnsupportedCompressionAlgorithmError(JoseError): + error: str + description: str + +class InvalidUseError(JoseError): + error: str + description: str + +class InvalidClaimError(JoseError): + error: str + claim_name: Incomplete + def __init__(self, claim) -> None: ... + +class MissingClaimError(JoseError): + error: str + def __init__(self, claim) -> None: ... + +class InsecureClaimError(JoseError): + error: str + def __init__(self, claim) -> None: ... + +class ExpiredTokenError(JoseError): + error: str + description: str + +class InvalidTokenError(JoseError): + error: str + description: str diff --git a/stubs/Authlib/authlib/jose/jwk.pyi b/stubs/Authlib/authlib/jose/jwk.pyi new file mode 100644 index 000000000000..4a90a1bd2e31 --- /dev/null +++ b/stubs/Authlib/authlib/jose/jwk.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +@deprecated("Please use `JsonWebKey` directly.") +def loads(obj, kid=None): ... +@deprecated("Please use `JsonWebKey` directly.") +def dumps(key, kty=None, **params) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi new file mode 100644 index 000000000000..cac2e167f330 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/__init__.pyi @@ -0,0 +1,4 @@ +from .jws import JsonWebSignature as JsonWebSignature +from .models import JWSAlgorithm as JWSAlgorithm, JWSHeader as JWSHeader, JWSObject as JWSObject + +__all__ = ["JsonWebSignature", "JWSAlgorithm", "JWSHeader", "JWSObject"] diff --git a/stubs/Authlib/authlib/jose/rfc7515/jws.pyi b/stubs/Authlib/authlib/jose/rfc7515/jws.pyi new file mode 100644 index 000000000000..0de9cb372359 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/jws.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +from .models import JWSAlgorithm, JWSObject + +class JsonWebSignature: + REGISTERED_HEADER_PARAMETER_NAMES: frozenset[str] + MAX_CONTENT_LENGTH: int + ALGORITHMS_REGISTRY: dict[str, JWSAlgorithm] + def __init__(self, algorithms=None, private_headers=None) -> None: ... + @classmethod + def register_algorithm(cls, algorithm: JWSAlgorithm) -> None: ... + def serialize_compact(self, protected, payload, key) -> bytes: ... + def deserialize_compact( + self, s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, key, decode=None + ) -> JWSObject: ... + def serialize_json(self, header_obj, payload, key) -> dict[str, Incomplete]: ... + def deserialize_json(self, obj, key, decode=None) -> JWSObject: ... + def serialize(self, header, payload, key) -> dict[str, Incomplete] | bytes: ... + def deserialize(self, s, key, decode=None) -> JWSObject: ... diff --git a/stubs/Authlib/authlib/jose/rfc7515/models.pyi b/stubs/Authlib/authlib/jose/rfc7515/models.pyi new file mode 100644 index 000000000000..77663de68e55 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7515/models.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +class JWSAlgorithm: + name: str | None + description: str | None + deprecated: bool + algorithm_type: str + algorithm_location: str + def prepare_key(self, raw_data): ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +class JWSHeader(dict[str, object]): + protected: Incomplete + header: Incomplete + def __init__(self, protected, header) -> None: ... + @classmethod + def from_dict(cls, obj) -> Self: ... + +class JWSObject(dict[str, object]): + header: Incomplete + payload: Incomplete + type: str + def __init__(self, header, payload, type: str = "compact") -> None: ... + @property + def headers(self): ... diff --git a/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi new file mode 100644 index 000000000000..84393afbd11b --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/__init__.pyi @@ -0,0 +1,9 @@ +from .jwe import JsonWebEncryption as JsonWebEncryption +from .models import ( + JWEAlgorithm as JWEAlgorithm, + JWEAlgorithmWithTagAwareKeyAgreement as JWEAlgorithmWithTagAwareKeyAgreement, + JWEEncAlgorithm as JWEEncAlgorithm, + JWEZipAlgorithm as JWEZipAlgorithm, +) + +__all__ = ["JsonWebEncryption", "JWEAlgorithm", "JWEAlgorithmWithTagAwareKeyAgreement", "JWEEncAlgorithm", "JWEZipAlgorithm"] diff --git a/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi b/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi new file mode 100644 index 000000000000..c0783698a279 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/jwe.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections import OrderedDict +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +from .models import JWEAlgorithmBase, JWEEncAlgorithm, JWEZipAlgorithm + +class JsonWebEncryption: + REGISTERED_HEADER_PARAMETER_NAMES: frozenset[str] + ALG_REGISTRY: dict[str, JWEAlgorithmBase] + ENC_REGISTRY: dict[str, JWEEncAlgorithm] + ZIP_REGISTRY: dict[str, JWEZipAlgorithm] + def __init__(self, algorithms=None, private_headers=None) -> None: ... + @classmethod + def register_algorithm(cls, algorithm: JWEAlgorithmBase | JWEEncAlgorithm | JWEZipAlgorithm) -> None: ... + def serialize_compact(self, protected, payload, key, sender_key=None) -> bytes: ... + def serialize_json(self, header_obj, payload, keys, sender_key=None) -> OrderedDict[Incomplete, Incomplete]: ... + def serialize(self, header, payload, key, sender_key=None) -> OrderedDict[Incomplete, Incomplete] | bytes: ... + def deserialize_compact( + self, + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + key, + decode=None, + sender_key=None, + ) -> dict[str, Incomplete]: ... + def deserialize_json(self, obj, key, decode=None, sender_key=None) -> dict[str, Incomplete]: ... + def deserialize(self, obj, key, decode=None, sender_key=None) -> dict[str, Incomplete]: ... + @staticmethod + def parse_json(obj) -> dict[Incomplete, Incomplete]: ... + def get_header_alg(self, header) -> JWEAlgorithmBase: ... + def get_header_enc(self, header) -> JWEEncAlgorithm: ... + def get_header_zip(self, header) -> JWEZipAlgorithm: ... + +def prepare_key(alg, header, key): ... diff --git a/stubs/Authlib/authlib/jose/rfc7516/models.pyi b/stubs/Authlib/authlib/jose/rfc7516/models.pyi new file mode 100644 index 000000000000..e40d84bf486d --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7516/models.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from abc import ABCMeta +from collections.abc import Iterable, Sized +from typing import ClassVar +from typing_extensions import Self + +class JWEAlgorithmBase(metaclass=ABCMeta): + EXTRA_HEADERS: ClassVar[Iterable[str] | None] + name: str | None + description: str | None + deprecated: bool + algorithm_type: str + algorithm_location: str + def prepare_key(self, raw_data): ... + def generate_preset(self, enc_alg, key): ... + +class JWEAlgorithm(JWEAlgorithmBase, metaclass=ABCMeta): + def wrap(self, enc_alg, headers, key, preset=None): ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class JWEAlgorithmWithTagAwareKeyAgreement(JWEAlgorithmBase, metaclass=ABCMeta): + def generate_keys_and_prepare_headers(self, enc_alg, key, sender_key, preset=None): ... + def agree_upon_key_and_wrap_cek(self, enc_alg, headers, key, sender_key, epk, cek, tag): ... + def wrap(self, enc_alg, headers, key, sender_key, preset=None): ... + def unwrap(self, enc_alg, ek, headers, key, sender_key, tag=None): ... + +class JWEEncAlgorithm: + name: str | None + description: str | None + algorithm_type: str + algorithm_location: str + IV_SIZE: int | None + CEK_SIZE: int | None + def generate_cek(self) -> bytes: ... + def generate_iv(self) -> bytes: ... + def check_iv(self, iv: Sized) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +class JWEZipAlgorithm: + name: Incomplete + description: Incomplete + algorithm_type: str + algorithm_location: str + def compress(self, s: bytes) -> bytes | None: ... + def decompress(self, s: bytes) -> bytes | None: ... + +class JWESharedHeader(dict[str, object]): + protected: Incomplete + unprotected: Incomplete + def __init__(self, protected, unprotected) -> None: ... + def update_protected(self, addition) -> None: ... + @classmethod + def from_dict(cls, obj) -> Self: ... + +class JWEHeader(dict[str, object]): + protected: Incomplete + unprotected: Incomplete + header: Incomplete + def __init__(self, protected, unprotected, header) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi new file mode 100644 index 000000000000..7a5ebe6a8eac --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/__init__.pyi @@ -0,0 +1,7 @@ +from ._cryptography_key import load_pem_key as load_pem_key +from .asymmetric_key import AsymmetricKey as AsymmetricKey +from .base_key import Key as Key +from .jwk import JsonWebKey as JsonWebKey +from .key_set import KeySet as KeySet + +__all__ = ["Key", "AsymmetricKey", "KeySet", "JsonWebKey", "load_pem_key"] diff --git a/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi new file mode 100644 index 000000000000..86a5476b8963 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/_cryptography_key.pyi @@ -0,0 +1,35 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Literal, SupportsBytes, SupportsIndex, overload + +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes, PublicKeyTypes +from cryptography.hazmat.primitives.serialization.ssh import SSHPublicKeyTypes + +@overload # if ssh_type is None +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: None = None, + key_type: str | None = None, + password: bytes | None = None, +) -> PublicKeyTypes | PrivateKeyTypes: ... +@overload # if key_type == "public" +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] | None = None, + key_type: Literal["public"] = ..., + password: bytes | None = None, +) -> PublicKeyTypes: ... +@overload # if key_type is not empty, but not "public" +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] | None = None, + key_type: str = ..., + password: bytes | None = None, +) -> PrivateKeyTypes: ... +@overload # if ssh_type is not empty +def load_pem_key( + raw: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, + ssh_type: ReadableBuffer | tuple[ReadableBuffer, ...] = ..., + key_type: str | None = None, + password: bytes | None = None, +) -> SSHPublicKeyTypes | PublicKeyTypes | PrivateKeyTypes: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi new file mode 100644 index 000000000000..1361ba23ac48 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/asymmetric_key.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import ClassVar, Literal, SupportsBytes, SupportsIndex +from typing_extensions import Self + +from authlib.jose.rfc7517 import Key + +class AsymmetricKey(Key): + PUBLIC_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_CLS: ClassVar[type | tuple[type, ...]] + PUBLIC_KEY_CLS: ClassVar[type | tuple[type, ...]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + private_key: Incomplete + public_key: Incomplete + def __init__(self, private_key=None, public_key=None, options=None) -> None: ... + @property + def public_only(self) -> bool: ... + def get_op_key(self, operation): ... + def get_public_key(self): ... + def get_private_key(self): ... + def load_raw_key(self) -> None: ... + def load_dict_key(self) -> None: ... + def dumps_private_key(self): ... + def dumps_public_key(self): ... + def load_private_key(self): ... + def load_public_key(self): ... + def as_dict(self, is_private: bool = False, **params) -> dict[Incomplete, Incomplete]: ... + def as_key(self, is_private: bool = False): ... + def as_bytes( + self, + encoding: Literal["PEM", "DER"] | None = None, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + def as_pem( + self, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + def as_der( + self, + is_private: bool = False, + password: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | None = None, + ): ... + @classmethod + def import_dict_key(cls, raw, options=None) -> Self: ... + @classmethod + def import_key(cls, raw, options=None) -> Self: ... + @classmethod + def validate_raw_key(cls, key) -> bool: ... + @classmethod + def generate_key(cls, crv_or_size, options=None, is_private: bool = False) -> AsymmetricKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi b/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi new file mode 100644 index 000000000000..0614eacf2a48 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/base_key.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from typing import ClassVar + +class Key: + kty: str + ALLOWED_PARAMS: ClassVar[list[str]] + PRIVATE_KEY_OPS: ClassVar[list[str]] + PUBLIC_KEY_OPS: ClassVar[list[str]] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + options: dict[Incomplete, Incomplete] + def __init__(self, options=None) -> None: ... + @property + def tokens(self) -> dict[Incomplete, Incomplete]: ... + @property + def kid(self): ... + def keys(self): ... + def __getitem__(self, item): ... + @property + def public_only(self): ... + def load_raw_key(self): ... + def load_dict_key(self): ... + def check_key_op(self, operation) -> None: ... + def as_dict(self, is_private: bool = False, **params): ... + def as_json(self, is_private: bool = False, **params) -> str: ... + def thumbprint(self) -> str: ... + @classmethod + def check_required_fields(cls, data) -> None: ... + @classmethod + def validate_raw_key(cls, key): ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi b/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi new file mode 100644 index 000000000000..97ca89d0c872 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/jwk.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Collection, Iterable, Mapping +from typing import SupportsBytes, SupportsIndex + +from authlib.jose.rfc7517 import Key, KeySet + +class JsonWebKey: + JWK_KEY_CLS: dict[Incomplete, Incomplete] + @classmethod + def generate_key(cls, kty, crv_or_size, options=None, is_private: bool = False): ... + @classmethod + def import_key( + cls, + raw: ( + str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer | Mapping[str, object] + ), + options: Mapping[str, object] | None = None, + ) -> Key: ... + @classmethod + def import_key_set(cls, raw: str | Collection[str] | dict[str, object]) -> KeySet: ... diff --git a/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi b/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi new file mode 100644 index 000000000000..b1538b72401d --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7517/key_set.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from authlib.jose.rfc7517 import Key + +class KeySet: + keys: Collection[Key] + def __init__(self, keys) -> None: ... + def as_dict(self, is_private: bool = False, **params) -> dict[str, list[Incomplete]]: ... + def as_json(self, is_private: bool = False, **params) -> str: ... + def find_by_kid(self, kid, **params): ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi new file mode 100644 index 000000000000..362234a1bdd7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/__init__.pyi @@ -0,0 +1,20 @@ +from .ec_key import ECKey as ECKey +from .jwe_algs import AESAlgorithm as AESAlgorithm, ECDHESAlgorithm as ECDHESAlgorithm, u32be_len_input as u32be_len_input +from .jwe_encs import CBCHS2EncAlgorithm as CBCHS2EncAlgorithm +from .oct_key import OctKey as OctKey +from .rsa_key import RSAKey as RSAKey + +__all__ = [ + "register_jws_rfc7518", + "register_jwe_rfc7518", + "OctKey", + "RSAKey", + "ECKey", + "u32be_len_input", + "AESAlgorithm", + "ECDHESAlgorithm", + "CBCHS2EncAlgorithm", +] + +def register_jws_rfc7518(cls) -> None: ... +def register_jwe_rfc7518(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi new file mode 100644 index 000000000000..ba5f1fd456e6 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/ec_key.pyi @@ -0,0 +1,24 @@ +from typing import ClassVar + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey + +class ECKey(AsymmetricKey): + kty: str + DSS_CURVES: dict[str, type] + CURVES_DSS: dict[property, str] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS # pyrefly: ignore [unknown-name] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_CLS: ClassVar[type] + PRIVATE_KEY_CLS: ClassVar[type] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def exchange_shared_key(self, pubkey): ... + @property + def curve_key_size(self): ... + def load_private_key(self) -> EllipticCurvePrivateKey: ... + def load_public_key(self) -> EllipticCurvePublicKey: ... + def dumps_private_key(self) -> dict[str, str]: ... + def dumps_public_key(self) -> dict[str, str]: ... + @classmethod + def generate_key(cls, crv: str = "P-256", options=None, is_private: bool = False) -> ECKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi new file mode 100644 index 000000000000..df9802481aa8 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_algs.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from typing import ClassVar, Final, SupportsBytes, SupportsIndex + +from authlib.jose.rfc7516 import JWEAlgorithm + +from .ec_key import ECKey +from .oct_key import OctKey +from .rsa_key import RSAKey + +class DirectAlgorithm(JWEAlgorithm): + name: str + description: str + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[Incomplete, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class RSAAlgorithm(JWEAlgorithm): + key_size: int + name: str + deprecated: bool + description: str + padding: Incomplete + def __init__(self, name: str, description: str, pad_fn) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key): ... + +class AESAlgorithm(JWEAlgorithm): + name: str + description: str + key_size: int + def __init__(self, key_size: int) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap_cek(self, cek, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +class AESGCMAlgorithm(JWEAlgorithm): + EXTRA_HEADERS: ClassVar[Iterable[str]] + name: str + description: str + key_size: int + def __init__(self, key_size: int) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +class ECDHESAlgorithm(JWEAlgorithm): + EXTRA_HEADERS: ClassVar[Iterable[str]] + ALLOWED_KEY_CLS = Incomplete + name: str + description: str + key_size: int | None + aeskw: AESAlgorithm + def __init__(self, key_size: int | None = None) -> None: ... + def prepare_key(self, raw_data) -> ECKey: ... + def generate_preset(self, enc_alg, key) -> dict[str, Incomplete]: ... + def compute_fixed_info(self, headers, bit_size) -> bytes: ... + def compute_derived_key(self, shared_key, fixed_info, bit_size) -> bytes: ... + def deliver(self, key, pubkey, headers, bit_size) -> bytes: ... + def wrap(self, enc_alg, headers, key, preset=None) -> dict[str, Incomplete]: ... + def unwrap(self, enc_alg, ek, headers, key) -> bytes: ... + +def u32be_len_input( + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, base64: bool = False +) -> bytes: ... + +JWE_ALG_ALGORITHMS: Final[list[JWEAlgorithm]] diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi new file mode 100644 index 000000000000..4fd43557af0f --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_encs.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import Final + +from authlib.jose.rfc7516 import JWEEncAlgorithm + +class CBCHS2EncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: int + key_len: int + CEK_SIZE: int + hash_alg: Incomplete + def __init__(self, key_size: int, hash_type: int | str) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +class GCMEncAlgorithm(JWEEncAlgorithm): + IV_SIZE: int + name: str + description: str + key_size: int + CEK_SIZE: int + def __init__(self, key_size: int) -> None: ... + def encrypt(self, msg, aad, iv, key) -> tuple[bytes, bytes]: ... + def decrypt(self, ciphertext, aad, iv, tag, key) -> bytes: ... + +JWE_ENC_ALGORITHMS: Final[list[CBCHS2EncAlgorithm | GCMEncAlgorithm]] diff --git a/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi b/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi new file mode 100644 index 000000000000..4bb30cd63311 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jwe_zips.pyi @@ -0,0 +1,14 @@ +from typing import Final + +from authlib.jose.rfc7516 import JWEZipAlgorithm + +GZIP_HEAD: Final[bytes] +MAX_SIZE: Final = 256000 + +class DeflateZipAlgorithm(JWEZipAlgorithm): + name: str + description: str + def compress(self, s: bytes) -> bytes: ... + def decompress(self, s: bytes) -> bytes: ... + +def register_jwe_rfc7518() -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi b/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi new file mode 100644 index 000000000000..0a7af53cdecb --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/jws_algs.pyi @@ -0,0 +1,70 @@ +import hashlib +from _typeshed import Incomplete + +from authlib.jose.rfc7515 import JWSAlgorithm +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 + +from .ec_key import ECKey +from .oct_key import OctKey +from .rsa_key import RSAKey + +class NoneAlgorithm(JWSAlgorithm): + name: str + description: str + deprecated: bool + def prepare_key(self, raw_data) -> None: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class HMACAlgorithm(JWSAlgorithm): + SHA256 = hashlib.sha256 + SHA384 = hashlib.sha384 + SHA512 = hashlib.sha512 + name: str + description: str + hash_alg: Incomplete + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> OctKey: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class RSAAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + description: str + hash_alg: Incomplete + padding: PKCS1v15 + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +class ECAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + curve: Incomplete + description: str + hash_alg: Incomplete + def __init__(self, name: str, curve, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> ECKey: ... + def sign(self, msg, key) -> bytes: ... + def verify(self, msg, sig, key) -> bool: ... + +class RSAPSSAlgorithm(JWSAlgorithm): + SHA256 = hashes.SHA256 + SHA384 = hashes.SHA384 + SHA512 = hashes.SHA512 + name: str + description: str + hash_alg: Incomplete + def __init__(self, sha_type: int | str) -> None: ... + def prepare_key(self, raw_data) -> RSAKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +JWS_ALGORITHMS: list[JWSAlgorithm] diff --git a/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi new file mode 100644 index 000000000000..d4fad5a6571c --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/oct_key.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final +from typing_extensions import Self + +from authlib.jose.rfc7517 import Key + +POSSIBLE_UNSAFE_KEYS: Final[tuple[bytes, ...]] + +class OctKey(Key): + kty: str + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + raw_key: Incomplete + def __init__(self, raw_key=None, options=None) -> None: ... + @property + def public_only(self) -> bool: ... + def get_op_key(self, operation): ... + def load_raw_key(self) -> None: ... + def load_dict_key(self) -> None: ... + def as_dict(self, is_private: bool = False, **params) -> dict[Incomplete, Incomplete]: ... + @classmethod + def validate_raw_key(cls, key) -> bool: ... + @classmethod + def import_key(cls, raw, options=None) -> Self: ... + @classmethod + def generate_key(cls, key_size: int = 256, options=None, is_private: bool = True) -> Self: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi b/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi new file mode 100644 index 000000000000..0a15f339f6f7 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/rsa_key.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from typing import ClassVar +from typing_extensions import Self + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey + +class RSAKey(AsymmetricKey): + kty: str + PUBLIC_KEY_CLS: ClassVar[type] + PRIVATE_KEY_CLS: ClassVar[type] + PUBLIC_KEY_FIELDS: ClassVar[list[str]] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def dumps_private_key(self) -> dict[str, str]: ... + def dumps_public_key(self) -> dict[str, str]: ... + def load_private_key(self) -> RSAPrivateKey: ... + def load_public_key(self) -> RSAPublicKey: ... + @classmethod + def generate_key(cls, key_size: int = 2048, options=None, is_private: bool = False) -> RSAKey: ... + @classmethod + def import_dict_key(cls, raw, options=None) -> Self: ... + +def has_all_prime_factors(obj: Iterable[str]) -> bool: ... diff --git a/stubs/Authlib/authlib/jose/rfc7518/util.pyi b/stubs/Authlib/authlib/jose/rfc7518/util.pyi new file mode 100644 index 000000000000..1edc796a9716 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7518/util.pyi @@ -0,0 +1,4 @@ +from _typeshed import ReadableBuffer + +def encode_int(num, bits) -> bytes: ... +def decode_int(b: ReadableBuffer) -> int: ... diff --git a/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi b/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi new file mode 100644 index 000000000000..bb053f7d5142 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/__init__.pyi @@ -0,0 +1,4 @@ +from .claims import BaseClaims as BaseClaims, JWTClaims as JWTClaims +from .jwt import JsonWebToken as JsonWebToken + +__all__ = ["JsonWebToken", "BaseClaims", "JWTClaims"] diff --git a/stubs/Authlib/authlib/jose/rfc7519/claims.pyi b/stubs/Authlib/authlib/jose/rfc7519/claims.pyi new file mode 100644 index 000000000000..55ec2dbf9a73 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/claims.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Any, ClassVar + +class BaseClaims(dict[str, Any]): # dict values are key-dependent + REGISTERED_CLAIMS: ClassVar[list[str]] + header: Incomplete + options: Incomplete + params: Incomplete + def __init__(self, payload, header, options=None, params=None) -> None: ... + # TODO: Adds an attribute for each key in REGISTERED_CLAIMS + def __getattr__(self, key: str): ... + def get_registered_claims(self) -> dict[str, Incomplete]: ... + +class JWTClaims(BaseClaims): + def validate(self, now: int | None = None, leeway: int = 0) -> None: ... + def validate_iss(self) -> None: ... + def validate_sub(self) -> None: ... + def validate_aud(self) -> None: ... + def validate_exp(self, now: int, leeway: int) -> None: ... + def validate_nbf(self, now: int, leeway: int) -> None: ... + def validate_iat(self, now: int, leeway: int) -> None: ... + def validate_jti(self) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi b/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi new file mode 100644 index 000000000000..b6785ca8f084 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc7519/jwt.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from re import Pattern +from typing import Any, Final, Generic, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +from ..rfc7517 import KeySet +from .claims import JWTClaims + +_T = TypeVar("_T") + +_LoadKey: TypeAlias = Callable[[Incomplete, Incomplete], Incomplete] + +class JsonWebToken: + SENSITIVE_NAMES: Final[tuple[str, ...]] + SENSITIVE_VALUES: Final[Pattern[str]] + + def __init__(self, algorithms, private_headers=None) -> None: ... + def check_sensitive_data(self, payload) -> None: ... + def encode(self, header, payload, key, check: bool = True) -> bytes: ... + + @overload + def decode( + self, + s: str | bytes, + key: _LoadKey | KeySet | tuple[Incomplete, ...] | list[Incomplete] | str, + claims_cls: None = None, + claims_options=None, + claims_params=None, + ) -> JWTClaims: ... + @overload + def decode( + self, + s: str | bytes, + key: _LoadKey | KeySet | tuple[Incomplete, ...] | list[Incomplete] | str, + claims_cls: type[_T], + claims_options=None, + claims_params=None, + ) -> _T: ... + +def decode_payload(bytes_payload) -> dict[Incomplete, Incomplete]: ... + +_TL = TypeVar("_TL", bound=tuple[Any, ...] | list[Any]) + +@type_check_only +class _Keys(TypedDict, Generic[_TL]): + keys: _TL + +@overload +def prepare_raw_key(raw: KeySet) -> KeySet: ... +@overload +def prepare_raw_key(raw: str) -> dict[str, Any] | str: ... # dict is a JSON object +@overload +def prepare_raw_key(raw: _TL) -> _Keys[_TL]: ... + +def find_encode_key(key, header): ... +def create_load_key(key: KeySet | _Keys[Incomplete] | Incomplete) -> _LoadKey: ... diff --git a/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi b/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi new file mode 100644 index 000000000000..915582d47ac5 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/__init__.pyi @@ -0,0 +1,4 @@ +from .jws_eddsa import register_jws_rfc8037 as register_jws_rfc8037 +from .okp_key import OKPKey as OKPKey + +__all__ = ["register_jws_rfc8037", "OKPKey"] diff --git a/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi b/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi new file mode 100644 index 000000000000..93bb7d3d72d0 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/jws_eddsa.pyi @@ -0,0 +1,12 @@ +from authlib.jose.rfc7515 import JWSAlgorithm + +from .okp_key import OKPKey + +class EdDSAAlgorithm(JWSAlgorithm): + name: str + description: str + def prepare_key(self, raw_data) -> OKPKey: ... + def sign(self, msg, key): ... + def verify(self, msg, sig, key) -> bool: ... + +def register_jws_rfc8037(cls) -> None: ... diff --git a/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi b/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi new file mode 100644 index 000000000000..f6a39d28e8a9 --- /dev/null +++ b/stubs/Authlib/authlib/jose/rfc8037/okp_key.pyi @@ -0,0 +1,28 @@ +from typing import ClassVar, Final + +from authlib.jose.rfc7517 import AsymmetricKey +from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey, Ed448PublicKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.asymmetric.x448 import X448PrivateKey, X448PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey + +PUBLIC_KEYS_MAP: Final[dict[str, type]] +PRIVATE_KEYS_MAP: Final[dict[str, type]] + +class OKPKey(AsymmetricKey): + kty: str + REQUIRED_JSON_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_FIELDS = REQUIRED_JSON_FIELDS # pyrefly: ignore [unknown-name] + PRIVATE_KEY_FIELDS: ClassVar[list[str]] + PUBLIC_KEY_CLS: ClassVar[tuple[type, ...]] + PRIVATE_KEY_CLS: ClassVar[tuple[type, ...]] + SSH_PUBLIC_PREFIX: ClassVar[bytes] + def exchange_shared_key(self, pubkey: X25519PrivateKey | X448PublicKey) -> bytes: ... + @staticmethod + def get_key_curve(key) -> str | None: ... + def load_private_key(self) -> Ed25519PrivateKey | Ed448PrivateKey | X25519PrivateKey | X448PrivateKey: ... + def load_public_key(self) -> Ed25519PublicKey | Ed448PublicKey | X25519PublicKey | X448PublicKey: ... + def dumps_private_key(self) -> dict[str, str | None]: ... + def dumps_public_key(self, public_key=None) -> dict[str, str | None]: ... + @classmethod + def generate_key(cls, crv: str = "Ed25519", options=None, is_private: bool = False) -> OKPKey: ... diff --git a/stubs/Authlib/authlib/jose/util.pyi b/stubs/Authlib/authlib/jose/util.pyi new file mode 100644 index 000000000000..780229067d4f --- /dev/null +++ b/stubs/Authlib/authlib/jose/util.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from authlib.common.errors import AuthlibBaseError + +def extract_header(header_segment: bytes, error_cls: AuthlibBaseError) -> dict[Incomplete, Incomplete]: ... +def extract_segment(segment: bytes, error_cls: AuthlibBaseError, name: str = "payload") -> bytes: ... +def ensure_dict(s: object, structure_name: str) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oauth1/__init__.pyi b/stubs/Authlib/authlib/oauth1/__init__.pyi new file mode 100644 index 000000000000..053e8f1d2c33 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/__init__.pyi @@ -0,0 +1,33 @@ +from .rfc5849 import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, + AuthorizationServer as AuthorizationServer, + ClientAuth as ClientAuth, + ClientMixin as ClientMixin, + OAuth1Request as OAuth1Request, + ResourceProtector as ResourceProtector, + TemporaryCredential as TemporaryCredential, + TemporaryCredentialMixin as TemporaryCredentialMixin, + TokenCredentialMixin as TokenCredentialMixin, +) + +__all__ = [ + "OAuth1Request", + "ClientAuth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "ClientMixin", + "TemporaryCredentialMixin", + "TokenCredentialMixin", + "TemporaryCredential", + "AuthorizationServer", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth1/client.pyi b/stubs/Authlib/authlib/oauth1/client.pyi new file mode 100644 index 000000000000..07b0221f9c15 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/client.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing import Any +from typing_extensions import Never + +from authlib.oauth1 import ClientAuth + +class OAuth1Client: + auth_class: type[ClientAuth] + session: Incomplete + auth: ClientAuth + def __init__( + self, + session, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method="HMAC-SHA1", + signature_type="HEADER", + force_include_body: bool = False, + realm=None, + **kwargs, + ) -> None: ... + + @property + def redirect_uri(self): ... + @redirect_uri.setter + def redirect_uri(self, uri) -> None: ... + + @property + def token(self) -> dict[Incomplete, Incomplete]: ... + @token.setter + def token(self, token) -> None: ... + + def create_authorization_url(self, url, request_token=None, **kwargs) -> str: ... + def fetch_request_token(self, url: str, **kwargs) -> dict[str, Any]: ... + def fetch_access_token(self, url, verifier=None, **kwargs): ... + def parse_authorization_response(self, url: str) -> dict[str, str]: ... + def parse_response_token(self, status_code: int, text: str): ... + @staticmethod + def handle_error(error_type: str, error_description: str) -> Never: ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth1/errors.pyi b/stubs/Authlib/authlib/oauth1/errors.pyi new file mode 100644 index 000000000000..21c42b76694a --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/errors.pyi @@ -0,0 +1 @@ +from authlib.oauth1.rfc5849.errors import * diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi new file mode 100644 index 000000000000..f6cd313f97d5 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/__init__.pyi @@ -0,0 +1,35 @@ +from .authorization_server import AuthorizationServer as AuthorizationServer +from .client_auth import ClientAuth as ClientAuth +from .models import ( + ClientMixin as ClientMixin, + TemporaryCredential as TemporaryCredential, + TemporaryCredentialMixin as TemporaryCredentialMixin, + TokenCredentialMixin as TokenCredentialMixin, +) +from .resource_protector import ResourceProtector as ResourceProtector +from .signature import ( + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_HEADER as SIGNATURE_TYPE_HEADER, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, +) +from .wrapper import OAuth1Request as OAuth1Request + +__all__ = [ + "OAuth1Request", + "ClientAuth", + "SIGNATURE_HMAC_SHA1", + "SIGNATURE_RSA_SHA1", + "SIGNATURE_PLAINTEXT", + "SIGNATURE_TYPE_HEADER", + "SIGNATURE_TYPE_QUERY", + "SIGNATURE_TYPE_BODY", + "ClientMixin", + "TemporaryCredentialMixin", + "TokenCredentialMixin", + "TemporaryCredential", + "AuthorizationServer", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi new file mode 100644 index 000000000000..e77bd50c9227 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/authorization_server.pyi @@ -0,0 +1,19 @@ +from authlib.oauth1.rfc5849.base_server import BaseServer + +class AuthorizationServer(BaseServer): + TOKEN_RESPONSE_HEADER: list[tuple[str, str]] + TEMPORARY_CREDENTIALS_METHOD: str + def create_oauth1_request(self, request): ... + def handle_response(self, status_code, payload, headers): ... + def handle_error_response(self, error): ... + def validate_temporary_credentials_request(self, request): ... + def create_temporary_credentials_response(self, request=None): ... + def validate_authorization_request(self, request): ... + def create_authorization_response(self, request, grant_user=None): ... + def validate_token_request(self, request): ... + def create_token_response(self, request): ... + def create_temporary_credential(self, request): ... + def get_temporary_credential(self, request): ... + def delete_temporary_credential(self, request): ... + def create_authorization_verifier(self, request): ... + def create_token_credential(self, request): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi new file mode 100644 index 000000000000..ac2c014e5144 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/base_server.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable + +class BaseServer: + SIGNATURE_METHODS: dict[str, Callable[..., bool]] + SUPPORTED_SIGNATURE_METHODS: list[str] + EXPIRY_TIME: int + @classmethod + def register_signature_method(cls, name: str, verify: Callable[..., bool]) -> None: ... + def validate_timestamp_and_nonce(self, request) -> None: ... + def validate_oauth_signature(self, request) -> None: ... + def get_client_by_id(self, client_id): ... + def exists_nonce(self, nonce, request) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi new file mode 100644 index 000000000000..4fc70d6c19dc --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/client_auth.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final + +CONTENT_TYPE_FORM_URLENCODED: Final = "application/x-www-form-urlencoded" +CONTENT_TYPE_MULTI_PART: Final = "multipart/form-data" + +class ClientAuth: + SIGNATURE_METHODS: dict[str, Callable[..., str]] + @classmethod + def register_signature_method(cls, name: str, sign: Callable[..., str]) -> None: ... + client_id: Incomplete + client_secret: Incomplete + token: Incomplete + token_secret: Incomplete + redirect_uri: Incomplete + signature_method: Incomplete + signature_type: Incomplete + rsa_key: Incomplete + verifier: Incomplete + realm: Incomplete + force_include_body: Incomplete + def __init__( + self, + client_id, + client_secret=None, + token=None, + token_secret=None, + redirect_uri=None, + rsa_key=None, + verifier=None, + signature_method="HMAC-SHA1", + signature_type="HEADER", + realm=None, + force_include_body: bool = False, + ) -> None: ... + def get_oauth_signature(self, method, uri, headers, body) -> str: ... + def get_oauth_params(self, nonce, timestamp) -> list[tuple[str, Incomplete]]: ... + def sign(self, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def prepare(self, method, uri, headers, body) -> tuple[Incomplete, ...]: ... + +def generate_nonce() -> str: ... +def generate_timestamp() -> str: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi new file mode 100644 index 000000000000..f6140d851d1c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/errors.pyi @@ -0,0 +1,52 @@ +from authlib.common.errors import AuthlibHTTPError + +class OAuth1Error(AuthlibHTTPError): + def __init__(self, description=None, uri=None, status_code=None) -> None: ... + def get_headers(self) -> list[tuple[str, str]]: ... + +class InsecureTransportError(OAuth1Error): + error: str + description: str + @classmethod + def check(cls, uri) -> None: ... + +class InvalidRequestError(OAuth1Error): + error: str + +class UnsupportedParameterError(OAuth1Error): + error: str + +class UnsupportedSignatureMethodError(OAuth1Error): + error: str + +class MissingRequiredParameterError(OAuth1Error): + error: str + def __init__(self, key) -> None: ... + +class DuplicatedOAuthProtocolParameterError(OAuth1Error): + error: str + +class InvalidClientError(OAuth1Error): + error: str + status_code: int + +class InvalidTokenError(OAuth1Error): + error: str + description: str + status_code: int + +class InvalidSignatureError(OAuth1Error): + error: str + status_code: int + +class InvalidNonceError(OAuth1Error): + error: str + status_code: int + +class AccessDeniedError(OAuth1Error): + error: str + description: str + +class MethodNotAllowedError(OAuth1Error): + error: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi new file mode 100644 index 000000000000..98e0cfd55d7c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/models.pyi @@ -0,0 +1,21 @@ +class ClientMixin: + def get_default_redirect_uri(self): ... + def get_client_secret(self): ... + def get_rsa_public_key(self): ... + +class TokenCredentialMixin: + def get_oauth_token(self): ... + def get_oauth_token_secret(self): ... + +class TemporaryCredentialMixin(TokenCredentialMixin): + def get_client_id(self): ... + def get_redirect_uri(self): ... + def check_verifier(self, verifier) -> bool: ... + +class TemporaryCredential(dict[str, object], TemporaryCredentialMixin): + def get_client_id(self): ... + def get_user_id(self): ... + def get_redirect_uri(self): ... + def check_verifier(self, verifier) -> bool: ... + def get_oauth_token(self): ... + def get_oauth_token_secret(self): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi new file mode 100644 index 000000000000..543a091de424 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/parameters.pyi @@ -0,0 +1,3 @@ +def prepare_headers(oauth_params, headers=None, realm=None): ... +def prepare_form_encoded_body(oauth_params, body) -> str: ... +def prepare_request_uri_query(oauth_params, uri): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi new file mode 100644 index 000000000000..45f147d4d80c --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/resource_protector.pyi @@ -0,0 +1,7 @@ +from authlib.oauth1.rfc5849.base_server import BaseServer + +from .wrapper import OAuth1Request + +class ResourceProtector(BaseServer): + def validate_request(self, method, uri, body, headers) -> OAuth1Request: ... + def get_token_credential(self, request): ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi new file mode 100644 index 000000000000..8e650fbd9cc9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/rsa.pyi @@ -0,0 +1,2 @@ +def sign_sha1(msg, rsa_private_key): ... +def verify_sha1(sig, msg, rsa_public_key) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi new file mode 100644 index 000000000000..1fb8119798cc --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/signature.pyi @@ -0,0 +1,22 @@ +from typing import Final + +SIGNATURE_HMAC_SHA1: Final = "HMAC-SHA1" +SIGNATURE_RSA_SHA1: Final = "RSA-SHA1" +SIGNATURE_PLAINTEXT: Final = "PLAINTEXT" +SIGNATURE_TYPE_HEADER: Final = "HEADER" +SIGNATURE_TYPE_QUERY: Final = "QUERY" +SIGNATURE_TYPE_BODY: Final = "BODY" + +def construct_base_string(method, uri, params, host=None) -> str: ... +def normalize_base_string_uri(uri, host=None): ... +def normalize_parameters(params) -> str: ... +def generate_signature_base_string(request) -> str: ... +def hmac_sha1_signature(base_string, client_secret, token_secret) -> str: ... +def rsa_sha1_signature(base_string, rsa_private_key) -> str: ... +def plaintext_signature(client_secret, token_secret) -> str: ... +def sign_hmac_sha1(client, request) -> str: ... +def sign_rsa_sha1(client, request) -> str: ... +def sign_plaintext(client, request) -> str: ... +def verify_hmac_sha1(request) -> bool: ... +def verify_rsa_sha1(request) -> bool: ... +def verify_plaintext(request) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi new file mode 100644 index 000000000000..a7e79606ff55 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/util.pyi @@ -0,0 +1,2 @@ +def escape(s) -> str: ... +def unescape(s: str | bytes) -> str: ... diff --git a/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi b/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi new file mode 100644 index 000000000000..973e82fc0bf9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth1/rfc5849/wrapper.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete + +class OAuth1Request: + method: Incomplete + uri: Incomplete + body: Incomplete + headers: Incomplete + client: Incomplete | None + credential: Incomplete | None + user: Incomplete | None + query: Incomplete + query_params: Incomplete + body_params: Incomplete + auth_params: Incomplete + realm: Incomplete + signature_type: str | None + oauth_params: Incomplete + params: list[Incomplete] + def __init__(self, method, uri, body=None, headers=None) -> None: ... + @property + def client_id(self): ... + @property + def client_secret(self): ... + @property + def rsa_public_key(self): ... + @property + def timestamp(self): ... + @property + def redirect_uri(self): ... + @property + def signature(self): ... + @property + def signature_method(self): ... + @property + def token(self): ... + @property + def token_secret(self): ... diff --git a/stubs/Authlib/authlib/oauth2/__init__.pyi b/stubs/Authlib/authlib/oauth2/__init__.pyi new file mode 100644 index 000000000000..716ca9309f0c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/__init__.pyi @@ -0,0 +1,22 @@ +from .auth import ClientAuth as ClientAuth, TokenAuth as TokenAuth +from .base import OAuth2Error as OAuth2Error +from .client import OAuth2Client as OAuth2Client +from .rfc6749 import ( + AuthorizationServer as AuthorizationServer, + ClientAuthentication as ClientAuthentication, + JsonRequest as JsonRequest, + OAuth2Request as OAuth2Request, + ResourceProtector as ResourceProtector, +) + +__all__ = [ + "OAuth2Error", + "ClientAuth", + "TokenAuth", + "OAuth2Client", + "OAuth2Request", + "JsonRequest", + "AuthorizationServer", + "ClientAuthentication", + "ResourceProtector", +] diff --git a/stubs/Authlib/authlib/oauth2/auth.pyi b/stubs/Authlib/authlib/oauth2/auth.pyi new file mode 100644 index 000000000000..5be0ac7fc0f6 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/auth.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +def encode_client_secret_basic(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def encode_client_secret_post(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, str]: ... +def encode_none(client, method, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +class ClientAuth: + DEFAULT_AUTH_METHODS: dict[str, Incomplete] + client_id: Incomplete + client_secret: Incomplete + auth_method: Incomplete + def __init__(self, client_id, client_secret, auth_method=None) -> None: ... + def prepare(self, method, uri, headers, body): ... + +class TokenAuth: + DEFAULT_TOKEN_TYPE: str + SIGN_METHODS: dict[str, Incomplete] + token: Incomplete + token_placement: str + client: Incomplete | None + hooks: set[Incomplete] + def __init__(self, token, token_placement: str = "header", client=None) -> None: ... + def set_token(self, token) -> None: ... + def prepare(self, uri, headers, body) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/base.pyi b/stubs/Authlib/authlib/oauth2/base.pyi new file mode 100644 index 000000000000..91181720ef60 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/base.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from typing import Literal + +from authlib.common.errors import AuthlibHTTPError + +def invalid_error_characters(text: str) -> list[str]: ... + +class OAuth2Error(AuthlibHTTPError): + state: Incomplete + redirect_uri: Incomplete + redirect_fragment: Incomplete + def __init__( + self, + description: str | None = None, + uri=None, + status_code=None, + state=None, + redirect_uri=None, + redirect_fragment: bool = False, + error=None, + ) -> None: ... + def get_body(self) -> list[tuple[Literal["error", "error_description", "error_uri"], str | None]]: ... + def __call__(self, uri: str | None = None): ... diff --git a/stubs/Authlib/authlib/oauth2/claims.pyi b/stubs/Authlib/authlib/oauth2/claims.pyi new file mode 100644 index 000000000000..899113298ca0 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/claims.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import TypedDict + +class ClaimsOption(TypedDict, total=False): + essential: bool + allow_blank: bool | None + value: str | int | bool + values: list[str | int | bool] | list[str] | list[int] | list[bool] + validate: Callable[[BaseClaims, Incomplete], bool] + +class BaseClaims(dict[str, Incomplete]): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + header: dict[str, Incomplete] + options: dict[str, ClaimsOption] + params: dict[str, Incomplete] + def __init__( + self, + claims: dict[str, Incomplete], + header: dict[str, Incomplete], + options: dict[str, ClaimsOption] | None = None, + params: dict[str, Incomplete] | None = None, + ) -> None: ... + def get_registered_claims(self) -> dict[str, Incomplete]: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + +class JWTClaims(BaseClaims): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/client.pyi b/stubs/Authlib/authlib/oauth2/client.pyi new file mode 100644 index 000000000000..ec4028af4372 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/client.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import ClientAuth, OAuth2Error, TokenAuth + +DEFAULT_HEADERS: Incomplete + +class OAuth2Client: + client_auth_class = ClientAuth + token_auth_class = TokenAuth + oauth_error_class = OAuth2Error + EXTRA_AUTHORIZE_PARAMS: tuple[str, ...] + SESSION_REQUEST_PARAMS: list[str] + session: Incomplete + client_id: Incomplete + client_secret: Incomplete + state: Incomplete + token_endpoint_auth_method: Incomplete + revocation_endpoint_auth_method: Incomplete + scope: Incomplete + redirect_uri: Incomplete + code_challenge_method: Incomplete + token_auth: Incomplete + update_token: Incomplete + metadata: dict[str, Incomplete] + compliance_hook: dict[str, set[Incomplete]] + leeway: int + def __init__( + self, + session, + client_id=None, + client_secret=None, + token_endpoint_auth_method=None, + revocation_endpoint_auth_method=None, + scope=None, + state=None, + redirect_uri=None, + code_challenge_method=None, + token=None, + token_placement: str = "header", + update_token=None, + leeway: int = 60, + *, + token_updater=None, + response_type=None, + grant_type: str | None = None, + token_endpoint=None, + **metadata, + ) -> None: ... + def register_client_auth_method(self, auth) -> None: ... + def client_auth(self, auth_method) -> ClientAuth: ... + + @property + def token(self): ... + @token.setter + def token(self, token) -> None: ... + + def create_authorization_url(self, url, state=None, code_verifier=None, **kwargs) -> tuple[str, Incomplete]: ... + def fetch_token( + self, url=None, body: str = "", method: str = "POST", headers=None, auth=None, grant_type=None, state=None, **kwargs + ): ... + def token_from_fragment(self, authorization_response, state=None) -> dict[Incomplete, Incomplete]: ... + def refresh_token(self, url=None, refresh_token=None, body: str = "", auth=None, headers=None, **kwargs): ... + def ensure_active_token(self, token=None): ... + def revoke_token(self, url, token=None, token_type_hint=None, body=None, auth=None, headers=None, **kwargs): ... + def introspect_token( + self, + url: str, + token: str | None = None, + token_type_hint: str | None = None, + body: str | None = None, + auth=None, + headers=None, + **kwargs, + ): ... + def register_compliance_hook(self, hook_type, hook) -> None: ... + def parse_response_token(self, resp): ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi new file mode 100644 index 000000000000..378c042e688b --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi @@ -0,0 +1,86 @@ +from .authenticate_client import ClientAuthentication as ClientAuthentication +from .authorization_server import AuthorizationServer as AuthorizationServer +from .endpoint import Endpoint, EndpointRequest +from .errors import ( + AccessDeniedError as AccessDeniedError, + InsecureTransportError as InsecureTransportError, + InvalidClientError as InvalidClientError, + InvalidGrantError as InvalidGrantError, + InvalidRequestError as InvalidRequestError, + InvalidScopeError as InvalidScopeError, + MismatchingStateException as MismatchingStateException, + MissingAuthorizationError as MissingAuthorizationError, + MissingCodeException as MissingCodeException, + MissingTokenException as MissingTokenException, + MissingTokenTypeException as MissingTokenTypeException, + OAuth2Error as OAuth2Error, + UnauthorizedClientError as UnauthorizedClientError, + UnsupportedGrantTypeError as UnsupportedGrantTypeError, + UnsupportedResponseTypeError as UnsupportedResponseTypeError, + UnsupportedTokenTypeError as UnsupportedTokenTypeError, +) +from .grants import ( + AuthorizationCodeGrant as AuthorizationCodeGrant, + AuthorizationEndpointMixin as AuthorizationEndpointMixin, + BaseGrant as BaseGrant, + ClientCredentialsGrant as ClientCredentialsGrant, + ImplicitGrant as ImplicitGrant, + RefreshTokenGrant as RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant, + TokenEndpointMixin as TokenEndpointMixin, +) +from .models import AuthorizationCodeMixin as AuthorizationCodeMixin, ClientMixin as ClientMixin, TokenMixin as TokenMixin +from .requests import ( + JsonPayload as JsonPayload, + JsonRequest as JsonRequest, + OAuth2Payload as OAuth2Payload, + OAuth2Request as OAuth2Request, +) +from .resource_protector import ResourceProtector as ResourceProtector, TokenValidator as TokenValidator +from .token_endpoint import TokenEndpoint as TokenEndpoint +from .util import list_to_scope as list_to_scope, scope_to_list as scope_to_list +from .wrappers import OAuth2Token as OAuth2Token + +__all__ = [ + "OAuth2Payload", + "OAuth2Token", + "OAuth2Request", + "JsonPayload", + "JsonRequest", + "OAuth2Error", + "AccessDeniedError", + "MissingAuthorizationError", + "InvalidGrantError", + "InvalidClientError", + "InvalidRequestError", + "InvalidScopeError", + "InsecureTransportError", + "UnauthorizedClientError", + "UnsupportedResponseTypeError", + "UnsupportedGrantTypeError", + "UnsupportedTokenTypeError", + "MissingCodeException", + "MissingTokenException", + "MissingTokenTypeException", + "MismatchingStateException", + "ClientMixin", + "AuthorizationCodeMixin", + "TokenMixin", + "ClientAuthentication", + "AuthorizationServer", + "ResourceProtector", + "TokenValidator", + "Endpoint", + "EndpointRequest", + "TokenEndpoint", + "BaseGrant", + "AuthorizationEndpointMixin", + "TokenEndpointMixin", + "AuthorizationCodeGrant", + "ImplicitGrant", + "ResourceOwnerPasswordCredentialsGrant", + "ClientCredentialsGrant", + "RefreshTokenGrant", + "scope_to_list", + "list_to_scope", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi new file mode 100644 index 000000000000..01af6828efd2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/authenticate_client.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable, Collection + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import ClientMixin + +__all__ = ["ClientAuthentication"] + +class ClientAuthentication: + query_client: Callable[[str], ClientMixin] + def __init__(self, query_client: Callable[[str], ClientMixin]) -> None: ... + def register(self, method: str, func: Callable[[Callable[[str], ClientMixin], OAuth2Request], ClientMixin]) -> None: ... + def authenticate(self, request: OAuth2Request, methods: Collection[str], endpoint: str) -> ClientMixin: ... + def __call__(self, request: OAuth2Request, methods: Collection[str], endpoint: str = "token") -> ClientMixin: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi new file mode 100644 index 000000000000..932bec1278f1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi @@ -0,0 +1,55 @@ +from collections.abc import Callable, Collection, Mapping +from typing import TypeAlias, overload +from typing_extensions import deprecated + +from authlib.oauth2 import JsonRequest, OAuth2Error, OAuth2Request +from authlib.oauth2.rfc6749 import BaseGrant, ClientMixin +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +from .endpoint import Endpoint, EndpointRequest +from .hooks import Hookable + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +class AuthorizationServer(Hookable): + scopes_supported: Collection[str] | None + def __init__(self, scopes_supported: Collection[str] | None = None) -> None: ... + def query_client(self, client_id: str) -> ClientMixin: ... + def save_token(self, token: dict[str, str | int], request: OAuth2Request) -> None: ... + def generate_token( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def register_token_generator(self, grant_type: str, func: BearerTokenGenerator) -> None: ... + def authenticate_client(self, request: OAuth2Request, methods: Collection[str], endpoint: str = "token") -> ClientMixin: ... + def register_client_auth_method(self, method, func) -> None: ... + def register_extension(self, extension) -> None: ... + def get_error_uri(self, request, error): ... + def send_signal(self, name, *args: object, **kwargs: object) -> None: ... + def create_oauth2_request(self, request) -> OAuth2Request: ... + def create_json_request(self, request) -> JsonRequest: ... + def handle_response(self, status: int, body: Mapping[str, object], headers: Mapping[str, str]) -> object: ... + def validate_requested_scope(self, scope: str) -> None: ... + def register_grant( + self, grant_cls: type[BaseGrant], extensions: Collection[Callable[[BaseGrant], None]] | None = None + ) -> None: ... + def register_endpoint(self, endpoint: type[Endpoint] | Endpoint) -> None: ... + def get_authorization_grant(self, request: OAuth2Request) -> BaseGrant: ... + def get_consent_grant(self, request=None, end_user=None): ... + def get_token_grant(self, request: OAuth2Request) -> BaseGrant: ... + def validate_endpoint_request(self, name, request=None) -> EndpointRequest: ... + def create_endpoint_response(self, name, request=None): ... + + @overload + @deprecated("The 'grant' parameter will become mandatory.") + def create_authorization_response(self, request=None, grant_user=None) -> object: ... + @overload + def create_authorization_response(self, request=None, grant_user=None, grant=None) -> object: ... + + def create_token_response(self, request=None) -> _ServerResponse: ... + def handle_error_response(self, request: OAuth2Request, error: OAuth2Error) -> object: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi new file mode 100644 index 000000000000..6fb13da985f7 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from .requests import OAuth2Request + +@dataclass +class EndpointRequest: + request: OAuth2Request + client: Incomplete | None = None + +class Endpoint: + ENDPOINT_NAME: str | None + server: Incomplete + def __init__(self, server=None) -> None: ... + def create_endpoint_request(self, request): ... + def validate_request(self, request: OAuth2Request) -> EndpointRequest: ... + def create_response(self, validated_request: EndpointRequest) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def create_endpoint_response(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def __call__(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi new file mode 100644 index 000000000000..8436b28f2c11 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/errors.pyi @@ -0,0 +1,102 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error as OAuth2Error + +__all__ = [ + "OAuth2Error", + "InsecureTransportError", + "InvalidRequestError", + "InvalidClientError", + "UnauthorizedClientError", + "InvalidGrantError", + "UnsupportedResponseTypeError", + "UnsupportedGrantTypeError", + "InvalidScopeError", + "AccessDeniedError", + "MissingAuthorizationError", + "UnsupportedTokenTypeError", + "MissingCodeException", + "MissingTokenException", + "MissingTokenTypeException", + "MismatchingStateException", +] + +class InsecureTransportError(OAuth2Error): + error: str + description: str + @classmethod + def check(cls, uri) -> None: ... + +class InvalidRequestError(OAuth2Error): + error: str + +class InvalidClientError(OAuth2Error): + error: str + status_code: int + def get_headers(self): ... + +class InvalidGrantError(OAuth2Error): + error: str + +class UnauthorizedClientError(OAuth2Error): + error: str + +class UnsupportedResponseTypeError(OAuth2Error): + error: str + response_type: Incomplete + def __init__( + self, + response_type, + description=None, + uri=None, + status_code=None, + state=None, + redirect_uri=None, + redirect_fragment: bool = False, + error=None, + ) -> None: ... + def get_error_description(self): ... + +class UnsupportedGrantTypeError(OAuth2Error): + error: str + grant_type: Incomplete + def __init__(self, grant_type) -> None: ... + def get_error_description(self): ... + +class InvalidScopeError(OAuth2Error): + error: str + description: str + +class AccessDeniedError(OAuth2Error): + error: str + description: str + +class ForbiddenError(OAuth2Error): + status_code: int + auth_type: Incomplete + realm: Incomplete + def __init__(self, auth_type=None, realm=None) -> None: ... + def get_headers(self): ... + +class MissingAuthorizationError(ForbiddenError): + error: str + description: str + +class UnsupportedTokenTypeError(ForbiddenError): + error: str + +class MissingCodeException(OAuth2Error): + error: str + description: str + +class MissingTokenException(OAuth2Error): + error: str + description: str + +class MissingTokenTypeException(OAuth2Error): + error: str + description: str + +class MismatchingStateException(OAuth2Error): + error: str + description: str diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi new file mode 100644 index 000000000000..b0300118a192 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/__init__.pyi @@ -0,0 +1,21 @@ +from .authorization_code import AuthorizationCodeGrant as AuthorizationCodeGrant +from .base import ( + AuthorizationEndpointMixin as AuthorizationEndpointMixin, + BaseGrant as BaseGrant, + TokenEndpointMixin as TokenEndpointMixin, +) +from .client_credentials import ClientCredentialsGrant as ClientCredentialsGrant +from .implicit import ImplicitGrant as ImplicitGrant +from .refresh_token import RefreshTokenGrant as RefreshTokenGrant +from .resource_owner_password_credentials import ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant + +__all__ = [ + "BaseGrant", + "AuthorizationEndpointMixin", + "TokenEndpointMixin", + "AuthorizationCodeGrant", + "ImplicitGrant", + "ResourceOwnerPasswordCredentialsGrant", + "ClientCredentialsGrant", + "RefreshTokenGrant", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi new file mode 100644 index 000000000000..1ee7e57abbb9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/authorization_code.pyi @@ -0,0 +1,27 @@ +from collections.abc import Collection +from logging import Logger +from typing import TypeAlias + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import AuthorizationEndpointMixin, BaseGrant, ClientMixin, TokenEndpointMixin + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +log: Logger + +class AuthorizationCodeGrant(BaseGrant, AuthorizationEndpointMixin, TokenEndpointMixin): + TOKEN_ENDPOINT_AUTH_METHODS: Collection[str] + AUTHORIZATION_CODE_LENGTH: int + RESPONSE_TYPES: Collection[str] + GRANT_TYPE: str + def validate_authorization_request(self) -> str: ... + def create_authorization_response(self, redirect_uri: str, grant_user) -> _ServerResponse: ... + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + def generate_authorization_code(self) -> str: ... + def save_authorization_code(self, code: str, request: OAuth2Request): ... + def query_authorization_code(self, code: str, client: ClientMixin): ... + def delete_authorization_code(self, authorization_code): ... + def authenticate_user(self, authorization_code): ... + +def validate_code_authorization_request(grant: AuthorizationCodeGrant) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi new file mode 100644 index 000000000000..82cd47e1c2d3 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/base.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from collections.abc import Collection +from typing import TypeAlias + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import ClientMixin + +from ..hooks import Hookable + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +class BaseGrant(Hookable): + TOKEN_ENDPOINT_AUTH_METHODS: Collection[str] + GRANT_TYPE: str | None + TOKEN_RESPONSE_HEADER: Collection[tuple[str, str]] + prompt: Incomplete + redirect_uri: Incomplete + request: OAuth2Request + server: Incomplete + def __init__(self, request: OAuth2Request, server) -> None: ... + @property + def client(self): ... + def generate_token( + self, + user=None, + scope: str | None = None, + grant_type: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def authenticate_token_endpoint_client(self) -> ClientMixin: ... + def save_token(self, token): ... + def validate_requested_scope(self) -> None: ... + +class TokenEndpointMixin: + TOKEN_ENDPOINT_HTTP_METHODS: Incomplete + GRANT_TYPE: Incomplete + @classmethod + def check_token_endpoint(cls, request: OAuth2Request) -> bool: ... + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + +class AuthorizationEndpointMixin: + RESPONSE_TYPES: Collection[str] + ERROR_RESPONSE_FRAGMENT: bool + @classmethod + def check_authorization_endpoint(cls, request: OAuth2Request) -> bool: ... + @staticmethod + def validate_authorization_redirect_uri(request: OAuth2Request, client: ClientMixin) -> str: ... + @staticmethod + def validate_no_multiple_request_parameter(request: OAuth2Request): ... + redirect_uri: str + def validate_consent_request(self) -> str: ... + def validate_authorization_request(self) -> str: ... + def create_authorization_response(self, redirect_uri: str, grant_user) -> _ServerResponse: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi new file mode 100644 index 000000000000..39a26a843f82 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/client_credentials.pyi @@ -0,0 +1,10 @@ +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger + +class ClientCredentialsGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + def validate_token_request(self) -> None: ... + def create_token_response(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi new file mode 100644 index 000000000000..69b1946356d2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/implicit.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import AuthorizationEndpointMixin, BaseGrant + +log: Logger + +class ImplicitGrant(BaseGrant, AuthorizationEndpointMixin): + AUTHORIZATION_ENDPOINT: bool + TOKEN_ENDPOINT_AUTH_METHODS: Incomplete + RESPONSE_TYPES: Incomplete + GRANT_TYPE: str + ERROR_RESPONSE_FRAGMENT: bool + def validate_authorization_request(self): ... + def create_authorization_response(self, redirect_uri, grant_user): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi new file mode 100644 index 000000000000..670fc27460b8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/refresh_token.pyi @@ -0,0 +1,18 @@ +from logging import Logger +from typing import TypeAlias + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin, TokenMixin + +_ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] + +log: Logger + +class RefreshTokenGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + INCLUDE_NEW_REFRESH_TOKEN: bool + def validate_token_request(self) -> None: ... + def create_token_response(self) -> _ServerResponse: ... + def issue_token(self, user, refresh_token: TokenMixin) -> dict[str, str | int]: ... + def authenticate_refresh_token(self, refresh_token: str) -> TokenMixin: ... + def authenticate_user(self, refresh_token): ... + def revoke_old_credential(self, refresh_token: TokenMixin) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi new file mode 100644 index 000000000000..13037ed8d2f6 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/grants/resource_owner_password_credentials.pyi @@ -0,0 +1,11 @@ +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger + +class ResourceOwnerPasswordCredentialsGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE: str + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def authenticate_user(self, username, password): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi new file mode 100644 index 000000000000..78aa94a7a20d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/hooks.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable + +class Hookable: + def __init__(self) -> None: ... + def register_hook(self, hook_type: str, hook: Callable[..., None]) -> None: ... + def execute_hook(self, hook_type: str, *args, **kwargs) -> None: ... + +def hooked(func=None, before: str | None = None, after: str | None = None): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi new file mode 100644 index 000000000000..47c8ed0ebcfc --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/models.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection + +class ClientMixin: + def get_client_id(self) -> str: ... + def get_default_redirect_uri(self) -> str: ... + def get_allowed_scope(self, scope: Collection[str] | str) -> str: ... + def check_redirect_uri(self, redirect_uri: str) -> bool: ... + def check_client_secret(self, client_secret: str) -> bool: ... + def check_endpoint_auth_method(self, method: str, endpoint: str) -> bool: ... + def check_response_type(self, response_type: str) -> bool: ... + def check_grant_type(self, grant_type: str) -> bool: ... + +class AuthorizationCodeMixin: + def get_redirect_uri(self) -> str: ... + def get_scope(self) -> str: ... + +class TokenMixin: + def check_client(self, client) -> bool: ... + def get_scope(self) -> str: ... + def get_expires_in(self) -> int: ... + def is_expired(self) -> bool: ... + def is_revoked(self) -> bool: ... + def get_user(self): ... + def get_client(self) -> ClientMixin: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi new file mode 100644 index 000000000000..615c0493b77b --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/parameters.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): ... +def prepare_token_request(grant_type, body: str = "", redirect_uri=None, **kwargs) -> str: ... +def parse_authorization_code_response(uri, state=None) -> dict[Incomplete, Incomplete]: ... +def parse_implicit_response(uri, state=None) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi new file mode 100644 index 000000000000..37cafb6b54c9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi @@ -0,0 +1,98 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import overload +from typing_extensions import deprecated + +from authlib.oauth2.rfc6749 import ClientMixin + +class OAuth2Payload: + @property + def data(self) -> dict[str, str]: ... + @property + def datalist(self) -> dict[str, list[Incomplete]]: ... + @property + def client_id(self) -> str: ... + @property + def response_type(self) -> str: ... + @property + def grant_type(self) -> str: ... + @property + def redirect_uri(self) -> str: ... + @property + def scope(self) -> str: ... + @property + def state(self) -> str | None: ... + +class BasicOAuth2Payload(OAuth2Payload): + def __init__(self, payload: dict[str, str]) -> None: ... + @property + def data(self) -> dict[str, str]: ... + @property + def datalist(self) -> dict[str, list[Incomplete]]: ... + +class OAuth2Request(OAuth2Payload): + method: str + uri: str + headers: Mapping[str, str] | None + payload: OAuth2Payload | None + client: ClientMixin | None + auth_method: str | None + user: Incomplete | None + authorization_code: Incomplete | None + refresh_token: Incomplete | None + credential: Incomplete | None + + @overload + def __init__(self, method: str, uri: str, body: None = None, headers: Mapping[str, str] | None = None) -> None: ... + @overload + @deprecated("The `body` parameter in OAuth2Request is deprecated. Use the payload system instead.") + def __init__(self, method: str, uri: str, body, headers: Mapping[str, str] | None = None) -> None: ... + + @property + def args(self) -> dict[str, str | None]: ... + @property + def form(self) -> dict[str, str]: ... + @property + @deprecated("'request.data' is deprecated in favor of 'request.payload.data'") + def data(self) -> dict[str, str]: ... + @property + @deprecated("'request.datalist' is deprecated in favor of 'request.payload.datalist'") + def datalist(self) -> dict[str, list[Incomplete]]: ... + @property + @deprecated("'request.client_id' is deprecated in favor of 'request.payload.client_id'") + def client_id(self) -> str: ... + @property + @deprecated("'request.response_type' is deprecated in favor of 'request.payload.response_type'") + def response_type(self) -> str: ... + @property + @deprecated("'request.grant_type' is deprecated in favor of 'request.payload.grant_type'") + def grant_type(self) -> str: ... + @property + @deprecated("'request.redirect_uri' is deprecated in favor of 'request.payload.redirect_uri'") + def redirect_uri(self) -> str: ... + + @property + def scope(self) -> str: ... + @scope.setter + def scope(self, value: str) -> None: ... + + @property + @deprecated("'request.state' is deprecated in favor of 'request.payload.state'") + def state(self) -> str | None: ... + @property + @deprecated("'request.body' is deprecated. Use the payload system instead.") + def body(self): ... + +class JsonPayload: + @property + def data(self): ... + +class JsonRequest: + method: str + uri: str + payload: JsonPayload | None + headers: Mapping[str, str] + def __init__(self, method: str, uri: str, headers: Mapping[str, str] | None = None) -> None: ... + @property + @deprecated("'request.data' is deprecated in favor of 'request.payload.data'") + def data(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi new file mode 100644 index 000000000000..930a52fcc21f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/resource_protector.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +class TokenValidator: + TOKEN_TYPE: str + realm: Incomplete + extra_attributes: Incomplete + def __init__(self, realm=None, **extra_attributes) -> None: ... + @staticmethod + def scope_insufficient(token_scopes, required_scopes): ... + def authenticate_token(self, token_string): ... + def validate_request(self, request) -> None: ... + def validate_token(self, token, scopes, request) -> None: ... + +class ResourceProtector: + def __init__(self) -> None: ... + def register_token_validator(self, validator: TokenValidator): ... + def get_token_validator(self, token_type): ... + def parse_request_authorization(self, request): ... + def validate_request(self, scopes, request, **kwargs): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi new file mode 100644 index 000000000000..579acec4ab20 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from .endpoint import Endpoint + +class TokenEndpoint(Endpoint): + ENDPOINT_NAME: str | None + SUPPORTED_TOKEN_TYPES: Incomplete + CLIENT_AUTH_METHODS: Incomplete + def authenticate_endpoint_client(self, request): ... + def authenticate_token(self, request, client): ... + def create_endpoint_response(self, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi new file mode 100644 index 000000000000..89ba8a33c9b1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/util.pyi @@ -0,0 +1,5 @@ +from collections.abc import Collection + +def list_to_scope(scope: Collection[str] | str | None) -> str: ... +def scope_to_list(scope: Collection[str] | str | None) -> list[str]: ... +def extract_basic_authorization(headers: dict[str, str]) -> tuple[str, str]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi b/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi new file mode 100644 index 000000000000..ab80ddf1a775 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6749/wrappers.pyi @@ -0,0 +1,5 @@ +class OAuth2Token(dict[str, object]): + def __init__(self, params) -> None: ... + def is_expired(self, leeway: int = 60) -> bool | None: ... + @classmethod + def from_dict(cls, token): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi new file mode 100644 index 000000000000..5c9b3d97670c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/__init__.pyi @@ -0,0 +1,15 @@ +from .errors import InsufficientScopeError as InsufficientScopeError, InvalidTokenError as InvalidTokenError +from .parameters import add_bearer_token as add_bearer_token +from .token import BearerTokenGenerator as BearerTokenGenerator +from .validator import BearerTokenValidator as BearerTokenValidator + +__all__ = [ + "InvalidTokenError", + "InsufficientScopeError", + "add_bearer_token", + "BearerToken", + "BearerTokenGenerator", + "BearerTokenValidator", +] + +BearerToken = BearerTokenGenerator diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi new file mode 100644 index 000000000000..4f1576dd0ac4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error + +__all__ = ["InvalidTokenError", "InsufficientScopeError"] + +class InvalidTokenError(OAuth2Error): + error: str + description: str + status_code: int + realm: Incomplete + extra_attributes: dict[str, Incomplete] + def __init__( + self, + description=None, + uri=None, + status_code=None, + state=None, + realm=None, + extra_attributes: dict[str, Incomplete] | None = None, + ) -> None: ... + def get_headers(self) -> list[tuple[str, str]]: ... + +class InsufficientScopeError(OAuth2Error): + error: str + description: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi new file mode 100644 index 000000000000..00d3365808ff --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/parameters.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +def add_to_uri(token, uri) -> str: ... +def add_to_headers(token, headers=None): ... +def add_to_body(token, body=None) -> str: ... +def add_bearer_token(token, uri, headers, body, placement: str = "header") -> tuple[Incomplete, Incomplete, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi new file mode 100644 index 000000000000..bd521552611f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/token.pyi @@ -0,0 +1,41 @@ +from collections.abc import Callable +from typing import Protocol, type_check_only + +from authlib.oauth2.rfc6749 import ClientMixin + +@type_check_only +class _TokenGenerator(Protocol): + def __call__(self, *, client: ClientMixin, grant_type: str, user, scope: str) -> str: ... + +class BearerTokenGenerator: + DEFAULT_EXPIRES_IN: int + GRANT_TYPES_EXPIRES_IN: dict[str, int] + access_token_generator: _TokenGenerator + refresh_token_generator: _TokenGenerator + expires_generator: Callable[[ClientMixin, str], int] + def __init__( + self, + access_token_generator: _TokenGenerator, + refresh_token_generator: _TokenGenerator | None = None, + expires_generator: Callable[[ClientMixin, str], int] | None = None, + ) -> None: ... + @staticmethod + def get_allowed_scope(client: ClientMixin, scope: str) -> str: ... + def generate( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... + def __call__( + self, + grant_type: str, + client: ClientMixin, + user=None, + scope: str | None = None, + expires_in: int | None = None, + include_refresh_token: bool = True, + ) -> dict[str, str | int]: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi b/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi new file mode 100644 index 000000000000..87adfb5a67e8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc6750/validator.pyi @@ -0,0 +1,6 @@ +from authlib.oauth2.rfc6749 import TokenValidator + +class BearerTokenValidator(TokenValidator): + TOKEN_TYPE: str + def authenticate_token(self, token_string): ... + def validate_token(self, token, scopes, request) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi new file mode 100644 index 000000000000..845277693e1f --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/__init__.pyi @@ -0,0 +1,4 @@ +from .parameters import prepare_revoke_token_request as prepare_revoke_token_request +from .revocation import RevocationEndpoint as RevocationEndpoint + +__all__ = ["prepare_revoke_token_request", "RevocationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi new file mode 100644 index 000000000000..4b3804813015 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/parameters.pyi @@ -0,0 +1 @@ +def prepare_revoke_token_request(token, token_type_hint=None, body=None, headers=None): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi b/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi new file mode 100644 index 000000000000..7bd58dc41581 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7009/revocation.pyi @@ -0,0 +1,9 @@ +from authlib.oauth2.rfc6749 import TokenEndpoint + +class RevocationEndpoint(TokenEndpoint): + ENDPOINT_NAME: str + def authenticate_token(self, request, client): ... + def check_params(self, request, client) -> None: ... + def create_endpoint_response(self, request): ... + def query_token(self, token_string, token_type_hint): ... + def revoke_token(self, token, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi new file mode 100644 index 000000000000..5c15a9779df8 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7521/__init__.pyi @@ -0,0 +1,3 @@ +from .client import AssertionClient as AssertionClient + +__all__ = ["AssertionClient"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi b/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi new file mode 100644 index 000000000000..fb021f8ccb5c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7521/client.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Error + +class AssertionClient: + DEFAULT_GRANT_TYPE: Incomplete + ASSERTION_METHODS: Incomplete + token_auth_class: Incomplete + oauth_error_class = OAuth2Error + session: Incomplete + token_endpoint: Incomplete + grant_type: Incomplete + issuer: Incomplete + subject: Incomplete + audience: Incomplete + claims: Incomplete + scope: Incomplete + token_auth: Incomplete + leeway: Incomplete + def __init__( + self, + session, + token_endpoint, + issuer, + subject, + audience=None, + grant_type=None, + claims=None, + token_placement: str = "header", + scope=None, + leeway: int = 60, + **kwargs, + ) -> None: ... + + @property + def token(self): ... + @token.setter + def token(self, token) -> None: ... + + def refresh_token(self): ... + def parse_response_token(self, resp): ... + def __del__(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi new file mode 100644 index 000000000000..693cfd64285d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/__init__.pyi @@ -0,0 +1,18 @@ +from .assertion import client_secret_jwt_sign as client_secret_jwt_sign, private_key_jwt_sign as private_key_jwt_sign +from .auth import ClientSecretJWT as ClientSecretJWT, PrivateKeyJWT as PrivateKeyJWT +from .client import JWTBearerClientAssertion as JWTBearerClientAssertion +from .jwt_bearer import JWTBearerGrant as JWTBearerGrant +from .token import JWTBearerTokenGenerator as JWTBearerTokenGenerator +from .validator import JWTBearerToken as JWTBearerToken, JWTBearerTokenValidator as JWTBearerTokenValidator + +__all__ = [ + "JWTBearerGrant", + "JWTBearerClientAssertion", + "client_secret_jwt_sign", + "private_key_jwt_sign", + "ClientSecretJWT", + "PrivateKeyJWT", + "JWTBearerToken", + "JWTBearerTokenGenerator", + "JWTBearerTokenValidator", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi new file mode 100644 index 000000000000..e4b5986a41ee --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi @@ -0,0 +1,27 @@ +def sign_jwt_bearer_assertion( + key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, header=None, *, alg=None, expires_in=3600 +) -> str: ... +def client_secret_jwt_sign( + client_secret, + client_id, + token_endpoint, + alg: str = "HS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... +def private_key_jwt_sign( + private_key, + client_id, + token_endpoint, + alg: str = "RS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi new file mode 100644 index 000000000000..c6c88e80c984 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +class ClientSecretJWT: + name: str + alg: str + token_endpoint: Incomplete + claims: Incomplete + headers: Incomplete + def __init__(self, token_endpoint=None, claims=None, headers=None, alg=None) -> None: ... + def sign(self, auth, token_endpoint) -> str: ... + def __call__(self, auth, method, uri, headers, body): ... + +class PrivateKeyJWT(ClientSecretJWT): + name: str + alg: str + def sign(self, auth, token_endpoint) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi new file mode 100644 index 000000000000..a58719ac613a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Final, overload +from typing_extensions import deprecated + +ASSERTION_TYPE: Final[str] +log: Logger + +class JWTBearerClientAssertion: + CLIENT_ASSERTION_TYPE: Final[str] + CLIENT_AUTH_METHOD: Final[str] + token_url: str | None + leeway: int + + @overload + @deprecated("The `token_url` parameter is deprecated. Override `get_audiences` instead.") + def __init__(self, token_url: str = ..., validate_jti: bool = True, leeway: int = 60) -> None: ... + @overload + def __init__(self, token_url: None = None, validate_jti: bool = True, leeway: int = 60) -> None: ... + + def __call__(self, query_client, request): ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def get_audiences(self) -> list[str]: ... + def process_assertion_claims(self, assertion, resolve_key) -> dict[str, Incomplete]: ... + def authenticate_client(self, client): ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], Incomplete]: ... + def validate_jti(self, claims, jti): ... + def resolve_client_public_key(self, client): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi new file mode 100644 index 000000000000..d50561b210a4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import ClassVar, Final + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger +JWT_BEARER_GRANT_TYPE: Final[str] + +class JWTBearerGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE = JWT_BEARER_GRANT_TYPE + CLAIMS_OPTIONS: ClassVar[dict[str, dict[str, bool]]] + LEEWAY: ClassVar[int] + @staticmethod + def sign(key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, **kwargs): ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def process_assertion_claims(self, assertion) -> dict[str, Incomplete]: ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], Incomplete]: ... + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def resolve_issuer_client(self, issuer): ... + def resolve_client_public_key(self, client): ... + def authenticate_user(self, subject): ... + def get_audiences(self) -> list[str]: ... + def has_granted_permission(self, client, user) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi new file mode 100644 index 000000000000..e8612390e482 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/token.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +class JWTBearerTokenGenerator: + DEFAULT_EXPIRES_IN: int + secret_key: Incomplete + issuer: Incomplete + alg: Incomplete + def __init__(self, secret_key, issuer=None, alg: str = "RS256") -> None: ... + @staticmethod + def get_allowed_scope(client, scope): ... + @staticmethod + def get_sub_value(user): ... + def get_token_data(self, grant_type, client, expires_in, user=None, scope=None): ... + def generate(self, grant_type, client, user=None, scope=None, expires_in=None): ... + def __call__(self, grant_type, client, user=None, scope=None, expires_in=None, include_refresh_token: bool = True): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi b/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi new file mode 100644 index 000000000000..068756c77c80 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6749 import TokenMixin +from authlib.oauth2.rfc6750 import BearerTokenValidator + +logger: Incomplete + +class JWTBearerToken(TokenMixin, dict[str, Incomplete]): + def check_client(self, client) -> bool: ... + def get_scope(self): ... + def get_expires_in(self): ... + def is_expired(self) -> bool: ... + def is_revoked(self) -> bool: ... + +class JWTBearerTokenValidator(BearerTokenValidator): + TOKEN_TYPE: str + token_cls = JWTBearerToken + public_key: Incomplete + claims_options: Incomplete + def __init__(self, public_key, issuer=None, realm=None, **extra_attributes) -> None: ... + def authenticate_token(self, token_string: str) -> JWTBearerToken | None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi new file mode 100644 index 000000000000..5cd9f6b3ac5a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/__init__.pyi @@ -0,0 +1,17 @@ +from .claims import ClientMetadataClaims as ClientMetadataClaims +from .endpoint import ClientRegistrationEndpoint as ClientRegistrationEndpoint +from .errors import ( + InvalidClientMetadataError as InvalidClientMetadataError, + InvalidRedirectURIError as InvalidRedirectURIError, + InvalidSoftwareStatementError as InvalidSoftwareStatementError, + UnapprovedSoftwareStatementError as UnapprovedSoftwareStatementError, +) + +__all__ = [ + "ClientMetadataClaims", + "ClientRegistrationEndpoint", + "InvalidRedirectURIError", + "InvalidClientMetadataError", + "InvalidSoftwareStatementError", + "UnapprovedSoftwareStatementError", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi new file mode 100644 index 000000000000..15179250147a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Any + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_redirect_uris(self) -> None: ... + def validate_token_endpoint_auth_method(self) -> None: ... + def validate_grant_types(self) -> None: ... + def validate_response_types(self) -> None: ... + def validate_client_name(self) -> None: ... + def validate_client_uri(self) -> None: ... + def validate_logo_uri(self) -> None: ... + def validate_scope(self) -> None: ... + def validate_contacts(self) -> None: ... + def validate_tos_uri(self) -> None: ... + def validate_policy_uri(self) -> None: ... + def validate_jwks_uri(self) -> None: ... + def validate_jwks(self) -> None: ... + def validate_software_id(self) -> None: ... + def validate_software_version(self) -> None: ... + @classmethod + def get_claims_options(cls, metadata: Mapping[str, Incomplete]) -> dict[str, Any]: ... # dict values are key-dependent diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi new file mode 100644 index 000000000000..21dde441cee9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Final + +class ClientRegistrationEndpoint: + ENDPOINT_NAME: Final = "client_registration" + software_statement_alg_values_supported: Incomplete + server: Incomplete + claims_classes: list[type[Incomplete]] + def __init__(self, server=None, claims_classes: list[type[Incomplete]] | None = None) -> None: ... + def __call__(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def create_registration_response(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def extract_client_metadata(self, request) -> dict[Incomplete, Incomplete]: ... + def extract_software_statement(self, software_statement, request) -> dict[str, Incomplete]: ... + def generate_client_info(self, request) -> dict[str, Incomplete]: ... + def generate_client_registration_info(self, client, request) -> Incomplete | None: ... + def create_endpoint_request(self, request): ... + def generate_client_id(self, request) -> str: ... + def generate_client_secret(self, request) -> str: ... + def get_server_metadata(self): ... + def authenticate_token(self, request): ... + def resolve_public_key(self, request): ... + def save_client(self, client_info, client_metadata, request): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi new file mode 100644 index 000000000000..7229ef4e6ede --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7591/errors.pyi @@ -0,0 +1,13 @@ +from authlib.oauth2 import OAuth2Error + +class InvalidRedirectURIError(OAuth2Error): + error: str + +class InvalidClientMetadataError(OAuth2Error): + error: str + +class InvalidSoftwareStatementError(OAuth2Error): + error: str + +class UnapprovedSoftwareStatementError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi new file mode 100644 index 000000000000..e4ff814ea64e --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7592/__init__.pyi @@ -0,0 +1,3 @@ +from .endpoint import ClientConfigurationEndpoint as ClientConfigurationEndpoint + +__all__ = ["ClientConfigurationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi new file mode 100644 index 000000000000..fce1d9d54e94 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7592/endpoint.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from typing import Final + +class ClientConfigurationEndpoint: + ENDPOINT_NAME: Final = "client_configuration" + server: Incomplete + claims_classes: list[type[Incomplete]] + def __init__(self, server=None, claims_classes: list[type[Incomplete]] | None = None) -> None: ... + def __call__(self, request): ... + def create_configuration_response(self, request): ... + def create_endpoint_request(self, request): ... + def create_read_client_response(self, client, request): ... + def create_delete_client_response(self, client, request): ... + def create_update_client_response(self, client, request): ... + def extract_client_metadata(self, request): ... + def introspect_client(self, client): ... + def generate_client_registration_info(self, client, request): ... + def authenticate_token(self, request): ... + def authenticate_client(self, request): ... + def revoke_access_token(self, token, request): ... + def check_permission(self, client, request): ... + def delete_client(self, client, request): ... + def update_client(self, client, client_metadata, request): ... + def get_server_metadata(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi new file mode 100644 index 000000000000..18a2be1b0e43 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7636/__init__.pyi @@ -0,0 +1,3 @@ +from .challenge import CodeChallenge as CodeChallenge, create_s256_code_challenge as create_s256_code_challenge + +__all__ = ["CodeChallenge", "create_s256_code_challenge"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi b/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi new file mode 100644 index 000000000000..e3d07e846686 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7636/challenge.pyi @@ -0,0 +1,23 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final + +CODE_VERIFIER_PATTERN: Final[re.Pattern[str]] +CODE_CHALLENGE_PATTERN: Final[re.Pattern[str]] + +def create_s256_code_challenge(code_verifier): ... +def compare_plain_code_challenge(code_verifier, code_challenge): ... +def compare_s256_code_challenge(code_verifier, code_challenge): ... + +class CodeChallenge: + DEFAULT_CODE_CHALLENGE_METHOD: str + SUPPORTED_CODE_CHALLENGE_METHOD: list[str] + CODE_CHALLENGE_METHODS: dict[str, Callable[[Incomplete, Incomplete], Incomplete]] + required: bool + def __init__(self, required: bool = True) -> None: ... + def __call__(self, grant) -> None: ... + def validate_code_challenge(self, grant, redirect_uri) -> None: ... + def validate_code_verifier(self, grant, result) -> None: ... + def get_authorization_code_challenge(self, authorization_code): ... + def get_authorization_code_challenge_method(self, authorization_code): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi new file mode 100644 index 000000000000..8b48b0ce9476 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/__init__.pyi @@ -0,0 +1,5 @@ +from .introspection import IntrospectionEndpoint as IntrospectionEndpoint +from .models import IntrospectionToken as IntrospectionToken +from .token_validator import IntrospectTokenValidator as IntrospectTokenValidator + +__all__ = ["IntrospectionEndpoint", "IntrospectionToken", "IntrospectTokenValidator"] diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi new file mode 100644 index 000000000000..58d178475a51 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/introspection.pyi @@ -0,0 +1,11 @@ +from authlib.oauth2.rfc6749 import TokenEndpoint + +class IntrospectionEndpoint(TokenEndpoint): + ENDPOINT_NAME: str + def authenticate_token(self, request, client): ... + def check_params(self, request, client) -> None: ... + def create_endpoint_response(self, request): ... + def create_introspection_payload(self, token): ... + def check_permission(self, token, client, request): ... + def query_token(self, token_string, token_type_hint): ... + def introspect_token(self, token): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi new file mode 100644 index 000000000000..bb583baaa4f4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/models.pyi @@ -0,0 +1,8 @@ +from authlib.oauth2.rfc6749 import TokenMixin + +class IntrospectionToken(dict[str, object], TokenMixin): + def get_client_id(self): ... + def get_scope(self): ... + def get_expires_in(self): ... + def get_expires_at(self): ... + def __getattr__(self, key): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi b/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi new file mode 100644 index 000000000000..8b7a74400ae2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc7662/token_validator.pyi @@ -0,0 +1,7 @@ +from authlib.oauth2.rfc6749 import TokenValidator + +class IntrospectTokenValidator(TokenValidator): + TOKEN_TYPE: str + def introspect_token(self, token_string): ... + def authenticate_token(self, token_string): ... + def validate_token(self, token, scopes, request) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi new file mode 100644 index 000000000000..b7b5b3a03967 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/__init__.pyi @@ -0,0 +1,4 @@ +from .models import AuthorizationServerMetadata as AuthorizationServerMetadata +from .well_known import get_well_known_url as get_well_known_url + +__all__ = ["AuthorizationServerMetadata", "get_well_known_url"] diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi new file mode 100644 index 000000000000..54dec12ec5ea --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +class AuthorizationServerMetadata(dict[str, object]): + REGISTRY_KEYS: list[str] + def validate_issuer(self) -> None: ... + def validate_authorization_endpoint(self) -> None: ... + def validate_token_endpoint(self) -> None: ... + def validate_jwks_uri(self) -> None: ... + def validate_registration_endpoint(self) -> None: ... + def validate_scopes_supported(self) -> None: ... + def validate_response_types_supported(self) -> None: ... + def validate_response_modes_supported(self) -> None: ... + def validate_grant_types_supported(self) -> None: ... + def validate_token_endpoint_auth_methods_supported(self) -> None: ... + def validate_token_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_service_documentation(self) -> None: ... + def validate_ui_locales_supported(self) -> None: ... + def validate_op_policy_uri(self) -> None: ... + def validate_op_tos_uri(self) -> None: ... + def validate_revocation_endpoint(self) -> None: ... + def validate_revocation_endpoint_auth_methods_supported(self) -> None: ... + def validate_revocation_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_introspection_endpoint(self) -> None: ... + def validate_introspection_endpoint_auth_methods_supported(self) -> None: ... + def validate_introspection_endpoint_auth_signing_alg_values_supported(self) -> None: ... + def validate_code_challenge_methods_supported(self) -> None: ... + @property + def response_modes_supported(self): ... + @property + def grant_types_supported(self): ... + @property + def token_endpoint_auth_methods_supported(self): ... + @property + def revocation_endpoint_auth_methods_supported(self): ... + @property + def introspection_endpoint_auth_methods_supported(self): ... + def validate(self, metadata_classes: list[type[Incomplete]] | None = None) -> None: ... + def __getattr__(self, key): ... + +def validate_array_value(metadata, key) -> None: ... +def validate_language_tags_array(metadata, key) -> None: ... +def validate_boolean_value(metadata, key) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi b/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi new file mode 100644 index 000000000000..bcf7aae84e28 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8414/well_known.pyi @@ -0,0 +1 @@ +def get_well_known_url(issuer: str, external: bool = False, suffix: str = "oauth-authorization-server") -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi new file mode 100644 index 000000000000..669437e26bb9 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/__init__.pyi @@ -0,0 +1,19 @@ +from .device_code import DEVICE_CODE_GRANT_TYPE as DEVICE_CODE_GRANT_TYPE, DeviceCodeGrant as DeviceCodeGrant +from .endpoint import DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint +from .errors import ( + AuthorizationPendingError as AuthorizationPendingError, + ExpiredTokenError as ExpiredTokenError, + SlowDownError as SlowDownError, +) +from .models import DeviceCredentialDict as DeviceCredentialDict, DeviceCredentialMixin as DeviceCredentialMixin + +__all__ = [ + "DeviceAuthorizationEndpoint", + "DeviceCodeGrant", + "DEVICE_CODE_GRANT_TYPE", + "DeviceCredentialMixin", + "DeviceCredentialDict", + "AuthorizationPendingError", + "SlowDownError", + "ExpiredTokenError", +] diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi new file mode 100644 index 000000000000..da0bd0bd1bb4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/device_code.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin + +log: Logger +DEVICE_CODE_GRANT_TYPE: str + +class DeviceCodeGrant(BaseGrant, TokenEndpointMixin): + GRANT_TYPE = DEVICE_CODE_GRANT_TYPE + TOKEN_ENDPOINT_AUTH_METHODS: Incomplete + def validate_token_request(self) -> None: ... + def create_token_response(self): ... + def validate_device_credential(self, credential): ... + def query_device_credential(self, device_code): ... + def query_user_grant(self, user_code): ... + def should_slow_down(self, credential): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi new file mode 100644 index 000000000000..06d0d884a926 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/endpoint.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +class DeviceAuthorizationEndpoint: + ENDPOINT_NAME: str + CLIENT_AUTH_METHODS: Incomplete + USER_CODE_TYPE: str + EXPIRES_IN: int + INTERVAL: int + server: Incomplete + def __init__(self, server) -> None: ... + def __call__(self, request): ... + def create_endpoint_request(self, request): ... + def authenticate_client(self, request): ... + def create_endpoint_response(self, request): ... + def generate_user_code(self): ... + def generate_device_code(self): ... + def get_verification_uri(self): ... + def save_device_credential(self, client_id, scope, data): ... + +def create_string_user_code(): ... +def create_digital_user_code(): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi new file mode 100644 index 000000000000..dc3803877039 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/errors.pyi @@ -0,0 +1,10 @@ +from authlib.oauth2 import OAuth2Error + +class AuthorizationPendingError(OAuth2Error): + error: str + +class SlowDownError(OAuth2Error): + error: str + +class ExpiredTokenError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi b/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi new file mode 100644 index 000000000000..a9b987cd86f5 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc8628/models.pyi @@ -0,0 +1,13 @@ +class DeviceCredentialMixin: + def get_client_id(self): ... + def get_scope(self): ... + def get_user_code(self): ... + def is_expired(self): ... + +class DeviceCredentialDict(dict[str, object], DeviceCredentialMixin): + def get_client_id(self): ... + def get_scope(self): ... + def get_user_code(self): ... + def get_nonce(self): ... + def get_auth_time(self): ... + def is_expired(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc8693/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc8693/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi new file mode 100644 index 000000000000..f8a3418f836d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/__init__.pyi @@ -0,0 +1,6 @@ +from .introspection import JWTIntrospectionEndpoint as JWTIntrospectionEndpoint +from .revocation import JWTRevocationEndpoint as JWTRevocationEndpoint +from .token import JWTBearerTokenGenerator as JWTBearerTokenGenerator +from .token_validator import JWTBearerTokenValidator as JWTBearerTokenValidator + +__all__ = ["JWTBearerTokenGenerator", "JWTBearerTokenValidator", "JWTIntrospectionEndpoint", "JWTRevocationEndpoint"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi new file mode 100644 index 000000000000..d91f4321a212 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable + +from authlib.jose import JWTClaims + +# Inherits from joserfc.jwt.JWTClaimsRegistry +class JWTAccessTokenClaimsValidator: + def validate_auth_time(self, auth_time) -> None: ... + def validate_amr(self, amr) -> None: ... + +class JWTAccessTokenClaims(JWTClaims): + registry_cls = JWTAccessTokenClaimsValidator + def validate(self, *, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... # type: ignore[override] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi new file mode 100644 index 000000000000..c54599bf0a83 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from ..rfc7662 import IntrospectionEndpoint +from .claims import JWTAccessTokenClaims + +class JWTIntrospectionEndpoint(IntrospectionEndpoint): + ENDPOINT_NAME: str + issuer: Incomplete + def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... + def create_endpoint_response(self, request): ... + def authenticate_token(self, request, client) -> JWTAccessTokenClaims | None: ... + def create_introspection_payload(self, token: JWTAccessTokenClaims) -> dict[str, Incomplete]: ... + def get_jwks(self): ... + def get_username(self, user_id: str) -> str: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi new file mode 100644 index 000000000000..befb05a1702d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +from authlib.oauth2.rfc7009 import RevocationEndpoint + +class JWTRevocationEndpoint(RevocationEndpoint): + issuer: Incomplete + def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... + def authenticate_token(self, request, client) -> Never: ... + def get_jwks(self): ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi new file mode 100644 index 000000000000..6ef3b9c2d46d --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6750 import BearerTokenGenerator + +class JWTBearerTokenGenerator(BearerTokenGenerator): + issuer: Incomplete + alg: Incomplete + def __init__(self, issuer, alg: str = "RS256", refresh_token_generator=None, expires_generator=None) -> None: ... + def get_jwks(self): ... + def get_extra_claims(self, client, grant_type, user, scope): ... + def get_audiences(self, client, user, scope) -> str | list[str]: ... + def get_acr(self, user) -> str | None: ... + def get_auth_time(self, user) -> int | None: ... + def get_amr(self, user) -> list[str] | None: ... + def get_jti(self, client, grant_type, user, scope) -> str: ... + # Override seems safe, but mypy doesn't like that it's a callabe protocol in the base + def access_token_generator(self, client, grant_type, user, scope) -> str: ... # type: ignore[override] diff --git a/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi b/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi new file mode 100644 index 000000000000..c893ec9349f1 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from authlib.oauth2.rfc6750.validator import BearerTokenValidator + +from .claims import JWTAccessTokenClaims + +class JWTBearerTokenValidator(BearerTokenValidator): + issuer: Incomplete + resource_server: Incomplete + def __init__(self, issuer, resource_server, *args, **kwargs) -> None: ... + def get_jwks(self): ... + def validate_iss(self, claims, iss: str) -> bool: ... + def authenticate_token(self, token_string) -> JWTAccessTokenClaims: ... + def validate_token( + self, token: JWTAccessTokenClaims, scopes, request, groups=None, roles=None, entitlements=None + ) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi new file mode 100644 index 000000000000..8a6295782b36 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/__init__.pyi @@ -0,0 +1,5 @@ +from .authorization_server import JWTAuthenticationRequest as JWTAuthenticationRequest +from .discovery import AuthorizationServerMetadata as AuthorizationServerMetadata +from .registration import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["AuthorizationServerMetadata", "JWTAuthenticationRequest", "ClientMetadataClaims"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi new file mode 100644 index 000000000000..5461a00b654c --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from ..rfc6749 import AuthorizationServer, ClientMixin +from ..rfc6749.requests import OAuth2Request + +class JWTAuthenticationRequest: + claims_validator: Incomplete + support_request: bool + support_request_uri: bool + def __init__(self, support_request: bool = True, support_request_uri: bool = True) -> None: ... + def __call__(self, authorization_server: AuthorizationServer) -> None: ... + def get_request_object_signing_algorithms(self, client) -> list[str]: ... + def parse_authorization_request(self, authorization_server: AuthorizationServer, request: OAuth2Request) -> None: ... + def get_request_object(self, request_uri: str): ... + def resolve_client_public_key(self, client: ClientMixin): ... + def get_server_metadata(self) -> dict[str, Incomplete]: ... + def get_client_require_signed_request_object(self, client: ClientMixin) -> bool: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi new file mode 100644 index 000000000000..92b57602e5ef --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/discovery.pyi @@ -0,0 +1,3 @@ +class AuthorizationServerMetadata(dict[str, object]): + REGISTRY_KEYS: list[str] + def validate_require_signed_request_object(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi new file mode 100644 index 000000000000..a0bcd96e173b --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/errors.pyi @@ -0,0 +1,23 @@ +from ..base import OAuth2Error + +__all__ = ["InvalidRequestUriError", "InvalidRequestObjectError", "RequestNotSupportedError", "RequestUriNotSupportedError"] + +class InvalidRequestUriError(OAuth2Error): + error: str + description: str + status_code: int + +class InvalidRequestObjectError(OAuth2Error): + error: str + description: str + status_code: int + +class RequestNotSupportedError(OAuth2Error): + error: str + description: str + status_code: int + +class RequestUriNotSupportedError(OAuth2Error): + error: str + description: str + status_code: int diff --git a/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi b/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi new file mode 100644 index 000000000000..66af83e065b4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_require_signed_request_object(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi new file mode 100644 index 000000000000..559a1c9263f4 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi @@ -0,0 +1,4 @@ +from .discovery import AuthorizationServerMetadata as AuthorizationServerMetadata +from .parameter import IssuerParameter as IssuerParameter + +__all__ = ["AuthorizationServerMetadata", "IssuerParameter"] diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi new file mode 100644 index 000000000000..654d2d31e28a --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class AuthorizationServerMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_authorization_response_iss_parameter_supported(self) -> None: ... diff --git a/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi b/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi new file mode 100644 index 000000000000..70e2ee20b7f2 --- /dev/null +++ b/stubs/Authlib/authlib/oauth2/rfc9207/parameter.pyi @@ -0,0 +1,4 @@ +class IssuerParameter: + def __call__(self, authorization_server) -> None: ... + def add_issuer_parameter(self, authorization_server, response) -> None: ... + def get_issuer(self) -> str | None: ... diff --git a/stubs/Authlib/authlib/oidc/__init__.pyi b/stubs/Authlib/authlib/oidc/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Authlib/authlib/oidc/core/__init__.pyi b/stubs/Authlib/authlib/oidc/core/__init__.pyi new file mode 100644 index 000000000000..0763373dc8ff --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/__init__.pyi @@ -0,0 +1,31 @@ +from .claims import ( + CodeIDToken as CodeIDToken, + HybridIDToken as HybridIDToken, + IDToken as IDToken, + ImplicitIDToken as ImplicitIDToken, + UserInfo as UserInfo, + get_claim_cls_by_response_type as get_claim_cls_by_response_type, +) +from .grants import ( + OpenIDCode as OpenIDCode, + OpenIDHybridGrant as OpenIDHybridGrant, + OpenIDImplicitGrant as OpenIDImplicitGrant, + OpenIDToken as OpenIDToken, +) +from .models import AuthorizationCodeMixin as AuthorizationCodeMixin +from .userinfo import UserInfoEndpoint as UserInfoEndpoint + +__all__ = [ + "AuthorizationCodeMixin", + "IDToken", + "CodeIDToken", + "ImplicitIDToken", + "HybridIDToken", + "UserInfo", + "UserInfoEndpoint", + "get_claim_cls_by_response_type", + "OpenIDToken", + "OpenIDCode", + "OpenIDHybridGrant", + "OpenIDImplicitGrant", +] diff --git a/stubs/Authlib/authlib/oidc/core/claims.pyi b/stubs/Authlib/authlib/oidc/core/claims.pyi new file mode 100644 index 000000000000..f9a24cfbcfa6 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/claims.pyi @@ -0,0 +1,36 @@ +from collections.abc import Callable + +from authlib.jose import JWTClaims + +__all__ = ["IDToken", "CodeIDToken", "ImplicitIDToken", "HybridIDToken", "UserInfo", "get_claim_cls_by_response_type"] + +class IDToken(JWTClaims): + ESSENTIAL_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + def validate_auth_time(self) -> None: ... + def validate_nonce(self) -> None: ... + def validate_amr(self) -> None: ... + def validate_azp(self) -> None: ... + def validate_at_hash(self) -> None: ... + +class CodeIDToken(IDToken): + RESPONSE_TYPES: tuple[str, ...] + +class ImplicitIDToken(IDToken): + RESPONSE_TYPES: tuple[str, ...] + ESSENTIAL_CLAIMS: list[str] + def validate_at_hash(self) -> None: ... + +class HybridIDToken(ImplicitIDToken): + RESPONSE_TYPES: tuple[str, ...] + def validate(self, now=None, leeway: int = 0) -> None: ... + def validate_c_hash(self) -> None: ... + +class UserInfo(dict[str, object]): + REGISTERED_CLAIMS: list[str] + SCOPES_CLAIMS_MAPPING: dict[str, list[str]] + def validate_locale(self) -> None: ... + def filter(self, scope: str) -> UserInfo: ... + def __getattr__(self, key): ... + +def get_claim_cls_by_response_type(response_type) -> type: ... diff --git a/stubs/Authlib/authlib/oidc/core/errors.pyi b/stubs/Authlib/authlib/oidc/core/errors.pyi new file mode 100644 index 000000000000..a7132d25fd7a --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/errors.pyi @@ -0,0 +1,28 @@ +from authlib.oauth2 import OAuth2Error + +class InteractionRequiredError(OAuth2Error): + error: str + +class LoginRequiredError(OAuth2Error): + error: str + +class AccountSelectionRequiredError(OAuth2Error): + error: str + +class ConsentRequiredError(OAuth2Error): + error: str + +class InvalidRequestURIError(OAuth2Error): + error: str + +class InvalidRequestObjectError(OAuth2Error): + error: str + +class RequestNotSupportedError(OAuth2Error): + error: str + +class RequestURINotSupportedError(OAuth2Error): + error: str + +class RegistrationNotSupportedError(OAuth2Error): + error: str diff --git a/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi b/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi new file mode 100644 index 000000000000..d4bc9d9b42e7 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/__init__.pyi @@ -0,0 +1,5 @@ +from .code import OpenIDCode as OpenIDCode, OpenIDToken as OpenIDToken +from .hybrid import OpenIDHybridGrant as OpenIDHybridGrant +from .implicit import OpenIDImplicitGrant as OpenIDImplicitGrant + +__all__ = ["OpenIDToken", "OpenIDCode", "OpenIDImplicitGrant", "OpenIDHybridGrant"] diff --git a/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi b/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi new file mode 100644 index 000000000000..ba67813c9836 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Request + +class LegacyMixin: + DEFAULT_EXPIRES_IN: int + def resolve_client_private_key(self, client): ... + def get_client_algorithm(self, client): ... + def get_client_claims(self, client) -> dict[str, Incomplete]: ... + def get_encode_header(self, client) -> dict[str, Incomplete]: ... + def get_compatible_claims(self, request: OAuth2Request) -> dict[str, Incomplete]: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/code.pyi b/stubs/Authlib/authlib/oidc/core/grants/code.pyi new file mode 100644 index 000000000000..6c29a87897f2 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/code.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2 import OAuth2Request +from authlib.oauth2.rfc6749 import BaseGrant +from authlib.oidc.core import UserInfo + +from ..models import AuthorizationCodeMixin +from ._legacy import LegacyMixin + +log: Logger + +class OpenIDToken(LegacyMixin): + def get_authorization_code_claims(self, authorization_code: AuthorizationCodeMixin) -> dict[str, Incomplete]: ... + def generate_user_info(self, user, scope: str) -> UserInfo: ... + def encode_id_token(self, token, request: OAuth2Request) -> str: ... + def process_token(self, grant: BaseGrant, response) -> dict[str, Incomplete]: ... + def __call__(self, grant: BaseGrant) -> None: ... + +class OpenIDCode(OpenIDToken): + require_nonce: bool + def __init__(self, require_nonce: bool = False) -> None: ... + def exists_nonce(self, nonce: str, request: OAuth2Request) -> bool: ... + def validate_openid_authorization_request(self, grant: BaseGrant, redirect_uri) -> None: ... + def __call__(self, grant: BaseGrant) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi b/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi new file mode 100644 index 000000000000..f2652cc1b9cc --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/hybrid.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oidc.core import OpenIDImplicitGrant + +log: Logger + +class OpenIDHybridGrant(OpenIDImplicitGrant): + AUTHORIZATION_CODE_LENGTH: int + RESPONSE_TYPES: Incomplete + GRANT_TYPE: str + DEFAULT_RESPONSE_MODE: str + def generate_authorization_code(self) -> str: ... + def save_authorization_code(self, code, request): ... + def validate_authorization_request(self) -> str: ... + def create_granted_params(self, grant_user) -> list[tuple[str, str]]: ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi b/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi new file mode 100644 index 000000000000..959a688b0e35 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from logging import Logger + +from authlib.oauth2.rfc6749 import ImplicitGrant +from authlib.oidc.core import UserInfo + +from ._legacy import LegacyMixin + +log: Logger + +class OpenIDImplicitGrant(LegacyMixin, ImplicitGrant): + RESPONSE_TYPES: Incomplete + DEFAULT_RESPONSE_MODE: str + def exists_nonce(self, nonce, request) -> bool: ... + def generate_user_info(self, user, scope) -> UserInfo: ... + def get_audiences(self, request) -> list[Incomplete]: ... + def validate_authorization_request(self) -> str: ... + def validate_consent_request(self) -> str: ... + def create_authorization_response(self, redirect_uri, grant_user): ... + def create_granted_params(self, grant_user) -> list[tuple[str, Incomplete]]: ... + def process_implicit_token(self, token, code=None): ... diff --git a/stubs/Authlib/authlib/oidc/core/grants/util.pyi b/stubs/Authlib/authlib/oidc/core/grants/util.pyi new file mode 100644 index 000000000000..772103c305ce --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/grants/util.pyi @@ -0,0 +1,21 @@ +from authlib.oidc.core import UserInfo + +def is_openid_scope(scope: str | None) -> bool: ... +def validate_request_prompt(grant, redirect_uri, redirect_fragment: bool = False): ... +def validate_nonce(request, exists_nonce, required: bool = False): ... +def generate_id_token( + token: dict[str, str | int], + user_info: UserInfo, + key: str, + iss: str, + aud: list[str], + alg: str = "RS256", + exp: int = 3600, + nonce: str | None = None, + auth_time: int | None = None, + acr: str | None = None, + amr: list[str] | None = None, + code: str | None = None, + kid: str | None = None, +) -> str: ... +def create_response_mode_response(redirect_uri, params, response_mode): ... diff --git a/stubs/Authlib/authlib/oidc/core/models.pyi b/stubs/Authlib/authlib/oidc/core/models.pyi new file mode 100644 index 000000000000..d204f91d0cb3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/models.pyi @@ -0,0 +1,7 @@ +from authlib.oauth2.rfc6749 import AuthorizationCodeMixin as _AuthorizationCodeMixin + +class AuthorizationCodeMixin(_AuthorizationCodeMixin): + def get_nonce(self) -> str | None: ... + def get_auth_time(self) -> int | None: ... + def get_acr(self) -> str: ... + def get_amr(self) -> list[str]: ... diff --git a/stubs/Authlib/authlib/oidc/core/userinfo.pyi b/stubs/Authlib/authlib/oidc/core/userinfo.pyi new file mode 100644 index 000000000000..cf3bf956cba3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/userinfo.pyi @@ -0,0 +1,19 @@ +from authlib.oauth2.rfc6749.authorization_server import AuthorizationServer +from authlib.oauth2.rfc6749.requests import OAuth2Request +from authlib.oauth2.rfc6749.resource_protector import ResourceProtector + +from .claims import UserInfo + +class UserInfoEndpoint: + ENDPOINT_NAME: str + server: AuthorizationServer | None + resource_protector: ResourceProtector | None + def __init__( + self, server: AuthorizationServer | None = None, resource_protector: ResourceProtector | None = None + ) -> None: ... + def create_endpoint_request(self, request: OAuth2Request) -> OAuth2Request: ... + def __call__(self, request: OAuth2Request) -> tuple[int, str | UserInfo, list[tuple[str, str]]]: ... + def get_supported_algorithms(self) -> list[str]: ... + def generate_user_info(self, user, scope: str) -> UserInfo: ... + def get_issuer(self) -> str: ... + def resolve_private_key(self): ... diff --git a/stubs/Authlib/authlib/oidc/core/util.pyi b/stubs/Authlib/authlib/oidc/core/util.pyi new file mode 100644 index 000000000000..5c0a4bff37f6 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/core/util.pyi @@ -0,0 +1,7 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import SupportsBytes, SupportsIndex + +def create_half_hash( + s: str | bytes | float | Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, alg: str +) -> bytes | None: ... diff --git a/stubs/Authlib/authlib/oidc/discovery/__init__.pyi b/stubs/Authlib/authlib/oidc/discovery/__init__.pyi new file mode 100644 index 000000000000..84d76b371134 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/__init__.pyi @@ -0,0 +1,4 @@ +from .models import OpenIDProviderMetadata as OpenIDProviderMetadata +from .well_known import get_well_known_url as get_well_known_url + +__all__ = ["OpenIDProviderMetadata", "get_well_known_url"] diff --git a/stubs/Authlib/authlib/oidc/discovery/models.pyi b/stubs/Authlib/authlib/oidc/discovery/models.pyi new file mode 100644 index 000000000000..63f2211780fc --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/models.pyi @@ -0,0 +1,34 @@ +from authlib.oauth2.rfc8414 import AuthorizationServerMetadata + +class OpenIDProviderMetadata(AuthorizationServerMetadata): + REGISTRY_KEYS: list[str] + def validate_jwks_uri(self): ... + def validate_acr_values_supported(self) -> None: ... + def validate_subject_types_supported(self) -> None: ... + def validate_id_token_signing_alg_values_supported(self) -> None: ... + def validate_id_token_encryption_alg_values_supported(self) -> None: ... + def validate_id_token_encryption_enc_values_supported(self) -> None: ... + def validate_userinfo_signing_alg_values_supported(self) -> None: ... + def validate_userinfo_encryption_alg_values_supported(self) -> None: ... + def validate_userinfo_encryption_enc_values_supported(self) -> None: ... + def validate_request_object_signing_alg_values_supported(self) -> None: ... + def validate_request_object_encryption_alg_values_supported(self) -> None: ... + def validate_request_object_encryption_enc_values_supported(self) -> None: ... + def validate_display_values_supported(self) -> None: ... + def validate_claim_types_supported(self) -> None: ... + def validate_claims_supported(self) -> None: ... + def validate_claims_locales_supported(self) -> None: ... + def validate_claims_parameter_supported(self) -> None: ... + def validate_request_parameter_supported(self) -> None: ... + def validate_request_uri_parameter_supported(self) -> None: ... + def validate_require_request_uri_registration(self) -> None: ... + @property + def claim_types_supported(self): ... + @property + def claims_parameter_supported(self): ... + @property + def request_parameter_supported(self): ... + @property + def request_uri_parameter_supported(self): ... + @property + def require_request_uri_registration(self): ... diff --git a/stubs/Authlib/authlib/oidc/discovery/well_known.pyi b/stubs/Authlib/authlib/oidc/discovery/well_known.pyi new file mode 100644 index 000000000000..b10c03b65439 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/discovery/well_known.pyi @@ -0,0 +1 @@ +def get_well_known_url(issuer: str, external: bool = False) -> str: ... diff --git a/stubs/Authlib/authlib/oidc/registration/__init__.pyi b/stubs/Authlib/authlib/oidc/registration/__init__.pyi new file mode 100644 index 000000000000..e0fca8da8da3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/registration/__init__.pyi @@ -0,0 +1,3 @@ +from .claims import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["ClientMetadataClaims"] diff --git a/stubs/Authlib/authlib/oidc/registration/claims.pyi b/stubs/Authlib/authlib/oidc/registration/claims.pyi new file mode 100644 index 000000000000..5327d0704d7e --- /dev/null +++ b/stubs/Authlib/authlib/oidc/registration/claims.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping + +from authlib.jose import BaseClaims + +class ClientMetadataClaims(BaseClaims): + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + # The "cls" argument is called "self" in the actual implementation, + # but stubtest will not allow that. + @classmethod + def get_claims_options(cls, metadata: Mapping[str, Incomplete]) -> dict[str, Incomplete]: ... + def validate_token_endpoint_auth_signing_alg(self) -> None: ... + def validate_application_type(self) -> None: ... + def validate_sector_identifier_uri(self) -> None: ... + def validate_subject_type(self) -> None: ... + def validate_id_token_signed_response_alg(self) -> None: ... + def validate_id_token_encrypted_response_alg(self) -> None: ... + def validate_id_token_encrypted_response_enc(self) -> None: ... + def validate_userinfo_signed_response_alg(self) -> None: ... + def validate_userinfo_encrypted_response_alg(self) -> None: ... + def validate_userinfo_encrypted_response_enc(self) -> None: ... + def validate_default_max_age(self) -> None: ... + def validate_require_auth_time(self) -> None: ... + def validate_default_acr_values(self) -> None: ... + def validate_initiate_login_uri(self) -> None: ... + def validate_request_object_signing_alg(self) -> None: ... + def validate_request_object_encryption_alg(self) -> None: ... + def validate_request_object_encryption_enc(self) -> None: ... + def validate_request_uris(self) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi new file mode 100644 index 000000000000..1da8effafddf --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi @@ -0,0 +1,5 @@ +from .discovery import OpenIDProviderMetadata as OpenIDProviderMetadata +from .end_session import EndSessionEndpoint as EndSessionEndpoint, EndSessionRequest as EndSessionRequest +from .registration import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["EndSessionEndpoint", "EndSessionRequest", "ClientMetadataClaims", "OpenIDProviderMetadata"] diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi new file mode 100644 index 000000000000..b492c7e6654a --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class OpenIDProviderMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_end_session_endpoint(self) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi new file mode 100644 index 000000000000..85e56a5465e3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from authlib.oauth2.rfc6749.endpoint import Endpoint, EndpointRequest +from authlib.oauth2.rfc6749.requests import OAuth2Request + +@dataclass +class EndSessionRequest(EndpointRequest): + id_token_claims: dict[Incomplete, Incomplete] | None = None + redirect_uri: str | None = None + logout_hint: str | None = None + ui_locales: str | None = None + @property + def needs_confirmation(self) -> bool: ... + +class EndSessionEndpoint(Endpoint): + ENDPOINT_NAME: str + def validate_request(self, request: OAuth2Request) -> EndSessionRequest: ... + def create_response(self, validated_request: EndSessionRequest) -> tuple[int, Incomplete, list[tuple[str, str]]] | None: ... # type: ignore[override] + def resolve_client_from_id_token_claims(self, id_token_claims: dict[Incomplete, Incomplete]) -> Incomplete | None: ... + def is_post_logout_redirect_uri_legitimate( + self, request: OAuth2Request, post_logout_redirect_uri: str, client, logout_hint: str | None + ) -> bool: ... + def get_server_jwks(self): ... + def get_algorithms(self) -> list[str]: ... + def end_session(self, end_session_request: EndSessionRequest) -> None: ... diff --git a/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi b/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi new file mode 100644 index 000000000000..6fe844ac1df3 --- /dev/null +++ b/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable + +from authlib.oauth2.claims import BaseClaims + +class ClientMetadataClaims(BaseClaims): + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/stubs/Deprecated/METADATA.toml b/stubs/Deprecated/METADATA.toml new file mode 100644 index 000000000000..e5fbb122e82f --- /dev/null +++ b/stubs/Deprecated/METADATA.toml @@ -0,0 +1,2 @@ +version = "~=1.3.1" +upstream-repository = "https://github.com/laurent-laporte-pro/deprecated" diff --git a/stubs/Deprecated/deprecated/__init__.pyi b/stubs/Deprecated/deprecated/__init__.pyi new file mode 100644 index 000000000000..3d4b2bfd8a92 --- /dev/null +++ b/stubs/Deprecated/deprecated/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .classic import deprecated as deprecated +from .params import deprecated_params as deprecated_params + +__version__: Final[str] +__author__: Final[str] +__date__: Final[str] +__credits__: Final[str] diff --git a/stubs/Deprecated/deprecated/classic.pyi b/stubs/Deprecated/deprecated/classic.pyi new file mode 100644 index 000000000000..99d2bd6e9bfa --- /dev/null +++ b/stubs/Deprecated/deprecated/classic.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from typing import Any, Literal, TypeAlias, TypeVar, overload + +_F = TypeVar("_F", bound=Callable[..., Any]) +_Actions: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] + +string_types: tuple[type, ...] + +class ClassicAdapter: + reason: str + version: str + action: _Actions | None + category: type[Warning] + def __init__( + self, + reason: str = "", + version: str = "", + action: _Actions | None = None, + category: type[Warning] = ..., + extra_stacklevel: int = 0, + ) -> None: ... + def get_deprecated_msg(self, wrapped: Callable[..., Any], instance: object) -> str: ... + def __call__(self, wrapped: _F) -> Callable[[_F], _F]: ... + +@overload +def deprecated(wrapped: _F, /) -> _F: ... +@overload +def deprecated( + reason: str = ..., + *, + version: str = ..., + action: _Actions | None = ..., + category: type[Warning] | None = ..., + extra_stacklevel: int = 0, +) -> Callable[[_F], _F]: ... diff --git a/stubs/Deprecated/deprecated/params.pyi b/stubs/Deprecated/deprecated/params.pyi new file mode 100644 index 000000000000..721d2d225900 --- /dev/null +++ b/stubs/Deprecated/deprecated/params.pyi @@ -0,0 +1,21 @@ +from collections.abc import Callable, Iterable +from inspect import Signature +from typing import Any, ParamSpec, TypeVar + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +class DeprecatedParams: + messages: dict[str, str] + category: type[Warning] + def __init__( + self, param: str | dict[str, str], reason: str = "", category: type[Warning] = DeprecationWarning # noqa: Y011 + ) -> None: ... + def populate_messages(self, param: str | dict[str, str], reason: str = "") -> None: ... + def check_params( + self, signature: Signature, *args: Any, **kwargs: Any # args and kwargs passing to Signature.bind method + ) -> list[str]: ... + def warn_messages(self, messages: Iterable[str]) -> None: ... + def __call__(self, f: Callable[_P, _R]) -> Callable[_P, _R]: ... + +deprecated_params = DeprecatedParams diff --git a/stubs/Deprecated/deprecated/sphinx.pyi b/stubs/Deprecated/deprecated/sphinx.pyi new file mode 100644 index 000000000000..9d8128d1449b --- /dev/null +++ b/stubs/Deprecated/deprecated/sphinx.pyi @@ -0,0 +1,36 @@ +from collections.abc import Callable +from typing import Any, Literal, TypeVar + +from .classic import ClassicAdapter, _Actions + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class SphinxAdapter(ClassicAdapter): + directive: Literal["versionadded", "versionchanged", "deprecated"] + reason: str + version: str + action: _Actions | None + category: type[Warning] + def __init__( + self, + directive: Literal["versionadded", "versionchanged", "deprecated"], + reason: str = "", + version: str = "", + action: _Actions | None = None, + category: type[Warning] = DeprecationWarning, # noqa: Y011 + extra_stacklevel: int = 0, + line_length: int = 70, + ) -> None: ... + def __call__(self, wrapped: _F) -> Callable[[_F], _F]: ... + +def versionadded(reason: str = "", version: str = "", line_length: int = 70) -> Callable[[_F], _F]: ... +def versionchanged(reason: str = "", version: str = "", line_length: int = 70) -> Callable[[_F], _F]: ... +def deprecated( + reason: str = "", + version: str = "", + line_length: int = 70, + *, + action: _Actions | None = ..., + category: type[Warning] | None = ..., + extra_stacklevel: int = 0, +) -> Callable[[_F], _F]: ... diff --git a/stubs/Flask-Cors/METADATA.toml b/stubs/Flask-Cors/METADATA.toml new file mode 100644 index 000000000000..beef2e8378bc --- /dev/null +++ b/stubs/Flask-Cors/METADATA.toml @@ -0,0 +1,5 @@ +version = "6.0.3" +upstream-repository = "https://github.com/corydolphin/flask-cors" +# Requires a version of flask with a `py.typed` file +dependencies = ["Flask>=2.0.0"] +obsolete-since = { version = "6.0.4", date = "2026-06-07" } diff --git a/stubs/Flask-Cors/flask_cors/__init__.pyi b/stubs/Flask-Cors/flask_cors/__init__.pyi new file mode 100644 index 000000000000..bb2d755dee6e --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/__init__.pyi @@ -0,0 +1,11 @@ +from logging import Logger +from typing import Final + +from .decorator import cross_origin as cross_origin +from .extension import CORS as CORS + +__version__: Final[str] + +rootlogger: Logger + +__all__ = ["CORS", "__version__", "cross_origin"] diff --git a/stubs/Flask-Cors/flask_cors/core.pyi b/stubs/Flask-Cors/flask_cors/core.pyi new file mode 100644 index 000000000000..5b5e2d78561d --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/core.pyi @@ -0,0 +1,74 @@ +from collections.abc import Iterable +from datetime import timedelta +from logging import Logger +from re import Match, Pattern +from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +import flask + +_IterableT = TypeVar("_IterableT", bound=Iterable[Any]) +_T = TypeVar("_T") +_MultiDict: TypeAlias = Any # werkzeug is not part of typeshed + +@type_check_only +class _Options(TypedDict, total=False): + resources: dict[str, dict[str, Any]] | list[str] | str | None + origins: Iterable[str | Pattern[str]] + methods: str | list[str] | None + expose_headers: str | list[str] | None + allow_headers: Iterable[str | Pattern[str]] + supports_credentials: bool | None + max_age: timedelta | int | str | None + send_wildcard: bool | None + vary_header: bool | None + automatic_options: bool | None + intercept_exceptions: bool | None + always_send: bool | None + +LOG: Logger + +ACL_ORIGIN: Final = "Access-Control-Allow-Origin" +ACL_METHODS: Final = "Access-Control-Allow-Methods" +ACL_ALLOW_HEADERS: Final = "Access-Control-Allow-Headers" +ACL_EXPOSE_HEADERS: Final = "Access-Control-Expose-Headers" +ACL_CREDENTIALS: Final = "Access-Control-Allow-Credentials" +ACL_MAX_AGE: Final = "Access-Control-Max-Age" +ACL_RESPONSE_PRIVATE_NETWORK: Final = "Access-Control-Allow-Private-Network" +ACL_REQUEST_METHOD: Final = "Access-Control-Request-Method" +ACL_REQUEST_HEADERS: Final = "Access-Control-Request-Headers" +ACL_REQUEST_HEADER_PRIVATE_NETWORK: Final = "Access-Control-Request-Private-Network" +ALL_METHODS: Final[list[str]] +CONFIG_OPTIONS: Final[list[str]] +FLASK_CORS_EVALUATED: Final = "_FLASK_CORS_EVALUATED" +RegexObject: Final[type[Pattern[str]]] +DEFAULT_OPTIONS: Final[_Options] + +def parse_resources(resources: dict[str, _Options] | Iterable[str] | str | Pattern[str]) -> list[tuple[str, _Options]]: ... +def get_regexp_pattern(regexp: str | Pattern[str]) -> str: ... +def get_cors_origins(options: _Options, request_origin: str | None) -> list[str] | None: ... +def get_allow_headers(options: _Options, acl_request_headers: str | None) -> str | None: ... +def get_cors_headers(options: _Options, request_headers: dict[str, Any], request_method: str) -> _MultiDict: ... +def set_cors_headers(resp: flask.Response, options: _Options) -> flask.Response: ... + +@overload +def probably_regex(maybe_regex: Pattern[str]) -> Literal[True]: ... +@overload +def probably_regex(maybe_regex: str) -> bool: ... + +def re_fix(reg: str) -> str: ... +def try_match_any_pattern(inst: str, patterns: Iterable[str | Pattern[str]], caseSensitive: bool = True) -> bool: ... +def try_match_pattern(value: str, pattern: str | Pattern[str], caseSensitive: bool = True) -> bool | Match[str]: ... +def get_cors_options(appInstance: flask.Flask | None, *dicts: _Options) -> _Options: ... +def get_app_kwarg_dict(appInstance: flask.Flask | None = None) -> _Options: ... +def flexible_str(obj: object) -> str | None: ... +def serialize_option(options_dict: _Options, key: str, upper: bool = False) -> None: ... + +@overload +def ensure_iterable(inst: str) -> list[str]: ... # type: ignore[overload-overlap] +@overload +def ensure_iterable(inst: _IterableT) -> _IterableT: ... # type: ignore[overload-overlap] +@overload +def ensure_iterable(inst: _T) -> list[_T]: ... + +def sanitize_regex_param(param: str | list[str]) -> list[str]: ... +def serialize_options(opts: _Options) -> _Options: ... diff --git a/stubs/Flask-Cors/flask_cors/decorator.pyi b/stubs/Flask-Cors/flask_cors/decorator.pyi new file mode 100644 index 000000000000..66b846d37f64 --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/decorator.pyi @@ -0,0 +1,22 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from logging import Logger +from re import Pattern +from typing import Any, ParamSpec + +_P = ParamSpec("_P") + +LOG: Logger + +def cross_origin( + *args: Any, + origins: str | Pattern[str] | Iterable[str | Pattern[str]] | None = ..., + methods: str | list[str] | None = ..., + expose_headers: str | list[str] | None = ..., + allow_headers: str | Pattern[str] | Iterable[str | Pattern[str]] | None = ..., + supports_credentials: bool | None = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool | None = ..., + vary_header: bool | None = ..., + automatic_options: bool | None = ..., +) -> Callable[[Callable[_P, Any]], Callable[_P, Any]]: ... diff --git a/stubs/Flask-Cors/flask_cors/extension.pyi b/stubs/Flask-Cors/flask_cors/extension.pyi new file mode 100644 index 000000000000..7617107da5da --- /dev/null +++ b/stubs/Flask-Cors/flask_cors/extension.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from logging import Logger +from re import Pattern +from typing import Any + +import flask + +LOG: Logger + +class CORS: + def __init__( + self, + app: flask.Flask | flask.Blueprint | None = None, + *, + resources: dict[str, dict[str, Any]] | list[str] | str | None = ..., + origins: str | Pattern[str] | Iterable[str | Pattern[str]] = ..., + methods: str | list[str] | None = ..., + expose_headers: str | list[str] | None = ..., + allow_headers: str | list[str] | None = ..., + supports_credentials: bool | None = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool | None = ..., + vary_header: bool | None = ..., + **kwargs: Any, + ) -> None: ... + def init_app( + self, + app: flask.Flask, + *, + resources: dict[str, dict[str, Any]] | list[str] | str = ..., + origins: str | Pattern[str] | Iterable[str | Pattern[str]] = ..., + methods: str | list[str] = ..., + expose_headers: str | list[str] = ..., + allow_headers: str | list[str] = ..., + supports_credentials: bool = ..., + max_age: timedelta | int | str | None = ..., + send_wildcard: bool = ..., + vary_header: bool = ..., + **kwargs: Any, + ) -> None: ... + +def make_after_request_function(resources: Iterable[tuple[str, dict[str, Any]]]) -> Callable[..., Any]: ... diff --git a/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt b/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..05ab57df9c75 --- /dev/null +++ b/stubs/Flask-Migrate/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Flask-Migrate users don't need to interact with this undocumented module from within python +flask_migrate.cli diff --git a/stubs/Flask-Migrate/METADATA.toml b/stubs/Flask-Migrate/METADATA.toml new file mode 100644 index 000000000000..526b6c3e0d03 --- /dev/null +++ b/stubs/Flask-Migrate/METADATA.toml @@ -0,0 +1,4 @@ +version = "4.1.*" +upstream-repository = "https://github.com/miguelgrinberg/Flask-Migrate" +# Requires versions of flask and Flask-SQLAlchemy with `py.typed` files +dependencies = ["Flask-SQLAlchemy>=3.0.1", "Flask>=2.0.0"] diff --git a/stubs/Flask-Migrate/flask_migrate/__init__.pyi b/stubs/Flask-Migrate/flask_migrate/__init__.pyi new file mode 100644 index 000000000000..b9235dafed9f --- /dev/null +++ b/stubs/Flask-Migrate/flask_migrate/__init__.pyi @@ -0,0 +1,136 @@ +# pyright: reportInvalidStubStatement=none + +import sys +from _typeshed import StrPath, SupportsFlush, SupportsKeysAndGetItem, SupportsWrite +from argparse import Namespace +from collections.abc import Callable, Iterable, Sequence +from logging import Logger +from typing import Any, ParamSpec, Protocol, TypeAlias, TypeVar, type_check_only + +import flask +from flask_sqlalchemy import SQLAlchemy + +_T = TypeVar("_T") +_T_contra = TypeVar("_T_contra", contravariant=True) +_P = ParamSpec("_P") +_ConfigureCallback: TypeAlias = Callable[[Config], Config] +_AlembicConfigValue: TypeAlias = Any + +alembic_version: tuple[int, int, int] +log: Logger + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol): ... + +class Config: # should inherit from alembic.config.Config which is not possible yet + template_directory: str | None + # Same as alembic.config.Config + template_directory kwarg + def __init__( + self, + file_: StrPath | None = None, + ini_section: str = "alembic", + # Same as buffer argument in TextIOWrapper.__init__.buffer + output_buffer: _SupportsWriteAndFlush[str] | None = None, + # Same as stream argument in alembic.util.messaging + stdout: SupportsWrite[str] = sys.stdout, + cmd_opts: Namespace | None = None, + config_args: SupportsKeysAndGetItem[str, _AlembicConfigValue] | Iterable[tuple[str, _AlembicConfigValue]] = ..., + attributes: ( + SupportsKeysAndGetItem[_AlembicConfigValue, _AlembicConfigValue] + | Iterable[tuple[_AlembicConfigValue, _AlembicConfigValue]] + | None + ) = None, + *, + template_directory: str | None = None, + ) -> None: ... + def get_template_directory(self) -> str: ... + +class Migrate: + configure_callbacks: list[_ConfigureCallback] + db: SQLAlchemy | None + directory: str + alembic_ctx_kwargs: dict[str, _AlembicConfigValue] + def __init__( + self, + app: flask.Flask | None = None, + db: SQLAlchemy | None = None, + directory: str = "migrations", + command: str = "db", + compare_type: bool = True, + render_as_batch: bool = True, + **kwargs: _AlembicConfigValue, + ) -> None: ... + def init_app( + self, + app: flask.Flask, + db: SQLAlchemy | None = None, + directory: str | None = None, + command: str | None = None, + compare_type: bool | None = None, + render_as_batch: bool | None = None, + **kwargs: _AlembicConfigValue, + ) -> None: ... + def configure(self, f: _ConfigureCallback) -> _ConfigureCallback: ... + def call_configure_callbacks(self, config: Config) -> Config: ... + def get_config( + self, directory: str | None = None, x_arg: str | Sequence[str] | None = None, opts: Iterable[str] | None = None + ) -> Config: ... + +def catch_errors(f: Callable[_P, _T]) -> Callable[_P, _T]: ... +def list_templates() -> None: ... +def init(directory: str | None = None, multidb: bool = False, template: str | None = None, package: bool = False) -> None: ... +def revision( + directory: str | None = None, + message: str | None = None, + autogenerate: bool = False, + sql: bool = False, + head: str = "head", + splice: bool = False, + branch_label: str | None = None, + version_path: str | None = None, + rev_id: str | None = None, +) -> None: ... +def migrate( + directory: str | None = None, + message: str | None = None, + sql: bool = False, + head: str = "head", + splice: bool = False, + branch_label: str | None = None, + version_path: str | None = None, + rev_id: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def edit(directory: str | None = None, revision: str = "current") -> None: ... +def merge( + directory: str | None = None, + revisions: str = "", + message: str | None = None, + branch_label: str | None = None, + rev_id: str | None = None, +) -> None: ... +def upgrade( + directory: str | None = None, + revision: str = "head", + sql: bool = False, + tag: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def downgrade( + directory: str | None = None, + revision: str = "-1", + sql: bool = False, + tag: str | None = None, + x_arg: str | Sequence[str] | None = None, +) -> None: ... +def show(directory: str | None = None, revision: str = "head") -> None: ... +def history( + directory: str | None = None, rev_range: str | None = None, verbose: bool = False, indicate_current: bool = False +) -> None: ... +def heads(directory: str | None = None, verbose: bool = False, resolve_dependencies: bool = False) -> None: ... +def branches(directory: str | None = None, verbose: bool = False) -> None: ... +def current(directory: str | None = None, verbose: bool = False) -> None: ... +def stamp( + directory: str | None = None, revision: str = "head", sql: bool = False, tag: str | None = None, purge: bool = False +) -> None: ... +def check(directory: str | None = None) -> None: ... diff --git a/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt b/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6e232db3142d --- /dev/null +++ b/stubs/Flask-SocketIO/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# private attributes / methods, not present in docs +flask_socketio.test_client.SocketIOTestClient.clients +flask_socketio.gevent_socketio_found +flask_socketio.call diff --git a/stubs/Flask-SocketIO/METADATA.toml b/stubs/Flask-SocketIO/METADATA.toml new file mode 100644 index 000000000000..13115c99f63b --- /dev/null +++ b/stubs/Flask-SocketIO/METADATA.toml @@ -0,0 +1,3 @@ +version = "5.6.*" +upstream-repository = "https://github.com/miguelgrinberg/flask-socketio" +dependencies = ["Flask>=0.9"] diff --git a/stubs/Flask-SocketIO/flask_socketio/__init__.pyi b/stubs/Flask-SocketIO/flask_socketio/__init__.pyi new file mode 100644 index 000000000000..af770c766947 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/__init__.pyi @@ -0,0 +1,166 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger +from threading import Thread +from typing import Any, Literal, ParamSpec, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from flask import Flask +from flask.testing import FlaskClient + +from .namespace import Namespace as Namespace +from .test_client import SocketIOTestClient as SocketIOTestClient + +_P = ParamSpec("_P") +_R_co = TypeVar("_R_co", covariant=True) +_ExceptionHandler: TypeAlias = Callable[[BaseException], _R_co] +_Handler: TypeAlias = Callable[_P, _R_co] + +@type_check_only +class _HandlerDecorator(Protocol): + def __call__(self, handler: _Handler[_P, _R_co]) -> _Handler[_P, _R_co]: ... + +@type_check_only +class _ExceptionHandlerDecorator(Protocol): + def __call__(self, exception_handler: _ExceptionHandler[_R_co]) -> _ExceptionHandler[_R_co]: ... + +@type_check_only +class _SocketIOServerOptions(TypedDict, total=False): + client_manager: Incomplete + logger: Logger | bool + json: Incomplete + async_handlers: bool + always_connect: bool + +@type_check_only +class _EngineIOServerConfig(TypedDict, total=False): + async_mode: Literal["threading", "eventlet", "gevent", "gevent_uwsgi"] + ping_interval: float | tuple[float, float] # seconds + ping_timeout: float # seconds + max_http_buffer_size: int + allow_upgrades: bool + http_compression: bool + compression_threshold: int + cookie: str | dict[str, Any] | None + cors_allowed_origins: str | list[str] + cors_credentials: bool + monitor_clients: bool + engineio_logger: Logger | bool + +@type_check_only +class _SocketIOKwargs(_SocketIOServerOptions, _EngineIOServerConfig): ... + +class SocketIO: + # This is an alias for `socketio.Server.reason` in `python-socketio`, which is not typed. + reason: Incomplete + # Many instance attributes are deliberately not included here, + # as the maintainer of Flask-SocketIO considers them private, internal details: + # https://github.com/python/typeshed/pull/10735#discussion_r1330768869 + def __init__( + self, + app: Flask | None = None, + *, + # SocketIO options + manage_session: bool = True, + message_queue: str | None = None, + channel: str = "flask-socketio", + path: str = "socket.io", + resource: str = "socket.io", + **kwargs: Unpack[_SocketIOKwargs], + ) -> None: ... + def init_app( + self, + app: Flask, + *, + # SocketIO options + manage_session: bool = True, + message_queue: str | None = None, + channel: str = "flask-socketio", + path: str = "socket.io", + resource: str = "socket.io", + **kwargs: Unpack[_SocketIOKwargs], + ) -> None: ... + def on(self, message: str, namespace: str | None = None) -> _HandlerDecorator: ... + def on_error(self, namespace: str | None = None) -> _ExceptionHandlerDecorator: ... + def on_error_default(self, exception_handler: _ExceptionHandler[_R_co]) -> _ExceptionHandler[_R_co]: ... + def on_event(self, message: str, handler: _Handler[[Incomplete], object], namespace: str | None = None) -> None: ... + + @overload + def event(self, event_handler: _Handler[_P, _R_co], /) -> _Handler[_P, _R_co]: ... + @overload + def event(self, namespace: str | None = None, *args, **kwargs) -> _HandlerDecorator: ... + + def on_namespace(self, namespace_handler: Namespace) -> None: ... + def emit( + self, + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + include_self: bool = True, + skip_sid: str | list[str] | None = None, + callback: Callable[..., Incomplete] | None = None, + ) -> None: ... + def call( + self, + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + timeout: int = 60, # seconds + ignore_queue: bool = False, + ): ... + def send( + self, + data: Any, + json: bool = False, + namespace: str | None = None, + to: str | None = None, + callback: Callable[..., Incomplete] | None = None, + include_self: bool = True, + skip_sid: list[str] | str | None = None, + **kwargs, + ) -> None: ... + def close_room(self, room: str, namespace: str | None = None) -> None: ... + def run( + self, + app, + host: str | None = None, + port: int | None = None, + *, + debug: bool = True, + use_reloader: bool = ..., + reloader_options: dict[str, Incomplete] = {}, + log_output: bool = ..., + allow_unsafe_werkzeug: bool = False, + **kwargs, + ) -> None: ... + def stop(self) -> None: ... + def start_background_task(self, target: Callable[_P, None], *args: _P.args, **kwargs: _P.kwargs) -> Thread: ... + def sleep(self, seconds: int = 0): ... + def test_client( + self, + app: Flask, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + flask_test_client: FlaskClient | None = None, + ) -> SocketIOTestClient: ... + +def emit( + event: str, + *args, + namespace: str = "/", # / is the default (global) namespace + to: str | None = None, + include_self: bool = True, + skip_sid: str | list[str] | None = None, + callback: Callable[..., Incomplete] | None = None, + broadcast: bool = False, +) -> None: ... +def send(message: str, **kwargs) -> None: ... +def join_room(room: str, sid: str | None = None, namespace: str | None = None) -> None: ... +def leave_room(room: str, sid: str | None = None, namespace: str | None = None) -> None: ... +def close_room(room: str, namespace: str | None = None) -> None: ... +def rooms(sid: str | None = None, namespace: str | None = None) -> list[str]: ... +def disconnect(sid: str | None = None, namespace: str | None = None, silent: bool = False) -> None: ... diff --git a/stubs/Flask-SocketIO/flask_socketio/namespace.pyi b/stubs/Flask-SocketIO/flask_socketio/namespace.pyi new file mode 100644 index 000000000000..94ec7b716dd2 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/namespace.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Protocol, TypeVar, type_check_only + +_T = TypeVar("_T") + +# at runtime, socketio.namespace.BaseNamespace, but socketio isn't py.typed +@type_check_only +class _BaseNamespace(Protocol): + def is_asyncio_based(self) -> bool: ... + def trigger_event(self, event: str, *args): ... + +# at runtime, socketio.namespace.BaseNamespace, but socketio isn't py.typed +class _Namespace(_BaseNamespace, Protocol): + def emit( + self, + event: str, + data=None, + to=None, + room: str | None = None, + skip_sid=None, + namespace: str | None = None, + callback: Callable[..., Incomplete] | None = None, + ignore_queue: bool = False, + ): ... + def send( + self, + data, + to=None, + room: str | None = None, + skip_sid=None, + namespace: str | None = None, + callback: Callable[..., Incomplete] | None = None, + ignore_queue: bool = False, + ) -> None: ... + def call( + self, event: str, data=None, to=None, sid=None, namespace: str | None = None, timeout=None, ignore_queue: bool = False + ): ... + def enter_room(self, sid, room: str, namespace: str | None = None): ... + def leave_room(self, sid, room: str, namespace: str | None = None): ... + def close_room(self, room: str, namespace: str | None = None): ... + def rooms(self, sid, namespace: str | None = None): ... + def get_session(self, sid, namespace: str | None = None): ... + def save_session(self, sid, session, namespace: str | None = None): ... + def session(self, sid, namespace: str | None = None): ... + def disconnect(self, sid, namespace: str | None = None): ... + +class Namespace(_Namespace): + def __init__(self, namespace: str | None = None) -> None: ... + def trigger_event(self, event: str, *args): ... + def emit( # type: ignore[override] + self, + event: str, + data=None, + room: str | None = None, + include_self: bool = True, + namespace: str | None = None, + callback: Callable[..., _T] | None = None, + ) -> _T | tuple[str, int]: ... + def send( # type: ignore[override] + self, + data, + room: str | None = None, + include_self: bool = True, + namespace: str | None = None, + callback: Callable[..., Any] | None = None, + ) -> None: ... + def close_room(self, room: str, namespace: str | None = None) -> None: ... diff --git a/stubs/Flask-SocketIO/flask_socketio/test_client.pyi b/stubs/Flask-SocketIO/flask_socketio/test_client.pyi new file mode 100644 index 000000000000..15cf426959a0 --- /dev/null +++ b/stubs/Flask-SocketIO/flask_socketio/test_client.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from typing import Any, TypedDict, type_check_only + +from flask import Flask +from flask.testing import FlaskClient + +@type_check_only +class _Packet(TypedDict): + name: str + args: Any + namespace: str + +class SocketIOTestClient: + def __init__( + self, + app: Flask, + socketio, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + flask_test_client: FlaskClient | None = None, + ) -> None: ... + def is_connected(self, namespace: str | None = None) -> bool: ... + def connect( + self, + namespace: str | None = None, + query_string: str | None = None, + headers: dict[str, Incomplete] | None = None, + auth: dict[str, Incomplete] | None = None, + ) -> None: ... + def disconnect(self, namespace: str | None = None) -> None: ... + def emit(self, event: str, *args, callback: bool = False, namespace: str | None = None) -> Incomplete | None: ... + def send( + self, + data: str | dict[str, Incomplete] | list[Incomplete], + json: bool = False, + callback: bool = False, + namespace: str | None = None, + ): ... + def get_received(self, namespace: str | None = None) -> list[_Packet]: ... diff --git a/stubs/JACK-Client/@tests/stubtest_allowlist.txt b/stubs/JACK-Client/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5a7c05f46db9 --- /dev/null +++ b/stubs/JACK-Client/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# The available constants differ based on the local environment. +(jack\.METADATA_.*)? diff --git a/stubs/JACK-Client/METADATA.toml b/stubs/JACK-Client/METADATA.toml new file mode 100644 index 000000000000..b192bf639cf1 --- /dev/null +++ b/stubs/JACK-Client/METADATA.toml @@ -0,0 +1,14 @@ +version = "0.5.*" +upstream-repository = "https://github.com/spatialaudio/jackclient-python" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20", "types-cffi"] + +[tool.stubtest] +# darwin and win32 are equivalent +# TODO (2026-06-26): darwin temporarily disabled, see +# https://github.com/python/typeshed/issues/15947 +ci-platforms = ["linux"] +apt-dependencies = ["libjack-dev"] +brew-dependencies = ["jack"] +# No need to install on the CI. Leaving here as information for Windows contributors. +# choco-dependencies = ["jack"] diff --git a/stubs/JACK-Client/jack/__init__.pyi b/stubs/JACK-Client/jack/__init__.pyi new file mode 100644 index 000000000000..18a33f2cc219 --- /dev/null +++ b/stubs/JACK-Client/jack/__init__.pyi @@ -0,0 +1,341 @@ +from _typeshed import Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from typing import Any, Final, Literal, overload, type_check_only +from typing_extensions import Never, Self + +import numpy +from _cffi_backend import _CDataBase +from numpy.typing import NDArray + +# Aka jack_position_t +# Actual type: _cffi_backend.__CDataOwn +# This is not a real subclassing. Just ensuring type-checkers sees this type as compatible with _CDataBase +# pyright has no error code for subclassing final +@type_check_only +class _JackPositionT(_CDataBase): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] # pyrefly: ignore [invalid-inheritance] + audio_frames_per_video_frame: float + bar: int + bar_start_tick: float + bbt_offset: int + beat: int + beat_type: float + beats_per_bar: float + beats_per_minute: float + frame: int + frame_rate: int + frame_time: float + next_time: float + padding: _CDataBase # + tick: int + ticks_per_beat: float + unique_1: int + unique_2: int + usecs: int + valid: int + video_offset: int + +@type_check_only +class _CBufferType: + @overload + def __getitem__(self, key: int) -> str: ... + @overload + def __getitem__(self, key: slice) -> bytes: ... + + @overload + def __setitem__(self, key: int, val: str) -> None: ... + @overload + def __setitem__(self, key: slice, val: bytes) -> None: ... + + def __len__(self) -> int: ... + def __bytes__(self) -> bytes: ... + +STOPPED: int +ROLLING: int +STARTING: int +NETSTARTING: int +PROPERTY_CREATED: int +PROPERTY_CHANGED: int +PROPERTY_DELETED: int +POSITION_BBT: int +POSITION_TIMECODE: int +POSITION_BBT_FRAME_OFFSET: int +POSITION_AUDIO_VIDEO_RATIO: int +POSITION_VIDEO_FRAME_OFFSET: int + +class JackError(Exception): ... + +class JackErrorCode(JackError): + def __init__(self, message: str, code: int) -> None: ... + message: str + code: int + +class JackOpenError(JackError): + def __init__(self, name: str, status: Status) -> None: ... + name: str + status: Status + +class Client: + def __init__( + self, + name: str, + use_exact_name: bool = False, + no_start_server: bool = False, + servername: str | None = None, + session_id: str | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def __del__(self) -> None: ... + @property + def name(self) -> str: ... + @property + def uuid(self) -> str: ... + @property + def samplerate(self) -> int: ... + + @property + def blocksize(self) -> int: ... + @blocksize.setter + def blocksize(self, blocksize: int) -> None: ... + + @property + def status(self) -> Status: ... + @property + def realtime(self) -> bool: ... + @property + def frames_since_cycle_start(self) -> int: ... + @property + def frame_time(self) -> int: ... + @property + def last_frame_time(self) -> int: ... + @property + def inports(self) -> Ports: ... + @property + def outports(self) -> Ports: ... + @property + def midi_inports(self) -> Ports: ... + @property + def midi_outports(self) -> Ports: ... + def owns(self, port: str | Port) -> bool: ... + def activate(self) -> None: ... + def deactivate(self, ignore_errors: bool = True) -> None: ... + def cpu_load(self) -> float: ... + def close(self, ignore_errors: bool = True) -> None: ... + def connect(self, source: str | Port, destination: str | Port) -> None: ... + def disconnect(self, source: str | Port, destination: str | Port) -> None: ... + def transport_start(self) -> None: ... + def transport_stop(self) -> None: ... + @property + def transport_state(self) -> TransportState: ... + + @property + def transport_frame(self) -> int: ... + @transport_frame.setter + def transport_frame(self, frame: int) -> None: ... + + def transport_locate(self, frame: int) -> None: ... + def transport_query(self) -> tuple[TransportState, dict[str, Any]]: ... # Anyof[int, float, _CDataBase] + def transport_query_struct(self) -> tuple[TransportState, _JackPositionT]: ... + def transport_reposition_struct(self, position: _JackPositionT) -> None: ... + def set_sync_timeout(self, timeout: int) -> None: ... + def set_freewheel(self, onoff: bool) -> None: ... + def set_shutdown_callback(self, callback: Callable[[Status, str], object]) -> None: ... + def set_process_callback(self, callback: Callable[[int], object]) -> None: ... + def set_freewheel_callback(self, callback: Callable[[bool], object]) -> None: ... + def set_blocksize_callback(self, callback: Callable[[int], object]) -> None: ... + def set_samplerate_callback(self, callback: Callable[[int], object]) -> None: ... + def set_client_registration_callback(self, callback: Callable[[str, bool], object]) -> None: ... + def set_port_registration_callback( + self, callback: Callable[[Port, bool], object] | None = None, only_available: bool = True + ) -> None: ... + def set_port_connect_callback( + self, callback: Callable[[Port, Port, bool], object] | None = None, only_available: bool = True + ) -> None: ... + def set_port_rename_callback( + self, callback: Callable[[Port, str, str], object] | None = None, only_available: bool = True + ) -> None: ... + def set_graph_order_callback(self, callback: Callable[[], object]) -> None: ... + def set_xrun_callback(self, callback: Callable[[float], object]) -> None: ... + def set_sync_callback(self, callback: Callable[[int, _JackPositionT], object] | None) -> None: ... + def release_timebase(self) -> None: ... + def set_timebase_callback( + self, callback: Callable[[int, int, _JackPositionT, bool], object] | None = None, conditional: bool = False + ) -> bool: ... + def set_property_change_callback(self, callback: Callable[[int, str, int], object]) -> None: ... + def get_uuid_for_client_name(self, name: str) -> str: ... + def get_client_name_by_uuid(self, uuid: str) -> str: ... + def get_port_by_name(self, name: str) -> Port: ... + def get_all_connections(self, port: Port) -> list[Port]: ... + def get_ports( + self, + name_pattern: str = "", + is_audio: bool = False, + is_midi: bool = False, + is_input: bool = False, + is_output: bool = False, + is_physical: bool = False, + can_monitor: bool = False, + is_terminal: bool = False, + ) -> list[Port]: ... + def set_property(self, subject: int | str, key: str, value: str | bytes, type: str = "") -> None: ... + def remove_property(self, subject: int | str, key: str) -> None: ... + def remove_properties(self, subject: int | str) -> int: ... + def remove_all_properties(self) -> None: ... + +class Port: + # + def __init__(self, port_ptr: _CDataBase, client: Client) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + @property + def name(self) -> str: ... + + @property + def shortname(self) -> str: ... + @shortname.setter + def shortname(self, shortname: str) -> None: ... + + @property + def aliases(self) -> list[str]: ... + def set_alias(self, alias: str) -> None: ... + def unset_alias(self, alias: str) -> None: ... + @property + def uuid(self) -> int: ... + @property + def is_audio(self) -> bool: ... + @property + def is_midi(self) -> bool: ... + @property + def is_input(self) -> bool: ... + @property + def is_output(self) -> bool: ... + @property + def is_physical(self) -> bool: ... + @property + def can_monitor(self) -> bool: ... + @property + def is_terminal(self) -> bool: ... + def request_monitor(self, onoff: bool) -> None: ... + +class MidiPort(Port): + @property + def is_audio(self) -> Literal[False]: ... + @property + def is_midi(self) -> Literal[True]: ... + +class OwnPort(Port): + @property + def number_of_connections(self) -> int: ... + @property + def connections(self) -> list[Port]: ... + def is_connected_to(self, port: str | Port) -> bool: ... + def connect(self, port: str | Port) -> None: ... + def disconnect(self, other: str | Port | None = None) -> None: ... + def unregister(self) -> None: ... + def get_buffer(self) -> _CBufferType: ... + def get_array(self) -> NDArray[numpy.float32]: ... + +class OwnMidiPort(MidiPort, OwnPort): + def __init__(self, port_ptr: _CDataBase, client: Client) -> None: ... + # The implementation raises NotImplementedError, but this is not an abstract class. + # `get_buffer()` and `get_array()` are disabled for OwnMidiPort + def get_buffer(self) -> Never: ... + def get_array(self) -> Never: ... + @property + def max_event_size(self) -> int: ... + @property + def lost_midi_events(self) -> int: ... + def incoming_midi_events(self) -> Generator[tuple[int, _CBufferType]]: ... + def clear_buffer(self) -> None: ... + def write_midi_event(self, time: int, event: bytes | Sequence[int] | _CBufferType) -> None: ... + def reserve_midi_event(self, time: int, size: int) -> _CBufferType: ... + +class Ports: + def __init__(self, client: Client, porttype: str, flag: int) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, name: str) -> Port: ... + def __iter__(self) -> Iterator[Port]: ... + def register(self, shortname: str, is_terminal: bool = False, is_physical: bool = False) -> Port: ... + def clear(self) -> None: ... + +class RingBuffer: + def __init__(self, size: int) -> None: ... + @property + def write_space(self) -> int: ... + def write(self, data: bytes | Iterable[int] | _CBufferType) -> int: ... + @property + def write_buffers(self) -> tuple[_CBufferType, _CBufferType]: ... + def write_advance(self, size: int) -> None: ... + @property + def read_space(self) -> int: ... + def read(self, size: int) -> _CBufferType: ... + def peek(self, size: int) -> _CBufferType: ... + @property + def read_buffers(self) -> tuple[_CBufferType, _CBufferType]: ... + def read_advance(self, size: int) -> None: ... + def mlock(self) -> None: ... + def reset(self, size: int | None = None) -> None: ... + @property + def size(self) -> int: ... + +class Status: + __slots__ = "_code" + def __init__(self, code: int) -> None: ... + @property + def failure(self) -> bool: ... + @property + def invalid_option(self) -> bool: ... + @property + def name_not_unique(self) -> bool: ... + @property + def server_started(self) -> bool: ... + @property + def server_failed(self) -> bool: ... + @property + def server_error(self) -> bool: ... + @property + def no_such_client(self) -> bool: ... + @property + def load_failure(self) -> bool: ... + @property + def init_failure(self) -> bool: ... + @property + def shm_failure(self) -> bool: ... + @property + def version_error(self) -> bool: ... + @property + def backend_error(self) -> bool: ... + @property + def client_zombie(self) -> bool: ... + +class TransportState: + __slots__ = "_code" + def __init__(self, code: int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class CallbackExit(Exception): ... + +def get_property(subject: int | str, key: str) -> tuple[bytes, str] | None: ... +def get_properties(subject: int | str) -> dict[str, tuple[bytes, str]]: ... +def get_all_properties() -> dict[int, dict[str, tuple[bytes, str]]]: ... +def position2dict(pos: _JackPositionT) -> dict[str, Any]: ... # Anyof[int, float, _CDataBase] +def version() -> tuple[int, int, int, int]: ... +def version_string() -> str: ... +def client_name_size() -> int: ... +def port_name_size() -> int: ... +def set_error_function(callback: Callable[[str], object] | None = None) -> None: ... +def set_info_function(callback: Callable[[str], object] | None = None) -> None: ... +def client_pid(name: str) -> int: ... + +# Some METADATA_ constants are not available on all systems. +METADATA_CONNECTED: Final[str] +METADATA_HARDWARE: Final[str] +METADATA_ICON_LARGE: Final[str] +METADATA_ICON_SMALL: Final[str] +METADATA_PORT_GROUP: Final[str] +METADATA_PRETTY_NAME: Final[str] +METADATA_EVENT_TYPES: Final[str] +METADATA_ICON_NAME: Final[str] +METADATA_ORDER: Final[str] +METADATA_SIGNAL_TYPE: Final[str] diff --git a/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt b/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0349b7eb0656 --- /dev/null +++ b/stubs/Jetson.GPIO/@tests/stubtest_allowlist.txt @@ -0,0 +1,9 @@ +# stubtest produces false positives for Jetson.GPIO-related modules in CI +# The high-level Jetson.GPIO library can only be imported on Jetson SBC, +# and requires specific system permissions (/dev/gpiochip0 access). +Jetson.GPIO +Jetson.GPIO.gpio +Jetson.GPIO.gpio_pinmux_lookup + +# This builtin error doesn't need to be re-exported +Jetson.GPIO.gpio_event.InterruptedError diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi new file mode 100644 index 000000000000..9c7fe6b35466 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/__init__.pyi @@ -0,0 +1,3 @@ +from .gpio import * + +VERSION: str = ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi new file mode 100644 index 000000000000..8de69f455183 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/constants.pyi @@ -0,0 +1,22 @@ +from typing import Final + +BOARD: Final = 10 +BCM: Final = 11 +TEGRA_SOC: Final = 1000 +CVM: Final = 1001 + +PUD_OFF: Final = 20 +PUD_DOWN: Final = 21 +PUD_UP: Final = 22 + +HIGH: Final = 1 +LOW: Final = 0 + +RISING: Final = 31 +FALLING: Final = 32 +BOTH: Final = 33 + +UNKNOWN: Final = -1 +OUT: Final = 0 +IN: Final = 1 +HARD_PWM: Final = 43 diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi new file mode 100644 index 000000000000..902334cf2eb4 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio.pyi @@ -0,0 +1,44 @@ +from collections.abc import Callable, Sequence +from typing import Literal + +from .constants import * + +model = ... +JETSON_INFO = ... +RPI_INFO = ... + +def setwarnings(state: bool) -> None: ... +def setmode(mode: Literal[10, 11, 1000, 1001]) -> None: ... +def getmode() -> Literal[10, 11, 1000, 1001]: ... +def setup( + channels: int | Sequence[int], + direction: Literal[0, 1], + pull_up_down: Literal[20, 21, 22] = ..., + initial: Literal[0, 1] = ..., + consumer: str = ..., +) -> None: ... +def cleanup(channel: int | Sequence[int] | None = ...) -> None: ... +def input(channel: int) -> Literal[0, 1]: ... +def output(channels: int | Sequence[int], values: Literal[0, 1]) -> None: ... +def add_event_detect( + channel: int, + edge: Literal[31, 32, 33], + callback: Callable[[int], None] | None = ..., + bouncetime: int | None = ..., + polltime: float = 0.2, +) -> None: ... +def remove_event_detect(channel: int, timeout: float = 0.5) -> None: ... +def event_detected(channel: int) -> bool: ... +def add_event_callback(channel: int, callback: Callable[[int], None]) -> None: ... +def wait_for_edge( + channel: int, edge: Literal[31, 32, 33], bouncetime: int | None = ..., timeout: float | None = ... +) -> int | None: ... +def gpio_function(channel: int) -> Literal[-1, 0, 1]: ... + +class PWM: + def __init__(self, channel: int, frequency_hz: float) -> None: ... + def __del__(self) -> None: ... + def start(self, duty_cycle_percent: float) -> None: ... + def ChangeFrequency(self, frequency_hz: float) -> None: ... + def ChangeDutyCycle(self, duty_cycle_percent: float) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi new file mode 100644 index 000000000000..20a8b6121349 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_cdev.pyi @@ -0,0 +1,84 @@ +import ctypes +from dataclasses import dataclass +from typing import Final, Literal + +from .gpio_pin_data import ChannelInfo + +GPIO_HIGH: Final = 1 + +GPIOHANDLE_REQUEST_INPUT: Final = 0x1 +GPIOHANDLE_REQUEST_OUTPUT: Final = 0x2 + +GPIOEVENT_REQUEST_RISING_EDGE: Final = 0x1 +GPIOEVENT_REQUEST_FALLING_EDGE: Final = 0x2 +GPIOEVENT_REQUEST_BOTH_EDGES: Final = 0x3 + +GPIO_GET_CHIPINFO_IOCTL: Final = 0x8044B401 +GPIO_GET_LINEINFO_IOCTL: Final = 0xC048B402 +GPIO_GET_LINEHANDLE_IOCTL: Final = 0xC16CB403 +GPIOHANDLE_GET_LINE_VALUES_IOCTL: Final = 0xC040B408 +GPIOHANDLE_SET_LINE_VALUES_IOCTL: Final = 0xC040B409 +GPIO_GET_LINEEVENT_IOCTL: Final = 0xC030B404 + +class gpiochip_info(ctypes.Structure): + name: str + label: str + lines: int + +class gpiohandle_request(ctypes.Structure): + lineoffsets: list[int] + flags: int + default_values: list[int] + consumer_label: str + lines: int + fd: int + +class gpiohandle_data(ctypes.Structure): + values: list[int] + +class gpioline_info(ctypes.Structure): + line_offset: int + flags: int + name: str + consumer: str + +class gpioline_info_changed(ctypes.Structure): + line_info: gpioline_info + timestamp: int + event_type: int + padding: list[int] + +class gpioevent_request(ctypes.Structure): + lineoffset: int + handleflags: int + eventflags: int + consumer_label: str + fd: int + +class gpioevent_data(ctypes.Structure): + timestamp: int + id: int + +class GPIOError(IOError): ... + +def chip_open(gpio_chip: str) -> int: ... +def chip_check_info(label: str, gpio_device: str) -> int | None: ... +def chip_open_by_label(label: str) -> int: ... +def close_chip(chip_fd: int) -> None: ... +def open_line(ch_info: ChannelInfo, request: int) -> None: ... +def close_line(line_handle: int) -> None: ... +def request_handle(line_offset: int, direction: Literal[0, 1], initial: Literal[0, 1], consumer: str) -> gpiohandle_request: ... +def request_event(line_offset: int, edge: int, consumer: str) -> gpioevent_request: ... +def get_value(line_handle: int) -> int: ... +def set_value(line_handle: int, value: int) -> None: ... + +@dataclass +class PadCtlRegister: + is_gpio: bool + is_input: bool + is_tristate: bool + def __init__(self, value: int) -> None: ... + @property + def is_bidi(self) -> bool: ... + +def check_pinmux(ch_info: ChannelInfo, direction: int) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi new file mode 100644 index 000000000000..8e470cba9ed5 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_event.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from typing import Any, Final, Literal + +NO_EDGE: Final = 0 +RISING_EDGE: Final = 1 +FALLING_EDGE: Final = 2 +BOTH_EDGE: Final = 3 + +def add_edge_detect( + chip_fd: int, chip_name: str, channel: int, request: int, bouncetime: int, poll_time: float +) -> Literal[1, 2, 0]: ... +def remove_edge_detect(chip_name: str, channel: int, timeout: float = 0.3) -> None: ... +def add_edge_callback(chip_name: str, channel: int, callback: Callable[[int], None]) -> None: ... +def edge_event_detected(chip_name: str, channel: int) -> bool: ... +def gpio_event_added(chip_name: str, channel: int) -> Any: ... +def blocking_wait_for_edge(chip_fd: int, chip_name: str, channel: int, request: int, bouncetime: int, timeout: float) -> int: ... +def event_cleanup(chip_name: str, channel: int) -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi new file mode 100644 index 000000000000..364e5ce79838 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pin_data.pyi @@ -0,0 +1,81 @@ +from collections.abc import Sequence +from typing import Any, Final + +CLARA_AGX_XAVIER: Final = "CLARA_AGX_XAVIER" +JETSON_NX: Final = "JETSON_NX" +JETSON_XAVIER: Final = "JETSON_XAVIER" +JETSON_TX2: Final = "JETSON_TX2" +JETSON_TX1: Final = "JETSON_TX1" +JETSON_NANO: Final = "JETSON_NANO" +JETSON_TX2_NX: Final = "JETSON_TX2_NX" +JETSON_ORIN: Final = "JETSON_ORIN" +JETSON_ORIN_NX: Final = "JETSON_ORIN_NX" +JETSON_ORIN_NANO: Final = "JETSON_ORIN_NANO" +JETSON_THOR_REFERENCE: Final = "JETSON_THOR_REFERENCE" + +JETSON_MODELS: list[str] + +JETSON_ORIN_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +compats_jetson_orins_nx: Sequence[str] +compats_jetson_orins_nano: Sequence[str] + +JETSON_ORIN_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +compats_jetson_orins: Sequence[str] + +CLARA_AGX_XAVIER_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_clara_agx_xavier: Sequence[str] + +JETSON_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_nx: Sequence[str] + +JETSON_XAVIER_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_xavier: Sequence[str] + +JETSON_TX2_NX_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx2_nx: Sequence[str] + +JETSON_TX2_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx2: Sequence[str] + +JETSON_TX1_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_tx1: Sequence[str] + +JETSON_NANO_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_nano: Sequence[str] + +JETSON_THOR_REFERENCE_PIN_DEFS: list[tuple[int, str, str, int, int, str, str, str | None, int | None]] +compats_jetson_thor_reference: Sequence[str] + +jetson_gpio_data: dict[str, tuple[list[tuple[int, str, str, int, int, str, str, str | None, int | None]], dict[str, Any]]] + +class ChannelInfo: + channel: int + chip_fd: int | None + line_handle: int | None + line_offset: int + direction: int | None + edge: int | None + consumer: str + gpio_name: str + gpio_chip: str + pwm_chip_dir: str + pwm_id: int + reg_addr: int | None + def __init__( + self, + channel: int, + line_offset: int, + gpio_name: str, + gpio_chip: str, + pwm_chip_dir: str, + pwm_id: int, + reg_addr: int | None = None, + ) -> None: ... + +ids_warned: bool + +def find_pmgr_board(prefix: str) -> str | None: ... +def warn_if_not_carrier_board(*carrier_boards: str) -> None: ... +def get_compatibles(compatible_path: str) -> list[str]: ... +def get_model() -> str: ... +def get_data() -> tuple[str, Any, dict[str, dict[Any, ChannelInfo]]]: ... diff --git a/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi new file mode 100644 index 000000000000..1cffa0bf2012 --- /dev/null +++ b/stubs/Jetson.GPIO/Jetson/GPIO/gpio_pinmux_lookup.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterable + +def lookup_mux_register( + gpio_pin: int, pin_defs: Iterable[tuple[int, str, str, int, int, str, str, str | None, int | None, int]] +) -> int: ... +def main() -> None: ... diff --git a/stubs/Jetson.GPIO/Jetson/__init__.pyi b/stubs/Jetson.GPIO/Jetson/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Jetson.GPIO/METADATA.toml b/stubs/Jetson.GPIO/METADATA.toml new file mode 100644 index 000000000000..d5b6d8358e23 --- /dev/null +++ b/stubs/Jetson.GPIO/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.1.13" +upstream-repository = "https://github.com/NVIDIA/jetson-gpio" diff --git a/stubs/Markdown/@tests/stubtest_allowlist.txt b/stubs/Markdown/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..1523b9aa78d0 --- /dev/null +++ b/stubs/Markdown/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# Deprecated types are infered as functions: +markdown.extensions.abbr.AbbrPreprocessor +markdown.extensions.abbr.AbbrInlineProcessor +markdown.postprocessors.UnescapePostprocessor diff --git a/stubs/Markdown/METADATA.toml b/stubs/Markdown/METADATA.toml new file mode 100644 index 000000000000..1e61a2413cbb --- /dev/null +++ b/stubs/Markdown/METADATA.toml @@ -0,0 +1,2 @@ +version = "~=3.10.2" +upstream-repository = "https://github.com/Python-Markdown/markdown" diff --git a/stubs/Markdown/markdown/__init__.pyi b/stubs/Markdown/markdown/__init__.pyi new file mode 100644 index 000000000000..f9e1394976fb --- /dev/null +++ b/stubs/Markdown/markdown/__init__.pyi @@ -0,0 +1,5 @@ +from .__meta__ import __version__ as __version__, __version_info__ as __version_info__ +from .core import Markdown as Markdown, markdown as markdown, markdownFromFile as markdownFromFile +from .extensions import Extension as Extension + +__all__ = ["Markdown", "markdown", "markdownFromFile"] diff --git a/stubs/Markdown/markdown/__main__.pyi b/stubs/Markdown/markdown/__main__.pyi new file mode 100644 index 000000000000..ca90cb1fa7f1 --- /dev/null +++ b/stubs/Markdown/markdown/__main__.pyi @@ -0,0 +1,10 @@ +import optparse +from logging import Logger +from typing import Any + +logger: Logger + +def parse_options( + args: list[str] | None = None, values: optparse.Values | None = None +) -> tuple[dict[str, Any], Any]: ... # first item is opts dict, second item is Values.verbose field +def run() -> None: ... diff --git a/stubs/Markdown/markdown/__meta__.pyi b/stubs/Markdown/markdown/__meta__.pyi new file mode 100644 index 000000000000..9fb408997220 --- /dev/null +++ b/stubs/Markdown/markdown/__meta__.pyi @@ -0,0 +1,2 @@ +__version_info__: tuple[int, int, int, str, int] +__version__: str diff --git a/stubs/Markdown/markdown/blockparser.pyi b/stubs/Markdown/markdown/blockparser.pyi new file mode 100644 index 000000000000..805eb13c47c3 --- /dev/null +++ b/stubs/Markdown/markdown/blockparser.pyi @@ -0,0 +1,23 @@ +from collections.abc import Iterable +from typing import Any, TypeVar +from xml.etree.ElementTree import Element, ElementTree + +from markdown import blockprocessors as _blockprocessors, util +from markdown.core import Markdown + +_T = TypeVar("_T") + +class State(list[_T]): + def set(self, state: _T) -> None: ... + def reset(self) -> None: ... + def isstate(self, state: _T) -> bool: ... + +class BlockParser: + blockprocessors: util.Registry[_blockprocessors.BlockProcessor] + state: State[Any] # TODO: possible to get rid of Any? + md: Markdown + def __init__(self, md: Markdown) -> None: ... + root: Element + def parseDocument(self, lines: Iterable[str]) -> ElementTree: ... + def parseChunk(self, parent: Element, text: str) -> None: ... + def parseBlocks(self, parent: Element, blocks: list[str]) -> None: ... diff --git a/stubs/Markdown/markdown/blockprocessors.pyi b/stubs/Markdown/markdown/blockprocessors.pyi new file mode 100644 index 000000000000..0b9461c82134 --- /dev/null +++ b/stubs/Markdown/markdown/blockprocessors.pyi @@ -0,0 +1,67 @@ +from logging import Logger +from re import Match, Pattern +from typing import Any, ClassVar +from xml.etree.ElementTree import Element + +from markdown.blockparser import BlockParser +from markdown.core import Markdown + +logger: Logger + +def build_block_parser(md: Markdown, **kwargs: Any) -> BlockParser: ... + +class BlockProcessor: + parser: BlockParser + tab_length: int + def __init__(self, parser: BlockParser) -> None: ... + def lastChild(self, parent: Element) -> Element | None: ... + def detab(self, text: str, length: int | None = None) -> tuple[str, str]: ... + def looseDetab(self, text: str, level: int = 1) -> str: ... + def test(self, parent: Element, block: str) -> bool: ... + def run(self, parent: Element, blocks: list[str]) -> bool | None: ... + +class ListIndentProcessor(BlockProcessor): + ITEM_TYPES: list[str] + LIST_TYPES: list[str] + INDENT_RE: Pattern[str] + def __init__(self, parser: BlockParser) -> None: ... # Note: This was done because the args are sent as-is. + def create_item(self, parent: Element, block: str) -> None: ... + def get_level(self, parent: Element, block: str) -> tuple[int, Element]: ... + +class CodeBlockProcessor(BlockProcessor): ... + +class BlockQuoteProcessor(BlockProcessor): + RE: Pattern[str] + def clean(self, line: str) -> str: ... + +class OListProcessor(BlockProcessor): + TAG: ClassVar[str] + STARTSWITH: ClassVar[str] + LAZY_OL: ClassVar[bool] + SIBLING_TAGS: ClassVar[list[str]] + RE: Pattern[str] + CHILD_RE: Pattern[str] + INDENT_RE: Pattern[str] + def __init__(self, parser: BlockParser) -> None: ... + def get_items(self, block: str) -> list[str]: ... + +class UListProcessor(OListProcessor): + def __init__(self, parser: BlockParser) -> None: ... + +class HashHeaderProcessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + +class SetextHeaderProcessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + +class HRProcessor(BlockProcessor): + RE: ClassVar[str] + SEARCH_RE: ClassVar[Pattern[str]] + match: Match[str] + +class EmptyBlockProcessor(BlockProcessor): ... + +class ReferenceProcessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + +class ParagraphProcessor(BlockProcessor): ... diff --git a/stubs/Markdown/markdown/core.pyi b/stubs/Markdown/markdown/core.pyi new file mode 100644 index 000000000000..98972399f1ea --- /dev/null +++ b/stubs/Markdown/markdown/core.pyi @@ -0,0 +1,75 @@ +from codecs import _ReadableStream, _WritableStream +from collections.abc import Callable, Mapping, Sequence +from logging import Logger +from typing import Any, ClassVar, Literal +from typing_extensions import Self +from xml.etree.ElementTree import Element + +from . import ( + blockparser, + inlinepatterns, + postprocessors as _postprocessors, + preprocessors as _preprocessors, + treeprocessors as _treeprocessors, +) +from .extensions import Extension +from .util import HtmlStash, Registry + +__all__ = ["Markdown", "markdown", "markdownFromFile"] + +logger: Logger + +class Markdown: + preprocessors: Registry[_preprocessors.Preprocessor] + inlinePatterns: Registry[inlinepatterns.Pattern] + treeprocessors: Registry[_treeprocessors.Treeprocessor] + postprocessors: Registry[_postprocessors.Postprocessor] + parser: blockparser.BlockParser + htmlStash: HtmlStash + output_formats: ClassVar[dict[Literal["xhtml", "html"], Callable[[Element], str]]] + output_format: Literal["xhtml", "html"] + serializer: Callable[[Element], str] + tab_length: int + block_level_elements: list[str] + registeredExtensions: list[Extension] + ESCAPED_CHARS: list[str] + doc_tag: ClassVar[str] + stripTopLevelTags: bool + def __init__( + self, + *, + extensions: Sequence[str | Extension] | None = ..., + extension_configs: Mapping[str, Mapping[str, Any]] | None = ..., + output_format: Literal["xhtml", "html"] | None = ..., + tab_length: int | None = ..., + ) -> None: ... + def build_parser(self) -> Self: ... + def registerExtensions(self, extensions: Sequence[Extension | str], configs: Mapping[str, dict[str, Any]]) -> Self: ... + def build_extension(self, ext_name: str, configs: Mapping[str, Any]) -> Extension: ... + def registerExtension(self, extension: Extension) -> Self: ... + def reset(self) -> Self: ... + def set_output_format(self, format: Literal["xhtml", "html"]) -> Self: ... + def is_block_level(self, tag: object) -> bool: ... + def convert(self, source: str) -> str: ... + def convertFile( + self, input: str | _ReadableStream | None = None, output: str | _WritableStream | None = None, encoding: str | None = None + ) -> Self: ... + +def markdown( + text: str, + *, + extensions: Sequence[str | Extension] | None = ..., + extension_configs: Mapping[str, Mapping[str, Any]] | None = ..., + output_format: Literal["xhtml", "html"] | None = ..., + tab_length: int | None = ..., +) -> str: ... +def markdownFromFile( + *, + input: str | _ReadableStream | None = ..., + output: str | _WritableStream | None = ..., + encoding: str | None = ..., + extensions: Sequence[str | Extension] | None = ..., + extension_configs: Mapping[str, Mapping[str, Any]] | None = ..., + output_format: Literal["xhtml", "html"] | None = ..., + tab_length: int | None = ..., +) -> None: ... diff --git a/stubs/Markdown/markdown/extensions/__init__.pyi b/stubs/Markdown/markdown/extensions/__init__.pyi new file mode 100644 index 000000000000..2ae632654e0f --- /dev/null +++ b/stubs/Markdown/markdown/extensions/__init__.pyi @@ -0,0 +1,14 @@ +from collections.abc import Iterable, Mapping +from typing import Any + +from markdown.core import Markdown + +class Extension: + config: Mapping[str, list[Any]] + def __init__(self, **kwargs: Any) -> None: ... + def getConfig(self, key: str, default: Any = "") -> Any: ... + def getConfigs(self) -> dict[str, Any]: ... + def getConfigInfo(self) -> list[tuple[str, str]]: ... + def setConfig(self, key: str, value: Any) -> None: ... + def setConfigs(self, items: Mapping[str, Any] | Iterable[tuple[str, Any]]) -> None: ... + def extendMarkdown(self, md: Markdown) -> None: ... diff --git a/stubs/Markdown/markdown/extensions/abbr.pyi b/stubs/Markdown/markdown/extensions/abbr.pyi new file mode 100644 index 000000000000..810ab601625f --- /dev/null +++ b/stubs/Markdown/markdown/extensions/abbr.pyi @@ -0,0 +1,39 @@ +from re import Pattern +from typing import ClassVar +from typing_extensions import deprecated +from xml.etree.ElementTree import Element + +from markdown.blockparser import BlockParser +from markdown.blockprocessors import BlockProcessor +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.inlinepatterns import InlineProcessor +from markdown.treeprocessors import Treeprocessor + +class AbbrExtension(Extension): + def reset(self) -> None: ... + def reset_glossary(self) -> None: ... + def load_glossary(self, dictionary: dict[str, str]) -> None: ... + +class AbbrTreeprocessor(Treeprocessor): + RE: Pattern[str] | None + abbrs: dict[str, str] + def __init__(self, md: Markdown | None = None, abbrs: dict[str, str] | None = None) -> None: ... + def create_element(self, title: str, text: str, tail: str) -> Element: ... + def iter_element(self, el: Element, parent: Element | None = None) -> None: ... + +# Techinically it is the same type as `AbbrPreprocessor` just not deprecated. +class AbbrBlockprocessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + abbrs: dict[str, str] + def __init__(self, parser: BlockParser, abbrs: dict[str, str]) -> None: ... + +@deprecated("This class will be removed in the future; use `AbbrTreeprocessor` instead.") +class AbbrPreprocessor(AbbrBlockprocessor): ... + +@deprecated("This class will be removed in the future; use `AbbrTreeprocessor` instead.") +class AbbrInlineProcessor(InlineProcessor): + title: str + def __init__(self, pattern: str, title: str) -> None: ... + +def makeExtension(**kwargs) -> AbbrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/admonition.pyi b/stubs/Markdown/markdown/extensions/admonition.pyi new file mode 100644 index 000000000000..0225c528edd7 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/admonition.pyi @@ -0,0 +1,22 @@ +from re import Match, Pattern +from typing import ClassVar +from xml.etree.ElementTree import Element + +from markdown import blockparser +from markdown.blockprocessors import BlockProcessor +from markdown.extensions import Extension + +class AdmonitionExtension(Extension): ... + +class AdmonitionProcessor(BlockProcessor): + CLASSNAME: str + CLASSNAME_TITLE: str + RE: ClassVar[Pattern[str]] + RE_SPACES: ClassVar[Pattern[str]] + current_sibling: Element | None + content_indent: int + def __init__(self, parser: blockparser.BlockParser) -> None: ... + def parse_content(self, parent: Element, block: str) -> tuple[Element | None, str, str]: ... + def get_class_and_title(self, match: Match[str]) -> tuple[str, str | None]: ... + +def makeExtension(**kwargs) -> AdmonitionExtension: ... diff --git a/stubs/Markdown/markdown/extensions/attr_list.pyi b/stubs/Markdown/markdown/extensions/attr_list.pyi new file mode 100644 index 000000000000..0a837e583259 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/attr_list.pyi @@ -0,0 +1,23 @@ +from re import Pattern +from xml.etree.ElementTree import Element + +from markdown.extensions import Extension +from markdown.treeprocessors import Treeprocessor + +def get_attrs_and_remainder(attrs_string: str) -> tuple[list[tuple[str, str]], str]: ... +def get_attrs(str: str) -> list[tuple[str, str]]: ... +def isheader(elem: Element) -> bool: ... + +class AttrListTreeprocessor(Treeprocessor): + BASE_RE: str + HEADER_RE: Pattern[str] + BLOCK_RE: Pattern[str] + INLINE_RE: Pattern[str] + NAME_RE: Pattern[str] + def run(self, doc: Element) -> None: ... + def assign_attrs(self, elem: Element, attrs_string: str, *, strict: bool = False) -> str: ... + def sanitize_name(self, name: str) -> str: ... + +class AttrListExtension(Extension): ... + +def makeExtension(**kwargs) -> AttrListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/codehilite.pyi b/stubs/Markdown/markdown/extensions/codehilite.pyi new file mode 100644 index 000000000000..b7458a80978e --- /dev/null +++ b/stubs/Markdown/markdown/extensions/codehilite.pyi @@ -0,0 +1,42 @@ +from typing import Any + +from markdown.extensions import Extension +from markdown.treeprocessors import Treeprocessor + +pygments: bool + +def parse_hl_lines(expr: str) -> list[int]: ... + +class CodeHilite: + src: str + lang: str | None + guess_lang: bool + use_pygments: bool + lang_prefix: str + pygments_formatter: Any + options: dict[str, Any] + def __init__( + self, + src: str, + *, + linenums: bool | None = None, + guess_lang: bool = ..., + css_class: str = ..., + lang: str | None = ..., + style: str = ..., + noclasses: bool = ..., + tab_length: int = ..., + hl_lines: list[int] = ..., + use_pygments: bool = ..., + **options: Any, + ) -> None: ... + def hilite(self, shebang: bool = True) -> str: ... + +class HiliteTreeprocessor(Treeprocessor): + config: dict[str, Any] + def code_unescape(self, text: str) -> str: ... + +class CodeHiliteExtension(Extension): + def __init__(self, **kwargs) -> None: ... + +def makeExtension(**kwargs) -> CodeHiliteExtension: ... diff --git a/stubs/Markdown/markdown/extensions/def_list.pyi b/stubs/Markdown/markdown/extensions/def_list.pyi new file mode 100644 index 000000000000..345ea5077d5b --- /dev/null +++ b/stubs/Markdown/markdown/extensions/def_list.pyi @@ -0,0 +1,13 @@ +from re import Pattern + +from markdown.blockprocessors import BlockProcessor, ListIndentProcessor +from markdown.extensions import Extension + +class DefListProcessor(BlockProcessor): + RE: Pattern[str] + NO_INDENT_RE: Pattern[str] + +class DefListIndentProcessor(ListIndentProcessor): ... +class DefListExtension(Extension): ... + +def makeExtension(**kwargs) -> DefListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/extra.pyi b/stubs/Markdown/markdown/extensions/extra.pyi new file mode 100644 index 000000000000..b063970d1a05 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/extra.pyi @@ -0,0 +1,8 @@ +from markdown.extensions import Extension + +extensions: list[str] + +class ExtraExtension(Extension): + def __init__(self, **kwargs) -> None: ... + +def makeExtension(**kwargs) -> ExtraExtension: ... diff --git a/stubs/Markdown/markdown/extensions/fenced_code.pyi b/stubs/Markdown/markdown/extensions/fenced_code.pyi new file mode 100644 index 000000000000..39810ab260c8 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/fenced_code.pyi @@ -0,0 +1,21 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Any, ClassVar + +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.preprocessors import Preprocessor + +class FencedCodeExtension(Extension): + def __init__(self, **kwargs) -> None: ... + +class FencedBlockPreprocessor(Preprocessor): + FENCED_BLOCK_RE: ClassVar[Pattern[str]] + checked_for_deps: bool + codehilite_conf: dict[str, Any] + use_attr_list: bool + bool_options: list[str] + def __init__(self, md: Markdown, config: dict[str, Any]) -> None: ... + def handle_attrs(self, attrs: Iterable[tuple[str, str]]) -> tuple[str, list[str], dict[str, Any]]: ... + +def makeExtension(**kwargs) -> FencedCodeExtension: ... diff --git a/stubs/Markdown/markdown/extensions/footnotes.pyi b/stubs/Markdown/markdown/extensions/footnotes.pyi new file mode 100644 index 000000000000..f1535eb79140 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/footnotes.pyi @@ -0,0 +1,73 @@ +from collections import OrderedDict +from re import Pattern +from typing import ClassVar +from xml.etree.ElementTree import Element + +from markdown.blockparser import BlockParser +from markdown.blockprocessors import BlockProcessor +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.inlinepatterns import InlineProcessor +from markdown.postprocessors import Postprocessor +from markdown.treeprocessors import Treeprocessor + +FN_BACKLINK_TEXT: str +NBSP_PLACEHOLDER: str +RE_REF_ID: Pattern[str] +RE_REFERENCE: Pattern[str] + +class FootnoteExtension(Extension): + unique_prefix: int + found_refs: dict[str, int] + used_refs: set[str] + def __init__(self, **kwargs) -> None: ... + parser: BlockParser + md: Markdown + footnote_order: list[str] + footnotes: OrderedDict[str, str] + def reset(self) -> None: ... + def unique_ref(self, reference: str, found: bool = False) -> str: ... + def findFootnotesPlaceholder(self, root: Element) -> tuple[Element, Element, bool] | None: ... + def setFootnote(self, id: str, text: str) -> None: ... + def addFootnoteRef(self, id: str) -> None: ... + def get_separator(self) -> str: ... + def makeFootnoteId(self, id: str) -> str: ... + def makeFootnoteRefId(self, id: str, found: bool = False) -> str: ... + def makeFootnotesDiv(self, root: Element) -> Element | None: ... + +class FootnoteBlockProcessor(BlockProcessor): + RE: ClassVar[Pattern[str]] + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def detectTabbed(self, blocks: list[str]) -> list[str]: ... + def detab(self, block: str) -> str: ... # type: ignore[override] + +class FootnoteInlineProcessor(InlineProcessor): + footnotes: FootnoteExtension + def __init__(self, pattern: str, footnotes: FootnoteExtension) -> None: ... + +class FootnotePostTreeprocessor(Treeprocessor): + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def add_duplicates(self, li: Element, duplicates: int) -> None: ... + def get_num_duplicates(self, li: Element) -> int: ... + def handle_duplicates(self, parent: Element) -> None: ... + def run(self, root: Element) -> None: ... + offset: int + +class FootnoteTreeprocessor(Treeprocessor): + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def run(self, root: Element) -> None: ... + +class FootnoteReorderingProcessor(Treeprocessor): + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + def run(self, root: Element) -> None: ... + def reorder_footnotes(self, parent: Element) -> None: ... + +class FootnotePostprocessor(Postprocessor): + footnotes: FootnoteExtension + def __init__(self, footnotes: FootnoteExtension) -> None: ... + +def makeExtension(**kwargs) -> FootnoteExtension: ... diff --git a/stubs/Markdown/markdown/extensions/legacy_attrs.pyi b/stubs/Markdown/markdown/extensions/legacy_attrs.pyi new file mode 100644 index 000000000000..9464f3dff24d --- /dev/null +++ b/stubs/Markdown/markdown/extensions/legacy_attrs.pyi @@ -0,0 +1,15 @@ +from re import Pattern +from xml.etree.ElementTree import Element + +from markdown.extensions import Extension +from markdown.treeprocessors import Treeprocessor + +ATTR_RE: Pattern[str] + +class LegacyAttrs(Treeprocessor): + def run(self, doc: Element) -> None: ... + def handleAttributes(self, el: Element, txt: str) -> str: ... + +class LegacyAttrExtension(Extension): ... + +def makeExtension(**kwargs) -> LegacyAttrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/legacy_em.pyi b/stubs/Markdown/markdown/extensions/legacy_em.pyi new file mode 100644 index 000000000000..3ea44f44c74f --- /dev/null +++ b/stubs/Markdown/markdown/extensions/legacy_em.pyi @@ -0,0 +1,11 @@ +from markdown.extensions import Extension +from markdown.inlinepatterns import UnderscoreProcessor + +EMPHASIS_RE: str +STRONG_RE: str +STRONG_EM_RE: str + +class LegacyUnderscoreProcessor(UnderscoreProcessor): ... +class LegacyEmExtension(Extension): ... + +def makeExtension(**kwargs) -> LegacyEmExtension: ... diff --git a/stubs/Markdown/markdown/extensions/md_in_html.pyi b/stubs/Markdown/markdown/extensions/md_in_html.pyi new file mode 100644 index 000000000000..29cb8f631c11 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/md_in_html.pyi @@ -0,0 +1,41 @@ +from collections.abc import Iterable, Mapping +from typing import Literal +from xml.etree.ElementTree import Element, TreeBuilder + +from markdown.blockprocessors import BlockProcessor +from markdown.extensions import Extension +from markdown.htmlparser import HTMLExtractor +from markdown.postprocessors import RawHtmlPostprocessor +from markdown.preprocessors import Preprocessor + +class HTMLExtractorExtra(HTMLExtractor): + block_level_tags: set[str] + span_tags: set[str] + raw_tags: set[str] + block_tags: set[str] + span_and_blocks_tags: set[str] + mdstack: list[str] + treebuilder: TreeBuilder + mdstate: list[Literal["block", "span", "off"] | None] + mdstarted: list[bool] + def get_element(self) -> Element: ... + def get_state(self, tag: str, attrs: Mapping[str, str]) -> Literal["block", "span", "off"] | None: ... + def handle_starttag(self, tag: str, attrs: Iterable[tuple[str, str | None]]) -> None: ... + def handle_endtag(self, tag: str) -> None: ... + def handle_startendtag(self, tag: str, attrs: Iterable[tuple[str, str | None]]) -> None: ... + def handle_data(self, data: str) -> None: ... + def handle_empty_tag(self, data: str, is_block: bool) -> None: ... + def parse_pi(self, i: int) -> int: ... + def parse_html_declaration(self, i: int) -> int: ... + +class HtmlBlockPreprocessor(Preprocessor): ... + +class MarkdownInHtmlProcessor(BlockProcessor): + def parse_element_content(self, element: Element) -> None: ... + +class MarkdownInHTMLPostprocessor(RawHtmlPostprocessor): + def stash_to_string(self, text: str | Element) -> str: ... + +class MarkdownInHtmlExtension(Extension): ... + +def makeExtension(**kwargs) -> MarkdownInHtmlExtension: ... diff --git a/stubs/Markdown/markdown/extensions/meta.pyi b/stubs/Markdown/markdown/extensions/meta.pyi new file mode 100644 index 000000000000..d6a7f42a807f --- /dev/null +++ b/stubs/Markdown/markdown/extensions/meta.pyi @@ -0,0 +1,20 @@ +from logging import Logger +from re import Pattern + +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.preprocessors import Preprocessor + +log: Logger +META_RE: Pattern[str] +META_MORE_RE: Pattern[str] +BEGIN_RE: Pattern[str] +END_RE: Pattern[str] + +class MetaExtension(Extension): + md: Markdown + def reset(self) -> None: ... + +class MetaPreprocessor(Preprocessor): ... + +def makeExtension(**kwargs) -> MetaExtension: ... diff --git a/stubs/Markdown/markdown/extensions/nl2br.pyi b/stubs/Markdown/markdown/extensions/nl2br.pyi new file mode 100644 index 000000000000..914d39554187 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/nl2br.pyi @@ -0,0 +1,7 @@ +from markdown.extensions import Extension + +BR_RE: str + +class Nl2BrExtension(Extension): ... + +def makeExtension(**kwargs) -> Nl2BrExtension: ... diff --git a/stubs/Markdown/markdown/extensions/sane_lists.pyi b/stubs/Markdown/markdown/extensions/sane_lists.pyi new file mode 100644 index 000000000000..62404bee41db --- /dev/null +++ b/stubs/Markdown/markdown/extensions/sane_lists.pyi @@ -0,0 +1,13 @@ +from markdown import blockparser +from markdown.blockprocessors import OListProcessor, UListProcessor +from markdown.extensions import Extension + +class SaneOListProcessor(OListProcessor): + def __init__(self, parser: blockparser.BlockParser) -> None: ... + +class SaneUListProcessor(UListProcessor): + def __init__(self, parser: blockparser.BlockParser) -> None: ... + +class SaneListExtension(Extension): ... + +def makeExtension(**kwargs) -> SaneListExtension: ... diff --git a/stubs/Markdown/markdown/extensions/smarty.pyi b/stubs/Markdown/markdown/extensions/smarty.pyi new file mode 100644 index 000000000000..eca70b7b7027 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/smarty.pyi @@ -0,0 +1,44 @@ +from collections.abc import Mapping, Sequence +from xml.etree.ElementTree import Element + +from markdown import inlinepatterns, util +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.inlinepatterns import HtmlInlineProcessor + +punctClass: str +endOfWordClass: str +closeClass: str +openingQuotesBase: str +substitutions: Mapping[str, str] +singleQuoteStartRe: str +doubleQuoteStartRe: str +doubleQuoteSetsRe: str +singleQuoteSetsRe: str +doubleQuoteSetsRe2: str +singleQuoteSetsRe2: str +decadeAbbrRe: str +openingDoubleQuotesRegex: str +closingDoubleQuotesRegex: str +closingDoubleQuotesRegex2: str +openingSingleQuotesRegex: str +closingSingleQuotesRegex: str +closingSingleQuotesRegex2: str +remainingSingleQuotesRegex: str +remainingDoubleQuotesRegex: str +HTML_STRICT_RE: str + +class SubstituteTextPattern(HtmlInlineProcessor): + replace: Sequence[int | str | Element] + def __init__(self, pattern: str, replace: Sequence[int | str | Element], md: Markdown) -> None: ... + +class SmartyExtension(Extension): + substitutions: dict[str, str] + def __init__(self, **kwargs) -> None: ... + def educateDashes(self, md: Markdown) -> None: ... + def educateEllipses(self, md: Markdown) -> None: ... + def educateAngledQuotes(self, md: Markdown) -> None: ... + def educateQuotes(self, md: Markdown) -> None: ... + inlinePatterns: util.Registry[inlinepatterns.Pattern] + +def makeExtension(**kwargs) -> SmartyExtension: ... diff --git a/stubs/Markdown/markdown/extensions/tables.pyi b/stubs/Markdown/markdown/extensions/tables.pyi new file mode 100644 index 000000000000..a6ee99d7aac0 --- /dev/null +++ b/stubs/Markdown/markdown/extensions/tables.pyi @@ -0,0 +1,22 @@ +from re import Pattern +from typing import Any, ClassVar + +from markdown import blockparser +from markdown.blockprocessors import BlockProcessor +from markdown.extensions import Extension + +PIPE_NONE: int +PIPE_LEFT: int +PIPE_RIGHT: int + +class TableProcessor(BlockProcessor): + RE_CODE_PIPES: ClassVar[Pattern[str]] + RE_END_BORDER: ClassVar[Pattern[str]] + border: bool + separator: str + def __init__(self, parser: blockparser.BlockParser, config: dict[str, Any]) -> None: ... + +class TableExtension(Extension): + def __init__(self, **kwargs) -> None: ... + +def makeExtension(**kwargs) -> TableExtension: ... diff --git a/stubs/Markdown/markdown/extensions/toc.pyi b/stubs/Markdown/markdown/extensions/toc.pyi new file mode 100644 index 000000000000..27fd77b833ff --- /dev/null +++ b/stubs/Markdown/markdown/extensions/toc.pyi @@ -0,0 +1,70 @@ +from collections.abc import Iterator, MutableSet +from re import Pattern +from typing import Any, TypedDict, type_check_only +from typing_extensions import deprecated +from xml.etree.ElementTree import Element + +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.treeprocessors import Treeprocessor + +IDCOUNT_RE: Pattern[str] + +@type_check_only +class _FlatTocToken(TypedDict): + level: int + id: str + name: str + +@type_check_only +class _TocToken(_FlatTocToken): + children: list[_TocToken] + +def slugify(value: str, separator: str, unicode: bool = False) -> str: ... +def slugify_unicode(value: str, separator: str) -> str: ... +def unique(id: str, ids: MutableSet[str]) -> str: ... +@deprecated("Use `render_inner_html` and `striptags` instead.") +def get_name(el: Element) -> str: ... +@deprecated("Use `run_postprocessors`, `render_inner_html` and/or `striptags` instead.") +def stashedHTML2text(text: str, md: Markdown, strip_entities: bool = True) -> str: ... +def unescape(text: str) -> str: ... +def strip_tags(text: str) -> str: ... +def escape_cdata(text: str) -> str: ... +def run_postprocessors(text: str, md: Markdown) -> str: ... +def render_inner_html(el: Element, md: Markdown) -> str: ... +def remove_fnrefs(root: Element) -> Element: ... +def nest_toc_tokens(toc_list: list[_FlatTocToken]) -> list[_TocToken]: ... + +class TocTreeprocessor(Treeprocessor): + marker: str + title: str + base_level: int + slugify: Any + sep: Any + toc_class: Any + title_class: str + use_anchors: bool + anchorlink_class: str + use_permalinks: bool + permalink_class: str + permalink_title: str + permalink_leading: bool + header_rgx: Pattern[str] + toc_top: int + toc_bottom: int + def __init__(self, md: Markdown, config: dict[str, Any]) -> None: ... + def iterparent(self, node: Element) -> Iterator[tuple[Element, Element]]: ... + def replace_marker(self, root: Element, elem: Element) -> None: ... + def set_level(self, elem: Element) -> None: ... + def add_anchor(self, c: Element, elem_id: str) -> None: ... + def add_permalink(self, c: Element, elem_id: str) -> None: ... + def build_toc_div(self, toc_list: list[_TocToken]) -> Element: ... + def run(self, doc: Element) -> None: ... + +class TocExtension(Extension): + TreeProcessorClass: type[TocTreeprocessor] + def __init__(self, **kwargs) -> None: ... + md: Markdown + def reset(self) -> None: ... + +def makeExtension(**kwargs) -> TocExtension: ... diff --git a/stubs/Markdown/markdown/extensions/wikilinks.pyi b/stubs/Markdown/markdown/extensions/wikilinks.pyi new file mode 100644 index 000000000000..d31983af866a --- /dev/null +++ b/stubs/Markdown/markdown/extensions/wikilinks.pyi @@ -0,0 +1,17 @@ +from typing import Any + +from markdown.core import Markdown +from markdown.extensions import Extension +from markdown.inlinepatterns import InlineProcessor + +def build_url(label: str, base: str, end: str) -> str: ... + +class WikiLinkExtension(Extension): + def __init__(self, **kwargs) -> None: ... + md: Markdown + +class WikiLinksInlineProcessor(InlineProcessor): + config: dict[str, Any] + def __init__(self, pattern: str, config: dict[str, Any]) -> None: ... + +def makeExtension(**kwargs) -> WikiLinkExtension: ... diff --git a/stubs/Markdown/markdown/htmlparser.pyi b/stubs/Markdown/markdown/htmlparser.pyi new file mode 100644 index 000000000000..b0d95592ef93 --- /dev/null +++ b/stubs/Markdown/markdown/htmlparser.pyi @@ -0,0 +1,29 @@ +import html.parser as htmlparser +import re +from _frozen_importlib import ModuleSpec +from collections.abc import Sequence + +from markdown import Markdown + +spec: ModuleSpec +commentclose: re.Pattern[str] +blank_line_re: re.Pattern[str] + +class HTMLExtractor(htmlparser.HTMLParser): + empty_tags: set[str] + lineno_start_cache: list[int] + md: Markdown + def __init__(self, md: Markdown, *args, **kwargs): ... + inraw: bool + intail: bool + stack: list[str] + cleandoc: list[str] + @property + def line_offset(self) -> int: ... + def at_line_start(self) -> bool: ... + def get_endtag_text(self, tag: str) -> str: ... + def handle_starttag(self, tag: str, attrs: Sequence[tuple[str, str]]) -> None: ... # type: ignore[override] + def handle_empty_tag(self, data: str, is_block: bool) -> None: ... + def handle_decl(self, data: str) -> None: ... + def parse_bogus_comment(self, i: int, report: int = 0) -> int: ... + def get_starttag_text(self) -> str: ... diff --git a/stubs/Markdown/markdown/inlinepatterns.pyi b/stubs/Markdown/markdown/inlinepatterns.pyi new file mode 100644 index 000000000000..00ee4b4f0516 --- /dev/null +++ b/stubs/Markdown/markdown/inlinepatterns.pyi @@ -0,0 +1,112 @@ +import re +from collections.abc import Collection +from typing import ClassVar, NamedTuple +from xml.etree.ElementTree import Element + +from markdown import util +from markdown.core import Markdown + +def build_inlinepatterns(md: Markdown, **kwargs) -> util.Registry[Pattern]: ... + +NOIMG: str +BACKTICK_RE: str +ESCAPE_RE: str +EMPHASIS_RE: str +STRONG_RE: str +SMART_STRONG_RE: str +SMART_EMPHASIS_RE: str +SMART_STRONG_EM_RE: str +EM_STRONG_RE: str +EM_STRONG2_RE: str +STRONG_EM_RE: str +STRONG_EM2_RE: str +STRONG_EM3_RE: str +LINK_RE: str +IMAGE_LINK_RE: str +REFERENCE_RE: str +IMAGE_REFERENCE_RE: str +NOT_STRONG_RE: str +AUTOLINK_RE: str +AUTOMAIL_RE: str +HTML_RE: str +ENTITY_RE: str +LINE_BREAK_RE: str + +def dequote(string: str) -> str: ... + +class EmStrongItem(NamedTuple): + pattern: re.Pattern[str] + builder: str + tags: str + +class Pattern: + ANCESTOR_EXCLUDES: ClassVar[Collection[str]] + pattern: str + compiled_re: re.Pattern[str] + md: Markdown + def __init__(self, pattern: str, md: Markdown | None = None) -> None: ... + def getCompiledRegExp(self) -> re.Pattern[str]: ... + def handleMatch(self, m: re.Match[str]) -> str | Element | None: ... + def type(self) -> str: ... + def unescape(self, text: str) -> str: ... + +class InlineProcessor(Pattern): + safe_mode: bool + def __init__(self, pattern: str, md: Markdown | None = None) -> None: ... + def handleMatch(self, m: re.Match[str], data: str) -> tuple[Element | str | None, int | None, int | None]: ... # type: ignore[override] + +class SimpleTextPattern(Pattern): ... +class SimpleTextInlineProcessor(InlineProcessor): ... +class EscapeInlineProcessor(InlineProcessor): ... + +class SimpleTagPattern(Pattern): + tag: str + def __init__(self, pattern: str, tag: str) -> None: ... + +class SimpleTagInlineProcessor(InlineProcessor): + tag: str + def __init__(self, pattern: str, tag: str) -> None: ... + +class SubstituteTagPattern(SimpleTagPattern): ... +class SubstituteTagInlineProcessor(SimpleTagInlineProcessor): ... + +class BacktickInlineProcessor(InlineProcessor): + ESCAPED_BSLASH: str + tag: str + def __init__(self, pattern: str) -> None: ... + +class DoubleTagPattern(SimpleTagPattern): ... +class DoubleTagInlineProcessor(SimpleTagInlineProcessor): ... + +class HtmlInlineProcessor(InlineProcessor): + def unescape(self, text: str) -> str: ... + def backslash_unescape(self, text: str) -> str: ... + +class AsteriskProcessor(InlineProcessor): + PATTERNS: ClassVar[list[EmStrongItem]] + def build_single(self, m: re.Match[str], tag: str, idx: int) -> Element: ... + def build_double(self, m: re.Match[str], tags: str, idx: int) -> Element: ... + def build_double2(self, m: re.Match[str], tags: str, idx: int) -> Element: ... + def parse_sub_patterns(self, data: str, parent: Element, last: Element | None, idx: int) -> None: ... + def build_element(self, m: re.Match[str], builder: str, tags: str, index: int) -> Element: ... + +class UnderscoreProcessor(AsteriskProcessor): ... + +class LinkInlineProcessor(InlineProcessor): + RE_LINK: ClassVar[re.Pattern[str]] + RE_TITLE_CLEAN: ClassVar[re.Pattern[str]] + def getLink(self, data: str, index: int) -> tuple[str, str | None, int, bool]: ... + def getText(self, data: str, index: int) -> tuple[str, int, bool]: ... + +class ImageInlineProcessor(LinkInlineProcessor): ... + +class ReferenceInlineProcessor(LinkInlineProcessor): + NEWLINE_CLEANUP_RE: ClassVar[re.Pattern[str]] + def evalId(self, data: str, index: int, text: str) -> tuple[str | None, int, bool]: ... + def makeTag(self, href: str, title: str, text: str) -> Element: ... + +class ShortReferenceInlineProcessor(ReferenceInlineProcessor): ... +class ImageReferenceInlineProcessor(ReferenceInlineProcessor): ... +class ShortImageReferenceInlineProcessor(ImageReferenceInlineProcessor): ... +class AutolinkInlineProcessor(InlineProcessor): ... +class AutomailInlineProcessor(InlineProcessor): ... diff --git a/stubs/Markdown/markdown/postprocessors.pyi b/stubs/Markdown/markdown/postprocessors.pyi new file mode 100644 index 000000000000..24cb7d4210e0 --- /dev/null +++ b/stubs/Markdown/markdown/postprocessors.pyi @@ -0,0 +1,27 @@ +import re +from typing import ClassVar +from typing_extensions import deprecated + +from markdown.core import Markdown + +from . import util + +def build_postprocessors(md: Markdown, **kwargs) -> util.Registry[Postprocessor]: ... + +class Postprocessor(util.Processor): + def run(self, text: str) -> str: ... + +class RawHtmlPostprocessor(Postprocessor): + BLOCK_LEVEL_REGEX: ClassVar[re.Pattern[str]] + def isblocklevel(self, html: str) -> bool: ... + def stash_to_string(self, text: str) -> str: ... + +class AndSubstitutePostprocessor(Postprocessor): ... + +@deprecated( + "This class is deprecated and will be removed in the future; " + "use [`UnescapeTreeprocessor`][markdown.treeprocessors.UnescapeTreeprocessor] instead." +) +class UnescapePostprocessor(Postprocessor): + RE: ClassVar[re.Pattern[str]] + def unescape(self, m: re.Match[str]) -> str: ... diff --git a/stubs/Markdown/markdown/preprocessors.pyi b/stubs/Markdown/markdown/preprocessors.pyi new file mode 100644 index 000000000000..dc55669881e5 --- /dev/null +++ b/stubs/Markdown/markdown/preprocessors.pyi @@ -0,0 +1,11 @@ +from markdown.core import Markdown + +from . import util + +def build_preprocessors(md: Markdown, **kwargs) -> util.Registry[Preprocessor]: ... + +class Preprocessor(util.Processor): + def run(self, lines: list[str]) -> list[str]: ... + +class NormalizeWhitespace(Preprocessor): ... +class HtmlBlockPreprocessor(Preprocessor): ... diff --git a/stubs/Markdown/markdown/serializers.pyi b/stubs/Markdown/markdown/serializers.pyi new file mode 100644 index 000000000000..0fbcf66b57a8 --- /dev/null +++ b/stubs/Markdown/markdown/serializers.pyi @@ -0,0 +1,9 @@ +import re +from xml.etree.ElementTree import Element + +__all__ = ["to_html_string", "to_xhtml_string"] + +RE_AMP: re.Pattern[str] + +def to_html_string(element: Element) -> str: ... +def to_xhtml_string(element: Element) -> str: ... diff --git a/stubs/Markdown/markdown/test_tools.pyi b/stubs/Markdown/markdown/test_tools.pyi new file mode 100644 index 000000000000..8c9f300d2f92 --- /dev/null +++ b/stubs/Markdown/markdown/test_tools.pyi @@ -0,0 +1,30 @@ +import unittest +from _typeshed import Unused +from typing import Any + +__all__ = ["TestCase", "LegacyTestCase", "Kwargs"] + +class TestCase(unittest.TestCase): + default_kwargs: dict[str, Any] # taken from source code + def assertMarkdownRenders( + self, + source: str, + expected: str, + expected_attrs: dict[str, Any] | None = None, # values passing to self.assertEqual() + **kwargs, + ) -> None: ... + def dedent(self, text: str) -> str: ... + +class recursionlimit: + limit: int + old_limit: int + def __init__(self, limit: int) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, type: Unused, value: Unused, tb: Unused) -> None: ... + +class Kwargs(dict[str, Any]): ... + +class LegacyTestMeta(type): + def __new__(cls, name: str, bases: tuple[type, ...], dct: dict[str, Any]): ... # dct is namespace argument for type.__new__() + +class LegacyTestCase(unittest.TestCase, metaclass=LegacyTestMeta): ... diff --git a/stubs/Markdown/markdown/treeprocessors.pyi b/stubs/Markdown/markdown/treeprocessors.pyi new file mode 100644 index 000000000000..343896f9bb62 --- /dev/null +++ b/stubs/Markdown/markdown/treeprocessors.pyi @@ -0,0 +1,26 @@ +from re import Pattern +from typing import ClassVar, TypeGuard +from xml.etree.ElementTree import Element + +from markdown import util +from markdown.core import Markdown + +def build_treeprocessors(md: Markdown, **kwargs) -> util.Registry[Treeprocessor]: ... +def isString(s: object) -> TypeGuard[str]: ... + +class Treeprocessor(util.Processor): + def run(self, root: Element) -> Element | None: ... + +class InlineProcessor(Treeprocessor): + inlinePatterns: util.Registry[InlineProcessor] + ancestors: list[str] + def __init__(self, md: Markdown) -> None: ... + stashed_nodes: dict[str, Element | str] + parent_map: dict[Element[str], Element[str]] + def run(self, tree: Element, ancestors: list[str] | None = None) -> Element: ... + +class PrettifyTreeprocessor(Treeprocessor): ... + +class UnescapeTreeprocessor(Treeprocessor): + RE: ClassVar[Pattern[str]] + def unescape(self, text: str) -> str: ... diff --git a/stubs/Markdown/markdown/util.pyi b/stubs/Markdown/markdown/util.pyi new file mode 100644 index 000000000000..82615ec3843f --- /dev/null +++ b/stubs/Markdown/markdown/util.pyi @@ -0,0 +1,70 @@ +from collections.abc import Iterator +from importlib import metadata +from re import Pattern +from typing import Final, Generic, TypedDict, TypeVar, overload, type_check_only + +from markdown.core import Markdown + +_T = TypeVar("_T") + +BLOCK_LEVEL_ELEMENTS: Final[list[str]] +STX: Final[str] +ETX: Final[str] +INLINE_PLACEHOLDER_PREFIX: Final[str] +INLINE_PLACEHOLDER: Final[str] +INLINE_PLACEHOLDER_RE: Final[Pattern[str]] +AMP_SUBSTITUTE: Final[str] +HTML_PLACEHOLDER: Final[str] +HTML_PLACEHOLDER_RE: Final[Pattern[str]] +TAG_PLACEHOLDER: Final[str] +RTL_BIDI_RANGES: Final[tuple[tuple[str, str], tuple[str, str]]] + +def get_installed_extensions() -> metadata.EntryPoints: ... +def deprecated(message: str, stacklevel: int = 2): ... + +@overload +def parseBoolValue(value: str) -> bool: ... +@overload +def parseBoolValue(value: str | None, fail_on_errors: bool = True, preserve_none: bool = False) -> bool | None: ... + +def code_escape(text: str) -> str: ... +def nearing_recursion_limit() -> bool: ... + +class AtomicString(str): ... + +class Processor: + md: Markdown + def __init__(self, md: Markdown | None = None) -> None: ... + +@type_check_only +class _TagData(TypedDict): + tag: str + attrs: dict[str, str] + left_index: int + right_index: int + +class HtmlStash: + html_counter: int + rawHtmlBlocks: list[str] + tag_counter: int + tag_data: list[_TagData] + def __init__(self) -> None: ... + def store(self, html: str) -> str: ... + def reset(self) -> None: ... + def get_placeholder(self, key: int) -> str: ... + def store_tag(self, tag: str, attrs: dict[str, str], left_index: int, right_index: int) -> str: ... + +class Registry(Generic[_T]): + def __init__(self) -> None: ... + def __contains__(self, item: str | _T) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + + @overload + def __getitem__(self, key: slice) -> Registry[_T]: ... + @overload + def __getitem__(self, key: str | int) -> _T: ... + + def __len__(self) -> int: ... + def get_index_for_name(self, name: str) -> int: ... + def register(self, item: _T, name: str, priority: float) -> None: ... + def deregister(self, name: str, strict: bool = True) -> None: ... diff --git a/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt b/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a511c3b35f7d --- /dev/null +++ b/stubs/PyAutoGUI/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +pyautogui.__main__ diff --git a/stubs/PyAutoGUI/METADATA.toml b/stubs/PyAutoGUI/METADATA.toml new file mode 100644 index 000000000000..32947c6d216d --- /dev/null +++ b/stubs/PyAutoGUI/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.9.*" +upstream-repository = "https://github.com/asweigart/pyautogui" +dependencies = ["types-PyScreeze"] diff --git a/stubs/PyAutoGUI/pyautogui/__init__.pyi b/stubs/PyAutoGUI/pyautogui/__init__.pyi new file mode 100644 index 000000000000..17ac847943c7 --- /dev/null +++ b/stubs/PyAutoGUI/pyautogui/__init__.pyi @@ -0,0 +1,252 @@ +import contextlib +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Iterable, Sequence +from datetime import datetime +from typing import Final, NamedTuple, ParamSpec, SupportsIndex, SupportsInt, TypeAlias, TypeVar + +from pyscreeze import ( + center as center, + locate as locate, + locateAll as locateAll, + locateAllOnScreen as locateAllOnScreen, + locateCenterOnScreen as locateCenterOnScreen, + locateOnScreen as locateOnScreen, + locateOnWindow as locateOnWindow, + pixel as pixel, + pixelMatchesColor as pixelMatchesColor, + screenshot as screenshot, +) + +_P = ParamSpec("_P") +_R = TypeVar("_R") +# Explicitly mentioning str despite being in the ConvertibleToInt Alias because it has a different meaning (filename on screen) +# Specifying non-None Y arg when X is a string or sequence raises an error +# TODO: This could be better represented through overloads +_NormalizeableXArg: TypeAlias = str | ConvertibleToInt | Sequence[ConvertibleToInt] + +# Constants +KEY_NAMES: list[str] +KEYBOARD_KEYS: list[str] +LEFT: Final = "left" +MIDDLE: Final = "middle" +RIGHT: Final = "right" +PRIMARY: Final = "primary" +SECONDARY: Final = "secondary" +G_LOG_SCREENSHOTS_FILENAMES: list[str] +# Implementation details +QWERTY: Final[str] +QWERTZ: Final[str] +MINIMUM_SLEEP: Final[float] + +# These are meant to be overridable +LOG_SCREENSHOTS: bool +LOG_SCREENSHOTS_LIMIT: int | None +# https://pyautogui.readthedocs.io/en/latest/index.html#fail-safes +FAILSAFE: bool +PAUSE: float +DARWIN_CATCH_UP_TIME: float +FAILSAFE_POINTS: list[tuple[int, int]] +# https://pyautogui.readthedocs.io/en/latest/mouse.htmln#mouse-movement +MINIMUM_DURATION: float + +class PyAutoGUIException(Exception): ... +class FailSafeException(PyAutoGUIException): ... +class ImageNotFoundException(PyAutoGUIException): ... + +def raisePyAutoGUIImageNotFoundException(wrappedFunction: Callable[_P, _R]) -> Callable[_P, _R]: ... +def mouseInfo() -> None: ... +def useImageNotFoundException(value: bool | None = None) -> None: ... +def isShiftCharacter(character: str) -> bool: ... + +class Point(NamedTuple): + x: int + y: int + +class Size(NamedTuple): + width: int + height: int + +def getPointOnLine(x1: float, y1: float, x2: float, y2: float, n: float) -> tuple[float, float]: ... +def linear(n: float) -> float: ... +def position(x: int | None = None, y: int | None = None) -> Point: ... +def size() -> Size: ... + +resolution = size + +def onScreen(x: _NormalizeableXArg | None, y: SupportsInt | None = None) -> bool: ... +def mouseDown( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def mouseUp( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def click( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + clicks: SupportsIndex = 1, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def leftClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def rightClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def middleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def doubleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "left", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def tripleClick( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + interval: float = 0.0, + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "left", + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def scroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def hscroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def vscroll( + clicks: float, + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def moveTo( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool = False, + _pause: bool = True, +) -> None: ... +def moveRel( + xOffset: _NormalizeableXArg | None = None, + yOffset: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + logScreenshot: bool = False, + _pause: bool = True, +) -> None: ... + +move = moveRel + +def dragTo( + x: _NormalizeableXArg | None = None, + y: SupportsInt | None = None, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + logScreenshot: bool | None = None, + _pause: bool = True, + mouseDownUp: bool = True, +) -> None: ... +def dragRel( + xOffset: _NormalizeableXArg | None = 0, + yOffset: SupportsInt | None = 0, + duration: float = 0.0, + tween: Callable[[float], float] = ..., + # Docstring says `button` can also be `int`, but `.lower()` is called unconditionally in `_normalizeButton()` + button: str = "primary", + logScreenshot: bool | None = None, + _pause: bool = True, + mouseDownUp: bool = True, +) -> None: ... + +drag = dragRel + +def isValidKey(key: str) -> bool: ... +def keyDown(key: str, logScreenshot: bool | None = None, _pause: bool = True) -> None: ... +def keyUp(key: str, logScreenshot: bool | None = None, _pause: bool = True) -> None: ... +def press( + keys: str | Iterable[str], + presses: SupportsIndex = 1, + interval: float = 0.0, + logScreenshot: bool | None = None, + _pause: bool = True, +) -> None: ... +def hold( + keys: str | Iterable[str], logScreenshot: bool | None = None, _pause: bool = True +) -> contextlib._GeneratorContextManager[None]: ... +def typewrite( + message: str | Sequence[str], interval: float = 0.0, logScreenshot: bool | None = None, _pause: bool = True +) -> None: ... + +write = typewrite + +def hotkey(*args: str, logScreenshot: bool | None = None, interval: float = 0.0) -> None: ... + +shortcut = hotkey + +def failSafeCheck() -> None: ... +def displayMousePosition(xOffset: float = 0, yOffset: float = 0) -> None: ... +def sleep(seconds: float) -> None: ... +def countdown(seconds: SupportsIndex) -> None: ... +def run(commandStr: str, _ssCount: Sequence[int] | None = None) -> None: ... +def printInfo(dontPrint: bool = False) -> str: ... +def getInfo() -> tuple[str, str, str, str, Size, datetime]: ... diff --git a/stubs/PyMeeus/METADATA.toml b/stubs/PyMeeus/METADATA.toml new file mode 100644 index 000000000000..f8508a58ef40 --- /dev/null +++ b/stubs/PyMeeus/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/architest/pymeeus" diff --git a/stubs/PyMeeus/pymeeus/Angle.pyi b/stubs/PyMeeus/pymeeus/Angle.pyi new file mode 100644 index 000000000000..5f65ee04f79b --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Angle.pyi @@ -0,0 +1,100 @@ +from typing import overload +from typing_extensions import Self + +class Angle: + @overload + def __init__(self, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a: Angle, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a: float, /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def __init__(self, a: list[float] | tuple[float, ...], /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, a3: float, /, *, ra: bool = False) -> None: ... + @overload + def __init__(self, a1: float, a2: float, a3: float, a4: float, /, *, ra: bool = False) -> None: ... + + @staticmethod + def reduce_deg(deg: float | Angle) -> float: ... + @staticmethod + def reduce_dms(degrees: float, minutes: float, seconds: float = 0.0) -> tuple[int, int, float, float]: ... + @staticmethod + def deg2dms(deg: float | Angle) -> tuple[int, int, float, float]: ... + @staticmethod + def dms2deg(degrees: float, minutes: float, seconds: float = 0.0) -> float: ... + def get_tolerance(self) -> float: ... + def set_tolerance(self, tol: float) -> None: ... + def __call__(self) -> float: ... + + @overload + def set(self, *, ra: bool = False) -> None: ... + @overload + def set(self, a: Angle, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a: float, /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def set(self, a: list[float] | tuple[float, ...], /, *, ra: bool = False, radians: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, a3: float, /, *, ra: bool = False) -> None: ... + @overload + def set(self, a1: float, a2: float, a3: float, a4: float, /, *, ra: bool = False) -> None: ... + + def set_radians(self, rads: float) -> None: ... + + @overload + def set_ra(self) -> None: ... + @overload + def set_ra(self, a: float | Angle | list[float] | tuple[float, ...], /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, a3: float, /) -> None: ... + @overload + def set_ra(self, a1: float, a2: float, a3: float, a4: float, /) -> None: ... + + def dms_str(self, fancy: bool | None = True, n_dec: int = -1) -> str: ... + def get_ra(self) -> float: ... + def ra_str(self, fancy: bool | None = True, n_dec: int = -1) -> str: ... + def rad(self) -> float: ... + def dms_tuple(self) -> tuple[int, int, float, float]: ... + def ra_tuple(self) -> tuple[int, int, float, float]: ... + def to_positive(self) -> Self: ... + def __eq__(self, b: float | Angle) -> bool: ... # type: ignore[override] + def __ne__(self, b: float | Angle) -> bool: ... # type: ignore[override] + def __lt__(self, b: float | Angle) -> bool: ... + def __ge__(self, b: float | Angle) -> bool: ... + def __gt__(self, b: float | Angle) -> bool: ... + def __le__(self, b: float | Angle) -> bool: ... + def __neg__(self) -> Angle: ... + def __abs__(self) -> Angle: ... + def __mod__(self, b: float | Angle) -> Angle: ... + def __add__(self, b: float | Angle) -> Angle: ... + def __sub__(self, b: float | Angle) -> Angle: ... + def __mul__(self, b: float | Angle) -> Angle: ... + def __div__(self, b: float | Angle) -> Angle: ... + def __truediv__(self, b: float | Angle) -> Angle: ... + def __pow__(self, b: float | Angle) -> Angle: ... + def __imod__(self, b: float | Angle) -> Self: ... + def __iadd__(self, b: float | Angle) -> Self: ... + def __isub__(self, b: float | Angle) -> Self: ... + def __imul__(self, b: float | Angle) -> Self: ... + def __idiv__(self, b: float | Angle) -> Angle: ... + def __itruediv__(self, b: float | Angle) -> Self: ... + def __ipow__(self, b: float | Angle) -> Self: ... + def __rmod__(self, b: float | Angle) -> Angle: ... + def __radd__(self, b: float | Angle) -> Angle: ... + def __rsub__(self, b: float | Angle) -> Angle: ... + def __rmul__(self, b: float | Angle) -> Angle: ... + def __rdiv__(self, b: float | Angle) -> Angle: ... + def __rtruediv__(self, b: float | Angle) -> Angle: ... + def __rpow__(self, b: float | Angle) -> Angle: ... + def __float__(self) -> float: ... + def __int__(self) -> int: ... + def __round__(self, n: float = 0) -> Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Coordinates.pyi b/stubs/PyMeeus/pymeeus/Coordinates.pyi new file mode 100644 index 000000000000..05814b68c48f --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Coordinates.pyi @@ -0,0 +1,196 @@ +import datetime +from typing import Final, overload + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +NUTATION_ARG_TABLE: Final[list[list[int]]] +NUTATION_SINE_COEF_TABLE: Final[list[list[float]]] +NUTATION_COSINE_COEF_TABLE: Final[list[list[float]]] + +@overload +def mean_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def mean_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def true_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def true_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def nutation_longitude( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def nutation_longitude( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +@overload +def nutation_obliquity( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, +) -> Angle: ... +@overload +def nutation_obliquity( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False +) -> Angle: ... + +def precession_equatorial( + start_epoch: Epoch, + final_epoch: Epoch, + start_ra: Angle, + start_dec: Angle, + p_motion_ra: float | Angle = 0.0, + p_motion_dec: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def precession_ecliptical( + start_epoch: Epoch, + final_epoch: Epoch, + start_lon: Angle, + start_lat: Angle, + p_motion_lon: float | Angle = 0.0, + p_motion_lat: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def p_motion_equa2eclip( + p_motion_ra: Angle, p_motion_dec: Angle, ra: Angle, dec: Angle, lat: Angle, epsilon: Angle +) -> tuple[float, float]: ... +def precession_newcomb( + start_epoch: Epoch, + final_epoch: Epoch, + start_ra: Angle, + start_dec: Angle, + p_motion_ra: float | Angle = 0.0, + p_motion_dec: float | Angle = 0.0, +) -> tuple[Angle, Angle]: ... +def motion_in_space( + start_ra: Angle, + start_dec: Angle, + distance: float, + velocity: float, + p_motion_ra: float | Angle, + p_motion_dec: float | Angle, + time: float, +) -> tuple[Angle, Angle]: ... +def equatorial2ecliptical(right_ascension: Angle, declination: Angle, obliquity: Angle) -> tuple[Angle, Angle]: ... +def ecliptical2equatorial(longitude: Angle, latitude: Angle, obliquity: Angle) -> tuple[Angle, Angle]: ... +def equatorial2horizontal(hour_angle: Angle, declination: Angle, geo_latitude: Angle) -> tuple[Angle, Angle]: ... +def horizontal2equatorial(azimuth: Angle, elevation: Angle, geo_latitude: Angle) -> tuple[Angle, Angle]: ... +def equatorial2galactic(right_ascension: Angle, declination: Angle) -> tuple[Angle, Angle]: ... +def galactic2equatorial(longitude: Angle, latitude: Angle) -> tuple[Angle, Angle]: ... +def parallactic_angle(hour_angle: Angle, declination: Angle, geo_latitude: Angle) -> Angle | None: ... +def ecliptic_horizon(local_sidereal_time: Angle, geo_latitude: Angle, obliquity: Angle) -> tuple[Angle, Angle, Angle]: ... +def ecliptic_equator(longitude: Angle, latitude: Angle, obliquity: Angle) -> Angle: ... +def diurnal_path_horizon(declination: Angle, geo_latitude: Angle) -> Angle: ... +def times_rise_transit_set( + longitude: Angle, + latitude: Angle, + alpha1: Angle, + delta1: Angle, + alpha2: Angle, + delta2: Angle, + alpha3: Angle, + delta3: Angle, + h0: Angle, + delta_t: float, + theta0: Angle, +) -> tuple[float, float, float] | tuple[None, None, None]: ... +def refraction_apparent2true(apparent_elevation: Angle, pressure: float = 1010.0, temperature: float = 10.0) -> Angle: ... +def refraction_true2apparent(true_elevation: Angle, pressure: float = 1010.0, temperature: float = 10.0) -> Angle: ... +def angular_separation(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle) -> Angle: ... +def minimum_angular_separation( + alpha1_1: Angle, + delta1_1: Angle, + alpha1_2: Angle, + delta1_2: Angle, + alpha1_3: Angle, + delta1_3: Angle, + alpha2_1: Angle, + delta2_1: Angle, + alpha2_2: Angle, + delta2_2: Angle, + alpha2_3: Angle, + delta2_3: Angle, +) -> tuple[float, Angle]: ... +def relative_position_angle(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle) -> Angle: ... +def planetary_conjunction( + alpha1_list: list[Angle] | tuple[Angle, ...], + delta1_list: list[Angle] | tuple[Angle, ...], + alpha2_list: list[Angle] | tuple[Angle, ...], + delta2_list: list[Angle] | tuple[Angle, ...], +) -> tuple[float, Angle]: ... +def planet_star_conjunction( + alpha_list: list[Angle] | tuple[Angle, ...], delta_list: list[Angle] | tuple[Angle, ...], alpha_star: Angle, delta_star: Angle +) -> tuple[float, Angle]: ... +def planet_stars_in_line( + alpha_list: list[Angle] | tuple[Angle, ...], + delta_list: list[Angle] | tuple[Angle, ...], + alpha_star1: Angle, + delta_star1: Angle, + alpha_star2: Angle, + delta_star2: Angle, +) -> float: ... +def straight_line( + alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle, alpha3: Angle, delta3: Angle +) -> tuple[Angle, Angle]: ... +def circle_diameter(alpha1: Angle, delta1: Angle, alpha2: Angle, delta2: Angle, alpha3: Angle, delta3: Angle) -> Angle: ... +def vsop_pos( + epoch: Epoch, vsop_l: list[list[list[float]]], vsop_b: list[list[list[float]]], vsop_r: list[list[list[float]]] +) -> tuple[Angle, Angle, float]: ... +def geometric_vsop_pos( + epoch: Epoch, + vsop_l: list[list[list[float]]], + vsop_b: list[list[list[float]]], + vsop_r: list[list[list[float]]], + tofk5: bool | None = True, +) -> tuple[Angle, Angle, float]: ... +def apparent_vsop_pos( + epoch: Epoch, + vsop_l: list[list[list[float]]], + vsop_b: list[list[list[float]]], + vsop_r: list[list[list[float]]], + nutation: bool | None = True, +) -> tuple[Angle, Angle, float]: ... +def apparent_position(epoch: Epoch, alpha: Angle, delta: Angle, sun_lon: Angle) -> tuple[Angle, Angle]: ... +def orbital_equinox2equinox(epoch0: Epoch, epoch: Epoch, i0: Angle, arg0: Angle, lon0: Angle) -> tuple[Angle, Angle, Angle]: ... +def kepler_equation(eccentricity: float, mean_anomaly: Angle) -> tuple[Angle, Angle]: ... +def orbital_elements( + epoch: Epoch, parameters1: list[list[float]], parameters2: list[list[float]] +) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... +def velocity(r: float, a: float) -> float: ... +def velocity_perihelion(e: float, a: float) -> float: ... +def velocity_aphelion(e: float, a: float) -> float: ... +def length_orbit(e: float, a: float) -> float: ... +def passage_nodes_elliptic(omega: Angle, e: float, a: float, t: Epoch, ascending: bool | None = True) -> tuple[Epoch, float]: ... +def passage_nodes_parabolic(omega: Angle, q: float, t: Epoch, ascending: bool | None = True) -> tuple[Epoch, float]: ... +def phase_angle(sun_dist: float, earth_dist: float, sun_earth_dist: float) -> Angle: ... +def illuminated_fraction(sun_dist: float, earth_dist: float, sun_earth_dist: float) -> float: ... +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/CurveFitting.pyi b/stubs/PyMeeus/pymeeus/CurveFitting.pyi new file mode 100644 index 000000000000..00ba40a02d7f --- /dev/null +++ b/stubs/PyMeeus/pymeeus/CurveFitting.pyi @@ -0,0 +1,45 @@ +from collections.abc import Callable +from typing import overload + +from pymeeus.Angle import Angle + +class CurveFitting: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, a: CurveFitting, /) -> None: ... + @overload + def __init__(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def __init__( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def __init__( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + @overload + def set(self) -> None: ... + @overload + def set(self, a: CurveFitting, /) -> None: ... + @overload + def set(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def set( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def set( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + def __len__(self) -> int: ... + def correlation_coeff(self) -> float: ... + def linear_fitting(self) -> tuple[float, float]: ... + def quadratic_fitting(self) -> tuple[float, float, float]: ... + def general_fitting( + self, f0: Callable[..., float], f1: Callable[..., float] = ..., f2: Callable[..., float] = ... + ) -> tuple[float, float, float]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Earth.pyi b/stubs/PyMeeus/pymeeus/Earth.pyi new file mode 100644 index 000000000000..764b459f3836 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Earth.pyi @@ -0,0 +1,64 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +VSOP87_L_J2000: Final[list[list[list[float]]]] +VSOP87_B_J2000: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Ellipsoid: + def __init__(self, a: float, f: float, omega: float) -> None: ... + def b(self) -> float: ... + def e(self) -> float: ... + +IAU76: Final[Ellipsoid] +WGS84: Final[Ellipsoid] + +class Earth: + def __init__(self, ellipsoid: Ellipsoid = ...) -> None: ... + def set(self, ellipsoid: Ellipsoid) -> None: ... + def rho(self, latitude: float | Angle) -> float: ... + def rho_sinphi(self, latitude: float | Angle, height: float) -> float: ... + def rho_cosphi(self, latitude: float | Angle, height: float) -> float: ... + def rp(self, latitude: float | Angle) -> float: ... + def linear_velocity(self, latitude: float | Angle) -> float: ... + def rm(self, latitude: float | Angle) -> float: ... + def distance( + self, lon1: float | Angle, lat1: float | Angle, lon2: float | Angle, lat2: float | Angle + ) -> tuple[float, float]: ... + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch, nutation: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geometric_heliocentric_position_j2000(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def parallax_correction( + right_ascension: Angle, declination: Angle, latitude: Angle, distance: float, hour_angle: Angle, height: float = 0.0 + ) -> tuple[Angle, Angle]: ... + @staticmethod + def parallax_ecliptical( + longitude: Angle, + latitude: Angle, + semidiameter: Angle, + obs_lat: Angle, + obliquity: Angle, + sidereal_time: Angle, + distance: float, + height: float = 0.0, + ) -> tuple[Angle, Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Epoch.pyi b/stubs/PyMeeus/pymeeus/Epoch.pyi new file mode 100644 index 000000000000..22dce2c398dc --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Epoch.pyi @@ -0,0 +1,139 @@ +import datetime +from typing import Final, Literal, overload +from typing_extensions import Self + +from pymeeus.Angle import Angle + +DAY2SEC: Final = 86400.0 +DAY2MIN: Final = 1440.0 +DAY2HOURS: Final = 24.0 +LEAP_TABLE: Final[dict[float, int]] + +class Epoch: + @overload + def __init__(self) -> None: ... + @overload + def __init__( + self, year: int, month: int, day: int, /, *time: float, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> None: ... + @overload + def __init__( + self, + a: float | Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> None: ... + + def __hash__(self) -> int: ... + + @overload + def set(self) -> None: ... + @overload + def set( + self, year: int, month: int, day: int, /, *time: float, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> None: ... + @overload + def set( + self, + a: float | Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> None: ... + + @overload + @overload + @staticmethod + def check_input_date( + a: Epoch | list[float] | tuple[float, ...] | datetime.date, + /, + *, + leap_seconds: float = 0, + local: bool = False, + utc: bool = False, + ) -> Epoch: ... + @overload + @staticmethod + def check_input_date( + year: int, month: int, day: int, /, *, leap_seconds: float = 0, local: bool = False, utc: bool = False + ) -> Epoch: ... + + @staticmethod + def is_julian(year: int, month: int, day: int) -> bool: ... + def julian(self) -> bool: ... + + @overload + @staticmethod + def get_month(month: float | str, as_string: Literal[True]) -> str: ... + @overload + @staticmethod + def get_month(month: float | str, as_string: Literal[False] | None = False) -> int: ... + + @staticmethod + def is_leap(year: float) -> bool: ... + def leap(self) -> bool: ... + @staticmethod + def get_doy(yyyy: int, mm: int, dd: int) -> float: ... + def doy(self) -> float: ... + @staticmethod + def doy2date(year: int, doy: float) -> tuple[int, int, float]: ... + @staticmethod + def leap_seconds(year: int, month: int) -> int: ... + @staticmethod + def get_last_leap_second() -> tuple[int, int, float, int]: ... + @staticmethod + def utc2local() -> float: ... + @staticmethod + def easter(year: float) -> tuple[int, int]: ... + @staticmethod + def jewish_pesach(year: float) -> tuple[int, int]: ... + @staticmethod + def moslem2gregorian(year: float, month: float, day: float) -> tuple[int, int, int]: ... + @staticmethod + def gregorian2moslem(year: float, month: float, day: float) -> tuple[int, int, int]: ... + def get_date(self, *, utc: bool = False, leap_seconds: float = 0.0, local: bool = ...) -> tuple[int, int, float]: ... + def get_full_date( + self, *, utc: bool = False, leap_seconds: float = 0.0, local: bool = ... + ) -> tuple[int, int, int, int, int, float]: ... + @staticmethod + def tt2ut(year: int, month: int) -> float: ... + + @overload + def dow(self, as_string: Literal[True]) -> str: ... + @overload + def dow(self, as_string: Literal[False] | None = False) -> int: ... + + def mean_sidereal_time(self) -> float: ... + def apparent_sidereal_time(self, true_obliquity: float | Angle, nutation_longitude: float | Angle) -> float: ... + def mjd(self) -> float: ... + def jde(self) -> float: ... + def year(self) -> float: ... + def rise_set(self, latitude: Angle, longitude: Angle, altitude: float = 0.0) -> tuple[Epoch, Epoch]: ... + def __call__(self) -> float: ... + def __add__(self, b: float) -> Epoch: ... + + @overload + def __sub__(self, b: float) -> Epoch: ... + @overload + def __sub__(self, b: Epoch) -> float: ... + + def __iadd__(self, b: float) -> Self: ... + def __isub__(self, b: float) -> Self: ... # type: ignore[misc] # __sub__ and __isub__ are incompatible + def __radd__(self, b: float) -> Epoch: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __eq__(self, b: float | Epoch) -> bool: ... # type: ignore[override] + def __ne__(self, b: float | Epoch) -> bool: ... # type: ignore[override] + def __lt__(self, b: float | Epoch) -> bool: ... + def __ge__(self, b: float | Epoch) -> bool: ... + def __gt__(self, b: float | Epoch) -> bool: ... + def __le__(self, b: float | Epoch) -> bool: ... + +JDE2000: Epoch + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Interpolation.pyi b/stubs/PyMeeus/pymeeus/Interpolation.pyi new file mode 100644 index 000000000000..d3e821633d03 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Interpolation.pyi @@ -0,0 +1,44 @@ +from typing import overload + +from pymeeus.Angle import Angle + +class Interpolation: + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, a: Interpolation, /) -> None: ... + @overload + def __init__(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def __init__( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def __init__( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + @overload + def set(self) -> None: ... + @overload + def set(self, a: Interpolation, /) -> None: ... + @overload + def set(self, a: list[float | Angle] | tuple[float | Angle, ...], /) -> None: ... + @overload + def set( + self, a1: list[float | Angle] | tuple[float | Angle, ...], a2: list[float | Angle] | tuple[float | Angle, ...], / + ) -> None: ... + @overload + def set( + self, a1: float | Angle, a2: float | Angle, a3: float | Angle, a4: float | Angle, /, *rest: float | Angle + ) -> None: ... + + def __len__(self) -> int: ... + def get_tolerance(self) -> float: ... + def set_tolerance(self, tol: float) -> None: ... + def __call__(self, x: float | Angle) -> float | Angle: ... + def derivative(self, x: float | Angle) -> float: ... + def root(self, xl: float | Angle = 0, xh: float | Angle = 0, max_iter: int = 1000) -> float | Angle: ... + def minmax(self, xl: float | Angle = 0, xh: float | Angle = 0, max_iter: int = 1000) -> float | Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Jupiter.pyi b/stubs/PyMeeus/pymeeus/Jupiter.pyi new file mode 100644 index 000000000000..8d62086bc09b --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Jupiter.pyi @@ -0,0 +1,38 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Jupiter: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/JupiterMoons.pyi b/stubs/PyMeeus/pymeeus/JupiterMoons.pyi new file mode 100644 index 000000000000..f86ebf994723 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/JupiterMoons.pyi @@ -0,0 +1,83 @@ +from typing import Literal, overload + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class JupiterMoons: + @staticmethod + def jupiter_system_angles(epoch: Epoch) -> tuple[float, float]: ... + @staticmethod + def rectangular_positions_jovian_equatorial( + epoch: Epoch, tofk5: bool = True, solar: bool = False, do_correction: bool = True + ) -> tuple[ + tuple[float, float, float], tuple[float, float, float], tuple[float, float, float], tuple[float, float, float] + ]: ... + + @overload + @staticmethod + def apparent_rectangular_coordinates( + epoch: Epoch, + X: float, + Y: float, + Z: float, + OMEGA: float, + psi: float, + i: float, + lambda_0: float, + beta_0: float, + D: float = 0, + isFictional: Literal[True] = ..., + ) -> float: ... + @overload + @staticmethod + def apparent_rectangular_coordinates( + epoch: Epoch, + X: float, + Y: float, + Z: float, + OMEGA: float, + psi: float, + i: float, + lambda_0: float, + beta_0: float, + D: float = 0, + isFictional: Literal[False] | None = False, + ) -> tuple[float, float, float]: ... + + @staticmethod + def calculate_delta( + epoch: Epoch, + ) -> tuple[float, float, Angle, Angle, float] | tuple[float, float, Literal[0], Literal[0], Literal[0]]: ... + + @overload + @staticmethod + def correct_rectangular_positions( + R: float, i_sat: int, DELTA: float, X_coordinate: list[float] | tuple[float, float, float] + ) -> tuple[float, float, float]: ... + @overload + @staticmethod + def correct_rectangular_positions( + R: float, i_sat: int, DELTA: float, X_coordinate: float, Y_coordinate: float = 0, Z_coordinate: float = 0 + ) -> tuple[float, float, float]: ... + + @overload + @staticmethod + def check_phenomena(epoch: Epoch, check_all: Literal[True] = True, i_sat: int = 0) -> list[list[float]]: ... + @overload + @staticmethod + def check_phenomena(epoch: Epoch, check_all: Literal[False] | None, i_sat: int = 0) -> tuple[float, float]: ... + + @staticmethod + def is_phenomena(epoch: Epoch) -> list[list[bool]]: ... + @staticmethod + def check_coordinates(X: float, Y: float) -> float: ... + @staticmethod + def check_occultation( + X: float = 0, Y: float = 0, Z: float = 0, epoch: Epoch | None = None, i_sat: int | None = None + ) -> float: ... + @staticmethod + def check_eclipse( + X_0: float = 0, Y_0: float = 0, Z_0: float = 0, epoch: Epoch | None = None, i_sat: int | None = None + ) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Mars.pyi b/stubs/PyMeeus/pymeeus/Mars.pyi new file mode 100644 index 000000000000..083c06a0b54e --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Mars.pyi @@ -0,0 +1,38 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Mars: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Mercury.pyi b/stubs/PyMeeus/pymeeus/Mercury.pyi new file mode 100644 index 000000000000..e5b53a02b941 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Mercury.pyi @@ -0,0 +1,42 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Mercury: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def inferior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def superior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def western_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def eastern_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Minor.pyi b/stubs/PyMeeus/pymeeus/Minor.pyi new file mode 100644 index 000000000000..54e6d380204d --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Minor.pyi @@ -0,0 +1,10 @@ +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class Minor: + def __init__(self, q: float, e: float, i: Angle, omega: Angle, w: Angle, t: Epoch) -> None: ... + def set(self, q: float, e: float, i: Angle, omega: Angle, w: Angle, t: Epoch) -> None: ... + def geocentric_position(self, epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + def heliocentric_ecliptical_position(self, epoch: Epoch) -> tuple[Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Moon.pyi b/stubs/PyMeeus/pymeeus/Moon.pyi new file mode 100644 index 000000000000..2a4ce12ae5f2 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Moon.pyi @@ -0,0 +1,39 @@ +from typing import Final, Literal + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +PERIODIC_TERMS_LR_TABLE: Final[list[list[float]]] +PERIODIC_TERMS_B_TABLE: Final[list[list[float]]] + +class Moon: + @staticmethod + def geocentric_ecliptical_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def apparent_ecliptical_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def apparent_equatorial_pos(epoch: Epoch) -> tuple[Angle, Angle, float, Angle]: ... + @staticmethod + def longitude_mean_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def longitude_true_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def longitude_mean_perigee(epoch: Epoch) -> Angle: ... + @staticmethod + def illuminated_fraction_disk(epoch: Epoch) -> float: ... + @staticmethod + def position_bright_limb(epoch: Epoch) -> Angle: ... + @staticmethod + def moon_phase(epoch: Epoch, target: Literal["new", "first", "full", "last"] = "new") -> Epoch: ... + @staticmethod + def moon_perigee_apogee(epoch: Epoch, target: Literal["perigee", "apogee"] = "perigee") -> tuple[Epoch, Angle]: ... + @staticmethod + def moon_passage_nodes(epoch: Epoch, target: Literal["ascending", "descending"] = "ascending") -> Epoch: ... + @staticmethod + def moon_maximum_declination(epoch: Epoch, target: Literal["northern", "southern"] = "northern") -> tuple[Epoch, Angle]: ... + @staticmethod + def moon_librations(epoch: Epoch) -> tuple[Angle, Angle, Angle, Angle, Angle, Angle]: ... + @staticmethod + def moon_position_angle_axis(epoch: Epoch) -> Angle: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Neptune.pyi b/stubs/PyMeeus/pymeeus/Neptune.pyi new file mode 100644 index 000000000000..3dd5e2a418b2 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Neptune.pyi @@ -0,0 +1,30 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Neptune: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Pluto.pyi b/stubs/PyMeeus/pymeeus/Pluto.pyi new file mode 100644 index 000000000000..bbe9825c81e9 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Pluto.pyi @@ -0,0 +1,17 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +PLUTO_ARGUMENT: Final[list[tuple[float, float, float]]] +PLUTO_LONGITUDE: Final[list[tuple[float, float]]] +PLUTO_LATITUDE: Final[list[tuple[float, float]]] +PLUTO_RADIUS_VECTOR: Final[list[tuple[float, float]]] + +class Pluto: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Saturn.pyi b/stubs/PyMeeus/pymeeus/Saturn.pyi new file mode 100644 index 000000000000..9794c54542e3 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Saturn.pyi @@ -0,0 +1,44 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Saturn: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, delta_U: float | Angle, B: float | Angle) -> float: ... + @staticmethod + def ring_inclination(epoch: Epoch) -> Angle: ... + @staticmethod + def ring_logitude_ascending_node(epoch: Epoch) -> Angle: ... + @staticmethod + def ring_parameters(epoch: Epoch) -> tuple[Angle, Angle, Angle, Angle, float, float]: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Sun.pyi b/stubs/PyMeeus/pymeeus/Sun.pyi new file mode 100644 index 000000000000..d2dfb258ff41 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Sun.pyi @@ -0,0 +1,35 @@ +from typing import Literal + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +class Sun: + def __init__(self) -> None: ... + @staticmethod + def true_longitude_coarse(epoch: Epoch) -> tuple[Angle, float]: ... + @staticmethod + def apparent_longitude_coarse(epoch: Epoch) -> tuple[Angle, float]: ... + @staticmethod + def apparent_rightascension_declination_coarse(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def geometric_geocentric_position(epoch: Epoch, tofk5: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_geocentric_position(epoch: Epoch, nutation: bool = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def rectangular_coordinates_mean_equinox(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_j2000(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_b1950(epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def rectangular_coordinates_equinox(epoch: Epoch, equinox_epoch: Epoch) -> tuple[float, float, float]: ... + @staticmethod + def get_equinox_solstice(year: int, target: Literal["spring", "summer", "autumn", "winter"] = "spring") -> Epoch: ... + @staticmethod + def equation_of_time(epoch: Epoch) -> tuple[int, float]: ... + @staticmethod + def ephemeris_physical_observations(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def beginning_synodic_rotation(number: int) -> Epoch: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Uranus.pyi b/stubs/PyMeeus/pymeeus/Uranus.pyi new file mode 100644 index 000000000000..ff2f3885f025 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Uranus.pyi @@ -0,0 +1,34 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Uranus: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def opposition(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/Venus.pyi b/stubs/PyMeeus/pymeeus/Venus.pyi new file mode 100644 index 000000000000..3fae751f4af6 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/Venus.pyi @@ -0,0 +1,44 @@ +from typing import Final + +from pymeeus.Angle import Angle +from pymeeus.Epoch import Epoch + +VSOP87_L: Final[list[list[list[float]]]] +VSOP87_B: Final[list[list[list[float]]]] +VSOP87_R: Final[list[list[list[float]]]] +ORBITAL_ELEM: Final[list[list[float]]] +ORBITAL_ELEM_J2000: Final[list[list[float]]] + +class Venus: + @staticmethod + def geometric_heliocentric_position(epoch: Epoch, tofk5: bool | None = True) -> tuple[Angle, Angle, float]: ... + @staticmethod + def apparent_heliocentric_position(epoch: Epoch) -> tuple[Angle, Angle, float]: ... + @staticmethod + def orbital_elements_mean_equinox(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def orbital_elements_j2000(epoch: Epoch) -> tuple[Angle, float, float, Angle, Angle, Angle]: ... + @staticmethod + def geocentric_position(epoch: Epoch) -> tuple[Angle, Angle, Angle]: ... + @staticmethod + def inferior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def superior_conjunction(epoch: Epoch) -> Epoch: ... + @staticmethod + def western_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def eastern_elongation(epoch: Epoch) -> tuple[Epoch, Angle]: ... + @staticmethod + def station_longitude_1(epoch: Epoch) -> Epoch: ... + @staticmethod + def station_longitude_2(epoch: Epoch) -> Epoch: ... + @staticmethod + def perihelion_aphelion(epoch: Epoch, perihelion: bool | None = True) -> Epoch: ... + @staticmethod + def passage_nodes(epoch: Epoch, ascending: bool = True) -> tuple[Epoch, float]: ... + @staticmethod + def illuminated_fraction(epoch: Epoch) -> float: ... + @staticmethod + def magnitude(sun_dist: float, earth_dist: float, phase_angle: float | Angle) -> float: ... + +def main() -> None: ... diff --git a/stubs/PyMeeus/pymeeus/__init__.pyi b/stubs/PyMeeus/pymeeus/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/PyMeeus/pymeeus/base.pyi b/stubs/PyMeeus/pymeeus/base.pyi new file mode 100644 index 000000000000..e61004af8567 --- /dev/null +++ b/stubs/PyMeeus/pymeeus/base.pyi @@ -0,0 +1,8 @@ +from typing import Final, Literal + +TOL: Final = 1e-10 + +def machine_accuracy() -> tuple[float, int]: ... +def get_ordinal_suffix(ordinal: float) -> Literal["st", "nd", "rd", "th"]: ... +def iint(number: float) -> int: ... +def main() -> None: ... diff --git a/stubs/PyMySQL/@tests/stubtest_allowlist.txt b/stubs/PyMySQL/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e7a8053fb866 --- /dev/null +++ b/stubs/PyMySQL/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# DictCursorMixin changes method types of inherited classes, but doesn't contain much at runtime +pymysql.cursors.DictCursorMixin.__iter__ +pymysql.cursors.DictCursorMixin.fetch[a-z]* diff --git a/stubs/PyMySQL/@tests/test_cases/check_connection.py b/stubs/PyMySQL/@tests/test_cases/check_connection.py new file mode 100644 index 000000000000..24d42664e3c7 --- /dev/null +++ b/stubs/PyMySQL/@tests/test_cases/check_connection.py @@ -0,0 +1,15 @@ +from typing_extensions import assert_type + +from pymysql.connections import Connection +from pymysql.cursors import Cursor + + +class MyCursor(Cursor): + pass + + +assert_type(Connection(), Connection[Cursor]) +assert_type(Connection(cursorclass=Cursor), Connection[Cursor]) +assert_type(Connection(cursorclass=MyCursor), Connection[MyCursor]) + +Connection(cursorclass=None) # type: ignore diff --git a/stubs/PyMySQL/METADATA.toml b/stubs/PyMySQL/METADATA.toml new file mode 100644 index 000000000000..b5cd7fc2bafb --- /dev/null +++ b/stubs/PyMySQL/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.2.*" +upstream-repository = "https://github.com/PyMySQL/PyMySQL" diff --git a/stubs/PyMySQL/pymysql/__init__.pyi b/stubs/PyMySQL/pymysql/__init__.pyi new file mode 100644 index 000000000000..5d4a4a3e2465 --- /dev/null +++ b/stubs/PyMySQL/pymysql/__init__.pyi @@ -0,0 +1,107 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Final, SupportsBytes, SupportsIndex + +from . import connections as connections, constants as constants, converters as converters, cursors as cursors +from .constants import FIELD_TYPE as FIELD_TYPE +from .err import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + MySQLError as MySQLError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, +) +from .times import ( + Date as Date, + DateFromTicks as DateFromTicks, + Time as Time, + TimeFromTicks as TimeFromTicks, + Timestamp as Timestamp, + TimestampFromTicks as TimestampFromTicks, +) + +VERSION: Final[tuple[str | int, ...]] +VERSION_STRING: Final[str] +version_info: tuple[int, int, int, str, int] +__version__: str + +def get_client_info() -> str: ... +def install_as_MySQLdb() -> None: ... + +threadsafety: int +apilevel: str +paramstyle: str + +class DBAPISet(frozenset[int]): + def __ne__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +STRING: DBAPISet +BINARY: DBAPISet +NUMBER: DBAPISet +DATE: DBAPISet +TIME: DBAPISet +TIMESTAMP: DBAPISet +DATETIME: DBAPISet +ROWID: DBAPISet + +def Binary(x: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer) -> bytes: ... +def thread_safe() -> bool: ... + +NULL: str + +Connect = connections.Connection +connect = connections.Connection +Connection = connections.Connection + +__all__ = [ + "BINARY", + "Binary", + "Connect", + "Connection", + "DATE", + "Date", + "Time", + "Timestamp", + "DateFromTicks", + "TimeFromTicks", + "TimestampFromTicks", + "DataError", + "DatabaseError", + "Error", + "FIELD_TYPE", + "IntegrityError", + "InterfaceError", + "InternalError", + "MySQLError", + "NULL", + "NUMBER", + "NotSupportedError", + "DBAPISet", + "OperationalError", + "ProgrammingError", + "ROWID", + "STRING", + "TIME", + "TIMESTAMP", + "Warning", + "apilevel", + "connect", + "connections", + "constants", + "converters", + "cursors", + "get_client_info", + "paramstyle", + "threadsafety", + "version_info", + "install_as_MySQLdb", + "__version__", +] diff --git a/stubs/PyMySQL/pymysql/_auth.pyi b/stubs/PyMySQL/pymysql/_auth.pyi new file mode 100644 index 000000000000..d8fe1ba35864 --- /dev/null +++ b/stubs/PyMySQL/pymysql/_auth.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete, ReadableBuffer +from typing import Final + +DEBUG: Final[bool] +SCRAMBLE_LENGTH: Final[int] +sha1_new: Incomplete + +def scramble_native_password(password: ReadableBuffer | None, message: ReadableBuffer | None) -> bytes: ... +def ed25519_password(password: ReadableBuffer, scramble: ReadableBuffer) -> bytes: ... +def sha2_rsa_encrypt(password: bytes, salt: bytes, public_key: bytes) -> bytes: ... +def sha256_password_auth(conn, pkt): ... +def scramble_caching_sha2(password: ReadableBuffer, nonce: ReadableBuffer) -> bytes: ... +def caching_sha2_password_auth(conn, pkt) -> Incomplete | None: ... diff --git a/stubs/PyMySQL/pymysql/charset.pyi b/stubs/PyMySQL/pymysql/charset.pyi new file mode 100644 index 000000000000..5dce19cce0c1 --- /dev/null +++ b/stubs/PyMySQL/pymysql/charset.pyi @@ -0,0 +1,22 @@ +from collections.abc import Callable +from typing import Final + +MBLENGTH: Final[dict[int, int]] + +class Charset: + is_default: bool + def __init__(self, id: int, name: str, collation: str, is_default: bool = False) -> None: ... + @property + def encoding(self) -> str: ... + @property + def is_binary(self) -> bool: ... + +class Charsets: + def __init__(self) -> None: ... + def add(self, c: Charset) -> None: ... + def by_id(self, id: int) -> Charset: ... + def by_name(self, name: str) -> Charset: ... + +_charsets: Charsets +charset_by_name: Callable[[str], Charset] +charset_by_id: Callable[[int], Charset] diff --git a/stubs/PyMySQL/pymysql/connections.pyi b/stubs/PyMySQL/pymysql/connections.pyi new file mode 100644 index 000000000000..f911c13600a1 --- /dev/null +++ b/stubs/PyMySQL/pymysql/connections.pyi @@ -0,0 +1,281 @@ +from _typeshed import FileDescriptorOrPath, Incomplete, Unused +from collections.abc import Callable, Mapping +from socket import _Address, socket as _socket +from ssl import SSLContext, _PasswordType +from typing import Any, AnyStr, Generic, Literal, overload +from typing_extensions import Self, TypeVar, deprecated + +from .charset import charset_by_id as charset_by_id, charset_by_name as charset_by_name +from .constants import CLIENT as CLIENT, COMMAND as COMMAND, FIELD_TYPE as FIELD_TYPE, SERVER_STATUS as SERVER_STATUS +from .cursors import Cursor +from .err import ( + DatabaseError, + DataError, + Error, + IntegrityError, + InterfaceError, + InternalError, + NotSupportedError, + OperationalError, + ProgrammingError, + Warning, +) + +_C = TypeVar("_C", bound=Cursor, default=Cursor) +_C2 = TypeVar("_C2", bound=Cursor) + +SSL_ENABLED: bool +DEFAULT_USER: str | None +DEBUG: bool +DEFAULT_CHARSET: str +TEXT_TYPES: set[int] +MAX_PACKET_LEN: int + +def dump_packet(data): ... +def _lenenc_int(i: int) -> bytes: ... + +class Connection(Generic[_C]): + ssl: bool + host: str + port: int + user: str | bytes | None + password: bytes + db: str | bytes | None + unix_socket: _Address | None + charset: str + collation: str | None + bind_address: str | None + use_unicode: bool + client_flag: int + cursorclass: type[_C] + connect_timeout: float | None + host_info: str + sql_mode: str | None + init_command: str | None + max_allowed_packet: int + server_public_key: bytes | None + encoding: str + autocommit_mode: bool | None + encoders: dict[type[Any], Callable[[Any], str]] # argument type depends on the key + decoders: dict[int, Callable[[str], Any]] # return type depends on the key + + @overload + def __init__( + self, + *, + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: SSLContext | None = None, # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: None = None, # deprecated + db: None = None, # deprecated + ) -> None: ... + @overload + @deprecated("Passing a dict for 'ssl' parameter is deprecated. Use 'ssl_*' parameters or 'ssl.SSLContext' instead.") + def __init__( + self, + *, + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: dict[str, Incomplete], # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: str | bytes | None = None, # deprecated + db: str | bytes | None = None, # deprecated + ) -> None: ... + @overload + @deprecated("'passwd' and 'db' arguments are deprecated. Use 'password' and 'database' instead.") + def __init__( + self, + *, + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: dict[str, Incomplete] | SSLContext | None = None, # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: str | bytes | None = None, # deprecated + db: str | bytes | None = None, # deprecated + ) -> None: ... + + def close(self) -> None: ... + @property + def open(self) -> bool: ... + def __del__(self) -> None: ... + def autocommit(self, value) -> None: ... + def get_autocommit(self) -> bool: ... + def commit(self) -> None: ... + def begin(self) -> None: ... + def rollback(self) -> None: ... + def select_db(self, db) -> None: ... + def escape(self, obj, mapping: Mapping[str, Incomplete] | None = None): ... + def literal(self, obj): ... + def escape_string(self, s: AnyStr) -> AnyStr: ... + + @overload + def cursor(self, cursor: None = None) -> _C: ... + @overload + def cursor(self, cursor: type[_C2]) -> _C2: ... + + def query(self, sql, unbuffered: bool = False) -> int: ... + def next_result(self, unbuffered: bool = False) -> int: ... + def affected_rows(self): ... + def kill(self, thread_id): ... + + @overload + def ping(self, reconnect: Literal[False] | None = False) -> None: ... + @overload + @deprecated("The 'reconnect' parameter is deprecated. Create a new connection if you want to reconnect.") + def ping(self, reconnect: Literal[True]) -> None: ... + + @deprecated("Method is deprecated. Use 'set_character_set()' instead.") + def set_charset(self, charset: str) -> None: ... + def set_character_set(self, charset: str, collation: str | None = None) -> None: ... + def connect(self, sock: _socket | None = None) -> None: ... + def write_packet(self, payload) -> None: ... + def _read_packet(self, packet_type=...): ... + def insert_id(self): ... + def thread_id(self): ... + def character_set_name(self): ... + def get_host_info(self) -> str: ... + def get_proto_info(self): ... + def get_server_info(self): ... + def show_warnings(self): ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: object) -> None: ... + Warning: type[Warning] + Error: type[Error] + InterfaceError: type[InterfaceError] + DatabaseError: type[DatabaseError] + DataError: type[DataError] + OperationalError: type[OperationalError] + IntegrityError: type[IntegrityError] + InternalError: type[InternalError] + ProgrammingError: type[ProgrammingError] + NotSupportedError: type[NotSupportedError] + +class MySQLResult: + connection: Connection[Any] | None + affected_rows: int | None + insert_id: int | None + server_status: int | None + warning_count: int + message: str | None + field_count: int + description: Incomplete + rows: Incomplete + has_next: bool | None + unbuffered_active: bool + def __init__(self, connection: Connection[Any]) -> None: ... + def __del__(self) -> None: ... + first_packet: Incomplete + def read(self) -> None: ... + def init_unbuffered_query(self) -> None: ... + +class LoadLocalFile: + filename: FileDescriptorOrPath + connection: Connection[Any] + def __init__(self, filename: FileDescriptorOrPath, connection: Connection[Any]) -> None: ... + def send_data(self) -> None: ... diff --git a/stubs/PyMySQL/pymysql/constants/CLIENT.pyi b/stubs/PyMySQL/pymysql/constants/CLIENT.pyi new file mode 100644 index 000000000000..4a1f58c48273 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/CLIENT.pyi @@ -0,0 +1,27 @@ +from typing import Final + +LONG_PASSWORD: Final[int] +FOUND_ROWS: Final[int] +LONG_FLAG: Final[int] +CONNECT_WITH_DB: Final[int] +NO_SCHEMA: Final[int] +COMPRESS: Final[int] +ODBC: Final[int] +LOCAL_FILES: Final[int] +IGNORE_SPACE: Final[int] +PROTOCOL_41: Final[int] +INTERACTIVE: Final[int] +SSL: Final[int] +IGNORE_SIGPIPE: Final[int] +TRANSACTIONS: Final[int] +SECURE_CONNECTION: Final[int] +MULTI_STATEMENTS: Final[int] +MULTI_RESULTS: Final[int] +PS_MULTI_RESULTS: Final[int] +PLUGIN_AUTH: Final[int] +CONNECT_ATTRS: Final[int] +PLUGIN_AUTH_LENENC_CLIENT_DATA: Final[int] +CAPABILITIES: Final[int] +HANDLE_EXPIRED_PASSWORDS: Final[int] +SESSION_TRACK: Final[int] +DEPRECATE_EOF: Final[int] diff --git a/stubs/PyMySQL/pymysql/constants/COMMAND.pyi b/stubs/PyMySQL/pymysql/constants/COMMAND.pyi new file mode 100644 index 000000000000..bc3f24fb81f3 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/COMMAND.pyi @@ -0,0 +1,34 @@ +from typing import Final + +COM_SLEEP: Final[int] +COM_QUIT: Final[int] +COM_INIT_DB: Final[int] +COM_QUERY: Final[int] +COM_FIELD_LIST: Final[int] +COM_CREATE_DB: Final[int] +COM_DROP_DB: Final[int] +COM_REFRESH: Final[int] +COM_SHUTDOWN: Final[int] +COM_STATISTICS: Final[int] +COM_PROCESS_INFO: Final[int] +COM_CONNECT: Final[int] +COM_PROCESS_KILL: Final[int] +COM_DEBUG: Final[int] +COM_PING: Final[int] +COM_TIME: Final[int] +COM_DELAYED_INSERT: Final[int] +COM_CHANGE_USER: Final[int] +COM_BINLOG_DUMP: Final[int] +COM_TABLE_DUMP: Final[int] +COM_CONNECT_OUT: Final[int] +COM_REGISTER_SLAVE: Final[int] +COM_STMT_PREPARE: Final[int] +COM_STMT_EXECUTE: Final[int] +COM_STMT_SEND_LONG_DATA: Final[int] +COM_STMT_CLOSE: Final[int] +COM_STMT_RESET: Final[int] +COM_SET_OPTION: Final[int] +COM_STMT_FETCH: Final[int] +COM_DAEMON: Final[int] +COM_BINLOG_DUMP_GTID: Final[int] +COM_END: Final[int] diff --git a/stubs/PyMySQL/pymysql/constants/CR.pyi b/stubs/PyMySQL/pymysql/constants/CR.pyi new file mode 100644 index 000000000000..5b6447f64390 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/CR.pyi @@ -0,0 +1,77 @@ +from typing import Final + +CR_ERROR_FIRST: Final = 2000 +CR_UNKNOWN_ERROR: Final = 2000 +CR_SOCKET_CREATE_ERROR: Final = 2001 +CR_CONNECTION_ERROR: Final = 2002 +CR_CONN_HOST_ERROR: Final = 2003 +CR_IPSOCK_ERROR: Final = 2004 +CR_UNKNOWN_HOST: Final = 2005 +CR_SERVER_GONE_ERROR: Final = 2006 +CR_VERSION_ERROR: Final = 2007 +CR_OUT_OF_MEMORY: Final = 2008 +CR_WRONG_HOST_INFO: Final = 2009 +CR_LOCALHOST_CONNECTION: Final = 2010 +CR_TCP_CONNECTION: Final = 2011 +CR_SERVER_HANDSHAKE_ERR: Final = 2012 +CR_SERVER_LOST: Final = 2013 +CR_COMMANDS_OUT_OF_SYNC: Final = 2014 +CR_NAMEDPIPE_CONNECTION: Final = 2015 +CR_NAMEDPIPEWAIT_ERROR: Final = 2016 +CR_NAMEDPIPEOPEN_ERROR: Final = 2017 +CR_NAMEDPIPESETSTATE_ERROR: Final = 2018 +CR_CANT_READ_CHARSET: Final = 2019 +CR_NET_PACKET_TOO_LARGE: Final = 2020 +CR_EMBEDDED_CONNECTION: Final = 2021 +CR_PROBE_SLAVE_STATUS: Final = 2022 +CR_PROBE_SLAVE_HOSTS: Final = 2023 +CR_PROBE_SLAVE_CONNECT: Final = 2024 +CR_PROBE_MASTER_CONNECT: Final = 2025 +CR_SSL_CONNECTION_ERROR: Final = 2026 +CR_MALFORMED_PACKET: Final = 2027 +CR_WRONG_LICENSE: Final = 2028 +CR_NULL_POINTER: Final = 2029 +CR_NO_PREPARE_STMT: Final = 2030 +CR_PARAMS_NOT_BOUND: Final = 2031 +CR_DATA_TRUNCATED: Final = 2032 +CR_NO_PARAMETERS_EXISTS: Final = 2033 +CR_INVALID_PARAMETER_NO: Final = 2034 +CR_INVALID_BUFFER_USE: Final = 2035 +CR_UNSUPPORTED_PARAM_TYPE: Final = 2036 +CR_SHARED_MEMORY_CONNECTION: Final = 2037 +CR_SHARED_MEMORY_CONNECT_REQUEST_ERROR: Final = 2038 +CR_SHARED_MEMORY_CONNECT_ANSWER_ERROR: Final = 2039 +CR_SHARED_MEMORY_CONNECT_FILE_MAP_ERROR: Final = 2040 +CR_SHARED_MEMORY_CONNECT_MAP_ERROR: Final = 2041 +CR_SHARED_MEMORY_FILE_MAP_ERROR: Final = 2042 +CR_SHARED_MEMORY_MAP_ERROR: Final = 2043 +CR_SHARED_MEMORY_EVENT_ERROR: Final = 2044 +CR_SHARED_MEMORY_CONNECT_ABANDONED_ERROR: Final = 2045 +CR_SHARED_MEMORY_CONNECT_SET_ERROR: Final = 2046 +CR_CONN_UNKNOW_PROTOCOL: Final = 2047 +CR_INVALID_CONN_HANDLE: Final = 2048 +CR_SECURE_AUTH: Final = 2049 +CR_FETCH_CANCELED: Final = 2050 +CR_NO_DATA: Final = 2051 +CR_NO_STMT_METADATA: Final = 2052 +CR_NO_RESULT_SET: Final = 2053 +CR_NOT_IMPLEMENTED: Final = 2054 +CR_SERVER_LOST_EXTENDED: Final = 2055 +CR_STMT_CLOSED: Final = 2056 +CR_NEW_STMT_METADATA: Final = 2057 +CR_ALREADY_CONNECTED: Final = 2058 +CR_AUTH_PLUGIN_CANNOT_LOAD: Final = 2059 +CR_DUPLICATE_CONNECTION_ATTR: Final = 2060 +CR_AUTH_PLUGIN_ERR: Final = 2061 +CR_INSECURE_API_ERR: Final = 2062 +CR_FILE_NAME_TOO_LONG: Final = 2063 +CR_SSL_FIPS_MODE_ERR: Final = 2064 +CR_DEPRECATED_COMPRESSION_NOT_SUPPORTED: Final = 2065 +CR_COMPRESSION_WRONGLY_CONFIGURED: Final = 2066 +CR_KERBEROS_USER_NOT_FOUND: Final = 2067 +CR_LOAD_DATA_LOCAL_INFILE_REJECTED: Final = 2068 +CR_LOAD_DATA_LOCAL_INFILE_REALPATH_FAIL: Final = 2069 +CR_DNS_SRV_LOOKUP_FAILED: Final = 2070 +CR_MANDATORY_TRACKER_NOT_FOUND: Final = 2071 +CR_INVALID_FACTOR_NO: Final = 2072 +CR_ERROR_LAST: Final = 2072 diff --git a/stubs/PyMySQL/pymysql/constants/ER.pyi b/stubs/PyMySQL/pymysql/constants/ER.pyi new file mode 100644 index 000000000000..8bd5e9b79e14 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/ER.pyi @@ -0,0 +1,476 @@ +from typing import Final + +ERROR_FIRST: Final = 1000 +HASHCHK: Final = 1000 +NISAMCHK: Final = 1001 +NO: Final = 1002 +YES: Final = 1003 +CANT_CREATE_FILE: Final = 1004 +CANT_CREATE_TABLE: Final = 1005 +CANT_CREATE_DB: Final = 1006 +DB_CREATE_EXISTS: Final = 1007 +DB_DROP_EXISTS: Final = 1008 +DB_DROP_DELETE: Final = 1009 +DB_DROP_RMDIR: Final = 1010 +CANT_DELETE_FILE: Final = 1011 +CANT_FIND_SYSTEM_REC: Final = 1012 +CANT_GET_STAT: Final = 1013 +CANT_GET_WD: Final = 1014 +CANT_LOCK: Final = 1015 +CANT_OPEN_FILE: Final = 1016 +FILE_NOT_FOUND: Final = 1017 +CANT_READ_DIR: Final = 1018 +CANT_SET_WD: Final = 1019 +CHECKREAD: Final = 1020 +DISK_FULL: Final = 1021 +DUP_KEY: Final = 1022 +ERROR_ON_CLOSE: Final = 1023 +ERROR_ON_READ: Final = 1024 +ERROR_ON_RENAME: Final = 1025 +ERROR_ON_WRITE: Final = 1026 +FILE_USED: Final = 1027 +FILSORT_ABORT: Final = 1028 +FORM_NOT_FOUND: Final = 1029 +GET_ERRNO: Final = 1030 +ILLEGAL_HA: Final = 1031 +KEY_NOT_FOUND: Final = 1032 +NOT_FORM_FILE: Final = 1033 +NOT_KEYFILE: Final = 1034 +OLD_KEYFILE: Final = 1035 +OPEN_AS_READONLY: Final = 1036 +OUTOFMEMORY: Final = 1037 +OUT_OF_SORTMEMORY: Final = 1038 +UNEXPECTED_EOF: Final = 1039 +CON_COUNT_ERROR: Final = 1040 +OUT_OF_RESOURCES: Final = 1041 +BAD_HOST_ERROR: Final = 1042 +HANDSHAKE_ERROR: Final = 1043 +DBACCESS_DENIED_ERROR: Final = 1044 +ACCESS_DENIED_ERROR: Final = 1045 +NO_DB_ERROR: Final = 1046 +UNKNOWN_COM_ERROR: Final = 1047 +BAD_NULL_ERROR: Final = 1048 +BAD_DB_ERROR: Final = 1049 +TABLE_EXISTS_ERROR: Final = 1050 +BAD_TABLE_ERROR: Final = 1051 +NON_UNIQ_ERROR: Final = 1052 +SERVER_SHUTDOWN: Final = 1053 +BAD_FIELD_ERROR: Final = 1054 +WRONG_FIELD_WITH_GROUP: Final = 1055 +WRONG_GROUP_FIELD: Final = 1056 +WRONG_SUM_SELECT: Final = 1057 +WRONG_VALUE_COUNT: Final = 1058 +TOO_LONG_IDENT: Final = 1059 +DUP_FIELDNAME: Final = 1060 +DUP_KEYNAME: Final = 1061 +DUP_ENTRY: Final = 1062 +WRONG_FIELD_SPEC: Final = 1063 +PARSE_ERROR: Final = 1064 +EMPTY_QUERY: Final = 1065 +NONUNIQ_TABLE: Final = 1066 +INVALID_DEFAULT: Final = 1067 +MULTIPLE_PRI_KEY: Final = 1068 +TOO_MANY_KEYS: Final = 1069 +TOO_MANY_KEY_PARTS: Final = 1070 +TOO_LONG_KEY: Final = 1071 +KEY_COLUMN_DOES_NOT_EXITS: Final = 1072 +BLOB_USED_AS_KEY: Final = 1073 +TOO_BIG_FIELDLENGTH: Final = 1074 +WRONG_AUTO_KEY: Final = 1075 +READY: Final = 1076 +NORMAL_SHUTDOWN: Final = 1077 +GOT_SIGNAL: Final = 1078 +SHUTDOWN_COMPLETE: Final = 1079 +FORCING_CLOSE: Final = 1080 +IPSOCK_ERROR: Final = 1081 +NO_SUCH_INDEX: Final = 1082 +WRONG_FIELD_TERMINATORS: Final = 1083 +BLOBS_AND_NO_TERMINATED: Final = 1084 +TEXTFILE_NOT_READABLE: Final = 1085 +FILE_EXISTS_ERROR: Final = 1086 +LOAD_INFO: Final = 1087 +ALTER_INFO: Final = 1088 +WRONG_SUB_KEY: Final = 1089 +CANT_REMOVE_ALL_FIELDS: Final = 1090 +CANT_DROP_FIELD_OR_KEY: Final = 1091 +INSERT_INFO: Final = 1092 +UPDATE_TABLE_USED: Final = 1093 +NO_SUCH_THREAD: Final = 1094 +KILL_DENIED_ERROR: Final = 1095 +NO_TABLES_USED: Final = 1096 +TOO_BIG_SET: Final = 1097 +NO_UNIQUE_LOGFILE: Final = 1098 +TABLE_NOT_LOCKED_FOR_WRITE: Final = 1099 +TABLE_NOT_LOCKED: Final = 1100 +BLOB_CANT_HAVE_DEFAULT: Final = 1101 +WRONG_DB_NAME: Final = 1102 +WRONG_TABLE_NAME: Final = 1103 +TOO_BIG_SELECT: Final = 1104 +UNKNOWN_ERROR: Final = 1105 +UNKNOWN_PROCEDURE: Final = 1106 +WRONG_PARAMCOUNT_TO_PROCEDURE: Final = 1107 +WRONG_PARAMETERS_TO_PROCEDURE: Final = 1108 +UNKNOWN_TABLE: Final = 1109 +FIELD_SPECIFIED_TWICE: Final = 1110 +INVALID_GROUP_FUNC_USE: Final = 1111 +UNSUPPORTED_EXTENSION: Final = 1112 +TABLE_MUST_HAVE_COLUMNS: Final = 1113 +RECORD_FILE_FULL: Final = 1114 +UNKNOWN_CHARACTER_SET: Final = 1115 +TOO_MANY_TABLES: Final = 1116 +TOO_MANY_FIELDS: Final = 1117 +TOO_BIG_ROWSIZE: Final = 1118 +STACK_OVERRUN: Final = 1119 +WRONG_OUTER_JOIN: Final = 1120 +NULL_COLUMN_IN_INDEX: Final = 1121 +CANT_FIND_UDF: Final = 1122 +CANT_INITIALIZE_UDF: Final = 1123 +UDF_NO_PATHS: Final = 1124 +UDF_EXISTS: Final = 1125 +CANT_OPEN_LIBRARY: Final = 1126 +CANT_FIND_DL_ENTRY: Final = 1127 +FUNCTION_NOT_DEFINED: Final = 1128 +HOST_IS_BLOCKED: Final = 1129 +HOST_NOT_PRIVILEGED: Final = 1130 +PASSWORD_ANONYMOUS_USER: Final = 1131 +PASSWORD_NOT_ALLOWED: Final = 1132 +PASSWORD_NO_MATCH: Final = 1133 +UPDATE_INFO: Final = 1134 +CANT_CREATE_THREAD: Final = 1135 +WRONG_VALUE_COUNT_ON_ROW: Final = 1136 +CANT_REOPEN_TABLE: Final = 1137 +INVALID_USE_OF_NULL: Final = 1138 +REGEXP_ERROR: Final = 1139 +MIX_OF_GROUP_FUNC_AND_FIELDS: Final = 1140 +NONEXISTING_GRANT: Final = 1141 +TABLEACCESS_DENIED_ERROR: Final = 1142 +COLUMNACCESS_DENIED_ERROR: Final = 1143 +ILLEGAL_GRANT_FOR_TABLE: Final = 1144 +GRANT_WRONG_HOST_OR_USER: Final = 1145 +NO_SUCH_TABLE: Final = 1146 +NONEXISTING_TABLE_GRANT: Final = 1147 +NOT_ALLOWED_COMMAND: Final = 1148 +SYNTAX_ERROR: Final = 1149 +DELAYED_CANT_CHANGE_LOCK: Final = 1150 +TOO_MANY_DELAYED_THREADS: Final = 1151 +ABORTING_CONNECTION: Final = 1152 +NET_PACKET_TOO_LARGE: Final = 1153 +NET_READ_ERROR_FROM_PIPE: Final = 1154 +NET_FCNTL_ERROR: Final = 1155 +NET_PACKETS_OUT_OF_ORDER: Final = 1156 +NET_UNCOMPRESS_ERROR: Final = 1157 +NET_READ_ERROR: Final = 1158 +NET_READ_INTERRUPTED: Final = 1159 +NET_ERROR_ON_WRITE: Final = 1160 +NET_WRITE_INTERRUPTED: Final = 1161 +TOO_LONG_STRING: Final = 1162 +TABLE_CANT_HANDLE_BLOB: Final = 1163 +TABLE_CANT_HANDLE_AUTO_INCREMENT: Final = 1164 +DELAYED_INSERT_TABLE_LOCKED: Final = 1165 +WRONG_COLUMN_NAME: Final = 1166 +WRONG_KEY_COLUMN: Final = 1167 +WRONG_MRG_TABLE: Final = 1168 +DUP_UNIQUE: Final = 1169 +BLOB_KEY_WITHOUT_LENGTH: Final = 1170 +PRIMARY_CANT_HAVE_NULL: Final = 1171 +TOO_MANY_ROWS: Final = 1172 +REQUIRES_PRIMARY_KEY: Final = 1173 +NO_RAID_COMPILED: Final = 1174 +UPDATE_WITHOUT_KEY_IN_SAFE_MODE: Final = 1175 +KEY_DOES_NOT_EXITS: Final = 1176 +CHECK_NO_SUCH_TABLE: Final = 1177 +CHECK_NOT_IMPLEMENTED: Final = 1178 +CANT_DO_THIS_DURING_AN_TRANSACTION: Final = 1179 +ERROR_DURING_COMMIT: Final = 1180 +ERROR_DURING_ROLLBACK: Final = 1181 +ERROR_DURING_FLUSH_LOGS: Final = 1182 +ERROR_DURING_CHECKPOINT: Final = 1183 +NEW_ABORTING_CONNECTION: Final = 1184 +DUMP_NOT_IMPLEMENTED: Final = 1185 +FLUSH_MASTER_BINLOG_CLOSED: Final = 1186 +INDEX_REBUILD: Final = 1187 +MASTER: Final = 1188 +MASTER_NET_READ: Final = 1189 +MASTER_NET_WRITE: Final = 1190 +FT_MATCHING_KEY_NOT_FOUND: Final = 1191 +LOCK_OR_ACTIVE_TRANSACTION: Final = 1192 +UNKNOWN_SYSTEM_VARIABLE: Final = 1193 +CRASHED_ON_USAGE: Final = 1194 +CRASHED_ON_REPAIR: Final = 1195 +WARNING_NOT_COMPLETE_ROLLBACK: Final = 1196 +TRANS_CACHE_FULL: Final = 1197 +SLAVE_MUST_STOP: Final = 1198 +SLAVE_NOT_RUNNING: Final = 1199 +BAD_SLAVE: Final = 1200 +MASTER_INFO: Final = 1201 +SLAVE_THREAD: Final = 1202 +TOO_MANY_USER_CONNECTIONS: Final = 1203 +SET_CONSTANTS_ONLY: Final = 1204 +LOCK_WAIT_TIMEOUT: Final = 1205 +LOCK_TABLE_FULL: Final = 1206 +READ_ONLY_TRANSACTION: Final = 1207 +DROP_DB_WITH_READ_LOCK: Final = 1208 +CREATE_DB_WITH_READ_LOCK: Final = 1209 +WRONG_ARGUMENTS: Final = 1210 +NO_PERMISSION_TO_CREATE_USER: Final = 1211 +UNION_TABLES_IN_DIFFERENT_DIR: Final = 1212 +LOCK_DEADLOCK: Final = 1213 +TABLE_CANT_HANDLE_FT: Final = 1214 +CANNOT_ADD_FOREIGN: Final = 1215 +NO_REFERENCED_ROW: Final = 1216 +ROW_IS_REFERENCED: Final = 1217 +CONNECT_TO_MASTER: Final = 1218 +QUERY_ON_MASTER: Final = 1219 +ERROR_WHEN_EXECUTING_COMMAND: Final = 1220 +WRONG_USAGE: Final = 1221 +WRONG_NUMBER_OF_COLUMNS_IN_SELECT: Final = 1222 +CANT_UPDATE_WITH_READLOCK: Final = 1223 +MIXING_NOT_ALLOWED: Final = 1224 +DUP_ARGUMENT: Final = 1225 +USER_LIMIT_REACHED: Final = 1226 +SPECIFIC_ACCESS_DENIED_ERROR: Final = 1227 +LOCAL_VARIABLE: Final = 1228 +GLOBAL_VARIABLE: Final = 1229 +NO_DEFAULT: Final = 1230 +WRONG_VALUE_FOR_VAR: Final = 1231 +WRONG_TYPE_FOR_VAR: Final = 1232 +VAR_CANT_BE_READ: Final = 1233 +CANT_USE_OPTION_HERE: Final = 1234 +NOT_SUPPORTED_YET: Final = 1235 +MASTER_FATAL_ERROR_READING_BINLOG: Final = 1236 +SLAVE_IGNORED_TABLE: Final = 1237 +INCORRECT_GLOBAL_LOCAL_VAR: Final = 1238 +WRONG_FK_DEF: Final = 1239 +KEY_REF_DO_NOT_MATCH_TABLE_REF: Final = 1240 +OPERAND_COLUMNS: Final = 1241 +SUBQUERY_NO_1_ROW: Final = 1242 +UNKNOWN_STMT_HANDLER: Final = 1243 +CORRUPT_HELP_DB: Final = 1244 +CYCLIC_REFERENCE: Final = 1245 +AUTO_CONVERT: Final = 1246 +ILLEGAL_REFERENCE: Final = 1247 +DERIVED_MUST_HAVE_ALIAS: Final = 1248 +SELECT_REDUCED: Final = 1249 +TABLENAME_NOT_ALLOWED_HERE: Final = 1250 +NOT_SUPPORTED_AUTH_MODE: Final = 1251 +SPATIAL_CANT_HAVE_NULL: Final = 1252 +COLLATION_CHARSET_MISMATCH: Final = 1253 +SLAVE_WAS_RUNNING: Final = 1254 +SLAVE_WAS_NOT_RUNNING: Final = 1255 +TOO_BIG_FOR_UNCOMPRESS: Final = 1256 +ZLIB_Z_MEM_ERROR: Final = 1257 +ZLIB_Z_BUF_ERROR: Final = 1258 +ZLIB_Z_DATA_ERROR: Final = 1259 +CUT_VALUE_GROUP_CONCAT: Final = 1260 +WARN_TOO_FEW_RECORDS: Final = 1261 +WARN_TOO_MANY_RECORDS: Final = 1262 +WARN_NULL_TO_NOTNULL: Final = 1263 +WARN_DATA_OUT_OF_RANGE: Final = 1264 +WARN_DATA_TRUNCATED: Final = 1265 +WARN_USING_OTHER_HANDLER: Final = 1266 +CANT_AGGREGATE_2COLLATIONS: Final = 1267 +DROP_USER: Final = 1268 +REVOKE_GRANTS: Final = 1269 +CANT_AGGREGATE_3COLLATIONS: Final = 1270 +CANT_AGGREGATE_NCOLLATIONS: Final = 1271 +VARIABLE_IS_NOT_STRUCT: Final = 1272 +UNKNOWN_COLLATION: Final = 1273 +SLAVE_IGNORED_SSL_PARAMS: Final = 1274 +SERVER_IS_IN_SECURE_AUTH_MODE: Final = 1275 +WARN_FIELD_RESOLVED: Final = 1276 +BAD_SLAVE_UNTIL_COND: Final = 1277 +MISSING_SKIP_SLAVE: Final = 1278 +UNTIL_COND_IGNORED: Final = 1279 +WRONG_NAME_FOR_INDEX: Final = 1280 +WRONG_NAME_FOR_CATALOG: Final = 1281 +WARN_QC_RESIZE: Final = 1282 +BAD_FT_COLUMN: Final = 1283 +UNKNOWN_KEY_CACHE: Final = 1284 +WARN_HOSTNAME_WONT_WORK: Final = 1285 +UNKNOWN_STORAGE_ENGINE: Final = 1286 +WARN_DEPRECATED_SYNTAX: Final = 1287 +NON_UPDATABLE_TABLE: Final = 1288 +FEATURE_DISABLED: Final = 1289 +OPTION_PREVENTS_STATEMENT: Final = 1290 +DUPLICATED_VALUE_IN_TYPE: Final = 1291 +TRUNCATED_WRONG_VALUE: Final = 1292 +TOO_MUCH_AUTO_TIMESTAMP_COLS: Final = 1293 +INVALID_ON_UPDATE: Final = 1294 +UNSUPPORTED_PS: Final = 1295 +GET_ERRMSG: Final = 1296 +GET_TEMPORARY_ERRMSG: Final = 1297 +UNKNOWN_TIME_ZONE: Final = 1298 +WARN_INVALID_TIMESTAMP: Final = 1299 +INVALID_CHARACTER_STRING: Final = 1300 +WARN_ALLOWED_PACKET_OVERFLOWED: Final = 1301 +CONFLICTING_DECLARATIONS: Final = 1302 +SP_NO_RECURSIVE_CREATE: Final = 1303 +SP_ALREADY_EXISTS: Final = 1304 +SP_DOES_NOT_EXIST: Final = 1305 +SP_DROP_FAILED: Final = 1306 +SP_STORE_FAILED: Final = 1307 +SP_LILABEL_MISMATCH: Final = 1308 +SP_LABEL_REDEFINE: Final = 1309 +SP_LABEL_MISMATCH: Final = 1310 +SP_UNINIT_VAR: Final = 1311 +SP_BADSELECT: Final = 1312 +SP_BADRETURN: Final = 1313 +SP_BADSTATEMENT: Final = 1314 +UPDATE_LOG_DEPRECATED_IGNORED: Final = 1315 +UPDATE_LOG_DEPRECATED_TRANSLATED: Final = 1316 +QUERY_INTERRUPTED: Final = 1317 +SP_WRONG_NO_OF_ARGS: Final = 1318 +SP_COND_MISMATCH: Final = 1319 +SP_NORETURN: Final = 1320 +SP_NORETURNEND: Final = 1321 +SP_BAD_CURSOR_QUERY: Final = 1322 +SP_BAD_CURSOR_SELECT: Final = 1323 +SP_CURSOR_MISMATCH: Final = 1324 +SP_CURSOR_ALREADY_OPEN: Final = 1325 +SP_CURSOR_NOT_OPEN: Final = 1326 +SP_UNDECLARED_VAR: Final = 1327 +SP_WRONG_NO_OF_FETCH_ARGS: Final = 1328 +SP_FETCH_NO_DATA: Final = 1329 +SP_DUP_PARAM: Final = 1330 +SP_DUP_VAR: Final = 1331 +SP_DUP_COND: Final = 1332 +SP_DUP_CURS: Final = 1333 +SP_CANT_ALTER: Final = 1334 +SP_SUBSELECT_NYI: Final = 1335 +STMT_NOT_ALLOWED_IN_SF_OR_TRG: Final = 1336 +SP_VARCOND_AFTER_CURSHNDLR: Final = 1337 +SP_CURSOR_AFTER_HANDLER: Final = 1338 +SP_CASE_NOT_FOUND: Final = 1339 +FPARSER_TOO_BIG_FILE: Final = 1340 +FPARSER_BAD_HEADER: Final = 1341 +FPARSER_EOF_IN_COMMENT: Final = 1342 +FPARSER_ERROR_IN_PARAMETER: Final = 1343 +FPARSER_EOF_IN_UNKNOWN_PARAMETER: Final = 1344 +VIEW_NO_EXPLAIN: Final = 1345 +FRM_UNKNOWN_TYPE: Final = 1346 +WRONG_OBJECT: Final = 1347 +NONUPDATEABLE_COLUMN: Final = 1348 +VIEW_SELECT_DERIVED: Final = 1349 +VIEW_SELECT_CLAUSE: Final = 1350 +VIEW_SELECT_VARIABLE: Final = 1351 +VIEW_SELECT_TMPTABLE: Final = 1352 +VIEW_WRONG_LIST: Final = 1353 +WARN_VIEW_MERGE: Final = 1354 +WARN_VIEW_WITHOUT_KEY: Final = 1355 +VIEW_INVALID: Final = 1356 +SP_NO_DROP_SP: Final = 1357 +SP_GOTO_IN_HNDLR: Final = 1358 +TRG_ALREADY_EXISTS: Final = 1359 +TRG_DOES_NOT_EXIST: Final = 1360 +TRG_ON_VIEW_OR_TEMP_TABLE: Final = 1361 +TRG_CANT_CHANGE_ROW: Final = 1362 +TRG_NO_SUCH_ROW_IN_TRG: Final = 1363 +NO_DEFAULT_FOR_FIELD: Final = 1364 +DIVISION_BY_ZERO: Final = 1365 +TRUNCATED_WRONG_VALUE_FOR_FIELD: Final = 1366 +ILLEGAL_VALUE_FOR_TYPE: Final = 1367 +VIEW_NONUPD_CHECK: Final = 1368 +VIEW_CHECK_FAILED: Final = 1369 +PROCACCESS_DENIED_ERROR: Final = 1370 +RELAY_LOG_FAIL: Final = 1371 +PASSWD_LENGTH: Final = 1372 +UNKNOWN_TARGET_BINLOG: Final = 1373 +IO_ERR_LOG_INDEX_READ: Final = 1374 +BINLOG_PURGE_PROHIBITED: Final = 1375 +FSEEK_FAIL: Final = 1376 +BINLOG_PURGE_FATAL_ERR: Final = 1377 +LOG_IN_USE: Final = 1378 +LOG_PURGE_UNKNOWN_ERR: Final = 1379 +RELAY_LOG_INIT: Final = 1380 +NO_BINARY_LOGGING: Final = 1381 +RESERVED_SYNTAX: Final = 1382 +WSAS_FAILED: Final = 1383 +DIFF_GROUPS_PROC: Final = 1384 +NO_GROUP_FOR_PROC: Final = 1385 +ORDER_WITH_PROC: Final = 1386 +LOGGING_PROHIBIT_CHANGING_OF: Final = 1387 +NO_FILE_MAPPING: Final = 1388 +WRONG_MAGIC: Final = 1389 +PS_MANY_PARAM: Final = 1390 +KEY_PART_0: Final = 1391 +VIEW_CHECKSUM: Final = 1392 +VIEW_MULTIUPDATE: Final = 1393 +VIEW_NO_INSERT_FIELD_LIST: Final = 1394 +VIEW_DELETE_MERGE_VIEW: Final = 1395 +CANNOT_USER: Final = 1396 +XAER_NOTA: Final = 1397 +XAER_INVAL: Final = 1398 +XAER_RMFAIL: Final = 1399 +XAER_OUTSIDE: Final = 1400 +XAER_RMERR: Final = 1401 +XA_RBROLLBACK: Final = 1402 +NONEXISTING_PROC_GRANT: Final = 1403 +PROC_AUTO_GRANT_FAIL: Final = 1404 +PROC_AUTO_REVOKE_FAIL: Final = 1405 +DATA_TOO_LONG: Final = 1406 +SP_BAD_SQLSTATE: Final = 1407 +STARTUP: Final = 1408 +LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR: Final = 1409 +CANT_CREATE_USER_WITH_GRANT: Final = 1410 +WRONG_VALUE_FOR_TYPE: Final = 1411 +TABLE_DEF_CHANGED: Final = 1412 +SP_DUP_HANDLER: Final = 1413 +SP_NOT_VAR_ARG: Final = 1414 +SP_NO_RETSET: Final = 1415 +CANT_CREATE_GEOMETRY_OBJECT: Final = 1416 +FAILED_ROUTINE_BREAK_BINLOG: Final = 1417 +BINLOG_UNSAFE_ROUTINE: Final = 1418 +BINLOG_CREATE_ROUTINE_NEED_SUPER: Final = 1419 +EXEC_STMT_WITH_OPEN_CURSOR: Final = 1420 +STMT_HAS_NO_OPEN_CURSOR: Final = 1421 +COMMIT_NOT_ALLOWED_IN_SF_OR_TRG: Final = 1422 +NO_DEFAULT_FOR_VIEW_FIELD: Final = 1423 +SP_NO_RECURSION: Final = 1424 +TOO_BIG_SCALE: Final = 1425 +TOO_BIG_PRECISION: Final = 1426 +M_BIGGER_THAN_D: Final = 1427 +WRONG_LOCK_OF_SYSTEM_TABLE: Final = 1428 +CONNECT_TO_FOREIGN_DATA_SOURCE: Final = 1429 +QUERY_ON_FOREIGN_DATA_SOURCE: Final = 1430 +FOREIGN_DATA_SOURCE_DOESNT_EXIST: Final = 1431 +FOREIGN_DATA_STRING_INVALID_CANT_CREATE: Final = 1432 +FOREIGN_DATA_STRING_INVALID: Final = 1433 +CANT_CREATE_FEDERATED_TABLE: Final = 1434 +TRG_IN_WRONG_SCHEMA: Final = 1435 +STACK_OVERRUN_NEED_MORE: Final = 1436 +TOO_LONG_BODY: Final = 1437 +WARN_CANT_DROP_DEFAULT_KEYCACHE: Final = 1438 +TOO_BIG_DISPLAYWIDTH: Final = 1439 +XAER_DUPID: Final = 1440 +DATETIME_FUNCTION_OVERFLOW: Final = 1441 +CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG: Final = 1442 +VIEW_PREVENT_UPDATE: Final = 1443 +PS_NO_RECURSION: Final = 1444 +SP_CANT_SET_AUTOCOMMIT: Final = 1445 +MALFORMED_DEFINER: Final = 1446 +VIEW_FRM_NO_USER: Final = 1447 +VIEW_OTHER_USER: Final = 1448 +NO_SUCH_USER: Final = 1449 +FORBID_SCHEMA_CHANGE: Final = 1450 +ROW_IS_REFERENCED_2: Final = 1451 +NO_REFERENCED_ROW_2: Final = 1452 +SP_BAD_VAR_SHADOW: Final = 1453 +TRG_NO_DEFINER: Final = 1454 +OLD_FILE_FORMAT: Final = 1455 +SP_RECURSION_LIMIT: Final = 1456 +SP_PROC_TABLE_CORRUPT: Final = 1457 +SP_WRONG_NAME: Final = 1458 +TABLE_NEEDS_UPGRADE: Final = 1459 +SP_NO_AGGREGATE: Final = 1460 +MAX_PREPARED_STMT_COUNT_REACHED: Final = 1461 +VIEW_RECURSIVE: Final = 1462 +NON_GROUPING_FIELD_USED: Final = 1463 +TABLE_CANT_HANDLE_SPKEYS: Final = 1464 +NO_TRIGGERS_ON_SYSTEM_SCHEMA: Final = 1465 +USERNAME: Final = 1466 +HOSTNAME: Final = 1467 +WRONG_STRING_LENGTH: Final = 1468 +ERROR_LAST: Final = 1468 +STATEMENT_TIMEOUT: Final = 1969 +QUERY_TIMEOUT: Final = 3024 +CONSTRAINT_FAILED: Final = 4025 diff --git a/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi b/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi new file mode 100644 index 000000000000..ab5a5b71f529 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/FIELD_TYPE.pyi @@ -0,0 +1,32 @@ +from typing import Final + +DECIMAL: Final = 0 +TINY: Final = 1 +SHORT: Final = 2 +LONG: Final = 3 +FLOAT: Final = 4 +DOUBLE: Final = 5 +NULL: Final = 6 +TIMESTAMP: Final = 7 +LONGLONG: Final = 8 +INT24: Final = 9 +DATE: Final = 10 +TIME: Final = 11 +DATETIME: Final = 12 +YEAR: Final = 13 +NEWDATE: Final = 14 +VARCHAR: Final = 15 +BIT: Final = 16 +JSON: Final = 245 +NEWDECIMAL: Final = 246 +ENUM: Final = 247 +SET: Final = 248 +TINY_BLOB: Final = 249 +MEDIUM_BLOB: Final = 250 +LONG_BLOB: Final = 251 +BLOB: Final = 252 +VAR_STRING: Final = 253 +STRING: Final = 254 +GEOMETRY: Final = 255 +CHAR: Final = TINY +INTERVAL: Final = ENUM diff --git a/stubs/PyMySQL/pymysql/constants/FLAG.pyi b/stubs/PyMySQL/pymysql/constants/FLAG.pyi new file mode 100644 index 000000000000..111e4739fe3d --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/FLAG.pyi @@ -0,0 +1,17 @@ +from typing import Final + +NOT_NULL: Final = 1 +PRI_KEY: Final = 2 +UNIQUE_KEY: Final = 4 +MULTIPLE_KEY: Final = 8 +BLOB: Final = 16 +UNSIGNED: Final = 32 +ZEROFILL: Final = 64 +BINARY: Final = 128 +ENUM: Final = 256 +AUTO_INCREMENT: Final = 512 +TIMESTAMP: Final = 1024 +SET: Final = 2048 +PART_KEY: Final = 16384 +GROUP: Final = 32767 +UNIQUE: Final = 65536 diff --git a/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi b/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi new file mode 100644 index 000000000000..2e006c848e04 --- /dev/null +++ b/stubs/PyMySQL/pymysql/constants/SERVER_STATUS.pyi @@ -0,0 +1,12 @@ +from typing import Final + +SERVER_STATUS_IN_TRANS: Final = 1 +SERVER_STATUS_AUTOCOMMIT: Final = 2 +SERVER_MORE_RESULTS_EXISTS: Final = 8 +SERVER_QUERY_NO_GOOD_INDEX_USED: Final = 16 +SERVER_QUERY_NO_INDEX_USED: Final = 32 +SERVER_STATUS_CURSOR_EXISTS: Final = 64 +SERVER_STATUS_LAST_ROW_SENT: Final = 128 +SERVER_STATUS_DB_DROPPED: Final = 256 +SERVER_STATUS_NO_BACKSLASH_ESCAPES: Final = 512 +SERVER_STATUS_METADATA_CHANGED: Final = 1024 diff --git a/stubs/PyMySQL/pymysql/constants/__init__.pyi b/stubs/PyMySQL/pymysql/constants/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/PyMySQL/pymysql/converters.pyi b/stubs/PyMySQL/pymysql/converters.pyi new file mode 100644 index 000000000000..dcda0644fb05 --- /dev/null +++ b/stubs/PyMySQL/pymysql/converters.pyi @@ -0,0 +1,52 @@ +import datetime +import re +import time +from _typeshed import Unused +from collections.abc import Callable, Mapping, Sequence +from decimal import Decimal +from typing import Any, TypeAlias, TypeVar +from typing_extensions import Never, deprecated + +_EscaperMapping: TypeAlias = Mapping[type[object], Callable[..., str]] | None +_T = TypeVar("_T") + +def escape_item(val: object, charset: object, mapping: _EscaperMapping = None) -> str: ... +@deprecated("dict cannot be used as parameter. It didn't produce valid SQL and might cause SQL injection.") +def escape_dict(val: Mapping[str, object], charset: object, mapping: _EscaperMapping = None) -> Never: ... +def escape_sequence(val: Sequence[object], charset: object, mapping: _EscaperMapping = None) -> str: ... +def escape_set(val: set[object], charset: object, mapping: _EscaperMapping = None) -> str: ... +def escape_bool(value: bool, mapping: _EscaperMapping = None) -> str: ... +def escape_int(value: int, mapping: _EscaperMapping = None) -> str: ... +def escape_float(value: float, mapping: _EscaperMapping = None) -> str: ... +def escape_string(value: str, mapping: _EscaperMapping = None) -> str: ... +def escape_bytes_prefixed(value: bytes, mapping: _EscaperMapping = None) -> str: ... +def escape_bytes(value: bytes, mapping: _EscaperMapping = None) -> str: ... +def escape_str(value: str, mapping: _EscaperMapping = None) -> str: ... +def escape_None(value: None, mapping: _EscaperMapping = None) -> str: ... +def escape_timedelta(obj: datetime.timedelta, mapping: _EscaperMapping = None) -> str: ... +def escape_time(obj: datetime.time, mapping: _EscaperMapping = None) -> str: ... +def escape_datetime(obj: datetime.datetime, mapping: _EscaperMapping = None) -> str: ... +def escape_date(obj: datetime.date, mapping: _EscaperMapping = None) -> str: ... +def escape_struct_time(obj: time.struct_time, mapping: _EscaperMapping = None) -> str: ... +def Decimal2Literal(o: Decimal, d: Unused) -> str: ... + +DATETIME_RE: re.Pattern[str] + +def convert_datetime(obj: str | bytes) -> datetime.datetime | str: ... + +TIMEDELTA_RE: re.Pattern[str] + +def convert_timedelta(obj: str | bytes) -> datetime.timedelta | str: ... + +TIME_RE: re.Pattern[str] + +def convert_time(obj: str | bytes) -> datetime.time | str: ... +def convert_date(obj: str | bytes) -> datetime.date | str: ... +def through(x: _T) -> _T: ... + +convert_bit = through + +encoders: dict[type[object], Callable[..., str]] +decoders: dict[int, Callable[[str | bytes], Any]] +conversions: dict[type[object] | int, Callable[..., Any]] +Thing2Literal = escape_str diff --git a/stubs/PyMySQL/pymysql/cursors.pyi b/stubs/PyMySQL/pymysql/cursors.pyi new file mode 100644 index 000000000000..ce6471711868 --- /dev/null +++ b/stubs/PyMySQL/pymysql/cursors.pyi @@ -0,0 +1,58 @@ +import re +from collections.abc import Iterable, Iterator +from typing import Any, ClassVar +from typing_extensions import Self + +from .connections import Connection + +RE_INSERT_VALUES: re.Pattern[str] + +class Cursor: + max_stmt_length: ClassVar[int] + connection: Connection[Any] + description: tuple[str, ...] + rownumber: int + rowcount: int + arraysize: int + messages: Any + errorhandler: Any + lastrowid: int + warning_count: int + def __init__(self, connection: Connection[Any]) -> None: ... + def close(self) -> None: ... + def setinputsizes(self, *args) -> None: ... + def setoutputsizes(self, *args) -> None: ... + def nextset(self) -> bool | None: ... + def mogrify(self, query: str, args: object = None) -> str: ... + def execute(self, query: str, args: object = None) -> int: ... + def executemany(self, query: str, args: Iterable[object]) -> int | None: ... + def callproc(self, procname: str, args: Iterable[Any] = ()) -> Any: ... + def scroll(self, value: int, mode: str = "relative") -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *exc_info: object) -> None: ... + # Methods returning result tuples are below. + def fetchone(self) -> tuple[Any, ...] | None: ... + def fetchmany(self, size: int | None = None) -> tuple[tuple[Any, ...], ...]: ... + def fetchall(self) -> tuple[tuple[Any, ...], ...]: ... + def __iter__(self) -> Iterator[tuple[Any, ...]]: ... + def __next__(self): ... + +class DictCursorMixin: + dict_type: Any # TODO: add support if someone needs this + def fetchone(self) -> dict[str, Any] | None: ... + def fetchmany(self, size: int | None = ...) -> tuple[dict[str, Any], ...]: ... + def fetchall(self) -> tuple[dict[str, Any], ...]: ... + def __iter__(self) -> Iterator[dict[str, Any]]: ... + +class SSCursor(Cursor): + def __del__(self) -> None: ... + def read_next(self) -> tuple[Any, ...] | None: ... + def fetchall(self) -> list[tuple[Any, ...]]: ... # type: ignore[override] + def fetchall_unbuffered(self) -> Iterator[tuple[Any, ...]]: ... + def scroll(self, value: int, mode: str = "relative") -> None: ... + +class DictCursor(DictCursorMixin, Cursor): ... # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + +class SSDictCursor(DictCursorMixin, SSCursor): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + def fetchall_unbuffered(self) -> Iterator[dict[str, Any]]: ... # type: ignore[override] + def read_next(self) -> dict[str, Any] | None: ... # type: ignore[override] diff --git a/stubs/PyMySQL/pymysql/err.pyi b/stubs/PyMySQL/pymysql/err.pyi new file mode 100644 index 000000000000..d8a2d837761c --- /dev/null +++ b/stubs/PyMySQL/pymysql/err.pyi @@ -0,0 +1,24 @@ +import builtins +from typing_extensions import Never + +from .constants import ER as ER + +class MySQLError(Exception): ... +class Warning(builtins.Warning, MySQLError): ... + +class Error(MySQLError): + sqlstate: str | None + def __init__(self, *args: object, sqlstate: str | None = None) -> None: ... + +class InterfaceError(Error): ... +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... + +error_map: dict[int, type[DatabaseError]] + +def raise_mysql_exception(data: bytes | bytearray) -> Never: ... diff --git a/stubs/PyMySQL/pymysql/optionfile.pyi b/stubs/PyMySQL/pymysql/optionfile.pyi new file mode 100644 index 000000000000..7848c4e04ec8 --- /dev/null +++ b/stubs/PyMySQL/pymysql/optionfile.pyi @@ -0,0 +1,40 @@ +import configparser +import sys +from collections.abc import Mapping, Sequence + +class Parser(configparser.RawConfigParser): + # __init__ signature was taken from RawConfigParser, but with no allow_no_value argument and all arguments are keyword-only + if sys.version_info >= (3, 13): + def __init__( + self, + *, + defaults: Mapping[str, str] | None = None, + dict_type: type[Mapping[str, str]] = ..., + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: configparser.Interpolation | None = ..., + converters: configparser._ConvertersMap = ..., + allow_unnamed_section: bool = False, + ) -> None: ... + else: + def __init__( + self, + *, + defaults: Mapping[str, str] | None = None, + dict_type: type[Mapping[str, str]] = ..., + delimiters: Sequence[str] = ("=", ":"), + comment_prefixes: Sequence[str] = ("#", ";"), + inline_comment_prefixes: Sequence[str] | None = None, + strict: bool = True, + empty_lines_in_values: bool = True, + default_section: str = "DEFAULT", + interpolation: configparser.Interpolation | None = ..., + converters: configparser._ConvertersMap = ..., + ) -> None: ... + + def optionxform(self, key: str) -> str: ... + def get(self, section: configparser._SectionName, option: str) -> str: ... # type: ignore[override] diff --git a/stubs/PyMySQL/pymysql/protocol.pyi b/stubs/PyMySQL/pymysql/protocol.pyi new file mode 100644 index 000000000000..dd742364215a --- /dev/null +++ b/stubs/PyMySQL/pymysql/protocol.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from typing import Final + +DEBUG: Final[bool] +NULL_COLUMN: Final[int] +UNSIGNED_CHAR_COLUMN: Final[int] +UNSIGNED_SHORT_COLUMN: Final[int] +UNSIGNED_INT24_COLUMN: Final[int] +UNSIGNED_INT64_COLUMN: Final[int] + +def dump_packet(data) -> None: ... + +class MysqlPacket: + __slots__ = ("_position", "_data") + def __init__(self, data, encoding) -> None: ... + def get_all_data(self): ... + def read(self, size): ... + def read_all(self): ... + def advance(self, length: int) -> None: ... + def rewind(self, position: int = 0) -> None: ... + def get_bytes(self, position: int, length: int = 1): ... + def read_uint8(self): ... + def read_uint16(self): ... + def read_uint24(self): ... + def read_uint32(self): ... + def read_uint64(self): ... + def read_string(self): ... + def read_length_encoded_integer(self) -> Incomplete | None: ... + def read_length_coded_string(self): ... + def read_struct(self, fmt: str): ... + def is_ok_packet(self) -> bool: ... + def is_eof_packet(self) -> bool: ... + def is_auth_switch_request(self) -> bool: ... + def is_extra_auth_data(self) -> bool: ... + def is_resultset_packet(self) -> bool: ... + def is_load_local_packet(self) -> bool: ... + def is_error_packet(self) -> bool: ... + def check_error(self) -> None: ... + def raise_for_error(self) -> None: ... + def dump(self) -> None: ... + +class FieldDescriptorPacket(MysqlPacket): + def __init__(self, data, encoding) -> None: ... + def description(self): ... + def get_column_length(self): ... + +class OKPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... + +class EOFPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... + +class LoadLocalPacketWrapper: + def __init__(self, from_packet) -> None: ... + # TODO: add attrs from `from_packet` + def __getattr__(self, key: str): ... diff --git a/stubs/PyMySQL/pymysql/times.pyi b/stubs/PyMySQL/pymysql/times.pyi new file mode 100644 index 000000000000..2c4f86f7ae31 --- /dev/null +++ b/stubs/PyMySQL/pymysql/times.pyi @@ -0,0 +1,10 @@ +from datetime import date, datetime, time, timedelta + +Date: type[date] +Time: type[time] +TimeDelta: type[timedelta] +Timestamp: type[datetime] + +def DateFromTicks(ticks: float | None) -> date: ... +def TimeFromTicks(ticks: float | None) -> time: ... +def TimestampFromTicks(ticks: float | None) -> datetime: ... diff --git a/stubs/PyScreeze/@tests/stubtest_allowlist.txt b/stubs/PyScreeze/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2fa942fc98c9 --- /dev/null +++ b/stubs/PyScreeze/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# present but unimplemented +pyscreeze.screenshotWindow diff --git a/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt b/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..fa9bd6fa07d7 --- /dev/null +++ b/stubs/PyScreeze/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# temp variable used to define scrotExists by checking if the command "scrot" exists +pyscreeze.whichProc diff --git a/stubs/PyScreeze/METADATA.toml b/stubs/PyScreeze/METADATA.toml new file mode 100644 index 000000000000..e14ea274756e --- /dev/null +++ b/stubs/PyScreeze/METADATA.toml @@ -0,0 +1,11 @@ +version = "1.0.1" +upstream-repository = "https://github.com/asweigart/pyscreeze" +dependencies = ["Pillow>=10.3.0"] + +[tool.stubtest] +# Linux has extra constants, win32 has different definitions +ci-platforms = ["linux", "win32"] +# PyScreeze has an odd setup.py file +# that doesn't list Pillow as a dependency for py312+ yet: +# https://github.com/asweigart/pyscreeze/blob/eeca245a135cf171c163b3691300138518efa64e/setup.py#L38-L46 +stubtest-dependencies = ["Pillow"] diff --git a/stubs/PyScreeze/pyscreeze/__init__.pyi b/stubs/PyScreeze/pyscreeze/__init__.pyi new file mode 100644 index 000000000000..5e1e7c7fb771 --- /dev/null +++ b/stubs/PyScreeze/pyscreeze/__init__.pyi @@ -0,0 +1,218 @@ +import sys +from _typeshed import ConvertibleToFloat, Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable, Generator +from typing import Final, NamedTuple, ParamSpec, TypeAlias, TypeVar, overload + +from PIL import Image + +_P = ParamSpec("_P") +_R = TypeVar("_R") +# cv2.typing.MatLike: is an alias for `numpy.ndarray | cv2.mat_wrapper.Mat`, Mat extends ndarray. +# But can't import either, because pyscreeze does not declare them as dependencies, stub_uploader won't let it. +_MatLike: TypeAlias = Incomplete + +PILLOW_VERSION: Final[tuple[int, int, int]] +RUNNING_PYTHON_2: Final = False +SCROT_EXISTS: Final[bool] +GNOMESCREENSHOT_EXISTS: Final[bool] + +if sys.platform == "linux": + RUNNING_X11: Final[bool] + RUNNING_WAYLAND: Final[bool] + +# Meant to be overridable as a setting +GRAYSCALE_DEFAULT: bool +# Meant to be overridable for backward-compatibility +USE_IMAGE_NOT_FOUND_EXCEPTION: bool + +class Box(NamedTuple): + left: int + top: int + width: int + height: int + +class Point(NamedTuple): + x: int + y: int + +class RGB(NamedTuple): + red: int + green: int + blue: int + +class PyScreezeException(Exception): ... +class ImageNotFoundException(PyScreezeException): ... + +def requiresPyGetWindow(wrappedFunction: Callable[_P, _R]) -> Callable[_P, _R]: ... + +# _locateAll_opencv +@overload +def locate( + needleImage: str | Image.Image | _MatLike, + haystackImage: str | Image.Image | _MatLike, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locate( + needleImage: str | Image.Image, + haystackImage: str | Image.Image, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +# _locateAll_opencv +@overload +def locateOnScreen( + image: str | Image.Image | _MatLike, + minSearchTime: float = 0, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locateOnScreen( + image: str | Image.Image, + minSearchTime: float = 0, + *, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +# _locateAll_opencv +@overload +def locateAllOnScreen( + image: str | Image.Image | _MatLike, + *, + grayscale: bool | None = None, + limit: int = 1000, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Generator[Box]: ... + +# _locateAll_pillow +@overload +def locateAllOnScreen( + image: str | Image.Image, + *, + grayscale: bool | None = None, + limit: int | None = None, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Generator[Box]: ... + +# _locateAll_opencv +@overload +def locateCenterOnScreen( + image: str | Image.Image | _MatLike, + *, + minSearchTime: float = 0, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Point | None: ... + +# _locateAll_pillow +@overload +def locateCenterOnScreen( + image: str | Image.Image, + *, + minSearchTime: float = 0, + grayscale: bool | None = None, + limit: Unused = 1, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Point | None: ... + +def locateOnScreenNear(image: str | Image.Image | _MatLike, x: int, y: int) -> Box: ... +def locateCenterOnScreenNear(image: str | Image.Image | _MatLike, x: int, y: int) -> Point | None: ... + +# _locateAll_opencv +@overload +def locateOnWindow( + image: str | Image.Image | _MatLike, + title: str, + *, + grayscale: bool | None = None, + limit: Unused = 1, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Box | None: ... + +# _locateAll_pillow +@overload +def locateOnWindow( + image: str | Image.Image, + title: str, + *, + grayscale: bool | None = None, + limit: Unused = 1, + step: int = 1, + confidence: None = None, +) -> Box | None: ... + +def showRegionOnScreen( + region: tuple[int, int, int, int], outlineColor: str = "red", filename: str = "_showRegionOnScreen.png" +) -> None: ... +def center(coords: tuple[int, int, int, int]) -> Point: ... +def pixelMatchesColor( + x: int, y: int, expectedRGBColor: tuple[int, int, int] | tuple[int, int, int, int], tolerance: int = 0 +) -> bool: ... +def pixel(x: int, y: int) -> tuple[int, int, int]: ... + +if sys.platform == "win32": + def screenshot( + imageFilename: StrOrBytesPath | None = None, region: tuple[int, int, int, int] | None = None, allScreens: bool = False + ) -> Image.Image: ... + +else: + def screenshot( + imageFilename: StrOrBytesPath | None = None, region: tuple[int, int, int, int] | None = None + ) -> Image.Image: ... + +# _locateAll_opencv +@overload +def locateAll( + needleImage: str | Image.Image | _MatLike, + haystackImage: str | Image.Image | _MatLike, + grayscale: bool | None = None, + limit: int = 1000, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: ConvertibleToFloat = 0.999, +) -> Generator[Box]: ... + +# _locateAll_pillow +@overload +def locateAll( + needleImage: str | Image.Image, + haystackImage: str | Image.Image, + grayscale: bool | None = None, + limit: int | None = None, + region: tuple[int, int, int, int] | None = None, + step: int = 1, + confidence: None = None, +) -> Generator[Box]: ... diff --git a/stubs/PySocks/@tests/stubtest_allowlist.txt b/stubs/PySocks/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..287b0a1f060f --- /dev/null +++ b/stubs/PySocks/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# Internal variables that were improperly leaked to the outside +socks.method +socks.name diff --git a/stubs/PySocks/METADATA.toml b/stubs/PySocks/METADATA.toml new file mode 100644 index 000000000000..2c0e6928c02f --- /dev/null +++ b/stubs/PySocks/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.7.1" +upstream-repository = "https://github.com/Anorov/PySocks" diff --git a/stubs/PySocks/socks.pyi b/stubs/PySocks/socks.pyi new file mode 100644 index 000000000000..18ecec651ef6 --- /dev/null +++ b/stubs/PySocks/socks.pyi @@ -0,0 +1,144 @@ +import logging +import socket +import types +from _typeshed import ReadableBuffer +from collections.abc import Callable, Iterable, Mapping +from typing import Final, ParamSpec, TypeAlias, TypeVar, overload + +__version__: Final[str] + +log: logging.Logger # undocumented + +_ProxyType: TypeAlias = int + +PROXY_TYPE_SOCKS4: Final[_ProxyType] +SOCKS4: Final[_ProxyType] +PROXY_TYPE_SOCKS5: Final[_ProxyType] +SOCKS5: Final[_ProxyType] +PROXY_TYPE_HTTP: Final[_ProxyType] +HTTP: Final[_ProxyType] + +PROXY_TYPES: Final[dict[str, _ProxyType]] +PRINTABLE_PROXY_TYPES: Final[dict[_ProxyType, str]] + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +def set_self_blocking(function: Callable[_P, _T]) -> Callable[_P, _T]: ... # undocumented + +class ProxyError(IOError): + msg: str + socket_err: socket.error + def __init__(self, msg: str, socket_err: socket.error | None = None) -> None: ... + +class GeneralProxyError(ProxyError): ... +class ProxyConnectionError(ProxyError): ... +class SOCKS5AuthError(ProxyError): ... +class SOCKS5Error(ProxyError): ... +class SOCKS4Error(ProxyError): ... +class HTTPError(ProxyError): ... + +SOCKS4_ERRORS: Final[Mapping[int, str]] +SOCKS5_ERRORS: Final[Mapping[int, str]] +DEFAULT_PORTS: Final[Mapping[_ProxyType, int]] + +_DefaultProxy: TypeAlias = tuple[_ProxyType | None, str | None, int | None, bool, bytes | None, bytes | None] + +def set_default_proxy( + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, +) -> None: ... +def setdefaultproxy( + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + proxytype: _ProxyType = ..., +) -> None: ... +def get_default_proxy() -> _DefaultProxy | None: ... + +getdefaultproxy = get_default_proxy + +def wrap_module(module: types.ModuleType) -> None: ... + +wrapmodule = wrap_module + +_Endpoint: TypeAlias = tuple[str, int] + +def create_connection( + dest_pair: _Endpoint, + timeout: int | None = None, + source_address: _Endpoint | None = None, + proxy_type: _ProxyType | None = None, + proxy_addr: str | None = None, + proxy_port: int | None = None, + proxy_rdns: bool = True, + proxy_username: str | None = None, + proxy_password: str | None = None, + socket_options: ( + Iterable[tuple[int, int, int | ReadableBuffer] | tuple[int, int, None, int]] | None + ) = None, # values passing to `socket.setsockopt` method +) -> socksocket: ... + +class _BaseSocket(socket.socket): # undocumented + ... + +class socksocket(_BaseSocket): + default_proxy: _DefaultProxy | None # undocumented + proxy: _DefaultProxy # undocumented + proxy_sockname: _Endpoint | None # undocumented + proxy_peername: _Endpoint | None # undocumented + def __init__( + self, family: socket.AddressFamily = ..., type: socket.SocketKind = ..., proto: int = 0, fileno: int | None = None + ) -> None: ... + def settimeout(self, timeout: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, v: bool) -> None: ... + def set_proxy( + self, + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + ) -> None: ... + def setproxy( + self, + proxy_type: _ProxyType | None = None, + addr: str | None = None, + port: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + proxytype: _ProxyType = ..., + ) -> None: ... + def bind(self, address: socket._Address, /) -> None: ... + + @overload + def sendto(self, bytes: ReadableBuffer, address: socket._Address) -> int: ... + @overload + def sendto(self, bytes: ReadableBuffer, flags: int, address: socket._Address) -> int: ... + + def send(self, bytes: ReadableBuffer, flags: int = 0) -> int: ... + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _Endpoint]: ... + def recv(self, bufsize: int, flags: int = 0) -> bytes: ... + def close(self) -> None: ... + def get_proxy_sockname(self) -> _Endpoint | None: ... + getproxysockname = get_proxy_sockname + def get_proxy_peername(self) -> _Endpoint | None: ... + getproxypeername = get_proxy_peername + def get_peername(self) -> _Endpoint | None: ... + getpeername = get_peername + @set_self_blocking + def connect(self, dest_pair: _Endpoint, catch_errors: bool | None = None) -> None: ... # type: ignore[override] + @set_self_blocking + def connect_ex(self, dest_pair: _Endpoint) -> int: ... # type: ignore[override] diff --git a/stubs/PySocks/sockshandler.pyi b/stubs/PySocks/sockshandler.pyi new file mode 100644 index 000000000000..94d1ceec399f --- /dev/null +++ b/stubs/PySocks/sockshandler.pyi @@ -0,0 +1,97 @@ +import http.client +import ssl +import sys +import urllib.request +from _typeshed import Incomplete, SupportsKeysAndGetItem +from typing import Any, TypeVar + +import socks + +_K = TypeVar("_K") +_V = TypeVar("_V") + +def merge_dict(a: dict[_K, _V], b: SupportsKeysAndGetItem[_K, _V]) -> dict[_K, _V]: ... # undocumented +def is_ip(s: str) -> bool: ... # undocumented + +socks4_no_rdns: set[str] # undocumented + +class SocksiPyConnection(http.client.HTTPConnection): # undocumented + proxyargs: tuple[int, str, int | None, bool, str | None, str | None] + sock: socks.socksocket + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + ) -> None: ... + def connect(self) -> None: ... + +class SocksiPyConnectionS(http.client.HTTPSConnection): # undocumented + proxyargs: tuple[int, str, int | None, bool, str | None, str | None] + sock: socks.socksocket + if sys.version_info >= (3, 12): + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + *, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + ) -> None: ... + else: + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + key_file: str | None = None, + cert_file: str | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + context: ssl.SSLContext | None = None, + check_hostname: bool | None = None, + blocksize: int = 8192, + ) -> None: ... + + def connect(self) -> None: ... + +class SocksiPyHandler(urllib.request.HTTPHandler, urllib.request.HTTPSHandler): + args: tuple[Incomplete, ...] # undocumented + kw: dict[str, Incomplete] # undocumented + def __init__( + self, + proxytype: int, + proxyaddr: str, + proxyport: int | None = None, + rdns: bool = True, + username: str | None = None, + password: str | None = None, + *, + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + **kwargs: Any, # any additional arguments to `SocksiPyConnection` or `SocksiPyConnectionS` + ) -> None: ... + def http_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: ... # undocumented + def https_open(self, req: urllib.request.Request) -> http.client.HTTPResponse: ... # undocumented diff --git a/stubs/PyYAML/@tests/stubtest_allowlist.txt b/stubs/PyYAML/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a50b77fb0b53 --- /dev/null +++ b/stubs/PyYAML/@tests/stubtest_allowlist.txt @@ -0,0 +1,11 @@ +# yaml._yaml is for backwards compatibility so none of it matters anyway +yaml._yaml.__test__ + +# Some arguments to these functions are technically positional or keyword +# arguments at runtime, but according to the documentation and other, +# similar functions, it's safer to treat them as keyword-only arguments. +yaml.dump_all +yaml.serialize_all + +# Auto-generated methods by Cython +.*_cython__ diff --git a/stubs/PyYAML/METADATA.toml b/stubs/PyYAML/METADATA.toml new file mode 100644 index 000000000000..036c3b255825 --- /dev/null +++ b/stubs/PyYAML/METADATA.toml @@ -0,0 +1,2 @@ +version = "6.0.*" +upstream-repository = "https://github.com/yaml/pyyaml" diff --git a/stubs/PyYAML/yaml/__init__.pyi b/stubs/PyYAML/yaml/__init__.pyi new file mode 100644 index 000000000000..189ea6812997 --- /dev/null +++ b/stubs/PyYAML/yaml/__init__.pyi @@ -0,0 +1,450 @@ +from collections.abc import Callable, Iterable, Iterator, Mapping +from re import Pattern +from typing import Any, TypeVar, overload + +from . import resolver as resolver # Help mypy a bit; this is implied by loader and dumper +from .constructor import BaseConstructor +from .cyaml import * +from .cyaml import _CLoader +from .dumper import * +from .dumper import _Inf +from .emitter import _WriteStream +from .error import * +from .events import * +from .loader import * +from .loader import _Loader +from .nodes import * +from .reader import _ReadStream +from .representer import BaseRepresenter +from .resolver import BaseResolver +from .tokens import * + +_T = TypeVar("_T") +_Constructor = TypeVar("_Constructor", bound=BaseConstructor) +_Representer = TypeVar("_Representer", bound=BaseRepresenter) + +__with_libyaml__: bool +__version__: str + +def warnings(settings=None): ... +def scan(stream, Loader: type[_Loader | _CLoader] = ...): ... +def parse(stream, Loader: type[_Loader | _CLoader] = ...): ... +def compose(stream, Loader: type[_Loader | _CLoader] = ...): ... +def compose_all(stream, Loader: type[_Loader | _CLoader] = ...): ... +def load(stream: _ReadStream, Loader: type[_Loader | _CLoader]) -> Any: ... +def load_all(stream: _ReadStream, Loader: type[_Loader | _CLoader]) -> Iterator[Any]: ... +def full_load(stream: _ReadStream) -> Any: ... +def full_load_all(stream: _ReadStream) -> Iterator[Any]: ... +def safe_load(stream: _ReadStream) -> Any: ... +def safe_load_all(stream: _ReadStream) -> Iterator[Any]: ... +def unsafe_load(stream: _ReadStream) -> Any: ... +def unsafe_load_all(stream: _ReadStream) -> Iterator[Any]: ... +def emit( + events, + stream: _WriteStream[Any] | None = None, + Dumper=..., + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, +): ... + +@overload +def serialize_all( + nodes, + stream: _WriteStream[Any], + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> None: ... +@overload +def serialize_all( + nodes, + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> str: ... +@overload +def serialize_all( + nodes, + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> bytes: ... + +@overload +def serialize( + node, + stream: _WriteStream[Any], + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> None: ... +@overload +def serialize( + node, + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> str: ... +@overload +def serialize( + node, + stream: None = None, + Dumper=..., + *, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, +) -> bytes: ... + +@overload +def dump_all( + documents: Iterable[Any], + stream: _WriteStream[Any], + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> None: ... +@overload +def dump_all( + documents: Iterable[Any], + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def dump_all( + documents: Iterable[Any], + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + +@overload +def dump( + data: Any, + stream: _WriteStream[Any], + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> None: ... +@overload +def dump( + data: Any, + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def dump( + data: Any, + stream: None = None, + Dumper=..., + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + +@overload +def safe_dump_all( + documents: Iterable[Any], + stream: _WriteStream[Any], + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> None: ... +@overload +def safe_dump_all( + documents: Iterable[Any], + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def safe_dump_all( + documents: Iterable[Any], + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + +@overload +def safe_dump( + data: Any, + stream: _WriteStream[Any], + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> None: ... +@overload +def safe_dump( + data: Any, + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> str: ... +@overload +def safe_dump( + data: Any, + stream: None = None, + *, + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, +) -> bytes: ... + +def add_implicit_resolver( + tag: str, + regexp: Pattern[str], + first: Iterable[Any] | None = None, + Loader: type[BaseResolver] | None = None, + Dumper: type[BaseResolver] = ..., +) -> None: ... +def add_path_resolver( + tag: str, + path: Iterable[Any], + kind: type[Any] | None = None, + Loader: type[BaseResolver] | None = None, + Dumper: type[BaseResolver] = ..., +) -> None: ... + +@overload +def add_constructor( + tag: str, constructor: Callable[[Loader | FullLoader | UnsafeLoader, Node], Any], Loader: None = None +) -> None: ... +@overload +def add_constructor(tag: str, constructor: Callable[[_Constructor, Node], Any], Loader: type[_Constructor]) -> None: ... + +@overload +def add_multi_constructor( + tag_prefix: str, multi_constructor: Callable[[Loader | FullLoader | UnsafeLoader, str, Node], Any], Loader: None = None +) -> None: ... +@overload +def add_multi_constructor( + tag_prefix: str, multi_constructor: Callable[[_Constructor, str, Node], Any], Loader: type[_Constructor] +) -> None: ... + +@overload +def add_representer(data_type: type[_T], representer: Callable[[Dumper, _T], Node]) -> None: ... +@overload +def add_representer(data_type: type[_T], representer: Callable[[_Representer, _T], Node], Dumper: type[_Representer]) -> None: ... + +@overload +def add_multi_representer(data_type: type[_T], multi_representer: Callable[[Dumper, _T], Node]) -> None: ... +@overload +def add_multi_representer( + data_type: type[_T], multi_representer: Callable[[_Representer, _T], Node], Dumper: type[_Representer] +) -> None: ... + +class YAMLObjectMetaclass(type): + def __init__(cls, name, bases, kwds) -> None: ... + +class YAMLObject(metaclass=YAMLObjectMetaclass): + __slots__ = () + yaml_loader: Any + yaml_dumper: Any + yaml_tag: Any + yaml_flow_style: Any + @classmethod + def from_yaml(cls, loader, node): ... + @classmethod + def to_yaml(cls, dumper, data): ... diff --git a/stubs/PyYAML/yaml/_yaml.pyi b/stubs/PyYAML/yaml/_yaml.pyi new file mode 100644 index 000000000000..f7412770b57a --- /dev/null +++ b/stubs/PyYAML/yaml/_yaml.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete, SupportsRead +from collections.abc import Mapping, Sequence +from typing import IO, Any +from typing_extensions import disjoint_base + +from .events import Event +from .nodes import Node +from .tokens import Token + +def get_version_string() -> str: ... +def get_version() -> tuple[int, int, int]: ... + +@disjoint_base +class Mark: + name: Any + index: int + line: int + column: int + buffer: Any + pointer: Any + def __init__(self, name, index: int, line: int, column: int, buffer, pointer) -> None: ... + def get_snippet(self): ... + +@disjoint_base +class CParser: + def __init__(self, stream: str | bytes | SupportsRead[str | bytes]) -> None: ... + def dispose(self) -> None: ... + def get_token(self) -> Token | None: ... + def peek_token(self) -> Token | None: ... + def check_token(self, *choices) -> bool: ... + def get_event(self) -> Event | None: ... + def peek_event(self) -> Event | None: ... + def check_event(self, *choices) -> bool: ... + def check_node(self) -> bool: ... + def get_node(self) -> Node | None: ... + def get_single_node(self) -> Node | None: ... + def raw_parse(self) -> int: ... + def raw_scan(self) -> int: ... + +@disjoint_base +class CEmitter: + def __init__( + self, + stream: IO[Any], + canonical: Incomplete | None = ..., + indent: int | None = ..., + width: int | None = ..., + allow_unicode: Incomplete | None = ..., + line_break: str | None = ..., + encoding: str | None = ..., + explicit_start: Incomplete | None = ..., + explicit_end: Incomplete | None = ..., + version: Sequence[int] | None = ..., + tags: Mapping[str, str] | None = ..., + ) -> None: ... + def dispose(self) -> None: ... + def emit(self, event_object) -> None: ... + def open(self) -> None: ... + def close(self) -> None: ... + def serialize(self, node) -> None: ... diff --git a/stubs/PyYAML/yaml/composer.pyi b/stubs/PyYAML/yaml/composer.pyi new file mode 100644 index 000000000000..4c80c5bd3da8 --- /dev/null +++ b/stubs/PyYAML/yaml/composer.pyi @@ -0,0 +1,20 @@ +from typing import Any + +from yaml.error import MarkedYAMLError +from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode + +class ComposerError(MarkedYAMLError): ... + +class Composer: + anchors: dict[Any, Node] + def __init__(self) -> None: ... + def check_node(self) -> bool: ... + def get_node(self) -> Node | None: ... + def get_single_node(self) -> Node | None: ... + def compose_document(self) -> Node | None: ... + def compose_node(self, parent: Node | None, index: int) -> Node | None: ... + def compose_scalar_node(self, anchor: dict[Any, Node]) -> ScalarNode: ... + def compose_sequence_node(self, anchor: dict[Any, Node]) -> SequenceNode: ... + def compose_mapping_node(self, anchor: dict[Any, Node]) -> MappingNode: ... + +__all__ = ["Composer", "ComposerError"] diff --git a/stubs/PyYAML/yaml/constructor.pyi b/stubs/PyYAML/yaml/constructor.pyi new file mode 100644 index 000000000000..cfbe7828b019 --- /dev/null +++ b/stubs/PyYAML/yaml/constructor.pyi @@ -0,0 +1,105 @@ +from collections.abc import Callable, Hashable +from datetime import date +from re import Pattern +from typing import Any, ClassVar, TypeVar + +from yaml.error import MarkedYAMLError +from yaml.nodes import MappingNode, Node, ScalarNode, SequenceNode + +from .cyaml import _CLoader +from .loader import _Loader + +_L = TypeVar("_L", bound=_Loader | _CLoader) +_N = TypeVar("_N", bound=Node) + +class ConstructorError(MarkedYAMLError): ... + +class BaseConstructor: + yaml_constructors: Any + yaml_multi_constructors: Any + constructed_objects: Any + recursive_objects: Any + state_generators: Any + deep_construct: Any + def __init__(self) -> None: ... + def check_data(self): ... + def check_state_key(self, key: str) -> None: ... + def get_data(self): ... + def get_single_data(self) -> Any: ... + def construct_document(self, node): ... + def construct_object(self, node, deep: bool = False): ... + def construct_scalar(self, node: ScalarNode) -> str: ... + def construct_sequence(self, node: SequenceNode, deep: bool = False) -> list[Any]: ... + def construct_mapping(self, node: MappingNode, deep: bool = False) -> dict[Hashable, Any]: ... + def construct_pairs(self, node, deep: bool = False): ... + @classmethod + # Use typevars so we can have covariant behaviour in the parameter types + def add_constructor(cls, tag: str, constructor: Callable[[_L, _N], Any]) -> None: ... + @classmethod + def add_multi_constructor(cls, tag_prefix, multi_constructor): ... + +class SafeConstructor(BaseConstructor): + def construct_scalar(self, node: ScalarNode | MappingNode) -> str: ... + def flatten_mapping(self, node: MappingNode) -> None: ... + def construct_mapping(self, node: MappingNode, deep: bool = False) -> dict[Hashable, Any]: ... + def construct_yaml_null(self, node: ScalarNode) -> None: ... + bool_values: ClassVar[dict[str, bool]] + def construct_yaml_bool(self, node: ScalarNode) -> bool: ... + def construct_yaml_int(self, node: ScalarNode) -> int: ... + inf_value: ClassVar[float] + nan_value: ClassVar[float] + def construct_yaml_float(self, node: ScalarNode) -> float: ... + def construct_yaml_binary(self, node: ScalarNode) -> bytes: ... + timestamp_regexp: ClassVar[Pattern[str]] + def construct_yaml_timestamp(self, node: ScalarNode) -> date: ... + def construct_yaml_omap(self, node): ... + def construct_yaml_pairs(self, node): ... + def construct_yaml_set(self, node): ... + def construct_yaml_str(self, node): ... + def construct_yaml_seq(self, node): ... + def construct_yaml_map(self, node): ... + def construct_yaml_object(self, node, cls): ... + def construct_undefined(self, node): ... + +class FullConstructor(SafeConstructor): + def get_state_keys_blacklist(self) -> list[str]: ... + def get_state_keys_blacklist_regexp(self) -> Pattern[str]: ... + def construct_python_str(self, node): ... + def construct_python_unicode(self, node): ... + def construct_python_bytes(self, node): ... + def construct_python_long(self, node): ... + def construct_python_complex(self, node): ... + def construct_python_tuple(self, node): ... + def find_python_module(self, name: str, mark, unsafe: bool = False): ... + def find_python_name(self, name: str, mark, unsafe: bool = False): ... + def construct_python_name(self, suffix, node): ... + def construct_python_module(self, suffix, node): ... + def make_python_instance(self, suffix, node, args=None, kwds=None, newobj: bool = False, unsafe: bool = False): ... + def set_python_instance_state(self, instance: Any, state, unsafe: bool = False) -> None: ... + def construct_python_object(self, suffix, node): ... + def construct_python_object_apply(self, suffix, node, newobj=False): ... + def construct_python_object_new(self, suffix, node): ... + +class UnsafeConstructor(FullConstructor): + def find_python_module(self, name: str, mark): ... # type: ignore[override] + def find_python_name(self, name: str, mark): ... # type: ignore[override] + def make_python_instance(self, suffix: str, node, args=None, kwds=None, newobj: bool = False): ... # type: ignore[override] + def set_python_instance_state(self, instance: Any, state): ... # type: ignore[override] + +class Constructor(SafeConstructor): + def construct_python_str(self, node): ... + def construct_python_unicode(self, node): ... + def construct_python_long(self, node): ... + def construct_python_complex(self, node): ... + def construct_python_tuple(self, node): ... + def find_python_module(self, name, mark): ... + def find_python_name(self, name, mark): ... + def construct_python_name(self, suffix, node): ... + def construct_python_module(self, suffix, node): ... + def make_python_instance(self, suffix, node, args=None, kwds=None, newobj=False): ... + def set_python_instance_state(self, instance, state): ... + def construct_python_object(self, suffix, node): ... + def construct_python_object_apply(self, suffix, node, newobj=False): ... + def construct_python_object_new(self, suffix, node): ... + +__all__ = ["BaseConstructor", "SafeConstructor", "FullConstructor", "UnsafeConstructor", "Constructor", "ConstructorError"] diff --git a/stubs/PyYAML/yaml/cyaml.pyi b/stubs/PyYAML/yaml/cyaml.pyi new file mode 100644 index 000000000000..abe297bd4da1 --- /dev/null +++ b/stubs/PyYAML/yaml/cyaml.pyi @@ -0,0 +1,68 @@ +from _typeshed import SupportsRead +from collections.abc import Mapping, Sequence +from typing import IO, Any, TypeAlias + +from ._yaml import CEmitter, CParser +from .constructor import BaseConstructor, FullConstructor, SafeConstructor, UnsafeConstructor +from .representer import BaseRepresenter, SafeRepresenter +from .resolver import BaseResolver, Resolver + +__all__ = ["CBaseLoader", "CSafeLoader", "CFullLoader", "CUnsafeLoader", "CLoader", "CBaseDumper", "CSafeDumper", "CDumper"] + +_Readable: TypeAlias = SupportsRead[str | bytes] +_CLoader: TypeAlias = CLoader | CBaseLoader | CFullLoader | CSafeLoader | CUnsafeLoader # noqa: Y047 # Used in other modules + +class CBaseLoader(CParser, BaseConstructor, BaseResolver): + def __init__(self, stream: str | bytes | _Readable) -> None: ... + +class CLoader(CParser, SafeConstructor, Resolver): + def __init__(self, stream: str | bytes | _Readable) -> None: ... + +class CSafeLoader(CParser, SafeConstructor, Resolver): + def __init__(self, stream: str | bytes | _Readable) -> None: ... + +class CFullLoader(CParser, FullConstructor, Resolver): + def __init__(self, stream: str | bytes | _Readable) -> None: ... + +class CUnsafeLoader(CParser, UnsafeConstructor, Resolver): + def __init__(self, stream: str | bytes | _Readable) -> None: ... + +class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): + def __init__( + self, + stream: IO[Any], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical=None, + indent: int | None = None, + width: int | None = None, + allow_unicode=None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start=None, + explicit_end=None, + version: Sequence[int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, + ) -> None: ... + +class CDumper(CEmitter, SafeRepresenter, Resolver): + def __init__( + self, + stream: IO[Any], + default_style: str | None = None, + default_flow_style: bool = False, + canonical=None, + indent: int | None = None, + width: int | None = None, + allow_unicode=None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start=None, + explicit_end=None, + version: Sequence[int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, + ) -> None: ... + +CSafeDumper = CDumper diff --git a/stubs/PyYAML/yaml/dumper.pyi b/stubs/PyYAML/yaml/dumper.pyi new file mode 100644 index 000000000000..e7b18733101d --- /dev/null +++ b/stubs/PyYAML/yaml/dumper.pyi @@ -0,0 +1,72 @@ +from collections.abc import Mapping +from typing import Any, TypeAlias + +from yaml.emitter import Emitter +from yaml.representer import BaseRepresenter, Representer, SafeRepresenter +from yaml.resolver import BaseResolver, Resolver +from yaml.serializer import Serializer + +from .emitter import _WriteStream + +# Ideally, there would be a way to limit these values to only +/- float("inf"), +# but that's not possible at the moment (https://github.com/python/typing/issues/1160). +_Inf: TypeAlias = float + +class BaseDumper(Emitter, Serializer, BaseRepresenter, BaseResolver): + def __init__( + self, + stream: _WriteStream[Any], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, + ) -> None: ... + +class SafeDumper(Emitter, Serializer, SafeRepresenter, Resolver): + def __init__( + self, + stream: _WriteStream[Any], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, + ) -> None: ... + +class Dumper(Emitter, Serializer, Representer, Resolver): + def __init__( + self, + stream: _WriteStream[Any], + default_style: str | None = None, + default_flow_style: bool | None = False, + canonical: bool | None = None, + indent: int | None = None, + width: int | _Inf | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + encoding: str | None = None, + explicit_start: bool | None = None, + explicit_end: bool | None = None, + version: tuple[int, int] | None = None, + tags: Mapping[str, str] | None = None, + sort_keys: bool = True, + ) -> None: ... + +__all__ = ["BaseDumper", "SafeDumper", "Dumper"] diff --git a/stubs/PyYAML/yaml/emitter.pyi b/stubs/PyYAML/yaml/emitter.pyi new file mode 100644 index 000000000000..3a19e94a31a9 --- /dev/null +++ b/stubs/PyYAML/yaml/emitter.pyi @@ -0,0 +1,136 @@ +from collections.abc import Callable +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Never + +from yaml.error import YAMLError + +from .events import Event + +_T_contra = TypeVar("_T_contra", str, bytes, contravariant=True) + +@type_check_only +class _WriteStream(Protocol[_T_contra]): + def write(self, data: _T_contra, /) -> object: ... + # Optional fields: + # encoding: str + # def flush(self) -> object: ... + +class EmitterError(YAMLError): ... + +class ScalarAnalysis: + scalar: Any + empty: Any + multiline: Any + allow_flow_plain: Any + allow_block_plain: Any + allow_single_quoted: Any + allow_double_quoted: Any + allow_block: Any + def __init__( + self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block + ) -> None: ... + +class Emitter: + DEFAULT_TAG_PREFIXES: dict[str, str] + stream: _WriteStream[Any] + encoding: str | None + states: list[Callable[[], None]] + state: Callable[[], None] | None + events: list[Event] + event: Event | None + indents: list[int | None] + indent: int | None + flow_level: int + root_context: bool + sequence_context: bool + mapping_context: bool + simple_key_context: bool + line: int + column: int + whitespace: bool + indention: bool + open_ended: bool + canonical: bool | None + allow_unicode: bool | None + best_indent: int + best_width: int + best_line_break: str + tag_prefixes: dict[str, str] | None + prepared_anchor: str | None + prepared_tag: str | None + analysis: ScalarAnalysis | None + style: str | None + def __init__( + self, + stream: _WriteStream[Any], + canonical: bool | None = None, + indent: int | None = None, + width: int | None = None, + allow_unicode: bool | None = None, + line_break: str | None = None, + ) -> None: ... + def dispose(self) -> None: ... + def emit(self, event: Event) -> None: ... + def need_more_events(self) -> bool: ... + def need_events(self, count: int) -> bool: ... + def increase_indent(self, flow: bool = False, indentless: bool = False) -> None: ... + def expect_stream_start(self) -> None: ... + def expect_nothing(self) -> Never: ... + def expect_first_document_start(self) -> None: ... + def expect_document_start(self, first: bool = False) -> None: ... + def expect_document_end(self) -> None: ... + def expect_document_root(self) -> None: ... + def expect_node( + self, root: bool = False, sequence: bool = False, mapping: bool = False, simple_key: bool = False + ) -> None: ... + def expect_alias(self) -> None: ... + def expect_scalar(self) -> None: ... + def expect_flow_sequence(self) -> None: ... + def expect_first_flow_sequence_item(self) -> None: ... + def expect_flow_sequence_item(self) -> None: ... + def expect_flow_mapping(self) -> None: ... + def expect_first_flow_mapping_key(self) -> None: ... + def expect_flow_mapping_key(self) -> None: ... + def expect_flow_mapping_simple_value(self) -> None: ... + def expect_flow_mapping_value(self) -> None: ... + def expect_block_sequence(self) -> None: ... + def expect_first_block_sequence_item(self) -> None: ... + def expect_block_sequence_item(self, first: bool = False) -> None: ... + def expect_block_mapping(self) -> None: ... + def expect_first_block_mapping_key(self) -> None: ... + def expect_block_mapping_key(self, first: bool = False) -> None: ... + def expect_block_mapping_simple_value(self) -> None: ... + def expect_block_mapping_value(self) -> None: ... + def check_empty_sequence(self) -> bool: ... + def check_empty_mapping(self) -> bool: ... + def check_empty_document(self) -> bool: ... + def check_simple_key(self) -> bool: ... + def process_anchor(self, indicator: str) -> None: ... + def process_tag(self) -> None: ... + def choose_scalar_style(self) -> str: ... + def process_scalar(self) -> None: ... + def prepare_version(self, version) -> str: ... + def prepare_tag_handle(self, handle: str) -> str: ... + def prepare_tag_prefix(self, prefix: str) -> str: ... + def prepare_tag(self, tag: str) -> str: ... + def prepare_anchor(self, anchor: str) -> str: ... + def analyze_scalar(self, scalar: str) -> ScalarAnalysis: ... + def flush_stream(self) -> None: ... + def write_stream_start(self) -> None: ... + def write_stream_end(self) -> None: ... + def write_indicator( + self, indicator: str, need_whitespace: bool, whitespace: bool = False, indention: bool = False + ) -> None: ... + def write_indent(self) -> None: ... + def write_line_break(self, data: str | None = None) -> None: ... + def write_version_directive(self, version_text: str) -> None: ... + def write_tag_directive(self, handle_text: str, prefix_text: str) -> None: ... + def write_single_quoted(self, text: str, split: bool = True) -> None: ... + ESCAPE_REPLACEMENTS: dict[str, str] + def write_double_quoted(self, text: str, split: bool = True) -> None: ... + def determine_block_hints(self, text: str) -> str: ... + def write_folded(self, text: str) -> None: ... + def write_literal(self, text: str) -> None: ... + def write_plain(self, text: str, split: bool = True) -> None: ... + +__all__ = ["Emitter", "EmitterError"] diff --git a/stubs/PyYAML/yaml/error.pyi b/stubs/PyYAML/yaml/error.pyi new file mode 100644 index 000000000000..9fe53f15d838 --- /dev/null +++ b/stubs/PyYAML/yaml/error.pyi @@ -0,0 +1,28 @@ +class Mark: + name: str + index: int + line: int + column: int + buffer: str | None + pointer: int + def __init__(self, name: str, index: int, line: int, column: int, buffer: str | None, pointer: int) -> None: ... + def get_snippet(self, indent: int = 4, max_length: int = 75) -> str | None: ... + +class YAMLError(Exception): ... + +class MarkedYAMLError(YAMLError): + context: str | None + context_mark: Mark | None + problem: str | None + problem_mark: Mark | None + note: str | None + def __init__( + self, + context: str | None = None, + context_mark: Mark | None = None, + problem: str | None = None, + problem_mark: Mark | None = None, + note: str | None = None, + ) -> None: ... + +__all__ = ["Mark", "YAMLError", "MarkedYAMLError"] diff --git a/stubs/PyYAML/yaml/events.pyi b/stubs/PyYAML/yaml/events.pyi new file mode 100644 index 000000000000..e4e2a8f1ce8b --- /dev/null +++ b/stubs/PyYAML/yaml/events.pyi @@ -0,0 +1,62 @@ +from typing import Any + +class Event: + start_mark: Any + end_mark: Any + def __init__(self, start_mark=None, end_mark=None) -> None: ... + +class NodeEvent(Event): + anchor: Any + start_mark: Any + end_mark: Any + def __init__(self, anchor, start_mark=None, end_mark=None) -> None: ... + +class CollectionStartEvent(NodeEvent): + anchor: Any + tag: Any + implicit: Any + start_mark: Any + end_mark: Any + flow_style: Any + def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None, flow_style=None) -> None: ... + +class CollectionEndEvent(Event): ... + +class StreamStartEvent(Event): + start_mark: Any + end_mark: Any + encoding: Any + def __init__(self, start_mark=None, end_mark=None, encoding=None) -> None: ... + +class StreamEndEvent(Event): ... + +class DocumentStartEvent(Event): + start_mark: Any + end_mark: Any + explicit: Any + version: Any + tags: Any + def __init__(self, start_mark=None, end_mark=None, explicit=None, version=None, tags=None) -> None: ... + +class DocumentEndEvent(Event): + start_mark: Any + end_mark: Any + explicit: Any + def __init__(self, start_mark=None, end_mark=None, explicit=None) -> None: ... + +class AliasEvent(NodeEvent): ... + +class ScalarEvent(NodeEvent): + anchor: Any + tag: Any + implicit: Any + value: Any + start_mark: Any + end_mark: Any + style: Any + def __init__(self, anchor, tag, implicit, value, start_mark=None, end_mark=None, style=None) -> None: ... + +class SequenceStartEvent(CollectionStartEvent): ... +class SequenceEndEvent(CollectionEndEvent): ... +class MappingStartEvent(CollectionStartEvent): ... +class MappingEndEvent(CollectionEndEvent): ... diff --git a/stubs/PyYAML/yaml/loader.pyi b/stubs/PyYAML/yaml/loader.pyi new file mode 100644 index 000000000000..5f29f390c2e0 --- /dev/null +++ b/stubs/PyYAML/yaml/loader.pyi @@ -0,0 +1,29 @@ +from typing import TypeAlias + +from yaml.composer import Composer +from yaml.constructor import BaseConstructor, Constructor, FullConstructor, SafeConstructor +from yaml.parser import Parser +from yaml.reader import Reader +from yaml.resolver import BaseResolver, Resolver +from yaml.scanner import Scanner + +from .reader import _ReadStream + +_Loader: TypeAlias = Loader | BaseLoader | FullLoader | SafeLoader | UnsafeLoader # noqa: Y047 # Used in other modules + +class BaseLoader(Reader, Scanner, Parser, Composer, BaseConstructor, BaseResolver): + def __init__(self, stream: _ReadStream) -> None: ... + +class FullLoader(Reader, Scanner, Parser, Composer, FullConstructor, Resolver): + def __init__(self, stream: _ReadStream) -> None: ... + +class SafeLoader(Reader, Scanner, Parser, Composer, SafeConstructor, Resolver): + def __init__(self, stream: _ReadStream) -> None: ... + +class Loader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + def __init__(self, stream: _ReadStream) -> None: ... + +class UnsafeLoader(Reader, Scanner, Parser, Composer, Constructor, Resolver): + def __init__(self, stream: _ReadStream) -> None: ... + +__all__ = ["BaseLoader", "FullLoader", "SafeLoader", "Loader", "UnsafeLoader"] diff --git a/stubs/PyYAML/yaml/nodes.pyi b/stubs/PyYAML/yaml/nodes.pyi new file mode 100644 index 000000000000..de490db93d1a --- /dev/null +++ b/stubs/PyYAML/yaml/nodes.pyi @@ -0,0 +1,32 @@ +from typing import Any, ClassVar + +from yaml.error import Mark + +# Any Unions: Avoid forcing the user to check for None when they know what Node was instantiated with +# Using generics may be overkill without support for default Generics +# Permissive Unions could also be useful here. +class Node: + tag: str + value: Any + start_mark: Mark | Any + end_mark: Mark | Any + def __init__(self, tag: str, value, start_mark: Mark | None, end_mark: Mark | None) -> None: ... + +class ScalarNode(Node): + id: ClassVar[str] + style: str | Any + def __init__( + self, tag: str, value, start_mark: Mark | None = None, end_mark: Mark | None = None, style: str | None = None + ) -> None: ... + +class CollectionNode(Node): + flow_style: bool | Any + def __init__( + self, tag: str, value, start_mark: Mark | None = None, end_mark: Mark | None = None, flow_style: bool | None = None + ) -> None: ... + +class SequenceNode(CollectionNode): + id: ClassVar[str] + +class MappingNode(CollectionNode): + id: ClassVar[str] diff --git a/stubs/PyYAML/yaml/parser.pyi b/stubs/PyYAML/yaml/parser.pyi new file mode 100644 index 000000000000..b2c7b42db3ce --- /dev/null +++ b/stubs/PyYAML/yaml/parser.pyi @@ -0,0 +1,47 @@ +from typing import Any + +from yaml.error import MarkedYAMLError + +class ParserError(MarkedYAMLError): ... + +class Parser: + DEFAULT_TAGS: Any + current_event: Any + yaml_version: Any + tag_handles: Any + states: Any + marks: Any + state: Any + def __init__(self) -> None: ... + def dispose(self): ... + def check_event(self, *choices): ... + def peek_event(self): ... + def get_event(self): ... + def parse_stream_start(self): ... + def parse_implicit_document_start(self): ... + def parse_document_start(self): ... + def parse_document_end(self): ... + def parse_document_content(self): ... + def process_directives(self): ... + def parse_block_node(self): ... + def parse_flow_node(self): ... + def parse_block_node_or_indentless_sequence(self): ... + def parse_node(self, block=False, indentless_sequence=False): ... + def parse_block_sequence_first_entry(self): ... + def parse_block_sequence_entry(self): ... + def parse_indentless_sequence_entry(self): ... + def parse_block_mapping_first_key(self): ... + def parse_block_mapping_key(self): ... + def parse_block_mapping_value(self): ... + def parse_flow_sequence_first_entry(self): ... + def parse_flow_sequence_entry(self, first=False): ... + def parse_flow_sequence_entry_mapping_key(self): ... + def parse_flow_sequence_entry_mapping_value(self): ... + def parse_flow_sequence_entry_mapping_end(self): ... + def parse_flow_mapping_first_key(self): ... + def parse_flow_mapping_key(self, first=False): ... + def parse_flow_mapping_value(self): ... + def parse_flow_mapping_empty_value(self): ... + def process_empty_scalar(self, mark): ... + +__all__ = ["Parser", "ParserError"] diff --git a/stubs/PyYAML/yaml/reader.pyi b/stubs/PyYAML/yaml/reader.pyi new file mode 100644 index 000000000000..84a0e36e2bee --- /dev/null +++ b/stubs/PyYAML/yaml/reader.pyi @@ -0,0 +1,40 @@ +from _typeshed import SupportsRead +from typing import Any, TypeAlias + +from yaml.error import YAMLError + +_ReadStream: TypeAlias = str | bytes | SupportsRead[str] | SupportsRead[bytes] + +class ReaderError(YAMLError): + name: Any + character: Any + position: Any + encoding: Any + reason: Any + def __init__(self, name, position, character, encoding, reason) -> None: ... + +class Reader: + name: Any + stream: SupportsRead[str] | SupportsRead[bytes] | None + stream_pointer: Any + eof: Any + buffer: Any + pointer: Any + raw_buffer: Any + raw_decode: Any + encoding: Any + index: Any + line: Any + column: Any + def __init__(self, stream: _ReadStream) -> None: ... + def peek(self, index=0): ... + def prefix(self, length=1): ... + def forward(self, length=1): ... + def get_mark(self): ... + def determine_encoding(self): ... + NON_PRINTABLE: Any + def check_printable(self, data): ... + def update(self, length): ... + def update_raw(self, size=4096): ... + +__all__ = ["Reader", "ReaderError"] diff --git a/stubs/PyYAML/yaml/representer.pyi b/stubs/PyYAML/yaml/representer.pyi new file mode 100644 index 000000000000..ac10d892949b --- /dev/null +++ b/stubs/PyYAML/yaml/representer.pyi @@ -0,0 +1,63 @@ +import datetime +from _typeshed import Incomplete, ReadableBuffer, SupportsItems +from collections.abc import Callable, Iterable, Mapping +from types import BuiltinFunctionType, FunctionType, ModuleType +from typing import Any, ClassVar, TypeVar +from typing_extensions import Never, Self + +from yaml.error import YAMLError as YAMLError +from yaml.nodes import MappingNode as MappingNode, Node as Node, ScalarNode as ScalarNode, SequenceNode as SequenceNode + +_T = TypeVar("_T") + +class RepresenterError(YAMLError): ... + +class BaseRepresenter: + yaml_representers: ClassVar[dict[type[Any], Callable[[BaseRepresenter, Any], Node]]] + yaml_multi_representers: ClassVar[dict[type[Any], Callable[[BaseRepresenter, Any], Node]]] + default_style: str | Incomplete + sort_keys: bool + default_flow_style: bool + represented_objects: dict[int, Node] + object_keeper: list[Any] + alias_key: int | Incomplete + def __init__(self, default_style: str | None = None, default_flow_style: bool = False, sort_keys: bool = True) -> None: ... + def represent(self, data) -> None: ... + def represent_data(self, data) -> Node: ... + @classmethod + def add_representer(cls, data_type: type[_T], representer: Callable[[Self, _T], Node]) -> None: ... + @classmethod + def add_multi_representer(cls, data_type: type[_T], representer: Callable[[Self, _T], Node]) -> None: ... + def represent_scalar(self, tag: str, value, style: str | None = None) -> ScalarNode: ... + def represent_sequence(self, tag: str, sequence: Iterable[Any], flow_style: bool | None = None) -> SequenceNode: ... + def represent_mapping( + self, tag: str, mapping: SupportsItems[Any, Any] | Iterable[tuple[Any, Any]], flow_style: bool | None = None + ) -> MappingNode: ... + def ignore_aliases(self, data) -> bool: ... + +class SafeRepresenter(BaseRepresenter): + inf_value: ClassVar[float] + def ignore_aliases(self, data) -> bool: ... + def represent_none(self, data) -> ScalarNode: ... + def represent_str(self, data: str) -> ScalarNode: ... + def represent_binary(self, data: ReadableBuffer) -> ScalarNode: ... + def represent_bool(self, data: bool) -> ScalarNode: ... + def represent_int(self, data: int) -> ScalarNode: ... + def represent_float(self, data: float) -> ScalarNode: ... + def represent_list(self, data: Iterable[Any]) -> SequenceNode: ... + def represent_dict(self, data: SupportsItems[Any, Any] | Iterable[tuple[Any, Any]]) -> MappingNode: ... + def represent_set(self, data: Iterable[Any]) -> MappingNode: ... + def represent_date(self, data: datetime.date) -> ScalarNode: ... + def represent_datetime(self, data: datetime.datetime) -> ScalarNode: ... + def represent_yaml_object(self, tag: str, data, cls, flow_style: bool | None = None) -> MappingNode: ... + def represent_undefined(self, data) -> Never: ... + +class Representer(SafeRepresenter): + def represent_complex(self, data: complex) -> ScalarNode: ... + def represent_tuple(self, data: Iterable[Any]) -> SequenceNode: ... + def represent_name(self, data: BuiltinFunctionType | FunctionType) -> ScalarNode: ... + def represent_module(self, data: ModuleType) -> ScalarNode: ... + def represent_object(self, data) -> SequenceNode | MappingNode: ... + def represent_ordered_dict(self, data: Mapping[Any, Any]) -> SequenceNode: ... + +__all__ = ["BaseRepresenter", "SafeRepresenter", "Representer", "RepresenterError"] diff --git a/stubs/PyYAML/yaml/resolver.pyi b/stubs/PyYAML/yaml/resolver.pyi new file mode 100644 index 000000000000..614425ab4cbb --- /dev/null +++ b/stubs/PyYAML/yaml/resolver.pyi @@ -0,0 +1,27 @@ +from typing import Any + +from yaml.error import YAMLError + +class ResolverError(YAMLError): ... + +class BaseResolver: + DEFAULT_SCALAR_TAG: Any + DEFAULT_SEQUENCE_TAG: Any + DEFAULT_MAPPING_TAG: Any + yaml_implicit_resolvers: Any + yaml_path_resolvers: Any + resolver_exact_paths: Any + resolver_prefix_paths: Any + def __init__(self) -> None: ... + @classmethod + def add_implicit_resolver(cls, tag, regexp, first): ... + @classmethod + def add_path_resolver(cls, tag, path, kind=None): ... + def descend_resolver(self, current_node, current_index): ... + def ascend_resolver(self): ... + def check_resolver_prefix(self, depth, path, kind, current_node, current_index): ... + def resolve(self, kind, value, implicit): ... + +class Resolver(BaseResolver): ... + +__all__ = ["BaseResolver", "Resolver"] diff --git a/stubs/PyYAML/yaml/scanner.pyi b/stubs/PyYAML/yaml/scanner.pyi new file mode 100644 index 000000000000..0feaf8caa88b --- /dev/null +++ b/stubs/PyYAML/yaml/scanner.pyi @@ -0,0 +1,99 @@ +from typing import Any + +from yaml.error import MarkedYAMLError + +class ScannerError(MarkedYAMLError): ... + +class SimpleKey: + token_number: Any + required: Any + index: Any + line: Any + column: Any + mark: Any + def __init__(self, token_number, required, index, line, column, mark) -> None: ... + +class Scanner: + done: Any + flow_level: Any + tokens: Any + tokens_taken: Any + indent: Any + indents: Any + allow_simple_key: Any + possible_simple_keys: Any + def __init__(self) -> None: ... + def check_token(self, *choices): ... + def peek_token(self): ... + def get_token(self): ... + def need_more_tokens(self): ... + def fetch_more_tokens(self): ... + def next_possible_simple_key(self): ... + def stale_possible_simple_keys(self): ... + def save_possible_simple_key(self): ... + def remove_possible_simple_key(self): ... + def unwind_indent(self, column): ... + def add_indent(self, column): ... + def fetch_stream_start(self): ... + def fetch_stream_end(self): ... + def fetch_directive(self): ... + def fetch_document_start(self): ... + def fetch_document_end(self): ... + def fetch_document_indicator(self, TokenClass): ... + def fetch_flow_sequence_start(self): ... + def fetch_flow_mapping_start(self): ... + def fetch_flow_collection_start(self, TokenClass): ... + def fetch_flow_sequence_end(self): ... + def fetch_flow_mapping_end(self): ... + def fetch_flow_collection_end(self, TokenClass): ... + def fetch_flow_entry(self): ... + def fetch_block_entry(self): ... + def fetch_key(self): ... + def fetch_value(self): ... + def fetch_alias(self): ... + def fetch_anchor(self): ... + def fetch_tag(self): ... + def fetch_literal(self): ... + def fetch_folded(self): ... + def fetch_block_scalar(self, style): ... + def fetch_single(self): ... + def fetch_double(self): ... + def fetch_flow_scalar(self, style): ... + def fetch_plain(self): ... + def check_directive(self): ... + def check_document_start(self): ... + def check_document_end(self): ... + def check_block_entry(self): ... + def check_key(self): ... + def check_value(self): ... + def check_plain(self): ... + def scan_to_next_token(self): ... + def scan_directive(self): ... + def scan_directive_name(self, start_mark): ... + def scan_yaml_directive_value(self, start_mark): ... + def scan_yaml_directive_number(self, start_mark): ... + def scan_tag_directive_value(self, start_mark): ... + def scan_tag_directive_handle(self, start_mark): ... + def scan_tag_directive_prefix(self, start_mark): ... + def scan_directive_ignored_line(self, start_mark): ... + def scan_anchor(self, TokenClass): ... + def scan_tag(self): ... + def scan_block_scalar(self, style): ... + def scan_block_scalar_indicators(self, start_mark): ... + def scan_block_scalar_ignored_line(self, start_mark): ... + def scan_block_scalar_indentation(self): ... + def scan_block_scalar_breaks(self, indent): ... + def scan_flow_scalar(self, style): ... + ESCAPE_REPLACEMENTS: Any + ESCAPE_CODES: Any + def scan_flow_scalar_non_spaces(self, double, start_mark): ... + def scan_flow_scalar_spaces(self, double, start_mark): ... + def scan_flow_scalar_breaks(self, double, start_mark): ... + def scan_plain(self): ... + def scan_plain_spaces(self, indent, start_mark): ... + def scan_tag_handle(self, name, start_mark): ... + def scan_tag_uri(self, name, start_mark): ... + def scan_uri_escapes(self, name, start_mark): ... + def scan_line_break(self): ... + +__all__ = ["Scanner", "ScannerError"] diff --git a/stubs/PyYAML/yaml/serializer.pyi b/stubs/PyYAML/yaml/serializer.pyi new file mode 100644 index 000000000000..ae1e98f796cf --- /dev/null +++ b/stubs/PyYAML/yaml/serializer.pyi @@ -0,0 +1,27 @@ +from typing import Any + +from yaml.error import YAMLError +from yaml.nodes import Node + +class SerializerError(YAMLError): ... + +class Serializer: + ANCHOR_TEMPLATE: Any + use_encoding: Any + use_explicit_start: Any + use_explicit_end: Any + use_version: Any + use_tags: Any + serialized_nodes: Any + anchors: Any + last_anchor_id: Any + closed: Any + def __init__(self, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None) -> None: ... + def open(self) -> None: ... + def close(self) -> None: ... + def serialize(self, node: Node) -> None: ... + def anchor_node(self, node): ... + def generate_anchor(self, node): ... + def serialize_node(self, node, parent, index): ... + +__all__ = ["Serializer", "SerializerError"] diff --git a/stubs/PyYAML/yaml/tokens.pyi b/stubs/PyYAML/yaml/tokens.pyi new file mode 100644 index 000000000000..632a1644ad79 --- /dev/null +++ b/stubs/PyYAML/yaml/tokens.pyi @@ -0,0 +1,93 @@ +from typing import Any + +class Token: + start_mark: Any + end_mark: Any + def __init__(self, start_mark, end_mark) -> None: ... + +class DirectiveToken(Token): + id: Any + name: Any + value: Any + start_mark: Any + end_mark: Any + def __init__(self, name, value, start_mark, end_mark) -> None: ... + +class DocumentStartToken(Token): + id: Any + +class DocumentEndToken(Token): + id: Any + +class StreamStartToken(Token): + id: Any + start_mark: Any + end_mark: Any + encoding: Any + def __init__(self, start_mark=None, end_mark=None, encoding=None) -> None: ... + +class StreamEndToken(Token): + id: Any + +class BlockSequenceStartToken(Token): + id: Any + +class BlockMappingStartToken(Token): + id: Any + +class BlockEndToken(Token): + id: Any + +class FlowSequenceStartToken(Token): + id: Any + +class FlowMappingStartToken(Token): + id: Any + +class FlowSequenceEndToken(Token): + id: Any + +class FlowMappingEndToken(Token): + id: Any + +class KeyToken(Token): + id: Any + +class ValueToken(Token): + id: Any + +class BlockEntryToken(Token): + id: Any + +class FlowEntryToken(Token): + id: Any + +class AliasToken(Token): + id: Any + value: Any + start_mark: Any + end_mark: Any + def __init__(self, value, start_mark, end_mark) -> None: ... + +class AnchorToken(Token): + id: Any + value: Any + start_mark: Any + end_mark: Any + def __init__(self, value, start_mark, end_mark) -> None: ... + +class TagToken(Token): + id: Any + value: Any + start_mark: Any + end_mark: Any + def __init__(self, value, start_mark, end_mark) -> None: ... + +class ScalarToken(Token): + id: Any + value: Any + plain: Any + start_mark: Any + end_mark: Any + style: Any + def __init__(self, value, plain, start_mark, end_mark, style=None) -> None: ... diff --git a/stubs/Pygments/@tests/stubtest_allowlist.txt b/stubs/Pygments/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e4edf8e46e26 --- /dev/null +++ b/stubs/Pygments/@tests/stubtest_allowlist.txt @@ -0,0 +1,20 @@ +# Pygments uses mcs, pyright wants cls +pygments.lexer.LexerMeta.__new__ +pygments.style.StyleMeta.__new__ + +# Inheriting from tuple is weird +pygments.token._TokenType.__init__ + +# Cannot import in stubtest (SystemExit: 2) +pygments.__main__ + +# Class attributes that are set to None in the base class, but are +# always overridden with a non-None value in subclasses. +pygments.lexer.Lexer.name +pygments.lexer.Lexer.url +pygments.lexer.Lexer.version_added +pygments.formatter.Formatter.name + +# Individual lexers and styles submodules are not stubbed at this time. +pygments\.lexers\.(?!get_|find_|load_|guess_).* +pygments\.styles\.(?!get_).* diff --git a/stubs/Pygments/@tests/test_cases/check_pygments.py b/stubs/Pygments/@tests/test_cases/check_pygments.py new file mode 100644 index 000000000000..5c6fafc9b36c --- /dev/null +++ b/stubs/Pygments/@tests/test_cases/check_pygments.py @@ -0,0 +1,10 @@ +from typing_extensions import assert_type + +from pygments.style import Style, _StyleDict +from pygments.token import _TokenType + + +def test_style_class_iterable(style_class: type[Style]) -> None: + for t, d in style_class: + assert_type(t, _TokenType) + assert_type(d, _StyleDict) diff --git a/stubs/Pygments/METADATA.toml b/stubs/Pygments/METADATA.toml new file mode 100644 index 000000000000..1768af3414c0 --- /dev/null +++ b/stubs/Pygments/METADATA.toml @@ -0,0 +1,7 @@ +version = "2.20.*" +upstream-repository = "https://github.com/pygments/pygments" +optional-dependencies = ["types-docutils"] +partial-stub = true + +[tool.stubtest] +stubtest-dependencies = ["sphinx"] diff --git a/stubs/Pygments/pygments/__init__.pyi b/stubs/Pygments/pygments/__init__.pyi new file mode 100644 index 000000000000..d5fab4ab32db --- /dev/null +++ b/stubs/Pygments/pygments/__init__.pyi @@ -0,0 +1,25 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable, Iterator +from typing import Final, TypeVar, overload + +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__version__: Final[str] +__docformat__: Final = "restructuredtext" +__all__ = ["lex", "format", "highlight"] + +def lex(code: str, lexer: Lexer) -> Iterator[tuple[_TokenType, str]]: ... + +@overload +def format(tokens: Iterable[tuple[_TokenType, str]], formatter: Formatter[_T], outfile: SupportsWrite[_T]) -> None: ... +@overload +def format(tokens: Iterable[tuple[_TokenType, str]], formatter: Formatter[_T], outfile: None = None) -> _T: ... + +@overload +def highlight(code: str, lexer: Lexer, formatter: Formatter[_T], outfile: SupportsWrite[_T]) -> None: ... +@overload +def highlight(code: str, lexer: Lexer, formatter: Formatter[_T], outfile: None = None) -> _T: ... diff --git a/stubs/Pygments/pygments/cmdline.pyi b/stubs/Pygments/pygments/cmdline.pyi new file mode 100644 index 000000000000..a99805b67040 --- /dev/null +++ b/stubs/Pygments/pygments/cmdline.pyi @@ -0,0 +1,9 @@ +import argparse +from collections.abc import Sequence + +def main_inner(parser: argparse.ArgumentParser, argns: argparse.Namespace) -> int: ... + +class HelpFormatter(argparse.HelpFormatter): + def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 16, width: int | None = None) -> None: ... + +def main(args: Sequence[str] | None = ...) -> int: ... diff --git a/stubs/Pygments/pygments/console.pyi b/stubs/Pygments/pygments/console.pyi new file mode 100644 index 000000000000..d76f250ab6fe --- /dev/null +++ b/stubs/Pygments/pygments/console.pyi @@ -0,0 +1,10 @@ +from typing import Final + +esc: Final = "\x1b[" +codes: Final[dict[str, str]] +dark_colors: Final[list[str]] +light_colors: Final[list[str]] + +def reset_color() -> str: ... +def colorize(color_key: str, text: str) -> str: ... +def ansiformat(attr: str, text: str) -> str: ... diff --git a/stubs/Pygments/pygments/filter.pyi b/stubs/Pygments/pygments/filter.pyi new file mode 100644 index 000000000000..6f05bbdddeb0 --- /dev/null +++ b/stubs/Pygments/pygments/filter.pyi @@ -0,0 +1,29 @@ +from collections.abc import Iterable, Iterator +from typing import Any, ClassVar, Protocol, type_check_only + +from pygments.lexer import Lexer +from pygments.token import _TokenType + +@type_check_only +class _SimpleFilterFunction(Protocol): + # Function that can looked up as a method on a FunctionFilter subclass. + def __call__( + self, self_: FunctionFilter, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]], options: dict[str, Any], / + ) -> Iterator[tuple[_TokenType, str]]: ... + +def apply_filters( + stream: Iterable[tuple[_TokenType, str]], filters: Iterable[Filter], lexer: Lexer | None = None +) -> Iterator[tuple[_TokenType, str]]: ... +def simplefilter(f: _SimpleFilterFunction) -> type[FunctionFilter]: ... + +class Filter: + options: dict[str, Any] # Arbitrary values used by subclasses. + def __init__(self, **options: Any) -> None: ... # ditto. + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class FunctionFilter(Filter): + # Set to None in class, but overridden with a non-None value in the subclasses created by @simplefilter. + function: ClassVar[_SimpleFilterFunction] + # 'options' gets passed as a dict to 'function'; valid types depends on the wrapped function's signature. + def __init__(self, **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... diff --git a/stubs/Pygments/pygments/filters/__init__.pyi b/stubs/Pygments/pygments/filters/__init__.pyi new file mode 100644 index 000000000000..b43a8e9ef047 --- /dev/null +++ b/stubs/Pygments/pygments/filters/__init__.pyi @@ -0,0 +1,86 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Generator, Iterable, Iterator +from re import Pattern +from typing import Any, ClassVar, Final, Literal + +from pygments.filter import Filter +from pygments.lexer import Lexer +from pygments.token import _TokenType + +def find_filter_class(filtername: str) -> type[Filter] | None: ... + +# Keyword arguments are forwarded to the filter class. +def get_filter_by_name(filtername: str, **options: Any) -> Filter: ... +def get_all_filters() -> Generator[str]: ... + +class CodeTagFilter(Filter): + tag_re: Pattern[str] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__( + self, *, codetags: str | list[str] | tuple[str, ...] = ["XXX", "TODO", "FIXME", "BUG", "NOTE"], **options: Any + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class SymbolFilter(Filter): + latex_symbols: ClassVar[dict[str, str]] + isabelle_symbols: ClassVar[dict[str, str]] + lang_map: ClassVar[dict[Literal["isabelle", "latex"], dict[str, str]]] + symbols: dict[str, str] # One of latex_symbols or isabelle_symbols. + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, lang: Literal["isabelle", "latex"] = "isabelle", **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class KeywordCaseFilter(Filter): + convert: Callable[[str], str] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, case: Literal["lower", "upper", "capitalize"] = "lower", **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class NameHighlightFilter(Filter): + names: set[str] + tokentype: _TokenType + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__( + self, *, names: str | list[str] | tuple[str, ...] = [], tokentype: str | _TokenType | None = None, **options: Any + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class ErrorToken(Exception): ... + +class RaiseOnErrorTokenFilter(Filter): + exception: type[Exception] + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, excclass: type[Exception] = ..., **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class VisibleWhitespaceFilter(Filter): + spaces: str + tabs: str + newlines: str + wstt: bool + def __init__( + self, + *, + spaces: str | bool = False, + tabs: str | bool = False, + newlines: str | bool = False, + tabsize: ConvertibleToInt = 8, + wstokentype: bool | int | str = True, # Any value accepted by get_bool_opt. + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + **options: Any, + ) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class GobbleFilter(Filter): + n: int + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, *, n: ConvertibleToInt = 0, **options: Any) -> None: ... + def gobble(self, value: str, left: int) -> tuple[str, int]: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +class TokenMergeFilter(Filter): + # Arbitrary additional keyword arguments are permitted and are stored in self.options. + def __init__(self, **options: Any) -> None: ... + def filter(self, lexer: Lexer | None, stream: Iterable[tuple[_TokenType, str]]) -> Iterator[tuple[_TokenType, str]]: ... + +FILTERS: Final[dict[str, type[Filter]]] diff --git a/stubs/Pygments/pygments/formatter.pyi b/stubs/Pygments/pygments/formatter.pyi new file mode 100644 index 000000000000..94c4dcdb65f1 --- /dev/null +++ b/stubs/Pygments/pygments/formatter.pyi @@ -0,0 +1,60 @@ +import types +from _typeshed import SupportsWrite +from collections.abc import Iterable, Sequence +from typing import Any, ClassVar, Generic, TypeVar, overload + +from pygments.style import Style +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["Formatter"] + +class Formatter(Generic[_T]): + name: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + aliases: ClassVar[Sequence[str]] # Not intended to be mutable + filenames: ClassVar[Sequence[str]] # Not intended to be mutable + unicodeoutput: ClassVar[bool] + style: type[Style] + full: bool + title: str + encoding: str | None + options: dict[str, Any] # arbitrary values used by subclasses + + @overload + def __init__( + self: Formatter[str], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: None = None, + outencoding: None = None, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + @overload + def __init__( + self: Formatter[bytes], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: str, + outencoding: None = None, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + @overload + def __init__( + self: Formatter[bytes], + *, + style: type[Style] | str = "default", + full: bool = False, + title: str = "", + encoding: None = None, + outencoding: str, + **options: Any, # arbitrary values used by subclasses + ) -> None: ... + + def __class_getitem__(cls, name: Any) -> types.GenericAlias: ... + def get_style_defs(self, arg: str = "") -> str: ... + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/__init__.pyi b/stubs/Pygments/pygments/formatters/__init__.pyi new file mode 100644 index 000000000000..5fdd2e310cf3 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/__init__.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from ..formatter import Formatter +from .bbcode import BBCodeFormatter as BBCodeFormatter +from .groff import GroffFormatter as GroffFormatter +from .html import HtmlFormatter as HtmlFormatter +from .img import ( + BmpImageFormatter as BmpImageFormatter, + GifImageFormatter as GifImageFormatter, + ImageFormatter as ImageFormatter, + JpgImageFormatter as JpgImageFormatter, +) +from .irc import IRCFormatter as IRCFormatter +from .latex import LatexFormatter as LatexFormatter +from .other import NullFormatter as NullFormatter, RawTokenFormatter as RawTokenFormatter, TestcaseFormatter as TestcaseFormatter +from .pangomarkup import PangoMarkupFormatter as PangoMarkupFormatter +from .rtf import RtfFormatter as RtfFormatter +from .svg import SvgFormatter as SvgFormatter +from .terminal import TerminalFormatter as TerminalFormatter +from .terminal256 import Terminal256Formatter as Terminal256Formatter, TerminalTrueColorFormatter as TerminalTrueColorFormatter + +__all__ = [ + "get_formatter_by_name", + "get_formatter_for_filename", + "get_all_formatters", + "load_formatter_from_file", + "BBCodeFormatter", + "BmpImageFormatter", + "GifImageFormatter", + "GroffFormatter", + "HtmlFormatter", + "IRCFormatter", + "ImageFormatter", + "JpgImageFormatter", + "LatexFormatter", + "NullFormatter", + "PangoMarkupFormatter", + "RawTokenFormatter", + "RtfFormatter", + "SvgFormatter", + "Terminal256Formatter", + "TerminalFormatter", + "TerminalTrueColorFormatter", + "TestcaseFormatter", +] + +def get_all_formatters() -> Generator[type[Formatter[Incomplete]]]: ... +def get_formatter_by_name(_alias, **options): ... +def load_formatter_from_file(filename, formattername: str = "CustomFormatter", **options): ... +def get_formatter_for_filename(fn, **options): ... diff --git a/stubs/Pygments/pygments/formatters/_mapping.pyi b/stubs/Pygments/pygments/formatters/_mapping.pyi new file mode 100644 index 000000000000..4ca06c4415b0 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/_mapping.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +FORMATTERS: Incomplete diff --git a/stubs/Pygments/pygments/formatters/bbcode.pyi b/stubs/Pygments/pygments/formatters/bbcode.pyi new file mode 100644 index 000000000000..2e596b6ec396 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/bbcode.pyi @@ -0,0 +1,14 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["BBCodeFormatter"] + +class BBCodeFormatter(Formatter[_T]): + styles: dict[_TokenType, tuple[str, str]] + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/groff.pyi b/stubs/Pygments/pygments/formatters/groff.pyi new file mode 100644 index 000000000000..d6b936a2dff5 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/groff.pyi @@ -0,0 +1,18 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +__all__ = ["GroffFormatter"] + +_T = TypeVar("_T", str, bytes) + +class GroffFormatter(Formatter[_T]): + monospaced: bool + linenos: bool + wrap: int + styles: dict[_TokenType, tuple[str, str]] + def __init__(self, **options) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/html.pyi b/stubs/Pygments/pygments/formatters/html.pyi new file mode 100644 index 000000000000..1354b930341a --- /dev/null +++ b/stubs/Pygments/pygments/formatters/html.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["HtmlFormatter"] + +class HtmlFormatter(Formatter[_T]): + title: Incomplete + nowrap: Incomplete + noclasses: Incomplete + classprefix: Incomplete + cssclass: Incomplete + cssstyles: Incomplete + prestyles: Incomplete + cssfile: Incomplete + noclobber_cssfile: Incomplete + tagsfile: Incomplete + tagurlformat: Incomplete + filename: Incomplete + wrapcode: Incomplete + span_element_openers: Incomplete + linenos: int + linenostart: Incomplete + linenostep: Incomplete + linenospecial: Incomplete + nobackground: Incomplete + lineseparator: Incomplete + lineanchors: Incomplete + linespans: Incomplete + anchorlinenos: Incomplete + hl_lines: Incomplete + def get_style_defs(self, arg=None): ... + def get_token_style_defs(self, arg=None): ... + def get_background_style_defs(self, arg=None): ... + def get_linenos_style_defs(self): ... + def get_css_prefix(self, arg): ... + def wrap(self, source): ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/img.pyi b/stubs/Pygments/pygments/formatters/img.pyi new file mode 100644 index 000000000000..26c8c131d5c8 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/img.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing_extensions import Never + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +__all__ = ["ImageFormatter", "GifImageFormatter", "JpgImageFormatter", "BmpImageFormatter"] + +class PilNotAvailable(ImportError): ... +class FontNotFound(Exception): ... + +class FontManager: + font_name: Incomplete + font_size: Incomplete + fonts: Incomplete + encoding: Incomplete + variable: bool + def __init__(self, font_name, font_size: int = 14) -> None: ... + def get_char_size(self): ... + def get_text_size(self, text): ... + def get_font(self, bold, oblique): ... + def get_style(self, style): ... + +class ImageFormatter(Formatter[bytes]): + default_image_format: str + encoding: str + styles: Incomplete + background_color: str + image_format: Incomplete + image_pad: Incomplete + line_pad: Incomplete + fonts: Incomplete + line_number_fg: Incomplete + line_number_bg: Incomplete + line_number_chars: Incomplete + line_number_bold: Incomplete + line_number_italic: Incomplete + line_number_pad: Incomplete + line_numbers: Incomplete + line_number_separator: Incomplete + line_number_step: Incomplete + line_number_start: Incomplete + line_number_width: Incomplete + hl_lines: Incomplete + hl_color: Incomplete + drawables: Incomplete + def get_style_defs(self, arg: str = "") -> Never: ... + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[bytes]) -> None: ... + +class GifImageFormatter(ImageFormatter): + default_image_format: str + +class JpgImageFormatter(ImageFormatter): + default_image_format: str + +class BmpImageFormatter(ImageFormatter): + default_image_format: str diff --git a/stubs/Pygments/pygments/formatters/irc.pyi b/stubs/Pygments/pygments/formatters/irc.pyi new file mode 100644 index 000000000000..0d34575c9ae8 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/irc.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["IRCFormatter"] + +class IRCFormatter(Formatter[_T]): + darkbg: Incomplete + colorscheme: Incomplete + linenos: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/latex.pyi b/stubs/Pygments/pygments/formatters/latex.pyi new file mode 100644 index 000000000000..b1c4b7d3fe2e --- /dev/null +++ b/stubs/Pygments/pygments/formatters/latex.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["LatexFormatter"] + +class LatexFormatter(Formatter[_T]): + docclass: Incomplete + preamble: Incomplete + linenos: Incomplete + linenostart: Incomplete + linenostep: Incomplete + verboptions: Incomplete + nobackground: Incomplete + commandprefix: Incomplete + texcomments: Incomplete + mathescape: Incomplete + escapeinside: Incomplete + left: Incomplete + right: Incomplete + envname: Incomplete + def get_style_defs(self, arg: str = ""): ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... + +class LatexEmbeddedLexer(Lexer): + left: Incomplete + right: Incomplete + lang: Incomplete + def __init__(self, left, right, lang, **options) -> None: ... + def get_tokens_unprocessed(self, text): ... diff --git a/stubs/Pygments/pygments/formatters/other.pyi b/stubs/Pygments/pygments/formatters/other.pyi new file mode 100644 index 000000000000..c30244da9e39 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/other.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["NullFormatter", "RawTokenFormatter", "TestcaseFormatter"] + +class NullFormatter(Formatter[_T]): + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + +class RawTokenFormatter(Formatter[bytes]): + encoding: str + compress: Incomplete + error_color: Incomplete + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[bytes]) -> None: ... + +class TestcaseFormatter(Formatter[_T]): + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/pangomarkup.pyi b/stubs/Pygments/pygments/formatters/pangomarkup.pyi new file mode 100644 index 000000000000..331eab16ca9a --- /dev/null +++ b/stubs/Pygments/pygments/formatters/pangomarkup.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["PangoMarkupFormatter"] + +class PangoMarkupFormatter(Formatter[_T]): + styles: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/rtf.pyi b/stubs/Pygments/pygments/formatters/rtf.pyi new file mode 100644 index 000000000000..dc374aaf4bcb --- /dev/null +++ b/stubs/Pygments/pygments/formatters/rtf.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["RtfFormatter"] + +class RtfFormatter(Formatter[_T]): + fontface: Incomplete + fontsize: Incomplete + @staticmethod + def hex_to_rtf_color(hex_color: str) -> str: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/svg.pyi b/stubs/Pygments/pygments/formatters/svg.pyi new file mode 100644 index 000000000000..900deb19f58c --- /dev/null +++ b/stubs/Pygments/pygments/formatters/svg.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["SvgFormatter"] + +class SvgFormatter(Formatter[_T]): + nowrap: Incomplete + fontfamily: Incomplete + fontsize: Incomplete + xoffset: Incomplete + yoffset: Incomplete + ystep: Incomplete + spacehack: Incomplete + linenos: Incomplete + linenostart: Incomplete + linenostep: Incomplete + linenowidth: Incomplete + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/terminal.pyi b/stubs/Pygments/pygments/formatters/terminal.pyi new file mode 100644 index 000000000000..c7c82cbdf257 --- /dev/null +++ b/stubs/Pygments/pygments/formatters/terminal.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["TerminalFormatter"] + +class TerminalFormatter(Formatter[_T]): + darkbg: Incomplete + colorscheme: Incomplete + linenos: Incomplete + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... diff --git a/stubs/Pygments/pygments/formatters/terminal256.pyi b/stubs/Pygments/pygments/formatters/terminal256.pyi new file mode 100644 index 000000000000..092a121f95aa --- /dev/null +++ b/stubs/Pygments/pygments/formatters/terminal256.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete, SupportsWrite +from collections.abc import Iterable +from typing import TypeVar + +from pygments.formatter import Formatter +from pygments.token import _TokenType + +_T = TypeVar("_T", str, bytes) + +__all__ = ["Terminal256Formatter", "TerminalTrueColorFormatter"] + +class EscapeSequence: + fg: Incomplete + bg: Incomplete + bold: Incomplete + underline: Incomplete + italic: Incomplete + def __init__(self, fg=None, bg=None, bold: bool = False, underline: bool = False, italic: bool = False) -> None: ... + def escape(self, attrs): ... + def color_string(self): ... + def true_color_string(self): ... + def reset_string(self): ... + +class Terminal256Formatter(Formatter[_T]): + xterm_colors: Incomplete + best_match: Incomplete + style_string: Incomplete + usebold: Incomplete + useunderline: Incomplete + useitalic: Incomplete + linenos: Incomplete + + def format(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[_T]) -> None: ... + def format_unencoded(self, tokensource: Iterable[tuple[_TokenType, str]], outfile: SupportsWrite[str]) -> None: ... + +class TerminalTrueColorFormatter(Terminal256Formatter[_T]): ... diff --git a/stubs/Pygments/pygments/lexer.pyi b/stubs/Pygments/pygments/lexer.pyi new file mode 100644 index 000000000000..124ba720f15e --- /dev/null +++ b/stubs/Pygments/pygments/lexer.pyi @@ -0,0 +1,121 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator, Sequence +from re import Pattern, RegexFlag +from typing import ClassVar, Final + +from pygments.token import _TokenType +from pygments.util import Future + +__all__ = [ + "Lexer", + "RegexLexer", + "ExtendedRegexLexer", + "DelegatingLexer", + "LexerContext", + "include", + "inherit", + "bygroups", + "using", + "this", + "default", + "words", + "line_re", +] + +line_re: Final[Pattern[str]] + +class LexerMeta(type): + def __new__(cls, name, bases, d): ... + +class Lexer(metaclass=LexerMeta): + name: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + aliases: ClassVar[Sequence[str]] # not intended to be mutable + filenames: ClassVar[Sequence[str]] + alias_filenames: ClassVar[Sequence[str]] + mimetypes: ClassVar[Sequence[str]] + priority: ClassVar[float] + url: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + version_added: ClassVar[str] # Set to None, but always overridden with a non-None value in subclasses. + options: Incomplete + stripnl: Incomplete + stripall: Incomplete + ensurenl: Incomplete + tabsize: Incomplete + encoding: Incomplete + filters: Incomplete + def __init__(self, **options) -> None: ... + def add_filter(self, filter_, **options) -> None: ... + @staticmethod # @staticmethod added by special handling in metaclass + def analyse_text(text: str) -> float: ... + def get_tokens(self, text: str, unfiltered: bool = False) -> Iterator[tuple[_TokenType, str]]: ... + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... + +class DelegatingLexer(Lexer): + root_lexer: Incomplete + language_lexer: Incomplete + needle: Incomplete + def __init__(self, _root_lexer, _language_lexer, _needle=..., **options) -> None: ... + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... + +class include(str): ... +class _inherit: ... + +inherit: Incomplete + +class combined(tuple[Incomplete, ...]): + def __new__(cls, *args): ... + def __init__(self, *args) -> None: ... + +class _PseudoMatch: + def __init__(self, start, text) -> None: ... + def start(self, arg=None): ... + def end(self, arg=None): ... + def group(self, arg=None): ... + def groups(self): ... + def groupdict(self): ... + +def bygroups(*args): ... + +class _This: ... + +this: Incomplete + +def using(_other, **kwargs): ... + +class default: + state: Incomplete + def __init__(self, state) -> None: ... + +class words(Future): + words: Incomplete + prefix: Incomplete + suffix: Incomplete + def __init__(self, words, prefix: str = "", suffix: str = "") -> None: ... + def get(self): ... + +class RegexLexerMeta(LexerMeta): + def process_tokendef(cls, name, tokendefs=None): ... + def get_tokendefs(cls): ... + def __call__(cls, *args, **kwds): ... + +class RegexLexer(Lexer, metaclass=RegexLexerMeta): + flags: ClassVar[RegexFlag] + tokens: ClassVar[dict[str, list[Incomplete]]] + def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ("root",)) -> Iterator[tuple[int, _TokenType, str]]: ... + +class LexerContext: + text: Incomplete + pos: Incomplete + end: Incomplete + stack: Incomplete + def __init__(self, text, pos, stack=None, end=None) -> None: ... + +class ExtendedRegexLexer(RegexLexer): + def get_tokens_unprocessed( # type: ignore[override] + self, text: str | None = None, context: LexerContext | None = None + ) -> Iterator[tuple[int, _TokenType, str]]: ... + +class ProfilingRegexLexerMeta(RegexLexerMeta): ... + +class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta): + def get_tokens_unprocessed(self, text: str, stack: Iterable[str] = ("root",)) -> Iterator[tuple[int, _TokenType, str]]: ... diff --git a/stubs/Pygments/pygments/lexers/__init__.pyi b/stubs/Pygments/pygments/lexers/__init__.pyi new file mode 100644 index 000000000000..6309716d9ace --- /dev/null +++ b/stubs/Pygments/pygments/lexers/__init__.pyi @@ -0,0 +1,18 @@ +from _typeshed import FileDescriptorOrPath, StrPath +from collections.abc import Iterator + +from pygments.lexer import Lexer + +def get_all_lexers(plugins: bool = True) -> Iterator[tuple[str, tuple[str, ...], tuple[str, ...], tuple[str, ...]]]: ... +def find_lexer_class(name: str) -> type[Lexer] | None: ... +def find_lexer_class_by_name(_alias: str) -> type[Lexer]: ... +def get_lexer_by_name(_alias: str, **options) -> Lexer: ... +def load_lexer_from_file(filename: FileDescriptorOrPath, lexername: str = "CustomLexer", **options) -> Lexer: ... +def find_lexer_class_for_filename(_fn: StrPath, code: str | bytes | None = None) -> type[Lexer] | None: ... +def get_lexer_for_filename(_fn: StrPath, code: str | bytes | None = None, **options) -> Lexer: ... +def get_lexer_for_mimetype(_mime: str, **options) -> Lexer: ... +def guess_lexer_for_filename(_fn: StrPath, _text: str, **options) -> Lexer: ... +def guess_lexer(_text: str | bytes, **options) -> Lexer: ... + +# Having every lexer class here doesn't seem to be worth it +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/Pygments/pygments/lexers/javascript.pyi b/stubs/Pygments/pygments/lexers/javascript.pyi new file mode 100644 index 000000000000..958ca3422c0c --- /dev/null +++ b/stubs/Pygments/pygments/lexers/javascript.pyi @@ -0,0 +1,40 @@ +from collections.abc import Iterator +from typing import Final + +from ..lexer import Lexer, RegexLexer +from ..token import _TokenType + +__all__ = [ + "JavascriptLexer", + "KalLexer", + "LiveScriptLexer", + "DartLexer", + "TypeScriptLexer", + "LassoLexer", + "ObjectiveJLexer", + "CoffeeScriptLexer", + "MaskLexer", + "EarlGreyLexer", + "JuttleLexer", + "NodeConsoleLexer", +] + +JS_IDENT_START: Final[str] +JS_IDENT_PART: Final[str] +JS_IDENT: Final[str] + +class JavascriptLexer(RegexLexer): ... +class TypeScriptLexer(JavascriptLexer): ... +class KalLexer(RegexLexer): ... +class LiveScriptLexer(RegexLexer): ... +class DartLexer(RegexLexer): ... + +class LassoLexer(RegexLexer): + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class ObjectiveJLexer(RegexLexer): ... +class CoffeeScriptLexer(RegexLexer): ... +class MaskLexer(RegexLexer): ... +class EarlGreyLexer(RegexLexer): ... +class JuttleLexer(RegexLexer): ... +class NodeConsoleLexer(Lexer): ... diff --git a/stubs/Pygments/pygments/lexers/jsx.pyi b/stubs/Pygments/pygments/lexers/jsx.pyi new file mode 100644 index 000000000000..2017e214f6b0 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/jsx.pyi @@ -0,0 +1,5 @@ +from .javascript import JavascriptLexer + +__all__ = ["JsxLexer"] + +class JsxLexer(JavascriptLexer): ... diff --git a/stubs/Pygments/pygments/lexers/kusto.pyi b/stubs/Pygments/pygments/lexers/kusto.pyi new file mode 100644 index 000000000000..7130f990315f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/kusto.pyi @@ -0,0 +1,10 @@ +from typing import Final + +from ..lexer import RegexLexer + +__all__ = ["KustoLexer"] + +KUSTO_KEYWORDS: Final[list[str]] +KUSTO_PUNCTUATION: Final[list[str]] + +class KustoLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/lexers/ldap.pyi b/stubs/Pygments/pygments/lexers/ldap.pyi new file mode 100644 index 000000000000..da0f4bf8586f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/ldap.pyi @@ -0,0 +1,6 @@ +from ..lexer import RegexLexer + +__all__ = ["LdifLexer", "LdaprcLexer"] + +class LdifLexer(RegexLexer): ... +class LdaprcLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/lexers/lean.pyi b/stubs/Pygments/pygments/lexers/lean.pyi new file mode 100644 index 000000000000..54e15be68a32 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/lean.pyi @@ -0,0 +1,7 @@ +from ..lexer import RegexLexer + +__all__ = ["Lean3Lexer"] + +class Lean3Lexer(RegexLexer): ... + +LeanLexer = Lean3Lexer diff --git a/stubs/Pygments/pygments/lexers/lisp.pyi b/stubs/Pygments/pygments/lexers/lisp.pyi new file mode 100644 index 000000000000..9f1cb3a08f84 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/lisp.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar + +from ..lexer import RegexLexer +from ..token import _TokenType + +__all__ = [ + "SchemeLexer", + "CommonLispLexer", + "HyLexer", + "RacketLexer", + "NewLispLexer", + "EmacsLispLexer", + "ShenLexer", + "CPSALexer", + "XtlangLexer", + "FennelLexer", +] + +class SchemeLexer(RegexLexer): + valid_name: ClassVar[str] + token_end: ClassVar[str] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + number_rules: ClassVar[dict[Incomplete, Incomplete]] + def decimal_cb(self, match) -> Iterator[tuple[Incomplete, Incomplete, Incomplete]]: ... + +class CommonLispLexer(RegexLexer): + nonmacro: ClassVar[str] + constituent: ClassVar[str] + terminated: ClassVar[str] + symbol: ClassVar[str] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class HyLexer(RegexLexer): + special_forms: ClassVar[tuple[str, ...]] + declarations: ClassVar[tuple[str, ...]] + hy_builtins: ClassVar[tuple[str, ...]] + hy_core: ClassVar[tuple[str, ...]] + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] + +class RacketLexer(RegexLexer): ... + +class NewLispLexer(RegexLexer): + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] + +class EmacsLispLexer(RegexLexer): + nonmacro: ClassVar[str] + constituent: ClassVar[str] + terminated: ClassVar[str] + symbol: ClassVar[str] + macros: ClassVar[set[str]] + special_forms: ClassVar[set[str]] + builtin_function: ClassVar[set[str]] + builtin_function_highlighted: ClassVar[set[str]] + lambda_list_keywords: ClassVar[set[str]] + error_keywords: ClassVar[set[str]] + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class ShenLexer(RegexLexer): + DECLARATIONS: ClassVar[tuple[str, ...]] + SPECIAL_FORMS: ClassVar[tuple[str, ...]] + BUILTINS: ClassVar[tuple[str, ...]] + BUILTINS_ANYWHERE: ClassVar[tuple[str, ...]] + MAPPINGS: ClassVar[dict[str, Incomplete]] + + valid_symbol_chars: ClassVar[str] + valid_name: ClassVar[str] + symbol_name: ClassVar[str] + variable: ClassVar[str] + + def get_tokens_unprocessed(self, text: str) -> Iterator[tuple[int, _TokenType, str]]: ... # type: ignore[override] + +class CPSALexer(RegexLexer): + valid_name: ClassVar[str] + +class XtlangLexer(RegexLexer): + common_keywords: ClassVar[tuple[str, ...]] + scheme_keywords: ClassVar[tuple[str, ...]] + xtlang_bind_keywords: ClassVar[tuple[str, ...]] + xtlang_keywords: ClassVar[tuple[str, ...]] + common_functions: ClassVar[tuple[str, ...]] + scheme_functions: ClassVar[tuple[str, ...]] + xtlang_functions: ClassVar[tuple[str, ...]] + + valid_scheme_name: ClassVar[str] + valid_xtlang_name: ClassVar[str] + valid_xtlang_type: ClassVar[str] + +class FennelLexer(RegexLexer): + special_forms: ClassVar[tuple[str, ...]] + declarations: ClassVar[tuple[str, ...]] + builtins: ClassVar[tuple[str, ...]] + valid_name: ClassVar[str] diff --git a/stubs/Pygments/pygments/lexers/prql.pyi b/stubs/Pygments/pygments/lexers/prql.pyi new file mode 100644 index 000000000000..682ff082c93f --- /dev/null +++ b/stubs/Pygments/pygments/lexers/prql.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..lexer import RegexLexer + +__all__ = ["PrqlLexer"] + +class PrqlLexer(RegexLexer): + builtinTypes: ClassVar[Incomplete] + def innerstring_rules(ttype) -> list[tuple[str, Incomplete]]: ... + def fstring_rules(ttype) -> list[tuple[str, Incomplete]]: ... diff --git a/stubs/Pygments/pygments/lexers/vip.pyi b/stubs/Pygments/pygments/lexers/vip.pyi new file mode 100644 index 000000000000..876a05d8bb86 --- /dev/null +++ b/stubs/Pygments/pygments/lexers/vip.pyi @@ -0,0 +1,19 @@ +from typing import ClassVar + +from ..lexer import RegexLexer + +__all__ = ["VisualPrologLexer", "VisualPrologGrammarLexer"] + +class VisualPrologBaseLexer(RegexLexer): + minorendkw: ClassVar[tuple[str, ...]] + minorkwexp: ClassVar[tuple[str, ...]] + dockw: ClassVar[tuple[str, ...]] + +class VisualPrologLexer(VisualPrologBaseLexer): + majorkw: ClassVar[tuple[str, ...]] + minorkw: ClassVar[tuple[str, ...]] + directivekw: ClassVar[tuple[str, ...]] + +class VisualPrologGrammarLexer(VisualPrologBaseLexer): + majorkw: ClassVar[tuple[str, ...]] + directivekw: ClassVar[tuple[str, ...]] diff --git a/stubs/Pygments/pygments/lexers/vyper.pyi b/stubs/Pygments/pygments/lexers/vyper.pyi new file mode 100644 index 000000000000..27a759b0404b --- /dev/null +++ b/stubs/Pygments/pygments/lexers/vyper.pyi @@ -0,0 +1,5 @@ +from ..lexer import RegexLexer + +__all__ = ["VyperLexer"] + +class VyperLexer(RegexLexer): ... diff --git a/stubs/Pygments/pygments/modeline.pyi b/stubs/Pygments/pygments/modeline.pyi new file mode 100644 index 000000000000..bf51d03f825a --- /dev/null +++ b/stubs/Pygments/pygments/modeline.pyi @@ -0,0 +1,3 @@ +__all__ = ["get_filetype_from_buffer"] + +def get_filetype_from_buffer(buf: str, max_lines: int = 5) -> str | None: ... diff --git a/stubs/Pygments/pygments/plugin.pyi b/stubs/Pygments/pygments/plugin.pyi new file mode 100644 index 000000000000..49b49c9d7641 --- /dev/null +++ b/stubs/Pygments/pygments/plugin.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from importlib.metadata import EntryPoints +from typing import Final + +from pygments.filter import Filter +from pygments.formatter import Formatter +from pygments.lexer import Lexer +from pygments.style import Style + +LEXER_ENTRY_POINT: Final = "pygments.lexers" +FORMATTER_ENTRY_POINT: Final = "pygments.formatters" +STYLE_ENTRY_POINT: Final = "pygments.styles" +FILTER_ENTRY_POINT: Final = "pygments.filters" + +def iter_entry_points(group_name: str) -> EntryPoints: ... +def find_plugin_lexers() -> Generator[type[Lexer]]: ... +def find_plugin_formatters() -> Generator[tuple[str, type[Formatter[Incomplete]]]]: ... +def find_plugin_styles() -> Generator[tuple[str, type[Style]]]: ... +def find_plugin_filters() -> Generator[tuple[str, type[Filter]]]: ... diff --git a/stubs/Pygments/pygments/regexopt.pyi b/stubs/Pygments/pygments/regexopt.pyi new file mode 100644 index 000000000000..2429349f90fb --- /dev/null +++ b/stubs/Pygments/pygments/regexopt.pyi @@ -0,0 +1,12 @@ +import re +from collections.abc import Iterable, Sequence +from operator import itemgetter +from typing import Final + +CS_ESCAPE: Final[re.Pattern[str]] +FIRST_ELEMENT: Final[itemgetter[int]] + +def commonprefix(m: Iterable[str]) -> str: ... +def make_charset(letters: Iterable[str]) -> str: ... +def regex_opt_inner(strings: Sequence[str], open_paren: str) -> str: ... +def regex_opt(strings: Iterable[str], prefix: str = "", suffix: str = "") -> str: ... diff --git a/stubs/Pygments/pygments/scanner.pyi b/stubs/Pygments/pygments/scanner.pyi new file mode 100644 index 000000000000..1d4557425b9f --- /dev/null +++ b/stubs/Pygments/pygments/scanner.pyi @@ -0,0 +1,19 @@ +from re import Match, Pattern, RegexFlag + +class EndOfText(RuntimeError): ... + +class Scanner: + data: str + data_length: int + start_pos: int + pos: int + flags: int | RegexFlag + last: str | None + match: str | None + def __init__(self, text: str, flags: int | RegexFlag = 0) -> None: ... + @property + def eos(self) -> bool: ... + def check(self, pattern: str | Pattern[str]) -> Match[str] | None: ... + def test(self, pattern: str | Pattern[str]) -> bool: ... + def scan(self, pattern: str | Pattern[str]) -> bool: ... + def get_char(self) -> None: ... diff --git a/stubs/Pygments/pygments/sphinxext.pyi b/stubs/Pygments/pygments/sphinxext.pyi new file mode 100644 index 000000000000..f0caf6e2fa52 --- /dev/null +++ b/stubs/Pygments/pygments/sphinxext.pyi @@ -0,0 +1,17 @@ +from typing import Any, Final + +from docutils.parsers.rst import Directive + +MODULEDOC: Final[str] +LEXERDOC: Final[str] +FMTERDOC: Final[str] +FILTERDOC: Final[str] + +class PygmentsDoc(Directive): + filenames: set[str] + def document_lexers_overview(self) -> str: ... + def document_lexers(self) -> str: ... + def document_formatters(self) -> str: ... + def document_filters(self) -> str: ... + +def setup(app: Any) -> None: ... # Actual type of 'app' is sphinx.application.Sphinx diff --git a/stubs/Pygments/pygments/style.pyi b/stubs/Pygments/pygments/style.pyi new file mode 100644 index 000000000000..6ebe3683dcfc --- /dev/null +++ b/stubs/Pygments/pygments/style.pyi @@ -0,0 +1,41 @@ +from _typeshed import Self +from collections.abc import Iterator, Mapping, Sequence, Set as AbstractSet +from typing import Any, ClassVar, TypedDict, type_check_only + +from pygments.token import _TokenType + +ansicolors: AbstractSet[str] # not intended to be mutable + +@type_check_only +class _StyleDict(TypedDict): + color: str | None + bold: bool + italic: bool + underline: bool + bgcolor: str | None + border: str | None + roman: bool | None # lol yes, can be True or False or None + sans: bool | None + mono: bool | None + ansicolor: str | None + bgansicolor: str | None + +class StyleMeta(type): + def __new__(cls: type[Self], name: str, bases: tuple[type[Any], ...], dct: dict[str, Any]) -> Self: ... + def style_for_token(cls, token: _TokenType) -> _StyleDict: ... + def styles_token(cls, ttype: _TokenType) -> bool: ... + def list_styles(cls) -> list[tuple[_TokenType, _StyleDict]]: ... + def __iter__(cls) -> Iterator[tuple[_TokenType, _StyleDict]]: ... + def __len__(cls) -> int: ... + +class Style(metaclass=StyleMeta): + background_color: ClassVar[str] + highlight_color: ClassVar[str] + line_number_color: ClassVar[str] + line_number_background_color: ClassVar[str] + line_number_special_color: ClassVar[str] + line_number_special_background_color: ClassVar[str] + styles: ClassVar[Mapping[_TokenType, str]] # not intended to be mutable + name: ClassVar[str] + aliases: ClassVar[Sequence[str]] # not intended to be mutable + web_style_gallery_exclude: ClassVar[bool] diff --git a/stubs/Pygments/pygments/styles/__init__.pyi b/stubs/Pygments/pygments/styles/__init__.pyi new file mode 100644 index 000000000000..6aeb9cf90f95 --- /dev/null +++ b/stubs/Pygments/pygments/styles/__init__.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterator, Mapping + +from pygments.style import Style +from pygments.util import ClassNotFound as ClassNotFound + +STYLE_MAP: Mapping[str, str] + +def get_style_by_name(name) -> type[Style]: ... +def get_all_styles() -> Iterator[str]: ... + +# Having every style class here doesn't seem to be worth it +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/Pygments/pygments/token.pyi b/stubs/Pygments/pygments/token.pyi new file mode 100644 index 000000000000..141ff50a1deb --- /dev/null +++ b/stubs/Pygments/pygments/token.pyi @@ -0,0 +1,34 @@ +from collections.abc import Mapping +from typing import Any, Final +from typing_extensions import Self + +class _TokenType(tuple[str, ...]): + parent: _TokenType | None + def split(self) -> list[_TokenType]: ... + subtypes: set[_TokenType] + def __contains__(self, val: _TokenType) -> bool: ... # type: ignore[override] + def __getattr__(self, name: str) -> _TokenType: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... + +Token: _TokenType +Text: _TokenType +Whitespace: _TokenType +Escape: _TokenType +Error: _TokenType +Other: _TokenType +Keyword: _TokenType +Name: _TokenType +Literal: _TokenType +String: _TokenType +Number: _TokenType +Punctuation: _TokenType +Operator: _TokenType +Comment: _TokenType +Generic: _TokenType + +def is_token_subtype(ttype: _TokenType, other: _TokenType) -> bool: ... +def string_to_tokentype(s: str | _TokenType) -> _TokenType: ... + +# dict, but shouldn't be mutated +STANDARD_TYPES: Final[Mapping[_TokenType, str]] diff --git a/stubs/Pygments/pygments/unistring.pyi b/stubs/Pygments/pygments/unistring.pyi new file mode 100644 index 000000000000..895f786c730d --- /dev/null +++ b/stubs/Pygments/pygments/unistring.pyi @@ -0,0 +1,71 @@ +from typing import Final, Literal, TypeAlias + +_Cats: TypeAlias = Literal[ + "Cc", + "Cf", + "Cn", + "Co", + "Cs", + "Ll", + "Lm", + "Lo", + "Lt", + "Lu", + "Mc", + "Me", + "Mn", + "Nd", + "Nl", + "No", + "Pc", + "Pd", + "Pe", + "Pf", + "Pi", + "Po", + "Ps", + "Sc", + "Sk", + "Sm", + "So", + "Zl", + "Zp", + "Zs", +] + +Cc: Final[str] +Cf: Final[str] +Cn: Final[str] +Co: Final[str] +Cs: Final[str] +Ll: Final[str] +Lm: Final[str] +Lo: Final[str] +Lt: Final[str] +Lu: Final[str] +Mc: Final[str] +Me: Final[str] +Mn: Final[str] +Nd: Final[str] +Nl: Final[str] +No: Final[str] +Pc: Final[str] +Pd: Final[str] +Pe: Final[str] +Pf: Final[str] +Pi: Final[str] +Po: Final[str] +Ps: Final[str] +Sc: Final[str] +Sk: Final[str] +Sm: Final[str] +So: Final[str] +Zl: Final[str] +Zp: Final[str] +Zs: Final[str] +xid_continue: Final[str] +xid_start: Final[str] +cats: Final[list[_Cats]] + +def combine(*args: _Cats) -> str: ... +def allexcept(*args: _Cats) -> str: ... diff --git a/stubs/Pygments/pygments/util.pyi b/stubs/Pygments/pygments/util.pyi new file mode 100644 index 000000000000..e2b63b730dd7 --- /dev/null +++ b/stubs/Pygments/pygments/util.pyi @@ -0,0 +1,53 @@ +from collections.abc import Callable, Container, Hashable, Iterable +from io import TextIOWrapper +from re import Pattern +from typing import Any, Final, Protocol, TypeVar, type_check_only + +_T = TypeVar("_T") +_H = TypeVar("_H", bound=Hashable) + +split_path_re: Final[Pattern[str]] +doctype_lookup_re: Final[Pattern[str]] +tag_re: Final[Pattern[str]] +xml_decl_re: Final[Pattern[str]] + +class ClassNotFound(ValueError): ... +class OptionError(Exception): ... + +@type_check_only +class _SupportsGetStrWithDefault(Protocol): + def get(self, item: str, default: Any, /) -> Any: ... + +# 'options' contains the **kwargs of an arbitrary function. +def get_choice_opt( + options: _SupportsGetStrWithDefault, optname: str, allowed: Container[_T], default: _T | None = None, normcase: bool = False +) -> _T: ... +def get_bool_opt(options: _SupportsGetStrWithDefault, optname: str, default: bool | None = None) -> bool: ... +def get_int_opt(options: _SupportsGetStrWithDefault, optname: str, default: int | None = None) -> int: ... + +# Return type and type of 'default' depend on the signature of the function whose **kwargs +# are being processed. +def get_list_opt( + options: _SupportsGetStrWithDefault, optname: str, default: list[Any] | tuple[Any, ...] | None = None +) -> list[Any]: ... +def docstring_headline(obj: object) -> str: ... +def make_analysator(f: Callable[[str], float]) -> Callable[[str], float]: ... +def shebang_matches(text: str, regex: str) -> bool: ... +def doctype_matches(text: str, regex: str) -> bool: ... +def html_doctype_matches(text: str) -> bool: ... +def looks_like_xml(text: str) -> bool: ... +def surrogatepair(c: int) -> int: ... +def format_lines(var_name: str, seq: Iterable[str], raw: bool = False, indent_level: int = 0) -> str: ... +def duplicates_removed(it: Iterable[_H], already_seen: Container[_H] = ()) -> list[_H]: ... + +class Future: + def get(self) -> None: ... + +def guess_decode(text: bytes) -> tuple[str, str]: ... + +# If 'term' has an 'encoding' attribute, it should be a str. Otherwise any object is accepted. +def guess_decode_from_terminal(text: bytes, term: Any) -> tuple[str, str]: ... +def terminal_encoding(term: Any) -> str: ... + +class UnclosingTextIOWrapper(TextIOWrapper): + def close(self) -> None: ... diff --git a/stubs/RPi.GPIO/METADATA.toml b/stubs/RPi.GPIO/METADATA.toml new file mode 100644 index 000000000000..503497d94a9f --- /dev/null +++ b/stubs/RPi.GPIO/METADATA.toml @@ -0,0 +1,10 @@ +version = "0.7.*" +upstream-repository = "https://sourceforge.net/p/raspberry-gpio-python/code/" + +[tool.stubtest] +# This package is only supported on Raspberry Pi hardware, which identifies +# itself as 'linux'. When run on other hardware, it raises a RuntimeError: +# RPi.GPIO failed to import. RuntimeError: This module can only be run on a Raspberry Pi! +# https://sourceforge.net/p/raspberry-gpio-python/code/ci/08048dd1894a6b09a104557b6eaa6bb68b6baac5/tree/source/py_gpio.c#l1008 +supported-platforms = [] +ci-platforms = [] diff --git a/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi b/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi new file mode 100644 index 000000000000..75b3139f45ae --- /dev/null +++ b/stubs/RPi.GPIO/RPi/GPIO/__init__.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable +from typing import Final, Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _RPi_Info(TypedDict): + P1_REVISION: int + REVISION: str + TYPE: str + MANUFACTURER: str + PROCESSOR: str + RAM: str + +VERSION: str +RPI_INFO: _RPi_Info +RPI_REVISION: int + +HIGH: Literal[1] +LOW: Literal[0] + +OUT: Final = 0 +IN: Final = 1 +HARD_PWM: Final = 43 +SERIAL: Final = 40 +I2C: Final = 42 +SPI: Final = 41 +UNKNOWN: Final = -1 + +BOARD: Final = 10 +BCM: Final = 11 + +PUD_OFF: Final = 20 +PUD_UP: Final = 22 +PUD_DOWN: Final = 21 + +RISING: Final = 31 +FALLING: Final = 32 +BOTH: Final = 33 + +_EventCallback: TypeAlias = Callable[[int], object] + +def setup( + channel: int | list[int] | tuple[int, ...], direction: Literal[0, 1], pull_up_down: int = 20, initial: int = -1 +) -> None: ... +def cleanup(channel: int | list[int] | tuple[int, ...] = -666) -> None: ... +def output( + channel: int | list[int] | tuple[int, ...], + value: Literal[0, 1] | bool | list[Literal[0, 1] | bool] | tuple[Literal[0, 1] | bool, ...], + /, +) -> None: ... +def input(channel: int, /) -> bool: ... +def setmode(mode: Literal[10, 11], /) -> None: ... +def getmode() -> Literal[10, 11] | None: ... +def add_event_detect(channel: int, edge: int, callback: _EventCallback | None = None, bouncetime: int = -666) -> None: ... +def remove_event_detect(channel: int, /) -> None: ... +def event_detected(channel: int, /) -> bool: ... +def add_event_callback(channel: int, callback: _EventCallback) -> None: ... +def wait_for_edge(channel: int, edge: int, bouncetime: int = -666, timeout: int = -1) -> int | None: ... +def gpio_function(channel: int, /) -> int: ... +def setwarnings(gpio_warnings: bool, /) -> None: ... + +class PWM: + def __init__(self, channel: int, frequency: float, /) -> None: ... + def start(self, dutycycle: float, /) -> None: ... + def ChangeDutyCycle(self, dutycycle: float, /) -> None: ... + def ChangeFrequency(self, frequency: float, /) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/RPi.GPIO/RPi/__init__.pyi b/stubs/RPi.GPIO/RPi/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/Send2Trash/@tests/stubtest_allowlist.txt b/stubs/Send2Trash/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0463983f46ff --- /dev/null +++ b/stubs/Send2Trash/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Modules that are not meant to be imported by users +send2trash.mac diff --git a/stubs/Send2Trash/METADATA.toml b/stubs/Send2Trash/METADATA.toml new file mode 100644 index 000000000000..53406caa9583 --- /dev/null +++ b/stubs/Send2Trash/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.1.*" +upstream-repository = "https://github.com/arsenetar/send2trash" diff --git a/stubs/Send2Trash/send2trash/__init__.pyi b/stubs/Send2Trash/send2trash/__init__.pyi new file mode 100644 index 000000000000..8c2e74a7a055 --- /dev/null +++ b/stubs/Send2Trash/send2trash/__init__.pyi @@ -0,0 +1,7 @@ +from _typeshed import StrOrBytesPath +from typing import Any + +from .exceptions import TrashPermissionError as TrashPermissionError + +# The list should be list[StrOrBytesPath] but that doesn't work because invariance +def send2trash(paths: list[Any] | StrOrBytesPath) -> None: ... diff --git a/stubs/Send2Trash/send2trash/__main__.pyi b/stubs/Send2Trash/send2trash/__main__.pyi new file mode 100644 index 000000000000..b75b3a4b3f25 --- /dev/null +++ b/stubs/Send2Trash/send2trash/__main__.pyi @@ -0,0 +1,3 @@ +from collections.abc import Iterable + +def main(args: Iterable[str] | None = None) -> None: ... diff --git a/stubs/Send2Trash/send2trash/exceptions.pyi b/stubs/Send2Trash/send2trash/exceptions.pyi new file mode 100644 index 000000000000..a263f6551942 --- /dev/null +++ b/stubs/Send2Trash/send2trash/exceptions.pyi @@ -0,0 +1,5 @@ +from typing import Any + +class TrashPermissionError(PermissionError): + # Typed the same as `filename` in `PermissionError`: + def __init__(self, filename: Any) -> None: ... diff --git a/stubs/Send2Trash/send2trash/util.pyi b/stubs/Send2Trash/send2trash/util.pyi new file mode 100644 index 000000000000..c89143c4f0f6 --- /dev/null +++ b/stubs/Send2Trash/send2trash/util.pyi @@ -0,0 +1,5 @@ +from _typeshed import StrOrBytesPath +from typing import Any + +# Should be consistent with `__init__.py` +def preprocess_paths(paths: list[Any] | StrOrBytesPath) -> list[str | bytes]: ... diff --git a/stubs/TgCrypto/@tests/stubtest_allowlist.txt b/stubs/TgCrypto/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..38f87688d4a0 --- /dev/null +++ b/stubs/TgCrypto/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# stubtest doesn't recognize these function as taking only positional-only arguments. +tgcrypto.cbc256_decrypt +tgcrypto.cbc256_encrypt +tgcrypto.ctr256_decrypt +tgcrypto.ctr256_encrypt +tgcrypto.ige256_decrypt +tgcrypto.ige256_encrypt diff --git a/stubs/TgCrypto/METADATA.toml b/stubs/TgCrypto/METADATA.toml new file mode 100644 index 000000000000..d859dd089bf5 --- /dev/null +++ b/stubs/TgCrypto/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.2.*" +upstream-repository = "https://github.com/pyrogram/tgcrypto" diff --git a/stubs/TgCrypto/tgcrypto/__init__.pyi b/stubs/TgCrypto/tgcrypto/__init__.pyi new file mode 100644 index 000000000000..ffee3190d325 --- /dev/null +++ b/stubs/TgCrypto/tgcrypto/__init__.pyi @@ -0,0 +1,8 @@ +from typing_extensions import Buffer + +def ige256_encrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def ige256_decrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def ctr256_encrypt(data: Buffer, key: Buffer, iv: Buffer, state: Buffer, /) -> bytes: ... +def ctr256_decrypt(data: Buffer, key: Buffer, iv: Buffer, state: Buffer, /) -> bytes: ... +def cbc256_encrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... +def cbc256_decrypt(data: Buffer, key: Buffer, iv: Buffer, /) -> bytes: ... diff --git a/stubs/WTForms/@tests/stubtest_allowlist.txt b/stubs/WTForms/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3d8e733ca9c7 --- /dev/null +++ b/stubs/WTForms/@tests/stubtest_allowlist.txt @@ -0,0 +1,12 @@ +# Error: is not present at runtime +# ============================= +# This is hack to get around Field.__new__ not being able to return +# UnboundField +wtforms.fields.core.Field.__get__ +# Since DefaultMeta can contain arbitrary values we added __getattr__ +# to let mypy know that arbitrary attribute access is possible +wtforms.meta.DefaultMeta.__getattr__ + +# Should allow setting and deleting any attribute +wtforms.fields.core.Flags.__delattr__ +wtforms.fields.core.Flags.__setattr__ diff --git a/stubs/WTForms/@tests/test_cases/check_choices.py b/stubs/WTForms/@tests/test_cases/check_choices.py new file mode 100644 index 000000000000..41204023ad25 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_choices.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from wtforms import SelectField + +# any way we can specify the choices inline with a literal should work + +# tuple of tuples +SelectField(choices=(("", ""),)) +SelectField(choices=((1, "1"),)) +SelectField(choices=(("", "", {}),)) +SelectField(choices=((True, "t", {}),)) +SelectField(choices=((True, "t"), (False, "f", {}))) + +# list of tuples +SelectField(choices=[("", "")]) +SelectField(choices=[(1, "1")]) +SelectField(choices=[("", "", {})]) +SelectField(choices=[(True, "t", {})]) +SelectField(choices=[(True, "t"), (False, "f", {})]) + +# dict of tuple of tuples +SelectField(choices={"a": (("", ""),)}) +SelectField(choices={"a": ((1, "1"),)}) +SelectField(choices={"a": (("", "", {}),)}) +SelectField(choices={"a": ((True, "t", {}),)}) +SelectField(choices={"a": ((True, "t"), (False, "f", {}))}) +SelectField(choices={"a": ((True, "", {}),), "b": ((False, "f"),)}) + +# dict of list of tuples +SelectField(choices={"a": [("", "")]}) +SelectField(choices={"a": [(1, "1")]}) +SelectField(choices={"a": [("", "", {})]}) +SelectField(choices={"a": [(True, "t", {})]}) +SelectField(choices={"a": [(True, "t"), (False, "f", {})]}) +SelectField(choices={"a": [(True, "", {})], "b": [(False, "f")]}) + +# the same should be true for lambdas + +# tuple of tuples +SelectField(choices=lambda: (("", ""),)) +SelectField(choices=lambda: ((1, "1"),)) +SelectField(choices=lambda: (("", "", {}),)) +SelectField(choices=lambda: ((True, "t", {}),)) +SelectField(choices=lambda: ((True, "t"), (False, "f", {}))) + +# list of tuples +SelectField(choices=lambda: [("", "")]) +SelectField(choices=lambda: [(1, "1")]) +SelectField(choices=lambda: [("", "", {})]) +SelectField(choices=lambda: [(True, "t", {})]) +SelectField(choices=lambda: [(True, "t"), (False, "f", {})]) + +# dict of tuple of tuples +SelectField(choices=lambda: {"a": (("", ""),)}) +SelectField(choices=lambda: {"a": ((1, "1"),)}) +SelectField(choices=lambda: {"a": (("", "", {}),)}) +SelectField(choices=lambda: {"a": ((True, "t", {}),)}) +SelectField(choices=lambda: {"a": ((True, "t"), (False, "f", {}))}) +SelectField(choices=lambda: {"a": ((True, "", {}),), "b": ((False, "f"),)}) + +# dict of list of tuples +SelectField(choices=lambda: {"a": [("", "")]}) +SelectField(choices=lambda: {"a": [(1, "1")]}) +SelectField(choices=lambda: {"a": [("", "", {})]}) +SelectField(choices=lambda: {"a": [(True, "t", {})]}) +SelectField(choices=lambda: {"a": [(True, "t"), (False, "f", {})]}) +SelectField(choices=lambda: {"a": [(True, "", {})], "b": [(False, "f")]}) diff --git a/stubs/WTForms/@tests/test_cases/check_filters.py b/stubs/WTForms/@tests/test_cases/check_filters.py new file mode 100644 index 000000000000..6a5abce57f23 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_filters.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from wtforms import Field, Form + + +class Filter1: + def __call__(self, value: object) -> None: ... + + +class Filter2: + def __call__(self, input: None) -> None: ... + + +def not_a_filter(a: object, b: object) -> None: ... + + +def also_not_a_filter() -> None: ... + + +# we should accept any mapping of sequences, we can't really validate +# the filter functions when it's this nested +form = Form() +form.process(extra_filters={"foo": (str.upper, str.strip, int), "bar": (Filter1(), Filter2())}) +form.process(extra_filters={"foo": [str.upper, str.strip, int], "bar": [Filter1(), Filter2()]}) + +# regardless of how we pass the filters into Field it should work +field = Field(filters=(str.upper, str.lower, int)) +Field(filters=(Filter1(), Filter2())) +Field(filters=[str.upper, str.lower, int]) +Field(filters=[Filter1(), Filter2()]) +field.process(None, extra_filters=(str.upper, str.lower, int)) +field.process(None, extra_filters=(Filter1(), Filter2())) +field.process(None, extra_filters=[str.upper, str.lower, int]) +field.process(None, extra_filters=[Filter1(), Filter2()]) + +# but if we pass in some callables with an incompatible param spec +# then we should get type errors +Field(filters=(str.upper, str.lower, int, not_a_filter)) # type: ignore +Field(filters=(Filter1(), Filter2(), also_not_a_filter)) # type: ignore +Field(filters=[str.upper, str.lower, int, also_not_a_filter]) # type: ignore +Field(filters=[Filter1(), Filter2(), not_a_filter]) # type: ignore +field.process(None, extra_filters=(str.upper, str.lower, int, not_a_filter)) # type: ignore +field.process(None, extra_filters=(Filter1(), Filter2(), also_not_a_filter)) # type: ignore +field.process(None, extra_filters=[str.upper, str.lower, int, also_not_a_filter]) # type: ignore +field.process(None, extra_filters=[Filter1(), Filter2(), not_a_filter]) # type: ignore diff --git a/stubs/WTForms/@tests/test_cases/check_form.py b/stubs/WTForms/@tests/test_cases/check_form.py new file mode 100644 index 000000000000..250e400a1875 --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_form.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from wtforms import Form, StringField +from wtforms.fields.core import UnboundField + + +class MyForm(Form): + name = StringField() + + +form = MyForm() +assert_type(form, MyForm) +assert_type(form.name, StringField) +assert_type(MyForm.name, UnboundField[StringField]) diff --git a/stubs/WTForms/@tests/test_cases/check_validators.py b/stubs/WTForms/@tests/test_cases/check_validators.py new file mode 100644 index 000000000000..592968c183dd --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_validators.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from wtforms import DateField, Field, Form, StringField +from wtforms.validators import Email, Optional + +form = Form() +# on form we should accept any validator mapping +form.validate({"field": (Optional(),), "string_field": (Optional(), Email())}) +form.validate({"field": [Optional()], "string_field": [Optional(), Email()]}) + +# both StringField validators and Field validators should be valid +# as inputs on a StringField +string_field = StringField(validators=(Optional(), Email())) +string_field.validate(form, (Optional(), Email())) + +# but not on Field +field = Field(validators=(Optional(), Email())) # type: ignore +field.validate(form, (Optional(), Email())) # type: ignore + +# unless we only pass the Field validator +Field(validators=(Optional(),)) +field.validate(form, (Optional(),)) + +# DateField should accept Field validators but not StringField validators +date_field = DateField(validators=(Optional(), Email())) # type: ignore +date_field.validate(form, (Optional(), Email())) # type: ignore +DateField(validators=(Optional(),)) + +# for lists we can't be as strict so we won't get type errors here +Field(validators=[Optional(), Email()]) +field.validate(form, [Optional(), Email()]) +DateField(validators=[Optional(), Email()]) +date_field.validate(form, [Optional(), Email()]) diff --git a/stubs/WTForms/@tests/test_cases/check_widgets.py b/stubs/WTForms/@tests/test_cases/check_widgets.py new file mode 100644 index 000000000000..7935359a08ea --- /dev/null +++ b/stubs/WTForms/@tests/test_cases/check_widgets.py @@ -0,0 +1,26 @@ +from __future__ import annotations + +from wtforms import Field, FieldList, Form, FormField, SelectField, StringField +from wtforms.widgets import Input, ListWidget, Option, Select, TableWidget, TextArea + +# more specific widgets should only work on more specific fields +Field(widget=Input()) +Field(widget=TextArea()) # type: ignore +Field(widget=Select()) # type: ignore + +# less specific widgets are fine, even if they're often not what you want +StringField(widget=Input()) +StringField(widget=TextArea()) + +SelectField(widget=Input(), option_widget=Input()) +SelectField(widget=Select(), option_widget=Option()) +# a more specific type other than Option widget is not allowed +SelectField(widget=Select(), option_widget=TextArea()) # type: ignore + +# we should be able to pass Field() even though it wants an unbound_field +# this gets around __new__ not working in type checking +FieldList(Field(), widget=Input()) +FieldList(Field(), widget=ListWidget()) + +FormField(Form, widget=Input()) +FormField(Form, widget=TableWidget()) diff --git a/stubs/WTForms/METADATA.toml b/stubs/WTForms/METADATA.toml new file mode 100644 index 000000000000..62e6a60d86ce --- /dev/null +++ b/stubs/WTForms/METADATA.toml @@ -0,0 +1,3 @@ +version = "~= 3.2.1" +upstream-repository = "https://github.com/pallets-eco/wtforms" +dependencies = ["MarkupSafe"] diff --git a/stubs/WTForms/wtforms/__init__.pyi b/stubs/WTForms/wtforms/__init__.pyi new file mode 100644 index 000000000000..1bdf94499a55 --- /dev/null +++ b/stubs/WTForms/wtforms/__init__.pyi @@ -0,0 +1,85 @@ +from typing import Final + +from wtforms import validators as validators, widgets as widgets +from wtforms.fields.choices import ( + RadioField as RadioField, + SelectField as SelectField, + SelectFieldBase as SelectFieldBase, + SelectMultipleField as SelectMultipleField, +) +from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label +from wtforms.fields.datetime import ( + DateField as DateField, + DateTimeField as DateTimeField, + DateTimeLocalField as DateTimeLocalField, + MonthField as MonthField, + TimeField as TimeField, + WeekField as WeekField, +) +from wtforms.fields.form import FormField as FormField +from wtforms.fields.list import FieldList as FieldList +from wtforms.fields.numeric import ( + DecimalField as DecimalField, + DecimalRangeField as DecimalRangeField, + FloatField as FloatField, + IntegerField as IntegerField, + IntegerRangeField as IntegerRangeField, +) +from wtforms.fields.simple import ( + BooleanField as BooleanField, + ColorField as ColorField, + EmailField as EmailField, + FileField as FileField, + HiddenField as HiddenField, + MultipleFileField as MultipleFileField, + PasswordField as PasswordField, + SearchField as SearchField, + StringField as StringField, + SubmitField as SubmitField, + TelField as TelField, + TextAreaField as TextAreaField, + URLField as URLField, +) +from wtforms.form import Form as Form +from wtforms.validators import ValidationError as ValidationError + +__version__: Final[str] +__all__ = [ + "validators", + "widgets", + "Form", + "ValidationError", + "SelectField", + "SelectFieldBase", + "SelectMultipleField", + "RadioField", + "Field", + "Flags", + "Label", + "DateTimeField", + "DateField", + "TimeField", + "MonthField", + "DateTimeLocalField", + "WeekField", + "FormField", + "FieldList", + "IntegerField", + "DecimalField", + "FloatField", + "IntegerRangeField", + "DecimalRangeField", + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", +] diff --git a/stubs/WTForms/wtforms/csrf/__init__.pyi b/stubs/WTForms/wtforms/csrf/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/WTForms/wtforms/csrf/core.pyi b/stubs/WTForms/wtforms/csrf/core.pyi new file mode 100644 index 000000000000..4db69c8c5223 --- /dev/null +++ b/stubs/WTForms/wtforms/csrf/core.pyi @@ -0,0 +1,41 @@ +from abc import abstractmethod +from collections.abc import Callable, Sequence +from typing import Any +from typing_extensions import Self + +from wtforms.fields import HiddenField +from wtforms.fields.core import UnboundField, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("CSRFTokenField", "CSRF") + +class CSRFTokenField(HiddenField): + current_token: str | None + csrf_impl: CSRF + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: str | Callable[[], str] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + *, + csrf_impl: CSRF, + ) -> None: ... + +class CSRF: + field_class: type[CSRFTokenField] + def setup_form(self, form: BaseForm) -> list[tuple[str, UnboundField[Any]]]: ... + @abstractmethod + def generate_csrf_token(self, csrf_token_field: CSRFTokenField) -> str: ... + @abstractmethod + def validate_csrf_token(self, form: BaseForm, field: CSRFTokenField) -> None: ... diff --git a/stubs/WTForms/wtforms/csrf/session.pyi b/stubs/WTForms/wtforms/csrf/session.pyi new file mode 100644 index 000000000000..954734a7b065 --- /dev/null +++ b/stubs/WTForms/wtforms/csrf/session.pyi @@ -0,0 +1,20 @@ +from _typeshed import SupportsItemAccess +from datetime import datetime, timedelta +from typing import Any + +from wtforms.csrf.core import CSRF, CSRFTokenField +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta + +__all__ = ("SessionCSRF",) + +class SessionCSRF(CSRF): + TIME_FORMAT: str + form_meta: DefaultMeta + def generate_csrf_token(self, csrf_token_field: CSRFTokenField) -> str: ... + def validate_csrf_token(self, form: BaseForm, field: CSRFTokenField) -> None: ... + def now(self) -> datetime: ... + @property + def time_limit(self) -> timedelta: ... + @property + def session(self) -> SupportsItemAccess[str, Any]: ... diff --git a/stubs/WTForms/wtforms/fields/__init__.pyi b/stubs/WTForms/wtforms/fields/__init__.pyi new file mode 100644 index 000000000000..b88edf9d427b --- /dev/null +++ b/stubs/WTForms/wtforms/fields/__init__.pyi @@ -0,0 +1,77 @@ +from wtforms.fields.choices import ( + RadioField as RadioField, + SelectField as SelectField, + SelectFieldBase as SelectFieldBase, + SelectMultipleField as SelectMultipleField, +) +from wtforms.fields.core import Field as Field, Flags as Flags, Label as Label +from wtforms.fields.datetime import ( + DateField as DateField, + DateTimeField as DateTimeField, + DateTimeLocalField as DateTimeLocalField, + MonthField as MonthField, + TimeField as TimeField, + WeekField as WeekField, +) +from wtforms.fields.form import FormField as FormField +from wtforms.fields.list import FieldList as FieldList +from wtforms.fields.numeric import ( + DecimalField as DecimalField, + DecimalRangeField as DecimalRangeField, + FloatField as FloatField, + IntegerField as IntegerField, + IntegerRangeField as IntegerRangeField, +) +from wtforms.fields.simple import ( + BooleanField as BooleanField, + ColorField as ColorField, + EmailField as EmailField, + FileField as FileField, + HiddenField as HiddenField, + MultipleFileField as MultipleFileField, + PasswordField as PasswordField, + SearchField as SearchField, + StringField as StringField, + SubmitField as SubmitField, + TelField as TelField, + TextAreaField as TextAreaField, + URLField as URLField, +) +from wtforms.utils import unset_value as _unset_value + +__all__ = [ + "Field", + "Flags", + "Label", + "SelectField", + "SelectFieldBase", + "SelectMultipleField", + "RadioField", + "DateTimeField", + "DateField", + "TimeField", + "MonthField", + "DateTimeLocalField", + "WeekField", + "FormField", + "IntegerField", + "DecimalField", + "FloatField", + "IntegerRangeField", + "DecimalRangeField", + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", + "FieldList", + "_unset_value", +] diff --git a/stubs/WTForms/wtforms/fields/choices.pyi b/stubs/WTForms/wtforms/fields/choices.pyi new file mode 100644 index 000000000000..6ba8d1b40f09 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/choices.pyi @@ -0,0 +1,79 @@ +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, TypeAlias +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("SelectField", "SelectMultipleField", "RadioField") + +# technically this allows a list, but we're more strict for type safety +_Choice: TypeAlias = tuple[Any, str] | tuple[Any, str, dict[str, Any]] +# it's too difficult to get type safety here due to to nested partially invariant collections +_GroupedChoices: TypeAlias = dict[str, Any] # Any should be Collection[_Choice] +_FullChoice: TypeAlias = tuple[Any, str, bool, dict[str, Any]] # value, label, selected, render_kw +_FullGroupedChoices: TypeAlias = tuple[str, Iterable[_FullChoice]] +_Option: TypeAlias = SelectFieldBase._Option + +class SelectFieldBase(Field): + option_widget: _Widget[_Option] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + option_widget: _Widget[_Option] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def iter_choices(self) -> Iterator[_FullChoice]: ... + def has_groups(self) -> bool: ... + def iter_groups(self) -> Iterator[_FullGroupedChoices]: ... + def __iter__(self) -> Iterator[_Option]: ... + + class _Option(Field): + checked: bool + +class SelectField(SelectFieldBase): + coerce: Callable[[Any], Any] + choices: Sequence[_Choice] | _GroupedChoices | None + validate_choice: bool + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + coerce: Callable[[Any], Any] = ..., + choices: Iterable[_Choice] | _GroupedChoices | Callable[[], Iterable[_Choice] | _GroupedChoices] | None = None, + validate_choice: bool = True, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + option_widget: _Widget[_Option] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def iter_choices(self) -> Iterator[_FullChoice]: ... + def has_groups(self) -> bool: ... + def iter_groups(self) -> Iterator[_FullGroupedChoices]: ... + +class SelectMultipleField(SelectField): + data: list[Any] | None + +class RadioField(SelectField): ... diff --git a/stubs/WTForms/wtforms/fields/core.pyi b/stubs/WTForms/wtforms/fields/core.pyi new file mode 100644 index 000000000000..101f31fc03c6 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/core.pyi @@ -0,0 +1,134 @@ +from builtins import type as _type # type is being shadowed in Field +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from markupsafe import Markup +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _MultiDictLikeWithGetlist, _SupportsGettextAndNgettext + +_FormT = TypeVar("_FormT", bound=BaseForm) +_FieldT = TypeVar("_FieldT", bound=Field) +_FormT_contra = TypeVar("_FormT_contra", bound=BaseForm, contravariant=True) +_FieldT_contra = TypeVar("_FieldT_contra", bound=Field, contravariant=True) +# It would be nice to annotate this as invariant, i.e. input type and output type +# needs to be the same, but it will probably be too annoying to use, for now we +# trust, that people won't use it to change the type of data in a field... +_Filter: TypeAlias = Callable[[Any], Any] + +@type_check_only +class _Validator(Protocol[_FormT_contra, _FieldT_contra]): + def __call__(self, form: _FormT_contra, field: _FieldT_contra, /) -> object: ... + +@type_check_only +class _Widget(Protocol[_FieldT_contra]): + def __call__(self, field: _FieldT_contra, **kwargs: Any) -> Markup: ... + +class Field: + errors: Sequence[str] + process_errors: Sequence[str] + raw_data: list[Any] | None + object_data: Any + data: Any + validators: Sequence[_Validator[Any, Self]] + # even though this could be None on the base class, this should + # never actually be None in a real field + widget: _Widget[Self] + do_not_call_in_templates: bool + meta: DefaultMeta + default: Any | None + description: str + render_kw: dict[str, Any] + filters: Sequence[_Filter] + flags: Flags + name: str + short_name: str + id: str + type: str + label: Label + # technically this can return UnboundField, but that is not allowed + # by type checkers, so we use a descriptor hack to get around this + # limitation instead + def __new__(cls, *args: Any, **kwargs: Any) -> Self: ... + def __init__( + self, + label: str | None = None, + # for tuple we can be a bit more type safe and only accept validators + # that would work on this or a less specific field, but in general it + # would be too annoying to restrict to Sequence[_Validator], since mypy + # will infer a list of mixed validators as list[object], since that is + # the common base class between all validators + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def __html__(self) -> str: ... + def __call__(self, **kwargs: object) -> Markup: ... + @classmethod + def check_validators(cls, validators: Iterable[_Validator[_FormT, Self]] | None) -> None: ... + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + def validate(self, form: BaseForm, extra_validators: tuple[_Validator[_FormT, Self], ...] | list[Any] = ()) -> bool: ... + def pre_validate(self, form: BaseForm) -> None: ... + def post_validate(self, form: BaseForm, validation_stopped: bool) -> None: ... + def process( + self, formdata: _MultiDictLikeWithGetlist | None, data: Any = ..., extra_filters: Sequence[_Filter] | None = None + ) -> None: ... + def process_data(self, value: Any) -> None: ... + def process_formdata(self, valuelist: list[Any]) -> None: ... + def populate_obj(self, obj: object, name: str) -> None: ... + + # this is a workaround for what is essentially illegal in static type checking + # Field.__new__ would return an UnboundField, unless the _form parameter is + # specified. We can't really work around it by making UnboundField a subclass + # of Field, since all subclasses of Field still need to return an UnboundField + # and we can't expect third parties to add a __new__ method to every field + # they define... + # This workaround only works for Form, not BaseForm, but we take what we can get + # BaseForm shouldn't really be used anyways + @overload + def __get__(self, obj: None, owner: _type[object] | None = None) -> UnboundField[Self]: ... + @overload + def __get__(self, obj: object, owner: _type[object] | None = None) -> Self: ... + +class UnboundField(Generic[_FieldT]): + creation_counter: int + field_class: type[_FieldT] + name: str | None + args: tuple[Any, ...] + kwargs: dict[str, Any] + def __init__(self, field_class: type[_FieldT], *args: object, name: str | None = None, **kwargs: object) -> None: ... + def bind( + self, + form: BaseForm, + name: str, + prefix: str = "", + translations: _SupportsGettextAndNgettext | None = None, + **kwargs: object, + ) -> _FieldT: ... + +class Flags: + # the API for this is a bit loosey goosey, the intention probably + # was that the values should always be boolean, but __contains__ + # just returns the same thing as __getattr__ and in the widgets + # there are fields that could accept numeric values from Flags + def __getattr__(self, name: str) -> Any | None: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, name: str) -> Any | None: ... + +class Label: + field_id: str + text: str + def __init__(self, field_id: str, text: str) -> None: ... + def __html__(self) -> str: ... + def __call__(self, text: str | None = None, **kwargs: Any) -> Markup: ... diff --git a/stubs/WTForms/wtforms/fields/datetime.pyi b/stubs/WTForms/wtforms/fields/datetime.pyi new file mode 100644 index 000000000000..426dbfaec91f --- /dev/null +++ b/stubs/WTForms/wtforms/fields/datetime.pyi @@ -0,0 +1,138 @@ +from collections.abc import Callable, Sequence +from datetime import date, datetime, time +from typing import Any +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("DateTimeField", "DateField", "TimeField", "MonthField", "DateTimeLocalField", "WeekField") + +class DateTimeField(Field): + format: list[str] + strptime_format: list[str] + data: datetime | None + default: datetime | Callable[[], datetime] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m-%d %H:%M:%S", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: datetime | Callable[[], datetime] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DateField(DateTimeField): + data: date | None # type: ignore[assignment] + default: date | Callable[[], date] | None # type: ignore[assignment] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m-%d", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: date | Callable[[], date] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class TimeField(DateTimeField): + data: time | None # type: ignore[assignment] + default: time | Callable[[], time] | None # type: ignore[assignment] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%H:%M", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class MonthField(DateField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-%m", + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class WeekField(DateField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = "%Y-W%W", # only difference is the default value + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DateTimeLocalField(DateTimeField): + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + format: str | list[str] = ..., + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: time | Callable[[], time] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... diff --git a/stubs/WTForms/wtforms/fields/form.pyi b/stubs/WTForms/wtforms/fields/form.pyi new file mode 100644 index 000000000000..16b7e2016eed --- /dev/null +++ b/stubs/WTForms/wtforms/fields/form.pyi @@ -0,0 +1,40 @@ +from collections.abc import Iterator +from typing import Any, Generic, TypeVar + +from wtforms.fields.core import Field, _Widget +from wtforms.form import BaseForm, _FormErrors +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("FormField",) + +_BoundFormT = TypeVar("_BoundFormT", bound=BaseForm) + +class FormField(Field, Generic[_BoundFormT]): + form_class: type[_BoundFormT] + form: _BoundFormT + separator: str + def __init__( + self: FormField[_BoundFormT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + form_class: type[_BoundFormT], + label: str | None = None, + validators: None = None, + separator: str = "-", + *, + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[FormField[_BoundFormT]] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def __iter__(self) -> Iterator[Field]: ... + def __getitem__(self, name: str) -> Field: ... + def __getattr__(self, name: str) -> Field: ... + @property + def data(self) -> dict[str, Any]: ... + @property + def errors(self) -> _FormErrors: ... # type: ignore[override] diff --git a/stubs/WTForms/wtforms/fields/list.pyi b/stubs/WTForms/wtforms/fields/list.pyi new file mode 100644 index 000000000000..2142009c810d --- /dev/null +++ b/stubs/WTForms/wtforms/fields/list.pyi @@ -0,0 +1,51 @@ +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, Generic, TypeVar + +from wtforms.fields.core import Field, UnboundField, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ("FieldList",) + +_BoundFieldT = TypeVar("_BoundFieldT", bound=Field) + +class FieldList(Field, Generic[_BoundFieldT]): + unbound_field: UnboundField[_BoundFieldT] + min_entries: int + max_entries: int | None + last_index: int + entries: list[_BoundFieldT] + object_data: Iterable[Any] + # NOTE: This depends on the shape of errors of the bound field, which usually should + # be a `Sequence[Sequence[str]]`, but can be `Sequence[_FormErrors]` for `FormField` + # we could model this with a fake descriptor with overloads for `FieldList[FormField]` + # but it might not be worth the hassle, for now we'll just leave it lax + errors: Sequence[Any] + def __init__( + self: FieldList[_BoundFieldT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + # because of our workaround we need to accept Field as well + unbound_field: UnboundField[_BoundFieldT] | _BoundFieldT, + label: str | None = None, + validators: tuple[_Validator[_FormT, _BoundFieldT], ...] | list[Any] | None = None, + min_entries: int = 0, + max_entries: int | None = None, + separator: str = "-", + default: Iterable[Any] | Callable[[], Iterable[Any]] = (), + *, + description: str = "", + id: str | None = None, + widget: _Widget[FieldList[Any]] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + def append_entry(self, data: Any = ...) -> _BoundFieldT: ... + def pop_entry(self) -> _BoundFieldT: ... + def __iter__(self) -> Iterator[_BoundFieldT]: ... + def __len__(self) -> int: ... + def __getitem__(self, index: int) -> _BoundFieldT: ... + @property + def data(self) -> list[Any]: ... diff --git a/stubs/WTForms/wtforms/fields/numeric.pyi b/stubs/WTForms/wtforms/fields/numeric.pyi new file mode 100644 index 000000000000..e88aad5a7c92 --- /dev/null +++ b/stubs/WTForms/wtforms/fields/numeric.pyi @@ -0,0 +1,146 @@ +from collections.abc import Callable, Sequence +from decimal import Decimal +from typing import Any, Literal, overload +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext +from wtforms.utils import UnsetValue + +__all__ = ("IntegerField", "DecimalField", "FloatField", "IntegerRangeField", "DecimalRangeField") + +class LocaleAwareNumberField(Field): + use_locale: bool + number_format: Any | None + locale: str + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + use_locale: bool = False, + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotating this one argument + number_format: str | Any | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: object | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class IntegerField(Field): + data: int | None + # technically this is not as strict and will accept anything + # that can be passed into int(), but we might as well be + default: int | Callable[[], int] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: int | Callable[[], int] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class DecimalField(LocaleAwareNumberField): + data: Decimal | None + # technically this is not as strict and will accept anything + # that can be passed into Decimal(), but we might as well be + default: Decimal | Callable[[], Decimal] | None + places: int | None + rounding: str | None + + @overload + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + places: UnsetValue = ..., + rounding: None = None, + use_locale: Literal[True], + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotation this one argument + number_format: str | Any | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: Decimal | Callable[[], Decimal] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + @overload + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + places: int | UnsetValue | None = ..., + rounding: str | None = None, + *, + use_locale: Literal[False] = False, + # this accepts a babel.numbers.NumberPattern, but since it + # is an optional dependency we don't want to depend on it + # for annotation this one argument + number_format: str | Any | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: Decimal | Callable[[], Decimal] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class FloatField(Field): + data: float | None + # technically this is not as strict and will accept anything + # that can be passed into float(), but we might as well be + default: float | Callable[[], float] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: float | Callable[[], float] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class IntegerRangeField(IntegerField): ... +class DecimalRangeField(DecimalField): ... diff --git a/stubs/WTForms/wtforms/fields/simple.pyi b/stubs/WTForms/wtforms/fields/simple.pyi new file mode 100644 index 000000000000..13bc3f4ed45d --- /dev/null +++ b/stubs/WTForms/wtforms/fields/simple.pyi @@ -0,0 +1,81 @@ +from collections.abc import Callable, Collection, Sequence +from typing import Any +from typing_extensions import Self + +from wtforms.fields.core import Field, _Filter, _FormT, _Validator, _Widget +from wtforms.form import BaseForm +from wtforms.meta import DefaultMeta, _SupportsGettextAndNgettext + +__all__ = ( + "BooleanField", + "TextAreaField", + "PasswordField", + "FileField", + "MultipleFileField", + "HiddenField", + "SearchField", + "SubmitField", + "StringField", + "TelField", + "URLField", + "EmailField", + "ColorField", +) + +class BooleanField(Field): + data: bool + default: bool | Callable[[], bool] | None + false_values: Collection[Any] + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + false_values: Collection[Any] | None = None, + *, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: bool | Callable[[], bool] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class StringField(Field): + data: str | None + default: str | Callable[[], str] | None + def __init__( + self, + label: str | None = None, + validators: tuple[_Validator[_FormT, Self], ...] | list[Any] | None = None, + filters: Sequence[_Filter] = (), + description: str = "", + id: str | None = None, + default: str | Callable[[], str] | None = None, + widget: _Widget[Self] | None = None, + render_kw: dict[str, Any] | None = None, + name: str | None = None, + _form: BaseForm | None = None, + _prefix: str = "", + _translations: _SupportsGettextAndNgettext | None = None, + _meta: DefaultMeta | None = None, + ) -> None: ... + +class TextAreaField(StringField): ... +class PasswordField(StringField): ... +class FileField(Field): ... + +class MultipleFileField(FileField): + data: list[Any] + +class HiddenField(StringField): ... +class SubmitField(BooleanField): ... +class SearchField(StringField): ... +class TelField(StringField): ... +class URLField(StringField): ... +class EmailField(StringField): ... +class ColorField(StringField): ... diff --git a/stubs/WTForms/wtforms/form.pyi b/stubs/WTForms/wtforms/form.pyi new file mode 100644 index 000000000000..a8337d394696 --- /dev/null +++ b/stubs/WTForms/wtforms/form.pyi @@ -0,0 +1,87 @@ +from _typeshed import SupportsItems +from collections.abc import Iterable, Iterator, Mapping, Sequence +from typing import Any, ClassVar, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from wtforms.fields.core import Field, UnboundField +from wtforms.meta import DefaultMeta, _MultiDictLike + +_T = TypeVar("_T") +_FormErrors: TypeAlias = dict[str, Sequence[str] | _FormErrors] + +# _unbound_fields will always be a list on an instance, but on a +# class it might be None, if it never has been instantiated, or +# not instantianted after a new field had been added/removed +@type_check_only +class _UnboundFields(Protocol): + @overload + def __get__(self, obj: None, owner: type[object] | None = None, /) -> list[tuple[str, UnboundField[Any]]] | None: ... + @overload + def __get__(self, obj: object, owner: type[object] | None = None, /) -> list[tuple[str, UnboundField[Any]]]: ... + +class BaseForm: + meta: DefaultMeta + form_errors: list[str] + # we document this, because it's the only efficient way to introspect + # the field names of the form, it also seems to be stable API-wise + _fields: dict[str, Field] + def __init__( + self, + fields: SupportsItems[str, UnboundField[Any]] | Iterable[tuple[str, UnboundField[Any]]], + prefix: str = "", + meta: DefaultMeta = ..., + ) -> None: ... + def __iter__(self) -> Iterator[Field]: ... + def __contains__(self, name: str) -> bool: ... + def __getitem__(self, name: str) -> Field: ... + def __setitem__(self, name: str, value: UnboundField[Any]) -> None: ... + def __delitem__(self, name: str) -> None: ... + def populate_obj(self, obj: object) -> None: ... + # while we would like to be more strict on extra_filters, we can't easily do that + # without it being annoying in most situations + def process( + self, + formdata: _MultiDictLike | None = None, + obj: object | None = None, + data: Mapping[str, Any] | None = None, + extra_filters: Mapping[str, Sequence[Any]] | None = None, + **kwargs: object, + ) -> None: ... + # same thing here with extra_validators + def validate(self, extra_validators: Mapping[str, Sequence[Any]] | None = None) -> bool: ... + @property + def data(self) -> dict[str, Any]: ... + # because of the Liskov violation in FormField.errors we need to make errors a recursive type + @property + def errors(self) -> _FormErrors: ... + +class FormMeta(type): + def __init__(cls, name: str, bases: Sequence[type[object]], attrs: Mapping[str, Any]) -> None: ... + def __call__(cls: type[_T], *args: Any, **kwargs: Any) -> _T: ... + def __setattr__(cls, name: str, value: object) -> None: ... + def __delattr__(cls, name: str) -> None: ... + +class Form(BaseForm, metaclass=FormMeta): + # due to the metaclass this should always be a subclass of DefaultMeta + # but if we annotate this as such, then subclasses cannot use it in the + # intended way + Meta: ClassVar[type[Any]] + # this attribute is documented, so we annotate it + _unbound_fields: _UnboundFields + def __init__( + self, + formdata: _MultiDictLike | None = None, + obj: object | None = None, + prefix: str = "", + data: Mapping[str, Any] | None = None, + meta: Mapping[str, Any] | None = None, + *, + # same issue as with process + extra_filters: Mapping[str, Sequence[Any]] | None = None, + **kwargs: object, + ) -> None: ... + # this should emit a type_error, since it's not allowed to be called + def __setitem__(self, name: str, value: None) -> None: ... # type: ignore[override] + def __delitem__(self, name: str) -> None: ... + def __delattr__(self, name: str) -> None: ... + +__all__ = ("BaseForm", "Form") diff --git a/stubs/WTForms/wtforms/i18n.pyi b/stubs/WTForms/wtforms/i18n.pyi new file mode 100644 index 000000000000..f8ac4b504556 --- /dev/null +++ b/stubs/WTForms/wtforms/i18n.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable, Iterable +from gettext import GNUTranslations +from typing import Protocol, TypeVar, overload, type_check_only + +_T = TypeVar("_T") + +@type_check_only +class _SupportsUgettextAndUngettext(Protocol): + def ugettext(self, string: str, /) -> str: ... + def ungettext(self, singular: str, plural: str, n: int, /) -> str: ... + +def messages_path() -> str: ... +def get_builtin_gnu_translations(languages: Iterable[str] | None = None) -> GNUTranslations: ... + +@overload +def get_translations( + languages: Iterable[str] | None = None, getter: Callable[[Iterable[str]], GNUTranslations] = ... +) -> GNUTranslations: ... +@overload +def get_translations(languages: Iterable[str] | None = None, *, getter: Callable[[Iterable[str]], _T]) -> _T: ... +@overload +def get_translations(languages: Iterable[str] | None, getter: Callable[[Iterable[str]], _T]) -> _T: ... + +class DefaultTranslations: + translations: _SupportsUgettextAndUngettext + def __init__(self, translations: _SupportsUgettextAndUngettext) -> None: ... + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... + +class DummyTranslations: + def gettext(self, string: str) -> str: ... + def ngettext(self, singular: str, plural: str, n: int) -> str: ... diff --git a/stubs/WTForms/wtforms/meta.pyi b/stubs/WTForms/wtforms/meta.pyi new file mode 100644 index 000000000000..ee207e7e782d --- /dev/null +++ b/stubs/WTForms/wtforms/meta.pyi @@ -0,0 +1,60 @@ +from _typeshed import SupportsItems +from collections.abc import Collection, Iterator, MutableMapping +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from markupsafe import Markup +from wtforms.fields.core import Field, UnboundField +from wtforms.form import BaseForm + +_FieldT = TypeVar("_FieldT", bound=Field) + +@type_check_only +class _SupportsGettextAndNgettext(Protocol): + def gettext(self, string: str, /) -> str: ... + def ngettext(self, singular: str, plural: str, n: int, /) -> str: ... + +# these are the methods WTForms depends on, the dict can either provide +# a getlist or getall, if it only provides getall, it will wrapped, to +# provide getlist instead +@type_check_only +class _MultiDictLikeBase(Protocol): + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: Any, /) -> bool: ... + +# since how file uploads are represented in formdata is implementation-specific +# we have to be generous in what we accept in the return of getlist/getall +# we can make this generic if we ever want to be more specific +@type_check_only +class _MultiDictLikeWithGetlist(_MultiDictLikeBase, Protocol): + def getlist(self, key: str, /) -> list[Any]: ... + +@type_check_only +class _MultiDictLikeWithGetall(_MultiDictLikeBase, Protocol): + def getall(self, key: str, /) -> list[Any]: ... + +_MultiDictLike: TypeAlias = _MultiDictLikeWithGetall | _MultiDictLikeWithGetlist + +class DefaultMeta: + def bind_field(self, form: BaseForm, unbound_field: UnboundField[_FieldT], options: MutableMapping[str, Any]) -> _FieldT: ... + + @overload + def wrap_formdata(self, form: BaseForm, formdata: None) -> None: ... + @overload + def wrap_formdata(self, form: BaseForm, formdata: _MultiDictLike) -> _MultiDictLikeWithGetlist: ... + + def render_field(self, field: Field, render_kw: SupportsItems[str, Any]) -> Markup: ... + csrf: bool + csrf_field_name: str + csrf_secret: Any | None + csrf_context: Any | None + csrf_class: type[Any] | None + def build_csrf(self, form: BaseForm) -> Any: ... + locales: Literal[False] | Collection[str] + cache_translations: bool + translations_cache: dict[str, _SupportsGettextAndNgettext] + def get_translations(self, form: BaseForm) -> _SupportsGettextAndNgettext: ... + def update_values(self, values: SupportsItems[str, Any]) -> None: ... + # since meta can be extended with arbitrary data we add a __getattr__ + # method that returns Any + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/WTForms/wtforms/utils.pyi b/stubs/WTForms/wtforms/utils.pyi new file mode 100644 index 000000000000..ded0e7bc7e6c --- /dev/null +++ b/stubs/WTForms/wtforms/utils.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable, Iterator +from typing import Any, Literal + +from wtforms.meta import _MultiDictLikeWithGetall + +def clean_datetime_format_for_strptime(formats: Iterable[str]) -> list[str]: ... + +class UnsetValue: + def __bool__(self) -> Literal[False]: ... + +unset_value: UnsetValue + +class WebobInputWrapper: + def __init__(self, multidict: _MultiDictLikeWithGetall) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, name: str) -> bool: ... + def getlist(self, name: str) -> list[Any]: ... diff --git a/stubs/WTForms/wtforms/validators.pyi b/stubs/WTForms/wtforms/validators.pyi new file mode 100644 index 000000000000..0389fcb38779 --- /dev/null +++ b/stubs/WTForms/wtforms/validators.pyi @@ -0,0 +1,214 @@ +from collections.abc import Callable, Collection, Iterable +from decimal import Decimal +from re import Match, Pattern +from typing import Any, TypeVar, overload + +from wtforms.fields import Field, StringField +from wtforms.form import BaseForm + +__all__ = ( + "DataRequired", + "data_required", + "Email", + "email", + "EqualTo", + "equal_to", + "IPAddress", + "ip_address", + "InputRequired", + "input_required", + "Length", + "length", + "NumberRange", + "number_range", + "Optional", + "optional", + "Regexp", + "regexp", + "URL", + "url", + "AnyOf", + "any_of", + "NoneOf", + "none_of", + "MacAddress", + "mac_address", + "UUID", + "ValidationError", + "StopValidation", + "readonly", + "ReadOnly", + "disabled", + "Disabled", +) + +_ValuesT_contra = TypeVar("_ValuesT_contra", bound=Collection[Any], contravariant=True) + +class ValidationError(ValueError): + def __init__(self, message: str = "", *args: object) -> None: ... + +class StopValidation(Exception): + def __init__(self, message: str = "", *args: object) -> None: ... + +class EqualTo: + fieldname: str + message: str | None + def __init__(self, fieldname: str, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Length: + min: int + max: int + message: str | None + field_flags: dict[str, Any] + def __init__(self, min: int = -1, max: int = -1, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class NumberRange: + min: float | Decimal | None + max: float | Decimal | None + message: str | None + field_flags: dict[str, Any] + def __init__( + self, min: float | Decimal | None = None, max: float | Decimal | None = None, message: str | None = None + ) -> None: ... + # any numeric field will work, for now we don't try to use a union + # to restrict to the defined numeric fields, since user-defined fields + # will likely not use a common base class, just like the existing + # numeric fields + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Optional: + string_check: Callable[[str], bool] + field_flags: dict[str, Any] + def __init__(self, strip_whitespace: bool = True) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class DataRequired: + message: str | None + field_flags: dict[str, Any] + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class InputRequired: + message: str | None + field_flags: dict[str, Any] + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Regexp: + regex: Pattern[str] + message: str | None + def __init__(self, regex: str | Pattern[str], flags: int = 0, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField, message: str | None = None) -> Match[str]: ... + +class Email: + message: str | None + granular_message: bool + check_deliverability: bool + allow_smtputf8: bool + allow_empty_local: bool + def __init__( + self, + message: str | None = None, + granular_message: bool = False, + check_deliverability: bool = False, + allow_smtputf8: bool = True, + allow_empty_local: bool = False, + ) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class IPAddress: + ipv4: bool + ipv6: bool + message: str | None + def __init__(self, ipv4: bool = True, ipv6: bool = False, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + @classmethod + def check_ipv4(cls, value: str | None) -> bool: ... + @classmethod + def check_ipv6(cls, value: str | None) -> bool: ... + +class MacAddress(Regexp): + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... # type: ignore[override] + +class URL(Regexp): + validate_hostname: HostnameValidation + def __init__(self, require_tld: bool = True, allow_ip: bool = True, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... # type: ignore[override] + +class UUID: + message: str | None + def __init__(self, message: str | None = None) -> None: ... + def __call__(self, form: BaseForm, field: StringField) -> None: ... + +class AnyOf: + values: Collection[Any] + message: str | None + values_formatter: Callable[[Any], str] + + @overload + def __init__(self, values: Collection[Any], message: str | None = None, values_formatter: None = None) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None = None, *, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + + def __call__(self, form: BaseForm, field: Field) -> None: ... + @staticmethod + def default_values_formatter(values: Iterable[object]) -> str: ... + +class NoneOf: + values: Collection[Any] + message: str | None + values_formatter: Callable[[Any], str] + + @overload + def __init__(self, values: Collection[Any], message: str | None = None, values_formatter: None = None) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + @overload + def __init__( + self, values: _ValuesT_contra, message: str | None = None, *, values_formatter: Callable[[_ValuesT_contra], str] + ) -> None: ... + + def __call__(self, form: BaseForm, field: Field) -> None: ... + @staticmethod + def default_values_formatter(v: Iterable[object]) -> str: ... + +class HostnameValidation: + hostname_part: Pattern[str] + tld_part: Pattern[str] + require_tld: bool + allow_ip: bool + def __init__(self, require_tld: bool = True, allow_ip: bool = False) -> None: ... + def __call__(self, hostname: str) -> bool: ... + +class ReadOnly: + def __call__(self, form: BaseForm, field: Field) -> None: ... + +class Disabled: + def __call__(self, form: BaseForm, field: Field) -> None: ... + +email = Email +equal_to = EqualTo +ip_address = IPAddress +mac_address = MacAddress +length = Length +number_range = NumberRange +optional = Optional +input_required = InputRequired +data_required = DataRequired +regexp = Regexp +url = URL +any_of = AnyOf +none_of = NoneOf +readonly = ReadOnly +disabled = Disabled diff --git a/stubs/WTForms/wtforms/widgets/__init__.pyi b/stubs/WTForms/wtforms/widgets/__init__.pyi new file mode 100644 index 000000000000..919a43b3e49a --- /dev/null +++ b/stubs/WTForms/wtforms/widgets/__init__.pyi @@ -0,0 +1,59 @@ +from wtforms.widgets.core import ( + CheckboxInput as CheckboxInput, + ColorInput as ColorInput, + DateInput as DateInput, + DateTimeInput as DateTimeInput, + DateTimeLocalInput as DateTimeLocalInput, + EmailInput as EmailInput, + FileInput as FileInput, + HiddenInput as HiddenInput, + Input as Input, + ListWidget as ListWidget, + MonthInput as MonthInput, + NumberInput as NumberInput, + Option as Option, + PasswordInput as PasswordInput, + RadioInput as RadioInput, + RangeInput as RangeInput, + SearchInput as SearchInput, + Select as Select, + SubmitInput as SubmitInput, + TableWidget as TableWidget, + TelInput as TelInput, + TextArea as TextArea, + TextInput as TextInput, + TimeInput as TimeInput, + URLInput as URLInput, + WeekInput as WeekInput, + html_params as html_params, +) + +__all__ = [ + "CheckboxInput", + "ColorInput", + "DateInput", + "DateTimeInput", + "DateTimeLocalInput", + "EmailInput", + "FileInput", + "HiddenInput", + "ListWidget", + "MonthInput", + "NumberInput", + "Option", + "PasswordInput", + "RadioInput", + "RangeInput", + "SearchInput", + "Select", + "SubmitInput", + "TableWidget", + "TextArea", + "TextInput", + "TelInput", + "TimeInput", + "URLInput", + "WeekInput", + "html_params", + "Input", +] diff --git a/stubs/WTForms/wtforms/widgets/core.pyi b/stubs/WTForms/wtforms/widgets/core.pyi new file mode 100644 index 000000000000..62861c43cb66 --- /dev/null +++ b/stubs/WTForms/wtforms/widgets/core.pyi @@ -0,0 +1,120 @@ +from decimal import Decimal +from typing import Any, Literal + +from markupsafe import Markup +from wtforms.fields import Field, FormField, StringField +from wtforms.fields.choices import SelectFieldBase, _Option + +__all__ = ( + "CheckboxInput", + "ColorInput", + "DateInput", + "DateTimeInput", + "DateTimeLocalInput", + "EmailInput", + "FileInput", + "HiddenInput", + "ListWidget", + "MonthInput", + "NumberInput", + "Option", + "PasswordInput", + "RadioInput", + "RangeInput", + "SearchInput", + "Select", + "SubmitInput", + "TableWidget", + "TextArea", + "TextInput", + "TelInput", + "TimeInput", + "URLInput", + "WeekInput", +) + +def html_params(**kwargs: object) -> str: ... + +class ListWidget: + html_tag: Literal["ul", "ol"] + prefix_label: bool + def __init__(self, html_tag: Literal["ul", "ol"] = "ul", prefix_label: bool = True) -> None: ... + # any iterable field is fine, since people might define iterable fields + # that are not derived from FieldList, we just punt and accept any field + # with Intersection we could be more specific + def __call__(self, field: Field, **kwargs: object) -> Markup: ... + +class TableWidget: + with_table_tag: bool + def __init__(self, with_table_tag: bool = True) -> None: ... + def __call__(self, field: FormField[Any], **kwargs: object) -> Markup: ... + +class Input: + validation_attrs: list[str] + input_type: str + def __init__(self, input_type: str | None = None) -> None: ... + def __call__(self, field: Field, **kwargs: object) -> Markup: ... + @staticmethod + def html_params(**kwargs: object) -> str: ... + +class TextInput(Input): ... + +class PasswordInput(Input): + hide_value: bool + def __init__(self, hide_value: bool = True) -> None: ... + +class HiddenInput(Input): + field_flags: dict[str, Any] + +class CheckboxInput(Input): ... +class RadioInput(Input): ... + +class FileInput(Input): + multiple: bool + def __init__(self, multiple: bool = False) -> None: ... + +class SubmitInput(Input): ... + +class TextArea: + validation_attrs: list[str] + def __call__(self, field: StringField, **kwargs: object) -> Markup: ... + +class Select: + validation_attrs: list[str] + multiple: bool + def __init__(self, multiple: bool = False) -> None: ... + def __call__(self, field: SelectFieldBase, **kwargs: object) -> Markup: ... + @classmethod + def render_option(cls, value: object, label: str, selected: bool, **kwargs: object) -> Markup: ... + +class Option: + def __call__(self, field: _Option, **kwargs: object) -> Markup: ... + +class SearchInput(Input): ... +class TelInput(Input): ... +class URLInput(Input): ... +class EmailInput(Input): ... +class DateTimeInput(Input): ... +class DateInput(Input): ... +class MonthInput(Input): ... +class WeekInput(Input): ... +class TimeInput(Input): ... +class DateTimeLocalInput(Input): ... + +class NumberInput(Input): + step: Decimal | float | str | None + min: Decimal | float | str | None + max: Decimal | float | str | None + def __init__( + self, + step: Decimal | float | str | None = None, + min: Decimal | float | str | None = None, + max: Decimal | float | str | None = None, + ) -> None: ... + +class RangeInput(Input): + # maybe we should allow any str for this + step: Decimal | float | str | None + def __init__(self, step: Decimal | float | str | None = None) -> None: ... + +class ColorInput(Input): ... diff --git a/stubs/WebOb/@tests/stubtest_allowlist.txt b/stubs/WebOb/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..4379483af587 --- /dev/null +++ b/stubs/WebOb/@tests/stubtest_allowlist.txt @@ -0,0 +1,166 @@ +# Error: is not present in stub +# ============================= +# These are plain strings, regex strings or compiled regex patterns +# which are used internally for parsing, so they should not be public API +webob.acceptparse.Accept.accept_compiled_re +webob.acceptparse.Accept.accept_ext_compiled_re +webob.acceptparse.Accept.accept_ext_re +webob.acceptparse.Accept.accept_params_re +webob.acceptparse.Accept.media_range_n_accept_params_compiled_re +webob.acceptparse.Accept.media_range_n_accept_params_re +webob.acceptparse.Accept.media_range_re +webob.acceptparse.Accept.media_type_compiled_re +webob.acceptparse.Accept.media_type_re +webob.acceptparse.Accept.obs_text_re +webob.acceptparse.Accept.parameter_re +webob.acceptparse.Accept.parameters_compiled_re +webob.acceptparse.Accept.qdtext_re +webob.acceptparse.Accept.quoted_pair_re +webob.acceptparse.Accept.quoted_string_re +webob.acceptparse.Accept.subtype_re +webob.acceptparse.Accept.type_re +webob.acceptparse.Accept.vchar_re +webob.acceptparse.AcceptCharset.accept_charset_compiled_re +webob.acceptparse.AcceptCharset.charset_n_weight_compiled_re +webob.acceptparse.AcceptCharset.charset_n_weight_re +webob.acceptparse.AcceptCharset.charset_re +webob.acceptparse.AcceptEncoding.accept_encoding_compiled_re +webob.acceptparse.AcceptEncoding.codings_n_weight_compiled_re +webob.acceptparse.AcceptEncoding.codings_n_weight_re +webob.acceptparse.AcceptEncoding.codings_re +webob.acceptparse.AcceptLanguage.accept_language_compiled_re +webob.acceptparse.AcceptLanguage.lang_range_n_weight_compiled_re +webob.acceptparse.AcceptLanguage.lang_range_n_weight_re +webob.acceptparse.AcceptLanguage.lang_range_re +webob.acceptparse.OWS_re +webob.acceptparse.qvalue_re +webob.acceptparse.tchar_re +webob.acceptparse.token_compiled_re +webob.acceptparse.token_re +webob.acceptparse.weight_re +webob.cachecontrol.need_quote_re +webob.cachecontrol.token_re +webob.client.SendRequest.MULTILINE_RE +webob.descriptors.CHARSET_RE +webob.descriptors.SCHEME_RE + +webob.acceptparse.MIMEAccept # Deprecated API + +# PY2 compat stuff that has already been removed upstream +webob.compat.PY2 +webob.compat.PY3 +webob.compat.bytes_ +webob.compat.class_types +webob.compat.integer_types +webob.compat.iteritems_ +webob.compat.itervalues_ +webob.compat.long +webob.compat.native_ +webob.compat.parse_qsl_text +webob.compat.reraise +webob.compat.string_types +webob.compat.text_ +webob.compat.text_type +webob.compat.unquote +webob.multidict.MultiDict.iteritems +webob.multidict.MultiDict.iterkeys +webob.multidict.MultiDict.itervalues +webob.multidict.NestedMultiDict.iteritems +webob.multidict.NestedMultiDict.iterkeys +webob.multidict.NestedMultiDict.itervalues +webob.multidict.NoVars.iterkeys + +# The implementation details of cgi_FieldStorage shouldn't matter +webob.compat.cgi_FieldStorage.read_multi + +# NoVars implements the MultiDict interface for better runtime errors +# but it is annoying for type checking, so the methods that are not +# valid to call on NoVars have been removed. In the future we would +# like to switch to a @type_error() decorator +webob.multidict.NoVars.__getitem__ +webob.multidict.NoVars.__setitem__ +webob.multidict.NoVars.__delitem__ +webob.multidict.NoVars.add +webob.multidict.NoVars.setdefault +webob.multidict.NoVars.update +webob.multidict.NoVars.clear +webob.multidict.NoVars.pop +webob.multidict.NoVars.popitem +webob.multidict.NoVars.getone + +# ResponseBodyFile cannot be closed and emits an Exception, so we're better +# off pretending the method doesn't exist +webob.response.ResponseBodyFile.close + +# Error: is inconsistent +# ====================== +# set_cookie has a deprecated argument `expires` which has been removed upstream +webob.response.Response.set_cookie + +# These are here due to the slightly more strict nature of the type annotation +# of these descriptors for type checking, it does not really have any runtime +# consequences since `_IntValueProperty` derives from `value_property` and +# only makes `__set__` slightly more strict. +webob.cachecontrol.UpdateDict.setdefault + +# Even though at runtime the default argument has a default value of `None` +# that will cause an exception, so we're better off pretending the argument +# is required, and that it can't be `None` +webob.headers.ResponseHeaders.setdefault +webob.multidict.GetDict.setdefault + +# These need to be ignored due to how WebOb decided to let people know +# that certain methods on `NestedMultiDict` should not be called since +# they are immutable, compared to a MultiDict, but still can be used +# interchangeably in some parts of the API. So they reuse generic functions +# that accept any parameters and assign them to methods which should still +# satisfy the same interface. The type annotations enforce the correct +# input arguments instead of the generic ones. +webob.multidict.NestedMultiDict.__delitem__ +webob.multidict.NestedMultiDict.__setitem__ +webob.multidict.NestedMultiDict.add +webob.multidict.NestedMultiDict.clear +webob.multidict.NestedMultiDict.pop +webob.multidict.NestedMultiDict.popitem +webob.multidict.NestedMultiDict.setdefault +webob.multidict.NestedMultiDict.update + +# The `DEFAULT` parameter on these dunder methods don't really make sense as +# part of the public API, so they have been removed from the stubs +webob.request.AdhocAttrMixin.__delattr__ +webob.request.AdhocAttrMixin.__getattr__ +webob.request.AdhocAttrMixin.__setattr__ + +# BaseRequest has a bunch of named parameters that have been deprecated and +# removed upstream, since there's a `**kwargs` anyways, it doesn't really +# make sense to annotate them and pretend they're part of the API. +webob.request.BaseRequest.__init__ + +# We needed to add a dummy *_: _P.args in order to support ParamSpec +webob.dec.wsgify.middleware +webob.dec._MiddlewareFactory.__call__ + +# We renamed some of the arguments in positional only overloads for greater +# clarity about what the arguments mean, stubtest should probably be a bit +# more lenient here, since this is only unsafe if that overload accepts +# arbitrary named arguments, that could overlap with the argument in that +# specific position +webob.dec.wsgify.__call__ + +# Error: is not present at runtime +# ============================= +# This attribute is there to help mypy type narrow NoVars based on its static +# falsyness, so it's to make it possible to narrow the type union in request.POST +# without importing MultiDict or NoVars +webob.multidict.NoVars.__bool__ + +# This attribute is set on the instance instead of the class in the `__init__` +# so the type annotation is technically wrong, however I am unsure about +# whether the ResponseBodyFile would satisfy some of the IO Protocols if +# `write` was defined as a Callable instance attribute. It's hard to come up +# with a use-case where the distinction matters, besides inheriting from +# the class and overwriting the __init__ and forgetting to populate `write`. +webob.response.ResponseBodyFile.write + +# A couple of utility types we use in multiple modules +webob._types diff --git a/stubs/WebOb/@tests/test_cases/check_cachecontrol.py b/stubs/WebOb/@tests/test_cases/check_cachecontrol.py new file mode 100644 index 000000000000..dd20460e466a --- /dev/null +++ b/stubs/WebOb/@tests/test_cases/check_cachecontrol.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import Any, Literal, Union +from typing_extensions import assert_type + +from webob.cachecontrol import CacheControl +from webob.request import BaseRequest +from webob.response import Response + +req = BaseRequest({}) +res = Response() +assert_type(req.cache_control, CacheControl[Literal["request"]]) +assert_type(res.cache_control, CacheControl[Literal["response"]]) + +assert_type(CacheControl.parse(""), CacheControl[None]) +assert_type(CacheControl.parse("", type="request"), CacheControl[Literal["request"]]) +assert_type(CacheControl.parse("", type="response"), CacheControl[Literal["response"]]) + +req_cc = req.cache_control +res_cc = res.cache_control +shared_cc = CacheControl.parse("") +assert_type(req_cc, CacheControl[Literal["request"]]) +assert_type(res_cc, CacheControl[Literal["response"]]) +assert_type(shared_cc, CacheControl[None]) +any_cc = CacheControl[Any]({}, None) + +assert_type(req_cc.max_stale, Union[int, Literal["*"], None]) +res_cc.max_stale # type: ignore +shared_cc.max_stale # type: ignore +assert_type(any_cc.max_stale, Union[int, Literal["*"], None]) + +assert_type(req_cc.min_fresh, Union[int, None]) +res_cc.min_fresh # type: ignore +shared_cc.min_fresh # type: ignore +assert_type(any_cc.min_fresh, Union[int, None]) + +assert_type(req_cc.only_if_cached, bool) +res_cc.only_if_cached # type: ignore +shared_cc.only_if_cached # type: ignore +assert_type(any_cc.only_if_cached, bool) + +req_cc.public # type: ignore +assert_type(res_cc.public, bool) +shared_cc.public # type: ignore +assert_type(any_cc.public, bool) + +# NOTE: pyright gets confused about the `Literal["*"]` the types match +req_cc.private # type: ignore +assert_type(res_cc.private, Union[str, Literal["*"], None]) # pyright: ignore +shared_cc.private # type: ignore +assert_type(any_cc.private, Union[str, Literal["*"], None]) # pyright: ignore + +assert_type(req_cc.no_cache, Union[str, Literal["*"], None]) # pyright: ignore +assert_type(res_cc.no_cache, Union[str, Literal["*"], None]) # pyright: ignore +assert_type(shared_cc.no_cache, Union[str, Literal["*"], None]) # pyright: ignore +assert_type(any_cc.no_cache, Union[str, Literal["*"], None]) # pyright: ignore + +assert_type(req_cc.no_store, bool) +assert_type(res_cc.no_store, bool) +assert_type(shared_cc.no_store, bool) +assert_type(any_cc.no_store, bool) + +assert_type(req_cc.no_transform, bool) +assert_type(res_cc.no_transform, bool) +assert_type(shared_cc.no_transform, bool) +assert_type(any_cc.no_transform, bool) + +req_cc.must_revalidate # type: ignore +assert_type(res_cc.must_revalidate, bool) +shared_cc.must_revalidate # type: ignore +assert_type(any_cc.must_revalidate, bool) + +req_cc.proxy_revalidate # type: ignore +assert_type(res_cc.proxy_revalidate, bool) +shared_cc.proxy_revalidate # type: ignore +assert_type(any_cc.proxy_revalidate, bool) + +# NOTE: pyright gets confused about the `Literal[-1]` the types match +assert_type(req_cc.max_age, Union[int, Literal[-1], None]) # pyright: ignore +assert_type(res_cc.max_age, Union[int, Literal[-1], None]) # pyright: ignore +assert_type(shared_cc.max_age, Union[int, Literal[-1], None]) # pyright: ignore +assert_type(any_cc.max_age, Union[int, Literal[-1], None]) # pyright: ignore + +req_cc.s_maxage # type: ignore +assert_type(res_cc.s_maxage, Union[int, None]) +shared_cc.s_maxage # type: ignore +assert_type(any_cc.s_maxage, Union[int, None]) + +req_cc.s_max_age # type: ignore +assert_type(res_cc.s_max_age, Union[int, None]) +shared_cc.s_max_age # type: ignore +assert_type(any_cc.s_max_age, Union[int, None]) + +req_cc.stale_while_revalidate # type: ignore +assert_type(res_cc.stale_while_revalidate, Union[int, None]) +shared_cc.stale_while_revalidate # type: ignore +assert_type(any_cc.stale_while_revalidate, Union[int, None]) + +req_cc.stale_if_error # type: ignore +assert_type(res_cc.stale_if_error, Union[int, None]) +shared_cc.stale_if_error # type: ignore +assert_type(any_cc.stale_if_error, Union[int, None]) diff --git a/stubs/WebOb/@tests/test_cases/check_wsgify.py b/stubs/WebOb/@tests/test_cases/check_wsgify.py new file mode 100644 index 000000000000..93de11429778 --- /dev/null +++ b/stubs/WebOb/@tests/test_cases/check_wsgify.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from typing_extensions import assert_type + +from webob.dec import _AnyResponse, wsgify +from webob.request import Request + + +class App: + @wsgify + def __call__(self, request: Request) -> str: + return "hello" + + +env: WSGIEnvironment = {} +start_response: StartResponse = lambda x, y, z=None: lambda b: None +application: WSGIApplication = lambda e, s: [b""] +request: Request = Request(env) + +x = App() +# since we wsgified our __call__ we should now be a valid WSGIApplication +application = x +assert_type(x(env, start_response), "Iterable[bytes]") +# currently we lose the exact response type, but that should be fine in +# most use-cases, since middlewares operate on an application level, not +# on these raw intermediary functions +assert_type(x(request), _AnyResponse) + +# accessing the method from the class should work as you expect it to +assert_type(App.__call__(x, env, start_response), "Iterable[bytes]") +assert_type(App.__call__(x, request), _AnyResponse) + + +# but we can also wrap it with a middleware that expects to deal with requests +class Middleware: + @wsgify.middleware + def restrict_ip(self, req: Request, app: WSGIApplication, ips: list[str]) -> WSGIApplication: + return app + + __call__ = restrict_ip(x, ips=["127.0.0.1"]) + + +# and we still end up with a valid WSGIApplication +m = Middleware() +application = m +assert_type(m(env, start_response), "Iterable[bytes]") +assert_type(m(request), _AnyResponse) + + +# the same should work with plain functions +@wsgify +def app(request: Request) -> str: + return "hello" + + +application = app +assert_type(app, "wsgify[[], Request]") +assert_type(app(env, start_response), "Iterable[bytes]") +assert_type(app(request), _AnyResponse) +assert_type(app(application), "wsgify[[], Request]") +application = app(application) + + +@wsgify.middleware +def restrict_ip(req: Request, app: WSGIApplication, ips: list[str]) -> WSGIApplication: + return app + + +@restrict_ip(ips=["127.0.0.1"]) +@wsgify +def m_app(request: Request) -> str: + return "hello" + + +application = m_app +assert_type(m_app, "wsgify[[WSGIApplication], Request]") +assert_type(m_app(env, start_response), "Iterable[bytes]") +assert_type(m_app(request), _AnyResponse) +assert_type(m_app(application), "wsgify[[WSGIApplication], Request]") +application = m_app(application) + + +# custom request +class MyRequest(Request): + pass + + +@wsgify(RequestClass=MyRequest) +def my_request_app(request: MyRequest) -> None: + pass + + +application = my_request_app +assert_type(my_request_app, "wsgify[[], MyRequest]") + + +# we are allowed to accept a less specific request class +@wsgify(RequestClass=MyRequest) +def valid_request_app(request: Request) -> None: + pass + + +# but the opposite is not allowed +@wsgify # type: ignore +def invalid_request_app(request: MyRequest) -> None: + pass + + +# we can't really make passing extra arguments directly work +# otherwise we have to give up most of our type safety for +# something that should only be used through wsgify.middleware +wsgify(args=(1,)) # type: ignore +wsgify(kwargs={"ips": ["127.0.0.1"]}) # type: ignore diff --git a/stubs/WebOb/METADATA.toml b/stubs/WebOb/METADATA.toml new file mode 100644 index 000000000000..eae85173da12 --- /dev/null +++ b/stubs/WebOb/METADATA.toml @@ -0,0 +1,2 @@ +version = "~=1.8.11" +upstream-repository = "https://github.com/Pylons/webob" diff --git a/stubs/WebOb/webob/__init__.pyi b/stubs/WebOb/webob/__init__.pyi new file mode 100644 index 000000000000..b190ee568d5a --- /dev/null +++ b/stubs/WebOb/webob/__init__.pyi @@ -0,0 +1,28 @@ +from webob.datetime_utils import ( + UTC as UTC, + day as day, + hour as hour, + minute as minute, + month as month, + second as second, + week as week, + year as year, +) +from webob.request import LegacyRequest as LegacyRequest, Request as Request +from webob.response import Response as Response +from webob.util import html_escape as html_escape + +__all__ = [ + "Request", + "LegacyRequest", + "Response", + "UTC", + "day", + "week", + "hour", + "minute", + "second", + "month", + "year", + "html_escape", +] diff --git a/stubs/WebOb/webob/_types.pyi b/stubs/WebOb/webob/_types.pyi new file mode 100644 index 000000000000..11c28a5efb9a --- /dev/null +++ b/stubs/WebOb/webob/_types.pyi @@ -0,0 +1,23 @@ +from typing import Protocol, TypeAlias, TypeVar, overload, type_check_only + +_T = TypeVar("_T") +_GetterReturnType_co = TypeVar("_GetterReturnType_co", covariant=True) +_SetterValueType_contra = TypeVar("_SetterValueType_contra", contravariant=True) + +@type_check_only +class AsymmetricProperty(Protocol[_GetterReturnType_co, _SetterValueType_contra]): + @overload + def __get__(self, obj: None, type: type[object] | None = ..., /) -> property: ... + @overload + def __get__(self, obj: object, type: type[object] | None = ..., /) -> _GetterReturnType_co: ... + + def __set__(self, obj: object, value: _SetterValueType_contra, /) -> None: ... + +@type_check_only +class AsymmetricPropertyWithDelete( + AsymmetricProperty[_GetterReturnType_co, _SetterValueType_contra], Protocol[_GetterReturnType_co, _SetterValueType_contra] +): + def __delete__(self, obj: object, /) -> None: ... + +SymmetricProperty: TypeAlias = AsymmetricProperty[_T, _T] +SymmetricPropertyWithDelete: TypeAlias = AsymmetricPropertyWithDelete[_T, _T] diff --git a/stubs/WebOb/webob/acceptparse.pyi b/stubs/WebOb/webob/acceptparse.pyi new file mode 100644 index 000000000000..6ccc4c804f26 --- /dev/null +++ b/stubs/WebOb/webob/acceptparse.pyi @@ -0,0 +1,757 @@ +from _typeshed import SupportsItems +from collections.abc import Callable, Iterable, Iterator, Sequence +from typing import Any, Literal, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricPropertyWithDelete + +_T = TypeVar("_T") +_ListOrTuple: TypeAlias = list[_T] | tuple[_T, ...] +_ParsedAccept: TypeAlias = tuple[str, float, list[tuple[str, str]], list[str | tuple[str, str]]] + +@type_check_only +class _SupportsStr(Protocol): + def __str__(self) -> str: ... # noqa: Y029 + +_AnyAcceptHeader: TypeAlias = AcceptValidHeader | AcceptInvalidHeader | AcceptNoHeader +_AnyAcceptCharsetHeader: TypeAlias = AcceptCharsetValidHeader | AcceptCharsetInvalidHeader | AcceptCharsetNoHeader +_AnyAcceptEncodingHeader: TypeAlias = AcceptEncodingValidHeader | AcceptEncodingInvalidHeader | AcceptEncodingNoHeader +_AnyAcceptLanguageHeader: TypeAlias = AcceptLanguageValidHeader | AcceptLanguageInvalidHeader | AcceptLanguageNoHeader + +_AcceptProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptHeader, + ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptCharsetProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptCharsetHeader, + ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptEncodingProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptEncodingHeader, + ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] +_AcceptLanguageProperty: TypeAlias = AsymmetricPropertyWithDelete[ + _AnyAcceptLanguageHeader, + ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), +] + +@type_check_only +class _AcceptOffer(NamedTuple): + type: str + subtype: str + params: tuple[tuple[str, str], ...] + +class AcceptOffer(_AcceptOffer): + __slots__ = () + +class Accept: + @classmethod + def parse(cls, value: str) -> Iterator[_ParsedAccept]: ... + @classmethod + def parse_offer(cls, offer: str | AcceptOffer) -> AcceptOffer: ... + +class AcceptValidHeader(Accept): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[_ParsedAccept]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def accept_html(self) -> bool: ... + @property + def accepts_html(self) -> bool: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptInvalidOrNoHeader(Accept): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def accept_html(self) -> bool: ... + @property + def accepts_html(self) -> bool: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float: ... + +class AcceptNoHeader(_AcceptInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __add__(self, other: AcceptNoHeader | AcceptInvalidHeader | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptValidHeader: ... + + @overload + def __radd__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __radd__(self, other: AcceptNoHeader | AcceptInvalidHeader | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptValidHeader: ... + +class AcceptInvalidHeader(_AcceptInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __add__(self, other: AcceptInvalidHeader | AcceptNoHeader | None) -> AcceptNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptValidHeader | AcceptNoHeader: ... + + @overload + def __radd__(self, other: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... + @overload + def __radd__(self, other: AcceptInvalidHeader | AcceptNoHeader | None) -> AcceptNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptHeader + | SupportsItems[str, float | tuple[float, str]] + | _ListOrTuple[str | tuple[str, float, str] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptValidHeader | AcceptNoHeader: ... + +@overload +def create_accept_header(header_value: AcceptValidHeader | Literal[""]) -> AcceptValidHeader: ... +@overload +def create_accept_header(header_value: AcceptInvalidHeader) -> AcceptInvalidHeader: ... +@overload +def create_accept_header(header_value: None | AcceptNoHeader) -> AcceptNoHeader: ... +@overload +def create_accept_header(header_value: str) -> AcceptValidHeader | AcceptInvalidHeader: ... +@overload +def create_accept_header(header_value: _AnyAcceptHeader | str | None) -> _AnyAcceptHeader: ... + +def accept_property() -> _AcceptProperty: ... + +class AcceptCharset: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptCharsetValidHeader(AcceptCharset): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptCharsetInvalidOrNoHeader(AcceptCharset): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def acceptable_offers(self, offers: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptCharsetNoHeader(_AcceptCharsetInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __add__(self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptCharsetValidHeader: ... + + @overload + def __radd__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __radd__(self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptCharsetValidHeader: ... + +class AcceptCharsetInvalidHeader(_AcceptCharsetInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __add__( + self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None + ) -> AcceptCharsetNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptCharsetValidHeader | AcceptCharsetNoHeader: ... + + @overload + def __radd__(self, other: AcceptCharsetValidHeader) -> AcceptCharsetValidHeader: ... + @overload + def __radd__( + self, other: AcceptCharsetInvalidHeader | AcceptCharsetNoHeader | Literal[""] | None + ) -> AcceptCharsetNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptCharsetHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptCharsetValidHeader | AcceptCharsetNoHeader: ... + +@overload +def create_accept_charset_header(header_value: AcceptCharsetValidHeader | Literal[""]) -> AcceptCharsetValidHeader: ... +@overload +def create_accept_charset_header(header_value: AcceptCharsetInvalidHeader) -> AcceptCharsetInvalidHeader: ... +@overload +def create_accept_charset_header(header_value: AcceptCharsetNoHeader | None) -> AcceptCharsetNoHeader: ... +@overload +def create_accept_charset_header(header_value: str) -> AcceptCharsetValidHeader | AcceptCharsetInvalidHeader: ... +@overload +def create_accept_charset_header(header_value: _AnyAcceptCharsetHeader | str | None) -> _AnyAcceptCharsetHeader: ... + +def accept_charset_property() -> _AcceptCharsetProperty: ... + +class AcceptEncoding: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptEncodingValidHeader(AcceptEncoding): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def acceptable_offers(self, offers: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptEncodingInvalidOrNoHeader(AcceptEncoding): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def acceptable_offers(self, offers: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptEncodingNoHeader(_AcceptEncodingInvalidOrNoHeader): + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + def __init__(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __add__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptEncodingValidHeader: ... + + @overload + def __radd__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __radd__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptEncodingValidHeader: ... + +class AcceptEncodingInvalidHeader(_AcceptEncodingInvalidOrNoHeader): + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + + @overload + def __add__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __add__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptEncodingValidHeader | AcceptEncodingNoHeader: ... + + @overload + def __radd__(self, other: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... + @overload + def __radd__(self, other: AcceptEncodingInvalidHeader | AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptEncodingHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptEncodingValidHeader | AcceptEncodingNoHeader: ... + +@overload +def create_accept_encoding_header(header_value: AcceptEncodingValidHeader | Literal[""]) -> AcceptEncodingValidHeader: ... +@overload +def create_accept_encoding_header(header_value: AcceptEncodingInvalidHeader) -> AcceptEncodingInvalidHeader: ... +@overload +def create_accept_encoding_header(header_value: AcceptEncodingNoHeader | None) -> AcceptEncodingNoHeader: ... +@overload +def create_accept_encoding_header(header_value: str) -> AcceptEncodingValidHeader | AcceptEncodingInvalidHeader: ... +@overload +def create_accept_encoding_header(header_value: _AnyAcceptEncodingHeader | str | None) -> _AnyAcceptEncodingHeader: ... + +def accept_encoding_property() -> _AcceptEncodingProperty: ... + +class AcceptLanguage: + @classmethod + def parse(cls, value: str) -> Iterator[tuple[str, float]]: ... + +class AcceptLanguageValidHeader(AcceptLanguage): + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> list[tuple[str, float]]: ... + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def __bool__(self) -> Literal[True]: ... + def __contains__(self, offer: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self: ... + def basic_filtering(self, language_tags: Sequence[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: str, default: None = None + ) -> str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], *, default_range: str | None = None, default_tag: str, default: None = None + ) -> str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: None, default: _T | Callable[[], _T] + ) -> _T | str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], default_range: str | None, default_tag: str, default: _T | Callable[[], _T] + ) -> _T | str: ... + @overload + def lookup( + self, + language_tags: Sequence[str], + *, + default_range: str | None = None, + default_tag: None = None, + default: _T | Callable[[], _T], + ) -> _T | str | None: ... + @overload + def lookup( + self, language_tags: Sequence[str], *, default_range: str | None = None, default_tag: str, default: _T | Callable[[], _T] + ) -> _T | str: ... + + def quality(self, offer: str) -> float | None: ... + +class _AcceptLanguageInvalidOrNoHeader(AcceptLanguage): + def __bool__(self) -> Literal[False]: ... + def __contains__(self, offer: str) -> Literal[True]: ... + def __iter__(self) -> Iterator[str]: ... + def basic_filtering(self, language_tags: Iterable[str]) -> list[tuple[str, float]]: ... + + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: None = None) -> str | None: ... + @overload + def best_match(self, offers: Iterable[str | tuple[str, float] | list[Any]], default_match: str) -> str: ... + + @overload + def lookup(self, language_tags: object, default_range: object, default_tag: str, default: object = None) -> str: ... + @overload + def lookup( + self, language_tags: object = None, *, default_range: object = None, default_tag: str, default: object = None + ) -> str: ... + @overload + def lookup(self, language_tags: object, default_range: object, default_tag: None, default: _T | Callable[[], _T]) -> _T: ... + @overload + def lookup( + self, + language_tags: object = None, + *, + default_range: object = None, + default_tag: None = None, + default: _T | Callable[[], _T], + ) -> _T: ... + + def quality(self, offer: str) -> float | None: ... + +class AcceptLanguageNoHeader(_AcceptLanguageInvalidOrNoHeader): + def __init__(self) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> None: ... + @property + def parsed(self) -> None: ... + + @overload + def __add__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __add__(self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None) -> Self: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptLanguageValidHeader: ... + + @overload + def __radd__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __radd__(self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None) -> Self: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> Self | AcceptLanguageValidHeader: ... + +class AcceptLanguageInvalidHeader(_AcceptLanguageInvalidOrNoHeader): + def __init__(self, header_value: str) -> None: ... + def copy(self) -> Self: ... + @property + def header_value(self) -> str: ... + @property + def parsed(self) -> None: ... + + @overload + def __add__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __add__( + self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None + ) -> AcceptLanguageNoHeader: ... + @overload + def __add__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptLanguageValidHeader | AcceptLanguageNoHeader: ... + + @overload + def __radd__(self, other: AcceptLanguageValidHeader) -> AcceptLanguageValidHeader: ... + @overload + def __radd__( + self, other: AcceptLanguageInvalidHeader | AcceptLanguageNoHeader | Literal[""] | None + ) -> AcceptLanguageNoHeader: ... + @overload + def __radd__( + self, + other: ( + _AnyAcceptLanguageHeader + | SupportsItems[str, float] + | _ListOrTuple[str | tuple[str, float] | list[Any]] + | _SupportsStr + | str + | None + ), + ) -> AcceptLanguageValidHeader | AcceptLanguageNoHeader: ... + +@overload +def create_accept_language_header(header_value: AcceptLanguageValidHeader | Literal[""]) -> AcceptLanguageValidHeader: ... +@overload +def create_accept_language_header(header_value: AcceptLanguageNoHeader | None) -> AcceptLanguageNoHeader: ... +@overload +def create_accept_language_header(header_value: AcceptLanguageInvalidHeader) -> AcceptLanguageInvalidHeader: ... +@overload +def create_accept_language_header(header_value: str) -> AcceptLanguageValidHeader | AcceptLanguageInvalidHeader: ... +@overload +def create_accept_language_header(header_value: _AnyAcceptLanguageHeader | str | None) -> _AnyAcceptLanguageHeader: ... + +def accept_language_property() -> _AcceptLanguageProperty: ... diff --git a/stubs/WebOb/webob/byterange.pyi b/stubs/WebOb/webob/byterange.pyi new file mode 100644 index 000000000000..6ce07a14c4ae --- /dev/null +++ b/stubs/WebOb/webob/byterange.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterator +from typing import overload +from typing_extensions import Self + +__all__ = ["Range", "ContentRange"] + +class Range: + start: int | None + end: int | None + + @overload + def __init__(self, start: None, end: None) -> None: ... + @overload + def __init__(self, start: int, end: int | None) -> None: ... + + def range_for_length(self, length: int | None) -> tuple[int, int] | None: ... + def content_range(self, length: int | None) -> ContentRange | None: ... + def __iter__(self) -> Iterator[int | None]: ... + @classmethod + def parse(cls, header: str | None) -> Self | None: ... + +class ContentRange: + start: int | None + stop: int | None + length: int | None + + @overload + def __init__(self, start: None, stop: None, length: int | None) -> None: ... + @overload + def __init__(self, start: int, stop: int, length: int | None) -> None: ... + + def __iter__(self) -> Iterator[int | None]: ... + @classmethod + def parse(cls, value: str | None) -> Self | None: ... diff --git a/stubs/WebOb/webob/cachecontrol.pyi b/stubs/WebOb/webob/cachecontrol.pyi new file mode 100644 index 000000000000..d86d481d1b6f --- /dev/null +++ b/stubs/WebOb/webob/cachecontrol.pyi @@ -0,0 +1,108 @@ +import builtins +from _typeshed import SupportsItems +from collections.abc import Callable +from typing import Any, Generic, Literal, overload +from typing_extensions import Self, TypeVar + +_T = TypeVar("_T") +_DefaultT = TypeVar("_DefaultT", default=None) +_NoneLiteral = TypeVar("_NoneLiteral", default=None) +_ScopeT = TypeVar("_ScopeT", Literal["request"], Literal["response"], None, default=None) +_ScopeT2 = TypeVar("_ScopeT2", Literal["request"], Literal["response"], None) + +class UpdateDict(dict[str, Any]): + updated: Callable[..., Any] | None + updated_args: tuple[Any, ...] | None + +class exists_property(Generic[_ScopeT]): + @overload + def __init__(self: exists_property[None], prop: str) -> None: ... + @overload + def __init__(self, prop: str, type: _ScopeT) -> None: ... + + @overload + def __get__(self, obj: None, type: type[CacheControl[Any]] | None = None) -> Self: ... + @overload + def __get__(self: exists_property[None], obj: CacheControl[Any], type: type[CacheControl[Any]] | None = None) -> bool: ... + @overload + def __get__(self, obj: CacheControl[_ScopeT], type: type[CacheControl[Any]] | None = None) -> bool: ... + + @overload + def __set__(self: exists_property[None], obj: CacheControl[Any], value: bool | None) -> None: ... + @overload + def __set__(self, obj: CacheControl[_ScopeT], value: bool | None) -> None: ... + + @overload + def __delete__(self, obj: CacheControl[Any]) -> None: ... + @overload + def __delete__(self, obj: CacheControl[_ScopeT]) -> None: ... + +class value_property(Generic[_T, _DefaultT, _NoneLiteral, _ScopeT]): + def __init__(self, prop: str, default: _DefaultT = None, none: _NoneLiteral = None, type: _ScopeT = None) -> None: ... # type: ignore[assignment] # ty:ignore[invalid-parameter-default] + + @overload + def __get__(self, obj: None, type: type[CacheControl[Any]] | None = None) -> Self: ... + @overload + def __get__( + self: value_property[_T, _DefaultT, _NoneLiteral, None], + obj: CacheControl[Any] | None, + type: type[CacheControl[Any]] | None = None, + ) -> _T | _DefaultT | _NoneLiteral: ... + @overload + def __get__( + self, obj: CacheControl[_ScopeT] | None, type: type[CacheControl[Any]] | None = None + ) -> _T | _DefaultT | _NoneLiteral: ... + + @overload + def __set__( + self: value_property[_T, _DefaultT, _NoneLiteral, None], + obj: CacheControl[Any], + value: _T | _DefaultT | Literal[True] | None, + ) -> None: ... + @overload + def __set__(self, obj: CacheControl[_ScopeT], value: _T | _DefaultT | Literal[True] | None) -> None: ... + + @overload + def __delete__(self, obj: CacheControl[Any]) -> None: ... + @overload + def __delete__(self, obj: CacheControl[_ScopeT]) -> None: ... + +class CacheControl(Generic[_ScopeT]): + header_value: str + update_dict: builtins.type[UpdateDict] + properties: dict[str, Any] + type: _ScopeT + def __init__(self, properties: dict[str, Any], type: _ScopeT) -> None: ... + + @overload + @classmethod + def parse( + cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None = None, type: None = None + ) -> CacheControl[None]: ... + @overload + @classmethod + def parse(cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None, type: _ScopeT2) -> CacheControl[_ScopeT2]: ... + @overload + @classmethod + def parse( + cls, header: str, updates_to: Callable[[dict[str, Any]], Any] | None = None, *, type: _ScopeT2 + ) -> CacheControl[_ScopeT2]: ... + + max_stale: value_property[int, None, Literal["*"], Literal["request"]] + min_fresh: value_property[int, None, None, Literal["request"]] + only_if_cached: exists_property[Literal["request"]] + public: exists_property[Literal["response"]] + private: value_property[str, None, Literal["*"], Literal["response"]] + no_cache: value_property[str, None, Literal["*"], None] + no_store: exists_property[None] + no_transform: exists_property[None] + must_revalidate: exists_property[Literal["response"]] + proxy_revalidate: exists_property[Literal["response"]] + max_age: value_property[int, None, Literal[-1], None] + s_maxage: value_property[int, None, None, Literal["response"]] + s_max_age = s_maxage # pyrefly: ignore [unknown-name] + stale_while_revalidate: value_property[int, None, None, Literal["response"]] + stale_if_error: value_property[int, None, None, Literal["response"]] + def copy(self) -> Self: ... + +def serialize_cache_control(properties: SupportsItems[str, Any] | CacheControl[Any]) -> str: ... diff --git a/stubs/WebOb/webob/client.pyi b/stubs/WebOb/webob/client.pyi new file mode 100644 index 000000000000..cdabe6fd5379 --- /dev/null +++ b/stubs/WebOb/webob/client.pyi @@ -0,0 +1,14 @@ +from _typeshed.wsgi import StartResponse, WSGIEnvironment +from collections.abc import Iterable +from http.client import HTTPConnection, HTTPMessage, HTTPSConnection +from typing import ClassVar + +__all__ = ["send_request_app", "SendRequest"] + +class SendRequest: + def __init__(self, HTTPConnection: type[HTTPConnection] = ..., HTTPSConnection: type[HTTPSConnection] = ...) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + filtered_headers: ClassVar[tuple[str, ...]] + def parse_headers(self, message: HTTPMessage) -> list[tuple[str, str]]: ... + +send_request_app: SendRequest diff --git a/stubs/WebOb/webob/compat.pyi b/stubs/WebOb/webob/compat.pyi new file mode 100644 index 000000000000..66e384c55329 --- /dev/null +++ b/stubs/WebOb/webob/compat.pyi @@ -0,0 +1,24 @@ +import sys +from html import escape as escape +from io import FileIO, TextIOWrapper +from queue import Empty as Empty, Queue as Queue +from typing import IO + +if sys.version_info >= (3, 13): + # NOTE: These are the only attributes we realistically care about + class cgi_FieldStorage: + filename: str + file: IO[bytes] + def make_file(self) -> TextIOWrapper | FileIO: ... + + def parse_header(line: str) -> tuple[str, dict[str, str]]: ... + +else: + from cgi import FieldStorage as _cgi_FieldStorage, parse_header as parse_header + + class cgi_FieldStorage(_cgi_FieldStorage): + # NOTE: The only kinds of objects of this type the user is exposed to + # will contain a file with a filename. We're technically lying + # if people create their own instances, but that shouldn't happen + filename: str + file: IO[bytes] diff --git a/stubs/WebOb/webob/cookies.pyi b/stubs/WebOb/webob/cookies.pyi new file mode 100644 index 000000000000..3bda178fc43f --- /dev/null +++ b/stubs/WebOb/webob/cookies.pyi @@ -0,0 +1,196 @@ +from _typeshed import sentinel +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Collection, ItemsView, Iterator, KeysView, MutableMapping, ValuesView +from datetime import date, datetime, timedelta +from time import _TimeTuple, struct_time +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from webob._types import AsymmetricProperty +from webob.request import BaseRequest +from webob.response import Response + +__all__ = [ + "Cookie", + "CookieProfile", + "SignedCookieProfile", + "SignedSerializer", + "JSONSerializer", + "Base64Serializer", + "make_cookie", +] + +_T = TypeVar("_T") +# we accept both the official spelling and the one used in the WebOb docs +# the implementation compares after lower() so technically there are more +# valid spellings, but it seems more natural to support these two spellings +_SameSitePolicy: TypeAlias = Literal["Strict", "Lax", "None", "strict", "lax", "none"] + +@type_check_only +class _Serializer(Protocol): + def dumps(self, appstruct: Any, /) -> bytes: ... + def loads(self, bstruct: bytes, /) -> Any: ... + +class RequestCookies(MutableMapping[str, str]): + def __init__(self, environ: WSGIEnvironment) -> None: ... + def __setitem__(self, name: str, value: str) -> None: ... + def __getitem__(self, name: str) -> str: ... + + @overload + def get(self, name: str, default: None = None) -> str | None: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: _T) -> str | _T: ... + + def __delitem__(self, name: str) -> None: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[str]: ... + def items(self) -> ItemsView[str, str]: ... + def __contains__(self, name: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def clear(self) -> None: ... + +class Cookie(dict[bytes, Morsel]): + def __init__(self, input: str | None = None) -> None: ... + def load(self, data: str) -> None: ... + def add(self, key: str | bytes, val: str | bytes) -> Morsel | dict[bytes, bytes]: ... + def __setitem__(self, key: str | bytes, val: str | bytes) -> Morsel | dict[bytes, bytes]: ... # type: ignore[override] + def serialize(self, full: bool = True) -> str: ... + def values(self) -> list[Morsel]: ... # type: ignore[override] + def __str__(self, full: bool = True) -> str: ... + +class Morsel(dict[bytes, bytes | bool | None]): + __slots__ = ("name", "value") + name: bytes + value: bytes + def __init__(self, name: str | bytes, value: str | bytes) -> None: ... + + @property + def path(self) -> bytes | None: ... + @path.setter + def path(self, v: bytes | None) -> None: ... + + @property + def domain(self) -> bytes | None: ... + @domain.setter + def domain(self, v: bytes | None) -> None: ... + + @property + def comment(self) -> bytes | None: ... + @comment.setter + def comment(self, v: bytes | None) -> None: ... + + expires: AsymmetricProperty[bytes | None, datetime | date | timedelta | _TimeTuple | struct_time | int | str | bytes | None] + max_age: AsymmetricProperty[bytes | None, timedelta | int | str | bytes | None] + httponly: AsymmetricProperty[bool, bool | None] + secure: AsymmetricProperty[bool, bool | None] + samesite: AsymmetricProperty[bytes, _SameSitePolicy | bytes] + def __setitem__(self, k: str | bytes, v: bytes | bool | None) -> None: ... + def serialize(self, full: bool = True) -> str: ... + def __str__(self, full: bool = True) -> str: ... + +def make_cookie( + name: str | bytes, + value: str | bytes | None, + max_age: int | timedelta | None = None, + path: str = "/", + domain: str | None = None, + secure: bool | None = False, + httponly: bool | None = False, + comment: str | None = None, + samesite: _SameSitePolicy | None = None, +) -> str: ... + +class JSONSerializer: + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes | str) -> Any: ... + +class Base64Serializer: + serializer: _Serializer + def __init__(self, serializer: _Serializer | None = None) -> None: ... + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes) -> Any: ... + +class SignedSerializer: + salt: str | bytes + secret: str | bytes + hashalg: str + salted_secret: bytes + digest_size: int + serializer: _Serializer + def __init__( + self, secret: str | bytes, salt: str | bytes, hashalg: str = "sha512", serializer: _Serializer | None = None + ) -> None: ... + def dumps(self, appstruct: Any) -> bytes: ... + def loads(self, bstruct: bytes) -> Any: ... + +class CookieProfile: + cookie_name: str + secure: bool + max_age: int | timedelta | None + httponly: bool | None + samesite: _SameSitePolicy | None + path: str + domains: Collection[str] | None + serializer: _Serializer + request: BaseRequest | None + def __init__( + self, + cookie_name: str, + secure: bool = False, + max_age: int | timedelta | None = None, + httponly: bool | None = None, + samesite: _SameSitePolicy | None = None, + path: str = "/", + # even though the docs claim any iterable is fine, that is + # clearly not the case judging by the implementation + domains: Collection[str] | None = None, + serializer: _Serializer | None = None, + ) -> None: ... + def __call__(self, request: BaseRequest) -> CookieProfile: ... + def bind(self, request: BaseRequest) -> CookieProfile: ... + def get_value(self) -> Any | None: ... + def set_cookies( + self, + response: Response, + value: Any, + domains: Collection[str] = sentinel, + max_age: int | timedelta | None = sentinel, + path: str = sentinel, + secure: bool = sentinel, + httponly: bool = sentinel, + samesite: _SameSitePolicy | None = sentinel, + ) -> Response: ... + def get_headers( + self, + value: Any, + domains: Collection[str] = sentinel, + max_age: int | timedelta | None = sentinel, + path: str = sentinel, + secure: bool = sentinel, + httponly: bool = sentinel, + samesite: _SameSitePolicy | None = sentinel, + ) -> list[tuple[str, str]]: ... + +class SignedCookieProfile(CookieProfile): + secret: str | bytes + salt: str | bytes + hashalg: str + original_serializer: _Serializer + def __init__( + self, + secret: str, + salt: str, + cookie_name: str, + secure: bool = False, + max_age: int | timedelta | None = None, + httponly: bool | None = False, + samesite: _SameSitePolicy | None = None, + path: str = "/", + domains: Collection[str] | None = None, + hashalg: str = "sha512", + serializer: _Serializer | None = None, + ) -> None: ... + def __call__(self, request: BaseRequest) -> SignedCookieProfile: ... + def bind(self, request: BaseRequest) -> SignedCookieProfile: ... diff --git a/stubs/WebOb/webob/datetime_utils.pyi b/stubs/WebOb/webob/datetime_utils.pyi new file mode 100644 index 000000000000..68c45d2f12db --- /dev/null +++ b/stubs/WebOb/webob/datetime_utils.pyi @@ -0,0 +1,40 @@ +from datetime import date, datetime, timedelta, tzinfo +from time import _TimeTuple, struct_time + +__all__ = [ + "UTC", + "timedelta_to_seconds", + "year", + "month", + "week", + "day", + "hour", + "minute", + "second", + "parse_date", + "serialize_date", + "parse_date_delta", + "serialize_date_delta", +] + +class _UTC(tzinfo): + def dst(self, dt: datetime | None) -> timedelta: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def tzname(self, dt: datetime | None) -> str: ... + +UTC: _UTC + +def timedelta_to_seconds(td: timedelta) -> int: ... + +day: timedelta +week: timedelta +hour: timedelta +minute: timedelta +second: timedelta +month: timedelta +year: timedelta + +def parse_date(value: str | bytes | None) -> datetime | None: ... +def serialize_date(dt: datetime | date | timedelta | _TimeTuple | struct_time | float | str | bytes) -> str: ... +def parse_date_delta(value: str | bytes | None) -> datetime | None: ... +def serialize_date_delta(value: datetime | date | timedelta | _TimeTuple | struct_time | float | str | bytes) -> str: ... diff --git a/stubs/WebOb/webob/dec.pyi b/stubs/WebOb/webob/dec.pyi new file mode 100644 index 000000000000..b8f58a6906e7 --- /dev/null +++ b/stubs/WebOb/webob/dec.pyi @@ -0,0 +1,204 @@ +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Concatenate, Generic, ParamSpec, TypeAlias, overload, type_check_only +from typing_extensions import Never, Self, TypeVar + +from webob.request import BaseRequest, Request +from webob.response import Response + +__all__ = ["wsgify"] + +_AnyResponse: TypeAlias = Response | WSGIApplication | str | None +_S = TypeVar("_S") +_AppT = TypeVar("_AppT", bound=WSGIApplication) +_AppT_contra = TypeVar("_AppT_contra", bound=WSGIApplication, contravariant=True) +_RequestT = TypeVar("_RequestT", bound=BaseRequest) +_RequestT_contra = TypeVar("_RequestT_contra", bound=BaseRequest, default=Request, contravariant=True) +_P = ParamSpec("_P") +_P2 = ParamSpec("_P2") + +_RequestHandlerCallable: TypeAlias = Callable[Concatenate[_RequestT, _P], _AnyResponse] +_RequestHandlerMethod: TypeAlias = Callable[Concatenate[Any, _RequestT, _P], _AnyResponse] +_MiddlewareCallable: TypeAlias = Callable[Concatenate[_RequestT, _AppT, _P], _AnyResponse] +_MiddlewareMethod: TypeAlias = Callable[Concatenate[Any, _RequestT, _AppT, _P], _AnyResponse] +_RequestHandler: TypeAlias = _RequestHandlerCallable[_RequestT, _P] | _RequestHandlerMethod[_RequestT, _P] +_Middleware: TypeAlias = _MiddlewareCallable[_RequestT, _AppT, _P] | _MiddlewareMethod[_RequestT, _AppT, _P] + +class wsgify(Generic[_P, _RequestT_contra]): + RequestClass: type[_RequestT_contra] + func: _RequestHandler[_RequestT_contra, _P] | None + args: tuple[Any, ...] + kwargs: dict[str, Any] + middleware_wraps: WSGIApplication | None + + # NOTE: We disallow passing args/kwargs using this direct API, because + # we can't really make it work as a decorator this way, these + # arguments should only really be used indirectly through the + # middleware decorator, where we can be more type safe + @overload + def __init__( + self: wsgify[[], Request], + func: _RequestHandler[Request, []] | None = None, + RequestClass: None = None, + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _RequestHandler[_RequestT_contra, []] | None, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _RequestHandler[_RequestT_contra, []] | None = None, + *, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: None = None, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], Request], + func: _Middleware[Request, _AppT_contra, []] | None = None, + RequestClass: None = None, + args: tuple[()] = (), + kwargs: None = None, + *, + middleware_wraps: _AppT_contra, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _Middleware[_RequestT_contra, _AppT_contra, []] | None, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + *, + middleware_wraps: _AppT_contra, + ) -> None: ... + @overload + def __init__( + self: wsgify[[_AppT_contra], _RequestT_contra], # pyright: ignore[reportInvalidTypeVarUse] #11780 + func: _Middleware[_RequestT_contra, _AppT_contra, []] | None = None, + *, + RequestClass: type[_RequestT_contra], + args: tuple[()] = (), + kwargs: None = None, + middleware_wraps: _AppT_contra, + ) -> None: ... + + @overload + def __get__(self, obj: None, type: type[_S]) -> _unbound_wsgify[_P, _S, _RequestT_contra]: ... + @overload + def __get__(self, obj: object, type: type | None = None) -> Self: ... + + @overload + def __call__(self, env: WSGIEnvironment, /, start_response: StartResponse) -> Iterable[bytes]: ... + @overload + def __call__(self, func: _RequestHandler[_RequestT_contra, _P], /) -> Self: ... + @overload + def __call__(self, req: _RequestT_contra) -> _AnyResponse: ... + @overload + def __call__(self, req: _RequestT_contra, *args: _P.args, **kw: _P.kwargs) -> _AnyResponse: ... + + def get(self, url: str, **kw: Any) -> _AnyResponse: ... + def post( + self, url: str, POST: str | bytes | Mapping[Any, Any] | Mapping[Any, list[Any] | tuple[Any, ...]] | None = None, **kw: Any + ) -> _AnyResponse: ... + def request(self, url: str, **kw: Any) -> _AnyResponse: ... + def call_func(self, req: _RequestT_contra, *args: _P.args, **kwargs: _P.kwargs) -> _AnyResponse: ... + # technically this could bind different type vars, but we disallow it for safety + def clone(self, func: _RequestHandler[_RequestT_contra, _P] | None = None, **kw: Never) -> Self: ... + @property + def undecorated(self) -> _RequestHandler[_RequestT_contra, _P] | None: ... + + @overload + @classmethod + def middleware( + cls, middle_func: None = None, app: None | _AppT = None, *_: _P.args, **kw: _P.kwargs + ) -> _UnboundMiddleware[_P, _AppT, Any]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareCallable[_RequestT, _AppT, _P2], app: None = None + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: None = None + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: None = None, *_: _P2.args, **kw: _P2.kwargs + ) -> _MiddlewareFactory[_P2, _AppT, _RequestT]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: _AppT + ) -> type[wsgify[Concatenate[_AppT, _P2], _RequestT]]: ... + @overload + @classmethod + def middleware( + cls, middle_func: _MiddlewareMethod[_RequestT, _AppT, _P2], app: _AppT, *_: _P2.args, **kw: _P2.kwargs + ) -> type[wsgify[Concatenate[_AppT, _P2], _RequestT]]: ... + +@type_check_only +class _unbound_wsgify(wsgify[_P, _RequestT_contra], Generic[_P, _S, _RequestT_contra]): + @overload # type: ignore[override] + def __call__(self, __self: _S, env: WSGIEnvironment, /, start_response: StartResponse) -> Iterable[bytes]: ... + @overload + def __call__(self, __self: _S, func: _RequestHandler[_RequestT_contra, _P], /) -> Self: ... + @overload + def __call__(self, __self: _S, /, req: _RequestT_contra) -> _AnyResponse: ... + @overload + def __call__(self, __self: _S, /, req: _RequestT_contra, *args: _P.args, **kw: _P.kwargs) -> _AnyResponse: ... + +class _UnboundMiddleware(Generic[_P, _AppT_contra, _RequestT_contra]): + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]] + app: _AppT_contra | None + kw: dict[str, Any] + def __init__( + self, + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]], + app: _AppT_contra | None, + kw: dict[str, Any], + ) -> None: ... + + @overload + def __call__(self, func: None, app: _AppT_contra | None = None) -> Self: ... + @overload + def __call__( + self, func: _Middleware[_RequestT_contra, _AppT_contra, _P], app: None = None + ) -> wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]: ... + @overload + def __call__( + self, func: _Middleware[_RequestT_contra, _AppT_contra, _P], app: _AppT_contra + ) -> wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]: ... + +class _MiddlewareFactory(Generic[_P, _AppT_contra, _RequestT_contra]): + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]] + middleware: _Middleware[_RequestT_contra, _AppT_contra, _P] + kw: dict[str, Any] + def __init__( + self, + wrapper_class: type[wsgify[Concatenate[_AppT_contra, _P], _RequestT_contra]], + middleware: _Middleware[_RequestT_contra, _AppT_contra, _P], + kw: dict[str, Any], + ) -> None: ... + + # NOTE: Technically you are not allowed to pass args, but we give up all kinds + # of other safety if we don't use ParamSpec + @overload + def __call__( + self, app: None = None, *_: _P.args, **config: _P.kwargs + ) -> _MiddlewareFactory[[], _AppT_contra, _RequestT_contra]: ... + @overload + def __call__(self, app: _AppT_contra, *_: _P.args, **config: _P.kwargs) -> wsgify[[_AppT_contra], _RequestT_contra]: ... diff --git a/stubs/WebOb/webob/descriptors.pyi b/stubs/WebOb/webob/descriptors.pyi new file mode 100644 index 000000000000..0cc3bfc51cff --- /dev/null +++ b/stubs/WebOb/webob/descriptors.pyi @@ -0,0 +1,100 @@ +from collections.abc import Callable, Iterable +from datetime import date, datetime, timedelta +from time import _TimeTuple, struct_time +from typing import Any, NamedTuple, TypeAlias, TypeVar, overload + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.byterange import ContentRange, Range +from webob.etag import IfRange, IfRangeDate + +_DefaultT = TypeVar("_DefaultT") +_GetterReturnType = TypeVar("_GetterReturnType") +_SetterValueType = TypeVar("_SetterValueType") +_ConvertedGetterReturnType = TypeVar("_ConvertedGetterReturnType") +_ConvertedSetterValueType = TypeVar("_ConvertedSetterValueType") +_DescriptorT = TypeVar("_DescriptorT", bound=AsymmetricPropertyWithDelete[Any, Any]) + +_StringProperty: TypeAlias = SymmetricPropertyWithDelete[str | None] +_ListProperty: TypeAlias = AsymmetricPropertyWithDelete[tuple[str, ...] | None, Iterable[str] | str | None] +_DateProperty: TypeAlias = AsymmetricPropertyWithDelete[ + datetime | None, date | datetime | timedelta | _TimeTuple | struct_time | float | str | None +] +_ContentRangeParams: TypeAlias = ( + ContentRange + | list[int] + | list[None] + | list[int | None] + | tuple[int, int] + | tuple[None, None] + | tuple[int, int, int | None] + | tuple[None, None, int | None] + | str + | None +) + +@overload +def environ_getter(key: str, *, rfc_section: str | None = None) -> SymmetricProperty[Any]: ... +@overload +def environ_getter(key: str, default: None, rfc_section: str | None = None) -> SymmetricPropertyWithDelete[Any | None]: ... +@overload +def environ_getter( + key: str, default: _DefaultT, rfc_section: str | None = None +) -> AsymmetricPropertyWithDelete[Any | _DefaultT, Any | _DefaultT | None]: ... + +@overload +def environ_decoder(key: str, *, rfc_section: str | None = None, encattr: str | None = None) -> SymmetricProperty[str]: ... +@overload +def environ_decoder( + key: str, default: str, rfc_section: str | None = None, encattr: str | None = None +) -> AsymmetricPropertyWithDelete[str, str | None]: ... +@overload +def environ_decoder( + key: str, default: None, rfc_section: str | None = None, encattr: str | None = None +) -> SymmetricPropertyWithDelete[str | None]: ... + +def upath_property(key: str) -> SymmetricProperty[str]: ... +def deprecated_property(attr: _DescriptorT, name: str, text: str, version: str) -> _DescriptorT: ... +def header_getter(header: str, rfc_section: str) -> _StringProperty: ... + +@overload +def converter( + prop: AsymmetricPropertyWithDelete[_GetterReturnType, _SetterValueType], + parse: Callable[[_GetterReturnType], _ConvertedGetterReturnType], + serialize: Callable[[_ConvertedSetterValueType], _SetterValueType], + convert_name: str | None = None, +) -> AsymmetricPropertyWithDelete[_ConvertedGetterReturnType, _ConvertedSetterValueType | None]: ... +@overload +def converter( + prop: AsymmetricProperty[_GetterReturnType, _SetterValueType], + parse: Callable[[_GetterReturnType], _ConvertedGetterReturnType], + serialize: Callable[[_ConvertedSetterValueType], _SetterValueType], + convert_name: str | None = None, +) -> AsymmetricProperty[_ConvertedGetterReturnType, _ConvertedSetterValueType | None]: ... + +def list_header(header: str, rfc_section: str) -> _ListProperty: ... +def parse_list(value: str | None) -> tuple[str, ...] | None: ... +def serialize_list(value: Iterable[str] | str) -> str: ... +def converter_date(prop: _StringProperty) -> _DateProperty: ... +def date_header(header: str, rfc_section: str) -> _DateProperty: ... +def parse_etag_response(value: str | None, strong: bool = False) -> str | None: ... +def serialize_etag_response(value: tuple[str, bool] | str) -> str: ... +def serialize_if_range(value: IfRange | IfRangeDate | datetime | date | str) -> str | None: ... +def parse_range(value: str | None) -> Range | None: ... +def serialize_range(value: tuple[int, int | None] | list[int | None] | list[int] | str | None) -> str | None: ... +def parse_int(value: str | None) -> int | None: ... +def parse_int_safe(value: str | None) -> int | None: ... + +serialize_int: Callable[[int], str] + +def parse_content_range(value: str | None) -> ContentRange | None: ... +def serialize_content_range(value: _ContentRangeParams) -> str | None: ... +def parse_auth_params(params: str) -> dict[str, str]: ... + +known_auth_schemes: dict[str, None] + +class _authorization(NamedTuple): + authtype: str + params: dict[str, str] | str + +def parse_auth(val: str | None) -> _authorization | None: ... +def serialize_auth(val: tuple[str, dict[str, str] | str] | list[Any] | str | None) -> str | None: ... diff --git a/stubs/WebOb/webob/etag.pyi b/stubs/WebOb/webob/etag.pyi new file mode 100644 index 000000000000..f6f5502d55f8 --- /dev/null +++ b/stubs/WebOb/webob/etag.pyi @@ -0,0 +1,45 @@ +from collections.abc import Collection +from datetime import datetime +from typing import Literal, TypeAlias + +from webob._types import AsymmetricPropertyWithDelete +from webob.response import Response + +__all__ = ["AnyETag", "NoETag", "ETagMatcher", "IfRange", "etag_property"] + +_ETag: TypeAlias = _AnyETag | _NoETag | ETagMatcher +_ETagProperty: TypeAlias = AsymmetricPropertyWithDelete[_ETag, _ETag | str | None] + +def etag_property(key: str, default: _ETag, rfc_section: str, strong: bool = True) -> _ETagProperty: ... + +class _AnyETag: + def __bool__(self) -> Literal[False]: ... + def __contains__(self, other: str | None) -> Literal[True]: ... + +AnyETag: _AnyETag + +class _NoETag: + def __bool__(self) -> Literal[False]: ... + def __contains__(self, other: str | None) -> Literal[False]: ... + +NoETag: _NoETag + +class ETagMatcher: + etags: Collection[str] + def __init__(self, etags: Collection[str]) -> None: ... + def __contains__(self, other: str | None) -> bool: ... + @classmethod + def parse(cls, value: str, strong: bool = True) -> ETagMatcher | _AnyETag: ... + +class IfRange: + etag: _ETag + def __init__(self, etag: _ETag) -> None: ... + @classmethod + def parse(cls, value: str | None) -> IfRange | IfRangeDate: ... + def __contains__(self, resp: Response) -> bool: ... + def __bool__(self) -> bool: ... + +class IfRangeDate: + date: datetime + def __init__(self, date: datetime) -> None: ... + def __contains__(self, resp: Response) -> bool: ... diff --git a/stubs/WebOb/webob/exc.pyi b/stubs/WebOb/webob/exc.pyi new file mode 100644 index 000000000000..d1671ef356dc --- /dev/null +++ b/stubs/WebOb/webob/exc.pyi @@ -0,0 +1,190 @@ +from _typeshed import SupportsItems, SupportsKeysAndGetItem +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from string import Template +from typing import Any, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Self + +from webob.response import Response + +__all__ = [ + "HTTPAccepted", + "HTTPBadGateway", + "HTTPBadRequest", + "HTTPClientError", + "HTTPConflict", + "HTTPCreated", + "HTTPError", + "HTTPExpectationFailed", + "HTTPFailedDependency", + "HTTPForbidden", + "HTTPFound", + "HTTPGatewayTimeout", + "HTTPGone", + "HTTPInsufficientStorage", + "HTTPInternalServerError", + "HTTPLengthRequired", + "HTTPLocked", + "HTTPMethodNotAllowed", + "HTTPMovedPermanently", + "HTTPMultipleChoices", + "HTTPNetworkAuthenticationRequired", + "HTTPNoContent", + "HTTPNonAuthoritativeInformation", + "HTTPNotAcceptable", + "HTTPNotFound", + "HTTPNotImplemented", + "HTTPNotModified", + "HTTPOk", + "HTTPPartialContent", + "HTTPPaymentRequired", + "HTTPPermanentRedirect", + "HTTPPreconditionFailed", + "HTTPPreconditionRequired", + "HTTPProxyAuthenticationRequired", + "HTTPRedirection", + "HTTPRequestEntityTooLarge", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPRequestRangeNotSatisfiable", + "HTTPRequestTimeout", + "HTTPRequestURITooLong", + "HTTPResetContent", + "HTTPSeeOther", + "HTTPServerError", + "HTTPServiceUnavailable", + "HTTPTemporaryRedirect", + "HTTPTooManyRequests", + "HTTPUnauthorized", + "HTTPUnavailableForLegalReasons", + "HTTPUnprocessableEntity", + "HTTPUnsupportedMediaType", + "HTTPUseProxy", + "HTTPVersionNotSupported", + "WSGIHTTPException", + "HTTPException", + "HTTPExceptionMiddleware", + "status_map", +] + +_Headers: TypeAlias = SupportsItems[str, str] | SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]] + +@type_check_only +class _JSONFormatter(Protocol): + def __call__(self, *, body: str, status: str, title: str, environ: WSGIEnvironment) -> Any: ... + +class HTTPException(Exception): + wsgi_response: Response + def __init__(self, message: str, wsgi_response: Response) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class WSGIHTTPException(Response, HTTPException): + code: int + title: str + explanation: str + body_template_obj: Template + plain_template_obj: Template + html_template_obj: Template + empty_body: bool + detail: str | None + comment: str | None + def __init__( + self, + detail: str | None = None, + headers: _Headers | None = None, + comment: str | None = None, + body_template: str | None = None, + json_formatter: _JSONFormatter | None = None, + **kw: Any, + ) -> None: ... + def plain_body(self, environ: WSGIEnvironment) -> str: ... + def html_body(self, environ: WSGIEnvironment) -> str: ... + def json_formatter(self, body: str, status: str, title: str, environ: WSGIEnvironment) -> Any: ... + def json_body(self, environ: WSGIEnvironment) -> str: ... # type: ignore[override] + def generate_response(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + @property + def wsgi_response(self) -> Self: ... # type: ignore[override] + def __str__(self) -> str: ... # type: ignore[override] # noqa: Y029 + +class HTTPError(WSGIHTTPException): ... +class HTTPRedirection(WSGIHTTPException): ... +class HTTPOk(WSGIHTTPException): ... +class HTTPCreated(HTTPOk): ... +class HTTPAccepted(HTTPOk): ... +class HTTPNonAuthoritativeInformation(HTTPOk): ... + +class HTTPNoContent(HTTPOk): + empty_body: Literal[True] + +class HTTPResetContent(HTTPOk): + empty_body: Literal[True] + +class HTTPPartialContent(HTTPOk): ... + +class _HTTPMove(HTTPRedirection): + explanation: str + add_slash: bool + def __init__( + self, + detail: str | None = None, + headers: _Headers | None = None, + comment: str | None = None, + body_template: str | None = None, + location: str | None = None, + add_slash: bool = False, + ) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class HTTPMultipleChoices(_HTTPMove): ... +class HTTPMovedPermanently(_HTTPMove): ... +class HTTPFound(_HTTPMove): ... +class HTTPSeeOther(_HTTPMove): ... + +class HTTPNotModified(HTTPRedirection): + empty_body: Literal[True] + +class HTTPUseProxy(_HTTPMove): ... +class HTTPTemporaryRedirect(_HTTPMove): ... +class HTTPPermanentRedirect(_HTTPMove): ... +class HTTPClientError(HTTPError): ... +class HTTPBadRequest(HTTPClientError): ... +class HTTPUnauthorized(HTTPClientError): ... +class HTTPPaymentRequired(HTTPClientError): ... +class HTTPForbidden(HTTPClientError): ... +class HTTPNotFound(HTTPClientError): ... +class HTTPMethodNotAllowed(HTTPClientError): ... +class HTTPNotAcceptable(HTTPClientError): ... +class HTTPProxyAuthenticationRequired(HTTPClientError): ... +class HTTPRequestTimeout(HTTPClientError): ... +class HTTPConflict(HTTPClientError): ... +class HTTPGone(HTTPClientError): ... +class HTTPLengthRequired(HTTPClientError): ... +class HTTPPreconditionFailed(HTTPClientError): ... +class HTTPRequestEntityTooLarge(HTTPClientError): ... +class HTTPRequestURITooLong(HTTPClientError): ... +class HTTPUnsupportedMediaType(HTTPClientError): ... +class HTTPRequestRangeNotSatisfiable(HTTPClientError): ... +class HTTPExpectationFailed(HTTPClientError): ... +class HTTPUnprocessableEntity(HTTPClientError): ... +class HTTPLocked(HTTPClientError): ... +class HTTPFailedDependency(HTTPClientError): ... +class HTTPPreconditionRequired(HTTPClientError): ... +class HTTPTooManyRequests(HTTPClientError): ... +class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): ... +class HTTPUnavailableForLegalReasons(HTTPClientError): ... +class HTTPServerError(HTTPError): ... +class HTTPInternalServerError(HTTPServerError): ... +class HTTPNotImplemented(HTTPServerError): ... +class HTTPBadGateway(HTTPServerError): ... +class HTTPServiceUnavailable(HTTPServerError): ... +class HTTPGatewayTimeout(HTTPServerError): ... +class HTTPVersionNotSupported(HTTPServerError): ... +class HTTPInsufficientStorage(HTTPServerError): ... +class HTTPNetworkAuthenticationRequired(HTTPServerError): ... + +class HTTPExceptionMiddleware: + application: WSGIApplication + def __init__(self, application: WSGIApplication) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +status_map: dict[int, type[HTTPOk | HTTPRedirection | HTTPClientError | HTTPServerError]] diff --git a/stubs/WebOb/webob/headers.pyi b/stubs/WebOb/webob/headers.pyi new file mode 100644 index 000000000000..5120b86ad866 --- /dev/null +++ b/stubs/WebOb/webob/headers.pyi @@ -0,0 +1,36 @@ +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Iterator, MutableMapping +from typing import TypeVar, overload + +from webob.multidict import MultiDict + +__all__ = ["ResponseHeaders", "EnvironHeaders"] + +_T = TypeVar("_T") + +class ResponseHeaders(MultiDict[str, str]): + def __getitem__(self, key: str) -> str: ... + def getall(self, key: str) -> list[str]: ... + def mixed(self) -> dict[str, str | list[str]]: ... + def dict_of_lists(self) -> dict[str, list[str]]: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def setdefault(self, key: str, default: str) -> str: ... # type: ignore[override] + + @overload + def pop(self, key: str) -> str: ... + @overload + def pop(self, key: str, default: _T) -> str | _T: ... + +class EnvironHeaders(MutableMapping[str, str]): + environ: WSGIEnvironment + def __init__(self, environ: WSGIEnvironment) -> None: ... + def __getitem__(self, hname: str) -> str: ... + def __setitem__(self, hname: str, value: str) -> None: ... + def __delitem__(self, hname: str) -> None: ... + def keys(self) -> Iterator[str]: ... # type: ignore[override] + def __contains__(self, hname: object) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... diff --git a/stubs/WebOb/webob/multidict.pyi b/stubs/WebOb/webob/multidict.pyi new file mode 100644 index 000000000000..4272d2197564 --- /dev/null +++ b/stubs/WebOb/webob/multidict.pyi @@ -0,0 +1,197 @@ +from _typeshed import SupportsGetItem, SupportsKeysAndGetItem +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Collection, Iterable, Iterator, MutableMapping +from typing import Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob.compat import cgi_FieldStorage, cgi_FieldStorage as _FieldStorageWithFile + +__all__ = ["MultiDict", "NestedMultiDict", "NoVars", "GetDict"] + +_T = TypeVar("_T") +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_KT_co = TypeVar("_KT_co", covariant=True) +_VT_co = TypeVar("_VT_co", covariant=True) + +@type_check_only +class _SupportsItemsWithIterableResult(Protocol[_KT_co, _VT_co]): + def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... + +class MultiDict(MutableMapping[_KT, _VT]): + @overload + def __init__(self) -> None: ... + @overload + def __init__(self: MultiDict[str, _VT], **kwargs: _VT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + @overload + def __init__(self, m: _SupportsItemsWithIterableResult[_KT, _VT], /) -> None: ... + @overload + def __init__( + self: MultiDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + m: _SupportsItemsWithIterableResult[str, _VT], + /, + **kwargs: _VT, + ) -> None: ... + @overload + def __init__(self, m: Iterable[tuple[_KT, _VT]], /) -> None: ... + @overload + def __init__( + self: MultiDict[str, _VT], # pyright: ignore[reportInvalidTypeVarUse] #11780 + m: Iterable[tuple[str, _VT]], + /, + **kwargs: _VT, + ) -> None: ... + + @classmethod + def view_list(cls, lst: list[tuple[_KT, _VT]]) -> Self: ... + @classmethod + def from_fieldstorage(cls, fs: cgi_FieldStorage) -> MultiDict[str, str | _FieldStorageWithFile]: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def add(self, key: _KT, value: _VT) -> None: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _VT | _T: ... + + def getall(self, key: _KT) -> list[_VT]: ... + def getone(self, key: _KT) -> _VT: ... + def mixed(self) -> dict[_KT, _VT | list[_VT]]: ... + def dict_of_lists(self) -> dict[_KT, list[_VT]]: ... + def __delitem__(self, key: _KT) -> None: ... + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def clear(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _VT | _T: ... + + def popitem(self) -> tuple[_KT, _VT]: ... + + @overload # type: ignore[override] + def update(self: SupportsGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def update(self, m: Collection[tuple[_KT, _VT]], /) -> None: ... + @overload + def update(self: SupportsGetItem[str, _VT], m: Collection[tuple[str, _VT]], /, **kwargs: _VT) -> None: ... + + @overload + def extend(self, other: _SupportsItemsWithIterableResult[_KT, _VT]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: _SupportsItemsWithIterableResult[str, _VT], **kwargs: _VT) -> None: ... + @overload + def extend(self, other: Iterable[tuple[_KT, _VT]]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... + @overload + def extend(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def extend(self: MultiDict[str, _VT], other: None = None, **kwargs: _VT) -> None: ... + + def __len__(self) -> int: ... + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + __iter__ = keys + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + +class GetDict(MultiDict[str, str]): + env: WSGIEnvironment + + @overload + def __init__(self, data: _SupportsItemsWithIterableResult[str, str], env: WSGIEnvironment) -> None: ... + @overload + def __init__(self, data: Iterable[tuple[str, str]], env: WSGIEnvironment) -> None: ... + + def on_change(self) -> None: ... + def __setitem__(self, key: str, value: str) -> None: ... + def add(self, key: str, value: str) -> None: ... + def __delitem__(self, key: str) -> None: ... + def clear(self) -> None: ... + def setdefault(self, key: str, default: str) -> str: ... # type: ignore[override] + + @overload + def pop(self, key: str) -> str: ... + @overload + def pop(self, key: str, default: _T) -> str | _T: ... + + def popitem(self) -> tuple[str, str]: ... + + @overload # type: ignore[override] + def update(self, **kwargs: str) -> None: ... + @overload + def update(self, m: Collection[tuple[str, str]], /, **kwargs: str) -> None: ... + + @overload + def extend(self, other: _SupportsItemsWithIterableResult[str, str], **kwargs: str) -> None: ... + @overload + def extend(self, other: Iterable[tuple[str, str]], **kwargs: str) -> None: ... + @overload + def extend(self, other: SupportsKeysAndGetItem[str, str], **kwargs: str) -> None: ... + @overload + def extend(self, other: None = None, **kwargs: str) -> None: ... + + def copy(self) -> MultiDict[str, str]: ... # type: ignore[override] + +class NestedMultiDict(MultiDict[_KT, _VT]): + # FIXME: It would be more accurate to use a Protocol here, which has a + # covariant _VT, instead of MultiDict + dicts: tuple[MultiDict[_KT, _VT], ...] + def __init__(self, *dicts: MultiDict[_KT, _VT]) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + # NOTE: These methods all return exceptions, so this will give us + # somewhat sane type checker errors, we would prefer to use + # something like @type_error here, if it existed. + # This is only really necessary, because the inheritance hierachy + # is a mess. + __setitem__: None # type: ignore[assignment] + add: None # type: ignore[assignment] + __delitem__: None # type: ignore[assignment] + clear: None # type: ignore[assignment] + setdefault: None # type: ignore[assignment] + pop: None # type: ignore[assignment] + popitem: None # type: ignore[assignment] + update: None # type: ignore[assignment] + def getall(self, key: _KT) -> list[_VT]: ... + def copy(self) -> MultiDict[_KT, _VT]: ... # type: ignore[override] + def __contains__(self, key: object) -> bool: ... + has_key = __contains__ + def __len__(self) -> int: ... + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + __iter__ = keys + +class NoVars: + reason: str + def __init__(self, reason: str | None = None) -> None: ... + + @overload + def get(self, key: str, default: None = None) -> None: ... + @overload + def get(self, key: str, default: _T) -> _T: ... + + def getall(self, key: str) -> list[str]: ... + def mixed(self) -> dict[str, str | list[str]]: ... + def dict_of_lists(self) -> dict[str, list[str]]: ... + def __contains__(self, key: object) -> Literal[False]: ... + has_key = __contains__ + def copy(self) -> Self: ... + def __len__(self) -> Literal[0]: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> Iterator[str]: ... + def values(self) -> Iterator[str]: ... + def items(self) -> Iterator[tuple[str, str]]: ... + def __bool__(self) -> Literal[False]: ... diff --git a/stubs/WebOb/webob/request.pyi b/stubs/WebOb/webob/request.pyi new file mode 100644 index 000000000000..e0135b3f1c74 --- /dev/null +++ b/stubs/WebOb/webob/request.pyi @@ -0,0 +1,259 @@ +import datetime +import io +from _typeshed import OptExcInfo, SupportsKeysAndGetItem, SupportsNoArgReadline, SupportsRead, WriteableBuffer +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Mapping +from re import Pattern +from typing import IO, Any, ClassVar, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.acceptparse import _AcceptCharsetProperty, _AcceptEncodingProperty, _AcceptLanguageProperty, _AcceptProperty +from webob.byterange import Range +from webob.cachecontrol import CacheControl +from webob.client import SendRequest +from webob.compat import cgi_FieldStorage +from webob.cookies import RequestCookies +from webob.descriptors import _authorization, _DateProperty +from webob.etag import IfRange, IfRangeDate, _ETagProperty +from webob.headers import EnvironHeaders +from webob.multidict import GetDict, MultiDict, NestedMultiDict, NoVars +from webob.response import Response + +__all__ = ["BaseRequest", "Request", "LegacyRequest"] + +_T = TypeVar("_T") +_HTTPMethod: TypeAlias = Literal["GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"] +_ListOrTuple: TypeAlias = list[_T] | tuple[_T, ...] +_RequestCacheControl: TypeAlias = CacheControl[Literal["request"]] + +@type_check_only +class _SupportsReadAndNoArgReadline(SupportsRead[str | bytes], SupportsNoArgReadline[str | bytes], Protocol): ... + +@type_check_only +class _RequestCacheControlDict(TypedDict, total=False): + max_stale: int + min_stale: int + only_if_cached: bool + no_cache: Literal[True] | str + no_store: bool + no_transform: bool + max_age: int + +_FieldStorageWithFile = cgi_FieldStorage + +class _NoDefault: ... + +NoDefault: _NoDefault + +class BaseRequest: + request_body_tempfile_limit: ClassVar[int] + environ: WSGIEnvironment + def __init__(self, environ: WSGIEnvironment, **kw: Any) -> None: ... + + @overload + def encget(self, key: str, default: _T, encattr: str | None = None) -> str | _T: ... + @overload + def encget(self, key: str, *, encattr: str | None = None) -> str: ... + + def encset(self, key: str, val: str, encattr: str | None = None) -> None: ... + @property + def charset(self) -> str | None: ... + def decode(self, charset: str | None = None, errors: str = "strict") -> Self: ... + + @property + def body_file(self) -> SupportsRead[bytes]: ... + @body_file.setter + def body_file(self, value: SupportsRead[bytes]) -> None: ... + @body_file.deleter + def body_file(self) -> None: ... + + content_length: SymmetricPropertyWithDelete[int | None] + body_file_raw: SymmetricProperty[SupportsRead[bytes]] + is_body_seekable: bool + @property + def body_file_seekable(self) -> IO[bytes]: ... + url_encoding: AsymmetricPropertyWithDelete[str, str | None] + scheme: SymmetricProperty[str] + method: AsymmetricPropertyWithDelete[_HTTPMethod, _HTTPMethod | None] + http_version: SymmetricProperty[str] + remote_user: SymmetricPropertyWithDelete[str | None] + remote_host: SymmetricPropertyWithDelete[str | None] + remote_addr: SymmetricPropertyWithDelete[str | None] + query_string: AsymmetricPropertyWithDelete[str, str | None] + server_name: SymmetricProperty[str] + server_port: SymmetricProperty[int] + script_name: AsymmetricPropertyWithDelete[str, str | None] + path_info: SymmetricProperty[str] + uscript_name = script_name # bw compat # pyrefly: ignore [unknown-name] + upath_info = path_info # bw compat # pyrefly: ignore [unknown-name] + content_type: AsymmetricPropertyWithDelete[str, str | None] + headers: AsymmetricProperty[EnvironHeaders, SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]]] + @property + def client_addr(self) -> str | None: ... + @property + def host_port(self) -> str: ... + @property + def host_url(self) -> str: ... + @property + def application_url(self) -> str: ... + @property + def path_url(self) -> str: ... + @property + def path(self) -> str: ... + @property + def path_qs(self) -> str: ... + @property + def url(self) -> str: ... + def relative_url(self, other_url: str, to_application: bool = False) -> str: ... + def path_info_pop(self, pattern: Pattern[str] | None = None) -> str | None: ... + def path_info_peek(self) -> str | None: ... + urlvars: SymmetricPropertyWithDelete[dict[str, str]] + urlargs: SymmetricPropertyWithDelete[tuple[str, ...]] + @property + def is_xhr(self) -> bool: ... + host: SymmetricPropertyWithDelete[str] + @property + def domain(self) -> str: ... + + @property + def body(self) -> bytes: ... + @body.setter + def body(self, value: bytes | None) -> None: ... + @body.deleter + def body(self) -> None: ... + + json: SymmetricPropertyWithDelete[Any] + json_body: SymmetricPropertyWithDelete[Any] + text: SymmetricPropertyWithDelete[str] + @property + def POST(self) -> MultiDict[str, str | _FieldStorageWithFile] | NoVars: ... + @property + def GET(self) -> GetDict: ... + @property + def params(self) -> NestedMultiDict[str, str | _FieldStorageWithFile]: ... + cookies: AsymmetricProperty[RequestCookies, SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]]] + def copy(self) -> Self: ... + def copy_get(self) -> Self: ... + + @property + def is_body_readable(self) -> bool: ... + @is_body_readable.setter + def is_body_readable(self, flag: bool) -> None: ... + + def make_body_seekable(self) -> None: ... + def copy_body(self) -> None: ... + def make_tempfile(self) -> io.BufferedRandom: ... + def remove_conditional_headers( + self, remove_encoding: bool = True, remove_range: bool = True, remove_match: bool = True, remove_modified: bool = True + ) -> None: ... + accept: _AcceptProperty + accept_charset: _AcceptCharsetProperty + accept_encoding: _AcceptEncodingProperty + accept_language: _AcceptLanguageProperty + authorization: AsymmetricPropertyWithDelete[_authorization | None, tuple[str, str | dict[str, str]] | list[Any] | str | None] + cache_control: AsymmetricPropertyWithDelete[ + _RequestCacheControl, _RequestCacheControl | _RequestCacheControlDict | str | None + ] + if_match: _ETagProperty + if_none_match: _ETagProperty + date: _DateProperty + if_modified_since: _DateProperty + if_unmodified_since: _DateProperty + if_range: AsymmetricPropertyWithDelete[ + IfRange | IfRangeDate, IfRange | IfRangeDate | datetime.datetime | datetime.date | str | None + ] + max_forwards: SymmetricPropertyWithDelete[int | None] + pragma: SymmetricPropertyWithDelete[str | None] + range: AsymmetricPropertyWithDelete[Range | None, tuple[int, int | None] | list[int | None] | list[int] | str | None] + referer: SymmetricPropertyWithDelete[str | None] + referrer = referer # pyrefly: ignore [unknown-name] + user_agent: SymmetricPropertyWithDelete[str | None] + def as_bytes(self, skip_body: bool = False) -> bytes: ... + def as_text(self) -> str: ... + @classmethod + def from_bytes(cls, b: bytes) -> Self: ... + @classmethod + def from_text(cls, s: str) -> Self: ... + @classmethod + def from_file(cls, fp: _SupportsReadAndNoArgReadline) -> Self: ... + + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: Literal[False] = False + ) -> tuple[str, list[tuple[str, str]], Iterable[bytes]]: ... + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: Literal[True] + ) -> tuple[str, list[tuple[str, str]], Iterable[bytes], OptExcInfo | None]: ... + @overload + def call_application( + self, application: WSGIApplication, catch_exc_info: bool + ) -> ( + tuple[str, list[tuple[str, str]], Iterable[bytes], OptExcInfo | None] | tuple[str, list[tuple[str, str]], Iterable[bytes]] + ): ... + + ResponseClass: type[Response] + def send(self, application: WSGIApplication | None = None, catch_exc_info: bool = False) -> Response: ... + get_response = send + def make_default_send_app(self) -> SendRequest: ... + @classmethod + def blank( + cls, + path: str, + environ: dict[str, None] | None = None, + base_url: str | None = None, + headers: Mapping[str, str] | None = None, + POST: str | bytes | Mapping[Any, Any] | Mapping[Any, _ListOrTuple[Any]] | None = None, + **kw: Any, + ) -> Self: ... + +class LegacyRequest(BaseRequest): + @property # type: ignore[override] + def uscript_name(self) -> str: ... + @uscript_name.setter + def uscript_name(self, value: str) -> None: ... + + @property # type: ignore[override] + def upath_info(self) -> str: ... + @upath_info.setter + def upath_info(self, value: str) -> None: ... + + def encget(self, key: str, default: Any = ..., encattr: str | None = None) -> Any: ... + +class AdhocAttrMixin: + def __setattr__(self, attr: str, value: Any) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + def __delattr__(self, attr: str) -> None: ... + +class Request(AdhocAttrMixin, BaseRequest): + # this is so Request doesn't count as callable, it's not very pretty + # but we run into trouble with overlapping overloads in wsgify if we + # don't exclude __call__ from arbitrary attribute access + __call__: None + +class DisconnectionError(IOError): ... + +def environ_from_url(path: str) -> WSGIEnvironment: ... +def environ_add_POST( + env: WSGIEnvironment, + data: str | bytes | Mapping[Any, Any] | Mapping[Any, _ListOrTuple[Any]] | None, + content_type: str | None = None, +) -> None: ... + +class LimitedLengthFile(io.RawIOBase): + file: SupportsRead[bytes] + maxlen: int + remaining: int + def __init__(self, file: SupportsRead[bytes], maxlen: int) -> None: ... + def fileno(self) -> int: ... + @staticmethod + def readable() -> Literal[True]: ... + def readinto(self, buff: WriteableBuffer) -> int: ... + +class Transcoder: + charset: str + errors: str + def __init__(self, charset: str, errors: str = "strict") -> None: ... + def transcode_query(self, q: str) -> str: ... + def transcode_fs(self, fs: cgi_FieldStorage, content_type: str) -> io.BytesIO: ... diff --git a/stubs/WebOb/webob/response.pyi b/stubs/WebOb/webob/response.pyi new file mode 100644 index 000000000000..3bfa3ae3d643 --- /dev/null +++ b/stubs/WebOb/webob/response.pyi @@ -0,0 +1,181 @@ +from _typeshed import SupportsItems, SupportsRead +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Iterator, Sequence +from datetime import timedelta +from typing import IO, Any, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Self + +from webob._types import AsymmetricProperty, AsymmetricPropertyWithDelete, SymmetricProperty, SymmetricPropertyWithDelete +from webob.byterange import ContentRange +from webob.cachecontrol import CacheControl +from webob.cookies import _SameSitePolicy +from webob.descriptors import _authorization, _ContentRangeParams, _DateProperty, _ListProperty +from webob.headers import ResponseHeaders +from webob.request import Request + +__all__ = ["Response"] + +_ResponseT = TypeVar("_ResponseT", bound=Response) +_ResponseCacheControl: TypeAlias = CacheControl[Literal["response"]] + +@type_check_only +class _ResponseCacheExpires(Protocol): + def __call__( + self, + seconds: int | timedelta = 0, + *, + public: bool = ..., + private: Literal[True] | str = ..., + no_cache: Literal[True] | str = ..., + no_store: bool = ..., + no_transform: bool = ..., + must_revalidate: bool = ..., + proxy_revalidate: bool = ..., + max_age: int = ..., + s_maxage: int = ..., + s_max_age: int = ..., + stale_while_revalidate: int = ..., + stale_if_error: int = ..., + ) -> None: ... + +@type_check_only +class _ResponseCacheControlDict(TypedDict, total=False): + public: bool + private: Literal[True] | str + no_cache: Literal[True] | str + no_store: bool + no_transform: bool + must_revalidate: bool + proxy_revalidate: bool + max_age: int + s_maxage: int + s_max_age: int + stale_while_revalidate: int + stale_if_error: int + +class Response: + default_content_type: str + default_charset: str + unicode_errors: str + default_conditional_response: bool + default_body_encoding: str + request: Request | None + environ: WSGIEnvironment | None + status: AsymmetricProperty[str, int | str | bytes] + conditional_response: bool + def __init__( + self, + body: bytes | str | None = None, + status: int | str | bytes | None = None, + headerlist: list[tuple[str, str]] | None = None, + app_iter: Iterable[bytes] | None = None, + content_type: str | None = None, + conditional_response: bool | None = None, + charset: str = ..., + **kw: Any, + ) -> None: ... + @classmethod + def from_file(cls, fp: IO[str] | IO[bytes]) -> Response: ... + def copy(self) -> Response: ... + status_code: SymmetricProperty[int] + status_int: SymmetricProperty[int] + headerlist: AsymmetricPropertyWithDelete[list[tuple[str, str]], Iterable[tuple[str, str]] | SupportsItems[str, str]] + headers: AsymmetricProperty[ResponseHeaders, SupportsItems[str, str] | Iterable[tuple[str, str]]] + body: SymmetricPropertyWithDelete[bytes] + json: SymmetricPropertyWithDelete[Any] + json_body: SymmetricPropertyWithDelete[Any] + @property + def has_body(self) -> bool: ... + text: SymmetricPropertyWithDelete[str] + unicode_body: SymmetricPropertyWithDelete[str] # deprecated + ubody: SymmetricPropertyWithDelete[str] # deprecated + body_file: AsymmetricPropertyWithDelete[ResponseBodyFile, SupportsRead[bytes]] + content_length: AsymmetricPropertyWithDelete[int | None, int | str | bytes | None] + def write(self, text: str | bytes) -> int: ... + app_iter: SymmetricPropertyWithDelete[Iterable[bytes]] + allow: _ListProperty + vary: _ListProperty + content_encoding: SymmetricPropertyWithDelete[str | None] + content_language: SymmetricPropertyWithDelete[str | None] + content_location: SymmetricPropertyWithDelete[str | None] + content_md5: SymmetricPropertyWithDelete[str | None] + content_disposition: SymmetricPropertyWithDelete[str | None] + accept_ranges: SymmetricPropertyWithDelete[str | None] + content_range: AsymmetricPropertyWithDelete[ContentRange | None, _ContentRangeParams] + date: _DateProperty + expires: _DateProperty + last_modified: _DateProperty + etag: AsymmetricPropertyWithDelete[str | None, tuple[str, bool] | str | None] + @property + def etag_strong(self) -> str | None: ... + location: SymmetricPropertyWithDelete[str | None] + pragma: SymmetricPropertyWithDelete[str | None] + age: SymmetricPropertyWithDelete[int | None] + retry_after: _DateProperty + server: SymmetricPropertyWithDelete[str | None] + www_authenticate: AsymmetricPropertyWithDelete[ + _authorization | None, tuple[str, str | dict[str, str]] | list[Any] | str | None + ] + charset: SymmetricPropertyWithDelete[str | None] + content_type: SymmetricPropertyWithDelete[str | None] + content_type_params: AsymmetricPropertyWithDelete[dict[str, str], SupportsItems[str, str] | None] + def set_cookie( + self, + name: str | bytes, + value: str | bytes | None = "", + max_age: int | timedelta | None = None, + path: str = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + comment: str | None = None, + overwrite: bool = False, + samesite: _SameSitePolicy | None = None, + ) -> None: ... + def delete_cookie(self, name: str | bytes, path: str = "/", domain: str | None = None) -> None: ... + def unset_cookie(self, name: str | bytes, strict: bool = True) -> None: ... + + @overload + def merge_cookies(self, resp: _ResponseT) -> _ResponseT: ... + @overload + def merge_cookies(self, resp: WSGIApplication) -> WSGIApplication: ... + + cache_control: AsymmetricProperty[_ResponseCacheControl, _ResponseCacheControl | _ResponseCacheControlDict | str | None] + cache_expires: AsymmetricProperty[_ResponseCacheExpires, timedelta | int | bool | None] + def encode_content(self, encoding: Literal["gzip", "identity"] = "gzip", lazy: bool = False) -> None: ... + def decode_content(self) -> None: ... + def md5_etag(self, body: bytes | None = None, set_content_md5: bool = False) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def conditional_response_app(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def app_iter_range(self, start: int, stop: int | None) -> AppIterRange: ... + def __str__(self, skip_body: bool = False) -> str: ... + +class ResponseBodyFile: + mode: Literal["wb"] + closed: Literal[False] + response: Response + def __init__(self, response: Response) -> None: ... + @property + def encoding(self) -> str | None: ... + # NOTE: Technically this is an instance attribute and not a method + def write(self, text: str | bytes) -> int: ... + def writelines(self, seq: Sequence[str | bytes]) -> None: ... + def flush(self) -> None: ... + def tell(self) -> int: ... + +class AppIterRange: + app_iter: Iterator[bytes] + start: int + stop: int | None + def __init__(self, app_iter: Iterable[bytes], start: int, stop: int | None) -> None: ... + def __iter__(self) -> Self: ... + def next(self) -> bytes: ... + __next__ = next + def close(self) -> None: ... + +class EmptyResponse: + def __init__(self, app_iter: Iterable[bytes] | None = None) -> None: ... + def __iter__(self) -> Self: ... + def __len__(self) -> Literal[0]: ... + def next(self) -> bytes: ... + __next__ = next diff --git a/stubs/WebOb/webob/static.pyi b/stubs/WebOb/webob/static.pyi new file mode 100644 index 000000000000..c74664103a5b --- /dev/null +++ b/stubs/WebOb/webob/static.pyi @@ -0,0 +1,40 @@ +from _typeshed import StrPath +from _typeshed.wsgi import WSGIApplication +from collections.abc import Iterator +from typing import IO, Any + +from webob.dec import wsgify +from webob.request import Request +from webob.response import Response + +__all__ = ["FileApp", "DirectoryApp"] + +BLOCK_SIZE: int + +class FileApp: + filename: StrPath + kw: dict[str, Any] + def __init__(self, filename: StrPath, **kw: Any) -> None: ... + @wsgify + def __call__(self, req: Request) -> WSGIApplication: ... + +class FileIter: + file: IO[bytes] + def __init__(self, file: IO[bytes]) -> None: ... + def app_iter_range( + self, seek: int | None = None, limit: int | None = None, block_size: int | None = None + ) -> Iterator[bytes]: ... + __iter__ = app_iter_range + +class DirectoryApp: + path: StrPath + index_page: str + hide_index_with_redirect: bool + fileapp_kw: dict[str, Any] + def __init__( + self, path: StrPath, index_page: str = "index.html", hide_index_with_redirect: bool = False, **kw: Any + ) -> None: ... + def make_fileapp(self, path: StrPath) -> FileApp: ... + @wsgify + def __call__(self, req: Request) -> Response | FileApp: ... + def index(self, req: Request, path: StrPath) -> Response | FileApp: ... diff --git a/stubs/WebOb/webob/util.pyi b/stubs/WebOb/webob/util.pyi new file mode 100644 index 000000000000..0c1c015c23bc --- /dev/null +++ b/stubs/WebOb/webob/util.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable +from typing import AnyStr + +def html_escape(s: object) -> str: ... +def urljoin(base: str, url: str | None) -> str: ... +def header_docstring(header: str, rfc_section: str) -> str: ... +def warn_deprecation(text: str, version: str, stacklevel: int) -> None: ... + +status_reasons: dict[int, str] +status_generic_reasons: dict[int, str] + +def strings_differ(string1: AnyStr, string2: AnyStr, compare_digest: Callable[[AnyStr, AnyStr], bool] = ...) -> bool: ... diff --git a/stubs/WebTest/@tests/stubtest_allowlist.txt b/stubs/WebTest/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..57f2ad0779b7 --- /dev/null +++ b/stubs/WebTest/@tests/stubtest_allowlist.txt @@ -0,0 +1,19 @@ +# error: failed to find stub +# ========================== +# These modules have been migrated to external packages +# and emit an `ImportError` if people try to use the +# functions/classes defined within +webtest.ext +webtest.sel +# Compatibility/utility modules for internal use that didn't +# seem worth including in the stubs +webtest.compat +webtest.lint +webtest.utils + +# error: variable differs from runtime type +# ========================================= +# Even though this can be `None`, it never should be during +# normal use of WebTest, so it seems more pragmatic to treat +# it as always non-`None` +webtest.response.TestResponse.request diff --git a/stubs/WebTest/METADATA.toml b/stubs/WebTest/METADATA.toml new file mode 100644 index 000000000000..0c917c5cbc93 --- /dev/null +++ b/stubs/WebTest/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.0.*" +upstream-repository = "https://github.com/Pylons/webtest" +dependencies = ["beautifulsoup4", "types-waitress", "types-WebOb"] diff --git a/stubs/WebTest/webtest/__init__.pyi b/stubs/WebTest/webtest/__init__.pyi new file mode 100644 index 000000000000..bad803e222dd --- /dev/null +++ b/stubs/WebTest/webtest/__init__.pyi @@ -0,0 +1,14 @@ +from webtest.app import AppError as AppError, TestApp as TestApp, TestRequest as TestRequest +from webtest.forms import ( + Checkbox as Checkbox, + Field as Field, + Form as Form, + Hidden as Hidden, + Radio as Radio, + Select as Select, + Submit as Submit, + Text as Text, + Textarea as Textarea, + Upload as Upload, +) +from webtest.response import TestResponse as TestResponse diff --git a/stubs/WebTest/webtest/app.pyi b/stubs/WebTest/webtest/app.pyi new file mode 100644 index 000000000000..0d43cc9ff633 --- /dev/null +++ b/stubs/WebTest/webtest/app.pyi @@ -0,0 +1,206 @@ +import json +from _typeshed import SupportsItems, SupportsKeysAndGetItem +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Iterable, Sequence +from http.cookiejar import CookieJar, DefaultCookiePolicy +from typing import Any, Generic, Literal, TypeAlias, TypeVar + +from webob.request import BaseRequest +from webtest.forms import File, Upload +from webtest.response import TestResponse + +# NOTE: While it is possible to pass different kinds of values depending on +# the exact configuration of the request, it seems more robust to +# restrict them to the types that are supported by all code paths. +# I don't expect anyone to try to pass different kinds of values +# in a non-JSON request. +_ParamValue: TypeAlias = File | Upload | int | bytes | str +_Params: TypeAlias = SupportsItems[str | bytes, _ParamValue] | Sequence[tuple[str | bytes, _ParamValue]] +# NOTE: Using `Collection` rather than `Iterable` would probably be slightly +# safer since WebTest will check this parameter for truthyness. But since +# objects are truthy by default, this should only lead to issues in truly +# exotic cases. +_ExtraEnviron: TypeAlias = SupportsKeysAndGetItem[str, Any] | Iterable[tuple[str, Any]] +_Files: TypeAlias = Sequence[tuple[str, str] | tuple[str, str, bytes]] +_AppT = TypeVar("_AppT", bound=WSGIApplication, default=WSGIApplication) + +__all__ = ["TestApp", "TestRequest"] + +class AppError(Exception): + def __init__(self, message: str, *args: object) -> None: ... + +class CookiePolicy(DefaultCookiePolicy): ... + +class TestRequest(BaseRequest): + ResponseClass: type[TestResponse] + __test__: Literal[False] + +class TestApp(Generic[_AppT]): + RequestClass: type[TestRequest] + app: _AppT + lint: bool + relative_to: str | None + extra_environ: WSGIEnvironment + use_unicode: bool + cookiejar: CookieJar + JSONEncoder: json.JSONEncoder + __test__: Literal[False] + def __init__( + self, + app: _AppT, + # NOTE: this extra_environ is different from the others and needs to + # support __delitem__, it seems easiest to just treat this like + # a regular WSGIEnvironment. The docs also say that this should + # be a dictionary. + extra_environ: WSGIEnvironment | None = None, + relative_to: str | None = None, + use_unicode: bool = True, + cookiejar: CookieJar | None = None, + parser_features: Sequence[str] | str | None = None, + json_encoder: json.JSONEncoder | None = None, + lint: bool = True, + ) -> None: ... + def get_authorization(self) -> tuple[str, str | tuple[str, str]]: ... + def set_authorization(self, value: tuple[str, str | tuple[str, str]]) -> None: ... + + @property + def authorization(self) -> tuple[str, str | tuple[str, str]]: ... + @authorization.setter + def authorization(self, value: tuple[str, str | tuple[str, str]]) -> None: ... + + @property + def cookies(self) -> dict[str, str | None]: ... + def set_cookie(self, name: str, value: str | None) -> None: ... + def reset(self) -> None: ... + def set_parser_features(self, parser_features: Sequence[str] | str) -> None: ... + def get( + self, + url: str, + params: _Params | str | None = None, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def post( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def put( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def patch( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + upload_files: _Files | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def delete( + self, + url: str, + params: _Params | str = "", + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def options( + self, + url: str, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def head( + self, + url: str, + params: _Params | str | None = None, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + xhr: bool = False, + ) -> TestResponse: ... + def post_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def put_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def patch_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def delete_json( + self, + url: str, + params: Any = ..., + *, + headers: dict[str, str] | None = None, + extra_environ: _ExtraEnviron | None = None, + status: int | str | None = None, + expect_errors: bool = False, + content_type: str | None = None, + xhr: bool = False, + ) -> TestResponse: ... + def encode_multipart(self, params: Iterable[tuple[str | bytes, _ParamValue]], files: _Files) -> tuple[str, bytes]: ... + def request( + self, url_or_req: str | TestRequest, status: int | str | None = None, expect_errors: bool = False, **req_params: Any + ) -> TestResponse: ... + def do_request( + self, req: TestRequest, status: int | str | None = None, expect_errors: bool | None = None + ) -> TestResponse: ... diff --git a/stubs/WebTest/webtest/debugapp.pyi b/stubs/WebTest/webtest/debugapp.pyi new file mode 100644 index 000000000000..ea633f9c8346 --- /dev/null +++ b/stubs/WebTest/webtest/debugapp.pyi @@ -0,0 +1,22 @@ +from _typeshed import StrOrBytesPath +from _typeshed.wsgi import StartResponse, WSGIEnvironment +from collections.abc import Iterable +from typing import TypedDict, type_check_only +from typing_extensions import Unpack + +@type_check_only +class _DebugAppParams(TypedDict, total=False): + form: StrOrBytesPath | bytes | None + show_form: bool + +__all__ = ["DebugApp", "make_debug_app"] + +class DebugApp: + form: bytes | None + show_form: bool + def __init__(self, form: StrOrBytesPath | bytes | None = None, show_form: bool = False) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +debug_app: DebugApp + +def make_debug_app(global_conf: object, **local_conf: Unpack[_DebugAppParams]) -> DebugApp: ... diff --git a/stubs/WebTest/webtest/forms.pyi b/stubs/WebTest/webtest/forms.pyi new file mode 100644 index 000000000000..695b943d7fb1 --- /dev/null +++ b/stubs/WebTest/webtest/forms.pyi @@ -0,0 +1,191 @@ +from collections.abc import Collection, Generator, Iterable, Sequence +from typing import Any, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +from bs4 import BeautifulSoup +from webtest.response import TestResponse + +_T = TypeVar("_T") + +@type_check_only +class _Classes(TypedDict): + submit: type[Submit] + button: type[Submit] + image: type[Submit] + multiple_select: type[MultipleSelect] + select: type[Select] + hidden: type[Hidden] + file: type[File] + text: type[Text] + search: type[Text] + email: type[Email] + password: type[Text] + checkbox: type[Checkbox] + textarea: type[Textarea] + radio: type[Radio] + +# NOTE: It seems unergonomic having to put isinstance checks everywhere +# in your test code where you're accessing a form field, so we +# return `Any` for now. What we would really like to use here is +# `AnyOf`, but that doesn't exist yet. +_AnyField: TypeAlias = Any + +class NoValue: ... + +class Upload: + filename: str + content: bytes | None + content_type: str | None + def __init__(self, filename: str, content: bytes | None = None, content_type: str | None = None) -> None: ... + def __iter__(self) -> Generator[str | bytes]: ... + +class Field: + classes: _Classes + form: Form + tag: str + name: str + pos: int + id: str + attrs: dict[str, str] + def __init__( + self, form: Form, tag: str, name: str, pos: int, value: str | None = None, id: str | None = None, **attrs: str + ) -> None: ... + def value__get(self) -> str: ... + def value__set(self, value: str | None) -> None: ... + + @property + def value(self) -> str: ... + @value.setter + def value(self, value: str | None) -> None: ... + + def force_value(self, value: str | None) -> None: ... + +class Select(Field): + options: list[tuple[str, bool, str]] + optionPositions: list[int] + selectedIndex: int | None + + # NOTE: Even though it's safe to pass any object into text, I don't + # think that follows the spirit of this argument and is more + # likely a consequence of reusing the same utility function + # in order to handle bytes for Py2 compat. + @overload + def select(self, value: None, text: str | bytes) -> None: ... + @overload + def select(self, value: None = None, *, text: str | bytes) -> None: ... + @overload + def select(self, value: object, text: None = None) -> None: ... + + def value__get(self) -> str: ... + def value__set(self, value: object | None) -> None: ... + + @property + def value(self) -> str: ... + @value.setter + def value(self, value: object | None) -> None: ... + +class MultipleSelect(Field): + options: list[tuple[str, bool, str]] + selectedIndices: list[int] + + @overload + def select_multiple(self, value: None, texts: Iterable[str | bytes]) -> None: ... + @overload + def select_multiple(self, value: None = None, *, texts: Iterable[str | bytes]) -> None: ... + @overload + def select_multiple(self, value: Collection[object], texts: None = None) -> None: ... + + def value__get(self) -> list[str] | None: ... # type: ignore[override] + def value__set(self, values: Collection[object] | None) -> None: ... + + @property # type: ignore[override] + def value(self) -> list[str] | None: ... + @value.setter + def value(self, value: Collection[object] | None) -> None: ... + + # NOTE: Since unlike setting the value normally this doesn't perform + # any kind of type conversion, we're better off only allowing + # what `value__get` is supposed to be able to return. + def force_value(self, values: list[str] | None) -> None: ... # type: ignore[override] + +class Radio(Select): ... + +class Checkbox(Field): + def value__get(self) -> str | None: ... # type: ignore[override] + def value__set(self, value: object) -> None: ... + + @property # type: ignore[override] + def value(self) -> str | None: ... + @value.setter + def value(self, value: object) -> None: ... + + def checked__get(self) -> bool: ... + def checked__set(self, value: object) -> None: ... + + @property + def checked(self) -> bool: ... + @checked.setter + def checked(self, value: object) -> None: ... + +class Text(Field): ... +class Email(Field): ... +class File(Field): ... +class Textarea(Text): ... +class Hidden(Text): ... + +class Submit(Field): + def value__get(self) -> None: ... # type: ignore[override] + @property # type: ignore[misc] + def value(self) -> None: ... # type: ignore[override] + def value_if_submitted(self) -> str: ... + +class Form: + FieldClass: type[Field] + response: TestResponse + text: str + html: BeautifulSoup + action: str + method: str + id: str | None + enctype: str + field_order: list[tuple[str, Field]] + fields: dict[str, list[Field]] + def __init__(self, response: TestResponse, text: str, parser_features: Sequence[str] | str = "html.parser") -> None: ... + # NOTE: Technically it is only safe to pass `str | None` for most fields + # but this method is not really usable if we don't lift this + # restriction, we just have to assume people know what they + # are doing + def __setitem__(self, name: str, value: Any | None) -> None: ... + def set(self, name: str, value: Any | None, index: int | None = None) -> None: ... + def __getitem__(self, name: str) -> _AnyField: ... + + @overload + def get(self, name: str, index: int | None = None) -> _AnyField: ... + @overload + def get(self, name: str, index: int | None, default: _T) -> _AnyField | _T: ... + @overload + def get(self, name: str, index: int | None = None, *, default: _T) -> _AnyField | _T: ... + + @overload + def select(self, name: str, value: None, text: str | bytes, index: int | None = None) -> None: ... + @overload + def select(self, name: str, value: None = None, *, text: str | bytes, index: int | None = None) -> None: ... + @overload + def select(self, name: str, value: object, text: None = None, index: int | None = None) -> None: ... + + @overload + def select_multiple(self, name: str, value: None, texts: Iterable[str | bytes], index: int | None = None) -> None: ... + @overload + def select_multiple( + self, name: str, value: None = None, *, texts: Iterable[str | bytes], index: int | None = None + ) -> None: ... + @overload + def select_multiple(self, name: str, value: Iterable[object], texts: None = None, index: int | None = None) -> None: ... + + def submit( + self, name: str | None = None, index: int | None = None, value: str | None = None, **args: Any + ) -> TestResponse: ... + def lint(self) -> None: ... + def upload_fields(self) -> list[tuple[str, str] | tuple[str, str, bytes]]: ... + def submit_fields( + self, name: str | None = None, index: int | None = None, submit_value: str | None = None + ) -> list[tuple[str, str]]: ... diff --git a/stubs/WebTest/webtest/http.pyi b/stubs/WebTest/webtest/http.pyi new file mode 100644 index 000000000000..8c0e3314db38 --- /dev/null +++ b/stubs/WebTest/webtest/http.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from threading import Thread +from typing import Literal, TypeAlias +from typing_extensions import Self + +from waitress.server import TcpWSGIServer + +# NOTE: We may never really be able to complete this, since `create` +# invokes `cls.__init__` which is exempt from LSP violations +# unless we get something like `KwArgsOf[cls.__init__]`. +_WSGIServerParams: TypeAlias = Incomplete + +def get_free_port() -> tuple[str, int]: ... +def check_server(host: str, port: int, path_info: str = "/", timeout: float = 3, retries: int = 30) -> int: ... + +class StopableWSGIServer(TcpWSGIServer): + was_shutdown: bool + runner: Thread + test_app: WSGIApplication + application_url: str + def wrapper(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + def run(self) -> None: ... + def shutdown(self, debug: bool = False) -> Literal[True]: ... + # NOTE: This has the same keyword arguments as cls.__init__, which + # we can't express + @classmethod + def create(cls, application: WSGIApplication, **kwargs: _WSGIServerParams) -> Self: ... + def wait(self, retries: int = 30) -> bool: ... diff --git a/stubs/WebTest/webtest/response.pyi b/stubs/WebTest/webtest/response.pyi new file mode 100644 index 000000000000..2821f616e16c --- /dev/null +++ b/stubs/WebTest/webtest/response.pyi @@ -0,0 +1,93 @@ +import re +from _typeshed.wsgi import WSGIApplication +from collections.abc import Callable, Mapping, Sequence +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Unpack +from xml.etree import ElementTree + +from bs4 import BeautifulSoup +from webob import Response +from webtest.app import TestApp, TestRequest, _Files +from webtest.forms import Form + +_Pattern: TypeAlias = str | bytes | re.Pattern[str] | Callable[[str], bool] +# NOTE: These are optional dependencies, so we don't want to depend on them +# in the stubs either. Also there are no stubs for pyquery anyways. +_PyQuery: TypeAlias = Any +_PyQueryParams: TypeAlias = Any +_LxmlElement: TypeAlias = Any + +@type_check_only +class _GetParams(TypedDict, total=False): + params: Mapping[str, str] | str + headers: Mapping[str, str] + extra_environ: Mapping[str, Any] + status: int | str | None + expect_errors: bool + xhr: bool + +@type_check_only +class _PostParams(_GetParams, total=False): + upload_files: _Files + content_type: str + +class TestResponse(Response): + # NOTE: The way WebTest creates reponses the request is always set + # we could've used `MaybeNone`, but it seems more pragmatic + # to just assume that this is always set. + request: TestRequest # type: ignore[assignment] + app: WSGIApplication + test_app: TestApp + parser_features: str | Sequence[str] + __test__: Literal[False] + @property + def forms(self) -> dict[str | int, Form]: ... + @property + def form(self) -> Form: ... + @property + def testbody(self) -> str: ... + def follow(self, **kw: Unpack[_GetParams]) -> TestResponse: ... + def maybe_follow(self, **kw: Unpack[_GetParams]) -> TestResponse: ... + def click( + self, + description: _Pattern | None = None, + linkid: _Pattern | None = None, + href: _Pattern | None = None, + index: int | None = None, + verbose: bool = False, + extra_environ: dict[str, Any] | None = None, + ) -> TestResponse: ... + def clickbutton( + self, + description: _Pattern | None = None, + buttonid: _Pattern | None = None, + href: _Pattern | None = None, + onclick: str | None = None, + index: int | None = None, + verbose: bool = False, + ) -> TestResponse: ... + + @overload + def goto(self, href: str, method: Literal["get"] = "get", **args: Unpack[_GetParams]) -> TestResponse: ... + @overload + def goto(self, href: str, method: Literal["post"], **args: Unpack[_PostParams]) -> TestResponse: ... + + @property + def normal_body(self) -> bytes: ... + @property + def unicode_normal_body(self) -> str: ... + def __contains__(self, s: str) -> bool: ... + def mustcontain(self, *strings: str, no: Sequence[str] | str = ...) -> None: ... + @property + def html(self) -> BeautifulSoup: ... + @property + def xml(self) -> ElementTree.Element: ... + @property + def lxml(self) -> _LxmlElement: ... + @property + def json(self) -> Any: ... + @property + def pyquery(self) -> _PyQuery: ... + def PyQuery(self, **kwargs: _PyQueryParams) -> _PyQuery: ... + def showbrowser(self) -> None: ... + def __str__(self) -> str: ... # type: ignore[override] # noqa: Y029 diff --git a/stubs/aiofiles/@tests/stubtest_allowlist.txt b/stubs/aiofiles/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6562daed8456 --- /dev/null +++ b/stubs/aiofiles/@tests/stubtest_allowlist.txt @@ -0,0 +1,91 @@ +# These all delegate using *args,**kwargs, but stubs use signature of +# method they are being delegated to. +aiofiles.threadpool.binary.AsyncBufferedIOBase.close +aiofiles.threadpool.binary.AsyncBufferedIOBase.detach +aiofiles.threadpool.binary.AsyncBufferedIOBase.fileno +aiofiles.threadpool.binary.AsyncBufferedIOBase.flush +aiofiles.threadpool.binary.AsyncBufferedIOBase.isatty +aiofiles.threadpool.binary.AsyncBufferedIOBase.readable +aiofiles.threadpool.binary.AsyncBufferedIOBase.seekable +aiofiles.threadpool.binary.AsyncBufferedIOBase.tell +aiofiles.threadpool.binary.AsyncBufferedIOBase.writable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.close +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.detach +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.fileno +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.flush +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.isatty +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.readable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.seekable +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.tell +aiofiles.threadpool.binary.AsyncIndirectBufferedIOBase.writable +aiofiles.threadpool.binary.AsyncFileIO.close +aiofiles.threadpool.binary.AsyncFileIO.fileno +aiofiles.threadpool.binary.AsyncFileIO.flush +aiofiles.threadpool.binary.AsyncFileIO.isatty +aiofiles.threadpool.binary.AsyncFileIO.readable +aiofiles.threadpool.binary.AsyncFileIO.readall +aiofiles.threadpool.binary.AsyncFileIO.seekable +aiofiles.threadpool.binary.AsyncFileIO.tell +aiofiles.threadpool.binary.AsyncFileIO.writable +aiofiles.threadpool.binary.AsyncIndirectFileIO.close +aiofiles.threadpool.binary.AsyncIndirectFileIO.fileno +aiofiles.threadpool.binary.AsyncIndirectFileIO.flush +aiofiles.threadpool.binary.AsyncIndirectFileIO.isatty +aiofiles.threadpool.binary.AsyncIndirectFileIO.readable +aiofiles.threadpool.binary.AsyncIndirectFileIO.readall +aiofiles.threadpool.binary.AsyncIndirectFileIO.seekable +aiofiles.threadpool.binary.AsyncIndirectFileIO.tell +aiofiles.threadpool.binary.AsyncIndirectFileIO.writable +aiofiles.threadpool.text.AsyncTextIOWrapper.close +aiofiles.threadpool.text.AsyncTextIOWrapper.detach +aiofiles.threadpool.text.AsyncTextIOWrapper.fileno +aiofiles.threadpool.text.AsyncTextIOWrapper.flush +aiofiles.threadpool.text.AsyncTextIOWrapper.isatty +aiofiles.threadpool.text.AsyncTextIOWrapper.readable +aiofiles.threadpool.text.AsyncTextIOWrapper.seekable +aiofiles.threadpool.text.AsyncTextIOWrapper.tell +aiofiles.threadpool.text.AsyncTextIOWrapper.writable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.close +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.detach +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.fileno +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.flush +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.isatty +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.readable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.seekable +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.tell +aiofiles.threadpool.text.AsyncTextIndirectIOWrapper.writable + +# These functions get the wrong signature from functools.wraps() +aiofiles.os.stat +aiofiles.os.rename +aiofiles.os.renames +aiofiles.os.replace +aiofiles.os.remove +aiofiles.os.unlink +aiofiles.os.mkdir +aiofiles.os.makedirs +aiofiles.os.link +aiofiles.os.symlink +aiofiles.os.readlink +aiofiles.os.rmdir +aiofiles.os.removedirs +aiofiles.os.scandir +aiofiles.os.listdir +aiofiles.ospath.exists +aiofiles.ospath.isfile +aiofiles.ospath.isdir +aiofiles.ospath.getsize +aiofiles.ospath.getmtime +aiofiles.ospath.getatime +aiofiles.ospath.getctime +aiofiles.ospath.samefile +aiofiles.ospath.sameopenfile + +# Same issues as above +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.close +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.fileno +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.flush +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.isatty +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.rollover +aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.tell +aiofiles.tempfile.temptypes.AsyncTemporaryDirectory.cleanup diff --git a/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt b/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..b0ea37bd4388 --- /dev/null +++ b/stubs/aiofiles/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# This function gets the wrong signature from functools.wraps() +aiofiles.os.sendfile diff --git a/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt b/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..b0ea37bd4388 --- /dev/null +++ b/stubs/aiofiles/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# This function gets the wrong signature from functools.wraps() +aiofiles.os.sendfile diff --git a/stubs/aiofiles/METADATA.toml b/stubs/aiofiles/METADATA.toml new file mode 100644 index 000000000000..c990b4bf835f --- /dev/null +++ b/stubs/aiofiles/METADATA.toml @@ -0,0 +1,6 @@ +version = "25.1.*" +upstream-repository = "https://github.com/Tinche/aiofiles" + +[tool.stubtest] +# linux and darwin are equivalent +ci-platforms = ["linux", "win32"] diff --git a/stubs/aiofiles/aiofiles/__init__.pyi b/stubs/aiofiles/aiofiles/__init__.pyi new file mode 100644 index 000000000000..64410d4ed529 --- /dev/null +++ b/stubs/aiofiles/aiofiles/__init__.pyi @@ -0,0 +1,12 @@ +from . import tempfile as tempfile +from .threadpool import ( + open as open, + stderr as stderr, + stderr_bytes as stderr_bytes, + stdin as stdin, + stdin_bytes as stdin_bytes, + stdout as stdout, + stdout_bytes as stdout_bytes, +) + +__all__ = ["open", "tempfile", "stdin", "stdout", "stderr", "stdin_bytes", "stdout_bytes", "stderr_bytes"] diff --git a/stubs/aiofiles/aiofiles/base.pyi b/stubs/aiofiles/aiofiles/base.pyi new file mode 100644 index 000000000000..5723a95d6307 --- /dev/null +++ b/stubs/aiofiles/aiofiles/base.pyi @@ -0,0 +1,31 @@ +from asyncio.events import AbstractEventLoop +from collections.abc import Awaitable, Callable, Generator +from concurrent.futures import Executor +from contextlib import AbstractAsyncContextManager +from types import TracebackType +from typing import Any, BinaryIO, Generic, TextIO, TypeVar +from typing_extensions import Self + +_T = TypeVar("_T") +_V_co = TypeVar("_V_co", covariant=True) + +def wrap(func: Callable[..., _T]) -> Callable[..., Awaitable[_T]]: ... + +class AsyncBase(Generic[_T]): + def __init__(self, file: TextIO | BinaryIO | None, loop: AbstractEventLoop | None, executor: Executor | None) -> None: ... + def __aiter__(self) -> Self: ... + async def __anext__(self) -> _T: ... + +class AsyncIndirectBase(AsyncBase[_T]): + def __init__( + self, name: str, loop: AbstractEventLoop | None, executor: Executor | None, indirect: Callable[[], TextIO | BinaryIO] + ) -> None: ... + +class AiofilesContextManager(Awaitable[_V_co], AbstractAsyncContextManager[_V_co]): + __slots__ = ("_coro", "_obj") + def __init__(self, coro: Awaitable[_V_co]) -> None: ... + def __await__(self) -> Generator[Any, Any, _V_co]: ... + async def __aenter__(self) -> _V_co: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... diff --git a/stubs/aiofiles/aiofiles/os.pyi b/stubs/aiofiles/aiofiles/os.pyi new file mode 100644 index 000000000000..506a0f2851bd --- /dev/null +++ b/stubs/aiofiles/aiofiles/os.pyi @@ -0,0 +1,171 @@ +import sys +from _typeshed import BytesPath, FileDescriptorOrPath, GenericPath, ReadableBuffer, StrOrBytesPath, StrPath +from asyncio.events import AbstractEventLoop +from collections.abc import Sequence +from concurrent.futures import Executor +from os import _ScandirIterator, stat_result +from typing import AnyStr, overload + +from aiofiles import ospath +from aiofiles.base import wrap as wrap + +__all__ = [ + "path", + "stat", + "rename", + "renames", + "replace", + "remove", + "unlink", + "mkdir", + "makedirs", + "rmdir", + "removedirs", + "link", + "symlink", + "readlink", + "listdir", + "scandir", + "access", + "wrap", + "getcwd", +] + +if sys.platform != "win32": + __all__ += ["statvfs", "sendfile"] + +path = ospath + +async def stat( + path: FileDescriptorOrPath, + *, + dir_fd: int | None = None, + follow_symlinks: bool = True, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> stat_result: ... +async def rename( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def renames( + old: StrOrBytesPath, new: StrOrBytesPath, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def replace( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def remove( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def unlink( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def mkdir( + path: StrOrBytesPath, + mode: int = 511, + *, + dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def makedirs( + name: StrOrBytesPath, + mode: int = 511, + exist_ok: bool = False, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def link( + src: StrOrBytesPath, + dst: StrOrBytesPath, + *, + src_dir_fd: int | None = None, + dst_dir_fd: int | None = None, + follow_symlinks: bool = True, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def symlink( + src: StrOrBytesPath, + dst: StrOrBytesPath, + target_is_directory: bool = False, + *, + dir_fd: int | None = None, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., +) -> None: ... +async def readlink( + path: AnyStr, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> AnyStr: ... +async def rmdir( + path: StrOrBytesPath, *, dir_fd: int | None = None, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> None: ... +async def removedirs(name: StrOrBytesPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> None: ... + +@overload +async def scandir( + path: None = None, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[str]: ... +@overload +async def scandir( + path: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[str]: ... +@overload +async def scandir( + path: GenericPath[AnyStr], *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> _ScandirIterator[AnyStr]: ... + +@overload +async def listdir( + path: StrPath | None, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> list[str]: ... +@overload +async def listdir(path: BytesPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> list[bytes]: ... +@overload +async def listdir(path: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> list[str]: ... + +async def access( + path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True +) -> bool: ... +async def getcwd() -> str: ... + +if sys.platform != "win32": + from os import statvfs_result + + @overload + async def sendfile( + out_fd: int, + in_fd: int, + offset: int | None, + count: int, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., + ) -> int: ... + @overload + async def sendfile( + out_fd: int, + in_fd: int, + offset: int, + count: int, + headers: Sequence[ReadableBuffer] = (), + trailers: Sequence[ReadableBuffer] = (), + flags: int = 0, + *, + loop: AbstractEventLoop | None = ..., + executor: Executor | None = ..., + ) -> int: ... # FreeBSD and Mac OS X only + + async def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ... # Unix only diff --git a/stubs/aiofiles/aiofiles/ospath.pyi b/stubs/aiofiles/aiofiles/ospath.pyi new file mode 100644 index 000000000000..2ef19d974489 --- /dev/null +++ b/stubs/aiofiles/aiofiles/ospath.pyi @@ -0,0 +1,47 @@ +from _typeshed import FileDescriptorOrPath +from asyncio.events import AbstractEventLoop +from concurrent.futures import Executor +from os import PathLike +from typing import AnyStr + +__all__ = [ + "abspath", + "getatime", + "getctime", + "getmtime", + "getsize", + "exists", + "isdir", + "isfile", + "islink", + "ismount", + "samefile", + "sameopenfile", +] + +async def exists( + path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def isfile( + path: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def isdir(s: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> bool: ... +async def islink(path: FileDescriptorOrPath) -> bool: ... +async def ismount(path: FileDescriptorOrPath) -> bool: ... +async def getsize( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> int: ... +async def getmtime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def getatime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def getctime( + filename: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> float: ... +async def samefile( + f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ... +) -> bool: ... +async def sameopenfile(fp1: int, fp2: int, *, loop: AbstractEventLoop | None = ..., executor: Executor | None = ...) -> bool: ... +async def abspath(path: PathLike[AnyStr] | AnyStr) -> AnyStr: ... diff --git a/stubs/aiofiles/aiofiles/tempfile/__init__.pyi b/stubs/aiofiles/aiofiles/tempfile/__init__.pyi new file mode 100644 index 000000000000..817da9bc77a1 --- /dev/null +++ b/stubs/aiofiles/aiofiles/tempfile/__init__.pyi @@ -0,0 +1,324 @@ +import sys +from _typeshed import ( + BytesPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + StrOrBytesPath, + StrPath, +) +from asyncio import AbstractEventLoop +from concurrent.futures import Executor +from typing import AnyStr, Literal, overload + +from ..base import AiofilesContextManager +from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO +from ..threadpool.text import AsyncTextIOWrapper + +# Text mode: always returns AsyncTextIOWrapper +@overload +def TemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + +# Unbuffered binary: returns a FileIO +@overload +def TemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... + +# Buffered binary reading/updating: AsyncBufferedReader +@overload +def TemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... + +# Buffered binary writing: AsyncBufferedIOBase +@overload +def TemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +# 3.12 added `delete_on_close` +if sys.version_info >= (3, 12): + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper[AnyStr]]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncFileIO[AnyStr]]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader[AnyStr]]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + delete_on_close: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase[AnyStr]]: ... +else: + # Text mode: always returns AsyncTextIOWrapper + @overload + def NamedTemporaryFile( + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncTextIOWrapper[AnyStr]]: ... + + # Unbuffered binary: returns a FileIO + @overload + def NamedTemporaryFile( + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncFileIO[AnyStr]]: ... + + # Buffered binary reading/updating: AsyncBufferedReader + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedReader[AnyStr]]: ... + + # Buffered binary writing: AsyncBufferedIOBase + @overload + def NamedTemporaryFile( + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + delete: bool = True, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, + ) -> AiofilesContextManager[AsyncBufferedIOBase[AnyStr]]: ... + +# Text mode: always returns AsyncTextIOWrapper +@overload +def SpooledTemporaryFile( + max_size: int = 0, + *, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenTextMode, + buffering: int = -1, + encoding: str | None = None, + newline: str | None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + +# Unbuffered binary: returns a FileIO +@overload +def SpooledTemporaryFile( + max_size: int = 0, + mode: OpenBinaryMode = "w+b", + *, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... + +# Buffered binary reading/updating: AsyncBufferedReader +@overload +def SpooledTemporaryFile( + max_size: int = 0, + mode: OpenBinaryModeReading | OpenBinaryModeUpdating = "w+b", + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... + +# Buffered binary writing: AsyncBufferedIOBase +@overload +def SpooledTemporaryFile( + max_size: int = 0, + *, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... +@overload +def SpooledTemporaryFile( + max_size: int, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + newline: None = None, + suffix: AnyStr | None = None, + prefix: AnyStr | None = None, + dir: StrOrBytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +@overload +def TemporaryDirectory( + suffix: str | None = None, + prefix: str | None = None, + dir: StrPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManagerTempDir: ... +@overload +def TemporaryDirectory( + suffix: bytes | None = None, + prefix: bytes | None = None, + dir: BytesPath | None = None, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManagerTempDir: ... + +class AiofilesContextManagerTempDir(AiofilesContextManager[str]): + async def __aenter__(self) -> str: ... + +__all__ = ["NamedTemporaryFile", "TemporaryFile", "SpooledTemporaryFile", "TemporaryDirectory"] diff --git a/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi b/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi new file mode 100644 index 000000000000..b6f05e13c7ce --- /dev/null +++ b/stubs/aiofiles/aiofiles/tempfile/temptypes.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete, OpenBinaryMode, ReadableBuffer +from asyncio import AbstractEventLoop +from collections.abc import Generator, Iterable +from concurrent.futures import Executor +from tempfile import TemporaryDirectory +from typing import TypeVar + +from aiofiles.base import AsyncBase as AsyncBase +from aiofiles.threadpool.utils import ( + cond_delegate_to_executor as cond_delegate_to_executor, + delegate_to_executor as delegate_to_executor, + proxy_property_directly as proxy_property_directly, +) + +_T = TypeVar("_T") + +class AsyncSpooledTemporaryFile(AsyncBase[_T]): + def fileno(self) -> Generator[Incomplete]: ... + def rollover(self) -> Generator[Incomplete]: ... + async def close(self) -> None: ... + async def flush(self) -> None: ... + async def isatty(self) -> bool: ... + async def read(self, n: int = ..., /) -> str | bytes: ... + async def readline(self, limit: int | None = ..., /) -> str | bytes: ... + async def readlines(self, hint: int = ..., /) -> list[str | bytes]: ... + async def seek(self, offset: int, whence: int = ...) -> int: ... + async def tell(self) -> int: ... + async def truncate(self, size: int | None = ...) -> None: ... + @property + def closed(self) -> bool: ... + @property + def encoding(self) -> str: ... + @property + def mode(self) -> OpenBinaryMode: ... + @property + def name(self) -> str | bytes: ... + @property + def newlines(self) -> str: ... + async def write(self, s: str | bytes | ReadableBuffer) -> int: ... + async def writelines(self, iterable: Iterable[str | bytes | ReadableBuffer]) -> None: ... + +class AsyncTemporaryDirectory: + async def cleanup(self) -> None: ... + @property + def name(self) -> str | bytes: ... + def __init__( + self, file: TemporaryDirectory[Incomplete], loop: AbstractEventLoop | None, executor: Executor | None + ) -> None: ... + async def close(self) -> None: ... diff --git a/stubs/aiofiles/aiofiles/threadpool/__init__.pyi b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi new file mode 100644 index 000000000000..bd2aea070627 --- /dev/null +++ b/stubs/aiofiles/aiofiles/threadpool/__init__.pyi @@ -0,0 +1,110 @@ +from _typeshed import ( + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, +) +from asyncio import AbstractEventLoop +from collections.abc import Callable +from concurrent.futures import Executor +from functools import _SingleDispatchCallable +from typing import Any, Literal, TypeAlias, overload + +from ..base import AiofilesContextManager +from .binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO, AsyncIndirectBufferedIOBase, _UnknownAsyncBinaryIO +from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper + +_Opener: TypeAlias = Callable[[str, int], int] + +# Text mode: always returns AsyncTextIOWrapper +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenTextMode = "r", + buffering: int = -1, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + closefd: bool = True, + opener: _Opener | None = None, + *, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncTextIOWrapper]: ... + +# Unbuffered binary: returns a FileIO +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryMode, + buffering: Literal[0], + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, + *, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncFileIO]: ... + +# Buffered binary reading/updating: AsyncBufferedReader +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryModeReading | OpenBinaryModeUpdating, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, + *, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedReader]: ... + +# Buffered binary writing: AsyncBufferedIOBase +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + buffering: Literal[-1, 1] = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, + *, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[AsyncBufferedIOBase]: ... + +# Buffering cannot be determined: fall back to _UnknownAsyncBinaryIO +@overload +def open( + file: FileDescriptorOrPath, + mode: OpenBinaryMode, + buffering: int = -1, + encoding: None = None, + errors: None = None, + newline: None = None, + closefd: bool = True, + opener: _Opener | None = None, + *, + loop: AbstractEventLoop | None = None, + executor: Executor | None = None, +) -> AiofilesContextManager[_UnknownAsyncBinaryIO]: ... + +wrap: _SingleDispatchCallable[Any] + +stdin: AsyncTextIndirectIOWrapper +stdout: AsyncTextIndirectIOWrapper +stderr: AsyncTextIndirectIOWrapper +stdin_bytes: AsyncIndirectBufferedIOBase +stdout_bytes: AsyncIndirectBufferedIOBase +stderr_bytes: AsyncIndirectBufferedIOBase + +__all__ = ("open", "stdin", "stdout", "stderr", "stdin_bytes", "stdout_bytes", "stderr_bytes") diff --git a/stubs/aiofiles/aiofiles/threadpool/binary.pyi b/stubs/aiofiles/aiofiles/threadpool/binary.pyi new file mode 100644 index 000000000000..3215fafc8706 --- /dev/null +++ b/stubs/aiofiles/aiofiles/threadpool/binary.pyi @@ -0,0 +1,59 @@ +from _typeshed import FileDescriptorOrPath, ReadableBuffer, WriteableBuffer +from collections.abc import Iterable +from io import FileIO +from typing import Generic, TypeVar, type_check_only + +from ..base import AsyncBase, AsyncIndirectBase + +_NameT = TypeVar("_NameT", bound=FileDescriptorOrPath, default=FileDescriptorOrPath) + +# This class does not exist at runtime and instead these methods are +# all dynamically patched in. +@type_check_only +class _UnknownAsyncBinaryIO(AsyncBase[bytes], Generic[_NameT]): + async def close(self) -> None: ... + async def flush(self) -> None: ... + async def isatty(self) -> bool: ... + async def read(self, size: int = ..., /) -> bytes: ... + async def readinto(self, buffer: WriteableBuffer, /) -> int | None: ... + async def readline(self, size: int | None = ..., /) -> bytes: ... + async def readlines(self, hint: int = ..., /) -> list[bytes]: ... + async def seek(self, offset: int, whence: int = ..., /) -> int: ... + async def seekable(self) -> bool: ... + async def tell(self) -> int: ... + async def truncate(self, size: int | None = ..., /) -> int: ... + async def writable(self) -> bool: ... + async def write(self, b: ReadableBuffer, /) -> int: ... + async def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ... + def fileno(self) -> int: ... + def readable(self) -> bool: ... + @property + def closed(self) -> bool: ... + @property + def mode(self) -> str: ... + @property + def name(self) -> _NameT: ... + +class AsyncBufferedIOBase(_UnknownAsyncBinaryIO[_NameT]): + async def read1(self, size: int = ..., /) -> bytes: ... + def detach(self) -> FileIO: ... + @property + def raw(self) -> FileIO: ... + +class AsyncIndirectBufferedIOBase(AsyncIndirectBase[bytes], _UnknownAsyncBinaryIO[_NameT], Generic[_NameT]): + async def read1(self, size: int = ..., /) -> bytes: ... + def detach(self) -> FileIO: ... + @property + def raw(self) -> FileIO: ... + +class AsyncBufferedReader(AsyncBufferedIOBase[_NameT]): + async def peek(self, size: int = ..., /) -> bytes: ... + +class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase[_NameT]): + async def peek(self, size: int = ..., /) -> bytes: ... + +class AsyncFileIO(_UnknownAsyncBinaryIO[_NameT]): + async def readall(self) -> bytes: ... + +class AsyncIndirectFileIO(AsyncIndirectBase[bytes], _UnknownAsyncBinaryIO[_NameT], Generic[_NameT]): + async def readall(self) -> bytes: ... diff --git a/stubs/aiofiles/aiofiles/threadpool/text.pyi b/stubs/aiofiles/aiofiles/threadpool/text.pyi new file mode 100644 index 000000000000..0976762f770c --- /dev/null +++ b/stubs/aiofiles/aiofiles/threadpool/text.pyi @@ -0,0 +1,45 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from typing import BinaryIO, Generic, TypeVar, type_check_only + +from ..base import AsyncBase, AsyncIndirectBase + +_NameT = TypeVar("_NameT", bound=FileDescriptorOrPath, default=FileDescriptorOrPath) + +@type_check_only +class _UnknownAsyncTextIO(AsyncBase[str], Generic[_NameT]): + async def close(self) -> None: ... + async def flush(self) -> None: ... + async def isatty(self) -> bool: ... + async def read(self, size: int | None = ..., /) -> str: ... + async def readline(self, size: int = ..., /) -> str: ... + async def readlines(self, hint: int = ..., /) -> list[str]: ... + async def seek(self, offset: int, whence: int = ..., /) -> int: ... + async def seekable(self) -> bool: ... + async def tell(self) -> int: ... + async def truncate(self, size: int | None = ..., /) -> int: ... + async def writable(self) -> bool: ... + async def write(self, b: str, /) -> int: ... + async def writelines(self, lines: Iterable[str], /) -> None: ... + def detach(self) -> BinaryIO: ... + def fileno(self) -> int: ... + def readable(self) -> bool: ... + @property + def buffer(self) -> BinaryIO: ... + @property + def closed(self) -> bool: ... + @property + def encoding(self) -> str: ... + @property + def errors(self) -> str | None: ... + @property + def line_buffering(self) -> bool: ... + @property + def newlines(self) -> str | tuple[str, ...] | None: ... + @property + def name(self) -> _NameT: ... + @property + def mode(self) -> str: ... + +class AsyncTextIOWrapper(_UnknownAsyncTextIO[_NameT]): ... +class AsyncTextIndirectIOWrapper(AsyncIndirectBase[str], _UnknownAsyncTextIO[_NameT], Generic[_NameT]): ... diff --git a/stubs/aiofiles/aiofiles/threadpool/utils.pyi b/stubs/aiofiles/aiofiles/threadpool/utils.pyi new file mode 100644 index 000000000000..438a6851ef72 --- /dev/null +++ b/stubs/aiofiles/aiofiles/threadpool/utils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Callable +from typing import TypeVar + +_T = TypeVar("_T", bound=type) + +# All these function actually mutate the given type: +def delegate_to_executor(*attrs: str) -> Callable[[_T], _T]: ... +def proxy_method_directly(*attrs: str) -> Callable[[_T], _T]: ... +def proxy_property_directly(*attrs: str) -> Callable[[_T], _T]: ... +def cond_delegate_to_executor(*attrs: str) -> Callable[[_T], _T]: ... diff --git a/stubs/antlr4-python3-runtime/METADATA.toml b/stubs/antlr4-python3-runtime/METADATA.toml new file mode 100644 index 000000000000..65d20d6ee09d --- /dev/null +++ b/stubs/antlr4-python3-runtime/METADATA.toml @@ -0,0 +1,5 @@ +version = "4.13.*" +upstream-repository = "https://github.com/antlr/antlr4" + +[tool.stubtest] +ci-platforms = ["linux", "win32"] diff --git a/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi b/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi new file mode 100644 index 000000000000..b6a2b43973fb --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/BufferedTokenStream.pyi @@ -0,0 +1,39 @@ +from antlr4.error.Errors import IllegalStateException as IllegalStateException +from antlr4.Lexer import Lexer as ActualLexer, TokenSource +from antlr4.Token import Token as Token + +Lexer: None + +class TokenStream: ... + +class BufferedTokenStream(TokenStream): + __slots__ = ("tokenSource", "tokens", "index", "fetchedEOF") + tokenSource: TokenSource + tokens: list[Token] + index: int + fetchedEOF: bool + def __init__(self, tokenSource: ActualLexer | None) -> None: ... + def mark(self) -> int: ... + def release(self, marker: int) -> None: ... + def reset(self) -> None: ... + def seek(self, index: int) -> None: ... + def get(self, index: int) -> Token: ... + def consume(self) -> None: ... + def sync(self, i: int) -> bool: ... + def fetch(self, n: int) -> int: ... + def getTokens(self, start: int, stop: int, types: set[int] | None = None) -> list[Token]: ... + def LA(self, i: int) -> int: ... + def LB(self, k: int) -> Token | None: ... + def LT(self, k: int) -> Token | None: ... + def adjustSeekIndex(self, i: int) -> int: ... + def lazyInit(self) -> None: ... + def setup(self) -> None: ... + def setTokenSource(self, tokenSource: ActualLexer | None) -> None: ... + def nextTokenOnChannel(self, i: int, channel: int) -> int: ... + def previousTokenOnChannel(self, i: int, channel: int) -> int: ... + def getHiddenTokensToRight(self, tokenIndex: int, channel: int = -1) -> list[Token] | None: ... + def getHiddenTokensToLeft(self, tokenIndex: int, channel: int = -1) -> list[Token] | None: ... + def filterForChannel(self, left: int, right: int, channel: int) -> list[Token] | None: ... + def getSourceName(self) -> str: ... + def getText(self, start: int | None = None, stop: int | None = None) -> str: ... + def fill(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi b/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi new file mode 100644 index 000000000000..e654055b7258 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/CommonTokenFactory.pyi @@ -0,0 +1,23 @@ +from antlr4.InputStream import InputStream +from antlr4.Lexer import TokenSource +from antlr4.Token import CommonToken as CommonToken + +class TokenFactory: ... + +class CommonTokenFactory(TokenFactory): + __slots__ = "copyText" + DEFAULT: CommonTokenFactory | None + copyText: bool + def __init__(self, copyText: bool = False) -> None: ... + def create( + self, + source: tuple[TokenSource, InputStream], + type: int, + text: str, + channel: int, + start: int, + stop: int, + line: int, + column: int, + ) -> CommonToken: ... + def createThin(self, type: int, text: str) -> CommonToken: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi b/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi new file mode 100644 index 000000000000..ad5d92d3bc9e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/CommonTokenStream.pyi @@ -0,0 +1,12 @@ +from antlr4.BufferedTokenStream import BufferedTokenStream as BufferedTokenStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.Token import Token as Token + +class CommonTokenStream(BufferedTokenStream): + __slots__ = "channel" + channel: int + def __init__(self, lexer: Lexer, channel: int = 0) -> None: ... + def adjustSeekIndex(self, i: int) -> int: ... + def LB(self, k: int) -> Token | None: ... + def LT(self, k: int) -> Token | None: ... + def getNumberOfOnChannelTokens(self) -> int: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi b/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi new file mode 100644 index 000000000000..75ae77b2447b --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/FileStream.pyi @@ -0,0 +1,7 @@ +from antlr4.InputStream import InputStream as InputStream + +class FileStream(InputStream): + __slots__ = "fileName" + fileName: str + def __init__(self, fileName: str, encoding: str = "ascii", errors: str = "strict") -> None: ... + def readDataFrom(self, fileName: str, encoding: str, errors: str = "strict") -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi b/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi new file mode 100644 index 000000000000..c4afb48832d6 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/InputStream.pyi @@ -0,0 +1,24 @@ +from typing import Literal + +from antlr4.Token import Token as Token + +class InputStream: + __slots__ = ("name", "strdata", "_index", "data", "_size") + name: str + strdata: str + data: list[int] + _index: int + _size: int + def __init__(self, data: str) -> None: ... + @property + def index(self) -> int: ... + @property + def size(self) -> int: ... + def reset(self) -> None: ... + def consume(self) -> None: ... + def LA(self, offset: int) -> int: ... + def LT(self, offset: int) -> int: ... + def mark(self) -> Literal[-1]: ... + def release(self, marker: int) -> None: ... + def seek(self, _index: int) -> None: ... + def getText(self, start: int, stop: int) -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi b/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi new file mode 100644 index 000000000000..2b84ca4e317e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/IntervalSet.pyi @@ -0,0 +1,20 @@ +from antlr4.Token import Token as Token + +class IntervalSet: + __slots__ = ("intervals", "readonly") + intervals: list[range] | None + readonly: bool + def __init__(self) -> None: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def addOne(self, v: int): ... + def addRange(self, v: range): ... + def addSet(self, other: IntervalSet): ... + def reduce(self, k: int): ... + def complement(self, start: int, stop: int): ... + def __contains__(self, item) -> bool: ... + def __len__(self) -> int: ... + def removeRange(self, v) -> None: ... + def removeOne(self, v) -> None: ... + def toString(self, literalNames: list[str], symbolicNames: list[str]): ... + def elementName(self, literalNames: list[str], symbolicNames: list[str], a: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi b/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi new file mode 100644 index 000000000000..5742e60131ca --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/LL1Analyzer.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNState import ATNState as ATNState, RuleStopState as RuleStopState +from antlr4.atn.Transition import ( + AbstractPredicateTransition as AbstractPredicateTransition, + NotSetTransition as NotSetTransition, + RuleTransition as RuleTransition, + WildcardTransition as WildcardTransition, +) +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextFromRuleContext as PredictionContextFromRuleContext, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class LL1Analyzer: + __slots__ = "atn" + HIT_PRED: Incomplete + atn: Incomplete + def __init__(self, atn: ATN) -> None: ... + def getDecisionLookahead(self, s: ATNState): ... + def LOOK(self, s: ATNState, stopState: ATNState | None = None, ctx: RuleContext | None = None): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi b/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi new file mode 100644 index 000000000000..3f46d7abe5d0 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Lexer.pyi @@ -0,0 +1,102 @@ +from typing import TextIO + +from antlr4.atn.LexerATNSimulator import LexerATNSimulator as LexerATNSimulator +from antlr4.CommonTokenFactory import CommonTokenFactory as CommonTokenFactory +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + LexerNoViableAltException as LexerNoViableAltException, + RecognitionException as RecognitionException, +) +from antlr4.InputStream import InputStream as InputStream +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.Token import CommonToken, Token as Token + +class TokenSource: ... + +class Lexer(Recognizer, TokenSource): + __slots__ = ( + "_input", + "_output", + "_factory", + "_tokenFactorySourcePair", + "_token", + "_tokenStartCharIndex", + "_tokenStartLine", + "_tokenStartColumn", + "_hitEOF", + "_channel", + "_type", + "_modeStack", + "_mode", + "_text", + ) + DEFAULT_MODE: int + MORE: int + SKIP: int + DEFAULT_TOKEN_CHANNEL: int + HIDDEN: int + MIN_CHAR_VALUE: int + MAX_CHAR_VALUE: int + _input: InputStream + _output: TextIO + _factory: CommonTokenFactory + _tokenFactorySourcePair: tuple[TokenSource, InputStream] + _interp: LexerATNSimulator + _token: Token | None + _tokenStartCharIndex: int + _tokenStartLine: int + _tokenStartColumn: int + _hitEOF: bool + _channel: int + _type: int + _modeStack: list[int] + _mode: int + _text: str | None + def __init__(self, input: InputStream, output: TextIO = ...) -> None: ... + def reset(self) -> None: ... + def nextToken(self) -> Token | None: ... + def skip(self) -> None: ... + def more(self) -> None: ... + def mode(self, m: int) -> None: ... + def pushMode(self, m: int) -> None: ... + def popMode(self) -> int: ... + + @property + def inputStream(self) -> InputStream: ... + @inputStream.setter + def inputStream(self, input: InputStream) -> None: ... + + @property + def sourceName(self) -> str: ... + def emitToken(self, token: Token) -> None: ... + def emit(self) -> CommonToken: ... + def emitEOF(self) -> CommonToken: ... + + @property + def type(self) -> int: ... + @type.setter + def type(self, type: int) -> None: ... + + @property + def line(self) -> int: ... + @line.setter + def line(self, line: int) -> None: ... + + @property + def column(self) -> int: ... + @column.setter + def column(self, column: int) -> None: ... + + def getCharIndex(self) -> int: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, txt: str) -> None: ... + + def getAllTokens(self) -> list[Token]: ... + def notifyListeners(self, e: LexerNoViableAltException) -> None: ... + def getErrorDisplay(self, s: str) -> str: ... + def getErrorDisplayForChar(self, c: str) -> str: ... + def getCharErrorDisplay(self, c: str) -> str: ... + def recover(self, re: RecognitionException) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi b/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi new file mode 100644 index 000000000000..e327864814cc --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ListTokenSource.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenFactory import CommonTokenFactory as CommonTokenFactory +from antlr4.Lexer import TokenSource as TokenSource +from antlr4.Token import Token as Token + +class ListTokenSource(TokenSource): + __slots__ = ("tokens", "sourceName", "pos", "eofToken", "_factory") + tokens: Incomplete + sourceName: Incomplete + pos: int + eofToken: Incomplete + def __init__(self, tokens: list[Token], sourceName: str | None = None) -> None: ... + @property + def column(self): ... + def nextToken(self): ... + @property + def line(self): ... + def getInputStream(self): ... + def getSourceName(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Parser.pyi b/stubs/antlr4-python3-runtime/antlr4/Parser.pyi new file mode 100644 index 000000000000..3e4409dba8af --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Parser.pyi @@ -0,0 +1,99 @@ +from _typeshed import Incomplete +from typing import Literal, TextIO + +from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions as ATNDeserializationOptions +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.atn.ParserATNSimulator import ParserATNSimulator +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.CommonTokenFactory import TokenFactory as TokenFactory +from antlr4.error.Errors import ( + RecognitionException as RecognitionException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.error.ErrorStrategy import DefaultErrorStrategy as DefaultErrorStrategy +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.ParseTreePattern import ParseTreePattern +from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher as ParseTreePatternMatcher +from antlr4.tree.Tree import ErrorNode as ErrorNode, ParseTreeListener as ParseTreeListener, TerminalNode as TerminalNode + +class TraceListener(ParseTreeListener): + __slots__ = "_parser" + def __init__(self, parser) -> None: ... + def enterEveryRule(self, ctx) -> None: ... + def visitTerminal(self, node) -> None: ... + def visitErrorNode(self, node) -> None: ... + def exitEveryRule(self, ctx) -> None: ... + +class Parser(Recognizer): + __slots__ = ( + "_input", + "_output", + "_errHandler", + "_precedenceStack", + "_ctx", + "buildParseTrees", + "_tracer", + "_parseListeners", + "_syntaxErrors", + ) + _input: TokenStream + _output: TextIO + _errHandler: DefaultErrorStrategy + _precedenceStack: list[int] + _ctx: ParserRuleContext | None + _tracer: TraceListener | None + _parseListeners: list[ParseTreeListener] + _syntaxErrors: int + _interp: ParserATNSimulator + bypassAltsAtnCache: dict[Incomplete, Incomplete] + buildParseTrees: bool + def __init__(self, input: TokenStream, output: TextIO = ...) -> None: ... + def reset(self) -> None: ... + def match(self, ttype: int) -> Token: ... + def matchWildcard(self) -> Token: ... + def getParseListeners(self) -> list[ParseTreeListener]: ... + def addParseListener(self, listener: ParseTreeListener) -> None: ... + def removeParseListener(self, listener: ParseTreeListener) -> None: ... + def removeParseListeners(self) -> None: ... + def triggerEnterRuleEvent(self) -> None: ... + def triggerExitRuleEvent(self) -> None: ... + def getNumberOfSyntaxErrors(self) -> int: ... + def getTokenFactory(self) -> TokenFactory: ... + def setTokenFactory(self, factory: TokenFactory) -> None: ... + def getATNWithBypassAlts(self): ... + def compileParseTreePattern(self, pattern: str, patternRuleIndex: int, lexer: Lexer | None = None) -> ParseTreePattern: ... + def getInputStream(self) -> InputStream: ... + def setInputStream(self, input: InputStream) -> None: ... + def getTokenStream(self) -> TokenStream: ... + def setTokenStream(self, input: TokenStream) -> None: ... + def getCurrentToken(self) -> Token | None: ... + def notifyErrorListeners( + self, msg: str, offendingToken: Token | None = None, e: RecognitionException | None = None + ) -> None: ... + def consume(self) -> None: ... + def addContextToParseTree(self) -> None: ... + state: int + def enterRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int) -> None: ... + def exitRule(self) -> None: ... + def enterOuterAlt(self, localctx: ParserRuleContext, altNum: int) -> None: ... + def getPrecedence(self) -> int: ... + def enterRecursionRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int, precedence: int) -> None: ... + def pushNewRecursionContext(self, localctx: ParserRuleContext, state: int, ruleIndex: int) -> None: ... + def unrollRecursionContexts(self, parentCtx: ParserRuleContext) -> None: ... + def getInvokingContext(self, ruleIndex: int) -> RuleContext | None: ... + def precpred(self, localctx: RuleContext, precedence: int) -> bool: ... + def inContext(self, context: str) -> Literal[False]: ... + def isExpectedToken(self, symbol: int) -> bool: ... + def getExpectedTokens(self): ... + def getExpectedTokensWithinCurrentRule(self): ... + def getRuleIndex(self, ruleName: str) -> int: ... + def getRuleInvocationStack(self, p: RuleContext | None = None) -> list[str]: ... + def getDFAStrings(self) -> list[str]: ... + def dumpDFA(self) -> None: ... + def getSourceName(self) -> str: ... + def setTrace(self, trace: bool) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi b/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi new file mode 100644 index 000000000000..121045923a2e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ParserInterpreter.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNState import ATNState as ATNState, LoopEndState as LoopEndState, StarLoopEntryState as StarLoopEntryState +from antlr4.atn.ParserATNSimulator import ParserATNSimulator as ParserATNSimulator +from antlr4.atn.Transition import Transition as Transition +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.dfa.DFA import DFA as DFA +from antlr4.error.Errors import ( + FailedPredicateException as FailedPredicateException, + RecognitionException as RecognitionException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.Lexer import Lexer as Lexer +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import InterpreterRuleContext as InterpreterRuleContext, ParserRuleContext as ParserRuleContext +from antlr4.PredictionContext import PredictionContextCache as PredictionContextCache +from antlr4.Token import Token as Token + +class ParserInterpreter(Parser): + __slots__ = ( + "grammarFileName", + "atn", + "tokenNames", + "ruleNames", + "decisionToDFA", + "sharedContextCache", + "_parentContextStack", + "pushRecursionContextStates", + ) + grammarFileName: str + atn: ATN + tokenNames: list[Incomplete] + ruleNames: list[str] + decisionToDFA: list[DFA] + sharedContextCache: PredictionContextCache + pushRecursionContextStates: set[int] + def __init__( + self, grammarFileName: str, tokenNames: list[str], ruleNames: list[str], atn: ATN, input: TokenStream + ) -> None: ... + state: int + def parse(self, startRuleIndex: int) -> ParserRuleContext | None: ... + def enterRecursionRule(self, localctx: ParserRuleContext, state: int, ruleIndex: int, precedence: int) -> None: ... + def getATNState(self) -> ATNState: ... + def visitState(self, p: ATNState) -> None: ... + def visitRuleStopState(self, p: ATNState) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi b/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi new file mode 100644 index 000000000000..37d5b6c9d36c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/ParserRuleContext.pyi @@ -0,0 +1,49 @@ +from collections.abc import Callable, Generator +from typing import TypeVar + +from antlr4.error.Errors import RecognitionException +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + INVALID_INTERVAL as INVALID_INTERVAL, + ErrorNodeImpl as ErrorNodeImpl, + ParseTree as ParseTree, + ParseTreeListener as ParseTreeListener, + TerminalNode as TerminalNode, + TerminalNodeImpl as TerminalNodeImpl, +) + +class ParserRuleContext(RuleContext): + __slots__ = ("children", "start", "stop", "exception") + children: list[ParseTree | TerminalNode] | None + start: Token | None + stop: Token | None + exception: RecognitionException | None + def __init__(self, parent: ParserRuleContext | None = None, invokingStateNumber: int | None = None) -> None: ... + parentCtx: RuleContext | None + invokingState: int + def copyFrom(self, ctx: ParserRuleContext) -> None: ... + def enterRule(self, listener: ParseTreeListener) -> None: ... + def exitRule(self, listener: ParseTreeListener) -> None: ... + def addChild(self, child: _ParseTreeT) -> _ParseTreeT: ... + def removeLastChild(self) -> None: ... + def addTokenNode(self, token: Token) -> TerminalNodeImpl: ... + def addErrorNode(self, badToken: Token) -> ErrorNodeImpl: ... + def getChild(self, i: int, ttype: type[_GenericType] | None = None) -> _GenericType | None: ... + def getChildren( + self, predicate: Callable[[ParseTree | TerminalNode], bool] | None = None + ) -> Generator[ParseTree | TerminalNode]: ... + def getToken(self, ttype: int, i: int) -> TerminalNode | None: ... + def getTokens(self, ttype: int) -> list[TerminalNode]: ... + def getTypedRuleContext(self, ctxType: type[_ParserRuleContextT], i: int) -> _ParserRuleContextT | None: ... + def getTypedRuleContexts(self, ctxType: type[_ParserRuleContextT]) -> list[_ParserRuleContextT]: ... + def getChildCount(self) -> int: ... + def getSourceInterval(self) -> tuple[int | None, int | None]: ... + +_GenericType = TypeVar("_GenericType", bound=type) +_ParseTreeT = TypeVar("_ParseTreeT", bound=ParseTree) +_ParserRuleContextT = TypeVar("_ParserRuleContextT", bound=ParserRuleContext) + +class InterpreterRuleContext(ParserRuleContext): + ruleIndex: int + def __init__(self, parent: ParserRuleContext, invokingStateNumber: int, ruleIndex: int) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi b/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi new file mode 100644 index 000000000000..e2b27608f629 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/PredictionContext.pyi @@ -0,0 +1,87 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem + +from antlr4.atn.ATN import ATN as ATN +from antlr4.error.Errors import IllegalStateException as IllegalStateException +from antlr4.RuleContext import RuleContext as RuleContext + +class PredictionContext: + EMPTY: Incomplete + EMPTY_RETURN_STATE: int + globalNodeCount: int + id = globalNodeCount # pyrefly: ignore [unknown-name] + cachedHashCode: Incomplete + def __init__(self, cachedHashCode: int) -> None: ... + def __len__(self) -> int: ... + def isEmpty(self): ... + def hasEmptyPath(self): ... + def getReturnState(self, index: int): ... + def __hash__(self): ... + +def calculateHashCode(parent: PredictionContext, returnState: int): ... +def calculateListsHashCode(parents: list[PredictionContext], returnStates: list[int]): ... + +class PredictionContextCache: + cache: Incomplete + def __init__(self) -> None: ... + def add(self, ctx: PredictionContext): ... + def get(self, ctx: PredictionContext): ... + def __len__(self) -> int: ... + +class SingletonPredictionContext(PredictionContext): + @staticmethod + def create(parent: PredictionContext, returnState: int): ... + parentCtx: Incomplete + returnState: Incomplete + def __init__(self, parent: PredictionContext, returnState: int) -> None: ... + def __len__(self) -> int: ... + def getParent(self, index: int): ... + def getReturnState(self, index: int): ... + def __eq__(self, other): ... + def __hash__(self): ... + +class EmptyPredictionContext(SingletonPredictionContext): + def __init__(self) -> None: ... + def isEmpty(self): ... + def __eq__(self, other): ... + def __hash__(self): ... + +class ArrayPredictionContext(PredictionContext): + parents: Incomplete + returnStates: Incomplete + def __init__(self, parents: list[PredictionContext], returnStates: list[int]) -> None: ... + def isEmpty(self): ... + def __len__(self) -> int: ... + def getParent(self, index: int): ... + def getReturnState(self, index: int): ... + def __eq__(self, other): ... + def __hash__(self): ... + +def PredictionContextFromRuleContext(atn: ATN, outerContext: RuleContext | None = None): ... +def merge( + a: PredictionContext, + b: PredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def mergeSingletons( + a: SingletonPredictionContext, + b: SingletonPredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def mergeRoot(a: SingletonPredictionContext, b: SingletonPredictionContext, rootIsWildcard: bool): ... +def mergeArrays( + a: ArrayPredictionContext, + b: ArrayPredictionContext, + rootIsWildcard: bool, + mergeCache: dict[tuple[Incomplete, Incomplete], SingletonPredictionContext] | None, +): ... +def combineCommonParents(parents: SupportsLenAndGetItem[PredictionContext]): ... +def getCachedPredictionContext( + context: PredictionContext, contextCache: PredictionContextCache, visited: dict[PredictionContext, PredictionContext] +): ... +def getAllContextNodes( + context: PredictionContext, + nodes: list[Incomplete] | None = None, + visited: dict[PredictionContext, PredictionContext] | None = None, +): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi b/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi new file mode 100644 index 000000000000..fc0db8acafbc --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Recognizer.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNSimulator import ATNSimulator +from antlr4.error.ErrorListener import ( + ConsoleErrorListener as ConsoleErrorListener, + ErrorListener, + ProxyErrorListener as ProxyErrorListener, +) +from antlr4.error.Errors import RecognitionException +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class Recognizer: + __slots__ = ("_listeners", "_interp", "_stateNumber") + tokenTypeMapCache: dict[Incomplete, int] + ruleIndexMapCache: dict[str, int] + _listeners: list[ErrorListener] + _interp: ATNSimulator | None + _stateNumber: int + def __init__(self) -> None: ... + def extractVersion(self, version: str) -> tuple[str, str]: ... + def checkVersion(self, toolVersion: str) -> None: ... + def addErrorListener(self, listener: ErrorListener) -> None: ... + def removeErrorListener(self, listener: ErrorListener) -> None: ... + def removeErrorListeners(self) -> None: ... + def getTokenTypeMap(self) -> dict[Incomplete, int]: ... + def getRuleIndexMap(self) -> dict[str, int]: ... + def getTokenType(self, tokenName: str) -> int: ... + def getErrorHeader(self, e: RecognitionException) -> str: ... + def getTokenErrorDisplay(self, t: Token | None) -> str: ... + def getErrorListenerDispatch(self) -> ProxyErrorListener: ... + def sempred(self, localctx: RuleContext, ruleIndex: int, actionIndex: int) -> bool: ... + def precpred(self, localctx: RuleContext, precedence: int) -> bool: ... + + @property + def state(self) -> int: ... + @state.setter + def state(self, atnState: int) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi b/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi new file mode 100644 index 000000000000..4edbedb1e6d7 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/RuleContext.pyi @@ -0,0 +1,31 @@ +from collections.abc import Generator +from typing import Any, Literal +from typing_extensions import Self + +from antlr4.Recognizer import Recognizer +from antlr4.tree.Tree import INVALID_INTERVAL as INVALID_INTERVAL, ParseTreeVisitor as ParseTreeVisitor, RuleNode as RuleNode +from antlr4.tree.Trees import Trees as Trees + +Parser: None + +class RuleContext(RuleNode): + __slots__ = ("parentCtx", "invokingState") + EMPTY: RuleContext | None + parentCtx: RuleContext | None + invokingState: int + def __init__(self, parent: RuleContext | None = None, invokingState: int = -1) -> None: ... + def depth(self) -> int: ... + def isEmpty(self) -> bool: ... + def getSourceInterval(self) -> tuple[int | None, int | None]: ... + def getRuleContext(self) -> Self: ... + def getPayload(self) -> Self: ... + def getText(self) -> str: ... + def getRuleIndex(self) -> Literal[-1]: ... + def getAltNumber(self) -> Literal[0]: ... + def setAltNumber(self, altNumber: int) -> None: ... + def getChild(self, i: int) -> Any: ... + def getChildCount(self) -> int: ... + def getChildren(self) -> Generator[Any]: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + def toStringTree(self, ruleNames: list[str] | None = None, recog: Recognizer | None = None) -> str: ... + def toString(self, ruleNames: list[str], stop: RuleContext) -> str: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi b/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi new file mode 100644 index 000000000000..54d3522b9a03 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/StdinStream.pyi @@ -0,0 +1,4 @@ +from antlr4.InputStream import InputStream as InputStream + +class StdinStream(InputStream): + def __init__(self, encoding: str = "ascii", errors: str = "strict") -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Token.pyi b/stubs/antlr4-python3-runtime/antlr4/Token.pyi new file mode 100644 index 000000000000..dc98e1ace2ce --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Token.pyi @@ -0,0 +1,53 @@ +from antlr4.InputStream import InputStream +from antlr4.Lexer import TokenSource + +class Token: + __slots__ = ("source", "type", "channel", "start", "stop", "tokenIndex", "line", "column", "_text") + INVALID_TYPE: int + EPSILON: int + MIN_USER_TOKEN_TYPE: int + EOF: int + DEFAULT_CHANNEL: int + HIDDEN_CHANNEL: int + source: tuple[TokenSource | None, InputStream | None] + type: int + channel: int + start: int + stop: int + tokenIndex: int | None + line: int + column: int + def __init__(self) -> None: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, text: str) -> None: ... + + def getTokenSource(self) -> TokenSource | None: ... + def getInputStream(self) -> InputStream | None: ... + +class CommonToken(Token): + EMPTY_SOURCE: tuple[None, None] + source: tuple[TokenSource | None, InputStream | None] + type: int + channel: int + start: int + stop: int + tokenIndex: int + line: int + column: int + def __init__( + self, + source: tuple[TokenSource | None, InputStream | None] = (None, None), + type: int | None = None, + channel: int = 0, + start: int = -1, + stop: int = -1, + ) -> None: ... + def clone(self) -> CommonToken: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, text: str) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi b/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi new file mode 100644 index 000000000000..81e2601e7be6 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/TokenStreamRewriter.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.Token import Token as Token + +class TokenStreamRewriter: + __slots__ = ("tokens", "programs", "lastRewriteTokenIndexes") + DEFAULT_PROGRAM_NAME: str + PROGRAM_INIT_SIZE: int + MIN_TOKEN_INDEX: int + tokens: Incomplete + programs: Incomplete + lastRewriteTokenIndexes: Incomplete + def __init__(self, tokens) -> None: ... + def getTokenStream(self): ... + def rollback(self, instruction_index, program_name) -> None: ... + def deleteProgram(self, program_name="default") -> None: ... + def insertAfterToken(self, token, text, program_name="default") -> None: ... + def insertAfter(self, index, text, program_name="default") -> None: ... + def insertBeforeIndex(self, index, text) -> None: ... + def insertBeforeToken(self, token, text, program_name="default") -> None: ... + def insertBefore(self, program_name, index, text) -> None: ... + def replaceIndex(self, index, text) -> None: ... + def replaceRange(self, from_idx, to_idx, text) -> None: ... + def replaceSingleToken(self, token, text) -> None: ... + def replaceRangeTokens(self, from_token, to_token, text, program_name="default") -> None: ... + def replace(self, program_name, from_idx, to_idx, text) -> None: ... + def deleteToken(self, token) -> None: ... + def deleteIndex(self, index) -> None: ... + def delete(self, program_name, from_idx, to_idx) -> None: ... + def lastRewriteTokenIndex(self, program_name="default"): ... + def setLastRewriteTokenIndex(self, program_name, i) -> None: ... + def getProgram(self, program_name): ... + def getDefaultText(self): ... + def getText(self, program_name, start: int, stop: int): ... + + class RewriteOperation: + __slots__ = ("tokens", "index", "text", "instructionIndex") + tokens: Incomplete + index: Incomplete + text: Incomplete + instructionIndex: int + def __init__(self, tokens, index, text: str = "") -> None: ... + def execute(self, buf): ... + + class InsertBeforeOp(RewriteOperation): + def __init__(self, tokens, index, text: str = "") -> None: ... + def execute(self, buf): ... + + class InsertAfterOp(InsertBeforeOp): ... + + class ReplaceOp(RewriteOperation): + __slots__ = "last_index" + last_index: Incomplete + def __init__(self, from_idx, to_idx, tokens, text) -> None: ... + def execute(self, buf): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/Utils.pyi b/stubs/antlr4-python3-runtime/antlr4/Utils.pyi new file mode 100644 index 000000000000..6c0130df5642 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/Utils.pyi @@ -0,0 +1,2 @@ +def str_list(val) -> str: ... +def escapeWhitespace(s: str, escapeSpaces: bool): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/__init__.pyi new file mode 100644 index 000000000000..7d6894a50a79 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/__init__.pyi @@ -0,0 +1,32 @@ +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.atn.LexerATNSimulator import LexerATNSimulator as LexerATNSimulator +from antlr4.atn.ParserATNSimulator import ParserATNSimulator as ParserATNSimulator +from antlr4.atn.PredictionMode import PredictionMode as PredictionMode +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.dfa.DFA import DFA as DFA +from antlr4.error.DiagnosticErrorListener import DiagnosticErrorListener as DiagnosticErrorListener +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + NoViableAltException as NoViableAltException, + RecognitionException as RecognitionException, +) +from antlr4.error.ErrorStrategy import BailErrorStrategy as BailErrorStrategy +from antlr4.FileStream import FileStream as FileStream +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext, RuleContext as RuleContext +from antlr4.PredictionContext import PredictionContextCache as PredictionContextCache +from antlr4.StdinStream import StdinStream as StdinStream +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + ErrorNode as ErrorNode, + ParseTreeListener as ParseTreeListener, + ParseTreeVisitor as ParseTreeVisitor, + ParseTreeWalker as ParseTreeWalker, + RuleNode as RuleNode, + TerminalNode as TerminalNode, +) +from antlr4.Utils import str_list as str_list diff --git a/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi b/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi new file mode 100644 index 000000000000..c45632a1e4d1 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/_pygrun.pyi @@ -0,0 +1,4 @@ +from antlr4 import * + +def beautify_lisp_string(in_string): ... +def main() -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi new file mode 100644 index 000000000000..f0951194380c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATN.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState +from antlr4.atn.ATNType import ATNType as ATNType +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token + +class ATN: + __slots__ = ( + "grammarType", + "maxTokenType", + "states", + "decisionToState", + "ruleToStartState", + "ruleToStopState", + "modeNameToStartState", + "ruleToTokenType", + "lexerActions", + "modeToStartState", + ) + INVALID_ALT_NUMBER: int + grammarType: Incomplete + maxTokenType: Incomplete + states: Incomplete + decisionToState: Incomplete + ruleToStartState: Incomplete + ruleToStopState: Incomplete + modeNameToStartState: Incomplete + ruleToTokenType: Incomplete + lexerActions: Incomplete + modeToStartState: Incomplete + def __init__(self, grammarType: ATNType, maxTokenType: int) -> None: ... + def nextTokensInContext(self, s: ATNState, ctx: RuleContext): ... + def nextTokensNoContext(self, s: ATNState): ... + def nextTokens(self, s: ATNState, ctx: RuleContext | None = None): ... + def addState(self, state: ATNState): ... + def removeState(self, state: ATNState): ... + def defineDecisionState(self, s: DecisionState): ... + def getDecisionState(self, decision: int): ... + def getExpectedTokens(self, stateNumber: int, ctx: RuleContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi new file mode 100644 index 000000000000..12046c969e40 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfig.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState +from antlr4.atn.LexerActionExecutor import LexerActionExecutor as LexerActionExecutor +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext +from antlr4.PredictionContext import PredictionContext as PredictionContext + +class ATNConfig: + __slots__ = ("state", "alt", "context", "semanticContext", "reachesIntoOuterContext", "precedenceFilterSuppressed") + state: Incomplete + alt: Incomplete + context: Incomplete + semanticContext: Incomplete + reachesIntoOuterContext: Incomplete + precedenceFilterSuppressed: Incomplete + def __init__( + self, + state: ATNState | None = None, + alt: int | None = None, + context: PredictionContext | None = None, + semantic: SemanticContext | None = None, + config: ATNConfig | None = None, + ) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def hashCodeForConfigSet(self): ... + def equalsForConfigSet(self, other): ... + +class LexerATNConfig(ATNConfig): + __slots__ = ("lexerActionExecutor", "passedThroughNonGreedyDecision") + lexerActionExecutor: Incomplete + passedThroughNonGreedyDecision: Incomplete + def __init__( + self, + state: ATNState, + alt: int | None = None, + context: PredictionContext | None = None, + semantic: SemanticContext = ..., + lexerActionExecutor: LexerActionExecutor | None = None, + config: LexerATNConfig | None = None, + ) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + def hashCodeForConfigSet(self): ... + def equalsForConfigSet(self, other): ... + def checkNonGreedyDecision(self, source: LexerATNConfig, target: ATNState): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi new file mode 100644 index 000000000000..aa82c295ce57 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNConfigSet.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext +from antlr4.error.Errors import ( + IllegalStateException as IllegalStateException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.PredictionContext import merge as merge +from antlr4.Utils import str_list as str_list + +ATNSimulator: Incomplete + +class ATNConfigSet: + __slots__ = ( + "configLookup", + "fullCtx", + "readonly", + "configs", + "uniqueAlt", + "conflictingAlts", + "hasSemanticContext", + "dipsIntoOuterContext", + "cachedHashCode", + ) + configLookup: Incomplete + fullCtx: Incomplete + readonly: bool + configs: Incomplete + uniqueAlt: int + conflictingAlts: Incomplete + hasSemanticContext: bool + dipsIntoOuterContext: bool + cachedHashCode: int + def __init__(self, fullCtx: bool = True) -> None: ... + def __iter__(self): ... + def add(self, config: ATNConfig, mergeCache=None): ... + def getOrAdd(self, config: ATNConfig): ... + def getStates(self): ... + def getPredicates(self): ... + def get(self, i: int): ... + def optimizeConfigs(self, interpreter: ATNSimulator): ... + def addAll(self, coll: list[Incomplete]): ... + def __eq__(self, other): ... + def __hash__(self): ... + def hashConfigs(self): ... + def __len__(self) -> int: ... + def isEmpty(self): ... + def __contains__(self, config) -> bool: ... + def clear(self) -> None: ... + def setReadonly(self, readonly: bool): ... + +class OrderedATNConfigSet(ATNConfigSet): + def __init__(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi new file mode 100644 index 000000000000..9a2021cd7d67 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializationOptions.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +class ATNDeserializationOptions: + __slots__ = ("readonly", "verifyATN", "generateRuleBypassTransitions") + defaultOptions: Incomplete + readonly: bool + verifyATN: Incomplete + generateRuleBypassTransitions: Incomplete + def __init__(self, copyFrom: ATNDeserializationOptions | None = None) -> None: ... + def __setattr__(self, key, value) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi new file mode 100644 index 000000000000..ed6b48bf8f84 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNDeserializer.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNDeserializationOptions import ATNDeserializationOptions as ATNDeserializationOptions +from antlr4.atn.ATNState import * +from antlr4.atn.ATNType import ATNType as ATNType +from antlr4.atn.LexerAction import * +from antlr4.atn.Transition import * +from antlr4.Token import Token as Token + +SERIALIZED_VERSION: int + +class ATNDeserializer: + __slots__ = ("deserializationOptions", "data", "pos") + deserializationOptions: Incomplete + def __init__(self, options: ATNDeserializationOptions | None = None) -> None: ... + data: Incomplete + pos: int + def deserialize(self, data: list[int]): ... + def checkVersion(self) -> None: ... + def readATN(self): ... + def readStates(self, atn: ATN): ... + def readRules(self, atn: ATN): ... + def readModes(self, atn: ATN): ... + def readSets(self, atn: ATN, sets: list[Incomplete]): ... + def readEdges(self, atn: ATN, sets: list[Incomplete]): ... + def readDecisions(self, atn: ATN): ... + def readLexerActions(self, atn: ATN): ... + def generateRuleBypassTransitions(self, atn: ATN): ... + def generateRuleBypassTransition(self, atn: ATN, idx: int): ... + def stateIsEndStateFor(self, state: ATNState, idx: int): ... + def markPrecedenceDecisions(self, atn: ATN): ... + def verifyATN(self, atn: ATN): ... + def checkCondition(self, condition: bool, message=None): ... + def readInt(self): ... + edgeFactories: Incomplete + def edgeFactory(self, atn: ATN, type: int, src: int, trg: int, arg1: int, arg2: int, arg3: int, sets: list[Incomplete]): ... + stateFactories: Incomplete + def stateFactory(self, type: int, ruleIndex: int): ... + CHANNEL: int + CUSTOM: int + MODE: int + MORE: int + POP_MODE: int + PUSH_MODE: int + SKIP: int + TYPE: int + actionFactories: Incomplete + def lexerActionFactory(self, type: int, data1: int, data2: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi new file mode 100644 index 000000000000..2ca0b846e9c9 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNSimulator.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + getCachedPredictionContext as getCachedPredictionContext, +) + +class ATNSimulator: + __slots__ = ("atn", "sharedContextCache", "__dict__") + ERROR: Incomplete + atn: Incomplete + sharedContextCache: Incomplete + def __init__(self, atn: ATN, sharedContextCache: PredictionContextCache) -> None: ... + def getCachedContext(self, context: PredictionContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi new file mode 100644 index 000000000000..5b432fa26026 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNState.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete + +from antlr4.atn.Transition import Transition as Transition + +INITIAL_NUM_TRANSITIONS: int + +class ATNState: + __slots__ = ("atn", "stateNumber", "stateType", "ruleIndex", "epsilonOnlyTransitions", "transitions", "nextTokenWithinRule") + INVALID_TYPE: int + BASIC: int + RULE_START: int + BLOCK_START: int + PLUS_BLOCK_START: int + STAR_BLOCK_START: int + TOKEN_START: int + RULE_STOP: int + BLOCK_END: int + STAR_LOOP_BACK: int + STAR_LOOP_ENTRY: int + PLUS_LOOP_BACK: int + LOOP_END: int + serializationNames: Incomplete + INVALID_STATE_NUMBER: int + atn: Incomplete + stateNumber: Incomplete + stateType: Incomplete + ruleIndex: int + epsilonOnlyTransitions: bool + transitions: Incomplete + nextTokenWithinRule: Incomplete + def __init__(self) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + def onlyHasEpsilonTransitions(self): ... + def isNonGreedyExitState(self): ... + def addTransition(self, trans: Transition, index: int = -1): ... + +class BasicState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class DecisionState(ATNState): + __slots__ = ("decision", "nonGreedy") + decision: int + nonGreedy: bool + def __init__(self) -> None: ... + +class BlockStartState(DecisionState): + __slots__ = "endState" + endState: Incomplete + def __init__(self) -> None: ... + +class BasicBlockStartState(BlockStartState): + stateType: Incomplete + def __init__(self) -> None: ... + +class BlockEndState(ATNState): + __slots__ = "startState" + stateType: Incomplete + startState: Incomplete + def __init__(self) -> None: ... + +class RuleStopState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class RuleStartState(ATNState): + __slots__ = ("stopState", "isPrecedenceRule") + stateType: Incomplete + stopState: Incomplete + isPrecedenceRule: bool + def __init__(self) -> None: ... + +class PlusLoopbackState(DecisionState): + stateType: Incomplete + def __init__(self) -> None: ... + +class PlusBlockStartState(BlockStartState): + __slots__ = "loopBackState" + stateType: Incomplete + loopBackState: Incomplete + def __init__(self) -> None: ... + +class StarBlockStartState(BlockStartState): + stateType: Incomplete + def __init__(self) -> None: ... + +class StarLoopbackState(ATNState): + stateType: Incomplete + def __init__(self) -> None: ... + +class StarLoopEntryState(DecisionState): + __slots__ = ("loopBackState", "isPrecedenceDecision") + stateType: Incomplete + loopBackState: Incomplete + isPrecedenceDecision: Incomplete + def __init__(self) -> None: ... + +class LoopEndState(ATNState): + __slots__ = "loopBackState" + stateType: Incomplete + loopBackState: Incomplete + def __init__(self) -> None: ... + +class TokensStartState(DecisionState): + stateType: Incomplete + def __init__(self) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi new file mode 100644 index 000000000000..5260cdf242d3 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ATNType.pyi @@ -0,0 +1,7 @@ +from enum import IntEnum + +class ATNType(IntEnum): + LEXER = 0 + PARSER = 1 + @classmethod + def fromOrdinal(cls, i: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi new file mode 100644 index 000000000000..0a00ea8445ff --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerATNSimulator.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import LexerATNConfig as LexerATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet, OrderedATNConfigSet as OrderedATNConfigSet +from antlr4.atn.ATNSimulator import ATNSimulator as ATNSimulator +from antlr4.atn.ATNState import ATNState as ATNState, RuleStopState as RuleStopState +from antlr4.atn.LexerActionExecutor import LexerActionExecutor as LexerActionExecutor +from antlr4.atn.Transition import Transition as Transition +from antlr4.dfa.DFA import DFA +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.error.Errors import ( + LexerNoViableAltException as LexerNoViableAltException, + UnsupportedOperationException as UnsupportedOperationException, +) +from antlr4.InputStream import InputStream as InputStream +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.Token import Token as Token + +class SimState: + __slots__ = ("index", "line", "column", "dfaState") + def __init__(self) -> None: ... + index: int + line: int + column: int + dfaState: Incomplete + def reset(self) -> None: ... + +class LexerATNSimulator(ATNSimulator): + __slots__ = ("decisionToDFA", "recog", "startIndex", "line", "column", "mode", "DEFAULT_MODE", "MAX_CHAR_VALUE", "prevAccept") + debug: bool + dfa_debug: bool + MIN_DFA_EDGE: int + MAX_DFA_EDGE: int + ERROR: Incomplete + decisionToDFA: Incomplete + recog: Incomplete + startIndex: int + line: int + column: int + mode: Incomplete + DEFAULT_MODE: Incomplete + MAX_CHAR_VALUE: Incomplete + prevAccept: Incomplete + def __init__(self, recog, atn: ATN, decisionToDFA: list[DFA], sharedContextCache: PredictionContextCache) -> None: ... + def copyState(self, simulator: LexerATNSimulator): ... + def match(self, input: InputStream, mode: int): ... + def reset(self) -> None: ... + def matchATN(self, input: InputStream): ... + def execATN(self, input: InputStream, ds0: DFAState): ... + def getExistingTargetState(self, s: DFAState, t: int): ... + def computeTargetState(self, input: InputStream, s: DFAState, t: int): ... + def failOrAccept(self, prevAccept: SimState, input: InputStream, reach: ATNConfigSet, t: int): ... + def getReachableConfigSet(self, input: InputStream, closure: ATNConfigSet, reach: ATNConfigSet, t: int): ... + def accept( + self, input: InputStream, lexerActionExecutor: LexerActionExecutor, startIndex: int, index: int, line: int, charPos: int + ): ... + def getReachableTarget(self, trans: Transition, t: int): ... + def computeStartState(self, input: InputStream, p: ATNState): ... + def closure( + self, + input: InputStream, + config: LexerATNConfig, + configs: ATNConfigSet, + currentAltReachedAcceptState: bool, + speculative: bool, + treatEofAsEpsilon: bool, + ): ... + def getEpsilonTarget( + self, + input: InputStream, + config: LexerATNConfig, + t: Transition, + configs: ATNConfigSet, + speculative: bool, + treatEofAsEpsilon: bool, + ): ... + def evaluatePredicate(self, input: InputStream, ruleIndex: int, predIndex: int, speculative: bool): ... + def captureSimState(self, settings: SimState, input: InputStream, dfaState: DFAState): ... + def addDFAEdge(self, from_: DFAState, tk: int, to: DFAState | None = None, cfgs: ATNConfigSet | None = None) -> DFAState: ... + def addDFAState(self, configs: ATNConfigSet) -> DFAState: ... + def getDFA(self, mode: int): ... + def getText(self, input: InputStream): ... + def consume(self, input: InputStream): ... + def getTokenName(self, t: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi new file mode 100644 index 000000000000..255a96f31eb8 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerAction.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete +from enum import IntEnum + +Lexer: Incomplete + +class LexerActionType(IntEnum): + CHANNEL = 0 + CUSTOM = 1 + MODE = 2 + MORE = 3 + POP_MODE = 4 + PUSH_MODE = 5 + SKIP = 6 + TYPE = 7 + +class LexerAction: + __slots__ = ("actionType", "isPositionDependent") + actionType: Incomplete + isPositionDependent: bool + def __init__(self, action: LexerActionType) -> None: ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerSkipAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerTypeAction(LexerAction): + __slots__ = "type" + type: Incomplete + def __init__(self, type: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerPushModeAction(LexerAction): + __slots__ = "mode" + mode: Incomplete + def __init__(self, mode: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerPopModeAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerMoreAction(LexerAction): + INSTANCE: Incomplete + def __init__(self) -> None: ... + def execute(self, lexer: Lexer): ... + +class LexerModeAction(LexerAction): + __slots__ = "mode" + mode: Incomplete + def __init__(self, mode: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerCustomAction(LexerAction): + __slots__ = ("ruleIndex", "actionIndex") + ruleIndex: Incomplete + actionIndex: Incomplete + isPositionDependent: bool + def __init__(self, ruleIndex: int, actionIndex: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerChannelAction(LexerAction): + __slots__ = "channel" + channel: Incomplete + def __init__(self, channel: int) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class LexerIndexedCustomAction(LexerAction): + __slots__ = ("offset", "action") + offset: Incomplete + action: Incomplete + isPositionDependent: bool + def __init__(self, offset: int, action: LexerAction) -> None: ... + def execute(self, lexer: Lexer): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi new file mode 100644 index 000000000000..ff09dd23e400 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/LexerActionExecutor.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from antlr4.atn.LexerAction import LexerAction as LexerAction, LexerIndexedCustomAction as LexerIndexedCustomAction +from antlr4.InputStream import InputStream as InputStream + +class LexerActionExecutor: + __slots__ = ("lexerActions", "hashCode") + lexerActions: Incomplete + hashCode: Incomplete + def __init__(self, lexerActions: list[LexerAction] = []) -> None: ... + @staticmethod + def append(lexerActionExecutor: LexerActionExecutor, lexerAction: LexerAction): ... + def fixOffsetBeforeMatch(self, offset: int): ... + def execute(self, lexer, input: InputStream, startIndex: int): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi new file mode 100644 index 000000000000..aa990870ce3c --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/ParserATNSimulator.pyi @@ -0,0 +1,134 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNSimulator import ATNSimulator as ATNSimulator +from antlr4.atn.ATNState import ATNState as ATNState, DecisionState as DecisionState, RuleStopState as RuleStopState +from antlr4.atn.PredictionMode import PredictionMode as PredictionMode +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext, andContext as andContext, orContext as orContext +from antlr4.atn.Transition import ( + ActionTransition as ActionTransition, + AtomTransition as AtomTransition, + NotSetTransition as NotSetTransition, + PrecedencePredicateTransition as PrecedencePredicateTransition, + PredicateTransition as PredicateTransition, + RuleTransition as RuleTransition, + SetTransition as SetTransition, + Transition as Transition, +) +from antlr4.BufferedTokenStream import TokenStream as TokenStream +from antlr4.dfa.DFAState import DFAState as DFAState, PredPrediction as PredPrediction +from antlr4.error.Errors import NoViableAltException as NoViableAltException +from antlr4.Parser import Parser as Parser +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.PredictionContext import ( + PredictionContext as PredictionContext, + PredictionContextCache as PredictionContextCache, + PredictionContextFromRuleContext as PredictionContextFromRuleContext, + SingletonPredictionContext as SingletonPredictionContext, +) +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.Utils import str_list as str_list + +class ParserATNSimulator(ATNSimulator): + __slots__ = ("parser", "decisionToDFA", "predictionMode", "_input", "_startIndex", "_outerContext", "_dfa", "mergeCache") + debug: bool + trace_atn_sim: bool + dfa_debug: bool + retry_debug: bool + parser: Incomplete + decisionToDFA: Incomplete + predictionMode: Incomplete + mergeCache: Incomplete + def __init__( + self, parser: Parser, atn: ATN, decisionToDFA: list[DFA], sharedContextCache: PredictionContextCache + ) -> None: ... + def reset(self) -> None: ... + def adaptivePredict(self, input: TokenStream, decision: int, outerContext: ParserRuleContext): ... + def execATN(self, dfa: DFA, s0: DFAState, input: TokenStream, startIndex: int, outerContext: ParserRuleContext): ... + def getExistingTargetState(self, previousD: DFAState, t: int): ... + def computeTargetState(self, dfa: DFA, previousD: DFAState, t: int): ... + def predicateDFAState(self, dfaState: DFAState, decisionState: DecisionState): ... + def execATNWithFullContext( + self, dfa: DFA, D: DFAState, s0: ATNConfigSet, input: TokenStream, startIndex: int, outerContext: ParserRuleContext + ): ... + def computeReachSet(self, closure: ATNConfigSet, t: int, fullCtx: bool): ... + def removeAllConfigsNotInRuleStopState(self, configs: ATNConfigSet, lookToEndOfRule: bool): ... + def computeStartState(self, p: ATNState, ctx: RuleContext, fullCtx: bool): ... + def applyPrecedenceFilter(self, configs: ATNConfigSet): ... + def getReachableTarget(self, trans: Transition, ttype: int): ... + def getPredsForAmbigAlts(self, ambigAlts: set[int], configs: ATNConfigSet, nalts: int): ... + def getPredicatePredictions(self, ambigAlts: set[int], altToPred: list[int]): ... + def getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule(self, configs: ATNConfigSet, outerContext: ParserRuleContext): ... + def getAltThatFinishedDecisionEntryRule(self, configs: ATNConfigSet): ... + def splitAccordingToSemanticValidity(self, configs: ATNConfigSet, outerContext: ParserRuleContext): ... + def evalSemanticContext(self, predPredictions: list[Incomplete], outerContext: ParserRuleContext, complete: bool): ... + def closure( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + treatEofAsEpsilon: bool, + ): ... + def closureCheckingStopState( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + depth: int, + treatEofAsEpsilon: bool, + ): ... + def closure_( + self, + config: ATNConfig, + configs: ATNConfigSet, + closureBusy: set[Incomplete], + collectPredicates: bool, + fullCtx: bool, + depth: int, + treatEofAsEpsilon: bool, + ): ... + def canDropLoopEntryEdgeInLeftRecursiveRule(self, config): ... + def getRuleName(self, index: int): ... + epsilonTargetMethods: Incomplete + def getEpsilonTarget( + self, config: ATNConfig, t: Transition, collectPredicates: bool, inContext: bool, fullCtx: bool, treatEofAsEpsilon: bool + ): ... + def actionTransition(self, config: ATNConfig, t: ActionTransition): ... + def precedenceTransition( + self, config: ATNConfig, pt: PrecedencePredicateTransition, collectPredicates: bool, inContext: bool, fullCtx: bool + ): ... + def predTransition( + self, config: ATNConfig, pt: PredicateTransition, collectPredicates: bool, inContext: bool, fullCtx: bool + ): ... + def ruleTransition(self, config: ATNConfig, t: RuleTransition): ... + def getConflictingAlts(self, configs: ATNConfigSet): ... + def getConflictingAltsOrUniqueAlt(self, configs: ATNConfigSet): ... + def getTokenName(self, t: int): ... + def getLookaheadName(self, input: TokenStream): ... + def dumpDeadEndConfigs(self, nvae: NoViableAltException): ... + def noViableAlt(self, input: TokenStream, outerContext: ParserRuleContext, configs: ATNConfigSet, startIndex: int): ... + def getUniqueAlt(self, configs: ATNConfigSet): ... + def addDFAEdge(self, dfa: DFA, from_: DFAState, t: int, to: DFAState): ... + def addDFAState(self, dfa: DFA, D: DFAState): ... + def reportAttemptingFullContext( + self, dfa: DFA, conflictingAlts: set[Incomplete], configs: ATNConfigSet, startIndex: int, stopIndex: int + ): ... + def reportContextSensitivity(self, dfa: DFA, prediction: int, configs: ATNConfigSet, startIndex: int, stopIndex: int): ... + def reportAmbiguity( + self, + dfa: DFA, + D: DFAState, + startIndex: int, + stopIndex: int, + exact: bool, + ambigAlts: set[Incomplete], + configs: ATNConfigSet, + ): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi new file mode 100644 index 000000000000..68fc4601bf91 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/PredictionMode.pyi @@ -0,0 +1,41 @@ +from collections.abc import Sequence +from enum import Enum + +from antlr4.atn.ATN import ATN as ATN +from antlr4.atn.ATNConfig import ATNConfig as ATNConfig +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNState import RuleStopState as RuleStopState +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext + +class PredictionMode(Enum): + SLL = 0 + LL = 1 + LL_EXACT_AMBIG_DETECTION = 2 + @classmethod + def hasSLLConflictTerminatingPrediction(cls, mode: PredictionMode, configs: ATNConfigSet): ... + @classmethod + def hasConfigInRuleStopState(cls, configs: ATNConfigSet): ... + @classmethod + def allConfigsInRuleStopStates(cls, configs: ATNConfigSet): ... + @classmethod + def resolvesToJustOneViableAlt(cls, altsets: Sequence[set[int]]): ... + @classmethod + def allSubsetsConflict(cls, altsets: Sequence[set[int]]): ... + @classmethod + def hasNonConflictingAltSet(cls, altsets: Sequence[set[int]]): ... + @classmethod + def hasConflictingAltSet(cls, altsets: Sequence[set[int]]): ... + @classmethod + def allSubsetsEqual(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getUniqueAlt(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getAlts(cls, altsets: Sequence[set[int]]): ... + @classmethod + def getConflictingAltSubsets(cls, configs: ATNConfigSet): ... + @classmethod + def getStateToAltMap(cls, configs: ATNConfigSet): ... + @classmethod + def hasStateAssociatedWithOneAlt(cls, configs: ATNConfigSet): ... + @classmethod + def getSingleViableAlt(cls, altsets: Sequence[set[int]]): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi new file mode 100644 index 000000000000..01f9acf5b0af --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/SemanticContext.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete + +from antlr4.Recognizer import Recognizer as Recognizer +from antlr4.RuleContext import RuleContext as RuleContext + +class SemanticContext: + NONE: Incomplete + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + +def andContext(a: SemanticContext, b: SemanticContext): ... +def orContext(a: SemanticContext, b: SemanticContext): ... +def filterPrecedencePredicates(collection: set[SemanticContext]): ... + +class EmptySemanticContext(SemanticContext): ... + +class Predicate(SemanticContext): + __slots__ = ("ruleIndex", "predIndex", "isCtxDependent") + ruleIndex: Incomplete + predIndex: Incomplete + isCtxDependent: Incomplete + def __init__(self, ruleIndex: int = -1, predIndex: int = -1, isCtxDependent: bool = False) -> None: ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class PrecedencePredicate(SemanticContext): + precedence: Incomplete + def __init__(self, precedence: int = 0) -> None: ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + def __lt__(self, other): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class AND(SemanticContext): + __slots__ = "opnds" + opnds: Incomplete + def __init__(self, a: SemanticContext, b: SemanticContext) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... + +class OR(SemanticContext): + __slots__ = "opnds" + opnds: Incomplete + def __init__(self, a: SemanticContext, b: SemanticContext) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + def eval(self, parser: Recognizer, outerContext: RuleContext): ... + def evalPrecedence(self, parser: Recognizer, outerContext: RuleContext): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi new file mode 100644 index 000000000000..608da7480780 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/atn/Transition.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import RuleStartState +from antlr4.IntervalSet import IntervalSet + +class Transition: + __slots__ = ("target", "isEpsilon", "label") + EPSILON: int + RANGE: int + RULE: int + PREDICATE: int + ATOM: int + ACTION: int + SET: int + NOT_SET: int + WILDCARD: int + PRECEDENCE: int + serializationNames: Incomplete + serializationTypes: Incomplete + target: Incomplete + isEpsilon: bool + label: Incomplete + def __init__(self, target) -> None: ... + +class AtomTransition(Transition): + __slots__ = ("label_", "serializationType") + label_: Incomplete + label: Incomplete + serializationType: Incomplete + def __init__(self, target, label: int) -> None: ... + def makeLabel(self): ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class RuleTransition(Transition): + __slots__ = ("ruleIndex", "precedence", "followState", "serializationType") + ruleIndex: Incomplete + precedence: Incomplete + followState: Incomplete + serializationType: Incomplete + isEpsilon: bool + def __init__(self, ruleStart: RuleStartState, ruleIndex: int, precedence: int, followState) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class EpsilonTransition(Transition): + __slots__ = ("serializationType", "outermostPrecedenceReturn") + serializationType: Incomplete + isEpsilon: bool + outermostPrecedenceReturn: Incomplete + def __init__(self, target, outermostPrecedenceReturn: int = -1) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class RangeTransition(Transition): + __slots__ = ("serializationType", "start", "stop") + serializationType: Incomplete + start: Incomplete + stop: Incomplete + label: Incomplete + def __init__(self, target, start: int, stop: int) -> None: ... + def makeLabel(self): ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class AbstractPredicateTransition(Transition): + def __init__(self, target) -> None: ... + +class PredicateTransition(AbstractPredicateTransition): + __slots__ = ("serializationType", "ruleIndex", "predIndex", "isCtxDependent") + serializationType: Incomplete + ruleIndex: Incomplete + predIndex: Incomplete + isCtxDependent: Incomplete + isEpsilon: bool + def __init__(self, target, ruleIndex: int, predIndex: int, isCtxDependent: bool) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + def getPredicate(self): ... + +class ActionTransition(Transition): + __slots__ = ("serializationType", "ruleIndex", "actionIndex", "isCtxDependent") + serializationType: Incomplete + ruleIndex: Incomplete + actionIndex: Incomplete + isCtxDependent: Incomplete + isEpsilon: bool + def __init__(self, target, ruleIndex: int, actionIndex: int = -1, isCtxDependent: bool = False) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class SetTransition(Transition): + __slots__ = "serializationType" + serializationType: Incomplete + label: Incomplete + def __init__(self, target, set: IntervalSet) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class NotSetTransition(SetTransition): + serializationType: Incomplete + def __init__(self, target, set: IntervalSet) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class WildcardTransition(Transition): + __slots__ = "serializationType" + serializationType: Incomplete + def __init__(self, target) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + +class PrecedencePredicateTransition(AbstractPredicateTransition): + __slots__ = ("serializationType", "precedence") + serializationType: Incomplete + precedence: Incomplete + isEpsilon: bool + def __init__(self, target, precedence: int) -> None: ... + def matches(self, symbol: int, minVocabSymbol: int, maxVocabSymbol: int): ... + def getPredicate(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/atn/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/atn/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi new file mode 100644 index 000000000000..b18b49cb941d --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFA.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.ATNState import DecisionState as DecisionState, StarLoopEntryState as StarLoopEntryState +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.error.Errors import IllegalStateException as IllegalStateException + +class DFA: + __slots__ = ("atnStartState", "decision", "_states", "s0", "precedenceDfa") + atnStartState: Incomplete + decision: Incomplete + s0: Incomplete + precedenceDfa: bool + def __init__(self, atnStartState: DecisionState, decision: int = 0) -> None: ... + def getPrecedenceStartState(self, precedence: int): ... + def setPrecedenceStartState(self, precedence: int, startState: DFAState): ... + def setPrecedenceDfa(self, precedenceDfa: bool): ... + @property + def states(self): ... + def sortedStates(self): ... + def toString(self, literalNames: list[str] | None = None, symbolicNames: list[str] | None = None): ... + def toLexerString(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi new file mode 100644 index 000000000000..efd431df7eaf --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFASerializer.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.dfa.DFAState import DFAState as DFAState +from antlr4.Utils import str_list as str_list + +class DFASerializer: + __slots__ = ("dfa", "literalNames", "symbolicNames") + dfa: Incomplete + literalNames: list[str] | None + symbolicNames: list[str] | None + def __init__(self, dfa: DFA, literalNames: list[str] | None = None, symbolicNames: list[str] | None = None) -> None: ... + def getEdgeLabel(self, i: int): ... + def getStateString(self, s: DFAState): ... + +class LexerDFASerializer(DFASerializer): + def __init__(self, dfa: DFA) -> None: ... + def getEdgeLabel(self, i: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi new file mode 100644 index 000000000000..55eff18b7840 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/dfa/DFAState.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.atn.SemanticContext import SemanticContext as SemanticContext + +class PredPrediction: + __slots__ = ("alt", "pred") + alt: Incomplete + pred: Incomplete + def __init__(self, pred: SemanticContext, alt: int) -> None: ... + +class DFAState: + __slots__ = ( + "stateNumber", + "configs", + "edges", + "isAcceptState", + "prediction", + "lexerActionExecutor", + "requiresFullContext", + "predicates", + ) + stateNumber: Incomplete + configs: Incomplete + edges: Incomplete + isAcceptState: bool + prediction: int + lexerActionExecutor: Incomplete + requiresFullContext: bool + predicates: Incomplete + def __init__(self, stateNumber: int = -1, configs: ATNConfigSet = ...) -> None: ... + def getAltSet(self): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/dfa/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/dfa/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi b/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi new file mode 100644 index 000000000000..750c04100245 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/DiagnosticErrorListener.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from antlr4 import DFA as DFA +from antlr4.atn.ATNConfigSet import ATNConfigSet as ATNConfigSet +from antlr4.error.ErrorListener import ErrorListener as ErrorListener + +class DiagnosticErrorListener(ErrorListener): + exactOnly: Incomplete + def __init__(self, exactOnly: bool = True) -> None: ... + def reportAmbiguity( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, exact: bool, ambigAlts: set[int], configs: ATNConfigSet + ): ... + def reportAttemptingFullContext( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, conflictingAlts: set[int], configs: ATNConfigSet + ): ... + def reportContextSensitivity( + self, recognizer, dfa: DFA, startIndex: int, stopIndex: int, prediction: int, configs: ATNConfigSet + ): ... + def getDecisionDescription(self, recognizer, dfa: DFA): ... + def getConflictingAlts(self, reportedAlts: set[int], configs: ATNConfigSet): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi b/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi new file mode 100644 index 000000000000..34482bde9131 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/ErrorListener.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +class ErrorListener: + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) -> None: ... + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) -> None: ... + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs) -> None: ... + +class ConsoleErrorListener(ErrorListener): + INSTANCE: Incomplete + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + +class ProxyErrorListener(ErrorListener): + delegates: Incomplete + def __init__(self, delegates) -> None: ... + def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e) -> None: ... + def reportAmbiguity(self, recognizer, dfa, startIndex, stopIndex, exact, ambigAlts, configs) -> None: ... + def reportAttemptingFullContext(self, recognizer, dfa, startIndex, stopIndex, conflictingAlts, configs) -> None: ... + def reportContextSensitivity(self, recognizer, dfa, startIndex, stopIndex, prediction, configs) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi b/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi new file mode 100644 index 000000000000..cde0e754c0d8 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/ErrorStrategy.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from antlr4.atn.ATNState import ATNState as ATNState +from antlr4.error.Errors import ( + FailedPredicateException as FailedPredicateException, + InputMismatchException as InputMismatchException, + NoViableAltException as NoViableAltException, + ParseCancellationException as ParseCancellationException, + RecognitionException as RecognitionException, +) +from antlr4.IntervalSet import IntervalSet as IntervalSet +from antlr4.Token import Token as Token + +class ErrorStrategy: + def reset(self, recognizer): ... + def recoverInline(self, recognizer): ... + def recover(self, recognizer, e: RecognitionException): ... + def sync(self, recognizer): ... + def inErrorRecoveryMode(self, recognizer): ... + def reportError(self, recognizer, e: RecognitionException): ... + +class DefaultErrorStrategy(ErrorStrategy): + errorRecoveryMode: bool + lastErrorIndex: int + lastErrorStates: Incomplete + nextTokensContext: Incomplete + nextTokenState: int + def __init__(self) -> None: ... + def reset(self, recognizer): ... + def beginErrorCondition(self, recognizer): ... + def inErrorRecoveryMode(self, recognizer): ... + def endErrorCondition(self, recognizer): ... + def reportMatch(self, recognizer): ... + def reportError(self, recognizer, e: RecognitionException): ... + def recover(self, recognizer, e: RecognitionException): ... + nextTokensState: Incomplete + def sync(self, recognizer): ... + def reportNoViableAlternative(self, recognizer, e: NoViableAltException): ... + def reportInputMismatch(self, recognizer, e: InputMismatchException): ... + def reportFailedPredicate(self, recognizer, e) -> None: ... + def reportUnwantedToken(self, recognizer): ... + def reportMissingToken(self, recognizer): ... + def recoverInline(self, recognizer): ... + def singleTokenInsertion(self, recognizer): ... + def singleTokenDeletion(self, recognizer): ... + def getMissingSymbol(self, recognizer): ... + def getExpectedTokens(self, recognizer): ... + def getTokenErrorDisplay(self, t: Token): ... + def escapeWSAndQuote(self, s: str): ... + def getErrorRecoverySet(self, recognizer): ... + def consumeUntil(self, recognizer, set_: set[int]): ... + +class BailErrorStrategy(DefaultErrorStrategy): + def recover(self, recognizer, e: RecognitionException): ... + def recoverInline(self, recognizer): ... + def sync(self, recognizer): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi b/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi new file mode 100644 index 000000000000..1a4fe8f7d38f --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/error/Errors.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete + +from antlr4.InputStream import InputStream as InputStream +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Recognizer import Recognizer as Recognizer + +class UnsupportedOperationException(Exception): + def __init__(self, msg: str) -> None: ... + +class IllegalStateException(Exception): + def __init__(self, msg: str) -> None: ... + +class CancellationException(IllegalStateException): + def __init__(self, msg: str) -> None: ... + +class RecognitionException(Exception): + message: Incomplete + recognizer: Incomplete + input: Incomplete + ctx: Incomplete + offendingToken: Incomplete + offendingState: int + def __init__( + self, message: str | None = None, recognizer: Recognizer | None = None, input: InputStream | None = None, ctx=None + ) -> None: ... + def getExpectedTokens(self): ... + +class LexerNoViableAltException(RecognitionException): + startIndex: Incomplete + deadEndConfigs: Incomplete + message: str + def __init__(self, lexer, input: InputStream, startIndex: int, deadEndConfigs) -> None: ... + +class NoViableAltException(RecognitionException): + deadEndConfigs: Incomplete + startToken: Incomplete + offendingToken: Incomplete + def __init__( + self, + recognizer, + input=None, + startToken=None, + offendingToken=None, + deadEndConfigs=None, + ctx: ParserRuleContext | None = None, + ) -> None: ... + +class InputMismatchException(RecognitionException): + offendingToken: Incomplete + def __init__(self, recognizer) -> None: ... + +class FailedPredicateException(RecognitionException): + ruleIndex: Incomplete + predicateIndex: Incomplete + predicate: Incomplete + offendingToken: Incomplete + def __init__(self, recognizer, predicate: str | None = None, message: str | None = None) -> None: ... + def formatMessage(self, predicate: str, message: str): ... + +class ParseCancellationException(CancellationException): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/error/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/error/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi new file mode 100644 index 000000000000..be68b31898e7 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Chunk.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class Chunk: ... + +class TagChunk(Chunk): + __slots__ = ("tag", "label") + tag: Incomplete + label: Incomplete + def __init__(self, tag: str, label: str | None = None) -> None: ... + +class TextChunk(Chunk): + __slots__ = "text" + text: Incomplete + def __init__(self, text: str) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi new file mode 100644 index 000000000000..71b3dd76899e --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreeMatch.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from antlr4.tree.ParseTreePattern import ParseTreePattern as ParseTreePattern +from antlr4.tree.Tree import ParseTree as ParseTree + +class ParseTreeMatch: + __slots__ = ("tree", "pattern", "labels", "mismatchedNode") + tree: Incomplete + pattern: Incomplete + labels: Incomplete + mismatchedNode: Incomplete + def __init__( + self, tree: ParseTree, pattern: ParseTreePattern, labels: dict[str, list[ParseTree]], mismatchedNode: ParseTree + ) -> None: ... + def get(self, label: str): ... + def getAll(self, label: str): ... + def succeeded(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi new file mode 100644 index 000000000000..ef542c0e1288 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePattern.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from antlr4.tree.ParseTreePatternMatcher import ParseTreePatternMatcher as ParseTreePatternMatcher +from antlr4.tree.Tree import ParseTree as ParseTree +from antlr4.xpath.XPathLexer import XPathLexer as XPathLexer + +class ParseTreePattern: + __slots__ = ("matcher", "patternRuleIndex", "pattern", "patternTree") + matcher: Incomplete + patternRuleIndex: Incomplete + pattern: Incomplete + patternTree: Incomplete + def __init__(self, matcher: ParseTreePatternMatcher, pattern: str, patternRuleIndex: int, patternTree: ParseTree) -> None: ... + def match(self, tree: ParseTree): ... + def matches(self, tree: ParseTree): ... + def findAll(self, tree: ParseTree, xpath: str): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi new file mode 100644 index 000000000000..0d94f19c0ec0 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/ParseTreePatternMatcher.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +from antlr4.CommonTokenStream import CommonTokenStream as CommonTokenStream +from antlr4.error.Errors import ( + ParseCancellationException as ParseCancellationException, + RecognitionException as RecognitionException, +) +from antlr4.error.ErrorStrategy import BailErrorStrategy as BailErrorStrategy +from antlr4.InputStream import InputStream as InputStream +from antlr4.Lexer import Lexer as Lexer +from antlr4.ListTokenSource import ListTokenSource as ListTokenSource +from antlr4.ParserRuleContext import ParserRuleContext as ParserRuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Chunk import TagChunk as TagChunk, TextChunk as TextChunk +from antlr4.tree.RuleTagToken import RuleTagToken as RuleTagToken +from antlr4.tree.TokenTagToken import TokenTagToken as TokenTagToken +from antlr4.tree.Tree import ParseTree as ParseTree, RuleNode as RuleNode, TerminalNode as TerminalNode + +Parser: Incomplete +ParseTreePattern: Incomplete + +class CannotInvokeStartRule(Exception): + def __init__(self, e: Exception) -> None: ... + +class StartRuleDoesNotConsumeFullPattern(Exception): ... + +class ParseTreePatternMatcher: + __slots__ = ("lexer", "parser", "start", "stop", "escape") + lexer: Incomplete + parser: Incomplete + start: str + stop: str + escape: str + def __init__(self, lexer: Lexer, parser: Parser) -> None: ... + def setDelimiters(self, start: str, stop: str, escapeLeft: str): ... + def matchesRuleIndex(self, tree: ParseTree, pattern: str, patternRuleIndex: int): ... + def matchesPattern(self, tree: ParseTree, pattern: ParseTreePattern): ... + def matchRuleIndex(self, tree: ParseTree, pattern: str, patternRuleIndex: int): ... + def matchPattern(self, tree: ParseTree, pattern: ParseTreePattern): ... + def compileTreePattern(self, pattern: str, patternRuleIndex: int): ... + def matchImpl(self, tree: ParseTree, patternTree: ParseTree, labels: dict[str, list[ParseTree]]): ... + def map(self, labels, label, tree) -> None: ... + def getRuleTagToken(self, tree: ParseTree): ... + def tokenize(self, pattern: str): ... + def split(self, pattern: str): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi new file mode 100644 index 000000000000..0594ab3c4f37 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/RuleTagToken.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from antlr4.Token import Token as Token + +class RuleTagToken(Token): + __slots__ = ("label", "ruleName") + source: Incomplete + type: Incomplete + channel: Incomplete + start: int + stop: int + tokenIndex: int + line: int + column: int + label: Incomplete + ruleName: Incomplete + def __init__(self, ruleName: str, bypassTokenType: int, label: str | None = None) -> None: ... + def getText(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi new file mode 100644 index 000000000000..902d685b8418 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/TokenTagToken.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from antlr4.Token import CommonToken as CommonToken + +class TokenTagToken(CommonToken): + __slots__ = ("tokenName", "label") + tokenName: Incomplete + label: Incomplete + def __init__(self, tokenName: str, type: int, label: str | None = None) -> None: ... + def getText(self): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi new file mode 100644 index 000000000000..0eca91c7d868 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Tree.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from typing import Any, Literal, TypeVar + +from antlr4.ParserRuleContext import ParserRuleContext, RuleContext +from antlr4.Token import Token as Token + +INVALID_INTERVAL: Incomplete + +class Tree: ... +class SyntaxTree(Tree): ... +class ParseTree(SyntaxTree): ... +class RuleNode(ParseTree): ... +class TerminalNode(ParseTree): ... +class ErrorNode(TerminalNode): ... + +_GenericType = TypeVar("_GenericType", bound=type) + +class ParseTreeVisitor: + def visit(self, tree: Tree) -> None: ... + def visitChildren(self, node) -> None: ... + def visitTerminal(self, node: TerminalNode) -> None: ... + def visitErrorNode(self, node: ErrorNode) -> None: ... + def defaultResult(self) -> None: ... + def aggregateResult(self, aggregate, nextResult: _GenericType) -> _GenericType: ... + def shouldVisitNextChild(self, node, currentResult) -> Literal[True]: ... + +class ParseTreeListener: + def visitTerminal(self, node: TerminalNode) -> None: ... + def visitErrorNode(self, node: ErrorNode) -> None: ... + def enterEveryRule(self, ctx: ParserRuleContext) -> None: ... + def exitEveryRule(self, ctx: ParserRuleContext) -> None: ... + +class TerminalNodeImpl(TerminalNode): + __slots__ = ("parentCtx", "symbol") + parentCtx: RuleContext | None + symbol: Token + def __init__(self, symbol: Token) -> None: ... + def __setattr__(self, key: str, value: Any) -> None: ... + def getChild(self, i: int) -> None: ... + def getSymbol(self) -> Token: ... + def getParent(self) -> RuleContext | None: ... + def getPayload(self) -> Token: ... + def getSourceInterval(self) -> tuple[Literal[-1], Literal[-2]] | tuple[int | None, int | None]: ... + def getChildCount(self) -> Literal[0]: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + def getText(self) -> str: ... + +class ErrorNodeImpl(TerminalNodeImpl, ErrorNode): + def __init__(self, token: Token) -> None: ... + def accept(self, visitor: ParseTreeVisitor) -> None: ... + +class ParseTreeWalker: + DEFAULT: ParseTreeWalker + def walk(self, listener: ParseTreeListener, t: ParseTree) -> None: ... + def enterRule(self, listener: ParseTreeListener, r: RuleNode) -> None: ... + def exitRule(self, listener: ParseTreeListener, r: RuleNode) -> None: ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi new file mode 100644 index 000000000000..896a4f9da254 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/tree/Trees.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ( + ErrorNode as ErrorNode, + ParseTree as ParseTree, + RuleNode as RuleNode, + TerminalNode as TerminalNode, + Tree as Tree, +) +from antlr4.Utils import escapeWhitespace as escapeWhitespace + +Parser: Incomplete + +class Trees: + @classmethod + def toStringTree(cls, t: Tree, ruleNames: list[str] | None = None, recog: Parser | None = None): ... + @classmethod + def getNodeText(cls, t: Tree, ruleNames: list[str] | None = None, recog: Parser | None = None): ... + @classmethod + def getChildren(cls, t: Tree): ... + @classmethod + def getAncestors(cls, t: Tree): ... + @classmethod + def findAllTokenNodes(cls, t: ParseTree, ttype: int): ... + @classmethod + def findAllRuleNodes(cls, t: ParseTree, ruleIndex: int): ... + @classmethod + def findAllNodes(cls, t: ParseTree, index: int, findTokens: bool): ... + @classmethod + def descendants(cls, t: ParseTree): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/tree/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/tree/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi new file mode 100644 index 000000000000..47ede0ad6bae --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/xpath/XPath.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete + +from antlr4 import ( + DFA as DFA, + CommonTokenStream as CommonTokenStream, + Lexer as Lexer, + LexerATNSimulator as LexerATNSimulator, + ParserRuleContext as ParserRuleContext, + PredictionContextCache as PredictionContextCache, + TerminalNode as TerminalNode, +) +from antlr4.atn.ATNDeserializer import ATNDeserializer as ATNDeserializer +from antlr4.error.ErrorListener import ErrorListener as ErrorListener +from antlr4.error.Errors import LexerNoViableAltException as LexerNoViableAltException +from antlr4.InputStream import InputStream as InputStream +from antlr4.Parser import Parser as Parser +from antlr4.RuleContext import RuleContext as RuleContext +from antlr4.Token import Token as Token +from antlr4.tree.Tree import ParseTree as ParseTree +from antlr4.tree.Trees import Trees as Trees +from antlr4.xpath.XPathLexer import XPathLexer as XPathLexer + +class XPath: + WILDCARD: str + NOT: str + parser: Incomplete + path: Incomplete + elements: Incomplete + def __init__(self, parser: Parser, path: str) -> None: ... + def split(self, path: str): ... + def getXPathElement(self, wordToken: Token, anywhere: bool): ... + @staticmethod + def findAll(tree: ParseTree, xpath: str, parser: Parser): ... + def evaluate(self, t: ParseTree): ... + +class XPathElement: + nodeName: Incomplete + invert: bool + def __init__(self, nodeName: str) -> None: ... + +class XPathRuleAnywhereElement(XPathElement): + ruleIndex: Incomplete + def __init__(self, ruleName: str, ruleIndex: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathRuleElement(XPathElement): + ruleIndex: Incomplete + def __init__(self, ruleName: str, ruleIndex: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathTokenAnywhereElement(XPathElement): + tokenType: Incomplete + def __init__(self, ruleName: str, tokenType: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathTokenElement(XPathElement): + tokenType: Incomplete + def __init__(self, ruleName: str, tokenType: int) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathWildcardAnywhereElement(XPathElement): + def __init__(self) -> None: ... + def evaluate(self, t: ParseTree): ... + +class XPathWildcardElement(XPathElement): + def __init__(self) -> None: ... + def evaluate(self, t: ParseTree): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi new file mode 100644 index 000000000000..5aac6033dbf9 --- /dev/null +++ b/stubs/antlr4-python3-runtime/antlr4/xpath/XPathLexer.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import TextIO + +from antlr4 import * + +def serializedATN(): ... + +class XPathLexer(Lexer): + atn: Incomplete + decisionsToDFA: Incomplete + TOKEN_REF: int + RULE_REF: int + ANYWHERE: int + ROOT: int + WILDCARD: int + BANG: int + ID: int + STRING: int + channelNames: Incomplete + modeNames: Incomplete + literalNames: Incomplete + symbolicNames: Incomplete + ruleNames: Incomplete + grammarFileName: str + def __init__(self, input=None, output: TextIO = ...) -> None: ... + def action(self, localctx: RuleContext, ruleIndex: int, actionIndex: int): ... + type: Incomplete + def ID_action(self, localctx: RuleContext, actionIndex: int): ... diff --git a/stubs/antlr4-python3-runtime/antlr4/xpath/__init__.pyi b/stubs/antlr4-python3-runtime/antlr4/xpath/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/assertpy/@tests/stubtest_allowlist.txt b/stubs/assertpy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..47dccabd33c1 --- /dev/null +++ b/stubs/assertpy/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Python 2 compatibility cruft: +assertpy\..+\.Iterable(\.__class_getitem__)? +assertpy.contains.str_types +assertpy.contains.xrange +assertpy.extracting.str_types +assertpy.file.str_types +assertpy.string.str_types diff --git a/stubs/assertpy/METADATA.toml b/stubs/assertpy/METADATA.toml new file mode 100644 index 000000000000..506bfdd1124b --- /dev/null +++ b/stubs/assertpy/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/assertpy/assertpy" diff --git a/stubs/assertpy/assertpy/__init__.pyi b/stubs/assertpy/assertpy/__init__.pyi new file mode 100644 index 000000000000..1eba206f802f --- /dev/null +++ b/stubs/assertpy/assertpy/__init__.pyi @@ -0,0 +1,12 @@ +from .assertpy import ( + WarningLoggingAdapter as WarningLoggingAdapter, + __version__ as __version__, + add_extension as add_extension, + assert_that as assert_that, + assert_warn as assert_warn, + fail as fail, + remove_extension as remove_extension, + soft_assertions as soft_assertions, + soft_fail as soft_fail, +) +from .file import contents_of as contents_of diff --git a/stubs/assertpy/assertpy/assertpy.pyi b/stubs/assertpy/assertpy/assertpy.pyi new file mode 100644 index 000000000000..922a86dcf426 --- /dev/null +++ b/stubs/assertpy/assertpy/assertpy.pyi @@ -0,0 +1,73 @@ +import logging +from collections.abc import Callable, Generator +from typing import Any, TypeVar +from typing_extensions import Self + +from .base import BaseMixin +from .collection import CollectionMixin +from .contains import ContainsMixin +from .date import DateMixin +from .dict import DictMixin +from .dynamic import DynamicMixin +from .exception import ExceptionMixin +from .extracting import ExtractingMixin +from .file import FileMixin +from .helpers import HelpersMixin +from .numeric import NumericMixin +from .snapshot import SnapshotMixin +from .string import StringMixin + +_T = TypeVar("_T") +_V = TypeVar("_V", default=Any) + +__version__: str +__tracebackhide__: bool + +class WarningLoggingAdapter(logging.LoggerAdapter[logging.Logger]): + def process(self, msg: str, kwargs: _T) -> tuple[str, _T]: ... + +class AssertionBuilder( + StringMixin, + SnapshotMixin, + NumericMixin, + HelpersMixin, + FileMixin, + ExtractingMixin, + ExceptionMixin, + DynamicMixin, + DictMixin, + DateMixin, + ContainsMixin[_V], + CollectionMixin[_V], + BaseMixin, +): + val: _V + description: str + kind: str | None + expected: BaseException | None + logger: logging.Logger + def __init__( + self, + val: _V, + description: str = "", + kind: str | None = None, + expected: BaseException | None = None, + logger: logging.Logger | None = None, + ) -> None: ... + def builder( + self, + val: _V, + description: str = "", + kind: str | None = None, + expected: BaseException | None = None, + logger: logging.Logger | None = None, + ) -> Self: ... + def error(self, msg: str) -> Self: ... + +def soft_assertions() -> Generator[None]: ... +def assert_that(val: _V, description: str = "") -> AssertionBuilder[_V]: ... +def assert_warn(val: _V, description: str = "", logger: logging.Logger | None = None) -> AssertionBuilder: ... +def fail(msg: str = "") -> None: ... +def soft_fail(msg: str = "") -> None: ... +def add_extension(func: Callable[..., AssertionBuilder[Any]]) -> None: ... +def remove_extension(func: Callable[..., AssertionBuilder[Any]]) -> None: ... diff --git a/stubs/assertpy/assertpy/base.pyi b/stubs/assertpy/assertpy/base.pyi new file mode 100644 index 000000000000..56238d4001e3 --- /dev/null +++ b/stubs/assertpy/assertpy/base.pyi @@ -0,0 +1,21 @@ +from typing import TypeAlias +from typing_extensions import Self + +__tracebackhide__: bool + +_IncludeIgnore: TypeAlias = str | list[str] | list[tuple[str, ...]] | None + +class BaseMixin: + description: str + def described_as(self, description: str) -> Self: ... + def is_equal_to(self, other: object, *, include: _IncludeIgnore = None, ignore: _IncludeIgnore = None) -> Self: ... + def is_not_equal_to(self, other: object) -> Self: ... + def is_same_as(self, other: object) -> Self: ... + def is_not_same_as(self, other: object) -> Self: ... + def is_true(self) -> Self: ... + def is_false(self) -> Self: ... + def is_none(self) -> Self: ... + def is_not_none(self) -> Self: ... + def is_type_of(self, some_type: type) -> Self: ... + def is_instance_of(self, some_class: type) -> Self: ... + def is_length(self, length: int) -> Self: ... diff --git a/stubs/assertpy/assertpy/collection.pyi b/stubs/assertpy/assertpy/collection.pyi new file mode 100644 index 000000000000..79cc4d5fb369 --- /dev/null +++ b/stubs/assertpy/assertpy/collection.pyi @@ -0,0 +1,20 @@ +from _typeshed import SupportsRichComparison +from collections.abc import Callable +from typing import Any, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +__tracebackhide__: bool + +_V = TypeVar("_V", default=Any) + +class CollectionMixin(Generic[_V]): + def is_iterable(self) -> Self: ... + def is_not_iterable(self) -> Self: ... + def is_subset_of(self, *supersets: _V) -> Self: ... + + @overload + def is_sorted(self, key: Callable[[_V], SupportsRichComparison] = ..., reverse: Literal[False] = False) -> Self: ... + @overload + def is_sorted(self, *, reverse: Literal[True]) -> Self: ... + @overload + def is_sorted(self, key: Callable[[_V], SupportsRichComparison], reverse: Literal[True]) -> Self: ... diff --git a/stubs/assertpy/assertpy/contains.pyi b/stubs/assertpy/assertpy/contains.pyi new file mode 100644 index 000000000000..6c59d2a5f81a --- /dev/null +++ b/stubs/assertpy/assertpy/contains.pyi @@ -0,0 +1,18 @@ +from typing import Any, Generic, TypeVar +from typing_extensions import Self + +__tracebackhide__: bool + +_V = TypeVar("_V", default=Any) + +class ContainsMixin(Generic[_V]): + def contains(self, *items: object) -> Self: ... + def does_not_contain(self, *items: object) -> Self: ... + def contains_only(self, *items: object) -> Self: ... + def contains_sequence(self, *items: object) -> Self: ... + def contains_duplicates(self) -> Self: ... + def does_not_contain_duplicates(self) -> Self: ... + def is_empty(self) -> Self: ... + def is_not_empty(self) -> Self: ... + def is_in(self, *items: _V) -> Self: ... + def is_not_in(self, *items: _V) -> Self: ... diff --git a/stubs/assertpy/assertpy/date.pyi b/stubs/assertpy/assertpy/date.pyi new file mode 100644 index 000000000000..5377724ef274 --- /dev/null +++ b/stubs/assertpy/assertpy/date.pyi @@ -0,0 +1,11 @@ +from datetime import date +from typing_extensions import Self + +__tracebackhide__: bool + +class DateMixin: + def is_before(self, other: date) -> Self: ... + def is_after(self, other: date) -> Self: ... + def is_equal_to_ignoring_milliseconds(self, other: date) -> Self: ... + def is_equal_to_ignoring_seconds(self, other: date) -> Self: ... + def is_equal_to_ignoring_time(self, other: date) -> Self: ... diff --git a/stubs/assertpy/assertpy/dict.pyi b/stubs/assertpy/assertpy/dict.pyi new file mode 100644 index 000000000000..ac114fb40888 --- /dev/null +++ b/stubs/assertpy/assertpy/dict.pyi @@ -0,0 +1,13 @@ +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class DictMixin: + def contains_key(self, *keys: object) -> Self: ... + def does_not_contain_key(self, *keys: object) -> Self: ... + def contains_value(self, *values: object) -> Self: ... + def does_not_contain_value(self, *values: object) -> Self: ... + # The dicts can contain arbitrary keys and values + def contains_entry(self, *args: dict[Any, Any], **kwargs: Any) -> Self: ... + def does_not_contain_entry(self, *args: dict[Any, Any], **kwargs: Any) -> Self: ... diff --git a/stubs/assertpy/assertpy/dynamic.pyi b/stubs/assertpy/assertpy/dynamic.pyi new file mode 100644 index 000000000000..681512a565bb --- /dev/null +++ b/stubs/assertpy/assertpy/dynamic.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from typing_extensions import Self + +__tracebackhide__: bool + +class DynamicMixin: + def __getattr__(self, attr: str) -> Callable[[object], Self]: ... diff --git a/stubs/assertpy/assertpy/exception.pyi b/stubs/assertpy/assertpy/exception.pyi new file mode 100644 index 000000000000..b1eb47da6915 --- /dev/null +++ b/stubs/assertpy/assertpy/exception.pyi @@ -0,0 +1,9 @@ +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class ExceptionMixin: + def raises(self, ex: type[BaseException] | BaseException) -> Self: ... + # The types of some_args and some_kwargs must equal the types of the called function. + def when_called_with(self, *some_args: Any, **some_kwargs: Any) -> Self: ... diff --git a/stubs/assertpy/assertpy/extracting.pyi b/stubs/assertpy/assertpy/extracting.pyi new file mode 100644 index 000000000000..00e82fb26beb --- /dev/null +++ b/stubs/assertpy/assertpy/extracting.pyi @@ -0,0 +1,15 @@ +from _typeshed import SupportsRichComparison +from collections.abc import Callable, Iterable, Mapping +from typing import Any +from typing_extensions import Self + +__tracebackhide__: bool + +class ExtractingMixin: + def extracting( + self, + *names: str, + # The callable must accept the type of the items in the self.val collection. + filter: str | Mapping[str, Any] | Callable[[Any], bool] = ..., + sort: str | Iterable[str] | Callable[[Any], SupportsRichComparison] = ..., + ) -> Self: ... diff --git a/stubs/assertpy/assertpy/file.pyi b/stubs/assertpy/assertpy/file.pyi new file mode 100644 index 000000000000..0bcf39525677 --- /dev/null +++ b/stubs/assertpy/assertpy/file.pyi @@ -0,0 +1,14 @@ +from _typeshed import StrPath, SupportsRead +from typing_extensions import Self + +__tracebackhide__: bool + +def contents_of(file: SupportsRead[str] | StrPath, encoding: str = "utf-8") -> str: ... + +class FileMixin: + def exists(self) -> Self: ... + def does_not_exist(self) -> Self: ... + def is_file(self) -> Self: ... + def is_directory(self) -> Self: ... + def is_named(self, filename: str) -> Self: ... + def is_child_of(self, parent: str) -> Self: ... diff --git a/stubs/assertpy/assertpy/helpers.pyi b/stubs/assertpy/assertpy/helpers.pyi new file mode 100644 index 000000000000..3ef068fa325f --- /dev/null +++ b/stubs/assertpy/assertpy/helpers.pyi @@ -0,0 +1,3 @@ +__tracebackhide__: bool + +class HelpersMixin: ... diff --git a/stubs/assertpy/assertpy/numeric.pyi b/stubs/assertpy/assertpy/numeric.pyi new file mode 100644 index 000000000000..cb3a0a372531 --- /dev/null +++ b/stubs/assertpy/assertpy/numeric.pyi @@ -0,0 +1,25 @@ +from datetime import date +from typing import TypeAlias +from typing_extensions import Self + +__tracebackhide__: bool + +_Numeric: TypeAlias = date | int | float + +class NumericMixin: + def is_zero(self) -> Self: ... + def is_not_zero(self) -> Self: ... + def is_nan(self) -> Self: ... + def is_not_nan(self) -> Self: ... + def is_inf(self) -> Self: ... + def is_not_inf(self) -> Self: ... + def is_greater_than(self, other: _Numeric) -> Self: ... + def is_greater_than_or_equal_to(self, other: _Numeric) -> Self: ... + def is_less_than(self, other: _Numeric) -> Self: ... + def is_less_than_or_equal_to(self, other: _Numeric) -> Self: ... + def is_positive(self) -> Self: ... + def is_negative(self) -> Self: ... + def is_between(self, low: _Numeric, high: _Numeric) -> Self: ... + def is_not_between(self, low: _Numeric, high: _Numeric) -> Self: ... + def is_close_to(self, other: _Numeric, tolerance: _Numeric) -> Self: ... + def is_not_close_to(self, other: _Numeric, tolerance: _Numeric) -> Self: ... diff --git a/stubs/assertpy/assertpy/snapshot.pyi b/stubs/assertpy/assertpy/snapshot.pyi new file mode 100644 index 000000000000..2a7abc9fed7b --- /dev/null +++ b/stubs/assertpy/assertpy/snapshot.pyi @@ -0,0 +1,6 @@ +from typing_extensions import Self + +__tracebackhide__: bool + +class SnapshotMixin: + def snapshot(self, id: str | None = None, path: str = "__snapshots") -> Self: ... diff --git a/stubs/assertpy/assertpy/string.pyi b/stubs/assertpy/assertpy/string.pyi new file mode 100644 index 000000000000..4b6c6717cde6 --- /dev/null +++ b/stubs/assertpy/assertpy/string.pyi @@ -0,0 +1,17 @@ +from typing_extensions import Self + +unicode = str +__tracebackhide__: bool + +class StringMixin: + def is_equal_to_ignoring_case(self, other: str) -> Self: ... + def contains_ignoring_case(self, *items: str) -> Self: ... + def starts_with(self, prefix: str) -> Self: ... + def ends_with(self, suffix: str) -> Self: ... + def matches(self, pattern: str) -> Self: ... + def does_not_match(self, pattern: str) -> Self: ... + def is_alpha(self) -> Self: ... + def is_digit(self) -> Self: ... + def is_lower(self) -> Self: ... + def is_upper(self) -> Self: ... + def is_unicode(self) -> Self: ... diff --git a/stubs/atheris/METADATA.toml b/stubs/atheris/METADATA.toml new file mode 100644 index 000000000000..43ba5cf276b1 --- /dev/null +++ b/stubs/atheris/METADATA.toml @@ -0,0 +1,6 @@ +version = "3.1.*" +upstream-repository = "https://github.com/google/atheris" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/atheris/atheris/__init__.pyi b/stubs/atheris/atheris/__init__.pyi new file mode 100644 index 000000000000..2a3312448ab0 --- /dev/null +++ b/stubs/atheris/atheris/__init__.pyi @@ -0,0 +1,9 @@ +from collections.abc import Callable + +def Setup( + args: list[str], + test_one_input: Callable[[bytes], None], + **kwargs: bool | Callable[[bytes, int, int], str | bytes] | Callable[[bytes, bytes, int, int], str | bytes] | None, +) -> list[str]: ... +def Fuzz() -> None: ... +def Mutate(data: bytes, max_size: int) -> bytes: ... diff --git a/stubs/atheris/atheris/function_hooks.pyi b/stubs/atheris/atheris/function_hooks.pyi new file mode 100644 index 000000000000..92ec044b7f0f --- /dev/null +++ b/stubs/atheris/atheris/function_hooks.pyi @@ -0,0 +1,14 @@ +from typing import Any + +def hook_re_module() -> None: ... + +class EnabledHooks: + def __init__(self) -> None: ... + def add(self, hook: str) -> None: ... + def __contains__(self, hook: str) -> bool: ... + +enabled_hooks: EnabledHooks + +# args[1] is an arbitrary string method that is called +# with the subsequent arguments, so they will vary +def _hook_str(*args: Any, **kwargs: Any) -> bool: ... diff --git a/stubs/atheris/atheris/import_hook.pyi b/stubs/atheris/atheris/import_hook.pyi new file mode 100644 index 000000000000..450923a31de9 --- /dev/null +++ b/stubs/atheris/atheris/import_hook.pyi @@ -0,0 +1,36 @@ +import types +from collections.abc import Sequence +from importlib import abc, machinery +from typing_extensions import Self + +def _should_skip(loader: abc.Loader) -> bool: ... + +class AtherisMetaPathFinder(abc.MetaPathFinder): + def __init__( + self, include_packages: set[str], exclude_modules: set[str], enable_loader_override: bool, trace_dataflow: bool + ) -> None: ... + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = None + ) -> machinery.ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... + +class AtherisSourceFileLoader: + def __init__(self, name: str, path: str, trace_dataflow: bool) -> None: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + +class AtherisSourcelessFileLoader: + def __init__(self, name: str, path: str, trace_dataflow: bool) -> None: ... + def get_code(self, fullname: str) -> types.CodeType | None: ... + +def make_dynamic_atheris_loader(loader: abc.Loader | type[abc.Loader], trace_dataflow: bool) -> abc.Loader: ... + +class HookManager: + def __init__( + self, include_packages: set[str], exclude_modules: set[str], enable_loader_override: bool, trace_dataflow: bool + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +def instrument_imports( + include: Sequence[str] | None = None, exclude: Sequence[str] | None = None, enable_loader_override: bool = True +) -> HookManager: ... diff --git a/stubs/atheris/atheris/instrument_bytecode.pyi b/stubs/atheris/atheris/instrument_bytecode.pyi new file mode 100644 index 000000000000..b6b935fd1c3b --- /dev/null +++ b/stubs/atheris/atheris/instrument_bytecode.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from typing import TypeVar + +_T = TypeVar("_T") + +def instrument_func(func: Callable[..., _T]) -> Callable[..., _T]: ... +def instrument_all() -> None: ... diff --git a/stubs/atheris/atheris/utils.pyi b/stubs/atheris/atheris/utils.pyi new file mode 100644 index 000000000000..481d9880b02b --- /dev/null +++ b/stubs/atheris/atheris/utils.pyi @@ -0,0 +1,20 @@ +from typing import Protocol, type_check_only + +def path() -> str: ... + +@type_check_only +class _Writer(Protocol): + def isatty(self) -> bool: ... + def write(self, content: str, /) -> object: ... + def flush(self) -> object: ... + +class ProgressRenderer: + def __init__(self, stream: _Writer, total_count: int) -> None: ... + def render(self) -> None: ... + def erase(self) -> None: ... + def drop(self) -> None: ... + + @property + def count(self) -> int: ... + @count.setter + def count(self, new_count: int) -> None: ... diff --git a/stubs/atheris/atheris/version_dependent.pyi b/stubs/atheris/atheris/version_dependent.pyi new file mode 100644 index 000000000000..eba864764ec9 --- /dev/null +++ b/stubs/atheris/atheris/version_dependent.pyi @@ -0,0 +1,32 @@ +import types +from typing import Final + +PYTHON_VERSION: Final[tuple[int, int]] +CONDITIONAL_JUMPS: Final[list[str]] +UNCONDITIONAL_JUMPS: Final[list[str]] +ENDS_FUNCTION: Final[list[str]] +HAVE_REL_REFERENCE: Final[list[str]] +HAVE_ABS_REFERENCE: Final[list[str]] +REL_REFERENCE_IS_INVERTED: Final[list[str]] + +def rel_reference_scale(opname: str) -> int: ... + +REVERSE_CMP_OP: Final[list[int]] + +def jump_arg_bytes(arg: int) -> int: ... +def add_bytes_to_jump_arg(arg: int, size: int) -> int: ... + +class ExceptionTableEntry: + def __init__(self, start_offset: int, end_offset: int, target: int, depth: int, lasti: bool) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class ExceptionTable: + def __init__(self, entries: list[ExceptionTableEntry]) -> None: ... + def __eq__(self, other: object) -> bool: ... + +def generate_exceptiontable(original_code: types.CodeType, exception_table_entries: list[ExceptionTableEntry]) -> bytes: ... + +CONST_PUSH_INSTRS: Final[set[str]] + +def is_func_start_resume(opname: str, arg: int | None) -> bool: ... +def has_argument(op: int) -> bool: ... diff --git a/stubs/auth0-python/@tests/stubtest_allowlist.txt b/stubs/auth0-python/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..8ebe98654c0b --- /dev/null +++ b/stubs/auth0-python/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Omit tests +auth0\.test.* + +# Omit _async functions because they aren't present at runtime +# The way these stubs are currently implemented is that we pretend all classes have async methods +# Even though in reality, users need to call `auth0.asyncify.asyncify` to generate async subclasses +auth0\..*_async diff --git a/stubs/auth0-python/METADATA.toml b/stubs/auth0-python/METADATA.toml new file mode 100644 index 000000000000..f05b227f3dd9 --- /dev/null +++ b/stubs/auth0-python/METADATA.toml @@ -0,0 +1,4 @@ +version = "4.10.*" +upstream-repository = "https://github.com/auth0/auth0-python" +dependencies = ["cryptography", "types-requests"] +obsolete-since = { version = "5.4.0", date = "2026-05-04" } diff --git a/stubs/auth0-python/auth0/__init__.pyi b/stubs/auth0-python/auth0/__init__.pyi new file mode 100644 index 000000000000..48e8b1da8e62 --- /dev/null +++ b/stubs/auth0-python/auth0/__init__.pyi @@ -0,0 +1,3 @@ +from auth0.exceptions import Auth0Error, RateLimitError, TokenValidationError + +__all__ = ("Auth0Error", "RateLimitError", "TokenValidationError") diff --git a/stubs/auth0-python/auth0/asyncify.pyi b/stubs/auth0-python/auth0/asyncify.pyi new file mode 100644 index 000000000000..c4109958aad6 --- /dev/null +++ b/stubs/auth0-python/auth0/asyncify.pyi @@ -0,0 +1,6 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +# See note in stubs/auth0-python/@tests/stubtest_allowlist.txt about _async methods +def asyncify(cls: type[_T]) -> type[_T]: ... diff --git a/stubs/auth0-python/auth0/authentication/__init__.pyi b/stubs/auth0-python/auth0/authentication/__init__.pyi new file mode 100644 index 000000000000..24384af11585 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/__init__.pyi @@ -0,0 +1,10 @@ +from .database import Database +from .delegated import Delegated +from .enterprise import Enterprise +from .get_token import GetToken +from .passwordless import Passwordless +from .revoke_token import RevokeToken +from .social import Social +from .users import Users + +__all__ = ("Database", "Delegated", "Enterprise", "GetToken", "Passwordless", "RevokeToken", "Social", "Users") diff --git a/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi b/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi new file mode 100644 index 000000000000..5b18760b06b2 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/async_token_verifier.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from .token_verifier import AsymmetricSignatureVerifier, JwksFetcher, TokenVerifier + +class AsyncAsymmetricSignatureVerifier(AsymmetricSignatureVerifier): + def __init__(self, jwks_url: str, algorithm: str = "RS256") -> None: ... + def set_session(self, session) -> None: ... + +class AsyncJwksFetcher(JwksFetcher): + def __init__(self, *args, **kwargs) -> None: ... + def set_session(self, session) -> None: ... + async def get_key(self, key_id: str): ... + +class AsyncTokenVerifier(TokenVerifier): + iss: str + aud: str + leeway: int + def __init__( + self, signature_verifier: AsyncAsymmetricSignatureVerifier, issuer: str, audience: str, leeway: int = 0 + ) -> None: ... + def set_session(self, session) -> None: ... + async def verify( # type: ignore[override] # Differs from supertype + self, token: str, nonce: str | None = None, max_age: int | None = None, organization: str | None = None + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/back_channel_login.pyi b/stubs/auth0-python/auth0/authentication/back_channel_login.pyi new file mode 100644 index 000000000000..0f5004a431ad --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/back_channel_login.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from .base import AuthenticationBase + +class BackChannelLogin(AuthenticationBase): + def back_channel_login( + self, + binding_message: str, + login_hint: str, + scope: str, + authorization_details: str | list[dict[str, Incomplete]] | None = None, + **kwargs, + ): ... diff --git a/stubs/auth0-python/auth0/authentication/base.pyi b/stubs/auth0-python/auth0/authentication/base.pyi new file mode 100644 index 000000000000..ca603c1dabb3 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/base.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from typing import Final + +from auth0.rest import RestClient +from auth0.types import RequestData + +UNKNOWN_ERROR: Final[str] + +class AuthenticationBase: + domain: str + client_id: str + client_secret: str | None + client_assertion_signing_key: str | None + client_assertion_signing_alg: str | None + protocol: str + client: RestClient + def __init__( + self, + domain: str, + client_id: str, + client_secret: str | None = None, + client_assertion_signing_key: str | None = None, + client_assertion_signing_alg: str | None = None, + telemetry: bool = True, + timeout: float | tuple[float, float] = 5.0, + protocol: str = "https", + ) -> None: ... + def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + def authenticated_post(self, url: str, data: dict[str, Incomplete], headers: dict[str, str] | None = None): ... + def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... diff --git a/stubs/auth0-python/auth0/authentication/client_authentication.pyi b/stubs/auth0-python/auth0/authentication/client_authentication.pyi new file mode 100644 index 000000000000..e75647fe00f5 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/client_authentication.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +def create_client_assertion_jwt( + domain: str, client_id: str, client_assertion_signing_key: str, client_assertion_signing_alg: str | None +) -> str: ... +def add_client_authentication( + payload: dict[str, Incomplete], + domain: str, + client_id: str, + client_secret: str | None, + client_assertion_signing_key: str | None, + client_assertion_signing_alg: str | None, +) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/database.pyi b/stubs/auth0-python/auth0/authentication/database.pyi new file mode 100644 index 000000000000..f5ed2a558afc --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/database.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from .base import AuthenticationBase + +class Database(AuthenticationBase): + def signup( + self, + email: str, + password: str, + connection: str, + username: str | None = None, + user_metadata: dict[str, Incomplete] | None = None, + given_name: str | None = None, + family_name: str | None = None, + name: str | None = None, + nickname: str | None = None, + picture: str | None = None, + ) -> dict[str, Incomplete]: ... + def change_password( + self, email: str, connection: str, password: str | None = None, organization: str | None = None + ) -> str: ... diff --git a/stubs/auth0-python/auth0/authentication/delegated.pyi b/stubs/auth0-python/auth0/authentication/delegated.pyi new file mode 100644 index 000000000000..5be5035f3ac9 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/delegated.pyi @@ -0,0 +1,12 @@ +from .base import AuthenticationBase + +class Delegated(AuthenticationBase): + def get_token( + self, + target: str, + api_type: str, + grant_type: str, + id_token: str | None = None, + refresh_token: str | None = None, + scope: str = "openid", + ): ... diff --git a/stubs/auth0-python/auth0/authentication/enterprise.pyi b/stubs/auth0-python/auth0/authentication/enterprise.pyi new file mode 100644 index 000000000000..0b205ebdb83f --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/enterprise.pyi @@ -0,0 +1,5 @@ +from .base import AuthenticationBase + +class Enterprise(AuthenticationBase): + def saml_metadata(self): ... + def wsfed_metadata(self): ... diff --git a/stubs/auth0-python/auth0/authentication/get_token.pyi b/stubs/auth0-python/auth0/authentication/get_token.pyi new file mode 100644 index 000000000000..5308543ca245 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/get_token.pyi @@ -0,0 +1,29 @@ +from .base import AuthenticationBase + +class GetToken(AuthenticationBase): + def authorization_code(self, code: str, redirect_uri: str | None, grant_type: str = "authorization_code"): ... + def authorization_code_pkce( + self, code_verifier: str, code: str, redirect_uri: str | None, grant_type: str = "authorization_code" + ): ... + def client_credentials(self, audience: str, grant_type: str = "client_credentials", organization: str | None = None): ... + def login( + self, + username: str, + password: str, + scope: str | None = None, + realm: str | None = None, + audience: str | None = None, + grant_type: str = "http://auth0.com/oauth/grant-type/password-realm", + forwarded_for: str | None = None, + ): ... + def refresh_token(self, refresh_token: str, scope: str = "", grant_type: str = "refresh_token"): ... + def passwordless_login(self, username: str, otp: str, realm: str, scope: str, audience: str): ... + def backchannel_login(self, auth_req_id: str, grant_type: str = "urn:openid:params:grant-type:ciba"): ... + def access_token_for_connection( + self, + subject_token_type: str, + subject_token: str, + requested_token_type: str, + connection: str | None = None, + grant_type: str = ..., + ): ... diff --git a/stubs/auth0-python/auth0/authentication/passwordless.pyi b/stubs/auth0-python/auth0/authentication/passwordless.pyi new file mode 100644 index 000000000000..aac13339a26c --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/passwordless.pyi @@ -0,0 +1,5 @@ +from .base import AuthenticationBase + +class Passwordless(AuthenticationBase): + def email(self, email: str, send: str = "link", auth_params: dict[str, str] | None = None): ... + def sms(self, phone_number: str): ... diff --git a/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi b/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi new file mode 100644 index 000000000000..6d0f0193c2ae --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/pushed_authorization_requests.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class PushedAuthorizationRequests(AuthenticationBase): + def pushed_authorization_request(self, response_type: str, redirect_uri: str, **kwargs): ... diff --git a/stubs/auth0-python/auth0/authentication/revoke_token.pyi b/stubs/auth0-python/auth0/authentication/revoke_token.pyi new file mode 100644 index 000000000000..8a26618fdbe7 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/revoke_token.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class RevokeToken(AuthenticationBase): + def revoke_refresh_token(self, token: str): ... diff --git a/stubs/auth0-python/auth0/authentication/social.pyi b/stubs/auth0-python/auth0/authentication/social.pyi new file mode 100644 index 000000000000..c17a225c507b --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/social.pyi @@ -0,0 +1,4 @@ +from .base import AuthenticationBase + +class Social(AuthenticationBase): + def login(self, access_token: str, connection: str, scope: str = "openid"): ... diff --git a/stubs/auth0-python/auth0/authentication/token_verifier.pyi b/stubs/auth0-python/auth0/authentication/token_verifier.pyi new file mode 100644 index 000000000000..8ce69a71fa9d --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/token_verifier.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing import ClassVar + +class SignatureVerifier: + DISABLE_JWT_CHECKS: ClassVar[dict[str, bool]] + def __init__(self, algorithm: str) -> None: ... + async def verify_signature(self, token: str) -> dict[str, Incomplete]: ... + +class SymmetricSignatureVerifier(SignatureVerifier): + def __init__(self, shared_secret: str, algorithm: str = "HS256") -> None: ... + +class JwksFetcher: + CACHE_TTL: ClassVar[int] + def __init__(self, jwks_url: str, cache_ttl: int = 600) -> None: ... + def get_key(self, key_id: str): ... + +class AsymmetricSignatureVerifier(SignatureVerifier): + def __init__(self, jwks_url: str, algorithm: str = "RS256", cache_ttl: int = 600) -> None: ... + +class TokenVerifier: + iss: str + aud: str + leeway: int + def __init__(self, signature_verifier: SignatureVerifier, issuer: str, audience: str, leeway: int = 0) -> None: ... + def verify( + self, token: str, nonce: str | None = None, max_age: int | None = None, organization: str | None = None + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/authentication/users.pyi b/stubs/auth0-python/auth0/authentication/users.pyi new file mode 100644 index 000000000000..3484f5f98e78 --- /dev/null +++ b/stubs/auth0-python/auth0/authentication/users.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from auth0.rest import RestClient +from auth0.types import TimeoutType + +class Users: + domain: str + protocol: str + client: RestClient + def __init__(self, domain: str, telemetry: bool = True, timeout: TimeoutType = 5.0, protocol: str = "https") -> None: ... + def userinfo(self, access_token: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/exceptions.pyi b/stubs/auth0-python/auth0/exceptions.pyi new file mode 100644 index 000000000000..608d6bb013f7 --- /dev/null +++ b/stubs/auth0-python/auth0/exceptions.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class Auth0Error(Exception): + status_code: int + error_code: str + message: str + content: Incomplete | None + def __init__(self, status_code: int, error_code: str, message: str, content=None) -> None: ... + +class RateLimitError(Auth0Error): + reset_at: int + def __init__(self, error_code: str, message: str, reset_at: int) -> None: ... + +class TokenValidationError(Exception): ... diff --git a/stubs/auth0-python/auth0/management/__init__.pyi b/stubs/auth0-python/auth0/management/__init__.pyi new file mode 100644 index 000000000000..ef02c99b9d43 --- /dev/null +++ b/stubs/auth0-python/auth0/management/__init__.pyi @@ -0,0 +1,65 @@ +from .actions import Actions +from .attack_protection import AttackProtection +from .auth0 import Auth0 +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .self_service_profiles import SelfServiceProfiles +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +__all__ = ( + "Auth0", + "Actions", + "AttackProtection", + "Blacklists", + "Branding", + "ClientCredentials", + "ClientGrants", + "Clients", + "Connections", + "CustomDomains", + "DeviceCredentials", + "EmailTemplates", + "Emails", + "Grants", + "Guardian", + "Hooks", + "Jobs", + "LogStreams", + "Logs", + "Organizations", + "ResourceServers", + "Roles", + "RulesConfigs", + "Rules", + "SelfServiceProfiles", + "Stats", + "Tenants", + "Tickets", + "UserBlocks", + "UsersByEmail", + "Users", +) diff --git a/stubs/auth0-python/auth0/management/actions.pyi b/stubs/auth0-python/auth0/management/actions.pyi new file mode 100644 index 000000000000..8c8179c20c82 --- /dev/null +++ b/stubs/auth0-python/auth0/management/actions.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Actions: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_actions( + self, + trigger_id: str | None = None, + action_name: str | None = None, + deployed: bool | None = None, + installed: bool = False, + page: int | None = None, + per_page: int | None = None, + ): ... + async def get_actions_async( + self, + trigger_id: str | None = None, + action_name: str | None = None, + deployed: bool | None = None, + installed: bool = False, + page: int | None = None, + per_page: int | None = None, + ): ... + def create_action(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_action_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_action(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_action_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_action(self, id: str) -> dict[str, Incomplete]: ... + async def get_action_async(self, id: str) -> dict[str, Incomplete]: ... + def delete_action(self, id: str, force: bool = False): ... + async def delete_action_async(self, id: str, force: bool = False): ... + def get_triggers(self) -> dict[str, Incomplete]: ... + async def get_triggers_async(self) -> dict[str, Incomplete]: ... + def get_execution(self, id: str) -> dict[str, Incomplete]: ... + async def get_execution_async(self, id: str) -> dict[str, Incomplete]: ... + def get_action_versions(self, id: str, page: int | None = None, per_page: int | None = None) -> dict[str, Incomplete]: ... + async def get_action_versions_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> dict[str, Incomplete]: ... + def get_trigger_bindings(self, id: str, page: int | None = None, per_page: int | None = None) -> dict[str, Incomplete]: ... + async def get_trigger_bindings_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> dict[str, Incomplete]: ... + def get_action_version(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + async def get_action_version_async(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + def deploy_action(self, id: str) -> dict[str, Incomplete]: ... + async def deploy_action_async(self, id: str) -> dict[str, Incomplete]: ... + def rollback_action_version(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + async def rollback_action_version_async(self, action_id: str, version_id: str) -> dict[str, Incomplete]: ... + def update_trigger_bindings(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_trigger_bindings_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/async_auth0.pyi b/stubs/auth0-python/auth0/management/async_auth0.pyi new file mode 100644 index 000000000000..f73b2a97fbd7 --- /dev/null +++ b/stubs/auth0-python/auth0/management/async_auth0.pyi @@ -0,0 +1,76 @@ +from types import TracebackType +from typing_extensions import Self + +from auth0.rest import RestClientOptions + +from .actions import Actions +from .attack_protection import AttackProtection +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .prompts import Prompts +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +class AsyncAuth0: + def __init__(self, domain: str, token: str, rest_options: RestClientOptions | None = None) -> None: ... + def set_session(self, session) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + + # Same attributes as Auth0 + # See note in stubs/auth0-python/@tests/stubtest_allowlist.txt about _async methods + actions: Actions + attack_protection: AttackProtection + blacklists: Blacklists + branding: Branding + client_credentials: ClientCredentials + client_grants: ClientGrants + clients: Clients + connections: Connections + custom_domains: CustomDomains + device_credentials: DeviceCredentials + email_templates: EmailTemplates + emails: Emails + grants: Grants + guardian: Guardian + hooks: Hooks + jobs: Jobs + log_streams: LogStreams + logs: Logs + organizations: Organizations + prompts: Prompts + resource_servers: ResourceServers + roles: Roles + rules_configs: RulesConfigs + rules: Rules + stats: Stats + tenants: Tenants + tickets: Tickets + user_blocks: UserBlocks + users_by_email: UsersByEmail + users: Users diff --git a/stubs/auth0-python/auth0/management/attack_protection.pyi b/stubs/auth0-python/auth0/management/attack_protection.pyi new file mode 100644 index 000000000000..d87701e522c7 --- /dev/null +++ b/stubs/auth0-python/auth0/management/attack_protection.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class AttackProtection: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_breached_password_detection(self) -> dict[str, Incomplete]: ... + async def get_breached_password_detection_async(self) -> dict[str, Incomplete]: ... + def update_breached_password_detection(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_breached_password_detection_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_brute_force_protection(self) -> dict[str, Incomplete]: ... + async def get_brute_force_protection_async(self) -> dict[str, Incomplete]: ... + def update_brute_force_protection(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_brute_force_protection_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_suspicious_ip_throttling(self) -> dict[str, Incomplete]: ... + async def get_suspicious_ip_throttling_async(self) -> dict[str, Incomplete]: ... + def update_suspicious_ip_throttling(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_suspicious_ip_throttling_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/auth0.pyi b/stubs/auth0-python/auth0/management/auth0.pyi new file mode 100644 index 000000000000..817d1700cc93 --- /dev/null +++ b/stubs/auth0-python/auth0/management/auth0.pyi @@ -0,0 +1,67 @@ +from auth0.rest import RestClientOptions + +from .actions import Actions +from .attack_protection import AttackProtection +from .blacklists import Blacklists +from .branding import Branding +from .client_credentials import ClientCredentials +from .client_grants import ClientGrants +from .clients import Clients +from .connections import Connections +from .custom_domains import CustomDomains +from .device_credentials import DeviceCredentials +from .email_templates import EmailTemplates +from .emails import Emails +from .grants import Grants +from .guardian import Guardian +from .hooks import Hooks +from .jobs import Jobs +from .log_streams import LogStreams +from .logs import Logs +from .organizations import Organizations +from .prompts import Prompts +from .resource_servers import ResourceServers +from .roles import Roles +from .rules import Rules +from .rules_configs import RulesConfigs +from .self_service_profiles import SelfServiceProfiles +from .stats import Stats +from .tenants import Tenants +from .tickets import Tickets +from .user_blocks import UserBlocks +from .users import Users +from .users_by_email import UsersByEmail + +class Auth0: + actions: Actions + attack_protection: AttackProtection + blacklists: Blacklists + branding: Branding + client_credentials: ClientCredentials + client_grants: ClientGrants + clients: Clients + connections: Connections + custom_domains: CustomDomains + device_credentials: DeviceCredentials + email_templates: EmailTemplates + emails: Emails + grants: Grants + guardian: Guardian + hooks: Hooks + jobs: Jobs + log_streams: LogStreams + logs: Logs + organizations: Organizations + prompts: Prompts + resource_servers: ResourceServers + roles: Roles + rules_configs: RulesConfigs + rules: Rules + self_service_profiles: SelfServiceProfiles + stats: Stats + tenants: Tenants + tickets: Tickets + user_blocks: UserBlocks + users_by_email: UsersByEmail + users: Users + def __init__(self, domain: str, token: str, rest_options: RestClientOptions | None = None) -> None: ... diff --git a/stubs/auth0-python/auth0/management/blacklists.pyi b/stubs/auth0-python/auth0/management/blacklists.pyi new file mode 100644 index 000000000000..b2793ec1272d --- /dev/null +++ b/stubs/auth0-python/auth0/management/blacklists.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Blacklists: + url: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, aud: str | None = None) -> list[dict[str, str]]: ... + async def get_async(self, aud: str | None = None) -> list[dict[str, str]]: ... + def create(self, jti: str, aud: str | None = None) -> dict[str, str]: ... + async def create_async(self, jti: str, aud: str | None = None) -> dict[str, str]: ... diff --git a/stubs/auth0-python/auth0/management/branding.pyi b/stubs/auth0-python/auth0/management/branding.pyi new file mode 100644 index 000000000000..8350d1a8267f --- /dev/null +++ b/stubs/auth0-python/auth0/management/branding.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Branding: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self) -> dict[str, Incomplete]: ... + async def get_async(self) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_template_universal_login(self) -> dict[str, Incomplete]: ... + async def get_template_universal_login_async(self) -> dict[str, Incomplete]: ... + def delete_template_universal_login(self): ... + async def delete_template_universal_login_async(self): ... + def update_template_universal_login(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_template_universal_login_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_default_branding_theme(self) -> dict[str, Incomplete]: ... + async def get_default_branding_theme_async(self) -> dict[str, Incomplete]: ... + def get_branding_theme(self, theme_id: str) -> dict[str, Incomplete]: ... + async def get_branding_theme_async(self, theme_id: str) -> dict[str, Incomplete]: ... + def delete_branding_theme(self, theme_id: str): ... + async def delete_branding_theme_async(self, theme_id: str): ... + def update_branding_theme(self, theme_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_branding_theme_async(self, theme_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create_branding_theme(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_branding_theme_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/client_credentials.pyi b/stubs/auth0-python/auth0/management/client_credentials.pyi new file mode 100644 index 000000000000..107534317423 --- /dev/null +++ b/stubs/auth0-python/auth0/management/client_credentials.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ClientCredentials: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self, client_id: str) -> list[dict[str, Incomplete]]: ... + async def all_async(self, client_id: str) -> list[dict[str, Incomplete]]: ... + def get(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + def create(self, client_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, client_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, client_id: str, id: str) -> dict[str, Incomplete]: ... + async def delete_async(self, client_id: str, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/client_grants.pyi b/stubs/auth0-python/auth0/management/client_grants.pyi new file mode 100644 index 000000000000..1938b8c2f29c --- /dev/null +++ b/stubs/auth0-python/auth0/management/client_grants.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ClientGrants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + audience: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + client_id: str | None = None, + allow_any_organization: bool | None = None, + ) -> dict[str, Incomplete]: ... + async def all_async( + self, + audience: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + client_id: str | None = None, + allow_any_organization: bool | None = None, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_organizations( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def get_organizations_async( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/clients.pyi b/stubs/auth0-python/auth0/management/clients.pyi new file mode 100644 index 000000000000..21358fc59ddf --- /dev/null +++ b/stubs/auth0-python/auth0/management/clients.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Clients: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + ) -> list[dict[str, Incomplete]]: ... + async def all_async( + self, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + ) -> list[dict[str, Incomplete]]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def rotate_secret(self, id: str) -> dict[str, Incomplete]: ... + async def rotate_secret_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/connections.pyi b/stubs/auth0-python/auth0/management/connections.pyi new file mode 100644 index 000000000000..69caf1afa4ee --- /dev/null +++ b/stubs/auth0-python/auth0/management/connections.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Connections: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + strategy: str | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + name: str | None = None, + ) -> list[dict[str, Incomplete]]: ... + async def all_async( + self, + strategy: str | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + extra_params: dict[str, Incomplete] | None = None, + name: str | None = None, + ) -> list[dict[str, Incomplete]]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_user_by_email(self, id: str, email: str): ... + async def delete_user_by_email_async(self, id: str, email: str): ... diff --git a/stubs/auth0-python/auth0/management/custom_domains.pyi b/stubs/auth0-python/auth0/management/custom_domains.pyi new file mode 100644 index 000000000000..e6e05a81e5cc --- /dev/null +++ b/stubs/auth0-python/auth0/management/custom_domains.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class CustomDomains: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self) -> list[dict[str, Incomplete]]: ... + async def all_async(self) -> list[dict[str, Incomplete]]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def create_new(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_new_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def verify(self, id: str) -> dict[str, Incomplete]: ... + async def verify_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/device_credentials.pyi b/stubs/auth0-python/auth0/management/device_credentials.pyi new file mode 100644 index 000000000000..a89bfa418fe0 --- /dev/null +++ b/stubs/auth0-python/auth0/management/device_credentials.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class DeviceCredentials: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get( + self, + user_id: str, + client_id: str, + type: str, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + async def get_async( + self, + user_id: str, + client_id: str, + type: str, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/email_templates.pyi b/stubs/auth0-python/auth0/management/email_templates.pyi new file mode 100644 index 000000000000..17e9b9c6c11d --- /dev/null +++ b/stubs/auth0-python/auth0/management/email_templates.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class EmailTemplates: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, template_name: str) -> dict[str, Incomplete]: ... + async def get_async(self, template_name: str) -> dict[str, Incomplete]: ... + def update(self, template_name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, template_name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/emails.pyi b/stubs/auth0-python/auth0/management/emails.pyi new file mode 100644 index 000000000000..24421140bd5b --- /dev/null +++ b/stubs/auth0-python/auth0/management/emails.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Emails: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def config(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def config_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self): ... + async def delete_async(self): ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/grants.pyi b/stubs/auth0-python/auth0/management/grants.pyi new file mode 100644 index 000000000000..7354186fd494 --- /dev/null +++ b/stubs/auth0-python/auth0/management/grants.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Grants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + extra_params: dict[str, Incomplete] | None = None, + ): ... + async def all_async( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + extra_params: dict[str, Incomplete] | None = None, + ): ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/guardian.pyi b/stubs/auth0-python/auth0/management/guardian.pyi new file mode 100644 index 000000000000..4614fb344f4c --- /dev/null +++ b/stubs/auth0-python/auth0/management/guardian.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Guardian: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all_factors(self) -> list[dict[str, Incomplete]]: ... + async def all_factors_async(self) -> list[dict[str, Incomplete]]: ... + def update_factor(self, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_factor_async(self, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_templates(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_templates_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_templates(self) -> dict[str, Incomplete]: ... + async def get_templates_async(self) -> dict[str, Incomplete]: ... + def get_enrollment(self, id: str) -> dict[str, Incomplete]: ... + async def get_enrollment_async(self, id: str) -> dict[str, Incomplete]: ... + def delete_enrollment(self, id: str): ... + async def delete_enrollment_async(self, id: str): ... + def create_enrollment_ticket(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_enrollment_ticket_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_factor_providers(self, factor_name: str, name: str) -> dict[str, Incomplete]: ... + async def get_factor_providers_async(self, factor_name: str, name: str) -> dict[str, Incomplete]: ... + def update_factor_providers(self, factor_name: str, name: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_factor_providers_async( + self, factor_name: str, name: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/hooks.pyi b/stubs/auth0-python/auth0/management/hooks.pyi new file mode 100644 index 000000000000..18d7f5c63e9a --- /dev/null +++ b/stubs/auth0-python/auth0/management/hooks.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Hooks: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + async def all_async( + self, + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ): ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_secrets(self, id: str) -> dict[str, Incomplete]: ... + async def get_secrets_async(self, id: str) -> dict[str, Incomplete]: ... + def add_secrets(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def add_secrets_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_secrets(self, id: str, body: list[str]): ... + async def delete_secrets_async(self, id: str, body: list[str]): ... + def update_secrets(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_secrets_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/jobs.pyi b/stubs/auth0-python/auth0/management/jobs.pyi new file mode 100644 index 000000000000..bd55f89399f3 --- /dev/null +++ b/stubs/auth0-python/auth0/management/jobs.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Jobs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def get_failed_job(self, id: str) -> dict[str, Incomplete]: ... + async def get_failed_job_async(self, id: str) -> dict[str, Incomplete]: ... + def export_users(self, body: dict[str, Incomplete]): ... + async def export_users_async(self, body: dict[str, Incomplete]): ... + def import_users( + self, + connection_id: str, + file_obj, + upsert: bool = False, + send_completion_email: bool = True, + external_id: str | None = None, + ) -> dict[str, Incomplete]: ... + async def import_users_async( + self, + connection_id: str, + file_obj, + upsert: bool = False, + send_completion_email: bool = True, + external_id: str | None = None, + ) -> dict[str, Incomplete]: ... + def send_verification_email(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def send_verification_email_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/log_streams.pyi b/stubs/auth0-python/auth0/management/log_streams.pyi new file mode 100644 index 000000000000..9990a570ee3a --- /dev/null +++ b/stubs/auth0-python/auth0/management/log_streams.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class LogStreams: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list(self) -> _list[dict[str, Incomplete]]: ... + async def list_async(self) -> _list[dict[str, Incomplete]]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete(self, id: str) -> dict[str, Incomplete]: ... + async def delete_async(self, id: str) -> dict[str, Incomplete]: ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/logs.pyi b/stubs/auth0-python/auth0/management/logs.pyi new file mode 100644 index 000000000000..800778d2dbf5 --- /dev/null +++ b/stubs/auth0-python/auth0/management/logs.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Logs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def search( + self, + page: int = 0, + per_page: int = 50, + sort: str | None = None, + q: str | None = None, + include_totals: bool = True, + fields: list[str] | None = None, + from_param: str | None = None, + take: int | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def search_async( + self, + page: int = 0, + per_page: int = 50, + sort: str | None = None, + q: str | None = None, + include_totals: bool = True, + fields: list[str] | None = None, + from_param: str | None = None, + take: int | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/organizations.pyi b/stubs/auth0-python/auth0/management/organizations.pyi new file mode 100644 index 000000000000..eb750ff79fd0 --- /dev/null +++ b/stubs/auth0-python/auth0/management/organizations.pyi @@ -0,0 +1,134 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Organizations: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all_organizations( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def all_organizations_async( + self, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + def get_organization_by_name(self, name: str | None = None) -> dict[str, Incomplete]: ... + async def get_organization_by_name_async(self, name: str | None = None) -> dict[str, Incomplete]: ... + def get_organization(self, id: str) -> dict[str, Incomplete]: ... + async def get_organization_async(self, id: str) -> dict[str, Incomplete]: ... + def create_organization(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_organization(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_organization_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization(self, id: str): ... + async def delete_organization_async(self, id: str): ... + def all_organization_connections( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> list[dict[str, Incomplete]]: ... + async def all_organization_connections_async( + self, id: str, page: int | None = None, per_page: int | None = None + ) -> list[dict[str, Incomplete]]: ... + def get_organization_connection(self, id: str, connection_id: str) -> dict[str, Incomplete]: ... + async def get_organization_connection_async(self, id: str, connection_id: str) -> dict[str, Incomplete]: ... + def create_organization_connection(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_connection_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_organization_connection( + self, id: str, connection_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + async def update_organization_connection_async( + self, id: str, connection_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_organization_connection(self, id: str, connection_id: str): ... + async def delete_organization_connection_async(self, id: str, connection_id: str): ... + def all_organization_members( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def all_organization_members_async( + self, + id: str, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + fields: list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def create_organization_members(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_members_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization_members(self, id: str, body: dict[str, Incomplete]): ... + async def delete_organization_members_async(self, id: str, body: dict[str, Incomplete]): ... + def all_organization_member_roles( + self, id: str, user_id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> list[dict[str, Incomplete]]: ... + async def all_organization_member_roles_async( + self, id: str, user_id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> list[dict[str, Incomplete]]: ... + def create_organization_member_roles(self, id: str, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_member_roles_async( + self, id: str, user_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_organization_member_roles(self, id: str, user_id: str, body: dict[str, Incomplete]): ... + async def delete_organization_member_roles_async(self, id: str, user_id: str, body: dict[str, Incomplete]): ... + def all_organization_invitations( + self, id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + async def all_organization_invitations_async( + self, id: str, page: int | None = None, per_page: int | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + def get_organization_invitation(self, id: str, invitaton_id: str) -> dict[str, Incomplete]: ... + async def get_organization_invitation_async(self, id: str, invitaton_id: str) -> dict[str, Incomplete]: ... + def create_organization_invitation(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_organization_invitation_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def delete_organization_invitation(self, id: str, invitation_id: str): ... + async def delete_organization_invitation_async(self, id: str, invitation_id: str): ... + def get_client_grants( + self, + id: str, + audience: str | None = None, + client_id: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + async def get_client_grants_async( + self, + id: str, + audience: str | None = None, + client_id: str | None = None, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + def add_client_grant(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + async def add_client_grant_async(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + def delete_client_grant(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... + async def delete_client_grant_async(self, id: str, grant_id: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/prompts.pyi b/stubs/auth0-python/auth0/management/prompts.pyi new file mode 100644 index 000000000000..5b11913678f4 --- /dev/null +++ b/stubs/auth0-python/auth0/management/prompts.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Prompts: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self) -> dict[str, Incomplete]: ... + async def get_async(self) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_custom_text(self, prompt: str, language: str): ... + async def get_custom_text_async(self, prompt: str, language: str): ... + def update_custom_text(self, prompt: str, language: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_custom_text_async( + self, prompt: str, language: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/resource_servers.pyi b/stubs/auth0-python/auth0/management/resource_servers.pyi new file mode 100644 index 000000000000..cb8e175b34dd --- /dev/null +++ b/stubs/auth0-python/auth0/management/resource_servers.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class ResourceServers: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_all(self, page: int | None = None, per_page: int | None = None, include_totals: bool = False): ... + async def get_all_async(self, page: int | None = None, per_page: int | None = None, include_totals: bool = False): ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/roles.pyi b/stubs/auth0-python/auth0/management/roles.pyi new file mode 100644 index 000000000000..5c288c09a5da --- /dev/null +++ b/stubs/auth0-python/auth0/management/roles.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Roles: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list( + self, page: int = 0, per_page: int = 25, include_totals: bool = True, name_filter: str | None = None + ) -> dict[str, Incomplete]: ... + async def list_async( + self, page: int = 0, per_page: int = 25, include_totals: bool = True, name_filter: str | None = None + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def list_users( + self, + id: str, + page: int = 0, + per_page: int = 25, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + async def list_users_async( + self, + id: str, + page: int = 0, + per_page: int = 25, + include_totals: bool = True, + from_param: str | None = None, + take: int | None = None, + ) -> dict[str, Incomplete]: ... + def add_users(self, id: str, users: _list[str]) -> dict[str, Incomplete]: ... + async def add_users_async(self, id: str, users: _list[str]) -> dict[str, Incomplete]: ... + def list_permissions( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_permissions_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_permissions(self, id: str, permissions: _list[dict[str, str]]): ... + async def remove_permissions_async(self, id: str, permissions: _list[dict[str, str]]): ... + def add_permissions(self, id: str, permissions: _list[dict[str, str]]) -> dict[str, Incomplete]: ... + async def add_permissions_async(self, id: str, permissions: _list[dict[str, str]]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/rules.pyi b/stubs/auth0-python/auth0/management/rules.pyi new file mode 100644 index 000000000000..6cee7f6e151d --- /dev/null +++ b/stubs/auth0-python/auth0/management/rules.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Rules: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all( + self, + stage: str = "login_success", + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + async def all_async( + self, + stage: str = "login_success", + enabled: bool = True, + fields: list[str] | None = None, + include_fields: bool = True, + page: int | None = None, + per_page: int | None = None, + include_totals: bool = False, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, id: str, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/rules_configs.pyi b/stubs/auth0-python/auth0/management/rules_configs.pyi new file mode 100644 index 000000000000..5f2f361d5f46 --- /dev/null +++ b/stubs/auth0-python/auth0/management/rules_configs.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class RulesConfigs: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self) -> list[dict[str, Incomplete]]: ... + async def all_async(self) -> list[dict[str, Incomplete]]: ... + def unset(self, key: str): ... + async def unset_async(self, key: str): ... + def set(self, key: str, value: str) -> dict[str, Incomplete]: ... + async def set_async(self, key: str, value: str) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/self_service_profiles.pyi b/stubs/auth0-python/auth0/management/self_service_profiles.pyi new file mode 100644 index 000000000000..e75e2a098844 --- /dev/null +++ b/stubs/auth0-python/auth0/management/self_service_profiles.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class SelfServiceProfiles: + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def all(self, page: int = 0, per_page: int = 25, include_totals: bool = True) -> list[dict[str, Incomplete]]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, profile_id: str) -> dict[str, Incomplete]: ... + def delete(self, profile_id: str) -> None: ... + def update(self, profile_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get_custom_text(self, profile_id: str, language: str, page: str) -> dict[str, Incomplete]: ... + def update_custom_text( + self, profile_id: str, language: str, page: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def create_sso_ticket(self, profile_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def revoke_sso_ticket(self, profile_id: str, ticket_id: str) -> None: ... diff --git a/stubs/auth0-python/auth0/management/stats.pyi b/stubs/auth0-python/auth0/management/stats.pyi new file mode 100644 index 000000000000..3cff2985672c --- /dev/null +++ b/stubs/auth0-python/auth0/management/stats.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Stats: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def active_users(self) -> int: ... + async def active_users_async(self) -> int: ... + def daily_stats(self, from_date: str | None = None, to_date: str | None = None) -> list[dict[str, Incomplete]]: ... + async def daily_stats_async( + self, from_date: str | None = None, to_date: str | None = None + ) -> list[dict[str, Incomplete]]: ... diff --git a/stubs/auth0-python/auth0/management/tenants.pyi b/stubs/auth0-python/auth0/management/tenants.pyi new file mode 100644 index 000000000000..3df24bf63374 --- /dev/null +++ b/stubs/auth0-python/auth0/management/tenants.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Tenants: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async(self, fields: list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + def update(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/tickets.pyi b/stubs/auth0-python/auth0/management/tickets.pyi new file mode 100644 index 000000000000..4c0dfaf2c879 --- /dev/null +++ b/stubs/auth0-python/auth0/management/tickets.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Tickets: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def create_email_verification(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_email_verification_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def create_pswd_change(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_pswd_change_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... diff --git a/stubs/auth0-python/auth0/management/user_blocks.pyi b/stubs/auth0-python/auth0/management/user_blocks.pyi new file mode 100644 index 000000000000..f6dbb555097f --- /dev/null +++ b/stubs/auth0-python/auth0/management/user_blocks.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class UserBlocks: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def get_by_identifier(self, identifier: str) -> dict[str, Incomplete]: ... + async def get_by_identifier_async(self, identifier: str) -> dict[str, Incomplete]: ... + def unblock_by_identifier(self, identifier: dict[str, Incomplete]): ... + async def unblock_by_identifier_async(self, identifier: dict[str, Incomplete]): ... + def get(self, id: str) -> dict[str, Incomplete]: ... + async def get_async(self, id: str) -> dict[str, Incomplete]: ... + def unblock(self, id: str): ... + async def unblock_async(self, id: str): ... diff --git a/stubs/auth0-python/auth0/management/users.pyi b/stubs/auth0-python/auth0/management/users.pyi new file mode 100644 index 000000000000..2a744f2db6fe --- /dev/null +++ b/stubs/auth0-python/auth0/management/users.pyi @@ -0,0 +1,119 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class Users: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def list( + self, + page: int = 0, + per_page: int = 25, + sort: str | None = None, + connection: str | None = None, + q: str | None = None, + search_engine: str | None = None, + include_totals: bool = True, + fields: _list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + async def list_async( + self, + page: int = 0, + per_page: int = 25, + sort: str | None = None, + connection: str | None = None, + q: str | None = None, + search_engine: str | None = None, + include_totals: bool = True, + fields: _list[str] | None = None, + include_fields: bool = True, + ) -> dict[str, Incomplete]: ... + def create(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_async(self, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def get(self, id: str, fields: _list[str] | None = None, include_fields: bool = True) -> dict[str, Incomplete]: ... + async def get_async( + self, id: str, fields: _list[str] | None = None, include_fields: bool = True + ) -> dict[str, Incomplete]: ... + def delete(self, id: str): ... + async def delete_async(self, id: str): ... + def update(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_async(self, id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def list_organizations( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_organizations_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def list_roles(self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True) -> dict[str, Incomplete]: ... + async def list_roles_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_roles(self, id: str, roles: _list[str]): ... + async def remove_roles_async(self, id: str, roles: _list[str]): ... + def add_roles(self, id: str, roles: _list[str]) -> dict[str, Incomplete]: ... + async def add_roles_async(self, id: str, roles: _list[str]) -> dict[str, Incomplete]: ... + def list_permissions( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + async def list_permissions_async( + self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True + ) -> dict[str, Incomplete]: ... + def remove_permissions(self, id: str, permissions: _list[str]): ... + async def remove_permissions_async(self, id: str, permissions: _list[str]): ... + def add_permissions(self, id: str, permissions: _list[str]) -> dict[str, Incomplete]: ... + async def add_permissions_async(self, id: str, permissions: _list[str]) -> dict[str, Incomplete]: ... + def delete_multifactor(self, id: str, provider: str): ... + async def delete_multifactor_async(self, id: str, provider: str): ... + def delete_authenticators(self, id: str): ... + async def delete_authenticators_async(self, id: str): ... + def unlink_user_account(self, id: str, provider: str, user_id: str): ... + async def unlink_user_account_async(self, id: str, provider: str, user_id: str): ... + def link_user_account(self, user_id: str, body: dict[str, Incomplete]) -> _list[dict[str, Incomplete]]: ... + async def link_user_account_async(self, user_id: str, body: dict[str, Incomplete]) -> _list[dict[str, Incomplete]]: ... + def regenerate_recovery_code(self, user_id: str) -> dict[str, Incomplete]: ... + async def regenerate_recovery_code_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_guardian_enrollments(self, user_id: str) -> dict[str, Incomplete]: ... + async def get_guardian_enrollments_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_log_events( + self, user_id: str, page: int = 0, per_page: int = 50, sort: str | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + async def get_log_events_async( + self, user_id: str, page: int = 0, per_page: int = 50, sort: str | None = None, include_totals: bool = False + ) -> dict[str, Incomplete]: ... + def invalidate_remembered_browsers(self, user_id: str) -> dict[str, Incomplete]: ... + async def invalidate_remembered_browsers_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_authentication_methods(self, user_id: str) -> dict[str, Incomplete]: ... + async def get_authentication_methods_async(self, user_id: str) -> dict[str, Incomplete]: ... + def get_authentication_method_by_id(self, user_id: str, authentication_method_id: str) -> dict[str, Incomplete]: ... + async def get_authentication_method_by_id_async( + self, user_id: str, authentication_method_id: str + ) -> dict[str, Incomplete]: ... + def create_authentication_method(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def create_authentication_method_async(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_authentication_methods(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + async def update_authentication_methods_async(self, user_id: str, body: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def update_authentication_method_by_id( + self, user_id: str, authentication_method_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + async def update_authentication_method_by_id_async( + self, user_id: str, authentication_method_id: str, body: dict[str, Incomplete] + ) -> dict[str, Incomplete]: ... + def delete_authentication_methods(self, user_id: str): ... + async def delete_authentication_methods_async(self, user_id: str): ... + def delete_authentication_method_by_id(self, user_id: str, authentication_method_id: str): ... + async def delete_authentication_method_by_id_async(self, user_id: str, authentication_method_id: str): ... + def list_tokensets(self, id: str, page: int = 0, per_page: int = 25, include_totals: bool = True): ... + def delete_tokenset_by_id(self, user_id: str, tokenset_id: str): ... diff --git a/stubs/auth0-python/auth0/management/users_by_email.pyi b/stubs/auth0-python/auth0/management/users_by_email.pyi new file mode 100644 index 000000000000..34b166a046cb --- /dev/null +++ b/stubs/auth0-python/auth0/management/users_by_email.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from ..rest import RestClientOptions +from ..types import TimeoutType + +class UsersByEmail: + domain: Incomplete + protocol: Incomplete + client: Incomplete + def __init__( + self, + domain: str, + token: str, + telemetry: bool = True, + timeout: TimeoutType = 5.0, + protocol: str = "https", + rest_options: RestClientOptions | None = None, + ) -> None: ... + def search_users_by_email( + self, email: str, fields: list[str] | None = None, include_fields: bool = True + ) -> list[dict[str, Incomplete]]: ... + async def search_users_by_email_async( + self, email: str, fields: list[str] | None = None, include_fields: bool = True + ) -> list[dict[str, Incomplete]]: ... diff --git a/stubs/auth0-python/auth0/rest.pyi b/stubs/auth0-python/auth0/rest.pyi new file mode 100644 index 000000000000..474716ed553b --- /dev/null +++ b/stubs/auth0-python/auth0/rest.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Final + +import requests +from auth0.rest_async import RequestsResponse +from auth0.types import RequestData, TimeoutType + +UNKNOWN_ERROR: Final[str] + +class RestClientOptions: + telemetry: bool + timeout: TimeoutType + retries: int + def __init__(self, telemetry: bool = True, timeout: TimeoutType = 5.0, retries: int = 3) -> None: ... + +class RestClient: + options: RestClientOptions + jwt: str | None + base_headers: dict[str, str] + telemetry: bool + timeout: TimeoutType + def __init__( + self, jwt: str | None, telemetry: bool = True, timeout: TimeoutType = 5.0, options: RestClientOptions | None = None + ) -> None: ... + def MAX_REQUEST_RETRIES(self) -> int: ... + def MAX_REQUEST_RETRY_JITTER(self) -> int: ... + def MAX_REQUEST_RETRY_DELAY(self) -> int: ... + def MIN_REQUEST_RETRY_DELAY(self) -> int: ... + def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... + def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + def file_post(self, url: str, data: RequestData | None = None, files: dict[str, Incomplete] | None = None): ... + def patch(self, url: str, data: RequestData | None = None): ... + def put(self, url: str, data: RequestData | None = None): ... + def delete(self, url: str, params: dict[str, Incomplete] | None = None, data: RequestData | None = None): ... + +class Response: + def __init__(self, status_code: int, content, headers: Mapping[str, str]) -> None: ... + def content(self): ... + +class JsonResponse(Response): + def __init__(self, response: requests.Response | RequestsResponse) -> None: ... + +class PlainResponse(Response): + def __init__(self, response: requests.Response | RequestsResponse) -> None: ... + +class EmptyResponse(Response): + def __init__(self, status_code: int) -> None: ... diff --git a/stubs/auth0-python/auth0/rest_async.pyi b/stubs/auth0-python/auth0/rest_async.pyi new file mode 100644 index 000000000000..56dc43e76804 --- /dev/null +++ b/stubs/auth0-python/auth0/rest_async.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete + +from auth0.types import RequestData + +from .rest import RestClient + +class AsyncRestClient(RestClient): + timeout: Incomplete + def set_session(self, session) -> None: ... + async def get(self, url: str, params: dict[str, Incomplete] | None = None, headers: dict[str, str] | None = None): ... + async def post(self, url: str, data: RequestData | None = None, headers: dict[str, str] | None = None): ... + async def file_post( # type: ignore[override] # Differs from supertype + self, url: str, data: dict[str, Incomplete], files: dict[str, Incomplete] + ): ... + async def patch(self, url: str, data: RequestData | None = None): ... + async def put(self, url: str, data: RequestData | None = None): ... + async def delete(self, url: str, params: dict[str, Incomplete] | None = None, data: RequestData | None = None): ... + +class RequestsResponse: + status_code: int + headers: Incomplete + text: str + def __init__(self, response, text: str) -> None: ... diff --git a/stubs/auth0-python/auth0/types.pyi b/stubs/auth0-python/auth0/types.pyi new file mode 100644 index 000000000000..2d9d79d8cbdb --- /dev/null +++ b/stubs/auth0-python/auth0/types.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +TimeoutType: TypeAlias = float | tuple[float, float] +RequestData: TypeAlias = dict[str, Incomplete] | list[Incomplete] diff --git a/stubs/auth0-python/auth0/utils.pyi b/stubs/auth0-python/auth0/utils.pyi new file mode 100644 index 000000000000..611cd037c258 --- /dev/null +++ b/stubs/auth0-python/auth0/utils.pyi @@ -0,0 +1 @@ +def is_async_available() -> bool: ... diff --git a/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt b/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0ccd2bd8b0ab --- /dev/null +++ b/stubs/aws-xray-sdk/@tests/stubtest_allowlist.txt @@ -0,0 +1,36 @@ +aws_xray_sdk.core.models.subsegment.subsegment_decorator +aws_xray_sdk.core.sampling.connector.ServiceConnector.fetch_sampling_rules + +# Inconsistency because `context_missing` param can be passed in *args or **kwargs: +aws_xray_sdk.core.async_context.AsyncContext.__init__ + +# We can not import 3rd-party libraries in teststubs runtime, +# but we can use Protocol to replace this types: +aws_xray_sdk.ext.aiobotocore +aws_xray_sdk.ext.aiobotocore.patch +aws_xray_sdk.ext.aiohttp.client +aws_xray_sdk.ext.aiohttp.middleware +aws_xray_sdk.ext.bottle.middleware +aws_xray_sdk.ext.django.apps +aws_xray_sdk.ext.django.conf +aws_xray_sdk.ext.django.db +aws_xray_sdk.ext.django.middleware +aws_xray_sdk.ext.django.templates +aws_xray_sdk.ext.flask.middleware +aws_xray_sdk.ext.flask_sqlalchemy.query +aws_xray_sdk.ext.httpx +aws_xray_sdk.ext.httpx.patch +aws_xray_sdk.ext.mysql +aws_xray_sdk.ext.mysql.patch +aws_xray_sdk.ext.pg8000 +aws_xray_sdk.ext.pg8000.patch +aws_xray_sdk.ext.pymongo +aws_xray_sdk.ext.pymongo.patch +aws_xray_sdk.ext.pymysql +aws_xray_sdk.ext.pymysql.patch +aws_xray_sdk.ext.pynamodb +aws_xray_sdk.ext.pynamodb.patch +aws_xray_sdk.ext.sqlalchemy.query +aws_xray_sdk.ext.sqlalchemy.util.decorators +aws_xray_sdk.ext.sqlalchemy_core +aws_xray_sdk.ext.sqlalchemy_core.patch diff --git a/stubs/aws-xray-sdk/METADATA.toml b/stubs/aws-xray-sdk/METADATA.toml new file mode 100644 index 000000000000..015cbb61e4a0 --- /dev/null +++ b/stubs/aws-xray-sdk/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.15.*" +upstream-repository = "https://github.com/aws/aws-xray-sdk-python" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/__init__.pyi new file mode 100644 index 000000000000..0db8933786e2 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/__init__.pyi @@ -0,0 +1,3 @@ +from .sdk_config import SDKConfig + +global_sdk_config: SDKConfig diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi new file mode 100644 index 000000000000..b42232c23d27 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/__init__.pyi @@ -0,0 +1,7 @@ +from .async_recorder import AsyncAWSXRayRecorder as AsyncAWSXRayRecorder +from .patcher import patch as patch, patch_all as patch_all +from .recorder import AWSXRayRecorder as AWSXRayRecorder + +xray_recorder: AsyncAWSXRayRecorder + +__all__ = ["patch", "patch_all", "xray_recorder", "AWSXRayRecorder"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi new file mode 100644 index 000000000000..85c366e821ee --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_context.pyi @@ -0,0 +1,23 @@ +from asyncio.events import AbstractEventLoop +from asyncio.tasks import Task, _TaskCompatibleCoro +from typing import Any, TypeVar + +from .context import Context as _Context + +_T_co = TypeVar("_T_co", covariant=True) + +class AsyncContext(_Context): + def __init__( + self, context_missing: str = "LOG_ERROR", loop: AbstractEventLoop | None = None, use_task_factory: bool = True + ) -> None: ... + def clear_trace_entities(self) -> None: ... + +class TaskLocalStorage: + def __init__(self, loop: AbstractEventLoop | None = None) -> None: ... + # Sets unknown items on the current task's context attribute + def __setattr__(self, name: str, value: Any) -> None: ... + # Returns unknown items from the current tasks context attribute + def __getattribute__(self, item: str) -> Any | None: ... + def clear(self) -> None: ... + +def task_factory(loop: AbstractEventLoop | None, coro: _TaskCompatibleCoro[_T_co]) -> Task[_T_co]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi new file mode 100644 index 000000000000..f7e4d588fa29 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/async_recorder.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete +from collections.abc import Awaitable, Callable, Iterable, Mapping +from types import TracebackType +from typing import TypeVar + +from .models.dummy_entities import DummySegment, DummySubsegment +from .models.segment import Segment, SegmentContextManager +from .models.subsegment import Subsegment, SubsegmentContextManager +from .recorder import AWSXRayRecorder + +_T = TypeVar("_T") + +class AsyncSegmentContextManager(SegmentContextManager): + async def __aenter__(self) -> DummySegment | Segment: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class AsyncSubsegmentContextManager(SubsegmentContextManager): + async def __call__( + self, wrapped: Callable[..., Awaitable[_T]], instance, args: Iterable[Incomplete], kwargs: Mapping[str, Incomplete] + ) -> _T: ... + async def __aenter__(self) -> DummySubsegment | Subsegment | None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class AsyncAWSXRayRecorder(AWSXRayRecorder): + def capture_async(self, name: str | None = None) -> AsyncSubsegmentContextManager: ... + def in_segment_async( + self, name: str | None = None, *, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None + ) -> AsyncSegmentContextManager: ... + def in_subsegment_async(self, name: str | None = None, *, namespace: str = "local") -> AsyncSubsegmentContextManager: ... + async def record_subsegment_async( + self, + wrapped: Callable[..., Awaitable[_T]], + instance, + args: Iterable[Incomplete], + kwargs: Mapping[str, Incomplete], + name: str, + namespace: str, + meta_processor: Callable[..., object] | None, + ) -> _T: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi new file mode 100644 index 000000000000..cb40f81ce44c --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/context.pyi @@ -0,0 +1,28 @@ +import time +from logging import Logger +from typing import Final + +from .models.entity import Entity +from .models.segment import Segment +from .models.subsegment import Subsegment + +log: Logger +MISSING_SEGMENT_MSG: Final[str] +SUPPORTED_CONTEXT_MISSING: Final = ("RUNTIME_ERROR", "LOG_ERROR", "IGNORE_ERROR") +CXT_MISSING_STRATEGY_KEY: Final = "AWS_XRAY_CONTEXT_MISSING" + +class Context: + def __init__(self, context_missing: str = "LOG_ERROR") -> None: ... + def put_segment(self, segment: Segment) -> None: ... + def end_segment(self, end_time: time.struct_time | None = None) -> None: ... + def put_subsegment(self, subsegment: Subsegment) -> None: ... + def end_subsegment(self, end_time: time.struct_time | None = None) -> bool: ... + def get_trace_entity(self) -> Entity: ... + def set_trace_entity(self, trace_entity: Entity) -> None: ... + def clear_trace_entities(self) -> None: ... + def handle_context_missing(self) -> None: ... + + @property + def context_missing(self) -> str: ... + @context_missing.setter + def context_missing(self, value: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi new file mode 100644 index 000000000000..35a393a7712b --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/daemon_config.pyi @@ -0,0 +1,15 @@ +from typing import Final + +DAEMON_ADDRESS_KEY: Final = "AWS_XRAY_DAEMON_ADDRESS" +DEFAULT_ADDRESS: Final = "127.0.0.1:2000" + +class DaemonConfig: + def __init__(self, daemon_address: str | None = "127.0.0.1:2000") -> None: ... + @property + def udp_ip(self) -> str: ... + @property + def udp_port(self) -> int: ... + @property + def tcp_ip(self) -> str: ... + @property + def tcp_port(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi new file mode 100644 index 000000000000..affa22d2a484 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/emitters/udp_emitter.pyi @@ -0,0 +1,18 @@ +from logging import Logger +from typing import Final + +from aws_xray_sdk.core.models.entity import Entity + +log: Logger +PROTOCOL_HEADER: Final[str] +PROTOCOL_DELIMITER: Final[str] +DEFAULT_DAEMON_ADDRESS: Final[str] + +class UDPEmitter: + def __init__(self, daemon_address: str = "127.0.0.1:2000") -> None: ... + def send_entity(self, entity: Entity) -> None: ... + def set_daemon_address(self, address: str | None) -> None: ... + @property + def ip(self) -> str: ... + @property + def port(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/exceptions.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/exceptions.pyi new file mode 100644 index 000000000000..82d208b0f9d4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/exceptions/exceptions.pyi @@ -0,0 +1,8 @@ +class InvalidSamplingManifestError(Exception): ... +class SegmentNotFoundException(Exception): ... +class InvalidDaemonAddressException(Exception): ... +class SegmentNameMissingException(Exception): ... +class SubsegmentNameMissingException(Exception): ... +class FacadeSegmentMutationException(Exception): ... +class MissingPluginNames(Exception): ... +class AlreadyEndedException(Exception): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi new file mode 100644 index 000000000000..42f78df47440 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/lambda_launcher.pyi @@ -0,0 +1,20 @@ +from logging import Logger +from typing import Final + +from .context import Context + +log: Logger +LAMBDA_TRACE_HEADER_KEY: Final = "_X_AMZN_TRACE_ID" +LAMBDA_TASK_ROOT_KEY: Final = "LAMBDA_TASK_ROOT" +TOUCH_FILE_DIR: Final = "/tmp/.aws-xray/" +TOUCH_FILE_PATH: Final = "/tmp/.aws-xray/initialized" + +def check_in_lambda() -> LambdaContext | None: ... + +class LambdaContext(Context): + def __init__(self) -> None: ... + + @property # type: ignore[override] + def context_missing(self) -> None: ... + @context_missing.setter + def context_missing(self, value: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi new file mode 100644 index 000000000000..ed31616245db --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/default_dynamic_naming.pyi @@ -0,0 +1,3 @@ +class DefaultDynamicNaming: + def __init__(self, pattern: str, fallback: str) -> None: ... + def get_name(self, host_name: str | None) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi new file mode 100644 index 000000000000..f10a1208d4b6 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/dummy_entities.pyi @@ -0,0 +1,8 @@ +from .segment import Segment +from .subsegment import Subsegment + +class DummySegment(Segment): + def __init__(self, name: str = "dummy") -> None: ... + +class DummySubsegment(Subsegment): + def __init__(self, segment, name: str = "dummy") -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi new file mode 100644 index 000000000000..8b4e17c6e4a1 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/entity.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete +from logging import Logger +from traceback import StackSummary +from typing import Any, Final, Literal, overload + +from .subsegment import Subsegment +from .throwable import Throwable + +log: Logger +ORIGIN_TRACE_HEADER_ATTR_KEY: Final = "_origin_trace_header" + +class Entity: + id: str + name: str + start_time: float + parent_id: str | None + sampled: bool + in_progress: bool + http: dict[str, dict[str, str | int]] + annotations: dict[str, float | str | bool] + metadata: dict[str, dict[str, Any]] # value is any object that can be serialized into JSON string + aws: dict[str, Incomplete] + cause: dict[str, str | list[Throwable]] + subsegments: list[Subsegment] + end_time: float + def __init__(self, name: str, entity_id: str | None = None) -> None: ... + def close(self, end_time: float | None = None) -> None: ... + def add_subsegment(self, subsegment: Subsegment) -> None: ... + def remove_subsegment(self, subsegment: Subsegment) -> None: ... + + @overload + def put_http_meta(self, key: Literal["status", "content_length"], value: int) -> None: ... + @overload + def put_http_meta(self, key: Literal["url", "method", "user_agent", "client_ip", "x_forwarded_for"], value: str) -> None: ... + + def put_annotation(self, key: str, value: float | str | bool) -> None: ... + def put_metadata( + self, key: str, value: Any, namespace: str = "default" # value is any object that can be serialized into JSON string + ) -> None: ... + def set_aws(self, aws_meta) -> None: ... + throttle: bool + def add_throttle_flag(self) -> None: ... + fault: bool + def add_fault_flag(self) -> None: ... + error: bool + def add_error_flag(self) -> None: ... + def apply_status_code(self, status_code: int | None) -> None: ... + def add_exception(self, exception: Exception, stack: StackSummary, remote: bool = False) -> None: ... + def save_origin_trace_header(self, trace_header) -> None: ... + def get_origin_trace_header(self): ... + def serialize(self) -> str: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi new file mode 100644 index 000000000000..2ae599e4c968 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/facade_segment.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .segment import Segment + +MUTATION_UNSUPPORTED_MESSAGE: Final = "FacadeSegments cannot be mutated." + +class FacadeSegment(Segment): + initializing: bool + def __init__(self, name: str, entityid: str | None, traceid: str | None, sampled: bool | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi new file mode 100644 index 000000000000..360493f2f829 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/http.pyi @@ -0,0 +1,13 @@ +from typing import Final + +URL: Final = "url" +METHOD: Final = "method" +USER_AGENT: Final = "user_agent" +CLIENT_IP: Final = "client_ip" +X_FORWARDED_FOR: Final = "x_forwarded_for" +STATUS: Final = "status" +CONTENT_LENGTH: Final = "content_length" +XRAY_HEADER: Final = "X-Amzn-Trace-Id" +ALT_XRAY_HEADER: Final = "HTTP_X_AMZN_TRACE_ID" +request_keys: tuple[str, ...] +response_keys: tuple[str, ...] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi new file mode 100644 index 000000000000..14771ae030b9 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/noop_traceid.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar + +class NoOpTraceId: + VERSION: ClassVar[str] + DELIMITER: ClassVar[str] + start_time: str + def __init__(self) -> None: ... + def to_id(self) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi new file mode 100644 index 000000000000..1851d8ea3282 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/segment.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from types import TracebackType +from typing import Final + +from ..recorder import AWSXRayRecorder +from ..utils.atomic_counter import AtomicCounter +from .dummy_entities import DummySegment +from .entity import Entity +from .subsegment import Subsegment + +ORIGIN_TRACE_HEADER_ATTR_KEY: Final = "_origin_trace_header" + +class SegmentContextManager: + name: str | None + segment_kwargs: dict[str, str | bool | None] + recorder: AWSXRayRecorder + segment: Segment | None + def __init__( + self, + recorder: AWSXRayRecorder, + name: str | None = None, + *, + traceid: str | None = None, + parent_id: str | None = None, + sampling: bool | None = None, + ) -> None: ... + def __enter__(self) -> DummySegment | Segment: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Segment(Entity): + trace_id: str + id: str + in_progress: bool + sampled: bool + user: str | None + ref_counter: AtomicCounter + parent_id: str + service: dict[str, str] + def __init__( + self, + name: str, + entityid: str | None = None, + traceid: str | None = None, + parent_id: str | None = None, + sampled: bool = True, + ) -> None: ... + def add_subsegment(self, subsegment: Subsegment) -> None: ... + def increment(self) -> None: ... + def decrement_ref_counter(self) -> None: ... + def ready_to_send(self) -> bool: ... + def get_total_subsegments_size(self) -> int: ... + def decrement_subsegments_size(self) -> int: ... + def remove_subsegment(self, subsegment: Subsegment) -> None: ... + def set_user(self, user) -> None: ... + def set_service(self, service_info: dict[str, str]) -> None: ... + def set_rule_name(self, rule_name: str) -> None: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi new file mode 100644 index 000000000000..27481f85870b --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/subsegment.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from types import TracebackType +from typing import Final + +from ..recorder import AWSXRayRecorder +from .dummy_entities import DummySubsegment +from .entity import Entity +from .segment import Segment + +SUBSEGMENT_RECORDING_ATTRIBUTE: Final = "_self___SUBSEGMENT_RECORDING_ATTRIBUTE__" + +def set_as_recording(decorated_func, wrapped) -> None: ... +def is_already_recording(func: Callable[..., object]) -> bool: ... +def subsegment_decorator(wrapped, instance, args, kwargs): ... + +class SubsegmentContextManager: + name: str | None + subsegment_kwargs: dict[str, str] + recorder: AWSXRayRecorder + subsegment: Subsegment | None + def __init__(self, recorder: AWSXRayRecorder, name: str | None = None, *, namespace: str = "local") -> None: ... + def __call__(self, wrapped, instance, args: list[Incomplete], kwargs: dict[str, Incomplete]): ... + def __enter__(self) -> DummySubsegment | Subsegment | None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Subsegment(Entity): + parent_segment: Segment + trace_id: str + type: str + namespace: str + sql: dict[str, Incomplete] + def __init__(self, name: str, namespace: str, segment: Segment) -> None: ... + def add_subsegment(self, subsegment: Subsegment) -> None: ... + def remove_subsegment(self, subsegment: Subsegment) -> None: ... + def close(self, end_time: float | None = None) -> None: ... + def set_sql(self, sql: dict[str, Incomplete]) -> None: ... + def to_dict(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi new file mode 100644 index 000000000000..e4e0f748fd59 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/throwable.pyi @@ -0,0 +1,29 @@ +from logging import Logger +from traceback import StackSummary +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +log: Logger + +@type_check_only +class _StackInfo(TypedDict): + path: str + line: int + label: str + +@type_check_only +class _ThrowableAttrs(TypedDict): + id: str + message: NotRequired[str] + type: str + remote: bool + stack: NotRequired[list[_StackInfo]] + +class Throwable: + id: str + message: str + type: str + remote: bool + stack: list[_StackInfo] | None + def __init__(self, exception: Exception, stack: StackSummary, remote: bool = False) -> None: ... + def to_dict(self) -> _ThrowableAttrs: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi new file mode 100644 index 000000000000..d691f30e730f --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/trace_header.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +_SampledTrue: TypeAlias = Literal[True, "1", 1] +_SampledFalse: TypeAlias = Literal[False, "0", 0] +_SampledUnknown: TypeAlias = Literal["?"] +_Sampled: TypeAlias = _SampledTrue | _SampledFalse | _SampledUnknown + +log: Logger +ROOT: Final = "Root" +PARENT: Final = "Parent" +SAMPLE: Final = "Sampled" +SELF: Final = "Self" +HEADER_DELIMITER: Final = ";" + +class TraceHeader: + def __init__( + self, + root: str | None = None, + parent: str | None = None, + sampled: _Sampled | None = None, + data: dict[str, Incomplete] | None = None, + ) -> None: ... + @classmethod + def from_header_str(cls, header: str | None) -> Self: ... + def to_header_str(self) -> str: ... + @property + def root(self) -> str | None: ... + @property + def parent(self) -> str | None: ... + @property + def sampled(self) -> Literal[1, 0, "?"] | None: ... + @property + def data(self) -> dict[str, Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi new file mode 100644 index 000000000000..3d076c862f95 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/models/traceid.pyi @@ -0,0 +1,8 @@ +from typing import ClassVar + +class TraceId: + VERSION: ClassVar[str] + DELIMITER: ClassVar[str] + start_time: int + def __init__(self) -> None: ... + def to_id(self) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi new file mode 100644 index 000000000000..6b9f5d73226a --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/patcher.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from logging import Logger +from typing import Final + +log: Logger +SUPPORTED_MODULES: Final[tuple[str, ...]] +NO_DOUBLE_PATCH: Final[tuple[str, ...]] + +def patch_all(double_patch: bool = False) -> None: ... +def patch( + modules_to_patch: Iterable[str], raise_errors: bool = True, ignore_module_patterns: Iterable[str] | None = None +) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi new file mode 100644 index 000000000000..b5af18b73702 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ec2_plugin.pyi @@ -0,0 +1,18 @@ +from collections.abc import MutableMapping +from logging import Logger +from typing import Any, Final, overload + +log: Logger +SERVICE_NAME: Final = "ec2" +ORIGIN: Final = "AWS::EC2::Instance" +IMDS_URL: Final = "http://169.254.169.254/latest/" + +def initialize() -> None: ... +def get_token() -> str | None: ... +def get_metadata(token: str | None = None) -> dict[str, Any]: ... # result of parse_metadata_json() +def parse_metadata_json(json_str: str | bytes | bytearray) -> dict[str, Any]: ... # result of json.loads() + +@overload +def do_request(url: str, headers: MutableMapping[str, str] | None = None, method: str = "GET") -> str: ... +@overload +def do_request(url: None, headers: MutableMapping[str, str] | None = None, method: str = "GET") -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi new file mode 100644 index 000000000000..019494fb0c57 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/ecs_plugin.pyi @@ -0,0 +1,8 @@ +from logging import Logger +from typing import Final + +log: Logger +SERVICE_NAME: Final = "ecs" +ORIGIN: Final = "AWS::ECS::Container" + +def initialize() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi new file mode 100644 index 000000000000..9ac631478457 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/elasticbeanstalk_plugin.pyi @@ -0,0 +1,9 @@ +from logging import Logger +from typing import Final + +log: Logger +CONF_PATH: Final = "/var/elasticbeanstalk/xray/environment.conf" +SERVICE_NAME: Final = "elastic_beanstalk" +ORIGIN: Final = "AWS::ElasticBeanstalk::Environment" + +def initialize() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi new file mode 100644 index 000000000000..6dbc20343cb6 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/plugins/utils.pyi @@ -0,0 +1,8 @@ +from collections.abc import Iterable +from types import ModuleType +from typing import Final + +module_prefix: Final[str] +PLUGIN_MAPPING: Final[dict[str, str]] + +def get_plugin_modules(plugins: Iterable[str]) -> tuple[ModuleType, ...]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi new file mode 100644 index 000000000000..905bcb2e7837 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/recorder.pyi @@ -0,0 +1,130 @@ +import time +from _typeshed import FileDescriptorOrPath, Incomplete +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import Any, Final, TypeVar + +from .context import Context +from .emitters.udp_emitter import UDPEmitter +from .models.default_dynamic_naming import DefaultDynamicNaming +from .models.dummy_entities import DummySegment, DummySubsegment +from .models.segment import Segment, SegmentContextManager +from .models.subsegment import Subsegment, SubsegmentContextManager +from .sampling.local.sampler import LocalSampler +from .sampling.sampler import DefaultSampler +from .streaming.default_streaming import DefaultStreaming + +log: Logger +TRACING_NAME_KEY: Final = "AWS_XRAY_TRACING_NAME" +DAEMON_ADDR_KEY: Final = "AWS_XRAY_DAEMON_ADDRESS" +CONTEXT_MISSING_KEY: Final = "AWS_XRAY_CONTEXT_MISSING" +XRAY_META: Final[dict[str, dict[str, str]]] +SERVICE_INFO: Final[dict[str, str]] + +_T = TypeVar("_T") + +class AWSXRayRecorder: + def __init__(self) -> None: ... + def configure( + self, + sampling: bool | None = None, + plugins: Iterable[str] | None = None, + context_missing: str | None = None, + sampling_rules: dict[str, Any] | FileDescriptorOrPath | None = None, + daemon_address: str | None = None, + service: str | None = None, + context: Context | None = None, + emitter: UDPEmitter | None = None, + streaming: DefaultStreaming | None = None, + dynamic_naming: DefaultDynamicNaming | None = None, + streaming_threshold: int | None = None, + max_trace_back: int | None = None, + sampler: LocalSampler | DefaultSampler | None = None, + stream_sql: bool | None = True, + ) -> None: ... + def in_segment( + self, name: str | None = None, *, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None + ) -> SegmentContextManager: ... + def in_subsegment(self, name: str | None = None, *, namespace: str = "local") -> SubsegmentContextManager: ... + def begin_segment( + self, name: str | None = None, traceid: str | None = None, parent_id: str | None = None, sampling: bool | None = None + ) -> Segment | DummySegment: ... + def end_segment(self, end_time: time.struct_time | None = None) -> None: ... + def current_segment(self) -> Segment: ... + def begin_subsegment(self, name: str, namespace: str = "local") -> DummySubsegment | Subsegment | None: ... + def begin_subsegment_without_sampling(self, name: str) -> DummySubsegment | Subsegment | None: ... + def current_subsegment(self) -> Subsegment | DummySubsegment | None: ... + def end_subsegment(self, end_time: time.struct_time | None = None) -> None: ... + def put_annotation(self, key: str, value: Any) -> None: ... + def put_metadata(self, key: str, value: Any, namespace: str = "default") -> None: ... + def is_sampled(self) -> bool: ... + def get_trace_entity(self) -> Segment | Subsegment | DummySegment | DummySubsegment: ... + def set_trace_entity(self, trace_entity: Segment | Subsegment | DummySegment | DummySubsegment) -> None: ... + def clear_trace_entities(self) -> None: ... + def stream_subsegments(self) -> None: ... + def capture(self, name: str | None = None) -> SubsegmentContextManager: ... + def record_subsegment( + self, + wrapped: Callable[..., _T], + instance: Any, + args: Iterable[Incomplete], + kwargs: Mapping[str, Incomplete], + name: str, + namespace: str, + meta_processor: Callable[..., object] | None, + ) -> _T: ... + + @property + def enabled(self) -> bool: ... + @enabled.setter + def enabled(self, value: bool) -> None: ... + + @property + def sampling(self) -> bool: ... + @sampling.setter + def sampling(self, value: bool) -> None: ... + + @property + def sampler(self) -> LocalSampler | DefaultSampler: ... + @sampler.setter + def sampler(self, value: LocalSampler | DefaultSampler) -> None: ... + + @property + def service(self) -> str: ... + @service.setter + def service(self, value: str) -> None: ... + + @property + def dynamic_naming(self) -> DefaultDynamicNaming | None: ... + @dynamic_naming.setter + def dynamic_naming(self, value: DefaultDynamicNaming | str) -> None: ... + + @property + def context(self) -> Context: ... + @context.setter + def context(self, cxt: Context) -> None: ... + + @property + def emitter(self) -> UDPEmitter: ... + @emitter.setter + def emitter(self, value: UDPEmitter) -> None: ... + + @property + def streaming(self) -> DefaultStreaming: ... + @streaming.setter + def streaming(self, value: DefaultStreaming) -> None: ... + + @property + def streaming_threshold(self) -> int: ... + @streaming_threshold.setter + def streaming_threshold(self, value: int) -> None: ... + + @property + def max_trace_back(self) -> int: ... + @max_trace_back.setter + def max_trace_back(self, value: int) -> None: ... + + @property + def stream_sql(self) -> bool: ... + @stream_sql.setter + def stream_sql(self, value: bool) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi new file mode 100644 index 000000000000..4fe3bcedb95d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/connector.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from aws_xray_sdk.core.context import Context + +from .sampling_rule import SamplingRule + +class ServiceConnector: + def __init__(self) -> None: ... + def fetch_sampling_rules(self) -> list[SamplingRule]: ... + def fetch_sampling_target(self, rules) -> tuple[Incomplete, int]: ... + def setup_xray_client(self, ip: str, port: str | int, client) -> None: ... + + @property + def context(self) -> Context: ... + @context.setter + def context(self, v: Context) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi new file mode 100644 index 000000000000..9263428ef9cf --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/reservoir.pyi @@ -0,0 +1,6 @@ +class Reservoir: + traces_per_sec: int + used_this_sec: int + this_sec: int + def __init__(self, traces_per_sec: int = 0) -> None: ... + def take(self) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi new file mode 100644 index 000000000000..f4bf2f677537 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampler.pyi @@ -0,0 +1,18 @@ +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +from .sampling_rule import SamplingRule, _Rule + +@type_check_only +class _SamplingRule(TypedDict): + version: NotRequired[int] + default: _Rule + rules: list[_Rule] + +local_sampling_rule: _SamplingRule +SUPPORTED_RULE_VERSION: tuple[int, ...] + +class LocalSampler: + def __init__(self, rules: _SamplingRule = ...) -> None: ... + def should_trace(self, sampling_req: SamplingRule | None = None) -> bool: ... + def load_local_rules(self, rules: _SamplingRule) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi new file mode 100644 index 000000000000..418c386559e6 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/local/sampling_rule.pyi @@ -0,0 +1,38 @@ +from typing import ClassVar, TypedDict, type_check_only +from typing_extensions import NotRequired + +from .reservoir import Reservoir + +@type_check_only +class _Rule(TypedDict): + description: NotRequired[str] + host: NotRequired[str] + service_name: NotRequired[str] + http_method: NotRequired[str] + url_path: NotRequired[str] + fixed_target: NotRequired[int] + rate: NotRequired[float] + +class SamplingRule: + FIXED_TARGET: ClassVar[str] + RATE: ClassVar[str] + HOST: ClassVar[str] + METHOD: ClassVar[str] + PATH: ClassVar[str] + SERVICE_NAME: ClassVar[str] + def __init__(self, rule_dict: _Rule, version: int = 2, default: bool = False) -> None: ... + def applies(self, host: str | None, method: str | None, path: str | None) -> bool: ... + @property + def fixed_target(self) -> int | None: ... + @property + def rate(self) -> float | None: ... + @property + def host(self) -> str | None: ... + @property + def method(self) -> str | None: ... + @property + def path(self) -> str | None: ... + @property + def reservoir(self) -> Reservoir: ... + @property + def version(self): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi new file mode 100644 index 000000000000..10b5b2b7cad9 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/reservoir.pyi @@ -0,0 +1,15 @@ +from enum import Enum + +class Reservoir: + def __init__(self) -> None: ... + def borrow_or_take(self, now: int, can_borrow: bool | None) -> ReservoirDecision | None: ... + def load_quota(self, quota: int | None, TTL: int | None, interval: int | None) -> None: ... + @property + def quota(self) -> int | None: ... + @property + def TTL(self) -> int | None: ... + +class ReservoirDecision(Enum): + TAKE = "take" + BORROW = "borrow" + NO = "no" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi new file mode 100644 index 000000000000..e28044cf0880 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_cache.pyi @@ -0,0 +1,19 @@ +from typing import Final + +TTL: Final = 3600 + +class RuleCache: + def __init__(self) -> None: ... + def get_matched_rule(self, sampling_req, now: float): ... + def load_rules(self, rules) -> None: ... + def load_targets(self, targets_dict) -> None: ... + + @property + def rules(self): ... + @rules.setter + def rules(self, v) -> None: ... + + @property + def last_updated(self) -> int | None: ... + @last_updated.setter + def last_updated(self, v: int | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi new file mode 100644 index 000000000000..5f1f6c3caf5a --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/rule_poller.pyi @@ -0,0 +1,13 @@ +from logging import Logger +from typing import Final + +from .connector import ServiceConnector +from .rule_cache import RuleCache + +log: Logger +DEFAULT_INTERVAL: Final = 300 + +class RulePoller: + def __init__(self, cache: RuleCache, connector: ServiceConnector) -> None: ... + def start(self) -> None: ... + def wake_up(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi new file mode 100644 index 000000000000..4f8ea28cd3d5 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampler.pyi @@ -0,0 +1,17 @@ +from logging import Logger + +from aws_xray_sdk.core.daemon_config import DaemonConfig + +log: Logger + +class DefaultSampler: + def __init__(self) -> None: ... + def start(self) -> None: ... + def should_trace(self, sampling_req=None): ... + def load_local_rules(self, rules) -> None: ... + def load_settings(self, daemon_config: DaemonConfig, context, origin=None) -> None: ... + + @property + def xray_client(self): ... + @xray_client.setter + def xray_client(self, v) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi new file mode 100644 index 000000000000..440fba9c4aeb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/sampling_rule.pyi @@ -0,0 +1,47 @@ +from typing import Literal, TypedDict, type_check_only + +from .reservoir import Reservoir + +@type_check_only +class _Stats(TypedDict): + request_count: int + borrow_count: int + sampled_count: int + +class SamplingRule: + def __init__( + self, name: str, priority, rate, reservoir_size, host=None, method=None, path=None, service=None, service_type=None + ) -> None: ... + def match(self, sampling_req) -> bool: ... + def is_default(self) -> bool: ... + def snapshot_statistics(self) -> _Stats: ... + def merge(self, rule) -> None: ... + def ever_matched(self) -> bool: ... + def time_to_report(self) -> Literal[True] | None: ... + def increment_request_count(self) -> None: ... + def increment_borrow_count(self) -> None: ... + def increment_sampled_count(self) -> None: ... + + @property + def rate(self): ... + @rate.setter + def rate(self, v) -> None: ... + + @property + def name(self) -> str: ... + @property + def priority(self): ... + + @property + def reservoir(self) -> Reservoir: ... + @reservoir.setter + def reservoir(self, v: Reservoir) -> None: ... + + @property + def can_borrow(self) -> bool: ... + @property + def request_count(self) -> int: ... + @property + def borrow_count(self) -> int: ... + @property + def sampled_count(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi new file mode 100644 index 000000000000..7a1a5ff753b1 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/sampling/target_poller.pyi @@ -0,0 +1,11 @@ +from logging import Logger + +from .connector import ServiceConnector +from .rule_cache import RuleCache +from .rule_poller import RulePoller + +log: Logger + +class TargetPoller: + def __init__(self, cache: RuleCache, rule_poller: RulePoller, connector: ServiceConnector) -> None: ... + def start(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi new file mode 100644 index 000000000000..cca12298fe5d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/streaming/default_streaming.pyi @@ -0,0 +1,15 @@ +from _typeshed import Unused +from collections.abc import Callable + +from aws_xray_sdk.core.models.entity import Entity +from aws_xray_sdk.core.models.segment import Segment + +class DefaultStreaming: + def __init__(self, streaming_threshold: int = 30) -> None: ... + def is_eligible(self, segment: Segment) -> bool: ... + def stream(self, entity: Entity, callback: Callable[..., Unused]) -> None: ... + + @property + def streaming_threshold(self) -> int: ... + @streaming_threshold.setter + def streaming_threshold(self, value: int) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi new file mode 100644 index 000000000000..66a7fb051c4e --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/atomic_counter.pyi @@ -0,0 +1,7 @@ +class AtomicCounter: + value: int + def __init__(self, initial: int = 0) -> None: ... + def increment(self, num: int = 1) -> int: ... + def decrement(self, num: int = 1) -> int: ... + def get_current(self) -> int: ... + def reset(self) -> int: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi new file mode 100644 index 000000000000..f6e9aa45654e --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/compat.pyi @@ -0,0 +1,4 @@ +annotation_value_types: tuple[type, ...] + +def is_classmethod(func: object) -> bool: ... # argument func is passing to getattr() function +def is_instance_method(parent_class: type, func_name: str, func: object) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi new file mode 100644 index 000000000000..c5201d5b6e04 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/conversion.pyi @@ -0,0 +1,13 @@ +from logging import Logger +from typing import Any, TypeVar, overload + +_K = TypeVar("_K") + +log: Logger + +@overload +def metadata_to_dict(obj: dict[_K, Any]) -> dict[_K, Any]: ... +@overload +def metadata_to_dict(obj: type) -> str: ... +@overload +def metadata_to_dict(obj: Any) -> Any: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi new file mode 100644 index 000000000000..94b94e569186 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/search_pattern.pyi @@ -0,0 +1,8 @@ +from typing import Literal, overload + +@overload +def wildcard_match(pattern: None, text: str, case_insensitive: bool = True) -> Literal[False]: ... +@overload +def wildcard_match(pattern: str, text: None, case_insensitive: bool = True) -> Literal[False]: ... +@overload +def wildcard_match(pattern: str, text: str, case_insensitive: bool = True) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi new file mode 100644 index 000000000000..c4c90e27adf6 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/sqs_message_helper.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Final + +SQS_XRAY_HEADER: Final = "AWSTraceHeader" + +class SqsMessageHelper: + @staticmethod + def isSampled(sqs_message: Mapping[str, Incomplete]) -> bool: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi new file mode 100644 index 000000000000..fd7daa078301 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/core/utils/stacktrace.pyi @@ -0,0 +1,3 @@ +import traceback + +def get_stacktrace(limit: int | None = None) -> list[traceback.FrameSummary]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiobotocore/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi new file mode 100644 index 000000000000..dd4500f9d662 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/client.pyi @@ -0,0 +1,10 @@ +from typing import Final + +REMOTE_NAMESPACE: Final = "remote" +LOCAL_NAMESPACE: Final = "local" +LOCAL_EXCEPTIONS: tuple[type[Exception], ...] + +async def begin_subsegment(session, trace_config_ctx, params): ... +async def end_subsegment(session, trace_config_ctx, params): ... +async def end_subsegment_with_exception(session, trace_config_ctx, params): ... +def aws_xray_trace_config(name=None): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi new file mode 100644 index 000000000000..93fab0a1f06c --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/aiohttp/middleware.pyi @@ -0,0 +1 @@ +async def middleware(request, handler): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi new file mode 100644 index 000000000000..29a962e55ed0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/boto_utils.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +whitelist: Incomplete + +def inject_header(wrapped, instance, args, kwargs): ... +def aws_meta_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/botocore/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi new file mode 100644 index 000000000000..5470f17a3482 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/bottle/middleware.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ClassVar + +class XRayMiddleware: + name: ClassVar[str] + api: ClassVar[int] + def __init__(self, recorder) -> None: ... + def apply(self, callback: Callable[..., Incomplete], route) -> Callable[..., Incomplete]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi new file mode 100644 index 000000000000..df291e1040cd --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/dbapi2.pyi @@ -0,0 +1,14 @@ +from typing_extensions import Self + +class XRayTracedConn: + def __init__(self, conn, meta={}) -> None: ... + def cursor(self, *args, **kwargs) -> XRayTracedCursor: ... + +class XRayTracedCursor: + def __init__(self, cursor, meta={}) -> None: ... + def __enter__(self) -> Self: ... + def execute(self, query, *args, **kwargs): ... + def executemany(self, query, *args, **kwargs): ... + def callproc(self, proc, args): ... + +def add_sql_meta(meta) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi new file mode 100644 index 000000000000..c4741233700b --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +default_app_config: Final = "aws_xray_sdk.ext.django.apps.XRayConfig" diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi new file mode 100644 index 000000000000..b00e299307b4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/apps.pyi @@ -0,0 +1,8 @@ +from logging import Logger +from typing import ClassVar + +log: Logger + +class XRayConfig: + name: ClassVar[str] + def ready(self) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi new file mode 100644 index 000000000000..538c47697398 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/conf.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Final + +DEFAULTS: dict[str, str | bool | tuple[Incomplete] | list[Incomplete] | None] +XRAY_NAMESPACE: Final = "XRAY_RECORDER" +SUPPORTED_ENV_VARS: tuple[str, ...] + +class XRaySettings: + defaults: dict[str, str | bool | tuple[Incomplete] | list[Incomplete] | None] + def __init__(self, user_settings=None) -> None: ... + @property + def user_settings(self): ... + def __getattr__(self, attr): ... + +settings: XRaySettings + +def reload_settings(*, settings: str | None = None, value=None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi new file mode 100644 index 000000000000..d71b2856e342 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/db.pyi @@ -0,0 +1,12 @@ +from logging import Logger + +from aws_xray_sdk.ext.dbapi2 import XRayTracedCursor + +log: Logger + +def patch_db() -> None: ... + +class DjangoXRayTracedCursor(XRayTracedCursor): + def execute(self, query, *args, **kwargs): ... + def executemany(self, query, *args, **kwargs): ... + def callproc(self, proc, args): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi new file mode 100644 index 000000000000..d5d5a1faa7cb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/middleware.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Final + +log: Logger + +USER_AGENT_KEY: Final = "HTTP_USER_AGENT" +X_FORWARDED_KEY: Final = "HTTP_X_FORWARDED_FOR" +REMOTE_ADDR_KEY: Final = "REMOTE_ADDR" +HOST_KEY: Final = "HTTP_HOST" +CONTENT_LENGTH_KEY: Final = "content-length" + +class XRayMiddleware: + get_response: Incomplete + in_lambda_ctx: bool + + def __init__(self, get_response) -> None: ... + def __call__(self, request): ... + def process_exception(self, request, exception: Exception) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi new file mode 100644 index 000000000000..142de83de16e --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/django/templates.pyi @@ -0,0 +1,5 @@ +from logging import Logger + +log: Logger + +def patch_template() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi new file mode 100644 index 000000000000..ab8e8a2feb4d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask/middleware.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +class XRayMiddleware: + app: Incomplete + in_lambda_ctx: bool + def __init__(self, app, recorder) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi new file mode 100644 index 000000000000..0f0f512d4fa9 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/flask_sqlalchemy/query.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from aws_xray_sdk.ext.sqlalchemy.query import XRaySession + +class XRayBaseQuery: ... + +class XRaySignallingSession(XRaySession): + app: Incomplete + def __init__(self, db, autocommit: bool = False, autoflush: bool = True, **options) -> None: ... + def get_bind(self, mapper=None, clause=None): ... + +class XRayFlaskSqlAlchemy: + def __init__( + self, + app=None, + use_native_unicode: bool = True, + session_options=None, + metadata=None, + query_class: type = ..., + model_class: type = ..., + ) -> None: ... + def create_session(self, options: dict[str, Incomplete]): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi new file mode 100644 index 000000000000..4f5e3a65b1c0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import add_ignored as add_ignored, patch as patch, reset_ignored as reset_ignored, unpatch as unpatch + +__all__ = ["patch", "unpatch", "add_ignored", "reset_ignored"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi new file mode 100644 index 000000000000..aaa85125c03a --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httplib/patch.pyi @@ -0,0 +1,12 @@ +from typing import Final + +httplib_client_module: Final = "http.client" +PATCH_FLAG: Final = "__xray_patched" + +def add_ignored(subclass=None, hostname=None, urls=None) -> None: ... +def reset_ignored() -> None: ... +def http_response_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def http_send_request_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def http_read_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi new file mode 100644 index 000000000000..b50265a56940 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/httpx/patch.pyi @@ -0,0 +1,9 @@ +def patch() -> None: ... + +class SyncInstrumentedTransport: + def __init__(self, transport): ... + def handle_request(self, request): ... + +class AsyncInstrumentedTransport: + def __init__(self, transport): ... + async def handle_async_request(self, request): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi new file mode 100644 index 000000000000..4b8b7d49c3a0 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/mysql/patch.pyi @@ -0,0 +1,6 @@ +from typing import Final + +MYSQL_ATTR: Final[dict[str, str]] + +def patch() -> None: ... +def sanitize_db_ver(raw: tuple[str]) -> str: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi new file mode 100644 index 000000000000..86f5664ff977 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pg8000/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi new file mode 100644 index 000000000000..969a93686fd4 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/psycopg2/patch.pyi @@ -0,0 +1 @@ +def patch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi new file mode 100644 index 000000000000..21c4ac034cb5 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymongo/patch.pyi @@ -0,0 +1,8 @@ +class XrayCommandListener: + record_full_documents: bool + def __init__(self, record_full_documents: bool) -> None: ... + def started(self, event) -> None: ... + def succeeded(self, event) -> None: ... + def failed(self, event) -> None: ... + +def patch(record_full_documents: bool = False) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi new file mode 100644 index 000000000000..a8cbba7f52bb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pymysql/patch.pyi @@ -0,0 +1,3 @@ +def patch() -> None: ... +def sanitize_db_ver(raw: tuple[str]) -> str: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi new file mode 100644 index 000000000000..d86fc62fb297 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/pynamodb/patch.pyi @@ -0,0 +1,6 @@ +from typing import Final + +PYNAMODB4: Final[bool] + +def patch() -> None: ... +def pynamodb_meta_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi new file mode 100644 index 000000000000..bd200a3bfbc1 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/requests/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def requests_processor(wrapped, instance, args, kwargs, return_value, exception, subsegment, stack) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi new file mode 100644 index 000000000000..6a54d0d6e23d --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/query.pyi @@ -0,0 +1,16 @@ +from typing import Any + +class XRaySession: ... +class XRayQuery: ... + +class XRaySessionMaker: + def __init__( + self, + bind=None, + class_: type = ..., + autoflush: bool = True, + autocommit: bool = False, + expire_on_commit: bool = True, + info: dict[Any, Any] | None = None, # it was taken from sqlalchemy stubs + **kw, + ) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi new file mode 100644 index 000000000000..78ffee475aed --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy/util/decorators.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +def decorate_all_functions(function_decorator: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... +def xray_on_call(cls, func: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... +def parse_bind(bind) -> dict[str, str]: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi new file mode 100644 index 000000000000..b65967051d08 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch, unpatch as unpatch + +__all__ = ["patch", "unpatch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi new file mode 100644 index 000000000000..86f5664ff977 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlalchemy_core/patch.pyi @@ -0,0 +1,2 @@ +def patch() -> None: ... +def unpatch() -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi new file mode 100644 index 000000000000..47b402c8e221 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/__init__.pyi @@ -0,0 +1,3 @@ +from .patch import patch as patch + +__all__ = ["patch"] diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi new file mode 100644 index 000000000000..71954e425e43 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/sqlite3/patch.pyi @@ -0,0 +1,7 @@ +from aws_xray_sdk.ext.dbapi2 import XRayTracedConn + +def patch() -> None: ... + +class XRayTracedSQLite(XRayTracedConn): + def execute(self, *args, **kwargs): ... + def executemany(self, *args, **kwargs): ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi new file mode 100644 index 000000000000..466fceaa1323 --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/ext/util.pyi @@ -0,0 +1,23 @@ +import re +from typing import Final, overload + +from aws_xray_sdk.core.models.trace_header import TraceHeader + +first_cap_re: Final[re.Pattern[str]] +all_cap_re: Final[re.Pattern[str]] +UNKNOWN_HOSTNAME: Final = "UNKNOWN HOST" + +def inject_trace_header(headers, entity) -> None: ... +def calculate_sampling_decision(trace_header, recorder, sampling_req): ... +def construct_xray_header(headers) -> TraceHeader: ... +def calculate_segment_name(host_name, recorder): ... +def prepare_response_header(origin_header, segment) -> str: ... +def to_snake_case(name: str) -> str: ... +def strip_url(url): ... + +@overload +def get_hostname(url: str | None) -> str: ... +@overload +def get_hostname(url: bytes | bytearray | None) -> str | bytes: ... + +def unwrap(obj: object, attr: str) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi new file mode 100644 index 000000000000..f9a79a65a89e --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/sdk_config.pyi @@ -0,0 +1,12 @@ +from logging import Logger +from typing import ClassVar + +log: Logger + +class SDKConfig: + XRAY_ENABLED_KEY: ClassVar[str] + DISABLED_ENTITY_NAME: ClassVar[str] + @classmethod + def sdk_enabled(cls) -> bool: ... + @classmethod + def set_sdk_enabled(cls, value: bool | None) -> None: ... diff --git a/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi b/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi new file mode 100644 index 000000000000..8052b08139fb --- /dev/null +++ b/stubs/aws-xray-sdk/aws_xray_sdk/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +VERSION: Final[str] diff --git a/stubs/behave/METADATA.toml b/stubs/behave/METADATA.toml new file mode 100644 index 000000000000..937f37b750e4 --- /dev/null +++ b/stubs/behave/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.3.*" +upstream-repository = "https://github.com/behave/behave" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/behave/behave/__init__.pyi b/stubs/behave/behave/__init__.pyi new file mode 100644 index 000000000000..70422a43ef94 --- /dev/null +++ b/stubs/behave/behave/__init__.pyi @@ -0,0 +1,13 @@ +from behave.fixture import fixture as fixture, use_fixture as use_fixture +from behave.step_registry import ( + Given as Given, + Step as Step, + Then as Then, + When as When, + given as given, + step as step, + then as then, + when as when, +) + +__all__ = ["given", "when", "then", "step", "Given", "When", "Then", "Step", "use_fixture", "fixture"] diff --git a/stubs/behave/behave/fixture.pyi b/stubs/behave/behave/fixture.pyi new file mode 100644 index 000000000000..b7a257847a1b --- /dev/null +++ b/stubs/behave/behave/fixture.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Concatenate, ParamSpec, TypeVar + +from behave.runner import Context + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +def use_fixture( + fixture_func: Callable[Concatenate[Context, _P], _T], context: Context, *fixture_args: _P.args, **fixture_kwargs: _P.kwargs +) -> _T: ... +def fixture(func: _F | None = None, name: str | None = None, pattern: str | None = None) -> _F: ... +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/behave/behave/runner.pyi b/stubs/behave/behave/runner.pyi new file mode 100644 index 000000000000..a3abfa2d0de2 --- /dev/null +++ b/stubs/behave/behave/runner.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from contextlib import AbstractContextManager +from typing import ClassVar, ParamSpec + +_P = ParamSpec("_P") + +class Context: + LAYER_NAMES: ClassVar[list[str]] + FAIL_ON_CLEANUP_ERRORS: ClassVar[bool] + + feature: Incomplete | None + scenario: Incomplete + tags: set[str] + aborted: bool + failed: bool + table: Incomplete | None + text: str | None + config: Incomplete + active_outline: Incomplete + fail_on_cleanup_errors: bool + + def __init__(self, runner) -> None: ... + def __getattr__(self, name: str) -> Incomplete: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, name: str) -> bool: ... + def abort(self, reason: str | None = None) -> None: ... + def use_or_assign_param(self, name: str, value): ... + def use_or_create_param(self, name: str, factory_func: Callable[_P, Incomplete], *args: _P.args, **kwargs: _P.kwargs): ... + def use_with_user_mode(self) -> AbstractContextManager[None]: ... + def execute_steps(self, steps_text: str) -> bool: ... + def add_cleanup(self, cleanup_func: Callable[_P, Incomplete], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + @property + def captured(self): ... + def attach(self, mime_type: str, data: bytes) -> None: ... + +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/behave/behave/step_registry.pyi b/stubs/behave/behave/step_registry.pyi new file mode 100644 index 000000000000..9b0237896c3d --- /dev/null +++ b/stubs/behave/behave/step_registry.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Concatenate, TypeVar + +from behave.runner import Context + +_F = TypeVar("_F", bound=Callable[Concatenate[Context, ...], None]) + +def given(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def when(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def then(step_text: str, **kwargs) -> Callable[[_F], _F]: ... +def step(step_text: str, **kwargs) -> Callable[[_F], _F]: ... + +# Title-case aliases +Given = given +When = when +Then = then +Step = step + +def __getattr__(name: str) -> Incomplete: ... diff --git a/stubs/binaryornot/@tests/stubtest_allowlist.txt b/stubs/binaryornot/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..742a3bb53e80 --- /dev/null +++ b/stubs/binaryornot/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +binaryornot\..+?\.logger diff --git a/stubs/binaryornot/METADATA.toml b/stubs/binaryornot/METADATA.toml new file mode 100644 index 000000000000..431cf6be18ef --- /dev/null +++ b/stubs/binaryornot/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.4.*" +upstream-repository = "https://github.com/binaryornot/binaryornot" +obsolete-since = { version = "0.5.0", date = "2026-03-07" } diff --git a/stubs/binaryornot/binaryornot/__init__.pyi b/stubs/binaryornot/binaryornot/__init__.pyi new file mode 100644 index 000000000000..4c304c608dbc --- /dev/null +++ b/stubs/binaryornot/binaryornot/__init__.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__author__: Final[str] +__email__: Final[str] +__version__: Final[str] diff --git a/stubs/binaryornot/binaryornot/check.pyi b/stubs/binaryornot/binaryornot/check.pyi new file mode 100644 index 000000000000..8ebb58019b10 --- /dev/null +++ b/stubs/binaryornot/binaryornot/check.pyi @@ -0,0 +1,3 @@ +from _typeshed import StrOrBytesPath + +def is_binary(filename: StrOrBytesPath) -> bool: ... diff --git a/stubs/binaryornot/binaryornot/helpers.pyi b/stubs/binaryornot/binaryornot/helpers.pyi new file mode 100644 index 000000000000..4534c3ffe99c --- /dev/null +++ b/stubs/binaryornot/binaryornot/helpers.pyi @@ -0,0 +1,5 @@ +from _typeshed import StrOrBytesPath + +def print_as_hex(s: str) -> None: ... +def get_starting_chunk(filename: StrOrBytesPath, length: int = 1024) -> bytes: ... +def is_binary_string(bytes_to_check: bytes | bytearray) -> bool: ... diff --git a/stubs/bleach/@tests/stubtest_allowlist.txt b/stubs/bleach/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..fd5e558aee0b --- /dev/null +++ b/stubs/bleach/@tests/stubtest_allowlist.txt @@ -0,0 +1,8 @@ +# Internal private stuff: +bleach._vendor.* + +# Is a property returning a method, simplified: +bleach.html5lib_shim.InputStreamWithMemory.changeEncoding + +# Shim for the obsolete six package, used by the vendored html5lib +bleach.six_shim diff --git a/stubs/bleach/METADATA.toml b/stubs/bleach/METADATA.toml new file mode 100644 index 000000000000..f43ce83e8f47 --- /dev/null +++ b/stubs/bleach/METADATA.toml @@ -0,0 +1,6 @@ +version = "6.4.*" +upstream-repository = "https://github.com/mozilla/bleach" +dependencies = ["types-html5lib"] + +[tool.stubtest] +extras = ["css"] diff --git a/stubs/bleach/bleach/__init__.pyi b/stubs/bleach/bleach/__init__.pyi new file mode 100644 index 000000000000..7c31c84d592b --- /dev/null +++ b/stubs/bleach/bleach/__init__.pyi @@ -0,0 +1,33 @@ +from collections.abc import Container, Iterable +from typing import TypeAlias + +from .callbacks import _Callback +from .css_sanitizer import CSSSanitizer +from .linkifier import DEFAULT_CALLBACKS as DEFAULT_CALLBACKS, Linker as Linker +from .sanitizer import ( + ALLOWED_ATTRIBUTES as ALLOWED_ATTRIBUTES, + ALLOWED_PROTOCOLS as ALLOWED_PROTOCOLS, + ALLOWED_TAGS as ALLOWED_TAGS, + Cleaner as Cleaner, + _Attributes, +) + +__all__ = ["clean", "linkify"] + +__releasedate__: str +__version__: str + +_HTMLAttrKey: TypeAlias = tuple[str | None, str] # noqa: Y047 + +def clean( + text: str, + tags: Iterable[str] = ..., + attributes: _Attributes = ..., + protocols: Iterable[str] = ..., + strip: bool = False, + strip_comments: bool = True, + css_sanitizer: CSSSanitizer | None = None, +) -> str: ... +def linkify( + text: str, callbacks: Iterable[_Callback] = ..., skip_tags: Container[str] | None = None, parse_email: bool = False +) -> str: ... diff --git a/stubs/bleach/bleach/callbacks.pyi b/stubs/bleach/bleach/callbacks.pyi new file mode 100644 index 000000000000..0ea1145fac8f --- /dev/null +++ b/stubs/bleach/bleach/callbacks.pyi @@ -0,0 +1,13 @@ +from collections.abc import MutableMapping +from typing import Protocol, TypeAlias, type_check_only + +from bleach import _HTMLAttrKey + +_HTMLAttrs: TypeAlias = MutableMapping[_HTMLAttrKey, str] + +@type_check_only +class _Callback(Protocol): # noqa: Y046 + def __call__(self, attrs: _HTMLAttrs, new: bool = ..., /) -> _HTMLAttrs: ... + +def nofollow(attrs: _HTMLAttrs, new: bool = False) -> _HTMLAttrs: ... +def target_blank(attrs: _HTMLAttrs, new: bool = False) -> _HTMLAttrs: ... diff --git a/stubs/bleach/bleach/css_sanitizer.pyi b/stubs/bleach/bleach/css_sanitizer.pyi new file mode 100644 index 000000000000..9fa319c6d79c --- /dev/null +++ b/stubs/bleach/bleach/css_sanitizer.pyi @@ -0,0 +1,12 @@ +from collections.abc import Container +from typing import Final + +ALLOWED_CSS_PROPERTIES: Final[frozenset[str]] +ALLOWED_SVG_PROPERTIES: Final[frozenset[str]] + +class CSSSanitizer: + allowed_css_properties: Container[str] + allowed_svg_properties: Container[str] + + def __init__(self, allowed_css_properties: Container[str] = ..., allowed_svg_properties: Container[str] = ...) -> None: ... + def sanitize_css(self, style: str) -> str: ... diff --git a/stubs/bleach/bleach/html5lib_shim.pyi b/stubs/bleach/bleach/html5lib_shim.pyi new file mode 100644 index 000000000000..d781faa9c7bb --- /dev/null +++ b/stubs/bleach/bleach/html5lib_shim.pyi @@ -0,0 +1,71 @@ +import re +from codecs import CodecInfo +from collections.abc import Generator, Iterable, Iterator +from typing import Any, Final, Protocol, type_check_only + +# We don't re-export any `html5lib` types / values here, because they are not +# really public and may change at any time. This is just a helper module, +# import things directly from `html5lib` instead! +from html5lib import HTMLParser +from html5lib._inputstream import HTMLBinaryInputStream, HTMLUnicodeInputStream +from html5lib._tokenizer import HTMLTokenizer +from html5lib._trie import Trie +from html5lib.serializer import HTMLSerializer +from html5lib.treewalkers.base import TreeWalker + +# Is actually webencodings.Encoding +@type_check_only +class _Encoding(Protocol): + name: str + codec_info: CodecInfo + def __init__(self, name: str, codec_info: CodecInfo) -> None: ... + +HTML_TAGS: Final[frozenset[str]] +HTML_TAGS_BLOCK_LEVEL: Final[frozenset[str]] +AMP_SPLIT_RE: Final[re.Pattern[str]] +ENTITIES: Final[dict[str, str]] +ENTITIES_TRIE: Final[Trie] +TAG_TOKEN_TYPES: Final[set[int]] +TAG_TOKEN_TYPE_CHARACTERS: Final[int] +TAG_TOKEN_TYPE_END: Final[int] +TAG_TOKEN_TYPE_PARSEERROR: Final[int] +TAG_TOKEN_TYPE_START: Final[int] + +class InputStreamWithMemory: + position = HTMLUnicodeInputStream.position + reset = HTMLUnicodeInputStream.reset + def __init__(self, inner_stream: HTMLUnicodeInputStream) -> None: ... + @property + def errors(self) -> list[str]: ... + @property + def charEncoding(self) -> tuple[_Encoding, str]: ... + # If inner_stream wasn't a HTMLBinaryInputStream, this will error at runtime + # Is a property returning a method, simplified: + changeEncoding = HTMLBinaryInputStream.changeEncoding + def char(self) -> str: ... + def charsUntil(self, characters: Iterable[str], opposite: bool = False) -> str: ... + def unget(self, char: str | None) -> None: ... + def get_tag(self) -> str: ... + def start_tag(self) -> None: ... + +class BleachHTMLTokenizer(HTMLTokenizer): + consume_entities: bool + stream: InputStreamWithMemory # type: ignore[assignment] + emitted_last_token: dict[str, Any] | None + def __init__(self, consume_entities: bool = False, **kwargs: Any) -> None: ... + +class BleachHTMLParser(HTMLParser): + tags: list[str] | None + strip: bool + consume_entities: bool + def __init__(self, tags: Iterable[str] | None, strip: bool, consume_entities: bool, **kwargs: Any) -> None: ... + +class BleachHTMLSerializer(HTMLSerializer): + escape_rcdata: bool + def escape_base_amp(self, stoken: str) -> Generator[str]: ... + def serialize(self, treewalker: TreeWalker, encoding: str | None = None) -> Generator[str]: ... # type: ignore[override] + +def convert_entity(value: str) -> str | None: ... +def convert_entities(text: str) -> str: ... +def match_entity(stream: str) -> str | None: ... +def next_possible_entity(text: str) -> Iterator[str]: ... diff --git a/stubs/bleach/bleach/linkifier.pyi b/stubs/bleach/bleach/linkifier.pyi new file mode 100644 index 000000000000..35d311f13dd1 --- /dev/null +++ b/stubs/bleach/bleach/linkifier.pyi @@ -0,0 +1,60 @@ +from collections.abc import Container, Iterable, Iterator, Sequence +from re import Pattern +from typing import Any, Final, TypeAlias + +from html5lib.filters.base import Filter +from html5lib.treewalkers.base import TreeWalker + +from .callbacks import _Callback, _HTMLAttrs + +DEFAULT_CALLBACKS: Final[list[_Callback]] +TLDS: Final[list[str]] + +def build_url_re(tlds: Iterable[str] = ..., protocols: Iterable[str] = ...) -> Pattern[str]: ... + +URL_RE: Final[Pattern[str]] +PROTO_RE: Final[Pattern[str]] + +def build_email_re(tlds: Iterable[str] = ...) -> Pattern[str]: ... + +EMAIL_RE: Final[Pattern[str]] + +class Linker: + def __init__( + self, + callbacks: Iterable[_Callback] = ..., + skip_tags: Container[str] | None = None, + parse_email: bool = False, + url_re: Pattern[str] = ..., + email_re: Pattern[str] = ..., + recognized_tags: Container[str] | None = ..., + ) -> None: ... + def linkify(self, text: str) -> str: ... + +# TODO: `_Token` might be converted into `TypedDict` +# or `html5lib` token might be reused +_Token: TypeAlias = dict[str, Any] + +class LinkifyFilter(Filter[_Token]): + callbacks: Iterable[_Callback] + skip_tags: Container[str] + parse_email: bool + url_re: Pattern[str] + email_re: Pattern[str] + def __init__( + self, + source: TreeWalker, + callbacks: Iterable[_Callback] | None = ..., + skip_tags: Container[str] | None = None, + parse_email: bool = False, + url_re: Pattern[str] = ..., + email_re: Pattern[str] = ..., + ) -> None: ... + def apply_callbacks(self, attrs: _HTMLAttrs, is_new: bool) -> _HTMLAttrs | None: ... + def extract_character_data(self, token_list: Iterable[_Token]) -> str: ... + def handle_email_addresses(self, src_iter: Iterable[_Token]) -> Iterator[_Token]: ... + def strip_non_url_bits(self, fragment: str) -> tuple[str, str, str]: ... + def handle_links(self, src_iter: Iterable[_Token]) -> Iterator[_Token]: ... + def handle_a_tag(self, token_buffer: Sequence[_Token]) -> Iterator[_Token]: ... + def extract_entities(self, token: _Token) -> Iterator[_Token]: ... + def __iter__(self) -> Iterator[_Token]: ... diff --git a/stubs/bleach/bleach/parse_shim.pyi b/stubs/bleach/bleach/parse_shim.pyi new file mode 100644 index 000000000000..5b1ef5a35a59 --- /dev/null +++ b/stubs/bleach/bleach/parse_shim.pyi @@ -0,0 +1 @@ +from urllib import parse as parse diff --git a/stubs/bleach/bleach/sanitizer.pyi b/stubs/bleach/bleach/sanitizer.pyi new file mode 100644 index 000000000000..8484b419fd4f --- /dev/null +++ b/stubs/bleach/bleach/sanitizer.pyi @@ -0,0 +1,91 @@ +from collections.abc import Callable, Container, Iterable, Iterator +from re import Pattern +from typing import Final, Protocol, TypeAlias, type_check_only + +from html5lib.filters.base import Filter +from html5lib.filters.sanitizer import Filter as SanitizerFilter +from html5lib.treewalkers.base import TreeWalker + +from . import _HTMLAttrKey +from .css_sanitizer import CSSSanitizer +from .html5lib_shim import BleachHTMLParser, BleachHTMLSerializer +from .linkifier import _Token + +ALLOWED_TAGS: Final[frozenset[str]] +ALLOWED_ATTRIBUTES: Final[dict[str, list[str]]] +ALLOWED_PROTOCOLS: Final[frozenset[str]] + +INVISIBLE_CHARACTERS: Final[str] +INVISIBLE_CHARACTERS_RE: Final[Pattern[str]] +INVISIBLE_REPLACEMENT_CHAR: Final = "?" + +class NoCssSanitizerWarning(UserWarning): ... + +@type_check_only +class _FilterConstructor(Protocol): + def __call__(self, *, source: BleachSanitizerFilter) -> Filter: ... + +# _FilterConstructor used to be called _Filter +# this alias is obsolete and can potentially be removed in the future +_Filter: TypeAlias = _FilterConstructor # noqa: Y047 + +_AttributeFilter: TypeAlias = Callable[[str, str, str], bool] +_AttributeDict: TypeAlias = dict[str, list[str] | _AttributeFilter] | dict[str, list[str]] | dict[str, _AttributeFilter] +_Attributes: TypeAlias = _AttributeFilter | _AttributeDict | list[str] + +class Cleaner: + tags: Iterable[str] + attributes: _Attributes + protocols: Iterable[str] + strip: bool + strip_comments: bool + filters: Iterable[_FilterConstructor] + css_sanitizer: CSSSanitizer | None + parser: BleachHTMLParser + walker: TreeWalker + serializer: BleachHTMLSerializer + def __init__( + self, + tags: Iterable[str] = ..., + attributes: _Attributes = ..., + protocols: Iterable[str] = ..., + strip: bool = False, + strip_comments: bool = True, + filters: Iterable[_FilterConstructor] | None = None, + css_sanitizer: CSSSanitizer | None = None, + ) -> None: ... + def clean(self, text: str) -> str: ... + +def attribute_filter_factory(attributes: _Attributes) -> _AttributeFilter: ... + +class BleachSanitizerFilter(SanitizerFilter): + allowed_tags: frozenset[str] + allowed_protocols: frozenset[str] + attr_filter: _AttributeFilter + strip_disallowed_tags: bool + strip_html_comments: bool + attr_val_is_uri: frozenset[_HTMLAttrKey] + svg_attr_val_allows_ref: frozenset[_HTMLAttrKey] + svg_allow_local_href: frozenset[_HTMLAttrKey] + css_sanitizer: CSSSanitizer | None + def __init__( + self, + source: TreeWalker, + allowed_tags: Iterable[str] = ..., + attributes: _Attributes = ..., + allowed_protocols: Iterable[str] = ..., + attr_val_is_uri: frozenset[_HTMLAttrKey] = ..., + svg_attr_val_allows_ref: frozenset[_HTMLAttrKey] = ..., + svg_allow_local_href: frozenset[_HTMLAttrKey] = ..., + strip_disallowed_tags: bool = False, + strip_html_comments: bool = True, + css_sanitizer: CSSSanitizer | None = None, + ) -> None: ... + def sanitize_stream(self, token_iterator: Iterable[_Token]) -> Iterator[_Token]: ... + def merge_characters(self, token_iterator: Iterable[_Token]) -> Iterator[_Token]: ... + def __iter__(self) -> Iterator[_Token]: ... + def sanitize_token(self, token: _Token) -> _Token | list[_Token] | None: ... # type: ignore[override] + def sanitize_characters(self, token: _Token) -> _Token | list[_Token]: ... + def sanitize_uri_value(self, value: str, allowed_protocols: Container[str]) -> str | None: ... + def allow_token(self, token: _Token) -> _Token: ... + def disallowed_token(self, token: _Token) -> _Token: ... diff --git a/stubs/boltons/@tests/stubtest_allowlist.txt b/stubs/boltons/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2ad9d612df92 --- /dev/null +++ b/stubs/boltons/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +boltons.funcutils.CachedInstancePartial.__partialmethod__ +boltons.funcutils.InstancePartial.__partialmethod__ diff --git a/stubs/boltons/METADATA.toml b/stubs/boltons/METADATA.toml new file mode 100644 index 000000000000..9c5868f7d067 --- /dev/null +++ b/stubs/boltons/METADATA.toml @@ -0,0 +1,2 @@ +version = "26.1.*" +upstream-repository = "https://github.com/mahmoud/boltons" diff --git a/stubs/boltons/boltons/__init__.pyi b/stubs/boltons/boltons/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/boltons/boltons/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/boltons/boltons/cacheutils.pyi b/stubs/boltons/boltons/cacheutils.pyi new file mode 100644 index 000000000000..978da569d563 --- /dev/null +++ b/stubs/boltons/boltons/cacheutils.pyi @@ -0,0 +1,152 @@ +import weakref +from _typeshed import Incomplete, SupportsItems, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Hashable, Iterable, Iterator, Mapping +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +PREV: int +NEXT: int +KEY: int +VALUE: int +DEFAULT_MAX_SIZE: int + +class LRI(dict[_KT, _VT]): + hit_count: int + miss_count: int + soft_miss_count: int + max_size: int + on_miss: Callable[[_KT], _VT] | None + def __init__(self, max_size: int = 128, values=None, on_miss: Callable[[_KT], _VT] | None = None) -> None: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + + @overload + def get(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT) -> _VT: ... + @overload + def get(self, key: _KT, default: _T) -> _T | _VT: ... + + def __delitem__(self, key: _KT) -> None: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _T) -> _T | _VT: ... + + def popitem(self) -> tuple[_KT, _VT]: ... + def clear(self) -> None: ... + def copy(self) -> Self: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + def update(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F: _VT) -> None: ... # type: ignore[override] + +class LRU(LRI[_KT, _VT]): + def __getitem__(self, key: _KT) -> _VT: ... + +def make_cache_key( + args: Iterable[Hashable], + kwargs: SupportsItems[Hashable, Hashable], + typed: bool = False, + kwarg_mark: object = ..., + fasttypes: frozenset[type] = ..., +): ... + +class CachedFunction: + func: Incomplete + get_cache: Incomplete + scoped: Incomplete + typed: Incomplete + key_func: Incomplete + def __init__( + self, + func, + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, + ): ... + def __call__(self, *args, **kwargs): ... + +class CachedMethod: + func: Incomplete + get_cache: Incomplete + scoped: Incomplete + typed: Incomplete + key_func: Incomplete + bound_to: Incomplete + def __init__( + self, + func, + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, + ): ... + def __get__(self, obj, objtype=None): ... + def __call__(self, *args, **kwargs): ... + +def cached( + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, +): ... +def cachedmethod( + cache: Mapping[Any, Any] | Callable[..., Incomplete], + scoped: bool = True, + typed: bool = False, + key: Callable[..., Incomplete] | None = None, +): ... + +class cachedproperty(Generic[_KT, _VT]): + func: Callable[[_KT], _VT] + def __init__(self, func: Callable[[_KT], _VT]) -> None: ... + + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: _KT, objtype: type | None = None) -> _VT: ... + +class ThresholdCounter(Generic[_T]): + total: int + def __init__(self, threshold: float = 0.001) -> None: ... + @property + def threshold(self) -> float: ... + def add(self, key: _T) -> None: ... + def elements(self) -> Iterator[_T]: ... + def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... + def get_common_count(self) -> int: ... + def get_uncommon_count(self) -> int: ... + def get_commonality(self) -> float: ... + def __getitem__(self, key: _T) -> int: ... + def __len__(self) -> int: ... + def __contains__(self, key: _T) -> bool: ... + def iterkeys(self) -> Iterator[_T]: ... + def keys(self) -> list[_T]: ... + def itervalues(self) -> Generator[int]: ... + def values(self) -> list[int]: ... + def iteritems(self) -> Generator[tuple[_T, int]]: ... + def items(self) -> list[tuple[_T, int]]: ... + def get(self, key: _T, default: int = 0) -> int: ... + def update(self, iterable: Iterable[_T] | Mapping[_T, int], **kwargs: Iterable[_T] | Mapping[_T, int]) -> None: ... + +class MinIDMap(Generic[_T]): + mapping: weakref.WeakKeyDictionary[_T, tuple[int, weakref.ReferenceType[_T]]] + ref_map: dict[weakref.ReferenceType[_T], int] + free: list[int] + def __init__(self) -> None: ... + def get(self, a: _T) -> int: ... + def drop(self, a: _T) -> None: ... + def __contains__(self, a: _T) -> bool: ... + def __iter__(self) -> Iterator[_T]: ... + def __len__(self) -> int: ... + def iteritems(self) -> Iterator[tuple[_T, int]]: ... diff --git a/stubs/boltons/boltons/debugutils.pyi b/stubs/boltons/boltons/debugutils.pyi new file mode 100644 index 000000000000..6b6f8f6989a4 --- /dev/null +++ b/stubs/boltons/boltons/debugutils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Callable +from typing import Any + +def pdb_on_signal(signalnum: int | None = None) -> None: ... +def pdb_on_exception(limit: int = 100) -> None: ... +def wrap_trace( + obj, hook: Callable[..., Any] = ..., which: str | None = None, events: str | None = None, label: str | None = None +): ... + +__all__ = ["pdb_on_signal", "pdb_on_exception", "wrap_trace"] diff --git a/stubs/boltons/boltons/deprutils.pyi b/stubs/boltons/boltons/deprutils.pyi new file mode 100644 index 000000000000..2e25d98e748e --- /dev/null +++ b/stubs/boltons/boltons/deprutils.pyi @@ -0,0 +1,8 @@ +from types import ModuleType +from typing import Any + +class DeprecatableModule(ModuleType): + def __init__(self, module: ModuleType) -> None: ... + def __getattribute__(self, name: str) -> Any: ... + +def deprecate_module_member(mod_name: str, name: str, message: str) -> None: ... diff --git a/stubs/boltons/boltons/dictutils.pyi b/stubs/boltons/boltons/dictutils.pyi new file mode 100644 index 000000000000..e2a8277fca00 --- /dev/null +++ b/stubs/boltons/boltons/dictutils.pyi @@ -0,0 +1,129 @@ +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Generator, ItemsView, Iterable, Iterator, KeysView, ValuesView +from typing import Any, Generic, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_T = TypeVar("_T") + +class OrderedMultiDict(dict[_KT, _VT]): + def __reduce__(self) -> tuple[type[Self], tuple[()], list[tuple[_KT, _VT]]]: ... + def add(self, k: _KT, v: _VT) -> None: ... + def addlist(self, k: _KT, v: Iterable[_VT]) -> None: ... + def clear(self) -> None: ... + def copy(self) -> Self: ... + def counts(self) -> OrderedMultiDict[_KT, int]: ... + + @overload # type: ignore[override] + @classmethod + def fromkeys(cls, keys: Iterable[_KT], default: None = None) -> OrderedMultiDict[_KT, Any | None]: ... + @overload + @classmethod + def fromkeys(cls, keys: Iterable[_KT], default: _T) -> OrderedMultiDict[_KT, _T]: ... + + @overload # type: ignore[override] + def get(self, k: _KT, default: None = None) -> _VT | None: ... + @overload + def get(self, k: _KT, default: _VT) -> _VT: ... + + @overload + def getlist(self, k: _KT) -> list[_VT]: ... + @overload + def getlist(self, k: _KT, default: _T) -> list[_VT] | _T: ... + + def inverted(self) -> OrderedMultiDict[_VT, _KT]: ... + def items(self, multi: bool = False) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def iteritems(self, multi: bool = False) -> Generator[tuple[_KT, _VT]]: ... + def iterkeys(self, multi: bool = False) -> Generator[_KT]: ... + def itervalues(self, multi: bool = False) -> Generator[_VT]: ... + def keys(self, multi: bool = False) -> list[_KT]: ... # type: ignore[override] + def pop(self, k: _KT, default: _VT = ...) -> _VT: ... # type: ignore[override] + def popall(self, k: _KT, default: _VT = ...) -> list[_VT]: ... + def poplast(self, k: _KT = ..., default: _VT = ...) -> _VT: ... + + @overload # type: ignore[override] + def setdefault(self, k: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, k: _KT, default: _VT) -> _VT: ... + + def sorted(self, key: _KT | None = None, reverse: bool = False) -> Self: ... + def sortedvalues(self, key: _KT | None = None, reverse: bool = False) -> Self: ... + def todict(self, multi: bool = False) -> dict[_KT, _VT]: ... + def update(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F) -> None: ... # type: ignore[override] + def update_extend(self, E: SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]], **F) -> None: ... + def values(self, multi: bool = False) -> list[_VT]: ... # type: ignore[override] + def viewitems(self) -> ItemsView[_KT, _VT]: ... + def viewkeys(self) -> KeysView[_KT]: ... + def viewvalues(self) -> ValuesView[_VT]: ... + +OMD: TypeAlias = OrderedMultiDict[_KT, _VT] +MultiDict: TypeAlias = OrderedMultiDict[_KT, _VT] + +class FastIterOrderedMultiDict(OrderedMultiDict[_KT, _VT]): # undocumented + def iteritems(self, multi: bool = False) -> Generator[tuple[_KT, _VT]]: ... + def iterkeys(self, multi: bool = False) -> Generator[_KT]: ... + +class OneToOne(dict[_KT, _VT]): + __slots__ = ("inv",) + inv: OneToOne[_VT, _KT] + def clear(self) -> None: ... + def copy(self) -> Self: ... + def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def popitem(self) -> tuple[_KT, _VT]: ... + + @overload + def setdefault(self, key: _KT, default: None = None) -> _VT | None: ... + @overload + def setdefault(self, key: _KT, default: _VT) -> _VT: ... + + @classmethod + def unique(cls, *a, **kw) -> Self: ... + def update(self, dict_or_iterable, **kw) -> None: ... # type: ignore[override] + +class ManyToMany(Generic[_KT, _VT]): + data: dict[_KT, set[_VT]] + inv: ManyToMany[_VT, _KT] + def __contains__(self, key: object) -> bool: ... + def __delitem__(self, key: _KT) -> None: ... + def __eq__(self, other): ... + def __getitem__(self, key: _KT) -> frozenset[_VT]: ... + def __init__( + self, items: ManyToMany[_KT, _VT] | SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]] | None = None + ) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + def __setitem__(self, key: _KT, vals: Iterable[_VT]) -> None: ... + def add(self, key: _KT, val: _VT) -> None: ... + + @overload + def get(self, key: _KT) -> frozenset[_VT]: ... + @overload + def get(self, key: _KT, default: _T) -> frozenset[_VT] | _T: ... + + def iteritems(self) -> Generator[tuple[_KT, _VT]]: ... + def keys(self) -> KeysView[_KT]: ... + def remove(self, key: _KT, val: _VT) -> None: ... + def replace(self, key: _KT, newkey: _KT) -> None: ... + def update(self, iterable: ManyToMany[_KT, _VT] | SupportsKeysAndGetItem[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + +def subdict(d: dict[_KT, _VT], keep: Iterable[_KT] | None = None, drop: Iterable[_KT] | None = None) -> dict[_KT, _VT]: ... + +class FrozenHashError(TypeError): ... # undocumented + +class FrozenDict(dict[_KT, _VT]): + __slots__ = ("_hash",) + def __copy__(self) -> Self: ... + @classmethod + def fromkeys(cls, keys: Iterable[_KT], value: _VT | None = None) -> Self: ... # type: ignore[override] + def updated(self, *a, **kw) -> Self: ... + def __ior__(self, *a, **kw) -> Never: ... # type: ignore[misc] # noqa: Y034 # Signature conflicts with superclass + def __setitem__(self, *a, **kw) -> Never: ... + def __delitem__(self, *a, **kw) -> Never: ... + def update(self, *a, **kw) -> Never: ... + def pop(self, *a, **kw) -> Never: ... + def popitem(self, *a, **kw) -> Never: ... + def setdefault(self, *a, **kw) -> Never: ... + def clear(self, *a, **kw) -> Never: ... + +__all__ = ["MultiDict", "OMD", "OrderedMultiDict", "OneToOne", "ManyToMany", "subdict", "FrozenDict"] diff --git a/stubs/boltons/boltons/easterutils.pyi b/stubs/boltons/boltons/easterutils.pyi new file mode 100644 index 000000000000..bea7b390f909 --- /dev/null +++ b/stubs/boltons/boltons/easterutils.pyi @@ -0,0 +1,3 @@ +from typing_extensions import Never + +def gobs_program() -> Never: ... diff --git a/stubs/boltons/boltons/ecoutils.pyi b/stubs/boltons/boltons/ecoutils.pyi new file mode 100644 index 000000000000..c02820701d97 --- /dev/null +++ b/stubs/boltons/boltons/ecoutils.pyi @@ -0,0 +1,26 @@ +from typing import Any + +ECO_VERSION: str +HAVE_URANDOM: bool +INSTANCE_ID: str +IS_64BIT: bool +HAVE_UCS4: bool +HAVE_READLINE: bool +SQLITE_VERSION: str +OPENSSL_VERSION: str +TKINTER_VERSION: str +ZLIB_VERSION: str +EXPAT_VERSION: str +CPU_COUNT: int +HAVE_THREADING: bool +HAVE_IPV6: bool +RLIMIT_FDS_SOFT: int +RLIMIT_FDS_HARD: int +START_TIME_INFO: dict[str, str | float] + +def getrandbits(k: int) -> int: ... +def get_python_info() -> dict[str, Any]: ... +def get_profile(**kwargs) -> dict[str, Any]: ... +def get_profile_json(indent: bool = False) -> str: ... +def main() -> None: ... +def dumps(val: Any, indent: int) -> str: ... diff --git a/stubs/boltons/boltons/excutils.pyi b/stubs/boltons/boltons/excutils.pyi new file mode 100644 index 000000000000..bb6a42dbcd11 --- /dev/null +++ b/stubs/boltons/boltons/excutils.pyi @@ -0,0 +1,11 @@ +from typing import Any +from typing_extensions import Self + +class ExceptionCauseMixin(Exception): + cause: Any + def __new__(cls, *args, **kw) -> Self: ... + def get_str(self) -> str: ... + +class MathError(ExceptionCauseMixin, ValueError): ... + +__all__ = ["ExceptionCauseMixin"] diff --git a/stubs/boltons/boltons/fileutils.pyi b/stubs/boltons/boltons/fileutils.pyi new file mode 100644 index 000000000000..8e2fb8b75b27 --- /dev/null +++ b/stubs/boltons/boltons/fileutils.pyi @@ -0,0 +1,96 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath +from collections.abc import Callable, Generator, Iterable +from os import PathLike +from types import TracebackType +from typing import IO, Any, TypeVar, overload +from typing_extensions import Never, Self + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) + +def mkdir_p(path: StrOrBytesPath) -> None: ... +def rotate_file(filename: PathLike[str], *, keep: int = 5) -> None: ... + +class FilePerms: + user: str + group: str + other: str + def __init__(self, user: str = "", group: str = "", other: str = "") -> None: ... + @classmethod + def from_int(cls, i: int) -> Self: ... + @classmethod + def from_path(cls, path: StrOrBytesPath) -> Self: ... + def __int__(self) -> int: ... + +def atomic_save(dest_path: str, **kwargs) -> AtomicSaver: ... + +class AtomicSaver: + dest_path: str + overwrite: bool + file_perms: int | None + overwrite_part: bool + part_filename: str | None + rm_part_on_exc: bool + text_mode: bool + buffering: int + dest_dir: str + part_path: str + mode: str + open_flags: int + part_file: str | None + def __init__(self, dest_path: str, **kwargs) -> None: ... + def setup(self) -> None: ... + def __enter__(self) -> IO[Any] | None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +def iter_find_files( + directory: str, + patterns: str | Iterable[str], + ignored: str | Iterable[str] | None = None, + include_dirs: bool = False, + max_depth: int | None = None, +) -> Generator[str]: ... + +@overload +def copy_tree( + src: _StrPathT, dst: _StrPathT, symlinks: bool = False, ignore: Callable[[_StrPathT, list[str]], Iterable[str]] | None = None +) -> None: ... +@overload +def copy_tree( + src: _BytesPathT, + dst: _BytesPathT, + symlinks: bool = False, + ignore: Callable[[_BytesPathT, list[bytes]], Iterable[bytes]] | None = None, +) -> None: ... + +copytree = copy_tree + +class DummyFile: + name: StrOrBytesPath + mode: str + closed: bool + errors: None + isatty: bool + encoding: None + newlines: None + softspace: int + def __init__(self, path: StrOrBytesPath, mode: str = "r", buffering: int | None = None) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def next(self) -> Never: ... + def read(self, size: int = 0) -> str: ... + def readline(self, size: int = 0) -> str: ... + def readlines(self, size: int = 0) -> list[str]: ... + def seek(self) -> None: ... + def tell(self) -> int: ... + def truncate(self) -> None: ... + def write(self, string: str) -> None: ... + def writelines(self, list_of_strings: list[str]) -> None: ... + def __next__(self) -> Never: ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +__all__ = ["mkdir_p", "atomic_save", "AtomicSaver", "FilePerms", "iter_find_files", "copytree"] diff --git a/stubs/boltons/boltons/formatutils.pyi b/stubs/boltons/boltons/formatutils.pyi new file mode 100644 index 000000000000..b9f3eb897b54 --- /dev/null +++ b/stubs/boltons/boltons/formatutils.pyi @@ -0,0 +1,46 @@ +from collections.abc import Callable +from typing import Generic, TypeVar + +_T = TypeVar("_T") + +def construct_format_field_str(fname: str | None, fspec: str | None, conv: str | None) -> str: ... +def infer_positional_format_args(fstr: str) -> str: ... +def get_format_args(fstr: str) -> tuple[list[tuple[int, type]], list[tuple[str, type]]]: ... +def tokenize_format_str(fstr: str, resolve_pos: bool = True) -> list[str | BaseFormatField]: ... + +class BaseFormatField: + def __init__(self, fname: str, fspec: str = "", conv: str | None = None) -> None: ... + base_name: str + fname: str + subpath: str + is_positional: bool + def set_fname(self, fname: str) -> None: ... + subfields: list[str] + fspec: str + type_char: str + type_func: str + def set_fspec(self, fspec) -> None: ... + conv: str | None + conv_func: str | None + def set_conv(self, conv: str | None) -> None: ... + @property + def fstr(self) -> str: ... + +class DeferredValue(Generic[_T]): + func: Callable[[], _T] + cache_value: bool + def __init__(self, func: Callable[[], _T], cache_value: bool = True) -> None: ... + def get_value(self) -> _T: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __unicode__(self) -> str: ... + def __format__(self, fmt: str) -> str: ... + +__all__ = [ + "DeferredValue", + "get_format_args", + "tokenize_format_str", + "construct_format_field_str", + "infer_positional_format_args", + "BaseFormatField", +] diff --git a/stubs/boltons/boltons/funcutils.pyi b/stubs/boltons/boltons/funcutils.pyi new file mode 100644 index 000000000000..d9b02dc9eb2e --- /dev/null +++ b/stubs/boltons/boltons/funcutils.pyi @@ -0,0 +1,68 @@ +import functools +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from functools import total_ordering as total_ordering +from typing import TypeVar + +_R = TypeVar("_R") + +NO_DEFAULT: Incomplete + +def inspect_formatargspec( + args, + varargs=None, + varkw=None, + defaults=None, + kwonlyargs=(), + kwonlydefaults={}, + annotations={}, + formatarg=..., + formatvarargs=..., + formatvarkw=..., + formatvalue=..., + formatreturns=..., + formatannotation=..., +): ... +def get_module_callables(mod, ignore=None): ... +def mro_items(type_obj): ... +def dir_dict(obj, raise_exc: bool = False): ... +def copy_function(orig, copy_dict: bool = True): ... +def partial_ordering(cls): ... + +class InstancePartial(functools.partial[Incomplete]): + def __get__(self, obj, obj_type): ... + +class CachedInstancePartial(functools.partial[Incomplete]): + __name__: Incomplete + def __set_name__(self, obj_type, name) -> None: ... + __doc__: Incomplete + __module__: Incomplete + def __get__(self, obj, obj_type): ... + +partial = CachedInstancePartial + +def format_invocation(name: str = "", args=(), kwargs=None, **kw): ... +def format_exp_repr(obj, pos_names, req_names=None, opt_names=None, opt_key=None): ... +def format_nonexp_repr(obj, req_names=None, opt_names=None, opt_key=None): ... +def wraps(func, injected=None, expected=None, **kw): ... +def update_wrapper(wrapper, func, injected=None, expected=None, build_from=None, **kw): ... + +class FunctionBuilder: + name: Incomplete + def __init__(self, name, **kw) -> None: ... + def get_sig_str(self, with_annotations: bool = True): ... + def get_invocation_str(self): ... + @classmethod + def from_func(cls, func): ... + def get_func(self, execdict=None, add_source: bool = True, with_dict: bool = True): ... + def get_defaults_dict(self): ... + def get_arg_names(self, only_required: bool = False): ... + defaults: Incomplete + def add_arg(self, arg_name, default=..., kwonly: bool = False) -> None: ... + def remove_arg(self, arg_name) -> None: ... + +class MissingArgument(ValueError): ... +class ExistingArgument(ValueError): ... + +def noop(*args: Unused, **kwargs: Unused) -> None: ... +def once(func: Callable[[], _R]) -> Callable[[], _R]: ... diff --git a/stubs/boltons/boltons/gcutils.pyi b/stubs/boltons/boltons/gcutils.pyi new file mode 100644 index 000000000000..33e8006102b9 --- /dev/null +++ b/stubs/boltons/boltons/gcutils.pyi @@ -0,0 +1,16 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +def get_all(type_obj: type[_T], include_subtypes: bool = True) -> list[_T]: ... + +class GCToggler: + postcollect: bool + def __init__(self, postcollect: bool = False) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... + +toggle_gc: GCToggler +toggle_gc_postcollect: GCToggler + +__all__ = ["get_all", "GCToggler", "toggle_gc", "toggle_gc_postcollect"] diff --git a/stubs/boltons/boltons/ioutils.pyi b/stubs/boltons/boltons/ioutils.pyi new file mode 100644 index 000000000000..90bb47dad2e1 --- /dev/null +++ b/stubs/boltons/boltons/ioutils.pyi @@ -0,0 +1,92 @@ +import abc +from _typeshed import Incomplete +from abc import abstractmethod + +READ_CHUNK_SIZE: int +EINVAL: Incomplete + +class SpooledIOBase(metaclass=abc.ABCMeta): + __metaclass__: Incomplete + def __init__(self, max_size: int = 5000000, dir=None) -> None: ... + @abstractmethod + def read(self, n: int = -1): ... + @abstractmethod + def write(self, s): ... + @abstractmethod + def seek(self, pos, mode: int = 0): ... + @abstractmethod + def readline(self, length=None): ... + @abstractmethod + def readlines(self, sizehint: int = 0): ... + def writelines(self, lines) -> None: ... + @abstractmethod + def rollover(self): ... + @abstractmethod + def tell(self): ... + @property + @abc.abstractmethod + def buffer(self): ... + @property + @abc.abstractmethod + def len(self): ... + softspace: Incomplete + def close(self): ... + def flush(self): ... + def isatty(self): ... + def next(self): ... + @property + def closed(self): ... + @property + def pos(self): ... + @property + def buf(self): ... + def fileno(self): ... + def truncate(self, size=None): ... + def getvalue(self): ... + def seekable(self): ... + def readable(self): ... + def writable(self): ... + __next__: Incomplete + def __len__(self): ... + def __iter__(self): ... + def __enter__(self): ... + def __exit__(self, *args) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __bool__(self): ... + def __del__(self) -> None: ... + __nonzero__: Incomplete + +class SpooledBytesIO(SpooledIOBase): + def read(self, n: int = -1): ... + def write(self, s) -> None: ... + def seek(self, pos, mode: int = 0): ... + def readline(self, length=None): ... + def readlines(self, sizehint: int = 0): ... + def rollover(self) -> None: ... + @property + def buffer(self): ... + @property + def len(self): ... + def tell(self): ... + +class SpooledStringIO(SpooledIOBase): + def __init__(self, *args, **kwargs) -> None: ... + def read(self, n: int = -1): ... + def write(self, s) -> None: ... + def seek(self, pos, mode: int = 0): ... + def readline(self, length=None): ... + def readlines(self, sizehint: int = 0): ... + @property + def buffer(self): ... + def rollover(self) -> None: ... + def tell(self): ... + @property + def len(self): ... + +def is_text_fileobj(fileobj) -> bool: ... + +class MultiFileReader: + def __init__(self, *fileobjs) -> None: ... + def read(self, amt=None): ... + def seek(self, offset, whence=0) -> None: ... diff --git a/stubs/boltons/boltons/iterutils.pyi b/stubs/boltons/boltons/iterutils.pyi new file mode 100644 index 000000000000..cf0251567288 --- /dev/null +++ b/stubs/boltons/boltons/iterutils.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable +from typing import TypeVar +from typing_extensions import TypeIs + +_T = TypeVar("_T") + +def is_iterable(obj: Iterable[_T] | object) -> TypeIs[Iterable[_T]]: ... +def is_scalar(obj: object) -> bool: ... +def is_collection(obj: object) -> bool: ... +def split(src, sep=None, maxsplit=None): ... +def split_iter(src, sep=None, maxsplit=None) -> Generator[list[Incomplete]]: ... +def lstrip(iterable, strip_value=None): ... +def lstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... +def rstrip(iterable, strip_value=None): ... +def rstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... +def strip(iterable, strip_value=None): ... +def strip_iter(iterable, strip_value=None): ... +def chunked(src, size, count=None, **kw): ... +def chunked_iter(src, size, **kw) -> Generator[str | bytes]: ... +def chunk_ranges( + input_size: int, chunk_size: int, input_offset: int = 0, overlap_size: int = 0, align: bool = False +) -> Generator[tuple[int, int]]: ... +def pairwise(src, end=...): ... +def pairwise_iter(src, end=...): ... +def windowed(src, size, fill=...): ... +def windowed_iter(src, size, fill=...): ... +def xfrange(stop, start=None, step: float = 1.0) -> Generator[Incomplete]: ... +def frange(stop, start=None, step: float = 1.0): ... +def backoff(start, stop, count=None, factor: float = 2.0, jitter: bool = False): ... +def backoff_iter(start, stop, count=None, factor: float = 2.0, jitter: bool = False) -> Generator[Incomplete]: ... +def bucketize(src, key=..., value_transform=None, key_filter=None): ... +def partition(src, key=..., *keys: str | Callable[..., Incomplete]) -> tuple[list[Incomplete], ...]: ... +def unique(src, key=None): ... +def unique_iter(src, key=None) -> Generator[Incomplete]: ... +def redundant(src, key=None, groups: bool = False): ... +def one(src, default=None, key=None): ... +def first(iterable, default=None, key=None): ... +def flatten_iter(iterable) -> Generator[Incomplete]: ... +def flatten(iterable): ... +def same(iterable, ref=...): ... +def default_visit(path, key, value): ... +def default_enter(path, key, value): ... +def default_exit(path, key, old_parent, new_parent, new_items): ... +def remap(root, visit=..., enter=..., exit=..., cache: bool = True, **kwargs): ... + +class PathAccessError(KeyError, IndexError, TypeError): + exc: Incomplete + seg: Incomplete + path: Incomplete + def __init__(self, exc, seg, path) -> None: ... + +def get_path(root, path, default=...): ... +def research(root, query=..., reraise: bool = False, enter=...): ... + +class GUIDerator: + size: Incomplete + count: Incomplete + def __init__(self, size: int = 24) -> None: ... + pid: Incomplete + salt: Incomplete + def reseed(self) -> None: ... + def __iter__(self): ... + def __next__(self): ... + next: Incomplete + +class SequentialGUIDerator(GUIDerator): + start: Incomplete + def reseed(self) -> None: ... + def __next__(self): ... + next: Incomplete + +guid_iter: Incomplete +seq_guid_iter: Incomplete + +def soft_sorted(iterable, first=None, last=None, key=None, reverse: bool = False): ... +def untyped_sorted(iterable, key=None, reverse: bool = False): ... diff --git a/stubs/boltons/boltons/jsonutils.pyi b/stubs/boltons/boltons/jsonutils.pyi new file mode 100644 index 000000000000..276db26ef881 --- /dev/null +++ b/stubs/boltons/boltons/jsonutils.pyi @@ -0,0 +1,25 @@ +from collections.abc import Generator +from typing import IO, Any, overload +from typing_extensions import Self + +@overload +def reverse_iter_lines( + file_obj: IO[bytes], blocksize: int = 4096, preseek: bool = True, encoding: None = None +) -> Generator[bytes]: ... +@overload +def reverse_iter_lines(file_obj: IO[str], blocksize: int = 4096, preseek: bool = True, *, encoding: str) -> Generator[str]: ... +@overload +def reverse_iter_lines(file_obj: IO[str], blocksize: int, preseek: bool, encoding: str) -> Generator[str]: ... + +class JSONLIterator: + ignore_errors: bool + def __init__( + self, file_obj: IO[str], ignore_errors: bool = False, reverse: bool = False, rel_seek: float | None = None + ) -> None: ... + @property + def cur_byte_pos(self) -> int: ... + def __iter__(self) -> Self: ... + def next(self) -> Any: ... + __next__ = next + +__all__ = ["JSONLIterator", "reverse_iter_lines"] diff --git a/stubs/boltons/boltons/listutils.pyi b/stubs/boltons/boltons/listutils.pyi new file mode 100644 index 000000000000..33be50272087 --- /dev/null +++ b/stubs/boltons/boltons/listutils.pyi @@ -0,0 +1,32 @@ +from collections.abc import Iterable +from typing import SupportsIndex, TypeAlias, TypeVar +from typing_extensions import Self + +_T = TypeVar("_T") + +class BarrelList(list[_T]): + lists: list[list[_T]] + def __init__(self, iterable: Iterable[_T] | None = None) -> None: ... + def insert(self, index: SupportsIndex, item: _T) -> None: ... + def append(self, item: _T) -> None: ... + def extend(self, iterable: Iterable[_T]) -> None: ... + def pop(self, *a) -> _T: ... + def iter_slice(self, start: int | None, stop: int | None, step: int | None = None) -> Iterable[_T]: ... + def del_slice(self, start: int, stop: int, step: int | None = None) -> None: ... + __delslice__ = del_slice + @classmethod + def from_iterable(cls, it: Iterable[_T]) -> Self: ... + def __getslice__(self, start: int, stop: int): ... + def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, sequence: Iterable[_T]) -> None: ... + def sort(self) -> None: ... # type: ignore[override] + def reverse(self) -> None: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T) -> int: ... # type: ignore[override] + +BList: TypeAlias = BarrelList[_T] + +class SplayList(list[_T]): + def shift(self, item_index: int, dest_index: int = 0) -> None: ... + def swap(self, item_index: SupportsIndex, dest_index: SupportsIndex) -> None: ... + +__all__ = ["BList", "BarrelList"] diff --git a/stubs/boltons/boltons/mathutils.pyi b/stubs/boltons/boltons/mathutils.pyi new file mode 100644 index 000000000000..42920bcf99a4 --- /dev/null +++ b/stubs/boltons/boltons/mathutils.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable +from typing import overload + +def clamp(x: float, lower: float = ..., upper: float = ...) -> float: ... + +@overload +def ceil(x: float, options: None = None) -> int: ... +@overload +def ceil(x: float, options: Iterable[float]) -> float: ... + +@overload +def floor(x: float, options: None = None) -> int: ... +@overload +def floor(x: float, options: Iterable[float]) -> float: ... + +class Bits: + __slots__ = ("val", "len") + val: int + len: int + def __init__(self, val: int | list[bool] | str | bytes = 0, len_: int | None = None) -> None: ... + def __getitem__(self, k) -> Bits | bool: ... + def __len__(self) -> int: ... + def __eq__(self, other) -> bool: ... + def __or__(self, other: Bits) -> Bits: ... + def __and__(self, other: Bits) -> Bits: ... + def __lshift__(self, other: int) -> Bits: ... + def __rshift__(self, other: int) -> Bits: ... + def __hash__(self) -> int: ... + def as_list(self) -> list[bool]: ... + def as_bin(self) -> str: ... + def as_hex(self) -> str: ... + def as_int(self) -> int: ... + def as_bytes(self) -> bytes: ... + @classmethod + def from_list(cls, list_): ... + @classmethod + def from_bin(cls, bin): ... + @classmethod + def from_hex(cls, hex): ... + @classmethod + def from_int(cls, int_, len_: int | None = None): ... + @classmethod + def from_bytes(cls, bytes_): ... diff --git a/stubs/boltons/boltons/mboxutils.pyi b/stubs/boltons/boltons/mboxutils.pyi new file mode 100644 index 000000000000..5d1019c9be16 --- /dev/null +++ b/stubs/boltons/boltons/mboxutils.pyi @@ -0,0 +1,17 @@ +import mailbox +from _typeshed import StrPath +from collections.abc import Callable +from typing import IO, Any + +DEFAULT_MAXMEM: int + +class mbox_readonlydir(mailbox.mbox): + maxmem: int + def __init__( + self, + path: StrPath, + factory: Callable[[IO[Any]], mailbox.mboxMessage] | None = None, + create: bool = True, + maxmem: int = 1048576, + ) -> None: ... + def flush(self) -> None: ... diff --git a/stubs/boltons/boltons/namedutils.pyi b/stubs/boltons/boltons/namedutils.pyi new file mode 100644 index 000000000000..ff57445a5998 --- /dev/null +++ b/stubs/boltons/boltons/namedutils.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterable + +def namedtuple(typename: str, field_names: str | Iterable[str], verbose: bool = False, rename: bool = False): ... +def namedlist(typename: str, field_names: str | Iterable[str], verbose: bool = False, rename: bool = False): ... + +__all__ = ["namedlist", "namedtuple"] diff --git a/stubs/boltons/boltons/pathutils.pyi b/stubs/boltons/boltons/pathutils.pyi new file mode 100644 index 000000000000..60566fa0f302 --- /dev/null +++ b/stubs/boltons/boltons/pathutils.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrPath + +def augpath( + path: StrPath, + suffix: str = "", + prefix: str = "", + ext: str | None = None, + base: str | None = None, + dpath: str | None = None, + multidot: bool = False, +) -> str: ... +def shrinkuser(path: StrPath, home: str = "~") -> str: ... +def expandpath(path: StrPath) -> str: ... + +__all__ = ["augpath", "shrinkuser", "expandpath"] diff --git a/stubs/boltons/boltons/queueutils.pyi b/stubs/boltons/boltons/queueutils.pyi new file mode 100644 index 000000000000..83c6dd01e8a5 --- /dev/null +++ b/stubs/boltons/boltons/queueutils.pyi @@ -0,0 +1,16 @@ +from typing import TypeAlias + +class BasePriorityQueue: + def __init__(self, **kw) -> None: ... + def add(self, task, priority: int | None = None) -> None: ... + def remove(self, task) -> None: ... + def peek(self, default=...): ... + def pop(self, default=...): ... + def __len__(self) -> int: ... + +class HeapPriorityQueue(BasePriorityQueue): ... +class SortedPriorityQueue(BasePriorityQueue): ... + +PriorityQueue: TypeAlias = SortedPriorityQueue + +__all__ = ["PriorityQueue", "BasePriorityQueue", "HeapPriorityQueue", "SortedPriorityQueue"] diff --git a/stubs/boltons/boltons/setutils.pyi b/stubs/boltons/boltons/setutils.pyi new file mode 100644 index 000000000000..d94de1967fc0 --- /dev/null +++ b/stubs/boltons/boltons/setutils.pyi @@ -0,0 +1,105 @@ +from collections.abc import Collection, Container, Generator, Iterable, Iterator, MutableSet +from itertools import islice +from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only +from typing_extensions import Self + +_T_co = TypeVar("_T_co", covariant=True) + +@type_check_only +class _RSub(Iterable[_T_co], Protocol): + def __new__(cls: type[_RSub[_T_co]], param: list[_T_co], /) -> _RSub[_T_co]: ... + +class IndexedSet(MutableSet[Any]): + item_index_map: dict[Any, Any] + item_list: list[Any] + dead_indices: list[int] + def __init__(self, other: Iterable[Any] | None = None) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, item: Any) -> bool: ... + def __iter__(self) -> Iterator[Any]: ... + def __reversed__(self) -> Generator[Any]: ... + @classmethod + def from_iterable(cls, it: Iterable[Any]) -> Self: ... + def add(self, item: Any) -> None: ... + def remove(self, item: Any) -> None: ... + def discard(self, item: Any) -> None: ... + def clear(self) -> None: ... + def isdisjoint(self, other: Iterable[Any]) -> bool: ... + def issubset(self, other: Collection[Any]) -> bool: ... + def issuperset(self, other: Collection[Any]) -> bool: ... + def union(self, *others: Iterable[Any]) -> Self: ... + def iter_intersection(self, *others: Container[Any]) -> Generator[Any]: ... + def intersection(self, *others: Container[Any]) -> Self: ... + def iter_difference(self, *others: Iterable[Any]) -> Generator[Any]: ... + def difference(self, *others: Iterable[Any]) -> Self: ... + def symmetric_difference(self, *others: Container[Any]) -> Self: ... + # __or__ = union + __ror__ = union + # __and__ = intersection + __rand__ = intersection + # __sub__ = difference + # __xor__ = symmetric_difference + __rxor__ = symmetric_difference + def __rsub__(self, other: _RSub[_T_co]) -> _RSub[_T_co]: ... + def update(self, *others: Iterable[Any]) -> None: ... + def intersection_update(self, *others: Iterable[Any]) -> None: ... + def difference_update(self, *others: Container[Any]) -> None: ... + def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... + def iter_slice(self, start: int, stop: int, step: int | None = None) -> islice[Iterable[Any]]: ... + + @overload + def __getitem__(self, index: slice) -> Self: ... + @overload + def __getitem__(self, index: SupportsIndex) -> Any: ... + + def pop(self, index: int | None = None) -> Any: ... + def count(self, val: Any) -> Literal[0, 1]: ... + def reverse(self) -> None: ... + def sort(self, **kwargs) -> None: ... + def index(self, val: Any) -> int: ... + +def complement(wrapped: Iterable[Any]) -> _ComplementSet: ... + +class _ComplementSet: + __slots__ = ("_included", "_excluded") + def __init__( + self, included: set[Any] | frozenset[Any] | None = None, excluded: set[Any] | frozenset[Any] | None = None + ) -> None: ... + def complemented(self) -> _ComplementSet: ... + __invert__ = complemented + def complement(self) -> None: ... + def __contains__(self, item: Any) -> bool: ... + def add(self, item: Any) -> None: ... + def remove(self, item: Any) -> None: ... + def pop(self) -> Any: ... + def intersection(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __and__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __rand__ = __and__ + def __iand__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def union(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __or__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __ror__ = __or__ + def __ior__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def update(self, items: Iterable[Any]) -> None: ... + def discard(self, items: Iterable[Any]) -> None: ... + def symmetric_difference(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __xor__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + __rxor__ = __xor__ + def symmetric_difference_update(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> None: ... + def isdisjoint(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def issubset(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __le__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __lt__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def issuperset(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __ge__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def __gt__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> bool: ... + def difference(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __sub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def __rsub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> _ComplementSet: ... + def difference_update(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> None: ... + def __isub__(self, other: set[Any] | frozenset[Any] | _ComplementSet) -> Self: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[Any]: ... + def __bool__(self) -> bool: ... + +__all__ = ["IndexedSet", "complement"] diff --git a/stubs/boltons/boltons/socketutils.pyi b/stubs/boltons/boltons/socketutils.pyi new file mode 100644 index 000000000000..30b438e689c3 --- /dev/null +++ b/stubs/boltons/boltons/socketutils.pyi @@ -0,0 +1,72 @@ +import socket +from _typeshed import ReadableBuffer, SliceableBuffer + +DEFAULT_TIMEOUT: int +DEFAULT_MAXSIZE: int + +class BufferedSocket: + sock: socket.socket + rbuf: bytes + sbuf: list[SliceableBuffer] + maxsize: int + timeout: int + def __init__(self, sock: socket.socket, timeout: int = ..., maxsize: int = 32768, recvsize: int = ...) -> None: ... + def settimeout(self, timeout: float) -> None: ... + def gettimeout(self) -> float: ... + def setblocking(self, blocking: bool) -> None: ... + def setmaxsize(self, maxsize) -> None: ... + def getrecvbuffer(self) -> bytes: ... + def getsendbuffer(self) -> bytes: ... + def recv(self, size: int, flags: int = 0, timeout: float = ...) -> bytes: ... + def peek(self, size: int, timeout: float = ...) -> bytes: ... + def recv_close(self, timeout: float = ..., maxsize: int = ...) -> bytes: ... + def recv_until( + self, delimiter: ReadableBuffer, timeout: float = ..., maxsize: int = ..., with_delimiter: bool = False + ) -> bytes: ... + def recv_size(self, size: int, timeout: float = ...) -> bytes: ... + def send(self, data: SliceableBuffer, flags: int = 0, timeout: float = ...) -> str: ... + def sendall(self, data: SliceableBuffer, flags: int = 0, timeout: float = ...) -> str: ... + def flush(self) -> None: ... + def buffer(self, data: SliceableBuffer) -> None: ... + def getsockname(self) -> str: ... + def getpeername(self) -> str: ... + def getsockopt(self, level: int, optname: int, buflen: int | None = None) -> bytes | int: ... + def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer | None) -> bytes | int: ... + @property + def type(self) -> int: ... + @property + def family(self) -> int: ... + @property + def proto(self) -> int: ... + def fileno(self) -> int: ... + rbuf_unconsumed: bytes + def close(self) -> None: ... + def shutdown(self, how: int) -> None: ... + +class Error(socket.error): ... +class ConnectionClosed(Error): ... + +class MessageTooLong(Error): + def __init__(self, bytes_read: int | None = None, delimiter: str | None = None) -> None: ... + +class Timeout(socket.timeout, Error): + def __init__(self, timeout: float, extra: str = "") -> None: ... + +class NetstringSocket: + bsock: BufferedSocket + timeout: float + maxsize: int + def __init__(self, sock: socket.socket, timeout: float = 10, maxsize: int = 32768) -> None: ... + def fileno(self) -> int: ... + def settimeout(self, timeout: float) -> None: ... + def setmaxsize(self, maxsize: int) -> None: ... + def read_ns(self, timeout: float = ..., maxsize: int = ...): ... + def write_ns(self, payload: bytes) -> None: ... + +class NetstringProtocolError(Error): ... + +class NetstringInvalidSize(NetstringProtocolError): + def __init__(self, msg: str) -> None: ... + +class NetstringMessageTooLong(NetstringProtocolError): + def __init__(self, size: int, maxsize: int) -> None: ... diff --git a/stubs/boltons/boltons/statsutils.pyi b/stubs/boltons/boltons/statsutils.pyi new file mode 100644 index 000000000000..4165b8a16373 --- /dev/null +++ b/stubs/boltons/boltons/statsutils.pyi @@ -0,0 +1,76 @@ +from _typeshed import ConvertibleToFloat, Incomplete +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Literal, overload +from typing_extensions import Self + +class _StatsProperty: + name: str + func: Callable[..., Any] + internal_name: str + __doc__: str | None + def __init__(self, name: str, func: Callable[..., Any]) -> None: ... + + @overload + def __get__(self, obj: None, objtype: object = None) -> Self: ... + @overload + def __get__(self, obj: Stats, objtype: object = None) -> float: ... + +class Stats: + data: list[float] + default: float + + @overload + def __init__(self, data: list[float], default: float = 0.0, *, use_copy: Literal[False], is_sorted: bool = False) -> None: ... + @overload + def __init__(self, data: list[float], default: float, use_copy: Literal[False], is_sorted: bool = False) -> None: ... + @overload + def __init__( + self, data: Iterable[float], default: float = 0.0, use_copy: Literal[True] = True, is_sorted: bool = False + ) -> None: ... + + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[float]: ... + def clear_cache(self) -> None: ... + count: _StatsProperty + mean: _StatsProperty + max: _StatsProperty + min: _StatsProperty + median: _StatsProperty + iqr: _StatsProperty + trimean: _StatsProperty + variance: _StatsProperty + std_dev: _StatsProperty + median_abs_dev: _StatsProperty + mad: _StatsProperty + rel_std_dev: _StatsProperty + skewness: _StatsProperty + kurtosis: _StatsProperty + pearson_type: _StatsProperty + def get_quantile(self, q: ConvertibleToFloat) -> float: ... + def get_zscore(self, value: float) -> float: ... + def trim_relative(self, amount: float = 0.15) -> None: ... + def get_histogram_counts(self, bins: int | list[float] | None = None, **kw) -> list[tuple[float, int]]: ... + def format_histogram(self, bins: int | list[float] | None = None, **kw) -> str: ... + def describe( + self, quantiles: Iterable[float] | None = None, format: str | None = None + ) -> dict[str, float] | list[tuple[str, float]] | str: ... + +def describe( + data: Iterable[float], quantiles: Iterable[float] | None = None, format: str | None = None +) -> dict[str, float] | list[tuple[str, float]] | str: ... + +mean: Incomplete +median: Incomplete +iqr: Incomplete +trimean: Incomplete +variance: Incomplete +std_dev: Incomplete +median_abs_dev: Incomplete +rel_std_dev: Incomplete +skewness: Incomplete +kurtosis: Incomplete +pearson_type: Incomplete + +def format_histogram_counts( + bin_counts: list[float], width: int | None = None, format_bin: Callable[..., Any] | None = None +) -> str: ... diff --git a/stubs/boltons/boltons/strutils.pyi b/stubs/boltons/boltons/strutils.pyi new file mode 100644 index 000000000000..2eae46714980 --- /dev/null +++ b/stubs/boltons/boltons/strutils.pyi @@ -0,0 +1,103 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable, Generator, Iterable, Sequence, Sized +from html.parser import HTMLParser +from re import Pattern +from typing import Literal, overload + +def camel2under(camel_string: str) -> str: ... +def under2camel(under_string: str) -> str: ... + +@overload +def slugify(text: str, delim: str = "_", lower: bool = True, *, ascii: Literal[True]) -> bytes: ... +@overload +def slugify(text: str, delim: str, lower: bool, ascii: Literal[True]) -> bytes: ... +@overload +def slugify(text: str, delim: str = "_", lower: bool = True, ascii: Literal[False] = False) -> str: ... + +def split_punct_ws(text: str) -> list[str]: ... +def unit_len(sized_iterable: Sized, unit_noun: str = "item") -> str: ... +def ordinalize(number: int | str, ext_only: bool = False) -> str: ... +def cardinalize(unit_noun: str, count: int) -> str: ... +def singularize(word: str) -> str: ... +def pluralize(word: str) -> str: ... +def find_hashtags(string: str) -> list[str]: ... +def a10n(string: str) -> str: ... +def strip_ansi(text: str) -> str: ... +def asciify(text: str | bytes | bytearray, ignore: bool = False) -> bytes: ... +def is_ascii(text: str) -> bool: ... + +class DeaccenterDict(dict[int, int]): + def __missing__(self, key: int) -> int: ... + +def bytes2human(nbytes: int, ndigits: int = 0) -> str: ... + +class HTMLTextExtractor(HTMLParser): + result: list[str] + def __init__(self) -> None: ... + def handle_data(self, d: str) -> None: ... + def handle_charref(self, number: str) -> None: ... + def handle_entityref(self, name: str) -> None: ... + def get_text(self) -> str: ... + +def html2text(html: str) -> str: ... +def gunzip_bytes(bytestring: ReadableBuffer) -> bytes: ... +def gzip_bytes(bytestring: ReadableBuffer, level: int = 6) -> int: ... +def iter_splitlines(text: str) -> Generator[str]: ... +def indent(text: str, margin: str, newline: str = "\n", key: Callable[[str], bool] = ...) -> str: ... +def is_uuid(obj, version: int = 4) -> bool: ... +def escape_shell_args(args: Iterable[str], sep: str = " ", style: Literal["cmd", "sh"] | None = None) -> str: ... +def args2sh(args: Iterable[str], sep: str = " ") -> str: ... +def args2cmd(args: Iterable[str], sep: str = " ") -> str: ... +def parse_int_list(range_string: str, delim: str = ",", range_delim: str = "-") -> list[int]: ... +def format_int_list(int_list: list[int], delim: str = ",", range_delim: str = "-", delim_space: bool = False) -> str: ... +def complement_int_list( + range_string: str, range_start: int = 0, range_end: int | None = None, delim: str = ",", range_delim: str = "-" +) -> str: ... +def int_ranges_from_int_list(range_string: str, delim: str = ",", range_delim: str = "-") -> tuple[tuple[int, int], ...]: ... + +class MultiReplace: + group_map: dict[str, str] + combined_pattern: Pattern[str] + def __init__(self, sub_map: dict[str, str], **kwargs) -> None: ... + def sub(self, text: str) -> str: ... + +def multi_replace(text: str, sub_map: dict[str, str], **kwargs) -> str: ... +def unwrap_text(text: str, ending: str | None = "\n\n") -> str: ... +def removeprefix(text: str, prefix: str) -> str: ... +def human_readable_list(items: Sequence[str], delimiter: str = ",", conjunction: str = "and", *, oxford: bool = True) -> str: ... + +__all__ = [ + "camel2under", + "under2camel", + "slugify", + "split_punct_ws", + "unit_len", + "ordinalize", + "cardinalize", + "pluralize", + "singularize", + "asciify", + "is_ascii", + "is_uuid", + "html2text", + "strip_ansi", + "bytes2human", + "find_hashtags", + "a10n", + "gzip_bytes", + "gunzip_bytes", + "iter_splitlines", + "indent", + "escape_shell_args", + "args2cmd", + "args2sh", + "parse_int_list", + "format_int_list", + "complement_int_list", + "int_ranges_from_int_list", + "MultiReplace", + "multi_replace", + "unwrap_text", + "removeprefix", + "human_readable_list", +] diff --git a/stubs/boltons/boltons/tableutils.pyi b/stubs/boltons/boltons/tableutils.pyi new file mode 100644 index 000000000000..19c2ee650767 --- /dev/null +++ b/stubs/boltons/boltons/tableutils.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete + +class UnsupportedData(TypeError): ... + +class InputType: + def __init__(self, *a, **kw) -> None: ... + def get_entry_seq(self, data_seq, headers): ... + +class DictInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj, headers): ... + +class ObjectInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + +class ListInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj) -> None: ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class TupleInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj) -> None: ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class NamedTupleInputType(InputType): + def check_type(self, obj): ... + def guess_headers(self, obj): ... + def get_entry(self, obj, headers): ... + def get_entry_seq(self, obj_seq, headers): ... + +class Table: + headers: Incomplete + metadata: Incomplete + def __init__(self, data=None, headers=..., metadata=None) -> None: ... + def extend(self, data) -> None: ... + @classmethod + def from_dict(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_list(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_object(cls, data, headers=..., max_depth: int = 1, metadata=None): ... + @classmethod + def from_data(cls, data, headers=..., max_depth: int = 1, **kwargs): ... + def __len__(self): ... + def __getitem__(self, idx): ... + def to_html( + self, + orientation=None, + wrapped: bool = True, + with_headers: bool = True, + with_newlines: bool = True, + with_metadata: bool = False, + max_depth: int = 1, + ): ... + def get_cell_html(self, value): ... + def to_text(self, with_headers: bool = True, maxlen=None): ... + +__all__ = ["Table"] diff --git a/stubs/boltons/boltons/tbutils.pyi b/stubs/boltons/boltons/tbutils.pyi new file mode 100644 index 000000000000..1d4648d6f129 --- /dev/null +++ b/stubs/boltons/boltons/tbutils.pyi @@ -0,0 +1,107 @@ +from collections.abc import Iterable, Iterator, Mapping +from types import FrameType, TracebackType +from typing import Any, Generic, Literal, TypeVar +from typing_extensions import Self + +class Callpoint: + __slots__ = ("func_name", "lineno", "module_name", "module_path", "lasti", "line") + func_name: str + lineno: int + module_name: str + module_path: str + lasti: int + line: str + def __init__( + self, module_name: str, module_path: str, func_name: str, lineno: int, lasti: int, line: str | None = None + ) -> None: ... + def to_dict(self) -> dict[str, Any]: ... + @classmethod + def from_current(cls, level: int = 1) -> Self: ... + @classmethod + def from_frame(cls, frame: FrameType) -> Self: ... + @classmethod + def from_tb(cls, tb: TracebackType) -> Self: ... + def tb_frame_str(self) -> str: ... + +_CallpointT_co = TypeVar("_CallpointT_co", bound=Callpoint, covariant=True, default=Callpoint) + +class TracebackInfo(Generic[_CallpointT_co]): + callpoint_type: type[_CallpointT_co] + frames: list[_CallpointT_co] + def __init__(self, frames: list[_CallpointT_co]) -> None: ... + @classmethod + def from_frame(cls, frame: FrameType | None = None, level: int = 1, limit: int | None = None) -> Self: ... + @classmethod + def from_traceback(cls, tb: TracebackType | None = None, limit: int | None = None) -> Self: ... + @classmethod + def from_dict(cls, d: Mapping[Literal["frames"], list[_CallpointT_co]]) -> Self: ... + def to_dict(self) -> dict[str, list[dict[str, _CallpointT_co]]]: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_CallpointT_co]: ... + def get_formatted(self) -> str: ... + +_TracebackInfoT_co = TypeVar("_TracebackInfoT_co", bound=TracebackInfo, covariant=True, default=TracebackInfo) + +class ExceptionInfo(Generic[_TracebackInfoT_co]): + tb_info_type: type[_TracebackInfoT_co] + exc_type: str + exc_msg: str + tb_info: _TracebackInfoT_co + def __init__(self, exc_type: str, exc_msg: str, tb_info: _TracebackInfoT_co) -> None: ... + @classmethod + def from_exc_info(cls, exc_type: type[BaseException], exc_value: BaseException, traceback: TracebackType) -> Self: ... + @classmethod + def from_current(cls) -> Self: ... + def to_dict(self) -> dict[str, str | dict[str, list[FrameType]]]: ... + def get_formatted(self) -> str: ... + def get_formatted_exception_only(self) -> str: ... + +class ContextualCallpoint(Callpoint): + local_reprs: dict[Any, Any] + pre_lines: list[str] + post_lines: list[str] + def __init__(self, *a, **kw) -> None: ... + @classmethod + def from_frame(cls, frame: FrameType) -> Self: ... + @classmethod + def from_tb(cls, tb: TracebackType) -> Self: ... + def to_dict(self) -> dict[str, Any]: ... + +class ContextualTracebackInfo(TracebackInfo[ContextualCallpoint]): + callpoint_type: type[ContextualCallpoint] + +class ContextualExceptionInfo(ExceptionInfo[ContextualTracebackInfo]): + tb_info_type: type[ContextualTracebackInfo] + +def print_exception( + etype: type[BaseException] | None, + value: BaseException | None, + tb: TracebackType | None, + limit: int | None = None, + file: str | None = None, +) -> None: ... + +class ParsedException: + exc_type: str + exc_msg: str + frames: list[FrameType] + def __init__(self, exc_type_name: str, exc_msg: str, frames: Iterable[Mapping[str, Any]] | None = None) -> None: ... + @property + def source_file(self) -> str | None: ... + def to_dict(self) -> dict[str, str | list[FrameType]]: ... + def to_string(self) -> str: ... + @classmethod + def from_string(cls, tb_str: str) -> Self: ... + +ParsedTB = ParsedException + +__all__ = [ + "ExceptionInfo", + "TracebackInfo", + "Callpoint", + "ContextualExceptionInfo", + "ContextualTracebackInfo", + "ContextualCallpoint", + "print_exception", + "ParsedException", +] diff --git a/stubs/boltons/boltons/timeutils.pyi b/stubs/boltons/boltons/timeutils.pyi new file mode 100644 index 000000000000..7416be362361 --- /dev/null +++ b/stubs/boltons/boltons/timeutils.pyi @@ -0,0 +1,62 @@ +from collections.abc import Generator +from datetime import date, datetime, timedelta, tzinfo + +total_seconds = timedelta.total_seconds + +def dt_to_timestamp(dt: datetime) -> int: ... +def isoparse(iso_str: str) -> datetime: ... +def parse_timedelta(text: str) -> timedelta: ... + +parse_td = parse_timedelta + +def decimal_relative_time( + d: datetime, other: datetime | None = None, ndigits: int = 0, cardinalize: bool = True +) -> tuple[float, str]: ... +def relative_time(d: datetime, other: datetime | None = None, ndigits: int = 0) -> str: ... +def strpdate(string: str, format: str) -> date: ... +def daterange(start: date, stop: date, step: int = 1, inclusive: bool = False) -> Generator[date]: ... + +ZERO: timedelta +HOUR: timedelta + +class ConstantTZInfo(tzinfo): + name: str + offset: timedelta + def __init__(self, name: str = "ConstantTZ", offset: timedelta = ...) -> None: ... + @property + def utcoffset_hours(self) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def tzname(self, dt: datetime | None) -> str: ... + def dst(self, dt: datetime | None) -> timedelta: ... + +UTC: ConstantTZInfo +EPOCH_AWARE: datetime + +class LocalTZInfo(tzinfo): + def is_dst(self, dt: datetime) -> bool: ... + def utcoffset(self, dt: datetime) -> timedelta: ... # type: ignore[override] # Doesn't support None + def dst(self, dt: datetime) -> timedelta: ... # type: ignore[override] # Doesn't support None + def tzname(self, dt: datetime) -> str: ... # type: ignore[override] # Doesn't support None + +LocalTZ: LocalTZInfo +DSTSTART_2007: datetime +DSTEND_2007: datetime +DSTSTART_1987_2006: datetime +DSTEND_1987_2006: datetime +DSTSTART_1967_1986: datetime +DSTEND_1967_1986: datetime + +class USTimeZone(tzinfo): + stdoffset: timedelta + reprname: str + stdname: str + dstname: str + def __init__(self, hours: int, reprname: str, stdname: str, dstname: str) -> None: ... + def tzname(self, dt: datetime | None) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def dst(self, dt: datetime | None) -> timedelta: ... + +Eastern: USTimeZone +Central: USTimeZone +Mountain: USTimeZone +Pacific: USTimeZone diff --git a/stubs/boltons/boltons/typeutils.pyi b/stubs/boltons/boltons/typeutils.pyi new file mode 100644 index 000000000000..c2ae45147c94 --- /dev/null +++ b/stubs/boltons/boltons/typeutils.pyi @@ -0,0 +1,17 @@ +from typing import Any, Literal, Protocol, type_check_only +from typing_extensions import Self + +@type_check_only +class _Sentinel(Protocol): + def __bool__(self) -> Literal[False]: ... + def __copy__(self) -> Self: ... + def __deepcopy__(self, _memo) -> Self: ... + +def make_sentinel(name: str = "_MISSING", var_name: str | None = None) -> _Sentinel: ... +def issubclass(subclass: type, baseclass: type) -> bool: ... +def get_all_subclasses(cls: type) -> list[type]: ... + +class classproperty: + fn: Any + def __init__(self, fn) -> None: ... + def __get__(self, instance, cls): ... diff --git a/stubs/boltons/boltons/urlutils.pyi b/stubs/boltons/boltons/urlutils.pyi new file mode 100644 index 000000000000..869001e1504a --- /dev/null +++ b/stubs/boltons/boltons/urlutils.pyi @@ -0,0 +1,82 @@ +from _typeshed import Incomplete + +from boltons.dictutils import OrderedMultiDict + +SCHEME_PORT_MAP: Incomplete +NO_NETLOC_SCHEMES: Incomplete + +class URLParseError(ValueError): ... + +DEFAULT_ENCODING: str + +def to_unicode(obj: object) -> str: ... +def find_all_links(text, with_text: bool = False, default_scheme: str = "https", schemes=()): ... +def quote_path_part(text, full_quote: bool = True): ... +def quote_query_part(text, full_quote: bool = True): ... +def quote_fragment_part(text, full_quote: bool = True): ... +def quote_userinfo_part(text, full_quote: bool = True): ... +def unquote(string, encoding: str = "utf-8", errors: str = "replace"): ... +def unquote_to_bytes(string): ... +def register_scheme(text, uses_netloc=None, default_port=None) -> None: ... +def resolve_path_parts(path_parts): ... + +class cachedproperty: + __doc__: Incomplete + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, objtype=None): ... + +class URL: + scheme: Incomplete + username: Incomplete + password: Incomplete + family: Incomplete + host: Incomplete + port: Incomplete + path_parts: Incomplete + fragment: Incomplete + def __init__(self, url: str = "") -> None: ... + @classmethod + def from_parts( + cls, scheme=None, host=None, path_parts=(), query_params=(), fragment: str = "", port=None, username=None, password=None + ): ... + query_params: Incomplete + qp: Incomplete + + @property + def path(self): ... + @path.setter + def path(self, path_text) -> None: ... + + @property + def uses_netloc(self): ... + @property + def default_port(self): ... + def normalize(self, with_case: bool = True) -> None: ... + def navigate(self, dest): ... + def get_authority(self, full_quote: bool = False, with_userinfo: bool = False): ... + def to_text(self, full_quote: bool = False): ... + def __unicode__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + +def parse_host(host): ... +def parse_url(url_text): ... + +DEFAULT_PARSED_URL: Incomplete + +def parse_qsl(qs, keep_blank_values: bool = True, encoding="utf8"): ... + +PREV: Incomplete +NEXT: Incomplete +KEY: Incomplete +VALUE: Incomplete +SPREV: Incomplete +SNEXT: Incomplete + +OMD = OrderedMultiDict + +class QueryParamDict(OrderedMultiDict[Incomplete, Incomplete]): + @classmethod + def from_text(cls, query_string): ... + def to_text(self, full_quote: bool = False): ... diff --git a/stubs/braintree/@tests/stubtest_allowlist.txt b/stubs/braintree/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f40932c48318 --- /dev/null +++ b/stubs/braintree/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +.*\.AttributeGetter.__repr__ # has an extra argument, but also a million things inherit from it diff --git a/stubs/braintree/METADATA.toml b/stubs/braintree/METADATA.toml new file mode 100644 index 000000000000..ff317f5b020a --- /dev/null +++ b/stubs/braintree/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.45.*" +upstream-repository = "https://github.com/braintree/braintree_python" diff --git a/stubs/braintree/braintree/__init__.pyi b/stubs/braintree/braintree/__init__.pyi new file mode 100644 index 000000000000..be8a05595d49 --- /dev/null +++ b/stubs/braintree/braintree/__init__.pyi @@ -0,0 +1,111 @@ +from braintree.ach_mandate import AchMandate as AchMandate +from braintree.add_on import AddOn as AddOn +from braintree.add_on_gateway import AddOnGateway as AddOnGateway +from braintree.address import Address as Address +from braintree.address_gateway import AddressGateway as AddressGateway +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard as AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard as AndroidPayCard +from braintree.apple_pay_card import ApplePayCard as ApplePayCard +from braintree.apple_pay_gateway import ApplePayGateway as ApplePayGateway +from braintree.bank_account_instant_verification_gateway import ( + BankAccountInstantVerificationGateway as BankAccountInstantVerificationGateway, +) +from braintree.bank_account_instant_verification_jwt import BankAccountInstantVerificationJwt as BankAccountInstantVerificationJwt +from braintree.bank_account_instant_verification_jwt_request import ( + BankAccountInstantVerificationJwtRequest as BankAccountInstantVerificationJwtRequest, +) +from braintree.blik_alias import BlikAlias as BlikAlias +from braintree.braintree_gateway import BraintreeGateway as BraintreeGateway +from braintree.client_token import ClientToken as ClientToken +from braintree.configuration import Configuration as Configuration +from braintree.connected_merchant_paypal_status_changed import ( + ConnectedMerchantPayPalStatusChanged as ConnectedMerchantPayPalStatusChanged, +) +from braintree.connected_merchant_status_transitioned import ( + ConnectedMerchantStatusTransitioned as ConnectedMerchantStatusTransitioned, +) +from braintree.credentials_parser import CredentialsParser as CredentialsParser +from braintree.credit_card import CreditCard as CreditCard +from braintree.credit_card_gateway import CreditCardGateway as CreditCardGateway +from braintree.credit_card_verification import CreditCardVerification as CreditCardVerification +from braintree.credit_card_verification_search import CreditCardVerificationSearch as CreditCardVerificationSearch +from braintree.customer import Customer as Customer +from braintree.customer_gateway import CustomerGateway as CustomerGateway +from braintree.customer_search import CustomerSearch as CustomerSearch +from braintree.descriptor import Descriptor as Descriptor +from braintree.disbursement import Disbursement as Disbursement +from braintree.discount import Discount as Discount +from braintree.discount_gateway import DiscountGateway as DiscountGateway +from braintree.dispute import Dispute as Dispute +from braintree.dispute_search import DisputeSearch as DisputeSearch +from braintree.document_upload import DocumentUpload as DocumentUpload +from braintree.document_upload_gateway import DocumentUploadGateway as DocumentUploadGateway +from braintree.enriched_customer_data import EnrichedCustomerData as EnrichedCustomerData +from braintree.environment import Environment as Environment +from braintree.error_codes import ErrorCodes as ErrorCodes +from braintree.error_result import ErrorResult as ErrorResult +from braintree.errors import Errors as Errors +from braintree.europe_bank_account import EuropeBankAccount as EuropeBankAccount +from braintree.graphql import * +from braintree.liability_shift import LiabilityShift as LiabilityShift +from braintree.local_payment_completed import LocalPaymentCompleted as LocalPaymentCompleted +from braintree.local_payment_context import LocalPaymentContext as LocalPaymentContext +from braintree.local_payment_context_gateway import LocalPaymentContextGateway as LocalPaymentContextGateway +from braintree.local_payment_reversed import LocalPaymentReversed as LocalPaymentReversed +from braintree.local_payment_type import LocalPaymentType as LocalPaymentType +from braintree.merchant import Merchant as Merchant +from braintree.merchant_account import MerchantAccount as MerchantAccount +from braintree.merchant_account_gateway import MerchantAccountGateway as MerchantAccountGateway +from braintree.monetary_amount import MonetaryAmount as MonetaryAmount +from braintree.oauth_access_revocation import OAuthAccessRevocation as OAuthAccessRevocation +from braintree.partner_merchant import PartnerMerchant as PartnerMerchant +from braintree.payment_facilitator import PaymentFacilitator as PaymentFacilitator +from braintree.payment_instrument_type import PaymentInstrumentType as PaymentInstrumentType +from braintree.payment_method import PaymentMethod as PaymentMethod +from braintree.payment_method_customer_data_updated_metadata import ( + PaymentMethodCustomerDataUpdatedMetadata as PaymentMethodCustomerDataUpdatedMetadata, +) +from braintree.payment_method_nonce import PaymentMethodNonce as PaymentMethodNonce +from braintree.payment_method_parser import parse_payment_method as parse_payment_method +from braintree.paypal_account import PayPalAccount as PayPalAccount +from braintree.paypal_payment_resource import PayPalPaymentResource as PayPalPaymentResource +from braintree.plan import Plan as Plan +from braintree.plan_gateway import PlanGateway as PlanGateway +from braintree.processor_response_types import ProcessorResponseTypes as ProcessorResponseTypes +from braintree.receiver import Receiver as Receiver +from braintree.resource_collection import ResourceCollection as ResourceCollection +from braintree.risk_data import RiskData as RiskData +from braintree.samsung_pay_card import SamsungPayCard as SamsungPayCard +from braintree.search import Search as Search +from braintree.sender import Sender as Sender +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount as SepaDirectDebitAccount +from braintree.settlement_batch_summary import SettlementBatchSummary as SettlementBatchSummary +from braintree.signature_service import SignatureService as SignatureService +from braintree.status_event import StatusEvent as StatusEvent +from braintree.sub_merchant import SubMerchant as SubMerchant +from braintree.subscription import Subscription as Subscription +from braintree.subscription_gateway import SubscriptionGateway as SubscriptionGateway +from braintree.subscription_search import SubscriptionSearch as SubscriptionSearch +from braintree.subscription_status_event import SubscriptionStatusEvent as SubscriptionStatusEvent +from braintree.successful_result import SuccessfulResult as SuccessfulResult +from braintree.testing_gateway import TestingGateway as TestingGateway +from braintree.three_d_secure_info import ThreeDSecureInfo as ThreeDSecureInfo +from braintree.transaction import Transaction as Transaction +from braintree.transaction_amounts import TransactionAmounts as TransactionAmounts +from braintree.transaction_details import TransactionDetails as TransactionDetails +from braintree.transaction_gateway import TransactionGateway as TransactionGateway +from braintree.transaction_line_item import TransactionLineItem as TransactionLineItem +from braintree.transaction_search import TransactionSearch as TransactionSearch +from braintree.transaction_us_bank_account_request import TransactionUsBankAccountRequest as TransactionUsBankAccountRequest +from braintree.transfer import Transfer as Transfer +from braintree.unknown_payment_method import UnknownPaymentMethod as UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount as UsBankAccount +from braintree.us_bank_account_verification import UsBankAccountVerification as UsBankAccountVerification +from braintree.validation_error_collection import ValidationErrorCollection as ValidationErrorCollection +from braintree.venmo_account import VenmoAccount as VenmoAccount +from braintree.venmo_profile_data import VenmoProfileData as VenmoProfileData +from braintree.version import Version as Version +from braintree.webhook_notification import WebhookNotification as WebhookNotification +from braintree.webhook_notification_gateway import WebhookNotificationGateway as WebhookNotificationGateway +from braintree.webhook_testing import WebhookTesting as WebhookTesting +from braintree.webhook_testing_gateway import WebhookTestingGateway as WebhookTestingGateway diff --git a/stubs/braintree/braintree/account_updater_daily_report.pyi b/stubs/braintree/braintree/account_updater_daily_report.pyi new file mode 100644 index 000000000000..a2c67165b72a --- /dev/null +++ b/stubs/braintree/braintree/account_updater_daily_report.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class AccountUpdaterDailyReport(Resource): + report_url: Incomplete + report_date: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/ach_mandate.pyi b/stubs/braintree/braintree/ach_mandate.pyi new file mode 100644 index 000000000000..a09111a4d3e8 --- /dev/null +++ b/stubs/braintree/braintree/ach_mandate.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class AchMandate(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/add_on.pyi b/stubs/braintree/braintree/add_on.pyi new file mode 100644 index 000000000000..76f5079c16ac --- /dev/null +++ b/stubs/braintree/braintree/add_on.pyi @@ -0,0 +1,5 @@ +from braintree.modification import Modification + +class AddOn(Modification): + @staticmethod + def all() -> list[AddOn]: ... diff --git a/stubs/braintree/braintree/add_on_gateway.pyi b/stubs/braintree/braintree/add_on_gateway.pyi new file mode 100644 index 000000000000..95bd15bd8c46 --- /dev/null +++ b/stubs/braintree/braintree/add_on_gateway.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.add_on import AddOn + +class AddOnGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def all(self) -> list[AddOn]: ... diff --git a/stubs/braintree/braintree/address.pyi b/stubs/braintree/braintree/address.pyi new file mode 100644 index 000000000000..eaf4ec201650 --- /dev/null +++ b/stubs/braintree/braintree/address.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult + +class Address(Resource): + class ShippingMethod: + SameDay: Final = "same_day" + NextDay: Final = "next_day" + Priority: Final = "priority" + Ground: Final = "ground" + Electronic: Final = "electronic" + ShipToStore: Final = "ship_to_store" + PickupInStore: Final = "pickup_in_store" + + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def delete(customer_id: str, address_id: str) -> SuccessfulResult: ... + @staticmethod + def find(customer_id: str, address_id: str) -> Address: ... + @staticmethod + def update( + customer_id: str, address_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def create_signature() -> list[str | dict[str, list[str]]]: ... + @staticmethod + def update_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/address_gateway.pyi b/stubs/braintree/braintree/address_gateway.pyi new file mode 100644 index 000000000000..0ecadbe8c924 --- /dev/null +++ b/stubs/braintree/braintree/address_gateway.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from braintree.address import Address +from braintree.braintree_gateway import BraintreeGateway +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class AddressGateway: + gateway: BraintreeGateway + config: Incomplete + def __init__(self, gateway: BraintreeGateway) -> None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, customer_id: str, address_id: str) -> SuccessfulResult: ... + def find(self, customer_id: str, address_id: str) -> Address: ... + def update( + self, customer_id: str, address_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/amex_express_checkout_card.pyi b/stubs/braintree/braintree/amex_express_checkout_card.pyi new file mode 100644 index 000000000000..ad0e994fc436 --- /dev/null +++ b/stubs/braintree/braintree/amex_express_checkout_card.pyi @@ -0,0 +1,8 @@ +from braintree.resource import Resource +from braintree.subscription import Subscription + +class AmexExpressCheckoutCard(Resource): + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self): ... diff --git a/stubs/braintree/braintree/android_pay_card.pyi b/stubs/braintree/braintree/android_pay_card.pyi new file mode 100644 index 000000000000..41e05930a283 --- /dev/null +++ b/stubs/braintree/braintree/android_pay_card.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource +from braintree.subscription import Subscription + +class AndroidPayCard(Resource): + is_expired: Incomplete + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self): ... + @property + def last_4(self): ... + @property + def card_type(self): ... + @staticmethod + def signature() -> list[str | dict[str, list[str]]]: ... + @staticmethod + def card_signature() -> list[str | dict[str, list[str]]]: ... + @staticmethod + def network_token_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/apple_pay_card.pyi b/stubs/braintree/braintree/apple_pay_card.pyi new file mode 100644 index 000000000000..0b0e488ac808 --- /dev/null +++ b/stubs/braintree/braintree/apple_pay_card.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.credit_card_verification import CreditCardVerification +from braintree.resource import Resource +from braintree.subscription import Subscription + +class ApplePayCard(Resource): + class CardType: + AmEx: Final = "Apple Pay - American Express" + MasterCard: Final = "Apple Pay - MasterCard" + Visa: Final = "Apple Pay - Visa" + + is_expired: Incomplete + subscriptions: list[Subscription] + verification: CreditCardVerification | None + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self): ... + @staticmethod + def signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/apple_pay_gateway.pyi b/stubs/braintree/braintree/apple_pay_gateway.pyi new file mode 100644 index 000000000000..55477a1eb30b --- /dev/null +++ b/stubs/braintree/braintree/apple_pay_gateway.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class ApplePayGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def register_domain(self, domain: str) -> SuccessfulResult | ErrorResult | None: ... + def unregister_domain(self, domain: str) -> SuccessfulResult: ... + def registered_domains(self): ... diff --git a/stubs/braintree/braintree/apple_pay_options.pyi b/stubs/braintree/braintree/apple_pay_options.pyi new file mode 100644 index 000000000000..c7a6bc4413ef --- /dev/null +++ b/stubs/braintree/braintree/apple_pay_options.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class ApplePayOptions(AttributeGetter): ... diff --git a/stubs/braintree/braintree/attribute_getter.pyi b/stubs/braintree/braintree/attribute_getter.pyi new file mode 100644 index 000000000000..b38cb2a4816a --- /dev/null +++ b/stubs/braintree/braintree/attribute_getter.pyi @@ -0,0 +1,7 @@ +from typing import Any + +class AttributeGetter: + def __init__(self, attributes: dict[str, Any] | None = None) -> None: ... + # This doesn't exist at runtime, but subclasses should define their own fields populated by attributes in __init__ + # Until that's done, keep __getattribute__ to fill in the gaps + def __getattribute__(self, name: str, /) -> Any: ... diff --git a/stubs/braintree/braintree/authorization_adjustment.pyi b/stubs/braintree/braintree/authorization_adjustment.pyi new file mode 100644 index 000000000000..38f1bb810190 --- /dev/null +++ b/stubs/braintree/braintree/authorization_adjustment.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.attribute_getter import AttributeGetter + +class AuthorizationAdjustment(AttributeGetter): + amount: Decimal | None + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi b/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi new file mode 100644 index 000000000000..989bc822c03a --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class BankAccountInstantVerificationGateway: + gateway: Incomplete + config: Incomplete + graphql_client: Incomplete + CREATE_JWT_MUTATION: Final[str] + def __init__(self, gateway) -> None: ... + def create_jwt(self, request) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi b/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi new file mode 100644 index 000000000000..3874739b8bff --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_jwt.pyi @@ -0,0 +1,9 @@ +from braintree.attribute_getter import AttributeGetter + +class BankAccountInstantVerificationJwt(AttributeGetter): + def __init__(self, jwt) -> None: ... + + @property + def jwt(self): ... + @jwt.setter + def jwt(self, value) -> None: ... diff --git a/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi b/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi new file mode 100644 index 000000000000..43ae31462e5a --- /dev/null +++ b/stubs/braintree/braintree/bank_account_instant_verification_jwt_request.pyi @@ -0,0 +1,18 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _ParamsDict(TypedDict, total=False): + businessName: str + returnUrl: str + cancelUrl: str + +class BankAccountInstantVerificationJwtRequest: + def __init__(self) -> None: ... + def business_name(self, business_name: str) -> Self: ... + def return_url(self, return_url: str) -> Self: ... + def cancel_url(self, cancel_url: str) -> Self: ... + def get_business_name(self) -> str: ... + def get_return_url(self) -> str: ... + def get_cancel_url(self) -> str: ... + def to_graphql_variables(self) -> _ParamsDict: ... diff --git a/stubs/braintree/braintree/bin_data.pyi b/stubs/braintree/braintree/bin_data.pyi new file mode 100644 index 000000000000..4660a1ec6022 --- /dev/null +++ b/stubs/braintree/braintree/bin_data.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class BinData(AttributeGetter): ... diff --git a/stubs/braintree/braintree/blik_alias.pyi b/stubs/braintree/braintree/blik_alias.pyi new file mode 100644 index 000000000000..7b96548a71cc --- /dev/null +++ b/stubs/braintree/braintree/blik_alias.pyi @@ -0,0 +1,3 @@ +from braintree.resource import Resource + +class BlikAlias(Resource): ... diff --git a/stubs/braintree/braintree/braintree_gateway.pyi b/stubs/braintree/braintree/braintree_gateway.pyi new file mode 100644 index 000000000000..28a53728c47c --- /dev/null +++ b/stubs/braintree/braintree/braintree_gateway.pyi @@ -0,0 +1,70 @@ +from braintree.add_on_gateway import AddOnGateway +from braintree.address_gateway import AddressGateway +from braintree.apple_pay_gateway import ApplePayGateway +from braintree.bank_account_instant_verification_gateway import BankAccountInstantVerificationGateway +from braintree.client_token_gateway import ClientTokenGateway +from braintree.configuration import Configuration +from braintree.credit_card_gateway import CreditCardGateway +from braintree.credit_card_verification_gateway import CreditCardVerificationGateway +from braintree.customer_gateway import CustomerGateway +from braintree.discount_gateway import DiscountGateway +from braintree.dispute_gateway import DisputeGateway +from braintree.document_upload_gateway import DocumentUploadGateway +from braintree.exchange_rate_quote_gateway import ExchangeRateQuoteGateway +from braintree.local_payment_context_gateway import LocalPaymentContextGateway as LocalPaymentContextGateway +from braintree.merchant_account_gateway import MerchantAccountGateway +from braintree.merchant_gateway import MerchantGateway +from braintree.oauth_gateway import OAuthGateway +from braintree.payment_method_gateway import PaymentMethodGateway +from braintree.payment_method_nonce_gateway import PaymentMethodNonceGateway +from braintree.paypal_account_gateway import PayPalAccountGateway +from braintree.paypal_payment_resource_gateway import PayPalPaymentResourceGateway +from braintree.plan_gateway import PlanGateway +from braintree.sepa_direct_debit_account_gateway import SepaDirectDebitAccountGateway +from braintree.settlement_batch_summary_gateway import SettlementBatchSummaryGateway +from braintree.subscription_gateway import SubscriptionGateway +from braintree.testing_gateway import TestingGateway +from braintree.transaction_gateway import TransactionGateway +from braintree.transaction_line_item_gateway import TransactionLineItemGateway +from braintree.us_bank_account_gateway import UsBankAccountGateway +from braintree.us_bank_account_verification_gateway import UsBankAccountVerificationGateway +from braintree.util.graphql_client import GraphQLClient +from braintree.webhook_notification_gateway import WebhookNotificationGateway +from braintree.webhook_testing_gateway import WebhookTestingGateway + +class BraintreeGateway: + config: Configuration + add_on: AddOnGateway + address: AddressGateway + apple_pay: ApplePayGateway + bank_account_instant_verification: BankAccountInstantVerificationGateway + client_token: ClientTokenGateway + credit_card: CreditCardGateway + customer: CustomerGateway + discount: DiscountGateway + dispute: DisputeGateway + document_upload: DocumentUploadGateway + exchange_rate_quote: ExchangeRateQuoteGateway + local_payment_context: LocalPaymentContextGateway + graphql_client: GraphQLClient + merchant: MerchantGateway + merchant_account: MerchantAccountGateway + oauth: OAuthGateway + payment_method: PaymentMethodGateway + payment_method_nonce: PaymentMethodNonceGateway + paypal_account: PayPalAccountGateway + paypal_payment_resource: PayPalPaymentResourceGateway + plan: PlanGateway + sepa_direct_debit_account: SepaDirectDebitAccountGateway + settlement_batch_summary: SettlementBatchSummaryGateway + subscription: SubscriptionGateway + testing: TestingGateway + transaction: TransactionGateway + transaction_line_item: TransactionLineItemGateway + us_bank_account: UsBankAccountGateway + us_bank_account_verification: UsBankAccountVerificationGateway + verification: CreditCardVerificationGateway + webhook_notification: WebhookNotificationGateway + webhook_testing: WebhookTestingGateway + def __init__(self, config=None, **kwargs) -> None: ... + def close(self) -> None: ... diff --git a/stubs/braintree/braintree/client_token.pyi b/stubs/braintree/braintree/client_token.pyi new file mode 100644 index 000000000000..4855a008da44 --- /dev/null +++ b/stubs/braintree/braintree/client_token.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.braintree_gateway import BraintreeGateway + +class ClientToken: + @staticmethod + def generate(params: dict[str, Incomplete] | None = None, gateway: BraintreeGateway | None = None) -> str: ... + @staticmethod + def generate_signature() -> list[str | dict[str, list[str]]]: ... diff --git a/stubs/braintree/braintree/client_token_gateway.pyi b/stubs/braintree/braintree/client_token_gateway.pyi new file mode 100644 index 000000000000..b07681cee224 --- /dev/null +++ b/stubs/braintree/braintree/client_token_gateway.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.braintree_gateway import BraintreeGateway + +class ClientTokenGateway: + gateway: BraintreeGateway + config: Incomplete + def __init__(self, gateway: BraintreeGateway) -> None: ... + def generate(self, params: dict[str, Incomplete] | None = None) -> str: ... diff --git a/stubs/braintree/braintree/configuration.pyi b/stubs/braintree/braintree/configuration.pyi new file mode 100644 index 000000000000..25385ba8b292 --- /dev/null +++ b/stubs/braintree/braintree/configuration.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete + +from braintree.braintree_gateway import BraintreeGateway +from braintree.util.graphql_client import GraphQLClient +from braintree.util.http import Http + +class Configuration: + @staticmethod + def configure( + environment, + merchant_id: str, + public_key: str, + private_key: str, + *, + http_strategy=None, + timeout: int = 60, + wrap_http_exceptions: bool = False, + ) -> None: ... + @staticmethod + def for_partner( + environment, + partner_id: str, + public_key: str, + private_key: str, + *, + http_strategy=None, + timeout: int = 60, + wrap_http_exceptions: bool = False, + ) -> Configuration: ... + @staticmethod + def gateway() -> BraintreeGateway: ... + @staticmethod + def instantiate() -> Configuration: ... + @staticmethod + def api_version() -> str: ... + @staticmethod + def graphql_api_version() -> str: ... + environment: Incomplete + merchant_id: str | None + public_key: str | None + private_key: str | None + client_id: str | None + client_secret: str | None + access_token: str | None + timeout: int + wrap_http_exceptions: bool + def __init__( + self, + environment=None, + merchant_id: str | None = None, + public_key: str | None = None, + private_key: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + access_token: str | None = None, + *args, + timeout: int = 60, + wrap_http_exceptions: bool = False, + http_strategy=None, + ) -> None: ... + def base_merchant_path(self) -> str: ... + def base_url(self) -> str: ... + def graphql_base_url(self) -> str: ... + def http(self) -> Http: ... + def graphql_client(self) -> GraphQLClient: ... + def http_strategy(self): ... + def close(self) -> None: ... + def has_client_credentials(self) -> bool: ... + def assert_has_client_credentials(self) -> None: ... + def has_access_token(self) -> bool: ... diff --git a/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi b/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi new file mode 100644 index 000000000000..27b48b650328 --- /dev/null +++ b/stubs/braintree/braintree/connected_merchant_paypal_status_changed.pyi @@ -0,0 +1,6 @@ +from braintree.resource import Resource + +class ConnectedMerchantPayPalStatusChanged(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def merchant_id(self): ... diff --git a/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi b/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi new file mode 100644 index 000000000000..c840ac668b6b --- /dev/null +++ b/stubs/braintree/braintree/connected_merchant_status_transitioned.pyi @@ -0,0 +1,6 @@ +from braintree.resource import Resource + +class ConnectedMerchantStatusTransitioned(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def merchant_id(self): ... diff --git a/stubs/braintree/braintree/credentials_parser.pyi b/stubs/braintree/braintree/credentials_parser.pyi new file mode 100644 index 000000000000..bc24ea29893f --- /dev/null +++ b/stubs/braintree/braintree/credentials_parser.pyi @@ -0,0 +1,15 @@ +from braintree.environment import Environment + +class CredentialsParser: + client_id: str | None + client_secret: str | None + access_token: str | None + environment: Environment | None + merchant_id: str + def __init__( + self, client_id: str | None = None, client_secret: str | None = None, access_token: str | None = None + ) -> None: ... + def parse_client_credentials(self) -> None: ... + def parse_access_token(self) -> None: ... + def get_environment(self, credential: str) -> Environment | None: ... + def get_merchant_id(self, credential: str) -> str: ... diff --git a/stubs/braintree/braintree/credit_card.pyi b/stubs/braintree/braintree/credit_card.pyi new file mode 100644 index 000000000000..dd4a30c370e6 --- /dev/null +++ b/stubs/braintree/braintree/credit_card.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete +from datetime import date, datetime +from enum import Enum +from typing import Final, Literal + +from braintree.address import Address +from braintree.credit_card_verification import CreditCardVerification +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult + +class CreditCard(Resource): + class CardType: + AmEx: Final = "American Express" + CarteBlanche: Final = "Carte Blanche" + ChinaUnionPay: Final = "China UnionPay" + DinersClubInternational: Final = "Diners Club" + Discover: Final = "Discover" + Electron: Final = "Electron" + Elo: Final = "Elo" + Hiper: Final = "Hiper" + Hipercard: Final = "Hipercard" + JCB: Final = "JCB" + Laser: Final = "Laser" + UK_Maestro: Final = "UK Maestro" + Maestro: Final = "Maestro" + MasterCard: Final = "MasterCard" + Solo: Final = "Solo" + Switch: Final = "Switch" + Visa: Final = "Visa" + Unknown: Final = "Unknown" + + class CustomerLocation: + International: Final = "international" + US: Final = "us" + + class CardTypeIndicator: + Yes: Final = "Yes" + No: Final = "No" + Unknown: Final = "Unknown" + + class DebitNetwork(Enum): + Accel = "ACCEL" + Maestro = "MAESTRO" + Nyce = "NYCE" + Pulse = "PULSE" + Star = "STAR" + Star_Access = "STAR_ACCESS" + + Commercial: type[CardTypeIndicator] + DurbinRegulated: type[CardTypeIndicator] + Debit: type[CardTypeIndicator] + Healthcare: type[CardTypeIndicator] + CountryOfIssuance: type[CardTypeIndicator] + IssuingBank: type[CardTypeIndicator] + Payroll: type[CardTypeIndicator] + Prepaid: type[CardTypeIndicator] + ProductId: type[CardTypeIndicator] + PrepaidReloadable: type[CardTypeIndicator] + Business: type[CardTypeIndicator] + Consumer: type[CardTypeIndicator] + Corporate: type[CardTypeIndicator] + Purchase: type[CardTypeIndicator] + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def update(credit_card_token: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def delete(credit_card_token: str) -> SuccessfulResult: ... + @staticmethod + def expired() -> ResourceCollection: ... + @staticmethod + def expiring_between(start_date: date | datetime, end_date: date | datetime) -> ResourceCollection: ... + @staticmethod + def find(credit_card_token: str) -> CreditCard: ... + @staticmethod + def from_nonce(nonce: str) -> CreditCard: ... + @staticmethod + def create_signature() -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... + @staticmethod + def update_signature() -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... + @staticmethod + def signature( + type: Literal["create", "update", "update_via_customer"], + ) -> list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]: ... + is_expired = expired + billing_address: Address | None + subscriptions: list[Subscription] + verification: CreditCardVerification + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str | None: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/credit_card_gateway.pyi b/stubs/braintree/braintree/credit_card_gateway.pyi new file mode 100644 index 000000000000..2661ad018aea --- /dev/null +++ b/stubs/braintree/braintree/credit_card_gateway.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete, Unused +from datetime import date, datetime +from typing_extensions import Never + +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult + +class CreditCardGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, credit_card_token: str) -> SuccessfulResult: ... + def expired(self) -> ResourceCollection: ... + def expiring_between(self, start_date: date | datetime, end_date: date | datetime) -> ResourceCollection: ... + def find(self, credit_card_token: str) -> CreditCard: ... + def forward(self, credit_card_token: Unused, receiving_merchant_id: Unused) -> Never: ... + def from_nonce(self, nonce: str) -> CreditCard: ... + def update( + self, credit_card_token: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/credit_card_verification.pyi b/stubs/braintree/braintree/credit_card_verification.pyi new file mode 100644 index 000000000000..b131e293dd9f --- /dev/null +++ b/stubs/braintree/braintree/credit_card_verification.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from decimal import Decimal +from typing import Final + +from braintree.attribute_getter import AttributeGetter +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.risk_data import RiskData +from braintree.successful_result import SuccessfulResult +from braintree.three_d_secure_info import ThreeDSecureInfo + +class CreditCardVerification(AttributeGetter): + class Status: + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Verified: Final = "verified" + + amount: Decimal | None + currency_iso_code: Incomplete + mastercard_transaction_link_id: str | None + processor_response_code: Incomplete + processor_response_text: Incomplete + network_response_code: Incomplete + network_response_text: Incomplete + risk_data: RiskData | None + three_d_secure_info: ThreeDSecureInfo | None + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def find(verification_id: str) -> CreditCardVerification: ... + @staticmethod + def search(*query) -> ResourceCollection: ... + @staticmethod + def create(params) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def create_signature() -> list[dict[str, list[str | dict[str, list[str]]]] | dict[str, list[str]] | str]: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/braintree/braintree/credit_card_verification_gateway.pyi b/stubs/braintree/braintree/credit_card_verification_gateway.pyi new file mode 100644 index 000000000000..fa108beb5f2d --- /dev/null +++ b/stubs/braintree/braintree/credit_card_verification_gateway.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from braintree.credit_card_verification import CreditCardVerification +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult + +class CreditCardVerificationGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, verification_id: str) -> CreditCardVerification: ... + def search(self, *query) -> ResourceCollection: ... + def create(self, params: dict[str, Incomplete] | None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/credit_card_verification_search.pyi b/stubs/braintree/braintree/credit_card_verification_search.pyi new file mode 100644 index 000000000000..8e5444923484 --- /dev/null +++ b/stubs/braintree/braintree/credit_card_verification_search.pyi @@ -0,0 +1,15 @@ +from braintree.search import Search + +class CreditCardVerificationSearch: + credit_card_cardholder_name: Search.TextNodeBuilder + id: Search.TextNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.PartialMatchNodeBuilder + credit_card_card_type: Search.MultipleValueNodeBuilder + ids: Search.MultipleValueNodeBuilder + created_at: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + billing_postal_code: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/customer.pyi b/stubs/braintree/braintree/customer.pyi new file mode 100644 index 000000000000..22f5532ae8fb --- /dev/null +++ b/stubs/braintree/braintree/customer.pyi @@ -0,0 +1,66 @@ +from _typeshed import Incomplete + +from braintree.address import Address +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.samsung_pay_card import SamsungPayCard +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard + +class Customer(Resource): + @staticmethod + def all() -> ResourceCollection: ... + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def delete(customer_id: str) -> SuccessfulResult: ... + @staticmethod + def find(customer_id: str, association_filter_id: str | None = None) -> Customer: ... + @staticmethod + def search(*query) -> ResourceCollection: ... + @staticmethod + def update(customer_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def create_signature() -> ( + list[ + str + | dict[str, list[str]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]] + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + ] + ): ... + @staticmethod + def update_signature() -> ( + list[ + str + | dict[str, list[str]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str]]]]]] + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + ] + ): ... + payment_methods: list[Resource] + credit_cards: list[CreditCard] + addresses: list[Address] + paypal_accounts: list[PayPalAccount] + apple_pay_cards: list[ApplePayCard] + android_pay_cards: list[AndroidPayCard] + amex_express_checkout_cards: list[AmexExpressCheckoutCard] + europe_bank_accounts: list[EuropeBankAccount] + venmo_accounts: list[VenmoAccount] + us_bank_accounts: list[UsBankAccount] + visa_checkout_cards: list[VisaCheckoutCard] + masterpass_cards: list[MasterpassCard] + samsung_pay_cards: list[SamsungPayCard] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/customer_gateway.pyi b/stubs/braintree/braintree/customer_gateway.pyi new file mode 100644 index 000000000000..18558178134c --- /dev/null +++ b/stubs/braintree/braintree/customer_gateway.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from braintree.customer import Customer +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult + +class CustomerGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def all(self) -> ResourceCollection: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def delete(self, customer_id: str) -> SuccessfulResult: ... + def find(self, customer_id: str, association_filter_id: str | None = None) -> Customer: ... + def search(self, *query) -> ResourceCollection: ... + def update(self, customer_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/customer_search.pyi b/stubs/braintree/braintree/customer_search.pyi new file mode 100644 index 000000000000..57b7004602c6 --- /dev/null +++ b/stubs/braintree/braintree/customer_search.pyi @@ -0,0 +1,27 @@ +from braintree.search import Search + +class CustomerSearch: + address_extended_address: Search.TextNodeBuilder + address_first_name: Search.TextNodeBuilder + address_last_name: Search.TextNodeBuilder + address_locality: Search.TextNodeBuilder + address_postal_code: Search.TextNodeBuilder + address_region: Search.TextNodeBuilder + address_street_address: Search.TextNodeBuilder + address_country_name: Search.TextNodeBuilder + cardholder_name: Search.TextNodeBuilder + company: Search.TextNodeBuilder + created_at: Search.RangeNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.TextNodeBuilder + email: Search.TextNodeBuilder + fax: Search.TextNodeBuilder + first_name: Search.TextNodeBuilder + id: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + last_name: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + payment_method_token_with_duplicates: Search.IsNodeBuilder + phone: Search.TextNodeBuilder + website: Search.TextNodeBuilder + paypal_account_email: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/customer_session_gateway.pyi b/stubs/braintree/braintree/customer_session_gateway.pyi new file mode 100644 index 000000000000..dbcf24f78de3 --- /dev/null +++ b/stubs/braintree/braintree/customer_session_gateway.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.graphql import CreateCustomerSessionInput, CustomerRecommendationsInput, UpdateCustomerSessionInput +from braintree.successful_result import SuccessfulResult + +class CustomerSessionGateway: + gateway: Incomplete + graphql_client: Incomplete + def __init__(self, gateway) -> None: ... + def create_customer_session(self, customer_session_input: CreateCustomerSessionInput) -> SuccessfulResult | ErrorResult: ... + def update_customer_session( + self, update_customer_session_input: UpdateCustomerSessionInput + ) -> SuccessfulResult | ErrorResult: ... + def get_customer_recommendations( + self, get_customer_recommendations_input: CustomerRecommendationsInput + ) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/descriptor.pyi b/stubs/braintree/braintree/descriptor.pyi new file mode 100644 index 000000000000..bc2526c430f1 --- /dev/null +++ b/stubs/braintree/braintree/descriptor.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class Descriptor(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/disbursement.pyi b/stubs/braintree/braintree/disbursement.pyi new file mode 100644 index 000000000000..f406b972cb12 --- /dev/null +++ b/stubs/braintree/braintree/disbursement.pyi @@ -0,0 +1,17 @@ +from decimal import Decimal +from typing import Final + +from braintree.merchant_account import MerchantAccount +from braintree.resource import Resource + +class Disbursement(Resource): + class Type: + Credit: Final = "credit" + Debit: Final = "debit" + + amount: Decimal + merchant_account: MerchantAccount + def __init__(self, gateway, attributes) -> None: ... + def transactions(self): ... + def is_credit(self) -> bool: ... + def is_debit(self) -> bool: ... diff --git a/stubs/braintree/braintree/disbursement_detail.pyi b/stubs/braintree/braintree/disbursement_detail.pyi new file mode 100644 index 000000000000..8de304b964fb --- /dev/null +++ b/stubs/braintree/braintree/disbursement_detail.pyi @@ -0,0 +1,10 @@ +from decimal import Decimal + +from braintree.attribute_getter import AttributeGetter + +class DisbursementDetail(AttributeGetter): + settlement_amount: Decimal | None + settlement_currency_exchange_rate: Decimal | None + def __init__(self, attributes) -> None: ... + @property + def is_valid(self) -> bool: ... diff --git a/stubs/braintree/braintree/discount.pyi b/stubs/braintree/braintree/discount.pyi new file mode 100644 index 000000000000..0078843f6265 --- /dev/null +++ b/stubs/braintree/braintree/discount.pyi @@ -0,0 +1,5 @@ +from braintree.modification import Modification + +class Discount(Modification): + @staticmethod + def all() -> list[Discount]: ... diff --git a/stubs/braintree/braintree/discount_gateway.pyi b/stubs/braintree/braintree/discount_gateway.pyi new file mode 100644 index 000000000000..df1da780a7c2 --- /dev/null +++ b/stubs/braintree/braintree/discount_gateway.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.discount import Discount + +class DiscountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def all(self) -> list[Discount]: ... diff --git a/stubs/braintree/braintree/dispute.pyi b/stubs/braintree/braintree/dispute.pyi new file mode 100644 index 000000000000..338e7101a613 --- /dev/null +++ b/stubs/braintree/braintree/dispute.pyi @@ -0,0 +1,79 @@ +from _typeshed import Incomplete +from decimal import Decimal +from typing import Final + +from braintree.attribute_getter import AttributeGetter +from braintree.dispute_details import DisputeEvidence, DisputePayPalMessage, DisputeStatusHistory +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult +from braintree.transaction_details import TransactionDetails + +class Dispute(AttributeGetter): + class Status: + Accepted: Final = "accepted" + AutoAccepted: Final = "auto_accepted" + Disputed: Final = "disputed" + Expired: Final = "expired" + Lost: Final = "lost" + Open: Final = "open" + UnderReview: Final = "under_review" + Won: Final = "won" + + class Reason: + CancelledRecurringTransaction: Final = "cancelled_recurring_transaction" + CreditNotProcessed: Final = "credit_not_processed" + Duplicate: Final = "duplicate" + Fraud: Final = "fraud" + General: Final = "general" + InvalidAccount: Final = "invalid_account" + NotRecognized: Final = "not_recognized" + ProductNotReceived: Final = "product_not_received" + ProductUnsatisfactory: Final = "product_unsatisfactory" + Retrieval: Final = "retrieval" + TransactionAmountDiffers: Final = "transaction_amount_differs" + + class Kind: + Chargeback: Final = "chargeback" + PreArbitration: Final = "pre_arbitration" + Retrieval: Final = "retrieval" + + class ChargebackProtectionLevel: + Effortless: Final = "effortless" + Standard: Final = "standard" + NotProtected: Final = "not_protected" + + class PreDisputeProgram: + NONE: Final = "none" + VisaRdr: Final = "visa_rdr" + + class ProtectionLevel: + EffortlessCBP: Final = "Effortless Chargeback Protection tool" + StandardCBP: Final = "Chargeback Protection tool" + NoProtection: Final = "No Protection" + + @staticmethod + def accept(id: str) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def add_file_evidence(dispute_id: str, document_upload_id) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def add_text_evidence(id: str, content_or_request) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def finalize(id: str) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def find(id: str) -> Dispute: ... + @staticmethod + def remove_evidence(id: str, evidence_id: str) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def search(*query) -> SuccessfulResult: ... + amount: Decimal | None + amount_disputed: Decimal | None + amount_won: Decimal | None + protection_level: Incomplete + transaction_details: TransactionDetails + transaction = transaction_details # pyrefly: ignore [unknown-name] + evidence: list[DisputeEvidence] | None + paypal_messages: list[DisputePayPalMessage] | None + status_history: list[DisputeStatusHistory] | None + processor_comments: Incomplete + forwarded_comments: processor_comments # pyrefly: ignore [unknown-name] + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/__init__.pyi b/stubs/braintree/braintree/dispute_details/__init__.pyi new file mode 100644 index 000000000000..e03bf6a1ae79 --- /dev/null +++ b/stubs/braintree/braintree/dispute_details/__init__.pyi @@ -0,0 +1,3 @@ +from braintree.dispute_details.evidence import DisputeEvidence as DisputeEvidence +from braintree.dispute_details.paypal_message import DisputePayPalMessage as DisputePayPalMessage +from braintree.dispute_details.status_history import DisputeStatusHistory as DisputeStatusHistory diff --git a/stubs/braintree/braintree/dispute_details/evidence.pyi b/stubs/braintree/braintree/dispute_details/evidence.pyi new file mode 100644 index 000000000000..a7dd9100d4d1 --- /dev/null +++ b/stubs/braintree/braintree/dispute_details/evidence.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class DisputeEvidence(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/paypal_message.pyi b/stubs/braintree/braintree/dispute_details/paypal_message.pyi new file mode 100644 index 000000000000..7d5d8a2441e5 --- /dev/null +++ b/stubs/braintree/braintree/dispute_details/paypal_message.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class DisputePayPalMessage(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_details/status_history.pyi b/stubs/braintree/braintree/dispute_details/status_history.pyi new file mode 100644 index 000000000000..dd7466ace617 --- /dev/null +++ b/stubs/braintree/braintree/dispute_details/status_history.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class DisputeStatusHistory(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/dispute_gateway.pyi b/stubs/braintree/braintree/dispute_gateway.pyi new file mode 100644 index 000000000000..4c0a5d66481f --- /dev/null +++ b/stubs/braintree/braintree/dispute_gateway.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from braintree.dispute import Dispute +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class DisputeGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def accept(self, dispute_id: str) -> SuccessfulResult | ErrorResult: ... + def add_file_evidence(self, dispute_id: str, document_upload_id_or_request) -> SuccessfulResult | ErrorResult | None: ... + def add_text_evidence(self, dispute_id: str, content_or_request) -> SuccessfulResult | ErrorResult | None: ... + def finalize(self, dispute_id: str) -> SuccessfulResult | ErrorResult: ... + def find(self, dispute_id: str) -> Dispute: ... + def remove_evidence(self, dispute_id: str, evidence_id: int) -> SuccessfulResult | ErrorResult: ... + search_criteria: dict[Incomplete, Incomplete] + def search(self, *query) -> SuccessfulResult: ... diff --git a/stubs/braintree/braintree/dispute_search.pyi b/stubs/braintree/braintree/dispute_search.pyi new file mode 100644 index 000000000000..50bfce33a60f --- /dev/null +++ b/stubs/braintree/braintree/dispute_search.pyi @@ -0,0 +1,23 @@ +from braintree.search import Search + +class DisputeSearch: + amount_disputed: Search.RangeNodeBuilder + amount_won: Search.RangeNodeBuilder + case_number: Search.TextNodeBuilder + chargeback_protection_level: Search.MultipleValueNodeBuilder + protection_level: Search.MultipleValueNodeBuilder + customer_id: Search.TextNodeBuilder + disbursement_date: Search.RangeNodeBuilder + effective_date: Search.RangeNodeBuilder + id: Search.TextNodeBuilder + kind: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + pre_dispute_program: Search.MultipleValueNodeBuilder + reason: Search.MultipleValueNodeBuilder + reason_code: Search.MultipleValueNodeBuilder + received_date: Search.RangeNodeBuilder + reference_number: Search.TextNodeBuilder + reply_by_date: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + transaction_id: Search.TextNodeBuilder + transaction_source: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/document_upload.pyi b/stubs/braintree/braintree/document_upload.pyi new file mode 100644 index 000000000000..155b5596711e --- /dev/null +++ b/stubs/braintree/braintree/document_upload.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult + +class DocumentUpload(Resource): + class Kind: + EvidenceDocument: Final = "evidence_document" + + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def create_signature() -> list[str]: ... + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/document_upload_gateway.pyi b/stubs/braintree/braintree/document_upload_gateway.pyi new file mode 100644 index 000000000000..5dcf510fee1b --- /dev/null +++ b/stubs/braintree/braintree/document_upload_gateway.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class DocumentUploadGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/enriched_customer_data.pyi b/stubs/braintree/braintree/enriched_customer_data.pyi new file mode 100644 index 000000000000..18ad120319ee --- /dev/null +++ b/stubs/braintree/braintree/enriched_customer_data.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class EnrichedCustomerData(Resource): + profile_data: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/environment.pyi b/stubs/braintree/braintree/environment.pyi new file mode 100644 index 000000000000..cd272b3e434b --- /dev/null +++ b/stubs/braintree/braintree/environment.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing import ClassVar + +class Environment: + Development: ClassVar[Environment] + QA: ClassVar[Environment] + Sandbox: ClassVar[Environment] + Production: ClassVar[Environment] + All: ClassVar[dict[str, Environment]] + __name__: str + is_ssl: bool + ssl_certificate: Incomplete + def __init__( + self, + name, + server: str, + port, + auth_url: str, + is_ssl: bool, + ssl_certificate, + graphql_server: str = "", + graphql_port: str = "", + ) -> None: ... + @property + def base_url(self) -> str: ... + @property + def port(self) -> int: ... + @property + def auth_url(self) -> str: ... + @property + def protocol(self) -> str: ... + @property + def server(self) -> str: ... + @property + def server_and_port(self) -> str: ... + @property + def graphql_server(self) -> str: ... + @property + def graphql_port(self) -> str: ... + @property + def graphql_server_and_port(self) -> str: ... + @staticmethod + def parse_environment(environment: Environment | str | None) -> Environment | None: ... + @staticmethod + def braintree_root() -> str: ... diff --git a/stubs/braintree/braintree/error_codes.pyi b/stubs/braintree/braintree/error_codes.pyi new file mode 100644 index 000000000000..ee5086b0c5a3 --- /dev/null +++ b/stubs/braintree/braintree/error_codes.pyi @@ -0,0 +1,765 @@ +from typing import Final + +class ErrorCodes: + class Address: + CannotBeBlank: Final = "81801" + CompanyIsInvalid: Final = "91821" + CompanyIsTooLong: Final = "81802" + CountryCodeAlpha2IsNotAccepted: Final = "91814" + CountryCodeAlpha3IsNotAccepted: Final = "91816" + CountryCodeNumericIsNotAccepted: Final = "91817" + CountryNameIsNotAccepted: Final = "91803" + ExtendedAddressIsInvalid: Final = "91823" + ExtendedAddressIsTooLong: Final = "81804" + FirstNameIsInvalid: Final = "91819" + FirstNameIsTooLong: Final = "81805" + InconsistentCountry: Final = "91815" + IsInvalid: Final = "91828" + LastNameIsInvalid: Final = "91820" + LastNameIsTooLong: Final = "81806" + LocalityIsInvalid: Final = "91824" + LocalityIsTooLong: Final = "81807" + PostalCodeInvalidCharacters: Final = "81813" + PostalCodeIsInvalid: Final = "91826" + PostalCodeIsRequired: Final = "81808" + PostalCodeIsRequiredForCardBrandAndProcessor: Final = "81828" + PostalCodeIsTooLong: Final = "81809" + RegionIsInvalid: Final = "91825" + RegionIsTooLong: Final = "81810" + StateIsInvalidForSellerProtection: Final = "81827" + StreetAddressIsInvalid: Final = "91822" + StreetAddressIsRequired: Final = "81811" + StreetAddressIsTooLong: Final = "81812" + TooManyAddressesPerCustomer: Final = "91818" + + class AndroidPay: + AndroidPayCardsAreNotAccepted: Final = "83708" + + class ApplePay: + ApplePayCardsAreNotAccepted: Final = "83501" + CustomerIdIsRequiredForVaulting: Final = "83502" + TokenIsInUse: Final = "93503" + PaymentMethodNonceConsumed: Final = "93504" + PaymentMethodNonceUnknown: Final = "93505" + PaymentMethodNonceLocked: Final = "93506" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "83518" + CannotUpdateApplePayCardUsingPaymentMethodNonce: Final = "93507" + NumberIsRequired: Final = "93508" + ExpirationMonthIsRequired: Final = "93509" + ExpirationYearIsRequired: Final = "93510" + CryptogramIsRequired: Final = "93511" + DecryptionFailed: Final = "83512" + Disabled: Final = "93513" + MerchantNotConfigured: Final = "93514" + MerchantKeysAlreadyConfigured: Final = "93515" + MerchantKeysNotConfigured: Final = "93516" + NetworkTransactionIdNotAllowed: Final = "93532" + CertificateInvalid: Final = "93517" + CertificateMismatch: Final = "93519" + InvalidToken: Final = "83520" + PrivateKeyMismatch: Final = "93521" + KeyMismatchStoringCertificate: Final = "93522" + CustomerIdIsInvalid: Final = "93528" + BillingAddressFormatIsInvalid: Final = "93529" + + class Options: + class Verification: + AccountTypeIsInvalid: Final = "93538" + AccountTypeNotSupported: Final = "93543" + AmountCannotBeNegative: Final = "93535" + AmountFormatIsInvalid: Final = "93534" + AmountIsTooLarge: Final = "93537" + AmountNotSupportedByProcessor: Final = "93536" + MerchantAccountIdIsInvalid: Final = "93540" + MerchantAccountIsSuspended: Final = "93541" + NotSupportedByProcessor: Final = "93533" + + class AuthorizationFingerprint: + MissingFingerprint: Final = "93201" + InvalidFormat: Final = "93202" + SignatureRevoked: Final = "93203" + InvalidCreatedAt: Final = "93204" + InvalidPublicKey: Final = "93205" + InvalidSignature: Final = "93206" + OptionsNotAllowedWithoutCustomer: Final = "93207" + + class ClientToken: + CustomerDoesNotExist: Final = "92804" + FailOnDuplicatePaymentMethodRequiresCustomerId: Final = "92803" + FailOnDuplicatePaymentMethodForCustomerRequiresCustomerId: Final = "92805" + InvalidDomainFormat: Final = "92011" + MakeDefaultRequiresCustomerId: Final = "92801" + MerchantAccountDoesNotExist: Final = "92807" + ProxyMerchantDoesNotExist: Final = "92805" + TooManyDomains: Final = "92810" + UnsupportedVersion: Final = "92806" + VerifyCardRequiresCustomerId: Final = "92802" + + class CreditCard: + BillingAddressConflict: Final = "91701" + BillingAddressFormatIsInvalid: Final = "91744" + BillingAddressIdIsInvalid: Final = "91702" + CannotUpdateCardUsingPaymentMethodNonce: Final = "91735" + CardholderNameIsTooLong: Final = "81723" + CreditCardTypeIsNotAccepted: Final = "81703" + CreditCardTypeIsNotAcceptedBySubscriptionMerchantAccount: Final = "81718" + CustomerIdIsInvalid: Final = "91705" + CustomerIdIsRequired: Final = "91704" + CvvIsInvalid: Final = "81707" + CvvIsRequired: Final = "81706" + CvvVerificationFailed: Final = "81736" + DuplicateCardExists: Final = "81724" + DuplicateCardExistsForCustomer: Final = "81763" + ExpirationDateConflict: Final = "91708" + ExpirationDateIsInvalid: Final = "81710" + ExpirationDateIsRequired: Final = "81709" + ExpirationDateYearIsInvalid: Final = "81711" + ExpirationMonthIsInvalid: Final = "81712" + ExpirationYearIsInvalid: Final = "81713" + InvalidParamsForCreditCardUpdate: Final = "91745" + InvalidVenmoSDKPaymentMethodCode: Final = "91727" + LimitExceededforDuplicatePaymentMethodCheckForCustomer: Final = "81764" + NetworkTokenizationAttributeCryptogramIsRequired: Final = "81762" + NumberHasInvalidLength: Final = "81716" + NumberLengthIsInvalid: Final = "81716" + NumberIsInvalid: Final = "81715" + NumberIsProhibited: Final = "81750" + NumberIsRequired: Final = "81714" + NumberMustBeTestNumber: Final = "81717" + PaymentMethodConflict: Final = "81725" + PaymentMethodIsNotACreditCard: Final = "91738" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91734" + PaymentMethodNonceConsumed: Final = "91731" + PaymentMethodNonceLocked: Final = "91733" + PaymentMethodNonceUnknown: Final = "91732" + PostalCodeVerificationFailed: Final = "81737" + TokenInvalid: Final = "91718" + TokenFormatIsInvalid: Final = "91718" + TokenIsInUse: Final = "91719" + TokenIsNotAllowed: Final = "91721" + TokenIsRequired: Final = "91722" + TokenIsTooLong: Final = "91720" + VenmoSDKPaymentMethodCodeCardTypeIsNotAccepted: Final = "91726" + VerificationNotSupportedOnThisMerchantAccount: Final = "91730" + VerificationAccountTypeIsInvald: Final = "91757" + VerificationAccountTypeNotSupported: Final = "91758" + + class Options: + UpdateExistingTokenIsInvalid: Final = "91723" + UpdateExistingTokenNotAllowed: Final = "91729" + VerificationAmountCannotBeNegative: Final = "91739" + VerificationAmountFormatIsInvalid: Final = "91740" + VerificationAmountIsTooLarge: Final = "91752" + VerificationAmountNotSupportedByProcessor: Final = "91741" + VerificationMerchantAccountIdIsInvalid: Final = "91728" + VerificationMerchantAccountIsForbidden: Final = "91743" + VerificationMerchantAccountIsSuspended: Final = "91742" + + class Customer: + CompanyIsTooLong: Final = "81601" + CustomFieldIsInvalid: Final = "91602" + CustomFieldIsTooLong: Final = "81603" + EmailIsInvalid: Final = "81604" + EmailFormatIsInvalid: Final = "81604" + EmailIsRequired: Final = "81606" + EmailIsTooLong: Final = "81605" + FaxIsTooLong: Final = "81607" + FirstNameIsTooLong: Final = "81608" + IdIsInUse: Final = "91609" + IdIsInvalid: Final = "91610" + IdIsNotAllowed: Final = "91611" + IdIsRequired: Final = "91613" + IdIsTooLong: Final = "91612" + InternationalPhoneCountryCodeIsInvalid: Final = "91625" + InternationalPhoneNationalNumberIsInvalid: Final = "91626" + LastNameIsTooLong: Final = "81613" + PhoneIsTooLong: Final = "81614" + VaultedPaymentInstrumentNonceBelongsToDifferentCustomer: Final = "91617" + WebsiteIsInvalid: Final = "81616" + WebsiteFormatIsInvalid: Final = "81616" + WebsiteIsTooLong: Final = "81615" + + class Descriptor: + DynamicDescriptorsDisabled: Final = "92203" + InternationalNameFormatIsInvalid: Final = "92204" + InternationalPhoneFormatIsInvalid: Final = "92205" + NameFormatIsInvalid: Final = "92201" + PhoneFormatIsInvalid: Final = "92202" + UrlFormatIsInvalid: Final = "92206" + + class Dispute: + CanOnlyAddEvidenceToOpenDispute: Final = "95701" + CanOnlyRemoveEvidenceFromOpenDispute: Final = "95702" + CanOnlyAddEvidenceDocumentToDispute: Final = "95703" + CanOnlyAcceptOpenDispute: Final = "95704" + CanOnlyFinalizeOpenDispute: Final = "95705" + CanOnlyCreateEvidenceWithValidCategory: Final = "95706" + EvidenceContentDateInvalid: Final = "95707" + EvidenceContentTooLong: Final = "95708" + EvidenceContentARNTooLong: Final = "95709" + EvidenceContentPhoneTooLong: Final = "95710" + EvidenceCategoryTextOnly: Final = "95711" + EvidenceCategoryDocumentOnly: Final = "95712" + EvidenceCategoryNotForReasonCode: Final = "95713" + EvidenceCategoryDuplicate: Final = "95714" + EvidenceContentEmailInvalid: Final = "95715" + DigitalGoodsMissingEvidence: Final = "95720" + DigitalGoodsMissingDownloadDate: Final = "95721" + NonDisputedPriorTransactionEvidenceMissingARN: Final = "95722" + NonDisputedPriorTransactionEvidenceMissingDate: Final = "95723" + RecurringTransactionEvidenceMissingDate: Final = "95724" + RecurringTransactionEvidenceMissingARN: Final = "95725" + ValidEvidenceRequiredToFinalize: Final = "95726" + + class DocumentUpload: + KindIsInvalid: Final = "84901" + FileIsTooLarge: Final = "84902" + FileTypeIsInvalid: Final = "84903" + FileIsMalformedOrEncrypted: Final = "84904" + FileIsTooLong: Final = "84905" + FileIsEmpty: Final = "84906" + + class Merchant: + CountryCannotBeBlank: Final = "83603" + CountryCodeAlpha2IsInvalid: Final = "93607" + CountryCodeAlpha2IsNotAccepted: Final = "93606" + CountryCodeAlpha3IsInvalid: Final = "93605" + CountryCodeAlpha3IsNotAccepted: Final = "93604" + CountryCodeNumericIsInvalid: Final = "93609" + CountryCodeNumericIsNotAccepted: Final = "93608" + CountryNameIsInvalid: Final = "93611" + CountryNameIsNotAccepted: Final = "93610" + CurrenciesAreInvalid: Final = "93614" + EmailFormatIsInvalid: Final = "93602" + EmailIsRequired: Final = "83601" + InconsistentCountry: Final = "93612" + PaymentMethodsAreInvalid: Final = "93613" + PaymentMethodsAreNotAllowed: Final = "93615" + MerchantAccountExistsForCurrency: Final = "93616" + CurrencyIsRequired: Final = "93617" + CurrencyIsInvalid: Final = "93618" + NoMerchantAccounts: Final = "93619" + MerchantAccountExistsForId: Final = "93620" + + class MerchantAccount: + class ApplicantDetails: + Declined: Final = "82626" + DeclinedMasterCardMatch: Final = "82622" + DeclinedOFAC: Final = "82621" + DeclinedFailedKYC: Final = "82623" + DeclinedSsnInvalid: Final = "82624" + DeclinedSsnMatchesDeceased: Final = "82625" + + class OAuth: + InvalidGrant: Final = "93801" + InvalidCredentials: Final = "93802" + InvalidScope: Final = "93803" + InvalidRequest: Final = "93804" + UnsupportedGrantType: Final = "93805" + + class Verification: + ThreeDSecureAuthenticationIdIsInvalid: Final = "942196" + ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: Final = "942198" + ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: Final = "942197" + ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: Final = "942199" + ThreeDSecureAuthenticationFailed: Final = "94271" + ThreeDSecureTokenIsInvalid: Final = "94268" + ThreeDSecureVerificationDataDoesntMatchVerify: Final = "94270" + MerchantAccountDoesNotSupport3DSecure: Final = "942169" + MerchantAcountDoesNotMatch3DSecureMerchantAccount: Final = "94284" + AmountDoesNotMatch3DSecureAmount: Final = "94285" + + class ThreeDSecurePassThru: + EciFlagIsRequired: Final = "942113" + EciFlagIsInvalid: Final = "942114" + CavvIsRequired: Final = "942116" + ThreeDSecureVersionIsRequired: Final = "942117" + ThreeDSecureVersionIsInvalid: Final = "942119" + AuthenticationResponseIsInvalid: Final = "942120" + DirectoryResponseIsInvalid: Final = "942121" + CavvAlgorithmIsInvalid: Final = "942122" + + class Options: + AmountCannotBeNegative: Final = "94201" + AmountFormatIsInvalid: Final = "94202" + AmountIsTooLarge: Final = "94207" + AmountNotSupportedByProcessor: Final = "94203" + MerchantAccountIdIsInvalid: Final = "94204" + MerchantAccountIsSuspended: Final = "94205" + MerchantAccountIsForbidden: Final = "94206" + AccountTypeIsInvalid: Final = "942184" + AccountTypeNotSupported: Final = "942185" + + class PaymentMethod: + CannotForwardPaymentMethodType: Final = "93106" + PaymentMethodParamsAreRequired: Final = "93101" + NonceIsInvalid: Final = "93102" + NonceIsRequired: Final = "93103" + CustomerIdIsRequired: Final = "93104" + CustomerIdIsInvalid: Final = "93105" + PaymentMethodNonceConsumed: Final = "93107" + PaymentMethodNonceUnknown: Final = "93108" + PaymentMethodNonceLocked: Final = "93109" + PaymentMethodNoLongerSupported: Final = "93117" + AuthExpired: Final = "92911" + CannotHaveFundingSourceWithoutAccessToken: Final = "92912" + InvalidFundingSourceSelection: Final = "92913" + CannotUpdatePayPalAccountUsingPaymentMethodNonce: Final = "92914" + + class Options: + UsBankAccountVerificationMethodIsInvalid: Final = "93121" + + class PayPalAccount: + CannotHaveBothAccessTokenAndConsentCode: Final = "82903" + CannotVaultOneTimeUsePayPalAccount: Final = "82902" + ConsentCodeOrAccessTokenIsRequired: Final = "82901" + CustomerIdIsRequiredForVaulting: Final = "82905" + InvalidParamsForPayPalAccountUpdate: Final = "92915" + PayPalAccountsAreNotAccepted: Final = "82904" + PayPalCommunicationError: Final = "92910" + PaymentMethodNonceConsumed: Final = "92907" + PaymentMethodNonceLocked: Final = "92909" + PaymentMethodNonceUnknown: Final = "92908" + TokenIsInUse: Final = "92906" + + class PayPalPaymentResource: + NonceExpired: Final = "97301" + IdNotSupported: Final = "97302" + NonceRequired: Final = "97303" + InvalidEmail: Final = "97304" + EmailTooLong: Final = "97305" + ExpectedLineItemCollection: Final = "97306" + ExpectedLineItemHash: Final = "97307" + ExpectedLineItemDebit: Final = "97308" + InvalidUnitAmount: Final = "97309" + InvalidUnitTaxAmount: Final = "97310" + IsoCodeRequired: Final = "97311" + IsoCodeUnsupported: Final = "97312" + ShippingFieldsMissing: Final = "97313" + InvalidAmountBreakdown: Final = "97314" + ExpectedShippingOptionCollection: Final = "97315" + ShippingOptionsRequired: Final = "97316" + ShippingOptionFieldsMissing: Final = "97317" + InvalidShippingOptionType: Final = "97318" + ShippingOptionIdReused: Final = "97319" + TooManyShippingOptionsSelected: Final = "97320" + ShippingOptionMustMatchBreakdown: Final = "97321" + LineItemsShouldMatchTotal: Final = "97322" + LineItemsTaxShouldMatchTotal: Final = "97323" + PatchCallFailed: Final = "97324" + InvalidAmount: Final = "97325" + ShippingIdTooLong: Final = "97326" + ShippingLabelTooLong: Final = "97327" + ShippingFullNameTooLong: Final = "97328" + ShippingAddressTooLong: Final = "97329" + ShippingExtendedAddressTooLong: Final = "97330" + ShippingLocalityTooLong: Final = "97331" + ShippingRegionTooLong: Final = "97332" + CountryCodeTooLong: Final = "97333" + NationalNumberTooLong: Final = "97334" + PostalCodeTooLong: Final = "97335" + DescriptionTooLong: Final = "97336" + CustomFieldTooLong: Final = "97337" + OrderIdTooLong: Final = "97338" + + class SettlementBatchSummary: + CustomFieldIsInvalid: Final = "82303" + SettlementDateIsInvalid: Final = "82302" + SettlementDateIsRequired: Final = "82301" + + class SEPAMandate: + TypeIsRequired: Final = "93304" + IBANInvalidCharacter: Final = "83305" + BICInvalidCharacter: Final = "83306" + BICLengthIsInvalid: Final = "83307" + BICUnsupportedCountry: Final = "83308" + IBANUnsupportedCountry: Final = "83309" + IBANInvalidFormat: Final = "83310" + BillingAddressConflict: Final = "93311" + BillingAddressIdIsInvalid: Final = "93312" + TypeIsInvalid: Final = "93313" + + class EuropeBankAccount: + BICIsRequired: Final = "83302" + IBANIsRequired: Final = "83303" + AccountHolderNameIsRequired: Final = "83301" + + class SepaDirectDebitAccount: + SepaDebitAccountPaymentMethodMandateTypeIsNotSupported: Final = "87115" + SepaDebitAccountPaymentMethodCustomerIdIsInvalid: Final = "87116" + SepaDebitAccountPaymentMethodCustomerIdIsRequired: Final = "87117" + + class Subscription: + BillingDayOfMonthCannotBeUpdated: Final = "91918" + BillingDayOfMonthIsInvalid: Final = "91914" + BillingDayOfMonthMustBeNumeric: Final = "91913" + CannotAddDuplicateAddonOrDiscount: Final = "91911" + CannotEditCanceledSubscription: Final = "81901" + CannotEditExpiredSubscription: Final = "81910" + CannotEditPriceChangingFieldsOnPastDueSubscription: Final = "91920" + FirstBillingDateCannotBeInThePast: Final = "91916" + FirstBillingDateCannotBeUpdated: Final = "91919" + FirstBillingDateIsInvalid: Final = "91915" + IdIsInUse: Final = "81902" + InconsistentNumberOfBillingCycles: Final = "91908" + InconsistentStartDate: Final = "91917" + InvalidRequestFormat: Final = "91921" + MerchantAccountDoesNotSupportInstrumentType: Final = "91930" + MerchantAccountIdIsInvalid: Final = "91901" + MismatchCurrencyISOCode: Final = "91923" + NumberOfBillingCyclesCannotBeBlank: Final = "91912" + NumberOfBillingCyclesIsTooSmall: Final = "91909" + NumberOfBillingCyclesMustBeGreaterThanZero: Final = "91907" + NumberOfBillingCyclesMustBeNumeric: Final = "91906" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91924" + PaymentMethodNonceInstrumentTypeDoesNotSupportSubscriptions: Final = "91929" + PaymentMethodNonceIsInvalid: Final = "91925" + PaymentMethodNonceNotAssociatedWithCustomer: Final = "91926" + PaymentMethodNonceUnvaultedCardIsNotAccepted: Final = "91927" + PaymentMethodTokenCardTypeIsNotAccepted: Final = "91902" + PaymentMethodTokenInstrumentTypeDoesNotSupportSubscriptions: Final = "91928" + PaymentMethodTokenIsInvalid: Final = "91903" + PaymentMethodTokenNotAssociatedWithCustomer: Final = "91905" + PlanBillingFrequencyCannotBeUpdated: Final = "91922" + PlanIdIsInvalid: Final = "91904" + PriceCannotBeBlank: Final = "81903" + PriceFormatIsInvalid: Final = "81904" + PriceIsTooLarge: Final = "81923" + StatusIsCanceled: Final = "81905" + TokenFormatIsInvalid: Final = "81906" + TrialDurationFormatIsInvalid: Final = "81907" + TrialDurationIsRequired: Final = "81908" + TrialDurationUnitIsInvalid: Final = "81909" + + class Modification: + AmountCannotBeBlank: Final = "92003" + AmountIsInvalid: Final = "92002" + AmountIsTooLarge: Final = "92023" + CannotEditModificationsOnPastDueSubscription: Final = "92022" + CannotUpdateAndRemove: Final = "92015" + ExistingIdIsIncorrectKind: Final = "92020" + ExistingIdIsInvalid: Final = "92011" + ExistingIdIsRequired: Final = "92012" + IdToRemoveIsIncorrectKind: Final = "92021" + IdToRemoveIsNotPresent: Final = "92016" + InconsistentNumberOfBillingCycles: Final = "92018" + InheritedFromIdIsInvalid: Final = "92013" + InheritedFromIdIsRequired: Final = "92014" + Missing: Final = "92024" + NumberOfBillingCyclesCannotBeBlank: Final = "92017" + NumberOfBillingCyclesIsInvalid: Final = "92005" + NumberOfBillingCyclesMustBeGreaterThanZero: Final = "92019" + QuantityCannotBeBlank: Final = "92004" + QuantityIsInvalid: Final = "92001" + QuantityMustBeGreaterThanZero: Final = "92010" + IdToRemoveIsInvalid: Final = "92025" + + class Transaction: + AmountCannotBeNegative: Final = "81501" + AmountDoesNotMatch3DSecureAmount: Final = "91585" + AmountIsInvalid: Final = "81503" + AmountFormatIsInvalid: Final = "81503" + AmountIsRequired: Final = "81502" + AmountIsTooLarge: Final = "81528" + AmountMustBeGreaterThanZero: Final = "81531" + AmountNotSupportedByProcessor: Final = "815193" + BillingAddressConflict: Final = "91530" + BillingPhoneNumberIsInvalid: Final = "915206" + CannotBeVoided: Final = "91504" + CannotCancelRelease: Final = "91562" + CannotCloneCredit: Final = "91543" + CannotCloneMarketplaceTransaction: Final = "915137" + CannotCloneThirdPartyCofNetworkTokenTransaction: Final = "915274" + CannotCloneTransactionWithPayPalAccount: Final = "91573" + CannotCloneTransactionWithVaultCreditCard: Final = "91540" + CannotCloneUnsuccessfulTransaction: Final = "91542" + CannotCloneVoiceAuthorizations: Final = "91541" + CannotRefundCredit: Final = "91505" + CannotRefundSettlingTransaction: Final = "91574" + CannotRefundUnlessSettled: Final = "91506" + CannotRefundWithPendingMerchantAccount: Final = "91559" + CannotRefundWithSuspendedMerchantAccount: Final = "91538" + CannotSimulateTransactionSettlement: Final = "91575" + CannotSubmitForPartialSettlement: Final = "915103" + CannotSubmitForSettlement: Final = "91507" + CannotUpdateTransactionDetailsNotSubmittedForSettlement: Final = "915129" + ChannelIsTooLong: Final = "91550" + CreditCardIsRequired: Final = "91508" + CustomFieldIsInvalid: Final = "91526" + CustomFieldIsTooLong: Final = "81527" + CustomerDefaultPaymentMethodCardTypeIsNotAccepted: Final = "81509" + CustomerDoesNotHaveCreditCard: Final = "91511" + CustomerIdIsInvalid: Final = "91510" + DiscountAmountCannotBeNegative: Final = "915160" + DiscountAmountFormatIsInvalid: Final = "915159" + DiscountAmountIsTooLarge: Final = "915161" + ExchangeRateQuoteIdIsTooLong: Final = "915229" + ApiRequestKeyTooLong: Final = "915230" + ApiRequestKeyNotAllowed: Final = "915231" + ApiRequestKeyCanBeReusedOnlyWithTheSameRequest: Final = "915232" + ApiRequestKeyIsInFlight: Final = "915233" + ApiRequestKeyWithFailedRequest: Final = "915234" + ApiRequestKeyServerError: Final = "915235" + FailedAuthAdjustmentAllowRetry: Final = "95603" + FailedAuthAdjustmentHardDecline: Final = "95602" + FinalAuthSubmitForSettlementForDifferentAmount: Final = "95601" + HasAlreadyBeenRefunded: Final = "91512" + LineItemsExpected: Final = "915158" + MerchantAccountDoesNotMatch3DSecureMerchantAccount: Final = "91584" + MerchantAccountDoesNotSupportMOTO: Final = "91558" + MerchantAccountDoesNotSupportRefunds: Final = "91547" + MerchantAccountIdDoesNotMatchSubscription: Final = "915180" + MerchantAccountIdIsInvalid: Final = "91513" + MerchantAccountIsSuspended: Final = "91514" + NoNetAmountToPerformAuthAdjustment: Final = "95606" + OrderIdIsTooLong: Final = "91501" + PayPalAuthExpired: Final = "91579" + PayPalNotEnabled: Final = "91576" + PayPalVaultRecordMissingData: Final = "91583" + PaymentInstrumentNotSupportedByMerchantAccount: Final = "91577" + PaymentInstrumentTypeIsNotAccepted: Final = "915101" + PaymentInstrumentWithExternalVaultIsInvalid: Final = "915176" + PaymentMethodConflict: Final = "91515" + PaymentMethodConflictWithVenmoSDK: Final = "91549" + PaymentMethodDoesNotBelongToCustomer: Final = "91516" + PaymentMethodDoesNotBelongToSubscription: Final = "91527" + PaymentMethodNonceCardTypeIsNotAccepted: Final = "91567" + PaymentMethodNonceConsumed: Final = "91564" + PaymentMethodNonceHasNoValidPaymentInstrumentType: Final = "91569" + PaymentMethodNonceLocked: Final = "91566" + PaymentMethodNonceUnknown: Final = "91565" + PaymentMethodTokenCardTypeIsNotAccepted: Final = "91517" + PaymentMethodTokenIsInvalid: Final = "91518" + ProcessingMerchantCategoryCodeIsInvalid: Final = "915265" + ProcessorAuthorizationCodeCannotBeSet: Final = "91519" + ProcessorAuthorizationCodeIsInvalid: Final = "81520" + ProcessorDoesNotSupportAuths: Final = "915104" + ProcessorDoesNotSupportAuthAdjustment: Final = "915222" + ProcessorDoesNotSupportCredits: Final = "91546" + ProcessorDoesNotSupportIncrementalAuth: Final = "915220" + ProcessorDoesNotSupportMotoForCardType: Final = "915195" + ProcessorDoesNotSupportPartialAuthReversal: Final = "915221" + ProcessorDoesNotSupportPartialSettlement: Final = "915102" + ProcessorDoesNotSupportUpdatingDescriptor: Final = "915108" + ProcessorDoesNotSupportUpdatingOrderId: Final = "915107" + ProcessorDoesNotSupportUpdatingTransactionDetails: Final = "915130" + ProcessorDoesNotSupportVoiceAuthorizations: Final = "91545" + ProductSkuIsInvalid: Final = "915202" + PurchaseOrderNumberIsInvalid: Final = "91548" + PurchaseOrderNumberIsTooLong: Final = "91537" + RefundAmountIsTooLarge: Final = "91521" + RefundAuthHardDeclined: Final = "915200" + RefundAuthSoftDeclined: Final = "915201" + ScaExemptionInvalid: Final = "915213" + ServiceFeeAmountCannotBeNegative: Final = "91554" + ServiceFeeAmountFormatIsInvalid: Final = "91555" + ServiceFeeAmountIsTooLarge: Final = "91556" + ServiceFeeAmountNotAllowedOnMasterMerchantAccount: Final = "91557" + ServiceFeeIsNotAllowedOnCredits: Final = "91552" + ServiceFeeNotAcceptedForPayPal: Final = "91578" + SettlementAmountIsLessThanServiceFeeAmount: Final = "91551" + SettlementAmountIsTooLarge: Final = "91522" + ShippingAddressDoesntMatchCustomer: Final = "91581" + ShippingAmountCannotBeNegative: Final = "915163" + ShippingAmountFormatIsInvalid: Final = "915162" + ShippingAmountIsTooLarge: Final = "915164" + ShippingMethodIsInvalid: Final = "915203" + ShippingPhoneNumberIsInvalid: Final = "915204" + ShipsFromPostalCodeInvalidCharacters: Final = "915167" + ShipsFromPostalCodeIsInvalid: Final = "915166" + ShipsFromPostalCodeIsTooLong: Final = "915165" + SubscriptionDoesNotBelongToCustomer: Final = "91529" + SubscriptionIdIsInvalid: Final = "91528" + SubscriptionStatusMustBePastDue: Final = "91531" + TaxAmountCannotBeNegative: Final = "81534" + TaxAmountFormatIsInvalid: Final = "81535" + TaxAmountIsRequiredForAibSwedish: Final = "815224" + TaxAmountIsTooLarge: Final = "81536" + ThreeDSecureAuthenticationFailed: Final = "81571" + ThreeDSecureAuthenticationIdDoesntMatchNonceThreeDSecureAuthentication: Final = "915198" + ThreeDSecureAuthenticationIdIsInvalid: Final = "915196" + ThreeDSecureAuthenticationIdWithThreeDSecurePassThruIsInvalid: Final = "915199" + ThreeDSecureAuthenticationResponseIsInvalid: Final = "915120" + ThreeDSecureCavvAlgorithmIsInvalid: Final = "915122" + ThreeDSecureCavvIsRequired: Final = "915116" + ThreeDSecureDirectoryResponseIsInvalid: Final = "915121" + ThreeDSecureEciFlagIsInvalid: Final = "915114" + ThreeDSecureEciFlagIsRequired: Final = "915113" + ThreeDSecureMerchantAccountDoesNotSupportCardType: Final = "915131" + ThreeDSecureTokenIsInvalid: Final = "91568" + ThreeDSecureTransactionDataDoesntMatchVerify: Final = "91570" + ThreeDSecureTransactionPaymentMethodDoesntMatchThreeDSecureAuthenticationPaymentMethod: Final = "915197" + ThreeDSecureXidIsRequired: Final = "915115" + TooManyLineItems: Final = "915157" + TransactionIsNotEligibleForAdjustment: Final = "915219" + TransactionMustBeInStateAuthorized: Final = "915218" + TransactionSourceIsInvalid: Final = "915133" + TransferDetailsAreNotApplicableForThisMerchantAccount: Final = "97511" + TransferDetailsAreRequired: Final = "97510" + TransferReceiverAccountReferenceNumberIsNotValid: Final = "97509" + TransferReceiverAccountReferenceNumberTypeIsNotValid: Final = "97514" + TransferReceiverFirstNameIsNotValid: Final = "97507" + TransferReceiverLastNameIsNotValid: Final = "97508" + TransferReceiverTaxIdIsNotValid: Final = "97506" + TransferSenderAccountReferenceNumberIsNotValid: Final = "97505" + TransferSenderAccountReferenceNumberTypeIsNotValid: Final = "97513" + TransferSenderFirstNameIsNotValid: Final = "97503" + TransferSenderLastNameIsNotValid: Final = "97504" + TransferSenderTaxIdIsNotValid: Final = "97502" + TransferTypeIsInvalid: Final = "97501" + TypeIsInvalid: Final = "91523" + TypeIsRequired: Final = "91524" + UnsupportedVoiceAuthorization: Final = "91539" + UsBankAccountNonceMustBePlaidVerified: Final = "915171" + UsBankAccountNotVerified: Final = "915172" + + class ExternalVault: + StatusIsInvalid: Final = "915175" + StatusWithPreviousNetworkTransactionIdIsInvalid: Final = "915177" + CardTypeIsInvalid: Final = "915178" + PreviousNetworkTransactionIdIsInvalid: Final = "915179" + + class Options: + SubmitForSettlementIsRequiredForCloning: Final = "91544" + SubmitForSettlementIsRequiredForPayPalUnilateral: Final = "91582" + UseBillingForShippingDisabled: Final = "91572" + VaultIsDisabled: Final = "91525" + + class PayPal: + CustomFieldTooLong: Final = "91580" + + class CreditCard: + AccountTypeIsInvalid: Final = "915184" + AccountTypeNotSupported: Final = "915185" + AccountTypeDebitDoesNotSupportAuths: Final = "915186" + + class Industry: + IndustryTypeIsInvalid: Final = "93401" + + class Lodging: + EmptyData: Final = "93402" + FolioNumberIsInvalid: Final = "93403" + CheckInDateIsInvalid: Final = "93404" + CheckOutDateIsInvalid: Final = "93405" + CheckOutDateMustFollowCheckInDate: Final = "93406" + UnknownDataField: Final = "93407" + RoomRateMustBeGreaterThanZero: Final = "93433" + RoomRateFormatIsInvalid: Final = "93434" + RoomRateIsTooLarge: Final = "93435" + RoomTaxMustBeGreaterThanZero: Final = "93436" + RoomTaxFormatIsInvalid: Final = "93437" + RoomTaxIsTooLarge: Final = "93438" + NoShowIndicatorIsInvalid: Final = "93439" + AdvancedDepositIndicatorIsInvalid: Final = "93440" + FireSafetyIndicatorIsInvalid: Final = "93441" + PropertyPhoneIsInvalid: Final = "93442" + + class TravelCruise: + EmptyData: Final = "93408" + UnknownDataField: Final = "93409" + TravelPackageIsInvalid: Final = "93410" + DepartureDateIsInvalid: Final = "93411" + LodgingCheckInDateIsInvalid: Final = "93412" + LodgingCheckOutDateIsInvalid: Final = "93413" + + class TravelFlight: + EmptyData: Final = "93414" + UnknownDataField: Final = "93415" + CustomerCodeIsTooLong: Final = "93416" + FareAmountCannotBeNegative: Final = "93417" + FareAmountFormatIsInvalid: Final = "93418" + FareAmountIsTooLarge: Final = "93419" + FeeAmountCannotBeNegative: Final = "93420" + FeeAmountFormatIsInvalid: Final = "93421" + FeeAmountIsTooLarge: Final = "93422" + IssuedDateFormatIsInvalid: Final = "93423" + IssuingCarrierCodeIsTooLong: Final = "93424" + PassengerMiddleInitialIsTooLong: Final = "93425" + RestrictedTicketIsRequired: Final = "93426" + TaxAmountCannotBeNegative: Final = "93427" + TaxAmountFormatIsInvalid: Final = "93428" + TaxAmountIsTooLarge: Final = "93429" + TicketNumberIsTooLong: Final = "93430" + LegsExpected: Final = "93431" + TooManyLegs: Final = "93432" + + class Leg: + class TravelFlight: + ArrivalAirportCodeIsTooLong: Final = "96301" + ArrivalTimeFormatIsInvalid: Final = "96302" + CarrierCodeIsTooLong: Final = "96303" + ConjunctionTicketIsTooLong: Final = "96304" + CouponNumberIsTooLong: Final = "96305" + DepartureAirportCodeIsTooLong: Final = "96306" + DepartureTimeFormatIsInvalid: Final = "96307" + ExchangeTicketIsTooLong: Final = "96308" + FareAmountCannotBeNegative: Final = "96309" + FareAmountFormatIsInvalid: Final = "96310" + FareAmountIsTooLarge: Final = "96311" + FareBasisCodeIsTooLong: Final = "96312" + FeeAmountCannotBeNegative: Final = "96313" + FeeAmountFormatIsInvalid: Final = "96314" + FeeAmountIsTooLarge: Final = "96315" + ServiceClassIsTooLong: Final = "96316" + TaxAmountCannotBeNegative: Final = "96317" + TaxAmountFormatIsInvalid: Final = "96318" + TaxAmountIsTooLarge: Final = "96319" + TicketNumberIsTooLong: Final = "96320" + + class AdditionalCharge: + KindIsInvalid: Final = "96601" + KindMustBeUnique: Final = "96602" + AmountMustBeGreaterThanZero: Final = "96603" + AmountFormatIsInvalid: Final = "96604" + AmountIsTooLarge: Final = "96605" + AmountIsRequired: Final = "96606" + + class LineItem: + CommodityCodeIsTooLong: Final = "95801" + DescriptionIsTooLong: Final = "95803" + DiscountAmountCannotBeNegative: Final = "95806" + DiscountAmountFormatIsInvalid: Final = "95804" + DiscountAmountIsTooLarge: Final = "95805" + KindIsInvalid: Final = "95807" + KindIsRequired: Final = "95808" + NameIsRequired: Final = "95822" + NameIsTooLong: Final = "95823" + ProductCodeIsTooLong: Final = "95809" + QuantityFormatIsInvalid: Final = "95810" + QuantityIsRequired: Final = "95811" + QuantityIsTooLarge: Final = "95812" + TaxAmountCannotBeNegative: Final = "95829" + TaxAmountFormatIsInvalid: Final = "95827" + TaxAmountIsTooLarge: Final = "95828" + TotalAmountFormatIsInvalid: Final = "95813" + TotalAmountIsRequired: Final = "95814" + TotalAmountIsTooLarge: Final = "95815" + TotalAmountMustBeGreaterThanZero: Final = "95816" + UPCCodeIsMissing: Final = "95830" + UPCCodeIsTooLong: Final = "95831" + UPCTypeIsInvalid: Final = "95833" + UPCTypeIsMissing: Final = "95832" + UnitAmountFormatIsInvalid: Final = "95817" + UnitAmountIsRequired: Final = "95818" + UnitAmountIsTooLarge: Final = "95819" + UnitAmountMustBeGreaterThanZero: Final = "95820" + UnitOfMeasureIsTooLarge: Final = "95821" + UnitTaxAmountCannotBeNegative: Final = "95826" + UnitTaxAmountFormatIsInvalid: Final = "95824" + UnitTaxAmountIsTooLarge: Final = "95825" + + class UsBankAccountVerification: + NotConfirmable: Final = "96101" + MustBeMicroTransfersVerification: Final = "96102" + AmountsDoNotMatch: Final = "96103" + TooManyConfirmationAttempts: Final = "96104" + UnableToConfirmDepositAmounts: Final = "96105" + InvalidDepositAmounts: Final = "96106" + + class RiskData: + CustomerBrowserIsTooLong: Final = "94701" + CustomerDeviceIdIsTooLong: Final = "94702" + CustomerLocationZipInvalidCharacters: Final = "94703" + CustomerLocationZipIsInvalid: Final = "94704" + CustomerLocationZipIsTooLong: Final = "94705" + CustomerTenureIsTooLong: Final = "94706" diff --git a/stubs/braintree/braintree/error_result.pyi b/stubs/braintree/braintree/error_result.pyi new file mode 100644 index 000000000000..9f23d30fa60a --- /dev/null +++ b/stubs/braintree/braintree/error_result.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import Literal + +from braintree.credit_card_verification import CreditCardVerification +from braintree.errors import Errors +from braintree.plan import Plan +from braintree.subscription import Subscription +from braintree.transaction import Transaction + +class ErrorResult: + params: Incomplete + errors: Errors + message: Incomplete + credit_card_verification: CreditCardVerification | None + transaction: Transaction + subscription: Subscription + merchant_account: Plan + def __init__(self, gateway, attributes: dict[str, Incomplete]) -> None: ... + @property + def is_success(self) -> Literal[False]: ... diff --git a/stubs/braintree/braintree/errors.pyi b/stubs/braintree/braintree/errors.pyi new file mode 100644 index 000000000000..fa8d6b33ab48 --- /dev/null +++ b/stubs/braintree/braintree/errors.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.validation_error import ValidationError +from braintree.validation_error_collection import ValidationErrorCollection + +class Errors: + errors: ValidationErrorCollection + size = errors.deep_size # pyrefly: ignore [unknown-name] + def __init__(self, data: dict[str, Incomplete]) -> None: ... + @property + def deep_errors(self) -> list[ValidationError]: ... + def for_object(self, key: str) -> ValidationErrorCollection: ... + def __len__(self) -> int: ... diff --git a/stubs/braintree/braintree/europe_bank_account.pyi b/stubs/braintree/braintree/europe_bank_account.pyi new file mode 100644 index 000000000000..f9b9632ee832 --- /dev/null +++ b/stubs/braintree/braintree/europe_bank_account.pyi @@ -0,0 +1,11 @@ +from typing import Final + +from braintree.resource import Resource + +class EuropeBankAccount(Resource): + class MandateType: + Business: Final = "business" + Consumer: Final = "consumer" + + @staticmethod + def signature() -> list[str]: ... diff --git a/stubs/braintree/braintree/exceptions/__init__.pyi b/stubs/braintree/braintree/exceptions/__init__.pyi new file mode 100644 index 000000000000..38284711b57c --- /dev/null +++ b/stubs/braintree/braintree/exceptions/__init__.pyi @@ -0,0 +1,16 @@ +from braintree.exceptions.authentication_error import AuthenticationError as AuthenticationError +from braintree.exceptions.authorization_error import AuthorizationError as AuthorizationError +from braintree.exceptions.configuration_error import ConfigurationError as ConfigurationError +from braintree.exceptions.gateway_timeout_error import GatewayTimeoutError as GatewayTimeoutError +from braintree.exceptions.invalid_challenge_error import InvalidChallengeError as InvalidChallengeError +from braintree.exceptions.invalid_signature_error import InvalidSignatureError as InvalidSignatureError +from braintree.exceptions.not_found_error import NotFoundError as NotFoundError +from braintree.exceptions.request_timeout_error import RequestTimeoutError as RequestTimeoutError +from braintree.exceptions.server_error import ServerError as ServerError +from braintree.exceptions.service_unavailable_error import ServiceUnavailableError as ServiceUnavailableError +from braintree.exceptions.test_operation_performed_in_production_error import ( + TestOperationPerformedInProductionError as TestOperationPerformedInProductionError, +) +from braintree.exceptions.too_many_requests_error import TooManyRequestsError as TooManyRequestsError +from braintree.exceptions.unexpected_error import UnexpectedError as UnexpectedError +from braintree.exceptions.upgrade_required_error import UpgradeRequiredError as UpgradeRequiredError diff --git a/stubs/braintree/braintree/exceptions/authentication_error.pyi b/stubs/braintree/braintree/exceptions/authentication_error.pyi new file mode 100644 index 000000000000..cd370a008909 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/authentication_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class AuthenticationError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/authorization_error.pyi b/stubs/braintree/braintree/exceptions/authorization_error.pyi new file mode 100644 index 000000000000..60571eea3b93 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/authorization_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class AuthorizationError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/braintree_error.pyi b/stubs/braintree/braintree/exceptions/braintree_error.pyi new file mode 100644 index 000000000000..7437f6dc4f7a --- /dev/null +++ b/stubs/braintree/braintree/exceptions/braintree_error.pyi @@ -0,0 +1 @@ +class BraintreeError(Exception): ... diff --git a/stubs/braintree/braintree/exceptions/configuration_error.pyi b/stubs/braintree/braintree/exceptions/configuration_error.pyi new file mode 100644 index 000000000000..724af3481279 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/configuration_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.unexpected_error import UnexpectedError + +class ConfigurationError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi b/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi new file mode 100644 index 000000000000..86fb52e8724c --- /dev/null +++ b/stubs/braintree/braintree/exceptions/gateway_timeout_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class GatewayTimeoutError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/http/__init__.pyi b/stubs/braintree/braintree/exceptions/http/__init__.pyi new file mode 100644 index 000000000000..32eda380e81a --- /dev/null +++ b/stubs/braintree/braintree/exceptions/http/__init__.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.http.connection_error import ConnectionError as ConnectionError +from braintree.exceptions.http.invalid_response_error import InvalidResponseError as InvalidResponseError +from braintree.exceptions.http.timeout_error import TimeoutError as TimeoutError diff --git a/stubs/braintree/braintree/exceptions/http/connection_error.pyi b/stubs/braintree/braintree/exceptions/http/connection_error.pyi new file mode 100644 index 000000000000..7f97331a953f --- /dev/null +++ b/stubs/braintree/braintree/exceptions/http/connection_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.unexpected_error import UnexpectedError + +class ConnectionError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi b/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi new file mode 100644 index 000000000000..37f106d2b186 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/http/invalid_response_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.unexpected_error import UnexpectedError + +class InvalidResponseError(UnexpectedError): ... diff --git a/stubs/braintree/braintree/exceptions/http/timeout_error.pyi b/stubs/braintree/braintree/exceptions/http/timeout_error.pyi new file mode 100644 index 000000000000..649b9e18770a --- /dev/null +++ b/stubs/braintree/braintree/exceptions/http/timeout_error.pyi @@ -0,0 +1,5 @@ +from braintree.exceptions.unexpected_error import UnexpectedError + +class TimeoutError(UnexpectedError): ... +class ConnectTimeoutError(TimeoutError): ... +class ReadTimeoutError(TimeoutError): ... diff --git a/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi b/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi new file mode 100644 index 000000000000..a4ca43f62688 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/invalid_challenge_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class InvalidChallengeError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi b/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi new file mode 100644 index 000000000000..d55bc610ac69 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/invalid_signature_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class InvalidSignatureError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/not_found_error.pyi b/stubs/braintree/braintree/exceptions/not_found_error.pyi new file mode 100644 index 000000000000..955101fa34a3 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/not_found_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class NotFoundError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/request_timeout_error.pyi b/stubs/braintree/braintree/exceptions/request_timeout_error.pyi new file mode 100644 index 000000000000..c7dae6b0e27d --- /dev/null +++ b/stubs/braintree/braintree/exceptions/request_timeout_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class RequestTimeoutError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/server_error.pyi b/stubs/braintree/braintree/exceptions/server_error.pyi new file mode 100644 index 000000000000..83c3b6e8d3fd --- /dev/null +++ b/stubs/braintree/braintree/exceptions/server_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class ServerError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi b/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi new file mode 100644 index 000000000000..a1d5a82aa657 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/service_unavailable_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class ServiceUnavailableError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi b/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi new file mode 100644 index 000000000000..583b34429303 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/test_operation_performed_in_production_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class TestOperationPerformedInProductionError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi b/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi new file mode 100644 index 000000000000..9acc549e9a33 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/too_many_requests_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class TooManyRequestsError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/unexpected_error.pyi b/stubs/braintree/braintree/exceptions/unexpected_error.pyi new file mode 100644 index 000000000000..7c164d8609e0 --- /dev/null +++ b/stubs/braintree/braintree/exceptions/unexpected_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class UnexpectedError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi b/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi new file mode 100644 index 000000000000..48cdb303008d --- /dev/null +++ b/stubs/braintree/braintree/exceptions/upgrade_required_error.pyi @@ -0,0 +1,3 @@ +from braintree.exceptions.braintree_error import BraintreeError + +class UpgradeRequiredError(BraintreeError): ... diff --git a/stubs/braintree/braintree/exchange_rate_quote.pyi b/stubs/braintree/braintree/exchange_rate_quote.pyi new file mode 100644 index 000000000000..cc859132d075 --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote.pyi @@ -0,0 +1,4 @@ +from braintree.attribute_getter import AttributeGetter + +class ExchangeRateQuote(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi b/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi new file mode 100644 index 000000000000..ee551915d1e8 --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.exchange_rate_quote_payload import ExchangeRateQuotePayload +from braintree.successful_result import SuccessfulResult + +class ExchangeRateQuoteGateway: + gateway: Incomplete + config: Incomplete + graphql_client: Incomplete + def __init__(self, gateway, graphql_client=None) -> None: ... + exchange_rate_quote_payload: ExchangeRateQuotePayload + def generate(self, request) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_input.pyi b/stubs/braintree/braintree/exchange_rate_quote_input.pyi new file mode 100644 index 000000000000..43ca18533dbc --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_input.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.attribute_getter import AttributeGetter + +class ExchangeRateQuoteInput(AttributeGetter): + parent: Incomplete + def __init__(self, parent, attributes) -> None: ... + def done(self): ... + def to_graphql_variables(self) -> dict[str, Incomplete]: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_payload.pyi b/stubs/braintree/braintree/exchange_rate_quote_payload.pyi new file mode 100644 index 000000000000..39a7ed103bfb --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_payload.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from braintree.exchange_rate_quote import ExchangeRateQuote + +class ExchangeRateQuotePayload: + quotes: list[ExchangeRateQuote] + def __init__(self, data: Mapping[str, Incomplete]) -> None: ... + def get_quotes(self) -> list[ExchangeRateQuote]: ... diff --git a/stubs/braintree/braintree/exchange_rate_quote_request.pyi b/stubs/braintree/braintree/exchange_rate_quote_request.pyi new file mode 100644 index 000000000000..e5eec778b32f --- /dev/null +++ b/stubs/braintree/braintree/exchange_rate_quote_request.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.exchange_rate_quote_input import ExchangeRateQuoteInput + +class ExchangeRateQuoteRequest: + quotes: list[ExchangeRateQuoteInput] + def __init__(self) -> None: ... + def add_exchange_rate_quote_input(self, attributes) -> ExchangeRateQuoteInput: ... + def to_graphql_variables(self) -> dict[str, Incomplete]: ... diff --git a/stubs/braintree/braintree/facilitated_details.pyi b/stubs/braintree/braintree/facilitated_details.pyi new file mode 100644 index 000000000000..834dee8abc24 --- /dev/null +++ b/stubs/braintree/braintree/facilitated_details.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class FacilitatedDetails(AttributeGetter): ... diff --git a/stubs/braintree/braintree/facilitator_details.pyi b/stubs/braintree/braintree/facilitator_details.pyi new file mode 100644 index 000000000000..e91d76a76bfa --- /dev/null +++ b/stubs/braintree/braintree/facilitator_details.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class FacilitatorDetails(AttributeGetter): ... diff --git a/stubs/braintree/braintree/granted_payment_instrument_update.pyi b/stubs/braintree/braintree/granted_payment_instrument_update.pyi new file mode 100644 index 000000000000..2394d8843579 --- /dev/null +++ b/stubs/braintree/braintree/granted_payment_instrument_update.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class GrantedPaymentInstrumentUpdate(Resource): + payment_method_nonce: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/graphql/__init__.pyi b/stubs/braintree/braintree/graphql/__init__.pyi new file mode 100644 index 000000000000..c39a227b1fad --- /dev/null +++ b/stubs/braintree/braintree/graphql/__init__.pyi @@ -0,0 +1,20 @@ +from braintree.graphql.enums import Recommendations as Recommendations, RecommendedPaymentOption as RecommendedPaymentOption +from braintree.graphql.inputs import ( + BillingAddressInput as BillingAddressInput, + CreateCustomerSessionInput as CreateCustomerSessionInput, + CreateLocalPaymentContextInput as CreateLocalPaymentContextInput, + CustomerRecommendationsInput as CustomerRecommendationsInput, + CustomerSessionInput as CustomerSessionInput, + MonetaryAmountInput as MonetaryAmountInput, + PayerInfoInput as PayerInfoInput, + PayPalPayeeInput as PayPalPayeeInput, + PayPalPurchaseUnitInput as PayPalPurchaseUnitInput, + PhoneInput as PhoneInput, + UpdateCustomerSessionInput as UpdateCustomerSessionInput, +) +from braintree.graphql.types import ( + CustomerRecommendationsPayload as CustomerRecommendationsPayload, + PaymentOptions as PaymentOptions, + PaymentRecommendation as PaymentRecommendation, +) +from braintree.graphql.unions import CustomerRecommendations as CustomerRecommendations diff --git a/stubs/braintree/braintree/graphql/enums/__init__.pyi b/stubs/braintree/braintree/graphql/enums/__init__.pyi new file mode 100644 index 000000000000..ab73711c6d83 --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/__init__.pyi @@ -0,0 +1,2 @@ +from braintree.graphql.enums.recommendations import Recommendations as Recommendations +from braintree.graphql.enums.recommended_payment_option import RecommendedPaymentOption as RecommendedPaymentOption diff --git a/stubs/braintree/braintree/graphql/enums/recommendations.pyi b/stubs/braintree/braintree/graphql/enums/recommendations.pyi new file mode 100644 index 000000000000..907e49a1509d --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/recommendations.pyi @@ -0,0 +1,4 @@ +from enum import Enum + +class Recommendations(Enum): + PAYMENT_RECOMMENDATIONS = "PAYMENT_RECOMMENDATIONS" diff --git a/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi b/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi new file mode 100644 index 000000000000..b6e46e339492 --- /dev/null +++ b/stubs/braintree/braintree/graphql/enums/recommended_payment_option.pyi @@ -0,0 +1,5 @@ +from enum import Enum + +class RecommendedPaymentOption(Enum): + PAYPAL = "PAYPAL" + VENMO = "VENMO" diff --git a/stubs/braintree/braintree/graphql/inputs/__init__.pyi b/stubs/braintree/braintree/graphql/inputs/__init__.pyi new file mode 100644 index 000000000000..3ff432cc1a70 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/__init__.pyi @@ -0,0 +1,13 @@ +from braintree.graphql.inputs.billing_address_input import BillingAddressInput as BillingAddressInput +from braintree.graphql.inputs.create_customer_session_input import CreateCustomerSessionInput as CreateCustomerSessionInput +from braintree.graphql.inputs.create_local_payment_context_input import ( + CreateLocalPaymentContextInput as CreateLocalPaymentContextInput, +) +from braintree.graphql.inputs.customer_recommendations_input import CustomerRecommendationsInput as CustomerRecommendationsInput +from braintree.graphql.inputs.customer_session_input import CustomerSessionInput as CustomerSessionInput +from braintree.graphql.inputs.monetary_amount_input import MonetaryAmountInput as MonetaryAmountInput +from braintree.graphql.inputs.payer_info_input import PayerInfoInput as PayerInfoInput +from braintree.graphql.inputs.paypal_payee_input import PayPalPayeeInput as PayPalPayeeInput +from braintree.graphql.inputs.paypal_purchase_unit_input import PayPalPurchaseUnitInput as PayPalPurchaseUnitInput +from braintree.graphql.inputs.phone_input import PhoneInput as PhoneInput +from braintree.graphql.inputs.update_customer_session_input import UpdateCustomerSessionInput as UpdateCustomerSessionInput diff --git a/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi b/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi new file mode 100644 index 000000000000..94ef587a361d --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/billing_address_input.pyi @@ -0,0 +1,22 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryCode: str + extendedAddress: str + locality: str + postalCode: str + region: str + streetAddress: str + +class BillingAddressInput: + def __init__( + self, + country_code_alpha2: str | None = None, + extended_address: str | None = None, + locality: str | None = None, + postal_code: str | None = None, + region: str | None = None, + street_address: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi new file mode 100644 index 000000000000..28d6ab5385ed --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/create_customer_session_input.pyi @@ -0,0 +1,41 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + merchantAccountId: str + sessionId: str + customer: _CustomerSessionGraphqlVariables + domain: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + +class CreateCustomerSessionInput: + def __init__( + self, + merchant_account_id: str | None = None, + session_id: str | None = None, + customer: CustomerSessionInput | None = None, + domain: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def session_id(self, session_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def domain(self, domain: str) -> Self: ... + def build(self) -> CreateCustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi b/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi new file mode 100644 index 000000000000..dc8ea3b1c223 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/create_local_payment_context_input.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from braintree.graphql.inputs.monetary_amount_input import _GraphqlVariables as _MonetaryAmountGraphqlVariables +from braintree.graphql.inputs.payer_info_input import _GraphqlVariables as _PayerInfoGraphqlVariables + +@type_check_only +class _PaymentContext(TypedDict, total=False): + amount: _MonetaryAmountGraphqlVariables + cancelUrl: str + countryCode: str + expiryDate: str + merchantAccountId: str + orderId: str + payerInfo: _PayerInfoGraphqlVariables + returnUrl: str + type: str + +@type_check_only +class _GraphqlVariables(TypedDict): + paymentContext: _PaymentContext + +class CreateLocalPaymentContextInput: + def __init__( + self, + amount: dict[str, Incomplete] | None = None, + cancel_url: str | None = None, + country_code: str | None = None, + expiry_date: str | None = None, + merchant_account_id: str | None = None, + order_id: str | None = None, + payer_info: dict[str, Incomplete] | None = None, + return_url: str | None = None, + type: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi b/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi new file mode 100644 index 000000000000..2869cfd04ff1 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/customer_recommendations_input.pyi @@ -0,0 +1,41 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Required, Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + sessionId: Required[str] + merchantAccountId: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + domain: str + customer: _CustomerSessionGraphqlVariables + +class CustomerRecommendationsInput: + def __init__( + self, + session_id: str, + merchant_account_id: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + domain: str | None = None, + customer: CustomerSessionInput | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def session_id(self, session_id: str) -> Self: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def domain(self, domain: str) -> Self: ... + def build(self) -> CustomerRecommendationsInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi new file mode 100644 index 000000000000..91f694b892c2 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/customer_session_input.pyi @@ -0,0 +1,43 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.phone_input import PhoneInput, _GraphqlVariables as _PhoneInputGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + email: str + hashedEmail: str + phone: _PhoneInputGraphqlVariables + hashedPhoneNumber: str + deviceFingerprintId: str + paypalAppInstalled: bool + venmoAppInstalled: bool + userAgent: str + +class CustomerSessionInput: + def __init__( + self, + email: str | None = None, + hashed_email: str | None = None, + phone: PhoneInput | None = None, + hashed_phone_number: str | None = None, + device_fingerprint_id: str | None = None, + paypal_app_installed: bool | None = None, + venmo_app_installed: bool | None = None, + user_agent: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def email(self, email: str) -> Self: ... + def hashed_email(self, hashed_email: str) -> Self: ... + def phone(self, phone: PhoneInput) -> Self: ... + def hashed_phone_number(self, hashed_phone_number: str) -> Self: ... + def device_fingerprint_id(self, device_fingerprint_id: str) -> Self: ... + def paypal_app_installed(self, paypal_app_installed: bool) -> Self: ... + def venmo_app_installed(self, venmo_app_installed: bool) -> Self: ... + def user_agent(self, user_agent: str) -> Self: ... + def build(self) -> CustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi b/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi new file mode 100644 index 000000000000..f7180db3baa9 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/monetary_amount_input.pyi @@ -0,0 +1,11 @@ +from decimal import Decimal +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + value: str + currencyCode: str + +class MonetaryAmountInput: + def __init__(self, value: Decimal | None = None, currency_code: str | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi b/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi new file mode 100644 index 000000000000..c9dfe835bd52 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/payer_info_input.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +from braintree.graphql.inputs.billing_address_input import _GraphqlVariables as _BillingAddressGraphqlVariables +from braintree.graphql.inputs.shipping_address_input import _GraphqlVariables as _ShippingAddressGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + billingAddress: _BillingAddressGraphqlVariables + email: str + givenName: str + phoneCountryCode: str + phoneNumber: str + shippingAddress: _ShippingAddressGraphqlVariables + surname: str + +class PayerInfoInput: + def __init__( + self, + billing_address: dict[str, Incomplete] | None = None, + email: str | None = None, + given_name: str | None = None, + phone_country_code: str | None = None, + phone_number: str | None = None, + shipping_address: dict[str, Incomplete] | None = None, + surname: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi b/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi new file mode 100644 index 000000000000..92d40b81a679 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/paypal_payee_input.pyi @@ -0,0 +1,19 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + emailAddress: str + clientId: str + +class PayPalPayeeInput: + def __init__(self, email_address: str | None = None, client_id: str | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def email_address(self, email_address: str) -> Self: ... + def client_id(self, client_id: str) -> Self: ... + def build(self) -> PayPalPayeeInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi b/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi new file mode 100644 index 000000000000..4f4db97adc29 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/paypal_purchase_unit_input.pyi @@ -0,0 +1,24 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.monetary_amount_input import ( + MonetaryAmountInput, + _GraphqlVariables as _MonetaryAmountGraphqlVariables, +) +from braintree.graphql.inputs.paypal_payee_input import PayPalPayeeInput, _GraphqlVariables as _PayPalPayeeGraphqlVariables + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + payee: _PayPalPayeeGraphqlVariables + amount: _MonetaryAmountGraphqlVariables + +class PayPalPurchaseUnitInput: + def __init__(self, amount: MonetaryAmountInput | None = None, payee: PayPalPayeeInput | None = None) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder(amount: MonetaryAmountInput) -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self, amount: MonetaryAmountInput) -> None: ... + def payee(self, payee: PayPalPayeeInput) -> Self: ... + def build(self) -> PayPalPurchaseUnitInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/phone_input.pyi b/stubs/braintree/braintree/graphql/inputs/phone_input.pyi new file mode 100644 index 000000000000..667c1d531809 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/phone_input.pyi @@ -0,0 +1,23 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryPhoneCode: str + phoneNumber: str + extensionNumber: str + +class PhoneInput: + def __init__( + self, country_phone_code: str | None = None, phone_number: str | None = None, extension_number: str | None = None + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder() -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self) -> None: ... + def country_phone_code(self, country_phone_code: str) -> Self: ... + def phone_number(self, phone_number: str) -> Self: ... + def extension_number(self, extension_number: str) -> Self: ... + def build(self) -> PhoneInput: ... diff --git a/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi b/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi new file mode 100644 index 000000000000..f941611a7d90 --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/shipping_address_input.pyi @@ -0,0 +1,22 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + countryCode: str + extendedAddress: str + locality: str + postalCode: str + region: str + streetAddress: str + +class ShippingAddressInput: + def __init__( + self, + country_code_alpha2: str | None = None, + extended_address: str | None = None, + locality: str | None = None, + postal_code: str | None = None, + region: str | None = None, + street_address: str | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... diff --git a/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi b/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi new file mode 100644 index 000000000000..a8b580e70b2c --- /dev/null +++ b/stubs/braintree/braintree/graphql/inputs/update_customer_session_input.pyi @@ -0,0 +1,37 @@ +from typing import TypedDict, type_check_only +from typing_extensions import Self + +from braintree.graphql.inputs.customer_session_input import ( + CustomerSessionInput, + _GraphqlVariables as _CustomerSessionGraphqlVariables, +) +from braintree.graphql.inputs.paypal_purchase_unit_input import ( + PayPalPurchaseUnitInput, + _GraphqlVariables as _PayPalPurchaseUnitGraphqlVariables, +) + +@type_check_only +class _GraphqlVariables(TypedDict, total=False): + sessionId: str + customer: _CustomerSessionGraphqlVariables + merchantAccountId: str + purchaseUnits: list[_PayPalPurchaseUnitGraphqlVariables] + +class UpdateCustomerSessionInput: + def __init__( + self, + session_id: str, + customer: CustomerSessionInput | None = None, + merchant_account_id: str | None = None, + purchase_units: list[PayPalPurchaseUnitInput] | None = None, + ) -> None: ... + def to_graphql_variables(self) -> _GraphqlVariables: ... + @staticmethod + def builder(session_id: str) -> Builder: ... # pyrefly: ignore [unknown-name] + + class Builder: + def __init__(self, session_id: str) -> None: ... + def merchant_account_id(self, merchant_account_id: str) -> Self: ... + def customer(self, customer: CustomerSessionInput) -> Self: ... + def purchase_units(self, purchase_units: list[PayPalPurchaseUnitInput]) -> Self: ... + def build(self) -> UpdateCustomerSessionInput: ... diff --git a/stubs/braintree/braintree/graphql/types/__init__.pyi b/stubs/braintree/braintree/graphql/types/__init__.pyi new file mode 100644 index 000000000000..0e2d21a802d7 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/__init__.pyi @@ -0,0 +1,5 @@ +from braintree.graphql.types.customer_recommendations_payload import ( + CustomerRecommendationsPayload as CustomerRecommendationsPayload, +) +from braintree.graphql.types.payment_options import PaymentOptions as PaymentOptions +from braintree.graphql.types.payment_recommendation import PaymentRecommendation as PaymentRecommendation diff --git a/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi b/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi new file mode 100644 index 000000000000..488df1d1de61 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/customer_recommendations_payload.pyi @@ -0,0 +1,22 @@ +from typing import Any, overload + +from braintree.graphql.unions.customer_recommendations import CustomerRecommendations + +class CustomerRecommendationsPayload: + session_id: str + is_in_paypal_network: bool + recommendations: CustomerRecommendations + + @overload + def __init__( + self, + session_id: None = None, + is_in_paypal_network: None = None, + recommendations: None = None, + *, + response: dict[str, Any], + ): ... + @overload + def __init__( + self, session_id: str, is_in_paypal_network: bool, recommendations: CustomerRecommendations, response: None = None + ): ... diff --git a/stubs/braintree/braintree/graphql/types/payment_options.pyi b/stubs/braintree/braintree/graphql/types/payment_options.pyi new file mode 100644 index 000000000000..756f4d1410c4 --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/payment_options.pyi @@ -0,0 +1,6 @@ +from braintree.graphql.enums import RecommendedPaymentOption + +class PaymentOptions: + payment_option: RecommendedPaymentOption + recommended_priority: int + def __init__(self, payment_option: RecommendedPaymentOption, recommended_priority: int) -> None: ... diff --git a/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi b/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi new file mode 100644 index 000000000000..34ed4dc436db --- /dev/null +++ b/stubs/braintree/braintree/graphql/types/payment_recommendation.pyi @@ -0,0 +1,6 @@ +from braintree.graphql.enums import RecommendedPaymentOption + +class PaymentRecommendation: + payment_option: RecommendedPaymentOption + recommended_priority: int + def __init__(self, payment_option: RecommendedPaymentOption, recommended_priority: int) -> None: ... diff --git a/stubs/braintree/braintree/graphql/unions/__init__.pyi b/stubs/braintree/braintree/graphql/unions/__init__.pyi new file mode 100644 index 000000000000..6b6217e4c28e --- /dev/null +++ b/stubs/braintree/braintree/graphql/unions/__init__.pyi @@ -0,0 +1 @@ +from braintree.graphql.unions.customer_recommendations import CustomerRecommendations as CustomerRecommendations diff --git a/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi b/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi new file mode 100644 index 000000000000..63a3df64fd59 --- /dev/null +++ b/stubs/braintree/braintree/graphql/unions/customer_recommendations.pyi @@ -0,0 +1,7 @@ +from braintree.graphql.types.payment_options import PaymentOptions +from braintree.graphql.types.payment_recommendation import PaymentRecommendation + +class CustomerRecommendations: + payment_options: list[PaymentOptions] + payment_recommendations: list[PaymentRecommendation] + def __init__(self, payment_recommendations: list[PaymentRecommendation] | None = None) -> None: ... diff --git a/stubs/braintree/braintree/iban_bank_account.pyi b/stubs/braintree/braintree/iban_bank_account.pyi new file mode 100644 index 000000000000..26ac82783207 --- /dev/null +++ b/stubs/braintree/braintree/iban_bank_account.pyi @@ -0,0 +1,3 @@ +from braintree.resource import Resource + +class IbanBankAccount(Resource): ... diff --git a/stubs/braintree/braintree/ids_search.pyi b/stubs/braintree/braintree/ids_search.pyi new file mode 100644 index 000000000000..bea7f0fb954a --- /dev/null +++ b/stubs/braintree/braintree/ids_search.pyi @@ -0,0 +1,4 @@ +from braintree.search import Search + +class IdsSearch: + ids: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/liability_shift.pyi b/stubs/braintree/braintree/liability_shift.pyi new file mode 100644 index 000000000000..8f9b60d0ec98 --- /dev/null +++ b/stubs/braintree/braintree/liability_shift.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class LiabilityShift(AttributeGetter): ... diff --git a/stubs/braintree/braintree/local_payment.pyi b/stubs/braintree/braintree/local_payment.pyi new file mode 100644 index 000000000000..bb64eecd2a88 --- /dev/null +++ b/stubs/braintree/braintree/local_payment.pyi @@ -0,0 +1,3 @@ +from braintree.resource import Resource + +class LocalPayment(Resource): ... diff --git a/stubs/braintree/braintree/local_payment_completed.pyi b/stubs/braintree/braintree/local_payment_completed.pyi new file mode 100644 index 000000000000..4adab3529b4b --- /dev/null +++ b/stubs/braintree/braintree/local_payment_completed.pyi @@ -0,0 +1,6 @@ +from braintree.resource import Resource +from braintree.transaction import Transaction + +class LocalPaymentCompleted(Resource): + transaction: Transaction + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_context.pyi b/stubs/braintree/braintree/local_payment_context.pyi new file mode 100644 index 000000000000..6c7684b01a46 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_context.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +from braintree.attribute_getter import AttributeGetter + +class LocalPaymentContext(AttributeGetter): + def __init__(self, attributes: dict[str, Incomplete] | None = None) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_context_gateway.pyi b/stubs/braintree/braintree/local_payment_context_gateway.pyi new file mode 100644 index 000000000000..d33094c1a900 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_context_gateway.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.graphql import CreateLocalPaymentContextInput +from braintree.successful_result import SuccessfulResult + +class LocalPaymentContextGateway: + CREATE_LOCAL_PAYMENT_CONTEXT: str + FIND_LOCAL_PAYMENT_CONTEXT: str + gateway: Incomplete + graphql_client: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, input: CreateLocalPaymentContextInput) -> SuccessfulResult | ErrorResult: ... + def find(self, id) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/local_payment_expired.pyi b/stubs/braintree/braintree/local_payment_expired.pyi new file mode 100644 index 000000000000..3b69ab08a345 --- /dev/null +++ b/stubs/braintree/braintree/local_payment_expired.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class LocalPaymentExpired(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_funded.pyi b/stubs/braintree/braintree/local_payment_funded.pyi new file mode 100644 index 000000000000..0453a53194de --- /dev/null +++ b/stubs/braintree/braintree/local_payment_funded.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class LocalPaymentFunded(Resource): + transaction: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_reversed.pyi b/stubs/braintree/braintree/local_payment_reversed.pyi new file mode 100644 index 000000000000..8f4e5259162d --- /dev/null +++ b/stubs/braintree/braintree/local_payment_reversed.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class LocalPaymentReversed(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/local_payment_type.pyi b/stubs/braintree/braintree/local_payment_type.pyi new file mode 100644 index 000000000000..cf897047f2aa --- /dev/null +++ b/stubs/braintree/braintree/local_payment_type.pyi @@ -0,0 +1,5 @@ +from typing import Final + +class LocalPaymentType: + CRYPTO: Final = "CRYPTO" + MBWAY: Final = "MBWAY" diff --git a/stubs/braintree/braintree/masterpass_card.pyi b/stubs/braintree/braintree/masterpass_card.pyi new file mode 100644 index 000000000000..c50678e419b7 --- /dev/null +++ b/stubs/braintree/braintree/masterpass_card.pyi @@ -0,0 +1,12 @@ +from braintree.address import Address +from braintree.resource import Resource +from braintree.subscription import Subscription + +class MasterpassCard(Resource): + billing_address: Address | None + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/merchant.pyi b/stubs/braintree/braintree/merchant.pyi new file mode 100644 index 000000000000..4f6c03e283c3 --- /dev/null +++ b/stubs/braintree/braintree/merchant.pyi @@ -0,0 +1,6 @@ +from braintree.merchant_account import MerchantAccount +from braintree.resource import Resource + +class Merchant(Resource): + merchant_accounts: list[MerchantAccount] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/__init__.pyi b/stubs/braintree/braintree/merchant_account/__init__.pyi new file mode 100644 index 000000000000..85c7724f4d94 --- /dev/null +++ b/stubs/braintree/braintree/merchant_account/__init__.pyi @@ -0,0 +1 @@ +from braintree.merchant_account.merchant_account import MerchantAccount as MerchantAccount diff --git a/stubs/braintree/braintree/merchant_account/address_details.pyi b/stubs/braintree/braintree/merchant_account/address_details.pyi new file mode 100644 index 000000000000..0ae743222469 --- /dev/null +++ b/stubs/braintree/braintree/merchant_account/address_details.pyi @@ -0,0 +1,7 @@ +from typing import ClassVar + +from braintree.attribute_getter import AttributeGetter + +class AddressDetails(AttributeGetter): + detail_list: ClassVar[list[str]] + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/merchant_account/merchant_account.pyi b/stubs/braintree/braintree/merchant_account/merchant_account.pyi new file mode 100644 index 000000000000..2fbe0ac80ed9 --- /dev/null +++ b/stubs/braintree/braintree/merchant_account/merchant_account.pyi @@ -0,0 +1,24 @@ +from typing import Final + +from braintree.resource import Resource + +class MerchantAccount(Resource): + class Status: + Active: Final = "active" + Pending: Final = "pending" + Suspended: Final = "suspended" + + class FundingDestination: + Bank: Final = "bank" + Email: Final = "email" + MobilePhone: Final = "mobile_phone" + + FundingDestinations: type[FundingDestination] + master_merchant_account: MerchantAccount + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def create(params=None): ... + @staticmethod + def update(id, attributes): ... + @staticmethod + def find(id): ... diff --git a/stubs/braintree/braintree/merchant_account_gateway.pyi b/stubs/braintree/braintree/merchant_account_gateway.pyi new file mode 100644 index 000000000000..5d426f6b4108 --- /dev/null +++ b/stubs/braintree/braintree/merchant_account_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.merchant_account import MerchantAccount +from braintree.successful_result import SuccessfulResult + +class MerchantAccountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, merchant_account_id: str) -> MerchantAccount: ... + def create_for_currency(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def all(self) -> SuccessfulResult: ... diff --git a/stubs/braintree/braintree/merchant_gateway.pyi b/stubs/braintree/braintree/merchant_gateway.pyi new file mode 100644 index 000000000000..54773625e1b7 --- /dev/null +++ b/stubs/braintree/braintree/merchant_gateway.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class MerchantGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + @deprecated("gateway.merchant.create(...) is deprecated and will be removed in a future version.") + def create(self, params: dict[str, Incomplete] | None) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/meta_checkout_card.pyi b/stubs/braintree/braintree/meta_checkout_card.pyi new file mode 100644 index 000000000000..7ee4304b9cfa --- /dev/null +++ b/stubs/braintree/braintree/meta_checkout_card.pyi @@ -0,0 +1,8 @@ +from braintree.resource import Resource + +class MetaCheckoutCard(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str | None: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/meta_checkout_token.pyi b/stubs/braintree/braintree/meta_checkout_token.pyi new file mode 100644 index 000000000000..a9d7bece4d1c --- /dev/null +++ b/stubs/braintree/braintree/meta_checkout_token.pyi @@ -0,0 +1,8 @@ +from braintree.resource import Resource + +class MetaCheckoutToken(Resource): + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self) -> str | None: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/modification.pyi b/stubs/braintree/braintree/modification.pyi new file mode 100644 index 000000000000..aca8b4cd837a --- /dev/null +++ b/stubs/braintree/braintree/modification.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.resource import Resource + +class Modification(Resource): + amount: Decimal + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/monetary_amount.pyi b/stubs/braintree/braintree/monetary_amount.pyi new file mode 100644 index 000000000000..6da51aaaac91 --- /dev/null +++ b/stubs/braintree/braintree/monetary_amount.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.attribute_getter import AttributeGetter + +class MonetaryAmount(AttributeGetter): + value: Decimal + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/oauth_access_revocation.pyi b/stubs/braintree/braintree/oauth_access_revocation.pyi new file mode 100644 index 000000000000..5e06bcb21083 --- /dev/null +++ b/stubs/braintree/braintree/oauth_access_revocation.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class OAuthAccessRevocation(Resource): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/oauth_credentials.pyi b/stubs/braintree/braintree/oauth_credentials.pyi new file mode 100644 index 000000000000..a2e861aee39c --- /dev/null +++ b/stubs/braintree/braintree/oauth_credentials.pyi @@ -0,0 +1,3 @@ +from braintree.resource import Resource + +class OAuthCredentials(Resource): ... diff --git a/stubs/braintree/braintree/oauth_gateway.pyi b/stubs/braintree/braintree/oauth_gateway.pyi new file mode 100644 index 000000000000..53e5af4f3d3f --- /dev/null +++ b/stubs/braintree/braintree/oauth_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class OAuthGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def create_token_from_code(self, params: dict[str, Incomplete]) -> SuccessfulResult | ErrorResult: ... + def create_token_from_refresh_token(self, params: dict[str, Incomplete]) -> SuccessfulResult | ErrorResult: ... + def revoke_access_token(self, access_token: str) -> type[SuccessfulResult] | ErrorResult: ... + def connect_url(self, raw_params: dict[str, Incomplete]) -> str: ... diff --git a/stubs/braintree/braintree/package_details.pyi b/stubs/braintree/braintree/package_details.pyi new file mode 100644 index 000000000000..10693c94eea4 --- /dev/null +++ b/stubs/braintree/braintree/package_details.pyi @@ -0,0 +1,7 @@ +from typing import ClassVar + +from braintree.attribute_getter import AttributeGetter + +class PackageDetails(AttributeGetter): + detail_list: ClassVar[list[str]] + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paginated_collection.pyi b/stubs/braintree/braintree/paginated_collection.pyi new file mode 100644 index 000000000000..f370775e7db2 --- /dev/null +++ b/stubs/braintree/braintree/paginated_collection.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +class PaginatedCollection: + def __init__(self, method) -> None: ... + @property + def items(self) -> Generator[Incomplete]: ... + def __iter__(self): ... diff --git a/stubs/braintree/braintree/paginated_result.pyi b/stubs/braintree/braintree/paginated_result.pyi new file mode 100644 index 000000000000..3511f8708d6e --- /dev/null +++ b/stubs/braintree/braintree/paginated_result.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +class PaginatedResult: + total_items: Incomplete + page_size: Incomplete + current_page: Incomplete + def __init__(self, total_items, page_size, current_page) -> None: ... diff --git a/stubs/braintree/braintree/partner_merchant.pyi b/stubs/braintree/braintree/partner_merchant.pyi new file mode 100644 index 000000000000..cfb5581a4318 --- /dev/null +++ b/stubs/braintree/braintree/partner_merchant.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class PartnerMerchant(Resource): + partner_merchant_id: Incomplete + private_key: Incomplete + public_key: Incomplete + merchant_public_id: Incomplete + client_side_encryption_key: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_facilitator.pyi b/stubs/braintree/braintree/payment_facilitator.pyi new file mode 100644 index 000000000000..905ced231d28 --- /dev/null +++ b/stubs/braintree/braintree/payment_facilitator.pyi @@ -0,0 +1,6 @@ +from braintree.attribute_getter import AttributeGetter +from braintree.sub_merchant import SubMerchant + +class PaymentFacilitator(AttributeGetter): + sub_merchant: SubMerchant + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_instrument_type.pyi b/stubs/braintree/braintree/payment_instrument_type.pyi new file mode 100644 index 000000000000..ec607ffafcdb --- /dev/null +++ b/stubs/braintree/braintree/payment_instrument_type.pyi @@ -0,0 +1,19 @@ +from typing import Final + +class PaymentInstrumentType: + AmexExpressCheckoutCard: Final = "amex_express_checkout_card" + AndroidPayCard: Final = "android_pay_card" + ApplePayCard: Final = "apple_pay_card" + CreditCard: Final = "credit_card" + EuropeBankAccount: Final = "europe_bank_account" + LocalPayment: Final = "local_payment" + MasterpassCard: Final = "masterpass_card" + MetaCheckoutCard: Final = "meta_checkout_card" + MetaCheckoutToken: Final = "meta_checkout_token" + PayPalAccount: Final = "paypal_account" + PayPalHere: Final = "paypal_here" + SamsungPayCard: Final = "samsung_pay_card" + SepaDirectDebitAccount: Final = "sepa_debit_account" + UsBankAccount: Final = "us_bank_account" + VenmoAccount: Final = "venmo_account" + VisaCheckoutCard: Final = "visa_checkout_card" diff --git a/stubs/braintree/braintree/payment_method.pyi b/stubs/braintree/braintree/payment_method.pyi new file mode 100644 index 000000000000..41ac52cb6807 --- /dev/null +++ b/stubs/braintree/braintree/payment_method.pyi @@ -0,0 +1,66 @@ +from _typeshed import Incomplete + +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.resource import Resource +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.successful_result import SuccessfulResult +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard + +class PaymentMethod(Resource): + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def find( + payment_method_token: str, + ) -> ( + AndroidPayCard + | ApplePayCard + | EuropeBankAccount + | CreditCard + | PayPalAccount + | UsBankAccount + | VenmoAccount + | VisaCheckoutCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod + ): ... + @staticmethod + def update(payment_method_token: str, params) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def delete(payment_method_token: str, options=None) -> SuccessfulResult: ... + @staticmethod + def create_signature() -> ( + list[ + str + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + | dict[str, list[str]] + ] + ): ... + @staticmethod + def signature( + type: str, + ) -> list[ + str + | dict[str, list[str | dict[str, list[str]]]] + | dict[str, list[str | dict[str, list[str]] | dict[str, list[str | dict[str, list[str | dict[str, list[str]]]]]]]] + | dict[str, list[str]] + ]: ... + @staticmethod + def update_signature() -> list[str | dict[str, list[str | dict[str, list[str]]]] | dict[str, list[str]]]: ... + @staticmethod + def delete_signature() -> list[str]: ... diff --git a/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi b/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi new file mode 100644 index 000000000000..6bbe0f16bbb6 --- /dev/null +++ b/stubs/braintree/braintree/payment_method_customer_data_updated_metadata.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class PaymentMethodCustomerDataUpdatedMetadata(Resource): + payment_method: Incomplete + enriched_customer_data: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_method_gateway.pyi b/stubs/braintree/braintree/payment_method_gateway.pyi new file mode 100644 index 000000000000..16054b4413d5 --- /dev/null +++ b/stubs/braintree/braintree/payment_method_gateway.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.error_result import ErrorResult +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.successful_result import SuccessfulResult +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard + +class PaymentMethodGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult: ... + def find( + self, payment_method_token: str + ) -> ( + AndroidPayCard + | ApplePayCard + | EuropeBankAccount + | CreditCard + | PayPalAccount + | UsBankAccount + | VenmoAccount + | VisaCheckoutCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod + ): ... + def update(self, payment_method_token: str, params) -> SuccessfulResult | ErrorResult: ... + def delete(self, payment_method_token: str, options=None) -> SuccessfulResult: ... + options: dict[str, Incomplete] + def grant(self, payment_method_token: str, options=None) -> SuccessfulResult | ErrorResult: ... + def revoke(self, payment_method_token: str) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/payment_method_nonce.pyi b/stubs/braintree/braintree/payment_method_nonce.pyi new file mode 100644 index 000000000000..9848d09b7fe8 --- /dev/null +++ b/stubs/braintree/braintree/payment_method_nonce.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from braintree.bin_data import BinData +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult +from braintree.three_d_secure_info import ThreeDSecureInfo + +class PaymentMethodNonce(Resource): + @staticmethod + def create(payment_method_token: str, params={}) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def find(payment_method_nonce: str) -> PaymentMethodNonce: ... + three_d_secure_info: ThreeDSecureInfo | None + authentication_insight: Incomplete + bin_data: BinData + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/payment_method_nonce_gateway.pyi b/stubs/braintree/braintree/payment_method_nonce_gateway.pyi new file mode 100644 index 000000000000..df513455ac4d --- /dev/null +++ b/stubs/braintree/braintree/payment_method_nonce_gateway.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.payment_method_nonce import PaymentMethodNonce +from braintree.successful_result import SuccessfulResult + +class PaymentMethodNonceGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def create(self, payment_method_token: str, params=...) -> SuccessfulResult | ErrorResult: ... + def find(self, payment_method_nonce: str) -> PaymentMethodNonce: ... diff --git a/stubs/braintree/braintree/payment_method_parser.pyi b/stubs/braintree/braintree/payment_method_parser.pyi new file mode 100644 index 000000000000..9881d41f3a9c --- /dev/null +++ b/stubs/braintree/braintree/payment_method_parser.pyi @@ -0,0 +1,31 @@ +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.credit_card import CreditCard +from braintree.europe_bank_account import EuropeBankAccount +from braintree.masterpass_card import MasterpassCard +from braintree.paypal_account import PayPalAccount +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.unknown_payment_method import UnknownPaymentMethod +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard + +def parse_payment_method( + gateway, attributes +) -> ( + PayPalAccount + | CreditCard + | EuropeBankAccount + | ApplePayCard + | AndroidPayCard + | AmexExpressCheckoutCard + | SepaDirectDebitAccount + | VenmoAccount + | UsBankAccount + | VisaCheckoutCard + | MasterpassCard + | SamsungPayCard + | UnknownPaymentMethod +): ... diff --git a/stubs/braintree/braintree/paypal_account.pyi b/stubs/braintree/braintree/paypal_account.pyi new file mode 100644 index 000000000000..984bb08de2d8 --- /dev/null +++ b/stubs/braintree/braintree/paypal_account.pyi @@ -0,0 +1,16 @@ +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult + +class PayPalAccount(Resource): + @staticmethod + def find(paypal_account_token: str) -> PayPalAccount | None: ... + @staticmethod + def delete(paypal_account_token: str) -> SuccessfulResult: ... + @staticmethod + def update(paypal_account_token: str, params=None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def signature() -> list[str | dict[str, list[str]]]: ... + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paypal_account_gateway.pyi b/stubs/braintree/braintree/paypal_account_gateway.pyi new file mode 100644 index 000000000000..873cca8b10d1 --- /dev/null +++ b/stubs/braintree/braintree/paypal_account_gateway.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.paypal_account import PayPalAccount +from braintree.successful_result import SuccessfulResult + +class PayPalAccountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, paypal_account_token: str) -> PayPalAccount | None: ... + def delete(self, paypal_account_token: str) -> SuccessfulResult: ... + def update(self, paypal_account_token: str, params=None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/paypal_here.pyi b/stubs/braintree/braintree/paypal_here.pyi new file mode 100644 index 000000000000..9c187e69eae8 --- /dev/null +++ b/stubs/braintree/braintree/paypal_here.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class PayPalHere(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/paypal_payment_resource.pyi b/stubs/braintree/braintree/paypal_payment_resource.pyi new file mode 100644 index 000000000000..81b5e5e3d987 --- /dev/null +++ b/stubs/braintree/braintree/paypal_payment_resource.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult + +class PayPalPaymentResource(Resource): + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def update(request) -> SuccessfulResult | ErrorResult: ... + @staticmethod + def update_signature() -> list[Incomplete]: ... diff --git a/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi b/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi new file mode 100644 index 000000000000..10eb5fd462a1 --- /dev/null +++ b/stubs/braintree/braintree/paypal_payment_resource_gateway.pyi @@ -0,0 +1,10 @@ +from braintree.braintree_gateway import BraintreeGateway +from braintree.configuration import Configuration +from braintree.error_result import ErrorResult +from braintree.successful_result import SuccessfulResult + +class PayPalPaymentResourceGateway: + config: Configuration + gateway: BraintreeGateway + def __init__(self, gateway: BraintreeGateway) -> None: ... + def update(self, params) -> SuccessfulResult | ErrorResult: ... diff --git a/stubs/braintree/braintree/plan.pyi b/stubs/braintree/braintree/plan.pyi new file mode 100644 index 000000000000..47de7b28c147 --- /dev/null +++ b/stubs/braintree/braintree/plan.pyi @@ -0,0 +1,20 @@ +from braintree.add_on import AddOn +from braintree.discount import Discount +from braintree.resource import Resource + +class Plan(Resource): + add_ons: list[AddOn] + discounts: list[Discount] + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def all(): ... + @staticmethod + def create(params=None): ... + @staticmethod + def find(subscription_id): ... + @staticmethod + def update(subscription_id, params=None): ... + @staticmethod + def create_signature(): ... + @staticmethod + def update_signature(): ... diff --git a/stubs/braintree/braintree/plan_gateway.pyi b/stubs/braintree/braintree/plan_gateway.pyi new file mode 100644 index 000000000000..8d4416170c5d --- /dev/null +++ b/stubs/braintree/braintree/plan_gateway.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +class PlanGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def all(self): ... + def create(self, params=None): ... + def find(self, plan_id): ... + def update(self, plan_id, params=None): ... diff --git a/stubs/braintree/braintree/processor_response_types.pyi b/stubs/braintree/braintree/processor_response_types.pyi new file mode 100644 index 000000000000..e8a1751cc402 --- /dev/null +++ b/stubs/braintree/braintree/processor_response_types.pyi @@ -0,0 +1,6 @@ +from typing import Final + +class ProcessorResponseTypes: + Approved: Final = "approved" + SoftDeclined: Final = "soft_declined" + HardDeclined: Final = "hard_declined" diff --git a/stubs/braintree/braintree/receiver.pyi b/stubs/braintree/braintree/receiver.pyi new file mode 100644 index 000000000000..8c78f46a560a --- /dev/null +++ b/stubs/braintree/braintree/receiver.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class Receiver(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/resource.pyi b/stubs/braintree/braintree/resource.pyi new file mode 100644 index 000000000000..8f7d9f83e34e --- /dev/null +++ b/stubs/braintree/braintree/resource.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.attribute_getter import AttributeGetter + +text_type = str +raw_type = bytes + +class Resource(AttributeGetter): + @staticmethod + def verify_keys(params, signature) -> None: ... + gateway: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/resource_collection.pyi b/stubs/braintree/braintree/resource_collection.pyi new file mode 100644 index 000000000000..80b32c2f77b3 --- /dev/null +++ b/stubs/braintree/braintree/resource_collection.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +class ResourceCollection: + def __init__(self, query, results, method) -> None: ... + @property + def maximum_size(self): ... + @property + def first(self): ... + @property + def items(self) -> Generator[Incomplete]: ... + @property + def ids(self): ... + def __iter__(self): ... diff --git a/stubs/braintree/braintree/revoked_payment_method_metadata.pyi b/stubs/braintree/braintree/revoked_payment_method_metadata.pyi new file mode 100644 index 000000000000..b1464e75436e --- /dev/null +++ b/stubs/braintree/braintree/revoked_payment_method_metadata.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.resource import Resource + +class RevokedPaymentMethodMetadata(Resource): + revoked_payment_method: Incomplete + customer_id: Incomplete + token: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/risk_data.pyi b/stubs/braintree/braintree/risk_data.pyi new file mode 100644 index 000000000000..cda4f17551a2 --- /dev/null +++ b/stubs/braintree/braintree/risk_data.pyi @@ -0,0 +1,4 @@ +from braintree.attribute_getter import AttributeGetter + +class RiskData(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/samsung_pay_card.pyi b/stubs/braintree/braintree/samsung_pay_card.pyi new file mode 100644 index 000000000000..ef1dad97ebb7 --- /dev/null +++ b/stubs/braintree/braintree/samsung_pay_card.pyi @@ -0,0 +1,12 @@ +from braintree.address import Address +from braintree.resource import Resource +from braintree.subscription import Subscription + +class SamsungPayCard(Resource): + billing_address: Address | None + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... + @property + def expiration_date(self): ... + @property + def masked_number(self): ... diff --git a/stubs/braintree/braintree/search.pyi b/stubs/braintree/braintree/search.pyi new file mode 100644 index 000000000000..8ba8866b11e3 --- /dev/null +++ b/stubs/braintree/braintree/search.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete + +class Search: + class IsNodeBuilder: + name: Incomplete + def __init__(self, name) -> None: ... + def __eq__(self, value): ... + def is_equal(self, value): ... + + class EqualityNodeBuilder(IsNodeBuilder): + def __ne__(self, value): ... + def is_not_equal(self, value): ... + + class KeyValueNodeBuilder: + name: Incomplete + def __init__(self, name) -> None: ... + def __eq__(self, value): ... + def is_equal(self, value): ... + def __ne__(self, value): ... + def is_not_equal(self, value): ... + + class PartialMatchNodeBuilder(EqualityNodeBuilder): + def starts_with(self, value): ... + def ends_with(self, value): ... + + class EndsWithNodeBuilder: + name: Incomplete + def __init__(self, name) -> None: ... + def ends_with(self, value): ... + + class TextNodeBuilder(PartialMatchNodeBuilder): + def contains(self, value): ... + + class Node: + name: Incomplete + dict: Incomplete + def __init__(self, name, dict) -> None: ... + def to_param(self): ... + + class MultipleValueNodeBuilder: + name: Incomplete + whitelist: Incomplete + def __init__(self, name, whitelist=[]) -> None: ... + def in_list(self, *values): ... + def __eq__(self, value): ... + + class MultipleValueOrTextNodeBuilder(TextNodeBuilder, MultipleValueNodeBuilder): + def __init__(self, name, whitelist=[]) -> None: ... + + class RangeNodeBuilder: + name: Incomplete + def __init__(self, name) -> None: ... + def __eq__(self, value): ... + def is_equal(self, value): ... + def __ge__(self, min): ... + def greater_than_or_equal_to(self, min): ... + def __le__(self, max): ... + def less_than_or_equal_to(self, max): ... + def between(self, min, max): ... diff --git a/stubs/braintree/braintree/sender.pyi b/stubs/braintree/braintree/sender.pyi new file mode 100644 index 000000000000..5cd107b52b32 --- /dev/null +++ b/stubs/braintree/braintree/sender.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from braintree.attribute_getter import AttributeGetter + +class Sender(AttributeGetter): + def __init__(self, attributes: dict[str, Any] | None) -> None: ... diff --git a/stubs/braintree/braintree/sepa_direct_debit_account.pyi b/stubs/braintree/braintree/sepa_direct_debit_account.pyi new file mode 100644 index 000000000000..82b46b220f0d --- /dev/null +++ b/stubs/braintree/braintree/sepa_direct_debit_account.pyi @@ -0,0 +1,10 @@ +from braintree.resource import Resource +from braintree.subscription import Subscription + +class SepaDirectDebitAccount(Resource): + @staticmethod + def find(sepa_direct_debit_account_token): ... + @staticmethod + def delete(sepa_direct_debit_account_token): ... + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi b/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi new file mode 100644 index 000000000000..f3a6de9f9a54 --- /dev/null +++ b/stubs/braintree/braintree/sepa_direct_debit_account_gateway.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +class SepaDirectDebitAccountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, sepa_direct_debit_account_token): ... + def delete(self, sepa_direct_debit_account_token): ... diff --git a/stubs/braintree/braintree/settlement_batch_summary.pyi b/stubs/braintree/braintree/settlement_batch_summary.pyi new file mode 100644 index 000000000000..0e48629a28d1 --- /dev/null +++ b/stubs/braintree/braintree/settlement_batch_summary.pyi @@ -0,0 +1,5 @@ +from braintree.resource import Resource + +class SettlementBatchSummary(Resource): + @staticmethod + def generate(settlement_date, group_by_custom_field=None): ... diff --git a/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi b/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi new file mode 100644 index 000000000000..09c324ea0d3e --- /dev/null +++ b/stubs/braintree/braintree/settlement_batch_summary_gateway.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +class SettlementBatchSummaryGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def generate(self, settlement_date, group_by_custom_field=None): ... diff --git a/stubs/braintree/braintree/signature_service.pyi b/stubs/braintree/braintree/signature_service.pyi new file mode 100644 index 000000000000..3fa67bd103e2 --- /dev/null +++ b/stubs/braintree/braintree/signature_service.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +class SignatureService: + private_key: Incomplete + hmac_hash: Incomplete + def __init__(self, private_key, hashfunc=...) -> None: ... + def sign(self, data): ... + def hash(self, data): ... diff --git a/stubs/braintree/braintree/status_event.pyi b/stubs/braintree/braintree/status_event.pyi new file mode 100644 index 000000000000..8f316829d4a6 --- /dev/null +++ b/stubs/braintree/braintree/status_event.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.resource import Resource + +class StatusEvent(Resource): + amount: Decimal + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/sub_merchant.pyi b/stubs/braintree/braintree/sub_merchant.pyi new file mode 100644 index 000000000000..ad790ceae83e --- /dev/null +++ b/stubs/braintree/braintree/sub_merchant.pyi @@ -0,0 +1,4 @@ +from braintree.attribute_getter import AttributeGetter + +class SubMerchant(AttributeGetter): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/subscription.pyi b/stubs/braintree/braintree/subscription.pyi new file mode 100644 index 000000000000..24bb2a09a05c --- /dev/null +++ b/stubs/braintree/braintree/subscription.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from datetime import date +from decimal import Decimal +from typing import Final + +from braintree.add_on import AddOn +from braintree.descriptor import Descriptor +from braintree.discount import Discount +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.subscription_status_event import SubscriptionStatusEvent +from braintree.successful_result import SuccessfulResult +from braintree.transaction import Transaction + +class Subscription(Resource): + class TrialDurationUnit: + Day: Final = "day" + Month: Final = "month" + + class Source: + Api: Final = "api" + ControlPanel: Final = "control_panel" + Recurring: Final = "recurring" + + class Status: + Active: Final = "Active" + Canceled: Final = "Canceled" + Expired: Final = "Expired" + PastDue: Final = "Past Due" + Pending: Final = "Pending" + + @staticmethod + def create(params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def create_signature(): ... + @staticmethod + def find(subscription_id: str) -> Subscription: ... + @staticmethod + def retry_charge(subscription_id, amount=None, submit_for_settlement: bool = False): ... + @staticmethod + def update(subscription_id: str, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def cancel(subscription_id: str) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def search(*query) -> ResourceCollection: ... + @staticmethod + def update_signature(): ... + price: Decimal + balance: Decimal + next_billing_date: date + next_billing_period_amount: Decimal + add_ons: list[AddOn] + descriptor: Descriptor + description: Incomplete + discounts: list[Discount] + status_history: list[SubscriptionStatusEvent] + transactions: list[Transaction] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/subscription_details.pyi b/stubs/braintree/braintree/subscription_details.pyi new file mode 100644 index 000000000000..df2da1daa1a6 --- /dev/null +++ b/stubs/braintree/braintree/subscription_details.pyi @@ -0,0 +1,7 @@ +from datetime import date + +from braintree.attribute_getter import AttributeGetter + +class SubscriptionDetails(AttributeGetter): + billing_period_start_date: date + billing_period_end_date: date diff --git a/stubs/braintree/braintree/subscription_gateway.pyi b/stubs/braintree/braintree/subscription_gateway.pyi new file mode 100644 index 000000000000..44907bce1d97 --- /dev/null +++ b/stubs/braintree/braintree/subscription_gateway.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.subscription import Subscription +from braintree.successful_result import SuccessfulResult + +class SubscriptionGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def cancel(self, subscription_id: str) -> SuccessfulResult | ErrorResult | None: ... + def create(self, params: dict[str, Incomplete] | None = None) -> SuccessfulResult | ErrorResult | None: ... + def find(self, subscription_id: str) -> Subscription: ... + def retry_charge(self, subscription_id, amount=None, submit_for_settlement: bool = False): ... + def search(self, *query) -> ResourceCollection: ... + def update( + self, subscription_id: str, params: dict[str, Incomplete] | None = None + ) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/subscription_search.pyi b/stubs/braintree/braintree/subscription_search.pyi new file mode 100644 index 000000000000..45b03dccf6c8 --- /dev/null +++ b/stubs/braintree/braintree/subscription_search.pyi @@ -0,0 +1,15 @@ +from braintree.search import Search + +class SubscriptionSearch: + billing_cycles_remaining: Search.RangeNodeBuilder + created_at: Search.RangeNodeBuilder + days_past_due: Search.RangeNodeBuilder + id: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + in_trial_period: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + next_billing_date: Search.RangeNodeBuilder + plan_id: Search.MultipleValueOrTextNodeBuilder + price: Search.RangeNodeBuilder + status: Search.MultipleValueNodeBuilder + transaction_id: Search.TextNodeBuilder diff --git a/stubs/braintree/braintree/subscription_status_event.pyi b/stubs/braintree/braintree/subscription_status_event.pyi new file mode 100644 index 000000000000..987f44a788ee --- /dev/null +++ b/stubs/braintree/braintree/subscription_status_event.pyi @@ -0,0 +1,8 @@ +from decimal import Decimal + +from braintree.resource import Resource + +class SubscriptionStatusEvent(Resource): + balance: Decimal + price: Decimal + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/successful_result.pyi b/stubs/braintree/braintree/successful_result.pyi new file mode 100644 index 000000000000..962d23484093 --- /dev/null +++ b/stubs/braintree/braintree/successful_result.pyi @@ -0,0 +1,7 @@ +from typing import Literal + +from braintree.attribute_getter import AttributeGetter + +class SuccessfulResult(AttributeGetter): + @property + def is_success(self) -> Literal[True]: ... diff --git a/stubs/braintree/braintree/test/__init__.pyi b/stubs/braintree/braintree/test/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/braintree/braintree/test/authentication_ids.pyi b/stubs/braintree/braintree/test/authentication_ids.pyi new file mode 100644 index 000000000000..56f4664d370d --- /dev/null +++ b/stubs/braintree/braintree/test/authentication_ids.pyi @@ -0,0 +1,18 @@ +from typing import Final + +class AuthenticationIds: + ThreeDSecureVisaFullAuthentication: Final = "fake-three-d-secure-visa-full-authentication-id" + ThreeDSecureVisaLookupTimeout: Final = "fake-three-d-secure-visa-lookup-timeout-id" + ThreeDSecureVisaFailedSignature: Final = "fake-three-d-secure-visa-failed-signature-id" + ThreeDSecureVisaFailedAuthentication: Final = "fake-three-d-secure-visa-failed-authentication-id" + ThreeDSecureVisaAttemptsNonParticipating: Final[str] + ThreeDSecureVisaNoteEnrolled: Final = "fake-three-d-secure-visa-not-enrolled-id" + ThreeDSecureVisaUnavailable: Final = "fake-three-d-secure-visa-unavailable-id" + ThreeDSecureVisaMPILookupError: Final = "fake-three-d-secure-visa-mpi-lookup-error-id" + ThreeDSecureVisaMPIAuthenticateError: Final = "fake-three-d-secure-visa-mpi-authenticate-error-id" + ThreeDSecureVisaAuthenticationUnavailable: Final[str] + ThreeDSecureVisaBypassedAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulFrictionlessAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulStepUpAuthentication: Final[str] + ThreeDSecureTwoVisaErrorOnLookup: Final = "fake-three-d-secure-two-visa-error-on-lookup-id" + ThreeDSecureTwoVisaTimeoutOnLookup: Final = "fake-three-d-secure-two-visa-timeout-on-lookup-id" diff --git a/stubs/braintree/braintree/test/credit_card_defaults.pyi b/stubs/braintree/braintree/test/credit_card_defaults.pyi new file mode 100644 index 000000000000..74a1cdc4d67d --- /dev/null +++ b/stubs/braintree/braintree/test/credit_card_defaults.pyi @@ -0,0 +1,5 @@ +from typing import Final + +class CreditCardDefaults: + CountryOfIssuance: Final = "USA" + IssuingBank: Final = "NETWORK ONLY" diff --git a/stubs/braintree/braintree/test/credit_card_numbers.pyi b/stubs/braintree/braintree/test/credit_card_numbers.pyi new file mode 100644 index 000000000000..7ddbb912033b --- /dev/null +++ b/stubs/braintree/braintree/test/credit_card_numbers.pyi @@ -0,0 +1,45 @@ +from typing import Final + +class CreditCardNumbers: + class CardTypeIndicators: + Business: Final = "4229989800000003" + Commercial: Final = "4111111111131010" + Consumer: Final = "4229989700000004" + Corporate: Final = "4229989100000000" + DurbinRegulated: Final = "4111161010101010" + Debit: Final = "4117101010101010" + Healthcare: Final = "4111111510101010" + Payroll: Final = "4111111114101010" + Prepaid: Final = "4111111111111210" + PrepaidReloadable: Final = "4229989900000002" + Purchase: Final = "4229989500000006" + IssuingBank: Final = "4111111141010101" + CountryOfIssuance: Final = "4111111111121102" + No: Final = "4111111111310101" + Unknown: Final = "4111111111112101" + + Maestro: Final = "6304000000000000" + MasterCard: Final = "5555555555554444" + MasterCardInternational: Final = "5105105105105100" + Visa: Final = "4012888888881881" + VisaInternational: Final = "4009348888881881" + VisaPrepaid: Final = "4500600000000061" + Discover: Final = "6011111111111117" + Elo: Final = "5066991111111118" + Hiper: Final = "6370950000000005" + Hipercard: Final = "6062820524845321" + Amex: Final = "378734493671000" + + class FailsSandboxVerification: + AmEx: Final = "378734493671000" + Discover: Final = "6011000990139424" + MasterCard: Final = "5105105105105100" + Visa: Final = "4000111111111115" + + class AmexPayWithPoints: + Success: Final = "371260714673002" + IneligibleCard: Final = "378267515471109" + InsufficientPoints: Final = "371544868764018" + + class Disputes: + Chargeback: Final = "4023898493988028" diff --git a/stubs/braintree/braintree/test/merchant_account.pyi b/stubs/braintree/braintree/test/merchant_account.pyi new file mode 100644 index 000000000000..3c0c6fafdf14 --- /dev/null +++ b/stubs/braintree/braintree/test/merchant_account.pyi @@ -0,0 +1,7 @@ +from typing import Final + +Approve: Final = "approve_me" +InsufficientFundsContactUs: Final = "insufficient_funds__contact" +AccountNotAuthorizedContactUs: Final = "account_not_authorized__contact" +BankRejectedUpdateFundingInformation: Final = "bank_rejected__update" +BankRejectedNone: Final = "bank_rejected__none" diff --git a/stubs/braintree/braintree/test/nonces.pyi b/stubs/braintree/braintree/test/nonces.pyi new file mode 100644 index 000000000000..1c85c2864e91 --- /dev/null +++ b/stubs/braintree/braintree/test/nonces.pyi @@ -0,0 +1,88 @@ +from typing import Final + +class Nonces: + AbstractTransactable: Final = "fake-abstract-transactable-nonce" + AmexExpressCheckoutCard: Final = "fake-amex-express-checkout-nonce" + AndroidPayCard: Final = "fake-android-pay-nonce" + AndroidPayCardAmEx: Final = "fake-android-pay-amex-nonce" + AndroidPayCardDiscover: Final = "fake-android-pay-discover-nonce" + AndroidPayCardMasterCard: Final = "fake-android-pay-mastercard-nonce" + AndroidPayCardVisa: Final = "fake-android-pay-visa-nonce" + ApplePayAmEx: Final = "fake-apple-pay-amex-nonce" + ApplePayMasterCard: Final = "fake-apple-pay-mastercard-nonce" + ApplePayMpan: Final = "fake-apple-pay-mpan-nonce" + ApplePayVisa: Final = "fake-apple-pay-visa-nonce" + Consumed: Final = "fake-consumed-nonce" + Europe: Final = "fake-europe-bank-account-nonce" + GatewayRejectedFraud: Final = "fake-gateway-rejected-fraud-nonce" + GatewayRejectedRiskThreshold: Final = "fake-gateway-rejected-risk-thresholds-nonce" + LocalPayment: Final = "fake-local-payment-method-nonce" + LuhnInvalid: Final = "fake-luhn-invalid-nonce" + MasterpassAmEx: Final = "fake-masterpass-amex-nonce" + MasterpassDiscover: Final = "fake-masterpass-discover-nonce" + MasterpassMasterCard: Final = "fake-masterpass-mastercard-nonce" + MasterpassVisa: Final = "fake-masterpass-visa-nonce" + PayPalBillingAgreement: Final = "fake-paypal-billing-agreement-nonce" + PayPalFuturePayment: Final = "fake-paypal-future-nonce" + PayPalFuturePaymentRefreshToken: Final = "fake-paypal-future-refresh-token-nonce" + PayPalOneTimePayment: Final = "fake-paypal-one-time-nonce" + ProcessorDeclinedAmEx: Final = "fake-processor-declined-amex-nonce" + ProcessorDeclinedDiscover: Final = "fake-processor-declined-discover-nonce" + ProcessorDeclinedMasterCard: Final = "fake-processor-declined-mastercard-nonce" + ProcessorDeclinedVisa: Final = "fake-processor-declined-visa-nonce" + ProcessorFailureJCB: Final = "fake-processor-failure-jcb-nonce" + SEPA: Final = "fake-sepa-bank-account-nonce" + MetaCheckoutCard: Final = "fake-meta-checkout-card-nonce" + MetaCheckoutToken: Final = "fake-meta-checkout-token-nonce" + SamsungPayAmex: Final = "tokensam_fake_american_express" + SamsungPayDiscover: Final = "tokensam_fake_american_express" + SamsungPayMasterCard: Final = "tokensam_fake_mastercard" + SamsungPayVisa: Final = "tokensam_fake_visa" + SepaDirectDebit: Final = "fake-sepa-direct-debit-nonce" + ThreeDSecureTwoVisaErrorOnLookup: Final = "fake-three-d-secure-two-visa-error-on-lookup-nonce" + ThreeDSecureTwoVisaSuccessfulFrictionlessAuthentication: Final[str] + ThreeDSecureTwoVisaSuccessfulStepUpAuthentication: Final[str] + ThreeDSecureTwoVisaTimeoutOnLookup: Final[str] + ThreeDSecureVisaAttemptsNonParticipating: Final[str] + ThreeDSecureVisaAuthenticationUnavailable: Final[str] + ThreeDSecureVisaBypassedAuthentication: Final[str] + ThreeDSecureVisaFailedAuthentication: Final[str] + ThreeDSecureVisaFailedSignature: Final = "fake-three-d-secure-visa-failed-signature-nonce" + ThreeDSecureVisaFullAuthentication: Final = "fake-three-d-secure-visa-full-authentication-nonce" + ThreeDSecureVisaLookupTimeout: Final = "fake-three-d-secure-visa-lookup-timeout-nonce" + ThreeDSecureVisaMPIAuthenticateError: Final[str] + ThreeDSecureVisaMPILookupError: Final = "fake-three-d-secure-visa-mpi-lookup-error-nonce" + ThreeDSecureVisaNoteEnrolled: Final = "fake-three-d-secure-visa-not-enrolled-nonce" + ThreeDSecureVisaUnavailable: Final = "fake-three-d-secure-visa-unavailable-nonce" + Transactable: Final = "fake-valid-nonce" + TransactableAmEx: Final = "fake-valid-amex-nonce" + TransactableBusiness: Final = "fake-valid-business-nonce" + TransactableCommercial: Final = "fake-valid-commercial-nonce" + TransactableConsumer: Final = "fake-valid-consumer-nonce" + TransactableCorporate: Final = "fake-valid-corporate-nonce" + TransactableCountryOfIssuanceCAD: Final = "fake-valid-country-of-issuance-cad-nonce" + TransactableCountryOfIssuanceUSA: Final = "fake-valid-country-of-issuance-usa-nonce" + TransactableDebit: Final = "fake-valid-debit-nonce" + TransactableDinersClub: Final = "fake-valid-dinersclub-nonce" + TransactableDiscover: Final = "fake-valid-discover-nonce" + TransactableDurbinRegulated: Final = "fake-valid-durbin-regulated-nonce" + TransactableHealthcare: Final = "fake-valid-healthcare-nonce" + TransactableIssuingBankNetworkOnly: Final = "fake-valid-issuing-bank-network-only-nonce" + TransactableJCB: Final = "fake-valid-jcb-nonce" + TransactableMaestro: Final = "fake-valid-maestro-nonce" + TransactableMasterCard: Final = "fake-valid-mastercard-nonce" + TransactableNoIndicators: Final = "fake-valid-no-indicators-nonce" + TransactablePayroll: Final = "fake-valid-payroll-nonce" + TransactablePinlessDebitVisa: Final = "fake-pinless-debit-visa-nonce" + TransactablePrepaid: Final = "fake-valid-prepaid-nonce" + TransactablePrepaidReloadable: Final = "fake-valid-prepaid-reloadable-nonce" + TransactablePurchase: Final = "fake-valid-purchase-nonce" + TransactableUnknownIndicators: Final = "fake-valid-unknown-indicators-nonce" + TransactableVisa: Final = "fake-valid-visa-nonce" + VenmoAccount: Final = "fake-venmo-account-nonce" + VenmoAccountTokenIssuanceError: Final = "fake-token-issuance-error-venmo-account-nonce" + VisaCheckoutAmEx: Final = "fake-visa-checkout-amex-nonce" + VisaCheckoutDiscover: Final = "fake-visa-checkout-discover-nonce" + VisaCheckoutMasterCard: Final = "fake-visa-checkout-mastercard-nonce" + VisaCheckoutVisa: Final = "fake-visa-checkout-visa-nonce" + UsBankAccount: Final = "fake-us-bank-account-nonce" diff --git a/stubs/braintree/braintree/test/venmo_sdk.pyi b/stubs/braintree/braintree/test/venmo_sdk.pyi new file mode 100644 index 000000000000..5f749a1e8aa9 --- /dev/null +++ b/stubs/braintree/braintree/test/venmo_sdk.pyi @@ -0,0 +1,9 @@ +from typing import Final + +def generate_test_payment_method_code(number): ... + +VisaPaymentMethodCode: Final = "stub-4111111111111111" +InvalidPaymentMethodCode: Final = "stub-invalid-payment-method-code" + +Session: Final = "stub-session" +InvalidSession: Final = "stub-invalid-session" diff --git a/stubs/braintree/braintree/testing_gateway.pyi b/stubs/braintree/braintree/testing_gateway.pyi new file mode 100644 index 000000000000..54727fdffc97 --- /dev/null +++ b/stubs/braintree/braintree/testing_gateway.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +class TestingGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def make_past_due(self, subscription_id, number_of_days_past_due: int = 1) -> None: ... + def settle_transaction(self, transaction_id): ... + def settlement_confirm_transaction(self, transaction_id): ... + def settlement_decline_transaction(self, transaction_id): ... + def settlement_pending_transaction(self, transaction_id): ... + def create_3ds_verification(self, merchant_account_id, params): ... diff --git a/stubs/braintree/braintree/three_d_secure_info.pyi b/stubs/braintree/braintree/three_d_secure_info.pyi new file mode 100644 index 000000000000..466cd4f27ec6 --- /dev/null +++ b/stubs/braintree/braintree/three_d_secure_info.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class ThreeDSecureInfo(AttributeGetter): ... diff --git a/stubs/braintree/braintree/transaction.pyi b/stubs/braintree/braintree/transaction.pyi new file mode 100644 index 000000000000..667c9152d98d --- /dev/null +++ b/stubs/braintree/braintree/transaction.pyi @@ -0,0 +1,196 @@ +from _typeshed import Incomplete +from datetime import datetime +from decimal import Decimal +from typing import Final + +from braintree.add_on import AddOn +from braintree.address import Address +from braintree.amex_express_checkout_card import AmexExpressCheckoutCard +from braintree.android_pay_card import AndroidPayCard +from braintree.apple_pay_card import ApplePayCard +from braintree.authorization_adjustment import AuthorizationAdjustment +from braintree.credit_card import CreditCard +from braintree.customer import Customer +from braintree.descriptor import Descriptor +from braintree.disbursement_detail import DisbursementDetail +from braintree.discount import Discount +from braintree.dispute import Dispute +from braintree.europe_bank_account import EuropeBankAccount +from braintree.facilitated_details import FacilitatedDetails +from braintree.facilitator_details import FacilitatorDetails +from braintree.local_payment import LocalPayment +from braintree.masterpass_card import MasterpassCard +from braintree.meta_checkout_card import MetaCheckoutCard +from braintree.meta_checkout_token import MetaCheckoutToken +from braintree.package_details import PackageDetails +from braintree.payment_facilitator import PaymentFacilitator +from braintree.paypal_account import PayPalAccount +from braintree.paypal_here import PayPalHere +from braintree.resource import Resource +from braintree.resource_collection import ResourceCollection +from braintree.risk_data import RiskData +from braintree.samsung_pay_card import SamsungPayCard +from braintree.sepa_direct_debit_account import SepaDirectDebitAccount +from braintree.status_event import StatusEvent +from braintree.subscription_details import SubscriptionDetails +from braintree.three_d_secure_info import ThreeDSecureInfo +from braintree.transfer import Transfer +from braintree.us_bank_account import UsBankAccount +from braintree.venmo_account import VenmoAccount +from braintree.visa_checkout_card import VisaCheckoutCard + +class Transaction(Resource): + class CreatedUsing: + FullInformation: Final = "full_information" + Token: Final = "token" + + class GatewayRejectionReason: + ApplicationIncomplete: Final = "application_incomplete" + Avs: Final = "avs" + AvsAndCvv: Final = "avs_and_cvv" + Cvv: Final = "cvv" + Duplicate: Final = "duplicate" + ExcessiveRetry: Final = "excessive_retry" + Fraud: Final = "fraud" + RiskThreshold: Final = "risk_threshold" + ThreeDSecure: Final = "three_d_secure" + TokenIssuance: Final = "token_issuance" + + class ReasonCode: + ANY_REASON_CODE: Final = "any_reason_code" + + class Source: + Api: Final = "api" + ControlPanel: Final = "control_panel" + Recurring: Final = "recurring" + + class Status: + AuthorizationExpired: Final = "authorization_expired" + Authorized: Final = "authorized" + Authorizing: Final = "authorizing" + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Settled: Final = "settled" + SettlementConfirmed: Final = "settlement_confirmed" + SettlementDeclined: Final = "settlement_declined" + SettlementFailed: Final = "settlement_failed" + SettlementPending: Final = "settlement_pending" + Settling: Final = "settling" + SubmittedForSettlement: Final = "submitted_for_settlement" + Voided: Final = "voided" + + class Type: + Credit: Final = "credit" + Sale: Final = "sale" + + class IndustryType: + Lodging: Final = "lodging" + TravelAndCruise: Final = "travel_cruise" + TravelAndFlight: Final = "travel_flight" + + class AdditionalCharge: + Restaurant: Final = "restaurant" + GiftShop: Final = "gift_shop" + MiniBar: Final = "mini_bar" + Telephone: Final = "telephone" + Laundry: Final = "laundry" + Other: Final = "other" + + @staticmethod + def adjust_authorization(transaction_id, amount): ... + @staticmethod + def clone_transaction(transaction_id, params): ... + @staticmethod + def credit(params=None): ... + @staticmethod + def find(transaction_id: str) -> Transaction: ... + @staticmethod + def refund(transaction_id, amount_or_options=None): ... + @staticmethod + def sale(params=None): ... + @staticmethod + def search(*query) -> ResourceCollection: ... + @staticmethod + def submit_for_settlement(transaction_id, amount=None, params=None): ... + @staticmethod + def update_details(transaction_id, params=None): ... + @staticmethod + def void(transaction_id, params=None): ... + @staticmethod + def create(params): ... + @staticmethod + def clone_signature(): ... + @staticmethod + def create_signature(): ... + @staticmethod + def submit_for_settlement_signature(): ... + @staticmethod + def submit_for_partial_settlement_signature(): ... + @staticmethod + def package_tracking_signature(): ... + @staticmethod + def package_tracking(transaction_id, params=None): ... + @staticmethod + def update_details_signature(): ... + @staticmethod + def refund_signature(): ... + @staticmethod + def submit_for_partial_settlement(transaction_id, amount, params=None): ... + amount: Decimal + tax_amount: Decimal | None + discount_amount: Decimal | None + shipping_amount: Decimal | None + surcharge_amount: Decimal | None + billing_details: Address + credit_card_details: CreditCard + packages: list[PackageDetails] + paypal_details: PayPalAccount + paypal_here_details: PayPalHere + local_payment_details: LocalPayment + sepa_direct_debit_account_details: SepaDirectDebitAccount + europe_bank_account_details: EuropeBankAccount + us_bank_account: UsBankAccount + apple_pay_details: ApplePayCard + android_pay_card_details: AndroidPayCard + amex_express_checkout_card_details: AmexExpressCheckoutCard + venmo_account_details: VenmoAccount + visa_checkout_card_details: VisaCheckoutCard + masterpass_card_details: MasterpassCard + samsung_pay_card_details: SamsungPayCard + meta_checkout_card_details: MetaCheckoutCard + meta_checkout_token_details: MetaCheckoutToken + sca_exemption_requested: Incomplete + customer_details: Customer + shipping_details: Address + add_ons: list[AddOn] + discounts: list[Discount] + status_history: list[StatusEvent] + subscription_details: SubscriptionDetails + descriptor: Descriptor + disbursement_details: DisbursementDetail + disputes: list[Dispute] + authorization_adjustments: list[AuthorizationAdjustment] + payment_instrument_type: Incomplete + risk_data: RiskData | None + three_d_secure_info: ThreeDSecureInfo | None + facilitated_details: FacilitatedDetails + facilitator_details: FacilitatorDetails + network_transaction_id: Incomplete + payment_facilitator: PaymentFacilitator + transfer: Transfer + partially_authorized: bool + mastercard_transaction_link_id: str | None + subscription_id: str + created_at: datetime + def __init__(self, gateway, attributes) -> None: ... + @property + def vault_billing_address(self): ... + @property + def vault_credit_card(self): ... + @property + def vault_customer(self): ... + @property + def is_disbursed(self) -> bool: ... + @property + def line_items(self): ... diff --git a/stubs/braintree/braintree/transaction_amounts.pyi b/stubs/braintree/braintree/transaction_amounts.pyi new file mode 100644 index 000000000000..6853fa9807ec --- /dev/null +++ b/stubs/braintree/braintree/transaction_amounts.pyi @@ -0,0 +1,8 @@ +from typing import Final + +class TransactionAmounts: + Authorize: Final = "1000.00" + PartiallyAuthorized: Final = "1004.00" + Decline: Final = "2000.00" + HardDecline: Final = "2015.00" + Fail: Final = "3000.00" diff --git a/stubs/braintree/braintree/transaction_details.pyi b/stubs/braintree/braintree/transaction_details.pyi new file mode 100644 index 000000000000..4e9909074d34 --- /dev/null +++ b/stubs/braintree/braintree/transaction_details.pyi @@ -0,0 +1,7 @@ +from decimal import Decimal + +from braintree.attribute_getter import AttributeGetter + +class TransactionDetails(AttributeGetter): + amount: Decimal | None + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/transaction_gateway.pyi b/stubs/braintree/braintree/transaction_gateway.pyi new file mode 100644 index 000000000000..6c86d2e17397 --- /dev/null +++ b/stubs/braintree/braintree/transaction_gateway.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.transaction import Transaction + +class TransactionGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def adjust_authorization(self, transaction_id, amount) -> SuccessfulResult | ErrorResult | None: ... + def clone_transaction(self, transaction_id, params) -> SuccessfulResult | ErrorResult | None: ... + def cancel_release(self, transaction_id) -> SuccessfulResult | ErrorResult | None: ... + def create(self, params) -> SuccessfulResult | ErrorResult | None: ... + def credit(self, params) -> SuccessfulResult | ErrorResult | None: ... + def find(self, transaction_id: str) -> Transaction: ... + def refund(self, transaction_id, amount_or_options=None) -> SuccessfulResult | ErrorResult | None: ... + def sale(self, params) -> SuccessfulResult | ErrorResult | None: ... + def search(self, *query) -> ResourceCollection: ... + def submit_for_settlement(self, transaction_id, amount=None, params=None) -> SuccessfulResult | ErrorResult | None: ... + def update_details(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... + def submit_for_partial_settlement(self, transaction_id, amount, params=None) -> SuccessfulResult | ErrorResult | None: ... + def package_tracking(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... + def void(self, transaction_id, params=None) -> SuccessfulResult | ErrorResult | None: ... diff --git a/stubs/braintree/braintree/transaction_line_item.pyi b/stubs/braintree/braintree/transaction_line_item.pyi new file mode 100644 index 000000000000..7e9fe4ce9446 --- /dev/null +++ b/stubs/braintree/braintree/transaction_line_item.pyi @@ -0,0 +1,12 @@ +from typing import Final + +from braintree.attribute_getter import AttributeGetter + +class TransactionLineItem(AttributeGetter): + class Kind: + Credit: Final = "credit" + Debit: Final = "debit" + + def __init__(self, attributes) -> None: ... + @staticmethod + def find_all(transaction_id): ... diff --git a/stubs/braintree/braintree/transaction_line_item_gateway.pyi b/stubs/braintree/braintree/transaction_line_item_gateway.pyi new file mode 100644 index 000000000000..dcf1e5b87505 --- /dev/null +++ b/stubs/braintree/braintree/transaction_line_item_gateway.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.transaction_line_item import TransactionLineItem + +class TransactionLineItemGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find_all(self, transaction_id: str) -> list[TransactionLineItem]: ... diff --git a/stubs/braintree/braintree/transaction_review.pyi b/stubs/braintree/braintree/transaction_review.pyi new file mode 100644 index 000000000000..bfd6545725bc --- /dev/null +++ b/stubs/braintree/braintree/transaction_review.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class TransactionReview(Resource): + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/transaction_search.pyi b/stubs/braintree/braintree/transaction_search.pyi new file mode 100644 index 000000000000..e0dfa62b4764 --- /dev/null +++ b/stubs/braintree/braintree/transaction_search.pyi @@ -0,0 +1,73 @@ +from braintree.search import Search + +class TransactionSearch: + acquirer_reference_number: Search.TextNodeBuilder + billing_company: Search.TextNodeBuilder + billing_country_name: Search.TextNodeBuilder + billing_extended_address: Search.TextNodeBuilder + billing_first_name: Search.TextNodeBuilder + billing_last_name: Search.TextNodeBuilder + billing_locality: Search.TextNodeBuilder + billing_postal_code: Search.TextNodeBuilder + billing_region: Search.TextNodeBuilder + billing_street_address: Search.TextNodeBuilder + credit_card_cardholder_name: Search.TextNodeBuilder + currency: Search.TextNodeBuilder + customer_company: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_fax: Search.TextNodeBuilder + customer_first_name: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + customer_last_name: Search.TextNodeBuilder + customer_phone: Search.TextNodeBuilder + customer_website: Search.TextNodeBuilder + id: Search.TextNodeBuilder + order_id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + processor_authorization_code: Search.TextNodeBuilder + europe_bank_account_iban: Search.TextNodeBuilder + settlement_batch_id: Search.TextNodeBuilder + shipping_company: Search.TextNodeBuilder + shipping_country_name: Search.TextNodeBuilder + shipping_extended_address: Search.TextNodeBuilder + shipping_first_name: Search.TextNodeBuilder + shipping_last_name: Search.TextNodeBuilder + shipping_locality: Search.TextNodeBuilder + shipping_postal_code: Search.TextNodeBuilder + shipping_region: Search.TextNodeBuilder + shipping_street_address: Search.TextNodeBuilder + paypal_payer_email: Search.TextNodeBuilder + paypal_payment_id: Search.TextNodeBuilder + paypal_authorization_id: Search.TextNodeBuilder + sepa_debit_paypal_v2_order_id: Search.TextNodeBuilder + credit_card_unique_identifier: Search.TextNodeBuilder + store_id: Search.TextNodeBuilder + credit_card_expiration_date: Search.EqualityNodeBuilder + credit_card_number: Search.PartialMatchNodeBuilder + user: Search.MultipleValueNodeBuilder + ids: Search.MultipleValueNodeBuilder + merchant_account_id: Search.MultipleValueNodeBuilder + payment_instrument_type: Search.MultipleValueNodeBuilder + store_ids: Search.MultipleValueNodeBuilder + created_using: Search.MultipleValueNodeBuilder + credit_card_card_type: Search.MultipleValueNodeBuilder + credit_card_customer_location: Search.MultipleValueNodeBuilder + debit_network: Search.MultipleValueNodeBuilder + source: Search.MultipleValueNodeBuilder + status: Search.MultipleValueNodeBuilder + type: Search.MultipleValueNodeBuilder + refund: Search.KeyValueNodeBuilder + amount: Search.RangeNodeBuilder + authorization_expired_at: Search.RangeNodeBuilder + authorized_at: Search.RangeNodeBuilder + created_at: Search.RangeNodeBuilder + disbursement_date: Search.RangeNodeBuilder + dispute_date: Search.RangeNodeBuilder + failed_at: Search.RangeNodeBuilder + gateway_rejected_at: Search.RangeNodeBuilder + processor_declined_at: Search.RangeNodeBuilder + settled_at: Search.RangeNodeBuilder + submitted_for_settlement_at: Search.RangeNodeBuilder + voided_at: Search.RangeNodeBuilder + ach_return_responses_created_at: Search.RangeNodeBuilder + reason_code: Search.MultipleValueNodeBuilder diff --git a/stubs/braintree/braintree/transaction_us_bank_account_request.pyi b/stubs/braintree/braintree/transaction_us_bank_account_request.pyi new file mode 100644 index 000000000000..4f9e2991c728 --- /dev/null +++ b/stubs/braintree/braintree/transaction_us_bank_account_request.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from datetime import datetime +from typing import TypedDict, type_check_only +from typing_extensions import Self + +@type_check_only +class _ParamsDict(TypedDict, total=False): + ach_mandate_text: str + ach_mandate_accepted_at: str + +class TransactionUsBankAccountRequest: + parent: Incomplete + def __init__(self, parent) -> None: ... + def ach_mandate_text(self, ach_mandate_text: str) -> Self: ... + def ach_mandate_accepted_at(self, ach_mandate_accepted_at: str | datetime) -> Self: ... + def done(self): ... + def to_param_dict(self) -> _ParamsDict: ... diff --git a/stubs/braintree/braintree/transfer.pyi b/stubs/braintree/braintree/transfer.pyi new file mode 100644 index 000000000000..ac730e9345dd --- /dev/null +++ b/stubs/braintree/braintree/transfer.pyi @@ -0,0 +1,8 @@ +from braintree.attribute_getter import AttributeGetter +from braintree.receiver import Receiver +from braintree.sender import Sender + +class Transfer(AttributeGetter): + sender: Sender + receiver: Receiver + def __init__(self, attributes) -> None: ... diff --git a/stubs/braintree/braintree/unknown_payment_method.pyi b/stubs/braintree/braintree/unknown_payment_method.pyi new file mode 100644 index 000000000000..9551e3225685 --- /dev/null +++ b/stubs/braintree/braintree/unknown_payment_method.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class UnknownPaymentMethod(Resource): + def image_url(self) -> str: ... diff --git a/stubs/braintree/braintree/us_bank_account.pyi b/stubs/braintree/braintree/us_bank_account.pyi new file mode 100644 index 000000000000..538a965c739d --- /dev/null +++ b/stubs/braintree/braintree/us_bank_account.pyi @@ -0,0 +1,16 @@ +from braintree.ach_mandate import AchMandate +from braintree.error_result import ErrorResult +from braintree.resource import Resource +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account_verification import UsBankAccountVerification + +class UsBankAccount(Resource): + @staticmethod + def find(token: str) -> UsBankAccount | None: ... + @staticmethod + def sale(token: str, transactionRequest) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def signature() -> list[str]: ... + ach_mandate: AchMandate | None + verifications: list[UsBankAccountVerification] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/us_bank_account_gateway.pyi b/stubs/braintree/braintree/us_bank_account_gateway.pyi new file mode 100644 index 000000000000..8e3643b7f868 --- /dev/null +++ b/stubs/braintree/braintree/us_bank_account_gateway.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from braintree.us_bank_account import UsBankAccount + +class UsBankAccountGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def find(self, us_bank_account_token: str) -> UsBankAccount | None: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification.pyi b/stubs/braintree/braintree/us_bank_account_verification.pyi new file mode 100644 index 000000000000..92e90486795c --- /dev/null +++ b/stubs/braintree/braintree/us_bank_account_verification.pyi @@ -0,0 +1,36 @@ +from typing import Final + +from braintree.attribute_getter import AttributeGetter +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account import UsBankAccount + +class UsBankAccountVerification(AttributeGetter): + class Status: + Failed: Final = "failed" + GatewayRejected: Final = "gateway_rejected" + ProcessorDeclined: Final = "processor_declined" + Unrecognized: Final = "unrecognized" + Verified: Final = "verified" + Pending: Final = "pending" + + class VerificationMethod: + NetworkCheck: Final = "network_check" + IndependentCheck: Final = "independent_check" + InstantVerificationAccountValidation: Final = "instant_verification_account_validation" + TokenizedCheck: Final = "tokenized_check" + MicroTransfers: Final = "micro_transfers" + + class VerificationAddOns: + CustomerVerification: Final = "customer_verification" + + us_bank_account: UsBankAccount | None + def __init__(self, gateway, attributes) -> None: ... + @staticmethod + def confirm_micro_transfer_amounts(verification_id: str, amounts) -> SuccessfulResult | ErrorResult | None: ... + @staticmethod + def find(verification_id: str) -> UsBankAccountVerification: ... + @staticmethod + def search(*query) -> ResourceCollection: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi b/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi new file mode 100644 index 000000000000..5522b67d2f3a --- /dev/null +++ b/stubs/braintree/braintree/us_bank_account_verification_gateway.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from braintree.error_result import ErrorResult +from braintree.resource_collection import ResourceCollection +from braintree.successful_result import SuccessfulResult +from braintree.us_bank_account_verification import UsBankAccountVerification + +class UsBankAccountVerificationGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def confirm_micro_transfer_amounts(self, verification_id: str, amounts) -> SuccessfulResult | ErrorResult | None: ... + def find(self, verification_id: str) -> UsBankAccountVerification: ... + def search(self, *query) -> ResourceCollection: ... diff --git a/stubs/braintree/braintree/us_bank_account_verification_search.pyi b/stubs/braintree/braintree/us_bank_account_verification_search.pyi new file mode 100644 index 000000000000..2f8e58831d6c --- /dev/null +++ b/stubs/braintree/braintree/us_bank_account_verification_search.pyi @@ -0,0 +1,15 @@ +from braintree.search import Search + +class UsBankAccountVerificationSearch: + account_holder_name: Search.TextNodeBuilder + customer_email: Search.TextNodeBuilder + customer_id: Search.TextNodeBuilder + id: Search.TextNodeBuilder + payment_method_token: Search.TextNodeBuilder + routing_number: Search.TextNodeBuilder + ids: Search.MultipleValueNodeBuilder + status: Search.MultipleValueNodeBuilder + verification_method: Search.MultipleValueNodeBuilder + created_at: Search.RangeNodeBuilder + account_type: Search.EqualityNodeBuilder + account_number: Search.EndsWithNodeBuilder diff --git a/stubs/braintree/braintree/util/__init__.pyi b/stubs/braintree/braintree/util/__init__.pyi new file mode 100644 index 000000000000..62115e01e518 --- /dev/null +++ b/stubs/braintree/braintree/util/__init__.pyi @@ -0,0 +1,8 @@ +from braintree.util.constants import Constants as Constants +from braintree.util.crypto import Crypto as Crypto +from braintree.util.experimental import Experimental as Experimental +from braintree.util.generator import Generator as Generator +from braintree.util.graphql_client import GraphQLClient as GraphQLClient +from braintree.util.http import Http as Http +from braintree.util.parser import Parser as Parser +from braintree.util.xml_util import XmlUtil as XmlUtil diff --git a/stubs/braintree/braintree/util/constants.pyi b/stubs/braintree/braintree/util/constants.pyi new file mode 100644 index 000000000000..17cdc02f6ba8 --- /dev/null +++ b/stubs/braintree/braintree/util/constants.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete +from typing import Any + +class Constants: + @staticmethod + def get_all_constant_values_from_class(klass: object) -> list[Any]: ... # Any taken from klass.__dict__ + def get_all_enum_values(enum_class) -> list[Incomplete]: ... diff --git a/stubs/braintree/braintree/util/crypto.pyi b/stubs/braintree/braintree/util/crypto.pyi new file mode 100644 index 000000000000..6d0666648f62 --- /dev/null +++ b/stubs/braintree/braintree/util/crypto.pyi @@ -0,0 +1,24 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Literal, overload + +text_type = str + +class Crypto: + @staticmethod + def sha1_hmac_hash(secret_key: str | ReadableBuffer, content: str | ReadableBuffer | None) -> str: ... + @staticmethod + def sha256_hmac_hash(secret_key: str | ReadableBuffer, content: str | ReadableBuffer | None) -> str: ... + + @overload + @staticmethod + def secure_compare(left: None, right: Iterable[str | bytes | bytearray]) -> Literal[False]: ... + @overload + @staticmethod + def secure_compare(left: Iterable[str | bytes | bytearray], right: None) -> Literal[False]: ... + @overload + @staticmethod + def secure_compare(left: None, right: None) -> Literal[False]: ... + @overload + @staticmethod + def secure_compare(left: Iterable[str | bytes | bytearray], right: Iterable[str | bytes | bytearray]) -> bool: ... diff --git a/stubs/braintree/braintree/util/datetime_parser.pyi b/stubs/braintree/braintree/util/datetime_parser.pyi new file mode 100644 index 000000000000..c2341864097a --- /dev/null +++ b/stubs/braintree/braintree/util/datetime_parser.pyi @@ -0,0 +1,3 @@ +from datetime import datetime + +def parse_datetime(timestamp: str) -> datetime: ... diff --git a/stubs/braintree/braintree/util/experimental.pyi b/stubs/braintree/braintree/util/experimental.pyi new file mode 100644 index 000000000000..4b1c1b906de6 --- /dev/null +++ b/stubs/braintree/braintree/util/experimental.pyi @@ -0,0 +1,5 @@ +from typing import TypeVar + +_T = TypeVar("_T") + +def Experimental(cls: _T) -> _T: ... diff --git a/stubs/braintree/braintree/util/generator.pyi b/stubs/braintree/braintree/util/generator.pyi new file mode 100644 index 000000000000..03e10a43fede --- /dev/null +++ b/stubs/braintree/braintree/util/generator.pyi @@ -0,0 +1,27 @@ +import datetime +import decimal +from collections.abc import Iterable, Mapping +from typing import TypeAlias + +integer_types = int +text_type = str +binary_type = bytes + +_XMLValue: TypeAlias = ( + str + | bytes + | int + | bool + | decimal.Decimal + | Iterable[_XMLValue] + | Mapping[str, _XMLValue] + | datetime.datetime + | datetime.date + | None +) +_XML: TypeAlias = Mapping[str, _XMLValue] + +class Generator: + dict: _XML + def __init__(self, dict: _XML) -> None: ... + def generate(self) -> str: ... diff --git a/stubs/braintree/braintree/util/graphql_client.pyi b/stubs/braintree/braintree/util/graphql_client.pyi new file mode 100644 index 000000000000..60792398addd --- /dev/null +++ b/stubs/braintree/braintree/util/graphql_client.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import TypedDict, type_check_only + +from braintree.configuration import Configuration +from braintree.environment import Environment +from braintree.util.http import Http + +@type_check_only +class _Extension(TypedDict): + errorClass: Incomplete + legacyCode: int | None + +@type_check_only +class _Error(TypedDict): + attribute: str | None + code: int | None + message: str | None + extensions: _Extension | None + +@type_check_only +class _ValidationErrors(TypedDict): + errors: Iterable[_Error] + +@type_check_only +class _Response(TypedDict): + errors: Iterable[_Error] | None + +class GraphQLClient(Http): + @staticmethod + def raise_exception_for_graphql_error(response: _Response) -> None: ... + graphql_headers: dict[str, str] + def __init__(self, config: Configuration | None = None, environment: Environment | None = None) -> None: ... + def query(self, definition, variables=None, operation_name=None): ... + @staticmethod + def get_validation_errors(response) -> _ValidationErrors | None: ... + @staticmethod + def get_validation_error_code(error: _Error) -> int | None: ... diff --git a/stubs/braintree/braintree/util/http.pyi b/stubs/braintree/braintree/util/http.pyi new file mode 100644 index 000000000000..e2bda12df16c --- /dev/null +++ b/stubs/braintree/braintree/util/http.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.configuration import Configuration +from braintree.environment import Environment + +class Http: + class ContentType: + Xml: Final = "application/xml" + Multipart: Final = "multipart/form-data" + Json: Final = "application/json" + + @staticmethod + def is_error_status(status: int) -> bool: ... + @staticmethod + def raise_exception_from_status(status: int, message: str | None = None) -> None: ... + config: Configuration + environment: Environment + def __init__(self, config: Configuration, environment: Environment | None = None) -> None: ... + def close(self) -> None: ... + def post(self, path: str, params: dict[str, Incomplete] | None = None): ... + def delete(self, path: str): ... + def get(self, path: str): ... + def put(self, path: str, params: dict[str, Incomplete] | None = None): ... + def post_multipart(self, path: str, files, params: dict[str, Incomplete] | None = None): ... + def http_do( + self, http_verb: str, path: str, headers: dict[str, Incomplete], request_body: str | tuple[str, Incomplete] | None + ) -> list[int | str]: ... + def handle_exception(self, exception: IOError) -> None: ... diff --git a/stubs/braintree/braintree/util/parser.pyi b/stubs/braintree/braintree/util/parser.pyi new file mode 100644 index 000000000000..3798ec84dd65 --- /dev/null +++ b/stubs/braintree/braintree/util/parser.pyi @@ -0,0 +1,10 @@ +from xml.dom.minidom import Document + +from .generator import _XML + +binary_type = bytes + +class Parser: + doc: Document + def __init__(self, xml: str | bytes) -> None: ... + def parse(self) -> _XML: ... diff --git a/stubs/braintree/braintree/util/xml_util.pyi b/stubs/braintree/braintree/util/xml_util.pyi new file mode 100644 index 000000000000..eb340ea8c570 --- /dev/null +++ b/stubs/braintree/braintree/util/xml_util.pyi @@ -0,0 +1,7 @@ +from .generator import _XML + +class XmlUtil: + @staticmethod + def xml_from_dict(dict: _XML) -> str: ... + @staticmethod + def dict_from_xml(xml: str | bytes) -> _XML: ... diff --git a/stubs/braintree/braintree/validation_error.pyi b/stubs/braintree/braintree/validation_error.pyi new file mode 100644 index 000000000000..19b726ae1c8f --- /dev/null +++ b/stubs/braintree/braintree/validation_error.pyi @@ -0,0 +1,3 @@ +from braintree.attribute_getter import AttributeGetter + +class ValidationError(AttributeGetter): ... diff --git a/stubs/braintree/braintree/validation_error_collection.pyi b/stubs/braintree/braintree/validation_error_collection.pyi new file mode 100644 index 000000000000..d0d677c5c3f8 --- /dev/null +++ b/stubs/braintree/braintree/validation_error_collection.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from typing_extensions import Self + +from braintree.validation_error import ValidationError + +class ValidationErrorCollection: + data: dict[str, Incomplete] + def __init__(self, data: dict[str, Incomplete] | None = None) -> None: ... + @property + def deep_errors(self) -> list[ValidationError]: ... + def for_index(self, index: int | str) -> Self: ... + def for_object(self, nested_key: str) -> Self: ... + def on(self, attribute: str) -> list[ValidationError]: ... + @property + def deep_size(self) -> int: ... + @property + def errors(self) -> list[ValidationError]: ... + @property + def size(self) -> int: ... + def __getitem__(self, index: int) -> ValidationError: ... + def __len__(self) -> int: ... diff --git a/stubs/braintree/braintree/venmo_account.pyi b/stubs/braintree/braintree/venmo_account.pyi new file mode 100644 index 000000000000..71e2a37dc612 --- /dev/null +++ b/stubs/braintree/braintree/venmo_account.pyi @@ -0,0 +1,6 @@ +from braintree.resource import Resource +from braintree.subscription import Subscription + +class VenmoAccount(Resource): + subscriptions: list[Subscription] + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/venmo_profile_data.pyi b/stubs/braintree/braintree/venmo_profile_data.pyi new file mode 100644 index 000000000000..fd6dd4d8fca0 --- /dev/null +++ b/stubs/braintree/braintree/venmo_profile_data.pyi @@ -0,0 +1,4 @@ +from braintree.resource import Resource + +class VenmoProfileData(Resource): + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/version.pyi b/stubs/braintree/braintree/version.pyi new file mode 100644 index 000000000000..5fac495d89ce --- /dev/null +++ b/stubs/braintree/braintree/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +Version: Final[str] diff --git a/stubs/braintree/braintree/visa_checkout_card.pyi b/stubs/braintree/braintree/visa_checkout_card.pyi new file mode 100644 index 000000000000..9909b514e95e --- /dev/null +++ b/stubs/braintree/braintree/visa_checkout_card.pyi @@ -0,0 +1,17 @@ +from typing_extensions import deprecated + +from braintree.address import Address +from braintree.credit_card_verification import CreditCardVerification +from braintree.resource import Resource +from braintree.subscription import Subscription + +@deprecated("Visa Checkout is no longer supported for creating new transactions.") +class VisaCheckoutCard(Resource): + billing_address: Address | None + subscriptions: list[Subscription] + verification: CreditCardVerification + def __init__(self, gateway, attributes): ... + @property + def expiration_date(self) -> str: ... + @property + def masked_number(self) -> str: ... diff --git a/stubs/braintree/braintree/webhook_notification.pyi b/stubs/braintree/braintree/webhook_notification.pyi new file mode 100644 index 000000000000..06e38fef592a --- /dev/null +++ b/stubs/braintree/braintree/webhook_notification.pyi @@ -0,0 +1,94 @@ +from _typeshed import Incomplete +from typing import Final + +from braintree.account_updater_daily_report import AccountUpdaterDailyReport +from braintree.connected_merchant_paypal_status_changed import ConnectedMerchantPayPalStatusChanged +from braintree.connected_merchant_status_transitioned import ConnectedMerchantStatusTransitioned +from braintree.disbursement import Disbursement +from braintree.dispute import Dispute +from braintree.granted_payment_instrument_update import GrantedPaymentInstrumentUpdate +from braintree.local_payment_completed import LocalPaymentCompleted +from braintree.local_payment_expired import LocalPaymentExpired +from braintree.local_payment_funded import LocalPaymentFunded +from braintree.local_payment_reversed import LocalPaymentReversed +from braintree.merchant_account import MerchantAccount +from braintree.oauth_access_revocation import OAuthAccessRevocation +from braintree.partner_merchant import PartnerMerchant +from braintree.payment_method_customer_data_updated_metadata import PaymentMethodCustomerDataUpdatedMetadata +from braintree.resource import Resource +from braintree.revoked_payment_method_metadata import RevokedPaymentMethodMetadata +from braintree.subscription import Subscription +from braintree.transaction import Transaction +from braintree.transaction_review import TransactionReview +from braintree.validation_error_collection import ValidationErrorCollection + +class WebhookNotification(Resource): + class Kind: + AccountUpdaterDailyReport: Final = "account_updater_daily_report" + Check: Final = "check" + ConnectedMerchantPayPalStatusChanged: Final = "connected_merchant_paypal_status_changed" + ConnectedMerchantStatusTransitioned: Final = "connected_merchant_status_transitioned" + Disbursement: Final = "disbursement" + DisbursementException: Final = "disbursement_exception" + DisputeAccepted: Final = "dispute_accepted" + DisputeAutoAccepted: Final = "dispute_auto_accepted" + DisputeDisputed: Final = "dispute_disputed" + DisputeExpired: Final = "dispute_expired" + DisputeLost: Final = "dispute_lost" + DisputeOpened: Final = "dispute_opened" + DisputeUnderReview: Final = "dispute_under_review" + DisputeWon: Final = "dispute_won" + GrantedPaymentMethodRevoked: Final = "granted_payment_method_revoked" + GrantorUpdatedGrantedPaymentMethod: Final = "grantor_updated_granted_payment_method" + LocalPaymentCompleted: Final = "local_payment_completed" + LocalPaymentExpired: Final = "local_payment_expired" + LocalPaymentFunded: Final = "local_payment_funded" + LocalPaymentReversed: Final = "local_payment_reversed" + OAuthAccessRevoked: Final = "oauth_access_revoked" + PartnerMerchantConnected: Final = "partner_merchant_connected" + PartnerMerchantDeclined: Final = "partner_merchant_declined" + PartnerMerchantDisconnected: Final = "partner_merchant_disconnected" + PaymentMethodCustomerDataUpdated: Final = "payment_method_customer_data_updated" + PaymentMethodRevokedByCustomer: Final = "payment_method_revoked_by_customer" + RecipientUpdatedGrantedPaymentMethod: Final = "recipient_updated_granted_payment_method" + RefundFailed: Final = "refund_failed" + SubscriptionBillingSkipped: Final = "subscription_billing_skipped" + SubscriptionCanceled: Final = "subscription_canceled" + SubscriptionChargedSuccessfully: Final = "subscription_charged_successfully" + SubscriptionChargedUnsuccessfully: Final = "subscription_charged_unsuccessfully" + SubscriptionExpired: Final = "subscription_expired" + SubscriptionTrialEnded: Final = "subscription_trial_ended" + SubscriptionWentActive: Final = "subscription_went_active" + SubscriptionWentPastDue: Final = "subscription_went_past_due" + TransactionDisbursed: Final = "transaction_disbursed" + TransactionRetried: Final = "transaction_retried" + TransactionReviewed: Final = "transaction_reviewed" + TransactionSettled: Final = "transaction_settled" + TransactionSettlementDeclined: Final = "transaction_settlement_declined" + + @staticmethod + def parse(signature: str, payload: str) -> WebhookNotification: ... + @staticmethod + def verify(challenge: str) -> str: ... + source_merchant_id: Incomplete + subscription: Subscription + merchant_account: MerchantAccount + transaction: Transaction + transaction_review: TransactionReview + connected_merchant_status_transitioned: ConnectedMerchantStatusTransitioned + connected_merchant_paypal_status_changed: ConnectedMerchantPayPalStatusChanged + partner_merchant: PartnerMerchant + oauth_access_revocation: OAuthAccessRevocation + disbursement: Disbursement + dispute: Dispute + account_updater_daily_report: AccountUpdaterDailyReport + granted_payment_instrument_update: GrantedPaymentInstrumentUpdate + revoked_payment_method_metadata: RevokedPaymentMethodMetadata + local_payment_completed: LocalPaymentCompleted + local_payment_expired: LocalPaymentExpired + local_payment_funded: LocalPaymentFunded + local_payment_reversed: LocalPaymentReversed + payment_method_customer_data_updated_metadata: PaymentMethodCustomerDataUpdatedMetadata + errors: ValidationErrorCollection + message: Incomplete + def __init__(self, gateway, attributes) -> None: ... diff --git a/stubs/braintree/braintree/webhook_notification_gateway.pyi b/stubs/braintree/braintree/webhook_notification_gateway.pyi new file mode 100644 index 000000000000..671fde3deab9 --- /dev/null +++ b/stubs/braintree/braintree/webhook_notification_gateway.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from braintree.webhook_notification import WebhookNotification + +text_type = str + +class WebhookNotificationGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def parse(self, signature: str, payload: str) -> WebhookNotification: ... + def verify(self, challenge: str) -> str: ... diff --git a/stubs/braintree/braintree/webhook_testing.pyi b/stubs/braintree/braintree/webhook_testing.pyi new file mode 100644 index 000000000000..d47691caa553 --- /dev/null +++ b/stubs/braintree/braintree/webhook_testing.pyi @@ -0,0 +1,3 @@ +class WebhookTesting: + @staticmethod + def sample_notification(kind: str, id: str, source_merchant_id: str | None = None) -> dict[str, str | bytes]: ... diff --git a/stubs/braintree/braintree/webhook_testing_gateway.pyi b/stubs/braintree/braintree/webhook_testing_gateway.pyi new file mode 100644 index 000000000000..8bb417416bd8 --- /dev/null +++ b/stubs/braintree/braintree/webhook_testing_gateway.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +class WebhookTestingGateway: + gateway: Incomplete + config: Incomplete + def __init__(self, gateway) -> None: ... + def sample_notification(self, kind: str, id: str, source_merchant_id: str | None = None) -> dict[str, str | bytes]: ... diff --git a/stubs/cachetools/@tests/stubtest_allowlist.txt b/stubs/cachetools/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a0bcfbfe73bc --- /dev/null +++ b/stubs/cachetools/@tests/stubtest_allowlist.txt @@ -0,0 +1,21 @@ +cachetools.Cache.get + +# stubs omit defaulted arguments that are meant to be optimizations, not provided by user +cachetools.FIFOCache.__delitem__ +cachetools.FIFOCache.__setitem__ +cachetools.LFUCache.__delitem__ +cachetools.LFUCache.__getitem__ +cachetools.LFUCache.__setitem__ +cachetools.LRUCache.__delitem__ +cachetools.LRUCache.__getitem__ +cachetools.LRUCache.__setitem__ +cachetools.RRCache.__delitem__ +cachetools.RRCache.__setitem__ +cachetools.TLRUCache.__delitem__ +cachetools.TLRUCache.__getitem__ +cachetools.TLRUCache.__setitem__ +cachetools.TTLCache.__delitem__ +cachetools.TTLCache.__getitem__ +cachetools.TTLCache.__setitem__ +cachetools._TimedCache.__len__ +cachetools._TimedCache.__repr__ diff --git a/stubs/cachetools/@tests/test_cases/check_cachetools.py b/stubs/cachetools/@tests/test_cases/check_cachetools.py new file mode 100644 index 000000000000..cd890c76a209 --- /dev/null +++ b/stubs/cachetools/@tests/test_cases/check_cachetools.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from collections.abc import Hashable +from typing import Any +from typing_extensions import assert_type + +from cachetools import LRUCache, cached, keys as cachekeys +from cachetools.func import fifo_cache, lfu_cache, lru_cache, rr_cache, ttl_cache + +# Tests for cachetools.cached + +# Explicitly parameterize the cache to avoid Unknown types +cache_inst: LRUCache[int, int] = LRUCache(maxsize=128) + + +@cached(cache_inst) +def check_cached(x: int) -> int: + return x * 2 + + +assert_type(check_cached(3), int) +# Methods cache_info/cache_clear are only present when info=True; do not access them here. + + +@cached(cache_inst, info=True) +def check_cached_with_info(x: int) -> int: + return x + 1 + + +assert_type(check_cached_with_info(4), int) +assert_type(check_cached_with_info.cache_info().misses, int) +check_cached_with_info.cache_clear() + + +# Tests for cachetools.func decorators + + +@lru_cache +def lru_noparens(x: int) -> int: + return x * 2 + + +@lru_cache(maxsize=32) +def lru_with_maxsize(x: int) -> int: + return x * 3 + + +assert_type(lru_noparens(3), int) +assert_type(lru_with_maxsize(3), int) +assert_type(lru_noparens.cache_info().hits, int) +assert_type(lru_with_maxsize.cache_info().misses, int) +assert_type(lru_with_maxsize.cache_parameters(), dict[str, Any]) +lru_with_maxsize.cache_clear() + + +@fifo_cache +def fifo_func(x: int) -> int: + return x + + +@lfu_cache +def lfu_func(x: int) -> int: + return x + + +@rr_cache +def rr_func(x: int) -> int: + return x + + +@ttl_cache +def ttl_func(x: int) -> int: + return x + + +assert_type(fifo_func(1), int) +assert_type(lfu_func(1), int) +assert_type(rr_func(1), int) +assert_type(ttl_func(1), int) +assert_type(fifo_func.cache_info().currsize, float) +assert_type(lfu_func.cache_parameters(), dict[str, Any]) + + +# Tests for cachetools.keys + +k1 = cachekeys.hashkey(1, "a") +assert_type(k1, tuple[Hashable, ...]) + + +class C: + def method(self, a: int) -> int: + return a + + +inst = C() + +k2 = cachekeys.methodkey(inst, 5) +assert_type(k2, tuple[Hashable, ...]) + +k3 = cachekeys.typedkey(1, "x") +assert_type(k3, tuple[Hashable, ...]) + +k4 = cachekeys.typedmethodkey(inst, 2) +assert_type(k4, tuple[Hashable, ...]) diff --git a/stubs/cachetools/METADATA.toml b/stubs/cachetools/METADATA.toml new file mode 100644 index 000000000000..1099004a4a54 --- /dev/null +++ b/stubs/cachetools/METADATA.toml @@ -0,0 +1,3 @@ +version = "7.0.*" +upstream-repository = "https://github.com/tkem/cachetools" +obsolete-since = {version = "7.1.0", date = "2026-05-01"} diff --git a/stubs/cachetools/cachetools/__init__.pyi b/stubs/cachetools/cachetools/__init__.pyi new file mode 100644 index 000000000000..add55e47a10d --- /dev/null +++ b/stubs/cachetools/cachetools/__init__.pyi @@ -0,0 +1,183 @@ +import random +from collections.abc import Callable, Iterator, MutableMapping, Sequence +from contextlib import AbstractContextManager +from typing import Any, Final, Generic, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only + +__all__: Final = ("Cache", "FIFOCache", "LFUCache", "LRUCache", "RRCache", "TLRUCache", "TTLCache", "cached", "cachedmethod") +__version__: str + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_TT = TypeVar("_TT", default=float) +_T = TypeVar("_T") +_R = TypeVar("_R") +_KT2 = TypeVar("_KT2") +_VT2 = TypeVar("_VT2") + +class Cache(MutableMapping[_KT, _VT]): + def __init__(self, maxsize: float, getsizeof: Callable[[_VT], float] | None = None) -> None: ... + def __getitem__(self, key: _KT) -> _VT: ... + def __setitem__(self, key: _KT, value: _VT) -> None: ... + def __delitem__(self, key: _KT) -> None: ... + def __missing__(self, key: _KT) -> _VT: ... + def __iter__(self) -> Iterator[_KT]: ... + def __len__(self) -> int: ... + + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT | _T) -> _VT | _T: ... + + def setdefault(self, key: _KT, default: _VT | None = None) -> _VT: ... + @property + def maxsize(self) -> float: ... + @property + def currsize(self) -> float: ... + @staticmethod + def getsizeof(value: _VT) -> float: ... + +class FIFOCache(Cache[_KT, _VT]): ... +class LFUCache(Cache[_KT, _VT]): ... +class LRUCache(Cache[_KT, _VT]): ... + +class RRCache(Cache[_KT, _VT]): + def __init__( + self, + maxsize: float, + choice: Callable[[Sequence[_KT]], _KT] = random.choice, + getsizeof: Callable[[_VT], float] | None = None, + ) -> None: ... + @property + def choice(self) -> Callable[[Sequence[_KT]], _KT]: ... + +class _TimedCache(Cache[_KT, _VT], Generic[_KT, _VT, _TT]): + def __init__(self, maxsize: float, timer: Callable[[], _TT], getsizeof: Callable[[_VT], float] | None = None) -> None: ... + + class _Timer(AbstractContextManager[_T]): + def __init__(self, timer: Callable[[], _T]) -> None: ... + def __call__(self) -> _T: ... + def __enter__(self) -> _T: ... + def __exit__(self, *exc: object) -> None: ... + def __getattr__(self, name: str) -> Any: ... + + @property + def timer(self) -> _Timer[_TT]: ... + +class TTLCache(_TimedCache[_KT, _VT, _TT]): + @overload + def __init__( + self: TTLCache[_KT2, _VT2, float], maxsize: float, ttl: float, *, getsizeof: Callable[[_VT2], float] | None = None + ) -> None: ... + @overload + def __init__( + self, + maxsize: float, + ttl: Any, # FIXME: must be "addable" to _TT + timer: Callable[[], _TT], + getsizeof: Callable[[_VT], float] | None = None, + ) -> None: ... + + @property + def ttl(self) -> Any: ... + def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... + +class TLRUCache(_TimedCache[_KT, _VT, _TT]): + @overload + def __init__( + self: TLRUCache[_KT2, _VT2, float], + maxsize: float, + ttu: Callable[[_KT2, _VT2, float], float], + *, + getsizeof: Callable[[_VT2], float] | None = None, + ) -> None: ... + @overload + def __init__( + self, + maxsize: float, + ttu: Callable[[_KT, _VT, _TT], _TT], + timer: Callable[[], _TT], + getsizeof: Callable[[_VT], float] | None = None, + ) -> None: ... + + @property + def ttu(self) -> Callable[[_KT, _VT, _TT], _TT]: ... + def expire(self, time: _TT | None = None) -> list[tuple[_KT, _VT]]: ... + +class _CacheInfo(NamedTuple): + hits: int + misses: int + maxsize: float | None + currsize: float + +@type_check_only +class _AbstractCondition(AbstractContextManager[Any], Protocol): + def wait(self, timeout: float | None = None) -> bool: ... + def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: ... + def notify(self, n: int = 1) -> None: ... + def notify_all(self) -> None: ... + +@type_check_only +class _cached_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + cache: MutableMapping[Any, Any] | None + cache_key: Callable[..., Any] = ... + cache_lock: AbstractContextManager[Any] | None = None + cache_condition: _AbstractCondition | None = None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_clear(self) -> None: ... + +@type_check_only +class _cached_wrapper_info(_cached_wrapper[_R]): + def cache_info(self) -> _CacheInfo: ... + +@overload +def cached( + cache: MutableMapping[_KT, Any] | None, + key: Callable[..., _KT] = ..., + lock: AbstractContextManager[Any] | None = None, + condition: _AbstractCondition | None = None, + info: Literal[True] = ..., +) -> Callable[[Callable[..., _R]], _cached_wrapper_info[_R]]: ... +@overload +def cached( + cache: MutableMapping[_KT, Any] | None, + key: Callable[..., _KT] = ..., + lock: AbstractContextManager[Any] | None = None, + condition: _AbstractCondition | None = None, + info: Literal[False] = ..., +) -> Callable[[Callable[..., _R]], _cached_wrapper[_R]]: ... + +@type_check_only +class _cachedmethod_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + cache: MutableMapping[Any, Any] | None + cache_key: Callable[..., Any] = ... + cache_lock: AbstractContextManager[Any] | None = None + cache_condition: _AbstractCondition | None = None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_clear(self) -> None: ... + +@type_check_only +class _cachedmethod_wrapper_info(_cachedmethod_wrapper[_R]): + def cache_info(self) -> _CacheInfo: ... + +@overload +def cachedmethod( + cache: Callable[[Any], MutableMapping[_KT, Any]], + key: Callable[..., _KT] = ..., + lock: Callable[[Any], AbstractContextManager[Any]] | None = None, + condition: Callable[[Any], _AbstractCondition] | None = None, + info: Literal[True] = ..., +) -> Callable[[Callable[..., _R]], _cachedmethod_wrapper_info[_R]]: ... +@overload +def cachedmethod( + cache: Callable[[Any], MutableMapping[_KT, Any]], + key: Callable[..., _KT] = ..., + lock: Callable[[Any], AbstractContextManager[Any]] | None = None, + condition: Callable[[Any], _AbstractCondition] | None = None, + info: Literal[False] = ..., +) -> Callable[[Callable[..., _R]], _cachedmethod_wrapper[_R]]: ... diff --git a/stubs/cachetools/cachetools/func.pyi b/stubs/cachetools/cachetools/func.pyi new file mode 100644 index 000000000000..974dde3da37d --- /dev/null +++ b/stubs/cachetools/cachetools/func.pyi @@ -0,0 +1,54 @@ +from collections.abc import Callable, Sequence +from typing import Any, Final, Generic, TypeVar, overload, type_check_only + +from . import _CacheInfo + +__all__: Final = ("fifo_cache", "lfu_cache", "lru_cache", "rr_cache", "ttl_cache") + +_T = TypeVar("_T") +_R = TypeVar("_R") + +@type_check_only +class _cachetools_cache_wrapper(Generic[_R]): + __wrapped__: Callable[..., _R] + __name__: str + __doc__: str | None + def __call__(self, /, *args: Any, **kwargs: Any) -> _R: ... + def cache_info(self) -> _CacheInfo: ... + def cache_clear(self) -> None: ... + def cache_parameters(self) -> dict[str, Any]: ... + +@overload +def fifo_cache( + maxsize: int | None = 128, typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def fifo_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def lfu_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def lfu_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def lru_cache(maxsize: Callable[..., _R], typed: bool = False) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def rr_cache( + maxsize: int | None = 128, choice: Callable[[Sequence[_T]], _T] = ..., typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def rr_cache( + maxsize: Callable[..., _R], choice: Callable[[Sequence[_T]], _T] = ..., typed: bool = False +) -> _cachetools_cache_wrapper[_R]: ... + +@overload +def ttl_cache( + maxsize: int | None = 128, ttl: Any = 600, timer: Callable[[], _T] = ..., typed: bool = False +) -> Callable[[Callable[..., _R]], _cachetools_cache_wrapper[_R]]: ... +@overload +def ttl_cache( + maxsize: Callable[..., _R], ttl: Any = 600, timer: Callable[[], _T] = ..., typed: bool = False +) -> _cachetools_cache_wrapper[_R]: ... diff --git a/stubs/cachetools/cachetools/keys.pyi b/stubs/cachetools/cachetools/keys.pyi new file mode 100644 index 000000000000..feccf6f9bcea --- /dev/null +++ b/stubs/cachetools/cachetools/keys.pyi @@ -0,0 +1,10 @@ +from _typeshed import Unused +from collections.abc import Hashable +from typing import Final + +__all__: Final = ("hashkey", "methodkey", "typedkey", "typedmethodkey") + +def hashkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def methodkey(self: Unused, /, *args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def typedkey(*args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... +def typedmethodkey(self: Unused, /, *args: Hashable, **kwargs: Hashable) -> tuple[Hashable, ...]: ... diff --git a/stubs/capturer/@tests/stubtest_allowlist.txt b/stubs/capturer/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6f3cc357f2f6 --- /dev/null +++ b/stubs/capturer/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Tests should not be part of the stubs +capturer.tests.* diff --git a/stubs/capturer/METADATA.toml b/stubs/capturer/METADATA.toml new file mode 100644 index 000000000000..a64fd3f58135 --- /dev/null +++ b/stubs/capturer/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.0.*" +upstream-repository = "https://github.com/xolox/python-capturer" diff --git a/stubs/capturer/capturer.pyi b/stubs/capturer/capturer.pyi new file mode 100644 index 000000000000..0bd324a760ea --- /dev/null +++ b/stubs/capturer/capturer.pyi @@ -0,0 +1,122 @@ +from _typeshed import FileDescriptorOrPath, SupportsWrite +from collections.abc import Callable +from io import BufferedReader +from multiprocessing import Process +from multiprocessing.queues import Queue +from multiprocessing.synchronize import Event +from signal import Signals +from types import FrameType, TracebackType +from typing import IO, Any +from typing_extensions import Never, Self + +__version__: str +aliases: dict[str, Any] +DEFAULT_TEXT_ENCODING: str +GRACEFUL_SHUTDOWN_SIGNAL: Signals +TERMINATION_DELAY: float +PARTIAL_DEFAULT: bool +STDOUT_FD: int +STDERR_FD: int + +def enable_old_api() -> None: ... +def create_proxy_method(name: str) -> Callable[..., Any]: ... + +class MultiProcessHelper: + processes: list[Process] + def __init__(self) -> None: ... + def start_child(self, target: Callable[[Event], Any]) -> None: ... + def stop_children(self) -> None: ... + def wait_for_children(self) -> None: ... + def enable_graceful_shutdown(self) -> None: ... + def raise_shutdown_request(self, signum: int, frame: FrameType | None) -> Never: ... + +class CaptureOutput(MultiProcessHelper): + chunk_size: int + encoding: str + merged: bool + relay: bool + termination_delay: float + pseudo_terminals: list[PseudoTerminal] + streams: list[tuple[int, Stream]] + stdout_stream: Stream + stderr_stream: Stream + output: PseudoTerminal + output_queue: Queue[tuple[Any, bytes]] + stdout: PseudoTerminal + stderr: PseudoTerminal + def __init__( + self, merged: bool = True, encoding: str = ..., termination_delay: float = ..., chunk_size: int = 1024, relay: bool = True + ) -> None: ... + def initialize_stream(self, file_obj: IO[str], expected_fd: int) -> Stream: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> bool | None: ... + @property + def is_capturing(self) -> bool: ... + def start_capture(self) -> None: ... + def finish_capture(self) -> None: ... + def allocate_pty( + self, relay_fd: int | None = None, output_queue: Queue[tuple[Any, bytes]] | None = None, queue_token: Any | None = None + ) -> PseudoTerminal: ... + def merge_loop(self, started_event: Event) -> None: ... + def get_handle(self, partial: bool = ...) -> BufferedReader: ... + def get_bytes(self, partial: bool = ...) -> bytes: ... + def get_lines(self, interpreted: bool = True, partial: bool = ...) -> list[str]: ... + def get_text(self, interpreted: bool = ..., partial: bool = ...) -> str: ... + def save_to_handle(self, handle: SupportsWrite[bytes], partial: bool = ...) -> None: ... + def save_to_path(self, filename: FileDescriptorOrPath, partial: bool = ...) -> None: ... + +class OutputBuffer: + fd: int + buffer: bytes + def __init__(self, fd: int) -> None: ... + def add(self, output: bytes) -> None: ... + def flush(self) -> None: ... + +class PseudoTerminal(MultiProcessHelper): + encoding: str + termination_delay: float + chunk_size: int + relay_fd: int | None + output_queue: Queue[tuple[Any, bytes]] | None + queue_token: Any | None + streams: list[Stream] + master_fd: int + slave_fd: int + output_fd: int + output_handle: BufferedReader + def __init__( + self, + encoding: str, + termination_delay: float, + chunk_size: int, + relay_fd: int | None, + output_queue: Queue[tuple[int, bytes]] | None, + queue_token: Any | None, + ) -> None: ... + def attach(self, stream: Stream) -> None: ... + def start_capture(self) -> None: ... + def finish_capture(self) -> None: ... + def close_pseudo_terminal(self) -> None: ... + def restore_streams(self) -> None: ... + def get_handle(self, partial: bool = ...) -> BufferedReader: ... + def get_bytes(self, partial: bool = ...) -> bytes: ... + def get_lines(self, interpreted: bool = True, partial: bool = ...) -> list[str]: ... + def get_text(self, interpreted: bool = ..., partial: bool = ...) -> str: ... + def save_to_handle(self, handle: SupportsWrite[bytes], partial: bool = ...) -> None: ... + def save_to_path(self, filename: FileDescriptorOrPath, partial: bool = ...) -> None: ... + def capture_loop(self, started_event: Event) -> None: ... + +class Stream: + fd: int + original_fd: int + is_redirected: bool + def __init__(self, fd: int) -> None: ... + def redirect(self, target_fd: int) -> None: ... + def restore(self) -> None: ... + +class ShutdownRequested(Exception): ... diff --git a/stubs/cffi/@tests/stubtest_allowlist.txt b/stubs/cffi/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..908583146f5f --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# added dynamically and not detected by stubtest +cffi.(api.)?FFI.CData +cffi.(api.)?FFI.CType +cffi.(api.)?FFI.buffer diff --git a/stubs/cffi/@tests/stubtest_allowlist_darwin.txt b/stubs/cffi/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..55d4b889aca9 --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs +cffi.(api.)?FFI.getwinerror diff --git a/stubs/cffi/@tests/stubtest_allowlist_linux.txt b/stubs/cffi/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..55d4b889aca9 --- /dev/null +++ b/stubs/cffi/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs +cffi.(api.)?FFI.getwinerror diff --git a/stubs/cffi/METADATA.toml b/stubs/cffi/METADATA.toml new file mode 100644 index 000000000000..b42e584ae0b2 --- /dev/null +++ b/stubs/cffi/METADATA.toml @@ -0,0 +1,7 @@ +version = "2.0.*" +upstream-repository = "https://github.com/python-cffi/cffi/" +dependencies = ["types-setuptools"] + +[tool.stubtest] +# linux and darwin are mostly equivalent, except for a single `RTLD_DEEPBIND` variable +ci-platforms = ["linux", "win32"] diff --git a/stubs/cffi/_cffi_backend.pyi b/stubs/cffi/_cffi_backend.pyi new file mode 100644 index 000000000000..27c2f4d6cf00 --- /dev/null +++ b/stubs/cffi/_cffi_backend.pyi @@ -0,0 +1,286 @@ +import sys +import types +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Hashable +from typing import Any, ClassVar, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self, disjoint_base + +_T = TypeVar("_T") + +@type_check_only +class _Allocator(Protocol): + def __call__(self, cdecl: str | CType, init: Any = ...) -> _CDataBase: ... + +__version__: str + +FFI_CDECL: int +FFI_DEFAULT_ABI: int +RTLD_GLOBAL: int +RTLD_LAZY: int +RTLD_LOCAL: int +RTLD_NOW: int +if sys.platform == "linux": + RTLD_DEEPBIND: int +if sys.platform != "win32": + RTLD_NODELETE: int + RTLD_NOLOAD: int + +@final +class CField: + bitshift: Incomplete + bitsize: Incomplete + flags: Incomplete + offset: Incomplete + type: Incomplete + +@final +class CLibrary: + def close_lib(self) -> None: ... + def load_function(self, *args, **kwargs): ... + def read_variable(self, *args, **kwargs): ... + def write_variable(self, *args, **kwargs): ... + +@final +class CType: + abi: Incomplete + args: Incomplete + cname: Incomplete + elements: Incomplete + ellipsis: Incomplete + fields: Incomplete + item: Incomplete + kind: Incomplete + length: Incomplete + relements: Incomplete + result: Incomplete + def __dir__(self): ... + +@final +class Lib: + def __dir__(self): ... + +@final +class _CDataBase: + __name__: ClassVar[str] + def __add__(self, other, /): ... + def __bool__(self) -> bool: ... + def __call__(self, *args, **kwargs): ... + def __complex__(self) -> complex: ... + def __delitem__(self, other, /) -> None: ... + def __dir__(self): ... + def __enter__(self) -> Self: ... + def __eq__(self, other, /): ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None, / + ): ... + def __float__(self) -> float: ... + def __ge__(self, other, /): ... + def __getitem__(self, index: SupportsIndex | slice, /): ... + def __gt__(self, other, /): ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def __iter__(self): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __radd__(self, other, /): ... + def __rsub__(self, other, /): ... + def __setitem__(self, index: SupportsIndex | slice, object, /) -> None: ... + def __sub__(self, other, /): ... + +@final +class buffer: + __hash__: ClassVar[None] # type: ignore[assignment] + def __new__(cls, *args, **kwargs) -> Self: ... + def __buffer__(self, flags: int, /) -> memoryview: ... + def __delitem__(self, other, /) -> None: ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... + def __gt__(self, other, /): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __setitem__(self, index, object, /) -> None: ... + +# These aliases are to work around pyright complaints. +# Pyright doesn't like it when a class object is defined as an alias +# of a global object with the same name. +_tmp_CType = CType +_tmp_buffer = buffer + +@disjoint_base +class FFI: + CData: TypeAlias = _CDataBase + CType: TypeAlias = _tmp_CType + buffer: TypeAlias = _tmp_buffer # noqa: Y042 + + class error(Exception): ... + NULL: ClassVar[CData] + RTLD_GLOBAL: ClassVar[int] + RTLD_LAZY: ClassVar[int] + RTLD_LOCAL: ClassVar[int] + RTLD_NOW: ClassVar[int] + if sys.platform != "win32": + RTLD_DEEPBIND: ClassVar[int] + RTLD_NODELETE: ClassVar[int] + RTLD_NOLOAD: ClassVar[int] + + errno: int + + def __init__( + self, + module_name: str = ..., + _version: int = ..., + _types: bytes = ..., + _globals: tuple[bytes | int, ...] = ..., + _struct_unions: tuple[tuple[bytes, ...], ...] = ..., + _enums: tuple[bytes, ...] = ..., + _typenames: tuple[bytes, ...] = ..., + _includes: tuple[FFI, ...] = ..., + ) -> None: ... + + @overload + def addressof(self, cdata: CData, /, *field_or_index: str | int) -> CData: ... + @overload + def addressof(self, library: Lib, name: str, /) -> CData: ... + + def alignof(self, cdecl: str | CType | CData, /) -> int: ... + + @overload + def callback( + self, + cdecl: str | CType, + python_callable: None = ..., + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def callback( + self, + cdecl: str | CType, + python_callable: Callable[..., _T], + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + ) -> Callable[..., _T]: ... + + def cast(self, cdecl: str | CType, value: CData | int) -> CData: ... + def def_extern( + self, name: str = ..., error: Any = ..., onerror: Callable[[Exception, Any, types.TracebackType], Any] = ... + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def dlclose(self, lib: Lib, /) -> None: ... + if sys.platform == "win32": + def dlopen(self, libpath: str | CData, flags: int = ..., /) -> Lib: ... + else: + def dlopen(self, libpath: str | CData | None = ..., flags: int = ..., /) -> Lib: ... + + @overload + def from_buffer(self, cdecl: ReadableBuffer, require_writable: Literal[False] = ...) -> CData: ... + @overload + def from_buffer(self, cdecl: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: ReadableBuffer, require_writable: Literal[False] = ...) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + + def from_handle(self, x: CData, /) -> Any: ... + + @overload + def gc(self, cdata: CData, destructor: Callable[[CData], Any], size: int = ...) -> CData: ... + @overload + def gc(self, cdata: CData, destructor: None, size: int = ...) -> None: ... + + def getctype(self, cdecl: str | CType, replace_with: str = ...) -> str: ... + if sys.platform == "win32": + def getwinerror(self, code: int = ...) -> tuple[int, str]: ... + + def init_once(self, func: Callable[[], Any], tag: Hashable) -> Any: ... + def integer_const(self, name: str) -> int: ... + def list_types(self) -> tuple[list[str], list[str], list[str]]: ... + def memmove(self, dest: CData | WriteableBuffer, src: CData | ReadableBuffer, n: int) -> None: ... + def new(self, cdecl: str | CType, init: Any = ...) -> CData: ... + + @overload + def new_allocator(self, alloc: None = ..., free: None = ..., should_clear_after_alloc: bool = ...) -> _Allocator: ... + @overload + def new_allocator( + self, alloc: Callable[[int], CData], free: None = ..., should_clear_after_alloc: bool = ... + ) -> _Allocator: ... + @overload + def new_allocator( + self, alloc: Callable[[int], CData], free: Callable[[CData], Any], should_clear_after_alloc: bool = ... + ) -> _Allocator: ... + + def new_handle(self, x: Any, /) -> CData: ... + def offsetof(self, cdecl: str | CType, field_or_index: str | int, /, *__fields_or_indexes: str | int) -> int: ... + def release(self, cdata: CData, /) -> None: ... + def sizeof(self, cdecl: str | CType | CData, /) -> int: ... + def string(self, cdata: CData, maxlen: int = -1) -> bytes | str: ... + def typeof(self, cdecl: str | CData, /) -> CType: ... + def unpack(self, cdata: CData, length: int) -> bytes | str | list[Any]: ... + +def alignof(cdecl: CType, /) -> int: ... +def callback( + cdecl: CType, + python_callable: Callable[..., _T], + error: Any = ..., + onerror: Callable[[Exception, Any, Any], None] | None = ..., + /, +) -> Callable[..., _T]: ... +def cast(cdecl: CType, value: _CDataBase, /) -> _CDataBase: ... +def complete_struct_or_union( + cdecl: CType, + fields: list[tuple[str, CType, int, int]], + ignored: Any, + total_size: int, + total_alignment: int, + sflags: int, + pack: int, + /, +) -> None: ... + +@overload +def from_buffer(cdecl: CType, python_buffer: ReadableBuffer, /, require_writable: Literal[False] = ...) -> _CDataBase: ... +@overload +def from_buffer(cdecl: CType, python_buffer: WriteableBuffer, /, require_writable: Literal[True]) -> _CDataBase: ... + +def from_handle(x: _CDataBase, /) -> Any: ... + +@overload +def gcp(cdata: _CDataBase, destructor: Callable[[_CDataBase], Any], size: int = ...) -> _CDataBase: ... +@overload +def gcp(cdata: _CDataBase, destructor: None, size: int = ...) -> None: ... + +def get_errno() -> int: ... +def getcname(cdecl: CType, replace_with: str, /) -> str: ... + +if sys.platform == "win32": + def getwinerror(code: int = ...) -> tuple[int, str]: ... + +if sys.platform == "win32": + def load_library(libpath: str | _CDataBase, flags: int = ..., /) -> CLibrary: ... + +else: + def load_library(libpath: str | _CDataBase | None = ..., flags: int = ..., /) -> CLibrary: ... + +def memmove(dest: _CDataBase | WriteableBuffer, src: _CDataBase | ReadableBuffer, n: int) -> None: ... +def new_array_type(cdecl: CType, length: int | None, /) -> CType: ... +def new_enum_type(name: str, enumerators: tuple[str, ...], enumvalues: tuple[Any, ...], basetype: CType, /) -> CType: ... +def new_function_type(args: tuple[CType, ...], result: CType, ellipsis: int, abi: int, /) -> CType: ... +def new_pointer_type(cdecl: CType, /) -> CType: ... +def new_primitive_type(name: str, /) -> CType: ... +def new_struct_type(name: str, /) -> CType: ... +def new_union_type(name: str, /) -> CType: ... +def new_void_type() -> CType: ... +def newp(cdecl: CType, init: Any = ..., /) -> _CDataBase: ... +def newp_handle(cdecl: CType, x: Any, /) -> _CDataBase: ... +def rawaddressof(cdecl: CType, cdata: _CDataBase, offset: int, /) -> _CDataBase: ... +def release(cdata: _CDataBase, /) -> None: ... +def set_errno(errno: int, /) -> None: ... +def sizeof(cdecl: CType | _CDataBase, /) -> int: ... +def string(cdata: _CDataBase, maxlen: int) -> bytes | str: ... +def typeof(cdata: _CDataBase, /) -> CType: ... +def typeoffsetof(cdecl: CType, fieldname: str | int, following: bool = ..., /) -> tuple[CType, int]: ... +def unpack(cdata: _CDataBase, length: int) -> bytes | str | list[Any]: ... diff --git a/stubs/cffi/cffi/__init__.pyi b/stubs/cffi/cffi/__init__.pyi new file mode 100644 index 000000000000..b549eb5b1ea9 --- /dev/null +++ b/stubs/cffi/cffi/__init__.pyi @@ -0,0 +1,15 @@ +from typing import Final + +from .api import FFI as FFI +from .error import ( + CDefError as CDefError, + FFIError as FFIError, + PkgConfigError as PkgConfigError, + VerificationError as VerificationError, + VerificationMissing as VerificationMissing, +) + +__all__ = ["FFI", "VerificationError", "VerificationMissing", "CDefError", "FFIError"] +__version__: Final[str] +__version_info__: Final[tuple[int, int, int]] +__version_verifier_modules__: Final[str] diff --git a/stubs/cffi/cffi/api.pyi b/stubs/cffi/cffi/api.pyi new file mode 100644 index 000000000000..05ea2daecbfc --- /dev/null +++ b/stubs/cffi/cffi/api.pyi @@ -0,0 +1,111 @@ +import sys +import types +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable, Hashable +from typing import Any, Literal, TypeAlias, TypeVar, overload + +import _cffi_backend +from setuptools._distutils.extension import Extension + +_T = TypeVar("_T") + +basestring: TypeAlias = str # noqa: Y042 + +class FFI: + CData: TypeAlias = _cffi_backend._CDataBase + CType: TypeAlias = _cffi_backend.CType + buffer: TypeAlias = _cffi_backend.buffer # noqa: Y042 + + BVoidP: CType + BCharA: CType + NULL: CData + errno: int + + def __init__(self, backend: types.ModuleType | None = None) -> None: ... + def cdef(self, csource: str, override: bool = False, packed: bool = False, pack: int | None = None) -> None: ... + def embedding_api(self, csource: str, packed: bool = False, pack: bool | int | None = None) -> None: ... + + if sys.platform == "win32": + def dlopen(self, name: str, flags: int = ...) -> _cffi_backend.Lib: ... + else: + def dlopen(self, name: str | None, flags: int = 0) -> _cffi_backend.Lib: ... + + def dlclose(self, lib: _cffi_backend.Lib) -> None: ... + def typeof(self, cdecl: str | CData | types.BuiltinFunctionType | types.FunctionType) -> CType: ... + def sizeof(self, cdecl: str | CData) -> int: ... + def alignof(self, cdecl: str | CData) -> int: ... + def offsetof(self, cdecl: str | CData, *fields_or_indexes: str | int) -> int: ... + + # The acceptable types of `init` depend on the value of `cdecl` only known at runtime, and + # therefore unknown to the type checker. + def new(self, cdecl: str | CType, init: Any = None) -> CData: ... + def new_allocator( + self, + alloc: Callable[[int], CData] | None = None, + free: Callable[[CData], Any] | None = None, + should_clear_after_alloc: bool = True, + ) -> _cffi_backend._Allocator: ... + def cast(self, cdecl: str | CType, source: CData | float) -> CData: ... + def string(self, cdata: CData, maxlen: int = -1) -> bytes | str: ... + def unpack(self, cdata: CData, length: int) -> bytes | str | list[Any]: ... + + @overload + def from_buffer(self, cdecl: ReadableBuffer, require_writable: Literal[False] = False) -> CData: ... + @overload + def from_buffer(self, cdecl: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + @overload + def from_buffer( + self, cdecl: str | CType, python_buffer: ReadableBuffer, require_writable: Literal[False] = False + ) -> CData: ... + @overload + def from_buffer(self, cdecl: str | CType, python_buffer: WriteableBuffer, require_writable: Literal[True]) -> CData: ... + + def memmove(self, dest: CData | WriteableBuffer, src: CData | ReadableBuffer, n: int) -> None: ... + + @overload + def callback( + self, + cdecl: str | CType, + python_callable: None = None, + error: Any = None, + onerror: Callable[[Exception, Any, Any], None] | None = None, + ) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def callback( + self, + cdecl: str | CType, + python_callable: Callable[..., _T], + error: Any = None, + onerror: Callable[[Exception, Any, Any], None] | None = None, + ) -> Callable[..., _T]: ... + + def getctype(self, cdecl: str | CType, replace_with: str = "") -> str: ... + + @overload + def gc(self, cdata: CData, destructor: Callable[[CData], Any], size: int = 0) -> CData: ... + @overload + def gc(self, cdata: CData, destructor: None, size: int = 0) -> None: ... + + def verify(self, source: str = "", tmpdir: str | None = None, **kwargs: Any) -> _cffi_backend.Lib: ... + # Technically exists on all OSs, but crashes on all but Windows. So we hide it in stubs + if sys.platform == "win32": + def getwinerror(self, code: int = -1) -> tuple[int, str] | None: ... + + def addressof(self, cdata: CData, *fields_or_indexes: str | int) -> CData: ... + def include(self, ffi_to_include: FFI) -> None: ... + def new_handle(self, x: Any) -> CData: ... + def from_handle(self, x: CData) -> Any: ... + def release(self, x: CData) -> None: ... + def set_unicode(self, enabled_flag: bool) -> None: ... + def set_source(self, module_name: str, source: str | None, source_extension: str = ".c", **kwds: Any) -> None: ... + def set_source_pkgconfig( + self, module_name: str, pkgconfig_libs: list[str], source: str, source_extension: str = ".c", **kwds: Any + ) -> None: ... + def distutils_extension(self, tmpdir: str = "build", verbose: bool = True) -> Extension: ... + def emit_c_code(self, filename: str) -> None: ... + def emit_python_code(self, filename: str) -> None: ... + def compile(self, tmpdir: str = ".", verbose: int = 0, target: str | None = None, debug: bool | None = None) -> str: ... + def init_once(self, func: Callable[[], Any], tag: Hashable) -> Any: ... + def embedding_init_code(self, pysource: str) -> None: ... + def def_extern(self, *args: Any, **kwds: Any) -> None: ... + def list_types(self) -> tuple[list[str], list[str], list[str]]: ... diff --git a/stubs/cffi/cffi/backend_ctypes.pyi b/stubs/cffi/cffi/backend_ctypes.pyi new file mode 100644 index 000000000000..04c0e8a8ffbe --- /dev/null +++ b/stubs/cffi/cffi/backend_ctypes.pyi @@ -0,0 +1,85 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +unicode = str +long = int +xrange = range +bytechr: Callable[[float], bytes] + +class CTypesType(type): ... + +class CTypesData: + __slots__ = ["__weakref__"] + __metaclass__: Incomplete + __name__: str + def __init__(self, *args) -> None: ... + def __iter__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self) -> int: ... + def __repr__(self, c_name: str | None = None): ... + +class CTypesGenericPrimitive(CTypesData): + __slots__: list[str] = [] + def __hash__(self) -> int: ... + +class CTypesGenericArray(CTypesData): + __slots__: list[str] = [] + def __iter__(self): ... + +class CTypesGenericPtr(CTypesData): + __slots__ = ["_address", "_as_ctype_ptr"] + kind: str + def __nonzero__(self) -> bool: ... + def __bool__(self) -> bool: ... + +class CTypesBaseStructOrUnion(CTypesData): + __slots__ = ["_blob"] + +class CTypesBackend: + PRIMITIVE_TYPES: Incomplete + RTLD_LAZY: int + RTLD_NOW: int + RTLD_GLOBAL: Incomplete + RTLD_LOCAL: Incomplete + def __init__(self) -> None: ... + ffi: Incomplete + def set_ffi(self, ffi) -> None: ... + def load_library(self, path, flags: int = 0): ... + def new_void_type(self): ... + def new_primitive_type(self, name): ... + def new_pointer_type(self, BItem): ... + def new_array_type(self, CTypesPtr, length): ... + def new_struct_type(self, name): ... + def new_union_type(self, name): ... + def complete_struct_or_union( + self, CTypesStructOrUnion, fields, tp, totalsize: int = -1, totalalignment: int = -1, sflags: int = 0, pack: int = 0 + ): ... + def new_function_type(self, BArgs, BResult, has_varargs): ... + def new_enum_type(self, name, enumerators, enumvalues, CTypesInt): ... + def get_errno(self): ... + def set_errno(self, value) -> None: ... + def string(self, b, maxlen: int = -1): ... + def buffer(self, bptr, size: int = -1) -> None: ... + def sizeof(self, cdata_or_BType) -> int: ... + def alignof(self, BType) -> int: ... + def newp(self, BType, source): ... + def cast(self, BType, source): ... + def callback(self, BType, source, error, onerror): ... + def gcp(self, cdata, destructor, size: int = 0): ... + typeof: Incomplete + def getcname(self, BType, replace_with): ... + def typeoffsetof(self, BType, fieldname, num: int = 0): ... + def rawaddressof(self, BTypePtr, cdata, offset=None): ... + +class CTypesLibrary: + backend: Incomplete + cdll: Incomplete + def __init__(self, backend, cdll) -> None: ... + def load_function(self, BType, name): ... + def read_variable(self, BType, name): ... + def write_variable(self, BType, name, value) -> None: ... diff --git a/stubs/cffi/cffi/cffi_opcode.pyi b/stubs/cffi/cffi/cffi_opcode.pyi new file mode 100644 index 000000000000..a992eb339797 --- /dev/null +++ b/stubs/cffi/cffi/cffi_opcode.pyi @@ -0,0 +1,92 @@ +from typing import Final + +class CffiOp: + op: int | None + arg: str | None + def __init__(self, op: int | None, arg: str | None) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_bytes(self) -> str: ... + +def format_four_bytes(num: int) -> str: ... + +OP_PRIMITIVE: Final = 1 +OP_POINTER: Final = 3 +OP_ARRAY: Final = 5 +OP_OPEN_ARRAY: Final = 7 +OP_STRUCT_UNION: Final = 9 +OP_ENUM: Final = 11 +OP_FUNCTION: Final = 13 +OP_FUNCTION_END: Final = 15 +OP_NOOP: Final = 17 +OP_BITFIELD: Final = 19 +OP_TYPENAME: Final = 21 +OP_CPYTHON_BLTN_V: Final = 23 +OP_CPYTHON_BLTN_N: Final = 25 +OP_CPYTHON_BLTN_O: Final = 27 +OP_CONSTANT: Final = 29 +OP_CONSTANT_INT: Final = 31 +OP_GLOBAL_VAR: Final = 33 +OP_DLOPEN_FUNC: Final = 35 +OP_DLOPEN_CONST: Final = 37 +OP_GLOBAL_VAR_F: Final = 39 +OP_EXTERN_PYTHON: Final = 41 +PRIM_VOID: Final = 0 +PRIM_BOOL: Final = 1 +PRIM_CHAR: Final = 2 +PRIM_SCHAR: Final = 3 +PRIM_UCHAR: Final = 4 +PRIM_SHORT: Final = 5 +PRIM_USHORT: Final = 6 +PRIM_INT: Final = 7 +PRIM_UINT: Final = 8 +PRIM_LONG: Final = 9 +PRIM_ULONG: Final = 10 +PRIM_LONGLONG: Final = 11 +PRIM_ULONGLONG: Final = 12 +PRIM_FLOAT: Final = 13 +PRIM_DOUBLE: Final = 14 +PRIM_LONGDOUBLE: Final = 15 +PRIM_WCHAR: Final = 16 +PRIM_INT8: Final = 17 +PRIM_UINT8: Final = 18 +PRIM_INT16: Final = 19 +PRIM_UINT16: Final = 20 +PRIM_INT32: Final = 21 +PRIM_UINT32: Final = 22 +PRIM_INT64: Final = 23 +PRIM_UINT64: Final = 24 +PRIM_INTPTR: Final = 25 +PRIM_UINTPTR: Final = 26 +PRIM_PTRDIFF: Final = 27 +PRIM_SIZE: Final = 28 +PRIM_SSIZE: Final = 29 +PRIM_INT_LEAST8: Final = 30 +PRIM_UINT_LEAST8: Final = 31 +PRIM_INT_LEAST16: Final = 32 +PRIM_UINT_LEAST16: Final = 33 +PRIM_INT_LEAST32: Final = 34 +PRIM_UINT_LEAST32: Final = 35 +PRIM_INT_LEAST64: Final = 36 +PRIM_UINT_LEAST64: Final = 37 +PRIM_INT_FAST8: Final = 38 +PRIM_UINT_FAST8: Final = 39 +PRIM_INT_FAST16: Final = 40 +PRIM_UINT_FAST16: Final = 41 +PRIM_INT_FAST32: Final = 42 +PRIM_UINT_FAST32: Final = 43 +PRIM_INT_FAST64: Final = 44 +PRIM_UINT_FAST64: Final = 45 +PRIM_INTMAX: Final = 46 +PRIM_UINTMAX: Final = 47 +PRIM_FLOATCOMPLEX: Final = 48 +PRIM_DOUBLECOMPLEX: Final = 49 +PRIM_CHAR16: Final = 50 +PRIM_CHAR32: Final = 51 +PRIMITIVE_TO_INDEX: Final[dict[str, int]] +F_UNION: Final = 1 +F_CHECK_FIELDS: Final = 2 +F_PACKED: Final = 4 +F_EXTERNAL: Final = 8 +F_OPAQUE: Final = 16 +G_FLAGS: Final[dict[bytes, bytes]] +CLASS_NAME: Final[dict[int, str]] diff --git a/stubs/cffi/cffi/commontypes.pyi b/stubs/cffi/cffi/commontypes.pyi new file mode 100644 index 000000000000..fe9e35ee52b6 --- /dev/null +++ b/stubs/cffi/cffi/commontypes.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +COMMON_TYPES: Incomplete + +def resolve_common_type(parser, commontype): ... +def win_common_types(): ... diff --git a/stubs/cffi/cffi/cparser.pyi b/stubs/cffi/cffi/cparser.pyi new file mode 100644 index 000000000000..a42b2ddc0406 --- /dev/null +++ b/stubs/cffi/cffi/cparser.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +lock: Incomplete +CDEF_SOURCE_STRING: str + +class Parser: + def __init__(self) -> None: ... + def convert_pycparser_error(self, e, csource) -> None: ... + def parse(self, csource, override: bool = False, packed: bool = False, pack=None, dllexport: bool = False) -> None: ... + def parse_type(self, cdecl): ... + def parse_type_and_quals(self, cdecl): ... + def include(self, other) -> None: ... diff --git a/stubs/cffi/cffi/error.pyi b/stubs/cffi/cffi/error.pyi new file mode 100644 index 000000000000..a71f17e5d049 --- /dev/null +++ b/stubs/cffi/cffi/error.pyi @@ -0,0 +1,14 @@ +class FFIError(Exception): + __module__: str + +class CDefError(Exception): + __module__: str + +class VerificationError(Exception): + __module__: str + +class VerificationMissing(Exception): + __module__: str + +class PkgConfigError(Exception): + __module__: str diff --git a/stubs/cffi/cffi/ffiplatform.pyi b/stubs/cffi/cffi/ffiplatform.pyi new file mode 100644 index 000000000000..f7fe46729b32 --- /dev/null +++ b/stubs/cffi/cffi/ffiplatform.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrOrBytesPath +from typing import Any, Final + +LIST_OF_FILE_NAMES: Final[list[str]] + +def get_extension(srcfilename, modname, sources=(), **kwds): ... +def compile(tmpdir, ext, compiler_verbose: int = 0, debug=None): ... +def maybe_relative_path(path: StrOrBytesPath) -> StrOrBytesPath | str: ... + +int_or_long = int + +def flatten(x: int | str | list[Any] | tuple[Any] | dict[Any, Any]) -> str: ... diff --git a/stubs/cffi/cffi/lock.pyi b/stubs/cffi/cffi/lock.pyi new file mode 100644 index 000000000000..fc8393af7412 --- /dev/null +++ b/stubs/cffi/cffi/lock.pyi @@ -0,0 +1 @@ +from _thread import allocate_lock as allocate_lock diff --git a/stubs/cffi/cffi/model.pyi b/stubs/cffi/cffi/model.pyi new file mode 100644 index 000000000000..48a03c2dcea9 --- /dev/null +++ b/stubs/cffi/cffi/model.pyi @@ -0,0 +1,164 @@ +from _thread import LockType +from _typeshed import Incomplete +from collections.abc import Generator +from typing import Final + +from .error import CDefError as CDefError, VerificationError as VerificationError, VerificationMissing as VerificationMissing +from .lock import allocate_lock as allocate_lock + +Q_CONST: Final = 1 +Q_RESTRICT: Final = 2 +Q_VOLATILE: Final = 4 + +def qualify(quals: int, replace_with: str) -> str: ... + +class BaseTypeByIdentity: + is_array_type: bool + is_raw_function: bool + def get_c_name(self, replace_with: str = "", context: str = "a C file", quals: int = 0) -> str: ... + def has_c_name(self) -> bool: ... + def is_integer_type(self) -> bool: ... + def get_cached_btype(self, ffi, finishlist, can_delay: bool = False): ... + +class BaseType(BaseTypeByIdentity): + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class VoidType(BaseType): + c_name_with_marker: str + def __init__(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +void_type: VoidType + +class BasePrimitiveType(BaseType): + def is_complex_type(self) -> bool: ... + +class PrimitiveType(BasePrimitiveType): + ALL_PRIMITIVE_TYPES: dict[str, str] + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def is_char_type(self) -> bool: ... + def is_integer_type(self) -> bool: ... + def is_float_type(self) -> bool: ... + def is_complex_type(self) -> bool: ... + def build_backend_type(self, ffi, finishlist): ... + +class UnknownIntegerType(BasePrimitiveType): + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def is_integer_type(self) -> bool: ... + def build_backend_type(self, ffi, finishlist) -> None: ... + +class UnknownFloatType(BasePrimitiveType): + name: str + c_name_with_marker: str + def __init__(self, name: str) -> None: ... + def build_backend_type(self, ffi, finishlist) -> None: ... + +class BaseFunctionType(BaseType): + args: Incomplete + result: Incomplete + ellipsis: Incomplete + abi: Incomplete + c_name_with_marker: str + def __init__(self, args, result, ellipsis, abi=None) -> None: ... + +class RawFunctionType(BaseFunctionType): + is_raw_function: bool + def build_backend_type(self, ffi, finishlist) -> None: ... + def as_function_pointer(self) -> FunctionPtrType: ... + +class FunctionPtrType(BaseFunctionType): + def build_backend_type(self, ffi, finishlist): ... + def as_raw_function(self) -> RawFunctionType: ... + +class PointerType(BaseType): + totype: BaseTypeByIdentity + quals: int + c_name_with_marker: str + def __init__(self, totype: BaseTypeByIdentity, quals: int = 0) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +voidp_type: PointerType + +def ConstPointerType(totype: BaseTypeByIdentity) -> PointerType: ... + +const_voidp_type: PointerType + +class NamedPointerType(PointerType): + name: str + c_name_with_marker: str + def __init__(self, totype: BaseTypeByIdentity, name: str, quals: int = 0) -> None: ... + +class ArrayType(BaseType): + is_array_type: bool + item: Incomplete + length: str | None + c_name_with_marker: str + def __init__(self, item, length: str | None) -> None: ... + def length_is_unknown(self) -> bool: ... + def resolve_length(self, newlength: str | None) -> ArrayType: ... + def build_backend_type(self, ffi, finishlist): ... + +char_array_type: ArrayType + +class StructOrUnionOrEnum(BaseTypeByIdentity): + forcename: str | None + c_name_with_marker: str + def build_c_name_with_marker(self) -> None: ... + def force_the_name(self, forcename: str | None) -> None: ... + def get_official_name(self) -> str: ... + +class StructOrUnion(StructOrUnionOrEnum): + fixedlayout: Incomplete + completed: int + partial: bool + packed: int + name: Incomplete + fldnames: Incomplete + fldtypes: Incomplete + fldbitsize: Incomplete + fldquals: Incomplete + def __init__(self, name, fldnames, fldtypes, fldbitsize, fldquals=None) -> None: ... + def anonymous_struct_fields(self) -> Generator[StructOrUnion]: ... + def enumfields(self, expand_anonymous_struct_union: bool = True) -> Generator[Incomplete]: ... + def force_flatten(self) -> None: ... + def get_cached_btype(self, ffi, finishlist, can_delay: bool = False): ... + def finish_backend_type(self, ffi, finishlist) -> None: ... + def check_not_partial(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + +class StructType(StructOrUnion): + kind: str + +class UnionType(StructOrUnion): + kind: str + +class EnumType(StructOrUnionOrEnum): + kind: str + partial: bool + partial_resolved: bool + name: Incomplete + enumerators: Incomplete + enumvalues: Incomplete + baseinttype: Incomplete + def __init__(self, name, enumerators, enumvalues, baseinttype=None) -> None: ... + forcename: str | None + def force_the_name(self, forcename: str | None) -> None: ... + def check_not_partial(self) -> None: ... + def build_backend_type(self, ffi, finishlist): ... + def build_baseinttype(self, ffi, finishlist): ... + +def unknown_type(name: str, structname: str | None = None) -> StructType: ... +def unknown_ptr_type(name: str, structname: str | None = None) -> NamedPointerType: ... + +global_lock: LockType + +def get_typecache(backend): ... +def global_cache(srctype, ffi, funcname, *args, **kwds): ... +def pointer_cache(ffi, BType): ... +def attach_exception_info(e, name: str) -> None: ... diff --git a/stubs/cffi/cffi/pkgconfig.pyi b/stubs/cffi/cffi/pkgconfig.pyi new file mode 100644 index 000000000000..510961c2b349 --- /dev/null +++ b/stubs/cffi/cffi/pkgconfig.pyi @@ -0,0 +1,5 @@ +from collections.abc import Sequence + +def merge_flags(cfg1: dict[str, list[str]], cfg2: dict[str, list[str]]) -> dict[str, list[str]]: ... +def call(libname: str, flag: str, encoding: str = "utf-8") -> str: ... +def flags_from_pkgconfig(libs: Sequence[str]) -> dict[str, list[str]]: ... diff --git a/stubs/cffi/cffi/recompiler.pyi b/stubs/cffi/cffi/recompiler.pyi new file mode 100644 index 000000000000..f95c84932278 --- /dev/null +++ b/stubs/cffi/cffi/recompiler.pyi @@ -0,0 +1,96 @@ +import io +from _typeshed import Incomplete, StrPath +from typing import Final, TypeAlias + +from .cffi_opcode import * +from .error import VerificationError as VerificationError + +VERSION_BASE: Final = 9729 +VERSION_EMBEDDED: Final = 9985 +VERSION_CHAR16CHAR32: Final = 10241 +USE_LIMITED_API: Final = True + +class GlobalExpr: + name: Incomplete + address: Incomplete + type_op: Incomplete + size: Incomplete + check_value: Incomplete + def __init__(self, name, address, type_op, size: int = 0, check_value: int = 0) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class FieldExpr: + name: Incomplete + field_offset: Incomplete + field_size: Incomplete + fbitsize: Incomplete + field_type_op: Incomplete + def __init__(self, name, field_offset, field_size, fbitsize, field_type_op) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> None: ... + def as_field_python_expr(self) -> str: ... + +class StructUnionExpr: + name: Incomplete + type_index: Incomplete + flags: Incomplete + size: Incomplete + alignment: Incomplete + comment: Incomplete + first_field_index: Incomplete + c_fields: Incomplete + def __init__(self, name, type_index, flags, size, alignment, comment, first_field_index, c_fields) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class EnumExpr: + name: Incomplete + type_index: Incomplete + size: Incomplete + signed: Incomplete + allenums: Incomplete + def __init__(self, name, type_index, size, signed, allenums) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class TypenameExpr: + name: Incomplete + type_index: Incomplete + def __init__(self, name, type_index) -> None: ... + def as_c_expr(self) -> str: ... + def as_python_expr(self) -> str: ... + +class Recompiler: + ffi: Incomplete + module_name: str + target_is_python: bool + def __init__(self, ffi, module_name: str, target_is_python: bool = False) -> None: ... + def needs_version(self, ver: int) -> None: ... + cffi_types: list[Incomplete] + def collect_type_table(self) -> None: ... + ALL_STEPS: list[str] + def collect_step_tables(self) -> None: ... + def write_source_to_f(self, f, preamble: str) -> None: ... + def write_c_source_to_f(self, f, preamble: str) -> None: ... + def write_py_source_to_f(self, f) -> None: ... + +NativeIO: TypeAlias = io.StringIO + +def make_c_source(ffi, module_name: str, preamble: str, target_c_file, verbose: bool = False): ... +def make_py_source(ffi, module_name: str, target_py_file, verbose: bool = False): ... +def recompile( + ffi, + module_name: str | bytes, + preamble: str | None, + tmpdir: str = ".", + call_c_compiler: bool = True, + c_file=None, + source_extension: str = ".c", + extradir: StrPath | None = None, + compiler_verbose: int = 1, + target: str | None = None, + debug: int | None = None, + uses_ffiplatform: bool = True, + **kwds, +): ... diff --git a/stubs/cffi/cffi/setuptools_ext.pyi b/stubs/cffi/cffi/setuptools_ext.pyi new file mode 100644 index 000000000000..beb58858964d --- /dev/null +++ b/stubs/cffi/cffi/setuptools_ext.pyi @@ -0,0 +1,6 @@ +basestring = str + +def error(msg) -> None: ... +def execfile(filename, glob) -> None: ... +def add_cffi_module(dist, mod_spec) -> None: ... +def cffi_modules(dist, attr, value) -> None: ... diff --git a/stubs/cffi/cffi/vengine_cpy.pyi b/stubs/cffi/cffi/vengine_cpy.pyi new file mode 100644 index 000000000000..e9cd0afa70c0 --- /dev/null +++ b/stubs/cffi/cffi/vengine_cpy.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class VCPythonEngine: + verifier: Incomplete + ffi: Incomplete + def __init__(self, verifier) -> None: ... + def patch_extension_kwds(self, kwds) -> None: ... + def find_module(self, module_name, path, so_suffixes): ... + def collect_types(self) -> None: ... + def write_source_to_f(self) -> None: ... + def load_library(self, flags=None): ... + +cffimod_header: str diff --git a/stubs/cffi/cffi/vengine_gen.pyi b/stubs/cffi/cffi/vengine_gen.pyi new file mode 100644 index 000000000000..f77bf20fc0f9 --- /dev/null +++ b/stubs/cffi/cffi/vengine_gen.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +class VGenericEngine: + verifier: Incomplete + ffi: Incomplete + export_symbols: Incomplete + def __init__(self, verifier) -> None: ... + def patch_extension_kwds(self, kwds) -> None: ... + def find_module(self, module_name, path, so_suffixes): ... + def collect_types(self) -> None: ... + def write_source_to_f(self) -> None: ... + def load_library(self, flags: int = 0): ... + +cffimod_header: str diff --git a/stubs/cffi/cffi/verifier.pyi b/stubs/cffi/cffi/verifier.pyi new file mode 100644 index 000000000000..5c8b8d733fbc --- /dev/null +++ b/stubs/cffi/cffi/verifier.pyi @@ -0,0 +1,42 @@ +import io +import os +from _typeshed import Incomplete, StrPath +from typing import AnyStr, TypeAlias + +NativeIO: TypeAlias = io.StringIO + +class Verifier: + ffi: Incomplete + preamble: Incomplete + flags: int | None + kwds: dict[str, list[str] | tuple[str]] + tmpdir: StrPath + sourcefilename: str + modulefilename: str + ext_package: str | None + def __init__( + self, + ffi, + preamble, + tmpdir: StrPath | None = None, + modulename: str | None = None, + ext_package: str | None = None, + tag: str = "", + force_generic_engine: bool = False, + source_extension: str = ".c", + flags: int | None = None, + relative_to: os.PathLike[AnyStr] | None = None, + **kwds: list[str] | tuple[str], + ) -> None: ... + def write_source(self, file=None) -> None: ... + def compile_module(self) -> None: ... + def load_library(self): ... + def get_module_name(self) -> str: ... + def get_extension(self): ... + def generates_python_module(self) -> bool: ... + def make_relative_to( + self, kwds: dict[str, list[str] | tuple[str]], relative_to: os.PathLike[AnyStr] | None + ) -> dict[str, list[str] | tuple[str]]: ... + +def set_tmpdir(dirname: StrPath) -> None: ... +def cleanup_tmpdir(tmpdir: StrPath | None = None, keep_so: bool = False) -> None: ... diff --git a/stubs/channels/@tests/django_settings.py b/stubs/channels/@tests/django_settings.py new file mode 100644 index 000000000000..2be16834be19 --- /dev/null +++ b/stubs/channels/@tests/django_settings.py @@ -0,0 +1,12 @@ +SECRET_KEY = "1" + +INSTALLED_APPS = ( + "django.contrib.contenttypes", + "django.contrib.sites", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.admin.apps.SimpleAdminConfig", + "django.contrib.staticfiles", + "django.contrib.auth", + "channels", +) diff --git a/stubs/channels/@tests/stubtest_allowlist.txt b/stubs/channels/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..91fccf79e4ce --- /dev/null +++ b/stubs/channels/@tests/stubtest_allowlist.txt @@ -0,0 +1,20 @@ +# channels.auth.UserLazyObject metaclass is mismatch +channels.auth.UserLazyObject + +# these one need to be exclude due to mypy error: * is not present at runtime +channels.auth.UserLazyObject.DoesNotExist +channels.auth.UserLazyObject.MultipleObjectsReturned +channels.auth.UserLazyObject.NotUpdated +channels.auth.UserLazyObject@AnnotatedWith + +# "is not a function", because it's wrapped in database_sync_to_async, +# which makes it a class instance. +channels.consumer.SyncConsumer.dispatch + +# database_sync_to_async is implemented as a class instance but stubbed as a function +# for better type inference when used as decorator/function +channels.db.database_sync_to_async + +# Set to None on class, but initialized to non-None value in __init__ +channels.generic.websocket.WebsocketConsumer.groups +channels.generic.websocket.AsyncWebsocketConsumer.groups diff --git a/stubs/channels/METADATA.toml b/stubs/channels/METADATA.toml new file mode 100644 index 000000000000..1eed45be8e4d --- /dev/null +++ b/stubs/channels/METADATA.toml @@ -0,0 +1,8 @@ +version = "4.3.*" +upstream-repository = "https://github.com/django/channels" +dependencies = ["django-stubs>=6.0.3", "asgiref"] + +[tool.stubtest] +mypy-plugins = ['mypy_django_plugin.main'] +mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}} +stubtest-dependencies = ["daphne"] diff --git a/stubs/channels/channels/__init__.pyi b/stubs/channels/channels/__init__.pyi new file mode 100644 index 000000000000..561199954632 --- /dev/null +++ b/stubs/channels/channels/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Final + +__version__: Final[str] +DEFAULT_CHANNEL_LAYER: Final[str] diff --git a/stubs/channels/channels/apps.pyi b/stubs/channels/channels/apps.pyi new file mode 100644 index 000000000000..ad15a21b6961 --- /dev/null +++ b/stubs/channels/channels/apps.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from django.apps import AppConfig + +class ChannelsConfig(AppConfig): + name: Final = "channels" + verbose_name: str = "Channels" diff --git a/stubs/channels/channels/auth.pyi b/stubs/channels/channels/auth.pyi new file mode 100644 index 000000000000..8c2361d3bbdd --- /dev/null +++ b/stubs/channels/channels/auth.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.middleware import BaseMiddleware +from django.contrib.auth.backends import BaseBackend +from django.contrib.auth.base_user import AbstractBaseUser +from django.contrib.auth.models import AnonymousUser +from django.utils.functional import LazyObject + +from .consumer import _ChannelScope +from .utils import _ChannelApplication + +async def get_user(scope: _ChannelScope) -> AbstractBaseUser | AnonymousUser: ... +async def login(scope: _ChannelScope, user: AbstractBaseUser, backend: BaseBackend | None = None) -> None: ... +async def logout(scope: _ChannelScope) -> None: ... + +# Inherits AbstractBaseUser to improve autocomplete and show this is a lazy proxy for a user. +# At runtime, it's just a LazyObject that wraps the actual user instance. +class UserLazyObject(AbstractBaseUser, LazyObject[Incomplete]): ... + +class AuthMiddleware(BaseMiddleware): + def populate_scope(self, scope: _ChannelScope) -> None: ... + async def resolve_scope(self, scope: _ChannelScope) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... + +def AuthMiddlewareStack(inner: _ChannelApplication) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/consumer.pyi b/stubs/channels/channels/consumer.pyi new file mode 100644 index 000000000000..9f6f4725c00a --- /dev/null +++ b/stubs/channels/channels/consumer.pyi @@ -0,0 +1,75 @@ +from _typeshed import Incomplete +from collections.abc import Awaitable +from typing import Any, ClassVar, Protocol, TypedDict, type_check_only + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable, Scope, WebSocketScope +from channels.auth import UserLazyObject +from channels.layers import BaseChannelLayer +from django.contrib.sessions.backends.base import SessionBase +from django.utils.functional import LazyObject + +# _LazySession is a LazyObject that wraps a SessionBase instance. +# We subclass both for type checking purposes to expose SessionBase attributes, +# and suppress mypy's "misc" error with `# type: ignore[misc]`. +@type_check_only +class _LazySession(SessionBase, LazyObject[Incomplete]): # type: ignore[misc] + _wrapped: SessionBase + +@type_check_only +class _URLRoute(TypedDict): + # Values extracted from Django's URLPattern matching, + # passed through ASGI scope routing. + # `args` and `kwargs` are the result of pattern matching against the URL path. + args: tuple[Any, ...] + kwargs: dict[str, Any] + +# Channel Scope definition +@type_check_only +class _ChannelScope(WebSocketScope, total=False): + # Channels specific + channel: str + url_route: _URLRoute + path_remaining: str + + # Auth specific + cookies: dict[str, str] + session: _LazySession + user: UserLazyObject | None + +# Accepts any ASGI message dict with a required "type" key (str), +# but allows additional arbitrary keys for flexibility. +def get_handler_name(message: dict[str, Any]) -> str: ... + +@type_check_only +class _ASGIApplicationProtocol(Protocol): + consumer_class: AsyncConsumer + + # Accepts any initialization kwargs passed to the consumer class. + # Typed as `Any` to allow flexibility in subclass-specific arguments. + consumer_initkwargs: Any + + def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Awaitable[None]: ... + +class AsyncConsumer: + channel_layer_alias: ClassVar[str] + + scope: _ChannelScope + channel_layer: BaseChannelLayer + channel_name: str + channel_receive: ASGIReceiveCallable + base_send: ASGISendCallable + + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + async def dispatch(self, message: dict[str, Any]) -> None: ... + async def send(self, message: dict[str, Any]) -> None: ... + + # initkwargs will be used to instantiate the consumer instance. + @classmethod + def as_asgi(cls, **initkwargs: Any) -> _ASGIApplicationProtocol: ... + +class SyncConsumer(AsyncConsumer): + + # Since we're overriding asynchronous methods with synchronous ones, + # we need to use `# type: ignore[override]` to suppress mypy errors. + async def dispatch(self, message: dict[str, Any]) -> None: ... # type: ignore[override] + def send(self, message: dict[str, Any]) -> None: ... # type: ignore[override] diff --git a/stubs/channels/channels/db.pyi b/stubs/channels/channels/db.pyi new file mode 100644 index 000000000000..913b89ca24ea --- /dev/null +++ b/stubs/channels/channels/db.pyi @@ -0,0 +1,31 @@ +import asyncio +from _typeshed import OptExcInfo +from asyncio import BaseEventLoop +from collections.abc import Callable, Coroutine +from concurrent.futures import ThreadPoolExecutor +from typing import Any, ParamSpec, TypeVar + +from asgiref.sync import SyncToAsync + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +class DatabaseSyncToAsync(SyncToAsync[_P, _R]): + def thread_handler( + self, + loop: BaseEventLoop, + exc_info: OptExcInfo, + task_context: list[asyncio.Task[Any]] | None, + func: Callable[_P, _R], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> _R: ... + +# We define `database_sync_to_async` as a function instead of assigning +# `DatabaseSyncToAsync(...)` directly, to preserve both decorator and +# higher-order function behavior with correct type hints. +# A direct assignment would result in incorrect type inference for the wrapped function. +def database_sync_to_async( + func: Callable[_P, _R], thread_sensitive: bool = True, executor: ThreadPoolExecutor | None = None +) -> Callable[_P, Coroutine[Any, Any, _R]]: ... +async def aclose_old_connections() -> None: ... diff --git a/stubs/channels/channels/exceptions.pyi b/stubs/channels/channels/exceptions.pyi new file mode 100644 index 000000000000..eaba1dfaee14 --- /dev/null +++ b/stubs/channels/channels/exceptions.pyi @@ -0,0 +1,8 @@ +class RequestAborted(Exception): ... +class RequestTimeout(RequestAborted): ... +class InvalidChannelLayerError(ValueError): ... +class AcceptConnection(Exception): ... +class DenyConnection(Exception): ... +class ChannelFull(Exception): ... +class MessageTooLarge(Exception): ... +class StopConsumer(Exception): ... diff --git a/stubs/channels/channels/generic/__init__.pyi b/stubs/channels/channels/generic/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/channels/channels/generic/http.pyi b/stubs/channels/channels/generic/http.pyi new file mode 100644 index 000000000000..84e3b1dbff84 --- /dev/null +++ b/stubs/channels/channels/generic/http.pyi @@ -0,0 +1,19 @@ +from _typeshed import Unused +from collections.abc import Iterable +from typing import Any + +from asgiref.typing import HTTPDisconnectEvent, HTTPRequestEvent, HTTPScope +from channels.consumer import AsyncConsumer + +class AsyncHttpConsumer(AsyncConsumer): + body: list[bytes] + scope: HTTPScope # type: ignore[assignment] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + async def send_headers(self, *, status: int = 200, headers: Iterable[tuple[bytes, bytes]] | None = None) -> None: ... + async def send_body(self, body: bytes, *, more_body: bool = False) -> None: ... + async def send_response(self, status: int, body: bytes, **kwargs: Any) -> None: ... + async def handle(self, body: bytes) -> None: ... + async def disconnect(self) -> None: ... + async def http_request(self, message: HTTPRequestEvent) -> None: ... + async def http_disconnect(self, message: HTTPDisconnectEvent) -> None: ... diff --git a/stubs/channels/channels/generic/websocket.pyi b/stubs/channels/channels/generic/websocket.pyi new file mode 100644 index 000000000000..f19d406e1e5d --- /dev/null +++ b/stubs/channels/channels/generic/websocket.pyi @@ -0,0 +1,61 @@ +from _typeshed import Unused +from typing import Any + +from asgiref.typing import WebSocketConnectEvent, WebSocketDisconnectEvent, WebSocketReceiveEvent +from channels.consumer import AsyncConsumer, SyncConsumer + +class WebsocketConsumer(SyncConsumer): + groups: list[str] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + def websocket_connect(self, message: WebSocketConnectEvent) -> None: ... + def connect(self) -> None: ... + def accept(self, subprotocol: str | None = None, headers: list[tuple[str, str]] | None = None) -> None: ... + def websocket_receive(self, message: WebSocketReceiveEvent) -> None: ... + def receive(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + def send( # type: ignore[override] + self, text_data: str | None = None, bytes_data: bytes | None = None, close: bool = False + ) -> None: ... + def close(self, code: int | bool | None = None, reason: str | None = None) -> None: ... + def websocket_disconnect(self, message: WebSocketDisconnectEvent) -> None: ... + def disconnect(self, code: int) -> None: ... + +class JsonWebsocketConsumer(WebsocketConsumer): + def receive(self, text_data: str | None = None, bytes_data: bytes | None = None, **kwargs: Any) -> None: ... + # content is typed as Any to match json.loads() return type - JSON can represent + # various Python types (dict, list, str, int, float, bool, None) + def receive_json(self, content: Any, **kwargs: Any) -> None: ... + # content is typed as Any to match json.dumps() input type - accepts any JSON-serializable object + def send_json(self, content: Any, close: bool = False) -> None: ... + @classmethod + def decode_json(cls, text_data: str) -> Any: ... # Returns Any like json.loads() + @classmethod + def encode_json(cls, content: Any) -> str: ... # Accepts Any like json.dumps() + +class AsyncWebsocketConsumer(AsyncConsumer): + groups: list[str] + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + async def websocket_connect(self, message: WebSocketConnectEvent) -> None: ... + async def connect(self) -> None: ... + async def accept(self, subprotocol: str | None = None, headers: list[tuple[str, str]] | None = None) -> None: ... + async def websocket_receive(self, message: WebSocketReceiveEvent) -> None: ... + async def receive(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + async def send( # type: ignore[override] + self, text_data: str | None = None, bytes_data: bytes | None = None, close: bool = False + ) -> None: ... + async def close(self, code: int | bool | None = None, reason: str | None = None) -> None: ... + async def websocket_disconnect(self, message: WebSocketDisconnectEvent) -> None: ... + async def disconnect(self, code: int) -> None: ... + +class AsyncJsonWebsocketConsumer(AsyncWebsocketConsumer): + async def receive(self, text_data: str | None = None, bytes_data: bytes | None = None, **kwargs: Any) -> None: ... + # content is typed as Any to match json.loads() return type - JSON can represent + # various Python types (dict, list, str, int, float, bool, None) + async def receive_json(self, content: Any, **kwargs: Any) -> None: ... + # content is typed as Any to match json.dumps() input type - accepts any JSON-serializable object + async def send_json(self, content: Any, close: bool = False) -> None: ... + @classmethod + async def decode_json(cls, text_data: str) -> Any: ... # Returns Any like json.loads() + @classmethod + async def encode_json(cls, content: Any) -> str: ... # Accepts Any like json.dumps() diff --git a/stubs/channels/channels/layers.pyi b/stubs/channels/channels/layers.pyi new file mode 100644 index 000000000000..a527e5873b7e --- /dev/null +++ b/stubs/channels/channels/layers.pyi @@ -0,0 +1,96 @@ +import asyncio +from re import Pattern +from typing import Any, ClassVar, TypeAlias, overload +from typing_extensions import deprecated + +class ChannelLayerManager: + backends: dict[str, BaseChannelLayer] + + def __init__(self) -> None: ... + @property + def configs(self) -> dict[str, Any]: ... + def make_backend(self, name: str) -> BaseChannelLayer: ... + def make_test_backend(self, name: str) -> Any: ... + def __getitem__(self, key: str) -> BaseChannelLayer: ... + def __contains__(self, key: str) -> bool: ... + def set(self, key: str, layer: BaseChannelLayer) -> BaseChannelLayer | None: ... + +_ChannelCapacityPattern: TypeAlias = Pattern[str] | str +_ChannelCapacityDict: TypeAlias = dict[_ChannelCapacityPattern, int] +_CompiledChannelCapacity: TypeAlias = list[tuple[Pattern[str], int]] + +class BaseChannelLayer: + MAX_NAME_LENGTH: ClassVar[int] = 100 + expiry: int + capacity: int + channel_capacity: _ChannelCapacityDict + channel_name_regex: Pattern[str] + group_name_regex: Pattern[str] + invalid_name_error: str + + def __init__(self, expiry: int = 60, capacity: int = 100, channel_capacity: _ChannelCapacityDict | None = None) -> None: ... + def compile_capacities(self, channel_capacity: _ChannelCapacityDict) -> _CompiledChannelCapacity: ... + def get_capacity(self, channel: str) -> int: ... + + @overload + def match_type_and_length(self, name: str) -> bool: ... + @overload + def match_type_and_length(self, name: object) -> bool: ... + + @overload + def require_valid_channel_name(self, name: str, receive: bool = False) -> bool: ... + @overload + def require_valid_channel_name(self, name: object, receive: bool = False) -> bool: ... + + @overload + def require_valid_group_name(self, name: str) -> bool: ... + @overload + def require_valid_group_name(self, name: object) -> bool: ... + + @overload + def valid_channel_names(self, names: list[str], receive: bool = False) -> bool: ... + @overload + def valid_channel_names(self, names: list[Any], receive: bool = False) -> bool: ... + + def non_local_name(self, name: str) -> str: ... + async def send(self, channel: str, message: dict[str, Any]) -> None: ... + async def receive(self, channel: str) -> dict[str, Any]: ... + async def new_channel(self) -> str: ... + async def flush(self) -> None: ... + async def group_add(self, group: str, channel: str) -> None: ... + async def group_discard(self, group: str, channel: str) -> None: ... + async def group_send(self, group: str, message: dict[str, Any]) -> None: ... + @deprecated("Use require_valid_channel_name instead.") + def valid_channel_name(self, channel_name: str, receive: bool = False) -> bool: ... + @deprecated("Use require_valid_group_name instead.") + def valid_group_name(self, group_name: str) -> bool: ... + +_InMemoryQueueData: TypeAlias = tuple[float, dict[str, Any]] + +class InMemoryChannelLayer(BaseChannelLayer): + channels: dict[str, asyncio.Queue[_InMemoryQueueData]] + groups: dict[str, dict[str, float]] + group_expiry: int + + def __init__( + self, + expiry: int = 60, + group_expiry: int = 86400, + capacity: int = 100, + channel_capacity: _ChannelCapacityDict | None = None, + ) -> None: ... + + extensions: list[str] + + async def send(self, channel: str, message: dict[str, Any]) -> None: ... + async def receive(self, channel: str) -> dict[str, Any]: ... + async def new_channel(self, prefix: str = "specific.") -> str: ... + async def flush(self) -> None: ... + async def close(self) -> None: ... + async def group_add(self, group: str, channel: str) -> None: ... + async def group_discard(self, group: str, channel: str) -> None: ... + async def group_send(self, group: str, message: dict[str, Any]) -> None: ... + +def get_channel_layer(alias: str = "default") -> BaseChannelLayer | None: ... + +channel_layers: ChannelLayerManager diff --git a/stubs/channels/channels/management/__init__.pyi b/stubs/channels/channels/management/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/channels/channels/management/commands/__init__.pyi b/stubs/channels/channels/management/commands/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/channels/channels/management/commands/runworker.pyi b/stubs/channels/channels/management/commands/runworker.pyi new file mode 100644 index 000000000000..533b94cea88d --- /dev/null +++ b/stubs/channels/channels/management/commands/runworker.pyi @@ -0,0 +1,25 @@ +import logging +from _typeshed import Unused +from argparse import ArgumentParser +from typing import TypedDict, type_check_only + +from channels.layers import BaseChannelLayer +from channels.worker import Worker +from django.core.management.base import BaseCommand + +logger: logging.Logger + +@type_check_only +class _RunWorkerCommandOption(TypedDict): + verbosity: int | None + layer: str + channels: list[str] + +class Command(BaseCommand): + leave_locale_alone: bool = True + worker_class: type[Worker] = ... + verbosity: int + channel_layer: BaseChannelLayer + + def add_arguments(self, parser: ArgumentParser) -> None: ... + def handle(self, *args: Unused, **options: _RunWorkerCommandOption) -> None: ... diff --git a/stubs/channels/channels/middleware.pyi b/stubs/channels/channels/middleware.pyi new file mode 100644 index 000000000000..339ae9218244 --- /dev/null +++ b/stubs/channels/channels/middleware.pyi @@ -0,0 +1,12 @@ +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable + +from .consumer import _ChannelScope +from .utils import _ChannelApplication + +class BaseMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/routing.pyi b/stubs/channels/channels/routing.pyi new file mode 100644 index 000000000000..d2a0655d43ce --- /dev/null +++ b/stubs/channels/channels/routing.pyi @@ -0,0 +1,31 @@ +from typing import Any, type_check_only + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable, Scope +from django.urls.resolvers import URLPattern + +from .consumer import _ASGIApplicationProtocol, _ChannelScope +from .utils import _ChannelApplication + +def get_default_application() -> ProtocolTypeRouter: ... + +class ProtocolTypeRouter: + application_mapping: dict[str, _ChannelApplication] + + def __init__(self, application_mapping: dict[str, Any]) -> None: ... + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + +@type_check_only +class _ExtendedURLPattern(URLPattern): + callback: _ASGIApplicationProtocol | URLRouter + +class URLRouter: + routes: list[_ExtendedURLPattern | URLRouter] + + def __init__(self, routes: list[_ExtendedURLPattern | URLRouter]) -> None: ... + async def __call__(self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... + +class ChannelNameRouter: + application_mapping: dict[str, _ChannelApplication] + + def __init__(self, application_mapping: dict[str, _ChannelApplication]) -> None: ... + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> None: ... diff --git a/stubs/channels/channels/security/__init__.pyi b/stubs/channels/channels/security/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/channels/channels/security/websocket.pyi b/stubs/channels/channels/security/websocket.pyi new file mode 100644 index 000000000000..aa76a1b4012e --- /dev/null +++ b/stubs/channels/channels/security/websocket.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Any +from urllib.parse import ParseResult + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.consumer import _ChannelScope +from channels.generic.websocket import AsyncWebsocketConsumer +from channels.utils import _ChannelApplication + +class OriginValidator: + application: _ChannelApplication + allowed_origins: Iterable[str | Pattern[str]] + + def __init__(self, application: _ChannelApplication, allowed_origins: Iterable[str | Pattern[str]]) -> None: ... + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Any: ... + def valid_origin(self, parsed_origin: ParseResult | None) -> bool: ... + def validate_origin(self, parsed_origin: ParseResult | None) -> bool: ... + def match_allowed_origin(self, parsed_origin: ParseResult | None, pattern: str | Pattern[str]) -> bool: ... + def get_origin_port(self, origin: ParseResult | None) -> int | None: ... + +def AllowedHostsOriginValidator(application: _ChannelApplication) -> OriginValidator: ... + +class WebsocketDenier(AsyncWebsocketConsumer): + async def connect(self) -> None: ... diff --git a/stubs/channels/channels/sessions.pyi b/stubs/channels/channels/sessions.pyi new file mode 100644 index 000000000000..04a4eb729535 --- /dev/null +++ b/stubs/channels/channels/sessions.pyi @@ -0,0 +1,56 @@ +import datetime +from collections.abc import Awaitable +from typing import Any + +from asgiref.typing import ASGIReceiveCallable, ASGISendCallable +from channels.consumer import _ChannelScope +from channels.utils import _ChannelApplication +from django.contrib.sessions.backends.base import SessionBase + +class CookieMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + + # Returns the same type as the provided _ChannelApplication. + async def __call__(self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable) -> Any: ... + @classmethod + def set_cookie( + cls, + message: dict[str, Any], + key: str, + value: str = "", + max_age: int | None = None, + expires: str | datetime.datetime | None = None, + path: str = "/", + domain: str | None = None, + secure: bool = False, + httponly: bool = False, + samesite: str = "lax", + ) -> None: ... + @classmethod + def delete_cookie(cls, message: dict[str, Any], key: str, path: str = "/", domain: str | None = None) -> None: ... + +class InstanceSessionWrapper: + save_message_types: list[str] + cookie_response_message_types: list[str] + cookie_name: str + session_store: SessionBase + scope: _ChannelScope + activated: bool + real_send: ASGISendCallable + + def __init__(self, scope: _ChannelScope, send: ASGISendCallable) -> None: ... + async def resolve_session(self) -> None: ... + async def send(self, message: dict[str, Any]) -> Awaitable[None]: ... + async def save_session(self) -> None: ... + +class SessionMiddleware: + inner: _ChannelApplication + + def __init__(self, inner: _ChannelApplication) -> None: ... + async def __call__( + self, scope: _ChannelScope, receive: ASGIReceiveCallable, send: ASGISendCallable + ) -> _ChannelApplication: ... + +def SessionMiddlewareStack(inner: _ChannelApplication) -> _ChannelApplication: ... diff --git a/stubs/channels/channels/testing/__init__.pyi b/stubs/channels/channels/testing/__init__.pyi new file mode 100644 index 000000000000..1cb75a0bf6dd --- /dev/null +++ b/stubs/channels/channels/testing/__init__.pyi @@ -0,0 +1,6 @@ +from .application import ApplicationCommunicator +from .http import HttpCommunicator +from .live import ChannelsLiveServerTestCase +from .websocket import WebsocketCommunicator + +__all__ = ["ApplicationCommunicator", "HttpCommunicator", "ChannelsLiveServerTestCase", "WebsocketCommunicator"] diff --git a/stubs/channels/channels/testing/application.pyi b/stubs/channels/channels/testing/application.pyi new file mode 100644 index 000000000000..db3f567c1d61 --- /dev/null +++ b/stubs/channels/channels/testing/application.pyi @@ -0,0 +1,21 @@ +from typing import Any + +from asgiref.testing import ApplicationCommunicator as BaseApplicationCommunicator + +def no_op() -> None: ... + +class ApplicationCommunicator(BaseApplicationCommunicator): + # ASGI messages are dictionaries with a "type" key and protocol-specific fields. + # Dictionary values can be strings, bytes, lists, or other types depending on the protocol: + # - HTTP: {"type": "http.request", "body": b"request data", "headers": [...], ...} + # - WebSocket: {"type": "websocket.receive", "bytes": b"binary data"} or {"text": "string"} + # - Custom protocols: Application-specific message dictionaries + async def send_input(self, message: dict[str, Any]) -> None: ... + async def receive_output(self, timeout: float = 1) -> dict[str, Any]: ... + + # The following methods are not present in the original source code, + # but are commonly used in practice. Since the base package doesn't + # provide type hints for them, they are added here to improve type correctness. + async def receive_nothing(self, timeout: float = 0.1, interval: float = 0.01) -> bool: ... + async def wait(self, timeout: float = 1) -> None: ... + def stop(self, exceptions: bool = True) -> None: ... diff --git a/stubs/channels/channels/testing/http.pyi b/stubs/channels/channels/testing/http.pyi new file mode 100644 index 000000000000..6eb6650036c8 --- /dev/null +++ b/stubs/channels/channels/testing/http.pyi @@ -0,0 +1,41 @@ +from collections.abc import Iterable +from typing import Literal, TypedDict, type_check_only + +from channels.testing.application import ApplicationCommunicator +from channels.utils import _ChannelApplication + +# HTTP test-specific response type +@type_check_only +class _HTTPTestResponse(TypedDict, total=False): + status: int + headers: Iterable[tuple[bytes, bytes]] + body: bytes + +@type_check_only +class _HTTPTestScope(TypedDict, total=False): + type: Literal["http"] + http_version: str + method: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] | None + client: tuple[str, int] | None + server: tuple[str, int | None] | None + +class HttpCommunicator(ApplicationCommunicator): + scope: _HTTPTestScope + body: bytes + sent_request: bool + + def __init__( + self, + application: _ChannelApplication, + method: str, + path: str, + body: bytes = b"", + headers: Iterable[tuple[bytes, bytes]] | None = None, + ) -> None: ... + async def get_response(self, timeout: float = 1) -> _HTTPTestResponse: ... diff --git a/stubs/channels/channels/testing/live.pyi b/stubs/channels/channels/testing/live.pyi new file mode 100644 index 000000000000..e9f52d6e5e22 --- /dev/null +++ b/stubs/channels/channels/testing/live.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable +from typing import Any, ClassVar, TypeAlias + +from channels.routing import ProtocolTypeRouter +from channels.utils import _ChannelApplication +from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler +from django.test.testcases import TransactionTestCase + +DaphneProcess: TypeAlias = Any # TODO: temporary hack for daphne.testing.DaphneProcess; remove once daphne provides types + +_StaticWrapper: TypeAlias = Callable[[ProtocolTypeRouter], _ChannelApplication] + +def make_application(*, static_wrapper: _StaticWrapper | None) -> Any: ... +def set_database_connection() -> None: ... + +class ChannelsLiveServerTestCase(TransactionTestCase): + host: ClassVar[str] = "localhost" + ProtocolServerProcess: ClassVar[type[DaphneProcess]] = ... + static_wrapper: ClassVar[type[ASGIStaticFilesHandler]] = ... + serve_static: ClassVar[bool] = True + + @property + def live_server_url(self) -> str: ... + @property + def live_server_ws_url(self) -> str: ... diff --git a/stubs/channels/channels/testing/websocket.pyi b/stubs/channels/channels/testing/websocket.pyi new file mode 100644 index 000000000000..9b79d7dc10eb --- /dev/null +++ b/stubs/channels/channels/testing/websocket.pyi @@ -0,0 +1,55 @@ +from collections.abc import Iterable +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import NotRequired + +from asgiref.typing import ASGIVersions +from channels.testing.application import ApplicationCommunicator +from channels.utils import _ChannelApplication + +@type_check_only +class _WebsocketTestScope(TypedDict, total=False): + spec_version: int + type: Literal["websocket"] + asgi: ASGIVersions + http_version: str + scheme: str + path: str + raw_path: bytes + query_string: bytes + root_path: str + headers: Iterable[tuple[bytes, bytes]] | None + client: tuple[str, int] | None + server: tuple[str, int | None] | None + subprotocols: Iterable[str] | None + state: NotRequired[dict[str, Any]] + extensions: dict[str, dict[object, object]] | None + +_Connected: TypeAlias = bool +_CloseCodeOrAcceptSubProtocol: TypeAlias = int | str | None +_WebsocketConnectResponse: TypeAlias = tuple[_Connected, _CloseCodeOrAcceptSubProtocol] + +class WebsocketCommunicator(ApplicationCommunicator): + scope: _WebsocketTestScope + response_headers: list[tuple[bytes, bytes]] | None + + def __init__( + self, + application: _ChannelApplication, + path: str, + headers: Iterable[tuple[bytes, bytes]] | None = None, + subprotocols: Iterable[str] | None = None, + spec_version: int | None = None, + ) -> None: ... + async def connect(self, timeout: float = 1) -> _WebsocketConnectResponse: ... + async def send_to(self, text_data: str | None = None, bytes_data: bytes | None = None) -> None: ... + async def receive_from(self, timeout: float = 1) -> str | bytes: ... + + # These overloads reflect common usage, where users typically send and receive `dict[str, Any]`. + # The base case allows `Any` to support broader `json.dumps` / `json.loads` compatibility. + @overload + async def send_json_to(self, data: dict[str, Any]) -> None: ... + @overload + async def send_json_to(self, data: Any) -> None: ... + + async def receive_json_from(self, timeout: float = 1) -> Any: ... + async def disconnect(self, code: int = 1000, timeout: float = 1) -> None: ... diff --git a/stubs/channels/channels/utils.pyi b/stubs/channels/channels/utils.pyi new file mode 100644 index 000000000000..80b4dff1a902 --- /dev/null +++ b/stubs/channels/channels/utils.pyi @@ -0,0 +1,19 @@ +from collections.abc import Awaitable, Callable +from typing import Any, Protocol, TypeAlias, type_check_only + +from asgiref.typing import ASGIApplication, ASGIReceiveCallable + +def name_that_thing(thing: object) -> str: ... +async def await_many_dispatch( + consumer_callables: list[Callable[[], Awaitable[ASGIReceiveCallable]]], dispatch: Callable[[dict[str, Any]], Awaitable[None]] +) -> None: ... + +# Defines a generic ASGI middleware protocol. +# All arguments are typed as `Any` to maximize compatibility with third-party ASGI middleware +# that may not strictly follow type conventions or use more specific signatures. +@type_check_only +class _MiddlewareProtocol(Protocol): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + async def __call__(self, scope: Any, receive: Any, send: Any) -> Any: ... + +_ChannelApplication: TypeAlias = _MiddlewareProtocol | ASGIApplication # noqa: Y047 diff --git a/stubs/channels/channels/worker.pyi b/stubs/channels/channels/worker.pyi new file mode 100644 index 000000000000..a20b5feec275 --- /dev/null +++ b/stubs/channels/channels/worker.pyi @@ -0,0 +1,13 @@ +from asgiref.server import StatelessServer +from channels.layers import BaseChannelLayer +from channels.utils import _ChannelApplication + +class Worker(StatelessServer): + channels: list[str] + channel_layer: BaseChannelLayer + + def __init__( + self, application: _ChannelApplication, channels: list[str], channel_layer: BaseChannelLayer, max_applications: int = 1000 + ) -> None: ... + async def handle(self) -> None: ... + async def listener(self, channel: str) -> None: ... diff --git a/stubs/chevron/METADATA.toml b/stubs/chevron/METADATA.toml new file mode 100755 index 000000000000..83c82dbd7688 --- /dev/null +++ b/stubs/chevron/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.14.*" +upstream-repository = "https://github.com/noahmorrison/chevron" + +[tool.stubtest] diff --git a/stubs/chevron/chevron/__init__.pyi b/stubs/chevron/chevron/__init__.pyi new file mode 100644 index 000000000000..472809791640 --- /dev/null +++ b/stubs/chevron/chevron/__init__.pyi @@ -0,0 +1,5 @@ +from .main import cli_main as cli_main, main as main +from .renderer import render as render +from .tokenizer import ChevronError as ChevronError + +__all__ = ["main", "render", "cli_main", "ChevronError"] diff --git a/stubs/chevron/chevron/main.pyi b/stubs/chevron/chevron/main.pyi new file mode 100644 index 000000000000..c12595aaeed5 --- /dev/null +++ b/stubs/chevron/chevron/main.pyi @@ -0,0 +1,5 @@ +from _typeshed import FileDescriptorOrPath +from typing import Any + +def main(template: FileDescriptorOrPath, data: FileDescriptorOrPath | None = None, **kwargs: Any) -> str: ... +def cli_main() -> None: ... diff --git a/stubs/chevron/chevron/metadata.pyi b/stubs/chevron/chevron/metadata.pyi new file mode 100644 index 000000000000..c2ee2cab489b --- /dev/null +++ b/stubs/chevron/chevron/metadata.pyi @@ -0,0 +1 @@ +version: str diff --git a/stubs/chevron/chevron/renderer.pyi b/stubs/chevron/chevron/renderer.pyi new file mode 100644 index 000000000000..274a4719f602 --- /dev/null +++ b/stubs/chevron/chevron/renderer.pyi @@ -0,0 +1,22 @@ +from _typeshed import StrPath, SupportsRead +from collections.abc import MutableSequence, Sequence +from typing import Any, Literal + +g_token_cache: dict[str, list[tuple[str, str]]] # undocumented +python3: Literal[True] +string_type = str +unicode_type = str + +def unicode(x: str, y: str) -> str: ... +def render( + template: SupportsRead[str] | str | Sequence[tuple[str, str]] = "", + data: dict[str, Any] = {}, + partials_path: StrPath | None = ".", + partials_ext: str = "mustache", + partials_dict: dict[str, str] = {}, + padding: str = "", + def_ldel: str | None = "{{", + def_rdel: str | None = "}}", + scopes: MutableSequence[int] | None = None, + warn: bool = False, +) -> str: ... diff --git a/stubs/chevron/chevron/tokenizer.pyi b/stubs/chevron/chevron/tokenizer.pyi new file mode 100644 index 000000000000..1103c68c2d35 --- /dev/null +++ b/stubs/chevron/chevron/tokenizer.pyi @@ -0,0 +1,11 @@ +from collections.abc import Iterator + +class ChevronError(SyntaxError): ... + +def grab_literal(template: str, l_del: str | None) -> tuple[str, str]: ... # undocumented +def l_sa_check(template: str, literal: str, is_standalone: bool) -> bool | None: ... # undocumented +def r_sa_check(template: str, tag_type: str, is_standalone: bool) -> bool: ... # undocumented +def parse_tag(template: str, l_del: str | None, r_del: str | None) -> tuple[tuple[str, str], str]: ... # undocumented +def tokenize( + template: str, def_ldel: str | None = "{{", def_rdel: str | None = "}}" +) -> Iterator[tuple[str, str]]: ... # undocumented diff --git a/stubs/click-default-group/METADATA.toml b/stubs/click-default-group/METADATA.toml new file mode 100644 index 000000000000..d59ab76ab915 --- /dev/null +++ b/stubs/click-default-group/METADATA.toml @@ -0,0 +1,4 @@ +version = "1.2.*" +upstream-repository = "https://github.com/click-contrib/click-default-group" +# requires a version of click with a py.typed +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-default-group/click_default_group.pyi b/stubs/click-default-group/click_default_group.pyi new file mode 100644 index 000000000000..28a6ebedce2d --- /dev/null +++ b/stubs/click-default-group/click_default_group.pyi @@ -0,0 +1,84 @@ +from collections.abc import Callable, MutableMapping, Sequence +from typing import Any, Final, Literal, overload +from typing_extensions import deprecated + +import click + +__all__ = ["DefaultGroup"] +__version__: Final[str] + +class DefaultGroup(click.Group): + ignore_unknown_options: bool + default_cmd_name: str | None + default_if_no_args: bool + # type hints were taken from click lib + def __init__( + self, + name: str | None = None, + commands: MutableMapping[str, click.Command] | Sequence[click.Command] | None = None, + *, + ignore_unknown_options: Literal[True] | None = True, + default: str | None = None, + default_if_no_args: bool = False, + invoke_without_command: bool = False, + no_args_is_help: bool | None = None, + subcommand_metavar: str | None = None, + chain: bool = False, + result_callback: Callable[..., Any] | None = None, # Any is specified in click lib + context_settings: MutableMapping[str, Any] | None = None, # Any is specified in click lib + callback: Callable[..., Any] | None = None, # Any is specified in click lib + params: list[click.Parameter] | None = None, + help: str | None = None, + epilog: str | None = None, + short_help: str | None = None, + options_metavar: str | None = "[OPTIONS]", + add_help_option: bool = True, + hidden: bool = False, + deprecated: bool = False, + ) -> None: ... + def set_default_command(self, command: click.Command) -> None: ... + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: ... + def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None: ... + def resolve_command(self, ctx: click.Context, args: list[str]) -> tuple[str | None, click.Command | None, list[str]]: ... + def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None: ... + + @overload + def command( + self, + __func: Callable[..., Any], + /, + *, + name: str | None = ..., + cls: type[click.Command] | None = ..., + default: Literal[False] = False, + ) -> click.Command: ... + @overload + @deprecated("Use default param of `DefaultGroup` or `set_default_command()` instead") + def command( + self, + __func: Callable[..., Any], + /, + *, + name: str | None = ..., + cls: type[click.Command] | None = ..., + default: Literal[True], + ) -> click.Command: ... + @overload + def command( + self, *, name: str | None = ..., cls: type[click.Command] | None = ..., default: Literal[False] = False + ) -> Callable[[Callable[..., Any]], click.Command]: ... + @overload + @deprecated("Use default param of `DefaultGroup` or `set_default_command()` instead") + def command( + self, *, name: str | None = ..., cls: type[click.Command] | None = ..., default: Literal[True] + ) -> Callable[[Callable[..., Any]], click.Command]: ... + @overload + def command(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], click.Command] | click.Command: ... + +class DefaultCommandFormatter: + group: click.Group + formatter: click.HelpFormatter + mark: str + def __init__(self, group: click.Group, formatter: click.HelpFormatter, mark: str = "*") -> None: ... + def write_dl(self, rows: Sequence[tuple[str, str]], col_max: int = 30, col_spacing: int = -2) -> None: ... + def __getattr__(self, attr: str) -> Any: ... # attribute access is forwarded to click.HelpFormatter diff --git a/stubs/click-log/METADATA.toml b/stubs/click-log/METADATA.toml new file mode 100644 index 000000000000..af9b07a4091b --- /dev/null +++ b/stubs/click-log/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.4.*" +upstream-repository = "https://github.com/click-contrib/click-log" +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-log/click_log/__init__.pyi b/stubs/click-log/click_log/__init__.pyi new file mode 100644 index 000000000000..b3d38f6720c0 --- /dev/null +++ b/stubs/click-log/click_log/__init__.pyi @@ -0,0 +1,4 @@ +from .core import ClickHandler as ClickHandler, ColorFormatter as ColorFormatter, basic_config as basic_config +from .options import simple_verbosity_option as simple_verbosity_option + +__version__: str diff --git a/stubs/click-log/click_log/core.pyi b/stubs/click-log/click_log/core.pyi new file mode 100644 index 000000000000..8ee5d99e3596 --- /dev/null +++ b/stubs/click-log/click_log/core.pyi @@ -0,0 +1,15 @@ +import logging + +LOGGER_KEY: str +DEFAULT_LEVEL: int +PY2: bool +text_type: type + +class ColorFormatter(logging.Formatter): + colors: dict[str, dict[str, str]] + def format(self, record: logging.LogRecord) -> str: ... + +class ClickHandler(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: ... + +def basic_config(logger: logging.Logger | str | None = None) -> None: ... diff --git a/stubs/click-log/click_log/options.pyi b/stubs/click-log/click_log/options.pyi new file mode 100644 index 000000000000..cea9e5edd8ea --- /dev/null +++ b/stubs/click-log/click_log/options.pyi @@ -0,0 +1,10 @@ +import logging +from collections.abc import Callable +from typing import Any, TypeAlias, TypeVar + +import click + +_AnyCallable: TypeAlias = Callable[..., Any] +_FC = TypeVar("_FC", bound=_AnyCallable | click.Command) + +def simple_verbosity_option(logger: logging.Logger | str | None = None, *names: str, **kwargs: Any) -> Callable[[_FC], _FC]: ... diff --git a/stubs/click-shell/METADATA.toml b/stubs/click-shell/METADATA.toml new file mode 100644 index 000000000000..6d8aa15caf14 --- /dev/null +++ b/stubs/click-shell/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.1" +upstream-repository = "https://github.com/clarkperkins/click-shell" +dependencies = ["click>=8.0.0"] diff --git a/stubs/click-shell/click_shell/__init__.pyi b/stubs/click-shell/click_shell/__init__.pyi new file mode 100644 index 000000000000..38ef48feb91b --- /dev/null +++ b/stubs/click-shell/click_shell/__init__.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from .core import Shell as Shell, make_click_shell as make_click_shell +from .decorators import shell as shell + +__all__ = ["make_click_shell", "shell", "Shell", "__version__"] +__version__: Final[str] diff --git a/stubs/click-shell/click_shell/_cmd.pyi b/stubs/click-shell/click_shell/_cmd.pyi new file mode 100644 index 000000000000..c6848e48928e --- /dev/null +++ b/stubs/click-shell/click_shell/_cmd.pyi @@ -0,0 +1,28 @@ +from cmd import Cmd +from collections.abc import Callable +from typing import Any, ClassVar, TextIO + +import click + +class ClickCmd(Cmd): + nocommand: ClassVar[str] + def __init__( + self, + ctx: click.Context | None = None, + on_finished: Callable[[click.Context], None] | None = None, + hist_file: str | None = None, + completekey: str = "tab", + stdin: TextIO | None = None, + stdout: TextIO | None = None, + ) -> None: ... + def preloop(self) -> None: ... + def postloop(self) -> None: ... + def cmdloop(self, intro: str | None = None) -> None: ... + def get_prompt(self) -> str | None: ... + def emptyline(self) -> bool: ... + def default(self, line: str) -> None: ... + def get_names(self) -> list[str]: ... + def do_help(self, arg: str) -> None: ... + def do_quit(self, arg: str) -> bool: ... + def do_exit(self, arg: str) -> bool: ... + def print_topics(self, header: Any, cmds: list[str] | None, cmdlen: int, maxcol: int) -> None: ... diff --git a/stubs/click-shell/click_shell/_compat.pyi b/stubs/click-shell/click_shell/_compat.pyi new file mode 100644 index 000000000000..c383de4ff97c --- /dev/null +++ b/stubs/click-shell/click_shell/_compat.pyi @@ -0,0 +1,10 @@ +import types +from collections.abc import Callable +from typing import Any, Final + +import click + +PY2: Final = False + +def get_method_type(func: Callable[..., Any], obj: object) -> types.MethodType: ... +def get_choices(cli: click.Command, prog_name: str, args: list[str], incomplete: str) -> list[str]: ... diff --git a/stubs/click-shell/click_shell/core.pyi b/stubs/click-shell/click_shell/core.pyi new file mode 100644 index 000000000000..673c0c69464d --- /dev/null +++ b/stubs/click-shell/click_shell/core.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from logging import Logger +from typing import Any + +import click + +from ._cmd import ClickCmd + +logger: Logger + +def get_invoke(command: click.Command) -> Callable[[ClickCmd, str], bool]: ... +def get_help(command: click.Command) -> Callable[[ClickCmd], None]: ... +def get_complete(command: click.Command) -> Callable[[ClickCmd, str, str, int, int], list[str]]: ... + +class ClickShell(ClickCmd): + def add_command(self, cmd: click.Command, name: str) -> None: ... + +def make_click_shell( + ctx: click.Context, + prompt: str | Callable[[], str] | Callable[[click.Context, str], str] | None = None, + intro: str | None = None, + hist_file: str | None = None, +) -> ClickShell: ... + +class Shell(click.Group): + def __init__( + self, + prompt: str | Callable[[], str] | Callable[[click.Context, str], str] | None = None, + intro: str | None = None, + hist_file: str | None = None, + on_finished: Callable[[click.Context], None] | None = None, + **attrs: Any, + ) -> None: ... + def add_command(self, cmd: click.Command, name: str | None = None) -> None: ... + def invoke(self, ctx: click.Context) -> Any: ... diff --git a/stubs/click-shell/click_shell/decorators.pyi b/stubs/click-shell/click_shell/decorators.pyi new file mode 100644 index 000000000000..ce72f74fbd6e --- /dev/null +++ b/stubs/click-shell/click_shell/decorators.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import Any + +from click.decorators import _AnyCallable + +from .core import Shell + +def shell(name: str | None = None, **attrs: Any) -> Callable[[_AnyCallable], Shell]: ... diff --git a/stubs/click-spinner/METADATA.toml b/stubs/click-spinner/METADATA.toml new file mode 100644 index 000000000000..57e844258422 --- /dev/null +++ b/stubs/click-spinner/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.1.11" +upstream-repository = "https://github.com/click-contrib/click-spinner" +obsolete-since = { version = "0.2.0", date = "2026-06-23" } diff --git a/stubs/click-spinner/click_spinner/__init__.pyi b/stubs/click-spinner/click_spinner/__init__.pyi new file mode 100644 index 000000000000..6b576256729a --- /dev/null +++ b/stubs/click-spinner/click_spinner/__init__.pyi @@ -0,0 +1,32 @@ +import threading +from collections.abc import Iterator +from types import TracebackType +from typing import Final, Literal, Protocol, type_check_only +from typing_extensions import Self + +__version__: Final[str] + +@type_check_only +class _Stream(Protocol): + def isatty(self) -> bool: ... + def flush(self) -> None: ... + def write(self, s: str, /) -> int: ... + +class Spinner: + spinner_cycle: Iterator[str] + disable: bool + beep: bool + force: bool + stream: _Stream + stop_running: threading.Event | None + spin_thread: threading.Thread | None + def __init__(self, beep: bool = False, disable: bool = False, force: bool = False, stream: _Stream = ...) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def init_spin(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> Literal[False]: ... + +def spinner(beep: bool = False, disable: bool = False, force: bool = False, stream: _Stream = ...) -> Spinner: ... diff --git a/stubs/click-web/METADATA.toml b/stubs/click-web/METADATA.toml new file mode 100644 index 000000000000..b155c1e542e9 --- /dev/null +++ b/stubs/click-web/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.8.*" +upstream-repository = "https://github.com/fredrik-corneliusson/click-web" +dependencies = ["click>=8.0.0", "Flask>=2.3.2"] diff --git a/stubs/click-web/click_web/__init__.pyi b/stubs/click-web/click_web/__init__.pyi new file mode 100644 index 000000000000..3f97be32e833 --- /dev/null +++ b/stubs/click-web/click_web/__init__.pyi @@ -0,0 +1,16 @@ +import logging +import types +from _typeshed import Incomplete + +import click +import flask + +# This should be jinja2.Environment, but it does not have stubs and forbidden for requires in METADATA.toml +jinja_env: Incomplete +script_file: str | None +click_root_cmd: str | None +OUTPUT_FOLDER: str +_flask_app: flask.Flask | None +logger: logging.Logger | None + +def create_click_web_app(module: types.ModuleType, command: click.Command, root: str = "/") -> flask.Flask: ... diff --git a/stubs/click-web/click_web/exceptions.pyi b/stubs/click-web/click_web/exceptions.pyi new file mode 100644 index 000000000000..172a2026a871 --- /dev/null +++ b/stubs/click-web/click_web/exceptions.pyi @@ -0,0 +1,2 @@ +class ClickWebException(Exception): ... +class CommandNotFound(ClickWebException): ... diff --git a/stubs/click-web/click_web/resources/__init__.pyi b/stubs/click-web/click_web/resources/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/click-web/click_web/resources/cmd_exec.pyi b/stubs/click-web/click_web/resources/cmd_exec.pyi new file mode 100644 index 000000000000..b1121b450b8d --- /dev/null +++ b/stubs/click-web/click_web/resources/cmd_exec.pyi @@ -0,0 +1,93 @@ +import logging +from collections.abc import Generator +from typing import ClassVar, Final + +from flask import Response + +from .input_fields import FieldId + +logger: logging.Logger | None + +HTML_HEAD: Final[str] +HTML_TAIL: Final[str] + +class Executor: + RAW_CMD_PATH: ClassVar[str] + returncode: int | None + + def __init__(self) -> None: ... + def exec(self, command_path: str) -> Response: ... + def _exec_raw(self, command: list[str]) -> Response: ... # undocumented + def _exec_html(self, command_path: str) -> Response: ... # undocumented + def _run_script_and_generate_stream(self) -> Generator[str]: ... # undocumented + def _create_cmd_header(self, commands: list[CmdPart]) -> str: ... # undocumented + def _create_result_footer(self) -> Generator[str]: ... # undocumented + +def _get_download_link(field_info: FieldFileInfo) -> str: ... # undocumented + +class CommandLineRaw: + def __init__(self, script_file_path: str, command: str) -> None: ... + def append(self, part: str, secret: bool = False) -> None: ... + def get_commandline(self, obfuscate: bool = False) -> list[str]: ... + def get_download_field_infos(self) -> list[FieldInfo]: ... + def after_script_executed(self) -> None: ... + +class CommandLineForm: + command_line_bulder: FormToCommandLineBuilder + def __init__(self, script_file_path: str, commands: list[str]) -> None: ... + def append(self, part: str, secret: bool = False) -> None: ... + def get_commandline(self, obfuscate: bool = False) -> list[str]: ... + def get_download_field_infos(self) -> list[FieldInfo]: ... + def after_script_executed(self) -> None: ... + +def _get_python_interpreter() -> str: ... + +class CmdPart: + def __init__(self, part: str, secret: bool = False) -> None: ... + +class FormToCommandLineBuilder: + def __init__(self, command_line: CommandLineForm) -> None: ... + def add_command_args(self, command_index: int) -> None: ... + @staticmethod + def _is_option(cmd_option: str) -> bool: ... + def _process_option(self, field_info: FieldInfo) -> None: ... + +class FieldInfo: + param: FieldId + key: str + is_file: bool + cmd_opt: str + generate_download_link: bool + @staticmethod + def factory(key: str) -> FieldInfo: ... + def __init__(self, param: FieldId) -> None: ... + def before_script_execute(self) -> None: ... + def after_script_executed(self) -> None: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class FieldFileInfo(FieldInfo): + mode: str + generate_download_link: bool + link_name: str + file_path: str + def __init__(self, fimeta: FieldId) -> None: ... + def before_script_execute(self) -> None: ... + @classmethod + def temp_dir(cls) -> str: ... + def save(self) -> None: ... + +class FieldOutFileInfo(FieldFileInfo): + file_suffix: str + def __init__(self, fimeta: FieldId) -> None: ... + def save(self) -> None: ... + +class FieldPathInfo(FieldFileInfo): + def save(self) -> None: ... + def after_script_executed(self) -> None: ... + +class FieldPathOutInfo(FieldOutFileInfo): + def save(self) -> None: ... + def after_script_executed(self) -> None: ... + +def zip_folder(folder_path: str, out_folder: str, out_prefix: str) -> str: ... diff --git a/stubs/click-web/click_web/resources/cmd_form.pyi b/stubs/click-web/click_web/resources/cmd_form.pyi new file mode 100644 index 000000000000..d3f3ed573489 --- /dev/null +++ b/stubs/click-web/click_web/resources/cmd_form.pyi @@ -0,0 +1,13 @@ +from typing import Any, TypedDict, type_check_only + +import click + +@type_check_only +class _FormData(TypedDict): + command: click.Command + fields: list[dict[str, Any]] # each item is result of resources.input_fields.get_input_field() function + +def get_form_for(command_path: str) -> str: ... +def _get_commands_by_path(command_path: str) -> list[tuple[click.Context, click.Command]]: ... +def _generate_form_data(ctx_and_commands: list[tuple[click.Context, click.Command]]) -> list[_FormData]: ... +def _process_help(help_text: bool) -> str: ... diff --git a/stubs/click-web/click_web/resources/index.pyi b/stubs/click-web/click_web/resources/index.pyi new file mode 100644 index 000000000000..c0f3aebbbdf8 --- /dev/null +++ b/stubs/click-web/click_web/resources/index.pyi @@ -0,0 +1,9 @@ +from collections import OrderedDict +from typing import Any + +import click + +def index() -> str: ... +def _click_to_tree( + ctx: click.Context, node: click.Command, ancestors: list[click.Command] | None = None +) -> OrderedDict[str, Any]: ... diff --git a/stubs/click-web/click_web/resources/input_fields.pyi b/stubs/click-web/click_web/resources/input_fields.pyi new file mode 100644 index 000000000000..a1465ff56b70 --- /dev/null +++ b/stubs/click-web/click_web/resources/input_fields.pyi @@ -0,0 +1,81 @@ +from typing import Any, ClassVar, Final + +import click +from click_web.web_click_types import EmailParamType, PasswordParamType, TextAreaParamType + +class FieldId: + SEPARATOR: ClassVar[str] + command_index: int + param_index: int + param_type: str + click_type: str + nargs: int + form_type: str + name: str + key: str + + def __init__( + self, + command_index: int, + param_index: int, + param_type: str, + click_type: str, + nargs: int, + form_type: str, + name: str, + key: str | None = None, + ) -> None: ... + @classmethod + def from_string(cls, field_info_as_string: str) -> FieldId: ... + +class NotSupported(ValueError): ... + +class BaseInput: + param_type_cls: type[click.types.ParamType[Any]] | None + ctx: click.Context + param: click.Parameter + command_index: int + param_index: int + def __init__(self, ctx: click.Context, param: click.Parameter, command_index: int, param_index: int) -> None: ... + def is_supported(self) -> bool: ... + @property + def fields(self) -> dict[str, Any]: ... + @property + def type_attrs(self) -> dict[str, Any]: ... + def _to_cmd_line_name(self, name: str) -> str: ... + def _build_name(self, name: str) -> str: ... + +class ChoiceInput(BaseInput): + param_type_cls: type[click.Choice[Any]] + +class FlagInput(BaseInput): + param_type_cls: None + +class IntInput(BaseInput): + param_type_cls: type[click.types.IntParamType] + +class FloatInput(BaseInput): + param_type_cls: type[click.types.FloatParamType] + +class FolderInput(BaseInput): + param_type_cls: None + +class FileInput(BaseInput): + param_type_cls: None + +class EmailInput(BaseInput): + param_type_cls: type[EmailParamType] + +class PasswordInput(BaseInput): + param_type_cls: type[PasswordParamType] + +class TextAreaInput(BaseInput): + param_type_cls: type[TextAreaParamType] + +class DefaultInput(BaseInput): + param_type_cls: type[click.ParamType[Any]] + +INPUT_TYPES: Final[list[type[BaseInput]]] +_DEFAULT_INPUT: Final[list[type[DefaultInput]]] + +def get_input_field(ctx: click.Context, param: click.Parameter, command_index: int, param_index: int) -> dict[str, Any]: ... diff --git a/stubs/click-web/click_web/web_click_types.pyi b/stubs/click-web/click_web/web_click_types.pyi new file mode 100644 index 000000000000..db072f3cbc3a --- /dev/null +++ b/stubs/click-web/click_web/web_click_types.pyi @@ -0,0 +1,20 @@ +import re +from typing import Any, ClassVar, TypeVar + +import click + +_T = TypeVar("_T") + +class EmailParamType(click.ParamType[str]): + EMAIL_REGEX: ClassVar[re.Pattern[str]] + def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str: ... + +class PasswordParamType(click.ParamType[Any]): + def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ... + +class TextAreaParamType(click.ParamType[Any]): + def convert(self, value: _T, param: click.Parameter | None, ctx: click.Context | None) -> _T: ... + +EMAIL_TYPE: EmailParamType +PASSWORD_TYPE: PasswordParamType +TEXTAREA_TYPE: TextAreaParamType diff --git a/stubs/colorama/@tests/stubtest_allowlist.txt b/stubs/colorama/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..cee2f1962bb5 --- /dev/null +++ b/stubs/colorama/@tests/stubtest_allowlist.txt @@ -0,0 +1,46 @@ +# These are defined as ints, but later are converted to strings via magic: +colorama.ansi.AnsiBack.BLACK +colorama.ansi.AnsiBack.BLUE +colorama.ansi.AnsiBack.CYAN +colorama.ansi.AnsiBack.GREEN +colorama.ansi.AnsiBack.LIGHTBLACK_EX +colorama.ansi.AnsiBack.LIGHTBLUE_EX +colorama.ansi.AnsiBack.LIGHTCYAN_EX +colorama.ansi.AnsiBack.LIGHTGREEN_EX +colorama.ansi.AnsiBack.LIGHTMAGENTA_EX +colorama.ansi.AnsiBack.LIGHTRED_EX +colorama.ansi.AnsiBack.LIGHTWHITE_EX +colorama.ansi.AnsiBack.LIGHTYELLOW_EX +colorama.ansi.AnsiBack.MAGENTA +colorama.ansi.AnsiBack.RED +colorama.ansi.AnsiBack.RESET +colorama.ansi.AnsiBack.WHITE +colorama.ansi.AnsiBack.YELLOW +colorama.ansi.AnsiFore.BLACK +colorama.ansi.AnsiFore.BLUE +colorama.ansi.AnsiFore.CYAN +colorama.ansi.AnsiFore.GREEN +colorama.ansi.AnsiFore.LIGHTBLACK_EX +colorama.ansi.AnsiFore.LIGHTBLUE_EX +colorama.ansi.AnsiFore.LIGHTCYAN_EX +colorama.ansi.AnsiFore.LIGHTGREEN_EX +colorama.ansi.AnsiFore.LIGHTMAGENTA_EX +colorama.ansi.AnsiFore.LIGHTRED_EX +colorama.ansi.AnsiFore.LIGHTWHITE_EX +colorama.ansi.AnsiFore.LIGHTYELLOW_EX +colorama.ansi.AnsiFore.MAGENTA +colorama.ansi.AnsiFore.RED +colorama.ansi.AnsiFore.RESET +colorama.ansi.AnsiFore.WHITE +colorama.ansi.AnsiFore.YELLOW +colorama.ansi.AnsiStyle.BRIGHT +colorama.ansi.AnsiStyle.DIM +colorama.ansi.AnsiStyle.NORMAL +colorama.ansi.AnsiStyle.RESET_ALL + +# These are defined as None, but on initialization are set to correct values: +colorama.initialise.wrapped_stderr +colorama.initialise.wrapped_stdout + +# Not planning on writing stubs for tests: +colorama.tests.* diff --git a/stubs/colorama/@tests/stubtest_allowlist_linux.txt b/stubs/colorama/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..8bd292ef088e --- /dev/null +++ b/stubs/colorama/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,4 @@ +# These are only available on Windows: +colorama.winterm.WinColor +colorama.winterm.WinStyle +colorama.winterm.WinTerm diff --git a/stubs/colorama/METADATA.toml b/stubs/colorama/METADATA.toml new file mode 100644 index 000000000000..42172a31b734 --- /dev/null +++ b/stubs/colorama/METADATA.toml @@ -0,0 +1,5 @@ +version = "0.4.*" +upstream-repository = "https://github.com/tartley/colorama" + +[tool.stubtest] +ci-platforms = ["linux", "win32"] diff --git a/stubs/colorama/colorama/__init__.pyi b/stubs/colorama/colorama/__init__.pyi new file mode 100644 index 000000000000..e6d15ec71ddb --- /dev/null +++ b/stubs/colorama/colorama/__init__.pyi @@ -0,0 +1,9 @@ +from .ansi import Back as Back, Cursor as Cursor, Fore as Fore, Style as Style +from .ansitowin32 import AnsiToWin32 as AnsiToWin32 +from .initialise import ( + colorama_text as colorama_text, + deinit as deinit, + init as init, + just_fix_windows_console as just_fix_windows_console, + reinit as reinit, +) diff --git a/stubs/colorama/colorama/ansi.pyi b/stubs/colorama/colorama/ansi.pyi new file mode 100644 index 000000000000..3b857496e6d3 --- /dev/null +++ b/stubs/colorama/colorama/ansi.pyi @@ -0,0 +1,69 @@ +CSI: str +OSC: str +BEL: str + +def code_to_chars(code: int) -> str: ... +def set_title(title: str) -> str: ... +def clear_screen(mode: int = 2) -> str: ... +def clear_line(mode: int = 2) -> str: ... + +class AnsiCodes: + def __init__(self) -> None: ... + +class AnsiCursor: + def UP(self, n: int = 1) -> str: ... + def DOWN(self, n: int = 1) -> str: ... + def FORWARD(self, n: int = 1) -> str: ... + def BACK(self, n: int = 1) -> str: ... + def POS(self, x: int = 1, y: int = 1) -> str: ... + +# All attributes in the following classes are string in instances and int in the class. +# We use str since that is the common case for users. +class AnsiFore(AnsiCodes): + BLACK: str + RED: str + GREEN: str + YELLOW: str + BLUE: str + MAGENTA: str + CYAN: str + WHITE: str + RESET: str + LIGHTBLACK_EX: str + LIGHTRED_EX: str + LIGHTGREEN_EX: str + LIGHTYELLOW_EX: str + LIGHTBLUE_EX: str + LIGHTMAGENTA_EX: str + LIGHTCYAN_EX: str + LIGHTWHITE_EX: str + +class AnsiBack(AnsiCodes): + BLACK: str + RED: str + GREEN: str + YELLOW: str + BLUE: str + MAGENTA: str + CYAN: str + WHITE: str + RESET: str + LIGHTBLACK_EX: str + LIGHTRED_EX: str + LIGHTGREEN_EX: str + LIGHTYELLOW_EX: str + LIGHTBLUE_EX: str + LIGHTMAGENTA_EX: str + LIGHTCYAN_EX: str + LIGHTWHITE_EX: str + +class AnsiStyle(AnsiCodes): + BRIGHT: str + DIM: str + NORMAL: str + RESET_ALL: str + +Fore: AnsiFore +Back: AnsiBack +Style: AnsiStyle +Cursor: AnsiCursor diff --git a/stubs/colorama/colorama/ansitowin32.pyi b/stubs/colorama/colorama/ansitowin32.pyi new file mode 100644 index 000000000000..e32fec9d33c3 --- /dev/null +++ b/stubs/colorama/colorama/ansitowin32.pyi @@ -0,0 +1,53 @@ +import sys +from _typeshed import SupportsWrite +from collections.abc import Callable, Sequence +from re import Pattern +from types import TracebackType +from typing import Any, ClassVar, TextIO, TypeAlias + +if sys.platform == "win32": + from .winterm import WinTerm + + winterm: WinTerm +else: + winterm: None + +class StreamWrapper: + def __init__(self, wrapped: TextIO, converter: SupportsWrite[str]) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self, *args: object, **kwargs: object) -> TextIO: ... + def __exit__( + self, t: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, /, **kwargs: Any + ) -> None: ... + def write(self, text: str) -> None: ... + def isatty(self) -> bool: ... + @property + def closed(self) -> bool: ... + +_WinTermCall: TypeAlias = Callable[[int | None, bool, bool], None] +_WinTermCallDict: TypeAlias = dict[int, tuple[_WinTermCall] | tuple[_WinTermCall, int] | tuple[_WinTermCall, int, bool]] + +class AnsiToWin32: + ANSI_CSI_RE: ClassVar[Pattern[str]] + ANSI_OSC_RE: ClassVar[Pattern[str]] + wrapped: TextIO + autoreset: bool + stream: StreamWrapper + strip: bool + convert: bool + win32_calls: _WinTermCallDict + on_stderr: bool + def __init__( + self, wrapped: TextIO, convert: bool | None = None, strip: bool | None = None, autoreset: bool = False + ) -> None: ... + def should_wrap(self) -> bool: ... + def get_win32_calls(self) -> _WinTermCallDict: ... + def write(self, text: str) -> None: ... + def reset_all(self) -> None: ... + def write_and_convert(self, text: str) -> None: ... + def write_plain_text(self, text: str, start: int, end: int) -> None: ... + def convert_ansi(self, paramstring: str, command: str) -> None: ... + def extract_params(self, command: str, paramstring: str) -> tuple[int, ...]: ... + def call_win32(self, command: str, params: Sequence[int]) -> None: ... + def convert_osc(self, text: str) -> str: ... + def flush(self) -> None: ... diff --git a/stubs/colorama/colorama/initialise.pyi b/stubs/colorama/colorama/initialise.pyi new file mode 100644 index 000000000000..028b981307c8 --- /dev/null +++ b/stubs/colorama/colorama/initialise.pyi @@ -0,0 +1,23 @@ +from contextlib import AbstractContextManager +from typing import Any, TextIO, TypeVar + +from .ansitowin32 import StreamWrapper + +_TextIOT = TypeVar("_TextIOT", bound=TextIO) + +orig_stdout: TextIO | None +orig_stderr: TextIO | None +wrapped_stdout: TextIO | StreamWrapper +wrapped_stderr: TextIO | StreamWrapper +atexit_done: bool +fixed_windows_console: bool + +def reset_all() -> None: ... +def init(autoreset: bool = False, convert: bool | None = None, strip: bool | None = None, wrap: bool = True) -> None: ... +def deinit() -> None: ... +def colorama_text(*args: Any, **kwargs: Any) -> AbstractContextManager[None]: ... +def reinit() -> None: ... +def wrap_stream( + stream: _TextIOT, convert: bool | None, strip: bool | None, autoreset: bool, wrap: bool +) -> _TextIOT | StreamWrapper: ... +def just_fix_windows_console() -> None: ... diff --git a/stubs/colorama/colorama/win32.pyi b/stubs/colorama/colorama/win32.pyi new file mode 100644 index 000000000000..f1bcefe7063a --- /dev/null +++ b/stubs/colorama/colorama/win32.pyi @@ -0,0 +1,35 @@ +import sys +from collections.abc import Callable +from typing import Literal + +STDOUT: Literal[-11] +STDERR: Literal[-12] +ENABLE_VIRTUAL_TERMINAL_PROCESSING: int + +if sys.platform == "win32": + from ctypes import LibraryLoader, Structure, WinDLL, wintypes + + windll: LibraryLoader[WinDLL] + COORD = wintypes._COORD + + class CONSOLE_SCREEN_BUFFER_INFO(Structure): + dwSize: COORD + dwCursorPosition: COORD + wAttributes: wintypes.WORD + srWindow: wintypes.SMALL_RECT + dwMaximumWindowSize: COORD + + def winapi_test() -> bool: ... + def GetConsoleScreenBufferInfo(stream_id: int = -11) -> CONSOLE_SCREEN_BUFFER_INFO: ... + def SetConsoleTextAttribute(stream_id: int, attrs: wintypes.WORD) -> wintypes.BOOL: ... + def SetConsoleCursorPosition(stream_id: int, position: COORD, adjust: bool = True) -> wintypes.BOOL: ... + def FillConsoleOutputCharacter(stream_id: int, char: str, length: int, start: COORD) -> int: ... + def FillConsoleOutputAttribute(stream_id: int, attr: int, length: int, start: COORD) -> wintypes.BOOL: ... + def SetConsoleTitle(title: str) -> wintypes.BOOL: ... + def GetConsoleMode(handle: int) -> int: ... + def SetConsoleMode(handle: int, mode: int) -> None: ... + +else: + windll: None + SetConsoleTextAttribute: Callable[..., None] + winapi_test: Callable[..., None] diff --git a/stubs/colorama/colorama/winterm.pyi b/stubs/colorama/colorama/winterm.pyi new file mode 100644 index 000000000000..7762e0236262 --- /dev/null +++ b/stubs/colorama/colorama/winterm.pyi @@ -0,0 +1,38 @@ +import sys +from typing import Final + +if sys.platform == "win32": + from . import win32 + + class WinColor: + BLACK: Final = 0 + BLUE: Final = 1 + GREEN: Final = 2 + CYAN: Final = 3 + RED: Final = 4 + MAGENTA: Final = 5 + YELLOW: Final = 6 + GREY: Final = 7 + + class WinStyle: + NORMAL: Final = 0x00 + BRIGHT: Final = 0x08 + BRIGHT_BACKGROUND: Final = 0x80 + + class WinTerm: + def __init__(self) -> None: ... + def get_attrs(self) -> int: ... + def set_attrs(self, value: int) -> None: ... + def reset_all(self, on_stderr: bool | None = None) -> None: ... + def fore(self, fore: int | None = None, light: bool = False, on_stderr: bool = False) -> None: ... + def back(self, back: int | None = None, light: bool = False, on_stderr: bool = False) -> None: ... + def style(self, style: int | None = None, on_stderr: bool = False) -> None: ... + def set_console(self, attrs: int | None = None, on_stderr: bool = False) -> None: ... + def get_position(self, handle: int) -> win32.COORD: ... + def set_cursor_position(self, position: win32.COORD | None = None, on_stderr: bool = False) -> None: ... + def cursor_adjust(self, x: int, y: int, on_stderr: bool = False) -> None: ... + def erase_screen(self, mode: int = 0, on_stderr: bool = False) -> None: ... + def erase_line(self, mode: int = 0, on_stderr: bool = False) -> None: ... + def set_title(self, title: str) -> None: ... + +def enable_vt_processing(fd: int) -> bool: ... diff --git a/stubs/colorful/METADATA.toml b/stubs/colorful/METADATA.toml new file mode 100644 index 000000000000..51d16a937052 --- /dev/null +++ b/stubs/colorful/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/timofurrer/colorful" diff --git a/stubs/colorful/colorful/__init__.pyi b/stubs/colorful/colorful/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/colorful/colorful/ansi.pyi b/stubs/colorful/colorful/ansi.pyi new file mode 100644 index 000000000000..ed25609c6766 --- /dev/null +++ b/stubs/colorful/colorful/ansi.pyi @@ -0,0 +1,14 @@ +from typing import Final + +MODIFIERS: Final[dict[str, tuple[int, int]]] +MODIFIER_RESET_OFFSET: Final[int] +FOREGROUND_COLOR_OFFSET: Final[int] +BACKGROUND_COLOR_OFFSET: Final[int] +COLOR_CLOSE_OFFSET: Final[int] +CSI: Final[str] +ANSI_ESCAPE_CODE: Final[str] +NEST_PLACEHOLDER: Final[str] + +def round(value: float) -> int: ... +def rgb_to_ansi256(r: int, g: int, b: int) -> int: ... +def rgb_to_ansi16(r: int, g: int, b: int, use_bright: bool = False) -> int: ... diff --git a/stubs/colorful/colorful/colors.pyi b/stubs/colorful/colorful/colors.pyi new file mode 100644 index 000000000000..8865b2357284 --- /dev/null +++ b/stubs/colorful/colorful/colors.pyi @@ -0,0 +1,6 @@ +from _typeshed import SupportsItems + +def parse_colors(path: str) -> SupportsItems[str, str | tuple[int, int, int]]: ... +def parse_rgb_txt_file(path: str) -> SupportsItems[str, str | tuple[int, int, int]]: ... +def parse_json_color_file(path: str) -> dict[str, str]: ... +def sanitize_color_palette(colorpalette: SupportsItems[str, str | tuple[int, int, int]]) -> dict[str, tuple[int, int, int]]: ... diff --git a/stubs/colorful/colorful/core.pyi b/stubs/colorful/colorful/core.pyi new file mode 100644 index 000000000000..8fe0a797f7f6 --- /dev/null +++ b/stubs/colorful/colorful/core.pyi @@ -0,0 +1,104 @@ +from _typeshed import SupportsGetItem, SupportsItems, SupportsWrite + +# This module defines a function "str()", which is why "str" can't be used +# as a type annotation or type alias. +from builtins import str as _str +from collections.abc import Iterator +from typing import Any, Final, Literal, TypeAlias +from typing_extensions import LiteralString, Self + +# Custom type helpers +_ColorModeType: TypeAlias = Literal[0, 8, 16, 256, 16777215] +_PaletteType: TypeAlias = dict[_str, _str] | dict[_str, tuple[int, int, int]] | dict[_str, _str | tuple[int, int, int]] +_StyleType: TypeAlias = tuple[_str, _str] + +DEFAULT_RGB_TXT_PATH: Final[_str] +COLOR_PALETTE: Final[dict[_str, _str]] +COLORNAMES_COLORS_PATH: Final[_str] + +class ColorfulError(Exception): ... +class ColorfulAttributeError(AttributeError, ColorfulError): ... + +def translate_rgb_to_ansi_code(red: int, green: int, blue: int, offset: int, colormode: _ColorModeType) -> _str: ... +def translate_colorname_to_ansi_code( + colorname: _str, offset: int, colormode: _ColorModeType, colorpalette: SupportsGetItem[_str, _str | tuple[int, int, int]] +) -> _str: ... +def resolve_modifier_to_ansi_code(modifiername: _str, colormode: _ColorModeType) -> _str: ... +def translate_style( + style: _str, colormode: _ColorModeType, colorpalette: SupportsGetItem[_str, _str | tuple[int, int, int]] +) -> _str: ... +def style_string(string: _str, ansi_style: _StyleType, colormode: _ColorModeType, nested: bool = False) -> _str: ... + +class ColorfulString: + orig_string: _str + styled_string: _str + colorful_ctx: Colorful + def __init__(self, orig_string: _str, styled_string: _str, colorful_ctx: Colorful) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_str]: ... + def __add__(self, other: _str | ColorfulString) -> Self: ... + def __iadd__(self, other: _str | ColorfulString) -> Self: ... + def __radd__(self, other: _str | ColorfulString) -> Self: ... + def __mul__(self, other: _str) -> Self: ... + def __format__(self, format_spec: _str) -> _str: ... + # Forwards item access to styled_string (a str). + def __getattr__(self, name: _str) -> Any: ... + +class Colorful: + NO_COLORS: Final[int] + ANSI_8_COLORS: Final[int] + ANSI_16_COLORS: Final[int] + ANSI_256_COLORS: Final[int] + TRUE_COLORS: Final[int] + COLORNAMES_COLORS = COLORNAMES_COLORS_PATH + close_fg_color: Final[_str] + close_bg_color: Final[_str] + no_bold: Final[_str] + no_dimmed: Final[_str] + no_italic: Final[_str] + no_underlined: Final[_str] + no_blinkslow: Final[_str] + no_blinkrapid: Final[_str] + no_inversed: Final[_str] + no_concealed: Final[_str] + no_struckthrough: Final[_str] + colormode: _ColorModeType + def __init__(self, colormode: _ColorModeType | None = None, colorpalette: _str | _PaletteType | None = None) -> None: ... + + @property + def colorpalette(self) -> SupportsItems[_str, _str | tuple[int, int, int]] | None: ... + @colorpalette.setter + def colorpalette(self, colorpalette: _str | _PaletteType) -> None: ... + + def setup( + self, + colormode: _ColorModeType | None = None, + colorpalette: _str | _PaletteType | None = None, + extend_colors: bool = False, + ) -> None: ... + def disable(self) -> None: ... + def use_8_ansi_colors(self) -> None: ... + def use_16_ansi_colors(self) -> None: ... + def use_256_ansi_colors(self) -> None: ... + def use_true_colors(self) -> None: ... + def use_palette(self, colorpalette: _str | _PaletteType) -> None: ... + def update_palette(self, colorpalette: _str | _PaletteType) -> None: ... + def use_style(self, style_name: _str) -> None: ... + def format(self, string: _str, *args: LiteralString, **kwargs: LiteralString) -> _str: ... + def str(self, string: _str) -> ColorfulString: ... + def print( + self, *objects: object, sep: _str = " ", end: _str = "\n", file: SupportsWrite[_str] | None = None, flush: bool = False + ) -> None: ... + + class ColorfulStyle: + colormode: _ColorModeType + colorful_ctx: Colorful + def __init__(self, style: _StyleType, colormode: _ColorModeType, colorful_ctx: Colorful) -> None: ... + def evaluate(self, string: _str, nested: bool = False) -> ColorfulString: ... + def __and__(self, other: Self) -> Self: ... + def __call__(self, string: _str, nested: bool = False) -> ColorfulString: ... + def __or__(self, other) -> ColorfulString: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + + def __getattr__(self, name: _str) -> ColorfulStyle: ... diff --git a/stubs/colorful/colorful/styles.pyi b/stubs/colorful/colorful/styles.pyi new file mode 100644 index 000000000000..8a0fcbe01789 --- /dev/null +++ b/stubs/colorful/colorful/styles.pyi @@ -0,0 +1,4 @@ +from typing import Final + +SOLARIZED: Final[dict[str, str]] +MONOKAI: Final[dict[str, str]] diff --git a/stubs/colorful/colorful/terminal.pyi b/stubs/colorful/colorful/terminal.pyi new file mode 100644 index 000000000000..3445996c485b --- /dev/null +++ b/stubs/colorful/colorful/terminal.pyi @@ -0,0 +1,16 @@ +from typing import Final, Protocol, overload, type_check_only + +@type_check_only +class _SupportsGet(Protocol): + @overload + def get(self, name: str, /) -> str | None: ... + @overload + def get(self, name: str, default: str, /) -> str: ... + +NO_COLORS: Final[int] +ANSI_8_COLORS: Final[int] +ANSI_16_COLORS: Final[int] +ANSI_256_COLORS: Final[int] +TRUE_COLORS: Final[int] + +def detect_color_support(env: _SupportsGet) -> int: ... diff --git a/stubs/colorful/colorful/utils.pyi b/stubs/colorful/colorful/utils.pyi new file mode 100644 index 000000000000..a4156beb64f9 --- /dev/null +++ b/stubs/colorful/colorful/utils.pyi @@ -0,0 +1,2 @@ +def hex_to_rgb(value: str) -> tuple[int, int, int]: ... +def check_hex(value: str) -> None: ... diff --git a/stubs/console-menu/METADATA.toml b/stubs/console-menu/METADATA.toml new file mode 100644 index 000000000000..dbaaa6fd0ec8 --- /dev/null +++ b/stubs/console-menu/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.8.*" +upstream-repository = "https://github.com/aegirhall/console-menu" diff --git a/stubs/console-menu/consolemenu/__init__.pyi b/stubs/console-menu/consolemenu/__init__.pyi new file mode 100644 index 000000000000..e597f474c010 --- /dev/null +++ b/stubs/console-menu/consolemenu/__init__.pyi @@ -0,0 +1,17 @@ +from . import items as items +from .console_menu import ConsoleMenu as ConsoleMenu, Screen as Screen, clear_terminal as clear_terminal +from .menu_formatter import MenuFormatBuilder as MenuFormatBuilder +from .multiselect_menu import MultiSelectMenu as MultiSelectMenu +from .prompt_utils import PromptUtils as PromptUtils +from .selection_menu import SelectionMenu as SelectionMenu + +__all__ = [ + "ConsoleMenu", + "SelectionMenu", + "MultiSelectMenu", + "MenuFormatBuilder", + "PromptUtils", + "Screen", + "items", + "clear_terminal", +] diff --git a/stubs/console-menu/consolemenu/console_menu.pyi b/stubs/console-menu/consolemenu/console_menu.pyi new file mode 100644 index 000000000000..49bbdd7cbe4e --- /dev/null +++ b/stubs/console-menu/consolemenu/console_menu.pyi @@ -0,0 +1,97 @@ +from collections.abc import Callable + +from consolemenu.menu_formatter import MenuFormatBuilder as MenuFormatBuilder +from consolemenu.screen import Screen as Screen + +class ConsoleMenu: + currently_active_menu: ConsoleMenu | None + screen: Screen + clear_screen_before_render: bool + formatter: MenuFormatBuilder + title: str | Callable[[], str] | None + subtitle: str | Callable[[], str] | None + prologue_text: str | Callable[[], str] | None + epilogue_text: str | Callable[[], str] | None + highlight: None + normal: None + show_exit_option: bool + items: list[MenuItem] + parent: ConsoleMenu | None + exit_item: ExitItem + current_option: int + selected_option: int + returned_value: object + should_exit: bool + previous_active_menu: ConsoleMenu | None + def __init__( + self, + title: str | Callable[[], str] | None = None, + subtitle: str | Callable[[], str] | None = None, + screen: Screen | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | Callable[[], str] | None = None, + epilogue_text: str | Callable[[], str] | None = None, + clear_screen: bool = True, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + exit_menu_char: str | None = None, + ) -> None: ... + @property + def current_item(self) -> MenuItem | None: ... + @property + def selected_item(self) -> MenuItem | None: ... + def append_item(self, item: MenuItem) -> None: ... + def remove_item(self, item: MenuItem) -> bool: ... + def add_exit(self) -> bool: ... + def remove_exit(self) -> bool: ... + def is_selected_item_exit(self) -> bool: ... + def start(self, show_exit_option: bool | None = None) -> None: ... + def show(self, show_exit_option: bool | None = None) -> None: ... + def draw(self) -> None: ... + def is_running(self) -> bool: ... + def wait_for_start(self, timeout: float | None = None) -> bool: ... + def is_alive(self) -> bool: ... + def pause(self) -> None: ... + def resume(self) -> None: ... + def join(self, timeout: float | None = None) -> None: ... + def get_input(self) -> int: ... + def process_user_input(self) -> int | None: ... + def go_to(self, option: int) -> None: ... + def go_down(self) -> None: ... + def go_up(self) -> None: ... + def select(self) -> None: ... + def exit(self) -> None: ... + def clear_screen(self) -> None: ... + def get_title(self) -> str: ... + def get_subtitle(self) -> str: ... + def get_prologue_text(self) -> str: ... + def get_epilogue_text(self) -> str: ... + +class MenuItem: + text: str + menu: ConsoleMenu | None + should_exit: bool + index_item_separator: str + menu_char: str | None + def __init__( + self, + text: str | Callable[[], str], + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def show(self, index: int) -> str: ... + def set_up(self) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> object: ... + def __eq__(self, o: MenuItem) -> bool: ... # type: ignore[override] + def get_text(self) -> str: ... + +class ExitItem(MenuItem): + def __init__( + self, text: str | Callable[[], str] = "Exit", menu: ConsoleMenu | None = None, menu_char: str | None = None + ) -> None: ... + def show(self, index: int, available_width: None = None) -> str: ... + +def clear_terminal() -> None: ... diff --git a/stubs/console-menu/consolemenu/format/__init__.pyi b/stubs/console-menu/consolemenu/format/__init__.pyi new file mode 100644 index 000000000000..cc963da051c8 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/__init__.pyi @@ -0,0 +1,29 @@ +from .menu_borders import ( + AsciiBorderStyle as AsciiBorderStyle, + DoubleLineBorderStyle as DoubleLineBorderStyle, + DoubleLineOuterLightInnerBorderStyle as DoubleLineOuterLightInnerBorderStyle, + HeavyBorderStyle as HeavyBorderStyle, + HeavyOuterLightInnerBorderStyle as HeavyOuterLightInnerBorderStyle, + LightBorderStyle as LightBorderStyle, + MenuBorderStyle as MenuBorderStyle, + MenuBorderStyleFactory as MenuBorderStyleFactory, + MenuBorderStyleType as MenuBorderStyleType, +) +from .menu_margins import MenuMargins as MenuMargins +from .menu_padding import MenuPadding as MenuPadding +from .menu_style import MenuStyle as MenuStyle + +__all__ = [ + "MenuBorderStyle", + "MenuBorderStyleType", + "MenuBorderStyleFactory", + "MenuMargins", + "MenuPadding", + "MenuStyle", + "AsciiBorderStyle", + "LightBorderStyle", + "HeavyBorderStyle", + "DoubleLineBorderStyle", + "DoubleLineOuterLightInnerBorderStyle", + "HeavyOuterLightInnerBorderStyle", +] diff --git a/stubs/console-menu/consolemenu/format/menu_borders.pyi b/stubs/console-menu/consolemenu/format/menu_borders.pyi new file mode 100644 index 000000000000..9710b4abe2be --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_borders.pyi @@ -0,0 +1,194 @@ +import logging + +class MenuBorderStyle: + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class AsciiBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class LightBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class HeavyBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class HeavyOuterLightInnerBorderStyle(HeavyBorderStyle): + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + +class DoubleLineBorderStyle(MenuBorderStyle): + @property + def bottom_left_corner(self) -> str: ... + @property + def bottom_right_corner(self) -> str: ... + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + @property + def top_left_corner(self) -> str: ... + @property + def top_right_corner(self) -> str: ... + +class DoubleLineOuterLightInnerBorderStyle(DoubleLineBorderStyle): + @property + def inner_horizontal(self) -> str: ... + @property + def inner_vertical(self) -> str: ... + @property + def intersection(self) -> str: ... + @property + def outer_horizontal_inner_down(self) -> str: ... + @property + def outer_horizontal_inner_up(self) -> str: ... + @property + def outer_vertical_inner_left(self) -> str: ... + @property + def outer_vertical_inner_right(self) -> str: ... + +class MenuBorderStyleType: + ASCII_BORDER: int + LIGHT_BORDER: int + HEAVY_BORDER: int + DOUBLE_LINE_BORDER: int + HEAVY_OUTER_LIGHT_INNER_BORDER: int + DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER: int + +class MenuBorderStyleFactory: + logger: logging.Logger + def __init__(self) -> None: ... + def create_border(self, border_style_type: MenuBorderStyleType) -> MenuBorderStyle: ... + def create_ascii_border(self) -> AsciiBorderStyle: ... + def create_light_border(self) -> LightBorderStyle: ... + def create_heavy_border(self) -> HeavyBorderStyle: ... + def create_heavy_outer_light_inner_border(self) -> HeavyOuterLightInnerBorderStyle: ... + def create_doubleline_border(self) -> DoubleLineBorderStyle: ... + def create_doubleline_outer_light_inner_border(self) -> DoubleLineOuterLightInnerBorderStyle: ... + @staticmethod + def is_win_python35_or_earlier() -> bool: ... diff --git a/stubs/console-menu/consolemenu/format/menu_margins.pyi b/stubs/console-menu/consolemenu/format/menu_margins.pyi new file mode 100644 index 000000000000..92505a4999e9 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_margins.pyi @@ -0,0 +1,22 @@ +class MenuMargins: + def __init__(self, top: int = 1, left: int = 2, bottom: int = 0, right: int = 2) -> None: ... + + @property + def left(self) -> int: ... + @left.setter + def left(self, left: int) -> None: ... + + @property + def right(self) -> int: ... + @right.setter + def right(self, right: int) -> None: ... + + @property + def top(self) -> int: ... + @top.setter + def top(self, top: int) -> None: ... + + @property + def bottom(self) -> int: ... + @bottom.setter + def bottom(self, bottom: int) -> None: ... diff --git a/stubs/console-menu/consolemenu/format/menu_padding.pyi b/stubs/console-menu/consolemenu/format/menu_padding.pyi new file mode 100644 index 000000000000..41791c1efed0 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_padding.pyi @@ -0,0 +1,22 @@ +class MenuPadding: + def __init__(self, top: int = 1, left: int = 2, bottom: int = 1, right: int = 2) -> None: ... + + @property + def left(self) -> int: ... + @left.setter + def left(self, left: int) -> None: ... + + @property + def right(self) -> int: ... + @right.setter + def right(self, right: int) -> None: ... + + @property + def top(self) -> int: ... + @top.setter + def top(self, top: int) -> None: ... + + @property + def bottom(self) -> int: ... + @bottom.setter + def bottom(self, bottom: int) -> None: ... diff --git a/stubs/console-menu/consolemenu/format/menu_style.pyi b/stubs/console-menu/consolemenu/format/menu_style.pyi new file mode 100644 index 000000000000..a0bfc1c42259 --- /dev/null +++ b/stubs/console-menu/consolemenu/format/menu_style.pyi @@ -0,0 +1,33 @@ +from consolemenu.format.menu_borders import MenuBorderStyle as MenuBorderStyle, MenuBorderStyleFactory as MenuBorderStyleFactory +from consolemenu.format.menu_margins import MenuMargins as MenuMargins +from consolemenu.format.menu_padding import MenuPadding as MenuPadding + +class MenuStyle: + def __init__( + self, + margins: MenuMargins | None = None, + padding: MenuPadding | None = None, + border_style: MenuBorderStyle | None = None, + border_style_type: int | None = None, + border_style_factory: MenuBorderStyleFactory | None = None, + ) -> None: ... + + @property + def margins(self) -> MenuMargins: ... + @margins.setter + def margins(self, margins: MenuMargins) -> None: ... + + @property + def padding(self) -> MenuPadding: ... + @padding.setter + def padding(self, padding: MenuPadding) -> None: ... + + @property + def border_style(self) -> MenuBorderStyle: ... + @border_style.setter + def border_style(self, border_style: MenuBorderStyle) -> None: ... + + @property + def border_style_factory(self) -> MenuBorderStyleFactory: ... + @border_style_factory.setter + def border_style_factory(self, border_style_factory: MenuBorderStyleFactory) -> None: ... diff --git a/stubs/console-menu/consolemenu/items/__init__.pyi b/stubs/console-menu/consolemenu/items/__init__.pyi new file mode 100644 index 000000000000..29943004afbf --- /dev/null +++ b/stubs/console-menu/consolemenu/items/__init__.pyi @@ -0,0 +1,8 @@ +from ..console_menu import ExitItem as ExitItem, MenuItem as MenuItem +from .command_item import CommandItem as CommandItem +from .external_item import ExternalItem as ExternalItem +from .function_item import FunctionItem as FunctionItem +from .selection_item import SelectionItem as SelectionItem +from .submenu_item import SubmenuItem as SubmenuItem + +__all__ = ["CommandItem", "ExitItem", "ExternalItem", "FunctionItem", "MenuItem", "SelectionItem", "SubmenuItem"] diff --git a/stubs/console-menu/consolemenu/items/command_item.pyi b/stubs/console-menu/consolemenu/items/command_item.pyi new file mode 100644 index 000000000000..1df604797124 --- /dev/null +++ b/stubs/console-menu/consolemenu/items/command_item.pyi @@ -0,0 +1,18 @@ +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import ExternalItem as ExternalItem + +class CommandItem(ExternalItem): + command: str + arguments: list[str] + exit_status: int | None + def __init__( + self, + text: str, + command: str, + arguments: list[str] | None = None, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def action(self) -> None: ... + def get_return(self) -> int: ... diff --git a/stubs/console-menu/consolemenu/items/external_item.pyi b/stubs/console-menu/consolemenu/items/external_item.pyi new file mode 100644 index 000000000000..33cf83a8eb0c --- /dev/null +++ b/stubs/console-menu/consolemenu/items/external_item.pyi @@ -0,0 +1,5 @@ +from consolemenu.items import MenuItem as MenuItem + +class ExternalItem(MenuItem): + def set_up(self) -> None: ... + def clean_up(self) -> None: ... diff --git a/stubs/console-menu/consolemenu/items/function_item.pyi b/stubs/console-menu/consolemenu/items/function_item.pyi new file mode 100644 index 000000000000..3322c4a3042d --- /dev/null +++ b/stubs/console-menu/consolemenu/items/function_item.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping, Sequence +from typing import Any + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import ExternalItem as ExternalItem + +class FunctionItem(ExternalItem): + function: Callable[..., Any] + args: Sequence[Any] + kwargs: Mapping[str, Any] + return_value: Incomplete | None + def __init__( + self, + text: str, + function: Callable[..., Any], + args: Sequence[Any] | None = None, + kwargs: Mapping[str, Any] | None = None, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> Any | None: ... diff --git a/stubs/console-menu/consolemenu/items/selection_item.pyi b/stubs/console-menu/consolemenu/items/selection_item.pyi new file mode 100644 index 000000000000..ce37a82bba7f --- /dev/null +++ b/stubs/console-menu/consolemenu/items/selection_item.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import MenuItem as MenuItem + +class SelectionItem(MenuItem): + index: int + def __init__( + self, text: str | Callable[[], str], index: int, menu: ConsoleMenu | None = None, menu_char: str | None = None + ) -> None: ... + def get_return(self) -> int: ... diff --git a/stubs/console-menu/consolemenu/items/submenu_item.pyi b/stubs/console-menu/consolemenu/items/submenu_item.pyi new file mode 100644 index 000000000000..9cda42875cb8 --- /dev/null +++ b/stubs/console-menu/consolemenu/items/submenu_item.pyi @@ -0,0 +1,22 @@ +from collections.abc import Callable + +from consolemenu.console_menu import ConsoleMenu +from consolemenu.items import MenuItem as MenuItem + +class SubmenuItem(MenuItem): + submenu: ConsoleMenu + def __init__( + self, + text: str | Callable[[], str], + submenu: ConsoleMenu, + menu: ConsoleMenu | None = None, + should_exit: bool = False, + menu_char: str | None = None, + ) -> None: ... + menu: ConsoleMenu + def set_menu(self, menu: ConsoleMenu) -> None: ... + def set_up(self) -> None: ... + def action(self) -> None: ... + def clean_up(self) -> None: ... + def get_return(self) -> object: ... + def get_submenu(self) -> ConsoleMenu: ... diff --git a/stubs/console-menu/consolemenu/menu_component.pyi b/stubs/console-menu/consolemenu/menu_component.pyi new file mode 100644 index 000000000000..12cc5c53aae2 --- /dev/null +++ b/stubs/console-menu/consolemenu/menu_component.pyi @@ -0,0 +1,103 @@ +from collections.abc import Generator + +from consolemenu.console_menu import MenuItem +from consolemenu.format import MenuBorderStyle, MenuMargins, MenuPadding, MenuStyle as MenuStyle + +def ansilen(s: str) -> int: ... + +class Dimension: + width: int + height: int + def __init__(self, width: int = 0, height: int = 0, dimension: Dimension | None = None) -> None: ... + +class MenuComponent: + def __init__(self, menu_style: MenuStyle, max_dimension: Dimension | None = None) -> None: ... + @property + def max_dimension(self) -> Dimension: ... + @property + def style(self) -> MenuStyle: ... + @property + def margins(self) -> MenuMargins: ... + @property + def padding(self) -> MenuPadding: ... + @property + def border_style(self) -> MenuBorderStyle: ... + def calculate_border_width(self) -> int: ... + def calculate_content_width(self) -> int: ... + def generate(self) -> Generator[str]: ... + def inner_horizontals(self) -> str: ... + def inner_horizontal_border(self) -> str: ... + def outer_horizontals(self) -> str: ... + def outer_horizontal_border_bottom(self) -> str: ... + def outer_horizontal_border_top(self) -> str: ... + def row(self, content: str = "", align: str = "left", indent_len: int = 0) -> str: ... + +class MenuHeader(MenuComponent): + title: str + title_align: str + subtitle: str + subtitle_align: str + show_bottom_border: bool + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + title: str | None = None, + title_align: str = "left", + subtitle: str | None = None, + subtitle_align: str = "left", + show_bottom_border: bool = False, + ) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuTextSection(MenuComponent): + text: str + text_align: str + show_top_border: bool + show_bottom_border: bool + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + text: str | None = None, + text_align: str = "left", + show_top_border: bool = False, + show_bottom_border: bool = False, + ) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuItemsSection(MenuComponent): + items_align: str + def __init__( + self, + menu_style: MenuStyle, + max_dimension: Dimension | None = None, + items: list[MenuItem] | None = None, + items_align: str = "left", + ) -> None: ... + + @property + def items(self) -> list[MenuItem]: ... + @items.setter + def items(self, items: list[MenuItem]) -> None: ... + + @property + def items_with_bottom_border(self) -> list[str]: ... + @property + def items_with_top_border(self) -> list[str]: ... + def show_item_bottom_border(self, item_text: str, flag: bool) -> None: ... + def show_item_top_border(self, item_text: str, flag: bool) -> None: ... + def generate(self) -> Generator[str]: ... + +class MenuFooter(MenuComponent): + def generate(self) -> Generator[str]: ... + +class MenuPrompt(MenuComponent): + def __init__(self, menu_style: MenuStyle, max_dimension: Dimension | None = None, prompt_string: str = ">>") -> None: ... + + @property + def prompt(self) -> str: ... + @prompt.setter + def prompt(self, prompt: str) -> None: ... + + def generate(self) -> Generator[str]: ... diff --git a/stubs/console-menu/consolemenu/menu_formatter.pyi b/stubs/console-menu/consolemenu/menu_formatter.pyi new file mode 100644 index 000000000000..1144678da276 --- /dev/null +++ b/stubs/console-menu/consolemenu/menu_formatter.pyi @@ -0,0 +1,55 @@ +from consolemenu.console_menu import MenuItem +from consolemenu.format import MenuBorderStyleType +from consolemenu.format.menu_borders import MenuBorderStyle as MenuBorderStyle, MenuBorderStyleFactory as MenuBorderStyleFactory +from consolemenu.format.menu_style import MenuStyle as MenuStyle +from consolemenu.menu_component import ( + Dimension as Dimension, + MenuFooter as MenuFooter, + MenuHeader as MenuHeader, + MenuItemsSection as MenuItemsSection, + MenuPrompt as MenuPrompt, + MenuTextSection as MenuTextSection, +) + +class MenuFormatBuilder: + def __init__(self, max_dimension: Dimension | None = None) -> None: ... + def set_border_style(self, border_style: MenuBorderStyle) -> MenuFormatBuilder: ... + def set_border_style_type(self, border_style_type: MenuBorderStyleType) -> MenuFormatBuilder: ... + def set_border_style_factory(self, border_style_factory: MenuBorderStyleFactory) -> MenuFormatBuilder: ... + def set_bottom_margin(self, bottom_margin: int) -> MenuFormatBuilder: ... + def set_left_margin(self, left_margin: int) -> MenuFormatBuilder: ... + def set_right_margin(self, right_margin: int) -> MenuFormatBuilder: ... + def set_top_margin(self, top_margin: int) -> MenuFormatBuilder: ... + def set_title_align(self, align: str = "left") -> MenuFormatBuilder: ... + def set_subtitle_align(self, align: str = "left") -> MenuFormatBuilder: ... + def set_header_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_header_top_padding(self, x: int) -> MenuFormatBuilder: ... + def show_header_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_footer_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_footer_top_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_left_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_right_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_bottom_padding(self, x: int) -> MenuFormatBuilder: ... + def set_items_top_padding(self, x: int) -> MenuFormatBuilder: ... + def show_item_bottom_border(self, item_text: str, flag: bool) -> MenuFormatBuilder: ... + def show_item_top_border(self, item_text: str, flag: bool) -> MenuFormatBuilder: ... + def set_prologue_text_align(self, align: str = "left") -> MenuFormatBuilder: ... + def show_prologue_top_border(self, flag: bool) -> MenuFormatBuilder: ... + def show_prologue_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_epilogue_text_align(self, align: str = "left") -> MenuFormatBuilder: ... + def show_epilogue_top_border(self, flag: bool) -> MenuFormatBuilder: ... + def show_epilogue_bottom_border(self, flag: bool) -> MenuFormatBuilder: ... + def set_prompt(self, prompt: MenuPrompt) -> MenuFormatBuilder: ... + def clear_data(self) -> None: ... + def format( + self, + title: str | None = None, + subtitle: str | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + items: list[MenuItem] | None = None, + ) -> str: ... diff --git a/stubs/console-menu/consolemenu/multiselect_menu.pyi b/stubs/console-menu/consolemenu/multiselect_menu.pyi new file mode 100644 index 000000000000..4fe1a6260546 --- /dev/null +++ b/stubs/console-menu/consolemenu/multiselect_menu.pyi @@ -0,0 +1,22 @@ +from consolemenu import ConsoleMenu as ConsoleMenu +from consolemenu.console_menu import MenuItem +from consolemenu.items import SubmenuItem as SubmenuItem +from consolemenu.menu_formatter import MenuFormatBuilder + +class MultiSelectMenu(ConsoleMenu): + ack_item_completion: bool + def __init__( + self, + title: str | None = None, + subtitle: str | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + ack_item_completion: bool = True, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + clear_screen: bool = True, + ) -> None: ... + def append_item(self, item: MenuItem) -> None: ... + current_option: int + def process_user_input(self) -> None: ... diff --git a/stubs/console-menu/consolemenu/prompt_utils.pyi b/stubs/console-menu/consolemenu/prompt_utils.pyi new file mode 100644 index 000000000000..d40dda7d98de --- /dev/null +++ b/stubs/console-menu/consolemenu/prompt_utils.pyi @@ -0,0 +1,47 @@ +from collections.abc import Iterable, Sequence +from typing import Any, NamedTuple + +from consolemenu.screen import Screen +from consolemenu.validators.base import BaseValidator + +class InputResult(NamedTuple): + input_string: str + validation_result: bool + +class PromptFormatter: + @staticmethod + def format_prompt( + prompt: str | None = None, + default: str | None = None, + enable_quit: bool = False, + quit_string: str = "q", + quit_message: str = "(enter q to Quit)", + ) -> str: ... + +class PromptUtils: + def __init__(self, screen: Screen, prompt_formatter: PromptFormatter | None = None) -> None: ... + @property + def screen(self) -> Screen: ... + def clear(self) -> None: ... + def confirm_answer(self, answer: str, message: str | None = None) -> bool: ... + def enter_to_continue(self, message: str | None = None) -> None: ... + def input( + self, + prompt: str | None = None, + default: str | None = None, + validators: Iterable[BaseValidator] | None = None, + enable_quit: bool = False, + quit_string: str = "q", + quit_message: str = "(enter q to Quit)", + ) -> InputResult: ... + def input_password(self, message: str | None = None) -> str: ... + def printf(self, *args: Any) -> None: ... + def println(self, *args: Any) -> None: ... + def prompt_and_confirm_password(self, message: str) -> str: ... + def prompt_for_bilateral_choice(self, prompt: str, option1: str, option2: str) -> str: ... + def prompt_for_trilateral_choice(self, prompt: str, option1: str, option2: str, option3: str) -> str: ... + def prompt_for_yes_or_no(self, prompt: str) -> bool: ... + def prompt_for_numbered_choice(self, choices: Sequence[str], title: str | None = None, prompt: str = ">") -> int: ... + def validate_input(self, input_string: str, validators: BaseValidator) -> bool: ... + +class UserQuit(Exception): ... diff --git a/stubs/console-menu/consolemenu/screen.pyi b/stubs/console-menu/consolemenu/screen.pyi new file mode 100644 index 000000000000..63d5734327f3 --- /dev/null +++ b/stubs/console-menu/consolemenu/screen.pyi @@ -0,0 +1,17 @@ +from typing import Any + +class Screen: + def __init__(self) -> None: ... + @property + def screen_height(self) -> int: ... + @property + def screen_width(self) -> int: ... + @staticmethod + def clear() -> None: ... + @staticmethod + def flush() -> None: ... + def input(self, prompt: str = "") -> str: ... + @staticmethod + def printf(*args: Any) -> None: ... + @staticmethod + def println(*args: Any) -> None: ... diff --git a/stubs/console-menu/consolemenu/selection_menu.pyi b/stubs/console-menu/consolemenu/selection_menu.pyi new file mode 100644 index 000000000000..9760461e9542 --- /dev/null +++ b/stubs/console-menu/consolemenu/selection_menu.pyi @@ -0,0 +1,31 @@ +from collections.abc import Iterable + +from consolemenu import ConsoleMenu as ConsoleMenu +from consolemenu.items import SelectionItem as SelectionItem +from consolemenu.menu_formatter import MenuFormatBuilder +from consolemenu.screen import Screen + +class SelectionMenu(ConsoleMenu): + def __init__( + self, + strings: Iterable[str], + title: str | None = None, + subtitle: str | None = None, + screen: Screen | None = None, + formatter: MenuFormatBuilder | None = None, + prologue_text: str | None = None, + epilogue_text: str | None = None, + show_exit_option: bool = True, + exit_option_text: str = "Exit", + clear_screen: bool = True, + ) -> None: ... + @classmethod + def get_selection( + cls, + strings: Iterable[str], + title: str = "Select an option", + subtitle: str | None = None, + show_exit_option: bool = True, + _menu: ConsoleMenu | None = None, + ) -> int: ... + def append_string(self, string: str) -> None: ... diff --git a/stubs/console-menu/consolemenu/validators/__init__.pyi b/stubs/console-menu/consolemenu/validators/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/console-menu/consolemenu/validators/base.pyi b/stubs/console-menu/consolemenu/validators/base.pyi new file mode 100644 index 000000000000..eaea5c87caec --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/base.pyi @@ -0,0 +1,11 @@ +import abc +from abc import abstractmethod +from logging import Logger + +class InvalidValidator(Exception): ... + +class BaseValidator(metaclass=abc.ABCMeta): + log: Logger + def __init__(self) -> None: ... + @abstractmethod + def validate(self, input_string: str) -> bool: ... diff --git a/stubs/console-menu/consolemenu/validators/regex.pyi b/stubs/console-menu/consolemenu/validators/regex.pyi new file mode 100644 index 000000000000..fdadc44f6720 --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/regex.pyi @@ -0,0 +1,7 @@ +from consolemenu.validators.base import BaseValidator as BaseValidator + +class RegexValidator(BaseValidator): + def __init__(self, pattern: str) -> None: ... + @property + def pattern(self) -> str: ... + def validate(self, input_string: str) -> bool: ... diff --git a/stubs/console-menu/consolemenu/validators/url.pyi b/stubs/console-menu/consolemenu/validators/url.pyi new file mode 100644 index 000000000000..d9e92bb636cc --- /dev/null +++ b/stubs/console-menu/consolemenu/validators/url.pyi @@ -0,0 +1,5 @@ +from consolemenu.validators.base import BaseValidator as BaseValidator + +class UrlValidator(BaseValidator): + def __init__(self) -> None: ... + def validate(self, input_string: str) -> bool: ... diff --git a/stubs/console-menu/consolemenu/version.pyi b/stubs/console-menu/consolemenu/version.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/convertdate/METADATA.toml b/stubs/convertdate/METADATA.toml new file mode 100644 index 000000000000..4210dc427019 --- /dev/null +++ b/stubs/convertdate/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.4.1" +upstream-repository = "https://github.com/fitnr/convertdate" diff --git a/stubs/convertdate/convertdate/__init__.pyi b/stubs/convertdate/convertdate/__init__.pyi new file mode 100644 index 000000000000..b33581cac340 --- /dev/null +++ b/stubs/convertdate/convertdate/__init__.pyi @@ -0,0 +1,47 @@ +from typing import Final + +from . import ( + armenian as armenian, + bahai as bahai, + coptic as coptic, + daycount as daycount, + dublin as dublin, + french_republican as french_republican, + gregorian as gregorian, + hebrew as hebrew, + holidays as holidays, + indian_civil as indian_civil, + islamic as islamic, + iso as iso, + julian as julian, + julianday as julianday, + mayan as mayan, + ordinal as ordinal, + persian as persian, + positivist as positivist, + utils as utils, +) + +__version__: Final[str] + +__all__ = [ + "armenian", + "bahai", + "coptic", + "daycount", + "dublin", + "french_republican", + "gregorian", + "hebrew", + "holidays", + "indian_civil", + "islamic", + "iso", + "julian", + "julianday", + "mayan", + "ordinal", + "persian", + "positivist", + "utils", +] diff --git a/stubs/convertdate/convertdate/armenian.pyi b/stubs/convertdate/convertdate/armenian.pyi new file mode 100644 index 000000000000..3ff93da6847c --- /dev/null +++ b/stubs/convertdate/convertdate/armenian.pyi @@ -0,0 +1,24 @@ +from typing import Final, Literal + +EPOCH: Final = 1922501.5 +EPOCH_SARKAWAG: Final = 2117210.5 +MONTHS: Final[list[str]] +MONTHS_ARM: Final[list[str]] + +def leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None) -> float: ... +def from_jd(jd: float, method: Literal["sarkawag", "moveable"] | None = None) -> tuple[int, int, int]: ... +def to_julian(year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None) -> tuple[int, int, int]: ... +def from_julian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def to_gregorian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def from_gregorian( + year: int, month: int, day: int, method: Literal["sarkawag", "moveable"] | None = None +) -> tuple[int, int, int]: ... +def month_length(year: int, month: int, method: Literal["sarkawag", "moveable"] | None = None) -> Literal[5, 6, 30]: ... +def monthcalendar(year: int, month: int, method: Literal["sarkawag", "moveable"] | None = None) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... +def tostring(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/bahai.pyi b/stubs/convertdate/convertdate/bahai.pyi new file mode 100644 index 000000000000..53a426b839e3 --- /dev/null +++ b/stubs/convertdate/convertdate/bahai.pyi @@ -0,0 +1,37 @@ +from typing import Final + +EPOCH: Final = 2394646.5 +EPOCH_GREGORIAN_YEAR: Final = 1844 +TEHRAN: Final = 51.4215, 35.6944 +WEEKDAYS: Final = ("Jamál", "Kamál", "Fidál", "Idál", "Istijlál", "Istiqlál", "Jalál") +MONTHS: Final[tuple[str, ...]] +ENGLISH_MONTHS: Final[tuple[str, ...]] +BAHA: Final = 1 +JALAL: Final = 2 +JAMAL: Final = 3 +AZAMAT: Final = 4 +NUR: Final = 5 +RAHMAT: Final = 6 +KALIMAT: Final = 7 +KAMAL: Final = 8 +ASMA: Final = 9 +IZZAT: Final = 10 +MASHIYYAT: Final = 11 +ILM: Final = 12 +QUDRAT: Final = 13 +QAWL: Final = 14 +MASAIL: Final = 15 +SHARAF: Final = 16 +SULTAN: Final = 17 +MULK: Final = 18 +AYYAMIHA: Final = 19 +ALA: Final = 20 + +def gregorian_nawruz(year: int) -> tuple[int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> int: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/coptic.pyi b/stubs/convertdate/convertdate/coptic.pyi new file mode 100644 index 000000000000..dca579cabf68 --- /dev/null +++ b/stubs/convertdate/convertdate/coptic.pyi @@ -0,0 +1,14 @@ +from typing import Final, Literal + +EPOCH: Final = 1825029.5 +MONTHS: Final[list[str]] +WEEKDAYS: Final = ["Tkyriaka", "Pesnau", "Pshoment", "Peftoou", "Ptiou", "Psoou", "Psabbaton"] + +def is_leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jdc: float) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[5, 6, 30]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/data/__init__.pyi b/stubs/convertdate/convertdate/data/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/convertdate/convertdate/data/french_republican_days.pyi b/stubs/convertdate/convertdate/data/french_republican_days.pyi new file mode 100644 index 000000000000..9a37dc5f97b4 --- /dev/null +++ b/stubs/convertdate/convertdate/data/french_republican_days.pyi @@ -0,0 +1,3 @@ +from typing import Final + +french_republican_days: Final[dict[int, list[str]]] diff --git a/stubs/convertdate/convertdate/data/positivist.pyi b/stubs/convertdate/convertdate/data/positivist.pyi new file mode 100644 index 000000000000..a1529785d031 --- /dev/null +++ b/stubs/convertdate/convertdate/data/positivist.pyi @@ -0,0 +1,6 @@ +from typing import Final + +DAY_NAMES: Final[tuple[str, ...]] +leap_day_replacements: Final[dict[int, str]] +DAY_NAMES_LEAP: Final[list[str]] +FESTIVALS: Final[dict[tuple[int, int], str]] diff --git a/stubs/convertdate/convertdate/daycount.pyi b/stubs/convertdate/convertdate/daycount.pyi new file mode 100644 index 000000000000..e2029ede976e --- /dev/null +++ b/stubs/convertdate/convertdate/daycount.pyi @@ -0,0 +1,13 @@ +import datetime + +class DayCount: + epoch: float + def __init__(self, epoch: float) -> None: ... + def to_gregorian(self, dc: int) -> tuple[int, int, int]: ... + def from_gregorian(self, year: int, month: int, day: int) -> float: ... + def to_jd(self, dc: int) -> float: ... + def from_jd(self, jdc: float) -> float: ... + def from_julian(self, year: int, month: int, day: int) -> float: ... + def to_julian(self, dc: int) -> tuple[int, int, int]: ... + def to_datetime(self, dc: int) -> datetime.datetime: ... + def from_datetime(self, date: datetime.datetime) -> float: ... diff --git a/stubs/convertdate/convertdate/dublin.pyi b/stubs/convertdate/convertdate/dublin.pyi new file mode 100644 index 000000000000..5c28661a945c --- /dev/null +++ b/stubs/convertdate/convertdate/dublin.pyi @@ -0,0 +1,13 @@ +import datetime +from typing import Final + +EPOCH: Final = 2415020 + +def to_gregorian(dc: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> float: ... +def to_jd(dc: int) -> float: ... +def from_jd(jdc: float) -> float: ... +def from_julian(year: int, month: int, day: int) -> float: ... +def to_julian(dc: int) -> tuple[int, int, int]: ... +def to_datetime(dc: int) -> datetime.datetime: ... +def from_datetime(date: datetime.datetime) -> float: ... diff --git a/stubs/convertdate/convertdate/french_republican.pyi b/stubs/convertdate/convertdate/french_republican.pyi new file mode 100644 index 000000000000..d8c0c029a7ba --- /dev/null +++ b/stubs/convertdate/convertdate/french_republican.pyi @@ -0,0 +1,27 @@ +from typing import Final, Literal + +EPOCH: Final = 2375839.5 +YEAR_EPOCH: Final = 1791.0 +DAYS_IN_YEAR: Final = 365.0 +MOIS: Final[list[str]] +MONTHS: Final[list[str]] +LEAP_CYCLE_DAYS: Final = 1461.0 +LEAP_CYCLE_YEARS: Final = 4.0 + +def leap(year: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None) -> bool: ... +def premier_da_la_annee(jd: float) -> float: ... +def to_jd( + year: int, month: int, day: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> float: ... +def from_jd( + jd: float, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def decade(jour: float) -> int: ... +def day_name(month: int, day: int) -> str: ... +def from_gregorian( + year: int, month: int, day: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def to_gregorian( + an: int, mois: int, jour: int, method: Literal[4, 100, 128, "continuous", "madler", "romme", "equinox"] | None = None +) -> tuple[int, int, int]: ... +def format(an: int, mois: int, jour: int) -> str: ... diff --git a/stubs/convertdate/convertdate/gregorian.pyi b/stubs/convertdate/convertdate/gregorian.pyi new file mode 100644 index 000000000000..8d9c2df9044a --- /dev/null +++ b/stubs/convertdate/convertdate/gregorian.pyi @@ -0,0 +1,20 @@ +from typing import Final, Literal + +EPOCH: Final = 1721425.5 +INTERCALATION_CYCLE_YEARS: Final = 400 +INTERCALATION_CYCLE_DAYS: Final = 146097 +LEAP_SUPPRESSION_YEARS: Final = 100 +LEAP_SUPPRESSION_DAYS: Final = 36524 +LEAP_CYCLE_YEARS: Final = 4 +LEAP_CYCLE_DAYS: Final = 1461 +YEAR_DAYS: Final = 365 +HAVE_30_DAYS: Final = (4, 6, 9, 11) +HAVE_31_DAYS: Final = (1, 3, 5, 7, 8, 10, 12) + +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def to_jd2(year: int, month: int, day: int) -> float: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> int: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, format_string: str = "%-d %B %y") -> str: ... diff --git a/stubs/convertdate/convertdate/hebrew.pyi b/stubs/convertdate/convertdate/hebrew.pyi new file mode 100644 index 000000000000..dfe5544d185d --- /dev/null +++ b/stubs/convertdate/convertdate/hebrew.pyi @@ -0,0 +1,37 @@ +from typing import Final, Literal +from typing_extensions import deprecated + +EPOCH: Final = 347995.5 +HEBREW_YEAR_OFFSET: Final = 3760 +NISAN: Final = 1 +IYYAR: Final = 2 +SIVAN: Final = 3 +TAMMUZ: Final = 4 +AV: Final = 5 +ELUL: Final = 6 +TISHRI: Final = 7 +HESHVAN: Final = 8 +KISLEV: Final = 9 +TEVETH: Final = 10 +SHEVAT: Final = 11 +ADAR: Final = 12 +VEADAR: Final = 13 +MONTHS: Final[list[str]] +MONTHS_HEB: Final[list[str]] + +def leap(year: int) -> bool: ... +def year_months(year: int) -> Literal[12, 13]: ... +def delay_1(year: int) -> int: ... +def delay_2(year: int) -> Literal[0, 1, 2]: ... +def year_days(year: int) -> float: ... +def month_length(year: int, month: int) -> Literal[29, 30]: ... +@deprecated("The `month_days` function is deprecated. Use `month_length` instead.") +def month_days(year: int, month: int) -> Literal[29, 30]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_civil(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_jd_gregorianyear(gregorianyear: int, hebrew_month: int, hebrew_day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, lang: str | None = None) -> str: ... diff --git a/stubs/convertdate/convertdate/holidays.pyi b/stubs/convertdate/convertdate/holidays.pyi new file mode 100644 index 000000000000..02f709274187 --- /dev/null +++ b/stubs/convertdate/convertdate/holidays.pyi @@ -0,0 +1,161 @@ +from typing import Final, Literal +from typing_extensions import deprecated + +MON: Final = 0 +TUE: Final = 1 +WED: Final = 2 +THU: Final = 3 +FRI: Final = 4 +SAT: Final = 5 +SUN: Final = 6 +JAN: Final = 1 +FEB: Final = 2 +MAR: Final = 3 +APR: Final = 4 +MAY: Final = 5 +JUN: Final = 6 +JUL: Final = 7 +AUG: Final = 8 +SEP: Final = 9 +OCT: Final = 10 +NOV: Final = 11 +DEC: Final = 12 + +def new_years(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def martin_luther_king_day(year: int) -> tuple[int, int, int]: ... +def lincolns_birthday(year: int) -> tuple[int, int, int]: ... +def valentines_day(year: int) -> tuple[int, int, int]: ... +def washingtons_birthday(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def presidents_day(year: int) -> tuple[int, int, int]: ... +def pulaski_day(year: int) -> tuple[int, int, int]: ... +def easter(year: int, church: Literal["western", "orthodox", "eastern"] | None = None) -> tuple[int, int, int]: ... +def may_day(year: int) -> tuple[int, int, int]: ... +def mothers_day(year: int) -> tuple[int, int, int]: ... +def memorial_day(year: int) -> tuple[int, int, int]: ... +def fathers_day(year: int) -> tuple[int, int, int]: ... +def juneteenth(year: int) -> tuple[int, int, int]: ... +def flag_day(year: int) -> tuple[int, int, int]: ... +def independence_day(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def labor_day(year: int) -> tuple[int, int, int]: ... +def indigenous_peoples_day(year: int, country: str = "usa") -> tuple[int, int, int]: ... +@deprecated("The `columbus_day` function will be removed in a future release. Use `indigenous_peoples_day` instead.") +def columbus_day(year: int, country: str = "usa") -> tuple[int, int, int]: ... +def halloween(year: int) -> tuple[int, int, int]: ... +def election_day(year: int) -> tuple[int, int, int]: ... +def veterans_day(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def rememberance_day(year: int) -> tuple[int, int, int]: ... +def armistice_day(year: int) -> tuple[int, int, int]: ... +def thanksgiving(year: int, country: Literal["usa", "canada"] = "usa") -> tuple[int, int, int]: ... +def christmas_eve(year: int) -> tuple[int, int, int]: ... +def christmas(year: int, observed: bool | None = None) -> tuple[int, int, int]: ... +def new_years_eve(year: int) -> tuple[int, int, int]: ... +def hanukkah(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def purim(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def rosh_hashanah(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def yom_kippur(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def passover(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def shavuot(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def sukkot(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def shemini_azeret(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def lag_baomer(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def tu_beshvat(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def tisha_bav(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def dia_constitucion(year: int, observed: bool | None = True) -> tuple[int, int, int]: ... +def natalicio_benito_juarez(year: int, observed: bool | None = True) -> tuple[int, int, int]: ... +def dia_independencia(year: int) -> tuple[int, int, int]: ... +def dia_revolucion(year: int) -> tuple[int, int, int]: ... +def ramadan(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def ashura(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def eid_alfitr(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... +def eid_aladha(year: int, eve: bool | None = None) -> tuple[int, int, int]: ... + +class Holidays: + year: int + def __init__(self, year: int | None = None) -> None: ... + def set_year(self, year: int) -> None: ... + @property + def christmas(self) -> tuple[int, int, int]: ... + @property + def christmas_eve(self) -> tuple[int, int, int]: ... + @property + def thanksgiving(self) -> tuple[int, int, int]: ... + @property + def new_years(self) -> tuple[int, int, int]: ... + @property + def new_years_eve(self) -> tuple[int, int, int]: ... + @property + def independence_day(self) -> tuple[int, int, int]: ... + @property + def flag_day(self) -> tuple[int, int, int]: ... + @property + def election_day(self) -> tuple[int, int, int]: ... + @property + def presidents_day(self) -> tuple[int, int, int]: ... + @property + def washingtons_birthday(self) -> tuple[int, int, int]: ... + @property + def lincolns_birthday(self) -> tuple[int, int, int]: ... + @property + def memorial_day(self) -> tuple[int, int, int]: ... + @property + def juneteenth(self) -> tuple[int, int, int]: ... + @property + def labor_day(self) -> tuple[int, int, int]: ... + @property + def indigenous_peoples_day(self) -> tuple[int, int, int]: ... + @property + def columbus_day(self) -> tuple[int, int, int]: ... + @property + def veterans_day(self) -> tuple[int, int, int]: ... + @property + def valentines_day(self) -> tuple[int, int, int]: ... + @property + def halloween(self) -> tuple[int, int, int]: ... + @property + def mothers_day(self) -> tuple[int, int, int]: ... + @property + def fathers_day(self) -> tuple[int, int, int]: ... + @property + def pulaski_day(self) -> tuple[int, int, int]: ... + @property + def easter(self) -> tuple[int, int, int]: ... + @property + def martin_luther_king_day(self) -> tuple[int, int, int]: ... + @property + def hanukkah(self) -> tuple[int, int, int]: ... + @property + def purim(self) -> tuple[int, int, int]: ... + @property + def rosh_hashanah(self) -> tuple[int, int, int]: ... + @property + def yom_kippur(self) -> tuple[int, int, int]: ... + @property + def passover(self) -> tuple[int, int, int]: ... + @property + def shavuot(self) -> tuple[int, int, int]: ... + @property + def sukkot(self) -> tuple[int, int, int]: ... + @property + def tu_beshvat(self) -> tuple[int, int, int]: ... + @property + def shemini_azeret(self) -> tuple[int, int, int]: ... + @property + def lag_baomer(self) -> tuple[int, int, int]: ... + @property + def tisha_bav(self) -> tuple[int, int, int]: ... + @property + def dia_constitucion(self) -> tuple[int, int, int]: ... + @property + def natalicio_benito_juarez(self) -> tuple[int, int, int]: ... + @property + def dia_independencia(self) -> tuple[int, int, int]: ... + @property + def dia_revolucion(self) -> tuple[int, int, int]: ... + @property + def ramadan(self) -> tuple[int, int, int]: ... + @property + def ashura(self) -> tuple[int, int, int]: ... + @property + def eid_alfitr(self) -> tuple[int, int, int]: ... + @property + def eid_aladha(self) -> tuple[int, int, int]: ... diff --git a/stubs/convertdate/convertdate/indian_civil.pyi b/stubs/convertdate/convertdate/indian_civil.pyi new file mode 100644 index 000000000000..d3121e0f3bba --- /dev/null +++ b/stubs/convertdate/convertdate/indian_civil.pyi @@ -0,0 +1,15 @@ +from typing import Final, Literal + +WEEKDAYS: Final = ("Ravivāra", "Somavāra", "Maṅgalavāra", "Budhavāra", "Guruvāra", "Śukravāra", "Śanivāra") +MONTHS: Final[tuple[str, ...]] +HAVE_31_DAYS: Final = (2, 3, 4, 5, 6) +HAVE_30_DAYS: Final = (7, 8, 9, 10, 11, 12) +SAKA_EPOCH: Final = 78 + +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[30, 31]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/islamic.pyi b/stubs/convertdate/convertdate/islamic.pyi new file mode 100644 index 000000000000..a1b29ee695c9 --- /dev/null +++ b/stubs/convertdate/convertdate/islamic.pyi @@ -0,0 +1,17 @@ +from typing import Final, Literal + +EPOCH: Final = 1948439.5 +WEEKDAYS: Final = ("al-'ahad", "al-'ithnayn", "ath-thalatha'", "al-'arb`a'", "al-khamis", "al-jum`a", "as-sabt") +MONTHS: Final[list[str]] +HAS_29_DAYS: Final = (2, 4, 6, 8, 10) +HAS_30_DAYS: Final = (1, 3, 5, 7, 9, 11) + +def leap(year: int) -> bool: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_jd_gregorianyear(gregorianyear: int, islamic_month: int, islamic_day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[29, 30]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/iso.pyi b/stubs/convertdate/convertdate/iso.pyi new file mode 100644 index 000000000000..f8f6021cf11a --- /dev/null +++ b/stubs/convertdate/convertdate/iso.pyi @@ -0,0 +1,17 @@ +import datetime +from typing import Final, Literal + +MON: Final = 0 +TUE: Final = 1 +WED: Final = 2 +THU: Final = 3 +FRI: Final = 4 +SAT: Final = 5 +SUN: Final = 6 + +def to_jd(year: int, week: int, day: int) -> float: ... +def from_jd(jd: float) -> datetime._IsoCalendarDate: ... +def weeks_per_year(year: int) -> Literal[52, 53]: ... +def from_gregorian(year: int, month: int, day: int) -> datetime._IsoCalendarDate: ... +def to_gregorian(year: int, week: int, day: int) -> tuple[int, int, int]: ... +def format(year: int, week: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/julian.pyi b/stubs/convertdate/convertdate/julian.pyi new file mode 100644 index 000000000000..4ef363bb981c --- /dev/null +++ b/stubs/convertdate/convertdate/julian.pyi @@ -0,0 +1,20 @@ +from typing import Final, Literal + +J0000: Final = 1721424.5 +J1970: Final = 2440587.5 +JMJD: Final = 2400000.5 +JULIAN_EPOCH: Final = 1721423.5 +J2000: Final = 2451545.0 +JULIANCENTURY: Final = 36525.0 +HAVE_30_DAYS: Final = (4, 6, 9, 11) +HAVE_31_DAYS: Final = (1, 3, 5, 7, 8, 10, 12) + +def leap(year: int) -> bool: ... +def month_length(year: int, month: int) -> Literal[28, 29, 30, 31]: ... +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int, format_string: str = "%-d %B %y") -> str: ... diff --git a/stubs/convertdate/convertdate/julianday.pyi b/stubs/convertdate/convertdate/julianday.pyi new file mode 100644 index 000000000000..cedad663b7ab --- /dev/null +++ b/stubs/convertdate/convertdate/julianday.pyi @@ -0,0 +1,8 @@ +import datetime + +def to_datetime(jdc: float) -> datetime.datetime: ... +def from_datetime(dt: datetime.datetime) -> float: ... +def to_gregorian(jdc: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> float: ... +def to_julian(jdc: float) -> tuple[int, int, int]: ... +def from_julian(year: int, month: int, day: int) -> float: ... diff --git a/stubs/convertdate/convertdate/mayan.pyi b/stubs/convertdate/convertdate/mayan.pyi new file mode 100644 index 000000000000..310f04093135 --- /dev/null +++ b/stubs/convertdate/convertdate/mayan.pyi @@ -0,0 +1,43 @@ +from _typeshed import Unused +from collections.abc import Generator +from typing import Final, Literal, overload +from typing_extensions import Never + +EPOCH: Final = 584282.5 +HAAB: Final[list[str]] +HAAB_TRANSLATIONS: Final[list[str]] +TZOLKIN: Final[list[str]] +TZOLKIN_TRANSLATIONS: Final[list[str]] + +def to_jd(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int, int, int]: ... +def to_gregorian(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int, int, int]: ... +def to_haab(jd: float) -> tuple[int, str]: ... +def to_tzolkin(jd: float) -> tuple[int, str]: ... +def lc_to_haab(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, str]: ... +def lc_to_tzolkin(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> tuple[int, str]: ... +def lc_to_haab_tzolkin(baktun: int, katun: int, tun: int, uinal: int, kin: int) -> str: ... +def translate_haab(h: str) -> str | None: ... +def translate_tzolkin(tz: str) -> str | None: ... +def tzolkin_generator(number: int | None = None, name: str | None = None) -> Generator[tuple[int, str]]: ... +def longcount_generator( + baktun: int, katun: int, tun: int, uinal: int, kin: int +) -> Generator[tuple[int, int, int, int, int], None, Never]: ... +def next_haab(month: str, jd: float) -> float: ... +def next_tzolkin(tzolkin: tuple[int, str], jd: float) -> float: ... +def next_tzolkin_haab(tzolkin: tuple[int, str], haab: tuple[int, str], jd: float) -> float: ... +def month_length(month: str) -> Literal[5, 20]: ... + +@overload +def haab_monthcalendar( + baktun: int, katun: int, tun: int, uinal: int, kin: int, jdc: None = None +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... +@overload +def haab_monthcalendar( + baktun: Unused = None, katun: Unused = None, tun: Unused = None, uinal: Unused = None, kin: Unused = None, jdc: float = ... +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... + +def haab_monthcalendar_prospective( + haabmonth: str, jdc: float +) -> list[list[tuple[int | None, tuple[int, str] | None, tuple[int, int, int, int, int] | None]]]: ... diff --git a/stubs/convertdate/convertdate/ordinal.pyi b/stubs/convertdate/convertdate/ordinal.pyi new file mode 100644 index 000000000000..893fc7abb1be --- /dev/null +++ b/stubs/convertdate/convertdate/ordinal.pyi @@ -0,0 +1,4 @@ +def to_jd(year: int, dayofyear: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int]: ... +def to_gregorian(year: int, dayofyear: int) -> tuple[int, int, int]: ... diff --git a/stubs/convertdate/convertdate/persian.pyi b/stubs/convertdate/convertdate/persian.pyi new file mode 100644 index 000000000000..35746af8adc7 --- /dev/null +++ b/stubs/convertdate/convertdate/persian.pyi @@ -0,0 +1,19 @@ +from typing import Final, Literal + +EPOCH: Final = 1948320.5 +WEEKDAYS: Final[tuple[str, ...]] +MONTHS: Final[list[str]] +HAS_31_DAYS: Final = (1, 2, 3, 4, 5, 6) +HAS_30_DAYS: Final = (7, 8, 9, 10, 11) + +def leap(year: int) -> bool: ... +def equinox_jd(gyear: int) -> int: ... +def last_equinox_jd(jd: float) -> int: ... +def jd_to_pyear(jd: float) -> tuple[int, int]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def month_length(year: int, month: int) -> Literal[29, 30, 31]: ... +def monthcalendar(year: int, month: int) -> list[list[int | None]]: ... +def format(year: int, month: int, day: int) -> str: ... diff --git a/stubs/convertdate/convertdate/positivist.pyi b/stubs/convertdate/convertdate/positivist.pyi new file mode 100644 index 000000000000..51dcfd398dc4 --- /dev/null +++ b/stubs/convertdate/convertdate/positivist.pyi @@ -0,0 +1,15 @@ +from typing import Final, Literal + +EPOCH: Final = 2374479.5 +YEAR_EPOCH: Final = 1789 +DAYS_IN_YEAR: Final = 365 +MONTHS: Final[tuple[str, ...]] + +def legal_date(year: int, month: int, day: int) -> Literal[True]: ... +def to_jd(year: int, month: int, day: int) -> float: ... +def from_jd(jd: float) -> tuple[int, int, int]: ... +def from_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def to_gregorian(year: int, month: int, day: int) -> tuple[int, int, int]: ... +def dayname(year: int, month: int, day: int) -> tuple[str, str]: ... +def weekday(day: int) -> int: ... +def festival(month: int, day: int) -> str | None: ... diff --git a/stubs/convertdate/convertdate/utils.pyi b/stubs/convertdate/convertdate/utils.pyi new file mode 100644 index 000000000000..3e6f89a2e981 --- /dev/null +++ b/stubs/convertdate/convertdate/utils.pyi @@ -0,0 +1,53 @@ +from typing import Final, Literal, overload + +TROPICALYEAR: Final[float] + +@overload +def amod(a: float, b: int) -> int: ... +@overload +def amod(a: float, b: float) -> float: ... + +def jwday(j: float) -> int: ... + +@overload +def weekday_before(weekday: int, jd: int) -> int: ... +@overload +def weekday_before(weekday: int, jd: float) -> float: ... + +@overload +def search_weekday(weekday: int, jd: int, direction: Literal[-1, 1], offset: int) -> int: ... +@overload +def search_weekday(weekday: int, jd: float, direction: Literal[-1, 1], offset: int) -> float: ... + +@overload +def nearest_weekday(weekday: int, jd: int) -> int: ... +@overload +def nearest_weekday(weekday: int, jd: float) -> float: ... + +@overload +def next_weekday(weekday: int, jd: int) -> int: ... +@overload +def next_weekday(weekday: int, jd: float) -> float: ... + +@overload +def next_or_current_weekday(weekday: int, jd: int) -> int: ... +@overload +def next_or_current_weekday(weekday: int, jd: float) -> float: ... + +@overload +def previous_weekday(weekday: int, jd: int) -> int: ... +@overload +def previous_weekday(weekday: int, jd: float) -> float: ... + +@overload +def previous_or_current_weekday(weekday: int, jd: int) -> int: ... +@overload +def previous_or_current_weekday(weekday: int, jd: float) -> float: ... + +@overload +def n_weeks(weekday: int, jd: int, nthweek: int) -> int: ... +@overload +def n_weeks(weekday: int, jd: float, nthweek: int) -> float: ... + +def monthcalendarhelper(start_weekday: int, month_length: int) -> list[list[int | None]]: ... +def nth_day_of_month(n: int, weekday: int, month: int, year: int) -> tuple[int, int, int]: ... diff --git a/stubs/croniter/@tests/stubtest_allowlist.txt b/stubs/croniter/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..a5206909ac76 --- /dev/null +++ b/stubs/croniter/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +croniter.tests.* diff --git a/stubs/croniter/METADATA.toml b/stubs/croniter/METADATA.toml new file mode 100644 index 000000000000..0470bcfbbb5a --- /dev/null +++ b/stubs/croniter/METADATA.toml @@ -0,0 +1,2 @@ +version = "6.2.4" +upstream-repository = "https://github.com/pallets-eco/croniter" diff --git a/stubs/croniter/croniter/__init__.pyi b/stubs/croniter/croniter/__init__.pyi new file mode 100644 index 000000000000..164f8b701f56 --- /dev/null +++ b/stubs/croniter/croniter/__init__.pyi @@ -0,0 +1,43 @@ +from . import croniter as croniter_m +from .croniter import ( + DAY_FIELD as DAY_FIELD, + HOUR_FIELD as HOUR_FIELD, + MINUTE_FIELD as MINUTE_FIELD, + MONTH_FIELD as MONTH_FIELD, + OVERFLOW32B_MODE as OVERFLOW32B_MODE, + SECOND_FIELD as SECOND_FIELD, + UTC_DT as UTC_DT, + YEAR_FIELD as YEAR_FIELD, + CroniterBadCronError as CroniterBadCronError, + CroniterBadDateError as CroniterBadDateError, + CroniterBadTypeRangeError as CroniterBadTypeRangeError, + CroniterError as CroniterError, + CroniterNotAlphaError as CroniterNotAlphaError, + CroniterUnsupportedSyntaxError as CroniterUnsupportedSyntaxError, + croniter as croniter, + croniter_range as croniter_range, + datetime_to_timestamp as datetime_to_timestamp, +) + +cron_m = croniter_m + +__all__ = [ + "DAY_FIELD", + "HOUR_FIELD", + "MINUTE_FIELD", + "MONTH_FIELD", + "OVERFLOW32B_MODE", + "SECOND_FIELD", + "UTC_DT", + "YEAR_FIELD", + "CroniterBadCronError", + "CroniterBadDateError", + "CroniterBadTypeRangeError", + "CroniterError", + "CroniterNotAlphaError", + "CroniterUnsupportedSyntaxError", + "cron_m", + "croniter", + "croniter_range", + "datetime_to_timestamp", +] diff --git a/stubs/croniter/croniter/croniter.pyi b/stubs/croniter/croniter/croniter.pyi new file mode 100644 index 000000000000..b9ba661e3ca9 --- /dev/null +++ b/stubs/croniter/croniter/croniter.pyi @@ -0,0 +1,359 @@ +import datetime +from _typeshed import Unused +from collections.abc import Generator, Iterable +from re import Match, Pattern +from typing import Any, Final, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self + +_R_co = TypeVar("_R_co", float, datetime.datetime, default=float, covariant=True) +_R2_co = TypeVar("_R2_co", float, datetime.datetime, covariant=True) +_Expressions: TypeAlias = list[str] # fixed-length list of 5 or 6 strings +ExpandedExpression: TypeAlias = list[int | Literal["*", "l"]] + +@type_check_only +class _AllIter(Protocol[_R_co]): + @overload + def __call__( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def __call__( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + +def is_32bit() -> bool: ... + +OVERFLOW32B_MODE: Final[bool] + +UTC_DT: Final[datetime.timezone] +EPOCH: Final[datetime.datetime] +M_ALPHAS: Final[dict[str, int]] +DOW_ALPHAS: Final[dict[str, int]] + +MINUTE_FIELD: Final = 0 +HOUR_FIELD: Final = 1 +DAY_FIELD: Final = 2 +MONTH_FIELD: Final = 3 +DOW_FIELD: Final = 4 +SECOND_FIELD: Final = 5 +YEAR_FIELD: Final = 6 + +UNIX_FIELDS: Final[tuple[int, int, int, int, int]] +SECOND_FIELDS: Final[tuple[int, int, int, int, int, int]] +YEAR_FIELDS: Final[tuple[int, int, int, int, int, int, int]] + +step_search_re: Final[Pattern[str]] +only_int_re: Final[Pattern[str]] + +DAYS: Final[tuple[int, int, int, int, int, int, int, int, int, int, int, int]] +WEEKDAYS: Final[str] +MONTHS: Final[str] +star_or_int_re: Final[Pattern[str]] +special_dow_re: Final[Pattern[str]] +nearest_weekday_re: Final[Pattern[str]] +re_star: Final[Pattern[str]] +hash_expression_re: Final[Pattern[str]] + +CRON_FIELDS: Final[dict[str | int, tuple[int, ...]]] +UNIX_CRON_LEN: Final = 5 +SECOND_CRON_LEN: Final = 6 +YEAR_CRON_LEN: Final = 7 +VALID_LEN_EXPRESSION: Final[set[int]] +MARKER: object + +def datetime_to_timestamp(d: datetime.datetime) -> float: ... + +class CroniterError(ValueError): ... +class CroniterBadTypeRangeError(TypeError): ... +class CroniterBadCronError(CroniterError): ... +class CroniterUnsupportedSyntaxError(CroniterBadCronError): ... +class CroniterBadDateError(CroniterError): ... +class CroniterNotAlphaError(CroniterError): ... + +class croniter(Generic[_R_co]): + MONTHS_IN_YEAR: Final = 12 + RANGES: Final[ + tuple[ + tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int], tuple[int, int] + ] + ] + ALPHACONV: Final[ + tuple[ + dict[Never, Never], + dict[Never, Never], + dict[str, str], + dict[str, int], + dict[str, int], + dict[Never, Never], + dict[Never, Never], + ] + ] + LOWMAP: Final[ + tuple[ + dict[Never, Never], + dict[Never, Never], + dict[int, int], + dict[int, int], + dict[int, int], + dict[Never, Never], + dict[Never, Never], + ] + ] + LEN_MEANS_ALL: Final[tuple[int, int, int, int, int, int, int]] + + second_at_beginning: bool + tzinfo: datetime.tzinfo | None + + start_time: float + dst_start_time: float + cur: float + + expanded: list[list[str]] + nth_weekday_of_month: dict[str, set[int]] + expressions: _Expressions + nearest_weekday: set[int] + fields: tuple[int, ...] + + @overload + def __new__( + cls, + expr_format: str, + start_time: float | datetime.datetime | None = None, + ret_type: type[float] = ..., + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[float]: ... + @overload + def __new__( + cls, + expr_format: str, + start_time: float | datetime.datetime | None, + ret_type: type[datetime.datetime], + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[datetime.datetime]: ... + @overload + def __new__( + cls, + expr_format: str, + *, + ret_type: type[datetime.datetime], + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> croniter[datetime.datetime]: ... + + def __init__( + self, + expr_format: str, + start_time: float | datetime.datetime | None = None, + ret_type: type[_R_co] = ..., + day_or: bool = True, + max_years_between_matches: int | None = None, + is_prev: bool = False, + hash_id: str | bytes | None = None, + implement_cron_bug: bool = False, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, + ) -> None: ... + + @overload + def get_next( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R2_co: ... + @overload + def get_next( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R_co: ... + + @overload + def get_prev( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R2_co: ... + @overload + def get_prev( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool = True + ) -> _R_co: ... + + @overload + def get_current(self, ret_type: type[_R2_co]) -> _R2_co: ... + @overload + def get_current(self, ret_type: None = None) -> _R_co: ... + + def set_current(self, start_time: float | datetime.datetime | None, force: bool = True) -> float: ... + @staticmethod + def datetime_to_timestamp(d: datetime.datetime) -> float: ... + def timestamp_to_datetime(self, timestamp: float, tzinfo: datetime.tzinfo | None = ...) -> datetime.datetime: ... + + @overload + def all_next( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def all_next( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + + @overload + def all_prev( + self, ret_type: type[_R2_co], start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R2_co]: ... + @overload + def all_prev( + self, ret_type: None = None, start_time: float | datetime.datetime | None = None, update_current: bool | None = None + ) -> Generator[_R_co]: ... + + def iter(self, *args: Unused, **kwargs: Unused) -> _AllIter[_R_co]: ... + def __iter__(self) -> Self: ... + + @overload + def next( + self, + ret_type: type[_R2_co], + start_time: float | datetime.datetime | None = None, + is_prev: bool | None = None, + update_current: bool | None = None, + ) -> _R2_co: ... + @overload + def next( + self, + ret_type: None = None, + start_time: float | datetime.datetime | None = None, + is_prev: bool | None = None, + update_current: bool | None = None, + ) -> _R_co: ... + + __next__ = next + @classmethod + def value_alias( + cls, + val: int, + field_index: Literal[0, 1, 2, 3, 4, 5, 6], + len_expressions: int | list[Any] | dict[Any, Any] | tuple[Any, ...] | set[Any] = 5, + ) -> int: ... + DAYS_IN_MONTH: Final[dict[int, int]] + @classmethod + def expand( + cls, + expr_format: str, + hash_id: bytes | None = None, + second_at_beginning: bool = False, + from_timestamp: float | None = None, + strict: bool = False, + strict_year: int | Iterable[int] | None = None, + ) -> tuple[list[ExpandedExpression], dict[str, set[int]]]: ... + @classmethod + def is_valid( + cls, + expression: str, + hash_id: bytes | None = None, + encoding: str = "UTF-8", + second_at_beginning: bool = False, + strict: bool = False, + strict_year: int | Iterable[int] | None = None, + ) -> bool: ... + @classmethod + def match( + cls, + cron_expression: str, + testdate: float | datetime.datetime | None, + day_or: bool = True, + second_at_beginning: bool = False, + precision_in_seconds: int | None = None, + ) -> bool: ... + @classmethod + def match_range( + cls, + cron_expression: str, + from_datetime: datetime.datetime, + to_datetime: datetime.datetime, + day_or: bool = True, + second_at_beginning: bool = False, + precision_in_seconds: int | None = None, + ) -> bool: ... + +@overload +def croniter_range( + start: float | datetime.datetime, + stop: float | datetime.datetime, + expr_format: str, + ret_type: type[_R2_co], + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[_R2_co]: ... +@overload +def croniter_range( + start: float, + stop: float | datetime.datetime, + expr_format: str, + ret_type: None = None, + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[float]: ... +@overload +def croniter_range( + start: datetime.datetime, + stop: float | datetime.datetime, + expr_format: str, + ret_type: None = None, + day_or: bool = True, + exclude_ends: bool = False, + _croniter: type[croniter] | None = None, + second_at_beginning: bool = False, + expand_from_start_time: bool = False, +) -> Generator[datetime.datetime]: ... + +class HashExpander: + cron: croniter + def __init__(self, cronit: croniter) -> None: ... + + @overload + def do( + self, + idx: int, + hash_type: Literal["r"], + hash_id: None = None, + range_end: int | None = None, + range_begin: int | None = None, + ) -> int: ... + @overload + def do( + self, idx: int, hash_type: str, hash_id: bytes, range_end: int | None = None, range_begin: int | None = None + ) -> int: ... + @overload + def do( + self, idx: int, hash_type: str = "h", *, hash_id: bytes, range_end: int | None = None, range_begin: int | None = None + ) -> int: ... + + def match(self, efl: Unused, idx: Unused, expr: str, hash_id: bytes | None = None, **kw: Unused) -> Match[str] | None: ... + def expand( + self, + efl: object, + idx: int, + expr: str, + hash_id: bytes | None = None, + match: Match[str] | None | Literal[""] = "", + **kw: object, + ) -> str: ... + +EXPANDERS: dict[str, type[HashExpander]] diff --git a/stubs/datauri/METADATA.toml b/stubs/datauri/METADATA.toml new file mode 100644 index 000000000000..1c6aeddc2a16 --- /dev/null +++ b/stubs/datauri/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/eclecticiq/python-data-uri" diff --git a/stubs/datauri/datauri/__init__.pyi b/stubs/datauri/datauri/__init__.pyi new file mode 100644 index 000000000000..491565ffefb8 --- /dev/null +++ b/stubs/datauri/datauri/__init__.pyi @@ -0,0 +1 @@ +from .datauri import DataURIError as DataURIError, discover as discover, parse as parse diff --git a/stubs/datauri/datauri/datauri.pyi b/stubs/datauri/datauri/datauri.pyi new file mode 100644 index 000000000000..d9223caca30f --- /dev/null +++ b/stubs/datauri/datauri/datauri.pyi @@ -0,0 +1,19 @@ +from collections.abc import Generator +from re import Pattern +from typing import Final + +RE_DATA_URI: Final[Pattern[str]] # undocumented + +class DataURIError(ValueError): ... + +class ParsedDataURI: + media_type: str | None + data: bytes + uri: str + + def __init__(self, media_type: str | None, data: bytes, uri: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +def parse(uri: str) -> ParsedDataURI: ... +def discover(s: str) -> Generator[ParsedDataURI]: ... diff --git a/stubs/dateparser/@tests/stubtest_allowlist.txt b/stubs/dateparser/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..40724a190bca --- /dev/null +++ b/stubs/dateparser/@tests/stubtest_allowlist.txt @@ -0,0 +1,8 @@ +dateparser.calendars.hijri +dateparser.calendars.hijri_parser +dateparser.calendars.jalali +dateparser.calendars.jalali_parser +dateparser.search.detection.BaseLanguageDetector.iterate_applicable_languages + +# Timezone and other internal data: +dateparser.data.date_translation_data.* diff --git a/stubs/dateparser/METADATA.toml b/stubs/dateparser/METADATA.toml new file mode 100644 index 000000000000..34b910b18e45 --- /dev/null +++ b/stubs/dateparser/METADATA.toml @@ -0,0 +1,5 @@ +version = "1.4.1" +upstream-repository = "https://github.com/scrapinghub/dateparser" + +[tool.stubtest] +extras = ["fasttext", "langdetect"] diff --git a/stubs/dateparser/dateparser/__init__.pyi b/stubs/dateparser/dateparser/__init__.pyi new file mode 100644 index 000000000000..ff3ab72b686a --- /dev/null +++ b/stubs/dateparser/dateparser/__init__.pyi @@ -0,0 +1,44 @@ +import datetime +from typing import Any, Final, Literal, TypedDict, type_check_only + +from dateparser.conf import Settings + +from .date import DateDataParser, _DetectLanguagesFunction + +__version__: Final[str] + +_default_parser: DateDataParser + +@type_check_only +class _Settings(TypedDict, total=False): # noqa: Y049 + DATE_ORDER: str + PREFER_LOCALE_DATE_ORDER: bool + TIMEZONE: str + TO_TIMEZONE: str + RETURN_AS_TIMEZONE_AWARE: bool + PREFER_MONTH_OF_YEAR: Literal["current", "first", "last"] + PREFER_DAY_OF_MONTH: Literal["current", "first", "last"] + PREFER_DATES_FROM: Literal["current_period", "future", "past"] + RELATIVE_BASE: datetime.datetime + STRICT_PARSING: bool + REQUIRE_PARTS: list[Literal["day", "month", "year"]] + SKIP_TOKENS: list[str] + NORMALIZE: bool + RETURN_TIME_AS_PERIOD: bool + RETURN_TIME_SPAN: bool + DEFAULT_START_OF_WEEK: Literal["monday", "sunday"] + DEFAULT_DAYS_IN_MONTH: int + PARSERS: list[Literal["timestamp", "relative-time", "custom-formats", "absolute-time", "no-spaces-time"]] + DEFAULT_LANGUAGES: list[str] + LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD: float + CACHE_SIZE_LIMIT: int + +def parse( + date_string: str, + date_formats: list[str] | tuple[str, ...] | set[str] | None = None, + languages: list[str] | tuple[str, ...] | set[str] | None = None, + locales: list[str] | tuple[str, ...] | set[str] | None = None, + region: str | None = None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, +) -> datetime.datetime | None: ... diff --git a/stubs/dateparser/dateparser/calendars/__init__.pyi b/stubs/dateparser/dateparser/calendars/__init__.pyi new file mode 100644 index 000000000000..82f7f5df75b6 --- /dev/null +++ b/stubs/dateparser/dateparser/calendars/__init__.pyi @@ -0,0 +1,47 @@ +from abc import abstractmethod +from datetime import datetime +from typing import ClassVar, Protocol, type_check_only + +from dateparser.conf import Settings +from dateparser.date import DateData +from dateparser.parser import _parser + +# Examples: `hijri_parser.hijri` class or `convertdate.persian` module +@type_check_only +class _CalendarConverter(Protocol): + @classmethod + def to_gregorian(cls, year: int, month: int, day: int) -> tuple[int, int, int]: ... + @classmethod + def from_gregorian( + cls, year: int | None = None, month: int | None = None, day: int | None = None + ) -> tuple[int, int, int]: ... + @classmethod + def month_length(cls, year: int, month: int) -> int: ... + +# Examples: `hijri_parser.HijriDate` or `jalali_parser.PersianDate` +@type_check_only +class _NonGregorianDate(Protocol): + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... + +class CalendarBase: + parser: type[_parser] + source: str + def __init__(self, source: str) -> None: ... + def get_date(self) -> DateData | None: ... + +class non_gregorian_parser(_parser): + calendar_converter: ClassVar[type[_CalendarConverter]] + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[_NonGregorianDate]] + @classmethod + def to_latin(cls, source: str) -> str: ... + @abstractmethod + def handle_two_digit_year(self, year: int) -> int: ... + @classmethod + def parse(cls, datestring: str, settings: Settings) -> tuple[datetime, str | None]: ... # type: ignore[override] diff --git a/stubs/dateparser/dateparser/calendars/hijri.pyi b/stubs/dateparser/dateparser/calendars/hijri.pyi new file mode 100644 index 000000000000..3a134a5b0b69 --- /dev/null +++ b/stubs/dateparser/dateparser/calendars/hijri.pyi @@ -0,0 +1,5 @@ +from dateparser.calendars import CalendarBase +from dateparser.calendars.hijri_parser import hijri_parser + +class HijriCalendar(CalendarBase): + parser: type[hijri_parser] diff --git a/stubs/dateparser/dateparser/calendars/hijri_parser.pyi b/stubs/dateparser/dateparser/calendars/hijri_parser.pyi new file mode 100644 index 000000000000..13551dba93dc --- /dev/null +++ b/stubs/dateparser/dateparser/calendars/hijri_parser.pyi @@ -0,0 +1,28 @@ +from typing import ClassVar + +from dateparser.calendars import non_gregorian_parser + +class hijri: + @classmethod + def to_gregorian(cls, year: int | None = None, month: int | None = None, day: int | None = None) -> tuple[int, int, int]: ... + @classmethod + def from_gregorian( + cls, year: int | None = None, month: int | None = None, day: int | None = None + ) -> tuple[int, int, int]: ... + @classmethod + def month_length(cls, year: int | None, month: int | None) -> int: ... + +class HijriDate: + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... + +class hijri_parser(non_gregorian_parser): + calendar_converter: ClassVar[type[hijri]] + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[HijriDate]] + def handle_two_digit_year(self, year: int) -> int: ... diff --git a/stubs/dateparser/dateparser/calendars/jalali.pyi b/stubs/dateparser/dateparser/calendars/jalali.pyi new file mode 100644 index 000000000000..8df2dce7228a --- /dev/null +++ b/stubs/dateparser/dateparser/calendars/jalali.pyi @@ -0,0 +1,6 @@ +from dateparser.calendars.jalali_parser import jalali_parser + +from . import CalendarBase + +class JalaliCalendar(CalendarBase): + parser: type[jalali_parser] diff --git a/stubs/dateparser/dateparser/calendars/jalali_parser.pyi b/stubs/dateparser/dateparser/calendars/jalali_parser.pyi new file mode 100644 index 000000000000..9c8064135b31 --- /dev/null +++ b/stubs/dateparser/dateparser/calendars/jalali_parser.pyi @@ -0,0 +1,18 @@ +from typing import ClassVar + +from dateparser.calendars import non_gregorian_parser + +class PersianDate: + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int) -> None: ... + def weekday(self) -> int | None: ... + +class jalali_parser(non_gregorian_parser): + # `calendar_converter` is `convertdate.persian` module + default_year: ClassVar[int] + default_month: ClassVar[int] + default_day: ClassVar[int] + non_gregorian_date_cls: ClassVar[type[PersianDate]] + def handle_two_digit_year(self, year: int) -> int: ... diff --git a/stubs/dateparser/dateparser/conf.pyi b/stubs/dateparser/dateparser/conf.pyi new file mode 100644 index 000000000000..d2fafefb1cdb --- /dev/null +++ b/stubs/dateparser/dateparser/conf.pyi @@ -0,0 +1,46 @@ +import datetime +from collections.abc import Callable +from typing import Any, Literal, ParamSpec, TypeVar +from typing_extensions import Self + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +class Settings: + # Next attributes are optional and may be missing. + # Please keep in sync with _Settings TypedDict + DATE_ORDER: str + PREFER_LOCALE_DATE_ORDER: bool + TIMEZONE: str + TO_TIMEZONE: str + RETURN_AS_TIMEZONE_AWARE: bool + PREFER_MONTH_OF_YEAR: Literal["current", "first", "last"] + PREFER_DAY_OF_MONTH: Literal["current", "first", "last"] + PREFER_DATES_FROM: Literal["current_period", "future", "past"] + RELATIVE_BASE: datetime.datetime + STRICT_PARSING: bool + REQUIRE_PARTS: list[Literal["day", "month", "year"]] + SKIP_TOKENS: list[str] + NORMALIZE: bool + RETURN_TIME_AS_PERIOD: bool + RETURN_TIME_SPAN: bool + DEFAULT_START_OF_WEEK: Literal["monday", "sunday"] + DEFAULT_DAYS_IN_MONTH: int + PARSERS: list[Literal["timestamp", "relative-time", "custom-formats", "absolute-time", "no-spaces-time"]] + DEFAULT_LANGUAGES: list[str] + LANGUAGE_DETECTION_CONFIDENCE_THRESHOLD: float + CACHE_SIZE_LIMIT: int + + def __new__(cls, *args, **kwargs) -> Self: ... + def __init__(self, settings: dict[str, Any] | None = None) -> None: ... + @classmethod + def get_key(cls, settings: dict[str, Any] | None = None) -> str: ... + def replace(self, mod_settings: dict[str, Any] | None = None, **kwds) -> Self: ... + +settings: Settings + +def apply_settings(f: Callable[_P, _R]) -> Callable[_P, _R]: ... + +class SettingValidationError(ValueError): ... + +def check_settings(settings: Settings) -> None: ... diff --git a/stubs/dateparser/dateparser/custom_language_detection/__init__.pyi b/stubs/dateparser/dateparser/custom_language_detection/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi b/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi new file mode 100644 index 000000000000..e7440af40333 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/fasttext.pyi @@ -0,0 +1 @@ +def detect_languages(text: str, confidence_threshold: float) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi b/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi new file mode 100644 index 000000000000..e7440af40333 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/langdetect.pyi @@ -0,0 +1 @@ +def detect_languages(text: str, confidence_threshold: float) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi b/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi new file mode 100644 index 000000000000..0f5de55de936 --- /dev/null +++ b/stubs/dateparser/dateparser/custom_language_detection/language_mapping.pyi @@ -0,0 +1 @@ +def map_languages(language_codes: list[str]) -> list[str]: ... diff --git a/stubs/dateparser/dateparser/data/__init__.pyi b/stubs/dateparser/dateparser/data/__init__.pyi new file mode 100644 index 000000000000..91633ea6b715 --- /dev/null +++ b/stubs/dateparser/dateparser/data/__init__.pyi @@ -0,0 +1 @@ +from .languages_info import language_locale_dict as language_locale_dict, language_order as language_order diff --git a/stubs/dateparser/dateparser/data/languages_info.pyi b/stubs/dateparser/dateparser/data/languages_info.pyi new file mode 100644 index 000000000000..5ac61c380052 --- /dev/null +++ b/stubs/dateparser/dateparser/data/languages_info.pyi @@ -0,0 +1,5 @@ +from typing import Final + +language_order: Final[list[str]] +language_map: Final[dict[str, list[str]]] +language_locale_dict: Final[dict[str, list[str]]] diff --git a/stubs/dateparser/dateparser/date.pyi b/stubs/dateparser/dateparser/date.pyi new file mode 100644 index 000000000000..0b730c9d6899 --- /dev/null +++ b/stubs/dateparser/dateparser/date.pyi @@ -0,0 +1,146 @@ +import re +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Callable, Iterable, Iterator, Set as AbstractSet +from datetime import date, datetime, tzinfo +from typing import Any, ClassVar, Final, Literal, NamedTuple, TypeAlias, TypeVar, overload, type_check_only + +from dateparser.conf import Settings +from dateparser.languages.loader import LocaleDataLoader +from dateparser.languages.locale import Locale + +_DateT = TypeVar("_DateT", bound=date) + +_DetectLanguagesFunction: TypeAlias = Callable[[str, float], list[str]] +_Period: TypeAlias = Literal["time", "day", "week", "month", "year"] +# Work around attribute and type having the same name. +_Weekday: TypeAlias = Incomplete # Actually it's dateutil._common.weekday class + +@type_check_only +class _DateData(NamedTuple): + date_obj: datetime | None + locale: str | None + period: _Period | None + +APOSTROPHE_LOOK_ALIKE_CHARS: Final[list[str]] +RE_NBSP: Final[re.Pattern[str]] +RE_SPACES: Final[re.Pattern[str]] +RE_TRIM_SPACES: Final[re.Pattern[str]] +RE_TRIM_COLONS: Final[re.Pattern[str]] +RE_SANITIZE_SKIP: Final[re.Pattern[str]] +RE_SANITIZE_RUSSIAN: Final[re.Pattern[str]] +RE_SANITIZE_PERIOD: Final[re.Pattern[str]] +RE_SANITIZE_ON: Final[re.Pattern[str]] +RE_SANITIZE_APOSTROPHE: Final[re.Pattern[str]] +RE_SEARCH_TIMESTAMP: Final[re.Pattern[str]] +RE_SANITIZE_CROATIAN: Final[re.Pattern[str]] +RE_SEARCH_NEGATIVE_TIMESTAMP: Final[re.Pattern[str]] + +def sanitize_spaces(date_string: str) -> str: ... +def date_range( + begin: _DateT, + end: _DateT, + *, + dt1: date | None = None, + dt2: date | None = None, + years: int = 0, + months: int = 0, + days: int = 0, + leapdays: int = 0, + weeks: int = 0, + hours: int = 0, + minutes: int = 0, + seconds: int = 0, + microseconds: int = 0, + weekday: int | _Weekday | None = None, + yearday: int | None = None, + nlyearday: int | None = None, + microsecond: int | None = None, +) -> Iterator[_DateT]: ... +def get_intersecting_periods( + low: _DateT, high: _DateT, period: Literal["year", "month", "week", "day", "hour", "minute", "second", "microsecond"] = "day" +) -> Iterator[_DateT]: ... +def sanitize_date(date_string: str) -> str: ... +def get_date_from_timestamp(date_string: str, settings: Settings, negative: bool | None = False) -> datetime | None: ... +def parse_with_formats(date_string: str, date_formats: Iterable[str], settings: Settings) -> DateData: ... + +class _DateLocaleParser: + locale: Locale + date_string: str + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None + def __init__( + self, + locale: Locale, + date_string: str, + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | None = None, + ) -> None: ... + @classmethod + def parse( + cls, + locale: Locale, + date_string: str, + date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | None = None, + ) -> DateData: ... + def _parse(self) -> DateData | None: ... + def _try_timestamp(self) -> DateData: ... + def _try_freshness_parser(self) -> DateData | None: ... + def _try_absolute_parser(self) -> DateData | None: ... + def _try_nospaces_parser(self) -> DateData | None: ... + def _try_parser(self, parse_method: Callable[[str, Settings, tzinfo | None], tuple[datetime, str]]) -> DateData | None: ... + def _try_given_formats(self) -> DateData | None: ... + def _get_translated_date(self) -> str: ... + def _get_translated_date_with_formatting(self) -> str: ... + def _is_valid_date_data(self, date_data: DateData) -> bool: ... + +class DateData: + date_obj: datetime | None + locale: str | None + period: _Period | None + def __init__(self, *, date_obj: datetime | None = None, period: _Period | None = None, locale: str | None = None) -> None: ... + + @overload + def __getitem__(self, k: Literal["date_obj"]) -> datetime | None: ... + @overload + def __getitem__(self, k: Literal["locale"]) -> str | None: ... + @overload + def __getitem__(self, k: Literal["period"]) -> _Period | None: ... + + @overload + def __setitem__(self, k: Literal["date_obj"], v: datetime) -> None: ... + @overload + def __setitem__(self, k: Literal["locale"], v: str) -> None: ... + @overload + def __setitem__(self, k: Literal["period"], v: _Period) -> None: ... + +class DateDataParser: + _settings: Settings + locale_loader: ClassVar[LocaleDataLoader | None] + try_previous_locales: bool + use_given_order: bool + languages: list[str] | None + locales: list[str] | tuple[str, ...] | AbstractSet[str] | None + region: str + detect_languages_function: _DetectLanguagesFunction | None + previous_locales: OrderedDict[Locale, None] + def __init__( + self, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + locales: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + region: str | None = None, + try_previous_locales: bool = False, + use_given_order: bool = False, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, + ) -> None: ... + def get_date_data( + self, date_string: str, date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None + ) -> DateData: ... + def get_date_tuple( + self, date_string: str, date_formats: list[str] | tuple[str, ...] | AbstractSet[str] | None = None + ) -> _DateData: ... + def _get_applicable_locales(self, date_string: str) -> Iterator[Locale]: ... + def _is_applicable_locale(self, locale: Locale, date_string: str) -> bool: ... + @classmethod + def _get_locale_loader(cls: type[DateDataParser]) -> LocaleDataLoader: ... diff --git a/stubs/dateparser/dateparser/date_parser.pyi b/stubs/dateparser/dateparser/date_parser.pyi new file mode 100644 index 000000000000..73a70cc9b735 --- /dev/null +++ b/stubs/dateparser/dateparser/date_parser.pyi @@ -0,0 +1,14 @@ +from collections.abc import Callable +from datetime import datetime, tzinfo + +from dateparser.conf import Settings + +class DateParser: + def parse( + self, + date_string: str, + parse_method: Callable[[str, Settings, tzinfo | None], tuple[datetime, str]], + settings: Settings | None = None, + ) -> tuple[datetime, str]: ... + +date_parser: DateParser diff --git a/stubs/dateparser/dateparser/freshness_date_parser.pyi b/stubs/dateparser/dateparser/freshness_date_parser.pyi new file mode 100644 index 000000000000..e05a0318a175 --- /dev/null +++ b/stubs/dateparser/dateparser/freshness_date_parser.pyi @@ -0,0 +1,20 @@ +import re +from _typeshed import Incomplete +from datetime import datetime +from typing import Final +from zoneinfo import ZoneInfo + +from dateparser.conf import Settings +from dateparser.date import DateData + +PATTERN: Final[re.Pattern[str]] + +class FreshnessDateDataParser: + def get_local_tz(self) -> ZoneInfo: ... + def parse(self, date_string: str, settings: Settings) -> tuple[datetime | None, str | None]: ... + def get_kwargs( + self, date_string: str + ) -> tuple[dict[str, float], dict[str, Incomplete]] | dict[None, None]: ... # return empty dict if pattern not found + def get_date_data(self, date_string: str, settings: Settings | None = None) -> DateData: ... + +freshness_date_parser: FreshnessDateDataParser diff --git a/stubs/dateparser/dateparser/languages/__init__.pyi b/stubs/dateparser/dateparser/languages/__init__.pyi new file mode 100644 index 000000000000..2f14a878d997 --- /dev/null +++ b/stubs/dateparser/dateparser/languages/__init__.pyi @@ -0,0 +1,2 @@ +from .loader import default_loader as default_loader +from .locale import Locale as Locale diff --git a/stubs/dateparser/dateparser/languages/dictionary.pyi b/stubs/dateparser/dateparser/languages/dictionary.pyi new file mode 100644 index 000000000000..a207c8ed5e7d --- /dev/null +++ b/stubs/dateparser/dateparser/languages/dictionary.pyi @@ -0,0 +1,32 @@ +import re +from _typeshed import Incomplete +from itertools import chain +from typing import Final, overload + +from dateparser.conf import Settings + +PARSER_HARDCODED_TOKENS: Final[list[str]] +PARSER_KNOWN_TOKENS: Final[list[str]] +ALWAYS_KEEP_TOKENS: Final[list[str]] +KNOWN_WORD_TOKENS: Final[list[str]] +PARENTHESES_PATTERN: Final[re.Pattern[str]] +NUMERAL_PATTERN: Final[re.Pattern[str]] +KEEP_TOKEN_PATTERN: Final[re.Pattern[str]] + +class UnknownTokenError(Exception): ... + +class Dictionary: + info: dict[str, Incomplete] + def __init__(self, locale_info: dict[str, Incomplete], settings: Settings | None = None) -> None: ... + def __contains__(self, key: str) -> bool: ... + def __getitem__(self, key: str): ... + def __iter__(self) -> chain[str]: ... + def are_tokens_valid(self, tokens: list[str]) -> bool: ... + + @overload + def split(self, string: None, keep_formatting: bool = False) -> None: ... + @overload + def split(self, string: str, keep_formatting: bool = False) -> list[str]: ... + +class NormalizedDictionary(Dictionary): + def __init__(self, locale_info: dict[str, Incomplete], settings: Settings | None = None) -> None: ... diff --git a/stubs/dateparser/dateparser/languages/loader.pyi b/stubs/dateparser/dateparser/languages/loader.pyi new file mode 100644 index 000000000000..80f89c211053 --- /dev/null +++ b/stubs/dateparser/dateparser/languages/loader.pyi @@ -0,0 +1,29 @@ +import re +from collections import OrderedDict +from collections.abc import Iterator +from typing import Final + +from .locale import Locale + +LOCALE_SPLIT_PATTERN: Final[re.Pattern[str]] + +class LocaleDataLoader: + def get_locale_map( + self, + languages: list[str] | None = None, + locales: list[str] | None = None, + region: str | None = None, + use_given_order: bool = False, + allow_conflicting_locales: bool = False, + ) -> OrderedDict[str, Locale]: ... + def get_locales( + self, + languages: list[str] | None = None, + locales: list[str] | None = None, + region: str | None = None, + use_given_order: bool = False, + allow_conflicting_locales: bool = False, + ) -> Iterator[Locale]: ... + def get_locale(self, shortname: str) -> Locale: ... + +default_loader: LocaleDataLoader diff --git a/stubs/dateparser/dateparser/languages/locale.pyi b/stubs/dateparser/dateparser/languages/locale.pyi new file mode 100644 index 000000000000..ad6ae9d283d2 --- /dev/null +++ b/stubs/dateparser/dateparser/languages/locale.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Mapping, Sized +from re import Pattern +from typing import Final, TypeVar + +from dateparser.conf import Settings + +_K = TypeVar("_K", bound=Sized) +_V = TypeVar("_V") + +NUMERAL_PATTERN: Final[Pattern[str]] + +class Locale: + shortname: str + info: OrderedDict[str, Incomplete] + def __init__(self, shortname: str, language_info: Mapping[Incomplete, Incomplete]) -> None: ... + def is_applicable(self, date_string: str, strip_timezone: bool = False, settings: Settings | None = None) -> bool: ... + def count_applicability(self, text: str, strip_timezone: bool = False, settings: Settings | None = None) -> list[int]: ... + @staticmethod + def clean_dictionary(dictionary: Mapping[_K, _V], threshold: int = 2) -> Mapping[_K, _V]: ... + def translate(self, date_string: str, keep_formatting: bool = False, settings: Settings | None = None) -> str: ... + def translate_search(self, search_string: str, settings: Settings | None = None) -> tuple[list[str], list[str]]: ... + def get_wordchars_for_detection(self, settings: Settings) -> set[str]: ... + def to_parserinfo(self, base_cls: type = ...): ... diff --git a/stubs/dateparser/dateparser/languages/validation.pyi b/stubs/dateparser/dateparser/languages/validation.pyi new file mode 100644 index 000000000000..b98ed3d6e90c --- /dev/null +++ b/stubs/dateparser/dateparser/languages/validation.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import ClassVar + +class LanguageValidator: + VALID_KEYS: ClassVar[list[str]] + logger: Logger | None + @classmethod + def get_logger(cls) -> Logger: ... + @classmethod + def validate_info(cls, language_id, info: dict[str, Incomplete]) -> bool: ... diff --git a/stubs/dateparser/dateparser/parser.pyi b/stubs/dateparser/dateparser/parser.pyi new file mode 100644 index 000000000000..1bede7cd2b9d --- /dev/null +++ b/stubs/dateparser/dateparser/parser.pyi @@ -0,0 +1,68 @@ +import datetime +import re +from collections import OrderedDict +from collections.abc import Callable, Iterable, Iterator +from io import StringIO +from typing import ClassVar, Final, Literal, TypeAlias, overload + +from dateparser.conf import Settings + +_TokenType: TypeAlias = Literal[0, 1, 2] +_Component: TypeAlias = Literal["year", "month", "day"] + +NSP_COMPATIBLE: Final[re.Pattern[str]] +MERIDIAN: Final[re.Pattern[str]] +MICROSECOND: Final[re.Pattern[str]] +EIGHT_DIGIT: Final[re.Pattern[str]] +HOUR_MINUTE_REGEX: Final[re.Pattern[str]] + +def no_space_parser_eligibile(datestring: str) -> bool: ... +def get_unresolved_attrs(parser_object: object) -> tuple[list[_Component], list[_Component]]: ... + +date_order_chart: Final[dict[str, str]] + +@overload +def resolve_date_order(order: str, lst: Literal[True]) -> list[_Component]: ... +@overload +def resolve_date_order(order: str, lst: Literal[False] | None = None) -> str: ... + +class _time_parser: + time_directives: list[str] + def __call__(self, timestring: str) -> datetime.time: ... + +time_parser: _time_parser + +class _no_spaces_parser: + period: dict[str, list[str]] + date_formats: dict[str, list[str]] + def __init__(self, *args, **kwargs) -> None: ... + @classmethod + def parse(cls, datestring: str, settings: Settings) -> tuple[datetime.datetime, str]: ... + +class _parser: + alpha_directives: ClassVar[dict[str, list[str]]] + num_directives: ClassVar[dict[str, list[str]]] + + settings: Settings + tokens: list[tuple[str, _TokenType]] + filtered_tokens: list[tuple[str, _TokenType, int]] + unset_tokens: list[tuple[str, _TokenType, _Component]] + day: int | None + month: int | None + year: int | None + time: Callable[[], datetime.time] | None + auto_order: list[str] + ordered_num_directives: OrderedDict[str, list[str]] + + def __init__(self, tokens: Iterable[tuple[str, _TokenType]], settings: Settings) -> None: ... + @classmethod + def parse( + cls, datestring: str, settings: Settings, tz: datetime.tzinfo | None = None + ) -> tuple[datetime.datetime, str | None]: ... + +class tokenizer: + digits: Literal["0123456789:"] + letters: Literal["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] + instream: StringIO + def __init__(self, ds: str) -> None: ... + def tokenize(self) -> Iterator[tuple[str, _TokenType]]: ... diff --git a/stubs/dateparser/dateparser/search/__init__.pyi b/stubs/dateparser/dateparser/search/__init__.pyi new file mode 100644 index 000000000000..d6eb3182de64 --- /dev/null +++ b/stubs/dateparser/dateparser/search/__init__.pyi @@ -0,0 +1,24 @@ +from collections.abc import Set as AbstractSet +from datetime import datetime +from typing import Any, Literal, overload + +from dateparser.conf import Settings + +from ..date import _DetectLanguagesFunction + +@overload +def search_dates( + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | dict[str, Any] | None, + add_detected_language: Literal[True], + detect_languages_function: _DetectLanguagesFunction | None = None, +) -> list[tuple[str, datetime, str]] | None: ... +@overload +def search_dates( + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | dict[str, Any] | None = None, + add_detected_language: Literal[False] = False, + detect_languages_function: _DetectLanguagesFunction | None = None, +) -> list[tuple[str, datetime]] | None: ... diff --git a/stubs/dateparser/dateparser/search/detection.pyi b/stubs/dateparser/dateparser/search/detection.pyi new file mode 100644 index 000000000000..1466b18175cc --- /dev/null +++ b/stubs/dateparser/dateparser/search/detection.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterator + +from dateparser.conf import Settings +from dateparser.languages.locale import Locale + +class BaseLanguageDetector: + languages: list[Locale] + def __init__(self, languages: list[Locale]) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... + +class AutoDetectLanguage(BaseLanguageDetector): + language_pool: list[Locale] + allow_redetection: bool + def __init__(self, languages: list[Locale], allow_redetection: bool = False) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... + +class ExactLanguages(BaseLanguageDetector): + def __init__(self, languages: list[Locale]) -> None: ... + def iterate_applicable_languages( + self, date_string: str, modify: bool = False, settings: Settings | None = None + ) -> Iterator[Locale]: ... diff --git a/stubs/dateparser/dateparser/search/search.pyi b/stubs/dateparser/dateparser/search/search.pyi new file mode 100644 index 000000000000..5e3c3d37dda2 --- /dev/null +++ b/stubs/dateparser/dateparser/search/search.pyi @@ -0,0 +1,76 @@ +import datetime +import re +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Iterable, Sequence, Set as AbstractSet +from typing import Any, Final, TypedDict, type_check_only + +from dateparser.conf import Settings +from dateparser.date import DateData, DateDataParser, _DetectLanguagesFunction +from dateparser.languages.loader import LocaleDataLoader +from dateparser.languages.locale import Locale +from dateparser.search.text_detection import FullTextLanguageDetector + +@type_check_only +class _SearchDates(TypedDict): + Language: str | None + Dates: list[tuple[str, datetime.datetime]] | None + +RELATIVE_REG: Final[re.Pattern[str]] + +def date_is_relative(translation: str) -> bool: ... + +class _ExactLanguageSearch: + loader: LocaleDataLoader + language: Locale | None + def __init__(self, loader: LocaleDataLoader) -> None: ... + def get_current_language(self, shortname: str) -> None: ... + def search(self, shortname: str, text: str, settings: Settings | None) -> tuple[list[str], list[str]]: ... + @staticmethod + def set_relative_base( + substring: str, already_parsed: list[tuple[DateData, bool]] + ) -> tuple[str, datetime.datetime | None]: ... + def choose_best_split( + self, possible_parsed_splits: list[Incomplete], possible_substrings_splits: list[Incomplete] + ) -> tuple[Incomplete, Incomplete]: ... + def split_by(self, item: str, original: str, splitter: str) -> list[list[list[str]]]: ... + def split_if_not_parsed(self, item: str, original: str) -> list[list[list[str]]]: ... + def parse_item( + self, + parser: DateDataParser, + item: str, + translated_item: str, + parsed: list[tuple[DateData, bool]], + need_relative_base: bool | None, + ) -> tuple[DateData, bool]: ... + def parse_found_objects( + self, + parser: DateDataParser, + to_parse: Iterable[str], + original: Sequence[str], + translated: Sequence[str], + settings: Settings, + ) -> tuple[list[tuple[DateData, bool]], list[str]]: ... + def search_parse(self, shortname: str, text: str, settings: Settings) -> list[tuple[str, datetime.datetime]]: ... + +class DateSearchWithDetection: + loader: LocaleDataLoader + available_language_map: OrderedDict[str, Locale] + search: _ExactLanguageSearch + language_detector: FullTextLanguageDetector + def __init__(self) -> None: ... + def detect_language( + self, + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, + ) -> str | None: ... + def search_dates( + self, + text: str, + languages: list[str] | tuple[str, ...] | AbstractSet[str] | None = None, + settings: Settings | dict[str, Any] | None = None, + detect_languages_function: _DetectLanguagesFunction | None = None, + ) -> _SearchDates: ... + def preprocess_text(self, text: str, languages: Iterable[str] | None) -> str: ... diff --git a/stubs/dateparser/dateparser/search/text_detection.pyi b/stubs/dateparser/dateparser/search/text_detection.pyi new file mode 100644 index 000000000000..fdbe298e2c0d --- /dev/null +++ b/stubs/dateparser/dateparser/search/text_detection.pyi @@ -0,0 +1,10 @@ +from dateparser.conf import Settings +from dateparser.languages.locale import Locale +from dateparser.search.detection import BaseLanguageDetector + +class FullTextLanguageDetector(BaseLanguageDetector): + language_unique_chars: list[set[str]] + language_chars: list[set[str]] + def __init__(self, languages: list[Locale]) -> None: ... + def get_unique_characters(self, settings: Settings) -> None: ... + def character_check(self, date_string: str, settings: Settings) -> None: ... diff --git a/stubs/dateparser/dateparser/timezone_parser.pyi b/stubs/dateparser/dateparser/timezone_parser.pyi new file mode 100644 index 000000000000..dbdbf8e73ece --- /dev/null +++ b/stubs/dateparser/dateparser/timezone_parser.pyi @@ -0,0 +1,22 @@ +import re +from collections.abc import Generator +from datetime import datetime, timedelta, tzinfo +from typing import TypeVar + +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +class StaticTzInfo(tzinfo): + def __init__(self, name: str, offset: timedelta) -> None: ... + def tzname(self, dt: datetime | None) -> str: ... + def utcoffset(self, dt: datetime | None) -> timedelta: ... + def dst(self, dt: datetime | None) -> timedelta: ... + def localize(self, dt: _DateTimeT, is_dst: bool = False) -> _DateTimeT: ... + def __getinitargs__(self) -> tuple[str, timedelta]: ... + +def pop_tz_offset_from_string(date_string: str, as_offset: bool = True) -> tuple[str, StaticTzInfo | str | None]: ... +def word_is_tz(word: str) -> bool: ... +def convert_to_local_tz(datetime_obj: _DateTimeT, datetime_tz_offset: timedelta) -> _DateTimeT: ... +def build_tz_offsets(search_regex_parts: list[str]) -> Generator[tuple[str, dict[str, re.Pattern[str] | timedelta]]]: ... +def get_local_tz_offset() -> timedelta: ... + +local_tz_offset: timedelta diff --git a/stubs/dateparser/dateparser/timezones.pyi b/stubs/dateparser/dateparser/timezones.pyi new file mode 100644 index 000000000000..c767c52dd861 --- /dev/null +++ b/stubs/dateparser/dateparser/timezones.pyi @@ -0,0 +1,3 @@ +from typing import Final + +timezone_info_list: Final[list[dict[str, list[str | tuple[str, str | int]]]]] diff --git a/stubs/dateparser/dateparser/utils/__init__.pyi b/stubs/dateparser/dateparser/utils/__init__.pyi new file mode 100644 index 000000000000..695d51a09400 --- /dev/null +++ b/stubs/dateparser/dateparser/utils/__init__.pyi @@ -0,0 +1,34 @@ +import datetime +from _typeshed import MaybeNone +from collections import OrderedDict +from collections.abc import Mapping +from logging import Logger +from typing import Any, TypeVar + +from dateparser.conf import Settings + +_DateT = TypeVar("_DateT", bound=datetime.date) +_DateTimeT = TypeVar("_DateTimeT", bound=datetime.datetime) + +def strip_braces(date_string: str) -> str: ... +def normalize_unicode(string: str, form: str = "NFKD") -> str: ... +def combine_dicts( + primary_dict: Mapping[Any, Any], supplementary_dict: Mapping[Any, Any] +) -> OrderedDict[str, str | list[Any]]: ... +def find_date_separator(format: str) -> str | MaybeNone | None: ... +def localize_timezone(date_time: _DateTimeT, tz_string: str) -> _DateTimeT: ... +def apply_tzdatabase_timezone(date_time: _DateTimeT, pytz_string: str) -> _DateTimeT: ... +def apply_dateparser_timezone(utc_datetime: _DateTimeT, offset_or_timezone_abb) -> _DateTimeT | None: ... +def apply_timezone(date_time: _DateTimeT, tz_string: str) -> _DateTimeT: ... +def apply_timezone_from_settings(date_obj: _DateTimeT, settings: Settings | None) -> _DateTimeT: ... +def get_last_day_of_month(year: int, month: int) -> int: ... +def get_previous_leap_year(year: int) -> int: ... +def get_next_leap_year(year: int) -> int: ... +def set_correct_day_from_settings(date_obj: _DateT, settings: Settings, current_day: int | None = None) -> _DateT: ... +def set_correct_month_from_settings(date_obj: _DateT, settings: Settings, current_month: int | None = None) -> _DateT: ... +def registry(cls): ... +def get_logger() -> Logger: ... +def setup_logging() -> None: ... + +# TODO: this needs `types-pytz` and a type-alias +def get_timezone_from_tz_string(tz_string: str): ... diff --git a/stubs/dateparser/dateparser/utils/strptime.pyi b/stubs/dateparser/dateparser/utils/strptime.pyi new file mode 100644 index 000000000000..69d630a709d0 --- /dev/null +++ b/stubs/dateparser/dateparser/utils/strptime.pyi @@ -0,0 +1,14 @@ +import re +from datetime import datetime +from time import struct_time +from typing import Final, Protocol, type_check_only + +TIME_MATCHER: Final[re.Pattern[str]] +MS_SEARCHER: Final[re.Pattern[str]] + +@type_check_only +class _strptime_time(Protocol): + def __call__(self, data_string: str, format: str = "%a %b %d %H:%M:%S %Y") -> struct_time: ... + +def patch_strptime() -> _strptime_time: ... +def strptime(date_string: str, format: str) -> datetime: ... diff --git a/stubs/dateparser/dateparser/utils/time_spans.pyi b/stubs/dateparser/dateparser/utils/time_spans.pyi new file mode 100644 index 000000000000..61726ba82839 --- /dev/null +++ b/stubs/dateparser/dateparser/utils/time_spans.pyi @@ -0,0 +1,23 @@ +import datetime +from typing import TypedDict, TypeVar, type_check_only +from typing_extensions import NotRequired + +from dateparser.conf import Settings + +_DateT = TypeVar("_DateT", bound=datetime.date) + +@type_check_only +class _SpanInformation(TypedDict): + type: str + direction: str + matched_text: str + start_pos: int + end_pos: int + number: NotRequired[int] + +def get_week_start(date: _DateT, start_of_week: str = "monday") -> _DateT: ... +def get_week_end(date: _DateT, start_of_week: str = "monday") -> _DateT: ... +def detect_time_span(text: str) -> _SpanInformation | None: ... +def generate_time_span( + span_info: _SpanInformation, base_date: _DateT | None = None, settings: Settings | None = None +) -> tuple[_DateT, _DateT]: ... diff --git a/stubs/dateparser/dateparser_data/__init__.pyi b/stubs/dateparser/dateparser_data/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/dateparser/dateparser_data/settings.pyi b/stubs/dateparser/dateparser_data/settings.pyi new file mode 100644 index 000000000000..42d65ec2bca0 --- /dev/null +++ b/stubs/dateparser/dateparser_data/settings.pyi @@ -0,0 +1,6 @@ +from typing import Final + +from dateparser import _Settings + +default_parsers: Final[list[str]] +settings: Final[_Settings] diff --git a/stubs/decorator/@tests/stubtest_allowlist.txt b/stubs/decorator/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3dd621676f14 --- /dev/null +++ b/stubs/decorator/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +decorator.FunctionMaker.args +decorator.FunctionMaker.kwonlyargs +decorator.FunctionMaker.kwonlydefaults +decorator.FunctionMaker.varargs +decorator.FunctionMaker.varkw diff --git a/stubs/decorator/METADATA.toml b/stubs/decorator/METADATA.toml new file mode 100644 index 000000000000..ec35837c7fa9 --- /dev/null +++ b/stubs/decorator/METADATA.toml @@ -0,0 +1,3 @@ +version = "5.2.*" +upstream-repository = "https://github.com/micheles/decorator" +obsolete-since = { version = "5.3.0", date = "2026-05-17" } diff --git a/stubs/decorator/decorator.pyi b/stubs/decorator/decorator.pyi new file mode 100644 index 000000000000..092f5c781823 --- /dev/null +++ b/stubs/decorator/decorator.pyi @@ -0,0 +1,72 @@ +import inspect +from builtins import dict as _dict # alias to avoid conflicts with attribute name +from collections.abc import Callable, Generator, Iterator +from contextlib import _GeneratorContextManager +from inspect import Signature, getfullargspec as getfullargspec, iscoroutinefunction as iscoroutinefunction +from re import Pattern +from typing import Any, Final, Literal, ParamSpec, TypeVar + +_C = TypeVar("_C", bound=Callable[..., Any]) +_Func = TypeVar("_Func", bound=Callable[..., Any]) +_T = TypeVar("_T") +_P = ParamSpec("_P") + +DEF: Final[Pattern[str]] +POS: Final[Literal[inspect._ParameterKind.POSITIONAL_OR_KEYWORD]] +EMPTY: Final[type[inspect._empty]] + +class FunctionMaker: + args: list[str] + varargs: str | None + varkw: str | None + defaults: tuple[Any, ...] | None + kwonlyargs: list[str] + kwonlydefaults: _dict[str, Any] | None + shortsignature: str | None + name: str + doc: str | None + module: str | None + annotations: _dict[str, Any] + signature: str + dict: _dict[str, Any] + def __init__( + self, + func: Callable[..., Any] | None = ..., + name: str | None = ..., + signature: str | None = ..., + defaults: tuple[Any, ...] | None = ..., + doc: str | None = ..., + module: str | None = ..., + funcdict: _dict[str, Any] | None = ..., + ) -> None: ... + def update(self, func: Any, **kw: Any) -> None: ... + def make( + self, src_templ: str, evaldict: _dict[str, Any] | None = ..., addsource: bool = ..., **attrs: Any + ) -> Callable[..., Any]: ... + @classmethod + def create( + cls, + obj: Any, + body: str, + evaldict: _dict[str, Any], + defaults: tuple[Any, ...] | None = ..., + doc: str | None = ..., + module: str | None = ..., + addsource: bool = ..., + **attrs: Any, + ) -> Callable[..., Any]: ... + +def fix(args: tuple[Any, ...], kwargs: dict[str, Any], sig: Signature) -> tuple[tuple[Any, ...], dict[str, Any]]: ... +def decorate(func: _Func, caller: Callable[..., Any], extras: tuple[Any, ...] = ..., kwsyntax: bool = False) -> _Func: ... +def decoratorx(caller: Callable[..., Any]) -> Callable[..., Any]: ... +def decorator( + caller: Callable[..., Any], _func: Callable[..., Any] | None = None, kwsyntax: bool = False +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ... + +class ContextManager(_GeneratorContextManager[_T]): + def __init__(self, g: Callable[..., Generator[_T]], *a: Any, **k: Any) -> None: ... + def __call__(self, func: _C) -> _C: ... + +def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, ContextManager[_T]]: ... +def append(a: type, vancestors: list[type]) -> None: ... +def dispatch_on(*dispatch_args: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ... diff --git a/stubs/defusedxml/METADATA.toml b/stubs/defusedxml/METADATA.toml new file mode 100644 index 000000000000..96a6481f670b --- /dev/null +++ b/stubs/defusedxml/METADATA.toml @@ -0,0 +1,5 @@ +version = "0.7.*" +upstream-repository = "https://github.com/tiran/defusedxml" + +[tool.stubtest] +stubtest-dependencies = ["lxml"] diff --git a/stubs/defusedxml/defusedxml/ElementTree.pyi b/stubs/defusedxml/defusedxml/ElementTree.pyi new file mode 100644 index 000000000000..638db7e47a16 --- /dev/null +++ b/stubs/defusedxml/defusedxml/ElementTree.pyi @@ -0,0 +1,78 @@ +from _typeshed import ReadableBuffer +from collections.abc import Sequence +from typing import Any, Final +from xml.etree.ElementTree import ( + Element, + ElementTree, + ParseError as ParseError, + XMLParser as _XMLParser, + _FileRead, + _IterParseIterator, + _Target, + tostring as tostring, +) + +__origin__: Final = "xml.etree.ElementTree" + +class DefusedXMLParser(_XMLParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, + html: object = ..., # argument is deprecated, if bool(html) is True you will get TypeError + target: _Target | None = None, + encoding: str | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + +XMLTreeBuilder = DefusedXMLParser +XMLParse = DefusedXMLParser +XMLParser = DefusedXMLParser + +# Wrapper to xml.etree.ElementTree.parse +def parse( + source: _FileRead, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> ElementTree: ... + +# Wrapper to xml.etree.ElementTree.iterparse +# +# See there for possible return types. +def iterparse( + source: _FileRead, + events: Sequence[str] | None = None, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> _IterParseIterator[Any]: ... +def fromstring( + text: str | ReadableBuffer, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True +) -> Element: ... + +XML = fromstring + +__all__ = ["ParseError", "XML", "XMLParse", "XMLParser", "XMLTreeBuilder", "fromstring", "iterparse", "parse", "tostring"] diff --git a/stubs/defusedxml/defusedxml/__init__.pyi b/stubs/defusedxml/defusedxml/__init__.pyi new file mode 100644 index 000000000000..396800468af8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/__init__.pyi @@ -0,0 +1,9 @@ +from .common import ( + DefusedXmlException as DefusedXmlException, + DTDForbidden as DTDForbidden, + EntitiesForbidden as EntitiesForbidden, + ExternalReferenceForbidden as ExternalReferenceForbidden, + NotSupportedError as NotSupportedError, +) + +__all__ = ["DefusedXmlException", "DTDForbidden", "EntitiesForbidden", "ExternalReferenceForbidden", "NotSupportedError"] diff --git a/stubs/defusedxml/defusedxml/cElementTree.pyi b/stubs/defusedxml/defusedxml/cElementTree.pyi new file mode 100644 index 000000000000..5d096d4f14d7 --- /dev/null +++ b/stubs/defusedxml/defusedxml/cElementTree.pyi @@ -0,0 +1,16 @@ +from typing import Final + +from .ElementTree import ( + XML as XML, + ParseError as ParseError, + XMLParse as XMLParse, + XMLParser as XMLParser, + XMLTreeBuilder as XMLTreeBuilder, + fromstring as fromstring, + iterparse as iterparse, + parse as parse, + tostring as tostring, +) + +__origin__: Final = "xml.etree.cElementTree" +__all__ = ["ParseError", "XML", "XMLParse", "XMLParser", "XMLTreeBuilder", "fromstring", "iterparse", "parse", "tostring"] diff --git a/stubs/defusedxml/defusedxml/common.pyi b/stubs/defusedxml/defusedxml/common.pyi new file mode 100644 index 000000000000..15eb3f181444 --- /dev/null +++ b/stubs/defusedxml/defusedxml/common.pyi @@ -0,0 +1,31 @@ +from typing import Final + +PY3: Final[bool] + +class DefusedXmlException(ValueError): ... + +class DTDForbidden(DefusedXmlException): + name: str + sysid: str | None + pubid: str | None + def __init__(self, name: str, sysid: str | None, pubid: str | None) -> None: ... + +class EntitiesForbidden(DefusedXmlException): + name: str + value: str | None + base: str | None + sysid: str | None + pubid: str | None + notation_name: str | None + def __init__( + self, name: str, value: str | None, base: str | None, sysid: str | None, pubid: str | None, notation_name: str | None + ) -> None: ... + +class ExternalReferenceForbidden(DefusedXmlException): + context: str + base: str | None + sysid: str | None + pubid: str | None + def __init__(self, context: str, base: str | None, sysid: str | None, pubid: str | None) -> None: ... + +class NotSupportedError(DefusedXmlException): ... diff --git a/stubs/defusedxml/defusedxml/expatbuilder.pyi b/stubs/defusedxml/defusedxml/expatbuilder.pyi new file mode 100644 index 000000000000..8905cab7c8d8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/expatbuilder.pyi @@ -0,0 +1,49 @@ +from _typeshed import SupportsRead +from typing import Final +from xml.dom.expatbuilder import ExpatBuilder as _ExpatBuilder, Namespaces as _Namespaces +from xml.dom.minidom import Document +from xml.dom.xmlbuilder import Options +from xml.parsers.expat import XMLParserType + +__origin__: Final = "xml.dom.expatbuilder" + +class DefusedExpatBuilder(_ExpatBuilder): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, options: Options | None = None, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + def install(self, parser: XMLParserType) -> None: ... + +class DefusedExpatBuilderNS(_Namespaces, DefusedExpatBuilder): + def install(self, parser: XMLParserType) -> None: ... + def reset(self) -> None: ... + +def parse( + file: str | SupportsRead[bytes | str], + namespaces: bool = True, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... +def parseString( + string: str, namespaces: bool = True, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True +) -> Document: ... diff --git a/stubs/defusedxml/defusedxml/expatreader.pyi b/stubs/defusedxml/defusedxml/expatreader.pyi new file mode 100644 index 000000000000..89155fba5e71 --- /dev/null +++ b/stubs/defusedxml/defusedxml/expatreader.pyi @@ -0,0 +1,43 @@ +from typing import Final +from xml.sax.expatreader import ExpatParser as _ExpatParser, _BoolType + +__origin__: Final = "xml.sax.expatreader" + +class DefusedExpatParser(_ExpatParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, + namespaceHandling: _BoolType = 0, + bufsize: int = 65516, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + def reset(self) -> None: ... + +def create_parser( + namespaceHandling: _BoolType = 0, + bufsize: int = 65516, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DefusedExpatParser: ... diff --git a/stubs/defusedxml/defusedxml/lxml.pyi b/stubs/defusedxml/defusedxml/lxml.pyi new file mode 100644 index 000000000000..0ff53d95ca3b --- /dev/null +++ b/stubs/defusedxml/defusedxml/lxml.pyi @@ -0,0 +1,55 @@ +import threading +from _typeshed import Incomplete +from typing import Final, Literal, type_check_only + +# Not bothering with types here as lxml support is supposed to be dropped in a future version of defusedxml + +LXML3: bool +__origin__: Final = "lxml.etree" + +def tostring( + element_or_tree, + *, + encoding: str | None = None, + method: Literal["xml", "html", "text", "c14n", "c14n2"] = "xml", + xml_declaration: bool | None = None, + pretty_print: bool = False, + with_tail: bool = True, + standalone: bool | None = None, + doctype=None, + exclusive: bool = False, + inclusive_ns_prefixes=None, + with_comments: bool = True, + strip_text: bool = False, +): ... + +# Should be imported from lxml.etree.ElementBase, but lxml lacks types +@type_check_only +class _ElementBase: ... + +class RestrictedElement(_ElementBase): + __slots__ = () + blacklist: Incomplete + def __iter__(self): ... + def iterchildren(self, tag=None, reversed: bool = False): ... + def iter(self, tag=None, *tags): ... + def iterdescendants(self, tag=None, *tags): ... + def itersiblings(self, tag=None, preceding: bool = False): ... + def getchildren(self): ... + def getiterator(self, tag=None): ... + +class GlobalParserTLS(threading.local): + parser_config: Incomplete + element_class: Incomplete + def createDefaultParser(self): ... + def setDefaultParser(self, parser) -> None: ... + def getDefaultParser(self): ... + +def getDefaultParser(): ... +def check_docinfo(elementtree, forbid_dtd: bool = False, forbid_entities: bool = True) -> None: ... +def parse(source, parser=None, base_url=None, forbid_dtd: bool = False, forbid_entities: bool = True): ... +def fromstring(text, parser=None, base_url=None, forbid_dtd: bool = False, forbid_entities: bool = True): ... + +XML = fromstring + +def iterparse(*args, **kwargs) -> None: ... diff --git a/stubs/defusedxml/defusedxml/minidom.pyi b/stubs/defusedxml/defusedxml/minidom.pyi new file mode 100644 index 000000000000..0097ebd5d5b8 --- /dev/null +++ b/stubs/defusedxml/defusedxml/minidom.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsRead +from typing import Final +from xml.dom.minidom import Document +from xml.sax.xmlreader import XMLReader + +__origin__: Final = "xml.dom.minidom" + +def parse( + file: str | SupportsRead[bytes | str], + parser: XMLReader | None = None, + bufsize: int | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... +def parseString( + string: str, + parser: XMLReader | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Document: ... diff --git a/stubs/defusedxml/defusedxml/pulldom.pyi b/stubs/defusedxml/defusedxml/pulldom.pyi new file mode 100644 index 000000000000..706b2b876c06 --- /dev/null +++ b/stubs/defusedxml/defusedxml/pulldom.pyi @@ -0,0 +1,22 @@ +from typing import Final +from xml.dom.pulldom import DOMEventStream +from xml.sax import _SupportsReadClose +from xml.sax.xmlreader import XMLReader + +__origin__: Final = "xml.dom.pulldom" + +def parse( + stream_or_string: str | _SupportsReadClose[str] | _SupportsReadClose[bytes], + parser: XMLReader | None = None, + bufsize: int | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DOMEventStream: ... +def parseString( + string: str, + parser: XMLReader | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> DOMEventStream: ... diff --git a/stubs/defusedxml/defusedxml/sax.pyi b/stubs/defusedxml/defusedxml/sax.pyi new file mode 100644 index 000000000000..9ecd454218bf --- /dev/null +++ b/stubs/defusedxml/defusedxml/sax.pyi @@ -0,0 +1,26 @@ +from _typeshed import ReadableBuffer, Unused +from typing import Final +from xml.sax import ErrorHandler as _ErrorHandler, _Source, xmlreader +from xml.sax.handler import _ContentHandlerProtocol + +from .expatreader import DefusedExpatParser + +__origin__: Final = "xml.sax" + +def parse( + source: xmlreader.InputSource | _Source, + handler: _ContentHandlerProtocol, + errorHandler: _ErrorHandler = ..., + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> None: ... +def parseString( + string: ReadableBuffer, + handler: _ContentHandlerProtocol, + errorHandler: _ErrorHandler = ..., + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> None: ... +def make_parser(parser_list: Unused = []) -> DefusedExpatParser: ... diff --git a/stubs/defusedxml/defusedxml/xmlrpc.pyi b/stubs/defusedxml/defusedxml/xmlrpc.pyi new file mode 100644 index 000000000000..da38c6870004 --- /dev/null +++ b/stubs/defusedxml/defusedxml/xmlrpc.pyi @@ -0,0 +1,48 @@ +import gzip +from _typeshed import ReadableBuffer +from typing import Final, Protocol, type_check_only +from xmlrpc.client import ExpatParser, Unmarshaller + +@type_check_only +class _Readable(Protocol): + def read(self, size: int | None = -1) -> bytes: ... + +__origin__: Final = "xmlrpc.client" +MAX_DATA: Final = 31457280 + +def defused_gzip_decode(data: ReadableBuffer, limit: int | None = None) -> bytes: ... + +class DefusedGzipDecodedResponse(gzip.GzipFile): + limit: int + readlength: int | None + def __init__(self, response: _Readable, limit: int | None = None) -> None: ... + def read(self, n: int) -> bytes: ... # type: ignore[override] + def close(self) -> None: ... + +class DefusedExpatParser(ExpatParser): + forbid_dtd: bool + forbid_entities: bool + forbid_external: bool + def __init__( + self, target: Unmarshaller, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True + ) -> None: ... + def defused_start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ... + def defused_entity_decl( + self, + name: str, + is_parameter_entity: bool, + value: str | None, + base: str | None, + sysid: str, + pubid: str | None, + notation_name: str | None, + ) -> None: ... + def defused_unparsed_entity_decl( + self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str + ) -> None: ... + def defused_external_entity_ref_handler( + self, context: str, base: str | None, sysid: str | None, pubid: str | None + ) -> None: ... + +def monkey_patch() -> None: ... +def unmonkey_patch() -> None: ... diff --git a/stubs/dirhash/METADATA.toml b/stubs/dirhash/METADATA.toml new file mode 100644 index 000000000000..a49924a2eb8a --- /dev/null +++ b/stubs/dirhash/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.5.*" +upstream-repository = "https://github.com/andhus/dirhash-python" diff --git a/stubs/dirhash/dirhash/__init__.pyi b/stubs/dirhash/dirhash/__init__.pyi new file mode 100644 index 000000000000..380aa3f9cbf4 --- /dev/null +++ b/stubs/dirhash/dirhash/__init__.pyi @@ -0,0 +1,92 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from os import PathLike +from typing import TypeAlias, TypeVar + +_DirNode: TypeAlias = Incomplete # scantree.DirNode +_RecursionPath: TypeAlias = Incomplete # scantree.RecursionPath +_RP = TypeVar("_RP", bound=_RecursionPath) + +__all__ = [ + "__version__", + "algorithms_guaranteed", + "algorithms_available", + "dirhash", + "dirhash_impl", + "included_paths", + "Filter", + "get_match_patterns", + "Protocol", +] + +__version__: str +algorithms_guaranteed: set[str] +algorithms_available: set[str] + +def dirhash( + directory: str | PathLike[str], + algorithm: str, + match: Iterable[str] = ("*",), + ignore: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + entry_properties: Iterable[str] = ("name", "data"), + allow_cyclic_links: bool = False, + chunk_size: int = 1048576, + jobs: int = 1, +) -> str: ... +def dirhash_impl( + directory: str | PathLike[str], + algorithm: str, + filter_: Filter | None = None, + protocol: Protocol | None = None, + chunk_size: int = 1048576, + jobs: int = 1, +) -> str: ... +def included_paths( + directory: str | PathLike[str], + match: Iterable[str] = ("*",), + ignore: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + allow_cyclic_links: bool = False, +) -> list[str]: ... + +class Filter: + linked_dirs: bool + linked_files: bool + empty_dirs: bool + + def __init__( + self, + match_patterns: Iterable[str] | None = None, + linked_dirs: bool = True, + linked_files: bool = True, + empty_dirs: bool = False, + ) -> None: ... + @property + def match_patterns(self) -> tuple[str, ...]: ... + def include(self, recursion_path: _RecursionPath) -> bool: ... + def match_file(self, filepath: str | PathLike[str]) -> bool: ... + def __call__(self, paths: Iterable[_RP]) -> Generator[_RP]: ... + +def get_match_patterns( + match: Iterable[str] | None = None, + ignore: Iterable[str] | None = None, + ignore_extensions: Iterable[str] | None = None, + ignore_hidden: bool = False, +) -> list[str]: ... + +class Protocol: + class EntryProperties: + NAME: str + DATA: str + IS_LINK: str + options: set[str] + + entry_properties: Iterable[str] + allow_cyclic_links: bool + def __init__(self, entry_properties: Iterable[str] = ("name", "data"), allow_cyclic_links: bool = False) -> None: ... + def get_descriptor(self, dir_node: _DirNode) -> str: ... diff --git a/stubs/dirhash/dirhash/cli.pyi b/stubs/dirhash/dirhash/cli.pyi new file mode 100644 index 000000000000..b8229142d858 --- /dev/null +++ b/stubs/dirhash/dirhash/cli.pyi @@ -0,0 +1,5 @@ +from collections.abc import Sequence +from typing import Any + +def main() -> None: ... +def get_kwargs(args: Sequence[str]) -> dict[str, Any]: ... # value depends on the key diff --git a/stubs/django-filter/@tests/django_settings.py b/stubs/django-filter/@tests/django_settings.py new file mode 100644 index 000000000000..f44d14e04e15 --- /dev/null +++ b/stubs/django-filter/@tests/django_settings.py @@ -0,0 +1,12 @@ +SECRET_KEY = "1" + +INSTALLED_APPS = ( + "django.contrib.contenttypes", + "django.contrib.sites", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.admin.apps.SimpleAdminConfig", + "django.contrib.staticfiles", + "django.contrib.auth", + "django_filters", +) diff --git a/stubs/django-filter/@tests/stubtest_allowlist.txt b/stubs/django-filter/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d52e9f9f922f --- /dev/null +++ b/stubs/django-filter/@tests/stubtest_allowlist.txt @@ -0,0 +1,19 @@ +# Lookup NamedTuple: Parameter name mismatch between inferred stub and runtime +django_filters.fields.Lookup.__new__ +django_filters.fields.Lookup.__doc__ + +# ChoiceIteratorMixin.choices: Cannot define choices property due to incompatibility with base class ChoiceField +django_filters.fields.ChoiceIteratorMixin.choices + +# Our __init__ signatures are more precise -- ignore "stub does not have *args argument" +django_filters.fields.BaseCSVField.__init__ +django_filters.fields.ChoiceField.__init__ +django_filters.fields.ChoiceIteratorMixin.__init__ +django_filters.fields.LookupChoiceField.__init__ +django_filters.fields.MultipleChoiceField.__init__ +django_filters.fields.RangeField.__init__ +django_filters.filters.QuerySetRequestMixin.__init__ +django_filters.widgets.CSVWidget.__init__ + +# BaseCSVFilter constructs a custom class dynamically, which stubtest can't handle. +django_filters(\.\w+)*\.OrderingFilter.field_class diff --git a/stubs/django-filter/METADATA.toml b/stubs/django-filter/METADATA.toml new file mode 100644 index 000000000000..1c9f66a865dd --- /dev/null +++ b/stubs/django-filter/METADATA.toml @@ -0,0 +1,7 @@ +version = "26.1.*" +upstream-repository = "https://github.com/carltongibson/django-filter/" +dependencies = ["django-stubs>=6.0.8"] + +[tool.stubtest] +mypy-plugins = ["mypy_django_plugin.main"] +mypy-plugins-config = {"django-stubs" = {"django_settings_module" = "@tests.django_settings"}} diff --git a/stubs/django-filter/django_filters/__init__.pyi b/stubs/django-filter/django_filters/__init__.pyi new file mode 100644 index 000000000000..1ed733b2476a --- /dev/null +++ b/stubs/django-filter/django_filters/__init__.pyi @@ -0,0 +1,10 @@ +from typing import Final + +from .filters import * +from .filterset import FilterSet as FilterSet, UnknownFieldBehavior as UnknownFieldBehavior + +__version__: Final[str] + +def parse_version(version: str) -> tuple[str | int]: ... + +VERSION: tuple[str | int, ...] diff --git a/stubs/django-filter/django_filters/compat.pyi b/stubs/django-filter/django_filters/compat.pyi new file mode 100644 index 000000000000..87785dfab536 --- /dev/null +++ b/stubs/django-filter/django_filters/compat.pyi @@ -0,0 +1 @@ +def is_crispy() -> bool: ... diff --git a/stubs/django-filter/django_filters/conf.pyi b/stubs/django-filter/django_filters/conf.pyi new file mode 100644 index 000000000000..b519d1da8b5d --- /dev/null +++ b/stubs/django-filter/django_filters/conf.pyi @@ -0,0 +1,17 @@ +from _typeshed import Unused +from typing import Any + +DEFAULTS: dict[str, Any] # Configuration values can be strings, booleans, callables, etc. +DEPRECATED_SETTINGS: list[str] + +def is_callable(value: Any) -> bool: ... # Accepts any value to test if it's callable + +class Settings: + # Setting values can be of any type, so getter and setter methods return/accept Any + def __getattr__(self, name: str) -> Any: ... # Returns setting values of various types + def get_setting(self, setting: str) -> Any: ... # Setting values vary by configuration option + def change_setting( + self, setting: str, value: Any, enter: bool, **kwargs: Unused + ) -> None: ... # Accepts any setting value type + +settings: Settings diff --git a/stubs/django-filter/django_filters/constants.pyi b/stubs/django-filter/django_filters/constants.pyi new file mode 100644 index 000000000000..1a88634ea477 --- /dev/null +++ b/stubs/django-filter/django_filters/constants.pyi @@ -0,0 +1,6 @@ +from typing import Any, Final + +# String constant used to indicate all model fields should be included +ALL_FIELDS: Final[str] = "__all__" +# Collection of values considered empty by Django filters - tuple type allows various empty containers +EMPTY_VALUES: Final[Any] = ... diff --git a/stubs/django-filter/django_filters/exceptions.pyi b/stubs/django-filter/django_filters/exceptions.pyi new file mode 100644 index 000000000000..725c08b5cada --- /dev/null +++ b/stubs/django-filter/django_filters/exceptions.pyi @@ -0,0 +1,8 @@ +from typing import Any + +from django.core.exceptions import FieldError +from django.db import models + +class FieldLookupError(FieldError): + # Field type params are runtime-determined + def __init__(self, model_field: models.Field[Any, Any], lookup_expr: str) -> None: ... diff --git a/stubs/django-filter/django_filters/fields.pyi b/stubs/django-filter/django_filters/fields.pyi new file mode 100644 index 000000000000..9a2b5293d4ee --- /dev/null +++ b/stubs/django-filter/django_filters/fields.pyi @@ -0,0 +1,159 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, NamedTuple, TypeAlias, TypeVar + +from django import forms +from django.db.models import Choices +from django.db.models.base import Model +from django.forms import Widget +from django_stubs_ext import StrOrPromise + +DJANGO_50: bool + +# Ref: django-stubs/forms/fields.pyi +# Problem: attribute `widget` is always of type `Widget` after field instantiation. +# However, on class level it can be set to `Type[Widget]` too. +# If we annotate it as `Union[Widget, Type[Widget]]`, every code that uses field +# instances will not typecheck. +# If we annotate it as `Widget`, any widget subclasses that do e.g. +# `widget = Select` will not typecheck. +# `Any` gives too much freedom, but does not create false positives. +_ClassLevelWidget: TypeAlias = Any +# Validator parameter type depends on type of the form field used. +_ValidatorCallable: TypeAlias = Callable[[Any], None] +# Based on django-stubs utils/choices.pyi +_Choice: TypeAlias = tuple[Any, Any] +_ChoiceNamedGroup: TypeAlias = tuple[str, Iterable[_Choice]] +_Choices: TypeAlias = Iterable[_Choice | _ChoiceNamedGroup] +_ChoicesMapping: TypeAlias = Mapping[Any, Any] +_ChoicesInput: TypeAlias = _Choices | _ChoicesMapping | type[Choices] | Callable[[], _Choices | _ChoicesMapping] + +_M = TypeVar("_M", bound=Model) + +class RangeField(forms.MultiValueField): + widget: _ClassLevelWidget = ... + def __init__( + self, + fields: tuple[forms.Field, forms.Field] | None = None, + *, + # Inherited from Django MultiValueField + require_all_fields: bool = True, + required: bool = ..., + widget: Widget | type[Widget] | None = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + help_text: StrOrPromise = ..., + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + ) -> None: ... # Args/kwargs can be any field params, passes to parent + def compress(self, data_list: list[Any] | None) -> slice | None: ... # Data list elements can be any field value type + +class DateRangeField(RangeField): + widget: _ClassLevelWidget = ... + def compress(self, data_list: list[Any] | None) -> slice | None: ... # Date values in list can be any date type + +class DateTimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class IsoDateTimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class TimeRangeField(RangeField): + widget: _ClassLevelWidget = ... + +class Lookup(NamedTuple): + value: Any # Lookup values can be any filterable type + lookup_expr: str + +class LookupChoiceField(forms.MultiValueField): + def __init__( + self, + field: forms.Field, + lookup_choices: Sequence[tuple[str, str]], + *, + empty_label: StrOrPromise = ..., + widget: Unused = ..., + help_text: Unused = ..., + # Inherited from Django MultiValueField + require_all_fields: bool = True, + required: bool = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + ) -> None: ... # Args/kwargs can be any field params, uses kwargs for empty_label + def compress(self, data_list: list[Any] | None) -> Lookup | None: ... # Data list can contain any lookup components + +class IsoDateTimeField(forms.DateTimeField): + ISO_8601: str + input_formats: list[str] + def strptime(self, value: str, format: str) -> Any: ... # Returns datetime objects or parsing results + +class BaseCSVField(forms.Field): + base_widget_class: _ClassLevelWidget = ... + def clean(self, value: Any) -> Any: ... # Cleaned values can be any valid field type + +class BaseRangeField(BaseCSVField): + widget: _ClassLevelWidget = ... + def clean(self, value: Any) -> Any: ... # Input and output values can be any range type + +class ChoiceIterator: + field: ChoiceField + choices: Sequence[tuple[Any, str]] # Choice values can be any type (int, str, Model, etc.) + def __init__( + self, field: ChoiceField, choices: Sequence[tuple[Any, str]] + ) -> None: ... # Choice values can be any selectable type + def __iter__(self) -> Any: ... # Iterator yields choice tuples with any value types + def __len__(self) -> int: ... + +class ModelChoiceIterator(forms.models.ModelChoiceIterator[_M]): + def __iter__(self) -> Any: ... # Iterator yields choice tuples with any value types + def __len__(self) -> int: ... + +class ChoiceIteratorMixin: + null_label: StrOrPromise | None + null_value: Any # Null choice values can be any type (None, empty string, etc.) + def __init__(self, *, null_label: StrOrPromise | None, null_value: Any) -> None: ... + +class ChoiceField(ChoiceIteratorMixin, forms.ChoiceField): + iterator = ChoiceIterator + empty_label: StrOrPromise + def __init__( + self, + *, + empty_label: StrOrPromise = ..., + # Inherited from Django ChoiceField + choices: _ChoicesInput = (), + required: bool = ..., + widget: Widget | type[Widget] | None = ..., + label: StrOrPromise | None = ..., + initial: Any | None = ..., # Type depends on the form field used. + help_text: StrOrPromise = ..., + error_messages: Mapping[str, StrOrPromise] | None = ..., + show_hidden_initial: bool = ..., + validators: Sequence[_ValidatorCallable] = ..., + localize: bool = ..., + disabled: bool = ..., + label_suffix: str | None = ..., + null_label: StrOrPromise | None, + null_value: Any, # Type depends on the form field used. + ) -> None: ... + +class MultipleChoiceField(ChoiceIteratorMixin, forms.MultipleChoiceField): + iterator = ChoiceIterator + empty_label: StrOrPromise | None + +class ModelChoiceField(ChoiceIteratorMixin, forms.ModelChoiceField[Any]): + iterator = ModelChoiceIterator + def to_python(self, value: Any) -> Any: ... # Converts any input to Python model objects or values + +class ModelMultipleChoiceField(ChoiceIteratorMixin, forms.ModelMultipleChoiceField[Any]): + iterator = ModelChoiceIterator diff --git a/stubs/django-filter/django_filters/filters.pyi b/stubs/django-filter/django_filters/filters.pyi new file mode 100644 index 000000000000..40707625c9b0 --- /dev/null +++ b/stubs/django-filter/django_filters/filters.pyi @@ -0,0 +1,328 @@ +from collections.abc import Callable, Iterable +from typing import Any + +from django import forms +from django.db.models import QuerySet +from django.forms import Field +from django_stubs_ext import StrOrPromise + +from .fields import ( + BaseCSVField, + BaseRangeField, + DateRangeField, + DateTimeRangeField, + IsoDateTimeField, + IsoDateTimeRangeField, + Lookup, + LookupChoiceField, + ModelChoiceField, + ModelMultipleChoiceField, + RangeField, + TimeRangeField, +) + +__all__ = [ + "AllValuesFilter", + "AllValuesMultipleFilter", + "BaseCSVFilter", + "BaseInFilter", + "BaseRangeFilter", + "BooleanFilter", + "CharFilter", + "ChoiceFilter", + "DateFilter", + "DateFromToRangeFilter", + "DateRangeFilter", + "DateTimeFilter", + "DateTimeFromToRangeFilter", + "DurationFilter", + "Filter", + "IsoDateTimeFilter", + "IsoDateTimeFromToRangeFilter", + "LookupChoiceFilter", + "ModelChoiceFilter", + "ModelMultipleChoiceFilter", + "MultipleChoiceFilter", + "NumberFilter", + "NumericRangeFilter", + "OrderingFilter", + "RangeFilter", + "TimeFilter", + "TimeRangeFilter", + "TypedChoiceFilter", + "TypedMultipleChoiceFilter", + "UUIDFilter", +] + +class Filter: + creation_counter: int + field_class: type[Any] # Subclasses specify more specific field types + field_name: str | None + lookup_expr: str + distinct: bool + exclude: bool + extra: dict[str, Any] # Field kwargs can include various types of parameters + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def get_method(self, qs: QuerySet[Any]) -> Callable[..., QuerySet[Any]]: ... # Returns QuerySet filtering methods + method: Callable[..., Any] | str | None # Custom filter methods return various types + label: StrOrPromise | None # Filter label for display + @property + def field(self) -> Field: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... # Filter value can be any user input type + +class CharFilter(Filter): + field_class: type[forms.CharField] + +class BooleanFilter(Filter): + field_class: type[forms.NullBooleanField] + +class ChoiceFilter(Filter): + field_class: type[Any] # Base class for choice-based filters + null_value: Any # Null value can be any type (None, empty string, etc.) + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class TypedChoiceFilter(Filter): + field_class: type[forms.TypedChoiceField] + +class UUIDFilter(Filter): + field_class: type[forms.UUIDField] + +class MultipleChoiceFilter(Filter): + field_class: type[Any] # Base class for multiple choice filters + always_filter: bool + conjoined: bool + null_value: Any # Multiple choice null values vary by implementation + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + distinct: bool = True, # Overrides distinct default + conjoined: bool = False, + null_value: Any = ..., # Multiple choice null values vary by implementation + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def is_noop(self, qs: QuerySet[Any], value: Any) -> bool: ... # Value can be any filter input + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + def get_filter_predicate(self, v: Any) -> dict[str, Any]: ... # Predicate value can be any filter input type + +class TypedMultipleChoiceFilter(MultipleChoiceFilter): + field_class: type[forms.TypedMultipleChoiceField] # More specific than parent MultipleChoiceField + +class DateFilter(Filter): + field_class: type[forms.DateField] + +class DateTimeFilter(Filter): + field_class: type[forms.DateTimeField] + +class IsoDateTimeFilter(DateTimeFilter): + field_class: type[IsoDateTimeField] + +class TimeFilter(Filter): + field_class: type[forms.TimeField] + +class DurationFilter(Filter): + field_class: type[forms.DurationField] + +class QuerySetRequestMixin: + queryset: QuerySet[Any] | None + def __init__(self, *, queryset: QuerySet[Any] | None) -> None: ... + def get_request(self) -> Any: ... # Request can be HttpRequest or other request types + def get_queryset(self, request: Any) -> QuerySet[Any]: ... # Request parameter accepts various request types + @property + def field(self) -> Field: ... + +class ModelChoiceFilter(QuerySetRequestMixin, ChoiceFilter): + field_class: type[ModelChoiceField] # More specific than parent ChoiceField + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from QuerySetRequestMixin + queryset: QuerySet[Any] | None = None, + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + +class ModelMultipleChoiceFilter(QuerySetRequestMixin, MultipleChoiceFilter): + field_class: type[ModelMultipleChoiceField] # More specific than parent MultipleChoiceField + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from QuerySetRequestMixin + queryset: QuerySet[Any] | None = None, + # Inherited from MultipleChoiceFilter + distinct: bool = True, # Overrides distinct default + conjoined: bool = False, + null_value: Any = ..., # Multiple choice null values vary by implementation + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + +class NumberFilter(Filter): + field_class: type[forms.DecimalField] + def get_max_validator(self) -> Any: ... # Validator can be various Django validator types + @property + def field(self) -> Field: ... + +class NumericRangeFilter(Filter): + field_class: type[RangeField] + lookup_expr: str + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class RangeFilter(Filter): + field_class: type[RangeField] + lookup_expr: str + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class DateRangeFilter(ChoiceFilter): + choices: list[tuple[str, str]] | None + filters: dict[str, Filter] | None + def __init__( + self, + choices: list[tuple[str, str]] | None = None, + filters: dict[str, Filter] | None = None, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... # Uses args/kwargs for choice and filter configuration + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + +class DateFromToRangeFilter(RangeFilter): + field_class: type[DateRangeField] + +class DateTimeFromToRangeFilter(RangeFilter): + field_class: type[DateTimeRangeField] + +class IsoDateTimeFromToRangeFilter(RangeFilter): + field_class: type[IsoDateTimeRangeField] + +class TimeRangeFilter(RangeFilter): + field_class: type[TimeRangeField] + +class AllValuesFilter(ChoiceFilter): + @property + def field(self) -> Field: ... + +class AllValuesMultipleFilter(MultipleChoiceFilter): + @property + def field(self) -> Field: ... + +class BaseCSVFilter(Filter): + base_field_class: type[BaseCSVField] = ... + field_class: type[Any] # Base class for CSV-based filters + +class BaseInFilter(BaseCSVFilter): ... + +class BaseRangeFilter(BaseCSVFilter): + base_field_class: type[BaseRangeField] = ... + +class LookupChoiceFilter(Filter): + field_class: type[forms.CharField] + outer_class: type[LookupChoiceField] = ... + empty_label: StrOrPromise | None + lookup_choices: list[tuple[str, StrOrPromise]] | None + def __init__( + self, + field_name: str | None = None, + lookup_choices: list[tuple[str, StrOrPromise]] | None = None, + field_class: type[Field] | None = None, + *, + empty_label: StrOrPromise = ..., + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + @classmethod + def normalize_lookup(cls, lookup: str | tuple[str, StrOrPromise]) -> tuple[str, StrOrPromise]: ... + def get_lookup_choices(self) -> list[tuple[str, StrOrPromise]]: ... + @property + def field(self) -> Field: ... + lookup_expr: str + def filter(self, qs: QuerySet[Any], lookup: Lookup) -> QuerySet[Any]: ... + +class OrderingFilter(BaseCSVFilter, ChoiceFilter): + # Inherits CSV field behavior for comma-separated ordering. + # BaseCSVFilter constructs a custom ConcreteCSVField class that derives + # from BaseCSVField. + field_class: type[BaseCSVField] + descending_fmt: str + param_map: dict[str, str] | None + def __init__( + self, + field_name: str | None = None, + lookup_expr: str | None = None, + *, + fields: dict[str, str] | Iterable[str] | Iterable[tuple[str, str]] = ..., + field_labels: dict[str, StrOrPromise] = ..., + # Inherited from ChoiceFilter + null_value: Any = ..., # Null value can be any type (None, empty string, etc.) + # Inherited from Filter + label: StrOrPromise | None = None, + method: Callable[..., Any] | str | None = None, # Filter methods can return various types + distinct: bool = False, + exclude: bool = False, + **kwargs: Any, # Field kwargs stored as extra (required, help_text, etc.) + ) -> None: ... + def get_ordering_value(self, param: str) -> str: ... + def filter(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + @classmethod + def normalize_fields(cls, fields: Any) -> list[str]: ... + def build_choices(self, fields: Any, labels: dict[str, StrOrPromise] | None) -> list[tuple[str, str]]: ... + +class FilterMethod: + f: Filter + def __init__(self, filter_instance: Filter) -> None: ... + def __call__(self, qs: QuerySet[Any], value: Any) -> QuerySet[Any]: ... + @property + def method(self) -> Callable[..., Any]: ... diff --git a/stubs/django-filter/django_filters/filterset.pyi b/stubs/django-filter/django_filters/filterset.pyi new file mode 100644 index 000000000000..72cdeab7b5aa --- /dev/null +++ b/stubs/django-filter/django_filters/filterset.pyi @@ -0,0 +1,88 @@ +from collections import OrderedDict +from collections.abc import Sequence +from enum import Enum +from typing import Any, ClassVar + +from django.db import models +from django.db.models import Model, QuerySet +from django.forms import Form +from django.http import HttpRequest, QueryDict + +from .filters import Filter + +def remote_queryset(field: models.Field[Any, Any]) -> QuerySet[Any]: ... # Field type params vary by model definition + +class UnknownFieldBehavior(Enum): + RAISE = "raise" + WARN = "warn" + IGNORE = "ignore" + +class FilterSetOptions: + model: type[Model] | None + fields: Sequence[str] | dict[str, Sequence[str]] | str | None + exclude: Sequence[str] | None + filter_overrides: dict[type[models.Field[Any, Any]], dict[str, Any]] # Field override mapping + form: type[Form] + unknown_field_behavior: UnknownFieldBehavior + def __init__(self, options: Any | None = None) -> None: ... # Meta options can be various configuration types + +class FilterSetMetaclass(type): + # Class attrs vary by definition + def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> FilterSetMetaclass: ... + + # Class attrs vary by definition + @classmethod + def get_declared_filters(cls, bases: tuple[type, ...], attrs: dict[str, Any]) -> OrderedDict[str, Filter]: ... + +# Django field types vary widely - Any allows mapping all field types to their filters +FILTER_FOR_DBFIELD_DEFAULTS: dict[type[models.Field[Any, Any]], dict[str, Any]] + +class BaseFilterSet: + FILTER_DEFAULTS: ClassVar[dict[type[models.Field[Any, Any]], dict[str, Any]]] = ... # Field type mapping + is_bound: bool + base_filters: OrderedDict[str, Filter] + declared_filters: OrderedDict[str, Filter] + data: QueryDict | dict[str, Any] | None # Filter input data values vary + queryset: QuerySet[Any] | None # Base queryset for any model type + request: HttpRequest | None + form_prefix: str | None + filters: OrderedDict[str, Filter] + def __init__( + self, + data: QueryDict | dict[str, Any] | None = None, # Filter data values vary + queryset: QuerySet[Any] | None = None, # Base queryset for any model + *, + request: HttpRequest | None = None, + prefix: str | None = None, + ) -> None: ... + def is_valid(self) -> bool: ... + @property + def errors(self) -> dict[str, list[str]]: ... + def filter_queryset(self, queryset: QuerySet[Any]) -> QuerySet[Any]: ... # Works with any model type + @property + def qs(self) -> QuerySet[Any]: ... # Filtered queryset of any model + def get_form_class(self) -> type[Form]: ... + @property + def form(self) -> Form: ... + @classmethod + def get_fields(cls) -> dict[str, models.Field[Any, Any]]: ... # Model fields have varying type params + @classmethod + def get_filter_name(cls, field_name: str, lookup_expr: str) -> str: ... + @classmethod + def get_filters(cls) -> OrderedDict[str, Filter]: ... + @classmethod + def handle_unrecognized_field(cls, field_name: str, message: str) -> None: ... + @classmethod + def filter_for_field( + cls, field: models.Field[Any, Any], field_name: str, lookup_expr: str | None = None + ) -> Filter: ... # Accepts any Django field type + @classmethod + def filter_for_lookup( + cls, field: models.Field[Any, Any], lookup_type: str # Field type varies by model + ) -> tuple[type[Filter], dict[str, Any]]: ... + +class FilterSet(BaseFilterSet, metaclass=FilterSetMetaclass): ... + +def filterset_factory( + model: type[Model], filterset: FilterSetMetaclass = ..., fields: Sequence[str] | dict[str, Sequence[str]] | str | None = None +) -> type[FilterSet]: ... diff --git a/stubs/django-filter/django_filters/rest_framework/__init__.pyi b/stubs/django-filter/django_filters/rest_framework/__init__.pyi new file mode 100644 index 000000000000..560557bc8d9b --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/__init__.pyi @@ -0,0 +1,34 @@ +from .backends import DjangoFilterBackend as DjangoFilterBackend +from .filters import ( + AllValuesFilter as AllValuesFilter, + AllValuesMultipleFilter as AllValuesMultipleFilter, + BaseCSVFilter as BaseCSVFilter, + BaseInFilter as BaseInFilter, + BaseRangeFilter as BaseRangeFilter, + BooleanFilter as BooleanFilter, + CharFilter as CharFilter, + ChoiceFilter as ChoiceFilter, + DateFilter as DateFilter, + DateFromToRangeFilter as DateFromToRangeFilter, + DateRangeFilter as DateRangeFilter, + DateTimeFilter as DateTimeFilter, + DateTimeFromToRangeFilter as DateTimeFromToRangeFilter, + DurationFilter as DurationFilter, + Filter as Filter, + IsoDateTimeFilter as IsoDateTimeFilter, + IsoDateTimeFromToRangeFilter as IsoDateTimeFromToRangeFilter, + LookupChoiceFilter as LookupChoiceFilter, + ModelChoiceFilter as ModelChoiceFilter, + ModelMultipleChoiceFilter as ModelMultipleChoiceFilter, + MultipleChoiceFilter as MultipleChoiceFilter, + NumberFilter as NumberFilter, + NumericRangeFilter as NumericRangeFilter, + OrderingFilter as OrderingFilter, + RangeFilter as RangeFilter, + TimeFilter as TimeFilter, + TimeRangeFilter as TimeRangeFilter, + TypedChoiceFilter as TypedChoiceFilter, + TypedMultipleChoiceFilter as TypedMultipleChoiceFilter, + UUIDFilter as UUIDFilter, +) +from .filterset import FilterSet as FilterSet diff --git a/stubs/django-filter/django_filters/rest_framework/backends.pyi b/stubs/django-filter/django_filters/rest_framework/backends.pyi new file mode 100644 index 000000000000..c58bf4c98260 --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/backends.pyi @@ -0,0 +1,29 @@ +from typing import Any, TypeAlias + +from django.db.models import QuerySet +from django.http import HttpRequest +from django_filters.filterset import FilterSetMetaclass + +from . import filterset + +# APIView placeholder - djangorestframework is optional, so we use Any for compatibility +_APIView: TypeAlias = Any + +class DjangoFilterBackend: + filterset_base: FilterSetMetaclass = ... + raise_exception: bool + @property + def template(self) -> str: ... + + # Works with any model type + def get_filterset(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> filterset.FilterSet | None: ... + + # Any model queryset + def get_filterset_class(self, view: _APIView, queryset: QuerySet[Any] | None = None) -> type[filterset.FilterSet] | None: ... + + # Kwargs vary by filterset + def get_filterset_kwargs(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> dict[str, Any]: ... + + # Filters any model type + def filter_queryset(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> QuerySet[Any]: ... + def to_html(self, request: HttpRequest, queryset: QuerySet[Any], view: _APIView) -> str: ... # Renders form for any model diff --git a/stubs/django-filter/django_filters/rest_framework/filters.pyi b/stubs/django-filter/django_filters/rest_framework/filters.pyi new file mode 100644 index 000000000000..9dec2084d15f --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/filters.pyi @@ -0,0 +1,68 @@ +from ..filters import ( + AllValuesFilter, + AllValuesMultipleFilter, + BaseCSVFilter, + BaseInFilter, + BaseRangeFilter, + BooleanFilter as _BaseBooleanFilter, + CharFilter, + ChoiceFilter, + DateFilter, + DateFromToRangeFilter, + DateRangeFilter, + DateTimeFilter, + DateTimeFromToRangeFilter, + DurationFilter, + Filter, + IsoDateTimeFilter, + IsoDateTimeFromToRangeFilter, + LookupChoiceFilter, + ModelChoiceFilter, + ModelMultipleChoiceFilter, + MultipleChoiceFilter, + NumberFilter, + NumericRangeFilter, + OrderingFilter, + RangeFilter, + TimeFilter, + TimeRangeFilter, + TypedChoiceFilter, + TypedMultipleChoiceFilter, + UUIDFilter, +) + +__all__ = [ + "AllValuesFilter", + "AllValuesMultipleFilter", + "BaseCSVFilter", + "BaseInFilter", + "BaseRangeFilter", + "BooleanFilter", + "CharFilter", + "ChoiceFilter", + "DateFilter", + "DateFromToRangeFilter", + "DateRangeFilter", + "DateTimeFilter", + "DateTimeFromToRangeFilter", + "DurationFilter", + "Filter", + "IsoDateTimeFilter", + "IsoDateTimeFromToRangeFilter", + "LookupChoiceFilter", + "ModelChoiceFilter", + "ModelMultipleChoiceFilter", + "MultipleChoiceFilter", + "NumberFilter", + "NumericRangeFilter", + "OrderingFilter", + "RangeFilter", + "TimeFilter", + "TimeRangeFilter", + "TypedChoiceFilter", + "TypedMultipleChoiceFilter", + "UUIDFilter", +] + +# REST framework specific BooleanFilter that uses BooleanWidget by default +class BooleanFilter(_BaseBooleanFilter): ... diff --git a/stubs/django-filter/django_filters/rest_framework/filterset.pyi b/stubs/django-filter/django_filters/rest_framework/filterset.pyi new file mode 100644 index 000000000000..cd7eb9ab5813 --- /dev/null +++ b/stubs/django-filter/django_filters/rest_framework/filterset.pyi @@ -0,0 +1,17 @@ +from collections import OrderedDict +from typing import Any, ClassVar + +from django.db import models +from django.forms import Form +from django_filters import filterset +from django_filters.filters import Filter + +# REST framework field mappings support all Django field types +FILTER_FOR_DBFIELD_DEFAULTS: dict[type[models.Field[Any, Any]], dict[str, Any]] + +class FilterSet(filterset.FilterSet): + FILTER_DEFAULTS: ClassVar[dict[type[models.Field[Any, Any]], dict[str, Any]]] = ... # DRF field mappings + base_filters: OrderedDict[str, Filter] + declared_filters: OrderedDict[str, Filter] + @property + def form(self) -> Form: ... diff --git a/stubs/django-filter/django_filters/utils.pyi b/stubs/django-filter/django_filters/utils.pyi new file mode 100644 index 000000000000..247108ee84ec --- /dev/null +++ b/stubs/django-filter/django_filters/utils.pyi @@ -0,0 +1,36 @@ +from collections.abc import Callable +from datetime import datetime +from typing import Any + +from django.db import models +from django.db.models import Model + +def deprecate(msg: str, level_modifier: int = 0) -> None: ... + +class MigrationNotice(DeprecationWarning): + url: str + def __init__(self, message: str) -> None: ... + +class RenameAttributesBase(type): + renamed_attributes: tuple[tuple[str, str, DeprecationWarning], ...] = () + + # Class attrs vary by definition + def __new__(metacls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> RenameAttributesBase: ... + def get_name(metacls, name: str) -> str: ... + def __getattr__(metacls, name: str) -> Any: ... # Attribute values vary by name and class + def __setattr__(metacls, name: str, value: Any) -> None: ... # Attribute values can be any type + +def try_dbfield( + fn: Callable[[models.Field[Any, Any]], Any], field_class: type[models.Field[Any, Any]] +) -> Any: ... # Generic field operation +def get_all_model_fields(model: type[Model]) -> dict[str, models.Field[Any, Any]]: ... # Fields vary by model definition +def get_model_field(model: type[Model], field_name: str) -> models.Field[Any, Any]: ... # Field type unknown at static time +def get_field_parts(model: type[Model], field_name: str) -> list[models.Field[Any, Any]]: ... # Relationship fields vary +def resolve_field( + model_field: models.Field[Any, Any], lookup_expr: str +) -> tuple[models.Field[Any, Any], str]: ... # Generic field resolution +def handle_timezone(value: datetime, is_dst: bool | None = None) -> datetime: ... +def verbose_field_name(model: type[Model], field_name: str) -> str: ... +def verbose_lookup_expr(lookup_expr: str) -> str: ... +def label_for_filter(model: type[Model], field_name: str, lookup_expr: str, exclude: bool = False) -> str: ... +def translate_validation(error_dict: dict[str, list[str]]) -> dict[str, list[str]]: ... diff --git a/stubs/django-filter/django_filters/views.pyi b/stubs/django-filter/django_filters/views.pyi new file mode 100644 index 000000000000..0af9f1f21256 --- /dev/null +++ b/stubs/django-filter/django_filters/views.pyi @@ -0,0 +1,38 @@ +from _typeshed import Unused +from typing import Any + +from django.db.models import Model, QuerySet +from django.http import HttpRequest, HttpResponse +from django.views.generic import View +from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin + +from .constants import ALL_FIELDS +from .filterset import FilterSet + +class FilterMixin: + filterset_class: type[FilterSet] | None + filterset_fields = ALL_FIELDS + strict: bool + def get_filterset_class(self) -> type[FilterSet] | None: ... + def get_filterset(self, filterset_class: type[FilterSet]) -> FilterSet: ... + def get_filterset_kwargs(self, filterset_class: type[FilterSet]) -> dict[str, Any]: ... # Filterset init params vary + def get_strict(self) -> bool: ... + +class BaseFilterView(FilterMixin, MultipleObjectMixin[Any], View): # Generic model type + filterset: FilterSet + object_list: QuerySet[Any] # Filtered objects of any model type + + def get(self, request: HttpRequest, *args: Unused, **kwargs: Unused) -> HttpResponse: ... + +class FilterView(MultipleObjectTemplateResponseMixin, BaseFilterView): + template_name_suffix: str + +def object_filter( + request: HttpRequest, + model: type[Model] | None = None, + queryset: QuerySet[Any] | None = None, # Base queryset for any model + template_name: str | None = None, + extra_context: dict[str, Any] | None = None, # Template context values vary + context_processors: list[Any] | None = None, # Context processors vary by implementation + filter_class: type[FilterSet] | None = None, +) -> HttpResponse: ... diff --git a/stubs/django-filter/django_filters/widgets.pyi b/stubs/django-filter/django_filters/widgets.pyi new file mode 100644 index 000000000000..8707dc0fdbfb --- /dev/null +++ b/stubs/django-filter/django_filters/widgets.pyi @@ -0,0 +1,81 @@ +from collections.abc import Mapping, Sequence +from typing import Any + +from django import forms +from django.http import QueryDict +from django.utils.safestring import SafeString + +class LinkWidget(forms.Widget): + # Choice values can be any type (int, str, Model, etc.) + choices: Sequence[tuple[Any, str]] + # Choice values can be any selectable type + def __init__(self, attrs: dict[str, Any] | None = None, choices: Sequence[tuple[Any, str]] = ()) -> None: ... + data: QueryDict | dict[str, Any] + # Return value depends on widget data type + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> Any: ... + # Widget value and renderer can be any type, choices parameter combines with class choices + def render( # type: ignore[override] + self, + name: str, + value: Any, + attrs: dict[str, Any] | None = None, + choices: Sequence[tuple[Any, str]] = (), + renderer: Any | None = None, + ) -> SafeString: ... + # Choice values and selections can be any type + def render_options(self, choices: Sequence[tuple[Any, str]], selected_choices: list[Any], name: str) -> str: ... + # Selected choices and option values can be any type + def render_option(self, name: str, selected_choices: list[Any], option_value: Any, option_label: str) -> str: ... + def option_string(self) -> str: ... + +class SuffixedMultiWidget(forms.MultiWidget): + suffixes: list[str] + def suffixed(self, name: str, suffix: str) -> str: ... + # Widget value and context can contain any data types + def get_context(self, name: str, value: Any, attrs: dict[str, Any] | None) -> dict[str, Any]: ... + # Returns list of any value types from widget data + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[Any]: ... + # Widget data can contain any types + def value_omitted_from_data(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> bool: ... + def replace_name(self, output: str, index: int) -> str: ... + # Decompresses any widget value into list of components + def decompress(self, value: Any) -> list[Any] | None: ... + +class RangeWidget(SuffixedMultiWidget): + template_name: str + suffixes: list[str] + # Accepts any widget attribute types + def __init__(self, attrs: dict[str, Any] | None = None) -> None: ... + # Decompresses any range value into list components + def decompress(self, value: Any) -> list[Any] | None: ... + +class DateRangeWidget(RangeWidget): + suffixes: list[str] + +class LookupChoiceWidget(SuffixedMultiWidget): + suffixes: list[str] + # Decompresses any lookup choice value into components + def decompress(self, value: Any) -> list[Any] | None: ... + +class BooleanWidget(forms.Select): + # Accepts any widget attribute types + def __init__(self, attrs: dict[str, Any] | None = None) -> None: ... + # Widget value and renderer can be any type + def render(self, name: str, value: Any, attrs: dict[str, Any] | None = None, renderer: Any | None = None) -> SafeString: ... + # Return value type depends on widget data + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> Any: ... + +class BaseCSVWidget(forms.Widget): + # Can be widget class or instance - __init__ converts to instance via instantiation or deepcopy + surrogate: type[Any] = ... + + # CSV widget data can contain any types + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[str]: ... + # Widget value and renderer can be any type + def render(self, name: str, value: Any, attrs: dict[str, Any] | None = None, renderer: Any | None = None) -> SafeString: ... + +class CSVWidget(BaseCSVWidget, forms.TextInput): ... + +class QueryArrayWidget(BaseCSVWidget, forms.TextInput): + # Query array widget data can contain any types + def value_from_datadict(self, data: Mapping[str, Any], files: Mapping[str, Any], name: str) -> list[str]: ... diff --git a/stubs/django-import-export/METADATA.toml b/stubs/django-import-export/METADATA.toml new file mode 100644 index 000000000000..9452959702c8 --- /dev/null +++ b/stubs/django-import-export/METADATA.toml @@ -0,0 +1,6 @@ +version = "4.4.*" +upstream-repository = "https://github.com/django-import-export/django-import-export" +dependencies = ["django-stubs"] # Add tablib when typed, and update _Incomplete aliases in stubs + +[tool.stubtest] +skip = true # Django requires configured settings at runtime diff --git a/stubs/django-import-export/import_export/__init__.pyi b/stubs/django-import-export/import_export/__init__.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/django-import-export/import_export/__init__.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/django-import-export/import_export/admin.pyi b/stubs/django-import-export/import_export/admin.pyi new file mode 100644 index 000000000000..070dbd26720e --- /dev/null +++ b/stubs/django-import-export/import_export/admin.pyi @@ -0,0 +1,109 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Any, Literal, TypeAlias, TypeVar +from typing_extensions import deprecated + +from django.contrib import admin +from django.contrib.admin.helpers import ActionForm +from django.core.files import File +from django.db.models import Model, QuerySet +from django.forms import Form +from django.http.request import HttpRequest +from django.http.response import HttpResponse +from django.template.response import TemplateResponse +from django.urls import URLPattern + +from .formats.base_formats import Format +from .mixins import BaseExportMixin, BaseImportMixin +from .results import Result +from .tmp_storages import BaseStorage + +Dataset: TypeAlias = Incomplete # tablib.Dataset +logger: Logger + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ImportExportMixinBase: + base_change_list_template: str + change_list_template: str + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def init_change_list_template(self) -> None: ... + def get_model_info(self) -> tuple[str, str]: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + +class ImportMixin(BaseImportMixin[_ModelT], ImportExportMixinBase): + import_export_change_list_template: str + import_template_name: str + import_form_class: type[Form] = ... + confirm_form_class: type[Form] = ... + from_encoding: str + import_error_display: Sequence[Literal["message", "row", "traceback"]] + skip_admin_log: bool | None + tmp_storage_class: str | type[BaseStorage] + def get_skip_admin_log(self) -> bool: ... + def get_tmp_storage_class(self) -> type[BaseStorage]: ... + def get_tmp_storage_class_kwargs(self) -> dict[str, Any]: ... + def has_import_permission(self, request: HttpRequest) -> bool: ... + def get_urls(self) -> list[URLPattern]: ... + def process_import(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: ... + def process_dataset(self, dataset: Dataset, form: Form, request: HttpRequest, **kwargs: Any) -> Result: ... + def process_result(self, result: Result, request: HttpRequest) -> HttpResponse: ... + def generate_log_entries(self, result: Result, request: HttpRequest) -> None: ... + def add_success_message(self, result: Result, request: HttpRequest) -> None: ... + def get_import_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def create_import_form(self, request: HttpRequest) -> Form: ... + def get_import_form_class(self, request: HttpRequest) -> type[Form]: ... + def get_import_form_kwargs(self, request: HttpRequest) -> dict[str, Any]: ... + def get_import_form_initial(self, request: HttpRequest) -> dict[str, Any]: ... + def create_confirm_form(self, request: HttpRequest, import_form: Form | None = None) -> Form: ... + def get_confirm_form_class(self, request: HttpRequest) -> type[Form]: ... + def get_confirm_form_kwargs(self, request: HttpRequest, import_form: Form | None = None) -> dict[str, Any]: ... + def get_confirm_form_initial(self, request: HttpRequest, import_form: Form | None) -> dict[str, Any]: ... + def get_import_data_kwargs(self, **kwargs: Any) -> dict[str, Any]: ... + def write_to_tmp_storage(self, import_file: File[bytes], input_format: Format) -> BaseStorage: ... + def add_data_read_fail_error_to_form(self, form: Form, e: Exception) -> None: ... + def import_action(self, request: HttpRequest, **kwargs: Any) -> TemplateResponse: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + +class ExportMixin(BaseExportMixin[_ModelT], ImportExportMixinBase): + import_export_change_list_template: str + export_template_name: str + to_encoding: str | None + export_form_class: type[Form] = ... + def get_urls(self) -> list[URLPattern]: ... + def has_export_permission(self, request: HttpRequest) -> bool: ... + def get_export_queryset(self, request: HttpRequest) -> QuerySet[_ModelT]: ... + def get_export_data( + self, file_format: Format, request: HttpRequest, queryset: QuerySet[_ModelT], **kwargs: Any + ) -> str | bytes: ... + def get_export_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_export_form_class(self) -> type[Form]: ... + def export_action(self, request: HttpRequest) -> TemplateResponse: ... + @deprecated( + "The 'get_valid_export_item_pks()' method is deprecated and will be removed in a future release. " + "Overwrite 'get_queryset()' or 'get_export_queryset()' instead." + ) + def get_valid_export_item_pks(self, request: HttpRequest) -> list[str]: ... + def changelist_view(self, request: HttpRequest, extra_context: dict[str, Any] | None = None) -> HttpResponse: ... + def get_export_filename(self, request: HttpRequest, queryset: QuerySet[_ModelT], file_format: Format) -> str: ... # type: ignore[override] + def init_request_context_data(self, request: HttpRequest, form: Form) -> dict[str, Any]: ... + +class ImportExportMixin(ImportMixin[_ModelT], ExportMixin[_ModelT]): ... +class ImportExportModelAdmin(ImportExportMixin[_ModelT], admin.ModelAdmin[_ModelT]): ... # type: ignore[misc] + +class ExportActionMixin(ExportMixin[_ModelT]): + change_form_template: str + show_change_form_export: bool + action_form: type[ActionForm] + def change_view( + self, request: HttpRequest, object_id: str, form_url: str = "", extra_context: dict[str, Any] | None = None + ) -> HttpResponse: ... + def response_change(self, request: HttpRequest, obj: _ModelT) -> HttpResponse: ... + def export_admin_action(self, request: HttpRequest, queryset: QuerySet[_ModelT]) -> HttpResponse: ... + def get_actions(self, request: HttpRequest) -> dict[str, tuple[Callable[..., str], str, str] | None]: ... + +class ExportActionModelAdmin(ExportActionMixin[_ModelT], admin.ModelAdmin[_ModelT]): ... # type: ignore[misc] +class ImportExportActionModelAdmin(ImportMixin[_ModelT], ExportActionModelAdmin[_ModelT]): ... # type: ignore[misc] diff --git a/stubs/django-import-export/import_export/command_utils.pyi b/stubs/django-import-export/import_export/command_utils.pyi new file mode 100644 index 000000000000..a3c1fb5e4236 --- /dev/null +++ b/stubs/django-import-export/import_export/command_utils.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrPath +from typing import Any + +from .formats.base_formats import Format +from .resources import ModelResource + +def get_resource_class(model_or_resource_class: str) -> ModelResource[Any]: ... + +MIME_TYPE_FORMAT_MAPPING: dict[str, type[Format]] + +def get_format_class(format_name: str, file_name: StrPath, encoding: str | None = None) -> Format: ... +def get_default_format_names() -> str: ... diff --git a/stubs/django-import-export/import_export/declarative.pyi b/stubs/django-import-export/import_export/declarative.pyi new file mode 100644 index 000000000000..e0c723239488 --- /dev/null +++ b/stubs/django-import-export/import_export/declarative.pyi @@ -0,0 +1,11 @@ +import _typeshed +from logging import Logger +from typing import Any + +logger: Logger + +class DeclarativeMetaclass(type): + def __new__(cls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], attrs: dict[str, Any]) -> _typeshed.Self: ... + +class ModelDeclarativeMetaclass(DeclarativeMetaclass): + def __new__(cls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], attrs: dict[str, Any]) -> _typeshed.Self: ... diff --git a/stubs/django-import-export/import_export/exceptions.pyi b/stubs/django-import-export/import_export/exceptions.pyi new file mode 100644 index 000000000000..3f6b99db52d9 --- /dev/null +++ b/stubs/django-import-export/import_export/exceptions.pyi @@ -0,0 +1,11 @@ +from typing import Any + +class ImportExportError(Exception): ... +class FieldError(ImportExportError): ... +class WidgetError(ImportExportError): ... + +class ImportError(ImportExportError): + error: Exception + number: int | None + row: dict[str, Any] | None + def __init__(self, error: Exception, number: int | None = None, row: dict[str, Any] | None = None) -> None: ... diff --git a/stubs/django-import-export/import_export/fields.pyi b/stubs/django-import-export/import_export/fields.pyi new file mode 100644 index 000000000000..d17fb1d7e2eb --- /dev/null +++ b/stubs/django-import-export/import_export/fields.pyi @@ -0,0 +1,34 @@ +from collections.abc import Callable, Mapping +from typing import Any, ClassVar + +from django.db.models import Model +from django.db.models.fields import NOT_PROVIDED + +from .widgets import Widget + +class Field: + empty_values: ClassVar[list[str | None]] + attribute: str | None + default: type[NOT_PROVIDED] | Callable[[], Any] | Any + column_name: str | None + widget: Widget + readonly: bool + saves_null_values: bool + dehydrate_method: str + m2m_add: bool + def __init__( + self, + attribute: str | None = None, + column_name: str | None = None, + widget: Widget | None = None, + default: type[NOT_PROVIDED] | Callable[[], Any] | Any = ..., + readonly: bool = False, + saves_null_values: bool = True, + dehydrate_method: str | None = None, + m2m_add: bool = False, + ) -> None: ... + def clean(self, row: Mapping[str, Any], **kwargs: Any) -> Any: ... + def get_value(self, instance: Model) -> Any: ... + def save(self, instance: Model, row: Mapping[str, Any], is_m2m: bool = False, **kwargs: Any) -> None: ... + def export(self, instance: Model, **kwargs: Any) -> str: ... + def get_dehydrate_method(self, field_name: str | None = None) -> str: ... diff --git a/stubs/django-import-export/import_export/formats/__init__.pyi b/stubs/django-import-export/import_export/formats/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/django-import-export/import_export/formats/base_formats.pyi b/stubs/django-import-export/import_export/formats/base_formats.pyi new file mode 100644 index 000000000000..17c7f4a60ad4 --- /dev/null +++ b/stubs/django-import-export/import_export/formats/base_formats.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete, ReadableBuffer +from logging import Logger +from typing import IO, Any, ClassVar, TypeAlias +from typing_extensions import Self + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +logger: Logger + +class Format: + def get_title(self) -> type[Self]: ... + def create_dataset(self, in_stream: str | bytes | IO[Any]) -> Dataset: ... + def export_data(self, dataset: Dataset, **kwargs: Any) -> Any: ... + def is_binary(self) -> bool: ... + def get_read_mode(self) -> str: ... + def get_extension(self) -> str: ... + def get_content_type(self) -> str: ... + @classmethod + def is_available(cls) -> bool: ... + def can_import(self) -> bool: ... + def can_export(self) -> bool: ... + +class TablibFormat(Format): + TABLIB_MODULE: ClassVar[str] + CONTENT_TYPE: ClassVar[str] + encoding: str | None + def __init__(self, encoding: str | None = None) -> None: ... + def get_format(self) -> type[Any]: ... + def get_title(self) -> str: ... # type: ignore[override] + def create_dataset(self, in_stream: str | bytes | IO[Any], **kwargs: Any) -> Dataset: ... # type: ignore[override] + +class TextFormat(TablibFormat): ... + +class CSV(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class JSON(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class YAML(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class TSV(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> str: ... + +class ODS(TextFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + +class HTML(TextFormat): ... + +class XLS(TablibFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + def create_dataset(self, in_stream: bytes) -> Dataset: ... # type: ignore[override] + +class XLSX(TablibFormat): + def export_data(self, dataset: Dataset, **kwargs: Any) -> bytes: ... + def create_dataset(self, in_stream: ReadableBuffer) -> Dataset: ... # type: ignore[override] + +DEFAULT_FORMATS: list[type[Format]] +BINARY_FORMATS: list[type[Format]] diff --git a/stubs/django-import-export/import_export/forms.pyi b/stubs/django-import-export/import_export/forms.pyi new file mode 100644 index 000000000000..910554c49bbb --- /dev/null +++ b/stubs/django-import-export/import_export/forms.pyi @@ -0,0 +1,38 @@ +from collections.abc import Iterable, Sequence +from typing import Any + +from django import forms + +from .formats.base_formats import Format +from .resources import ModelResource, Resource + +class ImportExportFormBase(forms.Form): + resource: forms.ChoiceField + format: forms.ChoiceField + def __init__( + self, formats: list[type[Format]], resources: list[type[Resource[Any]]] | None = None, **kwargs: Any + ) -> None: ... + +class ImportForm(ImportExportFormBase): + import_file: forms.FileField + field_order: Sequence[str] + @property + def media(self) -> forms.Media: ... + +class ConfirmImportForm(forms.Form): + import_file_name: forms.CharField + original_file_name: forms.CharField + resource: forms.CharField + def clean_import_file_name(self) -> str: ... + +class ExportForm(ImportExportFormBase): + export_items: forms.MultipleChoiceField + +class SelectableFieldsExportForm(ExportForm): + resources: Iterable[ModelResource[Any]] + is_selectable_fields_form: bool + resource_fields: dict[str, list[str]] + @staticmethod + def create_boolean_field_name(resource: ModelResource[Any], field_name: str) -> str: ... + def get_selected_resource(self) -> ModelResource[Any]: ... + def get_selected_resource_export_fields(self) -> list[str]: ... diff --git a/stubs/django-import-export/import_export/instance_loaders.pyi b/stubs/django-import-export/import_export/instance_loaders.pyi new file mode 100644 index 000000000000..e2840f83aba9 --- /dev/null +++ b/stubs/django-import-export/import_export/instance_loaders.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Any, TypeAlias + +from django.db.models import Model, QuerySet + +from .fields import Field +from .resources import Resource + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +class BaseInstanceLoader: + resource: Resource[Any] + dataset: Dataset | None + def __init__(self, resource: Resource[Any], dataset: Dataset | None = None) -> None: ... + def get_instance(self, row: dict[str, Any]) -> Model | None: ... + +class ModelInstanceLoader(BaseInstanceLoader): + def get_queryset(self) -> QuerySet[Any]: ... + +class CachedInstanceLoader(ModelInstanceLoader): + pk_field: Field + all_instances: dict[Any, Model] diff --git a/stubs/django-import-export/import_export/mixins.pyi b/stubs/django-import-export/import_export/mixins.pyi new file mode 100644 index 000000000000..7c5bd003e4f5 --- /dev/null +++ b/stubs/django-import-export/import_export/mixins.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete, SupportsGetItem +from logging import Logger +from typing import Any, Generic, TypeAlias, TypeVar +from typing_extensions import deprecated + +from django.db.models import Model, QuerySet +from django.forms import BaseForm, Form +from django.http.request import HttpRequest +from django.http.response import HttpResponse +from django.views.generic.edit import FormView + +from .formats.base_formats import Format +from .resources import Resource + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +logger: Logger + +_ModelT = TypeVar("_ModelT", bound=Model) + +class BaseImportExportMixin(Generic[_ModelT]): + resource_classes: SupportsGetItem[int, type[Resource[_ModelT]]] + @property + def formats(self) -> list[type[Format]]: ... + @property + def export_formats(self) -> list[type[Format]]: ... + @property + def import_formats(self) -> list[type[Format]]: ... + def check_resource_classes(self, resource_classes: SupportsGetItem[int, type[Resource[_ModelT]]]) -> None: ... + def get_resource_classes(self, request: HttpRequest) -> list[type[Resource[_ModelT]]]: ... + def get_resource_kwargs(self, request: HttpRequest, *args: Any, **kwargs: Any) -> dict[str, Any]: ... + def get_resource_index(self, form: Form) -> int: ... + +class BaseImportMixin(BaseImportExportMixin[_ModelT]): + skip_import_confirm: bool + def get_import_resource_classes(self, request: HttpRequest) -> list[type[Resource[_ModelT]]]: ... + def get_import_formats(self) -> list[Format]: ... + def get_import_resource_kwargs(self, request: HttpRequest, **kwargs: Any) -> dict[str, Any]: ... + def choose_import_resource_class(self, form: Form, request: HttpRequest) -> type[Resource[_ModelT]]: ... + def is_skip_import_confirm_enabled(self) -> bool: ... + +class BaseExportMixin(BaseImportExportMixin[_ModelT]): + model: Model + skip_export_form: bool + skip_export_form_from_action: bool + def get_export_formats(self) -> list[Format]: ... + def get_export_resource_classes(self, request: HttpRequest) -> list[Resource[_ModelT]]: ... + def choose_export_resource_class(self, form: Form, request: HttpRequest) -> Resource[_ModelT]: ... + def get_export_resource_kwargs(self, request: HttpRequest, **kwargs: Any) -> dict[str, Any]: ... + def get_data_for_export(self, request: HttpRequest, queryset: QuerySet[_ModelT], **kwargs: Any) -> Dataset: ... + def get_export_filename(self, file_format: Format) -> str: ... + def is_skip_export_form_enabled(self) -> bool: ... + def is_skip_export_form_from_action_enabled(self) -> bool: ... + +class ExportViewMixin(BaseExportMixin[_ModelT]): + form_class: type[BaseForm] = ... + def get_export_data(self, file_format: Format, queryset: QuerySet[_ModelT], **kwargs: Any) -> str | bytes: ... + def get_context_data(self, **kwargs: Any) -> dict[str, Any]: ... + def get_form_kwargs(self) -> dict[str, Any]: ... + +_FormT = TypeVar("_FormT", bound=BaseForm) + +@deprecated("ExportViewFormMixin is deprecated and will be removed in a future release.") +class ExportViewFormMixin(ExportViewMixin[_ModelT], FormView[_FormT]): # type: ignore[misc] + def form_valid(self, form: _FormT) -> HttpResponse: ... diff --git a/stubs/django-import-export/import_export/options.pyi b/stubs/django-import-export/import_export/options.pyi new file mode 100644 index 000000000000..6ddc523acc85 --- /dev/null +++ b/stubs/django-import-export/import_export/options.pyi @@ -0,0 +1,32 @@ +from collections.abc import Sequence +from typing import Any, Generic, TypeVar + +from django.db.models import Model + +from .instance_loaders import BaseInstanceLoader + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ResourceOptions(Generic[_ModelT]): + model: _ModelT | str + fields: Sequence[str] | None + exclude: Sequence[str] | None + instance_loader_class: type[BaseInstanceLoader] | None + import_id_fields: Sequence[str] + export_order: Sequence[str] | None + import_order: Sequence[str] | None + widgets: dict[str, Any] | None + use_transactions: bool | None + skip_unchanged: bool + report_skipped: bool + clean_model_instances: bool + chunk_size: int | None + skip_diff: bool + skip_html_diff: bool + use_bulk: bool + batch_size: int + force_init_instance: bool + using_db: str | None + store_row_values: bool + store_instance: bool + use_natural_foreign_keys: bool diff --git a/stubs/django-import-export/import_export/resources.pyi b/stubs/django-import-export/import_export/resources.pyi new file mode 100644 index 000000000000..4f1c75dac782 --- /dev/null +++ b/stubs/django-import-export/import_export/resources.pyi @@ -0,0 +1,170 @@ +import _typeshed +from collections import OrderedDict +from collections.abc import Iterator, Sequence +from functools import partial +from logging import Logger +from typing import Any, ClassVar, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Never, deprecated + +from django.db.models import Field as DjangoField, Model, QuerySet +from django.utils.safestring import SafeString + +from .declarative import DeclarativeMetaclass, ModelDeclarativeMetaclass +from .fields import Field +from .instance_loaders import BaseInstanceLoader +from .options import ResourceOptions +from .results import Error, Result, RowResult +from .widgets import ForeignKeyWidget, ManyToManyWidget, Widget + +Dataset: TypeAlias = _typeshed.Incomplete # tablib.Dataset +logger: Logger + +def has_natural_foreign_key(model: Model) -> bool: ... + +class Diff: + left: list[str] + right: list[str] + new: bool + def __init__(self, resource: Resource[_ModelT], instance: _ModelT, new: bool) -> None: ... + def compare_with(self, resource: Resource[_ModelT], instance: _ModelT, dry_run: bool = False) -> None: ... + def as_html(self) -> list[SafeString]: ... + +_ModelT = TypeVar("_ModelT", bound=Model) + +class Resource(Generic[_ModelT], metaclass=DeclarativeMetaclass): + _meta: ResourceOptions[_ModelT] + fields: OrderedDict[str, Field] + create_instances: list[_ModelT] + update_instances: list[_ModelT] + delete_instances: list[_ModelT] + def __init__(self, **kwargs: Any) -> None: ... + @classmethod + def get_result_class(self) -> type[Result]: ... + @classmethod + def get_row_result_class(self) -> type[RowResult]: ... + @classmethod + def get_error_result_class(self) -> type[Error]: ... + @classmethod + def get_diff_class(self) -> type[Diff]: ... + @classmethod + def get_db_connection_name(self) -> str: ... + def get_use_transactions(self) -> bool: ... + def get_chunk_size(self) -> int: ... + @deprecated("The 'get_fields()' method is deprecated and will be removed in a future release.") + def get_fields(self, **kwargs: Any) -> list[Field]: ... + def get_field_name(self, field: Field) -> str: ... + def init_instance(self, row: dict[str, Any] | None = None) -> _ModelT: ... + def get_instance(self, instance_loader: BaseInstanceLoader, row: dict[str, Any]) -> _ModelT | None: ... + def get_or_init_instance(self, instance_loader: BaseInstanceLoader, row: dict[str, Any]) -> tuple[_ModelT | None, bool]: ... + def get_import_id_fields(self) -> Sequence[str]: ... + def get_bulk_update_fields(self) -> list[str]: ... + def bulk_create( + self, + using_transactions: bool, + dry_run: bool, + raise_errors: bool, + batch_size: int | None = None, + result: Result | None = None, + ) -> None: ... + def bulk_update( + self, + using_transactions: bool, + dry_run: bool, + raise_errors: bool, + batch_size: int | None = None, + result: Result | None = None, + ) -> None: ... + def bulk_delete(self, using_transactions: bool, dry_run: bool, raise_errors: bool, result: Result | None = None) -> None: ... + def validate_instance( + self, instance: _ModelT, import_validation_errors: dict[str, Any] | None = None, validate_unique: bool = True + ) -> None: ... + # For all the definitions below (from `save_instance()` to `import_row()`), `**kwargs` should contain: + # dry_run: bool, use_transactions: bool, row_number: int, retain_instance_in_row_result: bool. + # Users are free to pass extra arguments in `import_data()`so PEP 728 can probably be leveraged here. + def save_instance(self, instance: _ModelT, is_create: bool, row: dict[str, Any], **kwargs: Any) -> None: ... + def do_instance_save(self, instance: _ModelT) -> None: ... + def before_save_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_save_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def before_delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_delete_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def import_field(self, field: Field, instance: _ModelT, row: dict[str, Any], is_m2m: bool = False, **kwargs: Any) -> None: ... + def get_import_fields(self) -> list[Field]: ... + def import_instance(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def save_m2m(self, instance: _ModelT, row: dict[str, Any], **kwargs: Any) -> None: ... + def for_delete(self, row: dict[str, Any], instance: _ModelT) -> bool: ... + def skip_row( + self, instance: _ModelT, original: _ModelT, row: dict[str, Any], import_validation_errors: dict[str, Any] | None = None + ) -> bool: ... + def get_diff_headers(self) -> list[str]: ... + def before_import(self, dataset: Dataset, **kwargs: Any) -> None: ... + def after_import(self, dataset: Dataset, result: Result, **kwargs: Any) -> None: ... + def before_import_row(self, row: dict[str, Any], **kwargs: Any) -> None: ... + def after_import_row(self, row: dict[str, Any], row_result: RowResult, **kwargs: Any) -> None: ... + def after_init_instance(self, instance: _ModelT, new: bool, row: dict[str, Any], **kwargs: Any) -> None: ... + + @overload + def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[True]) -> Never: ... + @overload + def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[False] = False) -> None: ... + + def import_row(self, row: dict[str, Any], instance_loader: BaseInstanceLoader, **kwargs: Any) -> RowResult: ... + def import_data( + self, + dataset: Dataset, + dry_run: bool = False, + raise_errors: bool = False, + use_transactions: bool | None = None, + collect_failed_rows: bool = False, + rollback_on_validation_errors: bool = False, + **kwargs: Any, + ) -> Result: ... + def import_data_inner( + self, + dataset: Dataset, + dry_run: bool, + raise_errors: bool, + using_transactions: bool, + collect_failed_rows: bool, + **kwargs: Any, + ) -> Result: ... + def get_import_order(self) -> tuple[str, ...]: ... + def get_export_order(self) -> tuple[str, ...]: ... + def before_export(self, queryset: QuerySet[_ModelT], **kwargs: Any) -> None: ... + def after_export(self, queryset: QuerySet[_ModelT], dataset: Dataset, **kwargs: Any) -> None: ... + def filter_export(self, queryset: QuerySet[_ModelT], **kwargs: Any) -> QuerySet[_ModelT]: ... + def export_field(self, field: Field, instance: _ModelT, **kwargs: Any) -> str: ... + def get_export_fields(self, selected_fields: Sequence[str] | None = None) -> list[Field]: ... + def export_resource(self, instance: _ModelT, selected_fields: Sequence[str] | None = None, **kwargs: Any) -> list[str]: ... + def get_export_headers(self, selected_fields: Sequence[str] | None = None) -> list[str]: ... + def get_user_visible_headers(self) -> list[str]: ... + def get_user_visible_fields(self) -> list[str]: ... + def iter_queryset(self, queryset: QuerySet[_ModelT]) -> Iterator[_ModelT]: ... + def export(self, queryset: QuerySet[_ModelT] | None = None, **kwargs: Any) -> Dataset: ... + +class ModelResource(Resource[_ModelT], metaclass=ModelDeclarativeMetaclass): + DEFAULT_RESOURCE_FIELD: ClassVar[type[Field]] = ... + WIDGETS_MAP: ClassVar[dict[str, type[Widget]]] + @classmethod + def get_m2m_widget(cls, field: DjangoField[Any, Any]) -> partial[ManyToManyWidget[Any]]: ... + @classmethod + def get_fk_widget(cls, field: DjangoField[Any, Any]) -> partial[ForeignKeyWidget[Any]]: ... + @classmethod + def widget_from_django_field(cls, f: DjangoField[Any, Any], default: type[Widget] = ...) -> type[Widget]: ... + @classmethod + def widget_kwargs_for_field(cls, field_name: str, django_field: DjangoField[Any, Any]) -> dict[str, Any]: ... + @classmethod + def field_from_django_field(cls, field_name: str, django_field: DjangoField[Any, Any], readonly: bool) -> Field: ... + def get_queryset(self) -> QuerySet[_ModelT]: ... + def init_instance(self, row: dict[str, Any] | None = None) -> _ModelT: ... + def after_import(self, dataset: Dataset, result: Result, **kwargs: Any) -> None: ... + @classmethod + def get_display_name(cls) -> str: ... + +_ResourceT = TypeVar("_ResourceT", bound=Resource[Any]) + +# HK Type Vars could help type the first overload: +@overload +def modelresource_factory(model: Model, resource_class: type[_ResourceT]) -> _ResourceT: ... +@overload +def modelresource_factory(model: _ModelT) -> ModelResource[_ModelT]: ... diff --git a/stubs/django-import-export/import_export/results.pyi b/stubs/django-import-export/import_export/results.pyi new file mode 100644 index 000000000000..5d108fbf6d4e --- /dev/null +++ b/stubs/django-import-export/import_export/results.pyi @@ -0,0 +1,88 @@ +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Iterator +from functools import cached_property +from typing import Any, ClassVar, Literal, TypeAlias + +from django.core.exceptions import ValidationError +from django.db.models import Model + +Dataset: TypeAlias = Incomplete # tablib.Dataset + +class Error: + error: Exception + row: dict[str, Any] + number: int | None + def __init__(self, error: Exception, row: dict[str, Any] | None = None, number: int | None = None) -> None: ... + @cached_property + def traceback(self) -> str: ... + +_ImportType: TypeAlias = Literal["update", "new", "delete", "skip", "error", "invalid"] + +class RowResult: + IMPORT_TYPE_UPDATE: ClassVar[Literal["update"]] + IMPORT_TYPE_NEW: ClassVar[Literal["new"]] + IMPORT_TYPE_DELETE: ClassVar[Literal["delete"]] + IMPORT_TYPE_SKIP: ClassVar[Literal["skip"]] + IMPORT_TYPE_ERROR: ClassVar[Literal["error"]] + IMPORT_TYPE_INVALID: ClassVar[Literal["invalid"]] + valid_import_types: frozenset[_ImportType] + errors: list[Error] + validation_error: ValidationError | None + diff: list[str] | None + import_type: _ImportType + row_values: dict[str, Any] + object_id: Any | None + object_repr: str | None + instance: Model + original: Model + def __init__(self) -> None: ... + def add_instance_info(self, instance: Model) -> None: ... + def is_update(self) -> bool: ... + def is_new(self) -> bool: ... + def is_delete(self) -> bool: ... + def is_skip(self) -> bool: ... + def is_error(self) -> bool: ... + def is_invalid(self) -> bool: ... + def is_valid(self) -> bool: ... + +class ErrorRow: + number: int + errors: list[Error] + def __init__(self, number: int, errors: list[Error]) -> None: ... + +class InvalidRow: + number: int + error: ValidationError + values: tuple[Any, ...] + error_dict: dict[str, list[str]] + def __init__(self, number: int, validation_error: ValidationError, values: tuple[Any, ...]) -> None: ... + @property + def field_specific_errors(self) -> dict[str, list[str]]: ... + @property + def non_field_specific_errors(self) -> list[str]: ... + @property + def error_count(self) -> int: ... + +class Result: + base_errors: list[Error] + diff_headers: list[str] + rows: list[RowResult] + invalid_rows: list[InvalidRow] + error_rows: list[ErrorRow] + failed_dataset: Dataset + totals: OrderedDict[_ImportType, int] + total_rows: int + def __init__(self) -> None: ... + def valid_rows(self) -> list[RowResult]: ... + def append_row_result(self, row_result: RowResult) -> None: ... + def append_base_error(self, error: Error) -> None: ... + def add_dataset_headers(self, headers: list[str] | None) -> None: ... + def append_failed_row(self, row: dict[str, Any], error: Exception) -> None: ... + def append_invalid_row(self, number: int, row: dict[str, Any], validation_error: ValidationError) -> None: ... + def append_error_row(self, number: int, row: dict[str, Any], errors: list[Error]) -> None: ... + def increment_row_result_total(self, row_result: RowResult) -> None: ... + def row_errors(self) -> list[tuple[int, Any]]: ... + def has_errors(self) -> bool: ... + def has_validation_errors(self) -> bool: ... + def __iter__(self) -> Iterator[RowResult]: ... diff --git a/stubs/django-import-export/import_export/signals.pyi b/stubs/django-import-export/import_export/signals.pyi new file mode 100644 index 000000000000..7d32df82f840 --- /dev/null +++ b/stubs/django-import-export/import_export/signals.pyi @@ -0,0 +1,4 @@ +from django.dispatch import Signal + +post_export: Signal +post_import: Signal diff --git a/stubs/django-import-export/import_export/templatetags/__init__.pyi b/stubs/django-import-export/import_export/templatetags/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi b/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi new file mode 100644 index 000000000000..9d6c0e4d7f68 --- /dev/null +++ b/stubs/django-import-export/import_export/templatetags/import_export_tags.pyi @@ -0,0 +1,8 @@ +from typing_extensions import LiteralString + +from django.template import Library + +register: Library + +@register.simple_tag +def compare_values(value1: str, value2: str) -> LiteralString: ... diff --git a/stubs/django-import-export/import_export/tmp_storages.pyi b/stubs/django-import-export/import_export/tmp_storages.pyi new file mode 100644 index 000000000000..eda138ffda97 --- /dev/null +++ b/stubs/django-import-export/import_export/tmp_storages.pyi @@ -0,0 +1,34 @@ +from abc import abstractmethod +from typing import IO, Any, ClassVar + +class BaseStorage: + name: str | None + read_mode: str + encoding: str | None + def __init__(self, *, name: str | None = None, read_mode: str = "", encoding: str | None = None) -> None: ... + @abstractmethod + def save(self, data: Any) -> None: ... + @abstractmethod + def read(self) -> Any: ... # `Any` because `read` returns things from `save` + @abstractmethod + def remove(self) -> None: ... + +class TempFolderStorage(BaseStorage): + def save(self, data: Any) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + def get_full_path(self) -> str: ... + +class CacheStorage(BaseStorage): + CACHE_LIFETIME: int + CACHE_PREFIX: str + def save(self, data: Any) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + +class MediaStorage(BaseStorage): + MEDIA_FOLDER: ClassVar[str] + def save(self, data: IO[Any]) -> None: ... + def read(self) -> Any: ... + def remove(self) -> None: ... + def get_full_path(self) -> str: ... diff --git a/stubs/django-import-export/import_export/utils.pyi b/stubs/django-import-export/import_export/utils.pyi new file mode 100644 index 000000000000..d4b968a3f3f7 --- /dev/null +++ b/stubs/django-import-export/import_export/utils.pyi @@ -0,0 +1,19 @@ +from types import TracebackType +from typing import Any, overload + +from django.db.models import Field as DjangoField, ForeignObjectRel, Model +from django.db.transaction import Atomic + +class atomic_if_using_transaction: + using_transactions: bool + context_manager: Atomic + def __init__(self, using_transactions: bool, using: str | None) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +@overload +def get_related_model(field: ForeignObjectRel) -> Model: ... +@overload +def get_related_model(field: DjangoField[Any, Any]) -> Model | None: ... diff --git a/stubs/django-import-export/import_export/widgets.pyi b/stubs/django-import-export/import_export/widgets.pyi new file mode 100644 index 000000000000..1939cad05f1f --- /dev/null +++ b/stubs/django-import-export/import_export/widgets.pyi @@ -0,0 +1,91 @@ +from collections.abc import Mapping +from datetime import datetime +from typing import Any, ClassVar, Generic, TypeVar, overload +from typing_extensions import deprecated + +from django.db.models import Model, QuerySet + +def format_datetime(value: datetime, datetime_format: str) -> str: ... + +class Widget: + coerce_to_string: bool + def __init__(self, coerce_to_string: bool = True) -> None: ... + def clean(self, value: Any, row: Mapping[str, Any] | None = None, **kwargs: Any) -> Any: ... + + @overload + @deprecated("The 'obj' parameter is deprecated and will be removed in a future release.") + def render(self, value: Any, obj: Model, **kwargs: Any) -> Any: ... + @overload + def render(self, value: Any, obj: None = None, **kwargs: Any) -> Any: ... + +class NumberWidget(Widget): + def is_empty(self, value: Any) -> bool: ... + +class FloatWidget(NumberWidget): ... +class IntegerWidget(NumberWidget): ... +class DecimalWidget(NumberWidget): ... + +class CharWidget(Widget): + allow_blank: bool + def __init__(self, coerce_to_string: bool = True, allow_blank: bool = True) -> None: ... + +class BooleanWidget(Widget): + TRUE_VALUES: ClassVar[list[str | int | bool]] + FALSE_VALUES: ClassVar[list[str | int | bool]] + NULL_VALUES: ClassVar[list[str | None]] + def __init__(self, coerce_to_string: bool = True) -> None: ... + +class DateWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class DateTimeWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class TimeWidget(Widget): + formats: tuple[str, ...] + def __init__(self, format: str | None = None, coerce_to_string: bool = True) -> None: ... + +class DurationWidget(Widget): ... + +class SimpleArrayWidget(Widget): + separator: str + def __init__(self, separator: str | None = None, coerce_to_string: bool = True) -> None: ... + +class JSONWidget(Widget): ... + +_ModelT = TypeVar("_ModelT", bound=Model) + +class ForeignKeyWidget(Widget, Generic[_ModelT]): + model: type[_ModelT] + field: str + key_is_id: bool + use_natural_foreign_keys: bool + def __init__( + self, + model: type[_ModelT], + field: str = "pk", + use_natural_foreign_keys: bool = False, + key_is_id: bool = False, + **kwargs: Any, + ) -> None: ... + def get_queryset(self, value: Any, row: Mapping[str, Any], *args: Any, **kwargs: Any) -> QuerySet[_ModelT]: ... + def get_instance_by_natural_key(self, value: str | bytes | bytearray) -> _ModelT: ... + def get_instance_by_lookup_fields(self, value: Any, row: Mapping[str, Any], **kwargs: Any) -> _ModelT: ... + def get_lookup_kwargs(self, value: Any, row: Mapping[str, Any] | None = None, **kwargs: Any) -> dict[str, Any]: ... + +class _CachedQuerySetWrapper(Generic[_ModelT]): + queryset: QuerySet[_ModelT] + model: type[_ModelT] + def __init__(self, queryset: QuerySet[_ModelT]) -> None: ... + def get(self, **lookup_fields: Any) -> _ModelT: ... # instance can have different fields + +class CachedForeignKeyWidget(ForeignKeyWidget[_ModelT]): + def get_instance_by_lookup_fields(self, value: Any, row: Mapping[str, Any], **kwargs: Any) -> _ModelT: ... + +class ManyToManyWidget(Widget, Generic[_ModelT]): + model: _ModelT + separator: str + field: str + def __init__(self, model: _ModelT, separator: str | None = None, field: str | None = None, **kwargs: Any) -> None: ... diff --git a/stubs/django-import-export/management/__init__.pyi b/stubs/django-import-export/management/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/django-import-export/management/commands/__init__.pyi b/stubs/django-import-export/management/commands/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/django-import-export/management/commands/export.pyi b/stubs/django-import-export/management/commands/export.pyi new file mode 100644 index 000000000000..8d75fb4d613f --- /dev/null +++ b/stubs/django-import-export/management/commands/export.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): ... diff --git a/stubs/django-import-export/management/commands/import.pyi b/stubs/django-import-export/management/commands/import.pyi new file mode 100644 index 000000000000..8d75fb4d613f --- /dev/null +++ b/stubs/django-import-export/management/commands/import.pyi @@ -0,0 +1,3 @@ +from django.core.management.base import BaseCommand + +class Command(BaseCommand): ... diff --git a/stubs/docker/@tests/stubtest_allowlist.txt b/stubs/docker/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..224425773c24 --- /dev/null +++ b/stubs/docker/@tests/stubtest_allowlist.txt @@ -0,0 +1,15 @@ +# additional requirements are needed, e.g. win32 apis +docker.transport.npipeconn +docker.transport.npipesocket +docker.transport.sshconn + +# model is always set by child classes +docker.models.resource.Collection.model + +# implementation has *args and **kwargs params that can't be used +docker.api.container.ContainerApiMixin.start +docker.client.DockerClient.info +docker.client.DockerClient.ping + +# Internal-use module for types shared by multiple modules. +docker._types diff --git a/stubs/docker/@tests/test_cases/check_attach.py b/stubs/docker/@tests/test_cases/check_attach.py new file mode 100644 index 000000000000..802099b9e2c2 --- /dev/null +++ b/stubs/docker/@tests/test_cases/check_attach.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from docker.models.containers import Container + + +def check_attach(c: Container) -> None: + assert_type(c.attach(), bytes) + assert_type(c.attach(stream=False), bytes) + for line in c.attach(stream=True): + assert_type(line, bytes) diff --git a/stubs/docker/METADATA.toml b/stubs/docker/METADATA.toml new file mode 100644 index 000000000000..70bcc93efcaa --- /dev/null +++ b/stubs/docker/METADATA.toml @@ -0,0 +1,4 @@ +version = "7.2.*" +upstream-repository = "https://github.com/docker/docker-py" +dependencies = ["types-requests", "urllib3>=2"] +optional-dependencies = ["types-paramiko"] diff --git a/stubs/docker/docker/__init__.pyi b/stubs/docker/docker/__init__.pyi new file mode 100644 index 000000000000..52a7b3243202 --- /dev/null +++ b/stubs/docker/docker/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .api import APIClient as APIClient +from .client import DockerClient as DockerClient, from_context as from_context, from_env as from_env +from .context import Context as Context, ContextAPI as ContextAPI +from .tls import TLSConfig as TLSConfig +from .version import __version__ as __version__ + +__title__: Final[str] diff --git a/stubs/docker/docker/_types.pyi b/stubs/docker/docker/_types.pyi new file mode 100644 index 000000000000..5500470c6fa5 --- /dev/null +++ b/stubs/docker/docker/_types.pyi @@ -0,0 +1,25 @@ +# Internal-use module for types shared by multiple modules. +# This does not match a module in docker-py. + +from pathlib import Path +from typing import TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +# Type alias for JSON, explained at: +# https://github.com/python/typing/issues/182#issuecomment-1320974824. +JSON: TypeAlias = dict[str, JSON] | list[JSON] | str | int | float | bool | None + +@type_check_only +class ContainerWeightDevice(TypedDict): + Path: Path + Weight: int + +# See https://docs.docker.com/engine/api/v1.42/#tag/Container/operation/ContainerWait +@type_check_only +class _WaitErrorDetails(TypedDict): + Message: str + +@type_check_only +class WaitContainerResponse(TypedDict): + StatusCode: int + Error: NotRequired[_WaitErrorDetails] diff --git a/stubs/docker/docker/api/__init__.pyi b/stubs/docker/docker/api/__init__.pyi new file mode 100644 index 000000000000..0b38db71747d --- /dev/null +++ b/stubs/docker/docker/api/__init__.pyi @@ -0,0 +1 @@ +from .client import APIClient as APIClient diff --git a/stubs/docker/docker/api/build.pyi b/stubs/docker/docker/api/build.pyi new file mode 100644 index 000000000000..73d69c033557 --- /dev/null +++ b/stubs/docker/docker/api/build.pyi @@ -0,0 +1,55 @@ +from collections.abc import Generator +from io import StringIO +from logging import Logger +from typing import IO, Any, TypedDict, type_check_only + +log: Logger + +@type_check_only +class _ContainerLimits(TypedDict, total=False): + memory: int + memswap: int + cpushares: int + cpusetcpus: str + +@type_check_only +class _Filers(TypedDict, total=False): + dangling: bool + until: str + +class BuildApiMixin: + def build( + self, + path: str | None = None, + tag: str | None = None, + quiet: bool = False, + fileobj: StringIO | IO[bytes] | None = None, + nocache: bool = False, + rm: bool = False, + timeout: int | None = None, + custom_context: bool = False, + encoding: str | None = None, + pull: bool = False, + forcerm: bool = False, + dockerfile: str | None = None, + container_limits: _ContainerLimits | None = None, + decode: bool = False, + buildargs: dict[str, Any] | None = None, + gzip: bool = False, + shmsize: int | None = None, + labels: dict[str, Any] | None = None, + # need to use list, because the type must be json serializable + cache_from: list[str] | None = None, + target: str | None = None, + network_mode: str | None = None, + squash: bool | None = None, + extra_hosts: list[str] | dict[str, str] | None = None, + platform: str | None = None, + isolation: str | None = None, + use_config_proxy: bool = True, + ) -> Generator[Any]: ... + def prune_builds( + self, filters: _Filers | None = None, keep_storage: int | None = None, all: bool | None = None + ) -> dict[str, Any]: ... + +def process_dockerfile(dockerfile: str | None, path: str) -> tuple[str | None, str | None]: ... diff --git a/stubs/docker/docker/api/client.pyi b/stubs/docker/docker/api/client.pyi new file mode 100644 index 000000000000..d3dd50eeb7c7 --- /dev/null +++ b/stubs/docker/docker/api/client.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence + +import requests +from docker.tls import TLSConfig +from requests.adapters import BaseAdapter + +from .build import BuildApiMixin +from .config import ConfigApiMixin +from .container import ContainerApiMixin +from .daemon import DaemonApiMixin +from .exec_api import ExecApiMixin +from .image import ImageApiMixin +from .network import NetworkApiMixin +from .plugin import PluginApiMixin +from .secret import SecretApiMixin +from .service import ServiceApiMixin +from .swarm import SwarmApiMixin +from .volume import VolumeApiMixin + +class APIClient( + requests.Session, + BuildApiMixin, + ConfigApiMixin, + ContainerApiMixin, + DaemonApiMixin, + ExecApiMixin, + ImageApiMixin, + NetworkApiMixin, + PluginApiMixin, + SecretApiMixin, + ServiceApiMixin, + SwarmApiMixin, + VolumeApiMixin, +): + __attrs__: Sequence[str] + base_url: str + timeout: int + credstore_env: Mapping[Incomplete, Incomplete] | None + def __init__( + self, + base_url: str | None = None, + version: str | None = None, + timeout: int = 60, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + use_ssh_client: bool = False, + max_pool_size: int = 10, + ) -> None: ... + def get_adapter(self, url: str) -> BaseAdapter: ... + @property + def api_version(self) -> str: ... + def reload_config(self, dockercfg_path: str | None = None) -> None: ... diff --git a/stubs/docker/docker/api/config.pyi b/stubs/docker/docker/api/config.pyi new file mode 100644 index 000000000000..df2a281ee813 --- /dev/null +++ b/stubs/docker/docker/api/config.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class ConfigApiMixin: + def create_config( + self, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ): ... + def inspect_config(self, id): ... + def remove_config(self, id): ... + def configs(self, filters=None): ... diff --git a/stubs/docker/docker/api/container.pyi b/stubs/docker/docker/api/container.pyi new file mode 100644 index 000000000000..09322cad2948 --- /dev/null +++ b/stubs/docker/docker/api/container.pyi @@ -0,0 +1,326 @@ +import datetime +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import NotRequired + +from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.types.containers import DeviceRequest, LogConfig, Ulimit +from docker.types.daemon import CancellableStream +from docker.types.healthcheck import Healthcheck +from docker.types.services import Mount + +from ..types import ContainerConfig, EndpointConfig, HostConfig, NetworkingConfig + +@type_check_only +class _RestartPolicy(TypedDict): + MaximumRetryCount: NotRequired[int] + Name: NotRequired[Literal["always", "on-failure"]] + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +@type_check_only +class _TopResult(TypedDict): + Titles: list[str] + Processes: list[list[str]] + +_Container: TypeAlias = _HasId | _HasID | str + +class ContainerApiMixin: + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + *, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + logs: bool = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def attach( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + logs: bool = False, + demux: Literal[True], + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + + def attach_socket(self, container: _Container, params=None, ws: bool = False): ... + def commit( + self, + container: _Container, + repository: str | None = None, + tag: str | None = None, + message=None, + author=None, + pause: bool = True, + changes=None, + conf=None, + ): ... + def containers( + self, + quiet: bool = False, + all: bool = False, + trunc: bool = False, + latest: bool = False, + since: str | None = None, + before: str | None = None, + limit: int = -1, + size: bool = False, + filters=None, + ): ... + def create_container( + self, + image, + command: str | list[str] | None = None, + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[Incomplete, Incomplete]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + name: str | None = None, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config=None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config=None, + healthcheck=None, + stop_timeout: int | None = None, + runtime: str | None = None, + use_config_proxy: bool = True, + platform: str | None = None, + ): ... + # Please keep in sync with docker.types.ContainerConfig + def create_container_config( + self, + image: str, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[str, str]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config: HostConfig | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config: NetworkingConfig | None = None, + healthcheck: Healthcheck | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, + ) -> ContainerConfig: ... + def create_container_from_config(self, config, name=None, platform=None): ... + # Please keep in sync with docker.types.HostConfig + def create_host_config( + self, + binds: dict[str, Mapping[str, str]] | list[str] | None = None, + port_bindings: Mapping[int | str, Any] | None = None, # Any: int, str, tuple, dict, or list + lxc_conf: dict[str, str] | list[dict[str, str]] | None = None, + publish_all_ports: bool = False, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + privileged: bool = False, + dns: list[str] | None = None, + dns_search: list[str] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: Mapping[str, str | int] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[str, str] | list[str] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: Iterable[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, + device_read_bps: list[Mapping[str, str | int]] | None = None, + device_write_bps: list[Mapping[str, str | int]] | None = None, + device_read_iops: list[Mapping[str, str | int]] | None = None, + device_write_iops: list[Mapping[str, str | int]] | None = None, + oom_kill_disable: bool = False, + shm_size: str | int | None = None, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[str] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, + auto_remove: bool = False, + storage_opt: dict[str, str] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[str] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, + ) -> HostConfig: ... + # Please keep in sync with docker.types.NetworkingConfig + def create_networking_config(self, endpoints_config: EndpointConfig | None = None) -> NetworkingConfig: ... + # Please keep in sync with docker.types.EndpointConfig + def create_endpoint_config( + self, + aliases: list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + ipv4_address: str | None = None, + ipv6_address: str | None = None, + link_local_ips: list[str] | None = None, + driver_opt: dict[str, str] | None = None, + mac_address: str | None = None, + ) -> EndpointConfig: ... + def diff(self, container: _Container) -> list[dict[Incomplete, Incomplete]]: ... + def export(self, container: _Container, chunk_size: int | None = 2097152): ... + def get_archive( + self, container: _Container, path, chunk_size: int | None = 2097152, encode_stream: bool = False + ) -> tuple[Incomplete, Incomplete]: ... + def inspect_container(self, container: _Container): ... + def kill(self, container: _Container, signal: str | int | None = None) -> None: ... + + @overload + def logs( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + *, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + container: _Container, + stdout: bool, + stderr: bool, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + container: _Container, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> bytes: ... + + def pause(self, container: _Container) -> None: ... + def port(self, container: _Container, private_port: int): ... + def put_archive(self, container: _Container, path: str, data) -> bool: ... + def prune_containers(self, filters=None): ... + def remove_container(self, container: _Container, v: bool = False, link: bool = False, force: bool = False) -> None: ... + def rename(self, container: _Container, name: str) -> None: ... + def resize(self, container: _Container, height: int, width: int) -> None: ... + def restart(self, container: _Container, timeout: int = 10) -> None: ... + def start(self, container: _Container) -> None: ... + def stats(self, container: _Container, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None): ... + def stop(self, container: _Container, timeout: int | None = None) -> None: ... + def top(self, container: _Container, ps_args: str | None = None) -> _TopResult: ... + def unpause(self, container: _Container) -> None: ... + def update_container( + self, + container: _Container, + blkio_weight: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + mem_limit: float | str | None = None, + mem_reservation: float | str | None = None, + memswap_limit: int | str | None = None, + kernel_memory: int | str | None = None, + restart_policy: _RestartPolicy | None = None, + ): ... + def wait( + self, + container: _Container, + timeout: int | None = None, + condition: Literal["not-running", "next-exit", "removed"] | None = None, + ) -> WaitContainerResponse: ... diff --git a/stubs/docker/docker/api/daemon.pyi b/stubs/docker/docker/api/daemon.pyi new file mode 100644 index 000000000000..d1fccfe7b3c4 --- /dev/null +++ b/stubs/docker/docker/api/daemon.pyi @@ -0,0 +1,37 @@ +from datetime import datetime +from typing import Any, Literal, overload + +from docker.types.daemon import CancellableStream + +class DaemonApiMixin: + def df(self) -> dict[str, Any]: ... + + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[False] | None = None, + ) -> CancellableStream[str]: ... + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[True] = ..., + ) -> CancellableStream[dict[str, Any]]: ... + + def info(self) -> dict[str, Any]: ... + def login( + self, + username: str, + password: str | None = None, + email: str | None = None, + registry: str | None = None, + reauth: bool = False, + dockercfg_path: str | None = None, + ) -> dict[str, Any]: ... + def ping(self) -> bool: ... + def version(self, api_version: bool = True) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/api/exec_api.pyi b/stubs/docker/docker/api/exec_api.pyi new file mode 100644 index 000000000000..4b5c1ca02cd0 --- /dev/null +++ b/stubs/docker/docker/api/exec_api.pyi @@ -0,0 +1,137 @@ +from _io import _BufferedReaderStream +from _typeshed import Incomplete +from socket import SocketIO +from typing import Literal, overload + +from docker.transport.sshconn import SSHSocket +from docker.types.daemon import CancellableStream + +class ExecApiMixin: + def exec_create( + self, + container, + cmd, + stdout: bool = True, + stderr: bool = True, + stdin: bool = False, + tty: bool = False, + privileged: bool = False, + user: str = "", + environment: dict[str, str] | list[str] | None = None, + workdir: str | None = None, + detach_keys: str | None = None, + ) -> dict[str, Incomplete]: ... + def exec_inspect(self, exec_id: str) -> dict[str, Incomplete]: ... + def exec_resize(self, exec_id: str, height: int | None = None, width: int | None = None) -> None: ... + + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[True], + tty: bool = False, + stream: bool = False, + socket: bool = False, + demux: bool = False, + ) -> bytes: ... + @overload + def exec_start( + self, exec_id: str, detach: Literal[False], tty: bool, stream: bool, socket: Literal[True], demux: bool = False + ) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: bool = False, + *, + socket: Literal[True], + demux: bool = False, + ) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + @overload + def exec_start( + self, exec_id: str, detach: Literal[False], tty: bool, stream: Literal[True], socket: Literal[False], demux: Literal[True] + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + socket: Literal[False] = False, + *, + stream: Literal[True], + demux: Literal[True], + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False], + tty: bool, + stream: Literal[True], + socket: Literal[False], + demux: Literal[False], + ) -> CancellableStream[bytes]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + *, + stream: Literal[True], + socket: Literal[False] = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False], + tty: bool, + stream: Literal[False], + socket: Literal[False], + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: Literal[False] = False, + socket: Literal[False] = False, + *, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def exec_start( + self, + exec_id: str, + detach: Literal[False] = False, + tty: bool = False, + stream: Literal[False] = False, + socket: Literal[False] = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def exec_start( + self, + exec_id: str, + detach: bool = False, + tty: bool = False, + stream: bool = False, + socket: bool = False, + demux: bool = False, + ) -> ( + str + | SocketIO + | _BufferedReaderStream + | SSHSocket + | CancellableStream[bytes] + | CancellableStream[tuple[bytes | None, bytes | None]] + | tuple[bytes | None, bytes | None] + | bytes + ): ... diff --git a/stubs/docker/docker/api/image.pyi b/stubs/docker/docker/api/image.pyi new file mode 100644 index 000000000000..565ed904d273 --- /dev/null +++ b/stubs/docker/docker/api/image.pyi @@ -0,0 +1,43 @@ +import logging +from typing import Any + +log: logging.Logger + +class ImageApiMixin: + def get_image(self, image: str, chunk_size: int | None = 2097152): ... + def history(self, image): ... + def images(self, name: str | None = None, quiet: bool = False, all: bool = False, filters=None): ... + def import_image( + self, + src=None, + repository: str | None = None, + tag: str | None = None, + image: str | None = None, + changes=None, + stream_src: bool = False, + ): ... + def import_image_from_data(self, data, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_file(self, filename: str, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_stream(self, stream, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_url(self, url, repository: str | None = None, tag: str | None = None, changes=None): ... + def import_image_from_image(self, image, repository: str | None = None, tag: str | None = None, changes=None): ... + def inspect_image(self, image): ... + def inspect_distribution(self, image, auth_config=None): ... + def load_image(self, data, quiet=None): ... + def prune_images(self, filters=None): ... + def pull( + self, + repository: str, + tag: str | None = None, + stream: bool = False, + auth_config: dict[str, Any] | None = None, + decode: bool = False, + platform: str | None = None, + all_tags: bool = False, + ): ... + def push(self, repository: str, tag: str | None = None, stream: bool = False, auth_config=None, decode: bool = False): ... + def remove_image(self, image: str, force: bool = False, noprune: bool = False): ... + def search(self, term: str, limit: int | None = None): ... + def tag(self, image, repository, tag: str | None = None, force: bool = False) -> bool: ... + +def is_file(src: str) -> bool: ... diff --git a/stubs/docker/docker/api/network.pyi b/stubs/docker/docker/api/network.pyi new file mode 100644 index 000000000000..c6a8cf6b434e --- /dev/null +++ b/stubs/docker/docker/api/network.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any, Literal, TypeAlias, TypedDict, type_check_only + +from docker.types import IPAMConfig + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +_Network: TypeAlias = _HasId | _HasID | str +_Container: TypeAlias = _HasId | _HasID | str + +class NetworkApiMixin: + def networks(self, names: list[Incomplete] | None = None, ids: list[Incomplete] | None = None, filters=None): ... + def create_network( + self, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, + internal: bool = False, + labels: dict[str, Any] | None = None, + enable_ipv6: bool = False, + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> dict[str, str]: ... + def prune_networks(self, filters=None): ... + def remove_network(self, net_id: _Network) -> None: ... + def inspect_network( + self, net_id: _Network, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ): ... + def connect_container_to_network( + self, + container: _Container, + net_id: str, + ipv4_address=None, + ipv6_address=None, + aliases=None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + link_local_ips=None, + driver_opt=None, + mac_address=None, + ) -> None: ... + def disconnect_container_from_network(self, container: _Container, net_id: str, force: bool = False) -> None: ... diff --git a/stubs/docker/docker/api/plugin.pyi b/stubs/docker/docker/api/plugin.pyi new file mode 100644 index 000000000000..2b8e21968b88 --- /dev/null +++ b/stubs/docker/docker/api/plugin.pyi @@ -0,0 +1,12 @@ +class PluginApiMixin: + def configure_plugin(self, name, options): ... + def create_plugin(self, name, plugin_data_dir, gzip: bool = False): ... + def disable_plugin(self, name, force: bool = False): ... + def enable_plugin(self, name, timeout: int = 0): ... + def inspect_plugin(self, name): ... + def pull_plugin(self, remote, privileges, name=None): ... + def plugins(self): ... + def plugin_privileges(self, name): ... + def push_plugin(self, name): ... + def remove_plugin(self, name, force: bool = False): ... + def upgrade_plugin(self, name, remote, privileges): ... diff --git a/stubs/docker/docker/api/secret.pyi b/stubs/docker/docker/api/secret.pyi new file mode 100644 index 000000000000..18e6acde3774 --- /dev/null +++ b/stubs/docker/docker/api/secret.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from typing import Any + +from docker.types import DriverConfig + +class SecretApiMixin: + def create_secret( + self, name: str, data: bytes, labels: dict[str, Any] | None = None, driver: DriverConfig | None = None + ) -> dict[str, Any]: ... + def inspect_secret(self, id: str) -> dict[str, Any]: ... + def remove_secret(self, id: str) -> bool: ... + def secrets(self, filters: dict[str, Any] | None = None) -> Iterable[dict[str, Any]]: ... diff --git a/stubs/docker/docker/api/service.pyi b/stubs/docker/docker/api/service.pyi new file mode 100644 index 000000000000..cf86afc7ba6f --- /dev/null +++ b/stubs/docker/docker/api/service.pyi @@ -0,0 +1,45 @@ +class ServiceApiMixin: + def create_service( + self, + task_template, + name=None, + labels=None, + mode=None, + update_config=None, + networks=None, + endpoint_config=None, + endpoint_spec=None, + rollback_config=None, + ): ... + def inspect_service(self, service, insert_defaults=None): ... + def inspect_task(self, task): ... + def remove_service(self, service): ... + def services(self, filters=None, status=None): ... + def service_logs( + self, + service, + details: bool = False, + follow: bool = False, + stdout: bool = False, + stderr: bool = False, + since: int = 0, + timestamps: bool = False, + tail: str = "all", + is_tty=None, + ): ... + def tasks(self, filters=None): ... + def update_service( + self, + service, + version, + task_template=None, + name=None, + labels=None, + mode=None, + update_config=None, + networks=None, + endpoint_config=None, + endpoint_spec=None, + fetch_current_spec: bool = False, + rollback_config=None, + ): ... diff --git a/stubs/docker/docker/api/swarm.pyi b/stubs/docker/docker/api/swarm.pyi new file mode 100644 index 000000000000..428375570858 --- /dev/null +++ b/stubs/docker/docker/api/swarm.pyi @@ -0,0 +1,85 @@ +import logging +from typing import Any, Literal, TypeAlias, TypedDict, type_check_only + +from docker.types.services import DriverConfig +from docker.types.swarm import SwarmExternalCA, SwarmSpec + +log: logging.Logger + +@type_check_only +class _HasId(TypedDict): + Id: str + +@type_check_only +class _HasID(TypedDict): + ID: str + +_Node: TypeAlias = _HasId | _HasID | str + +@type_check_only +class _NodeSpec(TypedDict, total=False): + Name: str + Labels: dict[str, str] + Role: Literal["worker", "manager"] + Availability: Literal["active", "pause", "drain"] + +@type_check_only +class _UnlockKeyResponse(TypedDict): + UnlockKey: str + +class SwarmApiMixin: + def create_swarm_spec( + self, + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> SwarmSpec: ... + def get_unlock_key(self) -> _UnlockKeyResponse: ... + def init_swarm( + self, + advertise_addr: str | None = None, + listen_addr: str = "0.0.0.0:2377", + force_new_cluster: bool = False, + swarm_spec: dict[str, Any] | None = None, # Any: arbitrary SwarmSpec configuration body + default_addr_pool: list[str] | None = None, + subnet_size: int | None = None, + data_path_addr: str | None = None, + data_path_port: int | None = None, + ) -> str: ... + def inspect_swarm(self) -> dict[str, Any]: ... # Any: deeply nested ClusterInfo + JoinTokens + def inspect_node(self, node_id: _Node) -> dict[str, Any]: ... # Any: deeply nested Node object + def join_swarm( + self, + remote_addrs: list[str], + join_token: str, + listen_addr: str = "0.0.0.0:2377", + advertise_addr: str | None = None, + data_path_addr: str | None = None, + ) -> Literal[True]: ... + def leave_swarm(self, force: bool = False) -> Literal[True]: ... + def nodes(self, filters: dict[str, Any] | None = None) -> list[dict[str, Any]]: ... # Any: filter values + Node response + def remove_node(self, node_id: _Node, force: bool = False) -> Literal[True]: ... + def unlock_swarm(self, key: str | _UnlockKeyResponse) -> Literal[True]: ... + def update_node(self, node_id: _Node, version: int, node_spec: _NodeSpec | None = None) -> Literal[True]: ... + def update_swarm( + self, + version: int, + swarm_spec: dict[str, Any] | None = None, # Any: arbitrary SwarmSpec configuration body + rotate_worker_token: bool = False, + rotate_manager_token: bool = False, + rotate_manager_unlock_key: bool = False, + ) -> Literal[True]: ... diff --git a/stubs/docker/docker/api/volume.pyi b/stubs/docker/docker/api/volume.pyi new file mode 100644 index 000000000000..b798f9f79782 --- /dev/null +++ b/stubs/docker/docker/api/volume.pyi @@ -0,0 +1,14 @@ +from typing import Any + +class VolumeApiMixin: + def volumes(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + def create_volume( + self, + name: str | None = None, + driver: str | None = None, + driver_opts: dict[str, Any] | None = None, + labels: dict[str, Any] | None = None, + ) -> dict[str, Any]: ... + def inspect_volume(self, name: str) -> dict[str, Any]: ... + def prune_volumes(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + def remove_volume(self, name, force: bool = False) -> None: ... diff --git a/stubs/docker/docker/auth.pyi b/stubs/docker/docker/auth.pyi new file mode 100644 index 000000000000..48d3c5c2cbd6 --- /dev/null +++ b/stubs/docker/docker/auth.pyi @@ -0,0 +1,48 @@ +from _typeshed import FileDescriptorOrPath, Incomplete, ReadableBuffer +from collections.abc import Mapping, MutableMapping +from logging import Logger +from typing import Final +from typing_extensions import Self + +INDEX_NAME: Final[str] +INDEX_URL: Final[str] +TOKEN_USERNAME: Final[str] +log: Logger + +def resolve_repository_name(repo_name: str) -> tuple[str, str]: ... +def resolve_index_name(index_name: str) -> str: ... +def get_config_header(client, registry) -> bytes | None: ... +def split_repo_name(repo_name: str) -> tuple[str, str]: ... +def get_credential_store(authconfig: AuthConfig | MutableMapping[str, Incomplete], registry: str | None): ... + +class AuthConfig(dict[str, Incomplete]): + def __init__(self, dct: MutableMapping[str, Incomplete], credstore_env=None) -> None: ... + @classmethod + def parse_auth( + cls, entries: Mapping[str, dict[Incomplete, Incomplete]], raise_on_error: bool = False + ) -> dict[str, Incomplete]: ... + @classmethod + def load_config( + cls, config_path: FileDescriptorOrPath | None, config_dict: dict[str, Incomplete] | None, credstore_env=None + ) -> Self: ... + @property + def auths(self) -> dict[str, Incomplete]: ... + @property + def creds_store(self): ... + @property + def cred_helpers(self): ... + @property + def is_empty(self) -> bool: ... + def resolve_authconfig(self, registry: str | None = None): ... + def get_credential_store(self, registry: str | None): ... + def get_all_credentials(self): ... + def add_auth(self, reg: str, data) -> None: ... + +def resolve_authconfig(authconfig, registry: str | None = None, credstore_env=None): ... +def convert_to_hostname(url: str) -> str: ... +def decode_auth(auth: str | ReadableBuffer) -> tuple[str, str]: ... +def encode_header(auth) -> bytes: ... +def parse_auth(entries: Mapping[str, dict[Incomplete, Incomplete]], raise_on_error: bool = False): ... +def load_config( + config_path: FileDescriptorOrPath | None = None, config_dict: dict[str, Incomplete] | None = None, credstore_env=None +) -> AuthConfig: ... diff --git a/stubs/docker/docker/client.pyi b/stubs/docker/docker/client.pyi new file mode 100644 index 000000000000..eef6be705974 --- /dev/null +++ b/stubs/docker/docker/client.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from datetime import datetime +from typing import Any, Literal, Protocol, overload, type_check_only +from typing_extensions import Never + +from docker import APIClient +from docker.models.configs import ConfigCollection +from docker.models.containers import ContainerCollection +from docker.models.images import ImageCollection +from docker.models.networks import NetworkCollection +from docker.models.nodes import NodeCollection +from docker.models.plugins import PluginCollection +from docker.models.secrets import SecretCollection +from docker.models.services import ServiceCollection +from docker.models.swarm import Swarm +from docker.models.volumes import VolumeCollection +from docker.tls import TLSConfig +from docker.types import CancellableStream + +@type_check_only +class _Environ(Protocol): + def __getitem__(self, k: str, /) -> str: ... + def keys(self) -> Iterable[str]: ... + +class DockerClient: + api: APIClient + # Please keep in sync with docker.APIClient + def __init__( + self, + base_url: str | None = None, + version: str | None = None, + timeout: int = 60, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + use_ssh_client: bool = False, + max_pool_size: int = 10, + ) -> None: ... + @classmethod + def from_env( + cls, + *, + version: str | None = None, + timeout: int = 60, + max_pool_size: int = 10, + environment: _Environ | None = None, + use_ssh_client: bool = False, + use_context: bool = True, + ) -> DockerClient: ... + @classmethod + def from_context( + cls, + name=None, + *, + version: str | None = None, + timeout: int = 60, + max_pool_size: int = 10, + use_ssh_client: bool = False, + base_url: str | None = None, + tls: bool | TLSConfig = False, + user_agent: str = ..., + num_pools: int | None = None, + credstore_env: Mapping[Incomplete, Incomplete] | None = None, + ): ... + @property + def configs(self) -> ConfigCollection: ... + @property + def containers(self) -> ContainerCollection: ... + @property + def images(self) -> ImageCollection: ... + @property + def networks(self) -> NetworkCollection: ... + @property + def nodes(self) -> NodeCollection: ... + @property + def plugins(self) -> PluginCollection: ... + @property + def secrets(self) -> SecretCollection: ... + @property + def services(self) -> ServiceCollection: ... + @property + def swarm(self) -> Swarm: ... + @property + def volumes(self) -> VolumeCollection: ... + + # Please keep in sync with docker.api.daemon.DaemonApiMixin.events + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[False] | None = None, + ) -> CancellableStream[str]: ... + @overload + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[True] = ..., + ) -> CancellableStream[dict[str, Any]]: ... + + def df(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.info + def info(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.login + def login( + self, + username: str, + password: str | None = None, + email: str | None = None, + registry: str | None = None, + reauth: bool = False, + dockercfg_path: str | None = None, + ) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.ping + def ping(self) -> bool: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.version + def version(self, api_version: bool = True) -> dict[str, Any]: ... + def close(self) -> None: ... + def __getattr__(self, name: str) -> Never: ... + +from_env = DockerClient.from_env +from_context = DockerClient.from_context diff --git a/stubs/docker/docker/constants.pyi b/stubs/docker/docker/constants.pyi new file mode 100644 index 000000000000..c9692144d083 --- /dev/null +++ b/stubs/docker/docker/constants.pyi @@ -0,0 +1,22 @@ +from collections.abc import Mapping, Sequence +from typing import Final + +DEFAULT_DOCKER_API_VERSION: Final[str] +MINIMUM_DOCKER_API_VERSION: Final[str] +DEFAULT_TIMEOUT_SECONDS: Final[int] +STREAM_HEADER_SIZE_BYTES: Final[int] +CONTAINER_LIMITS_KEYS: Final[Sequence[str]] +DEFAULT_HTTP_HOST: Final[str] +DEFAULT_UNIX_SOCKET: Final[str] +DEFAULT_NPIPE: Final[str] +BYTE_UNITS: Final[Mapping[str, int]] +INSECURE_REGISTRY_DEPRECATION_WARNING: Final[str] +IS_WINDOWS_PLATFORM: Final[bool] +WINDOWS_LONGPATH_PREFIX: Final[str] +DEFAULT_USER_AGENT: Final[str] +DEFAULT_NUM_POOLS: Final[int] +DEFAULT_NUM_POOLS_SSH: Final[int] +DEFAULT_MAX_POOL_SIZE: Final[int] +DEFAULT_DATA_CHUNK_SIZE: Final[int] +DEFAULT_SWARM_ADDR_POOL: Final[Sequence[str]] +DEFAULT_SWARM_SUBNET_SIZE: Final[int] diff --git a/stubs/docker/docker/context/__init__.pyi b/stubs/docker/docker/context/__init__.pyi new file mode 100644 index 000000000000..c9f9395972a2 --- /dev/null +++ b/stubs/docker/docker/context/__init__.pyi @@ -0,0 +1,2 @@ +from .api import ContextAPI as ContextAPI +from .context import Context as Context diff --git a/stubs/docker/docker/context/api.pyi b/stubs/docker/docker/context/api.pyi new file mode 100644 index 000000000000..e825b62e1c2e --- /dev/null +++ b/stubs/docker/docker/context/api.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence + +from docker.context.context import Context +from docker.tls import TLSConfig + +class ContextAPI: + DEFAULT_CONTEXT: Context + @classmethod + def create_context( + cls, + name: str, + orchestrator: str | None = None, + host: str | None = None, + tls_cfg: TLSConfig | None = None, + default_namespace: str | None = None, + skip_tls_verify: bool = False, + ) -> Context: ... + @classmethod + def get_context(cls, name: str | None = None) -> Context: ... + @classmethod + def contexts(cls) -> Sequence[Context]: ... + @classmethod + def get_current_context(cls) -> Context: ... + @classmethod + def kwargs_from_context( + cls, name: str | None = None, environment: Mapping[str, str | None] | None = None + ) -> dict[str, Incomplete]: ... # TODO: Use TypedDict, use SupportsGet + @classmethod + def set_current_context(cls, name: str = "default") -> None: ... + @classmethod + def remove_context(cls, name: str) -> None: ... + @classmethod + def inspect_context(cls, name: str = "default") -> Context: ... diff --git a/stubs/docker/docker/context/config.pyi b/stubs/docker/docker/context/config.pyi new file mode 100644 index 000000000000..a24b8e0f5cd2 --- /dev/null +++ b/stubs/docker/docker/context/config.pyi @@ -0,0 +1,10 @@ +METAFILE: str + +def get_current_context_name() -> str: ... +def write_context_name_to_docker_config(name: str | None = None) -> Exception | None: ... +def get_context_id(name: str) -> str: ... +def get_context_dir() -> str: ... +def get_meta_dir(name: str | None = None) -> str: ... +def get_meta_file(name: str) -> str: ... +def get_tls_dir(name: str | None = None, endpoint: str = "") -> str: ... +def get_context_host(path: str | None = None, tls: bool = False) -> str: ... diff --git a/stubs/docker/docker/context/context.pyi b/stubs/docker/docker/context/context.pyi new file mode 100644 index 000000000000..cffd95233e08 --- /dev/null +++ b/stubs/docker/docker/context/context.pyi @@ -0,0 +1,81 @@ +from typing import TypedDict, type_check_only + +from docker.tls import TLSConfig as _TLSConfig + +@type_check_only +class _StorageData(TypedDict): + MetadataPath: str + TLSPath: str + +@type_check_only +class _Storage(TypedDict): + Storage: _StorageData + +@type_check_only +class _Endpoint(TypedDict, total=False): + Host: str + SkipTLSVerify: bool + DefaultNamespace: str + +@type_check_only +class _TLSMaterial(TypedDict): + TLSMaterial: dict[str, list[str]] + +@type_check_only +class _MetaMetaData(TypedDict, total=False): + StackOrchestrator: str + +@type_check_only +class _Metadata(TypedDict): + Name: str + Metadata: _MetaMetaData + Endpoints: dict[str, _Endpoint] + +@type_check_only +class _Context(_Metadata, _TLSMaterial, _Storage): ... + +class Context: + name: str + context_type: str | None + orchestrator: str | None + endpoints: dict[str, _Endpoint] + tls_cfg: dict[str, _TLSConfig] + meta_path: str + tls_path: str + def __init__( + self, + name: str, + orchestrator: str | None = None, + host: str | None = None, + endpoints: dict[str, _Endpoint] | None = None, + tls: bool = False, + ) -> None: ... + def set_endpoint( + self, + name: str = "docker", + host: str | None = None, + tls_cfg: _TLSConfig | None = None, + skip_tls_verify: bool = False, + def_namespace: str | None = None, + ) -> None: ... + def inspect(self) -> _Context: ... + @classmethod + def load_context(cls, name: str) -> Context | None: ... + def save(self) -> None: ... + def remove(self) -> None: ... + def __call__(self) -> _Context: ... + def is_docker_host(self) -> bool: ... + @property + def Name(self) -> str: ... + @property + def Host(self) -> str | None: ... + @property + def Orchestrator(self) -> str: ... + @property + def Metadata(self) -> _Metadata: ... + @property + def TLSConfig(self) -> _TLSConfig: ... + @property + def TLSMaterial(self) -> _TLSMaterial: ... + @property + def Storage(self) -> _Storage: ... diff --git a/stubs/docker/docker/credentials/__init__.pyi b/stubs/docker/docker/credentials/__init__.pyi new file mode 100644 index 000000000000..d0b5f26cc128 --- /dev/null +++ b/stubs/docker/docker/credentials/__init__.pyi @@ -0,0 +1,8 @@ +from .constants import ( + DEFAULT_LINUX_STORE as DEFAULT_LINUX_STORE, + DEFAULT_OSX_STORE as DEFAULT_OSX_STORE, + DEFAULT_WIN32_STORE as DEFAULT_WIN32_STORE, + PROGRAM_PREFIX as PROGRAM_PREFIX, +) +from .errors import CredentialsNotFound as CredentialsNotFound, StoreError as StoreError +from .store import Store as Store diff --git a/stubs/docker/docker/credentials/constants.pyi b/stubs/docker/docker/credentials/constants.pyi new file mode 100644 index 000000000000..50bc76200277 --- /dev/null +++ b/stubs/docker/docker/credentials/constants.pyi @@ -0,0 +1,4 @@ +PROGRAM_PREFIX: str +DEFAULT_LINUX_STORE: str +DEFAULT_OSX_STORE: str +DEFAULT_WIN32_STORE: str diff --git a/stubs/docker/docker/credentials/errors.pyi b/stubs/docker/docker/credentials/errors.pyi new file mode 100644 index 000000000000..faff8f40e574 --- /dev/null +++ b/stubs/docker/docker/credentials/errors.pyi @@ -0,0 +1,7 @@ +from subprocess import CalledProcessError + +class StoreError(RuntimeError): ... +class CredentialsNotFound(StoreError): ... +class InitializationError(StoreError): ... + +def process_store_error(cpe: CalledProcessError, program: str) -> Exception: ... diff --git a/stubs/docker/docker/credentials/store.pyi b/stubs/docker/docker/credentials/store.pyi new file mode 100644 index 000000000000..42d05f34338e --- /dev/null +++ b/stubs/docker/docker/credentials/store.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +class Store: + program: str + exe: str | None + environment: Incomplete + def __init__(self, program: str, environment=None) -> None: ... + def get(self, server): ... + def store(self, server, username, secret): ... + def erase(self, server) -> None: ... + def list(self): ... diff --git a/stubs/docker/docker/credentials/utils.pyi b/stubs/docker/docker/credentials/utils.pyi new file mode 100644 index 000000000000..1e87e491697b --- /dev/null +++ b/stubs/docker/docker/credentials/utils.pyi @@ -0,0 +1 @@ +def create_environment_dict(overrides): ... diff --git a/stubs/docker/docker/errors.pyi b/stubs/docker/docker/errors.pyi new file mode 100644 index 000000000000..407f1afb13f9 --- /dev/null +++ b/stubs/docker/docker/errors.pyi @@ -0,0 +1,74 @@ +from collections.abc import Iterator, Mapping +from typing import Any +from typing_extensions import Never + +from docker.models.containers import Container +from docker.models.images import Image +from requests import HTTPError, Response + +class DockerException(Exception): ... + +def create_api_error_from_http_exception(e: HTTPError) -> Never: ... + +class APIError(HTTPError, DockerException): + response: Response | None + explanation: str | None + def __init__(self, message: str, response: Response | None = None, explanation: str | None = None) -> None: ... + @property + def status_code(self) -> int | None: ... + def is_error(self) -> bool: ... + def is_client_error(self) -> bool: ... + def is_server_error(self) -> bool: ... + +class NotFound(APIError): ... +class ImageNotFound(NotFound): ... +class InvalidVersion(DockerException): ... +class InvalidRepository(DockerException): ... +class InvalidConfigFile(DockerException): ... +class InvalidArgument(DockerException): ... +class DeprecatedMethod(DockerException): ... + +class TLSParameterError(DockerException): + msg: str + def __init__(self, msg: str) -> None: ... + +class NullResource(DockerException, ValueError): ... + +class ContainerError(DockerException): + container: Container + exit_status: int + command: str | list[str] | None + image: str | Image + stderr: str | None + def __init__( + self, container: Container, exit_status: int, command: str | list[str] | None, image: str | Image, stderr: str | None + ) -> None: ... + +class StreamParseError(RuntimeError): + msg: str + def __init__(self, reason: str) -> None: ... + +class BuildError(DockerException): + msg: str + build_log: Iterator[dict[str, str]] + def __init__(self, reason: str, build_log: Iterator[dict[str, str]]) -> None: ... + +class ImageLoadError(DockerException): ... + +def create_unexpected_kwargs_error(name, kwargs: Mapping[str, Any]) -> Never: ... + +class MissingContextParameter(DockerException): + param: str + def __init__(self, param: str) -> None: ... + +class ContextAlreadyExists(DockerException): + name: str + def __init__(self, name: str) -> None: ... + +class ContextException(DockerException): + msg: str + def __init__(self, msg: str) -> None: ... + +class ContextNotFound(DockerException): + name: str + def __init__(self, name: str) -> None: ... diff --git a/stubs/docker/docker/models/__init__.pyi b/stubs/docker/docker/models/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/docker/docker/models/configs.pyi b/stubs/docker/docker/models/configs.pyi new file mode 100644 index 000000000000..08a8fe4e6baa --- /dev/null +++ b/stubs/docker/docker/models/configs.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from .resource import Collection, Model + +class Config(Model): + id_attribute: str + @property + def name(self) -> str: ... + def remove(self) -> bool: ... + +class ConfigCollection(Collection[Config]): + model: type[Config] + # Please keep in sync with docker.api.config.ConfigApiMixin.create_config + def create( # type: ignore[override] + self, + *, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ) -> Config: ... + def get(self, config_id: str) -> Config: ... + # Please keep in sync with docker.api.config.ConfigApiMixin.configs + def list(self, *, filters=None) -> _list[Config]: ... diff --git a/stubs/docker/docker/models/containers.pyi b/stubs/docker/docker/models/containers.pyi new file mode 100644 index 000000000000..2a89fa402d89 --- /dev/null +++ b/stubs/docker/docker/models/containers.pyi @@ -0,0 +1,477 @@ +import datetime +from _io import _BufferedReaderStream +from builtins import list as _list +from collections.abc import Iterable, Iterator, Mapping +from socket import SocketIO +from typing import Any, Literal, NamedTuple, overload + +from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.api.container import _RestartPolicy, _TopResult +from docker.transport.sshconn import SSHSocket +from docker.types import EndpointConfig +from docker.types.containers import DeviceRequest, LogConfig, Ulimit +from docker.types.daemon import CancellableStream +from docker.types.services import Mount + +from .images import Image +from .resource import Collection, Model + +class Container(Model): + @property + def name(self) -> str | None: ... + @property + def image(self) -> Image | None: ... + @property + def labels(self): ... + @property + def status(self) -> str: ... + @property + def health(self) -> str: ... + @property + def ports(self) -> dict[str, list[dict[str, str]] | None]: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.attach + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[False] = False, + ) -> bytes: ... + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + logs: bool = False, + demux: Literal[True], + ) -> tuple[bytes | None, bytes | None]: ... + @overload + def attach( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[True], + logs: bool = False, + demux: Literal[False] = False, + ) -> CancellableStream[bytes]: ... + @overload + def attach( + self, *, stdout: bool = True, stderr: bool = True, stream: Literal[True], logs: bool = False, demux: Literal[True] + ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.attach_socket + def attach_socket(self, *, params=None, ws: bool = False) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.commit + def commit( + self, + repository: str | None = None, + tag: str | None = None, + *, + message=None, + author=None, + pause: bool = True, + changes=None, + conf=None, + ) -> Image: ... + def diff(self) -> list[dict[str, int | str]]: ... + def exec_run( + self, + cmd: str | list[str], + stdout: bool = True, + stderr: bool = True, + stdin: bool = False, + tty: bool = False, + privileged: bool = False, + user: str = "", + detach: bool = False, + stream: bool = False, + socket: bool = False, + environment: dict[str, str] | list[str] | None = None, + workdir: str | None = None, + demux: bool = False, + ) -> ExecResult: ... + def export(self, chunk_size: int | None = 2097152) -> str: ... + def get_archive( + self, path: str, chunk_size: int | None = 2097152, encode_stream: bool = False + ) -> tuple[Iterator[bytes], dict[str, Any] | None]: ... + def kill(self, signal: str | int | None = None) -> None: ... + + # Please keep in sync with docker.api.container.ContainerApiMixin.logs + @overload + def logs( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[True], + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> CancellableStream[bytes]: ... + @overload + def logs( + self, + *, + stdout: bool = True, + stderr: bool = True, + stream: Literal[False] = False, + timestamps: bool = False, + tail: Literal["all"] | int = "all", + since: datetime.datetime | float | None = None, + follow: bool | None = None, + until: datetime.datetime | float | None = None, + ) -> bytes: ... + + def pause(self) -> None: ... + def put_archive(self, path: str, data) -> bool: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.remove_container + def remove(self, *, v: bool = False, link: bool = False, force: bool = False) -> None: ... + def rename(self, name: str) -> None: ... + def resize(self, height: int, width: int) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.restart + def restart(self, *, timeout: float | None = 10) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.start + def start(self) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stats + def stats( + self, *, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None + ) -> Iterator[dict[str, Any]] | dict[str, Any]: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stop + def stop(self, *, timeout: float | None = None) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.top + def top(self, *, ps_args: str | None = None) -> _TopResult: ... + def unpause(self) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.update_container + def update( + self, + *, + blkio_weight: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + mem_limit: float | str | None = None, + mem_reservation: float | str | None = None, + memswap_limit: int | str | None = None, + kernel_memory: int | str | None = None, + restart_policy: _RestartPolicy | None = None, + ): ... + # Please keep in sync with docker.api.container.ContainerApiMixin.wait + def wait( + self, *, timeout: float | None = None, condition: Literal["not-running", "next-exit", "removed"] | None = None + ) -> WaitContainerResponse: ... + +class ContainerCollection(Collection[Container]): + model: type[Container] + + @overload + def run( + self, + image: str | Image, + command: str | _list[str] | None = None, + stdout: bool = True, + stderr: bool = False, + remove: bool = False, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: Literal[False] = False, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> bytes: ... # TODO: This should return a stream, if `stream` is True + @overload + def run( + self, + image: str | Image, + command: str | _list[str] | None = None, + stdout: bool = True, + stderr: bool = False, + remove: bool = False, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: Literal[True], + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> Container: ... + + def create( # type: ignore[override] + self, + image: str | Image, + command: str | _list[str] | None = None, + *, + auto_remove: bool = False, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, + blkio_weight: int | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, + cgroup_parent: str | None = None, + cgroupns: Literal["private", "host"] | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + cpu_period: int | None = None, + cpu_quota: int | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + cpuset_mems: str | None = None, + detach: bool = False, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, + extra_hosts: dict[str, str] | None = None, + group_add: Iterable[str | int] | None = None, + healthcheck: dict[str, Any] | None = None, + hostname: str | None = None, + init: bool | None = None, + init_path: str | None = None, + ipc_mode: str | None = None, + isolation: str | None = None, + kernel_memory: str | int | None = None, + labels: dict[str, str] | _list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + log_config: LogConfig | None = None, + lxc_conf: dict[str, str] | None = None, + mac_address: str | None = None, + mem_limit: str | int | None = None, + mem_reservation: str | int | None = None, + mem_swappiness: int | None = None, + memswap_limit: str | int | None = None, + mounts: _list[Mount] | None = None, + name: str | None = None, + nano_cpus: int | None = None, + network: str | None = None, + network_disabled: bool = False, + network_mode: str | None = None, + networking_config: dict[str, EndpointConfig] | None = None, + oom_kill_disable: bool = False, + oom_score_adj: int | None = None, + pid_mode: str | None = None, + pids_limit: int | None = None, + platform: str | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, + privileged: bool = False, + publish_all_ports: bool = False, + read_only: bool | None = None, + restart_policy: _RestartPolicy | None = None, + runtime: str | None = None, + security_opt: _list[str] | None = None, + shm_size: str | int | None = None, + stdin_open: bool = False, + stop_signal: str | None = None, + storage_opt: dict[str, str] | None = None, + stream: bool = False, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + tty: bool = False, + ulimits: _list[Ulimit] | None = None, + use_config_proxy: bool | None = None, + user: str | int | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + version: str | None = None, + volume_driver: str | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, + working_dir: str | None = None, + ) -> Container: ... + def get(self, container_id: str) -> Container: ... + def list( + self, + all: bool = False, + before: str | None = None, + filters: dict[str, str | _list[str] | bool] | None = None, + limit: int = -1, + since: str | None = None, + sparse: bool = False, + ignore_removed: bool = False, + ) -> _list[Container]: ... + def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + +RUN_CREATE_KWARGS: list[str] +RUN_HOST_CONFIG_KWARGS: list[str] + +class ExecResult(NamedTuple): + exit_code: int | None + output: bytes | Iterator[bytes] diff --git a/stubs/docker/docker/models/images.pyi b/stubs/docker/docker/models/images.pyi new file mode 100644 index 000000000000..db5b7954ca3e --- /dev/null +++ b/stubs/docker/docker/models/images.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete, SupportsRead +from builtins import list as _list +from collections.abc import Iterator +from io import StringIO +from typing import IO, Any, Literal, TypedDict, overload, type_check_only + +from docker._types import JSON +from docker.api.build import _Filers + +from .resource import Collection, Model + +@type_check_only +class _ContainerLimits(TypedDict, total=False): + memory: int + memswap: int + cpushares: int + cpusetcpus: str + +class Image(Model): + @property + def labels(self) -> dict[str, Any]: ... + @property + def short_id(self) -> str: ... + @property + def tags(self) -> list[str]: ... + def history(self) -> list[Any]: ... + def remove(self, force: bool = False, noprune: bool = False) -> dict[str, Any]: ... + def save(self, chunk_size: int = 2097152, named: str | bool = False) -> Iterator[Any]: ... + # Please keep in sync with docker.api.image.ImageApiMixin.tag + def tag(self, repository: str, tag: str | None = None, *, force: bool = False) -> bool: ... + +class RegistryData(Model): + image_name: str + # Please keep in sync with docker.models.resource.Model.__init__ + def __init__(self, image_name: str, attrs=None, client=None, collection=None) -> None: ... + @property + def id(self) -> str: ... + @property + def short_id(self) -> str: ... + def pull(self, platform: str | None = None) -> Image: ... + def has_platform(self, platform): ... + def reload(self) -> None: ... + +class ImageCollection(Collection[Image]): + model: type[Image] + # Please keep in sync with docker.api.build.BuildApiMixin.build + def build( + self, + *, + path: str | None = None, + tag: str | None = None, + quiet: bool = False, + fileobj: StringIO | IO[bytes] | None = None, + nocache: bool = False, + rm: bool = False, + timeout: int | None = None, + custom_context: bool = False, + encoding: str | None = None, + pull: bool = False, + forcerm: bool = False, + dockerfile: str | None = None, + container_limits: _ContainerLimits | None = None, + decode: bool = False, + buildargs: dict[str, Any] | None = None, + gzip: bool = False, + shmsize: int | None = None, + labels: dict[str, Any] | None = None, + # need to use list, because the type must be json serializable + cache_from: _list[str] | None = None, + target: str | None = None, + network_mode: str | None = None, + squash: bool | None = None, + extra_hosts: _list[str] | dict[str, str] | None = None, + platform: str | None = None, + isolation: str | None = None, + use_config_proxy: bool = True, + ) -> tuple[Image, Iterator[JSON]]: ... + def get(self, name: str) -> Image: ... + def get_registry_data(self, name, auth_config: dict[str, Any] | None = None) -> RegistryData: ... + def list(self, name: str | None = None, all: bool = False, filters: dict[str, Any] | None = None) -> _list[Image]: ... + def load(self, data: bytes | SupportsRead[bytes]) -> _list[Image]: ... + + # Please keep in sync with docker.api.image.ImageApiMixin.pull + @overload + def pull( + self, + repository: str, + tag: str | None = None, + all_tags: Literal[False] = False, + *, + platform: str | None = None, + auth_config: dict[str, Any] | None = None, + ) -> Image: ... + @overload + def pull( + self, + repository: str, + tag: str | None = None, + *, + all_tags: Literal[True], + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _list[Image]: ... + @overload + def pull( + self, + repository: str, + tag: str | None, + all_tags: Literal[True], + *, + auth_config: dict[str, Any] | None = None, + platform: str | None = None, + ) -> _list[Image]: ... + + # Please keep in sync with docker.api.image.ImageApiMixin.push + def push(self, repository: str, tag: str | None = None, *, stream: bool = False, auth_config=None, decode: bool = False): ... + # Please keep in sync with docker.api.image.ImageApiMixin.remove_image + def remove(self, image: str, force: bool = False, noprune: bool = False) -> None: ... + # Please keep in sync with docker.api.image.ImageApiMixin.search + def search(self, term: str, limit: int | None = None): ... + def prune(self, filters: dict[str, Any] | None = None): ... + # Please keep in sync with docker.api.build.BuildApiMixin.prune_builds + def prune_builds( + self, filters: _Filers | None = None, keep_storage: int | None = None, all: bool | None = None + ) -> dict[str, Incomplete]: ... + +def normalize_platform(platform, engine_info): ... diff --git a/stubs/docker/docker/models/networks.pyi b/stubs/docker/docker/models/networks.pyi new file mode 100644 index 000000000000..d1679aa9f397 --- /dev/null +++ b/stubs/docker/docker/models/networks.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete +from builtins import list as _list +from collections.abc import Iterable +from typing import Any, Literal + +from docker.types import IPAMConfig + +from .containers import Container +from .resource import Collection, Model + +class Network(Model): + @property + def name(self) -> str | None: ... + @property + def containers(self) -> list[Container]: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.connect_container_to_network + def connect( + self, + container: str | Container, + ipv4_address=None, + ipv6_address=None, + aliases=None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + link_local_ips=None, + driver_opt=None, + mac_address=None, + ) -> None: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.disconnect_container_from_network + def disconnect(self, container: str | Container, force: bool = False) -> None: ... + def remove(self) -> None: ... + +class NetworkCollection(Collection[Network]): + model: type[Network] + # Please keep in sync with docker.api.network.NetworkApiMixin.create_network + def create( # type: ignore[override] + self, + name: str, + driver: str | None = None, + options: dict[str, Any] | None = None, + ipam: IPAMConfig | None = None, + check_duplicate: bool | None = None, + internal: bool = False, + labels: dict[str, Any] | None = None, + enable_ipv6: bool = False, + attachable: bool | None = None, + scope: Literal["local", "global", "swarm"] | None = None, + ingress: bool | None = None, + ) -> Network: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.inspect_network + def get( # type: ignore[override] + self, network_id: str, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None + ) -> Network: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.networks + def list( + self, names: _list[Incomplete] | None = None, ids: _list[Incomplete] | None = None, filters=None, *, greedy: bool = False + ) -> _list[Network]: ... + def prune(self, filters: dict[str, Incomplete] | None = None) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/models/nodes.pyi b/stubs/docker/docker/models/nodes.pyi new file mode 100644 index 000000000000..e738c9f33bd0 --- /dev/null +++ b/stubs/docker/docker/models/nodes.pyi @@ -0,0 +1,17 @@ +from builtins import list as _list +from typing import Any + +from .resource import Collection, Model + +class Node(Model): + id_attribute: str + @property + def version(self): ... + def update(self, node_spec): ... + def remove(self, force: bool = False): ... + +class NodeCollection(Collection[Node]): + model: type[Node] + def get(self, node_id): ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.nodes + def list(self, filters: dict[str, Any] | None = None) -> _list[Node]: ... # Any: filter values + Node response diff --git a/stubs/docker/docker/models/plugins.pyi b/stubs/docker/docker/models/plugins.pyi new file mode 100644 index 000000000000..68c672edd038 --- /dev/null +++ b/stubs/docker/docker/models/plugins.pyi @@ -0,0 +1,26 @@ +from builtins import list as _list +from collections.abc import Generator +from typing import Any + +from .resource import Collection, Model + +class Plugin(Model): + @property + def name(self) -> str | None: ... + @property + def enabled(self) -> bool | None: ... + @property + def settings(self) -> dict[str, Any] | None: ... + def configure(self, options: dict[str, Any]) -> None: ... + def disable(self, force: bool = False) -> None: ... + def enable(self, timeout: int = 0) -> None: ... + def push(self) -> Generator[dict[str, Any]]: ... + def remove(self, force: bool = False) -> bool: ... + def upgrade(self, remote: str | None = None) -> Generator[dict[str, Any]]: ... + +class PluginCollection(Collection[Plugin]): + model: type[Plugin] + def create(self, name, plugin_data_dir, gzip: bool = False): ... # type: ignore[override] + def get(self, name): ... + def install(self, remote_name, local_name=None): ... + def list(self) -> _list[Plugin]: ... diff --git a/stubs/docker/docker/models/resource.pyi b/stubs/docker/docker/models/resource.pyi new file mode 100644 index 000000000000..4e22b67516ff --- /dev/null +++ b/stubs/docker/docker/models/resource.pyi @@ -0,0 +1,33 @@ +from builtins import list as _list +from typing import Any, Generic, TypeVar +from typing_extensions import Never, Self + +from docker import DockerClient + +_T = TypeVar("_T", bound=Model) + +class Model: + id_attribute: str + client: DockerClient | None + collection: Collection[Self] | None + attrs: dict[str, Any] + def __init__( + self, attrs: dict[str, Any] | None = None, client: DockerClient | None = None, collection: Collection[Self] | None = None + ) -> None: ... + def __eq__(self, other) -> bool: ... + def __hash__(self) -> int: ... + @property + def id(self) -> str | None: ... + @property + def short_id(self) -> str: ... + def reload(self) -> None: ... + +class Collection(Generic[_T]): + model: type[_T] + client: DockerClient + def __init__(self, client: DockerClient | None = None) -> None: ... + def __call__(self, *args, **kwargs) -> Never: ... + def list(self) -> _list[_T]: ... + def get(self, key: str) -> _T: ... + def create(self, attrs: Any | None = None) -> _T: ... + def prepare_model(self, attrs: Model | dict[str, Any]) -> _T: ... diff --git a/stubs/docker/docker/models/secrets.pyi b/stubs/docker/docker/models/secrets.pyi new file mode 100644 index 000000000000..b511220b6cdd --- /dev/null +++ b/stubs/docker/docker/models/secrets.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from docker.types import DriverConfig + +from .resource import Collection, Model + +class Secret(Model): + id_attribute: str + @property + def name(self): ... + def remove(self): ... + +class SecretCollection(Collection[Secret]): + model: type[Secret] + # Please keep in sync with docker.api.secret.SecretApiMixin.create_secret + def create( # type: ignore[override] + self, *, name: str, data: bytes, labels: dict[str, Incomplete] | None = None, driver: DriverConfig | None = None + ): ... + def get(self, secret_id: str): ... + # Please keep in sync with docker.api.secret.SecretApiMixin.secrets + def list(self, *, filters: dict[str, Incomplete] | None = None) -> _list[Secret]: ... diff --git a/stubs/docker/docker/models/services.pyi b/stubs/docker/docker/models/services.pyi new file mode 100644 index 000000000000..1dc00693427e --- /dev/null +++ b/stubs/docker/docker/models/services.pyi @@ -0,0 +1,39 @@ +from builtins import list as _list + +from .resource import Collection, Model + +class Service(Model): + id_attribute: str + @property + def name(self): ... + @property + def version(self): ... + def remove(self): ... + def tasks(self, filters=None): ... + def update(self, **kwargs): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.service_logs + def logs( + self, + *, + details: bool = False, + follow: bool = False, + stdout: bool = False, + stderr: bool = False, + since: int = 0, + timestamps: bool = False, + tail: str = "all", + ): ... + def scale(self, replicas: int | None): ... + def force_update(self): ... + +class ServiceCollection(Collection[Service]): + model: type[Service] + def create(self, image, command=None, **kwargs): ... # type: ignore[override] + def get(self, service_id, insert_defaults=None): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.services + def list(self, *, filters=None, status=None) -> _list[Service]: ... + +CONTAINER_SPEC_KWARGS: list[str] +TASK_TEMPLATE_KWARGS: list[str] +CREATE_SERVICE_KWARGS: list[str] +PLACEMENT_KWARGS: list[str] diff --git a/stubs/docker/docker/models/swarm.pyi b/stubs/docker/docker/models/swarm.pyi new file mode 100644 index 000000000000..f8a5dd9f9934 --- /dev/null +++ b/stubs/docker/docker/models/swarm.pyi @@ -0,0 +1,78 @@ +from collections.abc import Iterable +from typing import Any + +from docker.types.services import DriverConfig +from docker.types.swarm import SwarmExternalCA + +from .resource import Model + +class Swarm(Model): + id_attribute: str + @property + def version(self) -> str | None: ... + def get_unlock_key(self) -> dict[str, Any]: ... + def init( + self, + advertise_addr: str | None = None, + listen_addr: str = "0.0.0.0:2377", + force_new_cluster: bool = False, + default_addr_pool: Iterable[str] | None = None, + subnet_size: int | None = None, + data_path_addr: str | None = None, + data_path_port: int | None = None, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> str: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.join_swarm + def join( + self, + remote_addrs: list[str], + join_token: str, + listen_addr: str = "0.0.0.0:2377", + advertise_addr: str | None = None, + data_path_addr: str | None = None, + ) -> bool: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.leave_swarm + def leave(self, force: bool = False) -> bool: ... + def reload(self) -> None: ... + def unlock(self, key: str) -> bool: ... + def update( + self, + rotate_worker_token: bool = False, + rotate_manager_token: bool = False, + rotate_manager_unlock_key: bool = False, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> bool: ... diff --git a/stubs/docker/docker/models/volumes.pyi b/stubs/docker/docker/models/volumes.pyi new file mode 100644 index 000000000000..b33cfb30557c --- /dev/null +++ b/stubs/docker/docker/models/volumes.pyi @@ -0,0 +1,26 @@ +from builtins import list as _list +from typing import Any + +from .resource import Collection, Model + +class Volume(Model): + id_attribute: str + @property + def name(self) -> str: ... + def remove(self, force: bool = False) -> None: ... + +class VolumeCollection(Collection[Volume]): + model: type[Volume] + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def create( # type: ignore[override] + self, + name: str | None = None, + *, + driver: str | None = None, + driver_opts: dict[str, Any] | None = None, + labels: dict[str, Any] | None = None, + ) -> Volume: ... + def get(self, volume_id: str) -> Volume: ... + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def list(self, *, filters: dict[str, Any] | None = None) -> _list[Volume]: ... + def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/stubs/docker/docker/tls.pyi b/stubs/docker/docker/tls.pyi new file mode 100644 index 000000000000..e7d4a0cbe938 --- /dev/null +++ b/stubs/docker/docker/tls.pyi @@ -0,0 +1,10 @@ +from docker import APIClient + +class TLSConfig: + cert: tuple[str, str] | None + ca_cert: str | None + verify: bool | str | None + def __init__( + self, client_cert: tuple[str, str] | None = None, ca_cert: str | None = None, verify: bool | str | None = None + ) -> None: ... + def configure_client(self, client: APIClient) -> None: ... diff --git a/stubs/docker/docker/transport/__init__.pyi b/stubs/docker/docker/transport/__init__.pyi new file mode 100644 index 000000000000..69637bbd0ef8 --- /dev/null +++ b/stubs/docker/docker/transport/__init__.pyi @@ -0,0 +1,4 @@ +from .npipeconn import NpipeHTTPAdapter as NpipeHTTPAdapter +from .npipesocket import NpipeSocket as NpipeSocket +from .sshconn import SSHHTTPAdapter as SSHHTTPAdapter +from .unixconn import UnixHTTPAdapter as UnixHTTPAdapter diff --git a/stubs/docker/docker/transport/basehttpadapter.pyi b/stubs/docker/docker/transport/basehttpadapter.pyi new file mode 100644 index 000000000000..efa32eef4f7d --- /dev/null +++ b/stubs/docker/docker/transport/basehttpadapter.pyi @@ -0,0 +1,14 @@ +from collections.abc import Mapping + +import requests.adapters +from urllib3.connectionpool import ConnectionPool + +class BaseHTTPAdapter(requests.adapters.HTTPAdapter): + def close(self) -> None: ... + def get_connection_with_tls_context( + self, + request: requests.PreparedRequest, + verify: bool | str | None, + proxies: Mapping[str, str] | None = None, + cert: tuple[str, str] | str | None = None, + ) -> ConnectionPool: ... diff --git a/stubs/docker/docker/transport/npipeconn.pyi b/stubs/docker/docker/transport/npipeconn.pyi new file mode 100644 index 000000000000..c4d5e1c3787c --- /dev/null +++ b/stubs/docker/docker/transport/npipeconn.pyi @@ -0,0 +1,29 @@ +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from docker.transport.npipesocket import NpipeSocket +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class NpipeHTTPConnection(urllib3.connection.HTTPConnection): + npipe_path: str + timeout: int + def __init__(self, npipe_path: str, timeout: int = 60) -> None: ... + sock: NpipeSocket | None + def connect(self) -> None: ... + +class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + npipe_path: str + timeout: urllib3.Timeout + def __init__(self, npipe_path: str, timeout: int = 60, maxsize: int = 10) -> None: ... + +class NpipeHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + npipe_path: str + timeout: int + max_pool_size: int + pools: RecentlyUsedContainer + def __init__(self, base_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10) -> None: ... + def get_connection(self, url, proxies=None): ... + def request_url(self, request, proxies): ... diff --git a/stubs/docker/docker/transport/npipesocket.pyi b/stubs/docker/docker/transport/npipesocket.pyi new file mode 100644 index 000000000000..f68d4785b082 --- /dev/null +++ b/stubs/docker/docker/transport/npipesocket.pyi @@ -0,0 +1,57 @@ +import io +from _typeshed import ReadableBuffer +from typing import Any, Literal, TypeAlias +from typing_extensions import Never + +cERROR_PIPE_BUSY: int +cSECURITY_SQOS_PRESENT: int +cSECURITY_ANONYMOUS: int +MAXIMUM_RETRY_COUNT: int + +def check_closed(f): ... + +_PyHANDLE: TypeAlias = Any # pywin32._win32typing.PyHANDLE + +class NpipeSocket: + def __init__(self, handle: _PyHANDLE | None = None) -> None: ... + def accept(self) -> None: ... + def bind(self, address) -> None: ... + def close(self) -> None: ... + flags: int + def connect(self, address: str, retry_count: int = 0) -> None: ... + def connect_ex(self, address: str) -> None: ... + def detach(self) -> _PyHANDLE | None: ... + def dup(self) -> NpipeSocket: ... + def getpeername(self) -> str: ... + def getsockname(self) -> str: ... + # NotImplementedError + def getsockopt(self, level, optname, buflen=None) -> Never: ... + # NotImplementedError + def ioctl(self, control, option) -> Never: ... + # NotImplementedError + def listen(self, backlog) -> Never: ... + def makefile(self, mode: str | None = None, bufsize: int | None = None) -> io.BufferedReader: ... + def recv(self, bufsize: int, flags: int = 0) -> str: ... + def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[str, str]: ... + def recvfrom_into(self, buf: memoryview | ReadableBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, str]: ... + def recv_into(self, buf: memoryview | ReadableBuffer, nbytes: int = 0) -> int: ... + def send(self, string: str, flags: int = 0) -> int: ... + def sendall(self, string: str, flags: int = 0) -> int: ... + def sendto(self, string: str, address: str) -> int: ... + def setblocking(self, flag: bool) -> None: ... + def settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> int | None: ... + # NotImplementedError + def setsockopt(self, level, optname, value) -> Never: ... + def shutdown(self, how) -> None: ... + +class NpipeFileIOBase(io.RawIOBase): + sock: NpipeSocket + def __init__(self, npipe_socket: NpipeSocket) -> None: ... + def close(self) -> None: ... + def fileno(self): ... + def isatty(self) -> Literal[False]: ... + def readable(self) -> Literal[True]: ... + def readinto(self, buf: memoryview | ReadableBuffer) -> int: ... + def seekable(self) -> Literal[False]: ... + def writable(self) -> Literal[False]: ... diff --git a/stubs/docker/docker/transport/sshconn.pyi b/stubs/docker/docker/transport/sshconn.pyi new file mode 100644 index 000000000000..c184ecb5d3e6 --- /dev/null +++ b/stubs/docker/docker/transport/sshconn.pyi @@ -0,0 +1,53 @@ +import socket +import subprocess + +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from paramiko import SSHClient, Transport +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class SSHSocket(socket.socket): + host: str + port: str | None + user: str | None + proc: subprocess.Popen[bytes] | None + def __init__(self, host: str) -> None: ... + def connect(self, **kwargs) -> None: ... # type: ignore[override] + def sendall(self, data) -> None: ... # type: ignore[override] + def send(self, data): ... # type: ignore[override] + def recv(self, n): ... # type: ignore[override] + def makefile(self, mode): ... # type: ignore[override] + def close(self) -> None: ... + +class SSHConnection(urllib3.connection.HTTPConnection): + ssh_transport: Transport | None + timeout: int + ssh_host: str | None + def __init__(self, ssh_transport: Transport | None = None, timeout: int = 60, host: str | None = None) -> None: ... + sock: SSHSocket | None + def connect(self) -> None: ... + +class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + scheme: str + ssh_transport: Transport | None + timeout: urllib3.Timeout + ssh_host: str | None + def __init__( + self, ssh_client: SSHClient | None = None, timeout: int = 60, maxsize: int = 10, host: str | None = None + ) -> None: ... + +class SSHHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + ssh_client: SSHClient | None + ssh_host: str + timeout: int + max_pool_size: int + pools: int + def __init__( + self, base_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10, shell_out: bool = False + ) -> None: ... + def get_connection(self, url: str | bytes, proxies=None) -> SSHConnectionPool: ... + def close(self) -> None: ... diff --git a/stubs/docker/docker/transport/unixconn.pyi b/stubs/docker/docker/transport/unixconn.pyi new file mode 100644 index 000000000000..b2124a79fb90 --- /dev/null +++ b/stubs/docker/docker/transport/unixconn.pyi @@ -0,0 +1,34 @@ +import socket + +import urllib3 +import urllib3.connection +from docker.transport.basehttpadapter import BaseHTTPAdapter +from requests import PreparedRequest +from urllib3._collections import RecentlyUsedContainer as urllib3_RecentlyUsedContainer + +RecentlyUsedContainer = urllib3_RecentlyUsedContainer + +class UnixHTTPConnection(urllib3.connection.HTTPConnection): + base_url: str + unix_socket: str + timeout: int + def __init__(self, base_url: str, unix_socket: str, timeout: int = 60) -> None: ... + sock: socket.socket | None + def connect(self) -> None: ... + +class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool): + base_url: str + socket_path: str + timeout: urllib3.Timeout + def __init__(self, base_url: str, socket_path: str, timeout: int = 60, maxsize: int = 10) -> None: ... + +class UnixHTTPAdapter(BaseHTTPAdapter): + __attrs__: list[str] + socket_path: str + timeout: int + max_pool_size: int + pools: RecentlyUsedContainer + def __init__(self, socket_url: str, timeout: int = 60, pool_connections: int = 25, max_pool_size: int = 10) -> None: ... + def get_connection(self, url: bytes | str, proxies=None) -> UnixHTTPConnectionPool: ... + # proxies is unused + def request_url(self, request: PreparedRequest, proxies) -> str: ... diff --git a/stubs/docker/docker/types/__init__.pyi b/stubs/docker/docker/types/__init__.pyi new file mode 100644 index 000000000000..9404c047fe2b --- /dev/null +++ b/stubs/docker/docker/types/__init__.pyi @@ -0,0 +1,35 @@ +from .containers import ( + ContainerConfig as ContainerConfig, + DeviceRequest as DeviceRequest, + HostConfig as HostConfig, + LogConfig as LogConfig, + Ulimit as Ulimit, +) +from .daemon import CancellableStream as CancellableStream +from .healthcheck import Healthcheck as Healthcheck +from .networks import ( + EndpointConfig as EndpointConfig, + IPAMConfig as IPAMConfig, + IPAMPool as IPAMPool, + NetworkingConfig as NetworkingConfig, +) +from .services import ( + ConfigReference as ConfigReference, + ContainerSpec as ContainerSpec, + DNSConfig as DNSConfig, + DriverConfig as DriverConfig, + EndpointSpec as EndpointSpec, + Mount as Mount, + NetworkAttachmentConfig as NetworkAttachmentConfig, + Placement as Placement, + PlacementPreference as PlacementPreference, + Privileges as Privileges, + Resources as Resources, + RestartPolicy as RestartPolicy, + RollbackConfig as RollbackConfig, + SecretReference as SecretReference, + ServiceMode as ServiceMode, + TaskTemplate as TaskTemplate, + UpdateConfig as UpdateConfig, +) +from .swarm import SwarmExternalCA as SwarmExternalCA, SwarmSpec as SwarmSpec diff --git a/stubs/docker/docker/types/base.pyi b/stubs/docker/docker/types/base.pyi new file mode 100644 index 000000000000..913e6261d85c --- /dev/null +++ b/stubs/docker/docker/types/base.pyi @@ -0,0 +1,7 @@ +from collections.abc import Mapping +from typing import TypeVar + +_VT = TypeVar("_VT") + +class DictType(dict[str, _VT]): + def __init__(self, init: Mapping[str, _VT]) -> None: ... diff --git a/stubs/docker/docker/types/containers.pyi b/stubs/docker/docker/types/containers.pyi new file mode 100644 index 000000000000..98b38ffc069e --- /dev/null +++ b/stubs/docker/docker/types/containers.pyi @@ -0,0 +1,199 @@ +import builtins +from collections.abc import Iterable, Mapping +from typing import Any, Final, Literal + +from docker._types import ContainerWeightDevice + +from .. import errors +from .base import DictType +from .healthcheck import Healthcheck +from .networks import NetworkingConfig +from .services import Mount + +class LogConfigTypesEnum: + JSON: Final = "json-file" + SYSLOG: Final = "syslog" + JOURNALD: Final = "journald" + GELF: Final = "gelf" + FLUENTD: Final = "fluentd" + NONE: Final = "none" + +class LogConfig(DictType[Any]): + types: builtins.type[LogConfigTypesEnum] + def __init__(self, *, type: str = ..., Type: str = ..., config: dict[str, str] = {}, Config: dict[str, str] = {}) -> None: ... + + @property + def type(self) -> str: ... + @type.setter + def type(self, value: str) -> None: ... + + @property + def config(self) -> dict[str, str]: ... + def set_config_value(self, key: str, value: str) -> None: ... + def unset_config(self, key: str) -> None: ... + +class Ulimit(DictType[Any]): + def __init__( + self, *, name: str = ..., Name: str = ..., soft: int = ..., Soft: int = ..., hard: int = ..., Hard: int = ... + ) -> None: ... + + @property + def name(self) -> str: ... + @name.setter + def name(self, value: str) -> None: ... + + @property + def soft(self) -> int | None: ... + @soft.setter + def soft(self, value: int | None) -> None: ... + + @property + def hard(self) -> int | None: ... + @hard.setter + def hard(self, value: int | None) -> None: ... + +class DeviceRequest(DictType[Any]): + def __init__( + self, + *, + driver: str = ..., + Driver: str = ..., + count: int = ..., + Count: int = ..., + device_ids: list[str] = ..., + DeviceIDs: list[str] = ..., + capabilities: list[list[str]] = ..., + Capabilities: list[list[str]] = ..., + options: dict[str, str] = ..., + Options: dict[str, str] = ..., + ) -> None: ... + + @property + def driver(self) -> str: ... + @driver.setter + def driver(self, value: str) -> None: ... + + @property + def count(self) -> int: ... + @count.setter + def count(self, value: int) -> None: ... + + @property + def device_ids(self) -> list[str]: ... + @device_ids.setter + def device_ids(self, value: list[str]) -> None: ... + + @property + def capabilities(self) -> list[list[str]]: ... + @capabilities.setter + def capabilities(self, value: list[list[str]]) -> None: ... + + @property + def options(self) -> dict[str, str]: ... + @options.setter + def options(self, value: dict[str, str]) -> None: ... + +class HostConfig(dict[str, Any]): + def __init__( + self, + version: str, + binds: dict[str, Mapping[str, str]] | list[str] | None = None, + port_bindings: Mapping[int | str, Any] | None = None, # Any: int, str, tuple, dict, or list + lxc_conf: dict[str, str] | list[dict[str, str]] | None = None, + publish_all_ports: bool = False, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + privileged: bool = False, + dns: list[str] | None = None, + dns_search: list[str] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: Mapping[str, str | int] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[str, str] | list[str] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: Iterable[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, + device_read_bps: list[Mapping[str, str | int]] | None = None, + device_write_bps: list[Mapping[str, str | int]] | None = None, + device_read_iops: list[Mapping[str, str | int]] | None = None, + device_write_iops: list[Mapping[str, str | int]] | None = None, + oom_kill_disable: bool = False, + shm_size: str | int | None = None, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[str] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, + auto_remove: bool = False, + storage_opt: dict[str, str] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[str] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, + ) -> None: ... + +def host_config_type_error(param: str, param_value: object, expected: str) -> TypeError: ... +def host_config_version_error(param: str, version: str, less_than: bool = True) -> errors.InvalidVersion: ... +def host_config_value_error(param: str, param_value: object) -> ValueError: ... +def host_config_incompatible_error(param: str, param_value: str, incompatible_param: str) -> errors.InvalidArgument: ... + +class ContainerConfig(dict[str, Any]): + def __init__( + self, + version: str, + image: str, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[str, str]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config: HostConfig | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config: NetworkingConfig | None = None, + healthcheck: Healthcheck | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, + ) -> None: ... diff --git a/stubs/docker/docker/types/daemon.pyi b/stubs/docker/docker/types/daemon.pyi new file mode 100644 index 000000000000..6561a772fc7a --- /dev/null +++ b/stubs/docker/docker/types/daemon.pyi @@ -0,0 +1,14 @@ +from collections.abc import Iterator +from typing import Generic, TypeVar +from typing_extensions import Self + +from requests import Response + +_T_co = TypeVar("_T_co", covariant=True) + +class CancellableStream(Generic[_T_co]): + def __init__(self, stream: Iterator[_T_co], response: Response) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T_co: ... + next = __next__ + def close(self) -> None: ... diff --git a/stubs/docker/docker/types/healthcheck.pyi b/stubs/docker/docker/types/healthcheck.pyi new file mode 100644 index 000000000000..c113c3fb2b28 --- /dev/null +++ b/stubs/docker/docker/types/healthcheck.pyi @@ -0,0 +1,44 @@ +from typing import Any + +from .base import DictType + +class Healthcheck(DictType[Any]): + def __init__( + self, + *, + test: str | list[str] | None = None, + Test: str | list[str] | None = None, + interval: int | None = None, + Interval: int | None = None, + timeout: int | None = None, + Timeout: int | None = None, + retries: int | None = None, + Retries: int | None = None, + start_period: int | None = None, + StartPeriod: int | None = None, + ) -> None: ... + + @property + def test(self) -> list[str] | None: ... + @test.setter + def test(self, value: str | list[str] | None) -> None: ... + + @property + def interval(self) -> int | None: ... + @interval.setter + def interval(self, value: int | None) -> None: ... + + @property + def timeout(self) -> int | None: ... + @timeout.setter + def timeout(self, value: int | None) -> None: ... + + @property + def retries(self) -> int | None: ... + @retries.setter + def retries(self, value: int | None) -> None: ... + + @property + def start_period(self) -> int | None: ... + @start_period.setter + def start_period(self, value: int | None) -> None: ... diff --git a/stubs/docker/docker/types/networks.pyi b/stubs/docker/docker/types/networks.pyi new file mode 100644 index 000000000000..bf9e5d027714 --- /dev/null +++ b/stubs/docker/docker/types/networks.pyi @@ -0,0 +1,32 @@ +from collections.abc import Iterable +from typing import Any + +class EndpointConfig(dict[str, Any]): + def __init__( + self, + version: str, + aliases: list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + ipv4_address: str | None = None, + ipv6_address: str | None = None, + link_local_ips: list[str] | None = None, + driver_opt: dict[str, str] | None = None, + mac_address: str | None = None, + ) -> None: ... + +class NetworkingConfig(dict[str, Any]): + def __init__(self, endpoints_config: EndpointConfig | None = None) -> None: ... + +class IPAMConfig(dict[str, Any]): + def __init__( + self, driver: str = "default", pool_configs: list[IPAMPool] | None = None, options: dict[str, str] | None = None + ) -> None: ... + +class IPAMPool(dict[str, Any]): + def __init__( + self, + subnet: str | None = None, + iprange: str | None = None, + gateway: str | None = None, + aux_addresses: dict[str, str] | None = None, + ) -> None: ... diff --git a/stubs/docker/docker/types/services.pyi b/stubs/docker/docker/types/services.pyi new file mode 100644 index 000000000000..b82487a83824 --- /dev/null +++ b/stubs/docker/docker/types/services.pyi @@ -0,0 +1,195 @@ +from collections.abc import Iterable, Mapping +from typing import Any, Final, Literal, TypedDict, TypeVar, overload, type_check_only + +from .healthcheck import Healthcheck + +_T = TypeVar("_T") + +class TaskTemplate(dict[str, Any]): + def __init__( + self, + container_spec: ContainerSpec, + resources: Resources | None = None, + restart_policy: RestartPolicy | None = None, + placement: Placement | list[str] | None = None, + log_driver: DriverConfig | None = None, + networks: Iterable[str | NetworkAttachmentConfig] | None = None, + force_update: int | None = None, + ) -> None: ... + @property + def container_spec(self) -> ContainerSpec: ... + @property + def resources(self) -> Resources: ... + @property + def restart_policy(self) -> RestartPolicy: ... + @property + def placement(self) -> Placement: ... + +class ContainerSpec(dict[str, Any]): + def __init__( + self, + image: str, + command: str | list[str] | None = None, + args: list[str] | None = None, + hostname: str | None = None, + env: dict[str, str | bytes | None] | list[str] | None = None, + workdir: str | None = None, + user: str | None = None, + labels: dict[str, str] | None = None, + mounts: Iterable[str | Mount] | None = None, + stop_grace_period: int | None = None, + secrets: list[SecretReference] | None = None, + tty: bool | None = None, + groups: list[str] | None = None, + open_stdin: bool | None = None, + read_only: bool | None = None, + stop_signal: str | None = None, + healthcheck: Healthcheck | None = None, + hosts: Mapping[str, str] | None = None, + dns_config: DNSConfig | None = None, + configs: list[ConfigReference] | None = None, + privileges: Privileges | None = None, + isolation: str | None = None, + init: bool | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + sysctls: dict[str, str] | None = None, + ) -> None: ... + +class Mount(dict[str, Any]): + def __init__( + self, + target: str, + source: str | None, + type: Literal["bind", "volume", "tmpfs", "npipe"] = "volume", + read_only: bool = False, + consistency: Literal["default", "consistent", "cached", "delegated"] | None = None, + propagation: str | None = None, + no_copy: bool = False, + labels: dict[str, str] | None = None, + driver_config: DriverConfig | None = None, + tmpfs_size: int | str | None = None, + tmpfs_mode: int | None = None, + subpath: str | None = None, + ) -> None: ... + @classmethod + def parse_mount_string(cls, string: str) -> Mount: ... + +@type_check_only +class _ResourceDict(TypedDict): + Kind: str + Value: int + +class Resources(dict[str, Any]): + def __init__( + self, + cpu_limit: int | None = None, + mem_limit: int | None = None, + cpu_reservation: int | None = None, + mem_reservation: int | None = None, + generic_resources: ( + dict[str, int | str] | list[dict[Literal["DiscreteResourceSpec", "NamedResourceSpec"], _ResourceDict]] | None + ) = None, + ) -> None: ... + +class UpdateConfig(dict[str, Any]): + def __init__( + self, + parallelism: int = 0, + delay: int | None = None, + failure_action: Literal["pause", "continue", "rollback"] = "continue", + monitor: int | None = None, + max_failure_ratio: float | None = None, + order: Literal["start-first", "stop-first"] | None = None, + ) -> None: ... + +class RollbackConfig(UpdateConfig): ... + +class RestartConditionTypesEnum: + NONE: Final = "none" + ON_FAILURE: Final = "on-failure" + ANY: Final = "any" + +class RestartPolicy(dict[str, Any]): + condition_types: type[RestartConditionTypesEnum] + def __init__( + self, condition: Literal["none", "on-failure", "any"] = "none", delay: int = 0, max_attempts: int = 0, window: int = 0 + ) -> None: ... + +class DriverConfig(dict[str, Any]): + def __init__(self, name: str, options: dict[str, str] | None = None) -> None: ... + +class EndpointSpec(dict[str, Any]): + def __init__( + self, mode: str | None = None, ports: Mapping[str, str | tuple[str | None, ...]] | list[dict[str, str]] | None = None + ) -> None: ... + +@overload +def convert_service_ports(ports: list[_T]) -> list[_T]: ... +@overload +def convert_service_ports(ports: Mapping[str, str | tuple[str | None, ...]]) -> list[dict[str, str]]: ... + +class ServiceMode(dict[str, Any]): + mode: Literal["replicated", "global", "ReplicatedJob", "GlobalJob"] + def __init__( + self, + mode: Literal["replicated", "global", "replicated-job", "global-job"], + replicas: int | None = None, + concurrency: int | None = None, + ) -> None: ... + @property + def replicas(self) -> int | None: ... + +class SecretReference(dict[str, Any]): + def __init__( + self, + secret_id: str, + secret_name: str, + filename: str | None = None, + uid: str | None = None, + gid: str | None = None, + mode: int = 292, + ) -> None: ... + +class ConfigReference(dict[str, Any]): + def __init__( + self, + config_id: str, + config_name: str, + filename: str | None = None, + uid: str | None = None, + gid: str | None = None, + mode: int = 292, + ) -> None: ... + +class Placement(dict[str, Any]): + def __init__( + self, + constraints: list[str] | None = None, + preferences: Iterable[tuple[str, str] | PlacementPreference] | None = None, + platforms: Iterable[tuple[str, str]] | None = None, + maxreplicas: int | None = None, + ) -> None: ... + +class PlacementPreference(dict[str, Any]): + def __init__(self, strategy: Literal["spread"], descriptor: str) -> None: ... + +class DNSConfig(dict[str, Any]): + def __init__( + self, nameservers: list[str] | None = None, search: list[str] | None = None, options: list[str] | None = None + ) -> None: ... + +class Privileges(dict[str, Any]): + def __init__( + self, + credentialspec_file: str | None = None, + credentialspec_registry: str | None = None, + selinux_disable: bool | None = None, + selinux_user: str | None = None, + selinux_role: str | None = None, + selinux_type: str | None = None, + selinux_level: str | None = None, + ) -> None: ... + +class NetworkAttachmentConfig(dict[str, Any]): + def __init__(self, target: str, aliases: list[str] | None = None, options: dict[str, str] | None = None) -> None: ... diff --git a/stubs/docker/docker/types/swarm.pyi b/stubs/docker/docker/types/swarm.pyi new file mode 100644 index 000000000000..b7d81fe5cfea --- /dev/null +++ b/stubs/docker/docker/types/swarm.pyi @@ -0,0 +1,30 @@ +from typing import Any + +from .services import DriverConfig + +class SwarmSpec(dict[str, Any]): + def __init__( + self, + version: str, + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, + ) -> None: ... + +class SwarmExternalCA(dict[str, Any]): + def __init__( + self, url: str, protocol: str | None = None, options: dict[str, str] | None = None, ca_cert: str | None = None + ) -> None: ... diff --git a/stubs/docker/docker/utils/__init__.pyi b/stubs/docker/docker/utils/__init__.pyi new file mode 100644 index 000000000000..608f91d1cf65 --- /dev/null +++ b/stubs/docker/docker/utils/__init__.pyi @@ -0,0 +1,32 @@ +from .build import ( + create_archive as create_archive, + exclude_paths as exclude_paths, + match_tag as match_tag, + mkbuildcontext as mkbuildcontext, + tar as tar, +) +from .decorators import check_resource as check_resource, minimum_version as minimum_version, update_headers as update_headers +from .utils import ( + compare_version as compare_version, + convert_filters as convert_filters, + convert_port_bindings as convert_port_bindings, + convert_service_networks as convert_service_networks, + convert_volume_binds as convert_volume_binds, + create_host_config as create_host_config, + create_ipam_config as create_ipam_config, + create_ipam_pool as create_ipam_pool, + datetime_to_timestamp as datetime_to_timestamp, + decode_json_header as decode_json_header, + format_environment as format_environment, + format_extra_hosts as format_extra_hosts, + kwargs_from_env as kwargs_from_env, + normalize_links as normalize_links, + parse_bytes as parse_bytes, + parse_devices as parse_devices, + parse_env_file as parse_env_file, + parse_host as parse_host, + parse_repository_tag as parse_repository_tag, + split_command as split_command, + version_gte as version_gte, + version_lt as version_lt, +) diff --git a/stubs/docker/docker/utils/build.pyi b/stubs/docker/docker/utils/build.pyi new file mode 100644 index 000000000000..ec168530da14 --- /dev/null +++ b/stubs/docker/docker/utils/build.pyi @@ -0,0 +1,39 @@ +import io +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Generator, Iterable, MutableSequence +from os import PathLike +from tarfile import _Fileobj +from tempfile import _TemporaryFileWrapper + +def match_tag(tag: str) -> bool: ... +def tar( + path: PathLike[str], + exclude: list[str] | None = None, + dockerfile: tuple[str | None, str | None] | None = None, + fileobj: _Fileobj | None = None, + gzip: bool = False, +) -> _TemporaryFileWrapper[bytes] | _Fileobj: ... +def exclude_paths(root: StrPath, patterns: MutableSequence[str], dockerfile: str | None = None) -> set[str]: ... +def build_file_list(root: str) -> list[str]: ... +def create_archive( + root: str, files: Iterable[str] | None = None, fileobj: _Fileobj | None = None, gzip: bool = False, extra_files=None +) -> _TemporaryFileWrapper[bytes] | _Fileobj: ... +def mkbuildcontext(dockerfile: io.IOBase | StrOrBytesPath) -> _TemporaryFileWrapper[bytes]: ... +def split_path(p: str) -> list[str]: ... +def normalize_slashes(p: str) -> str: ... +def walk(root: StrPath, patterns: Iterable[str], default: bool = True) -> Generator[str]: ... + +class PatternMatcher: + patterns: list[Pattern] + def __init__(self, patterns: Iterable[str]) -> None: ... + def matches(self, filepath: PathLike[str]) -> bool: ... + def walk(self, root: StrPath) -> Generator[str]: ... + +class Pattern: + exclusion: bool + dirs: list[str] + cleaned_pattern: str + def __init__(self, pattern_str: str) -> None: ... + @classmethod + def normalize(cls, p: str) -> list[str]: ... + def match(self, filepath: str) -> bool: ... diff --git a/stubs/docker/docker/utils/config.pyi b/stubs/docker/docker/utils/config.pyi new file mode 100644 index 000000000000..50941696e163 --- /dev/null +++ b/stubs/docker/docker/utils/config.pyi @@ -0,0 +1,12 @@ +from _typeshed import FileDescriptorOrPath +from logging import Logger +from typing import Final + +DOCKER_CONFIG_FILENAME: Final[str] +LEGACY_DOCKER_CONFIG_FILENAME: Final[str] +log: Logger + +def find_config_file(config_path: FileDescriptorOrPath | None = None) -> FileDescriptorOrPath | None: ... +def config_path_from_environment() -> str | None: ... +def home_dir() -> str: ... +def load_general_config(config_path: FileDescriptorOrPath | None = None): ... diff --git a/stubs/docker/docker/utils/decorators.pyi b/stubs/docker/docker/utils/decorators.pyi new file mode 100644 index 000000000000..2a8a68524cd5 --- /dev/null +++ b/stubs/docker/docker/utils/decorators.pyi @@ -0,0 +1,9 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +def check_resource(resource_name: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def minimum_version(version: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... +def update_headers(f: Callable[_P, _R]) -> Callable[_P, _R]: ... diff --git a/stubs/docker/docker/utils/fnmatch.pyi b/stubs/docker/docker/utils/fnmatch.pyi new file mode 100644 index 000000000000..631a71ee5c0a --- /dev/null +++ b/stubs/docker/docker/utils/fnmatch.pyi @@ -0,0 +1,5 @@ +__all__ = ["fnmatch", "fnmatchcase", "translate"] + +def fnmatch(name: str, pat: str) -> bool: ... +def fnmatchcase(name: str, pat: str) -> bool: ... +def translate(pat: str) -> str: ... diff --git a/stubs/docker/docker/utils/json_stream.pyi b/stubs/docker/docker/utils/json_stream.pyi new file mode 100644 index 000000000000..4805785eb27b --- /dev/null +++ b/stubs/docker/docker/utils/json_stream.pyi @@ -0,0 +1,15 @@ +import json +from collections.abc import Callable, Generator, Iterator +from typing import Any + +from docker._types import JSON + +json_decoder: json.JSONDecoder + +def stream_as_text(stream: Iterator[str | bytes]) -> Generator[str]: ... +def json_splitter(buffer: str) -> tuple[JSON, str] | None: ... +def json_stream(stream: Iterator[str]) -> Generator[JSON]: ... +def line_splitter(buffer: str, separator: str = "\n") -> tuple[str, str] | None: ... +def split_buffer( + stream: Iterator[str | bytes], splitter: Callable[[str], tuple[str, str]] | None = None, decoder: Callable[[str], Any] = ... +) -> Generator[Any]: ... diff --git a/stubs/docker/docker/utils/ports.pyi b/stubs/docker/docker/utils/ports.pyi new file mode 100644 index 000000000000..ffc6615f36b4 --- /dev/null +++ b/stubs/docker/docker/utils/ports.pyi @@ -0,0 +1,11 @@ +import re +from _typeshed import Incomplete +from typing import Final + +PORT_SPEC: Final[re.Pattern[str]] + +def add_port_mapping(port_bindings, internal_port, external) -> None: ... +def add_port(port_bindings, internal_port_range, external_range) -> None: ... +def build_port_bindings(ports) -> dict[Incomplete, Incomplete]: ... +def port_range(start, end, proto, randomly_available_port: bool = False): ... +def split_port(port: object) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/docker/docker/utils/proxy.pyi b/stubs/docker/docker/utils/proxy.pyi new file mode 100644 index 000000000000..a8e84d1a6ba1 --- /dev/null +++ b/stubs/docker/docker/utils/proxy.pyi @@ -0,0 +1,35 @@ +from collections.abc import Sequence +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +@type_check_only +class _ProxyConfigDict(TypedDict): + http: NotRequired[str] + https: NotRequired[str] + ftpProxy: NotRequired[str] + noProxy: NotRequired[str] + +@type_check_only +class _Environment(TypedDict): + http_proxy: NotRequired[str] + HTTP_PROXY: NotRequired[str] + https_proxy: NotRequired[str] + HTTPS_PROXY: NotRequired[str] + ftp_proxy: NotRequired[str] + FTP_PROXY: NotRequired[str] + no_proxy: NotRequired[str] + NO_PROXY: NotRequired[str] + +class ProxyConfig(dict[str, str]): + @property + def http(self) -> str | None: ... + @property + def https(self) -> str | None: ... + @property + def ftp(self) -> str | None: ... + @property + def no_proxy(self) -> str | None: ... + @staticmethod + def from_dict(config: _ProxyConfigDict) -> ProxyConfig: ... + def get_environment(self) -> _Environment: ... + def inject_proxy_environment(self, environment: None | Sequence[str]) -> None | Sequence[str]: ... diff --git a/stubs/docker/docker/utils/socket.pyi b/stubs/docker/docker/utils/socket.pyi new file mode 100644 index 000000000000..67e4caab2beb --- /dev/null +++ b/stubs/docker/docker/utils/socket.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Generator, Iterable +from typing import Final, Literal, TypeVar, overload + +_T = TypeVar("_T") + +STDOUT: Final = 1 +STDERR: Final = 2 + +class SocketError(Exception): ... + +NPIPE_ENDED: Final = 109 + +def read(socket, n: int = 4096): ... +def read_exactly(socket, n: int) -> bytes: ... +def next_frame_header(socket) -> tuple[Incomplete, int]: ... +def frames_iter(socket, tty): ... +def frames_iter_no_tty(socket) -> Generator[tuple[str | Incomplete, str | bytes | Incomplete]]: ... +def frames_iter_tty(socket) -> Generator[Incomplete]: ... + +@overload +def consume_socket_output( + frames: Iterable[tuple[Incomplete, Incomplete]], demux: Literal[True] +) -> tuple[Incomplete, Incomplete]: ... +@overload +def consume_socket_output(frames: Iterable[ReadableBuffer], demux: Literal[False] = False) -> bytes: ... + +@overload +def demux_adaptor(stream_id: Literal[1], data: _T) -> tuple[_T, None]: ... +@overload +def demux_adaptor(stream_id: Literal[2], data: _T) -> tuple[None, _T]: ... diff --git a/stubs/docker/docker/utils/utils.pyi b/stubs/docker/docker/utils/utils.pyi new file mode 100644 index 000000000000..7b248df23535 --- /dev/null +++ b/stubs/docker/docker/utils/utils.pyi @@ -0,0 +1,78 @@ +import datetime +from _typeshed import FileDescriptorOrPath, ReadableBuffer, Unused +from collections.abc import Iterable, Mapping +from shlex import _ShlexInstream +from typing import Literal, NamedTuple, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated + +from ..tls import TLSConfig + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +@type_check_only +class _EnvKWArgs(TypedDict, total=False): + base_url: str + tls: TLSConfig + +class URLComponents(NamedTuple): + scheme: str | None + netloc: str | None + url: str + params: str | None + query: str | None + fragment: str | None + +@deprecated("utils.create_ipam_pool has been removed. Please use a docker.types.IPAMPool object instead.") +def create_ipam_pool(*args: Unused, **kwargs: Unused) -> Never: ... +@deprecated("utils.create_ipam_config has been removed. Please use a docker.types.IPAMConfig object instead.") +def create_ipam_config(*args: Unused, **kwargs: Unused) -> Never: ... +def decode_json_header(header: str | ReadableBuffer): ... +def compare_version(v1: str, v2: str) -> Literal[0, -1, 1]: ... +def version_lt(v1: str, v2: str) -> bool: ... +def version_gte(v1: str, v2: str) -> bool: ... +def convert_port_bindings( + port_bindings: Mapping[str, int | list[int] | tuple[str, int] | None], +) -> dict[str, list[dict[str, str]]]: ... + +@overload +def convert_volume_binds(binds: list[_T]) -> list[_T]: ... +@overload +def convert_volume_binds(binds: Mapping[str | bytes, bytes | str | dict[str, bytes | str]]) -> list[str]: ... + +@overload +def convert_tmpfs_mounts(tmpfs: dict[_K, _V]) -> dict[_K, _V]: ... +@overload +def convert_tmpfs_mounts(tmpfs: list[str]) -> dict[str, str]: ... + +@overload +def convert_service_networks(networks: None) -> None: ... +@overload +def convert_service_networks(networks: list[str] | list[dict[str, str]] | list[str | dict[str, str]]) -> list[dict[str, str]]: ... + +def parse_repository_tag(repo_name: str) -> tuple[str, str | None]: ... + +@overload +def parse_host(addr: None, is_win32: Literal[True], tls: bool = False) -> Literal["npipe:////./pipe/docker_engine"]: ... +@overload +def parse_host( + addr: None, is_win32: Literal[False] = False, tls: bool = False +) -> Literal["http+unix:///var/run/docker.sock"]: ... +@overload +def parse_host(addr: str | None, is_win32: bool = False, tls: bool = False) -> str | bytes: ... + +def parse_devices(devices: Iterable[str | dict[str, str]]) -> list[dict[str, str]]: ... +def kwargs_from_env(environment: Mapping[str, str] | None = None) -> _EnvKWArgs: ... +def convert_filters(filters) -> str: ... +def datetime_to_timestamp(dt: datetime.datetime) -> int: ... +def parse_bytes(s: float | str) -> float: ... +def normalize_links(links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]]): ... +def parse_env_file(env_file: FileDescriptorOrPath) -> dict[str, str]: ... +def split_command(command: str | _ShlexInstream) -> list[str]: ... +def format_environment(environment: Mapping[str, object | None]) -> list[str]: ... +def format_extra_hosts( + extra_hosts: Mapping[object, object], task: bool = False # keys and values are converted to str +) -> list[str]: ... +@deprecated("utils.create_host_config has been removed. Please use a docker.types.HostConfig object instead.") +def create_host_config(self, *args: Unused, **kwargs: Unused) -> Never: ... diff --git a/stubs/docker/docker/version.pyi b/stubs/docker/docker/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/docker/docker/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/dockerfile-parse/METADATA.toml b/stubs/dockerfile-parse/METADATA.toml new file mode 100644 index 000000000000..8f5cd433f5de --- /dev/null +++ b/stubs/dockerfile-parse/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.*" +upstream-repository = "https://github.com/containerbuildsystem/dockerfile-parse" diff --git a/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi b/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi new file mode 100644 index 000000000000..53ccc597c4dc --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/__init__.pyi @@ -0,0 +1,5 @@ +from typing import Final + +from .parser import DockerfileParser as DockerfileParser + +__version__: Final[str] diff --git a/stubs/dockerfile-parse/dockerfile_parse/constants.pyi b/stubs/dockerfile-parse/dockerfile_parse/constants.pyi new file mode 100644 index 000000000000..9453a8eff553 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/constants.pyi @@ -0,0 +1,4 @@ +from typing import Final + +DOCKERFILE_FILENAME: Final = "Dockerfile" +COMMENT_INSTRUCTION: Final = "COMMENT" diff --git a/stubs/dockerfile-parse/dockerfile_parse/parser.pyi b/stubs/dockerfile-parse/dockerfile_parse/parser.pyi new file mode 100644 index 000000000000..fbaa98096332 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/parser.pyi @@ -0,0 +1,70 @@ +import logging +from collections.abc import Mapping, Sequence +from typing import IO, ClassVar, TypedDict, type_check_only + +from .util import Context + +logger: logging.Logger + +class KeyValues(dict[str, str]): + parser_attr: ClassVar[str | None] + parser: DockerfileParser + def __init__(self, key_values: Mapping[str, str], parser: DockerfileParser) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __setitem__(self, key: str, value: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... # type: ignore[override] + +class Labels(KeyValues): ... +class Envs(KeyValues): ... +class Args(KeyValues): ... + +@type_check_only +class _InstructionDict(TypedDict): + instruction: str + startline: int + endline: int + content: str + value: str + +class DockerfileParser: + fileobj: IO[str] + dockerfile_path: str + cache_content: bool + cached_content: str + env_replace: bool + parent_env: dict[str, str] + build_args: dict[str, str] + def __init__( + self, + path: str | None = None, + cache_content: bool = False, + env_replace: bool = True, + parent_env: dict[str, str] | None = None, + fileobj: IO[str] | None = None, + build_args: dict[str, str] | None = None, + ) -> None: ... + lines: list[str] + content: str + @property + def structure(self) -> list[_InstructionDict]: ... + @property + def json(self) -> str: ... + parent_images: Sequence[str] + @property + def is_multistage(self) -> bool: ... + baseimage: str + cmd: str + labels: Mapping[str, str] + envs: Mapping[str, str] + args: Mapping[str, str] + def add_lines( + self, *lines: str, all_stages: bool | None = ..., at_start: bool | None = ..., skip_scratch: bool | None = ... + ) -> None: ... + def add_lines_at( + self, anchor: str | int | dict[str, int], *lines: str, replace: bool | None = ..., after: bool | None = ... + ) -> None: ... + @property + def context_structure(self) -> list[Context]: ... + +def image_from(from_value: str) -> tuple[str | None, str | None]: ... diff --git a/stubs/dockerfile-parse/dockerfile_parse/util.pyi b/stubs/dockerfile-parse/dockerfile_parse/util.pyi new file mode 100644 index 000000000000..ca1f4086b290 --- /dev/null +++ b/stubs/dockerfile-parse/dockerfile_parse/util.pyi @@ -0,0 +1,51 @@ +from collections.abc import Generator, Mapping, MutableMapping +from io import StringIO +from typing import ClassVar, Literal, TypeAlias + +def b2u(string: bytes | str) -> str: ... +def u2b(string: str | bytes) -> bytes: ... + +_Quotes: TypeAlias = Literal["'", '"'] +_ContextType: TypeAlias = Literal["ARG", "ENV", "LABEL"] + +class WordSplitter: + SQUOTE: ClassVar[_Quotes] + DQUOTE: ClassVar[_Quotes] + stream: StringIO + args: Mapping[str, str] | None + envs: Mapping[str, str] | None + quotes: _Quotes | None + escaped: bool + def __init__(self, s: str, args: Mapping[str, str] | None = None, envs: Mapping[str, str] | None = None) -> None: ... + def dequote(self) -> str: ... + def split(self, maxsplit: int | None = None, dequote: bool = True) -> Generator[str | None]: ... + +def extract_key_values( + env_replace: bool, args: Mapping[str, str], envs: Mapping[str, str], instruction_value: str +) -> list[tuple[str, str]]: ... +def get_key_val_dictionary( + instruction_value: str, + env_replace: bool = False, + args: Mapping[str, str] | None = None, + envs: Mapping[str, str] | None = None, +) -> dict[str, str]: ... + +class Context: + args: MutableMapping[str, str] + envs: MutableMapping[str, str] + labels: MutableMapping[str, str] + line_args: Mapping[str, str] + line_envs: Mapping[str, str] + line_labels: Mapping[str, str] + def __init__( + self, + args: MutableMapping[str, str] | None = None, + envs: MutableMapping[str, str] | None = None, + labels: MutableMapping[str, str] | None = None, + line_args: Mapping[str, str] | None = None, + line_envs: Mapping[str, str] | None = None, + line_labels: Mapping[str, str] | None = None, + ) -> None: ... + def set_line_value(self, context_type: _ContextType, value: Mapping[str, str]) -> None: ... + def get_line_value(self, context_type: _ContextType) -> Mapping[str, str]: ... + def get_values(self, context_type: _ContextType) -> Mapping[str, str]: ... diff --git a/stubs/docutils/@tests/stubtest_allowlist.txt b/stubs/docutils/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..25b1f04867fd --- /dev/null +++ b/stubs/docutils/@tests/stubtest_allowlist.txt @@ -0,0 +1,24 @@ +docutils.nodes.Element.__iter__ # doesn't exist at runtime, but the class is iterable due to __getitem__ +docutils.nodes.Element.tagname # class variable is overridden in __init__ method +docutils.nodes.NodeVisitor.depart_\w+ # Methods are discovered dynamically on commonly-used subclasses +docutils.nodes.NodeVisitor.visit_\w+ # Methods are discovered dynamically on commonly-used subclasses +docutils.nodes.NodeVisitor.__init__ # Argument "document" should be positional-only, but subclasses are not + +# these methods take a rawsource parameter that has been deprecated and is completely ignored, so we omit it from the stub +docutils.nodes.Text.__new__ +docutils.parsers.rst.directives.admonitions.BaseAdmonition.node_class # must be overridden by base classes (pseudo-abstract) +docutils.statemachine.State.nested_sm # is initialised in __init__ +docutils.statemachine.State.nested_sm_kwargs # is initialised in __init__ +docutils.statemachine.ViewList.__iter__ # doesn't exist at runtime, but the class is iterable due to __getitem__ +docutils.transforms.Transform.apply # method apply is not implemented +docutils.transforms.Transform.__getattr__ +docutils.TransformSpec.unknown_reference_resolvers +docutils.writers.latex2e.PreambleCmds... contents + +# Files that don't exist at runtime of stubtests, raises ImportError: +docutils.parsers.commonmark_wrapper +docutils.parsers.recommonmark_wrapper +docutils.writers.odf_odt.pygmentsformatter # import `pygments` third-party library + +# `TYPE_CHECKING` variable is for internal use: +docutils.*\.TYPE_CHECKING diff --git a/stubs/docutils/METADATA.toml b/stubs/docutils/METADATA.toml new file mode 100644 index 000000000000..3d0d77995d83 --- /dev/null +++ b/stubs/docutils/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.22.3" +upstream-repository = "https://sourceforge.net/p/docutils/code" diff --git a/stubs/docutils/docutils/__init__.pyi b/stubs/docutils/docutils/__init__.pyi new file mode 100644 index 000000000000..9845ec945daa --- /dev/null +++ b/stubs/docutils/docutils/__init__.pyi @@ -0,0 +1,46 @@ +from typing import Any, ClassVar, Final, NamedTuple, type_check_only +from typing_extensions import Self + +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" +__version__: Final[str] + +@type_check_only +class _VersionInfo(NamedTuple): + major: int + minor: int + micro: int + releaselevel: str + serial: int + release: bool + +class VersionInfo(_VersionInfo): + __slots__ = () + def __new__( + cls, major: int = 0, minor: int = 0, micro: int = 0, releaselevel: str = "final", serial: int = 0, release: bool = True + ) -> Self: ... + +__version_info__: Final[VersionInfo] +__version_details__: Final[str] + +class ApplicationError(Exception): ... +class DataError(ApplicationError): ... + +class SettingsSpec: + settings_spec: ClassVar[tuple[Any, ...]] # Mixed tuple structure; uses Any for flexibility in nested option definitions + settings_defaults: ClassVar[dict[Any, Any] | None] + settings_default_overrides: ClassVar[dict[Any, Any] | None] + relative_path_settings: ClassVar[tuple[Any, ...]] + config_section: ClassVar[str | None] + config_section_dependencies: ClassVar[tuple[str, ...] | None] + +class TransformSpec: + def get_transforms(self) -> list[type[Transform]]: ... + default_transforms: ClassVar[tuple[Any, ...]] + unknown_reference_resolvers: ClassVar[list[Any]] + +class Component(SettingsSpec, TransformSpec): + component_type: ClassVar[str | None] + supported: ClassVar[tuple[str, ...]] + def supports(self, format: str) -> bool: ... diff --git a/stubs/docutils/docutils/__main__.pyi b/stubs/docutils/docutils/__main__.pyi new file mode 100644 index 000000000000..819b94bd9593 --- /dev/null +++ b/stubs/docutils/docutils/__main__.pyi @@ -0,0 +1,11 @@ +from typing import ClassVar, Final + +import docutils + +__docformat__: Final = "reStructuredText" + +class CliSettingsSpec(docutils.SettingsSpec): + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + +def main() -> None: ... diff --git a/stubs/docutils/docutils/core.pyi b/stubs/docutils/docutils/core.pyi new file mode 100644 index 000000000000..3532dd0d86d6 --- /dev/null +++ b/stubs/docutils/docutils/core.pyi @@ -0,0 +1,219 @@ +from _typeshed import Incomplete, StrPath +from typing import Final +from typing_extensions import deprecated + +from docutils import SettingsSpec +from docutils.io import FileInput, Input, Output +from docutils.parsers import Parser +from docutils.readers import Reader +from docutils.utils import SystemMessage +from docutils.writers import Writer, _WriterParts + +__docformat__: Final = "reStructuredText" + +class Publisher: + document: Incomplete | None + reader: Reader[Incomplete] + parser: Parser + writer: Writer[Incomplete] + source: Input[Incomplete] + source_class: Incomplete + destination: Output | None + destination_class: Incomplete + settings: dict[str, Incomplete] + def __init__( + self, + reader: Reader[Incomplete] | None = None, + parser: Parser | None = None, + writer: Writer[Incomplete] | None = None, + source: Input[Incomplete] | None = None, + source_class=..., + destination: Output | None = None, + destination_class=..., + settings: dict[str, Incomplete] | None = None, + ) -> None: ... + def set_reader(self, reader: str, parser: Parser | None = None, parser_name: str | None = None) -> None: ... + def set_writer(self, writer_name: str) -> None: ... + @deprecated("The `Publisher.set_components()` will be removed in Docutils 2.0.") + def set_components(self, reader_name: str, parser_name: str, writer_name: str) -> None: ... + def get_settings( + self, + usage: str | None = None, + description: str | None = None, + settings_spec: SettingsSpec | None = None, + config_section: str | None = None, + **defaults, + ): ... + def process_programmatic_settings(self, settings_spec, settings_overrides, config_section) -> None: ... + def process_command_line( + self, + argv: list[str] | None = None, + usage=None, + description: str | None = None, + settings_spec=None, + config_section=None, + **defaults, + ) -> None: ... + def set_io(self, source_path: StrPath | None = None, destination_path: StrPath | None = None) -> None: ... + def set_source(self, source: str | None = None, source_path: StrPath | None = None) -> None: ... + def set_destination(self, destination=None, destination_path: StrPath | None = None) -> None: ... + def apply_transforms(self) -> None: ... + def publish( + self, + argv: list[str] | None = None, + usage: str | None = None, + description: str | None = None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, + ): ... + def debugging_dumps(self) -> None: ... + def prompt(self) -> None: ... + def report_Exception(self, error: BaseException) -> None: ... + def report_SystemMessage(self, error: SystemMessage) -> None: ... + def report_UnicodeError(self, error: UnicodeEncodeError) -> None: ... + +default_usage: Final[str] +default_description: Final[str] + +def publish_cmdline( + reader: Reader[Incomplete] | None = None, + reader_name: str | None = None, + parser: Parser | None = None, + parser_name: str | None = None, + writer: Writer[Incomplete] | None = None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = True, + argv: list[str] | None = None, + usage: str = "%prog [options] [ []]", + description: str = ..., +): ... +def publish_file( + source=None, + source_path: StrPath | None = None, + destination=None, + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +def publish_string( + source, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +def publish_parts( + source, + source_path: StrPath | None = None, + source_class=..., + destination_path: StrPath | None = None, + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides: dict[str, Incomplete] | None = None, + config_section: str | None = None, + enable_exit_status: bool = False, +) -> _WriterParts: ... +def publish_doctree( + source, + source_path: StrPath | None = None, + source_class=..., + reader=None, + reader_name: str | None = None, + parser=None, + parser_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +def publish_from_doctree( + document, + destination_path: StrPath | None = None, + writer=None, + writer_name: str | None = None, + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = False, +): ... +@deprecated("The `publish_cmdline_to_binary()` is deprecated by `publish_cmdline()` and will be removed in Docutils 0.24.") +def publish_cmdline_to_binary( + reader=None, + reader_name: str = "standalone", + parser=None, + parser_name: str = "restructuredtext", + writer=None, + writer_name: str = "pseudoxml", + settings=None, + settings_spec=None, + settings_overrides=None, + config_section: str | None = None, + enable_exit_status: bool = True, + argv: list[str] | None = None, + usage: str = "%prog [options] [ []]", + description: str = ..., + destination=None, + destination_class=..., +): ... +def publish_programmatically( + source_class: type[FileInput], + source, + source_path: StrPath | None, + destination_class, + destination, + destination_path: StrPath | None, + reader, + reader_name: str, + parser, + parser_name: str, + writer, + writer_name: str, + settings, + settings_spec, + settings_overrides, + config_section: str, + enable_exit_status: bool, +) -> tuple[str | bytes | None, Publisher]: ... +def rst2something(writer: str, documenttype: str, doc_path: str = "") -> None: ... +def rst2html() -> None: ... +def rst2html4() -> None: ... +def rst2html5() -> None: ... +def rst2latex() -> None: ... +def rst2man() -> None: ... +def rst2odt() -> None: ... +def rst2pseudoxml() -> None: ... +def rst2s5() -> None: ... +def rst2xetex() -> None: ... +def rst2xml() -> None: ... diff --git a/stubs/docutils/docutils/examples.pyi b/stubs/docutils/docutils/examples.pyi new file mode 100644 index 000000000000..3973316b9666 --- /dev/null +++ b/stubs/docutils/docutils/examples.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete, StrPath +from typing import Literal, TypeAlias, overload + +from docutils.core import Publisher +from docutils.nodes import document +from docutils.writers import _WriterParts + +_HTMLHeaderLevel: TypeAlias = Literal[1, 2, 3, 4, 5, 6] + +def html_parts( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> _WriterParts: ... + +@overload +def html_body( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + output_encoding: Literal["unicode"] = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> str: ... +@overload +def html_body( + input_string: str | bytes, + source_path: StrPath | None = None, + destination_path: StrPath | None = None, + input_encoding: str = "unicode", + output_encoding: str = "unicode", + doctitle: bool = True, + initial_header_level: _HTMLHeaderLevel = 1, +) -> str | bytes: ... + +def internals( + source: str, + source_path: StrPath | None = None, + input_encoding: str = "unicode", + settings_overrides: dict[str, Incomplete] | None = None, +) -> tuple[document | None, Publisher]: ... diff --git a/stubs/docutils/docutils/frontend.pyi b/stubs/docutils/docutils/frontend.pyi new file mode 100644 index 000000000000..1a457f810419 --- /dev/null +++ b/stubs/docutils/docutils/frontend.pyi @@ -0,0 +1,202 @@ +import optparse +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Mapping, Sequence +from configparser import RawConfigParser +from typing import Any, ClassVar, Final, Literal, Protocol, overload, type_check_only +from typing_extensions import deprecated + +from docutils import SettingsSpec +from docutils.utils import DependencyList + +__docformat__: Final = "reStructuredText" + +@type_check_only +class _OptionValidator(Protocol): + def __call__( + self, + setting: str, + value: str | None, + option_parser: OptionParser, + /, + config_parser: ConfigParser | None = None, + config_section: str | None = None, + ) -> Any: ... + +@deprecated("Deprecated and will be removed with the switch to from optparse to argparse.") +def store_multiple(option: optparse.Option, opt: str, value, parser: OptionParser, *args: str, **kwargs) -> None: ... +@deprecated("Deprecated and will be removed with the switch to from optparse to argparse.") +def read_config_file(option: optparse.Option, opt: str, value, parser: OptionParser) -> None: ... +def validate_encoding( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... +def validate_encoding_error_handler( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... +def validate_encoding_and_error_handler( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... +def validate_boolean( + setting: str | bool, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> bool: ... +def validate_ternary( + setting: str | bool, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str | bool | None: ... +def validate_nonnegative_int( + setting: str | int, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> int: ... +def validate_threshold( + setting: str | int, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> int: ... +def validate_colon_separated_string_list( + setting: str | list[str], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[str]: ... +def validate_comma_separated_list( + setting: str | list[str], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[str]: ... +def validate_math_output( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> tuple[()] | tuple[str, str]: ... +def validate_url_trailing_slash( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> str: ... +def validate_dependency_file( + setting: str | None, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> DependencyList: ... +def validate_strip_class( + setting: str, + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[str]: ... +def validate_smartquotes_locales( + setting: str | list[str | tuple[str, str]], + value: str | None = None, + option_parser: OptionParser | None = None, + config_parser: ConfigParser | None = None, + config_section: str | None = None, +) -> list[tuple[str, Sequence[str]]]: ... +def make_paths_absolute( + pathdict: dict[str, list[StrPath] | StrPath], keys: tuple[str], base_path: StrPath | None = None +) -> None: ... +@deprecated("The `frontend.make_one_path_absolute` will be removed in Docutils 2.0 or later.") +def make_one_path_absolute(base_path: StrPath, path: StrPath) -> str: ... +def filter_settings_spec(settings_spec, *exclude, **replace) -> tuple[Any, ...]: ... + +@deprecated("The `frontend.Values` class will be removed in Docutils 2.0 or later.") +class Values(optparse.Values): + record_dependencies: DependencyList + def __init__(self, defaults: dict[str, Any] | None = None) -> None: ... + def update(self, other_dict: Values | Mapping[str, Incomplete], option_parser: OptionParser) -> None: ... + def copy(self) -> Values: ... + def setdefault(self, name: str, default): ... + +@deprecated("The `frontend.Option` class will be removed in Docutils 2.0 or later.") +class Option(optparse.Option): + ATTRS: list[str] + validator: _OptionValidator + overrides: str | None + def __init__(self, *args: str | None, **kwargs) -> None: ... + +@deprecated( + "The `frontend.OptionParser` class will be replaced by a subclass of `argparse.ArgumentParser` in Docutils 2.0 or later." +) +class OptionParser(optparse.OptionParser, SettingsSpec): + standard_config_files: ClassVar[list[str]] + threshold_choices: ClassVar[tuple[str, ...]] + thresholds: ClassVar[dict[str, int]] + booleans: ClassVar[dict[str, bool]] + default_error_encoding: ClassVar[str] + default_error_encoding_error_handler: ClassVar[str] + config_section: ClassVar[str] + version_template: ClassVar[str] + details: str + lists: dict[str, Literal[True]] + config_files: list[str] + relative_path_settings: ClassVar[tuple[str, ...]] + version: str + components: tuple[SettingsSpec, ...] + def __init__( + self, + components: Iterable[SettingsSpec | type[SettingsSpec]] = (), + defaults: Mapping[str, Any] | None = None, + read_config_files: bool | None = False, + *args, + **kwargs, + ) -> None: ... + def populate_from_components(self, components: Iterable[SettingsSpec]) -> None: ... + @classmethod + def get_standard_config_files(cls) -> Sequence[StrPath]: ... + def get_standard_config_settings(self) -> Values: ... + def get_config_file_settings(self, config_file: str) -> dict[str, Incomplete]: ... + def check_values(self, values: Values, args: list[str]) -> Values: ... # type: ignore[override] + def check_args(self, args: list[str]) -> tuple[str | None, str | None]: ... + def get_default_values(self) -> Values: ... + def get_option_by_dest(self, dest: str) -> Option: ... + +class ConfigParser(RawConfigParser): + old_settings: ClassVar[dict[str, tuple[str, str]]] + old_warning: ClassVar[str] + not_utf8_error: ClassVar[str] + + @overload # type: ignore[override] + def read(self, filenames: str | Sequence[str]) -> list[str]: ... + @overload + @deprecated("The `option_parser` parameter is deprecated and will be removed in Docutils 0.24.") + def read(self, filenames: str | Sequence[str], option_parser: OptionParser | None) -> list[str]: ... + + def handle_old_config(self, filename: str) -> None: ... + def validate_settings(self, filename: str, option_parser: OptionParser) -> None: ... + def optionxform(self, optionstr: str) -> str: ... + +class ConfigDeprecationWarning(FutureWarning): ... + +def get_default_settings(*components: SettingsSpec) -> Values: ... diff --git a/stubs/docutils/docutils/io.pyi b/stubs/docutils/docutils/io.pyi new file mode 100644 index 000000000000..34fad7790bb4 --- /dev/null +++ b/stubs/docutils/docutils/io.pyi @@ -0,0 +1,136 @@ +from _typeshed import ( + Incomplete, + OpenBinaryModeReading, + OpenBinaryModeWriting, + OpenTextModeReading, + OpenTextModeWriting, + SupportsWrite, + Unused, +) +from re import Pattern +from typing import IO, Any, ClassVar, Final, Generic, Literal, TextIO, TypeVar +from typing_extensions import deprecated + +from docutils import TransformSpec, nodes + +__docformat__: Final = "reStructuredText" + +class InputError(OSError): ... +class OutputError(OSError): ... + +def check_encoding(stream: TextIO, encoding: str) -> bool | None: ... +def error_string(err: BaseException) -> str: ... + +_S = TypeVar("_S") + +class Input(TransformSpec, Generic[_S]): + component_type: ClassVar[str] + default_source_path: ClassVar[str | None] + encoding: str | None + error_handler: str + source: _S | None + source_path: str | None + successful_encoding: str | None = None + def __init__( + self, + source: _S | None = None, + source_path: str | None = None, + encoding: str | None = "utf-8", + error_handler: str = "strict", + ) -> None: ... + def read(self) -> str: ... + def decode(self, data: str | bytes | bytearray) -> str: ... + coding_slug: ClassVar[Pattern[bytes]] + byte_order_marks: ClassVar[tuple[tuple[bytes, str], ...]] + @deprecated("Deprecated and will be removed in Docutils 1.0.") + def determine_encoding_from_data(self, data: str | bytes | bytearray) -> str | None: ... + def isatty(self) -> bool: ... + +class Output(TransformSpec): + component_type: ClassVar[str] + default_destination_path: ClassVar[str | None] + encoding: Incomplete + error_handler: Incomplete + destination: Incomplete + destination_path: Incomplete + def __init__( + self, destination=None, destination_path=None, encoding: str | None = None, error_handler: str = "strict" + ) -> None: ... + def write(self, data: str) -> Any: ... # returns bytes or str + def encode(self, data: str) -> Any: ... # returns bytes or str + +class ErrorOutput: + destination: Incomplete + encoding: Incomplete + encoding_errors: Incomplete + decoding_errors: Incomplete + def __init__( + self, + destination: str | SupportsWrite[str] | SupportsWrite[bytes] | Literal[False] | None = None, + encoding: str | None = None, + encoding_errors: str = "backslashreplace", + decoding_errors: str = "replace", + ) -> None: ... + def write(self, data: str | bytes | Exception) -> None: ... + def close(self) -> None: ... + def isatty(self) -> bool: ... + +class FileInput(Input[IO[str]]): + autoclose: bool + def __init__( + self, + source=None, + source_path=None, + encoding: str | None = "utf-8", + error_handler: str = "strict", + autoclose: bool = True, + mode: OpenTextModeReading | OpenBinaryModeReading = "r", + ) -> None: ... + def read(self) -> str: ... + def readlines(self) -> list[str]: ... + def close(self) -> None: ... + +class FileOutput(Output): + default_destination_path: ClassVar[str] + mode: ClassVar[OpenTextModeWriting | OpenBinaryModeWriting] + opened: bool + autoclose: Incomplete + destination: Incomplete + destination_path: Incomplete + def __init__( + self, + destination=None, + destination_path=None, + encoding=None, + error_handler: str = "strict", + autoclose: bool = True, + handle_io_errors=None, + mode=None, + ) -> None: ... + def open(self) -> None: ... + def write(self, data): ... + def close(self) -> None: ... + +@deprecated("The `BinaryFileOutput` is deprecated by `FileOutput` and will be removed in Docutils 0.24.") +class BinaryFileOutput(FileOutput): ... + +class StringInput(Input[str]): + default_source_path: ClassVar[str] + def read(self): ... + +class StringOutput(Output): + default_destination_path: ClassVar[str] + destination: str | bytes # only defined after call to write() + def write(self, data): ... + +class NullInput(Input[Any]): + default_source_path: ClassVar[str] + def read(self) -> str: ... + +class NullOutput(Output): + default_destination_path: ClassVar[str] + def write(self, data: Unused) -> None: ... + +class DocTreeInput(Input[nodes.document]): + default_source_path: ClassVar[str] + def read(self): ... diff --git a/stubs/docutils/docutils/languages/__init__.pyi b/stubs/docutils/docutils/languages/__init__.pyi new file mode 100644 index 000000000000..415e42286a17 --- /dev/null +++ b/stubs/docutils/docutils/languages/__init__.pyi @@ -0,0 +1,25 @@ +from typing import ClassVar, Final, Protocol, type_check_only +from typing_extensions import Self + +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +@type_check_only +class _LanguageModule(Protocol): + labels: dict[str, str] + author_separators: list[str] + bibliographic_fields: list[str] + +class LanguageImporter: + packages: ClassVar[tuple[str, ...]] + warn_msg: ClassVar[str] + fallback: ClassVar[str] + cache: dict[str, _LanguageModule] + def __init__(self) -> None: ... + def import_from_packages(self, name: str, reporter: Reporter | None = None) -> _LanguageModule: ... + def check_content(self, module: _LanguageModule) -> None: ... + def __call__(self, language_code: str, reporter: Reporter | None = None) -> _LanguageModule: ... + def __class_getitem__(cls, name) -> type[Self]: ... + +get_language: LanguageImporter diff --git a/stubs/docutils/docutils/languages/af.pyi b/stubs/docutils/docutils/languages/af.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/af.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ar.pyi b/stubs/docutils/docutils/languages/ar.pyi new file mode 100644 index 000000000000..ea6236c81970 --- /dev/null +++ b/stubs/docutils/docutils/languages/ar.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal["؛", "،"]] diff --git a/stubs/docutils/docutils/languages/ca.pyi b/stubs/docutils/docutils/languages/ca.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ca.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/cs.pyi b/stubs/docutils/docutils/languages/cs.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/cs.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/da.pyi b/stubs/docutils/docutils/languages/da.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/da.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/de.pyi b/stubs/docutils/docutils/languages/de.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/de.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/en.pyi b/stubs/docutils/docutils/languages/en.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/en.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/eo.pyi b/stubs/docutils/docutils/languages/eo.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/eo.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/es.pyi b/stubs/docutils/docutils/languages/es.pyi new file mode 100644 index 000000000000..67f306e26583 --- /dev/null +++ b/stubs/docutils/docutils/languages/es.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +__docformat__: str +labels: Incomplete +bibliographic_fields: Incomplete +author_separators: Incomplete diff --git a/stubs/docutils/docutils/languages/fa.pyi b/stubs/docutils/docutils/languages/fa.pyi new file mode 100644 index 000000000000..ea6236c81970 --- /dev/null +++ b/stubs/docutils/docutils/languages/fa.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal["؛", "،"]] diff --git a/stubs/docutils/docutils/languages/fi.pyi b/stubs/docutils/docutils/languages/fi.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/fi.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/fr.pyi b/stubs/docutils/docutils/languages/fr.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/fr.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/gl.pyi b/stubs/docutils/docutils/languages/gl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/gl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/he.pyi b/stubs/docutils/docutils/languages/he.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/he.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/it.pyi b/stubs/docutils/docutils/languages/it.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/it.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ja.pyi b/stubs/docutils/docutils/languages/ja.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ja.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ka.pyi b/stubs/docutils/docutils/languages/ka.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ka.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ko.pyi b/stubs/docutils/docutils/languages/ko.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ko.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/lt.pyi b/stubs/docutils/docutils/languages/lt.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/lt.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/lv.pyi b/stubs/docutils/docutils/languages/lv.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/lv.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/nl.pyi b/stubs/docutils/docutils/languages/nl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/nl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/pl.pyi b/stubs/docutils/docutils/languages/pl.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/pl.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/pt_br.pyi b/stubs/docutils/docutils/languages/pt_br.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/pt_br.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/ru.pyi b/stubs/docutils/docutils/languages/ru.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/ru.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/sk.pyi b/stubs/docutils/docutils/languages/sk.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/sk.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/sv.pyi b/stubs/docutils/docutils/languages/sv.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/sv.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/uk.pyi b/stubs/docutils/docutils/languages/uk.pyi new file mode 100644 index 000000000000..1bc1c23e214b --- /dev/null +++ b/stubs/docutils/docutils/languages/uk.pyi @@ -0,0 +1,6 @@ +from typing import Final, Literal + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[Literal[";", ","]] diff --git a/stubs/docutils/docutils/languages/zh_cn.pyi b/stubs/docutils/docutils/languages/zh_cn.pyi new file mode 100644 index 000000000000..251a17cfe865 --- /dev/null +++ b/stubs/docutils/docutils/languages/zh_cn.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[str] diff --git a/stubs/docutils/docutils/languages/zh_tw.pyi b/stubs/docutils/docutils/languages/zh_tw.pyi new file mode 100644 index 000000000000..251a17cfe865 --- /dev/null +++ b/stubs/docutils/docutils/languages/zh_tw.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +labels: dict[str, str] +bibliographic_fields: dict[str, str] +author_separators: list[str] diff --git a/stubs/docutils/docutils/nodes.pyi b/stubs/docutils/docutils/nodes.pyi new file mode 100644 index 000000000000..d40fbed7cd19 --- /dev/null +++ b/stubs/docutils/docutils/nodes.pyi @@ -0,0 +1,759 @@ +import sys +import xml.dom.minidom +from _typeshed import Incomplete +from abc import abstractmethod +from collections import Counter +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from typing import Any, ClassVar, Final, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated + +from docutils.frontend import Values +from docutils.transforms import Transform, Transformer +from docutils.utils import Reporter + +_N = TypeVar("_N", bound=Node) +_ElementLikeType: TypeAlias = type[Element | Text | Body | Bibliographic | Inline] +_ContentModelCategory: TypeAlias = _ElementLikeType | tuple[_ElementLikeType, ...] +_ContentModelQuantifier: TypeAlias = Literal[".", "?", "+", "*"] +_ContentModelItem: TypeAlias = tuple[_ContentModelCategory, _ContentModelQuantifier] +_ContentModelTuple: TypeAlias = tuple[_ContentModelItem, ...] + +@type_check_only +class _DomModule(Protocol): + Document: type[xml.dom.minidom.Document] + +__docformat__: Final = "reStructuredText" + +# Functional Node Base Classes + +class Node: + # children is initialized by the subclasses + children: Sequence[Node] + # TODO: `parent` is actually `Element | None``, but `None`` only happens rarely, + # i.e. for synthetic nodes (or `document`, where it is overridden). + # See https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#the-any-trick + parent: Element | Any + source: str | None + line: int | None + + @property + def document(self) -> _Document | None: ... + @document.setter + def document(self, value: _Document) -> None: ... + + def __bool__(self) -> Literal[True]: ... + def asdom( + self, dom: _DomModule | None = None + ) -> xml.dom.minidom.Document | xml.dom.minidom.Element | xml.dom.minidom.Text: ... + # While docutils documents the Node class to be abstract it does not + # actually use the ABCMeta metaclass. We still set @abstractmethod here + # (although it's not used in the docutils implementation) because it + # makes Mypy reject Node() with "Cannot instantiate abstract class". + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def deepcopy(self) -> Self: ... + @abstractmethod + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + @abstractmethod + def astext(self) -> str: ... + def setup_child(self, child: Node) -> None: ... + def walk(self, visitor: NodeVisitor) -> bool: ... + def walkabout(self, visitor: NodeVisitor) -> bool: ... + + @overload + def findall( + self, condition: type[_N], include_self: bool = True, descend: bool = True, siblings: bool = False, ascend: bool = False + ) -> Generator[_N]: ... + @overload + def findall( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> Generator[Node]: ... + + @overload + @deprecated("The `nodes.Node.traverse()` is deprecated. Use `Node.findall()` instead.") + def traverse( + self, condition: type[_N], include_self: bool = True, descend: bool = True, siblings: bool = False, ascend: bool = False + ) -> list[_N]: ... + @overload + @deprecated("The `nodes.Node.traverse()` is deprecated. Use `Node.findall()` instead.") + def traverse( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = True, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> list[Node]: ... + + @overload + def next_node( + self, condition: type[_N], include_self: bool = False, descend: bool = True, siblings: bool = False, ascend: bool = False + ) -> _N | None: ... + @overload + def next_node( + self, + condition: Callable[[Node], bool] | None = None, + include_self: bool = False, + descend: bool = True, + siblings: bool = False, + ascend: bool = False, + ) -> Node | None: ... + + def validate(self, recursive: bool = True) -> None: ... + def validate_position(self) -> None: ... + +# Left out +# - def ensure_str (deprecated) +# - def unescape (canonical import from docutils.utils) +def unescape(text: str, restore_backslashes: bool = False, respect_whitespace: bool = False) -> str: ... + +class Text(Node, str): + tagname: ClassVar[str] + children: tuple[()] + + # we omit the rawsource parameter because it has been deprecated and is ignored + def __new__(cls, data: str) -> Self: ... + def shortrepr(self, maxlen: int = 18) -> str: ... + def copy(self) -> Self: ... + def deepcopy(self) -> Self: ... + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + def astext(self) -> str: ... + def rstrip(self, chars: str | None = None) -> str: ... + def lstrip(self, chars: str | None = None) -> str: ... + +_T = TypeVar("_T") + +class Element(Node): + local_attributes: ClassVar[Sequence[str]] + valid_attributes: ClassVar[Sequence[str]] + common_attributes: ClassVar[Sequence[str]] + basic_attributes: ClassVar[Sequence[str]] + list_attributes: ClassVar[Sequence[str]] + known_attributes: ClassVar[Sequence[str]] + content_model: ClassVar[_ContentModelTuple] + tagname: str + child_text_separator: ClassVar[str] + attributes: dict[str, Any] + children: list[Node] + rawsource: str + def __init__(self, rawsource: str = "", *children: Node, **attributes: Any) -> None: ... + def shortrepr(self) -> str: ... + def starttag(self, quoteattr: Callable[[str], str] | None = None) -> str: ... + def endtag(self) -> str: ... + def emptytag(self) -> str: ... + def __len__(self) -> int: ... + def __contains__(self, key: str | Node) -> bool: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + @overload + def __getitem__(self, key: int) -> Node: ... + @overload + def __getitem__(self, key: slice) -> list[Node]: ... + + @overload + def __setitem__(self, key: str, item: Any) -> None: ... + @overload + def __setitem__(self, key: int, item: Node) -> None: ... + @overload + def __setitem__(self, key: slice, item: Iterable[Node]) -> None: ... + + def __delitem__(self, key: str | int | slice) -> None: ... + def __add__(self, other: list[Node]) -> list[Node]: ... + def __radd__(self, other: list[Node]) -> list[Node]: ... + def __iadd__(self, other: Node | Iterable[Node]) -> Self: ... + def astext(self) -> str: ... + def non_default_attributes(self) -> dict[str, Any]: ... + def attlist(self) -> list[tuple[str, Any]]: ... + + @overload + def get(self, key: str) -> Any: ... + @overload + def get(self, key: str, failobj: _T) -> _T: ... + + def hasattr(self, attr: str) -> bool: ... + def delattr(self, attr: str) -> None: ... + + @overload + def setdefault(self, key: str) -> Any: ... + @overload + def setdefault(self, key: str, failobj: _T) -> Any | _T: ... + + has_key = hasattr + def get_language_code(self, fallback: str = "") -> str: ... + def append(self, item: Node) -> None: ... + def extend(self, item: Iterable[Node]) -> None: ... + def insert(self, index: SupportsIndex, item: Node | Iterable[Node] | None) -> None: ... + def pop(self, i: int = -1) -> Node: ... + def remove(self, item: Node) -> None: ... + def index(self, item: Node, start: int = 0, stop: int = sys.maxsize) -> int: ... + def previous_sibling(self) -> Node | None: ... + def section_hierarchy(self) -> list[section]: ... + def is_not_default(self, key: str) -> bool: ... + def update_basic_atts(self, dict_: Mapping[str, Any] | Node) -> None: ... + def append_attr_list(self, attr: str, values: Iterable[Any]) -> None: ... + def coerce_append_attr_list(self, attr: str, value) -> None: ... + def replace_attr(self, attr: str, value: Any, force: bool = True) -> None: ... + def copy_attr_convert(self, attr: str, value: Any, replace: bool = True) -> None: ... + def copy_attr_coerce(self, attr: str, value: Any, replace: bool) -> None: ... + def copy_attr_concatenate(self, attr: str, value: Any, replace: bool) -> None: ... + def copy_attr_consistent(self, attr: str, value: Any, replace: bool) -> None: ... + def update_all_atts( + self, + dict_: Mapping[str, Any] | Node, + update_fun: Callable[[Element, str, Any, bool], object] = ..., + replace: bool = True, + and_source: bool = False, + ) -> None: ... + def update_all_atts_consistantly( + self, dict_: Mapping[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_concatenating( + self, dict_: dict[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_coercion( + self, dict_: Mapping[str, Any] | Node, replace: bool = True, and_source: bool = False + ) -> None: ... + def update_all_atts_convert(self, dict_: Mapping[str, Any] | Node, and_source: bool = False) -> None: ... + def clear(self) -> None: ... + def replace(self, old: Node, new: Node | Sequence[Node]) -> None: ... + def replace_self(self, new: Node | Sequence[Node]) -> None: ... + def first_child_matching_class( + self, childclass: type[Node] | tuple[type[Node], ...], start: int = 0, end: int = sys.maxsize + ) -> int | None: ... + def first_child_not_matching_class( + self, childclass: type[Node] | tuple[type[Node], ...], start: int = 0, end: int = sys.maxsize + ) -> int | None: ... + def pformat(self, indent: str = " ", level: int = 0) -> str: ... + def copy(self) -> Self: ... + def deepcopy(self) -> Self: ... + def note_referenced_by(self, name: str | None = None, id: str | None = None) -> None: ... + @classmethod + def is_not_list_attribute(cls, attr: str) -> bool: ... + @classmethod + def is_not_known_attribute(cls, attr: str) -> bool: ... + def validate_attributes(self) -> None: ... + def validate_content( + self, model: _ContentModelTuple | None = None, elements: Sequence[Incomplete] | None = None + ) -> list[Incomplete]: ... + + # '__iter__' is added as workaround, since mypy doesn't support classes that are iterable via '__getitem__' + # see https://github.com/python/typeshed/pull/10099#issuecomment-1528789395 + def __iter__(self) -> Iterator[Node]: ... + +class TextElement(Element): + def __init__(self, rawsource: str = "", text: str = "", *children: Node, **attributes) -> None: ... + +class FixedTextElement(TextElement): ... +class PureTextElement(TextElement): ... + +# Mixins + +class Resolvable: + resolved: int + +class BackLinkable: + list_attributes: ClassVar[Sequence[str]] + valid_attributes: ClassVar[Sequence[str]] + def add_backref(self, refid: str) -> None: ... + +# Element Categories + +class Root: ... +class Titular: ... +class PreBibliographic: ... +class Bibliographic: ... + +class Decorative(PreBibliographic): + content_model: ClassVar[_ContentModelTuple] + +class Structural: ... +class SubStructural: ... +class Body: ... +class General(Body): ... +class Sequential(Body): ... + +class Admonition(Body): + content_model: ClassVar[_ContentModelTuple] + +class Special(Body): ... +class Invisible(PreBibliographic): ... +class Part: ... +class Inline: ... +class Referential(Resolvable): ... + +class Targetable(Resolvable): + referenced: int + indirect_reference_name: str | None + +class Labeled: ... + +# Root Element + +_Document: TypeAlias = document +_Decoration: TypeAlias = decoration + +class document(Root, Structural, Element): + current_source: str | None + current_line: int | None + settings: Values + reporter: Reporter + indirect_targets: list[target] + substitution_defs: dict[str, substitution_definition] + substitution_names: dict[str, str] + refnames: dict[str, list[Element]] + refids: dict[str, list[Element]] + nameids: dict[str, str] + nametypes: dict[str, bool] + ids: dict[str, Element] + footnote_refs: dict[str, list[footnote_reference]] + citation_refs: dict[str, list[citation_reference]] + autofootnotes: list[footnote] + autofootnote_refs: list[footnote_reference] + symbol_footnotes: list[footnote] + symbol_footnote_refs: list[footnote_reference] + footnotes: list[footnote] + citations: list[citation] + autofootnote_start: int + symbol_footnote_start: int + id_counter: Counter[int] + parse_messages: list[system_message] + transform_messages: list[system_message] + transformer: Transformer + decoration: decoration | None + document: Self + def __init__(self, settings: Values, reporter: Reporter, *args: Node, **kwargs: Any) -> None: ... + def asdom(self, dom: Any | None = None) -> Any: ... + def set_id(self, node: Element, msgnode: Element | None = None, suggested_prefix: str = "") -> str: ... + def set_name_id_map(self, node: Element, id: str, msgnode: Element | None = None, explicit: bool = False) -> None: ... + def set_duplicate_name_id(self, node: Element, id: str, name: str, msgnode: Element, explicit: bool) -> None: ... + def has_name(self, name: str) -> bool: ... + def note_implicit_target(self, target: Element, msgnode: Element | None = None) -> None: ... + def note_explicit_target(self, target: Element, msgnode: Element | None = None) -> None: ... + def note_refname(self, node: Element) -> None: ... + def note_refid(self, node: Element) -> None: ... + def note_indirect_target(self, target: target) -> None: ... + def note_anonymous_target(self, target: target) -> None: ... + def note_autofootnote(self, footnote: footnote) -> None: ... + def note_autofootnote_ref(self, ref: footnote_reference) -> None: ... + def note_symbol_footnote(self, footnote: footnote) -> None: ... + def note_symbol_footnote_ref(self, ref: footnote_reference) -> None: ... + def note_footnote(self, footnote: footnote) -> None: ... + def note_footnote_ref(self, ref: footnote_reference) -> None: ... + def note_citation(self, citation: citation) -> None: ... + def note_citation_ref(self, ref: citation_reference) -> None: ... + def note_substitution_def(self, subdef: substitution_definition, def_name: str, msgnode: Element | None = None) -> None: ... + def note_substitution_ref(self, subref: substitution_reference, refname: str) -> None: ... + def note_pending(self, pending: pending, priority: int | None = None) -> None: ... + def note_parse_message(self, message: system_message) -> None: ... + def note_transform_message(self, message: system_message) -> None: ... + def note_source(self, source: str, offset: int) -> None: ... + def copy(self) -> Self: ... + def get_decoration(self) -> _Decoration: ... + +# Title Elements + +class title(Titular, PreBibliographic, TextElement): ... +class subtitle(Titular, PreBibliographic, TextElement): ... +class rubric(Titular, TextElement): ... + +# Meta-Data Element + +class meta(PreBibliographic, Element): ... + +# Bibliographic Elements + +class docinfo(Bibliographic, Element): ... +class author(Bibliographic, TextElement): ... +class authors(Bibliographic, Element): ... +class organization(Bibliographic, TextElement): ... +class address(Bibliographic, FixedTextElement): ... +class contact(Bibliographic, TextElement): ... +class version(Bibliographic, TextElement): ... +class revision(Bibliographic, TextElement): ... +class status(Bibliographic, TextElement): ... +class date(Bibliographic, TextElement): ... +class copyright(Bibliographic, TextElement): ... + +# Decorative Elements + +class decoration(Decorative, Element): + def get_header(self) -> header: ... + def get_footer(self) -> footer: ... + +class header(Decorative, Element): ... +class footer(Decorative, Element): ... + +# Structural Elements + +class section(Structural, Element): ... +class topic(Structural, Element): ... +class sidebar(Structural, Element): ... +class transition(Structural, Element): ... + +# Body Elements +# =============== + +class paragraph(General, TextElement): ... +class compound(General, Element): ... +class container(General, Element): ... +class bullet_list(Sequential, Element): ... +class enumerated_list(Sequential, Element): ... +class list_item(Part, Element): ... +class definition_list(Sequential, Element): ... +class definition_list_item(Part, Element): ... +class term(Part, TextElement): ... +class classifier(Part, TextElement): ... +class definition(Part, Element): ... +class field_list(Sequential, Element): ... +class field(Part, Element): ... +class field_name(Part, TextElement): ... +class field_body(Part, Element): ... +class option(Part, Element): ... +class option_argument(Part, TextElement): ... +class option_group(Part, Element): ... +class option_list(Sequential, Element): ... +class option_list_item(Part, Element): ... +class option_string(Part, TextElement): ... +class description(Part, Element): ... +class literal_block(General, FixedTextElement): ... +class doctest_block(General, FixedTextElement): ... +class math_block(General, FixedTextElement): ... +class line_block(General, Element): ... + +class line(Part, TextElement): + indent: str | None + +class block_quote(General, Element): ... +class attribution(Part, TextElement): ... +class attention(Admonition, Element): ... +class caution(Admonition, Element): ... +class danger(Admonition, Element): ... +class error(Admonition, Element): ... +class important(Admonition, Element): ... +class note(Admonition, Element): ... +class tip(Admonition, Element): ... +class hint(Admonition, Element): ... +class warning(Admonition, Element): ... +class admonition(Admonition, Element): ... +class comment(Special, Invisible, FixedTextElement): ... +class substitution_definition(Special, Invisible, TextElement): ... +class target(Special, Invisible, Inline, TextElement, Targetable): ... +class footnote(General, BackLinkable, Element, Labeled, Targetable): ... +class citation(General, BackLinkable, Element, Labeled, Targetable): ... +class label(Part, TextElement): ... +class figure(General, Element): ... +class caption(Part, TextElement): ... +class legend(Part, Element): ... +class table(General, Element): ... +class tgroup(Part, Element): ... + +class colspec(Part, Element): + def propwidth(self) -> float: ... + +class thead(Part, Element): ... +class tbody(Part, Element): ... +class row(Part, Element): ... +class entry(Part, Element): ... + +class system_message(Special, BackLinkable, PreBibliographic, Element): + def __init__(self, message: str | None = None, *children: Node, **attributes) -> None: ... + def astext(self) -> str: ... + +class pending(Special, Invisible, Element): + transform: type[Transform] + details: Mapping[str, Any] + def __init__( + self, + transform: type[Transform], + details: Mapping[str, Any] | None = None, + rawsource: str = "", + *children: Node, + **attributes, + ) -> None: ... + +class raw(Special, Inline, PreBibliographic, FixedTextElement): ... + +# Inline Elements + +class emphasis(Inline, TextElement): ... +class strong(Inline, TextElement): ... +class literal(Inline, TextElement): ... +class reference(General, Inline, Referential, TextElement): ... +class footnote_reference(Inline, Referential, TextElement): ... +class citation_reference(Inline, Referential, TextElement): ... +class substitution_reference(Inline, TextElement): ... +class title_reference(Inline, TextElement): ... +class abbreviation(Inline, TextElement): ... +class acronym(Inline, TextElement): ... +class superscript(Inline, TextElement): ... +class subscript(Inline, TextElement): ... +class math(Inline, TextElement): ... +class image(General, Inline, Element): ... +class inline(Inline, TextElement): ... +class problematic(Inline, TextElement): ... +class generated(Inline, TextElement): ... + +# Auxiliary Classes, Functions, and Data + +node_class_names: list[str] + +class NodeVisitor: + optional: ClassVar[tuple[str, ...]] + document: _Document + def __init__(self, document: _Document) -> None: ... + def dispatch_visit(self, node: Node) -> Any: ... + def dispatch_departure(self, node: Node) -> Any: ... + def unknown_visit(self, node: Node) -> Any: ... + def unknown_departure(self, node: Node) -> Any: ... + + # These methods only exist on the subclasses `GenericNodeVisitor` and `SparseNodeVisitor` at runtime. + # If subclassing `NodeVisitor` directly, `visit_*` methods must be implemented for nodes and children that will be called + # with `Node.walk()` and `Node.walkabout()`. + # `depart_*` methods must also be implemented for nodes and children that will be called with `Node.walkabout()`. + def visit_Text(self, node: Text) -> Any: ... + def visit_abbreviation(self, node: abbreviation) -> Any: ... + def visit_acronym(self, node: acronym) -> Any: ... + def visit_address(self, node: address) -> Any: ... + def visit_admonition(self, node: admonition) -> Any: ... + def visit_attention(self, node: attention) -> Any: ... + def visit_attribution(self, node: attribution) -> Any: ... + def visit_author(self, node: author) -> Any: ... + def visit_authors(self, node: authors) -> Any: ... + def visit_block_quote(self, node: block_quote) -> Any: ... + def visit_bullet_list(self, node: bullet_list) -> Any: ... + def visit_caption(self, node: caption) -> Any: ... + def visit_caution(self, node: caution) -> Any: ... + def visit_citation(self, node: citation) -> Any: ... + def visit_citation_reference(self, node: citation_reference) -> Any: ... + def visit_classifier(self, node: classifier) -> Any: ... + def visit_colspec(self, node: colspec) -> Any: ... + def visit_comment(self, node: comment) -> Any: ... + def visit_compound(self, node: compound) -> Any: ... + def visit_contact(self, node: contact) -> Any: ... + def visit_container(self, node: container) -> Any: ... + def visit_copyright(self, node: copyright) -> Any: ... + def visit_danger(self, node: danger) -> Any: ... + def visit_date(self, node: date) -> Any: ... + def visit_decoration(self, node: decoration) -> Any: ... + def visit_definition(self, node: definition) -> Any: ... + def visit_definition_list(self, node: definition_list) -> Any: ... + def visit_definition_list_item(self, node: definition_list_item) -> Any: ... + def visit_description(self, node: description) -> Any: ... + def visit_docinfo(self, node: docinfo) -> Any: ... + def visit_doctest_block(self, node: doctest_block) -> Any: ... + def visit_document(self, node: _Document) -> Any: ... + def visit_emphasis(self, node: emphasis) -> Any: ... + def visit_entry(self, node: entry) -> Any: ... + def visit_enumerated_list(self, node: enumerated_list) -> Any: ... + def visit_error(self, node: error) -> Any: ... + def visit_field(self, node: field) -> Any: ... + def visit_field_body(self, node: field_body) -> Any: ... + def visit_field_list(self, node: field_list) -> Any: ... + def visit_field_name(self, node: field_name) -> Any: ... + def visit_figure(self, node: figure) -> Any: ... + def visit_footer(self, node: footer) -> Any: ... + def visit_footnote(self, node: footnote) -> Any: ... + def visit_footnote_reference(self, node: footnote_reference) -> Any: ... + def visit_generated(self, node: generated) -> Any: ... + def visit_header(self, node: header) -> Any: ... + def visit_hint(self, node: hint) -> Any: ... + def visit_image(self, node: image) -> Any: ... + def visit_important(self, node: important) -> Any: ... + def visit_inline(self, node: inline) -> Any: ... + def visit_label(self, node: label) -> Any: ... + def visit_legend(self, node: legend) -> Any: ... + def visit_line(self, node: line) -> Any: ... + def visit_line_block(self, node: line_block) -> Any: ... + def visit_list_item(self, node: list_item) -> Any: ... + def visit_literal(self, node: literal) -> Any: ... + def visit_literal_block(self, node: literal_block) -> Any: ... + def visit_math(self, node: math) -> Any: ... + def visit_math_block(self, node: math_block) -> Any: ... + def visit_meta(self, node: meta) -> Any: ... + def visit_note(self, node: note) -> Any: ... + def visit_option(self, node: option) -> Any: ... + def visit_option_argument(self, node: option_argument) -> Any: ... + def visit_option_group(self, node: option_group) -> Any: ... + def visit_option_list(self, node: option_list) -> Any: ... + def visit_option_list_item(self, node: option_list_item) -> Any: ... + def visit_option_string(self, node: option_string) -> Any: ... + def visit_organization(self, node: organization) -> Any: ... + def visit_paragraph(self, node: paragraph) -> Any: ... + def visit_pending(self, node: pending) -> Any: ... + def visit_problematic(self, node: problematic) -> Any: ... + def visit_raw(self, node: raw) -> Any: ... + def visit_reference(self, node: reference) -> Any: ... + def visit_revision(self, node: revision) -> Any: ... + def visit_row(self, node: row) -> Any: ... + def visit_rubric(self, node: rubric) -> Any: ... + def visit_section(self, node: section) -> Any: ... + def visit_sidebar(self, node: sidebar) -> Any: ... + def visit_status(self, node: status) -> Any: ... + def visit_strong(self, node: strong) -> Any: ... + def visit_subscript(self, node: subscript) -> Any: ... + def visit_substitution_definition(self, node: substitution_definition) -> Any: ... + def visit_substitution_reference(self, node: substitution_reference) -> Any: ... + def visit_subtitle(self, node: subtitle) -> Any: ... + def visit_superscript(self, node: superscript) -> Any: ... + def visit_system_message(self, node: system_message) -> Any: ... + def visit_table(self, node: table) -> Any: ... + def visit_target(self, node: target) -> Any: ... + def visit_tbody(self, node: tbody) -> Any: ... + def visit_term(self, node: term) -> Any: ... + def visit_tgroup(self, node: tgroup) -> Any: ... + def visit_thead(self, node: thead) -> Any: ... + def visit_tip(self, node: tip) -> Any: ... + def visit_title(self, node: title) -> Any: ... + def visit_title_reference(self, node: title_reference) -> Any: ... + def visit_topic(self, node: topic) -> Any: ... + def visit_transition(self, node: transition) -> Any: ... + def visit_version(self, node: version) -> Any: ... + def visit_warning(self, node: warning) -> Any: ... + def depart_Text(self, node: Text) -> Any: ... + def depart_abbreviation(self, node: abbreviation) -> Any: ... + def depart_acronym(self, node: acronym) -> Any: ... + def depart_address(self, node: address) -> Any: ... + def depart_admonition(self, node: admonition) -> Any: ... + def depart_attention(self, node: attention) -> Any: ... + def depart_attribution(self, node: attribution) -> Any: ... + def depart_author(self, node: author) -> Any: ... + def depart_authors(self, node: authors) -> Any: ... + def depart_block_quote(self, node: block_quote) -> Any: ... + def depart_bullet_list(self, node: bullet_list) -> Any: ... + def depart_caption(self, node: caption) -> Any: ... + def depart_caution(self, node: caution) -> Any: ... + def depart_citation(self, node: citation) -> Any: ... + def depart_citation_reference(self, node: citation_reference) -> Any: ... + def depart_classifier(self, node: classifier) -> Any: ... + def depart_colspec(self, node: colspec) -> Any: ... + def depart_comment(self, node: comment) -> Any: ... + def depart_compound(self, node: compound) -> Any: ... + def depart_contact(self, node: contact) -> Any: ... + def depart_container(self, node: container) -> Any: ... + def depart_copyright(self, node: copyright) -> Any: ... + def depart_danger(self, node: danger) -> Any: ... + def depart_date(self, node: date) -> Any: ... + def depart_decoration(self, node: decoration) -> Any: ... + def depart_definition(self, node: definition) -> Any: ... + def depart_definition_list(self, node: definition_list) -> Any: ... + def depart_definition_list_item(self, node: definition_list_item) -> Any: ... + def depart_description(self, node: description) -> Any: ... + def depart_docinfo(self, node: docinfo) -> Any: ... + def depart_doctest_block(self, node: doctest_block) -> Any: ... + def depart_document(self, node: _Document) -> Any: ... + def depart_emphasis(self, node: emphasis) -> Any: ... + def depart_entry(self, node: entry) -> Any: ... + def depart_enumerated_list(self, node: enumerated_list) -> Any: ... + def depart_error(self, node: error) -> Any: ... + def depart_field(self, node: field) -> Any: ... + def depart_field_body(self, node: field_body) -> Any: ... + def depart_field_list(self, node: field_list) -> Any: ... + def depart_field_name(self, node: field_name) -> Any: ... + def depart_figure(self, node: figure) -> Any: ... + def depart_footer(self, node: footer) -> Any: ... + def depart_footnote(self, node: footnote) -> Any: ... + def depart_footnote_reference(self, node: footnote_reference) -> Any: ... + def depart_generated(self, node: generated) -> Any: ... + def depart_header(self, node: header) -> Any: ... + def depart_hint(self, node: hint) -> Any: ... + def depart_image(self, node: image) -> Any: ... + def depart_important(self, node: important) -> Any: ... + def depart_inline(self, node: inline) -> Any: ... + def depart_label(self, node: label) -> Any: ... + def depart_legend(self, node: legend) -> Any: ... + def depart_line(self, node: line) -> Any: ... + def depart_line_block(self, node: line_block) -> Any: ... + def depart_list_item(self, node: list_item) -> Any: ... + def depart_literal(self, node: literal) -> Any: ... + def depart_literal_block(self, node: literal_block) -> Any: ... + def depart_math(self, node: math) -> Any: ... + def depart_math_block(self, node: math_block) -> Any: ... + def depart_meta(self, node: meta) -> Any: ... + def depart_note(self, node: note) -> Any: ... + def depart_option(self, node: option) -> Any: ... + def depart_option_argument(self, node: option_argument) -> Any: ... + def depart_option_group(self, node: option_group) -> Any: ... + def depart_option_list(self, node: option_list) -> Any: ... + def depart_option_list_item(self, node: option_list_item) -> Any: ... + def depart_option_string(self, node: option_string) -> Any: ... + def depart_organization(self, node: organization) -> Any: ... + def depart_paragraph(self, node: paragraph) -> Any: ... + def depart_pending(self, node: pending) -> Any: ... + def depart_problematic(self, node: problematic) -> Any: ... + def depart_raw(self, node: raw) -> Any: ... + def depart_reference(self, node: reference) -> Any: ... + def depart_revision(self, node: revision) -> Any: ... + def depart_row(self, node: row) -> Any: ... + def depart_rubric(self, node: rubric) -> Any: ... + def depart_section(self, node: section) -> Any: ... + def depart_sidebar(self, node: sidebar) -> Any: ... + def depart_status(self, node: status) -> Any: ... + def depart_strong(self, node: strong) -> Any: ... + def depart_subscript(self, node: subscript) -> Any: ... + def depart_substitution_definition(self, node: substitution_definition) -> Any: ... + def depart_substitution_reference(self, node: substitution_reference) -> Any: ... + def depart_subtitle(self, node: subtitle) -> Any: ... + def depart_superscript(self, node: superscript) -> Any: ... + def depart_system_message(self, node: system_message) -> Any: ... + def depart_table(self, node: table) -> Any: ... + def depart_target(self, node: target) -> Any: ... + def depart_tbody(self, node: tbody) -> Any: ... + def depart_term(self, node: term) -> Any: ... + def depart_tgroup(self, node: tgroup) -> Any: ... + def depart_thead(self, node: thead) -> Any: ... + def depart_tip(self, node: tip) -> Any: ... + def depart_title(self, node: title) -> Any: ... + def depart_title_reference(self, node: title_reference) -> Any: ... + def depart_topic(self, node: topic) -> Any: ... + def depart_transition(self, node: transition) -> Any: ... + def depart_version(self, node: version) -> Any: ... + def depart_warning(self, node: warning) -> Any: ... + +class SparseNodeVisitor(NodeVisitor): ... + +class GenericNodeVisitor(NodeVisitor): + def default_visit(self, node: Node) -> None: ... + def default_departure(self, node: Node) -> None: ... + +class TreeCopyVisitor(GenericNodeVisitor): + parent_stack: list[Node] + parent: list[Node] + def get_tree_copy(self) -> Node: ... + +class ValidationError(ValueError): + def __init__(self, msg: str, problematic_element: Element | None = None) -> None: ... + +class TreePruningException(Exception): ... +class SkipChildren(TreePruningException): ... +class SkipSiblings(TreePruningException): ... +class SkipNode(TreePruningException): ... +class SkipDeparture(TreePruningException): ... +class NodeFound(TreePruningException): ... +class StopTraversal(TreePruningException): ... + +def make_id(string: str) -> str: ... +def dupname(node: Node, name: str) -> None: ... +def fully_normalize_name(name: str) -> str: ... +def whitespace_normalize_name(name: str) -> str: ... +def serial_escape(value: str) -> str: ... +def split_name_list(s: str) -> list[str]: ... +def pseudo_quoteattr(value: str) -> str: ... +def parse_measure(measure: str, unit_pattern: str = "[a-zA-Zµ]*|%?") -> tuple[float, str]: ... +def create_keyword_validator(*keywords: str) -> Callable[[str], str]: ... +def validate_identifier(value: str) -> str: ... +def validate_identifier_list(value: str | list[str]) -> list[str]: ... +def validate_measure(measure: str) -> str: ... +def validate_colwidth(measure: str | float) -> float: ... +def validate_NMTOKEN(value: str) -> str: ... +def validate_NMTOKENS(value: str | list[str]) -> list[str]: ... +def validate_refname_list(value: str | list[str]) -> list[str]: ... +def validate_yesorno(value: str | int | bool) -> bool: ... + +ATTRIBUTE_VALIDATORS: dict[str, Callable[[str], Any]] diff --git a/stubs/docutils/docutils/parsers/__init__.pyi b/stubs/docutils/docutils/parsers/__init__.pyi new file mode 100644 index 000000000000..d15966c81088 --- /dev/null +++ b/stubs/docutils/docutils/parsers/__init__.pyi @@ -0,0 +1,19 @@ +from typing import ClassVar, Final + +from docutils import Component +from docutils.nodes import _Document + +__docformat__: Final = "reStructuredText" + +class Parser(Component): + component_type: ClassVar[str] + config_section: ClassVar[str] + inputstring: str # defined after call to setup_parse() + document: _Document # defined after call to setup_parse() + def parse(self, inputstring: str, document: _Document) -> None: ... + def setup_parse(self, inputstring: str, document: _Document) -> None: ... + def finish_parse(self) -> None: ... + +PARSER_ALIASES: Final[dict[str, str]] + +def get_parser_class(parser_name: str) -> type[Parser]: ... diff --git a/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi b/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi new file mode 100644 index 000000000000..a9b7a2c2956e --- /dev/null +++ b/stubs/docutils/docutils/parsers/commonmark_wrapper.pyi @@ -0,0 +1,9 @@ +from typing import Literal, TypeAlias + +from docutils import parsers + +_ParserName: TypeAlias = Literal["pycmark", "myst", "recommonmark"] + +commonmark_parser_names: tuple[_ParserName, ...] +Parser: type[parsers.Parser] # if Parser is None or parser_name is empty string, user cannot import current module +parser_name: _ParserName diff --git a/stubs/docutils/docutils/parsers/docutils_xml.pyi b/stubs/docutils/docutils/parsers/docutils_xml.pyi new file mode 100644 index 000000000000..d8351b0c7ea8 --- /dev/null +++ b/stubs/docutils/docutils/parsers/docutils_xml.pyi @@ -0,0 +1,16 @@ +import xml.etree.ElementTree as ET +from typing import ClassVar, Final + +from docutils import nodes, parsers + +__docformat__: Final = "reStructuredText" + +class Parser(parsers.Parser): + config_section_dependencies: ClassVar[tuple[str, ...]] + settings_default_overrides: ClassVar[dict[str, bool]] + +class Unknown(nodes.Special, nodes.Inline, nodes.Element): ... + +def parse_element(inputstring: str, document: nodes.document | None = None) -> nodes.Element: ... +def element2node(element: ET.Element | None, document: nodes.document | None = None, unindent: bool = True) -> nodes.Element: ... +def append_text(node: nodes.Element, text: str | None, unindent: bool | None) -> None: ... diff --git a/stubs/docutils/docutils/parsers/null.pyi b/stubs/docutils/docutils/parsers/null.pyi new file mode 100644 index 000000000000..ff81ca28c7fd --- /dev/null +++ b/stubs/docutils/docutils/parsers/null.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils import parsers + +__docformat__: Final = "reStructuredText" + +class Parser(parsers.Parser): + supported: ClassVar[tuple[str, ...]] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi b/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi new file mode 100644 index 000000000000..3f12ce9e59f7 --- /dev/null +++ b/stubs/docutils/docutils/parsers/recommonmark_wrapper.pyi @@ -0,0 +1,55 @@ +from types import ModuleType +from typing import ClassVar +from typing_extensions import deprecated + +from docutils import nodes +from docutils.transforms import Transform + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class pending_xref(nodes.Inline, nodes.Element): ... + +sphinx: ModuleType + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +def is_literal(node: nodes.Node) -> bool: ... + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class _CommonMarkParser: + default_config: ClassVar[dict[str, None]] + def __init__(self) -> None: ... + def convert_ast(self, ast): ... + def default_visit(self, mdnode): ... + def default_depart(self, mdnode): ... + def visit_heading(self, mdnode): ... + def depart_heading(self, _): ... + def visit_text(self, mdnode): ... + def visit_softbreak(self, _): ... + def visit_linebreak(self, _): ... + def visit_paragraph(self, mdnode): ... + def visit_emph(self, _): ... + def visit_strong(self, _): ... + def visit_code(self, mdnode): ... + def visit_link(self, mdnode): ... + def depart_link(self, mdnode): ... + def visit_image(self, mdnode): ... + def visit_list(self, mdnode): ... + def visit_item(self, mdnode): ... + def visit_code_block(self, mdnode): ... + def visit_block_quote(self, mdnode): ... + def visit_html(self, mdnode): ... + def visit_html_inline(self, mdnode): ... + def visit_html_block(self, mdnode): ... + def visit_thematic_break(self, _): ... + def setup_sections(self): ... + def add_section(self, section, level): ... + def is_section_level(self, level, section): ... + +@deprecated("The `recommonmark` package is unmaintained and deprecated; will be removed in Docutils 1.0.") +class Parser(_CommonMarkParser): + supported: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + def get_transforms(self) -> list[type[Transform]]: ... + def parse(self, inputstring: str, document: nodes.document) -> None: ... + def visit_document(self, node) -> None: ... + def visit_text(self, mdnode) -> None: ... diff --git a/stubs/docutils/docutils/parsers/rst/__init__.pyi b/stubs/docutils/docutils/parsers/rst/__init__.pyi new file mode 100644 index 000000000000..2ec7af62d1e1 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/__init__.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import Any, ClassVar, Final, Literal, TypeAlias + +from docutils import nodes, parsers +from docutils.parsers.rst.states import Inliner, RSTState, RSTStateMachine +from docutils.statemachine import StringList +from docutils.transforms import Transform +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +class Parser(parsers.Parser): + config_section_dependencies: ClassVar[tuple[str, ...]] + initial_state: Literal["Body", "RFC2822Body"] + state_classes: Sequence[type[RSTState]] + inliner: Inliner | None + statemachine: RSTStateMachine + def __init__(self, rfc2822: bool = False, inliner: Inliner | None = None) -> None: ... + def get_transforms(self) -> list[type[Transform]]: ... + def parse(self, inputstring: str, document: nodes.document) -> None: ... + +class DirectiveError(Exception): + level: int + msg: str + def __init__(self, level: int, message: str) -> None: ... + +class Directive: + required_arguments: ClassVar[int] + optional_arguments: ClassVar[int] + final_argument_whitespace: ClassVar[bool] + option_spec: ClassVar[dict[str, Callable[[str], Incomplete]] | None] + has_content: ClassVar[bool] + name: str + arguments: list[str] + options: dict[str, Incomplete] + content: StringList + lineno: int + content_offset: int + block_text: str + state: RSTState + state_machine: RSTStateMachine = ... + reporter: Reporter + def __init__( + self, + name: str, + arguments: list[str], + options: dict[str, Incomplete], + content: StringList, + lineno: int, + content_offset: int, + block_text: str, + state: RSTState, + state_machine: RSTStateMachine, + ) -> None: ... + def run(self) -> Sequence[nodes.Node]: ... + def directive_error(self, level: int, message: str) -> DirectiveError: ... + def debug(self, message: str) -> DirectiveError: ... + def info(self, message: str) -> DirectiveError: ... + def warning(self, message: str) -> DirectiveError: ... + def error(self, message: str) -> DirectiveError: ... + def severe(self, message: str) -> DirectiveError: ... + def assert_has_content(self) -> None: ... + def add_name(self, node: nodes.Node) -> None: ... + +_DirectiveFn: TypeAlias = Callable[ + [str, list[str], dict[str, Any], StringList, int, int, str, RSTState, RSTStateMachine], Directive +] + +def convert_directive_function(directive_fn: _DirectiveFn) -> type[Directive]: ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi b/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi new file mode 100644 index 000000000000..501bb87ddaf9 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/__init__.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable, Container, Iterable, Sequence +from re import Pattern +from typing import Final, Literal + +from docutils.languages import _LanguageModule +from docutils.nodes import document, system_message +from docutils.parsers import Parser +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +def register_directive(name: str, directive: type[Directive]) -> None: ... +def directive( + directive_name: str, language_module: _LanguageModule, document: document +) -> tuple[type[Directive] | None, list[system_message]]: ... +def flag(argument: str | None) -> None: ... +def unchanged_required(argument: str) -> str: ... +def unchanged(argument: str | None) -> str: ... +def path(argument: str) -> str: ... +def uri(argument: str) -> str: ... +def nonnegative_int(argument: str) -> int: ... +def percentage(argument: str) -> int: ... + +CSS3_LENGTH_UNITS: Final[tuple[str, ...]] +length_units: Final[list[str]] + +def get_measure(argument: str, units: Iterable[str]) -> str: ... +def length_or_unitless(argument: str) -> str: ... +def length_or_percentage_or_unitless(argument: str, default: str = "") -> str: ... +def class_option(argument: str) -> list[str]: ... + +unicode_pattern: Final[Pattern[str]] + +def unicode_code(code: str) -> str: ... +def single_char_or_unicode(argument: str) -> str: ... +def single_char_or_whitespace_or_unicode(argument: str | Literal["tab", "space"]) -> str: ... # noqa: Y051 +def positive_int(argument: str) -> int: ... +def positive_int_list(argument: str) -> list[int]: ... +def encoding(argument: str) -> str: ... +def choice(argument: str, values: Sequence[str]) -> str: ... +def format_values(values: Sequence[object]) -> str: ... +def value_or(values: Container[str], other: Callable[[str], str]) -> Callable[[str], str]: ... +def parser_name(argument: str | None) -> type[Parser] | None: ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi b/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi new file mode 100644 index 000000000000..58c4e5debc63 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/admonitions.pyi @@ -0,0 +1,39 @@ +from typing import Final + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class BaseAdmonition(Directive): + node_class: type[nodes.Admonition] # Subclasses must set this to the appropriate admonition node class. + +class Admonition(BaseAdmonition): + node_class: type[nodes.admonition] + +class Attention(BaseAdmonition): + node_class: type[nodes.attention] + +class Caution(BaseAdmonition): + node_class: type[nodes.caution] + +class Danger(BaseAdmonition): + node_class: type[nodes.danger] + +class Error(BaseAdmonition): + node_class: type[nodes.error] + +class Hint(BaseAdmonition): + node_class: type[nodes.hint] + +class Important(BaseAdmonition): + node_class: type[nodes.important] + +class Note(BaseAdmonition): + node_class: type[nodes.note] + +class Tip(BaseAdmonition): + node_class: type[nodes.tip] + +class Warning(BaseAdmonition): + node_class: type[nodes.warning] diff --git a/stubs/docutils/docutils/parsers/rst/directives/body.pyi b/stubs/docutils/docutils/parsers/rst/directives/body.pyi new file mode 100644 index 000000000000..345309e71599 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/body.pyi @@ -0,0 +1,73 @@ +from collections.abc import Callable +from typing import ClassVar, Final, TypeAlias + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +_DirectiveFn: TypeAlias = Callable[[str], str | list[str]] + +class BasePseudoSection(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + node_class: ClassVar[type[nodes.Node] | None] + invalid_parents: ClassVar[ + tuple[ + type[nodes.SubStructural], + type[nodes.Bibliographic], + type[nodes.Decorative], + type[nodes.Body], + type[nodes.Part], + type[nodes.topic], + ] + ] + def run(self): ... + +class Topic(BasePseudoSection): + node_class: ClassVar[type[nodes.Node]] + +class Sidebar(BasePseudoSection): + node_class: ClassVar[type[nodes.Node]] + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class LineBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class ParsedLiteral(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class CodeBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class MathBlock(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class Rubric(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class BlockQuote(Directive): + classes: ClassVar[list[str]] + def run(self): ... + +class Epigraph(BlockQuote): + classes: ClassVar[list[str]] + +class Highlights(BlockQuote): + classes: ClassVar[list[str]] + +class PullQuote(BlockQuote): + classes: ClassVar[list[str]] + +class Compound(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... + +class Container(Directive): + option_spec: ClassVar[dict[str, _DirectiveFn]] + def run(self): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/html.pyi b/stubs/docutils/docutils/parsers/rst/directives/html.pyi new file mode 100644 index 000000000000..d4dc9ba85ed5 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/html.pyi @@ -0,0 +1,5 @@ +from typing import Final + +from docutils.parsers.rst.directives.misc import Meta as Meta, MetaBody as MetaBody + +__docformat__: Final = "reStructuredText" diff --git a/stubs/docutils/docutils/parsers/rst/directives/images.pyi b/stubs/docutils/docutils/parsers/rst/directives/images.pyi new file mode 100644 index 000000000000..cd9654c65b4c --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/images.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class Image(Directive): + align_h_values: Incomplete + align_v_values: Incomplete + align_values: Incomplete + loading_values: Incomplete + def align(argument): ... + def loading(argument): ... + +class Figure(Image): + def align(argument): ... + def figwidth_value(argument): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/misc.pyi b/stubs/docutils/docutils/parsers/rst/directives/misc.pyi new file mode 100644 index 000000000000..46b89b555d45 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/misc.pyi @@ -0,0 +1,46 @@ +from _typeshed import StrPath +from pathlib import Path +from re import Match, Pattern +from typing import ClassVar, Final + +from docutils import nodes +from docutils.parsers.rst import Directive +from docutils.parsers.rst.states import SpecializedBody + +__docformat__: Final = "reStructuredText" + +def adapt_path(path: str, source: StrPath = "", root_prefix: StrPath = "") -> str: ... + +class Include(Directive): + standard_include_path: Path + def read_file(self, path: StrPath) -> str: ... + def as_literal_block(self, text: str) -> list[nodes.literal_block]: ... + def as_code_block(self, text: str) -> list[nodes.literal_block]: ... + def custom_parse(self, text: str) -> list[nodes.Node]: ... + def insert_into_input_lines(self, text: str) -> None: ... + +class Raw(Directive): ... +class Replace(Directive): ... + +class Unicode(Directive): + comment_pattern: Pattern[str] + +class Class(Directive): ... + +class Role(Directive): + argument_pattern: Pattern[str] + +class DefaultRole(Directive): ... +class Title(Directive): ... + +class MetaBody(SpecializedBody): + def field_marker( # type: ignore[override] + self, match: Match[str], context: list[str], next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def parsemeta(self, match: Match[str]): ... + +class Meta(Directive): + SMkwargs: ClassVar[dict[str, tuple[MetaBody]]] + +class Date(Directive): ... +class TestDirective(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/parts.pyi b/stubs/docutils/docutils/parsers/rst/directives/parts.pyi new file mode 100644 index 000000000000..c69296038b5b --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/parts.pyi @@ -0,0 +1,14 @@ +from collections.abc import Sequence +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class Contents(Directive): + backlinks_values: Sequence[str] + def backlinks(arg): ... + +class Sectnum(Directive): ... +class Header(Directive): ... +class Footer(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/references.pyi b/stubs/docutils/docutils/parsers/rst/directives/references.pyi new file mode 100644 index 000000000000..412af33927d8 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/references.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +class TargetNotes(Directive): ... diff --git a/stubs/docutils/docutils/parsers/rst/directives/tables.pyi b/stubs/docutils/docutils/parsers/rst/directives/tables.pyi new file mode 100644 index 000000000000..56d14a5a6ac6 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/directives/tables.pyi @@ -0,0 +1,62 @@ +import csv +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import ClassVar, Final +from typing_extensions import deprecated + +from docutils import nodes +from docutils.parsers.rst import Directive + +__docformat__: Final = "reStructuredText" + +def align(argument): ... + +class Table(Directive): + option_spec: ClassVar[dict[str, Callable[[str], str | list[str]]]] + def make_title(self): ... + def check_table_dimensions(self, rows, header_rows, stub_columns) -> None: ... + def set_table_width(self, table_node) -> None: ... + @property + def widths(self): ... + def get_column_widths(self, n_cols): ... + def extend_short_rows_with_empty_cells(self, columns, parts) -> None: ... + +class RSTTable(Table): + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + +class CSVTable(Table): + class DocutilsDialect(csv.Dialect): + delimiter: str + quotechar: str + doublequote: bool + skipinitialspace: bool + strict: bool + lineterminator: str + quoting: Incomplete + escapechar: Incomplete + def __init__(self, options) -> None: ... + + @deprecated("Deprecated and will be removed in Docutils 1.0.") + class HeaderDialect(csv.Dialect): + delimiter: str + quotechar: str + escapechar: str + doublequote: bool + skipinitialspace: bool + strict: bool + lineterminator: str + quoting: Incomplete + def __init__(self) -> None: ... + + @staticmethod + @deprecated("Deprecated and not required with Python 3; will be removed in Docutils 0.22.") + def check_requirements() -> None: ... + def process_header_option(self): ... + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + def get_csv_data(self): ... + def parse_csv_data_into_rows(self, csv_data, dialect, source): ... + +class ListTable(Table): + def run(self) -> Sequence[nodes.table | nodes.system_message]: ... + def check_list_content(self, node): ... + def build_table_from_list(self, table_data, col_widths, header_rows, stub_columns) -> nodes.table: ... diff --git a/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi b/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi new file mode 100644 index 000000000000..e38d495da4b6 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/__init__.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar, Final, Protocol, type_check_only + +from docutils.languages import LanguageImporter +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +@type_check_only +class _RstLanguageModule(Protocol): + directives: dict[str, str] + roles: dict[str, str] + +class RstLanguageImporter(LanguageImporter): + cache: dict[str, _RstLanguageModule] # type: ignore[assignment] + fallback: ClassVar[None] # type: ignore[assignment] + def import_from_packages(self, name: str, reporter: Reporter | None = None) -> _RstLanguageModule: ... # type: ignore[override] + def check_content(self, module: _RstLanguageModule) -> None: ... # type: ignore[override] + def __call__(self, language_code: str, reporter: Reporter | None = None) -> _RstLanguageModule: ... # type: ignore[override] + +get_language: RstLanguageImporter diff --git a/stubs/docutils/docutils/parsers/rst/languages/af.pyi b/stubs/docutils/docutils/parsers/rst/languages/af.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/af.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ar.pyi b/stubs/docutils/docutils/parsers/rst/languages/ar.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ar.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ca.pyi b/stubs/docutils/docutils/parsers/rst/languages/ca.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ca.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/cs.pyi b/stubs/docutils/docutils/parsers/rst/languages/cs.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/cs.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/da.pyi b/stubs/docutils/docutils/parsers/rst/languages/da.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/da.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/de.pyi b/stubs/docutils/docutils/parsers/rst/languages/de.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/de.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/en.pyi b/stubs/docutils/docutils/parsers/rst/languages/en.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/en.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/eo.pyi b/stubs/docutils/docutils/parsers/rst/languages/eo.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/eo.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/es.pyi b/stubs/docutils/docutils/parsers/rst/languages/es.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/es.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fa.pyi b/stubs/docutils/docutils/parsers/rst/languages/fa.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fa.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fi.pyi b/stubs/docutils/docutils/parsers/rst/languages/fi.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fi.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/fr.pyi b/stubs/docutils/docutils/parsers/rst/languages/fr.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/fr.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/gl.pyi b/stubs/docutils/docutils/parsers/rst/languages/gl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/gl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/he.pyi b/stubs/docutils/docutils/parsers/rst/languages/he.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/he.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/it.pyi b/stubs/docutils/docutils/parsers/rst/languages/it.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/it.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ja.pyi b/stubs/docutils/docutils/parsers/rst/languages/ja.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ja.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ka.pyi b/stubs/docutils/docutils/parsers/rst/languages/ka.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ka.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ko.pyi b/stubs/docutils/docutils/parsers/rst/languages/ko.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ko.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/lt.pyi b/stubs/docutils/docutils/parsers/rst/languages/lt.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/lt.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/lv.pyi b/stubs/docutils/docutils/parsers/rst/languages/lv.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/lv.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/nl.pyi b/stubs/docutils/docutils/parsers/rst/languages/nl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/nl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/pl.pyi b/stubs/docutils/docutils/parsers/rst/languages/pl.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/pl.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi b/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/pt_br.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/ru.pyi b/stubs/docutils/docutils/parsers/rst/languages/ru.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/ru.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/sk.pyi b/stubs/docutils/docutils/parsers/rst/languages/sk.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/sk.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/sv.pyi b/stubs/docutils/docutils/parsers/rst/languages/sv.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/sv.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/uk.pyi b/stubs/docutils/docutils/parsers/rst/languages/uk.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/uk.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi b/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/zh_cn.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi b/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi new file mode 100644 index 000000000000..3ea6b97b3445 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/languages/zh_tw.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +directives: dict[str, str] +roles: dict[str, str] diff --git a/stubs/docutils/docutils/parsers/rst/roles.pyi b/stubs/docutils/docutils/parsers/rst/roles.pyi new file mode 100644 index 000000000000..4697d6982e79 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/roles.pyi @@ -0,0 +1,135 @@ +from collections.abc import Callable, Mapping, Sequence +from typing import Any, Final, TypeAlias +from typing_extensions import deprecated + +import docutils.parsers.rst.states +from docutils import nodes +from docutils.languages import _LanguageModule +from docutils.nodes import Node, system_message +from docutils.parsers.rst.states import Inliner +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" +DEFAULT_INTERPRETED_ROLE: Final = "title-reference" + +_RoleFn: TypeAlias = Callable[ + [str, str, str, int, docutils.parsers.rst.states.Inliner, Mapping[str, Any], Sequence[str]], + tuple[Sequence[nodes.reference], Sequence[nodes.reference]], +] + +def register_canonical_role(name: str, role_fn: _RoleFn) -> None: ... +def register_local_role(name: str, role_fn: _RoleFn) -> None: ... +def role( + role_name: str, language_module: _LanguageModule, lineno: int, reporter: Reporter +) -> tuple[_RoleFn | None, list[system_message]]: ... +def set_implicit_options(role_fn: _RoleFn) -> None: ... +def register_generic_role(canonical_name: str, node_class: type[Node]) -> None: ... + +class GenericRole: + name: str + node_class: type[Node] + def __init__(self, role_name: str, node_class: type[Node]) -> None: ... + def __call__( + self, + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> tuple[list[Node], list[system_message]]: ... + +class CustomRole: + name: str + base_role: _RoleFn | CustomRole + options: Mapping[str, Any] + content: Sequence[str] + supplied_options: Mapping[str, Any] + supplied_content: Sequence[str] + def __init__( + self, + role_name: str, + base_role: _RoleFn | CustomRole, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> None: ... + def __call__( + self, + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, + ) -> tuple[list[Node], list[system_message]]: ... + +def generic_custom_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def pep_reference_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def rfc_reference_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def raw_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def code_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def math_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +def unimplemented_role( + role: str, + rawtext: str, + text: str, + lineno: int, + inliner: Inliner, + options: Mapping[str, Any] | None = None, + content: Sequence[str] | None = None, +) -> tuple[list[Node], list[system_message]]: ... +@deprecated("Deprecated and will be removed in Docutils 2.0, Use `roles.normalize_options()` instead.") +def set_classes(options: dict[str, str]) -> None: ... +@deprecated("Deprecated and will be removed in Docutils 2.0, Use `roles.normalize_options()` instead.") +def normalized_role_options(options: Mapping[str, Any] | None) -> dict[str, Any]: ... +def normalize_options(options: Mapping[str, Any] | None) -> dict[str, Any]: ... diff --git a/stubs/docutils/docutils/parsers/rst/states.pyi b/stubs/docutils/docutils/parsers/rst/states.pyi new file mode 100644 index 000000000000..d148d2521222 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/states.pyi @@ -0,0 +1,390 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence +from re import Match, Pattern +from types import ModuleType, SimpleNamespace as Struct +from typing import Any, ClassVar, Final, TypeAlias +from typing_extensions import Never + +from docutils import ApplicationError, DataError, nodes +from docutils.nodes import Node, system_message +from docutils.parsers.rst.languages import _RstLanguageModule +from docutils.statemachine import StateMachine, StateMachineWS, StateWS, StringList +from docutils.utils import Reporter + +__docformat__: Final = "reStructuredText" + +class MarkupError(DataError): ... +class UnknownInterpretedRoleError(DataError): ... +class InterpretedRoleNotImplementedError(DataError): ... +class ParserError(ApplicationError): ... +class MarkupMismatch(Exception): ... + +class RSTStateMachine(StateMachineWS[list[str]]): + language: _RstLanguageModule + match_titles: bool + memo: Struct | None + document: nodes.document + reporter: Reporter + node: nodes.document | None + section_level_offset: int + def run( # type: ignore[override] + self, + input_lines: Sequence[str] | StringList, + document: nodes.document, + input_offset: int = 0, + match_titles: bool = True, + inliner: Inliner | None = None, + ) -> None: ... + +class NestedStateMachine(RSTStateMachine): + parent_state_machine: Incomplete | None + def __init__(self, state_classes, initial_state, debug: bool = False, parent_state_machine=None) -> None: ... + def run( # type: ignore[override] + self, input_lines: Sequence[str] | StringList, input_offset: int, memo, node, match_titles: bool = True + ) -> list[str]: ... + +class RSTState(StateWS[list[str]]): + nested_sm: type[NestedStateMachine] + nested_sm_cache: list[StateMachine[Incomplete]] + def __init__(self, state_machine, debug: bool = False) -> None: ... + memo: Incomplete + reporter: Reporter + inliner: Inliner + document: nodes.document + parent: Incomplete + def runtime_init(self) -> None: ... + def goto_line(self, abs_line_offset: int) -> None: ... + def no_match(self, context: list[str], transitions): ... + def bof(self, context: list[str]): ... + def nested_parse( + self, + block: StringList, + input_offset: int, + node: nodes.Element | None = None, + match_titles: bool = False, + state_machine_class: StateMachineWS[Incomplete] | None = None, + state_machine_kwargs: dict[Incomplete, Incomplete] | None = None, + ) -> int: ... + def nested_list_parse( + self, + block, + input_offset: int, + node, + initial_state, + blank_finish, + blank_finish_state=None, + extra_settings={}, + match_titles: bool = False, + state_machine_class=None, + state_machine_kwargs=None, + ): ... + def section(self, title: str, source, style, lineno: int, messages) -> None: ... + def check_subsection(self, source, style, lineno: int): ... + def title_inconsistent(self, sourcetext: str, lineno: int): ... + def new_subsection(self, title: str, lineno: int, messages) -> None: ... + def paragraph(self, lines: Iterable[str], lineno: int): ... + def inline_text(self, text: str, lineno: int) -> tuple[list[Node], list[system_message]]: ... + def unindent_warning(self, node_name: str): ... + +def build_regexp(definition, compile_patterns: bool | None = True): ... + +_BasicDefinition: TypeAlias = tuple[str, str, str, list[Pattern[str]]] +_DefinitionParts: TypeAlias = tuple[str, str, str, list[Pattern[str] | _BasicDefinition]] +_DefinitionType: TypeAlias = tuple[str, str, str, list[Pattern[str] | _DefinitionParts]] + +class Inliner: + implicit_dispatch: list[tuple[Pattern[str], Callable[[Match[str], int], Sequence[nodes.Node]]]] + def __init__(self) -> None: ... + start_string_prefix: str + end_string_suffix: str + parts: _DefinitionType + patterns: Struct + def init_customizations(self, settings: Any) -> None: ... + reporter: Reporter + document: nodes.document + language: ModuleType + parent: nodes.Element + def parse( + self, text: str, lineno: int, memo: Struct, parent: nodes.Element + ) -> tuple[list[nodes.Node], list[nodes.system_message]]: ... + non_whitespace_before: str + non_whitespace_escape_before: str + non_unescaped_whitespace_escape_before: str + non_whitespace_after: str + simplename: str + uric: str + uri_end_delim: str + urilast: str + uri_end: str + emailc: str + email_pattern: str + def quoted_start(self, match: Match[str]) -> bool: ... + def inline_obj( + self, + match: Match[str], + lineno: int, + end_pattern: Pattern[str], + nodeclass: nodes.TextElement, + restore_backslashes: bool = False, + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message], str]: ... + def problematic(self, text: str, rawsource: str, message: nodes.system_message) -> nodes.problematic: ... + def emphasis( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def strong(self, match: Match[str], lineno: int) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def interpreted_or_phrase_ref( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def phrase_ref( + self, before: str, after: str, rawsource: str, escaped: str, text: str | None = None + ) -> tuple[str, list[nodes.Node], str, list[nodes.Node]]: ... + def adjust_uri(self, uri: str) -> str: ... + def interpreted( + self, rawsource: str, text: str, role: str, lineno: int + ) -> tuple[list[nodes.Node], list[nodes.system_message]]: ... + def literal(self, match: Match[str], lineno: int) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def inline_internal_target( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def substitution_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def footnote_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def reference( + self, match: Match[str], lineno: int, anonymous: bool = False + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def anonymous_reference( + self, match: Match[str], lineno: int + ) -> tuple[str, list[nodes.problematic], str, list[nodes.system_message]]: ... + def standalone_uri( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + def pep_reference( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + rfc_url: str = ... + def rfc_reference( + self, match: Match[str], lineno: int + ) -> list[tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]: ... + def implicit_inline(self, text: str, lineno: int) -> list[nodes.Text]: ... + dispatch: dict[str, Callable[[Match[str], int], tuple[str, list[nodes.problematic], str, list[nodes.system_message]]]] = ... + +class Body(RSTState): + double_width_pad_char: Incomplete + enum: Incomplete + grid_table_top_pat: Incomplete + simple_table_top_pat: Incomplete + simple_table_border_pat: Incomplete + pats: Incomplete + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[tuple[str, ...]] + sequence: str + format: str + def indent(self, match, context, next_state): ... + def block_quote(self, indented, line_offset): ... + attribution_pattern: Incomplete + def split_attribution(self, indented, line_offset): ... + def check_attribution(self, indented, attribution_start): ... + def parse_attribution(self, indented, line_offset): ... + def bullet(self, match, context, next_state): ... + def list_item(self, indent): ... + def enumerator(self, match, context, next_state): ... + def parse_enumerator(self, match, expected_sequence=None): ... + def is_enumerated_list_item(self, ordinal, sequence, format): ... + def make_enumerator(self, ordinal, sequence, format): ... + def field_marker(self, match, context, next_state): ... + def field(self, match): ... + def parse_field_marker(self, match): ... + def parse_field_body(self, indented, offset, node) -> None: ... + def option_marker(self, match, context, next_state): ... + def option_list_item(self, match): ... + def parse_option_marker(self, match): ... + def doctest(self, match, context, next_state): ... + def line_block(self, match, context, next_state): ... + def line_block_line(self, match, lineno): ... + def nest_line_block_lines(self, block) -> None: ... + def nest_line_block_segment(self, block) -> None: ... + def grid_table_top(self, match, context, next_state): ... + def simple_table_top(self, match, context, next_state): ... + def table_top(self, match, context, next_state, isolate_function, parser_class): ... + def table(self, isolate_function, parser_class): ... + def isolate_grid_table(self): ... + def isolate_simple_table(self): ... + def malformed_table(self, block, detail: str = "", offset: int = 0): ... + def build_table(self, tabledata, tableline, stub_columns: int = 0, widths=None) -> nodes.table: ... + def build_table_row(self, rowdata, tableline): ... + explicit: Incomplete + def footnote(self, match): ... + def citation(self, match): ... + def hyperlink_target(self, match): ... + def make_target(self, block, block_text, lineno, target_name): ... + def parse_target(self, block, block_text, lineno): ... + def is_reference(self, reference): ... + def add_target(self, targetname, refuri, target, lineno) -> None: ... + def substitution_def(self, match): ... + def disallowed_inside_substitution_definitions(self, node): ... + def directive(self, match, **option_presets): ... + def run_directive(self, directive, match, type_name, option_presets): ... + def parse_directive_block(self, indented, line_offset, directive, option_presets): ... + def parse_directive_options(self, option_presets, option_spec, arg_block): ... + def parse_directive_arguments(self, directive, arg_block): ... + def parse_extension_options(self, option_spec, datalines): ... + def unknown_directive(self, type_name): ... + def comment(self, match): ... + def explicit_markup(self, match, context, next_state): ... + def explicit_construct(self, match): ... + def explicit_list(self, blank_finish) -> None: ... + def anonymous(self, match: Match[str], context: list[str] | None, next_state: str): ... + def anonymous_target(self, match): ... + def line(self, match, context, next_state): ... + def text(self, match, context, next_state): ... + +class RFC2822Body(Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str | tuple[str, str], str]]] # type: ignore[assignment] + def rfc2822(self, match, context, next_state): ... + def rfc2822_field(self, match): ... + +class SpecializedBody(Body): + def invalid_input( + self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None + ) -> Never: ... + indent = invalid_input # type: ignore[assignment] + bullet = invalid_input + enumerator = invalid_input + field_marker = invalid_input + option_marker = invalid_input + doctest = invalid_input + line_block = invalid_input + grid_table_top = invalid_input + simple_table_top = invalid_input + explicit_markup = invalid_input + anonymous = invalid_input # type: ignore[assignment] + line = invalid_input + text = invalid_input + +class BulletList(SpecializedBody): + blank_finish: Incomplete + def bullet( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class DefinitionList(SpecializedBody): + def text(self, match: Match[str], context: list[str] | None, next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + +class EnumeratedList(SpecializedBody): + auto: int + blank_finish: Incomplete + lastordinal: Incomplete + def enumerator( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class FieldList(SpecializedBody): + blank_finish: Incomplete + def field_marker( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class OptionList(SpecializedBody): + blank_finish: Incomplete + def option_marker( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class RFC2822List(SpecializedBody, RFC2822Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str | tuple[str, str], str]]] # type: ignore[assignment] + blank_finish: Incomplete + def rfc2822(self, match, context, next_state): ... + blank: Incomplete + +class ExtensionOptions(FieldList): + def parse_field_body(self, indented, offset, node) -> None: ... + +class LineBlock(SpecializedBody): + blank: Incomplete + blank_finish: Incomplete + def line_block( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class Explicit(SpecializedBody): + blank_finish: Incomplete + blank: Incomplete + def explicit_markup( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def anonymous( # type: ignore[override] + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + +class SubstitutionDef(Body): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[str]] # type: ignore[assignment] + blank_finish: Incomplete + def embedded_directive(self, match, context, next_state) -> None: ... + def text(self, match, context, next_state) -> None: ... + +class Text(RSTState): + patterns: ClassVar[dict[str, str | Pattern[str]]] + initial_transitions: ClassVar[list[tuple[str, str]]] + def blank(self, match, context, next_state): ... + def eof(self, context): ... + def indent(self, match, context, next_state): ... + def underline(self, match, context, next_state): ... + def text(self, match, context, next_state): ... + def literal_block(self): ... + def quoted_literal_block(self): ... + def definition_list_item(self, termline): ... + classifier_delimiter: Incomplete + def term(self, lines, lineno): ... + +class SpecializedText(Text): + def eof(self, context): ... + def invalid_input( + self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None + ) -> Never: ... + blank = invalid_input + indent = invalid_input + underline = invalid_input + text = invalid_input + +class Definition(SpecializedText): + def eof(self, context): ... + blank_finish: Incomplete + def indent( # type: ignore[override] + self, match: Match[str] | None, context: list[str], next_state: str | None + ) -> tuple[list[str], str, list[str]]: ... + +class Line(SpecializedText): + eofcheck: int + def eof(self, context: list[str]): ... + def blank(self, match: Match[str] | None, context: list[str], next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + def text(self, match: Match[str], context: list[str], next_state: str | None) -> tuple[list[str], str, list[str]]: ... # type: ignore[override] + indent = text # type: ignore[assignment] + def underline( # type: ignore[override] + self, match: Match[str] | None, context: list[str], next_state: str | None + ) -> tuple[list[str], str, list[str]]: ... + def short_overline(self, context, blocktext, lineno, lines: int = 1) -> None: ... + def state_correction(self, context, lines: int = 1) -> None: ... + +class QuotedLiteralBlock(RSTState): + patterns: ClassVar[dict[str, str | Pattern[str]]] + messages: Incomplete + initial_lineno: Incomplete + def __init__(self, state_machine, debug: bool = False) -> None: ... + def blank(self, match, context, next_state): ... + def eof(self, context): ... + def indent(self, match: Match[str] | None, context: list[str], next_state: str | None) -> Never: ... + def initial_quoted( + self, match: Match[str], context: list[str] | None, next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def quoted( + self, match: Match[str], context: list[str], next_state: str | None + ) -> tuple[list[str], str | None, list[str]]: ... + def text(self, match: Match[str] | None, context: list[str] | None, next_state: str | None) -> None: ... + +state_classes: tuple[type[RSTState], ...] diff --git a/stubs/docutils/docutils/parsers/rst/tableparser.pyi b/stubs/docutils/docutils/parsers/rst/tableparser.pyi new file mode 100644 index 000000000000..ad805b9ccd52 --- /dev/null +++ b/stubs/docutils/docutils/parsers/rst/tableparser.pyi @@ -0,0 +1,64 @@ +from re import Pattern +from typing import ClassVar, Final, TypeAlias + +from docutils import DataError +from docutils.statemachine import StringList + +_Cell: TypeAlias = tuple[int, int, int, list[str]] +_Row: TypeAlias = list[_Cell | None] +_Colspecs: TypeAlias = list[int] + +__docformat__: Final = "reStructuredText" + +class TableMarkupError(DataError): + offset: int + def __init__(self, *args, **kwargs) -> None: ... + +class TableParser: + head_body_separator_pat: ClassVar[Pattern[str] | None] + double_width_pad_char: ClassVar[str] + head_body_sep: int + def parse(self, block: StringList) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + def find_head_body_sep(self) -> None: ... + +class GridTableParser(TableParser): + head_body_separator_pat: ClassVar[Pattern[str]] + block: StringList + bottom: int + right: int + head_body_sep: int + done: list[int] + cells: list[_Cell] + rowseps: dict[int, list[int]] + colseps: dict[int, list[int]] + def setup(self, block: StringList) -> None: ... + def parse_table(self) -> None: ... + def mark_done(self, top: int, left: int, bottom: int, right: int) -> None: ... + def check_parse_complete(self) -> bool: ... + def scan_cell(self, top: int, left: int) -> tuple[int, int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_right(self, top: int, left: int) -> tuple[int, int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_down(self, top: int, left: int, right: int) -> tuple[int, dict[int, list[int]], dict[int, list[int]]]: ... + def scan_left(self, top: int, left: int, bottom: int, right: int) -> tuple[dict[int, list[int]], dict[int, list[int]]]: ... + def scan_up(self, top: int, left: int, bottom: int, right: int) -> dict[int, list[int]]: ... + def structure_from_cells(self) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + +class SimpleTableParser(TableParser): + head_body_separator_pat: ClassVar[Pattern[str]] + span_pat: ClassVar[Pattern[str]] + block: StringList + head_body_sep: int + columns: list[tuple[int, int]] + border_end: int + table: tuple[list[int], list[_Row], list[_Row]] + done: list[int] + rowseps: dict[int, tuple[int]] + colseps: dict[int, tuple[int]] + def setup(self, block: StringList) -> None: ... + def parse_table(self) -> None: ... + def parse_columns(self, line: str, offset: int) -> list[tuple[int, int]]: ... + def init_row(self, colspec: list[tuple[int, int]], offset: int) -> list[_Cell]: ... + def parse_row(self, lines: list[str], start: int, spanline: tuple[str, int] | None = None) -> None: ... + def check_columns(self, lines: list[str], first_line: int, columns: list[tuple[int, int]]) -> None: ... + def structure_from_cells(self) -> tuple[_Colspecs, list[_Row], list[_Row]]: ... + +def update_dict_of_lists(master: dict[int, list[int]], newdata: dict[int, list[int]]) -> None: ... diff --git a/stubs/docutils/docutils/readers/__init__.pyi b/stubs/docutils/docutils/readers/__init__.pyi new file mode 100644 index 000000000000..d29e4aa717d3 --- /dev/null +++ b/stubs/docutils/docutils/readers/__init__.pyi @@ -0,0 +1,31 @@ +from typing import Any, ClassVar, Final, Generic, TypeVar + +from docutils import Component, nodes +from docutils.frontend import Values +from docutils.io import Input +from docutils.parsers import Parser +from docutils.transforms import Transform + +_S = TypeVar("_S") + +__docformat__: Final = "reStructuredText" + +class Reader(Component, Generic[_S]): + component_type: ClassVar[str] + config_section: ClassVar[str] + def get_transforms(self) -> list[type[Transform]]: ... + def __init__(self, parser: Parser | None = None, parser_name: str | None = None) -> None: ... + parser: Parser | None + source: Input[_S] | None + input: str | None + def set_parser(self, parser_name: str) -> None: ... + settings: Values + def read(self, source: Input[_S], parser: Parser, settings: Values) -> nodes.document: ... + document: nodes.document + def parse(self) -> None: ... + def new_document(self) -> nodes.document: ... + +class ReReader(Reader[_S]): + def get_transforms(self) -> list[type[Transform]]: ... + +def get_reader_class(reader_name: str) -> type[Reader[Any]]: ... diff --git a/stubs/docutils/docutils/readers/doctree.pyi b/stubs/docutils/docutils/readers/doctree.pyi new file mode 100644 index 000000000000..27be5d0e1f0e --- /dev/null +++ b/stubs/docutils/docutils/readers/doctree.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Final, TypeVar + +from docutils import readers + +_S = TypeVar("_S", bound=str | bytes) + +__docformat__: Final = "reStructuredText" + +class Reader(readers.ReReader[_S]): + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/readers/pep.pyi b/stubs/docutils/docutils/readers/pep.pyi new file mode 100644 index 000000000000..ef0247369aad --- /dev/null +++ b/stubs/docutils/docutils/readers/pep.pyi @@ -0,0 +1,12 @@ +from typing import ClassVar, Final, TypeVar + +from docutils.parsers.rst import states +from docutils.readers import standalone + +__docformat__: Final = "reStructuredText" + +_S = TypeVar("_S", bound=str | bytes) + +class Reader(standalone.Reader[_S]): + settings_default_overrides: ClassVar[dict[str, int]] + inliner_class: ClassVar[type[states.Inliner]] diff --git a/stubs/docutils/docutils/readers/standalone.pyi b/stubs/docutils/docutils/readers/standalone.pyi new file mode 100644 index 000000000000..6e7319e2c5d1 --- /dev/null +++ b/stubs/docutils/docutils/readers/standalone.pyi @@ -0,0 +1,11 @@ +from typing import ClassVar, Final, TypeVar + +from docutils import nodes, readers + +__docformat__: Final = "reStructuredText" + +_S = TypeVar("_S", bound=str | bytes) + +class Reader(readers.Reader[_S]): + document: nodes.document | None # type: ignore[assignment] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/statemachine.pyi b/stubs/docutils/docutils/statemachine.pyi new file mode 100644 index 000000000000..96b5f38a7461 --- /dev/null +++ b/stubs/docutils/docutils/statemachine.pyi @@ -0,0 +1,205 @@ +import sys +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from re import Match, Pattern +from typing import Any, ClassVar, Final, Generic, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self + +_T = TypeVar("_T") +_Context = TypeVar("_Context") +_TransitionResult: TypeAlias = tuple[_Context, str | None, list[str]] +_TransitionMethod: TypeAlias = Callable[[Match[str], _Context, str], _TransitionResult[_Context]] +_Observer: TypeAlias = Callable[[StateMachine[_Context]], None] + +__docformat__: Final = "restructuredtext" + +class StateMachine(Generic[_Context]): + input_lines: StringList | None + input_offset: int + line: str | None + line_offset: int + debug: bool + initial_state: str + current_state: str + states: dict[str, State[_Context]] + observers: list[_Observer[_Context]] + def __init__(self, state_classes: Iterable[type[State[_Context]]], initial_state: str, debug: bool = False) -> None: ... + def unlink(self) -> None: ... + def run( + self, + input_lines: Sequence[str] | StringList, + input_offset: int = 0, + context: _Context | None = None, + input_source: str | None = None, + initial_state: str | None = None, + ) -> list[str]: ... + def get_state(self, next_state: str | None = None) -> State[_Context]: ... + def next_line(self, n: int = 1) -> str: ... + def is_next_line_blank(self) -> bool: ... + def at_eof(self) -> bool: ... + def at_bof(self) -> bool: ... + def previous_line(self, n: int = 1) -> str | None: ... + def goto_line(self, line_offset: int) -> str | None: ... + def get_source(self, line_offset: int) -> str: ... + def abs_line_offset(self) -> int: ... + def abs_line_number(self) -> int: ... + def get_source_and_line(self, lineno: int | None = None) -> tuple[str, int] | tuple[None, None]: ... + def insert_input(self, input_lines: list[str] | StringList, source: str) -> None: ... + def get_text_block(self, flush_left: bool = False) -> StringList: ... + def check_line( + self, context: _Context, state: State[_Context], transitions: list[str] | None = None + ) -> _TransitionResult[_Context]: ... + def add_state(self, state_class: type[State[_Context]]) -> None: ... + def add_states(self, state_classes: Iterable[type[State[_Context]]]) -> None: ... + def runtime_init(self) -> None: ... + def error(self) -> None: ... + def attach_observer(self, observer: _Observer[_Context]) -> None: ... + def detach_observer(self, observer: _Observer[_Context]) -> None: ... + def notify_observers(self) -> None: ... + +class State(Generic[_Context]): + patterns: ClassVar[dict[str, str | Pattern[str]] | None] + initial_transitions: ClassVar[Sequence[str] | Sequence[tuple[str, str]] | None] + nested_sm: type[StateMachine[_Context]] + nested_sm_kwargs: dict[str, Any] + transition_order: list[str] + transitions: dict[str, tuple[Pattern[str], Callable[[], None], str]] + state_machine: StateMachine[_Context] + debug: bool + def __init__(self, state_machine: StateMachine[_Context], debug: bool = False) -> None: ... + def runtime_init(self) -> None: ... + def unlink(self) -> None: ... + def add_initial_transitions(self) -> None: ... + def add_transitions(self, names: Iterable[str], transitions) -> None: ... + def add_transition(self, name: str, transition: tuple[Pattern[str], str, str]) -> None: ... + def remove_transition(self, name: str) -> None: ... + def make_transition( + self, name: str, next_state: str | None = None + ) -> tuple[Pattern[str], _TransitionMethod[_Context], str]: ... + def make_transitions( + self, name_list: list[str | tuple[str] | tuple[str, str]] + ) -> tuple[list[str], dict[str, tuple[Pattern[str], _TransitionMethod[_Context], str]]]: ... + def no_match( + self, context: _Context, transitions: tuple[list[str], dict[str, tuple[Pattern[str], _TransitionMethod[_Context], str]]] + ) -> _TransitionResult[_Context]: ... + def bof(self, context: _Context) -> tuple[list[str], list[str]]: ... + def eof(self, context: _Context) -> list[str]: ... + def nop(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + +class StateMachineWS(StateMachine[_Context]): + def get_indented(self, until_blank: bool = False, strip_indent: bool = True) -> tuple[StringList, int, int, bool]: ... + def get_known_indented( + self, indent: int, until_blank: bool = False, strip_indent: bool = True + ) -> tuple[list[str], int, bool]: ... + def get_first_known_indented( + self, indent: int, until_blank: bool = False, strip_indent: bool = True, strip_top: bool = True + ) -> tuple[list[str], int, int, bool]: ... + +class StateWS(State[_Context]): + indent_sm: type[StateMachine[_Context]] | None + indent_sm_kwargs: dict[str, Any] | None + known_indent_sm: type[StateMachine[_Context]] | None + known_indent_sm_kwargs: dict[str, Any] | None + ws_patterns: dict[str, Pattern[str]] + ws_initial_transitions: Sequence[str] + def __init__(self, state_machine: StateMachine[_Context], debug: bool = False) -> None: ... + def add_initial_transitions(self) -> None: ... + def blank(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def known_indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + def first_known_indent(self, match: Match[str], context: _Context, next_state: str) -> _TransitionResult[_Context]: ... + +class _SearchOverride: + def match(self, pattern: Pattern[str]) -> Match[str]: ... + +class SearchStateMachine(_SearchOverride, StateMachine[_Context]): ... +class SearchStateMachineWS(_SearchOverride, StateMachineWS[_Context]): ... + +class ViewList(Generic[_T]): + data: list[_T] + items: list[tuple[str, int]] + parent: Self + parent_offset: int + def __init__( + self, + initlist: Self | Sequence[_T] | None = None, + source: str | None = None, + items: list[tuple[str, int]] | None = None, + parent: Self | None = None, + parent_offset: int | None = None, + ) -> None: ... + def __lt__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + def __contains__(self, item: _T) -> bool: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, i: slice) -> Self: ... + @overload + def __getitem__(self, i: SupportsIndex) -> _T: ... + + @overload + def __setitem__(self, i: slice, item: Self) -> None: ... + @overload + def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... + + def __delitem__(self, i: SupportsIndex) -> None: ... + def __add__(self, other: Self) -> Self: ... + def __radd__(self, other: Self) -> Self: ... + def __iadd__(self, other: Self) -> Self: ... + def __mul__(self, n: int) -> Self: ... + __rmul__ = __mul__ + def __imul__(self, n: int) -> Self: ... + def extend(self, other: Self) -> None: ... + def append(self, item: _T, source: str | None = None, offset: int = 0) -> None: ... + def insert(self, i: int, item: _T, source: str | None = None, offset: int = 0) -> None: ... + def pop(self, i: int = -1) -> _T: ... + def trim_start(self, n: int = 1) -> None: ... + def trim_end(self, n: int = 1) -> None: ... + def remove(self, item: _T) -> None: ... + def count(self, item: _T) -> int: ... + def index(self, item: _T) -> int: ... + def reverse(self) -> None: ... + def sort(self, *args: tuple[_T, tuple[str, int]]) -> None: ... + def info(self, i: int) -> tuple[str, int | None]: ... + def source(self, i: int) -> str: ... + def offset(self, i: int) -> int: ... + def disconnect(self) -> None: ... + def xitems(self) -> Generator[tuple[str, int, str]]: ... + def pprint(self) -> None: ... + + # dummy atribute to indicate to mypy that ViewList is Iterable[str] + def __iter__(self) -> Iterator[str]: ... + +class StringList(ViewList[str]): + def trim_left(self, length: int, start: int = 0, end: int = sys.maxsize) -> None: ... + def get_text_block(self, start: int, flush_left: bool = False) -> StringList: ... + def get_indented( + self, + start: int = 0, + until_blank: bool = False, + strip_indent: bool = True, + block_indent: int | None = None, + first_indent: int | None = None, + ) -> tuple[StringList, int, bool]: ... + def get_2D_block(self, top: int, left: int, bottom: int, right: int, strip_indent: bool = True) -> StringList: ... + def pad_double_width(self, pad_char: str) -> None: ... + def replace(self, old: str, new: str) -> None: ... + +class StateMachineError(Exception): ... +class UnknownStateError(StateMachineError): ... +class DuplicateStateError(StateMachineError): ... +class UnknownTransitionError(StateMachineError): ... +class DuplicateTransitionError(StateMachineError): ... +class TransitionPatternNotFound(StateMachineError): ... +class TransitionMethodNotFound(StateMachineError): ... +class UnexpectedIndentationError(StateMachineError): ... +class TransitionCorrection(Exception): ... +class StateCorrection(Exception): ... + +def string2lines( + astring: str, tab_width: int = 8, convert_whitespace: bool = False, whitespace: Pattern[str] = ... +) -> list[str]: ... diff --git a/stubs/docutils/docutils/transforms/__init__.pyi b/stubs/docutils/docutils/transforms/__init__.pyi new file mode 100644 index 000000000000..a848d0768f9f --- /dev/null +++ b/stubs/docutils/docutils/transforms/__init__.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import Any, ClassVar, Final, TypeAlias + +from docutils import ApplicationError, TransformSpec, nodes +from docutils.languages import LanguageImporter + +_TransformTuple: TypeAlias = tuple[str, type[Transform], nodes.Node | None, dict[str, Any]] + +__docformat__: Final = "reStructuredText" + +class TransformError(ApplicationError): ... + +class Transform: + default_priority: ClassVar[int | None] + document: nodes.document + startnode: nodes.Node | None + language: LanguageImporter + def __init__(self, document: nodes.document, startnode: nodes.Node | None = None) -> None: ... + def __getattr__(self, name: str, /) -> Incomplete: ... # method apply is not implemented + +class Transformer(TransformSpec): + transforms: list[_TransformTuple] + document: nodes.document + applied: list[_TransformTuple] + sorted: bool + components: Mapping[str, TransformSpec] + serialno: int + def __init__(self, document: nodes.document): ... + def add_transform(self, transform_class: type[Transform], priority: int | None = None, **kwargs) -> None: ... + def add_transforms(self, transform_list: Iterable[type[Transform]]) -> None: ... + def add_pending(self, pending: nodes.pending, priority: int | None = None) -> None: ... + def get_priority_string(self, priority: int) -> str: ... + def populate_from_components(self, components: Iterable[TransformSpec]) -> None: ... + def apply_transforms(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/components.pyi b/stubs/docutils/docutils/transforms/components.pyi new file mode 100644 index 000000000000..1c079281007a --- /dev/null +++ b/stubs/docutils/docutils/transforms/components.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Filter(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/frontmatter.pyi b/stubs/docutils/docutils/transforms/frontmatter.pyi new file mode 100644 index 000000000000..bb0a86afb869 --- /dev/null +++ b/stubs/docutils/docutils/transforms/frontmatter.pyi @@ -0,0 +1,34 @@ +import re +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class TitlePromoter(Transform): + def promote_title(self, node: nodes.Element) -> bool: ... + def promote_subtitle(self, node: nodes.Element) -> bool: ... + def candidate_index(self, node: nodes.Element) -> tuple[nodes.Node, int] | tuple[None, None]: ... + +class DocTitle(TitlePromoter): + default_priority: ClassVar[int] + def set_metadata(self) -> None: ... + def apply(self) -> None: ... + +class SectionSubTitle(TitlePromoter): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DocInfo(Transform): + default_priority: ClassVar[int] + biblio_nodes: ClassVar[dict[str, type[nodes.Element]]] + rcs_keyword_substitutions: ClassVar[list[tuple[re.Pattern[str], str]]] + def apply(self) -> None: ... + def extract_bibliographic(self, field_list): ... + def check_empty_biblio_field(self, field, name) -> bool: ... + def check_compound_biblio_field(self, field, name) -> bool: ... + def extract_authors(self, field, name, docinfo) -> None: ... + def authors_from_one_paragraph(self, field) -> list[list[nodes.Text]]: ... + def authors_from_bullet_list(self, field): ... + def authors_from_paragraphs(self, field): ... diff --git a/stubs/docutils/docutils/transforms/misc.pyi b/stubs/docutils/docutils/transforms/misc.pyi new file mode 100644 index 000000000000..3baa09ca0761 --- /dev/null +++ b/stubs/docutils/docutils/transforms/misc.pyi @@ -0,0 +1,19 @@ +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class CallBack(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class ClassAttribute(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class Transitions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... diff --git a/stubs/docutils/docutils/transforms/parts.pyi b/stubs/docutils/docutils/transforms/parts.pyi new file mode 100644 index 000000000000..39aa9e2aa8df --- /dev/null +++ b/stubs/docutils/docutils/transforms/parts.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterable, Sequence +from typing import ClassVar, Final +from typing_extensions import Never + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class SectNum(Transform): + default_priority: ClassVar[int] + maxdepth: int + startvalue: int + prefix: str + suffix: str + def apply(self) -> None: ... + def update_section_numbers(self, node: nodes.Element, prefix: Iterable[str] = (), depth: int = 0) -> None: ... + +class Contents(Transform): + default_priority: ClassVar[int] + toc_id: Incomplete + backlinks: Incomplete + def apply(self) -> None: ... + def build_contents( + self, node: nodes.Element, level: int = 0 + ) -> nodes.bullet_list | list[None]: ... # return empty list if entries is empty + def copy_and_filter(self, node: nodes.Node) -> Sequence[nodes.Node]: ... + +class ContentsFilter(nodes.TreeCopyVisitor): + def get_entry_text(self) -> Sequence[nodes.Node]: ... + def ignore_node_but_process_children(self, node: Unused) -> Never: ... + visit_problematic = ignore_node_but_process_children + visit_reference = ignore_node_but_process_children + visit_target = ignore_node_but_process_children diff --git a/stubs/docutils/docutils/transforms/peps.pyi b/stubs/docutils/docutils/transforms/peps.pyi new file mode 100644 index 000000000000..6b309245d35c --- /dev/null +++ b/stubs/docutils/docutils/transforms/peps.pyi @@ -0,0 +1,43 @@ +import re +from typing import ClassVar, Final + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Headers(Transform): + default_priority: ClassVar[int] + pep_url: ClassVar[str] + pep_cvs_url: ClassVar[str] + rcs_keyword_substitutions: ClassVar[tuple[tuple[re.Pattern[str], str], ...]] + def apply(self) -> None: ... + +class Contents(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TargetNotes(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def cleanup_callback(self, pending: nodes.pending) -> None: ... + +class PEPZero(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class PEPZeroSpecial(nodes.SparseNodeVisitor): + pep_url: ClassVar[str] + def unknown_visit(self, node: nodes.Node) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + pep_table: bool + entry: int + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + +non_masked_addresses: tuple[str, ...] + +def mask_email(ref: nodes.reference, pepno: int | None = None) -> nodes.Node: ... diff --git a/stubs/docutils/docutils/transforms/references.pyi b/stubs/docutils/docutils/transforms/references.pyi new file mode 100644 index 000000000000..3d6d710310ce --- /dev/null +++ b/stubs/docutils/docutils/transforms/references.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, overload + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class PropagateTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class AnonymousHyperlinks(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class IndirectHyperlinks(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def resolve_indirect_target(self, target: nodes.Element) -> None: ... + def nonexistent_indirect_target(self, target: nodes.Element) -> None: ... + def circular_indirect_reference(self, target: nodes.Element) -> None: ... + def indirect_target_error(self, target: nodes.Element, explanation) -> None: ... + def resolve_indirect_references(self, target: nodes.Element) -> None: ... + +class ExternalTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class InternalTargets(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def resolve_reference_ids(self, target: nodes.Element) -> None: ... + +class Footnotes(Transform): + default_priority: ClassVar[int] + autofootnote_labels: list[str] | None + symbols: ClassVar[list[str]] + def apply(self) -> None: ... + def number_footnotes(self, startnum: int) -> int: ... + def number_footnote_references(self, startnum: int) -> None: ... + def symbolize_footnotes(self) -> None: ... + def resolve_footnotes_and_citations(self) -> None: ... + + @overload + def resolve_references(self, note: nodes.footnote, reflist: Iterable[nodes.footnote_reference]) -> None: ... + @overload + def resolve_references(self, note: nodes.citation, reflist: Iterable[nodes.citation_reference]) -> None: ... + @overload + def resolve_references(self, note: nodes.title, reflist: Iterable[nodes.title_reference]) -> None: ... + +class CircularSubstitutionDefinitionError(Exception): ... + +class Substitutions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TargetNotes(Transform): + default_priority: ClassVar[int] + classes: Incomplete + def __init__(self, document: nodes.document, startnode: nodes.Node) -> None: ... + def apply(self) -> None: ... + def make_target_footnote(self, refuri: str, refs: list[Incomplete], notes: dict[Incomplete, Incomplete]): ... + +class CitationReferences(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DanglingReferences(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class DanglingReferencesVisitor(nodes.SparseNodeVisitor): + document: nodes.document + def __init__(self, document: nodes.document, unknown_reference_resolvers) -> None: ... + def unknown_visit(self, node: nodes.Node) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... diff --git a/stubs/docutils/docutils/transforms/universal.pyi b/stubs/docutils/docutils/transforms/universal.pyi new file mode 100644 index 000000000000..5d54735bbca8 --- /dev/null +++ b/stubs/docutils/docutils/transforms/universal.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import ClassVar, Final, Literal + +from docutils import nodes +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Decorations(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + def generate_header(self) -> None: ... + def generate_footer(self) -> list[nodes.paragraph] | None: ... + +class ExposeInternals(Transform): + default_priority: ClassVar[int] + def not_Text(self, node: object) -> bool: ... # node passing to isinstance() method + def apply(self) -> None: ... + +class Messages(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class FilterMessages(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class TestMessages(Transform): + __test__: bool + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class StripComments(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... + +class StripClassesAndElements(Transform): + default_priority: ClassVar[int] + strip_elements: set[Incomplete] + def apply(self) -> None: ... + def check_classes(self, node: object) -> bool: ... + +class SmartQuotes(Transform): + default_priority: ClassVar[int] + nodes_to_skip: ClassVar[tuple[type[nodes.Node | nodes.Special], ...]] + literal_nodes: ClassVar[tuple[type[nodes.Node | nodes.Body], ...]] + smartquotes_action: ClassVar[str] + unsupported_languages: set[str] + def __init__(self, document: nodes.document, startnode: nodes.Node | None) -> None: ... + def get_tokens(self, txtnodes: Iterable[nodes.Node]) -> Generator[tuple[Literal["literal", "plain"], str]]: ... + def apply(self) -> None: ... + +class Validate(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/transforms/writer_aux.pyi b/stubs/docutils/docutils/transforms/writer_aux.pyi new file mode 100644 index 000000000000..38523f07319e --- /dev/null +++ b/stubs/docutils/docutils/transforms/writer_aux.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils.transforms import Transform + +__docformat__: Final = "reStructuredText" + +class Admonitions(Transform): + default_priority: ClassVar[int] + def apply(self) -> None: ... diff --git a/stubs/docutils/docutils/utils/__init__.pyi b/stubs/docutils/docutils/utils/__init__.pyi new file mode 100644 index 000000000000..f076c0f2e8d8 --- /dev/null +++ b/stubs/docutils/docutils/utils/__init__.pyi @@ -0,0 +1,131 @@ +import optparse +from _typeshed import StrPath, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, Sequence +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypeVar +from typing_extensions import deprecated + +from docutils import ApplicationError, DataError, nodes +from docutils.frontend import Values +from docutils.io import ErrorOutput, FileOutput +from docutils.nodes import document, unescape as unescape + +_T = TypeVar("_T") +_Observer: TypeAlias = Callable[[nodes.system_message], object] +_SystemMessageLevel: TypeAlias = Literal[0, 1, 2, 3, 4] + +__docformat__: Final = "reStructuredText" + +class DependencyList: + list: list[str] + file: FileOutput | None + def __init__(self, output_file: str | None = None, dependencies: Iterable[str] = ()) -> None: ... + def set_output(self, output_file: str | None) -> None: ... + def add(self, *paths: str) -> None: ... + def close(self) -> None: ... + +class SystemMessagePropagation(ApplicationError): ... + +class Reporter: + get_source_and_line: Callable[[int | None], tuple[StrPath | None, int | None]] + levels: Final[Sequence[str]] + + DEBUG_LEVEL: Final = 0 + INFO_LEVEL: Final = 1 + WARNING_LEVEL: Final = 2 + ERROR_LEVEL: Final = 3 + SEVERE_LEVEL: Final = 4 + + stream: ErrorOutput + encoding: str + observers: list[_Observer] + max_level: int + def __init__( + self, + source: str, + report_level: int, + halt_level: int, + stream: SupportsWrite[str] | SupportsWrite[bytes] | str | bool | None = None, + debug: bool = False, + encoding: str | None = None, + error_handler: str = "backslashreplace", + ) -> None: ... + + source: str + error_handler: str + debug_flag: bool + report_level: _SystemMessageLevel + halt_level: int + def attach_observer(self, observer: _Observer) -> None: ... + def detach_observer(self, observer: _Observer) -> None: ... + def notify_observers(self, message: nodes.system_message) -> None: ... + def system_message( + self, + level: int, + message: str | Exception, + *children: nodes.Node, + base_node: nodes.Node = ..., + source: str = ..., + **kwargs, + ) -> nodes.system_message: ... + def debug( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def info( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def warning( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def error( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + def severe( + self, message: str | Exception, *children: nodes.Node, base_node: nodes.Node = ..., source: str = ..., **kwargs + ) -> nodes.system_message: ... + +class SystemMessage(ApplicationError): + level: _SystemMessageLevel + def __init__(self, system_message: object, level: _SystemMessageLevel): ... + +def new_reporter(source_path: str, settings: optparse.Values) -> Reporter: ... +def new_document(source_path: str, settings: optparse.Values | None = None) -> document: ... + +class ExtensionOptionError(DataError): ... +class BadOptionError(ExtensionOptionError): ... +class BadOptionDataError(ExtensionOptionError): ... +class DuplicateOptionError(ExtensionOptionError): ... + +def extract_extension_options( + field_list: nodes.field_list, options_spec: Mapping[str, Callable[[str], Any]] +) -> dict[str, Any]: ... +def extract_options(field_list: nodes.field_list) -> list[tuple[str, str]]: ... +def assemble_option_dict( + option_list: Iterable[tuple[str, str]], options_spec: Mapping[str, Callable[[str], Any]] +) -> dict[str, Any]: ... + +class NameValueError(DataError): ... + +@deprecated("Deprecated and will be removed in Docutils 1.0.") +def decode_path(path: str) -> str: ... +def extract_name_value(line: str) -> list[tuple[str, str]]: ... +def clean_rcs_keywords(paragraph: nodes.paragraph, keyword_substitutions: Iterable[tuple[Pattern[str], str]]) -> None: ... +def relative_path(source: StrPath | None, target: StrPath) -> str: ... +@deprecated("Deprecated and will be removed in Docutils 1.0. Use `get_stylesheet_list()` instead.") +def get_stylesheet_reference(settings: Values, relative_to: StrPath | None = None) -> str: ... +def get_stylesheet_list(settings: Values) -> list[str]: ... +def find_file_in_dirs(path: StrPath, dirs: Iterable[StrPath]) -> str: ... +def get_trim_footnote_ref_space(settings: Values) -> bool: ... +def get_source_line(node: nodes.Node) -> tuple[str, int]: ... +def escape2null(text: str) -> str: ... +def split_escaped_whitespace(text: str) -> list[str]: ... +def strip_combining_chars(text: str) -> str: ... +def find_combining_chars(text: str) -> list[int]: ... +def column_indices(text: str) -> list[int]: ... + +east_asian_widths: dict[str, int] + +def column_width(text: str) -> int: ... +def uniq(L: list[_T]) -> list[_T]: ... +def normalize_language_tag(tag: str) -> list[str]: ... +def xml_declaration(encoding: str | None = None) -> str: ... diff --git a/stubs/docutils/docutils/utils/_roman_numerals.pyi b/stubs/docutils/docutils/utils/_roman_numerals.pyi new file mode 100644 index 000000000000..0d7b27baff83 --- /dev/null +++ b/stubs/docutils/docutils/utils/_roman_numerals.pyi @@ -0,0 +1,30 @@ +from typing import Final, final +from typing_extensions import Self + +__all__ = ("MAX", "MIN", "InvalidRomanNumeralError", "OutOfRangeError", "RomanNumeral") + +MIN: Final = 1 +MAX: Final = 4_999 + +@final +class OutOfRangeError(TypeError): ... + +@final +class InvalidRomanNumeralError(ValueError): + def __init__(self, value: str, *args: object) -> None: ... + +@final +class RomanNumeral: + __slots__ = ("_value",) + def __init__(self, value: int, /) -> None: ... + def __int__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __setattr__(self, key: str, value: object) -> None: ... + def to_uppercase(self) -> str: ... + def to_lowercase(self) -> str: ... + @classmethod + def from_string(cls, string: str, /) -> Self: ... + +_ROMAN_NUMERAL_PREFIXES: Final[list[tuple[int, str, str]]] diff --git a/stubs/docutils/docutils/utils/code_analyzer.pyi b/stubs/docutils/docutils/utils/code_analyzer.pyi new file mode 100644 index 000000000000..e778c7db6afd --- /dev/null +++ b/stubs/docutils/docutils/utils/code_analyzer.pyi @@ -0,0 +1,28 @@ +from collections.abc import Generator, Iterable +from typing import Final, Literal, TypeAlias + +from docutils import ApplicationError + +_TokenNames: TypeAlias = Literal["long", "short", "none"] + +__docformat__: Final = "reStructuredText" +with_pygments: bool +unstyled_tokens: list[str] + +class LexerError(ApplicationError): ... + +class Lexer: + code: str + language: str + tokennames: _TokenNames + lexer: Lexer | None + def __init__(self, code: str, language: str, tokennames: _TokenNames = "short") -> None: ... + def merge(self, tokens: Iterable[tuple[_TokenNames, str]]) -> Generator[tuple[_TokenNames, str]]: ... + def __iter__(self) -> Generator[tuple[list[str], str]]: ... + +class NumberLines: + tokens: Iterable[tuple[list[str], str]] + startline: int + fmt_str: str + def __init__(self, tokens: Iterable[tuple[list[str], str]], startline: int, endline: int) -> None: ... + def __iter__(self) -> Generator[tuple[list[str], str]]: ... diff --git a/stubs/docutils/docutils/utils/math/__init__.pyi b/stubs/docutils/docutils/utils/math/__init__.pyi new file mode 100644 index 000000000000..cfe920e0bbc7 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/__init__.pyi @@ -0,0 +1,13 @@ +from typing import Final, Literal + +from docutils.nodes import Node + +__docformat__: Final = "reStructuredText" + +class MathError(ValueError): + details: list[Node] + def __init__(self, msg: object, details: list[Node] = []) -> None: ... + +def toplevel_code(code: str) -> str: ... +def pick_math_environment(code: str, numbered: bool = False) -> Literal["align*", "equation*", "align", "equation"]: ... +def wrap_math_code(code: str, as_block: bool | None) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/latex2mathml.pyi b/stubs/docutils/docutils/utils/math/latex2mathml.pyi new file mode 100644 index 000000000000..8adda7596f3a --- /dev/null +++ b/stubs/docutils/docutils/utils/math/latex2mathml.pyi @@ -0,0 +1,44 @@ +from collections.abc import Iterable + +from docutils.utils.math.mathml_elements import MathElement, mover, msub, msubsup, msup, mtd, munder, munderover + +letters: dict[str, str] +ordinary: dict[str, str] +greek_capitals: dict[str, str] +functions: dict[str, str | None] +modulo_functions: dict[str, tuple[bool, bool, bool, str]] +math_alphabets: dict[str, str] +stretchables: dict[str, str] +operators: dict[str, str] +thick_operators: dict[str, str] +small_operators: dict[str, str] +movablelimits: tuple[str, ...] +spaces: dict[str, str] +accents: dict[str, str] +over: dict[str, tuple[str, float]] +under: dict[str, tuple[str, float]] +anomalous_chars: dict[str, str] +mathbb: dict[str, str] +matrices: dict[str, tuple[str, str]] +layout_styles: dict[str, dict[str, bool | int]] +fractions: dict[str, dict[str, bool | int | str] | dict[str, bool | int] | dict[str, int]] +delimiter_sizes: list[str] +bigdelimiters: dict[str, int] + +def tex_cmdname(string: str) -> tuple[str, str]: ... +def tex_number(string: str) -> tuple[str, str]: ... +def tex_token(string: str) -> tuple[str, str]: ... +def tex_group(string: str) -> tuple[str, str]: ... +def tex_token_or_group(string: str) -> tuple[str, str]: ... +def tex_optarg(string: str) -> tuple[str, str]: ... +def parse_latex_math(root: MathElement, source: str) -> MathElement: ... +def handle_cmd(name: str, node: MathElement, string: str) -> tuple[MathElement, str]: ... +def handle_math_alphabet(name: str, node: MathElement, string: str) -> tuple[MathElement, str]: ... +def handle_script_or_limit( + node: MathElement, c: str, limits: str = "" +) -> munderover | msubsup | munder | msub | mover | msup: ... +def begin_environment(node: MathElement, string: str) -> tuple[mtd, str]: ... +def end_environment(node: MathElement, string: str) -> tuple[MathElement, str]: ... +def tex_equation_columns(rows: Iterable[str]) -> int: ... +def align_attributes(rows: Iterable[str]) -> dict[str, str | bool]: ... +def tex2mathml(tex_math: str, as_block: bool = False) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/math2html.pyi b/stubs/docutils/docutils/utils/math/math2html.pyi new file mode 100644 index 000000000000..0972842a9ad0 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/math2html.pyi @@ -0,0 +1,638 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import ClassVar, Final, TextIO, TypeVar + +_T = TypeVar("_T") + +__docformat__: Final = "reStructuredText" +__version__: Final[str] + +class Trace: + debugmode: ClassVar[bool] + quietmode: ClassVar[bool] + showlinesmode: ClassVar[bool] + prefix: ClassVar[str | None] + @classmethod + def debug(cls, message: str) -> None: ... + @classmethod + def message(cls, message: str) -> None: ... + @classmethod + def error(cls, message: str) -> None: ... + @classmethod + def show(cls, message: str, channel: TextIO) -> None: ... + +class ContainerConfig: + extracttext: ClassVar[dict[str, list[str]]] + +class EscapeConfig: + chars: ClassVar[dict[str, str]] + entities: ClassVar[dict[str, str]] + +class FormulaConfig: + alphacommands: ClassVar[dict[str, str]] + array: ClassVar[dict[str, str]] + bigbrackets: ClassVar[dict[str, list[str]]] + bracketcommands: ClassVar[dict[str, str]] + combiningfunctions: ClassVar[dict[str, str]] + commands: ClassVar[dict[str, str]] + cmddict: ClassVar[dict[str, str]] + oversetfunctions: ClassVar[dict[str, str]] + undersetfunctions: ClassVar[dict[str, str]] + endings: ClassVar[dict[str, str]] + environments: ClassVar[dict[str, list[str]]] + fontfunctions: ClassVar[dict[str, str]] + hybridfunctions: ClassVar[dict[str, list[str]]] + hybridsizes: ClassVar[dict[str, str]] + labelfunctions: ClassVar[dict[str, str]] + limitcommands: ClassVar[dict[str, str]] + modified: ClassVar[dict[str, str]] + onefunctions: ClassVar[dict[str, str]] + spacedcommands: ClassVar[dict[str, str]] + starts: ClassVar[dict[str, str]] + symbolfunctions: ClassVar[dict[str, str]] + textfunctions: ClassVar[dict[str, str]] + unmodified: ClassVar[dict[str, list[str]]] + key: str + value: str + +class CommandLineParser: + options: Incomplete + def __init__(self, options) -> None: ... + def parseoptions(self, args): ... + def readoption(self, args): ... + def readquoted(self, args, initial): ... + def readequalskey(self, arg, args): ... + +class Options: + location: Incomplete + debug: bool + quiet: bool + version: bool + help: bool + simplemath: bool + showlines: bool + branches: Incomplete + def parseoptions(self, args) -> None: ... + def processoptions(self) -> None: ... + def usage(self) -> None: ... + def showoptions(self) -> None: ... + def showversion(self) -> None: ... + +class Cloner: + @classmethod + def clone(cls, original: _T) -> _T: ... + @classmethod + def create(cls, type: type[_T]) -> _T: ... + +class ContainerExtractor: + allowed: Incomplete + extracted: Incomplete + def __init__(self, config) -> None: ... + def extract(self, container): ... + def process(self, container, lst) -> None: ... + def safeclone(self, container): ... + +class Parser: + begin: int + parameters: Incomplete + def __init__(self) -> None: ... + def parseheader(self, reader): ... + def parseparameter(self, reader) -> None: ... + def parseending(self, reader, process) -> None: ... + def parsecontainer(self, reader, contents) -> None: ... + +class LoneCommand(Parser): + def parse(self, reader): ... + +class TextParser(Parser): + stack: Incomplete + ending: Incomplete + endings: Incomplete + def __init__(self, container) -> None: ... + def parse(self, reader): ... + def isending(self, reader): ... + +class ExcludingParser(Parser): + def parse(self, reader): ... + +class BoundedParser(ExcludingParser): + def parse(self, reader): ... + +class BoundedDummy(Parser): + def parse(self, reader): ... + +class StringParser(Parser): + begin: Incomplete + def parseheader(self, reader): ... + def parse(self, reader): ... + +class ContainerOutput: + def gethtml(self, container) -> None: ... + def isempty(self): ... + +class EmptyOutput(ContainerOutput): + def gethtml(self, container): ... + def isempty(self): ... + +class FixedOutput(ContainerOutput): + def gethtml(self, container): ... + +class ContentsOutput(ContainerOutput): + def gethtml(self, container): ... + +class TaggedOutput(ContentsOutput): + tag: Incomplete + breaklines: bool + empty: bool + def settag(self, tag, breaklines: bool = False, empty: bool = False): ... + def setbreaklines(self, breaklines): ... + def gethtml(self, container): ... + def open(self, container): ... + def close(self, container): ... + def selfclosing(self, container): ... + def checktag(self, container): ... + +class FilteredOutput(ContentsOutput): + filters: Incomplete + def __init__(self) -> None: ... + def addfilter(self, original, replacement) -> None: ... + def gethtml(self, container): ... + def filter(self, line): ... + +class StringOutput(ContainerOutput): + def gethtml(self, container): ... + +class Globable: + leavepending: bool + endinglist: Incomplete + def __init__(self) -> None: ... + def checkbytemark(self) -> None: ... + def isout(self): ... + def current(self): ... + def checkfor(self, string): ... + def finished(self): ... + def skipcurrent(self): ... + def glob(self, currentcheck): ... + def globalpha(self): ... + def globnumber(self): ... + def isidentifier(self): ... + def globidentifier(self): ... + def isvalue(self): ... + def globvalue(self): ... + def skipspace(self): ... + def globincluding(self, magicchar): ... + def globexcluding(self, excluded): ... + def pushending(self, ending, optional: bool = False) -> None: ... + def popending(self, expected=None): ... + def nextending(self): ... + +class EndingList: + endings: Incomplete + def __init__(self) -> None: ... + def add(self, ending, optional: bool = False) -> None: ... + def pickpending(self, pos) -> None: ... + def checkin(self, pos): ... + def pop(self, pos): ... + def findending(self, pos): ... + def checkpending(self) -> None: ... + +class PositionEnding: + ending: Incomplete + optional: Incomplete + def __init__(self, ending, optional) -> None: ... + def checkin(self, pos): ... + +class Position(Globable): + def __init__(self) -> None: ... + def skip(self, string) -> None: ... + def identifier(self): ... + def extract(self, length) -> None: ... + def checkfor(self, string): ... + def checkforlower(self, string): ... + def skipcurrent(self): ... + def __next__(self): ... + def checkskip(self, string): ... + def error(self, message) -> None: ... + +class TextPosition(Position): + pos: int + text: Incomplete + def __init__(self, text) -> None: ... + def skip(self, string) -> None: ... + def identifier(self): ... + def isout(self): ... + def current(self): ... + def extract(self, length): ... + +class Container: + partkey: Incomplete + parent: Incomplete + begin: Incomplete + contents: Incomplete + def __init__(self) -> None: ... + def process(self) -> None: ... + def gethtml(self): ... + def escape(self, line, replacements={"&": "&", "<": "<", ">": ">"}): ... + def escapeentities(self, line): ... + def searchall(self, type): ... + def searchremove(self, type): ... + def searchprocess(self, type, process): ... + def locateprocess(self, locate, process) -> None: ... + def recursivesearch(self, locate, recursive, process) -> None: ... + def extracttext(self): ... + def group(self, index, group, isingroup) -> None: ... + def remove(self, index) -> None: ... + def tree(self, level: int = 0) -> None: ... + def getparameter(self, name): ... + def getparameterlist(self, name): ... + def hasemptyoutput(self): ... + +class BlackBox(Container): + parser: Incomplete + output: Incomplete + contents: Incomplete + def __init__(self) -> None: ... + +class StringContainer(Container): + parsed: Incomplete + parser: Incomplete + output: Incomplete + string: str + def __init__(self) -> None: ... + def process(self) -> None: ... + def replacespecial(self, line): ... + def changeline(self, line): ... + def extracttext(self): ... + +class Constant(StringContainer): + contents: Incomplete + string: Incomplete + output: Incomplete + def __init__(self, text) -> None: ... + +class DocumentParameters: + displaymode: bool + +class FormulaParser(Parser): + begin: Incomplete + def parseheader(self, reader): ... + def parsetype(self, reader): ... + def parse(self, reader): ... + def parseformula(self, reader): ... + def parsesingleliner(self, reader, start, ending): ... + def parsemultiliner(self, reader, start, ending): ... + +class FormulaBit(Container): + type: str | None + size: int + original: str + contents: Incomplete + output: Incomplete + def __init__(self) -> None: ... + factory: Incomplete + def setfactory(self, factory): ... + def add(self, bit) -> None: ... + def skiporiginal(self, string, pos) -> None: ... + def computesize(self): ... + def clone(self): ... + +class TaggedBit(FormulaBit): + output: Incomplete + def constant(self, constant, tag): ... + contents: Incomplete + def complete(self, contents, tag, breaklines: bool = False): ... + def selfcomplete(self, tag): ... + +class FormulaConstant(Constant): + original: Incomplete + size: int + type: str | None + def __init__(self, string) -> None: ... + def computesize(self): ... + def clone(self): ... + +class RawText(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class FormulaSymbol(FormulaBit): + modified: Incomplete + unmodified: Incomplete + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + def addsymbol(self, symbol, pos) -> None: ... + +class FormulaNumber(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos): ... + +class Comment(FormulaBit): + start: Incomplete + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class WhiteSpace(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class Bracket(FormulaBit): + start: Incomplete + ending: Incomplete + inner: Incomplete + def __init__(self) -> None: ... + def detect(self, pos): ... + def parsebit(self, pos): ... + def parsetext(self, pos): ... + def parseliteral(self, pos): ... + def parsecomplete(self, pos, innerparser) -> None: ... + def innerformula(self, pos) -> None: ... + def innertext(self, pos) -> None: ... + literal: str + def innerliteral(self, pos) -> None: ... + +class SquareBracket(Bracket): + start: Incomplete + ending: Incomplete + def clone(self): ... + +class MathsProcessor: + def process(self, contents, index) -> None: ... + +class FormulaProcessor: + processors: Incomplete + def process(self, bit) -> None: ... + def processcontents(self, bit) -> None: ... + def processinsides(self, bit) -> None: ... + def traversewhole(self, formula) -> None: ... + def traverse(self, bit) -> Generator[Incomplete, Incomplete]: ... + def italicize(self, bit, contents) -> None: ... + +class Formula(Container): + parser: Incomplete + output: Incomplete + def __init__(self) -> None: ... + def process(self) -> None: ... + contents: Incomplete + def classic(self) -> None: ... + def parse(self, pos): ... + header: Incomplete + def parsedollarinline(self, pos) -> None: ... + def parsedollarblock(self, pos) -> None: ... + parsed: Incomplete + def parsedollar(self, pos) -> None: ... + def parseinlineto(self, pos, limit) -> None: ... + def parseblockto(self, pos, limit) -> None: ... + def parseupto(self, pos, limit): ... + +class WholeFormula(FormulaBit): + def detect(self, pos): ... + def parsebit(self, pos) -> None: ... + +class FormulaFactory: + types: Incomplete + skippedtypes: Incomplete + defining: bool + instances: Incomplete + def __init__(self) -> None: ... + def detecttype(self, type, pos): ... + def instance(self, type): ... + def create(self, type): ... + def clearskipped(self, pos) -> None: ... + def skipany(self, pos): ... + def parseany(self, pos): ... + def parsetype(self, type, pos): ... + def parseformula(self, formula): ... + +class FormulaCommand(FormulaBit): + types: Incomplete + start: Incomplete + commandmap: ClassVar[dict[str, str] | dict[str, list[str]] | None] + def detect(self, pos): ... + output: Incomplete + def parsebit(self, pos): ... + def parsewithcommand(self, command, pos): ... + def parsecommandtype(self, command, type, pos): ... + def extractcommand(self, pos): ... + def emptycommand(self, pos): ... + def parseupgreek(self, command, pos): ... + +class CommandBit(FormulaCommand): + command: Incomplete + translated: Incomplete + def setcommand(self, command) -> None: ... + def parseparameter(self, pos): ... + def parsesquare(self, pos): ... + def parseliteral(self, pos): ... + def parsesquareliteral(self, pos): ... + def parsetext(self, pos): ... + +class EmptyCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class SpacedCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class AlphaCommand(EmptyCommand): + commandmap: ClassVar[dict[str, str]] + greek_capitals: Incomplete + def parsebit(self, pos) -> None: ... + +class OneParamFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + simplified: bool + output: Incomplete + def parsebit(self, pos) -> None: ... + html: Incomplete + def simplifyifpossible(self) -> None: ... + +class SymbolFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + def detect(self, pos): ... + output: Incomplete + def parsebit(self, pos) -> None: ... + +class TextFunction(CommandBit): + commandmap: ClassVar[dict[str, str]] + output: Incomplete + def parsebit(self, pos) -> None: ... + def process(self) -> None: ... + +class FontFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def process(self) -> None: ... + +class BigBracket: + size: Incomplete + original: Incomplete + alignment: Incomplete + pieces: Incomplete + def __init__(self, size, bracket, alignment: str = "l") -> None: ... + def getpiece(self, index): ... + def getpiece1(self, index): ... + def getpiece3(self, index): ... + def getpiece4(self, index): ... + def getcell(self, index): ... + def getcontents(self): ... + def getsinglebracket(self): ... + +class FormulaEquation(CommandBit): + piece: str + output: Incomplete + def parsebit(self, pos) -> None: ... + +class FormulaCell(FormulaCommand): + alignment: Incomplete + output: Incomplete + def setalignment(self, alignment): ... + def parsebit(self, pos) -> None: ... + +class FormulaRow(FormulaCommand): + cellseparator: Incomplete + alignments: Incomplete + output: Incomplete + def setalignments(self, alignments): ... + def parsebit(self, pos) -> None: ... + def createcell(self, index): ... + +class MultiRowFormula(CommandBit): + rows: Incomplete + size: Incomplete + def parserows(self, pos) -> None: ... + def iteraterows(self, pos) -> Generator[Incomplete]: ... + def addempty(self) -> None: ... + def addrow(self, row) -> None: ... + +class FormulaArray(MultiRowFormula): + piece: str + output: Incomplete + def parsebit(self, pos) -> None: ... + valign: str + alignments: Incomplete + def parsealignments(self, pos) -> None: ... + +class FormulaMatrix(MultiRowFormula): + piece: str + output: Incomplete + valign: str + alignments: Incomplete + def parsebit(self, pos) -> None: ... + +class FormulaCases(MultiRowFormula): + piece: str + output: Incomplete + alignments: Incomplete + contents: Incomplete + def parsebit(self, pos) -> None: ... + +class EquationEnvironment(MultiRowFormula): + output: Incomplete + alignments: Incomplete + def parsebit(self, pos) -> None: ... + +class BeginCommand(CommandBit): + commandmap: ClassVar[dict[str, str]] + types: Incomplete + size: Incomplete + def parsebit(self, pos) -> None: ... + def findbit(self, piece): ... + +class CombiningFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def parsebit(self, pos) -> None: ... + def parsesingleparameter(self, pos): ... + +class OversetFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + symbol: Incomplete + parameter: Incomplete + output: Incomplete + def parsebit(self, pos) -> None: ... + +class UndersetFunction(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + symbol: Incomplete + parameter: Incomplete + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitCommand(EmptyCommand): + commandmap: ClassVar[dict[str, str]] + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitPreviousCommand(LimitCommand): + commandmap: ClassVar[None] # type: ignore[assignment] + output: Incomplete + def parsebit(self, pos) -> None: ... + +class LimitsProcessor(MathsProcessor): + def process(self, contents, index) -> None: ... + def checklimits(self, contents, index): ... + def limitsahead(self, contents, index) -> None: ... + def modifylimits(self, contents, index) -> None: ... + def getlimit(self, contents, index): ... + def modifyscripts(self, contents, index) -> None: ... + def checkscript(self, contents, index): ... + def checkcommand(self, contents, index, type): ... + def getscript(self, contents, index): ... + +class BracketCommand(OneParamFunction): + commandmap: ClassVar[dict[str, str]] + def parsebit(self, pos) -> None: ... + original: Incomplete + command: Incomplete + contents: Incomplete + def create(self, direction, character): ... + +class BracketProcessor(MathsProcessor): + def process(self, contents, index): ... + def processleft(self, contents, index) -> None: ... + def checkleft(self, contents, index): ... + def checkright(self, contents, index): ... + def checkdirection(self, bit, command): ... + def findright(self, contents, index): ... + def findmax(self, contents, leftindex, rightindex): ... + def resize(self, command, size) -> None: ... + +class ParameterDefinition: + parambrackets: ClassVar[list[tuple[str, str]]] + name: str + literal: bool + optional: bool + value: Incomplete + literalvalue: Incomplete + def __init__(self) -> None: ... + def parse(self, pos): ... + def read(self, pos, function) -> None: ... + +class ParameterFunction(CommandBit): + params: Incomplete + def readparams(self, readtemplate, pos) -> None: ... + def paramdefs(self, readtemplate) -> Generator[Incomplete]: ... + def getparam(self, name): ... + def getvalue(self, name): ... + def getliteralvalue(self, name): ... + +class HybridFunction(ParameterFunction): + commandmap: ClassVar[dict[str, list[str]]] + contents: Incomplete + def parsebit(self, pos) -> None: ... + def writeparams(self, writetemplate): ... + def writepos(self, pos): ... + def writeparam(self, pos): ... + def writefunction(self, pos): ... + def readtag(self, pos): ... + def writebracket(self, direction, character): ... + size: Incomplete + def computehybridsize(self) -> None: ... + +class HybridSize: + configsizes: ClassVar[dict[str, str]] + def getsize(self, function): ... + +def math2html(formula): ... +def main() -> None: ... diff --git a/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi b/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi new file mode 100644 index 000000000000..15aa3be4ed02 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/mathalphabet2unichar.pyi @@ -0,0 +1,13 @@ +from typing import Final + +mathbb: Final[dict[str, str]] +mathbf: Final[dict[str, str]] +mathbfit: Final[dict[str, str]] +mathcal: Final[dict[str, str]] +mathfrak: Final[dict[str, str]] +mathit: Final[dict[str, str]] +mathsf: Final[dict[str, str]] +mathsfbf: Final[dict[str, str]] +mathsfbfit: Final[dict[str, str]] +mathsfit: Final[dict[str, str]] +mathtt: Final[dict[str, str]] diff --git a/stubs/docutils/docutils/utils/math/mathml_elements.pyi b/stubs/docutils/docutils/utils/math/mathml_elements.pyi new file mode 100644 index 000000000000..d55220a93166 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/mathml_elements.pyi @@ -0,0 +1,85 @@ +import numbers +import xml.etree.ElementTree as ET +from collections.abc import Iterable +from typing import ClassVar, Final, SupportsIndex, overload +from typing_extensions import Self + +__docformat__: Final = "reStructuredText" +GLOBAL_ATTRIBUTES: Final[tuple[str, ...]] + +class MathElement(ET.Element): + nchildren: ClassVar[int | None] + parent: MathElement | None + def __init__(self, *children, **attributes: object) -> None: ... # attributes is passed to self.a_str method + @staticmethod + def a_str(v: object) -> str: ... + def set(self, key: str, value: object) -> None: ... # value is passed to self.a_str method + + @overload # type: ignore[override] + def __setitem__(self, key: SupportsIndex, value: MathElement) -> None: ... + @overload # type: ignore[override] + def __setitem__(self, key: slice, value: Iterable[MathElement]) -> None: ... + + def is_full(self) -> bool: ... + def close(self) -> MathElement | None: ... + def append(self, element: MathElement) -> Self: ... # type: ignore[override] + def extend(self, elements: Iterable[MathElement]) -> Self: ... # type: ignore[override] + def pop(self, index: int = -1): ... + def in_block(self) -> bool: ... + def indent_xml(self, space: str = " ", level: int = 0) -> None: ... + def unindent_xml(self) -> None: ... + def toxml(self, encoding: str | None = None) -> str: ... + +class MathRow(MathElement): ... + +class MathSchema(MathElement): + nchildren: ClassVar[int] + switch: bool + def __init__(self, *children, switch: bool = False, **kwargs) -> None: ... + +class MathToken(MathElement): + nchildren: ClassVar[int] + text: str + def __init__(self, text: str | numbers.Number, **attributes: object) -> None: ... + +class math(MathRow): ... +class mtext(MathToken): ... +class mi(MathToken): ... +class mn(MathToken): ... +class mo(MathToken): ... + +class mspace(MathElement): + nchildren: ClassVar[int] + +class mrow(MathRow): + def transfer_attributes(self, other) -> None: ... + +class mfrac(MathSchema): ... + +class msqrt(MathRow): + nchildren: ClassVar[int] + +class mroot(MathSchema): ... +class mstyle(MathRow): ... +class merror(MathRow): ... + +class menclose(MathRow): + nchildren: ClassVar[int] + +class mpadded(MathRow): ... + +class mphantom(MathRow): + nchildren: ClassVar[int] + +class msub(MathSchema): ... +class msup(MathSchema): ... + +class msubsup(MathSchema): + nchildren: ClassVar[int] + +class munder(msub): ... +class mover(msup): ... +class munderover(msubsup): ... +class mtable(MathElement): ... +class mtr(MathRow): ... +class mtd(MathRow): ... diff --git a/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi b/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi new file mode 100644 index 000000000000..c15fde2125f9 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/tex2mathml_extern.pyi @@ -0,0 +1,9 @@ +from typing import Final + +__docformat__: Final = "reStructuredText" +document_template: Final[str] + +def blahtexml(math_code: str, as_block: bool = False) -> str: ... +def latexml(math_code: str, as_block: bool = False) -> str: ... +def pandoc(math_code: str, as_block: bool = False) -> str: ... +def ttm(math_code: str, as_block: bool = False) -> str: ... diff --git a/stubs/docutils/docutils/utils/math/tex2unichar.pyi b/stubs/docutils/docutils/utils/math/tex2unichar.pyi new file mode 100644 index 000000000000..3cbd0cfbcb54 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/tex2unichar.pyi @@ -0,0 +1,14 @@ +mathaccent: dict[str, str] +mathalpha: dict[str, str] +mathbin: dict[str, str] +mathclose: dict[str, str] +mathfence: dict[str, str] +mathop: dict[str, str] +mathopen: dict[str, str] +mathord: dict[str, str] +mathover: dict[str, str] +mathpunct: dict[str, str] +mathradical: dict[str, str] +mathrel: dict[str, str] +mathunder: dict[str, str] +space: dict[str, str] diff --git a/stubs/docutils/docutils/utils/math/unichar2tex.pyi b/stubs/docutils/docutils/utils/math/unichar2tex.pyi new file mode 100644 index 000000000000..3ef39b9d9bf0 --- /dev/null +++ b/stubs/docutils/docutils/utils/math/unichar2tex.pyi @@ -0,0 +1 @@ +uni2tex_table: dict[int, str] diff --git a/stubs/docutils/docutils/utils/punctuation_chars.pyi b/stubs/docutils/docutils/utils/punctuation_chars.pyi new file mode 100644 index 000000000000..9d593c137519 --- /dev/null +++ b/stubs/docutils/docutils/utils/punctuation_chars.pyi @@ -0,0 +1,9 @@ +from typing import Final + +openers: Final[str] +closers: Final[str] +delimiters: Final[str] +closing_delimiters: Final[str] +quote_pairs: dict[str, str] + +def match_chars(c1: str, c2: str) -> bool: ... diff --git a/stubs/docutils/docutils/utils/smartquotes.pyi b/stubs/docutils/docutils/utils/smartquotes.pyi new file mode 100644 index 000000000000..1d68592d288c --- /dev/null +++ b/stubs/docutils/docutils/utils/smartquotes.pyi @@ -0,0 +1,44 @@ +from collections.abc import Generator, Iterable +from re import Pattern +from typing import ClassVar, Final, Literal + +options: Final[str] + +class smartchars: + endash: ClassVar[str] + emdash: ClassVar[str] + ellipsis: ClassVar[str] + apostrophe: ClassVar[str] + quotes: ClassVar[dict[str, str | tuple[str, str, str, str]]] + language: str + def __init__(self, language: str = "en") -> None: ... + +class RegularExpressions: + START_SINGLE: ClassVar[Pattern[str]] + START_DOUBLE: ClassVar[Pattern[str]] + ADJACENT_1: ClassVar[Pattern[str]] + ADJACENT_2: ClassVar[Pattern[str]] + OPEN_SINGLE: ClassVar[Pattern[str]] + OPEN_DOUBLE: ClassVar[Pattern[str]] + DECADE: ClassVar[Pattern[str]] + APOSTROPHE: ClassVar[Pattern[str]] + OPENING_SECONDARY: ClassVar[Pattern[str]] + CLOSING_SECONDARY: ClassVar[Pattern[str]] + OPENING_PRIMARY: ClassVar[Pattern[str]] + CLOSING_PRIMARY: ClassVar[Pattern[str]] + +regexes: RegularExpressions +default_smartypants_attr: Final = "1" + +def smartyPants(text: str, attr="1", language: str = "en") -> str: ... +def educate_tokens(text_tokens: Iterable[tuple[str, str]], attr="1", language: str = "en") -> Generator[str]: ... +def educateQuotes(text: str, language: str = "en") -> str: ... +def educateBackticks(text: str, language: str = "en") -> str: ... +def educateSingleBackticks(text: str, language: str = "en") -> str: ... +def educateDashes(text: str) -> str: ... +def educateDashesOldSchool(text: str) -> str: ... +def educateDashesOldSchoolInverted(text: str) -> str: ... +def educateEllipses(text: str) -> str: ... +def stupefyEntities(text: str, language: str = "en") -> str: ... +def processEscapes(text: str, restore: bool = False) -> str: ... +def tokenize(text: str) -> Generator[tuple[Literal["tag", "text"], str]]: ... diff --git a/stubs/docutils/docutils/utils/urischemes.pyi b/stubs/docutils/docutils/utils/urischemes.pyi new file mode 100644 index 000000000000..5e6f8a70a45d --- /dev/null +++ b/stubs/docutils/docutils/utils/urischemes.pyi @@ -0,0 +1 @@ +schemes: dict[str, str] diff --git a/stubs/docutils/docutils/writers/__init__.pyi b/stubs/docutils/docutils/writers/__init__.pyi new file mode 100644 index 000000000000..3fa0f555d1ae --- /dev/null +++ b/stubs/docutils/docutils/writers/__init__.pyi @@ -0,0 +1,92 @@ +from _typeshed import StrPath +from pathlib import Path +from typing import Any, Final, Generic, TypedDict, TypeVar, type_check_only +from typing_extensions import Required + +from docutils import Component, nodes +from docutils.frontend import Values +from docutils.io import Output +from docutils.languages import LanguageImporter + +_S = TypeVar("_S") + +__docformat__: Final = "reStructuredText" + +# It would probably be better to specialize writers for subclasses, +# but this gives us all possible Writer items w/o instance checks +@type_check_only +class _WriterParts(TypedDict, total=False): + # Parts Provided by All Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-all-writers + + # See Writer.assemble_parts + whole: Required[str | bytes] + encoding: Required[str] + errors: Required[str] + version: Required[str] + + # Parts Provided by the HTML Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-the-html-writers + + # HTML4 Writer https://docutils.sourceforge.io/docs/api/publisher.html#html4-writer + # + HTML5 Writer https://docutils.sourceforge.io/docs/api/publisher.html#html5-writer + body: str + body_prefix: str + body_pre_docinfo: str + body_suffix: str + docinfo: str + footer: str + fragment: str + head: str + head_prefix: str + header: str + html_body: str + html_head: str + html_prolog: str + html_subtitle: str + html_title: str + meta: str + stylesheet: str + subtitle: str + title: str + # PEP/HTML Writer https://docutils.sourceforge.io/docs/api/publisher.html#pep-html-writer + # + S5/HTML Writer https://docutils.sourceforge.io/docs/api/publisher.html#s5-html-writer + pepnum: str + + # Parts Provided by the (Xe)LaTeX Writers https://docutils.sourceforge.io/docs/api/publisher.html#parts-provided-by-the-xe-latex-writers + + # (commenting out those already included) + abstract: str + # body: str + # body_pre_docinfo: str + dedication: str + # docinfo: str + fallbacks: str + # head_prefix: str + latex_preamble: str + pdfsetup: str + requirements: str + # stylesheet: str + # subtitle: str + # title: str + titledata: str + +class Writer(Component, Generic[_S]): + parts: _WriterParts + language: LanguageImporter | None = None + document: nodes.document | None = None + destination: Output | None = None + output: _S | None = None + def __init__(self) -> None: ... + def write(self, document: nodes.document, destination: Output) -> str | bytes | None: ... + def translate(self) -> None: ... + def assemble_parts(self) -> None: ... + +class UnfilteredWriter(Writer[_S]): ... + +class DoctreeTranslator(nodes.NodeVisitor): + settings: Values + def __init__(self, document: nodes.document) -> None: ... + def uri2path(self, uri: str, output_path: StrPath | None = None) -> Path: ... + +WRITER_ALIASES: Final[dict[str, str]] + +def get_writer_class(writer_name: str) -> type[Writer[Any]]: ... diff --git a/stubs/docutils/docutils/writers/_html_base.pyi b/stubs/docutils/docutils/writers/_html_base.pyi new file mode 100644 index 000000000000..dccf180e85ce --- /dev/null +++ b/stubs/docutils/docutils/writers/_html_base.pyi @@ -0,0 +1,305 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Callable +from re import Pattern +from typing import ClassVar, Final +from typing_extensions import Never + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule + +__docformat__: Final = "reStructuredText" + +class Writer(writers.Writer[str]): + settings_defaults: ClassVar[dict[str, str]] + relative_path_settings: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + visitor_attributes: ClassVar[tuple[str, ...]] + visitor: nodes.NodeVisitor + def translate(self) -> None: ... + def apply_template(self) -> str: ... + def interpolation_dict(self) -> dict[str, str]: ... + def assemble_parts(self) -> None: ... + +class HTMLTranslator(nodes.NodeVisitor): + doctype: ClassVar[str] + doctype_mathml: ClassVar[str] + head_prefix_template: ClassVar[str] + content_type: ClassVar[str] + generator: ClassVar[str] + documenttag_args: ClassVar[dict[str, str]] + mathjax_script: ClassVar[str] + mathjax_url: ClassVar[str] + stylesheet_link: ClassVar[str] + embedded_stylesheet: ClassVar[str] + words_and_spaces: ClassVar[Pattern[str]] + in_word_wrap_point: ClassVar[Pattern[str]] + lang_attribute: ClassVar[str] + special_characters: ClassVar[dict[int, str]] + videotypes: ClassVar[tuple[str, ...]] + attribution_formats: ClassVar[dict[str, tuple[str, str]]] + settings: Values + language: _LanguageModule + initial_header_level: int + image_loading: str + body: list[str] + body_prefix: list[str] + body_pre_docinfo: list[Incomplete] + body_suffix: list[str] + docinfo: list[str] + footer: list[str] + fragment: list[Incomplete] + head: list[Incomplete] + head_prefix: list[Incomplete] + header: list[Incomplete] + html_body: list[Incomplete] + html_head: list[Incomplete] + html_prolog: list[Incomplete] + html_subtitle: list[Incomplete] + html_title: list[Incomplete] + meta: list[Incomplete] + stylesheet: list[Incomplete] + title: list[Incomplete] + subtitle: list[Incomplete] + context: list[Incomplete] + section_level: int + colspecs: list[Incomplete] + compact_p: bool + compact_simple: bool + compact_field_list: bool + in_docinfo: bool + in_sidebar: bool + in_document_title: int + in_mailto: bool + author_in_authors: bool + math_header: list[str] + messages: list[Incomplete] + def __init__(self, document: nodes.document) -> None: ... + def astext(self) -> str: ... + def attval(self, text: str, whitespace: Pattern[str] = ...) -> str: ... + def cloak_email(self, addr: str) -> str: ... + def cloak_mailto(self, uri: str) -> str: ... + def encode(self, text: object) -> str: ... + def image_size(self, node: nodes.image) -> str: ... + def read_size_with_PIL(self, node) -> tuple[int, int] | None: ... + def prepare_svg(self, code: str | bytes, node: nodes.Element, atts: dict[str, Incomplete]) -> str: ... + def stylesheet_call(self, path: StrPath, adjust_path: bool | None = None) -> str: ... + def starttag(self, node: nodes.Element, tagname: str, suffix: str = "\n", empty: bool = False, **attributes) -> str: ... + def emptytag(self, node: nodes.Element, tagname: str, suffix: str = "\n", **attributes) -> str: ... + def report_messages(self, node: nodes.Node) -> None: ... + def set_class_on_child(self, node, class_, index: int = 0) -> None: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition | None = None) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def check_simple_list(self, node: nodes.Node) -> bool: ... + def is_compactable(self, node: nodes.Element) -> bool: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def visit_comment(self, node: nodes.comment, sub: Callable[[str, str], str] = ...) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_docinfo_item(self, node, name: str, meta: bool = True) -> None: ... + def depart_docinfo_item(self) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + math_tags: dict[str, tuple[str, str, list[str]]] + math_output: str | Incomplete + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def section_title_tags(self, node: nodes.Element) -> tuple[str, str]: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... + +class SimpleListChecker(nodes.GenericNodeVisitor): + def visit_list_item(self, node: nodes.list_item) -> None: ... + def pass_node(self, node: nodes.Node) -> None: ... + def ignore_node(self, node: nodes.Node) -> None: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def visit_pending(self, node: nodes.pending) -> None: ... diff --git a/stubs/docutils/docutils/writers/docutils_xml.pyi b/stubs/docutils/docutils/writers/docutils_xml.pyi new file mode 100644 index 000000000000..dfd4096071d4 --- /dev/null +++ b/stubs/docutils/docutils/writers/docutils_xml.pyi @@ -0,0 +1,45 @@ +from collections.abc import Callable +from typing import ClassVar, Final +from xml.sax.handler import ContentHandler +from xml.sax.xmlreader import Locator, XMLReader + +import docutils +from docutils import nodes, writers +from docutils.frontend import Values + +__docformat__: Final = "reStructuredText" + +class RawXmlError(docutils.ApplicationError): ... + +class Writer(writers.Writer[str]): + settings_defaults: ClassVar[dict[str, str]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[XMLTranslator] + visitor: XMLTranslator + +class XMLTranslator(nodes.GenericNodeVisitor): + doctype: ClassVar[str] + generator: ClassVar[str] + xmlparser: ClassVar[XMLReader] + warn: Callable[..., nodes.system_message] + error: Callable[..., nodes.system_message] + settings: Values + indent: str + newline: str + level: int + in_simple: int + fixed_text: int + output: list[str] + the_handle: TestXml + def __init__(self, document: nodes.document) -> None: ... + simple_nodes: ClassVar[tuple[type[nodes.Element], ...]] + def default_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def default_departure(self, node: nodes.Element) -> None: ... # type: ignore[override] + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + +class TestXml(ContentHandler): + locator: Locator + def setDocumentLocator(self, locator: Locator) -> None: ... diff --git a/stubs/docutils/docutils/writers/html4css1/__init__.pyi b/stubs/docutils/docutils/writers/html4css1/__init__.pyi new file mode 100644 index 000000000000..76da0b68d282 --- /dev/null +++ b/stubs/docutils/docutils/writers/html4css1/__init__.pyi @@ -0,0 +1,125 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final + +from docutils import nodes +from docutils.writers import _html_base + +__docformat__: Final = "reStructuredText" + +class Writer(_html_base.Writer): + default_stylesheets: ClassVar[list[str]] + default_stylesheet_dirs: ClassVar[list[str]] + default_template: ClassVar[str] + config_section: ClassVar[str] + translator_class: type[HTMLTranslator] + +class HTMLTranslator(_html_base.HTMLTranslator): + content_type: ClassVar[str] + content_type_mathml: ClassVar[str] + object_image_types: ClassVar[dict[str, str]] + def set_first_last(self, node) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition | None = None) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + author_in_authors: bool + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def is_compactable(self, node: nodes.Element) -> bool: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + in_docinfo: bool + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + docinfo: Incomplete + body: Incomplete + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_docinfo_item(self, node, name, meta: bool = True) -> None: ... + def depart_docinfo_item(self) -> None: ... + def visit_doctest_block(self, node) -> None: ... + def depart_doctest_block(self, node) -> None: ... + def visit_entry(self, node) -> None: ... + def depart_entry(self, node) -> None: ... + compact_p: Incomplete + compact_simple: Incomplete + def visit_enumerated_list(self, node) -> None: ... + def depart_enumerated_list(self, node) -> None: ... + def visit_field(self, node) -> None: ... + def depart_field(self, node) -> None: ... + def visit_field_body(self, node) -> None: ... + def depart_field_body(self, node) -> None: ... + compact_field_list: bool + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def footnote_backrefs(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def should_be_compact_paragraph(self, node: nodes.Element) -> bool: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + in_sidebar: bool + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + in_document_title: int + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + subtitle: list[Incomplete] + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def section_title_tags(self, node: nodes.Element) -> tuple[str, str]: ... + +class SimpleListChecker(_html_base.SimpleListChecker): + def visit_list_item(self, node: nodes.list_item) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... diff --git a/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi b/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi new file mode 100644 index 000000000000..dd59417aa099 --- /dev/null +++ b/stubs/docutils/docutils/writers/html5_polyglot/__init__.pyi @@ -0,0 +1,16 @@ +from pathlib import Path +from typing import ClassVar, Final + +from docutils.writers import _html_base + +__docformat__: Final = "reStructuredText" + +class Writer(_html_base.Writer): + default_stylesheets: ClassVar[list[str]] + default_stylesheet_dirs: ClassVar[list[str]] + default_template: ClassVar[Path] + translator_class: type[HTMLTranslator] + +class HTMLTranslator(_html_base.HTMLTranslator): + supported_block_tags: set[str] + supported_inline_tags: set[str] diff --git a/stubs/docutils/docutils/writers/latex2e/__init__.pyi b/stubs/docutils/docutils/writers/latex2e/__init__.pyi new file mode 100644 index 000000000000..5b75055a0140 --- /dev/null +++ b/stubs/docutils/docutils/writers/latex2e/__init__.pyi @@ -0,0 +1,423 @@ +import re +from _typeshed import Incomplete, StrPath +from collections.abc import Callable, Iterable +from io import TextIOWrapper +from pathlib import Path +from typing import ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Never, deprecated + +from docutils import nodes +from docutils.frontend import Values +from docutils.languages import _LanguageModule +from docutils.utils import Reporter +from docutils.writers import Writer as _Writer + +_K = TypeVar("_K") +_V = TypeVar("_V") + +__docformat__: Final = "reStructuredText" + +LATEX_WRITER_DIR: Final[Path] + +class Writer(_Writer[str]): + default_template: ClassVar[str] + default_template_path: ClassVar[Path] + default_preamble: ClassVar[str] + table_style_values: ClassVar[list[str]] + relative_path_settings: ClassVar[tuple[str, ...]] + settings_defaults: ClassVar[dict[str, int]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + head_parts: ClassVar[tuple[str, ...]] + visitor_attributes: ClassVar[tuple[str, ...]] + translator_class: type[LaTeXTranslator] + +class Babel: + language_codes: ClassVar[dict[str, str]] + warn_msg: ClassVar[str] + active_chars: ClassVar[dict[str, str]] + + reporter: Reporter | None + language: str + otherlanguages: dict[str, str | bool] + setup: list[str] + + def __init__(self, language_code: str, reporter: Reporter | None = None) -> None: ... + def __call__(self) -> str: ... + def language_name(self, language_code: str) -> str: ... + def get_language(self) -> str: ... + +@deprecated("Deprecated and will be removed in Docutils 0.24.") +class SortableDict(dict[_K, _V]): + def sortedkeys(self) -> list[_K]: ... + def sortedvalues(self) -> list[_V]: ... + +class PreambleCmds: + ch: ClassVar[str] + color: ClassVar[str] + float: ClassVar[str] + linking: ClassVar[str] + minitoc: ClassVar[str] + table: ClassVar[str] + table_columnwidth: ClassVar[str] + textcomp: ClassVar[str] + abstract_legacy: ClassVar[str] + admonition_legacy: ClassVar[str] + error_legacy: ClassVar[str] + title_legacy: ClassVar[str] + toc_list: ClassVar[str] + ttem: ClassVar[str] + duclass: ClassVar[str] + providelength: ClassVar[str] + abstract: ClassVar[str] + dedication: ClassVar[str] + docinfo: ClassVar[str] + error: ClassVar[str] + highlight_rules: ClassVar[str] + admonition: ClassVar[str] + fieldlist: ClassVar[str] + footnotes: ClassVar[str] + inline: ClassVar[str] + legend: ClassVar[str] + lineblock: ClassVar[str] + optionlist: ClassVar[str] + rubric: ClassVar[str] + sidebar: ClassVar[str] + title: ClassVar[str] + subtitle: ClassVar[str] + documentsubtitle: ClassVar[str] + titlereference: ClassVar[str] + transition: ClassVar[str] + secnumdepth: ClassVar[str] + rem: ClassVar[str] + vmin: ClassVar[str] + vmax: ClassVar[str] + +fp: TextIOWrapper +line: str +block_name: str +definitions: str + +class CharMaps: + alltt: ClassVar[dict[int, str]] + special: ClassVar[dict[int, str]] + unsupported_unicode: ClassVar[dict[int, str]] + utf8_supported_unicode: ClassVar[dict[int, str]] + textcomp: ClassVar[dict[int, str]] + pifont: ClassVar[dict[int, str]] + +class DocumentClass: + document_class: str + sections: list[str] + def __init__(self, document_class: str, with_part: bool = False) -> None: ... + def section(self, level: int) -> str: ... + def latex_section_depth(self, depth: int) -> int: ... + +class Table: + legacy_column_widths: bool + caption: list[str] + stubs: list[Incomplete] + colwidths_auto: bool + borders: str + def __init__(self, translator: LaTeXTranslator, latex_type: str) -> None: ... + def open(self) -> None: ... + def close(self) -> None: ... + def is_open(self) -> bool: ... + def set_table_style(self, node, settings) -> None: ... + def get_latex_type(self) -> str: ... + def set(self, attr, value) -> None: ... + def get(self, attr): ... + def get_vertical_bar(self) -> Literal["|", ""]: ... + def get_opening(self, width: str = r"\linewidth") -> str: ... + def get_closing(self) -> str: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def get_colspecs(self, node: nodes.Element) -> str: ... + def get_column_width(self) -> str: ... + def get_multicolumn_width(self, start: int, len_: int) -> str: ... + def need_recurse(self) -> bool | Literal[0]: ... + def visit_thead(self) -> list[str]: ... + def depart_thead(self) -> list[str]: ... + def visit_row(self) -> None: ... + def depart_row(self) -> list[str]: ... + def set_rowspan(self, cell, value) -> None: ... + def get_rowspan(self, cell): ... + def get_entry_number(self) -> int: ... + def visit_entry(self) -> None: ... + def is_stub_column(self): ... + +class LaTeXTranslator(nodes.NodeVisitor): + is_xetex: ClassVar[bool] + compound_enumerators: ClassVar[bool] + section_prefix_for_enumerators: ClassVar[bool] + section_enumerator_separator: ClassVar[str] + has_latex_toc: ClassVar[bool] + section_level: ClassVar[int] + inside_citation_reference_label: ClassVar[bool] + verbatim: ClassVar[bool] + insert_non_breaking_blanks: ClassVar[bool] + insert_newline: ClassVar[bool] + literal: ClassVar[bool] + alltt: ClassVar[bool] + TITLEDATA_NODES: ClassVar[tuple[type[nodes.Element], ...]] + + warn: Callable[..., nodes.system_message] + error: Callable[..., nodes.system_message] + settings: Values + latex_encoding: str + use_latex_toc: Incomplete + use_latex_docinfo: Incomplete + use_latex_citations: Incomplete + reference_label: Incomplete + hyperlink_color: Incomplete + font_encoding: str + literal_block_env: str + literal_block_options: str + bibtex: Incomplete + language_module: _LanguageModule + babel: Babel + author_separator: str + documentoptions: str + d_class: DocumentClass + graphicx_package: str + docutils_footnotes: Incomplete + head_prefix: list[str] + requirements: SortableDict[str, str] | list[str] + latex_preamble: list[Incomplete] + fallbacks: SortableDict[str, str] | list[str] + pdfsetup: list[str] + title: list[Incomplete] + subtitle: list[Incomplete] + titledata: list[Incomplete] + body_pre_docinfo: list[Incomplete] + docinfo: list[Incomplete] + dedication: list[Incomplete] + abstract: list[Incomplete] + body: list[Incomplete] + context: list[Incomplete] + title_labels: list[Incomplete] + subtitle_labels: list[Incomplete] + author_stack: list[Incomplete] + date: list[Incomplete] + pdfauthor: list[Incomplete] + pdfinfo: list[Incomplete] + table_stack: list[Incomplete] + active_table: Table + out: list[Incomplete] + out_stack: list[Incomplete] + fallback_stylesheet: bool + stylesheet: list[str] + hyperref_options: str + + def __init__(self, document: nodes.document, babel_class: type = ...) -> None: ... + def stylesheet_call(self, path: StrPath) -> str: ... + def to_latex_encoding(self, docutils_encoding: str) -> str: ... + def language_label(self, docutil_label: str) -> str: ... + def encode(self, text: str) -> str: ... + def attval(self, text: str, whitespace: re.Pattern[str] = ...) -> str: ... + def is_inline(self, node: nodes.Node) -> bool: ... + def ids_to_labels( + self, node: nodes.Element, set_anchor: bool = True, protect: bool = False, newline: bool = False, pre_nl: bool = False + ) -> list[str]: ... + def append_hypertargets(self, node: nodes.Element) -> None: ... + def set_align_from_classes(self, node) -> None: ... + def insert_align_declaration(self, node: nodes.Element, default: str | None = None) -> None: ... + def provide_fallback(self, feature: str, key: str | None = None) -> None: ... + def duclass_open(self, node) -> None: ... + def duclass_close(self, node) -> None: ... + def push_output_collector(self, new_out) -> None: ... + def pop_output_collector(self) -> None: ... + def term_postfix(self, node: nodes.Element) -> str: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def depart_comment(self, node: nodes.comment) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + + @overload + def visit_docinfo_item(self, node) -> None: ... + @overload + @deprecated("The `name` parameter is deprecated and will be removed in Docutils 0.24.") + def visit_docinfo_item(self, node, name: str | None) -> None: ... + + def depart_docinfo_item(self, node) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def make_title(self) -> None: ... + def append_bibliogaphy(self) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def insert_additional_table_colum_delimiters(self) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def label_delim(self, node, bracket, superscript) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def to_latex_length(self, length_str: str, node: nodes.Node | None = None) -> str: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def is_plaintext(self, node) -> bool: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_math(self, node: nodes.math, math_env: str = "$") -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def depart_raw(self, node: nodes.raw) -> None: ... + def has_unbalanced_braces(self, string: Iterable[str]) -> bool: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + attribution_formats: dict[str, tuple[str, str]] + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def thead_depth(self) -> int: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_contents(self, node) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/stubs/docutils/docutils/writers/manpage.pyi b/stubs/docutils/docutils/writers/manpage.pyi new file mode 100644 index 000000000000..9b9606008bb3 --- /dev/null +++ b/stubs/docutils/docutils/writers/manpage.pyi @@ -0,0 +1,253 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ClassVar, Final, Protocol, type_check_only +from typing_extensions import Never + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule + +@type_check_only +class _RegexPatternSub(Protocol): + # Matches the signature of the bound instance method `re.Pattern[str].sub` exactly + def __call__(self, /, repl: str | Callable[[re.Match[str]], str], string: str, count: int = 0) -> str: ... + +__docformat__: Final = "reStructuredText" +FIELD_LIST_INDENT: Final[int] +DEFINITION_LIST_INDENT: Final[int] +OPTION_LIST_INDENT: Final[int] +BLOCKQOUTE_INDENT: Final[float] +LITERAL_BLOCK_INDENT: Final[float] +MACRO_DEF: Final[str] +NONPRINTING_BREAKPOINT: Final[str] +NONBREAKING_INSERT_RE: Final[re.Pattern[str]] +NONBREAKING_INSERT_RE2: Final[re.Pattern[str]] + +def insert_URI_breakpoints(s: str) -> str: ... + +class Writer(writers.Writer[str]): + translator_class: type[Translator] + +class Table: + def __init__(self) -> None: ... + def new_row(self) -> None: ... + def append_separator(self, separator) -> None: ... + def append_cell(self, cell_lines: list[str]) -> None: ... + def as_list(self) -> list[str]: ... + +class Translator(nodes.NodeVisitor): + words_and_spaces: ClassVar[re.Pattern[str]] + possibly_a_roff_command: ClassVar[re.Pattern[str]] + document_start: ClassVar[str] + settings: Values + language: _LanguageModule + head: list[str] + body: list[str] + foot: list[str] + section_level: int + context: list[str | int] + topic_class: str + colspecs: list[nodes.colspec] + compact_p: int + compact_simple: Incomplete + header_written: int + authors: list[Incomplete] + defs: dict[str, tuple[str, ...]] + def comment_begin(self, text: str) -> str: ... + def comment(self, text: str) -> str: ... + def ensure_eol(self) -> None: ... + def ensure_c_eol(self) -> None: ... + def astext(self) -> str: ... + def deunicode(self, text: str) -> str: ... + def encode_special_chars(self, text: str) -> str: ... + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def list_start(self, node) -> None: ... + def list_end(self) -> None: ... + def header(self) -> str: ... + def append_header(self) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_admonition(self, node: nodes.admonition, name: str | None = None) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def visit_attention(self, node: nodes.attention) -> None: ... + def depart_attention(self, node: nodes.attention) -> None: ... + def visit_docinfo_item(self, node: nodes.docinfo, name: str) -> None: ... + def depart_docinfo_item(self, node: nodes.docinfo) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_caution(self, node: nodes.caution) -> None: ... + def depart_caution(self, node: nodes.caution) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + def write_colspecs(self) -> None: ... + def visit_comment(self, node: nodes.comment, sub: _RegexPatternSub = ...) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def visit_danger(self, node: nodes.danger) -> None: ... + def depart_danger(self, node: nodes.danger) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_error(self, node: nodes.error) -> None: ... + def depart_error(self, node: nodes.error) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + def footnote_backrefs(self, node) -> None: ... + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_hint(self, node: nodes.hint) -> None: ... + def depart_hint(self, node: nodes.hint) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_image(self, node: nodes.image) -> None: ... + def visit_important(self, node: nodes.important) -> None: ... + def depart_important(self, node: nodes.important) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_note(self, node: nodes.note) -> None: ... + def depart_note(self, node: nodes.note) -> None: ... + def indent(self, by: float = 0.5) -> None: ... + def dedent(self) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def first_child(self, node): ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_substitution_reference(self, node: nodes.substitution_reference) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def visit_tip(self, node: nodes.tip) -> None: ... + def depart_tip(self, node: nodes.tip) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def visit_warning(self, node: nodes.warning) -> None: ... + def depart_warning(self, node: nodes.warning) -> None: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/stubs/docutils/docutils/writers/null.pyi b/stubs/docutils/docutils/writers/null.pyi new file mode 100644 index 000000000000..f20c030b833c --- /dev/null +++ b/stubs/docutils/docutils/writers/null.pyi @@ -0,0 +1,11 @@ +from typing import ClassVar, Final + +from docutils import writers + +__docformat__: Final = "reStructuredText" + +class Writer(writers.UnfilteredWriter[str]): + supported: ClassVar[tuple[str, ...]] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str]] + def translate(self) -> None: ... diff --git a/stubs/docutils/docutils/writers/odf_odt/__init__.pyi b/stubs/docutils/docutils/writers/odf_odt/__init__.pyi new file mode 100644 index 000000000000..d9a6795a9438 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/__init__.pyi @@ -0,0 +1,426 @@ +import itertools +import re +import zipfile +from _typeshed import FileDescriptorOrPath, Incomplete, ReadableBuffer, SizedBuffer, Unused +from collections.abc import Generator +from typing import ClassVar, Final, Literal +from xml.etree import ElementTree + +from docutils import nodes, writers +from docutils.frontend import Values +from docutils.languages import _LanguageModule +from docutils.readers import standalone + +__docformat__: Final = "reStructuredText" +VERSION: Final[str] +IMAGE_NAME_COUNTER: Final[itertools.count[int]] + +class _ElementInterfaceWrapper(ElementTree.Element): + def __init__(self, tag: str, attrib: dict[str, str] | None = None) -> None: ... + def setparent(self, parent) -> None: ... + def getparent(self): ... + +SPACES_PATTERN: Final[re.Pattern[str]] +TABS_PATTERN: Final[re.Pattern[str]] +FILL_PAT1: Final[re.Pattern[str]] +FILL_PAT2: Final[re.Pattern[str]] +TABLESTYLEPREFIX: Final[str] +TABLENAMEDEFAULT: Final[str] +TABLEPROPERTYNAMES: Final[tuple[str, ...]] +GENERATOR_DESC: Final[str] +NAME_SPACE_1: Final[str] +CONTENT_NAMESPACE_DICT: Final[dict[str, str]] +CNSD: Final[dict[str, str]] +STYLES_NAMESPACE_DICT: Final[dict[str, str]] +SNSD: Final[dict[str, str]] +MANIFEST_NAMESPACE_DICT: Final[dict[str, str]] +MANNSD: Final[dict[str, str]] +META_NAMESPACE_DICT: Final[dict[str, str]] +METNSD: Final[dict[str, str]] +CONTENT_NAMESPACE_ATTRIB: Final[dict[str, str]] +STYLES_NAMESPACE_ATTRIB: Final[dict[str, str]] +MANIFEST_NAMESPACE_ATTRIB: Final[dict[str, str]] +META_NAMESPACE_ATTRIB: Final[dict[str, str]] + +def Element( + tag: str, attrib: dict[str, str] | None = None, nsmap: Unused = None, nsdict: Unused = ... +) -> _ElementInterfaceWrapper: ... +def SubElement( + parent: _ElementInterfaceWrapper, tag: str, attrib: dict[str, str] | None = None, nsmap: Unused = None, nsdict: Unused = ... +) -> _ElementInterfaceWrapper: ... +def fix_ns(tag: str, attrib: dict[str, str], nsdict: Unused) -> tuple[str, dict[str, str]]: ... +def add_ns(tag: str, nsdict: Unused = ...) -> str: ... +def ToString(et: ElementTree.ElementTree) -> str: ... +def escape_cdata(text: str) -> str: ... + +class TableStyle: + border: str | None + backgroundcolor: str | None + def __init__(self, border: str | None = None, backgroundcolor: str | None = None) -> None: ... + def get_border_(self): ... + def set_border_(self, border) -> None: ... + border_: Incomplete + def get_backgroundcolor_(self): ... + def set_backgroundcolor_(self, backgroundcolor) -> None: ... + backgroundcolor_: Incomplete + +BUILTIN_DEFAULT_TABLE_STYLE: TableStyle + +class ListLevel: + level: int + sibling_level: bool + nested_level: bool + def __init__(self, level: int, sibling_level: bool = True, nested_level: bool = True) -> None: ... + def get_sibling(self) -> bool: ... + def set_sibling(self, sibling_level: bool) -> None: ... + def get_nested(self) -> bool: ... + def set_nested(self, nested_level: bool) -> None: ... + def get_level(self) -> int: ... + def set_level(self, level: int) -> None: ... + +class Writer(writers.Writer[bytes]): + MIME_TYPE: ClassVar[str] + EXTENSION: ClassVar[str] + default_stylesheet: ClassVar[str] + default_stylesheet_path: ClassVar[str] + default_template: ClassVar[str] + default_template_path: ClassVar[str] + translator_class: type[ODFTranslator] + settings: Values + visitor: ODFTranslator + def assemble_my_parts(self) -> None: ... + def update_stylesheet(self, stylesheet_root, language_code: str | None, region_code: str | None): ... + def write_zip_str( + self, zfile: zipfile.ZipFile, name: str, bytes_: str | SizedBuffer, compress_type: int = zipfile.ZIP_DEFLATED + ) -> None: ... + def store_embedded_files(self, zfile: zipfile.ZipFile) -> None: ... + def get_settings(self) -> bytes: ... + def get_stylesheet(self) -> bytes: ... + def copy_from_stylesheet(self, outzipfile: zipfile.ZipFile) -> None: ... + def assemble_parts(self) -> None: ... + def create_manifest(self) -> str: ... + def create_meta(self) -> str: ... + +class ODFTranslator(nodes.GenericNodeVisitor): + used_styles: ClassVar[tuple[str, ...]] + settings: Values + language_code: str + language: _LanguageModule + format_map: dict[str, str] + section_level: int + section_count: int + content_tree: ElementTree.ElementTree + current_element: _ElementInterfaceWrapper + automatic_styles: _ElementInterfaceWrapper + body_text_element: _ElementInterfaceWrapper + paragraph_style_stack: list[str] + list_style_stack: list[str] + table_count: int + column_count: int + trace_level: int + optiontablestyles_generated: bool + field_name: Incomplete + field_element: Incomplete + title: str | None + image_count: int + image_style_count: int + image_dict: dict[str, tuple[str, str]] + embedded_file_list: list[Incomplete] + syntaxhighlighting: int + syntaxhighlight_lexer: str + header_content: list[Incomplete] + footer_content: list[Incomplete] + in_header: bool + in_footer: bool + blockstyle: str + in_table_of_contents: bool + table_of_content_index_body: _ElementInterfaceWrapper | None + list_level: int + def_list_level: int + footnote_ref_dict: dict[Incomplete, _ElementInterfaceWrapper] + footnote_list: list[tuple[Incomplete, Incomplete]] + footnote_chars_idx: int + footnote_level: int + pending_ids: Incomplete + in_paragraph: bool + found_doc_title: bool + bumped_list_level_stack: list[ListLevel] + meta_dict: dict[Incomplete, Incomplete] + line_block_level: int + line_indent_level: int + citation_id: Incomplete + style_index: int + str_stylesheet: str | bytes + str_stylesheetcontent: str | bytes | None + dom_stylesheet: ElementTree.Element | None + table_styles: dict[str, TableStyle] | None + in_citation: bool + inline_style_count_stack: list[int] + def get_str_stylesheet(self) -> str | bytes: ... + dom_stylesheetcontent: ElementTree.Element + def retrieve_styles(self, extension: str) -> None: ... + def extract_table_styles(self, styles_str: str | ReadableBuffer) -> dict[str, TableStyle]: ... + def get_property(self, stylenode: ElementTree.Element) -> str | None: ... + def add_doc_title(self) -> None: ... + def find_first_text_p(self, el: _ElementInterfaceWrapper) -> _ElementInterfaceWrapper | None: ... + def attach_page_style(self, el: _ElementInterfaceWrapper) -> None: ... + def rststyle(self, name: str, parameters: tuple[object, ...] = ()) -> str: ... + def generate_content_element(self, root: _ElementInterfaceWrapper) -> _ElementInterfaceWrapper: ... + def setup_page(self): ... + def get_dom_stylesheet(self) -> ElementTree.Element | None: ... + def setup_paper(self, root_el) -> None: ... + def add_header_footer(self, root_el) -> None: ... + code_none: int + code_field: int + code_text: int + field_pat: re.Pattern[str] + def create_custom_headfoot(self, parent: _ElementInterfaceWrapper, text: str, style_name, automatic_styles) -> None: ... + def make_field_element( + self, parent: _ElementInterfaceWrapper, text: str, style_name, automatic_styles + ) -> _ElementInterfaceWrapper | None: ... + def split_field_specifiers_iter(self, text: str) -> Generator[tuple[int, str]]: ... + def astext(self) -> str: ... + def content_astext(self) -> str: ... + def set_title(self, title: str) -> None: ... + def get_title(self) -> str | None: ... + def set_embedded_file_list(self, embedded_file_list) -> None: ... + def get_embedded_file_list(self): ... + def get_meta_dict(self): ... + def process_footnotes(self) -> None: ... + def append_child( + self, tag: str, attrib: dict[str, str] | None = None, parent: _ElementInterfaceWrapper | None = None + ) -> _ElementInterfaceWrapper: ... + def append_p(self, style: str, text: str | None = None) -> _ElementInterfaceWrapper: ... + def append_pending_ids(self, el: _ElementInterfaceWrapper) -> None: ... + def set_current_element(self, el: _ElementInterfaceWrapper) -> None: ... + def set_to_parent(self) -> None: ... + def generate_labeled_block(self, node: nodes.Node, label: str) -> _ElementInterfaceWrapper: ... + def generate_labeled_line(self, node: nodes.Node, label: str) -> _ElementInterfaceWrapper: ... + def encode(self, text: str) -> str: ... + def dispatch_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def handle_basic_atts(self, node: nodes.Element) -> None: ... + def default_visit(self, node: nodes.Element) -> None: ... # type: ignore[override] + def default_departure(self, node: nodes.Element) -> None: ... # type: ignore[override] + def visit_Text(self, node: nodes.Text) -> None: ... + def depart_Text(self, node: nodes.Text) -> None: ... + def visit_address(self, node: nodes.address) -> None: ... + def depart_address(self, node: nodes.address) -> None: ... + def visit_author(self, node: nodes.author) -> None: ... + def depart_author(self, node: nodes.author) -> None: ... + def visit_authors(self, node: nodes.authors) -> None: ... + def depart_authors(self, node: nodes.authors) -> None: ... + def visit_contact(self, node: nodes.contact) -> None: ... + def depart_contact(self, node: nodes.contact) -> None: ... + def visit_copyright(self, node: nodes.copyright) -> None: ... + def depart_copyright(self, node: nodes.copyright) -> None: ... + def visit_date(self, node: nodes.date) -> None: ... + def depart_date(self, node: nodes.date) -> None: ... + def visit_organization(self, node: nodes.organization) -> None: ... + def depart_organization(self, node: nodes.organization) -> None: ... + def visit_status(self, node: nodes.status) -> None: ... + def depart_status(self, node: nodes.status) -> None: ... + def visit_revision(self, node: nodes.revision) -> None: ... + def depart_revision(self, node: nodes.revision) -> None: ... + def visit_version(self, node: nodes.version) -> None: ... + def depart_version(self, node: nodes.version) -> None: ... + def visit_attribution(self, node: nodes.attribution) -> None: ... + def depart_attribution(self, node: nodes.attribution) -> None: ... + def visit_block_quote(self, node: nodes.block_quote) -> None: ... + def depart_block_quote(self, node: nodes.block_quote) -> None: ... + def visit_bullet_list(self, node: nodes.bullet_list) -> None: ... + def depart_bullet_list(self, node: nodes.bullet_list) -> None: ... + def visit_caption(self, node: nodes.caption) -> None: ... + def depart_caption(self, node: nodes.caption) -> None: ... + def visit_comment(self, node: nodes.comment) -> None: ... + def depart_comment(self, node: nodes.comment) -> None: ... + def visit_compound(self, node: nodes.compound) -> None: ... + def depart_compound(self, node: nodes.compound) -> None: ... + def visit_container(self, node: nodes.container) -> None: ... + def depart_container(self, node: nodes.container) -> None: ... + def visit_decoration(self, node: nodes.decoration) -> None: ... + def depart_decoration(self, node: nodes.decoration) -> None: ... + def visit_definition_list(self, node: nodes.definition_list) -> None: ... + def depart_definition_list(self, node: nodes.definition_list) -> None: ... + def visit_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def depart_definition_list_item(self, node: nodes.definition_list_item) -> None: ... + def visit_term(self, node: nodes.term) -> None: ... + def depart_term(self, node: nodes.term) -> None: ... + def visit_definition(self, node: nodes.definition) -> None: ... + def depart_definition(self, node: nodes.definition) -> None: ... + def visit_classifier(self, node: nodes.classifier) -> None: ... + def depart_classifier(self, node: nodes.classifier) -> None: ... + def visit_document(self, node: nodes.document) -> None: ... + def depart_document(self, node: nodes.document) -> None: ... + def visit_docinfo(self, node: nodes.docinfo) -> None: ... + def depart_docinfo(self, node: nodes.docinfo) -> None: ... + def visit_emphasis(self, node: nodes.emphasis) -> None: ... + def depart_emphasis(self, node: nodes.emphasis) -> None: ... + def visit_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def depart_enumerated_list(self, node: nodes.enumerated_list) -> None: ... + def visit_list_item(self, node: nodes.list_item) -> None: ... + def depart_list_item(self, node: nodes.list_item) -> None: ... + def visit_header(self, node: nodes.header) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_footer(self, node: nodes.footer) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def visit_field(self, node: nodes.field) -> None: ... + def depart_field(self, node: nodes.field) -> None: ... + def visit_field_list(self, node: nodes.field_list) -> None: ... + def depart_field_list(self, node: nodes.field_list) -> None: ... + def visit_field_name(self, node: nodes.field_name) -> None: ... + def depart_field_name(self, node: nodes.field_name) -> None: ... + def visit_field_body(self, node: nodes.field_body) -> None: ... + def depart_field_body(self, node: nodes.field_body) -> None: ... + def visit_figure(self, node: nodes.figure) -> None: ... + def depart_figure(self, node: nodes.figure) -> None: ... + save_footnote_current: _ElementInterfaceWrapper + def visit_footnote(self, node: nodes.footnote) -> None: ... + def depart_footnote(self, node: nodes.footnote) -> None: ... + footnote_chars: list[str] + def visit_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def depart_footnote_reference(self, node: nodes.footnote_reference) -> None: ... + def visit_citation(self, node: nodes.citation) -> None: ... + def depart_citation(self, node: nodes.citation) -> None: ... + def visit_citation_reference(self, node: nodes.citation_reference) -> None: ... + def depart_citation_reference(self, node: nodes.citation_reference) -> None: ... + def visit_label(self, node: nodes.label) -> None: ... + def depart_label(self, node: nodes.label) -> None: ... + def visit_generated(self, node: nodes.generated) -> None: ... + def depart_generated(self, node: nodes.generated) -> None: ... + def check_file_exists(self, path: FileDescriptorOrPath) -> Literal[1, 0]: ... + def visit_image(self, node: nodes.image) -> None: ... + def depart_image(self, node: nodes.image) -> None: ... + def get_image_width_height(self, node: nodes.image, attr: str) -> tuple[float | None, Literal["%", "cm"] | None]: ... + def convert_to_cm(self, size: str) -> tuple[float, Literal["cm"]]: ... + def get_image_scale(self, node: nodes.image) -> float: ... + def get_image_scaled_width_height(self, node: nodes.image, source) -> tuple[Incomplete, Incomplete]: ... + def get_page_width(self) -> float: ... + def generate_figure(self, node: nodes.image, source, destination, current_element): ... + def generate_image( + self, node: nodes.image, source, destination, current_element, frame_attrs: dict[str, str] | None = None + ): ... + def is_in_table(self, node: nodes.Node) -> bool: ... + def visit_legend(self, node: nodes.legend) -> None: ... + def depart_legend(self, node: nodes.legend) -> None: ... + def visit_line_block(self, node: nodes.line_block) -> None: ... + def depart_line_block(self, node: nodes.line_block) -> None: ... + def visit_line(self, node: nodes.line) -> None: ... + def depart_line(self, node: nodes.line) -> None: ... + def visit_literal(self, node: nodes.literal) -> None: ... + def depart_literal(self, node: nodes.literal) -> None: ... + def visit_inline(self, node: nodes.inline) -> None: ... + def depart_inline(self, node: nodes.inline) -> None: ... + def fill_line(self, line: str) -> str: ... + def fill_func1(self, matchobj: re.Match[str]) -> str: ... + def fill_func2(self, matchobj: re.Match[str]) -> str: ... + def visit_literal_block(self, node: nodes.literal_block) -> None: ... + def depart_literal_block(self, node: nodes.literal_block) -> None: ... + def visit_doctest_block(self, node: nodes.doctest_block) -> None: ... + def depart_doctest_block(self, node: nodes.doctest_block) -> None: ... + def visit_math(self, node: nodes.math) -> None: ... + def depart_math(self, node: nodes.math) -> None: ... + def visit_math_block(self, node: nodes.math_block) -> None: ... + def depart_math_block(self, node: nodes.math_block) -> None: ... + def visit_meta(self, node: nodes.meta) -> None: ... + def depart_meta(self, node: nodes.meta) -> None: ... + def visit_option_list(self, node: nodes.option_list) -> None: ... + def depart_option_list(self, node: nodes.option_list) -> None: ... + def visit_option_list_item(self, node: nodes.option_list_item) -> None: ... + def depart_option_list_item(self, node: nodes.option_list_item) -> None: ... + def visit_option_group(self, node: nodes.option_group) -> None: ... + def depart_option_group(self, node: nodes.option_group) -> None: ... + def visit_option(self, node: nodes.option) -> None: ... + def depart_option(self, node: nodes.option) -> None: ... + def visit_option_string(self, node: nodes.option_string) -> None: ... + def depart_option_string(self, node: nodes.option_string) -> None: ... + def visit_option_argument(self, node: nodes.option_argument) -> None: ... + def depart_option_argument(self, node: nodes.option_argument) -> None: ... + def visit_description(self, node: nodes.description) -> None: ... + def depart_description(self, node: nodes.description) -> None: ... + def visit_paragraph(self, node: nodes.paragraph) -> None: ... + def depart_paragraph(self, node: nodes.paragraph) -> None: ... + def visit_problematic(self, node: nodes.problematic) -> None: ... + def depart_problematic(self, node: nodes.problematic) -> None: ... + def visit_raw(self, node: nodes.raw) -> None: ... + def depart_raw(self, node: nodes.raw) -> None: ... + def visit_reference(self, node: nodes.reference) -> None: ... + def depart_reference(self, node: nodes.reference) -> None: ... + def visit_rubric(self, node: nodes.rubric) -> None: ... + def depart_rubric(self, node: nodes.rubric) -> None: ... + def visit_section(self, node: nodes.section, move_ids: int = 1) -> None: ... + def depart_section(self, node: nodes.section) -> None: ... + def visit_strong(self, node: nodes.strong) -> None: ... + def depart_strong(self, node: nodes.strong) -> None: ... + def visit_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def depart_substitution_definition(self, node: nodes.substitution_definition) -> None: ... + def visit_system_message(self, node: nodes.system_message) -> None: ... + def depart_system_message(self, node: nodes.system_message) -> None: ... + def get_table_style(self, node) -> TableStyle: ... + current_table_style: _ElementInterfaceWrapper + table_width: float + def visit_table(self, node: nodes.table) -> None: ... + def depart_table(self, node: nodes.table) -> None: ... + def visit_tgroup(self, node: nodes.tgroup) -> None: ... + def depart_tgroup(self, node: nodes.tgroup) -> None: ... + def visit_colspec(self, node: nodes.colspec) -> None: ... + def depart_colspec(self, node: nodes.colspec) -> None: ... + in_thead: bool + def visit_thead(self, node: nodes.thead) -> None: ... + def depart_thead(self, node: nodes.thead) -> None: ... + def visit_row(self, node: nodes.row) -> None: ... + def depart_row(self, node: nodes.row) -> None: ... + def visit_entry(self, node: nodes.entry) -> None: ... + def depart_entry(self, node: nodes.entry) -> None: ... + def visit_tbody(self, node: nodes.tbody) -> None: ... + def depart_tbody(self, node: nodes.tbody) -> None: ... + def visit_target(self, node: nodes.target) -> None: ... + def depart_target(self, node: nodes.target) -> None: ... + def visit_title(self, node: nodes.title, move_ids: int = 1, title_type: str = "title") -> None: ... + def depart_title(self, node: nodes.title) -> None: ... + def visit_subtitle(self, node: nodes.subtitle, move_ids: int = 1) -> None: ... + def depart_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_title_reference(self, node: nodes.title_reference) -> None: ... + def depart_title_reference(self, node: nodes.title_reference) -> None: ... + def generate_table_of_content_entry_template(self, el1) -> None: ... + def find_title_label(self, node, class_type, label_key): ... + save_current_element: Incomplete + def visit_topic(self, node: nodes.topic) -> None: ... + def depart_topic(self, node: nodes.topic) -> None: ... + def update_toc_page_numbers(self, el) -> None: ... + def update_toc_collect(self, el, level, collection) -> None: ... + def update_toc_add_numbers(self, collection) -> None: ... + def visit_transition(self, node: nodes.transition) -> None: ... + def depart_transition(self, node: nodes.transition) -> None: ... + def visit_warning(self, node: nodes.warning) -> None: ... + def depart_warning(self, node: nodes.warning) -> None: ... + def visit_attention(self, node: nodes.attention) -> None: ... + def depart_attention(self, node: nodes.attention) -> None: ... + def visit_caution(self, node: nodes.caution) -> None: ... + def depart_caution(self, node: nodes.caution) -> None: ... + def visit_danger(self, node: nodes.danger) -> None: ... + def depart_danger(self, node: nodes.danger) -> None: ... + def visit_error(self, node: nodes.error) -> None: ... + def depart_error(self, node: nodes.error) -> None: ... + def visit_hint(self, node: nodes.hint) -> None: ... + def depart_hint(self, node: nodes.hint) -> None: ... + def visit_important(self, node: nodes.important) -> None: ... + def depart_important(self, node: nodes.important) -> None: ... + def visit_note(self, node: nodes.note) -> None: ... + def depart_note(self, node: nodes.note) -> None: ... + def visit_tip(self, node: nodes.tip) -> None: ... + def depart_tip(self, node: nodes.tip) -> None: ... + def visit_admonition(self, node: nodes.admonition) -> None: ... + def depart_admonition(self, node: nodes.admonition) -> None: ... + def generate_admonition(self, node: nodes.Node, label: str, title: str | None = None) -> None: ... + def visit_subscript(self, node: nodes.subscript) -> None: ... + def depart_subscript(self, node: nodes.subscript) -> None: ... + def visit_superscript(self, node: nodes.superscript) -> None: ... + def depart_superscript(self, node: nodes.superscript) -> None: ... + def visit_abbreviation(self, node: nodes.abbreviation) -> None: ... + def depart_abbreviation(self, node: nodes.abbreviation) -> None: ... + def visit_acronym(self, node: nodes.acronym) -> None: ... + def depart_acronym(self, node: nodes.acronym) -> None: ... + def visit_sidebar(self, node: nodes.sidebar) -> None: ... + def depart_sidebar(self, node: nodes.sidebar) -> None: ... + +class Reader(standalone.Reader[str | bytes]): ... diff --git a/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi b/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi new file mode 100644 index 000000000000..d0fbc5009ca5 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/prepstyles.pyi @@ -0,0 +1,7 @@ +from _typeshed import StrPath +from typing import IO + +NAMESPACES: dict[str, str] + +def prepstyle(filename: StrPath | IO[bytes]) -> None: ... +def main() -> None: ... diff --git a/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi b/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi new file mode 100644 index 000000000000..10293d3fb075 --- /dev/null +++ b/stubs/docutils/docutils/writers/odf_odt/pygmentsformatter.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from typing import Any + +# Formatter[str] from types-pygments +class _Formatter: + name: Any + aliases: Any + filenames: Any + unicodeoutput: bool + style: Any + full: Any + title: Any + encoding: Any + options: Any + def __init__(self, *, encoding: None = None, outencoding: None = None, **options) -> None: ... + def get_style_defs(self, arg: str = ""): ... + def format(self, tokensource, outfile): ... + +class OdtPygmentsFormatter(_Formatter): + rststyle_function: Incomplete + escape_function: Incomplete + def __init__(self, rststyle_function, escape_function) -> None: ... + def rststyle(self, name, parameters=()): ... + def get_style_defs(self, arg: str = ""): ... + def format(self, tokensource, outfile): ... + +class OdtPygmentsProgFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile) -> None: ... + +class OdtPygmentsLaTeXFormatter(OdtPygmentsFormatter): + def format(self, tokensource, outfile) -> None: ... diff --git a/stubs/docutils/docutils/writers/pep_html/__init__.pyi b/stubs/docutils/docutils/writers/pep_html/__init__.pyi new file mode 100644 index 000000000000..bdefd546ad4e --- /dev/null +++ b/stubs/docutils/docutils/writers/pep_html/__init__.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar, Final + +from docutils.writers import html4css1 + +__docformat__: Final = "reStructuredText" + +class Writer(html4css1.Writer): + default_stylesheet: ClassVar[str] + default_stylesheet_path: ClassVar[str] + default_template_path: ClassVar[str] + settings_default_overrides: ClassVar[dict[str, str]] + relative_path_settings: ClassVar[tuple[str, ...]] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[HTMLTranslator] + pepnum: str + title: str + def interpolation_dict(self) -> dict[str, str | int]: ... # type: ignore[override] + +class HTMLTranslator(html4css1.HTMLTranslator): + def depart_field_list(self, node) -> None: ... diff --git a/stubs/docutils/docutils/writers/pseudoxml.pyi b/stubs/docutils/docutils/writers/pseudoxml.pyi new file mode 100644 index 000000000000..2372ffc0b509 --- /dev/null +++ b/stubs/docutils/docutils/writers/pseudoxml.pyi @@ -0,0 +1,9 @@ +from typing import ClassVar, Final + +from docutils import writers + +__docformat__: Final = "reStructuredText" + +class Writer(writers.Writer[str]): + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] diff --git a/stubs/docutils/docutils/writers/s5_html/__init__.pyi b/stubs/docutils/docutils/writers/s5_html/__init__.pyi new file mode 100644 index 000000000000..fe0f36f15b47 --- /dev/null +++ b/stubs/docutils/docutils/writers/s5_html/__init__.pyi @@ -0,0 +1,42 @@ +import re +from _typeshed import StrPath +from typing import ClassVar, Final + +from docutils import nodes +from docutils.writers import html4css1 + +__docformat__: Final = "reStructuredText" +themes_dir_path: Final[str] + +def find_theme(name: StrPath) -> str: ... + +class Writer(html4css1.Writer): + settings_default_overrides: ClassVar[dict[str, int]] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[S5HTMLTranslator] + +class S5HTMLTranslator(html4css1.HTMLTranslator): + s5_stylesheet_template: ClassVar[str] + disable_current_slide: ClassVar[str] + layout_template: ClassVar[str] + default_theme: ClassVar[str] + base_theme_file: ClassVar[str] + direct_theme_files: ClassVar[tuple[str, ...]] + indirect_theme_files: ClassVar[tuple[str, ...]] + required_theme_files: ClassVar[tuple[str, ...]] + theme_file_path: str | None + s5_footer: list[str] + s5_header: list[str] + section_count: int + theme_files_copied: dict[str, bool] + def __init__(self, document: nodes.document, /) -> None: ... + def setup_theme(self) -> None: ... + def copy_theme(self) -> None: ... + files_to_skip_pattern: re.Pattern[str] + def copy_file(self, name, source_dir, dest_dir): ... + def depart_document(self, node: nodes.document) -> None: ... + def depart_footer(self, node: nodes.footer) -> None: ... + def depart_header(self, node: nodes.header) -> None: ... + def visit_section(self, node: nodes.section) -> None: ... + def visit_subtitle(self, node: nodes.subtitle) -> None: ... + def visit_title(self, node: nodes.title) -> None: ... diff --git a/stubs/docutils/docutils/writers/xetex/__init__.pyi b/stubs/docutils/docutils/writers/xetex/__init__.pyi new file mode 100644 index 000000000000..a8528b3670b2 --- /dev/null +++ b/stubs/docutils/docutils/writers/xetex/__init__.pyi @@ -0,0 +1,30 @@ +from typing import ClassVar, Final + +from docutils import nodes +from docutils.utils import Reporter +from docutils.writers import latex2e + +__docformat__: Final = "reStructuredText" + +class Writer(latex2e.Writer): + default_template: ClassVar[str] + default_preamble: ClassVar[str] + config_section: ClassVar[str] + config_section_dependencies: ClassVar[tuple[str, ...]] + translator_class: type[XeLaTeXTranslator] + +class Babel(latex2e.Babel): + language_code: str + reporter: Reporter + language: str + warn_msg: str # type: ignore[misc] + quote_index: int + quotes: tuple[str, ...] + literal_double_quote: str + key: str + def __init__(self, language_code: str, reporter: Reporter) -> None: ... + +class XeLaTeXTranslator(latex2e.LaTeXTranslator): + is_xetex: bool # type: ignore[misc] + def __init__(self, document: nodes.document) -> None: ... + def to_latex_length(self, length_str: str, node: nodes.Node | None = None) -> str: ... diff --git a/stubs/editdistance/@tests/stubtest_allowlist.txt b/stubs/editdistance/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ef46eff1a3b5 --- /dev/null +++ b/stubs/editdistance/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Not public API -- the submodule is an implementation detail due to it being a cythonized package +editdistance.bycython diff --git a/stubs/editdistance/METADATA.toml b/stubs/editdistance/METADATA.toml new file mode 100644 index 000000000000..2c5ced48093a --- /dev/null +++ b/stubs/editdistance/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.8.*" +upstream-repository = "https://github.com/roy-ht/editdistance" diff --git a/stubs/editdistance/editdistance/__init__.pyi b/stubs/editdistance/editdistance/__init__.pyi new file mode 100644 index 000000000000..8d31bd35aa1b --- /dev/null +++ b/stubs/editdistance/editdistance/__init__.pyi @@ -0,0 +1,8 @@ +from collections.abc import Hashable, Iterable + +def eval(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... +def distance(a: Iterable[Hashable], b: Iterable[Hashable]) -> int: ... +def eval_criterion(a: Iterable[Hashable], b: Iterable[Hashable], thr: int) -> bool: ... +def distance_le_than(a: Iterable[Hashable], b: Iterable[Hashable], thr: int) -> bool: ... + +__all__ = ("eval", "distance", "eval_criterion", "distance_le_than") diff --git a/stubs/entrypoints/@tests/stubtest_allowlist.txt b/stubs/entrypoints/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7bfaa84f2a47 --- /dev/null +++ b/stubs/entrypoints/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# staticmethod weirdness: +entrypoints.CaseSensitiveConfigParser.optionxform diff --git a/stubs/entrypoints/METADATA.toml b/stubs/entrypoints/METADATA.toml new file mode 100644 index 000000000000..cd6b4631d954 --- /dev/null +++ b/stubs/entrypoints/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/takluyver/entrypoints" diff --git a/stubs/entrypoints/entrypoints.pyi b/stubs/entrypoints/entrypoints.pyi new file mode 100644 index 000000000000..c519f64f4cc9 --- /dev/null +++ b/stubs/entrypoints/entrypoints.pyi @@ -0,0 +1,48 @@ +from collections.abc import Iterator, Sequence +from configparser import ConfigParser +from re import Pattern +from typing import Any +from typing_extensions import Self + +entry_point_pattern: Pattern[str] +file_in_zip_pattern: Pattern[str] + +class BadEntryPoint(Exception): + epstr: str + def __init__(self, epstr: str) -> None: ... + @staticmethod + def err_to_warnings() -> Iterator[None]: ... + +class NoSuchEntryPoint(Exception): + group: str + name: str + def __init__(self, group: str, name: str) -> None: ... + +class CaseSensitiveConfigParser(ConfigParser): ... + +class EntryPoint: + name: str + module_name: str + object_name: str + extras: Sequence[str] | None + distro: Distribution | None + def __init__( + self, name: str, module_name: str, object_name: str, extras: Sequence[str] | None = ..., distro: Distribution | None = ... + ) -> None: ... + def load(self) -> Any: ... + @classmethod + def from_string(cls, epstr: str, name: str, distro: Distribution | None = ...) -> Self: ... + +class Distribution: + name: str + version: str + def __init__(self, name: str, version: str) -> None: ... + @classmethod + def from_name_version(cls, name: str) -> Self: ... + +def iter_files_distros( + path: Sequence[str] | None = ..., repeated_distro: str = ... +) -> Iterator[tuple[ConfigParser, Distribution | None]]: ... +def get_single(group: str, name: str, path: Sequence[str] | None = ...) -> EntryPoint: ... +def get_group_named(group: str, path: Sequence[str] | None = ...) -> dict[str, EntryPoint]: ... +def get_group_all(group: str, path: Sequence[str] | None = ...) -> list[EntryPoint]: ... diff --git a/stubs/ephem/@tests/stubtest_allowlist.txt b/stubs/ephem/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..78c3d158f1a7 --- /dev/null +++ b/stubs/ephem/@tests/stubtest_allowlist.txt @@ -0,0 +1,11 @@ +# Tests +ephem.tests.* + +# Leaked loop variables +ephem.stars.k +ephem.stars.v + +# Runtime signature has *args/**kwargs that raise TypeError; stub signature is correct +ephem._libastro.Observer.__init__ +ephem.FixedBody.__init__ +ephem._libastro.FixedBody.__init__ diff --git a/stubs/ephem/METADATA.toml b/stubs/ephem/METADATA.toml new file mode 100644 index 000000000000..1f1f7d6bc0e3 --- /dev/null +++ b/stubs/ephem/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.2.*" +upstream-repository = "https://github.com/brandon-rhodes/pyephem" diff --git a/stubs/ephem/ephem/__init__.pyi b/stubs/ephem/ephem/__init__.pyi new file mode 100644 index 000000000000..477799ef2be7 --- /dev/null +++ b/stubs/ephem/ephem/__init__.pyi @@ -0,0 +1,289 @@ +from collections.abc import Callable +from datetime import datetime as _datetime, timedelta as _timedelta, tzinfo as _tzinfo +from typing import Final, overload +from typing_extensions import Never, Self + +from . import _libastro + +__version__: Final[str] + +# Mathematical constants +tau: Final[float] +twopi: Final[float] +halfpi: Final[float] +quarterpi: Final[float] +eighthpi: Final[float] +degree: Final[float] +arcminute: Final[float] +arcsecond: Final[float] +half_arcsecond: Final[float] +tiny: Final[float] + +# Physical constants +c: Final[float] +meters_per_au: Final[float] +earth_radius: Final[float] +moon_radius: Final[float] +sun_radius: Final[float] + +# Epoch constants +B1900: Final[float] +B1950: Final[float] +J2000: Final[float] + +# Type imports from _libastro +Angle = _libastro.Angle +degrees = _libastro.degrees +hours = _libastro.hours +Date = _libastro.Date + +# Time constants +hour: Final[float] +minute: Final[float] +second: Final[float] + +# Precision constants +default_newton_precision: Final[float] +rise_set_iterations: Final[tuple[int, int, int, int, int, int, int]] + +# Function imports from _libastro +delta_t = _libastro.delta_t +julian_date = _libastro.julian_date + +# Body type imports from _libastro +Body = _libastro.Body +Planet = _libastro.Planet +PlanetMoon = _libastro.PlanetMoon +FixedBody = _libastro.FixedBody +EllipticalBody = _libastro.EllipticalBody +ParabolicBody = _libastro.ParabolicBody +HyperbolicBody = _libastro.HyperbolicBody +EarthSatellite = _libastro.EarthSatellite + +# Database and coordinate functions from _libastro +readdb = _libastro.readdb +readtle = _libastro.readtle +constellation = _libastro.constellation +separation = _libastro.separation +unrefract = _libastro.unrefract +now = _libastro.now + +# Star atlas functions from _libastro +millennium_atlas = _libastro.millennium_atlas +uranometria = _libastro.uranometria +uranometria2000 = _libastro.uranometria2000 + +# Special planet classes from _libastro +Jupiter = _libastro.Jupiter +Saturn = _libastro.Saturn +Moon = _libastro.Moon + +# Dynamically created planet classes +class Mercury(Planet): + __planet__: Final = 0 + +class Venus(Planet): + __planet__: Final = 1 + +class Mars(Planet): + __planet__: Final = 2 + +class Uranus(Planet): + __planet__: Final = 5 + +class Neptune(Planet): + __planet__: Final = 6 + +class Pluto(Planet): + __planet__: Final = 7 + +class Sun(Planet): + __planet__: Final = 8 + +# Planet moon classes +class Phobos(PlanetMoon): + __planet__: Final = 10 + +class Deimos(PlanetMoon): + __planet__: Final = 11 + +class Io(PlanetMoon): + __planet__: Final = 12 + +class Europa(PlanetMoon): + __planet__: Final = 13 + +class Ganymede(PlanetMoon): + __planet__: Final = 14 + +class Callisto(PlanetMoon): + __planet__: Final = 15 + +class Mimas(PlanetMoon): + __planet__: Final = 16 + +class Enceladus(PlanetMoon): + __planet__: Final = 17 + +class Tethys(PlanetMoon): + __planet__: Final = 18 + +class Dione(PlanetMoon): + __planet__: Final = 19 + +class Rhea(PlanetMoon): + __planet__: Final = 20 + +class Titan(PlanetMoon): + __planet__: Final = 21 + +class Hyperion(PlanetMoon): + __planet__: Final = 22 + +class Iapetus(PlanetMoon): + __planet__: Final = 23 + +class Ariel(PlanetMoon): + __planet__: Final = 24 + +class Umbriel(PlanetMoon): + __planet__: Final = 25 + +class Titania(PlanetMoon): + __planet__: Final = 26 + +class Oberon(PlanetMoon): + __planet__: Final = 27 + +class Miranda(PlanetMoon): + __planet__: Final = 28 + +# Newton's method +def newton(f: Callable[[float], float], x0: float, x1: float, precision: float = ...) -> float: ... + +# Equinox and solstice functions +def holiday(d0: _libastro._DateInitType, motion: float, offset: float) -> Date: ... +def previous_vernal_equinox(date: _libastro._DateInitType) -> Date: ... +def next_vernal_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_summer_solstice(date: _libastro._DateInitType) -> Date: ... +def next_summer_solstice(date: _libastro._DateInitType) -> Date: ... +def previous_autumnal_equinox(date: _libastro._DateInitType) -> Date: ... +def next_autumnal_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_winter_solstice(date: _libastro._DateInitType) -> Date: ... +def next_winter_solstice(date: _libastro._DateInitType) -> Date: ... + +# Synonyms +next_spring_equinox = next_vernal_equinox +previous_spring_equinox = previous_vernal_equinox +next_fall_equinox = next_autumnal_equinox +next_autumn_equinox = next_autumnal_equinox +previous_fall_equinox = previous_autumnal_equinox +previous_autumn_equinox = previous_autumnal_equinox + +# More general equinox/solstice functions +def previous_equinox(date: _libastro._DateInitType) -> Date: ... +def next_equinox(date: _libastro._DateInitType) -> Date: ... +def previous_solstice(date: _libastro._DateInitType) -> Date: ... +def next_solstice(date: _libastro._DateInitType) -> Date: ... +def previous_new_moon(date: _libastro._DateInitType) -> Date: ... +def next_new_moon(date: _libastro._DateInitType) -> Date: ... +def previous_first_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def next_first_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def previous_full_moon(date: _libastro._DateInitType) -> Date: ... +def next_full_moon(date: _libastro._DateInitType) -> Date: ... +def previous_last_quarter_moon(date: _libastro._DateInitType) -> Date: ... +def next_last_quarter_moon(date: _libastro._DateInitType) -> Date: ... + +# Exceptions +class CircumpolarError(ValueError): ... +class NeverUpError(CircumpolarError): ... +class AlwaysUpError(CircumpolarError): ... + +# Observer class +class Observer(_libastro.Observer): + __slots__: list[str] = ["name"] + + name: object + + def copy(self) -> Self: ... + __copy__ = copy + def compute_pressure(self) -> None: ... + def previous_transit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def next_transit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def previous_antitransit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def next_antitransit(self, body: Body, start: _libastro._DateInitType | None = None) -> Date: ... + def disallow_circumpolar(self, declination: float) -> None: ... + def previous_rising(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def previous_setting(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_rising(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_setting(self, body: Body, start: _libastro._DateInitType | None = None, use_center: bool = False) -> Date: ... + def next_pass( + self, body: EarthSatellite, singlepass: bool = True + ) -> tuple[Date | None, Date | None, Date | None, Date | None, Date | None, Date | None]: ... + +# Time conversion functions +def localtime(date: Date | float) -> _datetime: ... + +class _UTC(_tzinfo): + ZERO: _timedelta + def tzname(self, dt: _datetime | None, /) -> Never: ... + def utcoffset(self, dt: _datetime | None) -> _timedelta: ... + def dst(self, dt: _datetime | None) -> _timedelta: ... + +UTC: _UTC + +def to_timezone(date: Date | float, tzinfo: _tzinfo) -> _datetime: ... + +# Coordinate classes +class Coordinate: + epoch: Date + + @overload + def __init__(self, body: Body, *, epoch: _libastro._DateInitType | None = None) -> None: ... + @overload + def __init__(self, coord1: float | str, coord2: float | str, *, epoch: _libastro._DateInitType | None = None) -> None: ... + @overload + def __init__(self, coord: Coordinate, *, epoch: _libastro._DateInitType | None = None) -> None: ... + +class Equatorial(Coordinate): + ra: Angle + dec: Angle + + def get(self) -> tuple[Angle, Angle]: ... + def set(self, ra: float | str, dec: float | str) -> None: ... + + to_radec = get + from_radec = set + +class LonLatCoordinate(Coordinate): + lon: Angle + lat: Angle + + def set(self, lon: float | str, lat: float | str) -> None: ... + def get(self) -> tuple[Angle, Angle]: ... + + @property + def long(self) -> Angle: ... + @long.setter + def long(self, value: Angle) -> None: ... + +class Ecliptic(LonLatCoordinate): + def to_radec(self) -> tuple[Angle, Angle]: ... + def from_radec(self, ra: float | str, dec: float | str) -> None: ... + +class Galactic(LonLatCoordinate): + def to_radec(self) -> tuple[Angle, Angle]: ... + def from_radec(self, ra: float | str, dec: float | str) -> None: ... + +# Backwards compatibility aliases +date = Date +angle = Angle +LongLatCoordinate = LonLatCoordinate + +# Catalog functions +@overload +def star(name: str, observer: Observer, /) -> FixedBody: ... +@overload +def star(name: str, when: _libastro._DateInitType, epoch: _libastro._DateInitType) -> FixedBody: ... + +def city(name: str) -> Observer: ... diff --git a/stubs/ephem/ephem/_libastro.pyi b/stubs/ephem/ephem/_libastro.pyi new file mode 100644 index 000000000000..1d21f7e04c70 --- /dev/null +++ b/stubs/ephem/ephem/_libastro.pyi @@ -0,0 +1,394 @@ +import builtins +from _typeshed import Unused +from datetime import datetime as _datetime +from typing import Final, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated, disjoint_base + +_DateInitType: TypeAlias = ( + Date + | float + | str + | tuple[int] + | tuple[int, int] + | tuple[int, int, float] + | tuple[int, int, float, float] + | tuple[int, int, float, float, float] + | tuple[int, int, float, float, float, float] + | _datetime +) + +@type_check_only +class _DateDescriptor: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Date: ... + + def __set__(self, obj: object, value: _DateInitType) -> None: ... + +@type_check_only +class _AngleDescriptorRadiansHours: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + def __set__(self, obj: object, value: float | str) -> None: ... + +@type_check_only +class _AngleDescriptorRadiansDegrees: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + def __set__(self, obj: object, value: float | str) -> None: ... + +@type_check_only +class _AngleDescriptorDegreesRadians: + @overload + def __get__(self, obj: None, objtype: type | None = None) -> Self: ... + @overload + def __get__(self, obj: object, objtype: type | None = None) -> Angle: ... + + @overload + @deprecated("Do not pass Angle objects! The radian value will be incorrectly interpreted as degrees.") + def __set__(self, obj: object, value: Angle) -> None: ... + @overload + def __set__(self, obj: object, value: float | str) -> None: ... + +J2000: Final[float] +MJD0: Final[float] +earth_radius: Final[float] +meters_per_au: Final[float] +moon_radius: Final[float] +sun_radius: Final[float] + +@disjoint_base +class Angle(float): # type: ignore[type-var] + def __new__(cls, *args: Unused, **kwargs: Unused) -> Never: ... + @property + def norm(self) -> Angle: ... + @property + def znorm(self) -> Angle: ... + +class Date(float): + @overload + def __new__(cls) -> Date: ... + @overload + def __new__(cls, date: _DateInitType, /) -> Date: ... + + def triple(self) -> builtins.tuple[int, int, float]: ... + def tuple(self) -> builtins.tuple[int, int, int, int, int, float]: ... + def datetime(self) -> _datetime: ... + +@disjoint_base +class Observer: + lat: _AngleDescriptorRadiansDegrees + lon: _AngleDescriptorRadiansDegrees + long: _AngleDescriptorRadiansDegrees + elevation: float + elev: float + temp: float + temperature: float + pressure: float + horizon: _AngleDescriptorRadiansDegrees + epoch: _DateDescriptor + date: _DateDescriptor + + def __init__(self) -> None: ... + def sidereal_time(self) -> Angle: ... + def radec_of(self, az: float | str, alt: float | str) -> tuple[Angle, Angle]: ... + +@disjoint_base +class Body: + @property + def name(self) -> str | None: ... + @property + def a_ra(self) -> Angle: ... + @property + def a_dec(self) -> Angle: ... + @property + def a_epoch(self) -> Date: ... + @property + def ra(self) -> Angle: ... + @property + def dec(self) -> Angle: ... + @property + def g_ra(self) -> Angle: ... + @property + def g_dec(self) -> Angle: ... + @property + def elong(self) -> Angle: ... + @property + def mag(self) -> float: ... + @property + def size(self) -> float: ... + @property + def radius(self) -> Angle: ... + @property + def alt(self) -> Angle: ... + @property + def az(self) -> Angle: ... + @property + def ha(self) -> Angle: ... + @property + def rise_time(self) -> Date | None: ... + @property + def rise_az(self) -> Angle | None: ... + @property + def transit_time(self) -> Date | None: ... + @property + def transit_alt(self) -> Angle | None: ... + @property + def set_time(self) -> Date | None: ... + @property + def set_az(self) -> Angle | None: ... + @property + def circumpolar(self) -> bool: ... + @property + def neverup(self) -> bool: ... + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + def __copy__(self) -> Self: ... + + @overload + def compute(self, observer: Observer, /) -> None: ... + @overload + def compute(self, when: _DateInitType = ..., epoch: _DateInitType = ...) -> None: ... + + def copy(self) -> Self: ... + def writedb(self) -> str: ... + def parallactic_angle(self) -> Angle: ... + +class Planet(Body): + @property + def hlon(self) -> Angle: ... + @property + def hlat(self) -> Angle: ... + @property + def sun_distance(self) -> float: ... + @property + def earth_distance(self) -> float: ... + @property + def phase(self) -> float: ... + @property + def hlong(self) -> Angle: ... + + @overload + def __init__(self, observer: Observer, /) -> None: ... + @overload + def __init__(self, when: _DateInitType, /, epoch: _DateInitType = ...) -> None: ... + @overload + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +@disjoint_base +class Moon(Planet): + @property + def libration_lat(self) -> Angle: ... + @property + def libration_long(self) -> Angle: ... + @property + def colong(self) -> Angle: ... + @property + def moon_phase(self) -> float: ... + @property + def subsolar_lat(self) -> Angle: ... + +@disjoint_base +class Jupiter(Planet): + @property + def cmlI(self) -> Angle: ... + @property + def cmlII(self) -> Angle: ... + +@disjoint_base +class Saturn(Planet): + @property + def earth_tilt(self) -> Angle: ... + @property + def sun_tilt(self) -> Angle: ... + +@disjoint_base +class PlanetMoon: + @property + def name(self) -> str: ... + @property + def a_ra(self) -> Angle: ... + @property + def a_dec(self) -> Angle: ... + @property + def ra(self) -> Angle: ... + @property + def dec(self) -> Angle: ... + @property + def g_ra(self) -> Angle: ... + @property + def g_dec(self) -> Angle: ... + @property + def alt(self) -> Angle: ... + @property + def az(self) -> Angle: ... + @property + def x(self) -> float: ... + @property + def y(self) -> float: ... + @property + def z(self) -> float: ... + @property + def earth_visible(self) -> float: ... + @property + def sun_visible(self) -> float: ... + + @overload + def __init__(self, observer: Observer, /) -> None: ... + @overload + def __init__(self, when: _DateInitType, /, epoch: _DateInitType = ...) -> None: ... + @overload + def __init__(self, **kwargs: Unused) -> None: ... + + def __copy__(self) -> Self: ... + + @overload + def compute(self, observer: Observer, /) -> None: ... + @overload + def compute(self, when: _DateInitType = ..., epoch: _DateInitType = ...) -> None: ... + + def copy(self) -> Self: ... + def writedb(self) -> str: ... + def parallactic_angle(self) -> Angle: ... + +class FixedBody(Body): + name: str | None + mag: float + _spect: str + _ratio: float + _pa: _AngleDescriptorRadiansDegrees + _epoch: _DateDescriptor + _ra: _AngleDescriptorRadiansHours + _dec: _AngleDescriptorRadiansDegrees + _pmra: float + _pmdec: float + _class: str + + def __init__(self) -> None: ... + +class EllipticalBody(Planet): + name: str | None + _inc: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _M: _AngleDescriptorDegreesRadians + _epoch_M: _DateDescriptor + _epoch: _DateDescriptor + _H: float + _G: float + _g: float + _k: float + _a: float + _size: float + _e: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +class ParabolicBody(Planet): + name: str | None + _epoch: _DateDescriptor + _epoch_p: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _q: float + _g: float + _k: float + _size: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +class HyperbolicBody(Planet): + name: str | None + _epoch: _DateDescriptor + _epoch_p: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _Om: _AngleDescriptorDegreesRadians + _om: _AngleDescriptorDegreesRadians + _e: float + _q: float + _g: float + _k: float + _size: float + + def __init__(self, *args: Unused, **kwargs: Unused) -> None: ... + +@disjoint_base +class EarthSatellite(Body): + name: str | None + epoch: _DateDescriptor + _epoch: _DateDescriptor + _inc: _AngleDescriptorDegreesRadians + _raan: _AngleDescriptorDegreesRadians + _ap: _AngleDescriptorDegreesRadians + _M: _AngleDescriptorDegreesRadians + n: float + inc: float + raan: float + e: float + ap: float + M: float + decay: float + drag: float + orbit: float + _n: float + _e: float + _decay: float + _drag: float + _orbit: int + catalog_number: str | None + + @property + def sublat(self) -> Angle: ... + @property + def sublong(self) -> Angle: ... + @property + def elevation(self) -> float: ... + @property + def range(self) -> float: ... + @property + def range_velocity(self) -> float: ... + @property + def eclipsed(self) -> bool: ... + +@type_check_only +class _MoonPhases(TypedDict): + new: Date + full: Date + +def builtin_planets() -> list[tuple[int, str, str]]: ... +def degrees(angle: float | str, /) -> Angle: ... +def hours(angle: float | str, /) -> Angle: ... +def now() -> Date: ... +def separation( + obj1: tuple[float | str, float | str] | Body | Observer, obj2: tuple[float | str, float | str] | Body | Observer, / +) -> Angle: ... +def readdb(db_line: str, /) -> Body: ... +def readtle(name: str, line1: str, line2: str, /) -> EarthSatellite: ... +def unrefract(pressure: float, temperature: float, apparent_alt: float, /) -> Angle: ... +def uranometria(ra: float | str, dec: float | str, /) -> int: ... +def uranometria2000(ra: float | str, dec: float | str, /) -> int: ... +def millennium_atlas(ra: float | str, dec: float | str, /) -> int: ... + +@overload +def constellation(position: Body) -> tuple[str, str]: ... +@overload +def constellation(position: tuple[Angle | float, Angle | float], epoch: Date | float = ...) -> tuple[str, str]: ... + +def julian_date(date: _DateInitType | Observer = ..., /) -> float: ... +def delta_t(date: _DateInitType | Observer = ..., /) -> float: ... +def moon_phases(date: _DateInitType | Observer = ...) -> _MoonPhases: ... +def eq_ecl(epoch: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def ecl_eq(epoch: Date | float, lon: Angle | float, lat: Angle | float, /) -> tuple[Angle, Angle]: ... +def eq_gal(epoch: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def gal_eq(epoch: Date | float, glon: Angle | float, glat: Angle | float, /) -> tuple[Angle, Angle]: ... +def precess(epoch1: Date | float, epoch2: Date | float, ra: Angle | float, dec: Angle | float, /) -> tuple[Angle, Angle]: ... +def _next_pass( + observer: Observer, body: Body, / +) -> tuple[Date | None, Angle | None, Date | None, Angle | None, Date | None, Angle | None]: ... diff --git a/stubs/ephem/ephem/cities.pyi b/stubs/ephem/ephem/cities.pyi new file mode 100644 index 000000000000..fa6959106a6a --- /dev/null +++ b/stubs/ephem/ephem/cities.pyi @@ -0,0 +1,5 @@ +from . import Observer + +def city(name: str) -> Observer: ... +def lookup(address: str) -> None: ... +def lookup_with_geonames(q: str, username: str) -> Observer: ... diff --git a/stubs/ephem/ephem/stars.pyi b/stubs/ephem/ephem/stars.pyi new file mode 100644 index 000000000000..0806c1be73e0 --- /dev/null +++ b/stubs/ephem/ephem/stars.pyi @@ -0,0 +1,15 @@ +from typing import Final, overload + +from . import FixedBody, Observer +from ._libastro import _DateInitType + +db: Final[str] +stars: dict[str, FixedBody] + +@overload +def star(name: str, observer: Observer, /) -> FixedBody: ... +@overload +def star(name: str, when: _DateInitType = ..., epoch: _DateInitType = ...) -> FixedBody: ... + +STAR_NUMBER_NAME: Final[dict[int, str]] +STAR_NAME_NUMBER: Final[dict[str, int]] diff --git a/stubs/et_xmlfile/METADATA.toml b/stubs/et_xmlfile/METADATA.toml new file mode 100644 index 000000000000..db02b864055f --- /dev/null +++ b/stubs/et_xmlfile/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.*" +upstream-repository = "https://foss.heptapod.net/openpyxl/et_xmlfile" diff --git a/stubs/et_xmlfile/et_xmlfile/__init__.pyi b/stubs/et_xmlfile/et_xmlfile/__init__.pyi new file mode 100644 index 000000000000..ddf9bb3b811f --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Final + +from .xmlfile import xmlfile as xmlfile + +__version__: Final[str] +__author__: Final[str] +__license__: Final[str] +__author_email__: Final[str] +__url__: Final[str] diff --git a/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi b/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi new file mode 100644 index 000000000000..217728dbee3b --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/incremental_tree.pyi @@ -0,0 +1,173 @@ +import xml.etree.ElementTree as ET +from _typeshed import Unused +from collections.abc import Callable +from typing import Any, Literal, overload + +def current_global_nsmap() -> dict[str, str]: ... + +class IncrementalTree(ET.ElementTree): + def write( # type: ignore[override] + self, + file_or_filename: ET._FileWrite, + encoding: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + method: Literal["xml", "html", "text"] | None = None, # does not accept 'c14n', unlike parent method + *, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + ) -> None: ... + +def process_attribs( + elem: ET.Element[Any], + is_nsmap_scope_changed: bool | None, + default_ns_attr_prefix: str | None, + nsmap_scope: dict[str, str], + global_nsmap: dict[str, str], + new_namespace_prefixes: set[str], + uri_to_prefix: dict[str, str], +) -> tuple[list[tuple[str, str]], str | None, dict[str, str]]: ... +def write_elem_start( + write: Callable[..., None], + elem: ET.Element[Any], + nsmap_scope: dict[str, str], + global_nsmap: dict[str, str], + short_empty_elements: bool | None, + is_html: bool | None, + is_root: bool = False, + uri_to_prefix: dict[str, str] | None = None, + default_ns_attr_prefix: str | None = None, + new_nsmap: dict[str, str] | None = None, + **kwargs: Unused, +) -> tuple[str | None, dict[str, str], str | None, dict[str, str] | None, bool]: ... + +@overload +def tostring( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> bytes: ... +@overload +def tostring( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> str: ... +@overload +def tostring( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> Any: ... + +@overload +def tostringlist( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[bytes]: ... +@overload +def tostringlist( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[str]: ... +@overload +def tostringlist( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = False, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> list[Any]: ... + +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: None = None, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> bytes: ... +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: Literal["unicode"], + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> str: ... +@overload +def compat_tostring( + element: ET.Element[Any], + encoding: str, + method: Literal["xml", "html", "text"] | None = None, + *, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + nsmap: dict[str, str] | None = None, + root_ns_only: bool = True, + minimal_ns_only: bool = False, + tree_cls: type[ET.ElementTree] = ..., +) -> Any: ... diff --git a/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi b/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi new file mode 100644 index 000000000000..ffa96d78670c --- /dev/null +++ b/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi @@ -0,0 +1,36 @@ +import types +import xml.etree.ElementTree as ET +from collections.abc import Callable, Generator +from contextlib import _GeneratorContextManager, contextmanager +from typing import Any + +class LxmlSyntaxError(Exception): ... + +class _IncrementalFileWriter: + global_nsmap: dict[str, str] + is_html: bool + def __init__(self, output_file: Callable[[str], object]) -> None: ... + @contextmanager + def element( + self, + tag: str | ET._ElementCallable, + attrib: dict[str, str] | None = None, + nsmap: dict[str, str] | None = None, + **_extra: str, + ) -> Generator[None]: ... + def write(self, arg: str | ET.Element[Any]) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None + ) -> None: ... + +class xmlfile: + encoding: str + writer_cm: _GeneratorContextManager[tuple[Callable[[str], object], str]] | None + def __init__( + self, output_file: ET._FileWrite, buffered: bool = False, encoding: str = "utf-8", close: bool = False + ) -> None: ... + def __enter__(self) -> _IncrementalFileWriter: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: types.TracebackType | None + ) -> None: ... diff --git a/stubs/fanstatic/@tests/stubtest_allowlist.txt b/stubs/fanstatic/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e51f685c4d08 --- /dev/null +++ b/stubs/fanstatic/@tests/stubtest_allowlist.txt @@ -0,0 +1,69 @@ +# Error: is not present in stub +# ============================= +# These are methods and attributes that really should have been +# prefixed with a `_`, since they should only really be used +# internally +fanstatic.core.Asset.init_dependency_nr +fanstatic.core.Library.init_library_nr + +# In order to catch errors where DummyNeededResources would be called +# with clear/library_url/resources these methods were dropped from the +# stub. We would prefer to use @type_error() once that is an option +fanstatic.core.DummyNeededResources.clear +fanstatic.core.DummyNeededResources.library_url +fanstatic.core.DummyNeededResources.resources + +fanstatic.compiler.mtime + +# Error: is inconsistent +# ====================== +# The core API for Dependable is a bit annoying, since the base class +# should really be abstract and instead defines some attributes as +# None, even though all subclasses populate them, so these have been +# made abstract to make defining correct subclasses more easy +fanstatic.core.Asset.depends +fanstatic.core.Asset.resources +fanstatic.core.Asset.supports +fanstatic.core.Dependable.depends +fanstatic.core.Dependable.resources +fanstatic.core.Dependable.supports +fanstatic.core.Group.depends +fanstatic.core.Group.resources +fanstatic.core.Group.supports + +# The API for Compiler has very much the same problem, so these are +# some more attributes/methods that have been made abstract for the +# purposes of type checking +fanstatic.compiler.CommandlineBase.command +fanstatic.compiler.Compiler.name +fanstatic.compiler.Compiler.source_extension +fanstatic.compiler.Minifier.name +fanstatic.compiler.Minifier.source_extension +fanstatic.compiler.Minifier.target_extension +fanstatic.compiler.NullCompiler.name +fanstatic.registry.Registry.ENTRY_POINT + +# This is only inconsistent because the library authors set this +# attribute to `None` on the class, so they could assign a docstring +# to it. `__init__` will always populate this attribute with a `str` +fanstatic.core.Library.path + +# Error: variable differs from runtime type +# ====================== +# These are some sentinel objects which use the NewType pattern to create a +# distinct type +fanstatic.compiler.SOURCE +fanstatic.compiler.TARGET +fanstatic.core.NOTHING +fanstatic.core.REQUIRED_DEFAULT_MARKER + +# Error: is not present at runtime +# ================================ +# See above, defining correct subclasses is more easy with abstract +# properties on the superclass +fanstatic.injector.InjectorPlugin.name + +# Error: failed to find stubs +# =========================== +# Tests should not be part of the stubs +fanstatic.tests.* diff --git a/stubs/fanstatic/METADATA.toml b/stubs/fanstatic/METADATA.toml new file mode 100644 index 000000000000..a7eea5dca12e --- /dev/null +++ b/stubs/fanstatic/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.7.*" +upstream-repository = "https://github.com/zopefoundation/fanstatic" +dependencies = ["types-setuptools", "types-WebOb"] diff --git a/stubs/fanstatic/fanstatic/__init__.pyi b/stubs/fanstatic/fanstatic/__init__.pyi new file mode 100644 index 000000000000..9527cb5fb528 --- /dev/null +++ b/stubs/fanstatic/fanstatic/__init__.pyi @@ -0,0 +1,43 @@ +from fanstatic.compiler import Compiler as Compiler, Minifier as Minifier, sdist_compile as sdist_compile +from fanstatic.core import ( + BUNDLE_PREFIX as BUNDLE_PREFIX, + DEBUG as DEBUG, + DEFAULT_SIGNATURE as DEFAULT_SIGNATURE, + MINIFIED as MINIFIED, + NEEDED as NEEDED, + VERSION_PREFIX as VERSION_PREFIX, + ConfigurationError as ConfigurationError, + Group as Group, + GroupResource as GroupResource, + Library as Library, + LibraryDependencyCycleError as LibraryDependencyCycleError, + NeededResources as NeededResources, + Resource as Resource, + Slot as Slot, + SlotError as SlotError, + UnknownResourceError as UnknownResourceError, + UnknownResourceExtension as UnknownResourceExtension, + UnknownResourceExtensionError as UnknownResourceExtensionError, + clear_needed as clear_needed, + del_needed as del_needed, + get_needed as get_needed, + init_needed as init_needed, + register_inclusion_renderer as register_inclusion_renderer, + set_auto_register_library as set_auto_register_library, + set_resource_file_existence_checking as set_resource_file_existence_checking, +) +from fanstatic.inclusion import Inclusion as Inclusion, bundle_resources as bundle_resources, sort_resources as sort_resources +from fanstatic.injector import Injector as Injector, make_injector as make_injector +from fanstatic.publisher import ( + Delegator as Delegator, + LibraryPublisher as LibraryPublisher, + Publisher as Publisher, + make_publisher as make_publisher, +) +from fanstatic.registry import ( + CompilerRegistry as CompilerRegistry, + LibraryRegistry as LibraryRegistry, + MinifierRegistry as MinifierRegistry, + get_library_registry as get_library_registry, +) +from fanstatic.wsgi import Fanstatic as Fanstatic, Serf as Serf, make_fanstatic as make_fanstatic, make_serf as make_serf diff --git a/stubs/fanstatic/fanstatic/checksum.pyi b/stubs/fanstatic/fanstatic/checksum.pyi new file mode 100644 index 000000000000..316137739b11 --- /dev/null +++ b/stubs/fanstatic/fanstatic/checksum.pyi @@ -0,0 +1,10 @@ +from _typeshed import GenericPath, StrOrBytesPath, StrPath +from collections.abc import Iterator +from typing import AnyStr + +VCS_NAMES: list[str] +IGNORED_EXTENSIONS: list[str] + +def list_directory(path: GenericPath[AnyStr], include_directories: bool = True) -> Iterator[AnyStr]: ... +def mtime(path: StrOrBytesPath) -> str: ... +def md5(path: StrPath) -> str: ... diff --git a/stubs/fanstatic/fanstatic/compiler.pyi b/stubs/fanstatic/fanstatic/compiler.pyi new file mode 100644 index 000000000000..3ac5c78d6dd4 --- /dev/null +++ b/stubs/fanstatic/fanstatic/compiler.pyi @@ -0,0 +1,124 @@ +from _typeshed import StrOrBytesPath +from abc import abstractmethod +from logging import Logger +from subprocess import Popen +from typing import Any, ClassVar, Literal, NewType + +import setuptools.command.sdist +from fanstatic.core import Resource + +logger: Logger + +class CompilerError(Exception): ... + +class Compiler: + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def source_extension(self) -> str: ... + def __call__(self, resource: Resource, force: bool = False) -> None: ... + def process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Any: ... + def should_process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> bool: ... + @property + @abstractmethod + def available(self) -> bool: ... + def source_path(self, resource: Resource) -> str | None: ... + def target_path(self, resource: Resource) -> str | None: ... + +class Minifier(Compiler): + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def source_extension(self) -> str: ... + @property + @abstractmethod + def target_extension(self) -> str: ... + def source_to_target(self, resource: Resource) -> str: ... + +def compile_resources(argv: list[str] = ...) -> None: ... + +class sdist_compile(setuptools.command.sdist.sdist): ... + +class NullCompiler(Compiler): + name: ClassVar[Literal[""]] + source_extension = NotImplemented + def source_path(self, resource: Resource) -> None: ... + def target_path(self, resource: Resource) -> None: ... + def should_process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Literal[False]: ... + @property + def available(self) -> Literal[False]: ... + +_SourceType = NewType("_SourceType", object) +_TargetType = NewType("_TargetType", object) +SOURCE: _SourceType +TARGET: _TargetType + +class CommandlineBase: + @property + @abstractmethod + def command(self) -> str: ... + arguments: ClassVar[list[str]] + @property + def available(self) -> bool: ... + def process(self, source: StrOrBytesPath | _SourceType, target: StrOrBytesPath | _TargetType) -> Popen[str]: ... + +class CoffeeScript(CommandlineBase, Compiler): + name: ClassVar[Literal["coffee"]] + command: ClassVar[Literal["coffee"]] + source_extension = NotImplemented + def process( # type: ignore[override] + self, source: StrOrBytesPath | _SourceType, target: StrOrBytesPath | _TargetType + ) -> None: ... + +COFFEE_COMPILER: CoffeeScript + +class LESS(CommandlineBase, Compiler): + name: ClassVar[Literal["less"]] + command: ClassVar[Literal["lessc"]] + source_extension = NotImplemented + +LESS_COMPILER: LESS + +class SASS(CommandlineBase, Compiler): + name: ClassVar[Literal["sass"]] + command: ClassVar[Literal["sass"]] + source_extension: ClassVar[Literal[".scss"]] + +SASS_COMPILER: SASS + +class PythonPackageBase: + @property + @abstractmethod + def package(self) -> str: ... + @property + def available(self) -> bool: ... + +class CSSMin(PythonPackageBase, Minifier): + name: ClassVar[Literal["cssmin"]] + package: ClassVar[Literal["cssmin"]] + source_extension = NotImplemented + target_extension: ClassVar[Literal[".min.css"]] + +CSSMIN_MINIFIER: CSSMin + +class JSMin(PythonPackageBase, Minifier): + name: ClassVar[Literal["jsmin"]] + package: ClassVar[Literal["jsmin"]] + source_extension = NotImplemented + target_extension: ClassVar[Literal[".min.js"]] + +JSMIN_MINIFIER: JSMin + +class Closure(PythonPackageBase, Minifier): + name: ClassVar[Literal["closure"]] + package: ClassVar[Literal["closure"]] + source_extension = NotImplemented + target_extension: Literal[".min.js"] + arguments: ClassVar[list[str]] + def process(self, source: StrOrBytesPath, target: StrOrBytesPath) -> Popen[str]: ... + +CLOSURE_MINIFIER: Closure diff --git a/stubs/fanstatic/fanstatic/config.pyi b/stubs/fanstatic/fanstatic/config.pyi new file mode 100644 index 000000000000..551600e14faf --- /dev/null +++ b/stubs/fanstatic/fanstatic/config.pyi @@ -0,0 +1,10 @@ +from _typeshed import SupportsItems +from typing import TypeVar + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +BOOL_CONFIG: set[str] + +def asbool(obj: object) -> bool: ... +def convert_config(config: SupportsItems[_KT, _VT]) -> dict[_KT, _VT | bool]: ... diff --git a/stubs/fanstatic/fanstatic/core.pyi b/stubs/fanstatic/fanstatic/core.pyi new file mode 100644 index 000000000000..9197bdd323c2 --- /dev/null +++ b/stubs/fanstatic/fanstatic/core.pyi @@ -0,0 +1,236 @@ +from abc import abstractmethod +from collections.abc import Callable, Iterable +from threading import local +from types import ModuleType +from typing import Literal, NewType, TypeAlias + +from fanstatic.compiler import Compiler, Minifier + +_Renderer: TypeAlias = Callable[[str], str] + +DEFAULT_SIGNATURE: str +VERSION_PREFIX: str +BUNDLE_PREFIX: str +NEEDED: str +DEBUG: str +MINIFIED: str + +def set_resource_file_existence_checking(v: bool) -> None: ... +def set_auto_register_library(v: bool) -> None: ... + +class UnknownResourceExtensionError(Exception): ... +class ModeResourceDependencyError(Exception): ... + +UnknownResourceExtension = UnknownResourceExtensionError + +class UnknownResourceError(Exception): ... +class ConfigurationError(Exception): ... +class LibraryDependencyCycleError(Exception): ... +class SlotError(Exception): ... + +class Library: + path: str + name: str + rootpath: str + ignores: list[str] + version: str | None + known_resources: dict[str, Resource] + known_assets: dict[str, Asset] + module: ModuleType + compilers: dict[str, Compiler] + minifiers: dict[str, Minifier] + def __init__( + self, + name: str, + rootpath: str, + ignores: list[str] | None = None, + version: str | None = None, + compilers: dict[str, Compiler] | None = None, + minifiers: dict[str, Minifier] | None = None, + ) -> None: ... + def check_dependency_cycle(self, resource: Resource) -> None: ... + def register(self, resource: Resource) -> None: ... + def signature(self, recompute_hashes: bool = False, version_method: Callable[[str], str] | None = None) -> str: ... + +def caller_dir() -> str: ... + +class InclusionRenderers(dict[str, tuple[int, _Renderer]]): + def register(self, extension: str, renderer: _Renderer, order: int | None = None) -> None: ... + +inclusion_renderers: InclusionRenderers + +def register_inclusion_renderer(extension: str, renderer: _Renderer, order: int | None = None) -> None: ... +def render_ico(url: str) -> str: ... +def render_css(url: str) -> str: ... +def render_js(url: str) -> str: ... +def render_print_css(url: str) -> str: ... +def render_screen_css(url: str) -> str: ... + +class Renderable: + @abstractmethod + def render(self, library_url: str) -> str: ... + +class Dependable: + @property + @abstractmethod + def resources(self) -> set[Dependable]: ... + @property + @abstractmethod + def depends(self) -> set[Dependable]: ... + @property + @abstractmethod + def supports(self) -> set[Dependable]: ... + def add_dependency(self, dependency: Dependable) -> None: ... + @abstractmethod + def set_dependencies(self, dependencies: Iterable[Dependable] | None) -> None: ... + @abstractmethod + def list_assets(self) -> set[Asset]: ... + def list_supporting(self) -> set[Dependable]: ... + +class Asset(Dependable): + resources: set[Dependable] + depends: set[Dependable] + supports: set[Dependable] + library: Library + def __init__(self, library: Library, depends: Iterable[Dependable] | None = None) -> None: ... + def set_dependencies(self, depends: Iterable[Dependable] | None) -> None: ... + def list_assets(self) -> set[Asset]: ... + +_NothingType = NewType("_NothingType", object) +NOTHING: _NothingType + +class Resource(Renderable, Asset): + relpath: str + ext: str + mode_parent: str | None + compiler: Compiler + source: str | None + minifier: Minifier + minified: Resource | None + bottom: bool + dont_bundle: bool + renderer: _Renderer + modes: dict[str, Resource] + supersedes: list[Resource] + rollups: list[Resource] + def __init__( + self, + library: Library, + relpath: str, + depends: Iterable[Dependable] | None = None, + supersedes: list[Resource] | None = None, + bottom: bool = False, + renderer: _Renderer | None = None, + debug: str | Resource | None = None, + dont_bundle: bool = False, + minified: str | Resource | None = None, + minifier: Minifier | _NothingType = ..., + compiler: Compiler | _NothingType = ..., + source: str | None = None, + mode_parent: str | None = None, + ) -> None: ... + def fullpath(self, path: str | None = None) -> str: ... + def compile(self, force: bool = False) -> None: ... + def render(self, library_url: str) -> str: ... + def mode(self, mode: str | None) -> Resource: ... + def need(self, slots: dict[Slot, Resource] | None = None) -> None: ... + +_RequiredDefaultMarkerType = NewType("_RequiredDefaultMarkerType", object) +REQUIRED_DEFAULT_MARKER: _RequiredDefaultMarkerType + +class Slot(Asset): + default: Resource | None + ext: str + required: bool + def __init__( + self, + library: Library, + extension: str, + depends: Iterable[Dependable] | None = None, + required: bool | _RequiredDefaultMarkerType = ..., + default: Resource | None = None, + ) -> None: ... + +class FilledSlot(Renderable): + filledby: Resource + library: Library + relpath: str + bottom: bool + rollups: list[Resource] + dont_bundle: bool + ext: str + order: int + renderer: _Renderer + dependency_nr: int + modes: dict[str, FilledSlot] + def __init__(self, slot: Slot, resource: Resource) -> None: ... + def render(self, library_url: str) -> str: ... + def compile(self, force: bool = False) -> None: ... + def mode(self, mode: str | None) -> FilledSlot: ... + +class Group(Dependable): + resources: set[Dependable] + depends: set[Dependable] + supports: set[Dependable] + def __init__(self, depends: Iterable[Dependable]) -> None: ... + def set_dependencies(self, depends: Iterable[Dependable]) -> None: ... # type: ignore[override] + def list_assets(self) -> set[Asset]: ... + def need(self, slots: dict[Slot, Resource] | None = None) -> None: ... + +GroupResource = Group + +class NeededResources: + def __init__( + self, + versioning: bool = False, + versioning_use_md5: bool = False, + recompute_hashes: bool = True, + base_url: str | None = None, + script_name: str | None = None, + publisher_signature: str = "fanstatic", + resources: Iterable[Dependable] | None = None, + ) -> None: ... + def has_resources(self) -> bool: ... + def has_base_url(self) -> bool: ... + def set_base_url(self, url: str) -> None: ... + def need(self, resource: Resource | Group, slots: dict[Slot, Resource] | None = None) -> None: ... + def resources(self) -> set[Resource]: ... + def clear(self) -> None: ... + def library_url(self, library: Library) -> str: ... + +class DummyNeededResources: + def need(self, resource: Resource | Group, slots: dict[Slot, Resource] | None = None) -> None: ... + def has_resources(self) -> Literal[False]: ... + +thread_local_needed_data: local + +def init_needed( + versioning: bool = False, + versioning_use_md5: bool = False, + recompute_hashes: bool = True, + base_url: str | None = None, + script_name: str | None = None, + publisher_signature: str = ..., + resources: Iterable[Dependable] | None = None, +) -> NeededResources: ... +def del_needed() -> None: ... +def get_needed() -> NeededResources | DummyNeededResources: ... +def clear_needed() -> None: ... + +class Bundle(Renderable): + def __init__(self) -> None: ... + @property + def dirname(self) -> str: ... + @property + def library(self) -> Library: ... + @property + def renderer(self) -> _Renderer: ... + @property + def ext(self) -> str: ... + @property + def relpath(self) -> str: ... + def resources(self) -> list[Resource]: ... + def render(self, library_url: str) -> str: ... + def fits(self, resource: Resource) -> bool: ... + def append(self, resource: Resource) -> None: ... + def add_to_list(self, result: list[Renderable]) -> None: ... diff --git a/stubs/fanstatic/fanstatic/inclusion.pyi b/stubs/fanstatic/fanstatic/inclusion.pyi new file mode 100644 index 000000000000..53b0076396ef --- /dev/null +++ b/stubs/fanstatic/fanstatic/inclusion.pyi @@ -0,0 +1,22 @@ +from collections.abc import Iterable + +from fanstatic.core import Bundle, NeededResources, Resource + +def bundle_resources(resources: Iterable[Resource]) -> list[Resource | Bundle]: ... +def rollup_resources(resources: Iterable[Resource]) -> set[Resource]: ... +def sort_resources(resources: Iterable[Resource]) -> list[Resource]: ... + +class Inclusion: + needed: NeededResources + resources: list[Resource | Bundle] + def __init__( + self, + needed: NeededResources, + resources: Iterable[Resource] | None = None, + compile: bool = False, + bundle: bool = False, + mode: str | None = None, + rollup: bool = False, + ) -> None: ... + def __len__(self) -> int: ... + def render(self) -> str: ... diff --git a/stubs/fanstatic/fanstatic/injector.pyi b/stubs/fanstatic/fanstatic/injector.pyi new file mode 100644 index 000000000000..5d387b99d65a --- /dev/null +++ b/stubs/fanstatic/fanstatic/injector.pyi @@ -0,0 +1,60 @@ +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from abc import abstractmethod +from collections.abc import Iterable +from typing import Any, Literal, TypedDict, type_check_only +from typing_extensions import Unpack + +from fanstatic.core import Dependable, NeededResources, Resource +from fanstatic.inclusion import Inclusion +from webob import Request, Response + +@type_check_only +class _NeededResourcesConfig(TypedDict, total=False): + versioning: bool + versioning_use_md5: bool + recompute_hashes: bool + base_url: str | None + script_name: str | None + publisher_signature: str + resources: Iterable[Dependable] | None + +@type_check_only +class _InjectorPluginOptions(TypedDict, total=False): + compile: bool + bundle: bool + rollup: bool + debug: bool + minified: bool + +@type_check_only +class _TopBottomInjectorPluginOptions(_InjectorPluginOptions, total=False): + bottom: bool + force_bottom: bool + +CONTENT_TYPES: list[str] + +class Injector: + app: WSGIApplication + config: _NeededResourcesConfig + injector: InjectorPlugin + def __init__( + self, app: WSGIApplication, injector: InjectorPlugin | None = None, **config: Unpack[_NeededResourcesConfig] + ) -> None: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +class InjectorPlugin: + @property + @abstractmethod + def name(self) -> str: ... + def __init__(self, options: _InjectorPluginOptions) -> None: ... + def make_inclusion(self, needed: NeededResources, resources: set[Resource] | None = None) -> Inclusion: ... + def __call__( + self, html: bytes, needed: NeededResources, request: Request | None = None, response: Response | None = None + ) -> None: ... + +class TopBottomInjector(InjectorPlugin): + name: Literal["topbottom"] + def __init__(self, options: _TopBottomInjectorPluginOptions) -> None: ... + def group(self, needed: NeededResources) -> tuple[Inclusion, Inclusion]: ... + +def make_injector(app: WSGIApplication, global_config: Any, **local_config: Any) -> Injector: ... diff --git a/stubs/fanstatic/fanstatic/publisher.pyi b/stubs/fanstatic/fanstatic/publisher.pyi new file mode 100644 index 000000000000..ba239c5c7e47 --- /dev/null +++ b/stubs/fanstatic/fanstatic/publisher.pyi @@ -0,0 +1,48 @@ +from _typeshed import StrOrBytesPath +from _typeshed.wsgi import StartResponse, WSGIApplication, WSGIEnvironment +from collections.abc import Iterable +from typing import IO, Any, Literal + +from fanstatic.core import Library +from fanstatic.registry import LibraryRegistry +from webob import Request, Response +from webob.dec import wsgify +from webob.static import DirectoryApp, FileApp + +MINUTE_IN_SECONDS: Literal[60] +HOUR_IN_SECONDS: Literal[3600] +DAY_IN_SECONDS: Literal[86400] +YEAR_IN_SECONDS: int +FOREVER: int + +class BundleApp(FileApp): + filenames: list[str] + def __init__(self, rootpath: str, bundle: IO[bytes], filenames: Iterable[StrOrBytesPath]) -> None: ... + @wsgify + def __call__(self, req: Request) -> Response: ... + +class LibraryPublisher(DirectoryApp): + ignores: list[str] + library: Library + cached_apps: dict[str, FileApp] + def __init__(self, library: Library) -> None: ... + @wsgify + def __call__(self, req: Request) -> Response: ... + +class Publisher: + registry: LibraryRegistry + directory_publishers: dict[str, LibraryPublisher] + def __init__(self, registry: LibraryRegistry) -> None: ... + @wsgify + def __call__(self, request: Request) -> Response: ... + +class Delegator: + app: WSGIApplication + publisher: Publisher + publisher_signature: str + trigger: str + def __init__(self, app: WSGIApplication, publisher: Publisher, publisher_signature: str = "fanstatic") -> None: ... + def is_resource(self, request: Request) -> bool: ... + def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> Iterable[bytes]: ... + +def make_publisher(global_config: Any) -> Publisher: ... diff --git a/stubs/fanstatic/fanstatic/registry.pyi b/stubs/fanstatic/fanstatic/registry.pyi new file mode 100644 index 000000000000..c0a78589feea --- /dev/null +++ b/stubs/fanstatic/fanstatic/registry.pyi @@ -0,0 +1,50 @@ +from abc import abstractmethod +from collections.abc import Iterable +from threading import Lock +from typing import Any, ClassVar, Literal, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from fanstatic.compiler import Compiler, Minifier +from fanstatic.core import Library +from fanstatic.injector import InjectorPlugin + +# Used to be pkg_resources.EntryPoint, but any EntryPoint-like class with a `load` method works +@type_check_only +class _EntryPoint(Protocol): + def load(self) -> Any: ... # Can be any attribute in the module + +@type_check_only +class _HasName(Protocol): + @property + def name(self) -> str: ... + +_NamedT = TypeVar("_NamedT", bound=_HasName) + +prepare_lock: Lock + +class Registry(dict[str, _NamedT]): + @property + @abstractmethod + def ENTRY_POINT(self) -> str: ... + def __init__(self, items: Iterable[_NamedT] = ()) -> None: ... + def add(self, item: _NamedT) -> None: ... + def load_items_from_entry_points(self) -> None: ... + def make_item_from_entry_point(self, entry_point: _EntryPoint) -> Any: ... + @classmethod + def instance(cls) -> Self: ... + +class LibraryRegistry(Registry[Library]): + ENTRY_POINT: ClassVar[Literal["fanstatic.libraries"]] + prepared: bool + def prepare(self) -> None: ... + +get_library_registry = LibraryRegistry.instance + +class CompilerRegistry(Registry[Compiler]): + ENTRY_POINT: ClassVar[Literal["fanstatic.compilers"]] + +class MinifierRegistry(Registry[Minifier]): + ENTRY_POINT: ClassVar[Literal["fanstatic.minifiers"]] + +class InjectorRegistry(Registry[InjectorPlugin]): + ENTRY_POINT: ClassVar[Literal["fanstatic.injectors"]] diff --git a/stubs/fanstatic/fanstatic/wsgi.pyi b/stubs/fanstatic/fanstatic/wsgi.pyi new file mode 100644 index 000000000000..bd0859b091d3 --- /dev/null +++ b/stubs/fanstatic/fanstatic/wsgi.pyi @@ -0,0 +1,22 @@ +from _typeshed.wsgi import WSGIApplication +from typing import Any + +from fanstatic.core import Resource +from fanstatic.injector import InjectorPlugin +from fanstatic.publisher import Delegator +from webob import Request, Response +from webob.dec import wsgify + +def Fanstatic( + app: WSGIApplication, publisher_signature: str = "fanstatic", injector: InjectorPlugin | None = None, **config: Any +) -> Delegator: ... +def make_fanstatic(app: WSGIApplication, global_config: Any, **local_config: Any) -> Delegator: ... + +class Serf: + resource: Resource + def __init__(self, resource: Resource) -> None: ... + @wsgify + def __call__(self, request: Request) -> Response: ... + +def make_serf(global_config: Any, **local_config: Any) -> Serf: ... +def resolve(name: str, module: str | None = None) -> Any: ... diff --git a/stubs/first/METADATA.toml b/stubs/first/METADATA.toml new file mode 100644 index 000000000000..3fe3d66bda4d --- /dev/null +++ b/stubs/first/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.*" +upstream-repository = "https://github.com/hynek/first" diff --git a/stubs/first/first.pyi b/stubs/first/first.pyi new file mode 100644 index 000000000000..17fe072b2fe0 --- /dev/null +++ b/stubs/first/first.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable, Iterable +from typing import Any, TypeVar, overload + +_T = TypeVar("_T") +_S = TypeVar("_S") + +__license__: str +__title__: str + +@overload +def first(iterable: Iterable[_T]) -> _T | None: ... +@overload +def first(iterable: Iterable[_T], default: _S) -> _T | _S: ... +@overload +def first(iterable: Iterable[_T], default: _S, key: Callable[[_T], Any] | None) -> _T | _S: ... +@overload +def first(iterable: Iterable[_T], default: None, key: Callable[[_T], Any] | None) -> _T | None: ... +@overload +def first(iterable: Iterable[_T], *, key: Callable[[_T], Any] | None) -> _T | None: ... diff --git a/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt b/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ae255e50fb90 --- /dev/null +++ b/stubs/flake8-bugbear/@tests/stubtest_allowlist.txt @@ -0,0 +1,33 @@ +# Autogenerated methods using @attr.* decorators +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_props__ +bugbear.B040CaughtException.__match_args__ +bugbear.B041VariableKeyType.__match_args__ +bugbear.BugBearChecker.__ge__ +bugbear.BugBearChecker.__gt__ +bugbear.BugBearChecker.__le__ +bugbear.BugBearChecker.__lt__ +bugbear.BugBearChecker.__match_args__ +bugbear.BugBearVisitor.__ge__ +bugbear.BugBearVisitor.__gt__ +bugbear.BugBearVisitor.__le__ +bugbear.BugBearVisitor.__lt__ +bugbear.BugBearVisitor.__match_args__ +bugbear.NameFinder.__ge__ +bugbear.NameFinder.__gt__ +bugbear.NameFinder.__le__ +bugbear.NameFinder.__lt__ +bugbear.NameFinder.__match_args__ +bugbear.NamedExprFinder.__ge__ +bugbear.NamedExprFinder.__gt__ +bugbear.NamedExprFinder.__le__ +bugbear.NamedExprFinder.__lt__ +bugbear.NamedExprFinder.__match_args__ +# == Python 3.13 +bugbear.B040CaughtException.__replace__ +bugbear.B041VariableKeyType.__replace__ +bugbear.BugBearChecker.__replace__ +bugbear.BugBearVisitor.__replace__ +bugbear.NameFinder.__replace__ +bugbear.NamedExprFinder.__replace__ diff --git a/stubs/flake8-bugbear/METADATA.toml b/stubs/flake8-bugbear/METADATA.toml new file mode 100644 index 000000000000..f8d9fca3d6e9 --- /dev/null +++ b/stubs/flake8-bugbear/METADATA.toml @@ -0,0 +1,2 @@ +version = "25.11.29" +upstream-repository = "https://github.com/PyCQA/flake8-bugbear" diff --git a/stubs/flake8-bugbear/bugbear.pyi b/stubs/flake8-bugbear/bugbear.pyi new file mode 100644 index 000000000000..d3aa8e844186 --- /dev/null +++ b/stubs/flake8-bugbear/bugbear.pyi @@ -0,0 +1,270 @@ +import argparse +import ast +import sys +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Sequence +from functools import partial +from logging import Logger +from typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, overload + +__version__: Final[str] +LOG: Logger +CONTEXTFUL_NODES: Final[tuple[type[ast.AST], ...]] +FUNCTION_NODES: Final[tuple[type[ast.AST], ...]] +B908_pytest_functions: Final[set[str]] +B908_unittest_methods: Final[set[str]] +B902_default_decorators: Final[set[str]] + +class Context(NamedTuple): + node: ast.AST + stack: list[str] + +class BugBearChecker: + name: ClassVar[str] + version: ClassVar[str] + tree: ast.AST | None + filename: str + lines: Sequence[str] | None + max_line_length: int + visitor: ast.NodeVisitor + options: argparse.Namespace | None + def run(self) -> Iterable[tuple[int, int, str, type[BugBearChecker]]]: ... + def gen_line_based_checks(self) -> Generator[error]: ... + @classmethod + def adapt_error(cls, e: error) -> tuple[int, int, str, type[BugBearChecker]]: ... + def load_file(self) -> None: ... + @staticmethod + def add_options(optmanager: Any) -> None: ... + def __init__( + self, + tree: ast.AST | None = ..., + filename: str = ..., + lines: Sequence[str] | None = ..., + max_line_length: int = ..., + options: argparse.Namespace | None = ..., + ) -> None: ... + def should_warn(self, code: str) -> bool: ... + +def names_from_assignments(assign_target: ast.AST) -> Generator[str]: ... +def children_in_scope(node: ast.AST) -> Generator[ast.AST]: ... +def walk_list(nodes: Iterable[ast.AST]) -> Generator[ast.AST]: ... + +class ExceptBaseExceptionVisitor(ast.NodeVisitor): + root: ast.ExceptHandler + def __init__(self, except_node: ast.ExceptHandler) -> None: ... + def re_raised(self) -> bool: ... + def visit_Raise(self, node: ast.Raise) -> Incomplete | None: ... + def visit_ExceptHandler(self, node: ast.ExceptHandler) -> Incomplete | None: ... + +class B040CaughtException: + name: str + has_note: bool + def __init__(self, name: str, has_note: bool) -> None: ... + +class B041UnhandledKeyType: ... + +class B041VariableKeyType: + name: str + def __init__(self, name: str) -> None: ... + +class AstPositionNode(Protocol): + lineno: int + col_offset: int + +class BugBearVisitor(ast.NodeVisitor): + filename: str + lines: Sequence[str] | None + b008_b039_extend_immutable_calls: set[str] + b902_classmethod_decorators: set[str] + node_window: list[ast.AST] + errors: list[error] + contexts: list[Context] + b040_caught_exception: B040CaughtException | None + NODE_WINDOW_SIZE: ClassVar[int] = 4 + in_trystar: str + def __init__( + self, + filename: str, + lines: Sequence[str] | None, + b008_b039_extend_immutable_calls: set[str] = ..., + b902_classmethod_decorators: set[str] = ..., + node_window: list[ast.AST] = ..., + errors: list[error] = ..., + contexts: list[Context] = ..., + b040_caught_exception: B040CaughtException | None = None, + in_trystar: str = "", + ) -> None: ... + def add_error(self, code: str, node: AstPositionNode, *vars: object) -> None: ... + @property + def node_stack(self) -> list[Context]: ... + def in_class_init(self) -> bool: ... + def visit_Return(self, node: ast.Return) -> None: ... + def visit_Yield(self, node: ast.Yield) -> None: ... + def visit_YieldFrom(self, node: ast.YieldFrom) -> None: ... + def visit(self, node: ast.AST) -> None: ... + def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: ... + def visit_UAdd(self, node: ast.UAdd) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_Module(self, node: ast.Module) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_For(self, node: ast.For) -> None: ... + def visit_AsyncFor(self, node: ast.AsyncFor) -> None: ... + def visit_While(self, node: ast.While) -> None: ... + def visit_ListComp(self, node: ast.ListComp) -> None: ... + def visit_SetComp(self, node: ast.SetComp) -> None: ... + def visit_DictComp(self, node: ast.DictComp) -> None: ... + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: ... + def visit_Assert(self, node: ast.Assert) -> None: ... + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: ... + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + def visit_Try(self, node: ast.Try) -> None: ... + if sys.version_info >= (3, 11): + def visit_TryStar(self, node: ast.TryStar) -> None: ... + else: + def visit_TryStar(self, node: ast.Try) -> None: ... + + def visit_Compare(self, node: ast.Compare) -> None: ... + def visit_Raise(self, node: ast.Raise) -> None: ... + def visit_With(self, node: ast.With) -> None: ... + def visit_JoinedStr(self, node: ast.JoinedStr) -> None: ... + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: ... + def visit_Import(self, node: ast.Import) -> None: ... + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: ... + def visit_Set(self, node: ast.Set) -> None: ... + def visit_Dict(self, node: ast.Dict) -> None: ... + def check_for_b041(self, node: ast.Dict) -> None: ... + def check_for_b005(self, node: ast.Import | ast.ImportFrom | ast.Call) -> None: ... + def check_for_b006_and_b008(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b039(self, node: ast.Call) -> None: ... + def check_for_b007(self, node: ast.For | ast.AsyncFor) -> None: ... + def check_for_b011(self, node: ast.Assert) -> None: ... + if sys.version_info >= (3, 11): + def check_for_b012(self, node: ast.Try | ast.TryStar) -> None: ... + else: + def check_for_b012(self, node: ast.Try) -> None: ... + + def check_for_b013_b014_b029_b030(self, node: ast.ExceptHandler) -> list[str]: ... + def check_for_b015(self, node: ast.Compare) -> None: ... + def check_for_b016(self, node: ast.Raise) -> None: ... + def check_for_b017(self, node: ast.With | ast.AsyncWith) -> None: ... + def check_for_b019(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b020(self, node: ast.For | ast.AsyncFor | ast.comprehension) -> None: ... + def check_for_b023( + self, loop_node: ast.For | ast.AsyncFor | ast.While | ast.GeneratorExp | ast.SetComp | ast.ListComp | ast.DictComp + ) -> None: ... + def check_for_b024_and_b027(self, node: ast.ClassDef) -> None: ... + def check_for_b026(self, call: ast.Call) -> None: ... + def check_for_b031(self, loop_node: ast.For | ast.AsyncFor) -> None: ... + def check_for_b035(self, node: ast.DictComp) -> None: ... + def check_for_b040_add_note(self, node: ast.Attribute) -> bool: ... + def check_for_b040_usage(self, node: ast.expr | None) -> None: ... + def check_for_b904(self, node: ast.Raise) -> None: ... + def walk_function_body( + self, node: ast.FunctionDef | ast.AsyncFunctionDef + ) -> tuple[ast.FunctionDef | ast.AsyncFunctionDef, ast.stmt]: ... + def check_for_b901(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + + @overload + @classmethod + def find_decorator_name(cls, d: ast.Name | ast.Attribute | ast.Call) -> str: ... + @overload + @classmethod + def find_decorator_name(cls, d: ast.AST) -> str | None: ... + + def check_for_b902(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: ... + def check_for_b903(self, node: ast.ClassDef) -> None: ... + def check_for_b018(self, node: ast.Expr) -> None: ... + def check_for_b021(self, node: ast.AsyncFunctionDef | ast.FunctionDef | ast.ClassDef | ast.Module) -> None: ... + def check_for_b022(self, node: ast.With | ast.AsyncWith) -> None: ... + def check_for_b908(self, node: ast.With) -> None: ... + def check_for_b025(self, node: ast.Try) -> None: ... + def check_for_b905(self, node: ast.Call) -> None: ... + def check_for_b912(self, node: ast.Call) -> None: ... + def check_for_b906(self, node: ast.FunctionDef) -> None: ... + def check_for_b907(self, node: ast.JoinedStr) -> None: ... + def check_for_b028(self, node: ast.Call) -> None: ... + def check_for_b032(self, node: ast.AnnAssign) -> None: ... + def check_for_b033(self, node: ast.Set | ast.List | ast.Tuple) -> None: ... + def check_for_b034(self, node: ast.Call) -> None: ... + def check_for_b042(self, node: ast.ClassDef) -> None: ... + def check_for_b909(self, node: ast.For) -> None: ... + def check_for_b910(self, node: ast.Call) -> None: ... + def check_for_b911(self, node: ast.Call) -> None: ... + +def compose_call_path(node: ast.expr) -> Generator[str]: ... +def is_name(node: ast.expr, name: str) -> bool: ... + +class B909Checker(ast.NodeVisitor): + MUTATING_FUNCTIONS: ClassVar[tuple[str, ...]] + name: str + key: str + mutations: dict[int, list[ast.Assign | ast.AugAssign | ast.Delete | ast.Call]] + def __init__(self, name: str, key: str) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_AugAssign(self, node: ast.AugAssign) -> None: ... + def visit_Delete(self, node: ast.Delete) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_If(self, node: ast.If) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> Any: ... + +class NameFinder(ast.NodeVisitor): + names: dict[str, list[ast.Name]] + def __init__(self, names: dict[str, list[ast.Name]] = ...) -> None: ... + def visit_Name(self, node: ast.Name) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> Any: ... + +class NamedExprFinder(ast.NodeVisitor): + names: dict[str, list[ast.Name]] + def __init__(self, names: dict[str, list[ast.Name]] = ...) -> None: ... + def visit_NamedExpr(self, node: ast.NamedExpr) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> Any: ... + +class FunctionDefDefaultsVisitor(ast.NodeVisitor): + def __init__( + self, + error_code_calls: partial[error], + error_code_literals: partial[error], + b008_b039_extend_immutable_calls: set[str] | None = None, + ) -> None: ... + def visit_mutable_literal_or_comprehension( + self, node: ast.List | ast.Dict | ast.Set | ast.ListComp | ast.DictComp | ast.SetComp + ) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_Lambda(self, node: ast.Lambda) -> None: ... + def visit(self, node: ast.AST | list[ast.AST]) -> None: ... + +class B020NameFinder(NameFinder): + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: ... + def visit_ListComp(self, node: ast.ListComp) -> None: ... + def visit_DictComp(self, node: ast.DictComp) -> None: ... + def visit_comprehension(self, node: ast.comprehension) -> None: ... + def visit_Lambda(self, node: ast.Lambda) -> None: ... + +B005_METHODS: Final[set[str]] +B006_MUTABLE_LITERALS: Final[tuple[Literal["Dict"], Literal["List"], Literal["Set"]]] +B006_MUTABLE_COMPREHENSIONS: Final[tuple[Literal["ListComp"], Literal["DictComp"], Literal["SetComp"]]] +B006_MUTABLE_CALLS: Final[set[str]] +B008_IMMUTABLE_CALLS: Final[set[str]] +B014_REDUNDANT_EXCEPTIONS: Final[dict[Literal["OSError", "ValueError"], set[str]]] +B019_CACHES: Final[set[str]] +B902_IMPLICIT_CLASSMETHODS: Final[set[str]] +B902_SELF: Final[list[str]] +B902_CLS: Final[list[str]] +B902_METACLS: Final[list[str]] + +class error(NamedTuple): + lineno: int + col: int + message: str + type: type[BugBearChecker] + # Arguments for formatting the message, i.e. message.format(*vars). + vars: tuple[object, ...] + +class Error: + message: str + def __init__(self, message: str) -> None: ... + def __call__(self, lineno: int, col: int, vars: tuple[object, ...] = ()) -> error: ... + +error_codes: Final[dict[str, Error]] +disabled_by_default: Final[list[str]] diff --git a/stubs/flake8-builtins/METADATA.toml b/stubs/flake8-builtins/METADATA.toml new file mode 100644 index 000000000000..5f4f23a38df6 --- /dev/null +++ b/stubs/flake8-builtins/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.1.*" +upstream-repository = "https://github.com/gforcada/flake8-builtins" +dependencies = ["types-flake8"] diff --git a/stubs/flake8-builtins/flake8_builtins.pyi b/stubs/flake8-builtins/flake8_builtins.pyi new file mode 100644 index 000000000000..9e80c36dc14a --- /dev/null +++ b/stubs/flake8-builtins/flake8_builtins.pyi @@ -0,0 +1,45 @@ +import ast +from argparse import Namespace +from collections.abc import Iterator +from typing import ClassVar, TypeAlias + +from flake8.options.manager import OptionManager + +_Error: TypeAlias = tuple[int, int, str, type[BuiltinsChecker]] + +class BuiltinsChecker: + name: ClassVar[str] + version: ClassVar[str] + assign_msg: ClassVar[str] + argument_msg: ClassVar[str] + class_attribute_msg: ClassVar[str] + import_msg: ClassVar[str] + module_name_msg: ClassVar[str] + lambda_argument_msg: ClassVar[str] + + default_line_number: ClassVar[int] + default_column_offset: ClassVar[int] + + names: ClassVar[list[str]] + ignore_list: ClassVar[set[str]] + ignored_module_names: ClassVar[set[str]] + + def __init__(self, tree: ast.AST, filename: str) -> None: ... + @classmethod + def add_options(cls, option_manager: OptionManager) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Iterator[_Error]: ... + def check_assignment(self, statement: ast.Assign | ast.AnnAssign | ast.NamedExpr) -> Iterator[_Error]: ... + def check_function_definition(self, statement: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[_Error]: ... + def check_lambda_definition(self, statement: ast.Lambda) -> Iterator[_Error]: ... + def check_for_loop(self, statement: ast.For | ast.AsyncFor) -> Iterator[_Error]: ... + def check_with(self, statement: ast.With | ast.AsyncWith) -> Iterator[_Error]: ... + def check_exception(self, statement: ast.excepthandler) -> Iterator[_Error]: ... + def check_comprehension( + self, statement: ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp + ) -> Iterator[_Error]: ... + def check_import(self, statement: ast.Import | ast.ImportFrom) -> Iterator[_Error]: ... + def check_class(self, statement: ast.ClassDef) -> Iterator[_Error]: ... + def error(self, statement: ast.AST | None = None, variable: str | None = None, message: str | None = None) -> _Error: ... + def check_module_name(self, filename: str) -> Iterator[_Error]: ... diff --git a/stubs/flake8-docstrings/METADATA.toml b/stubs/flake8-docstrings/METADATA.toml new file mode 100644 index 000000000000..201a2cb77311 --- /dev/null +++ b/stubs/flake8-docstrings/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.7.*" +upstream-repository = "https://github.com/pycqa/flake8-docstrings" +dependencies = ["types-flake8"] diff --git a/stubs/flake8-docstrings/flake8_docstrings.pyi b/stubs/flake8-docstrings/flake8_docstrings.pyi new file mode 100644 index 000000000000..0c9f9344a561 --- /dev/null +++ b/stubs/flake8-docstrings/flake8_docstrings.pyi @@ -0,0 +1,24 @@ +import argparse +import ast +from collections.abc import Generator, Iterable +from typing import Any, ClassVar, Final, Literal +from typing_extensions import Self + +from flake8.options.manager import OptionManager + +__version__: Final[str] +__all__ = ("pep257Checker",) + +class pep257Checker: + name: ClassVar[str] + version: ClassVar[str] + tree: ast.AST + filename: str + checker: Any # actual type: pep257.ConventionChecker + source: str + def __init__(self, tree: ast.AST, filename: str, lines: Iterable[str]) -> None: ... + @classmethod + def add_options(cls, parser: OptionManager) -> None: ... + @classmethod + def parse_options(cls, options: argparse.Namespace) -> None: ... + def run(self) -> Generator[tuple[int, Literal[0], str, type[Self]]]: ... diff --git a/stubs/flake8-rst-docstrings/METADATA.toml b/stubs/flake8-rst-docstrings/METADATA.toml new file mode 100644 index 000000000000..f8912d7c9e35 --- /dev/null +++ b/stubs/flake8-rst-docstrings/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/peterjc/flake8-rst-docstrings" diff --git a/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi b/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi new file mode 100644 index 000000000000..b04ae53ef63b --- /dev/null +++ b/stubs/flake8-rst-docstrings/flake8_rst_docstrings.pyi @@ -0,0 +1,34 @@ +import ast +from argparse import Namespace +from collections.abc import Container, Generator +from typing import Any + +rst_prefix: str +rst_fail_load: int +rst_fail_lint: int +code_mapping_info: dict[str, int] +code_mapping_warning: dict[str, int] +code_mapping_error: dict[str, int] +code_mapping_severe: dict[str, int] +code_mappings_by_level: dict[int, dict[str, int]] + +def code_mapping( + level: int, + msg: str, + extra_directives: Container[str], + extra_roles: Container[str], + extra_substitutions: Container[str], + default: int = ..., +) -> int: ... + +class reStructuredTextChecker: + name: str + version: str + tree: ast.AST + filename: str + def __init__(self, tree: ast.AST, filename: str = ...) -> None: ... + @classmethod + def add_options(cls, parser: Any) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[reStructuredTextChecker]]]: ... diff --git a/stubs/flake8-simplify/METADATA.toml b/stubs/flake8-simplify/METADATA.toml new file mode 100644 index 000000000000..5ef28e476ab3 --- /dev/null +++ b/stubs/flake8-simplify/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.30.*" +upstream-repository = "https://github.com/MartinThoma/flake8-simplify" diff --git a/stubs/flake8-simplify/flake8_simplify/__init__.pyi b/stubs/flake8-simplify/flake8_simplify/__init__.pyi new file mode 100644 index 000000000000..161c2bf90499 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/__init__.pyi @@ -0,0 +1,31 @@ +import ast +import logging +from collections.abc import Generator +from typing import Any, ClassVar + +logger: logging.Logger + +class Visitor(ast.NodeVisitor): + errors: list[tuple[int, int, str]] + def __init__(self) -> None: ... + def visit_Assign(self, node: ast.Assign) -> None: ... + def visit_Call(self, node: ast.Call) -> None: ... + def visit_With(self, node: ast.With) -> None: ... + def visit_Expr(self, node: ast.Expr) -> None: ... + def visit_BoolOp(self, node: ast.BoolOp) -> None: ... + def visit_If(self, node: ast.If) -> None: ... + def visit_For(self, node: ast.For) -> None: ... + def visit_Subscript(self, node: ast.Subscript) -> None: ... + def visit_Try(self, node: ast.Try) -> None: ... + def visit_UnaryOp(self, node_v: ast.UnaryOp) -> None: ... + def visit_IfExp(self, node: ast.IfExp) -> None: ... + def visit_Compare(self, node: ast.Compare) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + +class Plugin: + name: ClassVar[str] + version: ClassVar[str] + def __init__(self, tree: ast.AST) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... + +def add_meta(root: ast.AST, level: int = 0) -> None: ... diff --git a/stubs/flake8-simplify/flake8_simplify/constants.pyi b/stubs/flake8-simplify/flake8_simplify/constants.pyi new file mode 100644 index 000000000000..58254db7068f --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/constants.pyi @@ -0,0 +1,6 @@ +import ast +from typing import Final + +BOOL_CONST_TYPES: Final[tuple[type[ast.Constant]]] +AST_CONST_TYPES: Final[tuple[type[ast.Constant]]] +STR_TYPES: Final[tuple[type[ast.Constant]]] diff --git a/stubs/flake8-simplify/flake8_simplify/rules/__init__.pyi b/stubs/flake8-simplify/flake8_simplify/rules/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi new file mode 100644 index 000000000000..019ac9f499a7 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_assign.pyi @@ -0,0 +1,6 @@ +import ast + +from flake8_simplify.utils import Assign + +def get_sim904(node: ast.Assign) -> list[tuple[int, int, str]]: ... +def get_sim909(node: Assign) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi new file mode 100644 index 000000000000..d130dceae322 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_bool_op.pyi @@ -0,0 +1,8 @@ +import ast + +def get_sim101(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim109(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim220(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim221(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim222(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... +def get_sim223(node: ast.BoolOp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi new file mode 100644 index 000000000000..d8b62cfa427d --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_call.pyi @@ -0,0 +1,13 @@ +import ast +import logging + +from flake8_simplify.utils import Call + +logger: logging.Logger + +def get_sim115(node: Call) -> list[tuple[int, int, str]]: ... +def get_sim901(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim905(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim906(node: ast.Call) -> list[tuple[int, int, str]]: ... +def get_sim910(node: Call) -> list[tuple[int, int, str]]: ... +def get_sim911(node: ast.AST) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi new file mode 100644 index 000000000000..09dc22b3595f --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_classdef.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim120(node: ast.ClassDef) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi new file mode 100644 index 000000000000..0a7b816a5e3c --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_compare.pyi @@ -0,0 +1,4 @@ +import ast + +def get_sim118(node: ast.Compare) -> list[tuple[int, int, str]]: ... +def get_sim300(node: ast.Compare) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi new file mode 100644 index 000000000000..af53ac0309d8 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_expr.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim112(node: ast.Expr) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi new file mode 100644 index 000000000000..235c7fd2b287 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_for.pyi @@ -0,0 +1,7 @@ +import ast + +from flake8_simplify.utils import For + +def get_sim104(node: ast.For) -> list[tuple[int, int, str]]: ... +def get_sim110_sim111(node: ast.For) -> list[tuple[int, int, str]]: ... +def get_sim113(node: For) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi new file mode 100644 index 000000000000..65121cfcef51 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_if.pyi @@ -0,0 +1,11 @@ +import ast + +from flake8_simplify.utils import If + +def get_sim102(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim103(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim108(node: If) -> list[tuple[int, int, str]]: ... +def get_sim114(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim116(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim908(node: ast.If) -> list[tuple[int, int, str]]: ... +def get_sim401(node: ast.If) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi new file mode 100644 index 000000000000..8a37a0c6a5ab --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_ifexp.pyi @@ -0,0 +1,5 @@ +import ast + +def get_sim210(node: ast.IfExp) -> list[tuple[int, int, str]]: ... +def get_sim211(node: ast.IfExp) -> list[tuple[int, int, str]]: ... +def get_sim212(node: ast.IfExp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi new file mode 100644 index 000000000000..eb2fa207b32b --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_subscript.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim907(node: ast.Subscript) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi new file mode 100644 index 000000000000..9156100ebbe1 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_try.pyi @@ -0,0 +1,4 @@ +import ast + +def get_sim105(node: ast.Try) -> list[tuple[int, int, str]]: ... +def get_sim107(node: ast.Try) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi new file mode 100644 index 000000000000..93603e0576f1 --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_unary_op.pyi @@ -0,0 +1,8 @@ +import ast + +from flake8_simplify.utils import UnaryOp + +def get_sim201(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim202(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim203(node: UnaryOp) -> list[tuple[int, int, str]]: ... +def get_sim208(node: ast.UnaryOp) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi b/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi new file mode 100644 index 000000000000..310080e7ec0d --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/rules/ast_with.pyi @@ -0,0 +1,3 @@ +import ast + +def get_sim117(node: ast.With) -> list[tuple[int, int, str]]: ... diff --git a/stubs/flake8-simplify/flake8_simplify/utils.pyi b/stubs/flake8-simplify/flake8_simplify/utils.pyi new file mode 100644 index 000000000000..06104640204a --- /dev/null +++ b/stubs/flake8-simplify/flake8_simplify/utils.pyi @@ -0,0 +1,36 @@ +import ast +from _typeshed import Incomplete + +class UnaryOp(ast.UnaryOp): + parent: ast.Expr + def __init__(self, orig: ast.UnaryOp) -> None: ... + +class Call(ast.Call): + parent: ast.Expr + def __init__(self, orig: ast.Call) -> None: ... + +class If(ast.If): + parent: ast.Expr + def __init__(self, orig: ast.If) -> None: ... + +class For(ast.For): + parent: ast.AST + previous_sibling: Incomplete + def __init__(self, orig: ast.For) -> None: ... + +class Assign(ast.Assign): + parent: ast.AST + previous_sibling: Incomplete + def __init__(self, orig: ast.Assign) -> None: ... + +def to_source(node: ast.expr | ast.Expr | ast.withitem | ast.slice | ast.Assign | None) -> str: ... +def strip_triple_quotes(string: str) -> str: ... +def use_double_quotes(string: str) -> str: ... +def is_body_same(body1: list[ast.stmt], body2: list[ast.stmt]) -> bool: ... +def is_stmt_equal(a: ast.stmt, b: ast.stmt) -> bool: ... +def get_if_body_pairs(node: ast.If) -> list[tuple[ast.expr, list[ast.stmt]]]: ... +def is_constant_increase(expr: ast.AugAssign) -> bool: ... +def is_exception_check(node: ast.If) -> bool: ... +def is_same_expression(a: ast.expr, b: ast.expr) -> bool: ... +def expression_uses_variable(expr: ast.expr, var: str) -> bool: ... +def body_contains_continue(stmts: list[ast.stmt]) -> bool: ... diff --git a/stubs/flake8-typing-imports/METADATA.toml b/stubs/flake8-typing-imports/METADATA.toml new file mode 100644 index 000000000000..77ede4ca1037 --- /dev/null +++ b/stubs/flake8-typing-imports/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.17.*" +upstream-repository = "https://github.com/asottile/flake8-typing-imports" diff --git a/stubs/flake8-typing-imports/flake8_typing_imports.pyi b/stubs/flake8-typing-imports/flake8_typing_imports.pyi new file mode 100644 index 000000000000..f2dd55ee9f12 --- /dev/null +++ b/stubs/flake8-typing-imports/flake8_typing_imports.pyi @@ -0,0 +1,40 @@ +import argparse +import ast +from collections.abc import Generator +from typing import Any, Final, NamedTuple +from typing_extensions import Self + +class Version(NamedTuple): + major: int = 0 + minor: int = 0 + patch: int = 0 + @classmethod + def parse(cls, s: str) -> Self: ... + +SYMBOLS: Final[list[tuple[Version, frozenset[str]]]] +VERSIONS: Final[frozenset[Version]] + +class Visitor(ast.NodeVisitor): + imports: dict[str, list[tuple[int, int]]] + attributes: dict[str, list[tuple[int, int]]] + defined_overload: bool + unions_pattern_or_match: list[tuple[int, int]] + from_imported_names: set[str] + namedtuple_methods: list[tuple[int, int]] + namedtuple_defaults: list[tuple[int, int]] + def __init__(self) -> None: ... + def visit_ImportFrom(self, node: ast.ImportFrom) -> None: ... + def visit_Attribute(self, node: ast.Attribute) -> None: ... + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: ... + def visit_Subscript(self, node: ast.Subscript) -> None: ... + def visit_ClassDef(self, node: ast.ClassDef) -> None: ... + def visit_AnnAssign(self, node: ast.AnnAssign) -> None: ... + def generic_visit(self, node: ast.AST) -> None: ... + +class Plugin: + @staticmethod + def add_options(option_manager: Any) -> None: ... + @classmethod + def parse_options(cls, options: argparse.Namespace) -> None: ... + def __init__(self, tree: ast.AST) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... diff --git a/stubs/flake8/@tests/stubtest_allowlist.txt b/stubs/flake8/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e33caad65504 --- /dev/null +++ b/stubs/flake8/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +flake8.__main__ diff --git a/stubs/flake8/METADATA.toml b/stubs/flake8/METADATA.toml new file mode 100644 index 000000000000..7a39dcb38917 --- /dev/null +++ b/stubs/flake8/METADATA.toml @@ -0,0 +1,3 @@ +version = "7.3.*" +upstream-repository = "https://github.com/pycqa/flake8" +dependencies = ["types-pyflakes"] diff --git a/stubs/flake8/flake8/__init__.pyi b/stubs/flake8/flake8/__init__.pyi new file mode 100644 index 000000000000..56cd4da6b6cd --- /dev/null +++ b/stubs/flake8/flake8/__init__.pyi @@ -0,0 +1,8 @@ +from logging import Logger + +LOG: Logger +__version__: str +__version_info__: tuple[int, int, int] +LOG_FORMAT: str + +def configure_logging(verbosity: int, filename: str | None = None, logformat: str = ...) -> None: ... diff --git a/stubs/flake8/flake8/_compat.pyi b/stubs/flake8/flake8/_compat.pyi new file mode 100644 index 000000000000..7fbc26e88fc1 --- /dev/null +++ b/stubs/flake8/flake8/_compat.pyi @@ -0,0 +1,9 @@ +from typing import Final + +FSTRING_START: Final[int] +FSTRING_MIDDLE: Final[int] +FSTRING_END: Final[int] + +TSTRING_START: Final[int] +TSTRING_MIDDLE: Final[int] +TSTRING_END: Final[int] diff --git a/stubs/flake8/flake8/api/__init__.pyi b/stubs/flake8/flake8/api/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8/flake8/api/legacy.pyi b/stubs/flake8/flake8/api/legacy.pyi new file mode 100644 index 000000000000..7f8ad95d25cc --- /dev/null +++ b/stubs/flake8/flake8/api/legacy.pyi @@ -0,0 +1,27 @@ +import argparse +from _typeshed import Unused +from typing import Any + +from ..formatting import base as formatter +from ..main import application as app + +__all__ = ("get_style_guide",) + +class Report: + def __init__(self, application: app.Application) -> None: ... + @property + def total_errors(self) -> int: ... + def get_statistics(self, violation: str) -> list[str]: ... + +class StyleGuide: + def __init__(self, application: app.Application) -> None: ... + @property + def options(self) -> argparse.Namespace: ... + @property + def paths(self) -> list[str]: ... + def check_files(self, paths: list[str] | None = None) -> Report: ... + def excluded(self, filename: str, parent: str | None = None) -> bool: ... + def init_report(self, reporter: type[formatter.BaseFormatter] | None = None) -> None: ... + def input_file(self, filename: str, lines: Unused = None, expected: Unused = None, line_offset: Unused = 0) -> Report: ... + +def get_style_guide(**kwargs: Any) -> StyleGuide: ... diff --git a/stubs/flake8/flake8/checker.pyi b/stubs/flake8/flake8/checker.pyi new file mode 100644 index 000000000000..d370840cc1b7 --- /dev/null +++ b/stubs/flake8/flake8/checker.pyi @@ -0,0 +1,55 @@ +import argparse +import tokenize +from _typeshed import Incomplete +from collections.abc import Sequence +from logging import Logger +from typing import Any, TypeAlias + +from .plugins.finder import Checkers, LoadedPlugin +from .processor import _LogicalMapping +from .style_guide import StyleGuideManager + +Results: TypeAlias = list[tuple[str, int, int, str, str | None]] + +LOG: Logger +SERIAL_RETRY_ERRNOS: Incomplete + +class Manager: + style_guide: Incomplete + options: Incomplete + plugins: Incomplete + jobs: Incomplete + statistics: Incomplete + exclude: Incomplete + argv: Incomplete + results: Incomplete + def __init__(self, style_guide: StyleGuideManager, plugins: Checkers, argv: Sequence[str]) -> None: ... + def report(self) -> tuple[int, int]: ... + def run_parallel(self) -> None: ... + def run_serial(self) -> None: ... + def run(self) -> None: ... + filenames: Incomplete + def start(self) -> None: ... + def stop(self) -> None: ... + +class FileChecker: + options: Incomplete + filename: Incomplete + plugins: Incomplete + results: Incomplete + statistics: Incomplete + processor: Incomplete + display_name: Incomplete + should_process: bool + def __init__(self, *, filename: str, plugins: Checkers, options: argparse.Namespace) -> None: ... + def report(self, error_code: str | None, line_number: int, column: int, text: str) -> str: ... + def run_check(self, plugin: LoadedPlugin, **arguments: Any) -> Any: ... + def run_ast_checks(self) -> None: ... + def run_logical_checks(self) -> None: ... + def run_physical_checks(self, physical_line: str) -> None: ... + def process_tokens(self) -> None: ... + def run_checks(self) -> tuple[str, Results, dict[str, int]]: ... + def handle_newline(self, token_type: int) -> None: ... + def check_physical_eol(self, token: tokenize.TokenInfo, prev_physical: str) -> None: ... + +def find_offset(offset: int, mapping: _LogicalMapping) -> tuple[int, int]: ... diff --git a/stubs/flake8/flake8/defaults.pyi b/stubs/flake8/flake8/defaults.pyi new file mode 100644 index 000000000000..1a9459d17410 --- /dev/null +++ b/stubs/flake8/flake8/defaults.pyi @@ -0,0 +1,12 @@ +from re import Pattern +from typing import Final + +EXCLUDE: Final[tuple[str, ...]] +IGNORE: Final[tuple[str, ...]] +MAX_LINE_LENGTH: Final = 79 +INDENT_SIZE: Final = 4 +WHITESPACE: Final[frozenset[str]] +STATISTIC_NAMES: Final[tuple[str, ...]] +NOQA_INLINE_REGEXP: Final[Pattern[str]] +NOQA_FILE: Final[Pattern[str]] +VALID_CODE_PREFIX: Final[Pattern[str]] diff --git a/stubs/flake8/flake8/discover_files.pyi b/stubs/flake8/flake8/discover_files.pyi new file mode 100644 index 000000000000..aca433fa617c --- /dev/null +++ b/stubs/flake8/flake8/discover_files.pyi @@ -0,0 +1,8 @@ +from collections.abc import Generator, Sequence +from logging import Logger + +LOG: Logger + +def expand_paths( + *, paths: Sequence[str], stdin_display_name: str, filename_patterns: Sequence[str], exclude: Sequence[str] +) -> Generator[str]: ... diff --git a/stubs/flake8/flake8/exceptions.pyi b/stubs/flake8/flake8/exceptions.pyi new file mode 100644 index 000000000000..7c6e3fc70629 --- /dev/null +++ b/stubs/flake8/flake8/exceptions.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +class Flake8Exception(Exception): ... +class EarlyQuit(Flake8Exception): ... +class ExecutionError(Flake8Exception): ... + +class FailedToLoadPlugin(Flake8Exception): + FORMAT: str + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, plugin_name: str, exception: Exception) -> None: ... + +class PluginRequestedUnknownParameters(Flake8Exception): + FORMAT: str + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, plugin_name: str, exception: Exception) -> None: ... + +class PluginExecutionFailed(Flake8Exception): + FORMAT: str + filename: Incomplete + plugin_name: Incomplete + original_exception: Incomplete + def __init__(self, filename: str, plugin_name: str, exception: Exception) -> None: ... diff --git a/stubs/flake8/flake8/formatting/__init__.pyi b/stubs/flake8/flake8/formatting/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8/flake8/formatting/_windows_color.pyi b/stubs/flake8/flake8/formatting/_windows_color.pyi new file mode 100644 index 000000000000..f8af8baa7fce --- /dev/null +++ b/stubs/flake8/flake8/formatting/_windows_color.pyi @@ -0,0 +1 @@ +terminal_supports_color: bool diff --git a/stubs/flake8/flake8/formatting/base.pyi b/stubs/flake8/flake8/formatting/base.pyi new file mode 100644 index 000000000000..8401cdf00ce1 --- /dev/null +++ b/stubs/flake8/flake8/formatting/base.pyi @@ -0,0 +1,25 @@ +import argparse +from _typeshed import Incomplete + +from ..statistics import Statistics +from ..violation import Violation as Violation + +class BaseFormatter: + options: Incomplete + filename: Incomplete + output_fd: Incomplete + newline: str + color: Incomplete + def __init__(self, options: argparse.Namespace) -> None: ... + def after_init(self) -> None: ... + def beginning(self, filename: str) -> None: ... + def finished(self, filename: str) -> None: ... + def start(self) -> None: ... + def handle(self, error: Violation) -> None: ... + def format(self, error: Violation) -> str | None: ... + def show_statistics(self, statistics: Statistics) -> None: ... + def show_benchmarks(self, benchmarks: list[tuple[str, float]]) -> None: ... + def show_source(self, error: Violation) -> str | None: ... + def write(self, line: str | None, source: str | None) -> None: ... + def _write(self, output: str) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/flake8/flake8/formatting/default.pyi b/stubs/flake8/flake8/formatting/default.pyi new file mode 100644 index 000000000000..a2cdebdd3456 --- /dev/null +++ b/stubs/flake8/flake8/formatting/default.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete + +from ..violation import Violation +from .base import BaseFormatter + +COLORS: dict[str, str] +COLORS_OFF: dict[str, str] + +class SimpleFormatter(BaseFormatter): + error_format: str + def format(self, error: Violation) -> str | None: ... + +class Default(SimpleFormatter): + error_format: str + def after_init(self) -> None: ... + +class Pylint(SimpleFormatter): + error_format: str + +class FilenameOnly(SimpleFormatter): + error_format: str + filenames_already_printed: Incomplete + def after_init(self) -> None: ... + def show_source(self, error: Violation) -> str | None: ... + def format(self, error: Violation) -> str | None: ... + +class Nothing(BaseFormatter): + def format(self, error: Violation) -> str | None: ... + def show_source(self, error: Violation) -> str | None: ... diff --git a/stubs/flake8/flake8/main/__init__.pyi b/stubs/flake8/flake8/main/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8/flake8/main/application.pyi b/stubs/flake8/flake8/main/application.pyi new file mode 100644 index 000000000000..b41ba83c8b06 --- /dev/null +++ b/stubs/flake8/flake8/main/application.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from logging import Logger + +LOG: Logger + +class Application: + start_time: Incomplete + end_time: Incomplete + plugins: Incomplete + formatter: Incomplete + guide: Incomplete + file_checker_manager: Incomplete + options: Incomplete + result_count: int + total_result_count: int + catastrophic_failure: bool + def __init__(self) -> None: ... + def exit_code(self) -> int: ... + def make_formatter(self) -> None: ... + def make_guide(self) -> None: ... + def make_file_checker_manager(self, argv: Sequence[str]) -> None: ... + def run_checks(self) -> None: ... + def report_benchmarks(self) -> None: ... + def report_errors(self) -> None: ... + def report_statistics(self) -> None: ... + def initialize(self, argv: Sequence[str]) -> None: ... + def report(self) -> None: ... + def run(self, argv: Sequence[str]) -> None: ... diff --git a/stubs/flake8/flake8/main/cli.pyi b/stubs/flake8/flake8/main/cli.pyi new file mode 100644 index 000000000000..2d91d1aa373c --- /dev/null +++ b/stubs/flake8/flake8/main/cli.pyi @@ -0,0 +1,3 @@ +from collections.abc import Sequence + +def main(argv: Sequence[str] | None = None) -> int: ... diff --git a/stubs/flake8/flake8/main/debug.pyi b/stubs/flake8/flake8/main/debug.pyi new file mode 100644 index 000000000000..2f1ef97cfeb0 --- /dev/null +++ b/stubs/flake8/flake8/main/debug.pyi @@ -0,0 +1,5 @@ +from typing import Any + +from ..plugins.finder import Plugins + +def information(version: str, plugins: Plugins) -> dict[str, Any]: ... diff --git a/stubs/flake8/flake8/main/options.pyi b/stubs/flake8/flake8/main/options.pyi new file mode 100644 index 000000000000..1f9bf70a5d7f --- /dev/null +++ b/stubs/flake8/flake8/main/options.pyi @@ -0,0 +1,12 @@ +from argparse import ArgumentParser + +from ..options.manager import OptionManager + +def stage1_arg_parser() -> ArgumentParser: ... + +class JobsArgument: + is_auto: bool + n_jobs: int + def __init__(self, arg: str) -> None: ... + +def register_default_options(option_manager: OptionManager) -> None: ... diff --git a/stubs/flake8/flake8/options/__init__.pyi b/stubs/flake8/flake8/options/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8/flake8/options/aggregator.pyi b/stubs/flake8/flake8/options/aggregator.pyi new file mode 100644 index 000000000000..a6bb859a8c3b --- /dev/null +++ b/stubs/flake8/flake8/options/aggregator.pyi @@ -0,0 +1,12 @@ +import argparse +import configparser +from collections.abc import Sequence +from logging import Logger + +from .manager import OptionManager + +LOG: Logger + +def aggregate_options( + manager: OptionManager, cfg: configparser.RawConfigParser, cfg_dir: str, argv: Sequence[str] | None +) -> argparse.Namespace: ... diff --git a/stubs/flake8/flake8/options/config.pyi b/stubs/flake8/flake8/options/config.pyi new file mode 100644 index 000000000000..a443261b15a2 --- /dev/null +++ b/stubs/flake8/flake8/options/config.pyi @@ -0,0 +1,10 @@ +import configparser +from logging import Logger +from typing import Any + +from .manager import OptionManager + +LOG: Logger + +def load_config(config: str | None, extra: list[str], *, isolated: bool = False) -> tuple[configparser.RawConfigParser, str]: ... +def parse_config(option_manager: OptionManager, cfg: configparser.RawConfigParser, cfg_dir: str) -> dict[str, Any]: ... diff --git a/stubs/flake8/flake8/options/manager.pyi b/stubs/flake8/flake8/options/manager.pyi new file mode 100644 index 000000000000..5bb2519d8e34 --- /dev/null +++ b/stubs/flake8/flake8/options/manager.pyi @@ -0,0 +1,71 @@ +import argparse +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from enum import Enum +from logging import Logger +from typing import Any + +from ..plugins.finder import Plugins + +LOG: Logger + +class _ARG(Enum): + NO = 1 + +class Option: + short_option_name: Incomplete + long_option_name: Incomplete + option_args: Incomplete + action: Incomplete + default: Incomplete + type: Incomplete + dest: Incomplete + nargs: Incomplete + const: Incomplete + choices: Incomplete + help: Incomplete + metavar: Incomplete + required: Incomplete + option_kwargs: Incomplete + parse_from_config: Incomplete + comma_separated_list: Incomplete + normalize_paths: Incomplete + config_name: Incomplete + def __init__( + self, + short_option_name: str | _ARG = ..., + long_option_name: str | _ARG = ..., + action: str | type[argparse.Action] | _ARG = ..., + default: Any | _ARG = ..., + type: Callable[..., Any] | _ARG = ..., + dest: str | _ARG = ..., + nargs: int | str | _ARG = ..., + const: Any | _ARG = ..., + choices: Sequence[Any] | _ARG = ..., + help: str | _ARG = ..., + metavar: str | _ARG = ..., + required: bool | _ARG = ..., + parse_from_config: bool = False, + comma_separated_list: bool = False, + normalize_paths: bool = False, + ) -> None: ... + @property + def filtered_option_kwargs(self) -> dict[str, Any]: ... + def normalize(self, value: Any, *normalize_args: str) -> Any: ... + def to_argparse(self) -> tuple[list[str], dict[str, Any]]: ... + +class OptionManager: + formatter_names: Incomplete + parser: Incomplete + config_options_dict: Incomplete + options: Incomplete + extended_default_ignore: Incomplete + extended_default_select: Incomplete + def __init__( + self, *, version: str, plugin_versions: str, parents: list[argparse.ArgumentParser], formatter_names: list[str] + ) -> None: ... + def register_plugins(self, plugins: Plugins) -> None: ... + def add_option(self, *args: Any, **kwargs: Any) -> None: ... + def extend_default_ignore(self, error_codes: Sequence[str]) -> None: ... + def extend_default_select(self, error_codes: Sequence[str]) -> None: ... + def parse_args(self, args: Sequence[str] | None = None, values: argparse.Namespace | None = None) -> argparse.Namespace: ... diff --git a/stubs/flake8/flake8/options/parse_args.pyi b/stubs/flake8/flake8/options/parse_args.pyi new file mode 100644 index 000000000000..2818b87ce814 --- /dev/null +++ b/stubs/flake8/flake8/options/parse_args.pyi @@ -0,0 +1,6 @@ +import argparse +from collections.abc import Sequence + +from ..plugins import finder + +def parse_args(argv: Sequence[str]) -> tuple[finder.Plugins, argparse.Namespace]: ... diff --git a/stubs/flake8/flake8/plugins/__init__.pyi b/stubs/flake8/flake8/plugins/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/flake8/flake8/plugins/finder.pyi b/stubs/flake8/flake8/plugins/finder.pyi new file mode 100644 index 000000000000..8a8a7d49a099 --- /dev/null +++ b/stubs/flake8/flake8/plugins/finder.pyi @@ -0,0 +1,48 @@ +import configparser +import importlib.metadata +from collections.abc import Generator +from logging import Logger +from typing import Any, Final, NamedTuple + +LOG: Logger +FLAKE8_GROUPS: Final[frozenset[str]] +BANNED_PLUGINS: dict[str, str] + +class Plugin(NamedTuple): + package: str + version: str + entry_point: importlib.metadata.EntryPoint + +class LoadedPlugin(NamedTuple): + plugin: Plugin + obj: Any + parameters: dict[str, bool] + @property + def entry_name(self) -> str: ... + @property + def display_name(self) -> str: ... + +class Checkers(NamedTuple): + tree: list[LoadedPlugin] + logical_line: list[LoadedPlugin] + physical_line: list[LoadedPlugin] + +class Plugins(NamedTuple): + checkers: Checkers + reporters: dict[str, LoadedPlugin] + disabled: list[LoadedPlugin] + def all_plugins(self) -> Generator[LoadedPlugin]: ... + def versions_str(self) -> str: ... + +class PluginOptions(NamedTuple): + local_plugin_paths: tuple[str, ...] + enable_extensions: frozenset[str] + require_plugins: frozenset[str] + @classmethod + def blank(cls) -> PluginOptions: ... + +def parse_plugin_options( + cfg: configparser.RawConfigParser, cfg_dir: str, *, enable_extensions: str | None, require_plugins: str | None +) -> PluginOptions: ... +def find_plugins(cfg: configparser.RawConfigParser, opts: PluginOptions) -> list[Plugin]: ... +def load_plugins(plugins: list[Plugin], opts: PluginOptions) -> Plugins: ... diff --git a/stubs/flake8/flake8/plugins/pycodestyle.pyi b/stubs/flake8/flake8/plugins/pycodestyle.pyi new file mode 100644 index 000000000000..108770a0ae93 --- /dev/null +++ b/stubs/flake8/flake8/plugins/pycodestyle.pyi @@ -0,0 +1,32 @@ +from collections.abc import Generator +from typing import Any + +def pycodestyle_logical( + blank_before: Any, + blank_lines: Any, + checker_state: Any, + hang_closing: Any, + indent_char: Any, + indent_level: Any, + indent_size: Any, + line_number: Any, + lines: Any, + logical_line: Any, + max_doc_length: Any, + noqa: Any, + previous_indent_level: Any, + previous_logical: Any, + previous_unindented_logical_line: Any, + tokens: Any, + verbose: Any, +) -> Generator[tuple[int, str]]: ... +def pycodestyle_physical( + indent_char: Any, + line_number: Any, + lines: Any, + max_line_length: Any, + multiline: Any, + noqa: Any, + physical_line: Any, + total_lines: Any, +) -> Generator[tuple[int, str]]: ... diff --git a/stubs/flake8/flake8/plugins/pyflakes.pyi b/stubs/flake8/flake8/plugins/pyflakes.pyi new file mode 100644 index 000000000000..6453e63d8385 --- /dev/null +++ b/stubs/flake8/flake8/plugins/pyflakes.pyi @@ -0,0 +1,21 @@ +from argparse import Namespace +from ast import AST +from collections.abc import Generator +from logging import Logger +from typing import Any + +from pyflakes.checker import Checker + +from ..options.manager import OptionManager + +LOG: Logger +FLAKE8_PYFLAKES_CODES: dict[str, str] + +class FlakesChecker(Checker): + with_doctest: bool + def __init__(self, tree: AST, filename: str) -> None: ... + @classmethod + def add_options(cls, parser: OptionManager) -> None: ... + @classmethod + def parse_options(cls, options: Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, type[Any]]]: ... diff --git a/stubs/flake8/flake8/plugins/reporter.pyi b/stubs/flake8/flake8/plugins/reporter.pyi new file mode 100644 index 000000000000..ee3e72711d6e --- /dev/null +++ b/stubs/flake8/flake8/plugins/reporter.pyi @@ -0,0 +1,9 @@ +import argparse +from logging import Logger + +from ..formatting.base import BaseFormatter +from .finder import LoadedPlugin + +LOG: Logger + +def make(reporters: dict[str, LoadedPlugin], options: argparse.Namespace) -> BaseFormatter: ... diff --git a/stubs/flake8/flake8/processor.pyi b/stubs/flake8/flake8/processor.pyi new file mode 100644 index 000000000000..a00e0b1e2359 --- /dev/null +++ b/stubs/flake8/flake8/processor.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from argparse import Namespace +from ast import AST +from collections.abc import Generator +from logging import Logger +from tokenize import TokenInfo +from typing import Any, Final, TypeAlias + +from .plugins.finder import LoadedPlugin + +LOG: Logger +NEWLINE: Final[frozenset[int]] +SKIP_TOKENS: Final[frozenset[int]] + +_LogicalMapping: TypeAlias = list[tuple[int, tuple[int, int]]] +_Logical: TypeAlias = tuple[list[str], list[str], _LogicalMapping] + +class FileProcessor: + noqa: bool + options: Incomplete + filename: Incomplete + lines: Incomplete + blank_before: int + blank_lines: int + checker_state: Incomplete + hang_closing: Incomplete + indent_char: Incomplete + indent_level: int + indent_size: Incomplete + line_number: int + logical_line: str + max_line_length: Incomplete + max_doc_length: Incomplete + multiline: bool + previous_indent_level: int + previous_logical: str + previous_unindented_logical_line: str + tokens: Incomplete + total_lines: Incomplete + verbose: Incomplete + statistics: Incomplete + def __init__(self, filename: str, options: Namespace, lines: list[str] | None = None) -> None: ... + @property + def file_tokens(self) -> list[TokenInfo]: ... + def tstring_start(self, lineno: int) -> None: ... + def fstring_start(self, lineno: int) -> None: ... + def multiline_string(self, token: TokenInfo) -> Generator[str]: ... + def reset_blank_before(self) -> None: ... + def delete_first_token(self) -> None: ... + def visited_new_blank_line(self) -> None: ... + def update_state(self, mapping: _LogicalMapping) -> None: ... + def update_checker_state_for(self, plugin: LoadedPlugin) -> None: ... + def next_logical_line(self) -> None: ... + def build_logical_line_tokens(self) -> _Logical: ... + def build_ast(self) -> AST: ... + def build_logical_line(self) -> tuple[str, str, _LogicalMapping]: ... + def keyword_arguments_for(self, parameters: dict[str, bool], arguments: dict[str, Any]) -> dict[str, Any]: ... + def generate_tokens(self) -> Generator[TokenInfo]: ... + def noqa_line_for(self, line_number: int) -> str | None: ... + def next_line(self) -> str: ... + def read_lines(self) -> list[str]: ... + def read_lines_from_filename(self) -> list[str]: ... + def read_lines_from_stdin(self) -> list[str]: ... + def should_ignore_file(self) -> bool: ... + def strip_utf_bom(self) -> None: ... + +def is_eol_token(token: TokenInfo) -> bool: ... +def is_multiline_string(token: TokenInfo) -> bool: ... +def token_is_newline(token: TokenInfo) -> bool: ... +def count_parentheses(current_parentheses_count: int, token_text: str) -> int: ... +def expand_indent(line: str) -> int: ... +def mutate_string(text: str) -> str: ... diff --git a/stubs/flake8/flake8/statistics.pyi b/stubs/flake8/flake8/statistics.pyi new file mode 100644 index 000000000000..5b7d1f551e44 --- /dev/null +++ b/stubs/flake8/flake8/statistics.pyi @@ -0,0 +1,27 @@ +from collections.abc import Generator +from typing import NamedTuple + +from .violation import Violation + +class Statistics: + def __init__(self) -> None: ... + def error_codes(self) -> list[str]: ... + def record(self, error: Violation) -> None: ... + def statistics_for(self, prefix: str, filename: str | None = None) -> Generator[Statistic]: ... + +class Key(NamedTuple): + filename: str + code: str + @classmethod + def create_from(cls, error: Violation) -> Key: ... + def matches(self, prefix: str, filename: str | None) -> bool: ... + +class Statistic: + error_code: str + filename: str + message: str + count: int + def __init__(self, error_code: str, filename: str, message: str, count: int) -> None: ... + @classmethod + def create_from(cls, error: Violation) -> Statistic: ... + def increment(self) -> None: ... diff --git a/stubs/flake8/flake8/style_guide.pyi b/stubs/flake8/flake8/style_guide.pyi new file mode 100644 index 000000000000..bc27ec55b820 --- /dev/null +++ b/stubs/flake8/flake8/style_guide.pyi @@ -0,0 +1,70 @@ +import argparse +import enum +from _typeshed import Incomplete +from collections.abc import Generator, Sequence + +from .formatting.base import BaseFormatter +from .statistics import Statistics + +__all__ = ("StyleGuide",) + +class Selected(enum.Enum): + Explicitly = "explicitly selected" + Implicitly = "implicitly selected" + +class Ignored(enum.Enum): + Explicitly = "explicitly ignored" + Implicitly = "implicitly ignored" + +class Decision(enum.Enum): + Ignored = "ignored error" + Selected = "selected error" + +class DecisionEngine: + cache: Incomplete + selected_explicitly: Incomplete + ignored_explicitly: Incomplete + selected: Incomplete + ignored: Incomplete + def __init__(self, options: argparse.Namespace) -> None: ... + def was_selected(self, code: str) -> Selected | Ignored: ... + def was_ignored(self, code: str) -> Selected | Ignored: ... + def make_decision(self, code: str) -> Decision: ... + def decision_for(self, code: str) -> Decision: ... + +class StyleGuideManager: + options: Incomplete + formatter: Incomplete + stats: Incomplete + decider: Incomplete + style_guides: Incomplete + default_style_guide: Incomplete + style_guide_for: Incomplete + def __init__(self, options: argparse.Namespace, formatter: BaseFormatter, decider: DecisionEngine | None = None) -> None: ... + def populate_style_guides_with(self, options: argparse.Namespace) -> Generator[StyleGuide]: ... + def processing_file(self, filename: str) -> Generator[StyleGuide]: ... + def handle_error( + self, code: str, filename: str, line_number: int, column_number: int, text: str, physical_line: str | None = None + ) -> int: ... + +class StyleGuide: + options: Incomplete + formatter: Incomplete + stats: Incomplete + decider: Incomplete + filename: Incomplete + def __init__( + self, + options: argparse.Namespace, + formatter: BaseFormatter, + stats: Statistics, + filename: str | None = None, + decider: DecisionEngine | None = None, + ) -> None: ... + def copy(self, filename: str | None = None, extend_ignore_with: Sequence[str] | None = None) -> StyleGuide: ... + def processing_file(self, filename: str) -> Generator[StyleGuide]: ... + def applies_to(self, filename: str) -> bool: ... + def should_report_error(self, code: str) -> Decision: ... + def handle_error( + self, code: str, filename: str, line_number: int, column_number: int, text: str, physical_line: str | None = None + ) -> int: ... diff --git a/stubs/flake8/flake8/utils.pyi b/stubs/flake8/flake8/utils.pyi new file mode 100644 index 000000000000..b12329404e01 --- /dev/null +++ b/stubs/flake8/flake8/utils.pyi @@ -0,0 +1,25 @@ +import logging +from collections.abc import Sequence +from re import Pattern +from typing import Final, NamedTuple + +COMMA_SEPARATED_LIST_RE: Final[Pattern[str]] +LOCAL_PLUGIN_LIST_RE: Final[Pattern[str]] +NORMALIZE_PACKAGE_NAME_RE: Final[Pattern[str]] + +def parse_comma_separated_list(value: str, regexp: Pattern[str] = ...) -> list[str]: ... + +class _Token(NamedTuple): + tp: str + src: str + +def parse_files_to_codes_mapping(value_: Sequence[str] | str) -> list[tuple[str, list[str]]]: ... +def normalize_paths(paths: Sequence[str], parent: str = ".") -> list[str]: ... +def normalize_path(path: str, parent: str = ".") -> str: ... +def stdin_get_value() -> str: ... +def stdin_get_lines() -> list[str]: ... +def is_using_stdin(paths: list[str]) -> bool: ... +def fnmatch(filename: str, patterns: Sequence[str]) -> bool: ... +def matches_filename(path: str, patterns: Sequence[str], log_message: str, logger: logging.Logger) -> bool: ... +def get_python_version() -> str: ... +def normalize_pypi_name(s: str) -> str: ... diff --git a/stubs/flake8/flake8/violation.pyi b/stubs/flake8/flake8/violation.pyi new file mode 100644 index 000000000000..7526471ebb71 --- /dev/null +++ b/stubs/flake8/flake8/violation.pyi @@ -0,0 +1,13 @@ +from logging import Logger +from typing import NamedTuple + +LOG: Logger + +class Violation(NamedTuple): + code: str + filename: str + line_number: int + column_number: int + text: str + physical_line: str | None + def is_inline_ignored(self, disable_noqa: bool) -> bool: ... diff --git a/stubs/fpdf2/@tests/stubtest_allowlist.txt b/stubs/fpdf2/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..549327b0abaa --- /dev/null +++ b/stubs/fpdf2/@tests/stubtest_allowlist.txt @@ -0,0 +1,15 @@ +# Argument has default at runtime, but using it raises a TypeError. +fpdf.fpdf.FPDF.set_creation_date + +# fonttools shims since we can't import it +fpdf._fonttools_shims + +# Only present if harfbuzz is installed +fpdf.fonts.HarfBuzzFont + +# Stubtest wants us to use Literals, but that is unreasonable. +fpdf.unicode_script.UNICODE_RANGE_TO_SCRIPT + +# Ignore stubtest weirdness "fpdf.fonts.Glyph._DT is not present at runtime" +# https://github.com/python/mypy/issues/18811 +fpdf.fonts.Glyph._DT diff --git a/stubs/fpdf2/METADATA.toml b/stubs/fpdf2/METADATA.toml new file mode 100644 index 000000000000..bc7b19c18581 --- /dev/null +++ b/stubs/fpdf2/METADATA.toml @@ -0,0 +1,7 @@ +version = "2.8.4" +upstream-repository = "https://github.com/py-pdf/fpdf2" +dependencies = ["Pillow>=10.3.0"] +obsolete-since = { version = "2.8.6", date = "2026-02-19" } + +[tool.stubtest] +stubtest-dependencies = ["cryptography"] diff --git a/stubs/fpdf2/fpdf/__init__.pyi b/stubs/fpdf2/fpdf/__init__.pyi new file mode 100644 index 000000000000..6151095247d7 --- /dev/null +++ b/stubs/fpdf2/fpdf/__init__.pyi @@ -0,0 +1,36 @@ +from pathlib import Path + +from .enums import Align as Align, TextMode as TextMode, XPos as XPos, YPos as YPos +from .fonts import FontFace as FontFace, TextStyle as TextStyle +from .fpdf import FPDF as FPDF, FPDFException as FPDFException, TitleStyle as TitleStyle +from .html import HTML2FPDF as HTML2FPDF, HTMLMixin as HTMLMixin +from .prefs import ViewerPreferences as ViewerPreferences +from .template import FlexTemplate as FlexTemplate, Template as Template +from .util import get_scale_factor as get_scale_factor + +__license__: str +__version__: str +FPDF_VERSION: str +FPDF_FONT_DIR: Path + +__all__ = [ + "__version__", + "__license__", + "FPDF", + "FPDFException", + "FontFace", + "Align", + "TextMode", + "XPos", + "YPos", + "Template", + "FlexTemplate", + "TitleStyle", + "TextStyle", + "ViewerPreferences", + "HTMLMixin", + "HTML2FPDF", + "FPDF_VERSION", + "FPDF_FONT_DIR", + "get_scale_factor", +] diff --git a/stubs/fpdf2/fpdf/_fonttools_shims.pyi b/stubs/fpdf2/fpdf/_fonttools_shims.pyi new file mode 100644 index 000000000000..761a6ca68b3d --- /dev/null +++ b/stubs/fpdf2/fpdf/_fonttools_shims.pyi @@ -0,0 +1,55 @@ +# from fontTools.misc.loggingTools +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from logging import Logger +from typing import Any, Protocol, TypeAlias, type_check_only + +# from fonttools.ttLib.ttGlyphSet +@type_check_only +class _TTGlyph(Protocol): + def __init__(self, glyphSet: _TTGlyphSet, glyphName: str) -> None: ... + def draw(self, pen) -> None: ... + def drawPoints(self, pen) -> None: ... + +_TTGlyphSet: TypeAlias = Mapping[str, _TTGlyph] # Simplified for our needs + +# fonttools.ttLib.TTFont +_TTFont: TypeAlias = Any # noqa: Y047 + +# from fontTools.misc.loggingTools + +class LogMixin: + @property + def log(self) -> Logger: ... + +# from fontTools.pens.basePen +class AbstractPen: + @abstractmethod + def moveTo(self, pt: tuple[float, float]) -> None: ... + @abstractmethod + def lineTo(self, pt: tuple[float, float]) -> None: ... + @abstractmethod + def curveTo(self, *points: tuple[float, float]) -> None: ... + @abstractmethod + def qCurveTo(self, *points: tuple[float, float]) -> None: ... + def closePath(self) -> None: ... + def endPath(self) -> None: ... + @abstractmethod + def addComponent(self, glyphName: str, transformation: tuple[float, float, float, float, float, float]) -> None: ... + +class LoggingPen(LogMixin, AbstractPen, metaclass=ABCMeta): ... + +class DecomposingPen(LoggingPen, metaclass=ABCMeta): + skipMissingComponents: bool + glyphSet: _TTGlyphSet | None + def __init__(self, glyphSet: _TTGlyphSet | None) -> None: ... + def addComponent(self, glyphName: str, transformation: tuple[float, float, float, float, float, float]) -> None: ... + +class BasePen(DecomposingPen): + def __init__(self, glyphSet: _TTGlyphSet | None = ...) -> None: ... + def closePath(self) -> None: ... + def endPath(self) -> None: ... + def moveTo(self, pt: tuple[float, float]) -> None: ... + def lineTo(self, pt: tuple[float, float]) -> None: ... + def curveTo(self, *points: tuple[float, float]) -> None: ... + def qCurveTo(self, *points: tuple[float, float]) -> None: ... diff --git a/stubs/fpdf2/fpdf/actions.pyi b/stubs/fpdf2/fpdf/actions.pyi new file mode 100644 index 000000000000..98c9dc82ba08 --- /dev/null +++ b/stubs/fpdf2/fpdf/actions.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from abc import ABC, abstractmethod + +from .syntax import PDFObject + +class Action(ABC): + next: PDFObject | str | None + def __init__(self, next_action: PDFObject | str | None = None) -> None: ... + @abstractmethod + def serialize(self) -> str: ... + +class URIAction(Action): + uri: str + def __init__(self, uri: str, next_action: PDFObject | str | None = None) -> None: ... + def serialize(self) -> str: ... + +class NamedAction(Action): + action_name: str + def __init__(self, action_name: str, next_action: PDFObject | str | None = None) -> None: ... + def serialize(self) -> str: ... + +class GoToAction(Action): + dest: Incomplete + def __init__(self, dest, next_action: PDFObject | str | None = None) -> None: ... + def serialize(self) -> str: ... + +class GoToRemoteAction(Action): + file: str + dest: Incomplete + def __init__(self, file: str, dest, next_action: PDFObject | str | None = None) -> None: ... + def serialize(self) -> str: ... + +class LaunchAction(Action): + file: str + def __init__(self, file: str, next_action: PDFObject | str | None = None) -> None: ... + def serialize(self) -> str: ... diff --git a/stubs/fpdf2/fpdf/annotations.pyi b/stubs/fpdf2/fpdf/annotations.pyi new file mode 100644 index 000000000000..b55b30978dff --- /dev/null +++ b/stubs/fpdf2/fpdf/annotations.pyi @@ -0,0 +1,102 @@ +from _typeshed import Incomplete +from datetime import datetime +from typing import NamedTuple + +from .actions import Action +from .enums import AnnotationFlag, AnnotationName, FileAttachmentAnnotationName +from .syntax import Destination, Name, PDFContentStream, PDFObject + +DEFAULT_ANNOT_FLAGS: tuple[AnnotationFlag, ...] + +class AnnotationMixin: + type: Name + subtype: Name + rect: str + border: str + f_t: Name | None + v: Incomplete | None + f: int # AnnotationFlags bitmask + contents: str | None + a: Action | None + dest: Destination | None + c: str | None + t: str | None + m: str | None + quad_points: str | None + p: Incomplete | None + name: AnnotationName | FileAttachmentAnnotationName | None + ink_list: str | None + f_s: str | None + d_a: str | None + def __init__( + self, + subtype: str, + x: int, + y: int, + width: int, + height: int, + flags: tuple[AnnotationFlag | str, ...] = ..., + contents: str | None = None, + dest: Destination | None = None, + action: Action | None = None, + color: tuple[int, int, int] | None = None, + modification_time: datetime | None = None, + title: str | None = None, + quad_points: tuple[float, ...] | None = None, # multiple of 8 floats + border_width: int = 0, + name: AnnotationName | FileAttachmentAnnotationName | None = None, + ink_list: tuple[int, ...] = (), + file_spec: str | None = None, + field_type: str | None = None, + value=None, + default_appearance: str | None = None, + ) -> None: ... + +class PDFAnnotation(AnnotationMixin, PDFObject): ... + +class AnnotationDict(AnnotationMixin): + __slots__ = ( + "type", + "subtype", + "rect", + "border", + "f_t", + "v", + "f", + "contents", + "a", + "dest", + "c", + "t", + "quad_points", + "p", + "name", + "ink_list", + "f_s", + "d_a", + ) + def serialize(self) -> str: ... + +class PDFEmbeddedFile(PDFContentStream): + type: Name + params: str + def __init__( + self, + basename: str, + contents: bytes, + desc: str = "", + creation_date: datetime | None = None, + modification_date: datetime | None = None, + compress: bool = False, + checksum: bool = False, + ) -> None: ... + def globally_enclosed(self) -> bool: ... + def set_globally_enclosed(self, value: bool) -> None: ... + def basename(self) -> str: ... + def file_spec(self) -> FileSpec: ... + +class FileSpec(NamedTuple): + embedded_file: PDFEmbeddedFile + basename: str + desc: str + def serialize(self) -> str: ... diff --git a/stubs/fpdf2/fpdf/bidi.pyi b/stubs/fpdf2/fpdf/bidi.pyi new file mode 100644 index 000000000000..c748e733f349 --- /dev/null +++ b/stubs/fpdf2/fpdf/bidi.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Final, Literal, TypedDict, type_check_only + +from .enums import TextDirection + +MAX_DEPTH: Final = 125 + +@type_check_only +class _BracketInfo(TypedDict): + pair: str + type: Literal["o", "c"] + +BIDI_BRACKETS: Final[dict[str, _BracketInfo]] + +class BidiCharacter: + __slots__ = ["character_index", "character", "bidi_class", "original_bidi_class", "embedding_level", "direction"] + character_index: int + character: str + bidi_class: str + original_bidi_class: str + embedding_level: str + direction: Incomplete | None + + def __init__(self, character_index: int, character: str, embedding_level: str, debug: bool) -> None: ... + def get_direction_from_level(self) -> Literal["L", "R"]: ... + def set_class(self, cls: str) -> None: ... + +@dataclass +class DirectionalStatus: + __slots__ = ["embedding_level", "directional_override_status", "directional_isolate_status"] + embedding_level: int # between 0 and MAX_DEPTH + directional_override_status: Literal["N", "L", "R"] + directional_isolate_status: bool + +class IsolatingRun: + __slots__ = ["characters", "previous_direction", "next_direction"] + characters: list[BidiCharacter] + previous_direction: str + next_direction: str + def __init__(self, characters: list[BidiCharacter], sos: str, eos: str) -> None: ... + def resolve_weak_types(self) -> None: ... + def pair_brackets(self) -> list[tuple[int, int]]: ... + def resolve_neutral_types(self) -> None: ... + def resolve_implicit_levels(self) -> None: ... + +def auto_detect_base_direction(string: str, stop_at_pdi: bool = False, debug: bool = False) -> TextDirection: ... +def calculate_isolate_runs(paragraph: Sequence[BidiCharacter]) -> list[IsolatingRun]: ... + +class BidiParagraph: + __slots__ = ("text", "base_direction", "debug", "base_embedding_level", "characters") + text: str + base_direction: TextDirection + debug: bool + base_embedding_level: int + characters: list[BidiCharacter] + + def __init__(self, text: str, base_direction: TextDirection | None = None, debug: bool = False) -> None: ... + def get_characters(self) -> list[BidiCharacter]: ... + def get_characters_with_embedding_level(self) -> list[BidiCharacter]: ... + def get_reordered_characters(self) -> list[BidiCharacter]: ... + def get_all(self) -> tuple[list[BidiCharacter], tuple[BidiCharacter, ...]]: ... + def get_reordered_string(self) -> str: ... + def get_bidi_fragments(self) -> tuple[tuple[str, Literal["L", "R"]], ...]: ... + def get_bidi_characters(self) -> None: ... + def split_bidi_fragments(self) -> tuple[tuple[str, Literal["L", "R"]], ...]: ... + def reorder_resolved_levels(self) -> tuple[BidiCharacter, ...]: ... diff --git a/stubs/fpdf2/fpdf/deprecation.pyi b/stubs/fpdf2/fpdf/deprecation.pyi new file mode 100644 index 000000000000..7766bb38ab4c --- /dev/null +++ b/stubs/fpdf2/fpdf/deprecation.pyi @@ -0,0 +1,12 @@ +from types import ModuleType +from typing import Any +from typing_extensions import Never + +def support_deprecated_txt_arg(fn): ... + +class WarnOnDeprecatedModuleAttributes(ModuleType): + def __call__(self) -> Never: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +def get_stack_level() -> int: ... diff --git a/stubs/fpdf2/fpdf/drawing.pyi b/stubs/fpdf2/fpdf/drawing.pyi new file mode 100644 index 000000000000..20ba4daaf838 --- /dev/null +++ b/stubs/fpdf2/fpdf/drawing.pyi @@ -0,0 +1,502 @@ +import decimal +from _typeshed import Incomplete, SupportsWrite +from collections import OrderedDict +from collections.abc import Callable, Generator, Iterable, Sequence +from contextlib import contextmanager +from re import Pattern +from types import EllipsisType +from typing import Any, ClassVar, Literal, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from .enums import PathPaintRule +from .syntax import Name, Raw + +__pdoc__: dict[str, bool] + +_T = TypeVar("_T") +_CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) + +@type_check_only +class _SupportsSerialize(Protocol): + def serialize(self) -> str: ... + +@type_check_only +class _SupportsEndPoint(Protocol): + @property + def end_point(self) -> Point: ... + +def force_nodocument(item: _CallableT) -> _CallableT: ... +def force_document(item: _CallableT) -> _CallableT: ... + +Number: TypeAlias = int | float | decimal.Decimal +NumberClass: tuple[type, ...] +WHITESPACE: frozenset[str] +EOL_CHARS: frozenset[str] +DELIMITERS: frozenset[str] +STR_ESC: Pattern[str] +STR_ESC_MAP: dict[str, str] +_Primitive: TypeAlias = ( + _SupportsSerialize + | Number + | str + | bytes + | bool + | Raw + | list[_Primitive] + | tuple[_Primitive, ...] + | dict[Name, _Primitive] + | None +) + +class GraphicsStateDictRegistry(OrderedDict[Raw, Name]): + def register_style(self, style: GraphicsStyle) -> Name | None: ... + +def number_to_str(number: Number) -> str: ... +def render_pdf_primitive(primitive: _Primitive) -> Raw: ... + +@type_check_only +class _DeviceRGBBase(NamedTuple): + r: Number + g: Number + b: Number + a: Number | None + +class DeviceRGB(_DeviceRGBBase): + OPERATOR: ClassVar[str] + def __new__(cls, r: Number, g: Number, b: Number, a: Number | None = None) -> Self: ... + @property + def colors(self) -> tuple[Number, Number, Number]: ... + @property + def colors255(self) -> tuple[Number, Number, Number]: ... + def serialize(self) -> str: ... + +@type_check_only +class _DeviceGrayBase(NamedTuple): + g: Number + a: Number | None + +class DeviceGray(_DeviceGrayBase): + OPERATOR: ClassVar[str] + def __new__(cls, g: Number, a: Number | None = None) -> Self: ... + @property + def colors(self) -> tuple[Number, Number, Number]: ... + @property + def colors255(self) -> tuple[Number, Number, Number]: ... + def serialize(self) -> str: ... + +@type_check_only +class _DeviceCMYKBase(NamedTuple): + c: Number + m: Number + y: Number + k: Number + a: Number | None + +class DeviceCMYK(_DeviceCMYKBase): + OPERATOR: ClassVar[str] + def __new__(cls, c: Number, m: Number, y: Number, k: Number, a: Number | None = None) -> Self: ... + @property + def colors(self) -> tuple[Number, Number, Number, Number]: ... + def serialize(self) -> str: ... + +def rgb8(r: Number, g: Number, b: Number, a: Number | None = None) -> DeviceRGB: ... +def gray8(g: Number, a: Number | None = None) -> DeviceGray: ... + +@overload +def convert_to_device_color(r: DeviceCMYK) -> DeviceCMYK: ... +@overload +def convert_to_device_color(r: DeviceGray) -> DeviceGray: ... +@overload +def convert_to_device_color(r: DeviceRGB) -> DeviceRGB: ... +@overload +def convert_to_device_color(r: str) -> DeviceRGB: ... +@overload +def convert_to_device_color(r: int, g: Literal[-1] = -1, b: Literal[-1] = -1) -> DeviceGray: ... +@overload +def convert_to_device_color(r: Sequence[int] | int, g: int, b: int) -> DeviceGray | DeviceRGB: ... + +def cmyk8(c, m, y, k, a=None) -> DeviceCMYK: ... +def color_from_hex_string(hexstr: str) -> DeviceRGB: ... +def color_from_rgb_string(rgbstr: str) -> DeviceRGB: ... + +class Point(NamedTuple): + x: Number + y: Number + def render(self) -> str: ... + def dot(self, other: Point) -> Number: ... + def angle(self, other: Point) -> float: ... + def mag(self) -> Number: ... + def __add__(self, other: Point) -> Point: ... # type: ignore[override] + def __sub__(self, other: Point) -> Point: ... + def __neg__(self) -> Point: ... + def __mul__(self, other: Number) -> Point: ... # type: ignore[override] + def __rmul__(self, other: Number) -> Point: ... # type: ignore[override] + def __truediv__(self, other: Number) -> Point: ... + def __floordiv__(self, other: Number) -> Point: ... + def __matmul__(self, other: Transform) -> Point: ... + +class Transform(NamedTuple): + a: Number + b: Number + c: Number + d: Number + e: Number + f: Number + @classmethod + def identity(cls) -> Self: ... + @classmethod + def translation(cls, x: Number, y: Number) -> Self: ... + @classmethod + def scaling(cls, x: Number, y: Number | None = None) -> Self: ... + @classmethod + def rotation(cls, theta: Number) -> Self: ... + @classmethod + def rotation_d(cls, theta_d: Number) -> Self: ... + @classmethod + def shearing(cls, x: Number, y: Number | None = None) -> Self: ... + def translate(self, x: Number, y: Number) -> Self: ... + def scale(self, x: Number, y: Number | None = None) -> Self: ... + def rotate(self, theta: Number) -> Self: ... + def rotate_d(self, theta_d: Number) -> Self: ... + def shear(self, x: Number, y: Number | None = None) -> Self: ... + def about(self, x: Number, y: Number) -> Transform: ... + def __mul__(self, other: Number) -> Transform: ... # type: ignore[override] + def __rmul__(self, other: Number) -> Transform: ... # type: ignore[override] + def __matmul__(self, other: Transform) -> Self: ... + def render(self, last_item: _T) -> tuple[str, _T]: ... + +class GraphicsStyle: + INHERIT: ClassVar[EllipsisType] + MERGE_PROPERTIES: ClassVar[tuple[str, ...]] + TRANSPARENCY_KEYS: ClassVar[tuple[Name, ...]] + PDF_STYLE_KEYS: ClassVar[tuple[Name, ...]] + @classmethod + def merge(cls, parent, child) -> Self: ... + def __init__(self) -> None: ... + def __deepcopy__(self, memo) -> Self: ... + + @property + def allow_transparency(self): ... + @allow_transparency.setter + def allow_transparency(self, new): ... + + @property + def paint_rule(self) -> PathPaintRule | EllipsisType: ... + @paint_rule.setter + def paint_rule(self, new: PathPaintRule | str | EllipsisType | None) -> None: ... + + @property + def auto_close(self) -> bool | EllipsisType: ... + @auto_close.setter + def auto_close(self, new: bool | EllipsisType) -> None: ... + + @property + def intersection_rule(self): ... + @intersection_rule.setter + def intersection_rule(self, new) -> None: ... + + @property + def fill_color(self): ... + @fill_color.setter + def fill_color(self, color) -> None: ... + + @property + def fill_opacity(self): ... + @fill_opacity.setter + def fill_opacity(self, new) -> None: ... + + @property + def stroke_color(self): ... + @stroke_color.setter + def stroke_color(self, color: str | DeviceRGB | DeviceGray | DeviceCMYK | EllipsisType | None) -> None: ... + + @property + def stroke_opacity(self): ... + @stroke_opacity.setter + def stroke_opacity(self, new) -> None: ... + + @property + def blend_mode(self): ... + @blend_mode.setter + def blend_mode(self, value) -> None: ... + + @property + def stroke_width(self): ... + @stroke_width.setter + def stroke_width(self, width: Number | EllipsisType | None) -> None: ... + + @property + def stroke_cap_style(self): ... + @stroke_cap_style.setter + def stroke_cap_style(self, value) -> None: ... + + @property + def stroke_join_style(self): ... + @stroke_join_style.setter + def stroke_join_style(self, value) -> None: ... + + @property + def stroke_miter_limit(self): ... + @stroke_miter_limit.setter + def stroke_miter_limit(self, value: Number | EllipsisType) -> None: ... + + @property + def stroke_dash_pattern(self): ... + @stroke_dash_pattern.setter + def stroke_dash_pattern(self, value: Number | Iterable[Number] | EllipsisType | None) -> None: ... + + @property + def stroke_dash_phase(self): ... + @stroke_dash_phase.setter + def stroke_dash_phase(self, value: Number | EllipsisType): ... + + def serialize(self) -> Raw | None: ... + def resolve_paint_rule(self) -> PathPaintRule: ... + +class Move(NamedTuple): + pt: Point + @property + def end_point(self) -> Point: ... + def render( + self, gsd_registry: GraphicsStateDictRegistry, style: GraphicsStyle, last_item: _SupportsEndPoint, initial_point: Point + ) -> tuple[str, Self, Point]: ... + def render_debug( + self, + gsd_registry: GraphicsStateDictRegistry, + style: GraphicsStyle, + last_item: _SupportsEndPoint, + initial_point: Point, + debug_stream: SupportsWrite[str], + pfx: str, + ) -> tuple[str, Self, Point]: ... + +class RelativeMove(NamedTuple): + pt: Point + def render( + self, gsd_registry: GraphicsStateDictRegistry, style: GraphicsStyle, last_item: _SupportsEndPoint, initial_point: Point + ) -> tuple[str, Move, Point]: ... + def render_debug( + self, + gsd_registry: GraphicsStateDictRegistry, + style: GraphicsStyle, + last_item: _SupportsEndPoint, + initial_point: Point, + debug_stream: SupportsWrite[str], + pfx: str, + ) -> tuple[str, Move, Point]: ... + +class Line(NamedTuple): + pt: Point + @property + def end_point(self) -> Point: ... + def render( + self, gsd_registry: GraphicsStateDictRegistry, style: GraphicsStyle, last_item: _SupportsEndPoint, initial_point: Point + ) -> tuple[str, Self, Point]: ... + def render_debug( + self, + gsd_registry: GraphicsStateDictRegistry, + style: GraphicsStyle, + last_item: _SupportsEndPoint, + initial_point: Point, + debug_stream: SupportsWrite[str], + pfx: str, + ) -> tuple[str, Self, Point]: ... + +class RelativeLine(NamedTuple): + pt: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class HorizontalLine(NamedTuple): + x: Number + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RelativeHorizontalLine(NamedTuple): + x: Number + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class VerticalLine(NamedTuple): + y: Number + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RelativeVerticalLine(NamedTuple): + y: Number + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class BezierCurve(NamedTuple): + c1: Point + c2: Point + end: Point + @property + def end_point(self) -> Point: ... + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RelativeBezierCurve(NamedTuple): + c1: Point + c2: Point + end: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class QuadraticBezierCurve(NamedTuple): + ctrl: Point + end: Point + @property + def end_point(self) -> Point: ... + def to_cubic_curve(self, start_point): ... + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RelativeQuadraticBezierCurve(NamedTuple): + ctrl: Point + end: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class Arc(NamedTuple): + radii: Point + rotation: Number + large: bool + sweep: bool + end: Point + @staticmethod + def subdivde_sweep(sweep_angle: Number) -> Generator[tuple[Point, Point, Point]]: ... + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RelativeArc(NamedTuple): + radii: Point + rotation: Number + large: bool + sweep: bool + end: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class Rectangle(NamedTuple): + org: Point + size: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class RoundedRectangle(NamedTuple): + org: Point + size: Point + corner_radii: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class Ellipse(NamedTuple): + radii: Point + center: Point + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class ImplicitClose(NamedTuple): + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class Close(NamedTuple): + def render(self, gsd_registry, style, last_item, initial_point): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class DrawingContext: + def __init__(self) -> None: ... + def add_item(self, item, _copy: bool = True) -> None: ... + def render(self, gsd_registry, first_point, scale, height, starting_style): ... + def render_debug(self, gsd_registry, first_point, scale, height, starting_style, debug_stream): ... + +class PaintedPath: + def __init__(self, x: Number = 0, y: Number = 0) -> None: ... + def __deepcopy__(self, memo) -> Self: ... + @property + def style(self) -> GraphicsStyle: ... + + @property + def transform(self): ... + @transform.setter + def transform(self, tf) -> None: ... + + @property + def auto_close(self): ... + @auto_close.setter + def auto_close(self, should) -> None: ... + + @property + def paint_rule(self): ... + @paint_rule.setter + def paint_rule(self, style) -> None: ... + + @property + def clipping_path(self): ... + @clipping_path.setter + def clipping_path(self, new_clipath) -> None: ... + + @contextmanager + def transform_group(self, transform) -> Generator[Self]: ... + def add_path_element(self, item, _copy: bool = True) -> None: ... + def remove_last_path_element(self) -> None: ... + def rectangle(self, x: Number, y: Number, w: Number, h: Number, rx: Number = 0, ry: Number = 0) -> Self: ... + def circle(self, cx: Number, cy: Number, r: Number) -> Self: ... + def ellipse(self, cx: Number, cy: Number, rx: Number, ry: Number) -> Self: ... + def move_to(self, x: Number, y: Number) -> Self: ... + def move_relative(self, x: Number, y: Number) -> Self: ... + def line_to(self, x: Number, y: Number) -> Self: ... + def line_relative(self, dx: Number, dy: Number) -> Self: ... + def horizontal_line_to(self, x: Number) -> Self: ... + def horizontal_line_relative(self, dx: Number) -> Self: ... + def vertical_line_to(self, y: Number) -> Self: ... + def vertical_line_relative(self, dy: Number) -> Self: ... + def curve_to(self, x1: Number, y1: Number, x2: Number, y2: Number, x3: Number, y3: Number) -> Self: ... + def curve_relative(self, dx1: Number, dy1: Number, dx2: Number, dy2: Number, dx3: Number, dy3: Number) -> Self: ... + def quadratic_curve_to(self, x1: Number, y1: Number, x2: Number, y2: Number) -> Self: ... + def quadratic_curve_relative(self, dx1: Number, dy1: Number, dx2: Number, dy2: Number) -> Self: ... + def arc_to( + self, rx: Number, ry: Number, rotation: Number, large_arc: bool, positive_sweep: bool, x: Number, y: Number + ) -> Self: ... + def arc_relative( + self, rx: Number, ry: Number, rotation: Number, large_arc: bool, positive_sweep: bool, dx: Number, dy: Number + ) -> Self: ... + def close(self) -> None: ... + def render(self, gsd_registry, style, last_item, initial_point, debug_stream=None, pfx=None): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class ClippingPath(PaintedPath): + paint_rule: PathPaintRule + def __init__(self, x: Number = 0, y: Number = 0) -> None: ... + def render(self, gsd_registry, style, last_item, initial_point, debug_stream=None, pfx=None): ... + def render_debug(self, gsd_registry, style, last_item, initial_point, debug_stream, pfx): ... + +class GraphicsContext: + style: GraphicsStyle + path_items: list[Incomplete] + def __init__(self) -> None: ... + def __deepcopy__(self, memo) -> Self: ... + + @property + def transform(self) -> Transform | None: ... + @transform.setter + def transform(self, tf) -> None: ... + + @property + def clipping_path(self) -> ClippingPath | None: ... + @clipping_path.setter + def clipping_path(self, new_clipath) -> None: ... + + def add_item(self, item, _copy: bool = True) -> None: ... + def remove_last_item(self) -> None: ... + def merge(self, other_context) -> None: ... + def build_render_list( + self, gsd_registry, style, last_item, initial_point, debug_stream=None, pfx=None, _push_stack: bool = True + ): ... + def render( + self, gsd_registry, style: DrawingContext, last_item, initial_point, debug_stream=None, pfx=None, _push_stack: bool = True + ): ... + def render_debug( + self, gsd_registry, style: DrawingContext, last_item, initial_point, debug_stream, pfx, _push_stack: bool = True + ): ... diff --git a/stubs/fpdf2/fpdf/encryption.pyi b/stubs/fpdf2/fpdf/encryption.pyi new file mode 100644 index 000000000000..6a02f052d0ec --- /dev/null +++ b/stubs/fpdf2/fpdf/encryption.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Generator, Iterable +from logging import Logger +from typing import ClassVar, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from .enums import AccessPermission, EncryptionMethod +from .fpdf import FPDF +from .syntax import Name, PDFObject + +_Key: TypeAlias = SupportsLenAndGetItem[int] +_T_co = TypeVar("_T_co", covariant=True) + +LOGGER: Logger + +import_error: ImportError | None + +@type_check_only +class _SupportsGetItem(Protocol[_T_co]): + def __getitem__(self, k: int, /) -> _T_co: ... + +class ARC4: + MOD: ClassVar[int] + def KSA(self, key: _Key) -> list[int]: ... + def PRGA(self, S: _SupportsGetItem[int]) -> Generator[int]: ... + def encrypt(self, key: _Key, text: Iterable[int]) -> list[int]: ... + +class CryptFilter: + type: Name + c_f_m: Name + length: int + def __init__(self, mode: str, length: int) -> None: ... + def serialize(self) -> str: ... + +class EncryptionDictionary(PDFObject): + filter: Name + length: int + r: int + o: str + u: str + v: int + p: int + encrypt_metadata: str # not always defined + c_f: str # not always defined + stm_f: Name + str_f: Name + def __init__(self, security_handler: StandardSecurityHandler) -> None: ... + +class StandardSecurityHandler: + DEFAULT_PADDING: ClassVar[bytes] + fpdf: FPDF + access_permission: int + owner_password: str + user_password: str + encryption_method: EncryptionMethod | None + cf: CryptFilter | None + key_length: int + version: int + revision: int + encrypt_metadata: bool + + # The following fields are only defined after a call to generate_passwords(). + file_id: Incomplete + info_id: Incomplete + o: str + k: str + u: str + # The following field is only defined after a call to generate_user_password_rev6(). + ue: Incomplete + # The following field is only defined after a call to generate_owner_password_rev6(). + oe: Incomplete + # The following field is only defined after a call to generate_perms_rev6(). + perms_rev6: Incomplete + + def __init__( + self, + fpdf: FPDF, + owner_password: str, + user_password: str | None = None, + permission: AccessPermission = ..., + encryption_method: EncryptionMethod = ..., + encrypt_metadata: bool = False, + ) -> None: ... + def generate_passwords(self, file_id: str) -> None: ... + def get_encryption_obj(self) -> EncryptionDictionary: ... + + @overload + def encrypt(self, text: bytes | bytearray, obj_id: int) -> bytes: ... + @overload + def encrypt(self, text: str, obj_id: int) -> str: ... + + def encrypt_string(self, string: str, obj_id: int) -> str: ... + def encrypt_stream(self, stream: bytes | bytearray, obj_id: int) -> bytes: ... + def is_aes_algorithm(self) -> bool: ... + def encrypt_bytes(self, data: bytes | bytearray, obj_id: int) -> list[int]: ... + def encrypt_AES_cryptography(self, key: bytes, data: bytes | bytearray) -> bytes: ... + @classmethod + def get_random_bytes(cls, size: int) -> bytes: ... + @classmethod + def prepare_string(cls, string: str) -> bytes: ... + def padded_password(self, password: str) -> bytearray: ... + def generate_owner_password(self) -> str: ... + def generate_user_password(self) -> str: ... + @classmethod + def compute_hash(cls, input_password: bytes | bytearray, salt: bytes, user_key: bytes | bytearray = ...) -> bytes: ... + def generate_user_password_rev6(self) -> None: ... + def generate_owner_password_rev6(self) -> None: ... + def generate_perms_rev6(self) -> None: ... + def generate_encryption_key(self) -> bytes: ... + +def md5(data: bytes | bytearray) -> bytes: ... +def int32(n: int) -> int: ... diff --git a/stubs/fpdf2/fpdf/enums.pyi b/stubs/fpdf2/fpdf/enums.pyi new file mode 100644 index 000000000000..076d48c0af6b --- /dev/null +++ b/stubs/fpdf2/fpdf/enums.pyi @@ -0,0 +1,421 @@ +from abc import ABC, abstractmethod +from collections.abc import Sequence +from dataclasses import dataclass +from enum import Enum, Flag, IntEnum, IntFlag +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +from .drawing import DeviceCMYK, DeviceGray, DeviceRGB +from .syntax import Name + +_Color: TypeAlias = str | int | Sequence[int] | DeviceCMYK | DeviceGray | DeviceRGB + +class SignatureFlag(IntEnum): + SIGNATURES_EXIST = 1 + APPEND_ONLY = 2 + +class CoerciveEnum(Enum): # type: ignore[misc] # Enum with no members + @classmethod + def coerce(cls, value: Self | str, case_sensitive: bool = False) -> Self: ... + +class CoerciveIntEnum(IntEnum): # type: ignore[misc] # Enum with no members + @classmethod + def coerce(cls, value: Self | str | int) -> Self: ... + +class CoerciveIntFlag(IntFlag): # type: ignore[misc] # Enum with no members + @classmethod + def coerce(cls, value: Self | str | int) -> Self: ... + +class WrapMode(CoerciveEnum): + WORD = "WORD" + CHAR = "CHAR" + +class CharVPos(CoerciveEnum): + SUP = "SUP" + SUB = "SUB" + NOM = "NOM" + DENOM = "DENOM" + LINE = "LINE" + +class Align(CoerciveEnum): + C = "CENTER" + X = "X_CENTER" + L = "LEFT" + R = "RIGHT" + J = "JUSTIFY" + + @classmethod + def coerce(cls, value: Self | str) -> Self: ... # type: ignore[override] + +_Align: TypeAlias = Align | Literal["CENTER", "X_CENTER", "LEFT", "RIGHT", "JUSTIFY"] # noqa: Y047 + +class VAlign(CoerciveEnum): + M = "MIDDLE" + T = "TOP" + B = "BOTTOM" + + @classmethod + def coerce(cls, value: Self | str) -> Self: ... # type: ignore[override] + +class TextEmphasis(CoerciveIntFlag): + NONE = 0 + B = 1 + I = 2 + U = 4 + S = 8 + + @property + def style(self) -> str: ... + def add(self, value: TextEmphasis) -> TextEmphasis: ... + def remove(self, value: TextEmphasis) -> TextEmphasis: ... + +class MethodReturnValue(CoerciveIntFlag): + PAGE_BREAK = 1 + LINES = 2 + HEIGHT = 4 + +class CellBordersLayout(CoerciveIntFlag): + NONE = 0 + LEFT = 1 + RIGHT = 2 + TOP = 4 + BOTTOM = 8 + ALL = 15 + INHERIT = 16 + +@dataclass +class TableBorderStyle: + thickness: float | None = None + color: int | tuple[int, int, int] | None = None + dash: float | None = None + gap: float = 0.0 + phase: float = 0.0 + + @staticmethod + def from_bool(should_draw: TableBorderStyle | bool | None) -> TableBorderStyle: ... + @property + def dash_dict(self) -> dict[str, float | None]: ... + def changes_stroke(self, pdf) -> bool: ... + def should_render(self) -> bool: ... + def get_change_stroke_commands(self, scale: float) -> list[str]: ... + @staticmethod + def get_line_command(x1: float, y1: float, x2: float, y2: float) -> list[str]: ... + def get_draw_commands(self, pdf, x1: float, y1: float, x2: float, y2: float) -> list[str]: ... + +@dataclass +class TableCellStyle: + left: bool | TableBorderStyle = False + bottom: bool | TableBorderStyle = False + right: bool | TableBorderStyle = False + top: bool | TableBorderStyle = False + + @staticmethod + def get_change_fill_color_command(color: _Color | None) -> list[str]: ... + def get_draw_commands( + self, pdf, x1: float, y1: float, x2: float, y2: float, fill_color: _Color | None = None + ) -> list[str]: ... + def override_cell_border(self, cell_border: CellBordersLayout) -> Self: ... + def draw_cell_border(self, pdf, x1: float, y1: float, x2: float, y2: float, fill_color: _Color | None = None) -> None: ... + +class TableBordersLayout(ABC): + ALL: Final[TableBordersLayoutAll] + NONE: Final[TableBordersLayoutNone] + INTERNAL: Final[TableBordersLayoutInternal] + MINIMAL: Final[TableBordersLayoutMinimal] + HORIZONTAL_LINES: Final[TableBordersLayoutHorizontalLines] + NO_HORIZONTAL_LINES: Final[TableBordersLayoutNoHorizontalLines] + SINGLE_TOP_LINE: Final[TableBordersLayoutSingleTopLine] + @abstractmethod + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + @classmethod + def coerce(cls, value: Self | str) -> Self: ... + +class TableBordersLayoutAll(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutNone(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutInternal(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutMinimal(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutHorizontalLines(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutNoHorizontalLines(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableBordersLayoutSingleTopLine(TableBordersLayout): + def cell_style_getter( + self, row_idx: int, col_idx: int, col_pos: int, num_heading_rows: int, num_rows: int, num_col_idx: int, num_col_pos: int + ) -> TableCellStyle: ... + +class TableCellFillMode(CoerciveEnum): + NONE = "NONE" + ALL = "ALL" + ROWS = "ROWS" + COLUMNS = "COLUMNS" + EVEN_ROWS = "EVEN_ROWS" + EVEN_COLUMNS = "EVEN_COLUMNS" + + def should_fill_cell(self, i: int, j: int) -> bool: ... + @classmethod + def coerce(cls, value: Self | str) -> Self: ... # type: ignore[override] + +class TableSpan(CoerciveEnum): + ROW = "ROW" + COL = "COL" + +class TableHeadingsDisplay(CoerciveIntEnum): + NONE = 0 + ON_TOP_OF_EVERY_PAGE = 1 + +class RenderStyle(CoerciveEnum): + D = "DRAW" + F = "FILL" + DF = "DRAW_FILL" + @property + def operator(self) -> str: ... + @property + def is_draw(self) -> bool: ... + @property + def is_fill(self) -> bool: ... + @classmethod + def coerce(cls, value: Self | str) -> Self: ... # type: ignore[override] + +class TextMode(CoerciveIntEnum): + FILL = 0 + STROKE = 1 + FILL_STROKE = 2 + INVISIBLE = 3 + FILL_CLIP = 4 + STROKE_CLIP = 5 + FILL_STROKE_CLIP = 6 + CLIP = 7 + +class XPos(CoerciveEnum): + LEFT = "LEFT" + RIGHT = "RIGHT" + START = "START" + END = "END" + WCONT = "WCONT" + CENTER = "CENTER" + LMARGIN = "LMARGIN" + RMARGIN = "RMARGIN" + +class YPos(CoerciveEnum): + TOP = "TOP" + LAST = "LAST" + NEXT = "NEXT" + TMARGIN = "TMARGIN" + BMARGIN = "BMARGIN" + +class Angle(CoerciveIntEnum): + NORTH = 90 + EAST = 0 + SOUTH = 270 + WEST = 180 + NORTHEAST = 45 + SOUTHEAST = 315 + SOUTHWEST = 225 + NORTHWEST = 135 + +class PageLayout(CoerciveEnum): + SINGLE_PAGE = Name("SinglePage") + ONE_COLUMN = Name("OneColumn") + TWO_COLUMN_LEFT = Name("TwoColumnLeft") + TWO_COLUMN_RIGHT = Name("TwoColumnRight") + TWO_PAGE_LEFT = Name("TwoPageLeft") + TWO_PAGE_RIGHT = Name("TwoPageRight") + +class PageMode(CoerciveEnum): + USE_NONE = Name("UseNone") + USE_OUTLINES = Name("UseOutlines") + USE_THUMBS = Name("UseThumbs") + FULL_SCREEN = Name("FullScreen") + USE_OC = Name("UseOC") + USE_ATTACHMENTS = Name("UseAttachments") + +class TextMarkupType(CoerciveEnum): + HIGHLIGHT = Name("Highlight") + UNDERLINE = Name("Underline") + SQUIGGLY = Name("Squiggly") + STRIKE_OUT = Name("StrikeOut") + +class BlendMode(CoerciveEnum): + NORMAL = Name("Normal") + MULTIPLY = Name("Multiply") + SCREEN = Name("Screen") + OVERLAY = Name("Overlay") + DARKEN = Name("Darken") + LIGHTEN = Name("Lighten") + COLOR_DODGE = Name("ColorDodge") + COLOR_BURN = Name("ColorBurn") + HARD_LIGHT = Name("HardLight") + SOFT_LIGHT = Name("SoftLight") + DIFFERENCE = Name("Difference") + EXCLUSION = Name("Exclusion") + HUE = Name("Hue") + SATURATION = Name("Saturation") + COLOR = Name("Color") + LUMINOSITY = Name("Luminosity") + +class AnnotationFlag(CoerciveIntEnum): + INVISIBLE = 1 + HIDDEN = 2 + PRINT = 4 + NO_ZOOM = 8 + NO_ROTATE = 16 + NO_VIEW = 32 + READ_ONLY = 64 + LOCKED = 128 + TOGGLE_NO_VIEW = 256 + LOCKED_CONTENTS = 512 + +class AnnotationName(CoerciveEnum): + NOTE = Name("Note") + COMMENT = Name("Comment") + HELP = Name("Help") + PARAGRAPH = Name("Paragraph") + NEW_PARAGRAPH = Name("NewParagraph") + INSERT = Name("Insert") + +class FileAttachmentAnnotationName(CoerciveEnum): + PUSH_PIN = Name("PushPin") + GRAPH_PUSH_PIN = Name("GraphPushPin") + PAPERCLIP_TAG = Name("PaperclipTag") + +class IntersectionRule(CoerciveEnum): + NONZERO = "nonzero" + EVENODD = "evenodd" + +class PathPaintRule(CoerciveEnum): + STROKE = "S" + FILL_NONZERO = "f" + FILL_EVENODD = "f*" + STROKE_FILL_NONZERO = "B" + STROKE_FILL_EVENODD = "B*" + DONT_PAINT = "n" + AUTO = "auto" + +class ClippingPathIntersectionRule(CoerciveEnum): + NONZERO = "W" + EVENODD = "W*" + +class StrokeCapStyle(CoerciveIntEnum): + BUTT = 0 + ROUND = 1 + SQUARE = 2 + +class StrokeJoinStyle(CoerciveIntEnum): + MITER = 0 + ROUND = 1 + BEVEL = 2 + +class PDFStyleKeys(Enum): + FILL_ALPHA = Name("ca") + BLEND_MODE = Name("BM") + STROKE_ALPHA = Name("CA") + STROKE_ADJUSTMENT = Name("SA") + STROKE_WIDTH = Name("LW") + STROKE_CAP_STYLE = Name("LC") + STROKE_JOIN_STYLE = Name("LJ") + STROKE_MITER_LIMIT = Name("ML") + STROKE_DASH_PATTERN = Name("D") + +class Corner(CoerciveEnum): + TOP_RIGHT = "TOP_RIGHT" + TOP_LEFT = "TOP_LEFT" + BOTTOM_RIGHT = "BOTTOM_RIGHT" + BOTTOM_LEFT = "BOTTOM_LEFT" + +class FontDescriptorFlags(Flag): + FIXED_PITCH = 1 + SYMBOLIC = 4 + ITALIC = 64 + FORCE_BOLD = 262144 + +class AccessPermission(IntFlag): + PRINT_LOW_RES = 4 + MODIFY = 8 + COPY = 16 + ANNOTATION = 32 + FILL_FORMS = 256 + COPY_FOR_ACCESSIBILITY = 512 + ASSEMBLE = 1024 + PRINT_HIGH_RES = 2048 + @classmethod + def all(cls) -> int: ... + @classmethod + def none(cls) -> Literal[0]: ... + +class EncryptionMethod(Enum): + NO_ENCRYPTION = 0 + RC4 = 1 + AES_128 = 2 + AES_256 = 3 + +class TextDirection(CoerciveEnum): + LTR = "LTR" + RTL = "RTL" + TTB = "TTB" + BTT = "BTT" + +class OutputIntentSubType(CoerciveEnum): + PDFX = "GTS_PDFX" + PDFA = "GTS_PDFA1" + ISOPDF = "ISO_PDFE1" + +class PageLabelStyle(CoerciveEnum): + NUMBER = "D" + UPPER_ROMAN = "R" + LOWER_ROMAN = "r" + UPPER_LETTER = "A" + LOWER_LETTER = "a" + NONE = None + +class Duplex(CoerciveEnum): + SIMPLEX = "Simplex" + DUPLEX_FLIP_SHORT_EDGE = "DuplexFlipShortEdge" + DUPLEX_FLIP_LONG_EDGE = "DuplexFlipLongEdge" + +class PageBoundaries(CoerciveEnum): + ART_BOX = "ArtBox" + BLEED_BOX = "BleedBox" + CROP_BOX = "CropBox" + MEDIA_BOX = "MediaBox" + TRIM_BOX = "TrimBox" + +class PageOrientation(CoerciveEnum): + PORTRAIT = "P" + LANDSCAPE = "L" + + @classmethod + def coerce(cls, value: Self | str) -> Self: ... # type: ignore[override] + +class PDFResourceType(Enum): + EXT_G_STATE = "ExtGState" + COLOR_SPACE = "ColorSpace" + PATTERN = "Pattern" + SHADDING = "Shading" + X_OBJECT = "XObject" + FONT = "Font" + PROC_SET = "ProcSet" + PROPERTIES = "Properties" diff --git a/stubs/fpdf2/fpdf/errors.pyi b/stubs/fpdf2/fpdf/errors.pyi new file mode 100644 index 000000000000..a2aff7bb139b --- /dev/null +++ b/stubs/fpdf2/fpdf/errors.pyi @@ -0,0 +1,12 @@ +from typing import Any + +class FPDFException(Exception): ... + +class FPDFPageFormatException(FPDFException): + argument: Any + unknown: Any + one: Any + def __init__(self, argument, unknown: bool = False, one: bool = False) -> None: ... + +class FPDFUnicodeEncodingException(FPDFException): + def __init__(self, text_index, character, font_name) -> None: ... diff --git a/stubs/fpdf2/fpdf/fonts.pyi b/stubs/fpdf2/fpdf/fonts.pyi new file mode 100644 index 000000000000..3b57d67408e8 --- /dev/null +++ b/stubs/fpdf2/fpdf/fonts.pyi @@ -0,0 +1,182 @@ +import dataclasses +from _typeshed import Incomplete, Unused +from collections import defaultdict +from collections.abc import Generator +from dataclasses import dataclass +from logging import Logger +from typing import Final, overload +from typing_extensions import Self, deprecated + +from ._fonttools_shims import _TTFont +from .drawing import DeviceGray, DeviceRGB, Number +from .enums import Align, TextEmphasis +from .syntax import PDFObject + +LOGGER: Logger + +# Only defined if harfbuzz is installed. +class HarfBuzzFont(Incomplete): # derives from uharfbuzz.Font + def __deepcopy__(self, _memo: object) -> Self: ... + +@dataclass +class FontFace: + __slots__ = ("family", "emphasis", "size_pt", "color", "fill_color") + family: str | None + emphasis: TextEmphasis | None + size_pt: int | None + color: DeviceGray | DeviceRGB | None + fill_color: DeviceGray | DeviceRGB | None + + def __init__( + self, + family: str | None = None, + emphasis=None, + size_pt: int | None = None, + color: int | tuple[Number, Number, Number] | DeviceGray | DeviceRGB | None = None, + fill_color: int | tuple[Number, Number, Number] | DeviceGray | DeviceRGB | None = None, + ) -> None: ... + + replace = dataclasses.replace + + @overload + @staticmethod + def combine(default_style: None, override_style: None) -> None: ... # type: ignore[misc] + @overload + @staticmethod + def combine(default_style: FontFace | None, override_style: FontFace | None) -> FontFace: ... + +class TextStyle(FontFace): + t_margin: int + l_margin: int | Align + b_margin: int + def __init__( + self, + font_family: str | None = None, + font_style: str | None = None, + font_size_pt: int | None = None, + color: int | tuple[int, int, int] | None = None, + fill_color: int | tuple[int, int, int] | None = None, + underline: bool = False, + t_margin: int | None = None, + l_margin: int | Align | str | None = None, + b_margin: int | None = None, + ): ... + def replace( # type: ignore[override] + self, + /, + font_family: str | None = None, + emphasis: TextEmphasis | None = None, + font_size_pt: int | None = None, + color: int | tuple[int, int, int] | None = None, + fill_color: int | tuple[int, int, int] | None = None, + t_margin: int | None = None, + l_margin: int | None = None, + b_margin: int | None = None, + ) -> TextStyle: ... + +@deprecated("fpdf.TitleStyle is deprecated since 2.7.10. It has been replaced by fpdf.TextStyle.") +class TitleStyle(TextStyle): ... + +__pdoc__: Final[dict[str, bool]] + +class CoreFont: + __slots__ = ("i", "type", "name", "sp", "ss", "up", "ut", "cw", "fontkey", "emphasis") + i: int + type: str + name: str + up: int + ut: int + sp: int + ss: int + cw: int + fontkey: str + emphasis: TextEmphasis + def __init__(self, fpdf, fontkey: str, style: int) -> None: ... + def get_text_width(self, text: str, font_size_pt: int, _: Unused) -> float: ... + def encode_text(self, text: str) -> str: ... + +class TTFFont: + __slots__ = ( + "i", + "type", + "name", + "desc", + "glyph_ids", + "hbfont", + "sp", + "ss", + "up", + "ut", + "cw", + "ttffile", + "fontkey", + "emphasis", + "scale", + "subset", + "cmap", + "ttfont", + "missing_glyphs", + ) + i: int + type: str + ttffile: Incomplete + fontkey: str + ttfont: _TTFont + scale: float + desc: PDFFontDescriptor + cw: defaultdict[str, int] + cmap: Incomplete + glyph_ids: dict[Incomplete, Incomplete] + missing_glyphs: list[Incomplete] + name: str + up: int + ut: int + sp: int + ss: int + emphasis: TextEmphasis + subset: SubsetMap + hbfont: HarfBuzzFont | None # Not always defined. + def __init__(self, fpdf, font_file_path, fontkey: str, style: int) -> None: ... + def __deepcopy__(self, memo) -> Self: ... + def close(self) -> None: ... + def get_text_width(self, text: str, font_size_pt: int, text_shaping_params): ... + def shaped_text_width(self, text: str, font_size_pt: int, text_shaping_params): ... + def perform_harfbuzz_shaping(self, text: str, font_size_pt: int, text_shaping_params): ... + def encode_text(self, text: str) -> str: ... + def shape_text(self, text: str, font_size_pt: int, text_shaping_params): ... + +class PDFFontDescriptor(PDFObject): + type: Incomplete + ascent: Incomplete + descent: Incomplete + cap_height: Incomplete + flags: Incomplete + font_b_box: Incomplete + italic_angle: Incomplete + stem_v: Incomplete + missing_width: Incomplete + font_name: Incomplete + def __init__(self, ascent, descent, cap_height, flags, font_b_box, italic_angle, stem_v, missing_width) -> None: ... + +@dataclass(order=True) +class Glyph: + __slots__ = ("glyph_id", "unicode", "glyph_name", "glyph_width") + glyph_id: int + unicode: tuple[Incomplete, ...] + glyph_name: str + glyph_width: int + def __hash__(self) -> int: ... + +class SubsetMap: + font: TTFFont + def __init__(self, font: TTFFont) -> None: ... + def __len__(self) -> int: ... + def items(self) -> Generator[Incomplete]: ... + def pick(self, unicode: int): ... + def pick_glyph(self, glyph): ... + def get_glyph(self, glyph=None, unicode=None, glyph_name=None, glyph_width=None) -> Glyph: ... + def get_all_glyph_names(self): ... + +CORE_FONTS: dict[str, str] +COURIER_FONT: dict[str, int] +CORE_FONTS_CHARWIDTHS: dict[str, dict[str, int]] diff --git a/stubs/fpdf2/fpdf/fpdf.pyi b/stubs/fpdf2/fpdf/fpdf.pyi new file mode 100644 index 000000000000..0ba3b314e0ee --- /dev/null +++ b/stubs/fpdf2/fpdf/fpdf.pyi @@ -0,0 +1,723 @@ +import datetime +from _typeshed import Incomplete, StrPath, Unused +from collections.abc import Callable, Generator, Iterable, Sequence +from contextlib import _GeneratorContextManager +from io import BytesIO +from pathlib import PurePath +from re import Pattern +from typing import Any, ClassVar, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import deprecated + +from fpdf import ViewerPreferences +from fpdf.outline import OutlineSection +from PIL import Image + +from .annotations import AnnotationDict, PDFEmbeddedFile +from .drawing import DeviceGray, DeviceRGB, DrawingContext, PaintedPath +from .enums import ( + AccessPermission, + Align, + AnnotationFlag, + AnnotationName, + Corner, + EncryptionMethod, + FileAttachmentAnnotationName, + MethodReturnValue, + OutputIntentSubType, + PageLabelStyle, + PageLayout, + PageMode, + PageOrientation, + PathPaintRule, + RenderStyle, + TableBordersLayout, + TableCellFillMode, + TableHeadingsDisplay, + TextDirection, + TextEmphasis, + TextMarkupType, + TextMode as TextMode, + VAlign, + WrapMode as WrapMode, + XPos as XPos, + YPos as YPos, + _Align, +) +from .errors import FPDFException as FPDFException +from .fonts import CoreFont, FontFace, TextStyle, TitleStyle as TitleStyle, TTFFont +from .graphics_state import GraphicsStateMixin +from .html import HTML2FPDF +from .image_datastructures import ( + ImageCache, + ImageInfo as ImageInfo, + RasterImageInfo as RasterImageInfo, + VectorImageInfo as VectorImageInfo, + _TextAlign, +) +from .output import OutputProducer, PDFICCProfile, PDFPage +from .recorder import FPDFRecorder +from .structure_tree import StructureTreeBuilder +from .syntax import DestinationXYZ +from .table import Table +from .transitions import Transition +from .util import Padding, _Unit + +__all__ = [ + "FPDF", + "XPos", + "YPos", + "get_page_format", + "ImageInfo", + "RasterImageInfo", + "VectorImageInfo", + "TextMode", + "TitleStyle", + "PAGE_FORMATS", +] + +_Orientation: TypeAlias = Literal["", "portrait", "p", "P", "landscape", "l", "L"] +_Format: TypeAlias = Literal["", "a3", "A3", "a4", "A4", "a5", "A5", "letter", "Letter", "legal", "Legal"] +_FontStyle: TypeAlias = Literal["", "B", "I", "BI"] +_FontStyles: TypeAlias = Literal[ + "", + "B", + "I", + "U", + "S", + "BU", + "UB", + "BI", + "IB", + "IU", + "UI", + "BS", + "SB", + "IS", + "SI", + "BIU", + "BUI", + "IBU", + "IUB", + "UBI", + "UIB", + "BIS", + "BSI", + "IBS", + "ISB", + "SBI", + "SIB", +] + +FPDF_VERSION: Final[str] +PAGE_FORMATS: Final[dict[_Format, tuple[float, float]]] + +class ToCPlaceholder(NamedTuple): + render_function: Callable[[FPDF, list[OutlineSection]], object] + start_page: int + y: int + page_orientation: str + pages: int = 1 + reset_page_indices: bool = True + +def get_page_format(format: _Format | tuple[float, float], k: float | None = None) -> tuple[float, float]: ... + +class FPDF(GraphicsStateMixin): + MARKDOWN_BOLD_MARKER: ClassVar[str] + MARKDOWN_ITALICS_MARKER: ClassVar[str] + MARKDOWN_STRIKETHROUGH_MARKER: ClassVar[str] + MARKDOWN_UNDERLINE_MARKER: ClassVar[str] + MARKDOWN_ESCAPE_CHARACTER: ClassVar[str] + MARKDOWN_LINK_REGEX: ClassVar[Pattern[str]] + MARKDOWN_LINK_COLOR: ClassVar[Incomplete | None] + MARKDOWN_LINK_UNDERLINE: ClassVar[bool] + + HTML2FPDF_CLASS: ClassVar[type[HTML2FPDF]] + + page: int + pages: dict[int, PDFPage] + fonts: dict[str, CoreFont | TTFFont] + fonts_used_per_page_number: dict[int, set[int]] + links: dict[int, DestinationXYZ] + embedded_files: list[PDFEmbeddedFile] + image_cache: ImageCache + images_used_per_page_number: dict[int, set[int]] + + in_footer: bool + str_alias_nb_pages: str + + xmp_metadata: str | None + page_duration: int + page_transition: Incomplete | None + allow_images_transparency: bool + oversized_images: Incomplete | None + oversized_images_ratio: float + struct_builder: StructureTreeBuilder + toc_placeholder: ToCPlaceholder | None + in_toc_rendering: bool + title: str | None + section_title_styles: dict[int, TextStyle] + + core_fonts: dict[str, str] + core_fonts_encoding: str + font_aliases: dict[str, str] + k: float + + page_background: Incomplete | None + + dw_pt: float + dh_pt: float + def_orientation: Literal["P", "L"] + x: float + y: float + l_margin: float + t_margin: float + c_margin: float + viewer_preferences: ViewerPreferences | None + compress: bool + pdf_version: str + creation_date: datetime.datetime + + buffer: bytearray | None + + # Set during call to _set_orientation(), called from __init__(). + cur_orientation: PageOrientation + w_pt: float + h_pt: float + w: float + h: float + + def __init__( + self, + orientation: _Orientation = "portrait", + unit: _Unit | float = "mm", + format: _Format | tuple[float, float] = "A4", + font_cache_dir: Literal["DEPRECATED"] = "DEPRECATED", + ) -> None: ... + def set_encryption( + self, + owner_password: str, + user_password: str | None = None, + encryption_method: EncryptionMethod | str = ..., + permissions: AccessPermission = ..., + encrypt_metadata: bool = False, + ) -> None: ... + # args and kwargs are passed to HTML2FPDF_CLASS constructor. + def write_html(self, text: str, *args: Any, **kwargs: Any) -> None: ... + @property + def emphasis(self) -> TextEmphasis: ... + @property + def is_ttf_font(self) -> bool: ... + + @property + def page_mode(self) -> PageMode: ... + @page_mode.setter + def page_mode(self, page_mode: PageMode) -> None: ... + + @property + def output_intents(self): ... + def add_output_intent( + self, + subtype: OutputIntentSubType, + output_condition_identifier: str | None = None, + output_condition: str | None = None, + registry_name: str | None = None, + dest_output_profile: PDFICCProfile | None = None, + info: str | None = None, + ) -> None: ... + @property + def epw(self) -> float: ... + @property + def eph(self) -> float: ... + @property + def pages_count(self) -> int: ... + def set_margin(self, margin: float) -> None: ... + def set_margins(self, left: float, top: float, right: float = -1) -> None: ... + def set_left_margin(self, margin: float) -> None: ... + def set_top_margin(self, margin: float) -> None: ... + r_margin: float + def set_right_margin(self, margin: float) -> None: ... + auto_page_break: bool + b_margin: float + page_break_trigger: float + def set_auto_page_break(self, auto: bool, margin: float = 0) -> None: ... + @property + def default_page_dimensions(self) -> tuple[float, float]: ... + zoom_mode: Literal["fullpage", "fullwidth", "real", "default"] | float + page_layout: PageLayout | None + def set_display_mode( + self, + zoom: Literal["fullpage", "fullwidth", "real", "default"] | float, + layout: Literal["single", "continuous", "two", "default"] = "continuous", + ) -> None: ... + def set_text_shaping( + self, + use_shaping_engine: bool = True, + features: dict[str, bool] | None = None, + direction: Literal["ltr", "rtl"] | TextDirection | None = None, + script: str | None = None, + language: str | None = None, + ) -> None: ... + def set_compression(self, compress: bool) -> None: ... + def set_title(self, title: str) -> None: ... + lang: str + def set_lang(self, lang: str) -> None: ... + subject: str + def set_subject(self, subject: str) -> None: ... + author: str + def set_author(self, author: str) -> None: ... + keywords: str + def set_keywords(self, keywords: str) -> None: ... + creator: str + def set_creator(self, creator: str) -> None: ... + producer: str + def set_producer(self, producer: str) -> None: ... + def set_creation_date(self, date: datetime.datetime) -> None: ... + def set_xmp_metadata(self, xmp_metadata: str) -> None: ... + def set_doc_option(self, opt: str, value: str) -> None: ... + def set_image_filter(self, image_filter: str) -> None: ... + def alias_nb_pages(self, alias: str = "{nb}") -> None: ... + def set_page_label( + self, label_style: PageLabelStyle | str | None = None, label_prefix: str | None = None, label_start: int | None = None + ) -> None: ... + def add_page( + self, + orientation: _Orientation = "", + format: _Format | tuple[float, float] = "", + same: bool = False, + duration: float = 0, + transition: Transition | None = None, + label_style: PageLabelStyle | str | None = None, + label_prefix: str | None = None, + label_start: int | None = None, + ) -> None: ... + def header(self) -> None: ... + def footer(self) -> None: ... + def page_no(self) -> int: ... + def get_page_label(self) -> str: ... + def set_draw_color(self, r: int, g: int = -1, b: int = -1) -> None: ... + def set_fill_color(self, r: int, g: int = -1, b: int = -1) -> None: ... + def set_text_color(self, r: int, g: int = -1, b: int = -1) -> None: ... + def get_string_width(self, s: str, normalized: bool = False, markdown: bool = False) -> float: ... + def set_line_width(self, width: float) -> None: ... + def set_page_background(self, background) -> None: ... + def drawing_context(self, debug_stream=None) -> _GeneratorContextManager[DrawingContext]: ... + def new_path( + self, x: float = 0, y: float = 0, paint_rule: PathPaintRule = ..., debug_stream=None + ) -> _GeneratorContextManager[PaintedPath]: ... + def draw_path(self, path: PaintedPath, debug_stream=None) -> None: ... + def set_dash_pattern(self, dash: float = 0, gap: float = 0, phase: float = 0) -> None: ... + def line(self, x1: float, y1: float, x2: float, y2: float) -> None: ... + def polyline( + self, + point_list: list[tuple[float, float]], + fill: bool = False, + polygon: bool = False, + style: RenderStyle | str | None = None, + ) -> None: ... + def polygon( + self, point_list: list[tuple[float, float]], fill: bool = False, style: RenderStyle | str | None = None + ) -> None: ... + def dashed_line(self, x1, y1, x2, y2, dash_length: int = 1, space_length: int = 1) -> None: ... + def rect( + self, + x: float, + y: float, + w: float, + h: float, + style: RenderStyle | str | None = None, + round_corners: tuple[str, ...] | tuple[Corner, ...] | bool = False, + corner_radius: float = 0, + ) -> None: ... + def ellipse(self, x: float, y: float, w: float, h: float, style: RenderStyle | str | None = None) -> None: ... + def circle(self, x: float, y: float, radius: float, style: RenderStyle | str | None = None) -> None: ... + def regular_polygon( + self, + x: float, + y: float, + numSides: int, + polyWidth: float, + rotateDegrees: float = 0, + style: RenderStyle | str | None = None, + ): ... + def star( + self, + x: float, + y: float, + r_in: float, + r_out: float, + corners: int, + rotate_degrees: float = 0, + style: RenderStyle | str | None = None, + ): ... + def arc( + self, + x: float, + y: float, + a: float, + start_angle: float, + end_angle: float, + b: float | None = None, + inclination: float = 0, + clockwise: bool = False, + start_from_center: bool = False, + end_at_center: bool = False, + style: RenderStyle | str | None = None, + ) -> None: ... + def solid_arc( + self, + x: float, + y: float, + a: float, + start_angle: float, + end_angle: float, + b: float | None = None, + inclination: float = 0, + clockwise: bool = False, + style: RenderStyle | str | None = None, + ) -> None: ... + def bezier( + self, + point_list: Sequence[tuple[int, int]], + closed: bool = False, + style: RenderStyle | Literal["D", "F", "DF", "FD"] | None = None, + ) -> None: ... + def use_pattern(self, shading) -> _GeneratorContextManager[None]: ... + def add_font( + self, + family: str | None = None, + style: _FontStyle = "", + fname: str | PurePath | None = None, + uni: bool | Literal["DEPRECATED"] = "DEPRECATED", + ) -> None: ... + def set_font(self, family: str | None = None, style: _FontStyles | TextEmphasis = "", size: int = 0) -> None: ... + def set_font_size(self, size: float) -> None: ... + def set_char_spacing(self, spacing: float) -> None: ... + def set_stretching(self, stretching: float) -> None: ... + def set_fallback_fonts(self, fallback_fonts: Iterable[str], exact_match: bool = True) -> None: ... + def add_link(self, y: float = 0, x: float = 0, page: int = -1, zoom: float | Literal["null"] = "null") -> int: ... + def set_link(self, link, y: float = 0, x: float = 0, page: int = -1, zoom: float | Literal["null"] = "null") -> None: ... + def link( + self, + x: float, + y: float, + w: float, + h: float, + link: str | int, + alt_text: str | None = None, + *, + border_width: int = 0, + **kwargs, # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def embed_file( + self, + file_path: StrPath | None = None, + bytes: bytes | None = None, + basename: str | None = None, + modification_date: datetime.datetime | None = None, + *, + creation_date: datetime.datetime | None = ..., + desc: str = ..., + compress: bool = ..., + checksum: bool = ..., + ) -> str: ... + def file_attachment_annotation( + self, + file_path: StrPath, + x: float, + y: float, + w: float = 1, + h: float = 1, + name: FileAttachmentAnnotationName | str | None = None, + flags: Iterable[AnnotationFlag | str] = ..., + *, + bytes: bytes | None = ..., + basename: str | None = ..., + creation_date: datetime.datetime | None = ..., + modification_date: datetime.datetime | None = ..., + desc: str = ..., + compress: bool = ..., + checksum: bool = ..., + ) -> AnnotationDict: ... + def text_annotation( + self, + x: float, + y: float, + text: str, + w: float = 1, + h: float = 1, + name: AnnotationName | str | None = None, + *, + flags: tuple[AnnotationFlag, ...] | tuple[str, ...] = ..., + **kwargs, # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def free_text_annotation( + self, + text: str, + x: float | None = None, + y: float | None = None, + w: float | None = None, + h: float | None = None, + *, + flags: tuple[AnnotationFlag, ...] | tuple[str, ...] = ..., + **kwargs, # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def add_action( + self, action, x: float, y: float, w: float, h: float, **kwargs # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def highlight( + self, + text: str, + type: TextMarkupType | str = "Highlight", + color: tuple[float, float, float] = (1, 1, 0), + modification_time: datetime.datetime | None = None, + *, + title: str | None = None, + **kwargs, # accepts AnnotationDict arguments + ) -> _GeneratorContextManager[None]: ... + add_highlight = highlight + def add_text_markup_annotation( + self, + type: str, + text: str, + quad_points: Sequence[int], + color: tuple[float, float, float] = (1, 1, 0), + modification_time: datetime.datetime | None = None, + page: int | None = None, + *, + title: str | None = None, + **kwargs, # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def ink_annotation( + self, + coords: Iterable[Incomplete], + text: str = "", + color: Sequence[float] = (1, 1, 0), + border_width: float = 1, + *, + title: str | None = None, + **kwargs, # accepts AnnotationDict arguments + ) -> AnnotationDict: ... + def text(self, x: float, y: float, text: str = "") -> None: ... + def rotate(self, angle: float, x: float | None = None, y: float | None = None) -> None: ... + def rotation(self, angle: float, x: float | None = None, y: float | None = None) -> _GeneratorContextManager[None]: ... + def skew( + self, ax: float = 0, ay: float = 0, x: float | None = None, y: float | None = None + ) -> _GeneratorContextManager[None]: ... + def mirror(self, origin, angle) -> Generator[None]: ... + def local_context( + self, + *, + font_family=None, + font_style=None, + font_size_pt=None, + line_width=None, + draw_color=None, + fill_color=None, + text_color=None, + dash_pattern=None, + font_size=..., # semi-deprecated, prefer font_size_pt + char_vpos=..., + char_spacing=..., + current_font=..., + denom_lift=..., + denom_scale=..., + font_stretching=..., + nom_lift=..., + nom_scale=..., + sub_lift=..., + sub_scale=..., + sup_lift=..., + sup_scale=..., + text_mode=..., + text_shaping=..., + underline=..., + paint_rule=..., + allow_transparency=..., + auto_close=..., + intersection_rule=..., + fill_opacity=..., + stroke_color=..., + stroke_opacity=..., + blend_mode=..., + stroke_width=..., + stroke_cap_style=..., + stroke_join_style=..., + stroke_miter_limit=..., + stroke_dash_pattern=..., + stroke_dash_phase=..., + ) -> _GeneratorContextManager[None]: ... + @property + def accept_page_break(self) -> bool: ... + def cell( + self, + w: float | None = None, + h: float | None = None, + text: str = "", + border: bool | Literal[0, 1] | str = 0, + ln: int | Literal["DEPRECATED"] = "DEPRECATED", + align: str | Align = ..., + fill: bool = False, + link: str | int = "", + center: bool = False, + markdown: bool = False, + new_x: XPos | str = ..., + new_y: YPos | str = ..., + ) -> bool: ... + def get_fallback_font(self, char: str, style: str = "") -> str | None: ... + def will_page_break(self, height: float) -> bool: ... + def multi_cell( + self, + w: float, + h: float | None = None, + text: str = "", + border: bool | Literal[0, 1] | str = 0, + align: str | Align = ..., + fill: bool = False, + split_only: bool = False, + link: str | int = "", + ln: int | Literal["DEPRECATED"] = "DEPRECATED", + max_line_height: float | None = None, + markdown: bool = False, + print_sh: bool = False, + new_x: XPos | str = ..., + new_y: YPos | str = ..., + wrapmode: WrapMode = ..., + dry_run: bool = False, + output: MethodReturnValue | str | int = ..., + center: bool = False, + padding: int = 0, + ): ... + def write( + self, h: float | None = None, text: str = "", link: str | int = "", print_sh: bool = False, wrapmode: WrapMode = ... + ) -> bool: ... + def text_columns( + self, + text: str | None = None, + img: str | None = None, + img_fill_width: bool = False, + ncols: int = 1, + gutter: float = 10, + balance: bool = False, + text_align: str | _TextAlign | tuple[_TextAlign | str, ...] = "LEFT", + line_height: float = 1, + l_margin: float | None = None, + r_margin: float | None = None, + print_sh: bool = False, + wrapmode: WrapMode = ..., + skip_leading_spaces: bool = False, + ): ... + def image( + self, + name: str | Image.Image | BytesIO | StrPath, + x: float | Align | None = None, + y: float | None = None, + w: float = 0, + h: float = 0, + type: str = "", + link: str | int = "", + title: str | None = None, + alt_text: str | None = None, + dims: tuple[float, float] | None = None, + keep_aspect_ratio: bool = False, + ) -> RasterImageInfo | VectorImageInfo: ... + def x_by_align(self, x: _Align, w: int, h: int, img_info: ImageInfo, keep_aspect_ratio: bool) -> int: ... + @deprecated("Deprecated since 2.7.7; use fpdf.image_parsing.preload_image() instead") + def preload_image( + self, name: str | Image.Image | BytesIO, dims: tuple[float, float] | None = None + ) -> tuple[str, Any, ImageInfo]: ... + def ln(self, h: float | None = None) -> None: ... + def get_x(self) -> float: ... + def set_x(self, x: float) -> None: ... + def get_y(self) -> float: ... + def set_y(self, y: float) -> None: ... + def set_xy(self, x: float, y: float) -> None: ... + def normalize_text(self, text: str) -> str: ... + def sign_pkcs12( + self, + pkcs_filepath: str, + password: bytes | None = None, + hashalgo: str = "sha256", + contact_info: str | None = None, + location: str | None = None, + signing_time: datetime.datetime | None = None, + reason: str | None = None, + flags: tuple[AnnotationFlag, ...] = ..., + ) -> None: ... + def sign( + self, + key, + cert, + extra_certs: Sequence[Incomplete] = (), + hashalgo: str = "sha256", + contact_info: str | None = None, + location: str | None = None, + signing_time: datetime.datetime | None = None, + reason: str | None = None, + flags: tuple[AnnotationFlag, ...] = ..., + ) -> None: ... + def file_id(self) -> str: ... + def interleaved2of5(self, text, x: float, y: float, w: float = 1, h: float = 10) -> None: ... + def code39(self, text, x: float, y: float, w: float = 1.5, h: float = 5) -> None: ... + def rect_clip(self, x: float, y: float, w: float, h: float) -> _GeneratorContextManager[None]: ... + def elliptic_clip(self, x: float, y: float, w: float, h: float) -> _GeneratorContextManager[None]: ... + def round_clip(self, x: float, y: float, r: float) -> _GeneratorContextManager[None]: ... + def unbreakable(self) -> _GeneratorContextManager[FPDFRecorder]: ... + def offset_rendering(self) -> _GeneratorContextManager[FPDFRecorder]: ... + def insert_toc_placeholder( + self, + render_toc_function: Callable[[FPDF, list[OutlineSection]], object], + pages: int = 1, + allow_extra_pages: bool = False, + reset_page_indices: bool = True, + ) -> None: ... + def set_section_title_styles( + self, + level0: TextStyle, + level1: TextStyle | None = None, + level2: TextStyle | None = None, + level3: TextStyle | None = None, + level4: TextStyle | None = None, + level5: TextStyle | None = None, + level6: TextStyle | None = None, + ) -> None: ... + def start_section(self, name: str, level: int = 0, strict: bool = True) -> None: ... + def use_text_style(self, text_style: TextStyle) -> _GeneratorContextManager[None]: ... + def use_font_face(self, font_face: FontFace) -> _GeneratorContextManager[None]: ... + def table( + self, + rows: Iterable[Incomplete] = (), + *, + # Keep in sync with `fpdf.table.Table`: + align: str | _TextAlign = "CENTER", + v_align: str | VAlign = "MIDDLE", + borders_layout: str | TableBordersLayout = ..., + cell_fill_color: int | tuple[Incomplete, ...] | DeviceGray | DeviceRGB | None = None, + cell_fill_mode: str | TableCellFillMode = ..., + col_widths: int | tuple[int, ...] | None = None, + first_row_as_headings: bool = True, + gutter_height: float = 0, + gutter_width: float = 0, + headings_style: FontFace = ..., + line_height: int | None = None, + markdown: bool = False, + text_align: str | _TextAlign | tuple[str | _TextAlign, ...] = "JUSTIFY", + width: int | None = None, + wrapmode: WrapMode = ..., + padding: float | Padding | None = None, + outer_border_width: float | None = None, + num_heading_rows: int = 1, + repeat_headings: TableHeadingsDisplay | int = 1, + ) -> _GeneratorContextManager[Table]: ... + + @overload + def output( # type: ignore[overload-overlap] + self, + name: Literal[""] | None = "", + dest: Unused = "", + linearize: bool = False, + output_producer_class: Callable[[FPDF], OutputProducer] = ..., + ) -> bytearray: ... + @overload + def output( + self, name: str, dest: Unused = "", linearize: bool = False, output_producer_class: Callable[[FPDF], OutputProducer] = ... + ) -> None: ... diff --git a/stubs/fpdf2/fpdf/graphics_state.pyi b/stubs/fpdf2/fpdf/graphics_state.pyi new file mode 100644 index 000000000000..39972466774e --- /dev/null +++ b/stubs/fpdf2/fpdf/graphics_state.pyi @@ -0,0 +1,155 @@ +from typing import Any, ClassVar, Final, Literal, TypedDict, type_check_only + +from .drawing import DeviceGray, DeviceRGB +from .enums import TextMode +from .fonts import FontFace + +@type_check_only +class _TextShaping(TypedDict): + use_shaping_engine: bool + features: dict[str, bool] + direction: Literal["ltr", "rtl"] + script: str | None + language: str | None + fragment_direction: Literal["L", "R"] | None + paragraph_direction: Literal["L", "R"] | None + +class GraphicsStateMixin: + DEFAULT_DRAW_COLOR: ClassVar[DeviceGray] + DEFAULT_FILL_COLOR: ClassVar[DeviceGray] + DEFAULT_TEXT_COLOR: ClassVar[DeviceGray] + def __init__(self, *args, **kwargs) -> None: ... + + @property + def draw_color(self) -> DeviceGray | DeviceRGB: ... + @draw_color.setter + def draw_color(self, v: DeviceGray | DeviceRGB) -> None: ... + + @property + def fill_color(self) -> DeviceGray | DeviceRGB: ... + @fill_color.setter + def fill_color(self, v: DeviceGray | DeviceRGB) -> None: ... + + @property + def text_color(self) -> DeviceGray | DeviceRGB: ... + @text_color.setter + def text_color(self, v: DeviceGray | DeviceRGB) -> None: ... + + @property + def underline(self) -> bool: ... + @underline.setter + def underline(self, v: bool) -> None: ... + + @property + def strikethrough(self) -> bool: ... + @strikethrough.setter + def strikethrough(self, v: bool) -> None: ... + + @property + def font_style(self) -> str: ... + @font_style.setter + def font_style(self, v: str) -> None: ... + + @property + def font_stretching(self) -> float: ... + @font_stretching.setter + def font_stretching(self, v: float) -> None: ... + + @property + def char_spacing(self) -> float: ... + @char_spacing.setter + def char_spacing(self, v: float) -> None: ... + + @property + def font_family(self) -> str: ... + @font_family.setter + def font_family(self, v: str) -> None: ... + + @property + def font_size_pt(self) -> float: ... + @font_size_pt.setter + def font_size_pt(self, v: float) -> None: ... + + @property + def font_size(self) -> float: ... + @font_size.setter + def font_size(self, v: float) -> None: ... + + @property + def current_font(self) -> dict[str, Any]: ... + @current_font.setter + def current_font(self, v: dict[str, Any]) -> None: ... + + @property + def current_font_is_set_on_page(self) -> bool: ... + @current_font_is_set_on_page.setter + def current_font_is_set_on_page(self, v: bool) -> None: ... + + @property + def dash_pattern(self) -> dict[str, float]: ... + @dash_pattern.setter + def dash_pattern(self, v: dict[str, float]) -> None: ... + + @property + def line_width(self) -> float: ... + @line_width.setter + def line_width(self, v: float) -> None: ... + + @property + def text_mode(self) -> TextMode: ... + @text_mode.setter + def text_mode(self, v: int | str) -> None: ... + + @property + def char_vpos(self): ... + @char_vpos.setter + def char_vpos(self, v) -> None: ... + + @property + def sub_scale(self): ... + @sub_scale.setter + def sub_scale(self, v) -> None: ... + + @property + def sup_scale(self): ... + @sup_scale.setter + def sup_scale(self, v) -> None: ... + + @property + def nom_scale(self): ... + @nom_scale.setter + def nom_scale(self, v) -> None: ... + + @property + def denom_scale(self): ... + @denom_scale.setter + def denom_scale(self, v) -> None: ... + + @property + def sub_lift(self): ... + @sub_lift.setter + def sub_lift(self, v) -> None: ... + + @property + def sup_lift(self): ... + @sup_lift.setter + def sup_lift(self, v) -> None: ... + + @property + def nom_lift(self): ... + @nom_lift.setter + def nom_lift(self, v) -> None: ... + + @property + def denom_lift(self): ... + @denom_lift.setter + def denom_lift(self, v) -> None: ... + + @property + def text_shaping(self) -> _TextShaping | None: ... + @text_shaping.setter + def text_shaping(self, v: _TextShaping | None) -> None: ... + + def font_face(self) -> FontFace: ... + +__pdoc__: Final[dict[str, bool]] diff --git a/stubs/fpdf2/fpdf/html.pyi b/stubs/fpdf2/fpdf/html.pyi new file mode 100644 index 000000000000..a838697b0d69 --- /dev/null +++ b/stubs/fpdf2/fpdf/html.pyi @@ -0,0 +1,96 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Iterable, Mapping +from html.parser import HTMLParser +from logging import Logger +from typing import ClassVar, Final, Literal, TypeAlias + +from fpdf import FPDF + +from .enums import Align, TextEmphasis +from .fonts import FontFace +from .table import Row, Table + +__author__: Final[str] +__copyright__: Final[str] + +_OLType: TypeAlias = Literal["1", "a", "A", "I", "i"] + +LOGGER: Logger +MESSAGE_WAITING_WIN1252: Final = "\x95" +BULLET_UNICODE: Final = "•" +DEGREE_SIGN_WIN1252: Final = "\xb0" +RING_OPERATOR_UNICODE: Final = "∘" +HEADING_TAGS: Final[tuple[str, ...]] +DEFAULT_TAG_STYLES: Final[dict[str, FontFace]] +INLINE_TAGS: Final[tuple[str, ...]] +BLOCK_TAGS: Final[tuple[str, ...]] + +COLOR_DICT: Final[dict[str, str]] + +def color_as_decimal(color: str | None = "#000000") -> tuple[int, int, int] | None: ... +def parse_css_style(style_attr: str) -> dict[str, str]: ... + +class HTML2FPDF(HTMLParser): + HTML_UNCLOSED_TAGS: ClassVar[tuple[str, ...]] + TABLE_LINE_HEIGHT: ClassVar[float] + + pdf: FPDF + image_map: Callable[[str], str] + ul_bullet_char: str + li_prefix_color: tuple[int, int, int] + warn_on_tags_not_matching: bool + + font_family: str + font_size_pt: float + font_emphasis: TextEmphasis + font_color: tuple[int, int, int] + + style_stack: list[FontFace] + h: float + follows_trailing_space: bool + follows_heading: bool + href: str + align: float | Align | None + indent: int + line_height_stack: list[Incomplete] + ol_type: dict[int, _OLType] + bullet: list[Incomplete] + heading_level: Incomplete | None + render_title_tag: bool + table_line_separators: bool + table: Table | None + table_row: Row | None + tr: dict[str, str] | None + td_th: dict[str, str] | None + tag_indents: dict[str, int] + tag_styles: dict[str, FontFace] + + def __init__( + self, + pdf: FPDF, + image_map: Callable[[str], str] | None = None, + li_tag_indent: int | None = None, + dd_tag_indent: int | None = None, + table_line_separators: bool = False, + ul_bullet_char: str = "disc", + li_prefix_color: tuple[int, int, int] = (190, 0, 0), + heading_sizes: SupportsKeysAndGetItem[str, int] | Iterable[tuple[str, int]] | None = None, + pre_code_font: str | None = None, + warn_on_tags_not_matching: bool = True, + tag_indents: dict[str, int] | None = None, + tag_styles: Mapping[str, FontFace] | None = None, + font_family: str = "times", + render_title_tag: bool = False, + ) -> None: ... + def handle_data(self, data) -> None: ... + def handle_starttag(self, tag, attrs) -> None: ... + def handle_endtag(self, tag) -> None: ... + def put_link(self, text) -> None: ... + def render_toc(self, pdf, outline) -> None: ... + def error(self, message: str) -> None: ... + +def ul_prefix(ul_type: str, is_ttf_font: bool | None) -> str: ... +def ol_prefix(ol_type: _OLType, index: int) -> str: ... + +class HTMLMixin: + def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/fpdf2/fpdf/image_datastructures.pyi b/stubs/fpdf2/fpdf/image_datastructures.pyi new file mode 100644 index 000000000000..a45a50ee8e7b --- /dev/null +++ b/stubs/fpdf2/fpdf/image_datastructures.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from dataclasses import dataclass +from typing import Any, Literal, TypeAlias + +from fpdf.enums import Align + +from .image_parsing import _ImageFilter + +_AlignLiteral: TypeAlias = Literal[ + "", + "CENTER", + "X_CENTER", + "LEFT", + "RIGHT", + "JUSTIFY", + "center", + "x_center", + "left", + "right", + "justify", + "C", + "X", + "L", + "R", + "J", + "c", + "x", + "l", + "r", + "j", +] +_TextAlign: TypeAlias = Align | _AlignLiteral # noqa: Y047 + +class ImageInfo(dict[str, Any]): + @property + def width(self) -> int: ... + @property + def height(self) -> int: ... + @property + def rendered_width(self) -> int: ... + @property + def rendered_height(self) -> int: ... + def scale_inside_box(self, x: float, y: float, w: float, h: float) -> tuple[float, float, float, float]: ... + +class RasterImageInfo(ImageInfo): + def size_in_document_units(self, w: float, h: float, scale=1) -> tuple[float, float]: ... + +class VectorImageInfo(ImageInfo): ... + +@dataclass +class ImageCache: + images: dict[str, dict[Incomplete, Incomplete]] = ... + icc_profiles: dict[bytes, int] = ... + image_filter: _ImageFilter = "AUTO" + + def reset_usages(self) -> None: ... diff --git a/stubs/fpdf2/fpdf/image_parsing.pyi b/stubs/fpdf2/fpdf/image_parsing.pyi new file mode 100644 index 000000000000..0d131c1338b2 --- /dev/null +++ b/stubs/fpdf2/fpdf/image_parsing.pyi @@ -0,0 +1,58 @@ +from collections.abc import Iterable +from dataclasses import dataclass +from io import BytesIO +from logging import Logger +from types import TracebackType +from typing import Any, Final, Literal, TypeAlias + +from PIL import Image + +from .image_datastructures import ImageCache, ImageInfo, VectorImageInfo +from .svg import SVGObject + +_ImageFilter: TypeAlias = Literal["AUTO", "FlateDecode", "DCTDecode", "JPXDecode", "LZWDecode"] + +RESAMPLE: Image.Resampling + +@dataclass +class ImageSettings: + compression_level: int = -1 + +LOGGER: Logger +SUPPORTED_IMAGE_FILTERS: tuple[_ImageFilter, ...] +SETTINGS: ImageSettings + +TIFFBitRevTable: list[int] + +LZW_CLEAR_TABLE_MARKER: Final = 256 +LZW_EOD_MARKER: Final = 257 +LZW_INITIAL_BITS_PER_CODE: Final = 9 +LZW_MAX_BITS_PER_CODE: Final = 12 + +def preload_image( + image_cache: ImageCache, name: str | BytesIO | Image.Image, dims: tuple[float, float] | None = None +) -> tuple[str, BytesIO | Image.Image | None, ImageInfo]: ... +def load_image(filename): ... +def is_iccp_valid(iccp, filename) -> bool: ... +def get_svg_info(filename: str, img: BytesIO, image_cache: ImageCache) -> tuple[str, SVGObject, VectorImageInfo]: ... + +# Returned dict could be typed as a TypedDict. +def get_img_info( + filename, img: BytesIO | Image.Image | None = None, image_filter: _ImageFilter = "AUTO", dims=None +) -> dict[str, Any]: ... + +class temp_attr: + obj: Any + field: str + value: Any + exists: bool # defined after __enter__ is called + def __init__(self, obj: Any, field: str, value: Any) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + ) -> None: ... + +def ccitt_payload_location_from_pil(img: Image.Image) -> tuple[int, int]: ... +def transcode_monochrome(img: Image.Image): ... +def pack_codes_into_bytes(codes: Iterable[int]) -> bytes: ... +def clear_table() -> tuple[dict[bytes, int], int, int, int]: ... diff --git a/stubs/fpdf2/fpdf/line_break.pyi b/stubs/fpdf2/fpdf/line_break.pyi new file mode 100644 index 000000000000..3ba2ee5a57f9 --- /dev/null +++ b/stubs/fpdf2/fpdf/line_break.pyi @@ -0,0 +1,172 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import Final, NamedTuple +from uuid import UUID + +from .enums import Align, TextDirection, WrapMode + +SOFT_HYPHEN: Final[str] +HYPHEN: Final[str] +SPACE: Final[str] +BREAKING_SPACE_SYMBOLS: Final[list[str]] +BREAKING_SPACE_SYMBOLS_STR: Final[str] +NBSP: Final[str] +NEWLINE: Final[str] +FORM_FEED: Final[str] + +class Fragment: + characters: list[str] + graphics_state: dict[str, Incomplete] + k: float + url: str | None + def __init__( + self, characters: list[str] | str, graphics_state: dict[str, Incomplete], k: float, link: str | int | None = None + ) -> None: ... + + @property + def font(self): ... + @font.setter + def font(self, v) -> None: ... + + @property + def is_ttf_font(self): ... + @property + def font_style(self): ... + @property + def font_family(self): ... + @property + def font_size_pt(self): ... + @property + def font_size(self): ... + @property + def font_stretching(self): ... + @property + def char_spacing(self): ... + @property + def text_mode(self): ... + @property + def underline(self) -> bool: ... + @property + def strikethrough(self) -> bool: ... + @property + def draw_color(self): ... + @property + def fill_color(self): ... + @property + def text_color(self): ... + @property + def line_width(self): ... + @property + def char_vpos(self): ... + @property + def lift(self): ... + @property + def string(self) -> str: ... + @property + def width(self) -> float: ... + @property + def text_shaping_parameters(self): ... + @property + def paragraph_direction(self) -> TextDirection: ... + @property + def fragment_direction(self) -> TextDirection: ... + def trim(self, index: int) -> None: ... + def __eq__(self, other: Fragment) -> bool: ... # type: ignore[override] + def get_width(self, start: int = 0, end: int | None = None, chars: str | None = None, initial_cs: bool = True) -> float: ... + def has_same_style(self, other: Fragment) -> bool: ... + def get_character_width(self, character: str, print_sh: bool = False, initial_cs: bool = True): ... + def render_pdf_text(self, frag_ws, current_ws, word_spacing, adjust_x, adjust_y, h): ... + def render_pdf_text_ttf(self, frag_ws, word_spacing): ... + def render_with_text_shaping(self, pos_x: float, pos_y: float, h: float, word_spacing: float) -> str: ... + def render_pdf_text_core(self, frag_ws, current_ws): ... + +class TotalPagesSubstitutionFragment(Fragment): + uuid: UUID + def get_placeholder_string(self) -> str: ... + def render_text_substitution(self, replacement_text: str) -> str: ... + +class TextLine(NamedTuple): + fragments: tuple[Fragment, ...] + text_width: float + number_of_spaces: int + align: Align + height: float + max_width: float + trailing_nl: bool = False + trailing_form_feed: bool = False + indent: float = 0 + def get_ordered_fragments(self) -> tuple[Fragment, ...]: ... + +class SpaceHint(NamedTuple): + original_fragment_index: int + original_character_index: int + current_line_fragment_index: int + current_line_character_index: int + line_width: float + number_of_spaces: int + +class HyphenHint(NamedTuple): + original_fragment_index: int + original_character_index: int + current_line_fragment_index: int + current_line_character_index: int + line_width: float + number_of_spaces: int + curchar: str + curchar_width: float + graphics_state: dict[str, Incomplete] + k: float + +class CurrentLine: + max_width: float + print_sh: bool + indent: float + fragments: list[Fragment] + height: int + number_of_spaces: int + space_break_hint: Incomplete + hyphen_break_hint: Incomplete + def __init__(self, max_width: float, print_sh: bool = False, indent: float = 0) -> None: ... + @property + def width(self) -> float: ... + def add_character( + self, + character: str, + character_width: float, + original_fragment: Fragment, + original_fragment_index: int, + original_character_index: int, + height: float, + url: str | None = None, + ) -> None: ... + def trim_trailing_spaces(self) -> None: ... + def manual_break(self, align: Align, trailing_nl: bool = False, trailing_form_feed: bool = False) -> TextLine: ... + def automatic_break_possible(self) -> bool: ... + def automatic_break(self, align: Align) -> tuple[Incomplete, Incomplete, TextLine]: ... + +class MultiLineBreak: + fragments: Sequence[Fragment] + get_width: float + margins: Sequence[float] + align: Align + print_sh: bool + wrapmode: WrapMode + line_height: float + skip_leading_spaces: bool + fragment_index: int + character_index: int + idx_last_forced_break: int | None + first_line_indent: float + def __init__( + self, + fragments: Sequence[Fragment], + max_width: float | Callable[[float], float], + margins: Sequence[float], + align: Align = ..., + print_sh: bool = False, + wrapmode: WrapMode = ..., + line_height: float = 1.0, + skip_leading_spaces: bool = False, + first_line_indent: float = 0, + ) -> None: ... + def get_line(self) -> TextLine: ... diff --git a/stubs/fpdf2/fpdf/linearization.pyi b/stubs/fpdf2/fpdf/linearization.pyi new file mode 100644 index 000000000000..479a6b8d547c --- /dev/null +++ b/stubs/fpdf2/fpdf/linearization.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from typing import Final + +from .encryption import StandardSecurityHandler +from .output import ContentWithoutID, OutputProducer +from .syntax import PDFContentStream, PDFObject + +HINT_STREAM_OFFSET_LENGTH_PLACEHOLDER: Final[str] +FIRST_PAGE_END_OFFSET_PLACEHOLDER: Final[str] +MAIN_XREF_1ST_ENTRY_OFFSET_PLACEHOLDER: Final[str] +FILE_LENGTH_PLACEHOLDER: Final[str] + +class PDFLinearization(PDFObject): + linearized: str + n: int + h: str + o: Incomplete | None + e: str + t: str + l: str + def __init__(self, pages_count: int) -> None: ... + +class PDFXrefAndTrailer(ContentWithoutID): + PREV_MAIN_XREF_START_PLACEHOLDER: str + output_builder: Incomplete + count: int + start_obj_id: int + catalog_obj: Incomplete | None + info_obj: Incomplete | None + first_xref: Incomplete | None + main_xref: Incomplete | None + startxref: Incomplete | None + def __init__(self, output_builder) -> None: ... + @property + def is_first_xref(self) -> bool: ... + @property + def is_main_xref(self) -> bool: ... + def serialize(self, _security_handler: StandardSecurityHandler | None = None) -> str: ... + +class PDFHintStream(PDFContentStream): + s: Incomplete | None + t: Incomplete | None + o: Incomplete | None + a: Incomplete | None + e: Incomplete | None + v: Incomplete | None + i: Incomplete | None + c: Incomplete | None + l: Incomplete | None + r: Incomplete | None + b: Incomplete | None + +class LinearizedOutputProducer(OutputProducer): + def bufferize(self) -> bytearray: ... diff --git a/stubs/fpdf2/fpdf/outline.pyi b/stubs/fpdf2/fpdf/outline.pyi new file mode 100644 index 000000000000..4a26d8ee0982 --- /dev/null +++ b/stubs/fpdf2/fpdf/outline.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from dataclasses import dataclass + +from .fonts import TextStyle +from .fpdf import FPDF +from .structure_tree import StructElem +from .syntax import Destination, PDFObject, PDFString + +@dataclass +class OutlineSection: + __slots__ = ("name", "level", "page_number", "dest", "struct_elem") + name: str + level: int + page_number: int + dest: Destination + struct_elem: StructElem | None = None + +class OutlineItemDictionary(PDFObject): + __slots__ = ("_id", "title", "parent", "prev", "next", "first", "last", "count", "dest", "struct_elem") + title: PDFString + parent: Incomplete | None + prev: Incomplete | None + next: Incomplete | None + first: Incomplete | None + last: Incomplete | None + count: int + dest: Destination | None + struct_elem: StructElem | None + def __init__(self, title: str, dest: Destination | None = None, struct_elem: StructElem | None = None) -> None: ... + +class OutlineDictionary(PDFObject): + __slots__ = ("_id", "type", "first", "last", "count") + type: str + first: Incomplete | None + last: Incomplete | None + count: int + def __init__(self) -> None: ... + +def build_outline_objs( + sections: Iterable[Incomplete], +) -> Generator[Incomplete, None, list[OutlineDictionary | OutlineItemDictionary]]: ... + +class TableOfContents: + text_style: TextStyle + use_section_title_styles: bool + level_indent: float + line_spacing: float + ignore_pages_before_toc: bool + + def __init__( + self, + text_style: TextStyle | None = None, + use_section_title_styles: bool = False, + level_indent: float = 7.5, + line_spacing: float = 1.5, + ignore_pages_before_toc: bool = True, + ) -> None: ... + def get_text_style(self, pdf: FPDF, item: OutlineSection) -> TextStyle: ... + def render_toc_item(self, pdf: FPDF, item: OutlineSection) -> None: ... + def render_toc(self, pdf: FPDF, outline: Iterable[OutlineSection]) -> None: ... diff --git a/stubs/fpdf2/fpdf/output.pyi b/stubs/fpdf2/fpdf/output.pyi new file mode 100644 index 000000000000..86c1b56c855e --- /dev/null +++ b/stubs/fpdf2/fpdf/output.pyi @@ -0,0 +1,271 @@ +from _typeshed import Incomplete, Unused +from collections import defaultdict +from logging import Logger +from typing import Final + +from .annotations import AnnotationDict +from .encryption import StandardSecurityHandler +from .enums import OutputIntentSubType, PageLabelStyle, PDFResourceType +from .fpdf import FPDF +from .image_datastructures import RasterImageInfo +from .line_break import TotalPagesSubstitutionFragment +from .syntax import Name, PDFArray, PDFContentStream, PDFObject, PDFString + +LOGGER: Logger +ZOOM_CONFIGS: Final[dict[str, tuple[str, ...]]] + +class ContentWithoutID: + def serialize(self, _security_handler: StandardSecurityHandler | None = None) -> str | None: ... + +class PDFHeader(ContentWithoutID): + pdf_version: str + def __init__(self, pdf_version: str) -> None: ... + def serialize(self, _security_handler: StandardSecurityHandler | None = None) -> str: ... + +class PDFFont(PDFObject): + type: Name + subtype: Name + base_font: Name + encoding: Name | None + d_w: Incomplete | None + w: Incomplete | None + descendant_fonts: Incomplete | None + to_unicode: Incomplete | None + c_i_d_system_info: Incomplete | None + font_descriptor: Incomplete | None + c_i_d_to_g_i_d_map: Incomplete | None + def __init__(self, subtype: str, base_font: str, encoding: str | None = None, d_w=None, w=None) -> None: ... + +class CIDSystemInfo(PDFObject): + registry: PDFString + ordering: PDFString + supplement: int + +class PDFInfo(PDFObject): + title: str | None + subject: str | None + author: str | None + keywords: str | None + creator: str | None + producer: str | None + creation_date: Incomplete + def __init__( + self, + title: str | None, + subject: str | None, + author: str | None, + keywords: str | None, + creator: str | None, + producer: str | None, + creation_date, + ) -> None: ... + +class AcroForm: + fields: Incomplete + sig_flags: Incomplete + def __init__(self, fields, sig_flags) -> None: ... + def serialize(self) -> str: ... + +class PDFCatalog(PDFObject): + type: Name + lang: str | None + page_layout: Incomplete | None + page_mode: Incomplete | None + viewer_preferences: Incomplete | None + pages: Incomplete | None + acro_form: Incomplete | None + open_action: Incomplete | None + mark_info: Incomplete | None + metadata: Incomplete | None + names: Incomplete | None + outlines: Incomplete | None + output_intents: Incomplete | None + struct_tree_root: Incomplete | None + def __init__(self, lang: str | None = None, page_layout=None, page_mode=None, viewer_preferences=None) -> None: ... + +class PDFResources(PDFObject): + proc_set: Incomplete + font: Incomplete + x_object: Incomplete + ext_g_state: Incomplete + shading: Incomplete + pattern: Incomplete + def __init__(self, proc_set, font, x_object, ext_g_state, shading, pattern) -> None: ... + +class PDFFontStream(PDFContentStream): + length1: int + def __init__(self, contents: bytes) -> None: ... + +class PDFXmpMetadata(PDFContentStream): + type: Name + subtype: Name + def __init__(self, contents: bytes) -> None: ... + +class PDFXObject(PDFContentStream): + __slots__ = ( + "_id", + "_contents", + "filter", + "length", + "type", + "subtype", + "width", + "height", + "color_space", + "bits_per_component", + "decode", + "decode_parms", + "s_mask", + ) + type: Name + subtype: Name + width: Incomplete + height: Incomplete + color_space: Incomplete + bits_per_component: Incomplete + filter: Name + decode: Incomplete | None + decode_parms: Incomplete | None + s_mask: Incomplete | None + def __init__( + self, + contents, + subtype: str, + width, + height, + color_space, + bits_per_component, + img_filter: str | None = None, + decode=None, + decode_parms=None, + ) -> None: ... + +class PDFICCProfile(PDFContentStream): + __slots__ = ("_id", "_contents", "filter", "length", "n", "alternate") + n: Incomplete + alternate: Name + def __init__(self, contents: bytes, n, alternate: str) -> None: ... + +class PDFPageLabel: + __slots__ = ("_style", "_prefix", "st") + st: int + def __init__(self, label_style: PageLabelStyle, label_prefix: str, label_start: int) -> None: ... + @property + def s(self) -> Name: ... + @property + def p(self) -> PDFString: ... + def serialize(self) -> dict[str, str]: ... + def get_style(self) -> PageLabelStyle: ... + def get_prefix(self) -> str: ... + def get_start(self) -> int: ... + +class PDFPage(PDFObject): + __slots__ = ( + "_id", + "type", + "contents", + "dur", + "trans", + "annots", + "group", + "media_box", + "struct_parents", + "resources", + "parent", + "_index", + "_width_pt", + "_height_pt", + "_page_label", + "_text_substitution_fragments", + ) + type: Name + contents: Incomplete + dur: Incomplete | None + trans: Incomplete + annots: PDFArray[AnnotationDict] + group: Incomplete | None + media_box: Incomplete | None + struct_parents: Incomplete | None + resources: Incomplete | None + parent: Incomplete | None + def __init__(self, duration: Incomplete | None, transition, contents, index) -> None: ... + def index(self) -> int: ... + def set_index(self, i: int) -> None: ... + def dimensions(self) -> tuple[float | None, float | None]: ... + def set_dimensions(self, width_pt: float | None, height_pt: float | None) -> None: ... + def set_page_label(self, previous_page_label: PDFPageLabel, page_label: PDFPageLabel) -> None: ... + def get_page_label(self) -> PDFPageLabel: ... + def get_label(self) -> str: ... + def get_text_substitutions(self) -> list[TotalPagesSubstitutionFragment]: ... + def add_text_substitution(self, fragment: TotalPagesSubstitutionFragment) -> None: ... + +class PDFPagesRoot(PDFObject): + type: Name + count: Incomplete + media_box: Incomplete + kids: Incomplete | None + def __init__(self, count, media_box) -> None: ... + +class PDFExtGState(PDFObject): + def __init__(self, dict_as_str) -> None: ... + def serialize(self, obj_dict: Unused = None, _security_handler: StandardSecurityHandler | None = None) -> str: ... + +class PDFXrefAndTrailer(ContentWithoutID): + output_builder: Incomplete + count: int + catalog_obj: Incomplete | None + info_obj: Incomplete | None + def __init__(self, output_builder) -> None: ... + def serialize(self, _security_handler: StandardSecurityHandler | None = None) -> str: ... + +class OutputIntentDictionary: + __slots__ = ("type", "s", "output_condition_identifier", "output_condition", "registry_name", "dest_output_profile", "info") + type: Name + s: Name + output_condition_identifier: PDFString | None + output_condition: PDFString | None + registry_name: PDFString | None + dest_output_profile: Incomplete | None + info: PDFString | None + + def __init__( + self, + subtype: OutputIntentSubType | str, + output_condition_identifier: str, + output_condition: str | None = None, + registry_name: str | None = None, + dest_output_profile: PDFICCProfile | None = None, + info: str | None = None, + ) -> None: ... + def serialize(self, _security_handler: StandardSecurityHandler | None = None, _obj_id=None): ... + +class ResourceCatalog: + resources: defaultdict[PDFResourceType, dict[Incomplete, Incomplete]] + resources_per_page: defaultdict[tuple[int, PDFResourceType], set[Incomplete]] + + def add(self, resource_type: PDFResourceType, resource, page_number: int) -> Incomplete | None: ... + def get_items(self, resource_type: PDFResourceType): ... + def get_resources_per_page(self, page_number: int, resource_type: PDFResourceType): ... + def get_used_resources(self, resource_type: PDFResourceType) -> set[Incomplete]: ... + +class OutputProducer: + fpdf: FPDF + pdf_objs: list[Incomplete] + obj_id: int + offsets: dict[Incomplete, Incomplete] + trace_labels_per_obj_id: dict[Incomplete, Incomplete] + sections_size_per_trace_label: defaultdict[Incomplete, int] + buffer: bytearray + def __init__(self, fpdf: FPDF) -> None: ... + def bufferize(self) -> bytearray: ... + +def stream_content_for_raster_image( + info: RasterImageInfo, + x: float, + y: float, + w: float, + h: float, + keep_aspect_ratio: bool = False, + scale: float = 1, + pdf_height_to_flip: float | None = None, +) -> str: ... diff --git a/stubs/fpdf2/fpdf/pattern.pyi b/stubs/fpdf2/fpdf/pattern.pyi new file mode 100644 index 000000000000..6d0d043764c6 --- /dev/null +++ b/stubs/fpdf2/fpdf/pattern.pyi @@ -0,0 +1,104 @@ +from _typeshed import Incomplete +from abc import ABC +from collections.abc import Iterable +from typing import Final, Literal + +from .drawing import DeviceCMYK, DeviceGray, DeviceRGB +from .fpdf import FPDF +from .syntax import Name, PDFObject + +class Pattern(PDFObject): + type: Name + pattern_type: int + def __init__(self, shading: LinearGradient | RadialGradient) -> None: ... + @property + def shading(self) -> str: ... + +class Type2Function(PDFObject): + function_type: Final = 2 + domain: str + c0: str + c1: str + n: int + def __init__(self, color_1, color_2) -> None: ... + +class Type3Function(PDFObject): + function_type: Final = 3 + domain: str + bounds: str + encode: str + n: int + + def __init__(self, functions: Iterable[Incomplete], bounds: Iterable[Incomplete]) -> None: ... + @property + def functions(self) -> str: ... + +class Shading(PDFObject): + shading_type: Literal[2, 3] + background: str | None + color_space: Name + coords: list[int] + function: str + extend: str + def __init__( + self, + shading_type: Literal[2, 3], + background: DeviceRGB | DeviceGray | DeviceCMYK | None, + color_space: str, + coords: list[int], + function: Type2Function | Type3Function, + extend_before: bool, + extend_after: bool, + ) -> None: ... + +class Gradient(ABC): + color_space: str + colors: list[Incomplete] + background: Incomplete | None + extend_before: Incomplete + extend_after: Incomplete + bounds: Incomplete + functions: Incomplete + pattern: Pattern + coords: Incomplete | None + shading_type: int + + def __init__(self, colors, background, extend_before, extend_after, bounds): ... + def get_shading_object(self) -> Shading: ... + def get_pattern(self) -> Pattern: ... + +class LinearGradient(Gradient): + coords: list[str] + shading_type: int + def __init__( + self, + fpdf: FPDF, + from_x: float, + from_y: float, + to_x: float, + to_y: float, + colors: list[Incomplete], + background=None, + extend_before: bool = False, + extend_after: bool = False, + bounds: list[int] | None = None, + ) -> None: ... + +class RadialGradient(Gradient): + coords: list[str] + shading_type: int + def __init__( + self, + fpdf: FPDF, + start_circle_x: float, + start_circle_y: float, + start_circle_radius: float, + end_circle_x: float, + end_circle_y: float, + end_circle_radius: float, + colors: list[Incomplete], + background=None, + extend_before: bool = False, + extend_after: bool = False, + bounds: list[int] | None = None, + ): ... diff --git a/stubs/fpdf2/fpdf/prefs.pyi b/stubs/fpdf2/fpdf/prefs.pyi new file mode 100644 index 000000000000..9d9882f837b2 --- /dev/null +++ b/stubs/fpdf2/fpdf/prefs.pyi @@ -0,0 +1,86 @@ +from typing import Literal + +from .enums import Duplex, PageBoundaries, PageMode, TextDirection + +class ViewerPreferences: + hide_toolbar: bool + hide_menubar: bool + hide_window_u_i: bool + fit_window: bool + center_window: bool + def __init__( + self, + hide_toolbar: bool = False, + hide_menubar: bool = False, + hide_window_u_i: bool = False, + fit_window: bool = False, + center_window: bool = False, + display_doc_title: bool = False, + non_full_screen_page_mode: PageMode | str | None = ..., + num_copies: int | None = None, + print_page_range: list[int] | None = None, + direction: TextDirection | str | None = None, + duplex: Duplex | str | None = None, + view_area: PageBoundaries | None = None, + view_clip: PageBoundaries | None = None, + print_area: PageBoundaries | None = None, + print_clip: PageBoundaries | None = None, + print_scaling=None, + ) -> None: ... + + @property + def non_full_screen_page_mode(self) -> PageMode | None: ... + @non_full_screen_page_mode.setter + def non_full_screen_page_mode(self, page_mode: PageMode | str | None) -> None: ... + + @property + def num_copies(self) -> int | None: ... + @num_copies.setter + def num_copies(self, num_copies: int | None) -> None: ... + + @property + def print_page_range(self) -> list[int] | None: ... + @print_page_range.setter + def print_page_range(self, print_page_range: list[int] | None) -> None: ... + + @property + def direction(self) -> TextDirection | None: ... + @direction.setter + def direction(self, direction: TextDirection | str | None) -> None: ... + + @property + def display_doc_title(self) -> bool: ... + @display_doc_title.setter + def display_doc_title(self, display_doc_title: bool) -> None: ... + + @property + def duplex(self) -> Duplex | None: ... + @duplex.setter + def duplex(self, duplex: Duplex | str | None) -> None: ... + + @property + def view_area(self) -> PageBoundaries | None: ... + @view_area.setter + def view_area(self, view_area: PageBoundaries | str | None) -> None: ... + + @property + def view_clip(self) -> PageBoundaries | None: ... + @view_clip.setter + def view_clip(self, view_area: PageBoundaries | str | None) -> None: ... + + @property + def print_area(self) -> PageBoundaries | None: ... + @print_area.setter + def print_area(self, view_area: PageBoundaries | str | None) -> None: ... + + @property + def print_clip(self) -> PageBoundaries | None: ... + @print_clip.setter + def print_clip(self, view_area: PageBoundaries | str | None) -> None: ... + + @property + def print_scaling(self) -> Literal["None", "AppDefault"] | None: ... + @print_scaling.setter + def print_scaling(self, print_scaling: Literal["None", "AppDefault"] | None) -> None: ... + + def serialize(self) -> str: ... diff --git a/stubs/fpdf2/fpdf/recorder.pyi b/stubs/fpdf2/fpdf/recorder.pyi new file mode 100644 index 000000000000..2588eef8e129 --- /dev/null +++ b/stubs/fpdf2/fpdf/recorder.pyi @@ -0,0 +1,13 @@ +from typing import Any + +class FPDFRecorder: + pdf: Any + accept_page_break: bool + def __init__(self, pdf, accept_page_break: bool = True) -> None: ... + def __getattr__(self, name: str): ... + def rewind(self) -> None: ... + def replay(self) -> None: ... + +class CallRecorder: + def __init__(self, func, calls) -> None: ... + def __call__(self, *args, **kwargs): ... diff --git a/stubs/fpdf2/fpdf/sign.pyi b/stubs/fpdf2/fpdf/sign.pyi new file mode 100644 index 000000000000..1176b1a099e1 --- /dev/null +++ b/stubs/fpdf2/fpdf/sign.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +class Signature: + type: str + filter: str + sub_filter: str + contact_info: Incomplete | None + location: Incomplete | None + m: Incomplete | None + reason: Incomplete | None + byte_range: str + contents: str + def __init__(self, contact_info=None, location=None, m=None, reason=None) -> None: ... + def serialize(self) -> str: ... + +def sign_content(signer, buffer, key, cert, extra_certs, hashalgo, sign_time): ... diff --git a/stubs/fpdf2/fpdf/structure_tree.pyi b/stubs/fpdf2/fpdf/structure_tree.pyi new file mode 100644 index 000000000000..6d3f35cd536f --- /dev/null +++ b/stubs/fpdf2/fpdf/structure_tree.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete, Unused +from collections import defaultdict +from collections.abc import Iterable, Iterator + +from .encryption import StandardSecurityHandler +from .syntax import PDFArray, PDFObject, PDFString + +class NumberTree(PDFObject): + __slots__ = ("_id", "nums") + nums: defaultdict[Incomplete, list[Incomplete]] + def __init__(self) -> None: ... + def serialize(self, obj_dict: Unused = None, _security_handler: StandardSecurityHandler | None = None) -> str: ... + +class StructTreeRoot(PDFObject): + __slots__ = ("_id", "type", "parent_tree", "k") + type: str + parent_tree: NumberTree + k: PDFArray[Incomplete] + def __init__(self) -> None: ... + +class StructElem(PDFObject): + __slots__ = ("_id", "type", "s", "p", "k", "t", "alt", "pg", "_page_number") + type: str + s: str + p: PDFObject + k: PDFArray[Incomplete] + t: PDFString | None + alt: PDFString | None + pg: Incomplete | None + def __init__( + self, + struct_type: str, + parent: PDFObject, + kids: Iterable[int] | Iterable[StructElem], + page_number: int | None = None, + title: str | None = None, + alt: str | None = None, + ) -> None: ... + def page_number(self) -> int | None: ... + +class StructureTreeBuilder: + struct_tree_root: Incomplete + doc_struct_elem: Incomplete + struct_elem_per_mc: Incomplete + def __init__(self) -> None: ... + def add_marked_content( + self, page_number: int, struct_type: str, mcid: int | None = None, title: str | None = None, alt_text: str | None = None + ) -> tuple[Incomplete, Incomplete]: ... + def next_mcid_for_page(self, page_number: int) -> int: ... + def empty(self) -> bool: ... + def __iter__(self) -> Iterator[Incomplete]: ... diff --git a/stubs/fpdf2/fpdf/svg.pyi b/stubs/fpdf2/fpdf/svg.pyi new file mode 100644 index 000000000000..9a06c8eb04d9 --- /dev/null +++ b/stubs/fpdf2/fpdf/svg.pyi @@ -0,0 +1,147 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from logging import Logger +from re import Pattern +from typing import Final, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only + +from ._fonttools_shims import BasePen, _TTGlyphSet +from .drawing import ClippingPath, PaintedPath +from .fpdf import FPDF +from .image_datastructures import ImageCache + +LOGGER: Logger +__pdoc__: dict[str, bool] + +@type_check_only +class _HasQualname(Protocol): + __qualname__: str + +_T = TypeVar("_T", bound=_HasQualname) + +def force_nodocument(item: _T) -> _T: ... + +NUMBER_SPLIT: Final[Pattern[str]] +TRANSFORM_GETTER: Final[Pattern[str]] + +class Percent(float): ... + +unit_splitter: Pattern[str] +relative_length_units: set[str] +absolute_length_units: dict[str, int] +angle_units: dict[str, float] + +def resolve_length(length_str, default_unit: str = "pt"): ... +def resolve_angle(angle_str, default_unit: str = "deg"): ... +def xmlns(space, name): ... +def xmlns_lookup(space, *names): ... +def without_ns(qualified_tag: str) -> str: ... + +shape_tags: Incomplete + +def svgcolor(colorstr): ... +def convert_stroke_width(incoming): ... +def convert_miterlimit(incoming): ... +def clamp_float(min_val, max_val): ... +def inheritable(value, converter=...): ... +def optional(value, converter=...): ... + +svg_attr_map: dict[str, Callable[[Incomplete], tuple[str, Incomplete]]] + +def apply_styles(stylable, svg_element) -> None: ... + +class ShapeBuilder: + @overload + @staticmethod + def new_path(tag, clipping_path: Literal[True]) -> ClippingPath: ... + @overload + @staticmethod + def new_path(tag, clipping_path: Literal[False] = False) -> PaintedPath: ... + + @overload + @classmethod + def rect(cls, tag, clipping_path: Literal[True]) -> ClippingPath: ... + @overload + @classmethod + def rect(cls, tag, clipping_path: Literal[False] = False) -> PaintedPath: ... + + @overload + @classmethod + def circle(cls, tag, clipping_path: Literal[True]) -> ClippingPath: ... + @overload + @classmethod + def circle(cls, tag, clipping_path: Literal[False] = False) -> PaintedPath: ... + + @overload + @classmethod + def ellipse(cls, tag, clipping_path: Literal[True]) -> ClippingPath: ... + @overload + @classmethod + def ellipse(cls, tag, clipping_path: Literal[False] = False) -> PaintedPath: ... + + @classmethod + def line(cls, tag) -> PaintedPath: ... + @classmethod + def polyline(cls, tag) -> PaintedPath: ... + + @overload + @classmethod + def polygon(cls, tag, clipping_path: Literal[True]) -> ClippingPath: ... + @overload + @classmethod + def polygon(cls, tag, clipping_path: Literal[False] = False) -> PaintedPath: ... + +def convert_transforms(tfstr): ... + +class PathPen(BasePen): + pdf_path: PaintedPath + last_was_line_to: bool + first_is_move: bool | None + def __init__(self, pdf_path: PaintedPath, glyphSet: _TTGlyphSet | None = ...): ... + def arcTo(self, rx, ry, rotation, arc, sweep, end) -> None: ... + +def svg_path_converter(pdf_path: PaintedPath, svg_path: str) -> None: ... + +class SVGObject: + image_cache: ImageCache | None + + @classmethod + def from_file(cls, filename, *args, encoding: str = "utf-8", **kwargs): ... + cross_references: Incomplete + def __init__(self, svg_text, image_cache: ImageCache | None = None) -> None: ... + preserve_ar: Incomplete + width: Incomplete + height: Incomplete + viewbox: Incomplete + def update_xref(self, key: str | None, referenced) -> None: ... + def extract_shape_info(self, root_tag) -> None: ... + base_group: Incomplete + def convert_graphics(self, root_tag) -> None: ... + def transform_to_page_viewport(self, pdf, align_viewbox: bool = True): ... + def transform_to_rect_viewport( + self, scale, width, height, align_viewbox: bool = True, ignore_svg_top_attrs: bool = False + ): ... + def draw_to_page(self, pdf: FPDF, x=None, y=None, debug_stream=None) -> None: ... + def handle_defs(self, defs) -> None: ... + def build_xref(self, xref): ... + def build_group(self, group, pdf_group=None): ... + def build_path(self, path): ... + def build_shape(self, shape): ... + def build_clipping_path(self, shape, clip_id): ... + def apply_clipping_path(self, stylable, svg_element) -> None: ... + def build_image(self, image) -> SVGImage: ... + +class SVGImage(NamedTuple): + href: str + x: float + y: float + width: float + height: float + svg_obj: SVGObject + + def __deepcopy__(self, _memo: Unused) -> SVGImage: ... + def render( + self, _gsd_registry: Unused, _style: Unused, last_item, initial_point + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def render_debug( + self, gsd_registry: Unused, style: Unused, last_item, initial_point, debug_stream, _pfx: Unused + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... diff --git a/stubs/fpdf2/fpdf/syntax.pyi b/stubs/fpdf2/fpdf/syntax.pyi new file mode 100644 index 000000000000..ca052a215fbb --- /dev/null +++ b/stubs/fpdf2/fpdf/syntax.pyi @@ -0,0 +1,82 @@ +import datetime +from _typeshed import Incomplete, SupportsItems +from abc import ABC, abstractmethod +from re import Pattern +from typing import ClassVar, Literal, TypeVar +from typing_extensions import Self + +from .encryption import StandardSecurityHandler + +_T = TypeVar("_T") + +def clear_empty_fields(d): ... +def create_dictionary_string( + dict_, + open_dict: str = "<<", + close_dict: str = ">>", + field_join: str = "\n", + key_value_join: str = " ", + has_empty_fields: bool = False, +) -> str: ... +def create_list_string(list_): ... +def iobj_ref(n): ... +def create_stream(stream: str | bytes | bytearray, encryption_handler: StandardSecurityHandler | None = None, obj_id=None): ... +def wrap_in_local_context(draw_commands: list[str]) -> list[str]: ... + +class Raw(str): ... + +class Name(str): + NAME_ESC: ClassVar[Pattern[bytes]] + def serialize(self) -> str: ... + +class PDFObject: + @property + def id(self) -> int: ... + @id.setter + def id(self, n: int) -> None: ... + + @property + def ref(self) -> str: ... + def serialize(self, obj_dict=None, _security_handler: StandardSecurityHandler | None = None) -> str: ... + def content_stream(self) -> bytes: ... + +class PDFContentStream(PDFObject): + filter: Name | None + length: int + def __init__(self, contents: bytes, compress: bool = False) -> None: ... + +def build_obj_dict(key_values: SupportsItems[str, Incomplete]) -> dict[str, str]: ... +def camel_case(snake_case: str) -> str: ... + +class PDFString(str): + USE_HEX_ENCODING: ClassVar[bool] + encrypt: bool + def __new__(cls, content: str, encrypt: bool = False) -> Self: ... + def serialize(self) -> str: ... + +class PDFDate: + date: datetime.datetime + with_tz: bool + encrypt: bool + + def __init__(self, date: datetime.datetime, with_tz: bool = False, encrypt: bool = False) -> None: ... + def serialize(self) -> str: ... + +class PDFArray(list[_T]): + def serialize(self) -> str: ... + +class Destination(ABC): + @abstractmethod + def serialize(self) -> str: ... + +class DestinationXYZ(Destination): + page_number: int + top: float + left: float + zoom: float | Literal["null"] + page_ref: Incomplete | None + def __init__(self, page: int, top: float, left: float = 0, zoom: float | Literal["null"] = "null") -> None: ... + def serialize(self) -> str: ... + def replace( + self, page=None, top: float | None = None, left: float | None = None, zoom: float | Literal["null"] | None = None + ) -> DestinationXYZ: ... diff --git a/stubs/fpdf2/fpdf/table.pyi b/stubs/fpdf2/fpdf/table.pyi new file mode 100644 index 000000000000..e07d318d5101 --- /dev/null +++ b/stubs/fpdf2/fpdf/table.pyi @@ -0,0 +1,140 @@ +from _typeshed import Incomplete, SupportsItems +from collections.abc import Iterable +from dataclasses import dataclass +from io import BytesIO +from typing import Literal, overload + +from PIL import Image + +from .drawing import DeviceGray, DeviceRGB +from .enums import ( + Align, + CellBordersLayout, + TableBordersLayout, + TableCellFillMode, + TableHeadingsDisplay, + TableSpan, + VAlign, + WrapMode, +) +from .fonts import FontFace +from .fpdf import FPDF +from .image_datastructures import _TextAlign +from .util import Padding + +DEFAULT_HEADINGS_STYLE: FontFace + +class Table: + rows: list[Row] + + def __init__( + self, + fpdf: FPDF, + rows: Iterable[str] = (), + *, + # Keep in sync with `fpdf.fpdf.FPDF.table`: + align: str | _TextAlign = "CENTER", + v_align: str | VAlign = "MIDDLE", + borders_layout: str | TableBordersLayout = ..., + cell_fill_color: int | tuple[Incomplete, ...] | DeviceGray | DeviceRGB | None = None, + cell_fill_mode: str | TableCellFillMode = ..., + col_widths: int | tuple[int, ...] | None = None, + first_row_as_headings: bool = True, + gutter_height: float = 0, + gutter_width: float = 0, + headings_style: FontFace = ..., + line_height: int | None = None, + markdown: bool = False, + text_align: str | _TextAlign | tuple[str | _TextAlign, ...] = "JUSTIFY", + width: int | None = None, + wrapmode: WrapMode = ..., + padding: float | Padding | None = None, + outer_border_width: float | None = None, + num_heading_rows: int = 1, + repeat_headings: TableHeadingsDisplay | int = 1, + min_row_height=None, + ) -> None: ... + def row( + self, cells: Iterable[str] = (), style: FontFace | None = None, v_align: VAlign | str | None = None, min_height=None + ) -> Row: ... + def render(self) -> None: ... + +class Row: + cells: list[Cell] + style: FontFace + v_align: VAlign | None + min_height: Incomplete | None + def __init__( + self, table: Table, style: FontFace | None = None, v_align: VAlign | str | None = None, min_height=None + ) -> None: ... + @property + def cols_count(self) -> int: ... + @property + def max_rowspan(self) -> int: ... + def convert_spans(self, active_rowspans: SupportsItems[int, int]) -> tuple[dict[int, int], list[int]]: ... + + @overload + def cell( + self, + text: str = "", + align: str | Align | None = None, + v_align: str | VAlign | None = None, + style: FontFace | None = None, + img: str | Image.Image | BytesIO | None = None, + img_fill_width: bool = False, + colspan: int = 1, + rowspan: int = 1, + padding: tuple[float, ...] | None = None, + link: str | int | None = None, + border: CellBordersLayout | int = ..., + ) -> str: ... + @overload + def cell( + self, + text: TableSpan, + align: str | Align | None = None, + v_align: str | VAlign | None = None, + style: FontFace | None = None, + img: str | Image.Image | BytesIO | None = None, + img_fill_width: bool = False, + colspan: int = 1, + rowspan: int = 1, + padding: tuple[float, ...] | None = None, + link: str | int | None = None, + border: CellBordersLayout | int = ..., + ) -> TableSpan: ... + +@dataclass +class Cell: + __slots__ = ("text", "align", "v_align", "style", "img", "img_fill_width", "colspan", "rowspan", "padding", "link", "border") + text: str + align: str | Align | None + v_align: str | VAlign | None + style: FontFace | None + img: str | None + img_fill_width: bool + colspan: int + rowspan: int + padding: int | tuple[float, ...] | None + link: str | int | None + border: CellBordersLayout | None + + def write(self, text, align=None): ... + +@dataclass(frozen=True) +class RowLayoutInfo: + height: int + pagebreak_height: float + rendered_heights: dict[Incomplete, Incomplete] + merged_heights: list[Incomplete] + +@dataclass(frozen=True) +class RowSpanLayoutInfo: + column: int + start: int + length: int + contents_height: float + + def row_range(self) -> range: ... + +def draw_box_borders(pdf: FPDF, x1, y1, x2, y2, border: str | Literal[0, 1], fill_color=None) -> None: ... diff --git a/stubs/fpdf2/fpdf/template.pyi b/stubs/fpdf2/fpdf/template.pyi new file mode 100644 index 000000000000..41d5f9d55308 --- /dev/null +++ b/stubs/fpdf2/fpdf/template.pyi @@ -0,0 +1,43 @@ +from os import PathLike +from typing import Any + +__author__: str +__copyright__: str +__license__: str + +class FlexTemplate: + pdf: Any + splitting_pdf: Any + handlers: Any + texts: Any + def __init__(self, pdf, elements=None) -> None: ... + elements: Any + keys: Any + def load_elements(self, elements) -> None: ... + def parse_json(self, infile: PathLike[Any], encoding: str = "utf-8") -> None: ... + def parse_csv( + self, infile: PathLike[Any], delimiter: str = ",", decimal_sep: str = ".", encoding: str | None = None + ) -> None: ... + def __setitem__(self, name, value) -> None: ... + set: Any + def __contains__(self, name): ... + def __getitem__(self, name): ... + def split_multicell(self, text: str, element_name: str) -> list[str]: ... + def render(self, offsetx: float = 0.0, offsety: float = 0.0, rotate: float = 0.0, scale: float = 1.0): ... + +class Template(FlexTemplate): + def __init__( + self, + infile=None, + elements=None, + format: str = "A4", + orientation: str = "portrait", + unit: str = "mm", + title: str = "", + author: str = "", + subject: str = "", + creator: str = "", + keywords: str = "", + ) -> None: ... + def add_page(self) -> None: ... + def render(self, outfile=None, dest=None) -> None: ... # type: ignore[override] diff --git a/stubs/fpdf2/fpdf/text_region.pyi b/stubs/fpdf2/fpdf/text_region.pyi new file mode 100644 index 000000000000..e5b62cfa839f --- /dev/null +++ b/stubs/fpdf2/fpdf/text_region.pyi @@ -0,0 +1,174 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import NamedTuple +from typing_extensions import Self + +from .enums import Align, WrapMode +from .image_datastructures import RasterImageInfo, VectorImageInfo, _TextAlign +from .line_break import Fragment, TextLine + +class Extents(NamedTuple): + left: float + right: float + +class TextRegionMixin: + def __init__(self, *args, **kwargs) -> None: ... + def register_text_region(self, region) -> None: ... + def is_current_text_region(self, region) -> bool: ... + def clear_text_region(self) -> None: ... + +class LineWrapper(NamedTuple): + line: Sequence[Incomplete] + paragraph: Paragraph + first_line: bool = False + last_line: bool = False + +class Bullet: + fragments: Sequence[Fragment] + text_line: TextLine + r_margin: float + rendered_flag: bool + def __init__(self, bullet_fragments: Sequence[Fragment], text_line: TextLine, bullet_r_margin: float) -> None: ... + def get_fragments_width(self) -> float: ... + +class Paragraph: + pdf: Incomplete + text_align: Align + line_height: Incomplete + top_margin: Incomplete + bottom_margin: Incomplete + indent: float + skip_leading_spaces: bool + wrapmode: Incomplete + bullet: Bullet | None + first_line_indent: float + + def __init__( + self, + region, + text_align: _TextAlign | None = None, + line_height=None, + top_margin: float = 0, + bottom_margin: float = 0, + indent: float = 0, + bullet_r_margin: float | None = None, + bullet_string: str = "", + skip_leading_spaces: bool = False, + wrapmode: WrapMode | None = None, + first_line_indent: float = 0, + ) -> None: ... + def __enter__(self): ... + def __exit__(self, exc_type, exc_value, traceback) -> None: ... + def write(self, text: str, link=None): ... + def generate_bullet_frags_and_tl( + self, bullet_string: str, bullet_r_margin: float + ) -> tuple[tuple[Fragment, ...], TextLine] | None: ... + def ln(self, h: float | None = None) -> None: ... + def build_lines(self, print_sh: bool) -> list[LineWrapper]: ... + +class ImageParagraph: + region: Incomplete + name: Incomplete + align: Align | None + width: float | None + height: float | None + fill_width: bool + keep_aspect_ratio: bool + top_margin: float + bottom_margin: float + link: Incomplete | None + title: Incomplete | None + alt_text: Incomplete | None + img: Incomplete | None + info: Incomplete | None + + def __init__( + self, + region, + name, + align: _TextAlign | None = None, + width: float | None = None, + height: float | None = None, + fill_width: bool = False, + keep_aspect_ratio: bool = False, + top_margin: float = 0, + bottom_margin: float = 0, + link=None, + title=None, + alt_text=None, + ) -> None: ... + def build_line(self) -> Self: ... + def render(self, col_left: float, col_width: float, max_height: float) -> VectorImageInfo | RasterImageInfo: ... + +class ParagraphCollectorMixin: + pdf: Incomplete + text_align: Align + line_height: Incomplete + print_sh: Incomplete + wrapmode: Incomplete + skip_leading_spaces: Incomplete + def __init__( + self, + pdf, + *args, + text: str | None = None, + text_align: _TextAlign = "LEFT", + line_height: float = 1.0, + print_sh: bool = False, + skip_leading_spaces: bool = False, + wrapmode: WrapMode | None = None, + img=None, + img_fill_width: bool = False, + **kwargs, + ) -> None: ... + def __enter__(self): ... + def __exit__(self, exc_type, exc_value, traceback) -> None: ... + def write(self, text: str, link=None): ... + def ln(self, h: float | None = None) -> None: ... + def paragraph( + self, + text_align: _TextAlign | None = None, + line_height=None, + skip_leading_spaces: bool = False, + top_margin: int = 0, + bottom_margin: int = 0, + indent: int = 0, + bullet_string: str = "", + bullet_r_margin: float | None = None, + wrapmode: WrapMode | None = None, + first_line_indent: float = 0, + ) -> Paragraph: ... + def end_paragraph(self) -> None: ... + def image( + self, + name, + align: _TextAlign | None = None, + width: float | None = None, + height: float | None = None, + fill_width: bool = False, + keep_aspect_ratio: bool = False, + top_margin: float = 0, + bottom_margin: float = 0, + link=None, + title=None, + alt_text=None, + ) -> None: ... + +class TextRegion(ParagraphCollectorMixin): + def current_x_extents(self, y, height) -> None: ... + def collect_lines(self): ... + def render(self) -> None: ... + def get_width(self, height): ... + +class TextColumnarMixin: + l_margin: Incomplete + r_margin: Incomplete + def __init__(self, pdf, *args, l_margin=None, r_margin=None, **kwargs) -> None: ... + +class TextColumns(TextRegion, TextColumnarMixin): + balance: Incomplete + def __init__(self, pdf, *args, ncols: int = 1, gutter: float = 10, balance: bool = False, **kwargs) -> None: ... + def __enter__(self) -> Self: ... + def new_column(self) -> None: ... + def render(self) -> None: ... + def current_x_extents(self, y, height): ... diff --git a/stubs/fpdf2/fpdf/transitions.pyi b/stubs/fpdf2/fpdf/transitions.pyi new file mode 100644 index 000000000000..7d7f2e6f9737 --- /dev/null +++ b/stubs/fpdf2/fpdf/transitions.pyi @@ -0,0 +1,59 @@ +from abc import ABC, abstractmethod +from typing import Literal + +class Transition(ABC): + @abstractmethod + def serialize(self) -> str: ... + +class SplitTransition(Transition): + dimension: Literal["H", "V"] + direction: Literal["I", "O"] + def __init__(self, dimension: Literal["H", "V"], direction: Literal["I", "O"]) -> None: ... + def serialize(self) -> str: ... + +class BlindsTransition(Transition): + dimension: Literal["H", "V"] + def __init__(self, dimension: Literal["H", "V"]) -> None: ... + def serialize(self) -> str: ... + +class BoxTransition(Transition): + direction: Literal["I", "O"] + def __init__(self, direction: Literal["I", "O"]) -> None: ... + def serialize(self) -> str: ... + +class WipeTransition(Transition): + direction: Literal[0, 90, 180, 270] + def __init__(self, direction: Literal[0, 90, 180, 270]) -> None: ... + def serialize(self) -> str: ... + +class DissolveTransition(Transition): + def serialize(self) -> str: ... + +class GlitterTransition(Transition): + direction: Literal[0, 270, 315] + def __init__(self, direction: Literal[0, 270, 315]) -> None: ... + def serialize(self) -> str: ... + +class FlyTransition(Transition): + dimension: Literal["H", "V"] + direction: Literal[0, 270] | None + def __init__(self, dimension: Literal["H", "V"], direction: Literal[0, 270] | None = None) -> None: ... + def serialize(self) -> str: ... + +class PushTransition(Transition): + direction: Literal[0, 270] + def __init__(self, direction: Literal[0, 270]) -> None: ... + def serialize(self) -> str: ... + +class CoverTransition(Transition): + direction: Literal[0, 270] + def __init__(self, direction: Literal[0, 270]) -> None: ... + def serialize(self) -> str: ... + +class UncoverTransition(Transition): + direction: Literal[0, 270] + def __init__(self, direction: Literal[0, 270]) -> None: ... + def serialize(self) -> str: ... + +class FadeTransition(Transition): + def serialize(self) -> str: ... diff --git a/stubs/fpdf2/fpdf/unicode_script.pyi b/stubs/fpdf2/fpdf/unicode_script.pyi new file mode 100644 index 000000000000..49e56f2d2923 --- /dev/null +++ b/stubs/fpdf2/fpdf/unicode_script.pyi @@ -0,0 +1,172 @@ +from enum import IntEnum +from typing import Final + +class UnicodeScript(IntEnum): + COMMON = 0 + LATIN = 1 + GREEK = 2 + CYRILLIC = 3 + ARMENIAN = 4 + HEBREW = 5 + ARABIC = 6 + SYRIAC = 7 + THAANA = 8 + DEVANAGARI = 9 + BENGALI = 10 + GURMUKHI = 11 + GUJARATI = 12 + ORIYA = 13 + TAMIL = 14 + TELUGU = 15 + KANNADA = 16 + MALAYALAM = 17 + SINHALA = 18 + THAI = 19 + LAO = 20 + TIBETAN = 21 + MYANMAR = 22 + GEORGIAN = 23 + HANGUL = 24 + ETHIOPIC = 25 + CHEROKEE = 26 + CANADIAN_ABORIGINAL = 27 + OGHAM = 28 + RUNIC = 29 + KHMER = 30 + MONGOLIAN = 31 + HIRAGANA = 32 + KATAKANA = 33 + BOPOMOFO = 34 + HAN = 35 + YI = 36 + OLD_ITALIC = 37 + GOTHIC = 38 + DESERET = 39 + INHERITED = 40 + TAGALOG = 41 + HANUNOO = 42 + BUHID = 43 + TAGBANWA = 44 + LIMBU = 45 + TAI_LE = 46 + LINEAR_B = 47 + UGARITIC = 48 + SHAVIAN = 49 + OSMANYA = 50 + CYPRIOT = 51 + BRAILLE = 52 + BUGINESE = 53 + COPTIC = 54 + NEW_TAI_LUE = 55 + GLAGOLITIC = 56 + TIFINAGH = 57 + SYLOTI_NAGRI = 58 + OLD_PERSIAN = 59 + KHAROSHTHI = 60 + BALINESE = 61 + CUNEIFORM = 62 + PHOENICIAN = 63 + PHAGS_PA = 64 + NKO = 65 + SUNDANESE = 66 + LEPCHA = 67 + OL_CHIKI = 68 + VAI = 69 + SAURASHTRA = 70 + KAYAH_LI = 71 + REJANG = 72 + LYCIAN = 73 + CARIAN = 74 + LYDIAN = 75 + CHAM = 76 + TAI_THAM = 77 + TAI_VIET = 78 + AVESTAN = 79 + EGYPTIAN_HIEROGLYPHS = 80 + SAMARITAN = 81 + LISU = 82 + BAMUM = 83 + JAVANESE = 84 + MEETEI_MAYEK = 85 + IMPERIAL_ARAMAIC = 86 + OLD_SOUTH_ARABIAN = 87 + INSCRIPTIONAL_PARTHIAN = 88 + INSCRIPTIONAL_PAHLAVI = 89 + OLD_TURKIC = 90 + KAITHI = 91 + BATAK = 92 + BRAHMI = 93 + MANDAIC = 94 + CHAKMA = 95 + MEROITIC_CURSIVE = 96 + MEROITIC_HIEROGLYPHS = 97 + MIAO = 98 + SHARADA = 99 + SORA_SOMPENG = 100 + TAKRI = 101 + CAUCASIAN_ALBANIAN = 102 + BASSA_VAH = 103 + DUPLOYAN = 104 + ELBASAN = 105 + GRANTHA = 106 + PAHAWH_HMONG = 107 + KHOJKI = 108 + LINEAR_A = 109 + MAHAJANI = 110 + MANICHAEAN = 111 + MENDE_KIKAKUI = 112 + MODI = 113 + MRO = 114 + OLD_NORTH_ARABIAN = 115 + NABATAEAN = 116 + PALMYRENE = 117 + PAU_CIN_HAU = 118 + OLD_PERMIC = 119 + PSALTER_PAHLAVI = 120 + SIDDHAM = 121 + KHUDAWADI = 122 + TIRHUTA = 123 + WARANG_CITI = 124 + AHOM = 125 + ANATOLIAN_HIEROGLYPHS = 126 + HATRAN = 127 + MULTANI = 128 + OLD_HUNGARIAN = 129 + SIGNWRITING = 130 + ADLAM = 131 + BHAIKSUKI = 132 + MARCHEN = 133 + NEWA = 134 + OSAGE = 135 + TANGUT = 136 + MASARAM_GONDI = 137 + NUSHU = 138 + SOYOMBO = 139 + ZANABAZAR_SQUARE = 140 + DOGRA = 141 + GUNJALA_GONDI = 142 + MAKASAR = 143 + MEDEFAIDRIN = 144 + HANIFI_ROHINGYA = 145 + SOGDIAN = 146 + OLD_SOGDIAN = 147 + ELYMAIC = 148 + NANDINAGARI = 149 + NYIAKENG_PUACHUE_HMONG = 150 + WANCHO = 151 + CHORASMIAN = 152 + DIVES_AKURU = 153 + KHITAN_SMALL_SCRIPT = 154 + YEZIDI = 155 + CYPRO_MINOAN = 156 + OLD_UYGHUR = 157 + TANGSA = 158 + TOTO = 159 + VITHKUQI = 160 + KAWI = 161 + NAG_MUNDARI = 162 + UNKNOWN = 999 + +UNICODE_RANGE_TO_SCRIPT: Final[tuple[tuple[int, int, int]]] + +def get_unicode_script(char: str) -> UnicodeScript: ... diff --git a/stubs/fpdf2/fpdf/util.pyi b/stubs/fpdf2/fpdf/util.pyi new file mode 100644 index 000000000000..9c98ae361a5f --- /dev/null +++ b/stubs/fpdf2/fpdf/util.pyi @@ -0,0 +1,38 @@ +from collections.abc import Iterable +from typing import Any, AnyStr, Final, Literal, NamedTuple, TypeAlias + +_Unit: TypeAlias = Literal["pt", "mm", "cm", "in"] + +PIL_MEM_BLOCK_SIZE_IN_MIB: Final = 16 + +class Padding(NamedTuple): + top: float = 0 + right: float = 0 + bottom: float = 0 + left: float = 0 + @classmethod + def new(cls, padding: float | tuple[float, ...] | list[float]): ... + +def buffer_subst(buffer: bytearray, placeholder: str, value: str) -> bytearray: ... +def escape_parens(s: AnyStr) -> AnyStr: ... +def get_scale_factor(unit: _Unit | float) -> float: ... +def convert_unit( + # to_convert has a recursive type + to_convert: float | Iterable[float | Iterable[Any]], + old_unit: str | float, + new_unit: str | float, +) -> float | tuple[float, ...]: ... + +ROMAN_NUMERAL_MAP: Final[tuple[tuple[str, int], ...]] + +def int2roman(n: int | None) -> str: ... +def int_to_letters(n: int) -> str: ... +def print_mem_usage(prefix: str) -> None: ... +def get_mem_usage(prefix: str) -> str: ... +def get_process_rss() -> str: ... +def get_process_rss_as_mib() -> float | None: ... +def get_process_heap_and_stack_sizes() -> tuple[str, str]: ... +def get_pymalloc_allocated_over_total_size() -> str: ... +def get_gc_managed_objs_total_size() -> str: ... +def get_tracemalloc_traced_memory() -> str: ... +def get_pillow_allocated_memory() -> str: ... diff --git a/stubs/gdb/@tests/stubtest_allowlist.txt b/stubs/gdb/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0defd3d50977 --- /dev/null +++ b/stubs/gdb/@tests/stubtest_allowlist.txt @@ -0,0 +1,83 @@ +# Internal list of packages to auto-load +gdb.packages +gdb.GdbSetPythonDirectory + +# optional method, only called when present +gdb.Command.complete +gdb.FinishBreakpoint.out_of_scope +gdb.Parameter.get_set_string +gdb.Parameter.get_show_string + +# TODO: abstract/optional methods to be implemented by subclasses +# gdb.FinishBreakpoint.out_of_scope +gdb.Breakpoint.stop +gdb.Command.invoke +gdb.Function.invoke +gdb.MICommand.invoke + +# TODO: investigate why they are not present at runtime +gdb.Instruction +gdb.LazyString +gdb.Membuf +gdb.Record +gdb.RecordFunctionSegment +gdb.RecordGap +gdb.RecordInstruction +gdb.TuiWindow + +# python implementation of built-in commands +gdb.command +gdb.command.explore +gdb.command.frame_filters +gdb.command.missing_debug +gdb.command.pretty_printers +gdb.command.prompt +gdb.command.type_printers +gdb.command.unwinders +gdb.command.xmethods + +# implementing internal convenience functions +gdb.function +gdb.function.as_string +gdb.function.caller_is +gdb.function.strfns + +# internal workers for frame filters +gdb.frames +gdb.FrameDecorator.FrameVars + +# function is only called when it's present +gdb.prompt_hook + +# internal methods used in the public gdb.prompt.substitute_prompt +gdb.prompt.prompt_help +gdb.prompt.prompt_substitutions + +# internal module to register a printer for mpx_bound128 type +gdb.printer +gdb.printer.bound_registers + +gdb.printing.RegexpCollectionPrettyPrinter.RegexpSubprinter +gdb.printing.add_builtin_pretty_printer + +# internal methods for colorful commandline output +gdb.styling + +# internal worker for SimpleXMethodMatcher +gdb.xmethod.SimpleXMethodMatcher.SimpleXMethodWorker + +# list of registered xmethods to be added by xmethod.register_xmethod_matcher() +gdb.xmethods +gdb.Objfile.xmethods +gdb.Progspace.xmethods + +# stubtest thinks this can't be sub-classed at runtime, but it is +gdb.disassembler.DisassemblerPart + +gdb.TuiEnabledEvent +gdb.events.tui_enabled + +gdb.Progspace.missing_debug_handlers +gdb.missing_debug_handlers +gdb.missing_files +gdb.missing_objfile diff --git a/stubs/gdb/METADATA.toml b/stubs/gdb/METADATA.toml new file mode 100644 index 000000000000..5fcf687ea80b --- /dev/null +++ b/stubs/gdb/METADATA.toml @@ -0,0 +1,16 @@ +version = "16.3.*" +# This is the official web portal for the GDB Git repo, +# see https://sourceware.org/gdb/current/ for other ways of obtaining the source code. +upstream-repository = "https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree" +extra-description = """\ + Type hints for GDB's \ + [Python API](https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html). \ + Note that this API is available only when running Python scripts under GDB: \ + it is not possible to install the `gdb` package separately, for instance \ + using `pip`.\ +""" + +[tool.stubtest] +skip = true # https://github.com/python/typeshed/issues/15236 +ci-platforms = ["linux"] +apt-dependencies = ["gdb"] diff --git a/stubs/gdb/gdb/FrameDecorator.pyi b/stubs/gdb/gdb/FrameDecorator.pyi new file mode 100644 index 000000000000..5ec95901e46a --- /dev/null +++ b/stubs/gdb/gdb/FrameDecorator.pyi @@ -0,0 +1,24 @@ +from collections.abc import Iterator +from typing import Protocol + +import gdb + +class SymValueWrapper(Protocol): + def symbol(self) -> gdb.Symbol | str: ... + def value(self) -> gdb._ValueOrNative | None: ... + +class _FrameDecoratorBase: + def __init__(self, base: gdb.Frame | FrameDecorator) -> None: ... + def elided(self) -> Iterator[gdb.Frame] | None: ... + def function(self) -> str | None: ... + def address(self) -> int | None: ... + def line(self) -> int | None: ... + def frame_args(self) -> Iterator[SymValueWrapper] | None: ... + def frame_locals(self) -> Iterator[SymValueWrapper] | None: ... + def inferior_frame(self) -> gdb.Frame: ... + +class FrameDecorator(_FrameDecoratorBase): + def filename(self) -> str | None: ... + +class DAPFrameDecorator(_FrameDecoratorBase): + def filename(self) -> str | None: ... diff --git a/stubs/gdb/gdb/FrameIterator.pyi b/stubs/gdb/gdb/FrameIterator.pyi new file mode 100644 index 000000000000..26e1dd436012 --- /dev/null +++ b/stubs/gdb/gdb/FrameIterator.pyi @@ -0,0 +1,8 @@ +import gdb + +class FrameIterator: + frame: gdb.Frame + + def __init__(self, frame_obj: gdb.Frame) -> None: ... + def __iter__(self) -> FrameIterator: ... + def __next__(self) -> gdb.Frame: ... diff --git a/stubs/gdb/gdb/__init__.pyi b/stubs/gdb/gdb/__init__.pyi new file mode 100644 index 000000000000..5911d37ab914 --- /dev/null +++ b/stubs/gdb/gdb/__init__.pyi @@ -0,0 +1,1051 @@ +# The GDB Python API is implemented in C, so the type hints below were made +# reading the documentation +# (https://sourceware.org/gdb/onlinedocs/gdb/Python-API.html). + +import _typeshed +import threading +from collections.abc import Callable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager +from typing import Any, Final, Generic, Literal, Protocol, TypeAlias, TypedDict, TypeVar, final, overload, type_check_only +from typing_extensions import deprecated, disjoint_base + +import gdb.FrameDecorator +import gdb.types +from gdb.missing_debug import MissingDebugHandler +from gdb.missing_files import MissingFileHandler + +# The following submodules are automatically imported +from . import events as events, printing as printing, prompt as prompt, types as types + +# Basic + +VERSION: str +HOST_CONFIG: str +TARGET_CONFIG: str + +PYTHONDIR: str + +STDOUT: int +STDERR: int +STDLOG: int + +@overload +def execute(command: str, from_tty: bool = False, to_string: Literal[False] = False) -> None: ... +@overload +def execute(command: str, *, to_string: Literal[True]) -> str: ... +@overload +def execute(command: str, from_tty: bool, to_string: Literal[True]) -> str: ... +@overload +def execute(command: str, from_tty: bool = False, to_string: bool = False) -> str | None: ... + +def breakpoints() -> Sequence[Breakpoint]: ... +def rbreak(regex: str, minsyms: bool = ..., throttle: int = ..., symtabs: Iterator[Symtab] = ...) -> list[Breakpoint]: ... +def parameter(parameter: str, /) -> bool | int | str | None: ... +def set_parameter(name: str, value: bool | int | str | None) -> None: ... +def with_parameter(name: str, value: bool | int | str | None) -> AbstractContextManager[None]: ... +def history(number: int, /) -> Value: ... +def add_history(value: Value, /) -> int: ... +def history_count() -> int: ... +def convenience_variable(name: str, /) -> Value | None: ... +def set_convenience_variable(name: str, value: _ValueOrNative | None, /) -> None: ... +def parse_and_eval(expression: str, global_context: bool = False) -> Value: ... +def format_address(address: int, progspace: Progspace = ..., architecture: Architecture = ...): ... +def find_pc_line(pc: int | Value) -> Symtab_and_line: ... +def post_event(event: Callable[[], object], /) -> None: ... +def write(string: str, stream: int = ...) -> None: ... +def flush(stream: int = ...) -> None: ... +def target_charset() -> str: ... +def target_wide_charset() -> str: ... +def host_charset() -> str: ... +def solib_name(addr: int) -> str | None: ... +def decode_line(expression: str = ..., /) -> tuple[str | None, tuple[Symtab_and_line, ...] | None]: ... +def architecture_names() -> list[str]: ... +def connections() -> list[TargetConnection]: ... + +prompt_hook: Callable[[str], str | None] + +# Exceptions + +class error(RuntimeError): ... +class MemoryError(error): ... +class GdbError(Exception): ... + +# Values + +_ValueOrNative: TypeAlias = bool | int | float | str | Value | LazyString +_ValueOrInt: TypeAlias = Value | int + +@disjoint_base +class Value: + address: Value | None + is_optimized_out: bool + type: Type + dynamic_type: Type + is_lazy: bool + bytes: bytes + + def __index__(self) -> int: ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __add__(self, other: _ValueOrNative, /) -> Value: ... + def __radd__(self, other: _ValueOrNative, /) -> Value: ... + def __sub__(self, other: _ValueOrNative, /) -> Value: ... + def __rsub__(self, other: _ValueOrNative, /) -> Value: ... + def __mul__(self, other: _ValueOrNative, /) -> Value: ... + def __rmul__(self, other: _ValueOrNative, /) -> Value: ... + def __truediv__(self, other: _ValueOrNative, /) -> Value: ... + def __rtruediv__(self, other: _ValueOrNative, /) -> Value: ... + def __mod__(self, other: _ValueOrNative, /) -> Value: ... + def __rmod__(self, other: _ValueOrNative, /) -> Value: ... + def __pow__(self, other: _ValueOrNative, mod: None = None, /) -> Value: ... + def __and__(self, other: _ValueOrNative, /) -> Value: ... + def __or__(self, other: _ValueOrNative, /) -> Value: ... + def __xor__(self, other: _ValueOrNative, /) -> Value: ... + def __lshift__(self, other: _ValueOrNative, /) -> Value: ... + def __rshift__(self, other: _ValueOrNative, /) -> Value: ... + def __eq__(self, other: _ValueOrNative, /) -> bool: ... # type: ignore[override] + def __ne__(self, other: _ValueOrNative, /) -> bool: ... # type: ignore[override] + def __lt__(self, other: _ValueOrNative, /) -> bool: ... + def __le__(self, other: _ValueOrNative, /) -> bool: ... + def __gt__(self, other: _ValueOrNative, /) -> bool: ... + def __ge__(self, other: _ValueOrNative, /) -> bool: ... + def __getitem__(self, key: int | str | Field, /) -> Value: ... + def __call__(self, *args: _ValueOrNative) -> Value: ... + + @overload + def __init__(self, val: _ValueOrNative, type: None = None) -> None: ... + @overload + def __init__(self, val: _BufferType, type: Type) -> None: ... + + def cast(self, type: Type) -> Value: ... + def dereference(self) -> Value: ... + def referenced_value(self) -> Value: ... + def reference_value(self) -> Value: ... + def rvalue_reference_value(self) -> Value: ... + def const_value(self) -> Value: ... + def dynamic_cast(self, type: Type) -> Value: ... + def reinterpret_cast(self, type: Type) -> Value: ... + def format_string( + self, + raw: bool = ..., + pretty_arrays: bool = ..., + pretty_structs: bool = ..., + array_indexes: bool = ..., + symbols: bool = ..., + unions: bool = ..., + address: bool = ..., + styling: bool = ..., + nibbles: bool = ..., + deref_refs: bool = ..., + actual_objects: bool = ..., + static_members: bool = ..., + max_characters: int = ..., + max_elements: int = ..., + max_depth: int = ..., + repeat_threshold: int = ..., + format: str = ..., + ) -> str: ... + def string(self, encoding: str = ..., errors: str = ..., length: int = ...) -> str: ... + def lazy_string(self, encoding: str = ..., length: int = ...) -> LazyString: ... + def fetch_lazy(self) -> None: ... + def assign(self, val): ... + def to_array(self): ... + +# Types + +def lookup_type(name: str, block: Block = ...) -> Type: ... + +@final +class Type(Mapping[str, Field]): + alignof: int + code: int + dynamic: bool + name: str + sizeof: int + tag: str | None + objfile: Objfile | None + is_scalar: bool + is_signed: bool + is_array_like: bool + is_string_like: bool + + def fields(self) -> list[Field]: ... + def array(self, n1: int | Value, n2: int | Value = ...) -> Type: ... + def vector(self, n1: int, n2: int = ...) -> Type: ... + def iteritems(self) -> TypeIterator[tuple[str, Field]]: ... + def iterkeys(self) -> TypeIterator[str]: ... + def itervalues(self) -> TypeIterator[Field]: ... + def const(self) -> Type: ... + def volatile(self) -> Type: ... + def unqualified(self) -> Type: ... + def range(self) -> tuple[int, int]: ... + def reference(self) -> Type: ... + def pointer(self) -> Type: ... + def strip_typedefs(self) -> Type: ... + def target(self) -> Type: ... + def template_argument(self, n: int, block: Block = ...) -> Type: ... + def optimized_out(self) -> Value: ... + def get(self, key: str, default: Any = ...) -> Field | Any: ... + def has_key(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def __getitem__(self, key: str, /) -> Field: ... + def __iter__(self) -> TypeIterator[str]: ... + +_T = TypeVar("_T") + +@final +class TypeIterator(Iterator[_T]): + def __next__(self) -> _T: ... + +@final +class Field: + bitpos: int | None + enumval: int + name: str | None + artificial: bool + is_base_class: bool + bitsize: int + type: Type | None + parent_type: Type + +TYPE_CODE_BITSTRING: Final = -1 +TYPE_CODE_PTR: Final = 1 +TYPE_CODE_ARRAY: Final = 2 +TYPE_CODE_STRUCT: Final = 3 +TYPE_CODE_UNION: Final = 4 +TYPE_CODE_ENUM: Final = 5 +TYPE_CODE_FLAGS: Final = 6 +TYPE_CODE_FUNC: Final = 7 +TYPE_CODE_INT: Final = 8 +TYPE_CODE_FLT: Final = 9 +TYPE_CODE_VOID: Final = 10 +TYPE_CODE_SET: Final = 11 +TYPE_CODE_RANGE: Final = 12 +TYPE_CODE_STRING: Final = 13 +TYPE_CODE_ERROR: Final = 14 +TYPE_CODE_METHOD: Final = 15 +TYPE_CODE_METHODPTR: Final = 16 +TYPE_CODE_MEMBERPTR: Final = 17 +TYPE_CODE_REF: Final = 18 +TYPE_CODE_RVALUE_REF: Final = 19 +TYPE_CODE_CHAR: Final = 20 +TYPE_CODE_BOOL: Final = 21 +TYPE_CODE_COMPLEX: Final = 22 +TYPE_CODE_TYPEDEF: Final = 23 +TYPE_CODE_NAMESPACE: Final = 24 +TYPE_CODE_DECFLOAT: Final = 25 +TYPE_CODE_MODULE: Final = 26 +TYPE_CODE_INTERNAL_FUNCTION: Final = 27 +TYPE_CODE_XMETHOD: Final = 28 +TYPE_CODE_FIXED_POINT: Final = 29 +TYPE_CODE_NAMELIST: Final = 30 + +SEARCH_UNDEF_DOMAIN: Final[int] +SEARCH_VAR_DOMAIN: Final[int] +SEARCH_STRUCT_DOMAIN: Final[int] +SEARCH_MODULE_DOMAIN: Final[int] +SEARCH_LABEL_DOMAIN: Final[int] +SEARCH_COMMON_BLOCK_DOMAIN: Final[int] +SEARCH_TYPE_DOMAIN: Final[int] +SEARCH_FUNCTION_DOMAIN: Final[int] + +# Pretty Printing + +@type_check_only +class _PrettyPrinter(Protocol): + # TODO: The "children" and "display_hint" methods are optional for + # pretty-printers. Unfortunately, there is no such thing as an optional + # method in the type system at the moment. + # + # def children(self) -> Iterator[tuple[str, _ValueOrNative]]: ... + # def display_hint(self) -> str | None: ... + def to_string(self) -> str | LazyString: ... + +_PrettyPrinterLookupFunction: TypeAlias = Callable[[Value], _PrettyPrinter | None] + +def default_visualizer(value: Value, /) -> _PrettyPrinter | None: ... + +# Selecting Pretty-Printers + +pretty_printers: list[_PrettyPrinterLookupFunction] +type_printers: list[gdb.types._TypePrinter] + +# Filtering Frames + +@type_check_only +class _FrameFilter(Protocol): + name: str + enabled: bool + priority: int + + def filter( + self, iterator: Iterator[gdb.FrameDecorator.FrameDecorator | gdb.FrameDecorator.DAPFrameDecorator] + ) -> Iterator[gdb.FrameDecorator.FrameDecorator | gdb.FrameDecorator.DAPFrameDecorator]: ... + +frame_filters: dict[str, _FrameFilter] + +# Unwinding Frames + +@final +class PendingFrame: + def read_register(self, register: str | RegisterDescriptor | int) -> Value: ... + def create_unwind_info(self, frame_id: object, /) -> UnwindInfo: ... + def architecture(self) -> Architecture: ... + def language(self): ... + def level(self) -> int: ... + def name(self) -> str: ... + def pc(self) -> int: ... + def block(self) -> Block: ... + def find_sal(self) -> Symtab_and_line: ... + def function(self) -> Symbol: ... + def is_valid(self) -> bool: ... + +@final +class UnwindInfo: + def add_saved_register(self, register: str | RegisterDescriptor | int, value: Value) -> None: ... + +@type_check_only +class _Unwinder(Protocol): + @property + def name(self) -> str: ... + enabled: bool + + def __call__(self, pending_frame: PendingFrame) -> UnwindInfo | None: ... + +frame_unwinders: list[_Unwinder] + +# Inferiors + +def inferiors() -> tuple[Inferior, ...]: ... +def selected_inferior() -> Inferior: ... + +_BufferType: TypeAlias = _typeshed.ReadableBuffer + +@final +class Inferior: + num: int + connection: TargetConnection | None + connection_num: int | None + pid: int + was_attached: bool + progspace: Progspace + main_name: str | None + + @property + def arguments(self) -> str | None: ... + @arguments.setter + def arguments(self, args: str | Sequence[str]) -> None: ... + + def is_valid(self) -> bool: ... + def threads(self) -> tuple[InferiorThread, ...]: ... + def architecture(self) -> Architecture: ... + def read_memory(self, address: _ValueOrInt, length: int) -> memoryview: ... + def write_memory(self, address: _ValueOrInt, buffer: _BufferType, length: int = ...) -> None: ... + def search_memory(self, address: _ValueOrInt, length: int, pattern: _BufferType) -> int | None: ... + def thread_from_handle(self, handle: Value) -> InferiorThread: ... + @deprecated("Use gdb.thread_from_handle() instead.") + def thread_from_thread_handle(self, handle: Value) -> InferiorThread: ... + def set_env(self, name: str, value: str) -> None: ... + def unset_env(self, name: str) -> None: ... + def clear_env(self) -> None: ... + +# Threads + +class Thread(threading.Thread): ... + +def selected_thread() -> InferiorThread: ... + +@final +class InferiorThread: + name: str | None + details: str | None + num: int + global_num: int + ptid: tuple[int, int, int] + ptid_string: str + inferior: Inferior + + def is_valid(self) -> bool: ... + def switch(self) -> None: ... + def is_stopped(self) -> bool: ... + def is_running(self) -> bool: ... + def is_exited(self) -> bool: ... + def handle(self) -> bytes: ... + +# Recordings + +def start_recording(method: str = ..., format: str = ..., /) -> Record: ... +def current_recording() -> Record | None: ... +def stop_recording() -> None: ... + +class Record: + method: str + format: str | None + begin: Instruction + end: Instruction + replay_position: Instruction | None + instruction_history: list[Instruction] + function_call_history: list[RecordFunctionSegment] + + def goto(self, instruction: Instruction, /) -> None: ... + def clear(self) -> None: ... + +class Instruction: + pc: int + data: memoryview + decoded: str + size: int + +class RecordInstruction(Instruction): + number: int + sal: Symtab_and_line | None + is_speculative: bool + +class RecordGap(Instruction): + number: int + error_code: int + error_string: str + +class RecordFunctionSegment: + number: int + symbol: Symbol | None + level: int | None + instructions: list[RecordInstruction | RecordGap] + up: RecordFunctionSegment | None + prev: RecordFunctionSegment | None + next: RecordFunctionSegment | None + +# CLI Commands + +@disjoint_base +class Command: + def __init__(self, name: str, command_class: int, completer_class: int = ..., prefix: bool = ...) -> None: ... + def dont_repeat(self) -> None: ... + def invoke(self, argument: str, from_tty: bool) -> None: ... + def complete(self, text: str, word: str) -> object: ... + +def string_to_argv(argv: str, /) -> list[str]: ... + +COMMAND_NONE: int +COMMAND_RUNNING: int +COMMAND_DATA: int +COMMAND_STACK: int +COMMAND_FILES: int +COMMAND_SUPPORT: int +COMMAND_STATUS: int +COMMAND_BREAKPOINTS: int +COMMAND_TRACEPOINTS: int +COMMAND_TUI: int +COMMAND_USER: int +COMMAND_OBSCURE: int +COMMAND_MAINTENANCE: int + +COMPLETE_NONE: int +COMPLETE_FILENAME: int +COMPLETE_LOCATION: int +COMPLETE_COMMAND: int +COMPLETE_SYMBOL: int +COMPLETE_EXPRESSION: int + +# GDB/MI Commands + +@disjoint_base +class MICommand: + name: str + installed: bool + + def __init__(self, name: str) -> None: ... + def invoke(self, arguments: list[str]) -> dict[str, object] | None: ... + +# Parameters + +@disjoint_base +class Parameter: + set_doc: str + show_doc: str + value: object + + def __init__(self, name: str, command_class: int, parameter_class: int, enum_sequence: Sequence[str] = ...) -> None: ... + def get_set_string(self) -> str: ... + def get_show_string(self, svalue: str) -> str: ... + +PARAM_BOOLEAN: int +PARAM_AUTO_BOOLEAN: int +PARAM_UINTEGER: int +PARAM_INTEGER: int +PARAM_STRING: int +PARAM_STRING_NOESCAPE: int +PARAM_OPTIONAL_FILENAME: int +PARAM_FILENAME: int +PARAM_ZINTEGER: int +PARAM_ZUINTEGER: int +PARAM_ZUINTEGER_UNLIMITED: int +PARAM_ENUM: int + +# Convenience functions + +class Function: + def __init__(self, name: str) -> None: ... + def invoke(self, *args: Value) -> _ValueOrNative: ... + +# Progspaces + +def current_progspace() -> Progspace | None: ... +def progspaces() -> Sequence[Progspace]: ... + +@final +class Progspace: + executable_filename: str | None + filename: str | None + symbol_file: Objfile | None + pretty_printers: list[_PrettyPrinterLookupFunction] + type_printers: list[gdb.types._TypePrinter] + frame_filters: dict[str, _FrameFilter] + frame_unwinders: list[_Unwinder] + missing_file_handlers: Sequence[tuple[Literal["debug"], MissingDebugHandler] | tuple[Literal["file"], MissingFileHandler]] + + def block_for_pc(self, pc: int, /) -> Block | None: ... + def find_pc_line(self, pc: int, /) -> Symtab_and_line: ... + def is_valid(self) -> bool: ... + def objfile_for_address(self, address: int, /) -> Objfile | None: ... + def objfiles(self) -> Sequence[Objfile]: ... + def solib_name(self, address: int, /) -> str | None: ... + +# Objfiles + +def current_objfile() -> Objfile | None: ... +def objfiles() -> list[Objfile]: ... +def lookup_objfile(name: str, by_build_id: bool = ...) -> Objfile | None: ... + +@final +class Objfile: + filename: str | None + username: str | None + owner: Objfile | None + build_id: str | None + progspace: Progspace | None + pretty_printers: list[_PrettyPrinterLookupFunction] + type_printers: list[gdb.types._TypePrinter] + frame_filters: dict[str, _FrameFilter] + frame_unwinders: list[_Unwinder] + is_file: bool + + def is_valid(self) -> bool: ... + def add_separate_debug_file(self, file: str) -> None: ... + def lookup_global_symbol(self, name: str, domain: int = ...) -> Symbol | None: ... + def lookup_static_symbol(self, name: str, domain: int = ...) -> Symbol | None: ... + +# Frames + +def selected_frame() -> Frame: ... +def newest_frame() -> Frame: ... +def frame_stop_reason_string(code: int, /) -> str: ... +def invalidate_cached_frames() -> None: ... + +NORMAL_FRAME: int +DUMMY_FRAME: int +INLINE_FRAME: int +TAILCALL_FRAME: int +SIGTRAMP_FRAME: int +ARCH_FRAME: int +SENTINEL_FRAME: int + +FRAME_UNWIND_NO_REASON: int +FRAME_UNWIND_NULL_ID: int +FRAME_UNWIND_OUTERMOST: int +FRAME_UNWIND_UNAVAILABLE: int +FRAME_UNWIND_INNER_ID: int +FRAME_UNWIND_SAME_ID: int +FRAME_UNWIND_NO_SAVED_PC: int +FRAME_UNWIND_MEMORY_ERROR: int + +@final +class Frame: + def is_valid(self) -> bool: ... + def name(self) -> str | None: ... + def architecture(self) -> Architecture: ... + def type(self) -> int: ... + def unwind_stop_reason(self) -> int: ... + def pc(self) -> int: ... + def block(self) -> Block: ... + def function(self) -> Symbol: ... + def older(self) -> Frame | None: ... + def newer(self) -> Frame | None: ... + def find_sal(self) -> Symtab_and_line: ... + def read_register(self, register: str | RegisterDescriptor | int) -> Value: ... + def read_var(self, variable: str | Symbol, block: Block | None = ...) -> Value: ... + def select(self) -> None: ... + def level(self) -> int: ... + def static_link(self) -> Frame | None: ... + def language(self): ... + +# Blocks + +def block_for_pc(pc: int) -> Block | None: ... + +@final +class Block: + start: int + end: int + function: Symbol | None + superblock: Block | None + global_block: Block + static_block: Block | None + is_global: bool + is_static: bool + + def is_valid(self) -> bool: ... + def __iter__(self) -> BlockIterator: ... + +@final +class BlockIterator: + def is_valid(self) -> bool: ... + def __iter__(self: _typeshed.Self) -> _typeshed.Self: ... + def __next__(self) -> Symbol: ... + +# Symbols + +def lookup_symbol(name: str, block: Block | None = ..., domain: int = ...) -> tuple[Symbol | None, bool]: ... +def lookup_global_symbol(name: str, domain: int = ...) -> Symbol | None: ... +def lookup_static_symbol(name: str, domain: int = ...) -> Symbol | None: ... +def lookup_static_symbols(name: str, domain: int = ...) -> list[Symbol]: ... + +@final +class Symbol: + type: Type | None + symtab: Symtab + line: int + name: str + linkage_name: str + print_name: str + addr_class: int + needs_frame: bool + is_argument: bool + is_constant: bool + is_function: bool + is_variable: bool + is_artificial: bool + + def is_valid(self) -> bool: ... + def value(self, frame: Frame = ..., /) -> Value: ... + +SYMBOL_UNDEF_DOMAIN: Final = 0 +SYMBOL_VAR_DOMAIN: Final = 1 +SYMBOL_STRUCT_DOMAIN: Final = 2 +SYMBOL_MODULE_DOMAIN: Final = 3 +SYMBOL_LABEL_DOMAIN: Final = 4 +SYMBOL_COMMON_BLOCK_DOMAIN: Final = 5 +SYMBOL_TYPE_DOMAIN: Final = 6 +SYMBOL_FUNCTION_DOMAIN: Final = 7 + +SYMBOL_LOC_UNDEF: Final = 0 +SYMBOL_LOC_CONST: Final = 1 +SYMBOL_LOC_STATIC: Final = 2 +SYMBOL_LOC_REGISTER: Final = 3 +SYMBOL_LOC_ARG: Final = 4 +SYMBOL_LOC_REF_ARG: Final = 5 +SYMBOL_LOC_REGPARM_ADDR: Final = 6 +SYMBOL_LOC_LOCAL: Final = 7 +SYMBOL_LOC_TYPEDEF: Final = 8 +SYMBOL_LOC_LABEL: Final = 9 +SYMBOL_LOC_BLOCK: Final = 10 +SYMBOL_LOC_CONST_BYTES: Final = 11 +SYMBOL_LOC_UNRESOLVED: Final = 12 +SYMBOL_LOC_OPTIMIZED_OUT: Final = 13 +SYMBOL_LOC_COMPUTED: Final = 14 +SYMBOL_LOC_COMMON_BLOCK: Final = 15 + +# Symbol tables + +@final +class Symtab_and_line: + symtab: Symtab + pc: int + last: int + line: int + + def is_valid(self) -> bool: ... + +@final +class Symtab: + filename: str + objfile: Objfile + producer: str + + def is_valid(self) -> bool: ... + def fullname(self) -> str: ... + def global_block(self) -> Block: ... + def static_block(self) -> Block: ... + def linetable(self) -> LineTable: ... + +# Line Tables + +@final +class LineTableEntry: + line: int + pc: int + +@final +class LineTableIterator(Iterator[LineTableEntry]): + def __next__(self) -> LineTableEntry: ... + def is_valid(self) -> bool: ... + +@final +class LineTable: + def __iter__(self) -> LineTableIterator: ... + def line(self, line: int, /) -> tuple[LineTableEntry, ...]: ... + def has_line(self, line: int, /) -> bool: ... + def source_lines(self) -> list[int]: ... + def is_valid(self) -> bool: ... + +# Breakpoints + +@disjoint_base +class Breakpoint: + # The where="spec" form of __init__(). See py-breakpoints.c:bppy_init():keywords for the positional order. + @overload + def __init__( + self, + # where + spec: str = ..., + # options + type: int = ..., + wp_class: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + + # The where="location" form of __init__(). A watchpoint (`type=BP_WATCHPOINT`) cannot be created with this form. + # + # We exclude the `wp_class` (watchpoint class) option here, even though py-breakpoints.c accepts it. It doesn't make sense + # unless type==BP_WATCHPOINT, and is silently ignored in those cases; allowing it in those cases is likely an oversight, not + # an intentional allowance. + # + # We repeat this 7 times because the type system doesn't have simple a way for us to say "at least one of `function`, `label`, + # or `line`", so we must repeat it for each combination of the 3. + # + # The len=3 combination. + @overload + def __init__( + self, + *, + # where + source: str = ..., + function: str, + label: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + # The 3 len=2 combinations. + @overload + def __init__( + self, + *, + source: str = ..., + # where + label: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + label: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + # The 3 len=1 combinations. + @overload + def __init__( + self, + *, + source: str = ..., + # where + function: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + label: str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + source: str = ..., + # where + line: int | str, + # options + type: int = ..., + internal: bool = ..., + temporary: bool = ..., + qualified: bool = ..., + ) -> None: ... + + # Methods. + def stop(self) -> bool: ... + def is_valid(self) -> bool: ... + def delete(self) -> None: ... + + enabled: bool + silent: bool + pending: bool + thread: int | None + task: str | None + ignore_count: int + number: int + type: int + visible: bool + temporary: bool + hit_count: int + location: str | None + locations: Sequence[BreakpointLocation] + inferior: int | None + expression: str | None + condition: str | None + commands: str | None + +@final +class BreakpointLocation: + address: int + enabled: bool + fullname: str + function: str | None + owner: Breakpoint + source: tuple[str, int] + thread_groups: Sequence[int] + +BP_NONE: int +BP_BREAKPOINT: int +BP_HARDWARE_BREAKPOINT: int +BP_WATCHPOINT: int +BP_HARDWARE_WATCHPOINT: int +BP_READ_WATCHPOINT: int +BP_ACCESS_WATCHPOINT: int +BP_CATCHPOINT: int + +WP_READ: int +WP_WRITE: int +WP_ACCESS: int + +# Finish Breakpoints + +@disjoint_base +class FinishBreakpoint(Breakpoint): + return_value: Value | None + + def __init__(self, frame: Frame = ..., internal: bool = ...) -> None: ... + def out_of_scope(self) -> None: ... + +# Lazy strings + +class LazyString: + def value(self) -> Value: ... + + address: Value + length: int + encoding: str + type: Type + +# Architectures + +@type_check_only +class _Instruction(TypedDict): + addr: int + asm: str + length: int + +@final +class Architecture: + def name(self) -> str: ... + def disassemble(self, start_pc: int, end_pc: int = ..., count: int = ...) -> list[_Instruction]: ... + def integer_type(self, size: int, signed: bool = ...) -> Type: ... + def registers(self, reggroup: str = ...) -> RegisterDescriptorIterator: ... + def register_groups(self) -> RegisterGroupsIterator: ... + +# Registers + +@final +class RegisterDescriptor: + name: str + +@final +class RegisterDescriptorIterator(Iterator[RegisterDescriptor]): + def __next__(self) -> RegisterDescriptor: ... + def find(self, name: str) -> RegisterDescriptor | None: ... + +@final +class RegisterGroup: + name: str + +@final +class RegisterGroupsIterator(Iterator[RegisterGroup]): + def __next__(self) -> RegisterGroup: ... + +# Connections + +@disjoint_base +class TargetConnection: + def is_valid(self) -> bool: ... + + num: int + type: str + description: str + details: str | None + +@final +class RemoteTargetConnection(TargetConnection): + def send_packet(self, packet: str | bytes) -> bytes: ... + +# TUI Windows + +def register_window_type(name: str, factory: Callable[[TuiWindow], _Window]) -> None: ... + +class TuiWindow: + width: int + height: int + title: str + + def is_valid(self) -> bool: ... + def erase(self) -> None: ... + def write(self, string: str, full_window: bool = ...) -> None: ... + +@type_check_only +class _Window(Protocol): + def close(self) -> None: ... + def render(self) -> None: ... + def hscroll(self, num: int) -> None: ... + def vscroll(self, num: int) -> None: ... + def click(self, x: int, y: int, button: int) -> None: ... + +# Events +@disjoint_base +class Event: ... + +class ThreadEvent(Event): + inferior_thread: InferiorThread + +class ContinueEvent(ThreadEvent): ... + +class ExitedEvent(Event): + exit_code: int + inferior: Inferior + +class ThreadExitedEvent(ThreadEvent): ... + +class StopEvent(ThreadEvent): + details: dict[str, object] + +class BreakpointEvent(StopEvent): + breakpoints: Sequence[Breakpoint] + breakpoint: Breakpoint + +class NewObjFileEvent(Event): + new_objfile: Objfile + +class FreeObjFileEvent(Event): + objfile: Objfile + +class ClearObjFilesEvent(Event): + progspace: Progspace + +class NewProgspaceEvent(Event): ... +class FreeProgspaceEvent(Event): ... + +class SignalEvent(StopEvent): + stop_signal: str + +@type_check_only +class _InferiorCallEvent(Event): ... + +class InferiorCallPreEvent(_InferiorCallEvent): + ptid: InferiorThread + address: Value + +class InferiorCallPostEvent(_InferiorCallEvent): + ptid: InferiorThread + address: Value + +class MemoryChangedEvent(Event): + address: Value + length: int + +class RegisterChangedEvent(Event): + frame: Frame + regnum: str + +class NewInferiorEvent(Event): + inferior: Inferior + +class InferiorDeletedEvent(Event): + inferior: Inferior + +class NewThreadEvent(ThreadEvent): ... + +class GdbExitingEvent(Event): + exit_code: int + +class ConnectionEvent(Event): + connection: TargetConnection + +class ExecutableChangedEvent(Event): ... + +class TuiEnabledEvent(Event): + enabled: bool + +_ET = TypeVar("_ET", bound=Event | Breakpoint | None) + +@final +class EventRegistry(Generic[_ET]): + def connect(self, object: Callable[[_ET], object], /) -> None: ... + def disconnect(self, object: Callable[[_ET], object], /) -> None: ... + +class ValuePrinter: ... + +def blocked_signals(): ... +def notify_mi(name: str, data: dict[str, object] | None = None): ... +def interrupt(): ... +def execute_mi(command: str, *args: str) -> dict[str, object]: ... diff --git a/stubs/gdb/gdb/dap/__init__.pyi b/stubs/gdb/gdb/dap/__init__.pyi new file mode 100644 index 000000000000..9c9c1931ee7e --- /dev/null +++ b/stubs/gdb/gdb/dap/__init__.pyi @@ -0,0 +1,21 @@ +from . import ( + breakpoint as breakpoint, + bt as bt, + evaluate as evaluate, + launch as launch, + locations as locations, + memory as memory, + modules as modules, + next as next, + pause as pause, + scopes as scopes, + sources as sources, + startup as startup, + threads as threads, +) +from .server import Server as Server + +def pre_command_loop() -> None: ... +def run() -> None: ... + +session_started: bool diff --git a/stubs/gdb/gdb/dap/breakpoint.pyi b/stubs/gdb/gdb/dap/breakpoint.pyi new file mode 100644 index 000000000000..6e96978e2f43 --- /dev/null +++ b/stubs/gdb/gdb/dap/breakpoint.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Sequence +from contextlib import AbstractContextManager +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +from .sources import Source + +@type_check_only +class _SourceBreakpoint(TypedDict): + source: str + line: int + condition: NotRequired[str | None] + hitCondition: NotRequired[str | None] + logMessage: NotRequired[str | None] + +@type_check_only +class _ExceptionFilterOptions(TypedDict): + filderId: str + condition: NotRequired[str | None] + +@type_check_only +class _BreakpointDescriptor(TypedDict): + id: int + verified: bool + reason: NotRequired[str] # only present when verified is False. Possibly only literal "pending" or "failed" + message: NotRequired[str] # only present when reason == "failed" + source: NotRequired[Source] + line: NotRequired[int] + instructionReference: NotRequired[str] + +@type_check_only +class _SetBreakpointResult(TypedDict): + breakpoints: list[_BreakpointDescriptor] + +# frozenset entries are tuples from _SourceBreakpoint.items() or _ExceptionFilterOptions.items() +breakpoint_map: dict[str, dict[frozenset[Incomplete], gdb.Breakpoint]] + +def suppress_new_breakpoint_event() -> AbstractContextManager[None]: ... +def set_breakpoint(*, source: Source, breakpoints: Sequence[_SourceBreakpoint] = (), **args: Unused) -> _SetBreakpointResult: ... +def set_fn_breakpoint(*, breakpoints: Sequence[_SourceBreakpoint], **args: Unused) -> _SetBreakpointResult: ... +def set_insn_breakpoints( + *, breakpoints: Sequence[_SourceBreakpoint], offset: int | None = None, **args: Unused +) -> _SetBreakpointResult: ... +def set_exception_breakpoints( + *, filters: Sequence[str], filterOptions: Sequence[_ExceptionFilterOptions] = (), **args: Unused +) -> _SetBreakpointResult: ... diff --git a/stubs/gdb/gdb/dap/bt.pyi b/stubs/gdb/gdb/dap/bt.pyi new file mode 100644 index 000000000000..0127cfbbaa0a --- /dev/null +++ b/stubs/gdb/gdb/dap/bt.pyi @@ -0,0 +1,49 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +from .sources import Source +from .varref import _ValueFormat + +@type_check_only +class _StackFrameFormat(_ValueFormat, total=False): + parameters: bool + parameterTypes: bool + parameterNames: bool + parameterValues: bool + line: bool + module: bool + includeAll: bool + +@type_check_only +class _StackFrame(TypedDict): + id: int + name: str + line: int + column: int + instructionPointerReference: str + moduleId: NotRequired[str | None] + source: NotRequired[Source] + +@type_check_only +class _StackTraceResult(TypedDict): + stackFrames: list[_StackFrame] + +def check_stack_frame( + *, + # From source: + # Note that StackFrameFormat extends ValueFormat, which is why + # "hex" appears here. + hex: bool = False, + parameters: bool = False, + parameterTypes: bool = False, + parameterNames: bool = False, + parameterValues: bool = False, + line: bool = False, + module: bool = False, + includeAll: bool = False, + **rest: Unused, +) -> _StackFrameFormat: ... +def stacktrace( + *, levels: int = 0, startFrame: int = 0, threadId: int, format: _StackFrameFormat | None = None, **extra: Unused +) -> _StackTraceResult: ... diff --git a/stubs/gdb/gdb/dap/disassemble.pyi b/stubs/gdb/gdb/dap/disassemble.pyi new file mode 100644 index 000000000000..387dbaf4b9bc --- /dev/null +++ b/stubs/gdb/gdb/dap/disassemble.pyi @@ -0,0 +1,22 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +from .sources import Source + +@type_check_only +class _Instruction(TypedDict): + address: str + instruction: str + instructionBytes: str + symbol: NotRequired[str] # only set if there's a corresponding label + line: NotRequired[int] # only set if source is available + location: NotRequired[Source] # only set if source is available + +@type_check_only +class _DisassembleResult(TypedDict): + instructions: list[_Instruction] + +def disassemble( + *, memoryReference: str, offset: int = 0, instructionOffset: int = 0, instructionCount: int, **extra: Unused +) -> _DisassembleResult: ... diff --git a/stubs/gdb/gdb/dap/evaluate.pyi b/stubs/gdb/gdb/dap/evaluate.pyi new file mode 100644 index 000000000000..04cd64085758 --- /dev/null +++ b/stubs/gdb/gdb/dap/evaluate.pyi @@ -0,0 +1,31 @@ +from _typeshed import Unused +from typing import Literal, TypedDict, type_check_only + +import gdb + +from .varref import VariableReference, _ValueFormat, _VariableReferenceDescriptor + +class EvaluateResult(VariableReference): + def __init__(self, value: gdb.Value) -> None: ... + +@type_check_only +class _VariablesResult(TypedDict): + variables: list[_VariableReferenceDescriptor] + +def eval_request( + *, + expression: str, + frameId: int | None = None, + context: Literal["watch", "variables", "hover", "repl"] = "variables", + format: _ValueFormat | None = None, + **args: Unused, +) -> _VariableReferenceDescriptor: ... +def variables( + *, variablesReference: int, start: int = 0, count: int = 0, format: _ValueFormat | None = None, **args: Unused +) -> _VariablesResult: ... +def set_expression( + *, expression: str, value: str, frameId: int | None = None, format: _ValueFormat | None = None, **args: Unused +) -> _VariableReferenceDescriptor: ... +def set_variable( + *, variablesReference: int, name: str, value: str, format: _ValueFormat | None = None, **args: Unused +) -> _VariableReferenceDescriptor: ... diff --git a/stubs/gdb/gdb/dap/events.pyi b/stubs/gdb/gdb/dap/events.pyi new file mode 100644 index 000000000000..7cd269266eff --- /dev/null +++ b/stubs/gdb/gdb/dap/events.pyi @@ -0,0 +1,12 @@ +import gdb + +inferior_running: bool + +def send_process_event_once() -> None: ... +def expect_process(reason: str) -> None: ... +def thread_event(event: gdb.ThreadEvent, reason: str) -> None: ... +def expect_stop(reason: str) -> None: ... +def exec_and_expect_stop(cmd: str, expected_pause: bool = False) -> None: ... + +# Map from gdb stop reasons to DAP stop reasons. +stop_reason_map: dict[str, str] diff --git a/stubs/gdb/gdb/dap/frames.pyi b/stubs/gdb/gdb/dap/frames.pyi new file mode 100644 index 000000000000..3c7d516e36c6 --- /dev/null +++ b/stubs/gdb/gdb/dap/frames.pyi @@ -0,0 +1,7 @@ +from collections.abc import Generator + +import gdb + +def frame_for_id(id: int) -> gdb.Frame: ... +def select_frame(id: int) -> None: ... +def dap_frame_generator(frame_low: int, levels: int, include_all: bool) -> Generator[tuple[int, gdb.Frame]]: ... diff --git a/stubs/gdb/gdb/dap/io.pyi b/stubs/gdb/gdb/dap/io.pyi new file mode 100644 index 000000000000..2cf4f182f395 --- /dev/null +++ b/stubs/gdb/gdb/dap/io.pyi @@ -0,0 +1,16 @@ +from _typeshed import SupportsFlush, SupportsRead, SupportsReadline, SupportsWrite +from typing import Any, type_check_only + +import gdb + +from .server import _JSONValue +from .startup import DAPQueue + +@type_check_only +class _SupportsReadAndReadlineBytes(SupportsRead[bytes], SupportsReadline[bytes]): ... + +@type_check_only +class _SupportsWriteAndFlushBytes(SupportsWrite[bytes], SupportsFlush): ... + +def read_json(stream: _SupportsReadAndReadlineBytes) -> Any: ... # returns result of json.loads +def start_json_writer(stream: _SupportsWriteAndFlushBytes, queue: DAPQueue[_JSONValue]) -> gdb.Thread: ... diff --git a/stubs/gdb/gdb/dap/launch.pyi b/stubs/gdb/gdb/dap/launch.pyi new file mode 100644 index 000000000000..5d573114df88 --- /dev/null +++ b/stubs/gdb/gdb/dap/launch.pyi @@ -0,0 +1,14 @@ +from _typeshed import Unused +from collections.abc import Mapping, Sequence + +def launch( + *, + program: str | None = None, + cwd: str | None = None, + args: Sequence[str] = (), + env: Mapping[str, str] | None = None, + stopAtBeginningOfMainSubprogram: bool = False, + **extra: Unused, +): ... +def attach(*, program: str | None = None, pid: int | None = None, target: str | None = None, **args: Unused) -> None: ... +def config_done(**args: Unused) -> None: ... diff --git a/stubs/gdb/gdb/dap/locations.pyi b/stubs/gdb/gdb/dap/locations.pyi new file mode 100644 index 000000000000..da63e65c83ea --- /dev/null +++ b/stubs/gdb/gdb/dap/locations.pyi @@ -0,0 +1,16 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only + +from .sources import Source + +@type_check_only +class _Line(TypedDict): + line: int + +@type_check_only +class _BreakpointLocationsResult(TypedDict): + breakpoints: list[_Line] + +def breakpoint_locations( + *, source: Source, line: int, endLine: int | None = None, **extra: Unused +) -> _BreakpointLocationsResult: ... diff --git a/stubs/gdb/gdb/dap/memory.pyi b/stubs/gdb/gdb/dap/memory.pyi new file mode 100644 index 000000000000..b6a33a3d1262 --- /dev/null +++ b/stubs/gdb/gdb/dap/memory.pyi @@ -0,0 +1,10 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only + +@type_check_only +class _ReadMemoryResult(TypedDict): + address: str + data: str + +def read_memory(*, memoryReference: str, offset: int = 0, count: int, **extra: Unused) -> _ReadMemoryResult: ... +def write_memory(*, memoryReference: str, offset: int = 0, data: str, **extra: Unused): ... diff --git a/stubs/gdb/gdb/dap/modules.pyi b/stubs/gdb/gdb/dap/modules.pyi new file mode 100644 index 000000000000..eae61cfb47da --- /dev/null +++ b/stubs/gdb/gdb/dap/modules.pyi @@ -0,0 +1,21 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +@type_check_only +class _Module(TypedDict): + id: str | None + name: str | None + path: NotRequired[str | None] + +@type_check_only +class _ModulesResult(TypedDict): + modules: list[_Module] + totalModules: int + +def module_id(objfile: gdb.Objfile) -> str | None: ... +def is_module(objfile: gdb.Objfile) -> bool: ... +def make_module(objf: gdb.Objfile) -> _Module: ... +def modules(*, startModule: int = 0, moduleCount: int = 0, **args: Unused) -> _ModulesResult: ... diff --git a/stubs/gdb/gdb/dap/next.pyi b/stubs/gdb/gdb/dap/next.pyi new file mode 100644 index 000000000000..1418de48f8da --- /dev/null +++ b/stubs/gdb/gdb/dap/next.pyi @@ -0,0 +1,13 @@ +from _typeshed import Unused +from typing import Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _ContinueRequestResult(TypedDict): + allThreadsContinued: bool + +_Granularity: TypeAlias = Literal["statement", "instruction"] + +def next(*, threadId: int, singleThread: bool = False, granularity: _Granularity = "statement", **args: Unused) -> None: ... +def step_in(*, threadId: int, singleThread: bool = False, granularity: _Granularity = "statement", **args: Unused) -> None: ... +def step_out(*, threadId: int, singleThread: bool = False, **args: Unused): ... +def continue_request(*, threadId: int, singleThread: bool = False, **args: Unused) -> _ContinueRequestResult: ... diff --git a/stubs/gdb/gdb/dap/pause.pyi b/stubs/gdb/gdb/dap/pause.pyi new file mode 100644 index 000000000000..6343b7b03156 --- /dev/null +++ b/stubs/gdb/gdb/dap/pause.pyi @@ -0,0 +1,3 @@ +from _typeshed import Unused + +def pause(**args: Unused) -> None: ... diff --git a/stubs/gdb/gdb/dap/scopes.pyi b/stubs/gdb/gdb/dap/scopes.pyi new file mode 100644 index 000000000000..c5421b6f747f --- /dev/null +++ b/stubs/gdb/gdb/dap/scopes.pyi @@ -0,0 +1,47 @@ +from _typeshed import Unused +from collections.abc import Iterable +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +from ..FrameDecorator import FrameDecorator, SymValueWrapper +from .varref import BaseReference, _ReferenceDescriptor + +frame_to_scope: dict[int, _ScopeReference] + +@type_check_only +class _ScopeReferenceDescriptor(_ReferenceDescriptor): + presentationHint: str + expensive: bool + namedVariables: int + line: NotRequired[int] + +@type_check_only +class _ScopesResult(TypedDict): + scopes: list[_ScopeReferenceDescriptor] + +def clear_scopes(event: Unused) -> None: ... +def set_finish_value(val: gdb.Value) -> None: ... +def symbol_value(sym: SymValueWrapper, frame: FrameDecorator) -> tuple[str, gdb.Value]: ... + +class _ScopeReference(BaseReference): + hint: str + frame: FrameDecorator + inf_frame: gdb.Frame + function: str | None + line: int | None + var_list: tuple[SymValueWrapper, ...] + def __init__(self, name: str, hint: str, frame: FrameDecorator, var_list: Iterable[SymValueWrapper]) -> None: ... + def to_object(self) -> _ScopeReferenceDescriptor: ... + def has_children(self) -> bool: ... + def child_count(self) -> int: ... + # note: parameter named changed from 'index' to 'idx' + def fetch_one_child(self, idx: int) -> tuple[str, gdb.Value]: ... + +class _FinishScopeReference(_ScopeReference): ... + +class _RegisterReference(_ScopeReference): + def __init__(self, name: str, frame: FrameDecorator) -> None: ... + +def scopes(*, frameId: int, **extra: Unused) -> _ScopesResult: ... diff --git a/stubs/gdb/gdb/dap/server.pyi b/stubs/gdb/gdb/dap/server.pyi new file mode 100644 index 000000000000..8d9f49c16193 --- /dev/null +++ b/stubs/gdb/gdb/dap/server.pyi @@ -0,0 +1,77 @@ +import threading +from _typeshed import Incomplete, SupportsReadline, Unused +from collections.abc import Callable +from contextlib import AbstractContextManager +from typing import Any, Generic, TypeAlias, TypeVar, type_check_only + +from .io import _SupportsReadAndReadlineBytes, _SupportsWriteAndFlushBytes +from .startup import DAPQueue + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) + +_RequestID: TypeAlias = int +_EventBody: TypeAlias = Any # arbitrary object, implicitly constrained by the event being sent +_JSONValue: TypeAlias = Any # any object that can be handled by json.dumps/json.loads + +class NotStoppedException(Exception): ... + +class CancellationHandler: + lock: threading.Lock + reqs: list[_RequestID] + in_flight_dap_thread: _RequestID | None + in_flight_gdb_thread: _RequestID | None + def starting(self, req: _RequestID) -> None: ... + def done(self, req: _RequestID) -> None: ... # req argument is not used + def cancel(self, req: _RequestID) -> None: ... + def interruptable_region(self, req: _RequestID | None) -> AbstractContextManager[None]: ... + +class Server: + in_stream: _SupportsReadAndReadlineBytes + out_stream: _SupportsWriteAndFlushBytes + child_stream: SupportsReadline[str] + delay_events: list[tuple[str, _EventBody]] + write_queue: DAPQueue[_JSONValue | None] + read_queue: DAPQueue[_JSONValue | None] + done: bool + canceller: CancellationHandler + config: dict[str, Incomplete] + def __init__( + self, + in_stream: _SupportsReadAndReadlineBytes, + out_stream: _SupportsWriteAndFlushBytes, + child_stream: SupportsReadline[str], + ) -> None: ... + def main_loop(self) -> None: ... + def send_event(self, event: str, body: _EventBody | None = None) -> None: ... + def send_event_later(self, event: str, body: _EventBody | None = None) -> None: ... + def shutdown(self) -> None: ... + +def send_event(event: str, body: _EventBody | None = None) -> None: ... + +@type_check_only +class _Wrapper: + def __call__(self, func: _F) -> _F: ... + +def request(name: str, *, response: bool = True, on_dap_thread: bool = False, expect_stopped: bool = True) -> _Wrapper: ... +def capability(name: str, value: bool = True) -> _Wrapper: ... +def client_bool_capability(name: str) -> bool: ... +def initialize(**args) -> dict[str, bool]: ... # args is arbitrary values for Server.config +def terminate(**args: Unused) -> None: ... +def disconnect(*, terminateDebuggee: bool = False, **args: Unused): ... +def cancel(**args: Unused) -> None: ... + +class Invoker: + cmd: str + def __init__(self, cmd: str) -> None: ... + def __call__(self) -> None: ... + +class Cancellable(Generic[_T]): + fn: Callable[[], _T] + result_q: DAPQueue[_T] | None + req: _RequestID + def __init__(self, fn: Callable[[], _T], result_q: DAPQueue[_T] | None = None) -> None: ... + def __call__(self) -> None: ... + +def send_gdb(cmd: str | Callable[[], object]) -> None: ... +def send_gdb_with_response(fn: str | Callable[[], _T]) -> _T: ... diff --git a/stubs/gdb/gdb/dap/sources.pyi b/stubs/gdb/gdb/dap/sources.pyi new file mode 100644 index 000000000000..7adee35f2c9b --- /dev/null +++ b/stubs/gdb/gdb/dap/sources.pyi @@ -0,0 +1,23 @@ +from _typeshed import Unused +from typing import TypeAlias, TypedDict, type_check_only + +_SourceReferenceID: TypeAlias = int + +@type_check_only +class Source(TypedDict, total=False): + name: str + path: str + sourceReference: _SourceReferenceID + +@type_check_only +class _LoadSourcesResult(TypedDict): + sources: list[Source] + +@type_check_only +class _SourceResult(TypedDict): + content: str + +def make_source(fullname: str, filename: str | None) -> Source: ... +def decode_source(source: Source) -> _SourceReferenceID: ... +def loaded_sources(**extra: Unused) -> _LoadSourcesResult: ... +def source(*, source: Source | None = None, sourceReference: _SourceReferenceID, **extra: Unused) -> _SourceResult: ... diff --git a/stubs/gdb/gdb/dap/startup.pyi b/stubs/gdb/gdb/dap/startup.pyi new file mode 100644 index 000000000000..107a408901d1 --- /dev/null +++ b/stubs/gdb/gdb/dap/startup.pyi @@ -0,0 +1,43 @@ +import enum +import io +import queue +import threading +from collections.abc import Callable, Iterable +from typing import Any, ClassVar, TypeAlias, TypeVar + +import gdb + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) + +DAPQueue: TypeAlias = queue.SimpleQueue[_T] + +class DAPException(Exception): ... + +def parse_and_eval(expression: str, global_context: bool = False) -> gdb.Value: ... + +# target and args are passed to gdb.Thread +def start_thread(name: str, target: Callable[..., object], args: Iterable[Any] = ()) -> gdb.Thread: ... +def start_dap(target: Callable[..., object]) -> None: ... +def in_gdb_thread(func: _F) -> _F: ... +def in_dap_thread(func: _F) -> _F: ... + +class LogLevel(enum.IntEnum): + DEFAULT = 1 + FULL = 2 + +class LogLevelParam(gdb.Parameter): + def __init__(self) -> None: ... + +class LoggingParam(gdb.Parameter): + lock: ClassVar[threading.Lock] + log_file: io.TextIOWrapper | None + def __init__(self) -> None: ... + def get_set_string(self) -> str: ... + +dap_log: LoggingParam + +def log(something: object, level: LogLevel = LogLevel.DEFAULT) -> None: ... +def thread_log(something: object, level: LogLevel = LogLevel.DEFAULT) -> None: ... +def log_stack(level: LogLevel = LogLevel.DEFAULT) -> None: ... +def exec_and_log(cmd: str) -> None: ... diff --git a/stubs/gdb/gdb/dap/state.pyi b/stubs/gdb/gdb/dap/state.pyi new file mode 100644 index 000000000000..1d80080e1531 --- /dev/null +++ b/stubs/gdb/gdb/dap/state.pyi @@ -0,0 +1 @@ +def set_thread(thread_id: int) -> None: ... diff --git a/stubs/gdb/gdb/dap/threads.pyi b/stubs/gdb/gdb/dap/threads.pyi new file mode 100644 index 000000000000..3de0ccff3b13 --- /dev/null +++ b/stubs/gdb/gdb/dap/threads.pyi @@ -0,0 +1,14 @@ +from _typeshed import Unused +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +@type_check_only +class _Thread(TypedDict): + id: int + name: NotRequired[str] + +@type_check_only +class _ThreadsResult(TypedDict): + threads: list[_Thread] + +def threads(**args: Unused) -> _ThreadsResult: ... diff --git a/stubs/gdb/gdb/dap/typecheck.pyi b/stubs/gdb/gdb/dap/typecheck.pyi new file mode 100644 index 000000000000..37993cca7a34 --- /dev/null +++ b/stubs/gdb/gdb/dap/typecheck.pyi @@ -0,0 +1,6 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def type_check(func: _F) -> _F: ... diff --git a/stubs/gdb/gdb/dap/varref.pyi b/stubs/gdb/gdb/dap/varref.pyi new file mode 100644 index 000000000000..83d700607585 --- /dev/null +++ b/stubs/gdb/gdb/dap/varref.pyi @@ -0,0 +1,70 @@ +import abc +from _typeshed import Unused +from collections import defaultdict +from collections.abc import Generator +from contextlib import AbstractContextManager +from typing import TypedDict, type_check_only +from typing_extensions import NotRequired + +import gdb + +@type_check_only +class _ValueFormat(TypedDict, total=False): + hex: bool + +@type_check_only +class _ReferenceDescriptor(TypedDict): + # Result of BaseReference.to_object() + variableReference: int + name: NotRequired[str] + +@type_check_only +class _VariableReferenceDescriptor(_ReferenceDescriptor): + # Result of VariableReference.to_object() + indexedVariables: NotRequired[int] + namedVariables: NotRequired[int] + memoryReference: NotRequired[str] + type: NotRequired[str] + # Below key name set by VariableReference.result_name + # Could be modelled with extra_items=str if PEP 728 is accepted. + value: NotRequired[str] + +all_variables: list[BaseReference] + +def clear_vars(event: Unused) -> None: ... +def apply_format(value_format: _ValueFormat | None) -> AbstractContextManager[None]: ... + +class BaseReference(abc.ABC): + ref: int + name: str + children: list[VariableReference | None] | None + by_name: dict[str, VariableReference] + name_counts: defaultdict[str, int] + def __init__(self, name: str) -> None: ... + def to_object(self) -> _ReferenceDescriptor: ... + @abc.abstractmethod + def has_children(self) -> bool: ... + def reset_children(self): ... + @abc.abstractmethod + def fetch_one_child(self, index: int) -> tuple[str, gdb.Value]: ... + @abc.abstractmethod + def child_count(self) -> int: ... + def fetch_children(self, start: int, count: int) -> Generator[VariableReference]: ... + def find_child_by_name(self, name: str) -> VariableReference: ... + +class VariableReference(BaseReference): + result_name: str + value: gdb.Value + child_cache: list[tuple[int | str, gdb.Value]] | None + count: int | None + printer: gdb._PrettyPrinter + def __init__(self, name: str, value: gdb.Value, result_name: str = "value") -> None: ... + def assign(self, value: gdb.Value) -> None: ... + def has_children(self) -> bool: ... + def cache_children(self) -> list[tuple[int | str, gdb.Value]]: ... + def child_count(self) -> int: ... + def to_object(self) -> _VariableReferenceDescriptor: ... + # note: parameter named changed from 'index' to 'idx' + def fetch_one_child(self, idx: int) -> tuple[str, gdb.Value]: ... + +def find_variable(ref: int) -> BaseReference: ... diff --git a/stubs/gdb/gdb/disassembler.pyi b/stubs/gdb/gdb/disassembler.pyi new file mode 100644 index 000000000000..e878264cfef5 --- /dev/null +++ b/stubs/gdb/gdb/disassembler.pyi @@ -0,0 +1,60 @@ +from collections.abc import Sequence +from typing import Final, final +from typing_extensions import disjoint_base + +import gdb +from gdb import Architecture, Progspace + +class Disassembler: + def __init__(self, name: str) -> None: ... + def __call__(self, info): ... + +@disjoint_base +class DisassembleInfo: + address: int + architecture: Architecture + progspace: Progspace + def __init__(self, info: DisassembleInfo) -> None: ... + def address_part(self, address: int) -> DisassemblerAddressPart: ... + def is_valid(self) -> bool: ... + def read_memory(self, len: int, offset: int = 0): ... + def text_part(self, style: int, string: str) -> DisassemblerTextPart: ... + +class DisassemblerPart: + def __init__(self, /, *args, **kwargs) -> None: ... + +@final +class DisassemblerAddressPart(DisassemblerPart): + address: int + string: str + +@final +class DisassemblerTextPart(DisassemblerPart): + string: str + style: int + +@final +class DisassemblerResult: + def __init__(self, length: int, string: str | None = None, parts: Sequence[DisassemblerPart] | None = None) -> None: ... + length: int + parts: Sequence[DisassemblerPart] + string: str + +STYLE_TEXT: Final = 0 +STYLE_MNEMONIC: Final = 1 +STYLE_SUB_MNEMONIC: Final = 2 +STYLE_ASSEMBLER_DIRECTIVE: Final = 3 +STYLE_REGISTER: Final = 4 +STYLE_IMMEDIATE: Final = 5 +STYLE_ADDRESS: Final = 6 +STYLE_ADDRESS_OFFSET: Final = 7 +STYLE_SYMBOL: Final = 8 +STYLE_COMMENT_START: Final = 9 + +def builtin_disassemble(info: DisassembleInfo) -> None: ... + +class maint_info_py_disassemblers_cmd(gdb.Command): + def __init__(self) -> None: ... + def invoke(self, args, from_tty): ... + +def register_disassembler(disassembler: type[Disassembler], architecture: str | None = None): ... diff --git a/stubs/gdb/gdb/events.pyi b/stubs/gdb/gdb/events.pyi new file mode 100644 index 000000000000..6160804bf485 --- /dev/null +++ b/stubs/gdb/gdb/events.pyi @@ -0,0 +1,25 @@ +import gdb + +cont: gdb.EventRegistry[gdb.ContinueEvent] +exited: gdb.EventRegistry[gdb.ExitedEvent] +thread_exited: gdb.EventRegistry[gdb.ThreadExitedEvent] +stop: gdb.EventRegistry[gdb.StopEvent] +new_objfile: gdb.EventRegistry[gdb.NewObjFileEvent] +free_objfile: gdb.EventRegistry[gdb.FreeObjFileEvent] +clear_objfiles: gdb.EventRegistry[gdb.ClearObjFilesEvent] +new_progspace: gdb.EventRegistry[gdb.NewProgspaceEvent] +free_progspace: gdb.EventRegistry[gdb.FreeProgspaceEvent] +inferior_call: gdb.EventRegistry[gdb._InferiorCallEvent] +memory_changed: gdb.EventRegistry[gdb.MemoryChangedEvent] +register_changed: gdb.EventRegistry[gdb.RegisterChangedEvent] +breakpoint_created: gdb.EventRegistry[gdb.Breakpoint] +breakpoint_modified: gdb.EventRegistry[gdb.Breakpoint] +breakpoint_deleted: gdb.EventRegistry[gdb.Breakpoint] +before_prompt: gdb.EventRegistry[None] +new_inferior: gdb.EventRegistry[gdb.NewInferiorEvent] +inferior_deleted: gdb.EventRegistry[gdb.InferiorDeletedEvent] +new_thread: gdb.EventRegistry[gdb.NewThreadEvent] +gdb_exiting: gdb.EventRegistry[gdb.GdbExitingEvent] +connection_removed: gdb.EventRegistry[gdb.ConnectionEvent] +executable_changed: gdb.EventRegistry[gdb.ExecutableChangedEvent] +tui_enabled: gdb.EventRegistry[gdb.TuiEnabledEvent] diff --git a/stubs/gdb/gdb/missing_debug.pyi b/stubs/gdb/gdb/missing_debug.pyi new file mode 100644 index 000000000000..1b9d5988f954 --- /dev/null +++ b/stubs/gdb/gdb/missing_debug.pyi @@ -0,0 +1,8 @@ +import gdb +from gdb import Progspace +from gdb.missing_files import MissingFileHandler + +class MissingDebugHandler(MissingFileHandler): + def __call__(self, objfile: gdb.Objfile) -> bool | str | None: ... + +def register_handler(locus: Progspace | None, handler: MissingDebugHandler, replace: bool = False) -> None: ... diff --git a/stubs/gdb/gdb/missing_files.pyi b/stubs/gdb/gdb/missing_files.pyi new file mode 100644 index 000000000000..fbc6f113167d --- /dev/null +++ b/stubs/gdb/gdb/missing_files.pyi @@ -0,0 +1,13 @@ +from typing import Literal + +from gdb import Progspace + +class MissingFileHandler: + @property + def name(self) -> str: ... + enabled: bool + def __init__(self, name: str) -> None: ... + +def register_handler( + handler_type: Literal["debug", "objfile"], locus: Progspace | None, handler: MissingFileHandler, replace: bool = False +) -> None: ... diff --git a/stubs/gdb/gdb/missing_objfile.pyi b/stubs/gdb/gdb/missing_objfile.pyi new file mode 100644 index 000000000000..8e50b1c1baa5 --- /dev/null +++ b/stubs/gdb/gdb/missing_objfile.pyi @@ -0,0 +1,7 @@ +from gdb import Progspace +from gdb.missing_files import MissingFileHandler + +class MissingObjfileHandler(MissingFileHandler): + def __call__(self, buildid: str, filename: str) -> bool | str | None: ... + +def register_handler(locus: Progspace | None, handler: MissingObjfileHandler, replace: bool = False) -> None: ... diff --git a/stubs/gdb/gdb/printing.pyi b/stubs/gdb/gdb/printing.pyi new file mode 100644 index 000000000000..f3348f1569ae --- /dev/null +++ b/stubs/gdb/gdb/printing.pyi @@ -0,0 +1,56 @@ +from collections.abc import Callable, Iterable + +import gdb +from gdb import _PrettyPrinterLookupFunction + +class PrettyPrinter: + name: str + subprinters: list[SubPrettyPrinter] | None + enabled: bool + + def __init__(self, name: str, subprinters: Iterable[SubPrettyPrinter] | None = ...) -> None: ... + def __call__(self, val: gdb.Value) -> gdb._PrettyPrinter | None: ... + +class SubPrettyPrinter: + name: str + enabled: bool + + def __init__(self, name: str) -> None: ... + +class RegexpCollectionPrettyPrinter(PrettyPrinter): + def __init__(self, name: str) -> None: ... + def add_printer(self, name: str, regexp: str, gen_printer: _PrettyPrinterLookupFunction) -> None: ... + +class FlagEnumerationPrinter(PrettyPrinter): + def __init__(self, enum_type: str) -> None: ... + +class NoOpArrayPrinter(gdb.ValuePrinter): + def __init__(self, ty, value) -> None: ... + def child(self, i): ... + def children(self): ... + def display_hint(self): ... + def num_children(self): ... + def to_string(self) -> str: ... + +class NoOpPointerReferencePrinter(gdb.ValuePrinter): + def __init__(self, value) -> None: ... + def child(self, i): ... + def children(self): ... + def num_children(self): ... + def to_string(self) -> str: ... + +class NoOpScalarPrinter(gdb.ValuePrinter): + def __init__(self, value) -> None: ... + def to_string(self) -> str: ... + +class NoOpStructPrinter(gdb.ValuePrinter): + def __init__(self, ty, value) -> None: ... + def children(self): ... + def to_string(self) -> str: ... + +def register_pretty_printer( + obj: gdb.Objfile | gdb.Progspace | None, + printer: PrettyPrinter | Callable[[gdb.Value], gdb._PrettyPrinter | None], + replace: bool = ..., +) -> None: ... +def make_visualizer(value: gdb.Value): ... diff --git a/stubs/gdb/gdb/prompt.pyi b/stubs/gdb/gdb/prompt.pyi new file mode 100644 index 000000000000..5690907e81e6 --- /dev/null +++ b/stubs/gdb/gdb/prompt.pyi @@ -0,0 +1 @@ +def substitute_prompt(prompt: str) -> str: ... diff --git a/stubs/gdb/gdb/types.pyi b/stubs/gdb/gdb/types.pyi new file mode 100644 index 000000000000..ec34ea3e606e --- /dev/null +++ b/stubs/gdb/gdb/types.pyi @@ -0,0 +1,30 @@ +from collections.abc import Iterator +from typing import Protocol, type_check_only + +import gdb + +def get_basic_type(type_: gdb.Type) -> gdb.Type: ... +def has_field(type_: gdb.Type, field: str) -> bool: ... +def make_enum_dict(enum_type: gdb.Type) -> dict[str, int]: ... +def deep_items(type_: gdb.Type) -> Iterator[tuple[str, gdb.Field]]: ... +def get_type_recognizers() -> list[_TypeRecognizer]: ... +def apply_type_recognizers(recognizers: list[_TypeRecognizer], type_obj: gdb.Type) -> str | None: ... +def register_type_printer(locus: gdb.Objfile | gdb.Progspace | None, printer: _TypePrinter) -> None: ... + +@type_check_only +class _TypePrinter(Protocol): + enabled: bool + name: str + + def instantiate(self) -> _TypeRecognizer | None: ... + +@type_check_only +class _TypeRecognizer(Protocol): + def recognize(self, type: gdb.Type, /) -> str | None: ... + +class TypePrinter: + enabled: bool + name: str + + def __init__(self, name: str) -> None: ... + def instantiate(self) -> _TypeRecognizer | None: ... diff --git a/stubs/gdb/gdb/unwinder.pyi b/stubs/gdb/gdb/unwinder.pyi new file mode 100644 index 000000000000..60a5f84d6dec --- /dev/null +++ b/stubs/gdb/gdb/unwinder.pyi @@ -0,0 +1,20 @@ +import gdb + +class FrameId: + def __init__(self, sp: gdb.Value | int, pc: gdb.Value | int, special: gdb.Value | int | None = None) -> None: ... + @property + def pc(self) -> gdb.Value | int: ... + @property + def sp(self) -> gdb.Value | int: ... + @property + def special(self) -> gdb.Value | int | None: ... + +class Unwinder: + @property + def name(self) -> str: ... + enabled: bool + + def __init__(self, name: str) -> None: ... + def __call__(self, pending_frame: gdb.PendingFrame) -> gdb.UnwindInfo | None: ... + +def register_unwinder(locus: gdb.Objfile | gdb.Progspace | None, unwinder: gdb._Unwinder, replace: bool = ...) -> None: ... diff --git a/stubs/gdb/gdb/xmethod.pyi b/stubs/gdb/gdb/xmethod.pyi new file mode 100644 index 000000000000..31ff16523322 --- /dev/null +++ b/stubs/gdb/gdb/xmethod.pyi @@ -0,0 +1,47 @@ +from collections.abc import Sequence +from re import Pattern +from typing import Protocol, type_check_only + +import gdb + +def register_xmethod_matcher( + locus: gdb.Objfile | gdb.Progspace | None, matcher: XMethodMatcher, replace: bool = False +) -> None: ... + +@type_check_only +class _XMethod(Protocol): + name: str + enabled: bool + +class XMethod: + name: str + enabled: bool + + def __init__(self, name: str) -> None: ... + +class XMethodWorker: + def get_arg_types(self) -> Sequence[gdb.Type] | gdb.Type | None: ... + def get_result_type(self, *args: gdb.Value) -> gdb.Type: ... + def __call__(self, *args: gdb.Value) -> object: ... + +class XMethodMatcher: + name: str + enabled: bool + methods: list[_XMethod] | None + + def __init__(self, name: str) -> None: ... + def match(self, class_type: gdb.Type, method_name: str) -> XMethodWorker | Sequence[XMethodWorker]: ... + +@type_check_only +class _SimpleWorkerMethod(Protocol): + def __call__(self, *args: gdb.Value) -> object: ... + +class SimpleXMethodMatcher(XMethodMatcher): + def __init__( + self, + name: str, + class_matcher: str | Pattern[str], + method_matcher: str | Pattern[str], + method_function: _SimpleWorkerMethod, + *arg_types: Sequence[gdb.Type] | gdb.Type | None, + ) -> None: ... diff --git a/stubs/geojson/@tests/stubtest_allowlist.txt b/stubs/geojson/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d3376f747930 --- /dev/null +++ b/stubs/geojson/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# Stub missing OK, not part of public API +geojson.factory +geojson.examples diff --git a/stubs/geojson/METADATA.toml b/stubs/geojson/METADATA.toml new file mode 100644 index 000000000000..2e98409a8944 --- /dev/null +++ b/stubs/geojson/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.0" +upstream-repository = "https://github.com/jazzband/geojson" diff --git a/stubs/geojson/geojson/__init__.pyi b/stubs/geojson/geojson/__init__.pyi new file mode 100644 index 000000000000..a022f4f97930 --- /dev/null +++ b/stubs/geojson/geojson/__init__.pyi @@ -0,0 +1,28 @@ +from geojson._version import __version__, __version_info__ +from geojson.base import GeoJSON +from geojson.codec import GeoJSONEncoder, dump, dumps, load, loads +from geojson.feature import Feature, FeatureCollection +from geojson.geometry import GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from geojson.utils import coords, map_coords + +__all__ = [ + "dump", + "dumps", + "load", + "loads", + "GeoJSONEncoder", + "coords", + "map_coords", + "Point", + "LineString", + "Polygon", + "MultiLineString", + "MultiPoint", + "MultiPolygon", + "GeometryCollection", + "Feature", + "FeatureCollection", + "GeoJSON", + "__version__", + "__version_info__", +] diff --git a/stubs/geojson/geojson/_version.pyi b/stubs/geojson/geojson/_version.pyi new file mode 100644 index 000000000000..fd947dd9c0e2 --- /dev/null +++ b/stubs/geojson/geojson/_version.pyi @@ -0,0 +1,2 @@ +__version__: str +__version_info__: tuple[int, ...] diff --git a/stubs/geojson/geojson/base.pyi b/stubs/geojson/geojson/base.pyi new file mode 100644 index 000000000000..7472837e0814 --- /dev/null +++ b/stubs/geojson/geojson/base.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any + +class GeoJSON(dict[str, Any]): + def __init__(self, iterable: Iterable[tuple[str, Any]] = (), **extra) -> None: ... + def __getattr__(self, name: str | int) -> Incomplete: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + @property + def __geo_interface__(self) -> None | GeoJSON: ... + @classmethod + def to_instance(cls, ob, default=None, strict: bool = False) -> GeoJSON: ... + @property + def is_valid(self) -> bool: ... + def check_list_errors(self, checkFunc, lst) -> list[str] | None: ... + def errors(self) -> list[str] | None: ... diff --git a/stubs/geojson/geojson/codec.pyi b/stubs/geojson/geojson/codec.pyi new file mode 100644 index 000000000000..7b9d82f0944e --- /dev/null +++ b/stubs/geojson/geojson/codec.pyi @@ -0,0 +1,33 @@ +import json +from _typeshed import SupportsRead, SupportsWrite +from collections.abc import Callable +from typing import Any +from typing_extensions import Never + +from geojson.base import GeoJSON + +class GeoJSONEncoder(json.JSONEncoder): + def default(self, obj) -> GeoJSON: ... + +def dump( + obj, fp: SupportsWrite[str], cls: type[json.JSONEncoder] | None = json.JSONEncoder, allow_nan: bool = False, **kwargs +) -> None: ... +def dumps( + obj, cls: type[json.JSONEncoder] | None = json.JSONEncoder, allow_nan: bool = False, ensure_ascii: bool = False, **kwargs +) -> str: ... +def load( + fp: SupportsRead[str], + cls: type[json.JSONDecoder] = json.JSONDecoder, + parse_constant: Callable[..., Never] = ..., + object_hook: Callable[[dict[str, Any]], GeoJSON] = GeoJSON.to_instance, + **kwargs, +) -> GeoJSON: ... +def loads( + s: str, + cls: type[json.JSONDecoder] = json.JSONDecoder, + parse_constant: Callable[..., Never] = ..., + object_hook: Callable[[dict[str, Any]], GeoJSON] = GeoJSON.to_instance, + **kwargs, +) -> GeoJSON: ... + +PyGFPEncoder = GeoJSONEncoder diff --git a/stubs/geojson/geojson/feature.pyi b/stubs/geojson/geojson/feature.pyi new file mode 100644 index 000000000000..41aff456863e --- /dev/null +++ b/stubs/geojson/geojson/feature.pyi @@ -0,0 +1,15 @@ +from typing import Any + +from geojson.base import GeoJSON +from geojson.geometry import Geometry + +class Feature(GeoJSON): + def __init__( + self, id: None | str | int = None, geometry: None | Geometry = None, properties: None | dict[str, Any] = None, **extra + ) -> None: ... + def errors(self) -> list[str] | None: ... + +class FeatureCollection(GeoJSON): + def __init__(self, features: list[Feature | Geometry], **extra) -> None: ... + def errors(self) -> list[str] | None: ... + def __getitem__(self, key: int | str) -> Feature: ... diff --git a/stubs/geojson/geojson/geometry.pyi b/stubs/geojson/geojson/geometry.pyi new file mode 100644 index 000000000000..04fa942cca7f --- /dev/null +++ b/stubs/geojson/geojson/geometry.pyi @@ -0,0 +1,52 @@ +from collections.abc import Sequence +from decimal import Decimal +from typing import Literal, TypeAlias + +from geojson.base import GeoJSON + +_InputCoord: TypeAlias = float | Decimal | Geometry | Sequence[_InputCoord] +_CleanCoord: TypeAlias = float | Decimal | list[_CleanCoord] + +DEFAULT_PRECISION: Literal[6] + +class Geometry(GeoJSON): + def __init__( + self, + coordinates: None | Sequence[_InputCoord] | Geometry = None, + validate: bool = False, + precision: None | int = None, + **extra, + ) -> None: ... + @classmethod + def clean_coordinates(cls, coords: Sequence[_InputCoord] | Geometry, precision: int) -> list[_CleanCoord]: ... + +class GeometryCollection(GeoJSON): + def __init__(self, geometries: Sequence[Geometry] | None = None, **extra) -> None: ... + def errors(self) -> list[str] | None: ... + def __getitem__(self, key) -> Geometry | tuple[()] | None: ... + +def check_point(coord) -> str | None: ... + +class Point(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiPoint(Geometry): + def errors(self) -> list[str] | None: ... + +def check_line_string(coord) -> str | None: ... + +class LineString(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiLineString(MultiPoint): + def errors(self) -> list[str] | None: ... + +def check_polygon(coord) -> str | None: ... + +class Polygon(Geometry): + def errors(self) -> list[str] | None: ... + +class MultiPolygon(Geometry): + def errors(self) -> list[str] | None: ... + +class Default: ... diff --git a/stubs/geojson/geojson/mapping.pyi b/stubs/geojson/geojson/mapping.pyi new file mode 100644 index 000000000000..d9b0e4900ebb --- /dev/null +++ b/stubs/geojson/geojson/mapping.pyi @@ -0,0 +1,6 @@ +from typing import Any, Literal + +GEO_INTERFACE_MARKER: Literal["__geo_interface__"] + +def is_mapping(obj) -> bool: ... +def to_mapping(obj) -> dict[str, Any]: ... diff --git a/stubs/geojson/geojson/utils.pyi b/stubs/geojson/geojson/utils.pyi new file mode 100644 index 000000000000..9e35c35bfc81 --- /dev/null +++ b/stubs/geojson/geojson/utils.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from typing import Any, Literal + +from geojson.base import GeoJSON +from geojson.geometry import Geometry, LineString, Point, Polygon + +def coords(obj: GeoJSON | dict[str, Any]) -> Generator[tuple[float]]: ... +def map_coords(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def map_tuples(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def map_geometries(func: Callable[[Incomplete], float | Geometry], obj: GeoJSON | dict[str, Any]) -> dict[str, Any]: ... +def generate_random( + featureType: Literal["Point", "LineString", "Polygon"], + numberVertices: int = 3, + boundingBox: list[float] = [-180.0, -90.0, 180.0, 90.0], +) -> Point | LineString | Polygon: ... diff --git a/stubs/geopandas/@tests/stubtest_allowlist.txt b/stubs/geopandas/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..2251765af4e4 --- /dev/null +++ b/stubs/geopandas/@tests/stubtest_allowlist.txt @@ -0,0 +1,25 @@ +# Stub missing OK +geopandas\.conftest +geopandas\.(.*\.)?tests.* +geopandas\.array\.(type_mapping|geometry_type_ids|geometry_type_values) +geopandas\.io\.file\.(FIONA|PYOGRIO)_GE_.* +geopandas\.io\.file\.(fiona|pyogrio)(_env|_import_error)? +geopandas\.io\.util +geopandas\.datasets\.* + +# Inconsistent OK +geopandas\.(geodataframe\.)?GeoDataFrame\.plot + +# Failed to import OK (require extra dependencies) +geopandas\.io\._geoarrow +geopandas\._exports + +# stub parameter differs from runtime parameter "self" +geopandas.geodataframe.GeoDataFrame.explore +geopandas.geoseries.GeoSeries.explore +geopandas.geoseries.GeoSeries.plot + +# Inconsistent (TODO) +geopandas\.(geoseries\.)?GeoSeries\.apply +geopandas\.(geoseries\.)?GeoSeries\.fillna +geopandas\.(geoseries\.)?GeoSeries\.sort_index diff --git a/stubs/geopandas/METADATA.toml b/stubs/geopandas/METADATA.toml new file mode 100644 index 000000000000..653120efd9b8 --- /dev/null +++ b/stubs/geopandas/METADATA.toml @@ -0,0 +1,9 @@ +version = "1.1.4" +upstream-repository = "https://github.com/geopandas/geopandas" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20", "pandas-stubs", "types-shapely", "pyproj"] + +[tool.stubtest] +# libproj-dev and proj-bin are required to build pyproj if wheels for the +# target Python version are not available. +apt-dependencies = ["libproj-dev", "proj-bin"] diff --git a/stubs/geopandas/geopandas/__init__.pyi b/stubs/geopandas/geopandas/__init__.pyi new file mode 100644 index 000000000000..d2a3b1899ed1 --- /dev/null +++ b/stubs/geopandas/geopandas/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Final + +from ._config import options as options +from ._exports import ( + gpd as gpd, + list_layers as list_layers, + np as np, + pd as pd, + read_feather as read_feather, + read_file as read_file, + read_parquet as read_parquet, + read_postgis as read_postgis, +) +from .array import points_from_xy as points_from_xy +from .geodataframe import GeoDataFrame as GeoDataFrame +from .geoseries import GeoSeries as GeoSeries +from .tools import clip as clip, overlay as overlay, sjoin as sjoin, sjoin_nearest as sjoin_nearest +from .tools._show_versions import show_versions as show_versions + +__version__: Final[str] diff --git a/stubs/geopandas/geopandas/_config.pyi b/stubs/geopandas/geopandas/_config.pyi new file mode 100644 index 000000000000..c60381fdc8ec --- /dev/null +++ b/stubs/geopandas/geopandas/_config.pyi @@ -0,0 +1,21 @@ +from _typeshed import SupportsItems, Unused +from collections.abc import Callable +from typing import Any, NamedTuple + +class Option(NamedTuple): + key: str + default_value: Any # Can be "any" type + doc: str + validator: Callable[[object], Unused] + callback: Callable[[str, object], Unused] | None + +class Options: + def __init__(self, options: SupportsItems[str, Option]) -> None: ... + # Accept and return arbitrary values + def __setattr__(self, key: str, value: Any) -> None: ... + def __getattr__(self, key: str) -> Any: ... + +display_precision: Option +use_pygeos: Option +io_engine: Option +options: Options diff --git a/stubs/geopandas/geopandas/_decorator.pyi b/stubs/geopandas/geopandas/_decorator.pyi new file mode 100644 index 000000000000..6d82bcec9198 --- /dev/null +++ b/stubs/geopandas/geopandas/_decorator.pyi @@ -0,0 +1,20 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar, overload + +_AnyCallable: TypeAlias = Callable[..., object] +_Func = TypeVar("_Func", bound=_AnyCallable) + +# We (ab)use this decorator to also copy the signature of the source function (overload 1) +# The advantages are: +# - avoid copying all parameters and types manually while conserving type safety +# - signature properly handeled in IDEs (at least with Pylance) +# - docstring from the original function properly displayed (at least with Pylance) +# Using the other overloads returns the signature of the decorated function instead +@overload +def doc(func: _Func, /, **params: object) -> Callable[[_AnyCallable], _Func]: ... +@overload +def doc(docstring: str, /, *docstrings: str | _AnyCallable, **params: object) -> Callable[[_Func], _Func]: ... +@overload +def doc( + docstring1: str | _AnyCallable, docstring2: str | _AnyCallable, /, *docstrings: str | _AnyCallable, **params: object +) -> Callable[[_Func], _Func]: ... diff --git a/stubs/geopandas/geopandas/_exports.pyi b/stubs/geopandas/geopandas/_exports.pyi new file mode 100644 index 000000000000..cfea4e64c3e9 --- /dev/null +++ b/stubs/geopandas/geopandas/_exports.pyi @@ -0,0 +1,21 @@ +# Type checking-only module to export public symbols with a different name in __init__.pyi + +import geopandas as gpd +import numpy as np +import pandas as pd +from geopandas.io.arrow import _read_feather as read_feather, _read_parquet as read_parquet +from geopandas.io.file import _list_layers as list_layers, _read_file as read_file +from geopandas.io.sql import _read_postgis as read_postgis + +__all__ = [ + # IO functions + "read_file", + "read_feather", + "read_parquet", + "read_postgis", + "list_layers", + # Modules for interactive use + "np", + "pd", + "gpd", +] diff --git a/stubs/geopandas/geopandas/accessors.pyi b/stubs/geopandas/geopandas/accessors.pyi new file mode 100644 index 000000000000..d69a67fe594b --- /dev/null +++ b/stubs/geopandas/geopandas/accessors.pyi @@ -0,0 +1,7 @@ +from typing import Any + +import pandas as pd + +class GeoSeriesAccessor: + def __init__(self, series: pd.Series[Any]) -> None: ... # Cannot use pd.Series[BaseGeometry] + def __getattr__(self, name: str) -> Any: ... # Delegate all attributes to the GeoSeries diff --git a/stubs/geopandas/geopandas/array.pyi b/stubs/geopandas/geopandas/array.pyi new file mode 100644 index 000000000000..3c6a469b7802 --- /dev/null +++ b/stubs/geopandas/geopandas/array.pyi @@ -0,0 +1,259 @@ +import builtins +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Collection +from typing import Any, ClassVar, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self, deprecated + +import numpy as np +import pandas as pd +from numpy.typing import ArrayLike, DTypeLike, NDArray +from pandas._typing import ScalarIndexer, SequenceIndexer, TakeIndexer +from pandas.api.extensions import ExtensionArray, ExtensionDtype +from pyproj import CRS, Transformer +from shapely import Geometry +from shapely.geometry.base import BaseGeometry + +from .base import _AffinityOrigin, _ConvertibleToCRS +from .sindex import SpatialIndex + +_ScalarType = TypeVar("_ScalarType", bound=np.generic) +_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarType]] +_Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_ScalarType]] +_ArrayOrGeom: TypeAlias = GeometryArray | ArrayLike | Geometry + +TransformerFromCRS = Transformer.from_crs +POLYGON_GEOM_TYPES: Final[set[str]] +LINE_GEOM_TYPES: Final[set[str]] +POINT_GEOM_TYPES: Final[set[str]] + +class GeometryDtype(ExtensionDtype): + type: ClassVar[type[BaseGeometry]] + name: ClassVar[str] + na_value: None + @classmethod + def construct_from_string(cls, string: str) -> Self: ... + @classmethod + def construct_array_type(cls) -> builtins.type[GeometryArray]: ... + +def isna(value: object) -> bool: ... +def from_shapely(data, crs: _ConvertibleToCRS | None = None) -> GeometryArray: ... +def to_shapely(geoms: GeometryArray) -> _Array1D[np.object_]: ... +def from_wkb( + data, crs: _ConvertibleToCRS | None = None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise" +) -> GeometryArray: ... + +@overload +def to_wkb(geoms: GeometryArray, hex: Literal[False] = False, **kwargs) -> _Array1D[np.bytes_]: ... +@overload +def to_wkb(geoms: GeometryArray, hex: Literal[True], **kwargs) -> _Array1D[np.str_]: ... + +def from_wkt( + data, crs: _ConvertibleToCRS | None = None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise" +) -> GeometryArray: ... +def to_wkt(geoms: GeometryArray, **kwargs) -> _Array1D[np.str_]: ... +def points_from_xy( + x: ArrayLike, y: ArrayLike, z: ArrayLike | None = None, crs: _ConvertibleToCRS | None = None +) -> GeometryArray: ... + +class GeometryArray(ExtensionArray): + def __init__(self, data: GeometryArray | NDArray[np.object_], crs: _ConvertibleToCRS | None = None) -> None: ... + @property + def sindex(self) -> SpatialIndex: ... + @property + def has_sindex(self) -> bool: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + def check_geographic_crs(self, stacklevel: int) -> None: ... + @property + def dtype(self) -> GeometryDtype: ... + def __len__(self) -> int: ... + + # np.integer[Any] because precision is not important + @overload + def __getitem__(self, idx: ScalarIndexer) -> BaseGeometry: ... # Always 1-D, doesn't accept tuple + @overload + def __getitem__(self, idx: SequenceIndexer) -> GeometryArray: ... + + def __setitem__( + self, key, value: _ArrayOrGeom | pd.DataFrame | pd.Series[Any] # Cannot use pd.Series[BaseGeometry] + ) -> None: ... + @property + def is_valid(self) -> _Array1D[np.bool_]: ... + def is_valid_reason(self) -> _Array1D[np.object_]: ... + def is_valid_coverage(self, gap_width: float = 0.0) -> bool: ... + def invalid_coverage_edges(self, gap_width: float = 0.0) -> _Array1D[np.object_]: ... + @property + def is_empty(self) -> _Array1D[np.bool_]: ... + @property + def is_simple(self) -> _Array1D[np.bool_]: ... + @property + def is_ring(self) -> _Array1D[np.bool_]: ... + @property + def is_closed(self) -> _Array1D[np.bool_]: ... + @property + def is_ccw(self) -> _Array1D[np.bool_]: ... + @property + def has_z(self) -> _Array1D[np.bool_]: ... + @property + def has_m(self) -> _Array1D[np.bool_]: ... + @property + def geom_type(self) -> _Array1D[np.str_]: ... + @property + def area(self) -> _Array1D[np.float64]: ... + @property + def length(self) -> _Array1D[np.float64]: ... + def count_coordinates(self) -> _Array1D[np.int32]: ... + def count_geometries(self) -> _Array1D[np.int32]: ... + def count_interior_rings(self) -> _Array1D[np.int32]: ... + def get_precision(self) -> _Array1D[np.float64]: ... + def get_geometry(self, index: SupportsIndex | ArrayLike) -> _Array1D[np.object_]: ... + @property + def boundary(self) -> GeometryArray: ... + @property + def centroid(self) -> GeometryArray: ... + def concave_hull(self, ratio: float, allow_holes: bool) -> _Array1D[np.object_]: ... + def constrained_delaunay_triangles(self) -> GeometryArray: ... + @property + def convex_hull(self) -> GeometryArray: ... + @property + def envelope(self) -> GeometryArray: ... + def minimum_rotated_rectangle(self) -> GeometryArray: ... + @property + def exterior(self) -> GeometryArray: ... + def extract_unique_points(self) -> GeometryArray: ... + def offset_curve( + self, + distance: float | ArrayLike, + quad_segs: int = 8, + join_style: Literal["round", "bevel", "mitre"] = "round", + mitre_limit: float = 5.0, + ) -> GeometryArray: ... + @property + def interiors(self) -> _Array1D[np.object_]: ... + def remove_repeated_points(self, tolerance: float | ArrayLike = 0.0) -> GeometryArray: ... + def representative_point(self) -> GeometryArray: ... + def minimum_bounding_circle(self) -> GeometryArray: ... + def maximum_inscribed_circle(self, tolerance: float | ArrayLike) -> GeometryArray: ... + def minimum_bounding_radius(self) -> _Array1D[np.float64]: ... + def minimum_clearance(self) -> _Array1D[np.float64]: ... + def minimum_clearance_line(self) -> GeometryArray: ... + def normalize(self) -> GeometryArray: ... + def orient_polygons(self, exterior_cw: bool = False) -> GeometryArray: ... + def make_valid(self, method: Literal["linework", "structure"] = "linework", keep_collapsed: bool = True) -> GeometryArray: ... + def reverse(self) -> GeometryArray: ... + def segmentize(self, max_segment_length: float | ArrayLike) -> GeometryArray: ... + def force_2d(self) -> GeometryArray: ... + def force_3d(self, z: float | ArrayLike = 0) -> GeometryArray: ... + def transform( + self, transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], include_z: bool = False + ) -> GeometryArray: ... + def line_merge(self, directed: bool = False) -> GeometryArray: ... + def set_precision( + self, grid_size: float, mode: Literal["valid_output", "pointwise", "keep_collapsed", 0, 1, 2] = "valid_output" + ) -> GeometryArray: ... + def covers(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def covered_by(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def contains(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def contains_properly(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def crosses(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def disjoint(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def geom_equals(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def intersects(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def overlaps(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def touches(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def within(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def dwithin(self, other: _ArrayOrGeom, distance: float) -> _Array1D[np.bool_]: ... + def geom_equals_exact(self, other: _ArrayOrGeom, tolerance: float | ArrayLike) -> _Array1D[np.bool_]: ... + def geom_equals_identical(self, other: _ArrayOrGeom) -> _Array1D[np.bool_]: ... + def clip_by_rect(self, xmin: float, ymin: float, xmax: float, ymax: float) -> GeometryArray: ... + def difference(self, other: _ArrayOrGeom) -> GeometryArray: ... + def intersection(self, other: _ArrayOrGeom) -> GeometryArray: ... + def symmetric_difference(self, other: _ArrayOrGeom) -> GeometryArray: ... + def union(self, other: _ArrayOrGeom) -> GeometryArray: ... + def shortest_line(self, other: _ArrayOrGeom) -> GeometryArray: ... + def snap(self, other: _ArrayOrGeom, tolerance: float | ArrayLike) -> GeometryArray: ... + def shared_paths(self, other: _ArrayOrGeom) -> GeometryArray: ... + def distance(self, other: _ArrayOrGeom) -> _Array1D[np.float64]: ... + def hausdorff_distance(self, other: _ArrayOrGeom, **kwargs) -> _Array1D[np.float64]: ... + def frechet_distance(self, other: _ArrayOrGeom, **kwargs) -> _Array1D[np.float64]: ... + def buffer(self, distance: float | ArrayLike, resolution: int = 16, **kwargs) -> GeometryArray: ... + def interpolate(self, distance: float | ArrayLike, normalized: bool = False) -> GeometryArray: ... + def simplify(self, tolerance: float | ArrayLike, preserve_topology: bool = True) -> GeometryArray: ... + def simplify_coverage(self, tolerance: float | ArrayLike, simplify_boundary: bool = True) -> GeometryArray: ... + def project(self, other: _ArrayOrGeom, normalized: bool = False) -> _Array1D[np.float64]: ... + def relate(self, other: _ArrayOrGeom) -> _Array1D[np.str_]: ... + def relate_pattern(self, other: _ArrayOrGeom, pattern: str) -> _Array1D[np.bool_]: ... + @deprecated("Use method `union_all` instead.") + def unary_union(self) -> BaseGeometry: ... + def union_all( + self, method: Literal["coverage", "unary", "disjoint_subset"] = "unary", grid_size: float | None = None + ) -> BaseGeometry: ... + def intersection_all(self) -> BaseGeometry: ... + def affine_transform(self, matrix: Collection[float]) -> GeometryArray: ... + def translate(self, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeometryArray: ... + def rotate(self, angle: float, origin: _AffinityOrigin = "center", use_radians: bool = False) -> GeometryArray: ... + def scale( + self, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _AffinityOrigin = "center" + ) -> GeometryArray: ... + def skew( + self, xs: float = 0.0, ys: float = 0.0, origin: _AffinityOrigin = "center", use_radians: bool = False + ) -> GeometryArray: ... + def to_crs(self, crs: _ConvertibleToCRS | None = None, epsg: int | None = None) -> GeometryArray: ... + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + @property + def x(self) -> _Array1D[np.float64]: ... + @property + def y(self) -> _Array1D[np.float64]: ... + @property + def z(self) -> _Array1D[np.float64]: ... + @property + def m(self) -> _Array1D[np.float64]: ... + @property + def bounds(self) -> _Array2D[np.float64]: ... + @property + def total_bounds(self) -> _Array1D[np.float64]: ... + @property + def size(self) -> int: ... + @property + def shape(self) -> tuple[int]: ... # Always 1-D, this is not mistaken for tuple[int, ...] + @property + def ndim(self) -> Literal[1]: ... + def copy(self, *args: Unused, **kwargs: Unused) -> GeometryArray: ... + def take(self, indices: TakeIndexer, allow_fill: bool = False, fill_value: Geometry | None = None) -> GeometryArray: ... + def fillna( # type: ignore[override] + self, + value: Geometry | GeometryArray | None = None, + method: Literal["backfill", "bfill", "pad", "ffill"] | None = None, + limit: int | None = None, + copy: bool = True, + ) -> GeometryArray: ... + + @overload # type: ignore[override] + def astype(self, dtype: GeometryDtype, copy: bool = True) -> GeometryArray: ... + @overload + def astype(self, dtype: ExtensionDtype | Literal["string"], copy: bool = True) -> ExtensionArray: ... # type: ignore[overload-overlap] + @overload + def astype(self, dtype: DTypeLike, copy: bool = True) -> _Array1D[Incomplete]: ... + + def isna(self) -> _Array1D[np.bool_]: ... + def value_counts(self, dropna: bool = True) -> pd.Series[int]: ... + def unique(self) -> GeometryArray: ... + @property + def nbytes(self) -> int: ... + def shift(self, periods: int = 1, fill_value: Geometry | None = None) -> GeometryArray: ... # type: ignore[override] + def argmin(self, skipna: bool = True) -> Never: ... + def argmax(self, skipna: bool = True) -> Never: ... + def __array__(self, dtype: DTypeLike | None = None, copy: bool | None = None) -> _Array1D[np.object_]: ... + def __eq__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] + def __ne__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] + def __contains__(self, item: object) -> np.bool_: ... + +# TODO: Improve `func` type with a callable protocol (with overloads for 2D and 3D geometries) +def transform( + data: NDArray[np.object_] | GeometryArray | pd.Series[Any], # Cannot use pd.Series[BaseGeometry] + func: Callable[..., NDArray[np.float64]], +) -> NDArray[np.object_]: ... diff --git a/stubs/geopandas/geopandas/base.pyi b/stubs/geopandas/geopandas/base.pyi new file mode 100644 index 000000000000..1cb2dc1c8420 --- /dev/null +++ b/stubs/geopandas/geopandas/base.pyi @@ -0,0 +1,246 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Collection, Hashable, Iterable, Mapping, Sequence +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +import numpy as np +import pandas as pd +from numpy.random import BitGenerator, Generator as RandomGenerator, SeedSequence +from numpy.typing import ArrayLike, NDArray +from pandas._typing import ListLikeU +from pandas.core.base import IndexOpsMixin +from pyproj import CRS +from shapely import Geometry, MultiPolygon, Point, Polygon +from shapely.geometry.base import BaseGeometry + +from .array import GeometryArray, _Array1D +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries +from .sindex import SpatialIndex + +@type_check_only +class _SupportsToWkt(Protocol): + def to_wkt(self) -> str: ... + +@type_check_only +class _SupportsGeoInterface(Protocol): # noqa: Y046 + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + +_ConvertibleToCRS: TypeAlias = str | int | tuple[str, str] | list[str] | dict[str, Incomplete] | _SupportsToWkt +_AffinityOrigin: TypeAlias = Literal["center", "centroid"] | Point | tuple[float, float] | tuple[float, float, float] +_ClipMask: TypeAlias = GeoDataFrame | GeoSeries | Polygon | MultiPolygon | tuple[float, float, float, float] # noqa: Y047 +# np.floating[Any] because precision is not important +_BboxLike: TypeAlias = Sequence[float] | NDArray[np.floating[Any]] | Geometry | GeoDataFrame | GeoSeries # noqa: Y047 +_MaskLike: TypeAlias = dict[str, Incomplete] | Geometry | GeoDataFrame | GeoSeries # noqa: Y047 + +# Cannot use IndexOpsMixin[Geometry] because of IndexOpsMixin type variable bounds +_GeoListLike: TypeAlias = ArrayLike | Sequence[Geometry] | IndexOpsMixin[Any] +_ConvertibleToGeoSeries: TypeAlias = Geometry | Mapping[int, Geometry] | Mapping[str, Geometry] | _GeoListLike # noqa: Y047 + +# Cannot use pd.Series[Geometry] because of pd.Series type variable bounds +_GeomSeq: TypeAlias = Sequence[Geometry] | NDArray[np.object_] | pd.Series[Any] | GeometryArray | GeoSeries +_GeomCol: TypeAlias = Hashable | _GeomSeq # name of column or column values # noqa: Y047 +# dict[Any, Any] because of variance issues +_ConvertibleToDataFrame: TypeAlias = ( # noqa: Y047 + ListLikeU | pd.DataFrame | dict[Any, Any] | Iterable[ListLikeU | tuple[Hashable, ListLikeU] | dict[Any, Any]] +) + +def is_geometry_type(data: object) -> bool: ... + +class GeoPandasBase: + @property + def area(self) -> pd.Series[float]: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + @property + def geom_type(self) -> pd.Series[str]: ... + @property + def type(self) -> pd.Series[str]: ... + @property + def length(self) -> pd.Series[float]: ... + @property + def is_valid(self) -> pd.Series[bool]: ... + def is_valid_reason(self) -> pd.Series[str]: ... + def is_valid_coverage(self, *, gap_width: float = 0.0) -> bool: ... + def invalid_coverage_edges(self, *, gap_width: float = 0.0) -> GeoSeries: ... + @property + def is_empty(self) -> pd.Series[bool]: ... + def count_coordinates(self) -> pd.Series[int]: ... + def count_geometries(self) -> pd.Series[int]: ... + def count_interior_rings(self) -> pd.Series[int]: ... + @property + def is_simple(self) -> pd.Series[bool]: ... + @property + def is_ring(self) -> pd.Series[bool]: ... + @property + def is_ccw(self) -> pd.Series[bool]: ... + @property + def is_closed(self) -> pd.Series[bool]: ... + @property + def has_z(self) -> pd.Series[bool]: ... + @property + def has_m(self) -> pd.Series[bool]: ... + def get_precision(self) -> pd.Series[float]: ... + def get_geometry(self, index: SupportsIndex | ArrayLike) -> GeoSeries: ... + @property + def boundary(self) -> GeoSeries: ... + @property + def centroid(self) -> GeoSeries: ... + def concave_hull(self, ratio: float = 0.0, allow_holes: bool = False) -> GeoSeries: ... + def constrained_delaunay_triangles(self) -> GeoSeries: ... + @property + def convex_hull(self) -> GeoSeries: ... + def delaunay_triangles(self, tolerance: float | ArrayLike = 0.0, only_edges: bool | ArrayLike = False) -> GeoSeries: ... + def voronoi_polygons( + self, tolerance: float | ArrayLike = 0.0, extend_to: Geometry | None = None, only_edges: bool = False + ) -> GeoSeries: ... + @property + def envelope(self) -> GeoSeries: ... + def minimum_rotated_rectangle(self) -> GeoSeries: ... + @property + def exterior(self) -> GeoSeries: ... + def extract_unique_points(self) -> GeoSeries: ... + def offset_curve( + self, + distance: float | ArrayLike, + quad_segs: int = 8, + join_style: Literal["round", "bevel", "mitre"] = "round", + mitre_limit: float = 5.0, + ) -> GeoSeries: ... + @property + def interiors(self) -> pd.Series[Any]: ... # Cannot use pd.Series[BaseGeometry] + def remove_repeated_points(self, tolerance: float = 0.0) -> GeoSeries: ... + def set_precision( + self, grid_size: float, mode: Literal["valid_output", "pointwise", "keep_collapsed"] = "valid_output" + ) -> GeoSeries: ... + def representative_point(self) -> GeoSeries: ... + def minimum_bounding_circle(self) -> GeoSeries: ... + def maximum_inscribed_circle(self, *, tolerance: float | ArrayLike | None = None) -> GeoSeries: ... + def minimum_bounding_radius(self) -> pd.Series[float]: ... + def minimum_clearance(self) -> pd.Series[float]: ... + def minimum_clearance_line(self) -> GeoSeries: ... + def normalize(self) -> GeoSeries: ... + def orient_polygons(self, *, exterior_cw: bool = False) -> GeoSeries: ... + def make_valid(self, *, method: Literal["linework", "structure"] = "linework", keep_collapsed: bool = True) -> GeoSeries: ... + def reverse(self) -> GeoSeries: ... + def segmentize(self, max_segment_length: float | ArrayLike) -> GeoSeries: ... + def transform( + self, transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], include_z: bool = False + ) -> GeoSeries: ... + def force_2d(self) -> GeoSeries: ... + def force_3d(self, z: float | ArrayLike = 0) -> GeoSeries: ... + def line_merge(self, directed: bool = False) -> GeoSeries: ... + @property + @deprecated("Use method `union_all` instead.") + def unary_union(self) -> BaseGeometry: ... + def union_all( + self, method: Literal["coverage", "unary", "disjoint_subset"] = "unary", *, grid_size: float | None = None + ) -> BaseGeometry: ... + def intersection_all(self) -> BaseGeometry: ... + def contains(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def contains_properly(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def dwithin(self, other: GeoSeries | Geometry, distance: float | ArrayLike, align: bool | None = None) -> pd.Series[bool]: ... + def geom_equals(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def geom_equals_exact( + self, other: GeoSeries | Geometry, tolerance: float | ArrayLike, align: bool | None = None + ) -> pd.Series[bool]: ... + def geom_equals_identical(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def crosses(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def disjoint(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def intersects(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def overlaps(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def touches(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def within(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def covers(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def covered_by(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[bool]: ... + def distance(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[float]: ... + def hausdorff_distance( + self, other: GeoSeries | Geometry, align: bool | None = None, densify: float | ArrayLike | None = None + ) -> pd.Series[float]: ... + def frechet_distance( + self, other: GeoSeries | Geometry, align: bool | None = None, densify: float | ArrayLike | None = None + ) -> pd.Series[float]: ... + def difference(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def symmetric_difference(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def union(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def intersection(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def clip_by_rect(self, xmin: float, ymin: float, xmax: float, ymax: float) -> GeoSeries: ... + def shortest_line(self, other: GeoSeries | Geometry, align: bool | None = None) -> GeoSeries: ... + def snap(self, other: GeoSeries | Geometry, tolerance: float | ArrayLike, align: bool | None = None) -> GeoSeries: ... + def shared_paths(self, other: GeoSeries | Geometry, align: bool | None = None): ... + @property + def bounds(self) -> pd.DataFrame: ... + @property + def total_bounds(self) -> _Array1D[np.float64]: ... + @property + def sindex(self) -> SpatialIndex: ... + @property + def has_sindex(self) -> bool: ... + def buffer( + self, + distance: float | ArrayLike, + resolution: int = 16, + cap_style: Literal["round", "square", "flat"] = "round", + join_style: Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs, + ) -> GeoSeries: ... + def simplify(self, tolerance: float | ArrayLike, preserve_topology: bool = True) -> GeoSeries: ... + def simplify_coverage(self, tolerance: float | ArrayLike, *, simplify_boundary: bool = True) -> GeoSeries: ... + def relate(self, other: GeoSeries | Geometry, align: bool | None = None) -> pd.Series[str]: ... + def relate_pattern(self, other: GeoSeries | Geometry, pattern: str, align: bool | None = None) -> pd.Series[bool]: ... + def project(self, other: GeoSeries | Geometry, normalized: bool = False, align: bool | None = None) -> pd.Series[float]: ... + def interpolate(self, distance: float | ArrayLike, normalized: bool = False) -> GeoSeries: ... + def affine_transform(self, matrix: Collection[float]) -> GeoSeries: ... + def translate(self, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeoSeries: ... + def rotate(self, angle: float, origin: _AffinityOrigin = "center", use_radians: bool = False) -> GeoSeries: ... + def scale( + self, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _AffinityOrigin = "center" + ) -> GeoSeries: ... + def skew( + self, xs: float = 0.0, ys: float = 0.0, origin: _AffinityOrigin = "center", use_radians: bool = False + ) -> GeoSeries: ... + @property + def cx(self) -> SupportsGetItem[tuple[SupportsIndex | slice, SupportsIndex | slice], Self]: ... + def get_coordinates( + self, include_z: bool = False, ignore_index: bool = False, index_parts: bool = False, *, include_m: bool = False + ) -> pd.DataFrame: ... + def hilbert_distance( + self, total_bounds: tuple[float, float, float, float] | Iterable[float] | None = None, level: int = 16 + ) -> pd.Series[int]: ... + + @overload + def sample_points( + self, + size: int | ArrayLike, + method: str = "uniform", + seed: None = None, + rng: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator | None = None, + **kwargs, + ) -> GeoSeries: ... + @overload + @deprecated("Parameter `seed` is deprecated. Use `rng` instead.") + def sample_points( + self, + size: int | ArrayLike, + method: str = "uniform", + *, + seed: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator, + rng: int | ArrayLike | SeedSequence | BitGenerator | RandomGenerator | None = None, + **kwargs, + ) -> GeoSeries: ... + + def build_area(self, node: bool = True) -> GeoSeries: ... + + @overload + def polygonize(self, node: bool = True, full: Literal[False] = False) -> GeoSeries: ... + @overload + def polygonize(self, node: bool = True, *, full: Literal[True]) -> tuple[GeoSeries, GeoSeries, GeoSeries, GeoSeries]: ... + @overload + def polygonize(self, node: bool, full: Literal[True]) -> tuple[GeoSeries, GeoSeries, GeoSeries, GeoSeries]: ... diff --git a/stubs/geopandas/geopandas/explore.pyi b/stubs/geopandas/geopandas/explore.pyi new file mode 100644 index 000000000000..1ecd3a1cb1cb --- /dev/null +++ b/stubs/geopandas/geopandas/explore.pyi @@ -0,0 +1,65 @@ +from collections.abc import Callable, Hashable, MutableMapping, Sequence +from typing import Any + +import branca # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +import folium # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +import pandas as pd +import xyzservices # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from matplotlib.colors import Colormap # type: ignore[import-not-found] +from numpy.typing import ArrayLike, NDArray + +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +def _explore( + df: GeoDataFrame, + column: Hashable | NDArray[Any] | pd.Series[Any] | None = None, # Accepts "any" array or series + cmap: str | Colormap | branca.colormap.ColorMap | Sequence[str] | Callable[[Any], str] | None = None, # accepts "any" object + color: str | ArrayLike | None = None, + m: folium.Map | None = None, + tiles: str | folium.TileLayer | xyzservices.TileProvider | None = "OpenStreetMap", + attr: str | None = None, + tooltip: bool = True, + popup: bool = False, + highlight: bool = True, + categorical: bool = False, + legend: bool = True, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + width: float | str = "100%", + height: float | str = "100%", + categories: Sequence[Any] | NDArray[Any] | pd.Series[Any] | pd.Index[Any] | None = None, # categories can have "any" type + classification_kwds: MutableMapping[str, Any] | None = None, + control_scale: bool = True, + marker_type: str | folium.Marker | None = None, + # The following kwds will never be typed more precisely than "Any" + marker_kwds: MutableMapping[str, Any] = {}, + style_kwds: MutableMapping[str, Any] = {}, + highlight_kwds: MutableMapping[str, Any] = {}, + missing_kwds: MutableMapping[str, Any] = {}, + tooltip_kwds: MutableMapping[str, Any] = {}, + popup_kwds: MutableMapping[str, Any] = {}, + legend_kwds: MutableMapping[str, Any] = {}, + map_kwds: MutableMapping[str, Any] = {}, + **kwargs, +) -> folium.Map: ... +def _explore_geoseries( + s: GeoSeries, + color: str | ArrayLike | None = None, + m: folium.Map | None = None, + tiles: str | folium.TileLayer | xyzservices.TileProvider | None = "OpenStreetMap", + attr: str | None = None, + highlight: bool = True, + width: float | str = "100%", + height: float | str = "100%", + control_scale: bool = True, + marker_type: str | folium.Marker | None = None, + # The following kwds will never be typed more precisely than "Any" + marker_kwds: MutableMapping[str, Any] = {}, + style_kwds: MutableMapping[str, Any] = {}, + highlight_kwds: MutableMapping[str, Any] = {}, + map_kwds: MutableMapping[str, Any] = {}, + **kwargs, +) -> folium.Map: ... diff --git a/stubs/geopandas/geopandas/geodataframe.pyi b/stubs/geopandas/geopandas/geodataframe.pyi new file mode 100644 index 000000000000..f51ba3119945 --- /dev/null +++ b/stubs/geopandas/geopandas/geodataframe.pyi @@ -0,0 +1,370 @@ +import io +import os +from _typeshed import Incomplete, SupportsGetItem, SupportsLenAndGetItem, SupportsRead, SupportsWrite +from collections.abc import Callable, Container, Hashable, Iterable, Iterator, Mapping, Sequence +from json import JSONEncoder +from typing import Any, Literal, overload +from typing_extensions import Self + +import pandas as pd +from numpy.typing import ArrayLike +from pandas._typing import AggFuncTypeFrame, Axes, Axis, Dtype, GroupByObject, IndexLabel, Scalar +from pyproj import CRS + +from ._decorator import doc +from .base import ( + GeoPandasBase, + _BboxLike, + _ClipMask, + _ConvertibleToCRS, + _ConvertibleToDataFrame, + _GeomCol, + _GeomSeq, + _MaskLike, + _SupportsGeoInterface, +) +from .explore import _explore +from .geoseries import GeoSeries +from .io._geoarrow import ArrowTable, _GeomEncoding +from .io.sql import _SQLConnection +from .plotting import GeoplotAccessor + +crs_mismatch_error: str + +class GeoDataFrame(GeoPandasBase, pd.DataFrame): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + # Override the weird annotation of DataFrame.__new__ in pandas-stubs + @overload + def __new__( + cls, + data: _ConvertibleToDataFrame | None = None, + index: Axes | None = None, + columns: Axes | None = None, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> Self: ... + @overload + def __new__( + cls, + data: Scalar, + index: Axes, + columns: Axes, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> Self: ... + + def __init__( + self, + data: _ConvertibleToDataFrame | None = None, + index: Axes | None = None, + columns: Axes | None = None, + dtype: Dtype | None = None, + copy: bool | None = None, + *, + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + ) -> None: ... + def __setattr__(self, attr: str, val: Any) -> None: ... # type: ignore[misc] # Can set arbitrary objects + + @property + def geometry(self) -> GeoSeries: ... + @geometry.setter + def geometry(self, col: _GeomSeq) -> None: ... + + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None = None, inplace: Literal[False] = False, crs: _ConvertibleToCRS | None = None + ) -> Self: ... + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None = None, *, inplace: Literal[True], crs: _ConvertibleToCRS | None = None + ) -> None: ... + @overload + def set_geometry( + self, col: _GeomCol, drop: bool | None, inplace: Literal[True], crs: _ConvertibleToCRS | None = None + ) -> None: ... + + @overload + def rename_geometry(self, col: Hashable, inplace: Literal[False] = False) -> Self: ... + @overload + def rename_geometry(self, col: Hashable, inplace: Literal[True]) -> None: ... + + @property + def active_geometry_name(self) -> str | None: ... + + @property + def crs(self) -> CRS | None: ... + @crs.setter + def crs(self, value: _ConvertibleToCRS | None) -> None: ... + + @classmethod + def from_dict( # type: ignore[override] + # Mapping[Any, Any] because of invariance keys and arbitrary values + cls, + data: Mapping[Any, Any], + geometry: _GeomCol | None = None, + crs: _ConvertibleToCRS | None = None, + **kwargs, + ) -> Self: ... + # Keep inline with GeoSeries.from_file and geopandas.io.file._read_file + @classmethod + def from_file( + cls, + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + *, + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # engine dependent + ) -> Self: ... + @classmethod + def from_features( + cls, + features: ( + _SupportsGeoInterface + | Mapping[str, _SupportsGeoInterface | SupportsGetItem[str, Incomplete]] + | Iterable[_SupportsGeoInterface | SupportsGetItem[str, Incomplete]] + ), + crs: _ConvertibleToCRS | None = None, + columns: Axes | None = None, + ) -> Self: ... + + @overload + @classmethod + def from_postgis( + cls, + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | list[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + *, + chunksize: int, + ) -> Iterator[GeoDataFrame]: ... + @overload + @classmethod + def from_postgis( + cls, + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | list[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: None = None, + ) -> GeoDataFrame: ... + + @classmethod + def from_arrow( + cls, table, geometry: str | None = None, to_pandas_kwargs: Mapping[str, Incomplete] | None = None + ) -> GeoDataFrame: ... # TODO: `table: pyarrow.Table | table-like` + def to_json( # type: ignore[override] + self, + na: str = "null", + show_bbox: bool = False, + drop_id: bool = False, + to_wgs84: bool = False, + *, + # json.dumps kwargs + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[JSONEncoder] | None = None, + indent: int | str | None = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, # as typed in the json stdlib module + sort_keys: bool = False, + **kwargs, + ) -> str: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + def iterfeatures( + self, na: str = "null", show_bbox: bool = False, drop_id: bool = False + ) -> Iterator[dict[str, Incomplete]]: ... + def to_geo_dict(self, na: str = "null", show_bbox: bool = False, drop_id: bool = False) -> dict[str, Incomplete]: ... + def to_wkb( + self, + hex: bool = False, + *, + # shapely kwargs + output_dimension: int = ..., + byte_order: int = ..., + include_srid: bool = ..., + flavor: Literal["iso", "extended"] = ..., + **kwargs, + ) -> pd.DataFrame: ... + def to_wkt( + self, + *, + # shapely kwargs + rounding_precision: int = ..., + trim: bool = ..., + output_dimension: int = ..., + old_3d: bool = ..., + **kwargs, + ) -> pd.DataFrame: ... + def to_arrow( + self, + *, + index: bool | None = None, + geometry_encoding: _GeomEncoding = "WKB", + interleaved: bool = True, + include_z: bool | None = None, + ) -> ArrowTable: ... + def to_parquet( # type: ignore[override] + self, + path: str | os.PathLike[str] | SupportsWrite[Incomplete], + index: bool | None = None, + compression: Literal["snappy", "gzip", "brotli", "lz4", "zstd"] | None = "snappy", + geometry_encoding: _GeomEncoding = "WKB", + write_covering_bbox: bool = False, + schema_version: str | None = None, + *, + engine: Literal["auto", "pyarrow"] = "auto", # Only these engines are supported, unlike pandas + **kwargs, + ) -> None: ... + def to_feather( + self, + path: str | os.PathLike[str] | SupportsWrite[Incomplete], + index: bool | None = None, + compression: Literal["zstd", "lz4", "uncompressed"] | None = None, + schema_version: str | None = None, + **kwargs, + ) -> None: ... + # Keep method to_file roughly in line with GeoSeries.to_file + def to_file( + self, + filename: str | os.PathLike[str] | io.BytesIO, + driver: str | None = None, + schema: dict[str, Incomplete] | None = None, + index: bool | None = None, + *, + # kwargs from `_to_file` function + mode: Literal["w", "a"] = "w", + crs: _ConvertibleToCRS | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + metadata: dict[str, str] | None = None, + # kwargs extracted from engines + layer: int | str | None = None, + encoding: str | None = None, + overwrite: bool | None = ..., + **kwargs, # engine and driver dependent + ) -> None: ... + + @overload + def set_crs( + self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs( + self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: bool = False, allow_override: bool = False) -> Self: ... + + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: Literal[False] = False) -> Self: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None, *, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: Literal[True]) -> None: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: Literal[True]) -> None: ... + + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + # def __getitem__(self, key): ... + def __delitem__(self, key) -> None: ... # type: ignore[misc] + # def __setitem__(self, key, value) -> None: ... + def copy(self, deep: bool = True) -> Self: ... # type: ignore[misc] + # def merge(self, *args, **kwargs) -> GeoDataFrame | pd.DataFrame: ... + def apply( # type: ignore[override] + self, + func: Callable[..., Incomplete], + axis: Axis = 0, + raw: bool = False, + result_type: Literal["expand", "reduce", "broadcast"] | None = None, + args: tuple[Any, ...] = (), # type inexpressible in the typing system + *, + by_row: Literal[False, "compat"] = "compat", + engine: Literal["python", "numba"] = "python", + engine_kwargs: dict[str, bool] | None = None, + **kwargs, + ) -> pd.DataFrame | pd.Series[Incomplete]: ... + def __finalize__(self, other, method: str | None = None, **kwargs) -> Self: ... # type: ignore[misc] + def dissolve( + self, + by: GroupByObject | None = None, + aggfunc: AggFuncTypeFrame = "first", + as_index: bool = True, + level: IndexLabel | None = None, + sort: bool = True, + observed: bool = False, + dropna: bool = True, + method: Literal["coverage", "unary", "disjoint_subset"] = "unary", + grid_size: float | None = None, + **kwargs, + ) -> GeoDataFrame: ... + def explode(self, column: IndexLabel | None = None, ignore_index: bool = False, index_parts: bool = False) -> Self: ... + def to_postgis( + self, + name: str, + con: _SQLConnection, + schema: str | None = None, + if_exists: Literal["fail", "replace", "append"] = "fail", + index: bool = False, + index_label: IndexLabel | None = None, + chunksize: int | None = None, + dtype: dict[Any, Incomplete] | None = None, # columns can be of "any" type + ) -> None: ... + @property + def plot(self) -> GeoplotAccessor: ... + @doc(_explore) # pyright: ignore[reportUnknownArgumentType] + def explore(self, *args, **kwargs): ... # signature of `_explore` copied in `@doc` + def sjoin( + self, + df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + predicate: str = "intersects", + lsuffix: str = "left", + rsuffix: str = "right", + *, + # **kwargs passed to geopandas.sjoin + distance: float | ArrayLike | None = None, + on_attribute: str | Sequence[str] | None = None, + **kwargs, + ) -> GeoDataFrame: ... + def sjoin_nearest( + self, + right: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + max_distance: float | None = None, + lsuffix: str = "left", + rsuffix: str = "right", + distance_col: str | None = None, + exclusive: bool = False, + ) -> GeoDataFrame: ... + def clip(self, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> GeoDataFrame: ... # type: ignore[override] + def overlay( + self, right: GeoDataFrame, how: str = "intersection", keep_geom_type: bool | None = None, make_valid: bool = True + ) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/geoseries.pyi b/stubs/geopandas/geopandas/geoseries.pyi new file mode 100644 index 000000000000..764fdb0a79a6 --- /dev/null +++ b/stubs/geopandas/geopandas/geoseries.pyi @@ -0,0 +1,218 @@ +import io +import json +import os +from _typeshed import Incomplete, SupportsRead +from collections.abc import Callable, Hashable +from typing import Any, Literal, final, overload +from typing_extensions import Self + +import pandas as pd +from numpy.typing import ArrayLike +from pandas._typing import Axes, Dtype +from pyproj import CRS +from shapely.geometry.base import BaseGeometry + +from ._decorator import doc +from .array import GeometryArray +from .base import GeoPandasBase, _BboxLike, _ClipMask, _ConvertibleToCRS, _ConvertibleToGeoSeries, _MaskLike +from .explore import _explore_geoseries +from .io._geoarrow import GeoArrowArray +from .plotting import plot_series + +class GeoSeries(GeoPandasBase, pd.Series[BaseGeometry]): # type: ignore[type-var,misc] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-type-arguments] # pyrefly: ignore [bad-specialization, inconsistent-inheritance] + # Override the weird annotation of Series.__new__ in pandas-stubs + def __new__( + self, + data: _ConvertibleToGeoSeries | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + def __init__( + self, + data: _ConvertibleToGeoSeries | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> None: ... + @final # type: ignore[misc] + def copy(self, deep: bool = True) -> Self: ... + @property + def values(self) -> GeometryArray: ... + @property + def geometry(self) -> Self: ... + @property + def x(self) -> pd.Series[float]: ... + @property + def y(self) -> pd.Series[float]: ... + @property + def z(self) -> pd.Series[float]: ... + @property + def m(self) -> pd.Series[float]: ... + # Keep inline with GeoDataFrame.from_file and geopandas.io.file._read_file + @classmethod + def from_file( + cls, + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + *, + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # engine dependent + ) -> GeoSeries: ... + @classmethod + def from_wkb( + cls, + data: ArrayLike, # array-like of bytes handled by shapely.from_wkb(data) + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_wkt( + cls, + data: ArrayLike, # array-like of str handled by shapely.from_wkt(data) + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_xy( + cls, + # x, y, z: array-like of floats handled by np.asarray(..., dtype="float64") + x: ArrayLike, + y: ArrayLike, + z: ArrayLike | None = None, + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + *, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @classmethod + def from_arrow( + cls, + arr, + *, + # GeoSeries constructor kwargs + index: Axes | None = None, + crs: _ConvertibleToCRS | None = None, + dtype: Dtype | None = None, + name: Hashable = None, + copy: bool | None = None, + fastpath: bool = False, + ) -> Self: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... # values are arbitrary + # Keep method to_file roughly in line with GeoDataFrame.to_file + def to_file( + self, + filename: str | os.PathLike[str] | io.BytesIO, + driver: str | None = None, + index: bool | None = None, + *, + # kwargs from `_to_file` function + schema: dict[str, Incomplete] | None = None, + mode: Literal["w", "a"] = "w", + crs: _ConvertibleToCRS | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + metadata: dict[str, str] | None = None, + # kwargs extracted from engines + layer: int | str | None = None, + encoding: str | None = None, + overwrite: bool | None = ..., + **kwargs, # engine and driver dependent + ) -> None: ... + # *** `__getitem__`, `sort_index` and `take` are annotated with `-> Self` in pandas-stubs; no need to override them *** + # *** `apply` annotation in pandas-stubs is compatible except for deprecated `convert_dtype` argument *** + # def apply(self, func, convert_dtype: bool | None = None, args=(), **kwargs): ... + def isna(self) -> pd.Series[bool]: ... + def isnull(self) -> pd.Series[bool]: ... + def notna(self) -> pd.Series[bool]: ... + def notnull(self) -> pd.Series[bool]: ... + # *** TODO: `fillna` annotation in pandas-stubs is NOT compatible; must `-> Self` *** + # def fillna(self, value=None, method: FillnaOptions | None = None, inplace: bool = False, **kwargs): ... + def __contains__(self, other: object) -> bool: ... # type: ignore[misc] + @doc(plot_series) + def plot(self, *args, **kwargs): ... # type: ignore[override] # signature of `plot_series` copied in `@doc` + @doc(_explore_geoseries) # pyright: ignore[reportUnknownArgumentType] + def explore(self, *args, **kwargs): ... # signature of `_explore_geoseries` copied in `@doc` + def explode(self, ignore_index: bool = False, index_parts: bool = False) -> GeoSeries: ... + + @overload + def set_crs( + self, crs: _ConvertibleToCRS, epsg: int | None = None, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs( + self, crs: _ConvertibleToCRS | None = None, *, epsg: int, inplace: bool = False, allow_override: bool = False + ) -> Self: ... + @overload + def set_crs(self, crs: _ConvertibleToCRS | None, epsg: int, inplace: bool = False, allow_override: bool = False) -> Self: ... + + @overload + def to_crs(self, crs: _ConvertibleToCRS, epsg: int | None = None) -> GeoSeries: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None = None, *, epsg: int) -> GeoSeries: ... + @overload + def to_crs(self, crs: _ConvertibleToCRS | None, epsg: int) -> GeoSeries: ... + + def estimate_utm_crs(self, datum_name: str = "WGS 84") -> CRS: ... + def to_json( # type: ignore[override] + self, + show_bbox: bool = True, + drop_id: bool = False, + to_wgs84: bool = False, + *, + # Keywords from json.dumps + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = True, + cls: type[json.JSONEncoder] | None = None, + indent: None | int | str = None, + separators: tuple[str, str] | None = None, + default: Callable[..., Any] | None = None, # as typed in the json stdlib module + sort_keys: bool = False, + **kwds, + ) -> str: ... + + @overload + def to_wkb(self, hex: Literal[False] = False, **kwargs) -> pd.Series[bytes]: ... + @overload + def to_wkb(self, hex: Literal[True], **kwargs) -> pd.Series[str]: ... + @overload + def to_wkb(self, hex: bool = False, **kwargs) -> pd.Series[str] | pd.Series[bytes]: ... + + def to_wkt(self, **kwargs) -> pd.Series[str]: ... + def to_arrow( + self, + geometry_encoding: Literal["WKB", "geoarrow", "wkb", "GeoArrow"] = "WKB", + interleaved: bool | None = True, + include_z: bool | None = None, + ) -> GeoArrowArray: ... + def clip(self, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> GeoSeries: ... # type: ignore[override] diff --git a/stubs/geopandas/geopandas/io/__init__.pyi b/stubs/geopandas/geopandas/io/__init__.pyi new file mode 100644 index 000000000000..43612d29b8bc --- /dev/null +++ b/stubs/geopandas/geopandas/io/__init__.pyi @@ -0,0 +1 @@ +from . import arrow as arrow, file as file, sql as sql diff --git a/stubs/geopandas/geopandas/io/_geoarrow.pyi b/stubs/geopandas/geopandas/io/_geoarrow.pyi new file mode 100644 index 000000000000..720cd25f9358 --- /dev/null +++ b/stubs/geopandas/geopandas/io/_geoarrow.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import ( + # pyarrow types returned as Any to avoid depending on pyarrow (40 MB) in stubs + Any as _PAArray, + Any as _PAField, + Any as _PATable, + Literal, + Protocol, + TypeAlias, + type_check_only, +) +from typing_extensions import CapsuleType + +import numpy as np +from numpy.typing import NDArray + +from ..array import GeometryArray +from ..geodataframe import GeoDataFrame + +# Literal for language server completions and str because runtime normalizes to lowercase +_GeomEncoding: TypeAlias = Literal["WKB", "geoarrow"] | str # noqa: Y051 + +@type_check_only +class _PyarrowTableLike(Protocol): + def __arrow_c_stream__(self, requested_schema=None) -> CapsuleType: ... + +@type_check_only +class _PyarrowFieldLike(Protocol): + def __arrow_c_schema__(self) -> CapsuleType: ... + +@type_check_only +class _PyarrowArrayLike(Protocol): + def __arrow_c_array__(self) -> tuple[CapsuleType, CapsuleType]: ... + +GEOARROW_ENCODINGS: list[str] + +class ArrowTable: + def __init__(self, pa_table: _PyarrowTableLike) -> None: ... + def __arrow_c_stream__(self, requested_schema=None) -> CapsuleType: ... + +class GeoArrowArray: + def __init__(self, pa_field: _PyarrowFieldLike, pa_array: _PyarrowArrayLike) -> None: ... + def __arrow_c_array__(self, requested_schema=None) -> tuple[CapsuleType, CapsuleType]: ... + +def geopandas_to_arrow( + df: GeoDataFrame, + index: bool | None = None, + geometry_encoding: _GeomEncoding = "WKB", + interleaved: bool = True, + include_z: bool | None = None, +) -> tuple[_PATable, dict[str, str]]: ... +def construct_wkb_array( + shapely_arr: NDArray[np.object_], *, field_name: str = "geometry", crs: str | None = None +) -> tuple[_PAField, _PAArray]: ... +def construct_geometry_array( + shapely_arr: NDArray[np.object_], + include_z: bool | None = None, + *, + field_name: str = "geometry", + crs: str | None = None, + interleaved: bool = True, +) -> tuple[_PAField, _PAArray]: ... +def arrow_to_geopandas( + table, geometry: str | None = None, to_pandas_kwargs: Mapping[str, Incomplete] | None = None +) -> GeoDataFrame: ... +def arrow_to_geometry_array(arr) -> GeometryArray: ... +def construct_shapely_array(arr: _PAArray, extension_name: str) -> NDArray[np.object_]: ... diff --git a/stubs/geopandas/geopandas/io/arrow.pyi b/stubs/geopandas/geopandas/io/arrow.pyi new file mode 100644 index 000000000000..88e2419b8d1e --- /dev/null +++ b/stubs/geopandas/geopandas/io/arrow.pyi @@ -0,0 +1,28 @@ +import os +from _typeshed import Incomplete, SupportsGetItem, SupportsKeysAndGetItem +from collections.abc import Iterable, Mapping +from typing import Any, Final + +from ..geodataframe import GeoDataFrame + +METADATA_VERSION: Final[str] +SUPPORTED_VERSIONS_LITERAL = Incomplete +SUPPORTED_VERSIONS: Final[list[str]] +GEOARROW_ENCODINGS: Final[list[str]] +SUPPORTED_ENCODINGS: Final[list[str]] +PARQUET_GEOMETRY_ENCODINGS = Incomplete + +def _read_parquet( + path: str | os.PathLike[str], + columns: Iterable[str] | None = None, + storage_options: SupportsKeysAndGetItem[str, Any] | None = None, # type depend on the connection + bbox: SupportsGetItem[int, float] | None = None, + to_pandas_kwargs: Mapping[str, Incomplete] | None = None, + **kwargs, # kwargs passed to pyarrow.parquet.read_table +) -> GeoDataFrame: ... +def _read_feather( + path: str | os.PathLike[str], + columns: Iterable[str] | None = None, + to_pandas_kwargs: Mapping[str, Incomplete] | None = None, + **kwargs, # kwargs passed to pyarrow.feather.read_table +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/io/file.pyi b/stubs/geopandas/geopandas/io/file.pyi new file mode 100644 index 000000000000..ec2b63b9e198 --- /dev/null +++ b/stubs/geopandas/geopandas/io/file.pyi @@ -0,0 +1,48 @@ +import os +from _typeshed import Incomplete, SupportsRead +from collections import OrderedDict +from typing import Literal, TypedDict, overload, type_check_only + +import pandas as pd +from pandas._typing import Axes + +from ..base import _BboxLike, _MaskLike +from ..geodataframe import GeoDataFrame + +# Keep inline with GeoDataFrame.from_file and GeoSeries.from_file +@overload +def _read_file( + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + columns: Axes | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + *, + ignore_geometry: Literal[False] = False, + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # depend on engine +) -> GeoDataFrame: ... +@overload +def _read_file( + filename: str | os.PathLike[str] | SupportsRead[Incomplete], + bbox: _BboxLike | None = None, + mask: _MaskLike | None = None, + columns: Axes | None = None, + rows: int | slice | None = None, + engine: Literal["fiona", "pyogrio"] | None = None, + *, + ignore_geometry: Literal[True], + layer: int | str | None = None, + encoding: str | None = None, + **kwargs, # depend on engine +) -> pd.DataFrame: ... + +@type_check_only +class _Schema(TypedDict): + geometry: str | list[str] + properties: OrderedDict[str, str] + +def infer_schema(df: GeoDataFrame) -> _Schema: ... +def _list_layers(filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | SupportsRead[Incomplete]) -> pd.DataFrame: ... diff --git a/stubs/geopandas/geopandas/io/sql.pyi b/stubs/geopandas/geopandas/io/sql.pyi new file mode 100644 index 000000000000..a68afccb51ed --- /dev/null +++ b/stubs/geopandas/geopandas/io/sql.pyi @@ -0,0 +1,117 @@ +import sqlite3 +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Container, Iterator, Mapping +from contextlib import AbstractContextManager +from typing import Any, Protocol, TypeAlias, overload, type_check_only + +from pandas._typing import Scalar + +from ..base import _ConvertibleToCRS +from ..geodataframe import GeoDataFrame + +# Start SQLAlchemy hack +# --------------------- +# The code actually explicitly checks for SQLAlchemy's `Connection` and `Engine` with +# isinstance checks. However to avoid a dependency on SQLAlchemy, we use "good-enough" +# protocols that match as much as possible the SQLAlchemy implementation. This makes it +# very hard for someone to pass in the wrong object. +@type_check_only +class _SqlalchemyTransactionLike(Protocol): + # is_active: bool + # connection: _SqlalchemyConnectionLike + # def __init__(self, connection: _SqlalchemyConnectionLike): ... + # @property + # def is_valid(self) -> bool: ... + def close(self) -> None: ... + def rollback(self) -> None: ... + def commit(self) -> None: ... + +# `Any` is used in places where it would require to copy a lot of types from sqlalchemy +@type_check_only +class _SqlAlchemyEventTarget(Protocol): + dispatch: Any + +@type_check_only +class _SqlalchemyConnectionLike(_SqlAlchemyEventTarget, Protocol): + engine: Any + @property + def closed(self) -> bool: ... + @property + def invalidated(self) -> bool: ... + def __enter__(self) -> _SqlalchemyConnectionLike: ... # noqa: Y034 + def __exit__(self, type_, value, traceback, /) -> None: ... + @property + def info(self) -> dict[Any, Any]: ... + def invalidate(self, exception: BaseException | None = None) -> None: ... + def detach(self) -> None: ... + def begin(self) -> _SqlalchemyTransactionLike: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def recover_twophase(self) -> list[Any]: ... + def rollback_prepared(self, xid: Any, recover: bool = ...) -> None: ... + def commit_prepared(self, xid: Any, recover: bool = ...) -> None: ... + def in_transaction(self) -> bool: ... + def in_nested_transaction(self) -> bool: ... + def close(self) -> None: ... + +@type_check_only +class _SqlalchemyEngineLike(_SqlAlchemyEventTarget, Protocol): + dialect: Any + pool: Any + url: Any + hide_parameters: bool + @property + def engine(self) -> _SqlalchemyEngineLike: ... + def clear_compiled_cache(self) -> None: ... + def update_execution_options(self, **opt: Any) -> None: ... + @property + def name(self) -> str: ... + @property + def driver(self) -> str: ... + def dispose(self, close: bool = True) -> None: ... + def begin(self) -> AbstractContextManager[Any]: ... + def connect(self) -> Any: ... + +_SqlalchemyConnectableLike: TypeAlias = _SqlalchemyConnectionLike | _SqlalchemyEngineLike +# --------------------- +# End SQLAlchemy hack + +_SQLConnection: TypeAlias = str | _SqlalchemyConnectableLike | sqlite3.Connection # coppied from pandas.io.sql + +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + *, + chunksize: int, +) -> Iterator[GeoDataFrame]: ... +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: None = None, +) -> GeoDataFrame: ... +@overload +def _read_postgis( + sql: str, + con: _SQLConnection, + geom_col: str = "geom", + crs: _ConvertibleToCRS | None = None, + index_col: str | Container[str] | None = None, + coerce_float: bool = True, + parse_dates: Container[str | Mapping[str, Incomplete]] | Mapping[str, str | Mapping[str, Incomplete]] | None = None, + params: SupportsLenAndGetItem[Scalar] | Mapping[str, Scalar] | None = None, + chunksize: int | None = None, +) -> GeoDataFrame | Iterator[GeoDataFrame]: ... diff --git a/stubs/geopandas/geopandas/plotting.pyi b/stubs/geopandas/geopandas/plotting.pyi new file mode 100644 index 000000000000..4d08e752d64c --- /dev/null +++ b/stubs/geopandas/geopandas/plotting.pyi @@ -0,0 +1,259 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Hashable, Iterable, Mapping, Sequence +from typing import Literal, TypeAlias, overload + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.colors import Colormap, Normalize # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] +from numpy.typing import ArrayLike, NDArray +from pandas.plotting import PlotAccessor + +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +_ColorOrColors: TypeAlias = ColorType | Sequence[ColorType] | ArrayLike + +def plot_series( + s: GeoSeries, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + figsize: tuple[float, float] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + autolim: bool = True, + *, + # Extracted from `**style_kwds` + vmin: float = ..., + vmax: float = ..., + facecolor: _ColorOrColors | None = None, + norm: Normalize | None = None, + **style_kwds, +) -> Axes: ... + +# IMPORTANT: keep roughly in sync with `GeoplotAccessor` methods below +def plot_dataframe( + df: GeoDataFrame, + column: Hashable | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + autolim: bool = True, + *, + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, +) -> Axes: ... + +# IMPORTANT: keep roughly in sync with `plot_dataframe` +class GeoplotAccessor(PlotAccessor): + # The first 3 overloads of calls are from pandas, the last overload is geopandas specific + @overload # type: ignore[override] + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["line", "bar", "barh", "hist", "box", "kde", "density", "area", "pie", "scatter", "hexbin"], + ax: Axes | None = None, + subplots: Literal[False] = False, + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> Axes: ... + @overload + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["line", "bar", "barh", "hist", "kde", "density", "area", "pie", "scatter", "hexbin"], + ax: Sequence[Axes] | None = None, + subplots: Literal[True] | Iterable[Iterable[Hashable]], + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | Collection[str] | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> NDArray[np.object_]: ... # should be NDArray[Axes] but it is not supported + @overload + def __call__( + self, + x: Hashable = ..., + y: Hashable | Sequence[Hashable] = ..., + *, + kind: Literal["box"], + ax: Sequence[Axes] | None = None, + subplots: Literal[True] | Iterable[Iterable[Hashable]], + sharex: bool | None = None, + sharey: bool | None = None, + layout: tuple[int, int] | None = None, + figsize: tuple[float, float] | None = None, + use_index: bool = True, + title: str | Collection[str] | None = None, + grid: bool | None = None, + legend: bool | Literal["reverse"] = True, + style: str | Sequence[str] | Mapping[Incomplete, str] | None = None, + logx: bool | Literal["sym"] = False, + logy: bool | Literal["sym"] = False, + loglog: bool | Literal["sym"] = False, + xticks: Sequence[float] | None = None, + yticks: Sequence[float] | None = None, + xlim: tuple[float, float] | list[float] | None = None, + ylim: tuple[float, float] | list[float] | None = None, + xlabel: str | None = None, + ylabel: str | None = None, + rot: float | None = None, + fontsize: float | None = None, + cmap: str | Colormap | None = None, # also accepts `colormap` but plot_dataframe uses `cmap` + colorbar: bool | None = None, + position: float = 0.5, + table: bool | pd.Series[Incomplete] | pd.DataFrame = False, + yerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + xerr: pd.DataFrame | pd.Series[float] | ArrayLike | Mapping[Incomplete, ArrayLike] | str = ..., + stacked: bool = ..., # default value depends on kind + secondary_y: bool | Sequence[Hashable] = False, + mark_right: bool = True, + include_bool: bool = False, + backend: str | None = None, + **kwargs, + ) -> pd.Series[Axes]: ... # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-type-arguments] # pyrefly: ignore [bad-specialization] + @overload + def __call__( + self, + column: Hashable | pd.Series | pd.Index | NDArray | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + *, + kind: Literal["geo"] = "geo", + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, + ) -> Axes: ... + + def geo( + self, + column: Hashable | pd.Series | pd.Index | NDArray | None = None, + cmap: str | Colormap | None = None, + color: _ColorOrColors | None = None, + ax: Axes | None = None, + cax: Axes | None = None, + categorical: bool = False, + legend: bool = False, + scheme: str | None = None, + k: int = 5, + vmin: float | None = None, + vmax: float | None = None, + markersize: str | float | Iterable[float] | ArrayLike | None = None, + figsize: tuple[float, float] | None = None, + legend_kwds: dict[str, Incomplete] | None = None, + categories: Iterable[Hashable] | None = None, + classification_kwds: dict[str, Incomplete] | None = None, + missing_kwds: dict[str, Incomplete] | None = None, + aspect: Literal["auto", "equal"] | float | None = "auto", + *, + # Extracted from `**style_kwds` + norm: Normalize | None = None, + alpha: float = 1, + facecolor: _ColorOrColors | None = None, + edgecolor: _ColorOrColors | None = None, + linewidth: float = ..., + label: str = "NaN", + **style_kwds, + ) -> Axes: ... diff --git a/stubs/geopandas/geopandas/sindex.pyi b/stubs/geopandas/geopandas/sindex.pyi new file mode 100644 index 000000000000..1ef9bcb01ad9 --- /dev/null +++ b/stubs/geopandas/geopandas/sindex.pyi @@ -0,0 +1,82 @@ +from collections.abc import Iterable +from typing import Any, Final, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from shapely import Geometry + +from .array import _Array1D, _Array2D + +PREDICATES: Final[set[str | None]] + +class SpatialIndex: + geometries: NDArray[np.object_] + def __init__(self, geometry: NDArray[np.object_]) -> None: ... + @property + def valid_query_predicates(self) -> set[str | None]: ... + + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + output_format: Literal["indices"] = "indices", + ) -> NDArray[np.int64]: ... + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + *, + output_format: Literal["dense"], + ) -> NDArray[np.bool_]: ... + @overload + def query( + self, + geometry: Geometry | ArrayLike, + predicate: str | None = None, + sort: bool = False, + distance: float | ArrayLike | None = None, + *, + output_format: Literal["sparse"], + ) -> Any: ... # returns scipy coo_array but we don't depend on scipy + + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + return_distance: Literal[False] = False, + exclusive: bool = False, + ) -> _Array2D[np.int64]: ... + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + *, + return_distance: Literal[True], + exclusive: bool = False, + ) -> tuple[_Array2D[np.int64], _Array1D[np.float64]]: ... + @overload + def nearest( + self, + geometry, + return_all: bool = True, + max_distance: float | None = None, + return_distance: bool = False, + exclusive: bool = False, + ) -> _Array2D[np.int64] | tuple[_Array2D[np.int64], _Array1D[np.float64]]: ... + + def intersection(self, coordinates: Iterable[float]) -> _Array1D[np.int64]: ... + @property + def size(self) -> int: ... + @property + def is_empty(self) -> bool: ... + def __len__(self) -> int: ... diff --git a/stubs/geopandas/geopandas/testing.pyi b/stubs/geopandas/geopandas/testing.pyi new file mode 100644 index 000000000000..5293b09b40fc --- /dev/null +++ b/stubs/geopandas/geopandas/testing.pyi @@ -0,0 +1,33 @@ +from typing import Literal + +from .array import GeometryArray +from .base import GeoPandasBase +from .geodataframe import GeoDataFrame +from .geoseries import GeoSeries + +def geom_equals(this: GeoPandasBase | GeometryArray, that: GeoPandasBase | GeometryArray) -> bool: ... +def geom_almost_equals(this: GeoPandasBase | GeometryArray, that: GeoPandasBase | GeometryArray) -> bool: ... +def assert_geoseries_equal( + left: GeoSeries, + right: GeoSeries, + check_dtype: bool = True, + check_index_type: bool = False, + check_series_type: bool = True, + check_less_precise: bool = False, + check_geom_type: bool = False, + check_crs: bool = True, + normalize: bool = False, +) -> None: ... +def assert_geodataframe_equal( + left: GeoDataFrame, + right: GeoDataFrame, + check_dtype: bool = True, + check_index_type: bool | Literal["equiv"] = "equiv", + check_column_type: bool | Literal["equiv"] = "equiv", + check_frame_type: bool = True, + check_like: bool = False, + check_less_precise: bool = False, + check_geom_type: bool = False, + check_crs: bool = True, + normalize: bool = False, +) -> None: ... diff --git a/stubs/geopandas/geopandas/tools/__init__.pyi b/stubs/geopandas/geopandas/tools/__init__.pyi new file mode 100644 index 000000000000..a194399c228c --- /dev/null +++ b/stubs/geopandas/geopandas/tools/__init__.pyi @@ -0,0 +1,7 @@ +from .clip import clip as clip +from .geocoding import geocode as geocode, reverse_geocode as reverse_geocode +from .overlay import overlay as overlay +from .sjoin import sjoin as sjoin, sjoin_nearest as sjoin_nearest +from .util import collect as collect + +__all__ = ["collect", "geocode", "overlay", "reverse_geocode", "sjoin", "sjoin_nearest", "clip"] diff --git a/stubs/geopandas/geopandas/tools/_show_versions.pyi b/stubs/geopandas/geopandas/tools/_show_versions.pyi new file mode 100644 index 000000000000..1eeec0747405 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/_show_versions.pyi @@ -0,0 +1 @@ +def show_versions() -> None: ... diff --git a/stubs/geopandas/geopandas/tools/clip.pyi b/stubs/geopandas/geopandas/tools/clip.pyi new file mode 100644 index 000000000000..bf91bbce3bbb --- /dev/null +++ b/stubs/geopandas/geopandas/tools/clip.pyi @@ -0,0 +1,9 @@ +from typing import TypeVar + +from ..base import _ClipMask +from ..geodataframe import GeoDataFrame +from ..geoseries import GeoSeries + +_G = TypeVar("_G", GeoDataFrame, GeoSeries) + +def clip(gdf: _G, mask: _ClipMask, keep_geom_type: bool = False, sort: bool = False) -> _G: ... diff --git a/stubs/geopandas/geopandas/tools/geocoding.pyi b/stubs/geopandas/geopandas/tools/geocoding.pyi new file mode 100644 index 000000000000..3748d7945de1 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/geocoding.pyi @@ -0,0 +1,18 @@ +from collections.abc import Callable, Iterable +from typing import Protocol, type_check_only + +from ..base import _ConvertibleToGeoSeries +from ..geodataframe import GeoDataFrame + +@type_check_only +class _GeoCoder(Protocol): + # Represents a geopy.geocoders.base.GeoCoder subclass without actually depending on geopy + def geocode(self, query: str, /): ... + def reverse(self, coords, /, exactly_one: bool = ...): ... + +# TODO: Use something like `provider: Callable[P, _GeoCoder], **kwargs: P.kwargs` in the functions +# below if this ever becomes a thing +def geocode(strings: Iterable[str], provider: str | Callable[..., _GeoCoder] | None = None, **kwargs) -> GeoDataFrame: ... +def reverse_geocode( + points: _ConvertibleToGeoSeries, provider: str | Callable[..., _GeoCoder] | None = None, **kwargs +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/hilbert_curve.pyi b/stubs/geopandas/geopandas/tools/hilbert_curve.pyi new file mode 100644 index 000000000000..9e9993ad673a --- /dev/null +++ b/stubs/geopandas/geopandas/tools/hilbert_curve.pyi @@ -0,0 +1 @@ +MAX_LEVEL: int diff --git a/stubs/geopandas/geopandas/tools/overlay.pyi b/stubs/geopandas/geopandas/tools/overlay.pyi new file mode 100644 index 000000000000..082d0ac5b15c --- /dev/null +++ b/stubs/geopandas/geopandas/tools/overlay.pyi @@ -0,0 +1,11 @@ +from typing import Literal + +from ..geodataframe import GeoDataFrame + +def overlay( + df1: GeoDataFrame, + df2: GeoDataFrame, + how: Literal["intersection", "union", "identity", "symmetric_difference", "difference"] = "intersection", + keep_geom_type: bool | None = None, + make_valid: bool = True, +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/sjoin.pyi b/stubs/geopandas/geopandas/tools/sjoin.pyi new file mode 100644 index 000000000000..a902f71d3e05 --- /dev/null +++ b/stubs/geopandas/geopandas/tools/sjoin.pyi @@ -0,0 +1,26 @@ +from typing import Literal + +from numpy.typing import ArrayLike + +from ..geodataframe import GeoDataFrame + +def sjoin( + left_df: GeoDataFrame, + right_df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + predicate: str = "intersects", + lsuffix: str = "left", + rsuffix: str = "right", + distance: float | ArrayLike | None = None, + on_attribute: str | tuple[str, ...] | list[str] | None = None, +) -> GeoDataFrame: ... +def sjoin_nearest( + left_df: GeoDataFrame, + right_df: GeoDataFrame, + how: Literal["left", "right", "inner"] = "inner", + max_distance: float | None = None, + lsuffix: str = "left", + rsuffix: str = "right", + distance_col: str | None = None, + exclusive: bool = False, +) -> GeoDataFrame: ... diff --git a/stubs/geopandas/geopandas/tools/util.pyi b/stubs/geopandas/geopandas/tools/util.pyi new file mode 100644 index 000000000000..ea80edd4c6aa --- /dev/null +++ b/stubs/geopandas/geopandas/tools/util.pyi @@ -0,0 +1,12 @@ +from collections.abc import Collection +from typing import Any + +import pandas as pd +from shapely import Geometry +from shapely.geometry.base import BaseGeometry + +from ..geoseries import GeoSeries + +def collect( + x: Collection[Geometry] | GeoSeries | pd.Series[Any] | Geometry, multi: bool = False # Cannot use pd.Series[BaseGeometry] +) -> BaseGeometry: ... diff --git a/stubs/gevent/@tests/stubtest_allowlist.txt b/stubs/gevent/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ed67e0945e91 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist.txt @@ -0,0 +1,164 @@ +# TODO: missing from stub +gevent.os.__all__ +gevent.socket.__all__ +gevent.ssl.__all__ +gevent.subprocess.__all__ + +# Error: failed to find stubs +# ============================= +# testing modules are not included in type stubs +gevent.testing +gevent.testing.* +gevent.tests +gevent.tests.* + +# these are only present for monkey patching and should not be used directly +gevent.thread +gevent.threading + +# deprecated module which should not be used anymore +gevent.builtins +gevent.contextvars +gevent.core + +# part of internal API which is not needed for public type stubs +gevent._ffi.callback + +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent._config.Config.subclass +gevent._ffi.CRITICAL +gevent._ffi.DEBUG +gevent._ffi.ERROR +gevent._ffi.GEVENT_DEBUG_LEVEL +gevent._ffi.TRACE +gevent._ffi.loop.AbstractLoop.async +gevent._fileobjectcommon.UniversalNewlineBytesWrapper +gevent._waiter.Waiter.switch_args + +# loop local that wasn't deleted +gevent.resolver.blocking.Resolver.method + +# isn't actually implemented for libuv, it just raises an exception +gevent.libuv.watcher.watcher.feed + +# unnecessary python 2 compatibility stuff +gevent._config.Config.trace_malloc +gevent._imap.IMapUnordered.next +gevent.pywsgi.Environ.iteritems + +# weird method that doesn't work with this being generic, so we removed it +# it's not necessary for public API +gevent.hub.Waiter.switch_args + +# zope.interface related attributes we can ignore +gevent.[\w\.]+\.__implemented__ +gevent.[\w\.]+\.__providedBy__ +gevent.[\w\.]+\.__provides__ + +# these shouldn't be in __all__ they end up there, due to how gevent imports +# the globals from the stdlib ssl module, For ssl/subprocess we ignore all symbols +# that start with an underscore (i.e. internal symbols) +gevent\.ssl\._[A-Za-z0-9]\w* +gevent.ssl.base64 +gevent.ssl.create_connection +gevent.ssl.errno +gevent.ssl.os +gevent.ssl.warnings +gevent\.subprocess\._[A-Za-z0-9]\w* + +# Error: differs from runtime type +# ====================== +# these are None in the base class, but all settings are a subclass +# so it makes sense to annotate this as not None +gevent._config.Setting.default +gevent._config.Setting.environment_key +gevent._config.Setting.name +gevent._config.Setting.value + +# it is set to None on the class but always initialized in __init__ +gevent.hub.Hub.thread_ident +gevent.pywsgi.WSGIServer.error_log +gevent.pywsgi.WSGIServer.log + +# Error: is inconsistent +# ====================== +# minor config validation implementation difference that don't matter for +# the actual subclasses, which are proper settings. +gevent._config.SettingType.__new__ +gevent._config._PositiveValueMixin.validate + +# internal API implementation detail we don't care about +gevent._ffi.watcher.AbstractWatcherType.__new__ + +# we don't care about write/writeall allowing a named parameter +gevent._fileobjectcommon.FlushingBufferedWriter.write +gevent._fileobjectcommon.WriteIsWriteallMixin.write +gevent._fileobjectcommon.WriteallMixin.writeall + +# these are different because of Cython, without Cython these don't have +# any arguments, so it should be annotated that way +gevent._ident.IdentRegistry.__init__ +gevent.event.AsyncResult.__init__ +gevent.event.Event.__init__ + +# positional only arguments due to Cython? +gevent._abstract_linkable.AbstractLinkable.rawlink +gevent._abstract_linkable.AbstractLinkable.unlink + +# removed undocumented arguments for internal use +gevent.greenlet.Greenlet.link +gevent.greenlet.Greenlet.link_exception +gevent.greenlet.Greenlet.link_value +gevent._threading.Queue.qsize + +# removed deprecated argument +gevent._hub_primitives.wait_readwrite +gevent._hub_primitives.wait_write +gevent.pywsgi.WSGIHandler.__init__ + +# we have punted on socket, the gevent version of these functions sometimes use +# named parameters, while the base implementation only allows positional arguments +# we're fine with holding the geven implemenation to the same restrictions +# additionally there's some functions with additional optional arguments, that +# we are fine with ignoring for now as well +gevent.socket.cancel_wait + +# gevent overwrites with a named parameter for fd, but we're fine with only +# supporting the API of the superclass +gevent.threadpool.ThreadPoolExecutor.submit + +# Error: is not a type/function +# ===================== +# zope.interface related errors, these shouldn't matter +gevent._monitor.implementer +gevent.events.implementer +gevent.events.IEventLoopBlocked +gevent.events.IGeventDidPatchAllEvent +gevent.events.IGeventDidPatchBuiltinModulesEvent +gevent.events.IGeventDidPatchEvent +gevent.events.IGeventDidPatchModuleEvent +gevent.events.IGeventPatchEvent +gevent.events.IGeventWillPatchAllEvent +gevent.events.IGeventWillPatchEvent +gevent.events.IGeventWillPatchModuleEvent +gevent.events.IMemoryUsageThresholdExceeded +gevent.events.IMemoryUsageUnderThreshold +gevent.events.IPeriodicMonitorThread +gevent.events.IPeriodicMonitorThreadStartedEvent + +# Error: failed to import +# ====================== +# internal use module for some complex protocols used across different modules +# so there wasn't really a great place for them +gevent._types + +# The first parameter is technically positional-or-keyword but there's no +# useful way to use it as a keyword argument; we mark it positional-only. +gevent.pool.GroupMappingMixin.imap +gevent.pool.GroupMappingMixin.imap_unordered + +# Importing gevent.monkey.__main__ leads to issues in stubtest, since gevent will +# try to monkeypatch stubtest +gevent.monkey.__main__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_darwin.txt b/stubs/gevent/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..9ef60bc83f94 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,14 @@ +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent.libev.corecext.loop.async + +# Error: is inconsistent +# ====================== +# these are inconsistent due to the ParamSpec hack for positional only callables +gevent.libev.corecext.loop.run_callback +gevent.libev.corecext.loop.run_callback_threadsafe +gevent.libev.watcher.watcher.feed + +# undocumented argument for internal use only +gevent.libev.watcher.watcher.__init__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_linux.txt b/stubs/gevent/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..9ef60bc83f94 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,14 @@ +# Error: is not present in stub +# ============================= +# internal API stuff we dropped because it wasn't necessary +gevent.libev.corecext.loop.async + +# Error: is inconsistent +# ====================== +# these are inconsistent due to the ParamSpec hack for positional only callables +gevent.libev.corecext.loop.run_callback +gevent.libev.corecext.loop.run_callback_threadsafe +gevent.libev.watcher.watcher.feed + +# undocumented argument for internal use only +gevent.libev.watcher.watcher.__init__ diff --git a/stubs/gevent/@tests/stubtest_allowlist_win32.txt b/stubs/gevent/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..f64157a5bae8 --- /dev/null +++ b/stubs/gevent/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,19 @@ +# Error: is not present in stub +# ============================= +# these get exported but don't actually work on win32 so we ignore them +gevent.signal.__all__ +gevent.signal.getsignal +gevent.signal.signal +gevent.signal.set_wakeup_fd + +# the docs say this doesn't work on windows, so it has been removed +gevent._ffi.loop.AbstractLoop.fork + +# for some reason this extension exists even though it is not supported on windows +gevent.libev.corecext.* + +# Error: failed to import +# ============================= +# these won't work until we find out if we can install libev somehow with choco +gevent.libev.corecffi +gevent.libev.watcher diff --git a/stubs/gevent/METADATA.toml b/stubs/gevent/METADATA.toml new file mode 100644 index 000000000000..30de564b477e --- /dev/null +++ b/stubs/gevent/METADATA.toml @@ -0,0 +1,12 @@ +version = "26.7.*" +upstream-repository = "https://github.com/gevent/gevent" +dependencies = ["types-greenlet", "types-psutil>=7.2.0"] + +[tool.stubtest] +# Run stubtest on all platforms, since there is some platform specific stuff +# especially in the stdlib module replacement +ci-platforms = ["linux", "darwin", "win32"] +# for testing the ffi loop implementations on all platforms +stubtest-dependencies = ["cffi", "dnspython"] +apt-dependencies = ["libev4", "libev-dev", "libuv1", "libuv1-dev"] +brew-dependencies = ["libev", "libuv"] diff --git a/stubs/gevent/gevent/__init__.pyi b/stubs/gevent/gevent/__init__.pyi new file mode 100644 index 000000000000..0a7c6aff3799 --- /dev/null +++ b/stubs/gevent/gevent/__init__.pyi @@ -0,0 +1,76 @@ +import sys + +from gevent._config import config as config +from gevent._hub_local import get_hub as get_hub +from gevent._hub_primitives import iwait_on_objects as iwait, wait_on_objects as wait +from gevent.greenlet import Greenlet as Greenlet, joinall as joinall, killall as killall +from gevent.hub import ( + GreenletExit as GreenletExit, + getcurrent as getcurrent, + idle as idle, + kill as kill, + reinit as reinit, + signal as signal_handler, + sleep as sleep, + spawn_raw as spawn_raw, +) +from gevent.timeout import Timeout as Timeout, with_timeout as with_timeout + +if sys.platform != "win32": + from gevent.os import fork + + __all__ = [ + "Greenlet", + "GreenletExit", + "Timeout", + "config", + "fork", + "get_hub", + "getcurrent", + "getswitchinterval", + "idle", + "iwait", + "joinall", + "kill", + "killall", + "reinit", + "setswitchinterval", + "signal_handler", + "sleep", + "spawn", + "spawn_later", + "spawn_raw", + "wait", + "with_timeout", + ] +else: + __all__ = [ + "Greenlet", + "GreenletExit", + "Timeout", + "config", + "get_hub", + "getcurrent", + "getswitchinterval", + "idle", + "iwait", + "joinall", + "kill", + "killall", + "reinit", + "setswitchinterval", + "signal_handler", + "sleep", + "spawn", + "spawn_later", + "spawn_raw", + "wait", + "with_timeout", + ] + +__version__: str + +getswitchinterval = sys.getswitchinterval +setswitchinterval = sys.setswitchinterval +spawn = Greenlet.spawn +spawn_later = Greenlet.spawn_later diff --git a/stubs/gevent/gevent/_abstract_linkable.pyi b/stubs/gevent/gevent/_abstract_linkable.pyi new file mode 100644 index 000000000000..5c312a96c763 --- /dev/null +++ b/stubs/gevent/gevent/_abstract_linkable.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable +from typing_extensions import Self + +from gevent.hub import Hub + +class AbstractLinkable: + __slots__ = ("hub", "_links", "_notifier", "_notify_all", "__weakref__") + @property + def hub(self) -> Hub | None: ... + def __init__(self, hub: Hub | None = None) -> None: ... + def linkcount(self) -> int: ... + def rawlink(self, callback: Callable[[Self], object], /) -> None: ... + def ready(self) -> bool: ... + def unlink(self, callback: Callable[[Self], object], /) -> None: ... + +__all__ = ["AbstractLinkable"] diff --git a/stubs/gevent/gevent/_config.pyi b/stubs/gevent/gevent/_config.pyi new file mode 100644 index 000000000000..7015d9f4252f --- /dev/null +++ b/stubs/gevent/gevent/_config.pyi @@ -0,0 +1,204 @@ +from collections.abc import Callable, Sequence +from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Never + +from gevent._types import _Loop, _Resolver +from gevent.fileobject import _FileObjectType +from gevent.threadpool import ThreadPool + +__all__ = ["config"] + +_T = TypeVar("_T") + +@type_check_only +class _SettingDescriptor(Protocol[_T]): + @overload + def __get__(self, obj: None, owner: type[Config]) -> property: ... + @overload + def __get__(self, obj: Config, owner: type[Config]) -> _T: ... + + def __set__(self, obj: Config, value: str | _T) -> None: ... + +class SettingType(type): + def fmt_desc(cls, desc: str) -> str: ... + +def validate_invalid(value: object) -> Never: ... +def validate_bool(value: str | bool) -> bool: ... +def validate_anything(value: _T) -> _T: ... + +convert_str_value_as_is = validate_anything + +class Setting(Generic[_T], metaclass=SettingType): + order: int # all subclasses have this + name: str + environment_key: str + value: _T + default: _T + document: bool + desc: str + validate: Callable[[Any], _T] + def get(self) -> _T: ... + def set(self, val: str | _T) -> None: ... + +class Config: + settings: dict[str, Setting[Any]] + def __init__(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: object) -> None: ... + def set(self, name: str, value: object) -> None: ... + def __dir__(self) -> list[str]: ... + def print_help(self) -> None: ... + + # we manually add properties for all the settings in this module + # SettingType inserts a property into Config for every subclass of Setting + resolver: _SettingDescriptor[type[_Resolver]] + threadpool: _SettingDescriptor[type[Threadpool]] + threadpool_idle_task_timeout: _SettingDescriptor[float] + loop: _SettingDescriptor[type[_Loop]] + format_context: _SettingDescriptor[Callable[[Any], str]] + libev_backend: _SettingDescriptor[str | None] + fileobject: _SettingDescriptor[_FileObjectType] + disable_watch_children: _SettingDescriptor[bool] + track_greenlet_tree: _SettingDescriptor[bool] + monitor_thread: _SettingDescriptor[bool] + max_blocking_time: _SettingDescriptor[float] + memory_monitor_period: _SettingDescriptor[float] + max_memory_usage: _SettingDescriptor[int | None] + resolver_nameservers: _SettingDescriptor[Sequence[str] | str | None] + resolver_timeout: _SettingDescriptor[float | None] + # these get parsed by gevent.resolver.cares.channel so the Setting does not + # perform any conversion, but we know at least what types can be valid + ares_flags: _SettingDescriptor[str | int | None] + ares_timeout: _SettingDescriptor[str | float | None] + ares_tries: _SettingDescriptor[str | int | None] + ares_ndots: _SettingDescriptor[str | int | None] + ares_udp_port: _SettingDescriptor[str | int | None] + ares_tcp_port: _SettingDescriptor[str | int | None] + ares_servers: _SettingDescriptor[Sequence[str] | str | None] + print_blocking_reports: _SettingDescriptor[bool] + +class ImportableSetting(Generic[_T]): + default: str | Sequence[str] + shortname_map: dict[str, str] + def validate(self, value: str | _T) -> _T: ... + def get_options(self) -> dict[str, _T]: ... + +class BoolSettingMixin: + @staticmethod + def validate(value: str | bool) -> bool: ... + +class IntSettingMixin: + @staticmethod + def validate(value: int) -> int: ... + +class _PositiveValueMixin(Generic[_T]): + @staticmethod + def validate(value: _T) -> _T: ... + +class FloatSettingMixin(_PositiveValueMixin[float]): ... +class ByteCountSettingMixin(_PositiveValueMixin[int]): ... + +class Resolver(ImportableSetting[type[_Resolver]], Setting[type[_Resolver]]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class Threadpool(ImportableSetting[type[ThreadPool]], Setting[type[ThreadPool]]): + desc: str + default: str # type: ignore[assignment] + +class ThreadpoolIdleTaskTimeout(FloatSettingMixin, Setting[float]): + document: bool + desc: str + default: float + +class Loop(ImportableSetting[type[_Loop]], Setting[type[_Loop]]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class FormatContext(ImportableSetting[Callable[[Any], str]], Setting[Callable[[Any], str]]): + default: str # type: ignore[assignment] + +class LibevBackend(Setting[str | None]): + desc: str + default: None + +class FileObject(ImportableSetting[_FileObjectType], Setting[_FileObjectType]): + desc: str + default: list[str] # type: ignore[assignment] + shortname_map: dict[str, str] + +class WatchChildren(BoolSettingMixin, Setting[bool]): + desc: str + default: bool + +class TrackGreenletTree(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MonitorThread(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MaxBlockingTime(FloatSettingMixin, Setting[float]): + default: float + desc: str + +class PrintBlockingReports(BoolSettingMixin, Setting[bool]): + default: bool + desc: str + +class MonitorMemoryPeriod(FloatSettingMixin, Setting[float]): + default: int + desc: str + +class MonitorMemoryMaxUsage(ByteCountSettingMixin, Setting[int | None]): + default: None + desc: str + +class AresSettingMixin: + document: bool + @property + def kwarg_name(self) -> str: ... + validate: Any # we just want this to mixin without errors + +class AresFlags(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresTimeout(AresSettingMixin, Setting[str | float | None]): + document: bool + default: None + desc: str + +class AresTries(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresNdots(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresUDPPort(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresTCPPort(AresSettingMixin, Setting[str | int | None]): + default: None + +class AresServers(AresSettingMixin, Setting[Sequence[str] | str | None]): + document: bool + default: None + desc: str + +class ResolverNameservers(AresSettingMixin, Setting[Sequence[str] | str | None]): + document: bool + default: None + desc: str + @property + def kwarg_name(self) -> str: ... + +class ResolverTimeout(FloatSettingMixin, AresSettingMixin, Setting[float | None]): + document: bool + desc: str + @property + def kwarg_name(self) -> str: ... + +config: Config = ... diff --git a/stubs/gevent/gevent/_ffi/__init__.pyi b/stubs/gevent/gevent/_ffi/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/gevent/gevent/_ffi/loop.pyi b/stubs/gevent/gevent/_ffi/loop.pyi new file mode 100644 index 000000000000..38222a945d36 --- /dev/null +++ b/stubs/gevent/gevent/_ffi/loop.pyi @@ -0,0 +1,87 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable, Sequence +from types import TracebackType +from typing import Protocol, TypeAlias, type_check_only +from typing_extensions import TypeVarTuple, Unpack + +from gevent._types import _AsyncWatcher, _Callback, _ChildWatcher, _IoWatcher, _StatWatcher, _TimerWatcher, _Watcher + +_Ts = TypeVarTuple("_Ts") +_ErrorHandlerFunc: TypeAlias = Callable[ + [object | None, type[BaseException] | None, BaseException | None, TracebackType | None], object +] + +@type_check_only +class _SupportsHandleError(Protocol): + handle_error: _ErrorHandlerFunc + +_ErrorHandler: TypeAlias = _ErrorHandlerFunc | _SupportsHandleError + +def assign_standard_callbacks( + ffi: object, lib: object, callbacks_class: Callable[[object], object], extras: Sequence[tuple[object, object]] = () +) -> object: ... + +class AbstractLoop: + CALLBACK_CHECK_COUNT: int + error_handler: _ErrorHandler | None + starting_timer_may_update_loop_time: bool + # internal API, this __init__ will only be called from subclasses + def __init__( + self, ffi: object, lib: object, watchers: object, flags: int | None = None, default: bool | None = None + ) -> None: ... + def destroy(self) -> bool | None: ... + @property + def ptr(self) -> int: ... + @property + def WatcherType(self) -> type[_Watcher]: ... + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int | None = ...) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + update = update_now # deprecated + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + @property + def activecnt(self) -> int: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> _TimerWatcher: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def idle(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def check(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> _ChildWatcher: ... + def install_sigchld(self) -> None: ... + + def async_(self, ref: bool = True, priority: int | None = None) -> _AsyncWatcher: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> _StatWatcher: ... + def run_callback(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> _Callback: ... + def callback(self, priority: float | None = None) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + +__all__ = ["AbstractLoop", "assign_standard_callbacks"] diff --git a/stubs/gevent/gevent/_ffi/watcher.pyi b/stubs/gevent/gevent/_ffi/watcher.pyi new file mode 100644 index 000000000000..9c5c3b181cf9 --- /dev/null +++ b/stubs/gevent/gevent/_ffi/watcher.pyi @@ -0,0 +1,98 @@ +from _typeshed import FileDescriptor, StrOrBytesPath +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, overload +from typing_extensions import Self, TypeVarTuple, Unpack + +from gevent._types import _Loop, _StatResult + +_Ts = TypeVarTuple("_Ts") + +class AbstractWatcherType(type): + def new_handle(cls, obj: object) -> int: ... + def new(cls, kind: object) -> Any: ... + +class watcher(metaclass=AbstractWatcherType): + loop: _Loop + def __init__(self, _loop: _Loop, ref: bool = True, priority: int | None = None, args: tuple[object, ...] = ()) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + @property + def ref(self) -> bool: ... + callback: Callable[..., Any] + args: tuple[Any, ...] + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def stop(self) -> None: ... + + @property + def priority(self) -> int | None: ... + @priority.setter + def priority(self, value: int | None) -> None: ... + + @property + def active(self) -> bool: ... + @property + def pending(self) -> bool: ... + +class IoMixin: + EVENT_MASK: int + def __init__(self, loop: _Loop, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> None: ... + + @overload + def start(self, callback: Callable[[int, Unpack[_Ts]], Any], *args: Unpack[_Ts], pass_events: Literal[True]) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +class TimerMixin: + def __init__( + self, loop: _Loop, after: float = 0.0, repeat: float = 0.0, ref: bool = True, priority: int | None = None + ) -> None: ... + + @overload + def start(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + + @overload + def again(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def again(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ... + +class SignalMixin: + def __init__(self, loop: _Loop, signalnum: int, ref: bool = True, priority: int | None = None) -> None: ... + +class IdleMixin: ... +class PrepareMixin: ... +class CheckMixin: ... +class ForkMixin: ... + +class AsyncMixin: + def send(self) -> None: ... + def send_ignoring_arg(self, _ignored: object) -> None: ... + @property + def pending(self) -> bool: ... + +class ChildMixin: + def __init__(self, loop: _Loop, pid: int, trace: int = 0, ref: bool = True) -> None: ... + @property + def pid(self) -> int: ... + @property + def rpid(self) -> int | None: ... + @property + def rstatus(self) -> int: ... + +class StatMixin: + def __init__( + self, _loop: _Loop, path: StrOrBytesPath, interval: float = 0.0, ref: bool = True, priority: float | None = None + ) -> None: ... + @property + def path(self) -> StrOrBytesPath: ... + @property + def attr(self) -> _StatResult | None: ... + @property + def prev(self) -> _StatResult | None: ... + @property + def interval(self) -> float: ... + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/_fileobjectcommon.pyi b/stubs/gevent/gevent/_fileobjectcommon.pyi new file mode 100644 index 000000000000..3aba7454d1ca --- /dev/null +++ b/stubs/gevent/gevent/_fileobjectcommon.pyi @@ -0,0 +1,371 @@ +import io +from _typeshed import ( + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ReadableBuffer, +) +from types import TracebackType +from typing import IO, Any, AnyStr, ClassVar, Generic, Literal, TypeVar, overload +from typing_extensions import Self + +from gevent.lock import DummySemaphore, Semaphore +from gevent.threadpool import ThreadPool + +_IOT = TypeVar("_IOT", bound=IO[Any]) + +class cancel_wait_ex(IOError): + def __init__(self) -> None: ... + +class FileObjectClosed(IOError): + def __init__(self) -> None: ... + +class FlushingBufferedWriter(io.BufferedWriter): ... + +class WriteallMixin: + def writeall(self, b: ReadableBuffer, /) -> int: ... + +class FileIO(io.FileIO): + __slots__ = () + +class WriteIsWriteallMixin(WriteallMixin): + def write(self, b: ReadableBuffer, /) -> int: ... + +class WriteallFileIO(WriteIsWriteallMixin, io.FileIO): ... # type: ignore[misc] + +class OpenDescriptor(Generic[_IOT]): + default_buffer_size: ClassVar[int] + fileio_mode: str + mode: str + creating: bool + reading: bool + writing: bool + appending: bool + updating: bool + text: bool + binary: bool + can_write: bool + can_read: bool + native: bool + universal: bool + buffering: int + encoding: str | None + errors: str | None + newline: bool + closefd: bool + atomic_write: bool + # we could add all the necessary overloads here too, but since this is internal API + # I don't think it makes sense to do that + def __init__( + self, + fobj: FileDescriptorOrPath, + mode: str = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + def is_fd(self) -> bool: ... + def opened(self) -> _IOT: ... + def opened_raw(self) -> FileIO: ... + @staticmethod + def is_buffered(stream: object) -> bool: ... + @classmethod + def buffer_size_for_stream(cls, stream: object) -> int: ... + +class FileObjectBase(Generic[_IOT, AnyStr]): + def __init__( + self: FileObjectBase[_IOT, AnyStr], descriptor: OpenDescriptor[_IOT] # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... + io: _IOT + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, /) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> AnyStr: ... + def __bool__(self) -> bool: ... + next = __next__ + +class FileObjectBlock(FileObjectBase[_IOT, AnyStr]): + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectBlock[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectBlock[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectBlock[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectBlock[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectBlock[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectBlock[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + +class FileObjectThread(FileObjectBase[_IOT, AnyStr]): + threadpool: ThreadPool + lock: Semaphore | DummySemaphore + + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectThread[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectThread[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectThread[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + @overload + def __init__( + self: FileObjectThread[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectThread[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectThread[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + *, + lock: bool = True, + threadpool: ThreadPool | None = None, + ) -> None: ... diff --git a/stubs/gevent/gevent/_greenlet_primitives.pyi b/stubs/gevent/gevent/_greenlet_primitives.pyi new file mode 100644 index 000000000000..60356ed148d6 --- /dev/null +++ b/stubs/gevent/gevent/_greenlet_primitives.pyi @@ -0,0 +1,21 @@ +from abc import abstractmethod +from typing import Any +from typing_extensions import Never, disjoint_base + +from gevent._types import _Loop +from greenlet import greenlet + +class TrackedRawGreenlet(greenlet): ... + +@disjoint_base +class SwitchOutGreenletWithLoop(TrackedRawGreenlet): + @property + @abstractmethod + def loop(self) -> _Loop: ... + @loop.setter + def loop(self, value: _Loop) -> None: ... + + def switch(self) -> Any: ... + def switch_out(self) -> Never: ... + +__all__ = ["TrackedRawGreenlet", "SwitchOutGreenletWithLoop"] diff --git a/stubs/gevent/gevent/_hub_local.pyi b/stubs/gevent/gevent/_hub_local.pyi new file mode 100644 index 000000000000..783ef5bc7b0d --- /dev/null +++ b/stubs/gevent/gevent/_hub_local.pyi @@ -0,0 +1,15 @@ +from gevent._types import _Loop +from gevent.hub import Hub as _Hub + +__all__ = ["get_hub", "get_hub_noargs", "get_hub_if_exists"] + +Hub: type[_Hub] | None + +def get_hub_class() -> type[_Hub] | None: ... +def set_default_hub_class(hubtype: type[_Hub]) -> None: ... +def get_hub() -> _Hub: ... +def get_hub_noargs() -> _Hub: ... +def get_hub_if_exists() -> _Hub | None: ... +def set_hub(hub: _Hub) -> None: ... +def get_loop() -> _Loop: ... +def set_loop(loop: _Loop) -> None: ... diff --git a/stubs/gevent/gevent/_hub_primitives.pyi b/stubs/gevent/gevent/_hub_primitives.pyi new file mode 100644 index 000000000000..9771e2adf81d --- /dev/null +++ b/stubs/gevent/gevent/_hub_primitives.pyi @@ -0,0 +1,74 @@ +from _typeshed import FileDescriptor +from collections.abc import Callable, Collection, Iterable +from types import TracebackType +from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack, disjoint_base + +from gevent._greenlet_primitives import SwitchOutGreenletWithLoop +from gevent._types import _Loop, _Watcher +from gevent.hub import Hub +from gevent.socket import socket + +__all__ = ["WaitOperationsGreenlet", "iwait_on_objects", "wait_on_objects", "wait_read", "wait_write", "wait_readwrite"] + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts") +_WaitableT = TypeVar("_WaitableT", bound=_Waitable) + +@type_check_only +class _Waitable(Protocol): + def rawlink(self, callback: Callable[[Any], object], /) -> object: ... + def unlink(self, callback: Callable[[Any], object], /) -> object: ... + +class WaitOperationsGreenlet(SwitchOutGreenletWithLoop): + loop: _Loop + def wait(self, watcher: _Watcher) -> None: ... + def cancel_waits_close_and_then( + self, + watchers: Iterable[_Watcher], + exc_kind: type[BaseException] | BaseException, + then: Callable[[Unpack[_Ts]], object], + *then_args: Unpack[_Ts], + ) -> None: ... + def cancel_wait(self, watcher: _Watcher, error: type[BaseException] | BaseException, close_watcher: bool = False) -> None: ... + +@disjoint_base +class _WaitIterator(Generic[_T]): + def __init__(self, objects: Collection[_T], hub: Hub, timeout: float, count: None | int) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + next = __next__ + +@overload +def iwait_on_objects(objects: None, timeout: float | None = None, count: int | None = None) -> list[bool]: ... +@overload +def iwait_on_objects( + objects: Collection[_WaitableT], timeout: float | None = None, count: int | None = None +) -> _WaitIterator[_WaitableT]: ... + +@overload +def wait_on_objects(objects: None = None, timeout: float | None = None, count: int | None = None) -> bool: ... +@overload +def wait_on_objects( + objects: Collection[_WaitableT], timeout: float | None = None, count: int | None = None +) -> list[_WaitableT]: ... + +def set_default_timeout_error(e: type[BaseException]) -> None: ... +def wait_on_socket(socket: socket, watcher: _Watcher, timeout_exc: type[BaseException] | BaseException | None = None) -> None: ... +def wait_on_watcher( + watcher: _Watcher, + timeout: float | None = None, + timeout_exc: type[BaseException] | BaseException = ..., + hub: Hub | None = None, +) -> None: ... +def wait_read( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... +def wait_write( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... +def wait_readwrite( + fileno: FileDescriptor, timeout: float | None = None, timeout_exc: type[BaseException] | BaseException = ... +) -> None: ... diff --git a/stubs/gevent/gevent/_ident.pyi b/stubs/gevent/gevent/_ident.pyi new file mode 100644 index 000000000000..e59d21de18cf --- /dev/null +++ b/stubs/gevent/gevent/_ident.pyi @@ -0,0 +1,15 @@ +from typing import Any, final +from weakref import ref + +@final +class ValuedWeakRef(ref): + __slots__ = ("value",) + value: Any + +@final +class IdentRegistry: + def __init__(self) -> None: ... + def get_ident(self, obj: object) -> int: ... + def __len__(self) -> int: ... + +__all__ = ["IdentRegistry"] diff --git a/stubs/gevent/gevent/_imap.pyi b/stubs/gevent/gevent/_imap.pyi new file mode 100644 index 000000000000..2a515665cf6b --- /dev/null +++ b/stubs/gevent/gevent/_imap.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable, Iterable +from typing import Any, ParamSpec, TypeVar +from typing_extensions import Self, disjoint_base + +from gevent.greenlet import Greenlet +from gevent.queue import UnboundQueue + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +# this matches builtins.map to some degree, but since it is an non-public API type that just gets +# returned by some public API functions, we don't bother adding a whole bunch of overloads to handle +# the case of 1-n Iterables being passed in and just go for the fully unsafe signature +# we do the crazy overloads instead in the functions that create these objects +@disjoint_base +class IMapUnordered(Greenlet[_P, _T]): + finished: bool + # it may contain an undocumented Failure object + queue: UnboundQueue[_T | object] + def __init__(self, func: Callable[_P, _T], iterable: Iterable[Any], spawn: Callable[_P, Greenlet[_P, _T]]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + +@disjoint_base +class IMap(IMapUnordered[_P, _T]): + index: int + +__all__ = ["IMapUnordered", "IMap"] diff --git a/stubs/gevent/gevent/_monitor.pyi b/stubs/gevent/gevent/_monitor.pyi new file mode 100644 index 000000000000..3647e0f33f0d --- /dev/null +++ b/stubs/gevent/gevent/_monitor.pyi @@ -0,0 +1,51 @@ +from collections.abc import Callable, Sequence +from typing import Any, TypeVar + +from gevent.events import IPeriodicMonitorThread, MemoryUsageThresholdExceeded, MemoryUsageUnderThreshold +from gevent.hub import Hub +from greenlet import greenlet + +__all__ = ["PeriodicMonitoringThread"] + +_T = TypeVar("_T") + +# FIXME: While it would be nice to import Interface from zope.interface here so the +# mypy plugin will work correctly for the people that use it, it causes all +# sorts of issues to reference a module that is not stubbed in typeshed, so +# for now we punt and just define an alias for Interface and implementer we +# can get rid of later +def implementer(interface: Any, /) -> Callable[[_T], _T]: ... + +class MonitorWarning(RuntimeWarning): ... + +class _MonitorEntry: + __slots__ = ("function", "period", "last_run_time") + function: Callable[[Hub], object] + period: float + last_run_time: float + def __init__(self, function: Callable[[Hub], object], period: float) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +@implementer(IPeriodicMonitorThread) +class PeriodicMonitoringThread: + inactive_sleep_time: float + min_sleep_time: float + min_memory_monitor_period: float + should_run: bool + monitor_thread_ident: int + pid: int + def __init__(self, hub: Hub) -> None: ... + @property + def hub(self) -> Hub | None: ... + def monitoring_functions(self) -> list[_MonitorEntry]: ... + def add_monitoring_function(self, function: Callable[[Hub], object], period: float) -> None: ... + def calculate_sleep_time(self) -> float: ... + def kill(self) -> None: ... + def __call__(self) -> None: ... + def monitor_blocking(self, hub: Hub) -> tuple[greenlet, Sequence[str]]: ... + def ignore_current_greenlet_blocking(self) -> None: ... + def monitor_current_greenlet_blocking(self) -> None: ... + def can_monitor_memory_usage(self) -> bool: ... + def install_monitor_memory_usage(self) -> None: ... + def monitor_memory_usage(self, _hub: Hub) -> MemoryUsageThresholdExceeded | MemoryUsageUnderThreshold | None: ... diff --git a/stubs/gevent/gevent/_threading.pyi b/stubs/gevent/gevent/_threading.pyi new file mode 100644 index 000000000000..1c671bdec7f9 --- /dev/null +++ b/stubs/gevent/gevent/_threading.pyi @@ -0,0 +1,22 @@ +from _thread import LockType, allocate_lock as Lock +from typing import Generic, NewType, TypeVar + +__all__ = ["Lock", "Queue", "EmptyTimeout"] + +_T = TypeVar("_T") +_Cookie = NewType("_Cookie", LockType) + +class EmptyTimeout(Exception): ... + +class Queue(Generic[_T]): + __slots__ = ("_queue", "_mutex", "_not_empty", "unfinished_tasks") + unfinished_tasks: int + def __init__(self) -> None: ... + def task_done(self) -> None: ... + def qsize(self) -> int: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def put(self, item: _T) -> None: ... + def get(self, cookie: _Cookie, timeout: int = -1) -> _T: ... + def allocate_cookie(self) -> _Cookie: ... + def kill(self) -> None: ... diff --git a/stubs/gevent/gevent/_types.pyi b/stubs/gevent/gevent/_types.pyi new file mode 100644 index 000000000000..a5718fb32d7e --- /dev/null +++ b/stubs/gevent/gevent/_types.pyi @@ -0,0 +1,160 @@ +import sys +from _typeshed import FileDescriptor, StrOrBytesPath +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVarTuple, Unpack + +_Ts = TypeVarTuple("_Ts") + +# gevent uses zope.interface interanlly which does not work well with type checkers +# partially due to the odd call signatures without self and partially due to them +# behaving essentially like a Protocol, so a mypy plugin is necessary to type check +# them correctly, and then you still have to give up on some valuable features due +# to the missing self/cls argument. +# To ensure maximum compatibility with other type checkers and so we don't depend +# on mypy-zope we define an equivalent Protocol for each interface, which we will +# use on arguments in place of the interface +# it also looks like ILoop is possibly too strict, since there are additional +# properties and methods that are available on all event loops, so these have +# been added as well, instead of completely mirroring the internal interface + +@type_check_only +class _Loop(Protocol): # noqa: Y046 + @property + def approx_timer_resolution(self) -> float: ... + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + @property + def activecnt(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int | None = ...) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + def destroy(self) -> None: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> _TimerWatcher: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def idle(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def check(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> _Watcher: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> _ChildWatcher: ... + def install_sigchld(self) -> None: ... + + def async_(self, ref: bool = True, priority: int | None = None) -> _AsyncWatcher: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = ...) -> _StatWatcher: ... + def run_callback(self, func: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + +@type_check_only +class _Watcher(Protocol): + # while IWatcher allows for kwargs the actual implementation does not... + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + def stop(self) -> None: ... + def close(self) -> None: ... + +# this matches Intersection[_Watcher, TimerMixin] +@type_check_only +class _TimerWatcher(_Watcher, Protocol): + # this has one specific allowed keyword argument, if it is given we don't try to check + # the passed in arguments, but if it isn't passed in, then we do. + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + + @overload + def again(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts], update: bool) -> None: ... + @overload + def again(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +# this matches Intersection[_Watcher, IoMixin] +@type_check_only +class _IoWatcher(_Watcher, Protocol): + EVENT_MASK: int + + # pass_events means the first argument of the callback needs to be an integer, but we can't + # type check the other passed in args in this case + @overload + def start(self, callback: Callable[[int, Unpack[_Ts]], Any], *args: Unpack[_Ts], pass_events: Literal[True]) -> None: ... + @overload + def start(self, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ... + +# this matches Intersection[_Watcher, ChildMixin] +@type_check_only +class _ChildWatcher(_Watcher, Protocol): + @property + def pid(self) -> int: ... + @property + def rpid(self) -> int | None: ... + @property + def rstatus(self) -> int: ... + +# this matches Intersection[_Watcher, AsyncMixin] +@type_check_only +class _AsyncWatcher(_Watcher, Protocol): + def send(self) -> None: ... + def send_ignoring_arg(self, ignored: object, /) -> None: ... + @property + def pending(self) -> bool: ... + +# all implementations return something of this shape +@type_check_only +class _StatResult(Protocol): + @property + def st_nlink(self) -> int: ... + +# this matches Intersection[_Watcher, StatMixin] +@type_check_only +class _StatWatcher(_Watcher, Protocol): + @property + def path(self) -> StrOrBytesPath: ... + @property + def attr(self) -> _StatResult | None: ... + @property + def prev(self) -> _StatResult | None: ... + @property + def interval(self) -> float: ... + +@type_check_only +class _Callback(Protocol): + pending: bool + def stop(self) -> None: ... + def close(self) -> None: ... + +_FullSockAddr: TypeAlias = tuple[str, int, int, int] # host, port, flowinfo, scopeid +_SockAddr: TypeAlias = _FullSockAddr | tuple[str, int] +_AddrinfoResult: TypeAlias = list[tuple[int, int, int, str, _SockAddr]] # family, type, protocol, cname, sockaddr +_NameinfoResult: TypeAlias = tuple[str, str] + +@type_check_only +class _Resolver(Protocol): # noqa: Y046 + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... diff --git a/stubs/gevent/gevent/_util.pyi b/stubs/gevent/gevent/_util.pyi new file mode 100644 index 000000000000..d0f6df62d749 --- /dev/null +++ b/stubs/gevent/gevent/_util.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Iterable, MutableMapping, Sequence +from types import ModuleType +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +_T = TypeVar("_T") + +WRAPPER_ASSIGNMENTS: tuple[str, ...] +WRAPPER_UPDATES: tuple[str, ...] + +def update_wrapper( + wrapper: _T, + wrapped: object, + assigned: Sequence[str] = ("__module__", "__name__", "__qualname__", "__doc__", "__annotations__"), + updated: Sequence[str] = ("__dict__",), +) -> _T: ... +def copy_globals( + source: ModuleType, + globs: MutableMapping[str, Any], + only_names: Iterable[str] | None = None, + ignore_missing_names: bool = False, + names_to_ignore: Sequence[str] = (), + dunder_names_to_keep: Sequence[str] = ("__implements__", "__all__", "__imports__"), + cleanup_globs: bool = True, +) -> list[str]: ... +def import_c_accel(globs: MutableMapping[str, Any], cname: str) -> None: ... + +class Lazy(Generic[_T]): + data: _T + def __init__(self, func: Callable[[Any], _T]) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +class readproperty(Generic[_T]): + func: Callable[[Any], _T] + def __init__( + self: readproperty[_T], func: Callable[[Any], _T] # pyright: ignore[reportInvalidTypeVarUse] #11780 + ) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +class LazyOnClass(Generic[_T]): + @classmethod + def lazy(cls, cls_dict: MutableMapping[str, Any], func: Callable[[Any], _T]) -> None: ... + name: str + func: Callable[[Any], _T] + def __init__(self, func: Callable[[Any], _T], name: str | None = None) -> None: ... + + @overload + def __get__(self, inst: None, class_: type[object]) -> Self: ... + @overload + def __get__(self, inst: object, class_: type[object]) -> _T: ... + +def gmctime() -> str: ... +def prereleaser_middle(data: MutableMapping[str, Any]) -> None: ... +def postreleaser_before(data: MutableMapping[str, Any]) -> None: ... diff --git a/stubs/gevent/gevent/_waiter.pyi b/stubs/gevent/gevent/_waiter.pyi new file mode 100644 index 000000000000..bd1125d84f1e --- /dev/null +++ b/stubs/gevent/gevent/_waiter.pyi @@ -0,0 +1,48 @@ +from types import TracebackType +from typing import Generic, TypeAlias, TypeVar, final, overload + +from gevent.event import _ValueSource +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t + +__all__ = ["Waiter"] + +_T = TypeVar("_T") +# this is annoying, it's due to them using *throw args, rather than just storing them in standardized form +_ThrowArgs: TypeAlias = ( + tuple[()] + | tuple[BaseException] + | tuple[BaseException, None] + | tuple[BaseException, None, TracebackType | None] + | tuple[type[BaseException]] + | tuple[type[BaseException], BaseException | object] + | tuple[type[BaseException], BaseException | object, TracebackType | None] +) + +class Waiter(Generic[_T]): + __slots__ = ["hub", "greenlet", "value", "_exception"] + @property + def hub(self) -> Hub: ... # readonly in Cython + @property + def greenlet(self) -> greenlet_t | None: ... # readonly in Cython + @property + def value(self) -> _T | None: ... # readonly in Cython + def __init__(self, hub: Hub | None = None) -> None: ... + def clear(self) -> None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + @property + def exc_info(self) -> _ThrowArgs | None: ... + def switch(self, value: _T) -> None: ... + + @overload + def throw(self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /) -> None: ... + @overload + def throw(self, typ: BaseException = ..., val: None = None, tb: TracebackType | None = None, /) -> None: ... + + def get(self) -> _T: ... + def __call__(self, source: _ValueSource[_T]) -> None: ... + +@final +class MultipleWaiter(Waiter[_T]): + __slots__ = ["_values"] diff --git a/stubs/gevent/gevent/ares.pyi b/stubs/gevent/gevent/ares.pyi new file mode 100644 index 000000000000..6104efb65acc --- /dev/null +++ b/stubs/gevent/gevent/ares.pyi @@ -0,0 +1,3 @@ +from gevent.resolver.cares import * + +__all__ = ["channel"] diff --git a/stubs/gevent/gevent/backdoor.pyi b/stubs/gevent/gevent/backdoor.pyi new file mode 100644 index 000000000000..d88cd66710f9 --- /dev/null +++ b/stubs/gevent/gevent/backdoor.pyi @@ -0,0 +1,49 @@ +from _typeshed import StrOrBytesPath +from typing import Any, overload + +from gevent.baseserver import _Spawner +from gevent.server import StreamServer, _Address +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext + +class BackdoorServer(StreamServer): + locals: dict[str, Any] + banner: str | None + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + locals: dict[str, Any] | None = None, + banner: str | None = None, + *, + backlog: int | None = None, + spawn: _Spawner = "default", + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + locals: dict[str, Any] | None = None, + banner: str | None = None, + *, + backlog: int | None = None, + spawn: _Spawner = "default", + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + def handle(self, conn: _GeventSocket, _address: _Address) -> None: ... + +__all__ = ["BackdoorServer"] diff --git a/stubs/gevent/gevent/baseserver.pyi b/stubs/gevent/gevent/baseserver.pyi new file mode 100644 index 000000000000..453f974eefec --- /dev/null +++ b/stubs/gevent/gevent/baseserver.pyi @@ -0,0 +1,65 @@ +from collections.abc import Callable, Container +from types import TracebackType +from typing import Generic, Literal, ParamSpec, Protocol, TypeAlias, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack + +from gevent._types import _Loop +from gevent.pool import Pool +from gevent.socket import socket as _GeventSocket +from greenlet import greenlet + +_Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") + +@type_check_only +class _SpawnFunc(Protocol): + def __call__(self, func: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> greenlet: ... + +_Spawner: TypeAlias = Pool | _SpawnFunc | int | Literal["default"] | None + +class BaseServer(Generic[Unpack[_Ts]]): + min_delay: float + max_delay: float + max_accept: int + stop_timeout: float + fatal_errors: Container[int] + pool: Pool | None + delay: float + loop: _Loop + family: int + address: str | tuple[str, int] + socket: _GeventSocket + handle: Callable[[Unpack[_Ts]], object] + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[Unpack[_Ts]], object] | None = None, + spawn: _Spawner = "default", + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, /) -> None: ... + def set_listener(self, listener: _GeventSocket | tuple[str, int] | str) -> None: ... + def set_spawn(self, spawn: _Spawner) -> None: ... + def set_handle(self, handle: Callable[[Unpack[_Ts]], object]) -> None: ... + def start_accepting(self) -> None: ... + def stop_accepting(self) -> None: ... + def do_handle(self, *args: Unpack[_Ts]) -> None: ... + def do_close(self, *args: Unpack[_Ts]) -> None: ... + def do_read(self) -> tuple[Unpack[_Ts]] | None: ... + def full(self) -> bool: ... + @property + def server_host(self) -> str | None: ... + @property + def server_port(self) -> int | None: ... + def init_socket(self) -> None: ... + @property + def started(self) -> bool: ... + def start(self) -> None: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def stop(self, timeout: float | None = None) -> None: ... + def serve_forever(self, stop_timeout: float | None = None) -> None: ... + def is_fatal_error(self, ex: BaseException) -> bool: ... + +__all__ = ["BaseServer"] diff --git a/stubs/gevent/gevent/event.pyi b/stubs/gevent/gevent/event.pyi new file mode 100644 index 000000000000..4652810532d2 --- /dev/null +++ b/stubs/gevent/gevent/event.pyi @@ -0,0 +1,70 @@ +from types import TracebackType +from typing import Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from gevent._abstract_linkable import AbstractLinkable + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +# gevent generally allows the tracebock to be omitted, it can also fail to serialize +# in which case it will be None as well. +_ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] +_OptExcInfo: TypeAlias = _ExcInfo | tuple[None, None, None] + +@type_check_only +class _ValueSource(Protocol[_T_co]): + def successful(self) -> bool: ... + @property + def value(self) -> _T_co | None: ... + @property + def exception(self) -> BaseException | None: ... + +class Event(AbstractLinkable): + __slots__ = ("_flag",) + def __init__(self) -> None: ... + def is_set(self) -> bool: ... + def isSet(self) -> bool: ... + def ready(self) -> bool: ... + def set(self) -> None: ... + def clear(self) -> None: ... + + @overload + def wait(self, timeout: None = None) -> Literal[True]: ... + @overload + def wait(self, timeout: float) -> bool: ... + +class AsyncResult(AbstractLinkable, Generic[_T]): + __slots__ = ("_value", "_exc_info", "_imap_task_index") + def __init__(self) -> None: ... + @property + def value(self) -> _T | None: ... + @property + def exc_info(self) -> _OptExcInfo | tuple[None, None, None] | tuple[()]: ... + @property + def exception(self) -> BaseException | None: ... + def ready(self) -> bool: ... + def successful(self) -> bool: ... + def set(self, value: _T | None = None) -> None: ... + + @overload + def set_exception(self, exception: BaseException, exc_info: None = None) -> None: ... + @overload + def set_exception(self, exception: BaseException | None, exc_info: _OptExcInfo) -> None: ... + + # technically get/get_nowait/result should just return _T, but the API is designed in + # such a way that it is perfectly legal for a ValueSource to have neither its value nor + # its exception set, while still being marked successful, at which point None would be + # stored into value, it's also legal to call set without arguments, which has the same + # effect, this is a little annoying, since it will introduce some additional None checks + # that may not be necessary, but it's impossible to annotate this situation, so for now + # we just deal with the possibly redundant None checks... + def get(self, block: bool = True, timeout: float | None = None) -> _T | None: ... + def get_nowait(self) -> _T | None: ... + def wait(self, timeout: float | None = None) -> _T | None: ... + def __call__(self, source: _ValueSource[_T]) -> None: ... + def result(self, timeout: float | None = None) -> _T | None: ... + set_result = set + def done(self) -> bool: ... + def cancel(self) -> Literal[False]: ... + def cancelled(self) -> Literal[False]: ... + +__all__ = ["Event", "AsyncResult"] diff --git a/stubs/gevent/gevent/events.pyi b/stubs/gevent/gevent/events.pyi new file mode 100644 index 000000000000..ff6fc39f082a --- /dev/null +++ b/stubs/gevent/gevent/events.pyi @@ -0,0 +1,186 @@ +from collections.abc import Callable, Mapping, Sequence +from types import ModuleType +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only + +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t +from psutil._ntuples import pmem + +_T = TypeVar("_T") +# FIXME: While it would be nice to import Interface from zope.interface here so the +# mypy plugin will work correctly for the people that use it, it causes all +# sorts of issues to reference a module that is not stubbed in typeshed, so +# for now we punt and just define an alias for Interface and implementer we +# can get rid of later +Interface: TypeAlias = Any + +def implementer(interface: Interface, /) -> Callable[[_T], _T]: ... + +subscribers: list[Callable[[Any], object]] + +@type_check_only +class _PeriodicMonitorThread(Protocol): + def add_monitoring_function(self, function: Callable[[Hub], object], period: float | None) -> object: ... + +class IPeriodicMonitorThread(Interface): + def add_monitoring_function(function: Callable[[Hub], object], period: float | None) -> object: ... + +class IPeriodicMonitorThreadStartedEvent(Interface): + monitor: IPeriodicMonitorThread + +@implementer(IPeriodicMonitorThread) +class PeriodicMonitorThreadStartedEvent: + ENTRY_POINT_NAME: str + monitor: _PeriodicMonitorThread + def __init__(self, monitor: _PeriodicMonitorThread) -> None: ... + +class IEventLoopBlocked(Interface): + greenlet: greenlet_t + blocking_time: float + info: Sequence[str] + hub: Hub | None + +@implementer(IEventLoopBlocked) +class EventLoopBlocked: + greenlet: greenlet_t + blocking_time: float + info: Sequence[str] + hub: Hub | None + def __init__(self, greenlet: greenlet_t, blocking_time: float, info: Sequence[str], *, hub: Hub | None = None) -> None: ... + +class IMemoryUsageThresholdExceeded(Interface): + mem_usage: int + max_allowed: int + memory_info: pmem + +class _AbstractMemoryEvent: + mem_usage: int + max_allowed: int + memory_info: pmem + def __init__(self, mem_usage: int, max_allowed: int, memory_info: pmem) -> None: ... + +@implementer(IMemoryUsageThresholdExceeded) +class MemoryUsageThresholdExceeded(_AbstractMemoryEvent): ... + +class IMemoryUsageUnderThreshold(Interface): + mem_usage: int + max_allowed: int + max_memory_usage: int + memory_info: pmem + +@implementer(IMemoryUsageUnderThreshold) +class MemoryUsageUnderThreshold(_AbstractMemoryEvent): + max_memory_usage: int + def __init__(self, mem_usage: int, max_allowed: int, memory_info: pmem, max_usage: int) -> None: ... + +class IGeventPatchEvent(Interface): + source: object + target: object + +@implementer(IGeventPatchEvent) +class GeventPatchEvent: + source: object + target: object + def __init__(self, source: object, target: object) -> None: ... + +class IGeventWillPatchEvent(IGeventPatchEvent): ... +class DoNotPatch(BaseException): ... + +@implementer(IGeventWillPatchEvent) +class GeventWillPatchEvent(GeventPatchEvent): ... + +class IGeventDidPatchEvent(IGeventPatchEvent): ... + +@implementer(IGeventWillPatchEvent) +class GeventDidPatchEvent(GeventPatchEvent): ... + +class IGeventWillPatchModuleEvent(IGeventWillPatchEvent): + source: ModuleType + target: ModuleType + module_name: str + target_item_names: list[str] + +@implementer(IGeventWillPatchModuleEvent) +class GeventWillPatchModuleEvent(GeventWillPatchEvent): + ENTRY_POINT_NAME: str + source: ModuleType + target: ModuleType + module_name: str + target_item_names: list[str] + def __init__(self, module_name: str, source: ModuleType, target: ModuleType, items: list[str]) -> None: ... + +class IGeventDidPatchModuleEvent(IGeventDidPatchEvent): + source: ModuleType + target: ModuleType + module_name: str + +@implementer(IGeventDidPatchModuleEvent) +class GeventDidPatchModuleEvent(GeventDidPatchEvent): + ENTRY_POINT_NAME: str + source: ModuleType + target: ModuleType + module_name: str + def __init__(self, module_name: str, source: ModuleType, target: ModuleType) -> None: ... + +class IGeventWillPatchAllEvent(IGeventWillPatchEvent): + patch_all_arguments: Mapping[str, Any] + patch_all_kwargs: Mapping[str, Any] + def will_patch_module(module_name: str) -> bool: ... # pyrefly: ignore [invalid-annotation] + +class _PatchAllMixin: + def __init__(self, patch_all_arguments: Mapping[str, Any], patch_all_kwargs: Mapping[str, Any]) -> None: ... + @property + def patch_all_arguments(self) -> dict[str, Any]: ... # safe to mutate, it's a copy + @property + def patch_all_kwargs(self) -> dict[str, Any]: ... # safe to mutate, it's a copy + +@implementer(IGeventWillPatchAllEvent) +class GeventWillPatchAllEvent(_PatchAllMixin, GeventWillPatchEvent): + ENTRY_POINT_NAME: str + def will_patch_module(self, module_name: str) -> bool: ... + +class IGeventDidPatchBuiltinModulesEvent(IGeventDidPatchEvent): + patch_all_arguments: Mapping[str, Any] + patch_all_kwargs: Mapping[str, Any] + +@implementer(IGeventDidPatchBuiltinModulesEvent) +class GeventDidPatchBuiltinModulesEvent(_PatchAllMixin, GeventDidPatchEvent): + ENTRY_POINT_NAME: str + +class IGeventDidPatchAllEvent(IGeventDidPatchEvent): ... + +@implementer(IGeventDidPatchAllEvent) +class GeventDidPatchAllEvent(_PatchAllMixin, GeventDidPatchEvent): + ENTRY_POINT_NAME: str + +__all__ = [ + "subscribers", + # monitor thread + "IEventLoopBlocked", + "EventLoopBlocked", + "IMemoryUsageThresholdExceeded", + "MemoryUsageThresholdExceeded", + "IMemoryUsageUnderThreshold", + "MemoryUsageUnderThreshold", + # Hub + "IPeriodicMonitorThread", + "IPeriodicMonitorThreadStartedEvent", + "PeriodicMonitorThreadStartedEvent", + # monkey + "IGeventPatchEvent", + "GeventPatchEvent", + "IGeventWillPatchEvent", + "DoNotPatch", + "GeventWillPatchEvent", + "IGeventDidPatchEvent", + "IGeventWillPatchModuleEvent", + "GeventWillPatchModuleEvent", + "IGeventDidPatchModuleEvent", + "GeventDidPatchModuleEvent", + "IGeventWillPatchAllEvent", + "GeventWillPatchAllEvent", + "IGeventDidPatchBuiltinModulesEvent", + "GeventDidPatchBuiltinModulesEvent", + "IGeventDidPatchAllEvent", + "GeventDidPatchAllEvent", +] diff --git a/stubs/gevent/gevent/exceptions.pyi b/stubs/gevent/gevent/exceptions.pyi new file mode 100644 index 000000000000..26cacfa4fc7d --- /dev/null +++ b/stubs/gevent/gevent/exceptions.pyi @@ -0,0 +1,17 @@ +from gevent.hub import Hub +from greenlet import GreenletExit + +class LoopExit(Exception): + @property + def hub(self) -> Hub | None: ... + +class BlockingSwitchOutError(AssertionError): ... +class InvalidSwitchError(AssertionError): ... +class ConcurrentObjectUseError(AssertionError): ... +class InvalidThreadUseError(RuntimeError): ... + +class HubDestroyed(GreenletExit): + destroy_loop: bool + def __init__(self, destroy_loop: bool) -> None: ... + +__all__ = ["LoopExit"] diff --git a/stubs/gevent/gevent/fileobject.pyi b/stubs/gevent/gevent/fileobject.pyi new file mode 100644 index 000000000000..d832e066b7ef --- /dev/null +++ b/stubs/gevent/gevent/fileobject.pyi @@ -0,0 +1,157 @@ +import sys +from typing import Any, TypeAlias + +from gevent._fileobjectcommon import FileObjectBlock as FileObjectBlock, FileObjectThread as FileObjectThread + +if sys.platform != "win32": + import io + from _typeshed import ( + FileDescriptorOrPath, + OpenBinaryMode, + OpenBinaryModeReading, + OpenBinaryModeUpdating, + OpenBinaryModeWriting, + OpenTextMode, + ) + from typing import IO, AnyStr, Literal, overload + + from gevent._fileobjectcommon import _IOT, FileObjectBase + + # this is implemented in _fileobjectposix and technically uses an undocumented subclass + # of RawIOBase, but the interface is the same, so it doesn't seem worth it to add + # annotations for it. _fileobjectcommon was barely worth it due to the common base class + # of all three FileObject types + class FileObjectPosix(FileObjectBase[_IOT, AnyStr]): + default_bufsize = io.DEFAULT_BUFFER_SIZE + fileio: io.RawIOBase + + # Text mode: always binds a TextIOWrapper + @overload + def __init__( + self: FileObjectPosix[io.TextIOWrapper, str], + fobj: FileDescriptorOrPath, + mode: OpenTextMode = "r", + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Unbuffered binary mode: binds a FileIO + @overload + def __init__( + self: FileObjectPosix[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0], + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[0] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.FileIO, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: Literal[0] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + *, + buffering: Literal[0], + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter + @overload + def __init__( + self: FileObjectPosix[io.BufferedRandom, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeUpdating, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.BufferedWriter, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeWriting, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + @overload + def __init__( + self: FileObjectPosix[io.BufferedReader, bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryModeReading, + bufsize: Literal[-1, 1] | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: Literal[-1, 1] | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Buffering cannot be determined: fall back to BinaryIO + @overload + def __init__( + self: FileObjectPosix[IO[bytes], bytes], + fobj: FileDescriptorOrPath, + mode: OpenBinaryMode, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + # Fallback if mode is not specified + @overload + def __init__( + self: FileObjectPosix[IO[Any], Any], + fobj: FileDescriptorOrPath, + mode: str, + bufsize: int | None = None, + close: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + buffering: int | None = None, + closefd: bool | None = None, + atomic_write: bool = False, + ) -> None: ... + + _FileObjectType: TypeAlias = type[FileObjectPosix[Any, Any] | FileObjectBlock[Any, Any] | FileObjectThread[Any, Any]] + __all__ = ["FileObjectPosix", "FileObjectThread", "FileObjectBlock", "FileObject"] +else: + _FileObjectType: TypeAlias = type[FileObjectBlock[Any, Any] | FileObjectThread[Any, Any]] + __all__ = ["FileObjectThread", "FileObjectBlock", "FileObject"] + +FileObject: _FileObjectType diff --git a/stubs/gevent/gevent/greenlet.pyi b/stubs/gevent/gevent/greenlet.pyi new file mode 100644 index 000000000000..e6551f06f9de --- /dev/null +++ b/stubs/gevent/gevent/greenlet.pyi @@ -0,0 +1,106 @@ +import weakref +from collections.abc import Callable, Iterable, Sequence +from types import FrameType, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, overload +from typing_extensions import Self, disjoint_base + +import greenlet +from gevent._types import _Loop +from gevent._util import readproperty + +_T = TypeVar("_T") +_G = TypeVar("_G", bound=greenlet.greenlet) +_P = ParamSpec("_P") + +@disjoint_base +class Greenlet(greenlet.greenlet, Generic[_P, _T]): + # we can't use _P.args/_P.kwargs here because pyright will complain + # mypy doesn't seem to mind though + args: tuple[Any, ...] + kwargs: dict[str, Any] + value: _T | None + + @overload + def __init__( + self: Greenlet[_P, _T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + run: Callable[_P, _T], + *args: _P.args, + **kwargs: _P.kwargs, + ) -> None: ... + @overload + def __init__(self: Greenlet[[], None]) -> None: ... + + @readproperty + def name(self) -> str: ... + @property + def minimal_ident(self) -> int: ... + @property + def loop(self) -> _Loop: ... + @property + def dead(self) -> bool: ... + @property + def started(self) -> bool: ... + @property + def exception(self) -> BaseException | None: ... + @property + def exc_info(self) -> tuple[type[BaseException], BaseException, TracebackType | None] | None: ... + @staticmethod + def add_spawn_callback(callback: Callable[[Greenlet[..., Any]], object]) -> None: ... + @staticmethod + def remove_spawn_callback(callback: Callable[[Greenlet[..., Any]], object]) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def has_links(self) -> bool: ... + def join(self, timeout: float | None = None) -> None: ... + def kill( + self, exception: type[BaseException] | BaseException = ..., block: bool = True, timeout: float | None = None + ) -> None: ... + def link(self, callback: Callable[[Self], object]) -> None: ... + def link_exception(self, callback: Callable[[Self], object]) -> None: ... + def link_value(self, callback: Callable[[Self], object]) -> None: ... + def rawlink(self, callback: Callable[[Self], object]) -> None: ... + def unlink(self, callback: Callable[[Self], Any]) -> None: ... + def unlink_all(self) -> None: ... + def ready(self) -> bool: ... + def run(self) -> Any: ... + + @overload + @classmethod + def spawn(cls, run: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + @overload + @classmethod + def spawn(cls) -> Greenlet[[], None]: ... + + @overload + @classmethod + def spawn_later(cls, seconds: float, run: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + @overload + @classmethod + def spawn_later(cls, seconds: float) -> Greenlet[[], None]: ... + + def start(self) -> None: ... + def start_later(self, seconds: float) -> None: ... + def successful(self) -> bool: ... + def __bool__(self) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + + # since these are for instrumentation which is disabled by default, we could + # consider just not annotating them... + spawning_stack_limit: ClassVar[int] + spawn_tree_locals: dict[str, Any] | None + spawning_greenlet: weakref.ref[greenlet.greenlet] | None + # not quite accurate, since it may be an internal dummy type instead + # but since it has all the same fields as FrameType we shouldn't care + spawning_stack: FrameType | None + +def joinall( + greenlets: Sequence[_G], timeout: float | None = None, raise_error: bool = False, count: int | None = None +) -> list[_G]: ... +def killall( + greenlets: Iterable[greenlet.greenlet], + exception: type[BaseException] | BaseException = ..., + block: bool = True, + timeout: float | None = None, +) -> None: ... + +__all__ = ["Greenlet", "joinall", "killall"] diff --git a/stubs/gevent/gevent/hub.pyi b/stubs/gevent/gevent/hub.pyi new file mode 100644 index 000000000000..0daf83413755 --- /dev/null +++ b/stubs/gevent/gevent/hub.pyi @@ -0,0 +1,118 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Generic, ParamSpec, Protocol, TextIO, TypeVar, overload, type_check_only + +import gevent._hub_local +import gevent._waiter +import greenlet +from gevent._hub_primitives import WaitOperationsGreenlet +from gevent._ident import IdentRegistry +from gevent._monitor import PeriodicMonitoringThread +from gevent._types import _Loop, _Watcher +from gevent._util import Lazy, readproperty +from gevent.greenlet import Greenlet +from gevent.resolver import AbstractResolver +from gevent.threadpool import ThreadPool + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +GreenletExit = greenlet.GreenletExit +getcurrent = greenlet.getcurrent +get_hub = gevent._hub_local.get_hub +Waiter = gevent._waiter.Waiter + +@type_check_only +class _DefaultReturnProperty(Protocol[_T]): + @overload + def __get__(self, obj: None, owner: type[object] | None = None) -> property: ... + @overload + def __get__(self, obj: object, owner: type[object] | None = None) -> _T: ... + + def __set__(self, obj: object, value: _T | None) -> None: ... + def __del__(self) -> None: ... + +def spawn_raw(function: Callable[..., object], *args: object, **kwargs: object) -> greenlet.greenlet: ... +def sleep(seconds: float = 0, ref: bool = True) -> None: ... +def idle(priority: int = 0) -> None: ... +def kill(greenlet: greenlet.greenlet, exception: type[BaseException] | BaseException = ...) -> None: ... + +class signal(Generic[_P]): + greenlet_class: type[Greenlet[..., Any]] | None + hub: Hub + watcher: _Watcher + handler: Callable[_P, object] + # we can't use _P.args/_P.kwargs here because pyright will complain + # mypy doesn't seem to mind though + args: tuple[Any, ...] + kwargs: dict[str, Any] + def __init__(self, signalnum: int, handler: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + + def cancel(self) -> None: ... + def handle(self) -> None: ... + +def reinit(hub: Hub | None = None) -> None: ... + +class Hub(WaitOperationsGreenlet): + SYSTEM_ERROR: tuple[type[BaseException], ...] + NOT_ERROR: tuple[type[BaseException], ...] + threadpool_size: int + periodic_monitoring_thread: PeriodicMonitoringThread | None + thread_ident: int + name: str + loop: _Loop + format_context: Callable[[object], str] + minimal_ident: int + + @overload + def __init__(self, loop: _Loop, default: None = None) -> None: ... + @overload + def __init__(self, loop: None = None, default: bool | None = None) -> None: ... + + @Lazy + def ident_registry(self) -> IdentRegistry: ... + @property + def loop_class(self) -> type[_Loop]: ... + @property + def backend(self) -> int | str: ... + @property + def main_hub(self) -> bool: ... + def handle_error( + self, + context: object | None, + type: type[BaseException] | None, + value: BaseException | str | None, + tb: TracebackType | None, + ) -> None: ... + def handle_system_error( + self, type: type[BaseException], value: BaseException | None, tb: TracebackType | None = None + ) -> None: ... + @readproperty + def exception_stream(self) -> TextIO | None: ... + def print_exception( + self, context: object | None, t: type[BaseException] | None, v: BaseException | str | None, tb: TracebackType | None + ) -> None: ... + def run(self) -> None: ... + def start_periodic_monitoring_thread(self) -> PeriodicMonitoringThread: ... + def join(self, timeout: float | None = None) -> bool: ... + def destroy(self, destroy_loop: bool | None = None) -> None: ... + @property + def resolver_class(self) -> type[AbstractResolver]: ... + resolver: _DefaultReturnProperty[AbstractResolver] + @property + def threadpool_class(self) -> type[ThreadPool]: ... + threadpool: _DefaultReturnProperty[ThreadPool] + +class linkproxy: + __slots__ = ["callback", "obj"] + callback: Callable[[object], object] + obj: object + def __init__(self, callback: Callable[[_T], object], obj: _T) -> None: ... + def __call__(self, *args: object) -> None: ... + +__all__ = ["getcurrent", "GreenletExit", "spawn_raw", "sleep", "kill", "signal", "reinit", "get_hub", "Hub", "Waiter"] diff --git a/stubs/gevent/gevent/libev/__init__.pyi b/stubs/gevent/gevent/libev/__init__.pyi new file mode 100644 index 000000000000..c9c2ef67bd9d --- /dev/null +++ b/stubs/gevent/gevent/libev/__init__.pyi @@ -0,0 +1 @@ +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libev/corecext.pyi b/stubs/gevent/gevent/libev/corecext.pyi new file mode 100644 index 000000000000..fd2f8d80f4dd --- /dev/null +++ b/stubs/gevent/gevent/libev/corecext.pyi @@ -0,0 +1,103 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable, Sequence +from types import TracebackType +from typing import Any, ParamSpec +from typing_extensions import disjoint_base + +from gevent._ffi.loop import _ErrorHandler +from gevent._types import _Callback +from gevent.libev import watcher + +# this c extension is only available on posix +if sys.platform != "win32": + _P = ParamSpec("_P") + + def get_version() -> str: ... + def get_header_version() -> str: ... + # the final item in the list could be an integer if one of the backends did not have a string mapping + def embeddable_backends() -> list[str | int]: ... + def recommended_backends() -> list[str | int]: ... + def supported_backends() -> list[str | int]: ... + def time() -> float: ... + + @disjoint_base + class loop: + starting_timer_may_update_loop_time: bool + error_handler: _ErrorHandler + @property + def approx_timer_resolution(self) -> float: ... # readonly in Cython + def __init__(self, flags: Sequence[str] | str | int | None = None, default: bool | None = None, ptr: int = 0) -> None: ... + def destroy(self) -> None: ... + @property + def ptr(self) -> int: ... + @property + def WatcherType(self) -> type[watcher.watcher]: ... + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def handle_error( + self, context: object | None, type: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> None: ... + def run(self, nowait: bool = False, once: bool = False) -> None: ... + def reinit(self) -> None: ... + def ref(self) -> None: ... + def unref(self) -> None: ... + def break_(self, how: int = 1) -> None: ... + def verify(self) -> None: ... + def now(self) -> float: ... + def update_now(self) -> None: ... + update = update_now # deprecated + @property + def default(self) -> bool: ... + @property + def iteration(self) -> int: ... + @property + def depth(self) -> int: ... + @property + def backend_int(self) -> int: ... + @property + def backend(self) -> str | int: ... + @property + def pendingcnt(self) -> int: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> watcher.io: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> watcher.prepare: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + def install_sigchld(self) -> None: ... + def reset_sigchld(self) -> None: ... + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> watcher.stat: ... + # These technically don't allow the functions arguments to be passed in as kwargs + # but there's no way to express that yet with ParamSpec, however, we would still like + # to verify that the arguments match + def run_callback(self, func: Callable[_P, Any], *args: _P.args, **_: _P.kwargs) -> _Callback: ... + def run_callback_threadsafe(self, func: Callable[_P, Any], *args: _P.args, **_: _P.kwargs) -> _Callback: ... + def fileno(self) -> FileDescriptor | None: ... + @property + def activecnt(self) -> int: ... + @property + def sig_pending(self) -> int: ... + # the final item in the list could be a integer if some of the flags don't a string mapping + @property + def origflags(self) -> list[str | int]: ... + @property + def origflags_int(self) -> int: ... + @property + def sigfd(self) -> FileDescriptor: ... + + __all__ = [ + "get_version", + "get_header_version", + "supported_backends", + "recommended_backends", + "embeddable_backends", + "time", + "loop", + ] diff --git a/stubs/gevent/gevent/libev/corecffi.pyi b/stubs/gevent/gevent/libev/corecffi.pyi new file mode 100644 index 000000000000..3f7821a82524 --- /dev/null +++ b/stubs/gevent/gevent/libev/corecffi.pyi @@ -0,0 +1,46 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Sequence + +from gevent._ffi.loop import AbstractLoop +from gevent.libev import watcher + +def get_version() -> str: ... +def get_header_version() -> str: ... +def supported_backends() -> list[str | int]: ... +def recommended_backends() -> list[str | int]: ... +def embeddable_backends() -> list[str | int]: ... +def time() -> float: ... + +class loop(AbstractLoop): + approx_timer_resolution: float + error_handler: None + @property + def MAXPRI(self) -> int: ... + @property + def MINPRI(self) -> int: ... + def __init__(self, flags: Sequence[str] | str | int | None = None, default: bool | None = None) -> None: ... + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> watcher.io: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def prepare(self, ref: bool = True, priority: int | None = None) -> watcher.prepare: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + def reset_sigchld(self) -> None: ... + + def stat(self, path: str, interval: float = 0.0, ref: bool = True, priority: bool | None = None) -> watcher.stat: ... + +__all__ = [ + "get_version", + "get_header_version", + "supported_backends", + "recommended_backends", + "embeddable_backends", + "time", + "loop", +] diff --git a/stubs/gevent/gevent/libev/watcher.pyi b/stubs/gevent/gevent/libev/watcher.pyi new file mode 100644 index 000000000000..776056872c35 --- /dev/null +++ b/stubs/gevent/gevent/libev/watcher.pyi @@ -0,0 +1,71 @@ +import sys +from _typeshed import FileDescriptor +from collections.abc import Callable +from typing import ParamSpec, TypeAlias + +from gevent._ffi import watcher as _base +from gevent.libev.corecffi import loop as cffi_loop + +__all__: list[str] = [] + +if sys.platform != "win32": + from gevent.libev.corecext import loop as cext_loop + + _Loop: TypeAlias = cffi_loop | cext_loop +else: + _Loop: TypeAlias = cffi_loop + +_P = ParamSpec("_P") + +class watcher(_base.watcher): + def __init__(self, _loop: _Loop, ref: bool = True, priority: int | None = None) -> None: ... + + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + + # does not accept keyword arguments + def feed(self, revents: int, callback: Callable[_P, object], *args: _P.args, **_: _P.kwargs) -> None: ... + +class io(_base.IoMixin, watcher): + EVENT_MASK: int + + @property + def fd(self) -> FileDescriptor: ... + @fd.setter + def fd(self, value: FileDescriptor) -> None: ... + + @property + def events(self) -> int: ... + @events.setter + def events(self, events: int) -> None: ... + + @property + def events_str(self) -> str: ... + +class timer(_base.TimerMixin, watcher): + @property + def at(self) -> float: ... + +class signal(_base.SignalMixin, watcher): ... +class idle(_base.IdleMixin, watcher): ... +class prepare(_base.PrepareMixin, watcher): ... +class check(_base.CheckMixin, watcher): ... +class fork(_base.ForkMixin, watcher): ... +class async_(_base.AsyncMixin, watcher): ... + +class child(_base.ChildMixin, watcher): + @property + def rpid(self) -> int: ... + @rpid.setter + def rpid(self, value: int) -> None: ... + + @property + def rstatus(self) -> int: ... + @rstatus.setter + def rstatus(self, value: int) -> None: ... + +class stat(_base.StatMixin, watcher): + @property + def interval(self) -> float: ... diff --git a/stubs/gevent/gevent/libuv/__init__.pyi b/stubs/gevent/gevent/libuv/__init__.pyi new file mode 100644 index 000000000000..c9c2ef67bd9d --- /dev/null +++ b/stubs/gevent/gevent/libuv/__init__.pyi @@ -0,0 +1 @@ +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libuv/loop.pyi b/stubs/gevent/gevent/libuv/loop.pyi new file mode 100644 index 000000000000..cd4ccd5287ef --- /dev/null +++ b/stubs/gevent/gevent/libuv/loop.pyi @@ -0,0 +1,44 @@ +import sys +from _typeshed import FileDescriptor +from typing import NamedTuple + +from gevent._ffi.loop import AbstractLoop +from gevent._types import _IoWatcher +from gevent.libuv import watcher + +def get_version() -> str: ... +def get_header_version() -> str: ... +def supported_backends() -> list[str]: ... + +class loop(AbstractLoop): + CALLBACK_CHECK_COUNT: int + SIGNAL_CHECK_INTERVAL_MS: int + approx_timer_resolution: float + error_handler: None + def __init__(self, flags: int | None = None, default: bool | None = None) -> None: ... + + class _HandleState(NamedTuple): + handle: int + type: str + watcher: watcher.watcher + ref: bool + active: bool + closing: bool + + def debug(self) -> list[_HandleState]: ... + def install_sigchld(self) -> None: ... + def reset_sigchld(self) -> None: ... + # this returns a class private to gevent.libuv.watcher.io, which satisifies the protocol + def io(self, fd: FileDescriptor, events: int, ref: bool = True, priority: int | None = None) -> _IoWatcher: ... + def closing_fd(self, fd: FileDescriptor) -> bool: ... + def timer(self, after: float, repeat: float = 0.0, ref: bool = True, priority: int | None = None) -> watcher.timer: ... + def signal(self, signum: int, ref: bool = True, priority: int | None = None) -> watcher.signal: ... + def idle(self, ref: bool = True, priority: int | None = None) -> watcher.idle: ... + def check(self, ref: bool = True, priority: int | None = None) -> watcher.check: ... + def async_(self, ref: bool = True, priority: int | None = None) -> watcher.async_: ... + if sys.platform != "win32": + def fork(self, ref: bool = True, priority: int | None = None) -> watcher.fork: ... + def child(self, pid: int, trace: int = 0, ref: bool = True) -> watcher.child: ... + # prepare is not supported on libuv yet, but we need type_error to annotate that + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/libuv/watcher.pyi b/stubs/gevent/gevent/libuv/watcher.pyi new file mode 100644 index 000000000000..84c9fe212baf --- /dev/null +++ b/stubs/gevent/gevent/libuv/watcher.pyi @@ -0,0 +1,37 @@ +from gevent._ffi import watcher as _base +from gevent._types import _IoWatcher + +class watcher(_base.watcher): + @property + def ref(self) -> bool: ... + @ref.setter + def ref(self, value: bool) -> None: ... + +class io(_base.IoMixin, watcher): + EVENT_MASK: int + + @property + def events(self) -> int: ... + @events.setter + def events(self, value: int) -> None: ... + + def multiplex(self, events: int) -> _IoWatcher: ... + def close_all(self) -> None: ... + +class fork(_base.ForkMixin, watcher): ... +class child(_base.ChildMixin, watcher): ... + +# for some reason pending on this has been overwritten with None, but we don't +# necessarily want to change our Protocol to reflect that, so for now we ignore it +class async_(_base.AsyncMixin, watcher): ... +class timer(_base.TimerMixin, watcher): ... + +class stat(_base.StatMixin, watcher): + MIN_STAT_INTERVAL: float + +class signal(_base.SignalMixin, watcher): ... +class idle(_base.IdleMixin, watcher): ... +class check(_base.CheckMixin, watcher): ... +class prepare(_base.PrepareMixin, watcher): ... + +__all__: list[str] = [] diff --git a/stubs/gevent/gevent/local.pyi b/stubs/gevent/gevent/local.pyi new file mode 100644 index 000000000000..ac2642fbe6a9 --- /dev/null +++ b/stubs/gevent/gevent/local.pyi @@ -0,0 +1,20 @@ +from typing import Any +from typing_extensions import Self + +class local: + __slots__ = ( + "_local__impl", + "_local_type_set_descriptors", + "_local_type_get_descriptors", + "_local_type_vars", + "_local_type_del_descriptors", + "_local_type", + "_local_type_set_or_del_descriptors", + ) + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + def __copy__(self) -> Self: ... + def __getattribute__(self, name: str, /) -> Any: ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +__all__ = ["local"] diff --git a/stubs/gevent/gevent/lock.pyi b/stubs/gevent/gevent/lock.pyi new file mode 100644 index 000000000000..80cb2342f661 --- /dev/null +++ b/stubs/gevent/gevent/lock.pyi @@ -0,0 +1,44 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal + +from gevent._abstract_linkable import AbstractLinkable +from gevent.hub import Hub + +__all__ = ["Semaphore", "BoundedSemaphore", "DummySemaphore", "RLock"] + +class Semaphore(AbstractLinkable): + __slots__ = ("counter", "_multithreaded") + counter: int + def __init__(self, value: int = 1, hub: Hub | None = None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def locked(self) -> bool: ... + def ready(self) -> bool: ... + def release(self) -> int: ... + def wait(self, timeout: float | None = None) -> int: ... + def __enter__(self) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +class BoundedSemaphore(Semaphore): + __slots__ = ("_initial_value",) + +class DummySemaphore: + def __init__(self, value: int | None = None) -> None: ... + def locked(self) -> Literal[False]: ... + def ready(self) -> Literal[True]: ... + def release(self) -> None: ... + def rawlink(self, callback: Callable[[Any], object]) -> None: ... + def unlink(self, callback: Callable[[Any], object]) -> None: ... + def wait(self, timeout: float | None = None) -> Literal[1]: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> Literal[True]: ... + def __enter__(self) -> None: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + +class RLock: + __slots__ = ("_block", "_owner", "_count", "__weakref__") + def __init__(self, hub: Hub | None = None) -> None: ... + def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... + def __enter__(self) -> bool: ... + def release(self) -> None: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + def locked(self) -> bool: ... diff --git a/stubs/gevent/gevent/monkey/__init__.pyi b/stubs/gevent/gevent/monkey/__init__.pyi new file mode 100644 index 000000000000..da6da0c3f35f --- /dev/null +++ b/stubs/gevent/gevent/monkey/__init__.pyi @@ -0,0 +1,68 @@ +from typing import Any + +from gevent.monkey.api import get_original as get_original, patch_module as patch_module + +class MonkeyPatchWarning(RuntimeWarning): ... + +def is_module_patched(mod_name: str) -> bool: ... +def is_object_patched(mod_name: str, item_name: str) -> bool: ... +def patch_os() -> None: ... +def patch_queue() -> None: ... +def patch_time() -> None: ... +def patch_thread( + threading: bool = True, _threading_local: bool = True, Event: bool = True, logging: bool = True, existing_locks: bool = True +) -> None: ... +def patch_socket(dns: bool = True, aggressive: bool = True) -> None: ... +def patch_builtins() -> None: ... +def patch_dns() -> None: ... +def patch_ssl() -> None: ... +def patch_select(aggressive: bool = True) -> None: ... +def patch_selectors(aggressive: bool = True) -> None: ... +def patch_subprocess() -> None: ... +def patch_sys(stdin: bool = True, stdout: bool = True, stderr: bool = True) -> None: ... +def patch_signal() -> None: ... +def patch_all( + socket: bool = True, + dns: bool = True, + time: bool = True, + select: bool = True, + thread: bool = True, + os: bool = True, + ssl: bool = True, + subprocess: bool = True, + sys: bool = False, + aggressive: bool = True, + Event: bool = True, + builtins: bool = True, # does nothing on Python 3 + signal: bool = True, + queue: bool = True, + contextvars: bool = True, # does nothing on Python 3.7+ + **kwargs: object, +) -> bool | None: ... +def main() -> dict[str, Any]: ... + +__all__ = [ + "patch_all", + "patch_builtins", + "patch_dns", + "patch_os", + "patch_queue", + "patch_select", + "patch_signal", + "patch_socket", + "patch_ssl", + "patch_subprocess", + "patch_sys", + "patch_thread", + "patch_time", + # query functions + "get_original", + "is_module_patched", + "is_object_patched", + # plugin API + "patch_module", + # module functions + "main", + # Errors and warnings + "MonkeyPatchWarning", +] diff --git a/stubs/gevent/gevent/monkey/api.pyi b/stubs/gevent/gevent/monkey/api.pyi new file mode 100644 index 000000000000..130687dec5c0 --- /dev/null +++ b/stubs/gevent/gevent/monkey/api.pyi @@ -0,0 +1,7 @@ +from types import ModuleType +from typing import Any + +def get_original(mod_name: str, item_name: str) -> Any: ... +def patch_item(module: ModuleType, attr: str, newitem: object) -> None: ... +def remove_item(module: ModuleType, attr: str) -> None: ... +def patch_module(target_module: ModuleType, source_module: ModuleType, items: list[str] | None = None) -> bool: ... diff --git a/stubs/gevent/gevent/os.pyi b/stubs/gevent/gevent/os.pyi new file mode 100644 index 000000000000..ac7d0cf0b976 --- /dev/null +++ b/stubs/gevent/gevent/os.pyi @@ -0,0 +1,36 @@ +import os +import sys +from _typeshed import FileDescriptor, ReadableBuffer +from collections.abc import Callable +from typing import Literal + +from gevent._types import _ChildWatcher, _Loop + +def tp_read(fd: FileDescriptor, n: int) -> bytes: ... +def tp_write(fd: FileDescriptor, buf: ReadableBuffer) -> int: ... + +if sys.platform != "win32": + def close(fd: FileDescriptor) -> None: ... + def make_nonblocking(fd: FileDescriptor) -> Literal[True] | None: ... + def nb_read(fd: FileDescriptor, n: int) -> bytes: ... + def nb_write(fd: FileDescriptor, buf: ReadableBuffer) -> int: ... + fork = os.fork + forkpty = os.forkpty + def fork_gevent() -> int: ... + def forkpty_gevent() -> tuple[int, int]: ... + waitpid = os.waitpid + def fork_and_watch( + callback: Callable[[_ChildWatcher], object] | None = None, + loop: _Loop | None = None, + ref: bool = False, + fork: Callable[[], int] = ..., + ) -> int: ... + def forkpty_and_watch( + callback: Callable[[_ChildWatcher], object] | None = None, + loop: _Loop | None = None, + ref: bool = False, + forkpty: Callable[[], tuple[int, int]] = ..., + ) -> tuple[int, int]: ... + + posix_spawn = os.posix_spawn + posix_spawnp = os.posix_spawnp diff --git a/stubs/gevent/gevent/pool.pyi b/stubs/gevent/gevent/pool.pyi new file mode 100644 index 000000000000..74345130b9ed --- /dev/null +++ b/stubs/gevent/gevent/pool.pyi @@ -0,0 +1,209 @@ +from collections.abc import Callable, Collection, Iterable, Iterator +from typing import Any, ParamSpec, TypeVar, overload + +from gevent._imap import IMap, IMapUnordered +from gevent.greenlet import Greenlet +from gevent.queue import Full as QueueFull + +__all__ = ["Group", "Pool", "PoolFull"] + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_T4 = TypeVar("_T4") +_T5 = TypeVar("_T5") +_S = TypeVar("_S") +_P = ParamSpec("_P") + +class GroupMappingMixin: + __slots__ = () + def spawn(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Greenlet[_P, _T]: ... + # we would like to use ParamSpec for these, but since args and kwds are passed in as is + # pyright will complain if we use _P.args/_P.kwargs, it appears to work on mypy though + # we can probably get away with Sequence and Mapping instead of tuple and dict, but for + # now we will be strict, just to be safe + def apply_cb( + self, + func: Callable[..., _T], + args: tuple[Any, ...] | None = None, + kwds: dict[str, Any] | None = None, + callback: Callable[[_T], object] | None = None, + ) -> _T: ... + # The ParamSpec of the spawned greenlet can differ from the one being passed in, but the return type will match + def apply_async( + self, + func: Callable[..., _T], + args: tuple[Any, ...] | None = None, + kwds: dict[str, Any] | None = None, + callback: Callable[[_T], object] | None = None, + ) -> Greenlet[..., _T]: ... + def apply(self, func: Callable[..., _T], args: tuple[Any, ...] | None = None, kwds: dict[str, Any] | None = None) -> _T: ... + def map(self, func: Callable[[_T], _S], iterable: Iterable[_T]) -> list[_S]: ... + def map_cb( + self, func: Callable[[_T], _S], iterable: Iterable[_T], callback: Callable[[list[_S]], object] | None = None + ) -> list[_S]: ... + def map_async( + self, func: Callable[[_T], _S], iterable: Iterable[_T], callback: Callable[[list[_S]], object] | None = None + ) -> Greenlet[..., list[_S]]: ... + + @overload + def imap(self, func: Callable[[_T1], _S], iter1: Iterable[_T1], /, *, maxsize: int | None = None) -> IMap[[_T1], _S]: ... + @overload + def imap( + self, func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, maxsize: int | None = None + ) -> IMap[[_T1, _T2], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3, _T4], _S]: ... + @overload + def imap( + self, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + maxsize: int | None = None, + ) -> IMap[[_T1, _T2, _T3, _T4, _T5], _S]: ... + @overload + def imap( + self, + func: Callable[_P, _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + maxsize: int | None = None, + ) -> IMap[_P, _S]: ... + + @overload + def imap_unordered( + self, func: Callable[[_T1], _S], iter1: Iterable[_T1], /, *, maxsize: int | None = None + ) -> IMapUnordered[[_T1], _S]: ... + @overload + def imap_unordered( + self, func: Callable[[_T1, _T2], _S], iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, maxsize: int | None = None + ) -> IMapUnordered[[_T1, _T2], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3, _T4], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3, _T4], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + maxsize: int | None = None, + ) -> IMapUnordered[[_T1, _T2, _T3, _T4, _T5], _S]: ... + @overload + def imap_unordered( + self, + func: Callable[_P, _S], + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + maxsize: int | None = None, + ) -> IMapUnordered[_P, _S]: ... + +# TODO: Consider making these generic in Greenlet. The drawback would be, that it +# wouldn't be possible to mix Greenlets with different return values/ParamSpecs +# unless you bind Grenlet[..., object], but in that case all the spawn/apply/map +# methods become less helpful, because the return types cannot be as specific... +# We would need higher-kinded TypeVars if we wanted to give up neither +class Group(GroupMappingMixin): + greenlet_class: type[Greenlet[..., Any]] + greenlets: set[Greenlet[..., Any]] + dying: set[Greenlet[..., Any]] + + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, grenlets: Collection[Greenlet[..., object]], /) -> None: ... + + def __len__(self) -> int: ... + def __contains__(self, item: Greenlet[..., object]) -> bool: ... + def __iter__(self) -> Iterator[Greenlet[..., object]]: ... + def add(self, greenlet: Greenlet[..., object]) -> None: ... + def discard(self, greenlet: Greenlet[..., object]) -> None: ... + def start(self, greenlet: Greenlet[..., object]) -> None: ... + def join(self, timeout: float | None = None, raise_error: bool = False) -> bool: ... + def kill( + self, exception: type[BaseException] | BaseException = ..., block: bool = True, timeout: float | None = None + ) -> None: ... + def killone( + self, + greenlet: Greenlet[..., object], + exception: type[BaseException] | BaseException = ..., + block: bool = True, + timeout: float | None = None, + ) -> None: ... + def full(self) -> bool: ... + def wait_available(self, timeout: float | None = None) -> int | None: ... + +class PoolFull(QueueFull): ... + +class Pool(Group): + size: int | None + def __init__(self, size: int | None = None, greenlet_class: type[Greenlet[..., object]] | None = None) -> None: ... + def wait_available(self, timeout: float | None = None) -> int: ... + def free_count(self) -> int: ... + def start(self, greenlet: Greenlet[..., object], blocking: bool = True, timeout: float | None = None) -> None: ... + def add(self, greenlet: Greenlet[..., object], blocking: bool = True, timeout: float | None = None) -> None: ... diff --git a/stubs/gevent/gevent/pywsgi.pyi b/stubs/gevent/gevent/pywsgi.pyi new file mode 100644 index 000000000000..cda7fd112a38 --- /dev/null +++ b/stubs/gevent/gevent/pywsgi.pyi @@ -0,0 +1,197 @@ +from _typeshed import OptExcInfo, StrOrBytesPath, SupportsWrite +from _typeshed.wsgi import WSGIApplication, WSGIEnvironment +from collections.abc import Callable, Container, Iterable, Iterator +from http.client import HTTPMessage +from io import BufferedIOBase, BufferedReader +from logging import Logger +from types import TracebackType +from typing import Any, ClassVar, Literal, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from gevent.baseserver import _Spawner +from gevent.server import StreamServer +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext + +__all__ = ["WSGIServer", "WSGIHandler", "LoggingLogAdapter", "Environ", "SecureEnviron", "WSGISecureEnviron"] + +_T = TypeVar("_T") + +@type_check_only +class _LogOutputStream(SupportsWrite[str], Protocol): + def writelines(self, lines: Iterable[str], /) -> None: ... + def flush(self) -> None: ... + +class Input: + __slots__ = ( + "rfile", + "content_length", + "socket", + "position", + "chunked_input", + "chunk_length", + "_chunked_input_error", + "send_100_continue_enabled", + ) + rfile: BufferedReader + content_length: int | None + socket: _GeventSocket | None + position: int + chunked_input: bool + chunk_length: int + send_100_continue_enabled: bool + def __init__( + self, rfile: BufferedReader, content_length: int | None, socket: _GeventSocket | None = None, chunked_input: bool = False + ) -> None: ... + def read(self, length: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: object | None = None) -> list[bytes]: ... + def __iter__(self) -> Self: ... + def next(self) -> bytes: ... + __next__ = next + +class OldMessage(HTTPMessage): + status: str + def __init__(self) -> None: ... + + @overload + def getheader(self, name: str, default: None = None) -> str | None: ... + @overload + def getheader(self, name: str, default: _T) -> str | _T: ... + + @property + def headers(self) -> Iterator[str]: ... + @property + def typeheader(self) -> str | None: ... + +class WSGIHandler: + protocol_version: str + def MessageClass(self, fp: BufferedIOBase) -> OldMessage: ... + status: str | None + response_headers: list[tuple[str, str]] | None + code: int | None + provided_date: str | None + provided_content_length: str | None + close_connection: bool + time_start: float + time_finish: float + headers_sent: bool + response_use_chunked: bool + connection_upgraded: bool + environ: WSGIEnvironment | None + application: WSGIApplication | None + requestline: str | None + response_length: int + result: Iterable[bytes] | None + wsgi_input: Input | None + content_length: int + headers: OldMessage + request_version: str | None + command: str | None + path: str | None + socket: _GeventSocket + client_address: str + server: WSGIServer + rfile: BufferedReader + def __init__(self, sock: _GeventSocket, address: str, server: WSGIServer) -> None: ... + def handle(self) -> None: ... + def read_request(self, raw_requestline: str) -> OldMessage: ... + def log_error(self, msg: str, *args: object) -> None: ... + def read_requestline(self) -> str: ... + def handle_one_request(self) -> tuple[str, bytes] | Literal[True] | None: ... + def finalize_headers(self) -> None: ... + ApplicationError: type[AssertionError] + def write(self, data: bytes) -> None: ... + def start_response( + self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None + ) -> Callable[[bytes], None]: ... + def log_request(self) -> None: ... + def format_request(self) -> str: ... + def process_result(self) -> None: ... + def run_application(self) -> None: ... + ignored_socket_errors: tuple[int, ...] + def handle_one_response(self) -> None: ... + def handle_error(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def get_environ(self) -> WSGIEnvironment: ... + +class LoggingLogAdapter: + __slots__ = ("_logger", "_level") + def __init__(self, logger: Logger, level: int = 20) -> None: ... + def write(self, msg: str) -> None: ... + def flush(self) -> None: ... + def writelines(self, lines: Iterable[str]) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: object) -> None: ... + def __delattr__(self, name: str) -> None: ... + +class Environ(WSGIEnvironment): + __slots__ = () + +class SecureEnviron(Environ): + __slots__ = ("secure_repr", "whitelist_keys", "print_masked_keys") + default_secure_repr: ClassVar[bool] + default_whitelist_keys: ClassVar[Container[str]] + default_print_masked_keys: ClassVar[bool] + secure_repr: bool + whitelist_keys: Container[str] + print_masked_keys: bool + +class WSGISecureEnviron(SecureEnviron): ... + +class WSGIServer(StreamServer): + handler_class: type[WSGIHandler] + log: _LogOutputStream + error_log: _LogOutputStream + environ_class: type[WSGIEnvironment] + secure_environ_class: type[SecureEnviron] + base_env: WSGIEnvironment + application: WSGIApplication + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + application: WSGIApplication | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + log: str | Logger | _LogOutputStream | None = "default", + error_log: str | Logger | _LogOutputStream | None = "default", + handler_class: type[WSGIHandler] | None = None, + environ: WSGIEnvironment | None = None, + *, + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + application: WSGIApplication | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + log: str | Logger | _LogOutputStream | None = "default", + error_log: str | Logger | _LogOutputStream | None = "default", + handler_class: type[WSGIHandler] | None = None, + environ: WSGIEnvironment | None = None, + *, + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + environ: WSGIEnvironment + def set_environ(self, environ: WSGIEnvironment | None = None) -> None: ... + max_accept: int + def set_max_accept(self) -> None: ... + def get_environ(self) -> WSGIEnvironment: ... + def init_socket(self) -> None: ... + def update_environ(self) -> None: ... + def handle(self, sock: _GeventSocket, address: str) -> None: ... diff --git a/stubs/gevent/gevent/queue.pyi b/stubs/gevent/gevent/queue.pyi new file mode 100644 index 000000000000..afe1ce226dc0 --- /dev/null +++ b/stubs/gevent/gevent/queue.pyi @@ -0,0 +1,115 @@ +import sys +import types +from collections import deque +from collections.abc import Iterable + +# technically it is using _PySimpleQueue, which has the same interface as SimpleQueue +from queue import Empty as Empty, Full as Full +from typing import Any, Generic, Literal, TypeVar, final, overload +from typing_extensions import Self + +from gevent._waiter import Waiter +from gevent.hub import Hub + +__all__ = ["Queue", "PriorityQueue", "LifoQueue", "SimpleQueue", "JoinableQueue", "Channel", "Empty", "Full", "ShutDown"] + +if sys.version_info >= (3, 13): + from queue import ShutDown as ShutDown +else: + class ShutDown(Exception): ... + +_T = TypeVar("_T") + +class SimpleQueue(Generic[_T]): + __slots__ = ("_maxsize", "getters", "putters", "hub", "_event_unlock", "queue", "__weakref__", "is_shutdown") + @property + def hub(self) -> Hub: ... # readonly in Cython + @property + def queue(self) -> deque[_T]: ... # readonly in Cython + maxsize: int | None + is_shutdown: bool + + @classmethod + def __class_getitem__(cls, item: Any, /) -> types.GenericAlias: ... + + @overload + def __init__(self, maxsize: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None, items: Iterable[_T]) -> None: ... + @overload + def __init__(self, maxsize: int | None = None, *, items: Iterable[_T]) -> None: ... + + def copy(self) -> Self: ... + def empty(self) -> bool: ... + def full(self) -> bool: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def peek(self, block: bool = True, timeout: float | None = None) -> _T: ... + def peek_nowait(self) -> _T: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def qsize(self) -> int: ... + def __bool__(self) -> bool: ... + def __iter__(self) -> Self: ... + def __len__(self) -> int: ... + def __next__(self) -> _T: ... + next = __next__ + +class Queue(SimpleQueue[_T]): + __slots__ = ("_cond", "unfinished_tasks") + @property + def unfinished_tasks(self) -> int: ... # readonly in Cython + + @overload + def __init__(self, maxsize: int | None = None, *, unfinished_tasks: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None, items: Iterable[_T], unfinished_tasks: int | None = None) -> None: ... + @overload + def __init__(self, maxsize: int | None = None, *, items: Iterable[_T], unfinished_tasks: int | None = None) -> None: ... + + def join(self, timeout: float | None = None) -> bool: ... + def task_done(self) -> None: ... + def shutdown(self, immediate: bool = False) -> None: ... + +JoinableQueue = Queue + +@final +class UnboundQueue(Queue[_T]): + __slots__ = () + + @overload + def __init__(self, maxsize: None = None) -> None: ... + @overload + def __init__(self, maxsize: None, items: Iterable[_T]) -> None: ... + @overload + def __init__(self, maxsize: None = None, *, items: Iterable[_T]) -> None: ... + +class PriorityQueue(Queue[_T]): + __slots__ = () + +class LifoQueue(Queue[_T]): + __slots__ = () + +class Channel(Generic[_T]): + __slots__ = ("getters", "putters", "hub", "_event_unlock", "__weakref__") + @property + def getters(self) -> deque[Waiter[Any]]: ... # readonly in Cython + @property + def putters(self) -> deque[tuple[_T, Waiter[Any]]]: ... # readonly in Cython + @property + def hub(self) -> Hub: ... # readonly in Cython + def __init__(self, maxsize: Literal[1] = 1) -> None: ... + @classmethod + def __class_getitem__(cls, item: Any, /) -> types.GenericAlias: ... + @property + def balance(self) -> int: ... + def qsize(self) -> Literal[0]: ... + def empty(self) -> Literal[True]: ... + def full(self) -> Literal[True]: ... + def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... + def put_nowait(self, item: _T) -> None: ... + def get(self, block: bool = True, timeout: float | None = None) -> _T: ... + def get_nowait(self) -> _T: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + next = __next__ diff --git a/stubs/gevent/gevent/resolver/__init__.pyi b/stubs/gevent/gevent/resolver/__init__.pyi new file mode 100644 index 000000000000..72609bc06442 --- /dev/null +++ b/stubs/gevent/gevent/resolver/__init__.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class AbstractResolver: + HOSTNAME_ENCODING: str + EAI_NONAME_MSG: str + EAI_FAMILY_MSG: str + def close(self) -> None: ... + @staticmethod + def fixup_gaierror(func: _F) -> _F: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = () diff --git a/stubs/gevent/gevent/resolver/ares.pyi b/stubs/gevent/gevent/resolver/ares.pyi new file mode 100644 index 000000000000..ca16b3cf1dc1 --- /dev/null +++ b/stubs/gevent/gevent/resolver/ares.pyi @@ -0,0 +1,41 @@ +from collections.abc import Sequence +from typing import TypedDict, type_check_only + +from gevent._types import _Watcher +from gevent.hub import Hub +from gevent.resolver import AbstractResolver +from gevent.resolver.cares import channel + +@type_check_only +class _ChannelArgs(TypedDict): + flags: str | int | None + timeout: str | float | None + tries: str | int | None + ndots: str | int | None + udp_port: str | int | None + tcp_port: str | int | None + servers: Sequence[str] | str | None + +class Resolver(AbstractResolver): + cares_class: type[channel] + hub: Hub + cares: channel + pid: int + params: _ChannelArgs + fork_watcher: _Watcher + def __init__( + self, + hub: Hub | None = None, + use_environ: bool = True, + *, + flags: str | int | None = None, + timeout: str | float | None = None, + tries: str | int | None = None, + ndots: str | int | None = None, + udp_port: str | int | None = None, + tcp_port: str | int | None = None, + servers: Sequence[str] | str | None = None, + ) -> None: ... + def __del__(self) -> None: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/blocking.pyi b/stubs/gevent/gevent/resolver/blocking.pyi new file mode 100644 index 000000000000..54ee37b7ce31 --- /dev/null +++ b/stubs/gevent/gevent/resolver/blocking.pyi @@ -0,0 +1,15 @@ +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr +from gevent.hub import Hub + +class Resolver: + def __init__(self, hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/cares.pyi b/stubs/gevent/gevent/resolver/cares.pyi new file mode 100644 index 000000000000..01dbe77d2e2c --- /dev/null +++ b/stubs/gevent/gevent/resolver/cares.pyi @@ -0,0 +1,52 @@ +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Generic, TypeVar +from typing_extensions import Self, disjoint_base + +from gevent._types import _AddrinfoResult, _Loop, _NameinfoResult, _SockAddr + +_T = TypeVar("_T") + +class ares_host_result(tuple[str, list[str], list[str]]): + family: int + def __new__(cls, family: int, iterable: Iterable[Any]) -> Self: ... + +@disjoint_base +class Result(Generic[_T]): + exception: BaseException | None + value: _T | None + def __init__(self, value: _T | None = None, exception: BaseException | None = None) -> None: ... + def get(self) -> Any | None: ... + def successful(self) -> bool: ... + +@disjoint_base +class channel: + @property + def loop(self) -> _Loop: ... + def __init__( + self, + loop: _Loop, + flags: str | int | None = None, + timeout: str | float | None = None, + tries: str | int | None = None, + ndots: str | int | None = None, + udp_port: str | int | None = None, + tcp_port: str | int | None = None, + servers: Sequence[str] | str | None = None, + ) -> None: ... + def destroy(self) -> None: ... + def getaddrinfo( + self, + callback: Callable[[Result[_AddrinfoResult]], object], + name: str, + service: str | None, + family: int = 0, + type: int = 0, + proto: int = 0, + flags: int = 0, + ) -> None: ... + def gethostbyaddr(self, callback: Callable[[Result[ares_host_result]], object], addr: str) -> Any: ... + def gethostbyname(self, callback: Callable[[Result[ares_host_result]], object], name: str, family: int = 2) -> None: ... + def getnameinfo(self, callback: Callable[[Result[_NameinfoResult]], object], sockaddr: _SockAddr, flags: int) -> None: ... + def set_servers(self, servers: Sequence[str] | str | None = None) -> None: ... + +__all__ = ["channel"] diff --git a/stubs/gevent/gevent/resolver/dnspython.pyi b/stubs/gevent/gevent/resolver/dnspython.pyi new file mode 100644 index 000000000000..cf965d10a2c9 --- /dev/null +++ b/stubs/gevent/gevent/resolver/dnspython.pyi @@ -0,0 +1,11 @@ +from typing import Any + +from gevent.hub import Hub +from gevent.resolver import AbstractResolver + +class Resolver(AbstractResolver): + def __init__(self, hub: Hub | None = ...) -> None: ... + @property + def resolver(self) -> Any: ... # this is a custom dnspython Resolver + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver/thread.pyi b/stubs/gevent/gevent/resolver/thread.pyi new file mode 100644 index 000000000000..3a265ed172c3 --- /dev/null +++ b/stubs/gevent/gevent/resolver/thread.pyi @@ -0,0 +1,17 @@ +from gevent._types import _AddrinfoResult, _NameinfoResult, _SockAddr +from gevent.hub import Hub +from gevent.threadpool import ThreadPool + +class Resolver: + pool: ThreadPool + def __init__(self, hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def gethostbyname(self, hostname: str, family: int = 2) -> str: ... + def gethostbyname_ex(self, hostname: str, family: int = 2) -> tuple[str, list[str], list[str]]: ... + def getaddrinfo( + self, host: str, port: int, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0 + ) -> _AddrinfoResult: ... + def gethostbyaddr(self, ip_address: str) -> tuple[str, list[str], list[str]]: ... + def getnameinfo(self, sockaddr: _SockAddr, flags: int) -> _NameinfoResult: ... + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver_ares.pyi b/stubs/gevent/gevent/resolver_ares.pyi new file mode 100644 index 000000000000..4d1fbbaae20e --- /dev/null +++ b/stubs/gevent/gevent/resolver_ares.pyi @@ -0,0 +1,3 @@ +from gevent.resolver.ares import * + +__all__ = ["Resolver"] diff --git a/stubs/gevent/gevent/resolver_thread.pyi b/stubs/gevent/gevent/resolver_thread.pyi new file mode 100644 index 000000000000..f960eab26073 --- /dev/null +++ b/stubs/gevent/gevent/resolver_thread.pyi @@ -0,0 +1,2 @@ +from gevent.resolver.thread import * +from gevent.resolver.thread import __all__ as __all__ diff --git a/stubs/gevent/gevent/select.pyi b/stubs/gevent/gevent/select.pyi new file mode 100644 index 000000000000..b1313ceda1b7 --- /dev/null +++ b/stubs/gevent/gevent/select.pyi @@ -0,0 +1,20 @@ +import sys +from _typeshed import FileDescriptorLike +from collections.abc import Iterable +from select import error as error +from typing import Any + +def select( + rlist: Iterable[Any], wlist: Iterable[Any], xlist: Iterable[Any], timeout: float | None = None +) -> tuple[list[Any], list[Any], list[Any]]: ... + +if sys.platform != "win32": + __all__ = ["error", "poll", "select"] +else: + __all__ = ["error", "select"] + +class poll: + def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... + def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... + def poll(self, timeout: float | None = None) -> list[tuple[int, int]]: ... + def unregister(self, fd: FileDescriptorLike) -> None: ... diff --git a/stubs/gevent/gevent/selectors.pyi b/stubs/gevent/gevent/selectors.pyi new file mode 100644 index 000000000000..12614ef1e6ff --- /dev/null +++ b/stubs/gevent/gevent/selectors.pyi @@ -0,0 +1,24 @@ +from _typeshed import FileDescriptorLike +from collections.abc import Mapping +from selectors import BaseSelector, SelectorKey +from typing import Any + +from gevent._util import Lazy +from gevent.hub import Hub + +__all__ = ["DefaultSelector", "GeventSelector"] + +# technically this derives from _BaseSelectorImpl, which does not have type annotations +# but in terms of type checking the only difference is, that we need to add get_map since +# GeventSelector does not override it +class GeventSelector(BaseSelector): + def __init__(self, hub: Hub | None = None) -> None: ... + @Lazy + def hub(self) -> Hub: ... + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + def close(self) -> None: ... + def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... + +DefaultSelector = GeventSelector diff --git a/stubs/gevent/gevent/server.pyi b/stubs/gevent/gevent/server.pyi new file mode 100644 index 000000000000..8f8306684052 --- /dev/null +++ b/stubs/gevent/gevent/server.pyi @@ -0,0 +1,89 @@ +from _socket import _Address as _StrictAddress +from _typeshed import ReadableBuffer, StrOrBytesPath +from collections.abc import Callable +from typing import Any, ClassVar, TypeAlias, TypedDict, overload, type_check_only + +from gevent.baseserver import BaseServer, _Spawner +from gevent.socket import socket as _GeventSocket +from gevent.ssl import SSLContext, wrap_socket as ssl_wrap_socket + +# For simplicity we treat _Address as Any, we could be more strict and use the definition +# from the stdlib _socket.pyi. But that would exclude some potentially valid handlers. +_Address: TypeAlias = Any + +@type_check_only +class _SSLArguments(TypedDict, total=False): + keyfile: StrOrBytesPath + certfile: StrOrBytesPath + server_side: bool + cert_reqs: int + ssl_version: int + ca_certs: str + suppress_ragged_eofs: bool + do_handshake_on_connect: bool + ciphers: str + +class StreamServer(BaseServer[_GeventSocket, _Address]): + backlog: int + reuse_addr: ClassVar[int | None] + wrap_socket = ssl_wrap_socket + ssl_args: _SSLArguments | None + + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + *, + ssl_context: SSLContext, + server_side: bool = True, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ) -> None: ... + @overload + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + backlog: int | None = None, + spawn: _Spawner = "default", + *, + keyfile: StrOrBytesPath = ..., + certfile: StrOrBytesPath = ..., + server_side: bool = True, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str = ..., + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str = ..., + ) -> None: ... + + @property + def ssl_enabled(self) -> bool: ... + @classmethod + def get_listener(cls, address: _StrictAddress, backlog: int | None = None, family: int | None = None) -> _GeventSocket: ... + def do_read(self) -> tuple[_GeventSocket, _Address]: ... + def do_close(self, sock: _GeventSocket, address: _Address) -> None: ... + def wrap_socket_and_handle(self, client_socket: _GeventSocket, address: _StrictAddress) -> Any: ... + +class DatagramServer(BaseServer[_GeventSocket, _Address]): + reuse_addr: ClassVar[int | None] + def __init__( + self, + listener: _GeventSocket | tuple[str, int] | str, + handle: Callable[[_GeventSocket, _Address], object] | None = None, + spawn: _Spawner = "default", + ) -> None: ... + @classmethod + def get_listener(cls, address: _StrictAddress, family: int | None = None) -> _GeventSocket: ... + def do_read(self) -> tuple[_GeventSocket, _Address]: ... + + @overload + def sendto(self, data: ReadableBuffer, address: _StrictAddress, /) -> int: ... + @overload + def sendto(self, data: ReadableBuffer, flags: int, address: _StrictAddress, /) -> int: ... + +__all__ = ["StreamServer", "DatagramServer"] diff --git a/stubs/gevent/gevent/signal.pyi b/stubs/gevent/gevent/signal.pyi new file mode 100644 index 000000000000..66d277ac680a --- /dev/null +++ b/stubs/gevent/gevent/signal.pyi @@ -0,0 +1,13 @@ +import sys +from signal import _HANDLER, _SIGNUM + +# technically the implementations will always be around, but since they always +# throw an exception on windows, due to the missing SIGCHLD, we might as well +# pretent they don't exist, but what is different, is that the parameters are +# named even pre 3.10, so we don't just import the symbol from stdlib signal +if sys.platform != "win32": + def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... + def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... + def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = True) -> int: ... + + __all__ = ["signal", "getsignal", "set_wakeup_fd"] diff --git a/stubs/gevent/gevent/socket.pyi b/stubs/gevent/gevent/socket.pyi new file mode 100644 index 000000000000..ccfc9a4c6f2c --- /dev/null +++ b/stubs/gevent/gevent/socket.pyi @@ -0,0 +1,23 @@ +from socket import * + +from gevent._hub_primitives import ( + wait_on_watcher, + wait_read as wait_read, + wait_readwrite as wait_readwrite, + wait_write as wait_write, +) +from gevent._types import _Watcher + +# This matches the stdlib socket module almost exactly, but contains a couple of extensions +# as a result we just pretend we import everything from socket, which is not entirely correct +# but it gets us most of the way there without having to write a really long list of imports +# with the same platform and version checks, just so we can properly distinguish this module's +# socket class from the native socket class (which could cause issues anyways, since functions +# that accept a socket should still accept the gevent implementation...) +# we can put in the work and do it properly once we have a use-case for it. +# the majority of the gevent implementation can be found in _socket3 and _socketcommon +# which also just imports a lot of symbols from the stdlib socket/_socket module + +wait = wait_on_watcher + +def cancel_wait(watcher: _Watcher, error: type[BaseException] | BaseException) -> None: ... diff --git a/stubs/gevent/gevent/ssl.pyi b/stubs/gevent/gevent/ssl.pyi new file mode 100644 index 000000000000..a8acf2abdaf5 --- /dev/null +++ b/stubs/gevent/gevent/ssl.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import StrOrBytesPath +from ssl import * + +import gevent.socket + +# for simplicity we trust that gevent's implementation matches the stdlib version exactly +# for the most part they just copy all the symbols anyways and re-implment the few that +# need to work differently. The only potentially problematic symbol is SSLSocket, since +# it derives from gevent's socket, rather than the stdlib one. SSLContext derives from +# the stdlib SSLContext. Since we already punted on socket, we don't need to change +# anything here either, until we decide that we can't punt on socket. + +if sys.version_info >= (3, 12): + # FIXME: wrap_socket has been removed in 3.12, gevent implements its own, so it + # will probably still be there in 3.12, but until we stub out gevent.ssl + # properly we will have to just pretend it still exists + def wrap_socket( + sock: gevent.socket.socket, + keyfile: StrOrBytesPath | None = None, + certfile: StrOrBytesPath | None = None, + server_side: bool = False, + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: str | None = None, + do_handshake_on_connect: bool = True, + suppress_ragged_eofs: bool = True, + ciphers: str | None = None, + ) -> SSLSocket: ... diff --git a/stubs/gevent/gevent/subprocess.pyi b/stubs/gevent/gevent/subprocess.pyi new file mode 100644 index 000000000000..8f4c048ba1e0 --- /dev/null +++ b/stubs/gevent/gevent/subprocess.pyi @@ -0,0 +1,4 @@ +from subprocess import * + +# this is another module we decide to just punt on and trust that gevent's implementation +# at the very least satisfies the stdlib interface. diff --git a/stubs/gevent/gevent/threadpool.pyi b/stubs/gevent/gevent/threadpool.pyi new file mode 100644 index 000000000000..22f71e18256b --- /dev/null +++ b/stubs/gevent/gevent/threadpool.pyi @@ -0,0 +1,71 @@ +import concurrent.futures +from collections.abc import Callable +from typing import Any, Generic, ParamSpec, TypeAlias, TypeVar + +from gevent._threading import Queue +from gevent._types import _AsyncWatcher, _Watcher +from gevent.event import AsyncResult, _OptExcInfo, _ValueSource +from gevent.greenlet import Greenlet +from gevent.hub import Hub +from gevent.pool import GroupMappingMixin + +_T = TypeVar("_T") +_P = ParamSpec("_P") +_TaskItem: TypeAlias = tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any], ThreadResult[Any]] +_Receiver: TypeAlias = Callable[[_ValueSource[_T]], object] + +class ThreadPool(GroupMappingMixin): + __slots__ = ( + "hub", + "_maxsize", + "manager", + "pid", + "fork_watcher", + "_available_worker_threads_greenlet_sem", + "_worker_greenlets", + "task_queue", + "_idle_task_timeout", + ) + hub: Hub + pid: int + manager: Greenlet[..., Any] | None + task_queue: Queue[_TaskItem] + fork_watcher: _Watcher + def __init__(self, maxsize: int, hub: Hub | None = None, idle_task_timeout: int = -1) -> None: ... + + @property + def maxsize(self) -> int: ... + @maxsize.setter + def maxsize(self, value: int) -> None: ... + + @property + def size(self) -> int: ... + @size.setter + def size(self, value: int) -> None: ... + + def __len__(self) -> int: ... + def join(self) -> None: ... + def kill(self) -> None: ... + def adjust(self) -> None: ... + def spawn(self, func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> AsyncResult[_T]: ... # type: ignore[override] + +class ThreadResult(Generic[_T]): + __slots__ = ("exc_info", "async_watcher", "_call_when_ready", "value", "context", "hub", "receiver") + receiver: _Receiver[_T] + hub: Hub + context: object | None + value: _T | None + exc_info: _OptExcInfo | tuple[()] + async_watcher: _AsyncWatcher + def __init__(self, receiver: _Receiver[_T], hub: Hub, call_when_ready: Callable[[], object]) -> None: ... + @property + def exception(self) -> BaseException | None: ... + def destroy_in_main_thread(self) -> None: ... + def set(self, value: _T) -> None: ... + def handle_error(self, context: object, exc_info: _OptExcInfo) -> None: ... + def successful(self) -> bool: ... + +class ThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor): + kill = concurrent.futures.ThreadPoolExecutor.shutdown + +__all__ = ["ThreadPool", "ThreadResult", "ThreadPoolExecutor"] diff --git a/stubs/gevent/gevent/time.pyi b/stubs/gevent/gevent/time.pyi new file mode 100644 index 000000000000..7bd856892efd --- /dev/null +++ b/stubs/gevent/gevent/time.pyi @@ -0,0 +1,3 @@ +from gevent.hub import sleep as sleep + +__all__ = ["sleep"] diff --git a/stubs/gevent/gevent/timeout.pyi b/stubs/gevent/gevent/timeout.pyi new file mode 100644 index 000000000000..0278eb2b51dd --- /dev/null +++ b/stubs/gevent/gevent/timeout.pyi @@ -0,0 +1,60 @@ +from collections.abc import Callable +from types import TracebackType +from typing import Any, Literal, ParamSpec, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Self + +from gevent._types import _TimerWatcher + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_TimeoutT = TypeVar("_TimeoutT", bound=Timeout) +_P = ParamSpec("_P") + +@type_check_only +class _HasSeconds(Protocol): + @property + def seconds(self) -> float | int: ... + +class Timeout(BaseException): + seconds: float | None + exception: type[BaseException] | BaseException | None + timer: _TimerWatcher + def __init__( + self, + seconds: float | None = None, + exception: type[BaseException] | BaseException | None = None, + ref: bool = True, + priority: int = -1, + ) -> None: ... + def start(self) -> None: ... + + @overload + @classmethod + def start_new( + cls, timeout: None | float = None, exception: type[BaseException] | BaseException | None = None, ref: bool = True + ) -> Self: ... + @overload + @classmethod + def start_new(cls, timeout: _TimeoutT) -> _TimeoutT: ... + + @property + def pending(self) -> bool: ... + def cancel(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None + ) -> Literal[True] | None: ... + def __lt__(self, other: _HasSeconds | float) -> bool: ... + +# when timeout_value is provided we unfortunately get no type checking on *args, **kwargs, because +# ParamSpec does not allow mixing in additional keyword arguments +@overload +def with_timeout( + seconds: float | None, function: Callable[..., _T1], *args: Any, timeout_value: _T2, **kwds: Any +) -> _T1 | _T2: ... +@overload +def with_timeout(seconds: float | None, function: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T: ... + +__all__ = ["Timeout", "with_timeout"] diff --git a/stubs/gevent/gevent/util.pyi b/stubs/gevent/gevent/util.pyi new file mode 100644 index 000000000000..d0fce9863178 --- /dev/null +++ b/stubs/gevent/gevent/util.pyi @@ -0,0 +1,51 @@ +from _typeshed import SupportsWrite +from collections.abc import Callable +from types import TracebackType +from typing import Any, Generic, ParamSpec, TypeVar +from typing_extensions import Self + +from gevent.hub import Hub +from greenlet import greenlet as greenlet_t + +_T = TypeVar("_T") +_P = ParamSpec("_P") + +class wrap_errors(Generic[_P, _T]): + def __init__(self, errors: tuple[type[BaseException], ...], func: Callable[_P, _T]) -> None: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ... + def __getattr__(self, name: str) -> Any: ... + +def print_run_info( + thread_stacks: bool = True, greenlet_stacks: bool = True, limit: int | None = ..., file: SupportsWrite[str] | None = None +) -> None: ... +def format_run_info( + thread_stacks: bool = True, greenlet_stacks: bool = True, limit: int | None = ..., current_thread_ident: int | None = None +) -> None: ... + +class GreenletTree: + greenlet: greenlet_t | None + is_current_tree: bool + child_trees: list[GreenletTree] + DEFAULT_DETAILS: dict[str, Any] + def __init__(self, greenlet: greenlet_t | None) -> None: ... + def add_child(self, tree: GreenletTree) -> None: ... + @property + def root(self) -> bool: ... + def __getattr__(self, name: str) -> Any: ... + def format_lines(self, details: bool | dict[str, Any] = True) -> str: ... + def format(self, details: bool | dict[str, Any] = True) -> str: ... + @classmethod + def forest(cls) -> list[GreenletTree]: ... + @classmethod + def current_tree(cls) -> GreenletTree: ... + +class assert_switches: + hub: Hub | None + tracer: object | None + max_blocking_time: float | None + hub_only: bool + def __init__(self, max_blocking_time: float | None = None, hub_only: bool = False) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + +__all__ = ["format_run_info", "print_run_info", "GreenletTree", "wrap_errors", "assert_switches"] diff --git a/stubs/gevent/gevent/win32util.pyi b/stubs/gevent/gevent/win32util.pyi new file mode 100644 index 000000000000..e6fc566ee52c --- /dev/null +++ b/stubs/gevent/gevent/win32util.pyi @@ -0,0 +1,5 @@ +from collections.abc import Callable + +formatError: Callable[[object], str] + +__all__ = ["formatError"] diff --git a/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt b/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..cdb920843ba3 --- /dev/null +++ b/stubs/google-cloud-ndb/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# inconsistency of signatures between stub and implementation (cls vs self) +google.cloud.ndb.metadata.EntityGroup.__new__ +google.cloud.ndb.model.ModelAdapter.__new__ diff --git a/stubs/google-cloud-ndb/METADATA.toml b/stubs/google-cloud-ndb/METADATA.toml new file mode 100644 index 000000000000..fb13602f4b47 --- /dev/null +++ b/stubs/google-cloud-ndb/METADATA.toml @@ -0,0 +1,6 @@ +version = "2.4.*" +upstream-repository = "https://github.com/googleapis/python-ndb" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi new file mode 100644 index 000000000000..39c67d5ae96d --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/__init__.pyi @@ -0,0 +1,218 @@ +from google.cloud.ndb._datastore_api import EVENTUAL as EVENTUAL, EVENTUAL_CONSISTENCY as EVENTUAL_CONSISTENCY, STRONG as STRONG +from google.cloud.ndb._datastore_query import Cursor as Cursor, QueryIterator as QueryIterator +from google.cloud.ndb._transaction import ( + in_transaction as in_transaction, + non_transactional as non_transactional, + transaction as transaction, + transaction_async as transaction_async, + transactional as transactional, + transactional_async as transactional_async, + transactional_tasklet as transactional_tasklet, +) +from google.cloud.ndb.client import Client as Client +from google.cloud.ndb.context import ( + AutoBatcher as AutoBatcher, + Context as Context, + ContextOptions as ContextOptions, + TransactionOptions as TransactionOptions, + get_context as get_context, + get_toplevel_context as get_toplevel_context, +) +from google.cloud.ndb.global_cache import GlobalCache as GlobalCache, MemcacheCache as MemcacheCache, RedisCache as RedisCache +from google.cloud.ndb.key import Key as Key +from google.cloud.ndb.model import ( + BadProjectionError as BadProjectionError, + BlobKey as BlobKey, + BlobKeyProperty as BlobKeyProperty, + BlobProperty as BlobProperty, + BooleanProperty as BooleanProperty, + ComputedProperty as ComputedProperty, + ComputedPropertyError as ComputedPropertyError, + DateProperty as DateProperty, + DateTimeProperty as DateTimeProperty, + Expando as Expando, + FloatProperty as FloatProperty, + GenericProperty as GenericProperty, + GeoPt as GeoPt, + GeoPtProperty as GeoPtProperty, + Index as Index, + IndexProperty as IndexProperty, + IndexState as IndexState, + IntegerProperty as IntegerProperty, + InvalidPropertyError as InvalidPropertyError, + JsonProperty as JsonProperty, + KeyProperty as KeyProperty, + KindError as KindError, + LocalStructuredProperty as LocalStructuredProperty, + MetaModel as MetaModel, + Model as Model, + ModelAdapter as ModelAdapter, + ModelAttribute as ModelAttribute, + ModelKey as ModelKey, + PickleProperty as PickleProperty, + Property as Property, + ReadonlyPropertyError as ReadonlyPropertyError, + Rollback as Rollback, + StringProperty as StringProperty, + StructuredProperty as StructuredProperty, + TextProperty as TextProperty, + TimeProperty as TimeProperty, + UnprojectedPropertyError as UnprojectedPropertyError, + User as User, + UserNotFoundError as UserNotFoundError, + UserProperty as UserProperty, + delete_multi as delete_multi, + delete_multi_async as delete_multi_async, + get_indexes as get_indexes, + get_indexes_async as get_indexes_async, + get_multi as get_multi, + get_multi_async as get_multi_async, + make_connection as make_connection, + put_multi as put_multi, + put_multi_async as put_multi_async, +) +from google.cloud.ndb.polymodel import PolyModel as PolyModel +from google.cloud.ndb.query import ( + AND as AND, + OR as OR, + ConjunctionNode as ConjunctionNode, + DisjunctionNode as DisjunctionNode, + FalseNode as FalseNode, + FilterNode as FilterNode, + Node as Node, + Parameter as Parameter, + ParameterizedFunction as ParameterizedFunction, + ParameterizedThing as ParameterizedThing, + ParameterNode as ParameterNode, + PostFilterNode as PostFilterNode, + Query as Query, + QueryOptions as QueryOptions, + RepeatedStructuredPropertyPredicate as RepeatedStructuredPropertyPredicate, + gql as gql, +) +from google.cloud.ndb.tasklets import ( + Future as Future, + QueueFuture as QueueFuture, + ReducingFuture as ReducingFuture, + Return as Return, + SerialQueueFuture as SerialQueueFuture, + add_flow_exception as add_flow_exception, + make_context as make_context, + make_default_context as make_default_context, + set_context as set_context, + sleep as sleep, + synctasklet as synctasklet, + tasklet as tasklet, + toplevel as toplevel, + wait_all as wait_all, + wait_any as wait_any, +) +from google.cloud.ndb.version import __version__ as __version__ + +__all__ = [ + "__version__", + "AutoBatcher", + "Client", + "Context", + "ContextOptions", + "EVENTUAL", + "EVENTUAL_CONSISTENCY", + "STRONG", + "TransactionOptions", + "Key", + "BlobKey", + "BlobKeyProperty", + "BlobProperty", + "BooleanProperty", + "ComputedProperty", + "ComputedPropertyError", + "DateProperty", + "DateTimeProperty", + "delete_multi", + "delete_multi_async", + "Expando", + "FloatProperty", + "GenericProperty", + "GeoPt", + "GeoPtProperty", + "get_indexes", + "get_indexes_async", + "get_multi", + "get_multi_async", + "GlobalCache", + "in_transaction", + "Index", + "IndexProperty", + "IndexState", + "IntegerProperty", + "InvalidPropertyError", + "BadProjectionError", + "JsonProperty", + "KeyProperty", + "KindError", + "LocalStructuredProperty", + "make_connection", + "MemcacheCache", + "MetaModel", + "Model", + "ModelAdapter", + "ModelAttribute", + "ModelKey", + "non_transactional", + "PickleProperty", + "PolyModel", + "Property", + "put_multi", + "put_multi_async", + "ReadonlyPropertyError", + "RedisCache", + "Rollback", + "StringProperty", + "StructuredProperty", + "TextProperty", + "TimeProperty", + "transaction", + "transaction_async", + "transactional", + "transactional_async", + "transactional_tasklet", + "UnprojectedPropertyError", + "User", + "UserNotFoundError", + "UserProperty", + "ConjunctionNode", + "AND", + "Cursor", + "DisjunctionNode", + "OR", + "FalseNode", + "FilterNode", + "gql", + "Node", + "Parameter", + "ParameterizedFunction", + "ParameterizedThing", + "ParameterNode", + "PostFilterNode", + "Query", + "QueryIterator", + "QueryOptions", + "RepeatedStructuredPropertyPredicate", + "add_flow_exception", + "Future", + "get_context", + "get_toplevel_context", + "make_context", + "make_default_context", + "QueueFuture", + "ReducingFuture", + "Return", + "SerialQueueFuture", + "set_context", + "sleep", + "synctasklet", + "tasklet", + "toplevel", + "wait_all", + "wait_any", +] diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi new file mode 100644 index 000000000000..be6e53a0daf0 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_batch.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +def get_batch(batch_cls, options: Incomplete | None = ...): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi new file mode 100644 index 000000000000..1047e3028f53 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_cache.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import tasklets as tasklets + +class ContextCache: + def get_and_validate(self, key): ... + +class _GlobalCacheBatch: + def full(self): ... + def idle_callback(self) -> None: ... + def done_callback(self, cache_call) -> None: ... + def make_call(self) -> None: ... + def future_info(self, key) -> None: ... + +global_get: Incomplete + +class _GlobalCacheGetBatch(_GlobalCacheBatch): + todo: Incomplete + keys: Incomplete + def __init__(self, ignore_options) -> None: ... + def add(self, key): ... + def done_callback(self, cache_call) -> None: ... + def make_call(self): ... + def future_info(self, key): ... + +def global_set(key, value, expires: Incomplete | None = ..., read: bool = ...): ... + +class _GlobalCacheSetBatch(_GlobalCacheBatch): + expires: Incomplete + todo: object + futures: object + def __init__(self, options) -> None: ... + def done_callback(self, cache_call) -> None: ... + def add(self, key, value): ... + def make_call(self): ... + def future_info(self, key, value): ... # type: ignore[override] + +class _GlobalCacheSetIfNotExistsBatch(_GlobalCacheSetBatch): + def add(self, key, value): ... + def make_call(self): ... + def future_info(self, key, value): ... # type: ignore[override] + +global_delete: Incomplete + +class _GlobalCacheDeleteBatch(_GlobalCacheBatch): + keys: Incomplete + futures: Incomplete + def __init__(self, ignore_options) -> None: ... + def add(self, key): ... + def make_call(self): ... + def future_info(self, key): ... + +global_watch: Incomplete + +class _GlobalCacheWatchBatch(_GlobalCacheDeleteBatch): + def make_call(self): ... + def future_info(self, key, value): ... # type: ignore[override] + +def global_unwatch(key): ... + +class _GlobalCacheUnwatchBatch(_GlobalCacheDeleteBatch): + def make_call(self): ... + def future_info(self, key): ... + +global_compare_and_swap: Incomplete + +class _GlobalCacheCompareAndSwapBatch(_GlobalCacheSetBatch): + def make_call(self): ... + def future_info(self, key, value): ... # type: ignore[override] + +def is_locked_value(value): ... +def global_cache_key(key): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi new file mode 100644 index 000000000000..e1dda8111460 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_api.pyi @@ -0,0 +1,5 @@ +from typing import Literal + +EVENTUAL: Literal[2] +EVENTUAL_CONSISTENCY: Literal[2] +STRONG: Literal[1] diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi new file mode 100644 index 000000000000..93454c9e1b7b --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_datastore_query.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +class QueryIterator: + def __iter__(self): ... + def has_next(self) -> None: ... + def has_next_async(self) -> None: ... + def probably_has_next(self) -> None: ... + def next(self) -> None: ... + def cursor_before(self) -> None: ... + def cursor_after(self) -> None: ... + def index_list(self) -> None: ... + +class Cursor: + @classmethod + def from_websafe_string(cls, urlsafe): ... + cursor: Incomplete + def __init__(self, cursor: Incomplete | None = ..., urlsafe: Incomplete | None = ...) -> None: ... + def to_websafe_string(self): ... + def urlsafe(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi new file mode 100644 index 000000000000..47091d2d3915 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_eventloop.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +class _Event(NamedTuple): + when: Incomplete + callback: Incomplete + args: Incomplete + kwargs: Incomplete + +class EventLoop: + current: Incomplete + idlers: Incomplete + inactive: int + queue: Incomplete + rpcs: Incomplete + rpc_results: Incomplete + def __init__(self) -> None: ... + def clear(self) -> None: ... + def insort_event_right(self, event) -> None: ... + def call_soon(self, callback, *args, **kwargs) -> None: ... + def queue_call(self, delay, callback, *args, **kwargs) -> None: ... + def queue_rpc(self, rpc, callback) -> None: ... + def add_idle(self, callback, *args, **kwargs) -> None: ... + def run_idle(self): ... + def run0(self): ... + def run1(self): ... + def run(self) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi new file mode 100644 index 000000000000..578a82948c09 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_options.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +class Options: + __slots__ = ( + "retries", + "timeout", + "use_cache", + "use_global_cache", + "global_cache_timeout", + "use_datastore", + "force_writes", + "max_memcache_items", + "propagation", + "deadline", + "use_memcache", + "memcache_timeout", + ) + @classmethod + def options(cls, wrapped, _disambiguate_from_model_properties: bool = ...): ... + @classmethod + def slots(cls): ... + def __init__(self, config: Incomplete | None = ..., **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def copy(self, **kwargs): ... + def items(self) -> None: ... + +class ReadOptions(Options): + __slots__ = ("read_consistency", "read_policy", "transaction") + def __init__(self, config: Incomplete | None = ..., **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi new file mode 100644 index 000000000000..c19dc18be185 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/_transaction.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +def in_transaction(): ... +def transaction( + callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ... +): ... +def transaction_async( + callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ... +): ... +def transaction_async_( + callback, retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ... +): ... +def transactional(retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ...): ... +def transactional_async( + retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ... +): ... +def transactional_tasklet( + retries=..., read_only: bool = ..., join: bool = ..., xg: bool = ..., propagation: Incomplete | None = ... +): ... +def non_transactional(allow_existing: bool = ...): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi new file mode 100644 index 000000000000..8db54d2a1908 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/blobstore.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import model + +BlobKey: Incomplete +BLOB_INFO_KIND: str +BLOB_MIGRATION_KIND: str +BLOB_KEY_HEADER: str +BLOB_RANGE_HEADER: str +MAX_BLOB_FETCH_SIZE: int +UPLOAD_INFO_CREATION_HEADER: str +BlobKeyProperty = model.BlobKeyProperty + +class BlobFetchSizeTooLargeError: + def __init__(self, *args, **kwargs) -> None: ... + +class BlobInfo: + def __init__(self, *args, **kwargs) -> None: ... + @classmethod + def get(cls, *args, **kwargs) -> None: ... + @classmethod + def get_async(cls, *args, **kwargs) -> None: ... + @classmethod + def get_multi(cls, *args, **kwargs) -> None: ... + @classmethod + def get_multi_async(cls, *args, **kwargs) -> None: ... + +class BlobInfoParseError: + def __init__(self, *args, **kwargs) -> None: ... + +class BlobNotFoundError: + def __init__(self, *args, **kwargs) -> None: ... + +class BlobReader: + def __init__(self, *args, **kwargs) -> None: ... + +def create_upload_url(*args, **kwargs) -> None: ... +def create_upload_url_async(*args, **kwargs) -> None: ... + +class DataIndexOutOfRangeError: + def __init__(self, *args, **kwargs) -> None: ... + +def delete(*args, **kwargs) -> None: ... +def delete_async(*args, **kwargs) -> None: ... +def delete_multi(*args, **kwargs) -> None: ... +def delete_multi_async(*args, **kwargs) -> None: ... + +class Error: + def __init__(self, *args, **kwargs) -> None: ... + +def fetch_data(*args, **kwargs) -> None: ... +def fetch_data_async(*args, **kwargs) -> None: ... + +get: Incomplete +get_async: Incomplete +get_multi: Incomplete +get_multi_async: Incomplete + +class InternalError: + def __init__(self, *args, **kwargs) -> None: ... + +def parse_blob_info(*args, **kwargs) -> None: ... + +class PermissionDeniedError: + def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi new file mode 100644 index 000000000000..d5893fc73ca6 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/client.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import ClassVar + +from google.cloud.ndb import context as context_module, key + +DATASTORE_API_HOST: str + +class Client: + SCOPE: ClassVar[tuple[str, ...]] + namespace: str | None + host: str + client_info: Incomplete + secure: bool + stub: Incomplete + database: str | None + def __init__( + self, + project: str | None = ..., + namespace: str | None = ..., + credentials: Incomplete | None = ..., + client_options: Incomplete | None = ..., + database: str | None = None, + ) -> None: ... + @contextmanager + def context( + self, + namespace=..., + cache_policy: Callable[[key.Key], bool] | None = ..., + global_cache: Incomplete | None = ..., + global_cache_policy: Callable[[key.Key], bool] | None = ..., + global_cache_timeout_policy: Callable[[key.Key], int] | None = ..., + legacy_data: bool = ..., + ) -> Generator[context_module.Context]: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi new file mode 100644 index 000000000000..e222fc32eacb --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/context.pyi @@ -0,0 +1,112 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import NamedTuple + +from google.cloud.ndb import Key, exceptions as exceptions + +class _LocalState: + def __init__(self) -> None: ... + + @property + def context(self): ... + @context.setter + def context(self, value) -> None: ... + + @property + def toplevel_context(self): ... + @toplevel_context.setter + def toplevel_context(self, value) -> None: ... + +def get_context(raise_context_error: bool = ...): ... +def get_toplevel_context(raise_context_error: bool = ...): ... + +class _ContextTuple(NamedTuple): + id: Incomplete + client: Incomplete + namespace: Incomplete + eventloop: Incomplete + batches: Incomplete + commit_batches: Incomplete + transaction: Incomplete + cache: Incomplete + global_cache: Incomplete + on_commit_callbacks: Incomplete + transaction_complete_callbacks: Incomplete + legacy_data: Incomplete + +class _Context(_ContextTuple): + def __new__( + cls, + client, + id: Incomplete | None = ..., + namespace=..., + eventloop: Incomplete | None = ..., + batches: Incomplete | None = ..., + commit_batches: Incomplete | None = ..., + transaction: Incomplete | None = ..., + cache: Incomplete | None = ..., + cache_policy: Incomplete | None = ..., + global_cache: Incomplete | None = ..., + global_cache_policy: Callable[[Key], bool] | None = ..., + global_cache_timeout_policy: Incomplete | None = ..., + datastore_policy: Incomplete | None = ..., + on_commit_callbacks: Incomplete | None = ..., + transaction_complete_callbacks: Incomplete | None = ..., + legacy_data: bool = ..., + retry: Incomplete | None = ..., + rpc_time: Incomplete | None = ..., + wait_time: Incomplete | None = ..., + ): ... + def new(self, **kwargs): ... + rpc_time: int + wait_time: int + def use(self) -> None: ... + +class Context(_Context): + def clear_cache(self) -> None: ... + def flush(self) -> None: ... + def get_namespace(self): ... + def get_cache_policy(self): ... + def get_datastore_policy(self) -> None: ... + def get_global_cache_policy(self): ... + get_memcache_policy: Incomplete + def get_global_cache_timeout_policy(self): ... + get_memcache_timeout_policy: Incomplete + cache_policy: Incomplete + def set_cache_policy(self, policy): ... + datastore_policy: Incomplete + def set_datastore_policy(self, policy): ... + global_cache_policy: Incomplete + def set_global_cache_policy(self, policy): ... + set_memcache_policy: Incomplete + global_cache_timeout_policy: Incomplete + def set_global_cache_timeout_policy(self, policy): ... + set_memcache_timeout_policy: Incomplete + def get_retry_state(self): ... + def set_retry_state(self, state) -> None: ... + def clear_retry_state(self) -> None: ... + def call_on_commit(self, callback) -> None: ... + def in_transaction(self): ... + def in_retry(self): ... + def memcache_add(self, *args, **kwargs) -> None: ... + def memcache_cas(self, *args, **kwargs) -> None: ... + def memcache_decr(self, *args, **kwargs) -> None: ... + def memcache_delete(self, *args, **kwargs) -> None: ... + def memcache_get(self, *args, **kwargs) -> None: ... + def memcache_gets(self, *args, **kwargs) -> None: ... + def memcache_incr(self, *args, **kwargs) -> None: ... + def memcache_replace(self, *args, **kwargs) -> None: ... + def memcache_set(self, *args, **kwargs) -> None: ... + def urlfetch(self, *args, **kwargs) -> None: ... + +class ContextOptions: + def __init__(self, *args, **kwargs) -> None: ... + +class TransactionOptions: + NESTED: int + MANDATORY: int + ALLOWED: int + INDEPENDENT: int + +class AutoBatcher: + def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/django_middleware.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/django_middleware.pyi new file mode 100644 index 000000000000..8d4c846e526d --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/django_middleware.pyi @@ -0,0 +1,2 @@ +class NdbDjangoMiddleware: + def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi new file mode 100644 index 000000000000..c575423699d3 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/exceptions.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +class Error(Exception): ... + +class ContextError(Error): + def __init__(self) -> None: ... + +class BadValueError(Error): ... +class BadArgumentError(Error): ... +class BadRequestError(Error): ... +class Rollback(Error): ... +class BadQueryError(Error): ... + +class BadFilterError(Error): + filter: Incomplete + def __init__(self, filter) -> None: ... + +class NoLongerImplementedError(NotImplementedError): + def __init__(self) -> None: ... + +class Cancelled(Error): ... +class NestedRetryException(Error): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi new file mode 100644 index 000000000000..aa91d31411cd --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/global_cache.pyi @@ -0,0 +1,77 @@ +import abc +from _typeshed import Incomplete +from typing_extensions import Self + +ConnectionError: Incomplete + +class GlobalCache(metaclass=abc.ABCMeta): + __metaclass__: Incomplete + transient_errors: Incomplete + strict_read: bool + strict_write: bool + @abc.abstractmethod + def get(self, keys): ... + @abc.abstractmethod + def set(self, items, expires: Incomplete | None = ...): ... + @abc.abstractmethod + def delete(self, keys): ... + @abc.abstractmethod + def watch(self, items): ... + @abc.abstractmethod + def unwatch(self, keys): ... + @abc.abstractmethod + def compare_and_swap(self, items, expires: Incomplete | None = ...): ... + @abc.abstractmethod + def clear(self): ... + +class _InProcessGlobalCache(GlobalCache): + cache: Incomplete + def __init__(self) -> None: ... + def get(self, keys): ... + def set(self, items, expires: Incomplete | None = ...) -> None: ... + def delete(self, keys) -> None: ... + def watch(self, items) -> None: ... + def unwatch(self, keys) -> None: ... + def compare_and_swap(self, items, expires: Incomplete | None = ...): ... + def clear(self) -> None: ... + +class RedisCache(GlobalCache): + transient_errors: Incomplete + @classmethod + def from_environment(cls, strict_read: bool = ..., strict_write: bool = ...) -> Self: ... + redis: Incomplete + strict_read: Incomplete + strict_write: Incomplete + def __init__(self, redis, strict_read: bool = ..., strict_write: bool = ...) -> None: ... + @property + def pipes(self): ... + def get(self, keys): ... + def set(self, items, expires: Incomplete | None = ...) -> None: ... + def delete(self, keys) -> None: ... + def watch(self, items) -> None: ... + def unwatch(self, keys) -> None: ... + def compare_and_swap(self, items, expires: Incomplete | None = ...): ... + def clear(self) -> None: ... + +class MemcacheCache(GlobalCache): + class KeyNotSet(Exception): + key: Incomplete + def __init__(self, key) -> None: ... + def __eq__(self, other): ... + + transient_errors: Incomplete + @classmethod + def from_environment(cls, max_pool_size: int = ..., strict_read: bool = ..., strict_write: bool = ...) -> Self: ... + client: Incomplete + strict_read: Incomplete + strict_write: Incomplete + def __init__(self, client, strict_read: bool = ..., strict_write: bool = ...) -> None: ... + @property + def caskeys(self): ... + def get(self, keys): ... + def set(self, items, expires: Incomplete | None = ...): ... + def delete(self, keys) -> None: ... + def watch(self, items) -> None: ... + def unwatch(self, keys) -> None: ... + def compare_and_swap(self, items, expires: Incomplete | None = ...): ... + def clear(self) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi new file mode 100644 index 000000000000..fde8894a3905 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/key.pyi @@ -0,0 +1,99 @@ +from _typeshed import Incomplete + +UNDEFINED: Incomplete + +class Key: + def __new__(cls, *path_args, **kwargs): ... + def __hash__(self) -> int: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __getnewargs__(self): ... + def parent(self): ... + def root(self): ... + def namespace(self): ... + def project(self): ... + app: Incomplete + def database(self) -> str | None: ... + def id(self): ... + def string_id(self): ... + def integer_id(self): ... + def pairs(self): ... + def flat(self): ... + def kind(self): ... + def reference(self): ... + def serialized(self): ... + def urlsafe(self): ... + def to_legacy_urlsafe(self, location_prefix): ... + def get( + self, + read_consistency: Incomplete | None = ..., + read_policy: Incomplete | None = ..., + transaction: Incomplete | None = ..., + retries: Incomplete | None = ..., + timeout: Incomplete | None = ..., + deadline: Incomplete | None = ..., + use_cache: Incomplete | None = ..., + use_global_cache: Incomplete | None = ..., + use_datastore: Incomplete | None = ..., + global_cache_timeout: Incomplete | None = ..., + use_memcache: Incomplete | None = ..., + memcache_timeout: Incomplete | None = ..., + max_memcache_items: Incomplete | None = ..., + force_writes: Incomplete | None = ..., + _options: Incomplete | None = ..., + ): ... + def get_async( + self, + read_consistency: Incomplete | None = ..., + read_policy: Incomplete | None = ..., + transaction: Incomplete | None = ..., + retries: Incomplete | None = ..., + timeout: Incomplete | None = ..., + deadline: Incomplete | None = ..., + use_cache: Incomplete | None = ..., + use_global_cache: Incomplete | None = ..., + use_datastore: Incomplete | None = ..., + global_cache_timeout: Incomplete | None = ..., + use_memcache: Incomplete | None = ..., + memcache_timeout: Incomplete | None = ..., + max_memcache_items: Incomplete | None = ..., + force_writes: Incomplete | None = ..., + _options: Incomplete | None = ..., + ): ... + def delete( + self, + retries: Incomplete | None = ..., + timeout: Incomplete | None = ..., + deadline: Incomplete | None = ..., + use_cache: Incomplete | None = ..., + use_global_cache: Incomplete | None = ..., + use_datastore: Incomplete | None = ..., + global_cache_timeout: Incomplete | None = ..., + use_memcache: Incomplete | None = ..., + memcache_timeout: Incomplete | None = ..., + max_memcache_items: Incomplete | None = ..., + force_writes: Incomplete | None = ..., + _options: Incomplete | None = ..., + ): ... + def delete_async( + self, + retries: Incomplete | None = ..., + timeout: Incomplete | None = ..., + deadline: Incomplete | None = ..., + use_cache: Incomplete | None = ..., + use_global_cache: Incomplete | None = ..., + use_datastore: Incomplete | None = ..., + global_cache_timeout: Incomplete | None = ..., + use_memcache: Incomplete | None = ..., + memcache_timeout: Incomplete | None = ..., + max_memcache_items: Incomplete | None = ..., + force_writes: Incomplete | None = ..., + _options: Incomplete | None = ..., + ): ... + @classmethod + def from_old_key(cls, old_key) -> None: ... + def to_old_key(self) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi new file mode 100644 index 000000000000..4e22eee3598f --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/metadata.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import model + +class _BaseMetadata(model.Model): + KIND_NAME: str + def __new__(cls, *args, **kwargs): ... + +class Namespace(_BaseMetadata): + KIND_NAME: str + EMPTY_NAMESPACE_ID: int + @property + def namespace_name(self): ... + @classmethod + def key_for_namespace(cls, namespace): ... + @classmethod + def key_to_namespace(cls, key): ... + +class Kind(_BaseMetadata): + KIND_NAME: str + @property + def kind_name(self): ... + @classmethod + def key_for_kind(cls, kind): ... + @classmethod + def key_to_kind(cls, key): ... + +class Property(_BaseMetadata): + KIND_NAME: str + @property + def property_name(self): ... + @property + def kind_name(self): ... + property_representation: Incomplete + @classmethod + def key_for_kind(cls, kind): ... + @classmethod + def key_for_property(cls, kind, property): ... + @classmethod + def key_to_kind(cls, key): ... + @classmethod + def key_to_property(cls, key): ... + +class EntityGroup: + def __new__(cls, *args, **kwargs): ... + +def get_entity_group_version(*args, **kwargs) -> None: ... +def get_kinds(start: Incomplete | None = ..., end: Incomplete | None = ...): ... +def get_namespaces(start: Incomplete | None = ..., end: Incomplete | None = ...): ... +def get_properties_of_kind(kind, start: Incomplete | None = ..., end: Incomplete | None = ...): ... +def get_representations_of_kind(kind, start: Incomplete | None = ..., end: Incomplete | None = ...): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi new file mode 100644 index 000000000000..54233f0ab42e --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi @@ -0,0 +1,516 @@ +import datetime +from _typeshed import Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, TypeAlias +from typing_extensions import Never, Self + +from google.cloud.ndb import exceptions, key as key_module, query as query_module, tasklets as tasklets_module + +Key = key_module.Key +Rollback = exceptions.Rollback +BlobKey: object +GeoPt: object + +class KindError(exceptions.BadValueError): ... +class InvalidPropertyError(exceptions.Error): ... + +BadProjectionError = InvalidPropertyError + +class UnprojectedPropertyError(exceptions.Error): ... +class ReadonlyPropertyError(exceptions.Error): ... +class ComputedPropertyError(ReadonlyPropertyError): ... +class UserNotFoundError(exceptions.Error): ... + +class _NotEqualMixin: + def __ne__(self, other: object) -> bool: ... + +_Direction: TypeAlias = Literal["asc", "desc"] + +class IndexProperty(_NotEqualMixin): + def __new__(cls, name: str, direction: _Direction) -> Self: ... + @property + def name(self) -> str: ... + @property + def direction(self) -> _Direction: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class Index(_NotEqualMixin): + def __new__(cls, kind: str, properties: list[IndexProperty], ancestor: bool) -> Self: ... + @property + def kind(self) -> str: ... + @property + def properties(self) -> list[IndexProperty]: ... + @property + def ancestor(self) -> bool: ... + def __eq__(self, other) -> bool: ... + def __hash__(self) -> int: ... + +class IndexState(_NotEqualMixin): + def __new__(cls, definition, state, id): ... + @property + def definition(self): ... + @property + def state(self): ... + @property + def id(self): ... + def __eq__(self, other) -> bool: ... + def __hash__(self) -> int: ... + +class ModelAdapter: + # This actually returns Never, but mypy can't handle that + def __new__(cls, *args, **kwargs) -> Self: ... + +def make_connection(*args, **kwargs) -> Never: ... + +class ModelAttribute: ... + +class _BaseValue(_NotEqualMixin): + b_val: object + def __init__(self, b_val) -> None: ... + def __eq__(self, other) -> bool: ... + def __hash__(self) -> int: ... + +class Property(ModelAttribute): + def __init__( + self, + name: str | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: object = None, + choices: Iterable[object] | None = ..., + validator: Callable[[Property, Any], object] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + def __eq__(self, value: object) -> query_module.FilterNode: ... # type: ignore[override] + def __ne__(self, value: object) -> query_module.FilterNode: ... # type: ignore[override] + def __lt__(self, value: object) -> query_module.FilterNode: ... + def __le__(self, value: object) -> query_module.FilterNode: ... + def __gt__(self, value: object) -> query_module.FilterNode: ... + def __ge__(self, value: object) -> query_module.FilterNode: ... + def IN( + self, value: Iterable[object], server_op: bool = False + ) -> query_module.DisjunctionNode | query_module.FilterNode | query_module.FalseNode: ... + def NOT_IN( + self, value: Iterable[object], server_op: bool = False + ) -> query_module.DisjunctionNode | query_module.FilterNode | query_module.FalseNode: ... + def __neg__(self) -> query_module.PropertyOrder: ... + def __pos__(self) -> query_module.PropertyOrder: ... + def __set__(self, entity: Model, value: object) -> None: ... + def __delete__(self, entity: Model) -> None: ... + +class ModelKey(Property): + def __init__(self) -> None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> key_module.Key | list[key_module.Key] | None: ... + +class BooleanProperty(Property): + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> bool | list[bool] | None: ... + +class IntegerProperty(Property): + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> int | list[int] | None: ... + +class FloatProperty(Property): + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> float | list[float] | None: ... + +class _CompressedValue(bytes): + z_val: bytes + def __init__(self, z_val: bytes) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> Never: ... + +class BlobProperty(Property): + def __init__( + self, + name: str | None = ..., + compressed: bool | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: bytes | None = ..., + choices: Iterable[bytes] | None = ..., + validator: Callable[[Property, Any], object] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> bytes | list[bytes] | None: ... + +class CompressedTextProperty(BlobProperty): + __slots__ = () + def __init__(self, *args, **kwargs) -> None: ... + +class TextProperty(Property): + def __new__(cls, *args, **kwargs): ... + def __init__(self, *args, **kwargs) -> None: ... + def __get__(self, entity: Model, unused_cls: type[Model] | None = ...) -> str | list[str] | None: ... + +class StringProperty(TextProperty): + def __init__(self, *args, **kwargs) -> None: ... + +class GeoPtProperty(Property): ... +class PickleProperty(BlobProperty): ... + +class JsonProperty(BlobProperty): + def __init__( + self, + name: str | None = ..., + compressed: bool | None = ..., + json_type: type | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: object = None, + choices: Iterable[object] | None = ..., + validator: Callable[[Property, Any], object] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + +class User: + def __init__(self, email: str | None = ..., _auth_domain: str | None = ..., _user_id: str | None = ...) -> None: ... + def nickname(self) -> str: ... + def email(self): ... + def user_id(self) -> str | None: ... + def auth_domain(self) -> str: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + +class UserProperty(Property): + def __init__( + self, + name: str | None = ..., + auto_current_user: bool | None = ..., + auto_current_user_add: bool | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: bytes | None = ..., + choices: Iterable[bytes] | None = ..., + validator: Callable[[Property, Any], object] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + +class KeyProperty(Property): + def __init__( + self, + name: str | None = ..., + kind: type[Model] | str | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: key_module.Key | None = ..., + choices: Iterable[key_module.Key] | None = ..., + validator: Callable[[Property, key_module.Key], key_module.Key] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + +class BlobKeyProperty(Property): ... + +class DateTimeProperty(Property): + def __init__( + self, + name: str | None = ..., + auto_now: bool | None = ..., + auto_now_add: bool | None = ..., + tzinfo: datetime.tzinfo | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + required: bool | None = ..., + default: datetime.datetime | None = ..., + choices: Iterable[datetime.datetime] | None = ..., + validator: Callable[[Property, Any], object] | None = ..., + verbose_name: str | None = ..., + write_empty_list: bool | None = ..., + ) -> None: ... + +class DateProperty(DateTimeProperty): ... +class TimeProperty(DateTimeProperty): ... + +class StructuredProperty(Property): + def __init__(self, model_class: type, name: str | None = ..., **kwargs) -> None: ... + def __getattr__(self, attrname: str): ... + def IN(self, value: Iterable[object]) -> query_module.DisjunctionNode | query_module.FalseNode: ... # type: ignore[override] + +class LocalStructuredProperty(BlobProperty): + def __init__(self, model_class: type[Model], **kwargs) -> None: ... + +class GenericProperty(Property): + def __init__(self, name: str | None = ..., compressed: bool = ..., **kwargs) -> None: ... + +class ComputedProperty(GenericProperty): + def __init__( + self, + func: Callable[[Model], object], + name: str | None = ..., + indexed: bool | None = ..., + repeated: bool | None = ..., + verbose_name: str | None = ..., + ) -> None: ... + +class MetaModel(type): + def __init__(cls, name: str, bases, classdict) -> None: ... + +class Model(_NotEqualMixin, metaclass=MetaModel): + key: ModelKey + def __init__(_self, **kwargs) -> None: ... + def __hash__(self) -> Never: ... + def __eq__(self, other: object) -> bool: ... + @classmethod + def gql(cls: type[Model], query_string: str, *args, **kwargs) -> query_module.Query: ... + def put(self, **kwargs): ... + def put_async(self, **kwargs) -> tasklets_module.Future: ... + @classmethod + def query(cls: type[Model], *args, **kwargs) -> query_module.Query: ... + @classmethod + def allocate_ids( + cls: type[Model], + size: int | None = ..., + max: int | None = ..., + parent: key_module.Key | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + ) -> tuple[key_module.Key, key_module.Key]: ... + @classmethod + def allocate_ids_async( + cls: type[Model], + size: int | None = ..., + max: int | None = ..., + parent: key_module.Key | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + ) -> tasklets_module.Future: ... + @classmethod + def get_by_id( + cls: type[Model], + id: int | str | None, + parent: key_module.Key | None = ..., + namespace: str | None = ..., + project: str | None = ..., + app: str | None = ..., + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + database: str | None = None, + ) -> Model | None: ... + @classmethod + def get_by_id_async( + cls: type[Model], + id: int | str, + parent: key_module.Key | None = ..., + namespace: str | None = ..., + project: str | None = ..., + app: str | None = ..., + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + database: str | None = None, + ) -> tasklets_module.Future: ... + @classmethod + def get_or_insert( + cls: type[Model], + _name: str, + parent: key_module.Key | None = ..., + namespace: str | None = ..., + project: str | None = ..., + app: str | None = ..., + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + **kw_model_args, + ) -> Model: ... + @classmethod + def get_or_insert_async( + cls: type[Model], + _name: str, + parent: key_module.Key | None = ..., + namespace: str | None = ..., + project: str | None = ..., + app: str | None = ..., + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options=..., + **kw_model_args, + ) -> tasklets_module.Future: ... + def populate(self, **kwargs) -> None: ... + def has_complete_key(self) -> bool: ... + def to_dict( + self, + include: list[object] | tuple[object, object] | set[object] | None = ..., + exclude: list[object] | tuple[object, object] | set[object] | None = ..., + ): ... + +class Expando(Model): + def __getattr__(self, name: str): ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + +def get_multi_async( + keys: Sequence[key_module.Key], + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[tasklets_module.Future]: ... +def get_multi( + keys: Sequence[key_module.Key], + read_consistency: Literal["EVENTUAL"] | None = ..., + read_policy: Literal["EVENTUAL"] | None = ..., + transaction: bytes | None = ..., + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[Model | None]: ... +def put_multi_async( + entities: list[Model], + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[tasklets_module.Future]: ... +def put_multi( + entities: list[Model], + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[key_module.Key]: ... +def delete_multi_async( + keys: Sequence[key_module.Key], + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[tasklets_module.Future]: ... +def delete_multi( + keys: Sequence[key_module.Key], + retries: int | None = ..., + timeout: float | None = ..., + deadline: float | None = ..., + use_cache: bool | None = ..., + use_global_cache: bool | None = ..., + global_cache_timeout: int | None = ..., + use_datastore: bool | None = ..., + use_memcache: bool | None = ..., + memcache_timeout: int | None = ..., + max_memcache_items: int | None = ..., + force_writes: bool | None = ..., + _options: object = None, +) -> list[None]: ... +def get_indexes_async(**options: Unused) -> Never: ... +def get_indexes(**options: Unused) -> Never: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/msgprop.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/msgprop.pyi new file mode 100644 index 000000000000..2bb3e67d8435 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/msgprop.pyi @@ -0,0 +1,5 @@ +class EnumProperty: + def __init__(self, *args, **kwargs) -> None: ... + +class MessageProperty: + def __init__(self, *args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi new file mode 100644 index 000000000000..29d9aa8b5f8a --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/polymodel.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import model + +class _ClassKeyProperty(model.StringProperty): + def __init__(self, name=..., indexed: bool = ...) -> None: ... + +class PolyModel(model.Model): + class_: Incomplete diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi new file mode 100644 index 000000000000..4f926d6ad8c2 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/query.pyi @@ -0,0 +1,167 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import _options + +class PropertyOrder: + name: Incomplete + reverse: Incomplete + def __init__(self, name, reverse: bool = ...) -> None: ... + def __neg__(self): ... + +class RepeatedStructuredPropertyPredicate: + name: Incomplete + match_keys: Incomplete + match_values: Incomplete + def __init__(self, name, match_keys, entity_pb) -> None: ... + def __call__(self, entity_pb): ... + +class ParameterizedThing: + def __eq__(self, other): ... + def __ne__(self, other): ... + +class Parameter(ParameterizedThing): + def __init__(self, key) -> None: ... + def __eq__(self, other): ... + @property + def key(self): ... + def resolve(self, bindings, used): ... + +class ParameterizedFunction(ParameterizedThing): + func: Incomplete + values: Incomplete + def __init__(self, func, values) -> None: ... + def __eq__(self, other): ... + def is_parameterized(self): ... + def resolve(self, bindings, used): ... + +class Node: + def __new__(cls): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __le__(self, unused_other): ... + def __lt__(self, unused_other): ... + def __ge__(self, unused_other): ... + def __gt__(self, unused_other): ... + def resolve(self, bindings, used): ... + +class FalseNode(Node): + def __eq__(self, other): ... + +class ParameterNode(Node): + def __new__(cls, prop, op, param): ... + def __getnewargs__(self): ... + def __eq__(self, other): ... + def resolve(self, bindings, used): ... + +class FilterNode(Node): + def __new__(cls, name, opsymbol, value, server_op: bool = False): ... + def __getnewargs__(self): ... + def __eq__(self, other): ... + +class PostFilterNode(Node): + def __new__(cls, predicate): ... + def __getnewargs__(self): ... + def __eq__(self, other): ... + +class _BooleanClauses: + name: Incomplete + combine_or: Incomplete + or_parts: Incomplete + def __init__(self, name, combine_or) -> None: ... + def add_node(self, node) -> None: ... + +class ConjunctionNode(Node): + def __new__(cls, *nodes): ... + def __getnewargs__(self): ... + def __iter__(self): ... + def __eq__(self, other): ... + def resolve(self, bindings, used): ... + +class DisjunctionNode(Node): + def __new__(cls, *nodes): ... + def __getnewargs__(self): ... + def __iter__(self): ... + def __eq__(self, other): ... + def resolve(self, bindings, used): ... + +AND = ConjunctionNode +OR = DisjunctionNode + +class QueryOptions(_options.ReadOptions): + __slots__ = ( + "kind", + "ancestor", + "filters", + "order_by", + "orders", + "distinct_on", + "group_by", + "namespace", + "project", + "database", + "keys_only", + "limit", + "offset", + "start_cursor", + "end_cursor", + "projection", + "callback", + ) + project: Incomplete + namespace: Incomplete + database: str | None + def __init__(self, config: Incomplete | None = ..., context: Incomplete | None = ..., **kwargs) -> None: ... + +class Query: + default_options: Incomplete + kind: Incomplete + ancestor: Incomplete + filters: Incomplete + order_by: Incomplete + project: Incomplete + namespace: Incomplete + limit: Incomplete + offset: Incomplete + keys_only: Incomplete + projection: Incomplete + distinct_on: Incomplete + database: str | None + def __init__( + self, + kind: Incomplete | None = ..., + filters: Incomplete | None = ..., + ancestor: Incomplete | None = ..., + order_by: Incomplete | None = ..., + orders: Incomplete | None = ..., + project: Incomplete | None = ..., + app: Incomplete | None = ..., + namespace: Incomplete | None = ..., + projection: Incomplete | None = ..., + distinct_on: Incomplete | None = ..., + group_by: Incomplete | None = ..., + limit: Incomplete | None = ..., + offset: Incomplete | None = ..., + keys_only: Incomplete | None = ..., + default_options: Incomplete | None = ..., + ) -> None: ... + @property + def is_distinct(self): ... + def filter(self, *filters): ... + def order(self, *props): ... + def analyze(self): ... + def bind(self, *positional, **keyword): ... + def fetch(self, limit: Incomplete | None = ..., **kwargs): ... + def fetch_async(self, limit: Incomplete | None = ..., **kwargs): ... + def run_to_queue(self, queue, conn, options: Incomplete | None = ..., dsquery: Incomplete | None = ...) -> None: ... + def iter(self, **kwargs): ... + __iter__: Incomplete + def map(self, callback, **kwargs): ... + def map_async(self, callback, **kwargs) -> None: ... + def get(self, **kwargs): ... + def get_async(self, **kwargs) -> None: ... + def count(self, limit: Incomplete | None = ..., **kwargs): ... + def count_async(self, limit: Incomplete | None = ..., **kwargs): ... + def fetch_page(self, page_size, **kwargs): ... + def fetch_page_async(self, page_size, **kwargs) -> None: ... + +def gql(query_string: str, *args, **kwds) -> Query: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi new file mode 100644 index 000000000000..7dfaaa5c7042 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/stats.pyi @@ -0,0 +1,102 @@ +from _typeshed import Incomplete + +from google.cloud.ndb import model + +class BaseStatistic(model.Model): + STORED_KIND_NAME: str + bytes: Incomplete + count: Incomplete + timestamp: Incomplete + +class BaseKindStatistic(BaseStatistic): + STORED_KIND_NAME: str + kind_name: Incomplete + entity_bytes: Incomplete + +class GlobalStat(BaseStatistic): + STORED_KIND_NAME: str + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete + +class NamespaceStat(BaseStatistic): + STORED_KIND_NAME: str + subject_namespace: Incomplete + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete + +class KindStat(BaseKindStatistic): + STORED_KIND_NAME: str + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + composite_index_bytes: Incomplete + composite_index_count: Incomplete + +class KindRootEntityStat(BaseKindStatistic): + STORED_KIND_NAME: str + +class KindNonRootEntityStat(BaseKindStatistic): + STORED_KIND_NAME: str + +class PropertyTypeStat(BaseStatistic): + STORED_KIND_NAME: str + property_type: Incomplete + entity_bytes: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + +class KindPropertyTypeStat(BaseKindStatistic): + STORED_KIND_NAME: str + property_type: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + +class KindPropertyNameStat(BaseKindStatistic): + STORED_KIND_NAME: str + property_name: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + +class KindPropertyNamePropertyTypeStat(BaseKindStatistic): + STORED_KIND_NAME: str + property_type: Incomplete + property_name: Incomplete + builtin_index_bytes: Incomplete + builtin_index_count: Incomplete + +class KindCompositeIndexStat(BaseStatistic): + STORED_KIND_NAME: str + index_id: Incomplete + kind_name: Incomplete + +class NamespaceGlobalStat(GlobalStat): + STORED_KIND_NAME: str + +class NamespaceKindStat(KindStat): + STORED_KIND_NAME: str + +class NamespaceKindRootEntityStat(KindRootEntityStat): + STORED_KIND_NAME: str + +class NamespaceKindNonRootEntityStat(KindNonRootEntityStat): + STORED_KIND_NAME: str + +class NamespacePropertyTypeStat(PropertyTypeStat): + STORED_KIND_NAME: str + +class NamespaceKindPropertyTypeStat(KindPropertyTypeStat): + STORED_KIND_NAME: str + +class NamespaceKindPropertyNameStat(KindPropertyNameStat): + STORED_KIND_NAME: str + +class NamespaceKindPropertyNamePropertyTypeStat(KindPropertyNamePropertyTypeStat): + STORED_KIND_NAME: str + +class NamespaceKindCompositeIndexStat(KindCompositeIndexStat): + STORED_KIND_NAME: str diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi new file mode 100644 index 000000000000..8788f40f6c16 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/tasklets.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete + +class Future: + info: Incomplete + def __init__(self, info: str = ...) -> None: ... + def done(self): ... + def running(self): ... + def wait(self) -> None: ... + def check_success(self) -> None: ... + def set_result(self, result) -> None: ... + def set_exception(self, exception) -> None: ... + def result(self): ... + get_result: Incomplete + def exception(self): ... + get_exception: Incomplete + def get_traceback(self): ... + def add_done_callback(self, callback) -> None: ... + def cancel(self) -> None: ... + def cancelled(self): ... + @staticmethod + def wait_any(futures): ... + @staticmethod + def wait_all(futures): ... + +class _TaskletFuture(Future): + generator: Incomplete + context: Incomplete + waiting_on: Incomplete + def __init__(self, generator, context, info: str = ...) -> None: ... + def cancel(self) -> None: ... + +class _MultiFuture(Future): + def __init__(self, dependencies) -> None: ... + def cancel(self) -> None: ... + +def tasklet(wrapped): ... +def wait_any(futures): ... +def wait_all(futures) -> None: ... + +class Return(Exception): ... + +def sleep(seconds): ... +def add_flow_exception(*args, **kwargs) -> None: ... +def make_context(*args, **kwargs) -> None: ... +def make_default_context(*args, **kwargs) -> None: ... + +class QueueFuture: + def __init__(self, *args, **kwargs) -> None: ... + +class ReducingFuture: + def __init__(self, *args, **kwargs) -> None: ... + +class SerialQueueFuture: + def __init__(self, *args, **kwargs) -> None: ... + +def set_context(*args, **kwargs) -> None: ... +def synctasklet(wrapped): ... +def toplevel(wrapped): ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi new file mode 100644 index 000000000000..ccc5ca208d88 --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/utils.pyi @@ -0,0 +1,28 @@ +import threading +from _typeshed import Incomplete + +TRUTHY_STRINGS: Incomplete + +def asbool(value): ... + +DEBUG: Incomplete + +def code_info(*args, **kwargs) -> None: ... +def decorator(*args, **kwargs) -> None: ... +def frame_info(*args, **kwargs) -> None: ... +def func_info(*args, **kwargs) -> None: ... +def gen_info(*args, **kwargs) -> None: ... +def get_stack(*args, **kwargs) -> None: ... +def logging_debug(log, message, *args, **kwargs) -> None: ... + +class keyword_only: + defaults: Incomplete + def __init__(self, **kwargs) -> None: ... + def __call__(self, wrapped): ... + +def positional(max_pos_args): ... + +threading_local = threading.local + +def tweak_logging(*args, **kwargs) -> None: ... +def wrapping(*args, **kwargs) -> None: ... diff --git a/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi b/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/google-cloud-ndb/google/cloud/ndb/version.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/greenlet/@tests/stubtest_allowlist.txt b/stubs/greenlet/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..38d2d056903f --- /dev/null +++ b/stubs/greenlet/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Error: is not present in stub +# ============================= +# this module only contains C code and exports no Python code, so it's better +# if we pretend it doesn't exist +greenlet.platform +# the tests should not be part of the modules +greenlet.tests diff --git a/stubs/greenlet/@tests/test_cases/check_greenlet.py b/stubs/greenlet/@tests/test_cases/check_greenlet.py new file mode 100644 index 000000000000..976772d1775c --- /dev/null +++ b/stubs/greenlet/@tests/test_cases/check_greenlet.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from typing import Optional +from typing_extensions import assert_type + +import greenlet + +g = greenlet.greenlet() +h = greenlet.greenlet() +assert_type(g.parent, Optional[greenlet.greenlet]) +g.parent = h + +# Although "parent" sometimes can be None at runtime, +# it's always illegal for it to be set to None +g.parent = None # type: ignore diff --git a/stubs/greenlet/METADATA.toml b/stubs/greenlet/METADATA.toml new file mode 100644 index 000000000000..5677f8261f6b --- /dev/null +++ b/stubs/greenlet/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.5.*" +upstream-repository = "https://github.com/python-greenlet/greenlet" diff --git a/stubs/greenlet/greenlet/__init__.pyi b/stubs/greenlet/greenlet/__init__.pyi new file mode 100644 index 000000000000..903fc6f31c70 --- /dev/null +++ b/stubs/greenlet/greenlet/__init__.pyi @@ -0,0 +1,14 @@ +from typing import Final + +from ._greenlet import ( + _C_API as _C_API, + GreenletExit as GreenletExit, + error as error, + getcurrent as getcurrent, + gettrace as gettrace, + greenlet as greenlet, + settrace as settrace, +) + +__version__: Final[str] +__all__ = ["__version__", "_C_API", "GreenletExit", "error", "getcurrent", "greenlet", "gettrace", "settrace"] diff --git a/stubs/greenlet/greenlet/_greenlet.pyi b/stubs/greenlet/greenlet/_greenlet.pyi new file mode 100644 index 000000000000..09c4cb22ec8f --- /dev/null +++ b/stubs/greenlet/greenlet/_greenlet.pyi @@ -0,0 +1,90 @@ +import sys +from collections.abc import Callable +from contextvars import Context +from types import FrameType, TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import disjoint_base + +_TraceEvent: TypeAlias = Literal["switch", "throw"] +_TraceCallback: TypeAlias = Callable[[_TraceEvent, tuple[greenlet, greenlet]], object] + +CLOCKS_PER_SEC: int +GREENLET_USE_CONTEXT_VARS: bool +GREENLET_USE_GC: bool +GREENLET_USE_STANDARD_THREADING: bool +GREENLET_USE_TRACING: bool +# this is a PyCapsule, it may be used to pass the gevent C-API to another C-extension +# there isn't a runtime type for this, since it's only an opaque wrapper around void* +# but it's probably still better than pretending it doesn't exist, so people that need +# to pass this around, can still pass it around without having to ignore type errors... +_C_API: object + +@type_check_only +class _ParentDescriptor(Protocol): + def __get__(self, obj: greenlet, owner: type[greenlet] | None = None) -> greenlet | None: ... + def __set__(self, obj: greenlet, value: greenlet) -> None: ... + +class GreenletExit(BaseException): ... +class error(Exception): ... + +@disjoint_base +class greenlet: + @property + def dead(self) -> bool: ... + + @property + def gr_context(self) -> Context | None: ... + @gr_context.setter + def gr_context(self, value: Context | None) -> None: ... + + @property + def gr_frame(self) -> FrameType | None: ... + # the parent attribute is a bit special, since it can't be set to `None` manually, but + # it can be `None` for the master greenlet which will always be around, regardless of + # how many greenlets have been spawned explicitly. Since there can only be one such + # greenlet per thread, there is no way to create another one manually. + parent: _ParentDescriptor + + @property + def run(self) -> Callable[..., Any]: ... + @run.setter + def run(self, value: Callable[..., Any]) -> None: ... + + def __init__(self, run: Callable[..., Any] | None = None, parent: greenlet | None = None) -> None: ... + def switch(self, *args: Any, **kwargs: Any) -> Any: ... + + @overload + def throw( + self, typ: type[BaseException] = ..., val: BaseException | object = None, tb: TracebackType | None = None, / + ) -> Any: ... + @overload + def throw(self, typ: BaseException = ..., val: None = None, tb: TracebackType | None = None, /) -> Any: ... + + def __bool__(self) -> bool: ... + + # aliases for some module attributes/methods + GreenletExit: type[GreenletExit] + error: type[error] + @staticmethod + def getcurrent() -> greenlet: ... + @staticmethod + def gettrace() -> _TraceCallback | None: ... + @staticmethod + def settrace(callback: _TraceCallback | None, /) -> _TraceCallback | None: ... + +class UnswitchableGreenlet(greenlet): # undocumented + force_switch_error: bool + force_slp_switch_error: bool + +def enable_optional_cleanup(enabled: bool, /) -> None: ... +def get_clocks_used_doing_optional_cleanup() -> int: ... +def get_pending_cleanup_count() -> int: ... +def get_total_main_greenlets() -> int: ... + +if sys.version_info < (3, 13): + def get_tstate_trash_delete_nesting() -> int: ... + +def getcurrent() -> greenlet: ... +def gettrace() -> _TraceCallback | None: ... +def set_thread_local(key: object, value: object, /) -> None: ... +def settrace(callback: _TraceCallback | None, /) -> _TraceCallback | None: ... diff --git a/stubs/grpcio-channelz/METADATA.toml b/stubs/grpcio-channelz/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-channelz/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stubs/grpcio-channelz/grpc_channelz/__init__.pyi b/stubs/grpcio-channelz/grpc_channelz/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/__init__.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi new file mode 100644 index 000000000000..87aa2bf125d1 --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/_async.pyi @@ -0,0 +1,19 @@ +from grpc_channelz.v1 import channelz_pb2, channelz_pb2_grpc + +class ChannelzServicer(channelz_pb2_grpc.ChannelzServicer): + @staticmethod + async def GetTopChannels(request: channelz_pb2.GetTopChannelsRequest, context) -> channelz_pb2.GetTopChannelsResponse: ... + @staticmethod + async def GetServers(request: channelz_pb2.GetServersRequest, context) -> channelz_pb2.GetServersResponse: ... + @staticmethod + async def GetServer(request: channelz_pb2.GetServerRequest, context) -> channelz_pb2.GetServerResponse: ... + @staticmethod + async def GetServerSockets( + request: channelz_pb2.GetServerSocketsRequest, context + ) -> channelz_pb2.GetServerSocketsResponse: ... + @staticmethod + async def GetChannel(request: channelz_pb2.GetChannelRequest, context) -> channelz_pb2.GetChannelResponse: ... + @staticmethod + async def GetSubchannel(request: channelz_pb2.GetSubchannelRequest, context) -> channelz_pb2.GetSubchannelResponse: ... + @staticmethod + async def GetSocket(request: channelz_pb2.GetSocketRequest, context) -> channelz_pb2.GetSocketResponse: ... diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi new file mode 100644 index 000000000000..f8b7ba089b47 --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/_servicer.pyi @@ -0,0 +1,25 @@ +import grpc_channelz.v1.channelz_pb2 as _channelz_pb2 +import grpc_channelz.v1.channelz_pb2_grpc as _channelz_pb2_grpc +from grpc import ServicerContext + +class ChannelzServicer(_channelz_pb2_grpc.ChannelzServicer): + @staticmethod + def GetTopChannels( + request: _channelz_pb2.GetTopChannelsRequest, context: ServicerContext + ) -> _channelz_pb2.GetTopChannelsResponse: ... + @staticmethod + def GetServers(request: _channelz_pb2.GetServersRequest, context: ServicerContext) -> _channelz_pb2.GetServersResponse: ... + @staticmethod + def GetServer(request: _channelz_pb2.GetServerRequest, context: ServicerContext) -> _channelz_pb2.GetServerResponse: ... + @staticmethod + def GetServerSockets( + request: _channelz_pb2.GetServerSocketsRequest, context: ServicerContext + ) -> _channelz_pb2.GetServerSocketsResponse: ... + @staticmethod + def GetChannel(request: _channelz_pb2.GetChannelRequest, context: ServicerContext) -> _channelz_pb2.GetChannelResponse: ... + @staticmethod + def GetSubchannel( + request: _channelz_pb2.GetSubchannelRequest, context: ServicerContext + ) -> _channelz_pb2.GetSubchannelResponse: ... + @staticmethod + def GetSocket(request: _channelz_pb2.GetSocketRequest, context: ServicerContext) -> _channelz_pb2.GetSocketResponse: ... diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi new file mode 100644 index 000000000000..2ed61fd4fa3a --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz.pyi @@ -0,0 +1,6 @@ +from grpc_channelz.v1 import _async as aio +from grpc_channelz.v1._servicer import ChannelzServicer + +def add_channelz_servicer(server) -> None: ... + +__all__ = ["aio", "add_channelz_servicer", "ChannelzServicer"] diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi new file mode 100644 index 000000000000..262fa0f3f89c --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2.pyi @@ -0,0 +1,604 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import any_pb2, duration_pb2, message, timestamp_pb2, wrappers_pb2 +from google.protobuf.internal import containers + +DESCRIPTOR: FileDescriptor + +@final +class Channel(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + ref: ChannelRef + data: ChannelData + channel_ref: containers.RepeatedCompositeFieldContainer[ChannelRef] + subchannel_ref: containers.RepeatedCompositeFieldContainer[SubchannelRef] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: ChannelRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ChannelData | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: Iterable[ChannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + subchannel_ref: Iterable[SubchannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Subchannel(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + ref: SubchannelRef + data: ChannelData + channel_ref: containers.RepeatedCompositeFieldContainer[ChannelRef] + subchannel_ref: containers.RepeatedCompositeFieldContainer[SubchannelRef] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: SubchannelRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ChannelData | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: Iterable[ChannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + subchannel_ref: Iterable[SubchannelRef | Mapping[Incomplete, Incomplete]] | None = ..., + socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelConnectivityState(message.Message, metaclass=MessageMeta): + State: Incomplete + UNKNOWN: Incomplete + IDLE: Incomplete + CONNECTING: Incomplete + READY: Incomplete + TRANSIENT_FAILURE: Incomplete + SHUTDOWN: Incomplete + STATE_FIELD_NUMBER: ClassVar[int] + state: Incomplete + def __init__(self, state: Incomplete | str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelData(message.Message, metaclass=MessageMeta): + STATE_FIELD_NUMBER: ClassVar[int] + TARGET_FIELD_NUMBER: ClassVar[int] + TRACE_FIELD_NUMBER: ClassVar[int] + CALLS_STARTED_FIELD_NUMBER: ClassVar[int] + CALLS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + CALLS_FAILED_FIELD_NUMBER: ClassVar[int] + LAST_CALL_STARTED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + state: ChannelConnectivityState + target: str + trace: ChannelTrace + calls_started: int + calls_succeeded: int + calls_failed: int + last_call_started_timestamp: timestamp_pb2.Timestamp + def __init__( + self, + state: ChannelConnectivityState | Mapping[Incomplete, Incomplete] | None = ..., + target: str | None = ..., + trace: ChannelTrace | Mapping[Incomplete, Incomplete] | None = ..., + calls_started: int | None = ..., + calls_succeeded: int | None = ..., + calls_failed: int | None = ..., + last_call_started_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelTraceEvent(message.Message, metaclass=MessageMeta): + Severity: Incomplete + CT_UNKNOWN: Incomplete + CT_INFO: Incomplete + CT_WARNING: Incomplete + CT_ERROR: Incomplete + DESCRIPTION_FIELD_NUMBER: ClassVar[int] + SEVERITY_FIELD_NUMBER: ClassVar[int] + TIMESTAMP_FIELD_NUMBER: ClassVar[int] + CHANNEL_REF_FIELD_NUMBER: ClassVar[int] + SUBCHANNEL_REF_FIELD_NUMBER: ClassVar[int] + description: str + severity: Incomplete + timestamp: timestamp_pb2.Timestamp + channel_ref: ChannelRef + subchannel_ref: SubchannelRef + def __init__( + self, + description: str | None = ..., + severity: Incomplete | str | None = ..., + timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + channel_ref: ChannelRef | Mapping[Incomplete, Incomplete] | None = ..., + subchannel_ref: SubchannelRef | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelTrace(message.Message, metaclass=MessageMeta): + NUM_EVENTS_LOGGED_FIELD_NUMBER: ClassVar[int] + CREATION_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + EVENTS_FIELD_NUMBER: ClassVar[int] + num_events_logged: int + creation_timestamp: timestamp_pb2.Timestamp + events: containers.RepeatedCompositeFieldContainer[ChannelTraceEvent] + def __init__( + self, + num_events_logged: int | None = ..., + creation_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + events: Iterable[ChannelTraceEvent | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ChannelRef(message.Message, metaclass=MessageMeta): + CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + channel_id: int + name: str + def __init__(self, channel_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SubchannelRef(message.Message, metaclass=MessageMeta): + SUBCHANNEL_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + subchannel_id: int + name: str + def __init__(self, subchannel_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketRef(message.Message, metaclass=MessageMeta): + SOCKET_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + socket_id: int + name: str + def __init__(self, socket_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerRef(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + NAME_FIELD_NUMBER: ClassVar[int] + server_id: int + name: str + def __init__(self, server_id: int | None = ..., name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Server(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + LISTEN_SOCKET_FIELD_NUMBER: ClassVar[int] + ref: ServerRef + data: ServerData + listen_socket: containers.RepeatedCompositeFieldContainer[SocketRef] + def __init__( + self, + ref: ServerRef | Mapping[Incomplete, Incomplete] | None = ..., + data: ServerData | Mapping[Incomplete, Incomplete] | None = ..., + listen_socket: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerData(message.Message, metaclass=MessageMeta): + TRACE_FIELD_NUMBER: ClassVar[int] + CALLS_STARTED_FIELD_NUMBER: ClassVar[int] + CALLS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + CALLS_FAILED_FIELD_NUMBER: ClassVar[int] + LAST_CALL_STARTED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + trace: ChannelTrace + calls_started: int + calls_succeeded: int + calls_failed: int + last_call_started_timestamp: timestamp_pb2.Timestamp + def __init__( + self, + trace: ChannelTrace | Mapping[Incomplete, Incomplete] | None = ..., + calls_started: int | None = ..., + calls_succeeded: int | None = ..., + calls_failed: int | None = ..., + last_call_started_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Socket(message.Message, metaclass=MessageMeta): + REF_FIELD_NUMBER: ClassVar[int] + DATA_FIELD_NUMBER: ClassVar[int] + LOCAL_FIELD_NUMBER: ClassVar[int] + REMOTE_FIELD_NUMBER: ClassVar[int] + SECURITY_FIELD_NUMBER: ClassVar[int] + REMOTE_NAME_FIELD_NUMBER: ClassVar[int] + ref: SocketRef + data: SocketData + local: Address + remote: Address + security: Security + remote_name: str + def __init__( + self, + ref: SocketRef | Mapping[Incomplete, Incomplete] | None = ..., + data: SocketData | Mapping[Incomplete, Incomplete] | None = ..., + local: Address | Mapping[Incomplete, Incomplete] | None = ..., + remote: Address | Mapping[Incomplete, Incomplete] | None = ..., + security: Security | Mapping[Incomplete, Incomplete] | None = ..., + remote_name: str | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketData(message.Message, metaclass=MessageMeta): + STREAMS_STARTED_FIELD_NUMBER: ClassVar[int] + STREAMS_SUCCEEDED_FIELD_NUMBER: ClassVar[int] + STREAMS_FAILED_FIELD_NUMBER: ClassVar[int] + MESSAGES_SENT_FIELD_NUMBER: ClassVar[int] + MESSAGES_RECEIVED_FIELD_NUMBER: ClassVar[int] + KEEP_ALIVES_SENT_FIELD_NUMBER: ClassVar[int] + LAST_LOCAL_STREAM_CREATED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_REMOTE_STREAM_CREATED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_MESSAGE_SENT_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LAST_MESSAGE_RECEIVED_TIMESTAMP_FIELD_NUMBER: ClassVar[int] + LOCAL_FLOW_CONTROL_WINDOW_FIELD_NUMBER: ClassVar[int] + REMOTE_FLOW_CONTROL_WINDOW_FIELD_NUMBER: ClassVar[int] + OPTION_FIELD_NUMBER: ClassVar[int] + streams_started: int + streams_succeeded: int + streams_failed: int + messages_sent: int + messages_received: int + keep_alives_sent: int + last_local_stream_created_timestamp: timestamp_pb2.Timestamp + last_remote_stream_created_timestamp: timestamp_pb2.Timestamp + last_message_sent_timestamp: timestamp_pb2.Timestamp + last_message_received_timestamp: timestamp_pb2.Timestamp + local_flow_control_window: wrappers_pb2.Int64Value + remote_flow_control_window: wrappers_pb2.Int64Value + option: containers.RepeatedCompositeFieldContainer[SocketOption] + def __init__( + self, + streams_started: int | None = ..., + streams_succeeded: int | None = ..., + streams_failed: int | None = ..., + messages_sent: int | None = ..., + messages_received: int | None = ..., + keep_alives_sent: int | None = ..., + last_local_stream_created_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_remote_stream_created_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_message_sent_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + last_message_received_timestamp: timestamp_pb2.Timestamp | Mapping[Incomplete, Incomplete] | None = ..., + local_flow_control_window: wrappers_pb2.Int64Value | Mapping[Incomplete, Incomplete] | None = ..., + remote_flow_control_window: wrappers_pb2.Int64Value | Mapping[Incomplete, Incomplete] | None = ..., + option: Iterable[SocketOption | Mapping[Incomplete, Incomplete]] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Address(message.Message, metaclass=MessageMeta): + @final + class TcpIpAddress(message.Message, metaclass=MessageMeta): + IP_ADDRESS_FIELD_NUMBER: ClassVar[int] + PORT_FIELD_NUMBER: ClassVar[int] + ip_address: bytes + port: int + def __init__(self, ip_address: bytes | None = ..., port: int | None = ...) -> None: ... + + @final + class UdsAddress(message.Message, metaclass=MessageMeta): + FILENAME_FIELD_NUMBER: ClassVar[int] + filename: str + def __init__(self, filename: str | None = ...) -> None: ... + + @final + class OtherAddress(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + name: str + value: any_pb2.Any + def __init__(self, name: str | None = ..., value: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + + TCPIP_ADDRESS_FIELD_NUMBER: ClassVar[int] + UDS_ADDRESS_FIELD_NUMBER: ClassVar[int] + OTHER_ADDRESS_FIELD_NUMBER: ClassVar[int] + tcpip_address: Address.TcpIpAddress + uds_address: Address.UdsAddress + other_address: Address.OtherAddress + def __init__( + self, + tcpip_address: Address.TcpIpAddress | Mapping[Incomplete, Incomplete] | None = ..., + uds_address: Address.UdsAddress | Mapping[Incomplete, Incomplete] | None = ..., + other_address: Address.OtherAddress | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class Security(message.Message, metaclass=MessageMeta): + @final + class Tls(message.Message, metaclass=MessageMeta): + STANDARD_NAME_FIELD_NUMBER: ClassVar[int] + OTHER_NAME_FIELD_NUMBER: ClassVar[int] + LOCAL_CERTIFICATE_FIELD_NUMBER: ClassVar[int] + REMOTE_CERTIFICATE_FIELD_NUMBER: ClassVar[int] + standard_name: str + other_name: str + local_certificate: bytes + remote_certificate: bytes + def __init__( + self, + standard_name: str | None = ..., + other_name: str | None = ..., + local_certificate: bytes | None = ..., + remote_certificate: bytes | None = ..., + ) -> None: ... + + @final + class OtherSecurity(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + name: str + value: any_pb2.Any + def __init__(self, name: str | None = ..., value: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + + TLS_FIELD_NUMBER: ClassVar[int] + OTHER_FIELD_NUMBER: ClassVar[int] + tls: Security.Tls + other: Security.OtherSecurity + def __init__( + self, + tls: Security.Tls | Mapping[Incomplete, Incomplete] | None = ..., + other: Security.OtherSecurity | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOption(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + VALUE_FIELD_NUMBER: ClassVar[int] + ADDITIONAL_FIELD_NUMBER: ClassVar[int] + name: str + value: str + additional: any_pb2.Any + def __init__( + self, + name: str | None = ..., + value: str | None = ..., + additional: any_pb2.Any | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionTimeout(message.Message, metaclass=MessageMeta): + DURATION_FIELD_NUMBER: ClassVar[int] + duration: duration_pb2.Duration + def __init__(self, duration: duration_pb2.Duration | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionLinger(message.Message, metaclass=MessageMeta): + ACTIVE_FIELD_NUMBER: ClassVar[int] + DURATION_FIELD_NUMBER: ClassVar[int] + active: bool + duration: duration_pb2.Duration + def __init__( + self, active: bool = ..., duration: duration_pb2.Duration | Mapping[Incomplete, Incomplete] | None = ... + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class SocketOptionTcpInfo(message.Message, metaclass=MessageMeta): + TCPI_STATE_FIELD_NUMBER: ClassVar[int] + TCPI_CA_STATE_FIELD_NUMBER: ClassVar[int] + TCPI_RETRANSMITS_FIELD_NUMBER: ClassVar[int] + TCPI_PROBES_FIELD_NUMBER: ClassVar[int] + TCPI_BACKOFF_FIELD_NUMBER: ClassVar[int] + TCPI_OPTIONS_FIELD_NUMBER: ClassVar[int] + TCPI_SND_WSCALE_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_WSCALE_FIELD_NUMBER: ClassVar[int] + TCPI_RTO_FIELD_NUMBER: ClassVar[int] + TCPI_ATO_FIELD_NUMBER: ClassVar[int] + TCPI_SND_MSS_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_MSS_FIELD_NUMBER: ClassVar[int] + TCPI_UNACKED_FIELD_NUMBER: ClassVar[int] + TCPI_SACKED_FIELD_NUMBER: ClassVar[int] + TCPI_LOST_FIELD_NUMBER: ClassVar[int] + TCPI_RETRANS_FIELD_NUMBER: ClassVar[int] + TCPI_FACKETS_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_DATA_SENT_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_ACK_SENT_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_DATA_RECV_FIELD_NUMBER: ClassVar[int] + TCPI_LAST_ACK_RECV_FIELD_NUMBER: ClassVar[int] + TCPI_PMTU_FIELD_NUMBER: ClassVar[int] + TCPI_RCV_SSTHRESH_FIELD_NUMBER: ClassVar[int] + TCPI_RTT_FIELD_NUMBER: ClassVar[int] + TCPI_RTTVAR_FIELD_NUMBER: ClassVar[int] + TCPI_SND_SSTHRESH_FIELD_NUMBER: ClassVar[int] + TCPI_SND_CWND_FIELD_NUMBER: ClassVar[int] + TCPI_ADVMSS_FIELD_NUMBER: ClassVar[int] + TCPI_REORDERING_FIELD_NUMBER: ClassVar[int] + tcpi_state: int + tcpi_ca_state: int + tcpi_retransmits: int + tcpi_probes: int + tcpi_backoff: int + tcpi_options: int + tcpi_snd_wscale: int + tcpi_rcv_wscale: int + tcpi_rto: int + tcpi_ato: int + tcpi_snd_mss: int + tcpi_rcv_mss: int + tcpi_unacked: int + tcpi_sacked: int + tcpi_lost: int + tcpi_retrans: int + tcpi_fackets: int + tcpi_last_data_sent: int + tcpi_last_ack_sent: int + tcpi_last_data_recv: int + tcpi_last_ack_recv: int + tcpi_pmtu: int + tcpi_rcv_ssthresh: int + tcpi_rtt: int + tcpi_rttvar: int + tcpi_snd_ssthresh: int + tcpi_snd_cwnd: int + tcpi_advmss: int + tcpi_reordering: int + def __init__( + self, + tcpi_state: int | None = ..., + tcpi_ca_state: int | None = ..., + tcpi_retransmits: int | None = ..., + tcpi_probes: int | None = ..., + tcpi_backoff: int | None = ..., + tcpi_options: int | None = ..., + tcpi_snd_wscale: int | None = ..., + tcpi_rcv_wscale: int | None = ..., + tcpi_rto: int | None = ..., + tcpi_ato: int | None = ..., + tcpi_snd_mss: int | None = ..., + tcpi_rcv_mss: int | None = ..., + tcpi_unacked: int | None = ..., + tcpi_sacked: int | None = ..., + tcpi_lost: int | None = ..., + tcpi_retrans: int | None = ..., + tcpi_fackets: int | None = ..., + tcpi_last_data_sent: int | None = ..., + tcpi_last_ack_sent: int | None = ..., + tcpi_last_data_recv: int | None = ..., + tcpi_last_ack_recv: int | None = ..., + tcpi_pmtu: int | None = ..., + tcpi_rcv_ssthresh: int | None = ..., + tcpi_rtt: int | None = ..., + tcpi_rttvar: int | None = ..., + tcpi_snd_ssthresh: int | None = ..., + tcpi_snd_cwnd: int | None = ..., + tcpi_advmss: int | None = ..., + tcpi_reordering: int | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetTopChannelsRequest(message.Message, metaclass=MessageMeta): + START_CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + start_channel_id: int + max_results: int + def __init__(self, start_channel_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetTopChannelsResponse(message.Message, metaclass=MessageMeta): + CHANNEL_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + channel: containers.RepeatedCompositeFieldContainer[Channel] + end: bool + def __init__(self, channel: Iterable[Channel | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServersRequest(message.Message, metaclass=MessageMeta): + START_SERVER_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + start_server_id: int + max_results: int + def __init__(self, start_server_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServersResponse(message.Message, metaclass=MessageMeta): + SERVER_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + server: containers.RepeatedCompositeFieldContainer[Server] + end: bool + def __init__(self, server: Iterable[Server | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerRequest(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + server_id: int + def __init__(self, server_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerResponse(message.Message, metaclass=MessageMeta): + SERVER_FIELD_NUMBER: ClassVar[int] + server: Server + def __init__(self, server: Server | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerSocketsRequest(message.Message, metaclass=MessageMeta): + SERVER_ID_FIELD_NUMBER: ClassVar[int] + START_SOCKET_ID_FIELD_NUMBER: ClassVar[int] + MAX_RESULTS_FIELD_NUMBER: ClassVar[int] + server_id: int + start_socket_id: int + max_results: int + def __init__(self, server_id: int | None = ..., start_socket_id: int | None = ..., max_results: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetServerSocketsResponse(message.Message, metaclass=MessageMeta): + SOCKET_REF_FIELD_NUMBER: ClassVar[int] + END_FIELD_NUMBER: ClassVar[int] + socket_ref: containers.RepeatedCompositeFieldContainer[SocketRef] + end: bool + def __init__( + self, socket_ref: Iterable[SocketRef | Mapping[Incomplete, Incomplete]] | None = ..., end: bool = ... + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetChannelRequest(message.Message, metaclass=MessageMeta): + CHANNEL_ID_FIELD_NUMBER: ClassVar[int] + channel_id: int + def __init__(self, channel_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetChannelResponse(message.Message, metaclass=MessageMeta): + CHANNEL_FIELD_NUMBER: ClassVar[int] + channel: Channel + def __init__(self, channel: Channel | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSubchannelRequest(message.Message, metaclass=MessageMeta): + SUBCHANNEL_ID_FIELD_NUMBER: ClassVar[int] + subchannel_id: int + def __init__(self, subchannel_id: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSubchannelResponse(message.Message, metaclass=MessageMeta): + SUBCHANNEL_FIELD_NUMBER: ClassVar[int] + subchannel: Subchannel + def __init__(self, subchannel: Subchannel | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSocketRequest(message.Message, metaclass=MessageMeta): + SOCKET_ID_FIELD_NUMBER: ClassVar[int] + SUMMARY_FIELD_NUMBER: ClassVar[int] + socket_id: int + summary: bool + def __init__(self, socket_id: int | None = ..., summary: bool = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class GetSocketResponse(message.Message, metaclass=MessageMeta): + SOCKET_FIELD_NUMBER: ClassVar[int] + socket: Socket + def __init__(self, socket: Socket | Mapping[Incomplete, Incomplete] | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi new file mode 100644 index 000000000000..bd6f78fecf4d --- /dev/null +++ b/stubs/grpcio-channelz/grpc_channelz/v1/channelz_pb2_grpc.pyi @@ -0,0 +1,121 @@ +from _typeshed import Incomplete +from typing import Final + +import grpc + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class ChannelzStub: + GetTopChannels: Incomplete + GetServers: Incomplete + GetServer: Incomplete + GetServerSockets: Incomplete + GetChannel: Incomplete + GetSubchannel: Incomplete + GetSocket: Incomplete + def __init__(self, channel: grpc.Channel): ... + +class ChannelzServicer: + def GetTopChannels(self, request, context): ... + def GetServers(self, request, context): ... + def GetServer(self, request, context): ... + def GetServerSockets(self, request, context): ... + def GetChannel(self, request, context): ... + def GetSubchannel(self, request, context): ... + def GetSocket(self, request, context): ... + +def add_ChannelzServicer_to_server(servicer, server) -> None: ... + +class Channelz: + @staticmethod + def GetTopChannels( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServers( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServer( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetServerSockets( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetChannel( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetSubchannel( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def GetSocket( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-health-checking/METADATA.toml b/stubs/grpcio-health-checking/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-health-checking/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stubs/grpcio-health-checking/grpc_health/__init__.pyi b/stubs/grpcio-health-checking/grpc_health/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-health-checking/grpc_health/v1/__init__.pyi b/stubs/grpcio-health-checking/grpc_health/v1/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health.pyi new file mode 100644 index 000000000000..e98ffdbcd980 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from concurrent import futures +from typing import Final, overload +from typing_extensions import Self + +from grpc import ServicerContext +from grpc_health.v1 import health_pb2, health_pb2_grpc + +SERVICE_NAME: Final[str] +OVERALL_HEALTH: Final[str] + +class _Watcher: + def __init__(self) -> None: ... + def __iter__(self) -> Self: ... + def next(self) -> health_pb2.HealthCheckResponse: ... + def __next__(self) -> health_pb2.HealthCheckResponse: ... + def add(self, response: health_pb2.HealthCheckResponse) -> None: ... + def close(self) -> None: ... + +class HealthServicer(health_pb2_grpc.HealthServicer): + def __init__( + self, experimental_non_blocking: bool = True, experimental_thread_pool: futures.ThreadPoolExecutor | None = None + ) -> None: ... + def Check(self, request: health_pb2.HealthCheckRequest, context: ServicerContext) -> health_pb2.HealthCheckResponse: ... + + @overload + def Watch( + self, request: health_pb2.HealthCheckRequest, context: ServicerContext, send_response_callback: None = None + ) -> _Watcher: ... + @overload + def Watch( + self, request: health_pb2.HealthCheckRequest, context: ServicerContext, send_response_callback: Callable[..., Incomplete] + ) -> None: ... + + def set(self, service: str, status: health_pb2.HealthCheckResponse.ServingStatus) -> None: ... + def enter_graceful_shutdown(self) -> None: ... diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi new file mode 100644 index 000000000000..82191f79b659 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import message + +DESCRIPTOR: FileDescriptor + +@final +class HealthCheckRequest(message.Message, metaclass=MessageMeta): + SERVICE_FIELD_NUMBER: ClassVar[int] + service: str + def __init__(self, service: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class HealthCheckResponse(message.Message, metaclass=MessageMeta): + ServingStatus: Incomplete + UNKNOWN: Incomplete + SERVING: Incomplete + NOT_SERVING: Incomplete + SERVICE_UNKNOWN: Incomplete + STATUS_FIELD_NUMBER: ClassVar[int] + status: Incomplete + def __init__(self, status: Incomplete | str | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi new file mode 100644 index 000000000000..8170664f0cb1 --- /dev/null +++ b/stubs/grpcio-health-checking/grpc_health/v1/health_pb2_grpc.pyi @@ -0,0 +1,41 @@ +from typing import Final + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class HealthStub: + def __init__(self, channel) -> None: ... + +class HealthServicer: + def Check(self, request, context): ... + def Watch(self, request, context): ... + +def add_HealthServicer_to_server(servicer, server) -> None: ... + +class Health: + @staticmethod + def Check( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... + @staticmethod + def Watch( + request, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py b/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py new file mode 100644 index 000000000000..5287283960a8 --- /dev/null +++ b/stubs/grpcio-reflection/@tests/test_cases/check_reflection.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from typing import cast + +import grpc +from grpc_reflection.v1alpha.reflection import enable_server_reflection + +server = cast(grpc.Server, None) +enable_server_reflection(["foo"], server, None) diff --git a/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py b/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py new file mode 100644 index 000000000000..80d4054cc123 --- /dev/null +++ b/stubs/grpcio-reflection/@tests/test_cases/check_reflection_aio.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from typing import cast + +import grpc.aio +from grpc_reflection.v1alpha.reflection import enable_server_reflection + +server = cast(grpc.aio.Server, None) +enable_server_reflection(["foo"], server, None) diff --git a/stubs/grpcio-reflection/METADATA.toml b/stubs/grpcio-reflection/METADATA.toml new file mode 100644 index 000000000000..b12e58c39175 --- /dev/null +++ b/stubs/grpcio-reflection/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio", "types-protobuf"] diff --git a/stubs/grpcio-reflection/grpc_reflection/__init__.pyi b/stubs/grpcio-reflection/grpc_reflection/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/__init__.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi new file mode 100644 index 000000000000..39fa94fe1d91 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_async.pyi @@ -0,0 +1,11 @@ +from collections.abc import AsyncIterable + +from grpc_reflection.v1alpha import reflection_pb2 +from grpc_reflection.v1alpha._base import BaseReflectionServicer + +class ReflectionServicer(BaseReflectionServicer): + async def ServerReflectionInfo( + self, request_iterator: AsyncIterable[reflection_pb2.ServerReflectionRequest], unused_context + ) -> AsyncIterable[reflection_pb2.ServerReflectionResponse]: ... + +__all__ = ["ReflectionServicer"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi new file mode 100644 index 000000000000..e808f4a9147a --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/_base.pyi @@ -0,0 +1,6 @@ +from grpc_reflection.v1alpha import reflection_pb2_grpc + +class BaseReflectionServicer(reflection_pb2_grpc.ServerReflectionServicer): + def __init__(self, service_names, pool=None) -> None: ... + +__all__ = ["BaseReflectionServicer"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi new file mode 100644 index 000000000000..e41b1edb0bab --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/proto_reflection_descriptor_database.pyi @@ -0,0 +1,11 @@ +import grpc +from google.protobuf.descriptor_database import DescriptorDatabase +from google.protobuf.descriptor_pb2 import FileDescriptorProto + +class ProtoReflectionDescriptorDatabase(DescriptorDatabase): + def __init__(self, channel: grpc.Channel) -> None: ... + def get_services(self) -> list[str]: ... + def FindFileByName(self, name: str) -> FileDescriptorProto: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptorProto: ... + def FindAllExtensionNumbers(self, extendee_name: str) -> list[int]: ... + def FindFileContainingExtension(self, extendee_name: str, extension_number: int) -> FileDescriptorProto: ... diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi new file mode 100644 index 000000000000..0c00500de3a7 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Final, TypeAlias + +import grpc +import grpc.aio +from google.protobuf import descriptor_pool +from grpc_reflection.v1alpha import reflection_pb2 as _reflection_pb2 +from grpc_reflection.v1alpha._base import BaseReflectionServicer + +from . import _async as aio + +SERVICE_NAME: Final[str] + +_AnyServer: TypeAlias = grpc.Server | grpc.aio.Server +_AnyServicerContext: TypeAlias = grpc.ServicerContext | grpc.aio.ServicerContext[Incomplete, Incomplete] + +class ReflectionServicer(BaseReflectionServicer): + def ServerReflectionInfo( + self, request_iterator: Iterable[_reflection_pb2.ServerReflectionRequest], context: _AnyServicerContext + ): ... + +def enable_server_reflection( + service_names: Iterable[str], server: _AnyServer, pool: descriptor_pool.DescriptorPool | None = None +) -> None: ... + +__all__ = ["SERVICE_NAME", "ReflectionServicer", "enable_server_reflection", "aio"] diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi new file mode 100644 index 000000000000..94f335771385 --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from typing import ClassVar, final + +from google._upb._message import Descriptor, FileDescriptor, MessageMeta +from google.protobuf import message +from google.protobuf.internal import containers + +DESCRIPTOR: FileDescriptor + +@final +class ServerReflectionRequest(message.Message, metaclass=MessageMeta): + HOST_FIELD_NUMBER: ClassVar[int] + FILE_BY_FILENAME_FIELD_NUMBER: ClassVar[int] + FILE_CONTAINING_SYMBOL_FIELD_NUMBER: ClassVar[int] + FILE_CONTAINING_EXTENSION_FIELD_NUMBER: ClassVar[int] + ALL_EXTENSION_NUMBERS_OF_TYPE_FIELD_NUMBER: ClassVar[int] + LIST_SERVICES_FIELD_NUMBER: ClassVar[int] + host: str + file_by_filename: str + file_containing_symbol: str + file_containing_extension: ExtensionRequest + all_extension_numbers_of_type: str + list_services: str + def __init__( + self, + host: str | None = ..., + file_by_filename: str | None = ..., + file_containing_symbol: str | None = ..., + file_containing_extension: ExtensionRequest | Mapping[Incomplete, Incomplete] | None = ..., + all_extension_numbers_of_type: str | None = ..., + list_services: str | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ExtensionRequest(message.Message, metaclass=MessageMeta): + CONTAINING_TYPE_FIELD_NUMBER: ClassVar[int] + EXTENSION_NUMBER_FIELD_NUMBER: ClassVar[int] + containing_type: str + extension_number: int + def __init__(self, containing_type: str | None = ..., extension_number: int | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServerReflectionResponse(message.Message, metaclass=MessageMeta): + VALID_HOST_FIELD_NUMBER: ClassVar[int] + ORIGINAL_REQUEST_FIELD_NUMBER: ClassVar[int] + FILE_DESCRIPTOR_RESPONSE_FIELD_NUMBER: ClassVar[int] + ALL_EXTENSION_NUMBERS_RESPONSE_FIELD_NUMBER: ClassVar[int] + LIST_SERVICES_RESPONSE_FIELD_NUMBER: ClassVar[int] + ERROR_RESPONSE_FIELD_NUMBER: ClassVar[int] + valid_host: str + original_request: ServerReflectionRequest + file_descriptor_response: FileDescriptorResponse + all_extension_numbers_response: ExtensionNumberResponse + list_services_response: ListServiceResponse + error_response: ErrorResponse + def __init__( + self, + valid_host: str | None = ..., + original_request: ServerReflectionRequest | Mapping[Incomplete, Incomplete] | None = ..., + file_descriptor_response: FileDescriptorResponse | Mapping[Incomplete, Incomplete] | None = ..., + all_extension_numbers_response: ExtensionNumberResponse | Mapping[Incomplete, Incomplete] | None = ..., + list_services_response: ListServiceResponse | Mapping[Incomplete, Incomplete] | None = ..., + error_response: ErrorResponse | Mapping[Incomplete, Incomplete] | None = ..., + ) -> None: ... + DESCRIPTOR: Descriptor + +@final +class FileDescriptorResponse(message.Message, metaclass=MessageMeta): + FILE_DESCRIPTOR_PROTO_FIELD_NUMBER: ClassVar[int] + file_descriptor_proto: containers.RepeatedScalarFieldContainer[bytes] + def __init__(self, file_descriptor_proto: Iterable[bytes] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ExtensionNumberResponse(message.Message, metaclass=MessageMeta): + BASE_TYPE_NAME_FIELD_NUMBER: ClassVar[int] + EXTENSION_NUMBER_FIELD_NUMBER: ClassVar[int] + base_type_name: str + extension_number: containers.RepeatedScalarFieldContainer[int] + def __init__(self, base_type_name: str | None = ..., extension_number: Iterable[int] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ListServiceResponse(message.Message, metaclass=MessageMeta): + SERVICE_FIELD_NUMBER: ClassVar[int] + service: containers.RepeatedCompositeFieldContainer[ServiceResponse] + def __init__(self, service: Iterable[ServiceResponse | Mapping[Incomplete, Incomplete]] | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ServiceResponse(message.Message, metaclass=MessageMeta): + NAME_FIELD_NUMBER: ClassVar[int] + name: str + def __init__(self, name: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor + +@final +class ErrorResponse(message.Message, metaclass=MessageMeta): + ERROR_CODE_FIELD_NUMBER: ClassVar[int] + ERROR_MESSAGE_FIELD_NUMBER: ClassVar[int] + error_code: int + error_message: str + def __init__(self, error_code: int | None = ..., error_message: str | None = ...) -> None: ... + DESCRIPTOR: Descriptor diff --git a/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi new file mode 100644 index 000000000000..31b983b4f82c --- /dev/null +++ b/stubs/grpcio-reflection/grpc_reflection/v1alpha/reflection_pb2_grpc.pyi @@ -0,0 +1,31 @@ +from binascii import Incomplete +from typing import Final + +import grpc + +GRPC_GENERATED_VERSION: Final[str] +GRPC_VERSION: Final[str] + +class ServerReflectionStub: + ServerReflectionInfo: Incomplete + def __init__(self, channel: grpc.Channel) -> None: ... + +class ServerReflectionServicer: + def ServerReflectionInfo(self, request_iterator, context): ... + +def add_ServerReflectionServicer_to_server(servicer, server): ... + +class ServerReflection: + @staticmethod + def ServerReflectionInfo( + request_iterator, + target, + options=(), + channel_credentials=None, + call_credentials=None, + insecure=False, + compression=None, + wait_for_ready=None, + timeout=None, + metadata=None, + ): ... diff --git a/stubs/grpcio-status/METADATA.toml b/stubs/grpcio-status/METADATA.toml new file mode 100644 index 000000000000..3591441645d2 --- /dev/null +++ b/stubs/grpcio-status/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.*" +upstream-repository = "https://github.com/grpc/grpc" +dependencies = ["types-grpcio"] diff --git a/stubs/grpcio-status/grpc_status/__init__.pyi b/stubs/grpcio-status/grpc_status/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/grpcio-status/grpc_status/_async.pyi b/stubs/grpcio-status/grpc_status/_async.pyi new file mode 100644 index 000000000000..a636b3f59f20 --- /dev/null +++ b/stubs/grpcio-status/grpc_status/_async.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +async def from_call(call) -> Incomplete | None: ... + +__all__ = ["from_call"] diff --git a/stubs/grpcio-status/grpc_status/rpc_status.pyi b/stubs/grpcio-status/grpc_status/rpc_status.pyi new file mode 100644 index 000000000000..e2e0204167f5 --- /dev/null +++ b/stubs/grpcio-status/grpc_status/rpc_status.pyi @@ -0,0 +1,11 @@ +import grpc + +from . import _async as aio + +# Returns a google.rpc.status.Status message corresponding to a given grpc.Call. +def from_call(call: grpc.Call): ... + +# Convert a google.rpc.status.Status message to grpc.Status. +def to_status(status) -> grpc.Status: ... + +__all__ = ["from_call", "to_status", "aio"] diff --git a/stubs/grpcio/@tests/stubtest_allowlist.txt b/stubs/grpcio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3409137cfdce --- /dev/null +++ b/stubs/grpcio/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Error: is not present at runtime +# ============================= +# Error class attributes that aren't defined. +grpc.RpcError.code +grpc.RpcError.details +grpc.RpcError.trailing_metadata diff --git a/stubs/grpcio/@tests/test_cases/check_aio.py b/stubs/grpcio/@tests/test_cases/check_aio.py new file mode 100644 index 000000000000..f76a34987cb5 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_aio.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +from typing import cast +from typing_extensions import assert_type + +import grpc.aio + +# Interceptor casts +client_interceptors: list[grpc.aio.ClientInterceptor] = [] +grpc.aio.insecure_channel("target", interceptors=client_interceptors) + +server_interceptors: list[grpc.aio.ServerInterceptor] = [] +grpc.aio.server(interceptors=server_interceptors) + + +# Metadata +async def metadata() -> None: + metadata = await cast(grpc.aio.Call, None).initial_metadata() + assert_type(metadata["foo"], grpc.aio._MetadataValue) + # grpc.aio.Metadata is a Collection that iterates as (key, value) tuples, + # not a Mapping that iterates bare keys. + for key, value in metadata: + assert_type(key, str) + assert_type(value, grpc.aio._MetadataValue) diff --git a/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py b/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py new file mode 100644 index 000000000000..36fb5870380b --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_aio_multi_callable.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Protocol, cast +from typing_extensions import assert_type + +import grpc.aio + + +class DummyRequest: + pass + + +class DummyReply: + pass + + +class DummyServiceStub(Protocol): + UnaryUnary: grpc.aio.UnaryUnaryMultiCallable[DummyRequest, DummyReply] + UnaryStream: grpc.aio.UnaryStreamMultiCallable[DummyRequest, DummyReply] + StreamUnary: grpc.aio.StreamUnaryMultiCallable[DummyRequest, DummyReply] + StreamStream: grpc.aio.StreamStreamMultiCallable[DummyRequest, DummyReply] + + +stub = cast(DummyServiceStub, None) +req = DummyRequest() + + +async def async_context() -> None: + assert_type(await stub.UnaryUnary(req), DummyReply) + + async for resp in stub.UnaryStream(req): + assert_type(resp, DummyReply) + + assert_type(await stub.StreamUnary(iter([req])), DummyReply) + + async for resp in stub.StreamStream(iter([req])): + assert_type(resp, DummyReply) diff --git a/stubs/grpcio/@tests/test_cases/check_grpc.py b/stubs/grpcio/@tests/test_cases/check_grpc.py new file mode 100644 index 000000000000..4ff365685afc --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_grpc.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import Optional, cast +from typing_extensions import assert_type + +import grpc + +# Channel options: +assert_type(grpc.insecure_channel("target", ()), grpc.Channel) +assert_type(grpc.insecure_channel("target", (("a", "b"),)), grpc.Channel) +assert_type(grpc.insecure_channel("target", (("a", "b"), ("c", "d"))), grpc.Channel) + +# Local channel credentials: +creds = grpc.local_channel_credentials(grpc.LocalConnectionType.LOCAL_TCP) +assert_type(creds, grpc.ChannelCredentials) + +# Other credential types: +assert_type(grpc.alts_channel_credentials(), grpc.ChannelCredentials) +assert_type(grpc.alts_server_credentials(), grpc.ServerCredentials) +assert_type(grpc.compute_engine_channel_credentials(grpc.CallCredentials("")), grpc.ChannelCredentials) +assert_type(grpc.insecure_server_credentials(), grpc.ServerCredentials) + +# XDS credentials: +assert_type( + grpc.xds_channel_credentials(grpc.local_channel_credentials(grpc.LocalConnectionType.LOCAL_TCP)), grpc.ChannelCredentials +) +assert_type(grpc.xds_server_credentials(grpc.insecure_server_credentials()), grpc.ServerCredentials) + +# Channel ready future +channel = grpc.insecure_channel("target", ()) +assert_type(grpc.channel_ready_future(channel).result(), None) + +# Channel options supports list: +assert_type(grpc.insecure_channel("target", []), grpc.Channel) +assert_type(grpc.insecure_channel("target", [("a", "b")]), grpc.Channel) +assert_type(grpc.insecure_channel("target", [("a", "b"), ("c", "d")]), grpc.Channel) + +# Client call details optionals: +call_details = grpc.ClientCallDetails() +assert_type(call_details.method, str) +assert_type(call_details.timeout, Optional[float]) + +# Call iterator +call_iter = cast(grpc._CallIterator[str], None) +for call in call_iter: + assert_type(call, str) +assert_type(next(call_iter), str) diff --git a/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py b/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py new file mode 100644 index 000000000000..ce74855fa76d --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_handler_inheritance.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import Any, cast +from typing_extensions import assert_type + +import grpc + + +class Request: + pass + + +class Response: + pass + + +def unary_unary_call(rq: Request, ctx: grpc.ServicerContext) -> Response: + assert_type(rq, Request) + return Response() + + +class ServiceHandler(grpc.ServiceRpcHandler): + def service_name(self) -> str: + return "hello" + + def service(self, handler_call_details: grpc.HandlerCallDetails) -> grpc.RpcMethodHandler[Any, Any] | None: + rpc = grpc.RpcMethodHandler[Request, Response]() + rpc.unary_unary = unary_unary_call + return rpc + + +h = ServiceHandler() +hcd = cast(grpc.HandlerCallDetails, None) +ctx = cast(grpc.ServicerContext, None) +svc = h.service(hcd) +if svc is not None and svc.unary_unary is not None: + svc.unary_unary(Request(), ctx) diff --git a/stubs/grpcio/@tests/test_cases/check_multi_callable.py b/stubs/grpcio/@tests/test_cases/check_multi_callable.py new file mode 100644 index 000000000000..254d60b2a228 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_multi_callable.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import Protocol, cast +from typing_extensions import assert_type + +import grpc + + +class DummyRequest: + pass + + +class DummyReply: + pass + + +class DummyServiceStub(Protocol): + UnaryUnary: grpc.UnaryUnaryMultiCallable[DummyRequest, DummyReply] + UnaryStream: grpc.UnaryStreamMultiCallable[DummyRequest, DummyReply] + StreamUnary: grpc.StreamUnaryMultiCallable[DummyRequest, DummyReply] + StreamStream: grpc.StreamStreamMultiCallable[DummyRequest, DummyReply] + + +stub = cast(DummyServiceStub, None) +req = DummyRequest() + +assert_type(stub.UnaryUnary(req), DummyReply) + +for resp in stub.UnaryStream(req): + assert_type(resp, DummyReply) + +assert_type(stub.StreamUnary(iter([req])), DummyReply) + +for resp in stub.StreamStream(iter([req])): + assert_type(resp, DummyReply) diff --git a/stubs/grpcio/@tests/test_cases/check_register.py b/stubs/grpcio/@tests/test_cases/check_register.py new file mode 100644 index 000000000000..b68daa523e7a --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_register.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from typing import Any + +import grpc + + +@grpc.Call.register +class CallProxy: + def __init__(self, target: grpc.Call) -> None: + self._target = target + + def __getattr__(self, name: str) -> Any: + return getattr(self._target, name) diff --git a/stubs/grpcio/@tests/test_cases/check_server_interceptor.py b/stubs/grpcio/@tests/test_cases/check_server_interceptor.py new file mode 100644 index 000000000000..893ff591fb52 --- /dev/null +++ b/stubs/grpcio/@tests/test_cases/check_server_interceptor.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from collections.abc import Callable +from concurrent.futures.thread import ThreadPoolExecutor +from typing import Awaitable, TypeVar + +import grpc +import grpc.aio + +RequestT = TypeVar("RequestT") +ResponseT = TypeVar("ResponseT") + + +class NoopInterceptor(grpc.ServerInterceptor): + def intercept_service( + self, + continuation: Callable[[grpc.HandlerCallDetails], grpc.RpcMethodHandler[RequestT, ResponseT] | None], + handler_call_details: grpc.HandlerCallDetails, + ) -> grpc.RpcMethodHandler[RequestT, ResponseT] | None: + return continuation(handler_call_details) + + +grpc.server(interceptors=[NoopInterceptor()], thread_pool=ThreadPoolExecutor()) + + +class NoopAioInterceptor(grpc.aio.ServerInterceptor): + async def intercept_service( + self, + continuation: Callable[[grpc.HandlerCallDetails], Awaitable[grpc.RpcMethodHandler[RequestT, ResponseT] | None]], + handler_call_details: grpc.HandlerCallDetails, + ) -> grpc.RpcMethodHandler[RequestT, ResponseT] | None: + return await continuation(handler_call_details) + + +grpc.aio.server(interceptors=[NoopAioInterceptor()]) diff --git a/stubs/grpcio/METADATA.toml b/stubs/grpcio/METADATA.toml new file mode 100644 index 000000000000..83fb9bd9533b --- /dev/null +++ b/stubs/grpcio/METADATA.toml @@ -0,0 +1,6 @@ +version = "~= 1.83.0" +upstream-repository = "https://github.com/grpc/grpc" +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/grpcio/grpc/__init__.pyi b/stubs/grpcio/grpc/__init__.pyi new file mode 100644 index 000000000000..bd0210796ec4 --- /dev/null +++ b/stubs/grpcio/grpc/__init__.pyi @@ -0,0 +1,611 @@ +import abc +import enum +import threading +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from concurrent import futures +from types import ModuleType, TracebackType +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, runtime_checkable, type_check_only +from typing_extensions import Never, Self + +from . import aio as aio + +__version__: str + +_T = TypeVar("_T") + +# XXX: Early attempts to tame this used literals for all the keys (gRPC is +# a bit segfaulty and doesn't adequately validate the option keys), but that +# didn't quite work out. Maybe it's something we can come back to +_OptionKeyValue: TypeAlias = tuple[str, Any] +_Options: TypeAlias = Sequence[_OptionKeyValue] + +class Compression(enum.IntEnum): + NoCompression = 0 + Deflate = 1 + Gzip = 2 + +@enum.unique +class LocalConnectionType(enum.Enum): + UDS = 0 + LOCAL_TCP = 1 + +# XXX: not documented, needs more investigation. +# Some evidence: +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_metadata_test.py#L71 +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_metadata_test.py#L58 +# - https://github.com/grpc/grpc/blob/0e1984effd7e977ef18f1ad7fde7d10a2a153e1d/src/python/grpcio_tests/tests/unit/_invocation_defects_test.py#L66 +_Metadata: TypeAlias = tuple[tuple[str, str | bytes], ...] + +_TRequest = TypeVar("_TRequest") +_TResponse = TypeVar("_TResponse") +_Serializer: TypeAlias = Callable[[_T], bytes] +_Deserializer: TypeAlias = Callable[[bytes], _T] + +# Future Interfaces: + +class FutureTimeoutError(Exception): ... +class FutureCancelledError(Exception): ... + +_TFutureValue = TypeVar("_TFutureValue") + +class Future(abc.ABC, Generic[_TFutureValue]): + @abc.abstractmethod + def add_done_callback(self, fn: Callable[[Future[_TFutureValue]], None]) -> None: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def cancelled(self) -> bool: ... + @abc.abstractmethod + def done(self) -> bool: ... + @abc.abstractmethod + def exception(self, timeout: float | None = None) -> Exception | None: ... + @abc.abstractmethod + def result(self, timeout: float | None = None) -> _TFutureValue: ... + @abc.abstractmethod + def running(self) -> bool: ... + + # FIXME: unsure of the exact return type here. Is it a traceback.StackSummary? + @abc.abstractmethod + def traceback(self, timeout: float | None = None): ... + +# Create Client: + +def insecure_channel(target: str, options: _Options | None = None, compression: Compression | None = None) -> Channel: ... +def secure_channel( + target: str, credentials: ChannelCredentials, options: _Options | None = None, compression: Compression | None = None +) -> Channel: ... + +_Interceptor: TypeAlias = ( + UnaryUnaryClientInterceptor | UnaryStreamClientInterceptor | StreamUnaryClientInterceptor | StreamStreamClientInterceptor +) + +def intercept_channel(channel: Channel, *interceptors: _Interceptor) -> Channel: ... + +# Create Client Credentials: + +def ssl_channel_credentials( + root_certificates: bytes | None = None, private_key: bytes | None = None, certificate_chain: bytes | None = None +) -> ChannelCredentials: ... +def local_channel_credentials(local_connect_type: LocalConnectionType = ...) -> ChannelCredentials: ... +def metadata_call_credentials(metadata_plugin: AuthMetadataPlugin, name: str | None = None) -> CallCredentials: ... +def access_token_call_credentials(access_token: str) -> CallCredentials: ... +def alts_channel_credentials(service_accounts: Sequence[str] | None = None) -> ChannelCredentials: ... +def compute_engine_channel_credentials(call_credentials: CallCredentials) -> ChannelCredentials: ... +def xds_channel_credentials(fallback_credentials: ChannelCredentials | None = None) -> ChannelCredentials: ... + +# GRPC docs say there should be at least two: +def composite_call_credentials(creds1: CallCredentials, creds2: CallCredentials, *rest: CallCredentials) -> CallCredentials: ... + +# Compose a ChannelCredentials and one or more CallCredentials objects. +def composite_channel_credentials( + channel_credentials: ChannelCredentials, call_credentials: CallCredentials, *rest: CallCredentials +) -> ChannelCredentials: ... + +# Create Server: + +def server( + thread_pool: futures.ThreadPoolExecutor, + handlers: list[GenericRpcHandler] | None = None, + interceptors: list[ServerInterceptor] | None = None, + options: _Options | None = None, + maximum_concurrent_rpcs: int | None = None, + compression: Compression | None = None, + xds: bool = False, +) -> Server: ... + +# Create Server Credentials: + +_CertificateChainPair: TypeAlias = tuple[bytes, bytes] + +def ssl_server_credentials( + private_key_certificate_chain_pairs: list[_CertificateChainPair], + root_certificates: bytes | None = None, + require_client_auth: bool = False, +) -> ServerCredentials: ... +def local_server_credentials(local_connect_type: LocalConnectionType = ...) -> ServerCredentials: ... +def ssl_server_certificate_configuration( + private_key_certificate_chain_pairs: list[_CertificateChainPair], root_certificates: bytes | None = None +) -> ServerCertificateConfiguration: ... +def dynamic_ssl_server_credentials( + initial_certificate_configuration: ServerCertificateConfiguration, + certificate_configuration_fetcher: Callable[[], ServerCertificateConfiguration], + require_client_authentication: bool = False, +) -> ServerCredentials: ... +def alts_server_credentials() -> ServerCredentials: ... +def insecure_server_credentials() -> ServerCredentials: ... +def xds_server_credentials(fallback_credentials: ServerCredentials) -> ServerCredentials: ... + +# RPC Method Handlers: + +# XXX: This is probably what appears in the add_FooServicer_to_server function +# in the _pb2_grpc files that get generated, which points to the FooServicer +# handler functions that get generated, which look like this: +# +# def FloobDoob(self, request, context): +# return response +# +@type_check_only +class _Behaviour(Protocol): + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + +def unary_unary_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def unary_stream_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def stream_unary_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def stream_stream_rpc_method_handler( + behavior: _Behaviour, + request_deserializer: _Deserializer[_TRequest] | None = None, + response_serializer: _Serializer[_TResponse] | None = None, +) -> RpcMethodHandler[_TRequest, _TResponse]: ... +def method_handlers_generic_handler( + service: str, method_handlers: dict[str, RpcMethodHandler[Any, Any]] +) -> GenericRpcHandler: ... + +# Channel Ready Future: + +def channel_ready_future(channel: Channel) -> Future[None]: ... + +# Channel Connectivity: + +class ChannelConnectivity(enum.Enum): + IDLE = (0, "idle") + CONNECTING = (1, "connecting") + READY = (2, "ready") + TRANSIENT_FAILURE = (3, "transient failure") + SHUTDOWN = (4, "shutdown") + +# gRPC Status Code: + +class Status(abc.ABC): + code: StatusCode + + # XXX: misnamed property, does not align with status.proto, where it is called 'message': + details: str + + trailing_metadata: _Metadata + +# https://grpc.github.io/grpc/core/md_doc_statuscodes.html +class StatusCode(enum.Enum): + OK = (0, "ok") + CANCELLED = (1, "cancelled") + UNKNOWN = (2, "unknown") + INVALID_ARGUMENT = (3, "invalid argument") + DEADLINE_EXCEEDED = (4, "deadline exceeded") + NOT_FOUND = (5, "not found") + ALREADY_EXISTS = (6, "already exists") + PERMISSION_DENIED = (7, "permission denied") + RESOURCE_EXHAUSTED = (8, "resource exhausted") + FAILED_PRECONDITION = (9, "failed precondition") + ABORTED = (10, "aborted") + OUT_OF_RANGE = (11, "out of range") + UNIMPLEMENTED = (12, "unimplemented") + INTERNAL = (13, "internal") + UNAVAILABLE = (14, "unavailable") + DATA_LOSS = (15, "data loss") + UNAUTHENTICATED = (16, "unauthenticated") + +# Channel Object: + +class Channel(abc.ABC): + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def stream_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def stream_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def subscribe(self, callback: Callable[[ChannelConnectivity], None], try_to_connect: bool = False) -> None: ... + @abc.abstractmethod + def unary_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unsubscribe(self, callback: Callable[[ChannelConnectivity], None]) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + +# Server Object: + +class Server(abc.ABC): + @abc.abstractmethod + def add_generic_rpc_handlers(self, generic_rpc_handlers: Iterable[GenericRpcHandler]) -> None: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_insecure_port(self, address: str) -> int: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_secure_port(self, address: str, server_credentials: ServerCredentials) -> int: ... + @abc.abstractmethod + def start(self) -> None: ... + + # Grace period is in seconds. + @abc.abstractmethod + def stop(self, grace: float | None) -> threading.Event: ... + + # Block current thread until the server stops. Returns a bool + # indicates if the operation times out. Timeout is in seconds. + def wait_for_termination(self, timeout: float | None = None) -> bool: ... + +# Authentication & Authorization Objects: + +# This class has no supported interface +class ChannelCredentials: + def __init__(self, credentials) -> None: ... + +# This class has no supported interface +class CallCredentials: + def __init__(self, credentials) -> None: ... + +class AuthMetadataContext(abc.ABC): + service_url: str + method_name: str + +class AuthMetadataPluginCallback(abc.ABC): + def __call__(self, metadata: _Metadata, error: Exception | None) -> None: ... + +class AuthMetadataPlugin(abc.ABC): + def __call__(self, context: AuthMetadataContext, callback: AuthMetadataPluginCallback) -> None: ... + +# This class has no supported interface +class ServerCredentials: + def __init__(self, credentials) -> None: ... + +# This class has no supported interface +class ServerCertificateConfiguration: + def __init__(self, certificate_configuration) -> None: ... + +# gRPC Exceptions: + +@type_check_only +class _Metadatum: + key: str + value: bytes + +# FIXME: There is scant documentation about what is actually available in this type. +# The properties here are the properties observed in the wild, and may be inaccurate. +# A better source to confirm their presence needs to be found at some point. +class RpcError(Exception): + def code(self) -> StatusCode: ... + + # misnamed property, does not align with status.proto, where it is called 'message': + def details(self) -> str | None: ... + + # XXX: This has a slightly different return type to all the other metadata: + def trailing_metadata(self) -> tuple[_Metadatum, ...]: ... + +# Shared Context: + +class RpcContext(abc.ABC): + @abc.abstractmethod + def add_callback(self, callback: Callable[[], None]) -> bool: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def is_active(self) -> bool: ... + @abc.abstractmethod + def time_remaining(self) -> float: ... + +# Client-Side Context: + +class Call(RpcContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def code(self) -> StatusCode: ... + + # misnamed property, does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def details(self) -> str: ... + @abc.abstractmethod + def initial_metadata(self) -> _Metadata: ... + @abc.abstractmethod + def trailing_metadata(self) -> _Metadata: ... + +# Client-Side Interceptor: + +class ClientCallDetails(abc.ABC): + method: str + timeout: float | None + metadata: _Metadata | None + credentials: CallCredentials | None + + # "This is an EXPERIMENTAL argument. An optional flag t enable wait for ready mechanism." + wait_for_ready: bool | None + + compression: Compression | None + +# 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. +# +@type_check_only +class _CallFuture(Call, Future[_TResponse], metaclass=abc.ABCMeta): ... + +class UnaryUnaryClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request)`. + @abc.abstractmethod + def intercept_unary_unary( + self, + continuation: Callable[[ClientCallDetails, _TRequest], _CallFuture[_TResponse]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _CallFuture[_TResponse]: ... + +@type_check_only +class _CallIterator(Call, Generic[_TResponse], metaclass=abc.ABCMeta): + def __iter__(self) -> Iterator[_TResponse]: ... + def __next__(self) -> _TResponse: ... + +class UnaryStreamClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request)`. + @abc.abstractmethod + def intercept_unary_stream( + self, + continuation: Callable[[ClientCallDetails, _TRequest], _CallIterator[_TResponse]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _CallIterator[_TResponse]: ... + +class StreamUnaryClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + def intercept_stream_unary( + self, + continuation: Callable[[ClientCallDetails, Iterator[_TRequest]], _CallFuture[_TResponse]], + client_call_details: ClientCallDetails, + request_iterator: Iterator[_TRequest], + ) -> _CallFuture[_TResponse]: ... + +class StreamStreamClientInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + def intercept_stream_stream( + self, + continuation: Callable[[ClientCallDetails, Iterator[_TRequest]], _CallIterator[_TResponse]], + client_call_details: ClientCallDetails, + request_iterator: Iterator[_TRequest], + ) -> _CallIterator[_TResponse]: ... + +# Service-Side Context: + +class ServicerContext(RpcContext, metaclass=abc.ABCMeta): + # misnamed parameter 'details', does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def abort(self, code: StatusCode, details: str) -> Never: ... + @abc.abstractmethod + def abort_with_status(self, status: Status) -> Never: ... + + # FIXME: The docs say "A map of strings to an iterable of bytes for each auth property". + # Does that mean 'bytes' (which is iterable), or 'Iterable[bytes]'? + @abc.abstractmethod + def auth_context(self) -> Mapping[str, bytes]: ... + def disable_next_message_compression(self) -> None: ... + @abc.abstractmethod + def invocation_metadata(self) -> _Metadata: ... + @abc.abstractmethod + def peer(self) -> str: ... + @abc.abstractmethod + def peer_identities(self) -> Iterable[bytes] | None: ... + @abc.abstractmethod + def peer_identity_key(self) -> str | None: ... + @abc.abstractmethod + def send_initial_metadata(self, initial_metadata: _Metadata) -> None: ... + @abc.abstractmethod + def set_code(self, code: StatusCode) -> None: ... + def set_compression(self, compression: Compression) -> None: ... + @abc.abstractmethod + def set_trailing_metadata(self, trailing_metadata: _Metadata) -> None: ... + + # misnamed function 'details', does not align with status.proto, where it is called 'message': + @abc.abstractmethod + def set_details(self, details: str) -> None: ... + def trailing_metadata(self) -> _Metadata: ... + +# Service-Side Handler: + +class RpcMethodHandler(abc.ABC, Generic[_TRequest, _TResponse]): + request_streaming: bool + response_streaming: bool + + # XXX: not clear from docs whether this is optional or not + request_deserializer: _Deserializer[_TRequest] | None + + # XXX: not clear from docs whether this is optional or not + response_serializer: _Serializer[_TResponse] | None + + unary_unary: Callable[[_TRequest, ServicerContext], _TResponse] | None + + unary_stream: Callable[[_TRequest, ServicerContext], Iterator[_TResponse]] | None + + stream_unary: Callable[[Iterator[_TRequest], ServicerContext], _TResponse] | None + + stream_stream: Callable[[Iterator[_TRequest], ServicerContext], Iterator[_TResponse]] | None + +@runtime_checkable +class HandlerCallDetails(Protocol): + method: str + invocation_metadata: _Metadata + +class GenericRpcHandler(abc.ABC): + # The return type depends on the handler call details. + @abc.abstractmethod + def service(self, handler_call_details: HandlerCallDetails) -> RpcMethodHandler[Any, Any] | None: ... + +class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta): + @abc.abstractmethod + def service_name(self) -> str: ... + +# Service-Side Interceptor: + +class ServerInterceptor(abc.ABC): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return continuation(handler_call_details)`. + @abc.abstractmethod + def intercept_service( + self, + continuation: Callable[[HandlerCallDetails], RpcMethodHandler[_TRequest, _TResponse] | None], + handler_call_details: HandlerCallDetails, + ) -> RpcMethodHandler[_TRequest, _TResponse] | None: ... + +# Multi-Callable Interfaces: + +class UnaryUnaryMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _TResponse: ... + @abc.abstractmethod + def future( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallFuture[_TResponse]: ... + @abc.abstractmethod + def with_call( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + # FIXME: Return value is documented as "The response value for the RPC and a Call value for the RPC"; + # this is slightly unclear so this return type is a best-effort guess. + ) -> tuple[_TResponse, Call]: ... + +class UnaryStreamMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallIterator[_TResponse]: ... + +class StreamUnaryMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _TResponse: ... + @abc.abstractmethod + def future( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallFuture[_TResponse]: ... + @abc.abstractmethod + def with_call( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + # FIXME: Return value is documented as "The response value for the RPC and a Call value for the RPC"; + # this is slightly unclear so this return type is a best-effort guess. + ) -> tuple[_TResponse, Call]: ... + +class StreamStreamMultiCallable(abc.ABC, Generic[_TRequest, _TResponse]): + @abc.abstractmethod + def __call__( + self, + request_iterator: Iterator[_TRequest], + timeout: float | None = None, + metadata: _Metadata | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> _CallIterator[_TResponse]: ... + +# Runtime Protobuf Parsing: + +def protos(protobuf_path: str) -> ModuleType: ... +def services(protobuf_path: str) -> ModuleType: ... +def protos_and_services(protobuf_path: str) -> tuple[ModuleType, ModuleType]: ... diff --git a/stubs/grpcio/grpc/aio/__init__.pyi b/stubs/grpcio/grpc/aio/__init__.pyi new file mode 100644 index 000000000000..4703a0864a0f --- /dev/null +++ b/stubs/grpcio/grpc/aio/__init__.pyi @@ -0,0 +1,536 @@ +import abc +import asyncio +from _typeshed import Incomplete, MaybeNone +from collections.abc import ( + AsyncIterable, + AsyncIterator, + Awaitable, + Callable, + Collection, + Generator, + Iterable, + Iterator, + Mapping, + Sequence, +) +from concurrent import futures +from types import TracebackType +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self + +from grpc import ( + CallCredentials, + ChannelConnectivity, + ChannelCredentials, + Compression, + GenericRpcHandler, + HandlerCallDetails, + RpcError, + RpcMethodHandler, + ServerCredentials, + Status, + StatusCode, + _Options, +) + +__all__ = ( + "EOF", + "AbortError", + "AioRpcError", + "BaseError", + "Call", + "Channel", + "ClientCallDetails", + "ClientInterceptor", + "InterceptedUnaryUnaryCall", + "InternalError", + "Metadata", + "RpcContext", + "Server", + "ServerInterceptor", + "ServicerContext", + "StreamStreamCall", + "StreamStreamClientInterceptor", + "StreamStreamMultiCallable", + "StreamUnaryCall", + "StreamUnaryClientInterceptor", + "StreamUnaryMultiCallable", + "UnaryStreamCall", + "UnaryStreamClientInterceptor", + "UnaryStreamMultiCallable", + "UnaryUnaryCall", + "UnaryUnaryClientInterceptor", + "UnaryUnaryMultiCallable", + "UsageError", + "init_grpc_aio", + "insecure_channel", + "secure_channel", + "server", + "shutdown_grpc_aio", +) + +_TRequest = TypeVar("_TRequest") +_TResponse = TypeVar("_TResponse") + +@type_check_only +class _EOF: + def __bool__(self) -> Literal[False]: ... + def __len__(self) -> Literal[0]: ... + +EOF: Final[_EOF] + +def init_grpc_aio() -> None: ... +def shutdown_grpc_aio() -> None: ... + +# Exceptions: + +class BaseError(Exception): ... +class UsageError(BaseError): ... +class AbortError(BaseError): ... +class InternalError(BaseError): ... + +class AioRpcError(RpcError): + def __init__( + self, + code: StatusCode, + initial_metadata: Metadata | None = None, + trailing_metadata: Metadata | None = None, + details: str | None = None, + debug_error_string: str | None = None, + ) -> None: ... + def code(self) -> StatusCode: ... + def details(self) -> str | None: ... + def initial_metadata(self) -> Metadata | MaybeNone: ... + # AioRpcError returns the async Metadata, overriding the synchronous + # grpc.RpcError.trailing_metadata() -> tuple[_Metadatum, ...]. + def trailing_metadata(self) -> Metadata | MaybeNone: ... # type: ignore[override] + def debug_error_string(self) -> str | None: ... + +# Create Client: + +def insecure_channel( + target: str, + options: _Options | None = None, + compression: Compression | None = None, + interceptors: Sequence[ClientInterceptor] | None = None, +) -> Channel: ... +def secure_channel( + target: str, + credentials: ChannelCredentials, + options: _Options | None = None, + compression: Compression | None = None, + interceptors: Sequence[ClientInterceptor] | None = None, +) -> Channel: ... + +# Create Server: + +def server( + migration_thread_pool: futures.Executor | None = None, + handlers: Sequence[GenericRpcHandler] | None = None, + interceptors: Sequence[ServerInterceptor] | None = None, + options: _Options | None = None, + maximum_concurrent_rpcs: int | None = None, + compression: Compression | None = None, +) -> Server: ... + +# Channel Object: + +_Serializer: TypeAlias = Callable[[_T], bytes] +_Deserializer: TypeAlias = Callable[[bytes], _T] + +class Channel(abc.ABC): + @abc.abstractmethod + async def close(self, grace: float | None = None) -> None: ... + @abc.abstractmethod + def get_state(self, try_to_connect: bool = False) -> ChannelConnectivity: ... + @abc.abstractmethod + async def wait_for_state_change(self, last_observed_state: ChannelConnectivity) -> None: ... + @abc.abstractmethod + def stream_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def stream_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> StreamUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_stream( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryStreamMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + def unary_unary( + self, + method: str, + request_serializer: _Serializer[_TRequest] | None = None, + response_deserializer: _Deserializer[_TResponse] | None = None, + ) -> UnaryUnaryMultiCallable[_TRequest, _TResponse]: ... + @abc.abstractmethod + async def __aenter__(self) -> Self: ... + @abc.abstractmethod + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + @abc.abstractmethod + async def channel_ready(self) -> None: ... + +# Server Object: + +class Server(metaclass=abc.ABCMeta): + @abc.abstractmethod + def add_generic_rpc_handlers(self, generic_rpc_handlers: Iterable[GenericRpcHandler]) -> None: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_insecure_port(self, address: str) -> int: ... + + # Returns an integer port on which server will accept RPC requests. + @abc.abstractmethod + def add_secure_port(self, address: str, server_credentials: ServerCredentials) -> int: ... + @abc.abstractmethod + async def start(self) -> None: ... + + # Grace period is in seconds. + @abc.abstractmethod + async def stop(self, grace: float | None) -> None: ... + + # Returns a bool indicates if the operation times out. Timeout is in seconds. + @abc.abstractmethod + async def wait_for_termination(self, timeout: float | None = None) -> bool: ... + +# Client-Side Context: + +_DoneCallbackType: TypeAlias = Callable[[Any], None] +_EOFType: TypeAlias = object + +class RpcContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def cancelled(self) -> bool: ... + @abc.abstractmethod + def done(self) -> bool: ... + @abc.abstractmethod + def time_remaining(self) -> float | None: ... + @abc.abstractmethod + def cancel(self) -> bool: ... + @abc.abstractmethod + def add_done_callback(self, callback: _DoneCallbackType) -> None: ... + +class Call(RpcContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + async def initial_metadata(self) -> Metadata: ... + @abc.abstractmethod + async def trailing_metadata(self) -> Metadata: ... + @abc.abstractmethod + async def code(self) -> StatusCode: ... + @abc.abstractmethod + async def details(self) -> str: ... + @abc.abstractmethod + async def wait_for_connection(self) -> None: ... + +class UnaryUnaryCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __await__(self) -> Generator[None, None, _TResponse]: ... + +class UnaryStreamCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __aiter__(self) -> AsyncIterator[_TResponse]: ... + @abc.abstractmethod + async def read(self) -> _EOFType | _TResponse: ... + +class StreamUnaryCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + async def write(self, request: _TRequest) -> None: ... + @abc.abstractmethod + async def done_writing(self) -> None: ... + @abc.abstractmethod + def __await__(self) -> Generator[None, None, _TResponse]: ... + +class StreamStreamCall(Call, Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __aiter__(self) -> AsyncIterator[_TResponse]: ... + @abc.abstractmethod + async def read(self) -> _EOFType | _TResponse: ... + @abc.abstractmethod + async def write(self, request: _TRequest) -> None: ... + @abc.abstractmethod + async def done_writing(self) -> None: ... + +# Service-Side Context: + +@type_check_only +class _DoneCallback(Generic[_TRequest, _TResponse]): + def __call__(self, ctx: ServicerContext[_TRequest, _TResponse]) -> None: ... + +class ServicerContext(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + async def abort(self, code: StatusCode, details: str = "", trailing_metadata: _MetadataType = ()) -> Never: ... + @abc.abstractmethod + async def read(self) -> _TRequest: ... + @abc.abstractmethod + async def write(self, message: _TResponse) -> None: ... + @abc.abstractmethod + async def send_initial_metadata(self, initial_metadata: _MetadataType) -> None: ... + def add_done_callback(self, callback: _DoneCallback[_TRequest, _TResponse]) -> None: ... + @abc.abstractmethod + async def abort_with_status(self, status: Status) -> Never: ... + @abc.abstractmethod + def set_trailing_metadata(self, trailing_metadata: _MetadataType) -> None: ... + @abc.abstractmethod + def invocation_metadata(self) -> Metadata | None: ... + @abc.abstractmethod + def set_code(self, code: StatusCode) -> None: ... + @abc.abstractmethod + def set_details(self, details: str) -> None: ... + @abc.abstractmethod + def set_compression(self, compression: Compression) -> None: ... + @abc.abstractmethod + def disable_next_message_compression(self) -> None: ... + @abc.abstractmethod + def peer(self) -> str: ... + @abc.abstractmethod + def peer_identities(self) -> Iterable[bytes] | None: ... + @abc.abstractmethod + def peer_identity_key(self) -> str | None: ... + @abc.abstractmethod + def auth_context(self) -> Mapping[str, Iterable[bytes]]: ... + def time_remaining(self) -> float: ... + def trailing_metadata(self) -> Metadata: ... + def code(self) -> StatusCode: ... + def details(self) -> str: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + +# Client-Side Interceptor: + +class ClientCallDetails(abc.ABC): + def __new__( + _cls, + method: str, + timeout: float | None, + metadata: Metadata | None, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + ) -> Self: ... + + method: str + timeout: float | None + metadata: Metadata | None + credentials: CallCredentials | None + + # "This is an EXPERIMENTAL argument. An optional flag t enable wait for ready mechanism." + wait_for_ready: bool | None + + # As at 1.53.0, this is not supported in aio: + # compression: Compression | None + +@type_check_only +class _InterceptedCall(Generic[_TRequest, _TResponse]): + def __init__(self, interceptors_task: asyncio.Task[Any]) -> None: ... + def __del__(self) -> None: ... + def cancel(self) -> bool: ... + def cancelled(self) -> bool: ... + def done(self) -> bool: ... + def add_done_callback(self, callback: _DoneCallback[_TRequest, _TResponse]) -> None: ... + def time_remaining(self) -> float | None: ... + async def initial_metadata(self) -> Metadata | None: ... + async def trailing_metadata(self) -> Metadata | None: ... + async def code(self) -> StatusCode: ... + async def details(self) -> str: ... + async def debug_error_string(self) -> str | None: ... + async def wait_for_connection(self) -> None: ... + +class InterceptedUnaryUnaryCall(_InterceptedCall[_TRequest, _TResponse], metaclass=abc.ABCMeta): + def __await__(self) -> Generator[Incomplete, None, _TResponse]: ... + def __init__( + self, + interceptors: Sequence[UnaryUnaryClientInterceptor], + request: _TRequest, + timeout: float | None, + metadata: Metadata, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + channel: Channel, + method: bytes, + request_serializer: _Serializer[_TRequest], + response_deserializer: _Deserializer[_TResponse], + loop: asyncio.AbstractEventLoop, + ) -> None: ... + + # pylint: disable=too-many-arguments + async def _invoke( + self, + interceptors: Sequence[UnaryUnaryClientInterceptor], + method: bytes, + timeout: float | None, + metadata: Metadata | None, + credentials: CallCredentials | None, + wait_for_ready: bool | None, + request: _TRequest, + request_serializer: _Serializer[_TRequest], + response_deserializer: _Deserializer[_TResponse], + ) -> UnaryUnaryCall[_TRequest, _TResponse]: ... + def time_remaining(self) -> float | None: ... + +class ClientInterceptor(metaclass=abc.ABCMeta): ... + +class UnaryUnaryClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request)`. + @abc.abstractmethod + async def intercept_unary_unary( + self, + continuation: Callable[[ClientCallDetails, _TRequest], Awaitable[UnaryUnaryCall[_TRequest, _TResponse]]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> _TResponse | UnaryUnaryCall[_TRequest, _TResponse]: ... + +class UnaryStreamClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request)`. + @abc.abstractmethod + async def intercept_unary_stream( + self, + continuation: Callable[[ClientCallDetails, _TRequest], Awaitable[UnaryStreamCall[_TRequest, _TResponse]]], + client_call_details: ClientCallDetails, + request: _TRequest, + ) -> AsyncIterator[_TResponse] | UnaryStreamCall[_TRequest, _TResponse]: ... + +class StreamUnaryClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + async def intercept_stream_unary( + self, + continuation: Callable[ + [ClientCallDetails, AsyncIterable[_TRequest] | Iterable[_TRequest]], Awaitable[StreamUnaryCall[_TRequest, _TResponse]] + ], + client_call_details: ClientCallDetails, + request_iterator: AsyncIterable[_TRequest] | Iterable[_TRequest], + ) -> _TResponse | StreamUnaryCall[_TRequest, _TResponse]: ... + +class StreamStreamClientInterceptor(ClientInterceptor, metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(client_call_details, request_iterator)`. + @abc.abstractmethod + async def intercept_stream_stream( + self, + continuation: Callable[ + [ClientCallDetails, AsyncIterable[_TRequest] | Iterable[_TRequest]], + Awaitable[StreamStreamCall[_TRequest, _TResponse]], + ], + client_call_details: ClientCallDetails, + request_iterator: AsyncIterable[_TRequest] | Iterable[_TRequest], + ) -> AsyncIterator[_TResponse] | StreamStreamCall[_TRequest, _TResponse]: ... + +# Server-Side Interceptor: + +class ServerInterceptor(metaclass=abc.ABCMeta): + # This method (not the class) is generic over _TRequest and _TResponse + # and the types must satisfy the no-op implementation of + # `return await continuation(handler_call_details)`. + # The return is Optional: per the runtime docstring, an interceptor + # may return None to signal that the RPC is not serviced, and the + # continuation propagates that None down the chain. + @abc.abstractmethod + async def intercept_service( + self, + continuation: Callable[[HandlerCallDetails], Awaitable[RpcMethodHandler[_TRequest, _TResponse] | None]], + handler_call_details: HandlerCallDetails, + ) -> RpcMethodHandler[_TRequest, _TResponse] | None: ... + +# Multi-Callable Interfaces: + +class UnaryUnaryMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + *, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> UnaryUnaryCall[_TRequest, _TResponse]: ... + +class UnaryStreamMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request: _TRequest, + *, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> UnaryStreamCall[_TRequest, _TResponse]: ... + +class StreamUnaryMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request_iterator: AsyncIterator[_TRequest] | Iterator[_TRequest] | None = None, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> StreamUnaryCall[_TRequest, _TResponse]: ... + +class StreamStreamMultiCallable(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): + @abc.abstractmethod + def __call__( + self, + request_iterator: AsyncIterator[_TRequest] | Iterator[_TRequest] | None = None, + timeout: float | None = None, + metadata: _MetadataType | None = None, + credentials: CallCredentials | None = None, + wait_for_ready: bool | None = None, + compression: Compression | None = None, + ) -> StreamStreamCall[_TRequest, _TResponse]: ... + +# Metadata: + +_MetadataKey: TypeAlias = str +_MetadataValue: TypeAlias = str | bytes +_MetadatumType: TypeAlias = tuple[_MetadataKey, _MetadataValue] +_MetadataType: TypeAlias = Metadata | Sequence[_MetadatumType] +_T = TypeVar("_T") + +class Metadata(Collection[_MetadatumType]): + def __init__(self, *args: tuple[_MetadataKey, _MetadataValue]) -> None: ... + @classmethod + def from_tuple(cls, raw_metadata: tuple[_MetadataKey, _MetadataValue]) -> Metadata: ... + def add(self, key: _MetadataKey, value: _MetadataValue) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _MetadataKey) -> _MetadataValue: ... + def __setitem__(self, key: _MetadataKey, value: _MetadataValue) -> None: ... + def __delitem__(self, key: _MetadataKey) -> None: ... + def delete_all(self, key: _MetadataKey) -> None: ... + def __iter__(self) -> Iterator[_MetadatumType]: ... + + @overload + def get(self, key: _MetadataKey, default: None = None) -> _MetadataValue | None: ... + @overload + def get(self, key: _MetadataKey, default: _MetadataValue) -> _MetadataValue: ... + @overload + def get(self, key: _MetadataKey, default: _T) -> _MetadataValue | _T: ... + + def get_all(self, key: _MetadataKey) -> list[_MetadataValue]: ... + def set_all(self, key: _MetadataKey, values: list[_MetadataValue]) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: Any) -> Metadata: ... diff --git a/stubs/grpcio/grpc/experimental/gevent.pyi b/stubs/grpcio/grpc/experimental/gevent.pyi new file mode 100644 index 000000000000..71163b4763c9 --- /dev/null +++ b/stubs/grpcio/grpc/experimental/gevent.pyi @@ -0,0 +1 @@ +def init_gevent() -> None: ... diff --git a/stubs/gunicorn/@tests/stubtest_allowlist.txt b/stubs/gunicorn/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c5b7678827c3 --- /dev/null +++ b/stubs/gunicorn/@tests/stubtest_allowlist.txt @@ -0,0 +1,9 @@ +# Is not present in runtime. For more details, see the file itself. +gunicorn._types + +# .pyi file doesn't exist +gunicorn.__main__ + +# Internal API stuff: +gunicorn.config.Config.forwarded_allow_networks +gunicorn.config.Config.proxy_allow_networks diff --git a/stubs/gunicorn/METADATA.toml b/stubs/gunicorn/METADATA.toml new file mode 100644 index 000000000000..3725c9c6add0 --- /dev/null +++ b/stubs/gunicorn/METADATA.toml @@ -0,0 +1,14 @@ +version = "26.0.0" +upstream-repository = "https://github.com/benoitc/gunicorn" +optional-dependencies = ["types-gevent"] + +[tool.stubtest] +supported-platforms = ["linux", "darwin"] +ci-platforms = ["linux", "darwin"] +stubtest-dependencies = [ + "gevent>=1.4.0", + "tornado>=0.2", + "setproctitle", + "PasteDeploy", + "inotify", +] diff --git a/stubs/gunicorn/gunicorn/__init__.pyi b/stubs/gunicorn/gunicorn/__init__.pyi new file mode 100644 index 000000000000..ddd769a92a3e --- /dev/null +++ b/stubs/gunicorn/gunicorn/__init__.pyi @@ -0,0 +1,6 @@ +from typing import Final + +version_info: Final[tuple[int, int, int]] +__version__: Final[str] +SERVER: Final[str] +SERVER_SOFTWARE: Final[str] diff --git a/stubs/gunicorn/gunicorn/_types.pyi b/stubs/gunicorn/gunicorn/_types.pyi new file mode 100644 index 000000000000..815a1179f98c --- /dev/null +++ b/stubs/gunicorn/gunicorn/_types.pyi @@ -0,0 +1,23 @@ +### This .pyi file is a helper for centralized storage types that are reused across different runtime modules. ### +from _typeshed import FileDescriptor +from collections.abc import Awaitable, Callable, Iterable, MutableMapping +from typing import Any, TypeAlias +from typing_extensions import LiteralString + +_StatusType: TypeAlias = str +_HeadersType: TypeAlias = Iterable[tuple[str, str]] + +_EnvironType: TypeAlias = MutableMapping[str, Any] # See https://peps.python.org/pep-0333/ +_StartResponseType: TypeAlias = Callable[[_StatusType, _HeadersType], None] +_ResponseBodyType: TypeAlias = Iterable[bytes] +_WSGIAppType: TypeAlias = Callable[[_EnvironType, _StartResponseType], _ResponseBodyType] # noqa: Y047 + +_ScopeType: TypeAlias = MutableMapping[str, Any] +_MessageType: TypeAlias = MutableMapping[str, Any] +_ReceiveType: TypeAlias = Callable[[], Awaitable[_MessageType]] +_SendType: TypeAlias = Callable[[_MessageType], Awaitable[None]] +_ASGIAppType: TypeAlias = Callable[[_ScopeType, _ReceiveType, _SendType], Awaitable[None]] # noqa: Y047 + +_UnixSocketPathType: TypeAlias = str +_TcpAddressType: TypeAlias = tuple[LiteralString, int] # noqa: Y047 +_AddressType: TypeAlias = _UnixSocketPathType | FileDescriptor | _TcpAddressType # noqa: Y047 diff --git a/stubs/gunicorn/gunicorn/app/__init__.pyi b/stubs/gunicorn/gunicorn/app/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/gunicorn/gunicorn/app/base.pyi b/stubs/gunicorn/gunicorn/app/base.pyi new file mode 100644 index 000000000000..6e06417eca5d --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/base.pyi @@ -0,0 +1,33 @@ +from argparse import ArgumentParser, Namespace +from typing import Any + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType, _WSGIAppType + +class BaseApplication: + usage: str | None + cfg: Config + callable: _WSGIAppType | _ASGIAppType | None + prog: str | None + logger: GLogger + + def __init__(self, usage: str | None = None, prog: str | None = None) -> None: ... + def do_load_config(self) -> None: ... + def load_default_config(self) -> None: ... + def init(self, parser: ArgumentParser, opts: Namespace, args: list[str]) -> dict[str, Any] | None: ... + def load(self) -> _WSGIAppType | _ASGIAppType: ... + def load_config(self) -> None: ... + def reload(self) -> None: ... + def wsgi(self) -> _WSGIAppType | _ASGIAppType: ... + def run(self) -> None: ... + +class Application(BaseApplication): + def chdir(self) -> None: ... + def get_config_from_filename(self, filename: str) -> dict[str, Any]: ... + def get_config_from_module_name(self, module_name: str) -> dict[str, Any]: ... + def load_config_from_module_name_or_filename(self, location: str) -> dict[str, Any]: ... + def load_config_from_file(self, filename: str) -> dict[str, Any]: ... + def load_config(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/app/pasterapp.pyi b/stubs/gunicorn/gunicorn/app/pasterapp.pyi new file mode 100644 index 000000000000..ab94b4872f49 --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/pasterapp.pyi @@ -0,0 +1,7 @@ +from typing import Any + +from .._types import _WSGIAppType + +def get_wsgi_app(config_uri: str, name: str | None = None, defaults: dict[str, Any] | None = None) -> _WSGIAppType: ... +def has_logging_config(config_file: str) -> bool: ... +def serve(app: _WSGIAppType, global_conf: dict[str, Any], **local_conf: Any) -> None: ... diff --git a/stubs/gunicorn/gunicorn/app/wsgiapp.pyi b/stubs/gunicorn/gunicorn/app/wsgiapp.pyi new file mode 100644 index 000000000000..36e0cedc410f --- /dev/null +++ b/stubs/gunicorn/gunicorn/app/wsgiapp.pyi @@ -0,0 +1,16 @@ +from argparse import ArgumentParser, Namespace + +from gunicorn.app.base import Application + +from .._types import _WSGIAppType + +class WSGIApplication(Application): + app_uri: str | None + + def init(self, parser: ArgumentParser, opts: Namespace, args: list[str]) -> None: ... + def load_config(self) -> None: ... + def load_wsgiapp(self) -> _WSGIAppType: ... + def load_pasteapp(self) -> _WSGIAppType: ... + def load(self) -> _WSGIAppType: ... + +def run(prog: str | None = None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/arbiter.pyi b/stubs/gunicorn/gunicorn/arbiter.pyi new file mode 100644 index 000000000000..15710a89669d --- /dev/null +++ b/stubs/gunicorn/gunicorn/arbiter.pyi @@ -0,0 +1,79 @@ +from queue import SimpleQueue +from types import FrameType +from typing import ClassVar + +from gunicorn.app.base import BaseApplication +from gunicorn.config import Config +from gunicorn.dirty import DirtyArbiter +from gunicorn.glogging import Logger as GLogger +from gunicorn.sock import BaseSocket +from gunicorn.workers.base import Worker + +from ._types import _AddressType +from .pidfile import Pidfile + +class Arbiter: + WORKER_BOOT_ERROR: ClassVar[int] + APP_LOAD_ERROR: ClassVar[int] + START_CTX: ClassVar[dict[int | str, str | list[str]]] + LISTENERS: ClassVar[list[BaseSocket]] + WORKERS: ClassVar[dict[int, Worker]] + WAKEUP_REQUEST: ClassVar[int] + SIGNALS: ClassVar[list[int]] + SIG_NAMES: ClassVar[dict[int, str]] + log: GLogger | None + SIG_QUEUE: SimpleQueue[int] + pidfile: Pidfile | None + systemd: bool + worker_age: int + reexec_pid: int + master_pid: int + master_name: str + dirty_arbiter_pid: int + dirty_arbiter: DirtyArbiter | None + dirty_pidfile: str | None + pid: int + app: BaseApplication + cfg: Config + worker_class: type[Worker] + address: list[_AddressType] + timeout: int + proc_name: str + num_workers: int + + def __init__(self, app: BaseApplication) -> None: ... + def setup(self, app: BaseApplication) -> None: ... + def start(self) -> None: ... + def init_signals(self) -> None: ... + def signal(self, sig: int, frame: FrameType | None) -> None: ... + def run(self) -> None: ... + def signal_chld(self, sig: int, frame: FrameType | None) -> None: ... + def handle_chld(self) -> None: ... + handle_cld = handle_chld + def handle_hup(self) -> None: ... + def handle_term(self) -> None: ... + def handle_int(self) -> None: ... + def handle_quit(self) -> None: ... + def handle_ttin(self) -> None: ... + def handle_ttou(self) -> None: ... + def handle_usr1(self) -> None: ... + def handle_usr2(self) -> None: ... + def handle_winch(self) -> None: ... + def maybe_promote_master(self) -> None: ... + def wakeup(self) -> None: ... + def halt(self, reason: str | None = None, exit_status: int = 0) -> None: ... + def wait_for_signals(self, timeout: float | None = 1.0) -> list[int]: ... + def stop(self, graceful: bool = True) -> None: ... + def reexec(self) -> None: ... + def reload(self) -> None: ... + def murder_workers(self) -> None: ... + def reap_workers(self) -> None: ... + def manage_workers(self) -> None: ... + def spawn_worker(self) -> int: ... + def spawn_workers(self) -> None: ... + def kill_workers(self, sig: int) -> None: ... + def kill_worker(self, pid: int, sig: int) -> None: ... + def spawn_dirty_arbiter(self) -> int | None: ... + def kill_dirty_arbiter(self, sig: int) -> None: ... + def reap_dirty_arbiter(self) -> None: ... + def manage_dirty_arbiter(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/__init__.pyi b/stubs/gunicorn/gunicorn/asgi/__init__.pyi new file mode 100644 index 000000000000..0e635cb1217d --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/__init__.pyi @@ -0,0 +1,4 @@ +from gunicorn.asgi.lifespan import LifespanManager as LifespanManager +from gunicorn.asgi.unreader import AsyncUnreader as AsyncUnreader + +__all__ = ["AsyncUnreader", "LifespanManager"] diff --git a/stubs/gunicorn/gunicorn/asgi/lifespan.pyi b/stubs/gunicorn/gunicorn/asgi/lifespan.pyi new file mode 100644 index 000000000000..a55dca666674 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/lifespan.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType + +class LifespanManager: + app: _ASGIAppType + logger: GLogger + state: dict[Incomplete, Incomplete] + + def __init__(self, app: _ASGIAppType, logger: GLogger, state: dict[Incomplete, Incomplete] | None = None) -> None: ... + async def startup(self) -> None: ... + async def shutdown(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/parser.pyi b/stubs/gunicorn/gunicorn/asgi/parser.pyi new file mode 100644 index 000000000000..f98f04a0f178 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/parser.pyi @@ -0,0 +1,158 @@ +from collections.abc import Callable, Iterable +from enum import IntEnum +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self + +_H1CProtocol: TypeAlias = Any # gunicorn_h1c H1CProtocol class + +class ParseError(Exception): ... +class InvalidProxyLine(ParseError): ... +class InvalidProxyHeader(ParseError): ... + +@type_check_only +class _ProxyProtocolInfo(TypedDict): + proxy_protocol: Literal["TCP4", "TCP6", "UDP4", "UDP6"] + client_addr: str + client_port: int + proxy_addr: str + proxy_port: int + +@type_check_only +class _ProxyProtocolInfoUnknown(TypedDict): + proxy_protocol: Literal["UNKNOWN", "LOCAL", "UNSPEC"] + client_addr: None + client_port: None + proxy_addr: None + proxy_port: None + +PP_V2_SIGNATURE: Final[bytes] +RFC9110_6_5_1_FORBIDDEN_TRAILER: Final[frozenset[bytes]] + +class PPCommand(IntEnum): + LOCAL = 0x0 + PROXY = 0x1 + +class PPFamily(IntEnum): + UNSPEC = 0x0 + INET = 0x1 + INET6 = 0x2 + UNIX = 0x3 + +class PPProtocol(IntEnum): + UNSPEC = 0x0 + STREAM = 0x1 + DGRAM = 0x2 + +class LimitRequestLine(ParseError): ... +class InvalidRequestLine(ParseError): ... +class LimitRequestHeaders(ParseError): ... +class InvalidRequestMethod(ParseError): ... +class InvalidHTTPVersion(ParseError): ... +class InvalidHeaderName(ParseError): ... +class InvalidHeader(ParseError): ... +class UnsupportedTransferCoding(ParseError): ... +class InvalidChunkSize(ParseError): ... +class InvalidChunkExtension(ParseError): ... + +class PythonProtocol: + __slots__ = ( + "_on_message_begin", + "_on_url", + "_on_header", + "_on_headers_complete", + "_on_body", + "_on_message_complete", + "_state", + "_buffer", + "_headers_list", + "method", + "path", + "http_version", + "headers", + "content_length", + "is_chunked", + "should_keep_alive", + "is_complete", + "_body_remaining", + "_skip_body", + "_chunk_state", + "_chunk_size", + "_chunk_remaining", + "_limit_request_line", + "_limit_request_fields", + "_limit_request_field_size", + "_permit_unconventional_http_method", + "_permit_unconventional_http_version", + "_header_count", + "_proxy_protocol", + "_proxy_protocol_info", + "_proxy_protocol_done", + ) + method: bytes | None + path: bytes | None + http_version: tuple[int, int] | None + headers: list[tuple[bytes, bytes]] + content_length: int | None + is_chunked: bool + should_keep_alive: bool + is_complete: bool + + def __init__( + self, + on_message_begin: Callable[[], object] | None = None, + on_url: Callable[[bytes], object] | None = None, + on_header: Callable[[bytes, bytes], object] | None = None, + on_headers_complete: Callable[[], bool] | None = None, + on_body: Callable[[bytes], object] | None = None, + on_message_complete: Callable[[], object] | None = None, + limit_request_line: int = 8190, + limit_request_fields: int = 100, + limit_request_field_size: int = 8190, + permit_unconventional_http_method: bool = False, + permit_unconventional_http_version: bool = False, + proxy_protocol: Literal["off", "v1", "v2", "auto"] = "off", + ) -> None: ... + def feed(self, data: Iterable[SupportsIndex]) -> None: ... + @property + def proxy_protocol_info(self) -> _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None: ... + def reset(self) -> None: ... + def finish(self) -> None: ... + +class CallbackRequest: + __slots__ = ( + "method", + "uri", + "path", + "query", + "fragment", + "version", + "headers", + "headers_bytes", + "scheme", + "raw_path", + "content_length", + "chunked", + "must_close", + "proxy_protocol_info", + "_expect_100_continue", + ) + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] | None + headers: list[tuple[str, str]] + headers_bytes: list[tuple[bytes, bytes]] + scheme: Literal["https", "http"] + raw_path: bytes + content_length: int + chunked: bool + must_close: bool + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self) -> None: ... + @classmethod + def from_parser(cls, parser: _H1CProtocol | PythonProtocol, is_ssl: bool = False) -> Self: ... + def should_close(self) -> bool: ... + def get_header(self, name: str) -> str | None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/protocol.pyi b/stubs/gunicorn/gunicorn/asgi/protocol.pyi new file mode 100644 index 000000000000..376851ee89ab --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/protocol.pyi @@ -0,0 +1,61 @@ +import asyncio +from collections.abc import Iterable +from typing import Final, Literal, TypedDict, type_check_only +from typing_extensions import NotRequired + +from gunicorn.asgi.parser import CallbackRequest +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers.gasgi import ASGIWorker + +from .._types import _ASGIAppType + +HIGH_WATER_LIMIT: Final = 65536 + +class FlowControl: + __slots__ = ("_transport", "read_paused", "write_paused", "_is_writable_event") + read_paused: bool + write_paused: bool + + def __init__(self, transport: asyncio.BaseTransport) -> None: ... + async def drain(self) -> None: ... + def pause_reading(self) -> None: ... + def resume_reading(self) -> None: ... + def pause_writing(self) -> None: ... + def resume_writing(self) -> None: ... + +class ASGIResponseInfo: + status: str | int + sent: int + headers: list[tuple[str, str]] + + def __init__(self, status: str | int, headers: Iterable[tuple[str | bytes, str | bytes]], sent: int) -> None: ... + +@type_check_only +class _BodyReceieverReceiveReturnType(TypedDict): + type: Literal["http.disconnect", "http.request"] + body: NotRequired[bytes] + more_body: NotRequired[bool] + +class BodyReceiver: + __slots__ = ("_chunks", "_complete", "_body_finished", "_closed", "_body_wait_expired", "_waiter", "request", "protocol") + request: CallbackRequest + protocol: ASGIProtocol + + def __init__(self, request: CallbackRequest, protocol: ASGIProtocol) -> None: ... + def feed(self, chunk: bytes) -> None: ... + def set_complete(self) -> None: ... + def signal_disconnect(self) -> None: ... + async def receive(self) -> _BodyReceieverReceiveReturnType: ... + +class ASGIProtocol(asyncio.Protocol): + worker: ASGIWorker + cfg: Config + log: GLogger + app: _ASGIAppType + transport: asyncio.BaseTransport | None + reader: asyncio.StreamReader | None + writer: asyncio.BaseTransport | None + req_count: int + + def __init__(self, worker: ASGIWorker) -> None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/unreader.pyi b/stubs/gunicorn/gunicorn/asgi/unreader.pyi new file mode 100644 index 000000000000..8bb53ea2f396 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/unreader.pyi @@ -0,0 +1,13 @@ +import asyncio +import io +from _typeshed import ReadableBuffer + +class AsyncUnreader: + reader: asyncio.StreamReader + buf: io.BytesIO + max_chunk: int + + def __init__(self, reader: asyncio.StreamReader, max_chunk: int = 8192) -> None: ... + async def read(self, size: int | None = None) -> bytes: ... + def unread(self, data: ReadableBuffer) -> None: ... + def has_buffered_data(self) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi b/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi new file mode 100644 index 000000000000..c76678bf8199 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi @@ -0,0 +1,39 @@ +from typing import Literal +from typing_extensions import Self + +from gunicorn.asgi.unreader import AsyncUnreader +from gunicorn.config import Config +from gunicorn.uwsgi.message import UWSGIRequest + +from .._types import _AddressType +from .parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +class AsyncUWSGIRequest(UWSGIRequest): + cfg: Config + unreader: AsyncUnreader # type: ignore[assignment] + peer_addr: _AddressType + remote_addr: _AddressType + req_number: int + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + scheme: Literal["https", "http"] + must_close: bool + uwsgi_vars: dict[str, str] + modifier1: int + modifier2: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + content_length: int + chunked: bool + + def __init__(self, cfg: Config, unreader: AsyncUnreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + @classmethod + async def parse(cls, cfg: Config, unreader: AsyncUnreader, peer_addr: _AddressType, req_number: int = 1) -> Self: ... # type: ignore[override] + async def read_body(self, size: int = 8192) -> bytes: ... + async def drain_body(self) -> None: ... + def get_header(self, name: str) -> str | None: ... diff --git a/stubs/gunicorn/gunicorn/asgi/websocket.pyi b/stubs/gunicorn/gunicorn/asgi/websocket.pyi new file mode 100644 index 000000000000..457d53f0f637 --- /dev/null +++ b/stubs/gunicorn/gunicorn/asgi/websocket.pyi @@ -0,0 +1,40 @@ +import asyncio +from typing import Final + +from gunicorn.glogging import Logger as GLogger + +from .._types import _ASGIAppType, _ScopeType + +OPCODE_CONTINUATION: Final = 0x0 +OPCODE_TEXT: Final = 0x1 +OPCODE_BINARY: Final = 0x2 +OPCODE_CLOSE: Final = 0x8 +OPCODE_PING: Final = 0x9 +OPCODE_PONG: Final = 0xA +CLOSE_NORMAL: Final = 1000 +CLOSE_GOING_AWAY: Final = 1001 +CLOSE_PROTOCOL_ERROR: Final = 1002 +CLOSE_UNSUPPORTED: Final = 1003 +CLOSE_NO_STATUS: Final = 1005 +CLOSE_ABNORMAL: Final = 1006 +CLOSE_INVALID_DATA: Final = 1007 +CLOSE_POLICY_VIOLATION: Final = 1008 +CLOSE_MESSAGE_TOO_BIG: Final = 1009 +CLOSE_MANDATORY_EXT: Final = 1010 +CLOSE_INTERNAL_ERROR: Final = 1011 +WS_GUID: Final = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +class WebSocketProtocol: + transport: asyncio.Transport + scope: _ScopeType + app: _ASGIAppType + log: GLogger + accepted: bool + closed: bool + close_code: int | None + close_reason: str | None + + def __init__(self, transport: asyncio.Transport, scope: _ScopeType, app: _ASGIAppType, log: GLogger) -> None: ... + def feed_data(self, data: bytes) -> None: ... + def feed_eof(self) -> None: ... + async def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/config.pyi b/stubs/gunicorn/gunicorn/config.pyi new file mode 100644 index 000000000000..8eabbee8eddd --- /dev/null +++ b/stubs/gunicorn/gunicorn/config.pyi @@ -0,0 +1,1335 @@ +import argparse +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Container +from ssl import SSLContext, _SSLMethod +from typing import Annotated, Any, ClassVar, Final, TypeAlias, overload + +from gunicorn.arbiter import Arbiter +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request +from gunicorn.http.wsgi import Response +from gunicorn.workers.base import Worker + +from ._types import _AddressType, _EnvironType + +_ConfigValueType: TypeAlias = Any +# Any: Value type depends on the setting's validator (e.g., validate_bool, validate_pos_int). +# Maybe types: bool, int, str, list[str], dict[str, Any], Callable[..., object], type[object], ssl.PROTOCOL_*. +# Validator ensures type correctness at runtime. + +_OnStartingHookType: TypeAlias = Callable[[Arbiter], object] +_OnReloadHookType: TypeAlias = Callable[[Arbiter], object] +_WhenReadyHookType: TypeAlias = Callable[[Arbiter], object] +_PreForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_PostForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_PostWorkerInitHookType: TypeAlias = Callable[[Worker], object] +_WorkerIntHookType: TypeAlias = Callable[[Worker], object] +_WorkerAbortHookType: TypeAlias = Callable[[Worker], object] +_PreExecHookType: TypeAlias = Callable[[Arbiter], object] +_PreRequestHookType: TypeAlias = Callable[[Worker, Request], object] +_PostRequestHookType: TypeAlias = Callable[[Worker, Request, _EnvironType, Response], object] +_ChildExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_WorkerExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_NumWorkersChangedHookType: TypeAlias = Callable[[Arbiter, int, int | None], object] +_OnExitHookType: TypeAlias = Callable[[Arbiter], object] +_SSLContextHookType: TypeAlias = Callable[[Config, Callable[[], SSLContext]], SSLContext] +_OnDirtyStartingHookType: TypeAlias = Callable[[Arbiter], object] +_DirtyPostForkHookType: TypeAlias = Callable[[Arbiter, Worker], object] +_DirtyWorkerInitHookType: TypeAlias = Callable[[Worker], object] +_DirtyWorkerExitHookType: TypeAlias = Callable[[Arbiter, Worker], object] + +_HookType: TypeAlias = ( + _OnStartingHookType + | _OnReloadHookType + | _WhenReadyHookType + | _PreForkHookType + | _PostForkHookType + | _PostWorkerInitHookType + | _WorkerIntHookType + | _WorkerAbortHookType + | _PreExecHookType + | _PreRequestHookType + | _PostRequestHookType + | _ChildExitHookType + | _WorkerExitHookType + | _NumWorkersChangedHookType + | _OnExitHookType + | _SSLContextHookType + | _OnDirtyStartingHookType + | _DirtyPostForkHookType + | _DirtyWorkerInitHookType + | _DirtyWorkerExitHookType +) +# Validators +_BoolValidatorType: TypeAlias = Callable[[bool | str | None], bool | None] +_StringValidatorType: TypeAlias = Callable[[str | None], str | None] +_ListStringValidatorType: TypeAlias = Callable[[str | list[str] | None], list[str]] +_IntValidatorType: TypeAlias = Callable[[ConvertibleToInt], int] +_DictValidatorType: TypeAlias = Callable[[dict[str, Any]], dict[str, Any]] +_ClassValidatorType: TypeAlias = Callable[[object | str | None], type[Any] | None] +_UserGroupValidatorType: TypeAlias = Callable[[str | int | None], int] +_AddressValidatorType: TypeAlias = Callable[[str | None], _AddressType | None] +_CallableValidatorType: TypeAlias = Callable[[str | _HookType], _HookType] +_ProxyProtocolValidatorType: TypeAlias = Callable[[str | bool | None], str] +_ASGILoopValidatorType: TypeAlias = Callable[[str | None], str] +_ASGILifespanValidatorType: TypeAlias = Callable[[str | None], str] +_HTTP2FrameSizeValidatorType: TypeAlias = Callable[[ConvertibleToInt], int] +_HTTPProtocolsValidatorType: TypeAlias = Callable[[str | None], list[str]] +_HttpParserValidatorType: TypeAlias = Callable[[str | None], str] + +_ValidatorType: TypeAlias = ( # noqa: Y047 + _BoolValidatorType + | _StringValidatorType + | _ListStringValidatorType + | _IntValidatorType + | _DictValidatorType + | _ClassValidatorType + | _UserGroupValidatorType + | _AddressValidatorType + | _CallableValidatorType + | _ProxyProtocolValidatorType + | _ASGILoopValidatorType + | _ASGILifespanValidatorType + | _HTTP2FrameSizeValidatorType + | _HTTPProtocolsValidatorType + | _HttpParserValidatorType +) + +KNOWN_SETTINGS: list[Setting] +PLATFORM: str + +def make_settings(ignore: Container[Setting] | None = None) -> dict[str, Setting]: ... +def auto_int(_: Any, x: str) -> int: ... + +class Config: + settings: dict[str, Setting] + usage: str | None + prog: str | None + env_orig: dict[str, str] + + def __init__(self, usage: str | None = None, prog: str | None = None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + def set(self, name: str, value: _ConfigValueType) -> None: ... + def get_cmd_args_from_env(self) -> list[str]: ... + def parser(self) -> argparse.ArgumentParser: ... + @property + def worker_class_str(self) -> str: ... + @property + def worker_class(self) -> type[Worker]: ... + @property + def address(self) -> list[_AddressType]: ... + @property + def uid(self) -> int: ... + @property + def gid(self) -> int: ... + @property + def proc_name(self) -> str | None: ... + @property + def logger_class(self) -> type[GLogger]: ... + @property + def is_ssl(self) -> bool: ... + @property + def ssl_options(self) -> dict[str, Any]: ... + @property + def env(self) -> dict[str, str]: ... + @property + def sendfile(self) -> bool: ... + @property + def reuse_port(self) -> bool: ... + @property + def paste_global_conf(self) -> dict[str, str] | None: ... + +class SettingMeta(type): + def __new__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> SettingMeta: ... + def fmt_desc(cls, desc: str) -> None: ... + +class Setting(metaclass=SettingMeta): + name: ClassVar[str | None] + value: _ConfigValueType + section: ClassVar[str | None] + cli: ClassVar[list[str] | None] + validator: ClassVar[Callable[..., Any] | None] # See `_ValidatorType` + type: ClassVar[argparse._ActionType | None] + meta: ClassVar[str | None] + action: ClassVar[str | None] + default: ClassVar[Any] + short: ClassVar[str | None] + desc: ClassVar[str | None] + nargs: ClassVar[int | str | None] + const: ClassVar[bool | str | None] + order: ClassVar[int] + + def __init__(self) -> None: ... + def add_option(self, parser: argparse.ArgumentParser) -> None: ... + def copy(self) -> Setting: ... + def get(self) -> _ConfigValueType: ... + def set(self, val: _ConfigValueType) -> None: ... + def __lt__(self, other: Setting) -> bool: ... + + __cmp__ = __lt__ + +@overload +def validate_bool(val: bool) -> bool: ... +@overload +def validate_bool(val: None) -> None: ... +@overload +def validate_bool(val: Annotated[str, "Case-insensitive boolean string ('true'/'false' in any case)"]) -> bool: ... + +def validate_dict(val: dict[str, Any]) -> dict[str, Any]: ... +def validate_pos_int(val: ConvertibleToInt) -> int: ... +def validate_http2_frame_size(val: ConvertibleToInt) -> int: ... +def validate_ssl_version(val: _SSLMethod) -> _SSLMethod: ... + +@overload +def validate_string(val: str) -> str: ... +@overload +def validate_string(val: None) -> None: ... + +@overload +def validate_file_exists(val: str) -> str: ... +@overload +def validate_file_exists(val: None) -> None: ... + +def validate_list_string(val: str | list[str] | None) -> list[str]: ... +def validate_list_of_existing_files(val: str | list[str] | None) -> list[str]: ... +def validate_string_to_addr_list(val: str | None) -> list[str]: ... +def validate_string_to_list(val: str | None) -> list[str]: ... + +@overload +def validate_class(val: str) -> str: ... +@overload +def validate_class(val: None) -> None: ... +@overload +def validate_class(val: object) -> object: ... + +def validate_callable(arity: int) -> _CallableValidatorType: ... +def validate_user(val: int | str | None) -> int: ... +def validate_group(val: int | str | None) -> int: ... +def validate_post_request(val: str | _HookType) -> _PostRequestHookType: ... +def validate_chdir(val: str) -> str: ... + +@overload +def validate_statsd_address(val: str) -> _AddressType: ... +@overload +def validate_statsd_address(val: None) -> None: ... + +def validate_reload_engine(val: str) -> str: ... + +@overload +def validate_header_map_behaviour(val: str) -> str: ... +@overload +def validate_header_map_behaviour(val: None) -> None: ... + +def get_default_config_file() -> str | None: ... + +class ConfigFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class WSGIApp(Setting): + name: ClassVar[str] + section: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class Bind(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Backlog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Workers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class WorkerClass(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ClassValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class WorkerThreads(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class WorkerConnections(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class MaxRequests(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class MaxRequestsJitter(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Timeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class GracefulTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Keepalive(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestLine(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestFields(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class LimitRequestFieldSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Reload(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ReloadEngine(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[Callable[[str], str]] + default: ClassVar[str] + desc: ClassVar[str] + +class ReloadExtraFiles(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Spew(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ConfigCheck(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PrintConfig(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PreloadApp(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Sendfile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + const: ClassVar[bool] + desc: ClassVar[str] + +class ReusePort(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Chdir(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[Callable[[str], str]] + default: ClassVar[str] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Daemon(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Env(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class Pidfile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class WorkerTmpDir(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class User(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_UserGroupValidatorType] + default: ClassVar[int] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Group(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_UserGroupValidatorType] + default: ClassVar[int] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class Umask(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[Callable[[Any, str], int]] + default: ClassVar[int] + desc: ClassVar[str] + +class Initgroups(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class TmpUploadDir(Setting): + name: ClassVar[str] + section: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SecureSchemeHeader(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_DictValidatorType] + default: ClassVar[dict[str, str]] + desc: ClassVar[str] + +class ForwardedAllowIPS(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class AccessLog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class DisableRedirectAccessToSyslog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class AccessLogFormat(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ErrorLog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class Loglevel(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class CaptureOutput(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class LoggerClass(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ClassValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class LogConfig(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class LogConfigDict(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_DictValidatorType] + default: ClassVar[dict[str, Any]] + desc: ClassVar[str] + +class LogConfigJson(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SyslogTo(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + default_doc: ClassVar[str] + +class Syslog(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class SyslogPrefix(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SyslogFacility(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class EnableStdioInheritance(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + default: ClassVar[bool] + action: ClassVar[str] + desc: ClassVar[str] + +class StatsdHost(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[None] + validator: ClassVar[_AddressValidatorType] + desc: ClassVar[str] + +class DogstatsdTags(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[str] + validator: ClassVar[_StringValidatorType] + desc: ClassVar[str] + +class StatsdPrefix(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + default: ClassVar[str] + validator: ClassVar[_StringValidatorType] + desc: ClassVar[str] + +class BacklogMetric(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + default: ClassVar[bool] + action: ClassVar[str] + desc: ClassVar[str] + +class Procname(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class DefaultProcName(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class PythonPath(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class Paste(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class OnStarting(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnStartingHookType] + desc: ClassVar[str] + + def on_starting(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class OnReload(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnReloadHookType] + desc: ClassVar[str] + + def on_reload(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WhenReady(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WhenReadyHookType] + desc: ClassVar[str] + + def when_ready(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class Prefork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreForkHookType] + desc: ClassVar[str] + + def pre_fork(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class Postfork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostForkHookType] + desc: ClassVar[str] + + def post_fork(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PostWorkerInit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostWorkerInitHookType] + desc: ClassVar[str] + + def post_worker_init(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerInt(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerIntHookType] + desc: ClassVar[str] + + def worker_int(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerAbort(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerAbortHookType] + desc: ClassVar[str] + + def worker_abort(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PreExec(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreExecHookType] + desc: ClassVar[str] + + def pre_exec(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PreRequest(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PreRequestHookType] + desc: ClassVar[str] + + def pre_request(worker: Worker, req: Request) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class PostRequest(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_PostRequestHookType] + desc: ClassVar[str] + + def post_request(worker: Worker, req: Request, environ: _EnvironType, resp: Response) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class ChildExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_ChildExitHookType] + desc: ClassVar[str] + + def child_exit(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class WorkerExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_WorkerExitHookType] + desc: ClassVar[str] + + def worker_exit(server: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class NumWorkersChanged(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_NumWorkersChangedHookType] + desc: ClassVar[str] + + def nworkers_changed(server: Arbiter, new_value: int, old_value: int | None) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class OnExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + default: ClassVar[_OnExitHookType] + desc: ClassVar[str] + + def on_exit(server: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class NewSSLContext(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_SSLContextHookType] + desc: ClassVar[str] + + def ssl_context(config: Config, default_ssl_context_factory: Callable[[], SSLContext]) -> SSLContext: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +def validate_proxy_protocol(val: str | bool | None) -> str: ... + +class ProxyProtocol(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ProxyProtocolValidatorType] + default: ClassVar[str] + nargs: ClassVar[str] + const: ClassVar[str] + desc: ClassVar[str] + +class ProxyAllowFrom(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class Protocol(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class UWSGIAllowFrom(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class KeyFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class CertFile(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SSLVersion(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[Callable[[_SSLMethod], _SSLMethod]] + default: ClassVar[_SSLMethod] + desc: ClassVar[str] + +class CertReqs(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_IntValidatorType] + default: ClassVar[int] + desc: ClassVar[str] + +class CACerts(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +class SuppressRaggedEOFs(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + action: ClassVar[str] + default: ClassVar[bool] + validator: ClassVar[_BoolValidatorType] + desc: ClassVar[str] + +class DoHandshakeOnConnect(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class Ciphers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_StringValidatorType] + default: ClassVar[None] + desc: ClassVar[str] + +VALID_HTTP_PROTOCOLS: Final[frozenset[str]] +ALPN_PROTOCOL_MAP: Final[dict[str, str]] + +def validate_http_protocols(val: str | None) -> list[str]: ... + +class HTTPProtocols(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HTTPProtocolsValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class HTTP2MaxConcurrentStreams(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2InitialWindowSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2MaxFrameSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HTTP2FrameSizeValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HTTP2MaxHeaderListSize(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class PasteGlobalConf(Setting): + name: ClassVar[str] + action: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class PermitObsoleteFolding(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class StripHeaderSpaces(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PermitUnconventionalHTTPMethod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class PermitUnconventionalHTTPVersion(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class CasefoldHTTPMethod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] + +class ForwarderHeaders(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class HeaderMap(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +def validate_asgi_loop(val: str | None) -> str: ... +def validate_asgi_lifespan(val: str | None) -> str: ... +def validate_http_parser(val: str | None) -> str: ... + +class ASGILoop(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ASGILoopValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ASGILifespan(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_ASGILifespanValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class ASGIDisconnectGracePeriod(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class HttpParser(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_HttpParserValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class RootPath(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + desc: ClassVar[str] + +class DirtyApps(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + action: ClassVar[str] + meta: ClassVar[str] + validator: ClassVar[_ListStringValidatorType] + default: ClassVar[list[str]] + desc: ClassVar[str] + +class DirtyWorkers(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyThreads(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class DirtyGracefulTimeout(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[type[int]] + default: ClassVar[int] + desc: ClassVar[str] + +class OnDirtyStarting(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_OnDirtyStartingHookType] + desc: ClassVar[str] + + def on_dirty_starting(arbiter: Arbiter) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyPostFork(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyPostForkHookType] + desc: ClassVar[str] + + def dirty_post_fork(arbiter: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyWorkerInit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyWorkerInitHookType] + desc: ClassVar[str] + + def dirty_worker_init(worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class DirtyWorkerExit(Setting): + name: ClassVar[str] + section: ClassVar[str] + validator: ClassVar[_CallableValidatorType] + type: ClassVar[Callable[..., Any]] + default: ClassVar[_DirtyWorkerExitHookType] + desc: ClassVar[str] + + def dirty_worker_exit(arbiter: Arbiter, worker: Worker) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # pyrefly: ignore [invalid-annotation] + +class ControlSocket(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_StringValidatorType] + default: ClassVar[str] + default_doc: ClassVar[str] + desc: ClassVar[str] + +class ControlSocketMode(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + meta: ClassVar[str] + validator: ClassVar[_IntValidatorType] + type: ClassVar[Callable[[Any, str], int]] + default: ClassVar[int] + desc: ClassVar[str] + +class ControlSocketDisable(Setting): + name: ClassVar[str] + section: ClassVar[str] + cli: ClassVar[list[str]] + validator: ClassVar[_BoolValidatorType] + action: ClassVar[str] + default: ClassVar[bool] + desc: ClassVar[str] diff --git a/stubs/gunicorn/gunicorn/ctl/__init__.pyi b/stubs/gunicorn/gunicorn/ctl/__init__.pyi new file mode 100644 index 000000000000..03f497fa809f --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/__init__.pyi @@ -0,0 +1,5 @@ +from gunicorn.ctl.client import ControlClient as ControlClient +from gunicorn.ctl.protocol import ControlProtocol as ControlProtocol +from gunicorn.ctl.server import ControlSocketServer as ControlSocketServer + +__all__ = ["ControlSocketServer", "ControlClient", "ControlProtocol"] diff --git a/stubs/gunicorn/gunicorn/ctl/cli.pyi b/stubs/gunicorn/gunicorn/ctl/cli.pyi new file mode 100644 index 000000000000..e0e4775c6910 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/cli.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +def format_workers(data: dict[str, Incomplete]) -> str: ... +def format_dirty(data: dict[str, Incomplete]) -> str: ... +def format_stats(data: dict[str, Incomplete]) -> str: ... +def format_listeners(data: dict[str, Incomplete]) -> str: ... +def format_config(data: dict[str, Incomplete]) -> str: ... +def format_help(data: dict[str, Incomplete]) -> str: ... +def format_all(data: dict[str, Incomplete]) -> str: ... +def format_response(command: str, data: dict[str, Incomplete]) -> str: ... +def run_command(socket_path: str, command: str, json_output: bool = False) -> int: ... +def run_interactive(socket_path: str, json_output: bool = False) -> int: ... +def main() -> int: ... diff --git a/stubs/gunicorn/gunicorn/ctl/client.pyi b/stubs/gunicorn/gunicorn/ctl/client.pyi new file mode 100644 index 000000000000..7cc5912eed33 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/client.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete, Unused +from typing_extensions import Self + +class ControlClientError(Exception): ... + +class ControlClient: + socket_path: str + timeout: float + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def send_command(self, command: str, args: list[str] | None = None) -> dict[Incomplete, Incomplete]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + +def parse_command(line: str) -> tuple[str, list[str]]: ... diff --git a/stubs/gunicorn/gunicorn/ctl/handlers.pyi b/stubs/gunicorn/gunicorn/ctl/handlers.pyi new file mode 100644 index 000000000000..7814cef1cb3c --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/handlers.pyi @@ -0,0 +1,113 @@ +from _typeshed import Incomplete +from typing import Literal, TypedDict, type_check_only +from typing_extensions import NotRequired + +from gunicorn.arbiter import Arbiter + +@type_check_only +class _Worker(TypedDict): + pid: int + age: int + booted: bool + last_heartbeat: float + aborted: NotRequired[bool] + apps: NotRequired[list[str]] + +@type_check_only +class _ShowWorkersReturnType(TypedDict): + workers: list[_Worker] + count: int + +@type_check_only +class _App(TypedDict): + import_path: str + worker_count: int | None + current_workers: int + worker_pids: list[int] + +@type_check_only +class _ShowDirtyReturnType(TypedDict): + enabled: bool + pid: int | None + workers: list[_Worker] + apps: list[_App] + +@type_check_only +class _ShowStatsReturnType(TypedDict): + uptime: float | None + pid: int + workers_current: int + workers_target: int + workers_spawned: int + workers_killed: int + reloads: int + dirty_arbiter_pid: int | None + +@type_check_only +class _ListenerInfo(TypedDict): + address: str + fd: int + type: Literal["unix", "tcp", "tcp6", "unknown"] + +@type_check_only +class _ShowListenersReturnType(TypedDict): + listeners: list[_ListenerInfo] + count: int + +@type_check_only +class _WorkerAddReturnType(TypedDict): + added: int + previous: int + total: int + +@type_check_only +class _WorkerRemovedReturnType(TypedDict): + removed: int + previous: int + total: int + +@type_check_only +class _WorkerKillSucessReturnType(TypedDict): + success: Literal[True] + killed: int + +@type_check_only +class _WorkerKillFailedReturnType(TypedDict): + success: Literal[False] + error: str + +@type_check_only +class _ReloadReturnType(TypedDict): + status: Literal["reloading"] + +@type_check_only +class _ReopenReturnType(TypedDict): + status: Literal["reopening"] + +@type_check_only +class _ShutdownReturnType(TypedDict): + status: Literal["shutting_down"] + mode: str + +@type_check_only +class _HelpReturnType(TypedDict): + commands: dict[str, str] + +class CommandHandlers: + arbiter: Arbiter + def __init__(self, arbiter: Arbiter) -> None: ... + def show_workers(self) -> _ShowWorkersReturnType: ... + def show_dirty(self) -> _ShowDirtyReturnType: ... + def show_config(self) -> dict[str, Incomplete]: ... + def show_stats(self) -> _ShowStatsReturnType: ... + def show_listeners(self) -> _ShowListenersReturnType: ... + def worker_add(self, count: int = 1) -> _WorkerAddReturnType: ... + def worker_remove(self, count: int = 1) -> _WorkerRemovedReturnType: ... + def worker_kill(self, pid: int) -> _WorkerKillSucessReturnType | _WorkerKillFailedReturnType: ... + def dirty_add(self, count: int = 1) -> dict[str, Incomplete]: ... + def dirty_remove(self, count: int = 1) -> dict[str, Incomplete]: ... + def reload(self) -> _ReloadReturnType: ... + def reopen(self) -> _ReopenReturnType: ... + def shutdown(self, mode: str = "graceful") -> _ShutdownReturnType: ... + def show_all(self) -> dict[str, Incomplete]: ... + def help(self) -> _HelpReturnType: ... diff --git a/stubs/gunicorn/gunicorn/ctl/protocol.pyi b/stubs/gunicorn/gunicorn/ctl/protocol.pyi new file mode 100644 index 000000000000..c4a8a62cee27 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/protocol.pyi @@ -0,0 +1,45 @@ +from asyncio import StreamReader, StreamWriter +from socket import socket +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _CtlRequest(TypedDict): + id: int + command: str + args: list[str] + +@type_check_only +class _CtlSuccessResponse(TypedDict): + id: int + status: Literal["ok"] + data: dict[str, Any] + +@type_check_only +class _CtlErrorResponse(TypedDict): + id: int + status: Literal["error"] + error: str + +_CtlResponse: TypeAlias = _CtlSuccessResponse | _CtlErrorResponse +_CtlMessage: TypeAlias = _CtlRequest | _CtlResponse + +class ProtocolError(Exception): ... + +class ControlProtocol: + MAX_MESSAGE_SIZE: ClassVar[int] + @staticmethod + def encode_message(data: _CtlMessage) -> bytes: ... + @staticmethod + def decode_message(data: bytes) -> _CtlMessage: ... + @staticmethod + def read_message(sock: socket) -> _CtlMessage: ... + @staticmethod + def write_message(sock: socket, data: _CtlMessage) -> None: ... + @staticmethod + async def read_message_async(reader: StreamReader) -> _CtlMessage: ... + @staticmethod + async def write_message_async(writer: StreamWriter, data: _CtlMessage) -> None: ... + +def make_request(request_id: int, command: str, args: list[str] | None = None) -> _CtlRequest: ... +def make_response(request_id: int, data: dict[str, Any] | None = None) -> _CtlSuccessResponse: ... +def make_error_response(request_id: int, error: str) -> _CtlErrorResponse: ... diff --git a/stubs/gunicorn/gunicorn/ctl/server.pyi b/stubs/gunicorn/gunicorn/ctl/server.pyi new file mode 100644 index 000000000000..0ab97c7a2df9 --- /dev/null +++ b/stubs/gunicorn/gunicorn/ctl/server.pyi @@ -0,0 +1,11 @@ +from gunicorn.arbiter import Arbiter +from gunicorn.ctl.handlers import CommandHandlers + +class ControlSocketServer: + arbiter: Arbiter + socket_path: str + socket_mode: int + handlers: CommandHandlers + def __init__(self, arbiter: Arbiter, socket_path: str, socket_mode: int = 0o600) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/debug.pyi b/stubs/gunicorn/gunicorn/debug.pyi new file mode 100644 index 000000000000..8769f873c587 --- /dev/null +++ b/stubs/gunicorn/gunicorn/debug.pyi @@ -0,0 +1,18 @@ +__all__ = ["spew", "unspew"] + +from collections.abc import Container +from types import FrameType +from typing import Any +from typing_extensions import Self + +class Spew: + trace_names: Container[str] | None = None + show_values: bool + + def __init__(self, trace_names: Container[str] | None = None, show_values: bool = True) -> None: ... + def __call__( + self, frame: FrameType, event: str, arg: Any # `arg` is not used inside the function, stub is set Any + ) -> Self: ... + +def spew(trace_names: Container[str] | None = None, show_values: bool = False) -> None: ... +def unspew() -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/__init__.pyi b/stubs/gunicorn/gunicorn/dirty/__init__.pyi new file mode 100644 index 000000000000..9d0294631e6f --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/__init__.pyi @@ -0,0 +1,51 @@ +from . import stash as stash +from .app import DirtyApp as DirtyApp +from .arbiter import DirtyArbiter as DirtyArbiter +from .client import ( + DirtyClient as DirtyClient, + close_dirty_client as close_dirty_client, + close_dirty_client_async as close_dirty_client_async, + get_dirty_client as get_dirty_client, + get_dirty_client_async as get_dirty_client_async, + set_dirty_socket_path as set_dirty_socket_path, +) +from .errors import ( + DirtyAppError as DirtyAppError, + DirtyAppNotFoundError as DirtyAppNotFoundError, + DirtyConnectionError as DirtyConnectionError, + DirtyError as DirtyError, + DirtyProtocolError as DirtyProtocolError, + DirtyTimeoutError as DirtyTimeoutError, + DirtyWorkerError as DirtyWorkerError, +) +from .stash import ( + StashClient as StashClient, + StashError as StashError, + StashKeyNotFoundError as StashKeyNotFoundError, + StashTable as StashTable, + StashTableNotFoundError as StashTableNotFoundError, +) + +__all__ = [ + "DirtyError", + "DirtyTimeoutError", + "DirtyConnectionError", + "DirtyWorkerError", + "DirtyAppError", + "DirtyAppNotFoundError", + "DirtyProtocolError", + "DirtyApp", + "DirtyClient", + "get_dirty_client", + "get_dirty_client_async", + "close_dirty_client", + "close_dirty_client_async", + "stash", + "StashClient", + "StashTable", + "StashError", + "StashTableNotFoundError", + "StashKeyNotFoundError", + "DirtyArbiter", + "set_dirty_socket_path", +] diff --git a/stubs/gunicorn/gunicorn/dirty/app.pyi b/stubs/gunicorn/gunicorn/dirty/app.pyi new file mode 100644 index 000000000000..c2355e8c438c --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/app.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Any + +class DirtyApp: + workers: Incomplete | None + + def init(self) -> None: ... + def __call__( + self, action: str, *args: Any, **kwargs: Any + ) -> Any: ... # Arguments and result depend on method name passed to action + def close(self) -> None: ... + +def parse_dirty_app_spec(spec: str) -> tuple[str, int | None]: ... +def load_dirty_app(import_path: str): ... +def load_dirty_apps(import_paths: Iterable[str]) -> dict[str, Incomplete]: ... +def get_app_workers_attribute(import_path: str) -> int | None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/arbiter.pyi b/stubs/gunicorn/gunicorn/dirty/arbiter.pyi new file mode 100644 index 000000000000..c1e9114c29a3 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/arbiter.pyi @@ -0,0 +1,48 @@ +import asyncio +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from signal import Signals +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.dirty.worker import DirtyWorker +from gunicorn.glogging import Logger as GLogger + +class DirtyArbiter: + SIGNALS: ClassVar[list[Signals]] + WORKER_BOOT_ERROR: ClassVar[int] + cfg: Config + log: GLogger + pid: int | None + ppid: int + pidfile: str | None + tmpdir: str + socket_path: str + workers: dict[int, DirtyWorker] + worker_sockets: dict[int, str] + worker_connections: dict[int, tuple[Incomplete, Incomplete]] + worker_queues: dict[int, asyncio.Queue[Incomplete]] + worker_consumers: dict[int, asyncio.Task[None]] + worker_age: int + alive: bool + num_workers: int + app_specs: dict[str, dict[Incomplete, Incomplete]] + app_worker_map: dict[str, set[Incomplete]] + worker_app_map: dict[int, list[Incomplete]] + stash_tables: dict[str, dict[Incomplete, Incomplete]] + + def __init__(self, cfg: Config, log: GLogger, socket_path: str | None = None, pidfile: str | None = None) -> None: ... + def run(self) -> None: ... + def init_signals(self) -> None: ... + async def handle_client(self, reader: StreamReader, writer: StreamWriter) -> None: ... + async def route_request(self, request: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_status_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_manage_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def handle_stash_request(self, message: dict[str, Incomplete], client_writer: StreamWriter) -> None: ... + async def manage_workers(self) -> None: ... + def spawn_worker(self, force_all_apps: bool = False) -> int | None: ... + def kill_worker(self, pid: int, sig: int) -> None: ... + async def murder_workers(self) -> None: ... + def reap_workers(self) -> None: ... + async def reload(self) -> None: ... + async def stop(self, graceful: bool = True) -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/client.pyi b/stubs/gunicorn/gunicorn/dirty/client.pyi new file mode 100644 index 000000000000..3d77eb9a31df --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/client.pyi @@ -0,0 +1,74 @@ +from _typeshed import Incomplete +from types import TracebackType +from typing import Any, ClassVar +from typing_extensions import Self + +class DirtyClient: + socket_path: str + timeout: float + + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def connect(self) -> None: ... + # Arguments and result depend on app path and method name passed to action + def execute(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> Any: ... + def stream(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> DirtyStreamIterator: ... + def close(self) -> None: ... + async def connect_async(self) -> None: ... + async def execute_async(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> Any: ... + def stream_async(self, app_path: str, action: str, *args: Any, **kwargs: Any) -> DirtyAsyncStreamIterator: ... + async def close_async(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class DirtyStreamIterator: + DEFAULT_IDLE_TIMEOUT: ClassVar[float] + client: DirtyClient + app_path: str + action: str + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + + def __init__( + self, + client: DirtyClient, + app_path: str, + action: str, + args: tuple[Incomplete, ...], + kwargs: dict[str, Incomplete], + idle_timeout: float | None = None, + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> Incomplete | None: ... + +class DirtyAsyncStreamIterator: + DEFAULT_IDLE_TIMEOUT: ClassVar[float] + client: DirtyClient + app_path: str + action: str + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + + def __init__( + self, + client: DirtyClient, + app_path: str, + action: str, + args: tuple[Incomplete, ...], + kwargs: dict[str, Incomplete], + idle_timeout: float | None = None, + ) -> None: ... + def __aiter__(self) -> Self: ... + async def __anext__(self) -> Incomplete | None: ... + +def set_dirty_socket_path(path: str) -> None: ... +def get_dirty_socket_path() -> str: ... +def get_dirty_client(timeout: float = 30.0) -> DirtyClient: ... +async def get_dirty_client_async(timeout: float = 30.0) -> DirtyClient: ... +def close_dirty_client() -> None: ... +async def close_dirty_client_async() -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/errors.pyi b/stubs/gunicorn/gunicorn/dirty/errors.pyi new file mode 100644 index 000000000000..0bfd9ed341ab --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/errors.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + +@type_check_only +class _DirtyErrorDict(TypedDict): + error_type: str + message: str + details: dict[str, Incomplete] + +class DirtyError(Exception): + message: str + details: dict[str, Incomplete] + + def __init__(self, message: str, details: dict[str, Incomplete] | None = None) -> None: ... + def to_dict(self) -> _DirtyErrorDict: ... + @classmethod + def from_dict(cls, data: dict[str, Incomplete]) -> DirtyError: ... + +class DirtyTimeoutError(DirtyError): + timeout: float | None + + def __init__(self, message: str = "Operation timed out", timeout: float | None = None) -> None: ... + +class DirtyConnectionError(DirtyError): + socket_path: str | None + + def __init__(self, message: str = "Connection failed", socket_path: str | None = None) -> None: ... + +class DirtyWorkerError(DirtyError): + worker_id: int | None + traceback: str | None + + def __init__(self, message: str, worker_id: int | None = None, traceback: str | None = None) -> None: ... + +class DirtyAppError(DirtyError): + app_path: str | None + action: str | None + traceback: str | None + + def __init__( + self, message: str, app_path: str | None = None, action: str | None = None, traceback: str | None = None + ) -> None: ... + +class DirtyAppNotFoundError(DirtyAppError): + app_path: str + + def __init__(self, app_path: str) -> None: ... + +class DirtyNoWorkersAvailableError(DirtyError): + app_path: str + + def __init__(self, app_path: str, message: str | None = None) -> None: ... + +class DirtyProtocolError(DirtyError): + def __init__(self, message: str = "Protocol error", raw_data: str | bytes | None = None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/dirty/protocol.pyi b/stubs/gunicorn/gunicorn/dirty/protocol.pyi new file mode 100644 index 000000000000..66135ae193bf --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/protocol.pyi @@ -0,0 +1,171 @@ +import asyncio +import socket +from _typeshed import Incomplete +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +from .errors import _DirtyErrorDict + +MAGIC: Final = b"GD" +VERSION: Final = 0x01 +MSG_TYPE_REQUEST: Final = 0x01 +MSG_TYPE_RESPONSE: Final = 0x02 +MSG_TYPE_ERROR: Final = 0x03 +MSG_TYPE_CHUNK: Final = 0x04 +MSG_TYPE_END: Final = 0x05 +MSG_TYPE_STASH: Final = 0x10 +MSG_TYPE_STATUS: Final = 0x11 +MSG_TYPE_MANAGE: Final = 0x12 +MSG_TYPE_REQUEST_STR: Final = "request" +MSG_TYPE_RESPONSE_STR: Final = "response" +MSG_TYPE_ERROR_STR: Final = "error" +MSG_TYPE_CHUNK_STR: Final = "chunk" +MSG_TYPE_END_STR: Final = "end" +MSG_TYPE_STASH_STR: Final = "stash" +MSG_TYPE_STATUS_STR: Final = "status" +MSG_TYPE_MANAGE_STR: Final = "manage" +MSG_TYPE_TO_STR: Final[dict[int, str]] +MSG_TYPE_FROM_STR: Final[dict[str, int]] +STASH_OP_PUT: Final = 1 +STASH_OP_GET: Final = 2 +STASH_OP_DELETE: Final = 3 +STASH_OP_KEYS: Final = 4 +STASH_OP_CLEAR: Final = 5 +STASH_OP_INFO: Final = 6 +STASH_OP_ENSURE: Final = 7 +STASH_OP_DELETE_TABLE: Final = 8 +STASH_OP_TABLES: Final = 9 +STASH_OP_EXISTS: Final = 10 +MANAGE_OP_ADD: Final = 1 +MANAGE_OP_REMOVE: Final = 2 +HEADER_FORMAT: Final = ">2sBBIQ" +HEADER_SIZE: Final[int] +MAX_MESSAGE_SIZE: Final = 67108864 + +@type_check_only +class _DirtyRequest(TypedDict): + type: Literal["request"] + id: int | str + app_path: str + action: str + args: list[Incomplete] + kwargs: dict[str, Incomplete] + +@type_check_only +class _DirtyResponse(TypedDict): + type: Literal["response"] + id: int | str + result: Incomplete + +@type_check_only +class _DirtyErrorResponse(TypedDict): + type: Literal["error"] + id: int | str + error: _DirtyErrorDict | dict[str, Incomplete] + +@type_check_only +class _DirtyChunkMessage(TypedDict): + type: Literal["chunk"] + id: int | str + data: Incomplete + +@type_check_only +class _DirtyEndMessage(TypedDict): + type: Literal["end"] + id: int | str + +@type_check_only +class _DirtyStashMessage(TypedDict): + type: Literal["stash"] + id: int | str + op: int + table: str + key: NotRequired[Incomplete] + value: NotRequired[Incomplete] + pattern: NotRequired[Incomplete] + +@type_check_only +class _DirtyManageMessage(TypedDict): + type: Literal["manage"] + id: int | str + op: int + count: int + +_DirtyMessage: TypeAlias = ( + _DirtyRequest + | _DirtyResponse + | _DirtyErrorResponse + | _DirtyChunkMessage + | _DirtyEndMessage + | _DirtyStashMessage + | _DirtyManageMessage +) + +class BinaryProtocol: + HEADER_SIZE: ClassVar[int] + MAX_MESSAGE_SIZE: ClassVar[int] + MSG_TYPE_REQUEST: ClassVar[str] + MSG_TYPE_RESPONSE: ClassVar[str] + MSG_TYPE_ERROR: ClassVar[str] + MSG_TYPE_CHUNK: ClassVar[str] + MSG_TYPE_END: ClassVar[str] + MSG_TYPE_STASH: ClassVar[str] + MSG_TYPE_STATUS: ClassVar[str] + MSG_TYPE_MANAGE: ClassVar[str] + + @staticmethod + def encode_header(msg_type: int, request_id: int, payload_length: int) -> bytes: ... + @staticmethod + def decode_header(data: bytes) -> tuple[int, int, int]: ... + @staticmethod + def encode_request( + request_id: int, + app_path: str, + action: str, + args: tuple[Incomplete, ...] | None = None, + kwargs: dict[str, Incomplete] | None = None, + ) -> bytes: ... + @staticmethod + def encode_response(request_id: int, result) -> bytes: ... + @staticmethod + def encode_error(request_id: int, error: BaseException | dict[str, Incomplete]) -> bytes: ... + @staticmethod + def encode_chunk(request_id: int, data) -> bytes: ... + @staticmethod + def encode_end(request_id: int) -> bytes: ... + @staticmethod + def encode_status(request_id: int) -> bytes: ... + @staticmethod + def encode_manage(request_id: int, op: int, count: int = 1) -> bytes: ... + @staticmethod + def encode_stash(request_id: int, op: int, table: str, key=None, value=None, pattern=None) -> bytes: ... + @staticmethod + def decode_message(data: bytes) -> tuple[str, int, Incomplete]: ... + @staticmethod + async def read_message_async(reader: asyncio.StreamReader) -> _DirtyMessage: ... + @staticmethod + async def write_message_async(writer: asyncio.StreamWriter, message: _DirtyMessage) -> None: ... + @staticmethod + def _recv_exactly(sock: socket.socket, n: int) -> bytes: ... + @staticmethod + def read_message(sock: socket.socket) -> _DirtyMessage: ... + @staticmethod + def write_message(sock: socket.socket, message: _DirtyMessage) -> None: ... + @staticmethod + def _encode_from_dict(message: _DirtyMessage) -> bytes: ... + +DirtyProtocol = BinaryProtocol + +def make_request( + request_id: int | str, + app_path: str, + action: str, + args: tuple[Incomplete, ...] | None = None, + kwargs: dict[str, Incomplete] | None = None, +) -> _DirtyRequest: ... +def make_response(request_id: int | str, result) -> _DirtyResponse: ... +def make_error_response(request_id: int | str, error) -> _DirtyErrorResponse: ... +def make_chunk_message(request_id: int | str, data) -> _DirtyChunkMessage: ... +def make_end_message(request_id: int | str) -> _DirtyEndMessage: ... +def make_stash_message(request_id: int | str, op: int, table: str, key=None, value=None, pattern=None) -> _DirtyStashMessage: ... +def make_manage_message(request_id: int | str, op: int, count: int = 1) -> _DirtyManageMessage: ... diff --git a/stubs/gunicorn/gunicorn/dirty/stash.pyi b/stubs/gunicorn/gunicorn/dirty/stash.pyi new file mode 100644 index 000000000000..113180170b71 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/stash.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from types import TracebackType +from typing_extensions import Self + +from .errors import DirtyError + +class StashError(DirtyError): ... + +class StashTableNotFoundError(StashError): + table_name: str + + def __init__(self, table_name: str) -> None: ... + +class StashKeyNotFoundError(StashError): + table_name: str + key: str + + def __init__(self, table_name: str, key: str) -> None: ... + +class StashClient: + socket_path: str + timeout: float + + def __init__(self, socket_path: str, timeout: float = 30.0) -> None: ... + def put(self, table: str, key: str, value) -> None: ... + def get(self, table: str, key: str, default=None): ... + def delete(self, table: str, key: str) -> bool: ... + def keys(self, table: str, pattern: str | None = None) -> list[str]: ... + def clear(self, table: str) -> None: ... + def info(self, table: str) -> dict[str, Incomplete]: ... + def ensure(self, table: str) -> None: ... + def exists(self, table: str, key=None) -> bool: ... + def delete_table(self, table: str) -> None: ... + def tables(self) -> list[str]: ... + def table(self, name: str) -> StashTable: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class StashTable: + def __init__(self, client: StashClient, name: str) -> None: ... + @property + def name(self) -> str: ... + def __getitem__(self, key: str): ... + def __setitem__(self, key: str, value) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __contains__(self, key: str) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def get(self, key: str, default=None): ... + def keys(self, pattern: str | None = None) -> list[str]: ... + def clear(self) -> None: ... + def items(self) -> Iterator[tuple[Incomplete, Incomplete]]: ... + def values(self) -> Iterator[Incomplete]: ... + +def set_stash_socket_path(path: str) -> None: ... +def get_stash_socket_path() -> str: ... +def put(table: str, key: str, value) -> None: ... +def get(table: str, key: str, default=None): ... +def delete(table: str, key: str) -> bool: ... +def keys(table: str, pattern: str | None = None) -> list[str]: ... +def clear(table: str) -> None: ... +def info(table: str) -> dict[str, Incomplete]: ... +def ensure(table: str) -> None: ... +def exists(table: str, key: str | None = None) -> bool: ... +def delete_table(table: str) -> None: ... +def tables() -> list[str]: ... +def table(name: str) -> StashTable: ... diff --git a/stubs/gunicorn/gunicorn/dirty/tlv.pyi b/stubs/gunicorn/gunicorn/dirty/tlv.pyi new file mode 100644 index 000000000000..abc9f1432a34 --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/tlv.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from typing import Final + +TYPE_NONE: Final = 0x00 +TYPE_BOOL: Final = 0x01 +TYPE_INT64: Final = 0x05 +TYPE_FLOAT64: Final = 0x06 +TYPE_BYTES: Final = 0x10 +TYPE_STRING: Final = 0x11 +TYPE_LIST: Final = 0x20 +TYPE_DICT: Final = 0x21 +MAX_STRING_SIZE: Final = 67108864 +MAX_BYTES_SIZE: Final = 67108864 +MAX_LIST_SIZE: Final = 1048576 +MAX_DICT_SIZE: Final = 1048576 + +class TLVEncoder: + @staticmethod + def encode( + value: bool | float | str | bytes | list[Incomplete] | tuple[Incomplete, ...] | dict[object, Incomplete] | None, + ) -> bytes: ... # dict key passed to `str()` function + @staticmethod + def decode(data: bytes, offset: int = 0) -> tuple[Incomplete, int]: ... + @staticmethod + def decode_full(data: bytes): ... diff --git a/stubs/gunicorn/gunicorn/dirty/worker.pyi b/stubs/gunicorn/gunicorn/dirty/worker.pyi new file mode 100644 index 000000000000..2d6d93817d4c --- /dev/null +++ b/stubs/gunicorn/gunicorn/dirty/worker.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from collections.abc import Iterable, Mapping +from signal import Signals +from typing import Any, ClassVar, Literal + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers.workertmp import WorkerTmp + +class DirtyWorker: + SIGNALS: ClassVar[list[Signals]] + age: int + pid: int | Literal["[booting]"] + ppid: int + app_paths: list[str] + cfg: Config + log: GLogger + socket_path: str + booted: bool + aborted: bool + alive: bool + tmp: WorkerTmp + apps: dict[str, Incomplete] + + def __init__(self, age: int, ppid: int, app_paths: list[str], cfg: Config, log: GLogger, socket_path: str) -> None: ... + def notify(self) -> None: ... + def init_process(self) -> None: ... + def init_signals(self) -> None: ... + def load_apps(self) -> None: ... + def run(self) -> None: ... + async def handle_connection(self, reader: StreamReader, writer: StreamWriter) -> None: ... + async def handle_request(self, message: dict[str, Incomplete], writer: StreamWriter) -> None: ... + async def execute( + self, app_path: str, action: str, args: Iterable[Any], kwargs: Mapping[str, Any] + ) -> Any: ... # Arguments and result depend on method name passed to action diff --git a/stubs/gunicorn/gunicorn/errors.pyi b/stubs/gunicorn/gunicorn/errors.pyi new file mode 100644 index 000000000000..f25818c3ff07 --- /dev/null +++ b/stubs/gunicorn/gunicorn/errors.pyi @@ -0,0 +1,8 @@ +class HaltServer(BaseException): + reason: str + exit_status: int + + def __init__(self, reason: str, exit_status: int = 1) -> None: ... + +class ConfigError(Exception): ... +class AppImportError(Exception): ... diff --git a/stubs/gunicorn/gunicorn/glogging.pyi b/stubs/gunicorn/gunicorn/glogging.pyi new file mode 100644 index 000000000000..964c528bd95b --- /dev/null +++ b/stubs/gunicorn/gunicorn/glogging.pyi @@ -0,0 +1,159 @@ +import logging +import threading +from collections.abc import Mapping +from datetime import timedelta +from logging.config import _DictConfigArgs +from socket import SocketKind +from typing import Annotated, Any, ClassVar, Literal, TypeAlias, TypedDict, type_check_only + +from gunicorn.http import Request +from gunicorn.http.wsgi import Response + +from ._types import _EnvironType +from .config import Config + +SYSLOG_FACILITIES: dict[str, int] + +@type_check_only +class _AtomsDict(TypedDict, total=False): + h: str + l: str + u: str + t: str + r: str + s: str + m: str | None + U: str | None + q: str | None + H: str | None + b: str + B: int | None + f: str + a: str + T: int + D: int + M: int + L: str + p: str + +_CriticalIntType: TypeAlias = Annotated[int, "50"] +_ErrorIntType: TypeAlias = Annotated[int, "40"] +_WarningIntType: TypeAlias = Annotated[int, "30"] +_InfoIntType: TypeAlias = Annotated[int, "20"] +_DebugIntType: TypeAlias = Annotated[int, "10"] +_LogLevelIntType: TypeAlias = _CriticalIntType | _ErrorIntType | _WarningIntType | _InfoIntType | _DebugIntType +_LogLevelStrType: TypeAlias = Literal["critical", "error", "warning", "info", "debug"] +_LogLevelType: TypeAlias = _LogLevelIntType | _LogLevelStrType + +CONFIG_DEFAULTS: _DictConfigArgs + +def loggers() -> list[logging.Logger]: ... + +class SafeAtoms(dict[str, Any]): + def __init__(self, atoms: dict[str, Any]) -> None: ... + def __getitem__(self, k: str) -> str: ... + +_SyslogAddressType: TypeAlias = ( + tuple[Literal[SocketKind.SOCK_DGRAM] | None, str] # Unix Socket + | tuple[Literal[SocketKind.SOCK_DGRAM, SocketKind.SOCK_STREAM], tuple[str, int]] # TCP/UDP Socket +) + +def parse_syslog_address(addr: str) -> _SyslogAddressType: ... + +@type_check_only +class _LogLevels(TypedDict): + critical: _CriticalIntType + error: _ErrorIntType + warning: _WarningIntType + info: _InfoIntType + debug: _DebugIntType + +class Logger: + LOG_LEVELS: ClassVar[_LogLevels] + loglevel: ClassVar[_LogLevelIntType] + error_fmt: ClassVar[str] + datefmt: ClassVar[str] + access_fmt: ClassVar[str] + syslog_fmt: ClassVar[str] + atoms_wrapper_class: ClassVar[type[SafeAtoms]] + error_log: logging.Logger + access_log: logging.Logger + error_handlers: list[logging.Handler] + access_handlers: list[logging.Handler] + logfile: Any | None + lock: threading.Lock + cfg: Config + + def __init__(self, cfg: Config) -> None: ... + def setup(self, cfg: Config) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def debug( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + lvl: _LogLevelType, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def atoms(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> _AtomsDict: ... + @property + def access_log_enabled(self) -> bool: ... + def access(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> None: ... + def now(self) -> str: ... + def reopen_files(self) -> None: ... + def close_on_exec(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http/__init__.pyi b/stubs/gunicorn/gunicorn/http/__init__.pyi new file mode 100644 index 000000000000..8265485b044a --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/__init__.pyi @@ -0,0 +1,25 @@ +import socket +from collections.abc import Iterable +from typing import Literal, overload + +from gunicorn.config import Config +from gunicorn.http.message import Message as Message, Request as Request +from gunicorn.http.parser import RequestParser as RequestParser +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.uwsgi.parser import UWSGIParser + +from .._types import _AddressType + +@overload +def get_parser( + cfg: Config, + source: socket.socket | Iterable[bytes], + source_addr: _AddressType, + http2_connection: Literal[False] | None = False, +) -> UWSGIParser | RequestParser: ... +@overload +def get_parser( + cfg: Config, source: socket.socket | Iterable[bytes], source_addr: _AddressType, http2_connection: Literal[True] = ... +) -> HTTP2ServerConnection: ... + +__all__ = ["Message", "Request", "RequestParser", "get_parser"] diff --git a/stubs/gunicorn/gunicorn/http/body.pyi b/stubs/gunicorn/gunicorn/http/body.pyi new file mode 100644 index 000000000000..a8ac9a698588 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/body.pyi @@ -0,0 +1,48 @@ +import io +from collections.abc import Callable, Generator, Iterator +from typing import TypeAlias + +from gunicorn.http.message import Request +from gunicorn.http.unreader import Unreader + +class ChunkedReader: + req: Request + parser: Generator[bytes] | None + buf: io.BytesIO + + def __init__(self, req: Request, unreader: Unreader) -> None: ... + def read(self, size: int) -> bytes: ... + def parse_trailers(self, unreader: Unreader, data: bytes) -> None: ... + def parse_chunked(self, unreader: Unreader) -> Generator[bytes]: ... + def parse_chunk_size(self, unreader: Unreader, data: bytes | None = None) -> tuple[int, bytes | None]: ... + def get_data(self, unreader: Unreader, buf: io.BytesIO) -> None: ... + +class LengthReader: + unreader: Unreader + length: int + + def __init__(self, unreader: Unreader, length: int) -> None: ... + def read(self, size: int) -> bytes: ... + +class EOFReader: + unreader: Unreader + buf: io.BytesIO + finished: bool + + def __init__(self, unreader: Unreader) -> None: ... + def read(self, size: int) -> bytes: ... + +_ReaderType: TypeAlias = ChunkedReader | LengthReader | EOFReader + +class Body: + reader: _ReaderType + buf: io.BytesIO + + def __init__(self, reader: _ReaderType) -> None: ... + def __iter__(self) -> Iterator[bytes]: ... + def __next__(self) -> bytes: ... + next: Callable[[Body], bytes] + def getsize(self, size: int | None) -> int: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, size: int | None = None) -> list[bytes]: ... diff --git a/stubs/gunicorn/gunicorn/http/errors.pyi b/stubs/gunicorn/gunicorn/http/errors.pyi new file mode 100644 index 000000000000..a7698a0973bc --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/errors.pyi @@ -0,0 +1,104 @@ +from typing_extensions import Buffer + +from gunicorn.http import Message + +class ParseException(Exception): ... + +class NoMoreData(IOError): + buf: Buffer + + def __init__(self, buf: Buffer | None = None) -> None: ... + +class ConfigurationProblem(ParseException): + info: str + code: int + + def __init__(self, info: str) -> None: ... + +class InvalidRequestLine(ParseException): + req: str + code: int + + def __init__(self, req: str) -> None: ... + +class InvalidRequestMethod(ParseException): + method: str + + def __init__(self, method: str) -> None: ... + +class ExpectationFailed(ParseException): + expect: str + + def __init__(self, expect: str) -> None: ... + +class InvalidHTTPVersion(ParseException): + version: str | tuple[int, int] + + def __init__(self, version: str | tuple[int, int]) -> None: ... + +class InvalidHeader(ParseException): + hdr: str + req: Message | None + + def __init__(self, hdr: str, req: Message | None = None) -> None: ... + +class ObsoleteFolding(ParseException): + hdr: str + + def __init__(self, hdr: str) -> None: ... + +class InvalidHeaderName(ParseException): + hdr: str + + def __init__(self, hdr: str) -> None: ... + +class UnsupportedTransferCoding(ParseException): + hdr: str + code: int + + def __init__(self, hdr: str) -> None: ... + +class InvalidChunkSize(IOError): + data: bytes + + def __init__(self, data: bytes) -> None: ... + +class ChunkMissingTerminator(IOError): + term: bytes + + def __init__(self, term: bytes) -> None: ... + +class InvalidChunkExtension(IOError): + reason: str + def __init__(self, reason: str) -> None: ... + +class LimitRequestLine(ParseException): + size: int + max_size: int | None + + def __init__(self, size: int, max_size: int | None = None) -> None: ... + +class LimitRequestHeaders(ParseException): + msg: str + + def __init__(self, msg: str) -> None: ... + +class InvalidProxyLine(ParseException): + line: str + code: int + + def __init__(self, line: str) -> None: ... + +class InvalidProxyHeader(ParseException): + msg: str + code: int + + def __init__(self, msg: str) -> None: ... + +class ForbiddenProxyRequest(ParseException): + host: str + code: int + + def __init__(self, host: str) -> None: ... + +class InvalidSchemeHeaders(ParseException): ... diff --git a/stubs/gunicorn/gunicorn/http/message.pyi b/stubs/gunicorn/gunicorn/http/message.pyi new file mode 100644 index 000000000000..4819ab116870 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/message.pyi @@ -0,0 +1,80 @@ +import io +import re +from enum import IntEnum +from typing import Final + +from gunicorn.config import Config +from gunicorn.http.body import Body +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +PP_V2_SIGNATURE: Final = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" + +class PPCommand(IntEnum): + LOCAL = 0x0 + PROXY = 0x1 + +class PPFamily(IntEnum): + UNSPEC = 0x0 + INET = 0x1 + INET6 = 0x2 + UNIX = 0x3 + +class PPProtocol(IntEnum): + UNSPEC = 0x0 + STREAM = 0x1 + DGRAM = 0x2 + +MAX_REQUEST_LINE: Final = 8190 +MAX_HEADERS: Final = 32768 +DEFAULT_MAX_HEADERFIELD_SIZE: Final = 8190 +RFC9110_5_6_2_TOKEN_SPECIALS: Final = r"!#$%&'*+-.^_`|~" +TOKEN_RE: Final[re.Pattern[str]] +METHOD_BADCHAR_RE: Final[re.Pattern[str]] +VERSION_RE: Final[re.Pattern[str]] +RFC9110_5_5_INVALID_AND_DANGEROUS: Final[re.Pattern[str]] +RFC9110_6_5_1_FORBIDDEN_TRAILER: Final[frozenset[str]] + +class Message: + cfg: Config + unreader: Unreader + peer_addr: _AddressType + remote_addr: _AddressType + version: tuple[int, int] | None + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + body: Body | None + scheme: str + must_close: bool + limit_request_fields: int + limit_request_field_size: int + max_buffer_headers: int + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType) -> None: ... + def force_close(self) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def parse_headers(self, data: bytes, from_trailer: bool = False) -> list[tuple[str, str]]: ... + def set_body_reader(self) -> None: ... + def should_close(self) -> bool: ... + +class Request(Message): + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + limit_request_line: int + req_number: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + def get_data(self, unreader: Unreader, buf: io.BytesIO, stop: bool = False) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def read_into(self, unreader: Unreader, buf: bytearray, stop: bool | None = False) -> None: ... + def read_line(self, unreader: Unreader, buf: bytearray, limit: int = 0) -> tuple[bytes, bytearray]: ... + def read_bytes(self, unreader: Unreader, buf: bytearray, count: int) -> tuple[bytes, bytearray]: ... + def proxy_protocol_access_check(self) -> None: ... + def parse_request_line(self, line_bytes: bytes) -> None: ... + def set_body_reader(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http/parser.pyi b/stubs/gunicorn/gunicorn/http/parser.pyi new file mode 100644 index 000000000000..5da5625d7d67 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/parser.pyi @@ -0,0 +1,28 @@ +import socket +from collections.abc import Callable, Iterable, Iterator +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.http.message import Request +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType + +class Parser: + # TODO: Use Protocol instead of Request class + mesg_class: ClassVar[type[Request] | None] + cfg: Config + unreader: Unreader + mesg: Request | None + source_addr: _AddressType + req_count: int + + def __init__(self, cfg: Config, source: socket.socket | Iterable[bytes], source_addr: _AddressType) -> None: ... + def __iter__(self) -> Iterator[Request]: ... + def finish_body(self, deadline: float | None = None, max_bytes: int | None = None) -> None: ... + def __next__(self) -> Request: ... + + next: Callable[[Parser], Request] + +class RequestParser(Parser): + mesg_class: ClassVar[type[Request]] diff --git a/stubs/gunicorn/gunicorn/http/unreader.pyi b/stubs/gunicorn/gunicorn/http/unreader.pyi new file mode 100644 index 000000000000..be3da9d5d948 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/unreader.pyi @@ -0,0 +1,25 @@ +import io +import socket +from _typeshed import ReadableBuffer +from collections.abc import Iterable, Iterator + +class Unreader: + buf: io.BytesIO + + def __init__(self) -> None: ... + def chunk(self) -> bytes: ... + def read(self, size: int | None = None) -> bytes: ... + def unread(self, data: ReadableBuffer) -> None: ... + +class SocketUnreader(Unreader): + sock: socket.socket + mxchunk: int + + def __init__(self, sock: socket.socket, max_chunk: int = 8192) -> None: ... + def chunk(self) -> bytes: ... + +class IterUnreader(Unreader): + iter: Iterator[bytes] | None + + def __init__(self, iterable: Iterable[bytes]) -> None: ... + def chunk(self) -> bytes: ... diff --git a/stubs/gunicorn/gunicorn/http/wsgi.pyi b/stubs/gunicorn/gunicorn/http/wsgi.pyi new file mode 100644 index 000000000000..3c44489fd5c7 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http/wsgi.pyi @@ -0,0 +1,80 @@ +import io +import logging +import re +import socket +from _typeshed import ReadableBuffer, Unused +from collections.abc import Callable +from typing import Any, Final, Protocol, type_check_only +from typing_extensions import Self + +from gunicorn.config import Config +from gunicorn.http import Request + +from .._types import _AddressType, _EnvironType, _HeadersType, _StatusType + +BLKSIZE: Final = 0x3FFFFFFF +HEADER_VALUE_RE: Final[re.Pattern[str]] +log: logging.Logger + +@type_check_only +class _FileLikeProtocol(Protocol): + def read(self, size: int, /) -> bytes: ... + def seek(self, offset: int, /) -> object: ... + + # optional fields: + # def close(self) -> None: ... + # def fileno(self) -> int: ... + +class FileWrapper: + filelike: io.IOBase + blksize: int + close: Callable[[], None] | None + + def __init__(self, filelike: _FileLikeProtocol, blksize: int = 8192) -> None: ... + def __getitem__(self, key: Unused) -> bytes: ... + def __iter__(self) -> Self: ... + def __next__(self) -> bytes: ... + +class WSGIErrorsWrapper(io.RawIOBase): + streams: list[io.TextIOBase] + + def __init__(self, cfg: Config) -> None: ... + def write(self, data: ReadableBuffer) -> None: ... + +def base_environ(cfg: Config) -> _EnvironType: ... +def default_environ(req: Request, sock: socket.socket, cfg: Config) -> _EnvironType: ... +def proxy_environ(req: Request) -> _EnvironType: ... +def create( + req: Request, sock: socket.socket, client: _AddressType, server: _AddressType, cfg: Config +) -> tuple[Response, _EnvironType]: ... + +class Response: + req: Request + sock: socket.socket + version: str + status: str | None + chunked: bool + must_close: bool + headers: _HeadersType + headers_sent: bool + response_length: int | None + sent: int + upgrade: bool + cfg: Config + status_code: int | None + + def __init__(self, req: Request, sock: socket.socket, cfg: Config) -> None: ... + def force_close(self) -> None: ... + def should_close(self) -> bool: ... + def start_response( + self, status: _StatusType, headers: _HeadersType, exc_info: tuple[type, BaseException, Any] | None = None + ) -> Callable[[bytes], None]: ... + def process_headers(self, headers: _HeadersType) -> None: ... + def is_chunked(self) -> bool: ... + def default_headers(self) -> list[str]: ... + def send_headers(self) -> None: ... + def write(self, arg: bytes) -> None: ... + def can_sendfile(self) -> bool: ... + def sendfile(self, respiter: FileWrapper) -> bool: ... + def write_file(self, respiter: FileWrapper) -> None: ... + def close(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/http2/__init__.pyi b/stubs/gunicorn/gunicorn/http2/__init__.pyi new file mode 100644 index 000000000000..3ad38b85146f --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/__init__.pyi @@ -0,0 +1,19 @@ +from typing import Final + +from .async_connection import AsyncHTTP2Connection +from .connection import HTTP2ServerConnection + +H2_MIN_VERSION: Final[tuple[int, int, int]] + +def is_http2_available() -> bool: ... +def get_h2_version() -> tuple[int, int, int]: ... +def get_http2_connection_class() -> type[HTTP2ServerConnection]: ... +def get_async_http2_connection_class() -> type[AsyncHTTP2Connection]: ... + +__all__ = [ + "is_http2_available", + "get_h2_version", + "get_http2_connection_class", + "get_async_http2_connection_class", + "H2_MIN_VERSION", +] diff --git a/stubs/gunicorn/gunicorn/http2/async_connection.pyi b/stubs/gunicorn/gunicorn/http2/async_connection.pyi new file mode 100644 index 000000000000..12fbc8524366 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/async_connection.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from asyncio import StreamReader, StreamWriter +from collections.abc import Iterable +from typing import ClassVar + +from gunicorn.config import Config +from gunicorn.http2.connection import _H2Connection +from gunicorn.http2.request import HTTP2Request +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType + +class AsyncHTTP2Connection: + READ_BUFFER_SIZE: ClassVar[int] + cfg: Config + reader: StreamReader + writer: StreamWriter + client_addr: _AddressType + streams: dict[int, HTTP2Stream] + initial_window_size: int + max_concurrent_streams: int + max_frame_size: int + max_header_list_size: int + h2_conn: _H2Connection + + def __init__(self, cfg: Config, reader: StreamReader, writer: StreamWriter, client_addr: _AddressType) -> None: ... + async def initiate_connection(self) -> None: ... + async def receive_data(self, timeout: float | None = None) -> list[HTTP2Request]: ... + async def send_informational(self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]]) -> None: ... + async def send_response( + self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]], body: bytes | None = None + ) -> bool: ... + async def send_data(self, stream_id: int, data: bytes, end_stream: bool = False) -> bool: ... + async def send_trailers(self, stream_id: int, trailers: Iterable[tuple[str, Incomplete]]) -> bool: ... + async def send_error(self, stream_id: int, status_code: int, message: str | None = None) -> None: ... + async def reset_stream(self, stream_id: int, error_code: int = 0x8) -> None: ... + async def close(self, error_code: int = 0x0, last_stream_id: int | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + def cleanup_stream(self, stream_id: int) -> None: ... + +__all__ = ["AsyncHTTP2Connection"] diff --git a/stubs/gunicorn/gunicorn/http2/connection.pyi b/stubs/gunicorn/gunicorn/http2/connection.pyi new file mode 100644 index 000000000000..5ef587127e7f --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/connection.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from ssl import SSLSocket +from typing import Any, ClassVar, TypeAlias + +from gunicorn.config import Config +from gunicorn.http2.request import HTTP2Request +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType + +_H2Connection: TypeAlias = Any # h2.connection.H2Connection class + +class HTTP2ServerConnection: + READ_BUFFER_SIZE: ClassVar[int] + cfg: Config + sock: SSLSocket + client_addr: _AddressType + streams: dict[int, HTTP2Stream] + initial_window_size: int + max_concurrent_streams: int + max_frame_size: int + max_header_list_size: int + h2_conn: _H2Connection + + def __init__(self, cfg: Config, sock: SSLSocket, client_addr: _AddressType) -> None: ... + def initiate_connection(self) -> None: ... + def receive_data(self, data: bytes | None = None) -> list[HTTP2Request]: ... + def send_informational(self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]]) -> None: ... + def send_response( + self, stream_id: int, status: int, headers: Iterable[tuple[str, Incomplete]], body: bytes | None = None + ) -> bool: ... + def send_data(self, stream_id: int, data: bytes, end_stream: bool = False) -> bool: ... + def send_trailers(self, stream_id: int, trailers: Iterable[tuple[str, Incomplete]]) -> bool: ... + def send_error(self, stream_id: int, status_code: int, message: str | None = None) -> None: ... + def reset_stream(self, stream_id: int, error_code: int = 0x8) -> None: ... + def close(self, error_code: int = 0x0, last_stream_id: int | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + def cleanup_stream(self, stream_id: int) -> None: ... + +__all__ = ["HTTP2ServerConnection"] diff --git a/stubs/gunicorn/gunicorn/http2/errors.pyi b/stubs/gunicorn/gunicorn/http2/errors.pyi new file mode 100644 index 000000000000..7e033d23f7a1 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/errors.pyi @@ -0,0 +1,70 @@ +from typing import Final + +class HTTP2ErrorCode: + NO_ERROR: Final = 0x0 + PROTOCOL_ERROR: Final = 0x1 + INTERNAL_ERROR: Final = 0x2 + FLOW_CONTROL_ERROR: Final = 0x3 + SETTINGS_TIMEOUT: Final = 0x4 + STREAM_CLOSED: Final = 0x5 + FRAME_SIZE_ERROR: Final = 0x6 + REFUSED_STREAM: Final = 0x7 + CANCEL: Final = 0x8 + COMPRESSION_ERROR: Final = 0x9 + CONNECT_ERROR: Final = 0xA + ENHANCE_YOUR_CALM: Final = 0xB + INADEQUATE_SECURITY: Final = 0xC + HTTP_1_1_REQUIRED: Final = 0xD + +class HTTP2Error(Exception): + message: str + error_code: int + + def __init__(self, message: str | None = None, error_code: int | None = None) -> None: ... + +class HTTP2ProtocolError(HTTP2Error): ... +class HTTP2InternalError(HTTP2Error): ... +class HTTP2FlowControlError(HTTP2Error): ... +class HTTP2SettingsTimeout(HTTP2Error): ... +class HTTP2StreamClosed(HTTP2Error): ... +class HTTP2FrameSizeError(HTTP2Error): ... +class HTTP2RefusedStream(HTTP2Error): ... +class HTTP2Cancel(HTTP2Error): ... +class HTTP2CompressionError(HTTP2Error): ... +class HTTP2ConnectError(HTTP2Error): ... +class HTTP2EnhanceYourCalm(HTTP2Error): ... +class HTTP2InadequateSecurity(HTTP2Error): ... +class HTTP2RequiresHTTP11(HTTP2Error): ... + +class HTTP2StreamError(HTTP2Error): + stream_id: int + + def __init__(self, stream_id: int, message: str | None = None, error_code: int | None = None) -> None: ... + +class HTTP2ConnectionError(HTTP2Error): ... +class HTTP2ConfigurationError(HTTP2Error): ... + +class HTTP2NotAvailable(HTTP2Error): + def __init__(self, message: str | None = None) -> None: ... + +__all__ = [ + "HTTP2ErrorCode", + "HTTP2Error", + "HTTP2ProtocolError", + "HTTP2InternalError", + "HTTP2FlowControlError", + "HTTP2SettingsTimeout", + "HTTP2StreamClosed", + "HTTP2FrameSizeError", + "HTTP2RefusedStream", + "HTTP2Cancel", + "HTTP2CompressionError", + "HTTP2ConnectError", + "HTTP2EnhanceYourCalm", + "HTTP2InadequateSecurity", + "HTTP2RequiresHTTP11", + "HTTP2StreamError", + "HTTP2ConnectionError", + "HTTP2ConfigurationError", + "HTTP2NotAvailable", +] diff --git a/stubs/gunicorn/gunicorn/http2/request.pyi b/stubs/gunicorn/gunicorn/http2/request.pyi new file mode 100644 index 000000000000..b9a3a377d865 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/request.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterator +from typing import Literal + +from gunicorn.config import Config +from gunicorn.http2.stream import HTTP2Stream + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +class HTTP2Body: + def __init__(self, data: ReadableBuffer) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, hint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... + def __len__(self) -> int: ... + def close(self) -> None: ... + +class HTTP2Request: + stream: HTTP2Stream + cfg: Config + peer_addr: _AddressType + remote_addr: _AddressType + version: tuple[int, int] + method: str + scheme: Literal["https", "http"] + uri: str + path: str + query: str + fragment: str + headers: list[tuple[str, str]] + trailers: list[tuple[str, Incomplete]] + body: HTTP2Body + must_close: bool + req_number: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + priority_weight: int + priority_depends_on: int + + def __init__(self, stream: HTTP2Stream, cfg: Config, peer_addr: _AddressType) -> None: ... + def force_close(self) -> None: ... + def should_close(self) -> bool: ... + def get_header(self, name: str) -> str | None: ... + @property + def content_length(self) -> int | None: ... + @property + def content_type(self) -> str | None: ... + +__all__ = ["HTTP2Request", "HTTP2Body"] diff --git a/stubs/gunicorn/gunicorn/http2/stream.pyi b/stubs/gunicorn/gunicorn/http2/stream.pyi new file mode 100644 index 000000000000..5e7eecb15c19 --- /dev/null +++ b/stubs/gunicorn/gunicorn/http2/stream.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable +from enum import Enum +from io import BytesIO + +from gunicorn.http2.connection import HTTP2ServerConnection + +class StreamState(Enum): + IDLE = 1 + RESERVED_LOCAL = 2 + RESERVED_REMOTE = 3 + OPEN = 4 + HALF_CLOSED_LOCAL = 5 + HALF_CLOSED_REMOTE = 6 + CLOSED = 7 + +class HTTP2Stream: + stream_id: int + connection: HTTP2ServerConnection + state: StreamState + request_headers: list[tuple[str, Incomplete]] + request_body: BytesIO + request_complete: bool + response_started: bool + response_headers_sent: bool + response_complete: bool + window_size: int + trailers: list[tuple[str, Incomplete]] | None + response_trailers: list[tuple[str, Incomplete]] | None + priority_weight: int + priority_depends_on: int + priority_exclusive: bool + + def __init__(self, stream_id: int, connection: HTTP2ServerConnection) -> None: ... + @property + def is_client_stream(self) -> bool: ... + @property + def is_server_stream(self) -> bool: ... + @property + def can_receive(self) -> bool: ... + @property + def can_send(self) -> bool: ... + def receive_headers(self, headers: Iterable[tuple[str, Incomplete]], end_stream: bool | None = False) -> None: ... + def receive_data(self, data: ReadableBuffer, end_stream: bool | None = False) -> None: ... + def receive_trailers(self, trailers: list[tuple[str, Incomplete]]) -> None: ... + def send_headers(self, headers: Iterable[tuple[str, Incomplete]], end_stream: bool | None = False) -> None: ... + def send_data(self, data: ReadableBuffer, end_stream: bool | None = False) -> None: ... + def send_trailers(self, trailers: list[tuple[str, Incomplete]]) -> None: ... + def reset(self, error_code: int = 0x8) -> None: ... + def close(self) -> None: ... + def update_priority( + self, weight: int | None = None, depends_on: int | None = None, exclusive: bool | None = None + ) -> None: ... + def get_request_body(self) -> bytes: ... + async def read_body_chunk(self) -> bytes | None: ... + def get_pseudo_headers(self) -> dict[str, Incomplete]: ... + def get_regular_headers(self) -> list[tuple[str, Incomplete]]: ... + +__all__ = ["HTTP2Stream", "StreamState"] diff --git a/stubs/gunicorn/gunicorn/instrument/__init__.pyi b/stubs/gunicorn/gunicorn/instrument/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/gunicorn/gunicorn/instrument/statsd.pyi b/stubs/gunicorn/gunicorn/instrument/statsd.pyi new file mode 100644 index 000000000000..d08e86de095d --- /dev/null +++ b/stubs/gunicorn/gunicorn/instrument/statsd.pyi @@ -0,0 +1,99 @@ +import logging +import socket +from collections.abc import Mapping +from datetime import timedelta +from typing import Final + +from gunicorn.config import Config +from gunicorn.glogging import Logger +from gunicorn.http import Request +from gunicorn.http.wsgi import Response + +from .._types import _EnvironType +from ..glogging import _LogLevelType + +METRIC_VAR: Final = "metric" +VALUE_VAR: Final = "value" +MTYPE_VAR: Final = "mtype" +GAUGE_TYPE: Final = "gauge" +COUNTER_TYPE: Final = "counter" +HISTOGRAM_TYPE: Final = "histogram" +TIMER_TYPE: Final = "timer" + +class Statsd(Logger): + prefix: str + sock: socket.socket | None + dogstatsd_tags: str | None + cfg: Config + + def __init__(self, cfg: Config) -> None: ... + def critical( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def error( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def warning( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def info( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def debug( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def exception( + self, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = True, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def log( + self, + lvl: _LogLevelType, + msg: object, + *args: object, + exc_info: logging._ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def access(self, resp: Response, req: Request, environ: _EnvironType, request_time: timedelta) -> None: ... + def gauge(self, name: str, value: float) -> None: ... + def increment(self, name: str, value: int, sampling_rate: float = 1.0) -> None: ... + def decrement(self, name: str, value: int, sampling_rate: float = 1.0) -> None: ... + def timer(self, name: str, value: float) -> None: ... + def histogram(self, name: str, value: float) -> None: ... diff --git a/stubs/gunicorn/gunicorn/pidfile.pyi b/stubs/gunicorn/gunicorn/pidfile.pyi new file mode 100644 index 000000000000..9ff0d9dd91d0 --- /dev/null +++ b/stubs/gunicorn/gunicorn/pidfile.pyi @@ -0,0 +1,11 @@ +from _typeshed import StrOrBytesPath + +class Pidfile: + fname: StrOrBytesPath + pid: int | None + + def __init__(self, fname: StrOrBytesPath) -> None: ... + def create(self, pid: int) -> None: ... + def rename(self, path: StrOrBytesPath) -> None: ... + def unlink(self) -> None: ... + def validate(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/reloader.pyi b/stubs/gunicorn/gunicorn/reloader.pyi new file mode 100644 index 000000000000..62371ed476e0 --- /dev/null +++ b/stubs/gunicorn/gunicorn/reloader.pyi @@ -0,0 +1,49 @@ +import sys +import threading +from collections.abc import Callable, Iterable +from re import Pattern +from typing import Final, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never + +COMPILED_EXT_RE: Final[Pattern[str]] + +class ReloaderBase(threading.Thread): + daemon: bool + + def __init__( + self, extra_files: Iterable[str] | None = None, interval: int = 1, callback: Callable[[str], None] | None = None + ) -> None: ... + def add_extra_file(self, filename: str) -> None: ... + def get_files(self) -> list[str]: ... + +class Reloader(ReloaderBase): + def run(self) -> None: ... + +has_inotify: bool + +if sys.platform == "linux": + class InotifyReloader(ReloaderBase): + event_mask: int + daemon: bool + + def __init__(self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None) -> None: ... + def add_extra_file(self, filename: str) -> None: ... + def get_dirs(self) -> set[str]: ... + def refresh_dirs(self) -> None: ... + def run(self) -> None: ... + +else: + class InotifyReloader: + def __init__(self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None) -> Never: ... + +_PreferredReloaderType: TypeAlias = type[InotifyReloader | Reloader] +_ReloaderType: TypeAlias = InotifyReloader | Reloader # noqa: Y047 + +@type_check_only +class _ReloadedEngines(TypedDict): + auto: _PreferredReloaderType + pool: type[Reloader] + inotify: type[InotifyReloader] + +preferred_reloader: _PreferredReloaderType +reloader_engines: _ReloadedEngines diff --git a/stubs/gunicorn/gunicorn/sock.pyi b/stubs/gunicorn/gunicorn/sock.pyi new file mode 100644 index 000000000000..0fd5963d0777 --- /dev/null +++ b/stubs/gunicorn/gunicorn/sock.pyi @@ -0,0 +1,46 @@ +import socket +import sys +from collections.abc import Iterable +from ssl import SSLContext, SSLSocket +from typing import Any, ClassVar, Final, Literal, SupportsIndex + +from gunicorn.glogging import Logger as GLogger + +from .config import Config + +PLATFORM: Final[str] + +class BaseSocket: + sock: socket.socket + + def __init__(self, address: str, conf: Config, log: GLogger, fd: SupportsIndex | None = None) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def set_options(self, sock: socket.socket, bound: bool = False) -> socket.socket: ... + def bind(self, sock: socket.socket) -> None: ... + def close(self) -> None: ... + def get_backlog(self) -> int: ... + +class TCPSocket(BaseSocket): + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_INET, socket.AddressFamily.AF_INET6]] + + def set_options(self, sock: socket.socket, bound: bool = False) -> socket.socket: ... + def get_backlog(self) -> int: ... + +class TCP6Socket(TCPSocket): + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_INET6]] + +class UnixSocket(BaseSocket): + if sys.platform != "win32": + FAMILY: ClassVar[Literal[socket.AddressFamily.AF_UNIX]] + else: + FAMILY: ClassVar[Literal[0]] # Stub for windows + + def __init__(self, addr: str, conf: Config, log: GLogger, fd: SupportsIndex | None = None) -> None: ... + def bind(self, sock: socket.socket) -> None: ... + +def create_sockets(conf: Config, log: GLogger, fds: Iterable[SupportsIndex] | None = None) -> list[BaseSocket]: ... +def close_sockets(listeners: Iterable[socket.socket], unlink: bool = True) -> None: ... +def ssl_context(conf: Config) -> SSLContext: ... +def ssl_wrap_socket(sock: socket.socket, conf: Config) -> SSLSocket: ... +def get_negotiated_protocol(ssl_socket: SSLSocket) -> str | None: ... +def is_http2_negotiated(ssl_socket: SSLSocket) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/systemd.pyi b/stubs/gunicorn/gunicorn/systemd.pyi new file mode 100644 index 000000000000..a7facceeec92 --- /dev/null +++ b/stubs/gunicorn/gunicorn/systemd.pyi @@ -0,0 +1,8 @@ +from typing import Final + +from gunicorn.glogging import Logger as GLogger + +SD_LISTEN_FDS_START: Final[int] + +def listen_fds(unset_environment: bool = True) -> int: ... +def sd_notify(state: str, logger: GLogger, unset_environment: bool = False) -> None: ... diff --git a/stubs/gunicorn/gunicorn/util.pyi b/stubs/gunicorn/gunicorn/util.pyi new file mode 100644 index 000000000000..bc71a50e5d2b --- /dev/null +++ b/stubs/gunicorn/gunicorn/util.pyi @@ -0,0 +1,50 @@ +import types +from _typeshed import FileDescriptorLike, FileDescriptorOrPath, StrOrBytesPath +from inspect import _IntrospectableCallable, _ParameterKind +from socket import socket +from typing import Any, Literal +from typing_extensions import Never +from urllib.parse import SplitResult + +from ._types import _AddressType, _WSGIAppType + +REDIRECT_TO: str +hop_headers: set[str] + +def load_entry_point(distribution: str, group: str, name: str) -> type[object]: ... +def load_class( + uri: str | object, default: str = "gunicorn.workers.sync.SyncWorker", section: str = "gunicorn.workers" +) -> type[Any]: ... + +positionals: tuple[Literal[_ParameterKind.POSITIONAL_ONLY], Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] + +def get_arity(f: _IntrospectableCallable) -> int: ... +def get_username(uid: int) -> str: ... +def set_owner_process(uid: int, gid: int, initgroups: bool = False) -> None: ... +def chown(path: FileDescriptorOrPath, uid: int, gid: int) -> None: ... +def unlink(filename: StrOrBytesPath) -> None: ... +def is_ipv6(addr: str) -> bool: ... +def parse_address(netloc: str, default_port: str = "8000") -> _AddressType: ... +def close_on_exec(fd: FileDescriptorLike) -> None: ... +def set_non_blocking(fd: FileDescriptorLike) -> None: ... +def close(sock: socket) -> None: ... +def close_graceful(sock: socket, timeout: float = 2.0, max_drain: int = 65536) -> None: ... +def write_chunk(sock: socket, data: bytes) -> None: ... +def write(sock: socket, data: bytes, chunked: bool = False) -> None: ... +def write_nonblock(sock: socket, data: bytes, chunked: bool = False) -> None: ... +def write_error(sock: socket, status_int: int, reason: str, mesg: str) -> None: ... +def import_app(module: str) -> _WSGIAppType: ... +def getcwd() -> str: ... +def http_date(timestamp: float | None = None) -> str: ... +def is_hoppish(header: str) -> bool: ... +def daemonize(enable_stdio_inheritance: bool = False) -> None: ... +def seed() -> None: ... +def check_is_writable(path: FileDescriptorOrPath) -> None: ... +def to_bytestring(value: str | bytes, encoding: str = "utf8") -> bytes: ... +def has_fileno(obj: object) -> bool: ... +def warn(msg: str) -> None: ... +def make_fail_app(msg: str) -> _WSGIAppType: ... +def split_request_uri(uri: str) -> SplitResult: ... +def reraise(tp: type[BaseException], value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... +def bytes_to_str(b: bytes) -> str: ... +def unquote_to_wsgi_str(string: str) -> str: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi b/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi new file mode 100644 index 000000000000..47193b1757e6 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/__init__.pyi @@ -0,0 +1,17 @@ +from gunicorn.uwsgi.errors import ( + ForbiddenUWSGIRequest as ForbiddenUWSGIRequest, + InvalidUWSGIHeader as InvalidUWSGIHeader, + UnsupportedModifier as UnsupportedModifier, + UWSGIParseException as UWSGIParseException, +) +from gunicorn.uwsgi.message import UWSGIRequest as UWSGIRequest +from gunicorn.uwsgi.parser import UWSGIParser as UWSGIParser + +__all__ = [ + "UWSGIRequest", + "UWSGIParser", + "UWSGIParseException", + "InvalidUWSGIHeader", + "UnsupportedModifier", + "ForbiddenUWSGIRequest", +] diff --git a/stubs/gunicorn/gunicorn/uwsgi/errors.pyi b/stubs/gunicorn/gunicorn/uwsgi/errors.pyi new file mode 100644 index 000000000000..265536815654 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/errors.pyi @@ -0,0 +1,19 @@ +class UWSGIParseException(Exception): ... + +class InvalidUWSGIHeader(UWSGIParseException): + msg: str + code: int + + def __init__(self, msg: str = "") -> None: ... + +class UnsupportedModifier(UWSGIParseException): + modifier: int + code: int + + def __init__(self, modifier: int) -> None: ... + +class ForbiddenUWSGIRequest(UWSGIParseException): + host: str + code: int + + def __init__(self, host: str) -> None: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/message.pyi b/stubs/gunicorn/gunicorn/uwsgi/message.pyi new file mode 100644 index 000000000000..b89c893ad508 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/message.pyi @@ -0,0 +1,38 @@ +from typing import Final, Literal + +from gunicorn.config import Config +from gunicorn.http.body import Body +from gunicorn.http.unreader import Unreader + +from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown + +MAX_UWSGI_VARS: Final = 1000 + +class UWSGIRequest: + cfg: Config + unreader: Unreader + peer_addr: _AddressType + remote_addr: _AddressType + req_number: int + method: str | None + uri: str | None + path: str | None + query: str | None + fragment: str | None + version: tuple[int, int] + headers: list[tuple[str, str]] + trailers: list[tuple[str, str]] + body: Body | None + scheme: Literal["https", "http"] + must_close: bool + uwsgi_vars: dict[str, str] + modifier1: int + modifier2: int + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None + + def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... + def force_close(self) -> None: ... + def parse(self, unreader: Unreader) -> bytes: ... + def set_body_reader(self) -> None: ... + def should_close(self) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/uwsgi/parser.pyi b/stubs/gunicorn/gunicorn/uwsgi/parser.pyi new file mode 100644 index 000000000000..488b318b2299 --- /dev/null +++ b/stubs/gunicorn/gunicorn/uwsgi/parser.pyi @@ -0,0 +1,7 @@ +from typing import ClassVar + +from gunicorn.http.parser import Parser +from gunicorn.uwsgi.message import UWSGIRequest + +class UWSGIParser(Parser): + mesg_class: ClassVar[type[UWSGIRequest]] # type: ignore[assignment] diff --git a/stubs/gunicorn/gunicorn/workers/__init__.pyi b/stubs/gunicorn/gunicorn/workers/__init__.pyi new file mode 100644 index 000000000000..d687a67ab557 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/__init__.pyi @@ -0,0 +1,13 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _SupportedWorkers(TypedDict): + sync: str + gevent: str + gevent_wsgi: str + gevent_pywsgi: str + tornado: str + gthread: str + asgi: str + +SUPPORTED_WORKERS: _SupportedWorkers diff --git a/stubs/gunicorn/gunicorn/workers/base.pyi b/stubs/gunicorn/gunicorn/workers/base.pyi new file mode 100644 index 000000000000..aa0d5fc3a76a --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/base.pyi @@ -0,0 +1,48 @@ +import socket +from types import FrameType +from typing import ClassVar + +from gunicorn.app.base import BaseApplication +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request +from gunicorn.workers.workertmp import WorkerTmp + +from .._types import _AddressType, _WSGIAppType +from ..reloader import _ReloaderType + +class Worker: + SIGNALS: ClassVar[list[int]] + PIPE: ClassVar[list[int]] + age: int + pid: str + ppid: int + sockets: list[socket.socket] + app: BaseApplication + timeout: int + cfg: Config + booted: bool + aborted: bool + reloader: _ReloaderType | None + nr: int + max_requests: int + alive: bool + log: GLogger + tmp: WorkerTmp + wait_fds: list[socket.socket | int] + wsgi: _WSGIAppType + + def __init__( + self, age: int, ppid: int, sockets: list[socket.socket], app: BaseApplication, timeout: int, cfg: Config, log: GLogger + ) -> None: ... + def notify(self) -> None: ... + def run(self) -> None: ... + def init_process(self) -> None: ... + def load_wsgi(self) -> None: ... + def init_signals(self) -> None: ... + def handle_usr1(self, sig: int, frame: FrameType | None) -> None: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_abort(self, sig: int, frame: FrameType | None) -> None: ... + def handle_error(self, req: Request | None, client: socket.socket, addr: _AddressType, exc: BaseException) -> None: ... + def handle_winch(self, sig: int, fname: str | None) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/base_async.pyi b/stubs/gunicorn/gunicorn/workers/base_async.pyi new file mode 100644 index 000000000000..8a24aaf53b67 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/base_async.pyi @@ -0,0 +1,22 @@ +import socket + +from gunicorn.http import Request +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.workers import base + +from .._types import _AddressType + +ALREADY_HANDLED: object + +class AsyncWorker(base.Worker): + worker_connections: int + alive: bool + + def timeout_ctx(self) -> None: ... + def is_already_handled(self, respiter: object) -> bool: ... + def handle(self, listener: socket.socket, client: socket.socket, addr: _AddressType) -> None: ... + def handle_http2(self, listener: socket.socket, client: socket.socket, addr: _AddressType) -> None: ... + def handle_http2_request( + self, listener_name: _AddressType, req: Request, sock: socket.socket, addr: _AddressType, h2_conn: HTTP2ServerConnection + ) -> None: ... + def handle_request(self, listener_name: _AddressType, req: Request, sock: socket.socket, addr: _AddressType) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/workers/gasgi.pyi b/stubs/gunicorn/gunicorn/workers/gasgi.pyi new file mode 100644 index 000000000000..564d6d375a9d --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gasgi.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from asyncio.base_events import Server +from asyncio.events import AbstractEventLoop +from typing_extensions import Never + +from gunicorn.asgi.lifespan import LifespanManager +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.workers import base + +from .._types import _ASGIAppType + +class ASGIWorker(base.Worker): + worker_connections: int + loop: AbstractEventLoop | None + servers: list[Server] + nr_conns: int + lifespan: LifespanManager | None + state: dict[Incomplete, Incomplete] + asgi: _ASGIAppType + + @classmethod + def check_config(cls, cfg: Config, log: GLogger) -> None: ... + def init_process(self) -> None: ... + def load_wsgi(self) -> None: ... + def init_signals(self) -> None: ... + def handle_quit_signal(self) -> None: ... + def handle_exit_signal(self) -> None: ... + def handle_usr1_signal(self) -> None: ... + def handle_winch_signal(self) -> None: ... + def handle_abort_signal(self) -> Never: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/ggevent.pyi b/stubs/gunicorn/gunicorn/workers/ggevent.pyi new file mode 100644 index 000000000000..6e2aa6da142d --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/ggevent.pyi @@ -0,0 +1,45 @@ +from types import FrameType +from typing import Any, ClassVar, Final + +from gevent import pywsgi +from gevent.pywsgi import WSGIHandler +from gevent.server import StreamServer +from gevent.socket import socket as GeventSocket +from gunicorn.http import Request +from gunicorn.workers.base_async import AsyncWorker + +from .._types import _AddressType + +VERSION: Final[str] + +class GeventWorker(AsyncWorker): + server_class: ClassVar[type[StreamServer] | None] + wsgi_handler: ClassVar[type[WSGIHandler] | None] + sockets: list[GeventSocket] + + def patch(self) -> None: ... + def notify(self) -> None: ... + def timeout_ctx(self) -> None: ... + def run(self) -> None: ... + def handle(self, listener: GeventSocket, client: GeventSocket, addr: _AddressType) -> None: ... + def handle_request(self, listener_name: _AddressType, req: Request, sock: GeventSocket, addr: _AddressType) -> bool: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_usr1(self, sig: int, frame: FrameType | None) -> None: ... + def init_process(self) -> None: ... + +class GeventResponse: + status: ClassVar[str | None] + headers: ClassVar[dict[str, str] | None] + sent: ClassVar[int | None] + + def __init__(self, status: str, headers: dict[str, str], clength: int | None) -> None: ... + +class PyWSGIHandler(pywsgi.WSGIHandler): + def log_request(self) -> None: ... + def get_environ(self) -> dict[str, Any]: ... + +class PyWSGIServer(pywsgi.WSGIServer): ... + +class GeventPyWSGIWorker(GeventWorker): + server_class: ClassVar[type[PyWSGIServer] | None] + wsgi_handler: ClassVar[type[PyWSGIHandler] | None] diff --git a/stubs/gunicorn/gunicorn/workers/gthread.pyi b/stubs/gunicorn/gunicorn/workers/gthread.pyi new file mode 100644 index 000000000000..51fab72f4e07 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gthread.pyi @@ -0,0 +1,80 @@ +import socket +from _typeshed import Unused +from collections import deque +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor +from selectors import DefaultSelector +from types import FrameType +from typing import Final + +from gunicorn.config import Config +from gunicorn.glogging import Logger as GLogger +from gunicorn.http import Request, RequestParser +from gunicorn.http2.connection import HTTP2ServerConnection +from gunicorn.uwsgi.parser import UWSGIParser + +from .._types import _AddressType +from . import base + +DEFAULT_WORKER_DATA_TIMEOUT: Final = 5.0 + +class TConn: + cfg: Config + sock: socket.socket + client: _AddressType + server: _AddressType + timeout: float | None + parser: HTTP2ServerConnection | UWSGIParser | RequestParser | None + initialized: bool + is_http2: bool + data_ready: bool + + def __init__(self, cfg: Config, sock: socket.socket, client: _AddressType, server: _AddressType) -> None: ... + def init(self) -> None: ... + def set_timeout(self) -> None: ... + def wait_for_data(self, timeout: float | None) -> bool: ... + def close(self, graceful: bool = False) -> None: ... + +class PollableMethodQueue: + def __init__(self) -> None: ... + def init(self) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int | None: ... + # Actually, `*args` are expected to match the parameter types of `callback`. + # Ideally this would be typed using ParamSpec as: + # def defer(self, callback: Callable[_P, object], *args: _P.args) -> None + def defer(self, callback: Callable[..., object], *args: object) -> None: ... + def run_callbacks(self, _fileobj: Unused, max_callbacks: int = 50) -> None: ... + +class ThreadWorker(base.Worker): + worker_connections: int + max_keepalived: int + tpool: ThreadPoolExecutor + poller: DefaultSelector + method_queue: PollableMethodQueue + keepalived_conns: deque[TConn] + pending_conns: deque[TConn] + nr_conns: int + alive: bool + + @classmethod + def check_config(cls, cfg: Config, log: GLogger) -> None: ... + def init_process(self) -> None: ... + def get_thread_pool(self) -> ThreadPoolExecutor: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_quit(self, sig: int, frame: FrameType | None) -> None: ... + def set_accept_enabled(self, enabled: bool | None) -> None: ... + def enqueue_req(self, conn: TConn) -> None: ... + def accept(self, listener: socket.socket) -> None: ... + def on_client_socket_readable(self, conn: TConn, client: socket.socket) -> None: ... + def on_pending_socket_readable(self, conn: TConn, client: socket.socket) -> None: ... + def murder_keepalived(self) -> None: ... + def murder_pending(self) -> None: ... + def is_parent_alive(self) -> bool: ... + def wait_for_and_dispatch_events(self, timeout: float | None) -> None: ... + def run(self) -> None: ... + def finish_request(self, conn: TConn, fs: Future[bool]) -> None: ... + def handle(self, conn: TConn) -> bool: ... + def handle_http2(self, conn: TConn) -> bool: ... + def handle_http2_request(self, req: Request, conn: TConn, h2_conn: HTTP2ServerConnection) -> None: ... + def handle_request(self, req: Request, conn: TConn) -> bool: ... diff --git a/stubs/gunicorn/gunicorn/workers/gtornado.pyi b/stubs/gunicorn/gunicorn/workers/gtornado.pyi new file mode 100644 index 000000000000..25267d4d46bb --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/gtornado.pyi @@ -0,0 +1,24 @@ +from types import FrameType +from typing import Any, TypeAlias + +from gunicorn.workers.base import Worker + +IOLoop: TypeAlias = Any # tornado IOLoop class +PeriodicCallback: TypeAlias = Any # tornado PeriodicCallback class +_HTTPServer: TypeAlias = Any # tornado httpserver.HTTPServer class + +class TornadoWorker(Worker): + alive: bool + server_alive: bool + ioloop: IOLoop + callbacks: list[PeriodicCallback] + server: _HTTPServer + + @classmethod + def setup(cls) -> None: ... + def handle_exit(self, sig: int, frame: FrameType | None) -> None: ... + def handle_request(self) -> None: ... + def watchdog(self) -> None: ... + def heartbeat(self) -> None: ... + def init_process(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/sync.pyi b/stubs/gunicorn/gunicorn/workers/sync.pyi new file mode 100644 index 000000000000..cf461d5e785c --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/sync.pyi @@ -0,0 +1,19 @@ +import socket + +from gunicorn.http import Request +from gunicorn.workers.base import Worker + +from .._types import _AddressType + +class StopWaiting(Exception): ... + +class SyncWorker(Worker): + def accept(self, listener: socket.socket) -> None: ... + def wait(self, timeout: int) -> list[socket.socket | int] | None: ... + def is_parent_alive(self) -> bool: ... + def run_for_one(self, timeout: int) -> None: ... + def run_for_multiple(self, timeout: int) -> None: ... + def run(self) -> None: ... + def handle(self, listener: socket.socket, client: socket.socket, addr: _AddressType) -> None: ... + def handle_request(self, listener: socket.socket, req: Request, client: socket.socket, addr: tuple[str, int]) -> bool: ... + def handle_error(self, req: Request | None, client: socket.socket, addr: _AddressType, exc: BaseException) -> None: ... diff --git a/stubs/gunicorn/gunicorn/workers/workertmp.pyi b/stubs/gunicorn/gunicorn/workers/workertmp.pyi new file mode 100644 index 000000000000..4bfc3c6182f9 --- /dev/null +++ b/stubs/gunicorn/gunicorn/workers/workertmp.pyi @@ -0,0 +1,13 @@ +from typing import Final + +from gunicorn.config import Config + +PLATFORM: Final[str] +IS_CYGWIN: Final[bool] + +class WorkerTmp: + def __init__(self, cfg: Config) -> None: ... + def notify(self) -> None: ... + def last_update(self) -> float: ... + def fileno(self) -> int: ... + def close(self) -> None: ... diff --git a/stubs/hdbcli/@tests/stubtest_allowlist.txt b/stubs/hdbcli/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0a8477f582f6 --- /dev/null +++ b/stubs/hdbcli/@tests/stubtest_allowlist.txt @@ -0,0 +1,23 @@ +# Are set to `None` by default, initialized later: +hdbcli.dbapi.Error.errorcode +hdbcli.dbapi.Error.errortext +hdbcli.dbapi.Warning.errorcode +hdbcli.dbapi.Warning.errortext +hdbcli.dbapi.ExecuteManyErrorEntry.rownumber + +hdbcli.dbapi.buffer +hdbcli.dbapi.long +hdbcli.dbapi.unicode + +# async_connect is an alias for AsyncConnection, but at runtime its a function +hdbcli.dbapi.async_connect + +# *args/**kwargs are not added by purpose but are part of the python wrapper +hdbcli.dbapi.AsyncLob.close +hdbcli.dbapi.AsyncCursor.nextset +hdbcli.dbapi.AsyncCursor.fetchall +hdbcli.dbapi.AsyncCursor.close +hdbcli.dbapi.AsyncConnection.rollback +hdbcli.dbapi.AsyncConnection.commit +hdbcli.dbapi.AsyncConnection.close +hdbcli.dbapi.AsyncConnection.cancel diff --git a/stubs/hdbcli/METADATA.toml b/stubs/hdbcli/METADATA.toml new file mode 100644 index 000000000000..2bc0cad45c11 --- /dev/null +++ b/stubs/hdbcli/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.29.*" +# upstream-repository = closed-source diff --git a/stubs/hdbcli/hdbcli/__init__.pyi b/stubs/hdbcli/hdbcli/__init__.pyi new file mode 100644 index 000000000000..bbf8a8962414 --- /dev/null +++ b/stubs/hdbcli/hdbcli/__init__.pyi @@ -0,0 +1,7 @@ +from typing import Final + +from . import dbapi as dbapi + +__version__: Final[str] + +__all__ = ["dbapi"] diff --git a/stubs/hdbcli/hdbcli/dbapi.pyi b/stubs/hdbcli/hdbcli/dbapi.pyi new file mode 100644 index 000000000000..4acfa34cdcfd --- /dev/null +++ b/stubs/hdbcli/hdbcli/dbapi.pyi @@ -0,0 +1,193 @@ +import decimal +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable, Sequence +from datetime import date, datetime, time +from types import TracebackType +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import Self, disjoint_base + +from .resultrow import ResultRow + +apilevel: Final[str] +threadsafety: Final[int] +paramstyle: Final[tuple[str, ...]] # hdbcli defines it as a tuple which does not follow PEP 249 + +@disjoint_base +class Connection: + def __init__( + self, + address: str = "", + port: int = 0, + user: str = "", + password: str = "", + autocommit: bool = True, + packetsize: int | None = None, + userkey: str | None = ..., + *, + sessionvariables: dict[str, str] | None = ..., + forcebulkfetch: bool | None = ..., + ) -> None: ... + def cancel(self) -> bool: ... + def close(self) -> None: ... + def commit(self) -> None: ... + def cursor(self) -> Cursor: ... + def getaddress(self) -> str: ... + def getautocommit(self) -> bool: ... + def getclientinfo(self, key: str = ...) -> str | dict[str, str]: ... + def getproperty(self, *args, **kwargs): ... + def isconnected(self) -> bool: ... + def rollback(self) -> None: ... + def setautocommit(self, auto: bool = ...) -> None: ... + def setclientinfo(self, key: str, value: str | None = ...) -> None: ... + def ontrace(self, callback: Callable[[str], Any], options: str = ...) -> None: ... + def ping(self) -> bool: ... + +connect = Connection + +@disjoint_base +class LOB: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def close(self) -> bool: ... + def find(self, object: str, length: int, position: int = ...) -> int: ... + def read(self, size: int = ..., position: int = ...) -> str | bytes: ... + def write(self, object: str | bytes) -> int: ... + +_Parameters: TypeAlias = Sequence[tuple[Any, ...]] | None +_Holdability: TypeAlias = Literal[0, 1, 2, 3] + +@disjoint_base +class Cursor: + description: tuple[tuple[Any, ...], ...] + rowcount: int + statementhash: str | None + connection: Connection + arraysize: int + refreshts: int | None + maxage: int + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + def callproc(self, procname: str, parameters: tuple[Any, ...] = ..., overview: bool = ...) -> tuple[Any, ...]: ... + def close(self) -> None: ... + def description_ext(self) -> Sequence[tuple[Any, ...]]: ... + def execute(self, operation: str, parameters: tuple[Any, ...] | None = ...) -> bool: ... + def executemany(self, operation: str, parameters: _Parameters = ..., batcherrors: bool = False) -> Any: ... + def executemanyprepared(self, parameters: _Parameters = ...) -> Any: ... + def executeprepared(self, parameters: _Parameters = ...) -> Any: ... + def fetchone(self, uselob: bool = ...) -> ResultRow | None: ... + def fetchall(self) -> list[ResultRow]: ... + def fetchmany(self, size: int | None = ...) -> list[ResultRow]: ... + def getrowsaffectedcounts(self) -> tuple[Any, ...]: ... + def getpacketsize(self) -> int: ... + def get_resultset_holdability(self) -> _Holdability: ... + def getwarning(self) -> Warning | None: ... + def haswarning(self) -> bool: ... + def clearwarning(self) -> None: ... + def has_result_set(self) -> bool: ... + def nextset(self) -> None: ... + def parameter_description(self) -> tuple[str, ...]: ... + + @overload + def prepare(self, operation: str, newcursor: Literal[True]) -> Cursor: ... + @overload + def prepare(self, operation: str, newcursor: Literal[False]) -> Any: ... + + def print_message(self): ... + def parsenamedquery(self, *args, **kwargs): ... + def scroll(self, value: int, mode: Literal["absolute", "relative"] = ...) -> None: ... + def server_cpu_time(self) -> int: ... + def server_memory_usage(self) -> int: ... + def server_processing_time(self) -> int: ... + def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... + def setfetchsize(self, value: int) -> None: ... + def setquerytimeout(self, value: int) -> None: ... + def setpacketsize(self, value: int) -> None: ... + def set_resultset_holdability(self, holdability: _Holdability) -> None: ... + def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... + def setcommandinfo(self, command_info: str, line_number: int) -> None: ... + +class Warning(Exception): + errorcode: int + errortext: str + +class Error(Exception): + errorcode: int + errortext: str + +class DatabaseError(Error): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(Error): ... +class InternalError(DatabaseError): ... +class DataError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... + +class ExecuteManyError(Error): + errors: Incomplete + +class ExecuteManyErrorEntry(Error): + rownumber: int + +def Date(year: int, month: int, day: int) -> date: ... +def Time(hour: int, minute: int, second: int, millisecond: int = 0) -> time: ... +def Timestamp(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int = 0) -> datetime: ... +def DateFromTicks(ticks: float) -> date: ... +def TimeFromTicks(ticks: float) -> time: ... +def TimestampFromTicks(ticks: float) -> datetime: ... +def Binary(data: ReadableBuffer) -> memoryview: ... + +Decimal = decimal.Decimal + +NUMBER: type[int | float | complex] +DATETIME: type[date | time | datetime] +STRING = str +BINARY = memoryview +ROWID = int + +class AsyncConnection(Connection): + @classmethod + async def create( + cls, + address: str = "", + port: int = 0, + user: str = "", + password: str = "", + autocommit: bool = True, + packetsize: int | None = None, + userkey: str | None = ..., + *, + sessionvariables: dict[str, str] | None = ..., + forcebulkfetch: bool | None = ..., + ) -> Self: ... + async def cancel(self) -> bool: ... # type: ignore[override] + async def close(self) -> None: ... # type: ignore[override] + async def commit(self) -> None: ... # type: ignore[override] + async def cursor(self) -> AsyncCursor: ... # type: ignore[override] + async def rollback(self) -> None: ... # type: ignore[override] + +class AsyncCursor(Cursor): + async def callproc(self, procname: str, parameters: tuple[Any, ...] = ..., overview: bool = ...) -> tuple[Any, ...]: ... # type: ignore[override] + async def close(self) -> None: ... # type: ignore[override] + async def execute(self, operation: str, parameters: tuple[Any, ...] | None = ...) -> bool: ... # type: ignore[override] + async def executemany(self, operation: str, parameters: _Parameters = ..., batcherrors: bool = False) -> Any: ... + async def executemanyprepared(self, parameters: _Parameters = ...) -> Any: ... + async def executeprepared(self, parameters: _Parameters = ...) -> Any: ... + async def fetchone(self, uselob: bool = ...) -> ResultRow | None: ... # type: ignore[override] + async def fetchall(self) -> list[ResultRow]: ... # type: ignore[override] + async def fetchmany(self, size: int | None = ...) -> list[ResultRow]: ... # type: ignore[override] + async def nextset(self) -> None: ... # type: ignore[override] + async def prepare(self, operation: str, newcursor: bool = ...) -> Any: ... # type: ignore[override] + async def scroll(self, value: int, mode: Literal["absolute", "relative"] = ...) -> None: ... # type: ignore[override] + async def __aenter__(self) -> Self: ... + async def __aexit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... + +class AsyncLob(LOB): + async def close(self) -> None: ... # type: ignore[override] + async def find(self, object: str, length: int, position: int = ...) -> int: ... # type: ignore[override] + async def read(self, size: int = ..., position: int = ...) -> str | bytes: ... # type: ignore[override] + async def write(self, object: str | bytes) -> int: ... # type: ignore[override] + +async_connect = AsyncConnection + +def set_async_mode(enabled: bool = True) -> None: ... diff --git a/stubs/hdbcli/hdbcli/resultrow.pyi b/stubs/hdbcli/hdbcli/resultrow.pyi new file mode 100644 index 000000000000..d3e9454dbfe1 --- /dev/null +++ b/stubs/hdbcli/hdbcli/resultrow.pyi @@ -0,0 +1,19 @@ +from collections.abc import Iterator, Sequence +from typing import Any, overload +from typing_extensions import disjoint_base + +@disjoint_base +class ResultRow: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + column_names: tuple[str, ...] + column_values: tuple[Any, ...] + + def __len__(self) -> int: ... + + @overload + def __getitem__(self, index: int, /) -> Any: ... + @overload + def __getitem__(self, index: slice, /) -> Sequence[Any]: ... + + def __iter__(self) -> Iterator[Any]: ... + # __next__, __delitem__, __setitem__ are technically defined but lead always to an error diff --git a/stubs/hnswlib/@tests/stubtest_allowlist.txt b/stubs/hnswlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c8b95d1e576d --- /dev/null +++ b/stubs/hnswlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# The metaclass of Index is pybind11_builtins.pybind11_type. Since pybind11 is not a +# runtime dependency of hnswlib, we exclude Index from stubtest checks. +hnswlib.Index diff --git a/stubs/hnswlib/METADATA.toml b/stubs/hnswlib/METADATA.toml new file mode 100644 index 000000000000..df04086d96d4 --- /dev/null +++ b/stubs/hnswlib/METADATA.toml @@ -0,0 +1,9 @@ +version = "0.8.*" +upstream-repository = "https://github.com/nmslib/hnswlib" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.21"] + +[tool.stubtest] +# TODO: stubtest fails on Linux because it gets killed with a SIGILL +# for unknown reasons. See https://github.com/python/typeshed/issues/16100 +ci-platforms = ["darwin"] diff --git a/stubs/hnswlib/hnswlib.pyi b/stubs/hnswlib/hnswlib.pyi new file mode 100644 index 000000000000..3c2656748fa0 --- /dev/null +++ b/stubs/hnswlib/hnswlib.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Literal, overload + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +BFIndex: Incomplete + +class Index: + ef: int + num_threads: int + + @overload + def __init__(self, params: dict[str, Any]) -> None: ... + @overload + def __init__(self, index: Index) -> None: ... + @overload + def __init__(self, space: Literal["l2", "ip", "cosine"], dim: int) -> None: ... + + def add_items( + self, data: ArrayLike, ids: ArrayLike | None = None, num_threads: int = -1, replace_deleted: bool = False + ) -> None: ... + def get_current_count(self) -> int: ... + def get_ids_list(self) -> list[int]: ... + + @overload + def get_items(self, ids: ArrayLike | None = ..., return_type: Literal["list"] = ...) -> list[float]: ... + @overload + def get_items(self, ids: ArrayLike | None = ..., return_type: Literal["numpy"] = ...) -> NDArray[np.float32]: ... + @overload + def get_items( + self, ids: ArrayLike | None = None, return_type: Literal["numpy", "list"] = "numpy" + ) -> NDArray[np.float32] | list[float]: ... + + def get_max_elements(self) -> int: ... + def index_file_size(self) -> int: ... + def init_index( + self, + max_elements: int, + M: int = 16, + ef_construction: int = 200, + random_seed: int = 100, + allow_replace_delete: bool = False, + ) -> None: ... + def knn_query( + self, data: ArrayLike, k: int = 1, num_threads: int = -1, filter: Callable[[int], bool] | None = None + ) -> tuple[NDArray[np.uint64], NDArray[np.float32]]: ... + def load_index(self, path_to_index: str, max_elements: int = 0, allow_replace_delete: bool = False) -> None: ... + def mark_deleted(self, label: int) -> None: ... + def resize_index(self, new_size: int) -> None: ... + def save_index(self, path_to_index: str) -> None: ... + def set_ef(self, ef: int) -> None: ... + def set_num_threads(self, num_threads: int) -> None: ... + def unmark_deleted(self, label: int) -> None: ... + @property + def M(self) -> int: ... + @property + def dim(self) -> int: ... + @property + def ef_construction(self) -> int: ... + @property + def element_count(self) -> int: ... + @property + def max_elements(self) -> int: ... + @property + def space(self) -> str: ... diff --git a/stubs/html5lib/@tests/stubtest_allowlist.txt b/stubs/html5lib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7d9f867632d2 --- /dev/null +++ b/stubs/html5lib/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Side effects from module initialization: +html5lib.serializer.k +html5lib.serializer.v +html5lib.treeadapters.sax.prefix +html5lib.treeadapters.sax.localName +html5lib.treeadapters.sax.namespace diff --git a/stubs/html5lib/METADATA.toml b/stubs/html5lib/METADATA.toml new file mode 100644 index 000000000000..7049e9bd2e85 --- /dev/null +++ b/stubs/html5lib/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.1.*" +upstream-repository = "https://github.com/html5lib/html5lib-python" +dependencies = ["types-webencodings"] + +[tool.stubtest] +extras = ["all"] diff --git a/stubs/html5lib/html5lib/__init__.pyi b/stubs/html5lib/html5lib/__init__.pyi new file mode 100644 index 000000000000..3a24c70e9f41 --- /dev/null +++ b/stubs/html5lib/html5lib/__init__.pyi @@ -0,0 +1,10 @@ +from typing import Final + +from .html5parser import HTMLParser as HTMLParser, parse as parse, parseFragment as parseFragment +from .serializer import serialize as serialize +from .treebuilders import getTreeBuilder as getTreeBuilder +from .treewalkers import getTreeWalker as getTreeWalker + +__all__ = ["HTMLParser", "parse", "parseFragment", "getTreeBuilder", "getTreeWalker", "serialize"] + +__version__: Final[str] diff --git a/stubs/html5lib/html5lib/_ihatexml.pyi b/stubs/html5lib/html5lib/_ihatexml.pyi new file mode 100644 index 000000000000..4f0844635aa3 --- /dev/null +++ b/stubs/html5lib/html5lib/_ihatexml.pyi @@ -0,0 +1,55 @@ +import re + +baseChar: str +ideographic: str +combiningCharacter: str +digit: str +extender: str +letter: str +name: str +nameFirst: str +reChar: re.Pattern[str] +reCharRange: re.Pattern[str] + +def charStringToList(chars: str) -> list[list[int]]: ... +def normaliseCharList(charList: list[list[int]]) -> list[list[int]]: ... + +max_unicode: int + +def missingRanges(charList: list[list[int]]) -> list[list[int]]: ... +def listToRegexpStr(charList: list[list[int]]) -> str: ... +def hexToInt(hex_str: str | bytes | bytearray) -> int: ... +def escapeRegexp(string: str) -> str: ... + +nonXmlNameBMPRegexp: re.Pattern[str] +nonXmlNameFirstBMPRegexp: re.Pattern[str] +nonPubidCharRegexp: re.Pattern[str] + +class InfosetFilter: + replacementRegexp: re.Pattern[str] + dropXmlnsLocalName: bool + dropXmlnsAttrNs: bool + preventDoubleDashComments: bool + preventDashAtCommentEnd: bool + replaceFormFeedCharacters: bool + preventSingleQuotePubid: bool + replaceCache: dict[str, str] + def __init__( + self, + dropXmlnsLocalName: bool = False, + dropXmlnsAttrNs: bool = False, + preventDoubleDashComments: bool = False, + preventDashAtCommentEnd: bool = False, + replaceFormFeedCharacters: bool = True, + preventSingleQuotePubid: bool = False, + ) -> None: ... + def coerceAttribute(self, name: str, namespace: str | None = None) -> str | None: ... + def coerceElement(self, name: str) -> str: ... + def coerceComment(self, data: str) -> str: ... + def coerceCharacters(self, data: str) -> str: ... + def coercePubid(self, data: str) -> str: ... + def toXmlName(self, name: str) -> str: ... + def getReplacementCharacter(self, char: str) -> str: ... + def fromXmlName(self, name: str) -> str: ... + def escapeChar(self, char: str) -> str: ... + def unescapeChar(self, charcode: str | bytes | bytearray) -> str: ... diff --git a/stubs/html5lib/html5lib/_inputstream.pyi b/stubs/html5lib/html5lib/_inputstream.pyi new file mode 100644 index 000000000000..1a011ee46eb8 --- /dev/null +++ b/stubs/html5lib/html5lib/_inputstream.pyi @@ -0,0 +1,150 @@ +import re +from _io import BytesIO, StringIO +from _typeshed import Incomplete, ReadableBuffer, SupportsRead +from collections.abc import Callable, Iterable +from typing import Any, AnyStr, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from webencodings import Encoding + +_UnicodeInputStream: TypeAlias = str | SupportsRead[str] +_BinaryInputStream: TypeAlias = bytes | SupportsRead[bytes] +_InputStream: TypeAlias = _UnicodeInputStream | _BinaryInputStream # noqa: Y047 # used in other files +_SupportsReadT = TypeVar("_SupportsReadT", bound=SupportsRead[Any]) +_SupportsReadBytesT = TypeVar("_SupportsReadBytesT", bound=SupportsRead[bytes]) + +spaceCharactersBytes: frozenset[bytes] +asciiLettersBytes: frozenset[bytes] +asciiUppercaseBytes: frozenset[bytes] +spacesAngleBrackets: frozenset[bytes] +invalid_unicode_no_surrogate: str +invalid_unicode_re: re.Pattern[str] +non_bmp_invalid_codepoints: set[int] +ascii_punctuation_re: re.Pattern[str] +charsUntilRegEx: dict[tuple[Iterable[str | bytes | bytearray], bool], re.Pattern[str]] + +class BufferedStream(Generic[AnyStr]): + stream: SupportsRead[AnyStr] + buffer: list[AnyStr] + position: list[int] + def __init__(self, stream: SupportsRead[AnyStr]) -> None: ... + def tell(self) -> int: ... + def seek(self, pos: int) -> None: ... + def read(self, bytes: int) -> AnyStr: ... + +@overload +def HTMLInputStream(source: _UnicodeInputStream) -> HTMLUnicodeInputStream: ... +@overload +def HTMLInputStream( + source: _BinaryInputStream, + *, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, +) -> HTMLBinaryInputStream: ... + +class HTMLUnicodeInputStream: + reportCharacterErrors: Callable[[str], None] + newLines: list[int] + charEncoding: tuple[Encoding, str] + dataStream: Incomplete + def __init__(self, source: _UnicodeInputStream) -> None: ... + chunk: str + chunkSize: int + chunkOffset: int + errors: list[str] + prevNumLines: int + prevNumCols: int + def reset(self) -> None: ... + + @overload + def openStream(self, source: _SupportsReadT) -> _SupportsReadT: ... + @overload + def openStream(self, source: str | None) -> StringIO: ... + + def position(self) -> tuple[int, int]: ... + def char(self) -> str | None: ... + def readChunk(self, chunkSize: int | None = None) -> bool: ... + def characterErrorsUCS4(self, data: str) -> None: ... + def characterErrorsUCS2(self, data: str) -> None: ... + def charsUntil(self, characters: Iterable[str | bytes | bytearray], opposite: bool = False) -> str: ... + def unget(self, char: str | None) -> None: ... + +class HTMLBinaryInputStream(HTMLUnicodeInputStream): + rawStream: Incomplete + numBytesMeta: int + numBytesChardet: int + override_encoding: Incomplete + transport_encoding: Incomplete + same_origin_parent_encoding: Incomplete + likely_encoding: Incomplete + default_encoding: str + charEncoding: tuple[Encoding, str] + def __init__( + self, + source: _BinaryInputStream, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, + ) -> None: ... + dataStream: Incomplete + def reset(self) -> None: ... + + @overload # type: ignore[override] + def openStream(self, source: _SupportsReadBytesT) -> _SupportsReadBytesT: ... + @overload # type: ignore[override] + def openStream(self, source: ReadableBuffer) -> BytesIO: ... + + def determineEncoding(self, chardet: bool = True): ... + def changeEncoding(self, newEncoding: str | bytes | None) -> None: ... + def detectBOM(self) -> Encoding | None: ... + def detectEncodingMeta(self) -> Encoding | None: ... + +class EncodingBytes(bytes): + def __new__(self, value: bytes) -> Self: ... + def __init__(self, value: bytes) -> None: ... + def __iter__(self) -> Self: ... # type: ignore[override] + def __next__(self) -> bytes: ... + def next(self) -> bytes: ... + def previous(self) -> bytes: ... + def setPosition(self, position: int) -> None: ... + def getPosition(self) -> int | None: ... + + @property + def position(self) -> int | None: ... + @position.setter + def position(self, position: int) -> None: ... + + def getCurrentByte(self) -> bytes: ... + @property + def currentByte(self) -> bytes: ... + def skip(self, chars: bytes | bytearray | Iterable[bytes] = ...) -> bytes | None: ... + def skipUntil(self, chars: bytes | bytearray | Iterable[bytes]) -> bytes | None: ... + def matchBytes(self, bytes: bytes | bytearray) -> bool: ... + def jumpTo(self, bytes: bytes | bytearray) -> Literal[True]: ... + +class EncodingParser: + data: EncodingBytes + encoding: Encoding | None + def __init__(self, data: bytes) -> None: ... + def getEncoding(self) -> Encoding | None: ... + def handleComment(self) -> bool: ... + def handleMeta(self) -> bool: ... + def handlePossibleStartTag(self) -> bool: ... + def handlePossibleEndTag(self) -> bool: ... + def handlePossibleTag(self, endTag: bool | None) -> bool: ... + def handleOther(self) -> bool: ... + def getAttribute(self) -> tuple[bytes, bytes] | None: ... + +class ContentAttrParser: + data: EncodingBytes + def __init__(self, data: EncodingBytes) -> None: ... + def parse(self) -> bytes | None: ... + +def lookupEncoding(encoding: str | bytes | None) -> Encoding | None: ... diff --git a/stubs/html5lib/html5lib/_tokenizer.pyi b/stubs/html5lib/html5lib/_tokenizer.pyi new file mode 100644 index 000000000000..d2c148b5e21d --- /dev/null +++ b/stubs/html5lib/html5lib/_tokenizer.pyi @@ -0,0 +1,128 @@ +from _typeshed import Incomplete +from collections import deque +from collections.abc import Callable, Iterator +from typing import TypedDict, overload, type_check_only + +from ._inputstream import HTMLBinaryInputStream, HTMLUnicodeInputStream, _BinaryInputStream, _UnicodeInputStream +from ._trie import Trie + +@type_check_only +class _DataVars(TypedDict, total=False): + data: str | None + charAsInt: int + +@type_check_only +class _Token(TypedDict, total=False): + type: int + data: str | list[str] + datavars: _DataVars + name: str + selfClosing: bool + selfClosingAcknowledged: bool + publicId: str | None + systemId: str | None + correct: bool + +entitiesTrie: Trie +attributeMap = dict + +class HTMLTokenizer: + # TODO: Use Protocol to allow subclasses to set `stream` that do not inherit from HTMLUnicodeInputStream + stream: HTMLUnicodeInputStream | HTMLBinaryInputStream + parser: Incomplete + escapeFlag: bool + lastFourChars: list[Incomplete] + state: Callable[[], bool] + escape: bool + currentToken: _Token | None + + @overload + def __init__(self, stream: _UnicodeInputStream, parser=None) -> None: ... + @overload + def __init__( + self, + stream: _BinaryInputStream, + parser=None, + *, + override_encoding: str | bytes | None = None, + transport_encoding: str | bytes | None = None, + same_origin_parent_encoding: str | bytes | None = None, + likely_encoding: str | bytes | None = None, + default_encoding: str = "windows-1252", + useChardet: bool = True, + ) -> None: ... + + tokenQueue: deque[_Token] + def __iter__(self) -> Iterator[_Token]: ... + def consumeNumberEntity(self, isHex: bool | None) -> str: ... + def consumeEntity(self, allowedChar: str | None = None, fromAttribute: bool = False) -> None: ... + def processEntityInAttribute(self, allowedChar: str | None) -> None: ... + def emitCurrentToken(self) -> None: ... + def dataState(self) -> bool: ... + def entityDataState(self) -> bool: ... + def rcdataState(self) -> bool: ... + def characterReferenceInRcdata(self) -> bool: ... + def rawtextState(self) -> bool: ... + def scriptDataState(self) -> bool: ... + def plaintextState(self) -> bool: ... + def tagOpenState(self) -> bool: ... + def closeTagOpenState(self) -> bool: ... + def tagNameState(self) -> bool: ... + temporaryBuffer: str + def rcdataLessThanSignState(self) -> bool: ... + def rcdataEndTagOpenState(self) -> bool: ... + def rcdataEndTagNameState(self) -> bool: ... + def rawtextLessThanSignState(self) -> bool: ... + def rawtextEndTagOpenState(self) -> bool: ... + def rawtextEndTagNameState(self) -> bool: ... + def scriptDataLessThanSignState(self) -> bool: ... + def scriptDataEndTagOpenState(self) -> bool: ... + def scriptDataEndTagNameState(self) -> bool: ... + def scriptDataEscapeStartState(self) -> bool: ... + def scriptDataEscapeStartDashState(self) -> bool: ... + def scriptDataEscapedState(self) -> bool: ... + def scriptDataEscapedDashState(self) -> bool: ... + def scriptDataEscapedDashDashState(self) -> bool: ... + def scriptDataEscapedLessThanSignState(self) -> bool: ... + def scriptDataEscapedEndTagOpenState(self) -> bool: ... + def scriptDataEscapedEndTagNameState(self) -> bool: ... + def scriptDataDoubleEscapeStartState(self) -> bool: ... + def scriptDataDoubleEscapedState(self) -> bool: ... + def scriptDataDoubleEscapedDashState(self) -> bool: ... + def scriptDataDoubleEscapedDashDashState(self) -> bool: ... + def scriptDataDoubleEscapedLessThanSignState(self) -> bool: ... + def scriptDataDoubleEscapeEndState(self) -> bool: ... + def beforeAttributeNameState(self) -> bool: ... + def attributeNameState(self) -> bool: ... + def afterAttributeNameState(self) -> bool: ... + def beforeAttributeValueState(self) -> bool: ... + def attributeValueDoubleQuotedState(self) -> bool: ... + def attributeValueSingleQuotedState(self) -> bool: ... + def attributeValueUnQuotedState(self) -> bool: ... + def afterAttributeValueState(self) -> bool: ... + def selfClosingStartTagState(self) -> bool: ... + def bogusCommentState(self) -> bool: ... + def markupDeclarationOpenState(self) -> bool: ... + def commentStartState(self) -> bool: ... + def commentStartDashState(self) -> bool: ... + def commentState(self) -> bool: ... + def commentEndDashState(self) -> bool: ... + def commentEndState(self) -> bool: ... + def commentEndBangState(self) -> bool: ... + def doctypeState(self) -> bool: ... + def beforeDoctypeNameState(self) -> bool: ... + def doctypeNameState(self) -> bool: ... + def afterDoctypeNameState(self) -> bool: ... + def afterDoctypePublicKeywordState(self) -> bool: ... + def beforeDoctypePublicIdentifierState(self) -> bool: ... + def doctypePublicIdentifierDoubleQuotedState(self) -> bool: ... + def doctypePublicIdentifierSingleQuotedState(self) -> bool: ... + def afterDoctypePublicIdentifierState(self) -> bool: ... + def betweenDoctypePublicAndSystemIdentifiersState(self) -> bool: ... + def afterDoctypeSystemKeywordState(self) -> bool: ... + def beforeDoctypeSystemIdentifierState(self) -> bool: ... + def doctypeSystemIdentifierDoubleQuotedState(self) -> bool: ... + def doctypeSystemIdentifierSingleQuotedState(self) -> bool: ... + def afterDoctypeSystemIdentifierState(self) -> bool: ... + def bogusDoctypeState(self) -> bool: ... + def cdataSectionState(self) -> bool: ... diff --git a/stubs/html5lib/html5lib/_trie/__init__.pyi b/stubs/html5lib/html5lib/_trie/__init__.pyi new file mode 100644 index 000000000000..3b0ea9a093bf --- /dev/null +++ b/stubs/html5lib/html5lib/_trie/__init__.pyi @@ -0,0 +1,3 @@ +from .py import Trie as Trie + +__all__ = ["Trie"] diff --git a/stubs/html5lib/html5lib/_trie/_base.pyi b/stubs/html5lib/html5lib/_trie/_base.pyi new file mode 100644 index 000000000000..45725be511b6 --- /dev/null +++ b/stubs/html5lib/html5lib/_trie/_base.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from abc import ABCMeta +from collections.abc import Mapping + +class Trie(Mapping[Incomplete, Incomplete], metaclass=ABCMeta): + def keys(self, prefix=None): ... + def has_keys_with_prefix(self, prefix): ... + def longest_prefix(self, prefix): ... + def longest_prefix_item(self, prefix): ... diff --git a/stubs/html5lib/html5lib/_trie/py.pyi b/stubs/html5lib/html5lib/_trie/py.pyi new file mode 100644 index 000000000000..4d3f7c7bb069 --- /dev/null +++ b/stubs/html5lib/html5lib/_trie/py.pyi @@ -0,0 +1,10 @@ +from ._base import Trie as ABCTrie + +class Trie(ABCTrie): + def __init__(self, data) -> None: ... + def __contains__(self, key): ... + def __len__(self) -> int: ... + def __iter__(self): ... + def __getitem__(self, key): ... + def keys(self, prefix=None): ... + def has_keys_with_prefix(self, prefix): ... diff --git a/stubs/html5lib/html5lib/_utils.pyi b/stubs/html5lib/html5lib/_utils.pyi new file mode 100644 index 000000000000..3197ccb548e0 --- /dev/null +++ b/stubs/html5lib/html5lib/_utils.pyi @@ -0,0 +1,43 @@ +import xml.etree.ElementTree as default_etree +from _typeshed import Incomplete, Unused +from collections.abc import Iterable, Mapping, Sequence +from typing import Final, TypeVar, overload + +__all__ = [ + "default_etree", + "MethodDispatcher", + "isSurrogatePair", + "surrogatePairToCodepoint", + "moduleFactoryFactory", + "supports_lone_surrogates", +] + +supports_lone_surrogates: Final[bool] + +_K = TypeVar("_K") +_V = TypeVar("_V") + +class MethodDispatcher(dict[_K, _V]): + default: _V | None + + @overload # to solve `reportInvalidTypeVarUse` + def __init__(self) -> None: ... + @overload + def __init__(self, items: Iterable[tuple[_K | Iterable[_K], _V]]) -> None: ... + + def __getitem__(self, key: _K) -> _V | None: ... # type: ignore[override] + def __get__(self, instance, owner: Unused = None) -> BoundMethodDispatcher: ... + +class BoundMethodDispatcher(Mapping[Incomplete, Incomplete]): + instance: Incomplete + dispatcher: Incomplete + def __init__(self, instance, dispatcher) -> None: ... + def __getitem__(self, key): ... + def get(self, key, default): ... # type: ignore[override] + def __iter__(self): ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + +def isSurrogatePair(data: Sequence[str | bytes | bytearray]) -> bool: ... +def surrogatePairToCodepoint(data: Sequence[str | bytes | bytearray]) -> int: ... +def moduleFactoryFactory(factory): ... diff --git a/stubs/html5lib/html5lib/constants.pyi b/stubs/html5lib/html5lib/constants.pyi new file mode 100644 index 000000000000..a5c4c5289afd --- /dev/null +++ b/stubs/html5lib/html5lib/constants.pyi @@ -0,0 +1,35 @@ +EOF: None +E: dict[str, str] +namespaces: dict[str, str] +scopingElements: frozenset[tuple[str, str]] +formattingElements: frozenset[tuple[str, str]] +specialElements: frozenset[tuple[str, str]] +htmlIntegrationPointElements: frozenset[tuple[str, str]] +mathmlTextIntegrationPointElements: frozenset[tuple[str, str]] +adjustSVGAttributes: dict[str, str] +adjustMathMLAttributes: dict[str, str] +adjustForeignAttributes: dict[str, tuple[str, str, str] | tuple[None, str, str]] +unadjustForeignAttributes: dict[tuple[str, str], str] +spaceCharacters: frozenset[str] +tableInsertModeElements: frozenset[str] +asciiLowercase: frozenset[str] +asciiUppercase: frozenset[str] +asciiLetters: frozenset[str] +digits: frozenset[str] +hexDigits: frozenset[str] +asciiUpper2Lower: dict[int, int] +headingElements: tuple[str, ...] +voidElements: frozenset[str] +cdataElements: frozenset[str] +rcdataElements: frozenset[str] +booleanAttributes: dict[str, frozenset[str]] +entitiesWindows1252: tuple[int, ...] +xmlEntities: frozenset[str] +entities: dict[str, str] +replacementCharacters: dict[int, str] +tokenTypes: dict[str, int] +tagTokenTypes: frozenset[int] +prefixes: dict[str, str] + +class DataLossWarning(UserWarning): ... +class _ReparseException(Exception): ... diff --git a/stubs/html5lib/html5lib/filters/__init__.pyi b/stubs/html5lib/html5lib/filters/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi b/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi new file mode 100644 index 000000000000..955bae07d8ba --- /dev/null +++ b/stubs/html5lib/html5lib/filters/alphabeticalattributes.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +from . import base + +class Filter(base.Filter[dict[str, Incomplete]]): ... diff --git a/stubs/html5lib/html5lib/filters/base.pyi b/stubs/html5lib/html5lib/filters/base.pyi new file mode 100644 index 000000000000..ddbaf78f74ab --- /dev/null +++ b/stubs/html5lib/html5lib/filters/base.pyi @@ -0,0 +1,10 @@ +from collections.abc import Iterable, Iterator +from typing import Any, Generic, TypeVar + +_T = TypeVar("_T", default=Any) + +class Filter(Generic[_T]): + source: Iterable[_T] + def __init__(self, source: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __getattr__(self, name: str) -> Any: ... # Depends on `source` diff --git a/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi b/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi new file mode 100644 index 000000000000..d8bb75bfcf99 --- /dev/null +++ b/stubs/html5lib/html5lib/filters/inject_meta_charset.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from . import base + +class Filter(base.Filter[dict[str, Incomplete]]): + encoding: str | None + def __init__(self, source: Iterable[dict[str, Incomplete]], encoding: str | None) -> None: ... diff --git a/stubs/html5lib/html5lib/filters/lint.pyi b/stubs/html5lib/html5lib/filters/lint.pyi new file mode 100644 index 000000000000..37da9926b41a --- /dev/null +++ b/stubs/html5lib/html5lib/filters/lint.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from . import base + +spaceCharacters: str + +class Filter(base.Filter[dict[str, Incomplete]]): + require_matching_tags: bool + def __init__(self, source: Iterable[dict[str, Incomplete]], require_matching_tags: bool = True) -> None: ... diff --git a/stubs/html5lib/html5lib/filters/optionaltags.pyi b/stubs/html5lib/html5lib/filters/optionaltags.pyi new file mode 100644 index 000000000000..9050d864e756 --- /dev/null +++ b/stubs/html5lib/html5lib/filters/optionaltags.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from . import base + +class Filter(base.Filter[dict[str, Incomplete]]): + def slider(self) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... + def is_optional_start(self, tagname: str, previous, next) -> bool: ... + def is_optional_end(self, tagname: str, next) -> bool: ... diff --git a/stubs/html5lib/html5lib/filters/sanitizer.pyi b/stubs/html5lib/html5lib/filters/sanitizer.pyi new file mode 100644 index 000000000000..3308d7fd60cd --- /dev/null +++ b/stubs/html5lib/html5lib/filters/sanitizer.pyi @@ -0,0 +1,51 @@ +import re +from _typeshed import Incomplete +from collections.abc import Iterable +from typing_extensions import deprecated + +from . import base + +__all__ = ["Filter"] + +allowed_elements: frozenset[tuple[str, str]] +allowed_attributes: frozenset[tuple[None, str] | tuple[str, str]] +attr_val_is_uri: frozenset[tuple[None, str] | tuple[str, str]] +svg_attr_val_allows_ref: frozenset[tuple[None, str]] +svg_allow_local_href: frozenset[tuple[None, str]] +allowed_css_properties: frozenset[str] +allowed_css_keywords: frozenset[str] +allowed_svg_properties: frozenset[str] +allowed_protocols: frozenset[str] +allowed_content_types: frozenset[str] +data_content_type: re.Pattern[str] + +@deprecated("html5lib's sanitizer is deprecated; see https://github.com/html5lib/html5lib-python/issues/443") +class Filter(base.Filter[dict[str, Incomplete]]): + allowed_elements: Iterable[tuple[str | None, str]] + allowed_attributes: Iterable[tuple[str | None, str]] + allowed_css_properties: Iterable[str] + allowed_css_keywords: Iterable[str] + allowed_svg_properties: Iterable[str] + allowed_protocols: Iterable[str] + allowed_content_types: Iterable[str] + attr_val_is_uri: Iterable[tuple[str | None, str]] + svg_attr_val_allows_ref: Iterable[tuple[str | None, str]] + svg_allow_local_href: Iterable[tuple[str | None, str]] + def __init__( + self, + source: Iterable[dict[str, Incomplete]], + allowed_elements: Iterable[tuple[str | None, str]] = ..., + allowed_attributes: Iterable[tuple[str | None, str]] = ..., + allowed_css_properties: Iterable[str] = ..., + allowed_css_keywords: Iterable[str] = ..., + allowed_svg_properties: Iterable[str] = ..., + allowed_protocols: Iterable[str] = ..., + allowed_content_types: Iterable[str] = ..., + attr_val_is_uri: Iterable[tuple[str | None, str]] = ..., + svg_attr_val_allows_ref: Iterable[tuple[str | None, str]] = ..., + svg_allow_local_href: Iterable[tuple[str | None, str]] = ..., + ) -> None: ... + def sanitize_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete] | None: ... + def allowed_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def disallowed_token(self, token: dict[str, Incomplete]) -> dict[str, Incomplete]: ... + def sanitize_css(self, style: str) -> str: ... diff --git a/stubs/html5lib/html5lib/filters/whitespace.pyi b/stubs/html5lib/html5lib/filters/whitespace.pyi new file mode 100644 index 000000000000..89334b070913 --- /dev/null +++ b/stubs/html5lib/html5lib/filters/whitespace.pyi @@ -0,0 +1,12 @@ +import re +from _typeshed import Incomplete + +from . import base + +spaceCharacters: str +SPACES_REGEX: re.Pattern[str] + +class Filter(base.Filter[dict[str, Incomplete]]): + spacePreserveElements: frozenset[str] + +def collapse_spaces(text: str) -> str: ... diff --git a/stubs/html5lib/html5lib/html5parser.pyi b/stubs/html5lib/html5lib/html5parser.pyi new file mode 100644 index 000000000000..5f78cf43a2ba --- /dev/null +++ b/stubs/html5lib/html5lib/html5parser.pyi @@ -0,0 +1,66 @@ +from _typeshed import Incomplete +from typing import Any, Literal, overload +from xml.etree.ElementTree import Element + +from ._inputstream import _InputStream +from ._tokenizer import HTMLTokenizer +from .treebuilders.base import TreeBuilder + +@overload +def parse( + doc: _InputStream, treebuilder: Literal["etree"] = "etree", namespaceHTMLElements: bool = True, **kwargs +) -> Element: ... +@overload +def parse(doc: _InputStream, treebuilder: str, namespaceHTMLElements: bool = True, **kwargs): ... + +def parseFragment( + doc: _InputStream, container: str = "div", treebuilder: str = "etree", namespaceHTMLElements: bool = True, **kwargs +): ... +def method_decorator_metaclass(function): ... + +class HTMLParser: + strict: bool + tree: Incomplete + errors: list[Incomplete] + phases: Incomplete + def __init__( + self, + tree: str | type[TreeBuilder] | None = None, + strict: bool = False, + namespaceHTMLElements: bool = True, + debug: bool = False, + ) -> None: ... + firstStartTag: bool + log: Incomplete + compatMode: str + container: str + innerHTML: Incomplete + phase: Incomplete + lastPhase: Incomplete + beforeRCDataPhase: Incomplete + framesetOK: bool + tokenizer: HTMLTokenizer + def reset(self) -> None: ... + @property + def documentEncoding(self) -> str | None: ... + def isHTMLIntegrationPoint(self, element: Element) -> bool: ... + def isMathMLTextIntegrationPoint(self, element: Element) -> bool: ... + def mainLoop(self) -> None: ... + def parse(self, stream: _InputStream, scripting: bool = ..., **kwargs): ... + def parseFragment(self, stream: _InputStream, *args, **kwargs): ... + def parseError(self, errorcode: str = "XXX-undefined-error", datavars=None) -> None: ... + def adjustMathMLAttributes(self, token: dict[str, Any]) -> None: ... + def adjustSVGAttributes(self, token: dict[str, Any]) -> None: ... + def adjustForeignAttributes(self, token: dict[str, Any]) -> None: ... + def reparseTokenNormal(self, token: dict[str, Any]) -> None: ... + def resetInsertionMode(self) -> None: ... + originalPhase: Incomplete + def parseRCDataRawtext(self, token, contentType: Literal["RAWTEXT", "RCDATA"]) -> None: ... + +def getPhases(debug: bool | None) -> dict[str, type]: ... +def adjust_attributes(token: dict[str, Any], replacements: dict[str, Any]) -> None: ... +def impliedTagToken( + name: str, type: str = "EndTag", attributes: dict[str, Any] | None = None, selfClosing: bool = False +) -> dict[str, Any]: ... + +class ParseError(Exception): ... diff --git a/stubs/html5lib/html5lib/serializer.pyi b/stubs/html5lib/html5lib/serializer.pyi new file mode 100644 index 000000000000..a4e990c78803 --- /dev/null +++ b/stubs/html5lib/html5lib/serializer.pyi @@ -0,0 +1,102 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import Literal, overload + +def htmlentityreplace_errors(exc: UnicodeError) -> tuple[str | bytes, int]: ... + +@overload +def serialize( + input, + tree: Literal["dom", "genshi", "lxml", "etree"] = "etree", + encoding: Literal[""] | None = None, + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, +) -> str: ... +@overload +def serialize( + input, + tree: Literal["dom", "genshi", "lxml", "etree"] = "etree", + encoding: str = ..., + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, +) -> bytes: ... + +class HTMLSerializer: + quote_attr_values: Literal["legacy", "spec", "always"] + quote_char: str + use_best_quote_char: bool + omit_optional_tags: bool + minimize_boolean_attributes: bool + use_trailing_solidus: bool + space_before_trailing_solidus: bool + escape_lt_in_attrs: bool + escape_rcdata: bool + resolve_entities: bool + alphabetical_attributes: bool + inject_meta_charset: bool + strip_whitespace: bool + sanitize: bool + options: tuple[str, ...] + errors: list[Incomplete] + strict: bool + def __init__( + self, + *, + quote_attr_values: Literal["legacy", "spec", "always"] = "legacy", + quote_char: str = '"', + use_best_quote_char: bool = ..., # default value depends on whether quote_char was passed + omit_optional_tags: bool = True, + minimize_boolean_attributes: bool = True, + use_trailing_solidus: bool = False, + space_before_trailing_solidus: bool = True, + escape_lt_in_attrs: bool = False, + escape_rcdata: bool = False, + resolve_entities: bool = True, + alphabetical_attributes: bool = False, + inject_meta_charset: bool = True, + strip_whitespace: bool = False, + sanitize: bool = False, + ) -> None: ... + def encode(self, string: str) -> str | bytes: ... # result depends on self.encoding + def encodeStrict(self, string: str) -> str | bytes: ... # result depends on self.encoding + encoding: str | None + + @overload + def serialize(self, treewalker, encoding: Literal[""] | None = None) -> Generator[str]: ... + @overload + def serialize(self, treewalker, encoding: str = ...) -> Generator[bytes]: ... + + @overload + def render(self, treewalker, encoding: Literal[""] | None = None) -> str: ... + @overload + def render(self, treewalker, encoding: str = ...) -> bytes: ... + + def serializeError(self, data="XXX ERROR MESSAGE NEEDED") -> None: ... + +class SerializeError(Exception): ... diff --git a/stubs/html5lib/html5lib/treeadapters/__init__.pyi b/stubs/html5lib/html5lib/treeadapters/__init__.pyi new file mode 100644 index 000000000000..49b1ebb296a2 --- /dev/null +++ b/stubs/html5lib/html5lib/treeadapters/__init__.pyi @@ -0,0 +1,3 @@ +from . import genshi as genshi, sax as sax + +__all__ = ["sax", "genshi"] diff --git a/stubs/html5lib/html5lib/treeadapters/genshi.pyi b/stubs/html5lib/html5lib/treeadapters/genshi.pyi new file mode 100644 index 000000000000..fa42d5d0908b --- /dev/null +++ b/stubs/html5lib/html5lib/treeadapters/genshi.pyi @@ -0,0 +1 @@ +def to_genshi(walker) -> None: ... diff --git a/stubs/html5lib/html5lib/treeadapters/sax.pyi b/stubs/html5lib/html5lib/treeadapters/sax.pyi new file mode 100644 index 000000000000..22c93013ce67 --- /dev/null +++ b/stubs/html5lib/html5lib/treeadapters/sax.pyi @@ -0,0 +1,3 @@ +prefix_mapping: dict[str, str] + +def to_sax(walker, handler) -> None: ... diff --git a/stubs/html5lib/html5lib/treebuilders/__init__.pyi b/stubs/html5lib/html5lib/treebuilders/__init__.pyi new file mode 100644 index 000000000000..7fc1af410d92 --- /dev/null +++ b/stubs/html5lib/html5lib/treebuilders/__init__.pyi @@ -0,0 +1,5 @@ +from typing import Literal + +treeBuilderCache: dict[str, type] + +def getTreeBuilder(treeType: Literal["dom", "etree", "lxml"], implementation=None, **kwargs): ... diff --git a/stubs/html5lib/html5lib/treebuilders/base.pyi b/stubs/html5lib/html5lib/treebuilders/base.pyi new file mode 100644 index 000000000000..59137fe3239f --- /dev/null +++ b/stubs/html5lib/html5lib/treebuilders/base.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete + +Marker: Incomplete +listElementsMap: dict[str | None, tuple[frozenset[tuple[str, str]], bool]] + +class Node: + name: str + parent: Incomplete + value: Incomplete + attributes: Incomplete + childNodes: Incomplete + def __init__(self, name: str) -> None: ... + def appendChild(self, node) -> None: ... + def insertText(self, data, insertBefore=None) -> None: ... + def insertBefore(self, node, refNode) -> None: ... + def removeChild(self, node) -> None: ... + def reparentChildren(self, newParent) -> None: ... + def cloneNode(self) -> None: ... + def hasContent(self) -> None: ... + +class ActiveFormattingElements(list[Incomplete]): + def append(self, node) -> None: ... + def nodesEqual(self, node1, node2) -> bool: ... + +class TreeBuilder: + documentClass: Incomplete + elementClass: Incomplete + commentClass: Incomplete + doctypeClass: Incomplete + fragmentClass: Incomplete + defaultNamespace: str | None + def __init__(self, namespaceHTMLElements: bool | None) -> None: ... + openElements: Incomplete + activeFormattingElements: Incomplete + headPointer: Incomplete + formPointer: Incomplete + insertFromTable: bool + document: Incomplete + def reset(self) -> None: ... + def elementInScope(self, target, variant=None): ... + def reconstructActiveFormattingElements(self) -> None: ... + def clearActiveFormattingElements(self) -> None: ... + def elementInActiveFormattingElements(self, name): ... + def insertRoot(self, token) -> None: ... + def insertDoctype(self, token) -> None: ... + def insertComment(self, token, parent=None) -> None: ... + def createElement(self, token): ... + def insertElementNormal(self, token): ... + def insertElementTable(self, token): ... + def insertText(self, data, parent=None) -> None: ... + def getTableMisnestedNodePosition(self): ... + def generateImpliedEndTags(self, exclude=None) -> None: ... + def getDocument(self): ... + def getFragment(self): ... + def testSerializer(self, node): ... diff --git a/stubs/html5lib/html5lib/treebuilders/dom.pyi b/stubs/html5lib/html5lib/treebuilders/dom.pyi new file mode 100644 index 000000000000..d8049c383cf1 --- /dev/null +++ b/stubs/html5lib/html5lib/treebuilders/dom.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from types import ModuleType + +def getDomBuilder(DomImplementation) -> dict[str, Incomplete]: ... + +getDomModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treebuilders/etree.pyi b/stubs/html5lib/html5lib/treebuilders/etree.pyi new file mode 100644 index 000000000000..b9dfabb88835 --- /dev/null +++ b/stubs/html5lib/html5lib/treebuilders/etree.pyi @@ -0,0 +1,10 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from types import ModuleType + +tag_regexp: re.Pattern[str] + +def getETreeBuilder(ElementTreeImplementation, fullTree: bool = False) -> dict[str, Incomplete]: ... + +getETreeModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi b/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi new file mode 100644 index 000000000000..665eb117d358 --- /dev/null +++ b/stubs/html5lib/html5lib/treebuilders/etree_lxml.pyi @@ -0,0 +1,45 @@ +import re +from _typeshed import Incomplete + +from . import base + +fullTree: bool +tag_regexp: re.Pattern[str] +comment_type: Incomplete + +class DocumentType: + name: Incomplete + publicId: Incomplete + systemId: Incomplete + def __init__(self, name, publicId, systemId) -> None: ... + +class Document: + def __init__(self) -> None: ... + def appendChild(self, element) -> None: ... + @property + def childNodes(self): ... + +def testSerializer(element) -> str: ... +def tostring(element) -> str: ... + +class TreeBuilder(base.TreeBuilder): + documentClass: Incomplete + doctypeClass: Incomplete + elementClass: Incomplete + commentClass: Incomplete + fragmentClass: Incomplete + implementation: Incomplete + namespaceHTMLElements: Incomplete + def __init__(self, namespaceHTMLElements, fullTree: bool = False): ... + insertComment: Incomplete + initial_comments: Incomplete + doctype: Incomplete + def reset(self) -> None: ... + def testSerializer(self, element): ... + def getDocument(self): ... + def getFragment(self): ... + def insertDoctype(self, token) -> None: ... + def insertCommentInitial(self, data, parent=None) -> None: ... + def insertCommentMain(self, data, parent=None) -> None: ... + document: Incomplete + def insertRoot(self, token) -> None: ... diff --git a/stubs/html5lib/html5lib/treewalkers/__init__.pyi b/stubs/html5lib/html5lib/treewalkers/__init__.pyi new file mode 100644 index 000000000000..247912e69830 --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/__init__.pyi @@ -0,0 +1,7 @@ +from types import ModuleType + +__all__ = ["getTreeWalker", "pprint"] + +def getTreeWalker(treeType: str, implementation: ModuleType | None = None, **kwargs): ... +def concatenateCharacterTokens(tokens): ... +def pprint(walker) -> str: ... diff --git a/stubs/html5lib/html5lib/treewalkers/base.pyi b/stubs/html5lib/html5lib/treewalkers/base.pyi new file mode 100644 index 000000000000..2ef37965b6d2 --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/base.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +__all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN", "TreeWalker", "NonRecursiveTreeWalker"] + +DOCUMENT: int +DOCTYPE: int +TEXT: int +ELEMENT: int +COMMENT: int +ENTITY: int +UNKNOWN: str +spaceCharacters: str + +class TreeWalker: + tree: Incomplete + def __init__(self, tree) -> None: ... + def __iter__(self): ... + def error(self, msg): ... + def emptyTag(self, namespace, name, attrs, hasChildren: bool = False) -> None: ... + def startTag(self, namespace, name, attrs): ... + def endTag(self, namespace, name): ... + def text(self, data) -> None: ... + def comment(self, data): ... + def doctype(self, name, publicId=None, systemId=None): ... + def entity(self, name): ... + def unknown(self, nodeType): ... + +class NonRecursiveTreeWalker(TreeWalker): + def getNodeDetails(self, node) -> None: ... + def getFirstChild(self, node) -> None: ... + def getNextSibling(self, node) -> None: ... + def getParentNode(self, node) -> None: ... + def __iter__(self): ... diff --git a/stubs/html5lib/html5lib/treewalkers/dom.pyi b/stubs/html5lib/html5lib/treewalkers/dom.pyi new file mode 100644 index 000000000000..72a71d00a26a --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/dom.pyi @@ -0,0 +1,7 @@ +from .base import NonRecursiveTreeWalker + +class TreeWalker(NonRecursiveTreeWalker): + def getNodeDetails(self, node): ... + def getFirstChild(self, node): ... + def getNextSibling(self, node): ... + def getParentNode(self, node): ... diff --git a/stubs/html5lib/html5lib/treewalkers/etree.pyi b/stubs/html5lib/html5lib/treewalkers/etree.pyi new file mode 100644 index 000000000000..94878061a818 --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/etree.pyi @@ -0,0 +1,9 @@ +import re +from collections.abc import Callable +from types import ModuleType + +tag_regexp: re.Pattern[str] + +def getETreeBuilder(ElementTreeImplementation): ... + +getETreeModule: Callable[..., ModuleType] diff --git a/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi b/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi new file mode 100644 index 000000000000..4071bb068650 --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/etree_lxml.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete +from typing import SupportsIndex, overload + +from .base import NonRecursiveTreeWalker + +@overload +def ensure_str(s: None) -> None: ... +@overload +def ensure_str(s: str | bytes | bytearray) -> str: ... + +class Root: + elementtree: Incomplete + children: list[Incomplete] + text: str | None + tail: str | None + def __init__(self, et) -> None: ... + def __getitem__(self, key: SupportsIndex): ... + def getnext(self) -> None: ... + def __len__(self) -> int: ... + +class Doctype: + root_node: Incomplete + name: Incomplete + public_id: Incomplete + system_id: Incomplete + text: Incomplete + tail: Incomplete + def __init__(self, root_node, name, public_id, system_id) -> None: ... + def getnext(self): ... + +class FragmentRoot(Root): + children: Incomplete + text: Incomplete + def __init__(self, children) -> None: ... + def getnext(self) -> None: ... + +class FragmentWrapper: + root_node: Incomplete + obj: Incomplete + text: Incomplete + tail: Incomplete + def __init__(self, fragment_root, obj) -> None: ... + def __getattr__(self, name: str): ... + def getnext(self): ... + def __getitem__(self, key): ... + def __bool__(self) -> bool: ... + def getparent(self) -> None: ... + def __unicode__(self) -> str: ... + def __len__(self) -> int: ... + +class TreeWalker(NonRecursiveTreeWalker): + fragmentChildren: Incomplete + filter: Incomplete + def __init__(self, tree) -> None: ... + def getNodeDetails(self, node): ... + def getFirstChild(self, node): ... + def getNextSibling(self, node): ... + def getParentNode(self, node): ... diff --git a/stubs/html5lib/html5lib/treewalkers/genshi.pyi b/stubs/html5lib/html5lib/treewalkers/genshi.pyi new file mode 100644 index 000000000000..2e75daf20017 --- /dev/null +++ b/stubs/html5lib/html5lib/treewalkers/genshi.pyi @@ -0,0 +1,5 @@ +from . import base + +class TreeWalker(base.TreeWalker): + def __iter__(self): ... + def tokens(self, event, next) -> None: ... diff --git a/stubs/httplib2/@tests/stubtest_allowlist.txt b/stubs/httplib2/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..6b90fbdac749 --- /dev/null +++ b/stubs/httplib2/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# __getattr__() replaced with actual field in stub +httplib2.Response.dict diff --git a/stubs/httplib2/METADATA.toml b/stubs/httplib2/METADATA.toml new file mode 100644 index 000000000000..69b14a50a93a --- /dev/null +++ b/stubs/httplib2/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.32.0" +upstream-repository = "https://github.com/httplib2/httplib2" diff --git a/stubs/httplib2/httplib2/__init__.pyi b/stubs/httplib2/httplib2/__init__.pyi new file mode 100644 index 000000000000..7be7c15e3ea0 --- /dev/null +++ b/stubs/httplib2/httplib2/__init__.pyi @@ -0,0 +1,232 @@ +import builtins +import email.message +import http.client +import re +from _ssl import _PasswordType +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, MaybeNone, StrOrBytesPath +from collections.abc import Generator +from ssl import _SSLMethod +from typing import Any, ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Self + +from .error import * + +_T = TypeVar("_T", default=str) +_R = TypeVar("_R") +_D = TypeVar("_D") + +__author__: Final[str] +__copyright__: Final[str] +__contributors__: Final[list[str]] +__license__: Final[str] +__version__: Final[str] +__all__ = [ + "debuglevel", + "FailedToDecompressContent", + "Http", + "HttpLib2Error", + "ProxyInfo", + "RedirectLimit", + "RedirectMissingLocation", + "Response", + "RETRIES", + "UnimplementedDigestAuthOptionError", + "UnimplementedHmacDigestAuthOptionError", +] + +def has_timeout(timeout: float | None) -> bool: ... + +debuglevel: Final[int] +RETRIES: Final[int] +DEFAULT_MAX_REDIRECTS: Final[int] +HOP_BY_HOP: Final[list[str]] +SAFE_METHODS: Final[tuple[str, ...]] +REDIRECT_CODES: Final[frozenset[int]] +CA_CERTS: Final[str] +DEFAULT_TLS_VERSION: Final[_SSLMethod] +URI: Final[re.Pattern[str]] + +def parse_uri(uri: str) -> tuple[str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone]: ... +def urlnorm(uri: str) -> tuple[str | MaybeNone, str | MaybeNone, str | MaybeNone, str | MaybeNone]: ... + +re_url_scheme: Final[re.Pattern[str]] +re_unsafe: Final[re.Pattern[str]] + +def safename(filename: str | bytes) -> str: ... + +NORMALIZE_SPACE: Final[re.Pattern[str]] +USE_WWW_AUTH_STRICT_PARSING: Final[int] + +class Authentication: + path: Incomplete + host: Incomplete + credentials: Incomplete + http: Incomplete + def __init__(self, credentials, host, request_uri: str, headers, response, content, http) -> None: ... + def depth(self, request_uri: str) -> int: ... + def inscope(self, host: str, request_uri: str) -> bool: ... + def request(self, method, request_uri, headers, content) -> None: ... + def response(self, response, content) -> bool: ... + def __eq__(self, auth: object) -> bool: ... + def __ne__(self, auth: object) -> bool: ... + def __lt__(self, auth: object) -> bool: ... + def __gt__(self, auth: object) -> bool: ... + def __le__(self, auth: object) -> bool: ... + def __ge__(self, auth: object) -> bool: ... + def __bool__(self) -> bool: ... + +class BasicAuthentication(Authentication): + def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... + def request(self, method, request_uri, headers, content) -> None: ... + +class DigestAuthentication(Authentication): + challenge: Incomplete + A1: Incomplete + def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... + def request(self, method, request_uri, headers, content, cnonce=None): ... + def response(self, response, content) -> bool: ... + +class HmacDigestAuthentication(Authentication): + challenge: Incomplete + hashmod: Incomplete + pwhashmod: Incomplete + key: Incomplete + __author__: ClassVar[str] + def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... + def request(self, method, request_uri, headers, content) -> None: ... + def response(self, response, content) -> bool: ... + +class WsseAuthentication(Authentication): + def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... + def request(self, method, request_uri, headers, content) -> None: ... + +class GoogleLoginAuthentication(Authentication): + Auth: str + def __init__(self, credentials, host, request_uri, headers, response, content, http) -> None: ... + def request(self, method, request_uri, headers, content) -> None: ... + +class FileCache: + cache: Incomplete + safe: Incomplete + def __init__(self, cache, safe=...) -> None: ... + def get(self, key): ... + def set(self, key, value) -> None: ... + def delete(self, key) -> None: ... + +class Credentials: + credentials: Incomplete + def __init__(self) -> None: ... + def add(self, name, password, domain: str = "") -> None: ... + def clear(self) -> None: ... + def iter(self, domain) -> Generator[tuple[str, str]]: ... + +class KeyCerts(Credentials): + def add(self, key, cert, domain, password) -> None: ... # type: ignore[override] + def iter(self, domain) -> Generator[tuple[str, str, str]]: ... # type: ignore[override] + +class AllHosts: ... + +class ProxyInfo: + bypass_hosts: Incomplete + def __init__( + self, proxy_type, proxy_host, proxy_port, proxy_rdns: bool = True, proxy_user=None, proxy_pass=None, proxy_headers=None + ) -> None: ... + def astuple(self): ... + def isgood(self): ... + def applies_to(self, hostname): ... + def bypass_host(self, hostname): ... + +def proxy_info_from_environment(method: Literal["http", "https"] = "http") -> ProxyInfo | None: ... +def proxy_info_from_url(url: str, method: Literal["http", "https"] = "http", noproxy: str | None = None) -> ProxyInfo: ... + +class HTTPConnectionWithTimeout(http.client.HTTPConnection): + proxy_info: Incomplete + def __init__(self, host, port=None, timeout=None, proxy_info=None) -> None: ... + sock: Incomplete + def connect(self) -> None: ... + +class HTTPSConnectionWithTimeout(http.client.HTTPSConnection): + disable_ssl_certificate_validation: bool + ca_certs: StrOrBytesPath | None + proxy_info: Incomplete + key_file: StrOrBytesPath | None + cert_file: StrOrBytesPath | None + key_password: _PasswordType | None + def __init__( + self, + host: str, + port: int | None = None, + key_file: StrOrBytesPath | None = None, + cert_file: StrOrBytesPath | None = None, + timeout: float | None = None, + proxy_info=None, + ca_certs: StrOrBytesPath | None = None, + disable_ssl_certificate_validation: bool = False, + tls_maximum_version=None, + tls_minimum_version=None, + key_password: _PasswordType | None = None, + ) -> None: ... + sock: Incomplete + def connect(self) -> None: ... + +SCHEME_TO_CONNECTION: Final[dict[Literal["http", "https"], type[http.client.HTTPConnection]]] + +class Http: + proxy_info: Incomplete + ca_certs: Incomplete + disable_ssl_certificate_validation: bool + tls_maximum_version: Incomplete + tls_minimum_version: Incomplete + connections: Incomplete + cache: FileCache + credentials: Credentials + certificates: KeyCerts + authorizations: list[Authentication] + follow_redirects: bool + redirect_codes: frozenset[int] + optimistic_concurrency_methods: list[str] + safe_methods: list[str] + follow_all_redirects: bool + ignore_etag: bool + force_exception_to_status_code: bool + timeout: float | None + forward_authorization_headers: bool + limit_kwargs: dict[str, float] + def __init__( + self, + cache: str | FileCache | None = None, + timeout: float | None = None, + proxy_info=..., + ca_certs=None, + disable_ssl_certificate_validation: bool = False, + tls_maximum_version=None, + tls_minimum_version=None, + decode_limit_hard: ConvertibleToInt | None = None, + decode_limit_safe: ConvertibleToInt | None = None, + decode_limit_ratio: ConvertibleToFloat | None = None, + decode_limit_chunk: ConvertibleToInt | None = None, + ) -> None: ... + def close(self) -> None: ... + def add_credentials(self, name, password, domain: str = "") -> None: ... + def add_certificate(self, key, cert, domain, password=None) -> None: ... + def clear_credentials(self) -> None: ... + def request(self, uri, method: str = "GET", body=None, headers=None, redirections=5, connection_type=None): ... + +class Response(dict[str, str | _T]): + fromcache: bool + version: int + status: int + reason: str + previous: Response[_T] | None + def __init__(self, info: http.client.HTTPResponse | email.message.Message | builtins.dict[str, _T]) -> None: ... + @property + def dict(self) -> Self: ... + +@overload +def try_value_or_env( + to: type[_R], value: Any, env_key: str, default: None = None # `value` type depends on what `to()` can convert +) -> _R | None: ... +@overload +def try_value_or_env( + to: type[_R], value: Any, env_key: str, default: _D = ... # `value` type depends on what `to()` can convert +) -> _R | _D: ... diff --git a/stubs/httplib2/httplib2/auth.pyi b/stubs/httplib2/httplib2/auth.pyi new file mode 100644 index 000000000000..8e4faf3b08fc --- /dev/null +++ b/stubs/httplib2/httplib2/auth.pyi @@ -0,0 +1,18 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Final + +UNQUOTE_PAIRS: Final[re.Pattern[str]] +unquote: Callable[..., str] +tchar: Final[str] +token: Incomplete # types from pyparsing library +token68: Incomplete +quoted_string: Incomplete +auth_param_name: Incomplete +auth_param: Incomplete +params: Incomplete +scheme: Incomplete +challenge: Incomplete +authentication_info: Incomplete +www_authenticate: Incomplete diff --git a/stubs/httplib2/httplib2/certs.pyi b/stubs/httplib2/httplib2/certs.pyi new file mode 100644 index 000000000000..197e1ced1d60 --- /dev/null +++ b/stubs/httplib2/httplib2/certs.pyi @@ -0,0 +1,10 @@ +from collections.abc import Callable +from typing import Final + +certifi_available: bool +certifi_where: Callable[[], str] | None +custom_ca_locater_available: bool +custom_ca_locater_where: Callable[..., str] | None +BUILTIN_CA_CERTS: Final[str] + +def where() -> str: ... diff --git a/stubs/httplib2/httplib2/decode.pyi b/stubs/httplib2/httplib2/decode.pyi new file mode 100644 index 000000000000..9c9e14ca1601 --- /dev/null +++ b/stubs/httplib2/httplib2/decode.pyi @@ -0,0 +1,52 @@ +from typing import Final, Protocol + +class DecodeRatioError(Exception): ... +class DecodeLimitError(Exception): ... + +class DecoderProtocol(Protocol): + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... + def consume_bytes(self, data: bytes, chunk_size: int = 65536) -> bytes: ... + +class ZlibDecoder(DecoderProtocol): + __slots__ = ("_decoder",) + WBITS_DEFLATE: Final = -15 + WBITS_ZLIB: Final = 15 + WBITS_GZIP: Final = 31 + WBITS_AUTO_GZIP_ZLIB: Final = 47 + + def __init__(self, wbits: int = 47): ... + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... + +def DeflateDecoder() -> ZlibDecoder: ... + +class LimitDecoder(DecoderProtocol): + __slots__ = ( + "_decoder", + "_ratio", + "_chunk_size", + "_safe_limit", + "_hard_limit", + "_consumed_length", + "_output_length", + "_input_buffer", + "_flushed", + ) + + def __init__( + self, + decoder: DecoderProtocol, + ratio: float = 100, + chunk_size: int = 65536, + safe_limit: int = 10485760, + hard_limit: int = ..., + ) -> None: ... + @property + def needs_input(self) -> bool: ... + def decode(self, b: bytes) -> bytes: ... + def flush(self) -> bytes: ... diff --git a/stubs/httplib2/httplib2/error.pyi b/stubs/httplib2/httplib2/error.pyi new file mode 100644 index 000000000000..fa94b45ba8c0 --- /dev/null +++ b/stubs/httplib2/httplib2/error.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +from httplib2 import Response + +class HttpLib2Error(Exception): ... + +class HttpLib2ErrorWithResponse(HttpLib2Error): + response: Response | dict[str, Incomplete] | None + content: str | bytes | None + def __init__( + self, desc: str | None, response: Response | dict[str, Incomplete] | None, content: str | bytes | None + ) -> None: ... + +class RedirectMissingLocation(HttpLib2ErrorWithResponse): ... +class RedirectLimit(HttpLib2ErrorWithResponse): ... +class FailedToDecompressContent(HttpLib2ErrorWithResponse): ... +class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse): ... +class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse): ... +class MalformedHeader(HttpLib2Error): ... +class RelativeURIError(HttpLib2Error): ... +class ServerNotFoundError(HttpLib2Error): ... +class ProxiesUnavailableError(HttpLib2Error): ... diff --git a/stubs/httplib2/httplib2/iri2uri.pyi b/stubs/httplib2/httplib2/iri2uri.pyi new file mode 100644 index 000000000000..d935ed36f15e --- /dev/null +++ b/stubs/httplib2/httplib2/iri2uri.pyi @@ -0,0 +1,14 @@ +from typing import Final, TypeVar + +_T = TypeVar("_T") + +__author__: Final[str] +__copyright__: Final[str] +__contributors__: Final[list[str]] +__version__: Final[str] +__license__: Final[str] + +escape_range: list[tuple[int, int]] + +def encode(c: str) -> str: ... +def iri2uri(uri: _T) -> _T: ... diff --git a/stubs/hvac/METADATA.toml b/stubs/hvac/METADATA.toml new file mode 100644 index 000000000000..fe7a9ba835b4 --- /dev/null +++ b/stubs/hvac/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.4.*" +upstream-repository = "https://github.com/hvac/hvac" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/hvac/hvac/__init__.pyi b/stubs/hvac/hvac/__init__.pyi new file mode 100644 index 000000000000..cc4d88cd6958 --- /dev/null +++ b/stubs/hvac/hvac/__init__.pyi @@ -0,0 +1,3 @@ +from hvac.v1 import Client as Client + +__all__ = ("Client",) diff --git a/stubs/hvac/hvac/adapters.pyi b/stubs/hvac/hvac/adapters.pyi new file mode 100644 index 000000000000..3bd1b3e0d981 --- /dev/null +++ b/stubs/hvac/hvac/adapters.pyi @@ -0,0 +1,66 @@ +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from typing import Any, Generic, TypeVar, type_check_only +from typing_extensions import Self + +from requests import Response, Session + +_R = TypeVar("_R") + +class Adapter(Generic[_R], metaclass=ABCMeta): + @classmethod + def from_adapter(cls, adapter: Adapter[_R]) -> Self: ... + base_uri: str + token: str | None + namespace: str | None + session: Session + allow_redirects: bool + ignore_exceptions: bool + strict_http: bool + request_header: bool + def __init__( + self, + base_uri: str = "http://localhost:8200", + token: str | None = None, + cert: tuple[str, str] | None = None, + verify: bool = True, + timeout: int = 30, + proxies: Mapping[str, str] | None = None, + allow_redirects: bool = True, + session: Session | None = None, + namespace: str | None = None, + ignore_exceptions: bool = False, + strict_http: bool = False, + request_header: bool = True, + ) -> None: ... + @staticmethod + def urljoin(*args: object) -> str: ... + def close(self) -> None: ... + def get(self, url: str, **kwargs: Any) -> _R: ... + def post(self, url: str, **kwargs: Any) -> _R: ... + def put(self, url: str, **kwargs: Any) -> _R: ... + def delete(self, url: str, **kwargs: Any) -> _R: ... + def list(self, url: str, **kwargs: Any) -> _R: ... + def head(self, url: str, **kwargs: Any) -> _R: ... + def login(self, url: str, use_token: bool = True, **kwargs: Any) -> Response: ... + @abstractmethod + def get_login_token(self, response: _R) -> str: ... + @abstractmethod + def request( + self, method, url: str, headers: Mapping[str, str] | None = None, raise_exception: bool = True, **kwargs: Any + ) -> _R: ... + +@type_check_only +class _GenericRawAdapter(Adapter[_R]): + def get_login_token(self, response: _R) -> str: ... + def request( + self, method: str, url: str, headers: Mapping[str, str] | None = None, raise_exception: bool = True, **kwargs: Any + ) -> _R: ... + +class RawAdapter(_GenericRawAdapter[Response]): ... + +class JSONAdapter(_GenericRawAdapter[Response | dict[Any, Any]]): + def get_login_token(self, response: Response | dict[Any, Any]) -> str: ... + def request(self, *args: Any, **kwargs: Any) -> Response | dict[Any, Any]: ... + +Request = RawAdapter diff --git a/stubs/hvac/hvac/api/__init__.pyi b/stubs/hvac/hvac/api/__init__.pyi new file mode 100644 index 000000000000..f794e4d52c59 --- /dev/null +++ b/stubs/hvac/hvac/api/__init__.pyi @@ -0,0 +1,7 @@ +from hvac.api.auth_methods import AuthMethods as AuthMethods +from hvac.api.secrets_engines import SecretsEngines as SecretsEngines +from hvac.api.system_backend import SystemBackend as SystemBackend +from hvac.api.vault_api_base import VaultApiBase as VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory as VaultApiCategory + +__all__ = ("AuthMethods", "SecretsEngines", "SystemBackend", "VaultApiBase", "VaultApiCategory") diff --git a/stubs/hvac/hvac/api/auth_methods/__init__.pyi b/stubs/hvac/hvac/api/auth_methods/__init__.pyi new file mode 100644 index 000000000000..7d3e80ff560b --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/__init__.pyi @@ -0,0 +1,40 @@ +from hvac.api.auth_methods.approle import AppRole as AppRole +from hvac.api.auth_methods.aws import Aws as Aws +from hvac.api.auth_methods.azure import Azure as Azure +from hvac.api.auth_methods.cert import Cert as Cert +from hvac.api.auth_methods.gcp import Gcp as Gcp +from hvac.api.auth_methods.github import Github as Github +from hvac.api.auth_methods.jwt import JWT as JWT +from hvac.api.auth_methods.kubernetes import Kubernetes as Kubernetes +from hvac.api.auth_methods.ldap import Ldap as Ldap +from hvac.api.auth_methods.legacy_mfa import LegacyMfa as LegacyMfa +from hvac.api.auth_methods.oidc import OIDC as OIDC +from hvac.api.auth_methods.okta import Okta as Okta +from hvac.api.auth_methods.radius import Radius as Radius +from hvac.api.auth_methods.token import Token as Token +from hvac.api.auth_methods.userpass import Userpass as Userpass +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "AuthMethods", + "AppRole", + "Azure", + "Gcp", + "Github", + "JWT", + "Kubernetes", + "Ldap", + "Userpass", + "LegacyMfa", + "OIDC", + "Okta", + "Radius", + "Token", + "Aws", + "Cert", +) + +class AuthMethods(VaultApiCategory): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] diff --git a/stubs/hvac/hvac/api/auth_methods/approle.pyi b/stubs/hvac/hvac/api/auth_methods/approle.pyi new file mode 100644 index 000000000000..530e11f8bf0e --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/approle.pyi @@ -0,0 +1,39 @@ +from hvac.api.vault_api_base import VaultApiBase + +class AppRole(VaultApiBase): + def create_or_update_approle( + self, + role_name, + bind_secret_id=None, + secret_id_bound_cidrs=None, + secret_id_num_uses=None, + secret_id_ttl=None, + enable_local_secret_ids=None, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + mount_point="approle", + ): ... + def list_roles(self, mount_point="approle"): ... + def read_role(self, role_name, mount_point="approle"): ... + def delete_role(self, role_name, mount_point="approle"): ... + def read_role_id(self, role_name, mount_point="approle"): ... + def update_role_id(self, role_name, role_id, mount_point="approle"): ... + def generate_secret_id( + self, role_name, metadata=None, cidr_list=None, token_bound_cidrs=None, mount_point="approle", wrap_ttl=None + ): ... + def create_custom_secret_id( + self, role_name, secret_id, metadata=None, cidr_list=None, token_bound_cidrs=None, mount_point="approle", wrap_ttl=None + ): ... + def read_secret_id(self, role_name, secret_id, mount_point="approle"): ... + def destroy_secret_id(self, role_name, secret_id, mount_point="approle"): ... + def list_secret_id_accessors(self, role_name, mount_point="approle"): ... + def read_secret_id_accessor(self, role_name, secret_id_accessor, mount_point="approle"): ... + def destroy_secret_id_accessor(self, role_name, secret_id_accessor, mount_point="approle"): ... + def login(self, role_id, secret_id=None, use_token: bool = True, mount_point="approle"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/aws.pyi b/stubs/hvac/hvac/api/auth_methods/aws.pyi new file mode 100644 index 000000000000..7298a79a1cc9 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/aws.pyi @@ -0,0 +1,103 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Aws(VaultApiBase): + def configure( + self, + max_retries=None, + access_key=None, + secret_key=None, + endpoint=None, + iam_endpoint=None, + sts_endpoint=None, + iam_server_id_header_value=None, + mount_point: str = "aws", + sts_region: str | None = None, + ): ... + def read_config(self, mount_point: str = "aws"): ... + def delete_config(self, mount_point: str = "aws"): ... + def configure_identity_integration( + self, + iam_alias=None, + ec2_alias=None, + mount_point: str = "aws", + iam_metadata: str | list[str] | None = None, + ec2_metadata: str | list[str] | None = None, + ): ... + def read_identity_integration(self, mount_point: str = "aws"): ... + def create_certificate_configuration(self, cert_name, aws_public_cert, document_type=None, mount_point: str = "aws"): ... + def read_certificate_configuration(self, cert_name, mount_point: str = "aws"): ... + def delete_certificate_configuration(self, cert_name, mount_point: str = "aws"): ... + def list_certificate_configurations(self, mount_point: str = "aws"): ... + def create_sts_role(self, account_id, sts_role, mount_point: str = "aws"): ... + def read_sts_role(self, account_id, mount_point: str = "aws"): ... + def list_sts_roles(self, mount_point: str = "aws"): ... + def delete_sts_role(self, account_id, mount_point: str = "aws"): ... + def configure_identity_whitelist_tidy(self, safety_buffer=None, disable_periodic_tidy=None, mount_point: str = "aws"): ... + def read_identity_whitelist_tidy(self, mount_point: str = "aws"): ... + def delete_identity_whitelist_tidy(self, mount_point: str = "aws"): ... + def configure_role_tag_blacklist_tidy(self, safety_buffer=None, disable_periodic_tidy=None, mount_point: str = "aws"): ... + def read_role_tag_blacklist_tidy(self, mount_point: str = "aws"): ... + def delete_role_tag_blacklist_tidy(self, mount_point: str = "aws"): ... + def create_role( + self, + role, + auth_type=None, + bound_ami_id=None, + bound_account_id=None, + bound_region=None, + bound_vpc_id=None, + bound_subnet_id=None, + bound_iam_role_arn=None, + bound_iam_instance_profile_arn=None, + bound_ec2_instance_id=None, + role_tag=None, + bound_iam_principal_arn=None, + inferred_entity_type=None, + inferred_aws_region=None, + resolve_aws_unique_ids=None, + ttl=None, + max_ttl=None, + period=None, + policies=None, + allow_instance_migration=None, + disallow_reauthentication=None, + mount_point: str = "aws", + ): ... + def read_role(self, role, mount_point: str = "aws"): ... + def list_roles(self, mount_point: str = "aws"): ... + def delete_role(self, role, mount_point: str = "aws"): ... + def create_role_tags( + self, + role, + policies=None, + max_ttl=None, + instance_id=None, + allow_instance_migration=None, + disallow_reauthentication=None, + mount_point: str = "aws", + ): ... + def iam_login( + self, + access_key, + secret_key, + session_token=None, + header_value=None, + role=None, + use_token: bool = True, + region: str = "us-east-1", + mount_point: str = "aws", + ): ... + def ec2_login(self, pkcs7, nonce=None, role=None, use_token: bool = True, mount_point: str = "aws"): ... + def place_role_tags_in_blacklist(self, role_tag, mount_point: str = "aws"): ... + def read_role_tag_blacklist(self, role_tag, mount_point: str = "aws"): ... + def list_blacklist_tags(self, mount_point: str = "aws"): ... + def delete_blacklist_tags(self, role_tag, mount_point: str = "aws"): ... + def tidy_blacklist_tags(self, safety_buffer: str = "72h", mount_point: str = "aws"): ... + def read_identity_whitelist(self, instance_id, mount_point: str = "aws"): ... + def list_identity_whitelist(self, mount_point: str = "aws"): ... + def delete_identity_whitelist_entries(self, instance_id, mount_point: str = "aws"): ... + def tidy_identity_whitelist_entries(self, safety_buffer: str = "72h", mount_point: str = "aws"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/azure.pyi b/stubs/hvac/hvac/api/auth_methods/azure.pyi new file mode 100644 index 000000000000..ffa918c02e17 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/azure.pyi @@ -0,0 +1,42 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +logger: logging.Logger + +class Azure(VaultApiBase): + def configure(self, tenant_id, resource, environment=None, client_id=None, client_secret=None, mount_point="azure"): ... + def read_config(self, mount_point="azure"): ... + def delete_config(self, mount_point="azure"): ... + def create_role( + self, + name, + policies=None, + ttl=None, + max_ttl=None, + period=None, + bound_service_principal_ids=None, + bound_group_ids=None, + bound_locations=None, + bound_subscription_ids=None, + bound_resource_groups=None, + bound_scale_sets=None, + num_uses=None, + mount_point="azure", + ): ... + def read_role(self, name, mount_point="azure"): ... + def list_roles(self, mount_point="azure"): ... + def delete_role(self, name, mount_point="azure"): ... + def login( + self, + role, + jwt, + subscription_id=None, + resource_group_name=None, + vm_name=None, + vmss_name=None, + use_token: bool = True, + mount_point="azure", + ): ... diff --git a/stubs/hvac/hvac/api/auth_methods/cert.pyi b/stubs/hvac/hvac/api/auth_methods/cert.pyi new file mode 100644 index 000000000000..9fdfc8701a7d --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/cert.pyi @@ -0,0 +1,41 @@ +from hvac.api.vault_api_base import VaultApiBase + +class Cert(VaultApiBase): + def create_ca_certificate_role( + self, + name, + certificate: str = "", + certificate_file: str = "", + allowed_common_names: str = "", + allowed_dns_sans: str = "", + allowed_email_sans: str = "", + allowed_uri_sans: str = "", + allowed_organizational_units: str = "", + required_extensions: str = "", + display_name: str = "", + token_ttl: int = 0, + token_max_ttl: int = 0, + token_policies=[], + token_bound_cidrs=[], + token_explicit_max_ttl: int = 0, + token_no_default_policy: bool = False, + token_num_uses: int = 0, + token_period: int = 0, + token_type: str = "", + mount_point: str = "cert", + ): ... + def read_ca_certificate_role(self, name, mount_point: str = "cert"): ... + def list_certificate_roles(self, mount_point: str = "cert"): ... + def delete_certificate_role(self, name, mount_point: str = "cert"): ... + def configure_tls_certificate(self, mount_point: str = "cert", disable_binding: bool = False): ... + def login( + self, + name: str = "", + cacert: bool = False, + cert_pem: str = "", + key_pem: str = "", + mount_point: str = "cert", + use_token: bool = True, + ): ... + + class CertificateAuthError(Exception): ... diff --git a/stubs/hvac/hvac/api/auth_methods/gcp.pyi b/stubs/hvac/hvac/api/auth_methods/gcp.pyi new file mode 100644 index 000000000000..8ebb0e03faf4 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/gcp.pyi @@ -0,0 +1,38 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +logger: logging.Logger + +class Gcp(VaultApiBase): + def configure( + self, credentials=None, google_certs_endpoint="https://www.googleapis.com/oauth2/v3/certs", mount_point="gcp" + ): ... + def read_config(self, mount_point="gcp"): ... + def delete_config(self, mount_point="gcp"): ... + def create_role( + self, + name, + role_type, + project_id, + ttl=None, + max_ttl=None, + period=None, + policies=None, + bound_service_accounts=None, + max_jwt_exp=None, + allow_gce_inference=None, + bound_zones=None, + bound_regions=None, + bound_instance_groups=None, + bound_labels=None, + mount_point="gcp", + ): ... + def edit_service_accounts_on_iam_role(self, name, add=None, remove=None, mount_point="gcp"): ... + def edit_labels_on_gce_role(self, name, add=None, remove=None, mount_point="gcp"): ... + def read_role(self, name, mount_point="gcp"): ... + def list_roles(self, mount_point="gcp"): ... + def delete_role(self, role, mount_point="gcp"): ... + def login(self, role, jwt, use_token: bool = True, mount_point="gcp"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/github.pyi b/stubs/hvac/hvac/api/auth_methods/github.pyi new file mode 100644 index 000000000000..3005c03d599a --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/github.pyi @@ -0,0 +1,12 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Github(VaultApiBase): + def configure(self, organization, base_url=None, ttl=None, max_ttl=None, mount_point="github"): ... + def read_configuration(self, mount_point="github"): ... + def map_team(self, team_name, policies=None, mount_point="github"): ... + def read_team_mapping(self, team_name, mount_point="github"): ... + def map_user(self, user_name, policies=None, mount_point="github"): ... + def read_user_mapping(self, user_name, mount_point="github"): ... + def login(self, token, use_token: bool = True, mount_point="github"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/jwt.pyi b/stubs/hvac/hvac/api/auth_methods/jwt.pyi new file mode 100644 index 000000000000..9db9396fe388 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/jwt.pyi @@ -0,0 +1,59 @@ +from hvac.api.vault_api_base import VaultApiBase + +class JWT(VaultApiBase): + DEFAULT_PATH: str + def resolve_path(self, path): ... + def configure( + self, + oidc_discovery_url=None, + oidc_discovery_ca_pem=None, + oidc_client_id=None, + oidc_client_secret=None, + oidc_response_mode=None, + oidc_response_types=None, + jwks_url=None, + jwks_ca_pem=None, + jwt_validation_pubkeys=None, + bound_issuer=None, + jwt_supported_algs=None, + default_role=None, + provider_config=None, + path: str | None = None, + namespace_in_state: bool | None = None, + ): ... + def read_config(self, path=None): ... + def create_role( + self, + name, + user_claim, + allowed_redirect_uris, + role_type: str = "jwt", + bound_audiences=None, + clock_skew_leeway=None, + expiration_leeway=None, + not_before_leeway=None, + bound_subject=None, + bound_claims=None, + groups_claim=None, + claim_mappings=None, + oidc_scopes=None, + bound_claims_type: str = "string", + verbose_oidc_logging: bool = False, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + path=None, + user_claim_json_pointer=None, + ): ... + def read_role(self, name, path=None): ... + def list_roles(self, path=None): ... + def delete_role(self, name, path=None): ... + def oidc_authorization_url_request(self, role, redirect_uri, path=None): ... + def oidc_callback(self, state, nonce, code, path=None): ... + def jwt_login(self, role, jwt, use_token: bool = True, path=None): ... diff --git a/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi b/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi new file mode 100644 index 000000000000..15d674291da8 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi @@ -0,0 +1,34 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Kubernetes(VaultApiBase): + def configure( + self, + kubernetes_host: str, + kubernetes_ca_cert: str | None = None, + token_reviewer_jwt: str | None = None, + pem_keys: list[str] | None = None, + issuer: str | None = None, + mount_point: str = "kubernetes", + disable_local_ca_jwt: bool = False, + ): ... + def read_config(self, mount_point: str = "kubernetes"): ... + def create_role( + self, + name: str, + bound_service_account_names: list[str] | str, + bound_service_account_namespaces: list[str] | str, + ttl: str | None = None, + max_ttl: str | None = None, + period: str | None = None, + policies: list[str] | str | None = None, + token_type: str = "", + mount_point: str = "kubernetes", + alias_name_source: str | None = None, + audience: str | None = None, + ): ... + def read_role(self, name: str, mount_point: str = "kubernetes"): ... + def list_roles(self, mount_point: str = "kubernetes"): ... + def delete_role(self, name: str, mount_point: str = "kubernetes"): ... + def login(self, role: str, jwt: str, use_token: bool = True, mount_point: str = "kubernetes"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/ldap.pyi b/stubs/hvac/hvac/api/auth_methods/ldap.pyi new file mode 100644 index 000000000000..f2d19fc58cb6 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/ldap.pyi @@ -0,0 +1,56 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Ldap(VaultApiBase): + def configure( + self, + userdn=None, + groupdn=None, + url=None, + case_sensitive_names=None, + starttls=None, + tls_min_version=None, + tls_max_version=None, + insecure_tls=None, + certificate=None, + binddn=None, + bindpass=None, + userattr=None, + discoverdn=None, + deny_null_bind: bool = True, + upndomain=None, + groupfilter=None, + groupattr=None, + use_token_groups=None, + token_ttl=None, + token_max_ttl=None, + mount_point="ldap", + *, + anonymous_group_search=None, + client_tls_cert=None, + client_tls_key=None, + connection_timeout=None, + dereference_aliases=None, + max_page_size=None, + request_timeout=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_policies=None, + token_type=None, + userfilter=None, + username_as_alias=None, + ): ... + def read_configuration(self, mount_point="ldap"): ... + def create_or_update_group(self, name, policies=None, mount_point="ldap"): ... + def list_groups(self, mount_point="ldap"): ... + def read_group(self, name, mount_point="ldap"): ... + def delete_group(self, name, mount_point="ldap"): ... + def create_or_update_user(self, username, policies=None, groups=None, mount_point="ldap"): ... + def list_users(self, mount_point="ldap"): ... + def read_user(self, username, mount_point="ldap"): ... + def delete_user(self, username, mount_point="ldap"): ... + def login(self, username, password, use_token: bool = True, mount_point="ldap"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi b/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi new file mode 100644 index 000000000000..68f56a952845 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/legacy_mfa.pyi @@ -0,0 +1,11 @@ +from hvac.api.vault_api_base import VaultApiBase + +SUPPORTED_MFA_TYPES: list[str] +SUPPORTED_AUTH_METHODS: list[str] + +class LegacyMfa(VaultApiBase): + def configure(self, mount_point, mfa_type: str = "duo", force: bool = False): ... + def read_configuration(self, mount_point): ... + def configure_duo_access(self, mount_point, host, integration_key, secret_key): ... + def configure_duo_behavior(self, mount_point, push_info=None, user_agent=None, username_format: str = "%s"): ... + def read_duo_behavior_configuration(self, mount_point): ... diff --git a/stubs/hvac/hvac/api/auth_methods/oidc.pyi b/stubs/hvac/hvac/api/auth_methods/oidc.pyi new file mode 100644 index 000000000000..c53113665a6e --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/oidc.pyi @@ -0,0 +1,33 @@ +from hvac.api.auth_methods.jwt import JWT + +class OIDC(JWT): + DEFAULT_PATH: str + def create_role( + self, + name, + user_claim, + allowed_redirect_uris, + role_type: str = "oidc", + bound_audiences=None, + clock_skew_leeway=None, + expiration_leeway=None, + not_before_leeway=None, + bound_subject=None, + bound_claims=None, + groups_claim=None, + claim_mappings=None, + oidc_scopes=None, + bound_claims_type: str = "string", + verbose_oidc_logging: bool = False, + token_ttl=None, + token_max_ttl=None, + token_policies=None, + token_bound_cidrs=None, + token_explicit_max_ttl=None, + token_no_default_policy=None, + token_num_uses=None, + token_period=None, + token_type=None, + path=None, + user_claim_json_pointer=None, + ) -> None: ... diff --git a/stubs/hvac/hvac/api/auth_methods/okta.pyi b/stubs/hvac/hvac/api/auth_methods/okta.pyi new file mode 100644 index 000000000000..d48dfbf6de1f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/okta.pyi @@ -0,0 +1,18 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Okta(VaultApiBase): + def configure( + self, org_name, api_token=None, base_url=None, ttl=None, max_ttl=None, bypass_okta_mfa=None, mount_point="okta" + ): ... + def read_config(self, mount_point="okta"): ... + def list_users(self, mount_point="okta"): ... + def register_user(self, username, groups=None, policies=None, mount_point="okta"): ... + def read_user(self, username, mount_point="okta"): ... + def delete_user(self, username, mount_point="okta"): ... + def list_groups(self, mount_point="okta"): ... + def register_group(self, name, policies=None, mount_point="okta"): ... + def read_group(self, name, mount_point="okta"): ... + def delete_group(self, name, mount_point="okta"): ... + def login(self, username, password, use_token: bool = True, mount_point="okta"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/radius.pyi b/stubs/hvac/hvac/api/auth_methods/radius.pyi new file mode 100644 index 000000000000..1db73c5bef9f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/radius.pyi @@ -0,0 +1,14 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Radius(VaultApiBase): + def configure( + self, host, secret, port=None, unregistered_user_policies=None, dial_timeout=None, nas_port=None, mount_point="radius" + ): ... + def read_configuration(self, mount_point="radius"): ... + def register_user(self, username, policies=None, mount_point="radius"): ... + def list_users(self, mount_point="radius"): ... + def read_user(self, username, mount_point="radius"): ... + def delete_user(self, username, mount_point="radius"): ... + def login(self, username, password, use_token: bool = True, mount_point="radius"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/token.pyi b/stubs/hvac/hvac/api/auth_methods/token.pyi new file mode 100644 index 000000000000..5500be2fcab1 --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/token.pyi @@ -0,0 +1,70 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Token(VaultApiBase): + def create( + self, + id=None, + role_name=None, + policies=None, + meta=None, + no_parent: bool = False, + no_default_policy: bool = False, + renewable: bool = True, + ttl=None, + type=None, + explicit_max_ttl=None, + display_name: str = "token", + num_uses: int = 0, + period=None, + entity_alias=None, + wrap_ttl=None, + mount_point="token", + ): ... + def create_orphan( + self, + id=None, + role_name=None, + policies=None, + meta=None, + no_default_policy: bool = False, + renewable: bool = True, + ttl=None, + type=None, + explicit_max_ttl=None, + display_name: str = "token", + num_uses: int = 0, + period=None, + entity_alias=None, + wrap_ttl=None, + mount_point="token", + ): ... + def list_accessors(self, mount_point="token"): ... + def lookup(self, token, mount_point="token"): ... + def lookup_self(self, mount_point="token"): ... + def lookup_accessor(self, accessor, mount_point="token"): ... + def renew(self, token, increment=None, wrap_ttl=None, mount_point="token"): ... + def renew_self(self, increment=None, wrap_ttl=None, mount_point="token"): ... + def renew_accessor(self, accessor, increment=None, wrap_ttl=None, mount_point="token"): ... + def revoke(self, token, mount_point="token"): ... + def revoke_self(self, mount_point="token"): ... + def revoke_accessor(self, accessor, mount_point="token"): ... + def revoke_and_orphan_children(self, token, mount_point="token"): ... + def read_role(self, role_name, mount_point="token"): ... + def list_roles(self, mount_point="token"): ... + def create_or_update_role( + self, + role_name, + allowed_policies=None, + disallowed_policies=None, + orphan: bool = False, + renewable: bool = True, + path_suffix=None, + allowed_entity_aliases=None, + mount_point="token", + token_period=None, + token_explicit_max_ttl=None, + ): ... + def delete_role(self, role_name, mount_point="token"): ... + def tidy(self, mount_point="token"): ... diff --git a/stubs/hvac/hvac/api/auth_methods/userpass.pyi b/stubs/hvac/hvac/api/auth_methods/userpass.pyi new file mode 100644 index 000000000000..d8991c0b9f2f --- /dev/null +++ b/stubs/hvac/hvac/api/auth_methods/userpass.pyi @@ -0,0 +1,11 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Userpass(VaultApiBase): + def create_or_update_user(self, username, password=None, policies=None, mount_point="userpass", **kwargs): ... + def list_user(self, mount_point="userpass"): ... + def read_user(self, username, mount_point="userpass"): ... + def delete_user(self, username, mount_point="userpass"): ... + def update_password_on_user(self, username, password, mount_point="userpass"): ... + def login(self, username, password, use_token: bool = True, mount_point="userpass"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/__init__.pyi b/stubs/hvac/hvac/api/secrets_engines/__init__.pyi new file mode 100644 index 000000000000..00e078835556 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/__init__.pyi @@ -0,0 +1,59 @@ +from hvac.api.secrets_engines.active_directory import ActiveDirectory as ActiveDirectory +from hvac.api.secrets_engines.aws import Aws as Aws +from hvac.api.secrets_engines.azure import Azure as Azure +from hvac.api.secrets_engines.consul import Consul as Consul +from hvac.api.secrets_engines.database import Database as Database +from hvac.api.secrets_engines.gcp import Gcp as Gcp +from hvac.api.secrets_engines.identity import Identity as Identity +from hvac.api.secrets_engines.kv import Kv as Kv +from hvac.api.secrets_engines.kv_v1 import KvV1 as KvV1 +from hvac.api.secrets_engines.kv_v2 import KvV2 as KvV2 +from hvac.api.secrets_engines.ldap import Ldap as Ldap +from hvac.api.secrets_engines.pki import Pki as Pki +from hvac.api.secrets_engines.rabbitmq import RabbitMQ as RabbitMQ +from hvac.api.secrets_engines.ssh import Ssh as Ssh +from hvac.api.secrets_engines.transform import Transform as Transform +from hvac.api.secrets_engines.transit import Transit as Transit +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "Aws", + "Azure", + "Gcp", + "ActiveDirectory", + "Identity", + "Kv", + "KvV1", + "KvV2", + "Ldap", + "Pki", + "Transform", + "Transit", + "SecretsEngines", + "Database", + "RabbitMQ", + "Ssh", +) + +class SecretsEngines(VaultApiCategory): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] + + # The following attributes are dynamically created at runtime by + # VaultApiCategory based on implemented_classes. + # These explicit assignments make them visible for static type checkers. + aws: Aws + azure: Azure + gcp: Gcp + activedirectory: ActiveDirectory + identity: Identity + kv: Kv + ldap: Ldap + pki: Pki + transform: Transform + transit: Transit + database: Database + consul: Consul + rabbitmq: RabbitMQ + ssh: Ssh diff --git a/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi b/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi new file mode 100644 index 000000000000..f7d527c75232 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/active_directory.pyi @@ -0,0 +1,24 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class ActiveDirectory(VaultApiBase): + def configure( + self, + binddn=None, + bindpass=None, + url=None, + userdn=None, + upndomain=None, + ttl=None, + max_ttl=None, + mount_point="ad", + *args, + **kwargs, + ): ... + def read_config(self, mount_point="ad"): ... + def create_or_update_role(self, name, service_account_name=None, ttl=None, mount_point="ad"): ... + def read_role(self, name, mount_point="ad"): ... + def list_roles(self, mount_point="ad"): ... + def delete_role(self, name, mount_point="ad"): ... + def generate_credentials(self, name, mount_point="ad"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/aws.pyi b/stubs/hvac/hvac/api/secrets_engines/aws.pyi new file mode 100644 index 000000000000..373d55a4e0e5 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/aws.pyi @@ -0,0 +1,28 @@ +from hvac.api.vault_api_base import VaultApiBase + +class Aws(VaultApiBase): + def configure_root_iam_credentials( + self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None, max_retries=None, mount_point="aws" + ): ... + def rotate_root_iam_credentials(self, mount_point="aws"): ... + def configure_lease(self, lease, lease_max, mount_point="aws"): ... + def read_lease_config(self, mount_point="aws"): ... + def create_or_update_role( + self, + name, + credential_type, + policy_document=None, + default_sts_ttl=None, + max_sts_ttl=None, + role_arns=None, + policy_arns=None, + legacy_params: bool = False, + iam_tags=None, + mount_point="aws", + ): ... + def read_role(self, name, mount_point="aws"): ... + def list_roles(self, mount_point="aws"): ... + def delete_role(self, name, mount_point="aws"): ... + def generate_credentials( + self, name, role_arn=None, ttl=None, endpoint: str = "creds", mount_point="aws", role_session_name=None + ): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/azure.pyi b/stubs/hvac/hvac/api/secrets_engines/azure.pyi new file mode 100644 index 000000000000..5ba4e4eac2dd --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/azure.pyi @@ -0,0 +1,13 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Azure(VaultApiBase): + def configure( + self, subscription_id, tenant_id, client_id=None, client_secret=None, environment=None, mount_point="azure" + ): ... + def read_config(self, mount_point="azure"): ... + def delete_config(self, mount_point="azure"): ... + def create_or_update_role(self, name, azure_roles, ttl=None, max_ttl=None, mount_point="azure"): ... + def list_roles(self, mount_point="azure"): ... + def generate_credentials(self, name, mount_point="azure"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/consul.pyi b/stubs/hvac/hvac/api/secrets_engines/consul.pyi new file mode 100644 index 000000000000..0a27a6da6b70 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/consul.pyi @@ -0,0 +1,13 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Consul(VaultApiBase): + def configure_access(self, address, token, scheme=None, mount_point="consul"): ... + def create_or_update_role( + self, name, policy=None, policies=None, token_type=None, local=None, ttl=None, max_ttl=None, mount_point="consul" + ): ... + def read_role(self, name, mount_point="consul"): ... + def list_roles(self, mount_point="consul"): ... + def delete_role(self, name, mount_point="consul"): ... + def generate_credentials(self, name, mount_point="consul"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/database.pyi b/stubs/hvac/hvac/api/secrets_engines/database.pyi new file mode 100644 index 000000000000..ff88fe47d9e6 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/database.pyi @@ -0,0 +1,45 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Database(VaultApiBase): + def configure( + self, + name, + plugin_name, + verify_connection=None, + allowed_roles=None, + root_rotation_statements=None, + mount_point="database", + *args, + **kwargs, + ): ... + def rotate_root_credentials(self, name, mount_point="database"): ... + def read_connection(self, name, mount_point="database"): ... + def list_connections(self, mount_point="database"): ... + def delete_connection(self, name, mount_point="database"): ... + def reset_connection(self, name, mount_point="database"): ... + def create_role( + self, + name, + db_name, + creation_statements, + default_ttl=None, + max_ttl=None, + revocation_statements=None, + rollback_statements=None, + renew_statements=None, + mount_point="database", + ): ... + def create_static_role( + self, name, db_name, username, rotation_statements, rotation_period: int = 86400, mount_point="database" + ): ... + def read_role(self, name, mount_point="database"): ... + def read_static_role(self, name, mount_point="database"): ... + def list_roles(self, mount_point="database"): ... + def list_static_roles(self, mount_point="database"): ... + def delete_role(self, name, mount_point="database"): ... + def delete_static_role(self, name, mount_point="database"): ... + def generate_credentials(self, name, mount_point="database"): ... + def get_static_credentials(self, name, mount_point="database"): ... + def rotate_static_role_credentials(self, name, mount_point="database"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/gcp.pyi b/stubs/hvac/hvac/api/secrets_engines/gcp.pyi new file mode 100644 index 000000000000..8ccc89bbf6e3 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/gcp.pyi @@ -0,0 +1,46 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Gcp(VaultApiBase): + def configure(self, credentials=None, ttl=None, max_ttl=None, mount_point="gcp"): ... + def rotate_root_credentials(self, mount_point="gcp"): ... + def read_config(self, mount_point="gcp"): ... + def create_or_update_roleset(self, name, project, bindings, secret_type=None, token_scopes=None, mount_point="gcp"): ... + def rotate_roleset_account(self, name, mount_point="gcp"): ... + def rotate_roleset_account_key(self, name, mount_point="gcp"): ... + def read_roleset(self, name, mount_point="gcp"): ... + def list_rolesets(self, mount_point="gcp"): ... + def delete_roleset(self, name, mount_point="gcp"): ... + def generate_oauth2_access_token(self, roleset, mount_point="gcp"): ... + def generate_service_account_key( + self, + roleset, + key_algorithm: str = "KEY_ALG_RSA_2048", + key_type: str = "TYPE_GOOGLE_CREDENTIALS_FILE", + method: str = "POST", + mount_point="gcp", + ): ... + def create_or_update_static_account( + self, name, service_account_email, bindings=None, secret_type=None, token_scopes=None, mount_point="gcp" + ): ... + def rotate_static_account_key(self, name, mount_point="gcp"): ... + def read_static_account(self, name, mount_point="gcp"): ... + def list_static_accounts(self, mount_point="gcp"): ... + def delete_static_account(self, name, mount_point="gcp"): ... + def generate_static_account_oauth2_access_token(self, name, mount_point="gcp"): ... + def generate_static_account_service_account_key( + self, + name, + key_algorithm: str = "KEY_ALG_RSA_2048", + key_type: str = "TYPE_GOOGLE_CREDENTIALS_FILE", + method: str = "POST", + mount_point="gcp", + ): ... + def create_or_update_impersonated_account( + self, name, service_account_email, token_scopes=None, ttl=None, mount_point="gcp" + ): ... + def read_impersonated_account(self, name, mount_point="gcp"): ... + def list_impersonated_accounts(self, mount_point="gcp"): ... + def delete_impersonated_account(self, name, mount_point="gcp"): ... + def generate_impersonated_account_oauth2_access_token(self, name, mount_point="gcp"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/identity.pyi b/stubs/hvac/hvac/api/secrets_engines/identity.pyi new file mode 100644 index 000000000000..7adc58901956 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/identity.pyi @@ -0,0 +1,106 @@ +import logging + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Identity(VaultApiBase): + def create_or_update_entity( + self, name, entity_id=None, metadata=None, policies=None, disabled=None, mount_point: str = "identity" + ): ... + def create_or_update_entity_by_name( + self, name, metadata=None, policies=None, disabled=None, mount_point: str = "identity" + ): ... + def read_entity(self, entity_id, mount_point: str = "identity"): ... + def read_entity_by_name(self, name, mount_point: str = "identity"): ... + def update_entity(self, entity_id, name=None, metadata=None, policies=None, disabled=None, mount_point: str = "identity"): ... + def delete_entity(self, entity_id, mount_point: str = "identity"): ... + def delete_entity_by_name(self, name, mount_point: str = "identity"): ... + def list_entities(self, method: str = "LIST", mount_point: str = "identity"): ... + def list_entities_by_name(self, method: str = "LIST", mount_point: str = "identity"): ... + def merge_entities( + self, from_entity_ids, to_entity_id, force=None, mount_point: str = "identity", conflicting_alias_ids_to_keep=None + ): ... + def create_or_update_entity_alias(self, name, canonical_id, mount_accessor, alias_id=None, mount_point: str = "identity"): ... + def read_entity_alias(self, alias_id, mount_point: str = "identity"): ... + def update_entity_alias(self, alias_id, name, canonical_id, mount_accessor, mount_point: str = "identity"): ... + def list_entity_aliases(self, method: str = "LIST", mount_point: str = "identity"): ... + def delete_entity_alias(self, alias_id, mount_point: str = "identity"): ... + @staticmethod + def validate_member_id_params_for_group_type(group_type, params, member_group_ids, member_entity_ids): ... + def create_or_update_group( + self, + name, + group_id=None, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def read_group(self, group_id, mount_point: str = "identity"): ... + def update_group( + self, + group_id, + name, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def delete_group(self, group_id, mount_point: str = "identity"): ... + def list_groups(self, method: str = "LIST", mount_point: str = "identity"): ... + def list_groups_by_name(self, method: str = "LIST", mount_point: str = "identity"): ... + def create_or_update_group_by_name( + self, + name, + group_type: str = "internal", + metadata=None, + policies=None, + member_group_ids=None, + member_entity_ids=None, + mount_point: str = "identity", + ): ... + def read_group_by_name(self, name, mount_point: str = "identity"): ... + def delete_group_by_name(self, name, mount_point: str = "identity"): ... + def create_or_update_group_alias( + self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point: str = "identity" + ): ... + def update_group_alias(self, entity_id, name, mount_accessor=None, canonical_id=None, mount_point="identity"): ... + def read_group_alias(self, alias_id, mount_point: str = "identity"): ... + def delete_group_alias(self, entity_id, mount_point: str = "identity"): ... + def list_group_aliases(self, method: str = "LIST", mount_point: str = "identity"): ... + def lookup_entity( + self, name=None, entity_id=None, alias_id=None, alias_name=None, alias_mount_accessor=None, mount_point: str = "identity" + ): ... + def lookup_group( + self, name=None, group_id=None, alias_id=None, alias_name=None, alias_mount_accessor=None, mount_point: str = "identity" + ): ... + def configure_tokens_backend(self, issuer=None, mount_point: str = "identity"): ... + def read_tokens_backend_configuration(self, mount_point: str = "identity"): ... + def create_named_key( + self, + name, + rotation_period: str = "24h", + verification_ttl: str = "24h", + allowed_client_ids=None, + algorithm: str = "RS256", + mount_point: str = "identity", + ): ... + def read_named_key(self, name, mount_point: str = "identity"): ... + def delete_named_key(self, name, mount_point: str = "identity"): ... + def list_named_keys(self, mount_point: str = "identity"): ... + def rotate_named_key(self, name, verification_ttl, mount_point: str = "identity"): ... + def create_or_update_role( + self, name, key, template=None, client_id=None, ttl: str = "24h", mount_point: str = "identity" + ): ... + def read_role(self, name, mount_point: str = "identity"): ... + def delete_role(self, name, mount_point: str = "identity"): ... + def list_roles(self, mount_point: str = "identity"): ... + def generate_signed_id_token(self, name, mount_point: str = "identity"): ... + def introspect_signed_id_token(self, token, client_id=None, mount_point: str = "identity"): ... + def read_well_known_configurations(self, mount_point: str = "identity"): ... + def read_active_public_keys(self, mount_point: str = "identity"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv.pyi b/stubs/hvac/hvac/api/secrets_engines/kv.pyi new file mode 100644 index 000000000000..5c0ec3a0c7ca --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv.pyi @@ -0,0 +1,23 @@ +import logging +from typing import Any + +from hvac.adapters import Adapter +from hvac.api.secrets_engines import KvV1, KvV2 +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class Kv(VaultApiBase): + allowed_kv_versions: list[str] + def __init__(self, adapter: Adapter[Any], default_kv_version: str = "2") -> None: ... + @property + def v1(self) -> KvV1: ... + @property + def v2(self) -> KvV2: ... + + @property + def default_kv_version(self) -> str: ... + @default_kv_version.setter + def default_kv_version(self, default_kv_version: str) -> None: ... + + def __getattr__(self, item: str): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi b/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi new file mode 100644 index 000000000000..68117f2bdddb --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi @@ -0,0 +1,13 @@ +from typing import Any + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class KvV1(VaultApiBase): + def read_secret(self, path: str, mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def create_or_update_secret( + self, path: str, secret: dict[str, Any], method: str | None = None, mount_point: str = "secret" + ): ... + def delete_secret(self, path: str, mount_point: str = "secret"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi b/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi new file mode 100644 index 000000000000..6e838ffd152f --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi @@ -0,0 +1,37 @@ +from typing import Any + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class KvV2(VaultApiBase): + def configure( + self, + max_versions: int = 10, + cas_required: bool | None = None, + delete_version_after: str = "0s", + mount_point: str = "secret", + ): ... + def read_configuration(self, mount_point: str = "secret"): ... + def read_secret(self, path: str, mount_point: str = "secret", raise_on_deleted_version: bool | None = None): ... + def read_secret_version( + self, path: str, version: int | None = None, mount_point: str = "secret", raise_on_deleted_version: bool | None = None + ): ... + def create_or_update_secret(self, path: str, secret: dict[str, Any], cas: int | None = None, mount_point: str = "secret"): ... + def patch(self, path: str, secret: dict[str, str], mount_point: str = "secret"): ... + def delete_latest_version_of_secret(self, path: str, mount_point: str = "secret"): ... + def delete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def undelete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def destroy_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def read_secret_metadata(self, path: str, mount_point: str = "secret"): ... + def update_metadata( + self, + path: str, + max_versions: int | None = None, + cas_required: bool | None = None, + delete_version_after: str = "0s", + mount_point: str = "secret", + custom_metadata: dict[str, str] | None = None, + ): ... + def delete_metadata_and_all_versions(self, path: str, mount_point: str = "secret"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/ldap.pyi b/stubs/hvac/hvac/api/secrets_engines/ldap.pyi new file mode 100644 index 000000000000..7a17162bf8c1 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/ldap.pyi @@ -0,0 +1,41 @@ +from typing import Final + +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: Final = "ldap" + +class Ldap(VaultApiBase): + def configure( + self, + binddn: str | None = None, + bindpass: str | None = None, + url: str | None = None, + password_policy: str | None = None, + schema: str | None = None, + userdn: str | None = None, + userattr: str | None = None, + upndomain: str | None = None, + connection_timeout: int | str | None = None, + request_timeout: int | str | None = None, + starttls: bool | None = None, + insecure_tls: bool | None = None, + certificate: str | None = None, + client_tls_cert: str | None = None, + client_tls_key: str | None = None, + mount_point: str = "ldap", + ): ... + def read_config(self, mount_point: str = "ldap"): ... + def rotate_root(self, mount_point: str = "ldap"): ... + def create_or_update_static_role( + self, + name: str, + username: str | None = None, + dn: str | None = None, + rotation_period: str | None = None, + mount_point: str = "ldap", + ): ... + def read_static_role(self, name: str, mount_point: str = "ldap"): ... + def list_static_roles(self, mount_point: str = "ldap"): ... + def delete_static_role(self, name: str, mount_point: str = "ldap"): ... + def generate_static_credentials(self, name: str, mount_point: str = "ldap"): ... + def rotate_static_credentials(self, name: str, mount_point: str = "ldap"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/pki.pyi b/stubs/hvac/hvac/api/secrets_engines/pki.pyi new file mode 100644 index 000000000000..f8ea43398709 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/pki.pyi @@ -0,0 +1,36 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Pki(VaultApiBase): + def read_ca_certificate(self, mount_point="pki"): ... + def read_ca_certificate_chain(self, mount_point="pki"): ... + def read_certificate(self, serial, mount_point="pki"): ... + def list_certificates(self, mount_point="pki"): ... + def submit_ca_information(self, pem_bundle, mount_point="pki"): ... + def read_crl_configuration(self, mount_point="pki"): ... + def set_crl_configuration(self, expiry=None, disable=None, extra_params=None, mount_point="pki"): ... + def read_urls(self, mount_point="pki"): ... + def set_urls(self, params, mount_point="pki"): ... + def read_crl(self, mount_point="pki"): ... + def rotate_crl(self, mount_point="pki"): ... + def generate_intermediate(self, type, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def set_signed_intermediate(self, certificate, mount_point="pki"): ... + def generate_certificate(self, name, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def revoke_certificate(self, serial_number, mount_point="pki"): ... + def create_or_update_role(self, name, extra_params=None, mount_point="pki"): ... + def read_role(self, name, mount_point="pki"): ... + def list_roles(self, mount_point="pki"): ... + def delete_role(self, name, mount_point="pki"): ... + def generate_root(self, type, common_name, extra_params=None, mount_point="pki", wrap_ttl=None): ... + def delete_root(self, mount_point="pki"): ... + def sign_intermediate(self, csr, common_name, extra_params=None, mount_point="pki"): ... + def sign_self_issued(self, certificate, mount_point="pki"): ... + def sign_certificate(self, name, csr, common_name, extra_params=None, mount_point="pki"): ... + def sign_verbatim(self, csr, name: bool = False, extra_params=None, mount_point="pki"): ... + def tidy(self, extra_params=None, mount_point="pki"): ... + def read_issuer(self, issuer_ref, mount_point="pki"): ... + def list_issuers(self, mount_point="pki"): ... + def update_issuer(self, issuer_ref, extra_params=None, mount_point="pki"): ... + def revoke_issuer(self, issuer_ref, mount_point="pki"): ... + def delete_issuer(self, issuer_ref, mount_point="pki"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi b/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi new file mode 100644 index 000000000000..6c77c2ed6590 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/rabbitmq.pyi @@ -0,0 +1,18 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class RabbitMQ(VaultApiBase): + def configure( + self, + connection_uri: str = "", + username: str = "", + password: str = "", + verify_connection: bool = True, + mount_point="rabbitmq", + ): ... + def configure_lease(self, ttl, max_ttl, mount_point="rabbitmq"): ... + def create_role(self, name, tags: str = "", vhosts: str = "", vhost_topics: str = "", mount_point: str = "rabbitmq"): ... + def read_role(self, name, mount_point="rabbitmq"): ... + def delete_role(self, name, mount_point="rabbitmq"): ... + def generate_credentials(self, name, mount_point="rabbitmq"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/ssh.pyi b/stubs/hvac/hvac/api/secrets_engines/ssh.pyi new file mode 100644 index 000000000000..b7b7f3d3305d --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/ssh.pyi @@ -0,0 +1,71 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Ssh(VaultApiBase): + def create_or_update_key(self, name: str = "", key: str = "", mount_point: str = "ssh"): ... + def delete_key(self, name: str = "", mount_point: str = "ssh"): ... + def create_role( + self, + name: str = "", + key: str = "", + admin_user: str = "", + default_user: str = "", + cidr_list: str = "", + exclude_cidr_list: str = "", + port: int = 22, + key_type: str = "", + key_bits: int = 1024, + install_script: str = "", + allowed_users: str = "", + allowed_users_template: str = "", + allowed_domains: str = "", + key_option_specs: str = "", + ttl: str = "", + max_ttl: str = "", + allowed_critical_options: str = "", + allowed_extensions: str = "", + default_critical_options=None, + default_extensions=None, + allow_user_certificates: str = "", + allow_host_certificates: bool = False, + allow_bare_domains: bool = False, + allow_subdomains: bool = False, + allow_user_key_ids: bool = False, + key_id_format: str = "", + allowed_user_key_lengths=None, + algorithm_signer: str = "", + mount_point="ssh", + ): ... + def read_role(self, name: str = "", mount_point: str = "ssh"): ... + def list_roles(self, mount_point: str = "ssh"): ... + def delete_role(self, name: str = "", mount_point: str = "ssh"): ... + def list_zeroaddress_roles(self, mount_point: str = "ssh"): ... + def configure_zeroaddress_roles(self, roles: str = "", mount_point: str = "ssh"): ... + def delete_zeroaddress_role(self, mount_point: str = "ssh"): ... + def generate_ssh_credentials(self, name: str = "", username: str = "", ip: str = "", mount_point: str = "ssh"): ... + def list_roles_by_ip(self, ip: str = "", mount_point: str = "ssh"): ... + def verify_ssh_otp(self, otp, mount_point="ssh"): ... + def submit_ca_information( + self, + private_key: str = "", + public_key: str = "", + generate_signing_key: bool = True, + key_type: str = "ssh-rsa", + key_bits: int = 0, + mount_point: str = "ssh", + ): ... + def delete_ca_information(self, mount_point: str = "ssh"): ... + def read_public_key(self, mount_point: str = "ssh"): ... + def sign_ssh_key( + self, + name: str = "", + public_key: str = "", + ttl: str = "", + valid_principals: str = "", + cert_type: str = "user", + key_id: str = "", + critical_options=None, + extensions=None, + mount_point: str = "ssh", + ): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/transform.pyi b/stubs/hvac/hvac/api/secrets_engines/transform.pyi new file mode 100644 index 000000000000..39aff82b3f50 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/transform.pyi @@ -0,0 +1,79 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Transform(VaultApiBase): + def create_or_update_role(self, name, transformations, mount_point: str = "transform"): ... + def read_role(self, name, mount_point: str = "transform"): ... + def list_roles(self, mount_point: str = "transform"): ... + def delete_role(self, name, mount_point: str = "transform"): ... + def create_or_update_transformation( + self, + name, + transform_type, + template, + tweak_source: str = "supplied", + masking_character: str = "*", + allowed_roles=None, + mount_point: str = "transform", + ): ... + def create_or_update_fpe_transformation( + self, name, template, tweak_source: str = "supplied", allowed_roles=None, mount_point: str = "transform" + ): ... + def create_or_update_masking_transformation( + self, name, template, masking_character: str = "*", allowed_roles=None, mount_point: str = "transform" + ): ... + def create_or_update_tokenization_transformation( + self, + name, + max_ttl: int = 0, + mapping_mode: str = "default", + allowed_roles=None, + stores=None, + mount_point: str = "transform", + ): ... + def read_transformation(self, name, mount_point: str = "transform"): ... + def list_transformations(self, mount_point: str = "transform"): ... + def delete_transformation(self, name, mount_point: str = "transform"): ... + def create_or_update_template(self, name, template_type, pattern, alphabet, mount_point: str = "transform"): ... + def read_template(self, name, mount_point: str = "transform"): ... + def list_templates(self, mount_point: str = "transform"): ... + def delete_template(self, name, mount_point: str = "transform"): ... + def create_or_update_alphabet(self, name, alphabet, mount_point: str = "transform"): ... + def read_alphabet(self, name, mount_point: str = "transform"): ... + def list_alphabets(self, mount_point: str = "transform"): ... + def delete_alphabet(self, name, mount_point: str = "transform"): ... + def create_or_update_tokenization_store( + self, + name, + driver, + connection_string, + username=None, + password=None, + type: str = "sql", + supported_transformations=None, + schema: str = "public", + max_open_connections: int = 4, + max_idle_connections: int = 4, + max_connection_lifetime: int = 0, + mount_point: str = "transform", + ): ... + def encode( + self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point: str = "transform" + ): ... + def decode( + self, role_name, value=None, transformation=None, tweak=None, batch_input=None, mount_point: str = "transform" + ): ... + def validate_token(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def check_tokenization(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def retrieve_token_metadata(self, role_name, value, transformation, batch_input=None, mount_point: str = "transform"): ... + def snapshot_tokenization_state(self, name, limit: int = 1000, continuation: str = "", mount_point: str = "transform"): ... + def restore_tokenization_state(self, name, values, mount_point: str = "transform"): ... + def export_decoded_tokenization_state( + self, name, limit: int = 1000, continuation: str = "", mount_point: str = "transform" + ): ... + def rotate_tokenization_key(self, transform_name, mount_point: str = "transform"): ... + def update_tokenization_key_config(self, transform_name, min_decryption_version, mount_point: str = "transform"): ... + def list_tokenization_key_configuration(self, mount_point: str = "transform"): ... + def read_tokenization_key_configuration(self, transform_name, mount_point: str = "transform"): ... + def trim_tokenization_key_version(self, transform_name, min_available_version, mount_point: str = "transform"): ... diff --git a/stubs/hvac/hvac/api/secrets_engines/transit.pyi b/stubs/hvac/hvac/api/secrets_engines/transit.pyi new file mode 100644 index 000000000000..86a2335ec4d6 --- /dev/null +++ b/stubs/hvac/hvac/api/secrets_engines/transit.pyi @@ -0,0 +1,93 @@ +from hvac.api.vault_api_base import VaultApiBase + +DEFAULT_MOUNT_POINT: str + +class Transit(VaultApiBase): + def create_key( + self, + name, + convergent_encryption=None, + derived=None, + exportable=None, + allow_plaintext_backup=None, + key_type=None, + mount_point="transit", + auto_rotate_period=None, + ): ... + def read_key(self, name, mount_point="transit"): ... + def list_keys(self, mount_point="transit"): ... + def delete_key(self, name, mount_point="transit"): ... + def update_key_configuration( + self, + name, + min_decryption_version=None, + min_encryption_version=None, + deletion_allowed=None, + exportable=None, + allow_plaintext_backup=None, + mount_point="transit", + auto_rotate_period=None, + ): ... + def rotate_key(self, name, mount_point="transit"): ... + def export_key(self, name, key_type, version=None, mount_point="transit"): ... + def encrypt_data( + self, + name, + plaintext=None, + context=None, + key_version=None, + nonce=None, + batch_input=None, + type=None, + convergent_encryption=None, + mount_point: str = "transit", + associated_data: str | None = None, + ): ... + def decrypt_data( + self, + name, + ciphertext=None, + context=None, + nonce=None, + batch_input=None, + mount_point: str = "transit", + associated_data: str | None = None, + ): ... + def rewrap_data( + self, name, ciphertext, context=None, key_version=None, nonce=None, batch_input=None, mount_point="transit" + ): ... + def generate_data_key(self, name, key_type, context=None, nonce=None, bits=None, mount_point="transit"): ... + def generate_random_bytes(self, n_bytes=None, output_format=None, mount_point="transit"): ... + def hash_data(self, hash_input, algorithm=None, output_format=None, mount_point="transit"): ... + def generate_hmac(self, name, hash_input, key_version=None, algorithm=None, mount_point="transit"): ... + def sign_data( + self, + name, + hash_input=None, + key_version=None, + hash_algorithm=None, + context=None, + prehashed=None, + signature_algorithm=None, + marshaling_algorithm=None, + salt_length=None, + mount_point="transit", + batch_input=None, + ): ... + def verify_signed_data( + self, + name, + hash_input, + signature=None, + hmac=None, + hash_algorithm=None, + context=None, + prehashed=None, + signature_algorithm=None, + salt_length=None, + marshaling_algorithm=None, + mount_point="transit", + ): ... + def backup_key(self, name, mount_point="transit"): ... + def restore_key(self, backup, name=None, force=None, mount_point="transit"): ... + def trim_key(self, name, min_version, mount_point="transit"): ... diff --git a/stubs/hvac/hvac/api/system_backend/__init__.pyi b/stubs/hvac/hvac/api/system_backend/__init__.pyi new file mode 100644 index 000000000000..c4066c28c71b --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/__init__.pyi @@ -0,0 +1,62 @@ +from hvac.api.system_backend.audit import Audit as Audit +from hvac.api.system_backend.auth import Auth as Auth +from hvac.api.system_backend.capabilities import Capabilities as Capabilities +from hvac.api.system_backend.health import Health as Health +from hvac.api.system_backend.init import Init as Init +from hvac.api.system_backend.key import Key as Key +from hvac.api.system_backend.leader import Leader as Leader +from hvac.api.system_backend.lease import Lease as Lease +from hvac.api.system_backend.mount import Mount as Mount +from hvac.api.system_backend.namespace import Namespace as Namespace +from hvac.api.system_backend.policies import Policies as Policies +from hvac.api.system_backend.policy import Policy as Policy +from hvac.api.system_backend.quota import Quota as Quota +from hvac.api.system_backend.raft import Raft as Raft +from hvac.api.system_backend.seal import Seal as Seal +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin as SystemBackendMixin +from hvac.api.system_backend.wrapping import Wrapping as Wrapping +from hvac.api.vault_api_base import VaultApiBase +from hvac.api.vault_api_category import VaultApiCategory + +__all__ = ( + "Audit", + "Auth", + "Capabilities", + "Health", + "Init", + "Key", + "Leader", + "Lease", + "Mount", + "Namespace", + "Policies", + "Policy", + "Quota", + "Raft", + "Seal", + "SystemBackend", + "SystemBackendMixin", + "Wrapping", +) + +class SystemBackend( + VaultApiCategory, + Audit, + Auth, + Capabilities, + Health, + Init, + Key, + Leader, + Lease, + Mount, + Namespace, + Policies, + Policy, + Quota, + Raft, + Seal, + Wrapping, +): + implemented_classes: list[type[VaultApiBase]] + unimplemented_classes: list[str] diff --git a/stubs/hvac/hvac/api/system_backend/audit.pyi b/stubs/hvac/hvac/api/system_backend/audit.pyi new file mode 100644 index 000000000000..99dea810178f --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/audit.pyi @@ -0,0 +1,7 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Audit(SystemBackendMixin): + def list_enabled_audit_devices(self): ... + def enable_audit_device(self, device_type, description=None, options=None, path=None, local=None): ... + def disable_audit_device(self, path): ... + def calculate_hash(self, path, input_to_hash): ... diff --git a/stubs/hvac/hvac/api/system_backend/auth.pyi b/stubs/hvac/hvac/api/system_backend/auth.pyi new file mode 100644 index 000000000000..1534a1c71499 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/auth.pyi @@ -0,0 +1,21 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Auth(SystemBackendMixin): + def list_auth_methods(self): ... + def enable_auth_method( + self, method_type, description=None, config=None, plugin_name=None, local: bool = False, path=None, **kwargs + ): ... + def disable_auth_method(self, path): ... + def read_auth_method_tuning(self, path): ... + def tune_auth_method( + self, + path, + default_lease_ttl=None, + max_lease_ttl=None, + description=None, + audit_non_hmac_request_keys=None, + audit_non_hmac_response_keys=None, + listing_visibility=None, + passthrough_request_headers=None, + **kwargs, + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/capabilities.pyi b/stubs/hvac/hvac/api/system_backend/capabilities.pyi new file mode 100644 index 000000000000..398f822a5870 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/capabilities.pyi @@ -0,0 +1,4 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Capabilities(SystemBackendMixin): + def get_capabilities(self, paths, token=None, accessor=None): ... diff --git a/stubs/hvac/hvac/api/system_backend/health.pyi b/stubs/hvac/hvac/api/system_backend/health.pyi new file mode 100644 index 000000000000..9e252742786e --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/health.pyi @@ -0,0 +1,14 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Health(SystemBackendMixin): + def read_health_status( + self, + standby_ok=None, + active_code=None, + standby_code=None, + dr_secondary_code=None, + performance_standby_code=None, + sealed_code=None, + uninit_code=None, + method: str = "HEAD", + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/init.pyi b/stubs/hvac/hvac/api/system_backend/init.pyi new file mode 100644 index 000000000000..bd96164557d3 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/init.pyi @@ -0,0 +1,16 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Init(SystemBackendMixin): + def read_init_status(self): ... + def is_initialized(self): ... + def initialize( + self, + secret_shares=None, + secret_threshold=None, + pgp_keys=None, + root_token_pgp_key=None, + stored_shares=None, + recovery_shares=None, + recovery_threshold=None, + recovery_pgp_keys=None, + ): ... diff --git a/stubs/hvac/hvac/api/system_backend/key.pyi b/stubs/hvac/hvac/api/system_backend/key.pyi new file mode 100644 index 000000000000..ada0db2177f4 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/key.pyi @@ -0,0 +1,27 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Key(SystemBackendMixin): + def read_root_generation_progress(self): ... + def start_root_token_generation(self, otp=None, pgp_key=None): ... + def generate_root(self, key, nonce): ... + def cancel_root_generation(self): ... + def get_encryption_key_status(self): ... + def rotate_encryption_key(self): ... + def read_rekey_progress(self, recovery_key: bool = False): ... + def start_rekey( + self, + secret_shares: int = 5, + secret_threshold: int = 3, + pgp_keys=None, + backup: bool = False, + require_verification: bool = False, + recovery_key: bool = False, + ): ... + def cancel_rekey(self, recovery_key: bool = False): ... + def rekey(self, key, nonce=None, recovery_key: bool = False): ... + def rekey_multi(self, keys, nonce=None, recovery_key: bool = False): ... + def read_backup_keys(self, recovery_key: bool = False): ... + def cancel_rekey_verify(self): ... + def rekey_verify(self, key, nonce): ... + def rekey_verify_multi(self, keys, nonce): ... + def read_rekey_verify_progress(self): ... diff --git a/stubs/hvac/hvac/api/system_backend/leader.pyi b/stubs/hvac/hvac/api/system_backend/leader.pyi new file mode 100644 index 000000000000..c46711c1b204 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/leader.pyi @@ -0,0 +1,5 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Leader(SystemBackendMixin): + def read_leader_status(self): ... + def step_down(self): ... diff --git a/stubs/hvac/hvac/api/system_backend/lease.pyi b/stubs/hvac/hvac/api/system_backend/lease.pyi new file mode 100644 index 000000000000..9fd68b3f5f9d --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/lease.pyi @@ -0,0 +1,9 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Lease(SystemBackendMixin): + def read_lease(self, lease_id): ... + def list_leases(self, prefix): ... + def renew_lease(self, lease_id, increment=None): ... + def revoke_lease(self, lease_id): ... + def revoke_prefix(self, prefix): ... + def revoke_force(self, prefix): ... diff --git a/stubs/hvac/hvac/api/system_backend/mount.pyi b/stubs/hvac/hvac/api/system_backend/mount.pyi new file mode 100644 index 000000000000..54e83c1af5d7 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/mount.pyi @@ -0,0 +1,34 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Mount(SystemBackendMixin): + def list_mounted_secrets_engines(self): ... + def retrieve_mount_option(self, mount_point, option_name, default_value=None): ... + def enable_secrets_engine( + self, + backend_type, + path=None, + description=None, + config=None, + plugin_name=None, + options=None, + local: bool = False, + seal_wrap: bool = False, + **kwargs, + ): ... + def disable_secrets_engine(self, path): ... + def read_mount_configuration(self, path): ... + def tune_mount_configuration( + self, + path, + default_lease_ttl=None, + max_lease_ttl=None, + description=None, + audit_non_hmac_request_keys=None, + audit_non_hmac_response_keys=None, + listing_visibility=None, + passthrough_request_headers=None, + options=None, + force_no_cache=None, + **kwargs, + ): ... + def move_backend(self, from_path, to_path): ... diff --git a/stubs/hvac/hvac/api/system_backend/namespace.pyi b/stubs/hvac/hvac/api/system_backend/namespace.pyi new file mode 100644 index 000000000000..68e86561c8c5 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/namespace.pyi @@ -0,0 +1,6 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Namespace(SystemBackendMixin): + def create_namespace(self, path): ... + def list_namespaces(self): ... + def delete_namespace(self, path): ... diff --git a/stubs/hvac/hvac/api/system_backend/policies.pyi b/stubs/hvac/hvac/api/system_backend/policies.pyi new file mode 100644 index 000000000000..324b0e4da8aa --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/policies.pyi @@ -0,0 +1,15 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Policies(SystemBackendMixin): + def list_acl_policies(self): ... + def read_acl_policy(self, name): ... + def create_or_update_acl_policy(self, name, policy, pretty_print: bool = True): ... + def delete_acl_policy(self, name): ... + def list_rgp_policies(self): ... + def read_rgp_policy(self, name): ... + def create_or_update_rgp_policy(self, name, policy, enforcement_level): ... + def delete_rgp_policy(self, name): ... + def list_egp_policies(self): ... + def read_egp_policy(self, name): ... + def create_or_update_egp_policy(self, name, policy, enforcement_level, paths): ... + def delete_egp_policy(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/policy.pyi b/stubs/hvac/hvac/api/system_backend/policy.pyi new file mode 100644 index 000000000000..51de631b3a26 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/policy.pyi @@ -0,0 +1,7 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Policy(SystemBackendMixin): + def list_policies(self): ... + def read_policy(self, name): ... + def create_or_update_policy(self, name, policy, pretty_print: bool = True): ... + def delete_policy(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/quota.pyi b/stubs/hvac/hvac/api/system_backend/quota.pyi new file mode 100644 index 000000000000..15385d68a492 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/quota.pyi @@ -0,0 +1,9 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Quota(SystemBackendMixin): + def read_quota(self, name): ... + def list_quotas(self): ... + def create_or_update_quota( + self, name, rate, path=None, interval=None, block_interval=None, role=None, rate_limit_type=None, inheritable=None + ): ... + def delete_quota(self, name): ... diff --git a/stubs/hvac/hvac/api/system_backend/raft.pyi b/stubs/hvac/hvac/api/system_backend/raft.pyi new file mode 100644 index 000000000000..94b531a53953 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/raft.pyi @@ -0,0 +1,21 @@ +from typing import Any + +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin +from requests import Response + +class Raft(SystemBackendMixin): + def join_raft_cluster( + self, leader_api_addr, retry: bool = False, leader_ca_cert=None, leader_client_cert=None, leader_client_key=None + ): ... + def read_raft_config(self): ... + def remove_raft_node(self, server_id): ... + def take_raft_snapshot(self): ... + def restore_raft_snapshot(self, snapshot): ... + def force_restore_raft_snapshot(self, snapshot): ... + def read_raft_auto_snapshot_status(self, name: str) -> Response: ... + def read_raft_auto_snapshot_config(self, name: str) -> Response: ... + def list_raft_auto_snapshot_configs(self) -> Response: ... + def create_or_update_raft_auto_snapshot_config( + self, name: str, interval: str, storage_type: str, retain: int = 1, **kwargs: Any + ) -> Response: ... + def delete_raft_auto_snapshot_config(self, name: str) -> Response: ... diff --git a/stubs/hvac/hvac/api/system_backend/seal.pyi b/stubs/hvac/hvac/api/system_backend/seal.pyi new file mode 100644 index 000000000000..9590f989df20 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/seal.pyi @@ -0,0 +1,8 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin + +class Seal(SystemBackendMixin): + def is_sealed(self): ... + def read_seal_status(self): ... + def seal(self): ... + def submit_unseal_key(self, key=None, reset: bool = False, migrate: bool = False): ... + def submit_unseal_keys(self, keys, migrate: bool = False): ... diff --git a/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi b/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi new file mode 100644 index 000000000000..5aab4a8129e5 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/system_backend_mixin.pyi @@ -0,0 +1,8 @@ +import logging +from abc import ABCMeta + +from hvac.api.vault_api_base import VaultApiBase + +logger: logging.Logger + +class SystemBackendMixin(VaultApiBase, metaclass=ABCMeta): ... diff --git a/stubs/hvac/hvac/api/system_backend/wrapping.pyi b/stubs/hvac/hvac/api/system_backend/wrapping.pyi new file mode 100644 index 000000000000..abed47c18ea1 --- /dev/null +++ b/stubs/hvac/hvac/api/system_backend/wrapping.pyi @@ -0,0 +1,6 @@ +from hvac.api.system_backend.system_backend_mixin import SystemBackendMixin +from requests._types import JsonType + +class Wrapping(SystemBackendMixin): + def unwrap(self, token=None): ... + def wrap(self, payload: JsonType = None, ttl: int = 60): ... diff --git a/stubs/hvac/hvac/api/vault_api_base.pyi b/stubs/hvac/hvac/api/vault_api_base.pyi new file mode 100644 index 000000000000..063f55d8fcf7 --- /dev/null +++ b/stubs/hvac/hvac/api/vault_api_base.pyi @@ -0,0 +1,10 @@ +from abc import ABCMeta +from logging import Logger +from typing import Any + +from hvac.adapters import Adapter + +logger: Logger + +class VaultApiBase(metaclass=ABCMeta): + def __init__(self, adapter: Adapter[Any]) -> None: ... diff --git a/stubs/hvac/hvac/api/vault_api_category.pyi b/stubs/hvac/hvac/api/vault_api_category.pyi new file mode 100644 index 000000000000..9d0e8be845bd --- /dev/null +++ b/stubs/hvac/hvac/api/vault_api_category.pyi @@ -0,0 +1,26 @@ +from abc import ABCMeta, abstractmethod +from logging import Logger +from typing import Any + +from hvac.adapters import Adapter +from hvac.api.vault_api_base import VaultApiBase + +logger: Logger + +class VaultApiCategory(VaultApiBase, metaclass=ABCMeta): + implemented_class_names: list[str] + def __init__(self, adapter: Adapter[Any]) -> None: ... + def __getattr__(self, item: str): ... + + @property + def adapter(self) -> Adapter[Any]: ... + @adapter.setter + def adapter(self, adapter: Adapter[Any]) -> None: ... + + @property + @abstractmethod + def implemented_classes(self) -> list[type[VaultApiBase]]: ... + @property + def unimplemented_classes(self) -> list[str]: ... + @staticmethod + def get_private_attr_name(class_name: str) -> str: ... diff --git a/stubs/hvac/hvac/aws_utils.pyi b/stubs/hvac/hvac/aws_utils.pyi new file mode 100644 index 000000000000..a63a1b022c81 --- /dev/null +++ b/stubs/hvac/hvac/aws_utils.pyi @@ -0,0 +1,11 @@ +import requests + +class SigV4Auth: + access_key: str + secret_key: str + session_token: str | None + region: str + def __init__(self, access_key: str, secret_key: str, session_token: str | None = None, region: str = "us-east-1") -> None: ... + def add_auth(self, request: requests.PreparedRequest) -> None: ... + +def generate_sigv4_auth_request(header_value: str | None = None): ... diff --git a/stubs/hvac/hvac/constants/__init__.pyi b/stubs/hvac/hvac/constants/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/hvac/hvac/constants/approle.pyi b/stubs/hvac/hvac/constants/approle.pyi new file mode 100644 index 000000000000..1eb6dc9a051b --- /dev/null +++ b/stubs/hvac/hvac/constants/approle.pyi @@ -0,0 +1,4 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_TOKEN_TYPES: Iterable[str] diff --git a/stubs/hvac/hvac/constants/aws.pyi b/stubs/hvac/hvac/constants/aws.pyi new file mode 100644 index 000000000000..7fed919b49f6 --- /dev/null +++ b/stubs/hvac/hvac/constants/aws.pyi @@ -0,0 +1,7 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_CREDS_ENDPOINTS: Iterable[str] +ALLOWED_CREDS_TYPES: Iterable[str] +ALLOWED_IAM_ALIAS_TYPES: Iterable[str] +ALLOWED_EC2_ALIAS_TYPES: Iterable[str] diff --git a/stubs/hvac/hvac/constants/azure.pyi b/stubs/hvac/hvac/constants/azure.pyi new file mode 100644 index 000000000000..c857aa27d47d --- /dev/null +++ b/stubs/hvac/hvac/constants/azure.pyi @@ -0,0 +1,3 @@ +from collections.abc import Iterable + +VALID_ENVIRONMENTS: Iterable[str] diff --git a/stubs/hvac/hvac/constants/client.pyi b/stubs/hvac/hvac/constants/client.pyi new file mode 100644 index 000000000000..81d22815bd8a --- /dev/null +++ b/stubs/hvac/hvac/constants/client.pyi @@ -0,0 +1,8 @@ +from hvac.utils import _DeprecateProperty + +DEPRECATED_PROPERTIES: dict[str, _DeprecateProperty] +DEFAULT_URL: str +VAULT_CACERT: str | None +VAULT_CAPATH: str | None +VAULT_CLIENT_CERT: str | None +VAULT_CLIENT_KEY: str | None diff --git a/stubs/hvac/hvac/constants/gcp.pyi b/stubs/hvac/hvac/constants/gcp.pyi new file mode 100644 index 000000000000..1c0bd678663c --- /dev/null +++ b/stubs/hvac/hvac/constants/gcp.pyi @@ -0,0 +1,8 @@ +from collections.abc import Iterable + +DEFAULT_MOUNT_POINT: str +ALLOWED_ROLE_TYPES: Iterable[str] +ALLOWED_SECRETS_TYPES: Iterable[str] +SERVICE_ACCOUNT_KEY_ALGORITHMS: Iterable[str] +SERVICE_ACCOUNT_KEY_TYPES: Iterable[str] +GCP_CERTS_ENDPOINT: str diff --git a/stubs/hvac/hvac/constants/identity.pyi b/stubs/hvac/hvac/constants/identity.pyi new file mode 100644 index 000000000000..c9041bf3e3b2 --- /dev/null +++ b/stubs/hvac/hvac/constants/identity.pyi @@ -0,0 +1,5 @@ +from collections.abc import Iterable +from typing import Final + +ALLOWED_GROUP_TYPES: Iterable[str] +DEFAULT_MOUNT_POINT: Final = "identity" diff --git a/stubs/hvac/hvac/constants/transit.pyi b/stubs/hvac/hvac/constants/transit.pyi new file mode 100644 index 000000000000..af633211ff13 --- /dev/null +++ b/stubs/hvac/hvac/constants/transit.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from re import Pattern + +ALLOWED_KEY_TYPES: Iterable[str] +ALLOWED_EXPORT_KEY_TYPES: Iterable[str] +ALLOWED_DATA_KEY_TYPES: Iterable[str] +ALLOWED_DATA_KEY_BITS: Iterable[int] +ALLOWED_HASH_DATA_ALGORITHMS: Iterable[str] +ALLOWED_HASH_DATA_FORMATS: Iterable[str] +ALLOWED_SIGNATURE_ALGORITHMS: Iterable[str] +ALLOWED_MARSHALING_ALGORITHMS: Iterable[str] +ALLOWED_SALT_LENGTHS: Pattern[str] diff --git a/stubs/hvac/hvac/exceptions.pyi b/stubs/hvac/hvac/exceptions.pyi new file mode 100644 index 000000000000..67c2ed53b81a --- /dev/null +++ b/stubs/hvac/hvac/exceptions.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable +from typing_extensions import Self + +class VaultError(Exception): + errors: Iterable[str] | str | None + method: str | None + url: str | None + text: str | None + json: object + def __init__( + self, + message: str | None = None, + errors: Iterable[str] | str | None = None, + method: str | None = None, + url: str | None = None, + text: str | None = None, + json: object | None = None, + ) -> None: ... + @classmethod + def from_status( + cls, + status_code: int, + message: str | None = ..., + errors: Iterable[str] | str | None = ..., + method: str | None = ..., + url: str | None = ..., + text: str | None = ..., + json: object | None = ..., + ) -> Self: ... + +class InvalidRequest(VaultError): ... +class Unauthorized(VaultError): ... +class Forbidden(VaultError): ... +class InvalidPath(VaultError): ... +class UnsupportedOperation(VaultError): ... +class PreconditionFailed(VaultError): ... +class RateLimitExceeded(VaultError): ... +class InternalServerError(VaultError): ... +class VaultNotInitialized(VaultError): ... +class VaultDown(VaultError): ... +class UnexpectedError(VaultError): ... +class BadGateway(VaultError): ... +class ParamValidationError(VaultError): ... diff --git a/stubs/hvac/hvac/utils.pyi b/stubs/hvac/hvac/utils.pyi new file mode 100644 index 000000000000..ba48033a43d4 --- /dev/null +++ b/stubs/hvac/hvac/utils.pyi @@ -0,0 +1,48 @@ +from collections.abc import Callable, Iterable, Mapping +from typing import Any, TypedDict, TypeVar, type_check_only +from typing_extensions import Never, NotRequired + +@type_check_only +class _DeprecateProperty(TypedDict): + to_be_removed_in_version: str + client_property: str + new_property: NotRequired[str] + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +def raise_for_error( + method: str, + url: str, + status_code: int, + message: str | None = None, + errors: Iterable[str] | str | None = None, + text: str | None = None, + json: object | None = None, +) -> Never: ... +def aliased_parameter( + name: str, *aliases: str, removed_in_version: str | None, position: int | None = None, raise_on_multiple: bool = True +) -> Callable[..., Any]: ... +def generate_parameter_deprecation_message( + to_be_removed_in_version: str, old_parameter_name: str, new_parameter_name: str | None = None, extra_notes: str | None = None +) -> str: ... +def generate_method_deprecation_message( + to_be_removed_in_version: str, old_method_name: str, method_name: str | None = None, module_name: str | None = None +) -> str: ... +def generate_property_deprecation_message( + to_be_removed_in_version: str, old_name: str, new_name: str, new_attribute: str, module_name: str = "Client" +) -> str: ... +def getattr_with_deprecated_properties(obj: object, item: str, deprecated_properties: dict[str, _DeprecateProperty]) -> Any: ... +def deprecated_method(to_be_removed_in_version: str, new_method: Callable[..., Any] | None = None) -> Callable[..., Any]: ... +def validate_list_of_strings_param(param_name: str, param_argument: Iterable[Any] | str) -> None: ... +def list_to_comma_delimited(list_param: Iterable[str] | None) -> str: ... +def get_token_from_env() -> str | None: ... +def comma_delimited_to_list(list_param: Iterable[_T]) -> Iterable[_T]: ... + +# the docstring states that this function returns a bool, but the code does not return anything +def validate_pem_format(param_name: str, param_argument: str) -> None: ... +def remove_nones(params: Mapping[_K, _V | None]) -> Mapping[_K, _V]: ... +def format_url( + format_str: str, *args: object, **kwargs: object +) -> str: ... # values are passed to builtins.str, which takes an object type diff --git a/stubs/hvac/hvac/v1/__init__.pyi b/stubs/hvac/hvac/v1/__init__.pyi new file mode 100644 index 000000000000..e368210f0a1c --- /dev/null +++ b/stubs/hvac/hvac/v1/__init__.pyi @@ -0,0 +1,92 @@ +from typing import Any, Literal, overload + +from hvac.adapters import Adapter +from hvac.api import AuthMethods, SystemBackend +from hvac.api.secrets_engines import SecretsEngines +from requests import Session +from requests.models import Response + +has_hcl_parser: bool + +class Client: + def __init__( + self, + url: str | None = None, + token: str | None = None, + cert: tuple[str, str] | None = None, + verify: bool | str | None = None, + timeout: int = 30, + proxies: dict[str, str] | None = None, + allow_redirects: bool = True, + session: Session | None = None, + adapter: type[Adapter[Any]] = ..., + namespace: str | None = None, + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + + @property + def adapter(self) -> Adapter[Any]: ... + @adapter.setter + def adapter(self, adapter: Adapter[Any]) -> None: ... + + @property + def url(self) -> str: ... + @url.setter + def url(self, url: str) -> None: ... + + @property + def token(self) -> str: ... + @token.setter + def token(self, token: str) -> None: ... + + @property + def session(self) -> Session: ... + @session.setter + def session(self, session: Session) -> None: ... + + @property + def allow_redirects(self) -> bool: ... + @allow_redirects.setter + def allow_redirects(self, allow_redirects: bool) -> None: ... + + @property + def auth(self) -> AuthMethods: ... + @property + def secrets(self) -> SecretsEngines: ... + @property + def sys(self) -> SystemBackend: ... + @property + def generate_root_status(self) -> dict[str, Any] | Response: ... + @property + def key_status(self) -> dict[str, Any] | Response: ... + @property + def rekey_status(self) -> dict[str, Any] | Response: ... + @property + def ha_status(self) -> dict[str, Any] | Response: ... + @property + def seal_status(self) -> dict[str, Any] | Response: ... + def read(self, path: str, wrap_ttl: int | str | None = None) -> dict[str, Any] | Response | None: ... + def list(self, path: str) -> dict[str, Any] | Response | None: ... + def write(self, path: str, wrap_ttl: int | str | None, **kwargs: Any) -> dict[str, Any] | Response: ... + def write_data( + self, path: str, *, data: dict[str, Any] | None = None, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def delete(self, path: str) -> None: ... + + @overload + def get_policy(self, name: str, parse: Literal[False] = False) -> str | None: ... + @overload + def get_policy(self, name: str, parse: Literal[True]) -> dict[str, Any] | None: ... + + def lookup_token( + self, token: str | None = None, accessor: bool = False, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def revoke_token(self, token: str, orphan: bool = False, accessor: bool = False) -> None: ... + def renew_token( + self, token: str, increment: bool | None = None, wrap_ttl: int | str | None = None + ) -> dict[str, Any] | Response: ... + def logout(self, revoke_token: bool = False) -> None: ... + def is_authenticated(self) -> bool: ... + def auth_cubbyhole(self, token: str) -> Response: ... + def login(self, url: str, use_token: bool = True, **kwargs: Any) -> Response: ... diff --git a/stubs/ibm-db/METADATA.toml b/stubs/ibm-db/METADATA.toml new file mode 100644 index 000000000000..a77703ca345a --- /dev/null +++ b/stubs/ibm-db/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.2.9" +upstream-repository = "https://github.com/ibmdb/python-ibmdb" diff --git a/stubs/ibm-db/ibm_db.pyi b/stubs/ibm-db/ibm_db.pyi new file mode 100644 index 000000000000..f5abb899bc83 --- /dev/null +++ b/stubs/ibm-db/ibm_db.pyi @@ -0,0 +1,358 @@ +from typing import Any, Final, final, overload +from typing_extensions import Self + +__version__: Final[str] +ATTR_CASE: Final = 3271982 +CASE_LOWER: Final = 1 +CASE_NATURAL: Final = 0 +CASE_UPPER: Final = 2 +PARAM_FILE: Final = 11 +QUOTED_LITERAL_REPLACEMENT_OFF: Final = 0 +QUOTED_LITERAL_REPLACEMENT_ON: Final = 1 +SQL_API_SQLROWCOUNT: Final[int] +SQL_ATTR_AUTOCOMMIT: Final[int] +SQL_ATTR_CALL_RETURN: Final[int] +SQL_ATTR_CURRENT_SCHEMA: Final[int] +SQL_ATTR_CURSOR_TYPE: Final[int] +SQL_ATTR_INFO_ACCTSTR: Final[int] +SQL_ATTR_INFO_APPLNAME: Final[int] +SQL_ATTR_INFO_PROGRAMNAME: Final[int] +SQL_ATTR_INFO_USERID: Final[int] +SQL_ATTR_INFO_WRKSTNNAME: Final[int] +SQL_ATTR_PARAMSET_SIZE: Final[int] +SQL_ATTR_PARAM_BIND_TYPE: Final[int] +SQL_ATTR_QUERY_TIMEOUT: Final[int] +SQL_ATTR_ROWCOUNT_PREFETCH: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_PASSWORD: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_USERID: Final[int] +SQL_ATTR_TXN_ISOLATION: Final[int] +SQL_ATTR_USE_TRUSTED_CONTEXT: Final[int] +SQL_ATTR_XML_DECLARATION: Final[int] +SQL_AUTOCOMMIT_OFF: Final[int] +SQL_AUTOCOMMIT_ON: Final[int] +SQL_BIGINT: Final[int] +SQL_BINARY: Final[int] +SQL_BIT: Final[int] +SQL_BLOB: Final[int] +SQL_BLOB_LOCATOR: Final[int] +SQL_BOOLEAN: Final[int] +SQL_CHAR: Final[int] +SQL_CLOB: Final[int] +SQL_CLOB_LOCATOR: Final[int] +SQL_CURSOR_DYNAMIC: Final[int] +SQL_CURSOR_FORWARD_ONLY: Final[int] +SQL_CURSOR_KEYSET_DRIVEN: Final[int] +SQL_CURSOR_STATIC: Final[int] +SQL_DBCLOB: Final[int] +SQL_DBCLOB_LOCATOR: Final[int] +SQL_DBMS_NAME: Final[int] +SQL_DBMS_VER: Final[int] +SQL_DECFLOAT: Final[int] +SQL_DECIMAL: Final[int] +SQL_DOUBLE: Final[int] +SQL_FALSE: Final[int] +SQL_FLOAT: Final[int] +SQL_GRAPHIC: Final[int] +SQL_INDEX_CLUSTERED: Final[int] +SQL_INDEX_OTHER: Final[int] +SQL_INTEGER: Final[int] +SQL_LONGVARBINARY: Final[int] +SQL_LONGVARCHAR: Final[int] +SQL_LONGVARGRAPHIC: Final[int] +SQL_NUMERIC: Final[int] +SQL_PARAM_BIND_BY_COLUMN: Final[int] +SQL_PARAM_INPUT: Final[int] +SQL_PARAM_INPUT_OUTPUT: Final[int] +SQL_PARAM_OUTPUT: Final[int] +SQL_REAL: Final[int] +SQL_ROWCOUNT_PREFETCH_OFF: Final[int] +SQL_ROWCOUNT_PREFETCH_ON: Final[int] +SQL_SMALLINT: Final[int] +SQL_TABLE_STAT: Final[int] +SQL_TINYINT: Final[int] +SQL_TRUE: Final[int] +SQL_TXN_NO_COMMIT: Final[int] +SQL_TXN_READ_COMMITTED: Final[int] +SQL_TXN_READ_UNCOMMITTED: Final[int] +SQL_TXN_REPEATABLE_READ: Final[int] +SQL_TXN_SERIALIZABLE: Final[int] +SQL_TYPE_DATE: Final[int] +SQL_TYPE_TIME: Final[int] +SQL_TYPE_TIMESTAMP: Final[int] +SQL_VARBINARY: Final[int] +SQL_VARCHAR: Final[int] +SQL_VARGRAPHIC: Final[int] +SQL_WCHAR: Final[int] +SQL_WLONGVARCHAR: Final[int] +SQL_WVARCHAR: Final[int] +SQL_XML: Final[int] +USE_WCHAR: Final = 100 +WCHAR_NO: Final = 0 +WCHAR_YES: Final = 1 + +SQL_ATTR_ACCESS_MODE: Final[int] +SQL_ATTR_ALLOW_INTERLEAVED_GETDATA: Final[int] +SQL_ATTR_ANSI_APP: Final[int] +SQL_ATTR_APPEND_FOR_FETCH_ONLY: Final[int] +SQL_ATTR_APP_USES_LOB_LOCATOR: Final[int] +SQL_ATTR_ASYNC_ENABLE: Final[int] +SQL_ATTR_AUTO_IPD: Final[int] +SQL_ATTR_CACHE_USRLIBL: Final[int] +SQL_ATTR_CLIENT_APPLCOMPAT: Final[int] +SQL_ATTR_CLIENT_CODEPAGE: Final[int] +SQL_ATTR_COLUMNWISE_MRI: Final[int] +SQL_ATTR_COMMITONEOF: Final[int] +SQL_ATTR_CONCURRENT_ACCESS_RESOLUTION: Final[int] +SQL_ATTR_CONFIG_KEYWORDS_ARRAY_SIZE: Final[int] +SQL_ATTR_CONFIG_KEYWORDS_MAXLEN: Final[int] +SQL_ATTR_CONNECTION_DEAD: Final[int] +SQL_ATTR_CONNECTTYPE: Final[int] +SQL_ATTR_CONNECT_NODE: Final[int] +SQL_ATTR_CONNECT_PASSIVE: Final[int] +SQL_ATTR_CONN_CONTEXT: Final[int] +SQL_ATTR_CURRENT_CATALOG: Final[int] +SQL_ATTR_CURRENT_IMPLICIT_XMLPARSE_OPTION: Final[int] +SQL_ATTR_CURRENT_PACKAGE_PATH: Final[int] +SQL_ATTR_CURRENT_PACKAGE_SET: Final[int] +SQL_ATTR_DATE_FMT: Final[int] +SQL_ATTR_DATE_SEP: Final[int] +SQL_ATTR_DB2EXPLAIN: Final[int] +SQL_ATTR_DB2_APPLICATION_HANDLE: Final[int] +SQL_ATTR_DB2_APPLICATION_ID: Final[int] +SQL_ATTR_DB2_SQLERRP: Final[int] +SQL_ATTR_DECFLOAT_ROUNDING_MODE: Final[int] +SQL_ATTR_DECIMAL_SEP: Final[int] +SQL_ATTR_DESCRIBE_CALL: Final[int] +SQL_ATTR_DESCRIBE_OUTPUT_LEVEL: Final[int] +SQL_ATTR_DETECT_READ_ONLY_TXN: Final[int] +SQL_ATTR_DEFERRED_PREPARE: Final[int] +SQL_ATTR_ENLIST_IN_DTC: Final[int] +SQL_ATTR_EXTENDED_INDICATORS: Final[int] +SQL_ATTR_FET_BUF_SIZE: Final[int] +SQL_ATTR_FORCE_ROLLBACK: Final[int] +SQL_ATTR_FREE_LOCATORS_ON_FETCH: Final[int] +SQL_ATTR_GET_LATEST_MEMBER: Final[int] +SQL_ATTR_GET_LATEST_MEMBER_NAME: Final[int] +SQL_ATTR_IGNORE_SERVER_LIST: Final[int] +SQL_ATTR_INFO_CRRTKN: Final[int] +SQL_ATTR_INFO_PROGRAMID: Final[int] +SQL_ATTR_KEEP_DYNAMIC: Final[int] +SQL_ATTR_LOB_CACHE_SIZE: Final[int] +SQL_ATTR_LOB_FILE_THRESHOLD: Final[int] +SQL_ATTR_LOGIN_TIMEOUT: Final[int] +SQL_ATTR_LONGDATA_COMPAT: Final[int] +SQL_ATTR_MAPCHAR: Final[int] +SQL_ATTR_MAXBLKEXT: Final[int] +SQL_ATTR_MAX_LOB_BLOCK_SIZE: Final[int] +SQL_ATTR_NETWORK_STATISTICS: Final[int] +SQL_ATTR_OVERRIDE_CHARACTER_CODEPAGE: Final[int] +SQL_ATTR_OVERRIDE_CODEPAGE: Final[int] +SQL_ATTR_OVERRIDE_PRIMARY_AFFINITY: Final[int] +SQL_ATTR_PARC_BATCH: Final[int] +SQL_ATTR_PING_DB: Final[int] +SQL_ATTR_PING_NTIMES: Final[int] +SQL_ATTR_PING_REQUEST_PACKET_SIZE: Final[int] +SQL_ATTR_QUERY_PREFETCH: Final[int] +SQL_ATTR_QUIET_MODE: Final[int] +SQL_ATTR_READ_ONLY_CONNECTION: Final[int] +SQL_ATTR_RECEIVE_TIMEOUT: Final[int] +SQL_ATTR_REOPT: Final[int] +SQL_ATTR_REPORT_ISLONG_FOR_LONGTYPES_OLEDB: Final[int] +SQL_ATTR_REPORT_SEAMLESSFAILOVER_WARNING: Final[int] +SQL_ATTR_REPORT_TIMESTAMP_TRUNC_AS_WARN: Final[int] +SQL_ATTR_RETRYONERROR: Final[int] +SQL_ATTR_RETRY_ON_MERGE: Final[int] +SQL_ATTR_SERVER_MSGTXT_MASK: Final[int] +SQL_ATTR_SERVER_MSGTXT_SP: Final[int] +SQL_ATTR_SESSION_GLOBAL_VAR: Final[int] +SQL_ATTR_SESSION_TIME_ZONE: Final[int] +SQL_ATTR_SPECIAL_REGISTER: Final[int] +SQL_ATTR_SQLCOLUMNS_SORT_BY_ORDINAL_OLEDB: Final[int] +SQL_ATTR_STMT_CONCENTRATOR: Final[int] +SQL_ATTR_STREAM_GETDATA: Final[int] +SQL_ATTR_STREAM_OUTPUTLOB_ON_CALL: Final[int] +SQL_ATTR_TIME_FMT: Final[int] +SQL_ATTR_TIME_SEP: Final[int] +SQL_ATTR_TRUSTED_CONTEXT_ACCESSTOKEN: Final[int] +SQL_ATTR_USER_REGISTRY_NAME: Final[int] +SQL_ATTR_WCHARTYPE: Final[int] + +@final +class IBM_DBClientInfo: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + APPL_CODEPAGE: int + CONN_CODEPAGE: int + DATA_SOURCE_NAME: str + DRIVER_NAME: str + DRIVER_ODBC_VER: str + DRIVER_VER: str + ODBC_SQL_CONFORMANCE: str + ODBC_VER: str + +@final +class IBM_DBConnection: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + +@final +class IBM_DBServerInfo: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + DBMS_NAME: str + DBMS_VER: str + DB_CODEPAGE: int + DB_NAME: str + DFT_ISOLATION: str + IDENTIFIER_QUOTE_CHAR: str + INST_NAME: str + ISOLATION_OPTION: tuple[str, str, str, str, str] + KEYWORDS: str + LIKE_ESCAPE_CLAUSE: bool + MAX_COL_NAME_LEN: int + MAX_IDENTIFIER_LEN: int + MAX_INDEX_SIZE: int + MAX_PROC_NAME_LEN: int + MAX_ROW_SIZE: int + MAX_SCHEMA_NAME_LEN: int + MAX_STATEMENT_LEN: int + MAX_TABLE_NAME_LEN: int + NON_NULLABLE_COLUMNS: bool + PROCEDURES: bool + SPECIAL_CHARS: str + SQL_CONFORMANCE: str + +@final +class IBM_DBStatement: + def __new__(cls, *args: object, **kwargs: object) -> Self: ... + +def active(connection: IBM_DBConnection | None, /) -> bool: ... +def autocommit(connection: IBM_DBConnection, value: int = ..., /) -> int | bool: ... +def bind_param( + stmt: IBM_DBStatement, + parameter_number: int, + variable: str, + parameter_type: int | None = ..., + data_type: int | None = ..., + precision: int | None = ..., + scale: int | None = ..., + size: int | None = ..., + /, +) -> bool: ... + +@overload +def callproc(connection: IBM_DBConnection, procname: str, /) -> IBM_DBStatement | None: ... +@overload +def callproc(connection: IBM_DBConnection, procname: str, parameters: tuple[object, ...], /) -> tuple[object, ...] | None: ... + +def check_function_support(connection: IBM_DBConnection, function_id: int, /) -> bool: ... +def client_info(connection: IBM_DBConnection, /) -> IBM_DBClientInfo | bool: ... +def close(connection: IBM_DBConnection, /) -> bool: ... +def column_privileges( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + column_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def columns( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + column_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def commit(connection: IBM_DBConnection, /) -> bool: ... +def conn_error(connection: IBM_DBConnection | None = ..., /) -> str: ... +def conn_errormsg(connection: IBM_DBConnection | None = ..., /) -> str: ... +def conn_warn(connection: IBM_DBConnection | None = ..., /) -> str: ... +def connect( + database: str, user: str, password: str, options: dict[int, int | str] | None = ..., replace_quoted_literal: int = ..., / +) -> IBM_DBConnection | None: ... +def createdb(connection: IBM_DBConnection, dbName: str, codeSet: str = ..., mode: str = ..., /) -> bool: ... +def createdbNX(connection: IBM_DBConnection, dbName: str, codeSet: str = ..., mode: str = ..., /) -> bool: ... +def cursor_type(stmt: IBM_DBStatement, /) -> int: ... +def debug(option: str | bool) -> None: ... +def dropdb(connection: IBM_DBConnection, dbName: str, /) -> bool: ... +def exec_immediate( + connection: IBM_DBConnection, statement: str | None, options: dict[int, int] = ..., / +) -> IBM_DBStatement | bool: ... +def execute(stmt: IBM_DBStatement, parameters: tuple[object, ...] | None = ..., /) -> bool: ... +def execute_many( + stmt: IBM_DBStatement, seq_of_parameters: tuple[object, ...], options: dict[int, int] = ..., / +) -> int | None: ... +def fetchall(stmt: IBM_DBStatement, /) -> list[tuple[object, ...]]: ... +def fetchmany(stmt: IBM_DBStatement, numberOfRows: int, /) -> list[tuple[object, ...]]: ... +def fetchone(stmt: IBM_DBStatement, /) -> tuple[object, ...]: ... +def fetch_assoc(stmt: IBM_DBStatement, row_number: int = ..., /) -> dict[str, object] | bool: ... +def fetch_both(stmt: IBM_DBStatement, row_number: int = ..., /) -> dict[int | str, object] | bool: ... +def fetch_row(stmt: IBM_DBStatement, row_number: int = ..., /) -> bool: ... +def fetch_tuple(stmt: IBM_DBStatement, row_number: int = ..., /) -> tuple[object, ...]: ... +def fetch_callproc(stmt: IBM_DBStatement, /) -> tuple[object, ...]: ... +def field_display_size(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_name(stmt: IBM_DBStatement, column: int | str, /) -> str | bool: ... +def field_nullable(stmt: IBM_DBStatement, column: int | str, /) -> bool: ... +def field_num(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_precision(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_scale(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def field_type(stmt: IBM_DBStatement, column: int | str, /) -> str | bool: ... +def field_width(stmt: IBM_DBStatement, column: int | str, /) -> int | bool: ... +def foreign_keys( + connection: IBM_DBConnection, + pk_qualifier: str | None, + pk_schema: str | None, + pk_table_name: str | None, + fk_qualifier: str | None = ..., + fk_schema: str | None = ..., + fk_table_name: str | None = ..., + /, +) -> IBM_DBStatement: ... +def free_result(stmt: IBM_DBStatement, /) -> bool: ... +def free_stmt(stmt: IBM_DBStatement, /) -> bool: ... +def get_db_info(connection: IBM_DBConnection, option: int, /) -> str | bool: ... +def get_last_serial_value(stmt: IBM_DBStatement, /) -> str | bool: ... +def get_num_result(stmt: IBM_DBStatement, /) -> int | bool: ... +def get_option(resc: IBM_DBConnection | IBM_DBStatement, options: int, type: int, /) -> Any: ... +def get_sqlcode(connection_or_stmt: IBM_DBConnection | IBM_DBStatement | None = None, /) -> str: ... +def next_result(stmt: IBM_DBStatement, /) -> IBM_DBStatement | bool: ... +def num_fields(stmt: IBM_DBStatement, /) -> int | bool: ... +def num_rows(stmt: IBM_DBStatement, /) -> int: ... +def pconnect( + database: str, username: str, password: str, options: dict[int, int | str] | None = ..., / +) -> IBM_DBConnection | None: ... +def prepare( + connection: IBM_DBConnection, statement: str, options: dict[int, int | str] | None = ..., / +) -> IBM_DBStatement | bool: ... +def primary_keys( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, / +) -> IBM_DBStatement: ... +def procedure_columns( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, procedure: str | None, parameter: str | None, / +) -> IBM_DBStatement | bool: ... +def procedures( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, procedure: str | None, / +) -> IBM_DBStatement | bool: ... +def recreatedb(connection: IBM_DBConnection, dbName: str, codeSet: str | None = ..., mode: str | None = ..., /) -> bool: ... +def result(stmt: IBM_DBStatement, column: int | str, /) -> Any: ... +def rollback(connection: IBM_DBConnection, /) -> bool: ... +def server_info(connection: IBM_DBConnection, /) -> IBM_DBServerInfo | bool: ... +def set_option(resc: IBM_DBConnection | IBM_DBStatement, options: dict[int, int | str], type: int, /) -> bool: ... +def special_columns( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, scope: int, / +) -> IBM_DBStatement: ... +def statistics( + connection: IBM_DBConnection, qualifier: str | None, schema: str | None, table_name: str | None, unique: bool | None, / +) -> IBM_DBStatement: ... +def stmt_error(stmt: IBM_DBStatement = ..., /) -> str: ... +def stmt_errormsg(stmt: IBM_DBStatement = ..., /) -> str: ... +def stmt_warn(connection: IBM_DBConnection = ..., /) -> IBM_DBStatement: ... +def table_privileges( + connection: IBM_DBConnection, qualifier: str | None = ..., schema: str | None = ..., table_name: str | None = ..., / +) -> IBM_DBStatement | bool: ... +def tables( + connection: IBM_DBConnection, + qualifier: str | None = ..., + schema: str | None = ..., + table_name: str | None = ..., + table_type: str | None = ..., + /, +) -> IBM_DBStatement | bool: ... diff --git a/stubs/ibm-db/ibm_db_ctx.pyi b/stubs/ibm-db/ibm_db_ctx.pyi new file mode 100644 index 000000000000..32620f29cf4f --- /dev/null +++ b/stubs/ibm-db/ibm_db_ctx.pyi @@ -0,0 +1,8 @@ +from types import TracebackType + +import ibm_db + +class Db2connect: + def __init__(self, dsn: str, username: str, password: str) -> None: ... + def __enter__(self) -> ibm_db.IBM_DBConnection: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... diff --git a/stubs/icalendar/@tests/stubtest_allowlist.txt b/stubs/icalendar/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d082afed2b4b --- /dev/null +++ b/stubs/icalendar/@tests/stubtest_allowlist.txt @@ -0,0 +1,11 @@ +# Command line app +icalendar.cli + +# Tests +icalendar\.tests(\..*)? + +# Methods that use `int` to mean `bool`. +icalendar.cal.Component.get_inline + +# Stubtest gets confused by multiple inheritance. +icalendar.prop.vSkip.__new__ diff --git a/stubs/icalendar/@tests/test_cases/check_cal.py b/stubs/icalendar/@tests/test_cases/check_cal.py new file mode 100644 index 000000000000..639034b1d222 --- /dev/null +++ b/stubs/icalendar/@tests/test_cases/check_cal.py @@ -0,0 +1,9 @@ +from icalendar.cal import Component + +component = Component() +component.add("summary", "Test 1") +component.add("dtstart", "2022-01-01", encode=True) +component.add("dtend", "2022-01-02", encode=False) +component.add("location", "Test 3", {}) +component.add("dtstamp", "2022-01-03", parameters={}, encode=True) +component.add("description", "Test 2", parameters={}, encode=False) # type: ignore diff --git a/stubs/icalendar/METADATA.toml b/stubs/icalendar/METADATA.toml new file mode 100644 index 000000000000..a835cf4fb948 --- /dev/null +++ b/stubs/icalendar/METADATA.toml @@ -0,0 +1,7 @@ +version = "6.3.2" +upstream-repository = "https://github.com/collective/icalendar" +dependencies = ["types-python-dateutil", "types-pytz"] +obsolete-since = { version = "7.0.0", date = "2026-02-11" } + +[tool.stubtest] +stubtest-dependencies = ["pytz"] diff --git a/stubs/icalendar/icalendar/__init__.pyi b/stubs/icalendar/icalendar/__init__.pyi new file mode 100644 index 000000000000..bb992fea4a81 --- /dev/null +++ b/stubs/icalendar/icalendar/__init__.pyi @@ -0,0 +1,125 @@ +from . import version as version_mod +from .alarms import Alarms as Alarms, AlarmTime as AlarmTime +from .cal import ( + Alarm as Alarm, + Calendar as Calendar, + Component as Component, + ComponentFactory as ComponentFactory, + Event as Event, + FreeBusy as FreeBusy, + Journal as Journal, + Timezone as Timezone, + TimezoneDaylight as TimezoneDaylight, + TimezoneStandard as TimezoneStandard, + Todo as Todo, +) +from .enums import ( + CUTYPE as CUTYPE, + FBTYPE as FBTYPE, + PARTSTAT as PARTSTAT, + RANGE as RANGE, + RELATED as RELATED, + RELTYPE as RELTYPE, + ROLE as ROLE, +) +from .error import ( + ComponentEndMissing as ComponentEndMissing, + ComponentStartMissing as ComponentStartMissing, + FeatureWillBeRemovedInFutureVersion as FeatureWillBeRemovedInFutureVersion, + IncompleteAlarmInformation as IncompleteAlarmInformation, + IncompleteComponent as IncompleteComponent, + InvalidCalendar as InvalidCalendar, + LocalTimezoneMissing as LocalTimezoneMissing, +) +from .parser import Parameters as Parameters, q_join as q_join, q_split as q_split +from .prop import ( + TypesFactory as TypesFactory, + vBinary as vBinary, + vBoolean as vBoolean, + vCalAddress as vCalAddress, + vDate as vDate, + vDatetime as vDatetime, + vDDDLists as vDDDLists, + vDDDTypes as vDDDTypes, + vDuration as vDuration, + vFloat as vFloat, + vFrequency as vFrequency, + vGeo as vGeo, + vInt as vInt, + vMonth as vMonth, + vPeriod as vPeriod, + vRecur as vRecur, + vSkip as vSkip, + vText as vText, + vTime as vTime, + vUri as vUri, + vUTCOffset as vUTCOffset, + vWeekday as vWeekday, +) +from .timezone import use_pytz, use_zoneinfo + +__all__ = [ + "Calendar", + "Event", + "Todo", + "Journal", + "Timezone", + "TimezoneStandard", + "TimezoneDaylight", + "FreeBusy", + "Alarm", + "ComponentFactory", + "vBinary", + "vBoolean", + "vCalAddress", + "vDatetime", + "vDate", + "vDDDLists", + "vDDDTypes", + "vDuration", + "vFloat", + "vInt", + "vPeriod", + "vWeekday", + "vFrequency", + "vRecur", + "vText", + "vTime", + "vUri", + "vGeo", + "vUTCOffset", + "Parameters", + "q_split", + "q_join", + "use_pytz", + "use_zoneinfo", + "__version__", + "version", + "__version_tuple__", + "version_tuple", + "TypesFactory", + "Component", + "vMonth", + "IncompleteComponent", + "InvalidCalendar", + "Alarms", + "AlarmTime", + "ComponentEndMissing", + "ComponentStartMissing", + "IncompleteAlarmInformation", + "LocalTimezoneMissing", + "CUTYPE", + "FBTYPE", + "PARTSTAT", + "RANGE", + "vSkip", + "RELATED", + "RELTYPE", + "ROLE", + "FeatureWillBeRemovedInFutureVersion", +] + +__version__ = version_mod.__version__ +__version_tuple__ = version_mod.__version_tuple__ +version = version_mod.version +version_tuple = version_mod.version_tuple diff --git a/stubs/icalendar/icalendar/alarms.pyi b/stubs/icalendar/icalendar/alarms.pyi new file mode 100644 index 000000000000..ec2befb72de1 --- /dev/null +++ b/stubs/icalendar/icalendar/alarms.pyi @@ -0,0 +1,48 @@ +import datetime +from typing import TypeAlias + +from .cal import Alarm, Event, Todo +from .error import ( + ComponentEndMissing as ComponentEndMissing, + ComponentStartMissing as ComponentStartMissing, + IncompleteAlarmInformation as IncompleteAlarmInformation, + LocalTimezoneMissing as LocalTimezoneMissing, +) + +__all__ = ["Alarms", "AlarmTime", "IncompleteAlarmInformation", "ComponentEndMissing", "ComponentStartMissing"] + +Parent: TypeAlias = Event | Todo + +class AlarmTime: + def __init__( + self, + alarm: Alarm, + trigger: datetime.datetime, + acknowledged_until: datetime.datetime | None = None, + snoozed_until: datetime.datetime | None = None, + parent: Parent | None = None, + ) -> None: ... + @property + def acknowledged(self) -> datetime.datetime | None: ... + @property + def alarm(self) -> Alarm: ... + @property + def parent(self) -> Parent | None: ... + def is_active(self) -> bool: ... + @property + def trigger(self) -> datetime.date: ... + +class Alarms: + def __init__(self, component: Alarm | Event | Todo | None = None) -> None: ... + def add_component(self, component: Alarm | Parent) -> None: ... + def set_parent(self, parent: Parent) -> None: ... + def add_alarm(self, alarm: Alarm) -> None: ... + def set_start(self, dt: datetime.date | None) -> None: ... + def set_end(self, dt: datetime.date | None) -> None: ... + def acknowledge_until(self, dt: datetime.date | None) -> None: ... + def snooze_until(self, dt: datetime.date | None) -> None: ... + def set_local_timezone(self, tzinfo: datetime.tzinfo | str | None) -> None: ... + @property + def times(self) -> list[AlarmTime]: ... + @property + def active(self) -> list[AlarmTime]: ... diff --git a/stubs/icalendar/icalendar/attr.pyi b/stubs/icalendar/icalendar/attr.pyi new file mode 100644 index 000000000000..c34df7522ce6 --- /dev/null +++ b/stubs/icalendar/icalendar/attr.pyi @@ -0,0 +1,26 @@ +rdates_property: property +exdates_property: property +rrules_property: property + +def multi_language_text_property(main_prop: str, compatibility_prop: str, doc: str) -> property: ... +def single_int_property(prop: str, default: int, doc: str) -> property: ... +def single_utc_property(name: str, docs: str) -> property: ... +def single_string_property(name: str, docs: str, other_name: str | None = None) -> property: ... + +color_property: property +sequence_property: property +categories_property: property +uid_property: property + +__all__ = [ + "categories_property", + "color_property", + "exdates_property", + "multi_language_text_property", + "rdates_property", + "rrules_property", + "sequence_property", + "single_int_property", + "single_utc_property", + "uid_property", +] diff --git a/stubs/icalendar/icalendar/cal.pyi b/stubs/icalendar/icalendar/cal.pyi new file mode 100644 index 000000000000..f78c9f8d7198 --- /dev/null +++ b/stubs/icalendar/icalendar/cal.pyi @@ -0,0 +1,551 @@ +import datetime +from _typeshed import Incomplete, SupportsItems +from collections.abc import Callable, Iterable +from typing import Any, ClassVar, Final, Literal, NamedTuple, TypeVar, overload +from typing_extensions import Self + +from .alarms import Alarms +from .caselessdict import CaselessDict +from .error import IncompleteComponent as IncompleteComponent +from .parser import Contentline, Contentlines +from .parser_tools import ICAL_TYPE +from .prop import TypesFactory, _vType, vRecur +from .timezone.tzp import TZP + +_D = TypeVar("_D") + +__all__ = [ + "Alarm", + "Calendar", + "Component", + "ComponentFactory", + "Event", + "FreeBusy", + "INLINE", + "Journal", + "Timezone", + "TimezoneDaylight", + "TimezoneStandard", + "Todo", + "component_factory", + "get_example", + "IncompleteComponent", +] + +def get_example(component_directory: str, example_name: str) -> bytes: ... + +class ComponentFactory(CaselessDict[Incomplete]): + # Inherit complex __init__ from CaselessDict<-dict. + ... + +INLINE: CaselessDict[int] + +class Component(CaselessDict[Incomplete]): + name: ClassVar[str | None] + required: ClassVar[tuple[str, ...]] + singletons: ClassVar[tuple[str, ...]] + multiple: ClassVar[tuple[str, ...]] + exclusive: ClassVar[tuple[str, ...]] + inclusive: ClassVar[tuple[tuple[str, ...], ...]] + ignore_exceptions: ClassVar[bool] + subcomponents: list[Incomplete] + errors: list[str] + + # Inherit complex __init__ from CaselessDict<-dict. + def __bool__(self) -> bool: ... + __nonzero__ = __bool__ + def is_empty(self) -> bool: ... + + @overload + def add(self, name: str, value: Any, *, encode: Literal[False]) -> None: ... + @overload + def add(self, name: str, value: Any, parameters: None, encode: Literal[False]) -> None: ... + @overload + def add( + self, name: str, value: Any, parameters: SupportsItems[str, str | None] | None = None, encode: Literal[True] = True + ) -> None: ... + + def decoded(self, name: str, default: _D = ...) -> Incomplete | _D: ... + def get_inline(self, name: str, decode: bool = True) -> list[Incomplete]: ... + + @overload + def set_inline(self, name: str, values: Iterable[str], encode: Literal[False] = ...) -> None: ... + @overload + def set_inline(self, name: str, values: Iterable[Incomplete], encode: Literal[True] = True) -> None: ... + + def add_component(self, component: Component) -> None: ... + def walk(self, name: str | None = None, select: Callable[[Component], bool] = ...) -> list[Component]: ... + def property_items(self, recursive: bool = True, sorted: bool = True) -> list[tuple[str, object]]: ... + + @overload + @classmethod + def from_ical(cls, st: str, multiple: Literal[False] = False) -> Component: ... # or any of its subclasses + @overload + @classmethod + def from_ical(cls, st: str, multiple: Literal[True]) -> list[Component]: ... # or any of its subclasses + + def content_line(self, name: str, value: _vType | ICAL_TYPE, sorted: bool = True) -> Contentline: ... + def content_lines(self, sorted: bool = True) -> Contentlines: ... + def to_ical(self, sorted: bool = True) -> bytes: ... + def __eq__(self, other: Component) -> bool: ... # type: ignore[override] + + @property + def DTSTAMP(self) -> datetime.datetime | None: ... + @DTSTAMP.setter + def DTSTAMP(self, value: datetime.datetime) -> None: ... + @DTSTAMP.deleter + def DTSTAMP(self) -> None: ... + + @property + def LAST_MODIFIED(self) -> datetime.datetime | None: ... + @LAST_MODIFIED.setter + def LAST_MODIFIED(self, value: datetime.datetime) -> None: ... + @LAST_MODIFIED.deleter + def LAST_MODIFIED(self) -> None: ... + + def is_thunderbird(self) -> bool: ... + +# type_def is a TypeForm +def create_single_property( + prop: str, value_attr: str | None, value_type: tuple[type, ...], type_def: Any, doc: str, vProp: type[Incomplete] = ... +) -> property: ... + +class Event(Component): + name: ClassVar[Literal["VEVENT"]] + @property + def alarms(self) -> Alarms: ... + @classmethod + def example(cls, name: str = "rfc_9074_example_3") -> Event: ... + + @property + def DTSTART(self) -> datetime.date | datetime.datetime | None: ... + @DTSTART.setter + def DTSTART(self, value: datetime.date | datetime.datetime | None) -> None: ... + @DTSTART.deleter + def DTSTART(self) -> None: ... + + @property + def DTEND(self) -> datetime.date | datetime.datetime | None: ... + @DTEND.setter + def DTEND(self, value: datetime.date | datetime.datetime | None) -> None: ... + @DTEND.deleter + def DTEND(self) -> None: ... + + @property + def DURATION(self) -> datetime.timedelta | None: ... + @DURATION.setter + def DURATION(self, value: datetime.timedelta | None) -> None: ... + @DURATION.deleter + def DURATION(self) -> None: ... + + @property + def duration(self) -> datetime.timedelta: ... + + @property + def start(self) -> datetime.date | datetime.datetime: ... + @start.setter + def start(self, value: datetime.date | datetime.datetime | None) -> None: ... + + @property + def end(self) -> datetime.date | datetime.datetime: ... + @end.setter + def end(self, value: datetime.date | datetime.datetime | None) -> None: ... + + @property + def X_MOZ_SNOOZE_TIME(self) -> datetime.datetime | None: ... + @X_MOZ_SNOOZE_TIME.setter + def X_MOZ_SNOOZE_TIME(self, value: datetime.datetime) -> None: ... + @X_MOZ_SNOOZE_TIME.deleter + def X_MOZ_SNOOZE_TIME(self) -> None: ... + + @property + def X_MOZ_LASTACK(self) -> datetime.datetime | None: ... + @X_MOZ_LASTACK.setter + def X_MOZ_LASTACK(self, value: datetime.datetime) -> None: ... + @X_MOZ_LASTACK.deleter + def X_MOZ_LASTACK(self) -> None: ... + + @property + def color(self) -> str: ... + @color.setter + def color(self, value: str) -> None: ... + @color.deleter + def color(self) -> None: ... + + @property + def sequence(self) -> int: ... + @sequence.setter + def sequence(self, value: int) -> None: ... + @sequence.deleter + def sequence(self) -> None: ... + + @property + def categories(self) -> list[str]: ... + @categories.setter + def categories(self, cats: list[str]) -> None: ... + @categories.deleter + def categories(self) -> None: ... + + @property + def rdates( + self, + ) -> list[tuple[datetime.date, None] | tuple[datetime.datetime, None] | tuple[datetime.datetime, datetime.datetime]]: ... + @property + def exdates(self) -> list[datetime.date | datetime.datetime]: ... + @property + def rrules(self) -> list[vRecur]: ... + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +class Todo(Component): + name: ClassVar[Literal["VTODO"]] + + @property + def DTSTART(self) -> datetime.datetime | datetime.date | None: ... + @DTSTART.setter + def DTSTART(self, value: datetime.datetime | datetime.date | None) -> None: ... + @DTSTART.deleter + def DTSTART(self) -> None: ... + + @property + def DUE(self) -> datetime.datetime | datetime.date | None: ... + @DUE.setter + def DUE(self, value: datetime.datetime | datetime.date | None) -> None: ... + @DUE.deleter + def DUE(self) -> None: ... + + @property + def DURATION(self) -> datetime.timedelta | None: ... + @DURATION.setter + def DURATION(self, value: datetime.timedelta | None) -> None: ... + @DURATION.deleter + def DURATION(self) -> None: ... + + @property + def start(self) -> datetime.datetime | datetime.date: ... + @start.setter + def start(self, value: datetime.datetime | datetime.date | None) -> None: ... + + @property + def end(self) -> datetime.datetime | datetime.date: ... + @end.setter + def end(self, value: datetime.datetime | datetime.date | None) -> None: ... + + @property + def duration(self) -> datetime.timedelta: ... + + @property + def X_MOZ_SNOOZE_TIME(self) -> datetime.datetime | None: ... + @X_MOZ_SNOOZE_TIME.setter + def X_MOZ_SNOOZE_TIME(self, value: datetime.datetime) -> None: ... + @X_MOZ_SNOOZE_TIME.deleter + def X_MOZ_SNOOZE_TIME(self) -> None: ... + + @property + def X_MOZ_LASTACK(self) -> datetime.datetime | None: ... + @X_MOZ_LASTACK.setter + def X_MOZ_LASTACK(self, value: datetime.datetime) -> None: ... + @X_MOZ_LASTACK.deleter + def X_MOZ_LASTACK(self) -> None: ... + + @property + def alarms(self) -> Alarms: ... + + @property + def color(self) -> str: ... + @color.setter + def color(self, value: str) -> None: ... + @color.deleter + def color(self) -> None: ... + + @property + def sequence(self) -> int: ... + @sequence.setter + def sequence(self, value: int) -> None: ... + @sequence.deleter + def sequence(self) -> None: ... + + @property + def categories(self) -> list[str]: ... + @categories.setter + def categories(self, cats: list[str]) -> None: ... + @categories.deleter + def categories(self) -> None: ... + + @property + def rdates( + self, + ) -> list[tuple[datetime.date, None] | tuple[datetime.datetime, None] | tuple[datetime.datetime, datetime.datetime]]: ... + @property + def exdates(self) -> list[datetime.date | datetime.datetime]: ... + @property + def rrules(self) -> list[vRecur]: ... + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +class Journal(Component): + name: ClassVar[Literal["VJOURNAL"]] + + @property + def DTSTART(self) -> datetime.date | datetime.datetime | None: ... + @DTSTART.setter + def DTSTART(self, value: datetime.date | datetime.datetime | None) -> None: ... + @DTSTART.deleter + def DTSTART(self) -> None: ... + + @property + def start(self) -> datetime.date | datetime.datetime: ... + @start.setter + def start(self, value: datetime.date | datetime.datetime | None) -> None: ... + + end = start + @property + def duration(self) -> datetime.timedelta: ... + + @property + def color(self) -> str: ... + @color.setter + def color(self, value: str) -> None: ... + @color.deleter + def color(self) -> None: ... + + @property + def sequence(self) -> int: ... + @sequence.setter + def sequence(self, value: int) -> None: ... + @sequence.deleter + def sequence(self) -> None: ... + + @property + def categories(self) -> list[str]: ... + @categories.setter + def categories(self, cats: list[str]) -> None: ... + @categories.deleter + def categories(self) -> None: ... + + @property + def rdates( + self, + ) -> list[tuple[datetime.date, None] | tuple[datetime.datetime, None] | tuple[datetime.datetime, datetime.datetime]]: ... + @property + def exdates(self) -> list[datetime.date | datetime.datetime]: ... + @property + def rrules(self) -> list[vRecur]: ... + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +class FreeBusy(Component): + name: ClassVar[Literal["VFREEBUSY"]] + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +class Timezone(Component): + subcomponents: list[TimezoneStandard | TimezoneDaylight] + name: ClassVar[Literal["VTIMEZONE"]] + @classmethod + def example(cls, name: str = "pacific_fiji") -> Calendar: ... + def to_tz(self, tzp: TZP = ..., lookup_tzid: bool = True) -> datetime.tzinfo: ... + @property + def tz_name(self) -> str: ... + def get_transitions(self) -> tuple[list[datetime.datetime], list[tuple[datetime.timedelta, datetime.timedelta, str]]]: ... + @classmethod + def from_tzinfo( + cls, timezone: datetime.tzinfo, tzid: str | None = None, first_date: datetime.date = ..., last_date: datetime.date = ... + ) -> Self: ... + @classmethod + def from_tzid(cls, tzid: str, tzp: TZP = ..., first_date: datetime.date = ..., last_date: datetime.date = ...) -> Self: ... + @property + def standard(self) -> list[TimezoneStandard]: ... + @property + def daylight(self) -> list[TimezoneDaylight]: ... + +class TimezoneStandard(Component): + name: ClassVar[Literal["STANDARD"]] + + @property + def DTSTART(self) -> datetime.date | datetime.datetime | None: ... + @DTSTART.setter + def DTSTART(self, value: datetime.date | datetime.datetime | None) -> None: ... + @DTSTART.deleter + def DTSTART(self) -> None: ... + + @property + def TZOFFSETTO(self) -> datetime.timedelta | None: ... + @TZOFFSETTO.setter + def TZOFFSETTO(self, value: datetime.timedelta | None) -> None: ... + @TZOFFSETTO.deleter + def TZOFFSETTO(self) -> None: ... + + @property + def TZOFFSETFROM(self) -> datetime.timedelta | None: ... + @TZOFFSETFROM.setter + def TZOFFSETFROM(self, value: datetime.timedelta | None) -> None: ... + @TZOFFSETFROM.deleter + def TZOFFSETFROM(self) -> None: ... + + @property + def rdates( + self, + ) -> list[tuple[datetime.date, None] | tuple[datetime.datetime, None] | tuple[datetime.datetime, datetime.datetime]]: ... + @property + def exdates(self) -> list[datetime.date | datetime.datetime]: ... + @property + def rrules(self) -> list[vRecur]: ... + +class TimezoneDaylight(Component): + name: ClassVar[Literal["DAYLIGHT"]] + + @property + def DTSTART(self) -> datetime.date | datetime.datetime | None: ... + @DTSTART.setter + def DTSTART(self, value: datetime.date | datetime.datetime | None) -> None: ... + @DTSTART.deleter + def DTSTART(self) -> None: ... + + @property + def TZOFFSETTO(self) -> datetime.timedelta | None: ... + @TZOFFSETTO.setter + def TZOFFSETTO(self, value: datetime.timedelta | None) -> None: ... + @TZOFFSETTO.deleter + def TZOFFSETTO(self) -> None: ... + + @property + def TZOFFSETFROM(self) -> datetime.timedelta | None: ... + @TZOFFSETFROM.setter + def TZOFFSETFROM(self, value: datetime.timedelta | None) -> None: ... + @TZOFFSETFROM.deleter + def TZOFFSETFROM(self) -> None: ... + + @property + def rdates( + self, + ) -> list[tuple[datetime.date, None] | tuple[datetime.datetime, None] | tuple[datetime.datetime, datetime.datetime]]: ... + @property + def exdates(self) -> list[datetime.date | datetime.datetime]: ... + @property + def rrules(self) -> list[vRecur]: ... + +class Alarm(Component): + name: ClassVar[Literal["VALARM"]] + + @property + def REPEAT(self) -> int: ... + @REPEAT.setter + def REPEAT(self, value: int) -> None: ... + @REPEAT.deleter + def REPEAT(self) -> None: ... + + @property + def DURATION(self) -> datetime.timedelta | None: ... + @DURATION.setter + def DURATION(self, value: datetime.timedelta | None) -> None: ... + @DURATION.deleter + def DURATION(self) -> None: ... + + @property + def ACKNOWLEDGED(self) -> datetime.datetime | None: ... + @ACKNOWLEDGED.setter + def ACKNOWLEDGED(self, value: datetime.datetime | None) -> None: ... + @ACKNOWLEDGED.deleter + def ACKNOWLEDGED(self) -> None: ... + + @property + def TRIGGER(self) -> datetime.timedelta | datetime.datetime | None: ... + @TRIGGER.setter + def TRIGGER(self, value: datetime.timedelta | datetime.datetime | None) -> None: ... + @TRIGGER.deleter + def TRIGGER(self) -> None: ... + + @property + def TRIGGER_RELATED(self) -> Literal["START", "END"]: ... + @TRIGGER_RELATED.setter + def TRIGGER_RELATED(self, value: Literal["START", "END"]) -> None: ... + + class Triggers(NamedTuple): + start: tuple[datetime.timedelta, ...] + end: tuple[datetime.timedelta, ...] + absolute: tuple[datetime.datetime, ...] + + @property + def triggers(self) -> Alarm.Triggers: ... + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +class Calendar(Component): + name: ClassVar[Literal["VCALENDAR"]] + @classmethod + def example(cls, name: str = "example") -> Calendar: ... + @property + def freebusy(self) -> list[FreeBusy]: ... + @property + def events(self) -> list[Event]: ... + @property + def todos(self) -> list[Todo]: ... + def get_used_tzids(self) -> set[str]: ... + def get_missing_tzids(self) -> set[str]: ... + @property + def timezones(self) -> list[Timezone]: ... + def add_missing_timezones(self, first_date: datetime.date = ..., last_date: datetime.date = ...) -> None: ... + + @property + def calendar_name(self) -> str | None: ... + @calendar_name.setter + def calendar_name(self, value: str) -> None: ... + @calendar_name.deleter + def calendar_name(self) -> None: ... + + @property + def description(self) -> str | None: ... + @description.setter + def description(self, value: str) -> None: ... + @description.deleter + def description(self) -> None: ... + + @property + def color(self) -> str: ... + @color.setter + def color(self, value: str) -> None: ... + @color.deleter + def color(self) -> None: ... + + @property + def categories(self) -> list[str]: ... + @categories.setter + def categories(self, cats: list[str]) -> None: ... + @categories.deleter + def categories(self) -> None: ... + + @property + def uid(self) -> str: ... + @uid.setter + def uid(self, value: str) -> None: ... + @uid.deleter + def uid(self) -> None: ... + +types_factory: Final[TypesFactory] +component_factory: Final[ComponentFactory] diff --git a/stubs/icalendar/icalendar/caselessdict.pyi b/stubs/icalendar/icalendar/caselessdict.pyi new file mode 100644 index 000000000000..aa046445f167 --- /dev/null +++ b/stubs/icalendar/icalendar/caselessdict.pyi @@ -0,0 +1,49 @@ +from _typeshed import SupportsItems +from collections import OrderedDict +from collections.abc import Iterable, Mapping +from typing import ClassVar, TypeVar, overload +from typing_extensions import Self + +__all__ = ["canonsort_keys", "canonsort_items", "CaselessDict"] + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +def canonsort_keys(keys: Iterable[str], canonical_order: Iterable[str] | None = None) -> list[str]: ... +def canonsort_items(dict1: Mapping[str, _VT], canonical_order: Iterable[str] | None = None) -> list[tuple[str, _VT]]: ... + +class CaselessDict(OrderedDict[str, _VT]): + # Inherit complex __init__ from dict. + def __getitem__(self, key: str | bytes) -> _VT: ... + def __setitem__(self, key: str | bytes, value: _VT) -> None: ... + def __delitem__(self, key: str | bytes) -> None: ... + def __contains__(self, key: str | bytes) -> bool: ... # type: ignore[override] + + @overload + def get(self, key: str | bytes, default: None = None) -> _VT: ... + @overload + def get(self, key: str | bytes, default: _VT) -> _VT: ... + @overload + def get(self, key: str | bytes, default: _T) -> _VT | _T: ... + + @overload + def setdefault(self: CaselessDict[_T | None], key: str | bytes, value: None = None) -> _T | None: ... + @overload + def setdefault(self, key: str | bytes, value: _VT) -> _VT: ... + + @overload # type: ignore[override] + def pop(self, key: str | bytes, default: None = None) -> _VT | None: ... + @overload + def pop(self, key: str | bytes, default: _VT) -> _VT: ... + @overload + def pop(self, key: str | bytes, default: _T) -> _VT | _T: ... + + def popitem(self) -> tuple[str, _VT]: ... # type: ignore[override] + def has_key(self, key: str | bytes) -> bool: ... + def update(self, *args: SupportsItems[str, _VT] | Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... # type: ignore[override] + def copy(self) -> Self: ... + def __eq__(self, other: SupportsItems[str, _VT]) -> bool: ... # type: ignore[override] + def __ne__(self, other: SupportsItems[str, _VT]) -> bool: ... # type: ignore[override] + canonical_order: ClassVar[Iterable[str] | None] + def sorted_keys(self) -> list[str]: ... + def sorted_items(self) -> list[tuple[str, _VT]]: ... diff --git a/stubs/icalendar/icalendar/enums.pyi b/stubs/icalendar/icalendar/enums.pyi new file mode 100644 index 000000000000..cfe73902b5c0 --- /dev/null +++ b/stubs/icalendar/icalendar/enums.pyi @@ -0,0 +1,44 @@ +from enum import Enum + +class PARTSTAT(Enum): + NEEDS_ACTION = "NEEDS-ACTION" + ACCEPTED = "ACCEPTED" + DECLINED = "DECLINED" + TENTATIVE = "TENTATIVE" + DELEGATED = "DELEGATED" + COMPLETED = "COMPLETED" + IN_PROCESS = "IN-PROCESS" + +class FBTYPE(Enum): + FREE = "FREE" + BUSY = "BUSY" + BUSY_UNAVAILABLE = "BUSY-UNAVAILABLE" + BUSY_TENTATIVE = "BUSY-TENTATIVE" + +class CUTYPE(Enum): + INDIVIDUAL = "INDIVIDUAL" + GROUP = "GROUP" + RESOURCE = "RESOURCE" + ROOM = "ROOM" + UNKNOWN = "UNKNOWN" + +class RELTYPE(Enum): + PARENT = "PARENT" + CHILD = "CHILD" + SIBLING = "SIBLING" + +class RANGE(Enum): + THISANDFUTURE = "THISANDFUTURE" + THISANDPRIOR = "THISANDPRIOR" # deprecated + +class RELATED(Enum): + START = "START" + END = "END" + +class ROLE(Enum): + CHAIR = "CHAIR" + REQ_PARTICIPANT = "REQ-PARTICIPANT" + OPT_PARTICIPANT = "OPT-PARTICIPANT" + NON_PARTICIPANT = "NON-PARTICIPANT" + +__all__ = ["PARTSTAT", "FBTYPE", "CUTYPE", "RANGE", "RELATED", "ROLE", "RELTYPE"] diff --git a/stubs/icalendar/icalendar/error.pyi b/stubs/icalendar/icalendar/error.pyi new file mode 100644 index 000000000000..ef195bd38d0f --- /dev/null +++ b/stubs/icalendar/icalendar/error.pyi @@ -0,0 +1,19 @@ +class InvalidCalendar(ValueError): ... +class IncompleteComponent(ValueError): ... +class IncompleteAlarmInformation(ValueError): ... +class LocalTimezoneMissing(IncompleteAlarmInformation): ... +class ComponentEndMissing(IncompleteAlarmInformation): ... +class ComponentStartMissing(IncompleteAlarmInformation): ... +class FeatureWillBeRemovedInFutureVersion(DeprecationWarning): ... +class WillBeRemovedInVersion7(FeatureWillBeRemovedInFutureVersion): ... + +__all__ = [ + "InvalidCalendar", + "IncompleteComponent", + "IncompleteAlarmInformation", + "LocalTimezoneMissing", + "ComponentEndMissing", + "ComponentStartMissing", + "FeatureWillBeRemovedInFutureVersion", + "WillBeRemovedInVersion7", +] diff --git a/stubs/icalendar/icalendar/param.pyi b/stubs/icalendar/icalendar/param.pyi new file mode 100644 index 000000000000..9620a3a6580b --- /dev/null +++ b/stubs/icalendar/icalendar/param.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable +from typing import TypeVar + +from .parser import Parameters + +class IcalendarProperty: + params: Parameters + +_T = TypeVar("_T") + +def string_parameter( + name: str, + doc: str, + default: Callable[..., str | None] = ..., + convert: Callable[[str], _T] | None = None, + convert_to: Callable[[_T], str] | None = None, +) -> property: ... + +ALTREP: property +CN: property +CUTYPE: property + +def quoted_list_parameter(name: str, doc: str) -> property: ... + +DELEGATED_FROM: property +DELEGATED_TO: property +DIR: property +FBTYPE: property +LANGUAGE: property +MEMBER: property +PARTSTAT: property +RANGE: property +RELATED: property +ROLE: property + +def boolean_parameter(name: str, default: bool, doc: str) -> property: ... + +RSVP: property +SENT_BY: property +TZID: property +RELTYPE: property + +__all__ = [ + "string_parameter", + "quoted_list_parameter", + "ALTREP", + "CN", + "CUTYPE", + "DELEGATED_FROM", + "DELEGATED_TO", + "DIR", + "FBTYPE", + "LANGUAGE", + "MEMBER", + "PARTSTAT", + "RANGE", + "RELATED", + "ROLE", + "RSVP", + "SENT_BY", + "TZID", +] diff --git a/stubs/icalendar/icalendar/parser.pyi b/stubs/icalendar/icalendar/parser.pyi new file mode 100644 index 000000000000..7c70dc920aeb --- /dev/null +++ b/stubs/icalendar/icalendar/parser.pyi @@ -0,0 +1,98 @@ +from _collections_abc import dict_keys +from _typeshed import Incomplete +from collections.abc import Iterable +from re import Pattern +from typing import AnyStr, ClassVar, Final, overload +from typing_extensions import Self + +from .caselessdict import CaselessDict +from .parser_tools import ICAL_TYPE +from .prop import _vType + +__all__ = [ + "Contentline", + "Contentlines", + "FOLD", + "NAME", + "NEWLINE", + "Parameters", + "QUNSAFE_CHAR", + "QUOTABLE", + "UNSAFE_CHAR", + "dquote", + "escape_char", + "escape_string", + "foldline", + "param_value", + "q_join", + "q_split", + "rfc_6868_escape", + "rfc_6868_unescape", + "uFOLD", + "unescape_char", + "unescape_list_or_string", + "unescape_string", + "validate_param_value", + "validate_token", +] + +def escape_char(text: str) -> str: ... +def unescape_char(text: AnyStr) -> AnyStr: ... +def foldline(line: str, limit: int = 75, fold_sep: str = "\r\n ") -> str: ... +def param_value(value: str | list[str] | tuple[str, ...] | Incomplete, always_quote: bool = False) -> str: ... + +NAME: Final[Pattern[str]] +UNSAFE_CHAR: Final[Pattern[str]] +QUNSAFE_CHAR: Final[Pattern[str]] +FOLD: Final[Pattern[bytes]] +uFOLD: Final[Pattern[str]] +NEWLINE: Final[Pattern[str]] + +def validate_token(name: str) -> None: ... +def validate_param_value(value: str, quoted: bool = True) -> None: ... + +QUOTABLE: Final[Pattern[str]] + +def dquote(val: str, always_quote: bool = False) -> str: ... +def q_split(st: str, sep: str = ",", maxsplit: int = -1) -> list[str]: ... +def q_join(lst: Iterable[str], sep: str = ",", always_quote: bool = False) -> str: ... + +class Parameters(CaselessDict[str]): + always_quoted: ClassVar[tuple[str, ...]] + quote_also: ClassVar[dict[str, str]] + def params(self) -> dict_keys[str, str]: ... + def to_ical(self, sorted: bool = True) -> bytes: ... + @classmethod + def from_ical(cls, st: str, strict: bool = False) -> Self: ... + +def escape_string(val: str) -> str: ... +def unescape_string(val: str) -> str: ... + +RFC_6868_UNESCAPE_REGEX: Final[Pattern[str]] + +def rfc_6868_unescape(param_value: str) -> str: ... + +RFC_6868_ESCAPE_REGEX: Final[Pattern[str]] + +def rfc_6868_escape(param_value: str) -> str: ... + +@overload +def unescape_list_or_string(val: list[str]) -> list[str]: ... +@overload +def unescape_list_or_string(val: str) -> str: ... + +class Contentline(str): + __slots__ = ("strict",) + strict: bool + def __new__(cls, value: str | bytes, strict: bool = False, encoding: str = "utf-8") -> Self: ... + @classmethod + def from_parts(cls, name: ICAL_TYPE, params: Parameters, values: _vType | ICAL_TYPE, sorted: bool = True) -> Self: ... + def parts(self) -> tuple[str, Parameters, str]: ... + @classmethod + def from_ical(cls, ical: str | bytes, strict: bool = False) -> Self: ... + def to_ical(self) -> bytes: ... + +class Contentlines(list[Contentline]): + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, st: str | bytes) -> Self: ... diff --git a/stubs/icalendar/icalendar/parser_tools.pyi b/stubs/icalendar/icalendar/parser_tools.pyi new file mode 100644 index 000000000000..ac90b121369d --- /dev/null +++ b/stubs/icalendar/icalendar/parser_tools.pyi @@ -0,0 +1,21 @@ +from typing import Any, Final, TypeAlias, TypeVar, overload + +_T = TypeVar("_T") + +__all__ = ["DEFAULT_ENCODING", "SEQUENCE_TYPES", "ICAL_TYPE", "data_encode", "from_unicode", "to_unicode"] + +SEQUENCE_TYPES: Final[tuple[type[Any], ...]] +DEFAULT_ENCODING: str +ICAL_TYPE: TypeAlias = str | bytes + +def from_unicode(value: ICAL_TYPE, encoding: str = "utf-8") -> bytes: ... +def to_unicode(value: ICAL_TYPE, encoding: str = "utf-8-sig") -> str: ... + +@overload +def data_encode(data: ICAL_TYPE, encoding: str = "utf-8") -> bytes: ... +@overload +def data_encode(data: dict[Any, Any], encoding: str = "utf-8") -> dict[Any, Any]: ... +@overload +def data_encode(data: list[Any] | tuple[Any, ...], encoding: str = "utf-8") -> list[Any]: ... +@overload +def data_encode(data: _T, encoding: str = "utf-8") -> _T: ... diff --git a/stubs/icalendar/icalendar/prop.pyi b/stubs/icalendar/icalendar/prop.pyi new file mode 100644 index 000000000000..d08a2b5b2bf9 --- /dev/null +++ b/stubs/icalendar/icalendar/prop.pyi @@ -0,0 +1,341 @@ +import datetime +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, SupportsKeysAndGetItem, Unused +from collections.abc import Iterable, Iterator +from enum import Enum +from re import Pattern +from typing import Any, ClassVar, Final, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self + +from .caselessdict import CaselessDict +from .parser import Parameters +from .parser_tools import ICAL_TYPE +from .timezone import tzid_from_dt as tzid_from_dt, tzid_from_tzinfo as tzid_from_tzinfo + +__all__ = [ + "DURATION_REGEX", + "TimeBase", + "TypesFactory", + "WEEKDAY_RULE", + "tzid_from_dt", + "vBinary", + "vBoolean", + "vCalAddress", + "vCategory", + "vDDDLists", + "vDDDTypes", + "vDate", + "vDatetime", + "vDuration", + "vFloat", + "vFrequency", + "vGeo", + "vInline", + "vInt", + "vMonth", + "vPeriod", + "vRecur", + "vText", + "vTime", + "vUTCOffset", + "vUri", + "vWeekday", + "tzid_from_tzinfo", + "vSkip", +] + +_PropType: TypeAlias = type[Any] # any of the v* classes in this file +_PeriodTuple: TypeAlias = tuple[datetime.datetime, datetime.datetime | datetime.timedelta] +_AnyTimeType: TypeAlias = datetime.datetime | datetime.date | datetime.timedelta | datetime.time | _PeriodTuple + +@type_check_only +class _vType(Protocol): + def to_ical(self) -> bytes | str: ... + +DURATION_REGEX: Final[Pattern[str]] +WEEKDAY_RULE: Final[Pattern[str]] + +class vBinary: + obj: str + params: Parameters + def __init__(self, obj: str | bytes) -> None: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: ICAL_TYPE) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + +class vBoolean(int): + BOOL_MAP: Final[CaselessDict[bool]] + params: Parameters + def __new__(cls, x: ConvertibleToInt = ..., /, *, params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> Literal[b"TRUE", b"FALSE"]: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> bool: ... + +class vText(str): + __slots__ = ("encoding", "params") + encoding: str + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + ALTREP: property + LANGUAGE: property + RELTYPE: property + +class vCalAddress(str): + __slots__ = ("params",) + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + @property + def email(self) -> str: ... + + @property + def name(self) -> str: ... + @name.setter + def name(self, value: str) -> None: ... + @name.deleter + def name(self) -> None: ... + + CN: property + CUTYPE: property + DELEGATED_FROM: property + DELEGATED_TO: property + DIR: property + LANGUAGE: property + PARTSTAT: property + ROLE: property + RSVP: property + SENT_BY: property + +class vFloat(float): + params: Parameters + def __new__(cls, x: ConvertibleToFloat = ..., /, *, params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class vInt(int): + params: Parameters + def __new__(cls, x: ConvertibleToInt = ..., /, *, params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class vDDDLists: + params: Parameters + dts: list[vDDDTypes] + def __init__(self, dt_list: Iterable[_AnyTimeType] | _AnyTimeType) -> None: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: str, timezone: str | datetime.timezone | None = None) -> list[Incomplete]: ... + def __eq__(self, other: object) -> bool: ... + +class vCategory: + cats: list[vText] + params: Parameters + def __init__(self, c_list: Iterable[ICAL_TYPE] | ICAL_TYPE, params: SupportsKeysAndGetItem[str, str] = {}) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: ICAL_TYPE) -> str: ... + def __eq__(self, other: object) -> bool: ... + RANGE: property + RELATED: property + TZID: property + +class TimeBase: + params: Parameters + ignore_for_equality: set[str] + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + RANGE: property + RELATED: property + TZID: property + +class vDDDTypes(TimeBase): + params: Parameters + dt: _AnyTimeType + def __init__(self, dt: _AnyTimeType) -> None: ... + def to_ical(self) -> bytes: ... + + @overload + @classmethod + def from_ical(cls, ical: Self, timezone: Unused | None = None) -> _AnyTimeType: ... + # Return type is one of vDuration, vPeriod, vDatetime, vDate, or vTime, + # depending on the ical string. + @overload + @classmethod + def from_ical(cls, ical: str, timezone: datetime.timezone | str | None = None) -> Any: ... + +class vDate(TimeBase): + dt: datetime.date + params: Parameters + def __init__(self, dt: datetime.date) -> None: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: ICAL_TYPE) -> datetime.date: ... + +class vDatetime(TimeBase): + dt: datetime.datetime + params: Parameters + def __init__(self, dt: datetime.datetime, params: SupportsKeysAndGetItem[str, str] = {}) -> None: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: ICAL_TYPE, timezone: datetime.timezone | str | None = None) -> datetime.datetime: ... + +class vDuration(TimeBase): + td: datetime.timedelta + params: Parameters + def __init__(self, td: datetime.timedelta, params: SupportsKeysAndGetItem[str, str] = {}) -> None: ... + def to_ical(self) -> bytes: ... + @staticmethod + def from_ical(ical: str) -> datetime.timedelta: ... + @property + def dt(self) -> datetime.timedelta: ... + +class vPeriod(TimeBase): + params: Parameters + start: datetime.datetime + end: datetime.datetime + by_duration: bool + duration: datetime.timedelta + def __init__(self, per: _PeriodTuple) -> None: ... + def overlaps(self, other: vPeriod) -> bool: ... + def to_ical(self) -> bytes: ... + # Return type is a tuple of vDuration, vPeriod, vDatetime, vDate, or vTime, + # depending on the ical string. If the ical string is formed according to + # the iCalendar specification, this should always return a + # (datetime, datetime) or a (datetime, timedelta) tuple, but this is not + # enforced. + @staticmethod + def from_ical(ical: str, timezone: datetime.timezone | str | None = None) -> tuple[Any, Any]: ... + @property + def dt(self) -> _PeriodTuple: ... + FBTYPE: property + +class vWeekday(str): + __slots__ = ("params", "relative", "weekday") + week_days: Final[CaselessDict[int]] + weekday: Literal["SU", "MO", "TU", "WE", "TH", "FR", "SA"] | None + relative: int | None + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class vFrequency(str): + __slots__ = ("params",) + frequencies: Final[CaselessDict[str]] + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class vMonth(int): + params: Parameters + def __new__(cls, month: vMonth | str | int, params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: vMonth | str | int) -> Self: ... + + @property + def leap(self) -> bool: ... + @leap.setter + def leap(self, value: bool) -> None: ... + +class vSkip(vText, Enum): + OMIT = "OMIT" + FORWARD = "FORWARD" + BACKWARD = "BACKWARD" + + def __reduce_ex__(self, _p: Unused) -> tuple[Self, tuple[str]]: ... + +# The type of the values depend on the key. Each key maps to a v* class, and +# the allowed types are the types that the corresponding v* class can parse. +class vRecur(CaselessDict[Iterable[Any] | Any]): + params: Parameters + frequencies: Final[list[str]] + canonical_order: ClassVar[tuple[str, ...]] + types: Final[CaselessDict[_PropType]] + def __init__( + self, *args, params: SupportsKeysAndGetItem[str, str] = {}, **kwargs: list[Any] | tuple[Any, ...] | Any + ) -> None: ... + def to_ical(self) -> bytes: ... + @classmethod + def parse_type(cls, key: str, values: str) -> list[Any]: ... # Returns a list of v* objects + @classmethod + def from_ical(cls, ical: vRecur | str) -> Self: ... + +class vTime(TimeBase): + dt: datetime.time | datetime.datetime + params: Parameters + + @overload + def __init__(self, dt: datetime.time | datetime.datetime, /) -> None: ... + # args are passed to the datetime.time() constructor + @overload + def __init__( + self, + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + tzinfo: datetime.tzinfo | None = ..., + /, + ) -> None: ... + + def to_ical(self) -> str: ... + @staticmethod + def from_ical(ical: ICAL_TYPE) -> datetime.time: ... + +class vUri(str): + __slots__ = ("params",) + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class vGeo: + latitude: float + longitude: float + params: Parameters + def __init__(self, geo: tuple[float | str, float | str], params: SupportsKeysAndGetItem[str, str] = {}) -> None: ... + def to_ical(self) -> str: ... + @staticmethod + def from_ical(ical: str) -> tuple[float, float]: ... + def __eq__(self, other: _vType) -> bool: ... # type: ignore[override] + +class vUTCOffset: + ignore_exceptions: bool + td: datetime.timedelta + params: Parameters + def __init__(self, td: datetime.timedelta, params: SupportsKeysAndGetItem[str, str] = {}) -> None: ... + def to_ical(self) -> str: ... + @classmethod + def from_ical(cls, ical: Self | ICAL_TYPE) -> datetime.timedelta: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +class vInline(str): + __slots__ = ("params",) + params: Parameters + def __new__(cls, value: ICAL_TYPE, encoding: str = "utf-8", params: SupportsKeysAndGetItem[str, str] = {}) -> Self: ... + def to_ical(self) -> bytes: ... + @classmethod + def from_ical(cls, ical: ICAL_TYPE) -> Self: ... + +class TypesFactory(CaselessDict[_PropType]): + all_types: tuple[_PropType, ...] + types_map: CaselessDict[str] + def for_property(self, name: str) -> _PropType: ... + # value is str | bytes, depending on what the v* class supports + def to_ical(self, name: str, value: Any) -> bytes: ... + # value and return type depend on what the v* class supports + def from_ical(self, name: str, value: Any) -> Any: ... diff --git a/stubs/icalendar/icalendar/timezone/__init__.pyi b/stubs/icalendar/icalendar/timezone/__init__.pyi new file mode 100644 index 000000000000..4cd6dade83ae --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/__init__.pyi @@ -0,0 +1,9 @@ +from ..timezone.tzp import TZP as TZP # to prevent "tzp" from being defined here +from .tzid import tzid_from_dt as tzid_from_dt, tzid_from_tzinfo as tzid_from_tzinfo, tzids_from_tzinfo as tzids_from_tzinfo + +__all__ = ["TZP", "tzp", "use_pytz", "use_zoneinfo", "tzid_from_tzinfo", "tzid_from_dt", "tzids_from_tzinfo"] + +tzp: TZP + +def use_pytz() -> None: ... +def use_zoneinfo() -> None: ... diff --git a/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids.pyi b/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids.pyi new file mode 100644 index 000000000000..f07cf5d17bdc --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids.pyi @@ -0,0 +1,13 @@ +import datetime +from collections.abc import Callable +from typing import Final + +__all__ = ["main"] + +START: Final[datetime.datetime] +END: Final[datetime.datetime] +DISTANCE_FROM_TIMEZONE_CHANGE: Final[datetime.timedelta] + +DTS: Final[list[datetime.datetime]] + +def main(create_timezones: list[Callable[[str], datetime.tzinfo]], name: str) -> None: ... diff --git a/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids_result.pyi b/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids_result.pyi new file mode 100644 index 000000000000..db990d137ae2 --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/equivalent_timezone_ids_result.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete +from typing import Final + +__all__ = ["lookup"] + +lookup: Final[Incomplete] diff --git a/stubs/icalendar/icalendar/timezone/provider.pyi b/stubs/icalendar/icalendar/timezone/provider.pyi new file mode 100644 index 000000000000..53a17a88579a --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/provider.pyi @@ -0,0 +1,29 @@ +__all__ = ["TZProvider"] + +import datetime +from abc import ABC, abstractmethod + +from dateutil.rrule import rrule + +from ..prop import vRecur + +class TZProvider(ABC): + @property + @abstractmethod + def name(self) -> str: ... + @abstractmethod + def localize_utc(self, dt: datetime.datetime) -> datetime.datetime: ... + @abstractmethod + def localize(self, dt: datetime.datetime, tz: datetime.tzinfo) -> datetime.datetime: ... + @abstractmethod + def knows_timezone_id(self, id: str) -> bool: ... + @abstractmethod + def fix_rrule_until(self, rrule: rrule, ical_rrule: vRecur) -> None: ... + @abstractmethod + def create_timezone(self, name: str, transition_times, transition_info) -> datetime.tzinfo: ... + @abstractmethod + def timezone(self, name: str) -> datetime.tzinfo | None: ... + @abstractmethod + def uses_pytz(self) -> bool: ... + @abstractmethod + def uses_zoneinfo(self) -> bool: ... diff --git a/stubs/icalendar/icalendar/timezone/pytz.pyi b/stubs/icalendar/icalendar/timezone/pytz.pyi new file mode 100644 index 000000000000..6c3373a86403 --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/pytz.pyi @@ -0,0 +1,22 @@ +__all__ = ["PYTZ"] + +import datetime +from typing import Literal + +from dateutil.rrule import rrule + +from ..cal import Timezone +from ..prop import vRecur +from .provider import TZProvider + +class PYTZ(TZProvider): + @property + def name(self) -> Literal["pytz"]: ... + def localize_utc(self, dt: datetime.datetime) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, tz: datetime.tzinfo) -> datetime.datetime: ... + def knows_timezone_id(self, id: str) -> bool: ... + def fix_rrule_until(self, rrule: rrule, ical_rrule: vRecur) -> None: ... + def create_timezone(self, tz: Timezone) -> datetime.tzinfo: ... # type: ignore[override] + def timezone(self, name: str) -> datetime.tzinfo | None: ... + def uses_pytz(self) -> bool: ... + def uses_zoneinfo(self) -> bool: ... diff --git a/stubs/icalendar/icalendar/timezone/tzid.pyi b/stubs/icalendar/icalendar/timezone/tzid.pyi new file mode 100644 index 000000000000..1e5b884c9c93 --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/tzid.pyi @@ -0,0 +1,7 @@ +import datetime + +__all__ = ["tzid_from_tzinfo", "tzid_from_dt", "tzids_from_tzinfo"] + +def tzids_from_tzinfo(tzinfo: datetime.tzinfo | None) -> tuple[str, ...]: ... +def tzid_from_tzinfo(tzinfo: datetime.tzinfo | None) -> str | None: ... +def tzid_from_dt(dt: datetime.datetime) -> str | None: ... diff --git a/stubs/icalendar/icalendar/timezone/tzp.pyi b/stubs/icalendar/icalendar/timezone/tzp.pyi new file mode 100644 index 000000000000..269bdf742af9 --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/tzp.pyi @@ -0,0 +1,30 @@ +import datetime +from typing import Final + +from dateutil.rrule import rrule + +from ..cal import Timezone +from ..prop import vRecur +from .provider import TZProvider + +__all__ = ["TZP"] + +DEFAULT_TIMEZONE_PROVIDER: Final = "zoneinfo" + +class TZP: + def __init__(self, provider: str | TZProvider = "zoneinfo") -> None: ... + def use_pytz(self) -> None: ... + def use_zoneinfo(self) -> None: ... + def use(self, provider: str | TZProvider) -> None: ... + def use_default(self) -> None: ... + def localize_utc(self, dt: datetime.date) -> datetime.datetime: ... + def localize(self, dt: datetime.date, tz: datetime.tzinfo | str) -> datetime.datetime: ... + def cache_timezone_component(self, timezone_component: Timezone) -> None: ... + def fix_rrule_until(self, rrule: rrule, ical_rrule: vRecur) -> None: ... + def create_timezone(self, timezone_component: Timezone) -> datetime.tzinfo: ... + def clean_timezone_id(self, tzid: str) -> str: ... + def timezone(self, tz_id: str) -> datetime.tzinfo | None: ... + def uses_pytz(self) -> bool: ... + def uses_zoneinfo(self) -> bool: ... + @property + def name(self) -> str: ... diff --git a/stubs/icalendar/icalendar/timezone/windows_to_olson.pyi b/stubs/icalendar/icalendar/timezone/windows_to_olson.pyi new file mode 100644 index 000000000000..7b8e1e881fb6 --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/windows_to_olson.pyi @@ -0,0 +1,3 @@ +from typing import Final + +WINDOWS_TO_OLSON: Final[dict[str, str]] diff --git a/stubs/icalendar/icalendar/timezone/zoneinfo.pyi b/stubs/icalendar/icalendar/timezone/zoneinfo.pyi new file mode 100644 index 000000000000..6891652c89ce --- /dev/null +++ b/stubs/icalendar/icalendar/timezone/zoneinfo.pyi @@ -0,0 +1,24 @@ +import datetime +from typing import Final, Literal +from zoneinfo import ZoneInfo + +from dateutil.rrule import rrule + +from ..cal import Timezone +from ..prop import vRecur +from .provider import TZProvider + +__all__ = ["ZONEINFO"] + +class ZONEINFO(TZProvider): + @property + def name(self) -> Literal["zoneinfo"]: ... + utc: Final[ZoneInfo] + def localize(self, dt: datetime.datetime, tz: ZoneInfo) -> datetime.datetime: ... # type: ignore[override] + def localize_utc(self, dt: datetime.datetime) -> datetime.datetime: ... + def timezone(self, name: str) -> datetime.tzinfo | None: ... + def knows_timezone_id(self, id: str) -> bool: ... + def fix_rrule_until(self, rrule: rrule, ical_rrule: vRecur) -> None: ... + def create_timezone(self, tz: Timezone) -> datetime.tzinfo: ... # type: ignore[override] + def uses_pytz(self) -> Literal[False]: ... + def uses_zoneinfo(self) -> Literal[True]: ... diff --git a/stubs/icalendar/icalendar/tools.pyi b/stubs/icalendar/icalendar/tools.pyi new file mode 100644 index 000000000000..b5d7c82d16bc --- /dev/null +++ b/stubs/icalendar/icalendar/tools.pyi @@ -0,0 +1,25 @@ +import datetime +from typing import Final, TypeGuard +from typing_extensions import TypeIs, deprecated + +from pytz.tzinfo import BaseTzInfo + +from .prop import vText + +__all__ = ["UIDGenerator", "is_date", "is_datetime", "to_datetime", "is_pytz", "is_pytz_dt", "normalize_pytz"] + +class UIDGenerator: + chars: Final[list[str]] + @staticmethod + @deprecated("Use the Python standard library's :func:`uuid.uuid4` instead.") + def rnd_string(length: int = 16) -> str: ... + @staticmethod + @deprecated("Use the Python standard library's :func:`uuid.uuid5` instead.") + def uid(host_name: str = "example.com", unique: str = "") -> vText: ... + +def is_date(dt: datetime.date) -> bool: ... # and not datetime.date +def is_datetime(dt: datetime.date) -> TypeIs[datetime.datetime]: ... +def to_datetime(dt: datetime.date) -> datetime.datetime: ... +def is_pytz(tz: datetime.tzinfo) -> TypeIs[BaseTzInfo]: ... +def is_pytz_dt(dt: datetime.date) -> TypeGuard[datetime.datetime]: ... # and dt.tzinfo is BaseTZInfo +def normalize_pytz(dt: datetime.date) -> datetime.datetime: ... diff --git a/stubs/icalendar/icalendar/version.pyi b/stubs/icalendar/icalendar/version.pyi new file mode 100644 index 000000000000..35b1799741e9 --- /dev/null +++ b/stubs/icalendar/icalendar/version.pyi @@ -0,0 +1,8 @@ +__all__ = ["__version__", "version", "__version_tuple__", "version_tuple"] + +from typing import Final + +__version__: Final[str] +__version_tuple__: Final[tuple[int, ...]] +version: Final[str] +version_tuple: Final[tuple[int, ...]] diff --git a/stubs/inifile/@tests/stubtest_allowlist.txt b/stubs/inifile/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f94f1cf123df --- /dev/null +++ b/stubs/inifile/@tests/stubtest_allowlist.txt @@ -0,0 +1,24 @@ +# These are internal use and python 2 compatibility variables and functions +inifile.PY2 +inifile.WIN +inifile.integer_types +inifile.iter_from_file +inifile.iteritems +inifile.reraise +inifile.string_types +inifile.text_type + +# Attributes that should be treated as read-only and thus are annotated +# with @property +inifile.Dialect.ns_sep +inifile.Dialect.kv_sep +inifile.Dialect.quotes +inifile.Dialect.true +inifile.Dialect.false +inifile.Dialect.comments +inifile.Dialect.allow_escaping +inifile.Dialect.linesep +inifile.IniData.dialect +inifile.IniFile.filename +inifile.IniFile.encoding +inifile.IniFile.is_new diff --git a/stubs/inifile/METADATA.toml b/stubs/inifile/METADATA.toml new file mode 100644 index 000000000000..5532296509e6 --- /dev/null +++ b/stubs/inifile/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/mitsuhiko/python-inifile" diff --git a/stubs/inifile/inifile.pyi b/stubs/inifile/inifile.pyi new file mode 100644 index 000000000000..db23bc4e06ce --- /dev/null +++ b/stubs/inifile/inifile.pyi @@ -0,0 +1,138 @@ +from _typeshed import StrPath, SupportsKeysAndGetItem +from collections.abc import Container, Iterable, Iterator, Mapping, MutableMapping, Sequence +from typing import Literal, TypeAlias, TypeVar, overload +from uuid import UUID + +_T = TypeVar("_T") + +_Token: TypeAlias = ( + tuple[Literal["EMPTY"], str, None] + | tuple[Literal["COMMENT"], str, None] + | tuple[Literal["SECTION"], str, tuple[str, ...]] + | tuple[Literal["KV"], str, tuple[str, str, str]] +) + +def get_app_dir(app_name: str, roaming: bool = ..., force_posix: bool = ...) -> str: ... + +class Dialect: + def __init__( + self, + ns_sep: str = ..., + kv_sep: str = ..., + quotes: Sequence[str] = ..., + true: Sequence[str] = ..., + false: Sequence[str] = ..., + comments: Container[str] = ..., + allow_escaping: bool = ..., + linesep: str | None = ..., + ) -> None: ... + @property + def ns_sep(self) -> str: ... + @property + def kv_sep(self) -> str: ... + @property + def quotes(self) -> Sequence[str]: ... + @property + def true(self) -> Sequence[str]: ... + @property + def false(self) -> Sequence[str]: ... + @property + def comments(self) -> Container[str]: ... + @property + def allow_escaping(self) -> bool: ... + @property + def linesep(self) -> str | None: ... + def get_actual_linesep(self) -> str: ... + def get_strippable_lineseps(self) -> str: ... + def kv_serialize(self, key: str, val: str | None) -> str | None: ... + def escape(self, value: str, quote: str | None = ...) -> str: ... + def unescape(self, value: str) -> str: ... + def to_string(self, value: bool | float | str) -> str: ... + def dict_from_iterable(self, iterable: Iterable[str]) -> MutableMapping[str, str]: ... + def tokenize(self, iterable: Iterable[str]) -> Iterator[_Token]: ... + def update_tokens( + self, old_tokens: Iterable[_Token], changes: SupportsKeysAndGetItem[str, str] | Iterable[tuple[str, str]] + ) -> list[_Token]: ... + +default_dialect: Dialect + +class IniData(MutableMapping[str, str]): + def __init__(self, mapping: Mapping[str, str] | None = ..., dialect: Dialect | None = ...) -> None: ... + @property + def dialect(self) -> Dialect: ... + @property + def is_dirty(self) -> bool: ... + def get_updated_lines(self, line_iter: Iterable[_Token] | None = ...) -> list[_Token]: ... + def discard(self) -> None: ... + def rollover(self) -> None: ... + def to_dict(self) -> dict[str, str]: ... + def __len__(self) -> int: ... + + @overload + def get(self, name: str, default: None = None) -> str | None: ... + @overload + def get(self, name: str, default: str) -> str: ... + @overload + def get(self, name: str, default: _T) -> str | _T: ... + + @overload + def get_ascii(self, name: str) -> str | None: ... + @overload + def get_ascii(self, name: str, default: _T) -> str | _T: ... + + @overload + def get_bool(self, name: str) -> bool: ... + @overload + def get_bool(self, name: str, default: _T) -> bool | _T: ... + + @overload + def get_int(self, name: str) -> int | None: ... + @overload + def get_int(self, name: str, default: _T = ...) -> int | _T: ... + + @overload + def get_float(self, name: str) -> float | None: ... + @overload + def get_float(self, name: str, default: _T) -> float | _T: ... + + @overload + def get_uuid(self, name: str) -> UUID | None: ... + @overload + def get_uuid(self, name: str, default: _T) -> UUID | _T: ... + + def itersections(self) -> Iterator[str]: ... + def sections(self) -> Iterator[str]: ... + def iteritems(self) -> Iterator[tuple[str, str]]: ... + def iterkeys(self) -> Iterator[str]: ... + def itervalues(self) -> Iterator[str]: ... + # NB: keys, items, values currently return a generator, which is + # incompatible with the views returned by Mappings + def items(self) -> Iterator[tuple[str, str]]: ... # type: ignore[override] + def keys(self) -> Iterator[str]: ... # type: ignore[override] + def __iter__(self) -> Iterator[str]: ... + def values(self) -> Iterator[str]: ... # type: ignore[override] + def section_as_dict(self, section: str) -> dict[str, str]: ... + def __getitem__(self, name: str) -> str: ... + def __setitem__(self, name: str, value: str) -> None: ... + def __delitem__(self, name: str) -> None: ... + +class IniFile(IniData): + def __init__(self, filename: StrPath, encoding: str | None = ..., dialect: Dialect | None = ...) -> None: ... + @property + def filename(self) -> str: ... + @property + def encoding(self) -> str | None: ... + @property + def is_new(self) -> bool: ... + def save(self, create_folder: bool = ...) -> None: ... + +class AppIniFile(IniFile): + def __init__( + self, + app_name: str, + filename: StrPath, + roaming: bool = ..., + force_posix: bool = ..., + encoding: str | None = ..., + dialect: Dialect | None = ..., + ) -> None: ... diff --git a/stubs/jmespath/METADATA.toml b/stubs/jmespath/METADATA.toml new file mode 100644 index 000000000000..856988fbacb3 --- /dev/null +++ b/stubs/jmespath/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/jmespath/jmespath.py" diff --git a/stubs/jmespath/jmespath/__init__.pyi b/stubs/jmespath/jmespath/__init__.pyi new file mode 100644 index 000000000000..f653d3f499a9 --- /dev/null +++ b/stubs/jmespath/jmespath/__init__.pyi @@ -0,0 +1,9 @@ +from typing import Any, Final + +from jmespath import parser as parser +from jmespath.visitor import Options as Options + +__version__: Final[str] + +def compile(expression: str) -> parser.ParsedResult: ... +def search(expression: str, data: Any, options: Options | None = None) -> Any: ... diff --git a/stubs/jmespath/jmespath/ast.pyi b/stubs/jmespath/jmespath/ast.pyi new file mode 100644 index 000000000000..53d718e084a0 --- /dev/null +++ b/stubs/jmespath/jmespath/ast.pyi @@ -0,0 +1,56 @@ +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +_NodeType: TypeAlias = Literal[ + "comparator", + "current", + "expref", + "function_expression", + "field", + "filter_projection", + "flatten", + "identity", + "index", + "index_expression", + "key_val_pair", + "literal", + "multi_select_dict", + "multi_select_list", + "or_expression", + "and_expression", + "not_expression", + "pipe", + "projection", + "subexpression", + "slice", + "value_projection", +] + +@type_check_only +class _ASTNode(TypedDict): + type: _NodeType + children: list[_ASTNode] + value: NotRequired[str] + +def comparator(name: str, first: _ASTNode, second: _ASTNode) -> _ASTNode: ... +def current_node() -> _ASTNode: ... +def expref(expression: _ASTNode) -> _ASTNode: ... +def function_expression(name: str, args: list[_ASTNode]) -> _ASTNode: ... +def field(name: str) -> _ASTNode: ... +def filter_projection(left: _ASTNode, right: _ASTNode, comparator: _ASTNode) -> _ASTNode: ... +def flatten(node: _ASTNode) -> _ASTNode: ... +def identity() -> _ASTNode: ... +def index(index: str) -> _ASTNode: ... +def index_expression(children: list[_ASTNode]) -> _ASTNode: ... +def key_val_pair(key_name: str, node: _ASTNode) -> _ASTNode: ... +def literal(literal_value: str) -> _ASTNode: ... +def multi_select_dict(nodes: list[_ASTNode]) -> _ASTNode: ... +def multi_select_list(nodes: list[_ASTNode]) -> _ASTNode: ... +def or_expression(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def and_expression(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def not_expression(expr: _ASTNode) -> _ASTNode: ... +def pipe(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def projection(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... +def subexpression(children: list[_ASTNode]) -> _ASTNode: ... +def slice(start: _ASTNode, end: _ASTNode, step: _ASTNode) -> _ASTNode: ... +def value_projection(left: _ASTNode, right: _ASTNode) -> _ASTNode: ... diff --git a/stubs/jmespath/jmespath/compat.pyi b/stubs/jmespath/jmespath/compat.pyi new file mode 100644 index 000000000000..771f0e5c3e50 --- /dev/null +++ b/stubs/jmespath/jmespath/compat.pyi @@ -0,0 +1,13 @@ +from collections.abc import Generator +from itertools import zip_longest as zip_longest +from types import FunctionType +from typing import TypeVar + +_T = TypeVar("_T") + +text_type = str +string_type = str + +def with_str_method(cls: _T) -> _T: ... +def with_repr_method(cls: _T) -> _T: ... +def get_methods(cls: object) -> Generator[tuple[str, FunctionType]]: ... diff --git a/stubs/jmespath/jmespath/exceptions.pyi b/stubs/jmespath/jmespath/exceptions.pyi new file mode 100644 index 000000000000..45a6c4ec514e --- /dev/null +++ b/stubs/jmespath/jmespath/exceptions.pyi @@ -0,0 +1,47 @@ +from collections.abc import Sequence +from typing import Any + +class JMESPathError(ValueError): ... + +class ParseError(JMESPathError): + lex_position: int + token_value: str + token_type: str + msg: str + expression: str | None + def __init__( + self, lex_position: int, token_value: str, token_type: str, msg: str = "Invalid jmespath expression" + ) -> None: ... + +class IncompleteExpressionError(ParseError): + # When ParseError is used directly, the token always have a non-null value and type + token_value: str | None # type: ignore[assignment] + token_type: str | None # type: ignore[assignment] + expression: str + def set_expression(self, expression: str) -> None: ... + +class LexerError(ParseError): + lexer_position: int + lexer_value: str + message: str + def __init__(self, lexer_position: int, lexer_value: str, message: str, expression: str | None = None) -> None: ... + +class ArityError(ParseError): + expected_arity: int + actual_arity: int + function_name: str + def __init__(self, expected: int, actual: int, name: str) -> None: ... + +class VariadictArityError(ArityError): ... + +class JMESPathTypeError(JMESPathError): + function_name: str + current_value: Any + actual_type: str + expected_types: Sequence[str] + def __init__(self, function_name: str, current_value: Any, actual_type: str, expected_types: Sequence[str]) -> None: ... + +class EmptyExpressionError(JMESPathError): + def __init__(self) -> None: ... + +class UnknownFunctionError(JMESPathError): ... diff --git a/stubs/jmespath/jmespath/functions.pyi b/stubs/jmespath/jmespath/functions.pyi new file mode 100644 index 000000000000..4d657f4c49ea --- /dev/null +++ b/stubs/jmespath/jmespath/functions.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable, Iterable +from typing import Any, TypedDict, TypeVar, type_check_only +from typing_extensions import NotRequired + +TYPES_MAP: dict[str, str] +REVERSE_TYPES_MAP: dict[str, tuple[str, ...]] + +@type_check_only +class _Signature(TypedDict): + types: list[str] + variadic: NotRequired[bool] + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def signature(*arguments: _Signature) -> Callable[[_F], _F]: ... + +class FunctionRegistry(type): + def __init__(cls, name: str, bases: tuple[type, ...], attrs: dict[str, Any]) -> None: ... + +class Functions(metaclass=FunctionRegistry): + FUNCTION_TABLE: Any + # resolved_args and return value are the *args and return of a function called by name + def call_function(self, function_name: str, resolved_args: Iterable[Any]) -> Any: ... diff --git a/stubs/jmespath/jmespath/lexer.pyi b/stubs/jmespath/jmespath/lexer.pyi new file mode 100644 index 000000000000..0e26ebc18888 --- /dev/null +++ b/stubs/jmespath/jmespath/lexer.pyi @@ -0,0 +1,19 @@ +from collections.abc import Iterator +from typing import ClassVar, TypedDict, type_check_only + +from jmespath.exceptions import EmptyExpressionError as EmptyExpressionError, LexerError as LexerError + +@type_check_only +class _LexerTokenizeResult(TypedDict): + type: str + value: str + start: int + end: int + +class Lexer: + START_IDENTIFIER: ClassVar[set[str]] + VALID_IDENTIFIER: ClassVar[set[str]] + VALID_NUMBER: ClassVar[set[str]] + WHITESPACE: ClassVar[set[str]] + SIMPLE_TOKENS: ClassVar[dict[str, str]] + def tokenize(self, expression: str) -> Iterator[_LexerTokenizeResult]: ... diff --git a/stubs/jmespath/jmespath/parser.pyi b/stubs/jmespath/jmespath/parser.pyi new file mode 100644 index 000000000000..fc3c7aa9d2be --- /dev/null +++ b/stubs/jmespath/jmespath/parser.pyi @@ -0,0 +1,19 @@ +from collections.abc import Iterator +from typing import Any, ClassVar + +from jmespath.lexer import _LexerTokenizeResult +from jmespath.visitor import Options, _TreeNode + +class Parser: + BINDING_POWER: ClassVar[dict[str, int]] + tokenizer: Iterator[_LexerTokenizeResult] | None + def __init__(self, lookahead: int = 2) -> None: ... + def parse(self, expression: str) -> ParsedResult: ... + @classmethod + def purge(cls) -> None: ... + +class ParsedResult: + expression: str + parsed: _TreeNode + def __init__(self, expression: str, parsed: _TreeNode) -> None: ... + def search(self, value: Any, options: Options | None = None) -> Any: ... diff --git a/stubs/jmespath/jmespath/visitor.pyi b/stubs/jmespath/jmespath/visitor.pyi new file mode 100644 index 000000000000..9c5da94684d5 --- /dev/null +++ b/stubs/jmespath/jmespath/visitor.pyi @@ -0,0 +1,67 @@ +from _typeshed import Unused +from collections.abc import Callable, MutableMapping +from typing import Any, ClassVar, TypedDict, TypeVar, type_check_only +from typing_extensions import Never + +from jmespath.functions import Functions + +_T = TypeVar("_T") + +class Options: + dict_cls: Callable[[], MutableMapping[Any, Any]] | None + custom_functions: Functions | None + def __init__( + self, dict_cls: Callable[[], MutableMapping[Any, Any]] | None = None, custom_functions: Functions | None = None + ) -> None: ... + +class _Expression: + expression: str + interpreter: Visitor + def __init__(self, expression: str, interpreter: Visitor) -> None: ... + # `args` and `kwargs` are passed to the appropriate `visit_*` method. + def visit(self, node: _TreeNode, *args: Any, **kwargs: Any) -> Any: ... + +class Visitor: + def __init__(self) -> None: ... + # `args` and `kwargs` are passed to the appropriate `visit_*` method. + # Its return value is returned from visit. + def visit(self, node: _TreeNode, *args: Any, **kwargs: Any) -> Any: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... + +@type_check_only +class _TreeNode(TypedDict): + type: str + value: Any + children: list[_TreeNode] + +class TreeInterpreter(Visitor): + COMPARATOR_FUNC: ClassVar[dict[str, Callable[[Any, Any], Any]]] + MAP_TYPE: ClassVar[Callable[[], MutableMapping[Any, Any]]] + def __init__(self, options: Options | None = None) -> None: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... + def visit_subexpression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_field(self, node: _TreeNode, value: Any) -> Any: ... + def visit_comparator(self, node: _TreeNode, value: Any) -> Any: ... + def visit_current(self, node: _TreeNode, value: _T) -> _T: ... + def visit_expref(self, node: _TreeNode, value: Any) -> _Expression: ... + def visit_function_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_filter_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_flatten(self, node: _TreeNode, value: Any) -> Any: ... + def visit_identity(self, node: _TreeNode, value: _T) -> _T: ... + def visit_index(self, node: _TreeNode, value: Any) -> Any: ... + def visit_index_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_slice(self, node: _TreeNode, value: Any) -> Any: ... + def visit_key_val_pair(self, node: _TreeNode, value: Any) -> Any: ... + def visit_literal(self, node: _TreeNode, value: Any) -> Any: ... + def visit_multi_select_dict(self, node: _TreeNode, value: Any) -> Any: ... + def visit_multi_select_list(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_or_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_and_expression(self, node: _TreeNode, value: Any) -> Any: ... + def visit_not_expression(self, node: _TreeNode, value: Any) -> bool: ... + def visit_pipe(self, node: _TreeNode, value: Any) -> Any: ... + def visit_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + def visit_value_projection(self, node: _TreeNode, value: Any) -> list[Any] | None: ... + +class GraphvizVisitor(Visitor): + def __init__(self) -> None: ... + def visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> str: ... diff --git a/stubs/jsonnet/METADATA.toml b/stubs/jsonnet/METADATA.toml new file mode 100644 index 000000000000..60c7cdd7f4e4 --- /dev/null +++ b/stubs/jsonnet/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.22.*" +upstream-repository = "https://github.com/google/jsonnet" diff --git a/stubs/jsonnet/_jsonnet.pyi b/stubs/jsonnet/_jsonnet.pyi new file mode 100644 index 000000000000..cad86c28b9d1 --- /dev/null +++ b/stubs/jsonnet/_jsonnet.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from typing import Final + +# Gleaned from https://github.com/google/jsonnet/blob/master/python/_jsonnet.c +version: Final[str] + +def evaluate_file( + filename: str, + jpathdir: str | list[str] | None = ..., + max_stack: int = 500, + gc_min_objects: int = 1000, + gc_growth_trigger: float = 2, + ext_vars: dict[str, str] | None = ..., + ext_codes: dict[str, str] | None = ..., + tla_vars: dict[str, str] | None = ..., + tla_codes: dict[str, str] | None = ..., + max_trace: int = 20, + import_callback: Callable[[str, str], tuple[str, object | None]] = ..., + native_callbacks: dict[str, tuple[tuple[str, ...], Callable[..., object]]] | None = ..., +) -> str: ... +def evaluate_snippet( + filename: str, + src: str, + jpathdir: str | list[str] | None = ..., + max_stack: int = 500, + gc_min_objects: int = 1000, + gc_growth_trigger: float = 2, + ext_vars: dict[str, str] | None = ..., + ext_codes: dict[str, str] | None = ..., + tla_vars: dict[str, str] | None = ..., + tla_codes: dict[str, str] | None = ..., + max_trace: int = 20, + import_callback: Callable[[str, str], tuple[str, object | None]] = ..., + native_callbacks: dict[str, tuple[tuple[str, ...], Callable[..., object]]] | None = ..., +) -> str: ... diff --git a/stubs/jsonschema/@tests/stubtest_allowlist.txt b/stubs/jsonschema/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0df25c11cc77 --- /dev/null +++ b/stubs/jsonschema/@tests/stubtest_allowlist.txt @@ -0,0 +1,35 @@ +# Testing modules are not included in type stubs: +jsonschema.tests.* +jsonschema.benchmarks.* + +# When importing this module, SystemExit: 2 is thrown: +jsonschema.__main__ + +# Autogenerated methods using @attr.* decorators: +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_post_init__ +.*\.__attrs_props__ +jsonschema._types.TypeChecker.__match_args__ +jsonschema.cli._Outputter.__match_args__ +jsonschema.cli._PlainFormatter.__match_args__ +jsonschema.cli._PrettyFormatter.__match_args__ +jsonschema.exceptions.RefResolutionError.__match_args__ +jsonschema.validators.Draft201909Validator.__match_args__ +jsonschema.validators.Draft202012Validator.__match_args__ +jsonschema.validators.Draft3Validator.__match_args__ +jsonschema.validators.Draft4Validator.__match_args__ +jsonschema.validators.Draft6Validator.__match_args__ +jsonschema.validators.Draft7Validator.__match_args__ +# >= Python 3.13 +jsonschema._types.TypeChecker.__replace__ +jsonschema.cli._Outputter.__replace__ +jsonschema.cli._PlainFormatter.__replace__ +jsonschema.cli._PrettyFormatter.__replace__ +jsonschema.exceptions.RefResolutionError.__replace__ +jsonschema.validators.Draft201909Validator.__replace__ +jsonschema.validators.Draft202012Validator.__replace__ +jsonschema.validators.Draft3Validator.__replace__ +jsonschema.validators.Draft4Validator.__replace__ +jsonschema.validators.Draft6Validator.__replace__ +jsonschema.validators.Draft7Validator.__replace__ diff --git a/stubs/jsonschema/METADATA.toml b/stubs/jsonschema/METADATA.toml new file mode 100644 index 000000000000..a9b3778d2826 --- /dev/null +++ b/stubs/jsonschema/METADATA.toml @@ -0,0 +1,6 @@ +version = "~=4.26.0" +upstream-repository = "https://github.com/python-jsonschema/jsonschema" +dependencies = ["referencing"] + +[tool.stubtest] +extras = ["format"] diff --git a/stubs/jsonschema/jsonschema/__init__.pyi b/stubs/jsonschema/jsonschema/__init__.pyi new file mode 100644 index 000000000000..61cf92fd5d18 --- /dev/null +++ b/stubs/jsonschema/jsonschema/__init__.pyi @@ -0,0 +1,42 @@ +from jsonschema._format import ( + FormatChecker as FormatChecker, + draft3_format_checker as draft3_format_checker, + draft4_format_checker as draft4_format_checker, + draft6_format_checker as draft6_format_checker, + draft7_format_checker as draft7_format_checker, + draft201909_format_checker as draft201909_format_checker, + draft202012_format_checker as draft202012_format_checker, +) +from jsonschema._types import TypeChecker as TypeChecker +from jsonschema.exceptions import ( + ErrorTree as ErrorTree, + FormatError as FormatError, + RefResolutionError as RefResolutionError, + SchemaError as SchemaError, + ValidationError as ValidationError, +) +from jsonschema.protocols import Validator as Validator +from jsonschema.validators import ( + Draft3Validator as Draft3Validator, + Draft4Validator as Draft4Validator, + Draft6Validator as Draft6Validator, + Draft7Validator as Draft7Validator, + Draft201909Validator as Draft201909Validator, + Draft202012Validator as Draft202012Validator, + RefResolver as RefResolver, + validate as validate, +) + +__all__ = [ + "Draft3Validator", + "Draft4Validator", + "Draft6Validator", + "Draft7Validator", + "Draft201909Validator", + "Draft202012Validator", + "FormatChecker", + "SchemaError", + "TypeChecker", + "ValidationError", + "validate", +] diff --git a/stubs/jsonschema/jsonschema/_format.pyi b/stubs/jsonschema/jsonschema/_format.pyi new file mode 100644 index 000000000000..9204059bee6d --- /dev/null +++ b/stubs/jsonschema/jsonschema/_format.pyi @@ -0,0 +1,48 @@ +from collections.abc import Callable, Iterable +from typing import TypeAlias, TypeVar + +_FormatCheckCallable: TypeAlias = Callable[[object], bool] +_F = TypeVar("_F", bound=_FormatCheckCallable) +_RaisesType: TypeAlias = type[Exception] | tuple[type[Exception], ...] + +class FormatChecker: + checkers: dict[str, tuple[_FormatCheckCallable, _RaisesType]] + + def __init__(self, formats: Iterable[str] | None = None) -> None: ... + def checks(self, format: str, raises: _RaisesType = ()) -> Callable[[_F], _F]: ... + @classmethod + def cls_checks(cls, format: str, raises: _RaisesType = ()) -> Callable[[_F], _F]: ... + def check(self, instance: object, format: str) -> None: ... + def conforms(self, instance: object, format: str) -> bool: ... + +draft3_format_checker: FormatChecker +draft4_format_checker: FormatChecker +draft6_format_checker: FormatChecker +draft7_format_checker: FormatChecker +draft201909_format_checker: FormatChecker +draft202012_format_checker: FormatChecker + +def is_email(instance: object) -> bool: ... +def is_ipv4(instance: object) -> bool: ... +def is_ipv6(instance: object) -> bool: ... + +# is_host_name is only defined if fqdn is installed. +def is_host_name(instance: object) -> bool: ... +def is_idn_host_name(instance: object) -> bool: ... +def is_uri(instance: object) -> bool: ... +def is_uri_reference(instance: object) -> bool: ... +def is_iri(instance: object) -> bool: ... +def is_iri_reference(instance: object) -> bool: ... +def is_datetime(instance: object) -> bool: ... +def is_time(instance: object) -> bool: ... +def is_regex(instance: object) -> bool: ... +def is_date(instance: object) -> bool: ... +def is_draft3_time(instance: object) -> bool: ... +def is_css21_color(instance: object) -> bool: ... +def is_json_pointer(instance: object) -> bool: ... +def is_relative_json_pointer(instance: object) -> bool: ... +def is_uri_template(instance: object) -> bool: ... + +# is_duration is only defined if isoduration is installed. +def is_duration(instance: object) -> bool: ... +def is_uuid(instance: object) -> bool: ... diff --git a/stubs/jsonschema/jsonschema/_keywords.pyi b/stubs/jsonschema/jsonschema/_keywords.pyi new file mode 100644 index 000000000000..3d050a93933a --- /dev/null +++ b/stubs/jsonschema/jsonschema/_keywords.pyi @@ -0,0 +1,36 @@ +def patternProperties(validator, patternProperties, instance, schema) -> None: ... +def propertyNames(validator, propertyNames, instance, schema) -> None: ... +def additionalProperties(validator, aP, instance, schema) -> None: ... +def items(validator, items, instance, schema) -> None: ... +def const(validator, const, instance, schema) -> None: ... +def contains(validator, contains, instance, schema) -> None: ... +def exclusiveMinimum(validator, minimum, instance, schema) -> None: ... +def exclusiveMaximum(validator, maximum, instance, schema) -> None: ... +def minimum(validator, minimum, instance, schema) -> None: ... +def maximum(validator, maximum, instance, schema) -> None: ... +def multipleOf(validator, dB, instance, schema) -> None: ... +def minItems(validator, mI, instance, schema) -> None: ... +def maxItems(validator, mI, instance, schema) -> None: ... +def uniqueItems(validator, uI, instance, schema) -> None: ... +def pattern(validator, patrn, instance, schema) -> None: ... +def format(validator, format, instance, schema) -> None: ... +def minLength(validator, mL, instance, schema) -> None: ... +def maxLength(validator, mL, instance, schema) -> None: ... +def dependentRequired(validator, dependentRequired, instance, schema) -> None: ... +def dependentSchemas(validator, dependentSchemas, instance, schema) -> None: ... +def enum(validator, enums, instance, schema) -> None: ... +def ref(validator, ref, instance, schema) -> None: ... +def dynamicRef(validator, dynamicRef, instance, schema) -> None: ... +def type(validator, types, instance, schema) -> None: ... +def properties(validator, properties, instance, schema) -> None: ... +def required(validator, required, instance, schema) -> None: ... +def minProperties(validator, mP, instance, schema) -> None: ... +def maxProperties(validator, mP, instance, schema) -> None: ... +def allOf(validator, allOf, instance, schema) -> None: ... +def anyOf(validator, anyOf, instance, schema) -> None: ... +def oneOf(validator, oneOf, instance, schema) -> None: ... +def not_(validator, not_schema, instance, schema) -> None: ... +def if_(validator, if_schema, instance, schema) -> None: ... +def unevaluatedItems(validator, unevaluatedItems, instance, schema) -> None: ... +def unevaluatedProperties(validator, unevaluatedProperties, instance, schema) -> None: ... +def prefixItems(validator, prefixItems, instance, schema) -> None: ... diff --git a/stubs/jsonschema/jsonschema/_legacy_keywords.pyi b/stubs/jsonschema/jsonschema/_legacy_keywords.pyi new file mode 100644 index 000000000000..e2898f8ed015 --- /dev/null +++ b/stubs/jsonschema/jsonschema/_legacy_keywords.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from collections.abc import ItemsView, Iterator + +from .exceptions import ValidationError + +def ignore_ref_siblings(schema) -> list[tuple[str, Incomplete]] | ItemsView[str, Incomplete]: ... +def dependencies_draft3(validator, dependencies, instance, schema) -> None: ... +def dependencies_draft4_draft6_draft7(validator, dependencies, instance, schema) -> None: ... +def disallow_draft3(validator, disallow, instance, schema) -> None: ... +def extends_draft3(validator, extends, instance, schema) -> None: ... +def items_draft3_draft4(validator, items, instance, schema) -> None: ... +def additionalItems(validator, aI, instance, schema) -> None: ... +def items_draft6_draft7_draft201909(validator, items, instance, schema) -> None: ... +def minimum_draft3_draft4(validator, minimum, instance, schema) -> None: ... +def maximum_draft3_draft4(validator, maximum, instance, schema) -> None: ... +def properties_draft3(validator, properties, instance, schema) -> None: ... +def type_draft3(validator, types, instance, schema) -> None: ... +def contains_draft6_draft7(validator, contains, instance, schema) -> None: ... +def recursiveRef(validator, recursiveRef, instance, schema) -> None: ... +def find_evaluated_item_indexes_by_schema(validator, instance, schema) -> list[int]: ... +def unevaluatedItems_draft2019(validator, unevaluatedItems, instance, schema) -> Iterator[ValidationError]: ... +def find_evaluated_property_keys_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def unevaluatedProperties_draft2019(validator, uP, instance, schema) -> Iterator[ValidationError]: ... diff --git a/stubs/jsonschema/jsonschema/_types.pyi b/stubs/jsonschema/jsonschema/_types.pyi new file mode 100644 index 000000000000..a4fa843f195c --- /dev/null +++ b/stubs/jsonschema/jsonschema/_types.pyi @@ -0,0 +1,27 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable, Mapping +from typing import Literal + +def is_array(checker: Unused, instance: object) -> bool: ... +def is_bool(checker: Unused, instance: object) -> bool: ... +def is_integer(checker: Unused, instance: object) -> bool: ... +def is_null(checker: Unused, instance: object) -> bool: ... +def is_number(checker: Unused, instance: object) -> bool: ... +def is_object(checker: Unused, instance: object) -> bool: ... +def is_string(checker: Unused, instance: object) -> bool: ... +def is_any(checker: Unused, instance: Unused) -> Literal[True]: ... + +class TypeChecker: + __slots__ = ("_type_checkers", "__weakref__") + def __init__(self, type_checkers: Mapping[str, Callable[[object], bool]] = ...) -> None: ... + def is_type(self, instance, type: str) -> bool: ... + def redefine(self, type: str, fn: Callable[..., bool]) -> TypeChecker: ... + def redefine_many(self, definitions=()) -> TypeChecker: ... + def remove(self, *types: Iterable[str]) -> TypeChecker: ... + +draft3_type_checker: TypeChecker +draft4_type_checker: TypeChecker +draft6_type_checker: TypeChecker +draft7_type_checker: TypeChecker +draft201909_type_checker: TypeChecker +draft202012_type_checker: TypeChecker diff --git a/stubs/jsonschema/jsonschema/_typing.pyi b/stubs/jsonschema/jsonschema/_typing.pyi new file mode 100644 index 000000000000..78e946676d79 --- /dev/null +++ b/stubs/jsonschema/jsonschema/_typing.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable, Iterable +from typing import Any, Protocol, TypeAlias + +from jsonschema.protocols import Validator +from referencing.jsonschema import Schema + +class SchemaKeywordValidator(Protocol): + def __call__(self, validator: Validator, value: Any, instance: Any, schema: Schema) -> None: ... + +id_of: TypeAlias = Callable[[Schema], str | None] # noqa: Y042 + +ApplicableValidators: TypeAlias = Callable[[Schema], Iterable[tuple[str, Any]]] diff --git a/stubs/jsonschema/jsonschema/_utils.pyi b/stubs/jsonschema/jsonschema/_utils.pyi new file mode 100644 index 000000000000..cc0a4f062227 --- /dev/null +++ b/stubs/jsonschema/jsonschema/_utils.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete, SupportsNext, SupportsRichComparison +from collections.abc import Generator, Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Literal, TypeVar, overload + +_T = TypeVar("_T") + +class URIDict(MutableMapping[str, MutableMapping[str, Any]]): + def normalize(self, uri: str) -> str: ... + store: dict[str, MutableMapping[str, Any]] + def __init__( + self, + m: Mapping[str, MutableMapping[str, Any]] | Iterable[tuple[str, MutableMapping[str, Any]]], + /, + **kwargs: MutableMapping[str, Any], + ) -> None: ... + def __getitem__(self, uri: str) -> MutableMapping[str, Any]: ... + def __setitem__(self, uri: str, value: MutableMapping[str, Any]) -> None: ... + def __delitem__(self, uri: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class Unset: ... + +def format_as_index(container: str, indices: Iterable[Incomplete] | None) -> str: ... +def find_additional_properties(instance: Iterable[str], schema: Mapping[str, Iterable[str]]) -> Generator[str]: ... +def extras_msg(extras: Iterable[object]) -> tuple[str, Literal["was", "were"]]: ... # elements are passed to the repr() function + +@overload +def ensure_list(thing: str) -> list[str]: ... +@overload +def ensure_list(thing: _T) -> _T: ... + +def equal(one, two) -> bool: ... +def unbool(element, true=..., false=...): ... +def uniq(container: Iterable[SupportsRichComparison]) -> bool: ... +def find_evaluated_item_indexes_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def find_evaluated_property_keys_by_schema(validator, instance, schema) -> list[Incomplete]: ... +def is_valid(errs_it: SupportsNext[object]) -> bool: ... diff --git a/stubs/jsonschema/jsonschema/cli.pyi b/stubs/jsonschema/jsonschema/cli.pyi new file mode 100644 index 000000000000..3d640e236fb6 --- /dev/null +++ b/stubs/jsonschema/jsonschema/cli.pyi @@ -0,0 +1,65 @@ +import argparse +from _typeshed import ExcInfo, FileDescriptorOrPath, Incomplete, OptExcInfo, SupportsWrite +from collections.abc import Mapping, Sequence +from typing import Any +from typing_extensions import Self, deprecated + +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +class _CannotLoadFile(Exception): ... + +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +class _Outputter: + __slots__ = ("_formatter", "_stdout", "_stderr", "__weakref__") + _formatter: _PlainFormatter | _PrettyFormatter + _stdout: SupportsWrite[str] + _stderr: SupportsWrite[str] + + def __init__( + self, formatter: _PlainFormatter | _PrettyFormatter, stdout: SupportsWrite[str], stderr: SupportsWrite[str] + ) -> None: ... + @classmethod + def from_arguments( + cls, arguments: Mapping[str, Incomplete], stdout: SupportsWrite[str], stderr: SupportsWrite[str] + ) -> Self: ... + def load(self, path: FileDescriptorOrPath) -> Any: ... # result of json.load() + def filenotfound_error(self, *, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> None: ... + def parsing_error(self, *, path: FileDescriptorOrPath, exc_info: ExcInfo) -> None: ... + def validation_error(self, *, instance_path: FileDescriptorOrPath, error: BaseException) -> None: ... + def validation_success(self, *, instance_path: FileDescriptorOrPath) -> None: ... + +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +class _PrettyFormatter: + __slots__ = ("__weakref__",) + _ERROR_MSG: str + _SUCCESS_MSG: str + + def __init__(self) -> None: ... + def filenotfound_error(self, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> str: ... + def parsing_error(self, path: FileDescriptorOrPath, exc_info: ExcInfo) -> str: ... + def validation_error(self, instance_path: FileDescriptorOrPath, error: BaseException) -> str: ... + def validation_success(self, instance_path: FileDescriptorOrPath) -> str: ... + +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +class _PlainFormatter: + __slots__ = ("_error_format", "__weakref__") + _error_format: str + + def __init__(self, error_format: str) -> None: ... + def filenotfound_error(self, path: FileDescriptorOrPath, exc_info: OptExcInfo) -> str: ... + def parsing_error(self, path: FileDescriptorOrPath, exc_info: ExcInfo) -> str: ... + def validation_error(self, instance_path: FileDescriptorOrPath, error: BaseException) -> str: ... + def validation_success(self, instance_path: FileDescriptorOrPath) -> str: ... + +parser: argparse.ArgumentParser + +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def parse_args(args: Sequence[str] | None) -> dict[str, Any]: ... # result of vars(argparse.Namespace()) +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def main(args: Sequence[str] = ...) -> None: ... +@deprecated("The jsonschema CLI is deprecated and will be removed in a future version. Please use check-jsonschema instead.") +def run( + arguments: Mapping[str, Incomplete], + stdout: SupportsWrite[str] = ..., + stderr: SupportsWrite[str] = ..., + stdin: SupportsWrite[str] = ..., +) -> int: ... diff --git a/stubs/jsonschema/jsonschema/exceptions.pyi b/stubs/jsonschema/jsonschema/exceptions.pyi new file mode 100644 index 000000000000..937a03e2587a --- /dev/null +++ b/stubs/jsonschema/jsonschema/exceptions.pyi @@ -0,0 +1,91 @@ +from _typeshed import Incomplete, SupportsRichComparison, sentinel +from collections import deque +from collections.abc import Callable, Container, Iterable, Iterator, Mapping, MutableMapping, Sequence +from typing import Any, TypeAlias +from typing_extensions import Self, deprecated + +from ._types import TypeChecker +from ._utils import Unset + +_RelevanceFuncType: TypeAlias = Callable[[ValidationError], SupportsRichComparison] + +WEAK_MATCHES: frozenset[str] +STRONG_MATCHES: frozenset[str] + +class _Error(Exception): + message: str + path: deque[str | int] + relative_path: deque[str | int] + schema_path: deque[str | int] + relative_schema_path: deque[str | int] + context: list[ValidationError] + cause: Exception | None + validator: str | Unset + validator_value: Any | Unset + instance: Any | Unset + schema: Mapping[str, Any] | bool | Unset + parent: _Error | None + def __init__( + self, + message: str, + validator: str | Unset = sentinel, + path: Iterable[str | int] = (), + cause: Exception | None = None, + context: Sequence[ValidationError] = (), + validator_value: Any | Unset = sentinel, + instance: Any | Unset = sentinel, + schema: Mapping[str, Any] | bool | Unset = sentinel, + schema_path: Iterable[str | int] = (), + parent: _Error | None = None, + type_checker: TypeChecker | Unset = sentinel, + ) -> None: ... + @classmethod + def create_from(cls, other: _Error) -> Self: ... + @property + def absolute_path(self) -> Sequence[str | int]: ... + @property + def absolute_schema_path(self) -> Sequence[str | int]: ... + @property + def json_path(self) -> str: ... + # TODO: this type could be made more precise using TypedDict to + # enumerate the types of the members + def _contents(self) -> dict[str, Incomplete]: ... + +class ValidationError(_Error): ... +class SchemaError(_Error): ... + +class RefResolutionError(Exception): + def __init__(self, cause: str) -> None: ... + +class UndefinedTypeCheck(Exception): + type: Incomplete + def __init__(self, type) -> None: ... + +class UnknownType(Exception): + type: Incomplete + instance: Incomplete + schema: Incomplete + def __init__(self, type, instance, schema) -> None: ... + +class FormatError(Exception): + message: Incomplete + cause: Incomplete + def __init__(self, message, cause=None) -> None: ... + +class ErrorTree: + errors: MutableMapping[str, ValidationError] + def __init__(self, errors: Iterable[ValidationError] = ()) -> None: ... + def __contains__(self, index: object) -> bool: ... + def __getitem__(self, index): ... + @deprecated("ErrorTree.__setitem__ is deprecated without replacement.") + def __setitem__(self, index: str | int, value: ErrorTree) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + @property + def total_errors(self): ... + +def by_relevance(weak: Container[str] = ..., strong: Container[str] = ...) -> _RelevanceFuncType: ... + +relevance: _RelevanceFuncType + +def best_match(errors: Iterable[ValidationError], key: _RelevanceFuncType = ...): ... diff --git a/stubs/jsonschema/jsonschema/protocols.pyi b/stubs/jsonschema/jsonschema/protocols.pyi new file mode 100644 index 000000000000..5fea709eeaaf --- /dev/null +++ b/stubs/jsonschema/jsonschema/protocols.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Iterator, Mapping, Sequence +from typing import Any, ClassVar, Protocol, TypeAlias + +import referencing.jsonschema +from jsonschema._format import FormatChecker +from jsonschema._types import TypeChecker +from jsonschema.exceptions import ValidationError + +_JsonParameter: TypeAlias = str | int | float | bool | None | Mapping[str, _JsonParameter] | Sequence[_JsonParameter] + +class Validator(Protocol): + META_SCHEMA: ClassVar[dict[Incomplete, Incomplete]] + VALIDATORS: ClassVar[dict[Incomplete, Incomplete]] + TYPE_CHECKER: ClassVar[TypeChecker] + FORMAT_CHECKER: ClassVar[FormatChecker] + schema: referencing.jsonschema.Schema + def __init__( + self, + schema: Mapping[Incomplete, Incomplete] | bool, + resolver: Any = None, # deprecated + format_checker: FormatChecker | None = None, + *, + registry: referencing.jsonschema.SchemaRegistry = ..., + ) -> None: ... + @classmethod + def check_schema(cls, schema: dict[Incomplete, Incomplete]) -> None: ... + def is_type(self, instance: _JsonParameter, type: str) -> bool: ... + def is_valid(self, instance: _JsonParameter) -> bool: ... + def iter_errors(self, instance: _JsonParameter) -> Iterator[ValidationError]: ... + def validate(self, instance: _JsonParameter) -> None: ... + def evolve(self, **kwargs) -> Validator: ... diff --git a/stubs/jsonschema/jsonschema/validators.pyi b/stubs/jsonschema/jsonschema/validators.pyi new file mode 100644 index 000000000000..5d5ab49c6333 --- /dev/null +++ b/stubs/jsonschema/jsonschema/validators.pyi @@ -0,0 +1,144 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping +from contextlib import contextmanager +from typing import Any, ClassVar, TypeAlias, overload, type_check_only +from typing_extensions import deprecated + +from referencing.jsonschema import Schema, SchemaRegistry +from referencing.typing import URI + +from ._format import FormatChecker +from ._types import TypeChecker +from ._utils import Unset, URIDict +from .exceptions import ValidationError +from .protocols import Validator + +# these type aliases do not exist at runtime, they're only defined here in the stub +_JsonObject: TypeAlias = Mapping[str, Any] +_JsonValue: TypeAlias = _JsonObject | list[Any] | str | int | float | bool | None +_ValidatorCallback: TypeAlias = Callable[[Any, Any, _JsonValue, _JsonObject], Iterator[ValidationError]] + +# This class does not exist at runtime. Compatible classes are created at +# runtime by create(). +@type_check_only +class _Validator(Validator): + VALIDATORS: ClassVar[dict[Incomplete, Incomplete]] + META_SCHEMA: ClassVar[dict[Incomplete, Incomplete]] + TYPE_CHECKER: ClassVar[Incomplete] + FORMAT_CHECKER: ClassVar[Incomplete] + @staticmethod + def ID_OF(contents: Schema) -> URI | None: ... + schema: Schema + format_checker: FormatChecker | None + def __init__( + self, + schema: Mapping[Incomplete, Incomplete] | bool, + resolver: Any = None, # deprecated + format_checker: FormatChecker | None = None, + *, + registry: SchemaRegistry = ..., + ) -> None: ... + @classmethod + def check_schema(cls, schema: Schema, format_checker: FormatChecker | Unset = ...) -> None: ... + @property + @deprecated( + "Accessing resolver() is deprecated as of v4.18.0, " + "in favor of the https://github.com/python-jsonschema/referencing library." + ) + def resolver(self): ... + def evolve(self, **changes) -> _Validator: ... + + @overload + def iter_errors(self, instance) -> Generator[Incomplete]: ... + @overload + @deprecated("Passing a schema to Validator.iter_errors is deprecated and will be removed in a future release.") + def iter_errors(self, instance, _schema: Schema | None) -> Generator[Incomplete]: ... + + def descend( + self, instance, schema: Schema, path: Incomplete | None = ..., schema_path: Incomplete | None = ..., resolver=None + ) -> Generator[Incomplete]: ... + def validate(self, *args, **kwargs) -> None: ... + def is_type(self, instance, type) -> bool: ... + + @overload + def is_valid(self, instance) -> bool: ... + @overload + @deprecated("Passing a schema to Validator.is_valid is deprecated and will be removed in a future release.") + def is_valid(self, instance, _schema: Schema | None) -> bool: ... + +def validates(version: str) -> Callable[[_Validator], _Validator]: ... +def create( + meta_schema: Schema, + validators: Mapping[str, _ValidatorCallback] | tuple[()] = (), + version=None, + type_checker: TypeChecker = ..., + format_checker: FormatChecker = ..., + id_of: Callable[[Schema], str] = ..., + applicable_validators: Callable[[Schema], Iterable[tuple[str, _ValidatorCallback]]] = ..., +) -> type[_Validator]: ... +def extend(validator, validators=(), version=None, type_checker=None, format_checker=None): ... + +# At runtime these are fields that are assigned the return values of create() calls. +class Draft3Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft4Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft6Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft7Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft201909Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +class Draft202012Validator(_Validator): + __slots__ = ("_validators", "schema", "_ref_resolver", "format_checker", "_registry", "_resolver", "__weakref__") + +_Handler: TypeAlias = Callable[[str], Incomplete] + +@deprecated( + "jsonschema.RefResolver is deprecated as of v4.18.0, in favor of the " + "https://github.com/python-jsonschema/referencing library, which " + "provides more compliant referencing behavior as well as more " + "flexible APIs for customization. A future release will remove " + "RefResolver. Please file a feature request (on referencing) if you " + "are missing an API for the kind of customization you need." +) +class RefResolver: + referrer: dict[str, Incomplete] + cache_remote: Incomplete + handlers: dict[str, _Handler] + store: URIDict + def __init__( + self, + base_uri: str, + referrer: dict[str, Incomplete], + store: Mapping[str, Mapping[str, Any]] | Iterable[tuple[str, Mapping[str, Any]]] = ..., + cache_remote: bool = True, + handlers: SupportsKeysAndGetItem[str, _Handler] | Iterable[tuple[str, _Handler]] = (), + urljoin_cache=None, + remote_cache=None, + ) -> None: ... + @classmethod + def from_schema(cls, schema: Schema, id_of=..., *args, **kwargs): ... + def push_scope(self, scope) -> None: ... + def pop_scope(self) -> None: ... + @property + def resolution_scope(self): ... + @property + def base_uri(self) -> str: ... + @contextmanager + @deprecated("jsonschema.RefResolver.in_scope is deprecated and will be removed in a future release.") + def in_scope(self, scope) -> Generator[None]: ... + @contextmanager + def resolving(self, ref: str) -> Generator[Incomplete]: ... + def resolve(self, ref: str) -> tuple[str, Incomplete]: ... + def resolve_from_url(self, url: str): ... + def resolve_fragment(self, document, fragment: str): ... + def resolve_remote(self, uri: str): ... + +def validate(instance: object, schema: Schema, cls: type[_Validator] | None = None, *args: Any, **kwargs: Any) -> None: ... +def validator_for(schema: Schema | bool, default: type[Validator] | Unset = ...) -> type[Validator]: ... diff --git a/stubs/jwcrypto/@tests/stubtest_allowlist.txt b/stubs/jwcrypto/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b81e7c4baa58 --- /dev/null +++ b/stubs/jwcrypto/@tests/stubtest_allowlist.txt @@ -0,0 +1,9 @@ +# test code does not need type hints +jwcrypto.tests +jwcrypto.tests-cookbook + +# even if the deprecated decorator is applied, the attribute is not present +jwcrypto.jwt.JWTMissingKeyID.__deprecated__ + +# https://github.com/python/mypy/issues/20160 +(jwcrypto.jwt.JWTMissingKeyID.__init_subclass__)? diff --git a/stubs/jwcrypto/METADATA.toml b/stubs/jwcrypto/METADATA.toml new file mode 100644 index 000000000000..746c8c0fb382 --- /dev/null +++ b/stubs/jwcrypto/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.5.8" +upstream-repository = "https://github.com/latchset/jwcrypto" +dependencies = ["cryptography"] diff --git a/stubs/jwcrypto/jwcrypto/__init__.pyi b/stubs/jwcrypto/jwcrypto/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/jwcrypto/jwcrypto/common.pyi b/stubs/jwcrypto/jwcrypto/common.pyi new file mode 100644 index 000000000000..b1361916a804 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/common.pyi @@ -0,0 +1,50 @@ +from collections.abc import Callable, Iterator, MutableMapping +from typing import Any, NamedTuple + +from jwcrypto.jwe import JWE +from jwcrypto.jws import JWS + +def base64url_encode(payload: str | bytes) -> str: ... +def base64url_decode(payload: str) -> bytes: ... +def json_encode(string: str | bytes) -> str: ... + +# The function returns json.loads which returns Any +def json_decode(string: str | bytes) -> Any: ... + +class JWException(Exception): ... + +class InvalidJWAAlgorithm(JWException): + def __init__(self, message: str | None = None) -> None: ... + +class InvalidCEKeyLength(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWEOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWEKeyType(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWEKeyLength(JWException): + def __init__(self, expected: int, obtained: int) -> None: ... + +class InvalidJWSERegOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWKeyNotFound(JWException): + def __init__(self, message: str | None = None) -> None: ... + +class JWSEHeaderParameter(NamedTuple): + description: str + mustprotect: bool + supported: bool + check_fn: Callable[[JWS | JWE], bool] | None + +class JWSEHeaderRegistry(MutableMapping[str, JWSEHeaderParameter]): + def __init__(self, init_registry: dict[str, JWSEHeaderParameter] | None = None) -> None: ... + def check_header(self, h: str, value: JWS | JWE) -> bool: ... + def __getitem__(self, key: str) -> JWSEHeaderParameter: ... + def __iter__(self) -> Iterator[str]: ... + def __delitem__(self, key: str) -> None: ... + def __setitem__(self, h: str, jwse_header_param: JWSEHeaderParameter) -> None: ... + def __len__(self) -> int: ... diff --git a/stubs/jwcrypto/jwcrypto/jwa.pyi b/stubs/jwcrypto/jwcrypto/jwa.pyi new file mode 100644 index 000000000000..e2932812cdcc --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwa.pyi @@ -0,0 +1,36 @@ +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from typing import ClassVar + +default_max_pbkdf2_iterations: int +default_enforce_hmac_key_length: bool + +class JWAAlgorithm(metaclass=ABCMeta): + @property + @abstractmethod + def name(self) -> str: ... + @property + @abstractmethod + def description(self) -> str: ... + @property + @abstractmethod + def keysize(self) -> int: ... + @property + @abstractmethod + def algorithm_usage_location(self) -> str: ... + @property + @abstractmethod + def algorithm_use(self) -> str: ... + @property + def input_keysize(self) -> int: ... + +class JWA: + algorithms_registry: ClassVar[Mapping[str, JWAAlgorithm]] + @classmethod + def instantiate_alg(cls, name: str, use: str | None = None) -> JWAAlgorithm: ... + @classmethod + def signing_alg(cls, name: str) -> JWAAlgorithm: ... + @classmethod + def keymgmt_alg(cls, name: str) -> JWAAlgorithm: ... + @classmethod + def encryption_alg(cls, name: str) -> JWAAlgorithm: ... diff --git a/stubs/jwcrypto/jwcrypto/jwe.pyi b/stubs/jwcrypto/jwcrypto/jwe.pyi new file mode 100644 index 000000000000..6c22794cd5e3 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwe.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import Any +from typing_extensions import LiteralString, Self + +from jwcrypto import common +from jwcrypto.common import JWException, JWSEHeaderParameter, JWSEHeaderRegistry +from jwcrypto.jwk import JWK, JWKSet + +default_max_compressed_size: int +default_max_plaintext_size: int + +JWEHeaderRegistry: dict[LiteralString, JWSEHeaderParameter] + +default_allowed_algs: list[LiteralString] + +class InvalidJWEData(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +InvalidCEKeyLength = common.InvalidCEKeyLength +InvalidJWEKeyLength = common.InvalidJWEKeyLength +InvalidJWEKeyType = common.InvalidJWEKeyType +InvalidJWEOperation = common.InvalidJWEOperation + +class JWE: + objects: dict[str, Any] + plaintext: bytes | None + header_registry: JWSEHeaderRegistry + flattened: bool + cek: Incomplete + decryptlog: list[str] | None + def __init__( + self, + plaintext: str | bytes | None = None, + protected: str | None = None, + unprotected: str | None = None, + aad: bytes | None = None, + algs: list[LiteralString] | None = None, + recipient: str | None = None, + header: str | None = None, + header_registry: ( + SupportsKeysAndGetItem[LiteralString, JWSEHeaderParameter] + | Iterable[tuple[LiteralString, JWSEHeaderParameter]] + | None + ) = None, + flattened: bool = True, + ) -> None: ... + + @property + def allowed_algs(self) -> list[LiteralString]: ... + @allowed_algs.setter + def allowed_algs(self, algs: list[LiteralString]) -> None: ... + + def add_recipient(self, key: JWK, header: dict[str, Any] | str | None = None) -> None: ... + def serialize(self, compact: bool = False) -> str: ... + def decrypt(self, key: JWK | JWKSet, max_plaintext: int = 0) -> None: ... + def deserialize(self, raw_jwe: str | bytes, key: JWK | JWKSet | None = None) -> None: ... + @property + def payload(self) -> bytes: ... + @property + def jose_header(self) -> dict[Incomplete, Incomplete]: ... + @classmethod + def from_jose_token(cls, token: str | bytes) -> Self: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/jwk.pyi b/stubs/jwcrypto/jwcrypto/jwk.pyi new file mode 100644 index 000000000000..5cdd0bcc45ba --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwk.pyi @@ -0,0 +1,278 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from enum import Enum +from typing import Any, Literal, NamedTuple, TypeAlias, TypeVar, overload +from typing_extensions import LiteralString, Self, deprecated + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, rsa +from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey as Ed448PrivateKey, Ed448PublicKey as Ed448PublicKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey as Ed25519PrivateKey, + Ed25519PublicKey as Ed25519PublicKey, +) +from cryptography.hazmat.primitives.asymmetric.x448 import X448PrivateKey as X448PrivateKey, X448PublicKey as X448PublicKey +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey as X25519PrivateKey, + X25519PublicKey as X25519PublicKey, +) +from jwcrypto.common import JWException + +_T = TypeVar("_T") + +class UnimplementedOKPCurveKey: + @classmethod + def generate(cls) -> None: ... + @classmethod + def from_public_bytes(cls, *args) -> None: ... + @classmethod + def from_private_bytes(cls, *args) -> None: ... + +ImplementedOkpCurves: Sequence[str] +priv_bytes: Callable[[bytes], X25519PrivateKey] | None + +class _Ed25519_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _Ed448_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _X25519_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +class _X448_CURVE(NamedTuple): + pubkey: UnimplementedOKPCurveKey + privkey: UnimplementedOKPCurveKey + +_JWKKeyTypeSupported: TypeAlias = Literal["oct", "RSA", "EC", "OKP"] +JWKTypesRegistry: dict[_JWKKeyTypeSupported, str] + +class ParmType(Enum): + name = "A string with a name" # pyright: ignore[reportAssignmentType] + b64 = "Base64url Encoded" + b64u = "Base64urlUint Encoded" + unsupported = "Unsupported Parameter" + +class JWKParameter(NamedTuple): + description: str + public: bool + required: bool | None + type: ParmType | None + +JWKValuesRegistry: dict[LiteralString, dict[LiteralString, JWKParameter]] +JWKParamsRegistry: dict[LiteralString, JWKParameter] +JWKEllipticCurveRegistry: dict[LiteralString, str] +_JWKUseSupported: TypeAlias = Literal["sig", "enc"] +JWKUseRegistry: dict[_JWKUseSupported, str] +_JWKOperationSupported: TypeAlias = Literal[ + "sign", "verify", "encrypt", "decrypt", "wrapKey", "unwrapKey", "deriveKey", "deriveBits" +] +JWKOperationsRegistry: dict[_JWKOperationSupported, str] +JWKpycaCurveMap: dict[LiteralString, LiteralString] +IANANamedInformationHashAlgorithmRegistry: dict[ + LiteralString, + hashes.SHA256 + | hashes.SHA384 + | hashes.SHA512 + | hashes.SHA3_224 + | hashes.SHA3_256 + | hashes.SHA3_384 + | hashes.SHA3_512 + | hashes.BLAKE2s + | hashes.BLAKE2b + | None, +] + +class InvalidJWKType(JWException): + value: str | None + def __init__(self, value: str | None = None) -> None: ... + +class InvalidJWKUsage(JWException): + value: str + use: str + def __init__(self, use: str, value: str) -> None: ... + +class InvalidJWKOperation(JWException): + op: str + values: Sequence[str] + def __init__(self, operation: str, values: Sequence[str]) -> None: ... + +class InvalidJWKValue(JWException): ... + +class JWK(dict[str, Any]): + unsafe_skip_rsa_key_validation: bool + + @overload + def __init__( + self, + *, + generate: Literal["RSA"], + public_exponent: int | None = None, + size: int | None = None, + kid: str | None = None, + alg: str | None = None, + use: _JWKUseSupported | None = None, + key_ops: list[_JWKOperationSupported] | None = None, + ) -> None: ... + @overload + def __init__(self, *, generate: Literal["oct", "EC", "OKP"], **kwargs) -> None: ... + @overload + def __init__(self, **kwargs) -> None: ... + + # TODO: __init__ may not be typed adequately because keyword arguments depend on the value of generate + @classmethod + @overload + def generate( + cls, + *, + kty: Literal["RSA"], + public_exponent: int | None = None, + size: int | None = None, + kid: str | None = None, + alg: str | None = None, + use: _JWKUseSupported | None = None, + key_ops: list[_JWKOperationSupported] | None = None, + ) -> Self: ... + @classmethod + @overload + def generate(cls, *, kty: _JWKKeyTypeSupported, **kwargs) -> Self: ... + + def generate_key(self, *, kty: _JWKKeyTypeSupported, **kwargs) -> None: ... + def import_key(self, **kwargs) -> None: ... + @classmethod + def from_json(cls, key) -> Self: ... + + @overload + def export(self, private_key: bool = True, as_dict: Literal[False] = False) -> str: ... + @overload + def export(self, private_key: bool, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export(self, *, as_dict: Literal[True]) -> dict[str, Any]: ... + + @overload + def export_public(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_public(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_public(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + @overload + def export_private(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_private(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_private(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + @overload + def export_symmetric(self, as_dict: Literal[False] = False) -> str: ... + @overload + def export_symmetric(self, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export_symmetric(self, as_dict: bool = False) -> str | dict[str, Any]: ... + + def public(self) -> Self: ... + @property + def has_public(self) -> bool: ... + @property + def has_private(self) -> bool: ... + @property + def is_symmetric(self) -> bool: ... + @property + @deprecated("") + def key_type(self) -> str | None: ... + @property + @deprecated("") + def key_id(self) -> str | None: ... + @property + @deprecated("") + def key_curve(self) -> str | None: ... + @deprecated("") + def get_curve( + self, arg: str + ) -> ( + ec.SECP256R1 + | ec.SECP384R1 + | ec.SECP521R1 + | ec.SECP256K1 + | ec.BrainpoolP256R1 + | ec.BrainpoolP384R1 + | ec.BrainpoolP512R1 + | _Ed25519_CURVE + | _Ed448_CURVE + | _X25519_CURVE + | _X448_CURVE + ): ... + def get_op_key( + self, operation: str | None = None, arg: str | None = None + ) -> str | rsa.RSAPrivateKey | rsa.RSAPublicKey | ec.EllipticCurvePrivateKey | ec.EllipticCurvePublicKey | None: ... + def import_from_pyca( + self, + key: ( + rsa.RSAPrivateKey + | rsa.RSAPublicKey + | ec.EllipticCurvePrivateKey + | ec.EllipticCurvePublicKey + | Ed25519PrivateKey + | Ed448PrivateKey + | X25519PrivateKey + | Ed25519PublicKey + | Ed448PublicKey + | X25519PublicKey + ), + ) -> None: ... + def import_from_pem(self, data: bytes, password: bytes | None = None, kid: str | None = None) -> None: ... + + @overload + def export_to_pem(self, private_key: Literal[False] = False, password: Unused = False) -> bytes: ... + @overload + def export_to_pem(self, private_key: Literal[True], password: bytes | None) -> bytes: ... + + @classmethod + def from_pyca( + cls, + key: ( + rsa.RSAPrivateKey + | rsa.RSAPublicKey + | ec.EllipticCurvePrivateKey + | ec.EllipticCurvePublicKey + | Ed25519PrivateKey + | Ed448PrivateKey + | X25519PrivateKey + | Ed25519PublicKey + | Ed448PublicKey + | X25519PublicKey + ), + ) -> Self: ... + @classmethod + def from_pem(cls, data: bytes, password: bytes | None = None) -> Self: ... + def thumbprint(self, hashalg: hashes.HashAlgorithm = ...) -> str: ... + def thumbprint_uri(self, hname: str = "sha-256") -> str: ... + @classmethod + def from_password(cls, password: str) -> Self: ... + def setdefault(self, key: str, default: _T | None = None) -> _T: ... + def __hash__(self) -> int: ... # type: ignore[override] + +class JWKSet(dict[Literal["keys"], set[JWK]]): + @overload + def __setitem__(self, key: Literal["keys"], val: JWK) -> None: ... + @overload + def __setitem__(self, key: str, val: Any) -> None: ... + + def add(self, elem: JWK) -> None: ... + + @overload + def export(self, private_keys: bool = True, as_dict: Literal[False] = False) -> str: ... + @overload + def export(self, private_keys: bool, as_dict: Literal[True]) -> dict[str, Any]: ... + @overload + def export(self, *, as_dict: Literal[True]) -> dict[str, Any]: ... + + def import_keyset(self, keyset: str | bytes) -> None: ... + @classmethod + def from_json(cls, keyset: str | bytes) -> Self: ... + def get_key(self, kid: str) -> JWK | None: ... + def get_keys(self, kid: str) -> set[JWK]: ... + def setdefault(self, key: str, default: _T | None = None) -> _T: ... diff --git a/stubs/jwcrypto/jwcrypto/jws.pyi b/stubs/jwcrypto/jwcrypto/jws.pyi new file mode 100644 index 000000000000..b73d3f1fd227 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jws.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete +from typing import Any, Literal +from typing_extensions import LiteralString, Self + +from jwcrypto.common import JWException, JWSEHeaderParameter +from jwcrypto.jwa import JWAAlgorithm +from jwcrypto.jwk import JWK, JWKSet + +JWSHeaderRegistry: dict[LiteralString, JWSEHeaderParameter] +default_allowed_algs: list[LiteralString] + +class InvalidJWSSignature(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWSObject(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class InvalidJWSOperation(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWSCore: + alg: str + engine: JWAAlgorithm + key: JWK | JWKSet + header: dict[str, Any] + protected: str + payload: bytes + def __init__( + self, + alg: str, + key: JWK | JWKSet, + header: dict[str, Any] | str | None, + payload: str | bytes, + algs: list[str] | None = None, + ) -> None: ... + def sign(self) -> dict[str, str | bytes]: ... + def verify(self, signature: bytes) -> Literal[True]: ... + +class JWS: + objects: dict[str, Incomplete] + verifylog: list[str] | None + header_registry: Incomplete + def __init__(self, payload=None, header_registry=None) -> None: ... + + @property + def allowed_algs(self): ... + @allowed_algs.setter + def allowed_algs(self, algs) -> None: ... + + @property + def is_valid(self): ... + def verify(self, key, alg=None, detached_payload=None) -> None: ... + def deserialize(self, raw_jws, key=None, alg=None) -> None: ... + def add_signature(self, key, alg=None, protected=None, header=None) -> None: ... + def serialize(self, compact: bool = False) -> str: ... + @property + def payload(self): ... + def detach_payload(self) -> None: ... + @property + def jose_header(self): ... + @classmethod + def from_jose_token(cls, token: str | bytes) -> Self: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/jwt.pyi b/stubs/jwcrypto/jwcrypto/jwt.pyi new file mode 100644 index 000000000000..f5fa84c6dc41 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/jwt.pyi @@ -0,0 +1,85 @@ +from typing import Any, SupportsInt +from typing_extensions import LiteralString, deprecated + +from jwcrypto.common import JWException, JWKeyNotFound +from jwcrypto.jwk import JWK, JWKSet + +JWTClaimsRegistry: dict[LiteralString, str] +JWT_expect_type: bool + +class JWTExpired(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTNotYetValid(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTMissingClaim(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTInvalidClaimValue(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTInvalidClaimFormat(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +@deprecated("") +class JWTMissingKeyID(JWException): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWTMissingKey(JWKeyNotFound): + def __init__(self, message: str | None = None, exception: BaseException | None = None) -> None: ... + +class JWT: + deserializelog: list[str] | None + def __init__( + self, + header: dict[str, Any] | str | None = None, + claims: dict[str, Any] | str | None = None, + jwt=None, + key: JWK | JWKSet | None = None, + algs=None, + default_claims=None, + check_claims=None, + expected_type=None, + strict_serialization: bool = False, + ) -> None: ... + + @property + def header(self) -> str: ... + @header.setter + def header(self, h: dict[str, Any] | str) -> None: ... + + @property + def claims(self) -> str: ... + @claims.setter + def claims(self, data: str) -> None: ... + + @property + def token(self): ... + @token.setter + def token(self, t) -> None: ... + + @property + def leeway(self) -> int: ... + @leeway.setter + def leeway(self, lwy: SupportsInt) -> None: ... + + @property + def validity(self) -> int: ... + @validity.setter + def validity(self, v: SupportsInt) -> None: ... + + @property + def expected_type(self): ... + @expected_type.setter + def expected_type(self, v) -> None: ... + + def norm_typ(self, val): ... + def make_signed_token(self, key: JWK) -> None: ... + def make_encrypted_token(self, key: JWK) -> None: ... + def validate(self, key: JWK | JWKSet) -> None: ... + def deserialize(self, jwt, key=None) -> None: ... + def serialize(self, compact: bool = True) -> str: ... + @classmethod + def from_jose_token(cls, token): ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/jwcrypto/jwcrypto/version.pyi b/stubs/jwcrypto/jwcrypto/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/jwcrypto/jwcrypto/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/kafka-python/@tests/stubtest_allowlist.txt b/stubs/kafka-python/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b8dfd146c7cc --- /dev/null +++ b/stubs/kafka-python/@tests/stubtest_allowlist.txt @@ -0,0 +1,24 @@ +# Command-line entry points are not a useful typed API surface. +kafka.__main__ +kafka.admin.__main__ +kafka.consumer.__main__ +kafka.producer.__main__ + +# Benchmark modules are not included in type stubs. +kafka.benchmarks.* + +# Concrete subclasses define these abstract properties as class attributes. +kafka.protocol.api.Request.API_KEY +kafka.protocol.api.Request.API_VERSION +kafka.protocol.api.Request.RESPONSE_TYPE +kafka.protocol.api.Request.SCHEMA +kafka.protocol.api.Response.API_KEY +kafka.protocol.api.Response.API_VERSION +kafka.protocol.api.Response.SCHEMA + +# Vendored compatibility modules are implementation details. +kafka.vendor +kafka.vendor.enum34 +kafka.vendor.selectors34 +kafka.vendor.six +kafka.vendor.socketpair diff --git a/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt b/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..0f5c5020fb76 --- /dev/null +++ b/stubs/kafka-python/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# The bytes subclass object layout differs by platform/Python build. +kafka.protocol.message.PartialMessage diff --git a/stubs/kafka-python/METADATA.toml b/stubs/kafka-python/METADATA.toml new file mode 100644 index 000000000000..33686d2d9baf --- /dev/null +++ b/stubs/kafka-python/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.3.2" +upstream-repository = "https://github.com/dpkp/kafka-python" diff --git a/stubs/kafka-python/kafka/__init__.pyi b/stubs/kafka-python/kafka/__init__.pyi new file mode 100644 index 000000000000..36252752f501 --- /dev/null +++ b/stubs/kafka-python/kafka/__init__.pyi @@ -0,0 +1,13 @@ +import logging + +from kafka.admin import KafkaAdminClient as KafkaAdminClient +from kafka.client_async import KafkaClient as KafkaClient +from kafka.conn import BrokerConnection as BrokerConnection +from kafka.consumer import KafkaConsumer as KafkaConsumer +from kafka.consumer.subscription_state import ConsumerRebalanceListener as ConsumerRebalanceListener +from kafka.producer import KafkaProducer as KafkaProducer + +__all__ = ["BrokerConnection", "ConsumerRebalanceListener", "KafkaAdminClient", "KafkaClient", "KafkaConsumer", "KafkaProducer"] + +class NullHandler(logging.Handler): + def emit(self, record) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/__init__.pyi b/stubs/kafka-python/kafka/admin/__init__.pyi new file mode 100644 index 000000000000..d895bbf521e0 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/__init__.pyi @@ -0,0 +1,30 @@ +from kafka.admin.acl_resource import ( + ACL as ACL, + ACLFilter as ACLFilter, + ACLOperation as ACLOperation, + ACLPermissionType as ACLPermissionType, + ACLResourcePatternType as ACLResourcePatternType, + ResourcePattern as ResourcePattern, + ResourcePatternFilter as ResourcePatternFilter, + ResourceType as ResourceType, +) +from kafka.admin.client import KafkaAdminClient as KafkaAdminClient +from kafka.admin.config_resource import ConfigResource as ConfigResource, ConfigResourceType as ConfigResourceType +from kafka.admin.new_partitions import NewPartitions as NewPartitions +from kafka.admin.new_topic import NewTopic as NewTopic + +__all__ = [ + "ConfigResource", + "ConfigResourceType", + "KafkaAdminClient", + "NewTopic", + "NewPartitions", + "ACL", + "ACLFilter", + "ResourcePattern", + "ResourcePatternFilter", + "ACLOperation", + "ResourceType", + "ACLPermissionType", + "ACLResourcePatternType", +] diff --git a/stubs/kafka-python/kafka/admin/acl_resource.pyi b/stubs/kafka-python/kafka/admin/acl_resource.pyi new file mode 100644 index 000000000000..ea613c07dbe3 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/acl_resource.pyi @@ -0,0 +1,91 @@ +from enum import IntEnum + +class ResourceType(IntEnum): + UNKNOWN = 0 + ANY = 1 + CLUSTER = 4 + DELEGATION_TOKEN = 6 + GROUP = 3 + TOPIC = 2 + TRANSACTIONAL_ID = 5 + +class ACLOperation(IntEnum): + UNKNOWN = 0 + ANY = 1 + ALL = 2 + READ = 3 + WRITE = 4 + CREATE = 5 + DELETE = 6 + ALTER = 7 + DESCRIBE = 8 + CLUSTER_ACTION = 9 + DESCRIBE_CONFIGS = 10 + ALTER_CONFIGS = 11 + IDEMPOTENT_WRITE = 12 + CREATE_TOKENS = 13 + DESCRIBE_TOKENS = 13 + +class ACLPermissionType(IntEnum): + UNKNOWN = 0 + ANY = 1 + DENY = 2 + ALLOW = 3 + +class ACLResourcePatternType(IntEnum): + UNKNOWN = 0 + ANY = 1 + MATCH = 2 + LITERAL = 3 + PREFIXED = 4 + +class ACLFilter: + principal: str | None + host: str | None + operation: ACLOperation + permission_type: ACLPermissionType + resource_pattern: ResourcePatternFilter + def __init__( + self, + principal: str | None, + host: str | None, + operation: ACLOperation, + permission_type: ACLPermissionType, + resource_pattern: ResourcePatternFilter, + ) -> None: ... + def validate(self) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + +class ACL(ACLFilter): + resource_pattern: ResourcePattern + def __init__( + self, + principal: str, + host: str, + operation: ACLOperation, + permission_type: ACLPermissionType, + resource_pattern: ResourcePattern, + ) -> None: ... + def validate(self) -> None: ... + +class ResourcePatternFilter: + resource_type: ResourceType + resource_name: str | None + pattern_type: ACLResourcePatternType + def __init__(self, resource_type: ResourceType, resource_name: str | None, pattern_type: ACLResourcePatternType) -> None: ... + def validate(self) -> None: ... + def __eq__(self, other): ... + def __hash__(self): ... + +class ResourcePattern(ResourcePatternFilter): + resource_name: str + def __init__( + self, + resource_type: ResourceType, + resource_name: str, + pattern_type: ACLResourcePatternType = ACLResourcePatternType.LITERAL, + ) -> None: ... + def validate(self) -> None: ... + +def valid_acl_operations(int_vals) -> set[ACLOperation]: ... diff --git a/stubs/kafka-python/kafka/admin/client.pyi b/stubs/kafka-python/kafka/admin/client.pyi new file mode 100644 index 000000000000..bbda95e50889 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/client.pyi @@ -0,0 +1,114 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Unpack + +from kafka.admin.acl_resource import ACL, ACLFilter +from kafka.admin.config_resource import ConfigResource +from kafka.admin.new_partitions import NewPartitions +from kafka.admin.new_topic import NewTopic +from kafka.errors import KafkaError +from kafka.protocol.admin import ElectionType +from kafka.structs import GroupInformation, OffsetAndMetadata, TopicPartition + +_ApiVersion: TypeAlias = tuple[int, ...] +_BootstrapServers: TypeAlias = str | Sequence[str] +_KafkaClientFactory: TypeAlias = Callable[..., object] +_SaslMechanism: TypeAlias = Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] +_SecurityProtocol: TypeAlias = Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] +_SocketOption: TypeAlias = tuple[int, int, int] + +@type_check_only +class _KafkaAdminClientConfig(TypedDict, total=False): + bootstrap_servers: _BootstrapServers + client_id: str + request_timeout_ms: int + connections_max_idle_ms: int + reconnect_backoff_ms: int + reconnect_backoff_max_ms: int + max_in_flight_requests_per_connection: int + receive_buffer_bytes: int | None + send_buffer_bytes: int | None + socket_options: Sequence[_SocketOption] + sock_chunk_bytes: int + sock_chunk_buffer_count: int + retry_backoff_ms: int + metadata_max_age_ms: int + security_protocol: _SecurityProtocol + ssl_context: ssl.SSLContext | None + ssl_check_hostname: bool + ssl_cafile: str | None + ssl_certfile: str | None + ssl_keyfile: str | None + ssl_password: str | None + ssl_crlfile: str | None + api_version: _ApiVersion | None + api_version_auto_timeout_ms: int + selector: type[selectors.BaseSelector] + sasl_mechanism: _SaslMechanism | None + sasl_plain_username: str | None + sasl_plain_password: str | None + sasl_kerberos_name: object | None + sasl_kerberos_service_name: str + sasl_kerberos_domain_name: str | None + sasl_oauth_token_provider: object | None + socks5_proxy: str | None + metric_reporters: Sequence[type[object]] + metrics_num_samples: int + metrics_sample_window_ms: int + kafka_client: _KafkaClientFactory + +@type_check_only +class _CreateAclsResult(TypedDict): + succeeded: list[ACL] + failed: list[tuple[ACL, KafkaError]] + +log: Incomplete + +class KafkaAdminClient: + DEFAULT_CONFIG: Incomplete + config: Incomplete + def __init__(self, **configs: Unpack[_KafkaAdminClientConfig]) -> None: ... + def close(self) -> None: ... + def send_request(self, request, node_id=None): ... + def send_requests(self, requests_and_node_ids, response_fn=...): ... + def create_topics(self, new_topics: Sequence[NewTopic], timeout_ms: int | None = None, validate_only: bool = False): ... + def delete_topics(self, topics: Sequence[str], timeout_ms: int | None = None): ... + def list_topics(self) -> list[str]: ... + def describe_topics(self, topics: Sequence[str] | None = None) -> list[dict[str, Incomplete]]: ... + def describe_cluster(self) -> dict[str, Incomplete]: ... + def describe_acls(self, acl_filter: ACLFilter) -> tuple[list[ACL], KafkaError]: ... + def create_acls(self, acls: Sequence[ACL]) -> _CreateAclsResult: ... + def delete_acls( + self, acl_filters: Sequence[ACLFilter] + ) -> list[tuple[ACLFilter, list[tuple[ACL, KafkaError]], KafkaError]]: ... + def describe_configs(self, config_resources: Sequence[ConfigResource], include_synonyms: bool = False): ... + def alter_configs(self, config_resources: Sequence[ConfigResource]): ... + def create_partitions( + self, topic_partitions: Mapping[str, NewPartitions], timeout_ms: int | None = None, validate_only: bool = False + ): ... + def delete_records( + self, + records_to_delete: Mapping[TopicPartition, int], + timeout_ms: float | None = None, + partition_leader_id: int | None = None, + ) -> dict[TopicPartition, Incomplete]: ... + def describe_consumer_groups( + self, group_ids: Sequence[str], group_coordinator_id: int | None = None, include_authorized_operations: bool = False + ) -> list[GroupInformation]: ... + def list_consumer_groups(self, broker_ids: Sequence[int] | None = None) -> list[tuple[str, str]]: ... + def list_consumer_group_offsets( + self, group_id: str, group_coordinator_id: int | None = None, partitions: Iterable[TopicPartition] | None = None + ) -> dict[TopicPartition, OffsetAndMetadata]: ... + def delete_consumer_groups( + self, group_ids: Sequence[str], group_coordinator_id: int | None = None + ) -> list[tuple[str, KafkaError]]: ... + def perform_leader_election( + self, + election_type: int | ElectionType, + topic_partitions: Mapping[str, Sequence[int]] | None = None, + timeout_ms: int | None = None, + ): ... + def describe_log_dirs(self): ... diff --git a/stubs/kafka-python/kafka/admin/config_resource.pyi b/stubs/kafka-python/kafka/admin/config_resource.pyi new file mode 100644 index 000000000000..8a54cca3b482 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/config_resource.pyi @@ -0,0 +1,12 @@ +from collections.abc import Mapping +from enum import IntEnum + +class ConfigResourceType(IntEnum): + BROKER = 4 + TOPIC = 2 + +class ConfigResource: + resource_type: ConfigResourceType + name: str + configs: Mapping[str, str] | None + def __init__(self, resource_type: ConfigResourceType, name: str, configs: Mapping[str, str] | None = None) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/new_partitions.pyi b/stubs/kafka-python/kafka/admin/new_partitions.pyi new file mode 100644 index 000000000000..b828f1f5fef6 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/new_partitions.pyi @@ -0,0 +1,6 @@ +from collections.abc import Sequence + +class NewPartitions: + total_count: int + new_assignments: Sequence[Sequence[int]] | None + def __init__(self, total_count: int, new_assignments: Sequence[Sequence[int]] | None = None) -> None: ... diff --git a/stubs/kafka-python/kafka/admin/new_topic.pyi b/stubs/kafka-python/kafka/admin/new_topic.pyi new file mode 100644 index 000000000000..4a1d64ba08c0 --- /dev/null +++ b/stubs/kafka-python/kafka/admin/new_topic.pyi @@ -0,0 +1,16 @@ +from collections.abc import Mapping, Sequence + +class NewTopic: + name: str + num_partitions: int + replication_factor: int + replica_assignments: Mapping[int, Sequence[int]] | None + topic_configs: Mapping[str, str] | None + def __init__( + self, + name: str, + num_partitions: int = -1, + replication_factor: int = -1, + replica_assignments: Mapping[int, Sequence[int]] | None = None, + topic_configs: Mapping[str, str] | None = None, + ) -> None: ... diff --git a/stubs/kafka-python/kafka/cli/__init__.pyi b/stubs/kafka-python/kafka/cli/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/kafka-python/kafka/cli/admin/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/__init__.pyi new file mode 100644 index 000000000000..50eefc19daa8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/__init__.pyi @@ -0,0 +1,3 @@ +def main_parser(): ... +def build_kwargs(props): ... +def run_cli(args=None): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi new file mode 100644 index 000000000000..3a1217ed3605 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/__init__.pyi @@ -0,0 +1,3 @@ +class ClusterSubCommand: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi b/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi new file mode 100644 index 000000000000..d68bcbed33cb --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/cluster/describe.pyi @@ -0,0 +1,3 @@ +class DescribeCluster: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi new file mode 100644 index 000000000000..bf9567add55a --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/__init__.pyi @@ -0,0 +1,3 @@ +class ConfigsSubCommand: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi b/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi new file mode 100644 index 000000000000..175fad7af132 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/configs/describe.pyi @@ -0,0 +1,5 @@ +class DescribeConfigs: + @classmethod + def add_subparser(cls, subparsers) -> None: ... + @classmethod + def command(cls, client, args): ... diff --git a/stubs/kafka-python/kafka/cli/admin/consumer_groups/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/consumer_groups/__init__.pyi new file mode 100644 index 000000000000..782b1765b411 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/consumer_groups/__init__.pyi @@ -0,0 +1,3 @@ +class ConsumerGroupsSubCommand: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/consumer_groups/delete.pyi b/stubs/kafka-python/kafka/cli/admin/consumer_groups/delete.pyi new file mode 100644 index 000000000000..90e373374fc5 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/consumer_groups/delete.pyi @@ -0,0 +1,3 @@ +class DeleteConsumerGroups: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/consumer_groups/describe.pyi b/stubs/kafka-python/kafka/cli/admin/consumer_groups/describe.pyi new file mode 100644 index 000000000000..ce25bc8a0d33 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/consumer_groups/describe.pyi @@ -0,0 +1,3 @@ +class DescribeConsumerGroups: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/consumer_groups/list.pyi b/stubs/kafka-python/kafka/cli/admin/consumer_groups/list.pyi new file mode 100644 index 000000000000..9e16c1de775f --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/consumer_groups/list.pyi @@ -0,0 +1,3 @@ +class ListConsumerGroups: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/consumer_groups/list_offsets.pyi b/stubs/kafka-python/kafka/cli/admin/consumer_groups/list_offsets.pyi new file mode 100644 index 000000000000..e175d4510b08 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/consumer_groups/list_offsets.pyi @@ -0,0 +1,3 @@ +class ListConsumerGroupOffsets: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/log_dirs/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/log_dirs/__init__.pyi new file mode 100644 index 000000000000..a42ac1f93a4e --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/log_dirs/__init__.pyi @@ -0,0 +1,3 @@ +class LogDirsSubCommand: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/log_dirs/describe.pyi b/stubs/kafka-python/kafka/cli/admin/log_dirs/describe.pyi new file mode 100644 index 000000000000..a9ab6d5a7bc9 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/log_dirs/describe.pyi @@ -0,0 +1,3 @@ +class DescribeLogDirs: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi b/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi new file mode 100644 index 000000000000..0345a054a456 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/__init__.pyi @@ -0,0 +1,3 @@ +class TopicsSubCommand: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/create.pyi b/stubs/kafka-python/kafka/cli/admin/topics/create.pyi new file mode 100644 index 000000000000..2902efef9999 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/create.pyi @@ -0,0 +1,5 @@ +class CreateTopic: + @classmethod + def add_subparser(cls, subparsers) -> None: ... + @classmethod + def command(cls, client, args): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi b/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi new file mode 100644 index 000000000000..128a5c51365e --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/delete.pyi @@ -0,0 +1,3 @@ +class DeleteTopic: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi b/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi new file mode 100644 index 000000000000..ab0ec7438f58 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/describe.pyi @@ -0,0 +1,3 @@ +class DescribeTopics: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/admin/topics/list.pyi b/stubs/kafka-python/kafka/cli/admin/topics/list.pyi new file mode 100644 index 000000000000..b23a865b72e4 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/admin/topics/list.pyi @@ -0,0 +1,3 @@ +class ListTopics: + @classmethod + def add_subparser(cls, subparsers): ... diff --git a/stubs/kafka-python/kafka/cli/consumer/__init__.pyi b/stubs/kafka-python/kafka/cli/consumer/__init__.pyi new file mode 100644 index 000000000000..50eefc19daa8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/consumer/__init__.pyi @@ -0,0 +1,3 @@ +def main_parser(): ... +def build_kwargs(props): ... +def run_cli(args=None): ... diff --git a/stubs/kafka-python/kafka/cli/producer/__init__.pyi b/stubs/kafka-python/kafka/cli/producer/__init__.pyi new file mode 100644 index 000000000000..50eefc19daa8 --- /dev/null +++ b/stubs/kafka-python/kafka/cli/producer/__init__.pyi @@ -0,0 +1,3 @@ +def main_parser(): ... +def build_kwargs(props): ... +def run_cli(args=None): ... diff --git a/stubs/kafka-python/kafka/client_async.pyi b/stubs/kafka-python/kafka/client_async.pyi new file mode 100644 index 000000000000..3946ec2b79a9 --- /dev/null +++ b/stubs/kafka-python/kafka/client_async.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections import OrderedDict as OrderedDict + +log: Incomplete +socketpair: Incomplete + +class KafkaClient: + DEFAULT_CONFIG: Incomplete + config: Incomplete + cluster: Incomplete + def __init__(self, **configs) -> None: ... + def maybe_connect(self, node_id, wakeup: bool = True): ... + def connection_failed(self, node_id): ... + def ready(self, node_id, metadata_priority: bool = True): ... + def connected(self, node_id): ... + def close(self, node_id=None) -> None: ... + def __del__(self) -> None: ... + def is_disconnected(self, node_id): ... + def connection_delay(self, node_id): ... + def throttle_delay(self, node_id): ... + def is_ready(self, node_id, metadata_priority: bool = True): ... + def send(self, node_id, request, wakeup: bool = True, request_timeout_ms=None): ... + def poll(self, timeout_ms=None, future=None): ... + def in_flight_request_count(self, node_id=None): ... + def least_loaded_node(self): ... + def least_loaded_node_refresh_ms(self): ... + def set_topics(self, topics): ... + def add_topic(self, topic): ... + def get_api_versions(self): ... + def check_version(self, node_id=None, timeout=None, **kwargs): ... + def api_version(self, operation, max_version=None): ... + def wakeup(self) -> None: ... + def bootstrap_connected(self): ... + def await_ready(self, node_id, timeout_ms: int = 30000): ... + def send_and_receive(self, node_id, request): ... + +class IdleConnectionManager: + connections_max_idle: Incomplete + next_idle_close_check_time: Incomplete + lru_connections: Incomplete + def __init__(self, connections_max_idle_ms) -> None: ... + def update(self, conn_id) -> None: ... + def remove(self, conn_id) -> None: ... + def is_expired(self, conn_id): ... + def next_check_ms(self): ... + def update_next_idle_close_check_time(self, ts) -> None: ... + def poll_expired_connection(self): ... + +class KafkaClientMetrics: + metrics: Incomplete + metric_group_name: Incomplete + connection_closed: Incomplete + connection_created: Incomplete + select_time: Incomplete + io_time: Incomplete + def __init__(self, metrics, metric_group_prefix, conns) -> None: ... diff --git a/stubs/kafka-python/kafka/cluster.pyi b/stubs/kafka-python/kafka/cluster.pyi new file mode 100644 index 000000000000..bcfab555ca99 --- /dev/null +++ b/stubs/kafka-python/kafka/cluster.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +log: Incomplete + +class ClusterMetadata: + DEFAULT_CONFIG: Incomplete + need_all_topic_metadata: bool + unauthorized_topics: Incomplete + internal_topics: Incomplete + controller: Incomplete + cluster_id: Incomplete + config: Incomplete + def __init__(self, **configs) -> None: ... + def is_bootstrap(self, node_id): ... + def brokers(self): ... + def broker_metadata(self, broker_id): ... + def partitions_for_topic(self, topic): ... + def available_partitions_for_topic(self, topic): ... + def leader_for_partition(self, partition): ... + def leader_epoch_for_partition(self, partition): ... + def partitions_for_broker(self, broker_id): ... + def coordinator_for_group(self, group): ... + def ttl(self): ... + def refresh_backoff(self): ... + def request_update(self): ... + @property + def need_update(self): ... + def topics(self, exclude_internal_topics: bool = True): ... + def failed_update(self, exception) -> None: ... + def update_metadata(self, metadata): ... + def add_listener(self, listener) -> None: ... + def remove_listener(self, listener) -> None: ... + def add_coordinator(self, response, coord_type, coord_key): ... + def with_partitions(self, partitions_to_add): ... + +def collect_hosts(hosts, randomize: bool = True): ... diff --git a/stubs/kafka-python/kafka/codec.pyi b/stubs/kafka-python/kafka/codec.pyi new file mode 100644 index 000000000000..fcd6af14d29d --- /dev/null +++ b/stubs/kafka-python/kafka/codec.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +ZSTD_MAX_OUTPUT_SIZE: Incomplete +PYPY: Incomplete + +def has_gzip(): ... +def has_snappy(): ... +def has_zstd(): ... +def has_lz4(): ... +def gzip_encode(payload, compresslevel=None): ... +def gzip_decode(payload): ... +def snappy_encode(payload, xerial_compatible: bool = True, xerial_blocksize=32768): ... +def snappy_decode(payload): ... + +lz4_encode: Incomplete + +def lz4f_decode(payload): ... + +lz4_decode: Incomplete +lz4_decode = lz4f_decode + +def lz4_encode_old_kafka(payload): ... +def lz4_decode_old_kafka(payload): ... +def zstd_encode(payload): ... +def zstd_decode(payload): ... diff --git a/stubs/kafka-python/kafka/conn.pyi b/stubs/kafka-python/kafka/conn.pyi new file mode 100644 index 000000000000..dd7d99adbc3a --- /dev/null +++ b/stubs/kafka-python/kafka/conn.pyi @@ -0,0 +1,70 @@ +import ssl +from _typeshed import Incomplete + +log: Incomplete +DEFAULT_KAFKA_PORT: int +ssl_available: bool +SSLEOFError = ssl.SSLEOFError +SSLWantReadError = ssl.SSLWantReadError +SSLWantWriteError = ssl.SSLWantWriteError +SSLZeroReturnError = ssl.SSLZeroReturnError + +AFI_NAMES: Incomplete + +class ConnectionStates: + DISCONNECTED: str + CONNECTING: str + HANDSHAKE: str + CONNECTED: str + AUTHENTICATING: str + API_VERSIONS_SEND: str + API_VERSIONS_RECV: str + +class BrokerConnection: + DEFAULT_CONFIG: Incomplete + SECURITY_PROTOCOLS: Incomplete + VERSION_CHECKS: Incomplete + host: Incomplete + port: Incomplete + afi: Incomplete + config: Incomplete + node_id: Incomplete + in_flight_requests: Incomplete + state: Incomplete + last_attempt: int + def __init__(self, host, port, afi, **configs) -> None: ... + def connect_blocking(self, timeout=...): ... + def connect(self): ... + def blacked_out(self): ... + def throttled(self): ... + def throttle_delay(self): ... + def connection_delay(self): ... + def connected(self): ... + def connecting(self): ... + def initializing(self): ... + def disconnected(self): ... + def connect_failed(self): ... + def __del__(self) -> None: ... + def close(self, error=None) -> None: ... + def send(self, request, blocking: bool = True, request_timeout_ms=None): ... + def send_pending_requests(self): ... + def send_pending_requests_v2(self): ... + def can_send_more(self): ... + def recv(self): ... + def requests_timed_out(self): ... + def timed_out_ifrs(self): ... + def next_ifr_request_timeout_ms(self): ... + def get_api_versions(self): ... + def check_version(self, timeout: int = 2, **kwargs): ... + +class BrokerConnectionMetrics: + metrics: Incomplete + bytes_sent: Incomplete + bytes_received: Incomplete + request_time: Incomplete + throttle_time: Incomplete + def __init__(self, metrics, metric_group_prefix, node_id) -> None: ... + +def get_ip_port_afi(host_and_port_str): ... +def is_inet_4_or_6(gai): ... +def dns_lookup(host, port, afi=...): ... diff --git a/stubs/kafka-python/kafka/consumer/__init__.pyi b/stubs/kafka-python/kafka/consumer/__init__.pyi new file mode 100644 index 000000000000..6830e557ab8b --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.consumer.group import KafkaConsumer as KafkaConsumer + +__all__ = ["KafkaConsumer"] diff --git a/stubs/kafka-python/kafka/consumer/fetcher.pyi b/stubs/kafka-python/kafka/consumer/fetcher.pyi new file mode 100644 index 000000000000..a34ae667d98b --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/fetcher.pyi @@ -0,0 +1,150 @@ +from _typeshed import Incomplete +from typing import ClassVar, NamedTuple + +import kafka.errors as Errors + +log: Incomplete +READ_UNCOMMITTED: int +READ_COMMITTED: int +ISOLATION_LEVEL_CONFIG: Incomplete + +class ConsumerRecord(NamedTuple): + topic: str + partition: int + leader_epoch: int | None + offset: int + timestamp: int + timestamp_type: int + key: Incomplete + value: Incomplete + headers: list[tuple[str, bytes]] + checksum: int | None + serialized_key_size: int + serialized_value_size: int + serialized_header_size: int + +class CompletedFetch(NamedTuple): + topic_partition: Incomplete + fetched_offset: Incomplete + response_version: Incomplete + partition_data: Incomplete + metric_aggregator: Incomplete + +class ExceptionMetadata(NamedTuple): + partition: Incomplete + fetched_offset: Incomplete + exception: Incomplete + +class NoOffsetForPartitionError(Errors.KafkaError): ... +class RecordTooLargeError(Errors.KafkaError): ... + +class Fetcher: + DEFAULT_CONFIG: Incomplete + config: Incomplete + def __init__(self, client, subscriptions, **configs) -> None: ... + def send_fetches(self): ... + def in_flight_fetches(self): ... + def reset_offsets_if_needed(self): ... + def offsets_by_times(self, timestamps, timeout_ms=None): ... + def beginning_offsets(self, partitions, timeout_ms): ... + def end_offsets(self, partitions, timeout_ms): ... + def beginning_or_end_offset(self, partitions, timestamp, timeout_ms): ... + def fetched_records(self, max_records=None, update_offsets: bool = True): ... + def close(self) -> None: ... + + class PartitionRecords: + fetch_offset: Incomplete + topic_partition: Incomplete + leader_epoch: int + next_fetch_offset: Incomplete + bytes_read: int + records_read: int + isolation_level: Incomplete + aborted_producer_ids: Incomplete + aborted_transactions: Incomplete + metric_aggregator: Incomplete + check_crcs: Incomplete + record_iterator: Incomplete + on_drain: Incomplete + def __init__( + self, + fetch_offset, + tp, + records, + key_deserializer=None, + value_deserializer=None, + check_crcs: bool = True, + isolation_level=0, + aborted_transactions=None, + metric_aggregator=None, + on_drain=..., + ) -> None: ... + def __bool__(self) -> bool: ... + __nonzero__ = __bool__ + def drain(self) -> None: ... + def take(self, n=None): ... + +class FetchSessionHandler: + node_id: Incomplete + next_metadata: Incomplete + session_partitions: Incomplete + def __init__(self, node_id) -> None: ... + def build_next(self, next_partitions): ... + def handle_response(self, response): ... + def handle_error(self, _exception) -> None: ... + +class FetchMetadata: + MAX_EPOCH: int + INVALID_SESSION_ID: int + THROTTLED_SESSION_ID: int + INITIAL_EPOCH: int + FINAL_EPOCH: int + INITIAL: ClassVar[FetchMetadata] + LEGACY: ClassVar[FetchMetadata] + session_id: Incomplete + epoch: Incomplete + def __init__(self, session_id, epoch) -> None: ... + @property + def is_full(self): ... + @classmethod + def next_epoch(cls, prev_epoch): ... + def next_close_existing(self): ... + @classmethod + def new_incremental(cls, session_id): ... + def next_incremental(self): ... + +class FetchRequestData: + def __init__(self, to_send, to_forget, metadata) -> None: ... + @property + def metadata(self): ... + @property + def id(self): ... + @property + def epoch(self): ... + @property + def to_send(self): ... + @property + def to_forget(self): ... + +class FetchMetrics: + total_bytes: int + total_records: int + def __init__(self) -> None: ... + +class FetchResponseMetricAggregator: + sensors: Incomplete + unrecorded_partitions: Incomplete + fetch_metrics: Incomplete + topic_fetch_metrics: Incomplete + def __init__(self, sensors, partitions) -> None: ... + def record(self, partition, num_bytes, num_records) -> None: ... + +class FetchManagerMetrics: + metrics: Incomplete + group_name: Incomplete + bytes_fetched: Incomplete + records_fetched: Incomplete + fetch_latency: Incomplete + records_fetch_lag: Incomplete + def __init__(self, metrics, prefix) -> None: ... + def record_topic_fetch_metrics(self, topic, num_bytes, num_records) -> None: ... diff --git a/stubs/kafka-python/kafka/consumer/group.pyi b/stubs/kafka-python/kafka/consumer/group.pyi new file mode 100644 index 000000000000..e18e3cf3dc33 --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/group.pyi @@ -0,0 +1,143 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from typing import Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, Unpack + +from kafka.consumer.fetcher import ConsumerRecord +from kafka.consumer.subscription_state import ConsumerRebalanceListener +from kafka.future import Future +from kafka.serializer.abstract import Deserializer +from kafka.structs import OffsetAndMetadata, OffsetAndTimestamp, TopicPartition + +_ApiVersion: TypeAlias = tuple[int, ...] +_BootstrapServers: TypeAlias = str | Sequence[str] +_CommitCallback: TypeAlias = Callable[[Mapping[TopicPartition, OffsetAndMetadata], object], object] +_ConsumerDeserializer: TypeAlias = Deserializer | Callable[[bytes | None], object] +_KafkaClientFactory: TypeAlias = Callable[..., object] +_SaslMechanism: TypeAlias = Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] +_SecurityProtocol: TypeAlias = Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] +_SocketOption: TypeAlias = tuple[int, int, int] + +@type_check_only +class _KafkaConsumerConfig(TypedDict, total=False): + bootstrap_servers: _BootstrapServers + client_id: str + group_id: str | None + group_instance_id: str | None + key_deserializer: _ConsumerDeserializer | None + value_deserializer: _ConsumerDeserializer | None + enable_incremental_fetch_sessions: bool + fetch_max_wait_ms: int + fetch_min_bytes: int + fetch_max_bytes: int + max_partition_fetch_bytes: int + request_timeout_ms: int + retry_backoff_ms: int + reconnect_backoff_ms: int + reconnect_backoff_max_ms: int + max_in_flight_requests_per_connection: int + auto_offset_reset: Literal["earliest", "latest", "smallest", "largest"] + enable_auto_commit: bool + auto_commit_interval_ms: int + default_offset_commit_callback: _CommitCallback + check_crcs: bool + isolation_level: Literal["read_uncommitted", "read_committed"] + allow_auto_create_topics: bool + metadata_max_age_ms: int + partition_assignment_strategy: Sequence[type[object]] + max_poll_records: int + max_poll_interval_ms: int + session_timeout_ms: int + heartbeat_interval_ms: int + receive_buffer_bytes: int | None + send_buffer_bytes: int | None + socket_options: Sequence[_SocketOption] + sock_chunk_bytes: int + sock_chunk_buffer_count: int + consumer_timeout_ms: int | float + security_protocol: _SecurityProtocol + ssl_context: ssl.SSLContext | None + ssl_check_hostname: bool + ssl_cafile: str | None + ssl_certfile: str | None + ssl_keyfile: str | None + ssl_crlfile: str | None + ssl_password: str | None + ssl_ciphers: str | None + api_version: _ApiVersion | None + api_version_auto_timeout_ms: int + connections_max_idle_ms: int + metric_reporters: Sequence[type[object]] + metrics_enabled: bool + metrics_num_samples: int + metrics_sample_window_ms: int + metric_group_prefix: str + selector: type[selectors.BaseSelector] + exclude_internal_topics: bool + sasl_mechanism: _SaslMechanism | None + sasl_plain_username: str | None + sasl_plain_password: str | None + sasl_kerberos_name: object | None + sasl_kerberos_service_name: str + sasl_kerberos_domain_name: str | None + sasl_oauth_token_provider: object | None + socks5_proxy: str | None + kafka_client: _KafkaClientFactory + +log: Incomplete + +class KafkaConsumer(Iterator[ConsumerRecord]): + DEFAULT_CONFIG: Incomplete + DEFAULT_SESSION_TIMEOUT_MS_0_9: int + config: Incomplete + def __init__(self, *topics: str, **configs: Unpack[_KafkaConsumerConfig]) -> None: ... + def bootstrap_connected(self): ... + def assign(self, partitions: Iterable[TopicPartition]) -> None: ... + def assignment(self) -> set[TopicPartition]: ... + def close(self, autocommit: bool = True, timeout_ms: int | None = None) -> None: ... + def commit_async( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata] | None = None, callback: _CommitCallback | None = None + ) -> Future: ... + def commit( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata] | None = None, timeout_ms: int | None = None + ) -> None: ... + + @overload + def committed( + self, partition: TopicPartition, metadata: Literal[False] = False, timeout_ms: int | None = None + ) -> int | None: ... + @overload + def committed( + self, partition: TopicPartition, metadata: Literal[True], timeout_ms: int | None = None + ) -> OffsetAndMetadata | None: ... + @overload + def committed( + self, partition: TopicPartition, metadata: bool, timeout_ms: int | None = None + ) -> int | OffsetAndMetadata | None: ... + + def topics(self) -> set[str]: ... + def partitions_for_topic(self, topic: str) -> set[int]: ... + def poll( + self, timeout_ms: int = 0, max_records: int | None = None, update_offsets: bool = True + ) -> dict[TopicPartition, list[ConsumerRecord]]: ... + def position(self, partition: TopicPartition, timeout_ms: int | None = None) -> int | None: ... + def highwater(self, partition: TopicPartition) -> int | None: ... + def pause(self, *partitions: TopicPartition) -> None: ... + def paused(self) -> set[TopicPartition]: ... + def resume(self, *partitions: TopicPartition) -> None: ... + def seek(self, partition: TopicPartition, offset: int) -> None: ... + def seek_to_beginning(self, *partitions: TopicPartition) -> None: ... + def seek_to_end(self, *partitions: TopicPartition) -> None: ... + def subscribe( + self, topics: Iterable[str] = (), pattern: str | None = None, listener: ConsumerRebalanceListener | None = None + ) -> None: ... + def subscription(self) -> set[str]: ... + def unsubscribe(self) -> None: ... + def metrics(self, raw: bool = False) -> dict[str, dict[str, object]] | dict[object, object] | None: ... + def offsets_for_times(self, timestamps: Mapping[TopicPartition, int]) -> dict[TopicPartition, OffsetAndTimestamp | None]: ... + def beginning_offsets(self, partitions: Iterable[TopicPartition]) -> dict[TopicPartition, int]: ... + def end_offsets(self, partitions: Iterable[TopicPartition]) -> dict[TopicPartition, int]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> ConsumerRecord: ... diff --git a/stubs/kafka-python/kafka/consumer/subscription_state.pyi b/stubs/kafka-python/kafka/consumer/subscription_state.pyi new file mode 100644 index 000000000000..e085b78873cf --- /dev/null +++ b/stubs/kafka-python/kafka/consumer/subscription_state.pyi @@ -0,0 +1,112 @@ +import abc +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.util import synchronized + +log: Incomplete + +class SubscriptionType(IntEnum): + NONE = 0 + AUTO_TOPICS = 1 + AUTO_PATTERN = 2 + USER_ASSIGNED = 3 + +class SubscriptionState: + subscription: Incomplete + subscription_type: Incomplete + subscribed_pattern: Incomplete + assignment: Incomplete + rebalance_listener: Incomplete + listeners: Incomplete + def __init__(self, offset_reset_strategy: str = "earliest") -> None: ... + @synchronized + def subscribe(self, topics=(), pattern=None, listener=None) -> None: ... + @synchronized + def change_subscription(self, topics) -> None: ... + @synchronized + def group_subscribe(self, topics) -> None: ... + @synchronized + def reset_group_subscription(self) -> None: ... + @synchronized + def assign_from_user(self, partitions) -> None: ... + @synchronized + def assign_from_subscribed(self, assignments) -> None: ... + @synchronized + def unsubscribe(self) -> None: ... + @synchronized + def group_subscription(self): ... + @synchronized + def seek(self, partition, offset) -> None: ... + @synchronized + def assigned_partitions(self): ... + @synchronized + def paused_partitions(self): ... + @synchronized + def fetchable_partitions(self): ... + @synchronized + def partitions_auto_assigned(self): ... + @synchronized + def all_consumed_offsets(self): ... + @synchronized + def request_offset_reset(self, partition, offset_reset_strategy=None) -> None: ... + @synchronized + def set_reset_pending(self, partitions, next_allowed_reset_time) -> None: ... + @synchronized + def has_default_offset_reset_policy(self): ... + @synchronized + def is_offset_reset_needed(self, partition): ... + @synchronized + def has_all_fetch_positions(self): ... + @synchronized + def missing_fetch_positions(self): ... + @synchronized + def has_valid_position(self, partition): ... + @synchronized + def reset_missing_positions(self) -> None: ... + @synchronized + def partitions_needing_reset(self): ... + @synchronized + def is_assigned(self, partition): ... + @synchronized + def is_paused(self, partition): ... + @synchronized + def is_fetchable(self, partition): ... + @synchronized + def pause(self, partition) -> None: ... + @synchronized + def resume(self, partition) -> None: ... + @synchronized + def reset_failed(self, partitions, next_retry_time) -> None: ... + @synchronized + def move_partition_to_end(self, partition) -> None: ... + @synchronized + def position(self, partition): ... + +class TopicPartitionState: + paused: bool + reset_strategy: Incomplete + highwater: Incomplete + drop_pending_record_batch: bool + next_allowed_retry_time: Incomplete + def __init__(self) -> None: ... + position: Incomplete + def reset(self, strategy) -> None: ... + def is_reset_allowed(self): ... + @property + def awaiting_reset(self): ... + def set_reset_pending(self, next_allowed_retry_time) -> None: ... + def reset_failed(self, next_allowed_retry_time) -> None: ... + @property + def has_valid_position(self): ... + def is_missing_position(self): ... + def seek(self, offset) -> None: ... + def pause(self) -> None: ... + def resume(self) -> None: ... + def is_fetchable(self): ... + +class ConsumerRebalanceListener(metaclass=abc.ABCMeta): + @abc.abstractmethod + def on_partitions_revoked(self, revoked): ... + @abc.abstractmethod + def on_partitions_assigned(self, assigned): ... diff --git a/stubs/kafka-python/kafka/coordinator/__init__.pyi b/stubs/kafka-python/kafka/coordinator/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/kafka-python/kafka/coordinator/assignors/__init__.pyi b/stubs/kafka-python/kafka/coordinator/assignors/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi b/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi new file mode 100644 index 000000000000..898c5dc4d676 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/abstract.pyi @@ -0,0 +1,15 @@ +import abc +from _typeshed import Incomplete + +log: Incomplete + +class AbstractPartitionAssignor(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self): ... + @abc.abstractmethod + def assign(self, cluster, members): ... + @abc.abstractmethod + def metadata(self, topics): ... + @abc.abstractmethod + def on_assignment(self, assignment): ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/range.pyi b/stubs/kafka-python/kafka/coordinator/assignors/range.pyi new file mode 100644 index 000000000000..667d52af7efd --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/range.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor + +log: Incomplete + +class RangePartitionAssignor(AbstractPartitionAssignor): + name: str + version: int + @classmethod + def assign(cls, cluster, group_subscriptions): ... + @classmethod + def metadata(cls, topics): ... + @classmethod + def on_assignment(cls, assignment) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi b/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi new file mode 100644 index 000000000000..b876b9cec002 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/roundrobin.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor + +log: Incomplete + +class RoundRobinPartitionAssignor(AbstractPartitionAssignor): + name: str + version: int + @classmethod + def assign(cls, cluster, group_subscriptions): ... + @classmethod + def metadata(cls, topics): ... + @classmethod + def on_assignment(cls, assignment) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/__init__.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi new file mode 100644 index 000000000000..1b3620d3623c --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/partition_movements.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +log: Incomplete + +class ConsumerPair(NamedTuple): + src_member_id: Incomplete + dst_member_id: Incomplete + +def is_sublist(source, target): ... + +class PartitionMovements: + partition_movements_by_topic: Incomplete + partition_movements: Incomplete + def __init__(self) -> None: ... + def move_partition(self, partition, old_consumer, new_consumer) -> None: ... + def get_partition_to_be_moved(self, partition, old_consumer, new_consumer): ... + def are_sticky(self): ... diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi new file mode 100644 index 000000000000..670cfe6b9c0b --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sorted_set.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class SortedSet: + def __init__(self, iterable=None, key=None) -> None: ... + def first(self): ... + def last(self): ... + def pop_last(self): ... + def add(self, value): ... + def remove(self, value): ... + def __contains__(self, value) -> bool: ... + def __iter__(self): ... + __nonzero__: Incomplete + __bool__: Incomplete diff --git a/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi new file mode 100644 index 000000000000..ad40223ebbfd --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/assignors/sticky/sticky_assignor.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.coordinator.assignors.abstract import AbstractPartitionAssignor +from kafka.protocol.struct import Struct + +log: Incomplete + +class ConsumerGenerationPair(NamedTuple): + consumer: Incomplete + generation: Incomplete + +def has_identical_list_elements(list_): ... +def subscriptions_comparator_key(element): ... +def partitions_comparator_key(element): ... +def remove_if_present(collection, element) -> None: ... + +class StickyAssignorMemberMetadataV1(NamedTuple): + subscription: Incomplete + partitions: Incomplete + generation: Incomplete + +class StickyAssignorUserDataV1(Struct): + SCHEMA: Incomplete + +class StickyAssignmentExecutor: + members: Incomplete + current_assignment: Incomplete + previous_assignment: Incomplete + current_partition_consumer: Incomplete + is_fresh_assignment: bool + partition_to_all_potential_consumers: Incomplete + consumer_to_all_potential_partitions: Incomplete + sorted_current_subscriptions: Incomplete + sorted_partitions: Incomplete + unassigned_partitions: Incomplete + revocation_required: bool + partition_movements: Incomplete + def __init__(self, cluster, members) -> None: ... + def perform_initial_assignment(self) -> None: ... + def balance(self) -> None: ... + def get_final_assignment(self, member_id): ... + +class StickyPartitionAssignor(AbstractPartitionAssignor): + DEFAULT_GENERATION_ID: int + name: str + version: int + member_assignment: Incomplete + generation = DEFAULT_GENERATION_ID # pyrefly: ignore [unknown-name] + @classmethod + def assign(cls, cluster, members): ... + @classmethod + def parse_member_metadata(cls, metadata): ... + @classmethod + def metadata(cls, topics): ... + @classmethod + def on_assignment(cls, assignment) -> None: ... + @classmethod + def on_generation_assignment(cls, generation) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/base.pyi b/stubs/kafka-python/kafka/coordinator/base.pyi new file mode 100644 index 000000000000..ae911d976734 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/base.pyi @@ -0,0 +1,86 @@ +import abc +import threading +from _typeshed import Incomplete +from typing import ClassVar + +from kafka import errors as Errors + +log: Incomplete +heartbeat_log: Incomplete + +class MemberState: + UNJOINED: str + REBALANCING: str + STABLE: str + +class Generation: + NO_GENERATION: ClassVar[Generation] + generation_id: Incomplete + member_id: Incomplete + protocol: Incomplete + def __init__(self, generation_id, member_id, protocol) -> None: ... + def has_member_id(self): ... + def __eq__(self, other): ... + +class UnjoinedGroupException(Errors.KafkaError): + retriable: bool + +class BaseCoordinator(metaclass=abc.ABCMeta): + DEFAULT_CONFIG: Incomplete + config: Incomplete + heartbeat: Incomplete + rejoin_needed: bool + rejoining: bool + state: Incomplete + join_future: Incomplete + coordinator_id: Incomplete + def __init__(self, client, **configs) -> None: ... + @property + def group_id(self): ... + @property + def group_instance_id(self): ... + @abc.abstractmethod + def protocol_type(self): ... + @abc.abstractmethod + def group_protocols(self): ... + def coordinator_unknown(self): ... + def coordinator(self): ... + def connected(self): ... + def ensure_coordinator_ready(self, timeout_ms=None): ... + def lookup_coordinator(self): ... + def need_rejoin(self): ... + def poll_heartbeat(self) -> None: ... + def time_to_next_heartbeat(self): ... + def ensure_active_group(self, timeout_ms=None): ... + def join_group(self, timeout_ms=None): ... + def coordinator_dead(self, error) -> None: ... + def generation_if_stable(self): ... + def generation(self): ... + def rebalance_in_progress(self): ... + def reset_generation(self, member_id="") -> None: ... + def request_rejoin(self) -> None: ... + def __del__(self) -> None: ... + def close(self, timeout_ms=None) -> None: ... + def is_dynamic_member(self): ... + def maybe_leave_group(self, timeout_ms=None) -> None: ... + +class GroupCoordinatorMetrics: + heartbeat: Incomplete + metrics: Incomplete + metric_group_name: Incomplete + heartbeat_latency: Incomplete + join_latency: Incomplete + sync_latency: Incomplete + def __init__(self, heartbeat, metrics, prefix, tags=None) -> None: ... + +class HeartbeatThread(threading.Thread): + name: Incomplete + coordinator: Incomplete + enabled: bool + closed: bool + failed: Incomplete + def __init__(self, coordinator) -> None: ... + def enable(self) -> None: ... + def disable(self) -> None: ... + def close(self, timeout_ms=None) -> None: ... + def run(self) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/consumer.pyi b/stubs/kafka-python/kafka/coordinator/consumer.pyi new file mode 100644 index 000000000000..159cbc4a2916 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/consumer.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from kafka.coordinator.base import BaseCoordinator + +log: Incomplete + +class ConsumerCoordinator(BaseCoordinator): + DEFAULT_CONFIG: Incomplete + config: Incomplete + auto_commit_interval: Incomplete + next_auto_commit_deadline: Incomplete + completed_offset_commits: Incomplete + def __init__(self, client, subscription, **configs) -> None: ... + def __del__(self) -> None: ... + def protocol_type(self): ... + def group_protocols(self): ... + def poll(self, timeout_ms=None): ... + def time_to_next_poll(self): ... + def need_rejoin(self): ... + def refresh_committed_offsets_if_needed(self, timeout_ms=None): ... + def fetch_committed_offsets(self, partitions, timeout_ms=None): ... + def close(self, autocommit: bool = True, timeout_ms=None) -> None: ... # type: ignore[override] + def commit_offsets_async(self, offsets, callback=None): ... + def commit_offsets_sync(self, offsets, timeout_ms=None): ... + def maybe_auto_commit_offsets_now(self) -> None: ... + +class ConsumerCoordinatorMetrics: + metrics: Incomplete + metric_group_name: Incomplete + commit_latency: Incomplete + def __init__(self, metrics, metric_group_prefix, subscription) -> None: ... diff --git a/stubs/kafka-python/kafka/coordinator/heartbeat.pyi b/stubs/kafka-python/kafka/coordinator/heartbeat.pyi new file mode 100644 index 000000000000..2fb958a5c868 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/heartbeat.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete + +log: Incomplete + +class Heartbeat: + DEFAULT_CONFIG: Incomplete + config: Incomplete + last_send: Incomplete + last_receive: Incomplete + last_poll: Incomplete + last_reset: Incomplete + heartbeat_failed: Incomplete + def __init__(self, **configs) -> None: ... + def poll(self) -> None: ... + def sent_heartbeat(self) -> None: ... + def fail_heartbeat(self) -> None: ... + def received_heartbeat(self) -> None: ... + def time_to_next_heartbeat(self): ... + def should_heartbeat(self): ... + def session_timeout_expired(self): ... + def reset_timeouts(self) -> None: ... + def poll_timeout_expired(self): ... diff --git a/stubs/kafka-python/kafka/coordinator/protocol.pyi b/stubs/kafka-python/kafka/coordinator/protocol.pyi new file mode 100644 index 000000000000..c099575b5c88 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/protocol.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from kafka.protocol.struct import Struct + +class ConsumerProtocolMemberMetadata_v0(Struct): + SCHEMA: Incomplete + +class ConsumerProtocolMemberAssignment_v0(Struct): + SCHEMA: Incomplete + def partitions(self): ... + +class ConsumerProtocol_v0: + PROTOCOL_TYPE: str + METADATA = ConsumerProtocolMemberMetadata_v0 + ASSIGNMENT = ConsumerProtocolMemberAssignment_v0 + +ConsumerProtocol: Incomplete diff --git a/stubs/kafka-python/kafka/coordinator/subscription.pyi b/stubs/kafka-python/kafka/coordinator/subscription.pyi new file mode 100644 index 000000000000..b04a77efda82 --- /dev/null +++ b/stubs/kafka-python/kafka/coordinator/subscription.pyi @@ -0,0 +1,13 @@ +class Subscription: + def __init__(self, metadata, group_instance_id) -> None: ... + @property + def version(self): ... + @property + def user_data(self): ... + @property + def topics(self): ... + subscription = topics + @property + def group_instance_id(self): ... + def encode(self): ... + def __eq__(self, other): ... diff --git a/stubs/kafka-python/kafka/errors.pyi b/stubs/kafka-python/kafka/errors.pyi new file mode 100644 index 000000000000..079bf3ebd5e4 --- /dev/null +++ b/stubs/kafka-python/kafka/errors.pyi @@ -0,0 +1,824 @@ +from _typeshed import Incomplete + +class KafkaError(RuntimeError): + retriable: bool + invalid_metadata: bool + def __eq__(self, other): ... + +class Cancelled(KafkaError): + retriable: bool + +class CommitFailedError(KafkaError): + def __init__(self, *args) -> None: ... + +class IllegalArgumentError(KafkaError): ... +class IllegalStateError(KafkaError): ... +class IncompatibleBrokerVersion(KafkaError): ... +class KafkaConfigurationError(KafkaError): ... + +class KafkaConnectionError(KafkaError): + retriable: bool + invalid_metadata: bool + +class KafkaProtocolError(KafkaError): + retriable: bool + +class CorrelationIdError(KafkaProtocolError): + retriable: bool + +class InvalidReceiveError(KafkaProtocolError): ... + +class KafkaTimeoutError(KafkaError): + retriable: bool + +class MetadataEmptyBrokerList(KafkaError): + retriable: bool + +class NoBrokersAvailable(KafkaError): + retriable: bool + invalid_metadata: bool + +class NoOffsetForPartitionError(KafkaError): ... + +class NodeNotReadyError(KafkaError): + retriable: bool + +class QuotaViolationError(KafkaError): ... + +class StaleMetadata(KafkaError): + retriable: bool + invalid_metadata: bool + +class TooManyInFlightRequests(KafkaError): + retriable: bool + +class UnrecognizedBrokerVersion(KafkaError): ... +class UnsupportedCodecError(KafkaError): ... +class TransactionAbortedError(KafkaError): ... + +class BrokerResponseError(KafkaError): + errno: Incomplete + message: Incomplete + description: Incomplete + +class AuthorizationError(BrokerResponseError): ... + +class NoError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetOutOfRangeError(BrokerResponseError): + errno: int + message: str + description: str + +class CorruptRecordError(BrokerResponseError): + errno: int + message: str + description: str + +CorruptRecordException = CorruptRecordError + +class UnknownTopicOrPartitionError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class InvalidFetchRequestError(BrokerResponseError): + errno: int + message: str + description: str + +class LeaderNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class NotLeaderForPartitionError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class RequestTimedOutError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class BrokerNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + +class ReplicaNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class MessageSizeTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class StaleControllerEpochError(BrokerResponseError): + errno: int + message: str + description: str + +class OffsetMetadataTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class NetworkExceptionError(BrokerResponseError): + errno: int + message: str + retriable: bool + invalid_metadata: bool + +class CoordinatorLoadInProgressError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class CoordinatorNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class NotCoordinatorError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidTopicError(BrokerResponseError): + errno: int + message: str + description: str + +class RecordListTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + +class NotEnoughReplicasError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class NotEnoughReplicasAfterAppendError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidRequiredAcksError(BrokerResponseError): + errno: int + message: str + description: str + +class IllegalGenerationError(BrokerResponseError): + errno: int + message: str + description: str + +class InconsistentGroupProtocolError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidGroupIdError(BrokerResponseError): + errno: int + message: str + description: str + +class UnknownMemberIdError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidSessionTimeoutError(BrokerResponseError): + errno: int + message: str + description: str + +class RebalanceInProgressError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidCommitOffsetSizeError(BrokerResponseError): + errno: int + message: str + description: str + +class TopicAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class GroupAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class ClusterAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + +class InvalidTimestampError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedSaslMechanismError(BrokerResponseError): + errno: int + message: str + description: str + +class IllegalSaslStateError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedVersionError(BrokerResponseError): + errno: int + message: str + description: str + +class TopicAlreadyExistsError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidPartitionsError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidReplicationFactorError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidReplicationAssignmentError(BrokerResponseError): + errno: int + message: str + description: str + +class InvalidConfigurationError(BrokerResponseError): + errno: int + message: str + description: str + +class NotControllerError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidRequestError(BrokerResponseError): + errno: int + message: str + description: str + +class UnsupportedForMessageFormatError(BrokerResponseError): + errno: int + message: str + description: str + +class PolicyViolationError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class OutOfOrderSequenceNumberError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DuplicateSequenceNumberError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidProducerEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidTxnStateError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidProducerIdMappingError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidTransactionTimeoutError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ConcurrentTransactionsError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class TransactionCoordinatorFencedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class TransactionalIdAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + retriable: bool + +class SecurityDisabledError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class OperationNotAttemptedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class KafkaStorageError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class LogDirNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class SaslAuthenticationFailedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnknownProducerIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ReassignmentInProgressError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenAuthDisabledError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenOwnerMismatchError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenRequestNotAllowedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenAuthorizationFailedError(AuthorizationError): + errno: int + message: str + description: str + retriable: bool + +class DelegationTokenExpiredError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidPrincipalTypeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class NonEmptyGroupError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class GroupIdNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FetchSessionIdNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidFetchSessionEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ListenerNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class TopicDeletionDisabledError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FencedLeaderEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class UnknownLeaderEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class UnsupportedCompressionTypeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class StaleBrokerEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class OffsetNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class MemberIdRequiredError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class PreferredLeaderNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class GroupMaxSizeReachedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FencedInstanceIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class EligibleLeadersNotAvailableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class ElectionNotNeededError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class NoReassignmentInProgressError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class GroupSubscribedToTopicError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidRecordError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnstableOffsetCommitError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ThrottlingQuotaExceededError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ProducerFencedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ResourceNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DuplicateResourceError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnacceptableCredentialError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InconsistentVoterSetError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidUpdateVersionError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FeatureUpdateFailedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class PrincipalDeserializationFailureError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class SnapshotNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class PositionOutOfRangeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnknownTopicIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class DuplicateBrokerRegistrationError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class BrokerIdNotRegisteredError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InconsistentTopicIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + invalid_metadata: bool + +class InconsistentClusterIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class TransactionalIdNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FetchSessionTopicIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class IneligibleReplicaError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class NewLeaderElectedError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class OffsetMovedToTieredStorageError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FencedMemberEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnreleasedInstanceIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnsupportedAssignorError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class StaleMemberEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class MismatchedEndpointTypeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnsupportedEndpointTypeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnknownControllerIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class UnknownSubscriptionIdError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class TelemetryTooLargeError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidRegistrationError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class TransactionAbortableError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidRecordStateError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class ShareSessionNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidShareSessionEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class FencedStateEpochError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class InvalidVoterKeyError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class DuplicateVoterError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +class VoterNotFoundError(BrokerResponseError): + errno: int + message: str + description: str + retriable: bool + +kafka_errors: Incomplete + +def for_code(error_code): ... diff --git a/stubs/kafka-python/kafka/future.pyi b/stubs/kafka-python/kafka/future.pyi new file mode 100644 index 000000000000..04b26e768662 --- /dev/null +++ b/stubs/kafka-python/kafka/future.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +log: Incomplete + +class Future: + error_on_callbacks: bool + is_done: bool + value: Incomplete + exception: Incomplete + def __init__(self) -> None: ... + def succeeded(self): ... + def failed(self): ... + def retriable(self): ... + def success(self, value): ... + def failure(self, e): ... + def add_callback(self, f, *args, **kwargs): ... + def add_errback(self, f, *args, **kwargs): ... + def add_both(self, f, *args, **kwargs): ... + def chain(self, future): ... diff --git a/stubs/kafka-python/kafka/metrics/__init__.pyi b/stubs/kafka-python/kafka/metrics/__init__.pyi new file mode 100644 index 000000000000..9e6b062abd21 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/__init__.pyi @@ -0,0 +1,10 @@ +from kafka.metrics.compound_stat import NamedMeasurable as NamedMeasurable +from kafka.metrics.dict_reporter import DictReporter as DictReporter +from kafka.metrics.kafka_metric import KafkaMetric as KafkaMetric +from kafka.metrics.measurable import AnonMeasurable as AnonMeasurable +from kafka.metrics.metric_config import MetricConfig as MetricConfig +from kafka.metrics.metric_name import MetricName as MetricName +from kafka.metrics.metrics import Metrics as Metrics +from kafka.metrics.quota import Quota as Quota + +__all__ = ["AnonMeasurable", "DictReporter", "KafkaMetric", "MetricConfig", "MetricName", "Metrics", "NamedMeasurable", "Quota"] diff --git a/stubs/kafka-python/kafka/metrics/compound_stat.pyi b/stubs/kafka-python/kafka/metrics/compound_stat.pyi new file mode 100644 index 000000000000..6f41b10ef0fa --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/compound_stat.pyi @@ -0,0 +1,13 @@ +import abc + +from kafka.metrics.stat import AbstractStat + +class AbstractCompoundStat(AbstractStat, metaclass=abc.ABCMeta): + def stats(self) -> None: ... + +class NamedMeasurable: + def __init__(self, metric_name, measurable_stat) -> None: ... + @property + def name(self): ... + @property + def stat(self): ... diff --git a/stubs/kafka-python/kafka/metrics/dict_reporter.pyi b/stubs/kafka-python/kafka/metrics/dict_reporter.pyi new file mode 100644 index 000000000000..c48a7d9acd80 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/dict_reporter.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from kafka.metrics.metrics_reporter import AbstractMetricsReporter + +logger: Incomplete + +class DictReporter(AbstractMetricsReporter): + def __init__(self, prefix: str = "") -> None: ... + def snapshot(self): ... + def init(self, metrics) -> None: ... + def metric_change(self, metric) -> None: ... + def metric_removal(self, metric): ... + def get_category(self, metric): ... + def configure(self, configs) -> None: ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/kafka_metric.pyi b/stubs/kafka-python/kafka/metrics/kafka_metric.pyi new file mode 100644 index 000000000000..856210a6d56b --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/kafka_metric.pyi @@ -0,0 +1,13 @@ +class KafkaMetric: + def __init__(self, metric_name, measurable, config) -> None: ... + @property + def metric_name(self): ... + @property + def measurable(self): ... + + @property + def config(self): ... + @config.setter + def config(self, config) -> None: ... + + def value(self, time_ms=None): ... diff --git a/stubs/kafka-python/kafka/metrics/measurable.pyi b/stubs/kafka-python/kafka/metrics/measurable.pyi new file mode 100644 index 000000000000..2753796bc8cd --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/measurable.pyi @@ -0,0 +1,9 @@ +import abc + +class AbstractMeasurable(metaclass=abc.ABCMeta): + @abc.abstractmethod + def measure(self, config, now): ... + +class AnonMeasurable(AbstractMeasurable): + def __init__(self, measure_fn) -> None: ... + def measure(self, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/measurable_stat.pyi b/stubs/kafka-python/kafka/metrics/measurable_stat.pyi new file mode 100644 index 000000000000..31569f41942a --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/measurable_stat.pyi @@ -0,0 +1,6 @@ +import abc + +from kafka.metrics.measurable import AbstractMeasurable +from kafka.metrics.stat import AbstractStat + +class AbstractMeasurableStat(AbstractStat, AbstractMeasurable, metaclass=abc.ABCMeta): ... diff --git a/stubs/kafka-python/kafka/metrics/metric_config.pyi b/stubs/kafka-python/kafka/metrics/metric_config.pyi new file mode 100644 index 000000000000..fc630189a272 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metric_config.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +class MetricConfig: + quota: Incomplete + event_window: Incomplete + time_window_ms: Incomplete + tags: Incomplete + def __init__(self, quota=None, samples: int = 2, event_window=..., time_window_ms=30000, tags=None) -> None: ... + + @property + def samples(self): ... + @samples.setter + def samples(self, value) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/metric_name.pyi b/stubs/kafka-python/kafka/metrics/metric_name.pyi new file mode 100644 index 000000000000..44a770132927 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metric_name.pyi @@ -0,0 +1,13 @@ +class MetricName: + def __init__(self, name, group, description=None, tags=None) -> None: ... + @property + def name(self): ... + @property + def group(self): ... + @property + def description(self): ... + @property + def tags(self): ... + def __hash__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... diff --git a/stubs/kafka-python/kafka/metrics/metrics.pyi b/stubs/kafka-python/kafka/metrics/metrics.pyi new file mode 100644 index 000000000000..31db3617f08d --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metrics.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +logger: Incomplete + +class Metrics: + def __init__(self, default_config=None, reporters=None, enable_expiration: bool = False) -> None: ... + @property + def config(self): ... + @property + def metrics(self): ... + def metric_name(self, name, group, description: str = "", tags=None): ... + def get_sensor(self, name): ... + def sensor(self, name, config=None, inactive_sensor_expiration_time_seconds=..., parents=None): ... + def remove_sensor(self, name) -> None: ... + def add_metric(self, metric_name, measurable, config=None) -> None: ... + def remove_metric(self, metric_name): ... + def add_reporter(self, reporter) -> None: ... + def register_metric(self, metric) -> None: ... + + class ExpireSensorTask: + @staticmethod + def run(metrics) -> None: ... + + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi b/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi new file mode 100644 index 000000000000..e8022ff431d2 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/metrics_reporter.pyi @@ -0,0 +1,13 @@ +import abc + +class AbstractMetricsReporter(metaclass=abc.ABCMeta): + @abc.abstractmethod + def init(self, metrics): ... + @abc.abstractmethod + def metric_change(self, metric): ... + @abc.abstractmethod + def metric_removal(self, metric): ... + @abc.abstractmethod + def configure(self, configs): ... + @abc.abstractmethod + def close(self): ... diff --git a/stubs/kafka-python/kafka/metrics/quota.pyi b/stubs/kafka-python/kafka/metrics/quota.pyi new file mode 100644 index 000000000000..3290e80589fc --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/quota.pyi @@ -0,0 +1,13 @@ +class Quota: + def __init__(self, bound, is_upper) -> None: ... + @staticmethod + def upper_bound(upper_bound): ... + @staticmethod + def lower_bound(lower_bound): ... + def is_upper_bound(self): ... + @property + def bound(self): ... + def is_acceptable(self, value): ... + def __hash__(self): ... + def __eq__(self, other): ... + def __ne__(self, other): ... diff --git a/stubs/kafka-python/kafka/metrics/stat.pyi b/stubs/kafka-python/kafka/metrics/stat.pyi new file mode 100644 index 000000000000..d9b5f9473988 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stat.pyi @@ -0,0 +1,5 @@ +import abc + +class AbstractStat(metaclass=abc.ABCMeta): + @abc.abstractmethod + def record(self, config, value, time_ms): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/__init__.pyi b/stubs/kafka-python/kafka/metrics/stats/__init__.pyi new file mode 100644 index 000000000000..bc86bfd66544 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/__init__.pyi @@ -0,0 +1,12 @@ +from kafka.metrics.stats.avg import Avg as Avg +from kafka.metrics.stats.count import Count as Count +from kafka.metrics.stats.histogram import Histogram as Histogram +from kafka.metrics.stats.max_stat import Max as Max +from kafka.metrics.stats.min_stat import Min as Min +from kafka.metrics.stats.percentile import Percentile as Percentile +from kafka.metrics.stats.percentiles import Percentiles as Percentiles +from kafka.metrics.stats.rate import Rate as Rate +from kafka.metrics.stats.sensor import Sensor as Sensor +from kafka.metrics.stats.total import Total as Total + +__all__ = ["Avg", "Count", "Histogram", "Max", "Min", "Percentile", "Percentiles", "Rate", "Sensor", "Total"] diff --git a/stubs/kafka-python/kafka/metrics/stats/avg.pyi b/stubs/kafka-python/kafka/metrics/stats/avg.pyi new file mode 100644 index 000000000000..0c00ef442744 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/avg.pyi @@ -0,0 +1,6 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Avg(AbstractSampledStat): + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/count.pyi b/stubs/kafka-python/kafka/metrics/stats/count.pyi new file mode 100644 index 000000000000..b13c9930b06a --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/count.pyi @@ -0,0 +1,6 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Count(AbstractSampledStat): + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/histogram.pyi b/stubs/kafka-python/kafka/metrics/stats/histogram.pyi new file mode 100644 index 000000000000..74a77e0ff50c --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/histogram.pyi @@ -0,0 +1,21 @@ +class Histogram: + def __init__(self, bin_scheme) -> None: ... + def record(self, value) -> None: ... + def value(self, quantile): ... + @property + def counts(self): ... + def clear(self) -> None: ... + + class ConstantBinScheme: + def __init__(self, bins, min_val, max_val) -> None: ... + @property + def bins(self): ... + def from_bin(self, b): ... + def to_bin(self, x): ... + + class LinearBinScheme: + def __init__(self, num_bins, max_val) -> None: ... + @property + def bins(self): ... + def from_bin(self, b): ... + def to_bin(self, x): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi new file mode 100644 index 000000000000..705b766b23a6 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/max_stat.pyi @@ -0,0 +1,6 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Max(AbstractSampledStat): + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi new file mode 100644 index 000000000000..cc5e3fbaf763 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/min_stat.pyi @@ -0,0 +1,6 @@ +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class Min(AbstractSampledStat): + def __init__(self) -> None: ... + def update(self, sample, config, value, now) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/percentile.pyi b/stubs/kafka-python/kafka/metrics/stats/percentile.pyi new file mode 100644 index 000000000000..a27b11c05a7b --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/percentile.pyi @@ -0,0 +1,6 @@ +class Percentile: + def __init__(self, metric_name, percentile) -> None: ... + @property + def name(self): ... + @property + def percentile(self): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi b/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi new file mode 100644 index 000000000000..8f7bbe0effcd --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/percentiles.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from kafka.metrics.compound_stat import AbstractCompoundStat +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class BucketSizing: + CONSTANT: int + LINEAR: int + +class Percentiles(AbstractSampledStat, AbstractCompoundStat): + bin_scheme: Incomplete + def __init__(self, size_in_bytes, bucketing, max_val, min_val: float = 0.0, percentiles=None) -> None: ... + def stats(self): ... + def value(self, config, now, quantile): ... + def combine(self, samples, config, now): ... + def new_sample(self, time_ms): ... + def update(self, sample, config, value, time_ms) -> None: ... + + class HistogramSample(AbstractSampledStat.Sample): + histogram: Incomplete + def __init__(self, scheme, now) -> None: ... diff --git a/stubs/kafka-python/kafka/metrics/stats/rate.pyi b/stubs/kafka-python/kafka/metrics/stats/rate.pyi new file mode 100644 index 000000000000..d5199a72807b --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/rate.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from kafka.metrics.measurable_stat import AbstractMeasurableStat +from kafka.metrics.stats.sampled_stat import AbstractSampledStat + +class TimeUnit: + NANOSECONDS: Incomplete + MICROSECONDS: Incomplete + MILLISECONDS: Incomplete + SECONDS: Incomplete + MINUTES: Incomplete + HOURS: Incomplete + DAYS: Incomplete + @staticmethod + def get_name(time_unit): ... + +class Rate(AbstractMeasurableStat): + def __init__(self, time_unit=3, sampled_stat=None) -> None: ... + def unit_name(self): ... + def record(self, config, value, time_ms) -> None: ... + def measure(self, config, now): ... + def window_size(self, config, now): ... + def convert(self, time_ms): ... + +class SampledTotal(AbstractSampledStat): + def __init__(self, initial_value=None) -> None: ... + def update(self, sample, config, value, time_ms) -> None: ... + def combine(self, samples, config, now): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi b/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi new file mode 100644 index 000000000000..c589cd800c80 --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/sampled_stat.pyi @@ -0,0 +1,26 @@ +import abc +from _typeshed import Incomplete + +from kafka.metrics.measurable_stat import AbstractMeasurableStat + +class AbstractSampledStat(AbstractMeasurableStat, metaclass=abc.ABCMeta): + def __init__(self, initial_value) -> None: ... + @abc.abstractmethod + def update(self, sample, config, value, time_ms): ... + @abc.abstractmethod + def combine(self, samples, config, now): ... + def record(self, config, value, time_ms) -> None: ... + def new_sample(self, time_ms): ... + def measure(self, config, now): ... + def current(self, time_ms): ... + def oldest(self, now): ... + def purge_obsolete_samples(self, config, now) -> None: ... + + class Sample: + initial_value: Incomplete + event_count: int + last_window_ms: Incomplete + value: Incomplete + def __init__(self, initial_value, now) -> None: ... + def reset(self, now) -> None: ... + def is_complete(self, time_ms, config): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/sensor.pyi b/stubs/kafka-python/kafka/metrics/stats/sensor.pyi new file mode 100644 index 000000000000..f302ed0944be --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/sensor.pyi @@ -0,0 +1,10 @@ +class Sensor: + def __init__(self, registry, name, parents, config, inactive_sensor_expiration_time_seconds) -> None: ... + @property + def name(self): ... + @property + def metrics(self): ... + def record(self, value: float = 1.0, time_ms=None) -> None: ... + def add_compound(self, compound_stat, config=None) -> None: ... + def add(self, metric_name, stat, config=None) -> None: ... + def has_expired(self): ... diff --git a/stubs/kafka-python/kafka/metrics/stats/total.pyi b/stubs/kafka-python/kafka/metrics/stats/total.pyi new file mode 100644 index 000000000000..2a33feb1b02b --- /dev/null +++ b/stubs/kafka-python/kafka/metrics/stats/total.pyi @@ -0,0 +1,6 @@ +from kafka.metrics.measurable_stat import AbstractMeasurableStat + +class Total(AbstractMeasurableStat): + def __init__(self, value: float = 0.0) -> None: ... + def record(self, config, value, now) -> None: ... + def measure(self, config, now): ... diff --git a/stubs/kafka-python/kafka/partitioner/__init__.pyi b/stubs/kafka-python/kafka/partitioner/__init__.pyi new file mode 100644 index 000000000000..93b321c722a6 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.partitioner.default import DefaultPartitioner as DefaultPartitioner, murmur2 as murmur2 + +__all__ = ["DefaultPartitioner", "murmur2"] diff --git a/stubs/kafka-python/kafka/partitioner/default.pyi b/stubs/kafka-python/kafka/partitioner/default.pyi new file mode 100644 index 000000000000..6800f5b03315 --- /dev/null +++ b/stubs/kafka-python/kafka/partitioner/default.pyi @@ -0,0 +1,5 @@ +class DefaultPartitioner: + @classmethod + def __call__(cls, key, all_partitions, available): ... + +def murmur2(data): ... diff --git a/stubs/kafka-python/kafka/producer/__init__.pyi b/stubs/kafka-python/kafka/producer/__init__.pyi new file mode 100644 index 000000000000..35360a27f231 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.producer.kafka import KafkaProducer as KafkaProducer + +__all__ = ["KafkaProducer"] diff --git a/stubs/kafka-python/kafka/producer/future.pyi b/stubs/kafka-python/kafka/producer/future.pyi new file mode 100644 index 000000000000..ad0fa3962f16 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/future.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.future import Future +from kafka.structs import TopicPartition + +class FutureProduceResult(Future): + topic_partition: TopicPartition + def __init__(self, topic_partition: TopicPartition) -> None: ... + def success(self, value): ... + def failure(self, error): ... + def wait(self, timeout=None): ... + +class FutureRecordMetadata(Future): + args: Incomplete + def __init__( + self, + produce_future, + batch_index, + timestamp_ms, + checksum, + serialized_key_size, + serialized_value_size, + serialized_header_size, + ) -> None: ... + def get(self, timeout=None): ... + +class RecordMetadata(NamedTuple): + topic: str + partition: int + topic_partition: TopicPartition + offset: int + timestamp: int + checksum: int | None + serialized_key_size: int + serialized_value_size: int + serialized_header_size: int diff --git a/stubs/kafka-python/kafka/producer/kafka.pyi b/stubs/kafka-python/kafka/producer/kafka.pyi new file mode 100644 index 000000000000..c00758c2f684 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/kafka.pyi @@ -0,0 +1,110 @@ +import selectors +import ssl +from _typeshed import Incomplete +from collections.abc import Callable, Mapping, Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Unpack + +from kafka.producer.future import FutureRecordMetadata +from kafka.serializer.abstract import Serializer +from kafka.structs import OffsetAndMetadata, TopicPartition + +_ApiVersion: TypeAlias = tuple[int, ...] +_BootstrapServers: TypeAlias = str | Sequence[str] +_KafkaClientFactory: TypeAlias = Callable[..., object] +_Partitioner: TypeAlias = Callable[[bytes | None, Sequence[int], Sequence[int]], int] +_ProducerSerializer: TypeAlias = Serializer | Callable[[object], bytes] +_SaslMechanism: TypeAlias = Literal["PLAIN", "GSSAPI", "OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-512"] +_SecurityProtocol: TypeAlias = Literal["PLAINTEXT", "SSL", "SASL_PLAINTEXT", "SASL_SSL"] +_SocketOption: TypeAlias = tuple[int, int, int] + +@type_check_only +class _KafkaProducerConfig(TypedDict, total=False): + bootstrap_servers: _BootstrapServers + client_id: str | None + key_serializer: _ProducerSerializer | None + value_serializer: _ProducerSerializer | None + enable_idempotence: bool + transactional_id: str | None + transaction_timeout_ms: int + delivery_timeout_ms: float + acks: int | Literal["all"] + bootstrap_topics_filter: set[str] + compression_type: Literal["gzip", "snappy", "lz4", "zstd"] | None + retries: int | float + batch_size: int + linger_ms: int + partitioner: _Partitioner + connections_max_idle_ms: int + max_block_ms: int + max_request_size: int + allow_auto_create_topics: bool + metadata_max_age_ms: int + retry_backoff_ms: int + request_timeout_ms: int + receive_buffer_bytes: int | None + send_buffer_bytes: int | None + socket_options: Sequence[_SocketOption] + sock_chunk_bytes: int + sock_chunk_buffer_count: int + reconnect_backoff_ms: int + reconnect_backoff_max_ms: int + max_in_flight_requests_per_connection: int + security_protocol: _SecurityProtocol + ssl_context: ssl.SSLContext | None + ssl_check_hostname: bool + ssl_cafile: str | None + ssl_certfile: str | None + ssl_keyfile: str | None + ssl_crlfile: str | None + ssl_password: str | None + ssl_ciphers: str | None + api_version: _ApiVersion | None + api_version_auto_timeout_ms: int + metric_reporters: Sequence[type[object]] + metrics_enabled: bool + metrics_num_samples: int + metrics_sample_window_ms: int + selector: type[selectors.BaseSelector] + sasl_mechanism: _SaslMechanism | None + sasl_plain_username: str | None + sasl_plain_password: str | None + sasl_kerberos_name: object | None + sasl_kerberos_service_name: str + sasl_kerberos_domain_name: str | None + sasl_oauth_token_provider: object | None + socks5_proxy: str | None + kafka_client: _KafkaClientFactory + +log: Incomplete +PRODUCER_CLIENT_ID_SEQUENCE: Incomplete + +class KafkaProducer: + DEFAULT_CONFIG: Incomplete + DEPRECATED_CONFIGS: Incomplete + config: Incomplete + def __init__(self, **configs: Unpack[_KafkaProducerConfig]) -> None: ... + def bootstrap_connected(self): ... + def __del__(self) -> None: ... + def close(self, timeout: float | None = None, null_logger: bool = False) -> None: ... + def partitions_for(self, topic: str) -> set[int]: ... + @classmethod + def max_usable_produce_magic(cls, api_version): ... + def init_transactions(self) -> None: ... + def begin_transaction(self) -> None: ... + def send_offsets_to_transaction( + self, offsets: Mapping[TopicPartition, OffsetAndMetadata], consumer_group_id: str + ) -> None: ... + def commit_transaction(self) -> None: ... + def abort_transaction(self) -> None: ... + def send( + self, + topic: str, + value: object = None, + key: object = None, + headers: Sequence[tuple[str, bytes]] | None = None, + partition: int | None = None, + timestamp_ms: int | None = None, + ) -> FutureRecordMetadata: ... + def flush(self, timeout: float | None = None) -> None: ... + def metrics(self, raw: bool = False) -> dict[str, dict[str, object]] | dict[object, object] | None: ... diff --git a/stubs/kafka-python/kafka/producer/producer_batch.pyi b/stubs/kafka-python/kafka/producer/producer_batch.pyi new file mode 100644 index 000000000000..6b94289a53dd --- /dev/null +++ b/stubs/kafka-python/kafka/producer/producer_batch.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from enum import IntEnum + +log: Incomplete + +class FinalState(IntEnum): + ABORTED = 0 + FAILED = 1 + SUCCEEDED = 2 + +class ProducerBatch: + max_record_size: int + created: Incomplete + drained: Incomplete + attempts: int + last_attempt: Incomplete + last_append: Incomplete + records: Incomplete + topic_partition: Incomplete + produce_future: Incomplete + def __init__(self, tp, records, now=None) -> None: ... + @property + def final_state(self): ... + @property + def record_count(self): ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def has_sequence(self): ... + def try_append(self, timestamp_ms, key, value, headers, now=None): ... + def abort(self, exception): ... + def complete(self, base_offset, log_append_time): ... + def complete_exceptionally(self, top_level_exception, record_exceptions_fn): ... + def done(self, base_offset=None, timestamp_ms=None, top_level_exception=None, record_exceptions_fn=None): ... + def has_reached_delivery_timeout(self, delivery_timeout_ms, now=None): ... + def in_retry(self): ... + def retry(self, now=None) -> None: ... + @property + def is_done(self): ... + def __lt__(self, other): ... diff --git a/stubs/kafka-python/kafka/producer/record_accumulator.pyi b/stubs/kafka-python/kafka/producer/record_accumulator.pyi new file mode 100644 index 000000000000..cb36265f18d5 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/record_accumulator.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete + +log: Incomplete + +class AtomicInteger: + def __init__(self, val: int = 0) -> None: ... + def increment(self): ... + def decrement(self): ... + def get(self): ... + +class RecordAccumulator: + DEFAULT_CONFIG: Incomplete + config: Incomplete + muted: Incomplete + def __init__(self, **configs) -> None: ... + @property + def delivery_timeout_ms(self): ... + @property + def next_expiry_time_ms(self): ... + def append(self, tp, timestamp_ms, key, value, headers, now=None): ... + def reset_next_batch_expiry_time(self) -> None: ... + def maybe_update_next_batch_expiry_time(self, batch) -> None: ... + def expired_batches(self, now=None): ... + def reenqueue(self, batch, now=None) -> None: ... + def ready(self, cluster, now=None): ... + def has_undrained(self): ... + def drain_batches_for_one_node(self, cluster, node_id, max_size, now=None): ... + def drain(self, cluster, nodes, max_size, now=None): ... + def deallocate(self, batch) -> None: ... + def flush_in_progress(self): ... + def begin_flush(self) -> None: ... + def await_flush_completion(self, timeout=None) -> None: ... + @property + def has_incomplete(self): ... + def abort_incomplete_batches(self) -> None: ... + def abort_undrained_batches(self, error) -> None: ... + def close(self) -> None: ... + +class IncompleteProducerBatches: + def __init__(self) -> None: ... + def add(self, batch) -> None: ... + def remove(self, batch) -> None: ... + def all(self): ... + def __bool__(self) -> bool: ... + __nonzero__ = __bool__ diff --git a/stubs/kafka-python/kafka/producer/sender.pyi b/stubs/kafka-python/kafka/producer/sender.pyi new file mode 100644 index 000000000000..abbb22aac1d7 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/sender.pyi @@ -0,0 +1,47 @@ +import threading +from _typeshed import Incomplete +from typing import NamedTuple + +log: Incomplete + +class PartitionResponse(NamedTuple): + error: Incomplete = ... + base_offset: Incomplete = ... + last_offset: Incomplete = ... + log_append_time: Incomplete = ... + log_start_offset: Incomplete = ... + record_errors: Incomplete = ... + error_message: Incomplete = ... + current_leader: Incomplete = ... + +class Sender(threading.Thread): + DEFAULT_CONFIG: Incomplete + config: Incomplete + name: Incomplete + def __init__(self, client, metadata, accumulator, **configs) -> None: ... + def run(self) -> None: ... + def run_once(self) -> None: ... + def initiate_close(self) -> None: ... + def force_close(self) -> None: ... + def add_topic(self, topic) -> None: ... + def wakeup(self) -> None: ... + def bootstrap_connected(self): ... + +class SenderMetrics: + metrics: Incomplete + batch_size_sensor: Incomplete + compression_rate_sensor: Incomplete + queue_time_sensor: Incomplete + records_per_request_sensor: Incomplete + byte_rate_sensor: Incomplete + retry_sensor: Incomplete + error_sensor: Incomplete + max_record_size_sensor: Incomplete + def __init__(self, metrics, client, metadata) -> None: ... + def add_metric( + self, metric_name, measurable, group_name: str = "producer-metrics", description=None, tags=None, sensor_name=None + ) -> None: ... + def maybe_register_topic_metrics(self, topic): ... + def update_produce_request_metrics(self, batches_map) -> None: ... + def record_retries(self, topic, count) -> None: ... + def record_errors(self, topic, count) -> None: ... diff --git a/stubs/kafka-python/kafka/producer/transaction_manager.pyi b/stubs/kafka-python/kafka/producer/transaction_manager.pyi new file mode 100644 index 000000000000..7e6f3e0374f0 --- /dev/null +++ b/stubs/kafka-python/kafka/producer/transaction_manager.pyi @@ -0,0 +1,187 @@ +import abc +from _typeshed import Incomplete +from enum import IntEnum + +log: Incomplete +NO_PRODUCER_ID: int +NO_PRODUCER_EPOCH: int +NO_SEQUENCE: int + +class ProducerIdAndEpoch: + producer_id: Incomplete + epoch: Incomplete + def __init__(self, producer_id, epoch) -> None: ... + @property + def is_valid(self): ... + def match(self, batch): ... + def __eq__(self, other): ... + +class TransactionState(IntEnum): + UNINITIALIZED = 0 + INITIALIZING = 1 + READY = 2 + IN_TRANSACTION = 3 + COMMITTING_TRANSACTION = 4 + ABORTING_TRANSACTION = 5 + ABORTABLE_ERROR = 6 + FATAL_ERROR = 7 + @classmethod + def is_transition_valid(cls, source, target): ... + +class Priority(IntEnum): + FIND_COORDINATOR = 0 + INIT_PRODUCER_ID = 1 + ADD_PARTITIONS_OR_OFFSETS = 2 + END_TXN = 3 + +class TransactionManager: + NO_INFLIGHT_REQUEST_CORRELATION_ID: int + ADD_PARTITIONS_RETRY_BACKOFF_MS: int + transactional_id: Incomplete + transaction_timeout_ms: Incomplete + producer_id_and_epoch: Incomplete + retry_backoff_ms: Incomplete + def __init__( + self, + transactional_id=None, + transaction_timeout_ms: int = 0, + retry_backoff_ms: int = 100, + api_version=(0, 11), + metadata=None, + ) -> None: ... + def initialize_transactions(self): ... + def begin_transaction(self) -> None: ... + def begin_commit(self): ... + def begin_abort(self): ... + def send_offsets_to_transaction(self, offsets, consumer_group_id): ... + def maybe_add_partition_to_transaction(self, topic_partition) -> None: ... + def is_send_to_partition_allowed(self, tp): ... + def has_producer_id(self, producer_id=None): ... + def is_transactional(self): ... + def has_partitions_to_add(self): ... + def is_completing(self): ... + @property + def last_error(self): ... + def has_error(self): ... + def is_aborting(self): ... + def transition_to_abortable_error(self, exc) -> None: ... + def transition_to_fatal_error(self, exc) -> None: ... + def is_partition_added(self, partition): ... + def is_partition_pending_add(self, partition): ... + def has_producer_id_and_epoch(self, producer_id, producer_epoch): ... + def set_producer_id_and_epoch(self, producer_id_and_epoch) -> None: ... + def reset_producer_id(self) -> None: ... + def sequence_number(self, tp): ... + def increment_sequence_number(self, tp, increment) -> None: ... + def reset_sequence_for_partition(self, tp) -> None: ... + def next_request_handler(self, has_incomplete_batches): ... + def retry(self, request) -> None: ... + def authentication_failed(self, exc) -> None: ... + def coordinator(self, coord_type): ... + def lookup_coordinator_for_request(self, request) -> None: ... + def next_in_flight_request_correlation_id(self): ... + def clear_in_flight_transactional_request_correlation_id(self) -> None: ... + def has_in_flight_transactional_request(self): ... + def has_fatal_error(self): ... + def has_abortable_error(self): ... + +class TransactionalRequestResult: + def __init__(self) -> None: ... + def done(self, error=None) -> None: ... + def wait(self, timeout_ms=None): ... + @property + def is_done(self): ... + @property + def succeeded(self): ... + @property + def failed(self): ... + @property + def exception(self): ... + +class TxnRequestHandler(metaclass=abc.ABCMeta): + transaction_manager: Incomplete + retry_backoff_ms: Incomplete + request: Incomplete + def __init__(self, transaction_manager, result=None) -> None: ... + @property + def transactional_id(self): ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + def fatal_error(self, exc) -> None: ... + def abortable_error(self, exc) -> None: ... + def fail(self, exc) -> None: ... + def reenqueue(self) -> None: ... + def on_complete(self, correlation_id, response_or_exc) -> None: ... + def needs_coordinator(self): ... + @property + def result(self): ... + @property + def coordinator_type(self): ... + @property + def coordinator_key(self): ... + def set_retry(self) -> None: ... + @property + def is_retry(self): ... + @abc.abstractmethod + def handle_response(self, response): ... + @property + @abc.abstractmethod + def priority(self): ... + +class InitProducerIdHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, transaction_timeout_ms) -> None: ... + @property + def priority(self): ... + def handle_response(self, response) -> None: ... + +class AddPartitionsToTxnHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, topic_partitions) -> None: ... + @property + def priority(self): ... + retry_backoff_ms: Incomplete + def handle_response(self, response) -> None: ... + def maybe_override_retry_backoff_ms(self) -> None: ... + +class FindCoordinatorHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, coord_type, coord_key) -> None: ... + @property + def priority(self): ... + @property + def coordinator_type(self) -> None: ... + @property + def coordinator_key(self) -> None: ... + def handle_response(self, response) -> None: ... + +class EndTxnHandler(TxnRequestHandler): + request: Incomplete + def __init__(self, transaction_manager, committed) -> None: ... + @property + def priority(self): ... + def handle_response(self, response) -> None: ... + +class AddOffsetsToTxnHandler(TxnRequestHandler): + consumer_group_id: Incomplete + offsets: Incomplete + request: Incomplete + def __init__(self, transaction_manager, consumer_group_id, offsets) -> None: ... + @property + def priority(self): ... + def handle_response(self, response) -> None: ... + +class TxnOffsetCommitHandler(TxnRequestHandler): + consumer_group_id: Incomplete + offsets: Incomplete + request: Incomplete + def __init__(self, transaction_manager, consumer_group_id, offsets, result) -> None: ... + @property + def priority(self): ... + @property + def coordinator_type(self): ... + @property + def coordinator_key(self): ... + def handle_response(self, response) -> None: ... diff --git a/stubs/kafka-python/kafka/protocol/__init__.pyi b/stubs/kafka-python/kafka/protocol/__init__.pyi new file mode 100644 index 000000000000..da1238775e56 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/__init__.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +API_KEYS: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/abstract.pyi b/stubs/kafka-python/kafka/protocol/abstract.pyi new file mode 100644 index 000000000000..3229b5ccfa05 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/abstract.pyi @@ -0,0 +1,9 @@ +import abc +from _typeshed import Incomplete + +class AbstractType(metaclass=abc.ABCMeta): + @abc.abstractmethod + def encode(cls, value): ... + @abc.abstractmethod + def decode(cls, data): ... + repr: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/add_offsets_to_txn.pyi b/stubs/kafka-python/kafka/protocol/add_offsets_to_txn.pyi new file mode 100644 index 000000000000..49066ce158a2 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/add_offsets_to_txn.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class AddOffsetsToTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddOffsetsToTxnResponse_v0 + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddOffsetsToTxnResponse_v1 + SCHEMA: Incomplete + +class AddOffsetsToTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddOffsetsToTxnResponse_v2 + SCHEMA: Incomplete + +AddOffsetsToTxnRequest: Incomplete +AddOffsetsToTxnResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/add_partitions_to_txn.pyi b/stubs/kafka-python/kafka/protocol/add_partitions_to_txn.pyi new file mode 100644 index 000000000000..4a1802ab6c28 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/add_partitions_to_txn.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class AddPartitionsToTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddPartitionsToTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddPartitionsToTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AddPartitionsToTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v0 + SCHEMA: Incomplete + +class AddPartitionsToTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v1 + SCHEMA: Incomplete + +class AddPartitionsToTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AddPartitionsToTxnResponse_v2 + SCHEMA: Incomplete + +AddPartitionsToTxnRequest: Incomplete +AddPartitionsToTxnResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/admin.pyi b/stubs/kafka-python/kafka/protocol/admin.pyi new file mode 100644 index 000000000000..7330c0ae74d1 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/admin.pyi @@ -0,0 +1,506 @@ +from _typeshed import Incomplete +from enum import IntEnum + +from kafka.protocol.api import Request, Response + +class CreateTopicsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateTopicsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateTopicsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateTopicsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateTopicsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateTopicsResponse_v0 + SCHEMA: Incomplete + +class CreateTopicsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateTopicsResponse_v1 + SCHEMA: Incomplete + +class CreateTopicsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateTopicsResponse_v2 + SCHEMA: Incomplete + +class CreateTopicsRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateTopicsResponse_v3 + SCHEMA: Incomplete + +CreateTopicsRequest: Incomplete +CreateTopicsResponse: Incomplete + +class DeleteTopicsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteTopicsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteTopicsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteTopicsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteTopicsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteTopicsResponse_v0 + SCHEMA: Incomplete + +class DeleteTopicsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteTopicsResponse_v1 + SCHEMA: Incomplete + +class DeleteTopicsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteTopicsResponse_v2 + SCHEMA: Incomplete + +class DeleteTopicsRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteTopicsResponse_v3 + SCHEMA: Incomplete + +DeleteTopicsRequest: Incomplete +DeleteTopicsResponse: Incomplete + +class DeleteRecordsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteRecordsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteRecordsResponse_v0 + SCHEMA: Incomplete + +DeleteRecordsResponse: Incomplete +DeleteRecordsRequest: Incomplete + +class ListGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListGroupsResponse_v0 + SCHEMA: Incomplete + +class ListGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListGroupsResponse_v1 + SCHEMA: Incomplete + +class ListGroupsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListGroupsResponse_v2 + SCHEMA: Incomplete + +ListGroupsRequest: Incomplete +ListGroupsResponse: Incomplete + +class DescribeGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeGroupsResponse_v0 + SCHEMA: Incomplete + +class DescribeGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeGroupsResponse_v1 + SCHEMA: Incomplete + +class DescribeGroupsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeGroupsResponse_v2 + SCHEMA: Incomplete + +class DescribeGroupsRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeGroupsResponse_v3 + SCHEMA: Incomplete + +DescribeGroupsRequest: Incomplete +DescribeGroupsResponse: Incomplete + +class DescribeAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeAclsResponse_v0 + SCHEMA: Incomplete + +class DescribeAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeAclsResponse_v1 + SCHEMA: Incomplete + +class DescribeAclsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeAclsResponse_v2 + SCHEMA: Incomplete + +DescribeAclsRequest: Incomplete +DescribeAclsResponse: Incomplete + +class CreateAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreateAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateAclsResponse_v0 + SCHEMA: Incomplete + +class CreateAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreateAclsResponse_v1 + SCHEMA: Incomplete + +CreateAclsRequest: Incomplete +CreateAclsResponse: Incomplete + +class DeleteAclsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteAclsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteAclsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteAclsResponse_v0 + SCHEMA: Incomplete + +class DeleteAclsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteAclsResponse_v1 + SCHEMA: Incomplete + +DeleteAclsRequest: Incomplete +DeleteAclsResponse: Incomplete + +class AlterConfigsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AlterConfigsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class AlterConfigsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AlterConfigsResponse_v0 + SCHEMA: Incomplete + +class AlterConfigsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AlterConfigsResponse_v1 + SCHEMA: Incomplete + +AlterConfigsRequest: Incomplete +AlterConfigsResponse: Incomplete + +class DescribeConfigsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeConfigsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeConfigsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeConfigsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeConfigsResponse_v0 + SCHEMA: Incomplete + +class DescribeConfigsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeConfigsResponse_v1 + SCHEMA: Incomplete + +class DescribeConfigsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeConfigsResponse_v2 + SCHEMA: Incomplete + +DescribeConfigsRequest: Incomplete +DescribeConfigsResponse: Incomplete + +class DescribeLogDirsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeLogDirsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeLogDirsResponse_v0 + SCHEMA: Incomplete + +DescribeLogDirsResponse: Incomplete +DescribeLogDirsRequest: Incomplete + +class SaslAuthenticateResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslAuthenticateResponse_v0 + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslAuthenticateResponse_v1 + SCHEMA: Incomplete + +SaslAuthenticateRequest: Incomplete +SaslAuthenticateResponse: Incomplete + +class CreatePartitionsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreatePartitionsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class CreatePartitionsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = CreatePartitionsResponse_v0 + SCHEMA: Incomplete + +class CreatePartitionsRequest_v1(Request): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + RESPONSE_TYPE = CreatePartitionsResponse_v1 + +CreatePartitionsRequest: Incomplete +CreatePartitionsResponse: Incomplete + +class DeleteGroupsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteGroupsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DeleteGroupsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteGroupsResponse_v0 + SCHEMA: Incomplete + +class DeleteGroupsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DeleteGroupsResponse_v1 + SCHEMA: Incomplete + +DeleteGroupsRequest: Incomplete +DeleteGroupsResponse: Incomplete + +class DescribeClientQuotasResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class DescribeClientQuotasRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = DescribeClientQuotasResponse_v0 + SCHEMA: Incomplete + +DescribeClientQuotasRequest: Incomplete +DescribeClientQuotasResponse: Incomplete + +class AlterPartitionReassignmentsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class AlterPartitionReassignmentsRequest_v0(Request): + FLEXIBLE_VERSION: bool + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = AlterPartitionReassignmentsResponse_v0 + SCHEMA: Incomplete + +AlterPartitionReassignmentsRequest: Incomplete +AlterPartitionReassignmentsResponse: Incomplete + +class ListPartitionReassignmentsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class ListPartitionReassignmentsRequest_v0(Request): + FLEXIBLE_VERSION: bool + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListPartitionReassignmentsResponse_v0 + SCHEMA: Incomplete + +ListPartitionReassignmentsRequest: Incomplete +ListPartitionReassignmentsResponse: Incomplete + +class ElectLeadersResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ElectLeadersRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ElectLeadersResponse_v0 + SCHEMA: Incomplete + +class ElectLeadersResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ElectLeadersRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ElectLeadersResponse_v1 + SCHEMA: Incomplete + +class ElectionType(IntEnum): + PREFERRED = 0 + UNCLEAN = 1 + +ElectLeadersRequest: Incomplete +ElectLeadersResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/api.pyi b/stubs/kafka-python/kafka/protocol/api.pyi new file mode 100644 index 000000000000..72634ee5ee15 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api.pyi @@ -0,0 +1,37 @@ +import abc +from _typeshed import Incomplete + +from kafka.protocol.struct import Struct + +class RequestHeader(Struct): + SCHEMA: Incomplete + def __init__(self, request, correlation_id: int = 0, client_id: str = "kafka-python") -> None: ... + +class RequestHeaderV2(Struct): + SCHEMA: Incomplete + def __init__(self, request, correlation_id: int = 0, client_id: str = "kafka-python", tags=None) -> None: ... + +class ResponseHeader(Struct): + SCHEMA: Incomplete + +class ResponseHeaderV2(Struct): + SCHEMA: Incomplete + +class Request(Struct, metaclass=abc.ABCMeta): + FLEXIBLE_VERSION: bool + API_KEY: Incomplete + API_VERSION: Incomplete + SCHEMA: Incomplete + RESPONSE_TYPE: Incomplete + def expect_response(self): ... + def to_object(self): ... + def build_header(self, correlation_id, client_id): ... + +class Response(Struct, metaclass=abc.ABCMeta): + FLEXIBLE_VERSION: bool + API_KEY: Incomplete + API_VERSION: Incomplete + SCHEMA: Incomplete + def to_object(self): ... + @classmethod + def parse_header(cls, read_buffer): ... diff --git a/stubs/kafka-python/kafka/protocol/api_versions.pyi b/stubs/kafka-python/kafka/protocol/api_versions.pyi new file mode 100644 index 000000000000..2d1a480aba34 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/api_versions.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class BaseApiVersionsResponse(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + @classmethod + def decode(cls, data): ... + +class ApiVersionsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v1(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v2(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v3(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsResponse_v4(BaseApiVersionsResponse): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ApiVersionsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ApiVersionsResponse_v0 + SCHEMA: Incomplete + +class ApiVersionsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ApiVersionsResponse_v1 + SCHEMA: Incomplete + +class ApiVersionsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ApiVersionsResponse_v2 + SCHEMA: Incomplete + +class ApiVersionsRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ApiVersionsResponse_v3 + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +class ApiVersionsRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ApiVersionsResponse_v4 + SCHEMA: Incomplete + FLEXIBLE_VERSION: bool + +ApiVersionsRequest: Incomplete +ApiVersionsResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/broker_api_versions.pyi b/stubs/kafka-python/kafka/protocol/broker_api_versions.pyi new file mode 100644 index 000000000000..9a9a50c93d65 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/broker_api_versions.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +BROKER_API_VERSIONS: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/commit.pyi b/stubs/kafka-python/kafka/protocol/commit.pyi new file mode 100644 index 000000000000..1d3c08d81410 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/commit.pyi @@ -0,0 +1,166 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class OffsetCommitResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetCommitRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v0 + SCHEMA: Incomplete + +class OffsetCommitRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v1 + SCHEMA: Incomplete + +class OffsetCommitRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v2 + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + +class OffsetCommitRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v3 + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + +class OffsetCommitRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v4 + SCHEMA: Incomplete + DEFAULT_RETENTION_TIME: int + +class OffsetCommitRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v5 + SCHEMA: Incomplete + +class OffsetCommitRequest_v6(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v6 + SCHEMA: Incomplete + +class OffsetCommitRequest_v7(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetCommitResponse_v7 + SCHEMA: Incomplete + +OffsetCommitRequest: Incomplete +OffsetCommitResponse: Incomplete + +class OffsetFetchResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetFetchRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v0 + SCHEMA: Incomplete + +class OffsetFetchRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v1 + SCHEMA: Incomplete + +class OffsetFetchRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v2 + SCHEMA: Incomplete + +class OffsetFetchRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v3 + SCHEMA: Incomplete + +class OffsetFetchRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v4 + SCHEMA: Incomplete + +class OffsetFetchRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetFetchResponse_v5 + SCHEMA: Incomplete + +OffsetFetchRequest: Incomplete +OffsetFetchResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/end_txn.pyi b/stubs/kafka-python/kafka/protocol/end_txn.pyi new file mode 100644 index 000000000000..07ba52aa0f26 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/end_txn.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class EndTxnResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class EndTxnRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = EndTxnResponse_v0 + SCHEMA: Incomplete + +class EndTxnRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = EndTxnResponse_v1 + SCHEMA: Incomplete + +class EndTxnRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = EndTxnResponse_v2 + SCHEMA: Incomplete + +EndTxnRequest: Incomplete +EndTxnResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/fetch.pyi b/stubs/kafka-python/kafka/protocol/fetch.pyi new file mode 100644 index 000000000000..e110f1557fcc --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/fetch.pyi @@ -0,0 +1,143 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.protocol.api import Request, Response + +class AbortedTransaction(NamedTuple): + producer_id: Incomplete + first_offset: Incomplete + +class FetchResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v9(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v10(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchResponse_v11(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FetchRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v0 + SCHEMA: Incomplete + +class FetchRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v1 + SCHEMA: Incomplete + +class FetchRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v2 + SCHEMA: Incomplete + +class FetchRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v3 + SCHEMA: Incomplete + +class FetchRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v4 + SCHEMA: Incomplete + +class FetchRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v5 + SCHEMA: Incomplete + +class FetchRequest_v6(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v6 + SCHEMA: Incomplete + +class FetchRequest_v7(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v7 + SCHEMA: Incomplete + +class FetchRequest_v8(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v8 + SCHEMA: Incomplete + +class FetchRequest_v9(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v9 + SCHEMA: Incomplete + +class FetchRequest_v10(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v10 + SCHEMA: Incomplete + +class FetchRequest_v11(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FetchResponse_v11 + SCHEMA: Incomplete + +FetchRequest: Incomplete +FetchResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/find_coordinator.pyi b/stubs/kafka-python/kafka/protocol/find_coordinator.pyi new file mode 100644 index 000000000000..bd121a8d50ab --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/find_coordinator.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class FindCoordinatorResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FindCoordinatorResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FindCoordinatorResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class FindCoordinatorRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FindCoordinatorResponse_v0 + SCHEMA: Incomplete + +class FindCoordinatorRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FindCoordinatorResponse_v1 + SCHEMA: Incomplete + +class FindCoordinatorRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = FindCoordinatorResponse_v2 + SCHEMA: Incomplete + +FindCoordinatorRequest: Incomplete +FindCoordinatorResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/frame.pyi b/stubs/kafka-python/kafka/protocol/frame.pyi new file mode 100644 index 000000000000..b3c8b9647588 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/frame.pyi @@ -0,0 +1,6 @@ +class KafkaBytes(bytearray): + def __init__(self, size) -> None: ... + def read(self, nbytes=None): ... + def write(self, data) -> None: ... + def seek(self, idx) -> None: ... + def tell(self): ... diff --git a/stubs/kafka-python/kafka/protocol/group.pyi b/stubs/kafka-python/kafka/protocol/group.pyi new file mode 100644 index 000000000000..8cfd38e655a3 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/group.pyi @@ -0,0 +1,229 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +from kafka.protocol.api import Request, Response +from kafka.protocol.struct import Struct + +DEFAULT_GENERATION_ID: int +UNKNOWN_MEMBER_ID: str + +class GroupMember(NamedTuple): + member_id: Incomplete = ... + group_instance_id: Incomplete = ... + metadata_bytes: Incomplete = ... + +class JoinGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class JoinGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v0 + SCHEMA: Incomplete + +class JoinGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v1 + SCHEMA: Incomplete + +class JoinGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v2 + SCHEMA: Incomplete + +class JoinGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v3 + SCHEMA: Incomplete + +class JoinGroupRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v4 + SCHEMA: Incomplete + +class JoinGroupRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = JoinGroupResponse_v5 + SCHEMA: Incomplete + +JoinGroupRequest: Incomplete +JoinGroupResponse: Incomplete + +class ProtocolMetadata(Struct): + SCHEMA: Incomplete + +class SyncGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SyncGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SyncGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SyncGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SyncGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SyncGroupResponse_v0 + SCHEMA: Incomplete + +class SyncGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SyncGroupResponse_v1 + SCHEMA: Incomplete + +class SyncGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SyncGroupResponse_v2 + SCHEMA: Incomplete + +class SyncGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SyncGroupResponse_v3 + SCHEMA: Incomplete + +SyncGroupRequest: Incomplete +SyncGroupResponse: Incomplete + +class MemberAssignment(Struct): + SCHEMA: Incomplete + +class HeartbeatResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class HeartbeatRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = HeartbeatResponse_v0 + SCHEMA: Incomplete + +class HeartbeatRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = HeartbeatResponse_v1 + SCHEMA: Incomplete + +class HeartbeatRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = HeartbeatResponse_v2 + SCHEMA: Incomplete + +class HeartbeatRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = HeartbeatResponse_v3 + SCHEMA: Incomplete + +HeartbeatRequest: Incomplete +HeartbeatResponse: Incomplete + +class LeaveGroupResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class LeaveGroupRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = LeaveGroupResponse_v0 + SCHEMA: Incomplete + +class LeaveGroupRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = LeaveGroupResponse_v1 + SCHEMA: Incomplete + +class LeaveGroupRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = LeaveGroupResponse_v2 + SCHEMA: Incomplete + +class LeaveGroupRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = LeaveGroupResponse_v3 + SCHEMA: Incomplete + +LeaveGroupRequest: Incomplete +LeaveGroupResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/init_producer_id.pyi b/stubs/kafka-python/kafka/protocol/init_producer_id.pyi new file mode 100644 index 000000000000..0025ce3e33c7 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/init_producer_id.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class InitProducerIdResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class InitProducerIdResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class InitProducerIdRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = InitProducerIdResponse_v0 + SCHEMA: Incomplete + +class InitProducerIdRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = InitProducerIdResponse_v1 + SCHEMA: Incomplete + +InitProducerIdRequest: Incomplete +InitProducerIdResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/list_offsets.pyi b/stubs/kafka-python/kafka/protocol/list_offsets.pyi new file mode 100644 index 000000000000..f8fe7767e0b3 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/list_offsets.pyi @@ -0,0 +1,85 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +UNKNOWN_OFFSET: int + +class OffsetResetStrategy: + LATEST: int + EARLIEST: int + NONE: int + +class ListOffsetsResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ListOffsetsRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v0 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v1 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v2 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v3 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v4 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +class ListOffsetsRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = ListOffsetsResponse_v5 + SCHEMA: Incomplete + DEFAULTS: Incomplete + +ListOffsetsRequest: Incomplete +ListOffsetsResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/message.pyi b/stubs/kafka-python/kafka/protocol/message.pyi new file mode 100644 index 000000000000..3e2a48204671 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/message.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from kafka.protocol.struct import Struct +from kafka.protocol.types import AbstractType + +class Message(Struct): + SCHEMAS: Incomplete + SCHEMA: Incomplete + CODEC_MASK: int + CODEC_GZIP: int + CODEC_SNAPPY: int + CODEC_LZ4: int + CODEC_ZSTD: int + TIMESTAMP_TYPE_MASK: int + HEADER_SIZE: int + timestamp: Incomplete + crc: Incomplete + magic: Incomplete + attributes: Incomplete + key: Incomplete + value: Incomplete + encode: Incomplete + def __init__(self, value, key=None, magic: int = 0, attributes: int = 0, crc: int = 0, timestamp=None) -> None: ... + @property + def timestamp_type(self): ... + @classmethod + def decode(cls, data): ... + def validate_crc(self): ... + def is_compressed(self): ... + def decompress(self): ... + def __hash__(self): ... + +class PartialMessage(bytes): ... + +class MessageSet(AbstractType): + ITEM: Incomplete + HEADER_SIZE: int + @classmethod + def encode(cls, items, prepend_size: bool = True): ... + @classmethod + def decode(cls, data, bytes_to_read=None): ... + @classmethod + def repr(cls, messages): ... diff --git a/stubs/kafka-python/kafka/protocol/metadata.pyi b/stubs/kafka-python/kafka/protocol/metadata.pyi new file mode 100644 index 000000000000..429ef2d111d6 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/metadata.pyi @@ -0,0 +1,123 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class MetadataResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class MetadataRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v0 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v1 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v2 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v3 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v4 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v5(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v5 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v6(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v6 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v7(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v7 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +class MetadataRequest_v8(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = MetadataResponse_v8 + SCHEMA: Incomplete + ALL_TOPICS: Incomplete + NO_TOPICS: Incomplete + +MetadataRequest: Incomplete +MetadataResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/offset_for_leader_epoch.pyi b/stubs/kafka-python/kafka/protocol/offset_for_leader_epoch.pyi new file mode 100644 index 000000000000..2d0c5e9aee2f --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/offset_for_leader_epoch.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class OffsetForLeaderEpochResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetForLeaderEpochResponse_v0 + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetForLeaderEpochResponse_v1 + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetForLeaderEpochResponse_v2 + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v3(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetForLeaderEpochResponse_v3 + SCHEMA: Incomplete + +class OffsetForLeaderEpochRequest_v4(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = OffsetForLeaderEpochResponse_v4 + SCHEMA: Incomplete + +OffsetForLeaderEpochRequest: Incomplete +OffsetForLeaderEpochResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/parser.pyi b/stubs/kafka-python/kafka/protocol/parser.pyi new file mode 100644 index 000000000000..63c350d3ee55 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/parser.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections import deque +from logging import Logger + +log: Logger + +class KafkaProtocol: + in_flight_requests: deque[tuple[int, Incomplete]] + bytes_to_send: list[bytes] + def __init__( + self, client_id: str | None = None, api_version: tuple[int, int, int] | None = None, max_frame_size: int = 100000000 + ) -> None: ... + def send_request(self, request, correlation_id: int | None = None) -> int: ... + def send_bytes(self) -> bytes: ... + def receive_bytes(self, data: bytes) -> list[Incomplete]: ... diff --git a/stubs/kafka-python/kafka/protocol/produce.pyi b/stubs/kafka-python/kafka/protocol/produce.pyi new file mode 100644 index 000000000000..7652fbf6be7c --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/produce.pyi @@ -0,0 +1,103 @@ +import abc +from _typeshed import Incomplete +from typing import type_check_only + +from kafka.protocol.api import Request, Response + +class ProduceResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v3(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v4(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v5(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v6(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v7(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class ProduceResponse_v8(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +@type_check_only +class _ProduceRequest(Request, metaclass=abc.ABCMeta): + API_KEY: int + def expect_response(self): ... + +class ProduceRequest_v0(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v0 + SCHEMA: Incomplete + +class ProduceRequest_v1(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v1 + SCHEMA: Incomplete + +class ProduceRequest_v2(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v2 + SCHEMA: Incomplete + +class ProduceRequest_v3(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v3 + SCHEMA: Incomplete + +class ProduceRequest_v4(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v4 + SCHEMA: Incomplete + +class ProduceRequest_v5(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v5 + SCHEMA: Incomplete + +class ProduceRequest_v6(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v6 + SCHEMA: Incomplete + +class ProduceRequest_v7(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v7 + SCHEMA: Incomplete + +class ProduceRequest_v8(_ProduceRequest): + API_VERSION: int + RESPONSE_TYPE = ProduceResponse_v8 + SCHEMA: Incomplete + +ProduceRequest: list[type[_ProduceRequest]] +ProduceResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/sasl_authenticate.pyi b/stubs/kafka-python/kafka/protocol/sasl_authenticate.pyi new file mode 100644 index 000000000000..da9781407f5b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/sasl_authenticate.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class SaslAuthenticateResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslAuthenticateResponse_v0 + SCHEMA: Incomplete + +class SaslAuthenticateRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslAuthenticateResponse_v1 + SCHEMA: Incomplete + +SaslAuthenticateRequest: Incomplete +SaslAuthenticateResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/sasl_handshake.pyi b/stubs/kafka-python/kafka/protocol/sasl_handshake.pyi new file mode 100644 index 000000000000..dad4e65bea5b --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/sasl_handshake.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class SaslHandshakeResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslHandshakeResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class SaslHandshakeRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslHandshakeResponse_v0 + SCHEMA: Incomplete + +class SaslHandshakeRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = SaslHandshakeResponse_v1 + SCHEMA: Incomplete + +SaslHandshakeRequest: Incomplete +SaslHandshakeResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/struct.pyi b/stubs/kafka-python/kafka/protocol/struct.pyi new file mode 100644 index 000000000000..11de387016c4 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/struct.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from kafka.protocol.abstract import AbstractType + +class Struct(AbstractType): + SCHEMA: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + @classmethod + def encode(cls, item): ... + @classmethod + def decode(cls, data): ... + def get_item(self, name): ... + def __hash__(self): ... + def __eq__(self, other): ... diff --git a/stubs/kafka-python/kafka/protocol/txn_offset_commit.pyi b/stubs/kafka-python/kafka/protocol/txn_offset_commit.pyi new file mode 100644 index 000000000000..d9b035c097da --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/txn_offset_commit.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete + +from kafka.protocol.api import Request, Response + +class TxnOffsetCommitResponse_v0(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitResponse_v1(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitResponse_v2(Response): + API_KEY: int + API_VERSION: int + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v0(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = TxnOffsetCommitResponse_v0 + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v1(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = TxnOffsetCommitResponse_v1 + SCHEMA: Incomplete + +class TxnOffsetCommitRequest_v2(Request): + API_KEY: int + API_VERSION: int + RESPONSE_TYPE = TxnOffsetCommitResponse_v2 + SCHEMA: Incomplete + +TxnOffsetCommitRequest: Incomplete +TxnOffsetCommitResponse: Incomplete diff --git a/stubs/kafka-python/kafka/protocol/types.pyi b/stubs/kafka-python/kafka/protocol/types.pyi new file mode 100644 index 000000000000..d1cc891ab005 --- /dev/null +++ b/stubs/kafka-python/kafka/protocol/types.pyi @@ -0,0 +1,115 @@ +from _typeshed import Incomplete + +from kafka.protocol.abstract import AbstractType as AbstractType + +class Int8(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int16(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int32(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Int64(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Float64(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class String(AbstractType): + encoding: Incomplete + def __init__(self, encoding: str = "utf-8") -> None: ... + def encode(self, value): ... + def decode(self, data): ... + +class Bytes(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + @classmethod + def repr(cls, value): ... + +class Boolean(AbstractType): + @classmethod + def encode(cls, value): ... + @classmethod + def decode(cls, data): ... + +class Schema(AbstractType): + def __init__(self, *fields) -> None: ... + def encode(self, item): ... + def decode(self, data): ... + def __len__(self) -> int: ... + def repr(self, value): ... + +class Array(AbstractType): + array_of: Incomplete + def __init__(self, *array_of) -> None: ... + def encode(self, items): ... + def decode(self, data): ... + def repr(self, list_of_items): ... + +class UnsignedVarInt32(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class VarInt32(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class VarInt64(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactString(String): + def decode(self, data): ... + def encode(self, value): ... + +class TaggedFields(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactBytes(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, value): ... + +class CompactArray(Array): + def encode(self, items): ... + def decode(self, data): ... + +class BitField(AbstractType): + @classmethod + def decode(cls, data): ... + @classmethod + def encode(cls, vals): ... + @classmethod + def to_32_bit_field(cls, vals): ... + @classmethod + def from_32_bit_field(cls, value): ... diff --git a/stubs/kafka-python/kafka/record/__init__.pyi b/stubs/kafka-python/kafka/record/__init__.pyi new file mode 100644 index 000000000000..7ac09dc7e0d8 --- /dev/null +++ b/stubs/kafka-python/kafka/record/__init__.pyi @@ -0,0 +1,3 @@ +from kafka.record.memory_records import MemoryRecords as MemoryRecords, MemoryRecordsBuilder as MemoryRecordsBuilder + +__all__ = ["MemoryRecords", "MemoryRecordsBuilder"] diff --git a/stubs/kafka-python/kafka/record/_crc32c.pyi b/stubs/kafka-python/kafka/record/_crc32c.pyi new file mode 100644 index 000000000000..3337132fe642 --- /dev/null +++ b/stubs/kafka-python/kafka/record/_crc32c.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +CRC_TABLE: Incomplete +CRC_INIT: int + +def crc_update(crc, data): ... +def crc_finalize(crc): ... +def crc(data): ... diff --git a/stubs/kafka-python/kafka/record/abc.pyi b/stubs/kafka-python/kafka/record/abc.pyi new file mode 100644 index 000000000000..c351d4fb6611 --- /dev/null +++ b/stubs/kafka-python/kafka/record/abc.pyi @@ -0,0 +1,60 @@ +import abc + +class ABCRecord(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def size_in_bytes(self): ... + @property + @abc.abstractmethod + def offset(self): ... + @property + @abc.abstractmethod + def timestamp(self): ... + @property + @abc.abstractmethod + def timestamp_type(self): ... + @property + @abc.abstractmethod + def key(self): ... + @property + @abc.abstractmethod + def value(self): ... + @property + @abc.abstractmethod + def checksum(self): ... + @abc.abstractmethod + def validate_crc(self): ... + @property + @abc.abstractmethod + def headers(self): ... + +class ABCRecordBatchBuilder(metaclass=abc.ABCMeta): + @abc.abstractmethod + def append(self, offset, timestamp, key, value, headers=None): ... + @abc.abstractmethod + def size_in_bytes(self, offset, timestamp, key, value, headers): ... + @abc.abstractmethod + def build(self): ... + +class ABCRecordBatch(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __iter__(self): ... + @property + @abc.abstractmethod + def base_offset(self): ... + @property + @abc.abstractmethod + def size_in_bytes(self): ... + @property + @abc.abstractmethod + def magic(self): ... + +class ABCRecords(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __init__(self, buffer): ... + @abc.abstractmethod + def size_in_bytes(self): ... + @abc.abstractmethod + def next_batch(self): ... + @abc.abstractmethod + def has_next(self): ... diff --git a/stubs/kafka-python/kafka/record/default_records.pyi b/stubs/kafka-python/kafka/record/default_records.pyi new file mode 100644 index 000000000000..bdb79252bc05 --- /dev/null +++ b/stubs/kafka-python/kafka/record/default_records.pyi @@ -0,0 +1,155 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder + +class DefaultRecordBase: + HEADER_STRUCT: Incomplete + ATTRIBUTES_OFFSET: Incomplete + CRC_OFFSET: Incomplete + AFTER_LEN_OFFSET: Incomplete + CODEC_MASK: int + CODEC_NONE: int + CODEC_GZIP: int + CODEC_SNAPPY: int + CODEC_LZ4: int + CODEC_ZSTD: int + TIMESTAMP_TYPE_MASK: int + TRANSACTIONAL_MASK: int + CONTROL_MASK: int + LOG_APPEND_TIME: int + CREATE_TIME: int + NO_PRODUCER_ID: int + NO_SEQUENCE: int + MAX_INT: int + +class DefaultRecordBatch(DefaultRecordBase, ABCRecordBatch): + def __init__(self, buffer) -> None: ... + @property + def base_offset(self): ... + @property + def size_in_bytes(self): ... + @property + def leader_epoch(self): ... + @property + def magic(self): ... + @property + def crc(self): ... + @property + def attributes(self): ... + @property + def last_offset_delta(self): ... + @property + def last_offset(self): ... + @property + def next_offset(self): ... + @property + def compression_type(self): ... + @property + def timestamp_type(self): ... + @property + def is_transactional(self): ... + @property + def is_control_batch(self): ... + @property + def first_timestamp(self): ... + @property + def max_timestamp(self): ... + @property + def producer_id(self): ... + def has_producer_id(self): ... + @property + def producer_epoch(self): ... + @property + def base_sequence(self): ... + @property + def has_sequence(self): ... + @property + def last_sequence(self): ... + @property + def records_count(self): ... + def __iter__(self): ... + def __next__(self): ... + next = __next__ + def validate_crc(self): ... + +class DefaultRecord(ABCRecord): + def __init__(self, size_in_bytes, offset, timestamp, timestamp_type, key, value, headers) -> None: ... + @property + def size_in_bytes(self): ... + @property + def offset(self): ... + @property + def timestamp(self): ... + @property + def timestamp_type(self): ... + @property + def key(self): ... + @property + def value(self): ... + @property + def headers(self): ... + @property + def checksum(self) -> None: ... + def validate_crc(self): ... + +class ControlRecord(DefaultRecord): + KEY_STRUCT: Incomplete + def __init__(self, size_in_bytes, offset, timestamp, timestamp_type, key, value, headers) -> None: ... + @property + def version(self): ... + @property + def type(self): ... + @property + def abort(self): ... + @property + def commit(self): ... + +class DefaultRecordBatchBuilder(DefaultRecordBase, ABCRecordBatchBuilder): + MAX_RECORD_OVERHEAD: int + def __init__( + self, magic, compression_type, is_transactional, producer_id, producer_epoch, base_sequence, batch_size + ) -> None: ... + def set_producer_state(self, producer_id, producer_epoch, base_sequence, is_transactional) -> None: ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + def append( # type: ignore[override] + self, + offset, + timestamp, + key, + value, + headers, + encode_varint=..., + size_of_varint=..., + get_type=..., + type_int=..., + time_time=..., + byte_like=..., + bytearray_type=..., + len_func=..., + zero_len_varint: int = 1, + ): ... + def write_header(self, use_compression_type: bool = True) -> None: ... + def build(self): ... + def size(self): ... + @classmethod + def header_size_in_bytes(cls): ... + @classmethod + def size_in_bytes(cls, offset_delta, timestamp_delta, key, value, headers): ... + @classmethod + def size_of(cls, key, value, headers): ... + @classmethod + def estimate_size_in_bytes(cls, key, value, headers): ... + +class DefaultRecordMetadata: + def __init__(self, offset, size, timestamp) -> None: ... + @property + def offset(self): ... + @property + def crc(self) -> None: ... + @property + def size(self): ... + @property + def timestamp(self): ... diff --git a/stubs/kafka-python/kafka/record/legacy_records.pyi b/stubs/kafka-python/kafka/record/legacy_records.pyi new file mode 100644 index 000000000000..d7165b0c0b10 --- /dev/null +++ b/stubs/kafka-python/kafka/record/legacy_records.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder + +class LegacyRecordBase: + HEADER_STRUCT_V0: Incomplete + HEADER_STRUCT_V1: Incomplete + LOG_OVERHEAD: Incomplete + CRC_OFFSET: Incomplete + MAGIC_OFFSET: Incomplete + RECORD_OVERHEAD_V0: Incomplete + RECORD_OVERHEAD_V1: Incomplete + KEY_OFFSET_V0: Incomplete + KEY_OFFSET_V1: Incomplete + KEY_LENGTH: Incomplete + VALUE_LENGTH: Incomplete + CODEC_MASK: int + CODEC_NONE: int + CODEC_GZIP: int + CODEC_SNAPPY: int + CODEC_LZ4: int + TIMESTAMP_TYPE_MASK: int + LOG_APPEND_TIME: int + CREATE_TIME: int + NO_TIMESTAMP: int + +class LegacyRecordBatch(ABCRecordBatch, LegacyRecordBase): + def __init__(self, buffer, magic) -> None: ... + @property + def base_offset(self): ... + @property + def size_in_bytes(self): ... + @property + def timestamp_type(self): ... + @property + def compression_type(self): ... + @property + def magic(self): ... + def validate_crc(self): ... + def __iter__(self): ... + +class LegacyRecord(ABCRecord): + def __init__(self, magic, offset, timestamp, timestamp_type, key, value, crc, crc_bytes) -> None: ... + @property + def magic(self): ... + @property + def offset(self): ... + @property + def timestamp(self): ... + @property + def timestamp_type(self): ... + @property + def key(self): ... + @property + def value(self): ... + @property + def headers(self): ... + @property + def checksum(self): ... + def validate_crc(self): ... + @property + def size_in_bytes(self): ... + +class LegacyRecordBatchBuilder(ABCRecordBatchBuilder, LegacyRecordBase): + def __init__(self, magic, compression_type, batch_size) -> None: ... + def append(self, offset, timestamp, key, value, headers=None): ... + def build(self): ... + def size(self): ... + def size_in_bytes(self, offset, timestamp, key, value, headers=None): ... + @classmethod + def record_size(cls, magic, key, value): ... + @classmethod + def record_overhead(cls, magic): ... + @classmethod + def estimate_size_in_bytes(cls, magic, compression_type, key, value): ... + +class LegacyRecordMetadata: + def __init__(self, offset, crc, size, timestamp) -> None: ... + @property + def offset(self): ... + @property + def crc(self): ... + @property + def size(self): ... + @property + def timestamp(self): ... diff --git a/stubs/kafka-python/kafka/record/memory_records.pyi b/stubs/kafka-python/kafka/record/memory_records.pyi new file mode 100644 index 000000000000..5dec0f3202fa --- /dev/null +++ b/stubs/kafka-python/kafka/record/memory_records.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete + +from kafka.record.abc import ABCRecords + +class MemoryRecords(ABCRecords): + LENGTH_OFFSET: Incomplete + LOG_OVERHEAD: Incomplete + MAGIC_OFFSET: Incomplete + MIN_SLICE: Incomplete + def __init__(self, bytes_data) -> None: ... + def size_in_bytes(self): ... + def valid_bytes(self): ... + def has_next(self): ... + def next_batch(self, _min_slice=26, _magic_offset=16): ... + def __iter__(self): ... + def __next__(self): ... + next = __next__ + +class MemoryRecordsBuilder: + def __init__( + self, + magic, + compression_type, + batch_size, + offset: int = 0, + transactional: bool = False, + producer_id: int = -1, + producer_epoch: int = -1, + base_sequence: int = -1, + ) -> None: ... + def skip(self, offsets_to_skip) -> None: ... + def append(self, timestamp, key, value, headers=[]): ... + def set_producer_state(self, producer_id, producer_epoch, base_sequence, is_transactional) -> None: ... + @property + def producer_id(self): ... + @property + def producer_epoch(self): ... + def records(self): ... + def close(self) -> None: ... + def size_in_bytes(self): ... + def compression_rate(self): ... + def is_full(self): ... + def next_offset(self): ... + def buffer(self): ... diff --git a/stubs/kafka-python/kafka/record/util.pyi b/stubs/kafka-python/kafka/record/util.pyi new file mode 100644 index 000000000000..fa94937bc8f8 --- /dev/null +++ b/stubs/kafka-python/kafka/record/util.pyi @@ -0,0 +1,5 @@ +def encode_varint(value, write): ... +def size_of_varint(value): ... +def decode_varint(buffer, pos: int = 0): ... +def calc_crc32c(memview, _crc32c=...): ... +def calc_crc32(memview): ... diff --git a/stubs/kafka-python/kafka/sasl/__init__.pyi b/stubs/kafka-python/kafka/sasl/__init__.pyi new file mode 100644 index 000000000000..93fcedc0ab97 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/__init__.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +SASL_MECHANISMS: Incomplete + +def register_sasl_mechanism(name, klass, overwrite: bool = False) -> None: ... +def get_sasl_mechanism(name): ... diff --git a/stubs/kafka-python/kafka/sasl/abc.pyi b/stubs/kafka-python/kafka/sasl/abc.pyi new file mode 100644 index 000000000000..52d76c08a27c --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/abc.pyi @@ -0,0 +1,14 @@ +import abc + +class SaslMechanism(metaclass=abc.ABCMeta): + @abc.abstractmethod + def __init__(self, **config): ... + @abc.abstractmethod + def auth_bytes(self): ... + @abc.abstractmethod + def receive(self, auth_bytes): ... + @abc.abstractmethod + def is_done(self): ... + @abc.abstractmethod + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/sasl/gssapi.pyi b/stubs/kafka-python/kafka/sasl/gssapi.pyi new file mode 100644 index 000000000000..2bbe75ee3526 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/gssapi.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +class SaslMechanismGSSAPI(SaslMechanism): + SASL_QOP_AUTH: int + SASL_QOP_AUTH_INT: int + SASL_QOP_AUTH_CONF: int + gssapi_name: Incomplete + auth_id: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/sasl/msk.pyi b/stubs/kafka-python/kafka/sasl/msk.pyi new file mode 100644 index 000000000000..3c3efed6fcc1 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/msk.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +log: Incomplete + +class SaslMechanismAwsMskIam(SaslMechanism): + host: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +class AwsMskIamClient: + UNRESERVED_CHARS: Incomplete + algorithm: str + expires: str + hashfunc: Incomplete + headers: Incomplete + version: str + service: str + action: Incomplete + datestamp: Incomplete + timestamp: Incomplete + host: Incomplete + access_key: Incomplete + secret_key: Incomplete + region: Incomplete + token: Incomplete + def __init__(self, host, access_key, secret_key, region, token=None) -> None: ... + def first_message(self): ... diff --git a/stubs/kafka-python/kafka/sasl/oauth.pyi b/stubs/kafka-python/kafka/sasl/oauth.pyi new file mode 100644 index 000000000000..089ad778c4f4 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/oauth.pyi @@ -0,0 +1,23 @@ +import abc +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +log: Incomplete + +class SaslMechanismOAuth(SaslMechanism): + token_provider: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +ABC: Incomplete + +class AbstractTokenProvider(ABC, metaclass=abc.ABCMeta): + def __init__(self, **config) -> None: ... + @abc.abstractmethod + def token(self): ... + def extensions(self): ... diff --git a/stubs/kafka-python/kafka/sasl/plain.pyi b/stubs/kafka-python/kafka/sasl/plain.pyi new file mode 100644 index 000000000000..be3f7961ad39 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/plain.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +log: Incomplete + +class SaslMechanismPlain(SaslMechanism): + username: Incomplete + password: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/sasl/scram.pyi b/stubs/kafka-python/kafka/sasl/scram.pyi new file mode 100644 index 000000000000..928d1efb094f --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/scram.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +log: Incomplete + +def xor_bytes(left, right): ... + +class SaslMechanismScram(SaslMechanism): + username: Incomplete + mechanism: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes): ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... + +class ScramClient: + MECHANISMS: Incomplete + nonce: Incomplete + auth_message: bytes + salted_password: Incomplete + user: Incomplete + password: Incomplete + hashfunc: Incomplete + hashname: Incomplete + stored_key: Incomplete + client_key: Incomplete + client_signature: Incomplete + client_proof: Incomplete + server_key: Incomplete + server_signature: Incomplete + def __init__(self, user, password, mechanism) -> None: ... + def first_message(self): ... + def process_server_first_message(self, server_first_message) -> None: ... + def hmac(self, key, msg): ... + def create_salted_password(self, salt, iterations) -> None: ... + def final_message(self): ... + def process_server_final_message(self, server_final_message) -> None: ... diff --git a/stubs/kafka-python/kafka/sasl/sspi.pyi b/stubs/kafka-python/kafka/sasl/sspi.pyi new file mode 100644 index 000000000000..600c382b4094 --- /dev/null +++ b/stubs/kafka-python/kafka/sasl/sspi.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete + +from kafka.sasl.abc import SaslMechanism + +log: Incomplete + +class SaslMechanismSSPI(SaslMechanism): + SASL_QOP_AUTH: int + SASL_QOP_AUTH_INT: int + SASL_QOP_AUTH_CONF: int + auth_id: Incomplete + def __init__(self, **config) -> None: ... + def auth_bytes(self): ... + def receive(self, auth_bytes) -> None: ... + def is_done(self): ... + def is_authenticated(self): ... + def auth_details(self): ... diff --git a/stubs/kafka-python/kafka/serializer/__init__.pyi b/stubs/kafka-python/kafka/serializer/__init__.pyi new file mode 100644 index 000000000000..b9caa9a2bcbb --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/__init__.pyi @@ -0,0 +1 @@ +from kafka.serializer.abstract import Deserializer as Deserializer, Serializer as Serializer diff --git a/stubs/kafka-python/kafka/serializer/abstract.pyi b/stubs/kafka-python/kafka/serializer/abstract.pyi new file mode 100644 index 000000000000..5e57c8b778a0 --- /dev/null +++ b/stubs/kafka-python/kafka/serializer/abstract.pyi @@ -0,0 +1,15 @@ +import abc + +class Serializer(metaclass=abc.ABCMeta): + __meta__ = abc.ABCMeta + def __init__(self, **config) -> None: ... + @abc.abstractmethod + def serialize(self, topic, value): ... + def close(self) -> None: ... + +class Deserializer(metaclass=abc.ABCMeta): + __meta__ = abc.ABCMeta + def __init__(self, **config) -> None: ... + @abc.abstractmethod + def deserialize(self, topic, bytes_): ... + def close(self) -> None: ... diff --git a/stubs/kafka-python/kafka/socks5_wrapper.pyi b/stubs/kafka-python/kafka/socks5_wrapper.pyi new file mode 100644 index 000000000000..871e8b20344f --- /dev/null +++ b/stubs/kafka-python/kafka/socks5_wrapper.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +log: Incomplete + +class ProxyConnectionStates: + DISCONNECTED: str + CONNECTING: str + NEGOTIATE_PROPOSE: str + NEGOTIATING: str + AUTHENTICATING: str + REQUEST_SUBMIT: str + REQUESTING: str + READ_ADDRESS: str + COMPLETE: str + +class Socks5Wrapper: + def __init__(self, proxy_url, afi) -> None: ... + @classmethod + def is_inet_4_or_6(cls, gai): ... + @classmethod + def dns_lookup(cls, host, port, afi=...): ... + @classmethod + def use_remote_lookup(cls, proxy_url): ... + def socket(self, family, sock_type): ... + def connect_ex(self, addr): ... diff --git a/stubs/kafka-python/kafka/structs.pyi b/stubs/kafka-python/kafka/structs.pyi new file mode 100644 index 000000000000..997afe9492f3 --- /dev/null +++ b/stubs/kafka-python/kafka/structs.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +class TopicPartition(NamedTuple): + topic: str + partition: int + +class BrokerMetadata(NamedTuple): + nodeId: int + host: str + port: int + rack: str | None + +class PartitionMetadata(NamedTuple): + topic: str + partition: int + leader: int + leader_epoch: int | None + replicas: list[int] + isr: list[int] + offline_replicas: list[int] + error: Incomplete + +class OffsetAndMetadata(NamedTuple): + offset: int + metadata: str + leader_epoch: int + +class OffsetAndTimestamp(NamedTuple): + offset: int + timestamp: int + leader_epoch: int + +class MemberInformation(NamedTuple): + member_id: str + client_id: str + client_host: str + member_metadata: Incomplete + member_assignment: Incomplete + +class GroupInformation(NamedTuple): + error_code: int + group: str + state: str + protocol_type: str + protocol: str + members: list[MemberInformation] + authorized_operations: list[str] + +class RetryOptions(NamedTuple): + limit: int + backoff_ms: int + retry_on_timeouts: bool diff --git a/stubs/kafka-python/kafka/util.pyi b/stubs/kafka-python/kafka/util.pyi new file mode 100644 index 000000000000..4783d02b462a --- /dev/null +++ b/stubs/kafka-python/kafka/util.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +MAX_INT: Incomplete +TO_SIGNED: Incomplete + +def crc32(data): ... + +class Timer: + def __init__(self, timeout_ms, error_message=None, start_at=None) -> None: ... + @property + def expired(self): ... + @property + def timeout_ms(self): ... + @property + def elapsed_ms(self): ... + def maybe_raise(self) -> None: ... + +TOPIC_MAX_LENGTH: int +TOPIC_LEGAL_CHARS: Incomplete + +def ensure_valid_topic_name(topic) -> None: ... + +class WeakMethod: + target: Incomplete + method: Incomplete + def __init__(self, object_dot_method) -> None: ... + def __call__(self, *args, **kwargs): ... + def __hash__(self): ... + def __eq__(self, other): ... + +class Dict(dict[Incomplete, Incomplete]): ... + +def synchronized(func: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/stubs/kafka-python/kafka/version.pyi b/stubs/kafka-python/kafka/version.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/kafka-python/kafka/version.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/keyboard/@tests/stubtest_allowlist.txt b/stubs/keyboard/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c508422424b0 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# scan_code *should* never be None in real use. This is also according to docs. +keyboard._keyboard_event.KeyboardEvent.scan_code +# TODO: Should this be allowlisted? +keyboard.__main__ + +keyboard._canonical_names.basestring +keyboard._keyboard_event.basestring diff --git a/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt b/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..cdf3ec0e6861 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +# Defaults don't align with possible values +keyboard.mouse.on_button +keyboard.mouse.wait diff --git a/stubs/keyboard/@tests/stubtest_allowlist_linux.txt b/stubs/keyboard/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..cdf3ec0e6861 --- /dev/null +++ b/stubs/keyboard/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +# Defaults don't align with possible values +keyboard.mouse.on_button +keyboard.mouse.wait diff --git a/stubs/keyboard/METADATA.toml b/stubs/keyboard/METADATA.toml new file mode 100644 index 000000000000..cda767908896 --- /dev/null +++ b/stubs/keyboard/METADATA.toml @@ -0,0 +1,9 @@ +version = "0.13.*" +upstream-repository = "https://github.com/boppreh/keyboard" + +# [tool.stubtest] +# While the stubs slightly differ on Windows vs Linux. +# It's only by possible mouse buttons and event literal types. +# As well as returning a tuple of int/long from keyboard.mouse.get_position +# The "mouse" module is obsoleted by the "mouse" package. +# ci-platforms = ["linux"] diff --git a/stubs/keyboard/keyboard/__init__.pyi b/stubs/keyboard/keyboard/__init__.pyi new file mode 100644 index 000000000000..a858acfa7658 --- /dev/null +++ b/stubs/keyboard/keyboard/__init__.pyi @@ -0,0 +1,113 @@ +from collections.abc import Callable, Generator, Iterable, Sequence +from queue import Queue +from threading import Event as _UninterruptibleEvent +from typing import TypeAlias + +from ._canonical_names import all_modifiers as all_modifiers, sided_modifiers as sided_modifiers +from ._keyboard_event import KEY_DOWN as KEY_DOWN, KEY_UP as KEY_UP, KeyboardEvent as KeyboardEvent + +_Key: TypeAlias = int | str +_ScanCodeList: TypeAlias = list[int] | tuple[int, ...] +_ParseableHotkey: TypeAlias = _Key | list[int | _ScanCodeList] | tuple[int | _ScanCodeList, ...] +_Callback: TypeAlias = Callable[[KeyboardEvent], bool | None] | Callable[[], bool | None] +# mypy doesn't support PEP 646's TypeVarTuple yet: https://github.com/python/mypy/issues/12280 +# _Ts = TypeVarTuple("_Ts") +_Ts: TypeAlias = tuple[object, ...] + +version: str + +class _Event(_UninterruptibleEvent): + def wait(self) -> None: ... # type: ignore[override] # Actual implementation + +def is_modifier(key: _Key | None) -> bool: ... +def key_to_scan_codes(key: _ParseableHotkey, error_if_missing: bool = True) -> tuple[int, ...]: ... +def parse_hotkey(hotkey: _ParseableHotkey) -> tuple[tuple[tuple[int, ...], ...], ...]: ... +def send(hotkey: _ParseableHotkey, do_press: bool = True, do_release: bool = True) -> None: ... + +press_and_release = send + +def press(hotkey: _ParseableHotkey) -> None: ... +def release(hotkey: _ParseableHotkey) -> None: ... + +# is_pressed cannot check multi-step hotkeys, so not using _ParseableHotkey + +def is_pressed(hotkey: _Key | _ScanCodeList) -> bool: ... +def call_later(fn: Callable[..., None], args: _Ts = (), delay: float = 0.001) -> None: ... +def hook(callback: _Callback, suppress: bool = False, on_remove: Callable[[], None] = ...) -> Callable[[], None]: ... +def on_press(callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_release(callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def hook_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_press_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def on_release_key(key: _ParseableHotkey, callback: _Callback, suppress: bool = False) -> Callable[[], None]: ... +def unhook(remove: _Callback) -> None: ... + +unhook_key = unhook + +def unhook_all() -> None: ... +def block_key(key: _ParseableHotkey) -> Callable[[], None]: ... + +unblock_key = unhook_key + +def remap_key(src: _ParseableHotkey, dst: _ParseableHotkey) -> Callable[[], None]: ... + +unremap_key = unhook_key + +def parse_hotkey_combinations(hotkey: _ParseableHotkey) -> tuple[tuple[tuple[int, ...], ...], ...]: ... +def add_hotkey( + hotkey: _ParseableHotkey, + callback: Callable[..., bool | None], + args: _Ts = (), + suppress: bool = False, + timeout: float = 1, + trigger_on_release: bool = False, +) -> Callable[[], None]: ... + +register_hotkey = add_hotkey + +def remove_hotkey(hotkey_or_callback: _ParseableHotkey | _Callback) -> None: ... + +unregister_hotkey = remove_hotkey +clear_hotkey = remove_hotkey + +def unhook_all_hotkeys() -> None: ... + +unregister_all_hotkeys = unhook_all_hotkeys +remove_all_hotkeys = unhook_all_hotkeys +clear_all_hotkeys = unhook_all_hotkeys + +def remap_hotkey( + src: _ParseableHotkey, dst: _ParseableHotkey, suppress: bool = True, trigger_on_release: bool = False +) -> Callable[[], None]: ... + +unremap_hotkey = remove_hotkey + +def stash_state() -> list[int]: ... +def restore_state(scan_codes: Iterable[int]) -> None: ... +def restore_modifiers(scan_codes: Iterable[int]) -> None: ... +def write(text: str, delay: float = 0, restore_state_after: bool = True, exact: bool | None = None) -> None: ... +def wait(hotkey: _ParseableHotkey | None = None, suppress: bool = False, trigger_on_release: bool = False) -> None: ... +def get_hotkey_name(names: Iterable[str] | None = None) -> str: ... +def read_event(suppress: bool = False) -> KeyboardEvent: ... +def read_key(suppress: bool = False) -> _Key: ... +def read_hotkey(suppress: bool = True) -> str: ... +def get_typed_strings(events: Iterable[KeyboardEvent], allow_backspace: bool = True) -> Generator[str]: ... +def start_recording( + recorded_events_queue: Queue[KeyboardEvent] | None = None, +) -> tuple[Queue[KeyboardEvent], Callable[[], None]]: ... +def stop_recording() -> list[KeyboardEvent]: ... +def record(until: str = "escape", suppress: bool = False, trigger_on_release: bool = False) -> list[KeyboardEvent]: ... +def play(events: Iterable[KeyboardEvent], speed_factor: float = 1.0) -> None: ... + +replay = play + +def add_word_listener( + word: str, callback: _Callback, triggers: Sequence[str] = ["space"], match_suffix: bool = False, timeout: float = 2 +) -> Callable[[], None]: ... +def remove_word_listener(word_or_handler: str | _Callback) -> None: ... +def add_abbreviation( + source_text: str, replacement_text: str, match_suffix: bool = False, timeout: float = 2 +) -> Callable[[], None]: ... + +register_word_listener = add_word_listener +register_abbreviation = add_abbreviation +remove_abbreviation = remove_word_listener diff --git a/stubs/keyboard/keyboard/_canonical_names.pyi b/stubs/keyboard/keyboard/_canonical_names.pyi new file mode 100644 index 000000000000..8a0c3a007643 --- /dev/null +++ b/stubs/keyboard/keyboard/_canonical_names.pyi @@ -0,0 +1,5 @@ +canonical_names: dict[str, str] +sided_modifiers: set[str] +all_modifiers: set[str] + +def normalize_name(name: str) -> str: ... diff --git a/stubs/keyboard/keyboard/_generic.pyi b/stubs/keyboard/keyboard/_generic.pyi new file mode 100644 index 000000000000..a1784b3d89a8 --- /dev/null +++ b/stubs/keyboard/keyboard/_generic.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable +from queue import Queue +from threading import Lock, Thread +from typing import ClassVar, Literal, TypeAlias + +from ._keyboard_event import KeyboardEvent +from ._mouse_event import _MouseEvent + +_Event: TypeAlias = KeyboardEvent | _MouseEvent + +class GenericListener: + lock: ClassVar[Lock] + handlers: list[Callable[[_Event], bool | None]] + listening: bool + queue: Queue[_Event] + listening_thread: Thread | None + processing_thread: Thread | None + def invoke_handlers(self, event: _Event) -> Literal[1] | None: ... + def start_if_necessary(self) -> None: ... + def pre_process_event(self, event: _Event) -> None: ... + def process(self) -> None: ... + def add_handler(self, handler: Callable[[_Event], bool | None]) -> None: ... + def remove_handler(self, handler: Callable[[_Event], bool | None]) -> None: ... diff --git a/stubs/keyboard/keyboard/_keyboard_event.pyi b/stubs/keyboard/keyboard/_keyboard_event.pyi new file mode 100644 index 000000000000..94746c56abba --- /dev/null +++ b/stubs/keyboard/keyboard/_keyboard_event.pyi @@ -0,0 +1,28 @@ +from typing import Literal + +from ._canonical_names import canonical_names as canonical_names, normalize_name as normalize_name + +KEY_DOWN: Literal["down"] +KEY_UP: Literal["up"] + +class KeyboardEvent: + event_type: Literal["down", "up"] | None + scan_code: int + name: str | None + time: float | None + device: str | None + modifiers: tuple[str, ...] | None + is_keypad: bool | None + + def __init__( + self, + event_type: Literal["down", "up"] | None, + scan_code: int, + name: str | None = None, + time: float | None = None, + device: str | None = None, + modifiers: tuple[str, ...] | None = None, + is_keypad: bool | None = None, + ) -> None: ... + def to_json(self, ensure_ascii: bool = False) -> str: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/keyboard/keyboard/_mouse_event.pyi b/stubs/keyboard/keyboard/_mouse_event.pyi new file mode 100644 index 000000000000..e9e95b80e112 --- /dev/null +++ b/stubs/keyboard/keyboard/_mouse_event.pyi @@ -0,0 +1,42 @@ +import sys +from typing import Literal, NamedTuple, TypeAlias + +_MouseEvent: TypeAlias = ButtonEvent | WheelEvent | MoveEvent # noqa: Y047 # Used outside + +LEFT: Literal["left"] +RIGHT: Literal["right"] +MIDDLE: Literal["middle"] +X: Literal["x"] +X2: Literal["x2"] + +UP: Literal["up"] +DOWN: Literal["down"] +DOUBLE: Literal["double"] +WHEEL: Literal["wheel"] + +VERTICAL: Literal["vertical"] +HORIZONTAL: Literal["horizontal"] + +if sys.platform == "linux" or sys.platform == "win32": + _MouseButton: TypeAlias = Literal["left", "right", "middle", "x", "x2"] +else: + _MouseButton: TypeAlias = Literal["left", "right", "middle"] + +if sys.platform == "win32": + _MouseEventType: TypeAlias = Literal["up", "down", "double", "wheel"] +else: + _MouseEventType: TypeAlias = Literal["up", "down"] + +class ButtonEvent(NamedTuple): + event_type: _MouseEventType + button: _MouseButton + time: float + +class WheelEvent(NamedTuple): + delta: int + time: float + +class MoveEvent(NamedTuple): + x: int + y: int + time: float diff --git a/stubs/keyboard/keyboard/mouse.pyi b/stubs/keyboard/keyboard/mouse.pyi new file mode 100644 index 000000000000..6105f85d59a9 --- /dev/null +++ b/stubs/keyboard/keyboard/mouse.pyi @@ -0,0 +1,83 @@ +import sys +from collections.abc import Callable, Iterable +from ctypes import c_long +from typing import Literal, SupportsInt, TypeAlias, TypeVar + +from ._generic import GenericListener as _GenericListener +from ._mouse_event import ( + DOUBLE as DOUBLE, + DOWN as DOWN, + LEFT as LEFT, + MIDDLE as MIDDLE, + RIGHT as RIGHT, + UP as UP, + X2 as X2, + ButtonEvent as ButtonEvent, + MoveEvent as MoveEvent, + WheelEvent as WheelEvent, + X as X, + _MouseButton, + _MouseEvent, + _MouseEventType, +) + +# mypy doesn't support PEP 646's TypeVarTuple yet: https://github.com/python/mypy/issues/12280 +# _Ts = TypeVarTuple("_Ts") +_Ts: TypeAlias = tuple[object, ...] +_Callback: TypeAlias = Callable[[_MouseEvent], bool | None] +_C = TypeVar("_C", bound=_Callback) + +class _MouseListener(_GenericListener): + def init(self) -> None: ... + def pre_process_event( # type: ignore[override] # Mouse specific events and return + self, event: _MouseEvent + ) -> Literal[True]: ... + def listen(self) -> None: ... + +def is_pressed(button: _MouseButton = "left") -> bool: ... +def press(button: _MouseButton = "left") -> None: ... +def release(button: _MouseButton = "left") -> None: ... +def click(button: _MouseButton = "left") -> None: ... +def double_click(button: _MouseButton = "left") -> None: ... +def right_click() -> None: ... +def wheel(delta: int = 1) -> None: ... +def move(x: SupportsInt, y: SupportsInt, absolute: bool = True, duration: float = 0) -> None: ... +def drag(start_x: int, start_y: int, end_x: int, end_y: int, absolute: bool = True, duration: float = 0) -> None: ... +def on_button( + callback: Callable[..., None], + args: _Ts = (), + # Omitting default: Darwin has no x and x2 + buttons: list[_MouseButton] | tuple[_MouseButton, ...] | _MouseButton = ..., + # Omitting default: Darwin and Linux don't have "double", yet the defaults includes it + types: list[_MouseEventType] | tuple[_MouseEventType, ...] | _MouseEventType = ..., +) -> _Callback: ... +def on_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_double_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_right_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def on_middle_click(callback: Callable[..., None], args: _Ts = ()) -> _Callback: ... +def wait( + button: _MouseButton = "left", + # Omitting default: Darwin and Linux don't have "double", yet the defaults includes it + target_types: tuple[_MouseEventType, ...] = ..., +) -> None: ... + +if sys.platform == "win32": + def get_position() -> tuple[c_long, c_long]: ... + +else: + def get_position() -> tuple[int, int]: ... + +def hook(callback: _C) -> _C: ... +def unhook(callback: _Callback) -> None: ... +def unhook_all() -> None: ... +def record(button: _MouseButton = "right", target_types: tuple[_MouseEventType] = ("down",)) -> _MouseEvent: ... +def play( + events: Iterable[_MouseEvent], + speed_factor: float = 1.0, + include_clicks: bool = True, + include_moves: bool = True, + include_wheel: bool = True, +) -> None: ... + +replay = play +hold = press diff --git a/stubs/ldap3/@tests/stubtest_allowlist.txt b/stubs/ldap3/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c1fe27b112fb --- /dev/null +++ b/stubs/ldap3/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +ldap3.utils.ordDict # file is available only in Python 2.6 diff --git a/stubs/ldap3/METADATA.toml b/stubs/ldap3/METADATA.toml new file mode 100644 index 000000000000..d50ccbe8478f --- /dev/null +++ b/stubs/ldap3/METADATA.toml @@ -0,0 +1,10 @@ +version = "2.9.*" +upstream-repository = "https://github.com/cannatag/ldap3" +dependencies = ["types-pyasn1"] + +[tool.stubtest] +apt-dependencies = ["libkrb5-dev"] +# No need to install on the CI. Leaving here as information for MacOs/Windows contributors. +# brew-dependencies = ["krb5"] +# choco-dependencies = ["mitkerberos"] +stubtest-dependencies = ["gssapi"] diff --git a/stubs/ldap3/ldap3/__init__.pyi b/stubs/ldap3/ldap3/__init__.pyi new file mode 100644 index 000000000000..7cb7544c04fa --- /dev/null +++ b/stubs/ldap3/ldap3/__init__.pyi @@ -0,0 +1,103 @@ +from typing import Literal + +from .abstract.attrDef import AttrDef as AttrDef +from .abstract.attribute import ( + Attribute as Attribute, + OperationalAttribute as OperationalAttribute, + WritableAttribute as WritableAttribute, +) +from .abstract.cursor import Reader as Reader, Writer as Writer +from .abstract.entry import Entry as Entry, WritableEntry as WritableEntry +from .abstract.objectDef import ObjectDef as ObjectDef +from .core.connection import Connection as Connection +from .core.pooling import ServerPool as ServerPool +from .core.rdns import ReverseDnsSetting as ReverseDnsSetting +from .core.server import Server as Server +from .core.tls import Tls as Tls +from .protocol.rfc4512 import DsaInfo as DsaInfo, SchemaInfo as SchemaInfo +from .utils.config import get_config_parameter as get_config_parameter, set_config_parameter as set_config_parameter +from .version import __description__ as __description__, __status__ as __status__, __url__ as __url__ + +ANONYMOUS: Literal["ANONYMOUS"] +SIMPLE: Literal["SIMPLE"] +SASL: Literal["SASL"] +NTLM: Literal["NTLM"] + +EXTERNAL: Literal["EXTERNAL"] +DIGEST_MD5: Literal["DIGEST-MD5"] +KERBEROS: Literal["GSSAPI"] +GSSAPI: Literal["GSSAPI"] +PLAIN: Literal["PLAIN"] + +AUTO_BIND_DEFAULT: Literal["DEFAULT"] +AUTO_BIND_NONE: Literal["NONE"] +AUTO_BIND_NO_TLS: Literal["NO_TLS"] +AUTO_BIND_TLS_BEFORE_BIND: Literal["TLS_BEFORE_BIND"] +AUTO_BIND_TLS_AFTER_BIND: Literal["TLS_AFTER_BIND"] + +IP_SYSTEM_DEFAULT: Literal["IP_SYSTEM_DEFAULT"] +IP_V4_ONLY: Literal["IP_V4_ONLY"] +IP_V6_ONLY: Literal["IP_V6_ONLY"] +IP_V4_PREFERRED: Literal["IP_V4_PREFERRED"] +IP_V6_PREFERRED: Literal["IP_V6_PREFERRED"] + +BASE: Literal["BASE"] +LEVEL: Literal["LEVEL"] +SUBTREE: Literal["SUBTREE"] + +DEREF_NEVER: Literal["NEVER"] +DEREF_SEARCH: Literal["SEARCH"] +DEREF_BASE: Literal["FINDING_BASE"] +DEREF_ALWAYS: Literal["ALWAYS"] + +ALL_ATTRIBUTES: Literal["*"] +NO_ATTRIBUTES: Literal["1.1"] +ALL_OPERATIONAL_ATTRIBUTES: Literal["+"] + +MODIFY_ADD: Literal["MODIFY_ADD"] +MODIFY_DELETE: Literal["MODIFY_DELETE"] +MODIFY_REPLACE: Literal["MODIFY_REPLACE"] +MODIFY_INCREMENT: Literal["MODIFY_INCREMENT"] + +SYNC: Literal["SYNC"] +SAFE_SYNC: Literal["SAFE_SYNC"] +SAFE_RESTARTABLE: Literal["SAFE_RESTARTABLE"] +ASYNC: Literal["ASYNC"] +LDIF: Literal["LDIF"] +RESTARTABLE: Literal["RESTARTABLE"] +REUSABLE: Literal["REUSABLE"] +MOCK_SYNC: Literal["MOCK_SYNC"] +MOCK_ASYNC: Literal["MOCK_ASYNC"] +ASYNC_STREAM: Literal["ASYNC_STREAM"] + +NONE: Literal["NO_INFO"] +DSA: Literal["DSA"] +SCHEMA: Literal["SCHEMA"] +ALL: Literal["ALL"] + +OFFLINE_EDIR_8_8_8: Literal["EDIR_8_8_8"] +OFFLINE_EDIR_9_1_4: Literal["EDIR_9_1_4"] +OFFLINE_AD_2012_R2: Literal["AD_2012_R2"] +OFFLINE_SLAPD_2_4: Literal["SLAPD_2_4"] +OFFLINE_DS389_1_3_3: Literal["DS389_1_3_3"] + +FIRST: Literal["FIRST"] +ROUND_ROBIN: Literal["ROUND_ROBIN"] +RANDOM: Literal["RANDOM"] + +HASHED_NONE: Literal["PLAIN"] +HASHED_SHA: Literal["SHA"] +HASHED_SHA256: Literal["SHA256"] +HASHED_SHA384: Literal["SHA384"] +HASHED_SHA512: Literal["SHA512"] +HASHED_MD5: Literal["MD5"] +HASHED_SALTED_SHA: Literal["SALTED_SHA"] +HASHED_SALTED_SHA256: Literal["SALTED_SHA256"] +HASHED_SALTED_SHA384: Literal["SALTED_SHA384"] +HASHED_SALTED_SHA512: Literal["SALTED_SHA512"] +HASHED_SALTED_MD5: Literal["SALTED_MD5"] + +NUMERIC_TYPES: tuple[type, ...] +INTEGER_TYPES: tuple[type, ...] +STRING_TYPES: tuple[type, ...] +SEQUENCE_TYPES: tuple[type, ...] diff --git a/stubs/ldap3/ldap3/abstract/__init__.pyi b/stubs/ldap3/ldap3/abstract/__init__.pyi new file mode 100644 index 000000000000..2e5fe21aca1c --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/__init__.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +STATUS_INIT: str +STATUS_VIRTUAL: str +STATUS_MANDATORY_MISSING: str +STATUS_READ: str +STATUS_WRITABLE: str +STATUS_PENDING_CHANGES: str +STATUS_COMMITTED: str +STATUS_READY_FOR_DELETION: str +STATUS_READY_FOR_MOVING: str +STATUS_READY_FOR_RENAMING: str +STATUS_DELETED: str +STATUSES: Incomplete +INITIAL_STATUSES: Incomplete diff --git a/stubs/ldap3/ldap3/abstract/attrDef.pyi b/stubs/ldap3/ldap3/abstract/attrDef.pyi new file mode 100644 index 000000000000..b59e04f5df98 --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/attrDef.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +class AttrDef: + name: Incomplete + key: Incomplete + validate: Incomplete + pre_query: Incomplete + post_query: Incomplete + default: Incomplete + dereference_dn: Incomplete + description: Incomplete + mandatory: Incomplete + single_value: Incomplete + oid_info: Incomplete + other_names: Incomplete + def __init__( + self, + name, + key=None, + validate=None, + pre_query=None, + post_query=None, + default=..., + dereference_dn=None, + description=None, + mandatory: bool = False, + single_value=None, + alias=None, + ) -> None: ... + def __eq__(self, other): ... + def __lt__(self, other): ... + def __hash__(self) -> int: ... + def __setattr__(self, key: str, value) -> None: ... diff --git a/stubs/ldap3/ldap3/abstract/attribute.pyi b/stubs/ldap3/ldap3/abstract/attribute.pyi new file mode 100644 index 000000000000..8040ae647a15 --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/attribute.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +class Attribute: + key: Incomplete + definition: Incomplete + values: Incomplete + raw_values: Incomplete + response: Incomplete + entry: Incomplete + cursor: Incomplete + other_names: Incomplete + def __init__(self, attr_def, entry, cursor) -> None: ... + def __len__(self) -> int: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + @property + def value(self): ... + +class OperationalAttribute(Attribute): ... + +class WritableAttribute(Attribute): + def __iadd__(self, other): ... + def __isub__(self, other): ... + def add(self, values) -> None: ... + def set(self, values) -> None: ... + def delete(self, values) -> None: ... + def remove(self) -> None: ... + def discard(self) -> None: ... + @property + def virtual(self): ... + @property + def changes(self): ... diff --git a/stubs/ldap3/ldap3/abstract/cursor.pyi b/stubs/ldap3/ldap3/abstract/cursor.pyi new file mode 100644 index 000000000000..9a22b44ac9e2 --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/cursor.pyi @@ -0,0 +1,106 @@ +from _typeshed import Incomplete +from typing import NamedTuple + +class Operation(NamedTuple): + request: Incomplete + result: Incomplete + response: Incomplete + +class Cursor: + connection: Incomplete + get_operational_attributes: Incomplete + definition: Incomplete + attributes: Incomplete + controls: Incomplete + execution_time: Incomplete + entries: Incomplete + schema: Incomplete + def __init__( + self, + connection, + object_def, + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, + ) -> None: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def match_dn(self, dn): ... + def match(self, attributes, value): ... + def remove(self, entry) -> None: ... + @property + def operations(self): ... + @property + def errors(self): ... + @property + def failed(self): ... + +class Reader(Cursor): + entry_class: Incomplete + attribute_class: Incomplete + entry_initial_status: Incomplete + sub_tree: Incomplete + base: Incomplete + dereference_aliases: Incomplete + validated_query: Incomplete + query_filter: Incomplete + def __init__( + self, + connection, + object_def, + base, + query: str = "", + components_in_and: bool = True, + sub_tree: bool = True, + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, + ) -> None: ... + + @property + def query(self): ... + @query.setter + def query(self, value) -> None: ... + + @property + def components_in_and(self): ... + @components_in_and.setter + def components_in_and(self, value) -> None: ... + + def clear(self) -> None: ... + execution_time: Incomplete + entries: Incomplete + def reset(self) -> None: ... + def search(self, attributes=None): ... + def search_object(self, entry_dn=None, attributes=None): ... + def search_level(self, attributes=None): ... + def search_subtree(self, attributes=None): ... + def search_paged(self, paged_size, paged_criticality: bool = True, generator: bool = True, attributes=None): ... + +class Writer(Cursor): + entry_class: Incomplete + attribute_class: Incomplete + entry_initial_status: Incomplete + @staticmethod + def from_cursor(cursor, connection=None, object_def=None, custom_validator=None): ... + @staticmethod + def from_response(connection, object_def, response=None): ... + dereference_aliases: Incomplete + def __init__( + self, + connection, + object_def, + get_operational_attributes: bool = False, + attributes=None, + controls=None, + auxiliary_class=None, + ) -> None: ... + execution_time: Incomplete + def commit(self, refresh: bool = True): ... + def discard(self) -> None: ... + def new(self, dn): ... + def refresh_entry(self, entry, tries: int = 4, seconds: int = 2): ... diff --git a/stubs/ldap3/ldap3/abstract/entry.pyi b/stubs/ldap3/ldap3/abstract/entry.pyi new file mode 100644 index 000000000000..1b2df740d130 --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/entry.pyi @@ -0,0 +1,76 @@ +from _typeshed import Incomplete + +class EntryState: + dn: Incomplete + status: Incomplete + attributes: Incomplete + raw_attributes: Incomplete + response: Incomplete + cursor: Incomplete + origin: Incomplete + read_time: Incomplete + changes: Incomplete + definition: Incomplete + def __init__(self, dn, cursor) -> None: ... + def set_status(self, status) -> None: ... + @property + def entry_raw_attributes(self): ... + +class EntryBase: + def __init__(self, dn, cursor) -> None: ... + def __iter__(self): ... + def __contains__(self, item): ... + def __getattr__(self, item: str): ... + def __setattr__(self, item: str, value) -> None: ... + def __getitem__(self, item): ... + def __eq__(self, other): ... + def __lt__(self, other): ... + @property + def entry_dn(self): ... + @property + def entry_cursor(self): ... + @property + def entry_status(self): ... + @property + def entry_definition(self): ... + @property + def entry_raw_attributes(self): ... + def entry_raw_attribute(self, name): ... + @property + def entry_mandatory_attributes(self): ... + @property + def entry_attributes(self): ... + @property + def entry_attributes_as_dict(self): ... + @property + def entry_read_time(self): ... + def entry_to_json( + self, + raw: bool = False, + indent: int = 4, + sort: bool = True, + stream=None, + checked_attributes: bool = True, + include_empty: bool = True, + ): ... + def entry_to_ldif(self, all_base64: bool = False, line_separator=None, sort_order=None, stream=None): ... + +class Entry(EntryBase): + def entry_writable( + self, object_def=None, writer_cursor=None, attributes=None, custom_validator=None, auxiliary_class=None + ): ... + +class WritableEntry(EntryBase): + def __setitem__(self, key, value) -> None: ... + def __setattr__(self, item: str, value) -> None: ... + def __getattr__(self, item: str): ... + @property + def entry_virtual_attributes(self): ... + def entry_commit_changes(self, refresh: bool = True, controls=None, clear_history: bool = True): ... + def entry_discard_changes(self) -> None: ... + def entry_delete(self) -> None: ... + def entry_refresh(self, tries: int = 4, seconds: int = 2): ... + def entry_move(self, destination_dn) -> None: ... + def entry_rename(self, new_name) -> None: ... + @property + def entry_changes(self): ... diff --git a/stubs/ldap3/ldap3/abstract/objectDef.pyi b/stubs/ldap3/ldap3/abstract/objectDef.pyi new file mode 100644 index 000000000000..4aaefa21448b --- /dev/null +++ b/stubs/ldap3/ldap3/abstract/objectDef.pyi @@ -0,0 +1,15 @@ +class ObjectDef: + def __init__(self, object_class=None, schema=None, custom_validator=None, auxiliary_class=None) -> None: ... + def __getitem__(self, item): ... + def __getattr__(self, item: str): ... + def __setattr__(self, key: str, value) -> None: ... + def __iadd__(self, other): ... + def __isub__(self, other): ... + def __iter__(self): ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __contains__(self, item): ... + def add_from_schema(self, attribute_name, mandatory: bool = False) -> None: ... + def add_attribute(self, definition=None) -> None: ... + def remove_attribute(self, item) -> None: ... + def clear_attributes(self) -> None: ... diff --git a/stubs/ldap3/ldap3/core/__init__.pyi b/stubs/ldap3/ldap3/core/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/core/connection.pyi b/stubs/ldap3/ldap3/core/connection.pyi new file mode 100644 index 000000000000..10cb20008e94 --- /dev/null +++ b/stubs/ldap3/ldap3/core/connection.pyi @@ -0,0 +1,182 @@ +from _collections_abc import Generator, dict_keys +from _typeshed import Incomplete, ReadableBuffer +from types import TracebackType +from typing import Literal, TypeAlias +from typing_extensions import Self + +from pyasn1.type.base import Asn1Item + +from .pooling import ServerPool +from .server import Server + +SASL_AVAILABLE_MECHANISMS: Incomplete +CLIENT_STRATEGIES: Incomplete + +_ServerSequence: TypeAlias = ( + set[Server] | list[Server] | tuple[Server, ...] | Generator[Server, None, None] | dict_keys[Server, Incomplete] +) + +class Connection: + connection_lock: Incomplete + last_error: str + strategy_type: Incomplete + user: Incomplete + password: Incomplete + authentication: Incomplete + version: Incomplete + auto_referrals: Incomplete + request: Incomplete + response: Incomplete | None + result: Incomplete + bound: bool + listening: bool + closed: bool + auto_bind: Incomplete + sasl_mechanism: Incomplete + sasl_credentials: Incomplete + socket: Incomplete + tls_started: bool + sasl_in_progress: bool + read_only: Incomplete + lazy: Incomplete + pool_name: Incomplete + pool_size: int | None + cred_store: Incomplete + pool_lifetime: Incomplete + pool_keepalive: Incomplete + starting_tls: bool + check_names: Incomplete + raise_exceptions: Incomplete + auto_range: Incomplete + extend: Incomplete + fast_decoder: Incomplete + receive_timeout: Incomplete + empty_attributes: Incomplete + use_referral_cache: Incomplete + auto_escape: Incomplete + auto_encode: Incomplete + source_address: Incomplete + source_port_list: Incomplete + server_pool: Incomplete | None + server: Incomplete + strategy: Incomplete + send: Incomplete + open: Incomplete + get_response: Incomplete + post_send_single_response: Incomplete + post_send_search: Incomplete + def __init__( + self, + server: Server | str | _ServerSequence | ServerPool, + user: str | None = None, + password: str | None = None, + auto_bind: Literal["DEFAULT", "NONE", "NO_TLS", "TLS_BEFORE_BIND", "TLS_AFTER_BIND"] | bool = "DEFAULT", + version: int = 3, + authentication: Literal["ANONYMOUS", "SIMPLE", "SASL", "NTLM"] | None = None, + client_strategy: Literal[ + "SYNC", + "SAFE_RESTARTABLE", + "SAFE_SYNC", + "ASYNC", + "LDIF", + "RESTARTABLE", + "REUSABLE", + "MOCK_SYNC", + "MOCK_ASYNC", + "ASYNC_STREAM", + ] = "SYNC", + auto_referrals: bool = True, + auto_range: bool = True, + sasl_mechanism: str | None = None, + sasl_credentials=None, + check_names: bool = True, + collect_usage: bool = False, + read_only: bool = False, + lazy: bool = False, + raise_exceptions: bool = False, + pool_name: str | None = None, + pool_size: int | None = None, + pool_lifetime: int | None = None, + cred_store=None, + fast_decoder: bool = True, + receive_timeout=None, + return_empty_attributes: bool = True, + use_referral_cache: bool = False, + auto_escape: bool = True, + auto_encode: bool = True, + pool_keepalive=None, + source_address: str | None = None, + source_port: int | None = None, + source_port_list=None, + ) -> None: ... + def repr_with_sensitive_data_stripped(self): ... + + @property + def stream(self): ... + @stream.setter + def stream(self, value) -> None: ... + + @property + def usage(self): ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> Literal[False] | None: ... + def bind(self, read_server_info: bool = True, controls=None): ... + def rebind( + self, + user=None, + password=None, + authentication=None, + sasl_mechanism=None, + sasl_credentials=None, + read_server_info: bool = True, + controls=None, + ): ... + def unbind(self, controls=None): ... + def search( + self, + search_base: str, + search_filter: str, + search_scope: Literal["BASE", "LEVEL", "SUBTREE"] = "SUBTREE", + dereference_aliases: Literal["NEVER", "SEARCH", "FINDING_BASE", "ALWAYS"] = "ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int | None = None, + paged_criticality: bool = False, + paged_cookie: str | bytes | None = None, + auto_escape: bool | None = None, + ): ... + def compare(self, dn, attribute, value, controls=None): ... + def add(self, dn, object_class=None, attributes=None, controls=None): ... + def delete(self, dn, controls=None): ... + def modify(self, dn, changes, controls=None): ... + def modify_dn(self, dn, relative_dn, delete_old_dn: bool = True, new_superior=None, controls=None): ... + def abandon(self, message_id, controls=None): ... + def extended( + self, request_name, request_value: Asn1Item | ReadableBuffer | None = None, controls=None, no_encode: bool | None = None + ): ... + def start_tls(self, read_server_info: bool = True): ... + def do_sasl_bind(self, controls): ... + def do_ntlm_bind(self, controls): ... + def refresh_server_info(self) -> None: ... + def response_to_ldif( + self, search_result=None, all_base64: bool = False, line_separator=None, sort_order=None, stream=None + ): ... + def response_to_json( + self, + raw: bool = False, + search_result=None, + indent: int = 4, + sort: bool = True, + stream=None, + checked_attributes: bool = True, + include_empty: bool = True, + ): ... + def response_to_file(self, target, raw: bool = False, indent: int = 4, sort: bool = True) -> None: ... + @property + def entries(self): ... diff --git a/stubs/ldap3/ldap3/core/exceptions.pyi b/stubs/ldap3/ldap3/core/exceptions.pyi new file mode 100644 index 000000000000..f0ce91bf5ba8 --- /dev/null +++ b/stubs/ldap3/ldap3/core/exceptions.pyi @@ -0,0 +1,129 @@ +import socket +from _typeshed import Incomplete +from typing_extensions import Self + +class LDAPException(Exception): ... + +class LDAPOperationResult(LDAPException): + def __new__(cls, result=None, description=None, dn=None, message=None, response_type=None, response=None) -> Self: ... + result: Incomplete + description: Incomplete + dn: Incomplete + message: Incomplete + type: Incomplete + response: Incomplete + def __init__(self, result=None, description=None, dn=None, message=None, response_type=None, response=None) -> None: ... + +class LDAPOperationsErrorResult(LDAPOperationResult): ... +class LDAPProtocolErrorResult(LDAPOperationResult): ... +class LDAPTimeLimitExceededResult(LDAPOperationResult): ... +class LDAPSizeLimitExceededResult(LDAPOperationResult): ... +class LDAPAuthMethodNotSupportedResult(LDAPOperationResult): ... +class LDAPStrongerAuthRequiredResult(LDAPOperationResult): ... +class LDAPReferralResult(LDAPOperationResult): ... +class LDAPAdminLimitExceededResult(LDAPOperationResult): ... +class LDAPUnavailableCriticalExtensionResult(LDAPOperationResult): ... +class LDAPConfidentialityRequiredResult(LDAPOperationResult): ... +class LDAPSASLBindInProgressResult(LDAPOperationResult): ... +class LDAPNoSuchAttributeResult(LDAPOperationResult): ... +class LDAPUndefinedAttributeTypeResult(LDAPOperationResult): ... +class LDAPInappropriateMatchingResult(LDAPOperationResult): ... +class LDAPConstraintViolationResult(LDAPOperationResult): ... +class LDAPAttributeOrValueExistsResult(LDAPOperationResult): ... +class LDAPInvalidAttributeSyntaxResult(LDAPOperationResult): ... +class LDAPNoSuchObjectResult(LDAPOperationResult): ... +class LDAPAliasProblemResult(LDAPOperationResult): ... +class LDAPInvalidDNSyntaxResult(LDAPOperationResult): ... +class LDAPAliasDereferencingProblemResult(LDAPOperationResult): ... +class LDAPInappropriateAuthenticationResult(LDAPOperationResult): ... +class LDAPInvalidCredentialsResult(LDAPOperationResult): ... +class LDAPInsufficientAccessRightsResult(LDAPOperationResult): ... +class LDAPBusyResult(LDAPOperationResult): ... +class LDAPUnavailableResult(LDAPOperationResult): ... +class LDAPUnwillingToPerformResult(LDAPOperationResult): ... +class LDAPLoopDetectedResult(LDAPOperationResult): ... +class LDAPNamingViolationResult(LDAPOperationResult): ... +class LDAPObjectClassViolationResult(LDAPOperationResult): ... +class LDAPNotAllowedOnNotLeafResult(LDAPOperationResult): ... +class LDAPNotAllowedOnRDNResult(LDAPOperationResult): ... +class LDAPEntryAlreadyExistsResult(LDAPOperationResult): ... +class LDAPObjectClassModsProhibitedResult(LDAPOperationResult): ... +class LDAPAffectMultipleDSASResult(LDAPOperationResult): ... +class LDAPOtherResult(LDAPOperationResult): ... +class LDAPLCUPResourcesExhaustedResult(LDAPOperationResult): ... +class LDAPLCUPSecurityViolationResult(LDAPOperationResult): ... +class LDAPLCUPInvalidDataResult(LDAPOperationResult): ... +class LDAPLCUPUnsupportedSchemeResult(LDAPOperationResult): ... +class LDAPLCUPReloadRequiredResult(LDAPOperationResult): ... +class LDAPCanceledResult(LDAPOperationResult): ... +class LDAPNoSuchOperationResult(LDAPOperationResult): ... +class LDAPTooLateResult(LDAPOperationResult): ... +class LDAPCannotCancelResult(LDAPOperationResult): ... +class LDAPAssertionFailedResult(LDAPOperationResult): ... +class LDAPAuthorizationDeniedResult(LDAPOperationResult): ... +class LDAPESyncRefreshRequiredResult(LDAPOperationResult): ... + +exception_table: Incomplete + +class LDAPExceptionError(LDAPException): ... +class LDAPConfigurationError(LDAPExceptionError): ... +class LDAPUnknownStrategyError(LDAPConfigurationError): ... +class LDAPUnknownAuthenticationMethodError(LDAPConfigurationError): ... +class LDAPSSLConfigurationError(LDAPConfigurationError): ... +class LDAPDefinitionError(LDAPConfigurationError): ... +class LDAPPackageUnavailableError(LDAPConfigurationError, ImportError): ... +class LDAPConfigurationParameterError(LDAPConfigurationError): ... +class LDAPKeyError(LDAPExceptionError, KeyError, AttributeError): ... +class LDAPObjectError(LDAPExceptionError, ValueError): ... +class LDAPAttributeError(LDAPExceptionError, ValueError, TypeError): ... +class LDAPCursorError(LDAPExceptionError): ... +class LDAPCursorAttributeError(LDAPCursorError, AttributeError): ... +class LDAPObjectDereferenceError(LDAPExceptionError): ... +class LDAPSSLNotSupportedError(LDAPExceptionError, ImportError): ... +class LDAPInvalidTlsSpecificationError(LDAPExceptionError): ... +class LDAPInvalidHashAlgorithmError(LDAPExceptionError, ValueError): ... +class LDAPSignatureVerificationFailedError(LDAPExceptionError): ... +class LDAPBindError(LDAPExceptionError): ... +class LDAPInvalidServerError(LDAPExceptionError): ... +class LDAPSASLMechanismNotSupportedError(LDAPExceptionError): ... +class LDAPConnectionIsReadOnlyError(LDAPExceptionError): ... +class LDAPChangeError(LDAPExceptionError, ValueError): ... +class LDAPServerPoolError(LDAPExceptionError): ... +class LDAPServerPoolExhaustedError(LDAPExceptionError): ... +class LDAPInvalidPortError(LDAPExceptionError): ... +class LDAPStartTLSError(LDAPExceptionError): ... +class LDAPCertificateError(LDAPExceptionError): ... +class LDAPUserNameNotAllowedError(LDAPExceptionError): ... +class LDAPUserNameIsMandatoryError(LDAPExceptionError): ... +class LDAPPasswordIsMandatoryError(LDAPExceptionError): ... +class LDAPInvalidFilterError(LDAPExceptionError): ... +class LDAPInvalidScopeError(LDAPExceptionError, ValueError): ... +class LDAPInvalidDereferenceAliasesError(LDAPExceptionError, ValueError): ... +class LDAPInvalidValueError(LDAPExceptionError, ValueError): ... +class LDAPControlError(LDAPExceptionError, ValueError): ... +class LDAPExtensionError(LDAPExceptionError, ValueError): ... +class LDAPLDIFError(LDAPExceptionError): ... +class LDAPSchemaError(LDAPExceptionError): ... +class LDAPSASLPrepError(LDAPExceptionError): ... +class LDAPSASLBindInProgressError(LDAPExceptionError): ... +class LDAPMetricsError(LDAPExceptionError): ... +class LDAPObjectClassError(LDAPExceptionError): ... +class LDAPInvalidDnError(LDAPExceptionError): ... +class LDAPResponseTimeoutError(LDAPExceptionError): ... +class LDAPTransactionError(LDAPExceptionError): ... +class LDAPInfoError(LDAPExceptionError): ... +class LDAPCommunicationError(LDAPExceptionError): ... +class LDAPSocketOpenError(LDAPCommunicationError): ... +class LDAPSocketCloseError(LDAPCommunicationError): ... +class LDAPSocketReceiveError(LDAPCommunicationError, socket.error): ... +class LDAPSocketSendError(LDAPCommunicationError, socket.error): ... +class LDAPSessionTerminatedByServerError(LDAPCommunicationError): ... +class LDAPUnknownResponseError(LDAPCommunicationError): ... +class LDAPUnknownRequestError(LDAPCommunicationError): ... +class LDAPReferralError(LDAPCommunicationError): ... +class LDAPConnectionPoolNameIsMandatoryError(LDAPExceptionError): ... +class LDAPConnectionPoolNotStartedError(LDAPExceptionError): ... +class LDAPMaximumRetriesError(LDAPExceptionError): ... + +def communication_exception_factory(exc_to_raise, exc): ... +def start_tls_exception_factory(exc): ... diff --git a/stubs/ldap3/ldap3/core/pooling.pyi b/stubs/ldap3/ldap3/core/pooling.pyi new file mode 100644 index 000000000000..861a4d06af53 --- /dev/null +++ b/stubs/ldap3/ldap3/core/pooling.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +POOLING_STRATEGIES: Incomplete + +class ServerState: + server: Incomplete + last_checked_time: Incomplete + available: Incomplete + def __init__(self, server, last_checked_time, available) -> None: ... + +class ServerPoolState: + server_states: Incomplete + strategy: Incomplete + server_pool: Incomplete + last_used_server: int + initialize_time: Incomplete + def __init__(self, server_pool) -> None: ... + def refresh(self) -> None: ... + def get_current_server(self): ... + def get_server(self): ... + def find_active_random_server(self): ... + def find_active_server(self, starting): ... + def __len__(self) -> int: ... + +class ServerPool: + servers: Incomplete + pool_states: Incomplete + active: Incomplete + exhaust: Incomplete + single: Incomplete + strategy: Incomplete + def __init__( + self, servers=None, pool_strategy="ROUND_ROBIN", active: bool = True, exhaust: bool = False, single_state: bool = True + ) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, item): ... + def __iter__(self): ... + def add(self, servers) -> None: ... + def remove(self, server) -> None: ... + def initialize(self, connection) -> None: ... + def get_server(self, connection): ... + def get_current_server(self, connection): ... diff --git a/stubs/ldap3/ldap3/core/rdns.pyi b/stubs/ldap3/ldap3/core/rdns.pyi new file mode 100644 index 000000000000..41205368d2d7 --- /dev/null +++ b/stubs/ldap3/ldap3/core/rdns.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +class ReverseDnsSetting: + OFF: Incomplete + REQUIRE_RESOLVE_ALL_ADDRESSES: Incomplete + REQUIRE_RESOLVE_IP_ADDRESSES_ONLY: Incomplete + OPTIONAL_RESOLVE_ALL_ADDRESSES: Incomplete + OPTIONAL_RESOLVE_IP_ADDRESSES_ONLY: Incomplete + SUPPORTED_VALUES: Incomplete + +def get_hostname_by_addr(addr, success_required: bool = True): ... +def is_ip_addr(addr): ... diff --git a/stubs/ldap3/ldap3/core/results.pyi b/stubs/ldap3/ldap3/core/results.pyi new file mode 100644 index 000000000000..67e1e0dcb549 --- /dev/null +++ b/stubs/ldap3/ldap3/core/results.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +RESULT_SUCCESS: int +RESULT_OPERATIONS_ERROR: int +RESULT_PROTOCOL_ERROR: int +RESULT_TIME_LIMIT_EXCEEDED: int +RESULT_SIZE_LIMIT_EXCEEDED: int +RESULT_COMPARE_FALSE: int +RESULT_COMPARE_TRUE: int +RESULT_AUTH_METHOD_NOT_SUPPORTED: int +RESULT_STRONGER_AUTH_REQUIRED: int +RESULT_RESERVED: int +RESULT_REFERRAL: int +RESULT_ADMIN_LIMIT_EXCEEDED: int +RESULT_UNAVAILABLE_CRITICAL_EXTENSION: int +RESULT_CONFIDENTIALITY_REQUIRED: int +RESULT_SASL_BIND_IN_PROGRESS: int +RESULT_NO_SUCH_ATTRIBUTE: int +RESULT_UNDEFINED_ATTRIBUTE_TYPE: int +RESULT_INAPPROPRIATE_MATCHING: int +RESULT_CONSTRAINT_VIOLATION: int +RESULT_ATTRIBUTE_OR_VALUE_EXISTS: int +RESULT_INVALID_ATTRIBUTE_SYNTAX: int +RESULT_NO_SUCH_OBJECT: int +RESULT_ALIAS_PROBLEM: int +RESULT_INVALID_DN_SYNTAX: int +RESULT_ALIAS_DEREFERENCING_PROBLEM: int +RESULT_INAPPROPRIATE_AUTHENTICATION: int +RESULT_INVALID_CREDENTIALS: int +RESULT_INSUFFICIENT_ACCESS_RIGHTS: int +RESULT_BUSY: int +RESULT_UNAVAILABLE: int +RESULT_UNWILLING_TO_PERFORM: int +RESULT_LOOP_DETECTED: int +RESULT_NAMING_VIOLATION: int +RESULT_OBJECT_CLASS_VIOLATION: int +RESULT_NOT_ALLOWED_ON_NON_LEAF: int +RESULT_NOT_ALLOWED_ON_RDN: int +RESULT_ENTRY_ALREADY_EXISTS: int +RESULT_OBJECT_CLASS_MODS_PROHIBITED: int +RESULT_AFFECT_MULTIPLE_DSAS: int +RESULT_OTHER: int +RESULT_LCUP_RESOURCES_EXHAUSTED: int +RESULT_LCUP_SECURITY_VIOLATION: int +RESULT_LCUP_INVALID_DATA: int +RESULT_LCUP_UNSUPPORTED_SCHEME: int +RESULT_LCUP_RELOAD_REQUIRED: int +RESULT_CANCELED: int +RESULT_NO_SUCH_OPERATION: int +RESULT_TOO_LATE: int +RESULT_CANNOT_CANCEL: int +RESULT_ASSERTION_FAILED: int +RESULT_AUTHORIZATION_DENIED: int +RESULT_E_SYNC_REFRESH_REQUIRED: int +RESULT_CODES: Incomplete +DO_NOT_RAISE_EXCEPTIONS: Incomplete diff --git a/stubs/ldap3/ldap3/core/server.pyi b/stubs/ldap3/ldap3/core/server.pyi new file mode 100644 index 000000000000..d31ad382f694 --- /dev/null +++ b/stubs/ldap3/ldap3/core/server.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from typing import Literal + +unix_socket_available: bool + +class Server: + ipc: bool + host: Incomplete + port: Incomplete + allowed_referral_hosts: Incomplete + ssl: Incomplete + tls: Incomplete + name: Incomplete + get_info: Incomplete + dit_lock: Incomplete + custom_formatter: Incomplete + custom_validator: Incomplete + current_address: Incomplete + connect_timeout: Incomplete + mode: Incomplete + def __init__( + self, + host: str, + port: int | None = None, + use_ssl: bool = False, + allowed_referral_hosts=None, + get_info: Literal["NO_INFO", "DSA", "SCHEMA", "ALL"] = "SCHEMA", + tls=None, + formatter=None, + connect_timeout=None, + mode: Literal["IP_SYSTEM_DEFAULT", "IP_V4_ONLY", "IP_V6_ONLY", "IP_V4_PREFERRED", "IP_V6_PREFERRED"] = "IP_V6_PREFERRED", + validator=None, + ) -> None: ... + @property + def address_info(self): ... + def update_availability(self, address, available) -> None: ... + def reset_availability(self) -> None: ... + def check_availability(self, source_address=None, source_port=None, source_port_list=None): ... + @staticmethod + def next_message_id(): ... + def get_info_from_server(self, connection) -> None: ... + def attach_dsa_info(self, dsa_info=None) -> None: ... + def attach_schema_info(self, dsa_schema=None) -> None: ... + @property + def info(self): ... + @property + def schema(self): ... + @staticmethod + def from_definition(host, dsa_info, dsa_schema, port=None, use_ssl: bool = False, formatter=None, validator=None): ... + def candidate_addresses(self): ... + def has_control(self, control): ... + def has_extension(self, extension): ... + def has_feature(self, feature): ... diff --git a/stubs/ldap3/ldap3/core/timezone.pyi b/stubs/ldap3/ldap3/core/timezone.pyi new file mode 100644 index 000000000000..f56ab0d9f4d3 --- /dev/null +++ b/stubs/ldap3/ldap3/core/timezone.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from datetime import tzinfo + +class OffsetTzInfo(tzinfo): + offset: Incomplete + name: Incomplete + def __init__(self, offset, name) -> None: ... + def utcoffset(self, dt): ... + def tzname(self, dt): ... + def dst(self, dt): ... + def __getinitargs__(self): ... diff --git a/stubs/ldap3/ldap3/core/tls.pyi b/stubs/ldap3/ldap3/core/tls.pyi new file mode 100644 index 000000000000..3636fa700ed1 --- /dev/null +++ b/stubs/ldap3/ldap3/core/tls.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +use_ssl_context: bool + +class Tls: + ssl_options: Incomplete + validate: Incomplete + ca_certs_file: Incomplete + ca_certs_path: Incomplete + ca_certs_data: Incomplete + private_key_password: Incomplete + version: Incomplete + private_key_file: Incomplete + certificate_file: Incomplete + valid_names: Incomplete + ciphers: Incomplete + sni: Incomplete + def __init__( + self, + local_private_key_file=None, + local_certificate_file=None, + validate=..., + version=None, + ssl_options=None, + ca_certs_file=None, + valid_names=None, + ca_certs_path=None, + ca_certs_data=None, + local_private_key_password=None, + ciphers=None, + sni=None, + ) -> None: ... + def wrap_socket(self, connection, do_handshake: bool = False) -> None: ... + def start_tls(self, connection): ... + +def check_hostname(sock, server_name, additional_names) -> None: ... diff --git a/stubs/ldap3/ldap3/core/usage.pyi b/stubs/ldap3/ldap3/core/usage.pyi new file mode 100644 index 000000000000..19bcd126af4e --- /dev/null +++ b/stubs/ldap3/ldap3/core/usage.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete + +class ConnectionUsage: + open_sockets: int + closed_sockets: int + wrapped_sockets: int + bytes_transmitted: int + bytes_received: int + messages_transmitted: int + messages_received: int + operations: int + abandon_operations: int + add_operations: int + bind_operations: int + compare_operations: int + delete_operations: int + extended_operations: int + modify_operations: int + modify_dn_operations: int + search_operations: int + unbind_operations: int + referrals_received: int + referrals_followed: int + referrals_connections: int + restartable_failures: int + restartable_successes: int + servers_from_pool: int + def reset(self) -> None: ... + initial_connection_start_time: Incomplete + open_socket_start_time: Incomplete + connection_stop_time: Incomplete + last_transmitted_time: Incomplete + last_received_time: Incomplete + def __init__(self) -> None: ... + def __iadd__(self, other): ... + def update_transmitted_message(self, message, length) -> None: ... + def update_received_message(self, length) -> None: ... + def start(self, reset: bool = True) -> None: ... + def stop(self) -> None: ... + @property + def elapsed_time(self): ... diff --git a/stubs/ldap3/ldap3/extend/__init__.pyi b/stubs/ldap3/ldap3/extend/__init__.pyi new file mode 100644 index 000000000000..db6afd88f452 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/__init__.pyi @@ -0,0 +1,97 @@ +from _typeshed import Incomplete + +class ExtendedOperationContainer: + def __init__(self, connection) -> None: ... + +class StandardExtendedOperations(ExtendedOperationContainer): + def who_am_i(self, controls=None): ... + def modify_password(self, user=None, old_password=None, new_password=None, hash_algorithm=None, salt=None, controls=None): ... + def paged_search( + self, + search_base, + search_filter, + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, + generator: bool = True, + ): ... + def persistent_search( + self, + search_base: str = "", + search_filter: str = "(objectclass=*)", + search_scope="SUBTREE", + dereference_aliases="NEVER", + attributes="*", + size_limit: int = 0, + time_limit: int = 0, + controls=None, + changes_only: bool = True, + show_additions: bool = True, + show_deletions: bool = True, + show_modifications: bool = True, + show_dn_modifications: bool = True, + notifications: bool = True, + streaming: bool = True, + callback=None, + ): ... + def funnel_search( + self, + search_base: str = "", + search_filter: str = "", + search_scope="SUBTREE", + dereference_aliases="NEVER", + attributes="*", + size_limit: int = 0, + time_limit: int = 0, + controls=None, + streaming: bool = False, + callback=None, + ): ... + +class NovellExtendedOperations(ExtendedOperationContainer): + def get_bind_dn(self, controls=None): ... + def get_universal_password(self, user, controls=None): ... + def set_universal_password(self, user, new_password=None, controls=None): ... + def list_replicas(self, server_dn, controls=None): ... + def partition_entry_count(self, partition_dn, controls=None): ... + def replica_info(self, server_dn, partition_dn, controls=None): ... + def start_transaction(self, controls=None): ... + def end_transaction(self, commit: bool = True, controls=None): ... + def add_members_to_groups(self, members, groups, fix: bool = True, transaction: bool = True): ... + def remove_members_from_groups(self, members, groups, fix: bool = True, transaction: bool = True): ... + def check_groups_memberships(self, members, groups, fix: bool = False, transaction: bool = True): ... + +class MicrosoftExtendedOperations(ExtendedOperationContainer): + def dir_sync( + self, + sync_base, + sync_filter: str = "(objectclass=*)", + attributes="*", + cookie=None, + object_security: bool = False, + ancestors_first: bool = True, + public_data_only: bool = False, + incremental_values: bool = True, + max_length: int = 2147483647, + hex_guid: bool = False, + ): ... + def modify_password(self, user, new_password, old_password=None, controls=None): ... + def unlock_account(self, user): ... + def add_members_to_groups(self, members, groups, fix: bool = True): ... + def remove_members_from_groups(self, members, groups, fix: bool = True): ... + def persistent_search( + self, search_base: str = "", search_scope="SUBTREE", attributes="*", streaming: bool = True, callback=None + ): ... + +class ExtendedOperationsRoot(ExtendedOperationContainer): + standard: Incomplete + novell: Incomplete + microsoft: Incomplete + def __init__(self, connection) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/__init__.pyi b/stubs/ldap3/ldap3/extend/microsoft/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi b/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi new file mode 100644 index 000000000000..39195431a854 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/addMembersToGroups.pyi @@ -0,0 +1 @@ +def ad_add_members_to_groups(connection, members_dn, groups_dn, fix: bool = True, raise_error: bool = False): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi b/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi new file mode 100644 index 000000000000..80f947e9589f --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/dirSync.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +class DirSync: + connection: Incomplete + base: Incomplete + filter: Incomplete + attributes: Incomplete + cookie: Incomplete + object_security: Incomplete + ancestors_first: Incomplete + public_data_only: Incomplete + incremental_values: Incomplete + max_length: Incomplete + hex_guid: Incomplete + more_results: bool + def __init__( + self, + connection, + sync_base, + sync_filter, + attributes, + cookie, + object_security, + ancestors_first, + public_data_only, + incremental_values, + max_length, + hex_guid, + ) -> None: ... + def loop(self): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi b/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi new file mode 100644 index 000000000000..6ee9b965f9d2 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/modifyPassword.pyi @@ -0,0 +1 @@ +def ad_modify_password(connection, user_dn, new_password, old_password, controls=None): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi b/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi new file mode 100644 index 000000000000..5c39dfc8b0b8 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/persistentSearch.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +class ADPersistentSearch: + connection: Incomplete + message_id: Incomplete + base: Incomplete + scope: Incomplete + attributes: Incomplete + controls: Incomplete + filter: str + def __init__(self, connection, search_base, search_scope, attributes, streaming, callback) -> None: ... + def start(self) -> None: ... + def stop(self, unbind: bool = True) -> None: ... + def next(self, block: bool = False, timeout=None): ... + def funnel(self, block: bool = False, timeout=None) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi b/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi new file mode 100644 index 000000000000..33fce56a80c1 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/removeMembersFromGroups.pyi @@ -0,0 +1 @@ +def ad_remove_members_from_groups(connection, members_dn, groups_dn, fix, raise_error: bool = False): ... diff --git a/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi b/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi new file mode 100644 index 000000000000..dd96df4b40a5 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/microsoft/unlockAccount.pyi @@ -0,0 +1 @@ +def ad_unlock_account(connection, user_dn, controls=None): ... diff --git a/stubs/ldap3/ldap3/extend/novell/__init__.pyi b/stubs/ldap3/ldap3/extend/novell/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/extend/novell/addMembersToGroups.pyi b/stubs/ldap3/ldap3/extend/novell/addMembersToGroups.pyi new file mode 100644 index 000000000000..5ba4cab9b309 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/addMembersToGroups.pyi @@ -0,0 +1 @@ +def edir_add_members_to_groups(connection, members_dn, groups_dn, fix, transaction): ... diff --git a/stubs/ldap3/ldap3/extend/novell/checkGroupsMemberships.pyi b/stubs/ldap3/ldap3/extend/novell/checkGroupsMemberships.pyi new file mode 100644 index 000000000000..551636c2904f --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/checkGroupsMemberships.pyi @@ -0,0 +1 @@ +def edir_check_groups_memberships(connection, members_dn, groups_dn, fix, transaction): ... diff --git a/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi b/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi new file mode 100644 index 000000000000..d771f87e9fc1 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/endTransaction.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from ...extend.operation import ExtendedOperation +from ...protocol.novell import EndGroupTypeRequestValue, EndGroupTypeResponseValue + +class EndTransaction(ExtendedOperation): + request_name: str + response_name: str + request_value: EndGroupTypeRequestValue + asn1_spec: EndGroupTypeResponseValue + def config(self) -> None: ... + def __init__(self, connection, commit: bool = True, controls=None) -> None: ... + def populate_result(self) -> None: ... + response_value: Incomplete + def set_response(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi b/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi new file mode 100644 index 000000000000..3e9e9c40b490 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/getBindDn.pyi @@ -0,0 +1,10 @@ +from ...extend.operation import ExtendedOperation +from ...protocol.novell import Identity + +class GetBindDn(ExtendedOperation): + request_name: str + response_name: str + response_attribute: str + asn1_spec: Identity + def config(self) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi b/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi new file mode 100644 index 000000000000..414761713115 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/listReplicas.pyi @@ -0,0 +1,13 @@ +from ...extend.operation import ExtendedOperation +from ...protocol.novell import ReplicaList +from ...protocol.rfc4511 import LDAPDN + +class ListReplicas(ExtendedOperation): + request_name: str + response_name: str + request_value: LDAPDN + asn1_spec: ReplicaList + response_attribute: str + def config(self) -> None: ... + def __init__(self, connection, server_dn, controls=None) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi b/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi new file mode 100644 index 000000000000..f18b0ab3ac64 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/nmasGetUniversalPassword.pyi @@ -0,0 +1,12 @@ +from ...extend.operation import ExtendedOperation +from ...protocol.novell import NmasGetUniversalPasswordRequestValue, NmasGetUniversalPasswordResponseValue + +class NmasGetUniversalPassword(ExtendedOperation): + request_name: str + response_name: str + request_value: NmasGetUniversalPasswordRequestValue + asn1_spec: NmasGetUniversalPasswordResponseValue + response_attribute: str + def config(self) -> None: ... + def __init__(self, connection, user, controls=None) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi b/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi new file mode 100644 index 000000000000..762b20e7e2b5 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/nmasSetUniversalPassword.pyi @@ -0,0 +1,12 @@ +from ...extend.operation import ExtendedOperation +from ...protocol.novell import NmasSetUniversalPasswordRequestValue, NmasSetUniversalPasswordResponseValue + +class NmasSetUniversalPassword(ExtendedOperation): + request_name: str + response_name: str + request_value: NmasSetUniversalPasswordRequestValue + asn1_spec: NmasSetUniversalPasswordResponseValue + response_attribute: str + def config(self) -> None: ... + def __init__(self, connection, user, new_password, controls=None) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi b/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi new file mode 100644 index 000000000000..3231221f71ab --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/partition_entry_count.pyi @@ -0,0 +1,11 @@ +from ...protocol.rfc4511 import LDAPDN +from ..operation import ExtendedOperation + +class PartitionEntryCount(ExtendedOperation): + request_name: str + response_name: str + request_value: LDAPDN + response_attribute: str + def config(self) -> None: ... + def __init__(self, connection, partition_dn, controls=None) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/removeMembersFromGroups.pyi b/stubs/ldap3/ldap3/extend/novell/removeMembersFromGroups.pyi new file mode 100644 index 000000000000..91a3223c52eb --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/removeMembersFromGroups.pyi @@ -0,0 +1 @@ +def edir_remove_members_from_groups(connection, members_dn, groups_dn, fix, transaction): ... diff --git a/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi b/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi new file mode 100644 index 000000000000..5bc47e022a2a --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/replicaInfo.pyi @@ -0,0 +1,11 @@ +from ...protocol.novell import ReplicaInfoRequestValue +from ..operation import ExtendedOperation + +class ReplicaInfo(ExtendedOperation): + request_name: str + response_name: str + request_value: ReplicaInfoRequestValue + response_attribute: str + def config(self) -> None: ... + def __init__(self, connection, server_dn, partition_dn, controls=None) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi b/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi new file mode 100644 index 000000000000..f5225664e7c3 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/novell/startTransaction.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from ...extend.operation import ExtendedOperation +from ...protocol.novell import CreateGroupTypeRequestValue, CreateGroupTypeResponseValue + +class StartTransaction(ExtendedOperation): + request_name: str + response_name: str + request_value: CreateGroupTypeRequestValue + asn1_spec: CreateGroupTypeResponseValue + def config(self) -> None: ... + def __init__(self, connection, controls=None) -> None: ... + def populate_result(self) -> None: ... + response_value: Incomplete + def set_response(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/operation.pyi b/stubs/ldap3/ldap3/extend/operation.pyi new file mode 100644 index 000000000000..614f5c9842c7 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/operation.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from pyasn1.type.base import Asn1Type + +class ExtendedOperation: + connection: Incomplete + decoded_response: Incomplete | None + result: Incomplete | None + asn1_spec: Asn1Type | None + request_name: Incomplete | None + response_name: Incomplete | None + request_value: Asn1Type | None + response_value: Incomplete | None + response_attribute: Incomplete | None + controls: Incomplete + def __init__(self, connection, controls=None) -> None: ... + def send(self): ... + def populate_result(self) -> None: ... + def decode_response(self, response=None) -> None: ... + def set_response(self) -> None: ... + def config(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi b/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi new file mode 100644 index 000000000000..d651eff6afda --- /dev/null +++ b/stubs/ldap3/ldap3/extend/standard/PagedSearch.pyi @@ -0,0 +1,30 @@ +def paged_search_generator( + connection, + search_base, + search_filter, + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, +) -> None: ... +def paged_search_accumulator( + connection, + search_base, + search_filter, + search_scope="SUBTREE", + dereference_aliases="ALWAYS", + attributes=None, + size_limit: int = 0, + time_limit: int = 0, + types_only: bool = False, + get_operational_attributes: bool = False, + controls=None, + paged_size: int = 100, + paged_criticality: bool = False, +): ... diff --git a/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi b/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi new file mode 100644 index 000000000000..8b059d36c29e --- /dev/null +++ b/stubs/ldap3/ldap3/extend/standard/PersistentSearch.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +class PersistentSearch: + connection: Incomplete + changes_only: Incomplete + notifications: Incomplete + message_id: Incomplete + base: Incomplete + filter: Incomplete + scope: Incomplete + dereference_aliases: Incomplete + attributes: Incomplete + size_limit: Incomplete + time_limit: Incomplete + controls: Incomplete + def __init__( + self, + connection, + search_base, + search_filter, + search_scope, + dereference_aliases, + attributes, + size_limit, + time_limit, + controls, + changes_only, + events_type, + notifications, + streaming, + callback, + ) -> None: ... + def start(self) -> None: ... + def stop(self, unbind: bool = True) -> None: ... + def next(self, block: bool = False, timeout=None): ... + def funnel(self, block: bool = False, timeout=None) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/standard/__init__.pyi b/stubs/ldap3/ldap3/extend/standard/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi b/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi new file mode 100644 index 000000000000..1cd8156be3e8 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/standard/modifyPassword.pyi @@ -0,0 +1,13 @@ +from ...extend.operation import ExtendedOperation +from ...protocol.rfc3062 import PasswdModifyRequestValue, PasswdModifyResponseValue + +class ModifyPassword(ExtendedOperation): + request_name: str + request_value: PasswdModifyRequestValue + asn1_spec: PasswdModifyResponseValue + response_attribute: str + def config(self) -> None: ... + def __init__( + self, connection, user=None, old_password=None, new_password=None, hash_algorithm=None, salt=None, controls=None + ) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/extend/standard/whoAmI.pyi b/stubs/ldap3/ldap3/extend/standard/whoAmI.pyi new file mode 100644 index 000000000000..e61b175e92c9 --- /dev/null +++ b/stubs/ldap3/ldap3/extend/standard/whoAmI.pyi @@ -0,0 +1,7 @@ +from ...extend.operation import ExtendedOperation + +class WhoAmI(ExtendedOperation): + request_name: str + response_attribute: str + def config(self) -> None: ... + def populate_result(self) -> None: ... diff --git a/stubs/ldap3/ldap3/operation/__init__.pyi b/stubs/ldap3/ldap3/operation/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/operation/abandon.pyi b/stubs/ldap3/ldap3/operation/abandon.pyi new file mode 100644 index 000000000000..2413c214cdc1 --- /dev/null +++ b/stubs/ldap3/ldap3/operation/abandon.pyi @@ -0,0 +1,2 @@ +def abandon_operation(msg_id): ... +def abandon_request_to_dict(request): ... diff --git a/stubs/ldap3/ldap3/operation/add.pyi b/stubs/ldap3/ldap3/operation/add.pyi new file mode 100644 index 000000000000..777b0e3c2f5f --- /dev/null +++ b/stubs/ldap3/ldap3/operation/add.pyi @@ -0,0 +1,3 @@ +def add_operation(dn, attributes, auto_encode, schema=None, validator=None, check_names: bool = False): ... +def add_request_to_dict(request): ... +def add_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/bind.pyi b/stubs/ldap3/ldap3/operation/bind.pyi new file mode 100644 index 000000000000..9d8f99c13ecd --- /dev/null +++ b/stubs/ldap3/ldap3/operation/bind.pyi @@ -0,0 +1,11 @@ +def bind_operation( + version, authentication, name: str = "", password=None, sasl_mechanism=None, sasl_credentials=None, auto_encode: bool = False +): ... +def bind_request_to_dict(request): ... +def bind_response_operation( + result_code, matched_dn: str = "", diagnostic_message: str = "", referral=None, server_sasl_credentials=None +): ... +def bind_response_to_dict(response): ... +def sicily_bind_response_to_dict(response): ... +def bind_response_to_dict_fast(response): ... +def sicily_bind_response_to_dict_fast(response): ... diff --git a/stubs/ldap3/ldap3/operation/compare.pyi b/stubs/ldap3/ldap3/operation/compare.pyi new file mode 100644 index 000000000000..911781143cc4 --- /dev/null +++ b/stubs/ldap3/ldap3/operation/compare.pyi @@ -0,0 +1,3 @@ +def compare_operation(dn, attribute, value, auto_encode, schema=None, validator=None, check_names: bool = False): ... +def compare_request_to_dict(request): ... +def compare_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/delete.pyi b/stubs/ldap3/ldap3/operation/delete.pyi new file mode 100644 index 000000000000..618c8f41c96a --- /dev/null +++ b/stubs/ldap3/ldap3/operation/delete.pyi @@ -0,0 +1,3 @@ +def delete_operation(dn): ... +def delete_request_to_dict(request): ... +def delete_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/extended.pyi b/stubs/ldap3/ldap3/operation/extended.pyi new file mode 100644 index 000000000000..e519cf999503 --- /dev/null +++ b/stubs/ldap3/ldap3/operation/extended.pyi @@ -0,0 +1,14 @@ +from _typeshed import ReadableBuffer + +from pyasn1.type.base import Asn1Item + +from ..protocol.rfc4511 import ExtendedRequest + +def extended_operation( + request_name, request_value: Asn1Item | ReadableBuffer | None = None, no_encode: bool | None = None +) -> ExtendedRequest: ... +def extended_request_to_dict(request): ... +def extended_response_to_dict(response): ... +def intermediate_response_to_dict(response): ... +def extended_response_to_dict_fast(response): ... +def intermediate_response_to_dict_fast(response): ... diff --git a/stubs/ldap3/ldap3/operation/modify.pyi b/stubs/ldap3/ldap3/operation/modify.pyi new file mode 100644 index 000000000000..f21725f4b7f1 --- /dev/null +++ b/stubs/ldap3/ldap3/operation/modify.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +change_table: Incomplete + +def modify_operation(dn, changes, auto_encode, schema=None, validator=None, check_names: bool = False): ... +def modify_request_to_dict(request): ... +def modify_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/modifyDn.pyi b/stubs/ldap3/ldap3/operation/modifyDn.pyi new file mode 100644 index 000000000000..b69d03458aae --- /dev/null +++ b/stubs/ldap3/ldap3/operation/modifyDn.pyi @@ -0,0 +1,3 @@ +def modify_dn_operation(dn, new_relative_dn, delete_old_rdn: bool = True, new_superior=None): ... +def modify_dn_request_to_dict(request): ... +def modify_dn_response_to_dict(response): ... diff --git a/stubs/ldap3/ldap3/operation/search.pyi b/stubs/ldap3/ldap3/operation/search.pyi new file mode 100644 index 000000000000..34f7b29c925a --- /dev/null +++ b/stubs/ldap3/ldap3/operation/search.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete + +ROOT: int +AND: int +OR: int +NOT: int +MATCH_APPROX: int +MATCH_GREATER_OR_EQUAL: int +MATCH_LESS_OR_EQUAL: int +MATCH_EXTENSIBLE: int +MATCH_PRESENT: int +MATCH_SUBSTRING: int +MATCH_EQUAL: int +SEARCH_OPEN: int +SEARCH_OPEN_OR_CLOSE: int +SEARCH_MATCH_OR_CLOSE: int +SEARCH_MATCH_OR_CONTROL: int + +class FilterNode: + tag: Incomplete + parent: Incomplete + assertion: Incomplete + elements: Incomplete + def __init__(self, tag=None, assertion=None) -> None: ... + def __str__(self, pos: int = 0) -> str: ... + def __repr__(self, pos: int = 0) -> str: ... + def append(self, filter_node): ... + +def evaluate_match(match, schema, auto_escape, auto_encode, validator, check_names): ... +def parse_filter(search_filter, schema, auto_escape, auto_encode, validator, check_names): ... +def compile_filter(filter_node): ... +def build_attribute_selection(attribute_list, schema): ... +def search_operation( + search_base, + search_filter, + search_scope, + dereference_aliases, + attributes, + size_limit, + time_limit, + types_only, + auto_escape, + auto_encode, + schema=None, + validator=None, + check_names: bool = False, +): ... +def decode_vals(vals): ... +def decode_vals_fast(vals): ... +def attributes_to_dict(attribute_list): ... +def attributes_to_dict_fast(attribute_list): ... +def decode_raw_vals(vals): ... +def decode_raw_vals_fast(vals): ... +def raw_attributes_to_dict(attribute_list): ... +def raw_attributes_to_dict_fast(attribute_list): ... +def checked_attributes_to_dict(attribute_list, schema=None, custom_formatter=None): ... +def checked_attributes_to_dict_fast(attribute_list, schema=None, custom_formatter=None): ... +def matching_rule_assertion_to_string(matching_rule_assertion): ... +def filter_to_string(filter_object): ... +def search_request_to_dict(request): ... +def search_result_entry_response_to_dict(response, schema, custom_formatter, check_names): ... +def search_result_done_response_to_dict(response): ... +def search_result_reference_response_to_dict(response): ... +def search_result_entry_response_to_dict_fast(response, schema, custom_formatter, check_names): ... +def search_result_reference_response_to_dict_fast(response): ... diff --git a/stubs/ldap3/ldap3/operation/unbind.pyi b/stubs/ldap3/ldap3/operation/unbind.pyi new file mode 100644 index 000000000000..0c66a79d615c --- /dev/null +++ b/stubs/ldap3/ldap3/operation/unbind.pyi @@ -0,0 +1 @@ +def unbind_operation(): ... diff --git a/stubs/ldap3/ldap3/protocol/__init__.pyi b/stubs/ldap3/ldap3/protocol/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/protocol/controls.pyi b/stubs/ldap3/ldap3/protocol/controls.pyi new file mode 100644 index 000000000000..589001327862 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/controls.pyi @@ -0,0 +1 @@ +def build_control(oid, criticality, value, encode_control_value: bool = True): ... diff --git a/stubs/ldap3/ldap3/protocol/convert.pyi b/stubs/ldap3/ldap3/protocol/convert.pyi new file mode 100644 index 000000000000..10b06b4f6165 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/convert.pyi @@ -0,0 +1,20 @@ +def to_str_or_normalized_unicode(val): ... +def attribute_to_dict(attribute): ... +def attributes_to_dict(attributes): ... +def referrals_to_list(referrals): ... +def search_refs_to_list(search_refs): ... +def search_refs_to_list_fast(search_refs): ... +def sasl_to_dict(sasl): ... +def authentication_choice_to_dict(authentication_choice): ... +def partial_attribute_to_dict(modification): ... +def change_to_dict(change): ... +def changes_to_list(changes): ... +def attributes_to_list(attributes): ... +def ava_to_dict(ava): ... +def substring_to_dict(substring): ... +def prepare_changes_for_request(changes): ... +def build_controls_list(controls): ... +def validate_assertion_value(schema, name, value, auto_escape, auto_encode, validator, check_names): ... +def validate_attribute_value(schema, name, value, auto_encode, validator=None, check_names: bool = False): ... +def prepare_filter_for_sending(raw_string): ... +def prepare_for_sending(raw_string): ... diff --git a/stubs/ldap3/ldap3/protocol/formatters/__init__.pyi b/stubs/ldap3/ldap3/protocol/formatters/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi b/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi new file mode 100644 index 000000000000..62eb577c68af --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/formatters/formatters.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +def format_unicode(raw_value): ... +def format_integer(raw_value): ... +def format_binary(raw_value): ... +def format_uuid(raw_value): ... +def format_uuid_le(raw_value): ... +def format_boolean(raw_value): ... +def format_ad_timestamp(raw_value): ... + +time_format: Incomplete + +def format_time(raw_value): ... +def format_ad_timedelta(raw_value): ... +def format_time_with_0_year(raw_value): ... +def format_sid(raw_value): ... diff --git a/stubs/ldap3/ldap3/protocol/formatters/standard.pyi b/stubs/ldap3/ldap3/protocol/formatters/standard.pyi new file mode 100644 index 000000000000..7fa4eb927472 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/formatters/standard.pyi @@ -0,0 +1,7 @@ +from _typeshed import Incomplete + +standard_formatter: Incomplete + +def find_attribute_helpers(attr_type, name, custom_formatter): ... +def format_attribute_values(schema, name, values, custom_formatter): ... +def find_attribute_validator(schema, name, custom_validator): ... diff --git a/stubs/ldap3/ldap3/protocol/formatters/validators.pyi b/stubs/ldap3/ldap3/protocol/formatters/validators.pyi new file mode 100644 index 000000000000..b49eee6262d2 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/formatters/validators.pyi @@ -0,0 +1,16 @@ +def check_backslash(value): ... +def check_type(input_value, value_type): ... +def always_valid(input_value): ... +def validate_generic_single_value(input_value): ... +def validate_zero_and_minus_one_and_positive_int(input_value): ... +def validate_integer(input_value): ... +def validate_bytes(input_value): ... +def validate_boolean(input_value): ... +def validate_time_with_0_year(input_value): ... +def validate_time(input_value): ... +def validate_ad_timestamp(input_value): ... +def validate_ad_timedelta(input_value): ... +def validate_guid(input_value): ... +def validate_uuid(input_value): ... +def validate_uuid_le(input_value): ... +def validate_sid(input_value): ... diff --git a/stubs/ldap3/ldap3/protocol/microsoft.pyi b/stubs/ldap3/ldap3/protocol/microsoft.pyi new file mode 100644 index 000000000000..ac18a70ff620 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/microsoft.pyi @@ -0,0 +1,25 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Sequence + +class SicilyBindResponse(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class DirSyncControlRequestValue(Sequence): + componentType: NamedTypes + +class DirSyncControlResponseValue(Sequence): + componentType: NamedTypes + +class SdFlags(Sequence): + componentType: NamedTypes + +class ExtendedDN(Sequence): + componentType: NamedTypes + +def dir_sync_control(criticality, object_security, ancestors_first, public_data_only, incremental_values, max_length, cookie): ... +def extended_dn_control(criticality: bool = False, hex_format: bool = False): ... +def show_deleted_control(criticality: bool = False): ... +def security_descriptor_control(criticality: bool = False, sdflags: int = 15): ... +def persistent_search_control(criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/novell.pyi b/stubs/ldap3/ldap3/protocol/novell.pyi new file mode 100644 index 000000000000..d3e9c48ef807 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/novell.pyi @@ -0,0 +1,67 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Integer, OctetString, Sequence, SequenceOf + +NMAS_LDAP_EXT_VERSION: int + +class Identity(OctetString): + encoding: str + +class LDAPDN(OctetString): + tagSet: TagSet + encoding: str + +class Password(OctetString): + tagSet: TagSet + encoding: str + +class LDAPOID(OctetString): + tagSet: TagSet + encoding: str + +class GroupCookie(Integer): + tagSet: TagSet + +class NmasVer(Integer): + tagSet: TagSet + +class Error(Integer): + tagSet: TagSet + +class NmasGetUniversalPasswordRequestValue(Sequence): + componentType: NamedTypes + +class NmasGetUniversalPasswordResponseValue(Sequence): + componentType: NamedTypes + +class NmasSetUniversalPasswordRequestValue(Sequence): + componentType: NamedTypes + +class NmasSetUniversalPasswordResponseValue(Sequence): + componentType: NamedTypes + +class ReplicaList(SequenceOf): + componentType: OctetString + +class ReplicaInfoRequestValue(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class ReplicaInfoResponseValue(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class CreateGroupTypeRequestValue(Sequence): + componentType: NamedTypes + +class CreateGroupTypeResponseValue(Sequence): + componentType: NamedTypes + +class EndGroupTypeRequestValue(Sequence): + componentType: NamedTypes + +class EndGroupTypeResponseValue(Sequence): + componentType: NamedTypes + +class GroupingControlValue(Sequence): + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/oid.pyi b/stubs/ldap3/ldap3/protocol/oid.pyi new file mode 100644 index 000000000000..83886b0b5654 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/oid.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete + +OID_CONTROL: str +OID_EXTENSION: str +OID_FEATURE: str +OID_UNSOLICITED_NOTICE: str +OID_ATTRIBUTE_TYPE: str +OID_DIT_CONTENT_RULE: str +OID_LDAP_URL_EXTENSION: str +OID_FAMILY: str +OID_MATCHING_RULE: str +OID_NAME_FORM: str +OID_OBJECT_CLASS: str +OID_ADMINISTRATIVE_ROLE: str +OID_LDAP_SYNTAX: str +CLASS_STRUCTURAL: str +CLASS_ABSTRACT: str +CLASS_AUXILIARY: str +ATTRIBUTE_USER_APPLICATION: str +ATTRIBUTE_DIRECTORY_OPERATION: str +ATTRIBUTE_DISTRIBUTED_OPERATION: str +ATTRIBUTE_DSA_OPERATION: str + +def constant_to_oid_kind(oid_kind): ... +def decode_oids(sequence): ... +def decode_syntax(syntax): ... +def oid_to_string(oid): ... + +Oids: Incomplete diff --git a/stubs/ldap3/ldap3/protocol/persistentSearch.pyi b/stubs/ldap3/ldap3/protocol/persistentSearch.pyi new file mode 100644 index 000000000000..199e6c4c750c --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/persistentSearch.pyi @@ -0,0 +1,14 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.namedval import NamedValues +from pyasn1.type.univ import Enumerated, Sequence + +class PersistentSearchControl(Sequence): + componentType: NamedTypes + +class ChangeType(Enumerated): + namedValues: NamedValues + +class EntryChangeNotificationControl(Sequence): + componentType: NamedTypes + +def persistent_search_control(change_types, changes_only: bool = True, return_ecs: bool = True, criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc2696.pyi b/stubs/ldap3/ldap3/protocol/rfc2696.pyi new file mode 100644 index 000000000000..4df6aa5aed3e --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc2696.pyi @@ -0,0 +1,19 @@ +from typing import Final + +from pyasn1.type.constraint import ConstraintsIntersection, ValueRangeConstraint +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Integer, OctetString, Sequence + +MAXINT: Final[Integer] +rangeInt0ToMaxConstraint: ValueRangeConstraint + +class Integer0ToMax(Integer): + subtypeSpec: ConstraintsIntersection + +class Size(Integer0ToMax): ... +class Cookie(OctetString): ... + +class RealSearchControlValue(Sequence): + componentType: NamedTypes + +def paged_search_control(criticality: bool = False, size: int = 10, cookie=None): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc2849.pyi b/stubs/ldap3/ldap3/protocol/rfc2849.pyi new file mode 100644 index 000000000000..62420dde63d3 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc2849.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +conf_ldif_line_length: Incomplete + +def safe_ldif_string(bytes_value): ... +def add_controls(controls, all_base64): ... +def add_attributes(attributes, all_base64): ... +def sort_ldif_lines(lines, sort_order): ... +def search_response_to_ldif(entries, all_base64, sort_order=None): ... +def add_request_to_ldif(entry, all_base64, sort_order=None): ... +def delete_request_to_ldif(entry, all_base64, sort_order=None): ... +def modify_request_to_ldif(entry, all_base64, sort_order=None): ... +def modify_dn_request_to_ldif(entry, all_base64, sort_order=None): ... +def operation_to_ldif(operation_type, entries, all_base64: bool = False, sort_order=None): ... +def add_ldif_header(ldif_lines): ... +def ldif_sort(line, sort_order): ... +def decode_persistent_search_control(change): ... +def persistent_search_response_to_ldif(change): ... diff --git a/stubs/ldap3/ldap3/protocol/rfc3062.pyi b/stubs/ldap3/ldap3/protocol/rfc3062.pyi new file mode 100644 index 000000000000..4a97a374a37f --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc3062.pyi @@ -0,0 +1,25 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import OctetString, Sequence + +class UserIdentity(OctetString): + tagSet: TagSet + encoding: str + +class OldPasswd(OctetString): + tagSet: TagSet + encoding: str + +class NewPasswd(OctetString): + tagSet: TagSet + encoding: str + +class GenPasswd(OctetString): + tagSet: TagSet + encoding: str + +class PasswdModifyRequestValue(Sequence): + componentType: NamedTypes + +class PasswdModifyResponseValue(Sequence): + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/rfc4511.pyi b/stubs/ldap3/ldap3/protocol/rfc4511.pyi new file mode 100644 index 000000000000..83b9c2b71b44 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc4511.pyi @@ -0,0 +1,321 @@ +# Alias the import to avoid name clash with a class called "Final" +from typing import Final as _Final + +from pyasn1.type.constraint import ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.namedval import NamedValues +from pyasn1.type.tag import TagSet +from pyasn1.type.univ import Boolean, Choice, Enumerated, Integer, Null, OctetString, Sequence, SequenceOf, SetOf + +LDAP_MAX_INT: _Final[int] +MAXINT: _Final[Integer] +rangeInt0ToMaxConstraint: ValueRangeConstraint +rangeInt1To127Constraint: ValueRangeConstraint +size1ToMaxConstraint: ValueSizeConstraint +responseValueConstraint: SingleValueConstraint +# Custom constraints. They have yet to be implemented so ldap3 keeps them as None. +numericOIDConstraint: None +distinguishedNameConstraint: None +nameComponentConstraint: None +attributeDescriptionConstraint: None +uriConstraint: None +attributeSelectorConstraint: None + +class Integer0ToMax(Integer): + subtypeSpec: ConstraintsIntersection + +class LDAPString(OctetString): + encoding: str + +class MessageID(Integer0ToMax): ... +class LDAPOID(OctetString): ... +class LDAPDN(LDAPString): ... +class RelativeLDAPDN(LDAPString): ... +class AttributeDescription(LDAPString): ... + +class AttributeValue(OctetString): + encoding: str + +class AssertionValue(OctetString): + encoding: str + +class AttributeValueAssertion(Sequence): + componentType: NamedTypes + +class MatchingRuleId(LDAPString): ... + +class Vals(SetOf): + componentType: AttributeValue + +class ValsAtLeast1(SetOf): + componentType: AttributeValue + subtypeSpec: ConstraintsIntersection + +class PartialAttribute(Sequence): + componentType: NamedTypes + +class Attribute(Sequence): + componentType: NamedTypes + +class AttributeList(SequenceOf): + componentType: Attribute + +class Simple(OctetString): + tagSet: TagSet + encoding: str + +class Credentials(OctetString): + encoding: str + +class SaslCredentials(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class SicilyPackageDiscovery(OctetString): + tagSet: TagSet + encoding: str + +class SicilyNegotiate(OctetString): + tagSet: TagSet + encoding: str + +class SicilyResponse(OctetString): + tagSet: TagSet + encoding: str + +class AuthenticationChoice(Choice): + componentType: NamedTypes + +class Version(Integer): + subtypeSpec: ConstraintsIntersection + +class ResultCode(Enumerated): + namedValues: NamedValues + subTypeSpec: ConstraintsIntersection + +class URI(LDAPString): ... + +class Referral(SequenceOf): + tagSet: TagSet + componentType: URI + +class ServerSaslCreds(OctetString): + tagSet: TagSet + encoding: str + +class LDAPResult(Sequence): + componentType: NamedTypes + +class Criticality(Boolean): + defaultValue: bool + +class ControlValue(OctetString): + encoding: str + +class Control(Sequence): + componentType: NamedTypes + +class Controls(SequenceOf): + tagSet: TagSet + componentType: Control + +class Scope(Enumerated): + namedValues: NamedValues + +class DerefAliases(Enumerated): + namedValues: NamedValues + +class TypesOnly(Boolean): ... +class Selector(LDAPString): ... + +class AttributeSelection(SequenceOf): + componentType: Selector + +class MatchingRule(MatchingRuleId): + tagSet: TagSet + +class Type(AttributeDescription): + tagSet: TagSet + +class MatchValue(AssertionValue): + tagSet: TagSet + +class DnAttributes(Boolean): + tagSet: TagSet + defaultValue: Boolean + +class MatchingRuleAssertion(Sequence): + componentType: NamedTypes + +class Initial(AssertionValue): + tagSet: TagSet + +class Any(AssertionValue): + tagSet: TagSet + +class Final(AssertionValue): + tagSet: TagSet + +class Substring(Choice): + componentType: NamedTypes + +class Substrings(SequenceOf): + subtypeSpec: ConstraintsIntersection + componentType: Substring + +class SubstringFilter(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class And(SetOf): + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: Filter + +class Or(SetOf): + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: Filter + +class Not(Choice): ... + +class EqualityMatch(AttributeValueAssertion): + tagSet: TagSet + +class GreaterOrEqual(AttributeValueAssertion): + tagSet: TagSet + +class LessOrEqual(AttributeValueAssertion): + tagSet: TagSet + +class Present(AttributeDescription): + tagSet: TagSet + +class ApproxMatch(AttributeValueAssertion): + tagSet: TagSet + +class ExtensibleMatch(MatchingRuleAssertion): + tagSet: TagSet + +class Filter(Choice): + componentType: NamedTypes + +class PartialAttributeList(SequenceOf): + componentType: PartialAttribute + +class Operation(Enumerated): + namedValues: NamedValues + +class Change(Sequence): + componentType: NamedTypes + +class Changes(SequenceOf): + componentType: Change + +class DeleteOldRDN(Boolean): ... + +class NewSuperior(LDAPDN): + tagSet: TagSet + +class RequestName(LDAPOID): + tagSet: TagSet + +class RequestValue(OctetString): + tagSet: TagSet + encoding: str + +class ResponseName(LDAPOID): + tagSet: TagSet + +class ResponseValue(OctetString): + tagSet: TagSet + encoding: str + +class IntermediateResponseName(LDAPOID): + tagSet: TagSet + +class IntermediateResponseValue(OctetString): + tagSet: TagSet + encoding: str + +class BindRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class BindResponse(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class UnbindRequest(Null): + tagSet: TagSet + +class SearchRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class SearchResultReference(SequenceOf): + tagSet: TagSet + subtypeSpec: ConstraintsIntersection + componentType: URI + +class SearchResultEntry(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class SearchResultDone(LDAPResult): + tagSet: TagSet + +class ModifyRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class ModifyResponse(LDAPResult): + tagSet: TagSet + +class AddRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class AddResponse(LDAPResult): + tagSet: TagSet + +class DelRequest(LDAPDN): + tagSet: TagSet + +class DelResponse(LDAPResult): + tagSet: TagSet + +class ModifyDNRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class ModifyDNResponse(LDAPResult): + tagSet: TagSet + +class CompareRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class CompareResponse(LDAPResult): + tagSet: TagSet + +class AbandonRequest(MessageID): + tagSet: TagSet + +class ExtendedRequest(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class ExtendedResponse(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class IntermediateResponse(Sequence): + tagSet: TagSet + componentType: NamedTypes + +class ProtocolOp(Choice): + componentType: NamedTypes + +class LDAPMessage(Sequence): + componentType: NamedTypes diff --git a/stubs/ldap3/ldap3/protocol/rfc4512.pyi b/stubs/ldap3/ldap3/protocol/rfc4512.pyi new file mode 100644 index 000000000000..8334585e4075 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc4512.pyi @@ -0,0 +1,204 @@ +from _typeshed import Incomplete + +def constant_to_class_kind(value): ... +def constant_to_attribute_usage(value): ... +def attribute_usage_to_constant(value): ... +def quoted_string_to_list(quoted_string): ... +def oids_string_to_list(oid_string): ... +def extension_to_tuple(extension_string): ... +def list_to_string(list_object): ... + +class BaseServerInfo: + raw: Incomplete + def __init__(self, raw_attributes) -> None: ... + @classmethod + def from_json(cls, json_definition, schema=None, custom_formatter=None): ... + @classmethod + def from_file(cls, target, schema=None, custom_formatter=None): ... + def to_file(self, target, indent: int = 4, sort: bool = True) -> None: ... + def to_json(self, indent: int = 4, sort: bool = True): ... + +class DsaInfo(BaseServerInfo): + alt_servers: Incomplete + naming_contexts: Incomplete + supported_controls: Incomplete + supported_extensions: Incomplete + supported_features: Incomplete + supported_ldap_versions: Incomplete + supported_sasl_mechanisms: Incomplete + vendor_name: Incomplete + vendor_version: Incomplete + schema_entry: Incomplete + other: Incomplete + def __init__(self, attributes, raw_attributes) -> None: ... + +class SchemaInfo(BaseServerInfo): + schema_entry: Incomplete + create_time_stamp: Incomplete + modify_time_stamp: Incomplete + attribute_types: Incomplete + object_classes: Incomplete + matching_rules: Incomplete + matching_rule_uses: Incomplete + dit_content_rules: Incomplete + dit_structure_rules: Incomplete + name_forms: Incomplete + ldap_syntaxes: Incomplete + other: Incomplete + def __init__(self, schema_entry, attributes, raw_attributes) -> None: ... + def is_valid(self): ... + +class BaseObjectInfo: + oid: Incomplete + name: Incomplete + description: Incomplete + obsolete: Incomplete + extensions: Incomplete + experimental: Incomplete + raw_definition: Incomplete + def __init__( + self, oid=None, name=None, description=None, obsolete: bool = False, extensions=None, experimental=None, definition=None + ) -> None: ... + @property + def oid_info(self): ... + @classmethod + def from_definition(cls, definitions): ... + +class MatchingRuleInfo(BaseObjectInfo): + syntax: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + syntax=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class MatchingRuleUseInfo(BaseObjectInfo): + apply_to: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + apply_to=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class ObjectClassInfo(BaseObjectInfo): + superior: Incomplete + kind: Incomplete + must_contain: Incomplete + may_contain: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + superior=None, + kind=None, + must_contain=None, + may_contain=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class AttributeTypeInfo(BaseObjectInfo): + superior: Incomplete + equality: Incomplete + ordering: Incomplete + substring: Incomplete + syntax: Incomplete + min_length: Incomplete + single_value: Incomplete + collective: Incomplete + no_user_modification: Incomplete + usage: Incomplete + mandatory_in: Incomplete + optional_in: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + superior=None, + equality=None, + ordering=None, + substring=None, + syntax=None, + min_length=None, + single_value: bool = False, + collective: bool = False, + no_user_modification: bool = False, + usage=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class LdapSyntaxInfo(BaseObjectInfo): + def __init__(self, oid=None, description=None, extensions=None, experimental=None, definition=None) -> None: ... + +class DitContentRuleInfo(BaseObjectInfo): + auxiliary_classes: Incomplete + must_contain: Incomplete + may_contain: Incomplete + not_contains: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + auxiliary_classes=None, + must_contain=None, + may_contain=None, + not_contains=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class DitStructureRuleInfo(BaseObjectInfo): + superior: Incomplete + name_form: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + name_form=None, + superior=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... + +class NameFormInfo(BaseObjectInfo): + object_class: Incomplete + must_contain: Incomplete + may_contain: Incomplete + def __init__( + self, + oid=None, + name=None, + description=None, + obsolete: bool = False, + object_class=None, + must_contain=None, + may_contain=None, + extensions=None, + experimental=None, + definition=None, + ) -> None: ... diff --git a/stubs/ldap3/ldap3/protocol/rfc4527.pyi b/stubs/ldap3/ldap3/protocol/rfc4527.pyi new file mode 100644 index 000000000000..bcacd48140af --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/rfc4527.pyi @@ -0,0 +1,2 @@ +def pre_read_control(attributes, criticality: bool = False): ... +def post_read_control(attributes, criticality: bool = False): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/__init__.pyi b/stubs/ldap3/ldap3/protocol/sasl/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/protocol/sasl/digestMd5.pyi b/stubs/ldap3/ldap3/protocol/sasl/digestMd5.pyi new file mode 100644 index 000000000000..433416f25d27 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/sasl/digestMd5.pyi @@ -0,0 +1,9 @@ +STATE_KEY: int +STATE_VALUE: int + +def md5_h(value): ... +def md5_kd(k, s): ... +def md5_hex(value): ... +def md5_hmac(k, s): ... +def sasl_digest_md5(connection, controls): ... +def decode_directives(directives_string): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/external.pyi b/stubs/ldap3/ldap3/protocol/sasl/external.pyi new file mode 100644 index 000000000000..8403ee7944af --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/sasl/external.pyi @@ -0,0 +1 @@ +def sasl_external(connection, controls): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/kerberos.pyi b/stubs/ldap3/ldap3/protocol/sasl/kerberos.pyi new file mode 100644 index 000000000000..7a795b210a71 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/sasl/kerberos.pyi @@ -0,0 +1,8 @@ +posix_gssapi_unavailable: bool +windows_gssapi_unavailable: bool +NO_SECURITY_LAYER: int +INTEGRITY_PROTECTION: int +CONFIDENTIALITY_PROTECTION: int + +def get_channel_bindings(ssl_socket): ... +def sasl_gssapi(connection, controls): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/plain.pyi b/stubs/ldap3/ldap3/protocol/sasl/plain.pyi new file mode 100644 index 000000000000..5be879c5abef --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/sasl/plain.pyi @@ -0,0 +1 @@ +def sasl_plain(connection, controls): ... diff --git a/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi b/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi new file mode 100644 index 000000000000..32c30e0f7a45 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/sasl/sasl.pyi @@ -0,0 +1,5 @@ +def sasl_prep(data): ... +def validate_simple_password(password, accept_empty: bool = False): ... +def abort_sasl_negotiation(connection, controls): ... +def send_sasl_negotiation(connection, controls, payload): ... +def random_hex_string(size): ... diff --git a/stubs/ldap3/ldap3/protocol/schemas/__init__.pyi b/stubs/ldap3/ldap3/protocol/schemas/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/protocol/schemas/ad2012R2.pyi b/stubs/ldap3/ldap3/protocol/schemas/ad2012R2.pyi new file mode 100644 index 000000000000..3f484293670c --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/schemas/ad2012R2.pyi @@ -0,0 +1,2 @@ +ad_2012_r2_schema: str +ad_2012_r2_dsa_info: str diff --git a/stubs/ldap3/ldap3/protocol/schemas/ds389.pyi b/stubs/ldap3/ldap3/protocol/schemas/ds389.pyi new file mode 100644 index 000000000000..4d90cdc59857 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/schemas/ds389.pyi @@ -0,0 +1,2 @@ +ds389_1_3_3_schema: str +ds389_1_3_3_dsa_info: str diff --git a/stubs/ldap3/ldap3/protocol/schemas/edir888.pyi b/stubs/ldap3/ldap3/protocol/schemas/edir888.pyi new file mode 100644 index 000000000000..5b982a48e0d1 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/schemas/edir888.pyi @@ -0,0 +1,2 @@ +edir_8_8_8_schema: str +edir_8_8_8_dsa_info: str diff --git a/stubs/ldap3/ldap3/protocol/schemas/edir914.pyi b/stubs/ldap3/ldap3/protocol/schemas/edir914.pyi new file mode 100644 index 000000000000..d7c9cf64f817 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/schemas/edir914.pyi @@ -0,0 +1,2 @@ +edir_9_1_4_schema: str +edir_9_1_4_dsa_info: str diff --git a/stubs/ldap3/ldap3/protocol/schemas/slapd24.pyi b/stubs/ldap3/ldap3/protocol/schemas/slapd24.pyi new file mode 100644 index 000000000000..c080d0820aa0 --- /dev/null +++ b/stubs/ldap3/ldap3/protocol/schemas/slapd24.pyi @@ -0,0 +1,2 @@ +slapd_2_4_schema: str +slapd_2_4_dsa_info: str diff --git a/stubs/ldap3/ldap3/strategy/__init__.pyi b/stubs/ldap3/ldap3/strategy/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/strategy/asyncStream.pyi b/stubs/ldap3/ldap3/strategy/asyncStream.pyi new file mode 100644 index 000000000000..ece52ea4d10e --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/asyncStream.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from ..strategy.asynchronous import AsyncStrategy + +class AsyncStreamStrategy(AsyncStrategy): + can_stream: bool + line_separator: Incomplete + all_base64: bool + stream: Incomplete + order: Incomplete + persistent_search_message_id: Incomplete + streaming: bool + callback: Incomplete + events: Incomplete + def __init__(self, ldap_connection) -> None: ... + def accumulate_stream(self, message_id, change) -> None: ... + def get_stream(self): ... + def set_stream(self, value) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/asynchronous.pyi b/stubs/ldap3/ldap3/strategy/asynchronous.pyi new file mode 100644 index 000000000000..5e8be4de852d --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/asynchronous.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from threading import Thread + +from ..strategy.base import BaseStrategy + +class AsyncStrategy(BaseStrategy): + class ReceiverSocketThread(Thread): + connection: Incomplete + socket_size: Incomplete + def __init__(self, ldap_connection) -> None: ... + def run(self) -> None: ... + + sync: bool + no_real_dsa: bool + pooled: bool + can_stream: bool + receiver: Incomplete + async_lock: Incomplete + event_lock: Incomplete + def __init__(self, ldap_connection) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... + def close(self) -> None: ... + def set_event_for_message(self, message_id) -> None: ... + def post_send_search(self, message_id): ... + def post_send_single_response(self, message_id): ... + def receiving(self) -> None: ... + def get_stream(self) -> None: ... + def set_stream(self, value) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/base.pyi b/stubs/ldap3/ldap3/strategy/base.pyi new file mode 100644 index 000000000000..1adc87f03185 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/base.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +unix_socket_available: bool +SESSION_TERMINATED_BY_SERVER: str +TRANSACTION_ERROR: str +RESPONSE_COMPLETE: str + +class BaseStrategy: + connection: Incomplete + sync: Incomplete + no_real_dsa: Incomplete + pooled: Incomplete + can_stream: Incomplete + referral_cache: Incomplete + thread_safe: bool + def __init__(self, ldap_connection) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... + def close(self) -> None: ... + def send(self, message_type, request, controls=None): ... + def get_response(self, message_id, timeout=None, get_request: bool = False): ... + @staticmethod + def compute_ldap_message_size(data): ... + def decode_response(self, ldap_message): ... + def decode_response_fast(self, ldap_message): ... + @staticmethod + def decode_control(control): ... + @staticmethod + def decode_control_fast(control, from_server: bool = True): ... + @staticmethod + def decode_request(message_type, component, controls=None): ... + def valid_referral_list(self, referrals): ... + def do_next_range_search(self, request, response, attr_name): ... + def do_search_on_auto_range(self, request, response): ... + def create_referral_connection(self, referrals): ... + def do_operation_on_referral(self, request, referrals): ... + def sending(self, ldap_message) -> None: ... + def receiving(self) -> None: ... + def post_send_single_response(self, message_id) -> None: ... + def post_send_search(self, message_id) -> None: ... + def get_stream(self) -> None: ... + def set_stream(self, value) -> None: ... + def unbind_referral_cache(self) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/ldifProducer.pyi b/stubs/ldap3/ldap3/strategy/ldifProducer.pyi new file mode 100644 index 000000000000..92524d3ad59c --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/ldifProducer.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from .base import BaseStrategy + +class LdifProducerStrategy(BaseStrategy): + sync: bool + no_real_dsa: bool + pooled: bool + can_stream: bool + line_separator: Incomplete + all_base64: bool + stream: Incomplete + order: Incomplete + def __init__(self, ldap_connection) -> None: ... + def receiving(self) -> None: ... + def send(self, message_type, request, controls=None): ... + def post_send_single_response(self, message_id): ... + def post_send_search(self, message_id) -> None: ... + def accumulate_stream(self, fragment) -> None: ... + def get_stream(self): ... + def set_stream(self, value) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/mockAsync.pyi b/stubs/ldap3/ldap3/strategy/mockAsync.pyi new file mode 100644 index 000000000000..9ff38e9dd117 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/mockAsync.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from .asynchronous import AsyncStrategy +from .mockBase import MockBaseStrategy + +class MockAsyncStrategy(MockBaseStrategy, AsyncStrategy): + def __init__(self, ldap_connection) -> None: ... + def post_send_search(self, payload): ... + bound: Incomplete + def post_send_single_response(self, payload): ... + def get_response(self, message_id, timeout=None, get_request: bool = False): ... diff --git a/stubs/ldap3/ldap3/strategy/mockBase.pyi b/stubs/ldap3/ldap3/strategy/mockBase.pyi new file mode 100644 index 000000000000..879cc5efecc8 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/mockBase.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete + +SEARCH_CONTROLS: Incomplete +SERVER_ENCODING: str + +def random_cookie(): ... + +class PagedSearchSet: + size: Incomplete + response: Incomplete + cookie: Incomplete + sent: int + done: bool + def __init__(self, response, size, criticality) -> None: ... + def next(self, size=None): ... + +class MockBaseStrategy: + entries: Incomplete + no_real_dsa: bool + bound: Incomplete + custom_validators: Incomplete + operational_attributes: Incomplete + def __init__(self) -> None: ... + def add_entry(self, dn, attributes, validate: bool = True): ... + def remove_entry(self, dn): ... + def entries_from_json(self, json_entry_file) -> None: ... + def mock_bind(self, request_message, controls): ... + def mock_delete(self, request_message, controls): ... + def mock_add(self, request_message, controls): ... + def mock_compare(self, request_message, controls): ... + def mock_modify_dn(self, request_message, controls): ... + def mock_modify(self, request_message, controls): ... + def mock_search(self, request_message, controls): ... + def mock_extended(self, request_message, controls): ... + def evaluate_filter_node(self, node, candidates): ... + def equal(self, dn, attribute_type, value_to_check): ... + def send(self, message_type, request, controls=None): ... diff --git a/stubs/ldap3/ldap3/strategy/mockSync.pyi b/stubs/ldap3/ldap3/strategy/mockSync.pyi new file mode 100644 index 000000000000..7d8b07ec7c3a --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/mockSync.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from .mockBase import MockBaseStrategy +from .sync import SyncStrategy + +class MockSyncStrategy(MockBaseStrategy, SyncStrategy): + def __init__(self, ldap_connection) -> None: ... + def post_send_search(self, payload): ... + bound: Incomplete + def post_send_single_response(self, payload): ... diff --git a/stubs/ldap3/ldap3/strategy/restartable.pyi b/stubs/ldap3/ldap3/strategy/restartable.pyi new file mode 100644 index 000000000000..bec37ed375ac --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/restartable.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from .sync import SyncStrategy + +class RestartableStrategy(SyncStrategy): + sync: bool + no_real_dsa: bool + pooled: bool + can_stream: bool + restartable_sleep_time: Incomplete + restartable_tries: Incomplete + exception_history: Incomplete + def __init__(self, ldap_connection) -> None: ... + def open(self, reset_usage: bool = False, read_server_info: bool = True) -> None: ... + def send(self, message_type, request, controls=None): ... + def post_send_single_response(self, message_id): ... + def post_send_search(self, message_id): ... + def get_stream(self) -> None: ... + def set_stream(self, value) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/reusable.pyi b/stubs/ldap3/ldap3/strategy/reusable.pyi new file mode 100644 index 000000000000..92b2f3ad7b8f --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/reusable.pyi @@ -0,0 +1,75 @@ +from _typeshed import Incomplete +from threading import Thread + +from .base import BaseStrategy + +TERMINATE_REUSABLE: str +BOGUS_BIND: int +BOGUS_UNBIND: int +BOGUS_EXTENDED: int +BOGUS_ABANDON: int + +class ReusableStrategy(BaseStrategy): + pools: Incomplete + def receiving(self) -> None: ... + def get_stream(self) -> None: ... + def set_stream(self, value) -> None: ... + + class ConnectionPool: + def __new__(cls, connection): ... + name: Incomplete + master_connection: Incomplete + workers: Incomplete + pool_size: Incomplete + lifetime: Incomplete + keepalive: Incomplete + request_queue: Incomplete + open_pool: bool + bind_pool: bool + tls_pool: bool + counter: int + terminated_usage: Incomplete + terminated: bool + pool_lock: Incomplete + started: bool + def __init__(self, connection) -> None: ... + def get_info_from_server(self) -> None: ... + def rebind_pool(self) -> None: ... + def start_pool(self): ... + def create_pool(self) -> None: ... + def terminate_pool(self) -> None: ... + + class PooledConnectionThread(Thread): + daemon: bool + worker: Incomplete + master_connection: Incomplete + def __init__(self, worker, master_connection) -> None: ... + def run(self) -> None: ... + + class PooledConnectionWorker: + master_connection: Incomplete + request_queue: Incomplete + running: bool + busy: bool + get_info_from_server: bool + connection: Incomplete + creation_time: Incomplete + task_counter: int + thread: Incomplete + worker_lock: Incomplete + def __init__(self, connection, request_queue) -> None: ... + def new_connection(self) -> None: ... + + sync: bool + no_real_dsa: bool + pooled: bool + can_stream: bool + pool: Incomplete + def __init__(self, ldap_connection) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... + def terminate(self) -> None: ... + def send(self, message_type, request, controls=None): ... + def validate_bind(self, controls): ... + def get_response(self, counter, timeout=None, get_request: bool = False): ... + def post_send_single_response(self, counter): ... + def post_send_search(self, counter): ... diff --git a/stubs/ldap3/ldap3/strategy/safeRestartable.pyi b/stubs/ldap3/ldap3/strategy/safeRestartable.pyi new file mode 100644 index 000000000000..b52aa5a1b4a1 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/safeRestartable.pyi @@ -0,0 +1,5 @@ +from .restartable import RestartableStrategy + +class SafeRestartableStrategy(RestartableStrategy): + thread_safe: bool + def __init__(self, ldap_connection) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/safeSync.pyi b/stubs/ldap3/ldap3/strategy/safeSync.pyi new file mode 100644 index 000000000000..2b8b51390eb8 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/safeSync.pyi @@ -0,0 +1,5 @@ +from .sync import SyncStrategy + +class SafeSyncStrategy(SyncStrategy): + thread_safe: bool + def __init__(self, ldap_connection) -> None: ... diff --git a/stubs/ldap3/ldap3/strategy/sync.pyi b/stubs/ldap3/ldap3/strategy/sync.pyi new file mode 100644 index 000000000000..c270ecb6dfc5 --- /dev/null +++ b/stubs/ldap3/ldap3/strategy/sync.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from ..strategy.base import BaseStrategy + +LDAP_MESSAGE_TEMPLATE: Incomplete + +class SyncStrategy(BaseStrategy): + sync: bool + no_real_dsa: bool + pooled: bool + can_stream: bool + socket_size: Incomplete + def __init__(self, ldap_connection) -> None: ... + def open(self, reset_usage: bool = True, read_server_info: bool = True) -> None: ... + def receiving(self): ... + def post_send_single_response(self, message_id): ... + def post_send_search(self, message_id): ... + def set_stream(self, value) -> None: ... + def get_stream(self) -> None: ... diff --git a/stubs/ldap3/ldap3/utils/__init__.pyi b/stubs/ldap3/ldap3/utils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/ldap3/ldap3/utils/asn1.pyi b/stubs/ldap3/ldap3/utils/asn1.pyi new file mode 100644 index 000000000000..11d682cb54e6 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/asn1.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete, IndexableBuffer, SliceableBuffer, Unused +from collections.abc import Callable, Mapping +from typing import Any, Final, TypeAlias, TypeVar, overload + +from pyasn1.codec.ber.encoder import AbstractItemEncoder +from pyasn1.type.tag import TagSet + +# Use _typeshed._SupportsGetItemBuffer after PEP 688 +_SupportsGetItemBuffer: TypeAlias = SliceableBuffer | IndexableBuffer +_R = TypeVar("_R") +_B = TypeVar("_B", bound=_SupportsGetItemBuffer) +# The possible return type is a union of all other decode methods, ie: AnyOf[Incomplete | bool] +_AllDecodersReturnType: TypeAlias = Any + +CLASSES: Final[dict[tuple[bool, bool], int]] + +class LDAPBooleanEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + # Requires pyasn1 > 0.3.7 + def encodeValue(self, value: bool | int, asn1Spec: Unused, encodeFun: Unused, **options: Unused): ... + +customTagMap: dict[TagSet, AbstractItemEncoder] +customTypeMap: dict[int, AbstractItemEncoder] + +def compute_ber_size(data): ... +def decode_message_fast(message): ... + +@overload +def decode_sequence(message: _B, start: int, stop: int, context_decoders: Mapping[int, Callable[[_B, int, int], _R]]) -> _R: ... +@overload +def decode_sequence( + message: _SupportsGetItemBuffer, start: int, stop: int, context_decoders: None = None +) -> _AllDecodersReturnType: ... + +def decode_integer(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_octet_string(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_boolean(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_bind_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_extended_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_intermediate_response(message, start: int, stop: int, context_decoders: Unused = None): ... +def decode_controls(message, start: int, stop: int, context_decoders: Unused = None): ... +def ldap_result_to_dict_fast(response): ... +def get_byte(x): ... +def get_bytes(x): ... + +# The possible return type is a union of all other decode methods, ie: AnyOf[Incomplete | bool] +DECODERS: dict[tuple[int, int], Callable[..., _AllDecodersReturnType]] +BIND_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +EXTENDED_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +INTERMEDIATE_RESPONSE_CONTEXT: dict[int, Callable[..., Incomplete]] +LDAP_MESSAGE_CONTEXT: dict[int, Callable[..., Incomplete]] +CONTROLS_CONTEXT: dict[int, Callable[..., Incomplete]] diff --git a/stubs/ldap3/ldap3/utils/ciDict.pyi b/stubs/ldap3/ldap3/utils/ciDict.pyi new file mode 100644 index 000000000000..ff9abffa557e --- /dev/null +++ b/stubs/ldap3/ldap3/utils/ciDict.pyi @@ -0,0 +1,29 @@ +from collections.abc import MutableMapping +from typing import TypeVar + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +class CaseInsensitiveDict(MutableMapping[_KT, _VT]): + def __init__(self, other=None, **kwargs) -> None: ... + def __contains__(self, item): ... + def __delitem__(self, key) -> None: ... + def __setitem__(self, key, item) -> None: ... + def __getitem__(self, key): ... + def __iter__(self): ... + def __len__(self) -> int: ... + def keys(self): ... + def values(self): ... + def items(self): ... + def __eq__(self, other): ... + def copy(self): ... + +class CaseInsensitiveWithAliasDict(CaseInsensitiveDict[_KT, _VT]): + def __init__(self, other=None, **kwargs) -> None: ... + def aliases(self): ... + def __setitem__(self, key, value) -> None: ... + def __delitem__(self, key) -> None: ... + def set_alias(self, key, alias, ignore_duplicates: bool = False) -> None: ... + def remove_alias(self, alias) -> None: ... + def __getitem__(self, key): ... + def copy(self): ... diff --git a/stubs/ldap3/ldap3/utils/config.pyi b/stubs/ldap3/ldap3/utils/config.pyi new file mode 100644 index 000000000000..e16df54889f5 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/config.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +PARAMETERS: Incomplete + +def get_config_parameter(parameter): ... +def set_config_parameter(parameter, value) -> None: ... diff --git a/stubs/ldap3/ldap3/utils/conv.pyi b/stubs/ldap3/ldap3/utils/conv.pyi new file mode 100644 index 000000000000..a31439c08e46 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/conv.pyi @@ -0,0 +1,12 @@ +def to_unicode(obj: float | bytes | str, encoding: str | None = None, from_server: bool = False) -> str: ... +def to_raw(obj, encoding: str = "utf-8"): ... +def escape_filter_chars(text: float | bytes | str, encoding: str | None = None) -> str: ... +def unescape_filter_chars(text, encoding=None): ... +def escape_bytes(bytes_value: str | bytes) -> str: ... +def prepare_for_stream(value): ... +def json_encode_b64(obj): ... +def check_json_dict(json_dict) -> None: ... +def json_hook(obj): ... +def format_json(obj, iso_format: bool = False): ... +def is_filter_escaped(text): ... +def ldap_escape_to_bytes(text): ... diff --git a/stubs/ldap3/ldap3/utils/dn.pyi b/stubs/ldap3/ldap3/utils/dn.pyi new file mode 100644 index 000000000000..0b5c559c604f --- /dev/null +++ b/stubs/ldap3/ldap3/utils/dn.pyi @@ -0,0 +1,11 @@ +STATE_ANY: int +STATE_ESCAPE: int +STATE_ESCAPE_HEX: int + +def to_dn( + iterator, decompose: bool = False, remove_space: bool = False, space_around_equal: bool = False, separate_rdn: bool = False +): ... +def parse_dn(dn, escape: bool = False, strip: bool = False): ... +def safe_dn(dn, decompose: bool = False, reverse: bool = False): ... +def safe_rdn(dn, decompose: bool = False): ... +def escape_rdn(rdn: str) -> str: ... diff --git a/stubs/ldap3/ldap3/utils/hashed.pyi b/stubs/ldap3/ldap3/utils/hashed.pyi new file mode 100644 index 000000000000..86c0f721e2d6 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/hashed.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +algorithms_table: Incomplete +salted_table: Incomplete + +def hashed(algorithm, value, salt=None, raw: bool = False, encoding: str = "utf-8"): ... diff --git a/stubs/ldap3/ldap3/utils/log.pyi b/stubs/ldap3/ldap3/utils/log.pyi new file mode 100644 index 000000000000..9ab59fda4045 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/log.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from logging import NullHandler as NullHandler + +OFF: int +ERROR: int +BASIC: int +PROTOCOL: int +NETWORK: int +EXTENDED: int +DETAIL_LEVELS: Incomplete + +def get_detail_level_name(level_name): ... +def log(detail, message, *args) -> None: ... +def log_enabled(detail): ... +def set_library_log_hide_sensitive_data(hide: bool = True) -> None: ... +def get_library_log_hide_sensitive_data(): ... +def set_library_log_activation_level(logging_level) -> None: ... +def get_library_log_activation_lavel(): ... +def set_library_log_max_line_length(length) -> None: ... +def get_library_log_max_line_length(): ... +def set_library_log_detail_level(detail) -> None: ... +def get_library_log_detail_level(): ... +def format_ldap_message(message, prefix): ... + +logger: Incomplete diff --git a/stubs/ldap3/ldap3/utils/ntlm.pyi b/stubs/ldap3/ldap3/utils/ntlm.pyi new file mode 100644 index 000000000000..37045dcbb0d8 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/ntlm.pyi @@ -0,0 +1,117 @@ +from _typeshed import Incomplete + +oem_encoding: Incomplete +NTLM_SIGNATURE: bytes +NTLM_MESSAGE_TYPE_NTLM_NEGOTIATE: int +NTLM_MESSAGE_TYPE_NTLM_CHALLENGE: int +NTLM_MESSAGE_TYPE_NTLM_AUTHENTICATE: int +FLAG_NEGOTIATE_56: int +FLAG_NEGOTIATE_KEY_EXCH: int +FLAG_NEGOTIATE_128: int +FLAG_NEGOTIATE_VERSION: int +FLAG_NEGOTIATE_TARGET_INFO: int +FLAG_REQUEST_NOT_NT_SESSION_KEY: int +FLAG_NEGOTIATE_IDENTIFY: int +FLAG_NEGOTIATE_EXTENDED_SESSIONSECURITY: int +FLAG_TARGET_TYPE_SERVER: int +FLAG_TARGET_TYPE_DOMAIN: int +FLAG_NEGOTIATE_ALWAYS_SIGN: int +FLAG_NEGOTIATE_OEM_WORKSTATION_SUPPLIED: int +FLAG_NEGOTIATE_OEM_DOMAIN_SUPPLIED: int +FLAG_NEGOTIATE_ANONYMOUS: int +FLAG_NEGOTIATE_NTLM: int +FLAG_NEGOTIATE_LM_KEY: int +FLAG_NEGOTIATE_DATAGRAM: int +FLAG_NEGOTIATE_SEAL: int +FLAG_NEGOTIATE_SIGN: int +FLAG_REQUEST_TARGET: int +FLAG_NEGOTIATE_OEM: int +FLAG_NEGOTIATE_UNICODE: int +FLAG_TYPES: Incomplete +AV_END_OF_LIST: int +AV_NETBIOS_COMPUTER_NAME: int +AV_NETBIOS_DOMAIN_NAME: int +AV_DNS_COMPUTER_NAME: int +AV_DNS_DOMAIN_NAME: int +AV_DNS_TREE_NAME: int +AV_FLAGS: int +AV_TIMESTAMP: int +AV_SINGLE_HOST_DATA: int +AV_TARGET_NAME: int +AV_CHANNEL_BINDINGS: int +AV_TYPES: Incomplete +AV_FLAG_CONSTRAINED: int +AV_FLAG_INTEGRITY: int +AV_FLAG_TARGET_SPN_UNTRUSTED: int +AV_FLAG_TYPES: Incomplete + +def pack_windows_version(debug: bool = False): ... +def unpack_windows_version(version_message): ... + +class NtlmClient: + client_config_flags: int + exported_session_key: Incomplete + negotiated_flags: Incomplete + user_name: Incomplete + user_domain: Incomplete + no_lm_response_ntlm_v1: Incomplete + client_blocked: bool + client_block_exceptions: Incomplete + client_require_128_bit_encryption: Incomplete + max_life_time: Incomplete + client_signing_key: Incomplete + client_sealing_key: Incomplete + sequence_number: Incomplete + server_sealing_key: Incomplete + server_signing_key: Incomplete + integrity: bool + replay_detect: bool + sequence_detect: bool + confidentiality: bool + datagram: bool + identity: bool + client_supplied_target_name: Incomplete + client_channel_binding_unhashed: Incomplete + unverified_target_name: Incomplete + server_challenge: Incomplete + server_target_name: Incomplete + server_target_info: Incomplete + server_version: Incomplete + server_av_netbios_computer_name: Incomplete + server_av_netbios_domain_name: Incomplete + server_av_dns_computer_name: Incomplete + server_av_dns_domain_name: Incomplete + server_av_dns_forest_name: Incomplete + server_av_target_name: Incomplete + server_av_flags: Incomplete + server_av_timestamp: Incomplete + server_av_single_host_data: Incomplete + server_av_channel_bindings: Incomplete + server_av_flag_constrained: Incomplete + server_av_flag_integrity: Incomplete + server_av_flag_target_spn_untrusted: Incomplete + current_encoding: Incomplete + client_challenge: Incomplete + server_target_info_raw: Incomplete + def __init__(self, domain, user_name, password) -> None: ... + def get_client_flag(self, flag): ... + def get_negotiated_flag(self, flag): ... + def get_server_av_flag(self, flag): ... + def set_client_flag(self, flags) -> None: ... + def reset_client_flags(self) -> None: ... + def unset_client_flag(self, flags) -> None: ... + def create_negotiate_message(self): ... + def parse_challenge_message(self, message): ... + def create_authenticate_message(self): ... + @staticmethod + def pack_field(value, offset): ... + @staticmethod + def unpack_field(field_message): ... + @staticmethod + def unpack_av_info(info): ... + @staticmethod + def pack_av_info(avs): ... + @staticmethod + def pack_windows_timestamp(): ... + def compute_nt_response(self): ... + def ntowf_v2(self): ... diff --git a/stubs/ldap3/ldap3/utils/port_validators.pyi b/stubs/ldap3/ldap3/utils/port_validators.pyi new file mode 100644 index 000000000000..c120f02b89b9 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/port_validators.pyi @@ -0,0 +1,2 @@ +def check_port(port): ... +def check_port_and_port_list(port, port_list): ... diff --git a/stubs/ldap3/ldap3/utils/repr.pyi b/stubs/ldap3/ldap3/utils/repr.pyi new file mode 100644 index 000000000000..41c269d19898 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/repr.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +repr_encoding: Incomplete + +def to_stdout_encoding(value): ... diff --git a/stubs/ldap3/ldap3/utils/tls_backport.pyi b/stubs/ldap3/ldap3/utils/tls_backport.pyi new file mode 100644 index 000000000000..c21998013cf2 --- /dev/null +++ b/stubs/ldap3/ldap3/utils/tls_backport.pyi @@ -0,0 +1,3 @@ +class CertificateError(ValueError): ... + +def match_hostname(cert, hostname): ... diff --git a/stubs/ldap3/ldap3/utils/uri.pyi b/stubs/ldap3/ldap3/utils/uri.pyi new file mode 100644 index 000000000000..45ea8bb7699d --- /dev/null +++ b/stubs/ldap3/ldap3/utils/uri.pyi @@ -0,0 +1 @@ +def parse_uri(uri): ... diff --git a/stubs/ldap3/ldap3/version.pyi b/stubs/ldap3/ldap3/version.pyi new file mode 100644 index 000000000000..5939bd051b4b --- /dev/null +++ b/stubs/ldap3/ldap3/version.pyi @@ -0,0 +1,9 @@ +from typing import Final + +__version__: Final[str] +__author__: Final[str] +__email__: Final[str] +__url__: Final[str] +__description__: Final[str] +__status__: Final[str] +__license__: Final[str] diff --git a/stubs/lunardate/METADATA.toml b/stubs/lunardate/METADATA.toml new file mode 100644 index 000000000000..87e20fe9932b --- /dev/null +++ b/stubs/lunardate/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.3.*" +upstream-repository = "https://github.com/lidaobing/python-lunardate" diff --git a/stubs/lunardate/lunardate.pyi b/stubs/lunardate/lunardate.pyi new file mode 100644 index 000000000000..2cb4e87ea2ec --- /dev/null +++ b/stubs/lunardate/lunardate.pyi @@ -0,0 +1,53 @@ +import datetime +from typing import Final, SupportsIndex, overload +from typing_extensions import deprecated + +__version__: Final[str] +__all__ = ["LunarDate"] + +class LunarDate: + year: int + month: int + day: int + is_leap_month: bool + def __init__(self, year: int, month: int, day: int, is_leap_month: bool | None = False) -> None: ... + @property + @deprecated("The `isLeapMonth` is deprecated since v0.3.0. Use `is_leap_month` instead.") + def isLeapMonth(self) -> bool: ... + @staticmethod + @deprecated("The `leapMonthForYear` is deprecated since v0.3.0. Use `leap_month_for_year` instead.") + def leapMonthForYear(year: int) -> int | None: ... + @staticmethod + def leap_month_for_year(year: int) -> int | None: ... + @staticmethod + @deprecated("The `fromSolarDate` is deprecated since v0.3.0. Use `from_solar_date` instead.") + def fromSolarDate(year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> LunarDate: ... + @staticmethod + def from_solar_date(year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> LunarDate: ... + @deprecated("The `toSolarDate` is deprecated since v0.3.0. Use `to_solar_date` instead.") + def toSolarDate(self) -> datetime.date: ... + def to_solar_date(self) -> datetime.date: ... + + @overload + def __sub__(self, other: LunarDate | datetime.date) -> datetime.timedelta: ... + @overload + def __sub__(self, other: datetime.timedelta) -> LunarDate: ... + + def __rsub__(self, other: datetime.date) -> datetime.timedelta: ... + def __add__(self, other: datetime.timedelta) -> LunarDate: ... + def __radd__(self, other: datetime.timedelta) -> LunarDate: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: LunarDate | datetime.date) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: LunarDate | datetime.date) -> bool: ... + @classmethod + def today(cls) -> LunarDate: ... + +YEAR_INFOS: Final[list[int]] + +def year_info_to_year_day(year_info: int) -> int: ... + +YEAR_DAYS: Final[list[int]] + +def day_to_lunar_date(offset: int) -> None: ... diff --git a/stubs/lupa/METADATA.toml b/stubs/lupa/METADATA.toml new file mode 100644 index 000000000000..7867a8a93236 --- /dev/null +++ b/stubs/lupa/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.6.*" +upstream-repository = "https://github.com/scoder/lupa" diff --git a/stubs/lupa/lupa/__init__.pyi b/stubs/lupa/lupa/__init__.pyi new file mode 100644 index 000000000000..d14ef918216c --- /dev/null +++ b/stubs/lupa/lupa/__init__.pyi @@ -0,0 +1,17 @@ +from .lua54 import * + +__all__ = [ + # from lua54 (newest lib) + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] diff --git a/stubs/lupa/lupa/lua51.pyi b/stubs/lupa/lupa/lua51.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua51.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua52.pyi b/stubs/lupa/lupa/lua52.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua52.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua53.pyi b/stubs/lupa/lupa/lua53.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua53.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/lua54.pyi b/stubs/lupa/lupa/lua54.pyi new file mode 100644 index 000000000000..7604148b370b --- /dev/null +++ b/stubs/lupa/lupa/lua54.pyi @@ -0,0 +1,102 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterable +from typing import Any, Final, Generic, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self, disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaTable: + def keys(self) -> Iterable[_LuaKey]: ... + def values(self) -> Iterable[_LuaObject]: ... + def items(self) -> Iterable[tuple[_LuaKey, _LuaObject]]: ... + def __getitem__(self, key: _LuaKey) -> _LuaObject: ... + def __setitem__(self, key: _LuaKey, value: _LuaObject) -> None: ... + def __delitem__(self, key: _LuaKey) -> None: ... + +# A Lua object can be a table or a primitive type. Because we have no way of +# knowing the actual type across languages, we simply use an Any for a Lua +# object. + +# A previous version of this code had +# _LuaObject: TypeAlias = _LuaTable | int | str | float | bool | None +# but that causes false type failures when running, e.g., `lua.globals()['foo']['bar']` +# (because `lua.globals()['foo']` is not known to be a nested table +_LuaKey: TypeAlias = str | int +_LuaObject: TypeAlias = Any + +@type_check_only +class _LuaNoGC: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + def __new__(cls, /, unpack_returned_tuples: bool) -> Self: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = False) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/luajit20.pyi b/stubs/lupa/lupa/luajit20.pyi new file mode 100644 index 000000000000..fdf3fe3d448e --- /dev/null +++ b/stubs/lupa/lupa/luajit20.pyi @@ -0,0 +1,96 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterator +from typing import Any, Final, Generic, TypeVar, type_check_only +from typing_extensions import disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaIter: + def __iter__(self) -> Iterator[object]: ... + +@type_check_only +class _LuaTable: + def keys(self) -> _LuaIter: ... + def values(self) -> _LuaIter: ... + def items(self) -> _LuaIter: ... + +@type_check_only +class _LuaNoGC: ... + +@type_check_only +class _LuaObject: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + # @classmethod + # def __cinit__(cls, unpack_return_tuples: bool) -> None: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = ...) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/luajit21.pyi b/stubs/lupa/lupa/luajit21.pyi new file mode 100644 index 000000000000..fdf3fe3d448e --- /dev/null +++ b/stubs/lupa/lupa/luajit21.pyi @@ -0,0 +1,96 @@ +from _typeshed import MaybeNone +from collections.abc import Callable, Iterator +from typing import Any, Final, Generic, TypeVar, type_check_only +from typing_extensions import disjoint_base + +__all__ = [ + "LUA_VERSION", + "LUA_MAXINTEGER", + "LUA_MININTEGER", + "LuaRuntime", + "LuaError", + "LuaSyntaxError", + "LuaMemoryError", + "as_itemgetter", + "as_attrgetter", + "lua_type", + "unpacks_lua_table", + "unpacks_lua_table_method", +] + +LUA_MAXINTEGER: Final[int] +LUA_MININTEGER: Final[int] +LUA_VERSION: Final[tuple[int, int]] + +# cyfunction object +as_attrgetter: Callable[[object], object] +as_itemgetter: Callable[[object], object] + +# cyfunction object +lua_type: Callable[[object], str | MaybeNone] + +# cyfunction object as decorator +unpacks_lua_table: Callable[[Callable[..., Any]], Callable[..., Any]] +unpacks_lua_table_method: Callable[[Callable[..., Any]], Callable[..., Any]] + +# inner classes + +@type_check_only +class _LuaIter: + def __iter__(self) -> Iterator[object]: ... + +@type_check_only +class _LuaTable: + def keys(self) -> _LuaIter: ... + def values(self) -> _LuaIter: ... + def items(self) -> _LuaIter: ... + +@type_check_only +class _LuaNoGC: ... + +@type_check_only +class _LuaObject: ... + +# classes + +_bint = TypeVar("_bint", bool, int) + +@disjoint_base +class FastRLock(Generic[_bint]): + # @classmethod + # def __init__(cls, /, *args: Any, **kwargs: Any) -> None: ... + def acquire(self, blocking: _bint = ...) -> _bint: ... + def release(self) -> None: ... + def __enter__(self) -> _bint: ... + def __exit__(self, t: object, v: object, tb: object) -> None: ... + +class LuaError(Exception): ... +class LuaSyntaxError(LuaError): ... +class LuaMemoryError(LuaError, MemoryError): ... + +@disjoint_base +class LuaRuntime: + lua_implementation: Final[str] + lua_version: Final[tuple[int, int]] + + # @classmethod + # def __cinit__(cls, unpack_return_tuples: bool) -> None: ... + # def add_pending_unref(self, ref: int) -> None: ... + # def clean_up_pending_unrefs(self) -> int: ... + def get_max_memory(self, total: bool = False) -> int | MaybeNone: ... + def get_memory_used(self, total: bool = False) -> int | MaybeNone: ... + # def reraise_on_exceptions(self) -> int: ... + # def store_raised_exception(self, L: object, lua_error_msg: str) -> None: ... # unannotated + def eval(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def execute(self, lua_code: str, *args: Any, name: str | None = None, mode: str | None = None) -> object: ... + def compile(self, lua_code: str, name: str | None = None, mode: str | None = None) -> Callable[..., object]: ... + def require(self, modulename: str) -> object: ... + def globals(self) -> _LuaTable: ... + def table(self, *items: Any, **kwargs: Any) -> _LuaTable: ... + def table_from(self, *args: Any, recursive: bool = ...) -> _LuaTable: ... + def nogc(self) -> _LuaNoGC: ... + def gccollect(self) -> None: ... + def set_max_memory(self, max_memory: int, total: bool = False) -> None: ... + def set_overflow_handler(self, overflow_handler: Callable[..., None]) -> None: ... + # def register_py_object(self, cname: str, pyname: str, obj: object) -> int: ... + # def init_python_lib(self, register_eval: bool, register_builtins: bool) -> int: ... diff --git a/stubs/lupa/lupa/version.pyi b/stubs/lupa/lupa/version.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/lupa/lupa/version.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/lzstring/@tests/stubtest_allowlist.txt b/stubs/lzstring/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..3f24b90e86d4 --- /dev/null +++ b/stubs/lzstring/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Internal implementation details that are intentionally missing from stub +lzstring.keyStrBase64 +lzstring.keyStrUriSafe +lzstring.baseReverseDic +lzstring.Object +lzstring.getBaseValue diff --git a/stubs/lzstring/METADATA.toml b/stubs/lzstring/METADATA.toml new file mode 100644 index 000000000000..22e4f392e123 --- /dev/null +++ b/stubs/lzstring/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.0.*" +upstream-repository = "https://github.com/gkovacs/lz-string-python" diff --git a/stubs/lzstring/lzstring/__init__.pyi b/stubs/lzstring/lzstring/__init__.pyi new file mode 100644 index 000000000000..8d66d865bd76 --- /dev/null +++ b/stubs/lzstring/lzstring/__init__.pyi @@ -0,0 +1,17 @@ +class LZString: + @staticmethod + def compress(uncompressed: str | None) -> str: ... + @staticmethod + def compressToUTF16(uncompressed: str | None) -> str: ... + @staticmethod + def compressToBase64(uncompressed: str | None) -> str: ... + @staticmethod + def compressToEncodedURIComponent(uncompressed: str | None) -> str: ... + @staticmethod + def decompress(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromUTF16(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromBase64(compressed: str | None) -> str | None: ... + @staticmethod + def decompressFromEncodedURIComponent(compressed: str | None) -> str | None: ... diff --git a/stubs/m3u8/@tests/stubtest_allowlist.txt b/stubs/m3u8/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7842199c24e4 --- /dev/null +++ b/stubs/m3u8/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +# type check only +m3u8.httpclient.HTTPSHandler.__new__ +# internal functions and attributes +m3u8.parser.get_segment_custom_value +m3u8.parser.save_segment_custom_value diff --git a/stubs/m3u8/METADATA.toml b/stubs/m3u8/METADATA.toml new file mode 100644 index 000000000000..eb4c10a4f5cc --- /dev/null +++ b/stubs/m3u8/METADATA.toml @@ -0,0 +1,2 @@ +version = "6.0.*" +upstream-repository = "https://github.com/globocom/m3u8" diff --git a/stubs/m3u8/m3u8/__init__.pyi b/stubs/m3u8/m3u8/__init__.pyi new file mode 100644 index 000000000000..6fe32d5edeee --- /dev/null +++ b/stubs/m3u8/m3u8/__init__.pyi @@ -0,0 +1,72 @@ +from collections.abc import Callable, Mapping +from typing import Any, TypeAlias + +from m3u8.httpclient import _HTTPClientProtocol +from m3u8.model import ( + M3U8, + ContentSteering, + DateRange, + DateRangeList, + IFramePlaylist, + ImagePlaylist, + Key, + Media, + MediaList, + PartialSegment, + PartialSegmentList, + PartInformation, + Playlist, + PlaylistList, + PreloadHint, + RenditionReport, + RenditionReportList, + Segment, + SegmentList, + ServerControl, + Skip, + Start, + Tiles, +) +from m3u8.parser import ParseError, parse + +__all__ = ( + "M3U8", + "Segment", + "SegmentList", + "PartialSegment", + "PartialSegmentList", + "Key", + "Playlist", + "IFramePlaylist", + "Media", + "MediaList", + "PlaylistList", + "Start", + "RenditionReport", + "RenditionReportList", + "ServerControl", + "Skip", + "PartInformation", + "PreloadHint", + "DateRange", + "DateRangeList", + "ContentSteering", + "ImagePlaylist", + "Tiles", + "loads", + "load", + "parse", + "ParseError", +) + +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Any], dict[str, Any]], object] + +def loads(content: str, uri: str | None = None, custom_tags_parser: _CustomTagsParser | None = None) -> M3U8: ... +def load( + uri: str, + timeout: float | None = None, + headers: Mapping[str, Any] = {}, + custom_tags_parser: _CustomTagsParser | None = None, + http_client: _HTTPClientProtocol = ..., + verify_ssl: bool = True, +) -> M3U8: ... diff --git a/stubs/m3u8/m3u8/httpclient.pyi b/stubs/m3u8/m3u8/httpclient.pyi new file mode 100644 index 000000000000..96569e96e167 --- /dev/null +++ b/stubs/m3u8/m3u8/httpclient.pyi @@ -0,0 +1,19 @@ +import urllib.request +from typing import Any, Protocol, type_check_only + +@type_check_only +class _HTTPClientProtocol(Protocol): # noqa: Y046 + def download( + self, uri: str, timeout: float | None = None, headers: dict[str, Any] = {}, verify_ssl: bool = True + ) -> tuple[str, str]: ... + +class DefaultHTTPClient: + proxies: dict[str, str] | None + + def __init__(self, proxies: dict[str, str] | None = None) -> None: ... + def download( + self, uri: str, timeout: float | None = None, headers: dict[str, Any] = {}, verify_ssl: bool = True + ) -> tuple[str, str]: ... + +class HTTPSHandler: + def __new__(cls, verify_ssl: bool = True) -> urllib.request.HTTPSHandler: ... # type: ignore[misc] diff --git a/stubs/m3u8/m3u8/mixins.pyi b/stubs/m3u8/m3u8/mixins.pyi new file mode 100644 index 000000000000..9e5d89db5772 --- /dev/null +++ b/stubs/m3u8/m3u8/mixins.pyi @@ -0,0 +1,28 @@ +from abc import ABCMeta +from collections.abc import Iterable +from typing import TypeVar + +_T = TypeVar("_T") + +class BasePathMixin: + uri: str | None + @property + def absolute_uri(self) -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def get_path_from_uri(self) -> str: ... + +class GroupedBasePathMixin(Iterable[_T], metaclass=ABCMeta): + @property + def base_uri(self) -> str: ... + @base_uri.setter + def base_uri(self, __new_url: str, /) -> None: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, __new_url: str, /) -> None: ... diff --git a/stubs/m3u8/m3u8/model.pyi b/stubs/m3u8/m3u8/model.pyi new file mode 100644 index 000000000000..f532280b71b2 --- /dev/null +++ b/stubs/m3u8/m3u8/model.pyi @@ -0,0 +1,454 @@ +import datetime as dt +from _typeshed import Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable, Iterable, Mapping +from decimal import Decimal +from typing import Any, ClassVar, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from m3u8.mixins import BasePathMixin, GroupedBasePathMixin +from m3u8.protocol import ext_x_map, ext_x_session_key + +_T = TypeVar("_T") +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Incomplete], dict[str, Incomplete]], object] + +@type_check_only +class _PlaylistProtocol(Protocol): + base_uri: str | None + uri: str | None + @property + def absolute_uri(self) -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def get_path_from_uri(self) -> str: ... + +_PlaylistAnyT = TypeVar("_PlaylistAnyT", bound=_PlaylistProtocol) + +class MalformedPlaylistError(Exception): ... + +class M3U8: + simple_attributes: tuple[tuple[str, str], ...] + data: dict[str, Incomplete] + keys: list[Key] + segment_map: list[InitializationSection] + segments: SegmentList + files: list[str | None] + media: MediaList + playlists: PlaylistList[Playlist] + iframe_playlists: PlaylistList[IFramePlaylist] + image_playlists: PlaylistList[ImagePlaylist] + start: Start + server_control: ServerControl + part_inf: PartInformation + skip: Skip + rendition_reports: RenditionReportList + session_data: SessionDataList + session_keys: list[SessionKey | None] + preload_hint: PreloadHint + content_steering: ContentSteering + + # inserted via setattr() + + is_variant: bool | None + is_endlist: bool | None + is_i_frames_only: bool | None + target_duration: float | None + media_sequence: int | None + program_date_time: dt.datetime | None + is_independent_segments: bool | None + version: str | None + allow_cache: str | None + playlist_type: str | None + discontinuity_sequence: Incomplete | None # undocmented + is_images_only: bool | None + + def __init__( + self, + content: str | None = None, + base_path: str | None = None, + base_uri: str | None = None, + strict: bool = False, + custom_tags_parser: _CustomTagsParser | None = None, + ) -> None: ... + + @property + def base_uri(self) -> str | None: ... + @base_uri.setter + def base_uri(self, new_base_uri: str) -> None: ... + + @property + def base_path(self) -> str | None: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + def add_playlist(self, playlist: Playlist) -> None: ... + def add_iframe_playlist(self, iframe_playlist: IFramePlaylist) -> None: ... + def add_image_playlist(self, image_playlist: ImagePlaylist) -> None: ... + def add_media(self, media: Media) -> None: ... + def add_segment(self, segment: Segment) -> None: ... + def add_rendition_report(self, report: RenditionReport) -> None: ... + def dumps(self, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + def dump(self, filename: StrOrBytesPath) -> None: ... + def __unicode__(self) -> str: ... + +class Segment(BasePathMixin): + media_sequence: int | None + uri: str | None + duration: float | None + title: str + bitrate: int | None + byterange: str | None + program_date_time: dt.datetime | None + current_program_date_time: dt.datetime | None + discontinuity: bool + cue_out_start: bool + cue_out_explicitly_duration: bool + cue_out: bool + cue_in: bool + scte35: str | None + oatcls_scte35: str | None + scte35_duration: float | None + scte35_elapsedtime: Incomplete | None + asset_metadata: dict[str, Incomplete] | None + key: Key | None + parts: PartialSegmentList + init_section: InitializationSection | None + dateranges: DateRangeList + gap_tag: Incomplete | None + custom_parser_values: dict[str, Incomplete] + def __init__( + self, + uri: str | None = None, + base_uri: str | None = None, + program_date_time: dt.datetime | None = None, + current_program_date_time: dt.datetime | None = None, + duration: float | None = None, + title: str | None = None, + bitrate: int | None = None, + byterange: str | None = None, + cue_out: bool = False, + cue_out_start: bool = False, + cue_out_explicitly_duration: bool = False, + cue_in: bool = False, + discontinuity: bool = False, + key: Unused = None, + scte35: str | None = None, + oatcls_scte35: str | None = None, + scte35_duration: float | None = None, + scte35_elapsedtime=None, + asset_metadata: Mapping[str, str] | None = None, + keyobject: Key | None = None, + parts: Iterable[Mapping[str, Incomplete]] | None = None, + init_section: Mapping[str, Incomplete] | None = None, + dateranges: Iterable[Mapping[str, Incomplete]] | None = None, + gap_tag: list[Mapping[str, Incomplete]] | None = None, + media_sequence: int | None = None, + custom_parser_values: dict[str, Incomplete] | None = None, + ) -> None: ... + def add_part(self, part: PartialSegment) -> None: ... + def dumps(self, last_segment: PartialSegment | None, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + + @property + def base_path(self) -> str: ... + @base_path.setter + def base_path(self, newbase_path: str) -> None: ... + + @property + def base_uri(self) -> str: ... + @base_uri.setter + def base_uri(self, newbase_uri: str) -> None: ... + +class SegmentList(list[Segment], GroupedBasePathMixin[Segment]): + def dumps(self, timespec: str = "milliseconds", infspec: str = "auto") -> str: ... + @property + def uri(self) -> list[str | None]: ... + def by_key(self, key: Key) -> list[Segment]: ... + +class PartialSegment(BasePathMixin): + base_uri: str + uri: str | None + duration: float | None + program_date_time: dt.datetime | None + current_program_date_time: dt.datetime | None + byterange: str | None + independent: bool + gap: str | None + dateranges: DateRangeList + gap_tag: str | None + + def __init__( + self, + base_uri: str, + uri: str | None, + duration: float | None, + program_date_time: dt.datetime | None = None, + current_program_date_time: dt.datetime | None = None, + byterange: str | None = None, + independent=None, + gap=None, + dateranges: Iterable[Mapping[str, Incomplete]] | None = None, + gap_tag=None, + ) -> None: ... + def dumps(self, last_segment) -> str: ... + +class PartialSegmentList(list[PartialSegment], GroupedBasePathMixin[PartialSegment]): ... + +class Key(BasePathMixin): + tag: ClassVar[str] = ... + method: str + base_uri: str + uri: str | None + iv: str | None + keyformat: str | None + keyformatversions: str | None + + def __init__( + self, + method: str, + base_uri: str, + uri: str | None = None, + iv: str | None = None, + keyformat: str | None = None, + keyformatversions: str | None = None, + **kwargs, + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class InitializationSection(BasePathMixin): + tag = ext_x_map + base_uri: str + uri: str | None + byterange: str | None + def __init__(self, base_uri: str, uri: str | None, byterange: str | None = None) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class SessionKey(Key): + tag = ext_x_session_key + +class Playlist(_PlaylistProtocol): + base_uri: str | None + uri: str | None + stream_info: StreamInfo + media: MediaList + def __init__(self, uri: str | None, stream_info: Mapping[str, Incomplete], media: MediaList, base_uri: str) -> None: ... + +class IFramePlaylist(_PlaylistProtocol): + uri: str | None + base_uri: str | None + iframe_stream_info: StreamInfo + def __init__(self, base_uri: str, uri: str | None, iframe_stream_info: Mapping[str, Incomplete]) -> None: ... + +class StreamInfo: + bandwidth: int | None + closed_captions: Incomplete | None + average_bandwidth: int | None + program_id: int | None + resolution: tuple[int, int] | None + codecs: str | None + audio: str | None + video: str | None + subtitles: str | None + frame_rate: float | None + video_range: str | None + hdcp_level: str | None + pathway_id: str | None + stable_variant_id: str | None + req_video_layout: str | None + def __init__( + self, + *, + bandwidth: int | None = None, + closed_captions=None, + average_bandwidth: int | None = None, + program_id: int | None = None, + resolution: tuple[int, int] | None = None, + codecs: str | None = None, + audio: str | None = None, + video: str | None = None, + subtitles: str | None = None, + frame_rate: float | None = None, + video_range: str | None = None, + hdcp_level: str | None = None, + pathway_id: str | None = None, + stable_variant_id: str | None = None, + req_video_layout: str | None = None, + ) -> None: ... + +class Media(BasePathMixin): + base_uri: str | None + uri: str | None + type: str | None + group_id: str | None + language: str | None + name: str | None + default: str | None + autoselect: str | None + forced: str | None + assoc_language: str | None + instream_id: str | None + characteristics: str | None + channels: str | None + stable_rendition_id: str | None + extras: dict[str, Incomplete] + + def __init__( + self, + uri: str | None = None, + type: str | None = None, + group_id: str | None = None, + language: str | None = None, + name: str | None = None, + default: str | None = None, + autoselect: str | None = None, + forced: str | None = None, + characteristics: str | None = None, + channels: str | None = None, + stable_rendition_id: str | None = None, + assoc_language: str | None = None, + instream_id: str | None = None, + base_uri: str | None = None, + **extras, + ) -> None: ... + def dumps(self) -> str: ... + +class TagList(list[_T]): ... + +class MediaList(TagList[Media], list[Media], GroupedBasePathMixin[Media]): + @property + def uri(self) -> list[str | None]: ... + +class PlaylistList(TagList[_PlaylistAnyT], list[_PlaylistAnyT], GroupedBasePathMixin[_PlaylistAnyT]): ... +class SessionDataList(TagList[SessionData], list[SessionData]): ... + +class Start: + time_offset: float + precise: Literal["YES", "NO"] + def __init__(self, time_offset: float, precise: Literal["YES", "NO"] | None = None) -> None: ... + +class RenditionReport(BasePathMixin): + base_uri: str | None + uri: str | None + last_msn: int + last_part: int | None + def __init__(self, base_uri: str | None, uri: str | None, last_msn: int, last_part: int | None = None) -> None: ... + def dumps(self) -> str: ... + +class RenditionReportList(list[RenditionReport], GroupedBasePathMixin[RenditionReport]): ... + +class ServerControl: + can_skip_until: float | None + can_block_reload: str | None + hold_back: float | None + part_hold_back: float | None + can_skip_dateranges: str | None + def __init__( + self, + can_skip_until: float | None = None, + can_block_reload: str | None = None, + hold_back: float | None = None, + part_hold_back: float | None = None, + can_skip_dateranges: str | None = None, + ) -> None: ... + def __getitem__(self, item: str) -> str | float | None: ... + def dumps(self) -> str: ... + +class Skip: + skipped_segments: int | None + recently_removed_dateranges: str | None + def __init__(self, skipped_segments: int, recently_removed_dateranges: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class PartInformation: + part_target: float | None + def __init__(self, part_target: float | None = None) -> None: ... + def dumps(self) -> str: ... + +class PreloadHint(BasePathMixin): + hint_type: str | None + base_uri: str | None + uri: str | None + byterange_start: int | None + byterange_length: int | None + def __init__( + self, + type: str | None, + base_uri: str | None, + uri: str | None, + byterange_start: int | None = None, + byterange_length: int | None = None, + ) -> None: ... + def __getitem__(self, item: str) -> str | int | None: ... + def dumps(self) -> str: ... + +class SessionData: + data_id: str + value: str | None + uri: str | None + language: str | None + def __init__(self, data_id: str, value: str | None = None, uri: str | None = None, language: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class DateRangeList(TagList[DateRange]): ... + +class DateRange: + id: str + start_date: str | None + class_: str | None + end_date: str | None + duration: float | None + planned_duration: float | None + scte35_cmd: str | None + scte35_out: str | None + scte35_in: str | None + end_on_next: Incomplete + x_client_attrs: list[tuple[str, str]] + def __init__( + self, + *, + id: str, + start_date: str | None = None, + class_: str | None = None, # actually passing as `class` argument + end_date: str | None = None, + duration: float | None = None, + planned_duration: float | None = None, + scte35_cmd: str | None = None, + scte35_out: str | None = None, + scte35_in: str | None = None, + end_on_next=None, + **kwargs: str, # for arguments with `x_` prefix + ) -> None: ... + def dumps(self) -> str: ... + +class ContentSteering(BasePathMixin): + base_uri: str | None + uri: str | None + pathway_id: str | None + def __init__(self, base_uri: str | None, server_uri: str | None, pathway_id: str | None = None) -> None: ... + def dumps(self) -> str: ... + +class ImagePlaylist(_PlaylistProtocol): + uri: str | None + base_uri: str | None + image_stream_info: StreamInfo + def __init__(self, base_uri: str | None, uri: str | None, image_stream_info: Mapping[str, Incomplete]) -> None: ... + +class Tiles(BasePathMixin): # this is unused in runtime, so this is (temporary) has incomplete + uri: str | None + resolution: Incomplete + layout: Incomplete + duration: Incomplete + def __init__(self, resolution, layout, duration) -> None: ... + def dumps(self) -> str: ... + +@overload +def find_key(keydata: None, keylist: Iterable[Key | None]) -> None: ... +@overload +def find_key(keydata: Mapping[str, Any], keylist: Iterable[Key | None]) -> Key: ... # keydata can contain any values + +def denormalize_attribute(attribute: str) -> str: ... +def quoted(string: str | None) -> str: ... +def number_to_string(number: str | float | Decimal) -> str: ... diff --git a/stubs/m3u8/m3u8/parser.pyi b/stubs/m3u8/m3u8/parser.pyi new file mode 100644 index 000000000000..5970547659bd --- /dev/null +++ b/stubs/m3u8/m3u8/parser.pyi @@ -0,0 +1,29 @@ +from collections.abc import Callable +from datetime import date, datetime, time +from itertools import repeat +from re import Pattern +from typing import Any, TypeAlias, overload + +_CustomTagsParser: TypeAlias = Callable[[str, int, dict[str, Any], dict[str, Any]], object] + +ATTRIBUTELISTPATTERN: Pattern[str] + +def cast_date_time(value: str) -> datetime: ... + +@overload +def format_date_time(value: time, *, timespec: str = ...) -> str: ... +@overload +def format_date_time(value: datetime, *, sep: str = ..., timespec: str = ...) -> str: ... +@overload +def format_date_time(value: date) -> str: ... + +class ParseError(Exception): + lineno: int + line: str + def __init__(self, lineno: int, line: str) -> None: ... + +def parse(content: str, strict: bool = False, custom_tags_parser: _CustomTagsParser | None = None) -> dict[str, Any]: ... +def string_to_lines(string: str) -> list[str]: ... +def remove_quotes_parser(*attrs: repeat[Callable[[str], str]]) -> dict[repeat[Callable[[str], str]], Callable[[str], str]]: ... +def remove_quotes(string: str) -> str: ... +def normalize_attribute(attribute: str) -> str: ... diff --git a/stubs/m3u8/m3u8/protocol.pyi b/stubs/m3u8/m3u8/protocol.pyi new file mode 100644 index 000000000000..06bb58b5a20c --- /dev/null +++ b/stubs/m3u8/m3u8/protocol.pyi @@ -0,0 +1,41 @@ +ext_m3u: str +ext_x_targetduration: str +ext_x_media_sequence: str +ext_x_discontinuity_sequence: str +ext_x_program_date_time: str +ext_x_media: str +ext_x_playlist_type: str +ext_x_key: str +ext_x_stream_inf: str +ext_x_version: str +ext_x_allow_cache: str +ext_x_endlist: str +extinf: str +ext_i_frames_only: str +ext_x_asset: str +ext_x_bitrate: str +ext_x_byterange: str +ext_x_i_frame_stream_inf: str +ext_x_discontinuity: str +ext_x_cue_out: str +ext_x_cue_out_cont: str +ext_x_cue_in: str +ext_x_cue_span: str +ext_oatcls_scte35: str +ext_is_independent_segments: str +ext_x_map: str +ext_x_start: str +ext_x_server_control: str +ext_x_part_inf: str +ext_x_part: str +ext_x_rendition_report: str +ext_x_skip: str +ext_x_session_data: str +ext_x_session_key: str +ext_x_preload_hint: str +ext_x_daterange: str +ext_x_gap: str +ext_x_content_steering: str +ext_x_image_stream_inf: str +ext_x_images_only: str +ext_x_tiles: str diff --git a/stubs/m3u8/m3u8/version_matching.pyi b/stubs/m3u8/m3u8/version_matching.pyi new file mode 100644 index 000000000000..6f4265b2ebfc --- /dev/null +++ b/stubs/m3u8/m3u8/version_matching.pyi @@ -0,0 +1,5 @@ +from m3u8.version_matching_rules import VersionMatchingError + +def get_version(file_lines: list[str]) -> float | None: ... +def valid_in_all_rules(line_number: int, line: str, version: float) -> list[VersionMatchingError]: ... +def validate(file_lines: list[str]) -> list[VersionMatchingError]: ... diff --git a/stubs/m3u8/m3u8/version_matching_rules.pyi b/stubs/m3u8/m3u8/version_matching_rules.pyi new file mode 100644 index 000000000000..2fb0bde7212f --- /dev/null +++ b/stubs/m3u8/m3u8/version_matching_rules.pyi @@ -0,0 +1,24 @@ +from dataclasses import dataclass + +@dataclass +class VersionMatchingError(Exception): + line_number: int + line: str + how_to_fix: str = ... + description: str = ... + +class VersionMatchRuleBase: + description: str + how_to_fix: str + version: float + line_number: int + line: str + def __init__(self, version: float, line_number: int, line: str) -> None: ... + def validate(self) -> bool: ... + def get_error(self) -> VersionMatchingError: ... + +class ValidIVInEXTXKEY(VersionMatchRuleBase): ... +class ValidFloatingPointEXTINF(VersionMatchRuleBase): ... +class ValidEXTXBYTERANGEOrEXTXIFRAMESONLY(VersionMatchRuleBase): ... + +available_rules: list[type[VersionMatchRuleBase]] diff --git a/stubs/mock/@tests/stubtest_allowlist.txt b/stubs/mock/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..636393741865 --- /dev/null +++ b/stubs/mock/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# Uses `_timeout_unset` sentinel: +mock.mock.ThreadingMixin.__init__ +mock.mock.ThreadingMixin.wait_until_called diff --git a/stubs/mock/METADATA.toml b/stubs/mock/METADATA.toml new file mode 100644 index 000000000000..1436f5662373 --- /dev/null +++ b/stubs/mock/METADATA.toml @@ -0,0 +1,2 @@ +version = "5.2.*" +upstream-repository = "https://github.com/testing-cabal/mock" diff --git a/stubs/mock/mock/__init__.pyi b/stubs/mock/mock/__init__.pyi new file mode 100644 index 000000000000..4fc3625d63a7 --- /dev/null +++ b/stubs/mock/mock/__init__.pyi @@ -0,0 +1,24 @@ +from .mock import * + +__all__ = ( + "__version__", + "version_info", + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "ThreadingMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +) +__version__: str +version_info: tuple[int, int, int] diff --git a/stubs/mock/mock/backports.pyi b/stubs/mock/mock/backports.pyi new file mode 100644 index 000000000000..9cb45af2cd60 --- /dev/null +++ b/stubs/mock/mock/backports.pyi @@ -0,0 +1,2 @@ +from inspect import iscoroutinefunction as iscoroutinefunction +from unittest import IsolatedAsyncioTestCase as IsolatedAsyncioTestCase diff --git a/stubs/mock/mock/mock.pyi b/stubs/mock/mock/mock.pyi new file mode 100644 index 000000000000..8ec149dd76a4 --- /dev/null +++ b/stubs/mock/mock/mock.pyi @@ -0,0 +1,377 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Coroutine, Iterable, Mapping, Sequence +from contextlib import AbstractContextManager +from types import TracebackType +from typing import Any, ClassVar, Generic, Literal, ParamSpec, TypeVar, overload, type_check_only +from typing_extensions import Self + +_F = TypeVar("_F", bound=Callable[..., Any]) +_AF = TypeVar("_AF", bound=Callable[..., Coroutine[Any, Any, Any]]) +_T = TypeVar("_T") +_TT = TypeVar("_TT", bound=type[Any]) +_R = TypeVar("_R") +_P = ParamSpec("_P") + +__all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "ThreadingMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", +) + +class InvalidSpecError(Exception): ... + +FILTER_DIR: bool + +class _SentinelObject: + def __init__(self, name: str) -> None: ... + name: str + +class _Sentinel: + def __getattr__(self, name: str) -> _SentinelObject: ... + +sentinel: _Sentinel +DEFAULT: _SentinelObject + +class _Call(tuple[Any, ...]): + def __new__( + cls, value: Any = (), name: Incomplete | None = "", parent=None, two: bool = False, from_kall: bool = True + ) -> Self: ... + name: Any + parent: Any + from_kall: Any + def __init__(self, value: Any = (), name=None, parent=None, two: bool = False, from_kall: bool = True) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... + def __getattr__(self, attr: str) -> Any: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> dict[str, Any]: ... + def call_list(self) -> _CallList: ... + +call: _Call + +class _CallList(list[_Call]): + def __contains__(self, value: Any) -> bool: ... + +class Base: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +# We subclass with "Any" because mocks are explicitly designed to stand in for other types, +# something that can't be expressed with our static type system. +class NonCallableMock(Base, Any): + def __new__( + cls, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state=None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> Self: ... + def __init__( + self, + spec: list[str] | object | type[object] | None = None, + wraps: Any | None = None, + name: str | None = None, + spec_set: list[str] | object | type[object] | None = None, + parent: NonCallableMock | None = None, + _spec_state=None, + _new_name: str = "", + _new_parent: NonCallableMock | None = None, + _spec_as_instance: bool = False, + _eat_self: bool | None = None, + unsafe: bool = False, + **kwargs: Any, + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def _calls_repr(self) -> str: ... + def assert_called_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_not_called(_mock_self) -> None: ... + def assert_called_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = "call") -> str: ... + def assert_called(_mock_self) -> None: ... + def assert_called_once(_mock_self) -> None: ... + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + def _extract_mock_name(self) -> str: ... + def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: ... + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ... + def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ... + def configure_mock(self, **kwargs: Any) -> None: ... + return_value: Any + side_effect: Any + called: bool + call_count: int + call_args: Any + call_args_list: _CallList + mock_calls: _CallList + def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... + def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: ... + def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... + +class CallableMixin(Base): + side_effect: Any + def __init__( + self, + spec=None, + side_effect=None, + return_value: Any = ..., + wraps=None, + name=None, + spec_set=None, + parent=None, + _spec_state=None, + _new_name: Any = "", + _new_parent=None, + **kwargs: Any, + ) -> None: ... + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + +class Mock(CallableMixin, NonCallableMock): ... + +class _patch(Generic[_T]): + attribute_name: Any + getter: Callable[[], Any] + attribute: str + new: _T + new_callable: Any + spec: Any + create: bool + has_local: Any + spec_set: Any + autospec: Any + kwargs: Mapping[str, Any] + additional_patchers: Any + def __init__( + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Incomplete | None, + create: bool, + spec_set: Incomplete | None, + autospec: Incomplete | None, + new_callable: Incomplete | None, + kwargs: Mapping[str, Any], + *, + unsafe: bool = False, + ) -> None: ... + def copy(self) -> _patch[_T]: ... + def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + def decorate_class(self, klass: _TT) -> _TT: ... + def decorate_callable(self, func: _F) -> _F: ... + def decorate_async_callable(self, func: _AF) -> _AF: ... + def decoration_helper( + self, patched: Any, args: tuple[Any, ...], keywargs: dict[str, Any] + ) -> AbstractContextManager[tuple[tuple[Any, ...], dict[str, Any]]]: ... + def get_original(self) -> tuple[Any, bool]: ... + target: Any + temp_original: Any + is_local: bool + def __enter__(self) -> _T: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + def start(self) -> _T: ... + def stop(self) -> None: ... + +class _patch_dict: + in_dict: Any + values: Any + clear: Any + def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ... + def __call__(self, f: Any) -> Any: ... + def decorate_callable(self, f: _F) -> _F: ... + def decorate_async_callable(self, f: _AF) -> _AF: ... + def decorate_class(self, klass: Any) -> Any: ... + def __enter__(self) -> Any: ... + def __exit__(self, *args: object) -> Any: ... + start: Any + stop: Any + +@type_check_only +class _patcher: + TEST_PREFIX: str + dict: type[_patch_dict] + + @overload + def __call__( + self, + target: Any, + *, + spec: Incomplete | None = ..., + create: bool = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + unsafe: bool = ..., + **kwargs: Any, + ) -> _patch[MagicMock | AsyncMock]: ... + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. + # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], + # but that's impossible with the current type system. + @overload + def __call__( + self, + target: Any, + new: _T, + spec: Incomplete | None = ..., + create: bool = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + + @overload + def object( + self, + target: Any, + attribute: str, + *, + spec: Incomplete | None = ..., + create: bool = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + unsafe: bool = ..., + **kwargs: Any, + ) -> _patch[MagicMock | AsyncMock]: ... + @overload + def object( + self, + target: Any, + attribute: str, + new: _T, + spec: Incomplete | None = ..., + create: bool = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., + **kwargs: Any, + ) -> _patch[_T]: ... + + def multiple( + self, + target: Any, + spec: Incomplete | None = ..., + create: bool = ..., + spec_set: Incomplete | None = ..., + autospec: Incomplete | None = ..., + new_callable: Incomplete | None = ..., + *, + unsafe: bool = ..., + **kwargs: _T, + ) -> _patch[_T]: ... + def stopall(self) -> None: ... + +patch: _patcher + +class MagicMixin: + def __init__(self, *args: Any, **kw: Any) -> None: ... + +class NonCallableMagicMock(MagicMixin, NonCallableMock): + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + +class MagicMock(MagicMixin, Mock): + def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ... + +class AsyncMockMixin(Base): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited(_mock_self) -> None: ... + def assert_awaited_once(_mock_self) -> None: ... + def assert_awaited_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_awaited_once_with(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_any_await(_mock_self, *args: Any, **kwargs: Any) -> None: ... + def assert_has_awaits(_mock_self, calls: Iterable[_Call], any_order: bool = False) -> None: ... + def assert_not_awaited(_mock_self) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + await_count: int + await_args: _Call | None + await_args_list: _CallList + __name__: str + __defaults__: tuple[Any, ...] + __kwdefaults__: dict[str, Any] + __annotations__: dict[str, Any] | None # type: ignore[assignment] + +class AsyncMagicMixin(MagicMixin): ... + +class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... + +class MagicProxy(Base): + name: str + parent: Any + def __init__(self, name: str, parent: Any) -> None: ... + def create_mock(self) -> Any: ... + def __get__(self, obj: Any, _type=None) -> Any: ... + +class _ANY(Any): + def __eq__(self, other: object) -> Literal[True]: ... + def __ne__(self, other: object) -> Literal[False]: ... + +ANY: _ANY + +def create_autospec( + spec: Any, spec_set: Any = False, instance: Any = False, _parent=None, _name=None, *, unsafe: bool = False, **kwargs: Any +) -> Any: ... + +class _SpecState: + spec: Any + ids: Any + spec_set: Any + parent: Any + instance: Any + name: Any + def __init__(self, spec: Any, spec_set: Any = False, parent=None, name=None, ids=None, instance: Any = False) -> None: ... + +def mock_open(mock=None, read_data: Any = "") -> Any: ... + +class PropertyMock(Mock): + def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ... + def __set__(self, obj: Any, value: Any) -> None: ... + +def seal(mock: Any) -> None: ... + +class ThreadingMixin(Base): + DEFAULT_TIMEOUT: ClassVar[float | None] + + def __init__(self, *args: Any, timeout: float | None = ..., **kwargs: Any) -> None: ... + def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... + def wait_until_called(self, *, timeout: float | None = ...) -> None: ... + def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ... + +class ThreadingMock(ThreadingMixin, MagicMixin, Mock): + # Improving the `reset_mock` signature. + # It is defined on `ThreadingMixin` with `*args, **kwargs`, which is not ideal. + # But, `NonCallableMock` super-class has the better version. + def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... diff --git a/stubs/mypy-extensions/@tests/stubtest_allowlist.txt b/stubs/mypy-extensions/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..4f48c1c4bbe4 --- /dev/null +++ b/stubs/mypy-extensions/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +mypy_extensions.FlexibleAlias +mypy_extensions.TypedDict +mypy_extensions.i64.* +mypy_extensions.i32.* +mypy_extensions.i16.* +mypy_extensions.u8.* diff --git a/stubs/mypy-extensions/METADATA.toml b/stubs/mypy-extensions/METADATA.toml new file mode 100644 index 000000000000..33583f5d725b --- /dev/null +++ b/stubs/mypy-extensions/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1.*" +upstream-repository = "https://github.com/python/mypy_extensions" diff --git a/stubs/mypy-extensions/mypy_extensions.pyi b/stubs/mypy-extensions/mypy_extensions.pyi new file mode 100644 index 000000000000..f4f7fa6faf76 --- /dev/null +++ b/stubs/mypy-extensions/mypy_extensions.pyi @@ -0,0 +1,95 @@ +import abc +from _collections_abc import dict_items, dict_keys, dict_values +from _typeshed import IdentityFunction, Unused +from collections.abc import Mapping +from typing import Any, ClassVar, Generic, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, deprecated + +_T = TypeVar("_T") +_U = TypeVar("_U") + +# Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing(_extensions)._TypedDict +@type_check_only +@deprecated("Use typing._TypedDict instead") +class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): + __total__: ClassVar[bool] + # Unlike typing(_extensions).TypedDict, + # subclasses of mypy_extensions.TypedDict do NOT have the __required_keys__ and __optional_keys__ ClassVars + def copy(self) -> Self: ... + # Using Never so that only calls using mypy plugin hook that specialize the signature + # can go through. + def setdefault(self, k: Never, default: object) -> object: ... + # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. + def pop(self, k: Never, default: _T = ...) -> object: ... # pyright: ignore[reportInvalidTypeVarUse] + def update(self, m: Self, /) -> None: ... + def items(self) -> dict_items[str, object]: ... + def keys(self) -> dict_keys[str, object]: ... + def values(self) -> dict_values[str, object]: ... + def __delitem__(self, k: Never) -> None: ... + + @overload + def __or__(self, value: Self, /) -> Self: ... + @overload + def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + @overload + def __ror__(self, value: Self, /) -> Self: ... + @overload + def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + + # supposedly incompatible definitions of `__or__` and `__ior__`: + def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] + +@deprecated("Use typing.TypedDict or typing_extensions.TypedDict instead") +def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... + +@overload +def Arg(type: _T, name: str | None = ...) -> _T: ... +@overload +def Arg(*, name: str | None = ...) -> Any: ... + +@overload +def DefaultArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultArg(*, name: str | None = ...) -> Any: ... + +@overload +def NamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def NamedArg(*, name: str | None = ...) -> Any: ... + +@overload +def DefaultNamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultNamedArg(*, name: str | None = ...) -> Any: ... + +@overload +def VarArg(type: _T) -> _T: ... +@overload +def VarArg() -> Any: ... + +@overload +def KwArg(type: _T) -> _T: ... +@overload +def KwArg() -> Any: ... + +# Return type that indicates a function does not return. +@deprecated("Use typing.Never instead") +class NoReturn: ... + +# This is consistent with implementation. Usage intends for this as +# a class decorator, but mypy does not support type[_T] for abstract +# classes until this issue is resolved, https://github.com/python/mypy/issues/4717. +def trait(cls: _T) -> _T: ... +def mypyc_attr(*attrs: str, **kwattrs: Unused) -> IdentityFunction: ... + +class FlexibleAlias(Generic[_T, _U]): ... + +# Mypy and mypyc treat these native int types as different from 'int', but this is +# a non-standard extension. For other tools, aliasing these to 'int' allows them +# to mostly do the right thing with these types. +i64 = int +i32 = int +i16 = int +u8 = int diff --git a/stubs/mysqlclient/METADATA.toml b/stubs/mysqlclient/METADATA.toml new file mode 100644 index 000000000000..0d734f1277b1 --- /dev/null +++ b/stubs/mysqlclient/METADATA.toml @@ -0,0 +1,5 @@ +version = "2.2.*" +upstream-repository = "https://github.com/PyMySQL/mysqlclient" + +[tool.stubtest] +apt-dependencies = ["libmariadb-dev"] diff --git a/stubs/mysqlclient/MySQLdb/__init__.pyi b/stubs/mysqlclient/MySQLdb/__init__.pyi new file mode 100644 index 000000000000..740ff8fe5f04 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/__init__.pyi @@ -0,0 +1,95 @@ +from _typeshed import Incomplete + +from MySQLdb import connections as connections, constants as constants, converters as converters, cursors as cursors +from MySQLdb._mysql import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + MySQLError as MySQLError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, + debug as debug, + get_client_info as get_client_info, + string_literal as string_literal, +) +from MySQLdb.connections import Connection as Connection +from MySQLdb.constants import FIELD_TYPE as FIELD_TYPE +from MySQLdb.release import version_info as version_info +from MySQLdb.times import ( + Date as Date, + DateFromTicks as DateFromTicks, + Time as Time, + TimeFromTicks as TimeFromTicks, + Timestamp as Timestamp, + TimestampFromTicks as TimestampFromTicks, +) + +threadsafety: int +apilevel: str +paramstyle: str + +class DBAPISet(frozenset[Incomplete]): + def __eq__(self, other): ... + +STRING: Incomplete +BINARY: Incomplete +NUMBER: Incomplete +DATE: Incomplete +TIME: Incomplete +TIMESTAMP: Incomplete +DATETIME: Incomplete +ROWID: Incomplete + +def Binary(x): ... +def Connect(*args, **kwargs) -> Connection: ... + +connect = Connect + +__all__ = [ + "BINARY", + "Binary", + "Connect", + "Connection", + "DATE", + "Date", + "Time", + "Timestamp", + "DateFromTicks", + "TimeFromTicks", + "TimestampFromTicks", + "DataError", + "DatabaseError", + "Error", + "FIELD_TYPE", + "IntegrityError", + "InterfaceError", + "InternalError", + "MySQLError", + "NUMBER", + "NotSupportedError", + "DBAPISet", + "OperationalError", + "ProgrammingError", + "ROWID", + "STRING", + "TIME", + "TIMESTAMP", + "Warning", + "apilevel", + "connect", + "connections", + "constants", + "converters", + "cursors", + "debug", + "get_client_info", + "paramstyle", + "string_literal", + "threadsafety", + "version_info", +] diff --git a/stubs/mysqlclient/MySQLdb/_exceptions.pyi b/stubs/mysqlclient/MySQLdb/_exceptions.pyi new file mode 100644 index 000000000000..37c3112b9b0c --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/_exceptions.pyi @@ -0,0 +1,13 @@ +import builtins + +class MySQLError(Exception): ... +class Warning(builtins.Warning, MySQLError): ... +class Error(MySQLError): ... +class InterfaceError(Error): ... +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... diff --git a/stubs/mysqlclient/MySQLdb/_mysql.pyi b/stubs/mysqlclient/MySQLdb/_mysql.pyi new file mode 100644 index 000000000000..2ee0b9493565 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/_mysql.pyi @@ -0,0 +1,92 @@ +import builtins +from _typeshed import Incomplete +from typing_extensions import disjoint_base + +import MySQLdb._exceptions + +version_info: tuple[Incomplete, ...] + +class DataError(MySQLdb._exceptions.DatabaseError): ... +class DatabaseError(MySQLdb._exceptions.Error): ... +class Error(MySQLdb._exceptions.MySQLError): ... +class IntegrityError(MySQLdb._exceptions.DatabaseError): ... +class InterfaceError(MySQLdb._exceptions.Error): ... +class InternalError(MySQLdb._exceptions.DatabaseError): ... +class MySQLError(Exception): ... +class NotSupportedError(MySQLdb._exceptions.DatabaseError): ... +class OperationalError(MySQLdb._exceptions.DatabaseError): ... +class ProgrammingError(MySQLdb._exceptions.DatabaseError): ... +class Warning(builtins.Warning, MySQLdb._exceptions.MySQLError): ... + +@disjoint_base +class connection: + client_flag: Incomplete + converter: Incomplete + open: Incomplete + port: Incomplete + server_capabilities: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def _get_native_connection(self): ... + def affected_rows(self): ... + def autocommit(self, on): ... + def change_user(self, *args, **kwargs): ... + def character_set_name(self): ... + def close(self): ... + def commit(self): ... + def dump_debug_info(self): ... + def errno(self): ... + def error(self): ... + def escape(self, obj, dict): ... + def escape_string(self, s): ... + def field_count(self): ... + def fileno(self): ... + def get_autocommit(self): ... + def get_character_set_info(self): ... + def get_host_info(self): ... + def get_proto_info(self): ... + def get_server_info(self): ... + def info(self): ... + def insert_id(self): ... + def kill(self, *args, **kwargs): ... + def next_result(self): ... + def ping(self): ... + def query(self, query): ... + def read_query_result(self): ... + def rollback(self): ... + def select_db(self, *args, **kwargs): ... + def send_query(self, *args, **kwargs): ... + def set_character_set(self, charset: str) -> None: ... + def set_server_option(self, option): ... + def shutdown(self): ... + def sqlstate(self): ... + def stat(self): ... + def store_result(self): ... + def string_literal(self, obj, /) -> str: ... + def thread_id(self): ... + def use_result(self): ... + def discard_result(self) -> None: ... + def warning_count(self): ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value, /) -> None: ... + +@disjoint_base +class result: + converter: Incomplete + has_next: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def data_seek(self, n): ... + def describe(self): ... + def fetch_row(self, *args, **kwargs): ... + def discard(self) -> None: ... + def field_flags(self): ... + def num_fields(self): ... + def num_rows(self): ... + def __delattr__(self, name: str, /) -> None: ... + def __setattr__(self, name: str, value, /) -> None: ... + +def connect(*args, **kwargs): ... +def debug(*args, **kwargs): ... +def escape(obj, dict): ... +def escape_string(s): ... +def get_client_info(): ... +def string_literal(obj, /) -> str: ... diff --git a/stubs/mysqlclient/MySQLdb/connections.pyi b/stubs/mysqlclient/MySQLdb/connections.pyi new file mode 100644 index 000000000000..c35ccd31689e --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/connections.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from re import Pattern +from types import TracebackType +from typing import Any, TypeAlias +from typing_extensions import LiteralString, Self + +from . import _mysql, cursors +from ._exceptions import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, +) + +# Any kind of object that can be passed to Connection.literal(). +# The allowed types depend on the defined encoders, but the following +# types are always allowed. +_Literal: TypeAlias = str | bytearray | bytes | tuple[_Literal, ...] | list[_Literal] | Any + +re_numeric_part: Pattern[str] + +def numeric_part(s): ... + +class Connection(_mysql.connection): + default_cursor: type[cursors.Cursor] + cursorclass: type[cursors.BaseCursor] + encoders: Incomplete + encoding: str + messages: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def autocommit(self, on: bool) -> None: ... + def cursor(self, cursorclass: type[cursors.BaseCursor] | None = None): ... + def query(self, query) -> None: ... + def literal(self, o: _Literal) -> bytes: ... + def begin(self) -> None: ... + def warning_count(self): ... + def set_character_set(self, charset: LiteralString, collation: LiteralString | None = None) -> None: ... + def set_sql_mode(self, sql_mode) -> None: ... + def show_warnings(self): ... + Warning: type[BaseException] + Error: type[BaseException] + InterfaceError: type[BaseException] + DatabaseError: type[BaseException] + DataError: type[BaseException] + OperationalError: type[BaseException] + IntegrityError: type[BaseException] + InternalError: type[BaseException] + ProgrammingError: type[BaseException] + NotSupportedError: type[BaseException] diff --git a/stubs/mysqlclient/MySQLdb/constants/CLIENT.pyi b/stubs/mysqlclient/MySQLdb/constants/CLIENT.pyi new file mode 100644 index 000000000000..66cb63023b8c --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/CLIENT.pyi @@ -0,0 +1,18 @@ +LONG_PASSWORD: int +FOUND_ROWS: int +LONG_FLAG: int +CONNECT_WITH_DB: int +NO_SCHEMA: int +COMPRESS: int +ODBC: int +LOCAL_FILES: int +IGNORE_SPACE: int +CHANGE_USER: int +INTERACTIVE: int +SSL: int +IGNORE_SIGPIPE: int +TRANSACTIONS: int +RESERVED: int +SECURE_CONNECTION: int +MULTI_STATEMENTS: int +MULTI_RESULTS: int diff --git a/stubs/mysqlclient/MySQLdb/constants/CR.pyi b/stubs/mysqlclient/MySQLdb/constants/CR.pyi new file mode 100644 index 000000000000..192117a07d6a --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/CR.pyi @@ -0,0 +1,69 @@ +ERROR_FIRST: int +MIN_ERROR: int +UNKNOWN_ERROR: int +SOCKET_CREATE_ERROR: int +CONNECTION_ERROR: int +CONN_HOST_ERROR: int +IPSOCK_ERROR: int +UNKNOWN_HOST: int +SERVER_GONE_ERROR: int +VERSION_ERROR: int +OUT_OF_MEMORY: int +WRONG_HOST_INFO: int +LOCALHOST_CONNECTION: int +TCP_CONNECTION: int +SERVER_HANDSHAKE_ERR: int +SERVER_LOST: int +COMMANDS_OUT_OF_SYNC: int +NAMEDPIPE_CONNECTION: int +NAMEDPIPEWAIT_ERROR: int +NAMEDPIPEOPEN_ERROR: int +NAMEDPIPESETSTATE_ERROR: int +CANT_READ_CHARSET: int +NET_PACKET_TOO_LARGE: int +EMBEDDED_CONNECTION: int +PROBE_SLAVE_STATUS: int +PROBE_SLAVE_HOSTS: int +PROBE_SLAVE_CONNECT: int +PROBE_MASTER_CONNECT: int +SSL_CONNECTION_ERROR: int +MALFORMED_PACKET: int +WRONG_LICENSE: int +NULL_POINTER: int +NO_PREPARE_STMT: int +PARAMS_NOT_BOUND: int +DATA_TRUNCATED: int +NO_PARAMETERS_EXISTS: int +INVALID_PARAMETER_NO: int +INVALID_BUFFER_USE: int +UNSUPPORTED_PARAM_TYPE: int +SHARED_MEMORY_CONNECTION: int +SHARED_MEMORY_CONNECT_REQUEST_ERROR: int +SHARED_MEMORY_CONNECT_ANSWER_ERROR: int +SHARED_MEMORY_CONNECT_FILE_MAP_ERROR: int +SHARED_MEMORY_CONNECT_MAP_ERROR: int +SHARED_MEMORY_FILE_MAP_ERROR: int +SHARED_MEMORY_MAP_ERROR: int +SHARED_MEMORY_EVENT_ERROR: int +SHARED_MEMORY_CONNECT_ABANDONED_ERROR: int +SHARED_MEMORY_CONNECT_SET_ERROR: int +CONN_UNKNOW_PROTOCOL: int +INVALID_CONN_HANDLE: int +UNUSED_1: int +FETCH_CANCELED: int +NO_DATA: int +NO_STMT_METADATA: int +NO_RESULT_SET: int +NOT_IMPLEMENTED: int +SERVER_LOST_EXTENDED: int +STMT_CLOSED: int +NEW_STMT_METADATA: int +ALREADY_CONNECTED: int +AUTH_PLUGIN_CANNOT_LOAD: int +DUPLICATE_CONNECTION_ATTR: int +AUTH_PLUGIN_ERR: int +INSECURE_API_ERR: int +FILE_NAME_TOO_LONG: int +SSL_FIPS_MODE_ERR: int +MAX_ERROR: int +ERROR_LAST: int diff --git a/stubs/mysqlclient/MySQLdb/constants/ER.pyi b/stubs/mysqlclient/MySQLdb/constants/ER.pyi new file mode 100644 index 000000000000..207a097a4e56 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/ER.pyi @@ -0,0 +1,790 @@ +ERROR_FIRST: int +NO: int +YES: int +CANT_CREATE_FILE: int +CANT_CREATE_TABLE: int +CANT_CREATE_DB: int +DB_CREATE_EXISTS: int +DB_DROP_EXISTS: int +DB_DROP_RMDIR: int +CANT_FIND_SYSTEM_REC: int +CANT_GET_STAT: int +CANT_LOCK: int +CANT_OPEN_FILE: int +FILE_NOT_FOUND: int +CANT_READ_DIR: int +CHECKREAD: int +DUP_KEY: int +ERROR_ON_READ: int +ERROR_ON_RENAME: int +ERROR_ON_WRITE: int +FILE_USED: int +FILSORT_ABORT: int +GET_ERRNO: int +ILLEGAL_HA: int +KEY_NOT_FOUND: int +NOT_FORM_FILE: int +NOT_KEYFILE: int +OLD_KEYFILE: int +OPEN_AS_READONLY: int +OUTOFMEMORY: int +OUT_OF_SORTMEMORY: int +CON_COUNT_ERROR: int +OUT_OF_RESOURCES: int +BAD_HOST_ERROR: int +HANDSHAKE_ERROR: int +DBACCESS_DENIED_ERROR: int +ACCESS_DENIED_ERROR: int +NO_DB_ERROR: int +UNKNOWN_COM_ERROR: int +BAD_NULL_ERROR: int +BAD_DB_ERROR: int +TABLE_EXISTS_ERROR: int +BAD_TABLE_ERROR: int +NON_UNIQ_ERROR: int +SERVER_SHUTDOWN: int +BAD_FIELD_ERROR: int +WRONG_FIELD_WITH_GROUP: int +WRONG_GROUP_FIELD: int +WRONG_SUM_SELECT: int +WRONG_VALUE_COUNT: int +TOO_LONG_IDENT: int +DUP_FIELDNAME: int +DUP_KEYNAME: int +DUP_ENTRY: int +WRONG_FIELD_SPEC: int +PARSE_ERROR: int +EMPTY_QUERY: int +NONUNIQ_TABLE: int +INVALID_DEFAULT: int +MULTIPLE_PRI_KEY: int +TOO_MANY_KEYS: int +TOO_MANY_KEY_PARTS: int +TOO_LONG_KEY: int +KEY_COLUMN_DOES_NOT_EXITS: int +BLOB_USED_AS_KEY: int +TOO_BIG_FIELDLENGTH: int +WRONG_AUTO_KEY: int +READY: int +SHUTDOWN_COMPLETE: int +FORCING_CLOSE: int +IPSOCK_ERROR: int +NO_SUCH_INDEX: int +WRONG_FIELD_TERMINATORS: int +BLOBS_AND_NO_TERMINATED: int +TEXTFILE_NOT_READABLE: int +FILE_EXISTS_ERROR: int +LOAD_INFO: int +ALTER_INFO: int +WRONG_SUB_KEY: int +CANT_REMOVE_ALL_FIELDS: int +CANT_DROP_FIELD_OR_KEY: int +INSERT_INFO: int +UPDATE_TABLE_USED: int +NO_SUCH_THREAD: int +KILL_DENIED_ERROR: int +NO_TABLES_USED: int +TOO_BIG_SET: int +NO_UNIQUE_LOGFILE: int +TABLE_NOT_LOCKED_FOR_WRITE: int +TABLE_NOT_LOCKED: int +BLOB_CANT_HAVE_DEFAULT: int +WRONG_DB_NAME: int +WRONG_TABLE_NAME: int +TOO_BIG_SELECT: int +UNKNOWN_ERROR: int +UNKNOWN_PROCEDURE: int +WRONG_PARAMCOUNT_TO_PROCEDURE: int +WRONG_PARAMETERS_TO_PROCEDURE: int +UNKNOWN_TABLE: int +FIELD_SPECIFIED_TWICE: int +INVALID_GROUP_FUNC_USE: int +UNSUPPORTED_EXTENSION: int +TABLE_MUST_HAVE_COLUMNS: int +RECORD_FILE_FULL: int +UNKNOWN_CHARACTER_SET: int +TOO_MANY_TABLES: int +TOO_MANY_FIELDS: int +TOO_BIG_ROWSIZE: int +STACK_OVERRUN: int +WRONG_OUTER_JOIN_UNUSED: int +NULL_COLUMN_IN_INDEX: int +CANT_FIND_UDF: int +CANT_INITIALIZE_UDF: int +UDF_NO_PATHS: int +UDF_EXISTS: int +CANT_OPEN_LIBRARY: int +CANT_FIND_DL_ENTRY: int +FUNCTION_NOT_DEFINED: int +HOST_IS_BLOCKED: int +HOST_NOT_PRIVILEGED: int +PASSWORD_ANONYMOUS_USER: int +PASSWORD_NOT_ALLOWED: int +PASSWORD_NO_MATCH: int +UPDATE_INFO: int +CANT_CREATE_THREAD: int +WRONG_VALUE_COUNT_ON_ROW: int +CANT_REOPEN_TABLE: int +INVALID_USE_OF_NULL: int +REGEXP_ERROR: int +MIX_OF_GROUP_FUNC_AND_FIELDS: int +NONEXISTING_GRANT: int +TABLEACCESS_DENIED_ERROR: int +COLUMNACCESS_DENIED_ERROR: int +ILLEGAL_GRANT_FOR_TABLE: int +GRANT_WRONG_HOST_OR_USER: int +NO_SUCH_TABLE: int +NONEXISTING_TABLE_GRANT: int +NOT_ALLOWED_COMMAND: int +SYNTAX_ERROR: int +ABORTING_CONNECTION: int +NET_PACKET_TOO_LARGE: int +NET_READ_ERROR_FROM_PIPE: int +NET_FCNTL_ERROR: int +NET_PACKETS_OUT_OF_ORDER: int +NET_UNCOMPRESS_ERROR: int +NET_READ_ERROR: int +NET_READ_INTERRUPTED: int +NET_ERROR_ON_WRITE: int +NET_WRITE_INTERRUPTED: int +TOO_LONG_STRING: int +TABLE_CANT_HANDLE_BLOB: int +TABLE_CANT_HANDLE_AUTO_INCREMENT: int +WRONG_COLUMN_NAME: int +WRONG_KEY_COLUMN: int +WRONG_MRG_TABLE: int +DUP_UNIQUE: int +BLOB_KEY_WITHOUT_LENGTH: int +PRIMARY_CANT_HAVE_NULL: int +TOO_MANY_ROWS: int +REQUIRES_PRIMARY_KEY: int +UPDATE_WITHOUT_KEY_IN_SAFE_MODE: int +KEY_DOES_NOT_EXITS: int +CHECK_NO_SUCH_TABLE: int +CHECK_NOT_IMPLEMENTED: int +CANT_DO_THIS_DURING_AN_TRANSACTION: int +ERROR_DURING_COMMIT: int +ERROR_DURING_ROLLBACK: int +ERROR_DURING_FLUSH_LOGS: int +NEW_ABORTING_CONNECTION: int +MASTER: int +MASTER_NET_READ: int +MASTER_NET_WRITE: int +FT_MATCHING_KEY_NOT_FOUND: int +LOCK_OR_ACTIVE_TRANSACTION: int +UNKNOWN_SYSTEM_VARIABLE: int +CRASHED_ON_USAGE: int +CRASHED_ON_REPAIR: int +WARNING_NOT_COMPLETE_ROLLBACK: int +TRANS_CACHE_FULL: int +SLAVE_NOT_RUNNING: int +BAD_SLAVE: int +MASTER_INFO: int +SLAVE_THREAD: int +TOO_MANY_USER_CONNECTIONS: int +SET_CONSTANTS_ONLY: int +LOCK_WAIT_TIMEOUT: int +LOCK_TABLE_FULL: int +READ_ONLY_TRANSACTION: int +WRONG_ARGUMENTS: int +NO_PERMISSION_TO_CREATE_USER: int +LOCK_DEADLOCK: int +TABLE_CANT_HANDLE_FT: int +CANNOT_ADD_FOREIGN: int +NO_REFERENCED_ROW: int +ROW_IS_REFERENCED: int +CONNECT_TO_MASTER: int +ERROR_WHEN_EXECUTING_COMMAND: int +WRONG_USAGE: int +WRONG_NUMBER_OF_COLUMNS_IN_SELECT: int +CANT_UPDATE_WITH_READLOCK: int +MIXING_NOT_ALLOWED: int +DUP_ARGUMENT: int +USER_LIMIT_REACHED: int +SPECIFIC_ACCESS_DENIED_ERROR: int +LOCAL_VARIABLE: int +GLOBAL_VARIABLE: int +NO_DEFAULT: int +WRONG_VALUE_FOR_VAR: int +WRONG_TYPE_FOR_VAR: int +VAR_CANT_BE_READ: int +CANT_USE_OPTION_HERE: int +NOT_SUPPORTED_YET: int +MASTER_FATAL_ERROR_READING_BINLOG: int +SLAVE_IGNORED_TABLE: int +INCORRECT_GLOBAL_LOCAL_VAR: int +WRONG_FK_DEF: int +KEY_REF_DO_NOT_MATCH_TABLE_REF: int +OPERAND_COLUMNS: int +SUBQUERY_NO_1_ROW: int +UNKNOWN_STMT_HANDLER: int +CORRUPT_HELP_DB: int +AUTO_CONVERT: int +ILLEGAL_REFERENCE: int +DERIVED_MUST_HAVE_ALIAS: int +SELECT_REDUCED: int +TABLENAME_NOT_ALLOWED_HERE: int +NOT_SUPPORTED_AUTH_MODE: int +SPATIAL_CANT_HAVE_NULL: int +COLLATION_CHARSET_MISMATCH: int +TOO_BIG_FOR_UNCOMPRESS: int +ZLIB_Z_MEM_ERROR: int +ZLIB_Z_BUF_ERROR: int +ZLIB_Z_DATA_ERROR: int +CUT_VALUE_GROUP_CONCAT: int +WARN_TOO_FEW_RECORDS: int +WARN_TOO_MANY_RECORDS: int +WARN_NULL_TO_NOTNULL: int +WARN_DATA_OUT_OF_RANGE: int +WARN_DATA_TRUNCATED: int +WARN_USING_OTHER_HANDLER: int +CANT_AGGREGATE_2COLLATIONS: int +REVOKE_GRANTS: int +CANT_AGGREGATE_3COLLATIONS: int +CANT_AGGREGATE_NCOLLATIONS: int +VARIABLE_IS_NOT_STRUCT: int +UNKNOWN_COLLATION: int +SLAVE_IGNORED_SSL_PARAMS: int +SERVER_IS_IN_SECURE_AUTH_MODE: int +WARN_FIELD_RESOLVED: int +BAD_SLAVE_UNTIL_COND: int +MISSING_SKIP_SLAVE: int +UNTIL_COND_IGNORED: int +WRONG_NAME_FOR_INDEX: int +WRONG_NAME_FOR_CATALOG: int +BAD_FT_COLUMN: int +UNKNOWN_KEY_CACHE: int +WARN_HOSTNAME_WONT_WORK: int +UNKNOWN_STORAGE_ENGINE: int +WARN_DEPRECATED_SYNTAX: int +NON_UPDATABLE_TABLE: int +FEATURE_DISABLED: int +OPTION_PREVENTS_STATEMENT: int +DUPLICATED_VALUE_IN_TYPE: int +TRUNCATED_WRONG_VALUE: int +INVALID_ON_UPDATE: int +UNSUPPORTED_PS: int +GET_ERRMSG: int +GET_TEMPORARY_ERRMSG: int +UNKNOWN_TIME_ZONE: int +WARN_INVALID_TIMESTAMP: int +INVALID_CHARACTER_STRING: int +WARN_ALLOWED_PACKET_OVERFLOWED: int +CONFLICTING_DECLARATIONS: int +SP_NO_RECURSIVE_CREATE: int +SP_ALREADY_EXISTS: int +SP_DOES_NOT_EXIST: int +SP_DROP_FAILED: int +SP_STORE_FAILED: int +SP_LILABEL_MISMATCH: int +SP_LABEL_REDEFINE: int +SP_LABEL_MISMATCH: int +SP_UNINIT_VAR: int +SP_BADSELECT: int +SP_BADRETURN: int +SP_BADSTATEMENT: int +UPDATE_LOG_DEPRECATED_IGNORED: int +UPDATE_LOG_DEPRECATED_TRANSLATED: int +QUERY_INTERRUPTED: int +SP_WRONG_NO_OF_ARGS: int +SP_COND_MISMATCH: int +SP_NORETURN: int +SP_NORETURNEND: int +SP_BAD_CURSOR_QUERY: int +SP_BAD_CURSOR_SELECT: int +SP_CURSOR_MISMATCH: int +SP_CURSOR_ALREADY_OPEN: int +SP_CURSOR_NOT_OPEN: int +SP_UNDECLARED_VAR: int +SP_WRONG_NO_OF_FETCH_ARGS: int +SP_FETCH_NO_DATA: int +SP_DUP_PARAM: int +SP_DUP_VAR: int +SP_DUP_COND: int +SP_DUP_CURS: int +SP_CANT_ALTER: int +SP_SUBSELECT_NYI: int +STMT_NOT_ALLOWED_IN_SF_OR_TRG: int +SP_VARCOND_AFTER_CURSHNDLR: int +SP_CURSOR_AFTER_HANDLER: int +SP_CASE_NOT_FOUND: int +FPARSER_TOO_BIG_FILE: int +FPARSER_BAD_HEADER: int +FPARSER_EOF_IN_COMMENT: int +FPARSER_ERROR_IN_PARAMETER: int +FPARSER_EOF_IN_UNKNOWN_PARAMETER: int +VIEW_NO_EXPLAIN: int +WRONG_OBJECT: int +NONUPDATEABLE_COLUMN: int +VIEW_SELECT_CLAUSE: int +VIEW_SELECT_VARIABLE: int +VIEW_SELECT_TMPTABLE: int +VIEW_WRONG_LIST: int +WARN_VIEW_MERGE: int +WARN_VIEW_WITHOUT_KEY: int +VIEW_INVALID: int +SP_NO_DROP_SP: int +TRG_ALREADY_EXISTS: int +TRG_DOES_NOT_EXIST: int +TRG_ON_VIEW_OR_TEMP_TABLE: int +TRG_CANT_CHANGE_ROW: int +TRG_NO_SUCH_ROW_IN_TRG: int +NO_DEFAULT_FOR_FIELD: int +DIVISION_BY_ZERO: int +TRUNCATED_WRONG_VALUE_FOR_FIELD: int +ILLEGAL_VALUE_FOR_TYPE: int +VIEW_NONUPD_CHECK: int +VIEW_CHECK_FAILED: int +PROCACCESS_DENIED_ERROR: int +RELAY_LOG_FAIL: int +UNKNOWN_TARGET_BINLOG: int +IO_ERR_LOG_INDEX_READ: int +BINLOG_PURGE_PROHIBITED: int +FSEEK_FAIL: int +BINLOG_PURGE_FATAL_ERR: int +LOG_IN_USE: int +LOG_PURGE_UNKNOWN_ERR: int +RELAY_LOG_INIT: int +NO_BINARY_LOGGING: int +RESERVED_SYNTAX: int +PS_MANY_PARAM: int +KEY_PART_0: int +VIEW_CHECKSUM: int +VIEW_MULTIUPDATE: int +VIEW_NO_INSERT_FIELD_LIST: int +VIEW_DELETE_MERGE_VIEW: int +CANNOT_USER: int +XAER_NOTA: int +XAER_INVAL: int +XAER_RMFAIL: int +XAER_OUTSIDE: int +XAER_RMERR: int +XA_RBROLLBACK: int +NONEXISTING_PROC_GRANT: int +PROC_AUTO_GRANT_FAIL: int +PROC_AUTO_REVOKE_FAIL: int +DATA_TOO_LONG: int +SP_BAD_SQLSTATE: int +STARTUP: int +LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR: int +CANT_CREATE_USER_WITH_GRANT: int +WRONG_VALUE_FOR_TYPE: int +TABLE_DEF_CHANGED: int +SP_DUP_HANDLER: int +SP_NOT_VAR_ARG: int +SP_NO_RETSET: int +CANT_CREATE_GEOMETRY_OBJECT: int +BINLOG_UNSAFE_ROUTINE: int +BINLOG_CREATE_ROUTINE_NEED_SUPER: int +STMT_HAS_NO_OPEN_CURSOR: int +COMMIT_NOT_ALLOWED_IN_SF_OR_TRG: int +NO_DEFAULT_FOR_VIEW_FIELD: int +SP_NO_RECURSION: int +TOO_BIG_SCALE: int +TOO_BIG_PRECISION: int +M_BIGGER_THAN_D: int +WRONG_LOCK_OF_SYSTEM_TABLE: int +CONNECT_TO_FOREIGN_DATA_SOURCE: int +QUERY_ON_FOREIGN_DATA_SOURCE: int +FOREIGN_DATA_SOURCE_DOESNT_EXIST: int +FOREIGN_DATA_STRING_INVALID_CANT_CREATE: int +FOREIGN_DATA_STRING_INVALID: int +TRG_IN_WRONG_SCHEMA: int +STACK_OVERRUN_NEED_MORE: int +TOO_LONG_BODY: int +WARN_CANT_DROP_DEFAULT_KEYCACHE: int +TOO_BIG_DISPLAYWIDTH: int +XAER_DUPID: int +DATETIME_FUNCTION_OVERFLOW: int +CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG: int +VIEW_PREVENT_UPDATE: int +PS_NO_RECURSION: int +SP_CANT_SET_AUTOCOMMIT: int +VIEW_FRM_NO_USER: int +VIEW_OTHER_USER: int +NO_SUCH_USER: int +FORBID_SCHEMA_CHANGE: int +ROW_IS_REFERENCED_2: int +NO_REFERENCED_ROW_2: int +SP_BAD_VAR_SHADOW: int +TRG_NO_DEFINER: int +OLD_FILE_FORMAT: int +SP_RECURSION_LIMIT: int +SP_WRONG_NAME: int +TABLE_NEEDS_UPGRADE: int +SP_NO_AGGREGATE: int +MAX_PREPARED_STMT_COUNT_REACHED: int +VIEW_RECURSIVE: int +NON_GROUPING_FIELD_USED: int +TABLE_CANT_HANDLE_SPKEYS: int +NO_TRIGGERS_ON_SYSTEM_SCHEMA: int +REMOVED_SPACES: int +AUTOINC_READ_FAILED: int +USERNAME: int +HOSTNAME: int +WRONG_STRING_LENGTH: int +NON_INSERTABLE_TABLE: int +ADMIN_WRONG_MRG_TABLE: int +TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT: int +NAME_BECOMES_EMPTY: int +AMBIGUOUS_FIELD_TERM: int +FOREIGN_SERVER_EXISTS: int +FOREIGN_SERVER_DOESNT_EXIST: int +ILLEGAL_HA_CREATE_OPTION: int +PARTITION_REQUIRES_VALUES_ERROR: int +PARTITION_WRONG_VALUES_ERROR: int +PARTITION_MAXVALUE_ERROR: int +PARTITION_WRONG_NO_PART_ERROR: int +PARTITION_WRONG_NO_SUBPART_ERROR: int +WRONG_EXPR_IN_PARTITION_FUNC_ERROR: int +FIELD_NOT_FOUND_PART_ERROR: int +INCONSISTENT_PARTITION_INFO_ERROR: int +PARTITION_FUNC_NOT_ALLOWED_ERROR: int +PARTITIONS_MUST_BE_DEFINED_ERROR: int +RANGE_NOT_INCREASING_ERROR: int +INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR: int +MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR: int +PARTITION_ENTRY_ERROR: int +MIX_HANDLER_ERROR: int +PARTITION_NOT_DEFINED_ERROR: int +TOO_MANY_PARTITIONS_ERROR: int +SUBPARTITION_ERROR: int +CANT_CREATE_HANDLER_FILE: int +BLOB_FIELD_IN_PART_FUNC_ERROR: int +UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF: int +NO_PARTS_ERROR: int +PARTITION_MGMT_ON_NONPARTITIONED: int +FOREIGN_KEY_ON_PARTITIONED: int +DROP_PARTITION_NON_EXISTENT: int +DROP_LAST_PARTITION: int +COALESCE_ONLY_ON_HASH_PARTITION: int +REORG_HASH_ONLY_ON_SAME_NO: int +REORG_NO_PARAM_ERROR: int +ONLY_ON_RANGE_LIST_PARTITION: int +ADD_PARTITION_SUBPART_ERROR: int +ADD_PARTITION_NO_NEW_PARTITION: int +COALESCE_PARTITION_NO_PARTITION: int +REORG_PARTITION_NOT_EXIST: int +SAME_NAME_PARTITION: int +NO_BINLOG_ERROR: int +CONSECUTIVE_REORG_PARTITIONS: int +REORG_OUTSIDE_RANGE: int +PARTITION_FUNCTION_FAILURE: int +LIMITED_PART_RANGE: int +PLUGIN_IS_NOT_LOADED: int +WRONG_VALUE: int +NO_PARTITION_FOR_GIVEN_VALUE: int +FILEGROUP_OPTION_ONLY_ONCE: int +CREATE_FILEGROUP_FAILED: int +DROP_FILEGROUP_FAILED: int +TABLESPACE_AUTO_EXTEND_ERROR: int +WRONG_SIZE_NUMBER: int +SIZE_OVERFLOW_ERROR: int +ALTER_FILEGROUP_FAILED: int +BINLOG_ROW_LOGGING_FAILED: int +EVENT_ALREADY_EXISTS: int +EVENT_DOES_NOT_EXIST: int +EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG: int +EVENT_ENDS_BEFORE_STARTS: int +EVENT_EXEC_TIME_IN_THE_PAST: int +EVENT_SAME_NAME: int +DROP_INDEX_FK: int +WARN_DEPRECATED_SYNTAX_WITH_VER: int +CANT_LOCK_LOG_TABLE: int +FOREIGN_DUPLICATE_KEY_OLD_UNUSED: int +COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE: int +TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR: int +STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT: int +PARTITION_NO_TEMPORARY: int +PARTITION_CONST_DOMAIN_ERROR: int +PARTITION_FUNCTION_IS_NOT_ALLOWED: int +NULL_IN_VALUES_LESS_THAN: int +WRONG_PARTITION_NAME: int +CANT_CHANGE_TX_CHARACTERISTICS: int +DUP_ENTRY_AUTOINCREMENT_CASE: int +EVENT_SET_VAR_ERROR: int +PARTITION_MERGE_ERROR: int +BASE64_DECODE_ERROR: int +EVENT_RECURSION_FORBIDDEN: int +ONLY_INTEGERS_ALLOWED: int +UNSUPORTED_LOG_ENGINE: int +BAD_LOG_STATEMENT: int +CANT_RENAME_LOG_TABLE: int +WRONG_PARAMCOUNT_TO_NATIVE_FCT: int +WRONG_PARAMETERS_TO_NATIVE_FCT: int +WRONG_PARAMETERS_TO_STORED_FCT: int +NATIVE_FCT_NAME_COLLISION: int +DUP_ENTRY_WITH_KEY_NAME: int +BINLOG_PURGE_EMFILE: int +EVENT_CANNOT_CREATE_IN_THE_PAST: int +EVENT_CANNOT_ALTER_IN_THE_PAST: int +NO_PARTITION_FOR_GIVEN_VALUE_SILENT: int +BINLOG_UNSAFE_STATEMENT: int +BINLOG_FATAL_ERROR: int +BINLOG_LOGGING_IMPOSSIBLE: int +VIEW_NO_CREATION_CTX: int +VIEW_INVALID_CREATION_CTX: int +TRG_CORRUPTED_FILE: int +TRG_NO_CREATION_CTX: int +TRG_INVALID_CREATION_CTX: int +EVENT_INVALID_CREATION_CTX: int +TRG_CANT_OPEN_TABLE: int +NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT: int +SLAVE_CORRUPT_EVENT: int +LOG_PURGE_NO_FILE: int +XA_RBTIMEOUT: int +XA_RBDEADLOCK: int +NEED_REPREPARE: int +WARN_NO_MASTER_INFO: int +WARN_OPTION_IGNORED: int +PLUGIN_DELETE_BUILTIN: int +WARN_PLUGIN_BUSY: int +VARIABLE_IS_READONLY: int +WARN_ENGINE_TRANSACTION_ROLLBACK: int +SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE: int +NDB_REPLICATION_SCHEMA_ERROR: int +CONFLICT_FN_PARSE_ERROR: int +EXCEPTIONS_WRITE_ERROR: int +TOO_LONG_TABLE_COMMENT: int +TOO_LONG_FIELD_COMMENT: int +FUNC_INEXISTENT_NAME_COLLISION: int +DATABASE_NAME: int +TABLE_NAME: int +PARTITION_NAME: int +SUBPARTITION_NAME: int +TEMPORARY_NAME: int +RENAMED_NAME: int +TOO_MANY_CONCURRENT_TRXS: int +WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED: int +DEBUG_SYNC_TIMEOUT: int +DEBUG_SYNC_HIT_LIMIT: int +DUP_SIGNAL_SET: int +SIGNAL_WARN: int +SIGNAL_NOT_FOUND: int +SIGNAL_EXCEPTION: int +RESIGNAL_WITHOUT_ACTIVE_HANDLER: int +SIGNAL_BAD_CONDITION_TYPE: int +WARN_COND_ITEM_TRUNCATED: int +COND_ITEM_TOO_LONG: int +UNKNOWN_LOCALE: int +SLAVE_IGNORE_SERVER_IDS: int +SAME_NAME_PARTITION_FIELD: int +PARTITION_COLUMN_LIST_ERROR: int +WRONG_TYPE_COLUMN_VALUE_ERROR: int +TOO_MANY_PARTITION_FUNC_FIELDS_ERROR: int +MAXVALUE_IN_VALUES_IN: int +TOO_MANY_VALUES_ERROR: int +ROW_SINGLE_PARTITION_FIELD_ERROR: int +FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD: int +PARTITION_FIELDS_TOO_LONG: int +BINLOG_ROW_ENGINE_AND_STMT_ENGINE: int +BINLOG_ROW_MODE_AND_STMT_ENGINE: int +BINLOG_UNSAFE_AND_STMT_ENGINE: int +BINLOG_ROW_INJECTION_AND_STMT_ENGINE: int +BINLOG_STMT_MODE_AND_ROW_ENGINE: int +BINLOG_ROW_INJECTION_AND_STMT_MODE: int +BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE: int +BINLOG_UNSAFE_LIMIT: int +BINLOG_UNSAFE_SYSTEM_TABLE: int +BINLOG_UNSAFE_AUTOINC_COLUMNS: int +BINLOG_UNSAFE_UDF: int +BINLOG_UNSAFE_SYSTEM_VARIABLE: int +BINLOG_UNSAFE_SYSTEM_FUNCTION: int +BINLOG_UNSAFE_NONTRANS_AFTER_TRANS: int +MESSAGE_AND_STATEMENT: int +SLAVE_CANT_CREATE_CONVERSION: int +INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT: int +PATH_LENGTH: int +WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT: int +WRONG_NATIVE_TABLE_STRUCTURE: int +WRONG_PERFSCHEMA_USAGE: int +WARN_I_S_SKIPPED_TABLE: int +INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT: int +STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT: int +SPATIAL_MUST_HAVE_GEOM_COL: int +TOO_LONG_INDEX_COMMENT: int +LOCK_ABORTED: int +DATA_OUT_OF_RANGE: int +WRONG_SPVAR_TYPE_IN_LIMIT: int +BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE: int +BINLOG_UNSAFE_MIXED_STATEMENT: int +INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN: int +STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN: int +FAILED_READ_FROM_PAR_FILE: int +VALUES_IS_NOT_INT_TYPE_ERROR: int +ACCESS_DENIED_NO_PASSWORD_ERROR: int +SET_PASSWORD_AUTH_PLUGIN: int +TRUNCATE_ILLEGAL_FK: int +PLUGIN_IS_PERMANENT: int +SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN: int +SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX: int +STMT_CACHE_FULL: int +MULTI_UPDATE_KEY_CONFLICT: int +TABLE_NEEDS_REBUILD: int +WARN_OPTION_BELOW_LIMIT: int +INDEX_COLUMN_TOO_LONG: int +ERROR_IN_TRIGGER_BODY: int +ERROR_IN_UNKNOWN_TRIGGER_BODY: int +INDEX_CORRUPT: int +UNDO_RECORD_TOO_BIG: int +BINLOG_UNSAFE_INSERT_IGNORE_SELECT: int +BINLOG_UNSAFE_INSERT_SELECT_UPDATE: int +BINLOG_UNSAFE_REPLACE_SELECT: int +BINLOG_UNSAFE_CREATE_IGNORE_SELECT: int +BINLOG_UNSAFE_CREATE_REPLACE_SELECT: int +BINLOG_UNSAFE_UPDATE_IGNORE: int +PLUGIN_NO_UNINSTALL: int +PLUGIN_NO_INSTALL: int +BINLOG_UNSAFE_WRITE_AUTOINC_SELECT: int +BINLOG_UNSAFE_CREATE_SELECT_AUTOINC: int +BINLOG_UNSAFE_INSERT_TWO_KEYS: int +TABLE_IN_FK_CHECK: int +UNSUPPORTED_ENGINE: int +BINLOG_UNSAFE_AUTOINC_NOT_FIRST: int +CANNOT_LOAD_FROM_TABLE_V2: int +MASTER_DELAY_VALUE_OUT_OF_RANGE: int +ONLY_FD_AND_RBR_EVENTS_ALLOWED_IN_BINLOG_STATEMENT: int +PARTITION_EXCHANGE_DIFFERENT_OPTION: int +PARTITION_EXCHANGE_PART_TABLE: int +PARTITION_EXCHANGE_TEMP_TABLE: int +PARTITION_INSTEAD_OF_SUBPARTITION: int +UNKNOWN_PARTITION: int +TABLES_DIFFERENT_METADATA: int +ROW_DOES_NOT_MATCH_PARTITION: int +BINLOG_CACHE_SIZE_GREATER_THAN_MAX: int +WARN_INDEX_NOT_APPLICABLE: int +PARTITION_EXCHANGE_FOREIGN_KEY: int +RPL_INFO_DATA_TOO_LONG: int +BINLOG_STMT_CACHE_SIZE_GREATER_THAN_MAX: int +CANT_UPDATE_TABLE_IN_CREATE_TABLE_SELECT: int +PARTITION_CLAUSE_ON_NONPARTITIONED: int +ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET: int +CHANGE_RPL_INFO_REPOSITORY_FAILURE: int +WARNING_NOT_COMPLETE_ROLLBACK_WITH_CREATED_TEMP_TABLE: int +WARNING_NOT_COMPLETE_ROLLBACK_WITH_DROPPED_TEMP_TABLE: int +MTS_FEATURE_IS_NOT_SUPPORTED: int +MTS_UPDATED_DBS_GREATER_MAX: int +MTS_CANT_PARALLEL: int +MTS_INCONSISTENT_DATA: int +FULLTEXT_NOT_SUPPORTED_WITH_PARTITIONING: int +DA_INVALID_CONDITION_NUMBER: int +INSECURE_PLAIN_TEXT: int +INSECURE_CHANGE_MASTER: int +FOREIGN_DUPLICATE_KEY_WITH_CHILD_INFO: int +FOREIGN_DUPLICATE_KEY_WITHOUT_CHILD_INFO: int +SQLTHREAD_WITH_SECURE_SLAVE: int +TABLE_HAS_NO_FT: int +VARIABLE_NOT_SETTABLE_IN_SF_OR_TRIGGER: int +VARIABLE_NOT_SETTABLE_IN_TRANSACTION: int +SET_STATEMENT_CANNOT_INVOKE_FUNCTION: int +GTID_NEXT_CANT_BE_AUTOMATIC_IF_GTID_NEXT_LIST_IS_NON_NULL: int +MALFORMED_GTID_SET_SPECIFICATION: int +MALFORMED_GTID_SET_ENCODING: int +MALFORMED_GTID_SPECIFICATION: int +GNO_EXHAUSTED: int +BAD_SLAVE_AUTO_POSITION: int +AUTO_POSITION_REQUIRES_GTID_MODE_NOT_OFF: int +CANT_DO_IMPLICIT_COMMIT_IN_TRX_WHEN_GTID_NEXT_IS_SET: int +GTID_MODE_ON_REQUIRES_ENFORCE_GTID_CONSISTENCY_ON: int +CANT_SET_GTID_NEXT_TO_GTID_WHEN_GTID_MODE_IS_OFF: int +CANT_SET_GTID_NEXT_TO_ANONYMOUS_WHEN_GTID_MODE_IS_ON: int +CANT_SET_GTID_NEXT_LIST_TO_NON_NULL_WHEN_GTID_MODE_IS_OFF: int +GTID_UNSAFE_NON_TRANSACTIONAL_TABLE: int +GTID_UNSAFE_CREATE_SELECT: int +GTID_UNSAFE_CREATE_DROP_TEMPORARY_TABLE_IN_TRANSACTION: int +GTID_MODE_CAN_ONLY_CHANGE_ONE_STEP_AT_A_TIME: int +MASTER_HAS_PURGED_REQUIRED_GTIDS: int +CANT_SET_GTID_NEXT_WHEN_OWNING_GTID: int +UNKNOWN_EXPLAIN_FORMAT: int +CANT_EXECUTE_IN_READ_ONLY_TRANSACTION: int +TOO_LONG_TABLE_PARTITION_COMMENT: int +SLAVE_CONFIGURATION: int +INNODB_FT_LIMIT: int +INNODB_NO_FT_TEMP_TABLE: int +INNODB_FT_WRONG_DOCID_COLUMN: int +INNODB_FT_WRONG_DOCID_INDEX: int +INNODB_ONLINE_LOG_TOO_BIG: int +UNKNOWN_ALTER_ALGORITHM: int +UNKNOWN_ALTER_LOCK: int +MTS_CHANGE_MASTER_CANT_RUN_WITH_GAPS: int +MTS_RECOVERY_FAILURE: int +MTS_RESET_WORKERS: int +COL_COUNT_DOESNT_MATCH_CORRUPTED_V2: int +SLAVE_SILENT_RETRY_TRANSACTION: int +DISCARD_FK_CHECKS_RUNNING: int +TABLE_SCHEMA_MISMATCH: int +TABLE_IN_SYSTEM_TABLESPACE: int +IO_READ_ERROR: int +IO_WRITE_ERROR: int +TABLESPACE_MISSING: int +TABLESPACE_EXISTS: int +TABLESPACE_DISCARDED: int +INTERNAL_ERROR: int +INNODB_IMPORT_ERROR: int +INNODB_INDEX_CORRUPT: int +INVALID_YEAR_COLUMN_LENGTH: int +NOT_VALID_PASSWORD: int +MUST_CHANGE_PASSWORD: int +FK_NO_INDEX_CHILD: int +FK_NO_INDEX_PARENT: int +FK_FAIL_ADD_SYSTEM: int +FK_CANNOT_OPEN_PARENT: int +FK_INCORRECT_OPTION: int +FK_DUP_NAME: int +PASSWORD_FORMAT: int +FK_COLUMN_CANNOT_DROP: int +FK_COLUMN_CANNOT_DROP_CHILD: int +FK_COLUMN_NOT_NULL: int +DUP_INDEX: int +FK_COLUMN_CANNOT_CHANGE: int +FK_COLUMN_CANNOT_CHANGE_CHILD: int +MALFORMED_PACKET: int +READ_ONLY_MODE: int +GTID_NEXT_TYPE_UNDEFINED_GTID: int +VARIABLE_NOT_SETTABLE_IN_SP: int +CANT_SET_GTID_PURGED_WHEN_GTID_EXECUTED_IS_NOT_EMPTY: int +CANT_SET_GTID_PURGED_WHEN_OWNED_GTIDS_IS_NOT_EMPTY: int +GTID_PURGED_WAS_CHANGED: int +GTID_EXECUTED_WAS_CHANGED: int +BINLOG_STMT_MODE_AND_NO_REPL_TABLES: int +ALTER_OPERATION_NOT_SUPPORTED: int +ALTER_OPERATION_NOT_SUPPORTED_REASON: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_COLUMN_TYPE: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_CHECK: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_NOPK: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_AUTOINC: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_HIDDEN_FTS: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_CHANGE_FTS: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_FTS: int +SQL_SLAVE_SKIP_COUNTER_NOT_SETTABLE_IN_GTID_MODE: int +DUP_UNKNOWN_IN_INDEX: int +IDENT_CAUSES_TOO_LONG_PATH: int +ALTER_OPERATION_NOT_SUPPORTED_REASON_NOT_NULL: int +MUST_CHANGE_PASSWORD_LOGIN: int +ROW_IN_WRONG_PARTITION: int +MTS_EVENT_BIGGER_PENDING_JOBS_SIZE_MAX: int +BINLOG_LOGICAL_CORRUPTION: int +WARN_PURGE_LOG_IN_USE: int +WARN_PURGE_LOG_IS_ACTIVE: int +AUTO_INCREMENT_CONFLICT: int +WARN_ON_BLOCKHOLE_IN_RBR: int +SLAVE_MI_INIT_REPOSITORY: int +SLAVE_RLI_INIT_REPOSITORY: int +ACCESS_DENIED_CHANGE_USER_ERROR: int +INNODB_READ_ONLY: int +STOP_SLAVE_SQL_THREAD_TIMEOUT: int +STOP_SLAVE_IO_THREAD_TIMEOUT: int +TABLE_CORRUPT: int +TEMP_FILE_WRITE_FAILURE: int +INNODB_FT_AUX_NOT_HEX_ID: int +OLD_TEMPORALS_UPGRADED: int +INNODB_FORCED_RECOVERY: int +AES_INVALID_IV: int +PLUGIN_CANNOT_BE_UNINSTALLED: int +GTID_UNSAFE_BINLOG_SPLITTABLE_STATEMENT_AND_ASSIGNED_GTID: int +SLAVE_HAS_MORE_GTIDS_THAN_MASTER: int +MISSING_KEY: int +ERROR_LAST: int diff --git a/stubs/mysqlclient/MySQLdb/constants/FIELD_TYPE.pyi b/stubs/mysqlclient/MySQLdb/constants/FIELD_TYPE.pyi new file mode 100644 index 000000000000..26f6105510dc --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/FIELD_TYPE.pyi @@ -0,0 +1,29 @@ +DECIMAL: int +TINY: int +SHORT: int +LONG: int +FLOAT: int +DOUBLE: int +NULL: int +TIMESTAMP: int +LONGLONG: int +INT24: int +DATE: int +TIME: int +DATETIME: int +YEAR: int +VARCHAR: int +BIT: int +JSON: int +NEWDECIMAL: int +ENUM: int +SET: int +TINY_BLOB: int +MEDIUM_BLOB: int +LONG_BLOB: int +BLOB: int +VAR_STRING: int +STRING: int +GEOMETRY: int +CHAR: int +INTERVAL: int diff --git a/stubs/mysqlclient/MySQLdb/constants/FLAG.pyi b/stubs/mysqlclient/MySQLdb/constants/FLAG.pyi new file mode 100644 index 000000000000..9fe6c7a72591 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/FLAG.pyi @@ -0,0 +1,16 @@ +NOT_NULL: int +PRI_KEY: int +UNIQUE_KEY: int +MULTIPLE_KEY: int +BLOB: int +UNSIGNED: int +ZEROFILL: int +BINARY: int +ENUM: int +AUTO_INCREMENT: int +TIMESTAMP: int +SET: int +NUM: int +PART_KEY: int +GROUP: int +UNIQUE: int diff --git a/stubs/mysqlclient/MySQLdb/constants/__init__.pyi b/stubs/mysqlclient/MySQLdb/constants/__init__.pyi new file mode 100644 index 000000000000..df9363bc4207 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/constants/__init__.pyi @@ -0,0 +1,3 @@ +from . import CLIENT as CLIENT, CR as CR, ER as ER, FIELD_TYPE as FIELD_TYPE, FLAG as FLAG + +__all__ = ["CR", "FIELD_TYPE", "CLIENT", "ER", "FLAG"] diff --git a/stubs/mysqlclient/MySQLdb/converters.pyi b/stubs/mysqlclient/MySQLdb/converters.pyi new file mode 100644 index 000000000000..510e795cf23a --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/converters.pyi @@ -0,0 +1,30 @@ +import array +from _typeshed import Incomplete + +from MySQLdb._exceptions import ProgrammingError as ProgrammingError +from MySQLdb._mysql import string_literal as string_literal +from MySQLdb.constants import FIELD_TYPE as FIELD_TYPE, FLAG as FLAG +from MySQLdb.times import ( + Date as Date, + Date_or_None as Date_or_None, + DateTime2literal as DateTime2literal, + DateTime_or_None as DateTime_or_None, + DateTimeDelta2literal as DateTimeDelta2literal, + DateTimeDeltaType as DateTimeDeltaType, + DateTimeType as DateTimeType, + TimeDelta_or_None as TimeDelta_or_None, +) + +NoneType: Incomplete +ArrayType = array.array + +def Bool2Str(s, d): ... +def Set2Str(s, d): ... +def Thing2Str(s, d): ... +def Float2Str(o, d): ... +def None2NULL(o, d): ... +def Thing2Literal(o, d): ... +def Decimal2Literal(o, d): ... +def array2Str(o, d): ... + +conversions: Incomplete diff --git a/stubs/mysqlclient/MySQLdb/cursors.pyi b/stubs/mysqlclient/MySQLdb/cursors.pyi new file mode 100644 index 000000000000..f0dd10ea95d8 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/cursors.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from re import Pattern +from typing import TypeAlias +from typing_extensions import LiteralString + +from .connections import _Literal + +_Arguments: TypeAlias = dict[str, _Literal] | dict[bytes, _Literal] | Iterable[_Literal] + +RE_INSERT_VALUES: Pattern[str] + +class BaseCursor: + from ._exceptions import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + MySQLError as MySQLError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, + ) + + max_stmt_length: Incomplete + connection: Incomplete + description: Incomplete + description_flags: Incomplete + rowcount: int + arraysize: int + lastrowid: Incomplete + rownumber: Incomplete + def __init__(self, connection) -> None: ... + def close(self) -> None: ... + def __enter__(self): ... + def __exit__(self, *exc_info: object) -> None: ... + def nextset(self): ... + def setinputsizes(self, *args) -> None: ... + def setoutputsizes(self, *args) -> None: ... + def execute(self, query, args=None): ... + def mogrify(self, query: str | bytes, args: _Arguments | None = None) -> str: ... + def executemany(self, query: LiteralString, args: Iterable[_Arguments]) -> int | None: ... + def callproc(self, procname, args=()): ... + def __iter__(self): ... + +class CursorStoreResultMixIn: + rownumber: Incomplete + def fetchone(self): ... + def fetchmany(self, size=None): ... + def fetchall(self): ... + def scroll(self, value, mode: str = "relative") -> None: ... + def __iter__(self): ... + +class CursorUseResultMixIn: + rownumber: Incomplete + def fetchone(self): ... + def fetchmany(self, size=None): ... + def fetchall(self): ... + def __iter__(self): ... + def next(self): ... + __next__ = next + +class CursorTupleRowsMixIn: ... +class CursorDictRowsMixIn: ... +class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn, BaseCursor): ... +class DictCursor(CursorStoreResultMixIn, CursorDictRowsMixIn, BaseCursor): ... +class SSCursor(CursorUseResultMixIn, CursorTupleRowsMixIn, BaseCursor): ... +class SSDictCursor(CursorUseResultMixIn, CursorDictRowsMixIn, BaseCursor): ... diff --git a/stubs/mysqlclient/MySQLdb/release.pyi b/stubs/mysqlclient/MySQLdb/release.pyi new file mode 100644 index 000000000000..a78eb9f6a30d --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/release.pyi @@ -0,0 +1 @@ +version_info: tuple[int, int, int, str, int] diff --git a/stubs/mysqlclient/MySQLdb/times.pyi b/stubs/mysqlclient/MySQLdb/times.pyi new file mode 100644 index 000000000000..21a14cfc8551 --- /dev/null +++ b/stubs/mysqlclient/MySQLdb/times.pyi @@ -0,0 +1,27 @@ +from _typeshed import Unused +from datetime import date, datetime, time, timedelta + +from MySQLdb._mysql import string_literal as string_literal + +Date = date +Time = time +TimeDelta = timedelta +Timestamp = datetime +DateTimeDeltaType = timedelta +DateTimeType = datetime + +def DateFromTicks(ticks: float | None) -> date: ... +def TimeFromTicks(ticks: float | None) -> time: ... +def TimestampFromTicks(ticks: float | None) -> datetime: ... + +format_TIME = str +format_DATE = str + +def format_TIMEDELTA(v: timedelta) -> str: ... +def format_TIMESTAMP(d: datetime) -> str: ... +def DateTime_or_None(s: str) -> datetime | None: ... +def TimeDelta_or_None(s: str) -> timedelta | None: ... +def Time_or_None(s: str) -> time | None: ... +def Date_or_None(s: str) -> date | None: ... +def DateTime2literal(d: datetime, c: Unused) -> str: ... +def DateTimeDelta2literal(d: datetime, c: Unused) -> str: ... diff --git a/stubs/nanoid/METADATA.toml b/stubs/nanoid/METADATA.toml new file mode 100644 index 000000000000..d2d220486c31 --- /dev/null +++ b/stubs/nanoid/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.0.0" +upstream-repository = "https://github.com/puyuan/py-nanoid" diff --git a/stubs/nanoid/nanoid/__init__.pyi b/stubs/nanoid/nanoid/__init__.pyi new file mode 100644 index 000000000000..37e83e31a712 --- /dev/null +++ b/stubs/nanoid/nanoid/__init__.pyi @@ -0,0 +1,4 @@ +from nanoid.generate import generate +from nanoid.non_secure_generate import non_secure_generate + +__all__ = ["generate", "non_secure_generate"] diff --git a/stubs/nanoid/nanoid/algorithm.pyi b/stubs/nanoid/nanoid/algorithm.pyi new file mode 100644 index 000000000000..e5d49982f64c --- /dev/null +++ b/stubs/nanoid/nanoid/algorithm.pyi @@ -0,0 +1 @@ +def algorithm_generate(random_bytes: int) -> bytearray: ... diff --git a/stubs/nanoid/nanoid/generate.pyi b/stubs/nanoid/nanoid/generate.pyi new file mode 100644 index 000000000000..8c3e6771b179 --- /dev/null +++ b/stubs/nanoid/nanoid/generate.pyi @@ -0,0 +1,3 @@ +def generate( + alphabet: str = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", size: int = 21 # noqa: Y053 +) -> str: ... diff --git a/stubs/nanoid/nanoid/method.pyi b/stubs/nanoid/nanoid/method.pyi new file mode 100644 index 000000000000..0e79a8e09215 --- /dev/null +++ b/stubs/nanoid/nanoid/method.pyi @@ -0,0 +1,6 @@ +from collections.abc import Callable, Sequence +from typing import TypeAlias + +_Algorithm: TypeAlias = Callable[[int], Sequence[int]] + +def method(algorithm: _Algorithm, alphabet: str, size: int) -> str: ... diff --git a/stubs/nanoid/nanoid/non_secure_generate.pyi b/stubs/nanoid/nanoid/non_secure_generate.pyi new file mode 100644 index 000000000000..d37459182d95 --- /dev/null +++ b/stubs/nanoid/nanoid/non_secure_generate.pyi @@ -0,0 +1,3 @@ +def non_secure_generate( + alphabet: str = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", size: int = 21 # noqa: Y053 +) -> str: ... diff --git a/stubs/nanoid/nanoid/resources.pyi b/stubs/nanoid/nanoid/resources.pyi new file mode 100644 index 000000000000..a0bd3b8f78ff --- /dev/null +++ b/stubs/nanoid/nanoid/resources.pyi @@ -0,0 +1,2 @@ +alphabet: str +size: int diff --git a/stubs/nanoleafapi/@tests/stubtest_allowlist.txt b/stubs/nanoleafapi/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..dcdd0cfdbb8f --- /dev/null +++ b/stubs/nanoleafapi/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +nanoleafapi.test_nanoleaf diff --git a/stubs/nanoleafapi/METADATA.toml b/stubs/nanoleafapi/METADATA.toml new file mode 100644 index 000000000000..4f4332fcd18c --- /dev/null +++ b/stubs/nanoleafapi/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.1.*" +upstream-repository = "https://github.com/MylesMor/nanoleafapi" diff --git a/stubs/nanoleafapi/nanoleafapi/__init__.pyi b/stubs/nanoleafapi/nanoleafapi/__init__.pyi new file mode 100644 index 000000000000..78cdd18a19f5 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/__init__.pyi @@ -0,0 +1,16 @@ +from nanoleafapi.digital_twin import NanoleafDigitalTwin as NanoleafDigitalTwin +from nanoleafapi.nanoleaf import ( + BLUE as BLUE, + GREEN as GREEN, + LIGHT_BLUE as LIGHT_BLUE, + ORANGE as ORANGE, + PINK as PINK, + PURPLE as PURPLE, + RED as RED, + WHITE as WHITE, + YELLOW as YELLOW, + Nanoleaf as Nanoleaf, + NanoleafConnectionError as NanoleafConnectionError, + NanoleafEffectCreationError as NanoleafEffectCreationError, + NanoleafRegistrationError as NanoleafRegistrationError, +) diff --git a/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi b/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi new file mode 100644 index 000000000000..5da49f6bedef --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/digital_twin.pyi @@ -0,0 +1,12 @@ +from nanoleafapi.nanoleaf import Nanoleaf + +class NanoleafDigitalTwin: + nanoleaf: Nanoleaf + tile_dict: dict[str, dict[str, int]] + def __init__(self, nl: Nanoleaf) -> None: ... + def set_color(self, panel_id: int, rgb: tuple[int, int, int]) -> None: ... + def set_all_colors(self, rgb: tuple[int, int, int]) -> None: ... + def get_ids(self) -> list[int]: ... + def get_color(self, panel_id: int) -> tuple[int, int, int]: ... + def get_all_colors(self) -> dict[int, tuple[int, int, int]]: ... + def sync(self) -> bool: ... diff --git a/stubs/nanoleafapi/nanoleafapi/discovery.pyi b/stubs/nanoleafapi/nanoleafapi/discovery.pyi new file mode 100644 index 000000000000..233eb0cd2553 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/discovery.pyi @@ -0,0 +1 @@ +def discover_devices(timeout: int = 30, debug: bool = False) -> dict[str | None, str]: ... diff --git a/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi b/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi new file mode 100644 index 000000000000..d83625ad5285 --- /dev/null +++ b/stubs/nanoleafapi/nanoleafapi/nanoleaf.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any + +RED: tuple[int, int, int] +ORANGE: tuple[int, int, int] +YELLOW: tuple[int, int, int] +GREEN: tuple[int, int, int] +LIGHT_BLUE: tuple[int, int, int] +BLUE: tuple[int, int, int] +PINK: tuple[int, int, int] +PURPLE: tuple[int, int, int] +WHITE: tuple[int, int, int] + +class Nanoleaf: + ip: str + print_errors: bool + url: str + auth_token: str + already_registered: bool + def __init__(self, ip: str, auth_token: str | None = None, print_errors: bool = False) -> None: ... + def create_auth_token(self) -> str | None: ... + def delete_auth_token(self, auth_token: str) -> bool: ... + def check_connection(self) -> None: ... + def get_info(self) -> dict[str, Incomplete]: ... + def get_name(self) -> str: ... + def get_auth_token(self) -> str | None: ... + def get_ids(self) -> list[int]: ... + @staticmethod + def get_custom_base_effect(anim_type: str = "custom", loop: bool = True) -> dict[str, Incomplete]: ... + def power_off(self) -> bool: ... + def power_on(self) -> bool: ... + def get_power(self) -> bool: ... + def toggle_power(self) -> bool: ... + def set_color(self, rgb: tuple[int, int, int]) -> bool: ... + def set_brightness(self, brightness: int, duration: int = 0) -> bool: ... + def increment_brightness(self, brightness: int) -> bool: ... + def get_brightness(self) -> int: ... + def identify(self) -> bool: ... + def set_hue(self, value: int) -> bool: ... + def increment_hue(self, value: int) -> bool: ... + def get_hue(self) -> int: ... + def set_saturation(self, value: int) -> bool: ... + def increment_saturation(self, value: int) -> bool: ... + def get_saturation(self) -> int: ... + def set_color_temp(self, value: int) -> bool: ... + def increment_color_temp(self, value: int) -> bool: ... + def get_color_temp(self) -> int: ... + def get_color_mode(self) -> str: ... + def get_current_effect(self) -> str: ... + def set_effect(self, effect_name: str) -> bool: ... + def list_effects(self) -> list[str]: ... + def write_effect(self, effect_dict: dict[str, Incomplete]) -> bool: ... + def effect_exists(self, effect_name: str) -> bool: ... + def pulsate(self, rgb: tuple[int, int, int], speed: float = 1) -> bool: ... + def flow(self, rgb_list: list[tuple[int, int, int]], speed: float = 1) -> bool: ... + def spectrum(self, speed: float = 1) -> bool: ... + def enable_extcontrol(self) -> bool: ... + def get_layout(self) -> dict[str, Incomplete]: ... + def register_event(self, func: Callable[[dict[str, Incomplete]], Any], event_types: list[int]) -> None: ... + +class NanoleafRegistrationError(Exception): + def __init__(self) -> None: ... + +class NanoleafConnectionError(Exception): + def __init__(self) -> None: ... + +class NanoleafEffectCreationError(Exception): ... diff --git a/stubs/netaddr/@tests/stubtest_allowlist.txt b/stubs/netaddr/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b493ad84230b --- /dev/null +++ b/stubs/netaddr/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +netaddr.tests.* + +# __getattr__ is not present at runtime but __init__ has `self.__dict__.update(kwargs)` +netaddr.ip.iana.XMLRecordParser.__getattr__ diff --git a/stubs/netaddr/METADATA.toml b/stubs/netaddr/METADATA.toml new file mode 100644 index 000000000000..fbb5fc4b2ac0 --- /dev/null +++ b/stubs/netaddr/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.3.*" +upstream-repository = "https://github.com/netaddr/netaddr" diff --git a/stubs/netaddr/netaddr/__init__.pyi b/stubs/netaddr/netaddr/__init__.pyi new file mode 100644 index 000000000000..efc922f6964e --- /dev/null +++ b/stubs/netaddr/netaddr/__init__.pyi @@ -0,0 +1,124 @@ +from netaddr.contrib.subnet_splitter import SubnetSplitter as SubnetSplitter +from netaddr.core import ( + INET_ATON as INET_ATON, + INET_PTON as INET_PTON, + NOHOST as NOHOST, + ZEROFILL as ZEROFILL, + AddrConversionError as AddrConversionError, + AddrFormatError as AddrFormatError, + NotRegisteredError as NotRegisteredError, +) +from netaddr.eui import EUI as EUI, IAB as IAB, OUI as OUI +from netaddr.ip import ( + IPAddress as IPAddress, + IPNetwork as IPNetwork, + IPRange as IPRange, + all_matching_cidrs as all_matching_cidrs, + cidr_abbrev_to_verbose as cidr_abbrev_to_verbose, + cidr_exclude as cidr_exclude, + cidr_merge as cidr_merge, + iprange_to_cidrs as iprange_to_cidrs, + iter_iprange as iter_iprange, + iter_unique_ips as iter_unique_ips, + largest_matching_cidr as largest_matching_cidr, + smallest_matching_cidr as smallest_matching_cidr, + spanning_cidr as spanning_cidr, +) +from netaddr.ip.glob import ( + IPGlob as IPGlob, + cidr_to_glob as cidr_to_glob, + glob_to_cidrs as glob_to_cidrs, + glob_to_iprange as glob_to_iprange, + glob_to_iptuple as glob_to_iptuple, + iprange_to_globs as iprange_to_globs, + valid_glob as valid_glob, +) +from netaddr.ip.nmap import iter_nmap_range as iter_nmap_range, valid_nmap_range as valid_nmap_range +from netaddr.ip.rfc1924 import base85_to_ipv6 as base85_to_ipv6, ipv6_to_base85 as ipv6_to_base85 +from netaddr.ip.sets import IPSet as IPSet +from netaddr.strategy.eui48 import ( + mac_bare as mac_bare, + mac_cisco as mac_cisco, + mac_eui48 as mac_eui48, + mac_pgsql as mac_pgsql, + mac_unix as mac_unix, + mac_unix_expanded as mac_unix_expanded, + valid_str as valid_mac, +) +from netaddr.strategy.eui64 import ( + eui64_bare as eui64_bare, + eui64_base as eui64_base, + eui64_cisco as eui64_cisco, + eui64_unix as eui64_unix, + eui64_unix_expanded as eui64_unix_expanded, + valid_str as valid_eui64, +) +from netaddr.strategy.ipv4 import expand_partial_address as expand_partial_ipv4_address, valid_str as valid_ipv4 +from netaddr.strategy.ipv6 import ( + ipv6_compact as ipv6_compact, + ipv6_full as ipv6_full, + ipv6_verbose as ipv6_verbose, + valid_str as valid_ipv6, +) + +__all__ = [ + "AddrConversionError", + "AddrFormatError", + "NotRegisteredError", + "ZEROFILL", + "INET_ATON", + "INET_PTON", + "NOHOST", + "IPAddress", + "IPNetwork", + "IPRange", + "all_matching_cidrs", + "cidr_abbrev_to_verbose", + "cidr_exclude", + "cidr_merge", + "iprange_to_cidrs", + "iter_iprange", + "iter_unique_ips", + "largest_matching_cidr", + "smallest_matching_cidr", + "spanning_cidr", + "IPSet", + "IPGlob", + "cidr_to_glob", + "glob_to_cidrs", + "glob_to_iprange", + "glob_to_iptuple", + "iprange_to_globs", + "valid_glob", + "valid_nmap_range", + "iter_nmap_range", + "base85_to_ipv6", + "ipv6_to_base85", + "EUI", + "IAB", + "OUI", + "valid_ipv4", + "valid_ipv6", + "ipv6_compact", + "ipv6_full", + "ipv6_verbose", + "mac_eui48", + "mac_unix", + "mac_unix_expanded", + "mac_cisco", + "mac_bare", + "mac_pgsql", + "valid_mac", + "eui64_base", + "eui64_unix", + "eui64_unix_expanded", + "eui64_cisco", + "eui64_bare", + "valid_eui64", + "SubnetSplitter", + "expand_partial_ipv4_address", +] + +__version__: str +VERSION: tuple[int, ...] +STATUS: str diff --git a/stubs/netaddr/netaddr/cli.pyi b/stubs/netaddr/netaddr/cli.pyi new file mode 100644 index 000000000000..c19fa74b5960 --- /dev/null +++ b/stubs/netaddr/netaddr/cli.pyi @@ -0,0 +1,8 @@ +from typing import Any + +SHELL_NAMESPACE: dict[str, Any] +ASCII_ART_LOGO: str + +def main() -> None: ... +def shell() -> None: ... +def info(network_input: str) -> None: ... diff --git a/stubs/netaddr/netaddr/compat.pyi b/stubs/netaddr/netaddr/compat.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/netaddr/netaddr/contrib/__init__.pyi b/stubs/netaddr/netaddr/contrib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi b/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi new file mode 100644 index 000000000000..55edd7f096bb --- /dev/null +++ b/stubs/netaddr/netaddr/contrib/subnet_splitter.pyi @@ -0,0 +1,7 @@ +from netaddr.ip import IPNetwork, _IPAddressAddr + +class SubnetSplitter: + def __init__(self, base_cidr: _IPAddressAddr) -> None: ... + def extract_subnet(self, prefix: int, count: int | None = None) -> list[IPNetwork]: ... + def available_subnets(self) -> list[IPNetwork]: ... + def remove_subnet(self, ip_network: IPNetwork) -> None: ... diff --git a/stubs/netaddr/netaddr/core.pyi b/stubs/netaddr/netaddr/core.pyi new file mode 100644 index 000000000000..03460aa3eb71 --- /dev/null +++ b/stubs/netaddr/netaddr/core.pyi @@ -0,0 +1,34 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterator, Mapping +from typing import Final + +BIG_ENDIAN_PLATFORM: bool +INET_PTON: Final = 1 +ZEROFILL: Final = 2 +NOHOST: Final = 4 +INET_ATON: Final = 8 + +class AddrFormatError(Exception): ... +class AddrConversionError(Exception): ... +class NotRegisteredError(Exception): ... + +class Subscriber: + def update(self, data) -> None: ... + +class PrettyPrinter(Subscriber): + fh: SupportsWrite[str] + write_eol: bool + def __init__(self, fh: SupportsWrite[str] = ..., write_eol: bool = True) -> None: ... + def update(self, data: object) -> None: ... + +class Publisher: + subscribers: list[Subscriber] + def __init__(self) -> None: ... + def attach(self, subscriber: Subscriber) -> None: ... + def detach(self, subscriber: Subscriber) -> None: ... + def notify(self, data: object) -> None: ... + +class DictDotLookup: + def __init__(self, d: Mapping[str, object]) -> None: ... + def __getitem__(self, name: str) -> object: ... + def __iter__(self) -> Iterator[str]: ... diff --git a/stubs/netaddr/netaddr/eui/__init__.pyi b/stubs/netaddr/netaddr/eui/__init__.pyi new file mode 100644 index 000000000000..4ff92b883f43 --- /dev/null +++ b/stubs/netaddr/netaddr/eui/__init__.pyi @@ -0,0 +1,91 @@ +from _typeshed import ConvertibleToInt +from typing import ClassVar, Literal, overload +from typing_extensions import Self + +from netaddr.core import DictDotLookup +from netaddr.ip import IPAddress +from netaddr.strategy.eui48 import mac_eui48 +from netaddr.strategy.eui64 import eui64_base + +class BaseIdentifier: + __slots__ = ("_value", "__weakref__") + def __init__(self) -> None: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + +class OUI(BaseIdentifier): + __slots__ = ("records",) + records: list[dict[str, object]] + def __init__(self, oui: str | int) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + @property + def reg_count(self) -> int: ... + def registration(self, index: int = 0) -> DictDotLookup: ... + +class IAB(BaseIdentifier): + __slots__ = ("record",) + IAB_EUI_VALUES: ClassVar[tuple[int, int]] + @classmethod + def split_iab_mac(cls, eui_int: int, strict: bool = False) -> tuple[int, int]: ... + record: dict[str, object] + def __init__(self, iab: str | int, strict: bool = False) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def registration(self) -> DictDotLookup: ... + +class EUI(BaseIdentifier): + __slots__ = ("_module", "_dialect") + def __init__( + self, addr: EUI | int | str, version: int | None = None, dialect: type[mac_eui48 | eui64_base] | None = None + ) -> None: ... + + @property + def value(self) -> int: ... + @value.setter + def value(self, value: ConvertibleToInt) -> None: ... + + @property + def dialect(self) -> type[mac_eui48 | eui64_base]: ... + @dialect.setter + def dialect(self, value: type[mac_eui48 | eui64_base] | None) -> None: ... + + @property + def oui(self) -> OUI: ... + @property + def ei(self) -> str: ... + def is_iab(self) -> bool: ... + @property + def iab(self) -> IAB | None: ... + @property + def version(self) -> Literal[48, 64]: ... + + @overload + def __getitem__(self, idx: int) -> int: ... + @overload + def __getitem__(self, idx: slice) -> list[int]: ... + @overload + def __getitem__(self, idx: int | slice) -> int | list[int]: ... + + def __setitem__(self, idx: int, value: int) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: EUI | int | str) -> bool: ... + def __le__(self, other: EUI | int | str) -> bool: ... + def __gt__(self, other: EUI | int | str) -> bool: ... + def __ge__(self, other: EUI | int | str) -> bool: ... + def bits(self, word_sep: str | None = None) -> str: ... + @property + def packed(self) -> bytes: ... + @property + def words(self) -> tuple[int, ...]: ... + @property + def bin(self) -> str: ... + def eui64(self) -> Self: ... + def modified_eui64(self) -> Self: ... + def ipv6(self, prefix: ConvertibleToInt) -> IPAddress: ... + def ipv6_link_local(self) -> IPAddress: ... + @property + def info(self) -> DictDotLookup: ... + def format(self, dialect: type[mac_eui48 | eui64_base] | None = None) -> str: ... diff --git a/stubs/netaddr/netaddr/eui/ieee.pyi b/stubs/netaddr/netaddr/eui/ieee.pyi new file mode 100644 index 000000000000..a0bcd560d645 --- /dev/null +++ b/stubs/netaddr/netaddr/eui/ieee.pyi @@ -0,0 +1,32 @@ +import _csv +from _typeshed import FileDescriptorOrPath, StrOrBytesPath +from collections.abc import Iterable +from typing import Any, BinaryIO, TextIO, TypeAlias + +from netaddr.core import Publisher, Subscriber + +_INDEX: TypeAlias = dict[int, list[tuple[int, int]]] +OUI_INDEX: _INDEX +IAB_INDEX: _INDEX + +class FileIndexer(Subscriber): + writer: _csv.Writer + def __init__(self, index_file: TextIO | FileDescriptorOrPath) -> None: ... + def update(self, data: Iterable[Any]) -> None: ... + +class OUIIndexParser(Publisher): + fh: BinaryIO + def __init__(self, ieee_file: BinaryIO | FileDescriptorOrPath) -> None: ... + def parse(self) -> None: ... + +class IABIndexParser(Publisher): + fh: BinaryIO + def __init__(self, ieee_file: BinaryIO | FileDescriptorOrPath) -> None: ... + def parse(self) -> None: ... + +def create_index_from_registry( + registry_fh: BinaryIO | FileDescriptorOrPath, index_path: StrOrBytesPath, parser: type[OUIIndexParser | IABIndexParser] +) -> None: ... +def create_indices() -> None: ... +def load_index(index: _INDEX, fp: Iterable[bytes]) -> None: ... +def load_indices() -> None: ... diff --git a/stubs/netaddr/netaddr/fbsocket.pyi b/stubs/netaddr/netaddr/fbsocket.pyi new file mode 100644 index 000000000000..f33989b5b19d --- /dev/null +++ b/stubs/netaddr/netaddr/fbsocket.pyi @@ -0,0 +1,8 @@ +from typing import Literal + +AF_INET: Literal[2] +AF_INET6: Literal[10] + +def inet_ntoa(packed_ip: bytes) -> str: ... +def inet_ntop(af: int, packed_ip: bytes) -> str: ... +def inet_pton(af: int, ip_string: str) -> str: ... diff --git a/stubs/netaddr/netaddr/ip/__init__.pyi b/stubs/netaddr/netaddr/ip/__init__.pyi new file mode 100644 index 000000000000..0f748120ca95 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/__init__.pyi @@ -0,0 +1,192 @@ +from _typeshed import ConvertibleToInt, Unused +from abc import abstractmethod +from collections.abc import Iterable, Iterator +from types import ModuleType +from typing import Literal, SupportsIndex, SupportsInt, TypeAlias, overload +from typing_extensions import Self + +from netaddr.core import DictDotLookup +from netaddr.strategy.ipv6 import ipv6_verbose + +class BaseIP: + __slots__ = ("_value", "_module", "__weakref__") + def __init__(self) -> None: ... + + @property + def value(self) -> int | None: ... + @value.setter + def value(self, value: int) -> None: ... + + @abstractmethod + def key(self) -> tuple[int, ...]: ... + @abstractmethod + def sort_key(self) -> tuple[int, ...]: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: BaseIP) -> bool: ... + def __le__(self, other: BaseIP) -> bool: ... + def __gt__(self, other: BaseIP) -> bool: ... + def __ge__(self, other: BaseIP) -> bool: ... + def is_unicast(self) -> bool: ... + def is_multicast(self) -> bool: ... + def is_loopback(self) -> bool: ... + def is_link_local(self) -> bool: ... + def is_reserved(self) -> bool: ... + def is_ipv4_mapped(self) -> bool: ... + def is_ipv4_compat(self) -> bool: ... + @property + def info(self) -> DictDotLookup: ... + @property + def version(self) -> Literal[4, 6]: ... + +_IPAddressAddr: TypeAlias = BaseIP | int | str +_IPNetworkAddr: TypeAlias = IPNetwork | IPAddress | tuple[int, int] | str + +class IPAddress(BaseIP): + __slots__ = () + def __init__(self, addr: _IPAddressAddr, version: Literal[4, 6] | None = None, flags: int = 0) -> None: ... + def netmask_bits(self) -> int: ... + def is_hostmask(self) -> bool: ... + def is_netmask(self) -> bool: ... + def __iadd__(self, num: int) -> Self: ... + def __isub__(self, num: int) -> Self: ... + def __add__(self, num: int) -> Self: ... + __radd__ = __add__ + def __sub__(self, num: int) -> Self: ... + def __rsub__(self, num: int) -> Self: ... + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def __int__(self) -> int: ... + def __index__(self) -> int: ... + def __bytes__(self) -> bytes: ... + def bits(self, word_sep: str | None = None) -> str: ... + @property + def packed(self) -> bytes: ... + @property + def words(self) -> tuple[int, ...]: ... + @property + def bin(self) -> str: ... + @property + def reverse_dns(self) -> str: ... + def ipv4(self) -> Self: ... + def ipv6(self, ipv4_compatible: bool = False) -> Self: ... + def format(self, dialect: type[ipv6_verbose] | None = None) -> str: ... + def __or__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __and__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __xor__(self, other: SupportsInt | SupportsIndex) -> Self: ... + def __lshift__(self, numbits: int) -> Self: ... + def __rshift__(self, numbits: int) -> Self: ... + def __bool__(self) -> bool: ... + def to_canonical(self) -> Self: ... + def is_global(self) -> bool: ... + def is_ipv4_private_use(self) -> bool: ... + def is_ipv6_unique_local(self) -> bool: ... + +class IPListMixin: + __slots__ = () + def __iter__(self) -> Iterator[IPAddress]: ... + @property + def size(self) -> int: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, index: SupportsIndex) -> IPAddress: ... + @overload + def __getitem__(self, index: slice) -> Iterator[IPAddress]: ... + @overload + def __getitem__(self, index: SupportsIndex | slice) -> IPAddress | Iterator[IPAddress]: ... + + def __contains__(self, other: BaseIP | _IPAddressAddr) -> bool: ... + def __bool__(self) -> Literal[True]: ... + +def parse_ip_network( + module: ModuleType, addr: tuple[int, int] | str, flags: int = 0, *, expand_partial: bool = False +) -> tuple[int, int]: ... + +class IPNetwork(BaseIP, IPListMixin): + __slots__ = ("_prefixlen",) + def __init__( + self, addr: _IPNetworkAddr, version: Literal[4, 6] | None = None, flags: int = 0, *, expand_partial: bool = False + ) -> None: ... + + @property + def prefixlen(self) -> int: ... + @prefixlen.setter + def prefixlen(self, value: int) -> None: ... + + @property + def ip(self) -> IPAddress: ... + @property + def network(self) -> IPAddress: ... + @property + def broadcast(self) -> IPAddress | None: ... + @property + def first(self) -> int: ... + @property + def last(self) -> int: ... + + @property + def netmask(self) -> IPAddress: ... + @netmask.setter + def netmask(self, value: _IPAddressAddr) -> None: ... + + @property + def hostmask(self) -> IPAddress: ... + @property + def cidr(self) -> IPNetwork: ... + def __iadd__(self, num: int) -> Self: ... + def __isub__(self, num: int) -> Self: ... + # runtime overrides __contains__ with incompatible type for "other" + def __contains__(self, other: BaseIP | _IPNetworkAddr) -> bool: ... # type: ignore[override] + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def ipv4(self) -> Self: ... + def ipv6(self, ipv4_compatible: bool = False) -> Self: ... + def previous(self, step: int = 1) -> Self: ... + def next(self, step: int = 1) -> Self: ... + def supernet(self, prefixlen: int = 0) -> list[IPNetwork]: ... + def subnet(self, prefixlen: int, count: int | None = None, fmt: Unused = None) -> Iterator[Self]: ... + def iter_hosts(self) -> Iterator[IPAddress]: ... + +class IPRange(BaseIP, IPListMixin): + __slots__ = ("_start", "_end") + def __init__(self, start: _IPAddressAddr, end: _IPAddressAddr, flags: int = 0) -> None: ... + def __contains__(self, other: BaseIP | _IPAddressAddr) -> bool: ... + @property + def first(self) -> int: ... + @property + def last(self) -> int: ... + def key(self) -> tuple[int, ...]: ... + def sort_key(self) -> tuple[int, ...]: ... + def cidrs(self) -> list[IPNetwork]: ... + +def iter_unique_ips(*args: IPRange | _IPNetworkAddr) -> Iterator[IPAddress]: ... +def cidr_abbrev_to_verbose(abbrev_cidr: ConvertibleToInt) -> str: ... +def cidr_merge(ip_addrs: Iterable[IPRange | _IPNetworkAddr]) -> list[IPNetwork]: ... +def cidr_exclude(target: _IPNetworkAddr, exclude: _IPNetworkAddr) -> list[IPNetwork]: ... +def cidr_partition( + target: _IPNetworkAddr, exclude: _IPNetworkAddr +) -> tuple[list[IPNetwork], list[IPNetwork], list[IPNetwork]]: ... +def spanning_cidr(ip_addrs: Iterable[_IPNetworkAddr]) -> IPNetwork: ... +def iter_iprange(start: _IPAddressAddr, end: _IPAddressAddr, step: SupportsInt | SupportsIndex = 1) -> Iterator[IPAddress]: ... +def iprange_to_cidrs(start: _IPNetworkAddr, end: _IPNetworkAddr) -> list[IPNetwork]: ... +def smallest_matching_cidr(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> IPNetwork | None: ... +def largest_matching_cidr(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> IPNetwork | None: ... +def all_matching_cidrs(ip: _IPAddressAddr, cidrs: Iterable[_IPNetworkAddr]) -> list[IPNetwork]: ... + +IPV4_LOOPBACK: IPNetwork +IPV4_PRIVATE_USE: list[IPNetwork] +IPV4_LINK_LOCAL: IPNetwork +IPV4_MULTICAST: IPNetwork +IPV4_6TO4: IPNetwork +IPV4_RESERVED: tuple[IPNetwork | IPRange, ...] +IPV4_NOT_GLOBALLY_REACHABLE: list[IPNetwork] +IPV4_NOT_GLOBALLY_REACHABLE_EXCEPTIONS: list[IPNetwork] +IPV6_LOOPBACK: IPNetwork +IPV6_UNIQUE_LOCAL: IPNetwork +IPV6_LINK_LOCAL: IPNetwork +IPV6_MULTICAST: IPNetwork +IPV6_RESERVED: tuple[IPNetwork, ...] +IPV6_NOT_GLOBALLY_REACHABLE: list[IPNetwork] +IPV6_NOT_GLOBALLY_REACHABLE_EXCEPTIONS: list[IPNetwork] diff --git a/stubs/netaddr/netaddr/ip/glob.pyi b/stubs/netaddr/netaddr/ip/glob.pyi new file mode 100644 index 000000000000..c2865d085e7b --- /dev/null +++ b/stubs/netaddr/netaddr/ip/glob.pyi @@ -0,0 +1,19 @@ +from typing import TypeGuard + +from netaddr.ip import IPAddress, IPNetwork, IPRange, _IPAddressAddr, _IPNetworkAddr + +def valid_glob(ipglob: object) -> TypeGuard[str]: ... +def glob_to_iptuple(ipglob: str) -> tuple[IPAddress, IPAddress]: ... +def glob_to_iprange(ipglob: str) -> IPRange: ... +def iprange_to_globs(start: _IPAddressAddr, end: _IPAddressAddr) -> list[str]: ... +def glob_to_cidrs(ipglob: str) -> list[IPNetwork]: ... +def cidr_to_glob(cidr: _IPNetworkAddr) -> str: ... + +class IPGlob(IPRange): + __slots__ = ("_glob",) + def __init__(self, ipglob: str) -> None: ... + + @property + def glob(self) -> str: ... + @glob.setter + def glob(self, value: str) -> None: ... diff --git a/stubs/netaddr/netaddr/ip/iana.pyi b/stubs/netaddr/netaddr/ip/iana.pyi new file mode 100644 index 000000000000..1d205a275d25 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/iana.pyi @@ -0,0 +1,51 @@ +from _typeshed import SupportsWrite +from collections.abc import Callable, Mapping, MutableMapping +from typing import Any, TypeAlias +from xml.sax import _Source, handler +from xml.sax.xmlreader import AttributesImpl, InputSource, XMLReader + +from netaddr.core import Publisher, Subscriber +from netaddr.ip import IPAddress, IPNetwork, IPRange + +_IanaInfoKey: TypeAlias = IPAddress | IPNetwork | IPRange + +IANA_INFO: dict[str, dict[_IanaInfoKey, dict[str, str]]] + +class SaxRecordParser(handler.ContentHandler): + def __init__(self, callback: Callable[[Mapping[str, object] | None], object] | None = None) -> None: ... + def startElement(self, name: str, attrs: AttributesImpl) -> None: ... + def endElement(self, name: str) -> None: ... + def characters(self, content: str) -> None: ... + +class XMLRecordParser(Publisher): + xmlparser: XMLReader + fh: InputSource | _Source + def __init__(self, fh: InputSource | _Source, **kwargs: object) -> None: ... + def process_record(self, rec: Mapping[str, object]) -> dict[str, str] | None: ... + def consume_record(self, rec: object) -> None: ... + def parse(self) -> None: ... + # Arbitrary attributes are set in __init__ with `self.__dict__.update(kwargs)` + def __getattr__(self, name: str, /) -> Any: ... + +class IPv4Parser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class IPv6Parser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class IPv6UnicastParser(XMLRecordParser): + def process_record(self, rec: Mapping[str, object]) -> dict[str, str]: ... + +class MulticastParser(XMLRecordParser): + def normalise_addr(self, addr: str) -> str: ... + +class DictUpdater(Subscriber): + dct: MutableMapping[_IanaInfoKey, dict[str, Any]] + topic: str + unique_key: str + def __init__(self, dct: MutableMapping[_IanaInfoKey, dict[str, Any]], topic: str, unique_key: str) -> None: ... + def update(self, data: dict[str, Any]) -> None: ... + +def load_info() -> None: ... +def pprint_info(fh: SupportsWrite[str] | None = None) -> None: ... +def query(ip_addr: IPAddress) -> dict[str, list[dict[str, str]]]: ... diff --git a/stubs/netaddr/netaddr/ip/nmap.pyi b/stubs/netaddr/netaddr/ip/nmap.pyi new file mode 100644 index 000000000000..b63826b5ec95 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/nmap.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterator + +from netaddr.ip import IPAddress + +def valid_nmap_range(target_spec: str) -> bool: ... +def iter_nmap_range(*nmap_target_spec: str) -> Iterator[IPAddress]: ... diff --git a/stubs/netaddr/netaddr/ip/rfc1924.pyi b/stubs/netaddr/netaddr/ip/rfc1924.pyi new file mode 100644 index 000000000000..6a4199bf0bae --- /dev/null +++ b/stubs/netaddr/netaddr/ip/rfc1924.pyi @@ -0,0 +1,9 @@ +from netaddr.ip import _IPAddressAddr + +def chr_range(low: str, high: str) -> list[str]: ... + +BASE_85: list[str] +BASE_85_DICT: dict[str, int] + +def ipv6_to_base85(addr: _IPAddressAddr) -> str: ... +def base85_to_ipv6(addr: str) -> str: ... diff --git a/stubs/netaddr/netaddr/ip/sets.pyi b/stubs/netaddr/netaddr/ip/sets.pyi new file mode 100644 index 000000000000..d8656f69b548 --- /dev/null +++ b/stubs/netaddr/netaddr/ip/sets.pyi @@ -0,0 +1,46 @@ +from collections.abc import Iterable, Iterator +from typing import TypeAlias +from typing_extensions import Never, Self + +from netaddr.ip import IPAddress, IPNetwork, IPRange, _IPNetworkAddr + +_IPIterable: TypeAlias = IPNetwork | IPRange | IPSet | Iterable[_IPNetworkAddr | IPRange | int] + +class IPSet: + __slots__ = ("_cidrs", "__weakref__") + def __init__(self, iterable: _IPIterable | None = None, flags: int = 0) -> None: ... + def compact(self) -> None: ... + def __hash__(self) -> Never: ... + def __contains__(self, ip: _IPNetworkAddr) -> bool: ... + def __bool__(self) -> bool: ... + def __iter__(self) -> Iterator[IPAddress]: ... + def iter_cidrs(self) -> list[IPNetwork]: ... + def add(self, addr: IPRange | _IPNetworkAddr | int, flags: int = 0) -> None: ... + def remove(self, addr: IPRange | _IPNetworkAddr | int, flags: int = 0) -> None: ... + def pop(self) -> IPNetwork: ... + def isdisjoint(self, other: IPSet) -> bool: ... + def copy(self) -> Self: ... + def update(self, iterable: _IPIterable, flags: int = 0) -> None: ... + def clear(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: IPSet) -> bool: ... + def issubset(self, other: IPSet) -> bool: ... + __le__ = issubset + def __gt__(self, other: IPSet) -> bool: ... + def issuperset(self, other: IPSet) -> bool: ... + __ge__ = issuperset + def union(self, other: IPSet) -> Self: ... + __or__ = union + def intersection(self, other: IPSet) -> IPSet: ... + __and__ = intersection + def symmetric_difference(self, other: IPSet) -> IPSet: ... + __xor__ = symmetric_difference + def difference(self, other: IPSet) -> IPSet: ... + __sub__ = difference + def __len__(self) -> int: ... + @property + def size(self) -> int: ... + def iscontiguous(self) -> bool: ... + def iprange(self) -> IPRange | None: ... + def iter_ipranges(self) -> Iterator[IPRange]: ... diff --git a/stubs/netaddr/netaddr/strategy/__init__.pyi b/stubs/netaddr/netaddr/strategy/__init__.pyi new file mode 100644 index 000000000000..0e93ac08c1b2 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/__init__.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable, Sequence + +def bytes_to_bits() -> list[str]: ... + +BYTES_TO_BITS: list[str] + +def valid_words(words: Iterable[int], word_size: int, num_words: int) -> bool: ... +def int_to_words(int_val: int, word_size: int, num_words: int) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], word_size: int, num_words: int) -> int: ... +def valid_bits(bits: str, width: int, word_sep: str = "") -> bool: ... +def bits_to_int(bits: str, width: int, word_sep: str = "") -> int: ... +def int_to_bits(int_val: int, word_size: int, num_words: int, word_sep: str = "") -> str: ... +def valid_bin(bin_val: str, width: int) -> bool: ... +def int_to_bin(int_val: int, width: int) -> str: ... +def bin_to_int(bin_val: str, width: int) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/eui48.pyi b/stubs/netaddr/netaddr/strategy/eui48.pyi new file mode 100644 index 000000000000..cd5f73b2f362 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/eui48.pyi @@ -0,0 +1,39 @@ +from collections.abc import Iterable, Sequence +from re import Pattern +from typing import ClassVar, Literal + +width: Literal[48] +version: Literal[48] +max_int: int + +class mac_eui48: + word_size: ClassVar[int] + num_words: ClassVar[int] + max_word: ClassVar[int] + word_sep: ClassVar[str] + word_fmt: ClassVar[str] + word_base: ClassVar[int] + +class mac_unix(mac_eui48): ... +class mac_unix_expanded(mac_unix): ... +class mac_cisco(mac_eui48): ... +class mac_bare(mac_eui48): ... +class mac_pgsql(mac_eui48): ... + +DEFAULT_DIALECT: type[mac_eui48] +RE_MAC_FORMATS: list[Pattern[str]] + +def valid_str(addr: str) -> bool: ... +def str_to_int(addr: str) -> int: ... +def int_to_str(int_val: int, dialect: type[mac_eui48] | None = None) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int], dialect: type[mac_eui48] | None = None) -> bool: ... +def int_to_words(int_val: int, dialect: type[mac_eui48] | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], dialect: type[mac_eui48] | None = None) -> int: ... +def valid_bits(bits: str, dialect: type[mac_eui48] | None = None) -> bool: ... +def bits_to_int(bits: str, dialect: type[mac_eui48] | None = None) -> int: ... +def int_to_bits(int_val: int, dialect: type[mac_eui48] | None = None) -> str: ... +def valid_bin(bin_val: str, dialect: type[mac_eui48] | None = None) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/eui64.pyi b/stubs/netaddr/netaddr/strategy/eui64.pyi new file mode 100644 index 000000000000..19d02f085e80 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/eui64.pyi @@ -0,0 +1,38 @@ +from collections.abc import Iterable, Sequence +from re import Pattern +from typing import ClassVar, Literal + +width: Literal[64] +version: Literal[64] +max_int: int + +class eui64_base: + word_size: ClassVar[int] + num_words: ClassVar[int] + max_word: ClassVar[int] + word_sep: ClassVar[str] + word_fmt: ClassVar[str] + word_base: ClassVar[int] + +class eui64_unix(eui64_base): ... +class eui64_unix_expanded(eui64_unix): ... +class eui64_cisco(eui64_base): ... +class eui64_bare(eui64_base): ... + +DEFAULT_EUI64_DIALECT: type[eui64_base] +RE_EUI64_FORMATS: list[Pattern[str]] + +def valid_str(addr: str) -> bool: ... +def str_to_int(addr: str) -> int: ... +def int_to_str(int_val: int, dialect: type[eui64_base] | None = None) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int], dialect: type[eui64_base] | None = None) -> bool: ... +def int_to_words(int_val: int, dialect: type[eui64_base] | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int], dialect: type[eui64_base] | None = None) -> int: ... +def valid_bits(bits: str, dialect: type[eui64_base] | None = None) -> bool: ... +def bits_to_int(bits: str, dialect: type[eui64_base] | None = None) -> int: ... +def int_to_bits(int_val: int, dialect: type[eui64_base] | None = None) -> str: ... +def valid_bin(bin_val: str, dialect: type[eui64_base] | None = None) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netaddr/netaddr/strategy/ipv4.pyi b/stubs/netaddr/netaddr/strategy/ipv4.pyi new file mode 100644 index 000000000000..b9510c4ed763 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/ipv4.pyi @@ -0,0 +1,39 @@ +from _typeshed import Unused +from collections.abc import Iterable, Sequence +from socket import AddressFamily +from typing import Literal + +from netaddr.core import INET_PTON as INET_PTON, ZEROFILL as ZEROFILL + +width: Literal[32] +word_size: Literal[8] +word_fmt: Literal["%d"] +word_sep: Literal["."] +family: Literal[AddressFamily.AF_INET] +family_name: Literal["IPv4"] +version: Literal[4] +word_base: Literal[10] +max_int: int +num_words: Literal[4] +max_word: int +prefix_to_netmask: dict[int, int] +netmask_to_prefix: dict[int, int] +prefix_to_hostmask: dict[int, int] +hostmask_to_prefix: dict[int, int] + +def valid_str(addr: str, flags: int = 0) -> bool: ... +def str_to_int(addr: str, flags: int = 0) -> int: ... +def int_to_str(int_val: int, dialect: Unused = None) -> str: ... +def int_to_arpa(int_val: int) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int]) -> bool: ... +def int_to_words(int_val: int) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int]) -> int: ... +def valid_bits(bits: str) -> bool: ... +def bits_to_int(bits: str) -> int: ... +def int_to_bits(int_val: int, word_sep: str | None = None) -> str: ... +def valid_bin(bin_val: str) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... +def expand_partial_address(addr: str) -> str: ... diff --git a/stubs/netaddr/netaddr/strategy/ipv6.pyi b/stubs/netaddr/netaddr/strategy/ipv6.pyi new file mode 100644 index 000000000000..a2988ffb8837 --- /dev/null +++ b/stubs/netaddr/netaddr/strategy/ipv6.pyi @@ -0,0 +1,43 @@ +from collections.abc import Iterable, Sequence +from typing import ClassVar, Final, Literal + +from netaddr.fbsocket import AF_INET6 + +OPT_IMPORTS: bool +width: Literal[128] +word_size: Literal[16] +word_sep: Literal[":"] +family: Final = AF_INET6 +family_name: Literal["IPv6"] +version: Literal[6] +word_base: Literal[16] +max_int: int +num_words: Literal[8] +max_word: int +prefix_to_netmask: dict[int, int] +netmask_to_prefix: dict[int, int] +prefix_to_hostmask: dict[int, int] +hostmask_to_prefix: dict[int, int] + +class ipv6_compact: + word_fmt: ClassVar[str] + compact: ClassVar[bool] + +class ipv6_full(ipv6_compact): ... +class ipv6_verbose(ipv6_compact): ... + +def valid_str(addr: str, flags: int = 0) -> bool: ... +def str_to_int(addr: str, flags: int = 0) -> int: ... +def int_to_str(int_val: int, dialect: type[ipv6_compact] | None = None) -> str: ... +def int_to_arpa(int_val: int) -> str: ... +def int_to_packed(int_val: int) -> bytes: ... +def packed_to_int(packed_int: bytes) -> int: ... +def valid_words(words: Iterable[int]) -> bool: ... +def int_to_words(int_val: int, num_words: int | None = None, word_size: int | None = None) -> tuple[int, ...]: ... +def words_to_int(words: Sequence[int]) -> int: ... +def valid_bits(bits: str) -> bool: ... +def bits_to_int(bits: str) -> int: ... +def int_to_bits(int_val: int, word_sep: str | None = None) -> str: ... +def valid_bin(bin_val: str) -> bool: ... +def int_to_bin(int_val: int) -> str: ... +def bin_to_int(bin_val: str) -> int: ... diff --git a/stubs/netifaces/@tests/stubtest_allowlist.txt b/stubs/netifaces/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..553280bdb8d9 --- /dev/null +++ b/stubs/netifaces/@tests/stubtest_allowlist.txt @@ -0,0 +1,34 @@ +# Values that may not always exist at runtime, as they are system-specific. +netifaces.AF_12844 +netifaces.AF_ATM +netifaces.AF_BAN +netifaces.AF_CCITT +netifaces.AF_CHAOS +netifaces.AF_CLUSTER +netifaces.AF_CNT +netifaces.AF_COIP +netifaces.AF_DATAKIT +netifaces.AF_DLI +netifaces.AF_ECMA +netifaces.AF_FIREFOX +netifaces.AF_HYLINK +netifaces.AF_IMPLINK +netifaces.AF_ISO +netifaces.AF_LAT +netifaces.AF_NATM +netifaces.AF_NDRV +netifaces.AF_NETBIOS +netifaces.AF_NETDES +netifaces.AF_NETGRAPH +netifaces.AF_NS +netifaces.AF_PPP +netifaces.AF_PUP +netifaces.AF_SIP +netifaces.AF_SYSTEM +netifaces.AF_UNKNOWN1 +netifaces.AF_VOICEVIEW +netifaces.IN6_IFF_AUTOCONF +netifaces.IN6_IFF_DYNAMIC +netifaces.IN6_IFF_OPTIMISTIC +netifaces.IN6_IFF_SECURED +netifaces.IN6_IFF_TEMPORARY diff --git a/stubs/netifaces/METADATA.toml b/stubs/netifaces/METADATA.toml new file mode 100644 index 000000000000..a6a6a2608f55 --- /dev/null +++ b/stubs/netifaces/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.11.*" +upstream-repository = "https://github.com/al45tair/netifaces" diff --git a/stubs/netifaces/netifaces.pyi b/stubs/netifaces/netifaces.pyi new file mode 100644 index 000000000000..fa146c35761c --- /dev/null +++ b/stubs/netifaces/netifaces.pyi @@ -0,0 +1,72 @@ +from typing import Final, Literal + +AF_12844: Final[int] +AF_APPLETALK: Final[int] +AF_ASH: Final[int] +AF_ATM: Final[int] +AF_ATMPVC: Final[int] +AF_ATMSVC: Final[int] +AF_AX25: Final[int] +AF_BAN: Final[int] +AF_BLUETOOTH: Final[int] +AF_BRIDGE: Final[int] +AF_DATAKIT: Final[int] +AF_DECnet: Final[int] +AF_CCITT: Final[int] +AF_CHAOS: Final[int] +AF_CLUSTER: Final[int] +AF_CNT: Final[int] +AF_COIP: Final[int] +AF_DLI: Final[int] +AF_ECONET: Final[int] +AF_ECMA: Final[int] +AF_FILE: Final[int] +AF_FIREFOX: Final[int] +AF_HYLINK: Final[int] +AF_IMPLINK: Final[int] +AF_INET: Final[int] +AF_INET6: Final[int] +AF_IPX: Final[int] +AF_IRDA: Final[int] +AF_ISDN: Final[int] +AF_ISO: Final[int] +AF_KEY: Final[int] +AF_LAT: Final[int] +AF_LINK: Final[int] +AF_NATM: Final[int] +AF_NETBEUI: Final[int] +AF_NETBIOS: Final[int] +AF_NETDES: Final[int] +AF_NETGRAPH: Final[int] +AF_NETLINK: Final[int] +AF_NETROM: Final[int] +AF_NDRV: Final[int] +AF_NS: Final[int] +AF_PACKET: Final[int] +AF_PPP: Final[int] +AF_PPPOX: Final[int] +AF_PUP: Final[int] +AF_ROSE: Final[int] +AF_ROUTE: Final[int] +AF_SECURITY: Final[int] +AF_SIP: Final[int] +AF_SNA: Final[int] +AF_SYSTEM: Final[int] +AF_UNIX: Final[int] +AF_UNKNOWN1: Final[int] +AF_UNSPEC: Final[int] +AF_VOICEVIEW: Final[int] +AF_WANPIPE: Final[int] +AF_X25: Final[int] +IN6_IFF_AUTOCONF: Final[int] +IN6_IFF_TEMPORARY: Final[int] +IN6_IFF_DYNAMIC: Final[int] +IN6_IFF_OPTIMISTIC: Final[int] +IN6_IFF_SECURED: Final[int] + +address_families: Final[dict[int, str]] +version: Final[str] + +def gateways() -> dict[int | Literal["default"], list[tuple[str, str, bool] | tuple[str, str]] | dict[int, tuple[str, str]]]: ... +def ifaddresses(ifname: str, /) -> dict[int, list[dict[str, str]]]: ... +def interfaces() -> list[str]: ... diff --git a/stubs/networkx/@tests/stubtest_allowlist.txt b/stubs/networkx/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b53baec2a0d1 --- /dev/null +++ b/stubs/networkx/@tests/stubtest_allowlist.txt @@ -0,0 +1,39 @@ +# overloaded class-decorators are not properly supported in type-checkers: +# - mypy: https://github.com/python/mypy/issues/16840 +# - pyright: https://github.com/microsoft/pyright/issues/7167 +networkx\.(algorithms\.)?(boundary\.)?edge_boundary +networkx\.(algorithms\.)?(bridges\.)?local_bridges +networkx\.(algorithms\.)?(clique\.)?node_clique_number +networkx\.(convert_matrix\.)?from_numpy_array +networkx\.(convert_matrix\.)?from_pandas_adjacency +networkx\.(convert_matrix\.)?from_pandas_edgelist +networkx\.(generators\.)?(random_clustered\.)?random_clustered_graph +networkx\.(relabel\.)?relabel_nodes + +# Stubtest doesn't understand aliases of class-decorated functions (possibly https://github.com/python/mypy/issues/6700 ) +networkx\.(algorithms\.)?(centrality\.)?(current_flow_closeness\.)?information_centrality +networkx\.(generators\.)?(random_graphs\.)?binomial_graph +networkx\.(generators\.)?(random_graphs\.)?erdos_renyi_graph +networkx\.(algorithms\.(minors\.(contraction\.)?)?)?identified_nodes +networkx\.algorithms\.flow\.maxflow\.default_flow_func +networkx\.algorithms\.[a-z_\.]+\.default_flow_func +networkx\.(algorithms\.(centrality\.(load\.)?)?)?load_centrality +networkx\.algorithms\.bipartite\.(matching\.)?maximum_matching +networkx\.algorithms\.bipartite\.(cluster\.)?clustering + +# Stubtest says: "runtime argument "backend" has a default value of type None, which is +# incompatible with stub argument type builtins.str. This is often caused by overloads +# failing to account for explicitly passing in the default value." +# Which is true, but would require some way of concatenating `backend` to ParamSpec.kwargs +networkx\.(utils\.)?(backends\.)?_dispatchable\.__call__ + +# Tests are excluded +networkx.conftest +networkx(\..+?)?\.tests(\..+?)? + +# Stub-only module +networkx\._typing + +# "..._DT is not present at runtime" but we don't set it in stubs, I don't understand this one +networkx(\.algorithms)?(\.tree)?(\.mst)?\.SpanningTreeIterator\.Partition\._DT +networkx(\.algorithms)?(\.tree)?(\.branchings)?\.ArborescenceIterator\.Partition\._DT diff --git a/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py b/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py new file mode 100644 index 000000000000..c4bb02d2026e --- /dev/null +++ b/stubs/networkx/@tests/test_cases/check_dispatch_decorator-py312.py @@ -0,0 +1,23 @@ +from typing_extensions import assert_type + +from networkx.utils.backends import _dispatchable + + +@_dispatchable +def some_method(int_p: int, str_p: str) -> float: + return 0.0 + + +# Wrong param / order +some_method("", 0) # type: ignore +# backend is kw-only +some_method(0, "", None) # type: ignore +# No backend means no **backend_kwargs allowed +some_method(0, "", backend_specific_kwarg="") # type: ignore +some_method(0, "", backend=None, backend_specific_kwarg="") # type: ignore + +# Correct usage +assert_type(some_method(0, ""), float) +# type system doesn't allow this yet (see comment in networkx/utils/backends.pyi) +# assert_type(some_method(0, "", backend=None), float) +assert_type(some_method(0, "", backend="custom backend", backend_specific_kwarg=""), float) diff --git a/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py b/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py new file mode 100644 index 000000000000..20a38a85a8ad --- /dev/null +++ b/stubs/networkx/@tests/test_cases/check_tricky_function_params-py312.py @@ -0,0 +1,25 @@ +from typing_extensions import assert_type + +import networkx as nx +from networkx.classes.reportviews import DegreeView, DiDegreeView + +# Test covariant dict type for `pos` in nx_latex functions +G: "nx.Graph[int]" = nx.Graph([(1, 2), (2, 3), (3, 4)]) +nx.to_latex_raw(G, pos=nx.spring_layout(G, seed=42)) # OK: dict[node, ndarray] +pos1: dict[int, tuple[int, int]] = {1: (1, 2), 2: (3, 4), 3: (5, 6), 4: (7, 8)} +nx.to_latex_raw(G, pos=pos1) # OK: dict[node, 2-tuple] +pos2: dict[int, str] = {1: "(1, 2)", 2: "(3, 4)", 3: "(5, 6)", 4: "(7, 8)"} +nx.to_latex_raw(G, pos=pos2) # OK: dict[node, str] +pos3: dict[int, int] = {1: 1, 2: 3, 3: 5, 4: 7} +nx.to_latex_raw(G, pos=pos3) # type: ignore # dict keys must be str or collection + +# Test that we don't confuse str and Iterable[str] in DiDegreeView.__call__ +G_str = nx.Graph[str]() +di_degree_view = DiDegreeView(G_str) +assert_type(di_degree_view(""), int) +assert_type(di_degree_view([""]), DiDegreeView[str]) +assert_type(di_degree_view({""}), DiDegreeView[str]) +degree_view = DegreeView(G_str) +assert_type(degree_view(""), int) +assert_type(degree_view([""]), DegreeView[str]) +assert_type(degree_view({""}), DegreeView[str]) diff --git a/stubs/networkx/METADATA.toml b/stubs/networkx/METADATA.toml new file mode 100644 index 000000000000..80c1685dcf49 --- /dev/null +++ b/stubs/networkx/METADATA.toml @@ -0,0 +1,8 @@ +version = "3.6.1" +upstream-repository = "https://github.com/networkx/networkx" +# requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] + +[tool.stubtest] +# stub_uploader won't allow pandas-stubs in the requires field https://github.com/typeshed-internal/stub_uploader/issues/90 +stubtest-dependencies = ["pandas"] diff --git a/stubs/networkx/networkx/__init__.pyi b/stubs/networkx/networkx/__init__.pyi new file mode 100644 index 000000000000..bdd328fb405a --- /dev/null +++ b/stubs/networkx/networkx/__init__.pyi @@ -0,0 +1,30 @@ +from typing import Final + +from networkx.algorithms import * +from networkx.classes import * +from networkx.classes import filters as filters +from networkx.convert import * +from networkx.convert_matrix import * +from networkx.drawing import * +from networkx.exception import * +from networkx.generators import * +from networkx.lazy_imports import _lazy_import as _lazy_import +from networkx.linalg import * +from networkx.readwrite import * +from networkx.relabel import * +from networkx.utils import _clear_cache as _clear_cache, _dispatchable as _dispatchable, config as config + +from . import ( + algorithms as algorithms, + classes as classes, + convert as convert, + convert_matrix as convert_matrix, + drawing as drawing, + generators as generators, + linalg as linalg, + readwrite as readwrite, + relabel as relabel, + utils as utils, +) + +__version__: Final[str] diff --git a/stubs/networkx/networkx/_typing.pyi b/stubs/networkx/networkx/_typing.pyi new file mode 100644 index 000000000000..b82d9673deb0 --- /dev/null +++ b/stubs/networkx/networkx/_typing.pyi @@ -0,0 +1,22 @@ +# Stub-only module, can't be imported at runtime. + +from collections.abc import Collection +from typing import Any, Protocol, TypeAlias, type_check_only +from typing_extensions import TypeVar + +import numpy as np + +_ScalarT = TypeVar("_ScalarT", bound=bool | int | float | complex | str | bytes | np.generic) +_GenericT = TypeVar("_GenericT", bound=np.generic) +_GenericT_co = TypeVar("_GenericT_co", bound=np.generic, covariant=True) +_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=Any, covariant=True) + +# numpy aliases +@type_check_only +class SupportsArray(Protocol[_GenericT_co, _ShapeT_co]): + def __array__(self) -> np.ndarray[_ShapeT_co, np.dtype[_GenericT_co]]: ... + +ArrayLike1D: TypeAlias = Collection[_ScalarT] | SupportsArray[_GenericT, tuple[int]] +Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_GenericT]] +Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_GenericT]] +Seed: TypeAlias = int | np.random.Generator | np.random.RandomState diff --git a/stubs/networkx/networkx/algorithms/__init__.pyi b/stubs/networkx/networkx/algorithms/__init__.pyi new file mode 100644 index 000000000000..7dc8465ff47b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/__init__.pyi @@ -0,0 +1,140 @@ +from networkx.algorithms import ( + approximation as approximation, + assortativity as assortativity, + bipartite as bipartite, + centrality as centrality, + chordal as chordal, + clique as clique, + cluster as cluster, + coloring as coloring, + community as community, + components as components, + connectivity as connectivity, + flow as flow, + isomorphism as isomorphism, + link_analysis as link_analysis, + lowest_common_ancestors as lowest_common_ancestors, + node_classification as node_classification, + operators as operators, + shortest_paths as shortest_paths, + tournament as tournament, + traversal as traversal, + tree as tree, +) +from networkx.algorithms.assortativity import * +from networkx.algorithms.asteroidal import * +from networkx.algorithms.bipartite import ( + complete_bipartite_graph as complete_bipartite_graph, + is_bipartite as is_bipartite, + projected_graph as projected_graph, +) +from networkx.algorithms.boundary import * +from networkx.algorithms.bridges import * +from networkx.algorithms.broadcasting import * +from networkx.algorithms.centrality import * +from networkx.algorithms.chains import * +from networkx.algorithms.chordal import * +from networkx.algorithms.clique import * +from networkx.algorithms.cluster import * +from networkx.algorithms.coloring import * +from networkx.algorithms.communicability_alg import * +from networkx.algorithms.components import * +from networkx.algorithms.connectivity import ( + all_node_cuts as all_node_cuts, + all_pairs_node_connectivity as all_pairs_node_connectivity, + average_node_connectivity as average_node_connectivity, + edge_connectivity as edge_connectivity, + edge_disjoint_paths as edge_disjoint_paths, + is_k_edge_connected as is_k_edge_connected, + k_components as k_components, + k_edge_augmentation as k_edge_augmentation, + k_edge_components as k_edge_components, + k_edge_subgraphs as k_edge_subgraphs, + minimum_edge_cut as minimum_edge_cut, + minimum_node_cut as minimum_node_cut, + node_connectivity as node_connectivity, + node_disjoint_paths as node_disjoint_paths, + stoer_wagner as stoer_wagner, +) +from networkx.algorithms.core import * +from networkx.algorithms.covering import * +from networkx.algorithms.cuts import * +from networkx.algorithms.cycles import * +from networkx.algorithms.d_separation import * +from networkx.algorithms.dag import * +from networkx.algorithms.distance_measures import * +from networkx.algorithms.distance_regular import * +from networkx.algorithms.dominance import * +from networkx.algorithms.dominating import * +from networkx.algorithms.efficiency_measures import * +from networkx.algorithms.euler import * +from networkx.algorithms.flow import ( + capacity_scaling as capacity_scaling, + cost_of_flow as cost_of_flow, + gomory_hu_tree as gomory_hu_tree, + max_flow_min_cost as max_flow_min_cost, + maximum_flow as maximum_flow, + maximum_flow_value as maximum_flow_value, + min_cost_flow as min_cost_flow, + min_cost_flow_cost as min_cost_flow_cost, + minimum_cut as minimum_cut, + minimum_cut_value as minimum_cut_value, + network_simplex as network_simplex, +) +from networkx.algorithms.graph_hashing import * +from networkx.algorithms.graphical import * +from networkx.algorithms.hierarchy import * +from networkx.algorithms.hybrid import * +from networkx.algorithms.isolate import * +from networkx.algorithms.isomorphism import ( + could_be_isomorphic as could_be_isomorphic, + fast_could_be_isomorphic as fast_could_be_isomorphic, + faster_could_be_isomorphic as faster_could_be_isomorphic, + is_isomorphic as is_isomorphic, +) +from networkx.algorithms.isomorphism.vf2pp import * +from networkx.algorithms.link_analysis import * +from networkx.algorithms.link_prediction import * +from networkx.algorithms.lowest_common_ancestors import * +from networkx.algorithms.matching import * +from networkx.algorithms.minors import * +from networkx.algorithms.mis import * +from networkx.algorithms.moral import * +from networkx.algorithms.non_randomness import * +from networkx.algorithms.operators import * +from networkx.algorithms.perfect_graph import * +from networkx.algorithms.planar_drawing import * +from networkx.algorithms.planarity import * +from networkx.algorithms.polynomials import * +from networkx.algorithms.reciprocity import * +from networkx.algorithms.regular import * +from networkx.algorithms.richclub import * +from networkx.algorithms.shortest_paths import * +from networkx.algorithms.similarity import * +from networkx.algorithms.simple_paths import * +from networkx.algorithms.smallworld import * +from networkx.algorithms.smetric import * +from networkx.algorithms.sparsifiers import * +from networkx.algorithms.structuralholes import * +from networkx.algorithms.summarization import * +from networkx.algorithms.swap import * +from networkx.algorithms.time_dependent import * +from networkx.algorithms.tournament import is_tournament as is_tournament +from networkx.algorithms.traversal import * +from networkx.algorithms.tree.branchings import ( + ArborescenceIterator as ArborescenceIterator, + maximum_branching as maximum_branching, + maximum_spanning_arborescence as maximum_spanning_arborescence, + minimum_branching as minimum_branching, + minimum_spanning_arborescence as minimum_spanning_arborescence, +) +from networkx.algorithms.tree.coding import * +from networkx.algorithms.tree.decomposition import * +from networkx.algorithms.tree.mst import * +from networkx.algorithms.tree.operations import * +from networkx.algorithms.tree.recognition import * +from networkx.algorithms.triads import * +from networkx.algorithms.vitality import * +from networkx.algorithms.voronoi import * +from networkx.algorithms.walks import * +from networkx.algorithms.wiener import * diff --git a/stubs/networkx/networkx/algorithms/approximation/__init__.pyi b/stubs/networkx/networkx/algorithms/approximation/__init__.pyi new file mode 100644 index 000000000000..c80fffaef227 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/__init__.pyi @@ -0,0 +1,14 @@ +from networkx.algorithms.approximation.clique import * +from networkx.algorithms.approximation.clustering_coefficient import * +from networkx.algorithms.approximation.connectivity import * +from networkx.algorithms.approximation.density import * +from networkx.algorithms.approximation.distance_measures import * +from networkx.algorithms.approximation.dominating_set import * +from networkx.algorithms.approximation.kcomponents import * +from networkx.algorithms.approximation.matching import * +from networkx.algorithms.approximation.maxcut import * +from networkx.algorithms.approximation.ramsey import * +from networkx.algorithms.approximation.steinertree import * +from networkx.algorithms.approximation.traveling_salesman import * +from networkx.algorithms.approximation.treewidth import * +from networkx.algorithms.approximation.vertex_cover import * diff --git a/stubs/networkx/networkx/algorithms/approximation/clique.pyi b/stubs/networkx/networkx/algorithms/approximation/clique.pyi new file mode 100644 index 000000000000..f0d3d435d5c8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/clique.pyi @@ -0,0 +1,13 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["clique_removal", "max_clique", "large_clique_size", "maximum_independent_set"] + +@_dispatchable +def maximum_independent_set(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def max_clique(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def clique_removal(G: Graph[_Node]) -> tuple[set[_Node], list[set[_Node]]]: ... +@_dispatchable +def large_clique_size(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi b/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi new file mode 100644 index 000000000000..cff53629ceb7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/clustering_coefficient.pyi @@ -0,0 +1,8 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["average_clustering"] + +@_dispatchable +def average_clustering(G: Graph[_Node], trials: int = 1000, seed: int | RandomState | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi b/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi new file mode 100644 index 000000000000..6fc71c4130eb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/connectivity.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["local_node_connectivity", "node_connectivity", "all_pairs_node_connectivity"] + +@_dispatchable +def local_node_connectivity(G: Graph[_Node], source: _Node, target: _Node, cutoff: float | None = None) -> float: ... +@_dispatchable +def node_connectivity(G: Graph[_Node], s: _Node | None = None, t: _Node | None = None) -> float: ... +@_dispatchable +def all_pairs_node_connectivity( + G: Graph[_Node], nbunch: Iterable[_Node] | None = None, cutoff: float | None = None +) -> dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/density.pyi b/stubs/networkx/networkx/algorithms/approximation/density.pyi new file mode 100644 index 000000000000..8d84f8373b39 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/density.pyi @@ -0,0 +1,14 @@ +from collections.abc import Callable, Hashable +from typing import Literal, TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_Algorithm: TypeAlias = Literal["greedy++", "fista"] + +__all__ = ["densest_subgraph"] + +ALGORITHMS: dict[_Algorithm, Callable[[Graph[Hashable], int], tuple[float, set[int]]]] + +@_dispatchable +def densest_subgraph(G: Graph[_Node], iterations: int = 1, *, method: _Algorithm = "fista") -> tuple[float, set[int]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi b/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi new file mode 100644 index 000000000000..f52a300f8f66 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/distance_measures.pyi @@ -0,0 +1,8 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["diameter"] + +@_dispatchable +def diameter(G: Graph[_Node], seed: int | RandomState | None = None) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi b/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi new file mode 100644 index 000000000000..e37d3713ce42 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/dominating_set.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_weighted_dominating_set", "min_edge_dominating_set"] + +@_dispatchable +def min_weighted_dominating_set(G: Graph[_Node], weight: str | None = None) -> set[Incomplete]: ... +@_dispatchable +def min_edge_dominating_set(G: Graph[_Node]) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi b/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi new file mode 100644 index 000000000000..e0fe94385cd5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/kcomponents.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections import defaultdict + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_components"] + +@_dispatchable +def k_components(G: Graph[_Node], min_density: float = 0.95) -> defaultdict[Incomplete, list[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/matching.pyi b/stubs/networkx/networkx/algorithms/approximation/matching.pyi new file mode 100644 index 000000000000..7b5f723d44d0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/matching.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_maximal_matching"] + +@_dispatchable +def min_maximal_matching(G: Graph[_Node]) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi b/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi new file mode 100644 index 000000000000..4518df47f2a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/maxcut.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["randomized_partitioning", "one_exchange"] + +@_dispatchable +def randomized_partitioning( + G: Graph[_Node], seed: int | RandomState | None = None, p: float = 0.5, weight: str | None = None +) -> tuple[float, tuple[set[Incomplete], set[Incomplete]]]: ... +@_dispatchable +def one_exchange( + G: Graph[_Node], initial_cut: set[Incomplete] | None = None, seed: int | RandomState | None = None, weight: str | None = None +) -> tuple[float, tuple[set[Incomplete], set[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi b/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi new file mode 100644 index 000000000000..f1248ef9d101 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/ramsey.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["ramsey_R2"] + +@_dispatchable +def ramsey_R2(G: Graph[_Node]) -> tuple[set[Incomplete], set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi b/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi new file mode 100644 index 000000000000..4f761fa97e24 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/steinertree.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["metric_closure", "steiner_tree"] + +@_dispatchable +@deprecated( + "`metric_closure` is deprecated and will be removed in NetworkX 3.8. Use `networkx.all_pairs_shortest_path_length` instead." +) +def metric_closure(G: Graph[_Node], weight="weight") -> Graph[Incomplete]: ... +@_dispatchable +def steiner_tree( + G: Graph[_Node], terminal_nodes: Iterable[Incomplete], weight: str = "weight", method: str | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi b/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi new file mode 100644 index 000000000000..3c388b8d6677 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/traveling_salesman.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Literal, TypeVar + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "traveling_salesman_problem", + "christofides", + "asadpour_atsp", + "greedy_tsp", + "simulated_annealing_tsp", + "threshold_accepting_tsp", +] + +_SupportsLenAndGetItemT = TypeVar("_SupportsLenAndGetItemT", bound=SupportsLenAndGetItem[Any]) + +def swap_two_nodes(soln: _SupportsLenAndGetItemT, seed) -> _SupportsLenAndGetItemT: ... +def move_one_node(soln: _SupportsLenAndGetItemT, seed) -> _SupportsLenAndGetItemT: ... +@_dispatchable +def christofides(G: Graph[_Node], weight: str | None = "weight", tree: Graph[_Node] | None = None) -> list[Incomplete]: ... +@_dispatchable +def traveling_salesman_problem( + G: Graph[_Node], + weight: str = "weight", + nodes=None, + cycle: bool = True, + method: Callable[..., Incomplete] | None = None, + **kwargs, +) -> list[Incomplete]: ... +@_dispatchable +def asadpour_atsp( + G: DiGraph[_Node], weight: str | None = "weight", seed: int | RandomState | None = None, source: str | None = None +) -> list[Incomplete]: ... +@_dispatchable +def held_karp_ascent( + G: Graph[_Node], weight: str = "weight" +) -> tuple[float, dict[Incomplete, Incomplete] | Graph[Incomplete]]: ... +@_dispatchable +def spanning_tree_distribution(G: Graph[_Node], z: Mapping[Incomplete, Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def greedy_tsp(G: Graph[_Node], weight: str | None = "weight", source=None) -> list[Incomplete]: ... +@_dispatchable +def simulated_annealing_tsp( + G: Graph[_Node], + init_cycle: Literal["greedy"] | Iterable[Incomplete], + weight: str | None = "weight", + source=None, + temp: int | None = 100, + move: Callable[..., Incomplete] | Literal["1-1", "1-0"] = "1-1", + max_iterations: int | None = 10, + N_inner: int | None = 100, + alpha: float = 0.01, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... +@_dispatchable +def threshold_accepting_tsp( + G: Graph[_Node], + init_cycle: Literal["greedy"] | Iterable[Incomplete], + weight: str | None = "weight", + source=None, + threshold: int | None = 1, + move: Callable[..., Incomplete] | Literal["1-1", "1-0"] = "1-1", + max_iterations: int | None = 10, + N_inner: int | None = 100, + alpha: float = 0.1, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi b/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi new file mode 100644 index 000000000000..6a9f9afe2d39 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/treewidth.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Generic + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["treewidth_min_degree", "treewidth_min_fill_in"] + +@_dispatchable +def treewidth_min_degree(G: Graph[_Node]) -> tuple[int, Graph[frozenset[_Node]]]: ... +@_dispatchable +def treewidth_min_fill_in(G: Graph[_Node]) -> tuple[int, Graph[frozenset[_Node]]]: ... + +class MinDegreeHeuristic(Generic[_Node]): + count: Incomplete + + def __init__(self, graph: Graph[_Node]) -> None: ... + def best_node(self, graph: Mapping[_Node, set[_Node]]) -> _Node | None: ... + +def min_fill_in_heuristic(graph_dict: Mapping[_Node, set[_Node]]) -> _Node | None: ... +@_dispatchable +def treewidth_decomp( + G: Graph[_Node], heuristic: Callable[[dict[_Node, set[_Node]]], _Node | None] = ... +) -> tuple[int, Graph[frozenset[_Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi b/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi new file mode 100644 index 000000000000..abec263a7bd0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/approximation/vertex_cover.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_weighted_vertex_cover"] + +@_dispatchable +def min_weighted_vertex_cover(G: Graph[_Node], weight: str | None = None) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi b/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi new file mode 100644 index 000000000000..4d9888609cbc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/__init__.pyi @@ -0,0 +1,5 @@ +from networkx.algorithms.assortativity.connectivity import * +from networkx.algorithms.assortativity.correlation import * +from networkx.algorithms.assortativity.mixing import * +from networkx.algorithms.assortativity.neighbor_degree import * +from networkx.algorithms.assortativity.pairs import * diff --git a/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi b/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi new file mode 100644 index 000000000000..349d6cff8a3c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/connectivity.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["average_degree_connectivity"] + +@_dispatchable +def average_degree_connectivity( + G: Graph[_Node], + source: Literal["in+out", "out", "in"] = "in+out", + target: Literal["in+out", "out", "in"] = "in+out", + nodes: Iterable[Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, int | float]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi b/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi new file mode 100644 index 000000000000..78f36749726d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/correlation.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "degree_pearson_correlation_coefficient", + "degree_assortativity_coefficient", + "attribute_assortativity_coefficient", + "numeric_assortativity_coefficient", +] + +@_dispatchable +def degree_assortativity_coefficient( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> float: ... +@_dispatchable +def degree_pearson_correlation_coefficient( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> float: ... +@_dispatchable +def attribute_assortativity_coefficient(G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None) -> float: ... +@_dispatchable +def numeric_assortativity_coefficient(G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi b/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi new file mode 100644 index 000000000000..ef4764e3d59d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/mixing.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["attribute_mixing_matrix", "attribute_mixing_dict", "degree_mixing_matrix", "degree_mixing_dict", "mixing_dict"] + +@_dispatchable +def attribute_mixing_dict( + G: Graph[_Node], attribute: str, nodes: Iterable[Incomplete] | None = None, normalized: bool = False +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def attribute_mixing_matrix( + G: Graph[_Node], + attribute: str, + nodes: Iterable[Incomplete] | None = None, + mapping: Mapping[Incomplete, Incomplete] | None = None, + normalized: bool = True, +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def degree_mixing_dict( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes=None, normalized: bool = False +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def degree_mixing_matrix( + G: Graph[_Node], + x: str = "out", + y: str = "in", + weight: str | None = None, + nodes: Iterable[Incomplete] | None = None, + normalized: bool = True, + mapping: Mapping[Incomplete, Incomplete] | None = None, +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def mixing_dict(xy: Iterable[tuple[Incomplete, Incomplete]], normalized: bool = False) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi b/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi new file mode 100644 index 000000000000..231c1966d0eb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/neighbor_degree.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["average_neighbor_degree"] + +@_dispatchable +def average_neighbor_degree( + G: Graph[_Node], + source: str | None = "out", + target: str | None = "out", + nodes: Iterable[Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi b/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi new file mode 100644 index 000000000000..502d5346f0d6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/assortativity/pairs.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_attribute_xy", "node_degree_xy"] + +@_dispatchable +def node_attribute_xy(G: Graph[_Node], attribute, nodes: Iterable[Incomplete] | None = None) -> Generator[Incomplete]: ... +@_dispatchable +def node_degree_xy( + G: Graph[_Node], x: str = "out", y: str = "in", weight: str | None = None, nodes: Iterable[Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/asteroidal.pyi b/stubs/networkx/networkx/algorithms/asteroidal.pyi new file mode 100644 index 000000000000..9e4dbd34028f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/asteroidal.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_at_free", "find_asteroidal_triple"] + +@_dispatchable +def find_asteroidal_triple(G: Graph[_Node]) -> list[Incomplete] | None: ... +@_dispatchable +def is_at_free(G: Graph[_Node]) -> bool: ... +@_dispatchable +def create_component_structure(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi b/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi new file mode 100644 index 000000000000..7b9c7b3c0d3c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/__init__.pyi @@ -0,0 +1,13 @@ +from networkx.algorithms.bipartite.basic import * +from networkx.algorithms.bipartite.centrality import * +from networkx.algorithms.bipartite.cluster import * +from networkx.algorithms.bipartite.covering import * +from networkx.algorithms.bipartite.edgelist import * +from networkx.algorithms.bipartite.extendability import * +from networkx.algorithms.bipartite.generators import * +from networkx.algorithms.bipartite.link_analysis import * +from networkx.algorithms.bipartite.matching import * +from networkx.algorithms.bipartite.matrix import * +from networkx.algorithms.bipartite.projection import * +from networkx.algorithms.bipartite.redundancy import * +from networkx.algorithms.bipartite.spectral import * diff --git a/stubs/networkx/networkx/algorithms/bipartite/basic.pyi b/stubs/networkx/networkx/algorithms/bipartite/basic.pyi new file mode 100644 index 000000000000..8610070f70ce --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/basic.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_bipartite", "is_bipartite_node_set", "color", "sets", "density", "degrees"] + +@_dispatchable +def color(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def is_bipartite(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_bipartite_node_set(G: Graph[_Node], nodes: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def sets(G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None) -> tuple[set[Incomplete], set[Incomplete]]: ... +@_dispatchable +def density(B: Graph[_Node], nodes: Collection[Incomplete]) -> float: ... +@_dispatchable +def degrees(B: Graph[_Node], nodes: Iterable[Incomplete], weight: str | None = None) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi b/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi new file mode 100644 index 000000000000..90ac03059f80 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/centrality.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["degree_centrality", "betweenness_centrality", "closeness_centrality"] + +@_dispatchable +def degree_centrality(G: Graph[_Node], nodes: Iterable[Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def betweenness_centrality(G: Graph[_Node], nodes: Iterable[Incomplete]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def closeness_centrality( + G: Graph[_Node], nodes: Iterable[Incomplete], normalized: bool | None = True +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi b/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi new file mode 100644 index 000000000000..1a341ef85e92 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/cluster.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["clustering", "average_clustering", "latapy_clustering", "robins_alexander_clustering"] + +def cc_dot(nu, nv) -> float: ... +def cc_max(nu, nv) -> float: ... +def cc_min(nu, nv) -> float: ... + +modes: dict[str, Callable[[Incomplete, Incomplete], float]] + +@_dispatchable +def latapy_clustering( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, mode: str = "dot" +) -> dict[Incomplete, Incomplete]: ... + +clustering = latapy_clustering + +@_dispatchable +def average_clustering(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, mode: str = "dot") -> float: ... +@_dispatchable +def robins_alexander_clustering(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/covering.pyi b/stubs/networkx/networkx/algorithms/bipartite/covering.pyi new file mode 100644 index 000000000000..ab33bcecf487 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/covering.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_edge_cover"] + +@_dispatchable +def min_edge_cover(G: Graph[_Node], matching_algorithm: Callable[..., Incomplete] | None = None) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi b/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi new file mode 100644 index 000000000000..de80e3d56b41 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/edgelist.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Collection, Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_edgelist", "write_edgelist", "parse_edgelist", "read_edgelist"] + +@_dispatchable +def write_edgelist( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + comments: str = "#", + delimiter: str = " ", + data: bool = True, + encoding: str = "utf-8", +) -> None: ... +@_dispatchable +def generate_edgelist(G: Graph[_Node], delimiter: str = " ", data: bool = True) -> Generator[str]: ... +@_dispatchable +def parse_edgelist( + lines: Iterable[str], + comments: str | None = "#", + delimiter: str | None = None, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + nodetype: type[Incomplete] | None = None, + data: bool | Collection[tuple[str, type[Incomplete]]] = True, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str | None = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + data: bool | Collection[tuple[str, type[Incomplete]]] = True, + edgetype=None, + encoding: str | None = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi b/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi new file mode 100644 index 000000000000..3269743ce9c2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/extendability.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["maximal_extendability"] + +@_dispatchable +def maximal_extendability(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/generators.pyi b/stubs/networkx/networkx/algorithms/bipartite/generators.pyi new file mode 100644 index 000000000000..cf5b9686cfb9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/generators.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "configuration_model", + "havel_hakimi_graph", + "reverse_havel_hakimi_graph", + "alternating_havel_hakimi_graph", + "preferential_attachment_graph", + "random_graph", + "gnmk_random_graph", + "complete_bipartite_graph", +] + +@_dispatchable +def complete_bipartite_graph(n1, n2, create_using: Graph[_Node] | type[Graph[_Node]] | None = None): ... +@_dispatchable +def configuration_model( + aseq: Iterable[Incomplete], + bseq: Iterable[Incomplete], + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + seed: int | RandomState | None = None, +): ... +@_dispatchable +def havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def reverse_havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def alternating_havel_hakimi_graph( + aseq: Iterable[Incomplete], bseq: Iterable[Incomplete], create_using: Graph[_Node] | type[Graph[_Node]] | None = None +): ... +@_dispatchable +def preferential_attachment_graph( + aseq: Iterable[Incomplete], + p: float, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + seed: int | RandomState | None = None, +): ... +@_dispatchable +def random_graph(n: int, m: int, p: float, seed: int | RandomState | None = None, directed: bool | None = False): ... +@_dispatchable +def gnmk_random_graph(n: int, m: int, k: int, seed: int | RandomState | None = None, directed: bool | None = False): ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi b/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi new file mode 100644 index 000000000000..75a125908432 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/link_analysis.pyi @@ -0,0 +1,20 @@ +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["birank"] + +@_dispatchable +def birank( + G: Graph[_Node], + nodes: Iterable[_Node], + *, + alpha: float | None = None, + beta: float | None = None, + top_personalization: Mapping[_Node, float] | None = None, + bottom_personalization: Mapping[_Node, float] | None = None, + max_iter: int = 100, + tol: float = 1.0e-6, + weight: str | None = "weight", +) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/matching.pyi b/stubs/networkx/networkx/algorithms/bipartite/matching.pyi new file mode 100644 index 000000000000..d0df0b6da990 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/matching.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["maximum_matching", "hopcroft_karp_matching", "eppstein_matching", "to_vertex_cover", "minimum_weight_full_matching"] + +@_dispatchable +def hopcroft_karp_matching(G: Graph[_Node], top_nodes: Iterable[_Node] | None = None) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def eppstein_matching(G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def to_vertex_cover( + G: Graph[_Node], matching: Mapping[Incomplete, Incomplete], top_nodes: Iterable[Incomplete] | None = None +) -> set[Incomplete]: ... + +maximum_matching = hopcroft_karp_matching + +@_dispatchable +def minimum_weight_full_matching( + G: Graph[_Node], top_nodes: Iterable[Incomplete] | None = None, weight: str | None = "weight" +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi b/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi new file mode 100644 index 000000000000..18bca470ca7f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/matrix.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["biadjacency_matrix", "from_biadjacency_matrix"] + +@_dispatchable +def biadjacency_matrix( + G: Graph[_Node], + row_order: Iterable[_Node], + column_order: Iterable[Incomplete] | None = None, + dtype: np.dtype[Incomplete] | None = None, + weight: str | None = "weight", + format: str = "csr", +): ... # Return is a complex union of scipy classes depending on the format param +@_dispatchable +def from_biadjacency_matrix( + A, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, + edge_attribute: str = "weight", + *, + row_order: Iterable[Incomplete] | None = None, + column_order: Iterable[Incomplete] | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/projection.pyi b/stubs/networkx/networkx/algorithms/bipartite/projection.pyi new file mode 100644 index 000000000000..3d383557dbf5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/projection.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "projected_graph", + "weighted_projected_graph", + "collaboration_weighted_projected_graph", + "overlap_weighted_projected_graph", + "generic_weighted_projected_graph", +] + +@_dispatchable +def projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], multigraph: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], ratio: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def collaboration_weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def overlap_weighted_projected_graph(B: Graph[_Node], nodes: Iterable[Incomplete], jaccard: bool = True) -> Graph[Incomplete]: ... +@_dispatchable +def generic_weighted_projected_graph( + B: Graph[_Node], nodes: Iterable[Incomplete], weight_function: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi b/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi new file mode 100644 index 000000000000..539e8012ad11 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/redundancy.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_redundancy"] + +@_dispatchable +def node_redundancy(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi b/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi new file mode 100644 index 000000000000..e7102d54aefe --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bipartite/spectral.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["spectral_bipartivity"] + +@_dispatchable +def spectral_bipartivity( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str = "weight" +) -> float | dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/boundary.pyi b/stubs/networkx/networkx/algorithms/boundary.pyi new file mode 100644 index 000000000000..358ed74eb197 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/boundary.pyi @@ -0,0 +1,112 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import TypeVar, overload + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_U = TypeVar("_U") +__all__ = ["edge_boundary", "node_boundary"] + +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default=None, +) -> Generator[tuple[_Node, _Node, int, dict[str, Incomplete]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, int, dict[str, _U]]]: ... +@overload +def edge_boundary( + G: Graph[_Node], + nbunch1: Iterable[Incomplete], + nbunch2: Iterable[Incomplete] | None = None, + data=False, + keys: bool = False, + default: _U | None = None, +) -> Generator[tuple[_Node, _Node, int, dict[str, _U]]]: ... + +@_dispatchable +def node_boundary(G: Graph[_Node], nbunch1: Iterable[Incomplete], nbunch2: Iterable[Incomplete] | None = None) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/bridges.pyi b/stubs/networkx/networkx/algorithms/bridges.pyi new file mode 100644 index 000000000000..104a682bc24c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/bridges.pyi @@ -0,0 +1,17 @@ +from collections.abc import Generator +from typing import overload + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["bridges", "has_bridges", "local_bridges"] + +@_dispatchable +def bridges(G: Graph[_Node], root: _Node | None = None) -> Generator[_Node]: ... +@_dispatchable +def has_bridges(G: Graph[_Node], root: _Node | None = None) -> bool: ... + +@overload +def local_bridges(G: Graph[_Node], with_span: bool = True, weight: str | None = None) -> Generator[tuple[_Node, _Node]]: ... +@overload +def local_bridges(G: Graph[_Node], with_span: bool = True, weight: str | None = None) -> Generator[tuple[_Node, _Node, int]]: ... diff --git a/stubs/networkx/networkx/algorithms/broadcasting.pyi b/stubs/networkx/networkx/algorithms/broadcasting.pyi new file mode 100644 index 000000000000..e61d77b28e7c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/broadcasting.pyi @@ -0,0 +1,9 @@ +import networkx as nx +from networkx.classes.graph import Graph, _Node + +__all__ = ["tree_broadcast_center", "tree_broadcast_time"] + +@nx._dispatchable +def tree_broadcast_center(G: Graph[_Node]) -> tuple[int, set[_Node]]: ... +@nx._dispatchable +def tree_broadcast_time(G: Graph[_Node], node: int | None = None) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/__init__.pyi b/stubs/networkx/networkx/algorithms/centrality/__init__.pyi new file mode 100644 index 000000000000..4a8ceb436a4b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/__init__.pyi @@ -0,0 +1,20 @@ +from .betweenness import * +from .betweenness_subset import * +from .closeness import * +from .current_flow_betweenness import * +from .current_flow_betweenness_subset import * +from .current_flow_closeness import * +from .degree_alg import * +from .dispersion import * +from .eigenvector import * +from .group import * +from .harmonic import * +from .katz import * +from .laplacian import * +from .load import * +from .percolation import * +from .reaching import * +from .second_order import * +from .subgraph_alg import * +from .trophic import * +from .voterank_alg import * diff --git a/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi b/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi new file mode 100644 index 000000000000..ddaf1288a3d4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/betweenness.pyi @@ -0,0 +1,23 @@ +from networkx.classes.graph import Graph, _Edge, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["betweenness_centrality", "edge_betweenness_centrality"] + +@_dispatchable +def betweenness_centrality( + G: Graph[_Node], + k: int | None = None, + normalized: bool | None = True, + weight: str | None = None, + endpoints: bool | None = False, + seed: int | RandomState | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def edge_betweenness_centrality( + G: Graph[_Node], + k: int | None = None, + normalized: bool | None = True, + weight: str | None = None, + seed: int | RandomState | None = None, +) -> dict[_Edge[_Node], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi b/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi new file mode 100644 index 000000000000..8f91e193b844 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/betweenness_subset.pyi @@ -0,0 +1,23 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Edge, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["betweenness_centrality_subset", "edge_betweenness_centrality_subset"] + +@_dispatchable +def betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = False, + weight: str | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def edge_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = False, + weight: str | None = None, +) -> dict[_Edge[_Node], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/closeness.pyi b/stubs/networkx/networkx/algorithms/centrality/closeness.pyi new file mode 100644 index 000000000000..7719ca78e687 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/closeness.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete, SupportsKeysAndGetItem + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["closeness_centrality", "incremental_closeness_centrality"] + +@_dispatchable +def closeness_centrality( + G: Graph[_Node], u: _Node | None = None, distance=None, wf_improved: bool | None = True +) -> dict[_Node, float]: ... +@_dispatchable +def incremental_closeness_centrality( + G: Graph[_Node], + edge: tuple[Incomplete], + prev_cc: SupportsKeysAndGetItem[Incomplete, Incomplete] | None = None, + insertion: bool | None = True, + wf_improved: bool | None = True, +) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi new file mode 100644 index 000000000000..cfee1601ec36 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "current_flow_betweenness_centrality", + "approximate_current_flow_betweenness_centrality", + "edge_current_flow_betweenness_centrality", +] + +@_dispatchable +def approximate_current_flow_betweenness_centrality( + G: Graph[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "full", + epsilon: float = 0.5, + kmax: int = 10000, + seed: int | RandomState | None = None, + *, + sample_weight: float = 1, +) -> dict[Incomplete, float]: ... +@_dispatchable +def current_flow_betweenness_centrality( + G: Graph[_Node], normalized: bool | None = True, weight: str | None = None, dtype: type = ..., solver: str = "full" +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def edge_current_flow_betweenness_centrality( + G: Graph[_Node], normalized: bool | None = True, weight: str | None = None, dtype: type = ..., solver: str = "full" +) -> dict[tuple[Incomplete, Incomplete], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi new file mode 100644 index 000000000000..b7f38a4c9b31 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_betweenness_subset.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["current_flow_betweenness_centrality_subset", "edge_current_flow_betweenness_centrality_subset"] + +@_dispatchable +def current_flow_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "lu", +) -> dict[Incomplete, float]: ... +@_dispatchable +def edge_current_flow_betweenness_centrality_subset( + G: Graph[_Node], + sources: Iterable[_Node], + targets: Iterable[_Node], + normalized: bool | None = True, + weight: str | None = None, + dtype: type = ..., + solver: str = "lu", +) -> dict[tuple[Incomplete, Incomplete], float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi b/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi new file mode 100644 index 000000000000..d7b95eeea326 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/current_flow_closeness.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["current_flow_closeness_centrality", "information_centrality"] + +@_dispatchable +def current_flow_closeness_centrality( + G: Graph[_Node], weight: str | None = None, dtype: type = ..., solver: str = "lu" +) -> dict[Incomplete, float]: ... + +information_centrality = current_flow_closeness_centrality diff --git a/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi new file mode 100644 index 000000000000..a3d4719c8eba --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/degree_alg.pyi @@ -0,0 +1,11 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["degree_centrality", "in_degree_centrality", "out_degree_centrality"] + +@_dispatchable +def degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... +@_dispatchable +def in_degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... +@_dispatchable +def out_degree_centrality(G: Graph[_Node]) -> dict[_Node, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi b/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi new file mode 100644 index 000000000000..4cc9ed0f4de0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/dispersion.pyi @@ -0,0 +1,15 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dispersion"] + +@_dispatchable +def dispersion( + G: Graph[_Node], + u: _Node | None = None, + v: _Node | None = None, + normalized: bool = True, + alpha: float = 1.0, + b: float = 0.0, + c: float = 0.0, +) -> dict[_Node, float] | dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi b/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi new file mode 100644 index 000000000000..75ee56abc272 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/eigenvector.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["eigenvector_centrality", "eigenvector_centrality_numpy"] + +@_dispatchable +def eigenvector_centrality( + G: Graph[_Node], + max_iter: int | None = 100, + tol: float | None = 1e-06, + nstart: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, float]: ... +@_dispatchable +def eigenvector_centrality_numpy( + G: Graph[_Node], weight: str | None = None, max_iter: int | None = 50, tol: float | None = 0 +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi b/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi new file mode 100644 index 000000000000..6b41a4822a94 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/flow_matrix.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +@_dispatchable +def flow_matrix_row(G: Graph[_Node], weight=None, dtype=..., solver: str = "lu") -> Generator[Incomplete]: ... + +class InverseLaplacian: + dtype: Incomplete + n: Incomplete + w: Incomplete + C: Incomplete + L1: Incomplete + + def __init__(self, L, width=None, dtype=None) -> None: ... + def init_solver(self, L) -> None: ... + def solve(self, r) -> None: ... + def solve_inverse(self, r) -> None: ... + def get_rows(self, r1, r2): ... + def get_row(self, r): ... + def width(self, L): ... + +class FullInverseLaplacian(InverseLaplacian): + IL: Incomplete + + def init_solver(self, L) -> None: ... + def solve(self, rhs): ... + def solve_inverse(self, r): ... + +class SuperLUInverseLaplacian(InverseLaplacian): + lusolve: Incomplete + + def init_solver(self, L) -> None: ... + def solve_inverse(self, r): ... + def solve(self, rhs): ... + +class CGInverseLaplacian(InverseLaplacian): + M: Incomplete + + def init_solver(self, L) -> None: ... + def solve(self, rhs): ... + def solve_inverse(self, r): ... diff --git a/stubs/networkx/networkx/algorithms/centrality/group.pyi b/stubs/networkx/networkx/algorithms/centrality/group.pyi new file mode 100644 index 000000000000..3a5e6b880783 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/group.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Collection, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "group_betweenness_centrality", + "group_closeness_centrality", + "group_degree_centrality", + "group_in_degree_centrality", + "group_out_degree_centrality", + "prominent_group", +] + +@_dispatchable +def group_betweenness_centrality( + G: Graph[_Node], + C: Collection[Incomplete], + normalized: bool | None = True, + weight: str | None = None, + endpoints: bool | None = False, +) -> list[float] | float: ... +@_dispatchable +def prominent_group( + G: Graph[_Node], + k: int, + weight: str | None = None, + C: Iterable[Incomplete] | None = None, + endpoints: bool | None = False, + normalized: bool | None = True, + greedy: bool | None = False, +) -> tuple[float, list[Incomplete]]: ... +@_dispatchable +def group_closeness_centrality(G: Graph[_Node], S: Iterable[Incomplete], weight: str | None = None) -> float: ... +@_dispatchable +def group_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... +@_dispatchable +def group_in_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... +@_dispatchable +def group_out_degree_centrality(G: Graph[_Node], S: Iterable[Incomplete]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi b/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi new file mode 100644 index 000000000000..4b00562653f8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/harmonic.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["harmonic_centrality"] + +@_dispatchable +def harmonic_centrality( + G: Graph[_Node], nbunch: Iterable[Incomplete] | None = None, distance=None, sources: Iterable[Incomplete] | None = None +) -> dict[Incomplete, int]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/katz.pyi b/stubs/networkx/networkx/algorithms/centrality/katz.pyi new file mode 100644 index 000000000000..b8b8cda7b7e5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/katz.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToFloat, Incomplete, SupportsItemAccess +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["katz_centrality", "katz_centrality_numpy"] + +@_dispatchable +def katz_centrality( + G: Graph[_Node], + alpha: float | None = 0.1, + beta: ConvertibleToFloat | Iterable[Incomplete] | None = 1.0, + max_iter: int | None = 1000, + tol: float | None = 1e-06, + nstart: SupportsItemAccess[Incomplete, Incomplete] | None = None, + normalized: bool | None = True, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def katz_centrality_numpy( + G: Graph[_Node], + alpha: float = 0.1, + beta: float | Mapping[Incomplete, Incomplete] | None = 1.0, + normalized: bool = True, + weight: str | None = None, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi b/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi new file mode 100644 index 000000000000..fa270ac3847c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/laplacian.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["laplacian_centrality"] + +@_dispatchable +def laplacian_centrality( + G: Graph[_Node], + normalized: bool = True, + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: str | None = None, + alpha: float = 0.95, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/load.pyi b/stubs/networkx/networkx/algorithms/centrality/load.pyi new file mode 100644 index 000000000000..30677a841399 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/load.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["load_centrality", "edge_load_centrality"] + +@_dispatchable +def newman_betweenness_centrality( + G: Graph[_Node], v=None, cutoff: bool | None = None, normalized: bool | None = True, weight: str | None = None +) -> float | dict[Incomplete, float]: ... + +load_centrality = newman_betweenness_centrality + +@_dispatchable +def edge_load_centrality(G: Graph[_Node], cutoff: bool | None = False) -> dict[tuple[Incomplete, Incomplete], int]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/percolation.pyi b/stubs/networkx/networkx/algorithms/centrality/percolation.pyi new file mode 100644 index 000000000000..becea462a050 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/percolation.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["percolation_centrality"] + +@_dispatchable +def percolation_centrality( + G: Graph[_Node], + attribute: str | None = "percolation", + states: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, +) -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/reaching.pyi b/stubs/networkx/networkx/algorithms/centrality/reaching.pyi new file mode 100644 index 000000000000..b491df5addf8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/reaching.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["global_reaching_centrality", "local_reaching_centrality"] + +@_dispatchable +def global_reaching_centrality(G: DiGraph[_Node], weight: str | None = None, normalized: bool | None = True) -> float: ... +@_dispatchable +def local_reaching_centrality( + G: DiGraph[_Node], + v: _Node, + paths: Mapping[Incomplete, Incomplete] | None = None, + weight: str | None = None, + normalized: bool | None = True, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/second_order.pyi b/stubs/networkx/networkx/algorithms/centrality/second_order.pyi new file mode 100644 index 000000000000..d6f64bcd4bda --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/second_order.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["second_order_centrality"] + +@_dispatchable +def second_order_centrality(G: Graph[_Node], weight: str | None = "weight") -> dict[Incomplete, float]: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi new file mode 100644 index 000000000000..c6824639b2d1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/subgraph_alg.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["subgraph_centrality_exp", "subgraph_centrality", "communicability_betweenness_centrality", "estrada_index"] + +@_dispatchable +def subgraph_centrality_exp(G: Graph[_Node], *, normalized: bool = False) -> dict[Incomplete, float]: ... +@_dispatchable +def subgraph_centrality(G: Graph[_Node], *, normalized: bool = False) -> dict[Incomplete, float]: ... +@_dispatchable +def communicability_betweenness_centrality(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def estrada_index(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/trophic.pyi b/stubs/networkx/networkx/algorithms/centrality/trophic.pyi new file mode 100644 index 000000000000..4215c89b46d1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/trophic.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["trophic_levels", "trophic_differences", "trophic_incoherence_parameter"] + +@_dispatchable +def trophic_levels(G: DiGraph[_Node], weight="weight") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def trophic_differences(G: DiGraph[_Node], weight="weight") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def trophic_incoherence_parameter(G: DiGraph[_Node], weight="weight", cannibalism: bool = False) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi b/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi new file mode 100644 index 000000000000..4dc2bb55728d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/centrality/voterank_alg.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["voterank"] + +@_dispatchable +def voterank(G: Graph[_Node], number_of_nodes: int | None = None) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/chains.pyi b/stubs/networkx/networkx/algorithms/chains.pyi new file mode 100644 index 000000000000..00c7ed63fbfe --- /dev/null +++ b/stubs/networkx/networkx/algorithms/chains.pyi @@ -0,0 +1,9 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["chain_decomposition"] + +@_dispatchable +def chain_decomposition(G: Graph[_Node], root: _Node | None = None) -> Generator[list[tuple[_Node, _Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/chordal.pyi b/stubs/networkx/networkx/algorithms/chordal.pyi new file mode 100644 index 000000000000..e7ad7d1d93d0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/chordal.pyi @@ -0,0 +1,29 @@ +import sys +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXException +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_chordal", + "find_induced_nodes", + "chordal_graph_cliques", + "chordal_graph_treewidth", + "NetworkXTreewidthBoundExceeded", + "complete_to_chordal_graph", +] + +class NetworkXTreewidthBoundExceeded(NetworkXException): ... + +@_dispatchable +def is_chordal(G: Graph[_Node]) -> bool: ... +@_dispatchable +def find_induced_nodes(G: Graph[_Node], s: _Node, t: _Node, treewidth_bound: float = sys.maxsize) -> set[_Node]: ... +@_dispatchable +def chordal_graph_cliques(G: Graph[_Node]) -> Generator[frozenset[_Node]]: ... +@_dispatchable +def chordal_graph_treewidth(G: Graph[_Node]) -> int: ... +@_dispatchable +def complete_to_chordal_graph(G: Graph[_Node]) -> tuple[Incomplete, dict[Incomplete, int]]: ... diff --git a/stubs/networkx/networkx/algorithms/clique.pyi b/stubs/networkx/networkx/algorithms/clique.pyi new file mode 100644 index 000000000000..225fc56a64e6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/clique.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Iterator +from typing import overload + +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "find_cliques", + "find_cliques_recursive", + "make_max_clique_graph", + "make_clique_bipartite", + "node_clique_number", + "number_of_cliques", + "enumerate_all_cliques", + "max_weight_clique", +] + +@_dispatchable +def enumerate_all_cliques(G: Graph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def find_cliques(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def find_cliques_recursive(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None) -> Iterator[list[_Node]]: ... +@_dispatchable +def make_max_clique_graph( + G: Graph[_Node], create_using: Graph[_Node, _NodeData, _EdgeData] | type[Graph[_Node, _NodeData, _EdgeData]] | None = None +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def make_clique_bipartite( + G: Graph[_Node, _NodeData, _EdgeData], + fpos: bool | None = None, + create_using: Graph[_Node, _NodeData, _EdgeData] | type[Graph[_Node, _NodeData, _EdgeData]] | None = None, + name=None, +) -> Graph[_Node]: ... + +@overload +def node_clique_number( + G: Graph[_Node], nodes=None, cliques: Iterable[Incomplete] | None = None, separate_nodes=False +) -> dict[_Node, int]: ... +@overload +def node_clique_number(G: Graph[_Node], nodes=None, cliques: Iterable[Incomplete] | None = None, separate_nodes=False) -> int: ... + +def number_of_cliques( + G: Graph[_Node], nodes: list[_Node] | _Node | None = None, cliques: Iterable[Incomplete] | None = None +) -> int | dict[Incomplete, Incomplete]: ... +@_dispatchable +def max_weight_clique(G: Graph[_Node], weight: str | None = "weight") -> tuple[list[Incomplete], int]: ... + +class MaxWeightClique: + G: Graph[Incomplete] + incumbent_nodes: list[Incomplete] + incumbent_weight: int + node_weights: dict[Incomplete, int] + def __init__(self, G: Graph[_Node], weight): ... + def update_incumbent_if_improved(self, C, C_weight): ... + def greedily_find_independent_set(self, P): ... + def find_branching_nodes(self, P, target): ... + def expand(self, C, C_weight, P): ... + def find_max_weight_clique(self): ... diff --git a/stubs/networkx/networkx/algorithms/cluster.pyi b/stubs/networkx/networkx/algorithms/cluster.pyi new file mode 100644 index 000000000000..ba66252cac44 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cluster.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections import Counter +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _NBunch, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "triangles", + "all_triangles", + "average_clustering", + "clustering", + "transitivity", + "square_clustering", + "generalized_degree", +] + +@_dispatchable +def triangles(G: Graph[_Node], nodes=None) -> int | dict[Incomplete, int]: ... +@_dispatchable +def all_triangles(G: Graph[_Node], nbunch: _NBunch[_Node] = None) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... +@_dispatchable +def average_clustering( + G: Graph[_Node], nodes: Iterable[_Node] | None = None, weight: str | None = None, count_zeros: bool = True +) -> float: ... +@_dispatchable +def clustering(G: Graph[_Node], nodes=None, weight: str | None = None) -> float | int | dict[Incomplete, float | int]: ... +@_dispatchable +def transitivity(G: Graph[_Node]) -> float: ... +@_dispatchable +def square_clustering(G: Graph[_Node], nodes: Iterable[_Node] | None = None) -> float | int | dict[Incomplete, float | int]: ... +@_dispatchable +def generalized_degree( + G: Graph[_Node], nodes: Iterable[_Node] | None = None +) -> Counter[Incomplete] | dict[Incomplete, Counter[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/coloring/__init__.pyi b/stubs/networkx/networkx/algorithms/coloring/__init__.pyi new file mode 100644 index 000000000000..764088306473 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.algorithms.coloring.equitable_coloring import equitable_color as equitable_color +from networkx.algorithms.coloring.greedy_coloring import * + +__all__ = ["greedy_color", "equitable_color"] diff --git a/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi b/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi new file mode 100644 index 000000000000..bae8b30ab4f1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/equitable_coloring.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Mapping +from typing import SupportsIndex + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["equitable_color"] + +@_dispatchable +def is_coloring(G: Graph[_Node], coloring: SupportsGetItem[Incomplete, Incomplete]) -> bool: ... +@_dispatchable +def is_equitable(G: Graph[_Node], coloring: Mapping[Incomplete, Incomplete], num_colors: SupportsIndex | None = None) -> bool: ... +def make_C_from_F(F): ... +def make_N_from_L_C(L, C): ... +def make_H_from_C_N(C, N): ... +def change_color(u, X, Y, N, H, F, C, L): ... +def move_witnesses(src_color, dst_color, N, H, F, C, T_cal, L): ... +@_dispatchable +def pad_graph(G: Graph[_Node], num_colors): ... +def procedure_P(V_minus, V_plus, N, H, F, C, L, excluded_colors=None): ... +@_dispatchable +def equitable_color(G: Graph[_Node], num_colors: int) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi b/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi new file mode 100644 index 000000000000..d3287b494edd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/coloring/greedy_coloring.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "greedy_color", + "strategy_connected_sequential", + "strategy_connected_sequential_bfs", + "strategy_connected_sequential_dfs", + "strategy_independent_set", + "strategy_largest_first", + "strategy_random_sequential", + "strategy_saturation_largest_first", + "strategy_smallest_last", +] + +@_dispatchable +def strategy_largest_first(G: Graph[_Node], colors: Unused): ... +@_dispatchable +def strategy_random_sequential(G: Graph[_Node], colors: Unused, seed=None): ... +@_dispatchable +def strategy_smallest_last(G: Graph[_Node], colors: Unused): ... +@_dispatchable +def strategy_independent_set(G: Graph[_Node], colors: Unused) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def strategy_connected_sequential_bfs(G: Graph[_Node], colors): ... +@_dispatchable +def strategy_connected_sequential_dfs(G: Graph[_Node], colors): ... +@_dispatchable +def strategy_connected_sequential(G: Graph[_Node], colors: Unused, traversal: str = "bfs") -> Generator[Incomplete]: ... +@_dispatchable +def strategy_saturation_largest_first(G: Graph[_Node], colors) -> Generator[Incomplete, None, Incomplete]: ... + +STRATEGIES: Final[dict[str, Callable[..., Incomplete]]] + +@_dispatchable +def greedy_color( + G: Graph[_Node], + strategy: ( + Callable[..., Incomplete] + | Literal[ + "largest_first", + "random_sequential", + "smallest_last", + "independent_set", + "connected_sequential_bfs", + "connected_sequential_dfs", + "connected_sequential", + "saturation_largest_first", + "DSATUR", + ] + ) = "largest_first", + interchange: bool = False, +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/communicability_alg.pyi b/stubs/networkx/networkx/algorithms/communicability_alg.pyi new file mode 100644 index 000000000000..b0636d34355f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/communicability_alg.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["communicability", "communicability_exp"] + +@_dispatchable +def communicability(G: Graph[_Node]) -> dict[_Node, dict[_Node, float]]: ... +@_dispatchable +def communicability_exp(G: Graph[_Node]) -> dict[_Node, dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/__init__.pyi b/stubs/networkx/networkx/algorithms/community/__init__.pyi new file mode 100644 index 000000000000..dc44dd7c344e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/__init__.pyi @@ -0,0 +1,13 @@ +from networkx.algorithms.community.asyn_fluid import * +from networkx.algorithms.community.bipartitions import * +from networkx.algorithms.community.centrality import * +from networkx.algorithms.community.community_utils import * +from networkx.algorithms.community.divisive import * +from networkx.algorithms.community.kclique import * +from networkx.algorithms.community.label_propagation import * +from networkx.algorithms.community.leiden import * +from networkx.algorithms.community.local import * +from networkx.algorithms.community.louvain import * +from networkx.algorithms.community.lukes import * +from networkx.algorithms.community.modularity_max import * +from networkx.algorithms.community.quality import * diff --git a/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi b/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi new file mode 100644 index 000000000000..2b3d11cc5a51 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/asyn_fluid.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["asyn_fluidc"] + +@_dispatchable +def asyn_fluidc(G: Graph[_Node], k: int, max_iter: int = 100, seed: int | RandomState | None = None) -> Iterator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/bipartitions.pyi b/stubs/networkx/networkx/algorithms/community/bipartitions.pyi new file mode 100644 index 000000000000..991590f7dac1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/bipartitions.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["kernighan_lin_bisection", "spectral_modularity_bipartition", "greedy_node_swap_bipartition"] + +@_dispatchable +def kernighan_lin_bisection( + G: Graph[_Node], + partition: tuple[Iterable[Incomplete], Iterable[Incomplete]] | None = None, + max_iter: int = 10, + weight: str | _WeightFunc[_Node] = "weight", + seed: int | RandomState | None = None, +) -> tuple[set[Incomplete], set[Incomplete]]: ... +def spectral_modularity_bipartition(G: Graph[_Node]) -> tuple[set[Incomplete], set[Incomplete]]: ... +def greedy_node_swap_bipartition( + G: Graph[_Node], *, init_split: tuple[set[Incomplete], set[Incomplete]] | None = None, max_iter: int = 10 +) -> tuple[set[Incomplete], set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/centrality.pyi b/stubs/networkx/networkx/algorithms/community/centrality.pyi new file mode 100644 index 000000000000..ec3b07141fe1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/centrality.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["girvan_newman"] + +@_dispatchable +def girvan_newman( + G: Graph[_Node], most_valuable_edge: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, None, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/community_utils.pyi b/stubs/networkx/networkx/algorithms/community/community_utils.pyi new file mode 100644 index 000000000000..b51294b995dd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/community_utils.pyi @@ -0,0 +1,9 @@ +from collections.abc import Container, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_partition"] + +@_dispatchable +def is_partition(G: Graph[_Node], communities: Iterable[Container[_Node]]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/community/divisive.pyi b/stubs/networkx/networkx/algorithms/community/divisive.pyi new file mode 100644 index 000000000000..a0c99adae0ef --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/divisive.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_betweenness_partition", "edge_current_flow_betweenness_partition"] + +@_dispatchable +def edge_betweenness_partition(G: Graph[_Node], number_of_sets: int, *, weight: str | None = None) -> list[Incomplete]: ... +@_dispatchable +def edge_current_flow_betweenness_partition( + G: Graph[_Node], number_of_sets: int, *, weight: str | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/kclique.pyi b/stubs/networkx/networkx/algorithms/community/kclique.pyi new file mode 100644 index 000000000000..f3fecef092a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/kclique.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_clique_communities"] + +@_dispatchable +def k_clique_communities(G: Graph[_Node], k: int, cliques: Iterable[Incomplete] | None = None) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/label_propagation.pyi b/stubs/networkx/networkx/algorithms/community/label_propagation.pyi new file mode 100644 index 000000000000..8d50d0043835 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/label_propagation.pyi @@ -0,0 +1,18 @@ +from _collections_abc import dict_values +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["label_propagation_communities", "asyn_lpa_communities", "fast_label_propagation_communities"] + +@_dispatchable +def fast_label_propagation_communities(G: Graph[_Node], *, weight=None, seed=None) -> Generator[Incomplete]: ... +@_dispatchable +def asyn_lpa_communities( + G: Graph[_Node], weight: str | None = None, seed: int | RandomState | None = None +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def label_propagation_communities(G: Graph[_Node]) -> dict_values[Incomplete, set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/leiden.pyi b/stubs/networkx/networkx/algorithms/community/leiden.pyi new file mode 100644 index 000000000000..2cf5052c1229 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/leiden.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["leiden_communities", "leiden_partitions"] + +@_dispatchable +def leiden_communities( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float = 1, + max_level: int | None = None, + seed: int | RandomState | None = None, +) -> list[Incomplete]: ... +@_dispatchable +def leiden_partitions( + G: Graph[_Node], weight: str | None = "weight", resolution: float = 1, seed: int | RandomState | None = None +): ... diff --git a/stubs/networkx/networkx/algorithms/community/local.pyi b/stubs/networkx/networkx/algorithms/community/local.pyi new file mode 100644 index 000000000000..9799724b299b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/local.pyi @@ -0,0 +1,14 @@ +from collections.abc import Callable, Hashable +from typing import Literal, TypeAlias + +from networkx.classes.graph import Graph, _Node + +__all__ = ["greedy_source_expansion"] + +_Algorithm: TypeAlias = Literal["clauset"] + +ALGORITHMS: dict[_Algorithm, Callable[[Graph[Hashable], Hashable, int | None], set[Hashable]]] + +def greedy_source_expansion( + G: Graph[_Node], *, source: _Node, cutoff: int | None = None, method: _Algorithm = "clauset" +) -> set[_Node | None]: ... diff --git a/stubs/networkx/networkx/algorithms/community/louvain.pyi b/stubs/networkx/networkx/algorithms/community/louvain.pyi new file mode 100644 index 000000000000..b4d07e965717 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/louvain.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["louvain_communities", "louvain_partitions"] + +@_dispatchable +def louvain_communities( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float | None = 1, + threshold: float | None = 1e-07, + max_level: int | None = None, + seed: int | RandomState | None = None, +) -> list[set[Incomplete]]: ... +@_dispatchable +def louvain_partitions( + G: Graph[_Node], + weight: str | None = "weight", + resolution: float | None = 1, + threshold: float | None = 1e-07, + seed: int | RandomState | None = None, +) -> Generator[list[set[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/community/lukes.pyi b/stubs/networkx/networkx/algorithms/community/lukes.pyi new file mode 100644 index 000000000000..da43a5a29eb8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/lukes.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Final + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["lukes_partitioning"] + +D_EDGE_W: Final = "weight" +D_EDGE_VALUE: Final[float] +D_NODE_W: Final = "weight" +D_NODE_VALUE: Final = 1 +PKEY: Final = "partitions" +CLUSTER_EVAL_CACHE_SIZE: Final = 2048 + +@_dispatchable +def lukes_partitioning(G: Graph[_Node], max_size: int, node_weight=None, edge_weight=None) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/modularity_max.pyi b/stubs/networkx/networkx/algorithms/community/modularity_max.pyi new file mode 100644 index 000000000000..977fe8b70630 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/modularity_max.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["greedy_modularity_communities", "naive_greedy_modularity_communities"] + +@_dispatchable +def greedy_modularity_communities( + G: Graph[_Node], weight: str | None = None, resolution: float | None = 1, cutoff: int | None = 1, best_n: int | None = None +) -> list[set[Incomplete]] | list[frozenset[Incomplete]]: ... +@_dispatchable +def naive_greedy_modularity_communities( + G: Graph[_Node], resolution: float = 1, weight: str | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/community/quality.pyi b/stubs/networkx/networkx/algorithms/community/quality.pyi new file mode 100644 index 000000000000..98aa38954f00 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/community/quality.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXError +from networkx.utils.backends import _dispatchable +from networkx.utils.decorators import argmap + +__all__ = ["modularity", "partition_quality"] + +class NotAPartition(NetworkXError): + def __init__(self, G: Graph[_Node], collection) -> None: ... + +require_partition: argmap + +@_dispatchable +def intra_community_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def inter_community_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def inter_community_non_edges(G: Graph[_Node], partition: Iterable[Incomplete]): ... +@_dispatchable +def modularity( + G: Graph[_Node], communities: Iterable[set[Incomplete]], weight: str | None = "weight", resolution: float = 1 +) -> float: ... +@_dispatchable +def partition_quality(G: Graph[_Node], partition: Iterable[Incomplete]) -> tuple[float, float]: ... diff --git a/stubs/networkx/networkx/algorithms/components/__init__.pyi b/stubs/networkx/networkx/algorithms/components/__init__.pyi new file mode 100644 index 000000000000..1aee3fd63206 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/__init__.pyi @@ -0,0 +1,6 @@ +from .attracting import * +from .biconnected import * +from .connected import * +from .semiconnected import * +from .strongly_connected import * +from .weakly_connected import * diff --git a/stubs/networkx/networkx/algorithms/components/attracting.pyi b/stubs/networkx/networkx/algorithms/components/attracting.pyi new file mode 100644 index 000000000000..b4599cb049d5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/attracting.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_attracting_components", "attracting_components", "is_attracting_component"] + +@_dispatchable +def attracting_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_attracting_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_attracting_component(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/components/biconnected.pyi b/stubs/networkx/networkx/algorithms/components/biconnected.pyi new file mode 100644 index 000000000000..f6b5e78f1401 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/biconnected.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["biconnected_components", "biconnected_component_edges", "is_biconnected", "articulation_points"] + +@_dispatchable +def is_biconnected(G: Graph[_Node]) -> bool: ... +@_dispatchable +def biconnected_component_edges(G: Graph[_Node]) -> Generator[list[tuple[_Node, _Node]]]: ... +@_dispatchable +def biconnected_components(G: Graph[_Node]) -> Generator[list[set[_Node]]]: ... +@_dispatchable +def articulation_points(G: Graph[_Node]) -> Generator[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/components/connected.pyi b/stubs/networkx/networkx/algorithms/components/connected.pyi new file mode 100644 index 000000000000..e19f09c06929 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/connected.pyi @@ -0,0 +1,15 @@ +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_connected_components", "connected_components", "is_connected", "node_connected_component"] + +@_dispatchable +def connected_components(G: Graph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_connected_components(G: Graph[_Node]) -> int: ... +@_dispatchable +def is_connected(G: Graph[_Node]) -> bool: ... +@_dispatchable +def node_connected_component(G: Graph[_Node], n: _Node) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/components/semiconnected.pyi b/stubs/networkx/networkx/algorithms/components/semiconnected.pyi new file mode 100644 index 000000000000..f83e432c4075 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/semiconnected.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_semiconnected"] + +@_dispatchable +def is_semiconnected(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi b/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi new file mode 100644 index 000000000000..bc0bb03a5970 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/strongly_connected.pyi @@ -0,0 +1,24 @@ +from collections.abc import Generator, Iterable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "number_strongly_connected_components", + "strongly_connected_components", + "is_strongly_connected", + "kosaraju_strongly_connected_components", + "condensation", +] + +@_dispatchable +def strongly_connected_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def kosaraju_strongly_connected_components(G: DiGraph[_Node], source: _Node | None = None) -> Generator[set[_Node]]: ... +@_dispatchable +def number_strongly_connected_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_strongly_connected(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def condensation(G: DiGraph[_Node], scc: Iterable[Iterable[_Node]] | None = None) -> DiGraph[int]: ... diff --git a/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi b/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi new file mode 100644 index 000000000000..ca026575a7e0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/components/weakly_connected.pyi @@ -0,0 +1,14 @@ +from collections.abc import Generator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_weakly_connected_components", "weakly_connected_components", "is_weakly_connected"] + +@_dispatchable +def weakly_connected_components(G: DiGraph[_Node]) -> Generator[set[_Node]]: ... +@_dispatchable +def number_weakly_connected_components(G: DiGraph[_Node]) -> int: ... +@_dispatchable +def is_weakly_connected(G: DiGraph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi b/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi new file mode 100644 index 000000000000..4c3ecc33e72d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/__init__.pyi @@ -0,0 +1,9 @@ +from .connectivity import * +from .cuts import * +from .disjoint_paths import * +from .edge_augmentation import * +from .edge_kcomponents import * +from .kcomponents import * +from .kcutsets import * +from .stoerwagner import * +from .utils import * diff --git a/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi b/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi new file mode 100644 index 000000000000..e38e1c82f756 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/connectivity.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Iterable + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "average_node_connectivity", + "local_node_connectivity", + "node_connectivity", + "local_edge_connectivity", + "edge_connectivity", + "all_pairs_node_connectivity", +] +default_flow_func = edmonds_karp + +@_dispatchable +def local_node_connectivity( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, + cutoff: float | None = None, +) -> float: ... +@_dispatchable +def node_connectivity( + G: Graph[_Node], + s: _Node | None = None, + t: _Node | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, +) -> float: ... +@_dispatchable +def average_node_connectivity( + G: Graph[_Node], flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None +) -> float: ... +@_dispatchable +def all_pairs_node_connectivity( + G: Graph[_Node], + nbunch: Iterable[tuple[_Node, _Node]] | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, +) -> dict[_Node, dict[_Node, float]]: ... +@_dispatchable +def local_edge_connectivity( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, + cutoff: float | None = None, +) -> float: ... +@_dispatchable +def edge_connectivity( + G: Graph[_Node], + s: _Node | None = None, + t: _Node | None = None, + flow_func: Callable[[DiGraph[_Node], _Node, _Node], DiGraph[_Node]] | None = None, + cutoff: float | None = None, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi b/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi new file mode 100644 index 000000000000..4170cc9d37cf --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/cuts.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing_extensions import Never + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["minimum_st_node_cut", "minimum_node_cut", "minimum_st_edge_cut", "minimum_edge_cut"] +default_flow_func = edmonds_karp + +@_dispatchable +def minimum_st_edge_cut( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> set[tuple[Incomplete, Incomplete]]: ... +@_dispatchable +def minimum_st_node_cut( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> dict[Never, Never] | set[Incomplete]: ... +@_dispatchable +def minimum_node_cut( + G: Graph[_Node], s: _Node | None = None, t: _Node | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> dict[Never, Never] | set[Incomplete]: ... +@_dispatchable +def minimum_edge_cut( + G: Graph[_Node], s: _Node | None = None, t: _Node | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi b/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi new file mode 100644 index 000000000000..1f9ab7fb4ef7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/disjoint_paths.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_disjoint_paths", "node_disjoint_paths"] +default_flow_func = edmonds_karp + +@_dispatchable +def edge_disjoint_paths( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + cutoff: int | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> Generator[Incomplete]: ... +@_dispatchable +def node_disjoint_paths( + G: Graph[_Node], + s: _Node, + t: _Node, + flow_func: Callable[..., Incomplete] | None = None, + cutoff: int | None = None, + auxiliary: DiGraph[_Node] | None = None, + residual: DiGraph[_Node] | None = None, +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi b/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi new file mode 100644 index 000000000000..b29620946b71 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/edge_augmentation.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Collection, Generator, Iterable +from typing import NamedTuple + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_edge_augmentation", "is_k_edge_connected", "is_locally_k_edge_connected"] + +@_dispatchable +def is_k_edge_connected(G: Graph[_Node], k: int) -> bool: ... +@_dispatchable +def is_locally_k_edge_connected(G: Graph[_Node], s: _Node, t: _Node, k: int) -> bool: ... +@_dispatchable +def k_edge_augmentation( + G: Graph[_Node], + k: int, + avail: set[tuple[int, int]] | set[tuple[int, int, float]] | SupportsGetItem[tuple[int, int], float] | None = None, + weight: str | None = None, + partial: bool = False, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def partial_k_edge_augmentation( + G: Graph[_Node], k: int, avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], weight: str | None = None +): ... +@_dispatchable +def one_edge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, + partial: bool = False, +): ... +@_dispatchable +def bridge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, +): ... + +class MetaEdge(NamedTuple): + meta_uv: Incomplete + uv: Incomplete + w: Incomplete + +@_dispatchable +def unconstrained_one_edge_augmentation(G: Graph[_Node]): ... +@_dispatchable +def weighted_one_edge_augmentation( + G: Graph[_Node], + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], + weight: str | None = None, + partial: bool = False, +): ... +@_dispatchable +def unconstrained_bridge_augmentation(G: Graph[_Node]): ... +@_dispatchable +def weighted_bridge_augmentation( + G: Graph[_Node], avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]], weight: str | None = None +): ... +@_dispatchable +def collapse(G: Graph[_Node], grouped_nodes: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def complement_edges(G: Graph[_Node]): ... +@_dispatchable +def greedy_k_edge_augmentation( + G: Graph[_Node], + k: int, + avail: dict[Incomplete, Incomplete] | Collection[tuple[Incomplete, ...]] | None = None, + weight: str | None = None, + seed=None, +): ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi b/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi new file mode 100644 index 000000000000..f35a458714dd --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/edge_kcomponents.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_edge_components", "k_edge_subgraphs", "bridge_components", "EdgeComponentAuxGraph"] + +@_dispatchable +def k_edge_components(G: Graph[_Node], k: int) -> Generator[set[Incomplete]]: ... +@_dispatchable +def k_edge_subgraphs(G: Graph[_Node], k: int) -> Generator[Incomplete, Incomplete, Incomplete]: ... +@_dispatchable +def bridge_components(G: Graph[_Node]) -> Generator[Incomplete, Incomplete]: ... + +class EdgeComponentAuxGraph: + A: Incomplete + H: Incomplete + + @classmethod + def construct(cls, G: Graph[_Node]): ... + def k_edge_components(self, k: int) -> Generator[Incomplete, Incomplete]: ... + def k_edge_subgraphs(self, k: int) -> Generator[Incomplete, Incomplete]: ... + +@_dispatchable +def general_k_edge_subgraphs(G: Graph[_Node], k: int): ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi b/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi new file mode 100644 index 000000000000..6b7c1e1a3b2a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/kcomponents.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["k_components"] +default_flow_func = edmonds_karp + +@_dispatchable +def k_components(G: Graph[_Node], flow_func: Callable[..., Incomplete] | None = None) -> dict[Incomplete, Incomplete]: ... +def build_k_number_dict(kcomps) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi b/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi new file mode 100644 index 000000000000..77b4805cdeda --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/kcutsets.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.algorithms.flow import edmonds_karp +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_node_cuts"] +default_flow_func = edmonds_karp + +@_dispatchable +def all_node_cuts( + G: Graph[_Node], k: int | None = None, flow_func: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi b/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi new file mode 100644 index 000000000000..e06ceda6d62d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/stoerwagner.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["stoer_wagner"] + +@_dispatchable +def stoer_wagner( + G: Graph[_Node], weight: str = "weight", heap: type = ... +) -> tuple[int | float, tuple[list[Incomplete], list[Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/connectivity/utils.pyi b/stubs/networkx/networkx/algorithms/connectivity/utils.pyi new file mode 100644 index 000000000000..efc380dd4a29 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/connectivity/utils.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["build_auxiliary_node_connectivity", "build_auxiliary_edge_connectivity"] + +@_dispatchable +def build_auxiliary_node_connectivity(G: Graph[_Node]): ... +@_dispatchable +def build_auxiliary_edge_connectivity(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/core.pyi b/stubs/networkx/networkx/algorithms/core.pyi new file mode 100644 index 000000000000..f32aade116df --- /dev/null +++ b/stubs/networkx/networkx/algorithms/core.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["core_number", "k_core", "k_shell", "k_crust", "k_corona", "k_truss", "onion_layers"] + +@_dispatchable +def core_number(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def k_core( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_shell( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_crust( + G: Graph[_Node], k: int | None = None, core_number: Mapping[Incomplete, Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def k_corona(G: Graph[_Node], k: int | None, core_number: Mapping[Incomplete, Incomplete] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def k_truss(G: Graph[_Node], k: int) -> Graph[Incomplete]: ... +@_dispatchable +def onion_layers(G: Graph[_Node]) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/covering.pyi b/stubs/networkx/networkx/algorithms/covering.pyi new file mode 100644 index 000000000000..e10e1967bb6f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/covering.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_edge_cover", "is_edge_cover"] + +@_dispatchable +def min_edge_cover(G: Graph[_Node], matching_algorithm: Callable[..., Incomplete] | None = None) -> set[Incomplete]: ... +@_dispatchable +def is_edge_cover(G: Graph[_Node], cover: Iterable[Iterable[Incomplete]]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/cuts.pyi b/stubs/networkx/networkx/algorithms/cuts.pyi new file mode 100644 index 000000000000..4d16d5f516ac --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cuts.pyi @@ -0,0 +1,36 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "boundary_expansion", + "conductance", + "cut_size", + "edge_expansion", + "mixing_expansion", + "node_expansion", + "normalized_cut_size", + "volume", +] + +@_dispatchable +def cut_size(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def volume(G: Graph[_Node], S: Iterable[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def normalized_cut_size( + G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None +) -> float: ... +@_dispatchable +def conductance(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def edge_expansion(G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None) -> float: ... +@_dispatchable +def mixing_expansion( + G: Graph[_Node], S: Iterable[_Node], T: Iterable[_Node] | None = None, weight: str | None = None +) -> float: ... +@_dispatchable +def node_expansion(G: Graph[_Node], S: Iterable[_Node]) -> float: ... +@_dispatchable +def boundary_expansion(G: Graph[_Node], S: Iterable[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/cycles.pyi b/stubs/networkx/networkx/algorithms/cycles.pyi new file mode 100644 index 000000000000..2890429d4516 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/cycles.pyi @@ -0,0 +1,33 @@ +from collections.abc import Generator +from typing import Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _NBunch, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "cycle_basis", + "simple_cycles", + "recursive_simple_cycles", + "find_cycle", + "minimum_cycle_basis", + "chordless_cycles", + "girth", +] + +@_dispatchable +def cycle_basis(G: Graph[_Node], root: _Node | None = None) -> list[list[_Node]]: ... +@_dispatchable +def simple_cycles(G: Graph[_Node], length_bound: int | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def chordless_cycles(G: DiGraph[_Node], length_bound: int | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def recursive_simple_cycles(G: DiGraph[_Node]) -> list[list[_Node]]: ... +@_dispatchable +def find_cycle( + G: Graph[_Node], source: _NBunch[_Node] = None, orientation: Literal["original", "reverse", "ignore"] | None = None +): ... +@_dispatchable +def minimum_cycle_basis(G: Graph[_Node], weight: str | None = None) -> list[list[_Node]]: ... +@_dispatchable +def girth(G: Graph[_Node]) -> float | int: ... # accepts any graph type diff --git a/stubs/networkx/networkx/algorithms/d_separation.pyi b/stubs/networkx/networkx/algorithms/d_separation.pyi new file mode 100644 index 000000000000..7904fb9cd3a9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/d_separation.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_d_separator", "is_minimal_d_separator", "find_minimal_d_separator"] + +@_dispatchable +def is_d_separator(G: DiGraph[_Node], x: _Node | set[_Node], y: _Node | set[_Node], z: _Node | set[_Node]) -> bool: ... +@_dispatchable +def find_minimal_d_separator( + G: DiGraph[_Node], x: set[Incomplete] | Incomplete, y: set[Incomplete] | Incomplete, *, included=None, restricted=None +) -> set[Incomplete] | None: ... +@_dispatchable +def is_minimal_d_separator( + G: DiGraph[_Node], + x: _Node | set[_Node], + y: _Node | set[_Node], + z: _Node | set[_Node], + *, + included: _Node | set[_Node] | None = None, + restricted: _Node | set[_Node] | None = None, +) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/dag.pyi b/stubs/networkx/networkx/algorithms/dag.pyi new file mode 100644 index 000000000000..62b93319e8b1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dag.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "descendants", + "ancestors", + "topological_sort", + "lexicographical_topological_sort", + "all_topological_sorts", + "topological_generations", + "is_directed_acyclic_graph", + "is_aperiodic", + "transitive_closure", + "transitive_closure_dag", + "transitive_reduction", + "antichains", + "dag_longest_path", + "dag_longest_path_length", + "dag_to_branching", +] + +@_dispatchable +def descendants(G: Graph[_Node], source) -> set[_Node]: ... +@_dispatchable +def ancestors(G: Graph[_Node], source) -> set[_Node]: ... +@_dispatchable +def is_directed_acyclic_graph(G: Graph[_Node]) -> bool: ... +@_dispatchable +def topological_generations(G: DiGraph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def topological_sort(G: DiGraph[_Node]) -> Generator[_Node]: ... +@_dispatchable +def lexicographical_topological_sort(G: DiGraph[_Node], key: Callable[..., Incomplete] | None = None) -> Generator[_Node]: ... +@_dispatchable +def all_topological_sorts(G: DiGraph[_Node]) -> Generator[list[_Node]]: ... +@_dispatchable +def is_aperiodic(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def transitive_closure( + G: Graph[_Node, _NodeData, _EdgeData], reflexive: bool | None = False +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def transitive_closure_dag( + G: DiGraph[_Node, _NodeData, _EdgeData], topo_order: Iterable[Incomplete] | None = None +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def transitive_reduction(G: DiGraph[_Node, _NodeData, _EdgeData]) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def antichains(G: DiGraph[_Node], topo_order: Iterable[Incomplete] | None = None) -> Generator[list[_Node]]: ... +@_dispatchable +def dag_longest_path( + G: DiGraph[_Node], + weight: str | None = "weight", + default_weight: int | None = 1, + topo_order: Iterable[Incomplete] | None = None, +) -> list[_Node]: ... +@_dispatchable +def dag_longest_path_length(G: DiGraph[_Node], weight: str | None = "weight", default_weight: int | None = 1) -> int: ... +@_dispatchable +def dag_to_branching(G: DiGraph[_Node, _NodeData, _EdgeData]) -> DiGraph[_Node, _NodeData, _EdgeData]: ... diff --git a/stubs/networkx/networkx/algorithms/distance_measures.pyi b/stubs/networkx/networkx/algorithms/distance_measures.pyi new file mode 100644 index 000000000000..8b109a2b9f5b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/distance_measures.pyi @@ -0,0 +1,63 @@ +from collections.abc import Callable, Mapping +from typing import TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_WeightFunction: TypeAlias = Callable[..., int] + +__all__ = [ + "eccentricity", + "diameter", + "harmonic_diameter", + "radius", + "periphery", + "center", + "barycenter", + "resistance_distance", + "kemeny_constant", + "effective_graph_resistance", +] + +@_dispatchable +def eccentricity( + G: Graph[_Node], + v: _Node | None = None, + sp: Mapping[_Node, Mapping[_Node, int]] | None = None, + weight: str | _WeightFunction | None = None, +) -> int | dict[_Node, int]: ... # TODO: overload on v: dict if v is None else int +@_dispatchable +def diameter( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> int: ... +@_dispatchable +def harmonic_diameter( + G: Graph[_Node], sp: Mapping[_Node, Mapping[_Node, int]] | None = None, *, weight: str | _WeightFunction | None = None +) -> float: ... +@_dispatchable +def periphery( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> list[_Node]: ... +@_dispatchable +def radius( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> int: ... +@_dispatchable +def center( + G: Graph[_Node], e: Mapping[_Node, int] | None = None, usebounds: bool = False, weight: str | _WeightFunction | None = None +) -> list[_Node]: ... +@_dispatchable +def barycenter( + G: Graph[_Node], + weight: str | _WeightFunction | None = None, + attr: str | None = None, + sp: Mapping[_Node, Mapping[_Node, int]] | None = None, +) -> list[_Node]: ... +@_dispatchable +def resistance_distance( + G: Graph[_Node], nodeA: _Node | None = None, nodeB: _Node | None = None, weight: str | None = None, invert_weight: bool = True +) -> float | dict[_Node, float]: ... # TODO: overload on the nodes: float if both are specified else dict +@_dispatchable +def effective_graph_resistance(G: Graph[_Node], weight: str | None = None, invert_weight: bool = True) -> float: ... +@_dispatchable +def kemeny_constant(G: Graph[_Node], *, weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/distance_regular.pyi b/stubs/networkx/networkx/algorithms/distance_regular.pyi new file mode 100644 index 000000000000..0735afbc4ef3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/distance_regular.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_distance_regular", "is_strongly_regular", "intersection_array", "global_parameters"] + +@_dispatchable +def is_distance_regular(G: Graph[_Node]) -> bool: ... +@_dispatchable +def global_parameters(b: list[Incomplete], c: list[Incomplete]) -> Generator[tuple[Incomplete, Incomplete, Incomplete]]: ... +@_dispatchable +def intersection_array(G: Graph[_Node]) -> tuple[list[Incomplete], list[Incomplete]]: ... +@_dispatchable +def is_strongly_regular(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/dominance.pyi b/stubs/networkx/networkx/algorithms/dominance.pyi new file mode 100644 index 000000000000..acc979d8d9ab --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dominance.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["immediate_dominators", "dominance_frontiers"] + +@_dispatchable +def immediate_dominators(G: Graph[_Node], start: _Node) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def dominance_frontiers(G: Graph[_Node], start: _Node) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/dominating.pyi b/stubs/networkx/networkx/algorithms/dominating.pyi new file mode 100644 index 000000000000..6a3eb9a4fa2e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/dominating.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dominating_set", "is_dominating_set", "connected_dominating_set", "is_connected_dominating_set"] + +@_dispatchable +def dominating_set(G: Graph[_Node], start_with: _Node | None = None) -> set[_Node]: ... +@_dispatchable +def is_dominating_set(G: Graph[_Node], nbunch: Iterable[_Node]) -> bool: ... +@_dispatchable +def connected_dominating_set(G: Graph[_Node]) -> set[_Node]: ... +@_dispatchable +def is_connected_dominating_set(G: Graph[_Node], nbunch: Iterable[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/efficiency_measures.pyi b/stubs/networkx/networkx/algorithms/efficiency_measures.pyi new file mode 100644 index 000000000000..43a2f8d307ca --- /dev/null +++ b/stubs/networkx/networkx/algorithms/efficiency_measures.pyi @@ -0,0 +1,11 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["efficiency", "local_efficiency", "global_efficiency"] + +@_dispatchable +def efficiency(G: Graph[_Node], u: _Node, v: _Node) -> float: ... +@_dispatchable +def global_efficiency(G: Graph[_Node]) -> float: ... +@_dispatchable +def local_efficiency(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/euler.pyi b/stubs/networkx/networkx/algorithms/euler.pyi new file mode 100644 index 000000000000..eaffb70723d6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/euler.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["is_eulerian", "eulerian_circuit", "eulerize", "is_semieulerian", "has_eulerian_path", "eulerian_path"] + +@_dispatchable +def is_eulerian(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_semieulerian(G: Graph[_Node]) -> bool: ... +@_dispatchable +def eulerian_circuit(G: Graph[_Node], source: _Node | None = None, keys: bool = False) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def has_eulerian_path(G: Graph[_Node], source: _Node | None = None) -> bool: ... +@_dispatchable +def eulerian_path(G: Graph[_Node], source=None, keys: bool = False) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def eulerize(G: Graph[_Node]) -> MultiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/__init__.pyi b/stubs/networkx/networkx/algorithms/flow/__init__.pyi new file mode 100644 index 000000000000..a5ac3895e457 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/__init__.pyi @@ -0,0 +1,11 @@ +from .boykovkolmogorov import * +from .capacityscaling import * +from .dinitz_alg import * +from .edmondskarp import * +from .gomory_hu import * +from .maxflow import * +from .mincost import * +from .networksimplex import * +from .preflowpush import * +from .shortestaugmentingpath import * +from .utils import build_flow_dict as build_flow_dict, build_residual_network as build_residual_network diff --git a/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi b/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi new file mode 100644 index 000000000000..767af34353d8 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/boykovkolmogorov.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["boykov_kolmogorov"] + +@_dispatchable +def boykov_kolmogorov( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi b/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi new file mode 100644 index 000000000000..08303e681bd2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/capacityscaling.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["capacity_scaling"] + +@_dispatchable +def capacity_scaling( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight", heap: type = ... +) -> tuple[int, dict[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi b/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi new file mode 100644 index 000000000000..9b866da0d367 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/dinitz_alg.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dinitz"] + +@_dispatchable +def dinitz( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi b/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi new file mode 100644 index 000000000000..e43617b2dc61 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/edmondskarp.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edmonds_karp"] + +@_dispatchable +def edmonds_karp( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi b/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi new file mode 100644 index 000000000000..08c65356dea4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/gomory_hu.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +from .edmondskarp import edmonds_karp + +__all__ = ["gomory_hu_tree"] +default_flow_func = edmonds_karp + +@_dispatchable +def gomory_hu_tree( + G: Graph[_Node], capacity: str = "capacity", flow_func: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/maxflow.pyi b/stubs/networkx/networkx/algorithms/flow/maxflow.pyi new file mode 100644 index 000000000000..65ec771c6e55 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/maxflow.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +from .preflowpush import preflow_push + +__all__ = ["maximum_flow", "maximum_flow_value", "minimum_cut", "minimum_cut_value"] +default_flow_func = preflow_push + +@_dispatchable +def maximum_flow( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> tuple[int | float, dict[Incomplete, Incomplete]]: ... +@_dispatchable +def maximum_flow_value( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> int | float: ... +@_dispatchable +def minimum_cut( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> tuple[int | float, tuple[set[Incomplete], set[Incomplete]]]: ... +@_dispatchable +def minimum_cut_value( + flowG: Graph[_Node], + _s: _Node, + _t: _Node, + capacity: str = "capacity", + flow_func: Callable[..., Incomplete] | None = None, + **kwargs, +) -> int | float: ... diff --git a/stubs/networkx/networkx/algorithms/flow/mincost.pyi b/stubs/networkx/networkx/algorithms/flow/mincost.pyi new file mode 100644 index 000000000000..7ca50162d01a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/mincost.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete, SupportsGetItem + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["min_cost_flow_cost", "min_cost_flow", "cost_of_flow", "max_flow_min_cost"] + +@_dispatchable +def min_cost_flow_cost( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> int | float: ... +@_dispatchable +def min_cost_flow( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> dict[Incomplete, dict[Incomplete, Incomplete]]: ... +@_dispatchable +def cost_of_flow(G: Graph[_Node], flowDict: SupportsGetItem[Incomplete, Incomplete], weight: str = "weight") -> int | float: ... +@_dispatchable +def max_flow_min_cost( + G: Graph[_Node], s: str, t: str, capacity: str = "capacity", weight: str = "weight" +) -> dict[Incomplete, dict[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi b/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi new file mode 100644 index 000000000000..c9a60b87455d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/networksimplex.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["network_simplex"] + +class _DataEssentialsAndFunctions: + node_list: Incomplete + node_indices: Incomplete + node_demands: Incomplete + edge_sources: Incomplete + edge_targets: Incomplete + edge_keys: Incomplete + edge_indices: Incomplete + edge_capacities: Incomplete + edge_weights: Incomplete + edge_count: Incomplete + edge_flow: Incomplete + node_potentials: Incomplete + parent: Incomplete + parent_edge: Incomplete + subtree_size: Incomplete + next_node_dft: Incomplete + prev_node_dft: Incomplete + last_descendent_dft: Incomplete + + def __init__( + self, G: Graph[_Node], multigraph, demand: str = "demand", capacity: str = "capacity", weight: str = "weight" + ) -> None: ... + def initialize_spanning_tree(self, n, faux_inf) -> None: ... + def find_apex(self, p, q): ... + def trace_path(self, p, w): ... + def find_cycle(self, i, p, q): ... + def augment_flow(self, Wn, We, f) -> None: ... + def trace_subtree(self, p) -> Generator[Incomplete]: ... + def remove_edge(self, s, t) -> None: ... + def make_root(self, q) -> None: ... + def add_edge(self, i, p, q) -> None: ... + def update_potentials(self, i, p, q) -> None: ... + def reduced_cost(self, i): ... + def find_entering_edges(self) -> Generator[Incomplete]: ... + def residual_capacity(self, i, p): ... + def find_leaving_edge(self, Wn, We): ... + +@_dispatchable +def network_simplex( + G: Graph[_Node], demand: str = "demand", capacity: str = "capacity", weight: str = "weight" +) -> tuple[int | Incomplete, dict[Incomplete, dict[Incomplete, Incomplete]]]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi b/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi new file mode 100644 index 000000000000..d31bbb22ac4e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/preflowpush.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["preflow_push"] + +@_dispatchable +def preflow_push( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + global_relabel_freq: float = 1, + value_only: bool = False, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi b/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi new file mode 100644 index 000000000000..62ec86a862c3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/shortestaugmentingpath.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["shortest_augmenting_path"] + +@_dispatchable +def shortest_augmenting_path( + G: Graph[_Node], + s: _Node, + t: _Node, + capacity: str = "capacity", + residual: Graph[_Node] | None = None, + value_only: bool = False, + two_phase: bool = False, + cutoff: float | None = None, +) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/flow/utils.pyi b/stubs/networkx/networkx/algorithms/flow/utils.pyi new file mode 100644 index 000000000000..5bc9995b51c9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/flow/utils.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import overload +from typing_extensions import Never, deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["CurrentEdge", "Level", "GlobalRelabelThreshold", "build_residual_network", "detect_unboundedness", "build_flow_dict"] + +class CurrentEdge: + __slots__ = ("_edges", "_it", "_curr") + def __init__(self, edges) -> None: ... + def get(self): ... + def move_to_next(self) -> None: ... + +class Level: + __slots__ = ("active", "inactive") + active: Incomplete + inactive: Incomplete + + def __init__(self) -> None: ... + +class GlobalRelabelThreshold: + def __init__(self, n, m, freq) -> None: ... + def add_work(self, work) -> None: ... + def is_reached(self) -> bool: ... + def clear_work(self) -> None: ... + +@overload +@deprecated("MultiGraph and MultiDiGraph not supported (yet).") +def build_residual_network(G: MultiGraph[_Node], capacity, *, backend: str | None = None, **backend_kwargs) -> Never: ... +@overload +def build_residual_network(G: Graph[_Node], capacity, *, backend: str | None = None, **backend_kwargs): ... + +@_dispatchable +def detect_unboundedness(R, s, t) -> None: ... +@_dispatchable +def build_flow_dict(G: Graph[_Node], R): ... diff --git a/stubs/networkx/networkx/algorithms/graph_hashing.pyi b/stubs/networkx/networkx/algorithms/graph_hashing.pyi new file mode 100644 index 000000000000..9829cc627f79 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/graph_hashing.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["weisfeiler_lehman_graph_hash", "weisfeiler_lehman_subgraph_hashes"] + +@_dispatchable +def weisfeiler_lehman_graph_hash( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, + iterations: int | None = 3, + digest_size: int | None = 16, +) -> str: ... +@_dispatchable +def weisfeiler_lehman_subgraph_hashes( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, + iterations: int | None = 3, + digest_size: int | None = 16, + include_initial_labels: bool | None = False, +) -> dict[Incomplete, list[str]]: ... diff --git a/stubs/networkx/networkx/algorithms/graphical.pyi b/stubs/networkx/networkx/algorithms/graphical.pyi new file mode 100644 index 000000000000..95054c768cbc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/graphical.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_graphical", + "is_multigraphical", + "is_pseudographical", + "is_digraphical", + "is_valid_degree_sequence_erdos_gallai", + "is_valid_degree_sequence_havel_hakimi", +] + +@_dispatchable +def is_graphical(sequence: Iterable[Incomplete], method: Literal["eg", "hh"] = "eg") -> bool: ... +@_dispatchable +def is_valid_degree_sequence_havel_hakimi(deg_sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_valid_degree_sequence_erdos_gallai(deg_sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_multigraphical(sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_pseudographical(sequence: Iterable[Incomplete]) -> bool: ... +@_dispatchable +def is_digraphical(in_sequence: Iterable[Incomplete], out_sequence: Iterable[Incomplete]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/hierarchy.pyi b/stubs/networkx/networkx/algorithms/hierarchy.pyi new file mode 100644 index 000000000000..283d8db11f5d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/hierarchy.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["flow_hierarchy"] + +@_dispatchable +def flow_hierarchy(G: DiGraph[_Node], weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/hybrid.pyi b/stubs/networkx/networkx/algorithms/hybrid.pyi new file mode 100644 index 000000000000..2e6aff5d823a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/hybrid.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["kl_connected_subgraph", "is_kl_connected"] + +@_dispatchable +def kl_connected_subgraph( + G: Graph[_Node], k: int, l: int, low_memory: bool = False, same_as_graph: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def is_kl_connected(G: Graph[_Node], k: int, l: int, low_memory: bool = False) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/isolate.pyi b/stubs/networkx/networkx/algorithms/isolate.pyi new file mode 100644 index 000000000000..8c0c8bfe0315 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isolate.pyi @@ -0,0 +1,14 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_isolate", "isolates", "number_of_isolates"] + +@_dispatchable +def is_isolate(G: Graph[_Node], n: _Node) -> bool: ... +@_dispatchable +def isolates(G: Graph[_Node]) -> Iterator[Incomplete]: ... +@_dispatchable +def number_of_isolates(G: Graph[_Node]) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi b/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi new file mode 100644 index 000000000000..878c13eed27c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/__init__.pyi @@ -0,0 +1,7 @@ +from networkx.algorithms.isomorphism.ismags import * +from networkx.algorithms.isomorphism.isomorph import * +from networkx.algorithms.isomorphism.matchhelpers import * +from networkx.algorithms.isomorphism.temporalisomorphvf2 import * +from networkx.algorithms.isomorphism.tree_isomorphism import * +from networkx.algorithms.isomorphism.vf2pp import * +from networkx.algorithms.isomorphism.vf2userfunc import * diff --git a/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi b/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi new file mode 100644 index 000000000000..2f7db7c1ec00 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/ismags.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Hashable, Iterable +from typing import Any + +__all__ = ["ISMAGS"] + +def are_all_equal(iterable: Iterable[Any]) -> bool: ... +def make_partition( + items: Iterable[Hashable], test: Callable[[Hashable, Hashable], bool], check: bool = True +) -> list[set[Incomplete]]: ... +def node_to_part_ID_dict(partition: Iterable[Iterable[Incomplete]]) -> dict[Incomplete, int]: ... +def color_degree_by_node(G, n_colors, e_colors): ... + +class EdgeLookup: + edge_dict: Incomplete + def __init__(self, edge_dict) -> None: ... + def __getitem__(self, edge): ... + def items(self): ... + +class ISMAGS: + graph: Incomplete + subgraph: Incomplete + + def __init__(self, graph, subgraph, node_match=None, edge_match=None, cache=None) -> None: ... + def create_aligned_partitions(self, thing_matcher, sg_things, g_things): ... + def find_isomorphisms(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete, Incomplete]: ... + def largest_common_subgraph(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete]: ... + def analyze_subgraph_symmetry(self) -> dict[Hashable, set[Hashable]]: ... + def is_isomorphic(self, symmetry: bool = False) -> bool: ... + def subgraph_is_isomorphic(self, symmetry: bool = False) -> bool: ... + def isomorphisms_iter(self, symmetry: bool = True) -> Generator[Incomplete, Incomplete]: ... + def subgraph_isomorphisms_iter(self, symmetry: bool = True): ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi b/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi new file mode 100644 index 000000000000..ebfbdf83d147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/isomorph.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["could_be_isomorphic", "fast_could_be_isomorphic", "faster_could_be_isomorphic", "is_isomorphic"] + +@_dispatchable +def could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node], *, properties: str = "dtc") -> bool: ... +@deprecated("`graph_could_be_isomorphic` is a deprecated alias for `could_be_isomorphic`. Use `could_be_isomorphic` instead.") +def graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def fast_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@deprecated( + "`fast_graph_could_be_isomorphic` is a deprecated alias for `fast_could_be_isomorphic`. " + "Use `fast_could_be_isomorphic` instead." +) +def fast_graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def faster_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@deprecated( + "`faster_graph_could_be_isomorphic` is a deprecated alias for `faster_could_be_isomorphic`. " + "Use `faster_could_be_isomorphic` instead." +) +def faster_graph_could_be_isomorphic(G1: Graph[_Node], G2: Graph[_Node]) -> bool: ... +@_dispatchable +def is_isomorphic( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, +) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi b/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi new file mode 100644 index 000000000000..734025b38f5e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/isomorphvf2.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +__all__ = ["GraphMatcher", "DiGraphMatcher"] + +class GraphMatcher: + G1: Incomplete + G2: Incomplete + G1_nodes: Incomplete + G2_nodes: Incomplete + G2_node_order: Incomplete + old_recursion_limit: Incomplete + test: str + + def __init__(self, G1, G2) -> None: ... + def reset_recursion_limit(self) -> None: ... + def candidate_pairs_iter(self) -> Generator[Incomplete]: ... + core_1: Incomplete + core_2: Incomplete + inout_1: Incomplete + inout_2: Incomplete + state: Incomplete + mapping: Incomplete + + def initialize(self) -> None: ... + def is_isomorphic(self) -> bool: ... + def isomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def match(self) -> Generator[Incomplete, Incomplete]: ... + def semantic_feasibility(self, G1_node, G2_node): ... + def subgraph_is_isomorphic(self): ... + def subgraph_is_monomorphic(self): ... + def subgraph_isomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def subgraph_monomorphisms_iter(self) -> Generator[Incomplete, Incomplete]: ... + def syntactic_feasibility(self, G1_node, G2_node): ... + +class DiGraphMatcher(GraphMatcher): + def __init__(self, G1, G2) -> None: ... + def candidate_pairs_iter(self) -> Generator[Incomplete]: ... + core_1: Incomplete + core_2: Incomplete + in_1: Incomplete + in_2: Incomplete + out_1: Incomplete + out_2: Incomplete + state: Incomplete + mapping: Incomplete + + def initialize(self) -> None: ... + def syntactic_feasibility(self, G1_node, G2_node): ... + +class GMState: + GM: Incomplete + G1_node: Incomplete + G2_node: Incomplete + depth: Incomplete + + def __init__(self, GM, G1_node=None, G2_node=None) -> None: ... + def restore(self) -> None: ... + +class DiGMState: + GM: Incomplete + G1_node: Incomplete + G2_node: Incomplete + depth: Incomplete + + def __init__(self, GM, G1_node=None, G2_node=None) -> None: ... + def restore(self) -> None: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi b/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi new file mode 100644 index 000000000000..382cacbd7ec7 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/matchhelpers.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence +from types import FunctionType + +from networkx.utils.backends import _dispatchable + +__all__ = [ + "categorical_node_match", + "categorical_edge_match", + "categorical_multiedge_match", + "numerical_node_match", + "numerical_edge_match", + "numerical_multiedge_match", + "generic_node_match", + "generic_edge_match", + "generic_multiedge_match", +] + +def copyfunc(f, name=None) -> FunctionType: ... +def allclose(x, y, rtol: float = 1.0000000000000001e-05, atol: float = 1e-08) -> bool: ... +@_dispatchable +def categorical_node_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete] +) -> Callable[..., Incomplete]: ... + +categorical_edge_match: Incomplete + +@_dispatchable +def categorical_multiedge_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete] +) -> Callable[..., Incomplete]: ... +@_dispatchable +def numerical_node_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete], rtol: float = 1e-05, atol: float = 1e-08 +) -> Callable[..., Incomplete]: ... + +numerical_edge_match: Incomplete + +@_dispatchable +def numerical_multiedge_match( + attr: str | Iterable[Incomplete], default: Incomplete | Iterable[Incomplete], rtol: float = 1e-05, atol: float = 1e-08 +) -> Callable[..., Incomplete]: ... +@_dispatchable +def generic_node_match( + attr: str | Iterable[Incomplete], + default: Incomplete | Iterable[Incomplete], + op: Callable[..., Incomplete] | Sequence[Incomplete], +) -> Callable[..., Incomplete]: ... + +generic_edge_match: Incomplete + +@_dispatchable +def generic_multiedge_match( + attr: str | Iterable[Incomplete], + default: Incomplete | Iterable[Incomplete], + op: Callable[..., Incomplete] | Sequence[Incomplete], +) -> Callable[..., Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi b/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi new file mode 100644 index 000000000000..7ab32a2abcb9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/temporalisomorphvf2.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from .isomorphvf2 import DiGraphMatcher, GraphMatcher + +__all__ = ["TimeRespectingGraphMatcher", "TimeRespectingDiGraphMatcher"] + +class TimeRespectingGraphMatcher(GraphMatcher): + temporal_attribute_name: Incomplete + delta: Incomplete + + def __init__(self, G1, G2, temporal_attribute_name, delta) -> None: ... + def one_hop(self, Gx, Gx_node, neighbors): ... + def two_hop(self, Gx, core_x, Gx_node, neighbors): ... + def semantic_feasibility(self, G1_node, G2_node): ... + +class TimeRespectingDiGraphMatcher(DiGraphMatcher): + temporal_attribute_name: Incomplete + delta: Incomplete + + def __init__(self, G1, G2, temporal_attribute_name, delta) -> None: ... + def get_pred_dates(self, Gx, Gx_node, core_x, pred): ... + def get_succ_dates(self, Gx, Gx_node, core_x, succ): ... + def one_hop(self, Gx, Gx_node, core_x, pred, succ): ... + def two_hop_pred(self, Gx, Gx_node, core_x, pred): ... + def two_hop_succ(self, Gx, Gx_node, core_x, succ): ... + def preds(self, Gx, core_x, v, Gx_node=None): ... + def succs(self, Gx, core_x, v, Gx_node=None): ... + def test_one(self, pred_dates, succ_dates): ... + def test_two(self, pred_dates, succ_dates): ... + def semantic_feasibility(self, G1_node, G2_node): ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi b/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi new file mode 100644 index 000000000000..1b3d07cd6e14 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/tree_isomorphism.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["rooted_tree_isomorphism", "tree_isomorphism"] + +@_dispatchable +def root_trees(t1, root1, t2, root2): ... +@_dispatchable +def rooted_tree_isomorphism( + t1: Graph[Incomplete], root1, t2: Graph[Incomplete], root2 +) -> list[tuple[Incomplete, Incomplete]]: ... +@_dispatchable +def tree_isomorphism(t1: Graph[_Node], t2: Graph[_Node]) -> list[tuple[Incomplete, Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi b/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi new file mode 100644 index 000000000000..f5cbbc1516b2 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/vf2pp.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import NamedTuple + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["vf2pp_isomorphism", "vf2pp_is_isomorphic", "vf2pp_all_isomorphisms"] + +class _GraphParameters(NamedTuple): + G1: Incomplete + G2: Incomplete + G1_labels: Incomplete + G2_labels: Incomplete + nodes_of_G1Labels: Incomplete + nodes_of_G2Labels: Incomplete + G2_nodes_of_degree: Incomplete + +class _StateParameters(NamedTuple): + mapping: Incomplete + reverse_mapping: Incomplete + T1: Incomplete + T1_in: Incomplete + T1_tilde: Incomplete + T1_tilde_in: Incomplete + T2: Incomplete + T2_in: Incomplete + T2_tilde: Incomplete + T2_tilde_in: Incomplete + +@_dispatchable +def vf2pp_isomorphism( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> dict[Incomplete, Incomplete] | None: ... +@_dispatchable +def vf2pp_is_isomorphic( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> bool: ... +@_dispatchable +def vf2pp_all_isomorphisms( + G1: Graph[_Node], G2: Graph[_Node], node_label: str | None = None, default_label: float | None = None +) -> Generator[Incomplete, None, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi b/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi new file mode 100644 index 000000000000..475020aa5b05 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/isomorphism/vf2userfunc.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +from . import isomorphvf2 as vf2 + +__all__ = ["GraphMatcher", "DiGraphMatcher", "MultiGraphMatcher", "MultiDiGraphMatcher"] + +class GraphMatcher(vf2.GraphMatcher): + node_match: Incomplete + edge_match: Incomplete + G1_adj: Incomplete + G2_adj: Incomplete + + def __init__(self, G1, G2, node_match=None, edge_match=None) -> None: ... + semantic_feasibility: Incomplete + +class DiGraphMatcher(vf2.DiGraphMatcher): + node_match: Incomplete + edge_match: Incomplete + G1_adj: Incomplete + G2_adj: Incomplete + + def __init__(self, G1, G2, node_match=None, edge_match=None) -> None: ... + def semantic_feasibility(self, G1_node, G2_node): ... + +class MultiGraphMatcher(GraphMatcher): ... +class MultiDiGraphMatcher(DiGraphMatcher): ... diff --git a/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi b/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi new file mode 100644 index 000000000000..6009f0008147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/__init__.pyi @@ -0,0 +1,2 @@ +from networkx.algorithms.link_analysis.hits_alg import * +from networkx.algorithms.link_analysis.pagerank_alg import * diff --git a/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi b/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi new file mode 100644 index 000000000000..f0def237e02f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/hits_alg.pyi @@ -0,0 +1,15 @@ +from collections.abc import Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["hits"] + +@_dispatchable +def hits( + G: Graph[_Node], + max_iter: int | None = 100, + tol: float | None = 1e-08, + nstart: Mapping[_Node, float] | None = None, + normalized: bool = True, +) -> tuple[dict[_Node, float], dict[_Node, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi b/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi new file mode 100644 index 000000000000..13fff963097e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_analysis/pagerank_alg.pyi @@ -0,0 +1,29 @@ +from collections.abc import Collection, Mapping + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["pagerank", "google_matrix"] + +@_dispatchable +def pagerank( + G: Graph[_Node], + alpha: float | None = 0.85, + personalization: Mapping[_Node, float] | None = None, + max_iter: int | None = 100, + tol: float | None = 1e-06, + nstart: Mapping[_Node, float] | None = None, + weight: str | None = "weight", + dangling: Mapping[_Node, float] | None = None, +) -> dict[_Node, float]: ... +@_dispatchable +def google_matrix( + G: Graph[_Node], + alpha: float = 0.85, + personalization: Mapping[_Node, float] | None = None, + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + dangling: Mapping[_Node, float] | None = None, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/algorithms/link_prediction.pyi b/stubs/networkx/networkx/algorithms/link_prediction.pyi new file mode 100644 index 000000000000..1a14f6609bb6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/link_prediction.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "resource_allocation_index", + "jaccard_coefficient", + "adamic_adar_index", + "preferential_attachment", + "cn_soundarajan_hopcroft", + "ra_index_soundarajan_hopcroft", + "within_inter_cluster", + "common_neighbor_centrality", +] + +@_dispatchable +def resource_allocation_index(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def jaccard_coefficient(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def adamic_adar_index(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def common_neighbor_centrality( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, alpha=0.8 +) -> Iterator[Incomplete]: ... +@_dispatchable +def preferential_attachment(G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None) -> Iterator[Incomplete]: ... +@_dispatchable +def cn_soundarajan_hopcroft( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, community: str | None = "community" +) -> Iterator[Incomplete]: ... +@_dispatchable +def ra_index_soundarajan_hopcroft( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, community: str | None = "community" +) -> Iterator[Incomplete]: ... +@_dispatchable +def within_inter_cluster( + G: Graph[_Node], ebunch: Iterable[Incomplete] | None = None, delta: float | None = 0.001, community: str | None = "community" +) -> Iterator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi b/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi new file mode 100644 index 000000000000..ce589b95035d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/lowest_common_ancestors.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Iterator + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_pairs_lowest_common_ancestor", "tree_all_pairs_lowest_common_ancestor", "lowest_common_ancestor"] + +@_dispatchable +def all_pairs_lowest_common_ancestor(G: DiGraph[_Node], pairs: Iterable[Incomplete] | None = None): ... +@_dispatchable +def lowest_common_ancestor(G: DiGraph[_Node], node1, node2, default=None): ... +@_dispatchable +def tree_all_pairs_lowest_common_ancestor( + G: DiGraph[_Node], root: _Node | None = None, pairs: Iterator[Incomplete] | None = None +) -> Generator[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/matching.pyi b/stubs/networkx/networkx/algorithms/matching.pyi new file mode 100644 index 000000000000..e55e966ed3ca --- /dev/null +++ b/stubs/networkx/networkx/algorithms/matching.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "is_matching", + "is_maximal_matching", + "is_perfect_matching", + "max_weight_matching", + "min_weight_matching", + "maximal_matching", +] + +@_dispatchable +def maximal_matching(G: Graph[_Node]) -> set[Incomplete]: ... +def matching_dict_to_set(matching: Mapping[Incomplete, Incomplete]) -> set[Incomplete]: ... +@_dispatchable +def is_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def is_maximal_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def is_perfect_matching(G: Graph[_Node], matching: dict[Incomplete, Incomplete] | Iterable[Iterable[Incomplete]]) -> bool: ... +@_dispatchable +def min_weight_matching(G: Graph[_Node], weight: str | None = "weight") -> set[Incomplete]: ... +@_dispatchable +def max_weight_matching( + G: Graph[_Node], maxcardinality: bool | None = False, weight: str | None = "weight" +) -> set[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/minors/__init__.pyi b/stubs/networkx/networkx/algorithms/minors/__init__.pyi new file mode 100644 index 000000000000..746914c0bcec --- /dev/null +++ b/stubs/networkx/networkx/algorithms/minors/__init__.pyi @@ -0,0 +1,9 @@ +from networkx.algorithms.minors.contraction import ( + contracted_edge as contracted_edge, + contracted_nodes as contracted_nodes, + equivalence_classes as equivalence_classes, + identified_nodes as identified_nodes, + quotient_graph as quotient_graph, +) + +__all__ = ["contracted_edge", "contracted_nodes", "equivalence_classes", "identified_nodes", "quotient_graph"] diff --git a/stubs/networkx/networkx/algorithms/minors/contraction.pyi b/stubs/networkx/networkx/algorithms/minors/contraction.pyi new file mode 100644 index 000000000000..eb6df5761260 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/minors/contraction.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["contracted_edge", "contracted_nodes", "equivalence_classes", "identified_nodes", "quotient_graph"] + +@_dispatchable +def equivalence_classes(iterable: Iterable[_Node], relation: Callable[[_Node, _Node], bool]) -> set[frozenset[_Node]]: ... +@_dispatchable +def quotient_graph( + G: Graph[_Node], + partition: Callable[..., Incomplete] | dict[Incomplete, Incomplete] | list[set[Incomplete]], + edge_relation: Callable[..., Incomplete] | None = None, + node_data: Callable[..., Incomplete] | None = None, + edge_data: Callable[..., Incomplete] | None = None, + weight: str | None = "weight", + relabel: bool = False, + create_using: Graph[_Node] | type[Graph[_Node]] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def contracted_nodes( + G: Graph[_Node], u, v, self_loops: bool = True, copy: bool = True, *, store_contraction_as: str | None = "contraction" +) -> Graph[Incomplete]: ... + +identified_nodes = contracted_nodes + +@_dispatchable +def contracted_edge( + G: Graph[_Node], + edge: tuple[Incomplete], + self_loops: bool = True, + copy: bool = True, + *, + store_contraction_as: str | None = "contraction", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/mis.pyi b/stubs/networkx/networkx/algorithms/mis.pyi new file mode 100644 index 000000000000..b0b6a9914384 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/mis.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["maximal_independent_set"] + +@_dispatchable +def maximal_independent_set( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, seed: int | RandomState | None = None +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/moral.pyi b/stubs/networkx/networkx/algorithms/moral.pyi new file mode 100644 index 000000000000..60b07f0e3b4b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/moral.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["moral_graph"] + +@_dispatchable +def moral_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/node_classification.pyi b/stubs/networkx/networkx/algorithms/node_classification.pyi new file mode 100644 index 000000000000..d613a26ded63 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/node_classification.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["harmonic_function", "local_and_global_consistency"] + +@_dispatchable +def harmonic_function(G: Graph[_Node], max_iter: int = 30, label_name: str = "label") -> list[Incomplete]: ... +@_dispatchable +def local_and_global_consistency( + G: Graph[_Node], alpha: float = 0.99, max_iter: int = 30, label_name: str = "label" +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/non_randomness.pyi b/stubs/networkx/networkx/algorithms/non_randomness.pyi new file mode 100644 index 000000000000..45ed928119da --- /dev/null +++ b/stubs/networkx/networkx/algorithms/non_randomness.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["non_randomness"] + +@_dispatchable +def non_randomness(G: Graph[_Node], k: int | None = None, weight: str | None = "weight") -> tuple[float, float]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/__init__.pyi b/stubs/networkx/networkx/algorithms/operators/__init__.pyi new file mode 100644 index 000000000000..0ebc6ab9998d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.algorithms.operators.all import * +from networkx.algorithms.operators.binary import * +from networkx.algorithms.operators.product import * +from networkx.algorithms.operators.unary import * diff --git a/stubs/networkx/networkx/algorithms/operators/all.pyi b/stubs/networkx/networkx/algorithms/operators/all.pyi new file mode 100644 index 000000000000..1283c534359c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/all.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["union_all", "compose_all", "disjoint_union_all", "intersection_all"] + +@_dispatchable +def union_all(graphs: Iterable[Incomplete], rename: Iterable[Incomplete] | None = ()) -> Graph[Incomplete]: ... +@_dispatchable +def disjoint_union_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def compose_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... +@_dispatchable +def intersection_all(graphs: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/binary.pyi b/stubs/networkx/networkx/algorithms/operators/binary.pyi new file mode 100644 index 000000000000..1b02515642a1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/binary.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from collections.abc import Hashable, Iterable +from typing import TypeVar + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["union", "compose", "disjoint_union", "intersection", "difference", "symmetric_difference", "full_join"] + +@_dispatchable +def disjoint_union(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def intersection(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def difference(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def symmetric_difference(G: Graph[_Node], H: Graph[_Node]) -> Graph[Incomplete]: ... + +_X_co = TypeVar("_X_co", bound=Hashable, covariant=True) +_Y_co = TypeVar("_Y_co", bound=Hashable, covariant=True) + +@_dispatchable +def compose(G: Graph[_X_co], H: Graph[_Y_co]) -> DiGraph[_X_co | _Y_co]: ... +@_dispatchable +def full_join(G: Graph[_Node], H, rename: tuple[Incomplete, Incomplete] = (None, None)) -> Graph[Incomplete]: ... +@_dispatchable +def union(G: Graph[_X_co], H: Graph[_Y_co], rename: Iterable[Incomplete] | None = ()) -> DiGraph[_X_co | _Y_co]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/product.pyi b/stubs/networkx/networkx/algorithms/operators/product.pyi new file mode 100644 index 000000000000..2fa5b93a77c1 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/product.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Hashable +from typing import TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_X = TypeVar("_X", bound=Hashable) +_Y = TypeVar("_Y", bound=Hashable) + +__all__ = [ + "tensor_product", + "cartesian_product", + "lexicographic_product", + "strong_product", + "power", + "rooted_product", + "corona_product", + "modular_product", +] + +@_dispatchable +def tensor_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def cartesian_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def lexicographic_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def strong_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def power(G: Graph[_Node], k: int) -> Graph[Incomplete]: ... +@_dispatchable +def rooted_product(G: Graph[_X], H: Graph[_Y], root: _Y) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def corona_product(G: Graph[_X], H: Graph[_Y]) -> Graph[tuple[_X, _Y]]: ... +@_dispatchable +def modular_product(G: Graph[_Node], H) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/operators/unary.pyi b/stubs/networkx/networkx/algorithms/operators/unary.pyi new file mode 100644 index 000000000000..11a8f76ae663 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/operators/unary.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Hashable +from typing import TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_G = TypeVar("_G", bound=Graph[Hashable]) + +__all__ = ["complement", "reverse"] + +@_dispatchable +def complement(G: Graph[_Node]) -> Graph[Incomplete]: ... +@_dispatchable +def reverse(G: _G, copy: bool = True) -> _G: ... diff --git a/stubs/networkx/networkx/algorithms/perfect_graph.pyi b/stubs/networkx/networkx/algorithms/perfect_graph.pyi new file mode 100644 index 000000000000..504389d87e7d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/perfect_graph.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_perfect_graph"] + +@_dispatchable +def is_perfect_graph(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/planar_drawing.pyi b/stubs/networkx/networkx/algorithms/planar_drawing.pyi new file mode 100644 index 000000000000..a40ab8611e12 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/planar_drawing.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.algorithms.planarity import PlanarEmbedding +from networkx.utils.backends import _dispatchable + +__all__ = ["combinatorial_embedding_to_pos"] + +@_dispatchable +def combinatorial_embedding_to_pos( + embedding: PlanarEmbedding[Incomplete], fully_triangulate: bool = False +) -> dict[Incomplete, Incomplete]: ... +def set_position(parent, tree, remaining_nodes, delta_x, y_coordinate, pos): ... +def get_canonical_ordering(embedding: PlanarEmbedding[Incomplete], outer_face: Sequence[Incomplete]) -> list[Incomplete]: ... +def triangulate_face(embedding: PlanarEmbedding[Incomplete], v1, v2): ... +def triangulate_embedding( + embedding: PlanarEmbedding[Incomplete], fully_triangulate: bool = True +) -> tuple[PlanarEmbedding[Incomplete], list[Incomplete]]: ... +def make_bi_connected( + embedding: PlanarEmbedding[Incomplete], starting_node, outgoing_node, edges_counted: set[tuple[Incomplete, Incomplete]] +) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/planarity.pyi b/stubs/networkx/networkx/algorithms/planarity.pyi new file mode 100644 index 000000000000..082bfb94007b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/planarity.pyi @@ -0,0 +1,114 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator, Iterable, Mapping, MutableSet, Reversible +from decimal import Decimal +from typing_extensions import Never + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _EdgePlus, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = ["check_planarity", "is_planar", "PlanarEmbedding"] + +@_dispatchable +def is_planar(G: Graph[_Node]) -> bool: ... +@_dispatchable +def check_planarity(G: Graph[_Node], counterexample: bool = False) -> tuple[bool, Graph[Incomplete]]: ... +@_dispatchable +def get_counterexample(G: Graph[_Node, _NodeData, _EdgeData]) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def get_counterexample_recursive(G: Graph[_Node, _NodeData, _EdgeData]) -> Graph[_Node, _NodeData, _EdgeData]: ... + +class Interval: + low: Incomplete + high: Incomplete + + def __init__(self, low=None, high=None) -> None: ... + def empty(self): ... + def copy(self): ... + def conflicting(self, b, planarity_state): ... + +class ConflictPair: + left: Incomplete + right: Incomplete + + def __init__(self, left=..., right=...) -> None: ... + def swap(self) -> None: ... + def lowest(self, planarity_state): ... + +class LRPlanarity: + __slots__ = [ + "G", + "roots", + "height", + "lowpt", + "lowpt2", + "nesting_depth", + "parent_edge", + "DG", + "adjs", + "ordered_adjs", + "ref", + "side", + "S", + "stack_bottom", + "lowpt_edge", + "left_ref", + "right_ref", + "embedding", + ] + G: Incomplete + roots: Incomplete + height: Incomplete + lowpt: Incomplete + lowpt2: Incomplete + nesting_depth: Incomplete + parent_edge: Incomplete + DG: Incomplete + adjs: Incomplete + ordered_adjs: Incomplete + ref: Incomplete + side: Incomplete + S: Incomplete + stack_bottom: Incomplete + lowpt_edge: Incomplete + left_ref: Incomplete + right_ref: Incomplete + embedding: Incomplete + + def __init__(self, G: Graph[_Node]) -> None: ... + def lr_planarity(self) -> PlanarEmbedding[Incomplete] | None: ... + def lr_planarity_recursive(self): ... + def dfs_orientation(self, v): ... + def dfs_orientation_recursive(self, v) -> None: ... + def dfs_testing(self, v): ... + def dfs_testing_recursive(self, v): ... + def add_constraints(self, ei, e): ... + def remove_back_edges(self, e) -> None: ... + def dfs_embedding(self, v): ... + def dfs_embedding_recursive(self, v) -> None: ... + def sign(self, e): ... + def sign_recursive(self, e): ... + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class PlanarEmbedding(DiGraph[_Node]): + def get_data(self) -> dict[_Node, list[_Node]]: ... + def set_data(self, data: Mapping[_Node, Reversible[_Node]]) -> None: ... + def neighbors_cw_order(self, v: _Node) -> Generator[_Node]: ... + def add_half_edge(self, start_node: _Node, end_node: _Node, *, cw: _Node | None = None, ccw: _Node | None = None): ... + def check_structure(self) -> None: ... + def add_half_edge_ccw(self, start_node: _Node, end_node: _Node, reference_neighbor: _Node) -> None: ... + def add_half_edge_cw(self, start_node: _Node, end_node: _Node, reference_neighbor: _Node) -> None: ... + def connect_components(self, v: _Node, w: _Node) -> None: ... + def add_half_edge_first(self, start_node: _Node, end_node: _Node) -> None: ... + def next_face_half_edge(self, v: _Node, w: _Node) -> tuple[_Node, _Node]: ... + def traverse_face( + self, v: _Node, w: _Node, mark_half_edges: MutableSet[tuple[_Node, _Node]] | None = None + ) -> list[_Node]: ... + # Overriden in __init__ to always raise + def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Unused) -> Never: ... + def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node]], **attr: Unused) -> Never: ... + def add_weighted_edges_from( + self, ebunch_to_add: Iterable[tuple[_Node, _Node, float | Decimal | None]], weight: str = "weight", **attr: Unused + ) -> Never: ... diff --git a/stubs/networkx/networkx/algorithms/polynomials.pyi b/stubs/networkx/networkx/algorithms/polynomials.pyi new file mode 100644 index 000000000000..9c40146e8d5b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/polynomials.pyi @@ -0,0 +1,9 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["tutte_polynomial", "chromatic_polynomial"] + +@_dispatchable +def tutte_polynomial(G: Graph[_Node]): ... +@_dispatchable +def chromatic_polynomial(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/reciprocity.pyi b/stubs/networkx/networkx/algorithms/reciprocity.pyi new file mode 100644 index 000000000000..de7191d31c0e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/reciprocity.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["reciprocity", "overall_reciprocity"] + +@_dispatchable +def reciprocity(G: Graph[_Node], nodes: Iterable[_Node] | None = None) -> float | dict[Incomplete, float | None]: ... +@_dispatchable +def overall_reciprocity(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/algorithms/regular.pyi b/stubs/networkx/networkx/algorithms/regular.pyi new file mode 100644 index 000000000000..063661966c6c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/regular.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_regular", "is_k_regular", "k_factor"] + +@_dispatchable +def is_regular(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_k_regular(G: Graph[_Node], k) -> bool: ... +@_dispatchable +def k_factor(G: Graph[_Node], k: int, matching_weight: str | None = "weight") -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/richclub.pyi b/stubs/networkx/networkx/algorithms/richclub.pyi new file mode 100644 index 000000000000..2f2b25d7b987 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/richclub.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["rich_club_coefficient"] + +@_dispatchable +def rich_club_coefficient( + G: Graph[_Node], normalized: bool = True, Q: float = 100, seed: int | RandomState | None = None +) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi new file mode 100644 index 000000000000..b64646da090c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/__init__.pyi @@ -0,0 +1,5 @@ +from networkx.algorithms.shortest_paths.astar import * +from networkx.algorithms.shortest_paths.dense import * +from networkx.algorithms.shortest_paths.generic import * +from networkx.algorithms.shortest_paths.unweighted import * +from networkx.algorithms.shortest_paths.weighted import * diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi new file mode 100644 index 000000000000..037db5b93ef9 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/astar.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["astar_path", "astar_path_length"] + +@_dispatchable +def astar_path( + G: Graph[_Node], + source: _Node, + target: _Node, + heuristic: Callable[[_Node, _Node], float] | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + *, + cutoff: float | None = None, +) -> list[_Node]: ... +@_dispatchable +def astar_path_length( + G: Graph[_Node], + source: _Node, + target: _Node, + heuristic: Callable[[_Node, _Node], float] | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + *, + cutoff: float | None = None, +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi new file mode 100644 index 000000000000..1290fe33c14c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/dense.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections import defaultdict +from collections.abc import Collection + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["floyd_warshall", "floyd_warshall_predecessor_and_distance", "reconstruct_path", "floyd_warshall_numpy"] + +@_dispatchable +def floyd_warshall_numpy( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight" +) -> np.ndarray[Incomplete, Incomplete]: ... +@_dispatchable +def floyd_warshall_predecessor_and_distance( + G: Graph[_Node], weight: str | None = "weight" +) -> tuple[dict[Incomplete, dict[Incomplete, Incomplete]], dict[Incomplete, dict[Incomplete, float]]]: ... +@_dispatchable +def reconstruct_path(source: _Node, target: _Node, predecessors: SupportsGetItem[Incomplete, Incomplete]) -> list[Incomplete]: ... +@_dispatchable +def floyd_warshall(G: Graph[_Node], weight: str | None = "weight") -> dict[Incomplete, defaultdict[Incomplete, float]]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi new file mode 100644 index 000000000000..abaf6a0f50f4 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/generic.pyi @@ -0,0 +1,148 @@ +from collections.abc import Generator +from typing import overload + +from networkx.algorithms.shortest_paths.weighted import _WeightFunc +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "shortest_path", + "all_shortest_paths", + "single_source_all_shortest_paths", + "all_pairs_all_shortest_paths", + "shortest_path_length", + "average_shortest_path_length", + "has_path", +] + +@_dispatchable +def has_path(G: Graph[_Node], source: _Node, target: _Node) -> bool: ... + +@overload # both source and target are specified => (s -> t) +def shortest_path( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> list[_Node]: ... +@overload # only source is specified => {t1: (s -> t), t2: (s -> t), ...} +def shortest_path( + G: Graph[_Node], + source: _Node, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload # only target is specified (positional) => {s1: (s1 -> t), s2: (s2 -> t), ...} +def shortest_path( + G: Graph[_Node], + source: None, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload # only target is specified (keyword) => {s1: (s1 -> t), s2: (s2 -> t), ...} +def shortest_path( + G: Graph[_Node], + source: None = None, + *, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, list[_Node]]: ... +@overload +def shortest_path( # source and target are not specified => generator of (t, {s1: (s1 -> t), s2: (s2 -> t), ...}) + G: Graph[_Node], + source: None = None, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> Generator[tuple[_Node, dict[str, list[_Node]]]]: ... + +@overload # both source and target are specified => len(s -> t) +def shortest_path_length( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> float: ... +@overload # only source is specified => {t1: len(s -> t1), t2: len(s -> t2), ...} +def shortest_path_length( + G: Graph[_Node], + source: _Node, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload # only target is specified (positional) => {s1: len(s1 -> t), s2: len(s2 -> t), ...} +def shortest_path_length( + G: Graph[_Node], + source: None, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload # only target is specified (keyword) => {s1: len(s1 -> t), s2: len(s2 -> t), ...} +def shortest_path_length( + G: Graph[_Node], + source: None = None, + *, + target: _Node, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + backend: str | None = None, + **backend_kwargs, +) -> dict[_Node, float]: ... +@overload +def shortest_path_length( # source and target are not specified => generator of (t, {s1: len(s1 -> t), s2: len(s2 -> t), ...}) + G: Graph[_Node], + source: None = None, + target: None = None, + weight: str | _WeightFunc[_Node] | None = None, + method: str | None = "dijkstra", + *, + backend: str | None = None, + **backend_kwargs, +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... + +@_dispatchable +def average_shortest_path_length( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = None, method: str | None = None +) -> float: ... +@_dispatchable +def all_shortest_paths( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[list[_Node]]: ... +@_dispatchable +def single_source_all_shortest_paths( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[tuple[_Node, list[list[_Node]]]]: ... +@_dispatchable +def all_pairs_all_shortest_paths( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = None, method: str | None = "dijkstra" +) -> Generator[tuple[_Node, dict[_Node, list[list[_Node]]]]]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi new file mode 100644 index 000000000000..636eb613875d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/unweighted.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "bidirectional_shortest_path", + "single_source_shortest_path", + "single_source_shortest_path_length", + "single_target_shortest_path", + "single_target_shortest_path_length", + "all_pairs_shortest_path", + "all_pairs_shortest_path_length", + "predecessor", +] + +@_dispatchable +def single_source_shortest_path_length(G: Graph[_Node], source: _Node, cutoff: int | None = None) -> dict[Incomplete, int]: ... +@_dispatchable +def single_target_shortest_path_length( + G: Graph[_Node], target: _Node, cutoff: int | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def all_pairs_shortest_path_length(G: Graph[_Node], cutoff: int | None = None) -> Generator[Incomplete]: ... +@_dispatchable +def bidirectional_shortest_path(G: Graph[_Node], source: _Node, target: _Node) -> list[Incomplete]: ... +@_dispatchable +def single_source_shortest_path( + G: Graph[_Node], source: _Node, cutoff: int | None = None +) -> dict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def single_target_shortest_path( + G: Graph[_Node], target: _Node, cutoff: int | None = None +) -> dict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def all_pairs_shortest_path( + G: Graph[_Node], cutoff: int | None = None +) -> Generator[tuple[Incomplete, dict[Incomplete, list[Incomplete]]]]: ... +@_dispatchable +def predecessor( + G: Graph[_Node], source: _Node, target: _Node | None = None, cutoff: int | None = None, return_seen: bool | None = None +) -> dict[_Node, list[_Node]] | list[_Node] | tuple[dict[_Node, list[_Node]], dict[_Node, int]] | tuple[list[_Node], int]: ... diff --git a/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi b/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi new file mode 100644 index 000000000000..bee3ecf7470c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/shortest_paths/weighted.pyi @@ -0,0 +1,145 @@ +from collections.abc import Callable, Collection, Generator +from typing import Any, TypeAlias + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "dijkstra_path", + "dijkstra_path_length", + "bidirectional_dijkstra", + "single_source_dijkstra", + "single_source_dijkstra_path", + "single_source_dijkstra_path_length", + "multi_source_dijkstra", + "multi_source_dijkstra_path", + "multi_source_dijkstra_path_length", + "all_pairs_dijkstra", + "all_pairs_dijkstra_path", + "all_pairs_dijkstra_path_length", + "dijkstra_predecessor_and_distance", + "bellman_ford_path", + "bellman_ford_path_length", + "single_source_bellman_ford", + "single_source_bellman_ford_path", + "single_source_bellman_ford_path_length", + "all_pairs_bellman_ford_path", + "all_pairs_bellman_ford_path_length", + "bellman_ford_predecessor_and_distance", + "negative_edge_cycle", + "find_negative_cycle", + "goldberg_radzik", + "johnson", +] + +_WeightFunc: TypeAlias = Callable[ + [_Node, _Node, dict[str, Any]], # Any: type of edge data cannot be known statically + float | None, # the weight or None to indicate a hidden edge +] + +@_dispatchable +def dijkstra_path( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> list[_Node]: ... +@_dispatchable +def dijkstra_path_length( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> float: ... +@_dispatchable +def single_source_dijkstra_path( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def single_source_dijkstra_path_length( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def single_source_dijkstra( + G: Graph[_Node], + source: _Node, + target: _Node | None = None, + cutoff: float | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def multi_source_dijkstra_path( + G: Graph[_Node], sources: Collection[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def multi_source_dijkstra_path_length( + G: Graph[_Node], sources: Collection[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def multi_source_dijkstra( + G: Graph[_Node], + sources: Collection[_Node], + target: _Node | None = None, + cutoff: float | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def dijkstra_predecessor_and_distance( + G: Graph[_Node], source: _Node, cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, list[_Node]], dict[_Node, float]]: ... +@_dispatchable +def all_pairs_dijkstra( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, tuple[dict[_Node, float], dict[_Node, list[_Node]]]]]: ... +@_dispatchable +def all_pairs_dijkstra_path_length( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... +@_dispatchable +def all_pairs_dijkstra_path( + G: Graph[_Node], cutoff: float | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, list[_Node]]]]: ... +@_dispatchable +def bellman_ford_predecessor_and_distance( + G: Graph[_Node], + source: _Node, + target: _Node | None = None, + weight: str | _WeightFunc[_Node] | None = "weight", + heuristic: bool = False, +) -> tuple[dict[_Node, list[_Node]], dict[_Node, float]]: ... +@_dispatchable +def bellman_ford_path( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> list[_Node]: ... +@_dispatchable +def bellman_ford_path_length( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> float: ... +@_dispatchable +def single_source_bellman_ford_path( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def single_source_bellman_ford_path_length( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> dict[_Node, float]: ... +@_dispatchable +def single_source_bellman_ford( + G: Graph[_Node], source: _Node, target: _Node | None = None, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, float], dict[_Node, list[_Node]]] | tuple[float, list[_Node]]: ... # TODO: overload on target +@_dispatchable +def all_pairs_bellman_ford_path_length( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, float]]]: ... +@_dispatchable +def all_pairs_bellman_ford_path( + G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight" +) -> Generator[tuple[_Node, dict[_Node, list[_Node]]]]: ... +@_dispatchable +def goldberg_radzik( + G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[dict[_Node, _Node | None], dict[_Node, float]]: ... +@_dispatchable +def negative_edge_cycle(G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight", heuristic: bool = True) -> bool: ... +@_dispatchable +def find_negative_cycle(G: Graph[_Node], source: _Node, weight: str | _WeightFunc[_Node] | None = "weight") -> list[_Node]: ... +@_dispatchable +def bidirectional_dijkstra( + G: Graph[_Node], source: _Node, target: _Node, weight: str | _WeightFunc[_Node] | None = "weight" +) -> tuple[float, list[_Node]]: ... +@_dispatchable +def johnson(G: Graph[_Node], weight: str | _WeightFunc[_Node] | None = "weight") -> dict[_Node, dict[_Node, list[_Node]]]: ... diff --git a/stubs/networkx/networkx/algorithms/similarity.pyi b/stubs/networkx/networkx/algorithms/similarity.pyi new file mode 100644 index 000000000000..b0ba3bbe8797 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/similarity.pyi @@ -0,0 +1,125 @@ +from _typeshed import Incomplete, SupportsItemAccess +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "graph_edit_distance", + "optimal_edit_paths", + "optimize_graph_edit_distance", + "optimize_edit_paths", + "simrank_similarity", + "panther_similarity", + "panther_vector_similarity", + "generate_random_paths", +] + +@_dispatchable +def graph_edit_distance( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + roots: tuple[Incomplete, Incomplete] | None = None, + upper_bound: float | None = None, + timeout: float | None = None, +): ... +@_dispatchable +def optimal_edit_paths( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, +) -> tuple[list[tuple[Incomplete, Incomplete]], float]: ... +@_dispatchable +def optimize_graph_edit_distance( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, +) -> Generator[Incomplete]: ... +@_dispatchable +def optimize_edit_paths( + G1: Graph[_Node], + G2: Graph[_Node], + node_match: Callable[..., Incomplete] | None = None, + edge_match: Callable[..., Incomplete] | None = None, + node_subst_cost: Callable[..., Incomplete] | None = None, + node_del_cost: Callable[..., Incomplete] | None = None, + node_ins_cost: Callable[..., Incomplete] | None = None, + edge_subst_cost: Callable[..., Incomplete] | None = None, + edge_del_cost: Callable[..., Incomplete] | None = None, + edge_ins_cost: Callable[..., Incomplete] | None = None, + upper_bound: float | None = None, + strictly_decreasing: bool = True, + roots: tuple[Incomplete, Incomplete] | None = None, + timeout: float | None = None, +) -> Generator[Incomplete, None, Incomplete]: ... +@_dispatchable +def simrank_similarity( + G: Graph[_Node], + source: _Node | None = None, + target: _Node | None = None, + importance_factor: float = 0.9, + max_iterations: int = 1000, + tolerance: float = 0.0001, +) -> float | dict[Incomplete, Incomplete]: ... +@_dispatchable +def panther_similarity( + G: Graph[_Node], + source: _Node, + k: int = 5, + path_length: int = 5, + c: float = 0.5, + delta: float = 0.1, + eps: float | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, +) -> dict[bytes, bytes]: ... +@_dispatchable +def panther_vector_similarity( + G: Graph[_Node], + source: _Node, + *, + D: int = 10, + k: int = 5, + path_length: int = 5, + c: float = 0.5, + delta: float = 0.1, + eps: float | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, +) -> dict[Incomplete, float]: ... +@_dispatchable +def generate_random_paths( + G: Graph[_Node], + sample_size: int, + path_length: int = 5, + index_map: SupportsItemAccess[Incomplete, Incomplete] | None = None, + weight: str | None = "weight", + seed: int | RandomState | None = None, + *, + source: _Node | None = None, +) -> Generator[list[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/simple_paths.pyi b/stubs/networkx/networkx/algorithms/simple_paths.pyi new file mode 100644 index 000000000000..f32d7d205d2b --- /dev/null +++ b/stubs/networkx/networkx/algorithms/simple_paths.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Collection, Generator, Iterable +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["all_simple_paths", "is_simple_path", "shortest_simple_paths", "all_simple_edge_paths"] + +@_dispatchable +def is_simple_path(G: Graph[_Node], nodes: Collection[Incomplete]) -> bool: ... +@_dispatchable +def all_simple_paths( + G: Graph[_Node], source: _Node, target: _Node | Iterable[_Node], cutoff: int | None = None +) -> Generator[list[_Node]]: ... +@_dispatchable +def all_simple_edge_paths( + G: Graph[_Node], source: _Node, target: _Node | Iterable[_Node], cutoff: int | None = None +) -> Generator[list[_Node] | list[tuple[_Node, _Node]], None, list[_Node] | None]: ... +@_dispatchable +def shortest_simple_paths( + G: Graph[_Node], + source: _Node, + target: _Node, + weight: str | Callable[[Any, Any, SupportsGetItem[str, Any]], float | None] | None = None, +) -> Generator[list[_Node]]: ... + +class PathBuffer: + paths: Incomplete + sortedpaths: Incomplete + counter: Incomplete + + def __init__(self) -> None: ... + def __len__(self): ... + def push(self, cost, path) -> None: ... + def pop(self): ... diff --git a/stubs/networkx/networkx/algorithms/smallworld.pyi b/stubs/networkx/networkx/algorithms/smallworld.pyi new file mode 100644 index 000000000000..0b6ae2986819 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/smallworld.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete + +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["random_reference", "lattice_reference", "sigma", "omega"] + +@_dispatchable +def random_reference( + G: Graph[_Node], niter: int = 1, connectivity: bool = True, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def lattice_reference( + G: Graph[_Node], + niter: int = 5, + D: np.ndarray[Incomplete, Incomplete] | None = None, + connectivity: bool = True, + seed: int | RandomState | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def sigma(G: Graph[_Node], niter: int = 100, nrand: int = 10, seed: int | RandomState | None = None) -> float: ... +@_dispatchable +def omega(G: Graph[_Node], niter: int = 5, nrand: int = 10, seed: int | RandomState | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/smetric.pyi b/stubs/networkx/networkx/algorithms/smetric.pyi new file mode 100644 index 000000000000..60f6d0ab5d25 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/smetric.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["s_metric"] + +@_dispatchable +def s_metric(G: Graph[_Node]) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/sparsifiers.pyi b/stubs/networkx/networkx/algorithms/sparsifiers.pyi new file mode 100644 index 000000000000..e94ffe57f37a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/sparsifiers.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["spanner"] + +@_dispatchable +def spanner( + G: Graph[_Node], stretch: float, weight: str | None = None, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/structuralholes.pyi b/stubs/networkx/networkx/algorithms/structuralholes.pyi new file mode 100644 index 000000000000..e869afe75614 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/structuralholes.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["constraint", "local_constraint", "effective_size"] + +@_dispatchable +def mutual_weight(G: Graph[_Node], u, v, weight=None) -> Incomplete | int: ... +@_dispatchable +def normalized_mutual_weight(G: Graph[_Node], u, v, norm=..., weight=None) -> float: ... +@_dispatchable +def effective_size( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def constraint( + G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, weight: str | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def local_constraint(G: Graph[_Node], u: _Node, v: _Node, weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/summarization.pyi b/stubs/networkx/networkx/algorithms/summarization.pyi new file mode 100644 index 000000000000..c2ec3253c28f --- /dev/null +++ b/stubs/networkx/networkx/algorithms/summarization.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["dedensify", "snap_aggregation"] + +@_dispatchable +def dedensify( + G: Graph[_Node], threshold: int, prefix: str | None = None, copy: bool | None = True +) -> tuple[Graph[Incomplete], set[Incomplete]]: ... +@_dispatchable +def snap_aggregation( + G: Graph[_Node], + node_attributes: Iterable[Incomplete], + edge_attributes: Iterable[Incomplete] | None = (), + prefix: str = "Supernode-", + supernode_attribute: str = "group", + superedge_attribute: str = "types", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/swap.pyi b/stubs/networkx/networkx/algorithms/swap.pyi new file mode 100644 index 000000000000..607e9ae99ee6 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/swap.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["double_edge_swap", "connected_double_edge_swap", "directed_edge_swap"] + +@_dispatchable +def directed_edge_swap( + G: DiGraph[_Node], *, nswap: int = 1, max_tries: int = 100, seed: int | RandomState | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def double_edge_swap( + G: Graph[_Node], nswap: int = 1, max_tries: int = 100, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def connected_double_edge_swap( + G: Graph[_Node], nswap: int = 1, _window_threshold: int = 3, seed: int | RandomState | None = None +) -> int: ... diff --git a/stubs/networkx/networkx/algorithms/threshold.pyi b/stubs/networkx/networkx/algorithms/threshold.pyi new file mode 100644 index 000000000000..c66a43788026 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/threshold.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = ["is_threshold_graph", "find_threshold_graph"] + +@_dispatchable +def is_threshold_graph(G: Graph[_Node]) -> bool: ... +def is_threshold_sequence(degree_sequence: Sequence[list[int]]) -> bool: ... +def creation_sequence(degree_sequence, with_labels=False, compact=False): ... +def make_compact(creation_sequence): ... +def uncompact(creation_sequence): ... +def creation_sequence_to_weights(creation_sequence): ... +def weights_to_creation_sequence(weights, threshold=1, with_labels=False, compact=False): ... +@_dispatchable +def threshold_graph(creation_sequence, create_using=None): ... +@_dispatchable +def find_alternating_4_cycle(G: Graph[_Node]): ... +@_dispatchable +def find_threshold_graph(G: Graph[_Node], create_using: Graph[_Node] | type[Graph[_Node]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def find_creation_sequence(G: Graph[_Node]): ... +def triangles(creation_sequence): ... +def triangle_sequence(creation_sequence): ... +def cluster_sequence(creation_sequence): ... +def degree_sequence(creation_sequence): ... +def density(creation_sequence): ... +def degree_correlation(creation_sequence): ... +def shortest_path(creation_sequence, u, v): ... +def shortest_path_length(creation_sequence, i): ... +def betweenness_sequence(creation_sequence, normalized=True): ... +def eigenvectors(creation_sequence): ... +def spectral_projection(u, eigenpairs): ... +def eigenvalues(creation_sequence): ... +def random_threshold_sequence(n, p, seed: int | RandomState | None = None): ... +def right_d_threshold_sequence(n: int, m: int) -> list[str]: ... +def left_d_threshold_sequence(n: int, m: int) -> list[str]: ... diff --git a/stubs/networkx/networkx/algorithms/time_dependent.pyi b/stubs/networkx/networkx/algorithms/time_dependent.pyi new file mode 100644 index 000000000000..abdd217acd5c --- /dev/null +++ b/stubs/networkx/networkx/algorithms/time_dependent.pyi @@ -0,0 +1,11 @@ +from datetime import timedelta + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["cd_index"] + +@_dispatchable +def cd_index( + G: Graph[_Node], node: _Node, time_delta: float | timedelta, *, time: str = "time", weight: str | None = None +) -> float: ... diff --git a/stubs/networkx/networkx/algorithms/tournament.pyi b/stubs/networkx/networkx/algorithms/tournament.pyi new file mode 100644 index 000000000000..0fff43290acb --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tournament.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "hamiltonian_path", + "is_reachable", + "is_strongly_connected", + "is_tournament", + "random_tournament", + "score_sequence", + "tournament_matrix", +] + +@_dispatchable +def is_tournament(G: Graph[_Node]) -> bool: ... +@_dispatchable +def hamiltonian_path(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def random_tournament(n: int, seed: int | RandomState | None = None) -> DiGraph[Incomplete]: ... +@_dispatchable +def tournament_matrix(G: Graph[_Node]): ... +@_dispatchable +def score_sequence(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def is_reachable(G: Graph[_Node], s: _Node, t: _Node) -> bool: ... +@_dispatchable +def is_strongly_connected(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/__init__.pyi b/stubs/networkx/networkx/algorithms/traversal/__init__.pyi new file mode 100644 index 000000000000..c97ceceb614a --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/__init__.pyi @@ -0,0 +1,5 @@ +from .beamsearch import * +from .breadth_first_search import * +from .depth_first_search import * +from .edgebfs import * +from .edgedfs import * diff --git a/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi b/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi new file mode 100644 index 000000000000..9c5c1784d269 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/beamsearch.pyi @@ -0,0 +1,11 @@ +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["bfs_beam_edges"] + +@_dispatchable +def bfs_beam_edges( + G: Graph[_Node], source: _Node, value: Callable[[_Node], float], width: int | None = None +) -> Generator[tuple[_Node, _Node]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi b/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi new file mode 100644 index 000000000000..60d27065db69 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/breadth_first_search.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Final, Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "bfs_edges", + "bfs_tree", + "bfs_predecessors", + "bfs_successors", + "descendants_at_distance", + "bfs_layers", + "bfs_labeled_edges", + "generic_bfs_edges", +] + +@_dispatchable +def generic_bfs_edges( + G: Graph[_Node], source: _Node, neighbors: Callable[[_Node], Iterable[_Node]] | None = None, depth_limit: int | None = None +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_edges( + G: Graph[_Node], + source: _Node, + reverse: bool | None = False, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_tree( + G: Graph[_Node, _NodeData, _EdgeData], + source: _Node, + reverse: bool | None = False, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def bfs_predecessors( + G: Graph[_Node], + source: _Node, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def bfs_successors( + G: Graph[_Node], + source: _Node, + depth_limit: int | None = None, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, list[_Node]]]: ... +@_dispatchable +def bfs_layers(G: Graph[_Node], sources: _Node | Iterable[_Node]) -> Generator[list[_Node]]: ... + +REVERSE_EDGE: Final = "reverse" +TREE_EDGE: Final = "tree" +FORWARD_EDGE: Final = "forward" +LEVEL_EDGE: Final = "level" + +@_dispatchable +def bfs_labeled_edges( + G: Graph[_Node], sources: _Node | Iterable[_Node] +) -> Generator[tuple[_Node, _Node, Literal["tree", "level", "forward", "reverse"]]]: ... +@_dispatchable +def descendants_at_distance(G: Graph[_Node], source: _Node, distance: int) -> set[_Node]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi b/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi new file mode 100644 index 000000000000..083e25e1561d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/depth_first_search.pyi @@ -0,0 +1,73 @@ +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Literal + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "dfs_edges", + "dfs_tree", + "dfs_predecessors", + "dfs_successors", + "dfs_preorder_nodes", + "dfs_postorder_nodes", + "dfs_labeled_edges", +] + +@_dispatchable +def dfs_edges( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node]]: ... +@_dispatchable +def dfs_tree( + G: Graph[_Node, _NodeData, _EdgeData], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def dfs_predecessors( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> dict[_Node, _Node]: ... +@_dispatchable +def dfs_successors( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def dfs_postorder_nodes( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[_Node]: ... +@_dispatchable +def dfs_preorder_nodes( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[_Node]: ... +@_dispatchable +def dfs_labeled_edges( + G: Graph[_Node], + source: _Node | None = None, + depth_limit: int | None = None, + *, + sort_neighbors: Callable[[Iterator[_Node]], Iterable[_Node]] | None = None, +) -> Generator[tuple[_Node, _Node, Literal["forward", "nontree", "reverse", "reverse-depth_limit"]]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi b/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi new file mode 100644 index 000000000000..f4f3b895c8d3 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/edgebfs.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_bfs"] + +FORWARD: Final = "forward" +REVERSE: Final = "reverse" + +@_dispatchable +def edge_bfs( + G: Graph[_Node], + source: _Node | Iterable[_Node] | None = None, + orientation: Literal["original", "reverse", "ignore"] | None = None, +) -> Generator[tuple[Incomplete, ...]]: ... diff --git a/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi b/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi new file mode 100644 index 000000000000..6c5e0bf9a75d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/traversal/edgedfs.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from collections.abc import Generator, Iterable +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["edge_dfs"] + +FORWARD: Final = "forward" +REVERSE: Final = "reverse" + +@_dispatchable +def edge_dfs( + G: Graph[_Node], + source: _Node | Iterable[_Node] | None = None, + orientation: Literal["original", "reverse", "ignore"] | None = None, +) -> Generator[tuple[Incomplete, ...]]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/__init__.pyi b/stubs/networkx/networkx/algorithms/tree/__init__.pyi new file mode 100644 index 000000000000..1a901de7bdef --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/__init__.pyi @@ -0,0 +1,7 @@ +from .branchings import * +from .coding import * +from .decomposition import * +from .distance_measures import * +from .mst import * +from .operations import * +from .recognition import * diff --git a/stubs/networkx/networkx/algorithms/tree/branchings.pyi b/stubs/networkx/networkx/algorithms/tree/branchings.pyi new file mode 100644 index 000000000000..c9444c109a8d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/branchings.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from dataclasses import dataclass +from typing import Final +from typing_extensions import Self + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "branching_weight", + "greedy_branching", + "maximum_branching", + "minimum_branching", + "minimal_branching", + "maximum_spanning_arborescence", + "minimum_spanning_arborescence", + "ArborescenceIterator", +] + +KINDS: Final[set[str]] +STYLES: Final[dict[str, str]] +INF: Final[float] + +def random_string(L=15, seed=None): ... +@_dispatchable +def branching_weight(G: DiGraph[_Node], attr: str = "weight", default: float = 1) -> int | float: ... +@_dispatchable +def greedy_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, kind: str = "max", seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def maximum_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimum_branching( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimal_branching( + G: DiGraph[_Node], /, *, attr="weight", default=1, preserve_attrs=False, partition=None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def maximum_spanning_arborescence( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def minimum_spanning_arborescence( + G: DiGraph[_Node], attr: str = "weight", default: float = 1, preserve_attrs: bool = False, partition: str | None = None +) -> DiGraph[Incomplete]: ... + +class ArborescenceIterator: + @dataclass(order=True) + class Partition: + mst_weight: float + partition_dict: dict[Incomplete, Incomplete] + def __copy__(self) -> ArborescenceIterator.Partition: ... + + G: Incomplete + weight: Incomplete + minimum: Incomplete + method: Incomplete + partition_key: str + init_partition: Incomplete + + def __init__(self, G: DiGraph[_Node], weight: str = "weight", minimum: bool = True, init_partition=None) -> None: ... + partition_queue: Incomplete + + def __iter__(self) -> Self: ... + def __next__(self): ... diff --git a/stubs/networkx/networkx/algorithms/tree/coding.pyi b/stubs/networkx/networkx/algorithms/tree/coding.pyi new file mode 100644 index 000000000000..7e6013a8526e --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/coding.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.exception import NetworkXException +from networkx.utils.backends import _dispatchable + +__all__ = ["from_nested_tuple", "from_prufer_sequence", "NotATree", "to_nested_tuple", "to_prufer_sequence"] + +class NotATree(NetworkXException): ... + +@_dispatchable +def to_nested_tuple(T: Graph[_Node], root: _Node, canonical_form: bool = False) -> tuple[Incomplete, ...]: ... +@_dispatchable +def from_nested_tuple(sequence: tuple[Incomplete, ...], sensible_relabeling: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def to_prufer_sequence(T: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def from_prufer_sequence(sequence: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/decomposition.pyi b/stubs/networkx/networkx/algorithms/tree/decomposition.pyi new file mode 100644 index 000000000000..f50ed7b684fc --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/decomposition.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["junction_tree"] + +@_dispatchable +def junction_tree(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi b/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi new file mode 100644 index 000000000000..eb523e2331ac --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/distance_measures.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["center", "centroid"] + +def center(G: Graph[_Node]) -> list[Incomplete]: ... +@_dispatchable +def centroid(G: Graph[_Node]) -> list[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/mst.pyi b/stubs/networkx/networkx/algorithms/tree/mst.pyi new file mode 100644 index 000000000000..dc175b1cb1f0 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/mst.pyi @@ -0,0 +1,106 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterator +from dataclasses import dataclass +from enum import Enum +from typing import Final, Literal +from typing_extensions import Self + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +__all__ = [ + "minimum_spanning_edges", + "maximum_spanning_edges", + "minimum_spanning_tree", + "maximum_spanning_tree", + "number_of_spanning_trees", + "random_spanning_tree", + "partition_spanning_tree", + "EdgePartition", + "SpanningTreeIterator", +] + +class EdgePartition(Enum): + OPEN = 0 + INCLUDED = 1 + EXCLUDED = 2 + +@_dispatchable +def boruvka_mst_edges( + G: Graph[_Node], minimum: bool = True, weight: str = "weight", keys: bool = False, data: bool = True, ignore_nan: bool = False +): ... +@_dispatchable +def kruskal_mst_edges( + G: Graph[_Node], + minimum: bool, + weight: str = "weight", + keys: bool = True, + data: bool = True, + ignore_nan: bool = False, + partition: str | None = None, +): ... +@_dispatchable +def prim_mst_edges( + G: Graph[_Node], minimum: bool, weight: str = "weight", keys: bool = True, data: bool = True, ignore_nan: bool = False +): ... + +ALGORITHMS: Final[dict[str, Callable[..., Generator[Incomplete, Incomplete, Incomplete]]]] + +@_dispatchable +def minimum_spanning_edges( + G: Graph[_Node], + algorithm: str = "kruskal", + weight: str = "weight", + keys: bool = True, + data: bool | None = True, + ignore_nan: bool = False, +) -> Iterator[Incomplete]: ... +@_dispatchable +def maximum_spanning_edges( + G: Graph[_Node], + algorithm: str = "kruskal", + weight: str = "weight", + keys: bool = True, + data: bool | None = True, + ignore_nan: bool = False, +) -> Iterator[Incomplete]: ... +@_dispatchable +def minimum_spanning_tree( + G: Graph[_Node], weight: str = "weight", algorithm: str = "kruskal", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def partition_spanning_tree( + G: Graph[_Node], minimum: bool = True, weight: str = "weight", partition: str = "partition", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def maximum_spanning_tree( + G: Graph[_Node], weight: str = "weight", algorithm: str = "kruskal", ignore_nan: bool = False +) -> Graph[Incomplete]: ... +@_dispatchable +def random_spanning_tree( + G: Graph[_Node], weight: str | None = None, *, multiplicative=True, seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... + +class SpanningTreeIterator: + @dataclass(order=True) + class Partition: + mst_weight: float + partition_dict: dict[Incomplete, Incomplete] + def __copy__(self) -> SpanningTreeIterator.Partition: ... + + G: Incomplete + weight: Incomplete + minimum: Incomplete + ignore_nan: Incomplete + partition_key: str + + def __init__(self, G: DiGraph[_Node], weight: str = "weight", minimum: bool = True, ignore_nan: bool = False) -> None: ... + partition_queue: Incomplete + + def __iter__(self) -> Self: ... + def __next__(self): ... + +@_dispatchable +def number_of_spanning_trees(G: Graph[_Node], *, root=None, weight=None) -> float | Literal[0]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/operations.pyi b/stubs/networkx/networkx/algorithms/tree/operations.pyi new file mode 100644 index 000000000000..b66207c5dfce --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/operations.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["join_trees"] + +@_dispatchable +def join_trees( + rooted_trees: Iterable[Incomplete], *, label_attribute: str | None = None, first_label: int | None = 0 +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/tree/recognition.pyi b/stubs/networkx/networkx/algorithms/tree/recognition.pyi new file mode 100644 index 000000000000..14b1b4ae6147 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/tree/recognition.pyi @@ -0,0 +1,14 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["is_arborescence", "is_branching", "is_forest", "is_tree"] + +@_dispatchable +def is_arborescence(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_branching(G: DiGraph[_Node]) -> bool: ... +@_dispatchable +def is_forest(G: Graph[_Node]) -> bool: ... +@_dispatchable +def is_tree(G: Graph[_Node]) -> bool: ... diff --git a/stubs/networkx/networkx/algorithms/triads.pyi b/stubs/networkx/networkx/algorithms/triads.pyi new file mode 100644 index 000000000000..b4b8fc840daf --- /dev/null +++ b/stubs/networkx/networkx/algorithms/triads.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Collection, Generator +from typing import Final + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["triadic_census", "is_triad", "all_triads", "triads_by_type", "triad_type"] + +TRICODES: Final[tuple[int, ...]] +TRIAD_NAMES: Final[tuple[str, ...]] +TRICODE_TO_NAME: Final[dict[int, str]] + +@_dispatchable +def triadic_census(G: DiGraph[_Node], nodelist: Collection[_Node] | None = None) -> dict[str, int]: ... +@_dispatchable +def is_triad(G: Graph[_Node]) -> bool: ... +@_dispatchable +def all_triads(G: DiGraph[_Node]) -> Generator[Incomplete]: ... +@_dispatchable +def triads_by_type(G: DiGraph[_Node]) -> defaultdict[Incomplete, list[Incomplete]]: ... +@_dispatchable +def triad_type(G: DiGraph[_Node]) -> str | None: ... diff --git a/stubs/networkx/networkx/algorithms/vitality.pyi b/stubs/networkx/networkx/algorithms/vitality.pyi new file mode 100644 index 000000000000..3fd2cfe0e482 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/vitality.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["closeness_vitality"] + +@_dispatchable +def closeness_vitality( + G: Graph[_Node], node=None, weight: str | None = None, wiener_index: float | None = None +) -> float | dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/voronoi.pyi b/stubs/networkx/networkx/algorithms/voronoi.pyi new file mode 100644 index 000000000000..63f890bf2591 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/voronoi.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["voronoi_cells"] + +@_dispatchable +def voronoi_cells( + G: Graph[_Node], + center_nodes: set[Incomplete], + weight: str | Callable[[Any, Any, SupportsGetItem[str, Any]], float | None] | None = "weight", +) -> dict[Incomplete, set[Incomplete]]: ... diff --git a/stubs/networkx/networkx/algorithms/walks.pyi b/stubs/networkx/networkx/algorithms/walks.pyi new file mode 100644 index 000000000000..44a872420ab5 --- /dev/null +++ b/stubs/networkx/networkx/algorithms/walks.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["number_of_walks"] + +@_dispatchable +def number_of_walks(G: Graph[_Node], walk_length: int) -> dict[Incomplete, Incomplete]: ... diff --git a/stubs/networkx/networkx/algorithms/wiener.pyi b/stubs/networkx/networkx/algorithms/wiener.pyi new file mode 100644 index 000000000000..6920d3e7176d --- /dev/null +++ b/stubs/networkx/networkx/algorithms/wiener.pyi @@ -0,0 +1,13 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["wiener_index", "schultz_index", "gutman_index", "hyper_wiener_index"] + +@_dispatchable +def wiener_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def schultz_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def gutman_index(G: Graph[_Node], weight: str | None = None) -> float: ... +@_dispatchable +def hyper_wiener_index(G: Graph[_Node], weight: str | None = None) -> float: ... diff --git a/stubs/networkx/networkx/classes/__init__.pyi b/stubs/networkx/networkx/classes/__init__.pyi new file mode 100644 index 000000000000..e8494acec551 --- /dev/null +++ b/stubs/networkx/networkx/classes/__init__.pyi @@ -0,0 +1,7 @@ +from . import coreviews as coreviews, filters as filters, graphviews as graphviews, reportviews as reportviews +from .digraph import DiGraph as DiGraph +from .function import * +from .graph import Graph as Graph +from .graphviews import reverse_view as reverse_view, subgraph_view as subgraph_view +from .multidigraph import MultiDiGraph as MultiDiGraph +from .multigraph import MultiGraph as MultiGraph diff --git a/stubs/networkx/networkx/classes/coreviews.pyi b/stubs/networkx/networkx/classes/coreviews.pyi new file mode 100644 index 000000000000..ed0114551bfc --- /dev/null +++ b/stubs/networkx/networkx/classes/coreviews.pyi @@ -0,0 +1,79 @@ +from collections.abc import Callable, Iterator, Mapping +from typing import TypeVar +from typing_extensions import Self + +_T = TypeVar("_T") +_U = TypeVar("_U") +_V = TypeVar("_V") + +__all__ = [ + "AtlasView", + "AdjacencyView", + "MultiAdjacencyView", + "UnionAtlas", + "UnionAdjacency", + "UnionMultiInner", + "UnionMultiAdjacency", + "FilterAtlas", + "FilterAdjacency", + "FilterMultiInner", + "FilterMultiAdjacency", +] + +class AtlasView(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_atlas",) + def __getstate__(self) -> dict[str, Mapping[_T, dict[_U, _V]]]: ... + def __setstate__(self, state: dict[str, Mapping[_T, dict[_U, _V]]]) -> None: ... + def __init__(self, d: Mapping[_T, dict[_U, _V]]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> dict[_T, dict[_U, _V]]: ... + +class AdjacencyView(AtlasView[_T, _U, _V]): + __slots__ = () + +class MultiAdjacencyView(AdjacencyView[_T, _U, _V]): + __slots__ = () + +class UnionAtlas(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_succ", "_pred") + def __init__(self, succ: AtlasView[_T, _U, _V], pred: AtlasView[_T, _U, _V]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> Self: ... + +class UnionAdjacency(Mapping[_T, dict[_U, _V]]): + __slots__ = ("_succ", "_pred") + def __init__(self, succ: AdjacencyView[_T, _U, _V], pred: AdjacencyView[_T, _U, _V]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> dict[_U, _V]: ... + def copy(self) -> Self: ... + +class UnionMultiInner(UnionAtlas[_T, _U, _V]): + __slots__ = () + +class UnionMultiAdjacency(UnionAdjacency[_T, _U, _V]): + __slots__ = () + +class FilterAtlas(Mapping[_T, _U]): + NODE_OK: Callable[[_T], bool] + def __init__(self, d: Mapping[_T, _U], NODE_OK: Callable[[_T], bool]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __getitem__(self, key: _T) -> _U: ... + +class FilterAdjacency(Mapping[_T, Mapping[_U, _V]]): + NODE_OK: Callable[[_T], bool] + EDGE_OK: Callable[[_T, _T], bool] + def __init__( + self, d: Mapping[_T, Mapping[_U, _V]], NODE_OK: Callable[[_T], bool], EDGE_OK: Callable[[_T, _T], bool] + ) -> None: ... + def __len__(self): ... + def __iter__(self): ... + def __getitem__(self, node: _T) -> FilterAtlas[_U, _V]: ... + +class FilterMultiInner(FilterAdjacency[_T, _U, _V]): ... +class FilterMultiAdjacency(FilterAdjacency[_T, _U, _V]): ... diff --git a/stubs/networkx/networkx/classes/digraph.pyi b/stubs/networkx/networkx/classes/digraph.pyi new file mode 100644 index 000000000000..e6a0afb41288 --- /dev/null +++ b/stubs/networkx/networkx/classes/digraph.pyi @@ -0,0 +1,52 @@ +from collections.abc import Iterator +from functools import cached_property +from typing import Any +from typing_extensions import Self + +from networkx.classes.coreviews import AdjacencyView +from networkx.classes.graph import Graph, _EdgeData, _Node, _NodeData +from networkx.classes.reportviews import ( + DiDegreeView, + InDegreeView, + InEdgeView, + InMultiDegreeView, + InMultiEdgeView, + OutDegreeView, + OutEdgeView, + OutMultiDegreeView, +) + +__all__ = ["DiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class DiGraph(Graph[_Node, _NodeData, _EdgeData]): + @cached_property + def succ(self) -> AdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def pred(self) -> AdjacencyView[_Node, _Node, dict[str, Any]]: ... + def has_successor(self, u: _Node, v: _Node) -> bool: ... + def has_predecessor(self, u: _Node, v: _Node) -> bool: ... + def successors(self, n: _Node) -> Iterator[_Node]: ... + + neighbors = successors + + def predecessors(self, n: _Node) -> Iterator[_Node]: ... + @cached_property + def edges(self) -> OutEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_edges(self) -> OutEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def in_edges(self) -> InEdgeView[_Node, _NodeData, _EdgeData] | InMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def degree(self) -> DiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def in_degree(self) -> InDegreeView[_Node, _NodeData, _EdgeData] | InMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + # Including subtypes' possible return types for LSP + def out_degree(self) -> OutDegreeView[_Node, _NodeData, _EdgeData] | OutMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, reciprocal: bool = False, as_view: bool = False) -> Graph[_Node, _NodeData, _EdgeData]: ... # type: ignore[override] # Has an additional `reciprocal` keyword argument + def reverse(self, copy: bool = True) -> Self: ... diff --git a/stubs/networkx/networkx/classes/filters.pyi b/stubs/networkx/networkx/classes/filters.pyi new file mode 100644 index 000000000000..c8689991e6f4 --- /dev/null +++ b/stubs/networkx/networkx/classes/filters.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +__all__ = [ + "no_filter", + "hide_nodes", + "hide_edges", + "hide_multiedges", + "hide_diedges", + "hide_multidiedges", + "show_nodes", + "show_edges", + "show_multiedges", + "show_diedges", + "show_multidiedges", +] + +def no_filter(*items): ... +def hide_nodes(nodes): ... +def hide_diedges(edges): ... +def hide_edges(edges): ... +def hide_multidiedges(edges): ... +def hide_multiedges(edges): ... + +class show_nodes: + nodes: Incomplete + def __init__(self, nodes) -> None: ... + def __call__(self, node): ... + +def show_diedges(edges): ... +def show_edges(edges): ... +def show_multidiedges(edges): ... +def show_multiedges(edges): ... diff --git a/stubs/networkx/networkx/classes/function.pyi b/stubs/networkx/networkx/classes/function.pyi new file mode 100644 index 000000000000..17d152c96157 --- /dev/null +++ b/stubs/networkx/networkx/classes/function.pyi @@ -0,0 +1,182 @@ +from _typeshed import Incomplete, SupportsItems, SupportsKeysAndGetItem, Unused +from collections.abc import Callable, Collection, Generator, Hashable, Iterable, Iterator +from typing import Literal, TypeVar, overload + +from networkx import _dispatchable +from networkx.algorithms.planarity import PlanarEmbedding +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _EdgeData, _NBunch, _Node, _NodeData +from networkx.classes.multigraph import MultiGraph + +__all__ = [ + "nodes", + "edges", + "degree", + "degree_histogram", + "neighbors", + "number_of_nodes", + "number_of_edges", + "density", + "is_directed", + "freeze", + "is_frozen", + "subgraph", + "induced_subgraph", + "edge_subgraph", + "restricted_view", + "to_directed", + "to_undirected", + "add_star", + "add_path", + "add_cycle", + "create_empty_copy", + "set_node_attributes", + "get_node_attributes", + "remove_node_attributes", + "set_edge_attributes", + "get_edge_attributes", + "remove_edge_attributes", + "all_neighbors", + "non_neighbors", + "non_edges", + "common_neighbors", + "is_weighted", + "is_negatively_weighted", + "is_empty", + "selfloop_edges", + "nodes_with_selfloops", + "number_of_selfloops", + "path_weight", + "is_path", + "describe", +] + +_U = TypeVar("_U") + +def nodes(G: Graph[_Node]): ... +def edges(G: Graph[_Node], nbunch=None): ... +def degree(G: Graph[_Node], nbunch=None, weight=None): ... +def neighbors(G: Graph[_Node], n): ... +def number_of_nodes(G: Graph[_Node]): ... +def number_of_edges(G: Graph[_Node]): ... +def density(G: Graph[_Node]): ... +def degree_histogram(G: Graph[_Node]) -> list[int]: ... + +@overload +def is_directed(G: PlanarEmbedding[Hashable]) -> Literal[False]: ... # type: ignore[misc] # Incompatible return types +@overload +def is_directed(G: DiGraph[Hashable]) -> Literal[True]: ... # type: ignore[misc] # Incompatible return types +@overload +def is_directed(G: Graph[Hashable]) -> Literal[False]: ... + +def freeze(G: Graph[_Node]): ... +def is_frozen(G: Graph[Incomplete]) -> bool: ... +def add_star(G_to_add_to: Graph[Incomplete], nodes_for_star: Iterable[Incomplete], **attr) -> None: ... +def add_path(G_to_add_to: Graph[Incomplete], nodes_for_path: Iterable[Incomplete], **attr) -> None: ... +def add_cycle(G_to_add_to: Graph[Incomplete], nodes_for_cycle: Iterable[Incomplete], **attr) -> None: ... +def subgraph(G: Graph[_Node], nbunch: Iterable[Incomplete]): ... +def induced_subgraph(G: Graph[_Node, _NodeData, _EdgeData], nbunch: _NBunch[_Node]) -> Graph[_Node, _NodeData, _EdgeData]: ... +def edge_subgraph(G: Graph[_Node], edges: Iterable[Incomplete]) -> Graph[Incomplete]: ... +def restricted_view(G: Graph[_Node], nodes: Iterable[Incomplete], edges: Iterable[Incomplete]) -> Graph[Incomplete]: ... +def to_directed(graph): ... +def to_undirected(graph): ... +def create_empty_copy(G: Graph[_Node], with_data: bool = True): ... + +# incomplete: Can "Any scalar value" be enforced? +@overload +def set_node_attributes( + G: Graph[Hashable], + values: SupportsItems[_Node, Unused], + name: str, + *, + backend=None, # @_dispatchable adds these arguments, but we can't use this decorator with @overload + **backend_kwargs, +) -> None: ... +@overload +def set_node_attributes( + G: Graph[_Node], + values: SupportsItems[_Node, SupportsKeysAndGetItem[Incomplete, Incomplete] | Iterable[tuple[Incomplete, Incomplete]]], + name: None = None, + *, + backend=None, + **backend_kwargs, +) -> None: ... + +@_dispatchable +def get_node_attributes(G: Graph[_Node], name: str, default=None) -> dict[_Node, Incomplete]: ... +@_dispatchable +def remove_node_attributes(G: Graph[_Node], *attr_names, nbunch=None) -> None: ... + +@overload +def set_edge_attributes( + G: Graph[_Node], + values: SupportsItems[tuple[_Node, _Node], Incomplete], + name: str, + *, + backend: str | None = None, # @_dispatchable adds these arguments, but we can't use this decorator with @overload + **backend_kwargs, +) -> None: ... +@overload +def set_edge_attributes( + G: MultiGraph[_Node], + values: dict[tuple[_Node, _Node, Incomplete], Incomplete], + name: str, + *, + backend: str | None = None, + **backend_kwargs, +) -> None: ... +@overload +def set_edge_attributes( + G: Graph[Hashable], values, name: None = None, *, backend: str | None = None, **backend_kwargs +) -> None: ... + +@_dispatchable +def get_edge_attributes(G: Graph[_Node], name: str, default=None) -> dict[tuple[_Node, _Node], Incomplete]: ... +@_dispatchable +def remove_edge_attributes(G: Graph[_Node], *attr_names, ebunch=None) -> None: ... +def all_neighbors(graph: Graph[_Node], node: _Node) -> Iterator[_Node]: ... +def non_neighbors(graph: Graph[_Node], node: _Node) -> Generator[_Node]: ... +def non_edges(graph: Graph[_Node]) -> Generator[tuple[_Node, _Node]]: ... +def common_neighbors(G: Graph[_Node], u: _Node, v: _Node) -> Generator[_Node]: ... +@_dispatchable +def is_weighted(G: Graph[_Node], edge: tuple[_Node, _Node] | None = None, weight: str = "weight") -> bool: ... +@_dispatchable +def is_negatively_weighted(G: Graph[_Node], edge: tuple[_Node, _Node] | None = None, weight: str = "weight") -> bool: ... +@_dispatchable +def is_empty(G: Graph[Hashable]) -> bool: ... +def nodes_with_selfloops(G: Graph[_Node]) -> Generator[_Node]: ... + +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False] = False, keys: Literal[False] = False, default=None +) -> Generator[tuple[_Node, _Node]]: ... +@overload +def selfloop_edges( + G: Graph[_Node, _NodeData, _EdgeData], data: Literal[True], keys: Literal[False] = False, default=None +) -> Generator[tuple[_Node, _Node, _EdgeData]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: str, keys: Literal[False] = False, default: _U | None = None +) -> Generator[tuple[_Node, _Node, _U]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False], keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: Literal[False] = False, *, keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int]]: ... +@overload +def selfloop_edges( + G: Graph[_Node, _NodeData, _EdgeData], data: Literal[True], keys: Literal[True], default=None +) -> Generator[tuple[_Node, _Node, int, _EdgeData]]: ... +@overload +def selfloop_edges( + G: Graph[_Node], data: str, keys: Literal[True], default: _U | None = None +) -> Generator[tuple[_Node, _Node, int, _U]]: ... + +@_dispatchable +def number_of_selfloops(G: Graph[Hashable]) -> int: ... +def is_path(G: Graph[_Node], path: Iterable[Incomplete]) -> bool: ... +def path_weight(G: Graph[_Node], path: Collection[Incomplete], weight: str) -> int: ... +def describe(G: Graph[_Node], describe_hook: Callable[[Graph[_Node]], dict[str, Incomplete]] | None = None) -> None: ... diff --git a/stubs/networkx/networkx/classes/graph.pyi b/stubs/networkx/networkx/classes/graph.pyi new file mode 100644 index 000000000000..a942816e731b --- /dev/null +++ b/stubs/networkx/networkx/classes/graph.pyi @@ -0,0 +1,128 @@ +from collections.abc import Callable, Collection, Hashable, Iterable, Iterator, Mapping, MutableMapping +from decimal import Decimal +from functools import cached_property +from typing import Any, ClassVar, Generic, TypeAlias, TypeVar, overload +from typing_extensions import Self + +import numpy +from networkx.classes.coreviews import AdjacencyView, AtlasView +from networkx.classes.digraph import DiGraph +from networkx.classes.reportviews import DegreeView, DiDegreeView, EdgeView, NodeView, OutEdgeView + +_DataBound: TypeAlias = Mapping[str, Any] + +_Node = TypeVar("_Node", bound=Hashable) +_NodeData = TypeVar("_NodeData", bound=_DataBound, default=dict[str, Any]) +_EdgeData = TypeVar("_EdgeData", bound=_DataBound, default=dict[str, Any]) + +_NodeWithData: TypeAlias = tuple[_Node, _NodeData] +_NodePlus: TypeAlias = _Node | _NodeWithData[_Node, _NodeData] +_Edge: TypeAlias = tuple[_Node, _Node] +_EdgeWithData: TypeAlias = tuple[_Node, _Node, _EdgeData] +_EdgePlus: TypeAlias = _Edge[_Node] | _EdgeWithData[_Node, _EdgeData] +_MapFactory: TypeAlias = Callable[[], MutableMapping[str, Any]] +_NBunch: TypeAlias = _Node | Iterable[_Node] | None +_Data: TypeAlias = ( + Graph[_Node, _NodeData, _EdgeData] + | dict[_Node, dict[_Node, _NodeData]] + | dict[_Node, Iterable[_Node]] + | Iterable[_EdgePlus[_Node, _EdgeData]] + | numpy.ndarray[Any, Any] + # | scipy.sparse.base.spmatrix +) + +__all__ = ["Graph"] + +class Graph(Collection[_Node], Generic[_Node, _NodeData, _EdgeData]): + __networkx_backend__: ClassVar[str] + node_dict_factory: ClassVar[_MapFactory] + node_attr_dict_factory: ClassVar[_MapFactory] + adjlist_outer_dict_factory: ClassVar[_MapFactory] + adjlist_inner_dict_factory: ClassVar[_MapFactory] + edge_attr_dict_factory: ClassVar[_MapFactory] + graph_attr_dict_factory: ClassVar[_MapFactory] + + graph: dict[str, Any] + __networkx_cache__: dict[str, Any] + + def to_directed_class(self) -> type[DiGraph[_Node, _NodeData, _EdgeData]]: ... + def to_undirected_class(self) -> type[Graph[_Node, _NodeData, _EdgeData]]: ... + # @_dispatchable adds `backend` argument, but this decorated is unsupported constructor type here + # and __init__() ignores this argument + def __new__(cls, *args, backend=None, **kwargs) -> Self: ... + def __init__( + self, incoming_graph_data: _Data[_Node, _NodeData, _EdgeData] | None = None, **attr: Any + ) -> None: ... # attr: key=value pairs + @cached_property + def adj(self) -> AdjacencyView[_Node, _Node, _EdgeData]: ... + + # This object is a read-only dict-like structure + @property + def name(self) -> str: ... + @name.setter + def name(self, s: str) -> None: ... + + def __iter__(self) -> Iterator[_Node]: ... + def __contains__(self, n: object) -> bool: ... + def __len__(self) -> int: ... + def __getitem__(self, n: _Node) -> AtlasView[_Node, str, Any]: ... + def add_node(self, node_for_adding: _Node, **attr: Any) -> None: ... # attr: Set or change node attributes using key=value + def add_nodes_from( + self, nodes_for_adding: Iterable[_NodePlus[_Node, _NodeData]], **attr: Any + ) -> None: ... # attr: key=value pairs + def remove_node(self, n: _Node) -> None: ... + def remove_nodes_from(self, nodes: Iterable[_Node]) -> None: ... + @cached_property + def nodes(self) -> NodeView[_Node, _NodeData, _EdgeData]: ... + def number_of_nodes(self) -> int: ... + def order(self) -> int: ... + def has_node(self, n: _Node) -> bool: ... + # Including subtypes' possible return types for LSP + def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Any) -> Hashable | None: ... + # attr: Edge data (or labels or objects) can be assigned using keyword arguments + def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node, _EdgeData]], **attr: Any) -> None: ... + # attr: Edge data (or labels or objects) can be assigned using keyword arguments + def add_weighted_edges_from( + self, ebunch_to_add: Iterable[tuple[_Node, _Node, float | Decimal | None]], weight: str = "weight", **attr: Any + ) -> None: ... + # attr: Edge attributes to add/update for all edges. + def remove_edge(self, u: _Node, v: _Node) -> None: ... + def remove_edges_from(self, ebunch: Iterable[_EdgePlus[_Node, _EdgeData]]) -> None: ... + + @overload + def update(self, edges: Graph[_Node, _NodeData, _EdgeData], nodes: None = None) -> None: ... + @overload + def update( + self, + edges: Graph[_Node, _NodeData, _EdgeData] | Iterable[_EdgePlus[_Node, _EdgeData]] | None = None, + nodes: Iterable[_Node] | None = None, + ) -> None: ... + + def has_edge(self, u: _Node, v: _Node) -> bool: ... + def neighbors(self, n: _Node) -> Iterator[_Node]: ... + @cached_property + # Including subtypes' possible return types for LSP + def edges(self) -> EdgeView[_Node, _NodeData, _EdgeData] | OutEdgeView[_Node, _NodeData, _EdgeData]: ... + def get_edge_data(self, u: _Node, v: _Node, default: Any = None) -> _EdgeData: ... + # default: any Python object + def adjacency(self) -> Iterator[tuple[_Node, dict[_Node, _EdgeData]]]: ... + @cached_property + # Including subtypes' possible return types for LSP + def degree(self) -> DegreeView[_Node, _NodeData, _EdgeData] | DiDegreeView[_Node, _NodeData, _EdgeData]: ... + def clear(self) -> None: ... + def clear_edges(self) -> None: ... + def is_multigraph(self) -> bool: ... + def is_directed(self) -> bool: ... + def copy(self, as_view: bool = False) -> Self: ... + def to_directed(self, as_view: bool = False) -> DiGraph[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, as_view: bool = False) -> Graph[_Node, _NodeData, _EdgeData]: ... + def subgraph(self, nodes: _NBunch[_Node]) -> Self: ... + def edge_subgraph(self, edges: Iterable[_Edge[_Node]]) -> Self: ... + + @overload + def size(self, weight: None = None) -> int: ... + @overload + def size(self, weight: str) -> float: ... + + def number_of_edges(self, u: _Node | None = None, v: _Node | None = None) -> int: ... + def nbunch_iter(self, nbunch: _NBunch[_Node] = None) -> Iterator[_Node]: ... diff --git a/stubs/networkx/networkx/classes/graphviews.pyi b/stubs/networkx/networkx/classes/graphviews.pyi new file mode 100644 index 000000000000..29c42a5191af --- /dev/null +++ b/stubs/networkx/networkx/classes/graphviews.pyi @@ -0,0 +1,62 @@ +from collections.abc import Callable, Hashable +from typing import TypeVar, overload + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _DataBound, _EdgeData, _Node, _NodeData +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.multigraph import MultiGraph + +_G = TypeVar("_G", bound=Graph[Hashable, _DataBound, _DataBound]) +_D = TypeVar("_D", bound=DiGraph[Hashable, _DataBound, _DataBound]) + +__all__ = ["generic_graph_view", "subgraph_view", "reverse_view"] + +@overload +def generic_graph_view(G: _G, create_using: None = None) -> _G: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[MultiDiGraph[_Node, _NodeData, _EdgeData]] +) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[DiGraph[_Node, _NodeData, _EdgeData]] +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[MultiGraph[_Node, _NodeData, _EdgeData]] +) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def generic_graph_view( + G: Graph[_Node, _NodeData, _EdgeData], create_using: type[Graph[_Node, _NodeData, _EdgeData]] +) -> Graph[_Node, _NodeData, _EdgeData]: ... + +@overload +def subgraph_view( + G: MultiDiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node, int], bool] = ..., +) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: MultiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node, int], bool] = ..., +) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: DiGraph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node], bool] = ..., +) -> DiGraph[_Node, _NodeData, _EdgeData]: ... +@overload +def subgraph_view( + G: Graph[_Node, _NodeData, _EdgeData], + *, + filter_node: Callable[[_Node], bool] = ..., + filter_edge: Callable[[_Node, _Node], bool] = ..., +) -> Graph[_Node, _NodeData, _EdgeData]: ... + +def reverse_view(G: _D) -> _D: ... diff --git a/stubs/networkx/networkx/classes/multidigraph.pyi b/stubs/networkx/networkx/classes/multidigraph.pyi new file mode 100644 index 000000000000..324f033ac0e6 --- /dev/null +++ b/stubs/networkx/networkx/classes/multidigraph.pyi @@ -0,0 +1,38 @@ +from functools import cached_property +from typing import Any + +from networkx.classes.coreviews import MultiAdjacencyView +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _EdgeData, _Node, _NodeData +from networkx.classes.multigraph import MultiGraph +from networkx.classes.reportviews import ( + DiMultiDegreeView, + InMultiDegreeView, + InMultiEdgeView, + OutMultiDegreeView, + OutMultiEdgeView, +) + +__all__ = ["MultiDiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class MultiDiGraph(MultiGraph[_Node, _NodeData, _EdgeData], DiGraph[_Node, _NodeData, _EdgeData]): + @cached_property + def succ(self) -> MultiAdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def pred(self) -> MultiAdjacencyView[_Node, _Node, dict[str, Any]]: ... + @cached_property + def edges(self) -> OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_edges(self) -> OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def in_edges(self) -> InMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def degree(self) -> DiMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def in_degree(self) -> InMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + @cached_property + def out_degree(self) -> OutMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, reciprocal: bool = False, as_view: bool = False) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... # type: ignore[override] # Has an additional `reciprocal` keyword argument diff --git a/stubs/networkx/networkx/classes/multigraph.pyi b/stubs/networkx/networkx/classes/multigraph.pyi new file mode 100644 index 000000000000..6d3fcdc56bc3 --- /dev/null +++ b/stubs/networkx/networkx/classes/multigraph.pyi @@ -0,0 +1,62 @@ +from collections.abc import Hashable +from functools import cached_property +from typing import Any, ClassVar, TypeAlias, overload +from typing_extensions import Self, TypeVar + +from networkx.classes.coreviews import MultiAdjacencyView +from networkx.classes.graph import Graph, _EdgeData, _MapFactory, _Node, _NodeData +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.reportviews import DiMultiDegreeView, MultiDegreeView, MultiEdgeView, OutMultiEdgeView + +_MultiEdge: TypeAlias = tuple[_Node, _Node, int] # noqa: Y047 + +_DefaultT = TypeVar("_DefaultT") +_KeyT = TypeVar("_KeyT", bound=Hashable) + +__all__ = ["MultiGraph"] + +# NOTE: Graph subclasses relationships are so complex +# we're only overriding methods that differ in signature from the base classes +# to use inheritance to our advantage and reduce complexity +class MultiGraph(Graph[_Node, _NodeData, _EdgeData]): + edge_key_dict_factory: ClassVar[_MapFactory] + def to_directed_class(self) -> type[MultiDiGraph[_Node, _NodeData, _EdgeData]]: ... + def to_undirected_class(self) -> type[MultiGraph[_Node, _NodeData, _EdgeData]]: ... + # @_dispatchable adds `backend` argument, but this decorated is unsupported constructor type here + # and __init__() ignores this argument + def __new__(cls, *args, backend=None, **kwargs) -> Self: ... + def __init__(self, incoming_graph_data=None, multigraph_input: bool | None = None, **attr: Any) -> None: ... + @cached_property + def adj(self) -> MultiAdjacencyView[_Node, _Node, _EdgeData]: ... # data can be any type + def new_edge_key(self, u: _Node, v: _Node) -> int: ... + + # key : hashable identifier, optional (default=lowest unused integer) + @overload # type: ignore[override] # More complex overload + def add_edge(self, u_for_edge: _Node, v_for_edge: _Node, key: int | None = None, **attr: Any) -> int: ... + @overload + def add_edge(self, u_for_edge: _Node, v_for_edge: _Node, key: _KeyT, **attr: Any) -> _KeyT: ... + + def remove_edge(self, u: _Node, v: _Node, key: Hashable | None = None) -> None: ... + def has_edge(self, u: _Node, v: _Node, key: Hashable | None = None) -> bool: ... + @cached_property + # Including subtypes' possible return types for LSP + def edges(self) -> MultiEdgeView[_Node, _NodeData, _EdgeData] | OutMultiEdgeView[_Node, _NodeData, _EdgeData]: ... + + # key : hashable identifier, optional (default=None). + # default : any Python object (default=None). Value to return if the specific edge (u, v, key) is not found. + # Returns: The edge attribute dictionary. + @overload # type: ignore[override] + def get_edge_data(self, u: _Node, v: _Node, key: Hashable, default: _DefaultT | None = None) -> _EdgeData | _DefaultT: ... + # default : any Python object (default=None). Value to return if there are no edges between u and v and no key is specified. + # Returns: A dictionary mapping edge keys to attribute dictionaries for each of those edges if no specific key is provided. + @overload + def get_edge_data( + self, u: _Node, v: _Node, key: None = None, default: _DefaultT | None = None + ) -> dict[Hashable, _EdgeData | _DefaultT]: ... + + def copy(self, as_view: bool = False) -> Self: ... + @cached_property + # Including subtypes' possible return types for LSP + def degree(self) -> MultiDegreeView[_Node, _NodeData, _EdgeData] | DiMultiDegreeView[_Node, _NodeData, _EdgeData]: ... + def to_directed(self, as_view: bool = False) -> MultiDiGraph[_Node, _NodeData, _EdgeData]: ... + def to_undirected(self, as_view: bool = False) -> MultiGraph[_Node, _NodeData, _EdgeData]: ... diff --git a/stubs/networkx/networkx/classes/reportviews.pyi b/stubs/networkx/networkx/classes/reportviews.pyi new file mode 100644 index 000000000000..a133389f2420 --- /dev/null +++ b/stubs/networkx/networkx/classes/reportviews.pyi @@ -0,0 +1,427 @@ +from _typeshed import Incomplete, Unused +from abc import ABC +from collections.abc import Iterable, Iterator, Mapping, Set as AbstractSet +from typing import Generic, Literal, TypeVar, overload +from typing_extensions import Self + +from networkx.classes.graph import Graph, _Edge, _EdgeData, _NBunch, _Node, _NodeData + +_D = TypeVar("_D") +_U = TypeVar("_U") + +__all__ = [ + "NodeView", + "NodeDataView", + "EdgeView", + "OutEdgeView", + "InEdgeView", + "EdgeDataView", + "OutEdgeDataView", + "InEdgeDataView", + "MultiEdgeView", + "OutMultiEdgeView", + "InMultiEdgeView", + "MultiEdgeDataView", + "OutMultiEdgeDataView", + "InMultiEdgeDataView", + "DegreeView", + "DiDegreeView", + "InDegreeView", + "OutDegreeView", + "MultiDegreeView", + "DiMultiDegreeView", + "InMultiDegreeView", + "OutMultiDegreeView", +] + +class NodeView(Mapping[_Node, _NodeData], AbstractSet[_Node], Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_nodes",) + def __init__(self, graph: Graph[_Node, _NodeData, _EdgeData]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_Node]: ... + def __getitem__(self, n: _Node) -> _NodeData: ... + def __contains__(self, n: object) -> bool: ... + + @overload + def __call__(self, data: Literal[False] = False, default=None) -> Self: ... + @overload + def __call__(self, data: Literal[True] | str, default=None) -> NodeDataView[_Node, _NodeData, _EdgeData]: ... + + @overload + def data(self, data: Literal[False], default=None) -> Self: ... + @overload + def data(self, data: Literal[True] | str = True, default=None) -> NodeDataView[_Node, _NodeData, _EdgeData]: ... + +class NodeDataView(AbstractSet[_Node], Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_nodes", "_data", "_default") + def __init__(self, nodedict: _NodeData, data: bool | str = False, default=None) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, _NodeData]]: ... # type: ignore[override] + def __contains__(self, n: object) -> bool: ... + def __getitem__(self, n: _Node) -> _NodeData | Incomplete: ... + +class DiDegreeView(Generic[_Node, _NodeData, _EdgeData]): + def __init__( + self, G: Graph[_Node, _NodeData, _EdgeData], nbunch: _NBunch[_Node] = None, weight: None | bool | str = None + ) -> None: ... + + @overload # Use this overload first in case _Node=str, since `str` matches `Iterable[str]` + def __call__(self, nbunch: _Node, weight: None | bool | str = None) -> int: ... # type: ignore[overload-overlap] + @overload + def __call__(self, nbunch: Iterable[_Node] | None = None, weight: None | bool | str = None) -> Self: ... + + def __getitem__(self, n: _Node) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, int]]: ... + def __len__(self) -> int: ... + +class DegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class OutDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class InDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class MultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class DiMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class InMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class OutMultiDegreeView(DiDegreeView[_Node, _NodeData, _EdgeData]): ... +class EdgeViewABC(ABC): ... + +class OutEdgeDataView(EdgeViewABC, Generic[_Node, _D]): + __slots__ = ("_viewer", "_nbunch", "_data", "_default", "_adjdict", "_nodes_nbrs", "_report") + def __init__(self, viewer, nbunch: _NBunch[_Node] = None, data: bool = False, *, default=None) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_D]: ... + def __contains__(self, e: _Edge[_Node]) -> bool: ... + +class EdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class InEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class OutMultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = ("keys",) + keys: bool + def __init__( + self, viewer, nbunch: _NBunch[_Node] = None, data: bool = False, *, default=None, keys: bool = False + ) -> None: ... + +class MultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class InMultiEdgeDataView(OutEdgeDataView[_Node, _D]): + __slots__ = () + +class OutEdgeView(AbstractSet[Incomplete], Mapping[Incomplete, Incomplete], EdgeViewABC, Generic[_Node, _NodeData, _EdgeData]): + __slots__ = ("_adjdict", "_graph", "_nodes_nbrs") + def __init__(self, G: Graph[_Node, _NodeData, _EdgeData]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[_Node, _Node]]: ... + def __contains__(self, e: _Edge[_Node]) -> bool: ... # type: ignore[override] + def __getitem__(self, e: _Edge[_Node]) -> _EdgeData: ... + dataview = OutEdgeDataView + + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> OutEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class EdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = EdgeDataView + + # Have to override parent's overloads with the proper return type based on dataview + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> EdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class InEdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = InEdgeDataView + + # Have to override parent's overloads with the proper return type based on dataview + @overload + def __call__(self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None) -> Self: ... # type: ignore[overload-overlap] + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None) -> Self: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None + ) -> InEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + +class OutMultiEdgeView(OutEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + def __iter__(self) -> Iterator[tuple[_Node, _Node, Incomplete]]: ... # type: ignore[override] + def __getitem__(self, e: tuple[_Node, _Node, Incomplete]) -> _EdgeData: ... # type: ignore[override] + dataview = OutMultiEdgeDataView + + @overload # type: ignore[override] # Has an additional `keys` keyword argument + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> OutMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + +class MultiEdgeView(OutMultiEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = MultiEdgeDataView # type: ignore[assignment] + + # Have to override parent's overloads with the proper return type based on dataview + @overload # type: ignore[override] # Has an additional `keys` keyword argument + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> MultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + +class InMultiEdgeView(OutMultiEdgeView[_Node, _NodeData, _EdgeData]): + __slots__ = () + dataview = InMultiEdgeDataView # type: ignore[assignment] + + # Have to override parent's overloads with the proper return type based on dataview + @overload # type: ignore[override] + def __call__( # type: ignore[overload-overlap] + self, nbunch: None = None, data: Literal[False] = False, *, default: Unused = None, keys: Literal[True] + ) -> Self: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, data: Literal[False] = False, *, default: None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def __call__( + self, nbunch: _Node | Iterable[_Node], data: Literal[False] = False, *, default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: Literal[True], *, default: None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: Literal[True], default: None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node], data: str, *, default: _U | None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... + @overload + def __call__( + self, nbunch: _NBunch[_Node] = None, *, data: str, default: _U | None = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + + @overload # type: ignore[override] + def data(self, data: Literal[False], default: Unused = None, nbunch: None = None, *, keys: Literal[True]) -> Self: ... + @overload + def data( + self, data: Literal[False], default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _EdgeData]]: ... + @overload + def data( + self, data: Literal[True] = True, default: None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _EdgeData]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, keys: Literal[False] = False + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, _U]]: ... + @overload + def data( + self, data: str, default: _U | None = None, nbunch: _NBunch[_Node] = None, *, keys: Literal[True] + ) -> InMultiEdgeDataView[_Node, tuple[_Node, _Node, Incomplete, _U]]: ... diff --git a/stubs/networkx/networkx/convert.pyi b/stubs/networkx/networkx/convert.pyi new file mode 100644 index 000000000000..b6bd41f09185 --- /dev/null +++ b/stubs/networkx/networkx/convert.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Iterable + +from networkx.classes.graph import Graph, _Data, _EdgeData, _Node, _NodeData +from networkx.utils.backends import _dispatchable + +__all__ = [ + "to_networkx_graph", + "from_dict_of_dicts", + "to_dict_of_dicts", + "from_dict_of_lists", + "to_dict_of_lists", + "from_edgelist", + "to_edgelist", +] + +def to_networkx_graph( + data: _Data[_Node], + create_using: Graph[_Node, _NodeData, _EdgeData] | Callable[[], Graph[_Node, _NodeData, _EdgeData]] | None = None, + multigraph_input: bool = False, +) -> Graph[_Node, _NodeData, _EdgeData]: ... +@_dispatchable +def to_dict_of_lists(G: Graph[_Node], nodelist: Collection[_Node] | None = None) -> dict[_Node, list[_Node]]: ... +@_dispatchable +def from_dict_of_lists( + d: dict[_Node, Iterable[_Node]], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[_Node]: ... +def to_dict_of_dicts( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, edge_data: float | None = None +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def from_dict_of_dicts( + d: dict[Incomplete, Incomplete], + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + multigraph_input: bool = False, +) -> Graph[Incomplete]: ... +@_dispatchable +def to_edgelist(G: Graph[_Node], nodelist: Collection[_Node] | None = None): ... +@_dispatchable +def from_edgelist( + edgelist: Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/convert_matrix.pyi b/stubs/networkx/networkx/convert_matrix.pyi new file mode 100644 index 000000000000..98179313bcea --- /dev/null +++ b/stubs/networkx/networkx/convert_matrix.pyi @@ -0,0 +1,119 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Hashable, Iterable +from typing import Literal, TypeAlias, TypeVar, overload + +import numpy +import numpy as np +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +# stub_uploader won't allow pandas-stubs in the requires field https://github.com/typeshed-internal/stub_uploader/issues/90 +# from pandas import DataFrame +_DataFrame: TypeAlias = Incomplete +# from pandas.core.dtypes.base import ExtensionDtype +_ExtensionDtype: TypeAlias = Incomplete +# pandas._typing import Axes +# _Axes: TypeAlias = Index | Series | np.ndarray | list | dict | range | tuple +_Axes: TypeAlias = Collection[_Node] +_G = TypeVar("_G", bound=Graph[Hashable]) + +__all__ = [ + "from_pandas_adjacency", + "to_pandas_adjacency", + "from_pandas_edgelist", + "to_pandas_edgelist", + "from_scipy_sparse_array", + "to_scipy_sparse_array", + "from_numpy_array", + "to_numpy_array", +] + +@_dispatchable +def to_pandas_adjacency( + G: Graph[_Node], + nodelist: _Axes[_Node] | None = None, + dtype: numpy.dtype[Incomplete] | None = None, + order: numpy._OrderCF = None, + multigraph_weight: Callable[[list[float]], float] = ..., + weight: str = "weight", + nonedge: float = 0.0, +) -> _DataFrame: ... + +@overload +def from_pandas_adjacency(df: _DataFrame, create_using: type[_G]) -> _G: ... +@overload +def from_pandas_adjacency(df: _DataFrame, create_using: None = None) -> Graph[Incomplete]: ... + +@_dispatchable +def to_pandas_edgelist( + G: Graph[_Node], + source: str | int = "source", + target: str | int = "target", + nodelist: Iterable[_Node] | None = None, + dtype: _ExtensionDtype | None = None, + edge_key: str | int | None = None, +) -> _DataFrame: ... + +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int, + target: str | int, + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None, + create_using: type[_G], + edge_key: str | None = None, +) -> _G: ... +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int = "source", + target: str | int = "target", + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None = None, + *, + create_using: type[_G], + edge_key: str | None = None, +) -> _G: ... +@overload +def from_pandas_edgelist( + df: _DataFrame, + source: str | int = "source", + target: str | int = "target", + edge_attr: str | int | list[str | int] | tuple[str | int] | Literal[True] | None = None, + create_using: None = None, + edge_key: str | None = None, +) -> Graph[Incomplete]: ... + +@_dispatchable +def to_scipy_sparse_array( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + dtype: np.dtype[Incomplete] | None = None, + weight: str | None = "weight", + format: str = "csr", +): ... +@_dispatchable +def from_scipy_sparse_array( + A, + parallel_edges: bool = False, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + edge_attribute: str = "weight", +): ... +@_dispatchable +def to_numpy_array( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + dtype: numpy.dtype[Incomplete] | None = None, + order: numpy._OrderCF = None, + multigraph_weight: Callable[[list[float]], float] = ..., + weight: str = "weight", + nonedge: float = 0.0, +) -> numpy.ndarray[Incomplete, numpy.dtype[Incomplete]]: ... + +@overload +def from_numpy_array( + A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool = False, create_using: None = None +) -> Graph[Incomplete]: ... +@overload +def from_numpy_array(A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool = False, *, create_using: type[_G]) -> _G: ... +@overload +def from_numpy_array(A: numpy.ndarray[Incomplete, Incomplete], parallel_edges: bool, create_using: type[_G]) -> _G: ... diff --git a/stubs/networkx/networkx/drawing/__init__.pyi b/stubs/networkx/networkx/drawing/__init__.pyi new file mode 100644 index 000000000000..ce16049ef6fa --- /dev/null +++ b/stubs/networkx/networkx/drawing/__init__.pyi @@ -0,0 +1,4 @@ +from . import nx_agraph as nx_agraph, nx_pydot as nx_pydot +from .layout import * +from .nx_latex import * +from .nx_pylab import * diff --git a/stubs/networkx/networkx/drawing/layout.pyi b/stubs/networkx/networkx/drawing/layout.pyi new file mode 100644 index 000000000000..0ecb4a6d4289 --- /dev/null +++ b/stubs/networkx/networkx/drawing/layout.pyi @@ -0,0 +1,158 @@ +from collections.abc import Collection, Mapping +from typing import Any, Literal, TypeAlias + +import numpy as np +from networkx._typing import Array1D, Array2D, ArrayLike1D, Seed +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.typing import NDArray + +__all__ = [ + "bipartite_layout", + "circular_layout", + "forceatlas2_layout", + "kamada_kawai_layout", + "random_layout", + "rescale_layout", + "rescale_layout_dict", + "shell_layout", + "spring_layout", + "spectral_layout", + "planar_layout", + "fruchterman_reingold_layout", + "spiral_layout", + "multipartite_layout", + "bfs_layout", + "arf_layout", +] + +_FloatArrayLike1D: TypeAlias = ArrayLike1D[float, np.number[Any]] # Any because we don't care about the bit base + +def random_layout( + G: Graph[_Node], + center: _FloatArrayLike1D | None = None, + dim: int = 2, + seed: Seed | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +def circular_layout( + G: Graph[_Node], scale: float = 1, center: _FloatArrayLike1D | None = None, dim: int = 2, store_pos_as: str | None = None +) -> dict[_Node, Array1D[np.float64]]: ... +def shell_layout( + G: Graph[_Node], + nlist: Collection[Collection[_Node]] | None = None, + rotate: float | None = None, + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def bipartite_layout( + G: Graph[_Node], + nodes: Collection[_Node] | None = None, + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + aspect_ratio: float = ..., + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def spring_layout( + G: Graph[_Node], + k: float | None = None, + pos: Mapping[_Node, Collection[float]] | None = None, + fixed: Collection[_Node] | None = None, + iterations: int = 50, + threshold: float = 0.0001, + weight: str | None = "weight", + scale: float | None = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + seed: Seed | None = None, + store_pos_as: str | None = None, + *, + method: Literal["auto", "force", "energy"] = "auto", + gravity: float = 1.0, +) -> dict[_Node, Array1D[np.float64]]: ... + +fruchterman_reingold_layout = spring_layout + +def kamada_kawai_layout( + G: Graph[_Node], + dist: Mapping[_Node, Mapping[_Node, float]] | None = None, + pos: Mapping[_Node, Collection[float]] | None = None, + weight: str | None = "weight", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def spectral_layout( + G: Graph[_Node], + weight: str | None = "weight", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def planar_layout( + G: Graph[_Node], scale: float = 1, center: _FloatArrayLike1D | None = None, dim: int = 2, store_pos_as: str | None = None +) -> dict[_Node, Array1D[np.float64]]: ... +def spiral_layout( + G: Graph[_Node], + scale: float = 1, + center: _FloatArrayLike1D | None = None, + dim: int = 2, + resolution: float = 0.35, + equidistant: bool = False, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def multipartite_layout( + G: Graph[_Node], + subset_key: str | Mapping[Any, Collection[_Node]] = "subset", # layers can be "any" hashable + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... +def arf_layout( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]] | None = None, + scaling: float = 1, + a: float = 1.1, + etol: float = 1e-06, + dt: float = 0.001, + max_iter: int = 1000, + *, + seed: Seed | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +@_dispatchable +def forceatlas2_layout( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]] | None = None, + *, + max_iter: int = 100, + jitter_tolerance: float = 1.0, + scaling_ratio: float = 2.0, + gravity: float = 1.0, + distributed_action: bool = False, + strong_gravity: bool = False, + node_mass: Mapping[_Node, float] | None = None, + node_size: Mapping[_Node, float] | None = None, + weight: str | None = None, + linlog: bool = False, + seed: Seed | None = None, + dim: int = 2, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float32]]: ... +def rescale_layout(pos: NDArray[np.number[Any]], scale: float = 1) -> Array2D[np.float64]: ... # ignore the bit base +def rescale_layout_dict(pos: Mapping[_Node, Collection[float]], scale: float = 1) -> dict[_Node, Array1D[np.float64]]: ... +def bfs_layout( + G: Graph[_Node], + start: _Node, + *, + align: Literal["vertical", "horizontal"] = "vertical", + scale: float = 1, + center: _FloatArrayLike1D | None = None, + store_pos_as: str | None = None, +) -> dict[_Node, Array1D[np.float64]]: ... diff --git a/stubs/networkx/networkx/drawing/nx_agraph.pyi b/stubs/networkx/networkx/drawing/nx_agraph.pyi new file mode 100644 index 000000000000..d3de4c55aae5 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_agraph.pyi @@ -0,0 +1,45 @@ +from _typeshed import OpenBinaryModeUpdating, OpenTextModeReading, OpenTextModeWriting, SupportsWrite +from collections.abc import Callable +from typing import IO, Any, Protocol, TypeVar, type_check_only + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from pygraphviz.agraph import AGraph # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +__all__ = ["from_agraph", "to_agraph", "write_dot", "read_dot", "graphviz_layout", "pygraphviz_layout", "view_pygraphviz"] + +_ModeT_contra = TypeVar("_ModeT_contra", bound=str, contravariant=True) +_FileT_co = TypeVar("_FileT_co", covariant=True) + +@type_check_only +class _SupportsOpen(Protocol[_ModeT_contra, _FileT_co]): + def open(self, *, mode: _ModeT_contra) -> _FileT_co: ... + +@_dispatchable +def from_agraph( + A: AGraph, create_using: Graph[str] | type[Graph[str]] | None = None # TODO: add overloads on `create_using` +) -> Graph[str]: ... +def to_agraph(N: Graph[_Node]) -> AGraph: ... +def write_dot( + G: Graph[_Node], path: str | IO[str] | IO[bytes] | _SupportsOpen[OpenTextModeWriting, IO[str] | IO[bytes]] +) -> None: ... +@_dispatchable +def read_dot(path: str | IO[str] | IO[bytes] | _SupportsOpen[OpenTextModeReading, IO[str] | IO[bytes]]) -> Graph[str]: ... +def graphviz_layout( + G: Graph[_Node], prog: str = "neato", root: str | None = None, args: str = "" +) -> dict[_Node, tuple[float, float]]: ... +def pygraphviz_layout( + G: Graph[_Node], prog: str = "neato", root: str | None = None, args: str = "" +) -> dict[_Node, tuple[float, float]]: ... +def view_pygraphviz( + G: Graph[_Node], + # From implementation looks like Callable could return object since it's always immediately stringified + # But judging by documentation this seems like an extra runtime safety thing and not intended + # Leaving as str unless anyone reports a valid use-case + edgelabel: str | Callable[[dict[str, Any]], str] | None = None, + prog: str = "dot", + args: str = "", + suffix: str = "", + path: str | SupportsWrite[bytes] | _SupportsOpen[OpenBinaryModeUpdating, SupportsWrite[bytes]] | None = None, + show: bool = True, +) -> tuple[str, AGraph]: ... diff --git a/stubs/networkx/networkx/drawing/nx_latex.pyi b/stubs/networkx/networkx/drawing/nx_latex.pyi new file mode 100644 index 000000000000..07639af60021 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_latex.pyi @@ -0,0 +1,70 @@ +from _typeshed import StrPath, SupportsWrite +from collections.abc import Collection +from typing import TypeAlias, TypeVar + +from networkx.classes.graph import Graph, _Node + +__all__ = ["to_latex_raw", "to_latex", "write_latex"] + +# runtime requires a dict but it doesn't mutate it, we use a bounded typevar as +# a values type to make type checkers treat the dict covariantely +_PosT = TypeVar("_PosT", bound=Collection[float] | str) +_Pos: TypeAlias = str | dict[_Node, _PosT] + +def to_latex_raw( + G: Graph[_Node], + pos: _Pos[_Node, _PosT] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", +) -> str: ... +def to_latex( + Gbunch: Graph[_Node] | Collection[Graph[_Node]], + pos: _Pos[_Node, _PosT] | Collection[_Pos[_Node, _PosT]] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "node_label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "edge_label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", + caption: str = "", + latex_label: str = "", + sub_captions: Collection[str] | None = None, + sub_labels: Collection[str] | None = None, + n_rows: int = 1, + as_document: bool = True, + document_wrapper: str = ..., + figure_wrapper: str = ..., + subfigure_wrapper: str = ..., +) -> str: ... +def write_latex( + Gbunch: Graph[_Node] | Collection[Graph[_Node]], + path: StrPath | SupportsWrite[str], + *, + # **options passed to `to_latex` + pos: _Pos[_Node, _PosT] | Collection[_Pos[_Node, _PosT]] = "pos", + tikz_options: str = "", + default_node_options: str = "", + node_options: str | dict[_Node, str] = "node_options", + node_label: str | dict[_Node, str] = "node_label", + default_edge_options: str = "", + edge_options: str | dict[tuple[_Node, _Node], str] = "edge_options", + edge_label: str | dict[tuple[_Node, _Node], str] = "edge_label", + edge_label_options: str | dict[tuple[_Node, _Node], str] = "edge_label_options", + caption: str = "", + latex_label: str = "", + sub_captions: Collection[str] | None = None, + sub_labels: Collection[str] | None = None, + n_rows: int = 1, + as_document: bool = True, + document_wrapper: str = ..., + figure_wrapper: str = ..., + subfigure_wrapper: str = ..., +) -> None: ... diff --git a/stubs/networkx/networkx/drawing/nx_pydot.pyi b/stubs/networkx/networkx/drawing/nx_pydot.pyi new file mode 100644 index 000000000000..fa0cb03f9944 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_pydot.pyi @@ -0,0 +1,18 @@ +from _typeshed import SupportsRead, SupportsWrite +from os import PathLike +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from pydot import Dot # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +__all__ = ["write_dot", "read_dot", "graphviz_layout", "pydot_layout", "to_pydot", "from_pydot"] + +def write_dot(G: Graph[_Node], path: str | PathLike[Any] | SupportsWrite[str]) -> None: ... +@_dispatchable +def read_dot(path: str | PathLike[Any] | SupportsRead[str]) -> Graph[str]: ... +@_dispatchable +def from_pydot(P: Dot) -> Graph[str]: ... +def to_pydot(N: Graph[_Node]) -> Dot: ... +def graphviz_layout(G: Graph[_Node], prog: str = "neato", root: _Node | None = None) -> dict[_Node, tuple[float, float]]: ... +def pydot_layout(G: Graph[_Node], prog: str = "neato", root: _Node | None = None) -> dict[_Node, tuple[float, float]]: ... diff --git a/stubs/networkx/networkx/drawing/nx_pylab.pyi b/stubs/networkx/networkx/drawing/nx_pylab.pyi new file mode 100644 index 000000000000..34c40c5f5f67 --- /dev/null +++ b/stubs/networkx/networkx/drawing/nx_pylab.pyi @@ -0,0 +1,376 @@ +from _typeshed import Incomplete, SupportsItems +from collections.abc import Callable, Collection, Hashable, Iterable, Mapping, Sequence +from typing import Any, Generic, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +import numpy as np +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.collections import LineCollection, PathCollection # type: ignore[import-not-found] +from matplotlib.colors import Colormap # type: ignore[import-not-found] +from matplotlib.patches import FancyArrowPatch # type: ignore[import-not-found] +from matplotlib.text import Text # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node + +__all__ = [ + "display", + "apply_matplotlib_colors", + "draw", + "draw_networkx", + "draw_networkx_nodes", + "draw_networkx_edges", + "draw_networkx_labels", + "draw_networkx_edge_labels", + "draw_bipartite", + "draw_circular", + "draw_kamada_kawai", + "draw_random", + "draw_spectral", + "draw_spring", + "draw_planar", + "draw_shell", + "draw_forceatlas2", +] + +_G = TypeVar("_G", bound=Graph[Any]) + +# types from matplotlib +_FontSize: TypeAlias = Literal["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"] | float +_FontWeight: TypeAlias = ( + Literal[ + "ultralight", + "light", + "normal", + "regular", + "book", + "medium", + "roman", + "semibold", + "demibold", + "demi", + "bold", + "heavy", + "extra bold", + "black", + ] + | int +) +_HAlign: TypeAlias = Literal["left", "center", "right"] +_VAlign: TypeAlias = Literal["baseline", "bottom", "center", "center_baseline", "top"] + +@type_check_only +class _DrawNetworkxKwds(TypedDict, Generic[_Node], total=False): + # draw nodes keywords; keep in sync with draw_networkx_nodes + node_color: ColorType | Collection[ColorType] | Collection[float] + cmap: str | Colormap | None + vmin: float | None + vmax: float | None + linewidths: float | Collection[float] | None + edgecolors: Literal["face", "none"] | ColorType | Collection[ColorType] | Collection[float] | None + margins: float | tuple[float, float] | None + # draw edges keywords; keep in sync with draw_networkx_edges + edgelist: Collection[_Node | Hashable] | None # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] + edge_color: ColorType | Collection[ColorType] + style: str | Collection[str] + arrowstyle: str | Collection[str] | None + arrowsize: float | list[int] | list[float] + edge_cmap: Colormap | None + edge_vmin: float | None + edge_vmax: float | None + connectionstyle: str | Iterable[str] + min_source_margin: int | Collection[int] + min_target_margin: int | Collection[int] + # draw labels keywords; keep in sync with draw_networkx_labels + labels: Mapping[_Node, object] | None + font_size: _FontSize | Mapping[_Node, _FontSize] + font_color: ColorType | Mapping[_Node, Colormap] + font_family: str | Mapping[_Node, str] + font_weight: _FontWeight | Mapping[_Node, _FontWeight] + bbox: dict[str, Any] | None + horizontalalignment: _HAlign + verticalalignment: _VAlign + clip_on: bool + # common keywords + nodelist: Sequence[_Node] | None + node_size: float | Collection[float] + node_shape: str + alpha: float | Collection[float] | None + label: str | None + hide_ticks: bool + +def apply_matplotlib_colors( + G: Graph[_Node], + src_attr: str, + dest_attr: str, + map: str | Colormap, + vmin: float | None = None, + vmax: float | None = None, + nodes: bool = True, +) -> None: ... + +class CurvedArrowTextBase: + arrow: FancyArrowPatch + label_pos: float + labels_horizontal: bool + ax: Axes + x: Incomplete + y: Incomplete + angle: Incomplete + def __init__( + self, + arrow: FancyArrowPatch, + *args, + label_pos: float = 0.5, + labels_horizontal: bool = False, + ax: Axes | None = None, + **kwargs, + ) -> None: ... + def draw(self, renderer) -> None: ... + +def display( + G: _G, + canvas: Axes | None = None, + *, + pos: str | Callable[[_G], Mapping[_Node, Collection[float]]] = ..., + node_visible: str | bool = ..., + node_color: str = ..., + node_size: str | float = ..., + node_label: str | bool = ..., + node_shape: str = ..., + node_alpha: str = ..., + node_border_width: str = ..., + node_border_color: str = ..., + edge_visible: str | bool = ..., + edge_width: str | int = ..., + edge_color: str | ColorType = ..., + edge_label: str = ..., + edge_style: str = ..., + edge_alpha: str | float = ..., + arrowstyle: str = ..., + arrowsize: str | int = ..., + edge_curvature: str = ..., + edge_source_margin: str | int = ..., + edge_target_margin: str | int = ..., + hide_ticks: bool = True, +) -> _G: ... +def draw( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]] | None = None, + ax: Axes | None = None, + *, + with_labels: bool = ..., # default depends on whether a label argument is passed + **kwds: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_networkx( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]] | None = None, + arrows: bool | None = None, + with_labels: bool = True, + *, + ax: Axes | None = None, + **kwds: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_networkx_nodes( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + nodelist: Collection[_Node] | None = None, + node_size: float | Collection[float] = 300, + node_color: ColorType | Collection[ColorType] | Collection[float] = "#1f78b4", + node_shape: str = "o", + alpha: float | Collection[float] | None = None, + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, + ax: Axes | None = None, + linewidths: float | Collection[float] | None = None, + edgecolors: Literal["face", "none"] | ColorType | Collection[ColorType] | Collection[float] | None = None, + label: str | None = None, + margins: float | tuple[float, float] | None = None, + hide_ticks: bool = True, +) -> PathCollection: ... + +@overload # arrows=None -> LineCollection if G is undirected, list[FancyArrowPatch] if G is directed +def draw_networkx_edges( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: None = None, + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> LineCollection | list[FancyArrowPatch]: ... +@overload # directed graph and arrows=None -> list[FancyArrowPatch] +def draw_networkx_edges( + G: DiGraph[_Node], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: None = None, + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> list[FancyArrowPatch]: ... +@overload # arrows=True -> list[FancyArrowPatch] +def draw_networkx_edges( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + arrowstyle: str | Collection[str] | None = None, + arrowsize: float | list[int] | list[float] = 10, # documented as int, mpl accepts float + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + *, + arrows: Literal[True], + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + connectionstyle: str | Iterable[str] = "arc3", + min_source_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + min_target_margin: int | Collection[int] = 0, # documented as int, mpl accepts float + hide_ticks: bool = True, +) -> list[FancyArrowPatch]: ... +@overload # arrows=False -> LineCollection +def draw_networkx_edges( + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + edgelist: Collection[_Node | Hashable] | None = None, # (u, v, k) for multigraphs and (u, v) for simple graphs + width: float | Collection[float] = 1.0, + edge_color: ColorType | Collection[ColorType] = "k", + style: str | Collection[str] = "solid", + alpha: float | Collection[float] | None = None, + *, + edge_cmap: Colormap | None = None, + edge_vmin: float | None = None, + edge_vmax: float | None = None, + ax: Axes | None = None, + arrows: Literal[False], + label: str | None = None, # documented as str, mpl accepts any object as it calls str on it + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + node_shape: str = "o", + hide_ticks: bool = True, +) -> LineCollection: ... + +def draw_networkx_labels( # keep in sync with _DrawNetworkxKwds above + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + labels: Mapping[_Node, object] | None = None, # labels are explicitly converted to str + font_size: _FontSize | Mapping[_Node, _FontSize] = 12, + font_color: ColorType | Mapping[_Node, Colormap] = "k", + font_family: str | Mapping[_Node, str] = "sans-serif", + font_weight: _FontWeight | Mapping[_Node, _FontWeight] = "normal", + alpha: float | Mapping[_Node, float] | None = None, + bbox: dict[str, Any] | None = None, # Any comes from mpl + horizontalalignment: _HAlign = "center", # doc is wrong, doesn't really accept array + verticalalignment: _VAlign = "center", # doc is wrong, doesn't really accept array + ax: Axes | None = None, + clip_on: bool = True, + hide_ticks: bool = True, +) -> dict[_Node, Text]: ... +def draw_networkx_edge_labels( + # TODO: find a way to have a covariant list for params annotated with `something | list[Incomplete]` + G: Graph[_Node], + pos: Mapping[_Node, Collection[float]], + edge_labels: ( + SupportsItems[ + Collection[_Node | Hashable], # (u, v, k) for multigraphs and (u, v) for simple graphs + object, # labels are explicitly converted to str and nx internally passes non-str + ] + | None + ) = None, + label_pos: float | list[Incomplete] = 0.5, + font_size: _FontSize | list[Incomplete] = 10, + font_color: ColorType | list[Incomplete] = "k", + font_family: str = "sans-serif", + font_weight: _FontWeight | list[Incomplete] = "normal", + alpha: float | list[Incomplete] | None = None, + bbox: dict[str, Any] | None = None, # Any comes from mpl + horizontalalignment: _HAlign | list[Incomplete] = "center", + verticalalignment: _VAlign | list[Incomplete] = "center", + ax: Axes | None = None, + rotate: bool | list[bool] = True, + clip_on: bool = True, + node_size: float | Collection[float] = 300, + nodelist: Sequence[_Node] | None = None, + connectionstyle: str | Iterable[str] = "arc3", + hide_ticks: bool = True, +) -> dict[tuple[_Node, _Node] | tuple[_Node, _Node, Any], Text]: ... # Any is for multigraph key +def draw_bipartite( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_circular( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_kamada_kawai( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_random( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_spectral( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_spring( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_shell( + G: Graph[_Node], + nlist: Collection[Collection[_Node]] | None = None, + *, + ax: Axes | None = None, + with_labels: bool = ..., + **kwargs: Unpack[_DrawNetworkxKwds[_Node]], +) -> None: ... +def draw_planar( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def draw_forceatlas2( + G: Graph[_Node], *, ax: Axes | None = None, with_labels: bool = ..., **kwargs: Unpack[_DrawNetworkxKwds[_Node]] +) -> None: ... +def apply_alpha( + colors: ColorType | Collection[ColorType] | Collection[float], + alpha: float | Collection[float], + elem_list: Collection[object], # nx objects (nodes, edges, labels) but its content is not used! + cmap: str | Colormap | None = None, + vmin: float | None = None, + vmax: float | None = None, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/exception.pyi b/stubs/networkx/networkx/exception.pyi new file mode 100644 index 000000000000..c1ebc86eee91 --- /dev/null +++ b/stubs/networkx/networkx/exception.pyi @@ -0,0 +1,33 @@ +__all__ = [ + "HasACycle", + "NodeNotFound", + "PowerIterationFailedConvergence", + "ExceededMaxIterations", + "AmbiguousSolution", + "NetworkXAlgorithmError", + "NetworkXException", + "NetworkXError", + "NetworkXNoCycle", + "NetworkXNoPath", + "NetworkXNotImplemented", + "NetworkXPointlessConcept", + "NetworkXUnbounded", + "NetworkXUnfeasible", +] + +class NetworkXException(Exception): ... +class NetworkXError(NetworkXException): ... +class NetworkXPointlessConcept(NetworkXException): ... +class NetworkXAlgorithmError(NetworkXException): ... +class NetworkXUnfeasible(NetworkXAlgorithmError): ... +class NetworkXNoPath(NetworkXUnfeasible): ... +class NetworkXNoCycle(NetworkXUnfeasible): ... +class HasACycle(NetworkXException): ... +class NetworkXUnbounded(NetworkXAlgorithmError): ... +class NetworkXNotImplemented(NetworkXException): ... +class NodeNotFound(NetworkXException): ... +class AmbiguousSolution(NetworkXException): ... +class ExceededMaxIterations(NetworkXException): ... + +class PowerIterationFailedConvergence(ExceededMaxIterations): + def __init__(self, num_iterations, *args, **kw) -> None: ... diff --git a/stubs/networkx/networkx/generators/__init__.pyi b/stubs/networkx/networkx/generators/__init__.pyi new file mode 100644 index 000000000000..878faee7cacc --- /dev/null +++ b/stubs/networkx/networkx/generators/__init__.pyi @@ -0,0 +1,29 @@ +from networkx.generators.atlas import * +from networkx.generators.classic import * +from networkx.generators.cographs import * +from networkx.generators.community import * +from networkx.generators.degree_seq import * +from networkx.generators.directed import * +from networkx.generators.duplication import * +from networkx.generators.ego import * +from networkx.generators.expanders import * +from networkx.generators.geometric import * +from networkx.generators.harary_graph import * +from networkx.generators.internet_as_graphs import * +from networkx.generators.intersection import * +from networkx.generators.interval_graph import * +from networkx.generators.joint_degree_seq import * +from networkx.generators.lattice import * +from networkx.generators.line import * +from networkx.generators.mycielski import * +from networkx.generators.nonisomorphic_trees import * +from networkx.generators.random_clustered import * +from networkx.generators.random_graphs import * +from networkx.generators.small import * +from networkx.generators.social import * +from networkx.generators.spectral_graph_forge import * +from networkx.generators.stochastic import * +from networkx.generators.sudoku import * +from networkx.generators.time_series import * +from networkx.generators.trees import * +from networkx.generators.triads import * diff --git a/stubs/networkx/networkx/generators/atlas.pyi b/stubs/networkx/networkx/generators/atlas.pyi new file mode 100644 index 000000000000..a17a5a5b24d8 --- /dev/null +++ b/stubs/networkx/networkx/generators/atlas.pyi @@ -0,0 +1,22 @@ +import sys +from _typeshed import Incomplete +from typing import Final + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: + from importlib.abc import Traversable + +__all__ = ["graph_atlas", "graph_atlas_g"] + +NUM_GRAPHS: Final = 1253 +ATLAS_FILE: Final[Traversable] + +@_dispatchable +def graph_atlas(i: int) -> Graph[Incomplete]: ... +@_dispatchable +def graph_atlas_g() -> list[Graph[Incomplete]]: ... diff --git a/stubs/networkx/networkx/generators/classic.pyi b/stubs/networkx/networkx/generators/classic.pyi new file mode 100644 index 000000000000..bd070af62575 --- /dev/null +++ b/stubs/networkx/networkx/generators/classic.pyi @@ -0,0 +1,88 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "balanced_tree", + "barbell_graph", + "binomial_tree", + "complete_graph", + "complete_multipartite_graph", + "circular_ladder_graph", + "circulant_graph", + "cycle_graph", + "dorogovtsev_goltsev_mendes_graph", + "empty_graph", + "full_rary_tree", + "kneser_graph", + "ladder_graph", + "lollipop_graph", + "null_graph", + "path_graph", + "star_graph", + "tadpole_graph", + "trivial_graph", + "turan_graph", + "wheel_graph", +] + +@_dispatchable +def full_rary_tree( + r: int, n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def kneser_graph(n: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def balanced_tree( + r: int, h: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def barbell_graph( + m1: int, m2: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def binomial_tree(n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def complete_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def circular_ladder_graph(n, create_using=None): ... +@_dispatchable +def circulant_graph( + n: int, offsets: list[int], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def cycle_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def dorogovtsev_goltsev_mendes_graph( + n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def empty_graph( + n: Incomplete | int = 0, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + default: type[Graph[Incomplete]] = ..., +): ... +@_dispatchable +def ladder_graph(n, create_using=None): ... +@_dispatchable +def lollipop_graph(m, n, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def null_graph(create_using=None): ... +@_dispatchable +def path_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def star_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def tadpole_graph( + m, n, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete] | Incomplete: ... +@_dispatchable +def trivial_graph(create_using=None): ... +@_dispatchable +def turan_graph(n: int, r: int): ... +@_dispatchable +def wheel_graph(n: int | Iterable[Incomplete], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def complete_multipartite_graph(*subset_sizes) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/cographs.pyi b/stubs/networkx/networkx/generators/cographs.pyi new file mode 100644 index 000000000000..53238e9fe20a --- /dev/null +++ b/stubs/networkx/networkx/generators/cographs.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["random_cograph"] + +@_dispatchable +def random_cograph(n: int, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/community.pyi b/stubs/networkx/networkx/generators/community.pyi new file mode 100644 index 000000000000..e3c9f38ada20 --- /dev/null +++ b/stubs/networkx/networkx/generators/community.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Collection + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "caveman_graph", + "connected_caveman_graph", + "relaxed_caveman_graph", + "random_partition_graph", + "planted_partition_graph", + "gaussian_random_partition_graph", + "ring_of_cliques", + "windmill_graph", + "stochastic_block_model", + "LFR_benchmark_graph", +] + +@_dispatchable +def caveman_graph(l: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def connected_caveman_graph(l: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def relaxed_caveman_graph(l: int, k: int, p: float, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_partition_graph( + sizes: list[int], p_in: float, p_out: float, seed=None, directed: bool = False +) -> DiGraph[Incomplete]: ... +@_dispatchable +def planted_partition_graph( + l: int, k: int, p_in: float, p_out: float, seed=None, directed: bool = False +) -> DiGraph[Incomplete]: ... +@_dispatchable +def gaussian_random_partition_graph( + n: int, s: float, v: float, p_in: float, p_out: float, directed: bool = False, seed=None +) -> DiGraph[Incomplete]: ... +@_dispatchable +def ring_of_cliques(num_cliques: int, clique_size: int) -> Graph[Incomplete]: ... +@_dispatchable +def windmill_graph(n: int, k: int) -> Graph[Incomplete]: ... +@_dispatchable +def stochastic_block_model( + sizes: list[int], + p: list[list[float]], + nodelist: Collection[Incomplete] | None = None, + seed=None, + directed: bool = False, + selfloops: bool = False, + sparse: bool = True, +) -> DiGraph[Incomplete]: ... +@_dispatchable +def LFR_benchmark_graph( + n: int, + tau1: float, + tau2: float, + mu: float, + average_degree: float | None = None, + min_degree: int | None = None, + max_degree: int | None = None, + min_community: int | None = None, + max_community: int | None = None, + tol: float = 1e-07, + max_iters: int = 500, + seed=None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/degree_seq.pyi b/stubs/networkx/networkx/generators/degree_seq.pyi new file mode 100644 index 000000000000..562806bed693 --- /dev/null +++ b/stubs/networkx/networkx/generators/degree_seq.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete + +from networkx.utils.backends import _dispatchable + +from ..classes.digraph import DiGraph +from ..classes.graph import Graph +from ..classes.multidigraph import MultiDiGraph +from ..classes.multigraph import MultiGraph + +__all__ = [ + "configuration_model", + "directed_configuration_model", + "expected_degree_graph", + "havel_hakimi_graph", + "directed_havel_hakimi_graph", + "degree_sequence_tree", + "random_degree_sequence_graph", +] + +@_dispatchable +def configuration_model( + deg_sequence: list[int], create_using: MultiGraph[Incomplete] | type[MultiGraph[Incomplete]] | None = None, seed=None +) -> MultiGraph[Incomplete]: ... +@_dispatchable +def directed_configuration_model( + in_degree_sequence: list[int], + out_degree_sequence: list[int], + create_using: MultiDiGraph[Incomplete] | type[MultiDiGraph[Incomplete]] | None = None, + seed=None, +) -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def expected_degree_graph(w: list[Incomplete], seed=None, selfloops: bool = True) -> Graph[Incomplete]: ... +@_dispatchable +def havel_hakimi_graph(deg_sequence: list[int], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None): ... +@_dispatchable +def directed_havel_hakimi_graph( + in_deg_sequence: list[int], + out_deg_sequence: list[int], + create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, +) -> DiGraph[Incomplete]: ... +@_dispatchable +def degree_sequence_tree( + deg_sequence, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def random_degree_sequence_graph(sequence: list[int], seed=None, tries: int = 10) -> Graph[Incomplete]: ... + +class DegreeSequenceRandomGraph: + rng: Incomplete + degree: Incomplete + m: Incomplete + dmax: Incomplete + def __init__(self, degree, rng) -> None: ... + remaining_degree: Incomplete + graph: Incomplete + def generate(self): ... + def update_remaining(self, u, v, aux_graph=None) -> None: ... + def p(self, u, v): ... + def q(self, u, v): ... + def suitable_edge(self): ... + def phase1(self) -> None: ... + def phase2(self) -> None: ... + def phase3(self) -> None: ... diff --git a/stubs/networkx/networkx/generators/directed.pyi b/stubs/networkx/networkx/generators/directed.pyi new file mode 100644 index 000000000000..0d32d803d860 --- /dev/null +++ b/stubs/networkx/networkx/generators/directed.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +from ..classes import MultiDiGraph + +__all__ = ["gn_graph", "gnc_graph", "gnr_graph", "random_k_out_graph", "scale_free_graph"] + +@_dispatchable +def gn_graph( + n: int, kernel: Callable[..., Incomplete] | None = None, create_using: DiGraph[Incomplete] | None = None, seed=None +): ... +@_dispatchable +def gnr_graph(n: int, p: float, create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, seed=None): ... +@_dispatchable +def gnc_graph(n: int, create_using: DiGraph[Incomplete] | type[DiGraph[Incomplete]] | None = None, seed=None): ... +@_dispatchable +def scale_free_graph( + n: int, + alpha: float = 0.41, + beta: float = 0.54, + gamma: float = 0.05, + delta_in: float = 0.2, + delta_out: float = 0, + create_using=None, + seed=None, + initial_graph: MultiDiGraph[Incomplete] | None = None, +) -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def random_uniform_k_out_graph( + n: int, k: int, self_loops: bool = True, with_replacement: bool = True, seed=None +) -> Graph[Incomplete]: ... +@_dispatchable +def random_k_out_graph(n: int, k: int, alpha: float, self_loops: bool = True, seed=None) -> MultiDiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/duplication.pyi b/stubs/networkx/networkx/generators/duplication.pyi new file mode 100644 index 000000000000..0212e9c3b060 --- /dev/null +++ b/stubs/networkx/networkx/generators/duplication.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +__all__ = ["partial_duplication_graph", "duplication_divergence_graph"] + +@_dispatchable +def partial_duplication_graph(N: int, n: int, p: float, q: float, seed=None): ... +@_dispatchable +def duplication_divergence_graph(n: int, p: float, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/ego.pyi b/stubs/networkx/networkx/generators/ego.pyi new file mode 100644 index 000000000000..17a15862aa1a --- /dev/null +++ b/stubs/networkx/networkx/generators/ego.pyi @@ -0,0 +1,7 @@ +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["ego_graph"] + +@_dispatchable +def ego_graph(G: Graph[_Node], n, radius: float = 1, center: bool = True, undirected: bool = False, distance=None): ... diff --git a/stubs/networkx/networkx/generators/expanders.pyi b/stubs/networkx/networkx/generators/expanders.pyi new file mode 100644 index 000000000000..72d061145a1a --- /dev/null +++ b/stubs/networkx/networkx/generators/expanders.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "margulis_gabber_galil_graph", + "chordal_cycle_graph", + "paley_graph", + "maybe_regular_expander", + "maybe_regular_expander_graph", + "is_regular_expander", + "random_regular_expander_graph", +] + +@_dispatchable +def margulis_gabber_galil_graph( + n: int, create_using: MultiGraph[Incomplete] | type[MultiGraph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def chordal_cycle_graph(p: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def paley_graph(p: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def maybe_regular_expander_graph(n: int, d: int, *, create_using=None, max_tries: int = 100, seed=None) -> Graph[Incomplete]: ... +@deprecated( + "`maybe_regular_expander` is a deprecated alias for `maybe_regular_expander_graph`. " + "Use `maybe_regular_expander_graph` instead." +) +def maybe_regular_expander(n, d, *, create_using=None, max_tries: int = 100, seed=None): ... +@_dispatchable +def is_regular_expander(G: Graph[_Node], *, epsilon: float = 0) -> bool: ... +@_dispatchable +def random_regular_expander_graph(n: int, d: int, *, epsilon=0, create_using=None, max_tries=100, seed=None): ... diff --git a/stubs/networkx/networkx/generators/geometric.pyi b/stubs/networkx/networkx/generators/geometric.pyi new file mode 100644 index 000000000000..1d12fb9c17be --- /dev/null +++ b/stubs/networkx/networkx/generators/geometric.pyi @@ -0,0 +1,78 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "geometric_edges", + "geographical_threshold_graph", + "navigable_small_world_graph", + "random_geometric_graph", + "soft_random_geometric_graph", + "thresholded_random_geometric_graph", + "waxman_graph", + "geometric_soft_configuration_graph", +] + +@_dispatchable +def geometric_edges(G: Graph[_Node], radius: float, p: float = 2) -> list[Incomplete]: ... +@_dispatchable +def random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def soft_random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + p_dist: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def geographical_threshold_graph( + n: int | Iterable[Incomplete], + theta: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + weight: dict[Incomplete, Incomplete] | None = None, + metric: Callable[..., Incomplete] | None = None, + p_dist: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def waxman_graph( + n: int | Iterable[Incomplete], + beta: float = 0.4, + alpha: float = 0.1, + L: float | None = None, + domain: tuple[float, float, float, float] = (0, 0, 1, 1), + metric: Callable[..., Incomplete] | None = None, + seed=None, +) -> Graph[Incomplete]: ... + +# docstring marks p as int, but it still works with floats. So I think it's better for consistency +@_dispatchable +def navigable_small_world_graph(n: int, p: float = 1, q: int = 1, r: float = 2, dim: int = 2, seed=None): ... +@_dispatchable +def thresholded_random_geometric_graph( + n: int | Iterable[Incomplete], + radius: float, + theta: float, + dim: int = 2, + pos: dict[Incomplete, Incomplete] | None = None, + weight: dict[Incomplete, Incomplete] | None = None, + p: float = 2, + seed=None, +) -> Graph[Incomplete]: ... +@_dispatchable +def geometric_soft_configuration_graph( + *, beta, n=None, gamma=None, mean_degree=None, kappas=None, seed=None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/harary_graph.pyi b/stubs/networkx/networkx/generators/harary_graph.pyi new file mode 100644 index 000000000000..bf2d609225a0 --- /dev/null +++ b/stubs/networkx/networkx/generators/harary_graph.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["hnm_harary_graph", "hkn_harary_graph"] + +@_dispatchable +def hnm_harary_graph( + n: int, m: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def hkn_harary_graph( + k: int, n: int, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/internet_as_graphs.pyi b/stubs/networkx/networkx/generators/internet_as_graphs.pyi new file mode 100644 index 000000000000..eb120b1fd7d5 --- /dev/null +++ b/stubs/networkx/networkx/generators/internet_as_graphs.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["random_internet_as_graph"] + +def uniform_int_from_avg(a, m, seed): ... +def choose_pref_attach(degs: Mapping[Incomplete, Incomplete], seed): ... + +class AS_graph_generator: + seed: Incomplete + n_t: Incomplete + n_m: Incomplete + n_cp: Incomplete + n_c: Incomplete + d_m: Incomplete + d_cp: Incomplete + d_c: Incomplete + p_m_m: Incomplete + p_cp_m: Incomplete + p_cp_cp: Incomplete + t_m: float + t_cp: float + t_c: float + def __init__(self, n, seed) -> None: ... + G: Incomplete + def t_graph(self) -> Graph[Incomplete]: ... + def add_edge(self, i, j, kind) -> None: ... + def choose_peer_pref_attach(self, node_list): ... + def choose_node_pref_attach(self, node_list): ... + def add_customer(self, i, j) -> None: ... + def add_node(self, i, kind: str, reg2prob: float, avg_deg: float, t_edge_prob: float): ... + def add_m_peering_link(self, m, to_kind: str) -> bool: ... + def add_cp_peering_link(self, cp, to_kind: str) -> bool: ... + regions: Incomplete + def graph_regions(self, rn: int) -> None: ... + def add_peering_links(self, from_kind, to_kind) -> None: ... + customers: Incomplete + providers: Incomplete + nodes: Incomplete + def generate(self) -> Graph[Incomplete]: ... + +@_dispatchable +def random_internet_as_graph(n: int, seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/intersection.pyi b/stubs/networkx/networkx/generators/intersection.pyi new file mode 100644 index 000000000000..b631d2b1e31c --- /dev/null +++ b/stubs/networkx/networkx/generators/intersection.pyi @@ -0,0 +1,10 @@ +from networkx.utils.backends import _dispatchable + +__all__ = ["uniform_random_intersection_graph", "k_random_intersection_graph", "general_random_intersection_graph"] + +@_dispatchable +def uniform_random_intersection_graph(n: int, m: int, p: float, seed=None): ... +@_dispatchable +def k_random_intersection_graph(n: int, m: int, k: float, seed=None): ... +@_dispatchable +def general_random_intersection_graph(n: int, m: int, p: list[float], seed=None): ... diff --git a/stubs/networkx/networkx/generators/interval_graph.pyi b/stubs/networkx/networkx/generators/interval_graph.pyi new file mode 100644 index 000000000000..89857e689d47 --- /dev/null +++ b/stubs/networkx/networkx/generators/interval_graph.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["interval_graph"] + +@_dispatchable +def interval_graph(intervals: Iterable[Incomplete]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/joint_degree_seq.pyi b/stubs/networkx/networkx/generators/joint_degree_seq.pyi new file mode 100644 index 000000000000..2814dd544138 --- /dev/null +++ b/stubs/networkx/networkx/generators/joint_degree_seq.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence + +from networkx.utils.backends import _dispatchable +from numpy.random import RandomState + +from ..classes.graph import Graph + +__all__ = ["is_valid_joint_degree", "is_valid_directed_joint_degree", "joint_degree_graph", "directed_joint_degree_graph"] + +@_dispatchable +def is_valid_joint_degree(joint_degrees: Mapping[int, Mapping[int, int]]) -> bool: ... +@_dispatchable +def joint_degree_graph( + joint_degrees: Mapping[int, Mapping[int, int]], seed: int | RandomState | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def is_valid_directed_joint_degree( + in_degrees: Sequence[int], out_degrees: Sequence[int], nkk: Mapping[int, Mapping[int, int]] +) -> bool: ... +@_dispatchable +def directed_joint_degree_graph( + in_degrees: Sequence[int], + out_degrees: Sequence[int], + nkk: Mapping[int, Mapping[int, int]], + seed: int | RandomState | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/lattice.pyi b/stubs/networkx/networkx/generators/lattice.pyi new file mode 100644 index 000000000000..1b365e7815b3 --- /dev/null +++ b/stubs/networkx/networkx/generators/lattice.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["grid_2d_graph", "grid_graph", "hypercube_graph", "triangular_lattice_graph", "hexagonal_lattice_graph"] + +@_dispatchable +def grid_2d_graph( + m, n, periodic: bool = False, create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def grid_graph(dim: list[float] | tuple[float, ...] | Iterable[Incomplete], periodic: bool = False) -> Graph[Incomplete]: ... +@_dispatchable +def hypercube_graph(n: int) -> Graph[Incomplete]: ... +@_dispatchable +def triangular_lattice_graph( + m: int, + n: int, + periodic: bool = False, + with_positions: bool = True, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def hexagonal_lattice_graph( + m: int, + n: int, + periodic: bool = False, + with_positions: bool = True, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/line.pyi b/stubs/networkx/networkx/generators/line.pyi new file mode 100644 index 000000000000..a9cd56c23186 --- /dev/null +++ b/stubs/networkx/networkx/generators/line.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["line_graph", "inverse_line_graph"] + +@_dispatchable +def line_graph(G: Graph[_Node], create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def inverse_line_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/mycielski.pyi b/stubs/networkx/networkx/generators/mycielski.pyi new file mode 100644 index 000000000000..ba383edc6ed0 --- /dev/null +++ b/stubs/networkx/networkx/generators/mycielski.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["mycielskian", "mycielski_graph"] + +@_dispatchable +def mycielskian(G: Graph[_Node], iterations: int = 1) -> Graph[Incomplete]: ... +@_dispatchable +def mycielski_graph(n: int) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi b/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi new file mode 100644 index 000000000000..d8bd5a19ee29 --- /dev/null +++ b/stubs/networkx/networkx/generators/nonisomorphic_trees.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +from networkx.utils.backends import _dispatchable + +__all__ = ["nonisomorphic_trees", "number_of_nonisomorphic_trees"] + +@_dispatchable +def nonisomorphic_trees(order: int) -> Generator[list[Incomplete]]: ... +@_dispatchable +def number_of_nonisomorphic_trees(order: int) -> int: ... diff --git a/stubs/networkx/networkx/generators/random_clustered.pyi b/stubs/networkx/networkx/generators/random_clustered.pyi new file mode 100644 index 000000000000..3fa7ff59543b --- /dev/null +++ b/stubs/networkx/networkx/generators/random_clustered.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import TypeVar, overload + +from networkx import MultiGraph +from networkx.classes.graph import Graph +from networkx.utils.misc import _RandomState + +_G = TypeVar("_G", bound=Graph[int]) +__all__ = ["random_clustered_graph"] + +@overload +def random_clustered_graph( + joint_degree_sequence: Iterable[tuple[int, int]], create_using: None = None, seed: _RandomState = None +) -> MultiGraph[int]: ... +@overload +def random_clustered_graph( + joint_degree_sequence: Iterable[tuple[int, int]], create_using: type[_G], seed: _RandomState = None +) -> _G: ... diff --git a/stubs/networkx/networkx/generators/random_graphs.pyi b/stubs/networkx/networkx/generators/random_graphs.pyi new file mode 100644 index 000000000000..d9e1d6c05571 --- /dev/null +++ b/stubs/networkx/networkx/generators/random_graphs.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing_extensions import deprecated + +from networkx.utils.backends import _dispatchable + +from ..classes.graph import Graph + +__all__ = [ + "fast_gnp_random_graph", + "gnp_random_graph", + "dense_gnm_random_graph", + "gnm_random_graph", + "erdos_renyi_graph", + "binomial_graph", + "newman_watts_strogatz_graph", + "watts_strogatz_graph", + "connected_watts_strogatz_graph", + "random_regular_graph", + "barabasi_albert_graph", + "dual_barabasi_albert_graph", + "extended_barabasi_albert_graph", + "powerlaw_cluster_graph", + "random_lobster", + "random_lobster_graph", + "random_shell_graph", + "random_powerlaw_tree", + "random_powerlaw_tree_sequence", + "random_kernel_graph", +] + +@_dispatchable +def fast_gnp_random_graph(n: int, p: float, seed=None, directed: bool = False, *, create_using=None): ... +@_dispatchable +def gnp_random_graph(n: int, p: float, seed=None, directed: bool = False, *, create_using=None): ... + +binomial_graph = gnp_random_graph +erdos_renyi_graph = gnp_random_graph + +@_dispatchable +def dense_gnm_random_graph(n: int, m: int, seed=None, *, create_using=None): ... +@_dispatchable +def gnm_random_graph(n: int, m: int, seed=None, directed: bool = False, *, create_using=None): ... +@_dispatchable +def newman_watts_strogatz_graph(n: int, k: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def watts_strogatz_graph(n: int, k: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def connected_watts_strogatz_graph(n: int, k: int, p: float, tries: int = 100, seed=None, *, create_using=None): ... +@_dispatchable +def random_regular_graph(d: int, n: int, seed=None, *, create_using=None): ... +@_dispatchable +def barabasi_albert_graph( + n: int, m: int, seed=None, initial_graph: Graph[Incomplete] | None = None, *, create_using=None +) -> Graph[Incomplete]: ... +@_dispatchable +def dual_barabasi_albert_graph( + n: int, m1: int, m2: int, p: float, seed=None, initial_graph: Graph[Incomplete] | None = None, *, create_using=None +) -> Graph[Incomplete]: ... +@_dispatchable +def extended_barabasi_albert_graph(n: int, m: int, p: float, q: float, seed=None, *, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def powerlaw_cluster_graph(n: int, m: int, p: float, seed=None, *, create_using=None): ... +@_dispatchable +def random_lobster_graph(n: int, p1: float, p2: float, seed=None, *, create_using=None): ... +@_dispatchable +@deprecated("`random_lobster` is a deprecated alias for `random_lobster_graph`. Use `random_lobster_graph` instead.") +def random_lobster(n, p1, p2, seed=None, *, create_using=None): ... +@_dispatchable +def random_shell_graph(constructor: Iterable[tuple[int, int, float]], seed=None, *, create_using=None): ... +@_dispatchable +def random_powerlaw_tree(n: int, gamma: float = 3, seed=None, tries: int = 100, *, create_using=None): ... +@_dispatchable +def random_powerlaw_tree_sequence(n: int, gamma: float = 3, seed=None, tries: int = 100): ... +@_dispatchable +def random_kernel_graph( + n: int, + kernel_integral: Callable[..., Incomplete], + kernel_root: Callable[..., Incomplete] | None = None, + seed=None, + *, + create_using=None, +): ... diff --git a/stubs/networkx/networkx/generators/small.pyi b/stubs/networkx/networkx/generators/small.pyi new file mode 100644 index 000000000000..c440b1d46c74 --- /dev/null +++ b/stubs/networkx/networkx/generators/small.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = [ + "LCF_graph", + "bull_graph", + "chvatal_graph", + "cubical_graph", + "desargues_graph", + "diamond_graph", + "dodecahedral_graph", + "frucht_graph", + "generalized_petersen_graph", + "heawood_graph", + "hoffman_singleton_graph", + "house_graph", + "house_x_graph", + "icosahedral_graph", + "krackhardt_kite_graph", + "moebius_kantor_graph", + "octahedral_graph", + "pappus_graph", + "petersen_graph", + "sedgewick_maze_graph", + "tetrahedral_graph", + "truncated_cube_graph", + "truncated_tetrahedron_graph", + "tutte_graph", +] + +@_dispatchable +def LCF_graph(n: int, shift_list: list[Incomplete], repeats: int, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def bull_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def chvatal_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def cubical_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def desargues_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def diamond_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def dodecahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def frucht_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def heawood_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def hoffman_singleton_graph() -> Graph[Incomplete]: ... +@_dispatchable +def house_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def house_x_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def icosahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def krackhardt_kite_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def moebius_kantor_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def octahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def pappus_graph() -> Graph[Incomplete]: ... +@_dispatchable +def petersen_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def generalized_petersen_graph(n: int, k: int, *, create_using=None) -> Graph[Incomplete]: ... +@_dispatchable +def sedgewick_maze_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def tetrahedral_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def truncated_cube_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def truncated_tetrahedron_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... +@_dispatchable +def tutte_graph(create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/social.pyi b/stubs/networkx/networkx/generators/social.pyi new file mode 100644 index 000000000000..7a67b31c5c2e --- /dev/null +++ b/stubs/networkx/networkx/generators/social.pyi @@ -0,0 +1,12 @@ +from networkx.utils.backends import _dispatchable + +__all__ = ["karate_club_graph", "davis_southern_women_graph", "florentine_families_graph", "les_miserables_graph"] + +@_dispatchable +def karate_club_graph(): ... +@_dispatchable +def davis_southern_women_graph(): ... +@_dispatchable +def florentine_families_graph(): ... +@_dispatchable +def les_miserables_graph(): ... diff --git a/stubs/networkx/networkx/generators/spectral_graph_forge.pyi b/stubs/networkx/networkx/generators/spectral_graph_forge.pyi new file mode 100644 index 000000000000..2822fc3544a7 --- /dev/null +++ b/stubs/networkx/networkx/generators/spectral_graph_forge.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["spectral_graph_forge"] + +@_dispatchable +def spectral_graph_forge(G: Graph[_Node], alpha: float, transformation: str = "identity", seed=None) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/stochastic.pyi b/stubs/networkx/networkx/generators/stochastic.pyi new file mode 100644 index 000000000000..c52c2a9b19e1 --- /dev/null +++ b/stubs/networkx/networkx/generators/stochastic.pyi @@ -0,0 +1,8 @@ +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["stochastic_graph"] + +@_dispatchable +def stochastic_graph(G: DiGraph[_Node], copy: bool = True, weight: str = "weight"): ... diff --git a/stubs/networkx/networkx/generators/sudoku.pyi b/stubs/networkx/networkx/generators/sudoku.pyi new file mode 100644 index 000000000000..89a44087d4be --- /dev/null +++ b/stubs/networkx/networkx/generators/sudoku.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["sudoku_graph"] + +@_dispatchable +def sudoku_graph(n: int = 3) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/time_series.pyi b/stubs/networkx/networkx/generators/time_series.pyi new file mode 100644 index 000000000000..aa9a3b755384 --- /dev/null +++ b/stubs/networkx/networkx/generators/time_series.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from collections.abc import Sequence + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["visibility_graph"] + +@_dispatchable +def visibility_graph(series: Sequence[float]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/trees.pyi b/stubs/networkx/networkx/generators/trees.pyi new file mode 100644 index 000000000000..eb63cdb49e94 --- /dev/null +++ b/stubs/networkx/networkx/generators/trees.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +from ..classes.digraph import DiGraph + +__all__ = [ + "prefix_tree", + "prefix_tree_recursive", + "random_labeled_tree", + "random_labeled_rooted_tree", + "random_labeled_rooted_forest", + "random_unlabeled_tree", + "random_unlabeled_rooted_tree", + "random_unlabeled_rooted_forest", +] + +@_dispatchable +def prefix_tree(paths: Iterable[Incomplete]) -> DiGraph[Incomplete]: ... +@_dispatchable +def prefix_tree_recursive(paths: Iterable[Incomplete]) -> DiGraph[Incomplete]: ... +@_dispatchable +def random_labeled_tree(n: int, *, seed=None): ... +@_dispatchable +def random_labeled_rooted_tree(n: int, *, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_unlabeled_rooted_tree(n: int, *, number_of_trees=None, seed=None) -> Incomplete | list[Incomplete]: ... +@_dispatchable +def random_labeled_rooted_forest(n: int, *, seed=None) -> Graph[Incomplete]: ... +@_dispatchable +def random_unlabeled_rooted_forest(n: int, *, q=None, number_of_forests=None, seed=None) -> Incomplete | list[Incomplete]: ... +@_dispatchable +def random_unlabeled_tree(n: int, *, number_of_trees=None, seed=None) -> Incomplete | list[Incomplete]: ... diff --git a/stubs/networkx/networkx/generators/triads.pyi b/stubs/networkx/networkx/generators/triads.pyi new file mode 100644 index 000000000000..66fb47f93757 --- /dev/null +++ b/stubs/networkx/networkx/generators/triads.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import Final + +from networkx import DiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["triad_graph"] + +TRIAD_EDGES: Final[dict[str, list[str]]] + +@_dispatchable +def triad_graph(triad_name: str) -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/lazy_imports.pyi b/stubs/networkx/networkx/lazy_imports.pyi new file mode 100644 index 000000000000..f806469927aa --- /dev/null +++ b/stubs/networkx/networkx/lazy_imports.pyi @@ -0,0 +1,14 @@ +import types +from _typeshed import Incomplete + +__all__ = ["attach", "_lazy_import"] + +def attach( + module_name: str, submodules: set[Incomplete] | None = None, submod_attrs: dict[Incomplete, Incomplete] | None = None +): ... + +class DelayedImportErrorModule(types.ModuleType): + def __init__(self, frame_data, *args, **kwargs) -> None: ... + def __getattr__(self, x) -> None: ... + +def _lazy_import(fullname: str) -> types.ModuleType | DelayedImportErrorModule: ... diff --git a/stubs/networkx/networkx/linalg/__init__.pyi b/stubs/networkx/networkx/linalg/__init__.pyi new file mode 100644 index 000000000000..af8d23d18616 --- /dev/null +++ b/stubs/networkx/networkx/linalg/__init__.pyi @@ -0,0 +1,15 @@ +from networkx.linalg import ( + attrmatrix as attrmatrix, + bethehessianmatrix as bethehessianmatrix, + graphmatrix as graphmatrix, + laplacianmatrix as laplacianmatrix, + modularitymatrix as modularitymatrix, + spectrum as spectrum, +) +from networkx.linalg.algebraicconnectivity import * +from networkx.linalg.attrmatrix import * +from networkx.linalg.bethehessianmatrix import * +from networkx.linalg.graphmatrix import * +from networkx.linalg.laplacianmatrix import * +from networkx.linalg.modularitymatrix import * +from networkx.linalg.spectrum import * diff --git a/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi b/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi new file mode 100644 index 000000000000..3ff0fd053a4d --- /dev/null +++ b/stubs/networkx/networkx/linalg/algebraicconnectivity.pyi @@ -0,0 +1,45 @@ +from typing import Literal + +import numpy as np +from networkx._typing import Array1D, Seed +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["algebraic_connectivity", "fiedler_vector", "spectral_ordering", "spectral_bisection"] + +@_dispatchable +def algebraic_connectivity( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> float: ... +@_dispatchable +def fiedler_vector( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> Array1D[np.float64]: ... +@_dispatchable +def spectral_ordering( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> list[_Node]: ... +@_dispatchable +def spectral_bisection( + G: Graph[_Node], + weight: str | None = "weight", + normalized: bool = False, + tol: float = 1e-08, + method: Literal["tracemin_pcg", "tracemin_lu", "lanczos", "lobpcg"] = "tracemin_pcg", + seed: Seed | None = None, +) -> tuple[set[_Node], set[_Node]]: ... diff --git a/stubs/networkx/networkx/linalg/attrmatrix.pyi b/stubs/networkx/networkx/linalg/attrmatrix.pyi new file mode 100644 index 000000000000..90b19c231e4d --- /dev/null +++ b/stubs/networkx/networkx/linalg/attrmatrix.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Collection +from typing import Any, Literal + +from networkx._typing import Array2D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.typing import DTypeLike +from scipy.sparse import lil_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["attr_matrix", "attr_sparse_matrix"] + +@_dispatchable +def attr_matrix( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, # runtime also accepts `Callable[[_Node], object]`, but it is not documented + normalized: bool = False, # runtime also accepts `Callable[[_Node, _Node], object]`, but it is not documented + rc_order: Collection[_Node] | None = None, + dtype: DTypeLike | None = None, + order: Literal["C", "F"] | None = None, + # TODO: overload on rc_order and node_attr + # (rc_order:[node], node_attr:None) -> 2D-array + # (rc_order:[any], node_attr:str) -> 2D-array + # (rc_order:None, node_attr:None) -> (2D-array, list[node]) + # (rc_order:None, node_attr:str) -> (2D-array, list[any]) +) -> Array2D[Incomplete] | tuple[Array2D[Incomplete], list[_Node] | list[Any]]: ... +@_dispatchable +def attr_sparse_matrix( + G: Graph[_Node], + edge_attr: str | None = None, + node_attr: str | None = None, # runtime also accepts `Callable[[_Node], object]`, but it is not documented + normalized: bool = False, # runtime also accepts `Callable[[_Node, _Node], object]`, but it is not documented + rc_order: Collection[_Node] | None = None, + dtype: DTypeLike | None = None, + # TODO: overload on rc_order and node_attr + # (rc_order:[node], node_attr:None) -> lil_array + # (rc_order:[any], node_attr:str) -> lil_array + # (rc_order:None, node_attr:None) -> (lil_array, list[node]) + # (rc_order:None, node_attr:str) -> (lil_array, list[any]) +) -> lil_array | tuple[lil_array, list[_Node] | list[Any]]: ... diff --git a/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi b/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi new file mode 100644 index 000000000000..6cc9100b9870 --- /dev/null +++ b/stubs/networkx/networkx/linalg/bethehessianmatrix.pyi @@ -0,0 +1,10 @@ +from collections.abc import Collection + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from scipy.sparse import csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["bethe_hessian_matrix"] + +@_dispatchable +def bethe_hessian_matrix(G: Graph[_Node], r: float | None = None, nodelist: Collection[_Node] | None = None) -> csr_array: ... diff --git a/stubs/networkx/networkx/linalg/graphmatrix.pyi b/stubs/networkx/networkx/linalg/graphmatrix.pyi new file mode 100644 index 000000000000..7d08761770d7 --- /dev/null +++ b/stubs/networkx/networkx/linalg/graphmatrix.pyi @@ -0,0 +1,31 @@ +from collections.abc import Collection, Hashable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from numpy.typing import DTypeLike +from scipy.sparse import csc_array, csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = ["incidence_matrix", "adjacency_matrix"] + +@_dispatchable +def incidence_matrix( + G: Graph[_Node], + nodelist: Collection[_Node] | None = None, + edgelist: ( + Collection[ + # Requiring tuples to represent an edge might be too strict as runtime does not check the type of + # the collection. We can replace the tuples by `Collection[_Node | Hashable]` if people complain. + tuple[_Node, _Node] # for normal graphs, this is (u, v) + | tuple[_Node, _Node, Hashable] # for multigraphs, this is (u, v, key) + ] + | None + ) = None, + oriented: bool = False, + weight: str | None = None, + *, + dtype: DTypeLike | None = None, +) -> csc_array: ... +@_dispatchable +def adjacency_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, dtype: DTypeLike | None = None, weight: str | None = "weight" +) -> csr_array: ... diff --git a/stubs/networkx/networkx/linalg/laplacianmatrix.pyi b/stubs/networkx/networkx/linalg/laplacianmatrix.pyi new file mode 100644 index 000000000000..089d31900cfb --- /dev/null +++ b/stubs/networkx/networkx/linalg/laplacianmatrix.pyi @@ -0,0 +1,39 @@ +from collections.abc import Collection +from typing import Literal + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable +from scipy.sparse import csr_array # type: ignore[import-untyped] # pyright: ignore[reportMissingImports] + +__all__ = [ + "laplacian_matrix", + "normalized_laplacian_matrix", + "directed_laplacian_matrix", + "directed_combinatorial_laplacian_matrix", +] + +@_dispatchable +def laplacian_matrix(G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight") -> csr_array: ... +@_dispatchable +def normalized_laplacian_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = "weight" +) -> csr_array: ... +@_dispatchable +def directed_laplacian_matrix( + G: DiGraph[_Node], + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: Literal["random", "lazy", "pagerank"] | None = None, + alpha: float = 0.95, +) -> Array2D[np.float64]: ... +@_dispatchable +def directed_combinatorial_laplacian_matrix( + G: DiGraph[_Node], + nodelist: Collection[_Node] | None = None, + weight: str | None = "weight", + walk_type: Literal["random", "lazy", "pagerank"] | None = None, + alpha: float = 0.95, +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/linalg/modularitymatrix.pyi b/stubs/networkx/networkx/linalg/modularitymatrix.pyi new file mode 100644 index 000000000000..d7537db42afc --- /dev/null +++ b/stubs/networkx/networkx/linalg/modularitymatrix.pyi @@ -0,0 +1,18 @@ +from collections.abc import Collection + +import numpy as np +from networkx._typing import Array2D +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["modularity_matrix", "directed_modularity_matrix"] + +@_dispatchable +def modularity_matrix( + G: Graph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = None +) -> Array2D[np.float64]: ... +@_dispatchable +def directed_modularity_matrix( + G: DiGraph[_Node], nodelist: Collection[_Node] | None = None, weight: str | None = None +) -> Array2D[np.float64]: ... diff --git a/stubs/networkx/networkx/linalg/spectrum.pyi b/stubs/networkx/networkx/linalg/spectrum.pyi new file mode 100644 index 000000000000..05e4455eb7da --- /dev/null +++ b/stubs/networkx/networkx/linalg/spectrum.pyi @@ -0,0 +1,23 @@ +import numpy as np +from networkx._typing import Array1D +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "laplacian_spectrum", + "adjacency_spectrum", + "modularity_spectrum", + "normalized_laplacian_spectrum", + "bethe_hessian_spectrum", +] + +@_dispatchable +def laplacian_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.float64]: ... +@_dispatchable +def normalized_laplacian_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.float64]: ... +@_dispatchable +def adjacency_spectrum(G: Graph[_Node], weight: str | None = "weight") -> Array1D[np.complex128]: ... +@_dispatchable +def modularity_spectrum(G: Graph[_Node]) -> Array1D[np.complex128]: ... +@_dispatchable +def bethe_hessian_spectrum(G: Graph[_Node], r: float | None = None) -> Array1D[np.float64]: ... diff --git a/stubs/networkx/networkx/readwrite/__init__.pyi b/stubs/networkx/networkx/readwrite/__init__.pyi new file mode 100644 index 000000000000..038e3613e9c3 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/__init__.pyi @@ -0,0 +1,12 @@ +from networkx.readwrite.adjlist import * +from networkx.readwrite.edgelist import * +from networkx.readwrite.gexf import * +from networkx.readwrite.gml import * +from networkx.readwrite.graph6 import * +from networkx.readwrite.graphml import * +from networkx.readwrite.json_graph import * +from networkx.readwrite.leda import * +from networkx.readwrite.multiline_adjlist import * +from networkx.readwrite.pajek import * +from networkx.readwrite.sparse6 import * +from networkx.readwrite.text import * diff --git a/stubs/networkx/networkx/readwrite/adjlist.pyi b/stubs/networkx/networkx/readwrite/adjlist.pyi new file mode 100644 index 000000000000..f416e8f891f4 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/adjlist.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_adjlist", "write_adjlist", "parse_adjlist", "read_adjlist"] + +def generate_adjlist(G: Graph[_Node], delimiter: str = " ") -> Generator[str]: ... +def write_adjlist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], comments: str = "#", delimiter: str = " ", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def parse_adjlist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_adjlist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/edgelist.pyi b/stubs/networkx/networkx/readwrite/edgelist.pyi new file mode 100644 index 000000000000..8c2983fc3efc --- /dev/null +++ b/stubs/networkx/networkx/readwrite/edgelist.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "generate_edgelist", + "write_edgelist", + "parse_edgelist", + "read_edgelist", + "read_weighted_edgelist", + "write_weighted_edgelist", +] + +def generate_edgelist(G: Graph[_Node], delimiter: str = " ", data: bool = True) -> Generator[Incomplete]: ... +def write_edgelist( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + comments: str = "#", + delimiter: str = " ", + data: bool = True, + encoding: str = "utf-8", +) -> None: ... +@_dispatchable +def parse_edgelist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + data: bool = True, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + data: bool = True, + edgetype=None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... +def write_weighted_edgelist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], comments: str = "#", delimiter: str = " ", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def read_weighted_edgelist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype=None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/gexf.pyi b/stubs/networkx/networkx/readwrite/gexf.pyi new file mode 100644 index 000000000000..bebb998dfe93 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/gexf.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["write_gexf", "read_gexf", "relabel_gexf_graph", "generate_gexf"] + +def write_gexf( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + version: str = "1.2draft", +) -> None: ... +def generate_gexf( + G: Graph[_Node], encoding: str = "utf-8", prettyprint: bool = True, version: str = "1.2draft" +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def read_gexf( + path: StrPath | SupportsRead[bytes], + node_type: type[Incomplete] | None = None, + relabel: bool = False, + version: str = "1.2draft", +) -> Graph[Incomplete]: ... + +class GEXF: + versions: Incomplete + xml_type: Incomplete + python_type: Incomplete + def construct_types(self) -> None: ... + convert_bool: Final[dict[Literal["true", "false", "True", "False", "0", 0, "1", 1], bool]] + NS_GEXF: Incomplete + NS_VIZ: Incomplete + NS_XSI: Incomplete + SCHEMALOCATION: Incomplete + VERSION: Incomplete + version: Incomplete + def set_version(self, version) -> None: ... + +class GEXFWriter(GEXF): + prettyprint: Incomplete + encoding: Incomplete + xml: Incomplete + edge_id: Incomplete + attr_id: Incomplete + all_edge_ids: Incomplete + attr: Incomplete + def __init__(self, graph=None, encoding: str = "utf-8", prettyprint: bool = True, version: str = "1.2draft") -> None: ... + graph_element: Incomplete + def add_graph(self, G: Graph[_Node]) -> None: ... + def add_nodes(self, G: Graph[_Node], graph_element) -> None: ... + def add_edges(self, G: Graph[_Node], graph_element) -> None: ... + def add_attributes(self, node_or_edge, xml_obj, data, default): ... + def get_attr_id(self, title, attr_type, edge_or_node, default, mode): ... + def add_viz(self, element, node_data): ... + def add_parents(self, node_element, node_data): ... + def add_slices(self, node_or_edge_element, node_or_edge_data): ... + def add_spells(self, node_or_edge_element, node_or_edge_data): ... + def alter_graph_mode_timeformat(self, start_or_end) -> None: ... + def write(self, fh) -> None: ... + def indent(self, elem, level: int = 0) -> None: ... + +class GEXFReader(GEXF): + node_type: Incomplete + simple_graph: bool + def __init__(self, node_type=None, version: str = "1.2draft") -> None: ... + xml: Incomplete + def __call__(self, stream): ... + timeformat: Incomplete + def make_graph(self, graph_xml): ... + def add_node(self, G: Graph[_Node], node_xml, node_attr, node_pid=None) -> None: ... + def add_start_end(self, data, xml): ... + def add_viz(self, data, node_xml): ... + def add_parents(self, data, node_xml): ... + def add_slices(self, data, node_or_edge_xml): ... + def add_spells(self, data, node_or_edge_xml): ... + def add_edge(self, G: Graph[_Node], edge_element, edge_attr) -> None: ... + def decode_attr_elements(self, gexf_keys, obj_xml): ... + def find_gexf_attributes(self, attributes_element): ... + +def relabel_gexf_graph(G: Graph[_Node]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/gml.pyi b/stubs/networkx/networkx/readwrite/gml.pyi new file mode 100644 index 000000000000..3a9e321d4edf --- /dev/null +++ b/stubs/networkx/networkx/readwrite/gml.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Callable, Generator, Iterable +from enum import Enum +from typing import Final, Generic, NamedTuple, TypeVar + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +_T = TypeVar("_T") + +__all__ = ["read_gml", "parse_gml", "generate_gml", "write_gml"] + +def escape(text): ... +def unescape(text): ... +def literal_destringizer(rep: str): ... +@_dispatchable +def read_gml( + path: StrPath | SupportsRead[bytes], label: str = "label", destringizer: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... +@_dispatchable +def parse_gml( + lines: str | Iterable[str], label: str = "label", destringizer: Callable[..., Incomplete] | None = None +) -> Graph[Incomplete]: ... + +class Pattern(Enum): + KEYS = 0 + REALS = 1 + INTS = 2 + STRINGS = 3 + DICT_START = 4 + DICT_END = 5 + COMMENT_WHITESPACE = 6 + +class Token(NamedTuple, Generic[_T]): + category: Pattern + value: _T + line: int + position: int + +LIST_START_VALUE: Final = "_networkx_list_start" + +def parse_gml_lines(lines, label, destringizer): ... +def literal_stringizer(value) -> str: ... +def generate_gml(G: Graph[_Node], stringizer: Callable[..., Incomplete] | None = None) -> Generator[Incomplete, Incomplete]: ... +def write_gml( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], stringizer: Callable[..., Incomplete] | None = None +) -> None: ... diff --git a/stubs/networkx/networkx/readwrite/graph6.pyi b/stubs/networkx/networkx/readwrite/graph6.pyi new file mode 100644 index 000000000000..17cd91d94b58 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/graph6.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["from_graph6_bytes", "read_graph6", "to_graph6_bytes", "write_graph6"] + +@_dispatchable +def from_graph6_bytes(bytes_in: bytes) -> Graph[Incomplete]: ... +def to_graph6_bytes(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +@_dispatchable +def read_graph6(path: StrPath | SupportsRead[bytes]) -> Graph[Incomplete]: ... +def write_graph6( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], nodes: Iterable[Incomplete] | None = None, header: bool = True +): ... +def write_graph6_file(G: Graph[_Node], f, nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +def data_to_n(data): ... +def n_to_data(n): ... diff --git a/stubs/networkx/networkx/readwrite/graphml.pyi b/stubs/networkx/networkx/readwrite/graphml.pyi new file mode 100644 index 000000000000..4beb539a4ca7 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/graphml.pyi @@ -0,0 +1,140 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator +from typing import Final, Literal + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = [ + "write_graphml", + "read_graphml", + "generate_graphml", + "write_graphml_xml", + "write_graphml_lxml", + "parse_graphml", + "GraphMLWriter", + "GraphMLReader", +] + +def write_graphml_xml( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +) -> None: ... +def write_graphml_lxml( + G: Graph[_Node], + path: StrPath | SupportsWrite[bytes], + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +): ... +def generate_graphml( + G: Graph[_Node], + encoding: str = "utf-8", + prettyprint: bool = True, + named_key_ids: bool = False, + edge_id_from_attribute: str | None = None, +) -> Generator[Incomplete, Incomplete]: ... +@_dispatchable +def read_graphml( + path: StrPath | SupportsRead[bytes], + node_type: type[Incomplete] = ..., + edge_key_type: type[Incomplete] = ..., + force_multigraph: bool = False, +) -> Graph[Incomplete]: ... +@_dispatchable +def parse_graphml( + graphml_string: str, node_type: type[Incomplete] = ..., edge_key_type: type[Incomplete] = ..., force_multigraph: bool = False +) -> Graph[Incomplete]: ... + +class GraphML: + NS_GRAPHML: Final[str] + NS_XSI: Final[str] + NS_Y: Final[str] + SCHEMALOCATION: Final[str] + xml_type: Incomplete + python_type: Incomplete + def construct_types(self) -> None: ... + convert_bool: Final[dict[Literal["true", "false", "0", 0, "1", 1], bool]] + def get_xml_type(self, key): ... + +class GraphMLWriter(GraphML): + myElement: Incomplete + infer_numeric_types: Incomplete + prettyprint: Incomplete + named_key_ids: Incomplete + edge_id_from_attribute: Incomplete + encoding: Incomplete + xml: Incomplete + keys: Incomplete + attributes: Incomplete + attribute_types: Incomplete + def __init__( + self, + graph=None, + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute=None, + ) -> None: ... + def attr_type(self, name, scope, value): ... + def get_key(self, name, attr_type, scope, default): ... + def add_data(self, name, element_type, value, scope: str = "all", default=None): ... + def add_attributes(self, scope, xml_obj, data, default) -> None: ... + def add_nodes(self, G: Graph[_Node], graph_element) -> None: ... + def add_edges(self, G: Graph[_Node], graph_element) -> None: ... + def add_graph_element(self, G: Graph[_Node]) -> None: ... + def add_graphs(self, graph_list) -> None: ... + def dump(self, stream) -> None: ... + def indent(self, elem, level: int = 0) -> None: ... + +class IncrementalElement: + xml: Incomplete + prettyprint: Incomplete + def __init__(self, xml, prettyprint) -> None: ... + def append(self, element) -> None: ... + +class GraphMLWriterLxml(GraphMLWriter): + myElement: Incomplete + named_key_ids: Incomplete + edge_id_from_attribute: Incomplete + infer_numeric_types: Incomplete + xml: Incomplete + keys: Incomplete + attribute_types: Incomplete + def __init__( + self, + path, + graph=None, + encoding: str = "utf-8", + prettyprint: bool = True, + infer_numeric_types: bool = False, + named_key_ids: bool = False, + edge_id_from_attribute=None, + ) -> None: ... + def add_graph_element(self, G: Graph[_Node]) -> None: ... + def add_attributes(self, scope, xml_obj, data, default) -> None: ... + def dump(self, stream=None) -> None: ... + +write_graphml = write_graphml_lxml + +class GraphMLReader(GraphML): + node_type: Incomplete + edge_key_type: Incomplete + multigraph: Incomplete + edge_ids: Incomplete + def __init__(self, node_type=..., edge_key_type=..., force_multigraph: bool = False) -> None: ... + xml: Incomplete + def __call__(self, path=None, string=None) -> Generator[Incomplete]: ... + def make_graph(self, graph_xml, graphml_keys, defaults, G=None): ... + def add_node(self, G: Graph[_Node], node_xml, graphml_keys, defaults) -> None: ... + def add_edge(self, G: Graph[_Node], edge_element, graphml_keys) -> None: ... + def decode_data_elements(self, graphml_keys, obj_xml): ... + def find_graphml_keys(self, graph_element): ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi b/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi new file mode 100644 index 000000000000..56ff476831de --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/__init__.pyi @@ -0,0 +1,4 @@ +from networkx.readwrite.json_graph.adjacency import * +from networkx.readwrite.json_graph.cytoscape import * +from networkx.readwrite.json_graph.node_link import * +from networkx.readwrite.json_graph.tree import * diff --git a/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi b/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi new file mode 100644 index 000000000000..e1728b1cc49f --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/adjacency.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["adjacency_data", "adjacency_graph"] + +# Any: Complex type union +def adjacency_data(G: Graph[_Node], attrs: dict[Incomplete, Incomplete] = {"id": "id", "key": "key"}) -> dict[str, Any]: ... +@_dispatchable +def adjacency_graph( + data: dict[Incomplete, Incomplete], + directed: bool = False, + multigraph: bool = True, + attrs: dict[Incomplete, Incomplete] = {"id": "id", "key": "key"}, +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi b/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi new file mode 100644 index 000000000000..959ffb3b2ed5 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/cytoscape.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete +from typing import Any + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["cytoscape_data", "cytoscape_graph"] + +# Any: Complex type union +def cytoscape_data(G: Graph[_Node], name: str = "name", ident: str = "id") -> dict[str, Any]: ... +@_dispatchable +def cytoscape_graph(data: dict[Incomplete, Incomplete], name: str = "name", ident: str = "id") -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi b/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi new file mode 100644 index 000000000000..15c7da4e2da3 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/node_link.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["node_link_data", "node_link_graph"] + +def node_link_data( + G: Graph[_Node], + *, + source: str = "source", + target: str = "target", + name: str = "id", + key: str = "key", + edges: str = "edges", + nodes: str = "nodes", +) -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def node_link_graph( + data: dict[Incomplete, Incomplete], + directed: bool = False, + multigraph: bool = True, + attrs=None, + *, + source: str = "source", + target: str = "target", + name: str = "id", + key: str = "key", + edges: str = "edges", + nodes: str = "nodes", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/json_graph/tree.pyi b/stubs/networkx/networkx/readwrite/json_graph/tree.pyi new file mode 100644 index 000000000000..052e8b5fb2b5 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/json_graph/tree.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["tree_data", "tree_graph"] + +def tree_data(G: DiGraph[_Node], root, ident: str = "id", children: str = "children") -> dict[Incomplete, Incomplete]: ... +@_dispatchable +def tree_graph(data: dict[Incomplete, Incomplete], ident: str = "id", children: str = "children") -> DiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/leda.pyi b/stubs/networkx/networkx/readwrite/leda.pyi new file mode 100644 index 000000000000..ddec97493fe4 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/leda.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete, StrPath, SupportsRead +from collections.abc import Iterable + +from networkx.classes.graph import Graph +from networkx.utils.backends import _dispatchable + +__all__ = ["read_leda", "parse_leda"] + +@_dispatchable +def read_leda(path: StrPath | SupportsRead[bytes], encoding: str = "UTF-8") -> Graph[Incomplete]: ... +@_dispatchable +def parse_leda(lines: str | Iterable[str]) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi b/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi new file mode 100644 index 000000000000..ae269ad60fb1 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/multiline_adjlist.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.utils.backends import _dispatchable + +__all__ = ["generate_multiline_adjlist", "write_multiline_adjlist", "parse_multiline_adjlist", "read_multiline_adjlist"] + +def generate_multiline_adjlist(G: Graph[_Node], delimiter: str = " ") -> Generator[str]: ... +def write_multiline_adjlist( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], delimiter: str = " ", comments: str = "#", encoding: str = "utf-8" +) -> None: ... +@_dispatchable +def parse_multiline_adjlist( + lines: Iterable[str], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + edgetype: type[Incomplete] | None = None, +) -> Graph[Incomplete]: ... +@_dispatchable +def read_multiline_adjlist( + path: StrPath | SupportsRead[bytes], + comments: str = "#", + delimiter: str | None = None, + create_using: Graph[Incomplete] | type[Graph[Incomplete]] | None = None, + nodetype: type[Incomplete] | None = None, + edgetype: type[Incomplete] | None = None, + encoding: str = "utf-8", +) -> Graph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/p2g.pyi b/stubs/networkx/networkx/readwrite/p2g.pyi new file mode 100644 index 000000000000..22d670a68c16 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/p2g.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete, StrPath, SupportsRead + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multidigraph import MultiDiGraph +from networkx.utils.backends import _dispatchable + +def write_p2g(G: Graph[_Node], path, encoding: str = "utf-8") -> None: ... +@_dispatchable +def read_p2g(path: StrPath | SupportsRead[str], encoding: str = "utf-8") -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def parse_p2g(lines) -> MultiDiGraph[Incomplete]: ... diff --git a/stubs/networkx/networkx/readwrite/pajek.pyi b/stubs/networkx/networkx/readwrite/pajek.pyi new file mode 100644 index 000000000000..efc593fb2122 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/pajek.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Generator, Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multidigraph import MultiDiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["read_pajek", "parse_pajek", "generate_pajek", "write_pajek"] + +def generate_pajek(G: Graph[_Node]) -> Generator[Incomplete]: ... +def write_pajek(G: Graph[_Node], path: StrPath | SupportsWrite[bytes], encoding: str = "UTF-8") -> None: ... +@_dispatchable +def read_pajek(path: StrPath | SupportsRead[bytes], encoding: str = "UTF-8") -> MultiDiGraph[Incomplete]: ... +@_dispatchable +def parse_pajek(lines: str | Iterable[str]) -> Graph[Incomplete]: ... +def make_qstr(t): ... diff --git a/stubs/networkx/networkx/readwrite/sparse6.pyi b/stubs/networkx/networkx/readwrite/sparse6.pyi new file mode 100644 index 000000000000..0e65988decab --- /dev/null +++ b/stubs/networkx/networkx/readwrite/sparse6.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete, StrPath, SupportsRead, SupportsWrite +from collections.abc import Iterable + +from networkx.classes.graph import Graph, _Node +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +__all__ = ["from_sparse6_bytes", "read_sparse6", "to_sparse6_bytes", "write_sparse6"] + +@_dispatchable +def from_sparse6_bytes(string: str) -> Graph[Incomplete]: ... +def to_sparse6_bytes(G: Graph[_Node], nodes: Iterable[Incomplete] | None = None, header: bool = True): ... +@_dispatchable +def read_sparse6(path: StrPath | SupportsRead[bytes]) -> MultiGraph[Incomplete]: ... +def write_sparse6( + G: Graph[_Node], path: StrPath | SupportsWrite[bytes], nodes: Iterable[Incomplete] | None = None, header: bool = True +) -> None: ... diff --git a/stubs/networkx/networkx/readwrite/text.pyi b/stubs/networkx/networkx/readwrite/text.pyi new file mode 100644 index 000000000000..9a91460b0f54 --- /dev/null +++ b/stubs/networkx/networkx/readwrite/text.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Collection, Generator +from typing import ClassVar + +from networkx.classes.graph import Graph + +__all__ = ["generate_network_text", "write_network_text"] + +class BaseGlyphs: + @classmethod + def as_dict(cls) -> dict[str, str]: ... + +class AsciiBaseGlyphs(BaseGlyphs): + empty: ClassVar[str] + newtree_last: ClassVar[str] + newtree_mid: ClassVar[str] + endof_forest: ClassVar[str] + within_forest: ClassVar[str] + within_tree: ClassVar[str] + +class AsciiDirectedGlyphs(AsciiBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class AsciiUndirectedGlyphs(AsciiBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class UtfBaseGlyphs(BaseGlyphs): + empty: ClassVar[str] + newtree_last: ClassVar[str] + newtree_mid: ClassVar[str] + endof_forest: ClassVar[str] + within_forest: ClassVar[str] + within_tree: ClassVar[str] + +class UtfDirectedGlyphs(UtfBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +class UtfUndirectedGlyphs(UtfBaseGlyphs): + last: ClassVar[str] + mid: ClassVar[str] + backedge: ClassVar[str] + vertical_edge: ClassVar[str] + +def generate_network_text( + graph: Graph[Incomplete], + with_labels: bool = True, + sources: Collection[Incomplete] | None = None, + max_depth: int | None = None, + ascii_only: bool = False, + vertical_chains: bool = False, +) -> Generator[Incomplete, None, Incomplete]: ... +def write_network_text( + graph: Graph[Incomplete], + path: Callable[..., Incomplete] | None = None, + with_labels: bool = True, + sources: Collection[Incomplete] | None = None, + max_depth: int | None = None, + ascii_only: bool = False, + end: str = "\n", + vertical_chains: bool = False, +) -> None: ... diff --git a/stubs/networkx/networkx/relabel.pyi b/stubs/networkx/networkx/relabel.pyi new file mode 100644 index 000000000000..5607b6e08149 --- /dev/null +++ b/stubs/networkx/networkx/relabel.pyi @@ -0,0 +1,30 @@ +from collections.abc import Hashable, Mapping +from typing import Literal, TypeVar, overload + +from networkx.classes.digraph import DiGraph +from networkx.classes.graph import Graph +from networkx.classes.multidigraph import MultiDiGraph +from networkx.classes.multigraph import MultiGraph +from networkx.utils.backends import _dispatchable + +_X = TypeVar("_X", bound=Hashable) +_Y = TypeVar("_Y", bound=Hashable) + +__all__ = ["convert_node_labels_to_integers", "relabel_nodes"] + +@overload +def relabel_nodes(G: MultiDiGraph[_X], mapping: Mapping[_X, _Y], copy: bool = True) -> MultiDiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: DiGraph[_X], mapping: Mapping[_X, _Y], copy: bool = True) -> DiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: MultiGraph[_X], mapping: Mapping[_X, _Y], copy: bool = True) -> MultiGraph[_X | _Y]: ... +@overload +def relabel_nodes(G: Graph[_X], mapping: Mapping[_X, _Y], copy: bool = True) -> Graph[_X | _Y]: ... + +@_dispatchable +def convert_node_labels_to_integers( + G: Graph[Hashable], + first_label: int = 0, + ordering: Literal["default", "sorted", "increasing degree", "decreasing degree"] = "default", + label_attribute: str | None = None, +) -> Graph[int]: ... diff --git a/stubs/networkx/networkx/utils/__init__.pyi b/stubs/networkx/networkx/utils/__init__.pyi new file mode 100644 index 000000000000..c615a6e8a8d1 --- /dev/null +++ b/stubs/networkx/networkx/utils/__init__.pyi @@ -0,0 +1,11 @@ +from networkx.utils.backends import * +from networkx.utils.configs import * +from networkx.utils.configs import NetworkXConfig +from networkx.utils.decorators import * +from networkx.utils.heaps import * +from networkx.utils.misc import * +from networkx.utils.random_sequence import * +from networkx.utils.rcm import * +from networkx.utils.union_find import * + +config: NetworkXConfig # Set by networkx/__init__.py diff --git a/stubs/networkx/networkx/utils/backends.pyi b/stubs/networkx/networkx/utils/backends.pyi new file mode 100644 index 000000000000..0935d701d8e3 --- /dev/null +++ b/stubs/networkx/networkx/utils/backends.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from typing import Any, Final, Generic, ParamSpec, TypeVar, overload +from typing_extensions import Self + +_P = ParamSpec("_P") +_R = TypeVar("_R") +__all__ = ["_dispatchable"] +FAILED_TO_CONVERT: Final[str] + +class _dispatchable(Generic[_P, _R]): + __defaults__: Incomplete + __kwdefaults__: Incomplete + __module__: Incomplete + __qualname__: Incomplete + __wrapped__: Incomplete + orig_func: Callable[_P, _R] | None + name: str + edge_attrs: dict[str, Any] | None + node_attrs: dict[str, Any] | None + preserve_edge_attrs: bool + preserve_node_attrs: bool + preserve_graph_attrs: bool + mutates_input: bool + optional_graphs: Incomplete + list_graphs: Incomplete + graphs: dict[str, int] + backends: dict[str, Incomplete] + # Incomplete: Ignoring the case where func=None returns a partial, + # we only care about `_dispatchable` used as a static-typing decorator + def __new__( + cls, + func: Callable[_P, _R] | None = None, + *, + name: str | None = None, + graphs: str | None | Mapping[str, int] = "G", + edge_attrs: str | dict[str, Any] | None = None, + node_attrs: str | dict[str, Any] | None = None, + preserve_edge_attrs: bool = False, + preserve_node_attrs: bool = False, + preserve_graph_attrs: bool = False, + preserve_all_attrs: bool = False, + mutates_input: bool = False, + returns_graph: bool = False, + implemented_by_nx: bool = True, + ) -> Self: ... + + @property + def __doc__(self): ... + @__doc__.setter + def __doc__(self, val) -> None: ... + + @property + def __signature__(self): ... + + # Type system limitations doesn't allow us to define this as it truly should. + # But specifying backend with backend_kwargs isn't a common usecase anyway + # and specifying backend as explicitly None is possible but not intended. + # If this ever changes, update stubs/networkx/@tests/test_cases/check_dispatch_decorator.py + @overload + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + @overload + def __call__(self, *args: Any, backend: str, **backend_kwargs: Any) -> _R: ... + + # @overload + # def __call__(self, *args: _P.args, backend: None = None, **kwargs: _P.kwargs) -> _R: ... + # @overload + # def __call__(self, *args: _P.args, backend: str, **kwargs: _P.kwargs, **backend_kwargs: Any) -> _R: ... + def __reduce__(self): ... diff --git a/stubs/networkx/networkx/utils/configs.pyi b/stubs/networkx/networkx/utils/configs.pyi new file mode 100644 index 000000000000..46d843940841 --- /dev/null +++ b/stubs/networkx/networkx/utils/configs.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete +from collections.abc import Callable, ItemsView, Iterable, Iterator, KeysView, ValuesView +from dataclasses import dataclass +from types import TracebackType +from typing_extensions import Self + +__all__ = ["Config"] + +@dataclass(init=False, eq=False, slots=True, kw_only=True, match_args=False) +class Config: + def __init_subclass__(cls, strict: bool = True) -> None: ... + def __new__(cls, **kwargs) -> Self: ... + def __dir__(self) -> Iterable[str]: ... + def __setattr__(self, name: str, value) -> None: ... + def __delattr__(self, name: str) -> None: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __reversed__(self) -> Iterator[str]: ... + def __getitem__(self, key: str): ... + def __setitem__(self, key: str, value) -> None: ... + def __delitem__(self, key: str) -> None: ... + def get(self, key: str, default=None): ... + def items(self) -> ItemsView[str, Incomplete]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[Incomplete]: ... + def __reduce__(self) -> tuple[Callable[..., Self], tuple[type[Self], dict[Incomplete, Incomplete]]]: ... + def __call__(self, **kwargs) -> Self: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +class NetworkXConfig(Config): + backend_priority: list[str] + backends: Config + cache_converted_graphs: bool + fallback_to_nx: bool + warnings_to_ignore: set[str] + def __init__( + self, + *, + backend_priority: list[str], + backends: Config, + cache_converted_graphs: bool, + fallback_to_nx: bool, + warnings_to_ignore: set[str], + ) -> None: ... + def __new__( + cls, + *, + backend_priority: list[str], + backends: Config, + cache_converted_graphs: bool, + fallback_to_nx: bool, + warnings_to_ignore: set[str], + ) -> Self: ... + +config: NetworkXConfig diff --git a/stubs/networkx/networkx/utils/decorators.pyi b/stubs/networkx/networkx/utils/decorators.pyi new file mode 100644 index 000000000000..66d2cd8121d5 --- /dev/null +++ b/stubs/networkx/networkx/utils/decorators.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from typing import NamedTuple + +__all__ = ["not_implemented_for", "open_file", "nodes_or_number", "np_random_state", "py_random_state", "argmap"] + +def not_implemented_for(*graph_types) -> Callable[..., Incomplete]: ... +def open_file(path_arg: str | int, mode: str = "r") -> Callable[..., Incomplete]: ... +def nodes_or_number(which_args: str | int | Sequence[str | int]) -> Callable[..., Incomplete]: ... +def np_random_state(random_state_argument: str | int) -> Callable[..., Incomplete]: ... +def py_random_state(random_state_argument: str | int) -> Callable[..., Incomplete]: ... + +class argmap: + def __init__(self, func, *args, try_finally: bool = False) -> None: ... + def __call__(self, f) -> Callable[..., Incomplete]: ... + def compile(self, f: Callable[..., Incomplete]) -> Callable[..., Incomplete]: ... + def assemble(self, f: Callable[..., Incomplete]): ... + @classmethod + def signature(cls, f: Callable[..., Incomplete]): ... + + class Signature(NamedTuple): + name: Incomplete + signature: Incomplete + def_sig: Incomplete + call_sig: Incomplete + names: Incomplete + n_positional: Incomplete + args: Incomplete + kwargs: Incomplete diff --git a/stubs/networkx/networkx/utils/heaps.pyi b/stubs/networkx/networkx/utils/heaps.pyi new file mode 100644 index 000000000000..f03e301f9e4b --- /dev/null +++ b/stubs/networkx/networkx/utils/heaps.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +__all__ = ["MinHeap", "PairingHeap", "BinaryHeap"] + +class MinHeap: + class _Item: + __slots__ = ("key", "value") + key: Incomplete + value: Incomplete + def __init__(self, key, value) -> None: ... + + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... + def __nonzero__(self): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + +class PairingHeap(MinHeap): + class _Node(MinHeap._Item): + __slots__ = ("left", "next", "prev", "parent") + left: Incomplete + next: Incomplete + prev: Incomplete + parent: Incomplete + def __init__(self, key, value) -> None: ... + + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... + +class BinaryHeap(MinHeap): + def __init__(self) -> None: ... + def min(self) -> tuple[Incomplete, Incomplete]: ... + def pop(self) -> tuple[Incomplete, Incomplete]: ... + def get(self, key, default=None): ... + def insert(self, key, value, allow_increase: bool = False) -> bool: ... diff --git a/stubs/networkx/networkx/utils/mapped_queue.pyi b/stubs/networkx/networkx/utils/mapped_queue.pyi new file mode 100644 index 000000000000..38710ddb601f --- /dev/null +++ b/stubs/networkx/networkx/utils/mapped_queue.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Iterator + +__all__ = ["MappedQueue"] + +class _HeapElement: + __slots__ = ["priority", "element", "_hash"] + priority: Incomplete + element: Incomplete + def __init__(self, priority, element) -> None: ... + def __lt__(self, other): ... + def __gt__(self, other): ... + def __eq__(self, other): ... + def __hash__(self): ... + def __getitem__(self, indx): ... + def __iter__(self) -> Iterator[Incomplete]: ... + +class MappedQueue: + heap: Incomplete + position: Incomplete + def __init__(self, data=None) -> None: ... + def __len__(self) -> int: ... + def push(self, elt, priority=None): ... + def pop(self): ... + def update(self, elt, new, priority=None) -> None: ... + def remove(self, elt) -> None: ... diff --git a/stubs/networkx/networkx/utils/misc.pyi b/stubs/networkx/networkx/utils/misc.pyi new file mode 100644 index 000000000000..cc14f1bff944 --- /dev/null +++ b/stubs/networkx/networkx/utils/misc.pyi @@ -0,0 +1,61 @@ +import random +from _typeshed import Incomplete +from collections.abc import Iterable, Iterator +from types import ModuleType +from typing import TypeAlias + +import numpy +from networkx.classes.graph import Graph, _Node + +__all__ = [ + "flatten", + "make_list_of_ints", + "dict_to_numpy_array", + "arbitrary_element", + "pairwise", + "groups", + "create_random_state", + "create_py_random_state", + "PythonRandomInterface", + "PythonRandomViaNumpyBits", + "nodes_equal", + "edges_equal", + "graphs_equal", + "_clear_cache", +] + +_RandomNumberGenerator: TypeAlias = ( + ModuleType | random.Random | numpy.random.RandomState | numpy.random.Generator | PythonRandomInterface +) +_RandomState: TypeAlias = int | _RandomNumberGenerator | None + +def flatten(obj, result=None): ... +def make_list_of_ints(sequence): ... +def dict_to_numpy_array(d, mapping=None): ... +def arbitrary_element(iterable: Iterable[Incomplete]) -> Iterable[Incomplete]: ... +def pairwise(iterable: Iterable[Incomplete], cyclic: bool = False) -> Iterator[Incomplete]: ... +def groups(many_to_one): ... +def create_random_state(random_state=None): ... + +class PythonRandomViaNumpyBits(random.Random): + def __init__(self, rng: numpy.random.Generator | None = None) -> None: ... + def getrandbits(self, k: int) -> int: ... + +class PythonRandomInterface: + def __init__(self, rng=None) -> None: ... + def random(self): ... + def uniform(self, a, b): ... + def randrange(self, a, b=None): ... + def choice(self, seq): ... + def gauss(self, mu, sigma): ... + def shuffle(self, seq): ... + def sample(self, seq, k): ... + def randint(self, a, b): ... + def expovariate(self, scale): ... + def paretovariate(self, shape): ... + +def create_py_random_state(random_state: _RandomState = None): ... +def nodes_equal(nodes1, nodes2) -> bool: ... +def edges_equal(edges1, edges2, *, directed: bool = False) -> bool: ... +def graphs_equal(graph1, graph2) -> bool: ... +def _clear_cache(G: Graph[_Node]) -> None: ... diff --git a/stubs/networkx/networkx/utils/random_sequence.pyi b/stubs/networkx/networkx/utils/random_sequence.pyi new file mode 100644 index 000000000000..1092bf7ab0c0 --- /dev/null +++ b/stubs/networkx/networkx/utils/random_sequence.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +__all__ = [ + "powerlaw_sequence", + "is_valid_tree_degree_sequence", + "zipf_rv", + "cumulative_distribution", + "discrete_sequence", + "random_weighted_sample", + "weighted_choice", +] + +def powerlaw_sequence(n, exponent: float = 2.0, seed=None): ... +def is_valid_tree_degree_sequence(degree_sequence: Iterable[Incomplete]) -> tuple[bool, str]: ... +def zipf_rv(alpha: float, xmin: int = 1, seed=None) -> int: ... +def cumulative_distribution(distribution): ... +def discrete_sequence(n, distribution=None, cdistribution=None, seed=None): ... +def random_weighted_sample(mapping, k, seed=None): ... +def weighted_choice(mapping, seed=None): ... diff --git a/stubs/networkx/networkx/utils/rcm.pyi b/stubs/networkx/networkx/utils/rcm.pyi new file mode 100644 index 000000000000..0f4f4ed838e3 --- /dev/null +++ b/stubs/networkx/networkx/utils/rcm.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Generator + +from networkx.classes.graph import Graph, _Node + +__all__ = ["cuthill_mckee_ordering", "reverse_cuthill_mckee_ordering"] + +def cuthill_mckee_ordering( + G: Graph[_Node], heuristic: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, Incomplete]: ... +def reverse_cuthill_mckee_ordering( + G: Graph[_Node], heuristic: Callable[..., Incomplete] | None = None +) -> Generator[Incomplete, Incomplete, Incomplete]: ... +def connected_cuthill_mckee_ordering(G: Graph[_Node], heuristic=None): ... +def pseudo_peripheral_node(G: Graph[_Node]): ... diff --git a/stubs/networkx/networkx/utils/union_find.pyi b/stubs/networkx/networkx/utils/union_find.pyi new file mode 100644 index 000000000000..1d73f4eb7b89 --- /dev/null +++ b/stubs/networkx/networkx/utils/union_find.pyi @@ -0,0 +1,13 @@ +from collections.abc import Generator, Iterable, Iterator, Mapping +from typing import Generic, TypeVar + +_T = TypeVar("_T") + +class UnionFind(Generic[_T]): + parents: Mapping[_T, _T] + weights: Mapping[_T, int] + def __init__(self, elements: Iterable[_T] | None = None) -> None: ... + def __getitem__(self, object: _T) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... + def to_sets(self) -> Generator[set[_T]]: ... + def union(self, *objects: _T) -> None: ... diff --git a/stubs/oauthlib/METADATA.toml b/stubs/oauthlib/METADATA.toml new file mode 100644 index 000000000000..6b2d25dc6222 --- /dev/null +++ b/stubs/oauthlib/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.*" +upstream-repository = "https://github.com/oauthlib/oauthlib" diff --git a/stubs/oauthlib/oauthlib/__init__.pyi b/stubs/oauthlib/oauthlib/__init__.pyi new file mode 100644 index 000000000000..96a9263bbff5 --- /dev/null +++ b/stubs/oauthlib/oauthlib/__init__.pyi @@ -0,0 +1,7 @@ +from typing import Final + +__author__: Final[str] +__version__: Final[str] + +def set_debug(debug_val: bool) -> None: ... +def get_debug() -> bool: ... diff --git a/stubs/oauthlib/oauthlib/common.pyi b/stubs/oauthlib/oauthlib/common.pyi new file mode 100644 index 000000000000..281303f83078 --- /dev/null +++ b/stubs/oauthlib/oauthlib/common.pyi @@ -0,0 +1,118 @@ +import re +from _typeshed import Incomplete, SupportsLenAndGetItem +from collections.abc import Iterable, Mapping +from logging import Logger +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload + +_T = TypeVar("_T") +_V = TypeVar("_V") + +_HTTPMethod: TypeAlias = Literal["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"] + +UNICODE_ASCII_CHARACTER_SET: Final[str] +CLIENT_ID_CHARACTER_SET: Final[str] +SANITIZE_PATTERN: Final[re.Pattern[str]] +INVALID_HEX_PATTERN: Final[re.Pattern[str]] +always_safe: Final[str] +log: Logger + +def quote(s: str | bytes, safe: bytes = b"/") -> str: ... +def unquote(s: str | bytes) -> str: ... +def urlencode(params: Iterable[tuple[str | bytes, str | bytes]]) -> str: ... +def encode_params_utf8(params: Iterable[tuple[str | bytes, str | bytes]]) -> list[tuple[bytes, bytes]]: ... +def decode_params_utf8(params: Iterable[tuple[str | bytes, str | bytes]]) -> list[tuple[str, str]]: ... + +urlencoded: Final[set[str]] + +def urldecode(query: str | bytes) -> list[tuple[str, str]]: ... +def extract_params(raw: str | bytes | dict[str, str] | Iterable[tuple[str, str]]) -> list[tuple[str, str]] | None: ... +def generate_nonce() -> str: ... +def generate_timestamp() -> str: ... +def generate_token(length: int = 30, chars: SupportsLenAndGetItem[str] = ...) -> str: ... +def generate_signed_token(private_pem: str, request: Request) -> str: ... +def verify_signed_token(public_pem, token): ... +def generate_client_id(length: int = 30, chars: SupportsLenAndGetItem[str] = ...) -> str: ... +def add_params_to_qs(query: str, params: dict[str, str] | Iterable[tuple[str, str]]) -> str: ... +def add_params_to_uri(uri: str, params: dict[str, str] | Iterable[tuple[str, str]], fragment: bool = False) -> str: ... +def safe_string_equals(a: str, b: str) -> bool: ... + +@overload +def to_unicode(data: str | bytes, encoding: str = "UTF-8") -> str: ... +@overload +def to_unicode(data: Mapping[str, _V] | Mapping[bytes, _V], encoding: str = "UTF-8") -> dict[str, _V]: ... +@overload +def to_unicode(data: _T, encoding: str = "UTF-8") -> _T: ... + +class CaseInsensitiveDict(dict[str, Incomplete]): + proxy: dict[str, str] + def __init__(self, data: dict[str, Incomplete]) -> None: ... + + @overload + def __contains__(self, k: str) -> bool: ... + @overload + def __contains__(self, k: object) -> bool: ... + + def __delitem__(self, k: str) -> None: ... + def __getitem__(self, k: str): ... + + @overload + def get(self, k: str, default: None = None) -> Incomplete | None: ... + @overload + def get(self, k: str, default): ... + + def __setitem__(self, k: str, v) -> None: ... + def update(self, *args, **kwargs) -> None: ... + +class Request: + uri: str + http_method: _HTTPMethod + headers: CaseInsensitiveDict + body: str | dict[str, str] | list[tuple[str, str]] | None + decoded_body: list[tuple[str, str]] | None + oauth_params: list[str] + validator_log: dict[str, Any] # value type depends on the key + access_token: Incomplete | None + client: Incomplete | None + client_id: Incomplete | None + client_secret: Incomplete | None + code: Incomplete | None + code_challenge: Incomplete | None + code_challenge_method: Incomplete | None + code_verifier: Incomplete | None + extra_credentials: Incomplete | None + grant_type: Incomplete | None + redirect_uri: Incomplete | None + refresh_token: Incomplete | None + request_token: Incomplete | None + response_type: Incomplete | None + scope: Incomplete | None + scopes: Incomplete | None + state: Incomplete | None + token: Incomplete | None + user: Incomplete | None + token_type_hint: Incomplete | None + response_mode: Incomplete | None + nonce: Incomplete | None + display: Incomplete | None + prompt: Incomplete | None + claims: Incomplete | None + max_age: Incomplete | None + ui_locales: Incomplete | None + id_token_hint: Incomplete | None + login_hint: Incomplete | None + acr_values: Incomplete | None + def __init__( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + encoding: str = "utf-8", + ): ... + def __getattr__(self, name: str) -> str | None: ... # or raises AttributeError if attribute is not found + @property + def uri_query(self) -> str: ... + @property + def uri_query_params(self) -> list[tuple[str, str]]: ... + @property + def duplicate_params(self) -> list[str]: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/__init__.pyi b/stubs/oauthlib/oauthlib/oauth1/__init__.pyi new file mode 100644 index 000000000000..1d6a88ddfe2a --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/__init__.pyi @@ -0,0 +1,31 @@ +from .rfc5849 import ( + SIGNATURE_HMAC as SIGNATURE_HMAC, + SIGNATURE_HMAC_SHA1 as SIGNATURE_HMAC_SHA1, + SIGNATURE_HMAC_SHA256 as SIGNATURE_HMAC_SHA256, + SIGNATURE_HMAC_SHA512 as SIGNATURE_HMAC_SHA512, + SIGNATURE_PLAINTEXT as SIGNATURE_PLAINTEXT, + SIGNATURE_RSA as SIGNATURE_RSA, + SIGNATURE_RSA_SHA1 as SIGNATURE_RSA_SHA1, + SIGNATURE_RSA_SHA256 as SIGNATURE_RSA_SHA256, + SIGNATURE_RSA_SHA512 as SIGNATURE_RSA_SHA512, + SIGNATURE_TYPE_AUTH_HEADER as SIGNATURE_TYPE_AUTH_HEADER, + SIGNATURE_TYPE_BODY as SIGNATURE_TYPE_BODY, + SIGNATURE_TYPE_QUERY as SIGNATURE_TYPE_QUERY, + Client as Client, +) +from .rfc5849.endpoints import ( + AccessTokenEndpoint as AccessTokenEndpoint, + AuthorizationEndpoint as AuthorizationEndpoint, + RequestTokenEndpoint as RequestTokenEndpoint, + ResourceEndpoint as ResourceEndpoint, + SignatureOnlyEndpoint as SignatureOnlyEndpoint, + WebApplicationServer as WebApplicationServer, +) +from .rfc5849.errors import ( + InsecureTransportError as InsecureTransportError, + InvalidClientError as InvalidClientError, + InvalidRequestError as InvalidRequestError, + InvalidSignatureMethodError as InvalidSignatureMethodError, + OAuth1Error as OAuth1Error, +) +from .rfc5849.request_validator import RequestValidator as RequestValidator diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi new file mode 100644 index 000000000000..c5e4a4127326 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/__init__.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from logging import Logger +from typing import Final + +from oauthlib.common import _HTTPMethod + +log: Logger +SIGNATURE_HMAC_SHA1: Final[str] +SIGNATURE_HMAC_SHA256: Final[str] +SIGNATURE_HMAC_SHA512: Final[str] +SIGNATURE_HMAC: Final[str] +SIGNATURE_RSA_SHA1: Final[str] +SIGNATURE_RSA_SHA256: Final[str] +SIGNATURE_RSA_SHA512: Final[str] +SIGNATURE_RSA: Final[str] +SIGNATURE_PLAINTEXT: Final[str] +SIGNATURE_METHODS: Final[tuple[str, str, str, str, str, str, str]] +SIGNATURE_TYPE_AUTH_HEADER: Final[str] +SIGNATURE_TYPE_QUERY: Final[str] +SIGNATURE_TYPE_BODY: Final[str] +CONTENT_TYPE_FORM_URLENCODED: Final[str] + +class Client: + SIGNATURE_METHODS: dict[str, Callable[[str, Incomplete], str]] + @classmethod + def register_signature_method(cls, method_name, method_callback) -> None: ... + client_key: Incomplete + client_secret: Incomplete + resource_owner_key: Incomplete + resource_owner_secret: Incomplete + signature_method: Incomplete + signature_type: Incomplete + callback_uri: Incomplete + rsa_key: Incomplete + verifier: Incomplete + realm: Incomplete + encoding: Incomplete + decoding: Incomplete + nonce: Incomplete + timestamp: Incomplete + def __init__( + self, + client_key: str, + client_secret: str | None = None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + realm=None, + encoding: str = "utf-8", + decoding=None, + nonce=None, + timestamp=None, + ): ... + def get_oauth_signature(self, request): ... + def get_oauth_params(self, request): ... + def sign( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + realm=None, + ): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/__init__.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/__init__.pyi new file mode 100644 index 000000000000..d9678f189971 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/__init__.pyi @@ -0,0 +1,7 @@ +from .access_token import AccessTokenEndpoint as AccessTokenEndpoint +from .authorization import AuthorizationEndpoint as AuthorizationEndpoint +from .base import BaseEndpoint as BaseEndpoint +from .pre_configured import WebApplicationServer as WebApplicationServer +from .request_token import RequestTokenEndpoint as RequestTokenEndpoint +from .resource import ResourceEndpoint as ResourceEndpoint +from .signature_only import SignatureOnlyEndpoint as SignatureOnlyEndpoint diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi new file mode 100644 index 000000000000..1a05e8f7a9b2 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/access_token.pyi @@ -0,0 +1,10 @@ +from logging import Logger + +from .base import BaseEndpoint as BaseEndpoint + +log: Logger + +class AccessTokenEndpoint(BaseEndpoint): + def create_access_token(self, request, credentials): ... + def create_access_token_response(self, uri, http_method: str = "GET", body=None, headers=None, credentials=None): ... + def validate_access_token_request(self, request): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi new file mode 100644 index 000000000000..478b0dc9ff20 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/authorization.pyi @@ -0,0 +1,8 @@ +from .base import BaseEndpoint as BaseEndpoint + +class AuthorizationEndpoint(BaseEndpoint): + def create_verifier(self, request, credentials): ... + def create_authorization_response( + self, uri, http_method: str = "GET", body=None, headers=None, realms=None, credentials=None + ): ... + def get_realms_and_credentials(self, uri, http_method: str = "GET", body=None, headers=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi new file mode 100644 index 000000000000..c409738cdaa9 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/base.pyi @@ -0,0 +1,6 @@ +from _typeshed import Incomplete + +class BaseEndpoint: + request_validator: Incomplete + token_generator: Incomplete + def __init__(self, request_validator, token_generator=None) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/pre_configured.pyi new file mode 100644 index 000000000000..fcc6a398e71d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/pre_configured.pyi @@ -0,0 +1,9 @@ +from . import ( + AccessTokenEndpoint as AccessTokenEndpoint, + AuthorizationEndpoint as AuthorizationEndpoint, + RequestTokenEndpoint as RequestTokenEndpoint, + ResourceEndpoint as ResourceEndpoint, +) + +class WebApplicationServer(RequestTokenEndpoint, AuthorizationEndpoint, AccessTokenEndpoint, ResourceEndpoint): + def __init__(self, request_validator) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi new file mode 100644 index 000000000000..9f8f06aca4d7 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/request_token.pyi @@ -0,0 +1,10 @@ +from logging import Logger + +from .base import BaseEndpoint as BaseEndpoint + +log: Logger + +class RequestTokenEndpoint(BaseEndpoint): + def create_request_token(self, request, credentials): ... + def create_request_token_response(self, uri, http_method: str = "GET", body=None, headers=None, credentials=None): ... + def validate_request_token_request(self, request): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi new file mode 100644 index 000000000000..a262b1a70729 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/resource.pyi @@ -0,0 +1,8 @@ +from logging import Logger + +from .base import BaseEndpoint as BaseEndpoint + +log: Logger + +class ResourceEndpoint(BaseEndpoint): + def validate_protected_resource_request(self, uri, http_method: str = "GET", body=None, headers=None, realms=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi new file mode 100644 index 000000000000..8000469a86c3 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/endpoints/signature_only.pyi @@ -0,0 +1,8 @@ +from logging import Logger + +from .base import BaseEndpoint as BaseEndpoint + +log: Logger + +class SignatureOnlyEndpoint(BaseEndpoint): + def validate_request(self, uri, http_method: str = "GET", body=None, headers=None): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi new file mode 100644 index 000000000000..31973a6da123 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/errors.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +class OAuth1Error(Exception): + error: Incomplete + description: str + uri: Incomplete + status_code: Incomplete + def __init__(self, description=None, uri=None, status_code: int = 400, request=None) -> None: ... + def in_uri(self, uri): ... + @property + def twotuples(self): ... + @property + def urlencoded(self): ... + +class InsecureTransportError(OAuth1Error): + error: str + description: str + +class InvalidSignatureMethodError(OAuth1Error): + error: str + +class InvalidRequestError(OAuth1Error): + error: str + +class InvalidClientError(OAuth1Error): + error: str diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi new file mode 100644 index 000000000000..49c06be9d17e --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/parameters.pyi @@ -0,0 +1,3 @@ +def prepare_headers(params, headers=None, realm=None): ... +def prepare_form_encoded_body(oauth_params, body): ... +def prepare_request_uri_query(oauth_params, uri): ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi new file mode 100644 index 000000000000..3bb84ae34ce1 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/request_validator.pyi @@ -0,0 +1,67 @@ +from ...common import Request + +class RequestValidator: + def __init__(self) -> None: ... + @property + def allowed_signature_methods(self) -> tuple[str, ...]: ... + @property + def safe_characters(self) -> set[str]: ... + @property + def client_key_length(self) -> tuple[int, int]: ... + @property + def request_token_length(self) -> tuple[int, int]: ... + @property + def access_token_length(self) -> tuple[int, int]: ... + @property + def timestamp_lifetime(self) -> int: ... + @property + def nonce_length(self) -> tuple[int, int]: ... + @property + def verifier_length(self) -> tuple[int, int]: ... + @property + def realms(self) -> list[str]: ... + @property + def enforce_ssl(self) -> bool: ... + def check_client_key(self, client_key: str) -> bool: ... + def check_request_token(self, request_token: str) -> bool: ... + def check_access_token(self, request_token: str) -> bool: ... + def check_nonce(self, nonce: str) -> bool: ... + def check_verifier(self, verifier: str) -> bool: ... + def check_realms(self, realms: list[str]) -> bool: ... + @property + def dummy_client(self) -> str: ... + @property + def dummy_request_token(self) -> str: ... + @property + def dummy_access_token(self) -> str: ... + def get_client_secret(self, client_key: str, request: Request) -> str: ... + def get_request_token_secret(self, client_key: str, token: str, request: Request) -> str: ... + def get_access_token_secret(self, client_key: str, token: str, request: Request) -> str: ... + def get_default_realms(self, client_key: str, request: Request) -> list[str]: ... + def get_realms(self, token: str, request: Request) -> list[str]: ... + def get_redirect_uri(self, token: str, request: Request) -> str: ... + def get_rsa_key(self, client_key: str, request: Request) -> str: ... + def invalidate_request_token(self, client_key: str, request_token: str, request: Request) -> None: ... + def validate_client_key(self, client_key: str, request: Request) -> bool: ... + def validate_request_token(self, client_key: str, token: str, request: Request) -> bool: ... + def validate_access_token(self, client_key: str, token: str, request: Request) -> bool: ... + def validate_timestamp_and_nonce( + self, + client_key: str, + timestamp, + nonce: str, + request: Request, + request_token: str | None = None, + access_token: str | None = None, + ) -> bool: ... + def validate_redirect_uri(self, client_key: str, redirect_uri, request: Request) -> bool: ... + def validate_requested_realms(self, client_key: str, realms: list[str], request: Request) -> bool: ... + def validate_realms( + self, client_key: str, token: str, request: Request, uri: str | None = None, realms: list[str] | None = None + ) -> bool: ... + def validate_verifier(self, client_key: str, token: str, verifier: str, request: Request) -> bool: ... + def verify_request_token(self, token: str, request: Request) -> bool: ... + def verify_realms(self, token: str, realms: list[str], request: Request) -> bool: ... + def save_access_token(self, token: str, request: Request) -> None: ... + def save_request_token(self, token: str, request: Request) -> None: ... + def save_verifier(self, token: str, verifier, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi new file mode 100644 index 000000000000..c86e96d0f646 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/signature.pyi @@ -0,0 +1,36 @@ +from _typeshed import Unused +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request, _HTTPMethod + +log: Logger + +def signature_base_string(http_method: _HTTPMethod, base_str_uri: str, normalized_encoded_request_parameters: str) -> str: ... +def base_string_uri(uri: str, host: str | None = None) -> str: ... +def collect_parameters( + uri_query: str = "", + body: str | bytes | dict[str, str] | Iterable[tuple[str, str]] | None = None, + headers: dict[str, str] | None = None, + exclude_oauth_signature: bool = True, + with_realm: bool = False, +) -> list[tuple[str, str]]: ... +def normalize_parameters(params: dict[str, str]) -> str: ... +def sign_hmac_sha1_with_client(sig_base_str: str, client): ... +def verify_hmac_sha1(request: Request, client_secret=None, resource_owner_secret=None) -> bool: ... +def sign_hmac_sha1(base_string: str | bytes, client_secret, resource_owner_secret): ... +def sign_hmac_sha256_with_client(sig_base_str, client): ... +def verify_hmac_sha256(request, client_secret=None, resource_owner_secret=None) -> bool: ... +def sign_hmac_sha256(base_string: str | bytes, client_secret, resource_owner_secret): ... +def sign_hmac_sha512_with_client(sig_base_str: str, client): ... +def verify_hmac_sha512(request, client_secret: str | None = None, resource_owner_secret: str | None = None) -> bool: ... +def sign_rsa_sha1_with_client(sig_base_str: str | bytes, client): ... +def verify_rsa_sha1(request, rsa_public_key: str) -> bool: ... +def sign_rsa_sha1(base_string, rsa_private_key): ... +def sign_rsa_sha256_with_client(sig_base_str: str, client): ... +def verify_rsa_sha256(request, rsa_public_key: str) -> bool: ... +def sign_rsa_sha512_with_client(sig_base_str: str, client): ... +def verify_rsa_sha512(request, rsa_public_key: str) -> bool: ... +def sign_plaintext_with_client(_signature_base_string: Unused, client) -> str: ... +def sign_plaintext(client_secret: str | None, resource_owner_secret: str | None) -> str: ... +def verify_plaintext(request, client_secret: str | None = None, resource_owner_secret: str | None = None) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi b/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi new file mode 100644 index 000000000000..46e93ea192fc --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth1/rfc5849/utils.pyi @@ -0,0 +1,18 @@ +from collections.abc import Callable, Iterable +from typing import Final, TypeVar + +_T = TypeVar("_T") + +UNICODE_ASCII_CHARACTER_SET: Final[str] + +def filter_params( + target: Callable[[dict[str, object] | Iterable[tuple[str, object]], _T], object], +) -> Callable[[list[str], _T], object]: ... +def filter_oauth_params( + params: dict[str, object] | Iterable[tuple[str, object]], +) -> list[str]: ... # we don't care about second (object) part +def escape(u: str) -> str: ... +def unescape(u: str) -> str: ... +def parse_keqv_list(l: list[str]) -> dict[str, str]: ... +def parse_http_list(u: str) -> list[str]: ... +def parse_authorization_header(authorization_header: str) -> list[tuple[str, str]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/__init__.pyi new file mode 100644 index 000000000000..117244ab80d8 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/__init__.pyi @@ -0,0 +1,65 @@ +from .rfc6749.clients import ( + BackendApplicationClient as BackendApplicationClient, + Client as Client, + LegacyApplicationClient as LegacyApplicationClient, + MobileApplicationClient as MobileApplicationClient, + ServiceApplicationClient as ServiceApplicationClient, + WebApplicationClient as WebApplicationClient, +) +from .rfc6749.endpoints import ( + AuthorizationEndpoint as AuthorizationEndpoint, + BackendApplicationServer as BackendApplicationServer, + IntrospectEndpoint as IntrospectEndpoint, + LegacyApplicationServer as LegacyApplicationServer, + MetadataEndpoint as MetadataEndpoint, + MobileApplicationServer as MobileApplicationServer, + ResourceEndpoint as ResourceEndpoint, + RevocationEndpoint as RevocationEndpoint, + Server as Server, + TokenEndpoint as TokenEndpoint, + WebApplicationServer as WebApplicationServer, +) +from .rfc6749.errors import ( + AccessDeniedError as AccessDeniedError, + FatalClientError as FatalClientError, + InsecureTransportError as InsecureTransportError, + InvalidClientError as InvalidClientError, + InvalidClientIdError as InvalidClientIdError, + InvalidGrantError as InvalidGrantError, + InvalidRedirectURIError as InvalidRedirectURIError, + InvalidRequestError as InvalidRequestError, + InvalidRequestFatalError as InvalidRequestFatalError, + InvalidScopeError as InvalidScopeError, + MismatchingRedirectURIError as MismatchingRedirectURIError, + MismatchingStateError as MismatchingStateError, + MissingClientIdError as MissingClientIdError, + MissingCodeError as MissingCodeError, + MissingRedirectURIError as MissingRedirectURIError, + MissingResponseTypeError as MissingResponseTypeError, + MissingTokenError as MissingTokenError, + MissingTokenTypeError as MissingTokenTypeError, + OAuth2Error as OAuth2Error, + ServerError as ServerError, + TemporarilyUnavailableError as TemporarilyUnavailableError, + TokenExpiredError as TokenExpiredError, + UnauthorizedClientError as UnauthorizedClientError, + UnsupportedGrantTypeError as UnsupportedGrantTypeError, + UnsupportedResponseTypeError as UnsupportedResponseTypeError, + UnsupportedTokenTypeError as UnsupportedTokenTypeError, +) +from .rfc6749.grant_types import ( + AuthorizationCodeGrant as AuthorizationCodeGrant, + ClientCredentialsGrant as ClientCredentialsGrant, + ImplicitGrant as ImplicitGrant, + RefreshTokenGrant as RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant, +) +from .rfc6749.request_validator import RequestValidator as RequestValidator +from .rfc6749.tokens import BearerToken as BearerToken, OAuth2Token as OAuth2Token +from .rfc6749.utils import is_secure_transport as is_secure_transport +from .rfc8628.clients import DeviceClient as DeviceClient +from .rfc8628.endpoints import ( + DeviceApplicationServer as DeviceApplicationServer, + DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint, +) +from .rfc8628.grant_types import DeviceCodeGrant as DeviceCodeGrant diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi new file mode 100644 index 000000000000..f168fb8a2b5d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/__init__.pyi @@ -0,0 +1,11 @@ +from logging import Logger + +from .endpoints.base import BaseEndpoint as BaseEndpoint, catch_errors_and_unavailability as catch_errors_and_unavailability +from .errors import ( + FatalClientError as FatalClientError, + OAuth2Error as OAuth2Error, + ServerError as ServerError, + TemporarilyUnavailableError as TemporarilyUnavailableError, +) + +log: Logger diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/__init__.pyi new file mode 100644 index 000000000000..a3b9711c21c0 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/__init__.pyi @@ -0,0 +1,6 @@ +from .backend_application import BackendApplicationClient as BackendApplicationClient +from .base import AUTH_HEADER as AUTH_HEADER, BODY as BODY, URI_QUERY as URI_QUERY, Client as Client +from .legacy_application import LegacyApplicationClient as LegacyApplicationClient +from .mobile_application import MobileApplicationClient as MobileApplicationClient +from .service_application import ServiceApplicationClient as ServiceApplicationClient +from .web_application import WebApplicationClient as WebApplicationClient diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi new file mode 100644 index 000000000000..7f8ff4894942 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/backend_application.pyi @@ -0,0 +1,15 @@ +from .base import Client + +class BackendApplicationClient(Client): + grant_type: str + def prepare_request_body( + self, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + code_verifier: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi new file mode 100644 index 000000000000..aa5cf71e7aa0 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/base.pyi @@ -0,0 +1,121 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Callable +from typing import Final, Literal, TypeAlias + +from oauthlib.common import _HTTPMethod +from oauthlib.oauth2.rfc6749.tokens import OAuth2Token + +_TokenPlacement: TypeAlias = Literal["auth_header", "query", "body"] + +AUTH_HEADER: Final[_TokenPlacement] +URI_QUERY: Final[_TokenPlacement] +BODY: Final[_TokenPlacement] +FORM_ENC_HEADERS: Final[dict[str, str]] + +class Client: + refresh_token_key: str + client_id: str + default_token_placement: _TokenPlacement + token_type: str + access_token: str | None + refresh_token: str | None + mac_key: str | bytes | bytearray | None + mac_algorithm: str | None + token: dict[str, Incomplete] + scope: str | set[object] | tuple[object] | list[object] + state_generator: Callable[[], str] + state: str | None + redirect_url: str | None + code: str | None + expires_in: ConvertibleToInt | None + code_verifier: str | None + code_challenge: str | None + code_challenge_method: str | None + def __init__( + self, + client_id: str, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + @property + def token_types( + self, + ) -> dict[ + Literal["Bearer", "MAC"], + Callable[ + [str, str, str | None, dict[str, str] | None, str | None, Incomplete], tuple[str, dict[str, str] | None, str | None] + ], + ]: ... + def prepare_request_uri(self, *args, **kwargs) -> str: ... + def prepare_request_body(self, *args, **kwargs) -> str: ... + def parse_request_uri_response(self, *args, **kwargs) -> dict[str, str]: ... + def add_token( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + token_placement: _TokenPlacement | None = None, + **kwargs, + ) -> tuple[str, dict[str, str] | None, str | None]: ... + def prepare_authorization_request( + self, + authorization_url: str, + state: str | None = None, + redirect_url: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... + def prepare_token_request( + self, + token_url: str, + authorization_response: str | None = None, + redirect_url: str | None = None, + state: str | None = None, + body: str = "", + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... + def prepare_refresh_token_request( + self, + token_url: str, + refresh_token: str | None = None, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> tuple[str, dict[str, str], str]: ... + def prepare_token_revocation_request( + self, + revocation_url: str, + token: str, + token_type_hint: Literal["access_token", "refresh_token"] | None = "access_token", + body: str = "", + callback: Callable[[Incomplete], Incomplete] | None = None, + **kwargs, + ): ... + def parse_request_body_response( + self, body: str, scope: str | set[object] | tuple[object] | list[object] | None = None, **kwargs + ) -> OAuth2Token: ... + def prepare_refresh_body( + self, + body: str = "", + refresh_token: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + **kwargs, + ) -> str: ... + def create_code_verifier(self, length: int) -> str: ... + def create_code_challenge(self, code_verifier: str, code_challenge_method: str | None = None) -> str: ... + def populate_code_attributes(self, response: dict[str, Incomplete]) -> None: ... + def populate_token_attributes(self, response: dict[str, Incomplete]) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi new file mode 100644 index 000000000000..9fe5fd41d0ff --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/legacy_application.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from .base import Client, _TokenPlacement + +class LegacyApplicationClient(Client): + grant_type: str + def __init__( + self, + client_id: str, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_body( + self, + username: str, + password: str, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + code_verifier: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi new file mode 100644 index 000000000000..a6b945f79259 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/mobile_application.pyi @@ -0,0 +1,18 @@ +from oauthlib.oauth2.rfc6749.tokens import OAuth2Token + +from .base import Client + +class MobileApplicationClient(Client): + response_type: str + def prepare_request_uri( + self, + uri, + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + **kwargs, + ) -> str: ... + token: OAuth2Token + def parse_request_uri_response( + self, uri: str, state: str | None = None, scope: str | set[object] | tuple[object] | list[object] | None = None + ) -> OAuth2Token: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi new file mode 100644 index 000000000000..00b375898b98 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/service_application.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from .base import Client, _TokenPlacement + +class ServiceApplicationClient(Client): + grant_type: str + private_key: str | None + subject: str | None + issuer: str | None + audience: str | None + def __init__( + self, + client_id: str, + private_key: str | None = None, + subject: str | None = None, + issuer: str | None = None, + audience: str | None = None, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_body( + self, + private_key: str | None = None, + subject: str | None = None, + issuer: str | None = None, + audience: str | None = None, + expires_at: float | None = None, + issued_at: float | None = None, + extra_claims: dict[str, Incomplete] | None = None, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + *, + not_before: int | None = None, + jwt_id: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi new file mode 100644 index 000000000000..53d4d600b9c1 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/clients/web_application.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from .base import Client, _TokenPlacement + +class WebApplicationClient(Client): + grant_type: str + code: str | None + def __init__( + self, + client_id: str, + code: str | None = None, + *, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_uri( + self, + uri: str, + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = "plain", + **kwargs, + ) -> str: ... + def prepare_request_body( + self, + code: str | None = None, + redirect_uri: str | None = None, + body: str = "", + include_client_id: bool = True, + code_verifier: str | None = None, + *, + scope: str | set[object] | tuple[object] | list[object] | None = None, + client_id: str | None = None, + client_secret: str | None = None, + **kwargs, + ) -> str: ... + def parse_request_uri_response(self, uri: str, state: str | None = None) -> dict[str, str]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/__init__.pyi new file mode 100644 index 000000000000..d05828233231 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/__init__.pyi @@ -0,0 +1,13 @@ +from .authorization import AuthorizationEndpoint as AuthorizationEndpoint +from .introspect import IntrospectEndpoint as IntrospectEndpoint +from .metadata import MetadataEndpoint as MetadataEndpoint +from .pre_configured import ( + BackendApplicationServer as BackendApplicationServer, + LegacyApplicationServer as LegacyApplicationServer, + MobileApplicationServer as MobileApplicationServer, + Server as Server, + WebApplicationServer as WebApplicationServer, +) +from .resource import ResourceEndpoint as ResourceEndpoint +from .revocation import RevocationEndpoint as RevocationEndpoint +from .token import TokenEndpoint as TokenEndpoint diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi new file mode 100644 index 000000000000..f4604fd1fe0b --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/authorization.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.common import _HTTPMethod + +from .base import BaseEndpoint + +log: Logger + +class AuthorizationEndpoint(BaseEndpoint): + def __init__(self, default_response_type: str, default_token_type: str, response_types: dict[str, Incomplete]) -> None: ... + @property + def response_types(self) -> dict[str, Incomplete]: ... + @property + def default_response_type(self) -> str: ... + @property + def default_response_type_handler(self): ... + @property + def default_token_type(self): ... + def create_authorization_response( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + scopes=None, + credentials: dict[str, Incomplete] | None = None, + ): ... + def validate_authorization_request( + self, uri: str, http_method: _HTTPMethod = "GET", body: str | None = None, headers: dict[str, str] | None = None + ): ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi new file mode 100644 index 000000000000..d4aade1edbd3 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/base.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger + +log: Logger + +class BaseEndpoint: + def __init__(self) -> None: ... + + @property + def valid_request_methods(self) -> Sequence[str] | None: ... + @valid_request_methods.setter + def valid_request_methods(self, valid_request_methods: Sequence[str] | None) -> None: ... + + @property + def available(self) -> bool: ... + @available.setter + def available(self, available: bool) -> None: ... + + @property + def catch_errors(self) -> bool: ... + @catch_errors.setter + def catch_errors(self, catch_errors: bool) -> None: ... + +def catch_errors_and_unavailability( + f: Callable[..., tuple[dict[str, Incomplete], str, int]], +) -> Callable[..., tuple[dict[str, Incomplete], str, int]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi new file mode 100644 index 000000000000..49ebf9ae0ff2 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/introspect.pyi @@ -0,0 +1,20 @@ +from logging import Logger +from typing import Literal + +from oauthlib.common import Request, _HTTPMethod + +from ..request_validator import RequestValidator +from .base import BaseEndpoint + +log: Logger + +class IntrospectEndpoint(BaseEndpoint): + valid_token_types: tuple[Literal["access_token"], Literal["refresh_token"]] + valid_request_methods: tuple[Literal["POST"]] + request_validator: RequestValidator + supported_token_types: tuple[str, ...] + def __init__(self, request_validator: RequestValidator, supported_token_types: tuple[str, ...] | None = None) -> None: ... + def create_introspect_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... + def validate_introspect_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi new file mode 100644 index 000000000000..fcd53ad14f0d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/metadata.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from logging import Logger + +from .base import BaseEndpoint + +log: Logger + +class MetadataEndpoint(BaseEndpoint): + raise_errors: bool + endpoints: Iterable[BaseEndpoint] + initial_claims: dict[str, Incomplete] + claims: dict[str, Incomplete] + def __init__( + self, endpoints: Iterable[BaseEndpoint], claims: dict[str, Incomplete] = {}, raise_errors: bool = True + ) -> None: ... + def create_metadata_response( + self, uri: str, http_method: str = "GET", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... + def validate_metadata( + self, array, key, is_required: bool = False, is_list: bool = False, is_url: bool = False, is_issuer: bool = False + ) -> None: ... + def validate_metadata_token(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_authorization(self, claims, endpoint: BaseEndpoint): ... + def validate_metadata_revocation(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_introspection(self, claims, endpoint: BaseEndpoint) -> None: ... + def validate_metadata_server(self) -> dict[str, Incomplete]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi new file mode 100644 index 000000000000..02414844d9fc --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/pre_configured.pyi @@ -0,0 +1,83 @@ +from _typeshed import Unused +from collections.abc import Callable + +from oauthlib.common import Request +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant + +from ..grant_types import ( + AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from ..request_validator import RequestValidator +from ..tokens import BearerToken +from .authorization import AuthorizationEndpoint +from .introspect import IntrospectEndpoint +from .resource import ResourceEndpoint +from .revocation import RevocationEndpoint +from .token import TokenEndpoint + +class Server(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint): + auth_grant: AuthorizationCodeGrant + implicit_grant: ImplicitGrant + password_grant: ResourceOwnerPasswordCredentialsGrant + credentials_grant: ClientCredentialsGrant + refresh_grant: RefreshTokenGrant + device_code_grant: DeviceCodeGrant + bearer: BearerToken + def __init__( + self, + request_validator: RequestValidator, + token_expires_in: int | Callable[[Request], int] | None = None, + token_generator: Callable[[Request], str] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + *args: Unused, + ) -> None: ... + +class WebApplicationServer(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint): + auth_grant: AuthorizationCodeGrant + refresh_grant: RefreshTokenGrant + bearer: BearerToken + def __init__( + self, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... + +class MobileApplicationServer(AuthorizationEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): + implicit_grant: ImplicitGrant + bearer: BearerToken + def __init__( + self, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... + +class LegacyApplicationServer(TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): + password_grant: ResourceOwnerPasswordCredentialsGrant + refresh_grant: RefreshTokenGrant + bearer: BearerToken + def __init__( + self, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... + +class BackendApplicationServer(TokenEndpoint, IntrospectEndpoint, ResourceEndpoint, RevocationEndpoint): + credentials_grant: ClientCredentialsGrant + bearer: BearerToken + def __init__( + self, + request_validator: RequestValidator, + token_generator: Callable[[Request], str] | None = None, + token_expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi new file mode 100644 index 000000000000..8c27bdffec02 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/resource.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.common import Request, _HTTPMethod + +from .base import BaseEndpoint + +log: Logger + +class ResourceEndpoint(BaseEndpoint): + def __init__(self, default_token: str, token_types: dict[str, Incomplete]) -> None: ... + @property + def default_token(self) -> str: ... + @property + def default_token_type_handler(self): ... + @property + def tokens(self) -> dict[str, Incomplete]: ... + def verify_request( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | None = None, + headers: dict[str, str] | None = None, + scopes=None, + ) -> tuple[bool, Request]: ... + def find_token_type(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi new file mode 100644 index 000000000000..aae37277292d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/revocation.pyi @@ -0,0 +1,26 @@ +from logging import Logger +from typing import Literal + +from oauthlib.common import Request, _HTTPMethod + +from ..request_validator import RequestValidator +from .base import BaseEndpoint + +log: Logger + +class RevocationEndpoint(BaseEndpoint): + valid_token_types: tuple[Literal["access_token"], Literal["refresh_token"]] + valid_request_methods: tuple[Literal["POST"]] + request_validator: RequestValidator + supported_token_types: tuple[str, ...] + enable_jsonp: bool + def __init__( + self, + request_validator: RequestValidator, + supported_token_types: tuple[str, ...] | None = None, + enable_jsonp: bool = False, + ) -> None: ... + def create_revocation_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], str, int]: ... + def validate_revocation_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi new file mode 100644 index 000000000000..421ff886a122 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/endpoints/token.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Literal + +from oauthlib.common import Request, _HTTPMethod + +from .base import BaseEndpoint + +log: Logger + +class TokenEndpoint(BaseEndpoint): + valid_request_methods: tuple[Literal["POST"]] + def __init__(self, default_grant_type: str, default_token_type: str, grant_types: dict[str, Incomplete]) -> None: ... + @property + def grant_types(self) -> dict[str, Incomplete]: ... + @property + def default_grant_type(self) -> str: ... + @property + def default_grant_type_handler(self): ... + @property + def default_token_type(self) -> str: ... + def create_token_response( + self, + uri: str, + http_method: _HTTPMethod = "POST", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: dict[str, str] | None = None, + credentials=None, + grant_type_for_scope=None, + claims=None, + ): ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi new file mode 100644 index 000000000000..d76eea7373a8 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi @@ -0,0 +1,150 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +from oauthlib.common import Request + +class OAuth2Error(Exception): + error: str | None + status_code: int + description: str + uri: str | None + state: str | None + redirect_uri: str | None + client_id: str | None + scopes: Incomplete | None + response_type: str | None + response_mode: str | None + grant_type: str | None + def __init__( + self, + description: str | None = None, + uri: str | None = None, + state: str | None = None, + status_code: int | None = None, + request: Request | None = None, + ) -> None: ... + def in_uri(self, uri: str) -> str: ... + @property + def twotuples(self) -> list[tuple[str, str | None]]: ... + @property + def urlencoded(self) -> str: ... + @property + def json(self) -> str: ... + @property + def headers(self) -> dict[str, str]: ... + +class TokenExpiredError(OAuth2Error): + error: str + +class InsecureTransportError(OAuth2Error): + error: str + description: str + +class MismatchingStateError(OAuth2Error): + error: str + description: str + +class MissingCodeError(OAuth2Error): + error: str + +class MissingTokenError(OAuth2Error): + error: str + +class MissingTokenTypeError(OAuth2Error): + error: str + +class FatalClientError(OAuth2Error): ... + +class InvalidRequestFatalError(FatalClientError): + error: str + +class InvalidRedirectURIError(InvalidRequestFatalError): + description: str + +class MissingRedirectURIError(InvalidRequestFatalError): + description: str + +class MismatchingRedirectURIError(InvalidRequestFatalError): + description: str + +class InvalidClientIdError(InvalidRequestFatalError): + description: str + +class MissingClientIdError(InvalidRequestFatalError): + description: str + +class InvalidRequestError(OAuth2Error): + error: str + +class MissingResponseTypeError(InvalidRequestError): + description: str + +class MissingCodeChallengeError(InvalidRequestError): + description: str + +class MissingCodeVerifierError(InvalidRequestError): + description: str + +class AccessDeniedError(OAuth2Error): + error: str + +class UnsupportedResponseTypeError(OAuth2Error): + error: str + +class UnsupportedCodeChallengeMethodError(InvalidRequestError): + description: str + +class InvalidScopeError(OAuth2Error): + error: str + +class ServerError(OAuth2Error): + error: str + +class TemporarilyUnavailableError(OAuth2Error): + error: str + +class InvalidClientError(FatalClientError): + error: str + status_code: int + +class InvalidGrantError(OAuth2Error): + error: str + status_code: int + +class UnauthorizedClientError(OAuth2Error): + error: str + +class UnsupportedGrantTypeError(OAuth2Error): + error: str + +class UnsupportedTokenTypeError(OAuth2Error): + error: str + +class InvalidTokenError(OAuth2Error): + error: str + status_code: int + description: str + +class InsufficientScopeError(OAuth2Error): + error: str + status_code: int + description: str + +class ConsentRequired(OAuth2Error): + error: str + +class LoginRequired(OAuth2Error): + error: str + +class CustomOAuth2Error(OAuth2Error): + def __init__( + self, + error: str, + description: str | None = None, + uri: str | None = None, + state: str | None = None, + status_code: int | None = None, + request: Request | None = None, + ) -> None: ... + +def raise_from_error(error: str, params: dict[str, Incomplete] | None = None) -> Never: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/__init__.pyi new file mode 100644 index 000000000000..d18b0495e4c4 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/__init__.pyi @@ -0,0 +1,5 @@ +from .authorization_code import AuthorizationCodeGrant as AuthorizationCodeGrant +from .client_credentials import ClientCredentialsGrant as ClientCredentialsGrant +from .implicit import ImplicitGrant as ImplicitGrant +from .refresh_token import RefreshTokenGrant as RefreshTokenGrant +from .resource_owner_password_credentials import ResourceOwnerPasswordCredentialsGrant as ResourceOwnerPasswordCredentialsGrant diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi new file mode 100644 index 000000000000..560dd3d63abf --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/authorization_code.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.common import Request + +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger + +def code_challenge_method_s256(verifier: str, challenge: str) -> bool: ... +def code_challenge_method_plain(verifier: str, challenge: str) -> bool: ... + +class AuthorizationCodeGrant(GrantTypeBase): + default_response_mode: str + response_types: list[str] + def create_authorization_code(self, request: Request) -> dict[str, str]: ... + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], None, int | None]: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_authorization_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... + def validate_token_request(self, request: Request) -> None: ... + def validate_code_challenge(self, challenge: str, challenge_method: str, verifier: str) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi new file mode 100644 index 000000000000..ec02b7862aba --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/base.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from itertools import chain +from logging import Logger +from typing import TypeAlias, TypeVar + +from oauthlib.common import Request + +from ..request_validator import RequestValidator +from ..tokens import TokenBase + +log: Logger + +_T = TypeVar("_T") +_AuthValidator: TypeAlias = Callable[[Request], dict[str, Incomplete]] +_TokenValidator: TypeAlias = Callable[[Request], None] +_CodeModifier: TypeAlias = Callable[[dict[str, str], TokenBase | None, Request | None], dict[str, str]] +_TokenModifier: TypeAlias = Callable[[dict[str, Incomplete], TokenBase | None, Request | None], dict[str, Incomplete]] + +class ValidatorsContainer: + pre_auth: Iterable[_AuthValidator] + post_auth: Iterable[_AuthValidator] + pre_token: Iterable[_TokenValidator] + post_token: Iterable[_TokenValidator] + def __init__( + self, + post_auth: Iterable[_AuthValidator], + post_token: Iterable[_TokenValidator], + pre_auth: Iterable[_AuthValidator], + pre_token: Iterable[_TokenValidator], + ) -> None: ... + @property + def all_pre(self) -> chain[_AuthValidator | _TokenValidator]: ... + @property + def all_post(self) -> chain[_AuthValidator | _TokenValidator]: ... + +class GrantTypeBase: + error_uri: str | None + request_validator: RequestValidator | None + default_response_mode: str + refresh_token: bool + response_types: list[str] + def __init__( + self, + request_validator: RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def register_response_type(self, response_type: str) -> None: ... + def register_code_modifier(self, modifier: _CodeModifier) -> None: ... + def register_token_modifier(self, modifier: _TokenModifier) -> None: ... + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int | None]: ... + def create_token_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int | None]: ... + def add_token(self, token: dict[str, _T], token_handler: TokenBase, request: Request) -> dict[str, _T]: ... + def validate_grant_type(self, request: Request) -> None: ... + def validate_scopes(self, request: Request) -> None: ... + def prepare_authorization_response( + self, request: Request, token: dict[str, Incomplete], headers: dict[str, str], body: str | None, status: int | None + ) -> tuple[dict[str, str], str | None, int | None]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi new file mode 100644 index 000000000000..d500ef4d4655 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/client_credentials.pyi @@ -0,0 +1,12 @@ +from logging import Logger + +from oauthlib.common import Request + +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger + +class ClientCredentialsGrant(GrantTypeBase): + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi new file mode 100644 index 000000000000..e17902e4b361 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/implicit.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.common import Request + +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger + +class ImplicitGrant(GrantTypeBase): + response_types: list[str] + grant_allows_refresh_token: bool + def create_authorization_response( + self, request: Request, token_handler: TokenBase + ) -> tuple[dict[str, str], str | None, int]: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str | None, int]: ... + def validate_authorization_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... + def validate_token_request(self, request: Request) -> tuple[Incomplete, dict[str, Incomplete]]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi new file mode 100644 index 000000000000..6d26d66cba39 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/refresh_token.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request + +from ..request_validator import RequestValidator +from ..tokens import TokenBase +from .base import GrantTypeBase, _AuthValidator, _TokenValidator + +log: Logger + +class RefreshTokenGrant(GrantTypeBase): + def __init__( + self, + request_validator: RequestValidator | None = None, + issue_new_refresh_tokens: bool = True, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi new file mode 100644 index 000000000000..ad407436f188 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/grant_types/resource_owner_password_credentials.pyi @@ -0,0 +1,12 @@ +from logging import Logger + +from oauthlib.common import Request + +from ..tokens import TokenBase +from .base import GrantTypeBase + +log: Logger + +class ResourceOwnerPasswordCredentialsGrant(GrantTypeBase): + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int | None]: ... + def validate_token_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi new file mode 100644 index 000000000000..c82a710d5205 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/parameters.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Literal + +from .tokens import OAuth2Token + +def prepare_grant_uri( + uri: str, + client_id: str, + response_type: Literal["code", "token"], + redirect_uri: str | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = "plain", + **kwargs, +) -> str: ... +def prepare_token_request( + grant_type: str, + body: str = "", + include_client_id: bool = True, + code_verifier: str | None = None, + *, + scope: str | set[object] | tuple[object] | list[object] | None = None, + client_id: str | None = None, + client_secret: str | None = None, + code: str | None = None, + redirect_uri: str | None = None, + **kwargs, +) -> str: ... +def prepare_token_revocation_request( + url: str, + token: str, + token_type_hint: Literal["access_token", "refresh_token"] | None = "access_token", + callback: Callable[[Incomplete], Incomplete] | None = None, + body: str = "", + **kwargs, +) -> tuple[str, dict[str, str], str]: ... +def parse_authorization_code_response(uri: str, state: str | None = None) -> dict[str, str]: ... +def parse_implicit_response( + uri: str, state: str | None = None, scope: str | set[object] | tuple[object] | list[object] | None = None +) -> OAuth2Token: ... +def parse_token_response( + body: str | bytes | bytearray, scope: str | set[object] | tuple[object] | list[object] | None = None +) -> OAuth2Token: ... +def validate_token_parameters(params: dict[str, Incomplete]) -> None: ... +def parse_expires(params: dict[str, Incomplete]) -> tuple[int | None, float | None, float | None]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi new file mode 100644 index 000000000000..4c60b62ec170 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/request_validator.pyi @@ -0,0 +1,62 @@ +from collections.abc import Mapping +from logging import Logger +from typing import Literal, TypedDict, type_check_only +from typing_extensions import NotRequired + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.clients import Client + +@type_check_only +class _BearerToken(TypedDict): + token_type: Literal["Bearer"] + access_token: str + expires_in: int + scope: NotRequired[str] + refresh_token: NotRequired[str] + state: NotRequired[str] + +@type_check_only +class _AuthorizationCode(TypedDict): + code: str + state: NotRequired[str] + nonce: NotRequired[str] + +log: Logger + +class RequestValidator: + def client_authentication_required(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client(self, request: Request, *args, **kwargs) -> bool: ... + def authenticate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def confirm_redirect_uri( + self, client_id: str, code: str, redirect_uri: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def get_default_redirect_uri(self, client_id: str, request: Request, *args, **kwargs) -> str: ... + def get_default_scopes(self, client_id: str, request: Request, *args, **kwargs) -> list[str]: ... + def get_original_scopes(self, refresh_token: str, request: Request, *args, **kwargs) -> list[str]: ... + def is_within_original_scope( + self, request_scopes: list[str], refresh_token: str, request: Request, *args, **kwargs + ) -> bool: ... + def introspect_token( + self, token: str, token_type_hint: str, request: Request, *args, **kwargs + ) -> dict[str, int | str | list[str]] | None: ... + def invalidate_authorization_code(self, client_id: str, code: str, request: Request, *args, **kwargs) -> None: ... + def revoke_token(self, token: str, token_type_hint: str, request: Request, *args, **kwargs) -> None: ... + def rotate_refresh_token(self, request: Request) -> bool: ... + def save_authorization_code(self, client_id: str, code: _AuthorizationCode, request: Request, *args, **kwargs) -> None: ... + def save_token(self, token: Mapping[str, object], request: Request, *args, **kwargs) -> object: ... + def save_bearer_token(self, token: _BearerToken, request: Request, *args, **kwargs) -> object: ... + def validate_bearer_token(self, token: str, scopes: list[str], request: Request) -> bool: ... + def validate_client_id(self, client_id: str, request: Request, *args, **kwargs) -> bool: ... + def validate_code(self, client_id: str, code: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_grant_type(self, client_id: str, grant_type: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_redirect_uri(self, client_id: str, redirect_uri: str, request: Request, *args, **kwargs) -> bool: ... + def validate_refresh_token(self, refresh_token: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_response_type( + self, client_id: str, response_type: str, client: Client, request: Request, *args, **kwargs + ) -> bool: ... + def validate_scopes(self, client_id: str, scopes: list[str], client: Client, request: Request, *args, **kwargs) -> bool: ... + def validate_user(self, username: str, password: str, client: Client, request: Request, *args, **kwargs) -> bool: ... + def is_pkce_required(self, client_id: str, request: Request) -> bool: ... + def get_code_challenge(self, code: str, request: Request) -> str: ... + def get_code_challenge_method(self, code: str, request: Request) -> str: ... + def is_origin_allowed(self, client_id: str, origin, request: Request, *args, **kwargs) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi new file mode 100644 index 000000000000..d55acfe0f56f --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/tokens.pyi @@ -0,0 +1,69 @@ +import datetime +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Literal + +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator + +class OAuth2Token(dict[str, Incomplete]): + def __init__( + self, params: dict[str, Incomplete], old_scope: str | set[object] | tuple[object] | list[object] | None = None + ) -> None: ... + @property + def scope_changed(self) -> bool: ... + @property + def old_scope(self) -> str | None: ... + @property + def old_scopes(self) -> list[str]: ... + @property + def scope(self) -> str | None: ... + @property + def scopes(self) -> list[str]: ... + @property + def missing_scopes(self) -> list[str]: ... + @property + def additional_scopes(self) -> list[str]: ... + +def prepare_mac_header( + token: str, + uri: str, + key: str | bytes | bytearray, + http_method: _HTTPMethod, + nonce: str | None = None, + headers: dict[str, str] | None = None, + body: str | None = None, + ext: str = "", + hash_algorithm: str = "hmac-sha-1", + issue_time: datetime.datetime | None = None, + draft: int = 0, +) -> dict[str, str]: ... +def prepare_bearer_uri(token: str, uri: str) -> str: ... +def prepare_bearer_headers(token: str, headers: dict[str, str] | None = None) -> dict[str, str]: ... +def prepare_bearer_body(token: str, body: str = "") -> str: ... +def random_token_generator(request: Request, refresh_token: bool = False) -> str: ... +def signed_token_generator(private_pem: str, **kwargs) -> Callable[[Request], str]: ... +def get_token_from_header(request: Request) -> str | None: ... + +class TokenBase: + __slots__ = () + def __call__(self, request: Request, refresh_token: bool = False) -> None: ... + def validate_request(self, request: Request) -> bool: ... + def estimate_type(self, request: Request) -> int: ... + +class BearerToken(TokenBase): + __slots__ = ("request_validator", "token_generator", "refresh_token_generator", "expires_in") + request_validator: RequestValidator | None + token_generator: Callable[[Request], str] + refresh_token_generator: Callable[[Request], str] + expires_in: int | Callable[[Request], int] + def __init__( + self, + request_validator: RequestValidator | None = None, + token_generator: Callable[[Request], str] | None = None, + expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... + def create_token(self, request: Request, refresh_token: bool = False, **kwargs) -> OAuth2Token: ... + def validate_request(self, request: Request) -> bool: ... + def estimate_type(self, request: Request) -> Literal[9, 5, 0]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi new file mode 100644 index 000000000000..97f51aa733ac --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc6749/utils.pyi @@ -0,0 +1,18 @@ +import datetime +from typing import overload + +@overload +def list_to_scope(scope: None) -> None: ... +@overload +def list_to_scope(scope: str | set[object] | tuple[object] | list[object]) -> str: ... + +@overload +def scope_to_list(scope: None) -> None: ... +@overload +def scope_to_list(scope: str | set[object] | tuple[object] | list[object]) -> list[str]: ... + +def params_from_uri(uri: str) -> dict[str, str | list[str]]: ... +def host_from_uri(uri: str) -> tuple[str, str | None]: ... +def escape(u: str) -> str: ... +def generate_age(issue_time: datetime.datetime | datetime.timedelta) -> str: ... +def is_secure_transport(uri: str) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi new file mode 100644 index 000000000000..8963764427d2 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/__init__.pyi @@ -0,0 +1,9 @@ +from logging import Logger + +from .errors import ( + AuthorizationPendingError as AuthorizationPendingError, + ExpiredTokenError as ExpiredTokenError, + SlowDownError as SlowDownError, +) + +log: Logger diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi new file mode 100644 index 000000000000..e03f44a720ca --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/__init__.pyi @@ -0,0 +1 @@ +from .device import DeviceClient as DeviceClient diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi new file mode 100644 index 000000000000..e7919258117d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/clients/device.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from oauthlib.oauth2.rfc6749.clients.base import Client, _TokenPlacement + +class DeviceClient(Client): + grant_type: str + client_secret: str | None + def __init__( + self, + client_id: str, + *, + client_secret: str | None = None, + default_token_placement: _TokenPlacement = "auth_header", + token_type: str = "Bearer", + access_token: str | None = None, + refresh_token: str | None = None, + mac_key: str | bytes | bytearray | None = None, + mac_algorithm: str | None = None, + token: dict[str, Incomplete] | None = None, + scope: str | set[object] | tuple[object] | list[object] | None = None, + state: str | None = None, + redirect_url: str | None = None, + state_generator: Callable[[], str] = ..., + code_verifier: str | None = None, + code_challenge: str | None = None, + code_challenge_method: str | None = None, + **kwargs, + ) -> None: ... + def prepare_request_uri( + self, uri: str, scope: str | set[object] | tuple[object] | list[object] | None = None, **kwargs + ) -> str: ... + def prepare_request_body( + self, + device_code: str, + body: str = "", + scope: str | set[object] | tuple[object] | list[object] | None = None, + include_client_id: bool = False, + **kwargs, + ) -> str: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi new file mode 100644 index 000000000000..65712957c40d --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/__init__.pyi @@ -0,0 +1,2 @@ +from .device_authorization import DeviceAuthorizationEndpoint as DeviceAuthorizationEndpoint +from .pre_configured import DeviceApplicationServer as DeviceApplicationServer diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi new file mode 100644 index 000000000000..ee67416c128a --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/device_authorization.pyi @@ -0,0 +1,32 @@ +from collections.abc import Callable +from logging import Logger + +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.endpoints.base import BaseEndpoint +from oauthlib.openid.connect.core.request_validator import RequestValidator + +log: Logger + +class DeviceAuthorizationEndpoint(BaseEndpoint): + request_validator: RequestValidator + user_code_generator: Callable[[None], str] | None + def __init__( + self, + request_validator: RequestValidator, + verification_uri: str, + expires_in: int = 1800, + interval: int | None = None, + verification_uri_complete: str | None = None, + user_code_generator: Callable[[None], str] | None = None, + ) -> None: ... + @property + def interval(self) -> int | None: ... + @property + def expires_in(self) -> int: ... + @property + def verification_uri(self) -> str: ... + def verification_uri_complete(self, user_code: str) -> str | None: ... + def validate_device_authorization_request(self, request: Request) -> None: ... + def create_device_authorization_response( + self, uri: str, http_method: _HTTPMethod = "POST", body: str | None = None, headers: dict[str, str] | None = None + ) -> tuple[dict[str, str], dict[str, str | int], int]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi new file mode 100644 index 000000000000..943520667914 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/endpoints/pre_configured.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable + +from oauthlib.openid.connect.core.request_validator import RequestValidator + +from .device_authorization import DeviceAuthorizationEndpoint + +class DeviceApplicationServer(DeviceAuthorizationEndpoint): + def __init__( + self, + request_validator: RequestValidator, + verification_uri: str, + interval: int = 5, + verification_uri_complete: str | None = None, + user_code_generator: Callable[[None], str] | None = None, + **kwargs, + ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi new file mode 100644 index 000000000000..9858cb379e23 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/errors.pyi @@ -0,0 +1,13 @@ +from oauthlib.oauth2.rfc6749.errors import OAuth2Error + +class AuthorizationPendingError(OAuth2Error): + error: str + +class SlowDownError(OAuth2Error): + error: str + +class ExpiredTokenError(OAuth2Error): + error: str + +class AccessDenied(OAuth2Error): + error: str diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi new file mode 100644 index 000000000000..6163747ce035 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/__init__.pyi @@ -0,0 +1 @@ +from .device_code import DeviceCodeGrant as DeviceCodeGrant diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi new file mode 100644 index 000000000000..0f70cb3b542b --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/grant_types/device_code.pyi @@ -0,0 +1,8 @@ +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import GrantTypeBase +from oauthlib.oauth2.rfc6749.tokens import TokenBase + +class DeviceCodeGrant(GrantTypeBase): + def create_authorization_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int]: ... + def validate_token_request(self, request: Request) -> None: ... + def create_token_response(self, request: Request, token_handler: TokenBase) -> tuple[dict[str, str], str, int]: ... diff --git a/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi b/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi new file mode 100644 index 000000000000..9fa7b042c5a0 --- /dev/null +++ b/stubs/oauthlib/oauthlib/oauth2/rfc8628/request_validator.pyi @@ -0,0 +1,5 @@ +from oauthlib.common import Request +from oauthlib.oauth2 import RequestValidator as OAuth2RequestValidator + +class RequestValidator(OAuth2RequestValidator): + def client_authentication_required(self, request: Request, *args, **kwargs) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/openid/__init__.pyi b/stubs/oauthlib/oauthlib/openid/__init__.pyi new file mode 100644 index 000000000000..e3f1f18f436f --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/__init__.pyi @@ -0,0 +1,2 @@ +from .connect.core.endpoints import Server as Server, UserInfoEndpoint as UserInfoEndpoint +from .connect.core.request_validator import RequestValidator as RequestValidator diff --git a/stubs/oauthlib/oauthlib/openid/connect/__init__.pyi b/stubs/oauthlib/oauthlib/openid/connect/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/__init__.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/__init__.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/__init__.pyi new file mode 100644 index 000000000000..2886b423134c --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/__init__.pyi @@ -0,0 +1,2 @@ +from .pre_configured import Server as Server +from .userinfo import UserInfoEndpoint as UserInfoEndpoint diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi new file mode 100644 index 000000000000..379d9cd847bf --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/pre_configured.pyi @@ -0,0 +1,54 @@ +from _typeshed import Unused +from collections.abc import Callable + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.endpoints import ( + AuthorizationEndpoint, + IntrospectEndpoint, + ResourceEndpoint, + RevocationEndpoint, + TokenEndpoint, +) +from oauthlib.oauth2.rfc6749.grant_types import ( + AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant, + ClientCredentialsGrant, + ImplicitGrant as OAuth2ImplicitGrant, + RefreshTokenGrant, + ResourceOwnerPasswordCredentialsGrant, +) +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator +from oauthlib.oauth2.rfc6749.tokens import BearerToken +from oauthlib.oauth2.rfc8628.grant_types import DeviceCodeGrant + +from ..grant_types import AuthorizationCodeGrant, HybridGrant, ImplicitGrant +from ..grant_types.dispatchers import ( + AuthorizationCodeGrantDispatcher, + AuthorizationTokenGrantDispatcher, + ImplicitTokenGrantDispatcher, +) +from ..tokens import JWTToken +from .userinfo import UserInfoEndpoint + +class Server(AuthorizationEndpoint, IntrospectEndpoint, TokenEndpoint, ResourceEndpoint, RevocationEndpoint, UserInfoEndpoint): + auth_grant: OAuth2AuthorizationCodeGrant + implicit_grant: OAuth2ImplicitGrant + password_grant: ResourceOwnerPasswordCredentialsGrant + credentials_grant: ClientCredentialsGrant + refresh_grant: RefreshTokenGrant + openid_connect_auth: AuthorizationCodeGrant + openid_connect_implicit: ImplicitGrant + openid_connect_hybrid: HybridGrant + device_code_grant: DeviceCodeGrant + bearer: BearerToken + jwt: JWTToken + auth_grant_choice: AuthorizationCodeGrantDispatcher + implicit_grant_choice: ImplicitTokenGrantDispatcher + token_grant_choice: AuthorizationTokenGrantDispatcher + def __init__( + self, + request_validator: OAuth2RequestValidator, + token_expires_in: int | Callable[[Request], int] | None = None, + token_generator: Callable[[Request], str] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + *args: Unused, + ) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi new file mode 100644 index 000000000000..13a8d4826a71 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/endpoints/userinfo.pyi @@ -0,0 +1,22 @@ +from collections.abc import Mapping +from logging import Logger + +from oauthlib.common import Request, _HTTPMethod +from oauthlib.oauth2.rfc6749.endpoints.base import BaseEndpoint +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator +from oauthlib.oauth2.rfc6749.tokens import BearerToken + +log: Logger + +class UserInfoEndpoint(BaseEndpoint): + bearer: BearerToken + request_validator: OAuth2RequestValidator + def __init__(self, request_validator: OAuth2RequestValidator) -> None: ... + def create_userinfo_response( + self, + uri: str, + http_method: _HTTPMethod = "GET", + body: str | dict[str, str] | list[tuple[str, str]] | None = None, + headers: Mapping[str, str] | None = None, + ) -> tuple[dict[str, str], str, int]: ... + def validate_userinfo_request(self, request: Request) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi new file mode 100644 index 000000000000..b552251df96a --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/exceptions.pyi @@ -0,0 +1,51 @@ +from oauthlib.oauth2.rfc6749.errors import FatalClientError, OAuth2Error + +class FatalOpenIDClientError(FatalClientError): ... +class OpenIDClientError(OAuth2Error): ... + +class InteractionRequired(OpenIDClientError): + error: str + status_code: int + +class LoginRequired(OpenIDClientError): + error: str + status_code: int + +class AccountSelectionRequired(OpenIDClientError): + error: str + +class ConsentRequired(OpenIDClientError): + error: str + status_code: int + +class InvalidRequestURI(OpenIDClientError): + error: str + description: str + +class InvalidRequestObject(OpenIDClientError): + error: str + description: str + +class RequestNotSupported(OpenIDClientError): + error: str + description: str + +class RequestURINotSupported(OpenIDClientError): + error: str + description: str + +class RegistrationNotSupported(OpenIDClientError): + error: str + description: str + +class InvalidTokenError(OAuth2Error): + error: str + status_code: int + description: str + +class InsufficientScopeError(OAuth2Error): + error: str + status_code: int + description: str + +def raise_from_error(error: object, params: dict[str, str] | None = None) -> None: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi new file mode 100644 index 000000000000..9d15b72bbf98 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/__init__.pyi @@ -0,0 +1,10 @@ +from .authorization_code import AuthorizationCodeGrant as AuthorizationCodeGrant +from .base import GrantTypeBase as GrantTypeBase +from .dispatchers import ( + AuthorizationCodeGrantDispatcher as AuthorizationCodeGrantDispatcher, + AuthorizationTokenGrantDispatcher as AuthorizationTokenGrantDispatcher, + ImplicitTokenGrantDispatcher as ImplicitTokenGrantDispatcher, +) +from .hybrid import HybridGrant as HybridGrant +from .implicit import ImplicitGrant as ImplicitGrant +from .refresh_token import RefreshTokenGrant as RefreshTokenGrant diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi new file mode 100644 index 000000000000..ff419e356d09 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/authorization_code.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +from .base import GrantTypeBase + +log: Logger + +class AuthorizationCodeGrant(GrantTypeBase): + proxy_target: OAuth2AuthorizationCodeGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi new file mode 100644 index 000000000000..c7c3039277b3 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/base.pyi @@ -0,0 +1,19 @@ +from _hashlib import HASH +from collections.abc import Callable +from logging import Logger + +from oauthlib.common import Request + +log: Logger + +class GrantTypeBase: + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def validate_authorization_request(self, request: Request): ... + def id_token_hash( + self, value: str, hashfunc: Callable[..., HASH] = ... # Arguments: ReadableBuffer (string) and bool (usedforsecurity) + ) -> str: ... + def add_id_token(self, token, token_handler, request: Request, nonce=None): ... + def openid_authorization_validator(self, request: Request): ... + +OpenIDConnectBase = GrantTypeBase diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi new file mode 100644 index 000000000000..67428ed7d1e8 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/dispatchers.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +log: Logger + +class Dispatcher: + default_grant: Incomplete | None + oidc_grant: Incomplete | None + +class AuthorizationCodeGrantDispatcher(Dispatcher): + default_grant: Incomplete | None + oidc_grant: Incomplete | None + def __init__(self, default_grant=None, oidc_grant=None) -> None: ... + def create_authorization_response(self, request: Request, token_handler): ... + def validate_authorization_request(self, request: Request): ... + +class ImplicitTokenGrantDispatcher(Dispatcher): + default_grant: Incomplete | None + oidc_grant: Incomplete | None + def __init__(self, default_grant=None, oidc_grant=None) -> None: ... + def create_authorization_response(self, request: Request, token_handler): ... + def validate_authorization_request(self, request: Request): ... + +class AuthorizationTokenGrantDispatcher(Dispatcher): + default_grant: Incomplete | None + oidc_grant: Incomplete | None + request_validator: OAuth2RequestValidator + def __init__(self, request_validator: OAuth2RequestValidator, default_grant=None, oidc_grant=None) -> None: ... + def create_token_response(self, request: Request, token_handler): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi new file mode 100644 index 000000000000..58532a495671 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/hybrid.pyi @@ -0,0 +1,29 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.errors import InvalidRequestError as InvalidRequestError +from oauthlib.oauth2.rfc6749.grant_types.authorization_code import AuthorizationCodeGrant as OAuth2AuthorizationCodeGrant +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +from ..request_validator import RequestValidator +from .base import GrantTypeBase + +log: Logger + +class HybridGrant(GrantTypeBase): + request_validator: OAuth2RequestValidator | RequestValidator + proxy_target: OAuth2AuthorizationCodeGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] + def openid_authorization_validator(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi new file mode 100644 index 000000000000..366627c0b008 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/implicit.pyi @@ -0,0 +1,26 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.grant_types.implicit import ImplicitGrant as OAuth2ImplicitGrant +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +from .base import GrantTypeBase + +log: Logger + +class ImplicitGrant(GrantTypeBase): + proxy_target: OAuth2ImplicitGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] + def openid_authorization_validator(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi new file mode 100644 index 000000000000..b9b953ebe478 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/grant_types/refresh_token.pyi @@ -0,0 +1,25 @@ +from collections.abc import Iterable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.grant_types.base import _AuthValidator, _TokenValidator +from oauthlib.oauth2.rfc6749.grant_types.refresh_token import RefreshTokenGrant as OAuth2RefreshTokenGrant +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +from .base import GrantTypeBase + +log: Logger + +class RefreshTokenGrant(GrantTypeBase): + proxy_target: OAuth2RefreshTokenGrant + def __init__( + self, + request_validator: OAuth2RequestValidator | None = None, + *, + post_auth: Iterable[_AuthValidator] | None = None, + post_token: Iterable[_TokenValidator] | None = None, + pre_auth: Iterable[_AuthValidator] | None = None, + pre_token: Iterable[_TokenValidator] | None = None, + **kwargs, + ) -> None: ... + def add_id_token(self, token, token_handler, request: Request): ... # type: ignore[override] diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi new file mode 100644 index 000000000000..ca6de4bf5752 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/request_validator.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.request_validator import RequestValidator as OAuth2RequestValidator + +log: Logger + +class RequestValidator(OAuth2RequestValidator): + def get_authorization_code_scopes(self, client_id: str, code: str, redirect_uri: str, request) -> list[str]: ... + def get_authorization_code_nonce(self, client_id: str, code: str, redirect_uri: str, request) -> str: ... + def get_jwt_bearer_token(self, token: dict[str, Incomplete], token_handler, request: Request) -> str: ... + def get_id_token(self, token: dict[str, Incomplete], token_handler, request: Request) -> str: ... + def finalize_id_token( + self, id_token: dict[str, Incomplete], token: dict[str, Incomplete], token_handler: Callable[..., str], request: Request + ) -> str: ... + def validate_jwt_bearer_token(self, token: str, scopes, request: Request) -> bool: ... + def validate_id_token(self, token: str, scopes, request: Request) -> bool: ... + def validate_silent_authorization(self, request: Request) -> bool: ... + def validate_silent_login(self, request: Request) -> bool: ... + def validate_user_match(self, id_token_hint: str, scopes, claims: dict[str, Incomplete], request: Request) -> bool: ... + def get_userinfo_claims(self, request: Request) -> dict[str, Incomplete] | str: ... + def refresh_id_token(self, request: Request) -> bool: ... diff --git a/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi b/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi new file mode 100644 index 000000000000..39c52b1d0753 --- /dev/null +++ b/stubs/oauthlib/oauthlib/openid/connect/core/tokens.pyi @@ -0,0 +1,23 @@ +from collections.abc import Callable + +from oauthlib.common import Request +from oauthlib.oauth2.rfc6749.tokens import TokenBase as TokenBase + +from .request_validator import RequestValidator + +class JWTToken(TokenBase): + __slots__ = ("request_validator", "token_generator", "refresh_token_generator", "expires_in") + request_validator: RequestValidator + token_generator: Callable[[Request], str] | Callable[[Request, bool], str] + refresh_token_generator: Callable[[Request], str] | Callable[[Request, bool], str] + expires_in: int | Callable[[Request], int] + def __init__( + self, + request_validator: RequestValidator | None = None, + token_generator: Callable[[Request], str] | None = None, + expires_in: int | Callable[[Request], int] | None = None, + refresh_token_generator: Callable[[Request], str] | None = None, + ) -> None: ... + def create_token(self, request: Request, refresh_token: bool = False): ... + def validate_request(self, request: Request): ... + def estimate_type(self, request: Request): ... diff --git a/stubs/oauthlib/oauthlib/signals.pyi b/stubs/oauthlib/oauthlib/signals.pyi new file mode 100644 index 000000000000..e24c057315a5 --- /dev/null +++ b/stubs/oauthlib/oauthlib/signals.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +signals_available: bool + +class Namespace: + def signal(self, name: str, doc: str | None = None) -> _FakeSignal: ... + +class _FakeSignal: + name: str + __doc__: str | None + def __init__(self, name: str, doc: str | None = None) -> None: ... + send: Incomplete + connect: Incomplete + disconnect: Incomplete + has_receivers_for: Incomplete + receivers_for: Incomplete + temporarily_connected_to: Incomplete + connected_to: Incomplete + +scope_changed: _FakeSignal diff --git a/stubs/oauthlib/oauthlib/uri_validate.pyi b/stubs/oauthlib/oauthlib/uri_validate.pyi new file mode 100644 index 000000000000..f4f90ea4c9f1 --- /dev/null +++ b/stubs/oauthlib/oauthlib/uri_validate.pyi @@ -0,0 +1,44 @@ +import re +from typing import Final + +DIGIT: Final[str] +ALPHA: Final[str] +HEXDIG: Final[str] +pct_encoded: Final[str] +unreserved: Final[str] +gen_delims: Final[str] +sub_delims: Final[str] +pchar: Final[str] +reserved: Final[str] +scheme: Final[str] +dec_octet: Final[str] +IPv4address: Final[str] +IPv6address: Final[str] +IPvFuture: Final[str] +IP_literal: Final[str] +reg_name: Final[str] +userinfo: Final[str] +host: Final[str] +port: Final[str] +authority: Final[str] +segment: Final[str] +segment_nz: Final[str] +segment_nz_nc: Final[str] +path_abempty: Final[str] +path_absolute: Final[str] +path_noscheme: Final[str] +path_rootless: Final[str] +path_empty: Final[str] +path: Final[str] +query: Final[str] +fragment: Final[str] +hier_part: Final[str] +relative_part: Final[str] +relative_ref: Final[str] +URI: Final[str] +URI_reference: Final[str] +absolute_URI: Final[str] + +def is_uri(uri: str) -> re.Match[str] | None: ... +def is_uri_reference(uri: str) -> re.Match[str] | None: ... +def is_absolute_uri(uri: str) -> re.Match[str] | None: ... diff --git a/stubs/objgraph/METADATA.toml b/stubs/objgraph/METADATA.toml new file mode 100644 index 000000000000..5ed5672fc501 --- /dev/null +++ b/stubs/objgraph/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.6.*" +upstream-repository = "https://github.com/mgedmin/objgraph" diff --git a/stubs/objgraph/objgraph.pyi b/stubs/objgraph/objgraph.pyi new file mode 100644 index 000000000000..8278461c3fde --- /dev/null +++ b/stubs/objgraph/objgraph.pyi @@ -0,0 +1,90 @@ +from _typeshed import Incomplete, SupportsWrite +from collections import defaultdict +from collections.abc import Callable, Container, Iterable +from types import ModuleType +from typing import Final, Literal, TypeAlias, TypeGuard + +IS_INTERACTIVE: bool + +__author__: Final[str] +__copyright__: Final[str] +__license__: Final[str] +__version__: Final[str] +__date__: Final[str] + +# GraphViz has types, but does not include the py.typed file. +# See https://github.com/xflr6/graphviz/pull/180 +_GraphvizSource: TypeAlias = Incomplete +_Filter: TypeAlias = Callable[[object], bool] + +def count(typename: str, objects: Iterable[object] | None = None) -> int: ... +def typestats( + objects: Iterable[object] | None = None, shortnames: bool = True, filter: _Filter | None = None +) -> dict[str, int]: ... +def most_common_types( + limit: int = 10, objects: Iterable[object] | None = None, shortnames: bool = True, filter: _Filter | None = None +) -> list[tuple[str, int]]: ... +def show_most_common_types( + limit: int = 10, + objects: Iterable[object] | None = None, + shortnames: bool = True, + file: SupportsWrite[str] | None = None, + filter: _Filter | None = None, +) -> None: ... +def growth( + limit: int = 10, peak_stats: dict[str, int] = {}, shortnames: bool = True, filter: _Filter | None = None +) -> list[tuple[str, int, int]]: ... +def show_growth( + limit: int = 10, + peak_stats: dict[str, int] | None = None, + shortnames: bool = True, + file: SupportsWrite[str] | None = None, + filter: _Filter | None = None, +) -> None: ... +def get_new_ids( + skip_update: bool = False, + limit: int = 10, + sortby: Literal["old", "current", "new", "deltas"] = "deltas", + shortnames: bool | None = None, + file: SupportsWrite[str] | None = None, +) -> defaultdict[str, set[int]]: ... +def get_leaking_objects(objects: Iterable[object] | None = None) -> list[object]: ... +def by_type(typename: str, objects: Iterable[object] | None = None) -> list[object]: ... +def at(addr: int) -> object: ... +def at_addrs(address_set: Container[int]) -> list[object]: ... +def find_ref_chain(obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = ()) -> list[object]: ... +def find_backref_chain( + obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = () +) -> list[object]: ... +def show_backrefs( + objs: object, + max_depth: int = 3, + extra_ignore: Iterable[int] = (), + filter: _Filter | None = None, + too_many: int = 10, + highlight: object = None, + filename: str | None = None, + extra_info: Callable[[object], str] | None = None, + refcounts: bool = False, + shortnames: bool = True, + output: SupportsWrite[str] | None = None, + extra_node_attrs: Callable[[object], dict[str, str]] | None = None, +) -> None | _GraphvizSource: ... +def show_refs( + objs: object, + max_depth: int = 3, + extra_ignore: Iterable[int] = (), + filter: _Filter | None = None, + too_many: int = 10, + highlight: object = None, + filename: str | None = None, + extra_info: Callable[[object], str] | None = None, + refcounts: bool = False, + shortnames: bool = True, + output: SupportsWrite[str] | None = None, + extra_node_attrs: Callable[[object], dict[str, str]] | None = None, +) -> None | _GraphvizSource: ... +def show_chain( + *chains: list[object], obj: object, predicate: _Filter, max_depth: int = 20, extra_ignore: Iterable[int] = () +) -> None: ... +def is_proper_module(obj: object) -> TypeGuard[ModuleType]: ... diff --git a/stubs/olefile/@tests/stubtest_allowlist.txt b/stubs/olefile/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f3c51d672f96 --- /dev/null +++ b/stubs/olefile/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +olefile.olefile2.* diff --git a/stubs/olefile/METADATA.toml b/stubs/olefile/METADATA.toml new file mode 100644 index 000000000000..63c57f41365d --- /dev/null +++ b/stubs/olefile/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.47.*" +upstream-repository = "https://github.com/decalage2/olefile" diff --git a/stubs/olefile/olefile/__init__.pyi b/stubs/olefile/olefile/__init__.pyi new file mode 100644 index 000000000000..4697cce81955 --- /dev/null +++ b/stubs/olefile/olefile/__init__.pyi @@ -0,0 +1,2 @@ +from .olefile import * +from .olefile import __all__ as __all__, __author__ as __author__, __date__ as __date__, __version__ as __version__ diff --git a/stubs/olefile/olefile/olefile.pyi b/stubs/olefile/olefile/olefile.pyi new file mode 100644 index 000000000000..3790921224bb --- /dev/null +++ b/stubs/olefile/olefile/olefile.pyi @@ -0,0 +1,247 @@ +import array +import datetime +import io +import logging +import traceback +from collections.abc import Sequence +from typing import IO, AnyStr, Generic, TypeAlias +from typing_extensions import Self + +__date__: str +__version__: str +__author__: str + +__all__ = [ + "isOleFile", + "OleFileIO", + "OleMetadata", + "enable_logging", + "MAGIC", + "STGTY_EMPTY", + "STGTY_STREAM", + "STGTY_STORAGE", + "STGTY_ROOT", + "STGTY_PROPERTY", + "STGTY_LOCKBYTES", + "MINIMAL_OLEFILE_SIZE", + "DEFECT_UNSURE", + "DEFECT_POTENTIAL", + "DEFECT_INCORRECT", + "DEFECT_FATAL", + "DEFAULT_PATH_ENCODING", + "MAXREGSECT", + "DIFSECT", + "FATSECT", + "ENDOFCHAIN", + "FREESECT", + "MAXREGSID", + "NOSTREAM", + "UNKNOWN_SIZE", + "WORD_CLSID", + "OleFileIONotClosed", +] + +UINT32: str + +DEFAULT_PATH_ENCODING: str | None + +def get_logger(name: str, level: int = 51) -> logging.Logger: ... + +log: logging.Logger + +def enable_logging() -> None: ... + +MAGIC: bytes + +MAXREGSECT: int +DIFSECT: int +FATSECT: int +ENDOFCHAIN: int +FREESECT: int + +MAXREGSID: int +NOSTREAM: int + +STGTY_EMPTY: int +STGTY_STORAGE: int +STGTY_STREAM: int +STGTY_LOCKBYTES: int +STGTY_PROPERTY: int +STGTY_ROOT: int + +UNKNOWN_SIZE: int + +VT_EMPTY: int +VT_NULL: int +VT_I2: int +VT_I4: int +VT_R4: int +VT_R8: int +VT_CY: int +VT_DATE: int +VT_BSTR: int +VT_DISPATCH: int +VT_ERROR: int +VT_BOOL: int +VT_VARIANT: int +VT_UNKNOWN: int +VT_DECIMAL: int +VT_I1: int +VT_UI1: int +VT_UI2: int +VT_UI4: int +VT_I8: int +VT_UI8: int +VT_INT: int +VT_UINT: int +VT_VOID: int +VT_HRESULT: int +VT_PTR: int +VT_SAFEARRAY: int +VT_CARRAY: int +VT_USERDEFINED: int +VT_LPSTR: int +VT_LPWSTR: int +VT_FILETIME: int +VT_BLOB: int +VT_STREAM: int +VT_STORAGE: int +VT_STREAMED_OBJECT: int +VT_STORED_OBJECT: int +VT_BLOB_OBJECT: int +VT_CF: int +VT_CLSID: int +VT_VECTOR: int + +VT: dict[int, str] + +WORD_CLSID: str +DEFECT_UNSURE: int +DEFECT_POTENTIAL: int +DEFECT_INCORRECT: int +DEFECT_FATAL: int +MINIMAL_OLEFILE_SIZE: int + +def isOleFile(filename: IO[bytes] | bytes | str | None = None, data: bytes | None = None) -> bool: ... +def i8(c: bytes | int) -> int: ... +def i16(c: bytes, o: int = 0) -> int: ... +def i32(c: bytes, o: int = 0) -> int: ... +def _clsid(clsid: bytes) -> str: ... +def filetime2datetime(filetime: int) -> datetime.datetime: ... + +class OleFileError(IOError): ... +class NotOleFileError(OleFileError): ... + +class OleMetadata: + SUMMARY_ATTRIBS: list[str] + DOCSUM_ATTRIBS: list[str] + + def __init__(self) -> None: ... + def parse_properties(self, ole_file: OleFileIO[AnyStr]) -> None: ... + def dump(self) -> None: ... + +class OleFileIONotClosed(RuntimeWarning): + def __init__(self, stack_of_open: traceback.FrameSummary | None = None) -> None: ... + +class OleStream(io.BytesIO): + def __init__( + self, + fp: IO[bytes], + sect: int, + size: int, + offset: int, + sectorsize: int, + fat: list[int], + filesize: int, + olefileio: OleFileIO[AnyStr], + ) -> None: ... + +class OleDirectoryEntry(Generic[AnyStr]): + STRUCT_DIRENTRY: str + DIRENTRY_SIZE: int + clsid: str + + def __init__(self, entry: bytes, sid: int, ole_file: OleFileIO[AnyStr]) -> None: ... + def build_sect_chain(self, ole_file: OleFileIO[AnyStr]) -> None: ... + def build_storage_tree(self) -> None: ... + def append_kids(self, child_sid: int) -> None: ... + def __eq__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __lt__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... + def __ne__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... # type: ignore[override] + def __le__(self, other: OleDirectoryEntry[AnyStr]) -> bool: ... + def dump(self, tab: int = 0) -> None: ... + def getmtime(self) -> datetime.datetime | None: ... + def getctime(self) -> datetime.datetime | None: ... + +_Property: TypeAlias = int | str | bytes | bool | None + +class OleFileIO(Generic[AnyStr]): + root: OleDirectoryEntry[AnyStr] | None + + def __init__( + self, + filename: IO[bytes] | AnyStr | None = None, + raise_defects: int = 40, + write_mode: bool = False, + debug: bool = False, + path_encoding: str | None = DEFAULT_PATH_ENCODING, # noqa: Y011 + ) -> None: ... + def __del__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def _raise_defect( + self, defect_level: int, message: str, exception_type: type[Exception] = OleFileError # noqa: Y011 + ) -> None: ... + def _decode_utf16_str(self, utf16_str: bytes, errors: str = "replace") -> str | bytes: ... + def open(self, filename: IO[bytes] | AnyStr, write_mode: bool = False) -> None: ... + def close(self) -> None: ... + def _close(self, warn: bool = False) -> None: ... + def _check_duplicate_stream(self, first_sect: int, minifat: bool = False) -> None: ... + def dumpfat(self, fat: Sequence[int], firstindex: int = 0) -> None: ... + def dumpsect(self, sector: bytes, firstindex: int = 0) -> None: ... + def sect2array(self, sect: bytes) -> Sequence[int]: ... + def loadfat_sect(self, sect: bytes | array.array[int]) -> int | None: ... + def loadfat(self, header: bytes) -> None: ... + def loadminifat(self) -> None: ... + def getsect(self, sect: int) -> bytes: ... + def write_sect(self, sect: int, data: bytes, padding: bytes = b"\x00") -> None: ... + def _write_mini_sect(self, fp_pos: int, data: bytes, padding: bytes = b"\x00") -> None: ... + def loaddirectory(self, sect: int) -> None: ... + def _load_direntry(self, sid: int) -> OleDirectoryEntry[AnyStr]: ... + def dumpdirectory(self) -> None: ... + def _open(self, start: int, size: int = 0x7FFFFFFF, force_FAT: bool = False) -> OleStream: ... + def _list( + self, + files: list[list[AnyStr]], + prefix: list[AnyStr], + node: OleDirectoryEntry[AnyStr], + streams: bool = True, + storages: bool = False, + ) -> None: ... + def listdir(self, streams: bool = True, storages: bool = False) -> list[list[AnyStr]]: ... + def _find(self, filename: str | Sequence[str]) -> int: ... + def openstream(self, filename: AnyStr | Sequence[AnyStr]) -> OleStream: ... + def _write_mini_stream(self, entry: OleDirectoryEntry[AnyStr], data_to_write: bytes) -> None: ... + def write_stream(self, stream_name: str | Sequence[str], data: bytes) -> None: ... + def get_type(self, filename: AnyStr | Sequence[AnyStr]) -> bool | int: ... + def getclsid(self, filename: AnyStr | Sequence[AnyStr]) -> str: ... + def getmtime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def getctime(self, filename: AnyStr | Sequence[AnyStr]) -> datetime.datetime | None: ... + def exists(self, filename: AnyStr | Sequence[AnyStr]) -> bool: ... + def get_size(self, filename: AnyStr | Sequence[AnyStr]) -> int: ... + def get_rootentry_name(self) -> bytes: ... + def getproperties( + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None + ) -> dict[int, list[_Property] | _Property]: ... + def _parse_property( + self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] + ) -> list[_Property] | _Property: ... + def _parse_property_basic( + self, s: bytes, offset: int, property_id: int, property_type: int, convert_time: bool, no_conversion: list[int] + ) -> tuple[_Property, int]: ... + def get_metadata(self) -> OleMetadata: ... + def get_userdefined_properties( + self, filename: AnyStr | Sequence[AnyStr], convert_time: bool = False, no_conversion: list[int] | None = None + ) -> list[dict[str, bytes | int | None]]: ... + +def main() -> None: ... diff --git a/stubs/openpyxl/@tests/stubtest_allowlist.txt b/stubs/openpyxl/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..20c1b03197d2 --- /dev/null +++ b/stubs/openpyxl/@tests/stubtest_allowlist.txt @@ -0,0 +1,183 @@ +# Unintended re-export from star-import +openpyxl.chart.marker.DRAWING_NS +openpyxl.chart.marker.PRESET_COLORS +openpyxl.chart.shapes.DRAWING_NS +openpyxl.chart.shapes.PRESET_COLORS +openpyxl.descriptors.DEBUG + +# The actual runtime definition depends on what else is installed +# (lxml, defusedxml, et_xmlfile) +openpyxl.xml._functions_overloads + +# Requires numpy to be installed +openpyxl.utils.dataframe + +# Fake getters +openpyxl.descriptors.(base.)?Descriptor.__get__ +openpyxl.descriptors.(base.)?MatchPattern.__get__ +openpyxl.descriptors.(base.)?Typed.__get__ +openpyxl.descriptors.nested.EmptyTag.__get__ +openpyxl.descriptors.nested.Nested.__get__ +openpyxl.descriptors.nested.NestedMinMax.__get__ +openpyxl.descriptors.nested.NestedText.__get__ +openpyxl.descriptors.nested.NestedValue.__get__ + +# Stubtest doesn't like generics here +openpyxl\.descriptors\.(base\.)?Bool\.allow_none +openpyxl\.descriptors\.(base\.)?DateTime\.allow_none +openpyxl\.descriptors\.(base\.)?Float\.allow_none +openpyxl\.descriptors\.(base\.)?Integer\.allow_none +openpyxl\.descriptors\.(base\.)?MatchPattern\.allow_none +openpyxl\.descriptors\.(base\.)?Max\.allow_none +openpyxl\.descriptors\.(base\.)?Min\.allow_none +openpyxl\.descriptors\.(base\.)?MinMax\.allow_none +openpyxl\.descriptors\.(base\.)?String\.allow_none +openpyxl\.descriptors\.(base\.)?Typed\.allow_none + +# Inconsistent methods because +# - using the default value results in an error because of the runtime type-guards +# - or, keyword arguments are explicitly specified +openpyxl.cell.cell.Cell.__init__ +openpyxl.cell.cell.WriteOnlyCell +openpyxl.cell.text.PhoneticProperties.__init__ +openpyxl.cell.text.PhoneticText.__init__ +openpyxl.chart.axis._BaseAxis.__init__ +openpyxl.chart.chartspace.ChartSpace.__init__ +openpyxl.chart.chartspace.ExternalData.__init__ +openpyxl.chart.data_source.NumFmt.__init__ +openpyxl.chart.data_source.NumVal.__init__ +openpyxl.chart.marker.DataPoint.__init__ +openpyxl.chart.pivot.PivotSource.__init__ +openpyxl.chartsheet.custom.CustomChartsheetView.__init__ +openpyxl.chartsheet.publish.WebPublishItem.__init__ +openpyxl.comments.comment_sheet.CommentSheet.__init__ +openpyxl.comments.comment_sheet.Properties.__init__ +openpyxl.descriptors.excel.Extension.__init__ +openpyxl.drawing.colors.HSLColor.__init__ +openpyxl.drawing.colors.RGBPercent.__init__ +openpyxl.drawing.colors.SchemeColor.__init__ +openpyxl.drawing.connector.Connection.__init__ +openpyxl.drawing.connector.ConnectorNonVisual.__init__ +openpyxl.drawing.connector.ConnectorShape.__init__ +openpyxl.drawing.connector.Shape.__init__ +openpyxl.drawing.connector.ShapeMeta.__init__ +openpyxl.drawing.effect.AlphaBiLevelEffect.__init__ +openpyxl.drawing.effect.AlphaModulateEffect.__init__ +openpyxl.drawing.effect.AlphaModulateFixedEffect.__init__ +openpyxl.drawing.effect.AlphaReplaceEffect.__init__ +openpyxl.drawing.effect.BiLevelEffect.__init__ +openpyxl.drawing.effect.BlurEffect.__init__ +openpyxl.drawing.effect.ColorChangeEffect.__init__ +openpyxl.drawing.effect.EffectContainer.__init__ +openpyxl.drawing.effect.FillOverlayEffect.__init__ +openpyxl.drawing.effect.GlowEffect.__init__ +openpyxl.drawing.effect.HSLEffect.__init__ +openpyxl.drawing.effect.InnerShadowEffect.__init__ +openpyxl.drawing.effect.OuterShadow.__init__ +openpyxl.drawing.effect.PresetShadowEffect.__init__ +openpyxl.drawing.effect.ReflectionEffect.__init__ +openpyxl.drawing.effect.SoftEdgesEffect.__init__ +openpyxl.drawing.fill.LinearShadeProperties.__init__ +openpyxl.drawing.fill.PathShadeProperties.__init__ +openpyxl.drawing.fill.TileInfoProperties.__init__ +openpyxl.drawing.geometry.Backdrop.__init__ +openpyxl.drawing.geometry.Bevel.__init__ +openpyxl.drawing.geometry.Camera.__init__ +openpyxl.drawing.geometry.ConnectionSite.__init__ +openpyxl.drawing.geometry.CustomGeometry2D.__init__ +openpyxl.drawing.geometry.GeomGuide.__init__ +openpyxl.drawing.geometry.LightRig.__init__ +openpyxl.drawing.geometry.Path2D.__init__ +openpyxl.drawing.geometry.Point3D.__init__ +openpyxl.drawing.geometry.PositiveSize2D.__init__ +openpyxl.drawing.geometry.PresetGeometry2D.__init__ +openpyxl.drawing.geometry.Scene3D.__init__ +openpyxl.drawing.geometry.ShapeStyle.__init__ +openpyxl.drawing.geometry.SphereCoords.__init__ +openpyxl.drawing.geometry.StyleMatrixReference.__init__ +openpyxl.drawing.geometry.Vector3D.__init__ +openpyxl.drawing.graphic.GroupShape.__init__ +openpyxl.drawing.properties.NonVisualDrawingProps.__init__ +openpyxl.drawing.properties.NonVisualGroupShape.__init__ +openpyxl.drawing.text.AutonumberBullet.__init__ +openpyxl.drawing.text.Font.__init__ +openpyxl.drawing.text.GeomGuide.__init__ +openpyxl.drawing.text.PresetTextShape.__init__ +openpyxl.drawing.text.TextField.__init__ +openpyxl.drawing.text.TextNormalAutofit.__init__ +openpyxl.formatting.rule.DataBar.__init__ +openpyxl.packaging.core.QualifiedDateTime.to_tree +openpyxl.packaging.relationship.get_rel +openpyxl.packaging.relationship.Relationship.__init__ +openpyxl.packaging.workbook.ChildSheet.__init__ +openpyxl.packaging.workbook.PivotCache.__init__ +openpyxl.pivot.cache.CacheDefinition.__init__ +openpyxl.pivot.cache.CacheField.__init__ +openpyxl.pivot.cache.CacheHierarchy.__init__ +openpyxl.pivot.cache.CacheSource.__init__ +openpyxl.pivot.cache.CalculatedItem.__init__ +openpyxl.pivot.cache.CalculatedMember.__init__ +openpyxl.pivot.cache.FieldUsage.__init__ +openpyxl.pivot.cache.GroupLevel.__init__ +openpyxl.pivot.cache.GroupMember.__init__ +openpyxl.pivot.cache.LevelGroup.__init__ +openpyxl.pivot.cache.MeasureGroup.__init__ +openpyxl.pivot.cache.OLAPSet.__init__ +openpyxl.pivot.cache.PageItem.__init__ +openpyxl.pivot.cache.PCDSDTCEntries.__init__ +openpyxl.pivot.cache.PivotDimension.__init__ +openpyxl.pivot.cache.Query.__init__ +openpyxl.pivot.cache.RangeSet.__init__ +openpyxl.pivot.fields.Error.__init__ +openpyxl.pivot.fields.Number.__init__ +openpyxl.pivot.fields.Tuple.__init__ +openpyxl.pivot.fields.TupleList.__init__ +openpyxl.pivot.table.AutoSortScope.__init__ +openpyxl.pivot.table.ChartFormat.__init__ +openpyxl.pivot.table.ConditionalFormat.__init__ +openpyxl.pivot.table.DataField.__init__ +openpyxl.pivot.table.Format.__init__ +openpyxl.pivot.table.HierarchyUsage.__init__ +openpyxl.pivot.table.Location.__init__ +openpyxl.pivot.table.MemberProperty.__init__ +openpyxl.pivot.table.PageField.__init__ +openpyxl.pivot.table.PivotFilter.__init__ +openpyxl.pivot.table.PivotFilters.__init__ +openpyxl.pivot.table.RowColField.__init__ +openpyxl.pivot.table.TableDefinition.__init__ +openpyxl.styles.colors.RgbColor.__init__ +openpyxl.styles.named_styles._NamedCellStyle.__init__ +openpyxl.styles.numbers.NumberFormat.__init__ +openpyxl.styles.table.TableStyle.__init__ +openpyxl.styles.table.TableStyleElement.__init__ +openpyxl.workbook.defined_name.DefinedName.__init__ +openpyxl.workbook.external_link.external.ExternalCell.__init__ +openpyxl.workbook.external_link.external.ExternalDefinedName.__init__ +openpyxl.workbook.external_link.external.ExternalRow.__init__ +openpyxl.workbook.external_link.external.ExternalSheetData.__init__ +openpyxl.workbook.function_group.FunctionGroup.__init__ +openpyxl.workbook.views.CustomWorkbookView.__init__ +openpyxl.workbook.web.WebPublishObject.__init__ +openpyxl.worksheet.cell_watch.CellWatch.__init__ +openpyxl.worksheet.controls.Control.__init__ +openpyxl.worksheet.controls.ControlProperty.__init__ +openpyxl.worksheet.custom.CustomProperty.__init__ +openpyxl.worksheet.dimensions.RowDimension.__init__ +openpyxl.worksheet.dimensions.SheetDimension.__init__ +openpyxl.worksheet.filters.DateGroupItem.__init__ +openpyxl.worksheet.filters.DynamicFilter.__init__ +openpyxl.worksheet.filters.FilterColumn.__init__ +openpyxl.worksheet.filters.IconFilter.__init__ +openpyxl.worksheet.filters.Top10.__init__ +openpyxl.worksheet.hyperlink.Hyperlink.__init__ +openpyxl.worksheet.ole.ObjectAnchor.__init__ +openpyxl.worksheet.ole.ObjectPr.__init__ +openpyxl.worksheet.ole.OleObject.__init__ +openpyxl.worksheet.print_settings.RowRange.__init__ +openpyxl.worksheet.scenario.InputCells.__init__ +openpyxl.worksheet.scenario.Scenario.__init__ +openpyxl.worksheet.smart_tag.CellSmartTag.__init__ +openpyxl.worksheet.smart_tag.CellSmartTagPr.__init__ +openpyxl.worksheet.smart_tag.CellSmartTags.__init__ +openpyxl.worksheet.table.TableColumn.__init__ +openpyxl.worksheet.table.XMLColumnProps.__init__ diff --git a/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py b/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py new file mode 100644 index 000000000000..858892a974bc --- /dev/null +++ b/stubs/openpyxl/@tests/test_cases/check_base_descriptors.py @@ -0,0 +1,392 @@ +# Needed until mypy issues are solved or https://github.com/python/mypy/issues/12358 +# pyright: reportUnnecessaryTypeIgnoreComment=false +from __future__ import annotations + +from _typeshed import ReadableBuffer +from datetime import date, datetime, time +from typing import Any, List, Literal, Tuple, Union +from typing_extensions import assert_type + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import ( + Bool, + Convertible, + DateTime, + Descriptor, + Float, + Integer, + Length, + MatchPattern, + MinMax, + NoneSet, + Set, + String, + Typed, +) +from openpyxl.descriptors.serialisable import Serialisable + + +class WithDescriptors(Serialisable): + descriptor = Descriptor[str]() + + typed_default = Typed(expected_type=str) + typed_not_none = Typed(expected_type=str, allow_none=False) + typed_none = Typed(expected_type=str, allow_none=True) + + set_tuple = Set(values=("a", 1, 0.0)) + set_list = Set(values=["a", 1, 0.0]) + set_tuple_none = Set(values=("a", 1, 0.0, None)) + + noneset_tuple = NoneSet(values=("a", 1, 0.0)) + noneset_list = NoneSet(values=["a", 1, 0.0]) + + length_tuple = Length[Tuple[str, str]](length=1) # Can't validate tuple length in a generic manner + length_list = Length[List[str]](length=1) + length_invalid = Length[object](length=1) # type: ignore + + match_pattern_str_default = MatchPattern(pattern="") + match_pattern_str = MatchPattern(pattern="", allow_none=False) + match_pattern_str_none = MatchPattern(pattern="", allow_none=True) + match_pattern_bytes_default = MatchPattern(pattern=b"") + match_pattern_bytes = MatchPattern(pattern=b"", allow_none=False) + match_pattern_bytes_none = MatchPattern(pattern=b"", allow_none=True) + + convertible_default = Convertible(expected_type=int) + convertible_not_none = Convertible(expected_type=int, allow_none=False) + convertible_none = Convertible(expected_type=int, allow_none=True) + + # NOTE: min and max params are independent of expected_type since int and floats can always be compared together + minmax_default = MinMax(min=0, max=0) + minmax_float = MinMax(min=0, max=0, expected_type=float, allow_none=False) + minmax_float_none = MinMax(min=0, max=0, expected_type=float, allow_none=True) + minmax_int = MinMax(min=0.0, max=0.0, expected_type=int, allow_none=False) + minmax_int_none = MinMax(min=0.0, max=0.0, expected_type=int, allow_none=True) + + bool_default = Bool() + bool_not_none = Bool(allow_none=False) + bool_none = Bool(allow_none=True) + + datetime_default = DateTime() + datetime_not_none = DateTime(allow_none=False) + datetime_none = DateTime(allow_none=True) + + string_default = String() + string_not_none = String(allow_none=False) + string_none = String(allow_none=True) + + float_default = Float() + float_not_none = Float(allow_none=False) + float_none = Float(allow_none=True) + + integer_default = Integer() + integer_not_none = Integer(allow_none=False) + integer_none = Integer(allow_none=True) + + # Test inferred annotation + assert_type(descriptor, Descriptor[str]) + + assert_type(typed_default, Typed[str, Literal[False]]) + assert_type(typed_not_none, Typed[str, Literal[False]]) + assert_type(typed_none, Typed[str, Literal[True]]) + + assert_type(set_tuple, Set[Union[Literal["a", 1], float]]) # type: ignore[assert-type] # False-positive in mypy + assert_type(set_list, Set[Union[str, int, float]]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples + assert_type(set_tuple_none, Set[Union[Literal["a", 1, None], float]]) # type: ignore[assert-type] # False-positive in mypy + + assert_type(noneset_tuple, NoneSet[Union[Literal["a", 1], float]]) # type: ignore[assert-type] # False-positive in mypy + assert_type(noneset_list, NoneSet[Union[str, float]]) # type: ignore[assert-type] # False-positive in mypy# int and float are merged in generic unions + + assert_type(length_tuple, Length[Tuple[str, str]]) + assert_type(length_list, Length[List[str]]) + + assert_type(match_pattern_str_default, MatchPattern[str, Literal[False]]) + assert_type(match_pattern_str, MatchPattern[str, Literal[False]]) + assert_type(match_pattern_str_none, MatchPattern[str, Literal[True]]) + assert_type(match_pattern_bytes_default, MatchPattern[ReadableBuffer, Literal[False]]) + assert_type(match_pattern_bytes, MatchPattern[ReadableBuffer, Literal[False]]) + assert_type(match_pattern_bytes_none, MatchPattern[ReadableBuffer, Literal[True]]) + + assert_type(convertible_default, Convertible[int, Literal[False]]) + assert_type(convertible_not_none, Convertible[int, Literal[False]]) + assert_type(convertible_none, Convertible[int, Literal[True]]) + + assert_type(minmax_default, MinMax[float, Literal[False]]) + assert_type(minmax_float, MinMax[float, Literal[False]]) + assert_type(minmax_float_none, MinMax[float, Literal[True]]) + assert_type(minmax_int, MinMax[int, Literal[False]]) + assert_type(minmax_int_none, MinMax[int, Literal[True]]) + + assert_type(bool_default, Bool[Literal[False]]) + assert_type(bool_not_none, Bool[Literal[False]]) + assert_type(bool_none, Bool[Literal[True]]) + + assert_type(datetime_default, DateTime[Literal[False]]) + assert_type(datetime_not_none, DateTime[Literal[False]]) + assert_type(datetime_none, DateTime[Literal[True]]) + + assert_type(string_default, String[Literal[False]]) + assert_type(string_not_none, String[Literal[False]]) + assert_type(string_none, String[Literal[True]]) + + assert_type(float_default, Float[Literal[False]]) + assert_type(float_not_none, Float[Literal[False]]) + assert_type(float_none, Float[Literal[True]]) + + assert_type(integer_default, Integer[Literal[False]]) + assert_type(integer_not_none, Integer[Literal[False]]) + assert_type(integer_none, Integer[Literal[True]]) + + +with_descriptors = WithDescriptors() + + +# Test with missing subclass +class NotSerialisable: + descriptor = Descriptor[Any]() + + +NotSerialisable().descriptor = None # type: ignore + + +# Test with Strict subclass +class WithDescriptorsStrict(Strict): + descriptor = Descriptor[Any]() + + +WithDescriptorsStrict().descriptor = None + + +# Test getters +assert_type(with_descriptors.descriptor, str) + +assert_type(with_descriptors.typed_not_none, str) +assert_type(with_descriptors.typed_none, Union[str, None]) + +assert_type(with_descriptors.set_tuple, Union[Literal["a", 1], float]) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.set_list, Union[str, int, float]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples +assert_type(with_descriptors.set_tuple_none, Union[Literal["a", 1, None], float]) # type: ignore[assert-type] # False-positive in mypy + +assert_type(with_descriptors.noneset_tuple, Union[Literal["a", 1], float, None]) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.noneset_list, Union[str, float, None]) # type: ignore[assert-type] # False-positive in mypy # int and float are merged in generic unions + +assert_type(with_descriptors.length_tuple, Tuple[str, str]) +assert_type(with_descriptors.length_list, List[str]) + +assert_type(with_descriptors.match_pattern_str, str) +assert_type(with_descriptors.match_pattern_str_none, Union[str, None]) +assert_type(with_descriptors.match_pattern_bytes, ReadableBuffer) +assert_type(with_descriptors.match_pattern_bytes_none, Union[ReadableBuffer, None]) + +assert_type(with_descriptors.convertible_not_none, int) +assert_type(with_descriptors.convertible_none, Union[int, None]) + +assert_type(with_descriptors.minmax_float, float) +assert_type(with_descriptors.minmax_float_none, Union[float, None]) +assert_type(with_descriptors.minmax_int, int) +assert_type(with_descriptors.minmax_int_none, Union[int, None]) + +assert_type(with_descriptors.bool_not_none, bool) +assert_type(with_descriptors.bool_none, Union[bool, None]) + +assert_type(with_descriptors.datetime_not_none, datetime) +assert_type(with_descriptors.datetime_none, Union[datetime, None]) + +assert_type(with_descriptors.string_not_none, str) +assert_type(with_descriptors.string_none, Union[str, None]) + +assert_type(with_descriptors.float_not_none, float) +assert_type(with_descriptors.float_none, Union[float, None]) + +assert_type(with_descriptors.integer_not_none, int) +assert_type(with_descriptors.integer_none, Union[int, None]) + + +# Test setters (expected type, None, unexpected type) +with_descriptors.descriptor = "" +with_descriptors.descriptor = None # type: ignore +with_descriptors.descriptor = 0 # type: ignore + + +with_descriptors.typed_not_none = "" +with_descriptors.typed_not_none = None # type: ignore +with_descriptors.typed_not_none = 0 # type: ignore + +with_descriptors.typed_none = "" +with_descriptors.typed_none = None +with_descriptors.typed_none = 0 # type: ignore + + +# NOTE: Can't check Set for literal int wen used with a float because any int is a valid float +with_descriptors.set_tuple = "a" +with_descriptors.set_tuple = 0 +with_descriptors.set_tuple = 0.0 +with_descriptors.set_tuple = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_list = "a" +with_descriptors.set_list = 0 +with_descriptors.set_list = 0.0 +with_descriptors.set_list = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = "none" # can't check literals validity +with_descriptors.set_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_tuple_none = "a" +with_descriptors.set_tuple_none = 0 +with_descriptors.set_tuple_none = 0.0 +with_descriptors.set_tuple_none = None +with_descriptors.set_tuple_none = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple_none = object() # type: ignore + + +with_descriptors.noneset_tuple = "a" +with_descriptors.noneset_tuple = 0 +with_descriptors.noneset_tuple = 0.0 +with_descriptors.noneset_tuple = None +with_descriptors.noneset_tuple = "none" +with_descriptors.noneset_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.noneset_list = "a" +with_descriptors.noneset_list = 0 +with_descriptors.noneset_list = 0.0 +with_descriptors.noneset_list = None +with_descriptors.noneset_list = "none" +with_descriptors.noneset_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + + +# NOTE: Can't validate tuple length in a generic manner +with_descriptors.length_tuple = ("a", "a") +with_descriptors.length_tuple = None # type: ignore +with_descriptors.length_tuple = ["a", "a"] # type: ignore +with_descriptors.length_tuple = "" # type: ignore + +with_descriptors.length_list = ["a", "a"] +with_descriptors.length_list = None # type: ignore +with_descriptors.length_list = ("a", "a") # type: ignore +with_descriptors.length_list = "" # type: ignore + + +with_descriptors.match_pattern_str = "" +with_descriptors.match_pattern_str = None # type: ignore +with_descriptors.match_pattern_str = b"" # type: ignore +with_descriptors.match_pattern_str = 0 # type: ignore + +with_descriptors.match_pattern_str_none = "" +with_descriptors.match_pattern_str_none = None +with_descriptors.match_pattern_str_none = b"" # type: ignore +with_descriptors.match_pattern_str_none = 0 # type: ignore + +with_descriptors.match_pattern_bytes = b"" +with_descriptors.match_pattern_bytes = None # type: ignore +with_descriptors.match_pattern_bytes = "" # type: ignore +with_descriptors.match_pattern_bytes = 0 # type: ignore + +with_descriptors.match_pattern_bytes_none = b"" +with_descriptors.match_pattern_bytes_none = None +with_descriptors.match_pattern_bytes_none = "" # type: ignore +with_descriptors.match_pattern_bytes_none = 0 # type: ignore + + +with_descriptors.convertible_not_none = 0 +with_descriptors.convertible_not_none = "0" +with_descriptors.convertible_not_none = None # type: ignore +with_descriptors.convertible_not_none = object() # type: ignore + +with_descriptors.convertible_none = 0 +with_descriptors.convertible_none = "0" +with_descriptors.convertible_none = None +with_descriptors.convertible_none = object() # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.minmax_float = 0 +with_descriptors.minmax_float = "0" +with_descriptors.minmax_float = 0.0 +with_descriptors.minmax_float = None # type: ignore +with_descriptors.minmax_float = object() # type: ignore + +with_descriptors.minmax_float_none = 0 +with_descriptors.minmax_float_none = "0" +with_descriptors.minmax_float_none = 0.0 +with_descriptors.minmax_float_none = None +with_descriptors.minmax_float_none = object() # type: ignore + +with_descriptors.minmax_int = 0 +with_descriptors.minmax_int = "0" +with_descriptors.minmax_int = 0.0 +with_descriptors.minmax_int = None # type: ignore +with_descriptors.minmax_int = object() # type: ignore + +with_descriptors.minmax_int_none = 0 +with_descriptors.minmax_int_none = "0" +with_descriptors.minmax_int_none = 0.0 +with_descriptors.minmax_int_none = None +with_descriptors.minmax_int_none = object() # type: ignore + + +with_descriptors.bool_not_none = False +with_descriptors.bool_not_none = "0" +with_descriptors.bool_not_none = 0 +with_descriptors.bool_not_none = None +with_descriptors.bool_not_none = 0.0 # type: ignore +with_descriptors.bool_not_none = object() # type: ignore + +with_descriptors.bool_none = False +with_descriptors.bool_none = "0" +with_descriptors.bool_none = 0 +with_descriptors.bool_none = None +with_descriptors.bool_none = 0.0 # type: ignore +with_descriptors.bool_none = object() # type: ignore + + +with_descriptors.datetime_not_none = datetime(0, 0, 0) +with_descriptors.datetime_not_none = "" +with_descriptors.datetime_not_none = None # type: ignore +with_descriptors.datetime_not_none = 0 # type: ignore +with_descriptors.datetime_not_none = date(0, 0, 0) # type: ignore +with_descriptors.datetime_not_none = time() # type: ignore + +with_descriptors.datetime_none = datetime(0, 0, 0) +with_descriptors.datetime_none = "" +with_descriptors.datetime_none = None +with_descriptors.datetime_none = 0 # type: ignore +with_descriptors.datetime_none = date(0, 0, 0) # type: ignore +with_descriptors.datetime_none = time() # type: ignore + + +with_descriptors.string_not_none = "" +with_descriptors.string_not_none = None # type: ignore +with_descriptors.string_not_none = 0 # type: ignore + +with_descriptors.string_none = "" +with_descriptors.string_none = None +with_descriptors.string_none = 0 # type: ignore + + +with_descriptors.float_not_none = 0 +with_descriptors.float_not_none = 0.0 +with_descriptors.float_not_none = "0" +with_descriptors.float_not_none = b"0" +with_descriptors.float_not_none = None # type: ignore +with_descriptors.float_not_none = object() # type: ignore + +with_descriptors.float_none = 0 +with_descriptors.float_none = 0.0 +with_descriptors.float_none = "0" +with_descriptors.float_none = b"0" +with_descriptors.float_none = None +with_descriptors.float_none = object() # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.integer_not_none = 0 +with_descriptors.integer_not_none = 0.0 +with_descriptors.integer_not_none = "0" +with_descriptors.integer_not_none = b"0" +with_descriptors.integer_not_none = None # type: ignore +with_descriptors.integer_not_none = object() # type: ignore + +with_descriptors.integer_none = 0 +with_descriptors.integer_none = 0.0 +with_descriptors.integer_none = "0" +with_descriptors.integer_none = b"0" +with_descriptors.integer_none = None +with_descriptors.integer_none = object() # FIXME: False negative(?) in pyright and mypy diff --git a/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py b/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py new file mode 100644 index 000000000000..3d36ab215fff --- /dev/null +++ b/stubs/openpyxl/@tests/test_cases/check_nested_descriptors.py @@ -0,0 +1,458 @@ +# Needed until mypy issues are solved or https://github.com/python/mypy/issues/12358 +# pyright: reportUnnecessaryTypeIgnoreComment=false + +# These tests are essentially a mirror of check_base_descriptors +from __future__ import annotations + +from typing import Literal, Union, cast +from typing_extensions import assert_type + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.nested import ( + EmptyTag, + Nested, + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedSet, + NestedString, + NestedText, + NestedValue, +) +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml._functions_overloads import _HasTagAndGet +from openpyxl.xml.functions import Element + +_ = object() # More concise discard object for casts + +# Ensure the default "Element" matches the _HasTagAndGet protocol +element: _HasTagAndGet[str] = Element("") + + +class WithDescriptors(Serialisable): + descriptor = Nested(expected_type=str) + + set_tuple = NestedSet(values=("a", 1, 0.0)) + set_list = NestedSet(values=["a", 1, 0.0]) + set_tuple_none = NestedSet(values=("a", 1, 0.0, None)) + + noneset_tuple = NestedNoneSet(values=("a", 1, 0.0)) + noneset_list = NestedNoneSet(values=["a", 1, 0.0]) + + convertible_default = NestedValue(expected_type=int) + convertible_not_none = NestedValue(expected_type=int, allow_none=False) + convertible_none = NestedValue(expected_type=int, allow_none=True) + + text_default = NestedText(expected_type=str) + text_str_not_none = NestedText(expected_type=str, allow_none=False) + text_str_none = NestedText(expected_type=str, allow_none=True) + text_int_not_none = NestedText(expected_type=int, allow_none=False) + text_int_none = NestedText(expected_type=int, allow_none=True) + + # NOTE: min and max params are independent of expected_type since int and floats can always be compared together + minmax_default = NestedMinMax(min=0, max=0) + minmax_float = NestedMinMax(min=0, max=0, expected_type=float, allow_none=False) + minmax_float_none = NestedMinMax(min=0, max=0, expected_type=float, allow_none=True) + minmax_int = NestedMinMax(min=0.0, max=0.0, expected_type=int, allow_none=False) + minmax_int_none = NestedMinMax(min=0.0, max=0.0, expected_type=int, allow_none=True) + + bool_default = NestedBool() + bool_not_none = NestedBool(allow_none=False) + bool_none = NestedBool(allow_none=True) + + emptytag_default = EmptyTag() + emptytag_not_none = EmptyTag(allow_none=False) + emptytag_none = EmptyTag(allow_none=True) + + string_default = NestedString() + string_not_none = NestedString(allow_none=False) + string_none = NestedString(allow_none=True) + + float_default = NestedFloat() + float_not_none = NestedFloat(allow_none=False) + float_none = NestedFloat(allow_none=True) + + integer_default = NestedInteger() + integer_not_none = NestedInteger(allow_none=False) + integer_none = NestedInteger(allow_none=True) + + # Test inferred annotation + assert_type(descriptor, Nested[str]) + + assert_type(set_tuple, NestedSet[Union[Literal["a", 1], float]]) # type: ignore[assert-type] # False-positive in mypy + assert_type(set_list, NestedSet[Union[str, int, float]]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples + assert_type(set_tuple_none, NestedSet[Union[Literal["a", 1, None], float]]) # type: ignore[assert-type] # False-positive in mypy + + assert_type(noneset_tuple, NestedNoneSet[Union[Literal["a", 1], float]]) # type: ignore[assert-type] # False-positive in mypy + assert_type(noneset_list, NestedNoneSet[Union[str, float]]) # type: ignore[assert-type] # False-positive in mypy# int and float are merged in generic unions + + assert_type(convertible_default, NestedValue[int, Literal[False]]) + assert_type(convertible_not_none, NestedValue[int, Literal[False]]) + assert_type(convertible_none, NestedValue[int, Literal[True]]) + + assert_type(text_default, NestedText[str, Literal[False]]) + assert_type(text_str_not_none, NestedText[str, Literal[False]]) + assert_type(text_str_none, NestedText[str, Literal[True]]) + assert_type(text_int_not_none, NestedText[int, Literal[False]]) + assert_type(text_int_none, NestedText[int, Literal[True]]) + + assert_type(minmax_default, NestedMinMax[float, Literal[False]]) + assert_type(minmax_float, NestedMinMax[float, Literal[False]]) + assert_type(minmax_float_none, NestedMinMax[float, Literal[True]]) + assert_type(minmax_int, NestedMinMax[int, Literal[False]]) + assert_type(minmax_int_none, NestedMinMax[int, Literal[True]]) + + assert_type(bool_default, NestedBool[Literal[False]]) + assert_type(bool_not_none, NestedBool[Literal[False]]) + assert_type(bool_none, NestedBool[Literal[True]]) + + assert_type(emptytag_default, EmptyTag[Literal[False]]) + assert_type(emptytag_not_none, EmptyTag[Literal[False]]) + assert_type(emptytag_none, EmptyTag[Literal[True]]) + + assert_type(string_default, NestedString[Literal[False]]) + assert_type(string_not_none, NestedString[Literal[False]]) + assert_type(string_none, NestedString[Literal[True]]) + + assert_type(float_default, NestedFloat[Literal[False]]) + assert_type(float_not_none, NestedFloat[Literal[False]]) + assert_type(float_none, NestedFloat[Literal[True]]) + + assert_type(integer_default, NestedInteger[Literal[False]]) + assert_type(integer_not_none, NestedInteger[Literal[False]]) + assert_type(integer_none, NestedInteger[Literal[True]]) + + +with_descriptors = WithDescriptors() + + +# Test with missing subclass +class NotSerialisable: + descriptor = Nested(expected_type=object) + + +NotSerialisable().descriptor = None # type: ignore + + +# Test with Strict subclass +class WithDescriptorsStrict(Strict): + descriptor = Nested(expected_type=object) + + +WithDescriptorsStrict().descriptor = None + + +# Test getters +assert_type(with_descriptors.descriptor, str) + +assert_type(with_descriptors.set_tuple, Union[Literal["a", 1], float]) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.set_list, Union[str, int, float]) # type: ignore[assert-type] # False-positive in mypy # Literals are simplified in non-tuples +assert_type(with_descriptors.set_tuple_none, Union[Literal["a", 1, None], float]) # type: ignore[assert-type] # False-positive in mypy + +assert_type(with_descriptors.noneset_tuple, Union[Literal["a", 1], float, None]) # type: ignore[assert-type] # False-positive in mypy +assert_type(with_descriptors.noneset_list, Union[str, float, None]) # type: ignore[assert-type] # False-positive in mypy # int and float are merged in generic unions + +assert_type(with_descriptors.convertible_not_none, int) +assert_type(with_descriptors.convertible_none, Union[int, None]) + +assert_type(with_descriptors.text_str_not_none, str) +assert_type(with_descriptors.text_str_none, Union[str, None]) +assert_type(with_descriptors.text_int_not_none, int) +assert_type(with_descriptors.text_int_none, Union[int, None]) + +assert_type(with_descriptors.minmax_float, float) +assert_type(with_descriptors.minmax_float_none, Union[float, None]) +assert_type(with_descriptors.minmax_int, int) +assert_type(with_descriptors.minmax_int_none, Union[int, None]) + +assert_type(with_descriptors.bool_not_none, bool) +assert_type(with_descriptors.bool_none, Union[bool, None]) + +assert_type(with_descriptors.emptytag_not_none, bool) +assert_type(with_descriptors.emptytag_none, Union[bool, None]) + +assert_type(with_descriptors.string_not_none, str) +assert_type(with_descriptors.string_none, Union[str, None]) + +assert_type(with_descriptors.float_not_none, float) +assert_type(with_descriptors.float_none, Union[float, None]) + +assert_type(with_descriptors.integer_not_none, int) +assert_type(with_descriptors.integer_none, Union[int, None]) + + +# Test setters (expected type, None, unexpected type, Elements) +with_descriptors.descriptor = "" +with_descriptors.descriptor = None # type: ignore +with_descriptors.descriptor = 0 # type: ignore +with_descriptors.descriptor = cast(_HasTagAndGet[str], _) +with_descriptors.descriptor = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.descriptor = cast(_HasTagAndGet[int], _) # type: ignore + + +# NOTE: Can't check NestedSet for literal int wen used with a float because any int is a valid float +with_descriptors.set_tuple = "a" +with_descriptors.set_tuple = 0 +with_descriptors.set_tuple = 0.0 +with_descriptors.set_tuple = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_tuple = cast(_HasTagAndGet[str], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast(_HasTagAndGet[None], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + +with_descriptors.set_list = "a" +with_descriptors.set_list = 0 +with_descriptors.set_list = 0.0 +with_descriptors.set_list = None # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = "none" # can't check literals validity +with_descriptors.set_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_list = cast(_HasTagAndGet[str], _) # can't check literals validity +with_descriptors.set_list = cast(_HasTagAndGet[None], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_list = cast(_HasTagAndGet[object], _) # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + +with_descriptors.set_tuple_none = "a" +with_descriptors.set_tuple_none = 0 +with_descriptors.set_tuple_none = 0.0 +with_descriptors.set_tuple_none = None +with_descriptors.set_tuple_none = "none" # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.set_tuple_none = object() # type: ignore +with_descriptors.set_tuple_none = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.set_tuple_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) +with_descriptors.set_tuple_none = cast(_HasTagAndGet[None], _) +with_descriptors.set_tuple_none = cast(_HasTagAndGet[object], _) # type: ignore + + +with_descriptors.noneset_tuple = "a" +with_descriptors.noneset_tuple = 0 +with_descriptors.noneset_tuple = 0.0 +with_descriptors.noneset_tuple = None +with_descriptors.noneset_tuple = "none" +with_descriptors.noneset_tuple = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.noneset_tuple = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.noneset_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) +with_descriptors.noneset_tuple = cast(_HasTagAndGet[None], _) +with_descriptors.noneset_tuple = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + +with_descriptors.noneset_list = "a" +with_descriptors.noneset_list = 0 +with_descriptors.noneset_list = 0.0 +with_descriptors.noneset_list = None +with_descriptors.noneset_list = "none" +with_descriptors.noneset_list = object() # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy +with_descriptors.noneset_list = cast(_HasTagAndGet[Literal["a"]], _) +with_descriptors.noneset_list = cast(_HasTagAndGet[str], _) +with_descriptors.noneset_list = cast(_HasTagAndGet[None], _) +with_descriptors.noneset_list = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[object], _ +) + + +with_descriptors.convertible_not_none = 0 +with_descriptors.convertible_not_none = "0" +with_descriptors.convertible_not_none = None # type: ignore +with_descriptors.convertible_not_none = object() # type: ignore +with_descriptors.convertible_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.convertible_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.convertible_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.convertible_none = 0 +with_descriptors.convertible_none = "0" +with_descriptors.convertible_none = None +with_descriptors.convertible_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.convertible_none = cast(_HasTagAndGet[str], _) +with_descriptors.convertible_none = cast(_HasTagAndGet[None], _) +with_descriptors.convertible_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.text_str_not_none = 0 +with_descriptors.text_str_not_none = "0" +with_descriptors.text_str_not_none = None +with_descriptors.text_str_not_none = object() +with_descriptors.text_str_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.text_str_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.text_str_not_none = cast(_HasTagAndGet[object], _) + +with_descriptors.text_str_none = 0 +with_descriptors.text_str_none = "0" +with_descriptors.text_str_none = None +with_descriptors.text_str_none = object() +with_descriptors.text_str_none = cast(_HasTagAndGet[str], _) +with_descriptors.text_str_none = cast(_HasTagAndGet[None], _) +with_descriptors.text_str_none = cast(_HasTagAndGet[object], _) + +with_descriptors.text_int_not_none = 0 +with_descriptors.text_int_not_none = "0" +with_descriptors.text_int_not_none = None # type: ignore +with_descriptors.text_int_not_none = object() # type: ignore +# If expected type (_T) is not str, it's impossible to use an Element as the value +with_descriptors.text_int_not_none = cast(_HasTagAndGet[int], _) # type: ignore +with_descriptors.text_int_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.text_int_not_none = cast(_HasTagAndGet[str], _) # type: ignore + +with_descriptors.text_int_none = 0 +with_descriptors.text_int_none = "0" +with_descriptors.text_int_none = None +with_descriptors.text_int_none = object() # FIXME: False negative(?) in pyright and mypy +# If expected type (_T) is not str, it's impossible to use an Element as the value +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[int], _ +) +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[None], _ +) +with_descriptors.text_int_none = cast( # pyright: ignore[reportAttributeAccessIssue] # false negative in mypy + _HasTagAndGet[str], _ +) + + +with_descriptors.minmax_float = 0 +with_descriptors.minmax_float = "0" +with_descriptors.minmax_float = 0.0 +with_descriptors.minmax_float = None # type: ignore +with_descriptors.minmax_float = object() # type: ignore +with_descriptors.minmax_float = cast(_HasTagAndGet[float], _) +with_descriptors.minmax_float = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.minmax_float = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_float_none = 0 +with_descriptors.minmax_float_none = "0" +with_descriptors.minmax_float_none = 0.0 +with_descriptors.minmax_float_none = None +with_descriptors.minmax_float_none = object() # type: ignore +with_descriptors.minmax_float_none = cast(_HasTagAndGet[float], _) +with_descriptors.minmax_float_none = cast(_HasTagAndGet[None], _) +with_descriptors.minmax_float_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_int = 0 +with_descriptors.minmax_int = "0" +with_descriptors.minmax_int = 0.0 +with_descriptors.minmax_int = None # type: ignore +with_descriptors.minmax_int = object() # type: ignore +with_descriptors.minmax_int = cast(_HasTagAndGet[int], _) +with_descriptors.minmax_int = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.minmax_int = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.minmax_int_none = 0 +with_descriptors.minmax_int_none = "0" +with_descriptors.minmax_int_none = 0.0 +with_descriptors.minmax_int_none = None +with_descriptors.minmax_int_none = object() # type: ignore +with_descriptors.minmax_int_none = cast(_HasTagAndGet[int], _) +with_descriptors.minmax_int_none = cast(_HasTagAndGet[None], _) +with_descriptors.minmax_int_none = cast(_HasTagAndGet[object], _) # type: ignore + + +with_descriptors.bool_not_none = False +with_descriptors.bool_not_none = "0" +with_descriptors.bool_not_none = 0 +with_descriptors.bool_not_none = None +with_descriptors.bool_not_none = 0.0 # type: ignore +with_descriptors.bool_not_none = object() # type: ignore +with_descriptors.bool_not_none = cast(_HasTagAndGet[bool], _) +with_descriptors.bool_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.bool_not_none = cast(_HasTagAndGet[float], _) # type: ignore + +with_descriptors.bool_none = False +with_descriptors.bool_none = "0" +with_descriptors.bool_none = 0 +with_descriptors.bool_none = None +with_descriptors.bool_none = 0.0 # type: ignore +with_descriptors.bool_none = object() # type: ignore +with_descriptors.bool_none = cast(_HasTagAndGet[bool], _) +with_descriptors.bool_none = cast(_HasTagAndGet[None], _) +with_descriptors.bool_none = cast(_HasTagAndGet[float], _) # type: ignore + + +with_descriptors.emptytag_not_none = False +with_descriptors.emptytag_not_none = "0" +with_descriptors.emptytag_not_none = 0 +with_descriptors.emptytag_not_none = None +with_descriptors.emptytag_not_none = 0.0 # type: ignore +with_descriptors.emptytag_not_none = object() # type: ignore +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[bool], _) +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.emptytag_not_none = cast(_HasTagAndGet[float], _) # type: ignore + +with_descriptors.emptytag_none = False +with_descriptors.emptytag_none = "0" +with_descriptors.emptytag_none = 0 +with_descriptors.emptytag_none = None +with_descriptors.emptytag_none = 0.0 # type: ignore +with_descriptors.emptytag_none = object() # type: ignore +with_descriptors.emptytag_none = cast(_HasTagAndGet[bool], _) +with_descriptors.emptytag_none = cast(_HasTagAndGet[None], _) +with_descriptors.emptytag_none = cast(_HasTagAndGet[float], _) # type: ignore + + +with_descriptors.string_not_none = "" +with_descriptors.string_not_none = None +with_descriptors.string_not_none = 0 +with_descriptors.string_not_none = object() +with_descriptors.string_not_none = cast(_HasTagAndGet[str], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[None], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[int], _) +with_descriptors.string_not_none = cast(_HasTagAndGet[object], _) + +with_descriptors.string_none = "" +with_descriptors.string_none = None +with_descriptors.string_none = 0 +with_descriptors.string_none = object() +with_descriptors.string_none = cast(_HasTagAndGet[str], _) +with_descriptors.string_none = cast(_HasTagAndGet[None], _) +with_descriptors.string_none = cast(_HasTagAndGet[int], _) +with_descriptors.string_none = cast(_HasTagAndGet[object], _) + + +with_descriptors.float_not_none = 0 +with_descriptors.float_not_none = 0.0 +with_descriptors.float_not_none = "0" +with_descriptors.float_not_none = b"0" +with_descriptors.float_not_none = None # type: ignore +with_descriptors.float_not_none = object() # type: ignore +with_descriptors.float_not_none = cast(_HasTagAndGet[float], _) +with_descriptors.float_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.float_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.float_none = 0 +with_descriptors.float_none = 0.0 +with_descriptors.float_none = "0" +with_descriptors.float_none = b"0" +with_descriptors.float_none = None +with_descriptors.float_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.float_none = cast(_HasTagAndGet[float], _) +with_descriptors.float_none = cast(_HasTagAndGet[None], _) +with_descriptors.float_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy + + +with_descriptors.integer_not_none = 0 +with_descriptors.integer_not_none = 0.0 +with_descriptors.integer_not_none = "0" +with_descriptors.integer_not_none = b"0" +with_descriptors.integer_not_none = None # type: ignore +with_descriptors.integer_not_none = object() # type: ignore +with_descriptors.integer_not_none = cast(_HasTagAndGet[int], _) +with_descriptors.integer_not_none = cast(_HasTagAndGet[None], _) # type: ignore +with_descriptors.integer_not_none = cast(_HasTagAndGet[object], _) # type: ignore + +with_descriptors.integer_none = 0 +with_descriptors.integer_none = 0.0 +with_descriptors.integer_none = "0" +with_descriptors.integer_none = b"0" +with_descriptors.integer_none = None +with_descriptors.integer_none = object() # FIXME: False negative(?) in pyright and mypy +with_descriptors.integer_none = cast(_HasTagAndGet[int], _) +with_descriptors.integer_none = cast(_HasTagAndGet[None], _) +with_descriptors.integer_none = cast(_HasTagAndGet[object], _) # FIXME: False negative(?) in pyright and mypy diff --git a/stubs/openpyxl/METADATA.toml b/stubs/openpyxl/METADATA.toml new file mode 100644 index 000000000000..076eb0ab762f --- /dev/null +++ b/stubs/openpyxl/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.1.5" +upstream-repository = "https://foss.heptapod.net/openpyxl/openpyxl" diff --git a/stubs/openpyxl/openpyxl/__init__.pyi b/stubs/openpyxl/openpyxl/__init__.pyi new file mode 100644 index 000000000000..13e79c8bdc1d --- /dev/null +++ b/stubs/openpyxl/openpyxl/__init__.pyi @@ -0,0 +1,31 @@ +from _typeshed import StrPath, SupportsRead, SupportsWrite +from typing import IO, Literal, Protocol, TypeAlias, type_check_only + +from openpyxl.compat.numbers import NUMPY as NUMPY +from openpyxl.reader.excel import load_workbook as load_workbook +from openpyxl.workbook import Workbook as Workbook +from openpyxl.xml import DEFUSEDXML as DEFUSEDXML, LXML as LXML + +from ._constants import ( + __author__ as __author__, + __author_email__ as __author_email__, + __license__ as __license__, + __maintainer_email__ as __maintainer_email__, + __url__ as __url__, + __version__ as __version__, +) + +DEBUG: bool +open = load_workbook + +# Utility types reused elsewhere +_VisibilityType: TypeAlias = Literal["visible", "hidden", "veryHidden"] # noqa: Y047 + +# TODO: Use a proper protocol from ZipFile. See: #10880 +# This alias is to minimize false-positives +_ZipFileFileProtocol: TypeAlias = StrPath | IO[bytes] | SupportsRead[bytes] # noqa: Y047 +_ZipFileFileWriteProtocol: TypeAlias = StrPath | IO[bytes] | SupportsWrite[bytes] # noqa: Y047 + +@type_check_only +class _Decodable(Protocol): # noqa: Y046 + def decode(self, encoding: str, /) -> str: ... diff --git a/stubs/openpyxl/openpyxl/_constants.pyi b/stubs/openpyxl/openpyxl/_constants.pyi new file mode 100644 index 000000000000..ed593cc2cf45 --- /dev/null +++ b/stubs/openpyxl/openpyxl/_constants.pyi @@ -0,0 +1,7 @@ +__author__: str +__author_email__: str +__license__: str +__maintainer_email__: str +__url__: str +__version__: str +__python__: str diff --git a/stubs/openpyxl/openpyxl/cell/__init__.pyi b/stubs/openpyxl/openpyxl/cell/__init__.pyi new file mode 100644 index 000000000000..7bd4c41d9494 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/__init__.pyi @@ -0,0 +1,27 @@ +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from typing import Any, TypeAlias + +from openpyxl.cell.rich_text import CellRichText +from openpyxl.worksheet.formula import ArrayFormula, DataTableFormula + +from .cell import Cell as Cell, MergedCell as MergedCell, WriteOnlyCell as WriteOnlyCell +from .read_only import ReadOnlyCell as ReadOnlyCell + +_TimeTypes: TypeAlias = datetime | date | time | timedelta +_CellGetValue: TypeAlias = ( # noqa: Y047 # Used in other modules + # if numpy is installed also numpy bool and number types + bool + | float + | Decimal + | str + | CellRichText + | _TimeTypes + | DataTableFormula + | ArrayFormula + | None +) +_AnyCellValue: TypeAlias = Any # AnyOf _CellGetValue # noqa: Y047 # Used in other modules +_CellSetValue: TypeAlias = _CellGetValue | bytes # noqa: Y047 # Used in other modules + +_CellOrMergedCell: TypeAlias = Cell | MergedCell # noqa: Y047 # Used in other modules diff --git a/stubs/openpyxl/openpyxl/cell/_writer.pyi b/stubs/openpyxl/openpyxl/cell/_writer.pyi new file mode 100644 index 000000000000..d079c8c08c77 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/_writer.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused + +from openpyxl.cell import _CellOrMergedCell + +def etree_write_cell(xf, worksheet: Unused, cell: _CellOrMergedCell, styled=None) -> None: ... +def lxml_write_cell(xf, worksheet: Unused, cell: _CellOrMergedCell, styled: bool = False) -> None: ... + +write_cell = lxml_write_cell +write_cell = etree_write_cell diff --git a/stubs/openpyxl/openpyxl/cell/cell.pyi b/stubs/openpyxl/openpyxl/cell/cell.pyi new file mode 100644 index 000000000000..b16d008d9f4e --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/cell.pyi @@ -0,0 +1,109 @@ +from _typeshed import ReadableBuffer +from datetime import datetime +from re import Pattern +from typing import Final, Literal, overload + +from openpyxl.cell import _CellGetValue, _CellOrMergedCell, _CellSetValue, _TimeTypes +from openpyxl.comments.comments import Comment +from openpyxl.compat.numbers import NUMERIC_TYPES as NUMERIC_TYPES # cell numeric types +from openpyxl.styles.cell_style import StyleArray +from openpyxl.styles.styleable import StyleableObject +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet +from openpyxl.worksheet.hyperlink import Hyperlink + +__docformat__: Final = "restructuredtext en" +TIME_TYPES: Final[tuple[type, ...]] +TIME_FORMATS: Final[dict[type[_TimeTypes], str]] +STRING_TYPES: Final[tuple[type, ...]] +KNOWN_TYPES: Final[tuple[type, ...]] + +ILLEGAL_CHARACTERS_RE: Final[Pattern[str]] +ERROR_CODES: Final[tuple[str, ...]] + +TYPE_STRING: Final = "s" +TYPE_FORMULA: Final = "f" +TYPE_NUMERIC: Final = "n" +TYPE_BOOL: Final = "b" +TYPE_NULL: Final = "n" +TYPE_INLINE: Final = "inlineStr" +TYPE_ERROR: Final = "e" +TYPE_FORMULA_CACHE_STRING: Final = "str" + +VALID_TYPES: Final[tuple[str, ...]] + +def get_type(t: type, value: object) -> Literal["n", "s", "d", "f"] | None: ... +def get_time_format(t: _TimeTypes) -> str: ... + +class Cell(StyleableObject): + __slots__ = ("row", "column", "_value", "data_type", "parent", "_hyperlink", "_comment") + row: int + column: int + data_type: str + # row and column are never meant to be None and would lead to errors + def __init__( + self, + worksheet: _WorkbookChild | ReadOnlyWorksheet, + row: int, + column: int, + value: _CellSetValue = None, + style_array: StyleArray | None = None, + ) -> None: ... + @property + def coordinate(self) -> str: ... + @property + def col_idx(self) -> int: ... + @property + def column_letter(self) -> str: ... + @property + def encoding(self) -> str: ... + @property + def base_date(self) -> datetime: ... + + @overload + def check_string(self, value: None) -> None: ... + @overload + def check_string(self, value: str | ReadableBuffer) -> str: ... + + def check_error(self, value: object) -> str: ... + + @property + def value(self) -> _CellGetValue: ... + @value.setter + def value(self, value: _CellSetValue) -> None: ... + + @property + def internal_value(self) -> _CellGetValue: ... + + @property + def hyperlink(self) -> Hyperlink | None: ... + @hyperlink.setter + def hyperlink(self, val: Hyperlink | str | None) -> None: ... + + @property + def is_date(self) -> bool: ... + def offset(self, row: int = 0, column: int = 0) -> _CellOrMergedCell: ... + + @property + def comment(self) -> Comment | None: ... + @comment.setter + def comment(self, value: Comment | None) -> None: ... + +class MergedCell(StyleableObject): + __slots__ = ("row", "column") + data_type: str + comment: Comment | None + hyperlink: Hyperlink | None + row: int | None + column: int | None + def __init__( + self, worksheet: _WorkbookChild | ReadOnlyWorksheet, row: int | None = None, column: int | None = None + ) -> None: ... + # Same as Cell.coordinate + # https://github.com/python/mypy/issues/6700 + @property + def coordinate(self) -> str: ... + # The value of a MergedCell is always None. + value: None + +def WriteOnlyCell(ws: _WorkbookChild | ReadOnlyWorksheet, value: str | float | datetime | None = None) -> Cell: ... diff --git a/stubs/openpyxl/openpyxl/cell/read_only.pyi b/stubs/openpyxl/openpyxl/cell/read_only.pyi new file mode 100644 index 000000000000..21fe3097e518 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/read_only.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete +from typing import Final + +from openpyxl.cell import _CellGetValue +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.borders import Border +from openpyxl.styles.cell_style import StyleArray +from openpyxl.styles.fills import Fill +from openpyxl.styles.fonts import Font +from openpyxl.styles.protection import Protection +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +class ReadOnlyCell: + __slots__ = ("parent", "row", "column", "_value", "data_type", "_style_id") + parent: _WorkbookChild | ReadOnlyWorksheet + row: Incomplete + column: Incomplete + data_type: Incomplete + def __init__( + self, sheet: _WorkbookChild | ReadOnlyWorksheet, row, column, value, data_type: str = "n", style_id: int = 0 + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + # Same as Cell.coordinate + # https://github.com/python/mypy/issues/6700 + # Defined twice in the implementation + @property + def coordinate(self) -> str: ... + # Same as Cell.column_letter + # https://github.com/python/mypy/issues/6700 + @property + def column_letter(self) -> str: ... + @property + def style_array(self) -> StyleArray: ... + @property + def has_style(self) -> bool: ... + @property + def number_format(self) -> str: ... + @property + def font(self) -> Font: ... + @property + def fill(self) -> Fill: ... + @property + def border(self) -> Border: ... + @property + def alignment(self) -> Alignment: ... + @property + def protection(self) -> Protection: ... + # Same as Cell.is_date + # https://github.com/python/mypy/issues/6700 + @property + def is_date(self) -> bool: ... + @property + def internal_value(self) -> _CellGetValue: ... + + @property + def value(self) -> _CellGetValue: ... + @value.setter + def value(self, value: None) -> None: ... + +class EmptyCell: + __slots__ = () + value: Incomplete + is_date: bool + font: Incomplete + border: Incomplete + fill: Incomplete + number_format: Incomplete + alignment: Incomplete + data_type: str + +EMPTY_CELL: Final[EmptyCell] diff --git a/stubs/openpyxl/openpyxl/cell/rich_text.pyi b/stubs/openpyxl/openpyxl/cell/rich_text.pyi new file mode 100644 index 000000000000..68a4e4c0d71f --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/rich_text.pyi @@ -0,0 +1,30 @@ +from collections.abc import Iterable +from typing import Literal, overload +from typing_extensions import Self + +from openpyxl.cell.text import InlineFont +from openpyxl.descriptors import Strict, String, Typed +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +class TextBlock(Strict): + font: Typed[InlineFont, Literal[False]] + text: String[Literal[False]] + + def __init__(self, font: InlineFont, text: str) -> None: ... + def __eq__(self, other: TextBlock) -> bool: ... # type: ignore[override] + def to_tree(self) -> Element: ... + +class CellRichText(list[str | TextBlock]): + @overload + def __init__(self, args: list[str] | list[TextBlock] | list[str | TextBlock] | tuple[str | TextBlock, ...], /) -> None: ... + @overload + def __init__(self, *args: str | TextBlock) -> None: ... + + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + def __add__(self, arg: Iterable[str | TextBlock]) -> CellRichText: ... # type: ignore[override] + def append(self, arg: str | TextBlock) -> None: ... + def extend(self, arg: Iterable[str | TextBlock]) -> None: ... + def as_list(self) -> list[str]: ... + def to_tree(self) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/cell/text.pyi b/stubs/openpyxl/openpyxl/cell/text.pyi new file mode 100644 index 000000000000..178fc1611059 --- /dev/null +++ b/stubs/openpyxl/openpyxl/cell/text.pyi @@ -0,0 +1,97 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Integer, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedString, NestedText, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color +from openpyxl.styles.fonts import Font, _FontScheme, _FontU, _FontVertAlign + +from ..xml._functions_overloads import _HasTagAndGet + +_PhoneticPropertiesType: TypeAlias = Literal["halfwidthKatakana", "fullwidthKatakana", "Hiragana", "noConversion"] +_PhoneticPropertiesAlignment: TypeAlias = Literal["noControl", "left", "center", "distributed"] + +class PhoneticProperties(Serialisable): + tagname: ClassVar[str] + fontId: Integer[Literal[False]] + type: NoneSet[_PhoneticPropertiesType] + alignment: NoneSet[_PhoneticPropertiesAlignment] + def __init__( + self, + fontId: ConvertibleToInt, + type: _PhoneticPropertiesType | Literal["none"] | None = None, + alignment: _PhoneticPropertiesAlignment | Literal["none"] | None = None, + ) -> None: ... + +_PhoneticProperties: TypeAlias = PhoneticProperties + +class PhoneticText(Serialisable): + tagname: ClassVar[str] + sb: Integer[Literal[False]] + eb: Integer[Literal[False]] + t: NestedText[str, Literal[False]] + text: Alias + def __init__(self, sb: ConvertibleToInt, eb: ConvertibleToInt, t: object = None) -> None: ... + +class InlineFont(Font): + tagname: ClassVar[str] + rFont: NestedString[Literal[True]] + # Same as parent + # charset = Font.charset + # family = Font.family + # b = Font.b + # i = Font.i + # strike = Font.strike + # outline = Font.outline + # shadow = Font.shadow + # condense = Font.condense + # extend = Font.extend + # color = Font.color + # sz = Font.sz + # u = Font.u + # vertAlign = Font.vertAlign + # scheme = Font.scheme + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rFont: object = None, + charset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + family: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + b: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + i: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + strike: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + outline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shadow: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + condense: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extend: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + color: Color | None = None, + sz: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + u: _NestedNoneSetParam[_FontU] = None, + vertAlign: _NestedNoneSetParam[_FontVertAlign] = None, + scheme: _NestedNoneSetParam[_FontScheme] = None, + ) -> None: ... + +class RichText(Serialisable): + tagname: ClassVar[str] + rPr: Typed[InlineFont, Literal[True]] + font: Alias + t: NestedText[str, Literal[True]] + text: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: InlineFont | None = None, t: object = None) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + t: NestedText[str, Literal[True]] + plain: Alias + r: Incomplete + formatted: Alias + rPh: Incomplete + phonetic: Alias + phoneticPr: Typed[_PhoneticProperties, Literal[True]] + PhoneticProperties: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, t: object = None, r=(), rPh=(), phoneticPr: _PhoneticProperties | None = None) -> None: ... + @property + def content(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/_3d.pyi b/stubs/openpyxl/openpyxl/chart/_3d.pyi new file mode 100644 index 000000000000..6c12831498f8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/_3d.pyi @@ -0,0 +1,66 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedMinMax +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class View3D(Serialisable): + tagname: ClassVar[str] + rotX: NestedMinMax[float, Literal[True]] + x_rotation: Alias + hPercent: NestedMinMax[float, Literal[True]] + height_percent: Alias + rotY: NestedInteger[Literal[True]] + y_rotation: Alias + depthPercent: NestedInteger[Literal[True]] + rAngAx: NestedBool[Literal[True]] + right_angle_axes: Alias + perspective: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rotX: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 15, + hPercent: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + rotY: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = 20, + depthPercent: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + rAngAx: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = True, + perspective: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + ) -> None: ... + +class Surface(Serialisable): + tagname: ClassVar[str] + thickness: NestedInteger[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + pictureOptions: Typed[PictureOptions, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + thickness: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + extLst: Unused = None, + ) -> None: ... + +class _3DBase(Serialisable): + tagname: ClassVar[str] + view3D: Typed[View3D, Literal[True]] + floor: Typed[Surface, Literal[True]] + sideWall: Typed[Surface, Literal[True]] + backWall: Typed[Surface, Literal[True]] + def __init__( + self, + view3D: View3D | None = None, + floor: Surface | None = None, + sideWall: Surface | None = None, + backWall: Surface | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/__init__.pyi b/stubs/openpyxl/openpyxl/chart/__init__.pyi new file mode 100644 index 000000000000..e0d73d198399 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/__init__.pyi @@ -0,0 +1,15 @@ +from .area_chart import AreaChart as AreaChart, AreaChart3D as AreaChart3D +from .bar_chart import BarChart as BarChart, BarChart3D as BarChart3D +from .bubble_chart import BubbleChart as BubbleChart +from .line_chart import LineChart as LineChart, LineChart3D as LineChart3D +from .pie_chart import ( + DoughnutChart as DoughnutChart, + PieChart as PieChart, + PieChart3D as PieChart3D, + ProjectedPieChart as ProjectedPieChart, +) +from .radar_chart import RadarChart as RadarChart +from .reference import Reference as Reference +from .scatter_chart import ScatterChart as ScatterChart +from .stock_chart import StockChart as StockChart +from .surface_chart import SurfaceChart as SurfaceChart, SurfaceChart3D as SurfaceChart3D diff --git a/stubs/openpyxl/openpyxl/chart/_chart.pyi b/stubs/openpyxl/openpyxl/chart/_chart.pyi new file mode 100644 index 000000000000..61e472151af8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/_chart.pyi @@ -0,0 +1,50 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.layout import Layout +from openpyxl.chart.legend import Legend +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.title import TitleDescriptor +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, Set, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +_ChartBaseDisplayBlanks: TypeAlias = Literal["span", "gap", "zero"] + +class AxId(Serialisable): + val: Integer[Literal[False]] + def __init__(self, val: ConvertibleToInt) -> None: ... + +def PlotArea(): ... + +class ChartBase(Serialisable): + legend: Typed[Legend, Literal[True]] + layout: Typed[Layout, Literal[True]] + roundedCorners: Bool[Literal[True]] + axId: Incomplete + visible_cells_only: Bool[Literal[True]] + display_blanks: Set[_ChartBaseDisplayBlanks] + ser: Incomplete + series: Alias + title: TitleDescriptor + anchor: str + width: int + height: float + style: MinMax[float, Literal[True]] + mime_type: str + graphical_properties: Typed[GraphicalProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + plot_area: Incomplete + pivotSource: Incomplete + pivotFormats: Incomplete + idx_base: int + def __init__(self, axId=(), **kw: Unused) -> None: ... + def __hash__(self) -> int: ... + def __iadd__(self, other): ... + # namespace is in the wrong order to respect the override. This is an issue in openpyxl itself + def to_tree(self, namespace: Unused = None, tagname: str | None = None, idx: Unused = None) -> Element: ... # type: ignore[override] + def set_categories(self, labels) -> None: ... + def add_data(self, data, from_rows: bool = False, titles_from_data: bool = False) -> None: ... + def append(self, value) -> None: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/area_chart.pyi b/stubs/openpyxl/openpyxl/chart/area_chart.pyi new file mode 100644 index 000000000000..25c1336a323a --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/area_chart.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_AreaChartBaseGrouping: TypeAlias = Literal["percentStacked", "standard", "stacked"] + +class _AreaChartBase(ChartBase): + grouping: NestedSet[_AreaChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + grouping: _HasTagAndGet[_AreaChartBaseGrouping] | _AreaChartBaseGrouping = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + ) -> None: ... + +class AreaChart(_AreaChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _AreaChartBase.grouping + # varyColors = _AreaChartBase.varyColors + # ser = _AreaChartBase.ser + # dLbls = _AreaChartBase.dLbls + # dropLines = _AreaChartBase.dropLines + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, axId: Unused = None, extLst: Unused = None, **kw) -> None: ... + +class AreaChart3D(AreaChart): + tagname: ClassVar[str] + # Same as parent and grandparent + # grouping = _AreaChartBase.grouping + # varyColors = _AreaChartBase.varyColors + # ser = _AreaChartBase.ser + # dLbls = _AreaChartBase.dLbls + # dropLines = _AreaChartBase.dropLines + gapDepth: Incomplete + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, gapDepth=None, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/axis.pyi b/stubs/openpyxl/openpyxl/chart/axis.pyi new file mode 100644 index 000000000000..b98f29d87c35 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/axis.pyi @@ -0,0 +1,312 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload +from typing_extensions import Self + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.chart.title import Title, TitleDescriptor +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import ( + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedSet, + _NestedNoneSetParam, +) +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText + +_ScalingOrientation: TypeAlias = Literal["maxMin", "minMax"] +_BaseAxisAxPos: TypeAlias = Literal["b", "l", "r", "t"] +_BaseAxisTickMark: TypeAlias = Literal["cross", "in", "out"] +_BaseAxisTickLblPos: TypeAlias = Literal["high", "low", "nextTo"] +_BaseAxisCrosses: TypeAlias = Literal["autoZero", "max", "min"] +_DisplayUnitsLabelListBuiltInUnit: TypeAlias = Literal[ + "hundreds", + "thousands", + "tenThousands", + "hundredThousands", + "millions", + "tenMillions", + "hundredMillions", + "billions", + "trillions", +] +_NumericAxisCrossBetween: TypeAlias = Literal["between", "midCat"] +_TextAxisLblAlgn: TypeAlias = Literal["ctr", "l", "r"] +_DateAxisTimeUnit: TypeAlias = Literal["days", "months", "years"] + +class ChartLines(Serialisable): + tagname: ClassVar[str] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + def __init__(self, spPr: GraphicalProperties | None = None) -> None: ... + +class Scaling(Serialisable): + tagname: ClassVar[str] + logBase: NestedFloat[Literal[True]] + orientation: NestedSet[_ScalingOrientation] + max: NestedFloat[Literal[True]] + min: NestedFloat[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + logBase: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + orientation: _HasTagAndGet[_ScalingOrientation] | _ScalingOrientation = "minMax", + max: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + min: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + extLst: Unused = None, + ) -> None: ... + +class _BaseAxis(Serialisable): + axId: NestedInteger[Literal[False]] + scaling: Typed[Scaling, Literal[False]] + delete: NestedBool[Literal[True]] + axPos: NestedSet[_BaseAxisAxPos] + majorGridlines: Typed[ChartLines, Literal[True]] + minorGridlines: Typed[ChartLines, Literal[True]] + title: TitleDescriptor + numFmt: Incomplete + number_format: Alias + majorTickMark: NestedNoneSet[_BaseAxisTickMark] + minorTickMark: NestedNoneSet[_BaseAxisTickMark] + tickLblPos: NestedNoneSet[_BaseAxisTickLblPos] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + crossAx: NestedInteger[Literal[False]] + crosses: NestedNoneSet[_BaseAxisCrosses] + crossesAt: NestedFloat[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + axId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + scaling: Scaling | None, + delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + axPos: _HasTagAndGet[_BaseAxisAxPos] | _BaseAxisAxPos, + majorGridlines: ChartLines | None, + minorGridlines: ChartLines | None, + title: str | Title | None, + numFmt: Incomplete | None, + majorTickMark: _NestedNoneSetParam[_BaseAxisTickMark], + minorTickMark: _NestedNoneSetParam[_BaseAxisTickMark], + tickLblPos: _NestedNoneSetParam[_BaseAxisTickLblPos], + spPr: GraphicalProperties | None, + txPr: RichText | None, + crossAx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + crosses: _NestedNoneSetParam[_BaseAxisCrosses] = None, + crossesAt: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... + @overload + def __init__( + self, + axId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + scaling: Scaling | None = None, + delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + axPos: _HasTagAndGet[_BaseAxisAxPos] | _BaseAxisAxPos = "l", + majorGridlines: ChartLines | None = None, + minorGridlines: ChartLines | None = None, + title: str | Title | None = None, + numFmt=None, + majorTickMark=None, + minorTickMark=None, + tickLblPos=None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + *, + crossAx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + crosses=None, + crossesAt: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... + +class DisplayUnitsLabel(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + tx: Typed[Text, Literal[True]] + text: Alias + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textPropertes: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + tx: Text | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + ) -> None: ... + +class DisplayUnitsLabelList(Serialisable): + tagname: ClassVar[str] + custUnit: NestedFloat[Literal[True]] + builtInUnit: NestedNoneSet[_DisplayUnitsLabelListBuiltInUnit] + dispUnitsLbl: Typed[DisplayUnitsLabel, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + custUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + builtInUnit: ( + _HasTagAndGet[_DisplayUnitsLabelListBuiltInUnit] | _DisplayUnitsLabelListBuiltInUnit | Literal["none"] | None + ) = None, + dispUnitsLbl: DisplayUnitsLabel | None = None, + extLst: Unused = None, + ) -> None: ... + +class NumericAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + crossBetween: NestedNoneSet[_NumericAxisCrossBetween] + majorUnit: NestedFloat[Literal[True]] + minorUnit: NestedFloat[Literal[True]] + dispUnits: Typed[DisplayUnitsLabelList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + crossBetween: _NestedNoneSetParam[_NumericAxisCrossBetween] = None, + majorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + minorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + dispUnits: DisplayUnitsLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + @classmethod + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... + +class TextAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + auto: NestedBool[Literal[True]] + lblAlgn: NestedNoneSet[_TextAxisLblAlgn] + lblOffset: NestedMinMax[float, Literal[False]] + tickLblSkip: NestedInteger[Literal[True]] + tickMarkSkip: NestedInteger[Literal[True]] + noMultiLvlLbl: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + auto: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lblAlgn: _NestedNoneSetParam[_TextAxisLblAlgn] = None, + lblOffset: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 100, + tickLblSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + tickMarkSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + noMultiLvlLbl: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class DateAxis(TextAxis): + tagname: ClassVar[str] + # Same as parent and grandparent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + auto: NestedBool[Literal[True]] + lblOffset: NestedInteger[Literal[True]] # type: ignore[assignment] + baseTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + majorUnit: NestedFloat[Literal[True]] + majorTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + minorUnit: NestedFloat[Literal[True]] + minorTimeUnit: NestedNoneSet[_DateAxisTimeUnit] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + auto: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lblOffset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + baseTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + majorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + majorTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + minorUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + minorTimeUnit: _NestedNoneSetParam[_DateAxisTimeUnit] = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class SeriesAxis(_BaseAxis): + tagname: ClassVar[str] + # Same as parent + # axId = _BaseAxis.axId + # scaling = _BaseAxis.scaling + # delete = _BaseAxis.delete + # axPos = _BaseAxis.axPos + # majorGridlines = _BaseAxis.majorGridlines + # minorGridlines = _BaseAxis.minorGridlines + # title = _BaseAxis.title + # numFmt = _BaseAxis.numFmt + # majorTickMark = _BaseAxis.majorTickMark + # minorTickMark = _BaseAxis.minorTickMark + # tickLblPos = _BaseAxis.tickLblPos + # spPr = _BaseAxis.spPr + # txPr = _BaseAxis.txPr + # crossAx = _BaseAxis.crossAx + # crosses = _BaseAxis.crosses + # crossesAt = _BaseAxis.crossesAt + tickLblSkip: NestedInteger[Literal[True]] + tickMarkSkip: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tickLblSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + tickMarkSkip: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/bar_chart.pyi b/stubs/openpyxl/openpyxl/chart/bar_chart.pyi new file mode 100644 index 000000000000..eecafc725838 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/bar_chart.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedNoneSet, NestedSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._3d import _3DBase +from ._chart import ChartBase + +_BarChartBaseBarDir: TypeAlias = Literal["bar", "col"] +_BarChartBaseGrouping: TypeAlias = Literal["percentStacked", "clustered", "standard", "stacked"] +_BarChart3DShape: TypeAlias = Literal["cone", "coneToMax", "box", "cylinder", "pyramid", "pyramidToMax"] + +class _BarChartBase(ChartBase): + barDir: NestedSet[_BarChartBaseBarDir] + type: Alias + grouping: NestedSet[_BarChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + barDir: _HasTagAndGet[_BarChartBaseBarDir] | _BarChartBaseBarDir = "col", + grouping: _HasTagAndGet[_BarChartBaseGrouping] | _BarChartBaseGrouping = "clustered", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + **kw, + ) -> None: ... + +class BarChart(_BarChartBase): + tagname: ClassVar[str] + # Same as parent + # barDir = _BarChartBase.barDir + # grouping = _BarChartBase.grouping + # varyColors = _BarChartBase.varyColors + # ser = _BarChartBase.ser + # dLbls = _BarChartBase.dLbls + gapWidth: Incomplete + overlap: Incomplete + serLines: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + legend: Incomplete + def __init__( + self, gapWidth: int = 150, overlap=None, serLines: ChartLines | None = None, extLst: Unused = None, **kw + ) -> None: ... + +class BarChart3D(_BarChartBase, _3DBase): + tagname: ClassVar[str] + # Same as parents + # barDir = _BarChartBase.barDir + # grouping = _BarChartBase.grouping + # varyColors = _BarChartBase.varyColors + # ser = _BarChartBase.ser + # dLbls = _BarChartBase.dLbls + # view3D = _3DBase.view3D + # floor = _3DBase.floor + # sideWall = _3DBase.sideWall + # backWall = _3DBase.backWall + gapWidth: Incomplete + gapDepth: Incomplete + shape: NestedNoneSet[_BarChart3DShape] + serLines: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + gapWidth: int = 150, + gapDepth: int = 150, + shape: _NestedNoneSetParam[_BarChart3DShape] = None, + serLines: ChartLines | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi b/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi new file mode 100644 index 000000000000..d9e1cd4dc4f8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/bubble_chart.pyi @@ -0,0 +1,40 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedMinMax, NestedNoneSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_BubbleChartSizeRepresents: TypeAlias = Literal["area", "w"] + +class BubbleChart(ChartBase): + tagname: ClassVar[str] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + bubble3D: NestedBool[Literal[True]] + bubbleScale: NestedMinMax[float, Literal[True]] + showNegBubbles: NestedBool[Literal[True]] + sizeRepresents: NestedNoneSet[_BubbleChartSizeRepresents] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[NumericAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + bubbleScale: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + showNegBubbles: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + sizeRepresents: _NestedNoneSetParam[_BubbleChartSizeRepresents] = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/chartspace.pyi b/stubs/openpyxl/openpyxl/chart/chartspace.pyi new file mode 100644 index 000000000000..5e21bb8397a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/chartspace.pyi @@ -0,0 +1,147 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.chart._3d import Surface, View3D +from openpyxl.chart.legend import Legend +from openpyxl.chart.pivot import PivotSource +from openpyxl.chart.plotarea import PlotArea +from openpyxl.chart.print_settings import PrintSettings +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.chart.title import Title +from openpyxl.descriptors.base import Alias, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedMinMax, NestedNoneSet, NestedString, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorMapping +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_ChartContainerDispBlanksAs: TypeAlias = Literal["span", "gap", "zero"] + +class ChartContainer(Serialisable): + tagname: ClassVar[str] + title: Typed[Title, Literal[True]] + autoTitleDeleted: NestedBool[Literal[True]] + pivotFmts: Incomplete + + # Same as _3DBase + # https://github.com/python/mypy/issues/6700 + view3D: Typed[View3D, Literal[True]] + floor: Typed[Surface, Literal[True]] + sideWall: Typed[Surface, Literal[True]] + backWall: Typed[Surface, Literal[True]] + + plotArea: Typed[PlotArea, Literal[False]] + legend: Typed[Legend, Literal[True]] + plotVisOnly: NestedBool[Literal[False]] + dispBlanksAs: NestedNoneSet[_ChartContainerDispBlanksAs] + showDLblsOverMax: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + title: Title | None = None, + autoTitleDeleted: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + pivotFmts=(), + view3D: View3D | None = None, + floor: Surface | None = None, + sideWall: Surface | None = None, + backWall: Surface | None = None, + plotArea: PlotArea | None = None, + legend: Legend | None = None, + plotVisOnly: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = True, + dispBlanksAs: _NestedNoneSetParam[_ChartContainerDispBlanksAs] = "gap", + showDLblsOverMax: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class Protection(Serialisable): + tagname: ClassVar[str] + chartObject: NestedBool[Literal[True]] + data: NestedBool[Literal[True]] + formatting: NestedBool[Literal[True]] + selection: NestedBool[Literal[True]] + userInterface: NestedBool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + chartObject: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + data: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + formatting: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + selection: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + userInterface: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ) -> None: ... + +class ExternalData(Serialisable): + tagname: ClassVar[str] + autoUpdate: NestedBool[Literal[True]] + id: String[Literal[False]] + + @overload + def __init__( + self, autoUpdate: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, *, id: str + ) -> None: ... + @overload + def __init__(self, autoUpdate: Incomplete | None, id: str) -> None: ... + +class ChartSpace(Serialisable): + tagname: ClassVar[str] + date1904: NestedBool[Literal[True]] + lang: NestedString[Literal[True]] + roundedCorners: NestedBool[Literal[True]] + style: NestedMinMax[float, Literal[True]] + clrMapOvr: Typed[ColorMapping, Literal[True]] + pivotSource: Typed[PivotSource, Literal[True]] + protection: Typed[Protection, Literal[True]] + chart: Typed[ChartContainer, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphical_properties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + externalData: Typed[ExternalData, Literal[True]] + printSettings: Typed[PrintSettings, Literal[True]] + userShapes: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + date1904: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + lang: object = None, + roundedCorners: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + style: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + clrMapOvr: ColorMapping | None = None, + pivotSource: PivotSource | None = None, + protection: Protection | None = None, + *, + chart: ChartContainer, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + externalData: ExternalData | None = None, + printSettings: PrintSettings | None = None, + userShapes=None, + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + date1904: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + lang: object, + roundedCorners: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + style: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + clrMapOvr: ColorMapping | None, + pivotSource: PivotSource | None, + protection: Protection | None, + chart: ChartContainer, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + externalData: ExternalData | None = None, + printSettings: PrintSettings | None = None, + userShapes=None, + extLst: Unused = None, + ) -> None: ... + + def to_tree(self, tagname: Unused = None, idx: Unused = None, namespace: Unused = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/chart/data_source.pyi b/stubs/openpyxl/openpyxl/chart/data_source.pyi new file mode 100644 index 000000000000..fa6460de3ae9 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/data_source.pyi @@ -0,0 +1,122 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, overload +from typing_extensions import Never + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger, NestedText +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class NumFmt(Serialisable): + formatCode: String[Literal[False]] + sourceLinked: Bool[Literal[False]] + def __init__(self, formatCode: str, sourceLinked: _ConvertibleToBool = False) -> None: ... + +class NumberValueDescriptor(NestedText[Incomplete, Incomplete]): + allow_none: bool + expected_type: type[Incomplete] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... # type: ignore[override] + +class NumVal(Serialisable): + idx: Integer[Literal[False]] + formatCode: NestedText[str, Literal[True]] + v: Incomplete + def __init__(self, idx: ConvertibleToInt, formatCode: object = None, v=None) -> None: ... + +class NumData(Serialisable): + formatCode: NestedText[str, Literal[True]] + ptCount: NestedInteger[Literal[True]] + pt: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + formatCode: object = None, + ptCount: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + pt=(), + extLst: Unused = None, + ) -> None: ... + +class NumRef(Serialisable): + f: NestedText[str, Literal[False]] + ref: Alias + numCache: Typed[NumData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, numCache: NumData | None = None, extLst: Unused = None) -> None: ... + +class StrVal(Serialisable): + tagname: ClassVar[str] + idx: Integer[Literal[False]] + v: NestedText[str, Literal[False]] + def __init__(self, idx: ConvertibleToInt = 0, v: object = None) -> None: ... + +class StrData(Serialisable): + tagname: ClassVar[str] + ptCount: NestedInteger[Literal[True]] + pt: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, ptCount: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, pt=(), extLst: Unused = None + ) -> None: ... + +class StrRef(Serialisable): + tagname: ClassVar[str] + f: NestedText[str, Literal[True]] + strCache: Typed[StrData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, strCache: StrData | None = None, extLst: Unused = None) -> None: ... + +class NumDataSource(Serialisable): + numRef: Typed[NumRef, Literal[True]] + numLit: Typed[NumData, Literal[True]] + def __init__(self, numRef: NumRef | None = None, numLit: NumData | None = None) -> None: ... + +class Level(Serialisable): + tagname: ClassVar[str] + pt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pt=()) -> None: ... + +class MultiLevelStrData(Serialisable): + tagname: ClassVar[str] + ptCount: Integer[Literal[True]] + lvl: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ptCount: ConvertibleToInt | None = None, lvl=(), extLst: Unused = None) -> None: ... + +class MultiLevelStrRef(Serialisable): + tagname: ClassVar[str] + f: NestedText[str, Literal[False]] + multiLvlStrCache: Typed[MultiLevelStrData, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, f: object = None, multiLvlStrCache: MultiLevelStrData | None = None, extLst: Unused = None) -> None: ... + +class AxDataSource(Serialisable): + tagname: ClassVar[str] + numRef: Typed[NumRef, Literal[True]] + numLit: Typed[NumData, Literal[True]] + strRef: Typed[StrRef, Literal[True]] + strLit: Typed[StrData, Literal[True]] + multiLvlStrRef: Typed[MultiLevelStrRef, Literal[True]] + + @overload + def __init__( + self, numRef: None = None, numLit: None = None, strRef: None = None, strLit: None = None, multiLvlStrRef: None = None + ) -> Never: ... + @overload + def __init__( + self, + numRef: NumRef | None = None, + numLit: NumData | None = None, + strRef: StrRef | None = None, + strLit: StrData | None = None, + multiLvlStrRef: MultiLevelStrRef | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/descriptors.pyi b/stubs/openpyxl/openpyxl/chart/descriptors.pyi new file mode 100644 index 000000000000..fa6f41d0238c --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/descriptors.pyi @@ -0,0 +1,21 @@ +from typing import Literal + +from openpyxl.chart.data_source import NumFmt +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.nested import NestedMinMax +from openpyxl.descriptors.serialisable import Serialisable + +class NestedGapAmount(NestedMinMax[float, bool]): + allow_none: bool + min: float + max: float + +class NestedOverlap(NestedMinMax[float, bool]): + allow_none: bool + min: float + max: float + +class NumberFormatDescriptor(Typed[NumFmt, Literal[True]]): + expected_type: type[NumFmt] + allow_none: Literal[True] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/error_bar.pyi b/stubs/openpyxl/openpyxl/chart/error_bar.pyi new file mode 100644 index 000000000000..f39d64fa107f --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/error_bar.pyi @@ -0,0 +1,44 @@ +from _typeshed import ConvertibleToFloat, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import NumDataSource +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ErrorBarsErrBarType: TypeAlias = Literal["both", "minus", "plus"] +_ErrorBarsErrValType: TypeAlias = Literal["cust", "fixedVal", "percentage", "stdDev", "stdErr"] +_ErrorBarsErrDir: TypeAlias = Literal["x", "y"] + +class ErrorBars(Serialisable): + tagname: ClassVar[str] + errDir: NestedNoneSet[_ErrorBarsErrDir] + direction: Alias + errBarType: NestedSet[_ErrorBarsErrBarType] + style: Alias + errValType: NestedSet[_ErrorBarsErrValType] + size: Alias + noEndCap: NestedBool[Literal[True]] + plus: Typed[NumDataSource, Literal[True]] + minus: Typed[NumDataSource, Literal[True]] + val: NestedFloat[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + errDir: _NestedNoneSetParam[_ErrorBarsErrDir] = None, + errBarType: _HasTagAndGet[_ErrorBarsErrBarType] | _ErrorBarsErrBarType = "both", + errValType: _HasTagAndGet[_ErrorBarsErrValType] | _ErrorBarsErrValType = "fixedVal", + noEndCap: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + plus: NumDataSource | None = None, + minus: NumDataSource | None = None, + val: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + spPr: GraphicalProperties | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/label.pyi b/stubs/openpyxl/openpyxl/chart/label.pyi new file mode 100644 index 000000000000..4c3fe53b3320 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/label.pyi @@ -0,0 +1,91 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedNoneSet, NestedString, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_DataLabelBaseDLblPos: TypeAlias = Literal["bestFit", "b", "ctr", "inBase", "inEnd", "l", "outEnd", "r", "t"] + +class _DataLabelBase(Serialisable): + numFmt: NestedString[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + dLblPos: NestedNoneSet[_DataLabelBaseDLblPos] + position: Alias + showLegendKey: NestedBool[Literal[True]] + showVal: NestedBool[Literal[True]] + showCatName: NestedBool[Literal[True]] + showSerName: NestedBool[Literal[True]] + showPercent: NestedBool[Literal[True]] + showBubbleSize: NestedBool[Literal[True]] + showLeaderLines: NestedBool[Literal[True]] + separator: NestedString[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + numFmt: object = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + dLblPos: _NestedNoneSetParam[_DataLabelBaseDLblPos] = None, + showLegendKey: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showVal: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showCatName: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showSerName: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showPercent: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showBubbleSize: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showLeaderLines: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + separator: object = None, + extLst: Unused = None, + ) -> None: ... + +class DataLabel(_DataLabelBase): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + # Same as parent + # numFmt = _DataLabelBase.numFmt + # spPr = _DataLabelBase.spPr + # txPr = _DataLabelBase.txPr + # dLblPos = _DataLabelBase.dLblPos + # showLegendKey = _DataLabelBase.showLegendKey + # showVal = _DataLabelBase.showVal + # showCatName = _DataLabelBase.showCatName + # showSerName = _DataLabelBase.showSerName + # showPercent = _DataLabelBase.showPercent + # showBubbleSize = _DataLabelBase.showBubbleSize + # showLeaderLines = _DataLabelBase.showLeaderLines + # separator = _DataLabelBase.separator + # extLst = _DataLabelBase.extLst + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, **kw) -> None: ... + +class DataLabelList(_DataLabelBase): + tagname: ClassVar[str] + dLbl: Incomplete + delete: NestedBool[Literal[True]] + # Same as parent + # numFmt = _DataLabelBase.numFmt + # spPr = _DataLabelBase.spPr + # txPr = _DataLabelBase.txPr + # dLblPos = _DataLabelBase.dLblPos + # showLegendKey = _DataLabelBase.showLegendKey + # showVal = _DataLabelBase.showVal + # showCatName = _DataLabelBase.showCatName + # showSerName = _DataLabelBase.showSerName + # showPercent = _DataLabelBase.showPercent + # showBubbleSize = _DataLabelBase.showBubbleSize + # showLeaderLines = _DataLabelBase.showLeaderLines + # separator = _DataLabelBase.separator + # extLst = _DataLabelBase.extLst + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, dLbl=(), delete: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, **kw + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/layout.pyi b/stubs/openpyxl/openpyxl/chart/layout.pyi new file mode 100644 index 000000000000..dde22b10a1d7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/layout.pyi @@ -0,0 +1,48 @@ +from _typeshed import ConvertibleToFloat, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedMinMax, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ManualLayoutMode: TypeAlias = Literal["edge", "factor"] +_ManualLayoutLayoutTarget: TypeAlias = Literal["inner", "outer"] + +class ManualLayout(Serialisable): + tagname: ClassVar[str] + layoutTarget: NestedNoneSet[_ManualLayoutLayoutTarget] + xMode: NestedNoneSet[_ManualLayoutMode] + yMode: NestedNoneSet[_ManualLayoutMode] + wMode: NestedSet[_ManualLayoutMode] + hMode: NestedSet[_ManualLayoutMode] + x: NestedMinMax[float, Literal[True]] + y: NestedMinMax[float, Literal[True]] + w: NestedMinMax[float, Literal[True]] + width: Alias + h: NestedMinMax[float, Literal[True]] + height: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layoutTarget: _NestedNoneSetParam[_ManualLayoutLayoutTarget] = None, + xMode: _NestedNoneSetParam[_ManualLayoutMode] = None, + yMode: _NestedNoneSetParam[_ManualLayoutMode] = None, + wMode: _HasTagAndGet[_ManualLayoutMode] | _ManualLayoutMode = "factor", + hMode: _HasTagAndGet[_ManualLayoutMode] | _ManualLayoutMode = "factor", + x: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + y: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + w: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + h: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + extLst: Unused = None, + ) -> None: ... + +class Layout(Serialisable): + tagname: ClassVar[str] + manualLayout: Typed[ManualLayout, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, manualLayout: ManualLayout | None = None, extLst: Unused = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/legend.pyi b/stubs/openpyxl/openpyxl/chart/legend.pyi new file mode 100644 index 000000000000..ba5fc7d3aa82 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/legend.pyi @@ -0,0 +1,53 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedSet +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_LegendLegendPos: TypeAlias = Literal["b", "tr", "l", "r", "t"] + +class LegendEntry(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + delete: NestedBool[Literal[False]] + txPr: Typed[RichText, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + delete: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = False, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class Legend(Serialisable): + tagname: ClassVar[str] + legendPos: NestedSet[_LegendLegendPos] + position: Alias + legendEntry: Incomplete + layout: Typed[Layout, Literal[True]] + overlay: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + legendPos: _HasTagAndGet[_LegendLegendPos] | _LegendLegendPos = "r", + legendEntry=(), + layout: Layout | None = None, + overlay: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/line_chart.pyi b/stubs/openpyxl/openpyxl/chart/line_chart.pyi new file mode 100644 index 000000000000..4bcdc2abd5c8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/line_chart.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines, NumericAxis, _BaseAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.updown_bars import UpDownBars +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_LineChartBaseGrouping: TypeAlias = Literal["percentStacked", "standard", "stacked"] + +class _LineChartBase(ChartBase): + grouping: NestedSet[_LineChartBaseGrouping] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + grouping: _HasTagAndGet[_LineChartBaseGrouping] | _LineChartBaseGrouping = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + **kw, + ) -> None: ... + +class LineChart(_LineChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _LineChartBase.grouping + # varyColors = _LineChartBase.varyColors + # ser = _LineChartBase.ser + # dLbls = _LineChartBase.dLbls + # dropLines = _LineChartBase.dropLines + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + marker: NestedBool[Literal[True]] + smooth: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[_BaseAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + marker: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... + +class LineChart3D(_LineChartBase): + tagname: ClassVar[str] + # Same as parent + # grouping = _LineChartBase.grouping + # varyColors = _LineChartBase.varyColors + # ser = _LineChartBase.ser + # dLbls = _LineChartBase.dLbls + # dropLines = _LineChartBase.dropLines + gapDepth: Incomplete + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + marker: NestedBool[Literal[True]] + smooth: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[ExtensionList, Literal[False]] + y_axis: Typed[ExtensionList, Literal[False]] + z_axis: Typed[ExtensionList, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + gapDepth=None, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + marker: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/marker.pyi b/stubs/openpyxl/openpyxl/chart/marker.pyi new file mode 100644 index 000000000000..bd526ee90985 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/marker.pyi @@ -0,0 +1,55 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedMinMax, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_MarkerSymbol: TypeAlias = Literal[ + "circle", "dash", "diamond", "dot", "picture", "plus", "square", "star", "triangle", "x", "auto" +] + +class Marker(Serialisable): + tagname: ClassVar[str] + symbol: NestedNoneSet[_MarkerSymbol] + size: NestedMinMax[float, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + symbol: _NestedNoneSetParam[_MarkerSymbol] = None, + size: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + spPr: GraphicalProperties | None = None, + extLst: Unused = None, + ) -> None: ... + +class DataPoint(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + invertIfNegative: NestedBool[Literal[True]] + marker: Typed[Marker, Literal[True]] + bubble3D: NestedBool[Literal[True]] + explosion: NestedInteger[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + pictureOptions: Typed[PictureOptions, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + invertIfNegative: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + marker: Marker | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + explosion: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/picture.pyi b/stubs/openpyxl/openpyxl/chart/picture.pyi new file mode 100644 index 000000000000..ee14ab6f85cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/picture.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToFloat +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import _ConvertibleToBool +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_PictureOptionsPictureFormat: TypeAlias = Literal["stretch", "stack", "stackScale"] + +class PictureOptions(Serialisable): + tagname: ClassVar[str] + applyToFront: NestedBool[Literal[True]] + applyToSides: NestedBool[Literal[True]] + applyToEnd: NestedBool[Literal[True]] + pictureFormat: NestedNoneSet[_PictureOptionsPictureFormat] + pictureStackUnit: NestedFloat[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + applyToFront: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + applyToSides: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + applyToEnd: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + pictureFormat: _NestedNoneSetParam[_PictureOptionsPictureFormat] = None, + pictureStackUnit: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/pie_chart.pyi b/stubs/openpyxl/openpyxl/chart/pie_chart.pyi new file mode 100644 index 000000000000..c43e6f1dafe6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/pie_chart.pyi @@ -0,0 +1,104 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import ChartLines +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedMinMax, NestedNoneSet, NestedSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_ProjectedPieChartOfPieType: TypeAlias = Literal["pie", "bar"] +_ProjectedPieChartSplitType: TypeAlias = Literal["auto", "cust", "percent", "pos", "val"] + +class _PieChartBase(ChartBase): + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = True, + ser=(), + dLbls: DataLabelList | None = None, + ) -> None: ... + +class PieChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + firstSliceAng: NestedMinMax[float, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, firstSliceAng: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 0, extLst: Unused = None, **kw + ) -> None: ... + +class PieChart3D(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + +class DoughnutChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + firstSliceAng: NestedMinMax[float, Literal[False]] + holeSize: NestedMinMax[float, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + firstSliceAng: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat = 0, + holeSize: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 10, + extLst: Unused = None, + **kw, + ) -> None: ... + +class CustomSplit(Serialisable): + tagname: ClassVar[str] + secondPiePt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, secondPiePt=()) -> None: ... + +class ProjectedPieChart(_PieChartBase): + tagname: ClassVar[str] + # Same as parent + # varyColors = _PieChartBase.varyColors + # ser = _PieChartBase.ser + # dLbls = _PieChartBase.dLbls + ofPieType: NestedSet[_ProjectedPieChartOfPieType] + type: Alias + gapWidth: Incomplete + splitType: NestedNoneSet[_ProjectedPieChartSplitType] + splitPos: NestedFloat[Literal[True]] + custSplit: Typed[CustomSplit, Literal[True]] + secondPieSize: NestedMinMax[float, Literal[True]] + serLines: Typed[ChartLines, Literal[True]] + join_lines: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + ofPieType: _HasTagAndGet[_ProjectedPieChartOfPieType] | _ProjectedPieChartOfPieType = "pie", + gapWidth=None, + splitType: _NestedNoneSetParam[_ProjectedPieChartSplitType] = "auto", + splitPos: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + custSplit: CustomSplit | None = None, + secondPieSize: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = 75, + serLines: ChartLines | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/pivot.pyi b/stubs/openpyxl/openpyxl/chart/pivot.pyi new file mode 100644 index 000000000000..2546e921560c --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/pivot.pyi @@ -0,0 +1,51 @@ +from _typeshed import ConvertibleToInt, Unused +from typing import ClassVar, Literal, overload + +from openpyxl.chart.label import DataLabel as _DataLabel +from openpyxl.chart.marker import Marker +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger, NestedText +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class PivotSource(Serialisable): + tagname: ClassVar[str] + name: NestedText[str, Literal[False]] + fmtId: NestedInteger[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, name: object, fmtId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, extLst: Unused = None + ) -> None: ... + @overload + def __init__( + self, name: object = None, *, fmtId: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, extLst: Unused = None + ) -> None: ... + +class PivotFormat(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + TextBody: Alias + marker: Typed[Marker, Literal[True]] + dLbl: Typed[_DataLabel, Literal[True]] + DataLabel: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + marker: Marker | None = None, + dLbl: _DataLabel | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/plotarea.pyi b/stubs/openpyxl/openpyxl/chart/plotarea.pyi new file mode 100644 index 000000000000..286b8150c5ca --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/plotarea.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal +from typing_extensions import Self + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +class DataTable(Serialisable): + tagname: ClassVar[str] + showHorzBorder: NestedBool[Literal[True]] + showVertBorder: NestedBool[Literal[True]] + showOutline: NestedBool[Literal[True]] + showKeys: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + showHorzBorder: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showVertBorder: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showOutline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + showKeys: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class PlotArea(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + dTable: Typed[DataTable, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + areaChart: Incomplete + area3DChart: Incomplete + lineChart: Incomplete + line3DChart: Incomplete + stockChart: Incomplete + radarChart: Incomplete + scatterChart: Incomplete + pieChart: Incomplete + pie3DChart: Incomplete + doughnutChart: Incomplete + barChart: Incomplete + bar3DChart: Incomplete + ofPieChart: Incomplete + surfaceChart: Incomplete + surface3DChart: Incomplete + bubbleChart: Incomplete + valAx: Incomplete + catAx: Incomplete + dateAx: Incomplete + serAx: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + dTable: DataTable | None = None, + spPr: GraphicalProperties | None = None, + _charts=(), + _axes=(), + extLst: Unused = None, + ) -> None: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: Unused = None) -> Element: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/chart/print_settings.pyi b/stubs/openpyxl/openpyxl/chart/print_settings.pyi new file mode 100644 index 000000000000..280114e4d7ac --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/print_settings.pyi @@ -0,0 +1,42 @@ +from _typeshed import ConvertibleToFloat +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Float, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.header_footer import HeaderFooter +from openpyxl.worksheet.page import PrintPageSetup + +class PageMargins(Serialisable): + tagname: ClassVar[str] + l: Float[Literal[False]] + left: Alias + r: Float[Literal[False]] + right: Alias + t: Float[Literal[False]] + top: Alias + b: Float[Literal[False]] + bottom: Alias + header: Float[Literal[False]] + footer: Float[Literal[False]] + def __init__( + self, + l: ConvertibleToFloat = 0.75, + r: ConvertibleToFloat = 0.75, + t: ConvertibleToFloat = 1, + b: ConvertibleToFloat = 1, + header: ConvertibleToFloat = 0.5, + footer: ConvertibleToFloat = 0.5, + ) -> None: ... + +class PrintSettings(Serialisable): + tagname: ClassVar[str] + headerFooter: Typed[HeaderFooter, Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + headerFooter: HeaderFooter | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/radar_chart.pyi b/stubs/openpyxl/openpyxl/chart/radar_chart.pyi new file mode 100644 index 000000000000..bf5cc4ca66ac --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/radar_chart.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedSet + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase + +_RadarChartRadarStyle: TypeAlias = Literal["standard", "marker", "filled"] + +class RadarChart(ChartBase): + tagname: ClassVar[str] + radarStyle: NestedSet[_RadarChartRadarStyle] + type: Alias + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + radarStyle: _HasTagAndGet[_RadarChartRadarStyle] | _RadarChartRadarStyle = "standard", + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/reader.pyi b/stubs/openpyxl/openpyxl/chart/reader.pyi new file mode 100644 index 000000000000..0e58541f2c2d --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/reader.pyi @@ -0,0 +1 @@ +def read_chart(chartspace): ... diff --git a/stubs/openpyxl/openpyxl/chart/reference.pyi b/stubs/openpyxl/openpyxl/chart/reference.pyi new file mode 100644 index 000000000000..be2cff94b357 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/reference.pyi @@ -0,0 +1,52 @@ +from _typeshed import ConvertibleToInt, Unused +from collections.abc import Generator +from typing import Literal, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import MinMax, String +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +class DummyWorksheet: + title: str + def __init__(self, title: str) -> None: ... + +class Reference(Strict): + min_row: MinMax[int, Literal[False]] + max_row: MinMax[int, Literal[False]] + min_col: MinMax[int, Literal[False]] + max_col: MinMax[int, Literal[False]] + range_string: String[Literal[True]] + worksheet: _WorkbookChild | ReadOnlyWorksheet | DummyWorksheet + + @overload + def __init__( + self, + *, + worksheet: _WorkbookChild | ReadOnlyWorksheet | DummyWorksheet | None = None, + min_col: Unused = None, + min_row: Unused = None, + max_col: Unused = None, + max_row: Unused = None, + range_string: str, + ) -> None: ... + @overload + def __init__( + self, + worksheet: _WorkbookChild | ReadOnlyWorksheet, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt | None = None, + max_row: ConvertibleToInt | None = None, + range_string: str | None = None, + ) -> None: ... + + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + @property + def rows(self) -> Generator[Reference]: ... + @property + def cols(self) -> Generator[Reference]: ... + def pop(self): ... + @property + def sheetname(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi b/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi new file mode 100644 index 000000000000..787e5c5e66c5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/scatter_chart.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.axis import NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedNoneSet, _NestedNoneSetParam + +from ..xml._functions_overloads import _HasTagAndGet +from ._chart import ChartBase as ChartBase + +_ScatterChartScatterStyle: TypeAlias = Literal["line", "lineMarker", "marker", "smooth", "smoothMarker"] + +class ScatterChart(ChartBase): + tagname: ClassVar[str] + scatterStyle: NestedNoneSet[_ScatterChartScatterStyle] + varyColors: NestedBool[Literal[True]] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[NumericAxis | TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scatterStyle: _NestedNoneSetParam[_ScatterChartScatterStyle] = None, + varyColors: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + dLbls: DataLabelList | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/series.pyi b/stubs/openpyxl/openpyxl/chart/series.pyi new file mode 100644 index 000000000000..7feb904e0961 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/series.pyi @@ -0,0 +1,106 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import AxDataSource, NumDataSource, StrRef +from openpyxl.chart.error_bar import ErrorBars +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.marker import Marker +from openpyxl.chart.picture import PictureOptions +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.trendline import Trendline +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger, NestedNoneSet, NestedText, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_SeriesShape: TypeAlias = Literal["cone", "coneToMax", "box", "cylinder", "pyramid", "pyramidToMax"] + +attribute_mapping: Incomplete + +class SeriesLabel(Serialisable): + tagname: ClassVar[str] + strRef: Typed[StrRef, Literal[True]] + v: NestedText[str, Literal[True]] + value: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, strRef: StrRef | None = None, v: object = None) -> None: ... + +class Series(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + order: NestedInteger[Literal[False]] + tx: Typed[SeriesLabel, Literal[True]] + title: Alias + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Incomplete + pictureOptions: Typed[PictureOptions, Literal[True]] + dPt: Incomplete + data_points: Alias + dLbls: Typed[DataLabelList, Literal[True]] + labels: Alias + trendline: Typed[Trendline, Literal[True]] + errBars: Typed[ErrorBars, Literal[True]] + cat: Typed[AxDataSource, Literal[True]] + identifiers: Alias + val: Typed[NumDataSource, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + invertIfNegative: NestedBool[Literal[True]] + shape: NestedNoneSet[_SeriesShape] + xVal: Typed[AxDataSource, Literal[True]] + yVal: Typed[NumDataSource, Literal[True]] + bubbleSize: Typed[NumDataSource, Literal[True]] + zVal: Alias + bubble3D: NestedBool[Literal[True]] + marker: Typed[Marker, Literal[True]] + smooth: NestedBool[Literal[True]] + explosion: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + order: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, + tx: SeriesLabel | None = None, + spPr: GraphicalProperties | None = None, + pictureOptions: PictureOptions | None = None, + dPt=(), + dLbls: DataLabelList | None = None, + trendline: Trendline | None = None, + errBars: ErrorBars | None = None, + cat: AxDataSource | None = None, + val: NumDataSource | None = None, + invertIfNegative: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shape: _NestedNoneSetParam[_SeriesShape] = None, + xVal: AxDataSource | None = None, + yVal: NumDataSource | None = None, + bubbleSize: NumDataSource | None = None, + bubble3D: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + marker: Marker | None = None, + smooth: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + explosion: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: Unused = None, + ) -> None: ... + def to_tree( # type: ignore[override] + self, tagname: str | None = None, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt | None = None + ) -> Element: ... + +class XYSeries(Series): + # Same as parent + # idx = Series.idx + # order = Series.order + # tx = Series.tx + # spPr = Series.spPr + # dPt = Series.dPt + # dLbls = Series.dLbls + # trendline = Series.trendline + # errBars = Series.errBars + # xVal = Series.xVal + # yVal = Series.yVal + # invertIfNegative = Series.invertIfNegative + # bubbleSize = Series.bubbleSize + # bubble3D = Series.bubble3D + # marker = Series.marker + # smooth = Series.smooth + ... diff --git a/stubs/openpyxl/openpyxl/chart/series_factory.pyi b/stubs/openpyxl/openpyxl/chart/series_factory.pyi new file mode 100644 index 000000000000..9faddc33a413 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/series_factory.pyi @@ -0,0 +1,9 @@ +from .reference import Reference + +def SeriesFactory( + values: Reference | str, + xvalues: Reference | str | None = None, + zvalues: Reference | str | None = None, + title: object = None, + title_from_data: bool = False, +): ... diff --git a/stubs/openpyxl/openpyxl/chart/shapes.pyi b/stubs/openpyxl/openpyxl/chart/shapes.pyi new file mode 100644 index 000000000000..d2758e4b2cc8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/shapes.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import EmptyTag +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.fill import GradientFillProperties, PatternFillProperties +from openpyxl.drawing.geometry import CustomGeometry2D, PresetGeometry2D, Scene3D, Shape3D, Transform2D +from openpyxl.drawing.line import LineProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_GraphicalPropertiesBwMode: TypeAlias = Literal[ + "clr", "auto", "gray", "ltGray", "invGray", "grayWhite", "blackGray", "blackWhite", "black", "white", "hidden" +] + +class GraphicalProperties(Serialisable): + tagname: ClassVar[str] + bwMode: NoneSet[_GraphicalPropertiesBwMode] + xfrm: Typed[Transform2D, Literal[True]] + transform: Alias + custGeom: Typed[CustomGeometry2D, Literal[True]] + prstGeom: Typed[PresetGeometry2D, Literal[True]] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + ln: Typed[LineProperties, Literal[True]] + line: Alias + scene3d: Typed[Scene3D, Literal[True]] + sp3d: Typed[Shape3D, Literal[True]] + shape3D: Alias + extLst: Typed[Incomplete, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + bwMode: _GraphicalPropertiesBwMode | Literal["none"] | None = None, + xfrm: Transform2D | None = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + ln=None, + scene3d: Scene3D | None = None, + custGeom: CustomGeometry2D | None = None, + prstGeom: PresetGeometry2D | None = None, + sp3d: Shape3D | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/stock_chart.pyi b/stubs/openpyxl/openpyxl/chart/stock_chart.pyi new file mode 100644 index 000000000000..1d2a715e4e6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/stock_chart.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.axis import ChartLines, NumericAxis, TextAxis +from openpyxl.chart.label import DataLabelList +from openpyxl.chart.updown_bars import UpDownBars +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList + +from ._chart import ChartBase + +class StockChart(ChartBase): + tagname: ClassVar[str] + ser: Incomplete + dLbls: Typed[DataLabelList, Literal[True]] + dataLabels: Alias + dropLines: Typed[ChartLines, Literal[True]] + hiLowLines: Typed[ChartLines, Literal[True]] + upDownBars: Typed[UpDownBars, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + ser=(), + dLbls: DataLabelList | None = None, + dropLines: ChartLines | None = None, + hiLowLines: ChartLines | None = None, + upDownBars: UpDownBars | None = None, + extLst: Unused = None, + **kw, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/surface_chart.pyi b/stubs/openpyxl/openpyxl/chart/surface_chart.pyi new file mode 100644 index 000000000000..944a588bd508 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/surface_chart.pyi @@ -0,0 +1,65 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.chart.axis import NumericAxis, SeriesAxis, TextAxis +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedInteger +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet +from ._3d import _3DBase +from ._chart import ChartBase + +class BandFormat(Serialisable): + tagname: ClassVar[str] + idx: NestedInteger[Literal[False]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt = 0, spPr: GraphicalProperties | None = None + ) -> None: ... + +class BandFormatList(Serialisable): + tagname: ClassVar[str] + bandFmt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, bandFmt=()) -> None: ... + +class _SurfaceChartBase(ChartBase): + wireframe: NestedBool[Literal[True]] + ser: Incomplete + bandFmts: Typed[BandFormatList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + wireframe: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ser=(), + bandFmts: BandFormatList | None = None, + **kw, + ) -> None: ... + +class SurfaceChart3D(_SurfaceChartBase, _3DBase): + tagname: ClassVar[str] + # Same as parent + # wireframe = _SurfaceChartBase.wireframe + # ser = _SurfaceChartBase.ser + # bandFmts = _SurfaceChartBase.bandFmts + extLst: Typed[ExtensionList, Literal[True]] + x_axis: Typed[TextAxis, Literal[False]] + y_axis: Typed[NumericAxis, Literal[False]] + z_axis: Typed[SeriesAxis, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, **kw) -> None: ... + +class SurfaceChart(SurfaceChart3D): + tagname: ClassVar[str] + # Same as parent and grandparent + # wireframe = _SurfaceChartBase.wireframe + # ser = _SurfaceChartBase.ser + # bandFmts = _SurfaceChartBase.bandFmts + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/text.pyi b/stubs/openpyxl/openpyxl/chart/text.pyi new file mode 100644 index 000000000000..b576900cc2e7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/text.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.data_source import StrRef +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.text import ListStyle, RichTextProperties +from openpyxl.xml.functions import Element + +class RichText(Serialisable): + tagname: ClassVar[str] + bodyPr: Typed[RichTextProperties, Literal[False]] + properties: Alias + lstStyle: Typed[ListStyle, Literal[True]] + p: Incomplete + paragraphs: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, bodyPr: RichTextProperties | None = None, lstStyle: ListStyle | None = None, p=None) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + strRef: Typed[StrRef, Literal[True]] + rich: Typed[RichText, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, strRef: StrRef | None = None, rich: RichText | None = None) -> None: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: str | None = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/chart/title.pyi b/stubs/openpyxl/openpyxl/chart/title.pyi new file mode 100644 index 000000000000..b602afe2e066 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/title.pyi @@ -0,0 +1,42 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import Alias, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +class Title(Serialisable): + tagname: ClassVar[str] + tx: Typed[Text, Literal[True]] + text: Alias + layout: Typed[Layout, Literal[True]] + overlay: NestedBool[Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + body: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tx: Text | None = None, + layout: Layout | None = None, + overlay: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +def title_maker(text) -> Title: ... + +class TitleDescriptor(Typed[Title, Literal[True]]): + expected_type: type[Title] + allow_none: Literal[True] + def __set__(self, instance: Serialisable | Strict, value: str | Title | None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/trendline.pyi b/stubs/openpyxl/openpyxl/chart/trendline.pyi new file mode 100644 index 000000000000..9b93515b49b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/trendline.pyi @@ -0,0 +1,67 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.chart.data_source import NumFmt +from openpyxl.chart.layout import Layout +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText, Text +from openpyxl.descriptors.base import Alias, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedBool, NestedFloat, NestedInteger, NestedSet +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml._functions_overloads import _HasTagAndGet + +_TrendlineTrendlineType: TypeAlias = Literal["exp", "linear", "log", "movingAvg", "poly", "power"] + +class TrendlineLabel(Serialisable): + tagname: ClassVar[str] + layout: Typed[Layout, Literal[True]] + tx: Typed[Text, Literal[True]] + numFmt: Typed[NumFmt, Literal[True]] + spPr: Typed[GraphicalProperties, Literal[True]] + graphicalProperties: Alias + txPr: Typed[RichText, Literal[True]] + textProperties: Alias + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + layout: Layout | None = None, + tx: Text | None = None, + numFmt: NumFmt | None = None, + spPr: GraphicalProperties | None = None, + txPr: RichText | None = None, + extLst: Unused = None, + ) -> None: ... + +class Trendline(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + spPr: Typed[ExtensionList, Literal[True]] + graphicalProperties: Alias + trendlineType: NestedSet[_TrendlineTrendlineType] + order: NestedInteger[Literal[True]] + period: NestedInteger[Literal[True]] + forward: NestedFloat[Literal[True]] + backward: NestedFloat[Literal[True]] + intercept: NestedFloat[Literal[True]] + dispRSqr: NestedBool[Literal[True]] + dispEq: NestedBool[Literal[True]] + trendlineLbl: Typed[ExtensionList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str | None = None, + spPr: ExtensionList | None = None, + trendlineType: _HasTagAndGet[_TrendlineTrendlineType] | _TrendlineTrendlineType = "linear", + order: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + period: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + forward: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + backward: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + intercept: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + dispRSqr: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + dispEq: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + trendlineLbl: ExtensionList | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chart/updown_bars.pyi b/stubs/openpyxl/openpyxl/chart/updown_bars.pyi new file mode 100644 index 000000000000..15fb09bef0c2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chart/updown_bars.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.chart.axis import ChartLines +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +class UpDownBars(Serialisable): + tagname: ClassVar[str] + gapWidth: Incomplete + upBars: Typed[ChartLines, Literal[True]] + downBars: Typed[ChartLines, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, gapWidth: int = 150, upBars: ChartLines | None = None, downBars: ChartLines | None = None, extLst: Unused = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi b/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi new file mode 100644 index 000000000000..59dba6f1cbf3 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/__init__.pyi @@ -0,0 +1 @@ +from .chartsheet import Chartsheet as Chartsheet diff --git a/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi b/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi new file mode 100644 index 000000000000..84d4fafede37 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/chartsheet.pyi @@ -0,0 +1,59 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl import _Decodable, _VisibilityType +from openpyxl.chartsheet.custom import CustomChartsheetViews +from openpyxl.chartsheet.properties import ChartsheetProperties +from openpyxl.chartsheet.protection import ChartsheetProtection +from openpyxl.chartsheet.publish import WebPublishItems +from openpyxl.chartsheet.relation import DrawingHF, SheetBackgroundPicture +from openpyxl.chartsheet.views import ChartsheetViewList +from openpyxl.descriptors.base import Alias, Set, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.drawing import Drawing +from openpyxl.worksheet.header_footer import HeaderFooter as _HeaderFooter +from openpyxl.worksheet.page import PageMargins, PrintPageSetup +from openpyxl.xml.functions import Element + +class Chartsheet(_WorkbookChild, Serialisable): + tagname: ClassVar[str] + mime_type: str + sheetPr: Typed[ChartsheetProperties, Literal[True]] + sheetViews: Typed[ChartsheetViewList, Literal[False]] + sheetProtection: Typed[ChartsheetProtection, Literal[True]] + customSheetViews: Typed[CustomChartsheetViews, Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + drawing: Typed[Drawing, Literal[True]] + drawingHF: Typed[DrawingHF, Literal[True]] + picture: Typed[SheetBackgroundPicture, Literal[True]] + webPublishItems: Typed[WebPublishItems, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + sheet_state: Set[_VisibilityType] + headerFooter: Typed[_HeaderFooter, Literal[False]] + HeaderFooter: Alias # type: ignore[assignment] # Different from parent class + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + sheetPr: ChartsheetProperties | None = None, + sheetViews: ChartsheetViewList | None = None, + sheetProtection: ChartsheetProtection | None = None, + customSheetViews: CustomChartsheetViews | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: _HeaderFooter | None = None, + drawing: Unused = None, + drawingHF: DrawingHF | None = None, + picture: SheetBackgroundPicture | None = None, + webPublishItems: WebPublishItems | None = None, + extLst: Unused = None, + parent: Workbook | None = None, + title: str | _Decodable | None = "", + sheet_state: _VisibilityType = "visible", + ) -> None: ... + def add_chart(self, chart) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/chartsheet/custom.pyi b/stubs/openpyxl/openpyxl/chartsheet/custom.pyi new file mode 100644 index 000000000000..be243e9f8fb2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/custom.pyi @@ -0,0 +1,49 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Bool, Integer, Set, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.header_footer import HeaderFooter +from openpyxl.worksheet.page import PageMargins, PrintPageSetup + +class CustomChartsheetView(Serialisable): + tagname: ClassVar[str] + guid: Incomplete + scale: Integer[Literal[False]] + state: Set[_VisibilityType] + zoomToFit: Bool[Literal[True]] + pageMargins: Typed[PageMargins, Literal[True]] + pageSetup: Typed[PrintPageSetup, Literal[True]] + headerFooter: Typed[HeaderFooter, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + guid=None, + *, + scale: ConvertibleToInt, + state: _VisibilityType = "visible", + zoomToFit: _ConvertibleToBool | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: HeaderFooter | None = None, + ) -> None: ... + @overload + def __init__( + self, + guid: Incomplete | None, + scale: ConvertibleToInt, + state: _VisibilityType = "visible", + zoomToFit: _ConvertibleToBool | None = None, + pageMargins: PageMargins | None = None, + pageSetup: PrintPageSetup | None = None, + headerFooter: HeaderFooter | None = None, + ) -> None: ... + +class CustomChartsheetViews(Serialisable): + tagname: ClassVar[str] + customSheetView: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, customSheetView=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/properties.pyi b/stubs/openpyxl/openpyxl/chartsheet/properties.pyi new file mode 100644 index 000000000000..c04213b58c33 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/properties.pyi @@ -0,0 +1,15 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color + +class ChartsheetProperties(Serialisable): + tagname: ClassVar[str] + published: Bool[Literal[True]] + codeName: String[Literal[True]] + tabColor: Typed[Color, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, published: _ConvertibleToBool | None = None, codeName: str | None = None, tabColor: Color | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/protection.pyi b/stubs/openpyxl/openpyxl/chartsheet/protection.pyi new file mode 100644 index 000000000000..c109380c2dd2 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/protection.pyi @@ -0,0 +1,27 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.protection import _Protected + +class ChartsheetProtection(Serialisable, _Protected): + tagname: ClassVar[str] + algorithmName: String[Literal[True]] + hashValue: Incomplete + saltValue: Incomplete + spinCount: Integer[Literal[True]] + content: Bool[Literal[True]] + objects: Bool[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + password: Incomplete + def __init__( + self, + content: _ConvertibleToBool | None = None, + objects: _ConvertibleToBool | None = None, + hashValue=None, + spinCount: ConvertibleToInt | None = None, + saltValue=None, + algorithmName: str | None = None, + password=None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/publish.pyi b/stubs/openpyxl/openpyxl/chartsheet/publish.pyi new file mode 100644 index 000000000000..e18f600c6991 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/publish.pyi @@ -0,0 +1,53 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, Set, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WebPublishItemSourceType: TypeAlias = Literal[ + "sheet", "printArea", "autoFilter", "range", "chart", "pivotTable", "query", "label" +] + +class WebPublishItem(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + divId: String[Literal[False]] + sourceType: Set[_WebPublishItemSourceType] + sourceRef: String[Literal[False]] + sourceObject: String[Literal[True]] + destinationFile: String[Literal[False]] + title: String[Literal[True]] + autoRepublish: Bool[Literal[True]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceType: _WebPublishItemSourceType, + sourceRef: str, + sourceObject: str | None = None, + *, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceType: _WebPublishItemSourceType, + sourceRef: str, + sourceObject: str | None, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + +class WebPublishItems(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[True]] + webPublishItem: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt | None = None, webPublishItem=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/relation.pyi b/stubs/openpyxl/openpyxl/chartsheet/relation.pyi new file mode 100644 index 000000000000..d355d7a7b1eb --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/relation.pyi @@ -0,0 +1,71 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Integer +from openpyxl.descriptors.serialisable import Serialisable + +class SheetBackgroundPicture(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... + +class DrawingHF(Serialisable): + id: Incomplete + lho: Integer[Literal[True]] + leftHeaderOddPages: Alias + lhe: Integer[Literal[True]] + leftHeaderEvenPages: Alias + lhf: Integer[Literal[True]] + leftHeaderFirstPage: Alias + cho: Integer[Literal[True]] + centerHeaderOddPages: Alias + che: Integer[Literal[True]] + centerHeaderEvenPages: Alias + chf: Integer[Literal[True]] + centerHeaderFirstPage: Alias + rho: Integer[Literal[True]] + rightHeaderOddPages: Alias + rhe: Integer[Literal[True]] + rightHeaderEvenPages: Alias + rhf: Integer[Literal[True]] + rightHeaderFirstPage: Alias + lfo: Integer[Literal[True]] + leftFooterOddPages: Alias + lfe: Integer[Literal[True]] + leftFooterEvenPages: Alias + lff: Integer[Literal[True]] + leftFooterFirstPage: Alias + cfo: Integer[Literal[True]] + centerFooterOddPages: Alias + cfe: Integer[Literal[True]] + centerFooterEvenPages: Alias + cff: Integer[Literal[True]] + centerFooterFirstPage: Alias + rfo: Integer[Literal[True]] + rightFooterOddPages: Alias + rfe: Integer[Literal[True]] + rightFooterEvenPages: Alias + rff: Integer[Literal[True]] + rightFooterFirstPage: Alias + def __init__( + self, + id=None, + lho: ConvertibleToInt | None = None, + lhe: ConvertibleToInt | None = None, + lhf: ConvertibleToInt | None = None, + cho: ConvertibleToInt | None = None, + che: ConvertibleToInt | None = None, + chf: ConvertibleToInt | None = None, + rho: ConvertibleToInt | None = None, + rhe: ConvertibleToInt | None = None, + rhf: ConvertibleToInt | None = None, + lfo: ConvertibleToInt | None = None, + lfe: ConvertibleToInt | None = None, + lff: ConvertibleToInt | None = None, + cfo: ConvertibleToInt | None = None, + cfe: ConvertibleToInt | None = None, + cff: ConvertibleToInt | None = None, + rfo: ConvertibleToInt | None = None, + rfe: ConvertibleToInt | None = None, + rff: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/chartsheet/views.pyi b/stubs/openpyxl/openpyxl/chartsheet/views.pyi new file mode 100644 index 000000000000..f13138f829b9 --- /dev/null +++ b/stubs/openpyxl/openpyxl/chartsheet/views.pyi @@ -0,0 +1,30 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +class ChartsheetView(Serialisable): + tagname: ClassVar[str] + tabSelected: Bool[Literal[True]] + zoomScale: Integer[Literal[True]] + workbookViewId: Integer[Literal[False]] + zoomToFit: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tabSelected: _ConvertibleToBool | None = None, + zoomScale: ConvertibleToInt | None = None, + workbookViewId: ConvertibleToInt = 0, + zoomToFit: _ConvertibleToBool | None = True, + extLst: Unused = None, + ) -> None: ... + +class ChartsheetViewList(Serialisable): + tagname: ClassVar[str] + sheetView: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetView=None, extLst: Unused = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/__init__.pyi b/stubs/openpyxl/openpyxl/comments/__init__.pyi new file mode 100644 index 000000000000..86ce8fc2d81b --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/__init__.pyi @@ -0,0 +1 @@ +from .comments import Comment as Comment diff --git a/stubs/openpyxl/openpyxl/comments/author.pyi b/stubs/openpyxl/openpyxl/comments/author.pyi new file mode 100644 index 000000000000..ceba5327e302 --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/author.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.base import Alias +from openpyxl.descriptors.serialisable import Serialisable + +class AuthorList(Serialisable): + tagname: ClassVar[str] + author: Incomplete + authors: Alias + def __init__(self, author=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi b/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi new file mode 100644 index 000000000000..f7ea59046e8a --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/comment_sheet.pyi @@ -0,0 +1,124 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Generator +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.cell.text import Text +from openpyxl.comments.author import AuthorList +from openpyxl.comments.comments import Comment +from openpyxl.descriptors.base import Bool, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.ole import ObjectAnchor +from openpyxl.xml.functions import Element + +_PropertiesTextHAlign: TypeAlias = Literal["left", "center", "right", "justify", "distributed"] +_PropertiesTextVAlign: TypeAlias = Literal["top", "center", "bottom", "justify", "distributed"] + +class Properties(Serialisable): + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + altText: String[Literal[True]] + textHAlign: Set[_PropertiesTextHAlign] + textVAlign: Set[_PropertiesTextVAlign] + lockText: Bool[Literal[True]] + justLastX: Bool[Literal[True]] + autoScale: Bool[Literal[True]] + rowHidden: Bool[Literal[True]] + colHidden: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + anchor: ObjectAnchor | None + + @overload + def __init__( + self, + locked: _ConvertibleToBool | None = None, + defaultSize: _ConvertibleToBool | None = None, + _print: _ConvertibleToBool | None = None, + disabled: _ConvertibleToBool | None = None, + uiObject: _ConvertibleToBool | None = None, + autoFill: _ConvertibleToBool | None = None, + autoLine: _ConvertibleToBool | None = None, + altText: str | None = None, + *, + textHAlign: _PropertiesTextHAlign, + textVAlign: _PropertiesTextVAlign, + lockText: _ConvertibleToBool | None = None, + justLastX: _ConvertibleToBool | None = None, + autoScale: _ConvertibleToBool | None = None, + rowHidden: _ConvertibleToBool | None = None, + colHidden: _ConvertibleToBool | None = None, + anchor: ObjectAnchor | None = None, + ) -> None: ... + @overload + def __init__( + self, + locked: _ConvertibleToBool | None, + defaultSize: _ConvertibleToBool | None, + _print: _ConvertibleToBool | None, + disabled: _ConvertibleToBool | None, + uiObject: _ConvertibleToBool | None, + autoFill: _ConvertibleToBool | None, + autoLine: _ConvertibleToBool | None, + altText: str | None, + textHAlign: _PropertiesTextHAlign, + textVAlign: _PropertiesTextVAlign, + lockText: _ConvertibleToBool | None = None, + justLastX: _ConvertibleToBool | None = None, + autoScale: _ConvertibleToBool | None = None, + rowHidden: _ConvertibleToBool | None = None, + colHidden: _ConvertibleToBool | None = None, + anchor: ObjectAnchor | None = None, + ) -> None: ... + +class CommentRecord(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + authorId: Integer[Literal[False]] + guid: Incomplete + shapeId: Integer[Literal[True]] + text: Typed[Text, Literal[False]] + commentPr: Typed[Properties, Literal[True]] + author: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + height: Incomplete + width: Incomplete + def __init__( + self, + ref: str = "", + authorId: ConvertibleToInt = 0, + guid=None, + shapeId: ConvertibleToInt | None = 0, + text: Text | None = None, + commentPr: Properties | None = None, + author: str | None = None, + height: int = 79, + width: int = 144, + ) -> None: ... + @classmethod + def from_cell(cls, cell: _CellOrMergedCell): ... + @property + def content(self) -> str: ... + +class CommentSheet(Serialisable): + tagname: ClassVar[str] + authors: Typed[AuthorList, Literal[False]] + commentList: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + mime_type: str + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, authors: AuthorList, commentList=None, extLst: Unused = None) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def comments(self) -> Generator[tuple[str, Comment]]: ... + @classmethod + def from_comments(cls, comments): ... + def write_shapes(self, vml=None): ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/comments/comments.pyi b/stubs/openpyxl/openpyxl/comments/comments.pyi new file mode 100644 index 000000000000..a4966493d9ed --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/comments.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import Any + +class Comment: + content: Incomplete + author: Incomplete + height: Incomplete + width: Incomplete + def __init__(self, text, author, height: int = 79, width: int = 144) -> None: ... + @property + def parent(self) -> Any: ... # AnyOf[Cell, MergedCell, ReadOnlyCell] + def __eq__(self, other: Comment) -> bool: ... # type: ignore[override] + def __copy__(self): ... + def bind(self, cell) -> None: ... + def unbind(self) -> None: ... + + @property + def text(self) -> str: ... + @text.setter + def text(self, value: str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/comments/shape_writer.pyi b/stubs/openpyxl/openpyxl/comments/shape_writer.pyi new file mode 100644 index 000000000000..b908498d47a5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/comments/shape_writer.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import Any, TypeAlias + +from ..xml._functions_overloads import _lxml_Element, _ParentElement + +_RootElement: TypeAlias = _ParentElement[Any] | _lxml_Element + +vmlns: str +officens: str +excelns: str + +class ShapeWriter: + vml: Incomplete + vml_path: Incomplete + comments: Incomplete + def __init__(self, comments) -> None: ... + def add_comment_shapetype(self, root: _RootElement) -> None: ... + def add_comment_shape(self, root: _RootElement, idx, coord, height, width) -> None: ... + # Any object missing "findall" is replaced by an Element + def write(self, root: _RootElement | None) -> str: ... diff --git a/stubs/openpyxl/openpyxl/compat/__init__.pyi b/stubs/openpyxl/openpyxl/compat/__init__.pyi new file mode 100644 index 000000000000..5c4b7cd1e711 --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/__init__.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from .numbers import NUMERIC_TYPES as NUMERIC_TYPES +from .strings import safe_string as safe_string + +class DummyCode: ... + +string_types: Incomplete + +def deprecated(reason): ... diff --git a/stubs/openpyxl/openpyxl/compat/abc.pyi b/stubs/openpyxl/openpyxl/compat/abc.pyi new file mode 100644 index 000000000000..5beda934a5fc --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/abc.pyi @@ -0,0 +1 @@ +from abc import ABC as ABC diff --git a/stubs/openpyxl/openpyxl/compat/numbers.pyi b/stubs/openpyxl/openpyxl/compat/numbers.pyi new file mode 100644 index 000000000000..060ba461585a --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/numbers.pyi @@ -0,0 +1,13 @@ +from decimal import Decimal +from typing import Final, TypeAlias + +# NOTE: Can't specify numpy as a dependency because openpyxl doesn't declare it as one +# import numpy +# import numpy._typing +# _NBitBase: TypeAlias = numpy._typing.NBitBase +# _NumericTypes: TypeAlias = int | float | Decimal | numpy.bool_ | numpy.floating[_NBitBase] | numpy.integer[_NBitBase] + +_NumericTypes: TypeAlias = int | float | Decimal +NUMERIC_TYPES: Final[tuple[type[_NumericTypes], ...]] + +NUMPY: Final[bool] diff --git a/stubs/openpyxl/openpyxl/compat/product.pyi b/stubs/openpyxl/openpyxl/compat/product.pyi new file mode 100644 index 000000000000..60e7b2989a5c --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/product.pyi @@ -0,0 +1,3 @@ +def product(sequence): ... + +prod = product diff --git a/stubs/openpyxl/openpyxl/compat/singleton.pyi b/stubs/openpyxl/openpyxl/compat/singleton.pyi new file mode 100644 index 000000000000..65749ec98e3a --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/singleton.pyi @@ -0,0 +1,17 @@ +from typing import Any, overload + +class Singleton(type): + @overload + def __init__(self, o: object, /) -> None: ... + @overload + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + + def __call__(self, *args: Any, **kwds: Any) -> Any: ... + +class Cached(type): + @overload + def __init__(self, o: object, /) -> None: ... + @overload + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + + def __call__(self, *args: Any) -> Any: ... diff --git a/stubs/openpyxl/openpyxl/compat/strings.pyi b/stubs/openpyxl/openpyxl/compat/strings.pyi new file mode 100644 index 000000000000..7d21aa72e2a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/compat/strings.pyi @@ -0,0 +1,6 @@ +import sys +from typing import Final + +VER: Final[sys._version_info] + +def safe_string(value: object) -> str: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/__init__.pyi b/stubs/openpyxl/openpyxl/descriptors/__init__.pyi new file mode 100644 index 000000000000..18097e820254 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/__init__.pyi @@ -0,0 +1,12 @@ +from _typeshed import Incomplete, Self + +from .base import * +from .sequence import Sequence as Sequence + +class MetaStrict(type): + def __new__(cls: type[Self], clsname: str, bases: tuple[type, ...], methods: dict[str, Descriptor[Incomplete]]) -> Self: ... + +class MetaSerialisable(type): + def __new__(cls: type[Self], clsname: str, bases: tuple[type, ...], methods: dict[str, Descriptor[Incomplete]]) -> Self: ... + +class Strict(metaclass=MetaStrict): ... diff --git a/stubs/openpyxl/openpyxl/descriptors/base.pyi b/stubs/openpyxl/openpyxl/descriptors/base.pyi new file mode 100644 index 000000000000..5636a3b25226 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/base.pyi @@ -0,0 +1,370 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, ReadableBuffer, Unused +from collections.abc import Iterable, Sized +from datetime import datetime +from re import Pattern +from typing import Any, Generic, Literal, TypeAlias, TypeVar, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import Blip +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange + +_T = TypeVar("_T") +_P = TypeVar("_P", str, ReadableBuffer) +_N = TypeVar("_N", bound=bool, default=Literal[False]) +_L = TypeVar("_L", bound=Sized) +_M = TypeVar("_M", int, float) + +_ExpectedTypeParam: TypeAlias = type[_T] | tuple[type[_T], ...] +_ConvertibleToMultiCellRange: TypeAlias = MultiCellRange | str | Iterable[CellRange] +# Since everything is convertible to a bool, this restricts to only intended expected types of intended literals +_ConvertibleToBool: TypeAlias = bool | str | int | None # True | False | "true" | "t" | "false" | "f" | 1 | 0 | None + +class Descriptor(Generic[_T]): + name: str | None + def __init__(self, name: str | None = None, **kw: object) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: type | None) -> _T: ... + def __set__(self, instance: Serialisable | Strict, value: _T) -> None: ... + +class Typed(Descriptor[_T], Generic[_T, _N]): + __doc__: str + # Members optional in __init__ + expected_type: type[_T] + allow_none: _N + nested: bool + + @overload + def __init__( + self: Typed[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + nested: bool = False, + ) -> None: ... + @overload + def __init__( + self: Typed[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + nested: bool = False, + ) -> None: ... + + @overload + def __get__(self: Typed[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: Typed[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + @overload + def __set__(self: Typed[_T, Literal[True]], instance: Serialisable | Strict, value: _T | None) -> None: ... + @overload + def __set__(self: Typed[_T, Literal[False]], instance: Serialisable | Strict, value: _T) -> None: ... + +class Convertible(Typed[_T, _N]): + @overload + def __init__( + self: Convertible[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: Convertible[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # MultiCellRange + @overload + def __set__( + self: Convertible[MultiCellRange, Literal[True]], + instance: Serialisable | Strict, + value: _ConvertibleToMultiCellRange | None, + ) -> None: ... + @overload + def __set__( + self: Convertible[MultiCellRange, Literal[False]], instance: Serialisable | Strict, value: _ConvertibleToMultiCellRange + ) -> None: ... + # str | Blip + @overload + def __set__( + self: Convertible[str, _N] | Convertible[Blip, _N], + instance: Serialisable | Strict, + value: object, # Not[None] when _N = False + ) -> None: ... + # bool + @overload + def __set__(self: Convertible[bool, _N], instance: Serialisable | Strict, value: _ConvertibleToBool) -> None: ... + # int + @overload + def __set__( + self: Convertible[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None + ) -> None: ... + @overload + def __set__(self: Convertible[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + # float + @overload + def __set__( + self: Convertible[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None + ) -> None: ... + @overload + def __set__(self: Convertible[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + # Anything else + @overload + def __set__(self: Convertible[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... + +class Max(Convertible[_M, _N]): + expected_type: type[_M] + allow_none: _N + max: float + + @overload + def __init__( + self: Max[int, Literal[True]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[True], max: float + ) -> None: ... + @overload + def __init__( + self: Max[int, Literal[False]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[False] = False, max: float + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: Max[float, Literal[True]], *, expected_type: _ExpectedTypeParam[float] = ..., allow_none: Literal[True], max: float + ) -> None: ... + @overload + def __init__( + self: Max[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + max: float, + ) -> None: ... + + @overload # type: ignore[override] # Different restrictions + def __set__(self: Max[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None) -> None: ... + @overload + def __set__(self: Max[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + @overload + def __set__(self: Max[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None) -> None: ... + @overload + def __set__(self: Max[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + +class Min(Convertible[_M, _N]): + expected_type: type[_M] + allow_none: _N + min: float + + @overload + def __init__( + self: Min[int, Literal[True]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[True], min: float + ) -> None: ... + @overload + def __init__( + self: Min[int, Literal[False]], *, expected_type: _ExpectedTypeParam[int], allow_none: Literal[False] = False, min: float + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: Min[float, Literal[True]], *, expected_type: _ExpectedTypeParam[float] = ..., allow_none: Literal[True], min: float + ) -> None: ... + @overload + def __init__( + self: Min[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + ) -> None: ... + + @overload # type: ignore[override] # Different restrictions + def __set__(self: Min[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None) -> None: ... + @overload + def __set__(self: Min[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + @overload + def __set__(self: Min[float, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToFloat | None) -> None: ... + @overload + def __set__(self: Min[float, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToFloat) -> None: ... + +class MinMax(Min[_M, _N], Max[_M, _N]): + expected_type: type[_M] + allow_none: _N + + @overload + def __init__( + self: MinMax[int, Literal[True]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: MinMax[int, Literal[False]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: MinMax[float, Literal[True]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: MinMax[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + +class Set(Descriptor[_T]): + __doc__: str + values: Iterable[_T] + def __init__(self, name: str | None = None, *, values: Iterable[_T]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _T) -> None: ... + +class NoneSet(Set[_T | None]): + def __init__(self, name: str | None = None, *, values: Iterable[_T | None]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _T | Literal["none"] | None) -> None: ... + +class Integer(Convertible[int, _N]): + allow_none: _N + expected_type: type[int] + + @overload + def __init__(self: Integer[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Integer[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Float(Convertible[float, _N]): + allow_none: _N + expected_type: type[float] + + @overload + def __init__(self: Float[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Float[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Bool(Convertible[bool, _N]): + expected_type: type[bool] + allow_none: _N + + @overload + def __init__(self: Bool[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: Bool[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + def __set__(self, instance: Serialisable | Strict, value: _ConvertibleToBool) -> None: ... + +class String(Typed[str, _N]): + allow_none: _N + expected_type: type[str] + + @overload + def __init__(self: String[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: String[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class Text(String[_N], Convertible[str, _N]): ... # unused + +class ASCII(Typed[bytes, _N]): # unused + expected_type: type[bytes] + def __init__(self, name: str | None = None, *, allow_none: bool = False) -> None: ... + +class Tuple(Typed[tuple[Any, ...], _N]): # unused + expected_type: type[tuple[Any, ...]] + def __init__(self, name: str | None = None, *, allow_none: bool = False) -> None: ... + +class Length(Descriptor[_L]): + def __init__(self, name: Unused = None, *, length: int) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _L) -> None: ... + +class Default(Typed[_T, _N]): # unused + def __init__( + self, name: Unused = None, *, expected_type: _ExpectedTypeParam[_T], allow_none: bool = False, defaults: Unused = {} + ) -> None: ... + def __call__(self) -> _T: ... + +# Note: Aliases types can't be inferred. Anyway an alias means there's another option. +# Incomplete: Make it generic with explicit getter/setter type arguments? +class Alias(Descriptor[Incomplete]): + alias: str + def __init__(self, alias: str) -> None: ... + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: Unused): ... + +class MatchPattern(Descriptor[_P], Generic[_P, _N]): + allow_none: _N + test_pattern: Pattern[bytes] | Pattern[str] + pattern: str | Pattern[str] | bytes | Pattern[bytes] + + @overload # str + def __init__( + self: MatchPattern[str, Literal[True]], name: str | None = None, *, pattern: str | Pattern[str], allow_none: Literal[True] + ) -> None: ... + @overload # str | None + def __init__( + self: MatchPattern[str, Literal[False]], + name: str | None = None, + *, + pattern: str | Pattern[str], + allow_none: Literal[False] = False, + ) -> None: ... + @overload # bytes + def __init__( + self: MatchPattern[ReadableBuffer, Literal[True]], + name: str | None = None, + *, + pattern: bytes | Pattern[bytes], + allow_none: Literal[True], + ) -> None: ... + @overload # bytes | None + def __init__( + self: MatchPattern[ReadableBuffer, Literal[False]], + name: str | None = None, + *, + pattern: bytes | Pattern[bytes], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: MatchPattern[_P, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _P | None: ... + @overload + def __get__(self: MatchPattern[_P, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _P: ... + + @overload + def __set__(self: MatchPattern[_P, Literal[True]], instance: Serialisable | Strict, value: _P | None) -> None: ... + @overload + def __set__(self: MatchPattern[_P, Literal[False]], instance: Serialisable | Strict, value: _P) -> None: ... + +class DateTime(Typed[datetime, _N]): + allow_none: _N + expected_type: type[datetime] + + @overload + def __init__(self: DateTime[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: DateTime[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __set__(self: DateTime[Literal[True]], instance: Serialisable | Strict, value: datetime | str | None) -> None: ... + @overload + def __set__(self: DateTime[Literal[False]], instance: Serialisable | Strict, value: datetime | str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/container.pyi b/stubs/openpyxl/openpyxl/descriptors/container.pyi new file mode 100644 index 000000000000..52106f1e6a08 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/container.pyi @@ -0,0 +1,18 @@ +from typing import TypeVar +from typing_extensions import Self + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +_T = TypeVar("_T", bound=Serialisable) + +# Abstract base class. +class ElementList(list[_T]): + @property + def tagname(self) -> str: ... # abstract + @property + def expected_type(self) -> type[_T]: ... # abstract + @classmethod + def from_tree(cls, tree: Element) -> Self: ... + def to_tree(self) -> Element: ... + def append(self, value: _T) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/excel.pyi b/stubs/openpyxl/openpyxl/descriptors/excel.pyi new file mode 100644 index 000000000000..eabbdcfafe6f --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/excel.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from . import Integer, MatchPattern, MinMax, Strict, String +from .base import _M, _N +from .serialisable import Serialisable + +class HexBinary(MatchPattern[str, Incomplete]): + pattern: str + +class UniversalMeasure(MatchPattern[str, Incomplete]): + pattern: str + +class TextPoint(MinMax[_M, _N]): + expected_type: type[_M] + min: float + max: float + +Coordinate = Integer + +class Percentage(MinMax[float, Incomplete]): + pattern: str + min: float + max: float + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class Extension(Serialisable): + uri: String[Literal[False]] + def __init__(self, uri: str) -> None: ... + +class ExtensionList(Serialisable): + ext: Incomplete + def __init__(self, ext=()) -> None: ... + +class Relation(String[Incomplete]): + namespace: ClassVar[str] + allow_none: bool + +class Base64Binary(MatchPattern[str, Incomplete]): + pattern: str + +class Guid(MatchPattern[str, Incomplete]): + pattern: str + +class CellRange(MatchPattern[str, Incomplete]): + pattern: str + allow_none: bool + def __set__(self, instance: Serialisable | Strict, value) -> None: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/namespace.pyi b/stubs/openpyxl/openpyxl/descriptors/namespace.pyi new file mode 100644 index 000000000000..edb18560d8fa --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/namespace.pyi @@ -0,0 +1,2 @@ +# 'None' shouldn't be a valid tagname and namespaced should always return str +def namespaced(obj: object, tagname: str, namespace: str | None = None) -> str: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/nested.pyi b/stubs/openpyxl/openpyxl/descriptors/nested.pyi new file mode 100644 index 000000000000..4a785b94720f --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/nested.pyi @@ -0,0 +1,289 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from collections.abc import Iterable +from typing import Any, ClassVar, Literal, TypeAlias, overload +from typing_extensions import Never + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Bool, Convertible, Descriptor, Float, Integer, MinMax, NoneSet, Set, String +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import Blip +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasGet, _HasTagAndGet, _HasText +from .base import _M, _N, _T, _ConvertibleToBool, _ExpectedTypeParam + +_NestedNoneSetParam: TypeAlias = _HasTagAndGet[_T | Literal["none"] | None] | _T | Literal["none"] | None + +# NOTE: type: ignore[misc]: Class does not reimplement the relevant methods, so runtime also has incompatible supertypes + +class Nested(Descriptor[_T]): + nested: ClassVar[Literal[True]] + attribute: ClassVar[str] + # Members optional in __init__ + expected_type: type[_T] + allow_none: bool + namespace: str | None + # In usage, "Nested" is closed to "Typed" than "Descriptor", but doesn't use allow_none + def __init__( + self: Nested[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: bool = False, + nested: Unused = True, + namespace: str | None = None, + ) -> None: ... + def __get__(self, instance: Serialisable | Strict, cls: type | None) -> _T: ... + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_T] | _T) -> None: ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... + +class NestedValue(Nested[_T], Convertible[_T, _N]): # type: ignore[misc] + @overload + def __init__( + self: NestedValue[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: NestedValue[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: NestedValue[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: NestedValue[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # str | Blip + @overload + def __set__( + self: NestedValue[str, _N] | NestedValue[Blip, _N], + instance: Serialisable | Strict, + value: object, # Not[None] when _N = False + ) -> None: ... + # bool + @overload + def __set__( + self: NestedValue[bool, _N], + instance: Serialisable | Strict, + value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool, + ) -> None: ... + # int + @overload + def __set__( + self: NestedValue[int, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + ) -> None: ... + @overload + def __set__( + self: NestedValue[int, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + ) -> None: ... + # float + @overload + def __set__( + self: NestedValue[float, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + ) -> None: ... + @overload + def __set__( + self: NestedValue[float, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat, + ) -> None: ... + # Anything else + @overload + def __set__( + self: NestedValue[_T, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[_T | int | Any] | _T | int | Any | None, + ) -> None: ... + +class NestedText(NestedValue[_T, _N]): + @overload + def __init__( + self: NestedText[_T, Literal[True]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[True], + ) -> None: ... + @overload + def __init__( + self: NestedText[_T, Literal[False]], # pyright: ignore[reportInvalidTypeVarUse] #11780 + name: str | None = None, + *, + expected_type: _ExpectedTypeParam[_T], + allow_none: Literal[False] = False, + ) -> None: ... + + @overload + def __get__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _T | None: ... + @overload + def __get__(self: NestedText[_T, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _T: ... + + # NOTE: It is currently impossible to make a generic based on the parameter type of another generic + # So we implement explicitly the types used internally + # str + @overload + def __set__( # type: ignore[overload-overlap] + self: NestedText[str, _N], instance: Serialisable | Strict, value: object # Not[None] when _N = False + ) -> None: ... + # int + @overload + def __set__( + self: NestedText[int, Literal[True]], instance: Serialisable | Strict, value: ConvertibleToInt | None + ) -> None: ... + @overload + def __set__(self: NestedText[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... + # If expected type (_T) is not str, it's impossible to use an Element as the value + @overload + def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _HasTagAndGet[Any]) -> Never: ... + # Anything else + @overload + def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... + + def from_tree(self, node: _HasText) -> str: ... # type: ignore[override] + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... + +class NestedFloat(NestedValue[float, _N], Float[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedFloat[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedFloat[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedInteger(NestedValue[int, _N], Integer[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedInteger[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedInteger[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedString(NestedValue[str, _N], String[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedString[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedString[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + +class NestedBool(NestedValue[bool, _N], Bool[_N]): # type: ignore[misc] + @overload + def __init__(self: NestedBool[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: NestedBool[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool) -> None: ... + def from_tree(self, node: _HasGet[bool]) -> bool: ... + +class NestedNoneSet(Nested[_T | None], NoneSet[_T]): + def __init__(self, name: str | None = None, *, values: Iterable[_T | None]) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: _NestedNoneSetParam[_T]) -> None: ... + +class NestedSet(Nested[_T], Set[_T]): + def __init__(self, name: str | None = None, *, values: Iterable[_T]) -> None: ... + +class NestedMinMax(Nested[_M], MinMax[_M, _N]): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + @overload + def __init__( + self: NestedMinMax[int, Literal[True]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: NestedMinMax[int, Literal[False]], + *, + expected_type: _ExpectedTypeParam[int], + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + # mypy can't infer type from `expected_type = float` (pyright can), so we have to add extra overloads + @overload + def __init__( + self: NestedMinMax[float, Literal[True]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[True], + min: float, + max: float, + ) -> None: ... + @overload + def __init__( + self: NestedMinMax[float, Literal[False]], + *, + expected_type: _ExpectedTypeParam[float] = ..., + allow_none: Literal[False] = False, + min: float, + max: float, + ) -> None: ... + + @overload + def __get__(self: NestedMinMax[_M, Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> _M | None: ... + @overload + def __get__(self: NestedMinMax[_M, Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> _M: ... + + @overload # type: ignore[override] # Different restrictions + def __set__( + self: NestedMinMax[int, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[int, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[float, Literal[True]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None, + ) -> None: ... + @overload + def __set__( + self: NestedMinMax[float, Literal[False]], + instance: Serialisable | Strict, + value: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat, + ) -> None: ... + +class EmptyTag(Nested[bool], Bool[_N]): # type: ignore[misc] # pyrefly: ignore [inconsistent-inheritance] + @overload + def __init__(self: EmptyTag[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: EmptyTag[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __get__(self: EmptyTag[Literal[True]], instance: Serialisable | Strict, cls: type | None = None) -> bool | None: ... + @overload + def __get__(self: EmptyTag[Literal[False]], instance: Serialisable | Strict, cls: type | None = None) -> bool: ... + + def __set__(self, instance: Serialisable | Strict, value: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool) -> None: ... + def from_tree(self, node: Unused) -> Literal[True]: ... + + @overload + def to_tree(self, tagname: Unused = None, value: None = None, namespace: Unused = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: object, namespace: str | None = None) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/sequence.pyi b/stubs/openpyxl/openpyxl/descriptors/sequence.pyi new file mode 100644 index 000000000000..01e44ca1a375 --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/sequence.pyi @@ -0,0 +1,76 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator, Iterable, Sized +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.serialisable import Serialisable, _SerialisableTreeElement +from openpyxl.xml._functions_overloads import _HasGet +from openpyxl.xml.functions import Element + +from .base import Alias, Descriptor + +_T = TypeVar("_T") +_ContainerT = TypeVar("_ContainerT") + +@type_check_only +class _SupportsFromTree(Protocol): + @classmethod + def from_tree(cls, node: _SerialisableTreeElement) -> Any: ... + +@type_check_only +class _SupportsToTree(Protocol): + def to_tree(self) -> Element: ... + +# `_ContainerT` is the internal container type (which defaults to `list`), or +# `IndexedList` if unique is `True`. +class Sequence(Descriptor[_ContainerT]): + expected_type: type[Any] # expected type of the sequence elements + seq_types: tuple[type, ...] # allowed settable sequence types, defaults to `list`, `tuple` + idx_base: int + unique: bool + container: type # internal container type, defaults to `list` + # seq must be an instance of any of the declared `seq_types`. + def __set__(self, instance: Serialisable | Strict, seq: Any) -> None: ... + def to_tree(self, tagname: str | None, obj: Iterable[object], namespace: str | None = None) -> Generator[Element]: ... + +# `_T` is the type of the elements in the sequence. +class UniqueSequence(Sequence[set[_T]]): + seq_types: tuple[type, ...] # defaults to `list`, `tuple`, `set` + container: type[set[_T]] + +# See `Sequence` for the meaning of `_ContainerT`. +class ValueSequence(Sequence[_ContainerT]): + attribute: str + def to_tree( + self, tagname: str, obj: Iterable[object], namespace: str | None = None # type: ignore[override] + ) -> Generator[Element]: ... + def from_tree(self, node: _HasGet[_T]) -> _T: ... + +@type_check_only +class _NestedSequenceToTreeObj(Sized, Iterable[_SupportsToTree], Protocol): ... + +# See `Sequence` for the meaning of `_ContainerT`. +class NestedSequence(Sequence[_ContainerT]): + count: bool + expected_type: type[_SupportsFromTree] + def to_tree( # type: ignore[override] + self, tagname: str, obj: _NestedSequenceToTreeObj, namespace: str | None = None + ) -> Element: ... + # returned list generic type should be same as the return type of expected_type.from_tree(node) + # Which can really be anything given the wildly different, and sometimes generic, from_tree return types + def from_tree(self, node: Iterable[_SerialisableTreeElement]) -> list[Any]: ... + +# `_T` is the type of the elements in the sequence. +class MultiSequence(Sequence[list[_T]]): + def __set__(self, instance: Serialisable | Strict, seq: tuple[_T, ...] | list[_T]) -> None: ... + def to_tree( + self, tagname: Unused, obj: Iterable[_SupportsToTree], namespace: str | None = None # type: ignore[override] + ) -> Generator[Element]: ... + +class MultiSequencePart(Alias): + expected_type: type[Incomplete] + store: Incomplete + def __init__(self, expected_type, store) -> None: ... + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + def __get__(self, instance: Unused, cls: Unused) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi b/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi new file mode 100644 index 000000000000..4ea4e6bae42b --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi @@ -0,0 +1,54 @@ +from _typeshed import ConvertibleToInt, Incomplete, SupportsIter +from collections.abc import Iterator +from typing import Any, ClassVar, Final, Protocol, type_check_only +from typing_extensions import Self + +from openpyxl.descriptors import MetaSerialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasAttrib, _HasGet, _HasTagAndGet, _HasText, _SupportsFindChartLines + +# For any override directly re-using Serialisable.from_tree +@type_check_only +class _ChildSerialisableTreeElement(_HasAttrib, _HasText, SupportsIter[Incomplete], Protocol): ... + +@type_check_only +class _SerialisableTreeElement(_HasGet[object], _SupportsFindChartLines, _ChildSerialisableTreeElement, Protocol): ... + +KEYWORDS: Final[frozenset[str]] +seq_types: Final[tuple[type[list[Any]], type[tuple[Any, ...]]]] + +class Serialisable(metaclass=MetaSerialisable): + # These dunders are always set at runtime by MetaSerialisable so they can't be None + __attrs__: ClassVar[tuple[str, ...]] + __nested__: ClassVar[tuple[str, ...]] + __elements__: ClassVar[tuple[str, ...]] + __namespaced__: ClassVar[tuple[tuple[str, str], ...]] + idx_base: int + # Needs overrides in many sub-classes. But a lot of subclasses are instantiated without overriding it, so can't be abstract + # Subclasses "overrides" this property with a ClassVar, and Serialisable is too widely used, + # so it can't be typed as Never either without introducing many false-positives. + @property + def tagname(self) -> str: ... + namespace: ClassVar[str | None] + # Note: To respect the Liskov substitution principle, the protocol for node includes all child class requirements. + # Same with the return type to avoid override issues. + # See comment in xml/functions.pyi as to why use a protocol instead of Element + # Child classes should be more precise than _SerialisableTreeElement ! + # Use _ChildSerialisableTreeElement instead for child classes that reuse Serialisable.from_tree directly. + @classmethod + def from_tree(cls, node: _SerialisableTreeElement) -> Self | None: ... + # Note: To respect the Liskov substitution principle, idx is a type union of all child class requirements. + # Use Unused instead for child classes that reuse Serialisable.to_tree directly. + def to_tree( + self, + tagname: str | None = None, + idx: _HasTagAndGet[ConvertibleToInt] | ConvertibleToInt | None = None, + namespace: str | None = None, + ) -> Element: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __add__(self, other): ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/descriptors/slots.pyi b/stubs/openpyxl/openpyxl/descriptors/slots.pyi new file mode 100644 index 000000000000..f74e59307e6e --- /dev/null +++ b/stubs/openpyxl/openpyxl/descriptors/slots.pyi @@ -0,0 +1,4 @@ +from _typeshed import Incomplete, Self + +class AutoSlotProperties(type): + def __new__(mcl: type[Self], classname: str, bases: tuple[type, ...], dictionary: dict[str, Incomplete]) -> Self: ... diff --git a/stubs/openpyxl/openpyxl/drawing/__init__.pyi b/stubs/openpyxl/openpyxl/drawing/__init__.pyi new file mode 100644 index 000000000000..a41cad04e6d8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/__init__.pyi @@ -0,0 +1 @@ +from .drawing import Drawing as Drawing diff --git a/stubs/openpyxl/openpyxl/drawing/colors.pyi b/stubs/openpyxl/openpyxl/drawing/colors.pyi new file mode 100644 index 000000000000..872589fbb8dc --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/colors.pyi @@ -0,0 +1,510 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Final, Literal, TypeAlias, overload + +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import Alias, Integer, MinMax, Set, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedInteger, NestedNoneSet, NestedValue, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _HasTagAndGet + +_ColorSetType: TypeAlias = Literal[ + "dk1", "lt1", "dk2", "lt2", "accent1", "accent2", "accent3", "accent4", "accent5", "accent6", "hlink", "folHlink" +] +_SystemColorVal: TypeAlias = Literal[ + "scrollBar", + "background", + "activeCaption", + "inactiveCaption", + "menu", + "window", + "windowFrame", + "menuText", + "windowText", + "captionText", + "activeBorder", + "inactiveBorder", + "appWorkspace", + "highlight", + "highlightText", + "btnFace", + "btnShadow", + "grayText", + "btnText", + "inactiveCaptionText", + "btnHighlight", + "3dDkShadow", + "3dLight", + "infoText", + "infoBk", + "hotLight", + "gradientActiveCaption", + "gradientInactiveCaption", + "menuHighlight", + "menuBar", +] +_SchemeColors: TypeAlias = Literal[ + "bg1", + "tx1", + "bg2", + "tx2", + "accent1", + "accent2", + "accent3", + "accent4", + "accent5", + "accent6", + "hlink", + "folHlink", + "phClr", + "dk1", + "lt1", + "dk2", + "lt2", +] +_PresetColors: TypeAlias = Literal[ + "aliceBlue", + "antiqueWhite", + "aqua", + "aquamarine", + "azure", + "beige", + "bisque", + "black", + "blanchedAlmond", + "blue", + "blueViolet", + "brown", + "burlyWood", + "cadetBlue", + "chartreuse", + "chocolate", + "coral", + "cornflowerBlue", + "cornsilk", + "crimson", + "cyan", + "darkBlue", + "darkCyan", + "darkGoldenrod", + "darkGray", + "darkGrey", + "darkGreen", + "darkKhaki", + "darkMagenta", + "darkOliveGreen", + "darkOrange", + "darkOrchid", + "darkRed", + "darkSalmon", + "darkSeaGreen", + "darkSlateBlue", + "darkSlateGray", + "darkSlateGrey", + "darkTurquoise", + "darkViolet", + "dkBlue", + "dkCyan", + "dkGoldenrod", + "dkGray", + "dkGrey", + "dkGreen", + "dkKhaki", + "dkMagenta", + "dkOliveGreen", + "dkOrange", + "dkOrchid", + "dkRed", + "dkSalmon", + "dkSeaGreen", + "dkSlateBlue", + "dkSlateGray", + "dkSlateGrey", + "dkTurquoise", + "dkViolet", + "deepPink", + "deepSkyBlue", + "dimGray", + "dimGrey", + "dodgerBlue", + "firebrick", + "floralWhite", + "forestGreen", + "fuchsia", + "gainsboro", + "ghostWhite", + "gold", + "goldenrod", + "gray", + "grey", + "green", + "greenYellow", + "honeydew", + "hotPink", + "indianRed", + "indigo", + "ivory", + "khaki", + "lavender", + "lavenderBlush", + "lawnGreen", + "lemonChiffon", + "lightBlue", + "lightCoral", + "lightCyan", + "lightGoldenrodYellow", + "lightGray", + "lightGrey", + "lightGreen", + "lightPink", + "lightSalmon", + "lightSeaGreen", + "lightSkyBlue", + "lightSlateGray", + "lightSlateGrey", + "lightSteelBlue", + "lightYellow", + "ltBlue", + "ltCoral", + "ltCyan", + "ltGoldenrodYellow", + "ltGray", + "ltGrey", + "ltGreen", + "ltPink", + "ltSalmon", + "ltSeaGreen", + "ltSkyBlue", + "ltSlateGray", + "ltSlateGrey", + "ltSteelBlue", + "ltYellow", + "lime", + "limeGreen", + "linen", + "magenta", + "maroon", + "medAquamarine", + "medBlue", + "medOrchid", + "medPurple", + "medSeaGreen", + "medSlateBlue", + "medSpringGreen", + "medTurquoise", + "medVioletRed", + "mediumAquamarine", + "mediumBlue", + "mediumOrchid", + "mediumPurple", + "mediumSeaGreen", + "mediumSlateBlue", + "mediumSpringGreen", + "mediumTurquoise", + "mediumVioletRed", + "midnightBlue", + "mintCream", + "mistyRose", + "moccasin", + "navajoWhite", + "navy", + "oldLace", + "olive", + "oliveDrab", + "orange", + "orangeRed", + "orchid", + "paleGoldenrod", + "paleGreen", + "paleTurquoise", + "paleVioletRed", + "papayaWhip", + "peachPuff", + "peru", + "pink", + "plum", + "powderBlue", + "purple", + "red", + "rosyBrown", + "royalBlue", + "saddleBrown", + "salmon", + "sandyBrown", + "seaGreen", + "seaShell", + "sienna", + "silver", + "skyBlue", + "slateBlue", + "slateGray", + "slateGrey", + "snow", + "springGreen", + "steelBlue", + "tan", + "teal", + "thistle", + "tomato", + "turquoise", + "violet", + "wheat", + "white", + "whiteSmoke", + "yellow", + "yellowGreen", +] + +PRESET_COLORS: Final[list[_PresetColors]] +SCHEME_COLORS: Final[list[_SchemeColors]] + +class Transform(Serialisable): ... + +class SystemColor(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + tint: NestedInteger[Literal[True]] + shade: NestedInteger[Literal[True]] + comp: Typed[Transform, Literal[True]] + inv: Typed[Transform, Literal[True]] + gray: Typed[Transform, Literal[True]] + alpha: NestedInteger[Literal[True]] + alphaOff: NestedInteger[Literal[True]] + alphaMod: NestedInteger[Literal[True]] + hue: NestedInteger[Literal[True]] + hueOff: NestedInteger[Literal[True]] + hueMod: NestedInteger[Literal[True]] + sat: NestedInteger[Literal[True]] + satOff: NestedInteger[Literal[True]] + satMod: NestedInteger[Literal[True]] + lum: NestedInteger[Literal[True]] + lumOff: NestedInteger[Literal[True]] + lumMod: NestedInteger[Literal[True]] + red: NestedInteger[Literal[True]] + redOff: NestedInteger[Literal[True]] + redMod: NestedInteger[Literal[True]] + green: NestedInteger[Literal[True]] + greenOff: NestedInteger[Literal[True]] + greenMod: NestedInteger[Literal[True]] + blue: NestedInteger[Literal[True]] + blueOff: NestedInteger[Literal[True]] + blueMod: NestedInteger[Literal[True]] + gamma: Typed[Transform, Literal[True]] + invGamma: Typed[Transform, Literal[True]] + val: Set[_SystemColorVal] + lastClr: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + val: _SystemColorVal = "windowText", + lastClr=None, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + comp: Transform | None = None, + inv: Transform | None = None, + gray: Transform | None = None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gamma: Transform | None = None, + invGamma: Transform | None = None, + ) -> None: ... + +class HSLColor(Serialisable): + tagname: ClassVar[str] + hue: Integer[Literal[False]] + sat: MinMax[float, Literal[False]] + lum: MinMax[float, Literal[False]] + def __init__(self, hue: ConvertibleToInt, sat: ConvertibleToFloat, lum: ConvertibleToFloat) -> None: ... + +class RGBPercent(Serialisable): + tagname: ClassVar[str] + r: MinMax[float, Literal[False]] + g: MinMax[float, Literal[False]] + b: MinMax[float, Literal[False]] + def __init__(self, r: ConvertibleToFloat, g: ConvertibleToFloat, b: ConvertibleToFloat) -> None: ... + +_RGBPercent: TypeAlias = RGBPercent + +class SchemeColor(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + tint: NestedInteger[Literal[True]] + shade: NestedInteger[Literal[True]] + comp: EmptyTag[Literal[True]] + inv: NestedInteger[Literal[True]] + gray: NestedInteger[Literal[True]] + alpha: NestedInteger[Literal[True]] + alphaOff: NestedInteger[Literal[True]] + alphaMod: NestedInteger[Literal[True]] + hue: NestedInteger[Literal[True]] + hueOff: NestedInteger[Literal[True]] + hueMod: NestedInteger[Literal[True]] + sat: NestedInteger[Literal[True]] + satOff: NestedInteger[Literal[True]] + satMod: NestedInteger[Literal[True]] + lum: NestedInteger[Literal[True]] + lumOff: NestedInteger[Literal[True]] + lumMod: NestedInteger[Literal[True]] + red: NestedInteger[Literal[True]] + redOff: NestedInteger[Literal[True]] + redMod: NestedInteger[Literal[True]] + green: NestedInteger[Literal[True]] + greenOff: NestedInteger[Literal[True]] + greenMod: NestedInteger[Literal[True]] + blue: NestedInteger[Literal[True]] + blueOff: NestedInteger[Literal[True]] + blueMod: NestedInteger[Literal[True]] + gamma: EmptyTag[Literal[True]] + invGamma: EmptyTag[Literal[True]] + val: Set[_SchemeColors] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + comp: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + inv: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gray: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + gamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + invGamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + *, + val: _SchemeColors, + ) -> None: ... + @overload + def __init__( + self, + tint: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + shade: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + comp: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + inv: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + gray: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alpha: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alphaOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + alphaMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + hueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + sat: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + satOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + satMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lum: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lumOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + lumMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + red: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + redOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + redMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + green: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + greenOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + greenMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blue: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blueOff: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + blueMod: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None, + gamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + invGamma: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None, + val: _SchemeColors, + ) -> None: ... + +class ColorChoice(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SystemColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SystemColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +_COLOR_SET: Final[tuple[_ColorSetType, ...]] + +class ColorMapping(Serialisable): + tagname: ClassVar[str] + bg1: Set[_ColorSetType] + tx1: Set[_ColorSetType] + bg2: Set[_ColorSetType] + tx2: Set[_ColorSetType] + accent1: Set[_ColorSetType] + accent2: Set[_ColorSetType] + accent3: Set[_ColorSetType] + accent4: Set[_ColorSetType] + accent5: Set[_ColorSetType] + accent6: Set[_ColorSetType] + hlink: Set[_ColorSetType] + folHlink: Set[_ColorSetType] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + bg1: str = "lt1", + tx1: str = "dk1", + bg2: str = "lt2", + tx2: str = "dk2", + accent1: str = "accent1", + accent2: str = "accent2", + accent3: str = "accent3", + accent4: str = "accent4", + accent5: str = "accent5", + accent6: str = "accent6", + hlink: str = "hlink", + folHlink: str = "folHlink", + extLst: ExtensionList | None = None, + ) -> None: ... + +class ColorChoiceDescriptor(Typed[ColorChoice, Literal[True]]): + expected_type: type[ColorChoice] + allow_none: Literal[True] + def __init__(self, name: str | None = None) -> None: ... + def __set__(self, instance: Serialisable | Strict, value: str | ColorChoice | None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/connector.pyi b/stubs/openpyxl/openpyxl/drawing/connector.pyi new file mode 100644 index 000000000000..2308021cdfc6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/connector.pyi @@ -0,0 +1,99 @@ +from _typeshed import ConvertibleToInt +from typing import ClassVar, Literal, overload + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.chart.text import RichText +from openpyxl.descriptors import Typed +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.geometry import ShapeStyle +from openpyxl.drawing.properties import NonVisualDrawingProps, NonVisualDrawingShapeProps + +class Connection(Serialisable): + id: Integer[Literal[False]] + idx: Integer[Literal[False]] + def __init__(self, id: ConvertibleToInt, idx: ConvertibleToInt) -> None: ... + +class ConnectorLocking(Serialisable): + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, extLst: ExtensionList | None = None) -> None: ... + +class NonVisualConnectorProperties(Serialisable): + cxnSpLocks: Typed[ConnectorLocking, Literal[True]] + stCxn: Typed[Connection, Literal[True]] + endCxn: Typed[Connection, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + cxnSpLocks: ConnectorLocking | None = None, + stCxn: Connection | None = None, + endCxn: Connection | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class ConnectorNonVisual(Serialisable): + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvCxnSpPr: Typed[NonVisualConnectorProperties, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvCxnSpPr: NonVisualConnectorProperties) -> None: ... + +class ConnectorShape(Serialisable): + tagname: ClassVar[str] + nvCxnSpPr: Typed[ConnectorNonVisual, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[False]] + style: Typed[ShapeStyle, Literal[True]] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + def __init__( + self, + nvCxnSpPr: ConnectorNonVisual, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + ) -> None: ... + +class ShapeMeta(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvSpPr: Typed[NonVisualDrawingShapeProps, Literal[False]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvSpPr: NonVisualDrawingShapeProps) -> None: ... + +class Shape(Serialisable): + macro: String[Literal[True]] + textlink: String[Literal[True]] + fPublished: Bool[Literal[True]] + fLocksText: Bool[Literal[True]] + nvSpPr: Typed[ShapeMeta, Literal[True]] + meta: Alias + spPr: Typed[GraphicalProperties, Literal[False]] + graphicalProperties: Alias + style: Typed[ShapeStyle, Literal[True]] + txBody: Typed[RichText, Literal[True]] + + @overload + def __init__( + self, + macro: str | None = None, + textlink: str | None = None, + fPublished: _ConvertibleToBool | None = None, + fLocksText: _ConvertibleToBool | None = None, + nvSpPr: ShapeMeta | None = None, + *, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + txBody: RichText | None = None, + ) -> None: ... + @overload + def __init__( + self, + macro: str | None, + textlink: str | None, + fPublished: _ConvertibleToBool | None, + fLocksText: _ConvertibleToBool | None, + nvSpPr: ShapeMeta | None, + spPr: GraphicalProperties, + style: ShapeStyle | None = None, + txBody: RichText | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/drawing.pyi b/stubs/openpyxl/openpyxl/drawing/drawing.pyi new file mode 100644 index 000000000000..069370e5e02c --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/drawing.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete + +from .spreadsheet_drawing import AbsoluteAnchor, OneCellAnchor + +class Drawing: + count: int + name: str + description: str + coordinates: Incomplete + left: int + top: int + resize_proportional: bool + rotation: int + anchortype: str + anchorcol: int + anchorrow: int + def __init__(self) -> None: ... + + @property + def width(self) -> int: ... + @width.setter + def width(self, w: int) -> None: ... + + @property + def height(self) -> int: ... + @height.setter + def height(self, h: int) -> None: ... + + def set_dimension(self, w: int = 0, h: int = 0) -> None: ... + @property + def anchor(self) -> AbsoluteAnchor | OneCellAnchor: ... diff --git a/stubs/openpyxl/openpyxl/drawing/effect.pyi b/stubs/openpyxl/openpyxl/drawing/effect.pyi new file mode 100644 index 000000000000..d0678bfbc406 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/effect.pyi @@ -0,0 +1,255 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Float, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +from .colors import ColorChoice + +_FillOverlayEffectBlend: TypeAlias = Literal["over", "mult", "screen", "darken", "lighten"] +_EffectContainerType: TypeAlias = Literal["sib", "tree"] +_Algn: TypeAlias = Literal["tl", "t", "tr", "l", "ctr", "r", "bl", "b", "br"] +_PresetShadowEffectPrst: TypeAlias = Literal[ + "shdw1", + "shdw2", + "shdw3", + "shdw4", + "shdw5", + "shdw6", + "shdw7", + "shdw8", + "shdw9", + "shdw10", + "shdw11", + "shdw12", + "shdw13", + "shdw14", + "shdw15", + "shdw16", + "shdw17", + "shdw18", + "shdw19", + "shdw20", +] + +class TintEffect(Serialisable): + tagname: ClassVar[str] + hue: Integer[Literal[False]] + amt: Integer[Literal[False]] + def __init__(self, hue: ConvertibleToInt = 0, amt: ConvertibleToInt = 0) -> None: ... + +class LuminanceEffect(Serialisable): + tagname: ClassVar[str] + bright: Integer[Literal[False]] + contrast: Integer[Literal[False]] + def __init__(self, bright: ConvertibleToInt = 0, contrast: ConvertibleToInt = 0) -> None: ... + +class HSLEffect(Serialisable): + hue: Integer[Literal[False]] + sat: Integer[Literal[False]] + lum: Integer[Literal[False]] + def __init__(self, hue: ConvertibleToInt, sat: ConvertibleToInt, lum: ConvertibleToInt) -> None: ... + +class GrayscaleEffect(Serialisable): + tagname: ClassVar[str] + +class FillOverlayEffect(Serialisable): + blend: Set[_FillOverlayEffectBlend] + def __init__(self, blend: _FillOverlayEffectBlend) -> None: ... + +class DuotoneEffect(Serialisable): ... +class ColorReplaceEffect(Serialisable): ... +class Color(Serialisable): ... + +class ColorChangeEffect(Serialisable): + useA: Bool[Literal[True]] + clrFrom: Typed[Color, Literal[False]] + clrTo: Typed[Color, Literal[False]] + + @overload + def __init__(self, useA: _ConvertibleToBool | None = None, *, clrFrom: Color, clrTo: Color) -> None: ... + @overload + def __init__(self, useA: _ConvertibleToBool | None, clrFrom: Color, clrTo: Color) -> None: ... + +class BlurEffect(Serialisable): + rad: Float[Literal[False]] + grow: Bool[Literal[True]] + def __init__(self, rad: ConvertibleToFloat, grow: _ConvertibleToBool | None = None) -> None: ... + +class BiLevelEffect(Serialisable): + thresh: Integer[Literal[False]] + def __init__(self, thresh: ConvertibleToInt) -> None: ... + +class AlphaReplaceEffect(Serialisable): + a: Integer[Literal[False]] + def __init__(self, a: ConvertibleToInt) -> None: ... + +class AlphaModulateFixedEffect(Serialisable): + amt: Integer[Literal[False]] + def __init__(self, amt: ConvertibleToInt) -> None: ... + +class EffectContainer(Serialisable): + type: Set[_EffectContainerType] + name: String[Literal[True]] + def __init__(self, type: _EffectContainerType, name: str | None = None) -> None: ... + +class AlphaModulateEffect(Serialisable): + cont: Typed[EffectContainer, Literal[False]] + def __init__(self, cont: EffectContainer) -> None: ... + +class AlphaInverseEffect(Serialisable): ... +class AlphaFloorEffect(Serialisable): ... +class AlphaCeilingEffect(Serialisable): ... + +class AlphaBiLevelEffect(Serialisable): + thresh: Integer[Literal[False]] + def __init__(self, thresh: ConvertibleToInt) -> None: ... + +class GlowEffect(ColorChoice): + rad: Float[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rad: ConvertibleToFloat, **kw) -> None: ... + +class InnerShadowEffect(ColorChoice): + blurRad: Float[Literal[False]] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, blurRad: ConvertibleToFloat, dist: ConvertibleToFloat, dir: ConvertibleToInt, **kw) -> None: ... + +class OuterShadow(ColorChoice): + tagname: ClassVar[str] + blurRad: Float[Literal[True]] + dist: Float[Literal[True]] + dir: Integer[Literal[True]] + sx: Integer[Literal[True]] + sy: Integer[Literal[True]] + kx: Integer[Literal[True]] + ky: Integer[Literal[True]] + algn: Set[_Algn] + rotWithShape: Bool[Literal[True]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + blurRad: ConvertibleToFloat | None = None, + dist: ConvertibleToFloat | None = None, + dir: ConvertibleToInt | None = None, + sx: ConvertibleToInt | None = None, + sy: ConvertibleToInt | None = None, + kx: ConvertibleToInt | None = None, + ky: ConvertibleToInt | None = None, + *, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + **kw, + ) -> None: ... + @overload + def __init__( + self, + blurRad: ConvertibleToFloat | None, + dist: ConvertibleToFloat | None, + dir: ConvertibleToInt | None, + sx: ConvertibleToInt | None, + sy: ConvertibleToInt | None, + kx: ConvertibleToInt | None, + ky: ConvertibleToInt | None, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + **kw, + ) -> None: ... + +class PresetShadowEffect(ColorChoice): + prst: Set[_PresetShadowEffectPrst] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + # Same as parent + # scrgbClr = ColorChoice.scrgbClr + # srgbClr = ColorChoice.srgbClr + # hslClr = ColorChoice.hslClr + # sysClr = ColorChoice.sysClr + # schemeClr = ColorChoice.schemeClr + # prstClr = ColorChoice.prstClr + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, prst: _PresetShadowEffectPrst, dist: ConvertibleToFloat, dir: ConvertibleToInt, **kw) -> None: ... + +class ReflectionEffect(Serialisable): + blurRad: Float[Literal[False]] + stA: Integer[Literal[False]] + stPos: Integer[Literal[False]] + endA: Integer[Literal[False]] + endPos: Integer[Literal[False]] + dist: Float[Literal[False]] + dir: Integer[Literal[False]] + fadeDir: Integer[Literal[False]] + sx: Integer[Literal[False]] + sy: Integer[Literal[False]] + kx: Integer[Literal[False]] + ky: Integer[Literal[False]] + algn: Set[_Algn] + rotWithShape: Bool[Literal[True]] + def __init__( + self, + blurRad: ConvertibleToFloat, + stA: ConvertibleToInt, + stPos: ConvertibleToInt, + endA: ConvertibleToInt, + endPos: ConvertibleToInt, + dist: ConvertibleToFloat, + dir: ConvertibleToInt, + fadeDir: ConvertibleToInt, + sx: ConvertibleToInt, + sy: ConvertibleToInt, + kx: ConvertibleToInt, + ky: ConvertibleToInt, + algn: _Algn, + rotWithShape: _ConvertibleToBool | None = None, + ) -> None: ... + +class SoftEdgesEffect(Serialisable): + rad: Float[Literal[False]] + def __init__(self, rad: ConvertibleToFloat) -> None: ... + +class EffectList(Serialisable): + blur: Typed[BlurEffect, Literal[True]] + fillOverlay: Typed[FillOverlayEffect, Literal[True]] + glow: Typed[GlowEffect, Literal[True]] + innerShdw: Typed[InnerShadowEffect, Literal[True]] + outerShdw: Typed[OuterShadow, Literal[True]] + prstShdw: Typed[PresetShadowEffect, Literal[True]] + reflection: Typed[ReflectionEffect, Literal[True]] + softEdge: Typed[SoftEdgesEffect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + blur: BlurEffect | None = None, + fillOverlay: FillOverlayEffect | None = None, + glow: GlowEffect | None = None, + innerShdw: InnerShadowEffect | None = None, + outerShdw: OuterShadow | None = None, + prstShdw: PresetShadowEffect | None = None, + reflection: ReflectionEffect | None = None, + softEdge: SoftEdgesEffect | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/fill.pyi b/stubs/openpyxl/openpyxl/drawing/fill.pyi new file mode 100644 index 000000000000..6ee8f5964c6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/fill.pyi @@ -0,0 +1,314 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, NoneSet, Set, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedNoneSet, NestedValue, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, HSLColor, RGBPercent as _RGBPercent, SchemeColor, SystemColor, _PresetColors +from openpyxl.drawing.effect import ( + AlphaBiLevelEffect, + AlphaCeilingEffect, + AlphaFloorEffect, + AlphaInverseEffect, + AlphaModulateEffect, + AlphaModulateFixedEffect, + AlphaReplaceEffect, + BiLevelEffect, + BlurEffect, + ColorChangeEffect, + ColorReplaceEffect, + DuotoneEffect, + FillOverlayEffect, + GrayscaleEffect, + HSLEffect, + LuminanceEffect, + TintEffect, +) + +from ..xml._functions_overloads import _HasTagAndGet + +_PatternFillPropertiesPrst: TypeAlias = Literal[ + "pct5", + "pct10", + "pct20", + "pct25", + "pct30", + "pct40", + "pct50", + "pct60", + "pct70", + "pct75", + "pct80", + "pct90", + "horz", + "vert", + "ltHorz", + "ltVert", + "dkHorz", + "dkVert", + "narHorz", + "narVert", + "dashHorz", + "dashVert", + "cross", + "dnDiag", + "upDiag", + "ltDnDiag", + "ltUpDiag", + "dkDnDiag", + "dkUpDiag", + "wdDnDiag", + "wdUpDiag", + "dashDnDiag", + "dashUpDiag", + "diagCross", + "smCheck", + "lgCheck", + "smGrid", + "lgGrid", + "dotGrid", + "smConfetti", + "lgConfetti", + "horzBrick", + "diagBrick", + "solidDmnd", + "openDmnd", + "dotDmnd", + "plaid", + "sphere", + "weave", + "divot", + "shingle", + "wave", + "trellis", + "zigZag", +] +_PropertiesFlip: TypeAlias = Literal["x", "y", "xy"] +_TileInfoPropertiesAlgn: TypeAlias = Literal["tl", "t", "tr", "l", "ctr", "r", "bl", "b", "br"] +_BlipCstate: TypeAlias = Literal["email", "screen", "print", "hqprint"] +_PathShadePropertiesPath: TypeAlias = Literal["shape", "circle", "rect"] + +class PatternFillProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + prst: NoneSet[_PatternFillPropertiesPrst] + preset: Alias + fgClr: Typed[ColorChoice, Literal[True]] + foreground: Alias + bgClr: Typed[ColorChoice, Literal[True]] + background: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + prst: _PatternFillPropertiesPrst | Literal["none"] | None = None, + fgClr: ColorChoice | None = None, + bgClr: ColorChoice | None = None, + ) -> None: ... + +class RelativeRect(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + l: Incomplete + left: Alias + t: Incomplete + top: Alias + r: Incomplete + right: Alias + b: Incomplete + bottom: Alias + def __init__(self, l=None, t=None, r=None, b=None) -> None: ... + +class StretchInfoProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + fillRect: Typed[RelativeRect, Literal[True]] + def __init__(self, fillRect: RelativeRect = ...) -> None: ... + +class GradientStop(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + pos: MinMax[float, Literal[True]] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SchemeColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + pos: ConvertibleToFloat | None = None, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SchemeColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +class LinearShadeProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + ang: Integer[Literal[False]] + scaled: Bool[Literal[True]] + def __init__(self, ang: ConvertibleToInt, scaled: _ConvertibleToBool | None = None) -> None: ... + +class PathShadeProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + path: Set[_PathShadePropertiesPath] + fillToRect: Typed[RelativeRect, Literal[True]] + def __init__(self, path: _PathShadePropertiesPath, fillToRect: RelativeRect | None = None) -> None: ... + +class GradientFillProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + flip: NoneSet[_PropertiesFlip] + rotWithShape: Bool[Literal[True]] + gsLst: Incomplete + stop_list: Alias + lin: Typed[LinearShadeProperties, Literal[True]] + linear: Alias + path: Typed[PathShadeProperties, Literal[True]] + tileRect: Typed[RelativeRect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + flip: _PropertiesFlip | Literal["none"] | None = None, + rotWithShape: _ConvertibleToBool | None = None, + gsLst=(), + lin: LinearShadeProperties | None = None, + path: PathShadeProperties | None = None, + tileRect: RelativeRect | None = None, + ) -> None: ... + +class SolidColorFillProperties(Serialisable): + tagname: ClassVar[str] + scrgbClr: Typed[_RGBPercent, Literal[True]] + RGBPercent: Alias + srgbClr: NestedValue[_RGBPercent, Literal[True]] + RGB: Alias + hslClr: Typed[HSLColor, Literal[True]] + sysClr: Typed[SystemColor, Literal[True]] + schemeClr: Typed[SchemeColor, Literal[True]] + prstClr: NestedNoneSet[_PresetColors] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scrgbClr: _RGBPercent | None = None, + srgbClr: _HasTagAndGet[_RGBPercent | None] | _RGBPercent | None = None, + hslClr: HSLColor | None = None, + sysClr: SystemColor | None = None, + schemeClr: SchemeColor | None = None, + prstClr: _NestedNoneSetParam[_PresetColors] = None, + ) -> None: ... + +class Blip(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + cstate: NoneSet[_BlipCstate] + embed: Incomplete + link: Incomplete + noGrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + alphaBiLevel: Typed[AlphaBiLevelEffect, Literal[True]] + alphaCeiling: Typed[AlphaCeilingEffect, Literal[True]] + alphaFloor: Typed[AlphaFloorEffect, Literal[True]] + alphaInv: Typed[AlphaInverseEffect, Literal[True]] + alphaMod: Typed[AlphaModulateEffect, Literal[True]] + alphaModFix: Typed[AlphaModulateFixedEffect, Literal[True]] + alphaRepl: Typed[AlphaReplaceEffect, Literal[True]] + biLevel: Typed[BiLevelEffect, Literal[True]] + blur: Typed[BlurEffect, Literal[True]] + clrChange: Typed[ColorChangeEffect, Literal[True]] + clrRepl: Typed[ColorReplaceEffect, Literal[True]] + duotone: Typed[DuotoneEffect, Literal[True]] + fillOverlay: Typed[FillOverlayEffect, Literal[True]] + grayscl: Typed[GrayscaleEffect, Literal[True]] + hsl: Typed[HSLEffect, Literal[True]] + lum: Typed[LuminanceEffect, Literal[True]] + tint: Typed[TintEffect, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + cstate: _BlipCstate | Literal["none"] | None = None, + embed=None, + link=None, + noGrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: ExtensionList | None = None, + alphaBiLevel: AlphaBiLevelEffect | None = None, + alphaCeiling: AlphaCeilingEffect | None = None, + alphaFloor: AlphaFloorEffect | None = None, + alphaInv: AlphaInverseEffect | None = None, + alphaMod: AlphaModulateEffect | None = None, + alphaModFix: AlphaModulateFixedEffect | None = None, + alphaRepl: AlphaReplaceEffect | None = None, + biLevel: BiLevelEffect | None = None, + blur: BlurEffect | None = None, + clrChange: ColorChangeEffect | None = None, + clrRepl: ColorReplaceEffect | None = None, + duotone: DuotoneEffect | None = None, + fillOverlay: FillOverlayEffect | None = None, + grayscl: GrayscaleEffect | None = None, + hsl: HSLEffect | None = None, + lum: LuminanceEffect | None = None, + tint: TintEffect | None = None, + ) -> None: ... + +class TileInfoProperties(Serialisable): + tx: Integer[Literal[True]] + ty: Integer[Literal[True]] + sx: Integer[Literal[True]] + sy: Integer[Literal[True]] + flip: NoneSet[_PropertiesFlip] + algn: Set[_TileInfoPropertiesAlgn] + def __init__( + self, + tx: ConvertibleToInt | None = None, + ty: ConvertibleToInt | None = None, + sx: ConvertibleToInt | None = None, + sy: ConvertibleToInt | None = None, + flip: _PropertiesFlip | Literal["none"] | None = None, + *, + algn: _TileInfoPropertiesAlgn, + ) -> None: ... + +class BlipFillProperties(Serialisable): + tagname: ClassVar[str] + dpi: Integer[Literal[True]] + rotWithShape: Bool[Literal[True]] + blip: Typed[Blip, Literal[True]] + srcRect: Typed[RelativeRect, Literal[True]] + tile: Typed[TileInfoProperties, Literal[True]] + stretch: Typed[StretchInfoProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + dpi: ConvertibleToInt | None = None, + rotWithShape: _ConvertibleToBool | None = None, + blip: Blip | None = None, + tile: TileInfoProperties | None = None, + stretch: StretchInfoProperties = ..., + srcRect: RelativeRect | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/geometry.pyi b/stubs/openpyxl/openpyxl/drawing/geometry.pyi new file mode 100644 index 000000000000..a15293e0c663 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/geometry.pyi @@ -0,0 +1,577 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Alias, Bool, Float, Integer, MinMax, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import Coordinate, ExtensionList, Percentage +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color + +_BevelPrst: TypeAlias = Literal[ + "relaxedInset", + "circle", + "slope", + "cross", + "angle", + "softRound", + "convex", + "coolSlant", + "divot", + "riblet", + "hardEdge", + "artDeco", +] +_Shape3DPrstMaterial: TypeAlias = Literal[ + "legacyMatte", + "legacyPlastic", + "legacyMetal", + "legacyWireframe", + "matte", + "plastic", + "metal", + "warmMatte", + "translucentPowder", + "powder", + "dkEdge", + "softEdge", + "clear", + "flat", + "softmetal", +] +_Path2DFill: TypeAlias = Literal["norm", "lighten", "lightenLess", "darken", "darkenLess"] +_FontReferenceIdx: TypeAlias = Literal["major", "minor"] +_CameraPrst: TypeAlias = Literal[ + "legacyObliqueTopLeft", + "legacyObliqueTop", + "legacyObliqueTopRight", + "legacyObliqueLeft", + "legacyObliqueFront", + "legacyObliqueRight", + "legacyObliqueBottomLeft", + "legacyObliqueBottom", + "legacyObliqueBottomRight", + "legacyPerspectiveTopLeft", + "legacyPerspectiveTop", + "legacyPerspectiveTopRight", + "legacyPerspectiveLeft", + "legacyPerspectiveFront", + "legacyPerspectiveRight", + "legacyPerspectiveBottomLeft", + "legacyPerspectiveBottom", + "legacyPerspectiveBottomRight", + "orthographicFront", + "isometricTopUp", + "isometricTopDown", + "isometricBottomUp", + "isometricBottomDown", + "isometricLeftUp", + "isometricLeftDown", + "isometricRightUp", + "isometricRightDown", + "isometricOffAxis1Left", + "isometricOffAxis1Right", + "isometricOffAxis1Top", + "isometricOffAxis2Left", + "isometricOffAxis2Right", + "isometricOffAxis2Top", + "isometricOffAxis3Left", + "isometricOffAxis3Right", + "isometricOffAxis3Bottom", + "isometricOffAxis4Left", + "isometricOffAxis4Right", + "isometricOffAxis4Bottom", + "obliqueTopLeft", + "obliqueTop", + "obliqueTopRight", + "obliqueLeft", + "obliqueRight", + "obliqueBottomLeft", + "obliqueBottom", + "obliqueBottomRight", + "perspectiveFront", + "perspectiveLeft", + "perspectiveRight", + "perspectiveAbove", + "perspectiveBelow", + "perspectiveAboveLeftFacing", + "perspectiveAboveRightFacing", + "perspectiveContrastingLeftFacing", + "perspectiveContrastingRightFacing", + "perspectiveHeroicLeftFacing", + "perspectiveHeroicRightFacing", + "perspectiveHeroicExtremeLeftFacing", + "perspectiveHeroicExtremeRightFacing", + "perspectiveRelaxed", + "perspectiveRelaxedModerately", +] +_LightRigRig: TypeAlias = Literal[ + "legacyFlat1", + "legacyFlat2", + "legacyFlat3", + "legacyFlat4", + "legacyNormal1", + "legacyNormal2", + "legacyNormal3", + "legacyNormal4", + "legacyHarsh1", + "legacyHarsh2", + "legacyHarsh3", + "legacyHarsh4", + "threePt", + "balanced", + "soft", + "harsh", + "flood", + "contrasting", + "morning", + "sunrise", + "sunset", + "chilly", + "freezing", + "flat", + "twoPt", + "glow", + "brightRoom", +] +_LightRigDir: TypeAlias = Literal["tl", "t", "tr", "l", "r", "bl", "b", "br"] +_PresetGeometry2DPrst: TypeAlias = Literal[ + "line", + "lineInv", + "triangle", + "rtTriangle", + "rect", + "diamond", + "parallelogram", + "trapezoid", + "nonIsoscelesTrapezoid", + "pentagon", + "hexagon", + "heptagon", + "octagon", + "decagon", + "dodecagon", + "star4", + "star5", + "star6", + "star7", + "star8", + "star10", + "star12", + "star16", + "star24", + "star32", + "roundRect", + "round1Rect", + "round2SameRect", + "round2DiagRect", + "snipRoundRect", + "snip1Rect", + "snip2SameRect", + "snip2DiagRect", + "plaque", + "ellipse", + "teardrop", + "homePlate", + "chevron", + "pieWedge", + "pie", + "blockArc", + "donut", + "noSmoking", + "rightArrow", + "leftArrow", + "upArrow", + "downArrow", + "stripedRightArrow", + "notchedRightArrow", + "bentUpArrow", + "leftRightArrow", + "upDownArrow", + "leftUpArrow", + "leftRightUpArrow", + "quadArrow", + "leftArrowCallout", + "rightArrowCallout", + "upArrowCallout", + "downArrowCallout", + "leftRightArrowCallout", + "upDownArrowCallout", + "quadArrowCallout", + "bentArrow", + "uturnArrow", + "circularArrow", + "leftCircularArrow", + "leftRightCircularArrow", + "curvedRightArrow", + "curvedLeftArrow", + "curvedUpArrow", + "curvedDownArrow", + "swooshArrow", + "cube", + "can", + "lightningBolt", + "heart", + "sun", + "moon", + "smileyFace", + "irregularSeal1", + "irregularSeal2", + "foldedCorner", + "bevel", + "frame", + "halfFrame", + "corner", + "diagStripe", + "chord", + "arc", + "leftBracket", + "rightBracket", + "leftBrace", + "rightBrace", + "bracketPair", + "bracePair", + "straightConnector1", + "bentConnector2", + "bentConnector3", + "bentConnector4", + "bentConnector5", + "curvedConnector2", + "curvedConnector3", + "curvedConnector4", + "curvedConnector5", + "callout1", + "callout2", + "callout3", + "accentCallout1", + "accentCallout2", + "accentCallout3", + "borderCallout1", + "borderCallout2", + "borderCallout3", + "accentBorderCallout1", + "accentBorderCallout2", + "accentBorderCallout3", + "wedgeRectCallout", + "wedgeRoundRectCallout", + "wedgeEllipseCallout", + "cloudCallout", + "cloud", + "ribbon", + "ribbon2", + "ellipseRibbon", + "ellipseRibbon2", + "leftRightRibbon", + "verticalScroll", + "horizontalScroll", + "wave", + "doubleWave", + "plus", + "flowChartProcess", + "flowChartDecision", + "flowChartInputOutput", + "flowChartPredefinedProcess", + "flowChartInternalStorage", + "flowChartDocument", + "flowChartMultidocument", + "flowChartTerminator", + "flowChartPreparation", + "flowChartManualInput", + "flowChartManualOperation", + "flowChartConnector", + "flowChartPunchedCard", + "flowChartPunchedTape", + "flowChartSummingJunction", + "flowChartOr", + "flowChartCollate", + "flowChartSort", + "flowChartExtract", + "flowChartMerge", + "flowChartOfflineStorage", + "flowChartOnlineStorage", + "flowChartMagneticTape", + "flowChartMagneticDisk", + "flowChartMagneticDrum", + "flowChartDisplay", + "flowChartDelay", + "flowChartAlternateProcess", + "flowChartOffpageConnector", + "actionButtonBlank", + "actionButtonHome", + "actionButtonHelp", + "actionButtonInformation", + "actionButtonForwardNext", + "actionButtonBackPrevious", + "actionButtonEnd", + "actionButtonBeginning", + "actionButtonReturn", + "actionButtonDocument", + "actionButtonSound", + "actionButtonMovie", + "gear6", + "gear9", + "funnel", + "mathPlus", + "mathMinus", + "mathMultiply", + "mathDivide", + "mathEqual", + "mathNotEqual", + "cornerTabs", + "squareTabs", + "plaqueTabs", + "chartX", + "chartStar", + "chartPlus", +] + +class Point2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + x: Incomplete + y: Incomplete + def __init__(self, x=None, y=None) -> None: ... + +class PositiveSize2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + cx: Integer[Literal[False]] + width: Alias + cy: Integer[Literal[False]] + height: Alias + def __init__(self, cx: ConvertibleToInt, cy: ConvertibleToInt) -> None: ... + +class Transform2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + flipH: Bool[Literal[True]] + flipV: Bool[Literal[True]] + off: Typed[Point2D, Literal[True]] + ext: Typed[PositiveSize2D, Literal[True]] + chOff: Typed[Point2D, Literal[True]] + chExt: Typed[PositiveSize2D, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = None, + flipH: _ConvertibleToBool | None = None, + flipV: _ConvertibleToBool | None = None, + off: Point2D | None = None, + ext: PositiveSize2D | None = None, + chOff: Point2D | None = None, + chExt: PositiveSize2D | None = None, + ) -> None: ... + +class GroupTransform2D(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + flipH: Bool[Literal[True]] + flipV: Bool[Literal[True]] + off = Typed(expected_type=Point2D, allow_none=True) + ext = Typed(expected_type=PositiveSize2D, allow_none=True) + chOff = Typed(expected_type=Point2D, allow_none=True) + chExt = Typed(expected_type=PositiveSize2D, allow_none=True) + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = 0, + flipH: _ConvertibleToBool | None = None, + flipV: _ConvertibleToBool | None = None, + off: Point2D | None = None, + ext: PositiveSize2D | None = None, + chOff: Point2D | None = None, + chExt: PositiveSize2D | None = None, + ) -> None: ... + +class SphereCoords(Serialisable): + tagname: ClassVar[str] + lat: Integer[Literal[False]] + lon: Integer[Literal[False]] + rev: Integer[Literal[False]] + def __init__(self, lat: ConvertibleToInt, lon: ConvertibleToInt, rev: ConvertibleToInt) -> None: ... + +class Camera(Serialisable): + tagname: ClassVar[str] + prst: Set[_CameraPrst] + fov: Integer[Literal[True]] + zoom: Typed[Percentage, Literal[True]] + rot: Typed[SphereCoords, Literal[True]] + def __init__( + self, + prst: _CameraPrst, + fov: ConvertibleToInt | None = None, + zoom: Percentage | None = None, + rot: SphereCoords | None = None, + ) -> None: ... + +class LightRig(Serialisable): + tagname: ClassVar[str] + rig: Set[_LightRigRig] + dir: Set[_LightRigDir] + rot: Typed[SphereCoords, Literal[True]] + def __init__(self, rig: _LightRigRig, dir: _LightRigDir, rot: SphereCoords | None = None) -> None: ... + +class Vector3D(Serialisable): + tagname: ClassVar[str] + dx: Integer[Literal[False]] + dy: Integer[Literal[False]] + dz: Integer[Literal[False]] + def __init__(self, dx: ConvertibleToInt, dy: ConvertibleToInt, dz: ConvertibleToInt) -> None: ... + +class Point3D(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + y: Integer[Literal[False]] + z: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt, y: ConvertibleToInt, z: ConvertibleToInt) -> None: ... + +class Backdrop(Serialisable): + anchor: Typed[Point3D, Literal[False]] + norm: Typed[Vector3D, Literal[False]] + up: Typed[Vector3D, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, anchor: Point3D, norm: Vector3D, up: Vector3D, extLst: ExtensionList | None = None) -> None: ... + +class Scene3D(Serialisable): + camera: Typed[Camera, Literal[False]] + lightRig: Typed[LightRig, Literal[False]] + backdrop: Typed[Backdrop, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, camera: Camera, lightRig: LightRig, backdrop: Backdrop | None = None, extLst: ExtensionList | None = None + ) -> None: ... + +class Bevel(Serialisable): + tagname: ClassVar[str] + w: Integer[Literal[False]] + h: Integer[Literal[False]] + prst: NoneSet[_BevelPrst] + def __init__(self, w: ConvertibleToInt, h: ConvertibleToInt, prst: _BevelPrst | Literal["none"] | None = None) -> None: ... + +class Shape3D(Serialisable): + namespace: ClassVar[str] + z: Typed[Coordinate[bool], Literal[True]] + extrusionH: Integer[Literal[True]] + contourW: Integer[Literal[True]] + prstMaterial: NoneSet[_Shape3DPrstMaterial] + bevelT: Typed[Bevel, Literal[True]] + bevelB: Typed[Bevel, Literal[True]] + extrusionClr: Typed[Color, Literal[True]] + contourClr: Typed[Color, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + z: Coordinate[bool] | None = None, + extrusionH: ConvertibleToInt | None = None, + contourW: ConvertibleToInt | None = None, + prstMaterial: _Shape3DPrstMaterial | Literal["none"] | None = None, + bevelT: Bevel | None = None, + bevelB: Bevel | None = None, + extrusionClr: Color | None = None, + contourClr: Color | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class Path2D(Serialisable): + w: Float[Literal[False]] + h: Float[Literal[False]] + fill: NoneSet[_Path2DFill] + stroke: Bool[Literal[True]] + extrusionOk: Bool[Literal[True]] + def __init__( + self, + w: ConvertibleToFloat, + h: ConvertibleToFloat, + fill: _Path2DFill | Literal["none"] | None = None, + stroke: _ConvertibleToBool | None = None, + extrusionOk: _ConvertibleToBool | None = None, + ) -> None: ... + +class Path2DList(Serialisable): + path: Typed[Path2D, Literal[True]] + def __init__(self, path: Path2D | None = None) -> None: ... + +class GeomRect(Serialisable): + l: Incomplete + t: Incomplete + r: Incomplete + b: Incomplete + def __init__(self, l=None, t=None, r=None, b=None) -> None: ... + +class AdjPoint2D(Serialisable): + x: Incomplete + y: Incomplete + def __init__(self, x=None, y=None) -> None: ... + +class ConnectionSite(Serialisable): + ang: MinMax[float, Literal[False]] + pos: Typed[AdjPoint2D, Literal[False]] + def __init__(self, ang: ConvertibleToFloat, pos: AdjPoint2D) -> None: ... + +class ConnectionSiteList(Serialisable): + cxn: Typed[ConnectionSite, Literal[True]] + def __init__(self, cxn: ConnectionSite | None = None) -> None: ... + +class AdjustHandleList(Serialisable): ... + +class GeomGuide(Serialisable): + name: String[Literal[False]] + fmla: String[Literal[False]] + def __init__(self, name: str, fmla: str) -> None: ... + +class GeomGuideList(Serialisable): + gd: Typed[GeomGuide, Literal[True]] + def __init__(self, gd: GeomGuide | None = None) -> None: ... + +class CustomGeometry2D(Serialisable): + avLst: Typed[GeomGuideList, Literal[True]] + gdLst: Typed[GeomGuideList, Literal[True]] + ahLst: Typed[AdjustHandleList, Literal[True]] + cxnLst: Typed[ConnectionSiteList, Literal[True]] + pathLst: Typed[Path2DList, Literal[False]] + rect: GeomRect | None + + @overload + def __init__( + self, + avLst: GeomGuideList | None = None, + gdLst: GeomGuideList | None = None, + ahLst: AdjustHandleList | None = None, + cxnLst: ConnectionSiteList | None = None, + rect: Unused = None, + *, + pathLst: Path2DList, + ) -> None: ... + @overload + def __init__( + self, + avLst: GeomGuideList | None, + gdLst: GeomGuideList | None, + ahLst: AdjustHandleList | None, + cxnLst: ConnectionSiteList | None, + rect: Unused, + pathLst: Path2DList, + ) -> None: ... + +class PresetGeometry2D(Serialisable): + namespace: ClassVar[str] + prst: Set[_PresetGeometry2DPrst] + avLst: Typed[GeomGuideList, Literal[True]] + def __init__(self, prst: _PresetGeometry2DPrst, avLst: GeomGuideList | None = None) -> None: ... + +class FontReference(Serialisable): + idx: NoneSet[_FontReferenceIdx] + def __init__(self, idx: _FontReferenceIdx | Literal["none"] | None = None) -> None: ... + +class StyleMatrixReference(Serialisable): + idx: Integer[Literal[False]] + def __init__(self, idx: ConvertibleToInt) -> None: ... + +class ShapeStyle(Serialisable): + lnRef: Typed[StyleMatrixReference, Literal[False]] + fillRef: Typed[StyleMatrixReference, Literal[False]] + effectRef: Typed[StyleMatrixReference, Literal[False]] + fontRef: Typed[FontReference, Literal[False]] + def __init__( + self, lnRef: StyleMatrixReference, fillRef: StyleMatrixReference, effectRef: StyleMatrixReference, fontRef: FontReference + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/graphic.pyi b/stubs/openpyxl/openpyxl/drawing/graphic.pyi new file mode 100644 index 000000000000..38164a99b4ef --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/graphic.pyi @@ -0,0 +1,83 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.picture import PictureFrame +from openpyxl.drawing.properties import GroupShapeProperties, NonVisualGroupShape +from openpyxl.drawing.relation import ChartRelation +from openpyxl.drawing.xdr import XDRTransform2D + +class GraphicFrameLocking(Serialisable): + noGrp: Bool[Literal[True]] + noDrilldown: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + noGrp: _ConvertibleToBool | None = None, + noDrilldown: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class NonVisualGraphicFrameProperties(Serialisable): + tagname: ClassVar[str] + graphicFrameLocks: Typed[GraphicFrameLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__(self, graphicFrameLocks: GraphicFrameLocking | None = None, extLst: ExtensionList | None = None) -> None: ... + +class NonVisualGraphicFrame(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[ExtensionList, Literal[False]] + cNvGraphicFramePr: Typed[ExtensionList, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr=None, cNvGraphicFramePr=None) -> None: ... + +class GraphicData(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + uri: String[Literal[False]] + chart: Typed[ChartRelation, Literal[True]] + def __init__(self, uri: str = ..., chart: ChartRelation | None = None) -> None: ... + +class GraphicObject(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + graphicData: Typed[GraphicData, Literal[False]] + def __init__(self, graphicData: GraphicData | None = None) -> None: ... + +class GraphicFrame(Serialisable): + tagname: ClassVar[str] + nvGraphicFramePr: Typed[NonVisualGraphicFrame, Literal[False]] + xfrm: Typed[XDRTransform2D, Literal[False]] + graphic: Typed[GraphicObject, Literal[False]] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + nvGraphicFramePr: NonVisualGraphicFrame | None = None, + xfrm: XDRTransform2D | None = None, + graphic: GraphicObject | None = None, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + ) -> None: ... + +class GroupShape(Serialisable): + nvGrpSpPr: Typed[NonVisualGroupShape, Literal[False]] + nonVisualProperties: Alias + grpSpPr: Typed[GroupShapeProperties, Literal[False]] + visualProperties: Alias + pic: Typed[PictureFrame, Literal[True]] + # Source incorrectly uses a list here instead of a tuple + __elements__: ClassVar[list[str]] # type: ignore[assignment] + def __init__( + self, nvGrpSpPr: NonVisualGroupShape, grpSpPr: GroupShapeProperties, pic: PictureFrame | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/image.pyi b/stubs/openpyxl/openpyxl/drawing/image.pyi new file mode 100644 index 000000000000..c3a35a1384b4 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/image.pyi @@ -0,0 +1,23 @@ +from _typeshed import SupportsRead +from pathlib import Path +from types import ModuleType +from typing import Any, Literal, TypeAlias + +from openpyxl.drawing.spreadsheet_drawing import _AnchorBase + +# Is actually PIL.Image.Image +_PILImageImage: TypeAlias = Any +# same as first parameter of PIL.Image.open +_PILImageFilePath: TypeAlias = str | bytes | Path | SupportsRead[bytes] + +PILImage: ModuleType | Literal[False] + +class Image: + anchor: str | _AnchorBase + ref: _PILImageImage | _PILImageFilePath + width: int + height: int + format: str + def __init__(self, img: _PILImageImage | _PILImageFilePath) -> None: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/drawing/line.pyi b/stubs/openpyxl/openpyxl/drawing/line.pyi new file mode 100644 index 000000000000..209d8165ea15 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/line.pyi @@ -0,0 +1,88 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Integer, MinMax, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedInteger, NestedNoneSet, _NestedNoneSetParam +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.fill import GradientFillProperties, PatternFillProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_LineEndPropertiesType: TypeAlias = Literal["none", "triangle", "stealth", "diamond", "oval", "arrow"] +_LineEndPropertiesWLen: TypeAlias = Literal["sm", "med", "lg"] +_LinePropertiesCap: TypeAlias = Literal["rnd", "sq", "flat"] +_LinePropertiesCmpd: TypeAlias = Literal["sng", "dbl", "thickThin", "thinThick", "tri"] +_LinePropertiesAlgn: TypeAlias = Literal["ctr", "in"] +_LinePropertiesPrstDash: TypeAlias = Literal[ + "solid", "dot", "dash", "lgDash", "dashDot", "lgDashDot", "lgDashDotDot", "sysDash", "sysDot", "sysDashDot", "sysDashDotDot" +] + +class LineEndProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + type: NoneSet[_LineEndPropertiesType] + w: NoneSet[_LineEndPropertiesWLen] + len: NoneSet[_LineEndPropertiesWLen] + def __init__( + self, + type: _LineEndPropertiesType | Literal["none"] | None = None, + w: _LineEndPropertiesWLen | Literal["none"] | None = None, + len: _LineEndPropertiesWLen | Literal["none"] | None = None, + ) -> None: ... + +class DashStop(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + d: Integer[Literal[False]] + length: Alias + sp: Integer[Literal[False]] + space: Alias + def __init__(self, d: ConvertibleToInt = 0, sp: ConvertibleToInt = 0) -> None: ... + +class DashStopList(Serialisable): + ds: Incomplete + def __init__(self, ds=None) -> None: ... + +class LineProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + w: MinMax[float, Literal[True]] + width: Alias + cap: NoneSet[_LinePropertiesCap] + cmpd: NoneSet[_LinePropertiesCmpd] + algn: NoneSet[_LinePropertiesAlgn] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + prstDash: NestedNoneSet[_LinePropertiesPrstDash] + dashStyle: Alias + custDash: Typed[DashStop, Literal[True]] + round: EmptyTag[Literal[False]] + bevel: EmptyTag[Literal[False]] + miter: NestedInteger[Literal[True]] + headEnd: Typed[LineEndProperties, Literal[True]] + tailEnd: Typed[LineEndProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + w: ConvertibleToFloat | None = None, + cap: _LinePropertiesCap | Literal["none"] | None = None, + cmpd: _LinePropertiesCmpd | Literal["none"] | None = None, + algn: _LinePropertiesAlgn | Literal["none"] | None = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + prstDash: _NestedNoneSetParam[_LinePropertiesPrstDash] = None, + custDash: DashStop | None = None, + round: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + bevel: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + miter: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + headEnd: LineEndProperties | None = None, + tailEnd: LineEndProperties | None = None, + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/picture.pyi b/stubs/openpyxl/openpyxl/drawing/picture.pyi new file mode 100644 index 000000000000..4a3de4c9ea65 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/picture.pyi @@ -0,0 +1,79 @@ +from _typeshed import Unused +from typing import ClassVar, Literal + +from openpyxl.chart.shapes import GraphicalProperties +from openpyxl.descriptors.base import Alias, Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.fill import BlipFillProperties +from openpyxl.drawing.geometry import ShapeStyle +from openpyxl.drawing.properties import NonVisualDrawingProps + +class PictureLocking(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + noCrop: Bool[Literal[True]] + noGrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + noCrop: _ConvertibleToBool | None = None, + noGrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class NonVisualPictureProperties(Serialisable): + tagname: ClassVar[str] + preferRelativeResize: Bool[Literal[True]] + picLocks: Typed[PictureLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, preferRelativeResize: _ConvertibleToBool | None = None, picLocks=None, extLst: Unused = None) -> None: ... + +class PictureNonVisual(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvPicPr: Typed[NonVisualPictureProperties, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, cNvPr: NonVisualDrawingProps | None = None, cNvPicPr: NonVisualPictureProperties | None = None + ) -> None: ... + +class PictureFrame(Serialisable): + tagname: ClassVar[str] + macro: String[Literal[True]] + fPublished: Bool[Literal[True]] + nvPicPr: Typed[PictureNonVisual, Literal[False]] + blipFill: Typed[BlipFillProperties, Literal[False]] + spPr: Typed[GraphicalProperties, Literal[False]] + graphicalProperties: Alias + style: Typed[ShapeStyle, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + macro: str | None = None, + fPublished: _ConvertibleToBool | None = None, + nvPicPr: PictureNonVisual | None = None, + blipFill: BlipFillProperties | None = None, + spPr: GraphicalProperties | None = None, + style: ShapeStyle | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/properties.pyi b/stubs/openpyxl/openpyxl/drawing/properties.pyi new file mode 100644 index 000000000000..48aae4d92053 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/properties.pyi @@ -0,0 +1,120 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.geometry import GroupTransform2D, Scene3D +from openpyxl.drawing.text import Hyperlink + +_GroupShapePropertiesBwMode: TypeAlias = Literal[ + "clr", "auto", "gray", "ltGray", "invGray", "grayWhite", "blackGray", "blackWhite", "black", "white", "hidden" +] + +class GroupShapeProperties(Serialisable): + tagname: ClassVar[str] + bwMode: NoneSet[_GroupShapePropertiesBwMode] + xfrm: Typed[GroupTransform2D, Literal[True]] + scene3d: Typed[Scene3D, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + def __init__( + self, + bwMode: _GroupShapePropertiesBwMode | Literal["none"] | None = None, + xfrm: GroupTransform2D | None = None, + scene3d: Scene3D | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class GroupLocking(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + noGrp: Bool[Literal[True]] + noUngrp: Bool[Literal[True]] + noSelect: Bool[Literal[True]] + noRot: Bool[Literal[True]] + noChangeAspect: Bool[Literal[True]] + noMove: Bool[Literal[True]] + noResize: Bool[Literal[True]] + noChangeArrowheads: Bool[Literal[True]] + noEditPoints: Bool[Literal[True]] + noAdjustHandles: Bool[Literal[True]] + noChangeShapeType: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + noGrp: _ConvertibleToBool | None = None, + noUngrp: _ConvertibleToBool | None = None, + noSelect: _ConvertibleToBool | None = None, + noRot: _ConvertibleToBool | None = None, + noChangeAspect: _ConvertibleToBool | None = None, + noChangeArrowheads: _ConvertibleToBool | None = None, + noMove: _ConvertibleToBool | None = None, + noResize: _ConvertibleToBool | None = None, + noEditPoints: _ConvertibleToBool | None = None, + noAdjustHandles: _ConvertibleToBool | None = None, + noChangeShapeType: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class NonVisualGroupDrawingShapeProps(Serialisable): + tagname: ClassVar[str] + grpSpLocks: Typed[GroupLocking, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, grpSpLocks=None, extLst: Unused = None) -> None: ... + +class NonVisualDrawingShapeProps(Serialisable): + tagname: ClassVar[str] + spLocks: Typed[GroupLocking, Literal[True]] + txBax: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + txBox: Incomplete + def __init__(self, spLocks=None, txBox: _ConvertibleToBool | None = None, extLst: Unused = None) -> None: ... + +class NonVisualDrawingProps(Serialisable): + tagname: ClassVar[str] + id: Incomplete + name: String[Literal[False]] + descr: String[Literal[True]] + hidden: Bool[Literal[True]] + title: String[Literal[True]] + hlinkClick: Typed[Hyperlink, Literal[True]] + hlinkHover: Typed[Hyperlink, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + # Source incorrectly uses a list here instead of a tuple + __elements__: ClassVar[list[str]] # type: ignore[assignment] + + @overload + def __init__( + self, + id=None, + *, + name: str, + descr: str | None = None, + hidden: _ConvertibleToBool | None = None, + title: str | None = None, + hlinkClick: Hyperlink | None = None, + hlinkHover: Hyperlink | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: Incomplete | None, + name: str, + descr: str | None = None, + hidden: _ConvertibleToBool | None = None, + title: str | None = None, + hlinkClick: Hyperlink | None = None, + hlinkHover: Hyperlink | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class NonVisualGroupShape(Serialisable): + tagname: ClassVar[str] + cNvPr: Typed[NonVisualDrawingProps, Literal[False]] + cNvGrpSpPr: Typed[NonVisualGroupDrawingShapeProps, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cNvPr: NonVisualDrawingProps, cNvGrpSpPr: NonVisualGroupDrawingShapeProps) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/relation.pyi b/stubs/openpyxl/openpyxl/drawing/relation.pyi new file mode 100644 index 000000000000..46828b6f9767 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/relation.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class ChartRelation(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi b/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi new file mode 100644 index 000000000000..f675b423b091 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/spreadsheet_drawing.pyi @@ -0,0 +1,120 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.connector import Shape +from openpyxl.drawing.graphic import GraphicFrame, GroupShape +from openpyxl.drawing.picture import PictureFrame +from openpyxl.drawing.xdr import XDRPoint2D, XDRPositiveSize2D + +_TwoCellAnchorEditAs: TypeAlias = Literal["twoCell", "oneCell", "absolute"] + +class AnchorClientData(Serialisable): + fLocksWithSheet: Bool[Literal[True]] + fPrintsWithSheet: Bool[Literal[True]] + def __init__( + self, fLocksWithSheet: _ConvertibleToBool | None = None, fPrintsWithSheet: _ConvertibleToBool | None = None + ) -> None: ... + +class AnchorMarker(Serialisable): + tagname: ClassVar[str] + col: NestedText[int, Literal[False]] + colOff: NestedText[int, Literal[False]] + row: NestedText[int, Literal[False]] + rowOff: NestedText[int, Literal[False]] + def __init__( + self, col: ConvertibleToInt = 0, colOff: ConvertibleToInt = 0, row: ConvertibleToInt = 0, rowOff: ConvertibleToInt = 0 + ) -> None: ... + +class _AnchorBase(Serialisable): + sp: Typed[Shape, Literal[True]] + shape: Alias + grpSp: Typed[GroupShape, Literal[True]] + groupShape: Alias + graphicFrame: Typed[GraphicFrame, Literal[True]] + cxnSp: Typed[Shape, Literal[True]] + connectionShape: Alias + pic: Typed[PictureFrame, Literal[True]] + contentPart: Incomplete + clientData: Typed[AnchorClientData, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + clientData: AnchorClientData | None = None, + sp: Shape | None = None, + grpSp: GroupShape | None = None, + graphicFrame: GraphicFrame | None = None, + cxnSp: Shape | None = None, + pic: PictureFrame | None = None, + contentPart=None, + ) -> None: ... + +class AbsoluteAnchor(_AnchorBase): + tagname: ClassVar[str] + pos: Typed[XDRPoint2D, Literal[False]] + ext: Typed[XDRPositiveSize2D, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pos: XDRPoint2D | None = None, ext: XDRPositiveSize2D | None = None, **kw) -> None: ... + +class OneCellAnchor(_AnchorBase): + tagname: ClassVar[str] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + ext: Typed[XDRPositiveSize2D, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, _from: AnchorMarker | None = None, ext: XDRPositiveSize2D | None = None, **kw) -> None: ... + +class TwoCellAnchor(_AnchorBase): + tagname: ClassVar[str] + editAs: NoneSet[_TwoCellAnchorEditAs] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + to: Typed[AnchorMarker, Literal[False]] + # Same as parent + # sp = _AnchorBase.sp + # grpSp = _AnchorBase.grpSp + # graphicFrame = _AnchorBase.graphicFrame + # cxnSp = _AnchorBase.cxnSp + # pic = _AnchorBase.pic + # contentPart = _AnchorBase.contentPart + # clientData = _AnchorBase.clientData + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + editAs: _TwoCellAnchorEditAs | Literal["none"] | None = None, + _from: AnchorMarker | None = None, + to: AnchorMarker | None = None, + **kw, + ) -> None: ... + +class SpreadsheetDrawing(Serialisable): + tagname: ClassVar[str] + mime_type: str + PartName: str + twoCellAnchor: Incomplete + oneCellAnchor: Incomplete + absoluteAnchor: Incomplete + __elements__: ClassVar[tuple[str, ...]] + charts: Incomplete + images: Incomplete + def __init__(self, twoCellAnchor=(), oneCellAnchor=(), absoluteAnchor=()) -> None: ... + def __hash__(self) -> int: ... + def __bool__(self) -> bool: ... + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/drawing/text.pyi b/stubs/openpyxl/openpyxl/drawing/text.pyi new file mode 100644 index 000000000000..3ead43febde6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/text.pyi @@ -0,0 +1,515 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Integer, MinMax, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import Coordinate, ExtensionList +from openpyxl.descriptors.nested import EmptyTag, NestedBool, NestedInteger, NestedText, NestedValue +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.colors import ColorChoice, ColorChoiceDescriptor +from openpyxl.drawing.effect import Color, EffectContainer, EffectList +from openpyxl.drawing.fill import Blip, BlipFillProperties, GradientFillProperties, PatternFillProperties +from openpyxl.drawing.geometry import Scene3D +from openpyxl.drawing.line import LineProperties + +from ..xml._functions_overloads import _HasTagAndGet + +_CharacterPropertiesU: TypeAlias = Literal[ + "words", + "sng", + "dbl", + "heavy", + "dotted", + "dottedHeavy", + "dash", + "dashHeavy", + "dashLong", + "dashLongHeavy", + "dotDash", + "dotDashHeavy", + "dotDotDash", + "dotDotDashHeavy", + "wavy", + "wavyHeavy", + "wavyDbl", +] +_CharacterPropertiesStrike: TypeAlias = Literal["noStrike", "sngStrike", "dblStrike"] +_CharacterPropertiesCap: TypeAlias = Literal["small", "all"] +_ParagraphPropertiesAlgn: TypeAlias = Literal["l", "ctr", "r", "just", "justLow", "dist", "thaiDist"] +_ParagraphPropertiesFontAlgn: TypeAlias = Literal["auto", "t", "ctr", "base", "b"] +_RichTextPropertiesVertOverflow: TypeAlias = Literal["overflow", "ellipsis", "clip"] +_RichTextPropertiesHorzOverflow: TypeAlias = Literal["overflow", "clip"] +_RichTextPropertiesVert: TypeAlias = Literal[ + "horz", "vert", "vert270", "wordArtVert", "eaVert", "mongolianVert", "wordArtVertRtl" +] +_RichTextPropertiesWrap: TypeAlias = Literal["none", "square"] +_RichTextPropertiesAnchor: TypeAlias = Literal["t", "ctr", "b", "just", "dist"] +_AutonumberBulletType: TypeAlias = Literal[ + "alphaLcParenBoth", + "alphaUcParenBoth", + "alphaLcParenR", + "alphaUcParenR", + "alphaLcPeriod", + "alphaUcPeriod", + "arabicParenBoth", + "arabicParenR", + "arabicPeriod", + "arabicPlain", + "romanLcParenBoth", + "romanUcParenBoth", + "romanLcParenR", + "romanUcParenR", + "romanLcPeriod", + "romanUcPeriod", + "circleNumDbPlain", + "circleNumWdBlackPlain", + "circleNumWdWhitePlain", + "arabicDbPeriod", + "arabicDbPlain", + "ea1ChsPeriod", + "ea1ChsPlain", + "ea1ChtPeriod", + "ea1ChtPlain", + "ea1JpnChsDbPeriod", + "ea1JpnKorPlain", + "ea1JpnKorPeriod", + "arabic1Minus", + "arabic2Minus", + "hebrew2Minus", + "thaiAlphaPeriod", + "thaiAlphaParenR", + "thaiAlphaParenBoth", + "thaiNumPeriod", + "thaiNumParenR", + "thaiNumParenBoth", + "hindiAlphaPeriod", + "hindiNumPeriod", + "hindiNumParenR", + "hindiAlpha1Period", +] +_TabStopAlgn: TypeAlias = Literal["l", "ctr", "r", "dec"] +_PresetTextShapePrst: TypeAlias = Literal[ + "textNoShape", + "textPlain", + "textStop", + "textTriangle", + "textTriangleInverted", + "textChevron", + "textChevronInverted", + "textRingInside", + "textRingOutside", + "textArchUp", + "textArchDown", + "textCircle", + "textButton", + "textArchUpPour", + "textArchDownPour", + "textCirclePour", + "textButtonPour", + "textCurveUp", + "textCurveDown", + "textCanUp", + "textCanDown", + "textWave1", + "textWave2", + "textDoubleWave1", + "textWave4", + "textInflate", + "textDeflate", + "textInflateBottom", + "textDeflateBottom", + "textInflateTop", + "textDeflateTop", + "textDeflateInflate", + "textDeflateInflateDeflate", + "textFadeRight", + "textFadeLeft", + "textFadeUp", + "textFadeDown", + "textSlantUp", + "textSlantDown", + "textCascadeUp", + "textCascadeDown", +] + +class EmbeddedWAVAudioFile(Serialisable): + name: String[Literal[True]] + def __init__(self, name: str | None = None) -> None: ... + +class Hyperlink(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + invalidUrl: String[Literal[True]] + action: String[Literal[True]] + tgtFrame: String[Literal[True]] + tooltip: String[Literal[True]] + history: Bool[Literal[True]] + highlightClick: Bool[Literal[True]] + endSnd: Bool[Literal[True]] + snd: Typed[EmbeddedWAVAudioFile, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + invalidUrl: str | None = None, + action: str | None = None, + tgtFrame: str | None = None, + tooltip: str | None = None, + history: _ConvertibleToBool | None = None, + highlightClick: _ConvertibleToBool | None = None, + endSnd: _ConvertibleToBool | None = None, + snd: EmbeddedWAVAudioFile | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + +class Font(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + typeface: String[Literal[False]] + panose: Incomplete + pitchFamily: MinMax[float, Literal[True]] + charset: Integer[Literal[True]] + def __init__( + self, typeface: str, panose=None, pitchFamily: ConvertibleToFloat | None = None, charset: ConvertibleToInt | None = None + ) -> None: ... + +class CharacterProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + kumimoji: Bool[Literal[True]] + lang: String[Literal[True]] + altLang: String[Literal[True]] + sz: MinMax[float, Literal[True]] + b: Bool[Literal[True]] + i: Bool[Literal[True]] + u: NoneSet[_CharacterPropertiesU] + strike: NoneSet[_CharacterPropertiesStrike] + kern: Integer[Literal[True]] + cap: NoneSet[_CharacterPropertiesCap] + spc: Integer[Literal[True]] + normalizeH: Bool[Literal[True]] + baseline: Integer[Literal[True]] + noProof: Bool[Literal[True]] + dirty: Bool[Literal[True]] + err: Bool[Literal[True]] + smtClean: Bool[Literal[True]] + smtId: Integer[Literal[True]] + bmk: String[Literal[True]] + ln: Typed[LineProperties, Literal[True]] + highlight: Typed[Color, Literal[True]] + latin: Typed[Font, Literal[True]] + ea: Typed[Font, Literal[True]] + cs: Typed[Font, Literal[True]] + sym: Typed[Font, Literal[True]] + hlinkClick: Typed[Hyperlink, Literal[True]] + hlinkMouseOver: Typed[Hyperlink, Literal[True]] + rtl: NestedBool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + noFill: EmptyTag[Literal[False]] + solidFill: ColorChoiceDescriptor + gradFill: Typed[GradientFillProperties, Literal[True]] + blipFill: Typed[BlipFillProperties, Literal[True]] + pattFill: Typed[PatternFillProperties, Literal[True]] + grpFill: EmptyTag[Literal[False]] + effectLst: Typed[EffectList, Literal[True]] + effectDag: Typed[EffectContainer, Literal[True]] + uLnTx: EmptyTag[Literal[False]] + uLn: Typed[LineProperties, Literal[True]] + uFillTx: EmptyTag[Literal[False]] + uFill: EmptyTag[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + kumimoji: _ConvertibleToBool | None = None, + lang: str | None = None, + altLang: str | None = None, + sz: ConvertibleToFloat | None = None, + b: _ConvertibleToBool | None = None, + i: _ConvertibleToBool | None = None, + u: _CharacterPropertiesU | Literal["none"] | None = None, + strike: _CharacterPropertiesStrike | Literal["none"] | None = None, + kern: ConvertibleToInt | None = None, + cap: _CharacterPropertiesCap | Literal["none"] | None = None, + spc: ConvertibleToInt | None = None, + normalizeH: _ConvertibleToBool | None = None, + baseline: ConvertibleToInt | None = None, + noProof: _ConvertibleToBool | None = None, + dirty: _ConvertibleToBool | None = None, + err: _ConvertibleToBool | None = None, + smtClean: _ConvertibleToBool | None = None, + smtId: ConvertibleToInt | None = None, + bmk: str | None = None, + ln: LineProperties | None = None, + highlight: Color | None = None, + latin: Font | None = None, + ea: Font | None = None, + cs: Font | None = None, + sym: Font | None = None, + hlinkClick: Hyperlink | None = None, + hlinkMouseOver: Hyperlink | None = None, + rtl: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extLst: Unused = None, + noFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + solidFill: str | ColorChoice | None = None, + gradFill: GradientFillProperties | None = None, + blipFill: BlipFillProperties | None = None, + pattFill: PatternFillProperties | None = None, + grpFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + effectLst: EffectList | None = None, + effectDag: EffectContainer | None = None, + uLnTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + uLn: LineProperties | None = None, + uFillTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + uFill: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + ) -> None: ... + +class TabStop(Serialisable): + pos: Typed[Coordinate[bool], Literal[True]] + algn: Typed[Set[_TabStopAlgn], Literal[False]] + def __init__(self, pos: Coordinate[bool] | None = None, algn: Set[_TabStopAlgn] | None = None) -> None: ... + +class TabStopList(Serialisable): + tab: Typed[TabStop, Literal[True]] + def __init__(self, tab=None) -> None: ... + +class Spacing(Serialisable): + spcPct: NestedInteger[Literal[True]] + spcPts: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + spcPct: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + spcPts: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + ) -> None: ... + +class AutonumberBullet(Serialisable): + type: Set[_AutonumberBulletType] + startAt: Integer[Literal[False]] + def __init__(self, type: _AutonumberBulletType, startAt: ConvertibleToInt) -> None: ... + +class ParagraphProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + marL: Integer[Literal[True]] + marR: Integer[Literal[True]] + lvl: Integer[Literal[True]] + indent: Integer[Literal[True]] + algn: NoneSet[_ParagraphPropertiesAlgn] + defTabSz: Integer[Literal[True]] + rtl: Bool[Literal[True]] + eaLnBrk: Bool[Literal[True]] + fontAlgn: NoneSet[_ParagraphPropertiesFontAlgn] + latinLnBrk: Bool[Literal[True]] + hangingPunct: Bool[Literal[True]] + lnSpc: Typed[Spacing, Literal[True]] + spcBef: Typed[Spacing, Literal[True]] + spcAft: Typed[Spacing, Literal[True]] + tabLst: Typed[TabStopList, Literal[True]] + defRPr: Typed[CharacterProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + buClrTx: EmptyTag[Literal[False]] + buClr: Typed[Color, Literal[True]] + buSzTx: EmptyTag[Literal[False]] + buSzPct: NestedInteger[Literal[True]] + buSzPts: NestedInteger[Literal[True]] + buFontTx: EmptyTag[Literal[False]] + buFont: Typed[Font, Literal[True]] + buNone: EmptyTag[Literal[False]] + buAutoNum: EmptyTag[Literal[False]] + buChar: NestedValue[str, Literal[True]] + buBlip: NestedValue[Blip, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + marL: ConvertibleToInt | None = None, + marR: ConvertibleToInt | None = None, + lvl: ConvertibleToInt | None = None, + indent: ConvertibleToInt | None = None, + algn: _ParagraphPropertiesAlgn | Literal["none"] | None = None, + defTabSz: ConvertibleToInt | None = None, + rtl: _ConvertibleToBool | None = None, + eaLnBrk: _ConvertibleToBool | None = None, + fontAlgn: _ParagraphPropertiesFontAlgn | Literal["none"] | None = None, + latinLnBrk: _ConvertibleToBool | None = None, + hangingPunct: _ConvertibleToBool | None = None, + lnSpc: Spacing | None = None, + spcBef: Spacing | None = None, + spcAft: Spacing | None = None, + tabLst: TabStopList | None = None, + defRPr: CharacterProperties | None = None, + extLst: ExtensionList | None = None, + buClrTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buClr: Color | None = None, + buSzTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buSzPct: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + buSzPts: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + buFontTx: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buFont: Font | None = None, + buNone: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buAutoNum: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + buChar: object = None, + buBlip: object = None, + ) -> None: ... + +class ListStyle(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + defPPr: Typed[ParagraphProperties, Literal[True]] + lvl1pPr: Typed[ParagraphProperties, Literal[True]] + lvl2pPr: Typed[ParagraphProperties, Literal[True]] + lvl3pPr: Typed[ParagraphProperties, Literal[True]] + lvl4pPr: Typed[ParagraphProperties, Literal[True]] + lvl5pPr: Typed[ParagraphProperties, Literal[True]] + lvl6pPr: Typed[ParagraphProperties, Literal[True]] + lvl7pPr: Typed[ParagraphProperties, Literal[True]] + lvl8pPr: Typed[ParagraphProperties, Literal[True]] + lvl9pPr: Typed[ParagraphProperties, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + defPPr: ParagraphProperties | None = None, + lvl1pPr: ParagraphProperties | None = None, + lvl2pPr: ParagraphProperties | None = None, + lvl3pPr: ParagraphProperties | None = None, + lvl4pPr: ParagraphProperties | None = None, + lvl5pPr: ParagraphProperties | None = None, + lvl6pPr: ParagraphProperties | None = None, + lvl7pPr: ParagraphProperties | None = None, + lvl8pPr: ParagraphProperties | None = None, + lvl9pPr: ParagraphProperties | None = None, + extLst: ParagraphProperties | None = None, + ) -> None: ... + +class RegularTextRun(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rPr: Typed[CharacterProperties, Literal[True]] + properties: Alias + t: NestedText[str, Literal[False]] + value: Alias + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: CharacterProperties | None = None, t: object = "") -> None: ... + +class LineBreak(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rPr: Typed[CharacterProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, rPr: CharacterProperties | None = None) -> None: ... + +class TextField(Serialisable): + id: String[Literal[False]] + type: String[Literal[True]] + rPr: Typed[CharacterProperties, Literal[True]] + pPr: Typed[CharacterProperties, Literal[True]] + t: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + id: str, + type: str | None = None, + rPr: CharacterProperties | None = None, + pPr: CharacterProperties | None = None, + t: str | None = None, + ) -> None: ... + +class Paragraph(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + pPr: Typed[ParagraphProperties, Literal[True]] + properties: Alias + endParaRPr: Typed[CharacterProperties, Literal[True]] + r: Incomplete + text: Alias + br: Typed[LineBreak, Literal[True]] + fld: Typed[TextField, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + pPr: ParagraphProperties | None = None, + endParaRPr: CharacterProperties | None = None, + r=None, + br: LineBreak | None = None, + fld: TextField | None = None, + ) -> None: ... + +class GeomGuide(Serialisable): + name: String[Literal[False]] + fmla: String[Literal[False]] + def __init__(self, name: str, fmla: str) -> None: ... + +class GeomGuideList(Serialisable): + gd: Incomplete + def __init__(self, gd=None) -> None: ... + +class PresetTextShape(Serialisable): + prst: Typed[Set[_PresetTextShapePrst], Literal[False]] + avLst: Typed[GeomGuideList, Literal[True]] + def __init__(self, prst: Set[_PresetTextShapePrst], avLst: GeomGuideList | None = None) -> None: ... + +class TextNormalAutofit(Serialisable): + fontScale: Integer[Literal[False]] + lnSpcReduction: Integer[Literal[False]] + def __init__(self, fontScale: ConvertibleToInt, lnSpcReduction: ConvertibleToInt) -> None: ... + +class RichTextProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + rot: Integer[Literal[True]] + spcFirstLastPara: Bool[Literal[True]] + vertOverflow: NoneSet[_RichTextPropertiesVertOverflow] + horzOverflow: NoneSet[_RichTextPropertiesHorzOverflow] + vert: NoneSet[_RichTextPropertiesVert] + wrap: NoneSet[_RichTextPropertiesWrap] + lIns: Integer[Literal[True]] + tIns: Integer[Literal[True]] + rIns: Integer[Literal[True]] + bIns: Integer[Literal[True]] + numCol: Integer[Literal[True]] + spcCol: Integer[Literal[True]] + rtlCol: Bool[Literal[True]] + fromWordArt: Bool[Literal[True]] + anchor: NoneSet[_RichTextPropertiesAnchor] + anchorCtr: Bool[Literal[True]] + forceAA: Bool[Literal[True]] + upright: Bool[Literal[True]] + compatLnSpc: Bool[Literal[True]] + prstTxWarp: Typed[PresetTextShape, Literal[True]] + scene3d: Typed[Scene3D, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + noAutofit: EmptyTag[Literal[False]] + normAutofit: EmptyTag[Literal[False]] + spAutoFit: EmptyTag[Literal[False]] + flatTx: NestedInteger[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + rot: ConvertibleToInt | None = None, + spcFirstLastPara: _ConvertibleToBool | None = None, + vertOverflow: _RichTextPropertiesVertOverflow | Literal["none"] | None = None, + horzOverflow: _RichTextPropertiesHorzOverflow | Literal["none"] | None = None, + vert: _RichTextPropertiesVert | Literal["none"] | None = None, + wrap: _RichTextPropertiesWrap | Literal["none"] | None = None, + lIns: ConvertibleToInt | None = None, + tIns: ConvertibleToInt | None = None, + rIns: ConvertibleToInt | None = None, + bIns: ConvertibleToInt | None = None, + numCol: ConvertibleToInt | None = None, + spcCol: ConvertibleToInt | None = None, + rtlCol: _ConvertibleToBool | None = None, + fromWordArt: _ConvertibleToBool | None = None, + anchor: _RichTextPropertiesAnchor | Literal["none"] | None = None, + anchorCtr: _ConvertibleToBool | None = None, + forceAA: _ConvertibleToBool | None = None, + upright: _ConvertibleToBool | None = None, + compatLnSpc: _ConvertibleToBool | None = None, + prstTxWarp: PresetTextShape | None = None, + scene3d: Scene3D | None = None, + extLst: Unused = None, + noAutofit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + normAutofit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + spAutoFit: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + flatTx: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/drawing/xdr.pyi b/stubs/openpyxl/openpyxl/drawing/xdr.pyi new file mode 100644 index 000000000000..cab346f7587b --- /dev/null +++ b/stubs/openpyxl/openpyxl/drawing/xdr.pyi @@ -0,0 +1,26 @@ +from typing import ClassVar + +from .geometry import Point2D, PositiveSize2D, Transform2D + +class XDRPoint2D(Point2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # x = Point2D.x + # y = Point2D.y + +class XDRPositiveSize2D(PositiveSize2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # cx = PositiveSize2D.cx + # cy = PositiveSize2D.cy + +class XDRTransform2D(Transform2D): + namespace: ClassVar[None] # type: ignore[assignment] + # Same as parent + # rot = Transform2D.rot + # flipH = Transform2D.flipH + # flipV = Transform2D.flipV + # off = Transform2D.off + # ext = Transform2D.ext + # chOff = Transform2D.chOff + # chExt = Transform2D.chExt diff --git a/stubs/openpyxl/openpyxl/formatting/__init__.pyi b/stubs/openpyxl/openpyxl/formatting/__init__.pyi new file mode 100644 index 000000000000..c4e04ce61425 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/__init__.pyi @@ -0,0 +1 @@ +from .rule import Rule as Rule diff --git a/stubs/openpyxl/openpyxl/formatting/formatting.pyi b/stubs/openpyxl/openpyxl/formatting/formatting.pyi new file mode 100644 index 000000000000..9d6e9e423f1f --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/formatting.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Alias, Bool, Convertible, _ConvertibleToBool, _ConvertibleToMultiCellRange +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange + +class ConditionalFormatting(Serialisable): + tagname: ClassVar[str] + sqref: Convertible[MultiCellRange, Literal[False]] + cells: Alias + pivot: Bool[Literal[True]] + cfRule: Incomplete + rules: Alias + def __init__( + self, sqref: _ConvertibleToMultiCellRange = (), pivot: _ConvertibleToBool | None = None, cfRule=(), extLst: Unused = None + ) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __contains__(self, coord: str | CellRange) -> bool: ... + +class ConditionalFormattingList: + max_priority: int + def __init__(self) -> None: ... + def add(self, range_string, cfRule) -> None: ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[ConditionalFormatting]: ... + def __getitem__(self, key): ... + def __delitem__(self, key) -> None: ... + def __setitem__(self, key, rule) -> None: ... diff --git a/stubs/openpyxl/openpyxl/formatting/rule.pyi b/stubs/openpyxl/openpyxl/formatting/rule.pyi new file mode 100644 index 000000000000..35ab566356c6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formatting/rule.pyi @@ -0,0 +1,202 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors import Float, Strict +from openpyxl.descriptors.base import Bool, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor +from openpyxl.styles.differential import DifferentialStyle + +_IconSetIconSet: TypeAlias = Literal[ + "3Arrows", + "3ArrowsGray", + "3Flags", + "3TrafficLights1", + "3TrafficLights2", + "3Signs", + "3Symbols", + "3Symbols2", + "4Arrows", + "4ArrowsGray", + "4RedToBlack", + "4Rating", + "4TrafficLights", + "5Arrows", + "5ArrowsGray", + "5Rating", + "5Quarters", +] +_RuleOperator: TypeAlias = Literal[ + "lessThan", + "lessThanOrEqual", + "equal", + "notEqual", + "greaterThanOrEqual", + "greaterThan", + "between", + "notBetween", + "containsText", + "notContains", + "beginsWith", + "endsWith", +] +_RuleTimePeriod: TypeAlias = Literal[ + "today", "yesterday", "tomorrow", "last7Days", "thisMonth", "lastMonth", "nextMonth", "thisWeek", "lastWeek", "nextWeek" +] +_FormatObjectType: TypeAlias = Literal["num", "percent", "max", "min", "formula", "percentile"] +_RuleType: TypeAlias = Literal[ + "expression", + "cellIs", + "colorScale", + "dataBar", + "iconSet", + "top10", + "uniqueValues", + "duplicateValues", + "containsText", + "notContainsText", + "beginsWith", + "endsWith", + "containsBlanks", + "notContainsBlanks", + "containsErrors", + "notContainsErrors", + "timePeriod", + "aboveAverage", +] + +class ValueDescriptor(Float[Incomplete]): + expected_type: type[Incomplete] + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class FormatObject(Serialisable): + tagname: ClassVar[str] + type: Set[_FormatObjectType] + val: Incomplete + gte: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, type: _FormatObjectType, val=None, gte: _ConvertibleToBool | None = None, extLst: Unused = None + ) -> None: ... + +class RuleType(Serialisable): + cfvo: Incomplete + +class IconSet(RuleType): + tagname: ClassVar[str] + iconSet: NoneSet[_IconSetIconSet] + showValue: Bool[Literal[True]] + percent: Bool[Literal[True]] + reverse: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + def __init__( + self, + iconSet: _IconSetIconSet | Literal["none"] | None = None, + showValue: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + reverse: _ConvertibleToBool | None = None, + cfvo=None, + ) -> None: ... + +class DataBar(RuleType): + tagname: ClassVar[str] + minLength: Integer[Literal[True]] + maxLength: Integer[Literal[True]] + showValue: Bool[Literal[True]] + color: ColorDescriptor[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + + @overload + def __init__( + self, + minLength: ConvertibleToInt | None = None, + maxLength: ConvertibleToInt | None = None, + showValue: _ConvertibleToBool | None = None, + cfvo=None, + *, + color: str | Color, + ) -> None: ... + @overload + def __init__( + self, + minLength: ConvertibleToInt | None, + maxLength: ConvertibleToInt | None, + showValue: _ConvertibleToBool | None, + cfvo: Incomplete | None, + color: str | Color, + ) -> None: ... + +class ColorScale(RuleType): + tagname: ClassVar[str] + color: Incomplete + __elements__: ClassVar[tuple[str, ...]] + cfvo: Incomplete + def __init__(self, cfvo=None, color=None) -> None: ... + +class Rule(Serialisable): + tagname: ClassVar[str] + type: Set[_RuleType] + dxfId: Integer[Literal[True]] + priority: Integer[Literal[False]] + stopIfTrue: Bool[Literal[True]] + aboveAverage: Bool[Literal[True]] + percent: Bool[Literal[True]] + bottom: Bool[Literal[True]] + operator: NoneSet[_RuleOperator] + text: String[Literal[True]] + timePeriod: NoneSet[_RuleTimePeriod] + rank: Integer[Literal[True]] + stdDev: Integer[Literal[True]] + equalAverage: Bool[Literal[True]] + formula: Incomplete + colorScale: Typed[ColorScale, Literal[True]] + dataBar: Typed[DataBar, Literal[True]] + iconSet: Typed[IconSet, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + dxf: Typed[DifferentialStyle, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + type: _RuleType, + dxfId: ConvertibleToInt | None = None, + priority: ConvertibleToInt = 0, + stopIfTrue: _ConvertibleToBool | None = None, + aboveAverage: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + bottom: _ConvertibleToBool | None = None, + operator: _RuleOperator | Literal["none"] | None = None, + text: str | None = None, + timePeriod: _RuleTimePeriod | Literal["none"] | None = None, + rank: ConvertibleToInt | None = None, + stdDev: ConvertibleToInt | None = None, + equalAverage: _ConvertibleToBool | None = None, + formula=(), + colorScale: ColorScale | None = None, + dataBar: DataBar | None = None, + iconSet: IconSet | None = None, + extLst: Unused = None, + dxf: DifferentialStyle | None = None, + ) -> None: ... + +def ColorScaleRule( + start_type=None, + start_value=None, + start_color=None, + mid_type=None, + mid_value=None, + mid_color=None, + end_type=None, + end_value=None, + end_color=None, +): ... +def FormulaRule(formula=None, stopIfTrue=None, font=None, border=None, fill=None): ... +def CellIsRule(operator=None, formula=None, stopIfTrue=None, font=None, border=None, fill=None): ... +def IconSetRule(icon_style=None, type=None, values=None, showValue=None, percent=None, reverse=None): ... +def DataBarRule( + start_type=None, start_value=None, end_type=None, end_value=None, color=None, showValue=None, minLength=None, maxLength=None +): ... diff --git a/stubs/openpyxl/openpyxl/formula/__init__.pyi b/stubs/openpyxl/openpyxl/formula/__init__.pyi new file mode 100644 index 000000000000..c2decb330c52 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/__init__.pyi @@ -0,0 +1 @@ +from .tokenizer import Tokenizer as Tokenizer diff --git a/stubs/openpyxl/openpyxl/formula/tokenizer.pyi b/stubs/openpyxl/openpyxl/formula/tokenizer.pyi new file mode 100644 index 000000000000..f7b2e270b690 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/tokenizer.pyi @@ -0,0 +1,62 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final, Literal, TypeAlias + +_TokenTypesNotOperand: TypeAlias = Literal[ + "LITERAL", "FUNC", "ARRAY", "PAREN", "SEP", "OPERATOR-PREFIX", "OPERATOR-INFIX", "OPERATOR-POSTFIX", "WHITE-SPACE" +] +_TokenTypes: TypeAlias = Literal["OPERAND", _TokenTypesNotOperand] +_TokenOperandSubtypes: TypeAlias = Literal["TEXT", "NUMBER", "LOGICAL", "ERROR", "RANGE"] +_TokenSubtypes: TypeAlias = Literal["", _TokenOperandSubtypes, "OPEN", "CLOSE", "ARG", "ROW"] + +class TokenizerError(Exception): ... + +class Tokenizer: + SN_RE: Final[Pattern[str]] + WSPACE_RE: Final[Pattern[str]] + STRING_REGEXES: Final[dict[str, Pattern[str]]] + ERROR_CODES: Final[tuple[str, ...]] + TOKEN_ENDERS: Final = ",;}) +-*/^&=><%" + formula: Incomplete + items: Incomplete + token_stack: Incomplete + offset: int + token: Incomplete + def __init__(self, formula) -> None: ... + def check_scientific_notation(self): ... + def assert_empty_token(self, can_follow=()) -> None: ... + def save_token(self) -> None: ... + def render(self): ... + +class Token: + __slots__ = ["value", "type", "subtype"] + LITERAL: Final = "LITERAL" + OPERAND: Final = "OPERAND" + FUNC: Final = "FUNC" + ARRAY: Final = "ARRAY" + PAREN: Final = "PAREN" + SEP: Final = "SEP" + OP_PRE: Final = "OPERATOR-PREFIX" + OP_IN: Final = "OPERATOR-INFIX" + OP_POST: Final = "OPERATOR-POSTFIX" + WSPACE: Final = "WHITE-SPACE" + value: Incomplete + type: _TokenTypes + subtype: _TokenSubtypes + def __init__(self, value, type_: _TokenTypes, subtype: _TokenSubtypes = "") -> None: ... + TEXT: Final = "TEXT" + NUMBER: Final = "NUMBER" + LOGICAL: Final = "LOGICAL" + ERROR: Final = "ERROR" + RANGE: Final = "RANGE" + @classmethod + def make_operand(cls, value): ... + OPEN: Final = "OPEN" + CLOSE: Final = "CLOSE" + @classmethod + def make_subexp(cls, value, func: bool = False): ... + def get_closer(self): ... + ARG: Final = "ARG" + ROW: Final = "ROW" + @classmethod + def make_separator(cls, value): ... diff --git a/stubs/openpyxl/openpyxl/formula/translate.pyi b/stubs/openpyxl/openpyxl/formula/translate.pyi new file mode 100644 index 000000000000..212f0bedd006 --- /dev/null +++ b/stubs/openpyxl/openpyxl/formula/translate.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final + +class TranslatorError(Exception): ... + +class Translator: + tokenizer: Incomplete + def __init__(self, formula, origin) -> None: ... + def get_tokens(self): ... + ROW_RANGE_RE: Final[Pattern[str]] + COL_RANGE_RE: Final[Pattern[str]] + CELL_REF_RE: Final[Pattern[str]] + @staticmethod + def translate_row(row_str, rdelta): ... + @staticmethod + def translate_col(col_str, cdelta): ... + @staticmethod + def strip_ws_name(range_str): ... + @classmethod + def translate_range(cls, range_str, rdelta, cdelta): ... + def translate_formula(self, dest=None, row_delta: int = 0, col_delta: int = 0): ... diff --git a/stubs/openpyxl/openpyxl/packaging/__init__.pyi b/stubs/openpyxl/openpyxl/packaging/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/openpyxl/openpyxl/packaging/core.pyi b/stubs/openpyxl/openpyxl/packaging/core.pyi new file mode 100644 index 000000000000..d42e5a6adc5f --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/core.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from datetime import datetime +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors import DateTime +from openpyxl.descriptors.base import Alias +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +# Does not reimplement the relevant methods, so runtime also has incompatible supertypes +class NestedDateTime(DateTime[Incomplete], NestedText[Incomplete, Incomplete]): # type: ignore[misc] + expected_type: type[Incomplete] + + @overload # type: ignore[override] + def to_tree(self, tagname: str | None = None, value: None = None, namespace: str | None = None) -> None: ... + @overload + def to_tree(self, tagname: str, value: datetime, namespace: str | None = None) -> Element: ... + +class QualifiedDateTime(NestedDateTime): + # value cannot be None or it'll raise + def to_tree(self, tagname: str, value: datetime, namespace: str | None = None) -> Element: ... # type: ignore[override] + +class DocumentProperties(Serialisable): + tagname: ClassVar[str] + namespace: ClassVar[str] + category: NestedText[str, Literal[True]] + contentStatus: NestedText[str, Literal[True]] + keywords: NestedText[str, Literal[True]] + lastModifiedBy: NestedText[str, Literal[True]] + lastPrinted: Incomplete + revision: NestedText[str, Literal[True]] + version: NestedText[str, Literal[True]] + last_modified_by: Alias + subject: NestedText[str, Literal[True]] + title: NestedText[str, Literal[True]] + creator: NestedText[str, Literal[True]] + description: NestedText[str, Literal[True]] + identifier: NestedText[str, Literal[True]] + language: NestedText[str, Literal[True]] + created: Incomplete + modified: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + category: object = None, + contentStatus: object = None, + keywords: object = None, + lastModifiedBy: object = None, + lastPrinted=None, + revision: object = None, + version: object = None, + created=None, + creator: object = "openpyxl", + description: object = None, + identifier: object = None, + language: object = None, + modified=None, + subject: object = None, + title: object = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/custom.pyi b/stubs/openpyxl/openpyxl/packaging/custom.pyi new file mode 100644 index 000000000000..8721ae124986 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/custom.pyi @@ -0,0 +1,66 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from collections.abc import Iterator +from datetime import datetime +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors import Sequence, Strict +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement +from openpyxl.xml.functions import Element + +_T = TypeVar("_T") + +# Does not reimplement anything, so runtime also has incompatible supertypes +class NestedBoolText(Bool[Incomplete], NestedText[Incomplete, Incomplete]): ... # type: ignore[misc] + +class _TypedProperty(Strict, Generic[_T]): + name: String[Literal[False]] + # Since this is internal, just list all possible values + value: ( + Integer[Literal[False]] + | Float[Literal[False]] + | String[Literal[True]] + | DateTime[Literal[False]] + | Bool[Literal[False]] + | String[Literal[False]] + ) + def __init__(self, name: str, value: _T) -> None: ... + def __eq__(self, other: _TypedProperty[Any]) -> bool: ... # type: ignore[override] + +class IntProperty(_TypedProperty[ConvertibleToInt]): + value: Integer[Literal[False]] + +class FloatProperty(_TypedProperty[ConvertibleToFloat]): + value: Float[Literal[False]] + +class StringProperty(_TypedProperty[str | None]): + value: String[Literal[True]] + +class DateTimeProperty(_TypedProperty[datetime]): + value: DateTime[Literal[False]] + +class BoolProperty(_TypedProperty[_ConvertibleToBool]): + value: Bool[Literal[False]] + +class LinkProperty(_TypedProperty[str]): + value: String[Literal[False]] + +_MappingPropertyType: TypeAlias = StringProperty | IntProperty | FloatProperty | DateTimeProperty | BoolProperty | LinkProperty +CLASS_MAPPING: Final[dict[type[_MappingPropertyType], str]] +XML_MAPPING: Final[dict[str, type[_MappingPropertyType]]] + +class CustomPropertyList(Strict, Generic[_T]): + props: Sequence[list[_TypedProperty[_T]]] + def __init__(self) -> None: ... + @classmethod + def from_tree(cls, tree: _ChildSerialisableTreeElement) -> Self: ... + def append(self, prop) -> None: ... + def to_tree(self) -> Element: ... + def __len__(self) -> int: ... + @property + def names(self) -> list[str]: ... + def __getitem__(self, name): ... + def __delitem__(self, name) -> None: ... + def __iter__(self) -> Iterator[_TypedProperty[_T]]: ... diff --git a/stubs/openpyxl/openpyxl/packaging/extended.pyi b/stubs/openpyxl/openpyxl/packaging/extended.pyi new file mode 100644 index 000000000000..5f8d7fd051a5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/extended.pyi @@ -0,0 +1,81 @@ +from _typeshed import ConvertibleToInt, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class DigSigBlob(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class VectorLpstr(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class VectorVariant(Serialisable): + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + +class ExtendedProperties(Serialisable): + tagname: ClassVar[str] + Template: NestedText[str, Literal[True]] + Manager: NestedText[str, Literal[True]] + Company: NestedText[str, Literal[True]] + Pages: NestedText[int, Literal[True]] + Words: NestedText[int, Literal[True]] + Characters: NestedText[int, Literal[True]] + PresentationFormat: NestedText[str, Literal[True]] + Lines: NestedText[int, Literal[True]] + Paragraphs: NestedText[int, Literal[True]] + Slides: NestedText[int, Literal[True]] + Notes: NestedText[int, Literal[True]] + TotalTime: NestedText[int, Literal[True]] + HiddenSlides: NestedText[int, Literal[True]] + MMClips: NestedText[int, Literal[True]] + ScaleCrop: NestedText[str, Literal[True]] + HeadingPairs: Typed[VectorVariant, Literal[True]] + TitlesOfParts: Typed[VectorLpstr, Literal[True]] + LinksUpToDate: NestedText[str, Literal[True]] + CharactersWithSpaces: NestedText[int, Literal[True]] + SharedDoc: NestedText[str, Literal[True]] + HyperlinkBase: NestedText[str, Literal[True]] + HLinks: Typed[VectorVariant, Literal[True]] + HyperlinksChanged: NestedText[str, Literal[True]] + DigSig: Typed[DigSigBlob, Literal[True]] + Application: NestedText[str, Literal[True]] + AppVersion: NestedText[str, Literal[True]] + DocSecurity: NestedText[int, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + Template: object = None, + Manager: object = None, + Company: object = None, + Pages: ConvertibleToInt | None = None, + Words: ConvertibleToInt | None = None, + Characters: ConvertibleToInt | None = None, + PresentationFormat: object = None, + Lines: ConvertibleToInt | None = None, + Paragraphs: ConvertibleToInt | None = None, + Slides: ConvertibleToInt | None = None, + Notes: ConvertibleToInt | None = None, + TotalTime: ConvertibleToInt | None = None, + HiddenSlides: ConvertibleToInt | None = None, + MMClips: ConvertibleToInt | None = None, + ScaleCrop: object = None, + HeadingPairs: Unused = None, + TitlesOfParts: Unused = None, + LinksUpToDate: object = None, + CharactersWithSpaces: ConvertibleToInt | None = None, + SharedDoc: object = None, + HyperlinkBase: object = None, + HLinks: Unused = None, + HyperlinksChanged: object = None, + DigSig: Unused = None, + Application: Unused = None, + AppVersion: str | None = None, + DocSecurity: ConvertibleToInt | None = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/packaging/interface.pyi b/stubs/openpyxl/openpyxl/packaging/interface.pyi new file mode 100644 index 000000000000..45a7da1114ea --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/interface.pyi @@ -0,0 +1,8 @@ +from abc import ABC, abstractmethod + +# This interface is unused. Nothing implements `id` as property either. +# IDs can be ints, strings, None, or a Descriptor returning those throughout the codebase. +class ISerialisableFile(ABC): + @property + @abstractmethod + def id(self) -> str | int | None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/manifest.pyi b/stubs/openpyxl/openpyxl/packaging/manifest.pyi new file mode 100644 index 000000000000..9700c10e2871 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/manifest.pyi @@ -0,0 +1,41 @@ +from _typeshed import Incomplete +from collections.abc import Generator +from typing import ClassVar, Final, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +mimetypes: Incomplete + +class FileExtension(Serialisable): + tagname: ClassVar[str] + Extension: String[Literal[False]] + ContentType: String[Literal[False]] + def __init__(self, Extension: str, ContentType: str) -> None: ... + +class Override(Serialisable): + tagname: ClassVar[str] + PartName: String[Literal[False]] + ContentType: String[Literal[False]] + def __init__(self, PartName: str, ContentType: str) -> None: ... + +DEFAULT_TYPES: Final[list[FileExtension]] +DEFAULT_OVERRIDE: Final[list[Override]] + +class Manifest(Serialisable): + tagname: ClassVar[str] + Default: Incomplete + Override: Incomplete + path: str + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, Default=(), Override=()) -> None: ... + @property + def filenames(self) -> list[str]: ... + @property + def extensions(self) -> list[tuple[str, str]]: ... + def to_tree(self) -> Element: ... # type: ignore[override] + def __contains__(self, content_type: str) -> bool: ... + def find(self, content_type): ... + def findall(self, content_type) -> Generator[Incomplete]: ... + def append(self, obj) -> None: ... diff --git a/stubs/openpyxl/openpyxl/packaging/relationship.pyi b/stubs/openpyxl/openpyxl/packaging/relationship.pyi new file mode 100644 index 000000000000..ca6bbb0b97f5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/relationship.pyi @@ -0,0 +1,57 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator +from typing import ClassVar, Literal, TypeVar, overload +from zipfile import ZipFile + +from openpyxl.descriptors.base import Alias, String +from openpyxl.descriptors.container import ElementList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.pivot.cache import CacheDefinition +from openpyxl.pivot.record import RecordList +from openpyxl.pivot.table import TableDefinition + +_SerialisableT = TypeVar("_SerialisableT", bound=Serialisable) +_SerialisableRelTypeT = TypeVar("_SerialisableRelTypeT", bound=CacheDefinition | RecordList | TableDefinition) + +class Relationship(Serialisable): + tagname: ClassVar[str] + Type: String[Literal[False]] + Target: String[Literal[False]] + target: Alias + TargetMode: String[Literal[True]] + Id: String[Literal[True]] + id: Alias + + @overload + def __init__( + self, Id: str, Type: Unused = None, *, type: str, Target: str | None = None, TargetMode: str | None = None + ) -> None: ... + @overload + def __init__(self, Id: str, Type: Unused, type: str, Target: str | None = None, TargetMode: str | None = None) -> None: ... + @overload + def __init__( + self, Id: str, Type: str, type: None = None, Target: str | None = None, TargetMode: str | None = None + ) -> None: ... + +class RelationshipList(ElementList[Relationship]): + expected_type: type[Relationship] + def find(self, content_type: str) -> Generator[Relationship]: ... + def get(self, key: str) -> Relationship: ... + def to_dict(self) -> dict[Incomplete, Relationship]: ... + +def get_rels_path(path): ... +def get_dependents(archive: ZipFile, filename: str) -> RelationshipList: ... + +# If `id` is None, `cls` needs to have ClassVar `rel_type`. +# The `deps` attribute used at runtime is for internal use immediately after the return. +# `cls` cannot be None +@overload +def get_rel( + archive: ZipFile, deps: RelationshipList, id: None = None, *, cls: type[_SerialisableRelTypeT] +) -> _SerialisableRelTypeT | None: ... +@overload +def get_rel( + archive: ZipFile, deps: RelationshipList, id: None, cls: type[_SerialisableRelTypeT] +) -> _SerialisableRelTypeT | None: ... +@overload +def get_rel(archive: ZipFile, deps: RelationshipList, id: str, cls: type[_SerialisableT]) -> _SerialisableT: ... diff --git a/stubs/openpyxl/openpyxl/packaging/workbook.pyi b/stubs/openpyxl/openpyxl/packaging/workbook.pyi new file mode 100644 index 000000000000..5eeb46b36fea --- /dev/null +++ b/stubs/openpyxl/openpyxl/packaging/workbook.pyi @@ -0,0 +1,100 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Alias, Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedString +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.defined_name import DefinedNameList +from openpyxl.workbook.function_group import FunctionGroupList +from openpyxl.workbook.properties import CalcProperties, FileVersion, WorkbookProperties +from openpyxl.workbook.protection import FileSharing, WorkbookProtection +from openpyxl.workbook.smart_tags import SmartTagList, SmartTagProperties +from openpyxl.workbook.web import WebPublishing, WebPublishObjectList +from openpyxl.xml.functions import Element + +_WorkbookPackageConformance: TypeAlias = Literal["strict", "transitional"] + +class FileRecoveryProperties(Serialisable): + tagname: ClassVar[str] + autoRecover: Bool[Literal[True]] + crashSave: Bool[Literal[True]] + dataExtractLoad: Bool[Literal[True]] + repairLoad: Bool[Literal[True]] + def __init__( + self, + autoRecover: _ConvertibleToBool | None = None, + crashSave: _ConvertibleToBool | None = None, + dataExtractLoad: _ConvertibleToBool | None = None, + repairLoad: _ConvertibleToBool | None = None, + ) -> None: ... + +class ChildSheet(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + sheetId: Integer[Literal[False]] + state: NoneSet[_VisibilityType] + id: Incomplete + def __init__( + self, name: str, sheetId: ConvertibleToInt, state: _VisibilityType | Literal["none"] | None = "visible", id=None + ) -> None: ... + +class PivotCache(Serialisable): + tagname: ClassVar[str] + cacheId: Integer[Literal[False]] + id: Incomplete + def __init__(self, cacheId: ConvertibleToInt, id=None) -> None: ... + +class WorkbookPackage(Serialisable): + tagname: ClassVar[str] + conformance: NoneSet[_WorkbookPackageConformance] + fileVersion: Typed[FileVersion, Literal[True]] + fileSharing: Typed[FileSharing, Literal[True]] + workbookPr: Typed[WorkbookProperties, Literal[True]] + properties: Alias + workbookProtection: Typed[WorkbookProtection, Literal[True]] + bookViews: Incomplete + sheets: Incomplete # NestedSequence[ChildSheet] + functionGroups: Typed[FunctionGroupList, Literal[True]] + externalReferences: Incomplete + definedNames: Typed[DefinedNameList, Literal[True]] + calcPr: Typed[CalcProperties, Literal[True]] + oleSize: NestedString[Literal[True]] + customWorkbookViews: Incomplete + pivotCaches: Incomplete + smartTagPr: Typed[SmartTagProperties, Literal[True]] + smartTagTypes: Typed[SmartTagList, Literal[True]] + webPublishing: Typed[WebPublishing, Literal[True]] + fileRecoveryPr: Typed[FileRecoveryProperties, Literal[True]] + webPublishObjects: Typed[WebPublishObjectList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + Ignorable: NestedString[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + conformance: _WorkbookPackageConformance | Literal["none"] | None = None, + fileVersion: FileVersion | None = None, + fileSharing: FileSharing | None = None, + workbookPr: WorkbookProperties | None = None, + workbookProtection: WorkbookProtection | None = None, + bookViews=(), + sheets=(), + functionGroups: FunctionGroupList | None = None, + externalReferences=(), + definedNames: DefinedNameList | None = None, + calcPr: CalcProperties | None = None, + oleSize: object = None, + customWorkbookViews=(), + pivotCaches=(), + smartTagPr: SmartTagProperties | None = None, + smartTagTypes: SmartTagList | None = None, + webPublishing: WebPublishing | None = None, + fileRecoveryPr: FileRecoveryProperties | None = None, + webPublishObjects: WebPublishObjectList | None = None, + extLst: Unused = None, + Ignorable: Unused = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def active(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/pivot/__init__.pyi b/stubs/openpyxl/openpyxl/pivot/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/openpyxl/openpyxl/pivot/cache.pyi b/stubs/openpyxl/openpyxl/pivot/cache.pyi new file mode 100644 index 000000000000..e2fc7b3f73dc --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/cache.pyi @@ -0,0 +1,649 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from datetime import datetime +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.nested import NestedInteger +from openpyxl.descriptors.sequence import NestedSequence +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.pivot.fields import Error, Missing, Number, Text, TupleList +from openpyxl.pivot.table import PivotArea +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasTagAndGet + +_RangePrGroupBy: TypeAlias = Literal["range", "seconds", "minutes", "hours", "days", "months", "quarters", "years"] +_CacheSourceType: TypeAlias = Literal["worksheet", "external", "consolidation", "scenario"] + +class MeasureDimensionMap(Serialisable): + tagname: ClassVar[str] + measureGroup: Integer[Literal[True]] + dimension: Integer[Literal[True]] + def __init__(self, measureGroup: ConvertibleToInt | None = None, dimension: ConvertibleToInt | None = None) -> None: ... + +class MeasureGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + caption: String[Literal[False]] + def __init__(self, name: str, caption: str) -> None: ... + +class PivotDimension(Serialisable): + tagname: ClassVar[str] + measure: Bool[Literal[False]] + name: String[Literal[False]] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + + @overload + def __init__(self, measure: _ConvertibleToBool = None, *, name: str, uniqueName: str, caption: str) -> None: ... + @overload + def __init__(self, measure: _ConvertibleToBool, name: str, uniqueName: str, caption: str) -> None: ... + +class CalculatedMember(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + mdx: String[Literal[False]] + memberName: String[Literal[True]] + hierarchy: String[Literal[True]] + parent: String[Literal[True]] + solveOrder: Integer[Literal[True]] + set: Bool[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + mdx: str, + memberName: str, + hierarchy: str, + parent: str, + solveOrder: ConvertibleToInt, + set: _ConvertibleToBool = None, + extLst: Unused = None, + ) -> None: ... + +class CalculatedItem(Serialisable): + tagname: ClassVar[str] + field: Integer[Literal[True]] + formula: String[Literal[False]] + pivotArea: Typed[PivotArea, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__(self, field: ConvertibleToInt | None = None, *, formula: str, pivotArea: PivotArea, extLst=None) -> None: ... + @overload + def __init__(self, field: ConvertibleToInt | None, formula: str, pivotArea: PivotArea, extLst=None) -> None: ... + +class ServerFormat(Serialisable): + tagname: ClassVar[str] + culture: String[Literal[True]] + format: String[Literal[True]] + def __init__(self, culture: str | None = None, format: str | None = None) -> None: ... + +class Query(Serialisable): + tagname: ClassVar[str] + mdx: String[Literal[False]] + tpls: Typed[TupleList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, mdx: str, tpls: TupleList | None = None) -> None: ... + +class OLAPSet(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[False]] + maxRank: Integer[Literal[False]] + setDefinition: String[Literal[False]] + sortType: Incomplete + queryFailed: Bool[Literal[False]] + tpls: Typed[TupleList, Literal[True]] + sortByTuple: Typed[TupleList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + count: ConvertibleToInt, + maxRank: ConvertibleToInt, + setDefinition: str, + sortType=None, + queryFailed: _ConvertibleToBool = None, + tpls: TupleList | None = None, + sortByTuple: TupleList | None = None, + ) -> None: ... + +class PCDSDTCEntries(Serialisable): + tagname: ClassVar[str] + count: Integer[Literal[True]] + m: Typed[Missing, Literal[True]] + n: Typed[Number, Literal[True]] + e: Typed[Error, Literal[True]] + s: Typed[Text, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt, m: Missing, n: Number, e: Error, s: Text) -> None: ... + +class TupleCache(Serialisable): + tagname: ClassVar[str] + entries: Typed[PCDSDTCEntries, Literal[True]] + sets: NestedSequence[list[OLAPSet]] + queryCache: NestedSequence[list[Query]] + serverFormats: NestedSequence[list[ServerFormat]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + entries: PCDSDTCEntries | None = None, + sets: list[OLAPSet] | tuple[OLAPSet, ...] = (), + queryCache: list[Query] | tuple[Query, ...] = (), + serverFormats: list[ServerFormat] | tuple[ServerFormat, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class OLAPKPI(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[True]] + displayFolder: String[Literal[True]] + measureGroup: String[Literal[True]] + parent: String[Literal[True]] + value: String[Literal[False]] + goal: String[Literal[True]] + status: String[Literal[True]] + trend: String[Literal[True]] + weight: String[Literal[True]] + time: String[Literal[True]] + def __init__( + self, + uniqueName: str | None = None, + caption: str | None = None, + displayFolder: str | None = None, + measureGroup: str | None = None, + parent: str | None = None, + value: str | None = None, + goal: str | None = None, + status: str | None = None, + trend: str | None = None, + weight: str | None = None, + time: str | None = None, + ) -> None: ... + +class GroupMember(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + group: Bool[Literal[False]] + def __init__(self, uniqueName: str, group: _ConvertibleToBool = None) -> None: ... + +class LevelGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + uniqueParent: String[Literal[False]] + id: Integer[Literal[False]] + groupMembers: NestedSequence[list[GroupMember]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + uniqueName: str, + caption: str, + uniqueParent: str, + id: ConvertibleToInt, + groupMembers: list[GroupMember] | tuple[GroupMember, ...] = (), + ) -> None: ... + +class GroupLevel(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[False]] + user: Bool[Literal[False]] + customRollUp: Bool[Literal[False]] + groups: NestedSequence[list[LevelGroup]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + uniqueName: str, + caption: str, + user: _ConvertibleToBool = None, + customRollUp: _ConvertibleToBool = None, + groups: list[LevelGroup] | tuple[LevelGroup, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class FieldUsage(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt) -> None: ... + +class CacheHierarchy(Serialisable): + tagname: ClassVar[str] + uniqueName: String[Literal[False]] + caption: String[Literal[True]] + measure: Bool[Literal[False]] + set: Bool[Literal[False]] + parentSet: Integer[Literal[True]] + iconSet: Integer[Literal[False]] + attribute: Bool[Literal[False]] + time: Bool[Literal[False]] + keyAttribute: Bool[Literal[False]] + defaultMemberUniqueName: String[Literal[True]] + allUniqueName: String[Literal[True]] + allCaption: String[Literal[True]] + dimensionUniqueName: String[Literal[True]] + displayFolder: String[Literal[True]] + measureGroup: String[Literal[True]] + measures: Bool[Literal[False]] + count: Integer[Literal[False]] + oneField: Bool[Literal[False]] + memberValueDatatype: Integer[Literal[True]] + unbalanced: Bool[Literal[True]] + unbalancedGroup: Bool[Literal[True]] + hidden: Bool[Literal[False]] + fieldsUsage: NestedSequence[list[FieldUsage]] + groupLevels: NestedSequence[list[GroupLevel]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + uniqueName: str = "", + caption: str | None = None, + measure: _ConvertibleToBool = None, + set: _ConvertibleToBool = None, + parentSet: ConvertibleToInt | None = None, + iconSet: ConvertibleToInt = 0, + attribute: _ConvertibleToBool = None, + time: _ConvertibleToBool = None, + keyAttribute: _ConvertibleToBool = None, + defaultMemberUniqueName: str | None = None, + allUniqueName: str | None = None, + allCaption: str | None = None, + dimensionUniqueName: str | None = None, + displayFolder: str | None = None, + measureGroup: str | None = None, + measures: _ConvertibleToBool = None, + *, + count: ConvertibleToInt, + oneField: _ConvertibleToBool = None, + memberValueDatatype: ConvertibleToInt | None = None, + unbalanced: _ConvertibleToBool | None = None, + unbalancedGroup: _ConvertibleToBool | None = None, + hidden: _ConvertibleToBool = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + uniqueName: str, + caption: str | None, + measure: _ConvertibleToBool, + set: _ConvertibleToBool, + parentSet: ConvertibleToInt | None, + iconSet: ConvertibleToInt, + attribute: _ConvertibleToBool, + time: _ConvertibleToBool, + keyAttribute: _ConvertibleToBool, + defaultMemberUniqueName: str | None, + allUniqueName: str | None, + allCaption: str | None, + dimensionUniqueName: str | None, + displayFolder: str | None, + measureGroup: str | None, + measures: _ConvertibleToBool, + count: ConvertibleToInt, + oneField: _ConvertibleToBool = None, + memberValueDatatype: ConvertibleToInt | None = None, + unbalanced: _ConvertibleToBool | None = None, + unbalancedGroup: _ConvertibleToBool | None = None, + hidden: _ConvertibleToBool = None, + fieldsUsage: list[FieldUsage] | tuple[FieldUsage, ...] = (), + groupLevels: list[FieldUsage] | tuple[FieldUsage, ...] = (), + extLst: ExtensionList | None = None, + ) -> None: ... + +class GroupItems(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, m=(), n=(), b=(), e=(), s=(), d=()) -> None: ... + @property + def count(self) -> int: ... + +class RangePr(Serialisable): + tagname: ClassVar[str] + autoStart: Bool[Literal[True]] + autoEnd: Bool[Literal[True]] + groupBy: NoneSet[_RangePrGroupBy] + startNum: Float[Literal[True]] + endNum: Float[Literal[True]] + startDate: DateTime[Literal[True]] + endDate: DateTime[Literal[True]] + groupInterval: Float[Literal[True]] + def __init__( + self, + autoStart: _ConvertibleToBool | None = True, + autoEnd: _ConvertibleToBool | None = True, + groupBy: _RangePrGroupBy = "range", + startNum: ConvertibleToFloat | None = None, + endNum: ConvertibleToFloat | None = None, + startDate: datetime | str | None = None, + endDate: datetime | str | None = None, + groupInterval: ConvertibleToFloat | None = 1, + ) -> None: ... + +class FieldGroup(Serialisable): + tagname: ClassVar[str] + par: Integer[Literal[True]] + base: Integer[Literal[True]] + rangePr: Typed[RangePr, Literal[True]] + discretePr: NestedSequence[list[NestedInteger[Literal[False]]]] + groupItems: Typed[GroupItems, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + par: ConvertibleToInt | None = None, + base: ConvertibleToInt | None = None, + rangePr: RangePr | None = None, + discretePr: list[NestedInteger[Literal[False]]] | tuple[NestedInteger[Literal[False]], ...] = (), + groupItems: GroupItems | None = None, + ) -> None: ... + +class SharedItems(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + containsSemiMixedTypes: Bool[Literal[True]] + containsNonDate: Bool[Literal[True]] + containsDate: Bool[Literal[True]] + containsString: Bool[Literal[True]] + containsBlank: Bool[Literal[True]] + containsMixedTypes: Bool[Literal[True]] + containsNumber: Bool[Literal[True]] + containsInteger: Bool[Literal[True]] + minValue: Float[Literal[True]] + maxValue: Float[Literal[True]] + minDate: DateTime[Literal[True]] + maxDate: DateTime[Literal[True]] + longText: Bool[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + _fields=(), + containsSemiMixedTypes: _ConvertibleToBool | None = None, + containsNonDate: _ConvertibleToBool | None = None, + containsDate: _ConvertibleToBool | None = None, + containsString: _ConvertibleToBool | None = None, + containsBlank: _ConvertibleToBool | None = None, + containsMixedTypes: _ConvertibleToBool | None = None, + containsNumber: _ConvertibleToBool | None = None, + containsInteger: _ConvertibleToBool | None = None, + minValue: ConvertibleToFloat | None = None, + maxValue: ConvertibleToFloat | None = None, + minDate: datetime | str | None = None, + maxDate: datetime | str | None = None, + count: Unused = None, + longText: _ConvertibleToBool | None = None, + ) -> None: ... + @property + def count(self) -> int: ... + +class CacheField(Serialisable): + tagname: ClassVar[str] + sharedItems: Typed[SharedItems, Literal[True]] + fieldGroup: Typed[FieldGroup, Literal[True]] + mpMap: NestedInteger[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + name: String[Literal[False]] + caption: String[Literal[True]] + propertyName: String[Literal[True]] + serverField: Bool[Literal[True]] + uniqueList: Bool[Literal[True]] + numFmtId: Integer[Literal[True]] + formula: String[Literal[True]] + sqlType: Integer[Literal[True]] + hierarchy: Integer[Literal[True]] + level: Integer[Literal[True]] + databaseField: Bool[Literal[True]] + mappingCount: Integer[Literal[True]] + memberPropertyField: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + sharedItems: SharedItems | None = None, + fieldGroup: FieldGroup | None = None, + mpMap: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + *, + name: str, + caption: str | None = None, + propertyName: str | None = None, + serverField: _ConvertibleToBool | None = None, + uniqueList: _ConvertibleToBool | None = True, + numFmtId: ConvertibleToInt | None = None, + formula: str | None = None, + sqlType: ConvertibleToInt | None = 0, + hierarchy: ConvertibleToInt | None = 0, + level: ConvertibleToInt | None = 0, + databaseField: _ConvertibleToBool | None = True, + mappingCount: ConvertibleToInt | None = None, + memberPropertyField: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + sharedItems: SharedItems | None, + fieldGroup: FieldGroup | None, + mpMap: Incomplete | None, + extLst: ExtensionList | None, + name: str, + caption: str | None = None, + propertyName: str | None = None, + serverField: _ConvertibleToBool | None = None, + uniqueList: _ConvertibleToBool | None = True, + numFmtId: ConvertibleToInt | None = None, + formula: str | None = None, + sqlType: ConvertibleToInt | None = 0, + hierarchy: ConvertibleToInt | None = 0, + level: ConvertibleToInt | None = 0, + databaseField: _ConvertibleToBool | None = True, + mappingCount: ConvertibleToInt | None = None, + memberPropertyField: _ConvertibleToBool | None = None, + ) -> None: ... + +class RangeSet(Serialisable): + tagname: ClassVar[str] + i1: Integer[Literal[True]] + i2: Integer[Literal[True]] + i3: Integer[Literal[True]] + i4: Integer[Literal[True]] + ref: String[Literal[False]] + name: String[Literal[True]] + sheet: String[Literal[True]] + + @overload + def __init__( + self, + i1: ConvertibleToInt | None = None, + i2: ConvertibleToInt | None = None, + i3: ConvertibleToInt | None = None, + i4: ConvertibleToInt | None = None, + *, + ref: str, + name: str | None = None, + sheet: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + i1: ConvertibleToInt | None, + i2: ConvertibleToInt | None, + i3: ConvertibleToInt | None, + i4: ConvertibleToInt | None, + ref: str, + name: str | None = None, + sheet: str | None = None, + ) -> None: ... + +class PageItem(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class Consolidation(Serialisable): + tagname: ClassVar[str] + autoPage: Bool[Literal[True]] + pages: NestedSequence[list[PageItem]] + rangeSets: NestedSequence[list[RangeSet]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + autoPage: _ConvertibleToBool | None = None, + pages: list[PageItem] | tuple[PageItem, ...] = (), + rangeSets: list[RangeSet] | tuple[RangeSet, ...] = (), + ) -> None: ... + +class WorksheetSource(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[True]] + name: String[Literal[True]] + sheet: String[Literal[True]] + def __init__(self, ref: str | None = None, name: str | None = None, sheet: str | None = None) -> None: ... + +class CacheSource(Serialisable): + tagname: ClassVar[str] + type: Set[_CacheSourceType] + connectionId: Integer[Literal[True]] + worksheetSource: Typed[WorksheetSource, Literal[True]] + consolidation: Typed[Consolidation, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + type: _CacheSourceType, + connectionId: ConvertibleToInt | None = None, + worksheetSource: WorksheetSource | None = None, + consolidation: Consolidation | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class CacheDefinition(Serialisable): + mime_type: str + rel_type: str + records: Incomplete + tagname: ClassVar[str] + invalid: Bool[Literal[True]] + saveData: Bool[Literal[True]] + refreshOnLoad: Bool[Literal[True]] + optimizeMemory: Bool[Literal[True]] + enableRefresh: Bool[Literal[True]] + refreshedBy: String[Literal[True]] + refreshedDate: Float[Literal[True]] + refreshedDateIso: DateTime[Literal[True]] + backgroundQuery: Bool[Literal[True]] + missingItemsLimit: Integer[Literal[True]] + createdVersion: Integer[Literal[True]] + refreshedVersion: Integer[Literal[True]] + minRefreshableVersion: Integer[Literal[True]] + recordCount: Integer[Literal[True]] + upgradeOnRefresh: Bool[Literal[True]] + supportSubquery: Bool[Literal[True]] + supportAdvancedDrill: Bool[Literal[True]] + cacheSource: Typed[CacheSource, Literal[True]] + cacheFields: Incomplete + cacheHierarchies: Incomplete + kpis: NestedSequence[list[OLAPKPI]] + tupleCache: Typed[TupleCache, Literal[True]] + calculatedItems: Incomplete + calculatedMembers: Incomplete + dimensions: Incomplete + measureGroups: Incomplete + maps: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + invalid: _ConvertibleToBool | None = None, + saveData: _ConvertibleToBool | None = None, + refreshOnLoad: _ConvertibleToBool | None = None, + optimizeMemory: _ConvertibleToBool | None = None, + enableRefresh: _ConvertibleToBool | None = None, + refreshedBy: str | None = None, + refreshedDate: ConvertibleToFloat | None = None, + refreshedDateIso: datetime | str | None = None, + backgroundQuery: _ConvertibleToBool | None = None, + missingItemsLimit: ConvertibleToInt | None = None, + createdVersion: ConvertibleToInt | None = None, + refreshedVersion: ConvertibleToInt | None = None, + minRefreshableVersion: ConvertibleToInt | None = None, + recordCount: ConvertibleToInt | None = None, + upgradeOnRefresh: _ConvertibleToBool | None = None, + tupleCache: TupleCache | None = None, + supportSubquery: _ConvertibleToBool | None = None, + supportAdvancedDrill: _ConvertibleToBool | None = None, + *, + cacheSource: CacheSource, + cacheFields=(), + cacheHierarchies=(), + kpis: list[OLAPKPI] | tuple[OLAPKPI, ...] = (), + calculatedItems=(), + calculatedMembers=(), + dimensions=(), + measureGroups=(), + maps=(), + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + @overload + def __init__( + self, + invalid: _ConvertibleToBool | None, + saveData: _ConvertibleToBool | None, + refreshOnLoad: _ConvertibleToBool | None, + optimizeMemory: _ConvertibleToBool | None, + enableRefresh: _ConvertibleToBool | None, + refreshedBy: str | None, + refreshedDate: ConvertibleToFloat | None, + refreshedDateIso: datetime | str | None, + backgroundQuery: _ConvertibleToBool | None, + missingItemsLimit: ConvertibleToInt | None, + createdVersion: ConvertibleToInt | None, + refreshedVersion: ConvertibleToInt | None, + minRefreshableVersion: ConvertibleToInt | None, + recordCount: ConvertibleToInt | None, + upgradeOnRefresh: _ConvertibleToBool | None, + tupleCache: TupleCache | None, + supportSubquery: _ConvertibleToBool | None, + supportAdvancedDrill: _ConvertibleToBool | None, + cacheSource: CacheSource, + cacheFields=(), + cacheHierarchies=(), + kpis=(), + calculatedItems=(), + calculatedMembers=(), + dimensions=(), + measureGroups=(), + maps=(), + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/pivot/fields.pyi b/stubs/openpyxl/openpyxl/pivot/fields.pyi new file mode 100644 index 000000000000..e2892e328bac --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/fields.pyi @@ -0,0 +1,245 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from datetime import datetime +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, DateTime, Float, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Index(Serialisable): + tagname: ClassVar[str] + v: Integer[Literal[True]] + def __init__(self, v: ConvertibleToInt | None = 0) -> None: ... + +class Tuple(Serialisable): + fld: Integer[Literal[True]] + hier: Integer[Literal[True]] + item: Integer[Literal[False]] + def __init__(self, fld: ConvertibleToInt, hier: ConvertibleToInt, item: ConvertibleToInt) -> None: ... + +class TupleList(Serialisable): + c: Integer[Literal[True]] + tpl: Typed[Tuple, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__(self, c: ConvertibleToInt | None = None, *, tpl: Tuple) -> None: ... + @overload + def __init__(self, c: ConvertibleToInt | None, tpl: Tuple) -> None: ... + +class Missing(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tpls=(), + x=(), + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Number(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + v: Float[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tpls=(), + x=(), + *, + v: ConvertibleToFloat, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + tpls, + x, + v: ConvertibleToFloat, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Error(Serialisable): + tagname: ClassVar[str] + tpls: Typed[TupleList, Literal[True]] + x: Incomplete + v: String[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + tpls: TupleList | None = None, + x=(), + *, + v: str, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + tpls: TupleList | None, + x, + v: str, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class Boolean(Serialisable): + tagname: ClassVar[str] + x: Incomplete + v: Bool[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + x=(), + v: _ConvertibleToBool = None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + ) -> None: ... + +class Text(Serialisable): + tagname: ClassVar[str] + tpls: Incomplete + x: Incomplete + v: String[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + _in: Integer[Literal[True]] # Not private. Avoids name clash + bc: Incomplete + fc: Incomplete + i: Bool[Literal[True]] + un: Bool[Literal[True]] + st: Bool[Literal[True]] + b: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + tpls=(), + x=(), + v=None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c=None, + cp: ConvertibleToInt | None = None, + _in: ConvertibleToInt | None = None, + bc=None, + fc=None, + i: _ConvertibleToBool | None = None, + un: _ConvertibleToBool | None = None, + st: _ConvertibleToBool | None = None, + b: _ConvertibleToBool | None = None, + ) -> None: ... + +class DateTimeField(Serialisable): + tagname: ClassVar[str] + x: Incomplete + v: DateTime[Literal[False]] + u: Bool[Literal[True]] + f: Bool[Literal[True]] + c: String[Literal[True]] + cp: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + x=(), + v: datetime | str | None = None, + u: _ConvertibleToBool | None = None, + f: _ConvertibleToBool | None = None, + c: str | None = None, + cp: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/pivot/record.pyi b/stubs/openpyxl/openpyxl/pivot/record.pyi new file mode 100644 index 000000000000..219fc70261c6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/record.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class Record(Serialisable): + tagname: ClassVar[str] + m: Incomplete + n: Incomplete + b: Incomplete + e: Incomplete + s: Incomplete + d: Incomplete + x: Incomplete + def __init__(self, _fields=(), m=None, n=None, b=None, e=None, s=None, d=None, x=None) -> None: ... + +class RecordList(Serialisable): + mime_type: str + rel_type: str + tagname: ClassVar[str] + r: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, r=(), extLst: ExtensionList | None = None) -> None: ... + @property + def count(self) -> int: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/pivot/table.pyi b/stubs/openpyxl/openpyxl/pivot/table.pyi new file mode 100644 index 000000000000..ec1f0dd3fd45 --- /dev/null +++ b/stubs/openpyxl/openpyxl/pivot/table.pyi @@ -0,0 +1,966 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.filters import AutoFilter +from openpyxl.xml.functions import Element + +_PivotAreaType: TypeAlias = Literal["normal", "data", "all", "origin", "button", "topEnd", "topRight"] +_PivotAxis: TypeAlias = Literal["axisRow", "axisCol", "axisPage", "axisValues"] +_ConditionalFormatType: TypeAlias = Literal["all", "row", "column"] +_FormatAction: TypeAlias = Literal["blank", "formatting", "drill", "formula"] +_PivotFilterType: TypeAlias = Literal[ + "unknown", + "count", + "percent", + "sum", + "captionEqual", + "captionNotEqual", + "captionBeginsWith", + "captionNotBeginsWith", + "captionEndsWith", + "captionNotEndsWith", + "captionContains", + "captionNotContains", + "captionGreaterThan", + "captionGreaterThanOrEqual", + "captionLessThan", + "captionLessThanOrEqual", + "captionBetween", + "captionNotBetween", + "valueEqual", + "valueNotEqual", + "valueGreaterThan", + "valueGreaterThanOrEqual", + "valueLessThan", + "valueLessThanOrEqual", + "valueBetween", + "valueNotBetween", + "dateEqual", + "dateNotEqual", + "dateOlderThan", + "dateOlderThanOrEqual", + "dateNewerThan", + "dateNewerThanOrEqual", + "dateBetween", + "dateNotBetween", + "tomorrow", + "today", + "yesterday", + "nextWeek", + "thisWeek", + "lastWeek", + "nextMonth", + "thisMonth", + "lastMonth", + "nextQuarter", + "thisQuarter", + "lastQuarter", + "nextYear", + "thisYear", + "lastYear", + "yearToDate", + "Q1", + "Q2", + "Q3", + "Q4", + "M1", + "M2", + "M3", + "M4", + "M5", + "M6", + "M7", + "M8", + "M9", + "M10", + "M11", + "M12", +] +_ConditionalFormatScope: TypeAlias = Literal["selection", "data", "field"] +_DataFieldSubtotal: TypeAlias = Literal[ + "average", "count", "countNums", "max", "min", "product", "stdDev", "stdDevp", "sum", "var", "varp" +] +_DataFieldShowDataAs: TypeAlias = Literal[ + "normal", "difference", "percent", "percentDiff", "runTotal", "percentOfRow", "percentOfCol", "percentOfTotal", "index" +] +_ItemType: TypeAlias = Literal[ + "data", + "default", + "sum", + "countA", + "avg", + "max", + "min", + "product", + "count", + "stdDev", + "stdDevP", + "var", + "varP", + "grand", + "blank", +] +_PivotFieldSortType: TypeAlias = Literal["manual", "ascending", "descending"] + +class HierarchyUsage(Serialisable): + tagname: ClassVar[str] + hierarchyUsage: Integer[Literal[False]] + def __init__(self, hierarchyUsage: ConvertibleToInt) -> None: ... + +class ColHierarchiesUsage(Serialisable): + tagname: ClassVar[str] + colHierarchyUsage: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, colHierarchyUsage=()) -> None: ... + @property + def count(self) -> int: ... + +class RowHierarchiesUsage(Serialisable): + tagname: ClassVar[str] + rowHierarchyUsage: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, rowHierarchyUsage=()) -> None: ... + @property + def count(self) -> int: ... + +class PivotFilter(Serialisable): + tagname: ClassVar[str] + fld: Integer[Literal[False]] + mpFld: Integer[Literal[True]] + type: Set[_PivotFilterType] + evalOrder: Integer[Literal[True]] + id: Integer[Literal[False]] + iMeasureHier: Integer[Literal[True]] + iMeasureFld: Integer[Literal[True]] + name: String[Literal[True]] + description: String[Literal[True]] + stringValue1: String[Literal[True]] + stringValue2: String[Literal[True]] + autoFilter: Typed[AutoFilter, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + fld: ConvertibleToInt, + mpFld: ConvertibleToInt | None = None, + *, + type: _PivotFilterType, + evalOrder: ConvertibleToInt | None = None, + id: ConvertibleToInt, + iMeasureHier: ConvertibleToInt | None = None, + iMeasureFld: ConvertibleToInt | None = None, + name: str | None = None, + description: str | None = None, + stringValue1: str | None = None, + stringValue2: str | None = None, + autoFilter: AutoFilter, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + fld: ConvertibleToInt, + mpFld: ConvertibleToInt | None, + type: _PivotFilterType, + evalOrder: ConvertibleToInt | None, + id: ConvertibleToInt, + iMeasureHier: ConvertibleToInt | None, + iMeasureFld: ConvertibleToInt | None, + name: str | None, + description: str | None, + stringValue1: str | None, + stringValue2: str | None, + autoFilter: AutoFilter, + extLst: ExtensionList | None = None, + ) -> None: ... + +class PivotFilters(Serialisable): + count: Integer[Literal[False]] + filter: Typed[PivotFilter, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: ConvertibleToInt, filter: PivotFilter | None = None) -> None: ... + +class PivotTableStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showRowHeaders: Bool[Literal[False]] + showColHeaders: Bool[Literal[False]] + showRowStripes: Bool[Literal[False]] + showColStripes: Bool[Literal[False]] + showLastColumn: Bool[Literal[False]] + def __init__( + self, + name: str | None = None, + showRowHeaders: _ConvertibleToBool = None, + showColHeaders: _ConvertibleToBool = None, + showRowStripes: _ConvertibleToBool = None, + showColStripes: _ConvertibleToBool = None, + showLastColumn: _ConvertibleToBool = None, + ) -> None: ... + +class MemberList(Serialisable): + tagname: ClassVar[str] + level: Integer[Literal[True]] + member: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count=None, level: ConvertibleToInt | None = None, member=()) -> None: ... + @property + def count(self) -> int: ... + +class MemberProperty(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showCell: Bool[Literal[True]] + showTip: Bool[Literal[True]] + showAsCaption: Bool[Literal[True]] + nameLen: Integer[Literal[True]] + pPos: Integer[Literal[True]] + pLen: Integer[Literal[True]] + level: Integer[Literal[True]] + field: Integer[Literal[False]] + + @overload + def __init__( + self, + name: str | None = None, + showCell: _ConvertibleToBool | None = None, + showTip: _ConvertibleToBool | None = None, + showAsCaption: _ConvertibleToBool | None = None, + nameLen: ConvertibleToInt | None = None, + pPos: ConvertibleToInt | None = None, + pLen: ConvertibleToInt | None = None, + level: ConvertibleToInt | None = None, + *, + field: ConvertibleToInt, + ) -> None: ... + @overload + def __init__( + self, + name: str | None, + showCell: _ConvertibleToBool | None, + showTip: _ConvertibleToBool | None, + showAsCaption: _ConvertibleToBool | None, + nameLen: ConvertibleToInt | None, + pPos: ConvertibleToInt | None, + pLen: ConvertibleToInt | None, + level: ConvertibleToInt | None, + field: ConvertibleToInt, + ) -> None: ... + +class PivotHierarchy(Serialisable): + tagname: ClassVar[str] + outline: Bool[Literal[False]] + multipleItemSelectionAllowed: Bool[Literal[False]] + subtotalTop: Bool[Literal[False]] + showInFieldList: Bool[Literal[False]] + dragToRow: Bool[Literal[False]] + dragToCol: Bool[Literal[False]] + dragToPage: Bool[Literal[False]] + dragToData: Bool[Literal[False]] + dragOff: Bool[Literal[False]] + includeNewItemsInFilter: Bool[Literal[False]] + caption: String[Literal[True]] + mps: Incomplete + members: Typed[MemberList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + outline: _ConvertibleToBool = None, + multipleItemSelectionAllowed: _ConvertibleToBool = None, + subtotalTop: _ConvertibleToBool = None, + showInFieldList: _ConvertibleToBool = None, + dragToRow: _ConvertibleToBool = None, + dragToCol: _ConvertibleToBool = None, + dragToPage: _ConvertibleToBool = None, + dragToData: _ConvertibleToBool = None, + dragOff: _ConvertibleToBool = None, + includeNewItemsInFilter: _ConvertibleToBool = None, + caption: str | None = None, + mps=(), + members: MemberList | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class Reference(Serialisable): + tagname: ClassVar[str] + field: Integer[Literal[True]] + selected: Bool[Literal[True]] + byPosition: Bool[Literal[True]] + relative: Bool[Literal[True]] + defaultSubtotal: Bool[Literal[True]] + sumSubtotal: Bool[Literal[True]] + countASubtotal: Bool[Literal[True]] + avgSubtotal: Bool[Literal[True]] + maxSubtotal: Bool[Literal[True]] + minSubtotal: Bool[Literal[True]] + productSubtotal: Bool[Literal[True]] + countSubtotal: Bool[Literal[True]] + stdDevSubtotal: Bool[Literal[True]] + stdDevPSubtotal: Bool[Literal[True]] + varSubtotal: Bool[Literal[True]] + varPSubtotal: Bool[Literal[True]] + x: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + field: ConvertibleToInt | None = None, + count: Unused = None, + selected: _ConvertibleToBool | None = None, + byPosition: _ConvertibleToBool | None = None, + relative: _ConvertibleToBool | None = None, + defaultSubtotal: _ConvertibleToBool | None = None, + sumSubtotal: _ConvertibleToBool | None = None, + countASubtotal: _ConvertibleToBool | None = None, + avgSubtotal: _ConvertibleToBool | None = None, + maxSubtotal: _ConvertibleToBool | None = None, + minSubtotal: _ConvertibleToBool | None = None, + productSubtotal: _ConvertibleToBool | None = None, + countSubtotal: _ConvertibleToBool | None = None, + stdDevSubtotal: _ConvertibleToBool | None = None, + stdDevPSubtotal: _ConvertibleToBool | None = None, + varSubtotal: _ConvertibleToBool | None = None, + varPSubtotal: _ConvertibleToBool | None = None, + x: Incomplete | None = (), + extLst: ExtensionList | None = None, + ) -> None: ... + @property + def count(self) -> int: ... + +class PivotArea(Serialisable): + tagname: ClassVar[str] + references: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + field: Integer[Literal[True]] + type: NoneSet[_PivotAreaType] + dataOnly: Bool[Literal[True]] + labelOnly: Bool[Literal[True]] + grandRow: Bool[Literal[True]] + grandCol: Bool[Literal[True]] + cacheIndex: Bool[Literal[True]] + outline: Bool[Literal[True]] + offset: String[Literal[True]] + collapsedLevelsAreSubtotals: Bool[Literal[True]] + axis: NoneSet[_PivotAxis] + fieldPosition: Integer[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + references=(), + extLst: ExtensionList | None = None, + field: ConvertibleToInt | None = None, + type: _PivotAreaType | Literal["none"] | None = "normal", + dataOnly: _ConvertibleToBool | None = True, + labelOnly: _ConvertibleToBool | None = None, + grandRow: _ConvertibleToBool | None = None, + grandCol: _ConvertibleToBool | None = None, + cacheIndex: _ConvertibleToBool | None = None, + outline: _ConvertibleToBool | None = True, + offset: str | None = None, + collapsedLevelsAreSubtotals: _ConvertibleToBool | None = None, + axis: _PivotAxis | Literal["none"] | None = None, + fieldPosition: ConvertibleToInt | None = None, + ) -> None: ... + +class ChartFormat(Serialisable): + tagname: ClassVar[str] + chart: Integer[Literal[False]] + format: Integer[Literal[False]] + series: Bool[Literal[False]] + pivotArea: Typed[PivotArea, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, chart: ConvertibleToInt, format: ConvertibleToInt, series: _ConvertibleToBool = None, *, pivotArea: PivotArea + ) -> None: ... + @overload + def __init__( + self, chart: ConvertibleToInt, format: ConvertibleToInt, series: _ConvertibleToBool, pivotArea: PivotArea + ) -> None: ... + +class ConditionalFormat(Serialisable): + tagname: ClassVar[str] + scope: Set[_ConditionalFormatScope] + type: NoneSet[_ConditionalFormatType] + priority: Integer[Literal[False]] + pivotAreas: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + scope: _ConditionalFormatScope = "selection", + type: _ConditionalFormatType | Literal["none"] | None = None, + *, + priority: ConvertibleToInt, + pivotAreas=(), + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + scope: _ConditionalFormatScope, + type: _ConditionalFormatType | Literal["none"] | None, + priority: ConvertibleToInt, + pivotAreas=(), + extLst: ExtensionList | None = None, + ) -> None: ... + +class ConditionalFormatList(Serialisable): + tagname: ClassVar[str] + conditionalFormat: Incomplete + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, conditionalFormat=(), count=None) -> None: ... + def by_priority(self): ... + @property + def count(self) -> int: ... + def to_tree(self, tagname: str | None = None) -> Element: ... # type: ignore[override] + +class Format(Serialisable): + tagname: ClassVar[str] + action: NoneSet[_FormatAction] + dxfId: Integer[Literal[True]] + pivotArea: Typed[PivotArea, Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + action: _FormatAction | Literal["none"] | None = "formatting", + dxfId: ConvertibleToInt | None = None, + *, + pivotArea: PivotArea, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + action: _FormatAction | Literal["none"] | None, + dxfId: ConvertibleToInt | None, + pivotArea: PivotArea, + extLst: ExtensionList | None = None, + ) -> None: ... + +class DataField(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + fld: Integer[Literal[False]] + subtotal: Set[_DataFieldSubtotal] + showDataAs: Set[_DataFieldShowDataAs] + baseField: Integer[Literal[False]] + baseItem: Integer[Literal[False]] + numFmtId: Integer[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str | None = None, + *, + fld: ConvertibleToInt, + subtotal: str = "sum", + showDataAs: str = "normal", + baseField: ConvertibleToInt = -1, + baseItem: ConvertibleToInt = 1048832, + numFmtId: ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + name: str | None, + fld: ConvertibleToInt, + subtotal: str = "sum", + showDataAs: str = "normal", + baseField: ConvertibleToInt = -1, + baseItem: ConvertibleToInt = 1048832, + numFmtId: ConvertibleToInt | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class PageField(Serialisable): + tagname: ClassVar[str] + fld: Integer[Literal[False]] + item: Integer[Literal[True]] + hier: Integer[Literal[True]] + name: String[Literal[True]] + cap: String[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + fld: ConvertibleToInt, + item: ConvertibleToInt | None = None, + hier: ConvertibleToInt | None = None, + name: str | None = None, + cap: str | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class RowColItem(Serialisable): + tagname: ClassVar[str] + t: Set[_ItemType] + r: Integer[Literal[False]] + i: Integer[Literal[False]] + x: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, t: _ItemType = "data", r: ConvertibleToInt = 0, i: ConvertibleToInt = 0, x=()) -> None: ... + +class RowColField(Serialisable): + tagname: ClassVar[str] + x: Integer[Literal[False]] + def __init__(self, x: ConvertibleToInt) -> None: ... + +class AutoSortScope(Serialisable): + pivotArea: Typed[PivotArea, Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, pivotArea: PivotArea) -> None: ... + +class FieldItem(Serialisable): + tagname: ClassVar[str] + n: String[Literal[True]] + t: Set[_ItemType] + h: Bool[Literal[True]] + s: Bool[Literal[True]] + sd: Bool[Literal[True]] + f: Bool[Literal[True]] + m: Bool[Literal[True]] + c: Bool[Literal[True]] + x: Integer[Literal[True]] + d: Bool[Literal[True]] + e: Bool[Literal[True]] + def __init__( + self, + n: str | None = None, + t: _ItemType = "data", + h: _ConvertibleToBool | None = None, + s: _ConvertibleToBool | None = None, + sd: _ConvertibleToBool | None = True, + f: _ConvertibleToBool | None = None, + m: _ConvertibleToBool | None = None, + c: _ConvertibleToBool | None = None, + x: ConvertibleToInt | None = None, + d: _ConvertibleToBool | None = None, + e: _ConvertibleToBool | None = None, + ) -> None: ... + +class PivotField(Serialisable): + tagname: ClassVar[str] + items: Incomplete + autoSortScope: Typed[AutoSortScope, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + name: String[Literal[True]] + axis: NoneSet[_PivotAxis] + dataField: Bool[Literal[True]] + subtotalCaption: String[Literal[True]] + showDropDowns: Bool[Literal[True]] + hiddenLevel: Bool[Literal[True]] + uniqueMemberProperty: String[Literal[True]] + compact: Bool[Literal[True]] + allDrilled: Bool[Literal[True]] + numFmtId: Integer[Literal[True]] + outline: Bool[Literal[True]] + subtotalTop: Bool[Literal[True]] + dragToRow: Bool[Literal[True]] + dragToCol: Bool[Literal[True]] + multipleItemSelectionAllowed: Bool[Literal[True]] + dragToPage: Bool[Literal[True]] + dragToData: Bool[Literal[True]] + dragOff: Bool[Literal[True]] + showAll: Bool[Literal[True]] + insertBlankRow: Bool[Literal[True]] + serverField: Bool[Literal[True]] + insertPageBreak: Bool[Literal[True]] + autoShow: Bool[Literal[True]] + topAutoShow: Bool[Literal[True]] + hideNewItems: Bool[Literal[True]] + measureFilter: Bool[Literal[True]] + includeNewItemsInFilter: Bool[Literal[True]] + itemPageCount: Integer[Literal[True]] + sortType: Set[_PivotFieldSortType] + dataSourceSort: Bool[Literal[True]] + nonAutoSortDefault: Bool[Literal[True]] + rankBy: Integer[Literal[True]] + defaultSubtotal: Bool[Literal[True]] + sumSubtotal: Bool[Literal[True]] + countASubtotal: Bool[Literal[True]] + avgSubtotal: Bool[Literal[True]] + maxSubtotal: Bool[Literal[True]] + minSubtotal: Bool[Literal[True]] + productSubtotal: Bool[Literal[True]] + countSubtotal: Bool[Literal[True]] + stdDevSubtotal: Bool[Literal[True]] + stdDevPSubtotal: Bool[Literal[True]] + varSubtotal: Bool[Literal[True]] + varPSubtotal: Bool[Literal[True]] + showPropCell: Bool[Literal[True]] + showPropTip: Bool[Literal[True]] + showPropAsCaption: Bool[Literal[True]] + defaultAttributeDrillState: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + items=(), + autoSortScope: AutoSortScope | None = None, + name: str | None = None, + axis: _PivotAxis | Literal["none"] | None = None, + dataField: _ConvertibleToBool | None = None, + subtotalCaption: str | None = None, + showDropDowns: _ConvertibleToBool | None = True, + hiddenLevel: _ConvertibleToBool | None = None, + uniqueMemberProperty: str | None = None, + compact: _ConvertibleToBool | None = True, + allDrilled: _ConvertibleToBool | None = None, + numFmtId: ConvertibleToInt | None = None, + outline: _ConvertibleToBool | None = True, + subtotalTop: _ConvertibleToBool | None = True, + dragToRow: _ConvertibleToBool | None = True, + dragToCol: _ConvertibleToBool | None = True, + multipleItemSelectionAllowed: _ConvertibleToBool | None = None, + dragToPage: _ConvertibleToBool | None = True, + dragToData: _ConvertibleToBool | None = True, + dragOff: _ConvertibleToBool | None = True, + showAll: _ConvertibleToBool | None = True, + insertBlankRow: _ConvertibleToBool | None = None, + serverField: _ConvertibleToBool | None = None, + insertPageBreak: _ConvertibleToBool | None = None, + autoShow: _ConvertibleToBool | None = None, + topAutoShow: _ConvertibleToBool | None = True, + hideNewItems: _ConvertibleToBool | None = None, + measureFilter: _ConvertibleToBool | None = None, + includeNewItemsInFilter: _ConvertibleToBool | None = None, + itemPageCount: ConvertibleToInt | None = 10, + sortType: _PivotFieldSortType = "manual", + dataSourceSort: _ConvertibleToBool | None = None, + nonAutoSortDefault: _ConvertibleToBool | None = None, + rankBy: ConvertibleToInt | None = None, + defaultSubtotal: _ConvertibleToBool | None = True, + sumSubtotal: _ConvertibleToBool | None = None, + countASubtotal: _ConvertibleToBool | None = None, + avgSubtotal: _ConvertibleToBool | None = None, + maxSubtotal: _ConvertibleToBool | None = None, + minSubtotal: _ConvertibleToBool | None = None, + productSubtotal: _ConvertibleToBool | None = None, + countSubtotal: _ConvertibleToBool | None = None, + stdDevSubtotal: _ConvertibleToBool | None = None, + stdDevPSubtotal: _ConvertibleToBool | None = None, + varSubtotal: _ConvertibleToBool | None = None, + varPSubtotal: _ConvertibleToBool | None = None, + showPropCell: _ConvertibleToBool | None = None, + showPropTip: _ConvertibleToBool | None = None, + showPropAsCaption: _ConvertibleToBool | None = None, + defaultAttributeDrillState: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class Location(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + firstHeaderRow: Integer[Literal[False]] + firstDataRow: Integer[Literal[False]] + firstDataCol: Integer[Literal[False]] + rowPageCount: Integer[Literal[True]] + colPageCount: Integer[Literal[True]] + def __init__( + self, + ref: str, + firstHeaderRow: ConvertibleToInt, + firstDataRow: ConvertibleToInt, + firstDataCol: ConvertibleToInt, + rowPageCount: ConvertibleToInt | None = None, + colPageCount: ConvertibleToInt | None = None, + ) -> None: ... + +class TableDefinition(Serialisable): + mime_type: str + rel_type: str + tagname: ClassVar[str] + cache: Incomplete + name: String[Literal[False]] + cacheId: Integer[Literal[False]] + dataOnRows: Bool[Literal[False]] + dataPosition: Integer[Literal[True]] + dataCaption: String[Literal[False]] + grandTotalCaption: String[Literal[True]] + errorCaption: String[Literal[True]] + showError: Bool[Literal[False]] + missingCaption: String[Literal[True]] + showMissing: Bool[Literal[False]] + pageStyle: String[Literal[True]] + pivotTableStyle: String[Literal[True]] + vacatedStyle: String[Literal[True]] + tag: String[Literal[True]] + updatedVersion: Integer[Literal[False]] + minRefreshableVersion: Integer[Literal[False]] + asteriskTotals: Bool[Literal[False]] + showItems: Bool[Literal[False]] + editData: Bool[Literal[False]] + disableFieldList: Bool[Literal[False]] + showCalcMbrs: Bool[Literal[False]] + visualTotals: Bool[Literal[False]] + showMultipleLabel: Bool[Literal[False]] + showDataDropDown: Bool[Literal[False]] + showDrill: Bool[Literal[False]] + printDrill: Bool[Literal[False]] + showMemberPropertyTips: Bool[Literal[False]] + showDataTips: Bool[Literal[False]] + enableWizard: Bool[Literal[False]] + enableDrill: Bool[Literal[False]] + enableFieldProperties: Bool[Literal[False]] + preserveFormatting: Bool[Literal[False]] + useAutoFormatting: Bool[Literal[False]] + pageWrap: Integer[Literal[False]] + pageOverThenDown: Bool[Literal[False]] + subtotalHiddenItems: Bool[Literal[False]] + rowGrandTotals: Bool[Literal[False]] + colGrandTotals: Bool[Literal[False]] + fieldPrintTitles: Bool[Literal[False]] + itemPrintTitles: Bool[Literal[False]] + mergeItem: Bool[Literal[False]] + showDropZones: Bool[Literal[False]] + createdVersion: Integer[Literal[False]] + indent: Integer[Literal[False]] + showEmptyRow: Bool[Literal[False]] + showEmptyCol: Bool[Literal[False]] + showHeaders: Bool[Literal[False]] + compact: Bool[Literal[False]] + outline: Bool[Literal[False]] + outlineData: Bool[Literal[False]] + compactData: Bool[Literal[False]] + published: Bool[Literal[False]] + gridDropZones: Bool[Literal[False]] + immersive: Bool[Literal[False]] + multipleFieldFilters: Bool[Literal[False]] + chartFormat: Integer[Literal[False]] + rowHeaderCaption: String[Literal[True]] + colHeaderCaption: String[Literal[True]] + fieldListSortAscending: Bool[Literal[False]] + mdxSubqueries: Bool[Literal[False]] + customListSort: Bool[Literal[True]] + autoFormatId: Integer[Literal[True]] + applyNumberFormats: Bool[Literal[False]] + applyBorderFormats: Bool[Literal[False]] + applyFontFormats: Bool[Literal[False]] + applyPatternFormats: Bool[Literal[False]] + applyAlignmentFormats: Bool[Literal[False]] + applyWidthHeightFormats: Bool[Literal[False]] + location: Typed[Location, Literal[False]] + pivotFields: Incomplete + rowFields: Incomplete + rowItems: Incomplete + colFields: Incomplete + colItems: Incomplete + pageFields: Incomplete + dataFields: Incomplete + formats: Incomplete + conditionalFormats: Typed[ConditionalFormatList, Literal[True]] + chartFormats: Incomplete + pivotHierarchies: Incomplete + pivotTableStyleInfo: Typed[PivotTableStyle, Literal[True]] + filters: Incomplete + rowHierarchiesUsage: Typed[RowHierarchiesUsage, Literal[True]] + colHierarchiesUsage: Typed[ColHierarchiesUsage, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str, + cacheId: ConvertibleToInt, + dataOnRows: _ConvertibleToBool = False, + dataPosition: ConvertibleToInt | None = None, + *, + dataCaption: str, + grandTotalCaption: str | None = None, + errorCaption: str | None = None, + showError: _ConvertibleToBool = False, + missingCaption: str | None = None, + showMissing: _ConvertibleToBool = True, + pageStyle: str | None = None, + pivotTableStyle: str | None = None, + vacatedStyle: str | None = None, + tag: str | None = None, + updatedVersion: ConvertibleToInt = 0, + minRefreshableVersion: ConvertibleToInt = 0, + asteriskTotals: _ConvertibleToBool = False, + showItems: _ConvertibleToBool = True, + editData: _ConvertibleToBool = False, + disableFieldList: _ConvertibleToBool = False, + showCalcMbrs: _ConvertibleToBool = True, + visualTotals: _ConvertibleToBool = True, + showMultipleLabel: _ConvertibleToBool = True, + showDataDropDown: _ConvertibleToBool = True, + showDrill: _ConvertibleToBool = True, + printDrill: _ConvertibleToBool = False, + showMemberPropertyTips: _ConvertibleToBool = True, + showDataTips: _ConvertibleToBool = True, + enableWizard: _ConvertibleToBool = True, + enableDrill: _ConvertibleToBool = True, + enableFieldProperties: _ConvertibleToBool = True, + preserveFormatting: _ConvertibleToBool = True, + useAutoFormatting: _ConvertibleToBool = False, + pageWrap: ConvertibleToInt = 0, + pageOverThenDown: _ConvertibleToBool = False, + subtotalHiddenItems: _ConvertibleToBool = False, + rowGrandTotals: _ConvertibleToBool = True, + colGrandTotals: _ConvertibleToBool = True, + fieldPrintTitles: _ConvertibleToBool = False, + itemPrintTitles: _ConvertibleToBool = False, + mergeItem: _ConvertibleToBool = False, + showDropZones: _ConvertibleToBool = True, + createdVersion: ConvertibleToInt = 0, + indent: ConvertibleToInt = 1, + showEmptyRow: _ConvertibleToBool = False, + showEmptyCol: _ConvertibleToBool = False, + showHeaders: _ConvertibleToBool = True, + compact: _ConvertibleToBool = True, + outline: _ConvertibleToBool = False, + outlineData: _ConvertibleToBool = False, + compactData: _ConvertibleToBool = True, + published: _ConvertibleToBool = False, + gridDropZones: _ConvertibleToBool = False, + immersive: _ConvertibleToBool = True, + multipleFieldFilters: _ConvertibleToBool = None, + chartFormat: ConvertibleToInt = 0, + rowHeaderCaption: str | None = None, + colHeaderCaption: str | None = None, + fieldListSortAscending: _ConvertibleToBool = None, + mdxSubqueries: _ConvertibleToBool = None, + customListSort: _ConvertibleToBool | None = None, + autoFormatId: ConvertibleToInt | None = None, + applyNumberFormats: _ConvertibleToBool = False, + applyBorderFormats: _ConvertibleToBool = False, + applyFontFormats: _ConvertibleToBool = False, + applyPatternFormats: _ConvertibleToBool = False, + applyAlignmentFormats: _ConvertibleToBool = False, + applyWidthHeightFormats: _ConvertibleToBool = False, + location: Location, + pivotFields=(), + rowFields=(), + rowItems=(), + colFields=(), + colItems=(), + pageFields=(), + dataFields=(), + formats=(), + conditionalFormats: ConditionalFormatList | None = None, + chartFormats=(), + pivotHierarchies=(), + pivotTableStyleInfo: PivotTableStyle | None = None, + filters=(), + rowHierarchiesUsage: RowHierarchiesUsage | None = None, + colHierarchiesUsage: ColHierarchiesUsage | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + @overload + def __init__( + self, + name: str, + cacheId: ConvertibleToInt, + dataOnRows: _ConvertibleToBool, + dataPosition: ConvertibleToInt | None, + dataCaption: str, + grandTotalCaption: str | None, + errorCaption: str | None, + showError: _ConvertibleToBool, + missingCaption: str | None, + showMissing: _ConvertibleToBool, + pageStyle: str | None, + pivotTableStyle: str | None, + vacatedStyle: str | None, + tag: str | None, + updatedVersion: ConvertibleToInt, + minRefreshableVersion: ConvertibleToInt, + asteriskTotals: _ConvertibleToBool, + showItems: _ConvertibleToBool, + editData: _ConvertibleToBool, + disableFieldList: _ConvertibleToBool, + showCalcMbrs: _ConvertibleToBool, + visualTotals: _ConvertibleToBool, + showMultipleLabel: _ConvertibleToBool, + showDataDropDown: _ConvertibleToBool, + showDrill: _ConvertibleToBool, + printDrill: _ConvertibleToBool, + showMemberPropertyTips: _ConvertibleToBool, + showDataTips: _ConvertibleToBool, + enableWizard: _ConvertibleToBool, + enableDrill: _ConvertibleToBool, + enableFieldProperties: _ConvertibleToBool, + preserveFormatting: _ConvertibleToBool, + useAutoFormatting: _ConvertibleToBool, + pageWrap: ConvertibleToInt, + pageOverThenDown: _ConvertibleToBool, + subtotalHiddenItems: _ConvertibleToBool, + rowGrandTotals: _ConvertibleToBool, + colGrandTotals: _ConvertibleToBool, + fieldPrintTitles: _ConvertibleToBool, + itemPrintTitles: _ConvertibleToBool, + mergeItem: _ConvertibleToBool, + showDropZones: _ConvertibleToBool, + createdVersion: ConvertibleToInt, + indent: ConvertibleToInt, + showEmptyRow: _ConvertibleToBool, + showEmptyCol: _ConvertibleToBool, + showHeaders: _ConvertibleToBool, + compact: _ConvertibleToBool, + outline: _ConvertibleToBool, + outlineData: _ConvertibleToBool, + compactData: _ConvertibleToBool, + published: _ConvertibleToBool, + gridDropZones: _ConvertibleToBool, + immersive: _ConvertibleToBool, + multipleFieldFilters: _ConvertibleToBool, + chartFormat: ConvertibleToInt, + rowHeaderCaption: str | None, + colHeaderCaption: str | None, + fieldListSortAscending: _ConvertibleToBool, + mdxSubqueries: _ConvertibleToBool, + customListSort: _ConvertibleToBool | None, + autoFormatId: ConvertibleToInt | None, + applyNumberFormats: _ConvertibleToBool, + applyBorderFormats: _ConvertibleToBool, + applyFontFormats: _ConvertibleToBool, + applyPatternFormats: _ConvertibleToBool, + applyAlignmentFormats: _ConvertibleToBool, + applyWidthHeightFormats: _ConvertibleToBool, + location: Location, + pivotFields=(), + rowFields=(), + rowItems=(), + colFields=(), + colItems=(), + pageFields=(), + dataFields=(), + formats=(), + conditionalFormats: ConditionalFormatList | None = None, + chartFormats=(), + pivotHierarchies=(), + pivotTableStyleInfo: PivotTableStyle | None = None, + filters=(), + rowHierarchiesUsage: RowHierarchiesUsage | None = None, + colHierarchiesUsage: ColHierarchiesUsage | None = None, + extLst: ExtensionList | None = None, + id=None, + ) -> None: ... + + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + def formatted_fields(self) -> dict[Incomplete, list[Incomplete]]: ... + @property + def summary(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/reader/__init__.pyi b/stubs/openpyxl/openpyxl/reader/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/openpyxl/openpyxl/reader/drawings.pyi b/stubs/openpyxl/openpyxl/reader/drawings.pyi new file mode 100644 index 000000000000..f2bf8cd0863f --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/drawings.pyi @@ -0,0 +1,6 @@ +from zipfile import ZipFile + +from openpyxl.chart._chart import ChartBase +from openpyxl.drawing.image import Image + +def find_images(archive: ZipFile, path: str) -> tuple[list[ChartBase], list[Image]]: ... diff --git a/stubs/openpyxl/openpyxl/reader/excel.pyi b/stubs/openpyxl/openpyxl/reader/excel.pyi new file mode 100644 index 000000000000..da45a60724e6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/excel.pyi @@ -0,0 +1,53 @@ +from typing import Final, Literal, TypeAlias +from zipfile import ZipFile + +from openpyxl import _ZipFileFileProtocol +from openpyxl.chartsheet.chartsheet import Chartsheet +from openpyxl.packaging.manifest import Manifest +from openpyxl.packaging.relationship import Relationship +from openpyxl.reader.workbook import WorkbookParser +from openpyxl.workbook import Workbook + +_SupportedFormats: TypeAlias = Literal[".xlsx", ".xlsm", ".xltx", ".xltm"] +SUPPORTED_FORMATS: Final[tuple[_SupportedFormats, ...]] + +class ExcelReader: + archive: ZipFile + valid_files: list[str] + read_only: bool + keep_vba: bool + data_only: bool + keep_links: bool + rich_text: bool + shared_strings: list[str] + package: Manifest # defined after call to read_manifest() + parser: WorkbookParser # defined after call to read_workbook() + wb: Workbook # defined after call to read_workbook() + + def __init__( + self, + fn: _ZipFileFileProtocol, + read_only: bool = False, + keep_vba: bool = False, + data_only: bool = False, + keep_links: bool = True, + rich_text: bool = False, + ) -> None: ... + def read_manifest(self) -> None: ... + def read_strings(self) -> None: ... + def read_workbook(self) -> None: ... + def read_properties(self) -> None: ... + def read_custom(self) -> None: ... + def read_theme(self) -> None: ... + def read_chartsheet(self, sheet: Chartsheet, rel: Relationship) -> None: ... + def read_worksheets(self) -> None: ... + def read(self) -> None: ... + +def load_workbook( + filename: _ZipFileFileProtocol, + read_only: bool = False, + keep_vba: bool = False, + data_only: bool = False, + keep_links: bool = True, + rich_text: bool = False, +) -> Workbook: ... diff --git a/stubs/openpyxl/openpyxl/reader/strings.pyi b/stubs/openpyxl/openpyxl/reader/strings.pyi new file mode 100644 index 000000000000..3d6b247ded12 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/strings.pyi @@ -0,0 +1,6 @@ +from xml.etree.ElementTree import _FileRead + +from openpyxl.cell.rich_text import CellRichText + +def read_string_table(xml_source: _FileRead) -> list[str]: ... +def read_rich_text(xml_source: _FileRead) -> list[CellRichText | str]: ... diff --git a/stubs/openpyxl/openpyxl/reader/workbook.pyi b/stubs/openpyxl/openpyxl/reader/workbook.pyi new file mode 100644 index 000000000000..7a8f3bec60a7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/reader/workbook.pyi @@ -0,0 +1,24 @@ +from collections.abc import Generator +from zipfile import ZipFile + +from openpyxl.packaging.relationship import Relationship, RelationshipList +from openpyxl.packaging.workbook import ChildSheet, PivotCache +from openpyxl.pivot.cache import CacheDefinition +from openpyxl.workbook import Workbook + +class WorkbookParser: + archive: ZipFile + workbook_part_name: str + wb: Workbook + keep_links: bool + sheets: list[ChildSheet] + def __init__(self, archive: ZipFile, workbook_part_name: str, keep_links: bool = True) -> None: ... + @property + def rels(self) -> RelationshipList: ... + # Errors if "parse" is never called. + caches: list[PivotCache] + def parse(self) -> None: ... + def find_sheets(self) -> Generator[tuple[ChildSheet, Relationship]]: ... + def assign_names(self) -> None: ... + @property + def pivot_caches(self) -> dict[int, CacheDefinition]: ... diff --git a/stubs/openpyxl/openpyxl/styles/__init__.pyi b/stubs/openpyxl/openpyxl/styles/__init__.pyi new file mode 100644 index 000000000000..946d3a30b775 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/__init__.pyi @@ -0,0 +1,8 @@ +from .alignment import Alignment as Alignment +from .borders import Border as Border, Side as Side +from .colors import Color as Color +from .fills import Fill as Fill, GradientFill as GradientFill, PatternFill as PatternFill +from .fonts import DEFAULT_FONT as DEFAULT_FONT, Font as Font +from .named_styles import NamedStyle as NamedStyle +from .numbers import NumberFormatDescriptor as NumberFormatDescriptor, is_builtin as is_builtin, is_date_format as is_date_format +from .protection import Protection as Protection diff --git a/stubs/openpyxl/openpyxl/styles/alignment.pyi b/stubs/openpyxl/openpyxl/styles/alignment.pyi new file mode 100644 index 000000000000..40f69c4e46cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/alignment.pyi @@ -0,0 +1,46 @@ +from _typeshed import ConvertibleToFloat +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, Min, MinMax, NoneSet, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_HorizontalAlignmentsType: TypeAlias = Literal[ + "general", "left", "center", "right", "fill", "justify", "centerContinuous", "distributed" +] +_VerticalAlignmentsType: TypeAlias = Literal["top", "center", "bottom", "justify", "distributed"] + +horizontal_alignments: Final[tuple[_HorizontalAlignmentsType, ...]] +vertical_aligments: Final[tuple[_VerticalAlignmentsType, ...]] + +class Alignment(Serialisable): + tagname: ClassVar[str] + horizontal: NoneSet[_HorizontalAlignmentsType] + vertical: NoneSet[_VerticalAlignmentsType] + textRotation: NoneSet[int] + text_rotation: Alias + wrapText: Bool[Literal[True]] + wrap_text: Alias + shrinkToFit: Bool[Literal[True]] + shrink_to_fit: Alias + indent: MinMax[float, Literal[False]] + relativeIndent: MinMax[float, Literal[False]] + justifyLastLine: Bool[Literal[True]] + readingOrder: Min[float, Literal[False]] + def __init__( + self, + horizontal=None, + vertical=None, + textRotation: int = 0, + wrapText: _ConvertibleToBool | None = None, + shrinkToFit: _ConvertibleToBool | None = None, + indent: ConvertibleToFloat = 0, + relativeIndent: ConvertibleToFloat = 0, + justifyLastLine: _ConvertibleToBool | None = None, + readingOrder: ConvertibleToFloat = 0, + text_rotation=None, + wrap_text=None, + shrink_to_fit=None, + mergeCell=None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... diff --git a/stubs/openpyxl/openpyxl/styles/borders.pyi b/stubs/openpyxl/openpyxl/styles/borders.pyi new file mode 100644 index 000000000000..099ce57e7446 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/borders.pyi @@ -0,0 +1,82 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors.base import Alias, Bool, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +_SideStyle: TypeAlias = Literal[ + "dashDot", + "dashDotDot", + "dashed", + "dotted", + "double", + "hair", + "medium", + "mediumDashDot", + "mediumDashDotDot", + "mediumDashed", + "slantDashDot", + "thick", + "thin", +] + +BORDER_NONE: Final = None +BORDER_DASHDOT: Final = "dashDot" +BORDER_DASHDOTDOT: Final = "dashDotDot" +BORDER_DASHED: Final = "dashed" +BORDER_DOTTED: Final = "dotted" +BORDER_DOUBLE: Final = "double" +BORDER_HAIR: Final = "hair" +BORDER_MEDIUM: Final = "medium" +BORDER_MEDIUMDASHDOT: Final = "mediumDashDot" +BORDER_MEDIUMDASHDOTDOT: Final = "mediumDashDotDot" +BORDER_MEDIUMDASHED: Final = "mediumDashed" +BORDER_SLANTDASHDOT: Final = "slantDashDot" +BORDER_THICK: Final = "thick" +BORDER_THIN: Final = "thin" + +class Side(Serialisable): + color: ColorDescriptor[Literal[True]] + style: NoneSet[_SideStyle] + border_style: Alias + def __init__( + self, style: _SideStyle | Literal["none"] | None = None, color: str | Color | None = None, border_style=None + ) -> None: ... + +class Border(Serialisable): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + start: Typed[Side, Literal[True]] + end: Typed[Side, Literal[True]] + left: Typed[Side, Literal[True]] + right: Typed[Side, Literal[True]] + top: Typed[Side, Literal[True]] + bottom: Typed[Side, Literal[True]] + diagonal: Typed[Side, Literal[True]] + vertical: Typed[Side, Literal[True]] + horizontal: Typed[Side, Literal[True]] + outline: Bool[Literal[False]] + diagonalUp: Bool[Literal[False]] + diagonalDown: Bool[Literal[False]] + diagonal_direction: Incomplete + def __init__( + self, + left: Side | None = None, + right: Side | None = None, + top: Side | None = None, + bottom: Side | None = None, + diagonal: Side | None = None, + diagonal_direction=None, + vertical: Side | None = None, + horizontal: Side | None = None, + diagonalUp: _ConvertibleToBool = False, + diagonalDown: _ConvertibleToBool = False, + outline: _ConvertibleToBool = True, + start: Side | None = None, + end: Side | None = None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +DEFAULT_BORDER: Final[Border] diff --git a/stubs/openpyxl/openpyxl/styles/builtins.pyi b/stubs/openpyxl/openpyxl/styles/builtins.pyi new file mode 100644 index 000000000000..aabe58d9813f --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/builtins.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete + +normal: str +comma: str +comma_0: str +currency: str +currency_0: str +percent: str +hyperlink: str +followed_hyperlink: str +title: str +headline_1: str +headline_2: str +headline_3: str +headline_4: str +good: str +bad: str +neutral: str +input: str +output: str +calculation: str +linked_cell: str +check_cell: str +warning: str +note: str +explanatory: str +total: str +accent_1: str +accent_1_20: str +accent_1_40: str +accent_1_60: str +accent_2: str +accent_2_20: str +accent_2_40: str +accent_2_60: str +accent_3: str +accent_3_20: str +accent_3_40: str +accent_3_60: str +accent_4: str +accent_4_20: str +accent_4_40: str +accent_4_60: str +accent_5: str +accent_5_20: str +accent_5_40: str +accent_5_60: str +accent_6: str +accent_6_20: str +accent_6_40: str +accent_6_60: str +pandas_highlight: str +styles: Incomplete diff --git a/stubs/openpyxl/openpyxl/styles/cell_style.pyi b/stubs/openpyxl/openpyxl/styles/cell_style.pyi new file mode 100644 index 000000000000..dc7f6c278449 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/cell_style.pyi @@ -0,0 +1,98 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from array import array +from collections.abc import Iterable, MutableSequence +from typing import ClassVar, Generic, Literal, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors.base import Bool, Integer, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.protection import Protection + +_T = TypeVar("_T") + +class ArrayDescriptor(Generic[_T]): + key: int + def __init__(self, key: int) -> None: ... + def __get__(self, instance: MutableSequence[_T], cls: Unused) -> _T: ... + def __set__(self, instance: MutableSequence[_T], value: _T) -> None: ... + +class StyleArray(array[int]): + __slots__ = () + tagname: ClassVar[str] + fontId: ArrayDescriptor[int] + fillId: ArrayDescriptor[int] + borderId: ArrayDescriptor[int] + numFmtId: ArrayDescriptor[int] + protectionId: ArrayDescriptor[int] + alignmentId: ArrayDescriptor[int] + pivotButton: ArrayDescriptor[int] + quotePrefix: ArrayDescriptor[int] + xfId: ArrayDescriptor[int] + def __new__(cls, args: bytes | bytearray | Iterable[int] = [0, 0, 0, 0, 0, 0, 0, 0, 0]) -> Self: ... + def __hash__(self) -> int: ... # type: ignore[override] + def __copy__(self) -> StyleArray: ... + def __deepcopy__(self, memo: Unused) -> StyleArray: ... + +class CellStyle(Serialisable): + tagname: ClassVar[str] + numFmtId: Integer[Literal[False]] + fontId: Integer[Literal[False]] + fillId: Integer[Literal[False]] + borderId: Integer[Literal[False]] + xfId: Integer[Literal[True]] + quotePrefix: Bool[Literal[True]] + pivotButton: Bool[Literal[True]] + applyNumberFormat: Bool[Literal[True]] + applyFont: Bool[Literal[True]] + applyFill: Bool[Literal[True]] + applyBorder: Bool[Literal[True]] + # Overwritten by properties below + # applyAlignment: Bool[Literal[True]] + # applyProtection: Bool[Literal[True]] + alignment: Typed[Alignment, Literal[True]] + protection: Typed[Protection, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + numFmtId: ConvertibleToInt = 0, + fontId: ConvertibleToInt = 0, + fillId: ConvertibleToInt = 0, + borderId: ConvertibleToInt = 0, + xfId: ConvertibleToInt | None = None, + quotePrefix: _ConvertibleToBool | None = None, + pivotButton: _ConvertibleToBool | None = None, + applyNumberFormat: _ConvertibleToBool | None = None, + applyFont: _ConvertibleToBool | None = None, + applyFill: _ConvertibleToBool | None = None, + applyBorder: _ConvertibleToBool | None = None, + applyAlignment: Unused = None, + applyProtection: Unused = None, + alignment: Alignment | None = None, + protection: Protection | None = None, + extLst: Unused = None, + ) -> None: ... + def to_array(self): ... + @classmethod + def from_array(cls, style): ... + @property + def applyProtection(self) -> Literal[True] | None: ... + @property + def applyAlignment(self) -> Literal[True] | None: ... + +class CellStyleList(Serialisable): + tagname: ClassVar[str] + __attrs__: ClassVar[tuple[str, ...]] + # Overwritten by property below + # count: Integer + xf: Incomplete + alignment: Incomplete + protection: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, xf=()) -> None: ... + @property + def count(self) -> int: ... + def __getitem__(self, idx): ... diff --git a/stubs/openpyxl/openpyxl/styles/colors.pyi b/stubs/openpyxl/openpyxl/styles/colors.pyi new file mode 100644 index 000000000000..be92324686c0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/colors.pyi @@ -0,0 +1,95 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterator +from re import Pattern +from typing import ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Self + +from openpyxl.descriptors import Strict, Typed +from openpyxl.descriptors.base import _N, Bool, Integer, MinMax, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_S = TypeVar("_S", bound=Serialisable) + +COLOR_INDEX: Final[tuple[str, ...]] +BLACK: Final = "00000000" +WHITE: Final = "00FFFFFF" +BLUE: Final = "000000FF" +aRGB_REGEX: Final[Pattern[str]] + +class RGB(Typed[str, _N]): + expected_type: type[str] + + @overload + def __init__(self: RGB[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__(self: RGB[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False) -> None: ... + + @overload + def __set__(self: RGB[Literal[True]], instance: Serialisable | Strict, value: str | None) -> None: ... + @overload + def __set__(self: RGB[Literal[False]], instance: Serialisable | Strict, value: str) -> None: ... + +class Color(Serialisable): + tagname: ClassVar[str] + rgb: RGB[Literal[False]] + indexed: Integer[Literal[False]] + auto: Bool[Literal[False]] + theme: Integer[Literal[False]] + tint: MinMax[float, Literal[False]] + type: String[Literal[False]] + def __init__( + self, + rgb="00000000", + indexed: ConvertibleToInt | None = None, + auto: _ConvertibleToBool | None = None, + theme: ConvertibleToInt | None = None, + tint: ConvertibleToFloat = 0.0, + index: ConvertibleToInt | None = None, + type: Unused = "rgb", + ) -> None: ... + + @property + def value(self) -> str | int | bool: ... + @value.setter + def value(self, value: str | ConvertibleToInt | _ConvertibleToBool) -> None: ... + + def __iter__(self) -> Iterator[tuple[str, str]]: ... + @property + def index(self) -> str | int | bool: ... + + @overload + def __add__(self, other: Color) -> Self: ... + @overload + def __add__(self, other: _S) -> _S: ... + +class ColorDescriptor(Typed[Color, _N]): + expected_type: type[Color] + + @overload + def __init__(self: ColorDescriptor[Literal[True]], name: str | None = None, *, allow_none: Literal[True]) -> None: ... + @overload + def __init__( + self: ColorDescriptor[Literal[False]], name: str | None = None, *, allow_none: Literal[False] = False + ) -> None: ... + + @overload + def __set__(self: ColorDescriptor[Literal[True]], instance: Serialisable | Strict, value: str | Color | None) -> None: ... + @overload + def __set__(self: ColorDescriptor[Literal[False]], instance: Serialisable | Strict, value: str | Color) -> None: ... + +class RgbColor(Serialisable): + tagname: ClassVar[str] + rgb: RGB[Literal[False]] + def __init__(self, rgb: str) -> None: ... + +class ColorList(Serialisable): + tagname: ClassVar[str] + indexedColors: Incomplete + mruColors: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, indexedColors: list[RgbColor] | tuple[RgbColor, ...] = (), mruColors: list[Color] | tuple[Color, ...] = () + ) -> None: ... + def __bool__(self) -> bool: ... + @property + def index(self) -> list[str]: ... diff --git a/stubs/openpyxl/openpyxl/styles/differential.pyi b/stubs/openpyxl/openpyxl/styles/differential.pyi new file mode 100644 index 000000000000..aacdc31ef7b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/differential.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, SupportsIndex + +from openpyxl.descriptors.base import Alias, Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles import Alignment, Border, Fill, Font, Protection +from openpyxl.styles.numbers import NumberFormat + +class DifferentialStyle(Serialisable): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + font: Typed[Font, Literal[True]] + numFmt: Typed[NumberFormat, Literal[True]] + fill: Typed[Fill, Literal[True]] + alignment: Typed[Alignment, Literal[True]] + border: Typed[Border, Literal[True]] + protection: Typed[Protection, Literal[True]] + extLst: ExtensionList | None + def __init__( + self, + font: Font | None = None, + numFmt: NumberFormat | None = None, + fill: Fill | None = None, + alignment: Alignment | None = None, + border: Border | None = None, + protection: Protection | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + +class DifferentialStyleList(Serialisable): + tagname: ClassVar[str] + dxf: Incomplete + styles: Alias + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, dxf=(), count: Unused = None) -> None: ... + def append(self, dxf: DifferentialStyle) -> None: ... + def add(self, dxf: DifferentialStyle) -> int: ... + def __bool__(self) -> bool: ... + def __getitem__(self, idx: SupportsIndex) -> DifferentialStyle: ... + @property + def count(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/styles/fills.pyi b/stubs/openpyxl/openpyxl/styles/fills.pyi new file mode 100644 index 000000000000..498f9d1a7c15 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/fills.pyi @@ -0,0 +1,117 @@ +from _typeshed import ConvertibleToFloat, Incomplete, Unused +from collections.abc import Iterable, Iterator, Sequence as ABCSequence +from typing import ClassVar, Final, Literal, TypeAlias + +from openpyxl.descriptors import Sequence, Strict +from openpyxl.descriptors.base import Alias, Float, MinMax, NoneSet, Set +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndTag + +FILL_NONE: Final = "none" +FILL_SOLID: Final = "solid" +FILL_PATTERN_DARKDOWN: Final = "darkDown" +FILL_PATTERN_DARKGRAY: Final = "darkGray" +FILL_PATTERN_DARKGRID: Final = "darkGrid" +FILL_PATTERN_DARKHORIZONTAL: Final = "darkHorizontal" +FILL_PATTERN_DARKTRELLIS: Final = "darkTrellis" +FILL_PATTERN_DARKUP: Final = "darkUp" +FILL_PATTERN_DARKVERTICAL: Final = "darkVertical" +FILL_PATTERN_GRAY0625: Final = "gray0625" +FILL_PATTERN_GRAY125: Final = "gray125" +FILL_PATTERN_LIGHTDOWN: Final = "lightDown" +FILL_PATTERN_LIGHTGRAY: Final = "lightGray" +FILL_PATTERN_LIGHTGRID: Final = "lightGrid" +FILL_PATTERN_LIGHTHORIZONTAL: Final = "lightHorizontal" +FILL_PATTERN_LIGHTTRELLIS: Final = "lightTrellis" +FILL_PATTERN_LIGHTUP: Final = "lightUp" +FILL_PATTERN_LIGHTVERTICAL: Final = "lightVertical" +FILL_PATTERN_MEDIUMGRAY: Final = "mediumGray" + +_GradientFillType: TypeAlias = Literal["linear", "path"] +_FillsType: TypeAlias = Literal[ + "solid", + "darkDown", + "darkGray", + "darkGrid", + "darkHorizontal", + "darkTrellis", + "darkUp", + "darkVertical", + "gray0625", + "gray125", + "lightDown", + "lightGray", + "lightGrid", + "lightHorizontal", + "lightTrellis", + "lightUp", + "lightVertical", + "mediumGray", +] +fills: Final[tuple[_FillsType, ...]] + +class Fill(Serialisable): + tagname: ClassVar[str] + @classmethod + def from_tree(cls, el: Iterable[ABCSequence[_SupportsIterAndAttribAndTextAndTag]]) -> PatternFill | GradientFill | None: ... + +class PatternFill(Fill): + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + patternType: NoneSet[_FillsType] + fill_type: Alias + fgColor: ColorDescriptor[Literal[False]] + start_color: Alias + bgColor: ColorDescriptor[Literal[False]] + end_color: Alias + def __init__( + self, + patternType: _FillsType | Literal["none"] | None = None, + fgColor: str | Color = ..., + bgColor: str | Color = ..., + fill_type: _FillsType | Literal["none"] | None = None, + start_color: str | Color | None = None, + end_color: str | Color | None = None, + ) -> None: ... + def to_tree(self, tagname: Unused = None, idx: Unused = None) -> Element: ... # type: ignore[override] + +DEFAULT_EMPTY_FILL: Final[PatternFill] +DEFAULT_GRAY_FILL: Final[PatternFill] + +class Stop(Serialisable): + tagname: ClassVar[str] + position: MinMax[float, Literal[False]] + color: Incomplete + def __init__(self, color, position: ConvertibleToFloat) -> None: ... + +class StopList(Sequence[list[Stop]]): + expected_type: type[Stop] + def __set__(self, obj: Serialisable | Strict, values: list[Stop] | tuple[Stop, ...]) -> None: ... + +class GradientFill(Fill): + tagname: ClassVar[str] + type: Set[_GradientFillType] + fill_type: Alias + degree: Float[Literal[False]] + left: Float[Literal[False]] + right: Float[Literal[False]] + top: Float[Literal[False]] + bottom: Float[Literal[False]] + stop: Incomplete + def __init__( + self, + type: _GradientFillType = "linear", + degree: ConvertibleToFloat = 0, + left: ConvertibleToFloat = 0, + right: ConvertibleToFloat = 0, + top: ConvertibleToFloat = 0, + bottom: ConvertibleToFloat = 0, + stop=(), + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def to_tree( # type: ignore[override] + self, tagname: Unused = None, namespace: Unused = None, idx: Unused = None + ) -> Element: ... diff --git a/stubs/openpyxl/openpyxl/styles/fonts.pyi b/stubs/openpyxl/openpyxl/styles/fonts.pyi new file mode 100644 index 000000000000..48aeeb27d9b3 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/fonts.pyi @@ -0,0 +1,77 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt +from typing import ClassVar, Final, Literal, TypeAlias +from typing_extensions import Self + +from openpyxl.descriptors.base import Alias, _ConvertibleToBool +from openpyxl.descriptors.nested import ( + NestedBool, + NestedFloat, + NestedInteger, + NestedMinMax, + NestedNoneSet, + NestedString, + _NestedNoneSetParam, +) +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +from ..xml._functions_overloads import _HasTagAndGet, _SupportsFindAndIterAndAttribAndText + +_FontU: TypeAlias = Literal["single", "double", "singleAccounting", "doubleAccounting"] +_FontVertAlign: TypeAlias = Literal["superscript", "subscript", "baseline"] +_FontScheme: TypeAlias = Literal["major", "minor"] + +class Font(Serialisable): + UNDERLINE_DOUBLE: Final = "double" + UNDERLINE_DOUBLE_ACCOUNTING: Final = "doubleAccounting" + UNDERLINE_SINGLE: Final = "single" + UNDERLINE_SINGLE_ACCOUNTING: Final = "singleAccounting" + name: NestedString[Literal[True]] + charset: NestedInteger[Literal[True]] + family: NestedMinMax[float, Literal[True]] + sz: NestedFloat[Literal[True]] + size: Alias + b: NestedBool[Literal[False]] + bold: Alias + i: NestedBool[Literal[False]] + italic: Alias + strike: NestedBool[Literal[True]] + strikethrough: Alias + outline: NestedBool[Literal[True]] + shadow: NestedBool[Literal[True]] + condense: NestedBool[Literal[True]] + extend: NestedBool[Literal[True]] + u: NestedNoneSet[_FontU] + underline: Alias + vertAlign: NestedNoneSet[_FontVertAlign] + color: ColorDescriptor[Literal[True]] + scheme: NestedNoneSet[_FontScheme] + tagname: ClassVar[str] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: object = None, + sz: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + b: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + i: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool = None, + charset: _HasTagAndGet[ConvertibleToInt | None] | ConvertibleToInt | None = None, + u: _NestedNoneSetParam[_FontU] = None, + strike: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + color: str | Color | None = None, + scheme: _NestedNoneSetParam[_FontScheme] = None, + family: _HasTagAndGet[ConvertibleToFloat | None] | ConvertibleToFloat | None = None, + size: _HasTagAndGet[ConvertibleToFloat] | ConvertibleToFloat | None = None, + bold: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + italic: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + strikethrough: _HasTagAndGet[_ConvertibleToBool] | _ConvertibleToBool | None = None, + underline: _NestedNoneSetParam[_FontU] = None, + vertAlign: _NestedNoneSetParam[_FontVertAlign] = None, + outline: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + shadow: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + condense: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + extend: _HasTagAndGet[_ConvertibleToBool | None] | _ConvertibleToBool | None = None, + ) -> None: ... + @classmethod + def from_tree(cls, node: _SupportsFindAndIterAndAttribAndText) -> Self: ... + +DEFAULT_FONT: Final[Font] diff --git a/stubs/openpyxl/openpyxl/styles/named_styles.pyi b/stubs/openpyxl/openpyxl/styles/named_styles.pyi new file mode 100644 index 000000000000..13af11fa42d8 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/named_styles.pyi @@ -0,0 +1,83 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterable, Iterator +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.alignment import Alignment +from openpyxl.styles.borders import Border +from openpyxl.styles.cell_style import CellStyle, StyleArray +from openpyxl.styles.fills import Fill +from openpyxl.styles.fonts import Font +from openpyxl.styles.protection import Protection +from openpyxl.workbook.workbook import Workbook + +class NamedStyle(Serialisable): + font: Typed[Font, Literal[False]] + fill: Typed[Fill, Literal[False]] + border: Typed[Border, Literal[False]] + alignment: Typed[Alignment, Literal[False]] + number_format: Incomplete + protection: Typed[Protection, Literal[False]] + builtinId: Integer[Literal[True]] + hidden: Bool[Literal[True]] + name: String[Literal[False]] + def __init__( + self, + name: str = "Normal", + font: Font | None = None, + fill: Fill | None = None, + border: Border | None = None, + alignment: Alignment | None = None, + number_format=None, + protection: Protection | None = None, + builtinId: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = False, + ) -> None: ... + def __setattr__(self, attr: str, value) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def bind(self, wb: Workbook) -> None: ... + def as_tuple(self) -> StyleArray: ... + def as_xf(self) -> CellStyle: ... + def as_name(self) -> _NamedCellStyle: ... + +class NamedStyleList(list[NamedStyle]): + def __init__(self, iterable: Iterable[NamedStyle] = ()) -> None: ... + @property + def names(self) -> list[str]: ... + def __getitem__(self, key: int | str) -> NamedStyle: ... # type: ignore[override] + def append(self, style: NamedStyle) -> None: ... + +class _NamedCellStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + xfId: Integer[Literal[False]] + builtinId: Integer[Literal[True]] + iLevel: Integer[Literal[True]] + hidden: Bool[Literal[True]] + customBuiltin: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + xfId: ConvertibleToInt, + builtinId: ConvertibleToInt | None = None, + iLevel: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = None, + customBuiltin: _ConvertibleToBool | None = None, + extLst: Unused = None, + ) -> None: ... + +class _NamedCellStyleList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer[Literal[True]] + cellStyle: Sequence[list[_NamedCellStyle]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, cellStyle: list[_NamedCellStyle] | tuple[_NamedCellStyle, ...] = ()) -> None: ... + @property + def count(self) -> int: ... + def remove_duplicates(self) -> list[_NamedCellStyle]: ... diff --git a/stubs/openpyxl/openpyxl/styles/numbers.pyi b/stubs/openpyxl/openpyxl/styles/numbers.pyi new file mode 100644 index 000000000000..abadbf89e764 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/numbers.pyi @@ -0,0 +1,86 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from re import Pattern +from typing import ClassVar, Final, Literal, SupportsIndex, TypeGuard, overload + +from openpyxl.descriptors import Strict, String +from openpyxl.descriptors.base import Integer +from openpyxl.descriptors.serialisable import Serialisable + +BUILTIN_FORMATS: Final[dict[int, str]] +BUILTIN_FORMATS_MAX_SIZE: Final = 164 +BUILTIN_FORMATS_REVERSE: Final[dict[str, int]] +FORMAT_GENERAL: Final = "General" +FORMAT_TEXT: Final = "@" +FORMAT_NUMBER: Final = "0" +FORMAT_NUMBER_00: Final = "0.00" +FORMAT_NUMBER_COMMA_SEPARATED1: Final = "#,##0.00" +FORMAT_NUMBER_COMMA_SEPARATED2: Final = "#,##0.00_-" +FORMAT_PERCENTAGE: Final = "0%" +FORMAT_PERCENTAGE_00: Final = "0.00%" +FORMAT_DATE_YYYYMMDD2: Final = "yyyy-mm-dd" +FORMAT_DATE_YYMMDD: Final = "yy-mm-dd" +FORMAT_DATE_DDMMYY: Final = "dd/mm/yy" +FORMAT_DATE_DMYSLASH: Final = "d/m/y" +FORMAT_DATE_DMYMINUS: Final = "d-m-y" +FORMAT_DATE_DMMINUS: Final = "d-m" +FORMAT_DATE_MYMINUS: Final = "m-y" +FORMAT_DATE_XLSX14: Final = "mm-dd-yy" +FORMAT_DATE_XLSX15: Final = "d-mmm-yy" +FORMAT_DATE_XLSX16: Final = "d-mmm" +FORMAT_DATE_XLSX17: Final = "mmm-yy" +FORMAT_DATE_XLSX22: Final = "m/d/yy h:mm" +FORMAT_DATE_DATETIME: Final = "yyyy-mm-dd h:mm:ss" +FORMAT_DATE_TIME1: Final = "h:mm AM/PM" +FORMAT_DATE_TIME2: Final = "h:mm:ss AM/PM" +FORMAT_DATE_TIME3: Final = "h:mm" +FORMAT_DATE_TIME4: Final = "h:mm:ss" +FORMAT_DATE_TIME5: Final = "mm:ss" +FORMAT_DATE_TIME6: Final = "h:mm:ss" +FORMAT_DATE_TIME7: Final = "i:s.S" +FORMAT_DATE_TIME8: Final = "h:mm:ss@" +FORMAT_DATE_TIMEDELTA: Final = "[hh]:mm:ss" +FORMAT_DATE_YYMMDDSLASH: Final = "yy/mm/dd@" +FORMAT_CURRENCY_USD_SIMPLE: Final = '"$"#,##0.00_-' +FORMAT_CURRENCY_USD: Final = "$#,##0_-" +FORMAT_CURRENCY_EUR_SIMPLE: Final = "[$EUR ]#,##0.00_-" + +COLORS: Final[str] +LITERAL_GROUP: Final = r'".*?"' +LOCALE_GROUP: Final = r"\[(?!hh?\]|mm?\]|ss?\])[^\]]*\]" +STRIP_RE: Final[Pattern[str]] +TIMEDELTA_RE: Final[Pattern[str]] + +def is_date_format(fmt: str | None) -> TypeGuard[str]: ... +def is_timedelta_format(fmt: str | None) -> TypeGuard[str]: ... + +@overload +def is_datetime(fmt: None) -> None: ... +@overload +def is_datetime(fmt: str) -> Literal["datetime", "date", "time"] | None: ... + +def is_builtin(fmt: str | None) -> TypeGuard[str]: ... +def builtin_format_code(index: int) -> str | None: ... + +@overload +def builtin_format_id(fmt: None) -> None: ... +@overload +def builtin_format_id(fmt: str) -> int | None: ... + +class NumberFormatDescriptor(String[Incomplete]): + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class NumberFormat(Serialisable): + numFmtId: Integer[Literal[False]] + formatCode: String[Literal[False]] + def __init__(self, numFmtId: ConvertibleToInt, formatCode: str) -> None: ... + +class NumberFormatList(Serialisable): + # Overwritten by property below + # count: Integer + numFmt: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, numFmt=()) -> None: ... + @property + def count(self) -> int: ... + def __getitem__(self, idx: SupportsIndex) -> NumberFormat: ... diff --git a/stubs/openpyxl/openpyxl/styles/protection.pyi b/stubs/openpyxl/openpyxl/styles/protection.pyi new file mode 100644 index 000000000000..8d4652f2e5b0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/protection.pyi @@ -0,0 +1,10 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Protection(Serialisable): + tagname: ClassVar[str] + locked: Bool[Literal[False]] + hidden: Bool[Literal[False]] + def __init__(self, locked: _ConvertibleToBool = True, hidden: _ConvertibleToBool = False) -> None: ... diff --git a/stubs/openpyxl/openpyxl/styles/proxy.pyi b/stubs/openpyxl/openpyxl/styles/proxy.pyi new file mode 100644 index 000000000000..1fd18127d71e --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/proxy.pyi @@ -0,0 +1,13 @@ +from typing_extensions import deprecated + +class StyleProxy: + __slots__ = "__target" + def __init__(self, target) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def __copy__(self): ... + def __add__(self, other): ... + @deprecated("Use copy(obj) or cell.obj = cell.obj + other") + def copy(self, **kw): ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/styles/styleable.pyi b/stubs/openpyxl/openpyxl/styles/styleable.pyi new file mode 100644 index 000000000000..1601d769d14b --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/styleable.pyi @@ -0,0 +1,54 @@ +from _typeshed import Unused +from collections.abc import Iterable + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet + +from .named_styles import NamedStyle +from .proxy import StyleProxy + +class StyleDescriptor: + collection: str + key: str + def __init__(self, collection: str, key: str) -> None: ... + def __set__(self, instance: StyleableObject, value: Serialisable) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> StyleProxy: ... + +class NumberFormatDescriptor: + key: str + collection: str + def __set__(self, instance: StyleableObject, value: str) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> str: ... + +class NamedStyleDescriptor: + key: str + collection: str + def __set__(self, instance: StyleableObject, value: NamedStyle | str) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> str: ... + +class StyleArrayDescriptor: + key: str + def __init__(self, key: str) -> None: ... + def __set__(self, instance: StyleableObject, value: int) -> None: ... + def __get__(self, instance: StyleableObject, cls: Unused) -> bool: ... + +class StyleableObject: + __slots__ = ("parent", "_style") + font: StyleDescriptor + fill: StyleDescriptor + border: StyleDescriptor + number_format: NumberFormatDescriptor + protection: StyleDescriptor + alignment: StyleDescriptor + style: NamedStyleDescriptor + quotePrefix: StyleArrayDescriptor + pivotButton: StyleArrayDescriptor + parent: _WorkbookChild | ReadOnlyWorksheet + def __init__( + self, sheet: _WorkbookChild | ReadOnlyWorksheet, style_array: bytes | bytearray | Iterable[int] | None = None + ) -> None: ... + @property + def style_id(self) -> int: ... + @property + def has_style(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/styles/stylesheet.pyi b/stubs/openpyxl/openpyxl/styles/stylesheet.pyi new file mode 100644 index 000000000000..c977920767fa --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/stylesheet.pyi @@ -0,0 +1,59 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar, Literal, TypeVar +from typing_extensions import Self +from zipfile import ZipFile + +from openpyxl.descriptors.base import Typed +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.styles.cell_style import CellStyleList +from openpyxl.styles.colors import ColorList +from openpyxl.styles.named_styles import _NamedCellStyleList +from openpyxl.styles.numbers import NumberFormatList +from openpyxl.styles.table import TableStyleList +from openpyxl.workbook.workbook import Workbook +from openpyxl.xml.functions import Element + +_WorkbookT = TypeVar("_WorkbookT", bound=Workbook) + +class Stylesheet(Serialisable): + tagname: ClassVar[str] + numFmts: Typed[NumberFormatList, Literal[False]] + fonts: Incomplete + fills: Incomplete + borders: Incomplete + cellStyleXfs: Typed[CellStyleList, Literal[False]] + cellXfs: Typed[CellStyleList, Literal[False]] + cellStyles: Typed[_NamedCellStyleList, Literal[False]] + dxfs: Incomplete + tableStyles: Typed[TableStyleList, Literal[True]] + colors: Typed[ColorList, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + number_formats: Incomplete + cell_styles: Incomplete + alignments: Incomplete + protections: Incomplete + named_styles: Incomplete + def __init__( + self, + numFmts: NumberFormatList | None = None, + fonts=(), + fills=(), + borders=(), + cellStyleXfs: CellStyleList | None = None, + cellXfs: CellStyleList | None = None, + cellStyles: _NamedCellStyleList | None = None, + dxfs=(), + tableStyles: TableStyleList | None = None, + colors: ColorList | None = None, + extLst: Unused = None, + ) -> None: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + @property + def custom_formats(self) -> dict[int, str]: ... + def to_tree(self, tagname: str | None = None, idx: Unused = None, namespace: str | None = None) -> Element: ... + +def apply_stylesheet(archive: ZipFile, wb: _WorkbookT) -> _WorkbookT | None: ... +def write_stylesheet(wb: Workbook): ... diff --git a/stubs/openpyxl/openpyxl/styles/table.pyi b/stubs/openpyxl/openpyxl/styles/table.pyi new file mode 100644 index 000000000000..03e629854e3c --- /dev/null +++ b/stubs/openpyxl/openpyxl/styles/table.pyi @@ -0,0 +1,79 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Integer, Set, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_TableStyleElementType: TypeAlias = Literal[ + "wholeTable", + "headerRow", + "totalRow", + "firstColumn", + "lastColumn", + "firstRowStripe", + "secondRowStripe", + "firstColumnStripe", + "secondColumnStripe", + "firstHeaderCell", + "lastHeaderCell", + "firstTotalCell", + "lastTotalCell", + "firstSubtotalColumn", + "secondSubtotalColumn", + "thirdSubtotalColumn", + "firstSubtotalRow", + "secondSubtotalRow", + "thirdSubtotalRow", + "blankRow", + "firstColumnSubheading", + "secondColumnSubheading", + "thirdColumnSubheading", + "firstRowSubheading", + "secondRowSubheading", + "thirdRowSubheading", + "pageFieldLabels", + "pageFieldValues", +] + +class TableStyleElement(Serialisable): + tagname: ClassVar[str] + type: Set[_TableStyleElementType] + size: Integer[Literal[True]] + dxfId: Integer[Literal[True]] + def __init__( + self, type: _TableStyleElementType, size: ConvertibleToInt | None = None, dxfId: ConvertibleToInt | None = None + ) -> None: ... + +class TableStyle(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + pivot: Bool[Literal[True]] + table: Bool[Literal[True]] + count: Integer[Literal[True]] + tableStyleElement: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + name: str, + pivot: _ConvertibleToBool | None = None, + table: _ConvertibleToBool | None = None, + count: ConvertibleToInt | None = None, + tableStyleElement=(), + ) -> None: ... + +class TableStyleList(Serialisable): + tagname: ClassVar[str] + defaultTableStyle: String[Literal[True]] + defaultPivotStyle: String[Literal[True]] + tableStyle: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + count: Unused = None, + defaultTableStyle: str | None = "TableStyleMedium9", + defaultPivotStyle: str | None = "PivotStyleLight16", + tableStyle=(), + ) -> None: ... + @property + def count(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/utils/__init__.pyi b/stubs/openpyxl/openpyxl/utils/__init__.pyi new file mode 100644 index 000000000000..ba45939538be --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/__init__.pyi @@ -0,0 +1,13 @@ +from .cell import ( + absolute_coordinate as absolute_coordinate, + cols_from_range as cols_from_range, + column_index_from_string as column_index_from_string, + coordinate_to_tuple as coordinate_to_tuple, + get_column_interval as get_column_interval, + get_column_letter as get_column_letter, + quote_sheetname as quote_sheetname, + range_boundaries as range_boundaries, + range_to_tuple as range_to_tuple, + rows_from_range as rows_from_range, +) +from .formulas import FORMULAE as FORMULAE diff --git a/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi b/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi new file mode 100644 index 000000000000..c4556fa4bb90 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/bound_dictionary.pyi @@ -0,0 +1,9 @@ +from collections import defaultdict +from typing import TypeVar + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +class BoundDictionary(defaultdict[_KT, _VT]): + reference: str | None + def __init__(self, reference: str | None = None, *args, **kw) -> None: ... diff --git a/stubs/openpyxl/openpyxl/utils/cell.pyi b/stubs/openpyxl/openpyxl/utils/cell.pyi new file mode 100644 index 000000000000..cb26c68f39be --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/cell.pyi @@ -0,0 +1,26 @@ +from collections.abc import Generator +from re import Pattern +from typing import Final, TypeAlias + +# "1:1" | "A1:A1" | "A:A" +_RangeBoundariesTuple: TypeAlias = tuple[None, int, None, int] | tuple[int, int, int, int] | tuple[int, None, int, None] + +COORD_RE: Final[Pattern[str]] +COL_RANGE: Final = "[A-Z]{1,3}:[A-Z]{1,3}:" +ROW_RANGE: Final = r"\d+:\d+:" +RANGE_EXPR: Final[str] +ABSOLUTE_RE: Final[Pattern[str]] +SHEET_TITLE: Final[str] +SHEETRANGE_RE: Final[Pattern[str]] + +def get_column_interval(start: str | int, end: str | int) -> list[str]: ... +def coordinate_from_string(coord_string: str) -> tuple[str, int]: ... +def absolute_coordinate(coord_string: str) -> str: ... +def get_column_letter(col_idx: int) -> str: ... +def column_index_from_string(col: str) -> int: ... +def range_boundaries(range_string: str) -> _RangeBoundariesTuple: ... +def rows_from_range(range_string: str) -> Generator[tuple[str, ...]]: ... +def cols_from_range(range_string: str) -> Generator[tuple[str, ...]]: ... +def coordinate_to_tuple(coordinate: str) -> tuple[int, int]: ... +def range_to_tuple(range_string: str) -> tuple[str, _RangeBoundariesTuple]: ... +def quote_sheetname(sheetname: str) -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/dataframe.pyi b/stubs/openpyxl/openpyxl/utils/dataframe.pyi new file mode 100644 index 000000000000..592aded19426 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/dataframe.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +def dataframe_to_rows(df, index: bool = True, header: bool = True) -> Generator[Incomplete]: ... +def expand_index(index, header: bool = False) -> Generator[Incomplete]: ... diff --git a/stubs/openpyxl/openpyxl/utils/datetime.pyi b/stubs/openpyxl/openpyxl/utils/datetime.pyi new file mode 100644 index 000000000000..ecb645ccb656 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/datetime.pyi @@ -0,0 +1,21 @@ +from datetime import datetime +from re import Pattern +from typing import Final + +MAC_EPOCH: Final[datetime] +WINDOWS_EPOCH: Final[datetime] +# The following two constants are defined twice in the implementation. +CALENDAR_WINDOWS_1900 = WINDOWS_EPOCH +CALENDAR_MAC_1904 = MAC_EPOCH +SECS_PER_DAY: Final = 86400 +ISO_FORMAT: Final = "%Y-%m-%dT%H:%M:%SZ" +ISO_REGEX: Final[Pattern[str]] +ISO_DURATION: Final[Pattern[str]] + +def to_ISO8601(dt): ... +def from_ISO8601(formatted_string): ... +def to_excel(dt, epoch=...): ... +def from_excel(value, epoch=..., timedelta: bool = False): ... +def time_to_days(value): ... +def timedelta_to_days(value): ... +def days_to_time(value): ... diff --git a/stubs/openpyxl/openpyxl/utils/escape.pyi b/stubs/openpyxl/openpyxl/utils/escape.pyi new file mode 100644 index 000000000000..0ad3a1008f0a --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/escape.pyi @@ -0,0 +1,2 @@ +def escape(value: str) -> str: ... +def unescape(value: str) -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/exceptions.pyi b/stubs/openpyxl/openpyxl/utils/exceptions.pyi new file mode 100644 index 000000000000..5e9ebead8950 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/exceptions.pyi @@ -0,0 +1,7 @@ +class CellCoordinatesException(Exception): ... +class IllegalCharacterError(Exception): ... +class NamedRangeException(Exception): ... +class SheetTitleException(Exception): ... +class InvalidFileException(Exception): ... +class ReadOnlyWorkbookException(Exception): ... +class WorkbookAlreadySaved(Exception): ... diff --git a/stubs/openpyxl/openpyxl/utils/formulas.pyi b/stubs/openpyxl/openpyxl/utils/formulas.pyi new file mode 100644 index 000000000000..ea7f2d97bc85 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/formulas.pyi @@ -0,0 +1,5 @@ +from typing import Final + +FORMULAE: Final[frozenset[str]] + +def validate(formula: str) -> None: ... diff --git a/stubs/openpyxl/openpyxl/utils/indexed_list.pyi b/stubs/openpyxl/openpyxl/utils/indexed_list.pyi new file mode 100644 index 000000000000..9bf453a0468b --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/indexed_list.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable +from typing import TypeVar + +_T = TypeVar("_T") + +class IndexedList(list[_T]): + clean: bool + def __init__(self, iterable: Iterable[_T] | None = None) -> None: ... + def __contains__(self, value: object) -> bool: ... + def index(self, value: _T) -> int: ... # type: ignore[override] + def append(self, value: _T) -> None: ... + def add(self, value: _T) -> int: ... diff --git a/stubs/openpyxl/openpyxl/utils/inference.pyi b/stubs/openpyxl/openpyxl/utils/inference.pyi new file mode 100644 index 000000000000..5787b6f19652 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/inference.pyi @@ -0,0 +1,10 @@ +from re import Pattern +from typing import Final + +PERCENT_REGEX: Final[Pattern[str]] +TIME_REGEX: Final[Pattern[str]] +NUMBER_REGEX: Final[Pattern[str]] + +def cast_numeric(value): ... +def cast_percentage(value): ... +def cast_time(value): ... diff --git a/stubs/openpyxl/openpyxl/utils/protection.pyi b/stubs/openpyxl/openpyxl/utils/protection.pyi new file mode 100644 index 000000000000..4bcddbe2b676 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/protection.pyi @@ -0,0 +1 @@ +def hash_password(plaintext_password: str = "") -> str: ... diff --git a/stubs/openpyxl/openpyxl/utils/units.pyi b/stubs/openpyxl/openpyxl/utils/units.pyi new file mode 100644 index 000000000000..6a799ed06424 --- /dev/null +++ b/stubs/openpyxl/openpyxl/utils/units.pyi @@ -0,0 +1,24 @@ +from typing import Final + +DEFAULT_ROW_HEIGHT: Final[float] +BASE_COL_WIDTH: Final = 8 +DEFAULT_COLUMN_WIDTH: Final = 13 +DEFAULT_LEFT_MARGIN: Final[float] +DEFAULT_TOP_MARGIN: Final[float] +DEFAULT_HEADER: Final[float] + +def inch_to_dxa(value): ... +def dxa_to_inch(value): ... +def dxa_to_cm(value): ... +def cm_to_dxa(value): ... +def pixels_to_EMU(value): ... +def EMU_to_pixels(value): ... +def cm_to_EMU(value): ... +def EMU_to_cm(value): ... +def inch_to_EMU(value): ... +def EMU_to_inch(value): ... +def pixels_to_points(value, dpi: int = 96): ... +def points_to_pixels(value, dpi: int = 96): ... +def degrees_to_angle(value): ... +def angle_to_degrees(value): ... +def short_color(color): ... diff --git a/stubs/openpyxl/openpyxl/workbook/__init__.pyi b/stubs/openpyxl/openpyxl/workbook/__init__.pyi new file mode 100644 index 000000000000..af0aa0b81088 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/__init__.pyi @@ -0,0 +1 @@ +from .workbook import Workbook as Workbook diff --git a/stubs/openpyxl/openpyxl/workbook/_writer.pyi b/stubs/openpyxl/openpyxl/workbook/_writer.pyi new file mode 100644 index 000000000000..40e639a58d32 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/_writer.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete + +from openpyxl.workbook.workbook import Workbook + +def get_active_sheet(wb: Workbook) -> int | None: ... + +class WorkbookWriter: + wb: Workbook + rels: Incomplete + package: Incomplete + def __init__(self, wb: Workbook) -> None: ... + def write_properties(self) -> None: ... + def write_worksheets(self) -> None: ... + def write_refs(self) -> None: ... + def write_names(self) -> None: ... + def write_pivots(self) -> None: ... + def write_views(self) -> None: ... + def write(self): ... + def write_rels(self): ... + def write_root_rels(self): ... diff --git a/stubs/openpyxl/openpyxl/workbook/child.pyi b/stubs/openpyxl/openpyxl/workbook/child.pyi new file mode 100644 index 000000000000..7e9df7c885a1 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/child.pyi @@ -0,0 +1,57 @@ +from collections.abc import Iterable +from re import Pattern +from typing import Final + +from openpyxl import _Decodable +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.header_footer import HeaderFooter, HeaderFooterItem + +INVALID_TITLE_REGEX: Final[Pattern[str]] + +def avoid_duplicate_name(names: Iterable[str], value: str) -> str: ... + +class _WorkbookChild: + HeaderFooter: HeaderFooter + def __init__(self, parent: Workbook | None = None, title: str | _Decodable | None = None) -> None: ... + @property + def parent(self) -> Workbook | None: ... + @property + def encoding(self) -> str: ... # Will error without a parent. + + @property + def title(self) -> str: ... + @title.setter + def title(self, value: str | _Decodable) -> None: ... + + @property + def oddHeader(self) -> HeaderFooterItem | None: ... + @oddHeader.setter + def oddHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def oddFooter(self) -> HeaderFooterItem | None: ... + @oddFooter.setter + def oddFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def evenHeader(self) -> HeaderFooterItem | None: ... + @evenHeader.setter + def evenHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def evenFooter(self) -> HeaderFooterItem | None: ... + @evenFooter.setter + def evenFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def firstHeader(self) -> HeaderFooterItem | None: ... + @firstHeader.setter + def firstHeader(self, value: HeaderFooterItem | None) -> None: ... + + @property + def firstFooter(self) -> HeaderFooterItem | None: ... + @firstFooter.setter + def firstFooter(self, value: HeaderFooterItem | None) -> None: ... + + @property + def path(self) -> str: ... diff --git a/stubs/openpyxl/openpyxl/workbook/defined_name.pyi b/stubs/openpyxl/openpyxl/workbook/defined_name.pyi new file mode 100644 index 000000000000..aa8780463371 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/defined_name.pyi @@ -0,0 +1,71 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections import defaultdict +from collections.abc import Generator, Iterator +from re import Pattern +from typing import ClassVar, Final, Literal + +from openpyxl.descriptors import Sequence +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.formula.tokenizer import _TokenOperandSubtypes, _TokenTypesNotOperand + +RESERVED: Final[frozenset[str]] +RESERVED_REGEX: Final[Pattern[str]] + +class DefinedName(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + comment: String[Literal[True]] + customMenu: String[Literal[True]] + description: String[Literal[True]] + help: String[Literal[True]] + statusBar: String[Literal[True]] + localSheetId: Integer[Literal[True]] + hidden: Bool[Literal[True]] + function: Bool[Literal[True]] + vbProcedure: Bool[Literal[True]] + xlm: Bool[Literal[True]] + functionGroupId: Integer[Literal[True]] + shortcutKey: String[Literal[True]] + publishToServer: Bool[Literal[True]] + workbookParameter: Bool[Literal[True]] + attr_text: Incomplete + value: Alias + def __init__( + self, + name: str, + comment: str | None = None, + customMenu: str | None = None, + description: str | None = None, + help: str | None = None, + statusBar: str | None = None, + localSheetId: ConvertibleToInt | None = None, + hidden: _ConvertibleToBool | None = None, + function: _ConvertibleToBool | None = None, + vbProcedure: _ConvertibleToBool | None = None, + xlm: _ConvertibleToBool | None = None, + functionGroupId: ConvertibleToInt | None = None, + shortcutKey: str | None = None, + publishToServer: _ConvertibleToBool | None = None, + workbookParameter: _ConvertibleToBool | None = None, + attr_text=None, + ) -> None: ... + @property + def type(self) -> _TokenTypesNotOperand | _TokenOperandSubtypes: ... + @property + def destinations(self) -> Generator[tuple[str, str]]: ... + @property + def is_reserved(self) -> str | None: ... + @property + def is_external(self) -> bool: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +class DefinedNameDict(dict[str, DefinedName]): + def add(self, value: DefinedName) -> None: ... + +class DefinedNameList(Serialisable): + tagname: ClassVar[str] + definedName: Sequence[list[DefinedName]] + def __init__(self, definedName: list[DefinedName] | tuple[DefinedName, ...] = ()) -> None: ... + def by_sheet(self) -> defaultdict[int, DefinedNameDict]: ... + def __len__(self) -> int: ... diff --git a/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi b/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi new file mode 100644 index 000000000000..37ef93721979 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_link/__init__.pyi @@ -0,0 +1 @@ +from .external import ExternalLink as ExternalLink diff --git a/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi b/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi new file mode 100644 index 000000000000..32cbcbd7371e --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_link/external.pyi @@ -0,0 +1,80 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias +from zipfile import ZipFile + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.packaging.relationship import Relationship +from openpyxl.xml.functions import Element + +_ExternalCellType: TypeAlias = Literal["b", "d", "n", "e", "s", "str", "inlineStr"] + +class ExternalCell(Serialisable): + r: String[Literal[False]] + t: NoneSet[_ExternalCellType] + vm: Integer[Literal[True]] + v: NestedText[str, Literal[True]] + def __init__( + self, r: str, t: _ExternalCellType | Literal["none"] | None = None, vm: ConvertibleToInt | None = None, v: object = None + ) -> None: ... + +class ExternalRow(Serialisable): + r: Integer[Literal[False]] + cell: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, r: ConvertibleToInt, cell=None) -> None: ... + +class ExternalSheetData(Serialisable): + sheetId: Integer[Literal[False]] + refreshError: Bool[Literal[True]] + row: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetId: ConvertibleToInt, refreshError: _ConvertibleToBool | None = None, row=()) -> None: ... + +class ExternalSheetDataSet(Serialisable): + sheetData: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetData=None) -> None: ... + +class ExternalSheetNames(Serialisable): + sheetName: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetName=()) -> None: ... + +class ExternalDefinedName(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + refersTo: String[Literal[True]] + sheetId: Integer[Literal[True]] + def __init__(self, name: str, refersTo: str | None = None, sheetId: ConvertibleToInt | None = None) -> None: ... + +class ExternalBook(Serialisable): + tagname: ClassVar[str] + sheetNames: Typed[ExternalSheetNames, Literal[True]] + definedNames: Incomplete + sheetDataSet: Typed[ExternalSheetDataSet, Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + sheetNames: ExternalSheetNames | None = None, + definedNames=(), + sheetDataSet: ExternalSheetDataSet | None = None, + id=None, + ) -> None: ... + +class ExternalLink(Serialisable): + tagname: ClassVar[str] + mime_type: str + externalBook: Typed[ExternalBook, Literal[True]] + file_link: Typed[Relationship, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, externalBook: ExternalBook | None = None, ddeLink: Unused = None, oleLink: Unused = None, extLst: Unused = None + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + +def read_external_link(archive: ZipFile, book_path: str) -> ExternalLink: ... diff --git a/stubs/openpyxl/openpyxl/workbook/external_reference.pyi b/stubs/openpyxl/openpyxl/workbook/external_reference.pyi new file mode 100644 index 000000000000..4b202d9ce5ee --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/external_reference.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class ExternalReference(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/function_group.pyi b/stubs/openpyxl/openpyxl/workbook/function_group.pyi new file mode 100644 index 000000000000..48bc87d80b8d --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/function_group.pyi @@ -0,0 +1,17 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Integer, String +from openpyxl.descriptors.serialisable import Serialisable + +class FunctionGroup(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class FunctionGroupList(Serialisable): + tagname: ClassVar[str] + builtInGroupCount: Integer[Literal[True]] + functionGroup: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, builtInGroupCount: ConvertibleToInt | None = 16, functionGroup=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/properties.pyi b/stubs/openpyxl/openpyxl/workbook/properties.pyi new file mode 100644 index 000000000000..145df27bd4b5 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/properties.pyi @@ -0,0 +1,102 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WorkbookPropertiesShowObjects: TypeAlias = Literal["all", "placeholders"] +_WorkbookPropertiesUpdateLinks: TypeAlias = Literal["userSet", "never", "always"] +_CalcPropertiesCalcMode: TypeAlias = Literal["manual", "auto", "autoNoTable"] +_CalcPropertiesRefMode: TypeAlias = Literal["A1", "R1C1"] + +class WorkbookProperties(Serialisable): + tagname: ClassVar[str] + date1904: Bool[Literal[True]] + dateCompatibility: Bool[Literal[True]] + showObjects: NoneSet[_WorkbookPropertiesShowObjects] + showBorderUnselectedTables: Bool[Literal[True]] + filterPrivacy: Bool[Literal[True]] + promptedSolutions: Bool[Literal[True]] + showInkAnnotation: Bool[Literal[True]] + backupFile: Bool[Literal[True]] + saveExternalLinkValues: Bool[Literal[True]] + updateLinks: NoneSet[_WorkbookPropertiesUpdateLinks] + codeName: String[Literal[True]] + hidePivotFieldList: Bool[Literal[True]] + showPivotChartFilter: Bool[Literal[True]] + allowRefreshQuery: Bool[Literal[True]] + publishItems: Bool[Literal[True]] + checkCompatibility: Bool[Literal[True]] + autoCompressPictures: Bool[Literal[True]] + refreshAllConnections: Bool[Literal[True]] + defaultThemeVersion: Integer[Literal[True]] + def __init__( + self, + date1904: _ConvertibleToBool | None = None, + dateCompatibility: _ConvertibleToBool | None = None, + showObjects: _WorkbookPropertiesShowObjects | Literal["none"] | None = None, + showBorderUnselectedTables: _ConvertibleToBool | None = None, + filterPrivacy: _ConvertibleToBool | None = None, + promptedSolutions: _ConvertibleToBool | None = None, + showInkAnnotation: _ConvertibleToBool | None = None, + backupFile: _ConvertibleToBool | None = None, + saveExternalLinkValues: _ConvertibleToBool | None = None, + updateLinks: _WorkbookPropertiesUpdateLinks | Literal["none"] | None = None, + codeName: str | None = None, + hidePivotFieldList: _ConvertibleToBool | None = None, + showPivotChartFilter: _ConvertibleToBool | None = None, + allowRefreshQuery: _ConvertibleToBool | None = None, + publishItems: _ConvertibleToBool | None = None, + checkCompatibility: _ConvertibleToBool | None = None, + autoCompressPictures: _ConvertibleToBool | None = None, + refreshAllConnections: _ConvertibleToBool | None = None, + defaultThemeVersion: ConvertibleToInt | None = None, + ) -> None: ... + +class CalcProperties(Serialisable): + tagname: ClassVar[str] + calcId: Integer[Literal[False]] + calcMode: NoneSet[_CalcPropertiesCalcMode] + fullCalcOnLoad: Bool[Literal[True]] + refMode: NoneSet[_CalcPropertiesRefMode] + iterate: Bool[Literal[True]] + iterateCount: Integer[Literal[True]] + iterateDelta: Float[Literal[True]] + fullPrecision: Bool[Literal[True]] + calcCompleted: Bool[Literal[True]] + calcOnSave: Bool[Literal[True]] + concurrentCalc: Bool[Literal[True]] + concurrentManualCount: Integer[Literal[True]] + forceFullCalc: Bool[Literal[True]] + def __init__( + self, + calcId: ConvertibleToInt = 124519, + calcMode: _CalcPropertiesCalcMode | Literal["none"] | None = None, + fullCalcOnLoad: _ConvertibleToBool | None = True, + refMode: _CalcPropertiesRefMode | Literal["none"] | None = None, + iterate: _ConvertibleToBool | None = None, + iterateCount: ConvertibleToInt | None = None, + iterateDelta: ConvertibleToFloat | None = None, + fullPrecision: _ConvertibleToBool | None = None, + calcCompleted: _ConvertibleToBool | None = None, + calcOnSave: _ConvertibleToBool | None = None, + concurrentCalc: _ConvertibleToBool | None = None, + concurrentManualCount: ConvertibleToInt | None = None, + forceFullCalc: _ConvertibleToBool | None = None, + ) -> None: ... + +class FileVersion(Serialisable): + tagname: ClassVar[str] + appName: String[Literal[True]] + lastEdited: String[Literal[True]] + lowestEdited: String[Literal[True]] + rupBuild: String[Literal[True]] + codeName: Incomplete + def __init__( + self, + appName: str | None = None, + lastEdited: str | None = None, + lowestEdited: str | None = None, + rupBuild: str | None = None, + codeName=None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/protection.pyi b/stubs/openpyxl/openpyxl/workbook/protection.pyi new file mode 100644 index 000000000000..ddedb7960f7b --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/protection.pyi @@ -0,0 +1,97 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload +from typing_extensions import Self + +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +from ..xml._functions_overloads import _SupportsIterAndAttribAndTextAndGet + +class WorkbookProtection(Serialisable): + tagname: ClassVar[str] + workbook_password: Alias + workbookPasswordCharacterSet: String[Literal[True]] + revision_password: Alias + revisionsPasswordCharacterSet: String[Literal[True]] + lockStructure: Bool[Literal[True]] + lock_structure: Alias + lockWindows: Bool[Literal[True]] + lock_windows: Alias + lockRevision: Bool[Literal[True]] + lock_revision: Alias + revisionsAlgorithmName: String[Literal[True]] + revisionsHashValue: Incomplete + revisionsSaltValue: Incomplete + revisionsSpinCount: Integer[Literal[True]] + workbookAlgorithmName: String[Literal[True]] + workbookHashValue: Incomplete + workbookSaltValue: Incomplete + workbookSpinCount: Integer[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + workbookPassword=None, + workbookPasswordCharacterSet: str | None = None, + revisionsPassword=None, + revisionsPasswordCharacterSet: str | None = None, + lockStructure: _ConvertibleToBool | None = None, + lockWindows: _ConvertibleToBool | None = None, + lockRevision: _ConvertibleToBool | None = None, + revisionsAlgorithmName: str | None = None, + revisionsHashValue=None, + revisionsSaltValue=None, + revisionsSpinCount: ConvertibleToInt | None = None, + workbookAlgorithmName: str | None = None, + workbookHashValue=None, + workbookSaltValue=None, + workbookSpinCount: ConvertibleToInt | None = None, + ) -> None: ... + + @overload + def set_workbook_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_workbook_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_workbook_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def workbookPassword(self) -> str | None: ... + @workbookPassword.setter + def workbookPassword(self, value: str) -> None: ... + + @overload + def set_revisions_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_revisions_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_revisions_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def revisionsPassword(self) -> str | None: ... + @revisionsPassword.setter + def revisionsPassword(self, value: str) -> None: ... + + @classmethod + def from_tree(cls, node: _SupportsIterAndAttribAndTextAndGet) -> Self: ... + +DocumentSecurity = WorkbookProtection + +class FileSharing(Serialisable): + tagname: ClassVar[str] + readOnlyRecommended: Bool[Literal[True]] + userName: String[Literal[True]] + reservationPassword: Incomplete + algorithmName: String[Literal[True]] + hashValue: Incomplete + saltValue: Incomplete + spinCount: Integer[Literal[True]] + def __init__( + self, + readOnlyRecommended: _ConvertibleToBool | None = None, + userName: str | None = None, + reservationPassword=None, + algorithmName: str | None = None, + hashValue=None, + saltValue=None, + spinCount: ConvertibleToInt | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi b/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi new file mode 100644 index 000000000000..6f0baf5e448d --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/smart_tags.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_SmartTagPropertiesShow: TypeAlias = Literal["all", "noIndicator"] + +class SmartTag(Serialisable): + tagname: ClassVar[str] + namespaceUri: String[Literal[True]] + name: String[Literal[True]] + url: String[Literal[True]] + def __init__(self, namespaceUri: str | None = None, name: str | None = None, url: str | None = None) -> None: ... + +class SmartTagList(Serialisable): + tagname: ClassVar[str] + smartTagType: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, smartTagType=()) -> None: ... + +class SmartTagProperties(Serialisable): + tagname: ClassVar[str] + embed: Bool[Literal[True]] + show: NoneSet[_SmartTagPropertiesShow] + def __init__( + self, embed: _ConvertibleToBool | None = None, show: _SmartTagPropertiesShow | Literal["none"] | None = None + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/views.pyi b/stubs/openpyxl/openpyxl/workbook/views.pyi new file mode 100644 index 000000000000..f32087949c1c --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/views.pyi @@ -0,0 +1,134 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl import _VisibilityType +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +_CustomWorkbookViewShowComments: TypeAlias = Literal["commNone", "commIndicator", "commIndAndComment"] +_CustomWorkbookViewShowObjects: TypeAlias = Literal["all", "placeholders"] + +class BookView(Serialisable): + tagname: ClassVar[str] + visibility: NoneSet[_VisibilityType] + minimized: Bool[Literal[True]] + showHorizontalScroll: Bool[Literal[True]] + showVerticalScroll: Bool[Literal[True]] + showSheetTabs: Bool[Literal[True]] + xWindow: Integer[Literal[True]] + yWindow: Integer[Literal[True]] + windowWidth: Integer[Literal[True]] + windowHeight: Integer[Literal[True]] + tabRatio: Integer[Literal[True]] + firstSheet: Integer[Literal[True]] + activeTab: Integer[Literal[True]] + autoFilterDateGrouping: Bool[Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + visibility: _VisibilityType | Literal["none"] | None = "visible", + minimized: _ConvertibleToBool | None = False, + showHorizontalScroll: _ConvertibleToBool | None = True, + showVerticalScroll: _ConvertibleToBool | None = True, + showSheetTabs: _ConvertibleToBool | None = True, + xWindow: ConvertibleToInt | None = None, + yWindow: ConvertibleToInt | None = None, + windowWidth: ConvertibleToInt | None = None, + windowHeight: ConvertibleToInt | None = None, + tabRatio: ConvertibleToInt | None = 600, + firstSheet: ConvertibleToInt | None = 0, + activeTab: ConvertibleToInt | None = 0, + autoFilterDateGrouping: _ConvertibleToBool | None = True, + extLst: Unused = None, + ) -> None: ... + +class CustomWorkbookView(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + guid: Incomplete + autoUpdate: Bool[Literal[True]] + mergeInterval: Integer[Literal[True]] + changesSavedWin: Bool[Literal[True]] + onlySync: Bool[Literal[True]] + personalView: Bool[Literal[True]] + includePrintSettings: Bool[Literal[True]] + includeHiddenRowCol: Bool[Literal[True]] + maximized: Bool[Literal[True]] + minimized: Bool[Literal[True]] + showHorizontalScroll: Bool[Literal[True]] + showVerticalScroll: Bool[Literal[True]] + showSheetTabs: Bool[Literal[True]] + xWindow: Integer[Literal[False]] + yWindow: Integer[Literal[False]] + windowWidth: Integer[Literal[False]] + windowHeight: Integer[Literal[False]] + tabRatio: Integer[Literal[True]] + activeSheetId: Integer[Literal[False]] + showFormulaBar: Bool[Literal[True]] + showStatusbar: Bool[Literal[True]] + showComments: NoneSet[_CustomWorkbookViewShowComments] + showObjects: NoneSet[_CustomWorkbookViewShowObjects] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + name: str, + guid=None, + autoUpdate: _ConvertibleToBool | None = None, + mergeInterval: ConvertibleToInt | None = None, + changesSavedWin: _ConvertibleToBool | None = None, + onlySync: _ConvertibleToBool | None = None, + personalView: _ConvertibleToBool | None = None, + includePrintSettings: _ConvertibleToBool | None = None, + includeHiddenRowCol: _ConvertibleToBool | None = None, + maximized: _ConvertibleToBool | None = None, + minimized: _ConvertibleToBool | None = None, + showHorizontalScroll: _ConvertibleToBool | None = None, + showVerticalScroll: _ConvertibleToBool | None = None, + showSheetTabs: _ConvertibleToBool | None = None, + *, + xWindow: ConvertibleToInt, + yWindow: ConvertibleToInt, + windowWidth: ConvertibleToInt, + windowHeight: ConvertibleToInt, + tabRatio: ConvertibleToInt | None = None, + activeSheetId: ConvertibleToInt, + showFormulaBar: _ConvertibleToBool | None = None, + showStatusbar: _ConvertibleToBool | None = None, + showComments: _CustomWorkbookViewShowComments | Literal["none"] | None = "commIndicator", + showObjects: _CustomWorkbookViewShowObjects | Literal["none"] | None = "all", + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + name: str, + guid: Incomplete | None, + autoUpdate: _ConvertibleToBool | None, + mergeInterval: ConvertibleToInt | None, + changesSavedWin: _ConvertibleToBool | None, + onlySync: _ConvertibleToBool | None, + personalView: _ConvertibleToBool | None, + includePrintSettings: _ConvertibleToBool | None, + includeHiddenRowCol: _ConvertibleToBool | None, + maximized: _ConvertibleToBool | None, + minimized: _ConvertibleToBool | None, + showHorizontalScroll: _ConvertibleToBool | None, + showVerticalScroll: _ConvertibleToBool | None, + showSheetTabs: _ConvertibleToBool | None, + xWindow: ConvertibleToInt, + yWindow: ConvertibleToInt, + windowWidth: ConvertibleToInt, + windowHeight: ConvertibleToInt, + tabRatio: ConvertibleToInt | None, + activeSheetId: ConvertibleToInt, + showFormulaBar: _ConvertibleToBool | None = None, + showStatusbar: _ConvertibleToBool | None = None, + showComments: _CustomWorkbookViewShowComments | Literal["none"] | None = "commIndicator", + showObjects: _CustomWorkbookViewShowObjects | Literal["none"] | None = "all", + extLst: Unused = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/web.pyi b/stubs/openpyxl/openpyxl/workbook/web.pyi new file mode 100644 index 000000000000..fbd5bc0b3cd6 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/web.pyi @@ -0,0 +1,84 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, NoneSet, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +_WebPublishingTargetScreenSize: TypeAlias = Literal[ + "544x376", + "640x480", + "720x512", + "800x600", + "1024x768", + "1152x882", + "1152x900", + "1280x1024", + "1600x1200", + "1800x1440", + "1920x1200", +] + +class WebPublishObject(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + divId: String[Literal[False]] + sourceObject: String[Literal[True]] + destinationFile: String[Literal[False]] + title: String[Literal[True]] + autoRepublish: Bool[Literal[True]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceObject: str | None = None, + *, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + divId: str, + sourceObject: str | None, + destinationFile: str, + title: str | None = None, + autoRepublish: _ConvertibleToBool | None = None, + ) -> None: ... + +class WebPublishObjectList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + webPublishObject: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, webPublishObject=()) -> None: ... + @property + def count(self) -> int: ... + +class WebPublishing(Serialisable): + tagname: ClassVar[str] + css: Bool[Literal[True]] + thicket: Bool[Literal[True]] + longFileNames: Bool[Literal[True]] + vml: Bool[Literal[True]] + allowPng: Bool[Literal[True]] + targetScreenSize: NoneSet[_WebPublishingTargetScreenSize] + dpi: Integer[Literal[True]] + codePage: Integer[Literal[True]] + characterSet: String[Literal[True]] + def __init__( + self, + css: _ConvertibleToBool | None = None, + thicket: _ConvertibleToBool | None = None, + longFileNames: _ConvertibleToBool | None = None, + vml: _ConvertibleToBool | None = None, + allowPng: _ConvertibleToBool | None = None, + targetScreenSize: _WebPublishingTargetScreenSize | Literal["none"] | None = "800x600", + dpi: ConvertibleToInt | None = None, + codePage: ConvertibleToInt | None = None, + characterSet: str | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/workbook/workbook.pyi b/stubs/openpyxl/openpyxl/workbook/workbook.pyi new file mode 100644 index 000000000000..3a2851da1574 --- /dev/null +++ b/stubs/openpyxl/openpyxl/workbook/workbook.pyi @@ -0,0 +1,126 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from datetime import datetime +from typing import Any, Final, TypeAlias, type_check_only +from typing_extensions import deprecated +from zipfile import ZipFile + +from openpyxl import _Decodable, _ZipFileFileWriteProtocol +from openpyxl.chartsheet.chartsheet import Chartsheet +from openpyxl.styles.named_styles import NamedStyle +from openpyxl.utils.indexed_list import IndexedList +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.worksheet._read_only import ReadOnlyWorksheet +from openpyxl.worksheet._write_only import WriteOnlyWorksheet +from openpyxl.worksheet.worksheet import Worksheet + +_WorkbookWorksheet: TypeAlias = Worksheet | WriteOnlyWorksheet | ReadOnlyWorksheet +_WorkbookSheet: TypeAlias = _WorkbookWorksheet | Chartsheet + +# The type of worksheets in a workbook are the same as the aliases above. +# However, because Worksheet adds a lots of attributes that other _WorkbookChild subclasses +# don't have (ReadOnlyWorksheet doesn't even inherit from it), this ends up being too +# disruptive to the typical usage of openpyxl where sheets are just Worksheets. +# Using Any may just lose too much type information and duck-typing +# from Worksheet works great here. Allowing instance type check, even if direct +# type comparison might be wrong. +@type_check_only +class _WorksheetLike( # type: ignore[misc] # Incompatible definitions, favor Worksheet # pyrefly: ignore [inconsistent-inheritance] + Worksheet, WriteOnlyWorksheet, ReadOnlyWorksheet +): ... + +@type_check_only +class _WorksheetOrChartsheetLike( # type: ignore[misc] # Incompatible definitions, favor Worksheet + Chartsheet, _WorksheetLike +): ... + +INTEGER_TYPES: Final[tuple[type[int]]] + +class Workbook: + template: bool + path: str + defined_names: Incomplete + properties: Incomplete + security: Incomplete + shared_strings: IndexedList[str] + loaded_theme: Incomplete + vba_archive: ZipFile | None + is_template: bool + code_name: Incomplete + encoding: str + iso_dates: Incomplete + rels: Incomplete + calculation: Incomplete + views: Incomplete + # Useful as a reference of what "sheets" can be for other types + # ExcelReader can add ReadOnlyWorksheet in read_only mode. + # _sheets: list[_WorksheetOrChartsheetLike] + def __init__(self, write_only: bool = False, iso_dates: bool = False) -> None: ... + + @property + def epoch(self) -> datetime: ... + @epoch.setter + def epoch(self, value: datetime) -> None: ... + + @property + def read_only(self) -> bool: ... + @property + def data_only(self) -> bool: ... + @property + def write_only(self) -> bool: ... + @property + def excel_base_date(self) -> datetime: ... + + @property + def active(self) -> _WorksheetOrChartsheetLike | None: ... + @active.setter + def active(self, value: Worksheet | Chartsheet | int) -> None: ... + + # read_only workbook cannot call this method + # Could be generic based on write_only + def create_sheet( + self, title: str | _Decodable | None = None, index: int | None = None + ) -> Any: ... # AnyOf[WriteOnlyWorksheet, Worksheet] + def move_sheet(self, sheet: Worksheet | str, offset: int = 0) -> None: ... + def remove(self, worksheet: _WorkbookSheet) -> None: ... + @deprecated("Use wb.remove(worksheet) or del wb[sheetname]") + def remove_sheet(self, worksheet: _WorkbookSheet) -> None: ... + def create_chartsheet(self, title: str | _Decodable | None = None, index: int | None = None) -> Chartsheet: ... + @deprecated("Use wb[sheetname]") + def get_sheet_by_name(self, name: str) -> _WorksheetOrChartsheetLike: ... + def __contains__(self, key: str) -> bool: ... + def index(self, worksheet: _WorkbookWorksheet) -> int: ... + @deprecated("Use wb.index(worksheet)") + def get_index(self, worksheet: _WorkbookWorksheet) -> int: ... + def __getitem__(self, key: str) -> _WorksheetOrChartsheetLike: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[_WorksheetLike]: ... + @deprecated("Use wb.sheetnames") + def get_sheet_names(self) -> list[str]: ... + @property + def worksheets(self) -> list[_WorksheetLike]: ... + @property + def chartsheets(self) -> list[Chartsheet]: ... + @property + def sheetnames(self) -> list[str]: ... + @deprecated("Assign scoped named ranges directly to worksheets or global ones to the workbook. Deprecated in 3.1") + def create_named_range( + self, + name: str, + worksheet: _WorkbookChild | ReadOnlyWorksheet | None = None, + value: str | Incomplete | None = None, + scope: Unused = None, + ) -> None: ... + def add_named_style(self, style: NamedStyle) -> None: ... + @property + def named_styles(self) -> list[str]: ... + @property + def mime_type(self) -> str: ... + def save(self, filename: _ZipFileFileWriteProtocol) -> None: ... + @property + def style_names(self) -> list[str]: ... + # A write_only and read_only workbooks can't use this method as it requires both reading and writing. + # On an implementation level, a WorksheetCopy is created from the call to self.create_sheet, + # but WorksheetCopy only works with Worksheet. + def copy_worksheet(self, from_worksheet: Worksheet) -> Worksheet: ... + def close(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/__init__.pyi b/stubs/openpyxl/openpyxl/worksheet/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi b/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi new file mode 100644 index 000000000000..a1f95ee4b577 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_read_only.pyi @@ -0,0 +1,40 @@ +from _typeshed import SupportsGetItem +from collections.abc import Generator + +from openpyxl import _VisibilityType +from openpyxl.cell import _CellGetValue, _CellOrMergedCell +from openpyxl.utils.cell import _RangeBoundariesTuple +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.worksheet import Worksheet + +def read_dimension(source) -> _RangeBoundariesTuple | None: ... + +class ReadOnlyWorksheet: + cell = Worksheet.cell + iter_rows = Worksheet.iter_rows + # Same as Worksheet.values + # https://github.com/python/mypy/issues/6700 + @property + def values(self) -> Generator[tuple[_CellGetValue, ...]]: ... + # Same as Worksheet.rows + # https://github.com/python/mypy/issues/6700 + @property + def rows(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + __getitem__ = Worksheet.__getitem__ + __iter__ = Worksheet.__iter__ + parent: Workbook + title: str + sheet_state: _VisibilityType + def __init__( + self, parent_workbook: Workbook, title: str, worksheet_path, shared_strings: SupportsGetItem[int, str] + ) -> None: ... + def calculate_dimension(self, force: bool = False): ... + def reset_dimensions(self) -> None: ... + @property + def min_row(self) -> int: ... + @property + def max_row(self) -> int | None: ... + @property + def min_column(self) -> int: ... + @property + def max_column(self) -> int | None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_reader.pyi b/stubs/openpyxl/openpyxl/worksheet/_reader.pyi new file mode 100644 index 000000000000..789dd30f6c6f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_reader.pyi @@ -0,0 +1,117 @@ +from _typeshed import Incomplete, SupportsGetItem, Unused +from collections.abc import Container, Generator +from datetime import datetime +from typing import Final +from xml.etree.ElementTree import _FileRead + +from openpyxl.cell import _AnyCellValue, _CellOrMergedCell +from openpyxl.cell.rich_text import CellRichText +from openpyxl.descriptors.serialisable import _ChildSerialisableTreeElement, _SerialisableTreeElement +from openpyxl.formula.translate import Translator +from openpyxl.utils.cell import _RangeBoundariesTuple + +from ..xml._functions_overloads import _HasAttrib, _SupportsIterAndAttrib +from .hyperlink import HyperlinkList +from .pagebreak import ColBreak, RowBreak +from .protection import SheetProtection +from .table import TablePartList +from .worksheet import Worksheet + +CELL_TAG: Final[str] +VALUE_TAG: Final[str] +FORMULA_TAG: Final[str] +MERGE_TAG: Final[str] +INLINE_STRING: Final[str] +COL_TAG: Final[str] +ROW_TAG: Final[str] +CF_TAG: Final[str] +LEGACY_TAG: Final[str] +PROT_TAG: Final[str] +EXT_TAG: Final[str] +HYPERLINK_TAG: Final[str] +TABLE_TAG: Final[str] +PRINT_TAG: Final[str] +MARGINS_TAG: Final[str] +PAGE_TAG: Final[str] +HEADER_TAG: Final[str] +FILTER_TAG: Final[str] +VALIDATION_TAG: Final[str] +PROPERTIES_TAG: Final[str] +VIEWS_TAG: Final[str] +FORMAT_TAG: Final[str] +ROW_BREAK_TAG: Final[str] +COL_BREAK_TAG: Final[str] +SCENARIOS_TAG: Final[str] +DATA_TAG: Final[str] +DIMENSION_TAG: Final[str] +CUSTOM_VIEWS_TAG: Final[str] + +def parse_richtext_string(element: _ChildSerialisableTreeElement) -> CellRichText | str: ... + +class WorkSheetParser: + min_row: Incomplete | None + min_col: Incomplete | None + epoch: datetime + source: _FileRead + shared_strings: SupportsGetItem[int, str] + data_only: bool + shared_formulae: dict[Incomplete, Translator] + row_counter: int + col_counter: int + tables: TablePartList + date_formats: Container[int] + timedelta_formats: Container[int] + row_dimensions: dict[Incomplete, Incomplete] + column_dimensions: dict[Incomplete, Incomplete] + number_formats: list[Incomplete] + keep_vba: bool + hyperlinks: HyperlinkList + formatting: list[Incomplete] + legacy_drawing: Incomplete | None + merged_cells: Incomplete | None + row_breaks: RowBreak + col_breaks: ColBreak + rich_text: bool + protection: SheetProtection # initialized after call to parse_sheet_protection() + + def __init__( + self, + src: _FileRead, + shared_strings: SupportsGetItem[int, str], + data_only: bool = False, + epoch: datetime = ..., + date_formats: Container[int] = ..., + timedelta_formats: Container[int] = ..., + rich_text: bool = False, + ) -> None: ... + def parse(self) -> Generator[Incomplete]: ... + def parse_dimensions(self) -> _RangeBoundariesTuple | None: ... + def parse_cell(self, element) -> dict[str, _AnyCellValue]: ... + def parse_formula(self, element): ... + def parse_column_dimensions(self, col: _HasAttrib) -> None: ... + def parse_row(self, row: _SupportsIterAndAttrib) -> tuple[int, list[dict[str, _AnyCellValue]]]: ... + def parse_formatting(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_sheet_protection(self, element: _SerialisableTreeElement) -> None: ... + def parse_extensions(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_legacy(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_row_breaks(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_col_breaks(self, element: _ChildSerialisableTreeElement) -> None: ... + def parse_custom_views(self, element: Unused) -> None: ... + +class WorksheetReader: + ws: Worksheet + parser: WorkSheetParser + tables: list[Incomplete] + def __init__( + self, ws: Worksheet, xml_source: _FileRead, shared_strings: SupportsGetItem[int, str], data_only: bool, rich_text: bool + ) -> None: ... + def bind_cells(self) -> None: ... + def bind_formatting(self) -> None: ... + def bind_tables(self) -> None: ... + def bind_merged_cells(self) -> None: ... + def bind_hyperlinks(self) -> None: ... + def normalize_merged_cell_link(self, coord: str) -> _CellOrMergedCell | None: ... + def bind_col_dimensions(self) -> None: ... + def bind_row_dimensions(self) -> None: ... + def bind_properties(self) -> None: ... + def bind_all(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi b/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi new file mode 100644 index 000000000000..c73e6d964898 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_write_only.pyi @@ -0,0 +1,50 @@ +from collections.abc import Iterable + +from openpyxl import _Decodable +from openpyxl.cell.cell import Cell +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.table import TableList +from openpyxl.worksheet.views import SheetView +from openpyxl.worksheet.worksheet import Worksheet + +class WriteOnlyWorksheet(_WorkbookChild): + mime_type = Worksheet.mime_type + add_chart = Worksheet.add_chart + add_image = Worksheet.add_image + add_table = Worksheet.add_table + + # Same properties as Worksheet + # https://github.com/python/mypy/issues/6700 + @property + def tables(self) -> TableList: ... + @property + def print_titles(self) -> str: ... + + @property + def print_title_cols(self) -> str | None: ... + @print_title_cols.setter + def print_title_cols(self, cols: str | None) -> None: ... + + @property + def print_title_rows(self) -> str | None: ... + @print_title_rows.setter + def print_title_rows(self, rows: str | None) -> None: ... + + @property + def freeze_panes(self) -> str | None: ... + @freeze_panes.setter + def freeze_panes(self, topLeftCell: str | Cell | None = ...) -> None: ... + + @property + def print_area(self) -> str: ... + @print_area.setter + def print_area(self, value: str | Iterable[str] | None) -> None: ... + + @property + def sheet_view(self) -> SheetView: ... + def __init__(self, parent: Workbook | None, title: str | _Decodable | None) -> None: ... + @property + def closed(self) -> bool: ... + def close(self) -> None: ... + def append(self, row) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/_writer.pyi b/stubs/openpyxl/openpyxl/worksheet/_writer.pyi new file mode 100644 index 000000000000..40fb98eacdac --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/_writer.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete, ReadableBuffer, StrPath, Unused +from collections.abc import Generator, Iterable +from typing import Protocol, TypeAlias, type_check_only + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.worksheet._write_only import WriteOnlyWorksheet +from openpyxl.worksheet.worksheet import Worksheet + +# WorksheetWriter.read has an explicit BytesIO branch. Let's make sure this protocol is viable for BytesIO too. +@type_check_only +class _SupportsCloseAndWrite(Protocol): + def write(self, buffer: ReadableBuffer, /) -> Unused: ... + def close(self) -> Unused: ... + +# et_xmlfile.xmlfile accepts a str | _SupportsCloseAndWrite +# lxml.etree.xmlfile should accept a StrPath | _SupportsClose https://lxml.de/api/lxml.etree.xmlfile-class.html +_OutType: TypeAlias = _SupportsCloseAndWrite | StrPath + +ALL_TEMP_FILES: list[str] + +def create_temporary_file(suffix: str = "") -> str: ... + +class WorksheetWriter: + ws: Worksheet | WriteOnlyWorksheet + out: _OutType + xf: Generator[Incomplete | None, Incomplete] + def __init__(self, ws: Worksheet | WriteOnlyWorksheet, out: _OutType | None = None) -> None: ... + def write_properties(self) -> None: ... + def write_dimensions(self) -> None: ... + def write_format(self) -> None: ... + def write_views(self) -> None: ... + def write_cols(self) -> None: ... + def write_top(self) -> None: ... + def rows(self) -> list[tuple[int, list[_CellOrMergedCell]]]: ... + def write_rows(self) -> None: ... + def write_row(self, xf, row: Iterable[_CellOrMergedCell], row_idx) -> None: ... + def write_protection(self) -> None: ... + def write_scenarios(self) -> None: ... + def write_filter(self) -> None: ... + def write_sort(self) -> None: ... + def write_merged_cells(self) -> None: ... + def write_formatting(self) -> None: ... + def write_validations(self) -> None: ... + def write_hyperlinks(self) -> None: ... + def write_print(self) -> None: ... + def write_margins(self) -> None: ... + def write_page(self) -> None: ... + def write_header(self) -> None: ... + def write_breaks(self) -> None: ... + def write_drawings(self) -> None: ... + def write_legacy(self) -> None: ... + def write_tables(self) -> None: ... + def get_stream(self) -> Generator[Incomplete | None, bool | None]: ... + def write_tail(self) -> None: ... + def write(self) -> None: ... + def close(self) -> None: ... + def read(self) -> bytes: ... + def cleanup(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi b/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi new file mode 100644 index 000000000000..9047a877351e --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/cell_range.pyi @@ -0,0 +1,105 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Generator, Iterator +from itertools import product +from typing import Any, Literal, overload + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import MinMax +from openpyxl.descriptors.serialisable import Serialisable + +class CellRange(Serialisable): + min_col: MinMax[int, Literal[False]] + min_row: MinMax[int, Literal[False]] + max_col: MinMax[int, Literal[False]] + max_row: MinMax[int, Literal[False]] + title: str | None + + # With `range_string`, min/max parameters go unused. + # Enforcing `None` to avoid confusion upon which params get used + # if the user still tries to pass a `ConvertibleToInt`. + @overload + def __init__( + self, + range_string: str, + min_col: None = None, + min_row: None = None, + max_col: None = None, + max_row: None = None, + title: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + range_string: None = None, + *, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt, + max_row: ConvertibleToInt, + title: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + range_string: None, + min_col: ConvertibleToInt, + min_row: ConvertibleToInt, + max_col: ConvertibleToInt, + max_row: ConvertibleToInt, + title: str | None = None, + ) -> None: ... + + @property + def bounds(self) -> tuple[int, int, int, int]: ... + @property + def coord(self) -> str: ... + @property + def rows(self) -> Generator[list[tuple[int, int]]]: ... + @property + def cols(self) -> Generator[list[tuple[int, int]]]: ... + @property + def cells(self) -> product[tuple[int, int]]: ... + def __copy__(self): ... + def shift(self, col_shift: int = 0, row_shift: int = 0) -> None: ... + def __ne__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def issubset(self, other: CellRange) -> bool: ... + __le__ = issubset + def __lt__(self, other: CellRange) -> bool: ... + def issuperset(self, other: CellRange) -> bool: ... + __ge__ = issuperset + def __contains__(self, coord: str) -> bool: ... + def __gt__(self, other: CellRange) -> bool: ... + def isdisjoint(self, other: CellRange) -> bool: ... + def intersection(self, other): ... + __and__ = intersection + def union(self, other): ... + __or__ = union + # Iterates over class attributes. Value could be anything. + def __iter__(self) -> Iterator[tuple[str, Any]]: ... + def expand(self, right: int = 0, down: int = 0, left: int = 0, up: int = 0) -> None: ... + def shrink(self, right: int = 0, bottom: int = 0, left: int = 0, top: int = 0) -> None: ... + @property + def size(self) -> dict[str, int]: ... + @property + def top(self) -> list[tuple[int, int]]: ... + @property + def bottom(self) -> list[tuple[int, int]]: ... + @property + def left(self) -> list[tuple[int, int]]: ... + @property + def right(self) -> list[tuple[int, int]]: ... + +class MultiCellRange(Strict): + ranges: Incomplete + def __init__(self, ranges=...) -> None: ... + def __contains__(self, coord: str | CellRange) -> bool: ... + def sorted(self) -> list[CellRange]: ... + def add(self, coord) -> None: ... + def __iadd__(self, coord): ... + def __eq__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] + def __ne__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] + def __bool__(self) -> bool: ... + def remove(self, coord) -> None: ... + def __iter__(self) -> Iterator[CellRange]: ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi b/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi new file mode 100644 index 000000000000..5cece50ffa7c --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/cell_watch.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable + +class CellWatch(Serialisable): + tagname: ClassVar[str] + r: String[Literal[True]] + def __init__(self, r: str) -> None: ... + +class CellWatches(Serialisable): + tagname: ClassVar[str] + cellWatch: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellWatch=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/controls.pyi b/stubs/openpyxl/openpyxl/worksheet/controls.pyi new file mode 100644 index 000000000000..2e42831a592c --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/controls.pyi @@ -0,0 +1,65 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Integer, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.ole import ObjectAnchor + +class ControlProperty(Serialisable): + tagname: ClassVar[str] + anchor: Typed[ObjectAnchor, Literal[False]] + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + recalcAlways: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + autoPict: Bool[Literal[True]] + macro: String[Literal[True]] + altText: String[Literal[True]] + linkedCell: String[Literal[True]] + listFillRange: String[Literal[True]] + cf: String[Literal[True]] + id: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None = True, + defaultSize: _ConvertibleToBool | None = True, + _print: _ConvertibleToBool | None = True, + disabled: _ConvertibleToBool | None = False, + recalcAlways: _ConvertibleToBool | None = False, + uiObject: _ConvertibleToBool | None = False, + autoFill: _ConvertibleToBool | None = True, + autoLine: _ConvertibleToBool | None = True, + autoPict: _ConvertibleToBool | None = True, + macro: str | None = None, + altText: str | None = None, + linkedCell: str | None = None, + listFillRange: str | None = None, + cf: str | None = "pict", + id=None, + ) -> None: ... + +class Control(Serialisable): + tagname: ClassVar[str] + controlPr: Typed[ControlProperty, Literal[True]] + shapeId: Integer[Literal[False]] + name: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, controlPr: ControlProperty | None = None, *, shapeId: ConvertibleToInt, name: str | None = None + ) -> None: ... + @overload + def __init__(self, controlPr: ControlProperty | None, shapeId: ConvertibleToInt, name: str | None = None) -> None: ... + +class Controls(Serialisable): + tagname: ClassVar[str] + control: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, control=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/copier.pyi b/stubs/openpyxl/openpyxl/worksheet/copier.pyi new file mode 100644 index 000000000000..e32d38c5747b --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/copier.pyi @@ -0,0 +1,7 @@ +from openpyxl.worksheet.worksheet import Worksheet + +class WorksheetCopy: + source: Worksheet + target: Worksheet + def __init__(self, source_worksheet: Worksheet, target_worksheet: Worksheet) -> None: ... + def copy_worksheet(self) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/custom.pyi b/stubs/openpyxl/openpyxl/worksheet/custom.pyi new file mode 100644 index 000000000000..53d330806ca1 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/custom.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.serialisable import Serialisable + +class CustomProperty(Serialisable): + tagname: ClassVar[str] + name: String[Literal[False]] + def __init__(self, name: str) -> None: ... + +class CustomProperties(Serialisable): + tagname: ClassVar[str] + customPr: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, customPr=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi b/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi new file mode 100644 index 000000000000..500a40aee250 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/datavalidation.pyi @@ -0,0 +1,109 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, Protocol, TypeAlias, type_check_only + +from openpyxl.descriptors.base import ( + Alias, + Bool, + Convertible, + Integer, + NoneSet, + String, + _ConvertibleToBool, + _ConvertibleToMultiCellRange, +) +from openpyxl.descriptors.nested import NestedText +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange +from openpyxl.xml.functions import Element + +_DataValidationType: TypeAlias = Literal["whole", "decimal", "list", "date", "time", "textLength", "custom"] +_DataValidationErrorStyle: TypeAlias = Literal["stop", "warning", "information"] +_DataValidationImeMode: TypeAlias = Literal[ + "noControl", + "off", + "on", + "disabled", + "hiragana", + "fullKatakana", + "halfKatakana", + "fullAlpha", + "halfAlpha", + "fullHangul", + "halfHangul", +] +_DataValidationOperator: TypeAlias = Literal[ + "between", "notBetween", "equal", "notEqual", "lessThan", "lessThanOrEqual", "greaterThan", "greaterThanOrEqual" +] + +@type_check_only +class _HasCoordinate(Protocol): + coordinate: str | CellRange + +def collapse_cell_addresses(cells, input_ranges=()): ... +def expand_cell_ranges(range_string): ... + +class DataValidation(Serialisable): + tagname: ClassVar[str] + sqref: Convertible[MultiCellRange, Literal[False]] + cells: Alias + ranges: Alias + showDropDown: Bool[Literal[True]] + hide_drop_down: Alias + showInputMessage: Bool[Literal[True]] + showErrorMessage: Bool[Literal[True]] + allowBlank: Bool[Literal[True]] + allow_blank: Alias + errorTitle: String[Literal[True]] + error: String[Literal[True]] + promptTitle: String[Literal[True]] + prompt: String[Literal[True]] + formula1: NestedText[str, Literal[True]] + formula2: NestedText[str, Literal[True]] + type: NoneSet[_DataValidationType] + errorStyle: NoneSet[_DataValidationErrorStyle] + imeMode: NoneSet[_DataValidationImeMode] + operator: NoneSet[_DataValidationOperator] + validation_type: Alias + def __init__( + self, + type: _DataValidationType | Literal["none"] | None = None, + formula1: object = None, + formula2: object = None, + showErrorMessage: _ConvertibleToBool | None = False, + showInputMessage: _ConvertibleToBool | None = False, + showDropDown: _ConvertibleToBool | None = False, + allowBlank: _ConvertibleToBool = False, + sqref: _ConvertibleToMultiCellRange = (), + promptTitle: str | None = None, + errorStyle: _DataValidationErrorStyle | Literal["none"] | None = None, + error: str | None = None, + prompt: str | None = None, + errorTitle: str | None = None, + imeMode: _DataValidationImeMode | Literal["none"] | None = None, + operator: _DataValidationOperator | Literal["none"] | None = None, + allow_blank: _ConvertibleToBool | None = None, + ) -> None: ... + def add(self, cell) -> None: ... + def __contains__(self, cell: _HasCoordinate | str | CellRange) -> bool: ... + +class DataValidationList(Serialisable): + tagname: ClassVar[str] + disablePrompts: Bool[Literal[True]] + xWindow: Integer[Literal[True]] + yWindow: Integer[Literal[True]] + dataValidation: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + disablePrompts: _ConvertibleToBool | None = None, + xWindow: ConvertibleToInt | None = None, + yWindow: ConvertibleToInt | None = None, + count=None, + dataValidation=(), + ) -> None: ... + @property + def count(self) -> int: ... + def __len__(self) -> int: ... + def append(self, dv) -> None: ... + def to_tree(self, tagname: str | None = None) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi b/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi new file mode 100644 index 000000000000..167dfb1c7b1f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/dimensions.pyi @@ -0,0 +1,149 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused +from collections.abc import Callable, Iterator +from typing import ClassVar, Literal, TypeVar +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Float, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.styleable import StyleableObject +from openpyxl.utils.bound_dictionary import BoundDictionary +from openpyxl.utils.cell import _RangeBoundariesTuple +from openpyxl.worksheet.worksheet import Worksheet +from openpyxl.xml.functions import Element + +_DimKeyT = TypeVar("_DimKeyT", bound=str | int) +_DimT = TypeVar("_DimT", bound=Dimension) + +class Dimension(Strict, StyleableObject): + __fields__: ClassVar[tuple[str, ...]] + + index: Integer[Literal[False]] + hidden: Bool[Literal[False]] + outlineLevel: Integer[Literal[True]] + outline_level: Alias + collapsed: Bool[Literal[False]] + style: Alias # type: ignore[assignment] + + # Dimensions are only meant to be used on Worksheet objects + parent: Worksheet + + def __init__( + self, + index: ConvertibleToInt, + hidden: _ConvertibleToBool, + outlineLevel: ConvertibleToInt | None, + collapsed: _ConvertibleToBool, + worksheet: Worksheet, + visible: Unused = True, + style=None, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + def __copy__(self) -> Self: ... + +class RowDimension(Dimension): + r: Alias + s: Alias + ht: Float[Literal[True]] + height: Alias + thickBot: Bool[Literal[False]] + thickTop: Bool[Literal[False]] + def __init__( + self, + worksheet: Worksheet, + index: int = 0, + ht: ConvertibleToFloat | None = None, + customHeight: Unused = None, + s=None, + customFormat: Unused = None, + hidden: _ConvertibleToBool = None, + outlineLevel: ConvertibleToInt | None = 0, + outline_level: ConvertibleToInt | None = None, + collapsed: _ConvertibleToBool = None, + visible=None, + height=None, + r=None, + spans: Unused = None, + thickBot: _ConvertibleToBool = None, + thickTop: _ConvertibleToBool = None, + **kw: Unused, + ) -> None: ... + @property + def customFormat(self) -> bool: ... + @property + def customHeight(self) -> bool: ... + +class ColumnDimension(Dimension): + width: Float[Literal[False]] + bestFit: Bool[Literal[False]] + auto_size: Alias + index: String[Literal[False]] # type: ignore[assignment] + min: Integer[Literal[True]] + max: Integer[Literal[True]] + collapsed: Bool[Literal[False]] + + def __init__( + self, + worksheet: Worksheet, + index: str = "A", + width: ConvertibleToFloat = 13, + bestFit: _ConvertibleToBool = False, + hidden: _ConvertibleToBool = False, + outlineLevel: ConvertibleToInt | None = 0, + outline_level: ConvertibleToInt | None = None, + collapsed: _ConvertibleToBool = False, + style=None, + min: ConvertibleToInt | None = None, + max: ConvertibleToInt | None = None, + customWidth: Unused = False, + visible: bool | None = None, + auto_size: _ConvertibleToBool | None = None, + ) -> None: ... + @property + def customWidth(self) -> bool: ... + def reindex(self) -> None: ... + @property + def range(self) -> str: ... + def to_tree(self) -> Element | None: ... + +class DimensionHolder(BoundDictionary[_DimKeyT, _DimT]): + worksheet: Worksheet + max_outline: int | None + default_factory: Callable[[], _DimT] | None + + def __init__( + self, worksheet: Worksheet, reference: str = "index", default_factory: Callable[[], _DimT] | None = None + ) -> None: ... + def group(self, start: _DimKeyT, end: _DimKeyT | None = None, outline_level: int = 1, hidden: bool = False) -> None: ... + def to_tree(self) -> Element | None: ... + +class SheetFormatProperties(Serialisable): + tagname: ClassVar[str] + baseColWidth: Integer[Literal[True]] + defaultColWidth: Float[Literal[True]] + defaultRowHeight: Float[Literal[False]] + customHeight: Bool[Literal[True]] + zeroHeight: Bool[Literal[True]] + thickTop: Bool[Literal[True]] + thickBottom: Bool[Literal[True]] + outlineLevelRow: Integer[Literal[True]] + outlineLevelCol: Integer[Literal[True]] + def __init__( + self, + baseColWidth: ConvertibleToInt | None = 8, + defaultColWidth: ConvertibleToFloat | None = None, + defaultRowHeight: ConvertibleToFloat = 15, + customHeight: _ConvertibleToBool | None = None, + zeroHeight: _ConvertibleToBool | None = None, + thickTop: _ConvertibleToBool | None = None, + thickBottom: _ConvertibleToBool | None = None, + outlineLevelRow: ConvertibleToInt | None = None, + outlineLevelCol: ConvertibleToInt | None = None, + ) -> None: ... + +class SheetDimension(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + def __init__(self, ref: str) -> None: ... + @property + def boundaries(self) -> _RangeBoundariesTuple: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/drawing.pyi b/stubs/openpyxl/openpyxl/worksheet/drawing.pyi new file mode 100644 index 000000000000..589c271fedea --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/drawing.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class Drawing(Serialisable): + tagname: ClassVar[str] + id: Incomplete + def __init__(self, id=None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/errors.pyi b/stubs/openpyxl/openpyxl/worksheet/errors.pyi new file mode 100644 index 000000000000..67883b448949 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/errors.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Extension(Serialisable): + tagname: ClassVar[str] + uri: String[Literal[True]] + def __init__(self, uri: str | None = None) -> None: ... + +class ExtensionList(Serialisable): + tagname: ClassVar[str] + ext: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ext=()) -> None: ... + +class IgnoredError(Serialisable): + tagname: ClassVar[str] + sqref: Incomplete + evalError: Bool[Literal[True]] + twoDigitTextYear: Bool[Literal[True]] + numberStoredAsText: Bool[Literal[True]] + formula: Bool[Literal[True]] + formulaRange: Bool[Literal[True]] + unlockedFormula: Bool[Literal[True]] + emptyCellReference: Bool[Literal[True]] + listDataValidation: Bool[Literal[True]] + calculatedColumn: Bool[Literal[True]] + def __init__( + self, + sqref=None, + evalError: _ConvertibleToBool | None = False, + twoDigitTextYear: _ConvertibleToBool | None = False, + numberStoredAsText: _ConvertibleToBool | None = False, + formula: _ConvertibleToBool | None = False, + formulaRange: _ConvertibleToBool | None = False, + unlockedFormula: _ConvertibleToBool | None = False, + emptyCellReference: _ConvertibleToBool | None = False, + listDataValidation: _ConvertibleToBool | None = False, + calculatedColumn: _ConvertibleToBool | None = False, + ) -> None: ... + +class IgnoredErrors(Serialisable): + tagname: ClassVar[str] + ignoredError: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ignoredError=(), extLst: ExtensionList | None = None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/filters.pyi b/stubs/openpyxl/openpyxl/worksheet/filters.pyi new file mode 100644 index 000000000000..932b53b604d7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/filters.pyi @@ -0,0 +1,317 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from datetime import datetime +from typing import ClassVar, Final, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import ( + Alias, + Bool, + DateTime, + Float, + Integer, + MinMax, + NoneSet, + Set, + String, + Typed, + _ConvertibleToBool, +) +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable + +_SortConditionSortBy: TypeAlias = Literal["value", "cellColor", "fontColor", "icon"] +_IconSet: TypeAlias = Literal[ + "3Arrows", + "3ArrowsGray", + "3Flags", + "3TrafficLights1", + "3TrafficLights2", + "3Signs", + "3Symbols", + "3Symbols2", + "4Arrows", + "4ArrowsGray", + "4RedToBlack", + "4Rating", + "4TrafficLights", + "5Arrows", + "5ArrowsGray", + "5Rating", + "5Quarters", +] +_SortStateSortMethod: TypeAlias = Literal["stroke", "pinYin"] +_CustomFilterOperator: TypeAlias = Literal[ + "equal", "lessThan", "lessThanOrEqual", "notEqual", "greaterThanOrEqual", "greaterThan" +] +_StringFilterOperator: TypeAlias = Literal["contains", "startswith", "endswith", "wildcard"] +_FiltersCalendarType: TypeAlias = Literal[ + "gregorian", + "gregorianUs", + "gregorianMeFrench", + "gregorianArabic", + "hijri", + "hebrew", + "taiwan", + "japan", + "thai", + "korea", + "saka", + "gregorianXlitEnglish", + "gregorianXlitFrench", +] +_DynamicFilterType: TypeAlias = Literal[ + "null", + "aboveAverage", + "belowAverage", + "tomorrow", + "today", + "yesterday", + "nextWeek", + "thisWeek", + "lastWeek", + "nextMonth", + "thisMonth", + "lastMonth", + "nextQuarter", + "thisQuarter", + "lastQuarter", + "nextYear", + "thisYear", + "lastYear", + "yearToDate", + "Q1", + "Q2", + "Q3", + "Q4", + "M1", + "M2", + "M3", + "M4", + "M5", + "M6", + "M7", + "M8", + "M9", + "M10", + "M11", + "M12", +] +_DateGroupItemDateTimeGrouping: TypeAlias = Literal["year", "month", "day", "hour", "minute", "second"] + +class SortCondition(Serialisable): + tagname: ClassVar[str] + descending: Bool[Literal[True]] + sortBy: NoneSet[_SortConditionSortBy] + ref: Incomplete + customList: String[Literal[True]] + dxfId: Integer[Literal[True]] + iconSet: NoneSet[_IconSet] + iconId: Integer[Literal[True]] + def __init__( + self, + ref=None, + descending: _ConvertibleToBool | None = None, + sortBy: _SortConditionSortBy | Literal["none"] | None = None, + customList: str | None = None, + dxfId: ConvertibleToInt | None = None, + iconSet: _IconSet | Literal["none"] | None = None, + iconId: ConvertibleToInt | None = None, + ) -> None: ... + +class SortState(Serialisable): + tagname: ClassVar[str] + columnSort: Bool[Literal[True]] + caseSensitive: Bool[Literal[True]] + sortMethod: NoneSet[_SortStateSortMethod] + ref: Incomplete + sortCondition: Incomplete + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + columnSort: _ConvertibleToBool | None = None, + caseSensitive: _ConvertibleToBool | None = None, + sortMethod: _SortStateSortMethod | Literal["none"] | None = None, + ref=None, + sortCondition=(), + extLst: Unused = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class IconFilter(Serialisable): + tagname: ClassVar[str] + iconSet: Set[_IconSet] + iconId: Integer[Literal[True]] + def __init__(self, iconSet: _IconSet, iconId: ConvertibleToInt | None = None) -> None: ... + +class ColorFilter(Serialisable): + tagname: ClassVar[str] + dxfId: Integer[Literal[True]] + cellColor: Bool[Literal[True]] + def __init__(self, dxfId: ConvertibleToInt | None = None, cellColor: _ConvertibleToBool | None = None) -> None: ... + +class DynamicFilter(Serialisable): + tagname: ClassVar[str] + type: Set[_DynamicFilterType] + val: Float[Literal[True]] + valIso: DateTime[Literal[True]] + maxVal: Float[Literal[True]] + maxValIso: DateTime[Literal[True]] + def __init__( + self, + type: _DynamicFilterType, + val: ConvertibleToFloat | None = None, + valIso: datetime | str | None = None, + maxVal: ConvertibleToFloat | None = None, + maxValIso: datetime | str | None = None, + ) -> None: ... + +class CustomFilter(Serialisable): + tagname: ClassVar[str] + val: String[Literal[False]] + operator: Set[_CustomFilterOperator] + def __init__(self, operator: _CustomFilterOperator = "equal", val: str | None = None) -> None: ... + def convert(self) -> BlankFilter | NumberFilter | StringFilter: ... + +class BlankFilter(CustomFilter): + def __init__(self, **kw: Unused) -> None: ... + @property + def operator(self) -> Literal["notEqual"]: ... # type: ignore[override] + @property + def val(self) -> Literal[" "]: ... # type: ignore[override] + +class NumberFilter(CustomFilter): + val: Float[Literal[False]] # type: ignore[assignment] + def __init__(self, operator: _CustomFilterOperator = "equal", val: ConvertibleToFloat | None = None) -> None: ... + +string_format_mapping: Final[dict[_StringFilterOperator, str]] + +class StringFilter(CustomFilter): + operator: Set[_StringFilterOperator] # type: ignore[assignment] + val: String[Literal[False]] + exclude: Bool[Literal[False]] + def __init__( + self, operator: _StringFilterOperator = "contains", val: str | None = None, exclude: _ConvertibleToBool = False + ) -> None: ... + +class CustomFilters(Serialisable): + tagname: ClassVar[str] + _and: Bool[Literal[True]] # Not private. Avoids name clash + customFilter: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, _and: _ConvertibleToBool | None = None, customFilter=()) -> None: ... + +class Top10(Serialisable): + tagname: ClassVar[str] + top: Bool[Literal[True]] + percent: Bool[Literal[True]] + val: Float[Literal[False]] + filterVal: Float[Literal[True]] + + @overload + def __init__( + self, + top: _ConvertibleToBool | None = None, + percent: _ConvertibleToBool | None = None, + *, + val: ConvertibleToFloat, + filterVal: ConvertibleToFloat | None = None, + ) -> None: ... + @overload + def __init__( + self, + top: _ConvertibleToBool | None, + percent: _ConvertibleToBool | None, + val: ConvertibleToFloat, + filterVal: ConvertibleToFloat | None = None, + ) -> None: ... + +class DateGroupItem(Serialisable): + tagname: ClassVar[str] + year: Integer[Literal[False]] + month: MinMax[float, Literal[True]] + day: MinMax[float, Literal[True]] + hour: MinMax[float, Literal[True]] + minute: MinMax[float, Literal[True]] + second: Integer[Literal[True]] + dateTimeGrouping: Set[_DateGroupItemDateTimeGrouping] + + @overload + def __init__( + self, + year: ConvertibleToInt, + month: ConvertibleToFloat | None = None, + day: ConvertibleToFloat | None = None, + hour: ConvertibleToFloat | None = None, + minute: ConvertibleToFloat | None = None, + second: ConvertibleToInt | None = None, + *, + dateTimeGrouping: _DateGroupItemDateTimeGrouping, + ) -> None: ... + @overload + def __init__( + self, + year: ConvertibleToInt, + month: ConvertibleToFloat | None, + day: ConvertibleToFloat | None, + hour: ConvertibleToFloat | None, + minute: ConvertibleToFloat | None, + second: ConvertibleToInt | None, + dateTimeGrouping: _DateGroupItemDateTimeGrouping, + ) -> None: ... + +class Filters(Serialisable): + tagname: ClassVar[str] + blank: Bool[Literal[True]] + calendarType: NoneSet[_FiltersCalendarType] + filter: Incomplete + dateGroupItem: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + blank: _ConvertibleToBool | None = None, + calendarType: _FiltersCalendarType | Literal["none"] | None = None, + filter=(), + dateGroupItem=(), + ) -> None: ... + +class FilterColumn(Serialisable): + tagname: ClassVar[str] + colId: Integer[Literal[False]] + col_id: Alias + hiddenButton: Bool[Literal[True]] + showButton: Bool[Literal[True]] + filters: Typed[Filters, Literal[True]] + top10: Typed[Top10, Literal[True]] + customFilters: Typed[CustomFilters, Literal[True]] + dynamicFilter: Typed[DynamicFilter, Literal[True]] + colorFilter: Typed[ColorFilter, Literal[True]] + iconFilter: Typed[IconFilter, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + colId: ConvertibleToInt, + hiddenButton: _ConvertibleToBool | None = False, + showButton: _ConvertibleToBool | None = True, + filters: Filters | None = None, + top10: Top10 | None = None, + customFilters: CustomFilters | None = None, + dynamicFilter: DynamicFilter | None = None, + colorFilter: ColorFilter | None = None, + iconFilter: IconFilter | None = None, + extLst: Unused = None, + blank=None, + vals=None, + ) -> None: ... + +class AutoFilter(Serialisable): + tagname: ClassVar[str] + ref: Incomplete + filterColumn: Incomplete + sortState: Typed[SortState, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, ref=None, filterColumn=(), sortState: SortState | None = None, extLst: Unused = None) -> None: ... + def __bool__(self) -> bool: ... + def add_filter_column(self, col_id, vals, blank: bool = False) -> None: ... + def add_sort_condition(self, ref, descending: bool = False) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/formula.pyi b/stubs/openpyxl/openpyxl/worksheet/formula.pyi new file mode 100644 index 000000000000..73e3601d9f6d --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/formula.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar + +class DataTableFormula: + t: ClassVar[str] + + ref: Incomplete + ca: bool + dt2D: bool + dtr: bool + r1: Incomplete | None + r2: Incomplete | None + del1: bool + del2: bool + + def __init__( + self, + ref, + ca: bool = False, + dt2D: bool = False, + dtr: bool = False, + r1=None, + r2=None, + del1: bool = False, + del2: bool = False, + **kw, + ) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... + +class ArrayFormula: + t: ClassVar[str] + ref: Incomplete + text: Incomplete | None + + def __init__(self, ref, text=None) -> None: ... + def __iter__(self) -> Iterator[tuple[str, str]]: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi b/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi new file mode 100644 index 000000000000..60936a73b7cd --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/header_footer.pyi @@ -0,0 +1,73 @@ +from _typeshed import ConvertibleToInt +from re import Pattern +from typing import ClassVar, Final, Literal +from typing_extensions import Self + +from openpyxl.descriptors import Strict +from openpyxl.descriptors.base import Alias, Bool, Integer, MatchPattern, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +from ..xml._functions_overloads import _HasText + +FONT_PATTERN: Final = '&"(?P.+)"' +COLOR_PATTERN: Final = "&K(?P[A-F0-9]{6})" +SIZE_REGEX: Final = r"&(?P\d+\s?)" +FORMAT_REGEX: Final[Pattern[str]] + +class _HeaderFooterPart(Strict): + text: String[Literal[True]] + font: String[Literal[True]] + size: Integer[Literal[True]] + RGB: ClassVar[str] + color: MatchPattern[str, Literal[True]] + def __init__( + self, text: str | None = None, font: str | None = None, size: ConvertibleToInt | None = None, color: str | None = None + ) -> None: ... + def __bool__(self) -> bool: ... + @classmethod + def from_str(cls, text): ... + +class HeaderFooterItem(Strict): + left: Typed[_HeaderFooterPart, Literal[False]] + center: Typed[_HeaderFooterPart, Literal[False]] + centre: Alias + right: Typed[_HeaderFooterPart, Literal[False]] + def __init__( + self, + left: _HeaderFooterPart | None = None, + right: _HeaderFooterPart | None = None, + center: _HeaderFooterPart | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + def to_tree(self, tagname: str) -> Element: ... + @classmethod + def from_tree(cls, node: _HasText) -> Self: ... + +class HeaderFooter(Serialisable): + tagname: ClassVar[str] + differentOddEven: Bool[Literal[True]] + differentFirst: Bool[Literal[True]] + scaleWithDoc: Bool[Literal[True]] + alignWithMargins: Bool[Literal[True]] + oddHeader: Typed[HeaderFooterItem, Literal[True]] + oddFooter: Typed[HeaderFooterItem, Literal[True]] + evenHeader: Typed[HeaderFooterItem, Literal[True]] + evenFooter: Typed[HeaderFooterItem, Literal[True]] + firstHeader: Typed[HeaderFooterItem, Literal[True]] + firstFooter: Typed[HeaderFooterItem, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + differentOddEven: _ConvertibleToBool | None = None, + differentFirst: _ConvertibleToBool | None = None, + scaleWithDoc: _ConvertibleToBool | None = None, + alignWithMargins: _ConvertibleToBool | None = None, + oddHeader: HeaderFooterItem | None = None, + oddFooter: HeaderFooterItem | None = None, + evenHeader: HeaderFooterItem | None = None, + evenFooter: HeaderFooterItem | None = None, + firstHeader: HeaderFooterItem | None = None, + firstFooter: HeaderFooterItem | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi b/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi new file mode 100644 index 000000000000..f569caaae701 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/hyperlink.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import String +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable + +class Hyperlink(Serialisable): + tagname: ClassVar[str] + ref: String[Literal[False]] + location: String[Literal[True]] + tooltip: String[Literal[True]] + display: String[Literal[True]] + id: Incomplete + target: String[Literal[True]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__( + self, + ref: str, + location: str | None = None, + tooltip: str | None = None, + display: str | None = None, + id=None, + target: str | None = None, + ) -> None: ... + +class HyperlinkList(Serialisable): + tagname: ClassVar[str] + hyperlink: Sequence[list[Hyperlink]] + def __init__(self, hyperlink: list[Hyperlink] | tuple[Hyperlink, ...] = ()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/merge.pyi b/stubs/openpyxl/openpyxl/worksheet/merge.pyi new file mode 100644 index 000000000000..0e97147febae --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/merge.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete, Unused +from typing import ClassVar + +from openpyxl.cell import _CellOrMergedCell +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.worksheet import Worksheet + +from .cell_range import CellRange + +class MergeCell(CellRange): + tagname: ClassVar[str] + # Same as CellRange.coord + # https://github.com/python/mypy/issues/6700 + @property + def ref(self) -> str: ... + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, ref=None) -> None: ... + def __copy__(self): ... + +class MergeCells(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + mergeCell: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, mergeCell=()) -> None: ... + @property + def count(self) -> int: ... + +class MergedCellRange(CellRange): + ws: Worksheet + start_cell: _CellOrMergedCell + def __init__(self, worksheet: Worksheet, coord) -> None: ... + def format(self) -> None: ... + def __contains__(self, coord: str) -> bool: ... + def __copy__(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/ole.pyi b/stubs/openpyxl/openpyxl/worksheet/ole.pyi new file mode 100644 index 000000000000..fedb4beaf3ef --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/ole.pyi @@ -0,0 +1,116 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias, overload + +from openpyxl.descriptors.base import Bool, Integer, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.drawing.spreadsheet_drawing import AnchorMarker + +_OleObjectDvAspect: TypeAlias = Literal["DVASPECT_CONTENT", "DVASPECT_ICON"] +_OleObjectOleUpdate: TypeAlias = Literal["OLEUPDATE_ALWAYS", "OLEUPDATE_ONCALL"] + +class ObjectAnchor(Serialisable): + tagname: ClassVar[str] + _from: Typed[AnchorMarker, Literal[False]] # Not private. Avoids name clash + to: Typed[AnchorMarker, Literal[False]] + moveWithCells: Bool[Literal[True]] + sizeWithCells: Bool[Literal[True]] + z_order: Integer[Literal[True]] + def __init__( + self, + _from: AnchorMarker, + to: AnchorMarker, + moveWithCells: _ConvertibleToBool | None = False, + sizeWithCells: _ConvertibleToBool | None = False, + z_order: ConvertibleToInt | None = None, + ) -> None: ... + +class ObjectPr(Serialisable): + tagname: ClassVar[str] + anchor: Typed[ObjectAnchor, Literal[False]] + locked: Bool[Literal[True]] + defaultSize: Bool[Literal[True]] + _print: Bool[Literal[True]] # Not private. Avoids name clash + disabled: Bool[Literal[True]] + uiObject: Bool[Literal[True]] + autoFill: Bool[Literal[True]] + autoLine: Bool[Literal[True]] + autoPict: Bool[Literal[True]] + macro: String[Literal[False]] + altText: String[Literal[True]] + dde: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None = None, + defaultSize: _ConvertibleToBool | None = None, + _print: _ConvertibleToBool | None = None, + disabled: _ConvertibleToBool | None = None, + uiObject: _ConvertibleToBool | None = None, + autoFill: _ConvertibleToBool | None = None, + autoLine: _ConvertibleToBool | None = None, + autoPict: _ConvertibleToBool | None = None, + *, + macro: str, + altText: str | None = None, + dde: _ConvertibleToBool | None = False, + ) -> None: ... + @overload + def __init__( + self, + anchor: ObjectAnchor, + locked: _ConvertibleToBool | None, + defaultSize: _ConvertibleToBool | None, + _print: _ConvertibleToBool | None, + disabled: _ConvertibleToBool | None, + uiObject: _ConvertibleToBool | None, + autoFill: _ConvertibleToBool | None, + autoLine: _ConvertibleToBool | None, + autoPict: _ConvertibleToBool | None, + macro: str, + altText: str | None = None, + dde: _ConvertibleToBool | None = False, + ) -> None: ... + +class OleObject(Serialisable): + tagname: ClassVar[str] + objectPr: Typed[ObjectPr, Literal[True]] + progId: String[Literal[True]] + dvAspect: Set[_OleObjectDvAspect] + link: String[Literal[True]] + oleUpdate: Set[_OleObjectOleUpdate] + autoLoad: Bool[Literal[True]] + shapeId: Integer[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + objectPr: ObjectPr | None = None, + progId: str | None = None, + dvAspect: _OleObjectDvAspect = "DVASPECT_CONTENT", + link: str | None = None, + *, + oleUpdate: _OleObjectOleUpdate, + autoLoad: _ConvertibleToBool | None = False, + shapeId: ConvertibleToInt, + ) -> None: ... + @overload + def __init__( + self, + objectPr: ObjectPr | None, + progId: str | None, + dvAspect: _OleObjectDvAspect, + link: str | None, + oleUpdate: _OleObjectOleUpdate, + autoLoad: _ConvertibleToBool | None, + shapeId: ConvertibleToInt, + ) -> None: ... + +class OleObjects(Serialisable): + tagname: ClassVar[str] + oleObject: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, oleObject=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/page.pyi b/stubs/openpyxl/openpyxl/worksheet/page.pyi new file mode 100644 index 000000000000..d86b80dd759f --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/page.pyi @@ -0,0 +1,108 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, TypeAlias +from typing_extensions import Self + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.worksheet.properties import PageSetupProperties + +_PrintPageSetupOrientation: TypeAlias = Literal["default", "portrait", "landscape"] +_PrintPageSetupPageOrder: TypeAlias = Literal["downThenOver", "overThenDown"] +_PrintPageSetupCellComments: TypeAlias = Literal["asDisplayed", "atEnd"] +_PrintPageSetupErrors: TypeAlias = Literal["displayed", "blank", "dash", "NA"] + +class PrintPageSetup(Serialisable): + tagname: ClassVar[str] + orientation: NoneSet[_PrintPageSetupOrientation] + paperSize: Integer[Literal[True]] + scale: Integer[Literal[True]] + fitToHeight: Integer[Literal[True]] + fitToWidth: Integer[Literal[True]] + firstPageNumber: Integer[Literal[True]] + useFirstPageNumber: Bool[Literal[True]] + paperHeight: Incomplete + paperWidth: Incomplete + pageOrder: NoneSet[_PrintPageSetupPageOrder] + usePrinterDefaults: Bool[Literal[True]] + blackAndWhite: Bool[Literal[True]] + draft: Bool[Literal[True]] + cellComments: NoneSet[_PrintPageSetupCellComments] + errors: NoneSet[_PrintPageSetupErrors] + horizontalDpi: Integer[Literal[True]] + verticalDpi: Integer[Literal[True]] + copies: Integer[Literal[True]] + id: Incomplete + def __init__( + self, + worksheet=None, + orientation: _PrintPageSetupOrientation | Literal["none"] | None = None, + paperSize: ConvertibleToInt | None = None, + scale: ConvertibleToInt | None = None, + fitToHeight: ConvertibleToInt | None = None, + fitToWidth: ConvertibleToInt | None = None, + firstPageNumber: ConvertibleToInt | None = None, + useFirstPageNumber: _ConvertibleToBool | None = None, + paperHeight=None, + paperWidth=None, + pageOrder: _PrintPageSetupPageOrder | Literal["none"] | None = None, + usePrinterDefaults: _ConvertibleToBool | None = None, + blackAndWhite: _ConvertibleToBool | None = None, + draft: _ConvertibleToBool | None = None, + cellComments: _PrintPageSetupCellComments | Literal["none"] | None = None, + errors: _PrintPageSetupErrors | Literal["none"] | None = None, + horizontalDpi: ConvertibleToInt | None = None, + verticalDpi: ConvertibleToInt | None = None, + copies: ConvertibleToInt | None = None, + id=None, + ) -> None: ... + def __bool__(self) -> bool: ... + @property + def sheet_properties(self) -> PageSetupProperties | None: ... + + @property + def fitToPage(self) -> bool | None: ... + @fitToPage.setter + def fitToPage(self, value: _ConvertibleToBool | None) -> None: ... + + @property + def autoPageBreaks(self) -> bool | None: ... + @autoPageBreaks.setter + def autoPageBreaks(self, value: _ConvertibleToBool | None) -> None: ... + + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + +class PrintOptions(Serialisable): + tagname: ClassVar[str] + horizontalCentered: Bool[Literal[True]] + verticalCentered: Bool[Literal[True]] + headings: Bool[Literal[True]] + gridLines: Bool[Literal[True]] + gridLinesSet: Bool[Literal[True]] + def __init__( + self, + horizontalCentered: _ConvertibleToBool | None = None, + verticalCentered: _ConvertibleToBool | None = None, + headings: _ConvertibleToBool | None = None, + gridLines: _ConvertibleToBool | None = None, + gridLinesSet: _ConvertibleToBool | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class PageMargins(Serialisable): + tagname: ClassVar[str] + left: Float[Literal[False]] + right: Float[Literal[False]] + top: Float[Literal[False]] + bottom: Float[Literal[False]] + header: Float[Literal[False]] + footer: Float[Literal[False]] + def __init__( + self, + left: ConvertibleToFloat = 0.75, + right: ConvertibleToFloat = 0.75, + top: ConvertibleToFloat = 1, + bottom: ConvertibleToFloat = 1, + header: ConvertibleToFloat = 0.5, + footer: ConvertibleToFloat = 0.5, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi b/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi new file mode 100644 index 000000000000..b0fe838d39db --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/pagebreak.pyi @@ -0,0 +1,48 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, Integer, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class Break(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[True]] + min: Integer[Literal[True]] + max: Integer[Literal[True]] + man: Bool[Literal[True]] + pt: Bool[Literal[True]] + def __init__( + self, + id: ConvertibleToInt | None = 0, + min: ConvertibleToInt | None = 0, + max: ConvertibleToInt | None = 16383, + man: _ConvertibleToBool | None = True, + pt: _ConvertibleToBool | None = None, + ) -> None: ... + +class RowBreak(Serialisable): + tagname: ClassVar[str] + # Overwritten by properties below + # count: Integer + # manualBreakCount: Integer + brk: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, manualBreakCount: Unused = None, brk=()) -> None: ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + @property + def count(self) -> int: ... + @property + def manualBreakCount(self) -> int: ... + def append(self, brk=None) -> None: ... + +PageBreak = RowBreak + +class ColBreak(RowBreak): + tagname: ClassVar[str] + # Same as parent + # count = RowBreak.count + # manualBreakCount = RowBreak.manualBreakCount + # brk = RowBreak.brk + __attrs__: ClassVar[tuple[str, ...]] diff --git a/stubs/openpyxl/openpyxl/worksheet/picture.pyi b/stubs/openpyxl/openpyxl/worksheet/picture.pyi new file mode 100644 index 000000000000..071947859eab --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/picture.pyi @@ -0,0 +1,6 @@ +from typing import ClassVar + +from openpyxl.descriptors.serialisable import Serialisable + +class SheetBackgroundPicture(Serialisable): + tagname: ClassVar[str] diff --git a/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi b/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi new file mode 100644 index 000000000000..f2d0f4c44155 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/print_settings.pyi @@ -0,0 +1,55 @@ +from _typeshed import ConvertibleToInt, Unused +from re import Pattern +from typing import Final, Literal, overload +from typing_extensions import Self + +from openpyxl.descriptors import Integer, Strict, String +from openpyxl.descriptors.base import Typed +from openpyxl.utils.cell import SHEETRANGE_RE as SHEETRANGE_RE + +from .cell_range import MultiCellRange + +COL_RANGE: Final[str] +COL_RANGE_RE: Final[Pattern[str]] +ROW_RANGE: Final[str] +ROW_RANGE_RE: Final[Pattern[str]] +TITLES_REGEX: Final[Pattern[str]] +PRINT_AREA_RE: Final[Pattern[str]] + +class ColRange(Strict): + min_col: String[Literal[False]] + max_col: String[Literal[False]] + + @overload + def __init__(self, range_string: None = None, *, min_col: str, max_col: str) -> None: ... + @overload + def __init__(self, range_string, min_col: Unused = None, max_col: Unused = None) -> None: ... + + def __eq__(self, other: object) -> bool: ... + +class RowRange(Strict): + min_row: Integer[Literal[False]] + max_row: Integer[Literal[False]] + + @overload + def __init__(self, range_string: None, min_row: ConvertibleToInt, max_row: ConvertibleToInt) -> None: ... + @overload + def __init__(self, range_string, min_row: Unused = None, max_row: Unused = None) -> None: ... + + def __eq__(self, other: object) -> bool: ... + +class PrintTitles(Strict): + cols: Typed[ColRange, Literal[True]] + rows: Typed[RowRange, Literal[True]] + title: String[Literal[False]] + def __init__(self, cols: ColRange | None = None, rows: RowRange | None = None, title: str = "") -> None: ... + @classmethod + def from_string(cls, value: str) -> Self: ... + def __eq__(self, other: object) -> bool: ... + +class PrintArea(MultiCellRange): + title: str + @classmethod + def from_string(cls, value) -> Self: ... + def __init__(self, ranges=(), title: Unused = "") -> None: ... + def __eq__(self, other: str | MultiCellRange) -> bool: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/properties.pyi b/stubs/openpyxl/openpyxl/worksheet/properties.pyi new file mode 100644 index 000000000000..ff31bb890d13 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/properties.pyi @@ -0,0 +1,56 @@ +from typing import ClassVar, Literal + +from openpyxl.descriptors.base import Bool, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.styles.colors import Color, ColorDescriptor + +class Outline(Serialisable): + tagname: ClassVar[str] + applyStyles: Bool[Literal[True]] + summaryBelow: Bool[Literal[True]] + summaryRight: Bool[Literal[True]] + showOutlineSymbols: Bool[Literal[True]] + def __init__( + self, + applyStyles: _ConvertibleToBool | None = None, + summaryBelow: _ConvertibleToBool | None = None, + summaryRight: _ConvertibleToBool | None = None, + showOutlineSymbols: _ConvertibleToBool | None = None, + ) -> None: ... + +class PageSetupProperties(Serialisable): + tagname: ClassVar[str] + autoPageBreaks: Bool[Literal[True]] + fitToPage: Bool[Literal[True]] + def __init__(self, autoPageBreaks: _ConvertibleToBool | None = None, fitToPage: _ConvertibleToBool | None = None) -> None: ... + +class WorksheetProperties(Serialisable): + tagname: ClassVar[str] + codeName: String[Literal[True]] + enableFormatConditionsCalculation: Bool[Literal[True]] + filterMode: Bool[Literal[True]] + published: Bool[Literal[True]] + syncHorizontal: Bool[Literal[True]] + syncRef: String[Literal[True]] + syncVertical: Bool[Literal[True]] + transitionEvaluation: Bool[Literal[True]] + transitionEntry: Bool[Literal[True]] + tabColor: ColorDescriptor[Literal[True]] + outlinePr: Typed[Outline, Literal[True]] + pageSetUpPr: Typed[PageSetupProperties, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + codeName: str | None = None, + enableFormatConditionsCalculation: _ConvertibleToBool | None = None, + filterMode: _ConvertibleToBool | None = None, + published: _ConvertibleToBool | None = None, + syncHorizontal: _ConvertibleToBool | None = None, + syncRef: str | None = None, + syncVertical: _ConvertibleToBool | None = None, + transitionEvaluation: _ConvertibleToBool | None = None, + transitionEntry: _ConvertibleToBool | None = None, + tabColor: str | Color | None = None, + outlinePr: Outline | None = None, + pageSetUpPr: PageSetupProperties | None = None, + ) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/protection.pyi b/stubs/openpyxl/openpyxl/worksheet/protection.pyi new file mode 100644 index 000000000000..02bf4dd923af --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/protection.pyi @@ -0,0 +1,79 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Alias, Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class _Protected: + @overload + def set_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + @property + def password(self) -> str | None: ... + @password.setter + def password(self, value: str) -> None: ... + +class SheetProtection(Serialisable, _Protected): + tagname: ClassVar[str] + sheet: Bool[Literal[False]] + enabled: Alias + objects: Bool[Literal[False]] + scenarios: Bool[Literal[False]] + formatCells: Bool[Literal[False]] + formatColumns: Bool[Literal[False]] + formatRows: Bool[Literal[False]] + insertColumns: Bool[Literal[False]] + insertRows: Bool[Literal[False]] + insertHyperlinks: Bool[Literal[False]] + deleteColumns: Bool[Literal[False]] + deleteRows: Bool[Literal[False]] + selectLockedCells: Bool[Literal[False]] + selectUnlockedCells: Bool[Literal[False]] + sort: Bool[Literal[False]] + autoFilter: Bool[Literal[False]] + pivotTables: Bool[Literal[False]] + saltValue: Incomplete + spinCount: Integer[Literal[True]] + algorithmName: String[Literal[True]] + hashValue: Incomplete + __attrs__: ClassVar[tuple[str, ...]] + password: Incomplete + def __init__( + self, + sheet: _ConvertibleToBool = False, + objects: _ConvertibleToBool = False, + scenarios: _ConvertibleToBool = False, + formatCells: _ConvertibleToBool = True, + formatRows: _ConvertibleToBool = True, + formatColumns: _ConvertibleToBool = True, + insertColumns: _ConvertibleToBool = True, + insertRows: _ConvertibleToBool = True, + insertHyperlinks: _ConvertibleToBool = True, + deleteColumns: _ConvertibleToBool = True, + deleteRows: _ConvertibleToBool = True, + selectLockedCells: _ConvertibleToBool = False, + selectUnlockedCells: _ConvertibleToBool = False, + sort: _ConvertibleToBool = True, + autoFilter: _ConvertibleToBool = True, + pivotTables: _ConvertibleToBool = True, + password=None, + algorithmName: str | None = None, + saltValue=None, + spinCount: ConvertibleToInt | None = None, + hashValue=None, + ) -> None: ... + + @overload + def set_password(self, value: str = "", already_hashed: Literal[False] = False) -> None: ... + @overload + def set_password(self, value: str | None, already_hashed: Literal[True]) -> None: ... + @overload + def set_password(self, value: str | None = "", *, already_hashed: Literal[True]) -> None: ... + + def enable(self) -> None: ... + def disable(self) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/related.pyi b/stubs/openpyxl/openpyxl/worksheet/related.pyi new file mode 100644 index 000000000000..3e31438cea64 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/related.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete, Unused + +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.xml.functions import Element + +class Related(Serialisable): + id: Incomplete + def __init__(self, id=None) -> None: ... + def to_tree(self, tagname: str | None, idx: Unused = None) -> Element: ... # type: ignore[override] diff --git a/stubs/openpyxl/openpyxl/worksheet/scenario.pyi b/stubs/openpyxl/openpyxl/worksheet/scenario.pyi new file mode 100644 index 000000000000..8ae7f0dca07e --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/scenario.pyi @@ -0,0 +1,89 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Convertible, Integer, String, _ConvertibleToBool, _ConvertibleToMultiCellRange +from openpyxl.descriptors.serialisable import Serialisable +from openpyxl.worksheet.cell_range import MultiCellRange + +class InputCells(Serialisable): + tagname: ClassVar[str] + r: String[Literal[False]] + deleted: Bool[Literal[True]] + undone: Bool[Literal[True]] + val: String[Literal[False]] + numFmtId: Integer[Literal[True]] + + @overload + def __init__( + self, + r: str, + deleted: _ConvertibleToBool | None = False, + undone: _ConvertibleToBool | None = False, + *, + val: str, + numFmtId: ConvertibleToInt | None = None, + ) -> None: ... + @overload + def __init__( + self, + r: str, + deleted: _ConvertibleToBool | None, + undone: _ConvertibleToBool | None, + val: str, + numFmtId: ConvertibleToInt | None = None, + ) -> None: ... + +class Scenario(Serialisable): + tagname: ClassVar[str] + inputCells: Incomplete + name: String[Literal[False]] + locked: Bool[Literal[True]] + hidden: Bool[Literal[True]] + user: String[Literal[True]] + comment: String[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + inputCells=(), + *, + name: str, + locked: _ConvertibleToBool | None = False, + hidden: _ConvertibleToBool | None = False, + count: Unused = None, + user: str | None = None, + comment: str | None = None, + ) -> None: ... + @overload + def __init__( + self, + inputCells, + name: str, + locked: _ConvertibleToBool | None = False, + hidden: _ConvertibleToBool | None = False, + count: Unused = None, + user: str | None = None, + comment: str | None = None, + ) -> None: ... + + @property + def count(self) -> int: ... + +class ScenarioList(Serialisable): + tagname: ClassVar[str] + scenario: Incomplete + current: Integer[Literal[True]] + show: Integer[Literal[True]] + sqref: Convertible[MultiCellRange, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + scenario=(), + current: ConvertibleToInt | None = None, + show: ConvertibleToInt | None = None, + sqref: _ConvertibleToMultiCellRange | None = None, + ) -> None: ... + def append(self, scenario) -> None: ... + def __bool__(self) -> bool: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi b/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi new file mode 100644 index 000000000000..9e45422c2ec0 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/smart_tag.pyi @@ -0,0 +1,50 @@ +from _typeshed import ConvertibleToInt, Incomplete +from typing import ClassVar, Literal, overload + +from openpyxl.descriptors.base import Bool, Integer, String, _ConvertibleToBool +from openpyxl.descriptors.serialisable import Serialisable + +class CellSmartTagPr(Serialisable): + tagname: ClassVar[str] + key: String[Literal[False]] + val: String[Literal[False]] + def __init__(self, key: str, val: str) -> None: ... + +class CellSmartTag(Serialisable): + tagname: ClassVar[str] + cellSmartTagPr: Incomplete + type: Integer[Literal[False]] + deleted: Bool[Literal[True]] + xmlBased: Bool[Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + cellSmartTagPr=(), + *, + type: ConvertibleToInt, + deleted: _ConvertibleToBool | None = False, + xmlBased: _ConvertibleToBool | None = False, + ) -> None: ... + @overload + def __init__( + self, + cellSmartTagPr, + type: ConvertibleToInt, + deleted: _ConvertibleToBool | None = False, + xmlBased: _ConvertibleToBool | None = False, + ) -> None: ... + +class CellSmartTags(Serialisable): + tagname: ClassVar[str] + cellSmartTag: Incomplete + r: String[Literal[False]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellSmartTag, r: str) -> None: ... + +class SmartTags(Serialisable): + tagname: ClassVar[str] + cellSmartTags: Incomplete + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, cellSmartTags=()) -> None: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/table.pyi b/stubs/openpyxl/openpyxl/worksheet/table.pyi new file mode 100644 index 000000000000..f8abd7b02a54 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/table.pyi @@ -0,0 +1,225 @@ +from _typeshed import ConvertibleToInt, Incomplete, Unused +from collections.abc import Iterator +from typing import ClassVar, Final, Literal, TypeAlias, overload +from typing_extensions import Self + +from openpyxl.descriptors import Strict, String +from openpyxl.descriptors.base import Alias, Bool, Integer, NoneSet, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.serialisable import Serialisable, _ChildSerialisableTreeElement +from openpyxl.worksheet.filters import AutoFilter, SortState +from openpyxl.xml.functions import Element + +_TableColumnTotalsRowFunction: TypeAlias = Literal[ + "sum", "min", "max", "average", "count", "countNums", "stdDev", "var", "custom" +] +_TableTableType: TypeAlias = Literal["worksheet", "xml", "queryTable"] + +TABLESTYLES: Final[tuple[str, ...]] +PIVOTSTYLES: Final[tuple[str, ...]] + +class TableStyleInfo(Serialisable): + tagname: ClassVar[str] + name: String[Literal[True]] + showFirstColumn: Bool[Literal[True]] + showLastColumn: Bool[Literal[True]] + showRowStripes: Bool[Literal[True]] + showColumnStripes: Bool[Literal[True]] + def __init__( + self, + name: str | None = None, + showFirstColumn: _ConvertibleToBool | None = None, + showLastColumn: _ConvertibleToBool | None = None, + showRowStripes: _ConvertibleToBool | None = None, + showColumnStripes: _ConvertibleToBool | None = None, + ) -> None: ... + +class XMLColumnProps(Serialisable): + tagname: ClassVar[str] + mapId: Integer[Literal[False]] + xpath: String[Literal[False]] + denormalized: Bool[Literal[True]] + xmlDataType: String[Literal[False]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + mapId: ConvertibleToInt, + xpath: str, + denormalized: _ConvertibleToBool | None = None, + *, + xmlDataType: str, + extLst: Unused = None, + ) -> None: ... + @overload + def __init__( + self, + mapId: ConvertibleToInt, + xpath: str, + denormalized: _ConvertibleToBool | None, + xmlDataType: str, + extLst: Unused = None, + ) -> None: ... + +class TableFormula(Serialisable): + tagname: ClassVar[str] + array: Bool[Literal[True]] + attr_text: Incomplete + text: Alias + def __init__(self, array: _ConvertibleToBool | None = None, attr_text=None) -> None: ... + +class TableColumn(Serialisable): + tagname: ClassVar[str] + id: Integer[Literal[False]] + uniqueName: String[Literal[True]] + name: String[Literal[False]] + totalsRowFunction: NoneSet[_TableColumnTotalsRowFunction] + totalsRowLabel: String[Literal[True]] + queryTableFieldId: Integer[Literal[True]] + headerRowDxfId: Integer[Literal[True]] + dataDxfId: Integer[Literal[True]] + totalsRowDxfId: Integer[Literal[True]] + headerRowCellStyle: String[Literal[True]] + dataCellStyle: String[Literal[True]] + totalsRowCellStyle: String[Literal[True]] + calculatedColumnFormula: Typed[TableFormula, Literal[True]] + totalsRowFormula: Typed[TableFormula, Literal[True]] + xmlColumnPr: Typed[XMLColumnProps, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + + @overload + def __init__( + self, + id: ConvertibleToInt, + uniqueName: str | None = None, + *, + name: str, + totalsRowFunction: _TableColumnTotalsRowFunction | Literal["none"] | None = None, + totalsRowLabel: str | None = None, + queryTableFieldId: ConvertibleToInt | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + calculatedColumnFormula: TableFormula | None = None, + totalsRowFormula: TableFormula | None = None, + xmlColumnPr: XMLColumnProps | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + @overload + def __init__( + self, + id: ConvertibleToInt, + uniqueName: str | None, + name: str, + totalsRowFunction: _TableColumnTotalsRowFunction | Literal["none"] | None = None, + totalsRowLabel: str | None = None, + queryTableFieldId: ConvertibleToInt | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + calculatedColumnFormula: TableFormula | None = None, + totalsRowFormula: TableFormula | None = None, + xmlColumnPr: XMLColumnProps | None = None, + extLst: ExtensionList | None = None, + ) -> None: ... + + def __iter__(self) -> Iterator[tuple[str, str]]: ... + @classmethod + def from_tree(cls, node: _ChildSerialisableTreeElement) -> Self: ... + +class TableNameDescriptor(String[Incomplete]): + def __set__(self, instance: Serialisable | Strict, value) -> None: ... + +class Table(Serialisable): + mime_type: str + tagname: ClassVar[str] + id: Integer[Literal[False]] + name: String[Literal[True]] + displayName: Incomplete + comment: String[Literal[True]] + ref: Incomplete + tableType: NoneSet[_TableTableType] + headerRowCount: Integer[Literal[True]] + insertRow: Bool[Literal[True]] + insertRowShift: Bool[Literal[True]] + totalsRowCount: Integer[Literal[True]] + totalsRowShown: Bool[Literal[True]] + published: Bool[Literal[True]] + headerRowDxfId: Integer[Literal[True]] + dataDxfId: Integer[Literal[True]] + totalsRowDxfId: Integer[Literal[True]] + headerRowBorderDxfId: Integer[Literal[True]] + tableBorderDxfId: Integer[Literal[True]] + totalsRowBorderDxfId: Integer[Literal[True]] + headerRowCellStyle: String[Literal[True]] + dataCellStyle: String[Literal[True]] + totalsRowCellStyle: String[Literal[True]] + connectionId: Integer[Literal[True]] + autoFilter: Typed[AutoFilter, Literal[True]] + sortState: Typed[SortState, Literal[True]] + tableColumns: Incomplete + tableStyleInfo: Typed[TableStyleInfo, Literal[True]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__( + self, + id: ConvertibleToInt = 1, + displayName=None, + ref=None, + name: str | None = None, + comment: str | None = None, + tableType: _TableTableType | Literal["none"] | None = None, + headerRowCount: ConvertibleToInt | None = 1, + insertRow: _ConvertibleToBool | None = None, + insertRowShift: _ConvertibleToBool | None = None, + totalsRowCount: ConvertibleToInt | None = None, + totalsRowShown: _ConvertibleToBool | None = None, + published: _ConvertibleToBool | None = None, + headerRowDxfId: ConvertibleToInt | None = None, + dataDxfId: ConvertibleToInt | None = None, + totalsRowDxfId: ConvertibleToInt | None = None, + headerRowBorderDxfId: ConvertibleToInt | None = None, + tableBorderDxfId: ConvertibleToInt | None = None, + totalsRowBorderDxfId: ConvertibleToInt | None = None, + headerRowCellStyle: str | None = None, + dataCellStyle: str | None = None, + totalsRowCellStyle: str | None = None, + connectionId: ConvertibleToInt | None = None, + autoFilter: AutoFilter | None = None, + sortState: SortState | None = None, + tableColumns=(), + tableStyleInfo: TableStyleInfo | None = None, + extLst: Unused = None, + ) -> None: ... + def to_tree(self) -> Element: ... # type: ignore[override] + @property + def path(self) -> str: ... + @property + def column_names(self) -> list[str]: ... + +class TablePartList(Serialisable): + tagname: ClassVar[str] + # Overwritten by property below + # count: Integer + tablePart: Incomplete + __elements__: ClassVar[tuple[str, ...]] + __attrs__: ClassVar[tuple[str, ...]] + def __init__(self, count: Unused = None, tablePart=()) -> None: ... + def append(self, part) -> None: ... + @property + def count(self) -> int: ... + def __bool__(self) -> bool: ... + +class TableList(dict[Incomplete, Incomplete]): + def add(self, table) -> None: ... + def get(self, name=None, table_range=None): ... + def items(self): ... diff --git a/stubs/openpyxl/openpyxl/worksheet/views.pyi b/stubs/openpyxl/openpyxl/worksheet/views.pyi new file mode 100644 index 000000000000..70e6420988fd --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/views.pyi @@ -0,0 +1,98 @@ +from _typeshed import ConvertibleToFloat, ConvertibleToInt, Incomplete, Unused +from typing import ClassVar, Literal, TypeAlias + +from openpyxl.descriptors.base import Bool, Float, Integer, NoneSet, Set, String, Typed, _ConvertibleToBool +from openpyxl.descriptors.excel import ExtensionList +from openpyxl.descriptors.sequence import Sequence +from openpyxl.descriptors.serialisable import Serialisable + +_Pane: TypeAlias = Literal["bottomRight", "topRight", "bottomLeft", "topLeft"] +_SheetViewView: TypeAlias = Literal["normal", "pageBreakPreview", "pageLayout"] +_PaneState: TypeAlias = Literal["split", "frozen", "frozenSplit"] + +class Pane(Serialisable): + xSplit: Float[Literal[True]] + ySplit: Float[Literal[True]] + topLeftCell: String[Literal[True]] + activePane: Set[_Pane] + state: Set[_PaneState] + def __init__( + self, + xSplit: ConvertibleToFloat | None = None, + ySplit: ConvertibleToFloat | None = None, + topLeftCell: str | None = None, + activePane: _Pane = "topLeft", + state: _PaneState = "split", + ) -> None: ... + +class Selection(Serialisable): + pane: NoneSet[_Pane] + activeCell: String[Literal[True]] + activeCellId: Integer[Literal[True]] + sqref: String[Literal[True]] + def __init__( + self, + pane: _Pane | Literal["none"] | None = None, + activeCell: str | None = "A1", + activeCellId: ConvertibleToInt | None = None, + sqref: str | None = "A1", + ) -> None: ... + +class SheetView(Serialisable): + tagname: ClassVar[str] + windowProtection: Bool[Literal[True]] + showFormulas: Bool[Literal[True]] + showGridLines: Bool[Literal[True]] + showRowColHeaders: Bool[Literal[True]] + showZeros: Bool[Literal[True]] + rightToLeft: Bool[Literal[True]] + tabSelected: Bool[Literal[True]] + showRuler: Bool[Literal[True]] + showOutlineSymbols: Bool[Literal[True]] + defaultGridColor: Bool[Literal[True]] + showWhiteSpace: Bool[Literal[True]] + view: NoneSet[_SheetViewView] + topLeftCell: String[Literal[True]] + colorId: Integer[Literal[True]] + zoomScale: Integer[Literal[True]] + zoomScaleNormal: Integer[Literal[True]] + zoomScaleSheetLayoutView: Integer[Literal[True]] + zoomScalePageLayoutView: Integer[Literal[True]] + zoomToFit: Bool[Literal[True]] + workbookViewId: Integer[Literal[True]] + selection: Incomplete + pane: Typed[Pane, Literal[True]] + def __init__( + self, + windowProtection: _ConvertibleToBool | None = None, + showFormulas: _ConvertibleToBool | None = None, + showGridLines: _ConvertibleToBool | None = None, + showRowColHeaders: _ConvertibleToBool | None = None, + showZeros: _ConvertibleToBool | None = None, + rightToLeft: _ConvertibleToBool | None = None, + tabSelected: _ConvertibleToBool | None = None, + showRuler: _ConvertibleToBool | None = None, + showOutlineSymbols: _ConvertibleToBool | None = None, + defaultGridColor: _ConvertibleToBool | None = None, + showWhiteSpace: _ConvertibleToBool | None = None, + view: _SheetViewView | Literal["none"] | None = None, + topLeftCell: str | None = None, + colorId: ConvertibleToInt | None = None, + zoomScale: ConvertibleToInt | None = None, + zoomScaleNormal: ConvertibleToInt | None = None, + zoomScaleSheetLayoutView: ConvertibleToInt | None = None, + zoomScalePageLayoutView: ConvertibleToInt | None = None, + zoomToFit: _ConvertibleToBool | None = None, + workbookViewId: ConvertibleToInt | None = 0, + selection=None, + pane: Pane | None = None, + ) -> None: ... + +class SheetViewList(Serialisable): + tagname: ClassVar[str] + sheetView: Sequence[list[SheetView]] + extLst: Typed[ExtensionList, Literal[True]] + __elements__: ClassVar[tuple[str, ...]] + def __init__(self, sheetView: SheetView | None = None, extLst: Unused = None) -> None: ... + @property + def active(self) -> SheetView: ... diff --git a/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi b/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi new file mode 100644 index 000000000000..be41858dc291 --- /dev/null +++ b/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi @@ -0,0 +1,289 @@ +from _typeshed import ConvertibleToInt, Incomplete +from collections.abc import Generator, Iterable, Iterator +from types import GeneratorType +from typing import Any, Final, Literal, overload +from typing_extensions import Never, deprecated + +from openpyxl import _Decodable, _VisibilityType +from openpyxl.cell import _AnyCellValue, _CellGetValue, _CellOrMergedCell, _CellSetValue +from openpyxl.cell.cell import Cell +from openpyxl.chart._chart import ChartBase +from openpyxl.drawing.image import Image +from openpyxl.formatting.formatting import ConditionalFormattingList +from openpyxl.workbook.child import _WorkbookChild +from openpyxl.workbook.defined_name import DefinedNameDict +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.cell_range import CellRange, MultiCellRange +from openpyxl.worksheet.datavalidation import DataValidation, DataValidationList +from openpyxl.worksheet.dimensions import ColumnDimension, DimensionHolder, RowDimension, SheetFormatProperties +from openpyxl.worksheet.filters import AutoFilter +from openpyxl.worksheet.page import PageMargins, PrintOptions, PrintPageSetup +from openpyxl.worksheet.pagebreak import ColBreak, RowBreak +from openpyxl.worksheet.properties import WorksheetProperties +from openpyxl.worksheet.protection import SheetProtection +from openpyxl.worksheet.scenario import ScenarioList +from openpyxl.worksheet.table import Table, TableList +from openpyxl.worksheet.views import SheetView, SheetViewList + +class Worksheet(_WorkbookChild): + mime_type: str + BREAK_NONE: Final = 0 + BREAK_ROW: Final = 1 + BREAK_COLUMN: Final = 2 + + SHEETSTATE_VISIBLE: Final = "visible" + SHEETSTATE_HIDDEN: Final = "hidden" + SHEETSTATE_VERYHIDDEN: Final = "veryHidden" + + PAPERSIZE_LETTER: Final = "1" + PAPERSIZE_LETTER_SMALL: Final = "2" + PAPERSIZE_TABLOID: Final = "3" + PAPERSIZE_LEDGER: Final = "4" + PAPERSIZE_LEGAL: Final = "5" + PAPERSIZE_STATEMENT: Final = "6" + PAPERSIZE_EXECUTIVE: Final = "7" + PAPERSIZE_A3: Final = "8" + PAPERSIZE_A4: Final = "9" + PAPERSIZE_A4_SMALL: Final = "10" + PAPERSIZE_A5: Final = "11" + + ORIENTATION_PORTRAIT: Final = "portrait" + ORIENTATION_LANDSCAPE: Final = "landscape" + + _cells: dict[tuple[int, int], _CellOrMergedCell] # private but very useful to understand typing + row_dimensions: DimensionHolder[int, RowDimension] + column_dimensions: DimensionHolder[str, ColumnDimension] + row_breaks: RowBreak + col_breaks: ColBreak + merged_cells: MultiCellRange + data_validations: DataValidationList + sheet_state: _VisibilityType + page_setup: PrintPageSetup + print_options: PrintOptions + page_margins: PageMargins + views: SheetViewList + protection: SheetProtection + defined_names: DefinedNameDict + auto_filter: AutoFilter + conditional_formatting: ConditionalFormattingList + legacy_drawing: Incomplete | None + sheet_properties: WorksheetProperties + sheet_format: SheetFormatProperties + scenarios: ScenarioList + + def __init__(self, parent: Workbook | None, title: str | _Decodable | None = None) -> None: ... + @property + def sheet_view(self) -> SheetView: ... + @property + def selected_cell(self) -> str | None: ... + @property + def active_cell(self) -> str | None: ... + @property + def array_formulae(self) -> dict[str, str]: ... + @property + def show_gridlines(self) -> bool | None: ... + + @property + def freeze_panes(self) -> str | None: ... + @freeze_panes.setter + def freeze_panes(self, topLeftCell: str | Cell | None = None) -> None: ... + + # A MergedCell value should be kept to None + @overload + def cell(self, row: int, column: int, value: None = None) -> _CellOrMergedCell: ... + @overload + def cell(self, row: int, column: int, value: _CellSetValue = None) -> Cell: ... + + # An int is necessarily a row selection + @overload + def __getitem__(self, key: int) -> tuple[_CellOrMergedCell, ...]: ... + # A slice is necessarily a row or rows, even if targetting a single cell + @overload + def __getitem__(self, key: slice) -> tuple[Any, ...]: ... # tuple[AnyOf[_CellOrMergedCell, tuple[_CellOrMergedCell, ...]]] + # A str could be an individual cell, row, column or full range + @overload + def __getitem__( + self, key: str + ) -> Any: ... # AnyOf[_CellOrMergedCell, tuple[_CellOrMergedCell, ...], tuple[tuple[_CellOrMergedCell, ...], ...]] + + def __setitem__(self, key: str, value: _CellSetValue) -> None: ... + def __iter__(self) -> Iterator[tuple[_CellOrMergedCell, ...]]: ... + def __delitem__(self, key: str) -> None: ... + @property + def min_row(self) -> int: ... + @property + def max_row(self) -> int: ... + @property + def min_column(self) -> int: ... + @property + def max_column(self) -> int: ... + def calculate_dimension(self) -> str: ... + @property + def dimensions(self) -> str: ... + + @overload + def iter_rows( + self, min_row: int | None, max_row: int | None, min_col: int | None, max_col: int | None, values_only: Literal[True] + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + *, + values_only: Literal[True], + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + values_only: Literal[False] = False, + ) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @overload + def iter_rows( + self, min_row: int | None, max_row: int | None, min_col: int | None, max_col: int | None, values_only: bool + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_rows( + self, + min_row: int | None = None, + max_row: int | None = None, + min_col: int | None = None, + max_col: int | None = None, + *, + values_only: bool, + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + + @property + def rows(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @property + def values(self) -> Generator[tuple[_CellGetValue, ...]]: ... + + @overload + def iter_cols( + self, min_col: int | None, max_col: int | None, min_row: int | None, max_row: int | None, values_only: Literal[True] + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + *, + values_only: Literal[True], + ) -> Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + values_only: Literal[False] = False, + ) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @overload + def iter_cols( + self, min_col: int | None, max_col: int | None, min_row: int | None, max_row: int | None, values_only: bool + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + @overload + def iter_cols( + self, + min_col: int | None = None, + max_col: int | None = None, + min_row: int | None = None, + max_row: int | None = None, + *, + values_only: bool, + ) -> Generator[tuple[_CellOrMergedCell, ...]] | Generator[tuple[_CellGetValue, ...]]: ... + + @property + def columns(self) -> Generator[tuple[_CellOrMergedCell, ...]]: ... + @property + def column_groups(self) -> list[str]: ... + def set_printer_settings( + self, paper_size: int | None, orientation: Literal["default", "portrait", "landscape"] | None + ) -> None: ... + def add_data_validation(self, data_validation: DataValidation) -> None: ... + def add_chart(self, chart: ChartBase, anchor: str | None = None) -> None: ... + def add_image(self, img: Image, anchor: str | None = None) -> None: ... + def add_table(self, table: Table) -> None: ... + @property + def tables(self) -> TableList: ... + def add_pivot(self, pivot) -> None: ... + + # Same overload as CellRange.__init__ + @overload + def merge_cells( + self, range_string: str, start_row: None = None, start_column: None = None, end_row: None = None, end_column: None = None + ) -> None: ... + @overload + def merge_cells( + self, + range_string: None = None, + *, + start_row: ConvertibleToInt, + start_column: ConvertibleToInt, + end_row: ConvertibleToInt, + end_column: ConvertibleToInt, + ) -> None: ... + @overload + def merge_cells( + self, + range_string: None, + start_row: ConvertibleToInt, + start_column: ConvertibleToInt, + end_row: ConvertibleToInt, + end_column: ConvertibleToInt, + ) -> None: ... + + # Will always raise: TypeError: 'set' object is not subscriptable + @property + @deprecated("Use ws.merged_cells.ranges") + def merged_cell_ranges(self) -> Never: ... + def unmerge_cells( + self, + range_string: str | None = None, + start_row: int | None = None, + start_column: int | None = None, + end_row: int | None = None, + end_column: int | None = None, + ) -> None: ... + def append( + self, + iterable: ( + list[_AnyCellValue] + | tuple[_CellOrMergedCell | _CellGetValue, ...] + | range + | GeneratorType[_CellOrMergedCell | _CellGetValue, object, object] + | dict[int | str, _AnyCellValue] + ), + ) -> None: ... + def insert_rows(self, idx: int, amount: int = 1) -> None: ... + def insert_cols(self, idx: int, amount: int = 1) -> None: ... + def delete_rows(self, idx: int, amount: int = 1) -> None: ... + def delete_cols(self, idx: int, amount: int = 1) -> None: ... + def move_range(self, cell_range: CellRange | str, rows: int = 0, cols: int = 0, translate: bool = False) -> None: ... + + @property + def print_title_rows(self) -> str | None: ... + @print_title_rows.setter + def print_title_rows(self, rows: str | None) -> None: ... + + @property + def print_title_cols(self) -> str | None: ... + @print_title_cols.setter + def print_title_cols(self, cols: str | None) -> None: ... + + @property + def print_titles(self) -> str: ... + + @property + def print_area(self) -> str: ... + @print_area.setter + def print_area(self, value: str | Iterable[str] | None) -> None: ... diff --git a/stubs/openpyxl/openpyxl/writer/__init__.pyi b/stubs/openpyxl/openpyxl/writer/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/openpyxl/openpyxl/writer/excel.pyi b/stubs/openpyxl/openpyxl/writer/excel.pyi new file mode 100644 index 000000000000..5baba43b2859 --- /dev/null +++ b/stubs/openpyxl/openpyxl/writer/excel.pyi @@ -0,0 +1,18 @@ +from typing import Literal +from zipfile import ZipFile + +from openpyxl import _ZipFileFileProtocol +from openpyxl.packaging.manifest import Manifest +from openpyxl.workbook.workbook import Workbook +from openpyxl.worksheet.worksheet import Worksheet + +class ExcelWriter: + workbook: Workbook + manifest: Manifest + vba_modified: set[str | None] + def __init__(self, workbook: Workbook, archive: ZipFile) -> None: ... + def write_data(self) -> None: ... + def write_worksheet(self, ws: Worksheet) -> None: ... + def save(self) -> None: ... + +def save_workbook(workbook: Workbook, filename: _ZipFileFileProtocol) -> Literal[True]: ... diff --git a/stubs/openpyxl/openpyxl/writer/theme.pyi b/stubs/openpyxl/openpyxl/writer/theme.pyi new file mode 100644 index 000000000000..079c7d6506cb --- /dev/null +++ b/stubs/openpyxl/openpyxl/writer/theme.pyi @@ -0,0 +1,3 @@ +theme_xml: str + +def write_theme(): ... diff --git a/stubs/openpyxl/openpyxl/xml/__init__.pyi b/stubs/openpyxl/openpyxl/xml/__init__.pyi new file mode 100644 index 000000000000..f3d56263e6ee --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/__init__.pyi @@ -0,0 +1,11 @@ +from typing import Final + +def lxml_available() -> bool: ... +def lxml_env_set() -> bool: ... + +LXML: Final[bool] + +def defusedxml_available() -> bool: ... +def defusedxml_env_set() -> bool: ... + +DEFUSEDXML: Final[bool] diff --git a/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi b/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi new file mode 100644 index 000000000000..a4a2d6103f3e --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/_functions_overloads.pyi @@ -0,0 +1,146 @@ +# This file does not exist at runtime. It is a helper file to overload imported functions in openpyxl.xml.functions + +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Iterable, Iterator, Mapping, Sequence +from typing import Any, Protocol, TypeAlias, TypeVar, overload, type_check_only +from xml.etree.ElementTree import Element, ElementTree, QName, XMLParser, _FileRead + +from openpyxl.chart.axis import ChartLines + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) + +# Useful protocols, see import comment in openpyxl/xml/functions.pyi + +# Comment from openpyxl.cell.rich_text.py +# Usually an Element() from either lxml or xml.etree (has a 'tag' element) +# lxml.etree._Element +# xml.etree.Element +@type_check_only +class _HasTag(Protocol): + tag: str + +@type_check_only +class _HasGet(Protocol[_T_co]): + def get(self, value: str, /) -> _T_co | None: ... + +@type_check_only +class _HasText(Protocol): + text: str + +@type_check_only +class _HasAttrib(Protocol): + attrib: Iterable[Any] # AnyOf[dict[str, str], Iterable[tuple[str, str]]] + +@type_check_only +class _HasTagAndGet(_HasTag, _HasGet[_T_co], Protocol[_T_co]): ... # noqa: Y046 + +@type_check_only +class _HasTagAndText(_HasTag, _HasText, Protocol): ... # noqa: Y046 + +@type_check_only +class _HasTagAndTextAndAttrib(_HasTag, _HasText, _HasAttrib, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsFindChartLines(Protocol): + def find(self, path: str, /) -> ChartLines | None: ... + +@type_check_only +class _SupportsFindAndIterAndAttribAndText( # noqa: Y046 + _SupportsFindChartLines, Iterable[Incomplete], _HasAttrib, _HasText, Protocol +): ... + +@type_check_only +class _SupportsIterAndAttrib(Iterable[Incomplete], _HasAttrib, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsIterAndAttribAndTextAndTag(Iterable[Incomplete], _HasAttrib, _HasText, _HasTag, Protocol): ... # noqa: Y046 + +@type_check_only +class _SupportsIterAndAttribAndTextAndGet( # noqa: Y046 + Iterable[Incomplete], _HasAttrib, _HasText, _HasGet[Incomplete], Protocol +): ... + +@type_check_only +class _ParentElement(Protocol[_T]): + def makeelement(self, tag: str, attrib: dict[str, str], /) -> _T: ... + def append(self, element: _T, /) -> object: ... + +# from lxml.etree import _Element +_lxml_Element: TypeAlias = Element # noqa: Y042 +# from lxml.etree import _ElementTree +_lxml_ElementTree: TypeAlias = ElementTree # noqa: Y042 +# from lxml.etree import QName +_lxml_QName: TypeAlias = QName # noqa: Y042 + +# from xml.etree import fromstring +@overload +def SubElement(parent: _ParentElement[_T], tag: str, attrib: dict[str, str] = ..., **extra: str) -> _T: ... + +# from lxml.etree import fromstring +@overload +def SubElement( + _parent: _lxml_Element, # This would be preferable as a protocol, but it's a C-Extension + _tag: str | bytes | _lxml_QName, + attrib: dict[str, str] | dict[bytes, bytes] | None = ..., + nsmap: Mapping[str, str] | None = ..., + **extra: str | bytes, +) -> _lxml_ElementTree: ... + +# from xml.etree.ElementTree import fromstring +@overload +def fromstring(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ... + +# from lxml.etree import fromstring +# But made partial, removing parser arg +@overload +def fromstring(text: str | bytes, *, base_url: str | bytes = ...) -> _lxml_Element: ... + +# from defusedxml.ElementTree import fromstring +@overload +def fromstring(text: str, forbid_dtd: bool = False, forbid_entities: bool = True, forbid_external: bool = True) -> int: ... + +# from xml.etree.ElementTree import tostring +# But made partial, removing encoding arg +@overload +def tostring( + element: Element, + method: str | None = "xml", + *, + xml_declaration: bool | None = None, + default_namespace: str | None = ..., + short_empty_elements: bool = ..., +) -> str: ... + +# from lxml.etree import Element +# But made partial, removing encoding arg +@overload +def tostring( + element_or_tree: _lxml_Element | _lxml_ElementTree, + method: str = ..., + xml_declaration: bool = ..., + pretty_print: bool = ..., + with_tail: bool = ..., + standalone: bool = ..., + doctype: str = ..., + exclusive: bool = ..., + with_comments: bool = ..., + inclusive_ns_prefixes=..., +) -> bytes: ... + +# from xml.etree.ElementTree import iterparse +@overload +def iterparse( + source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None +) -> Iterator[tuple[str, Any]]: ... + +# from defusedxml.ElementTree import iterparse +@overload +def iterparse( + source: _FileRead, + events: Sequence[str] | None = None, + parser: XMLParser | None = None, + forbid_dtd: bool = False, + forbid_entities: bool = True, + forbid_external: bool = True, +) -> Iterator[tuple[str, Any]]: ... diff --git a/stubs/openpyxl/openpyxl/xml/constants.pyi b/stubs/openpyxl/openpyxl/xml/constants.pyi new file mode 100644 index 000000000000..1c5a15bb8fd7 --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/constants.pyi @@ -0,0 +1,91 @@ +from typing import Final + +MIN_ROW: Final = 0 +MIN_COLUMN: Final = 0 +MAX_COLUMN: Final = 16384 +MAX_ROW: Final = 1048576 + +PACKAGE_PROPS: Final = "docProps" +PACKAGE_XL: Final = "xl" +PACKAGE_RELS: Final = "_rels" +PACKAGE_THEME: Final = "xl/theme" +PACKAGE_WORKSHEETS: Final = "xl/worksheets" +PACKAGE_CHARTSHEETS: Final = "xl/chartsheets" +PACKAGE_DRAWINGS: Final = "xl/drawings" +PACKAGE_CHARTS: Final = "xl/charts" +PACKAGE_IMAGES: Final = "xl/media" +PACKAGE_WORKSHEET_RELS: Final = "xl/worksheets/_rels" +PACKAGE_CHARTSHEETS_RELS: Final = "xl/chartsheets/_rels" +PACKAGE_PIVOT_TABLE: Final = "xl/pivotTables" +PACKAGE_PIVOT_CACHE: Final = "xl/pivotCache" + +ARC_CONTENT_TYPES: Final = "[Content_Types].xml" +ARC_ROOT_RELS: Final = "_rels/.rels" +ARC_WORKBOOK_RELS: Final = "xl/_rels/workbook.xml.rels" +ARC_CORE: Final = "docProps/core.xml" +ARC_APP: Final = "docProps/app.xml" +ARC_CUSTOM: Final = "docProps/custom.xml" +ARC_WORKBOOK: Final = "xl/workbook.xml" +ARC_STYLE: Final = "xl/styles.xml" +ARC_THEME: Final = "xl/theme/theme1.xml" +ARC_SHARED_STRINGS: Final = "xl/sharedStrings.xml" +ARC_CUSTOM_UI: Final = "customUI/customUI.xml" + +DCORE_NS: Final = "http://purl.org/dc/elements/1.1/" +DCTERMS_NS: Final = "http://purl.org/dc/terms/" +DCTERMS_PREFIX: Final = "dcterms" + +DOC_NS: Final[str] +REL_NS: Final[str] +COMMENTS_NS: Final[str] +IMAGE_NS: Final[str] +VML_NS: Final[str] +VTYPES_NS: Final[str] +XPROPS_NS: Final[str] +CUSTPROPS_NS: Final[str] +EXTERNAL_LINK_NS: Final[str] + +CPROPS_FMTID: Final = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}" + +PKG_NS: Final = "http://schemas.openxmlformats.org/package/2006/" +PKG_REL_NS: Final[str] +COREPROPS_NS: Final[str] +CONTYPES_NS: Final[str] + +XSI_NS: Final = "http://www.w3.org/2001/XMLSchema-instance" +XML_NS: Final = "http://www.w3.org/XML/1998/namespace" +SHEET_MAIN_NS: Final[str] + +CHART_NS: Final[str] +DRAWING_NS: Final[str] +SHEET_DRAWING_NS: Final[str] +CHART_DRAWING_NS: Final[str] + +CUSTOMUI_NS: Final[str] + +NAMESPACES: Final[dict[str, str]] + +WORKBOOK_MACRO: Final = "application/vnd.ms-excel.%s.macroEnabled.main+xml" +WORKBOOK: Final[str] +SPREADSHEET: Final[str] +SHARED_STRINGS: Final[str] +EXTERNAL_LINK: Final[str] +WORKSHEET_TYPE: Final[str] +COMMENTS_TYPE: Final[str] +STYLES_TYPE: Final[str] +CHARTSHEET_TYPE: Final[str] +DRAWING_TYPE: Final[str] +CHART_TYPE: Final[str] +CHARTSHAPE_TYPE: Final[str] +THEME_TYPE: Final[str] +CPROPS_TYPE: Final[str] +XLTM: Final[str] +XLSM: Final[str] +XLTX: Final[str] +XLSX: Final[str] + +EXT_TYPES: Final[dict[str, str]] + +CTRL: Final = "application/vnd.ms-excel.controlproperties+xml" +ACTIVEX: Final = "application/vnd.ms-office.activeX+xml" +VBA: Final = "application/vnd.ms-office.vbaProject" diff --git a/stubs/openpyxl/openpyxl/xml/functions.pyi b/stubs/openpyxl/openpyxl/xml/functions.pyi new file mode 100644 index 000000000000..fe6f96c20b23 --- /dev/null +++ b/stubs/openpyxl/openpyxl/xml/functions.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from re import Pattern +from typing import Final + +# Can actually be imported from a mix of xml, lxml, et_xmlfile and defusedxml +# But et_xmlfile is untyped. openpyxl does not directly depend on lxml/lxml-stubs. +# And forcing a dependency on defusedxml felt overkill as it just wraps xml +# So for typing purposes, let's pretend xml is the only dependency. +# Prefer using protocols over these for parameters. +from xml.etree.ElementTree import Element as Element, QName as QName + +from ._functions_overloads import ( + SubElement as SubElement, + _HasTag, + _HasText, + fromstring as fromstring, + iterparse as iterparse, + tostring as tostring, +) + +# from lxml.etree import xmlfile +# from et_xmlfile import xmlfile +xmlfile: Incomplete + +NS_REGEX: Final[Pattern[str]] + +def localname(node: _HasTag) -> str: ... +def whitespace(node: _HasText) -> None: ... diff --git a/stubs/opentracing/@tests/stubtest_allowlist.txt b/stubs/opentracing/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9f41ee7c2a11 --- /dev/null +++ b/stubs/opentracing/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +# They raise ModuleNotFoundError so they are not present at stubtest runtime: +opentracing.harness.api_check +opentracing.harness.scope_check +opentracing.scope_managers.gevent +opentracing.scope_managers.tornado diff --git a/stubs/opentracing/METADATA.toml b/stubs/opentracing/METADATA.toml new file mode 100644 index 000000000000..110d9ccd1660 --- /dev/null +++ b/stubs/opentracing/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.4.*" +upstream-repository = "https://github.com/opentracing/opentracing-python" diff --git a/stubs/opentracing/opentracing/__init__.pyi b/stubs/opentracing/opentracing/__init__.pyi new file mode 100644 index 000000000000..69d6e6b78ec2 --- /dev/null +++ b/stubs/opentracing/opentracing/__init__.pyi @@ -0,0 +1,24 @@ +from .propagation import ( + Format as Format, + InvalidCarrierException as InvalidCarrierException, + SpanContextCorruptedException as SpanContextCorruptedException, + UnsupportedFormatException as UnsupportedFormatException, +) +from .scope import Scope as Scope +from .scope_manager import ScopeManager as ScopeManager +from .span import Span as Span, SpanContext as SpanContext +from .tracer import ( + Reference as Reference, + ReferenceType as ReferenceType, + Tracer as Tracer, + child_of as child_of, + follows_from as follows_from, + start_child_span as start_child_span, +) + +tracer: Tracer +is_tracer_registered: bool + +def global_tracer() -> Tracer: ... +def set_global_tracer(value: Tracer) -> None: ... +def is_global_tracer_registered() -> bool: ... diff --git a/stubs/opentracing/opentracing/ext/__init__.pyi b/stubs/opentracing/opentracing/ext/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/opentracing/opentracing/ext/tags.pyi b/stubs/opentracing/opentracing/ext/tags.pyi new file mode 100644 index 000000000000..08687e50927d --- /dev/null +++ b/stubs/opentracing/opentracing/ext/tags.pyi @@ -0,0 +1 @@ +from ..tags import * diff --git a/stubs/opentracing/opentracing/harness/__init__.pyi b/stubs/opentracing/opentracing/harness/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/opentracing/opentracing/harness/api_check.pyi b/stubs/opentracing/opentracing/harness/api_check.pyi new file mode 100644 index 000000000000..dcc9734872f0 --- /dev/null +++ b/stubs/opentracing/opentracing/harness/api_check.pyi @@ -0,0 +1,34 @@ +from opentracing.span import Span + +from ..tracer import Tracer + +class APICompatibilityCheckMixin: + def tracer(self) -> Tracer: ... + def check_baggage_values(self) -> bool: ... + def check_scope_manager(self) -> bool: ... + def is_parent(self, parent: Span, span: Span) -> bool: ... + def test_active_span(self) -> None: ... + def test_start_active_span(self) -> None: ... + def test_start_active_span_parent(self) -> None: ... + def test_start_active_span_ignore_active_span(self) -> None: ... + def test_start_active_span_not_finish_on_close(self) -> None: ... + def test_start_active_span_finish_on_close(self) -> None: ... + def test_start_active_span_default_finish_on_close(self) -> None: ... + def test_start_span(self) -> None: ... + def test_start_span_propagation(self) -> None: ... + def test_start_span_propagation_ignore_active_span(self) -> None: ... + def test_start_span_with_parent(self) -> None: ... + def test_start_child_span(self) -> None: ... + def test_set_operation_name(self) -> None: ... + def test_span_as_context_manager(self) -> None: ... + def test_span_tag_value_types(self) -> None: ... + def test_span_tags_with_chaining(self) -> None: ... + def test_span_logs(self) -> None: ... + def test_span_baggage(self) -> None: ... + def test_context_baggage(self) -> None: ... + def test_text_propagation(self) -> None: ... + def test_binary_propagation(self) -> None: ... + def test_mandatory_formats(self) -> None: ... + def test_unknown_format(self) -> None: ... + def test_tracer_start_active_span_scope(self) -> None: ... + def test_tracer_start_span_scope(self) -> None: ... diff --git a/stubs/opentracing/opentracing/harness/scope_check.pyi b/stubs/opentracing/opentracing/harness/scope_check.pyi new file mode 100644 index 000000000000..10b5ce11d39e --- /dev/null +++ b/stubs/opentracing/opentracing/harness/scope_check.pyi @@ -0,0 +1,15 @@ +from collections.abc import Callable + +from ..scope_manager import ScopeManager + +class ScopeCompatibilityCheckMixin: + def scope_manager(self) -> ScopeManager: ... + def run_test(self, test_fn: Callable[[], object]) -> None: ... + def test_missing_active_external(self) -> None: ... + def test_missing_active(self) -> None: ... + def test_activate(self) -> None: ... + def test_activate_external(self) -> None: ... + def test_activate_finish_on_close(self) -> None: ... + def test_activate_nested(self) -> None: ... + def test_activate_finish_on_close_nested(self) -> None: ... + def test_close_wrong_order(self) -> None: ... diff --git a/stubs/opentracing/opentracing/logs.pyi b/stubs/opentracing/opentracing/logs.pyi new file mode 100644 index 000000000000..8aa6c11f3e89 --- /dev/null +++ b/stubs/opentracing/opentracing/logs.pyi @@ -0,0 +1,7 @@ +from typing import Final + +ERROR_KIND: Final = "error.kind" +ERROR_OBJECT: Final = "error.object" +EVENT: Final = "event" +MESSAGE: Final = "message" +STACK: Final = "stack" diff --git a/stubs/opentracing/opentracing/mocktracer/__init__.pyi b/stubs/opentracing/opentracing/mocktracer/__init__.pyi new file mode 100644 index 000000000000..85fa2ac93862 --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/__init__.pyi @@ -0,0 +1,2 @@ +from .propagator import Propagator as Propagator +from .tracer import MockTracer as MockTracer diff --git a/stubs/opentracing/opentracing/mocktracer/binary_propagator.pyi b/stubs/opentracing/opentracing/mocktracer/binary_propagator.pyi new file mode 100644 index 000000000000..33f94f4b7801 --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/binary_propagator.pyi @@ -0,0 +1,8 @@ +from typing import Any + +from .context import SpanContext +from .propagator import Propagator + +class BinaryPropagator(Propagator): + def inject(self, span_context: SpanContext, carrier: dict[Any, Any]) -> None: ... + def extract(self, carrier: dict[Any, Any]) -> SpanContext: ... diff --git a/stubs/opentracing/opentracing/mocktracer/context.pyi b/stubs/opentracing/opentracing/mocktracer/context.pyi new file mode 100644 index 000000000000..09022377e728 --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/context.pyi @@ -0,0 +1,13 @@ +from typing_extensions import Self + +import opentracing + +class SpanContext(opentracing.SpanContext): + trace_id: int | None + span_id: int | None + def __init__( + self, trace_id: int | None = None, span_id: int | None = None, baggage: dict[str, str] | None = None + ) -> None: ... + @property + def baggage(self) -> dict[str, str]: ... + def with_baggage_item(self, key: str, value: str) -> Self: ... diff --git a/stubs/opentracing/opentracing/mocktracer/propagator.pyi b/stubs/opentracing/opentracing/mocktracer/propagator.pyi new file mode 100644 index 000000000000..0a2ffb446a3d --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/propagator.pyi @@ -0,0 +1,7 @@ +from typing import Any + +from .context import SpanContext + +class Propagator: + def inject(self, span_context: SpanContext, carrier: dict[Any, Any]) -> None: ... + def extract(self, carrier: dict[Any, Any]) -> SpanContext: ... diff --git a/stubs/opentracing/opentracing/mocktracer/span.pyi b/stubs/opentracing/opentracing/mocktracer/span.pyi new file mode 100644 index 000000000000..229af11b8e16 --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/span.pyi @@ -0,0 +1,38 @@ +from typing import Any +from typing_extensions import Self + +from ..span import Span +from ..tracer import Tracer +from .context import SpanContext +from .tracer import MockTracer + +class MockSpan(Span): + operation_name: str | None + start_time: Any + parent_id: int | None + tags: dict[str, Any] + finish_time: float + finished: bool + logs: list[LogData] + def __init__( + self, + tracer: Tracer, + operation_name: str | None = None, + context: SpanContext | None = None, + parent_id: int | None = None, + tags: dict[str, Any] | None = None, + start_time: float | None = None, + ) -> None: ... + @property + def tracer(self) -> MockTracer: ... + @property + def context(self) -> SpanContext: ... + def set_operation_name(self, operation_name: str) -> Self: ... + def set_tag(self, key: str, value: str | bool | float) -> Self: ... + def log_kv(self, key_values: dict[str, Any], timestamp: float | None = None) -> Self: ... + def set_baggage_item(self, key: str, value: str) -> Self: ... + +class LogData: + key_values: dict[str, Any] + timestamp: float | None + def __init__(self, key_values: dict[str, Any], timestamp: float | None = None) -> None: ... diff --git a/stubs/opentracing/opentracing/mocktracer/text_propagator.pyi b/stubs/opentracing/opentracing/mocktracer/text_propagator.pyi new file mode 100644 index 000000000000..d828fe2f99ec --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/text_propagator.pyi @@ -0,0 +1,14 @@ +from typing import Any + +from .context import SpanContext +from .propagator import Propagator + +prefix_tracer_state: str +prefix_baggage: str +field_name_trace_id: str +field_name_span_id: str +field_count: int + +class TextPropagator(Propagator): + def inject(self, span_context: SpanContext, carrier: dict[Any, Any]) -> None: ... + def extract(self, carrier: dict[Any, Any]) -> SpanContext: ... diff --git a/stubs/opentracing/opentracing/mocktracer/tracer.pyi b/stubs/opentracing/opentracing/mocktracer/tracer.pyi new file mode 100644 index 000000000000..46d12c48fb90 --- /dev/null +++ b/stubs/opentracing/opentracing/mocktracer/tracer.pyi @@ -0,0 +1,26 @@ +from typing import Any + +from ..scope_manager import ScopeManager +from ..span import Span +from ..tracer import Reference, Tracer +from .context import SpanContext +from .propagator import Propagator +from .span import MockSpan + +class MockTracer(Tracer): + def __init__(self, scope_manager: ScopeManager | None = None) -> None: ... + @property + def active_span(self) -> MockSpan | None: ... + def register_propagator(self, format: str, propagator: Propagator) -> None: ... + def finished_spans(self) -> list[MockSpan]: ... + def reset(self) -> None: ... + def start_span( # type: ignore[override] + self, + operation_name: str | None = None, + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, + ) -> MockSpan: ... + def extract(self, format: str, carrier: dict[Any, Any]) -> SpanContext: ... diff --git a/stubs/opentracing/opentracing/propagation.pyi b/stubs/opentracing/opentracing/propagation.pyi new file mode 100644 index 000000000000..3c9607b8f405 --- /dev/null +++ b/stubs/opentracing/opentracing/propagation.pyi @@ -0,0 +1,10 @@ +from typing import Final + +class UnsupportedFormatException(Exception): ... +class InvalidCarrierException(Exception): ... +class SpanContextCorruptedException(Exception): ... + +class Format: + BINARY: Final = "binary" + TEXT_MAP: Final = "text_map" + HTTP_HEADERS: Final = "http_headers" diff --git a/stubs/opentracing/opentracing/scope.pyi b/stubs/opentracing/opentracing/scope.pyi new file mode 100644 index 000000000000..e312df143498 --- /dev/null +++ b/stubs/opentracing/opentracing/scope.pyi @@ -0,0 +1,17 @@ +from types import TracebackType +from typing_extensions import Self + +from .scope_manager import ScopeManager +from .span import Span + +class Scope: + def __init__(self, manager: ScopeManager, span: Span) -> None: ... + @property + def span(self) -> Span: ... + @property + def manager(self) -> ScopeManager: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... diff --git a/stubs/opentracing/opentracing/scope_manager.pyi b/stubs/opentracing/opentracing/scope_manager.pyi new file mode 100644 index 000000000000..cd07475479a2 --- /dev/null +++ b/stubs/opentracing/opentracing/scope_manager.pyi @@ -0,0 +1,8 @@ +from .scope import Scope +from .span import Span + +class ScopeManager: + def __init__(self) -> None: ... + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope | None: ... diff --git a/stubs/opentracing/opentracing/scope_managers/__init__.pyi b/stubs/opentracing/opentracing/scope_managers/__init__.pyi new file mode 100644 index 000000000000..2b0f720c3ad9 --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/__init__.pyi @@ -0,0 +1,9 @@ +from ..scope import Scope +from ..scope_manager import ScopeManager +from ..span import Span + +class ThreadLocalScopeManager(ScopeManager): + def __init__(self) -> None: ... + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope: ... diff --git a/stubs/opentracing/opentracing/scope_managers/asyncio.pyi b/stubs/opentracing/opentracing/scope_managers/asyncio.pyi new file mode 100644 index 000000000000..4b96d7883fda --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/asyncio.pyi @@ -0,0 +1,8 @@ +from ..scope import Scope +from ..scope_managers import ThreadLocalScopeManager +from ..span import Span + +class AsyncioScopeManager(ThreadLocalScopeManager): + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope: ... diff --git a/stubs/opentracing/opentracing/scope_managers/constants.pyi b/stubs/opentracing/opentracing/scope_managers/constants.pyi new file mode 100644 index 000000000000..0a791982f11a --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/constants.pyi @@ -0,0 +1 @@ +ACTIVE_ATTR: str diff --git a/stubs/opentracing/opentracing/scope_managers/contextvars.pyi b/stubs/opentracing/opentracing/scope_managers/contextvars.pyi new file mode 100644 index 000000000000..990045ee4c56 --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/contextvars.pyi @@ -0,0 +1,10 @@ +from ..scope import Scope +from ..scope_manager import ScopeManager +from ..span import Span + +class ContextVarsScopeManager(ScopeManager): + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope: ... + +def no_parent_scope() -> None: ... diff --git a/stubs/opentracing/opentracing/scope_managers/gevent.pyi b/stubs/opentracing/opentracing/scope_managers/gevent.pyi new file mode 100644 index 000000000000..6b835cd9787d --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/gevent.pyi @@ -0,0 +1,8 @@ +from ..scope import Scope +from ..scope_manager import ScopeManager +from ..span import Span + +class GeventScopeManager(ScopeManager): + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope: ... diff --git a/stubs/opentracing/opentracing/scope_managers/tornado.pyi b/stubs/opentracing/opentracing/scope_managers/tornado.pyi new file mode 100644 index 000000000000..59b1cab9cf50 --- /dev/null +++ b/stubs/opentracing/opentracing/scope_managers/tornado.pyi @@ -0,0 +1,16 @@ +from typing import Any + +from ..scope import Scope +from ..scope_managers import ThreadLocalScopeManager +from ..span import Span + +class TornadoScopeManager(ThreadLocalScopeManager): + def activate(self, span: Span, finish_on_close: bool) -> Scope: ... + @property + def active(self) -> Scope: ... + +class ThreadSafeStackContext: + contexts: Any + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +def tracer_stack_context() -> ThreadSafeStackContext: ... diff --git a/stubs/opentracing/opentracing/span.pyi b/stubs/opentracing/opentracing/span.pyi new file mode 100644 index 000000000000..dd9bff361ef7 --- /dev/null +++ b/stubs/opentracing/opentracing/span.pyi @@ -0,0 +1,29 @@ +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from .tracer import Tracer + +class SpanContext: + EMPTY_BAGGAGE: dict[str, str] + @property + def baggage(self) -> dict[str, str]: ... + +class Span: + def __init__(self, tracer: Tracer, context: SpanContext) -> None: ... + @property + def context(self) -> SpanContext: ... + @property + def tracer(self) -> Tracer: ... + def set_operation_name(self, operation_name: str) -> Self: ... + def finish(self, finish_time: float | None = None) -> None: ... + def set_tag(self, key: str, value: str | bool | float) -> Self: ... + def log_kv(self, key_values: dict[str, Any], timestamp: float | None = None) -> Self: ... + def set_baggage_item(self, key: str, value: str) -> Self: ... + def get_baggage_item(self, key: str) -> str | None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def log_event(self, event: Any, payload=None) -> Self: ... + def log(self, **kwargs: Any) -> Self: ... diff --git a/stubs/opentracing/opentracing/tags.pyi b/stubs/opentracing/opentracing/tags.pyi new file mode 100644 index 000000000000..c48c210be0cd --- /dev/null +++ b/stubs/opentracing/opentracing/tags.pyi @@ -0,0 +1,23 @@ +SPAN_KIND: str +SPAN_KIND_RPC_CLIENT: str +SPAN_KIND_RPC_SERVER: str +SPAN_KIND_CONSUMER: str +SPAN_KIND_PRODUCER: str +SERVICE: str +ERROR: str +COMPONENT: str +SAMPLING_PRIORITY: str +PEER_SERVICE: str +PEER_HOSTNAME: str +PEER_ADDRESS: str +PEER_HOST_IPV4: str +PEER_HOST_IPV6: str +PEER_PORT: str +HTTP_URL: str +HTTP_METHOD: str +HTTP_STATUS_CODE: str +DATABASE_INSTANCE: str +DATABASE_STATEMENT: str +DATABASE_TYPE: str +DATABASE_USER: str +MESSAGE_BUS_DESTINATION: str diff --git a/stubs/opentracing/opentracing/tracer.pyi b/stubs/opentracing/opentracing/tracer.pyi new file mode 100644 index 000000000000..275b9d7f682d --- /dev/null +++ b/stubs/opentracing/opentracing/tracer.pyi @@ -0,0 +1,47 @@ +from typing import Any, NamedTuple + +from .scope import Scope +from .scope_manager import ScopeManager +from .span import Span, SpanContext + +class Tracer: + def __init__(self, scope_manager: ScopeManager | None = None) -> None: ... + @property + def scope_manager(self) -> ScopeManager: ... + @property + def active_span(self) -> Span | None: ... + def start_active_span( + self, + operation_name: str, + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, + finish_on_close: bool = True, + ) -> Scope: ... + def start_span( + self, + operation_name: str | None = None, + child_of: Span | SpanContext | None = None, + references: list[Reference] | None = None, + tags: dict[Any, Any] | None = None, + start_time: float | None = None, + ignore_active_span: bool = False, + ) -> Span: ... + def inject(self, span_context: SpanContext, format: str, carrier: dict[Any, Any]) -> None: ... + def extract(self, format: str, carrier: dict[Any, Any]) -> SpanContext: ... + +class ReferenceType: + CHILD_OF: str + FOLLOWS_FROM: str + +class Reference(NamedTuple): + type: str + referenced_context: SpanContext | None + +def child_of(referenced_context: SpanContext | None = None) -> Reference: ... +def follows_from(referenced_context: SpanContext | None = None) -> Reference: ... +def start_child_span( + parent_span: Span, operation_name: str, tags: dict[Any, Any] | None = None, start_time: float | None = None +) -> Span: ... diff --git a/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt b/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..c510f2c7e366 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +paramiko._winapi +paramiko.win_openssh.* +paramiko.win_pageant diff --git a/stubs/paramiko/@tests/stubtest_allowlist_linux.txt b/stubs/paramiko/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..c510f2c7e366 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +paramiko._winapi +paramiko.win_openssh.* +paramiko.win_pageant diff --git a/stubs/paramiko/@tests/stubtest_allowlist_win32.txt b/stubs/paramiko/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..51664f850f12 --- /dev/null +++ b/stubs/paramiko/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,2 @@ +# Type-checkers don't support architecture checks. So we have to Union +paramiko.win_pageant.ULONG_PTR diff --git a/stubs/paramiko/METADATA.toml b/stubs/paramiko/METADATA.toml new file mode 100644 index 000000000000..3cde7708908c --- /dev/null +++ b/stubs/paramiko/METADATA.toml @@ -0,0 +1,8 @@ +version = "5.0.*" +upstream-repository = "https://github.com/paramiko/paramiko" +# Requires a version of cryptography where cryptography.hazmat.primitives.ciphers.Cipher is generic +dependencies = ["cryptography>=37.0.0"] + +[tool.stubtest] +# linux and darwin are equivalent +ci-platforms = ["linux", "win32"] diff --git a/stubs/paramiko/paramiko/__init__.pyi b/stubs/paramiko/paramiko/__init__.pyi new file mode 100644 index 000000000000..648141acf7eb --- /dev/null +++ b/stubs/paramiko/paramiko/__init__.pyi @@ -0,0 +1,47 @@ +from typing import Final + +from paramiko import util as util +from paramiko.agent import Agent as Agent, AgentKey as AgentKey +from paramiko.channel import Channel as Channel, ChannelFile as ChannelFile +from paramiko.client import ( + AutoAddPolicy as AutoAddPolicy, + MissingHostKeyPolicy as MissingHostKeyPolicy, + RejectPolicy as RejectPolicy, + SSHClient as SSHClient, + WarningPolicy as WarningPolicy, +) +from paramiko.common import io_sleep as io_sleep +from paramiko.config import SSHConfig as SSHConfig, SSHConfigDict as SSHConfigDict +from paramiko.ecdsakey import ECDSAKey as ECDSAKey +from paramiko.ed25519key import Ed25519Key as Ed25519Key +from paramiko.file import BufferedFile as BufferedFile +from paramiko.hostkeys import HostKeys as HostKeys +from paramiko.message import Message as Message +from paramiko.pkey import PKey as PKey +from paramiko.proxy import ProxyCommand as ProxyCommand +from paramiko.rsakey import RSAKey as RSAKey +from paramiko.server import ServerInterface as ServerInterface, SubsystemHandler as SubsystemHandler +from paramiko.sftp import SFTPError as SFTPError +from paramiko.sftp_attr import SFTPAttributes as SFTPAttributes +from paramiko.sftp_client import SFTP as SFTP, SFTPClient as SFTPClient +from paramiko.sftp_file import SFTPFile as SFTPFile +from paramiko.sftp_handle import SFTPHandle as SFTPHandle +from paramiko.sftp_server import SFTPServer as SFTPServer +from paramiko.sftp_si import SFTPServerInterface as SFTPServerInterface +from paramiko.ssh_exception import ( + AuthenticationException as AuthenticationException, + BadAuthenticationType as BadAuthenticationType, + BadHostKeyException as BadHostKeyException, + ChannelException as ChannelException, + ConfigParseError as ConfigParseError, + CouldNotCanonicalize as CouldNotCanonicalize, + PasswordRequiredException as PasswordRequiredException, + ProxyCommandFailure as ProxyCommandFailure, + SSHException as SSHException, +) +from paramiko.transport import SecurityOptions as SecurityOptions, Transport as Transport + +__version__: Final[str] +__author__: Final[str] +__license__: Final[str] +key_classes: list[type[PKey]] diff --git a/stubs/paramiko/paramiko/_winapi.pyi b/stubs/paramiko/paramiko/_winapi.pyi new file mode 100644 index 000000000000..0e3fc8a81869 --- /dev/null +++ b/stubs/paramiko/paramiko/_winapi.pyi @@ -0,0 +1,105 @@ +import builtins +import ctypes +import sys +from _typeshed import Incomplete +from types import TracebackType +from typing_extensions import Self + +if sys.platform == "win32": + def format_system_message(errno: int) -> str | None: ... + + class WindowsError(builtins.WindowsError): + def __init__(self, value: int | None = None) -> None: ... + @property + def message(self) -> str: ... + @property + def code(self) -> int: ... + + def handle_nonzero_success(result: int) -> None: ... + GMEM_MOVEABLE: int + GlobalAlloc: Incomplete + GlobalLock: Incomplete + GlobalUnlock: Incomplete + GlobalSize: Incomplete + CreateFileMapping: Incomplete + MapViewOfFile: Incomplete + UnmapViewOfFile: Incomplete + RtlMoveMemory: Incomplete + + class MemoryMap: + name: str + length: int + security_attributes: Incomplete | None + pos: int + filemap: Incomplete + view: Incomplete + def __init__(self, name: str, length: int, security_attributes=None) -> None: ... + def __enter__(self) -> Self: ... + def seek(self, pos: int) -> None: ... + def write(self, msg: bytes) -> None: ... + def read(self, n: int) -> bytes: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, tb: TracebackType | None + ) -> None: ... + + READ_CONTROL: int + STANDARD_RIGHTS_REQUIRED: int + STANDARD_RIGHTS_READ: int + STANDARD_RIGHTS_WRITE: int + STANDARD_RIGHTS_EXECUTE: int + STANDARD_RIGHTS_ALL: int + POLICY_VIEW_LOCAL_INFORMATION: int + POLICY_VIEW_AUDIT_INFORMATION: int + POLICY_GET_PRIVATE_INFORMATION: int + POLICY_TRUST_ADMIN: int + POLICY_CREATE_ACCOUNT: int + POLICY_CREATE_SECRET: int + POLICY_CREATE_PRIVILEGE: int + POLICY_SET_DEFAULT_QUOTA_LIMITS: int + POLICY_SET_AUDIT_REQUIREMENTS: int + POLICY_AUDIT_LOG_ADMIN: int + POLICY_SERVER_ADMIN: int + POLICY_LOOKUP_NAMES: int + POLICY_NOTIFICATION: int + POLICY_ALL_ACCESS: int + POLICY_READ: int + POLICY_WRITE: int + POLICY_EXECUTE: int + + class TokenAccess: + TOKEN_QUERY: int + + class TokenInformationClass: + TokenUser: int + + class TOKEN_USER(ctypes.Structure): + num: int + SID: Incomplete + ATTRIBUTES: Incomplete + + class SECURITY_DESCRIPTOR(ctypes.Structure): + SECURITY_DESCRIPTOR_CONTROL: Incomplete + REVISION: int + Revision: int + Sbz1: Incomplete + Control: Incomplete + Owner: Incomplete + Group: Incomplete + Sacl: Incomplete + Dacl: Incomplete + + class SECURITY_ATTRIBUTES(ctypes.Structure): + nLength: int + lpSecurityDescriptor: int + bInheritHandle: bool + def __init__(self, *args, **kwargs) -> None: ... + + @property + def descriptor(self): ... + @descriptor.setter + def descriptor(self, value) -> None: ... + + def GetTokenInformation(token, information_class): ... + def OpenProcessToken(proc_handle, access): ... + def get_current_user() -> TOKEN_USER: ... + def get_security_attributes_for_user(user: TOKEN_USER | None = None) -> SECURITY_ATTRIBUTES: ... diff --git a/stubs/paramiko/paramiko/agent.pyi b/stubs/paramiko/paramiko/agent.pyi new file mode 100644 index 000000000000..16621e9fa5d2 --- /dev/null +++ b/stubs/paramiko/paramiko/agent.pyi @@ -0,0 +1,98 @@ +import sys +from _typeshed import ReadableBuffer +from collections.abc import Mapping +from logging import _ExcInfoType +from socket import _RetAddress, socket +from threading import Thread +from typing import Final, Protocol, type_check_only + +from paramiko.channel import Channel +from paramiko.message import Message, _LikeBytes +from paramiko.pkey import PKey +from paramiko.transport import Transport + +@type_check_only +class _AgentProxy(Protocol): + def connect(self) -> None: ... + def close(self) -> None: ... + +cSSH2_AGENTC_REQUEST_IDENTITIES: Final[bytes] +SSH2_AGENT_IDENTITIES_ANSWER: Final = 12 +cSSH2_AGENTC_SIGN_REQUEST: Final[bytes] +SSH2_AGENT_SIGN_RESPONSE: Final = 14 + +SSH_AGENT_RSA_SHA2_256: Final = 2 +SSH_AGENT_RSA_SHA2_512: Final = 4 +ALGORITHM_FLAG_MAP: Final[dict[str, int]] +key: str +value: int + +class AgentSSH: + def __init__(self) -> None: ... + def get_keys(self) -> tuple[AgentKey, ...]: ... + +class AgentProxyThread(Thread): + def __init__(self, agent: _AgentProxy) -> None: ... + def run(self) -> None: ... + +class AgentLocalProxy(AgentProxyThread): + def __init__(self, agent: AgentServerProxy) -> None: ... + def get_connection(self) -> tuple[socket, _RetAddress]: ... + +class AgentRemoteProxy(AgentProxyThread): + def __init__(self, agent: AgentClientProxy, chan: Channel) -> None: ... + def get_connection(self) -> tuple[socket, _RetAddress]: ... + +if sys.platform == "win32": + from .win_openssh import OpenSSHAgentConnection + from .win_pageant import PageantConnection + + def get_agent_connection() -> PageantConnection | OpenSSHAgentConnection | None: ... + +else: + def get_agent_connection() -> socket | None: ... + +class AgentClientProxy: + thread: Thread + def __init__(self, chanRemote: Channel) -> None: ... + def __del__(self) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + +class AgentServerProxy(AgentSSH): + thread: Thread + def __init__(self, t: Transport) -> None: ... + def __del__(self) -> None: ... + def connect(self) -> None: ... + def close(self) -> None: ... + def get_env(self) -> dict[str, str]: ... + +class AgentRequestHandler: + def __init__(self, chanClient: Channel) -> None: ... + def __del__(self) -> None: ... + def close(self) -> None: ... + +class Agent(AgentSSH): + def __init__(self) -> None: ... + def close(self) -> None: ... + +class AgentKey(PKey): + agent: AgentSSH + blob: bytes + public_blob: None + name: str + comment: str + def __init__(self, agent: AgentSSH, blob: ReadableBuffer, comment: str = "") -> None: ... + def log( + self, + level: int, + msg: object, + *args: object, + exc_info: _ExcInfoType = None, + stack_info: bool = False, + stacklevel: int = 1, + extra: Mapping[str, object] | None = None, + ) -> None: ... + def asbytes(self) -> bytes: ... + def get_name(self) -> str: ... + def sign_ssh_data(self, data: _LikeBytes, algorithm: str | None = None) -> Message: ... diff --git a/stubs/paramiko/paramiko/auth_handler.pyi b/stubs/paramiko/paramiko/auth_handler.pyi new file mode 100644 index 000000000000..2f6d67a94ad1 --- /dev/null +++ b/stubs/paramiko/paramiko/auth_handler.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable +from threading import Event +from typing import TypeAlias + +from paramiko.message import Message +from paramiko.pkey import PKey +from paramiko.transport import Transport + +_InteractiveCallback: TypeAlias = Callable[[str, str, list[tuple[str, bool]]], list[str]] + +class AuthHandler: + transport: Transport + username: str | None + authenticated: bool + auth_event: Event | None + auth_method: str + banner: str | None + password: str | None + private_key: PKey | None + interactive_handler: _InteractiveCallback | None + submethods: str | None + auth_username: str | None + auth_fail_count: int + gss_host: str | None + gss_deleg_creds: bool + def __init__(self, transport: Transport) -> None: ... + def is_authenticated(self) -> bool: ... + def get_username(self) -> str | None: ... + def auth_none(self, username: str, event: Event) -> None: ... + def auth_publickey(self, username: str, key: PKey, event: Event) -> None: ... + def auth_password(self, username: str, password: str, event: Event) -> None: ... + def auth_interactive(self, username: str, handler: _InteractiveCallback, event: Event, submethods: str = "") -> None: ... + def abort(self) -> None: ... + def wait_for_response(self, event: Event) -> list[str]: ... + +class AuthOnlyHandler(AuthHandler): + def send_auth_request( + self, username: str, method: str, finish_message: Callable[[Message], None] | None = None + ) -> list[str]: ... + def auth_none(self, username: str) -> list[str]: ... # type: ignore[override] + def auth_publickey(self, username: str, key: PKey) -> list[str]: ... # type: ignore[override] + def auth_password(self, username: str, password: str) -> list[str]: ... # type: ignore[override] + def auth_interactive(self, username: str, handler: _InteractiveCallback, submethods: str = "") -> list[str]: ... # type: ignore[override] diff --git a/stubs/paramiko/paramiko/auth_strategy.pyi b/stubs/paramiko/paramiko/auth_strategy.pyi new file mode 100644 index 000000000000..707dd0f3d964 --- /dev/null +++ b/stubs/paramiko/paramiko/auth_strategy.pyi @@ -0,0 +1,57 @@ +import abc +from collections.abc import Callable, Iterator +from logging import Logger +from pathlib import Path +from typing import NamedTuple + +from paramiko.config import SSHConfig +from paramiko.pkey import PKey +from paramiko.ssh_exception import AuthenticationException +from paramiko.transport import Transport + +class AuthSource: + username: str + def __init__(self, username: str) -> None: ... + @abc.abstractmethod + def authenticate(self, transport: Transport) -> list[str]: ... + +class NoneAuth(AuthSource): + def authenticate(self, transport: Transport) -> list[str]: ... + +class Password(AuthSource): + password_getter: Callable[[], str] + def __init__(self, username: str, password_getter: Callable[[], str]) -> None: ... + def authenticate(self, transport: Transport) -> list[str]: ... + +class PrivateKey(AuthSource): + def authenticate(self, transport: Transport) -> list[str]: ... + +class InMemoryPrivateKey(PrivateKey): + pkey: PKey + def __init__(self, username: str, pkey: PKey) -> None: ... + +class OnDiskPrivateKey(PrivateKey): + source: str + path: Path + pkey: PKey + def __init__(self, username: str, source: str, path: Path, pkey: PKey) -> None: ... + +class SourceResult(NamedTuple): + source: AuthSource + result: list[str] | Exception + +class AuthResult(list[SourceResult]): + strategy: AuthStrategy + def __init__(self, strategy: AuthStrategy, *args: SourceResult, **kwargs: object) -> None: ... + +class AuthFailure(AuthenticationException): + result: AuthResult + def __init__(self, result: AuthResult) -> None: ... + +class AuthStrategy: + ssh_config: SSHConfig + log: Logger + def __init__(self, ssh_config: SSHConfig) -> None: ... + @abc.abstractmethod + def get_sources(self) -> Iterator[AuthSource]: ... + def authenticate(self, transport: Transport) -> list[SourceResult]: ... diff --git a/stubs/paramiko/paramiko/ber.pyi b/stubs/paramiko/paramiko/ber.pyi new file mode 100644 index 000000000000..d847e528a11a --- /dev/null +++ b/stubs/paramiko/paramiko/ber.pyi @@ -0,0 +1,18 @@ +from collections.abc import Iterable +from typing import Any + +class BERException(Exception): ... + +class BER: + content: bytes + idx: int + def __init__(self, content: bytes = b"") -> None: ... + def asbytes(self) -> bytes: ... + def decode(self) -> None | int | list[int]: ... + def decode_next(self) -> None | int | list[int]: ... + @staticmethod + def decode_sequence(data: bytes) -> list[int | list[int]]: ... + def encode_tlv(self, ident: int, val: bytes) -> None: ... + def encode(self, x: Any) -> None: ... + @staticmethod + def encode_sequence(data: Iterable[str]) -> bytes: ... diff --git a/stubs/paramiko/paramiko/buffered_pipe.pyi b/stubs/paramiko/paramiko/buffered_pipe.pyi new file mode 100644 index 000000000000..558df9d30549 --- /dev/null +++ b/stubs/paramiko/paramiko/buffered_pipe.pyi @@ -0,0 +1,14 @@ +from threading import Event +from typing import AnyStr, Generic + +class PipeTimeout(OSError): ... + +class BufferedPipe(Generic[AnyStr]): + def __init__(self) -> None: ... + def set_event(self, event: Event) -> None: ... + def feed(self, data: AnyStr) -> None: ... + def read_ready(self) -> bool: ... + def read(self, nbytes: int, timeout: float | None = None) -> AnyStr: ... + def empty(self) -> AnyStr: ... + def close(self) -> None: ... + def __len__(self) -> int: ... diff --git a/stubs/paramiko/paramiko/channel.pyi b/stubs/paramiko/paramiko/channel.pyi new file mode 100644 index 000000000000..0d8482db0556 --- /dev/null +++ b/stubs/paramiko/paramiko/channel.pyi @@ -0,0 +1,101 @@ +from _typeshed import SupportsItems +from collections.abc import Callable +from logging import Logger +from threading import Condition, Event, Lock +from typing import Any, Literal, TypeVar + +from paramiko.buffered_pipe import BufferedPipe +from paramiko.file import BufferedFile +from paramiko.message import _LikeBytes +from paramiko.transport import Transport +from paramiko.util import ClosingContextManager + +_F = TypeVar("_F", bound=Callable[..., Any]) + +def open_only(func: _F) -> Callable[[_F], _F]: ... + +class Channel(ClosingContextManager): + chanid: int + remote_chanid: int + transport: Transport | None + active: bool + eof_received: int + eof_sent: int + in_buffer: BufferedPipe[Any] + in_stderr_buffer: BufferedPipe[Any] + timeout: float | None + closed: bool + ultra_debug: bool + lock: Lock + out_buffer_cv: Condition + in_window_size: int + out_window_size: int + in_max_packet_size: int + out_max_packet_size: int + in_window_threshold: int + in_window_sofar: int + status_event: Event + logger: Logger + event: Event + event_ready: bool + combine_stderr: bool + exit_status: int + origin_addr: None + def __init__(self, chanid: int) -> None: ... + def __del__(self) -> None: ... + def get_pty( + self, term: _LikeBytes = "vt100", width: int = 80, height: int = 24, width_pixels: int = 0, height_pixels: int = 0 + ) -> None: ... + def invoke_shell(self) -> None: ... + def exec_command(self, command: _LikeBytes) -> None: ... + def invoke_subsystem(self, subsystem: _LikeBytes) -> None: ... + def resize_pty(self, width: int = 80, height: int = 24, width_pixels: int = 0, height_pixels: int = 0) -> None: ... + def update_environment(self, environment: SupportsItems[_LikeBytes, _LikeBytes]) -> None: ... + def set_environment_variable(self, name: _LikeBytes, value: _LikeBytes) -> None: ... + def exit_status_ready(self) -> bool: ... + def recv_exit_status(self) -> int: ... + def send_exit_status(self, status: int) -> None: ... + def request_x11( + self, + screen_number: int = 0, + auth_protocol: _LikeBytes | None = None, + auth_cookie: _LikeBytes | None = None, + single_connection: bool = False, + handler: Callable[[Channel, tuple[str, int]], object] | None = None, + ) -> bytes: ... + def request_forward_agent(self, handler: Callable[[Channel], object]) -> bool: ... + def get_transport(self) -> Transport: ... + def set_name(self, name: str) -> None: ... + def get_name(self) -> str: ... + def get_id(self) -> int: ... + def set_combine_stderr(self, combine: bool) -> bool: ... + def settimeout(self, timeout: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, blocking: bool | Literal[0, 1]) -> None: ... + def getpeername(self) -> str: ... + def close(self) -> None: ... + def recv_ready(self) -> bool: ... + def recv(self, nbytes: int) -> bytes: ... + def recv_stderr_ready(self) -> bool: ... + def recv_stderr(self, nbytes: int) -> bytes: ... + def send_ready(self) -> bool: ... + def send(self, s: bytes | bytearray) -> int: ... + def send_stderr(self, s: bytes | bytearray) -> int: ... + def sendall(self, s: bytes | bytearray) -> None: ... + def sendall_stderr(self, s: bytes | bytearray) -> None: ... + def makefile(self, *params: Any) -> ChannelFile: ... + def makefile_stderr(self, *params: Any) -> ChannelStderrFile: ... + def makefile_stdin(self, *params: Any) -> ChannelStdinFile: ... + def fileno(self) -> int: ... + def shutdown(self, how: int) -> None: ... + def shutdown_read(self) -> None: ... + def shutdown_write(self) -> None: ... + +class ChannelFile(BufferedFile[Any]): + channel: Channel + def __init__(self, channel: Channel, mode: str = "r", bufsize: int = -1) -> None: ... + +class ChannelStderrFile(ChannelFile): ... + +class ChannelStdinFile(ChannelFile): + def close(self) -> None: ... diff --git a/stubs/paramiko/paramiko/client.pyi b/stubs/paramiko/paramiko/client.pyi new file mode 100644 index 000000000000..b020f823fa83 --- /dev/null +++ b/stubs/paramiko/paramiko/client.pyi @@ -0,0 +1,86 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable, Mapping +from typing import Protocol, type_check_only +from typing_extensions import Never + +from paramiko.auth_strategy import AuthStrategy +from paramiko.channel import Channel, ChannelFile, ChannelStderrFile, ChannelStdinFile +from paramiko.hostkeys import HostKeys +from paramiko.pkey import PKey +from paramiko.sftp_client import SFTPClient +from paramiko.transport import Transport, _SocketLike +from paramiko.util import ClosingContextManager + +@type_check_only +class _TransportFactory(Protocol): + def __call__( + self, + sock: _SocketLike, + /, + *, + gss_kex: bool, + gss_deleg_creds: bool, + disabled_algorithms: Mapping[str, Iterable[str]] | None, + ) -> Transport: ... + +class SSHClient(ClosingContextManager): + def __init__(self) -> None: ... + def load_system_host_keys(self, filename: FileDescriptorOrPath | None = None) -> None: ... + def load_host_keys(self, filename: FileDescriptorOrPath) -> None: ... + def save_host_keys(self, filename: FileDescriptorOrPath) -> None: ... + def get_host_keys(self) -> HostKeys: ... + def set_log_channel(self, name: str) -> None: ... + def set_missing_host_key_policy(self, policy: type[MissingHostKeyPolicy] | MissingHostKeyPolicy) -> None: ... + def connect( + self, + hostname: str, + port: int = 22, + username: str | None = None, + password: str | None = None, + pkey: PKey | None = None, + key_filename: str | None = None, + timeout: float | None = None, + allow_agent: bool = True, + look_for_keys: bool = True, + compress: bool = False, + sock: _SocketLike | None = None, + banner_timeout: float | None = None, + auth_timeout: float | None = None, + channel_timeout: float | None = None, + passphrase: str | None = None, + disabled_algorithms: Mapping[str, Iterable[str]] | None = None, + transport_factory: _TransportFactory | None = None, + auth_strategy: AuthStrategy | None = None, + ) -> None: ... + def close(self) -> None: ... + def exec_command( + self, + command: str, + bufsize: int = -1, + timeout: float | None = None, + get_pty: bool = False, + environment: Mapping[str, str] | None = None, + ) -> tuple[ChannelStdinFile, ChannelFile, ChannelStderrFile]: ... + def invoke_shell( + self, + term: str = "vt100", + width: int = 80, + height: int = 24, + width_pixels: int = 0, + height_pixels: int = 0, + environment: Mapping[str, str] | None = None, + ) -> Channel: ... + def open_sftp(self) -> SFTPClient: ... + def get_transport(self) -> Transport | None: ... + +class MissingHostKeyPolicy: + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... + +class AutoAddPolicy(MissingHostKeyPolicy): + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... + +class RejectPolicy(MissingHostKeyPolicy): + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> Never: ... + +class WarningPolicy(MissingHostKeyPolicy): + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... diff --git a/stubs/paramiko/paramiko/common.pyi b/stubs/paramiko/paramiko/common.pyi new file mode 100644 index 000000000000..abe1a14e7fee --- /dev/null +++ b/stubs/paramiko/paramiko/common.pyi @@ -0,0 +1,133 @@ +import logging +from typing import Final + +def byte_ord(c: int | str) -> int: ... +def byte_chr(c: int) -> bytes: ... +def byte_mask(c: int, mask: int) -> bytes: ... + +MSG_DISCONNECT: Final = 1 +MSG_IGNORE: Final = 2 +MSG_UNIMPLEMENTED: Final = 3 +MSG_DEBUG: Final = 4 +MSG_SERVICE_REQUEST: Final = 5 +MSG_SERVICE_ACCEPT: Final = 6 +MSG_EXT_INFO: Final = 7 +MSG_KEXINIT: Final = 20 +MSG_NEWKEYS: Final = 21 +MSG_USERAUTH_REQUEST: Final = 50 +MSG_USERAUTH_FAILURE: Final = 51 +MSG_USERAUTH_SUCCESS: Final = 52 +MSG_USERAUTH_BANNER: Final = 53 +MSG_USERAUTH_PK_OK: Final = 60 +MSG_USERAUTH_INFO_REQUEST: Final = 60 +MSG_USERAUTH_INFO_RESPONSE: Final = 61 +MSG_USERAUTH_GSSAPI_RESPONSE: Final = 60 +MSG_USERAUTH_GSSAPI_TOKEN: Final = 61 +MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: Final = 63 +MSG_USERAUTH_GSSAPI_ERROR: Final = 64 +MSG_USERAUTH_GSSAPI_ERRTOK: Final = 65 +MSG_USERAUTH_GSSAPI_MIC: Final = 66 +HIGHEST_USERAUTH_MESSAGE_ID: Final = 79 +MSG_GLOBAL_REQUEST: Final = 80 +MSG_REQUEST_SUCCESS: Final = 81 +MSG_REQUEST_FAILURE: Final = 82 +MSG_CHANNEL_OPEN: Final = 90 +MSG_CHANNEL_OPEN_SUCCESS: Final = 91 +MSG_CHANNEL_OPEN_FAILURE: Final = 92 +MSG_CHANNEL_WINDOW_ADJUST: Final = 93 +MSG_CHANNEL_DATA: Final = 94 +MSG_CHANNEL_EXTENDED_DATA: Final = 95 +MSG_CHANNEL_EOF: Final = 96 +MSG_CHANNEL_CLOSE: Final = 97 +MSG_CHANNEL_REQUEST: Final = 98 +MSG_CHANNEL_SUCCESS: Final = 99 +MSG_CHANNEL_FAILURE: Final = 100 + +cMSG_DISCONNECT: Final[bytes] +cMSG_IGNORE: Final[bytes] +cMSG_UNIMPLEMENTED: Final[bytes] +cMSG_DEBUG: Final[bytes] +cMSG_SERVICE_REQUEST: Final[bytes] +cMSG_SERVICE_ACCEPT: Final[bytes] +cMSG_EXT_INFO: Final[bytes] +cMSG_KEXINIT: Final[bytes] +cMSG_NEWKEYS: Final[bytes] +cMSG_USERAUTH_REQUEST: Final[bytes] +cMSG_USERAUTH_FAILURE: Final[bytes] +cMSG_USERAUTH_SUCCESS: Final[bytes] +cMSG_USERAUTH_BANNER: Final[bytes] +cMSG_USERAUTH_PK_OK: Final[bytes] +cMSG_USERAUTH_INFO_REQUEST: Final[bytes] +cMSG_USERAUTH_INFO_RESPONSE: Final[bytes] +cMSG_USERAUTH_GSSAPI_RESPONSE: Final[bytes] +cMSG_USERAUTH_GSSAPI_TOKEN: Final[bytes] +cMSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE: Final[bytes] +cMSG_USERAUTH_GSSAPI_ERROR: Final[bytes] +cMSG_USERAUTH_GSSAPI_ERRTOK: Final[bytes] +cMSG_USERAUTH_GSSAPI_MIC: Final[bytes] +cMSG_GLOBAL_REQUEST: Final[bytes] +cMSG_REQUEST_SUCCESS: Final[bytes] +cMSG_REQUEST_FAILURE: Final[bytes] +cMSG_CHANNEL_OPEN: Final[bytes] +cMSG_CHANNEL_OPEN_SUCCESS: Final[bytes] +cMSG_CHANNEL_OPEN_FAILURE: Final[bytes] +cMSG_CHANNEL_WINDOW_ADJUST: Final[bytes] +cMSG_CHANNEL_DATA: Final[bytes] +cMSG_CHANNEL_EXTENDED_DATA: Final[bytes] +cMSG_CHANNEL_EOF: Final[bytes] +cMSG_CHANNEL_CLOSE: Final[bytes] +cMSG_CHANNEL_REQUEST: Final[bytes] +cMSG_CHANNEL_SUCCESS: Final[bytes] +cMSG_CHANNEL_FAILURE: Final[bytes] + +MSG_NAMES: dict[int, str] + +AUTH_SUCCESSFUL: Final = 0 +AUTH_PARTIALLY_SUCCESSFUL: Final = 1 +AUTH_FAILED: Final = 2 + +OPEN_SUCCEEDED: Final = 0 +OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED: Final = 1 +OPEN_FAILED_CONNECT_FAILED: Final = 2 +OPEN_FAILED_UNKNOWN_CHANNEL_TYPE: Final = 3 +OPEN_FAILED_RESOURCE_SHORTAGE: Final = 4 + +CONNECTION_FAILED_CODE: dict[int, str] + +DISCONNECT_SERVICE_NOT_AVAILABLE: Final = 7 +DISCONNECT_AUTH_CANCELLED_BY_USER: Final = 13 +DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE: Final = 14 + +zero_byte: bytes +one_byte: bytes +four_byte: bytes +max_byte: bytes +cr_byte: bytes +linefeed_byte: bytes +crlf: bytes +cr_byte_value: int +linefeed_byte_value: int +xffffffff: int +x80000000: int +o666: int +o660: int +o644: int +o600: int +o777: int +o700: int +o70: int + +DEBUG = logging.DEBUG +INFO = logging.INFO +WARNING = logging.WARNING +ERROR = logging.ERROR +CRITICAL = logging.CRITICAL + +io_sleep: float + +DEFAULT_WINDOW_SIZE: Final[int] +DEFAULT_MAX_PACKET_SIZE: Final[int] + +MIN_WINDOW_SIZE: Final[int] +MIN_PACKET_SIZE: Final[int] +MAX_WINDOW_SIZE: Final[int] diff --git a/stubs/paramiko/paramiko/compress.pyi b/stubs/paramiko/paramiko/compress.pyi new file mode 100644 index 000000000000..9dd81d17f4f5 --- /dev/null +++ b/stubs/paramiko/paramiko/compress.pyi @@ -0,0 +1,12 @@ +from _typeshed import ReadableBuffer +from zlib import _Compress, _Decompress + +class ZlibCompressor: + z: _Compress + def __init__(self) -> None: ... + def __call__(self, data: ReadableBuffer) -> bytes: ... + +class ZlibDecompressor: + z: _Decompress + def __init__(self) -> None: ... + def __call__(self, data: ReadableBuffer) -> bytes: ... diff --git a/stubs/paramiko/paramiko/config.pyi b/stubs/paramiko/paramiko/config.pyi new file mode 100644 index 000000000000..19b14ed53947 --- /dev/null +++ b/stubs/paramiko/paramiko/config.pyi @@ -0,0 +1,34 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from re import Pattern +from typing_extensions import Self + +from paramiko.ssh_exception import ConfigParseError as ConfigParseError, CouldNotCanonicalize as CouldNotCanonicalize + +invoke_import_error: ImportError | None +SSH_PORT: int + +class SSHConfig: + SETTINGS_REGEX: Pattern[str] + TOKENS_BY_CONFIG_KEY: dict[str, list[str]] + def __init__(self) -> None: ... + @classmethod + def from_text(cls, text: str) -> Self: ... + @classmethod + def from_path(cls, path: FileDescriptorOrPath) -> Self: ... + @classmethod + def from_file(cls, flo: Iterable[str]) -> Self: ... + def parse(self, file_obj: Iterable[str]) -> None: ... + def lookup(self, hostname: str) -> SSHConfigDict: ... + def canonicalize(self, hostname: str, options: SSHConfigDict, domains: Iterable[str]) -> str: ... + def get_hostnames(self) -> set[str]: ... + +class LazyFqdn: + fqdn: str | None + config: SSHConfig + host: str | None + def __init__(self, config: SSHConfigDict, host: str | None = None) -> None: ... + +class SSHConfigDict(dict[str, str]): + def as_bool(self, key: str) -> bool: ... + def as_int(self, key: str) -> int: ... diff --git a/stubs/paramiko/paramiko/ecdsakey.pyi b/stubs/paramiko/paramiko/ecdsakey.pyi new file mode 100644 index 000000000000..804107fb285e --- /dev/null +++ b/stubs/paramiko/paramiko/ecdsakey.pyi @@ -0,0 +1,57 @@ +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Callable, Sequence +from typing import Any + +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve, EllipticCurvePrivateKey, EllipticCurvePublicKey +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from paramiko.message import Message +from paramiko.pkey import PKey, _HasReadlines + +class _ECDSACurve: + nist_name: str + key_length: int + key_format_identifier: str + hash_object: type[HashAlgorithm] + curve_class: type[EllipticCurve] + def __init__(self, curve_class: type[EllipticCurve], nist_name: str) -> None: ... + +class _ECDSACurveSet: + ecdsa_curves: Sequence[_ECDSACurve] + def __init__(self, ecdsa_curves: Sequence[_ECDSACurve]) -> None: ... + def get_key_format_identifier_list(self) -> list[str]: ... + def get_by_curve_class(self, curve_class: type[Any]) -> _ECDSACurve | None: ... + def get_by_key_format_identifier(self, key_format_identifier: str) -> _ECDSACurve | None: ... + def get_by_key_length(self, key_length: int) -> _ECDSACurve | None: ... + +class ECDSAKey(PKey): + verifying_key: EllipticCurvePublicKey + signing_key: EllipticCurvePrivateKey + public_blob: None + ecdsa_curve: _ECDSACurve | None + def __init__( + self, + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + vals: tuple[EllipticCurvePrivateKey, EllipticCurvePublicKey] | None = None, + file_obj: _HasReadlines | None = None, + validate_point: bool = True, + ) -> None: ... + @classmethod + def identifiers(cls) -> list[str]: ... + @classmethod + def supported_key_format_identifiers(cls: Any) -> list[str]: ... + def asbytes(self) -> bytes: ... + def __hash__(self) -> int: ... + def get_name(self) -> str: ... + def get_bits(self) -> int: ... + def can_sign(self) -> bool: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... + def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... + @property + def private_key(self) -> EllipticCurvePrivateKey | None: ... + @classmethod + def generate( + cls, curve: EllipticCurve = ..., progress_func: Callable[..., object] | None = None, bits: int | None = None + ) -> ECDSAKey: ... diff --git a/stubs/paramiko/paramiko/ed25519key.pyi b/stubs/paramiko/paramiko/ed25519key.pyi new file mode 100644 index 000000000000..c57af34f794d --- /dev/null +++ b/stubs/paramiko/paramiko/ed25519key.pyi @@ -0,0 +1,30 @@ +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from typing import Any, Final, TypeAlias + +from paramiko.message import Message +from paramiko.pkey import PKey, _HasReadlines + +_VerifyKey: TypeAlias = Any # actually nacl.signing.VerifyKey + +class Ed25519Key(PKey): + name: Final = "ssh-ed25519" + + public_blob: None + + def __init__( + self, + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + file_obj: _HasReadlines | None = None, + ) -> None: ... + def asbytes(self) -> bytes: ... + def get_name(self) -> str: ... + def get_bits(self) -> int: ... + def can_sign(self) -> bool: ... + def can_verify(self) -> bool: ... + @property + def verifying_key(self) -> _VerifyKey | None: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... + def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... diff --git a/stubs/paramiko/paramiko/file.pyi b/stubs/paramiko/paramiko/file.pyi new file mode 100644 index 000000000000..f18d2a8566f5 --- /dev/null +++ b/stubs/paramiko/paramiko/file.pyi @@ -0,0 +1,39 @@ +from collections.abc import Iterable +from typing import Any, AnyStr, Generic + +from paramiko.util import ClosingContextManager + +class BufferedFile(ClosingContextManager, Generic[AnyStr]): + SEEK_SET: int + SEEK_CUR: int + SEEK_END: int + + FLAG_READ: int + FLAG_WRITE: int + FLAG_APPEND: int + FLAG_BINARY: int + FLAG_BUFFERED: int + FLAG_LINE_BUFFERED: int + FLAG_UNIVERSAL_NEWLINE: int + + newlines: None | AnyStr | tuple[AnyStr, ...] + def __init__(self) -> None: ... + def __del__(self) -> None: ... + def __iter__(self) -> BufferedFile[Any]: ... + def close(self) -> None: ... + def flush(self) -> None: ... + def __next__(self) -> AnyStr: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def readinto(self, buff: bytearray) -> int: ... + def read(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> AnyStr: ... + def readlines(self, sizehint: int | None = None) -> list[AnyStr]: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def tell(self) -> int: ... + def write(self, data: AnyStr) -> None: ... + def writelines(self, sequence: Iterable[AnyStr]) -> None: ... + def xreadlines(self) -> BufferedFile[Any]: ... + @property + def closed(self) -> bool: ... diff --git a/stubs/paramiko/paramiko/hostkeys.pyi b/stubs/paramiko/paramiko/hostkeys.pyi new file mode 100644 index 000000000000..c9d93b374af9 --- /dev/null +++ b/stubs/paramiko/paramiko/hostkeys.pyi @@ -0,0 +1,49 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterator, Mapping, MutableMapping +from typing import type_check_only +from typing_extensions import Self + +from paramiko.pkey import PKey + +# Internal to HostKeys.lookup(). Calls itself "SubDict". +@type_check_only +class _SubDict(MutableMapping[str, PKey]): + def __init__(self, hostname: str, entries: list[HostKeyEntry], hostkeys: HostKeys) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __delitem__(self, key: str) -> None: ... + def __getitem__(self, key: str) -> PKey: ... + def __setitem__(self, key: str, val: PKey) -> None: ... + def keys(self) -> list[str]: ... # type: ignore[override] + +class HostKeys(MutableMapping[str, _SubDict]): + def __init__(self, filename: FileDescriptorOrPath | None = None) -> None: ... + def add(self, hostname: str, keytype: str, key: PKey) -> None: ... + def load(self, filename: FileDescriptorOrPath) -> None: ... + def save(self, filename: FileDescriptorOrPath) -> None: ... + def lookup(self, hostname: str) -> _SubDict | None: ... + def check(self, hostname: str, key: PKey) -> bool: ... + def clear(self) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __getitem__(self, key: str) -> _SubDict: ... + def __delitem__(self, key: str) -> None: ... + def __setitem__(self, hostname: str, entry: Mapping[str, PKey]) -> None: ... + def keys(self) -> list[str]: ... # type: ignore[override] + def values(self) -> list[_SubDict]: ... # type: ignore[override] + @staticmethod + def hash_host(hostname: str, salt: str | None = None) -> str: ... + +class InvalidHostKey(Exception): + line: str + exc: Exception + def __init__(self, line: str, exc: Exception) -> None: ... + +class HostKeyEntry: + valid: bool + hostnames: list[str] + key: PKey + def __init__(self, hostnames: list[str] | None = None, key: PKey | None = None) -> None: ... + @classmethod + def from_line(cls, line: str, lineno: int | None = None) -> Self | None: ... + def to_line(self) -> str | None: ... diff --git a/stubs/paramiko/paramiko/kex_curve25519.pyi b/stubs/paramiko/paramiko/kex_curve25519.pyi new file mode 100644 index 000000000000..be33b1a57ac2 --- /dev/null +++ b/stubs/paramiko/paramiko/kex_curve25519.pyi @@ -0,0 +1,20 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash + +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey +from paramiko.message import Message +from paramiko.transport import Transport + +c_MSG_KEXECDH_INIT: bytes +c_MSG_KEXECDH_REPLY: bytes + +class KexCurve25519: + hash_algo: Callable[[ReadableBuffer], _Hash] + transport: Transport + key: X25519PrivateKey | None + def __init__(self, transport: Transport) -> None: ... + @classmethod + def is_available(cls) -> bool: ... + def start_kex(self) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... diff --git a/stubs/paramiko/paramiko/kex_ecdh_nist.pyi b/stubs/paramiko/paramiko/kex_ecdh_nist.pyi new file mode 100644 index 000000000000..3178b181e5e4 --- /dev/null +++ b/stubs/paramiko/paramiko/kex_ecdh_nist.pyi @@ -0,0 +1,32 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash + +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurve, EllipticCurvePrivateKey, EllipticCurvePublicKey +from paramiko.message import Message +from paramiko.transport import Transport + +c_MSG_KEXECDH_INIT: bytes +c_MSG_KEXECDH_REPLY: bytes + +class KexNistp256: + name: str + hash_algo: Callable[[ReadableBuffer], _Hash] + curve: EllipticCurve + transport: Transport + P: int | EllipticCurvePrivateKey + Q_C: EllipticCurvePublicKey | None + Q_S: EllipticCurvePublicKey | None + def __init__(self, transport: Transport) -> None: ... + def start_kex(self) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... + +class KexNistp384(KexNistp256): + name: str + hash_algo: Callable[[ReadableBuffer], _Hash] + curve: EllipticCurve + +class KexNistp521(KexNistp256): + name: str + hash_algo: Callable[[ReadableBuffer], _Hash] + curve: EllipticCurve diff --git a/stubs/paramiko/paramiko/kex_gex.pyi b/stubs/paramiko/paramiko/kex_gex.pyi new file mode 100644 index 000000000000..19795704f7a6 --- /dev/null +++ b/stubs/paramiko/paramiko/kex_gex.pyi @@ -0,0 +1,33 @@ +from _hashlib import HASH +from _typeshed import ReadableBuffer +from collections.abc import Callable +from typing import ClassVar, Final + +from paramiko.message import Message +from paramiko.transport import Transport + +c_MSG_KEXDH_GEX_REQUEST_OLD: Final[bytes] +c_MSG_KEXDH_GEX_GROUP: Final[bytes] +c_MSG_KEXDH_GEX_INIT: Final[bytes] +c_MSG_KEXDH_GEX_REPLY: Final[bytes] +c_MSG_KEXDH_GEX_REQUEST: Final[bytes] + +class KexGexSHA256: + name: ClassVar[str] + min_bits: ClassVar[int] + max_bits: ClassVar[int] + preferred_bits: ClassVar[int] + hash_algo: ClassVar[Callable[[ReadableBuffer], HASH]] + + transport: Transport + p: int | None + q: int | None + g: int | None + x: int | None + e: int | None + f: int | None + old_style: bool + + def __init__(self, transport: Transport) -> None: ... + def start_kex(self, _test_old_style: bool = False) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... diff --git a/stubs/paramiko/paramiko/kex_group14.pyi b/stubs/paramiko/paramiko/kex_group14.pyi new file mode 100644 index 000000000000..ce550589cc9b --- /dev/null +++ b/stubs/paramiko/paramiko/kex_group14.pyi @@ -0,0 +1,28 @@ +from _hashlib import HASH +from _typeshed import ReadableBuffer +from collections.abc import Callable +from typing import ClassVar, Final + +from paramiko.message import Message +from paramiko.transport import Transport + +c_MSG_KEXDH_INIT: Final[bytes] +c_MSG_KEXDH_REPLY: Final[bytes] +b7fffffffffffffff: Final[bytes] +b0000000000000000: Final[bytes] + +class KexGroup14SHA256: + P: ClassVar[int] + G: ClassVar[int] + + name: ClassVar[str] + hash_algo: ClassVar[Callable[[ReadableBuffer], HASH]] + + transport: Transport + x: int + e: int + f: int + + def __init__(self, transport: Transport) -> None: ... + def start_kex(self) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... diff --git a/stubs/paramiko/paramiko/kex_group16.pyi b/stubs/paramiko/paramiko/kex_group16.pyi new file mode 100644 index 000000000000..d8dd7905f195 --- /dev/null +++ b/stubs/paramiko/paramiko/kex_group16.pyi @@ -0,0 +1,3 @@ +from paramiko.kex_group14 import KexGroup14SHA256 + +class KexGroup16SHA512(KexGroup14SHA256): ... diff --git a/stubs/paramiko/paramiko/message.pyi b/stubs/paramiko/paramiko/message.pyi new file mode 100644 index 000000000000..88bed87b56a7 --- /dev/null +++ b/stubs/paramiko/paramiko/message.pyi @@ -0,0 +1,42 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from io import BytesIO +from typing import Any, Protocol, TypeAlias, type_check_only + +@type_check_only +class _SupportsAsBytes(Protocol): + def asbytes(self) -> bytes: ... + +_LikeBytes: TypeAlias = bytes | str | _SupportsAsBytes | ReadableBuffer + +class Message: + big_int: int + packet: BytesIO + seqno: int # only when packet.Packetizer.read_message() is used + def __init__(self, content: ReadableBuffer | None = None) -> None: ... + def __bytes__(self) -> bytes: ... + def asbytes(self) -> bytes: ... + def rewind(self) -> None: ... + def get_remainder(self) -> bytes: ... + def get_so_far(self) -> bytes: ... + def get_bytes(self, n: int) -> bytes: ... + def get_byte(self) -> bytes: ... + def get_boolean(self) -> bool: ... + def get_adaptive_int(self) -> int: ... + def get_int(self) -> int: ... + def get_int64(self) -> int: ... + def get_mpint(self) -> int: ... + def get_string(self) -> bytes: ... + def get_text(self) -> str: ... + def get_binary(self) -> bytes: ... + def get_list(self) -> list[str]: ... + def add_bytes(self, b: ReadableBuffer) -> Message: ... + def add_byte(self, b: ReadableBuffer) -> Message: ... + def add_boolean(self, b: bool) -> Message: ... + def add_int(self, n: int) -> Message: ... + def add_adaptive_int(self, n: int) -> Message: ... + def add_int64(self, n: int) -> Message: ... + def add_mpint(self, z: int) -> Message: ... + def add_string(self, s: _LikeBytes) -> Message: ... + def add_list(self, l: Iterable[str]) -> Message: ... + def add(self, *seq: Any) -> None: ... diff --git a/stubs/paramiko/paramiko/packet.pyi b/stubs/paramiko/paramiko/packet.pyi new file mode 100644 index 000000000000..1dce422c6b2b --- /dev/null +++ b/stubs/paramiko/paramiko/packet.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash +from logging import Logger +from socket import socket +from typing import Any + +from cryptography.hazmat.primitives.ciphers import Cipher +from paramiko.compress import ZlibCompressor, ZlibDecompressor +from paramiko.message import Message + +def compute_hmac(key: bytes | bytearray, message: ReadableBuffer, digest_class: _Hash) -> bytes: ... + +class NeedRekeyException(Exception): ... + +def first_arg(e: Exception) -> Any: ... + +class Packetizer: + REKEY_PACKETS: int + REKEY_BYTES: int + REKEY_PACKETS_OVERFLOW_MAX: int + REKEY_BYTES_OVERFLOW_MAX: int + def __init__(self, socket: socket) -> None: ... + @property + def closed(self) -> bool: ... + def reset_seqno_out(self) -> None: ... + def reset_seqno_in(self) -> None: ... + def set_log(self, log: Logger) -> None: ... + def set_outbound_cipher( + self, + block_engine: Cipher[Incomplete], + block_size: int, + mac_engine: _Hash, + mac_size: int, + mac_key: bytes | bytearray, + sdctr: bool = False, + etm: bool = False, + aead: bool = False, + iv_out: bytes | None = None, + ) -> None: ... + def set_inbound_cipher( + self, + block_engine: Cipher[Incomplete], + block_size: int, + mac_engine: _Hash, + mac_size: int, + mac_key: bytes | bytearray, + etm: bool = False, + aead: bool = False, + iv_in: bytes | None = None, + ) -> None: ... + def set_outbound_compressor(self, compressor: ZlibCompressor) -> None: ... + def set_inbound_compressor(self, compressor: ZlibDecompressor) -> None: ... + def close(self) -> None: ... + def set_hexdump(self, hexdump: bool) -> None: ... + def get_hexdump(self) -> bool: ... + def get_mac_size_in(self) -> int: ... + def get_mac_size_out(self) -> int: ... + def need_rekey(self) -> bool: ... + def set_keepalive(self, interval: float, callback: Callable[[], object]) -> None: ... + def read_timer(self) -> None: ... + def start_handshake(self, timeout: float) -> None: ... + def handshake_timed_out(self) -> bool: ... + def complete_handshake(self) -> None: ... + def read_all(self, n: int, check_rekey: bool = False) -> bytes: ... + def write_all(self, out: ReadableBuffer) -> None: ... + def readline(self, timeout: float) -> str: ... + def send_message(self, data: Message) -> None: ... + def read_message(self) -> tuple[int, Message]: ... diff --git a/stubs/paramiko/paramiko/pipe.pyi b/stubs/paramiko/paramiko/pipe.pyi new file mode 100644 index 000000000000..4cc8e54b09b4 --- /dev/null +++ b/stubs/paramiko/paramiko/pipe.pyi @@ -0,0 +1,37 @@ +from typing import Protocol, type_check_only + +@type_check_only +class _BasePipe(Protocol): + def clear(self) -> None: ... + def set(self) -> None: ... + +@type_check_only +class _Pipe(_BasePipe, Protocol): + def close(self) -> None: ... + def fileno(self) -> int: ... + def set_forever(self) -> None: ... + +def make_pipe() -> _Pipe: ... + +class PosixPipe: + def __init__(self) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def clear(self) -> None: ... + def set(self) -> None: ... + def set_forever(self) -> None: ... + +class WindowsPipe: + def __init__(self) -> None: ... + def close(self) -> None: ... + def fileno(self) -> int: ... + def clear(self) -> None: ... + def set(self) -> None: ... + def set_forever(self) -> None: ... + +class OrPipe: + def __init__(self, pipe: _Pipe) -> None: ... + def set(self) -> None: ... + def clear(self) -> None: ... + +def make_or_pipe(pipe: _Pipe) -> tuple[OrPipe, OrPipe]: ... diff --git a/stubs/paramiko/paramiko/pkey.pyi b/stubs/paramiko/paramiko/pkey.pyi new file mode 100644 index 000000000000..752039f792cd --- /dev/null +++ b/stubs/paramiko/paramiko/pkey.pyi @@ -0,0 +1,87 @@ +from _typeshed import StrOrBytesPath, SupportsWrite +from pathlib import Path +from re import Pattern +from typing import Final, NamedTuple, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self + +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat +from paramiko.message import Message + +@type_check_only +class _HasReadlines(Protocol): + def readlines(self) -> list[str]: ... + +OPENSSH_AUTH_MAGIC: bytes + +_BytesT = TypeVar("_BytesT", bound=bytes | bytearray) + +def _unpad_openssh(data: _BytesT) -> _BytesT: ... + +class UnknownKeyType(Exception): + key_type: str | type | None + key_bytes: bytes | None + def __init__(self, key_type: str | type | None = None, key_bytes: bytes | None = None) -> None: ... + +class FileFormat(NamedTuple): + format: PrivateFormat + encoding: Encoding + +PrivateKey: TypeAlias = RSAPrivateKey | EllipticCurvePrivateKey | Ed25519PrivateKey + +PEM: Final[FileFormat] +OPENSSH: Final[FileFormat] + +class PKey: + public_blob: PublicBlob | None + BEGIN_TAG: Pattern[str] + END_TAG: Pattern[str] + @staticmethod + def from_path(path: Path | str, password: str | None = None) -> PKey: ... + @staticmethod + def from_type_string(key_type: str, key_bytes: bytes, password: str | None = None) -> PKey: ... + @classmethod + def identifiers(cls) -> list[str]: ... + def __init__(self, msg: Message | None = None, data: str | None = None) -> None: ... + def asbytes(self) -> bytes: ... + def __bytes__(self) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def get_name(self) -> str: ... + @property + def algorithm_name(self) -> str: ... + def get_bits(self) -> int: ... + def can_sign(self) -> bool: ... + def get_fingerprint(self) -> bytes: ... + @property + def fingerprint(self) -> str: ... + def get_base64(self) -> str: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... + def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... + @classmethod + def from_private_key_file(cls, filename: StrOrBytesPath, password: str | None = None) -> Self: ... + @classmethod + def from_private_key(cls, file_obj: _HasReadlines, password: str | None = None) -> Self: ... + def write_private_key_file( + self, filename: StrOrBytesPath, password: str | None = None, file_format: FileFormat = PEM # noqa: Y011 + ) -> None: ... + def write_private_key( + self, file_obj: SupportsWrite[str], password: str | None = None, file_format: FileFormat = PEM # noqa: Y011 + ) -> None: ... + def load_certificate(self, value: Message | str) -> None: ... + +class PublicBlob: + key_type: str + key_blob: bytes + comment: str + def __init__(self, type_: str, blob: bytes, comment: str | None = None) -> None: ... + @classmethod + def from_file(cls, filename: StrOrBytesPath) -> Self: ... + @classmethod + def from_string(cls, string: str) -> Self: ... + @classmethod + def from_message(cls, message: Message) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... diff --git a/stubs/paramiko/paramiko/primes.pyi b/stubs/paramiko/paramiko/primes.pyi new file mode 100644 index 000000000000..a59dedce5b42 --- /dev/null +++ b/stubs/paramiko/paramiko/primes.pyi @@ -0,0 +1,8 @@ +from _typeshed import FileDescriptorOrPath + +class ModulusPack: + pack: dict[int, list[tuple[int, int]]] + discarded: list[tuple[int, str]] + def __init__(self) -> None: ... + def read_file(self, filename: FileDescriptorOrPath) -> None: ... + def get_modulus(self, min: int, prefer: int, max: int) -> tuple[int, int]: ... diff --git a/stubs/paramiko/paramiko/proxy.pyi b/stubs/paramiko/paramiko/proxy.pyi new file mode 100644 index 000000000000..c22af8eb32d8 --- /dev/null +++ b/stubs/paramiko/paramiko/proxy.pyi @@ -0,0 +1,19 @@ +from _typeshed import ReadableBuffer +from subprocess import Popen +from typing import Any + +from paramiko.util import ClosingContextManager + +subprocess_import_error: ImportError | None + +class ProxyCommand(ClosingContextManager): + cmd: list[str] + process: Popen[Any] + timeout: float | None + def __init__(self, command_line: str) -> None: ... + def send(self, content: ReadableBuffer) -> int: ... + def recv(self, size: int) -> bytes: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def settimeout(self, timeout: float) -> None: ... diff --git a/stubs/paramiko/paramiko/rsakey.pyi b/stubs/paramiko/paramiko/rsakey.pyi new file mode 100644 index 000000000000..8c071bb19c17 --- /dev/null +++ b/stubs/paramiko/paramiko/rsakey.pyi @@ -0,0 +1,40 @@ +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Callable +from typing import Final + +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey, RSAPublicNumbers +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from paramiko.message import Message +from paramiko.pkey import PKey, _HasReadlines + +class RSAKey(PKey): + name: Final = "ssh-rsa" + HASHES: Final[dict[str, type[HashAlgorithm]]] + + key: None | RSAPublicKey | RSAPrivateKey + public_blob: None + def __init__( + self, + msg: Message | None = None, + data: ReadableBuffer | None = None, + filename: FileDescriptorOrPath | None = None, + password: str | None = None, + key: None | RSAPublicKey | RSAPrivateKey = None, + file_obj: _HasReadlines | None = None, + ) -> None: ... + @classmethod + def identifiers(cls) -> list[str]: ... + @property + def size(self) -> int: ... + @property + def private_key(self) -> RSAPrivateKey | None: ... + @property + def public_numbers(self) -> RSAPublicNumbers: ... + def asbytes(self) -> bytes: ... + def get_name(self) -> str: ... + def get_bits(self) -> int: ... + def can_sign(self) -> bool: ... + def sign_ssh_data(self, data: bytes, algorithm: str | None = None) -> Message: ... + def verify_ssh_sig(self, data: bytes, msg: Message) -> bool: ... + @staticmethod + def generate(bits: int, progress_func: Callable[..., object] | None = None) -> RSAKey: ... diff --git a/stubs/paramiko/paramiko/server.pyi b/stubs/paramiko/paramiko/server.pyi new file mode 100644 index 000000000000..ad803371917e --- /dev/null +++ b/stubs/paramiko/paramiko/server.pyi @@ -0,0 +1,47 @@ +import threading + +from paramiko.channel import Channel +from paramiko.message import Message +from paramiko.pkey import PKey +from paramiko.transport import Transport + +class ServerInterface: + def check_channel_request(self, kind: str, chanid: int) -> int: ... + def get_allowed_auths(self, username: str) -> str: ... + def check_auth_none(self, username: str) -> int: ... + def check_auth_password(self, username: str, password: str) -> int: ... + def check_auth_publickey(self, username: str, key: PKey) -> int: ... + def check_auth_interactive(self, username: str, submethods: str) -> int | InteractiveQuery: ... + def check_auth_interactive_response(self, responses: list[str]) -> int | InteractiveQuery: ... + def check_port_forward_request(self, address: str, port: int) -> int: ... + def cancel_port_forward_request(self, address: str, port: int) -> None: ... + def check_global_request(self, kind: str, msg: Message) -> bool | tuple[bool | int | str, ...]: ... + def check_channel_pty_request( + self, channel: Channel, term: bytes, width: int, height: int, pixelwidth: int, pixelheight: int, modes: bytes + ) -> bool: ... + def check_channel_shell_request(self, channel: Channel) -> bool: ... + def check_channel_exec_request(self, channel: Channel, command: bytes) -> bool: ... + def check_channel_subsystem_request(self, channel: Channel, name: str) -> bool: ... + def check_channel_window_change_request( + self, channel: Channel, width: int, height: int, pixelwidth: int, pixelheight: int + ) -> bool: ... + def check_channel_x11_request( + self, channel: Channel, single_connection: bool, auth_protocol: str, auth_cookie: bytes, screen_number: int + ) -> bool: ... + def check_channel_forward_agent_request(self, channel: Channel) -> bool: ... + def check_channel_direct_tcpip_request(self, chanid: int, origin: tuple[str, int], destination: tuple[str, int]) -> int: ... + def check_channel_env_request(self, channel: Channel, name: bytes, value: bytes) -> bool: ... + def get_banner(self) -> tuple[str | None, str | None]: ... + +class InteractiveQuery: + name: str + instructions: str + prompts: list[tuple[str, bool]] + def __init__(self, name: str = "", instructions: str = "", *prompts: str | tuple[str, bool]) -> None: ... + def add_prompt(self, prompt: str, echo: bool = True) -> None: ... + +class SubsystemHandler(threading.Thread): + def __init__(self, channel: Channel, name: str, server: ServerInterface) -> None: ... + def get_server(self) -> ServerInterface: ... + def start_subsystem(self, name: str, transport: Transport, channel: Channel) -> None: ... + def finish_subsystem(self) -> None: ... diff --git a/stubs/paramiko/paramiko/sftp.pyi b/stubs/paramiko/paramiko/sftp.pyi new file mode 100644 index 000000000000..afcfc224f3d9 --- /dev/null +++ b/stubs/paramiko/paramiko/sftp.pyi @@ -0,0 +1,61 @@ +from logging import Logger + +from paramiko.channel import Channel + +CMD_INIT: int +CMD_VERSION: int +CMD_OPEN: int +CMD_CLOSE: int +CMD_READ: int +CMD_WRITE: int +CMD_LSTAT: int +CMD_FSTAT: int +CMD_SETSTAT: int +CMD_FSETSTAT: int +CMD_OPENDIR: int +CMD_READDIR: int +CMD_REMOVE: int +CMD_MKDIR: int +CMD_RMDIR: int +CMD_REALPATH: int +CMD_STAT: int +CMD_RENAME: int +CMD_READLINK: int +CMD_SYMLINK: int +CMD_STATUS: int +CMD_HANDLE: int +CMD_DATA: int +CMD_NAME: int +CMD_ATTRS: int +CMD_EXTENDED: int +CMD_EXTENDED_REPLY: int + +SFTP_OK: int +SFTP_EOF: int +SFTP_NO_SUCH_FILE: int +SFTP_PERMISSION_DENIED: int +SFTP_FAILURE: int +SFTP_BAD_MESSAGE: int +SFTP_NO_CONNECTION: int +SFTP_CONNECTION_LOST: int +SFTP_OP_UNSUPPORTED: int + +SFTP_DESC: list[str] + +SFTP_FLAG_READ: int +SFTP_FLAG_WRITE: int +SFTP_FLAG_APPEND: int +SFTP_FLAG_CREATE: int +SFTP_FLAG_TRUNC: int +SFTP_FLAG_EXCL: int + +CMD_NAMES: dict[int, str] + +class int64(int): ... +class SFTPError(Exception): ... + +class BaseSFTP: + logger: Logger + sock: Channel | None + ultra_debug: bool + def __init__(self) -> None: ... diff --git a/stubs/paramiko/paramiko/sftp_attr.pyi b/stubs/paramiko/paramiko/sftp_attr.pyi new file mode 100644 index 000000000000..7594ec937965 --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_attr.pyi @@ -0,0 +1,22 @@ +from os import stat_result +from typing_extensions import Self + +class SFTPAttributes: + FLAG_SIZE: int + FLAG_UIDGID: int + FLAG_PERMISSIONS: int + FLAG_AMTIME: int + FLAG_EXTENDED: int + st_size: int | None + st_uid: int | None + st_gid: int | None + st_mode: int | None + st_atime: int | None + st_mtime: int | None + filename: str # only when from_stat() is used + longname: str # only when from_stat() is used + attr: dict[str, str] + def __init__(self) -> None: ... + @classmethod + def from_stat(cls, obj: stat_result, filename: str | None = None) -> Self: ... + def asbytes(self) -> bytes: ... diff --git a/stubs/paramiko/paramiko/sftp_client.pyi b/stubs/paramiko/paramiko/sftp_client.pyi new file mode 100644 index 000000000000..f0bc69af6290 --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_client.pyi @@ -0,0 +1,73 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterator +from logging import Logger +from typing import IO, TypeAlias +from typing_extensions import Self + +from paramiko.channel import Channel +from paramiko.sftp import BaseSFTP +from paramiko.sftp_attr import SFTPAttributes +from paramiko.sftp_file import SFTPFile +from paramiko.transport import Transport +from paramiko.util import ClosingContextManager + +_Callback: TypeAlias = Callable[[int, int], object] + +b_slash: bytes + +class SFTPClient(BaseSFTP, ClosingContextManager): + sock: Channel + ultra_debug: bool + request_number: int + logger: Logger + def __init__(self, sock: Channel) -> None: ... + @classmethod + def from_transport(cls, t: Transport, window_size: int | None = None, max_packet_size: int | None = None) -> Self | None: ... + def close(self) -> None: ... + def get_channel(self) -> Channel | None: ... + def listdir(self, path: str = ".") -> list[str]: ... + def listdir_attr(self, path: str = ".") -> list[SFTPAttributes]: ... + def listdir_iter(self, path: bytes | str = ".", read_aheads: int = 50) -> Iterator[SFTPAttributes]: ... + def open(self, filename: bytes | str, mode: str = "r", bufsize: int = -1) -> SFTPFile: ... + file = open + def remove(self, path: bytes | str) -> None: ... + unlink = remove + def rename(self, oldpath: bytes | str, newpath: bytes | str) -> None: ... + def posix_rename(self, oldpath: bytes | str, newpath: bytes | str) -> None: ... + def mkdir(self, path: bytes | str, mode: int = 511) -> None: ... + def rmdir(self, path: bytes | str) -> None: ... + def stat(self, path: bytes | str) -> SFTPAttributes: ... + def lstat(self, path: bytes | str) -> SFTPAttributes: ... + def symlink(self, source: bytes | str, dest: bytes | str) -> None: ... + def chmod(self, path: bytes | str, mode: int) -> None: ... + def chown(self, path: bytes | str, uid: int, gid: int) -> None: ... + def utime(self, path: bytes | str, times: tuple[float, float] | None) -> None: ... + def truncate(self, path: bytes | str, size: int) -> None: ... + def readlink(self, path: bytes | str) -> str | None: ... + def normalize(self, path: bytes | str) -> str: ... + def chdir(self, path: None | bytes | str = None) -> None: ... + def getcwd(self) -> str | None: ... + def putfo( + self, fl: IO[bytes], remotepath: bytes | str, file_size: int = 0, callback: _Callback | None = None, confirm: bool = True + ) -> SFTPAttributes: ... + def put( + self, localpath: StrOrBytesPath, remotepath: bytes | str, callback: _Callback | None = None, confirm: bool = True + ) -> SFTPAttributes: ... + def getfo( + self, + remotepath: bytes | str, + fl: IO[bytes], + callback: _Callback | None = None, + prefetch: bool = True, + max_concurrent_prefetch_requests: int | None = None, + ) -> int: ... + def get( + self, + remotepath: bytes | str, + localpath: StrOrBytesPath, + callback: _Callback | None = None, + prefetch: bool = True, + max_concurrent_prefetch_requests: int | None = None, + ) -> None: ... + +class SFTP(SFTPClient): ... diff --git a/stubs/paramiko/paramiko/sftp_file.pyi b/stubs/paramiko/paramiko/sftp_file.pyi new file mode 100644 index 000000000000..56a740e06afe --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_file.pyi @@ -0,0 +1,33 @@ +from collections.abc import Iterator, Sequence +from typing import Any + +from paramiko.file import BufferedFile +from paramiko.message import _LikeBytes +from paramiko.sftp_attr import SFTPAttributes +from paramiko.sftp_client import SFTPClient +from paramiko.sftp_handle import SFTPHandle + +class SFTPFile(BufferedFile[Any]): + MAX_REQUEST_SIZE: int + sftp: SFTPClient + handle: SFTPHandle + pipelined: bool + def __init__(self, sftp: SFTPClient, handle: _LikeBytes, mode: str = "r", bufsize: int = -1) -> None: ... + def __del__(self) -> None: ... + def close(self) -> None: ... + def settimeout(self, timeout: float) -> None: ... + def gettimeout(self) -> float: ... + def setblocking(self, blocking: bool) -> None: ... + def seekable(self) -> bool: ... + def seek(self, offset: int, whence: int = 0) -> None: ... + def stat(self) -> SFTPAttributes: ... + def chmod(self, mode: int) -> None: ... + def chown(self, uid: int, gid: int) -> None: ... + def utime(self, times: tuple[float, float] | None) -> None: ... + def truncate(self, size: int) -> None: ... + def check(self, hash_algorithm: str, offset: int = 0, length: int = 0, block_size: int = 0) -> bytes: ... + def set_pipelined(self, pipelined: bool = True) -> None: ... + def prefetch(self, file_size: int | None = None, max_concurrent_requests: int | None = None) -> None: ... + def readv( + self, chunks: Sequence[tuple[int, int]], max_concurrent_prefetch_requests: int | None = None + ) -> Iterator[bytes]: ... diff --git a/stubs/paramiko/paramiko/sftp_handle.pyi b/stubs/paramiko/paramiko/sftp_handle.pyi new file mode 100644 index 000000000000..d730c69c4cdb --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_handle.pyi @@ -0,0 +1,12 @@ +from _typeshed import ReadableBuffer + +from paramiko.sftp_attr import SFTPAttributes +from paramiko.util import ClosingContextManager + +class SFTPHandle(ClosingContextManager): + def __init__(self, flags: int = 0) -> None: ... + def close(self) -> None: ... + def read(self, offset: int, length: int) -> bytes | int: ... + def write(self, offset: int, data: ReadableBuffer) -> int: ... + def stat(self) -> int | SFTPAttributes: ... + def chattr(self, attr: SFTPAttributes) -> int: ... diff --git a/stubs/paramiko/paramiko/sftp_server.pyi b/stubs/paramiko/paramiko/sftp_server.pyi new file mode 100644 index 000000000000..b4a289e8e7fb --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_server.pyi @@ -0,0 +1,35 @@ +from _typeshed import FileDescriptorOrPath +from logging import Logger +from typing import Any + +from paramiko.channel import Channel +from paramiko.server import ServerInterface, SubsystemHandler +from paramiko.sftp import BaseSFTP +from paramiko.sftp_attr import SFTPAttributes +from paramiko.sftp_handle import SFTPHandle +from paramiko.sftp_si import SFTPServerInterface +from paramiko.transport import Transport + +class SFTPServer(BaseSFTP, SubsystemHandler): + logger: Logger + ultra_debug: bool + next_handle: int + file_table: dict[bytes, SFTPHandle] + folder_table: dict[bytes, SFTPHandle] + server: SFTPServerInterface + sock: Channel | None + def __init__( + self, + channel: Channel, + name: str, + server: ServerInterface, + sftp_si: type[SFTPServerInterface] = ..., + *args: Any, + **kwargs: Any, + ) -> None: ... + def start_subsystem(self, name: str, transport: Transport, channel: Channel) -> None: ... + def finish_subsystem(self) -> None: ... + @staticmethod + def convert_errno(e: int) -> int: ... + @staticmethod + def set_file_attr(filename: FileDescriptorOrPath, attr: SFTPAttributes) -> None: ... diff --git a/stubs/paramiko/paramiko/sftp_si.pyi b/stubs/paramiko/paramiko/sftp_si.pyi new file mode 100644 index 000000000000..efca37e842f6 --- /dev/null +++ b/stubs/paramiko/paramiko/sftp_si.pyi @@ -0,0 +1,23 @@ +from typing import Any + +from paramiko.server import ServerInterface +from paramiko.sftp_attr import SFTPAttributes +from paramiko.sftp_handle import SFTPHandle + +class SFTPServerInterface: + def __init__(self, server: ServerInterface, *largs: Any, **kwargs: Any) -> None: ... + def session_started(self) -> None: ... + def session_ended(self) -> None: ... + def open(self, path: str, flags: int, attr: SFTPAttributes) -> SFTPHandle | int: ... + def list_folder(self, path: str) -> list[SFTPAttributes] | int: ... + def stat(self, path: str) -> SFTPAttributes | int: ... + def lstat(self, path: str) -> SFTPAttributes | int: ... + def remove(self, path: str) -> int: ... + def rename(self, oldpath: str, newpath: str) -> int: ... + def posix_rename(self, oldpath: str, newpath: str) -> int: ... + def mkdir(self, path: str, attr: SFTPAttributes) -> int: ... + def rmdir(self, path: str) -> int: ... + def chattr(self, path: str, attr: SFTPAttributes) -> int: ... + def canonicalize(self, path: str) -> str: ... + def readlink(self, path: str) -> str | int: ... + def symlink(self, target_path: str, path: str) -> int: ... diff --git a/stubs/paramiko/paramiko/ssh_exception.pyi b/stubs/paramiko/paramiko/ssh_exception.pyi new file mode 100644 index 000000000000..ddd60331d0ad --- /dev/null +++ b/stubs/paramiko/paramiko/ssh_exception.pyi @@ -0,0 +1,47 @@ +import socket +from collections.abc import Mapping + +from paramiko.pkey import PKey + +class SSHException(Exception): ... +class AuthenticationException(SSHException): ... +class PasswordRequiredException(AuthenticationException): ... + +class BadAuthenticationType(AuthenticationException): + allowed_types: list[str] + explanation: str + def __init__(self, explanation: str, types: list[str]) -> None: ... + +class PartialAuthentication(AuthenticationException): + allowed_types: list[str] + def __init__(self, types: list[str]) -> None: ... + +class UnableToAuthenticate(AuthenticationException): ... + +class ChannelException(SSHException): + code: int + text: str + def __init__(self, code: int, text: str) -> None: ... + +class BadHostKeyException(SSHException): + hostname: str + key: PKey + expected_key: PKey + def __init__(self, hostname: str, got_key: PKey, expected_key: PKey) -> None: ... + +class IncompatiblePeer(SSHException): ... + +class ProxyCommandFailure(SSHException): + command: str + error: str + def __init__(self, command: str, error: str) -> None: ... + +class MessageOrderError(SSHException): ... + +class NoValidConnectionsError(socket.error): + errors: Mapping[tuple[str, int] | tuple[str, int, int, int], Exception] + def __init__(self, errors: Mapping[tuple[str, int] | tuple[str, int, int, int], Exception]) -> None: ... + def __reduce__(self) -> tuple[type, tuple[Mapping[tuple[str, int] | tuple[str, int, int, int], Exception]]]: ... + +class CouldNotCanonicalize(SSHException): ... +class ConfigParseError(SSHException): ... diff --git a/stubs/paramiko/paramiko/transport.pyi b/stubs/paramiko/paramiko/transport.pyi new file mode 100644 index 000000000000..81b3c170881c --- /dev/null +++ b/stubs/paramiko/paramiko/transport.pyi @@ -0,0 +1,201 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Iterable, Mapping, Sequence +from logging import Logger +from socket import socket +from threading import Condition, Event, Lock, Thread +from typing import Any, Protocol, TypeAlias, type_check_only + +from paramiko.auth_handler import AuthHandler, AuthOnlyHandler, _InteractiveCallback +from paramiko.channel import Channel +from paramiko.message import Message +from paramiko.packet import Packetizer +from paramiko.pkey import PKey +from paramiko.proxy import ProxyCommand +from paramiko.server import ServerInterface, SubsystemHandler +from paramiko.sftp_client import SFTPClient +from paramiko.util import ClosingContextManager + +_Addr: TypeAlias = tuple[str, int] +_SocketLike: TypeAlias = str | _Addr | socket | Channel | ProxyCommand + +@type_check_only +class _KexEngine(Protocol): + def start_kex(self) -> None: ... + def parse_next(self, ptype: int, m: Message) -> None: ... + +class Transport(Thread, ClosingContextManager): + daemon: bool + sock: socket | Channel + + packetizer: Packetizer + local_version: str + remote_version: str + local_cipher: str + local_kex_init: bytes | None + local_mac: str | None + local_compression: str | None + session_id: bytes | None + host_key_type: str | None + host_key: PKey | None + + kex_engine: _KexEngine | None + H: bytes | None + K: int | None + + initial_kex_done: bool + in_kex: bool + authenticated: bool + lock: Lock + + channel_events: dict[int, Event] + channels_seen: dict[int, bool] + default_max_packet_size: int + default_window_size: int + + saved_exception: Exception | None + clear_to_send: Event + clear_to_send_lock: Lock + clear_to_send_timeout: float + log_name: str + logger: Logger + auth_handler: AuthHandler | None + global_response: Message | None + completion_event: Event | None + banner_timeout: float + handshake_timeout: float + auth_timeout: float + channel_timeout: float + disabled_algorithms: Mapping[str, Iterable[str]] | None + server_sig_algs: bool + + server_mode: bool + server_object: ServerInterface | None + server_key_dict: dict[str, PKey] + server_accepts: list[Channel] + server_accept_cv: Condition + subsystem_table: dict[str, tuple[type[SubsystemHandler], tuple[Any, ...], dict[str, Any]]] + + def __init__( + self, + sock: _SocketLike, + default_window_size: int = 2097152, + default_max_packet_size: int = 32768, + disabled_algorithms: Mapping[str, Iterable[str]] | None = None, + server_sig_algs: bool = True, + strict_kex: bool = True, + packetizer_class: type[Packetizer] | None = None, + ) -> None: ... + @property + def preferred_ciphers(self) -> Sequence[str]: ... + @property + def preferred_macs(self) -> Sequence[str]: ... + @property + def preferred_keys(self) -> Sequence[str]: ... + @property + def preferred_pubkeys(self) -> Sequence[str]: ... + @property + def preferred_kex(self) -> Sequence[str]: ... + @property + def preferred_compression(self) -> Sequence[str]: ... + def atfork(self) -> None: ... + def get_security_options(self) -> SecurityOptions: ... + def start_client(self, event: Event | None = None, timeout: float | None = None) -> None: ... + def start_server(self, event: Event | None = None, server: ServerInterface | None = None) -> None: ... + def add_server_key(self, key: PKey) -> None: ... + def get_server_key(self) -> PKey | None: ... + @staticmethod + def load_server_moduli(filename: FileDescriptorOrPath | None = None) -> bool: ... + def close(self) -> None: ... + def get_remote_server_key(self) -> PKey: ... + def is_active(self) -> bool: ... + def open_session( + self, window_size: int | None = None, max_packet_size: int | None = None, timeout: float | None = None + ) -> Channel: ... + def open_x11_channel(self, src_addr: _Addr | None = None) -> Channel: ... + def open_forward_agent_channel(self) -> Channel: ... + def open_forwarded_tcpip_channel(self, src_addr: _Addr, dest_addr: _Addr) -> Channel: ... + def open_channel( + self, + kind: str, + dest_addr: _Addr | None = None, + src_addr: _Addr | None = None, + window_size: int | None = None, + max_packet_size: int | None = None, + timeout: float | None = None, + ) -> Channel: ... + def request_port_forward( + self, address: str, port: int, handler: Callable[[Channel, _Addr, _Addr], object] | None = None + ) -> int: ... + def cancel_port_forward(self, address: str, port: int) -> None: ... + def open_sftp_client(self) -> SFTPClient | None: ... + def send_ignore(self, byte_count: int | None = None) -> None: ... + def renegotiate_keys(self) -> None: ... + def set_keepalive(self, interval: float) -> None: ... + def global_request(self, kind: str, data: Iterable[Any] | None = None, wait: bool = True) -> Message | None: ... + def accept(self, timeout: float | None = None) -> Channel | None: ... + def connect( + self, hostkey: PKey | None = None, username: str = "", password: str | None = None, pkey: PKey | None = None + ) -> None: ... + def get_exception(self) -> Exception | None: ... + def set_subsystem_handler(self, name: str, handler: type[SubsystemHandler], *larg: Any, **kwarg: Any) -> None: ... + def is_authenticated(self) -> bool: ... + def get_username(self) -> str | None: ... + def get_banner(self) -> bytes | None: ... + def auth_none(self, username: str) -> list[str]: ... + def auth_password(self, username: str, password: str, event: Event | None = None, fallback: bool = True) -> list[str]: ... + def auth_publickey(self, username: str, key: PKey, event: Event | None = None) -> list[str]: ... + def auth_interactive(self, username: str, handler: _InteractiveCallback, submethods: str = "") -> list[str]: ... + def auth_interactive_dumb( + self, username: str, handler: _InteractiveCallback | None = None, submethods: str = "" + ) -> list[str]: ... + def set_log_channel(self, name: str) -> None: ... + def get_log_channel(self) -> str: ... + def set_hexdump(self, hexdump: bool) -> None: ... + def get_hexdump(self) -> bool: ... + def use_compression(self, compress: bool = True) -> None: ... + def getpeername(self) -> tuple[str, int]: ... + def stop_thread(self) -> None: ... + def run(self) -> None: ... + +class SecurityOptions: + __slots__ = "_transport" + def __init__(self, transport: Transport) -> None: ... + + @property + def ciphers(self) -> Sequence[str]: ... + @ciphers.setter + def ciphers(self, x: Sequence[str]) -> None: ... + + @property + def digests(self) -> Sequence[str]: ... + @digests.setter + def digests(self, x: Sequence[str]) -> None: ... + + @property + def key_types(self) -> Sequence[str]: ... + @key_types.setter + def key_types(self, x: Sequence[str]) -> None: ... + + @property + def kex(self) -> Sequence[str]: ... + @kex.setter + def kex(self, x: Sequence[str]) -> None: ... + + @property + def compression(self) -> Sequence[str]: ... + @compression.setter + def compression(self, x: Sequence[str]) -> None: ... + +class ChannelMap: + def __init__(self) -> None: ... + def put(self, chanid: int, chan: Channel) -> None: ... + def get(self, chanid: int) -> Channel: ... + def delete(self, chanid: int) -> None: ... + def values(self) -> list[Channel]: ... + def __len__(self) -> int: ... + +class ServiceRequestingTransport(Transport): + def ensure_session(self) -> None: ... + def get_auth_handler(self) -> AuthOnlyHandler: ... + def auth_password(self, username: str, password: str, fallback: bool = True) -> list[str]: ... # type: ignore[override] + def auth_publickey(self, username: str, key: PKey) -> list[str]: ... # type: ignore[override] diff --git a/stubs/paramiko/paramiko/util.pyi b/stubs/paramiko/paramiko/util.pyi new file mode 100644 index 000000000000..09e4fcc10cc1 --- /dev/null +++ b/stubs/paramiko/paramiko/util.pyi @@ -0,0 +1,45 @@ +from _typeshed import FileDescriptorOrPath, ReadableBuffer +from collections.abc import Iterable +from hashlib import _Hash +from logging import Logger, LogRecord +from types import TracebackType +from typing import AnyStr +from typing_extensions import Self + +from paramiko.config import SSHConfig, SSHConfigDict +from paramiko.hostkeys import HostKeys + +def inflate_long(s: bytes | bytearray, always_positive: bool = False) -> int: ... +def deflate_long(n: int, add_sign_padding: bool = True) -> bytes: ... +def format_binary(data: bytes | bytearray, prefix: str = "") -> list[str]: ... +def format_binary_line(data: bytes | bytearray) -> str: ... +def safe_string(s: Iterable[int | str]) -> bytes: ... +def bit_length(n: int) -> int: ... +def tb_strings() -> list[str]: ... +def generate_key_bytes(hash_alg: type[_Hash], salt: ReadableBuffer, key: bytes | str, nbytes: int) -> bytes: ... +def load_host_keys(filename: FileDescriptorOrPath) -> HostKeys: ... +def parse_ssh_config(file_obj: Iterable[str]) -> SSHConfig: ... +def lookup_ssh_host_config(hostname: str, config: SSHConfig) -> SSHConfigDict: ... +def mod_inverse(x: int, m: int) -> int: ... +def get_thread_id() -> int: ... +def log_to_file(filename: FileDescriptorOrPath, level: int = 10) -> None: ... + +class PFilter: + def filter(self, record: LogRecord) -> bool: ... + +def get_logger(name: str) -> Logger: ... +def constant_time_bytes_eq(a: AnyStr, b: AnyStr) -> bool: ... + +class ClosingContextManager: + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +def clamp_value(minimum: int, val: int, maximum: int) -> int: ... + +# This function attempts to convert objects to bytes, +# *but* just returns the object unchanged if that was unsuccessful! +def asbytes(s: object) -> object: ... +def b(s: str | bytes, encoding: str = "utf8") -> bytes: ... +def u(s: str | bytes, encoding: str = "utf8") -> str: ... diff --git a/stubs/paramiko/paramiko/win_openssh.pyi b/stubs/paramiko/paramiko/win_openssh.pyi new file mode 100644 index 000000000000..bc74d4c21f58 --- /dev/null +++ b/stubs/paramiko/paramiko/win_openssh.pyi @@ -0,0 +1,12 @@ +import sys + +if sys.platform == "win32": + PIPE_NAME: str + + def can_talk_to_agent() -> bool: ... + + class OpenSSHAgentConnection: + def __init__(self) -> None: ... + def send(self, data: bytes) -> int: ... + def recv(self, n: int) -> bytes: ... + def close(self) -> None: ... diff --git a/stubs/paramiko/paramiko/win_pageant.pyi b/stubs/paramiko/paramiko/win_pageant.pyi new file mode 100644 index 000000000000..1f9edee17eae --- /dev/null +++ b/stubs/paramiko/paramiko/win_pageant.pyi @@ -0,0 +1,21 @@ +import ctypes +import sys +from _typeshed import Incomplete +from typing import Literal, TypeAlias + +if sys.platform == "win32": + win32con_WM_COPYDATA: int + def can_talk_to_agent() -> bool: ... + + ULONG_PTR: TypeAlias = ctypes.c_uint64 | ctypes.c_uint32 + + class COPYDATASTRUCT(ctypes.Structure): + num_data: Incomplete + data_size: Incomplete + data_loc: Incomplete + + class PageantConnection: + def __init__(self) -> None: ... + def send(self, data: bytes) -> None: ... + def recv(self, n: int) -> Literal[""] | bytes: ... + def close(self) -> None: ... diff --git a/stubs/parsimonious/@tests/stubtest_allowlist.txt b/stubs/parsimonious/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..abd7877e0cbf --- /dev/null +++ b/stubs/parsimonious/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +parsimonious.nodes.RuleDecoratorMeta.__new__ + +# Tests are shipped with the source, we ignore it: +parsimonious.tests +parsimonious\.tests\..* diff --git a/stubs/parsimonious/METADATA.toml b/stubs/parsimonious/METADATA.toml new file mode 100644 index 000000000000..4cd095524d0e --- /dev/null +++ b/stubs/parsimonious/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.11.*" +upstream-repository = "https://github.com/erikrose/parsimonious" diff --git a/stubs/parsimonious/parsimonious/__init__.pyi b/stubs/parsimonious/parsimonious/__init__.pyi new file mode 100644 index 000000000000..31f99b479767 --- /dev/null +++ b/stubs/parsimonious/parsimonious/__init__.pyi @@ -0,0 +1,8 @@ +from parsimonious.exceptions import ( + BadGrammar as BadGrammar, + IncompleteParseError as IncompleteParseError, + ParseError as ParseError, + UndefinedLabel as UndefinedLabel, +) +from parsimonious.grammar import Grammar as Grammar, TokenGrammar as TokenGrammar +from parsimonious.nodes import NodeVisitor as NodeVisitor, VisitationError as VisitationError, rule as rule diff --git a/stubs/parsimonious/parsimonious/exceptions.pyi b/stubs/parsimonious/parsimonious/exceptions.pyi new file mode 100644 index 000000000000..6b3eb1ac386b --- /dev/null +++ b/stubs/parsimonious/parsimonious/exceptions.pyi @@ -0,0 +1,27 @@ +from parsimonious.expressions import Expression +from parsimonious.grammar import LazyReference +from parsimonious.nodes import Node +from parsimonious.utils import StrAndRepr + +class ParsimoniousError(Exception): ... + +class ParseError(StrAndRepr, ParsimoniousError): + text: str + pos: int + expr: Expression | None + def __init__(self, text: str, pos: int = -1, expr: Expression | None = None) -> None: ... + def line(self) -> int: ... + def column(self) -> int: ... + +class LeftRecursionError(ParseError): ... +class IncompleteParseError(ParseError): ... + +class VisitationError(ParsimoniousError): + original_class: type[BaseException] + def __init__(self, exc: BaseException, exc_class: type[BaseException], node: Node) -> None: ... + +class BadGrammar(StrAndRepr, ParsimoniousError): ... + +class UndefinedLabel(BadGrammar): + label: LazyReference + def __init__(self, label: LazyReference) -> None: ... diff --git a/stubs/parsimonious/parsimonious/expressions.pyi b/stubs/parsimonious/parsimonious/expressions.pyi new file mode 100644 index 000000000000..514768f57b5a --- /dev/null +++ b/stubs/parsimonious/parsimonious/expressions.pyi @@ -0,0 +1,82 @@ +import collections.abc +from collections.abc import Callable, Mapping +from re import Pattern +from typing import Any, TypeAlias +from typing_extensions import Self + +from parsimonious.exceptions import ParseError +from parsimonious.grammar import Grammar +from parsimonious.nodes import Node +from parsimonious.utils import StrAndRepr + +_CALLABLE_RETURN_TYPE: TypeAlias = int | tuple[int, list[Node]] | Node | None +_CALLABLE_TYPE: TypeAlias = ( + Callable[[str, int], _CALLABLE_RETURN_TYPE] + | Callable[[str, int, Mapping[tuple[int, int], Node], ParseError, Grammar], _CALLABLE_RETURN_TYPE] +) + +def is_callable(value: object) -> bool: ... +def expression(callable: _CALLABLE_TYPE, rule_name: str, grammar: Grammar) -> Expression: ... + +IN_PROGRESS: object + +class Expression(StrAndRepr): + __slots__ = ["name", "identity_tuple"] + name: str + identity_tuple: tuple[str] + def __init__(self, name: str = "") -> None: ... + def resolve_refs(self, rule_map: Mapping[str, Expression]) -> Self: ... + def parse(self, text: str, pos: int = 0) -> Node: ... + def match(self, text: str, pos: int = 0) -> Node: ... + def match_core(self, text: str, pos: int, cache: Mapping[tuple[int, int], Node], error: ParseError) -> Node: ... + def as_rule(self) -> str: ... + +class Literal(Expression): + __slots__ = ["literal"] + literal: str + identity_tuple: tuple[str, str] # type: ignore[assignment] + def __init__(self, literal: str, name: str = "") -> None: ... + +class TokenMatcher(Literal): ... + +class Regex(Expression): + __slots__ = ["re"] + re: Pattern[str] + identity_tuple: tuple[str, Pattern[str]] # type: ignore[assignment] + def __init__( + self, + pattern: str, + name: str = "", + ignore_case: bool = False, + locale: bool = False, + multiline: bool = False, + dot_all: bool = False, + unicode: bool = False, + verbose: bool = False, + ascii: bool = False, + ) -> None: ... + +class Compound(Expression): + __slots__ = ["members"] + members: collections.abc.Sequence[Expression] + def __init__(self, *members: Expression, **kwargs: Any) -> None: ... + +class Sequence(Compound): ... +class OneOf(Compound): ... + +class Lookahead(Compound): + __slots__ = ["negativity"] + negativity: bool + def __init__(self, member: Expression, *, negative: bool = False, **kwargs: Any) -> None: ... + +def Not(term: Expression) -> Lookahead: ... + +class Quantifier(Compound): + __slots__ = ["min", "max"] + min: int + max: float + def __init__(self, member: Expression, *, min: int = 0, max: float = ..., name: str = "", **kwargs: Any) -> None: ... + +def ZeroOrMore(member: Expression, name: str = "") -> Quantifier: ... +def OneOrMore(member: Expression, name: str = "", min: int = 1) -> Quantifier: ... +def Optional(member: Expression, name: str = "") -> Quantifier: ... diff --git a/stubs/parsimonious/parsimonious/grammar.pyi b/stubs/parsimonious/parsimonious/grammar.pyi new file mode 100644 index 000000000000..7871c183072c --- /dev/null +++ b/stubs/parsimonious/parsimonious/grammar.pyi @@ -0,0 +1,61 @@ +import collections.abc +from _typeshed import Incomplete +from collections import OrderedDict +from collections.abc import Callable, Mapping +from typing import Any +from typing_extensions import Never + +from parsimonious.expressions import _CALLABLE_TYPE, Expression, Literal, Lookahead, OneOf, Regex, Sequence, TokenMatcher +from parsimonious.nodes import Node, NodeVisitor + +class Grammar(OrderedDict[str, Expression]): + default_rule: Expression | Incomplete + def __init__(self, rules: str = "", **more_rules: Expression | _CALLABLE_TYPE) -> None: ... + def default(self, rule_name: str) -> Grammar: ... + def parse(self, text: str, pos: int = 0) -> Node: ... + def match(self, text: str, pos: int = 0) -> Node: ... + +class TokenGrammar(Grammar): ... +class BootstrappingGrammar(Grammar): ... + +rule_syntax: str + +class LazyReference(str): + name: str + def resolve_refs(self, rule_map: Mapping[str, Expression | LazyReference]) -> Expression: ... + +class RuleVisitor(NodeVisitor[tuple[OrderedDict[str, Expression], Expression | None]]): + quantifier_classes: dict[str, type[Expression]] + visit_expression: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + visit_term: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + visit_atom: Callable[[RuleVisitor, Node, collections.abc.Sequence[Any]], Any] + custom_rules: dict[str, Expression] + def __init__(self, custom_rules: Mapping[str, Expression] | None = None) -> None: ... + def visit_parenthesized(self, node: Node, parenthesized: collections.abc.Sequence[Any]) -> Expression: ... + def visit_quantifier(self, node: Node, quantifier: collections.abc.Sequence[Any]) -> Node: ... + def visit_quantified(self, node: Node, quantified: collections.abc.Sequence[Any]) -> Expression: ... + def visit_lookahead_term(self, node: Node, lookahead_term: collections.abc.Sequence[Any]) -> Lookahead: ... + def visit_not_term(self, node: Node, not_term: collections.abc.Sequence[Any]) -> Lookahead: ... + def visit_rule(self, node: Node, rule: collections.abc.Sequence[Any]) -> Expression: ... + def visit_sequence(self, node: Node, sequence: collections.abc.Sequence[Any]) -> Sequence: ... + def visit_ored(self, node: Node, ored: collections.abc.Sequence[Any]) -> OneOf: ... + def visit_or_term(self, node: Node, or_term: collections.abc.Sequence[Any]) -> Expression: ... + def visit_label(self, node: Node, label: collections.abc.Sequence[Any]) -> str: ... + def visit_reference(self, node: Node, reference: collections.abc.Sequence[Any]) -> LazyReference: ... + def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> Regex: ... + def visit_spaceless_literal(self, spaceless_literal: Node, visited_children: collections.abc.Sequence[Any]) -> Literal: ... + def visit_literal(self, node: Node, literal: collections.abc.Sequence[Any]) -> Literal: ... + def generic_visit( + self, node: Node, visited_children: collections.abc.Sequence[Any] + ) -> collections.abc.Sequence[Any] | Node: ... + def visit_rules( + self, node: Node, rules_list: collections.abc.Sequence[Any] + ) -> tuple[OrderedDict[str, Expression], Expression | None]: ... + +class TokenRuleVisitor(RuleVisitor): + def visit_spaceless_literal( + self, spaceless_literal: Node, visited_children: collections.abc.Sequence[Any] + ) -> TokenMatcher: ... + def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> Never: ... + +rule_grammar: Grammar diff --git a/stubs/parsimonious/parsimonious/nodes.pyi b/stubs/parsimonious/parsimonious/nodes.pyi new file mode 100644 index 000000000000..1d67f2f2fd0c --- /dev/null +++ b/stubs/parsimonious/parsimonious/nodes.pyi @@ -0,0 +1,48 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterator, Sequence +from re import Match +from typing import Any, Generic, TypeVar + +from parsimonious.exceptions import VisitationError as VisitationError +from parsimonious.expressions import Expression +from parsimonious.grammar import Grammar + +class Node: + __slots__ = ["expr", "full_text", "start", "end", "children"] + expr: Expression + full_text: str + start: int + end: int + children: Sequence[Node] + def __init__( + self, expr: Expression, full_text: str, start: int, end: int, children: Sequence[Node] | None = None + ) -> None: ... + @property + def expr_name(self) -> str: ... + def __iter__(self) -> Iterator[Node]: ... + @property + def text(self) -> str: ... + def prettily(self, error: Node | None = None) -> str: ... + def __repr__(self, top_level: bool = True) -> str: ... + +class RegexNode(Node): + __slots__ = ["match"] + match: Match[str] + +class RuleDecoratorMeta(type): ... + +_VisitResultT = TypeVar("_VisitResultT") +_ChildT = TypeVar("_ChildT") + +class NodeVisitor(Generic[_VisitResultT], metaclass=RuleDecoratorMeta): + grammar: Grammar | Incomplete + unwrapped_exceptions: tuple[type[BaseException], ...] + def visit(self, node: Node) -> _VisitResultT: ... + def generic_visit(self, node: Node, visited_children: Sequence[Any]): ... + def parse(self, text: str, pos: int = 0) -> _VisitResultT: ... + def match(self, text: str, pos: int = 0) -> _VisitResultT: ... + def lift_child(self, node: Node, children: Sequence[_ChildT]) -> _ChildT: ... + +_CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) + +def rule(rule_string: str) -> Callable[[_CallableT], _CallableT]: ... diff --git a/stubs/parsimonious/parsimonious/utils.pyi b/stubs/parsimonious/parsimonious/utils.pyi new file mode 100644 index 000000000000..b9440d08abca --- /dev/null +++ b/stubs/parsimonious/parsimonious/utils.pyi @@ -0,0 +1,11 @@ +import ast +from typing import Any + +class StrAndRepr: ... + +def evaluate_string(string: str | ast.AST) -> Any: ... + +class Token(StrAndRepr): + __slots__ = ["type"] + type: str + def __init__(self, type: str) -> None: ... diff --git a/stubs/passpy/@tests/stubtest_allowlist.txt b/stubs/passpy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f7e53b666830 --- /dev/null +++ b/stubs/passpy/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +passpy.__main__ + +# Uses `git` dependency: +passpy.git +# Uses `gpg` dependency: +passpy.gpg diff --git a/stubs/passpy/METADATA.toml b/stubs/passpy/METADATA.toml new file mode 100644 index 000000000000..e72164f1cb04 --- /dev/null +++ b/stubs/passpy/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.0.*" +upstream-repository = "https://github.com/bfrascher/passpy" diff --git a/stubs/passpy/passpy/__init__.pyi b/stubs/passpy/passpy/__init__.pyi new file mode 100644 index 000000000000..98430cc71676 --- /dev/null +++ b/stubs/passpy/passpy/__init__.pyi @@ -0,0 +1,5 @@ +from .exceptions import RecursiveCopyMoveError as RecursiveCopyMoveError, StoreNotInitialisedError as StoreNotInitialisedError +from .store import Store as Store +from .util import gen_password as gen_password + +VERSION: str diff --git a/stubs/passpy/passpy/exceptions.pyi b/stubs/passpy/passpy/exceptions.pyi new file mode 100644 index 000000000000..f3a532d6c274 --- /dev/null +++ b/stubs/passpy/passpy/exceptions.pyi @@ -0,0 +1,2 @@ +class StoreNotInitialisedError(FileNotFoundError): ... +class RecursiveCopyMoveError(OSError): ... diff --git a/stubs/passpy/passpy/store.pyi b/stubs/passpy/passpy/store.pyi new file mode 100644 index 000000000000..e906bbe38280 --- /dev/null +++ b/stubs/passpy/passpy/store.pyi @@ -0,0 +1,31 @@ +from _typeshed import StrPath +from collections.abc import Iterator +from re import Match + +class Store: + def __init__( + self, + gpg_bin: str = "gpg2", + git_bin: str = "git", + store_dir: str = "~/.password-store", + use_agent: bool = True, + interactive: bool = False, + verbose: bool = False, + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def is_init(self) -> bool: ... + def init_store(self, gpg_ids: None | str | list[str], path: StrPath | None = None) -> None: ... + def init_git(self) -> None: ... + def git(self, method: str, *args: object, **kwargs: object) -> None: ... + def get_key(self, path: StrPath | None) -> str | None: ... + def set_key(self, path: StrPath | None, key_data: str, force: bool = False) -> None: ... + def remove_path(self, path: StrPath, recursive: bool = False, force: bool = False) -> None: ... + def gen_key( + self, path: StrPath | None, length: int, symbols: bool = True, force: bool = False, inplace: bool = False + ) -> str | None: ... + def copy_path(self, old_path: StrPath, new_path: StrPath, force: bool = False) -> None: ... + def move_path(self, old_path: StrPath, new_path: StrPath, force: bool = False) -> None: ... + def list_dir(self, path: StrPath) -> tuple[list[str], list[str]]: ... + def iter_dir(self, path: StrPath) -> Iterator[str]: ... + def find(self, names: None | str | list[str]) -> list[str]: ... + def search(self, term: str) -> dict[str, list[tuple[str, Match[str]]]]: ... diff --git a/stubs/passpy/passpy/util.pyi b/stubs/passpy/passpy/util.pyi new file mode 100644 index 000000000000..137b613f8916 --- /dev/null +++ b/stubs/passpy/passpy/util.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +_C = TypeVar("_C", bound=Callable[..., Any]) + +# Technically, the first argument of `_C` must be `Store`, +# but for now we leave it simple: +def initialised(func: _C) -> _C: ... +def trap(path_index: str | int) -> Callable[[_C], _C]: ... +def gen_password(length: int, symbols: bool = True) -> str: ... +def copy_move( + src: str, dst: str, force: bool = False, move: bool = False, interactive: bool = False, verbose: bool = False +) -> str | None: ... diff --git a/stubs/peewee/@tests/stubtest_allowlist.txt b/stubs/peewee/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..63e6f01a49f3 --- /dev/null +++ b/stubs/peewee/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# Stubtest doesn't recognize __ as indicating positional-only arg at runtime +# https://github.com/python/mypy/issues/15302 +peewee.Model.insert +peewee.Model.replace +peewee.Model.update + +# Wrapped with @Node.copy which changes the signature to "def (self, *args, **kwargs)" +peewee.DQ.__invert__ +peewee.Window.as_groups +peewee.Window.as_range +peewee.Window.as_rows +peewee._ModelQueryHelper.models + +# Wrapped with @database_required which sometimes injects the database argument +peewee.BaseQuery.execute +peewee.CompoundSelectQuery.exists +peewee.SelectBase.count +peewee.SelectBase.exists +peewee.SelectBase.first +peewee.SelectBase.get +peewee.SelectBase.peek +peewee.SelectBase.scalar +peewee.SelectBase.scalars + +# Descriptor methods exist on FieldAccessor at runtime, but are declared on the +# generic Field classes in the stub so that `instance.field` resolves to the +# field's Python value and `Model.field` resolves to the field (for queries). +peewee.Field.__get__ +peewee.Field.__set__ +# BigBitField overrides __get__ to yield a BigBitFieldData wrapper, not bytes. +peewee.BigBitField.__get__ +peewee.Field.__init__ +# These fields take named constructor args, carried by their __new__ overloads. +peewee.CharField.__init__ +peewee.ForeignKeyField.__init__ +peewee.DecimalField.__init__ +peewee.IdentityField.__init__ + +# Ignore missing playhouse modules and names we don't currently provide +playhouse\.\w+? +playhouse.flask_utils.PaginatedQuery +playhouse.flask_utils.get_\w+ +playhouse.flask_utils.object_list diff --git a/stubs/peewee/@tests/test_cases/check_fields.py b/stubs/peewee/@tests/test_cases/check_fields.py new file mode 100644 index 000000000000..9caafac908a5 --- /dev/null +++ b/stubs/peewee/@tests/test_cases/check_fields.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from peewee import BigBitField, BigBitFieldData, CharField, ForeignKeyField, IntegerField, Model + + +class User(Model): + username = CharField() + age = IntegerField() + nickname = CharField(null=True) + + +class Tweet(Model): + user = ForeignKeyField(User) + author = ForeignKeyField(User, null=True) + + +class Event(Model): + flags = BigBitField() + + +# A field is a descriptor that resolves differently depending on whether it is +# accessed on the model class or on an instance. `Model.field` is the Field +# object itself (used to build queries), while `instance.field` is the stored +# Python value. +assert_type(User.username, CharField[str]) +assert_type(User().username, str) + +assert_type(User.age, IntegerField[int]) +assert_type(User().age, int) + +# `null=True` allows the value to include None, both in the field's own +# parameterization and in the value produced on attribute access. +assert_type(User.nickname, CharField[str | None]) +assert_type(User().nickname, str | None) + +# Foreign keys resolve to the related model instance, or None when nullable. +assert_type(Tweet.user, ForeignKeyField[User]) +assert_type(Tweet().user, User) +assert_type(Tweet().author, User | None) + +# BigBitField is a special case: the instance descriptor yields a +# BigBitFieldData wrapper rather than the underlying bytes. +assert_type(Event.flags, BigBitField) +assert_type(Event().flags, BigBitFieldData) + +# __set__ accepts the field's value type... +user = User() +user.username = "guido" +user.age = 42 +user.nickname = None # nullable field accepts None + +# ...and rejects incompatible values. +user.age = "not an int" # type: ignore +user.username = None # type: ignore # non-null field rejects None diff --git a/stubs/peewee/METADATA.toml b/stubs/peewee/METADATA.toml new file mode 100644 index 000000000000..c273586ad9dc --- /dev/null +++ b/stubs/peewee/METADATA.toml @@ -0,0 +1,10 @@ +version = "4.3.0" +upstream-repository = "https://github.com/coleifer/peewee" +# We're not providing stubs for all playhouse modules right now +# https://github.com/python/typeshed/pull/11731#issuecomment-2065729058 +partial-stub = true + +[tool.stubtest] +stubtest-dependencies = ["Flask>=2.0.0"] +# Using stubtest_allowlist to ignore playhouse modules we don't provide. +ignore-missing-stub = false diff --git a/stubs/peewee/peewee.pyi b/stubs/peewee/peewee.pyi new file mode 100644 index 000000000000..10a6657b00ab --- /dev/null +++ b/stubs/peewee/peewee.pyi @@ -0,0 +1,2179 @@ +import re +import threading +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator, Iterable, Iterator +from datetime import date, datetime, time +from decimal import Decimal +from types import TracebackType +from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, TypeIs, TypeVar, Unpack +from uuid import UUID + +def callable_(c: object) -> TypeIs[Callable[..., object]]: ... + +multi_types: tuple[type[Incomplete], ...] + +_T = TypeVar("_T") +_VT = TypeVar("_VT") +_F = TypeVar("_F", bound=Callable[..., Any]) +_Model: TypeAlias = Model +_M = TypeVar("_M", bound=Model, default=Model) +# __get__/__set__ value type. Bare Field defaults to Field[Any]. +_V = TypeVar("_V", default=Any) +_DatabaseType: TypeAlias = Database | DatabaseProxy + +# Common field kwargs, Unpack-ed into the field __new__ overloads. +@type_check_only +class _FieldKwargs(TypedDict, total=False): + index: bool + unique: bool + primary_key: bool + column_name: str | None + default: Any # A value matching the field's type, or a callable returning one + constraints: list[Node] | None + sequence: str | None + collation: str | None + unindexed: bool + choices: Iterable[tuple[Any, str]] | None # (value, display) pairs (value type depends on the field) + help_text: str | None + verbose_name: str | None + index_type: str | None + db_column: str | None + +@type_check_only +class _FKKwargs(_FieldKwargs, total=False): + field: Field[Any] | str | None + backref: str | Callable[[Field[Any]], str] | None + on_delete: str | None + on_update: str | None + deferrable: str | None + to_field: Field[Any] | str | None + object_id_name: str | None + lazy_load: bool + constraint_name: str | None + related_name: str | Callable[[Field[Any]], str] | None + rel_model: type[Model] | None + +class attrdict(dict[str, _VT]): + def __getattr__(self, attr: str) -> _VT: ... + def __setattr__(self, attr: str, value: _VT) -> None: ... + # calls dict.update() + def __iadd__(self, rhs: SupportsKeysAndGetItem[str, _VT] | Iterable[tuple[str, _VT]]) -> Self: ... + def __add__(self, rhs: SupportsKeysAndGetItem[str, _VT] | Iterable[tuple[str, _VT]]) -> attrdict[_VT]: ... + +OP: attrdict[str] +DJANGO_MAP: attrdict[Incomplete] +JOIN: attrdict[str] +ROW: attrdict[int] +PREFETCH_TYPE: attrdict[int] +SCOPE_NORMAL: Final = 1 +SCOPE_SOURCE: Final = 2 +SCOPE_VALUES: Final = 4 +SCOPE_CTE: Final = 8 +SCOPE_COLUMN: Final = 16 +CSQ_PARENTHESES_NEVER: Final = 0 +CSQ_PARENTHESES_ALWAYS: Final = 1 +CSQ_PARENTHESES_UNNESTED: Final = 2 +CSQ_PARENTHESES_GROUPED: Final = 3 +CSQ_FLAT: Final = 0 +CSQ_PARENS: Final = 1 +CSQ_WRAP: Final = 2 +SNAKE_CASE_STEP1: Final[re.Pattern[str]] +SNAKE_CASE_STEP2: Final[re.Pattern[str]] +IDENTIFIER_RE: Final[re.Pattern[str]] + +def make_identifier(s: str) -> str: ... +def chunked(it: Iterable[_T], n: int) -> Generator[list[_T]]: ... + +class _callable_context_manager: + def __call__(self, fn): ... + +class Proxy: + __slots__ = ("obj", "_callbacks") + def __init__(self) -> None: ... + obj: Incomplete + def initialize(self, obj) -> None: ... + def attach_callback(self, callback): ... + def passthrough(method): ... + __enter__: Incomplete + __exit__: Incomplete + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + +class DatabaseProxy(Proxy): + __slots__ = ("obj", "_callbacks", "_Model") + def connection_context(self) -> ConnectionContext: ... + def atomic(self, *args, **kwargs) -> _atomic: ... + def manual_commit(self) -> _manual: ... + def transaction(self, *args, **kwargs) -> _transaction: ... + def savepoint(self) -> _savepoint: ... + @property + def Model(self) -> type[_Model]: ... + +class ModelDescriptor: ... + +class AliasManager: + __slots__ = ("_counter", "_current_index", "_mapping") + def __init__(self) -> None: ... + @property + def mapping(self): ... + def add(self, source): ... + def get(self, source, any_depth: bool = False): ... + def __getitem__(self, source): ... + def __setitem__(self, source, alias) -> None: ... + def push(self) -> None: ... + def pop(self) -> None: ... + +class State: + def __new__(cls, scope=1, parentheses: bool = False, **kwargs) -> Self: ... + def __call__(self, scope=None, parentheses=None, **kwargs) -> State: ... + def __getattr__(self, attr_name: str): ... + +class Context: + __slots__ = ("stack", "_sql", "_values", "alias_manager", "state") + stack: list[Incomplete] + alias_manager: AliasManager + state: State + def __init__(self, **settings) -> None: ... + def as_new(self) -> Context: ... + def column_sort_key(self, item): ... + @property + def scope(self): ... + @property + def parentheses(self): ... + @property + def subquery(self): ... + def __call__(self, **overrides) -> Self: ... + scope_normal: Incomplete + scope_source: Incomplete + scope_values: Incomplete + scope_cte: Incomplete + scope_column: Incomplete + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def push_alias(self) -> Generator[None]: ... + def sql(self, obj): ... + def literal(self, keyword) -> Self: ... + def value(self, value, converter=None, add_param: bool = True): ... + def __sql__(self, ctx): ... + def parse(self, node): ... + def query(self) -> tuple[str, list[Incomplete]]: ... + +class Node: + __isabstractmethod__: bool + def clone(self) -> Self: ... + def __sql__(self, ctx): ... + @staticmethod + def copy(method): ... + def coerce(self, _coerce: bool = True) -> Self: ... + def is_alias(self) -> bool: ... + def unwrap(self) -> Self: ... + +class ColumnFactory: + __slots__ = ("node",) + node: Node + def __init__(self, node: Node) -> None: ... + def __getattr__(self, attr: str) -> Column: ... + __getitem__ = __getattr__ + +class _DynamicColumn: + __slots__ = () + def __get__(self, instance, instance_type=None): ... + +class _ExplicitColumn: + __slots__ = () + def __get__(self, instance, instance_type=None) -> Self: ... + +class Star(Node): + def __init__(self, source) -> None: ... + def __sql__(self, ctx): ... + +class Source(Node): + c: Incomplete + def __init__(self, alias=None) -> None: ... + def alias(self, name) -> Self: ... + def select(self, *columns) -> Select: ... + @property + def __star__(self) -> Star: ... + def join(self, dest, join_type="INNER JOIN", on=None) -> Join: ... + def left_outer_join(self, dest, on=None) -> Join: ... + def cte(self, name, recursive: bool = False, columns=None, materialized=None) -> CTE: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def apply_alias(self, ctx): ... + def apply_column(self, ctx): ... + +class _HashableSource: + def __init__(self, *args, **kwargs) -> None: ... + def alias(self, name) -> Self: ... + def clone(self) -> _HashableSource: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + __lt__: Callable[[Self, Any], Expression] + __le__: Callable[[Self, Any], Expression] + __gt__: Callable[[Self, Any], Expression] + __ge__: Callable[[Self, Any], Expression] + +class BaseTable(Source): + def __and__(self, other) -> Join: ... + def __add__(self, other) -> Join: ... + def __sub__(self, other) -> Join: ... + def __or__(self, other) -> Join: ... + def __mul__(self, other) -> Join: ... + def __rand__(self, other) -> Join: ... + def __radd__(self, other) -> Join: ... + def __rsub__(self, other) -> Join: ... + def __ror__(self, other) -> Join: ... + def __rmul__(self, other) -> Join: ... + +class _BoundTableContext(_callable_context_manager): + table: Incomplete + database: Incomplete + def __init__(self, table, database: _DatabaseType) -> None: ... + def __enter__(self): ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Table(_HashableSource, BaseTable): # type: ignore[misc] + __name__: Incomplete + c: Incomplete + primary_key: Incomplete + def __init__( + self, name, columns=None, primary_key=None, schema: str | None = None, alias=None, _model=None, _database=None + ) -> None: ... + def clone(self) -> Table: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... + def bind_ctx(self, database: _DatabaseType | None = None) -> _BoundTableContext: ... + def select(self, *columns) -> Select: ... + def insert(self, insert=None, columns=None, **kwargs) -> Insert: ... + def replace(self, insert=None, columns=None, **kwargs): ... + def update(self, update=None, **kwargs) -> Update: ... + def delete(self) -> Delete: ... + def __sql__(self, ctx): ... + +class Join(BaseTable): + lhs: Incomplete + rhs: Incomplete + join_type: Incomplete + def __init__(self, lhs, rhs, join_type="INNER JOIN", on=None, alias=None) -> None: ... + def on(self, predicate) -> Self: ... + def __sql__(self, ctx): ... + +class ValuesList(_HashableSource, BaseTable): # type: ignore[misc] + def __init__(self, values, columns=None, alias=None) -> None: ... + def columns(self, *names) -> Self: ... + def __sql__(self, ctx): ... + +class CTE(_HashableSource, Source): # type: ignore[misc] + def __init__(self, name, query, recursive: bool = False, columns=None, materialized=None) -> None: ... + def select_from(self, *columns) -> Select: ... + def union_all(self, rhs) -> CTE: ... + __add__ = union_all + def union(self, rhs) -> CTE: ... + __or__ = union + def __sql__(self, ctx): ... + +class ColumnBase(Node): + def converter(self, converter=None) -> Self: ... + def alias(self, alias) -> Alias | Self: ... + def unalias(self) -> Self: ... + def bind_to(self, dest) -> BindTo: ... + def cast(self, as_type) -> Cast: ... + def asc(self, collation=None, nulls=None) -> Ordering: ... + __pos__ = asc + def desc(self, collation=None, nulls=None) -> Ordering: ... + __neg__ = desc + def __invert__(self): ... + __and__: ClassVar[Callable[[Self, Any], Expression]] + __or__: ClassVar[Callable[[Self, Any], Expression]] + def __add__(self, rhs: Any) -> Expression: ... + __sub__: ClassVar[Callable[[Self, Any], Expression]] + __mul__: ClassVar[Callable[[Self, Any], Expression]] + __truediv__: ClassVar[Callable[[Self, Any], Expression]] + __xor__: ClassVar[Callable[[Self, Any], Expression]] + def __radd__(self, rhs: Any) -> Expression: ... + __rsub__: ClassVar[Callable[[Self, Any], Expression]] + __rmul__: ClassVar[Callable[[Self, Any], Expression]] + __rtruediv__: ClassVar[Callable[[Self, Any], Expression]] + __rand__: ClassVar[Callable[[Self, Any], Expression]] + __ror__: ClassVar[Callable[[Self, Any], Expression]] + __rxor__: ClassVar[Callable[[Self, Any], Expression]] + def __eq__(self, rhs) -> Expression: ... # type: ignore[override] + def __ne__(self, rhs) -> Expression: ... # type: ignore[override] + __lt__: ClassVar[Callable[[Self, Any], Expression]] + __le__: ClassVar[Callable[[Self, Any], Expression]] + __gt__: ClassVar[Callable[[Self, Any], Expression]] + __ge__: ClassVar[Callable[[Self, Any], Expression]] + __lshift__: ClassVar[Callable[[Self, Any], Expression]] + __rshift__: ClassVar[Callable[[Self, Any], Expression]] + __mod__: ClassVar[Callable[[Self, Any], Expression]] + __pow__: ClassVar[Callable[[Self, Any], Expression]] + like: ClassVar[Callable[[Self, Any], Expression]] + ilike: ClassVar[Callable[[Self, Any], Expression]] + bin_and: ClassVar[Callable[[Self, Any], Expression]] + bin_or: ClassVar[Callable[[Self, Any], Expression]] + in_: ClassVar[Callable[[Self, Any], Expression]] + not_in: ClassVar[Callable[[Self, Any], Expression]] + regexp: ClassVar[Callable[[Self, Any], Expression]] + iregexp: ClassVar[Callable[[Self, Any], Expression]] + def is_null(self, is_null: bool = True) -> Expression: ... + def contains(self, rhs) -> Expression: ... + def startswith(self, rhs) -> Expression: ... + def endswith(self, rhs) -> Expression: ... + def between(self, lo, hi) -> Expression: ... + def concat(self, rhs) -> StringExpression: ... + def __getitem__(self, item): ... + __iter__: Incomplete + def distinct(self) -> NodeList: ... + def collate(self, collation) -> NodeList: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + +class Column(ColumnBase): + source: Incomplete + name: Incomplete + def __init__(self, source, name) -> None: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + +class WrappedNode(ColumnBase): + node: Incomplete + def __init__(self, node) -> None: ... + def is_alias(self) -> bool: ... + def unwrap(self): ... + +class EntityFactory: + __slots__ = ("node",) + node: Incomplete + def __init__(self, node) -> None: ... + def __getattr__(self, attr: str) -> Entity: ... + +class _DynamicEntity: + __slots__ = () + def __get__(self, instance, instance_type=None): ... + +class Alias(WrappedNode): + c: Incomplete + def __init__(self, node, alias) -> None: ... + def __hash__(self) -> int: ... + + @property + def name(self): ... + @name.setter + def name(self, value) -> None: ... + + def alias(self, alias=None): ... + def unalias(self): ... + def is_alias(self) -> bool: ... + def __sql__(self, ctx): ... + +class BindTo(WrappedNode): + dest: Incomplete + def __init__(self, node, dest) -> None: ... + def __sql__(self, ctx): ... + +class Negated(WrappedNode): + def __invert__(self): ... + def __sql__(self, ctx): ... + +class BitwiseMixin: + def __and__(self, other) -> Expression: ... + def __or__(self, other) -> Expression: ... + def __sub__(self, other) -> Expression: ... + def __invert__(self) -> BitwiseNegated: ... + +class BitwiseNegated(BitwiseMixin, WrappedNode): + op: str + def __invert__(self): ... + def __sql__(self, ctx): ... + +class Value(ColumnBase): + value: Incomplete + converter: Incomplete + multi: bool + values: list[Incomplete] | None + def __init__(self, value, converter=None, unpack: bool = True) -> None: ... + def __sql__(self, ctx): ... + +class ValueLiterals(WrappedNode): + def __sql__(self, ctx): ... + +def AsIs(value, converter=None) -> Value: ... + +class Cast(WrappedNode): + def __init__(self, node, cast) -> None: ... + def __sql__(self, ctx): ... + +class Ordering(WrappedNode): + direction: Incomplete + collation: Incomplete + nulls: Incomplete + def __init__(self, node, direction, collation=None, nulls=None) -> None: ... + def collate(self, collation=None) -> Self: ... # type: ignore[override] + def __sql__(self, ctx): ... + +def Asc(node, collation=None, nulls=None) -> Ordering: ... +def Desc(node, collation=None, nulls=None) -> Ordering: ... + +class Expression(ColumnBase): + lhs: Incomplete + op: Incomplete + rhs: Incomplete + flat: bool + def __init__(self, lhs, op, rhs, flat: bool = False) -> None: ... + def __sql__(self, ctx): ... + +class StringExpression(Expression): + def __add__(self, rhs) -> StringExpression: ... + def __radd__(self, lhs) -> StringExpression: ... + +class Entity(ColumnBase): + def __init__(self, *path) -> None: ... + def __getattr__(self, attr: str) -> Entity: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + +class SQL(ColumnBase): + sql: Incomplete + params: Incomplete + def __init__(self, sql, params=None) -> None: ... + def __sql__(self, ctx): ... + +def Check(constraint: str, name: str | None = None) -> SQL | NodeList: ... +def Default(value) -> SQL: ... + +class Function(ColumnBase): + no_coerce_functions: ClassVar[set[str]] + name: str | None + arguments: tuple[Any, ...] | None # Positional SQL function args: values, columns, or other nodes + def __init__(self, name, arguments, coerce: bool = True, python_value=None) -> None: ... + # fn.COUNT(...), fn.SUM(...), etc. each build a Function node. + def __getattr__(self, attr: str) -> Callable[..., Function]: ... + def filter(self, where=None) -> Self: ... + def order_by(self, *ordering) -> Self: ... + def python_value(self, func=None) -> Self: ... + def over( + self, partition_by=None, order_by=None, start=None, end=None, frame_type=None, window=None, exclude=None + ) -> NodeList: ... + def __sql__(self, ctx): ... + +fn: Function + +class Window(Node): + CURRENT_ROW: SQL + GROUP: SQL + TIES: SQL + NO_OTHERS: SQL + GROUPS: str + RANGE: str + ROWS: str + partition_by: Incomplete + order_by: Incomplete + start: Incomplete + end: Incomplete + frame_type: Incomplete + def __init__( + self, + partition_by=None, + order_by=None, + start=None, + end=None, + frame_type=None, + extends=None, + exclude=None, + alias=None, + _inline: bool = False, + ) -> None: ... + def alias(self, alias=None) -> Self: ... + def as_range(self) -> Self: ... + def as_rows(self) -> Self: ... + def as_groups(self) -> Self: ... + def extends(self, window=None) -> Self: ... + def exclude(self, frame_exclusion=None) -> Self: ... + @staticmethod + def following(value=None) -> SQL: ... + @staticmethod + def preceding(value=None) -> SQL: ... + def __sql__(self, ctx): ... + +class WindowAlias(Node): + window: Incomplete + def __init__(self, window) -> None: ... + def alias(self, window_alias) -> Self: ... + def __sql__(self, ctx): ... + +class ForUpdate(Node): + def __init__(self, expr, of=None, nowait: bool | None = None, skip_locked: bool | None = None) -> None: ... + def __sql__(self, ctx): ... + +class Case(ColumnBase): + predicate: Incomplete + expression_tuples: Incomplete + default: Incomplete | None + def __init__(self, predicate, expression_tuples, default=None) -> None: ... + def __sql__(self, ctx): ... + +class NodeList(ColumnBase): + nodes: Incomplete + glue: Incomplete + parens: bool + def __init__(self, nodes, glue: str = " ", parens: bool = False) -> None: ... + def __sql__(self, ctx): ... + +def CommaNodeList(nodes) -> NodeList: ... +def EnclosedNodeList(nodes) -> NodeList: ... + +class _Namespace(Node): + __slots__ = ("_name",) + def __init__(self, name) -> None: ... + def __getattr__(self, attr: str) -> NamespaceAttribute: ... + __getitem__ = __getattr__ + +class NamespaceAttribute(ColumnBase): + def __init__(self, namespace, attribute) -> None: ... + def __sql__(self, ctx): ... + +EXCLUDED: Incomplete + +class DQ(ColumnBase): + query: Incomplete + def __init__(self, **query) -> None: ... + def __invert__(self) -> Self: ... # type: ignore[override] + def clone(self) -> DQ: ... + +Tuple: Incomplete + +class QualifiedNames(WrappedNode): + def __init__(self, node, scope: int = 16) -> None: ... + def __sql__(self, ctx): ... + +class OnConflict(Node): + def __init__( + self, + action=None, + update=None, + preserve=None, + where=None, + conflict_target=None, + conflict_where=None, + conflict_constraint=None, + ) -> None: ... + def get_conflict_statement(self, ctx, query): ... + def get_conflict_update(self, ctx, query): ... + def preserve(self, *columns) -> Self: ... + def update(self, _data=None, **kwargs) -> Self: ... + def where(self, *expressions) -> Self: ... + def conflict_target(self, *constraints) -> Self: ... + def conflict_where(self, *expressions) -> Self: ... + def conflict_constraint(self, constraint) -> Self: ... + +class BaseQuery(Node): + default_row_type: Incomplete + def __init__(self, _database=None, **kwargs) -> None: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... + def clone(self) -> Self: ... + def dicts(self, as_dict: bool = True) -> Self: ... + def tuples(self, as_tuple: bool = True) -> Self: ... + def namedtuples(self, as_namedtuple: bool = True) -> Self: ... + def objects(self, constructor=None) -> Self: ... + def __sql__(self, ctx) -> None: ... + def sql(self) -> tuple[str, list[Any]]: ... # Returns (sql, params), params are bound query values + def execute(self, database: _DatabaseType | None = None): ... + async def aexecute(self, database: _DatabaseType | None = None): ... + def iterator(self, database: _DatabaseType | None = None): ... + def __iter__(self): ... + def __getitem__(self, value): ... + def __len__(self) -> int: ... + +class RawQuery(BaseQuery): + def __init__(self, sql=None, params=None, **kwargs) -> None: ... + def __sql__(self, ctx): ... + +class Query(BaseQuery): + def __init__(self, where=None, order_by=None, limit=None, offset=None, **kwargs) -> None: ... + def with_cte(self, *cte_list) -> Self: ... + def where(self, *expressions) -> Self: ... + def orwhere(self, *expressions) -> Self: ... + def order_by(self, *values) -> Self: ... + def order_by_extend(self, *values) -> Self: ... + def limit(self, value=None) -> Self: ... + def offset(self, value=None) -> Self: ... + def paginate(self, page, paginate_by: int = 20) -> Self: ... + def __sql__(self, ctx): ... + +class SelectQuery(Query): + def union_all(self, other) -> CompoundSelectQuery: ... + def __add__(self, other) -> CompoundSelectQuery: ... + def union(self, other) -> CompoundSelectQuery: ... + def __or__(self, other) -> CompoundSelectQuery: ... + def intersect(self, other) -> CompoundSelectQuery: ... + def __and__(self, other) -> CompoundSelectQuery: ... + def except_(self, other) -> CompoundSelectQuery: ... + def __sub__(self, other) -> CompoundSelectQuery: ... + def __radd__(self, other) -> CompoundSelectQuery: ... + def __ror__(self, other) -> CompoundSelectQuery: ... + def __rand__(self, other) -> CompoundSelectQuery: ... + def __rsub__(self, other) -> CompoundSelectQuery: ... + def select_from(self, *columns) -> Select: ... + +class SelectBase(_HashableSource, Source, SelectQuery): # type: ignore[misc] + def peek(self, database: _DatabaseType | None = None, n: int = 1): ... + def first(self, database: _DatabaseType | None = None, n: int = 1): ... + def scalar(self, database: _DatabaseType | None = None, as_tuple: bool = False, as_dict: bool = False): ... + def scalars(self, database: _DatabaseType | None = None) -> Generator[Incomplete]: ... + def count(self, database: _DatabaseType | None = None, clear_limit: bool = False) -> int: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... + def get(self, database: _DatabaseType | None = None): ... + +class CompoundSelectQuery(SelectBase): + lhs: Incomplete + op: Incomplete + rhs: Incomplete + def __init__(self, lhs, op, rhs) -> None: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... + def __sql__(self, ctx): ... + +class Select(SelectBase): + def __init__( + self, + from_list=None, + columns=None, + group_by=None, + having=None, + distinct=None, + windows=None, + for_update=None, + lateral=None, + **kwargs, + ) -> None: ... + def clone(self) -> Self: ... + def columns(self, *columns) -> Self: ... + select = columns + def select_extend(self, *columns) -> Self: ... + + @property + def selected_columns(self): ... + @selected_columns.setter + def selected_columns(self, value) -> None: ... + + def from_(self, *sources) -> Self: ... + def join(self, dest, join_type="INNER JOIN", on=None) -> Self: ... # type: ignore[override] + def left_outer_join(self, dest, on=None) -> Self: ... # type: ignore[override] + def group_by(self, *columns) -> Self: ... + def group_by_extend(self, *values) -> Self: ... + def having(self, *expressions) -> Self: ... + def distinct(self, *columns) -> Self: ... + def window(self, *windows) -> Self: ... + def for_update( + self, for_update: bool = True, of=None, nowait: bool | None = None, skip_locked: bool | None = None + ) -> Self: ... + def lateral(self, lateral: bool = True) -> Self: ... + def __sql_selection__(self, ctx, is_subquery: bool = False): ... + def __sql__(self, ctx): ... + +class _WriteQuery(Query): + table: Incomplete + def __init__(self, table, returning=None, **kwargs) -> None: ... + def cte(self, name, recursive: bool = False, columns=None, materialized=None) -> CTE: ... + def returning(self, *returning) -> Self: ... + def apply_returning(self, ctx): ... + def execute_returning(self, database: _DatabaseType): ... + def handle_result(self, database: _DatabaseType, cursor): ... + def __sql__(self, ctx): ... + +class Update(_WriteQuery): + def __init__(self, table, update=None, **kwargs) -> None: ... + def from_(self, *sources) -> Self: ... + def __sql__(self, ctx): ... + +class Insert(_WriteQuery): + SIMPLE: int + QUERY: int + MULTI: int + + class DefaultValuesException(Exception): ... + + def __init__(self, table, insert=None, columns=None, on_conflict=None, **kwargs) -> None: ... + def where(self, *expressions): ... + def as_rowcount(self, _as_rowcount: bool = True) -> Self: ... + def on_conflict_ignore(self, ignore: bool = True) -> Self: ... + def on_conflict_replace(self, replace: bool = True) -> Self: ... + def on_conflict(self, *args, **kwargs) -> Self: ... + def get_default_data(self): ... + def get_default_columns(self) -> list[Incomplete] | None: ... + def __sql__(self, ctx): ... + def handle_result(self, database: _DatabaseType, cursor): ... + +class Delete(_WriteQuery): + def __sql__(self, ctx): ... + +class Index(Node): + def __init__( + self, name, table, expressions, unique: bool = False, safe: bool = False, where=None, using=None, nulls_distinct=None + ) -> None: ... + def safe(self, _safe: bool = True) -> Self: ... + def where(self, *expressions) -> Self: ... + def using(self, _using=None) -> Self: ... + def nulls_distinct(self, nulls_distinct=None) -> Self: ... + def __sql__(self, ctx): ... + +class ModelIndex(Index): + def __init__( + self, model, fields, unique: bool = False, safe: bool = True, where=None, using=None, name=None, nulls_distinct=None + ) -> None: ... + +class PeeweeException(Exception): + def __init__(self, *args) -> None: ... + +class ImproperlyConfigured(PeeweeException): ... +class DatabaseError(PeeweeException): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InterfaceError(PeeweeException): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... + +class ExceptionWrapper: + __slots__ = ("exceptions",) + exceptions: Incomplete + def __init__(self, exceptions) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + +class IndexMetadata(NamedTuple): + name: Incomplete + sql: Incomplete + columns: Incomplete + unique: Incomplete + table: Incomplete + +class ColumnMetadata(NamedTuple): + name: Incomplete + data_type: Incomplete + null: Incomplete + primary_key: Incomplete + table: Incomplete + default: Incomplete + full_type: str | None = None + identity: bool = False + +class ForeignKeyMetadata(NamedTuple): + column: Incomplete + dest_table: Incomplete + dest_column: Incomplete + table: Incomplete + name: str | None = None + on_delete: str | None = None + on_update: str | None = None + +class ViewMetadata(NamedTuple): + name: Incomplete + sql: Incomplete + +class _ConnectionState: + def __init__(self, **kwargs) -> None: ... + closed: bool + conn: Incomplete + ctx: Incomplete + transactions: Incomplete + def reset(self) -> None: ... + def set_connection(self, conn) -> None: ... + +class _ConnectionLocal(_ConnectionState, threading.local): ... + +class _NoopLock: + __slots__ = () + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class ConnectionContext(_callable_context_manager): + __slots__ = ("db",) + db: Incomplete + def __init__(self, db) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Database(_callable_context_manager): + context_class: Incomplete + json_methods: Incomplete + field_types: Incomplete + operations: Incomplete + param: str + quote: str + server_version: Incomplete + compound_select_parentheses: Incomplete + for_update: bool + index_schema_prefix: bool + index_using_precedes_table: bool + index_value_literals: bool + limit_max: int | None + nulls_ordering: bool + returning_clause: bool + safe_create_index: bool + safe_drop_index: bool + sequences: bool + truncate_table: bool + autoconnect: Incomplete + thread_safe: Incomplete + connect_params: Incomplete + def __deepcopy__(self, memo: Any) -> Self: ... + def __init__( + self, + database: str | None, + thread_safe: bool = True, + autorollback: bool = False, + field_types=None, + operations=None, + autocommit=None, + autoconnect: bool = True, + **kwargs, + ) -> None: ... + database: Incomplete + deferred: Incomplete + def init(self, database: str | None, **kwargs) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def connection_context(self) -> ConnectionContext: ... + def connect(self, reuse_if_open: bool = False) -> bool: ... + def close(self) -> bool: ... + def is_closed(self) -> bool: ... + def is_connection_usable(self) -> bool: ... + def connection(self): ... + def cursor(self, named_cursor=None): ... + def execute_sql(self, sql, params=None): ... + def execute(self, query, **context_options): ... + def get_context_options(self) -> dict[str, Incomplete]: ... + def get_sql_context(self, **context_options) -> context_class: ... # pyrefly: ignore [unknown-name] + def conflict_statement(self, on_conflict, query): ... + def conflict_update(self, on_conflict, query): ... + def last_insert_id(self, cursor, query_type=None): ... + def rows_affected(self, cursor): ... + def default_values_insert(self, ctx): ... + def session_start(self) -> _transaction: ... + def session_commit(self) -> bool: ... + def session_rollback(self) -> bool: ... + def in_transaction(self) -> bool: ... + def push_transaction(self, transaction) -> None: ... + def pop_transaction(self): ... + def transaction_depth(self) -> int: ... + def top_transaction(self): ... + def atomic(self, *args, **kwargs) -> _atomic: ... + def manual_commit(self) -> _manual: ... + def transaction(self, *args, **kwargs) -> _transaction: ... + def savepoint(self) -> _savepoint: ... + def begin(self) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def batch_commit(self, it, n) -> Generator[Incomplete]: ... + def table_exists(self, table_name, schema: str | None = None) -> bool: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None): ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def sequence_exists(self, seq) -> bool: ... + def create_tables(self, models: Iterable[type[_Model]], **options) -> None: ... + def drop_tables(self, models: Iterable[type[_Model]], **kwargs) -> None: ... + def extract_date(self, date_part, date_field): ... + def truncate_date(self, date_part, date_field): ... + def to_timestamp(self, date_field): ... + def from_timestamp(self, date_field): ... + def random(self): ... + def bind(self, models: Iterable[type[_Model]], bind_refs: bool = True, bind_backrefs: bool = True) -> None: ... + def bind_ctx( + self, models: Iterable[type[_Model]], bind_refs: bool = True, bind_backrefs: bool = True + ) -> _BoundModelsContext: ... + def get_noop_select(self, ctx): ... + @property + def Model(self) -> type[_Model]: ... + +class SqliteDatabase(Database): + field_types: Incomplete + operations: Incomplete + index_schema_prefix: bool + index_value_literals: bool + limit_max: int + server_version: Incomplete + truncate_table: bool + nulls_ordering: bool + def __init__( + self, database: str | None, pragmas=None, regexp_function: bool = False, rank_functions: bool = False, *args, **kwargs + ) -> None: ... + returning_clause: Incomplete + def init(self, database: str | None, pragmas=None, timeout: int = 5, returning_clause=None, **kwargs) -> None: ... + def pragma(self, key, value=..., permanent: bool = False, schema: str | None = None): ... + cache_size: Incomplete + foreign_keys: Incomplete + journal_mode: Incomplete + journal_size_limit: Incomplete + mmap_size: Incomplete + page_size: Incomplete + read_uncommitted: Incomplete + synchronous: Incomplete + wal_autocheckpoint: Incomplete + application_id: Incomplete + user_version: Incomplete + data_version: Incomplete + + @property + def timeout(self): ... + @timeout.setter + def timeout(self, seconds) -> None: ... + + def register_aggregate(self, klass, name=None, num_params: int = -1) -> None: ... + def aggregate(self, name=None, num_params: int = -1): ... + def register_collation(self, fn, name=None) -> None: ... + def collation(self, name=None): ... + def register_function(self, fn, name: str | None = None, num_params: int = -1, deterministic: bool | None = None) -> None: ... + def func(self, name: str | None = None, num_params: int = -1, deterministic: bool | None = None) -> Callable[[_F], _F]: ... + def register_window_function(self, klass, name=None, num_params: int = -1) -> None: ... + def window_function(self, name=None, num_params: int = -1): ... + def unregister_aggregate(self, name) -> None: ... + def unregister_collation(self, name) -> None: ... + def unregister_function(self, name) -> None: ... + def unregister_window_function(self, name) -> None: ... + def load_extension(self, extension) -> None: ... + def unload_extension(self, extension) -> None: ... + def attach(self, filename, name) -> bool: ... + def detach(self, name) -> bool: ... + def begin(self, lock_type=None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def get_binary_type(self): ... + def conflict_statement(self, on_conflict, query) -> SQL | None: ... + def conflict_update(self, oc, query) -> SQL | NodeList | None: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def to_timestamp(self, date_field) -> Cast: ... + def from_timestamp(self, date_field) -> Function: ... + +class _BasePsycopgAdapter: + isolation_levels: dict[int, str] + isolation_levels_inv: dict[str, int] + def __init__(self) -> None: ... + + @overload + def isolation_level_int(self, isolation_level: str) -> int: ... + @overload + def isolation_level_int(self, isolation_level: _T) -> _T: ... + + @overload + def isolation_level_str(self, isolation_level: int) -> str: ... + @overload + def isolation_level_str(self, isolation_level: _T) -> _T: ... + + def server_side_cursor(self, conn): ... + +class Psycopg2Adapter(_BasePsycopgAdapter): + json_type: Incomplete + jsonb_type: Incomplete + cast_json_case: bool + def __init__(self) -> None: ... + def check_driver(self) -> None: ... + def get_binary_type(self) -> type[Incomplete]: ... + def connect(self, db, **params): ... + def get_server_version(self, conn): ... + def is_connection_usable(self, conn) -> bool: ... + def is_connection_reusable(self, conn) -> bool: ... + def is_connection_closed(self, conn) -> bool: ... + +class Psycopg3Adapter(_BasePsycopgAdapter): + json_type: Incomplete + jsonb_type: Incomplete + cast_json_case: bool + def __init__(self) -> None: ... + def check_driver(self) -> None: ... + def get_binary_type(self) -> type[Incomplete]: ... + def connect(self, db, **params): ... + def get_server_version(self, conn): ... + def is_connection_usable(self, conn) -> bool: ... + def is_connection_reusable(self, conn) -> bool: ... + def is_connection_closed(self, conn) -> bool: ... + +class PostgresqlDatabase(Database): + field_types: Incomplete + operations: Incomplete + param: str + compound_select_parentheses: Incomplete + for_update: bool + nulls_ordering: bool + returning_clause: bool + sequences: bool + psycopg2_adapter: Incomplete + psycopg3_adapter: Incomplete + def init( + self, + database: str | None, + register_unicode: bool = True, + encoding=None, + isolation_level=None, + *, + prefer_psycopg3: bool = False, + **kwargs, + ) -> None: ... + def is_connection_usable(self) -> bool: ... + def begin(self, isolation_level: str | None = None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def sequence_exists(self, sequence) -> bool: ... + def get_binary_type(self) -> type[Incomplete]: ... + def conflict_statement(self, on_conflict, query) -> None: ... + def conflict_update(self, oc, query) -> NodeList: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def interval(self, val) -> NodeList: ... + def to_timestamp(self, date_field) -> Function: ... + def from_timestamp(self, date_field) -> Function: ... + def get_noop_select(self, ctx): ... + def set_time_zone(self, timezone) -> None: ... + def set_isolation_level(self, isolation_level: int | str) -> None: ... + +class MySQLDatabase(Database): + field_types: Incomplete + operations: Incomplete + param: str + quote: str + compound_select_parentheses: Incomplete + for_update: bool + index_using_precedes_table: bool + limit_max: Incomplete + safe_create_index: bool + safe_drop_index: bool + sql_mode: str + mariadb: bool + def init(self, database: str | None, mariadb: bool | None = None, **kwargs) -> None: ... + def is_connection_usable(self) -> bool: ... + def default_values_insert(self, ctx): ... + def begin(self, isolation_level: str | None = None) -> None: ... + def get_tables(self, schema: str | None = None) -> list[str]: ... + def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... + def get_indexes(self, table, schema: str | None = None) -> list[IndexMetadata]: ... + def get_columns(self, table, schema: str | None = None) -> list[ColumnMetadata]: ... + def get_primary_keys(self, table, schema: str | None = None) -> list[Incomplete]: ... + def get_foreign_keys(self, table, schema: str | None = None) -> list[ForeignKeyMetadata]: ... + def get_binary_type(self): ... + def conflict_statement(self, on_conflict, query) -> SQL | None: ... + def conflict_update(self, on_conflict, query) -> NodeList | None: ... + def extract_date(self, date_part, date_field) -> Function: ... + def truncate_date(self, date_part, date_field) -> Function: ... + def to_timestamp(self, date_field) -> Function: ... + def from_timestamp(self, date_field) -> Function: ... + def random(self) -> Function: ... + def get_noop_select(self, ctx): ... + +class _manual(_callable_context_manager): + db: Incomplete + def __init__(self, db) -> None: ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _atomic(_callable_context_manager): + db: Incomplete + def __init__(self, db, *args, **kwargs) -> None: ... + def __enter__(self) -> _transaction | _savepoint: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _transaction(_callable_context_manager): + db: Incomplete + def __init__(self, db, *args, **kwargs) -> None: ... + def commit(self, begin: bool = True) -> None: ... + def rollback(self, begin: bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class _savepoint(_callable_context_manager): + db: Incomplete + sid: Incomplete + quoted_sid: Incomplete + def __init__(self, db, sid=None) -> None: ... + def commit(self, begin: bool = True) -> None: ... + def rollback(self, begin: bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class CursorWrapper: + cursor: Incomplete + count: int + index: int + initialized: bool + populated: bool + row_cache: list[Incomplete] + def __init__(self, cursor) -> None: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def __len__(self) -> int: ... + def initialize(self) -> None: ... + def iterate(self, cache: bool = True): ... + def process_row(self, row): ... + def iterator(self) -> Generator[Incomplete]: ... + def fill_cache(self, n: int = 0) -> None: ... + def dedupe_columns(self, columns: Iterable[str], valid_identifiers: bool = True) -> list[str]: ... + +class DictCursorWrapper(CursorWrapper): + columns: list[str] + ncols: int + def initialize(self) -> None: ... + def process_row(self, row): ... + +class NamedTupleCursorWrapper(CursorWrapper): + tuple_class: Incomplete + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ObjectCursorWrapper(DictCursorWrapper): + constructor: Incomplete + columns: list[str] + ncols: int + def __init__(self, cursor, constructor) -> None: ... + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ResultIterator: + cursor_wrapper: Incomplete + index: int + def __init__(self, cursor_wrapper) -> None: ... + def __iter__(self) -> Self: ... + def next(self): ... + __next__ = next + +class FieldAccessor: + model: Incomplete + field: Incomplete + name: Incomplete + def __init__(self, model, field, name) -> None: ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class ForeignKeyAccessor(FieldAccessor): + rel_model: Incomplete + def __init__(self, model, field, name) -> None: ... + def get_rel_instance(self, instance): ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, obj) -> None: ... + +class BackrefAccessor: + field: Incomplete + model: Incomplete + rel_model: Incomplete + def __init__(self, field) -> None: ... + def __get__(self, instance, instance_type=None): ... + +class ObjectIdAccessor: + field: Incomplete + def __init__(self, field) -> None: ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class Field(ColumnBase, Generic[_V]): + @overload + def __get__(self, instance: None, owner: Any) -> Self: ... + @overload + def __get__(self, instance: object, owner: Any) -> _V: ... + + def __set__(self, instance: object, value: _V) -> None: ... + accessor_class: Incomplete + auto_increment: bool + default_index_type: Incomplete + field_type: ClassVar[str] + null: Incomplete + index: Incomplete + unique: Incomplete + column_name: Incomplete + default: Incomplete + primary_key: Incomplete + constraints: Incomplete + sequence: Incomplete + collation: Incomplete + unindexed: Incomplete + choices: Incomplete + help_text: Incomplete + verbose_name: Incomplete + index_type: Incomplete + # Field constructor args are typed per-field in the __new__ overloads. + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __hash__(self) -> int: ... + model: Incomplete + name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + @property + def column(self) -> Column: ... + def adapt(self, value): ... + def db_value(self, value): ... + def python_value(self, value): ... + def to_value(self, value) -> Value: ... + def case_value(self, value) -> Value: ... + def get_sort_key(self, ctx) -> tuple[Incomplete, ...]: ... + def __sql__(self, ctx): ... + def get_modifiers(self) -> list[int] | None: ... + def ddl_datatype(self, ctx) -> SQL: ... + def ddl(self, ctx) -> NodeList: ... + +class AnyField(Field): ... + +class IntegerField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> IntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> IntegerField[int]: ... + + def adapt(self, value): ... + +class BigIntegerField(IntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BigIntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BigIntegerField[int]: ... + +class SmallIntegerField(IntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> SmallIntegerField[int | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> SmallIntegerField[int]: ... + +class AutoField(IntegerField[_V]): + auto_increment: bool + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> AutoField[int]: ... + +class BigAutoField(AutoField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> BigAutoField[int]: ... + +class IdentityField(AutoField[_V]): + def __new__(cls, *args: Any, generate_always: bool = False, **kwargs: Unpack[_FieldKwargs]) -> IdentityField[int]: ... + +class PrimaryKeyField(AutoField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> PrimaryKeyField[int]: ... + +class FloatField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> FloatField[float | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> FloatField[float]: ... + + def adapt(self, value): ... + +class DoubleField(FloatField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> DoubleField[float | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> DoubleField[float]: ... + +class DecimalField(Field[_V]): + max_digits: Incomplete + decimal_places: Incomplete + auto_round: Incomplete + rounding: Incomplete + + @overload + def __new__( + cls, + max_digits: int = ..., + decimal_places: int = ..., + auto_round: bool = ..., + rounding: str | None = ..., + *args: Any, + null: Literal[True], + **kwargs: Unpack[_FieldKwargs], + ) -> DecimalField[Decimal | None]: ... + @overload + def __new__( + cls, + max_digits: int = ..., + decimal_places: int = ..., + auto_round: bool = ..., + rounding: str | None = ..., + *args: Any, + null: Literal[False] = ..., + **kwargs: Unpack[_FieldKwargs], + ) -> DecimalField[Decimal]: ... + + def get_modifiers(self) -> list[int]: ... + def db_value(self, value): ... + def python_value(self, value) -> Decimal | None: ... + +class _StringField(Field[_V]): + def adapt(self, value) -> str: ... + def __add__(self, other) -> StringExpression: ... + def __radd__(self, other) -> StringExpression: ... + +class CharField(_StringField[_V]): + max_length: int + + @overload + def __new__( + cls, max_length: int = 255, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> CharField[str | None]: ... + @overload + def __new__( + cls, max_length: int = 255, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> CharField[str]: ... + + def get_modifiers(self) -> list[int] | None: ... + +class FixedCharField(CharField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> FixedCharField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> FixedCharField[str]: ... + + def adapt(self, value) -> str: ... + +class TextField(_StringField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> TextField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> TextField[str]: ... + +class FieldDatabaseHook: + def bind(self, model, name, set_attribute: bool = True): ... + +class BlobField(FieldDatabaseHook, Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BlobField[bytes | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BlobField[bytes]: ... + + def db_value(self, value): ... + +class JSONPath(ColumnBase): + def __init__(self, field, keys=..., as_text: bool = False) -> None: ... + def __getitem__(self, key) -> JSONPath: ... + def path(self, *keys) -> JSONPath: ... + def as_text(self, as_text: bool = True) -> Self: ... + def as_int(self) -> Cast: ... + def as_float(self) -> Cast: ... + def set(self, value) -> Expression: ... + def insert(self, value) -> Expression: ... + def replace(self, value) -> Expression: ... + def append(self, value) -> Expression: ... + def remove(self) -> Expression: ... + def length(self) -> Expression: ... + def contained_by(self, value) -> Expression: ... + def has_key(self, key) -> Expression: ... + def has_keys(self, key_list) -> Expression: ... + def has_any_keys(self, key_list) -> Expression: ... + +class JSONField(FieldDatabaseHook, Field): + def __init__(self, dumps=None, loads=None, **kwargs) -> None: ... + def path(self, *keys): ... + def length(self) -> Expression: ... + def append(self, value) -> Expression: ... + def update(self, value) -> Expression: ... + def contains(self, value) -> Expression: ... # type: ignore[override] + def contained_by(self, value) -> Expression: ... + def has_key(self, key) -> Expression: ... + def has_keys(self, key_list) -> Expression: ... + def has_any_keys(self, key_list) -> Expression: ... + +class BitField(BitwiseMixin, BigIntegerField[_V]): + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> BitField[int]: ... + def flag(self, value=None): ... + +class BigBitFieldData: + instance: Incomplete + name: Incomplete + def __init__(self, instance, name) -> None: ... + def clear(self) -> None: ... + def set_bit(self, idx) -> None: ... + def clear_bit(self, idx) -> None: ... + def toggle_bit(self, idx) -> bool: ... + def is_set(self, idx) -> bool: ... + __getitem__ = is_set + def __setitem__(self, item: int, value: bool) -> None: ... + __delitem__ = clear_bit + def __len__(self) -> int: ... + def __and__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __or__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __xor__(self, other: BigBitFieldData | bytes | bytearray | memoryview) -> bytearray: ... + def __iter__(self) -> Iterator[Literal[0, 1]]: ... + def __bytes__(self) -> bytes: ... + +class BigBitFieldAccessor(FieldAccessor): + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + +class BigBitField(BlobField[bytes]): + accessor_class: Incomplete + def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> Self: ... + + @overload # type: ignore[override] + def __get__(self, instance: None, owner: Any) -> Self: ... + @overload + def __get__(self, instance: object, owner: Any) -> BigBitFieldData: ... + + def db_value(self, value): ... + +class UUIDField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> UUIDField[UUID | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> UUIDField[UUID]: ... + + def db_value(self, value): ... + def python_value(self, value) -> UUID | None: ... + +class BinaryUUIDField(BlobField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BinaryUUIDField[UUID | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BinaryUUIDField[UUID]: ... + + def db_value(self, value): ... + def python_value(self, value) -> UUID | None: ... + +class _BaseFormattedField(Field[_V]): + formats: Incomplete + def __init__(self, formats=None, *args, **kwargs) -> None: ... + +class DateTimeField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> DateTimeField[datetime | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> DateTimeField[datetime]: ... + + formats: list[str] + def adapt(self, value): ... + def to_timestamp(self): ... + def truncate(self, part): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class DateField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> DateField[date | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> DateField[date]: ... + + formats: list[str] + def adapt(self, value): ... + def to_timestamp(self): ... + def truncate(self, part): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + +class TimeField(_BaseFormattedField[_V]): + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> TimeField[time | None]: ... + @overload + def __new__( + cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] + ) -> TimeField[time]: ... + + formats: list[str] + def adapt(self, value): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class TimestampField(BigIntegerField[_V]): + valid_resolutions: Incomplete + resolution: Incomplete + ticks_to_microsecond: Incomplete + utc: Incomplete + formats: list[str] + + @overload + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime | None]: ... + @overload + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[False] = False, **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime]: ... + + def get_timestamp(self, value) -> float: ... + def db_value(self, value) -> int | None: ... + def python_value(self, value): ... + def from_timestamp(self): ... + @property + def year(self): ... + @property + def month(self): ... + @property + def day(self): ... + @property + def hour(self): ... + @property + def minute(self): ... + @property + def second(self): ... + +class IPField(BigIntegerField[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> IPField[str | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> IPField[str]: ... + + def db_value(self, val): ... + def python_value(self, val) -> str | None: ... + +class BooleanField(Field[_V]): + @overload + def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> BooleanField[bool | None]: ... + @overload + def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> BooleanField[bool]: ... + + adapt: Incomplete + +class BareField(Field): + adapt: Incomplete + def __init__(self, adapt=None, *args, **kwargs) -> None: ... + def ddl_datatype(self, ctx): ... + +class ForeignKeyField(Field[_V]): + accessor_class: Incomplete + backref_accessor_class: Incomplete + rel_model: Incomplete + rel_field: Incomplete + declared_backref: Incomplete + backref: Incomplete + on_delete: Incomplete + on_update: Incomplete + deferrable: Incomplete + deferred: Incomplete + object_id_name: Incomplete + lazy_load: Incomplete + constraint_name: str | None + + @overload + def __new__( + cls, model: type[_M], *args: Any, null: Literal[True], **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[_M | None]: ... + @overload + def __new__( + cls, model: type[_M], *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[_M]: ... + @overload + # Self-reference, the only string peewee accepts. Named refs use DeferredForeignKey. + def __new__( + cls, model: Literal["self"] = ..., *args: Any, null: bool = ..., **kwargs: Unpack[_FKKwargs] + ) -> ForeignKeyField[Any]: ... + + @property + def field_type(self): ... # type: ignore[override] + def get_modifiers(self): ... + def adapt(self, value): ... + def db_value(self, value): ... + def python_value(self, value): ... + column_name: Incomplete + safe_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + def foreign_key_constraint(self, explicit_name: bool = False) -> NodeList: ... + def get_constraint_name(self) -> str: ... + def __getattr__(self, attr: str): ... + +class DeferredForeignKey(Field): + field_kwargs: Incomplete + rel_model_name: Incomplete + # Model named by string, so the related type isn't knowable and null can't refine it. + def __init__(self, rel_model_name: str, *, null: bool = ..., **kwargs: Unpack[_FKKwargs]) -> None: ... + __hash__ = object.__hash__ + def __deepcopy__(self, memo=None) -> DeferredForeignKey: ... + def set_model(self, rel_model) -> None: ... + @staticmethod + def resolve(model_cls) -> None: ... + +class DeferredThroughModel: + def __init__(self) -> None: ... + def set_field(self, model, field, name) -> None: ... + def set_model(self, through_model) -> None: ... + +class MetaField(Field): + column_name: Incomplete + default: Incomplete + model: Incomplete + name: Incomplete + primary_key: bool + +class ManyToManyFieldAccessor(FieldAccessor): + model: Incomplete + rel_model: Incomplete + through_model: Incomplete + src_fk: Incomplete + dest_fk: Incomplete + def __init__(self, model, field, name) -> None: ... + def __get__(self, instance, instance_type=None, force_query: bool = False): ... + def __set__(self, instance, value) -> None: ... + +class ManyToManyField(MetaField): + accessor_class: Incomplete + rel_model: Incomplete + backref: Incomplete + def __init__( + self, + model, + backref=None, + through_model=None, + on_delete=None, + on_update=None, + prevent_unsaved: bool = True, + _is_backref: bool = False, + ) -> None: ... + def bind(self, model, name, set_attribute: bool = True) -> None: ... + def get_models(self) -> list[Incomplete]: ... + + @property + def through_model(self): ... + @through_model.setter + def through_model(self, value) -> None: ... + + def get_through_model(self): ... + +class VirtualField(MetaField): + field_class: Incomplete + field_instance: Incomplete + def __init__(self, field_class=None, *args, **kwargs) -> None: ... + def db_value(self, value): ... + def python_value(self, value): ... + model: Incomplete + column_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + +class CompositeKey(MetaField): + sequence: Incomplete + field_names: Incomplete + def __init__(self, *field_names) -> None: ... + @property + def safe_field_names(self): ... + def __get__(self, instance, instance_type=None): ... + def __set__(self, instance, value) -> None: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + def __hash__(self) -> int: ... + def __sql__(self, ctx): ... + model: Incomplete + column_name: Incomplete + def bind(self, model, name, set_attribute: bool = True) -> None: ... + +class _SortedFieldList: + __slots__ = ("_keys", "_items") + def __init__(self) -> None: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, item) -> bool: ... + def index(self, field) -> int: ... + def insert(self, item) -> None: ... + def remove(self, item) -> None: ... + +class SchemaManager: + model: Incomplete + context_options: Incomplete + def __init__(self, model, database: _DatabaseType | None = None, **context_options) -> None: ... + + @property + def database(self): ... + @database.setter + def database(self, value) -> None: ... + + def create_table(self, safe: bool = True, **options) -> None: ... + def create_table_as(self, table_name, query, safe: bool = True, **meta) -> None: ... + def drop_table(self, safe: bool = True, **options) -> None: ... + def truncate_table(self, restart_identity: bool = False, cascade: bool = False) -> None: ... + def create_indexes(self, safe: bool = True) -> None: ... + def drop_index(self, field=None, index=None, safe: bool = True): ... + def drop_indexes(self, safe: bool = True) -> None: ... + def create_sequence(self, field) -> None: ... + def drop_sequence(self, field) -> None: ... + def create_foreign_key(self, field) -> None: ... + def create_sequences(self) -> None: ... + def create_all(self, safe: bool = True, **table_options) -> None: ... + def drop_sequences(self) -> None: ... + def drop_all(self, safe: bool = True, drop_sequences: bool = True, **options) -> None: ... + +class Metadata: + model: type[Model] + database: Incomplete + fields: Incomplete + columns: Incomplete + combined: Incomplete + sorted_fields: Incomplete + sorted_field_names: Incomplete + defaults: Incomplete + name: Incomplete + table_function: Incomplete + legacy_table_names: Incomplete + table_name: Incomplete + indexes: Incomplete + constraints: Incomplete + primary_key: Field[Any] | Literal[False] + composite_key: Incomplete + only_save_dirty: Incomplete + depends_on: Incomplete + table_settings: Incomplete + without_rowid: Incomplete + strict_tables: Incomplete + temporary: Incomplete + refs: Incomplete + backrefs: Incomplete + model_refs: Incomplete + model_backrefs: Incomplete + manytomany: Incomplete + options: Incomplete + def __init__( + self, + model, + database: _DatabaseType | None = None, + table_name=None, + indexes=None, + primary_key=None, + constraints=None, + schema: str | None = None, + only_save_dirty: bool = False, + depends_on=None, + options=None, + db_table=None, + table_function=None, + table_settings=None, + without_rowid: bool = False, + temporary: bool = False, + strict_tables=None, + legacy_table_names: bool = True, + **kwargs, + ) -> None: ... + def make_table_name(self) -> str: ... + def model_graph( + self, refs: bool = True, backrefs: bool = True, depth_first: bool = True + ) -> list[tuple[Incomplete, Incomplete, Incomplete]]: ... + def add_ref(self, field) -> None: ... + def remove_ref(self, field) -> None: ... + def add_manytomany(self, field) -> None: ... + def remove_manytomany(self, field) -> None: ... + + @property + def table(self) -> Table: ... + @table.deleter + def table(self) -> None: ... + + @property + def schema(self) -> str | None: ... + @schema.setter + def schema(self, value) -> None: ... + + @property + def entity(self) -> Entity: ... + def add_field(self, field_name, field, set_attribute: bool = True) -> None: ... + def remove_field(self, field_name) -> None: ... + auto_increment: Incomplete + def set_primary_key(self, name, field) -> None: ... + def get_primary_keys(self): ... + def get_default_dict(self): ... + def fields_to_index(self) -> list[Incomplete]: ... + def set_database(self, database: _DatabaseType) -> None: ... + def set_table_name(self, table_name) -> None: ... + +class SubclassAwareMetadata(Metadata): + models: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + def map_models(self, fn) -> None: ... + +class DoesNotExist(Exception): ... + +class ModelBase(type): + inheritable: set[str] + def __new__(cls, name, bases, attrs): ... + def __iter__(self): ... + def __getitem__(self, key): ... + def __setitem__(self, key, value) -> None: ... + def __delitem__(self, key) -> None: ... + def __contains__(self, key) -> bool: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __sql__(self, ctx): ... + +class _BoundModelsContext(_callable_context_manager): + models: Incomplete + database: Incomplete + bind_refs: Incomplete + bind_backrefs: Incomplete + def __init__(self, models, database: _DatabaseType, bind_refs, bind_backrefs) -> None: ... + def __enter__(self): ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Model(metaclass=ModelBase): + __data__: Incomplete + __rel__: Incomplete + _meta: Metadata + def __init__(self, *args, **kwargs) -> None: ... + @classmethod + def validate_model(cls) -> None: ... + @classmethod + def alias(cls, alias=None) -> ModelAlias[Self]: ... + @classmethod + def select(cls, *fields) -> ModelSelect[Self]: ... + @classmethod + def update(cls, data=None, /, **update) -> ModelUpdate: ... + @classmethod + def insert(cls, data=None, /, **insert) -> ModelInsert: ... + @classmethod + def insert_many(cls, rows, fields=None) -> ModelInsert: ... + @classmethod + def insert_from(cls, query, fields) -> ModelInsert: ... + @classmethod + def replace(cls, data=None, /, **insert): ... + @classmethod + def replace_many(cls, rows, fields=None): ... + @classmethod + def raw(cls, sql, *params) -> ModelRaw: ... + @classmethod + def delete(cls) -> ModelDelete: ... + @classmethod + def create(cls, **query) -> Self: ... + @classmethod + def bulk_create(cls, model_list, batch_size=None) -> None: ... + @classmethod + def bulk_update(cls, model_list, fields, batch_size=None): ... + @classmethod + def noop(cls) -> NoopModelSelect[Self]: ... + @classmethod + def get(cls, *query, **filters) -> Self: ... + @classmethod + def get_or_none(cls, *query, **filters) -> Self | None: ... + @classmethod + def get_by_id(cls, pk) -> Self: ... + @classmethod + def set_by_id(cls, key, value): ... + @classmethod + def delete_by_id(cls, pk): ... + @classmethod + def get_or_create(cls, **kwargs): ... + @classmethod + def filter(cls, *dq_nodes, **filters): ... + def get_id(self): ... + def save(self, force_insert: bool = False, only=None) -> int: ... + def is_dirty(self) -> bool: ... + @property + def dirty_fields(self) -> list[Field[Any]]: ... + @property + def dirty_field_names(self) -> list[str]: ... + def dependencies(self, search_nullable: bool = True, exclude_null_children: bool = False) -> Generator[Incomplete]: ... + def delete_instance(self, recursive: bool = False, delete_nullable: bool = False) -> int: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] + def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] + def __sql__(self, ctx): ... + @classmethod + def bind(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True, _exclude=None) -> bool: ... + @classmethod + def bind_ctx(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True) -> _BoundModelsContext: ... + @classmethod + def table_exists(cls): ... + @classmethod + def create_table(cls, safe: bool = True, **options) -> None: ... + @classmethod + def drop_table(cls, safe: bool = True, drop_sequences: bool = True, **options) -> None: ... + @classmethod + def truncate_table(cls, **options) -> None: ... + @classmethod + def index(cls, *fields, **kwargs) -> ModelIndex: ... + @classmethod + def add_index(cls, *fields, **kwargs) -> None: ... + +class ModelAlias(Node, Generic[_M]): + def __init__(self, model: type[_M], alias=None) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def get_field_aliases(self) -> list[Incomplete]: ... + def select(self, *selection) -> ModelSelect[_M]: ... + def __call__(self, **kwargs): ... + def __sql__(self, ctx): ... + +class FieldAlias(Field): + source: Incomplete + model: Incomplete + field: Incomplete + def __init__(self, source, field) -> None: ... + @classmethod + def create(cls, source, field): ... + def clone(self) -> FieldAlias: ... + def adapt(self, value): ... + def python_value(self, value): ... + def db_value(self, value): ... + def __getattr__(self, attr: str): ... + def __sql__(self, ctx): ... + +class _ModelQueryHelper: + default_row_type: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def objects(self, constructor=None) -> Self: ... + def models(self) -> Self: ... + +class ModelRaw(_ModelQueryHelper, RawQuery): # type: ignore[misc] + model: Incomplete + def __init__(self, model, sql, params, **kwargs) -> None: ... + def get(self) -> Model: ... + +class BaseModelSelect(_ModelQueryHelper): + def union_all(self, rhs) -> ModelCompoundSelectQuery: ... + __add__ = union_all + def union(self, rhs) -> ModelCompoundSelectQuery: ... + __or__ = union + def intersect(self, rhs) -> ModelCompoundSelectQuery: ... + __and__ = intersect + def except_(self, rhs) -> ModelCompoundSelectQuery: ... + __sub__ = except_ + def __iter__(self): ... + def prefetch(self, *subqueries, prefetch_type: int = ...): ... + def with_related(self, *loads: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... + def iterator(self, database: _DatabaseType | None = ...) -> Iterator[Any]: ... + def get(self, database: _DatabaseType | None = None): ... + def get_or_none(self, database: _DatabaseType | None = None): ... + def group_by(self, *columns) -> Self: ... + +class ModelCompoundSelectQuery(BaseModelSelect, CompoundSelectQuery): # type: ignore[misc] + model: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + +class ModelSelect(BaseModelSelect, Select, Generic[_M]): # type: ignore[misc] + model: type[_M] + def __init__(self, model, fields_or_models, is_default: bool = False) -> None: ... + def __iter__(self) -> Iterator[_M]: ... + def get(self, database: _DatabaseType | None = None) -> _M: ... + def get_or_none(self, database: _DatabaseType | None = None) -> _M | None: ... + def clone(self) -> Self: ... + def select(self, *fields_or_models) -> ModelSelect[_M]: ... + def select_extend(self, *columns) -> Self: ... + def switch(self, ctx=None) -> Self: ... + def join(self, dest, join_type="INNER JOIN", on=None, src=None, attr=None) -> Self: ... # type: ignore[override] + def left_outer_join(self, dest, on=None, src=None, attr=None) -> Self: ... # type: ignore[override] + def join_from(self, src, dest, join_type="INNER JOIN", on=None, attr=None) -> Self: ... + def ensure_join(self, lm, rm, on=None, **join_kwargs): ... + def convert_dict_to_node(self, qdict) -> tuple[list[Incomplete], list[Incomplete]]: ... + def filter(self, *args, **kwargs) -> Self: ... + def create_table(self, name, safe: bool = True, **meta): ... + def __sql_selection__(self, ctx, is_subquery: bool = False): ... + +class NoopModelSelect(ModelSelect[_M]): + def __sql__(self, ctx): ... + +class _ModelWriteQueryHelper(_ModelQueryHelper): + model: Incomplete + def __init__(self, model, *args, **kwargs) -> None: ... + def returning(self, *returning) -> Self: ... + +class ModelUpdate(_ModelWriteQueryHelper, Update): ... # type: ignore[misc] + +class ModelInsert(_ModelWriteQueryHelper, Insert): # type: ignore[misc] + default_row_type: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def returning(self, *returning) -> Self: ... + def get_default_data(self): ... + def get_default_columns(self): ... + +class ModelDelete(_ModelWriteQueryHelper, Delete): ... # type: ignore[misc] + +class ManyToManyQuery(ModelSelect[_M]): + def __init__(self, instance, accessor, rel, *args, **kwargs) -> None: ... + def add(self, value, clear_existing: bool = False) -> None: ... + def remove(self, value): ... + def clear(self): ... + +class BaseModelCursorWrapper(DictCursorWrapper): + model: Incomplete + select: Incomplete + ncols: int + columns: list[str] + converters: list[Incomplete] + fields: list[Incomplete] + no_convert: list[int] + convert: list[int] + def __init__(self, cursor, model, columns) -> None: ... + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ModelDictCursorWrapper(BaseModelCursorWrapper): + unique_columns: list[str] + def initialize(self) -> None: ... + def process_row(self, row) -> dict[str, Incomplete]: ... + +class ModelTupleCursorWrapper(BaseModelCursorWrapper): + constructor: Incomplete + def process_row(self, row) -> tuple[Incomplete, ...]: ... # type: ignore[override] + +class ModelNamedTupleCursorWrapper(ModelTupleCursorWrapper): + impl: Incomplete + constructor: Incomplete + def initialize(self) -> None: ... + +class ModelObjectCursorWrapper(ModelDictCursorWrapper): + constructor: Incomplete + is_model: Incomplete + identifiers: list[str] + def __init__(self, cursor, model, select, constructor) -> None: ... + def initialize(self) -> None: ... + def process_row(self, row): ... + +class ModelCursorWrapper(BaseModelCursorWrapper): + from_list: Incomplete + joins: Incomplete + def __init__(self, cursor, model, select, from_list, joins) -> None: ... + key_to_constructor: dict[Incomplete, tuple[Incomplete, Incomplete]] + src_to_dest: list[tuple[Incomplete, Incomplete, Incomplete, bool, Incomplete, bool]] + column_keys: list[Incomplete] + def initialize(self) -> None: ... + def process_row(self, row): ... + +@type_check_only +class _PrefetchQuery(NamedTuple): + query: Incomplete + fields: Incomplete + is_backref: bool + rel_models: Incomplete + field_to_name: Incomplete + model: Incomplete + +class PrefetchQuery(_PrefetchQuery): + def __new__(cls, query, fields=None, is_backref: bool | None = None, rel_models=None, field_to_name=None) -> Self: ... + def populate_instance(self, instance, id_map) -> None: ... + def store_instance(self, instance, id_map) -> None: ... + +def prefetch(sq, *subqueries, prefetch_type: int = ...): ... + +class Load(Node): + def __init__( + self, + rel: ForeignKeyField[Any] | BackrefAccessor, + query: ModelSelect[Any] | None = ..., + strategy: int = ..., + per_parent: int | None = ..., + ) -> None: ... + def then(self, *children: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... + +__all__ = [ + "AnyField", + "AsIs", + "AutoField", + "BareField", + "BigAutoField", + "BigBitField", + "BigIntegerField", + "BinaryUUIDField", + "BitField", + "BlobField", + "BooleanField", + "Case", + "Cast", + "CharField", + "Check", + "chunked", + "Column", + "CompositeKey", + "Context", + "Database", + "DatabaseError", + "DatabaseProxy", + "DataError", + "DateField", + "DateTimeField", + "DecimalField", + "Default", + "DeferredForeignKey", + "DeferredThroughModel", + "DJANGO_MAP", + "DoesNotExist", + "DoubleField", + "DQ", + "Entity", + "EXCLUDED", + "Field", + "FixedCharField", + "FloatField", + "fn", + "ForeignKeyField", + "IdentityField", + "ImproperlyConfigured", + "Index", + "IntegerField", + "IntegrityError", + "InterfaceError", + "InternalError", + "IPField", + "JOIN", + "JSONField", + "Load", + "ManyToManyField", + "Model", + "ModelIndex", + "MySQLDatabase", + "NotSupportedError", + "OP", + "OperationalError", + "PostgresqlDatabase", + "PrimaryKeyField", + "prefetch", + "PREFETCH_TYPE", + "ProgrammingError", + "Proxy", + "QualifiedNames", + "SchemaManager", + "SmallIntegerField", + "Select", + "SQL", + "SqliteDatabase", + "Table", + "TextField", + "TimeField", + "TimestampField", + "Tuple", + "UUIDField", + "Value", + "ValuesList", + "Window", +] diff --git a/stubs/peewee/playhouse/__init__.pyi b/stubs/peewee/playhouse/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/peewee/playhouse/flask_utils.pyi b/stubs/peewee/playhouse/flask_utils.pyi new file mode 100644 index 000000000000..a774c4eaa2fc --- /dev/null +++ b/stubs/peewee/playhouse/flask_utils.pyi @@ -0,0 +1,27 @@ +from _typeshed import Unused +from collections.abc import Container +from typing import Any, TypeAlias + +from peewee import Database, ModelBase, Proxy + +# Is actually flask.Flask +_Flask: TypeAlias = Any + +class FlaskDB: + # Omitting undocumented base_model_class on purpose, use FlaskDB.Model instead + database: Database | Proxy + def __init__( + self, + app: _Flask | None = None, + database: Database | Proxy | None = None, + # Is actually type[ModelClass] but stubtest likely confuses with Model property + # https://github.com/python/typeshed/pull/11731#issuecomment-2067694259 + model_class=..., + excluded_routes: Container[str] | None = None, + ) -> None: ... + def init_app(self, app: _Flask) -> None: ... + def get_model_class(self) -> type[ModelBase]: ... + @property + def Model(self) -> type[ModelBase]: ... + def connect_db(self) -> None: ... + def close_db(self, exc: Unused) -> None: ... diff --git a/stubs/pep8-naming/METADATA.toml b/stubs/pep8-naming/METADATA.toml new file mode 100644 index 000000000000..3b73248f1786 --- /dev/null +++ b/stubs/pep8-naming/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.15.*" +upstream-repository = "https://github.com/PyCQA/pep8-naming" diff --git a/stubs/pep8-naming/pep8ext_naming.pyi b/stubs/pep8-naming/pep8ext_naming.pyi new file mode 100644 index 000000000000..758bd4fce074 --- /dev/null +++ b/stubs/pep8-naming/pep8ext_naming.pyi @@ -0,0 +1,163 @@ +import argparse +import ast +import enum +import optparse +from collections import deque +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from typing import Any, Final, Literal +from typing_extensions import Self + +__version__: Final[str] + +CLASS_METHODS: Final[frozenset[Literal["__new__", "__init_subclass__", "__class_getitem__"]]] +METACLASS_BASES: Final[frozenset[Literal["type", "ABCMeta"]]] +METHOD_CONTAINER_NODES: Final[set[ast.AST]] +FUNC_NODES: Final[tuple[type[ast.FunctionDef], type[ast.AsyncFunctionDef]]] + +class BaseASTCheck: + all: list[BaseASTCheck] + codes: tuple[str, ...] + # Per convention, unknown kwargs are passed to the super-class. See there for the types. + def __init_subclass__(cls, **kwargs: Any) -> None: ... + def err(self, node: ast.AST, code: str, **kwargs: str) -> tuple[int, int, str, Self]: ... + +class NameSet(frozenset[str]): + def __new__(cls, iterable: Iterable[str]) -> Self: ... + def __contains__(self, item: object, /) -> bool: ... + +@enum.unique +class FunctionType(enum.Enum): + CLASSMETHOD = "classmethod" + STATICMETHOD = "staticmethod" + FUNCTION = "function" + METHOD = "method" + +class NamingChecker: + name: str + version: str + visitors: Sequence[BaseASTCheck] + decorator_to_type: dict[str, FunctionType] + ignored: NameSet + def __init__(self, tree: ast.AST, filename: str) -> None: ... + @classmethod + def add_options(cls, parser: optparse.OptionParser) -> None: ... + @classmethod + def parse_options(cls, options: argparse.Namespace) -> None: ... + def run(self) -> Generator[tuple[int, int, str, Self]] | tuple[()]: ... + def visit_tree(self, node: ast.AST, parents: deque[ast.AST]) -> Generator[tuple[int, int, str, Self]]: ... + def visit_node(self, node: ast.AST, parents: Sequence[ast.AST]) -> Generator[tuple[int, int, str, Self]]: ... + def tag_class_functions(self, cls_node: ast.ClassDef) -> None: ... + def set_function_nodes_types( + self, nodes: Iterator[ast.AST], ismetaclass: bool, late_decoration: dict[str, FunctionType] + ) -> None: ... + @classmethod + def find_decorator_name(cls, d: ast.Expr) -> str: ... + @staticmethod + def find_global_defs(func_def_node: ast.AST) -> None: ... + +class ClassNameCheck(BaseASTCheck): + codes: tuple[Literal["N801"], Literal["N818"]] + N801: Final[str] + N818: Final[str] + @classmethod + def get_classdef(cls, name: str, parents: Sequence[ast.AST]) -> ast.ClassDef | None: ... + @classmethod + def superclass_names(cls, name: str, parents: Sequence[ast.AST], _names: set[str] | None = None) -> set[str]: ... + def visit_classdef( + self, node: ast.ClassDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class FunctionNameCheck(BaseASTCheck): + codes: tuple[Literal["N802"], Literal["N807"]] + N802: Final[str] + N807: Final[str] + @staticmethod + def has_override_decorator(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool: ... + def visit_functiondef( + self, node: ast.FunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfunctiondef( + self, node: ast.AsyncFunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class FunctionArgNamesCheck(BaseASTCheck): + codes: tuple[Literal["N803"], Literal["N804"], Literal["N805"]] + N803: Final[str] + N804: Final[str] + N805: Final[str] + def visit_functiondef( + self, node: ast.FunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfunctiondef( + self, node: ast.AsyncFunctionDef, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class ImportAsCheck(BaseASTCheck): + codes: tuple[Literal["N811"], Literal["N812"], Literal["N813"], Literal["N814"], Literal["N817"]] + N811: Final[str] + N812: Final[str] + N813: Final[str] + N814: Final[str] + N817: Final[str] + def visit_importfrom( + self, node: ast.ImportFrom, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_import( + self, node: ast.Import, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +class VariablesCheck(BaseASTCheck): + codes: tuple[Literal["N806"], Literal["N815"], Literal["N816"]] + N806: Final[str] + N815: Final[str] + N816: Final[str] + @staticmethod + def is_namedtupe(node_value: ast.AST) -> bool: ... + def visit_assign( + self, node: ast.Assign, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_namedexpr( + self, node: ast.NamedExpr, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_annassign( + self, node: ast.AnnAssign, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_with( + self, node: ast.With, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncwith( + self, node: ast.AsyncWith, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_for(self, node: ast.For, parents: Sequence[ast.AST], ignored: NameSet) -> Generator[tuple[int, int, str, Self]]: ... + def visit_asyncfor( + self, node: ast.AsyncFor, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_excepthandler( + self, node: ast.ExceptHandler, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_generatorexp( + self, node: ast.GeneratorExp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_listcomp( + self, node: ast.ListComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_dictcomp( + self, node: ast.DictComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + def visit_setcomp( + self, node: ast.SetComp, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + @staticmethod + def global_variable_check(name: str) -> Literal["N816"] | None: ... + @staticmethod + def class_variable_check(name: str) -> Literal["N815"] | None: ... + @staticmethod + def function_variable_check(func: Callable[..., object], var_name: str) -> Literal["N806"] | None: ... + +class TypeVarNameCheck(BaseASTCheck): + N808: Final[str] + def visit_module( + self, node: ast.Module, parents: Sequence[ast.AST], ignored: NameSet + ) -> Generator[tuple[int, int, str, Self]]: ... + +def is_mixed_case(name: str) -> bool: ... diff --git a/stubs/pexpect/@tests/stubtest_allowlist.txt b/stubs/pexpect/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c65fb9a6e62e --- /dev/null +++ b/stubs/pexpect/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# python2 shim +pexpect.utils.InterruptedError diff --git a/stubs/pexpect/METADATA.toml b/stubs/pexpect/METADATA.toml new file mode 100644 index 000000000000..6e7cab5fa1ad --- /dev/null +++ b/stubs/pexpect/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.9.*" +upstream-repository = "https://github.com/pexpect/pexpect" diff --git a/stubs/pexpect/pexpect/ANSI.pyi b/stubs/pexpect/pexpect/ANSI.pyi new file mode 100644 index 000000000000..4185ba6fa245 --- /dev/null +++ b/stubs/pexpect/pexpect/ANSI.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from . import screen + +def DoEmit(fsm) -> None: ... +def DoStartNumber(fsm) -> None: ... +def DoBuildNumber(fsm) -> None: ... +def DoBackOne(fsm) -> None: ... +def DoBack(fsm) -> None: ... +def DoDownOne(fsm) -> None: ... +def DoDown(fsm) -> None: ... +def DoForwardOne(fsm) -> None: ... +def DoForward(fsm) -> None: ... +def DoUpReverse(fsm) -> None: ... +def DoUpOne(fsm) -> None: ... +def DoUp(fsm) -> None: ... +def DoHome(fsm) -> None: ... +def DoHomeOrigin(fsm) -> None: ... +def DoEraseDown(fsm) -> None: ... +def DoErase(fsm) -> None: ... +def DoEraseEndOfLine(fsm) -> None: ... +def DoEraseLine(fsm) -> None: ... +def DoEnableScroll(fsm) -> None: ... +def DoCursorSave(fsm) -> None: ... +def DoCursorRestore(fsm) -> None: ... +def DoScrollRegion(fsm) -> None: ... +def DoMode(fsm) -> None: ... +def DoLog(fsm) -> None: ... + +class term(screen.screen): + def __init__(self, r: int = 24, c: int = 80, *args, **kwargs) -> None: ... + +class ANSI(term): + state: Incomplete + def __init__(self, r: int = 24, c: int = 80, *args, **kwargs) -> None: ... + def process(self, c) -> None: ... + def process_list(self, l) -> None: ... + def write(self, s) -> None: ... + def flush(self) -> None: ... + def write_ch(self, ch) -> None: ... + def do_sgr(self, fsm) -> None: ... + def do_decsca(self, fsm) -> None: ... + def do_modecrap(self, fsm) -> None: ... diff --git a/stubs/pexpect/pexpect/FSM.pyi b/stubs/pexpect/pexpect/FSM.pyi new file mode 100644 index 000000000000..abc0cb037638 --- /dev/null +++ b/stubs/pexpect/pexpect/FSM.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete + +class ExceptionFSM(Exception): + value: Incomplete + def __init__(self, value) -> None: ... + +class FSM: + state_transitions: Incomplete + state_transitions_any: Incomplete + default_transition: Incomplete + input_symbol: Incomplete + initial_state: Incomplete + current_state: Incomplete + next_state: Incomplete + action: Incomplete + memory: Incomplete + def __init__(self, initial_state, memory=None) -> None: ... + def reset(self) -> None: ... + def add_transition(self, input_symbol, state, action=None, next_state=None) -> None: ... + def add_transition_list(self, list_input_symbols, state, action=None, next_state=None) -> None: ... + def add_transition_any(self, state, action=None, next_state=None) -> None: ... + def set_default_transition(self, action, next_state) -> None: ... + def get_transition(self, input_symbol, state): ... + def process(self, input_symbol) -> None: ... + def process_list(self, input_symbols) -> None: ... + +PY3: Incomplete + +def BeginBuildNumber(fsm) -> None: ... +def BuildNumber(fsm) -> None: ... +def EndBuildNumber(fsm) -> None: ... +def DoOperator(fsm) -> None: ... +def DoEqual(fsm) -> None: ... +def Error(fsm) -> None: ... +def main() -> None: ... diff --git a/stubs/pexpect/pexpect/__init__.pyi b/stubs/pexpect/pexpect/__init__.pyi new file mode 100644 index 000000000000..bd7f1ddac270 --- /dev/null +++ b/stubs/pexpect/pexpect/__init__.pyi @@ -0,0 +1,20 @@ +from .exceptions import EOF as EOF, TIMEOUT as TIMEOUT, ExceptionPexpect as ExceptionPexpect +from .pty_spawn import spawn as spawn, spawnu as spawnu +from .run import run as run, runu as runu +from .utils import split_command_line as split_command_line, which as which + +__version__: str +__revision__: str +__all__ = [ + "ExceptionPexpect", + "EOF", + "TIMEOUT", + "spawn", + "spawnu", + "run", + "runu", + "which", + "split_command_line", + "__version__", + "__revision__", +] diff --git a/stubs/pexpect/pexpect/_async.pyi b/stubs/pexpect/pexpect/_async.pyi new file mode 100644 index 000000000000..18daf19911dd --- /dev/null +++ b/stubs/pexpect/pexpect/_async.pyi @@ -0,0 +1,19 @@ +import asyncio +from typing import AnyStr, Generic + +from .expect import Expecter + +async def expect_async(expecter: Expecter[AnyStr], timeout: float | None = None) -> int: ... +async def repl_run_command_async(repl, cmdlines, timeout: float | None = -1): ... + +class PatternWaiter(asyncio.Protocol, Generic[AnyStr]): + transport: asyncio.ReadTransport | None + expecter: Expecter[AnyStr] + fut: asyncio.Future[int] + def set_expecter(self, expecter: Expecter[AnyStr]) -> None: ... + def found(self, result: int) -> None: ... + def error(self, exc: BaseException | type[BaseException]) -> None: ... + def connection_made(self, transport: asyncio.BaseTransport) -> None: ... + def data_received(self, data: bytes) -> None: ... + def eof_received(self) -> None: ... + def connection_lost(self, exc: BaseException | type[BaseException] | None) -> None: ... diff --git a/stubs/pexpect/pexpect/exceptions.pyi b/stubs/pexpect/pexpect/exceptions.pyi new file mode 100644 index 000000000000..5dc1790c7f20 --- /dev/null +++ b/stubs/pexpect/pexpect/exceptions.pyi @@ -0,0 +1,6 @@ +class ExceptionPexpect(Exception): + def __init__(self, value: str) -> None: ... + def get_trace(self): ... + +class EOF(ExceptionPexpect): ... +class TIMEOUT(ExceptionPexpect): ... diff --git a/stubs/pexpect/pexpect/expect.pyi b/stubs/pexpect/pexpect/expect.pyi new file mode 100644 index 000000000000..ec9c29b52f17 --- /dev/null +++ b/stubs/pexpect/pexpect/expect.pyi @@ -0,0 +1,38 @@ +import re +from collections.abc import Iterable +from typing import AnyStr, Generic + +from .spawnbase import SpawnBase, _CompiledRePattern, _CompiledStringPattern, _Searcher + +class searcher_string(Generic[AnyStr]): + eof_index: int + timeout_index: int + longest_string: int + def __init__(self, strings: Iterable[_CompiledStringPattern[AnyStr]]) -> None: ... + match: AnyStr + start: int + end: int + def search(self, buffer: AnyStr, freshlen: int, searchwindowsize: int | None = None): ... + +class searcher_re(Generic[AnyStr]): + eof_index: int + timeout_index: int + def __init__(self, patterns: Iterable[_CompiledRePattern[AnyStr]]) -> None: ... + match: re.Match[AnyStr] + start: int + end: int + def search(self, buffer: AnyStr, freshlen: int, searchwindowsize: int | None = None): ... + +class Expecter(Generic[AnyStr]): + spawn: SpawnBase[AnyStr] + searcher: _Searcher[AnyStr] + searchwindowsize: int | None + lookback: _Searcher[AnyStr] | int | None + def __init__(self, spawn: SpawnBase[AnyStr], searcher: _Searcher[AnyStr], searchwindowsize: int | None = -1) -> None: ... + def do_search(self, window: AnyStr, freshlen: int) -> int: ... + def existing_data(self) -> int: ... + def new_data(self, data: AnyStr) -> int: ... + def eof(self, err: object = None) -> int: ... + def timeout(self, err: object = None) -> int: ... + def errored(self) -> None: ... + def expect_loop(self, timeout: float | None = -1) -> int: ... diff --git a/stubs/pexpect/pexpect/fdpexpect.pyi b/stubs/pexpect/pexpect/fdpexpect.pyi new file mode 100644 index 000000000000..31a6a0a71ac3 --- /dev/null +++ b/stubs/pexpect/pexpect/fdpexpect.pyi @@ -0,0 +1,36 @@ +from _typeshed import FileDescriptorLike +from collections.abc import Iterable +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +__all__ = ["fdspawn"] + +class fdspawn(SpawnBase[AnyStr]): + args: None + command: None + child_fd: int + own_fd: bool + closed: bool + name: str + use_poll: bool + def __init__( + self, + fd: FileDescriptorLike, + args: None = None, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + use_poll: bool = False, + ) -> None: ... + def close(self) -> None: ... + def isalive(self) -> bool: ... + def terminate(self, force: bool = False) -> None: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes) -> int: ... + def write(self, s) -> None: ... + def writelines(self, sequence: Iterable[str | bytes]) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... diff --git a/stubs/pexpect/pexpect/popen_spawn.pyi b/stubs/pexpect/pexpect/popen_spawn.pyi new file mode 100644 index 000000000000..601595a9d00c --- /dev/null +++ b/stubs/pexpect/pexpect/popen_spawn.pyi @@ -0,0 +1,33 @@ +import subprocess +from _typeshed import StrOrBytesPath +from collections.abc import Callable +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +class PopenSpawn(SpawnBase[AnyStr]): + proc: subprocess.Popen[AnyStr] + closed: bool + def __init__( + self, + cmd, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: StrOrBytesPath | None = None, + env: subprocess._ENV | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + preexec_fn: Callable[[], None] | None = None, + ) -> None: ... + flag_eof: bool + def read_nonblocking(self, size, timeout): ... # type: ignore[override] + def write(self, s) -> None: ... + def writelines(self, sequence) -> None: ... + def send(self, s): ... + def sendline(self, s: str = ""): ... + terminated: bool + def wait(self): ... + def kill(self, sig) -> None: ... + def sendeof(self) -> None: ... diff --git a/stubs/pexpect/pexpect/pty_spawn.pyi b/stubs/pexpect/pexpect/pty_spawn.pyi new file mode 100644 index 000000000000..879915556e35 --- /dev/null +++ b/stubs/pexpect/pexpect/pty_spawn.pyi @@ -0,0 +1,96 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Callable, Mapping +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +PY3: bool + +class spawn(SpawnBase[AnyStr]): + use_native_pty_fork: bool + STDIN_FILENO: int + STDOUT_FILENO: int + STDERR_FILENO: int + str_last_chars: int + cwd: FileDescriptorOrPath | None + env: Mapping[str, str] | None + echo: bool + ignore_sighup: bool + command: str + args: list[str] + name: str + use_poll: bool + def __init__( + self, + command: str, + args: list[str] = [], + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = False, + echo: bool = True, + preexec_fn: Callable[[], None] | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + dimensions: tuple[int, int] | None = None, + use_poll: bool = False, + ) -> None: ... + child_fd: int + closed: bool + def close(self, force: bool = True) -> None: ... + def isatty(self) -> bool: ... + def waitnoecho(self, timeout: float | None = -1) -> None: ... + def getecho(self) -> bool: ... + def setecho(self, state: bool) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... + def write(self, s: str | bytes) -> None: ... + def writelines(self, sequence: list[str | bytes]) -> None: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes = "") -> int: ... + def sendcontrol(self, char: str) -> int: ... + def sendeof(self) -> None: ... + def sendintr(self) -> None: ... + + @property + def flag_eof(self) -> bool: ... + @flag_eof.setter + def flag_eof(self, value: bool) -> None: ... + + def eof(self) -> bool: ... + def terminate(self, force: bool = False) -> bool: ... + status: int | None + exitstatus: int | None + signalstatus: int | None + terminated: bool + def wait(self) -> int: ... + def isalive(self) -> bool: ... + def kill(self, sig: int) -> None: ... + def getwinsize(self) -> tuple[int, int]: ... + def setwinsize(self, rows, cols) -> None: ... + def interact( + self, + escape_character="\x1d", + input_filter: Callable[[AnyStr], AnyStr] | None = None, + output_filter: Callable[[AnyStr], AnyStr] | None = None, + ) -> None: ... + +def spawnu( + command: str, + args: list[str] = [], + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = False, + echo: bool = True, + preexec_fn: Callable[[], None] | None = None, + encoding: str | None = "utf-8", + codec_errors: str = "strict", + dimensions: tuple[int, int] | None = None, + use_poll: bool = False, +) -> spawn[str]: ... diff --git a/stubs/pexpect/pexpect/pxssh.pyi b/stubs/pexpect/pexpect/pxssh.pyi new file mode 100644 index 000000000000..2904e0ab628b --- /dev/null +++ b/stubs/pexpect/pexpect/pxssh.pyi @@ -0,0 +1,66 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Mapping +from typing import AnyStr, Literal + +from .exceptions import ExceptionPexpect +from .pty_spawn import spawn +from .spawnbase import _Logfile + +__all__ = ["ExceptionPxssh", "pxssh"] + +class ExceptionPxssh(ExceptionPexpect): ... + +class pxssh(spawn[AnyStr]): + name: str + UNIQUE_PROMPT: str + PROMPT: str + PROMPT_SET_SH: str + PROMPT_SET_CSH: str + PROMPT_SET_ZSH: str + SSH_OPTS: str + force_password: bool + debug_command_string: bool + options: dict[str, str] + def __init__( + self, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + ignore_sighup: bool = True, + echo: bool = True, + options: dict[str, str] = {}, + encoding: str | None = None, + codec_errors: str = "strict", + debug_command_string: bool = False, + use_poll: bool = False, + ) -> None: ... + def levenshtein_distance(self, a, b): ... + def try_read_prompt(self, timeout_multiplier): ... + def sync_original_prompt(self, sync_multiplier: float = 1.0): ... + def login( + self, + server, + username: str | None = None, + password: str = "", + terminal_type: str = "ansi", + original_prompt: str = "[#$]", + login_timeout: float | None = 10, + port: int | None = None, + auto_prompt_reset: bool = True, + ssh_key: FileDescriptorOrPath | Literal[True] | None = None, + quiet: bool = True, + sync_multiplier: int = 1, + check_local_ip: bool = True, + password_regex: str = "(?i)(?:password:)|(?:passphrase for key)", + ssh_tunnels: dict[str, list[str | int]] = {}, + spawn_local_ssh: bool = True, + sync_original_prompt: bool = True, + ssh_config: FileDescriptorOrPath | None = None, + cmd: str = "ssh", + ): ... + def logout(self) -> None: ... + def prompt(self, timeout: float | None = -1): ... + def set_unique_prompt(self): ... diff --git a/stubs/pexpect/pexpect/replwrap.pyi b/stubs/pexpect/pexpect/replwrap.pyi new file mode 100644 index 000000000000..1ef0a541ff8c --- /dev/null +++ b/stubs/pexpect/pexpect/replwrap.pyi @@ -0,0 +1,27 @@ +import sys +from _typeshed import Incomplete + +PY3: Incomplete +basestring = str +PEXPECT_PROMPT: str +PEXPECT_CONTINUATION_PROMPT: str + +class REPLWrapper: + child: Incomplete + prompt: Incomplete + continuation_prompt: Incomplete + def __init__( + self, + cmd_or_spawn, + orig_prompt, + prompt_change, + new_prompt="[PEXPECT_PROMPT>", + continuation_prompt="[PEXPECT_PROMPT+", + extra_init_cmd=None, + ) -> None: ... + def set_prompt(self, orig_prompt, prompt_change) -> None: ... + def run_command(self, command, timeout: float | None = -1, async_: bool = False): ... + +def python(command: str = sys.executable): ... +def bash(command: str = "bash"): ... +def zsh(command: str = "zsh", args=("--no-rcs", "-V", "+Z")): ... diff --git a/stubs/pexpect/pexpect/run.pyi b/stubs/pexpect/pexpect/run.pyi new file mode 100644 index 000000000000..b3b0a0b546ad --- /dev/null +++ b/stubs/pexpect/pexpect/run.pyi @@ -0,0 +1,28 @@ +from _typeshed import FileDescriptorOrPath +from collections.abc import Mapping +from typing import AnyStr + +from .spawnbase import _InputRePattern, _Logfile + +def run( + command: str, + timeout: float | None = 30, + withexitstatus: bool = False, + events: list[tuple[_InputRePattern, AnyStr]] | dict[_InputRePattern, AnyStr] | None = None, + extra_args: None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + **kwargs, +) -> AnyStr | tuple[AnyStr, int]: ... +def runu( + command: str, + timeout: float | None = 30, + withexitstatus: bool = False, + events: list[tuple[_InputRePattern, AnyStr]] | dict[_InputRePattern, AnyStr] | None = None, + extra_args: None = None, + logfile: _Logfile | None = None, + cwd: FileDescriptorOrPath | None = None, + env: Mapping[str, str] | None = None, + **kwargs, +) -> AnyStr | tuple[AnyStr, int]: ... diff --git a/stubs/pexpect/pexpect/screen.pyi b/stubs/pexpect/pexpect/screen.pyi new file mode 100644 index 000000000000..dffc81008b60 --- /dev/null +++ b/stubs/pexpect/pexpect/screen.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete + +NUL: int +ENQ: int +BEL: int +BS: int +HT: int +LF: int +VT: int +FF: int +CR: int +SO: int +SI: int +XON: int +XOFF: int +CAN: int +SUB: int +ESC: int +DEL: int +SPACE: str +PY3: Incomplete +unicode = str + +def constrain(n, min, max): ... + +class screen: + rows: Incomplete + cols: Incomplete + encoding: Incomplete + encoding_errors: Incomplete + decoder: Incomplete + cur_r: int + cur_c: int + cur_saved_r: int + cur_saved_c: int + scroll_row_start: int + scroll_row_end: Incomplete + w: Incomplete + def __init__(self, r: int = 24, c: int = 80, encoding: str = "latin-1", encoding_errors: str = "replace") -> None: ... + def dump(self): ... + def pretty(self): ... + def fill(self, ch=" ") -> None: ... + def fill_region(self, rs, cs, re, ce, ch=" ") -> None: ... + def cr(self) -> None: ... + def lf(self) -> None: ... + def crlf(self) -> None: ... + def newline(self) -> None: ... + def put_abs(self, r, c, ch) -> None: ... + def put(self, ch) -> None: ... + def insert_abs(self, r, c, ch) -> None: ... + def insert(self, ch) -> None: ... + def get_abs(self, r, c): ... + def get(self) -> None: ... + def get_region(self, rs, cs, re, ce): ... + def cursor_constrain(self) -> None: ... + def cursor_home(self, r: int = 1, c: int = 1) -> None: ... + def cursor_back(self, count: int = 1) -> None: ... + def cursor_down(self, count: int = 1) -> None: ... + def cursor_forward(self, count: int = 1) -> None: ... + def cursor_up(self, count: int = 1) -> None: ... + def cursor_up_reverse(self) -> None: ... + def cursor_force_position(self, r, c) -> None: ... + def cursor_save(self) -> None: ... + def cursor_unsave(self) -> None: ... + def cursor_save_attrs(self) -> None: ... + def cursor_restore_attrs(self) -> None: ... + def scroll_constrain(self) -> None: ... + def scroll_screen(self) -> None: ... + def scroll_screen_rows(self, rs, re) -> None: ... + def scroll_down(self) -> None: ... + def scroll_up(self) -> None: ... + def erase_end_of_line(self) -> None: ... + def erase_start_of_line(self) -> None: ... + def erase_line(self) -> None: ... + def erase_down(self) -> None: ... + def erase_up(self) -> None: ... + def erase_screen(self) -> None: ... + def set_tab(self) -> None: ... + def clear_tab(self) -> None: ... + def clear_all_tabs(self) -> None: ... diff --git a/stubs/pexpect/pexpect/socket_pexpect.pyi b/stubs/pexpect/pexpect/socket_pexpect.pyi new file mode 100644 index 000000000000..f3c8d42d0b56 --- /dev/null +++ b/stubs/pexpect/pexpect/socket_pexpect.pyi @@ -0,0 +1,35 @@ +from collections.abc import Iterable +from socket import socket as Socket +from typing import AnyStr + +from .spawnbase import SpawnBase, _Logfile + +__all__ = ["SocketSpawn"] + +class SocketSpawn(SpawnBase[AnyStr]): + args: None + command: None + socket: Socket + child_fd: int + closed: bool + name: str + use_poll: bool + def __init__( + self, + socket: Socket, + args: None = None, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + use_poll: bool = False, + ) -> None: ... + def close(self) -> None: ... + def isalive(self) -> bool: ... + def send(self, s: str | bytes) -> int: ... + def sendline(self, s: str | bytes) -> int: ... + def write(self, s: str | bytes) -> None: ... + def writelines(self, sequence: Iterable[str | bytes]) -> None: ... + def read_nonblocking(self, size: int = 1, timeout: float | None = -1) -> AnyStr: ... diff --git a/stubs/pexpect/pexpect/spawnbase.pyi b/stubs/pexpect/pexpect/spawnbase.pyi new file mode 100644 index 000000000000..d839fddd57f9 --- /dev/null +++ b/stubs/pexpect/pexpect/spawnbase.pyi @@ -0,0 +1,152 @@ +from asyncio import ReadTransport +from collections.abc import Awaitable, Callable, Iterable +from re import Match, Pattern +from typing import IO, AnyStr, Generic, Literal, Protocol, TextIO, TypeAlias, overload, type_check_only + +from ._async import PatternWaiter +from .exceptions import EOF, TIMEOUT +from .expect import searcher_re, searcher_string + +PY3: bool +text_type: type + +class _NullCoder: + @staticmethod + def encode(b: str, final: bool = False): ... + @staticmethod + def decode(b: str, final: bool = False): ... + +@type_check_only +class _Logfile(Protocol): + def write(self, s, /) -> object: ... + def flush(self) -> object: ... + +_ErrorPattern: TypeAlias = type[EOF | TIMEOUT] +_InputStringPattern: TypeAlias = str | bytes | _ErrorPattern +_InputRePattern: TypeAlias = Pattern[str] | Pattern[bytes] | _InputStringPattern +_CompiledStringPattern: TypeAlias = AnyStr | _ErrorPattern +_CompiledRePattern: TypeAlias = Pattern[AnyStr] | _ErrorPattern +_Searcher: TypeAlias = searcher_string[AnyStr] | searcher_re[AnyStr] + +class SpawnBase(Generic[AnyStr]): + encoding: str | None + pid: int | None + flag_eof: bool + stdin: TextIO + stdout: TextIO + stderr: TextIO + searcher: None + ignorecase: bool + before: AnyStr | None + after: _CompiledStringPattern[AnyStr] | None + match: AnyStr | Match[AnyStr] | _ErrorPattern | None + match_index: int | None + terminated: bool + exitstatus: int | None + signalstatus: int | None + status: int | None + child_fd: int + timeout: float | None + delimiter: type[EOF] + logfile: _Logfile | None + logfile_read: _Logfile | None + logfile_send: _Logfile | None + maxread: int + searchwindowsize: int | None + delaybeforesend: float | None + delayafterclose: float + delayafterterminate: float + delayafterread: float | None + softspace: bool + name: str + closed: bool + codec_errors: str + string_type: type[AnyStr] + buffer_type: IO[AnyStr] + crlf: AnyStr + allowed_string_types: tuple[type, ...] + linesep: AnyStr + write_to_stdout: Callable[[AnyStr], int] + async_pw_transport: tuple[PatternWaiter[AnyStr], ReadTransport] | None + def __init__( + self, + timeout: float | None = 30, + maxread: int = 2000, + searchwindowsize: int | None = None, + logfile: _Logfile | None = None, + encoding: str | None = None, + codec_errors: str = "strict", + ) -> None: ... + + @property + def buffer(self) -> AnyStr: ... + @buffer.setter + def buffer(self, value: AnyStr) -> None: ... + + def read_nonblocking(self, size: int = 1, timeout: float | None = None) -> AnyStr: ... + def compile_pattern_list(self, patterns: _InputRePattern | list[_InputRePattern]) -> list[_CompiledRePattern[AnyStr]]: ... + + @overload + def expect( + self, + pattern: _InputRePattern | list[_InputRePattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect( + self, + pattern: _InputRePattern | list[_InputRePattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + @overload + def expect_list( + self, + pattern_list: list[_CompiledRePattern[AnyStr]], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect_list( + self, + pattern_list: list[_CompiledRePattern[AnyStr]], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + @overload + def expect_exact( + self, + pattern_list: _InputStringPattern | Iterable[_InputStringPattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + async_: Literal[False] = False, + ) -> int: ... + @overload + def expect_exact( + self, + pattern_list: _InputStringPattern | Iterable[_InputStringPattern], + timeout: float | None = -1, + searchwindowsize: int | None = -1, + *, + async_: Literal[True], + ) -> Awaitable[int]: ... + + def expect_loop(self, searcher: _Searcher[AnyStr], timeout: float | None = -1, searchwindowsize: int | None = -1) -> int: ... + def read(self, size: int = -1) -> AnyStr: ... + def readline(self, size: int = -1) -> AnyStr: ... + def __iter__(self): ... + def readlines(self, sizehint: int = -1) -> list[AnyStr]: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def __enter__(self): ... + def __exit__(self, etype, evalue, tb) -> None: ... diff --git a/stubs/pexpect/pexpect/utils.pyi b/stubs/pexpect/pexpect/utils.pyi new file mode 100644 index 000000000000..29fd1ae2b2cd --- /dev/null +++ b/stubs/pexpect/pexpect/utils.pyi @@ -0,0 +1,10 @@ +from collections.abc import Mapping + +InterruptedError: type +string_types: tuple[type, ...] + +def is_executable_file(path): ... +def which(filename, env: Mapping[str, str] | None = None): ... +def split_command_line(command_line): ... +def select_ignore_interrupts(iwtd, owtd, ewtd, timeout: float | None = None): ... +def poll_ignore_interrupts(fds, timeout: float | None = None): ... diff --git a/stubs/pika/@tests/stubtest_allowlist.txt b/stubs/pika/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..260f43d685f2 --- /dev/null +++ b/stubs/pika/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# bytes alias for Python 3 compatibility +pika.spec.str + +# Behind a TYPE_CHECKING guard at runtime. +pika.adapters.select_connection.SELECT_ERROR_T +pika.adapters.select_connection.POLLER_PARAMS + +# The implementation has defaults for the arguments that would make the +# created instances unusable, so we require the arguments in the stub. +pika.spec.Queue.DeclareOk.__init__ + +# Type hackary that is unnecessary in the stubs. +pika.connection.ConnectionParameters.DefaultT +pika.connection.ConnectionParameters.T + +# Arguments have a sentinel default, which is not reflected in the stubs. +pika.connection.ConnectionParameters.__init__ + +# These are defined as None, but on initialization are set as callable attributes. +pika.adapters.base_connection._StreamingProtocolShim.connection_made +pika.adapters.base_connection._StreamingProtocolShim.connection_lost +pika.adapters.base_connection._StreamingProtocolShim.eof_received +pika.adapters.base_connection._StreamingProtocolShim.data_received + +# The following methods are not defined directly on this class; +# they are resolved via __getattr__. +pika.adapters.base_connection._StreamingProtocolShim.add_on_close_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_blocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_unblocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_error_callback +pika.adapters.base_connection._StreamingProtocolShim.channel +pika.adapters.base_connection._StreamingProtocolShim.update_secret +pika.adapters.base_connection._StreamingProtocolShim.close +pika.adapters.base_connection._StreamingProtocolShim.is_closed +pika.adapters.base_connection._StreamingProtocolShim.is_closing +pika.adapters.base_connection._StreamingProtocolShim.is_open +pika.adapters.base_connection._StreamingProtocolShim.basic_nack +pika.adapters.base_connection._StreamingProtocolShim.consumer_cancel_notify +pika.adapters.base_connection._StreamingProtocolShim.exchange_exchange_bindings +pika.adapters.base_connection._StreamingProtocolShim.publisher_confirms +pika.adapters.base_connection._StreamingProtocolShim.create_connection +pika.adapters.base_connection._StreamingProtocolShim.ioloop diff --git a/stubs/pika/METADATA.toml b/stubs/pika/METADATA.toml new file mode 100644 index 000000000000..217f389fcdcd --- /dev/null +++ b/stubs/pika/METADATA.toml @@ -0,0 +1,7 @@ +version = "1.4.*" +upstream-repository = "https://github.com/pika/pika" +stub-distribution = "types-pika-ts" # https://github.com/python/typeshed/issues/9246 +optional-dependencies = ["types-gevent"] + +[tool.stubtest] +stubtest-dependencies = ["gevent", "tornado", "twisted"] diff --git a/stubs/pika/pika/__init__.pyi b/stubs/pika/pika/__init__.pyi new file mode 100644 index 000000000000..17e07499aa60 --- /dev/null +++ b/stubs/pika/pika/__init__.pyi @@ -0,0 +1,29 @@ +from typing import Final + +from pika import adapters as adapters +from pika.adapters import ( + BaseConnection as BaseConnection, + BlockingConnection as BlockingConnection, + SelectConnection as SelectConnection, +) +from pika.adapters.utils.connection_workflow import AMQPConnectionWorkflow as AMQPConnectionWorkflow +from pika.connection import ConnectionParameters as ConnectionParameters, SSLOptions as SSLOptions, URLParameters as URLParameters +from pika.credentials import PlainCredentials as PlainCredentials +from pika.delivery_mode import DeliveryMode as DeliveryMode +from pika.spec import BasicProperties as BasicProperties + +__version__: Final[str] + +__all__ = [ + "adapters", + "AMQPConnectionWorkflow", + "BaseConnection", + "BasicProperties", + "BlockingConnection", + "ConnectionParameters", + "DeliveryMode", + "PlainCredentials", + "SelectConnection", + "SSLOptions", + "URLParameters", +] diff --git a/stubs/pika/pika/adapters/__init__.pyi b/stubs/pika/pika/adapters/__init__.pyi new file mode 100644 index 000000000000..803376324d51 --- /dev/null +++ b/stubs/pika/pika/adapters/__init__.pyi @@ -0,0 +1,6 @@ +from pika.adapters.asyncio_connection import AsyncioConnection as AsyncioConnection +from pika.adapters.base_connection import BaseConnection as BaseConnection +from pika.adapters.blocking_connection import BlockingConnection as BlockingConnection +from pika.adapters.select_connection import IOLoop as IOLoop, SelectConnection as SelectConnection + +__all__ = ["AsyncioConnection", "BaseConnection", "BlockingConnection", "SelectConnection", "IOLoop"] diff --git a/stubs/pika/pika/adapters/asyncio_connection.pyi b/stubs/pika/pika/adapters/asyncio_connection.pyi new file mode 100644 index 000000000000..b4f5b7d3b656 --- /dev/null +++ b/stubs/pika/pika/adapters/asyncio_connection.pyi @@ -0,0 +1,77 @@ +import asyncio +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing_extensions import Self + +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils import io_services_utils +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractTimerReference, +) +from pika.connection import Parameters + +LOGGER: Logger + +class AsyncioConnection(BaseConnection[asyncio.AbstractEventLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: asyncio.AbstractEventLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: asyncio.AbstractEventLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _AsyncioIOServicesAdapter( + io_services_utils.SocketConnectionMixin, + io_services_utils.StreamingConnectionMixin, + AbstractIOServices, + AbstractFileDescriptorServices, +): + def __init__(self, loop: asyncio.AbstractEventLoop | None = None) -> None: ... + def get_native_ioloop(self) -> asyncio.AbstractEventLoop: ... + def close(self) -> None: ... + def run(self) -> None: ... + def stop(self) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], object]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerHandle: ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], # type: ignore[override] + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + def set_reader(self, fd: int, on_readable: Callable[[], object]) -> None: ... + def remove_reader(self, fd: int) -> bool: ... + def set_writer(self, fd: int, on_writable: Callable[[], object]) -> None: ... + def remove_writer(self, fd: int) -> bool: ... + +class _TimerHandle(AbstractTimerReference): + def __init__(self, handle: asyncio.Handle) -> None: ... + def cancel(self) -> None: ... + +class _AsyncioIOReference(AbstractIOReference): + def __init__( + self, + future: asyncio.Future[Incomplete], + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], + ) -> None: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/adapters/base_connection.pyi b/stubs/pika/pika/adapters/base_connection.pyi new file mode 100644 index 000000000000..2766489ec660 --- /dev/null +++ b/stubs/pika/pika/adapters/base_connection.pyi @@ -0,0 +1,112 @@ +import abc +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Final, Generic, Literal, TypeVar +from typing_extensions import Self + +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol, AbstractStreamTransport +from pika.callback import CallbackManager +from pika.channel import Channel +from pika.connection import Connection, Parameters +from pika.frame import Method +from pika.spec import Connection as SpecConnection + +LOGGER: Logger + +_IOLoop = TypeVar("_IOLoop") + +class BaseConnection(Connection, Generic[_IOLoop], metaclass=abc.ABCMeta): + def __init__( + self, + parameters: Parameters | None, + on_open_callback: Callable[[Self], object] | None, + on_open_error_callback: Callable[[Self, BaseException], object] | None, + on_close_callback: Callable[[Self, BaseException], object] | None, + nbio: AbstractIOServices, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + @abc.abstractmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + @property + def ioloop(self) -> _IOLoop: ... + +class _StreamingProtocolShim(AbstractStreamProtocol, Generic[_IOLoop]): + conn: BaseConnection[_IOLoop] + def __init__(self, conn: BaseConnection[_IOLoop]) -> None: ... + # These are defined as None, but on initialization are set as callable attributes + def connection_made(self, transport: AbstractStreamTransport) -> None: ... + def connection_lost(self, error: BaseException | None) -> None: ... + def eof_received(self) -> bool: ... + def data_received(self, data: bytes) -> None: ... + + # Next attributes are accessed via getattr() from connection.Connection class: + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above + params: Parameters + callbacks: CallbackManager + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None + def add_on_close_callback(self, callback: Callable[[Self, BaseException], object]) -> None: ... + def add_on_connection_blocked_callback(self, callback: Callable[[Self, Method[SpecConnection.Blocked]], object]) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[Self, Method[SpecConnection.Unblocked]], object] + ) -> None: ... + def add_on_open_callback(self, callback: Callable[[Self], object]) -> None: ... + def add_on_open_error_callback( + self, callback: Callable[[Self, BaseException], object], remove_default: bool = True + ) -> None: ... + def channel( + self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None + ) -> Channel: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack(self) -> bool: ... + @property + def consumer_cancel_notify(self) -> bool: ... + @property + def exchange_exchange_bindings(self) -> bool: ... + @property + def publisher_confirms(self) -> bool: ... + + # Next attributes are accessed via getattr() from BaseConnection class: + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + @property + def ioloop(self) -> _IOLoop: ... diff --git a/stubs/pika/pika/adapters/blocking_connection.pyi b/stubs/pika/pika/adapters/blocking_connection.pyi new file mode 100644 index 000000000000..5dd25332bacb --- /dev/null +++ b/stubs/pika/pika/adapters/blocking_connection.pyi @@ -0,0 +1,286 @@ +from _typeshed import Incomplete +from collections import deque +from collections.abc import Callable, Generator, Mapping, Sequence +from logging import Logger +from types import TracebackType +from typing import Final, Generic, TypeVar, overload +from typing_extensions import Self + +from pika import connection +from pika.adapters.select_connection import SelectConnection +from pika.channel import Channel +from pika.exchange_type import ExchangeType +from pika.frame import Method +from pika.spec import Basic, BasicProperties, Connection, Exchange, Queue, Tx + +T = TypeVar("T", bound=Connection.Blocked | Connection.Unblocked) # noqa: Y001 + +LOGGER: Logger + +class _IoloopTimerContext: + def __init__(self, duration: float, connection: SelectConnection) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def is_ready(self) -> bool: ... + +class _TimerEvt: + __slots__ = ("timer_id", "_callback") + timer_id: object | None + def __init__(self, callback: Callable[[], None]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedUnblockedEvtBase(Generic[T]): + __slots__ = ("_callback", "_method_frame") + def __init__(self, callback: Callable[[Method[T]], None], method_frame: Method[T]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Blocked]): ... +class _ConnectionUnblockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Unblocked]): ... + +class BlockingConnection: + def __init__( + self, + parameters: connection.Parameters | Sequence[connection.Parameters] | None = None, + _impl_class: SelectConnection | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def add_on_connection_blocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Blocked]], None] + ) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Unblocked]], None] + ) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> object: ... + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... + def remove_timeout(self, timeout_id: object) -> None: ... + def update_secret(self, new_secret: str, reason: str) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + def process_data_events(self, time_limit: float | None = 0) -> None: ... + def sleep(self, duration: float) -> None: ... + def channel(self, channel_number: int | None = None) -> BlockingChannel: ... + @property + def is_closed(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack_supported(self) -> bool: ... + @property + def consumer_cancel_notify_supported(self) -> bool: ... + @property + def exchange_exchange_bindings_supported(self) -> bool: ... + @property + def publisher_confirms_supported(self) -> bool: ... + basic_nack = basic_nack_supported + consumer_cancel_notify = consumer_cancel_notify_supported + exchange_exchange_bindings = exchange_exchange_bindings_supported + publisher_confirms = publisher_confirms_supported + +class _ChannelPendingEvt: ... + +class _ConsumerDeliveryEvt(_ChannelPendingEvt): + __slots__ = ("method", "properties", "body") + method: Basic.Deliver + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Deliver, properties: BasicProperties, body: bytes) -> None: ... + +class _ConsumerCancellationEvt(_ChannelPendingEvt): + __slots__ = ("method_frame",) + method_frame: Method[Basic.Cancel] + def __init__(self, method_frame: Method[Basic.Cancel]) -> None: ... + @property + def method(self) -> Basic.Cancel: ... + +class _ReturnedMessageEvt(_ChannelPendingEvt): + __slots__ = ("callback", "channel", "method", "properties", "body") + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + channel: BlockingChannel + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__( + self, + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None], + channel: BlockingChannel, + method: Basic.Return, + properties: BasicProperties, + body: bytes, + ) -> None: ... + def dispatch(self) -> None: ... + +class ReturnedMessage: + __slots__ = ("method", "properties", "body") + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Return, properties: BasicProperties, body: bytes) -> None: ... + +class _ConsumerInfo: + __slots__ = ("consumer_tag", "auto_ack", "on_message_callback", "alternate_event_sink", "state") + SETTING_UP: Final = 1 + ACTIVE: Final = 2 + TEARING_DOWN: Final = 3 + CANCELLED_BY_BROKER: Final = 4 + consumer_tag: str + auto_ack: bool + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None] | None + alternate_event_sink: Callable[[_ChannelPendingEvt], None] | None + state: int + + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], + alternate_event_sink: None = None, + ) -> None: ... + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: None = None, + alternate_event_sink: Callable[[_ChannelPendingEvt], None] = ..., + ) -> None: ... + + @property + def setting_up(self) -> bool: ... + @property + def active(self) -> bool: ... + @property + def tearing_down(self) -> bool: ... + @property + def cancelled_by_broker(self) -> bool: ... + +class _QueueConsumerGeneratorInfo: + __slots__ = ("params", "consumer_tag", "pending_events") + params: tuple[str, bool, bool] + consumer_tag: str + pending_events: deque[_ChannelPendingEvt] + def __init__(self, params: tuple[str, bool, bool], consumer_tag: str) -> None: ... + +class BlockingChannel: + def __init__(self, channel_impl: Channel, connection: BlockingConnection) -> None: ... + def __int__(self) -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + @property + def channel_number(self) -> int: ... + @property + def connection(self) -> BlockingConnection: ... + @property + def is_closed(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def consumer_tags(self) -> list[str]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown") -> None: ... + def flow(self, active: bool) -> bool: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], None]) -> None: ... + def add_on_return_callback( + self, callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + ) -> None: ... + def basic_consume( + self, + queue: str, + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> str: ... + def basic_cancel(self, consumer_tag: str) -> list[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + def start_consuming(self) -> None: ... + def stop_consuming(self, consumer_tag: str | None = None) -> None: ... + + @overload + def consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: None = None, # different between overloads + consumer_tag: str | None = None, + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + @overload + def consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: float = ..., # different between overloads + consumer_tag: str | None = None, + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes] | tuple[None, None, None]]: ... + + def get_waiting_message_count(self) -> int: ... + def cancel(self) -> int: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_get( + self, queue: str, auto_ack: bool = False + ) -> tuple[Basic.GetOk, BasicProperties, bytes] | tuple[None, None, None]: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> None: ... + def basic_qos(self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False) -> None: ... + def basic_recover(self, requeue: bool = False) -> None: ... + def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None: ... + def confirm_delivery(self) -> None: ... + def exchange_declare( + self, + exchange: str, + exchange_type: ExchangeType | str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + def exchange_delete(self, exchange: str | None = None, if_unused: bool = False) -> Method[Exchange.DeleteOk]: ... + def exchange_bind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Exchange.BindOk]: ... + def exchange_unbind( + self, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + ) -> Method[Exchange.UnbindOk]: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Method[Queue.DeclareOk]: ... + def queue_delete(self, queue: str, if_unused: bool = False, if_empty: bool = False) -> Method[Queue.DeleteOk]: ... + def queue_purge(self, queue: str) -> Method[Queue.PurgeOk]: ... + def queue_bind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Queue.BindOk]: ... + def queue_unbind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Method[Queue.UnbindOk]: ... + def tx_select(self) -> Method[Tx.SelectOk]: ... + def tx_commit(self) -> Method[Tx.CommitOk]: ... + def tx_rollback(self) -> Method[Tx.RollbackOk]: ... diff --git a/stubs/pika/pika/adapters/gevent_connection.pyi b/stubs/pika/pika/adapters/gevent_connection.pyi new file mode 100644 index 000000000000..995579bf4991 --- /dev/null +++ b/stubs/pika/pika/adapters/gevent_connection.pyi @@ -0,0 +1,93 @@ +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Final +from typing_extensions import Self + +from gevent._types import _Loop, _TimerWatcher +from gevent.hub import Hub +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOReference, AbstractIOServices +from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop, SelectorIOServicesAdapter, _SupportsCancel +from pika.connection import Parameters + +LOGGER: Logger + +class GeventConnection(BaseConnection[_Loop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: _Loop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _Loop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _TSafeCallbackQueue: + def __init__(self) -> None: ... + @property + def fd(self) -> int: ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... + def run_next_callback(self) -> None: ... + +class _GeventSelectorIOLoop(AbstractSelectorIOLoop[_TimerWatcher]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + def __init__(self, gevent_hub: Hub | None = None) -> None: ... + def close(self) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def add_callback(self, callback: Callable[[], object]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerWatcher: ... + def remove_timeout(self, timeout_handle: _TimerWatcher) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... + +class _GeventSelectorIOServicesAdapter(SelectorIOServicesAdapter): + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + +class _GeventIOLoopIOHandle(AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _GeventAddressResolver: + __slots__ = ("_loop", "_on_done", "_greenlet", "_ga_host", "_ga_port", "_ga_family", "_ga_socktype", "_ga_proto", "_ga_flags") + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... + def start(self) -> None: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/adapters/select_connection.pyi b/stubs/pika/pika/adapters/select_connection.pyi new file mode 100644 index 000000000000..09d88fde568b --- /dev/null +++ b/stubs/pika/pika/adapters/select_connection.pyi @@ -0,0 +1,118 @@ +import abc +import select +from collections.abc import Callable, Sequence +from logging import Logger +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict +from typing_extensions import Self + +import pika.compat +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices +from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop +from pika.connection import Parameters + +SELECT_ERROR_T: TypeAlias = OSError | IOError | InterruptedError | select.error + +class POLLER_PARAMS(TypedDict): + get_wait_seconds: Callable[[], float | None] + process_timeouts: Callable[[], None] + +LOGGER: Logger +SELECT_TYPE: Literal["epoll", "kqueue", "poll"] | None + +class SelectConnection(BaseConnection[IOLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: IOLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + +class _Timeout: + __slots__ = ("deadline", "callback") + deadline: float + callback: Callable[[], None] + def __init__(self, deadline: float, callback: Callable[[], None]) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + +class _Timer: + def __init__(self) -> None: ... + def close(self) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _Timeout: ... + def remove_timeout(self, timeout: _Timeout) -> None: ... + def get_remaining_interval(self) -> float | None: ... + def process_timeouts(self) -> None: ... + +class PollEvents: + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + HANGUP: Final[int] + +class IOLoop(AbstractSelectorIOLoop[_Timeout]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + def __init__(self) -> None: ... + def close(self) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], object]) -> None: ... + add_callback = add_callback_threadsafe + def process_timeouts(self) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def activate_poller(self) -> None: ... + def deactivate_poller(self) -> None: ... + def poll(self) -> None: ... + +class _PollerBase(pika.compat.AbstractBase, metaclass=abc.ABCMeta): + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def close(self) -> None: ... + def wake_threadsafe(self) -> None: ... + def add_handler(self, fileno: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fileno: int, events: int) -> None: ... + def remove_handler(self, fileno: int) -> None: ... + def activate_poller(self) -> None: ... + def deactivate_poller(self) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + @abc.abstractmethod + def poll(self) -> None: ... + +class SelectPoller(_PollerBase): + POLL_TIMEOUT_MULT: ClassVar[int] + def poll(self) -> None: ... + +class KQueuePoller(_PollerBase): + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def poll(self) -> None: ... + +class PollPoller(_PollerBase): + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... + def poll(self) -> None: ... + +class EPollPoller(PollPoller): + POLL_TIMEOUT_MULT: ClassVar[int] diff --git a/stubs/pika/pika/adapters/tornado_connection.pyi b/stubs/pika/pika/adapters/tornado_connection.pyi new file mode 100644 index 000000000000..7a32602a0798 --- /dev/null +++ b/stubs/pika/pika/adapters/tornado_connection.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from logging import Logger +from typing import TypeAlias +from typing_extensions import Self + +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices +from pika.connection import Parameters + +_IOLoop: TypeAlias = Incomplete # actual type is tornado.ioloop.IOLoop + +LOGGER: Logger + +class TornadoConnection(BaseConnection[_IOLoop]): + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + custom_ioloop: _IOLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Self | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... diff --git a/stubs/pika/pika/adapters/twisted_connection.pyi b/stubs/pika/pika/adapters/twisted_connection.pyi new file mode 100644 index 000000000000..5fcaa6835c90 --- /dev/null +++ b/stubs/pika/pika/adapters/twisted_connection.pyi @@ -0,0 +1,169 @@ +# twisted is optional and self-contained in this module. +# We don't want to force it as a dependency but that means we also can't test it with type-checkers given the current setup. + +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import Generic, NamedTuple, TypeVar +from typing_extensions import Self + +from pika import amqp_object +from pika.adapters.utils.nbio_interface import AbstractTimerReference +from pika.channel import Channel +from pika.connection import Connection, ConnectionParameters, Parameters +from pika.exchange_type import ExchangeType +from pika.spec import BasicProperties +from twisted.internet.base import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + DelayedCall, + ReactorBase, +) +from twisted.internet.defer import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + Deferred, + DeferredQueue, +) +from twisted.internet.interfaces import ITransport # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.internet.protocol import Protocol # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from twisted.python.failure import Failure # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + +LOGGER: Logger + +_T = TypeVar("_T") + +class ClosableDeferredQueue(DeferredQueue[_T], Generic[_T]): # pyright: ignore[reportUntypedBaseClass] # noqa: Y060 + closed: Failure | BaseException | None + def __init__(self, size: int | None = None, backlog: int | None = None) -> None: ... + # Returns a Deferred with an error if fails. None if success + def put(self, obj: _T) -> Deferred[Failure | BaseException] | None: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest + def get(self) -> Deferred[Failure | BaseException | _T]: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest + pending: list[_T] + def close(self, reason: Failure | BaseException | None) -> None: ... + +class ReceivedMessage(NamedTuple): + channel: TwistedChannel + method: amqp_object.Method + properties: BasicProperties + body: bytes + +class TwistedChannel: + on_closed: Deferred[Incomplete | Failure | BaseException | None] + def __init__(self, channel: Channel) -> None: ... + @property + def channel_number(self) -> int: ... + @property + def connection(self) -> Connection: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def flow_active(self) -> bool: ... + @property + def consumer_tags(self) -> list[str]: ... + def callback_deferred(self, deferred: Deferred[Incomplete], replies: Iterable[Incomplete]) -> None: ... + def add_on_return_callback(self, callback: Callable[[ReceivedMessage], None]) -> None: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_cancel(self, consumer_tag: str = "") -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException]: ... + def basic_get(self, queue: str, auto_ack: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> Deferred[Incomplete | Failure | BaseException]: ... + def basic_qos( + self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_reject(self, delivery_tag: int, requeue: bool = True): ... + def basic_recover(self, requeue: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown"): ... + def confirm_delivery(self) -> Deferred[Incomplete | None]: ... + def exchange_bind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_declare( + self, + exchange, + exchange_type: str | ExchangeType = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_delete( + self, exchange: str | None = None, if_unused: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def exchange_unbind( + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def flow(self, active: bool = True) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def open(self): ... + def queue_bind( + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_delete( + self, queue: str, if_unused: bool = False, if_empty: bool = False + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_purge(self, queue: str) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_unbind( + self, queue: str, exchange: str | None, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None + ) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_commit(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_rollback(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def tx_select(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... + +class _TwistedConnectionAdapter(Connection): + def __init__( + self, + parameters: Parameters | None, + on_open_callback: Callable[[Self], object] | None, + on_open_error_callback: Callable[[Self, BaseException], object] | None, + on_close_callback: Callable[[Self, Exception], object] | None, + custom_reactor: ReactorBase | None = None, + ) -> None: ... + def connection_made(self, transport: ITransport) -> None: ... + def connection_lost(self, error: Exception) -> None: ... + def data_received(self, data: bytes) -> None: ... + +class TwistedProtocolConnection(Protocol): # pyright: ignore[reportUntypedBaseClass] + ready: Deferred[None] | None + closed: Deferred[None] | Failure | BaseException | None + def __init__(self, parameters: ConnectionParameters | None = None, custom_reactor: ReactorBase | None = None) -> None: ... + def channel(self, channel_number: int | None = None) -> Deferred[TwistedChannel]: ... + @property + def is_open(self) -> bool: ... + @property + def is_closed(self) -> bool: ... + def close( + self, reply_code: int = 200, reply_text: str = "Normal shutdown" + ) -> Deferred[None] | Failure | BaseException | None: ... + def dataReceived(self, data: bytes) -> None: ... + def connectionLost(self, reason: Failure | BaseException = ...) -> None: ... + def makeConnection(self, transport: ITransport) -> None: ... + def connectionReady(self) -> TwistedProtocolConnection | Deferred[TwistedProtocolConnection]: ... + +class _TimerHandle(AbstractTimerReference): + def __init__(self, handle: DelayedCall) -> None: ... + def cancel(self) -> None: ... diff --git a/stubs/pika/pika/adapters/utils/__init__.pyi b/stubs/pika/pika/adapters/utils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pika/pika/adapters/utils/connection_workflow.pyi b/stubs/pika/pika/adapters/utils/connection_workflow.pyi new file mode 100644 index 000000000000..a2284221bde8 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/connection_workflow.pyi @@ -0,0 +1,61 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence + +import pika.compat +import pika.connection +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol + +class AMQPConnectorException(Exception): ... +class AMQPConnectorStackTimeout(AMQPConnectorException): ... +class AMQPConnectorAborted(AMQPConnectorException): ... +class AMQPConnectorWrongState(AMQPConnectorException): ... + +class AMQPConnectorPhaseErrorBase(AMQPConnectorException): + exception: BaseException + def __init__(self, exception: BaseException, *args: object) -> None: ... + +class AMQPConnectorSocketConnectError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectorTransportSetupError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectorAMQPHandshakeError(AMQPConnectorPhaseErrorBase): ... +class AMQPConnectionWorkflowAborted(AMQPConnectorException): ... +class AMQPConnectionWorkflowWrongState(AMQPConnectorException): ... + +class AMQPConnectionWorkflowFailed(AMQPConnectorException): + exceptions: tuple[BaseException, ...] + def __init__(self, exceptions: Iterable[BaseException], *args: object) -> None: ... + +class AMQPConnector: + def __init__( + self, conn_factory: Callable[[pika.connection.Parameters], AbstractStreamProtocol], nbio: AbstractIOServices + ) -> None: ... + def start( + self, + addr_record: tuple[ # tuple taken result of socket.getaddrinfo + int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes] + ], + conn_params: pika.connection.Parameters, + on_done: Callable[[pika.connection.Connection | BaseException], None], + ) -> None: ... + def abort(self) -> None: ... + +class AbstractAMQPConnectionWorkflow(pika.compat.AbstractBase): + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... + def abort(self) -> None: ... + +class AMQPConnectionWorkflow(AbstractAMQPConnectionWorkflow): + def __init__(self, _until_first_amqp_attempt: bool = False) -> None: ... + def set_io_services(self, nbio: AbstractIOServices) -> None: ... + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... + def abort(self) -> None: ... diff --git a/stubs/pika/pika/adapters/utils/io_services_utils.pyi b/stubs/pika/pika/adapters/utils/io_services_utils.pyi new file mode 100644 index 000000000000..604e533bc5f3 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/io_services_utils.pyi @@ -0,0 +1,89 @@ +import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext, SSLSocket +from typing import Any + +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractStreamProtocol, + AbstractStreamTransport, +) +from pika.adapters.utils.selector_ioloop_adapter import _SupportsCancel + +def check_callback_arg(callback: Callable[..., Any], name: str) -> None: ... +def check_fd_arg(fd: int) -> None: ... + +class SocketConnectionMixin: + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> _AsyncServiceAsyncHandle: ... + +class StreamingConnectionMixin: + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... + +class _AsyncServiceAsyncHandle(AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _AsyncSocketConnector: + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + sock: socket, + resolved_addr: tuple[str, int], + on_done: Callable[[BaseException | None], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... + +class _AsyncStreamConnector: + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + ssl_context: SSLContext, + server_hostname: str | None, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... + +class _AsyncTransportBase(AbstractStreamTransport, metaclass=abc.ABCMeta): + class RxEndOfFile(OSError): + def __init__(self) -> None: ... + + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... + def abort(self) -> None: ... + def get_protocol(self) -> AbstractStreamProtocol: ... + def get_write_buffer_size(self) -> int: ... + +class _AsyncPlaintextTransport(_AsyncTransportBase): + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... + def write(self, data: bytes) -> None: ... + +class _AsyncSSLTransport(_AsyncTransportBase): + def __init__( + self, sock: SSLSocket, protocol: AbstractStreamProtocol, nbio: AbstractIOServices | AbstractFileDescriptorServices + ) -> None: ... + def write(self, data: bytes) -> None: ... diff --git a/stubs/pika/pika/adapters/utils/nbio_interface.pyi b/stubs/pika/pika/adapters/utils/nbio_interface.pyi new file mode 100644 index 000000000000..6b963642813e --- /dev/null +++ b/stubs/pika/pika/adapters/utils/nbio_interface.pyi @@ -0,0 +1,85 @@ +import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext + +import pika.compat + +class AbstractIOServices(pika.compat.AbstractBase, metaclass=abc.ABCMeta): + @abc.abstractmethod + def get_native_ioloop(self) -> object: ... + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def run(self) -> None: ... + @abc.abstractmethod + def stop(self) -> None: ... + @abc.abstractmethod + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... + @abc.abstractmethod + def call_later(self, delay: float, callback: Callable[..., None]) -> AbstractTimerReference: ... + @abc.abstractmethod + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... + @abc.abstractmethod + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> AbstractIOReference: ... + @abc.abstractmethod + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... + +class AbstractFileDescriptorServices(pika.compat.AbstractBase): + @abc.abstractmethod + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... + @abc.abstractmethod + def remove_reader(self, fd: int) -> bool: ... + @abc.abstractmethod + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... + @abc.abstractmethod + def remove_writer(self, fd: int) -> bool: ... + +class AbstractTimerReference(pika.compat.AbstractBase): + @abc.abstractmethod + def cancel(self) -> None: ... + +class AbstractIOReference(pika.compat.AbstractBase): + @abc.abstractmethod + def cancel(self) -> bool: ... + +class AbstractStreamProtocol(pika.compat.AbstractBase): + @abc.abstractmethod + def connection_made(self, transport: AbstractStreamTransport) -> None: ... + @abc.abstractmethod + def connection_lost(self, error: BaseException | None) -> None: ... + @abc.abstractmethod + def eof_received(self) -> bool | None: ... + @abc.abstractmethod + def data_received(self, data: bytes) -> None: ... + +class AbstractStreamTransport(pika.compat.AbstractBase): + @abc.abstractmethod + def abort(self) -> None: ... + @abc.abstractmethod + def get_protocol(self) -> AbstractStreamProtocol: ... + @abc.abstractmethod + def write(self, data: bytes) -> None: ... + @abc.abstractmethod + def get_write_buffer_size(self) -> int: ... diff --git a/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi b/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi new file mode 100644 index 000000000000..020017eacaf4 --- /dev/null +++ b/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi @@ -0,0 +1,111 @@ +import abc +from collections.abc import Callable +from logging import Logger +from typing import Final, Generic, Protocol, TypeVar, type_check_only + +from pika.adapters.utils import io_services_utils, nbio_interface + +LOGGER: Logger + +_Timeout = TypeVar("_Timeout", bound=object, default=object) + +@type_check_only +class _SupportsCancel(Protocol): + def cancel(self) -> bool: ... + +class AbstractSelectorIOLoop(Generic[_Timeout], metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def READ(self) -> int: ... + @property + @abc.abstractmethod + def WRITE(self) -> int: ... + @property + @abc.abstractmethod + def ERROR(self) -> int: ... + @abc.abstractmethod + def close(self) -> None: ... + @abc.abstractmethod + def start(self) -> None: ... + @abc.abstractmethod + def stop(self) -> None: ... + @abc.abstractmethod + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... + @abc.abstractmethod + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... + @abc.abstractmethod + def add_callback(self, callback: Callable[[], object]) -> None: ... + @abc.abstractmethod + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + @abc.abstractmethod + def update_handler(self, fd: int, events: int) -> None: ... + @abc.abstractmethod + def remove_handler(self, fd: int) -> None: ... + +class SelectorIOServicesAdapter( + io_services_utils.SocketConnectionMixin, + io_services_utils.StreamingConnectionMixin, + nbio_interface.AbstractIOServices, + nbio_interface.AbstractFileDescriptorServices, + Generic[_Timeout], +): + def __init__(self, native_loop: AbstractSelectorIOLoop[_Timeout]) -> None: ... + def get_native_ioloop(self) -> AbstractSelectorIOLoop[_Timeout]: ... + def close(self) -> None: ... + def run(self) -> None: ... + def stop(self) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _TimerHandle: ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> nbio_interface.AbstractIOReference: ... + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... + def remove_reader(self, fd: int) -> bool: ... + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... + def remove_writer(self, fd: int) -> bool: ... + +class _FileDescriptorCallbacks: + __slots__ = ("reader", "writer") + reader: Callable[[], None] + writer: Callable[[], None] + def __init__(self, reader: Callable[[], None] | None = None, writer: Callable[[], None] | None = None) -> None: ... + +class _TimerHandle(nbio_interface.AbstractTimerReference): + def __init__(self, handle: object, loop: AbstractSelectorIOLoop) -> None: ... + def cancel(self) -> None: ... + +class _SelectorIOLoopIOHandle(nbio_interface.AbstractIOReference): + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... + +class _AddressResolver: + NOT_STARTED: Final = 0 + ACTIVE: Final = 1 + CANCELED: Final = 2 + COMPLETED: Final = 3 + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... + def start(self) -> _SelectorIOLoopIOHandle: ... + def cancel(self) -> bool: ... diff --git a/stubs/pika/pika/amqp_object.pyi b/stubs/pika/pika/amqp_object.pyi new file mode 100644 index 000000000000..9f412173e43a --- /dev/null +++ b/stubs/pika/pika/amqp_object.pyi @@ -0,0 +1,20 @@ +from typing import ClassVar + +class AMQPObject: + NAME: ClassVar[str] + INDEX: ClassVar[int | None] + def __eq__(self, other: AMQPObject | None) -> bool: ... # type: ignore[override] + +class Class(AMQPObject): ... + +class Method(AMQPObject): + # This is a class attribute in the implementation, but subclasses use @property, + # so it's more convenient to use that here as well. + @property + def synchronous(self) -> bool: ... + def get_properties(self) -> Properties: ... + def get_body(self) -> bytes: ... + def encode(self) -> list[bytes]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Method: ... + +class Properties(AMQPObject): ... diff --git a/stubs/pika/pika/callback.pyi b/stubs/pika/pika/callback.pyi new file mode 100644 index 000000000000..852fc1643dc5 --- /dev/null +++ b/stubs/pika/pika/callback.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Mapping +from logging import Logger +from typing import Any, Final, Literal, ParamSpec, TypeAlias, TypeVar + +from .amqp_object import AMQPObject + +_P = ParamSpec("_P") +_R = TypeVar("_R") +AMQPValue: TypeAlias = type[AMQPObject] | AMQPObject | int | str + +LOGGER: Logger + +def name_or_value(value: AMQPValue) -> str: ... +def sanitize_prefix(function: Callable[_P, _R]) -> Callable[_P, _R]: ... +def check_for_prefix_and_key(function: Callable[_P, _R]) -> Callable[_P, _R | Literal[False]]: ... + +class CallbackManager: + CALLS: Final = "calls" + ARGUMENTS: Final = "arguments" + DUPLICATE_WARNING: Final = 'Duplicate callback found for "%s:%s"' + CALLBACK: Final = "callback" + ONE_SHOT: Final = "one_shot" + ONLY_CALLER: Final = "only" + def __init__(self) -> None: ... + def add( + self, + prefix: str | int, + key: AMQPValue, + # Parameter type must match arguments passed to process() + callback: Callable[..., object], + one_shot: bool = True, + only_caller: object | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> tuple[str | int, str | object]: ... + def clear(self) -> None: ... + def cleanup(self, prefix: str | int) -> bool: ... + def pending(self, prefix: str | int, key: AMQPValue) -> int | None: ... + def process( + self, + prefix: str | int, + key: AMQPValue, + caller, + *args: Any, # Arguments depends on callbacks stored on self._stack + **keywords: Any, + ) -> bool: ... + def remove( + self, + prefix: str | int, + key: AMQPValue, + callback_value: Callable[..., object] | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> bool: ... + def remove_all(self, prefix: str | int, key: AMQPValue) -> Literal[False] | None: ... diff --git a/stubs/pika/pika/channel.pyi b/stubs/pika/pika/channel.pyi new file mode 100644 index 000000000000..7fdbbd93d7b6 --- /dev/null +++ b/stubs/pika/pika/channel.pyi @@ -0,0 +1,165 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import Final, TypeVar +from typing_extensions import Self + +from . import amqp_object +from .callback import CallbackManager +from .connection import Connection +from .exchange_type import ExchangeType +from .frame import Body, Header, Method +from .spec import Basic, BasicProperties, Confirm, Exchange, Queue, Tx + +_Method = TypeVar("_Method", bound=amqp_object.Method) + +LOGGER: Logger +MAX_CHANNELS: Final = 65535 + +class Channel: + CLOSED: Final = 0 + OPENING: Final = 1 + OPEN: Final = 2 + CLOSING: Final = 3 + + channel_number: int + callbacks: CallbackManager + connection: Connection + flow_active: bool + + def __init__(self, connection: Connection, channel_number: int, on_open_callback: Callable[[Self], object]) -> None: ... + def __int__(self) -> int: ... + def add_callback(self, callback: Callable[..., object], replies: Iterable[Incomplete], one_shot: bool = True) -> None: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], object]) -> None: ... + def add_on_close_callback(self, callback: Callable[[Channel, Exception], object]) -> None: ... + def add_on_flow_callback(self, callback: Callable[[bool], object]) -> None: ... + def add_on_return_callback(self, callback: Callable[[Channel, Basic.Return, BasicProperties, bytes], object]) -> None: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_cancel( + self, consumer_tag: str = "", callback: Callable[[Method[Basic.CancelOk]], object] | None = None + ) -> None: ... + def basic_consume( + self, + queue: str, + on_message_callback: Callable[[Channel, Basic.Deliver, BasicProperties, bytes], object], + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Basic.ConsumeOk]], object] | None = None, + ) -> str: ... + def basic_get( + self, queue: str, callback: Callable[[Channel, Basic.GetOk, BasicProperties, bytes], object], auto_ack: bool = False + ) -> None: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + def basic_publish( + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, + ) -> None: ... + def basic_qos( + self, + prefetch_size: int = 0, + prefetch_count: int = 0, + global_qos: bool = False, + callback: Callable[[Method[Basic.QosOk]], object] | None = None, + ) -> None: ... + def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None: ... + def basic_recover( + self, requeue: bool = False, callback: Callable[[Method[Basic.RecoverOk]], object] | None = None + ) -> None: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown") -> None: ... + def confirm_delivery( + self, + ack_nack_callback: Callable[[Method[Basic.Ack | Basic.Nack]], object], + callback: Callable[[Method[Confirm.SelectOk]], object] | None = None, + ) -> None: ... + @property + def consumer_tags(self) -> list[str]: ... + def exchange_bind( + self, + destination: str, + source: str, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.BindOk]], object] | None = None, + ) -> None: ... + def exchange_declare( + self, + exchange: str, + exchange_type: ExchangeType | str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.DeclareOk]], object] | None = None, + ) -> None: ... + def exchange_delete( + self, + exchange: str | None = None, + if_unused: bool = False, + callback: Callable[[Method[Exchange.DeleteOk]], object] | None = None, + ) -> None: ... + def exchange_unbind( + self, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Exchange.UnbindOk]], object] | None = None, + ) -> None: ... + def flow(self, active: bool, callback: Callable[[bool], object] | None = None) -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def is_opening(self) -> bool: ... + def open(self) -> None: ... + def queue_bind( + self, + queue: str, + exchange: str, + routing_key: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.BindOk]], object] | None = None, + ) -> None: ... + def queue_declare( + self, + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.DeclareOk]], object] | None = None, + ) -> None: ... + def queue_delete( + self, + queue: str, + if_unused: bool = False, + if_empty: bool = False, + callback: Callable[[Method[Queue.DeleteOk]], object] | None = None, + ) -> None: ... + def queue_purge(self, queue: str, callback: Callable[[Method[Queue.PurgeOk]], object] | None = None) -> None: ... + def queue_unbind( + self, + queue: str, + exchange: str | None = None, + routing_key: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, + callback: Callable[[Method[Queue.UnbindOk]], object] | None = None, + ): ... + def tx_commit(self, callback: Callable[[Method[Tx.CommitOk]], object] | None = None) -> None: ... + def tx_rollback(self, callback: Callable[[Method[Tx.RollbackOk]], object] | None = None) -> None: ... + def tx_select(self, callback: Callable[[Method[Tx.SelectOk]], object] | None = None) -> None: ... + +class ContentFrameAssembler: + def __init__(self) -> None: ... + def process(self, frame_value: Method[_Method] | Header | Body) -> tuple[Method[_Method], Header, bytes] | None: ... diff --git a/stubs/pika/pika/compat.pyi b/stubs/pika/pika/compat.pyi new file mode 100644 index 000000000000..19237f6be186 --- /dev/null +++ b/stubs/pika/pika/compat.pyi @@ -0,0 +1,35 @@ +import socket +import sys +from abc import ABCMeta +from re import Pattern +from typing import Final, SupportsIndex + +RE_NUM: Final[Pattern[str]] +ON_LINUX: Final[bool] +ON_OSX: Final[bool] +ON_WINDOWS: Final[bool] + +class AbstractBase(metaclass=ABCMeta): ... + +SOCKET_ERROR = OSError +SOL_TCP: Final[int] +HAVE_SIGNAL: Final[bool] +str_or_bytes: Final[tuple[type[str], type[bytes]]] + +def time_now() -> float: ... +def byte(*args: SupportsIndex) -> bytes: ... + +class long(int): ... + +def as_bytes(value: str | bytes) -> bytes: ... +def to_digit(value: str) -> int: ... +def get_linux_version(release_str: str) -> tuple[int, int, int]: ... + +if sys.platform == "linux": + LINUX_VERSION: Final[tuple[int, int, int]] +else: + LINUX_VERSION: Final[None] + +def nonblocking_socketpair( + family: int = socket.AF_INET, socket_type: int = socket.SOCK_STREAM, proto: int = 0 +) -> tuple[socket.socket, socket.socket]: ... diff --git a/stubs/pika/pika/connection.pyi b/stubs/pika/pika/connection.pyi new file mode 100644 index 000000000000..0264ccc017e0 --- /dev/null +++ b/stubs/pika/pika/connection.pyi @@ -0,0 +1,231 @@ +import abc +import ssl +from _typeshed import Incomplete +from collections.abc import Callable +from logging import Logger +from typing import Final, Literal +from typing_extensions import Self + +from .callback import CallbackManager +from .channel import Channel +from .compat import AbstractBase +from .credentials import PlainCredentials, _Credentials +from .frame import Method +from .spec import Connection as SpecConnection + +PRODUCT: Final = "Pika Python Client Library" +LOGGER: Logger + +class Parameters: + __slots__ = ( + "_blocked_connection_timeout", + "_channel_max", + "_client_properties", + "_connection_attempts", + "_credentials", + "_frame_max", + "_heartbeat", + "_host", + "_locale", + "_port", + "_retry_delay", + "_socket_timeout", + "_stack_timeout", + "_ssl_options", + "_virtual_host", + "_tcp_options", + ) + DEFAULT_USERNAME: Final = "guest" + DEFAULT_PASSWORD: Final = "guest" + DEFAULT_BLOCKED_CONNECTION_TIMEOUT: Final = None + DEFAULT_CHANNEL_MAX: Final = 65535 + DEFAULT_CLIENT_PROPERTIES: Final = None + DEFAULT_CREDENTIALS: Final[PlainCredentials] + DEFAULT_CONNECTION_ATTEMPTS: Final = 1 + DEFAULT_FRAME_MAX: Final = 131072 + DEFAULT_HEARTBEAT_TIMEOUT: None + DEFAULT_HOST: Final = "localhost" + DEFAULT_LOCALE: Final = "en_US" + DEFAULT_PORT: Final = 5672 + DEFAULT_RETRY_DELAY: Final = 2.0 + DEFAULT_SOCKET_TIMEOUT: Final = 10.0 + DEFAULT_STACK_TIMEOUT: Final = 15.0 + DEFAULT_SSL: Final = False + DEFAULT_SSL_OPTIONS: Final = None + DEFAULT_SSL_PORT: Final = 5671 + DEFAULT_VIRTUAL_HOST: Final = "/" + DEFAULT_TCP_OPTIONS: Final = None + def __init__(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + + @property + def blocked_connection_timeout(self) -> float | None: ... + @blocked_connection_timeout.setter + def blocked_connection_timeout(self, value: float | None) -> None: ... + + @property + def channel_max(self) -> int: ... + @channel_max.setter + def channel_max(self, value: int) -> None: ... + + @property + def client_properties(self) -> dict[Incomplete, Incomplete] | None: ... + @client_properties.setter + def client_properties(self, value: dict[Incomplete, Incomplete] | None) -> None: ... + + @property + def connection_attempts(self) -> int: ... + @connection_attempts.setter + def connection_attempts(self, value: int) -> None: ... + + @property + def credentials(self) -> _Credentials: ... + @credentials.setter + def credentials(self, value: _Credentials) -> None: ... + + @property + def frame_max(self) -> int: ... + @frame_max.setter + def frame_max(self, value: int) -> None: ... + + @property + def heartbeat(self) -> int | Callable[[Connection, int], int] | None: ... + @heartbeat.setter + def heartbeat(self, value: int | Callable[[Connection, int], int] | None) -> None: ... + + @property + def host(self) -> str: ... + @host.setter + def host(self, value: str) -> None: ... + + @property + def locale(self) -> str: ... + @locale.setter + def locale(self, value: str) -> None: ... + + @property + def port(self) -> int: ... + @port.setter + def port(self, value: int | str) -> None: ... + + @property + def retry_delay(self) -> int | float: ... + @retry_delay.setter + def retry_delay(self, value: float) -> None: ... + + @property + def socket_timeout(self) -> float | None: ... + @socket_timeout.setter + def socket_timeout(self, value: float | None) -> None: ... + + @property + def stack_timeout(self) -> float | None: ... + @stack_timeout.setter + def stack_timeout(self, value: float | None) -> None: ... + + @property + def ssl_options(self) -> SSLOptions | None: ... + @ssl_options.setter + def ssl_options(self, value: SSLOptions | None) -> None: ... + + @property + def virtual_host(self) -> str: ... + @virtual_host.setter + def virtual_host(self, value: str) -> None: ... + + @property + def tcp_options(self) -> dict[str, Incomplete] | None: ... + @tcp_options.setter + def tcp_options(self, value: dict[str, Incomplete] | None) -> None: ... + +class ConnectionParameters(Parameters): + __slots__ = () + def __init__( + self, + host: str = ..., + port: int = ..., + virtual_host: str = ..., + credentials: _Credentials = ..., + channel_max: int = ..., + frame_max: int = ..., + heartbeat: int | Callable[[Connection, int], int] | None = ..., + ssl_options: SSLOptions | None = ..., + connection_attempts: int = ..., + retry_delay: float = ..., + socket_timeout: float | None = ..., + stack_timeout: float | None = ..., + locale: str = ..., + blocked_connection_timeout: float | None = ..., + client_properties: dict[str, Incomplete] | None = ..., + tcp_options: dict[str, Incomplete] | None = ..., + ) -> None: ... + +class URLParameters(Parameters): + __slots__ = ("_all_url_query_values",) + def __init__(self, url: str) -> None: ... + +class SSLOptions: + __slots__ = ("context", "server_hostname") + context: ssl.SSLContext + server_hostname: str | None + def __init__(self, context: ssl.SSLContext, server_hostname: str | None = None) -> None: ... + +class Connection(AbstractBase, metaclass=abc.ABCMeta): + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above + params: Parameters + callbacks: CallbackManager + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None + def __init__( + self, + parameters: Parameters | None = None, + on_open_callback: Callable[[Self], object] | None = None, + on_open_error_callback: Callable[[Self, BaseException], object] | None = None, + on_close_callback: Callable[[Self, BaseException], object] | None = None, + internal_connection_workflow: bool = True, + ) -> None: ... + def add_on_close_callback(self, callback: Callable[[Self, BaseException], object]) -> None: ... + def add_on_connection_blocked_callback(self, callback: Callable[[Self, Method[SpecConnection.Blocked]], object]) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[Self, Method[SpecConnection.Unblocked]], object] + ) -> None: ... + def add_on_open_callback(self, callback: Callable[[Self], object]) -> None: ... + def add_on_open_error_callback( + self, callback: Callable[[Self, BaseException], object], remove_default: bool = True + ) -> None: ... + def channel( + self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None + ) -> Channel: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack(self) -> bool: ... + @property + def consumer_cancel_notify(self) -> bool: ... + @property + def exchange_exchange_bindings(self) -> bool: ... + @property + def publisher_confirms(self) -> bool: ... diff --git a/stubs/pika/pika/credentials.pyi b/stubs/pika/pika/credentials.pyi new file mode 100644 index 000000000000..9e6288b7b5f4 --- /dev/null +++ b/stubs/pika/pika/credentials.pyi @@ -0,0 +1,37 @@ +from logging import Logger +from typing import ClassVar, Protocol, type_check_only + +from .spec import Connection + +@type_check_only +class _Credentials(Protocol): + TYPE: ClassVar[str] + erase_on_connect: bool + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +LOGGER: Logger + +class PlainCredentials: + TYPE: ClassVar[str] + erase_on_connect: bool + username: str + password: str + def __init__(self, username: str, password: str, erase_on_connect: bool = False) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +class ExternalCredentials: + TYPE: ClassVar[str] + erase_on_connect: bool + def __init__(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def response_for(self, start: Connection.Start) -> tuple[str | None, bytes | None]: ... + def erase_credentials(self) -> None: ... + +VALID_TYPES: list[_Credentials] diff --git a/stubs/pika/pika/data.pyi b/stubs/pika/pika/data.pyi new file mode 100644 index 000000000000..18ad67c71a6b --- /dev/null +++ b/stubs/pika/pika/data.pyi @@ -0,0 +1,14 @@ +from collections.abc import Mapping +from datetime import datetime +from decimal import Decimal +from typing import TypeAlias + +_Value: TypeAlias = str | bytes | bool | int | Decimal | datetime | _ArgumentMapping | list[_Value] | None +_ArgumentMapping: TypeAlias = Mapping[str, _Value] + +def encode_short_string(pieces: list[bytes], value: str | bytes) -> int: ... +def decode_short_string(encoded: bytes, offset: int) -> tuple[str | bytes, int]: ... +def encode_table(pieces: list[bytes], table: _ArgumentMapping) -> int: ... +def encode_value(pieces: list[bytes], value: _Value) -> int: ... +def decode_table(encoded: bytes, offset: int) -> tuple[dict[str | bytes, _Value], int]: ... +def decode_value(encoded: bytes, offset: int) -> tuple[_Value, int]: ... diff --git a/stubs/pika/pika/delivery_mode.pyi b/stubs/pika/pika/delivery_mode.pyi new file mode 100644 index 000000000000..61d5aa5c4237 --- /dev/null +++ b/stubs/pika/pika/delivery_mode.pyi @@ -0,0 +1,5 @@ +from enum import Enum + +class DeliveryMode(Enum): + Transient = 1 + Persistent = 2 diff --git a/stubs/pika/pika/diagnostic_utils.pyi b/stubs/pika/pika/diagnostic_utils.pyi new file mode 100644 index 000000000000..0c46e0f8eb33 --- /dev/null +++ b/stubs/pika/pika/diagnostic_utils.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable +from logging import Logger +from typing import Any, TypeVar + +F = TypeVar("F", bound=Callable[..., Any]) # noqa: Y001 + +def create_log_exception_decorator(logger: Logger) -> Callable[[F], F]: ... diff --git a/stubs/pika/pika/exceptions.pyi b/stubs/pika/pika/exceptions.pyi new file mode 100644 index 000000000000..5f77d4d67572 --- /dev/null +++ b/stubs/pika/pika/exceptions.pyi @@ -0,0 +1,62 @@ +from collections.abc import Sequence + +from pika.adapters.blocking_connection import ReturnedMessage + +class AMQPError(Exception): ... +class AMQPConnectionError(AMQPError): ... +class ConnectionOpenAborted(AMQPConnectionError): ... +class StreamLostError(AMQPConnectionError): ... +class IncompatibleProtocolError(AMQPConnectionError): ... +class AuthenticationError(AMQPConnectionError): ... +class ProbableAuthenticationError(AMQPConnectionError): ... +class ProbableAccessDeniedError(AMQPConnectionError): ... +class NoFreeChannels(AMQPConnectionError): ... +class ConnectionWrongStateError(AMQPConnectionError): ... + +class ConnectionClosed(AMQPConnectionError): + def __init__(self, reply_code: int, reply_text: str) -> None: ... + @property + def reply_code(self) -> int: ... + @property + def reply_text(self) -> str: ... + +class ConnectionClosedByBroker(ConnectionClosed): ... +class ConnectionClosedByClient(ConnectionClosed): ... +class ConnectionBlockedTimeout(AMQPConnectionError): ... +class AMQPHeartbeatTimeout(AMQPConnectionError): ... +class AMQPChannelError(AMQPError): ... +class ChannelWrongStateError(AMQPChannelError): ... + +class ChannelClosed(AMQPChannelError): + def __init__(self, reply_code: int, reply_text: str) -> None: ... + @property + def reply_code(self) -> int: ... + @property + def reply_text(self) -> str: ... + +class ChannelClosedByBroker(ChannelClosed): ... +class ChannelClosedByClient(ChannelClosed): ... +class DuplicateConsumerTag(AMQPChannelError): ... +class ConsumerCancelled(AMQPChannelError): ... + +class UnroutableError(AMQPChannelError): + messages: Sequence[ReturnedMessage] + def __init__(self, messages: Sequence[ReturnedMessage]) -> None: ... + +class NackError(AMQPChannelError): + messages: Sequence[ReturnedMessage] + def __init__(self, messages: Sequence[ReturnedMessage]) -> None: ... + +class InvalidChannelNumber(AMQPError): ... +class ProtocolSyntaxError(AMQPError): ... +class UnexpectedFrameError(ProtocolSyntaxError): ... +class ProtocolVersionMismatch(ProtocolSyntaxError): ... +class BodyTooLongError(ProtocolSyntaxError): ... +class InvalidFrameError(ProtocolSyntaxError): ... +class InvalidFieldTypeException(ProtocolSyntaxError): ... +class UnsupportedAMQPFieldException(ProtocolSyntaxError): ... +class MethodNotImplemented(AMQPError): ... +class ChannelError(Exception): ... +class ReentrancyError(Exception): ... +class ShortStringTooLong(AMQPError): ... +class DuplicateGetOkCallback(ChannelError): ... diff --git a/stubs/pika/pika/exchange_type.pyi b/stubs/pika/pika/exchange_type.pyi new file mode 100644 index 000000000000..af625976ee47 --- /dev/null +++ b/stubs/pika/pika/exchange_type.pyi @@ -0,0 +1,19 @@ +import sys + +if sys.version_info >= (3, 11): + from enum import StrEnum + + class ExchangeType(StrEnum): + direct = "direct" + fanout = "fanout" + headers = "headers" + topic = "topic" + +else: + from enum import Enum + + class ExchangeType(str, Enum): + direct = "direct" + fanout = "fanout" + headers = "headers" + topic = "topic" diff --git a/stubs/pika/pika/frame.pyi b/stubs/pika/pika/frame.pyi new file mode 100644 index 000000000000..8b547d8478ee --- /dev/null +++ b/stubs/pika/pika/frame.pyi @@ -0,0 +1,47 @@ +from abc import abstractmethod +from logging import Logger +from typing import Generic, TypeVar + +from . import amqp_object +from .spec import BasicProperties + +_M = TypeVar("_M", bound=amqp_object.Method) + +LOGGER: Logger + +class Frame(amqp_object.AMQPObject): + frame_type: int + channel_number: int + def __init__(self, frame_type: int, channel_number: int) -> None: ... + @abstractmethod + def marshal(self) -> bytes: ... + +class Method(Frame, Generic[_M]): + method: _M + def __init__(self, channel_number: int, method: _M) -> None: ... + def marshal(self) -> bytes: ... + +class Header(Frame): + body_size: int + properties: BasicProperties + def __init__(self, channel_number: int, body_size: int, props: BasicProperties) -> None: ... + def marshal(self) -> bytes: ... + +class Body(Frame): + fragment: bytes + def __init__(self, channel_number: int, fragment: bytes) -> None: ... + def marshal(self) -> bytes: ... + +class Heartbeat(Frame): + def __init__(self) -> None: ... + def marshal(self) -> bytes: ... + +class ProtocolHeader(amqp_object.AMQPObject): + frame_type: int + major: int + minor: int + revision: int + def __init__(self, major: int | None = None, minor: int | None = None, revision: int | None = None) -> None: ... + def marshal(self) -> bytes: ... + +def decode_frame(data_in: bytes) -> tuple[int, Frame | ProtocolHeader | None]: ... diff --git a/stubs/pika/pika/heartbeat.pyi b/stubs/pika/pika/heartbeat.pyi new file mode 100644 index 000000000000..1c6ec89dfc60 --- /dev/null +++ b/stubs/pika/pika/heartbeat.pyi @@ -0,0 +1,14 @@ +from logging import Logger + +from pika.connection import Connection + +LOGGER: Logger + +class HeartbeatChecker: + def __init__(self, connection: Connection, timeout: float) -> None: ... + @property + def bytes_received_on_connection(self) -> int: ... + @property + def connection_is_idle(self) -> bool: ... + def received(self) -> None: ... + def stop(self) -> None: ... diff --git a/stubs/pika/pika/spec.pyi b/stubs/pika/pika/spec.pyi new file mode 100644 index 000000000000..eee768972a16 --- /dev/null +++ b/stubs/pika/pika/spec.pyi @@ -0,0 +1,908 @@ +from _typeshed import Incomplete +from builtins import type as _type +from collections.abc import Mapping +from typing import ClassVar, Final, Literal +from typing_extensions import Self + +from pika.amqp_object import Class, Method, Properties +from pika.data import _ArgumentMapping +from pika.delivery_mode import DeliveryMode + +PROTOCOL_VERSION: Final[tuple[int, int, int]] +PORT: Final = 5672 +ACCESS_REFUSED: Final = 403 +CHANNEL_ERROR: Final = 504 +COMMAND_INVALID: Final = 503 +CONNECTION_FORCED: Final = 320 +CONTENT_TOO_LARGE: Final = 311 +FRAME_BODY: Final = 3 +FRAME_END: Final = 206 +FRAME_END_SIZE: Final = 1 +FRAME_ERROR: Final = 501 +FRAME_HEADER: Final = 2 +FRAME_HEADER_SIZE: Final = 7 +FRAME_HEARTBEAT: Final = 8 +FRAME_MAX_SIZE: Final = 131072 +FRAME_METHOD: Final = 1 +FRAME_MIN_SIZE: Final = 4096 +INTERNAL_ERROR: Final = 541 +INVALID_PATH: Final = 402 +NOT_ALLOWED: Final = 530 +NOT_FOUND: Final = 404 +NOT_IMPLEMENTED: Final = 540 +NO_CONSUMERS: Final = 313 +NO_ROUTE: Final = 312 +PERSISTENT_DELIVERY_MODE: Final = 2 +PRECONDITION_FAILED: Final = 406 +REPLY_SUCCESS: Final = 200 +RESOURCE_ERROR: Final = 506 +RESOURCE_LOCKED: Final = 405 +SYNTAX_ERROR: Final = 502 +TRANSIENT_DELIVERY_MODE: Final = 1 +UNEXPECTED_FRAME: Final = 505 + +class Connection(Class): + INDEX: ClassVar[int] + + class Start(Method): + INDEX: ClassVar[int] + version_major: int + version_minor: int + server_properties: _ArgumentMapping | None + mechanisms: str + locales: str + def __init__( + self, + version_major: int = 0, + version_minor: int = 9, + server_properties: _ArgumentMapping | None = None, + mechanisms: str = "PLAIN", + locales: str = "en_US", + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class StartOk(Method): + INDEX: ClassVar[int] + client_properties: _ArgumentMapping | None + mechanism: str + response: str | None + locale: str + def __init__( + self, + client_properties: _ArgumentMapping | None = None, + mechanism: str = "PLAIN", + response: str | None = None, + locale: str = "en_US", + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Secure(Method): + INDEX: ClassVar[int] + challenge: str | None + def __init__(self, challenge: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SecureOk(Method): + INDEX: ClassVar[int] + response: str + def __init__(self, response: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Tune(Method): + INDEX: ClassVar[int] + channel_max: int + frame_max: int + heartbeat: int + def __init__(self, channel_max: int = 0, frame_max: int = 0, heartbeat: int = 0) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class TuneOk(Method): + INDEX: ClassVar[int] + channel_max: int + frame_max: int + heartbeat: int + def __init__(self, channel_max: int = 0, frame_max: int = 0, heartbeat: int = 0) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Open(Method): + INDEX: ClassVar[int] + virtual_host: str + capabilities: str + insist: bool + def __init__(self, virtual_host: str = "/", capabilities: str = "", insist: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class OpenOk(Method): + INDEX: ClassVar[int] + known_hosts: str + def __init__(self, known_hosts: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Close(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CloseOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Blocked(Method): + INDEX: ClassVar[int] + reason: str + def __init__(self, reason: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unblocked(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UpdateSecret(Method): + INDEX: ClassVar[int] + new_secret: str + reason: str + mechanisms: str + def __init__(self, new_secret: str, reason: str) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UpdateSecretOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Channel(Class): + INDEX: ClassVar[int] + + class Open(Method): + INDEX: ClassVar[int] + out_of_band: str + def __init__(self, out_of_band: str = "") -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class OpenOk(Method): + INDEX: ClassVar[int] + channel_id: str + def __init__(self, channel_id: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Flow(Method): + INDEX: ClassVar[int] + active: bool | None + def __init__(self, active: bool | None = None) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class FlowOk(Method): + INDEX: ClassVar[int] + active: bool | None + def __init__(self, active: bool | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Close(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CloseOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Access(Class): + INDEX: ClassVar[int] + + class Request(Method): + INDEX: ClassVar[int] + realm: str + exclusive: bool + passive: bool + active: bool + write: bool + read: bool + def __init__( + self, + realm: str = "/data", + exclusive: bool = False, + passive: bool = True, + active: bool = True, + write: bool = True, + read: bool = True, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RequestOk(Method): + INDEX: ClassVar[int] + ticket: int + def __init__(self, ticket: int = 1) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Exchange(Class): + INDEX: ClassVar[int] + + class Declare(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str | None + type: str + passive: bool + durable: bool + auto_delete: bool + internal: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + exchange: str | None = None, + type: str = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeclareOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Delete(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str | None + if_unused: bool + nowait: bool + def __init__( + self, ticket: int = 0, exchange: str | None = None, if_unused: bool = False, nowait: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeleteOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Bind(Method): + INDEX: ClassVar[int] + ticket: int + destination: str | None + source: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class BindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unbind(Method): + INDEX: ClassVar[int] + ticket: int + destination: str | None + source: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UnbindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Queue(Class): + INDEX: ClassVar[int] + + class Declare(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + passive: bool + durable: bool + exclusive: bool + auto_delete: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeclareOk(Method): + INDEX: ClassVar[int] + queue: str + message_count: int + consumer_count: int + def __init__(self, queue: str, message_count: int, consumer_count: int) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Bind(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + exchange: str | None + routing_key: str + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class BindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Purge(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + nowait: bool + def __init__(self, ticket: int = 0, queue: str = "", nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class PurgeOk(Method): + INDEX: ClassVar[int] + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Delete(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + if_unused: bool + if_empty: bool + nowait: bool + def __init__( + self, ticket: int = 0, queue: str = "", if_unused: bool = False, if_empty: bool = False, nowait: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class DeleteOk(Method): + INDEX: ClassVar[int] + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Unbind(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + exchange: str | None + routing_key: str + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class UnbindOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Basic(Class): + INDEX: ClassVar[int] + + class Qos(Method): + INDEX: ClassVar[int] + prefetch_size: int + prefetch_count: int + global_qos: bool + def __init__(self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class QosOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Consume(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + consumer_tag: str + no_local: bool + no_ack: bool + exclusive: bool + nowait: bool + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + consumer_tag: str = "", + no_local: bool = False, + no_ack: bool = False, + exclusive: bool = False, + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class ConsumeOk(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Cancel(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + nowait: bool + def __init__(self, consumer_tag: str | None = None, nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CancelOk(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Publish(Method): + INDEX: ClassVar[int] + ticket: int + exchange: str + routing_key: str + mandatory: bool + immediate: bool + def __init__( + self, ticket: int = 0, exchange: str = "", routing_key: str = "", mandatory: bool = False, immediate: bool = False + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Return(Method): + INDEX: ClassVar[int] + reply_code: int | None + reply_text: str + exchange: str | None + routing_key: str | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", exchange: str | None = None, routing_key: str | None = None + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Deliver(Method): + INDEX: ClassVar[int] + consumer_tag: str | None + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None + def __init__( + self, + consumer_tag: str | None = None, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Get(Method): + INDEX: ClassVar[int] + ticket: int + queue: str + no_ack: bool + def __init__(self, ticket: int = 0, queue: str = "", no_ack: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class GetOk(Method): + INDEX: ClassVar[int] + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None + message_count: int | None + def __init__( + self, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, + message_count: int | None = None, + ) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class GetEmpty(Method): + INDEX: ClassVar[int] + cluster_id: str + def __init__(self, cluster_id: str = "") -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Ack(Method): + INDEX: ClassVar[int] + delivery_tag: int + multiple: bool + def __init__(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Reject(Method): + INDEX: ClassVar[int] + delivery_tag: int | None + requeue: bool + def __init__(self, delivery_tag: int | None = None, requeue: bool = True) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RecoverAsync(Method): + INDEX: ClassVar[int] + requeue: bool + def __init__(self, requeue: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Recover(Method): + INDEX: ClassVar[int] + requeue: bool + def __init__(self, requeue: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RecoverOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Nack(Method): + INDEX: ClassVar[int] + delivery_tag: int + multiple: bool + requeue: bool + def __init__(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Tx(Class): + INDEX: ClassVar[int] + + class Select(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SelectOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Commit(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class CommitOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class Rollback(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class RollbackOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class Confirm(Class): + INDEX: ClassVar[int] + + class Select(Method): + INDEX: ClassVar[int] + nowait: bool + def __init__(self, nowait: bool = False) -> None: ... + @property + def synchronous(self) -> Literal[True]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + + class SelectOk(Method): + INDEX: ClassVar[int] + def __init__(self) -> None: ... + @property + def synchronous(self) -> Literal[False]: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +class BasicProperties(Properties): + CLASS: ClassVar[_type[Basic]] + INDEX: ClassVar[int] + FLAG_CONTENT_TYPE: Final = 32768 + FLAG_CONTENT_ENCODING: Final = 16384 + FLAG_HEADERS: Final = 8192 + FLAG_DELIVERY_MODE: Final = 4096 + FLAG_PRIORITY: Final = 2048 + FLAG_CORRELATION_ID: Final = 1024 + FLAG_REPLY_TO: Final = 512 + FLAG_EXPIRATION: Final = 256 + FLAG_MESSAGE_ID: Final = 128 + FLAG_TIMESTAMP: Final = 64 + FLAG_TYPE: Final = 32 + FLAG_USER_ID: Final = 16 + FLAG_APP_ID: Final = 8 + FLAG_CLUSTER_ID: Final = 4 + content_type: str | None + content_encoding: str | None + headers: _ArgumentMapping | None + delivery_mode: Literal[1, 2] | None + priority: int | None + correlation_id: str | None + reply_to: str | None + expiration: str | None + message_id: str | None + timestamp: int | None + type: str | None + user_id: str | None + app_id: str | None + cluster_id: str | None + def __init__( + self, + content_type: str | None = None, + content_encoding: str | None = None, + headers: _ArgumentMapping | None = None, + delivery_mode: DeliveryMode | Literal[1, 2] | None = None, + priority: int | None = None, + correlation_id: str | None = None, + reply_to: str | None = None, + expiration: str | None = None, + message_id: str | None = None, + timestamp: int | None = None, + type: str | None = None, + user_id: str | None = None, + app_id: str | None = None, + cluster_id: str | None = None, + ) -> None: ... + def decode(self, encoded: bytes, offset: int = 0) -> Self: ... + def encode(self) -> list[bytes]: ... + +methods: Final[dict[int, type[Method]]] +props: Final[dict[int, type[BasicProperties]]] + +def has_content(methodNumber: int) -> bool: ... diff --git a/stubs/pika/pika/tcp_socket_opts.pyi b/stubs/pika/pika/tcp_socket_opts.pyi new file mode 100644 index 000000000000..7c15e0beb5e8 --- /dev/null +++ b/stubs/pika/pika/tcp_socket_opts.pyi @@ -0,0 +1,9 @@ +from _socket import SocketType +from logging import Logger + +LOGGER: Logger + +_SUPPORTED_TCP_OPTIONS: dict[str, int] + +def socket_requires_keepalive(tcp_options: dict[str, int]) -> bool: ... +def set_sock_opts(tcp_options: dict[str, int] | None, sock: SocketType) -> None: ... diff --git a/stubs/pika/pika/validators.pyi b/stubs/pika/pika/validators.pyi new file mode 100644 index 000000000000..07c2bb0f110d --- /dev/null +++ b/stubs/pika/pika/validators.pyi @@ -0,0 +1,15 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Callable +from typing import Literal, overload + +def require_string(value: object, value_name: str) -> None: ... # raise TypeError if value is not string +def require_callback( + callback: object, callback_name: str = "callback" # raise TypeError if callback is not callable +) -> None: ... + +@overload +def rpc_completion_callback(callback: None) -> Literal[True]: ... +@overload +def rpc_completion_callback(callback: Callable[..., object]) -> Literal[False]: ... + +def zero_or_greater(name: str, value: ConvertibleToInt) -> None: ... diff --git a/stubs/polib/METADATA.toml b/stubs/polib/METADATA.toml new file mode 100644 index 000000000000..959b3806d798 --- /dev/null +++ b/stubs/polib/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.2.*" +upstream-repository = "https://github.com/izimobil/polib" diff --git a/stubs/polib/polib.pyi b/stubs/polib/polib.pyi new file mode 100644 index 000000000000..a41fe1dea93a --- /dev/null +++ b/stubs/polib/polib.pyi @@ -0,0 +1,172 @@ +from collections.abc import Callable +from pathlib import Path +from typing import IO, Any, Generic, Literal, SupportsIndex, TypeVar, overload + +_TB = TypeVar("_TB", bound=_BaseEntry) +_TP = TypeVar("_TP", bound=POFile) +_TM = TypeVar("_TM", bound=MOFile) + +default_encoding: str + +# wrapwidth: int +# encoding: str +# check_for_duplicates: bool +@overload +def pofile(pofile: str | Path, *, klass: type[_TP], **kwargs: Any) -> _TP: ... +@overload +def pofile(pofile: str | Path, **kwargs: Any) -> POFile: ... + +@overload +def mofile(mofile: str, *, klass: type[_TM], **kwargs: Any) -> _TM: ... +@overload +def mofile(mofile: str, **kwargs: Any) -> MOFile: ... + +def detect_encoding(file: bytes | str, binary_mode: bool = ...) -> str: ... +def escape(st: str) -> str: ... +def unescape(st: str) -> str: ... + +class _BaseFile(list[_TB]): + fpath: str + wrapwidth: int + encoding: str + check_for_duplicates: bool + header: str + metadata: dict[str, str] + metadata_is_fuzzy: bool + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __unicode__(self) -> str: ... + def __contains__(self, entry: _TB) -> bool: ... # type: ignore[override] # AttributeError otherwise + def __eq__(self, other: object) -> bool: ... + def append(self, entry: _TB) -> None: ... + def insert(self, index: SupportsIndex, entry: _TB) -> None: ... + def metadata_as_entry(self) -> POEntry: ... + def save(self, fpath: str | None = ..., repr_method: str = ..., newline: str | None = ...) -> None: ... + def find( + self, st: str, by: str = ..., include_obsolete_entries: bool = ..., msgctxt: str | Literal[False] = ... + ) -> _TB | None: ... + def ordered_metadata(self) -> list[tuple[str, str]]: ... + def to_binary(self) -> bytes: ... + +class POFile(_BaseFile[POEntry]): + def __unicode__(self) -> str: ... + def save_as_mofile(self, fpath: str) -> None: ... + def percent_translated(self) -> int: ... + def translated_entries(self) -> list[POEntry]: ... + def untranslated_entries(self) -> list[POEntry]: ... + def fuzzy_entries(self) -> list[POEntry]: ... + def obsolete_entries(self) -> list[POEntry]: ... + def merge(self, refpot: POFile) -> None: ... + +class MOFile(_BaseFile[MOEntry]): + MAGIC: int + MAGIC_SWAPPED: int + magic_number: int | None + version: int + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def save_as_pofile(self, fpath: str) -> None: ... + def save(self, fpath: str | None = ...) -> None: ... # type: ignore[override] # binary file does not allow argument repr_method + def percent_translated(self) -> int: ... + def translated_entries(self) -> list[MOEntry]: ... + def untranslated_entries(self) -> list[MOEntry]: ... + def fuzzy_entries(self) -> list[MOEntry]: ... + def obsolete_entries(self) -> list[MOEntry]: ... + +class _BaseEntry: + msgid: str + msgstr: str + msgid_plural: str + msgstr_plural: dict[int, str] + msgctxt: str + obsolete: bool + encoding: str + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __unicode__(self, wrapwidth: int = ...) -> str: ... + def __eq__(self, other: object) -> bool: ... + @property + def msgid_with_context(self) -> str: ... + +class POEntry(_BaseEntry): + comment: str + tcomment: str + occurrences: list[tuple[str, str]] + flags: list[str] + previous_msgctxt: str | None + previous_msgid: str | None + previous_msgid_plural: str | None + linenum: int | None + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __unicode__(self, wrapwidth: int = ...) -> str: ... + def __cmp__(self, other: POEntry) -> int: ... + def __gt__(self, other: POEntry) -> bool: ... + def __lt__(self, other: POEntry) -> bool: ... + def __ge__(self, other: POEntry) -> bool: ... + def __le__(self, other: POEntry) -> bool: ... + def __eq__(self, other: POEntry) -> bool: ... # type: ignore[override] + def __ne__(self, other: POEntry) -> bool: ... # type: ignore[override] + def translated(self) -> bool: ... + def merge(self, other: POEntry) -> None: ... + @property + def fuzzy(self) -> bool: ... + @property + def msgid_with_context(self) -> str: ... + def __hash__(self) -> int: ... + +class MOEntry(_BaseEntry): + comment: str + tcomment: str + occurrences: list[tuple[str, str]] + flags: list[str] + previous_msgctxt: str | None + previous_msgid: str | None + previous_msgid_plural: str | None + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __hash__(self) -> int: ... + +class _POFileParser(Generic[_TP]): + fhandle: IO[str] + instance: _TP + transitions: dict[tuple[str, str], tuple[Callable[[], bool], str]] + current_line: int + current_entry: POEntry + current_state: str + current_token: str | None + msgstr_index: int + entry_obsolete: int + def __init__(self, pofile: str, *args: Any, **kwargs: Any) -> None: ... + def parse(self) -> _TP: ... + def add(self, symbol: str, states: list[str], next_state: str) -> None: ... + def process(self, symbol: str) -> None: ... + def handle_he(self) -> bool: ... + def handle_tc(self) -> bool: ... + def handle_gc(self) -> bool: ... + def handle_oc(self) -> bool: ... + def handle_fl(self) -> bool: ... + def handle_pp(self) -> bool: ... + def handle_pm(self) -> bool: ... + def handle_pc(self) -> bool: ... + def handle_ct(self) -> bool: ... + def handle_mi(self) -> bool: ... + def handle_mp(self) -> bool: ... + def handle_ms(self) -> bool: ... + def handle_mx(self) -> bool: ... + def handle_mc(self) -> bool: ... + +class _MOFileParser(Generic[_TM]): + fhandle: IO[bytes] + instance: _TM + def __init__(self, mofile: str, *args: Any, **kwargs: Any) -> None: ... + def __del__(self) -> None: ... + def parse(self) -> _TM: ... + +__all__ = [ + "pofile", + "POFile", + "POEntry", + "mofile", + "MOFile", + "MOEntry", + "default_encoding", + "escape", + "unescape", + "detect_encoding", +] diff --git a/stubs/pony/@tests/stubtest_allowlist.txt b/stubs/pony/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5592e76d682c --- /dev/null +++ b/stubs/pony/@tests/stubtest_allowlist.txt @@ -0,0 +1,14 @@ +# Tests should not be part of the stubs +pony.orm.tests.* + +# Modules with ImportError, cannot import third-party libraries: +pony.flask.* +pony.orm.dbproviders.cockroach +pony.orm.dbproviders.mysql +pony.orm.dbproviders.oracle +pony.orm.dbproviders.postgres +pony.orm.integration.bottle_plugin +pony.orm.examples.bottle_example + +# TODO: Incomplete issues in examples dir: +pony.orm.examples.* diff --git a/stubs/pony/METADATA.toml b/stubs/pony/METADATA.toml new file mode 100644 index 000000000000..517628fd01cf --- /dev/null +++ b/stubs/pony/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.7.*" +upstream-repository = "https://github.com/ponyorm/pony" +optional-dependencies = ["types-psycopg2", "types-PyMySQL"] diff --git a/stubs/pony/pony/__init__.pyi b/stubs/pony/pony/__init__.pyi new file mode 100644 index 000000000000..3a6a1123886a --- /dev/null +++ b/stubs/pony/pony/__init__.pyi @@ -0,0 +1,13 @@ +from typing import Final, Literal, TypeAlias + +_Mode: TypeAlias = Literal[ + "GAE-LOCAL", "GAE-SERVER", "MOD_WSGI", "INTERACTIVE", "FCGI-FLUP", "UWSGI", "FLASK", "CHERRYPY", "BOTTLE", "UNKNOWN" +] +__version__: Final[str] + +def detect_mode() -> _Mode: ... + +MODE: Final[_Mode] +MAIN_FILE: Final[str | None] +MAIN_DIR: Final[str | None] +PONY_DIR: Final[str] diff --git a/stubs/pony/pony/converting.pyi b/stubs/pony/pony/converting.pyi new file mode 100644 index 000000000000..631da5e69398 --- /dev/null +++ b/stubs/pony/pony/converting.pyi @@ -0,0 +1,48 @@ +import re +from _typeshed import ConvertibleToInt +from collections.abc import Callable, Sequence +from datetime import date, datetime, time, timedelta +from typing import Any, Literal + +class ValidationError(ValueError): ... + +def check_ip(s: str) -> str: ... +def check_positive(s: ConvertibleToInt) -> int: ... +def check_identifier(s: str) -> str: ... + +isbn_re: re.Pattern[str] + +def isbn10_checksum(digits: Sequence[ConvertibleToInt]) -> str: ... +def isbn13_checksum(digits: Sequence[ConvertibleToInt]) -> str: ... +def check_isbn(s: str, convert_to: Literal[10, 13] | None = None) -> str: ... +def isbn10_to_isbn13(s: str) -> str: ... +def isbn13_to_isbn10(s: str) -> str: ... + +email_re: re.Pattern[str] +rfc2822_email_re: re.Pattern[str] + +def check_email(s: str) -> str: ... +def check_rfc2822_email(s: str) -> str: ... + +date_str_list: list[str] +date_re_list: list[re.Pattern[str]] +time_str: str +time_re: re.Pattern[str] +datetime_re_list: list[re.Pattern[str]] +month_lists: list[list[str]] +month_list: list[str] +i: int +month: str +month_dict: dict[str, int] + +def str2date(s: str) -> date: ... +def str2time(s: str) -> time: ... +def str2datetime(s: str) -> datetime: ... +def str2timedelta(s: str) -> timedelta: ... +def timedelta2str(td: timedelta) -> str: ... + +converters: dict[type | str, tuple[Callable[[str], Any], type[str], str | None]] # Any type from types above + +def str2py( + value: str, type: str | type | tuple[Callable[[str], Any], type[str], str | None] | None +) -> Any: ... # Any type from types above diff --git a/stubs/pony/pony/flask/__init__.pyi b/stubs/pony/pony/flask/__init__.pyi new file mode 100644 index 000000000000..080bcc2272aa --- /dev/null +++ b/stubs/pony/pony/flask/__init__.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete +from types import ModuleType +from typing import Protocol, type_check_only + +# Protocol for flask.Flask class +@type_check_only +class _Flask(Protocol): + def before_request(self, f): ... + def after_request(self, f): ... + def teardown_request(self, f): ... + +flask_lib: ModuleType +request: Incomplete + +class Pony: + app: _Flask | None + def __init__(self, app: _Flask | None = None) -> None: ... + def init_app(self, app: _Flask) -> None: ... diff --git a/stubs/pony/pony/flask/example/__init__.pyi b/stubs/pony/pony/flask/example/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/flask/example/app.pyi b/stubs/pony/pony/flask/example/app.pyi new file mode 100644 index 000000000000..b45476eba0d9 --- /dev/null +++ b/stubs/pony/pony/flask/example/app.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from pony.flask import _Flask + +app: _Flask +login_manager: Incomplete + +def load_user(user_id): ... diff --git a/stubs/pony/pony/flask/example/config.pyi b/stubs/pony/pony/flask/example/config.pyi new file mode 100644 index 000000000000..0a7fba4bec91 --- /dev/null +++ b/stubs/pony/pony/flask/example/config.pyi @@ -0,0 +1 @@ +config: dict[str, bool | str | dict[str, str | bool]] diff --git a/stubs/pony/pony/flask/example/models.pyi b/stubs/pony/pony/flask/example/models.pyi new file mode 100644 index 000000000000..290f90e958b2 --- /dev/null +++ b/stubs/pony/pony/flask/example/models.pyi @@ -0,0 +1,10 @@ +from datetime import datetime + +from pony.orm.core import Database, Entity + +db: Database + +class User(Entity): + login: str + password: str + last_login: datetime | None diff --git a/stubs/pony/pony/flask/example/views.pyi b/stubs/pony/pony/flask/example/views.pyi new file mode 100644 index 000000000000..2043cc5ca582 --- /dev/null +++ b/stubs/pony/pony/flask/example/views.pyi @@ -0,0 +1,4 @@ +def index() -> str: ... +def login(): ... +def reg(): ... +def logout(): ... diff --git a/stubs/pony/pony/options.pyi b/stubs/pony/pony/options.pyi new file mode 100644 index 000000000000..c65f52a795c0 --- /dev/null +++ b/stubs/pony/pony/options.pyi @@ -0,0 +1,39 @@ +from typing import Final + +DEBUG: Final[bool] +STATIC_DIR: Final[None] +CUT_TRACEBACK: Final[bool] +STD_DOCTYPE: Final[str] +STD_STYLESHEETS: Final[list[tuple[str, ...]]] +BASE_STYLESHEETS_PLACEHOLDER: Final[str] +COMPONENT_STYLESHEETS_PLACEHOLDER: Final[str] +SCRIPTS_PLACEHOLDER: Final[str] +RELOADING_CHECK_INTERVAL: Final[float] +LOG_TO_SQLITE: Final[None] +LOGGING_LEVEL: Final[None] +LOGGING_PONY_LEVEL: Final[None] +MAX_SESSION_CTIME: Final[int] +MAX_SESSION_MTIME: Final[int] +MAX_LONGLIFE_SESSION: Final[int] +COOKIE_SERIALIZATION_TYPE: Final[str] +COOKIE_NAME: Final[str] +COOKIE_PATH: Final[str] +COOKIE_DOMAIN: Final[None] +HASH_ALGORITHM: Final[None] +SESSION_STORAGE: Final[None] +MEMCACHE: Final[None] +ALTERNATIVE_SESSION_MEMCACHE: Final[None] +ALTERNATIVE_ORM_MEMCACHE: Final[None] +ALTERNATIVE_TEMPLATING_MEMCACHE: Final[None] +ALTERNATIVE_RESPONSE_MEMCACHE: Final[None] +PICKLE_START_OFFSET: Final[int] +PICKLE_HTML_AS_PLAIN_STR: Final[bool] +RESTORE_ESCAPES: Final[bool] +SOURCE_ENCODING: Final[None] +CONSOLE_ENCODING: Final[None] +MAX_FETCH_COUNT: Final[None] +CONSOLE_WIDTH: Final[int] +SIMPLE_ALIASES: Final[bool] +INNER_JOIN_SYNTAX: Final[bool] +DEBUGGING_REMOVE_ADDR: Final[bool] +DEBUGGING_RESTORE_ESCAPES: Final[bool] diff --git a/stubs/pony/pony/orm/__init__.pyi b/stubs/pony/pony/orm/__init__.pyi new file mode 100644 index 000000000000..e1dd6b0275cb --- /dev/null +++ b/stubs/pony/pony/orm/__init__.pyi @@ -0,0 +1 @@ +from pony.orm.core import * diff --git a/stubs/pony/pony/orm/asttranslation.pyi b/stubs/pony/pony/orm/asttranslation.pyi new file mode 100644 index 000000000000..6b3cfcc0e7fe --- /dev/null +++ b/stubs/pony/pony/orm/asttranslation.pyi @@ -0,0 +1,139 @@ +import ast +import sys +from _typeshed import Incomplete +from collections.abc import Callable, Generator +from typing import Any, TypeVar + +_T = TypeVar("_T") + +class TranslationError(Exception): ... + +pre_method_caches: dict[type[ASTTranslator], dict[type[ast.AST], Callable[..., Any]]] +post_method_caches: dict[type[ASTTranslator], dict[type[ast.AST], Callable[..., Any]]] + +class ASTTranslator: + tree: Incomplete + def __init__(translator, tree) -> None: ... + def dispatch(translator, node: ast.AST) -> None: ... + def call(translator, method: Callable[[ASTTranslator, ast.AST], _T], node: ast.AST) -> _T | None: ... + def default_pre(translator, node: ast.AST) -> None: ... + def default_post(translator, node: ast.AST) -> None: ... + +def priority(p: int): ... +def binop_src(op: str, node) -> str: ... +def ast2src(tree): ... +def get_child_nodes(node: ast.AST) -> Generator[ast.AST]: ... + +class PythonTranslator(ASTTranslator): + def __init__(translator, tree) -> None: ... + def call(translator, method, node) -> None: ... + def default_pre(translator, node: ast.AST): ... + def default_post(translator, node: ast.AST) -> None: ... + def postGeneratorExp(translator, node: ast.GeneratorExp) -> str: ... + def postcomprehension(translator, node: ast.comprehension) -> str: ... + def postGenExprIf(translator, node) -> str: ... + def postExpr(translator, node: ast.Expr) -> str: ... + def postIfExp(translator, node: ast.IfExp) -> str: ... + def postLambda(translator, node: ast.Lambda) -> str: ... + def postarguments(translator, node: ast.arguments) -> str: ... + def postarg(translator, node: ast.arg) -> str: ... + def postOr(translator, node: ast.Or) -> str: ... + def postAnd(translator, node: ast.And) -> str: ... + def postNot(translator, node: ast.Not) -> str: ... + def postCompare(translator, node: ast.Compare) -> str: ... + def postEq(translator, node: ast.Eq) -> str: ... + def postNotEq(translator, node: ast.NotEq) -> str: ... + def postLt(translator, node: ast.Lt) -> str: ... + def postLtE(translator, node: ast.LtE) -> str: ... + def postGt(translator, node: ast.Gt) -> str: ... + def postGtE(translator, node: ast.GtE) -> str: ... + def postIs(translator, node: ast.Is) -> str: ... + def postIsNot(translator, node: ast.IsNot) -> str: ... + def postIn(translator, node: ast.In) -> str: ... + def postNotIn(translator, node: ast.NotIn) -> str: ... + def postBitOr(translator, node: ast.BitOr) -> str: ... + def postBitXor(translator, node: ast.BitXor) -> str: ... + def postBitAnd(translator, node: ast.BitAnd) -> str: ... + def postLShift(translator, node: ast.LShift) -> str: ... + def postRShift(translator, node: ast.RShift) -> str: ... + def postAdd(translator, node: ast.Add) -> str: ... + def postSub(translator, node: ast.Sub) -> str: ... + def postMult(translator, node: ast.Mult): ... + def postMatMult(translator, node: ast.MatMult) -> None: ... + def postDiv(translator, node: ast.Div) -> str: ... + def postFloorDiv(translator, node: ast.FloorDiv) -> str: ... + def postMod(translator, node: ast.Mod) -> str: ... + def postUSub(translator, node: ast.USub) -> str: ... + def postUAdd(translator, node: ast.UAdd) -> str: ... + def postInvert(translator, node: ast.Invert) -> str: ... + def postPow(translator, node: ast.Pow) -> str: ... + def postAttribute(translator, node: ast.Attribute) -> str: ... + def postCall(translator, node: ast.Call) -> str: ... + def postkeyword(translator, node: ast.keyword) -> str: ... + def postStarred(translator, node: ast.Starred) -> str: ... + def postSubscript(translator, node: ast.Subscript) -> str: ... + def postIndex(translator, node: ast.Index) -> str: ... + def postSlice(translator, node: ast.Slice) -> str: ... + def postConstant(translator, node: ast.Constant) -> str: ... + if sys.version_info >= (3, 14): + def postNameConstant(translator, node: ast.Constant) -> str: ... + def postNum(translator, node: ast.Constant) -> str: ... + def postStr(translator, node: ast.Constant) -> str: ... + def postBytes(translator, node: ast.Constant) -> str: ... + else: + def postNameConstant(translator, node: ast.NameConstant) -> str: ... + def postNum(translator, node: ast.Num) -> str: ... + def postStr(translator, node: ast.Str) -> str: ... + def postBytes(translator, node: ast.Bytes) -> str: ... + + def postList(translator, node: ast.List) -> str: ... + def postTuple(translator, node: ast.Tuple) -> str: ... + def postDict(translator, node: ast.Dict) -> str: ... + def postSet(translator, node: ast.Set) -> str: ... + def postName(translator, node: ast.Name) -> str: ... + def postJoinedStr(self, node: ast.JoinedStr) -> str: ... + def postFormattedValue(self, node: ast.FormattedValue) -> str: ... + +nonexternalizable_types: tuple[type[ast.AST], ...] + +class PreTranslator(ASTTranslator): + def __init__(translator, tree, globals, locals, special_functions, const_functions, outer_names=()) -> None: ... + def dispatch(translator, node) -> None: ... + def preGeneratorExp(translator, node: ast.GeneratorExp) -> bool: ... + def preLambda(translator, node: ast.Lambda) -> bool: ... + def postName(translator, node: ast.Name) -> None: ... + def postSlice(translator, node: ast.Slice) -> None: ... + def postStarred(translator, node: ast.Starred) -> None: ... + def postConstant(translator, node: ast.Constant) -> None: ... + if sys.version_info >= (3, 14): + def postNum(translator, node: ast.Constant) -> None: ... + def postStr(translator, node: ast.Constant) -> None: ... + def postBytes(translator, node: ast.Constant) -> None: ... + else: + def postNum(translator, node: ast.Num) -> None: ... + def postStr(translator, node: ast.Str) -> None: ... + def postBytes(translator, node: ast.Bytes) -> None: ... + + def postDict(translator, node: ast.Dict) -> None: ... + def postList(translator, node: ast.List) -> None: ... + def postkeyword(translator, node: ast.keyword) -> None: ... + def postIndex(translator, node: ast.Index) -> None: ... + def postCall(translator, node: ast.Call) -> None: ... + def postCompare(translator, node: ast.Compare) -> None: ... + def post_binop(translator, node: ast.BinOp) -> None: ... + def postBitOr(translator, node: ast.BitOr) -> None: ... + def postBitXor(translator, node: ast.BitXor) -> None: ... + def postBitAnd(translator, node: ast.BitAnd) -> None: ... + def postLShift(translator, node: ast.LShift) -> None: ... + def postRShift(translator, node: ast.RShift) -> None: ... + def postAdd(translator, node: ast.Add) -> None: ... + def postSub(translator, node: ast.Sub) -> None: ... + def postMult(translator, node: ast.Mult) -> None: ... + def postMatMult(translator, node: ast.MatMult) -> None: ... + def postDiv(translator, node: ast.Div) -> None: ... + def postFloorDiv(translator, node: ast.FloorDiv) -> None: ... + def postMod(translator, node: ast.Mod) -> None: ... + +extractors_cache: dict[str | int, tuple[Incomplete, dict[Incomplete, Incomplete]]] + +def create_extractors(code_key: str | int, tree, globals, locals, special_functions, const_functions, outer_names=()): ... diff --git a/stubs/pony/pony/orm/core.pyi b/stubs/pony/pony/orm/core.pyi new file mode 100644 index 000000000000..d05d3104f456 --- /dev/null +++ b/stubs/pony/pony/orm/core.pyi @@ -0,0 +1,917 @@ +import ast +import itertools +import re +import types +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Callable, Generator +from logging import Logger +from typing import Literal, TypeAlias, TypeVar +from typing_extensions import Never, Self, deprecated + +import pony as pony +from pony.orm.asttranslation import TranslationError as TranslationError +from pony.orm.dbapiprovider import ( + DatabaseError as DatabaseError, + DataError as DataError, + DBException as DBException, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Warning as Warning, +) +from pony.orm.ormtypes import ( + Array, + FloatArray as FloatArray, + IntArray as IntArray, + Json as Json, + LongStr as LongStr, + LongUnicode as LongUnicode, + StrArray as StrArray, + raw_sql as raw_sql, +) +from pony.py23compat import buffer as buffer, unicode as unicode +from pony.utils import between as between, coalesce as coalesce, concat as concat, localbase + +_T = TypeVar("_T") +_KnownProvider: TypeAlias = Literal["sqlite", "postgres", "mysql", "oracle"] + +__all__ = [ + "pony", + "DBException", + "RowNotFound", + "MultipleRowsFound", + "TooManyRowsFound", + "Warning", + "Error", + "InterfaceError", + "DatabaseError", + "DataError", + "OperationalError", + "IntegrityError", + "InternalError", + "ProgrammingError", + "NotSupportedError", + "OrmError", + "ERDiagramError", + "DBSchemaError", + "MappingError", + "BindingError", + "TableDoesNotExist", + "TableIsNotEmpty", + "ConstraintError", + "CacheIndexError", + "ObjectNotFound", + "MultipleObjectsFoundError", + "TooManyObjectsFoundError", + "OperationWithDeletedObjectError", + "TransactionError", + "ConnectionClosedError", + "TransactionIntegrityError", + "IsolationError", + "CommitException", + "RollbackException", + "UnrepeatableReadError", + "OptimisticCheckError", + "UnresolvableCyclicDependency", + "UnexpectedError", + "DatabaseSessionIsOver", + "PonyRuntimeWarning", + "DatabaseContainsIncorrectValue", + "DatabaseContainsIncorrectEmptyValue", + "TranslationError", + "ExprEvalError", + "PermissionError", + "Database", + "sql_debug", + "set_sql_debug", + "sql_debugging", + "show", + "PrimaryKey", + "Required", + "Optional", + "Set", + "Discriminator", + "composite_key", + "composite_index", + "flush", + "commit", + "rollback", + "db_session", + "with_transaction", + "make_proxy", + "LongStr", + "LongUnicode", + "Json", + "IntArray", + "StrArray", + "FloatArray", + "select", + "left_join", + "get", + "exists", + "delete", + "count", + "sum", + "min", + "max", + "avg", + "group_concat", + "distinct", + "JOIN", + "desc", + "between", + "concat", + "coalesce", + "raw_sql", + "buffer", + "unicode", + "get_current_user", + "set_current_user", + "perm", + "has_perm", + "get_user_groups", + "get_user_roles", + "get_object_labels", + "user_groups_getter", + "user_roles_getter", + "obj_labels_getter", +] + +suppress_debug_change: bool + +def sql_debug(value: bool) -> None: ... +def set_sql_debug(debug: bool = True, show_values=None) -> None: ... + +orm_logger: Logger +sql_logger: Logger +orm_log_level: int + +def log_orm(msg: object) -> None: ... +def args2str(args: list[object] | tuple[object] | dict[object, object]) -> str: ... + +class OrmError(Exception): ... +class ERDiagramError(OrmError): ... +class DBSchemaError(OrmError): ... +class MappingError(OrmError): ... +class BindingError(OrmError): ... +class TableDoesNotExist(OrmError): ... +class TableIsNotEmpty(OrmError): ... +class ConstraintError(OrmError): ... +class CacheIndexError(OrmError): ... +class RowNotFound(OrmError): ... +class MultipleRowsFound(OrmError): ... +class TooManyRowsFound(OrmError): ... +class PermissionError(OrmError): ... + +class ObjectNotFound(OrmError): + def __init__( + exc, entity: Entity, pkval: object | tuple[object, ...] | None = None # pkval passing to repr() builtins function + ) -> None: ... + +class MultipleObjectsFoundError(OrmError): ... +class TooManyObjectsFoundError(OrmError): ... +class OperationWithDeletedObjectError(OrmError): ... +class TransactionError(OrmError): ... +class ConnectionClosedError(TransactionError): ... + +class TransactionIntegrityError(TransactionError): + def __init__(exc, msg, original_exc=None) -> None: ... + +class CommitException(TransactionError): + def __init__(exc, msg, exceptions) -> None: ... + +class PartialCommitException(TransactionError): + def __init__(exc, msg, exceptions) -> None: ... + +class RollbackException(TransactionError): + def __init__(exc, msg, exceptions) -> None: ... + +class DatabaseSessionIsOver(TransactionError): ... + +TransactionRolledBack = DatabaseSessionIsOver + +class IsolationError(TransactionError): ... +class UnrepeatableReadError(IsolationError): ... +class OptimisticCheckError(IsolationError): ... +class UnresolvableCyclicDependency(TransactionError): ... + +class UnexpectedError(TransactionError): + def __init__(exc, msg, original_exc) -> None: ... + +class ExprEvalError(TranslationError): + def __init__(exc, src, cause) -> None: ... + +class PonyInternalException(Exception): ... +class OptimizationFailed(PonyInternalException): ... + +class UseAnotherTranslator(PonyInternalException): + translator: Incomplete + def __init__(self, translator) -> None: ... + +class PonyRuntimeWarning(RuntimeWarning): ... +class DatabaseContainsIncorrectValue(PonyRuntimeWarning): ... +class DatabaseContainsIncorrectEmptyValue(DatabaseContainsIncorrectValue): ... + +class PrefetchContext: + database: Incomplete + attrs_to_prefetch_dict: Incomplete + entities_to_prefetch: Incomplete + relations_to_prefetch_cache: Incomplete + def __init__(self, database=None) -> None: ... + def copy(self): ... + def __enter__(self) -> None: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def get_frozen_attrs_to_prefetch(self, entity): ... + def get_relations_to_prefetch(self, entity): ... + +class Local(localbase): + def __init__(local) -> None: ... + @property + def prefetch_context(local): ... + def push_debug_state(local, debug, show_values) -> None: ... + def pop_debug_state(local) -> None: ... + +local: Local + +def flush() -> None: ... +def commit() -> None: ... +def rollback() -> None: ... + +class DBSessionContextManager: + __slots__ = ( + "retry", + "retry_exceptions", + "allowed_exceptions", + "immediate", + "ddl", + "serializable", + "strict", + "optimistic", + "sql_debug", + "show_values", + ) + retry: int + ddl: bool + serializable: bool + immediate: bool + strict: bool + optimistic: bool + retry_exceptions: tuple[type[Exception], ...] + allowed_exceptions: tuple[type[Exception], ...] + sql_debug: bool | None + show_values: bool | None + def __init__( + db_session, + retry: int = 0, + immediate: bool = False, + ddl: bool = False, + serializable: bool = False, + strict: bool = False, + optimistic: bool = True, + retry_exceptions: tuple[type[Exception], ...] = ..., + allowed_exceptions: tuple[type[Exception], ...] = (), + sql_debug: bool | None = None, + show_values: bool | None = None, + ) -> None: ... + def __call__(db_session, *args, **kwargs): ... + def __enter__(db_session) -> None: ... + def __exit__(db_session, exc_type=None, exc=None, tb=None) -> None: ... + +db_session: DBSessionContextManager + +class SQLDebuggingContextManager: + debug: bool + show_values: Incomplete + def __init__(self, debug: bool = True, show_values=None) -> None: ... + def __call__(self, *args, **kwargs): ... + def __enter__(self) -> None: ... + def __exit__(self, exc_type=None, exc=None, tb=None) -> None: ... + +sql_debugging: SQLDebuggingContextManager + +def throw_db_session_is_over(action: str, obj: Entity, attr: Attribute | None = None) -> Never: ... +@deprecated("@with_transaction decorator is deprecated, use @db_session decorator instead.") +def with_transaction(*args, **kwargs): ... + +known_providers: tuple[_KnownProvider, ...] + +class OnConnectDecorator: + @staticmethod + def check_provider(provider: str | None) -> None: ... + provider: _KnownProvider | None + database: Incomplete + def __init__(self, database: Database, provider: str | None) -> None: ... + def __call__(self, func: types.FunctionType | None = None, provider: str | None = None) -> Self: ... + +db_id_counter: itertools.count[int] + +class Database: + def __deepcopy__(self, memo) -> Self: ... + id: Incomplete + priority: int + entities: Incomplete + schema: Incomplete + Entity: type[Entity] + on_connect: OnConnectDecorator + provider: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def call_on_connect(database, con) -> None: ... + def bind(self, *args, **kwargs) -> None: ... + @property + def last_sql(database): ... + @property + def local_stats(database): ... + def merge_local_stats(database) -> None: ... + @property + def global_stats(database): ... + @property + @deprecated("global_stats_lock is deprecated, just use global_stats property without any locking.") + def global_stats_lock(database): ... + def get_connection(database): ... + def disconnect(database) -> None: ... + def flush(database) -> None: ... + def commit(database) -> None: ... + def rollback(database) -> None: ... + def execute(database, sql, globals=None, locals=None): ... + def select(database, sql, globals=None, locals=None, frame_depth: int = 0): ... + def get(database, sql, globals=None, locals=None): ... + def exists(database, sql, globals=None, locals=None): ... + def insert(database, table_name, returning=None, **kwargs): ... + def generate_mapping(database, filename=None, check_tables: bool = True, create_tables: bool = False): ... + def drop_table(database, table_name, if_exists: bool = False, with_all_data: bool = False) -> None: ... + def drop_all_tables(database, with_all_data: bool = False) -> None: ... + def create_tables(database, check_tables: bool = False) -> None: ... + def check_tables(database) -> None: ... + def set_perms_for(database, *entities) -> Generator[None]: ... + def to_json(database, data, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + def from_json(database, changes, observer=None): ... + +def basic_converter(x): ... +def perm(*args, **kwargs) -> AccessRule: ... +def pop_names_from_kwargs(typename, kwargs, *kwnames): ... + +class AccessRule: + def __init__(rule, database, entities, permissions, groups, roles, labels) -> None: ... + def exclude(rule, *args) -> None: ... + +def has_perm(user, perm, x) -> bool: ... +def can_view(user, x) -> bool: ... +def can_edit(user, x) -> bool: ... +def can_create(user, x) -> bool: ... +def can_delete(user, x) -> bool: ... +def get_current_user(): ... +def set_current_user(user) -> None: ... + +anybody_frozenset: frozenset[str] + +def get_user_groups(user): ... +def get_user_roles(user, obj): ... +def get_object_labels(obj): ... + +usergroup_functions: list[Incomplete] + +def user_groups_getter(cls=None): ... + +userrole_functions: list[Incomplete] + +def user_roles_getter(user_cls=None, obj_cls=None): ... + +objlabel_functions: list[Incomplete] + +def obj_labels_getter(cls=None): ... + +class DbLocal(localbase): + stats: Incomplete + last_sql: Incomplete + def __init__(dblocal) -> None: ... + +class QueryStat: + def __init__(stat, sql, duration=None) -> None: ... + def copy(stat): ... + def query_executed(stat, duration) -> None: ... + def merge(stat, stat2) -> None: ... + @property + def avg_time(stat): ... + +num_counter: itertools.count[int] + +class SessionCache: + is_alive: bool + num: int + database: Database + objects: set[Incomplete] + indexes: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + seeds: defaultdict[Incomplete, set[Incomplete]] | None + max_id_cache: dict[Incomplete, Incomplete] | None + collection_statistics: dict[Incomplete, Incomplete] | None + for_update: set[Incomplete] | None + noflush_counter: int + modified_collections: defaultdict[Incomplete, set[Incomplete]] | None + objects_to_save: list[Incomplete] | None + saved_objects: list[Incomplete] | None + query_results: dict[Incomplete, Incomplete] | None + dbvals_deduplication_cache: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + modified: bool + db_session: Incomplete + immediate: bool + connection: Incomplete + in_transaction: bool + saved_fk_state: Incomplete + perm_cache: Incomplete + user_roles_cache: defaultdict[Incomplete, dict[Incomplete, Incomplete]] | None + obj_labels_cache: dict[Incomplete, Incomplete] | None + def __init__(cache, database: Database) -> None: ... + def connect(cache): ... + def reconnect(cache, exc): ... + def prepare_connection_for_query_execution(cache): ... + def flush_and_commit(cache) -> None: ... + def commit(cache) -> None: ... + def rollback(cache) -> None: ... + def release(cache) -> None: ... + def close(cache, rollback: bool = True) -> None: ... + def flush_disabled(cache) -> Generator[None]: ... + def flush(cache) -> None: ... + def call_after_save_hooks(cache) -> None: ... + def update_simple_index(cache, obj, attr, old_val, new_val, undo) -> None: ... + def db_update_simple_index(cache, obj, attr, old_dbval, new_dbval) -> None: ... + def update_composite_index(cache, obj, attrs, prev_vals, new_vals, undo) -> None: ... + def db_update_composite_index(cache, obj, attrs, prev_vals, new_vals) -> None: ... + +class NotLoadedValueType: ... + +NOT_LOADED: NotLoadedValueType + +class DefaultValueType: ... + +DEFAULT: DefaultValueType + +class DescWrapper: + attr: Attribute + def __init__(self, attr: Attribute) -> None: ... + def __call__(self) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +attr_id_counter: itertools.count[int] + +class Attribute: + __slots__ = ( + "nullable", + "is_required", + "is_discriminator", + "is_unique", + "is_part_of_unique_index", + "is_pk", + "is_collection", + "is_relation", + "is_basic", + "is_string", + "is_volatile", + "is_implicit", + "id", + "pk_offset", + "pk_columns_offset", + "py_type", + "sql_type", + "entity", + "name", + "lazy", + "lazy_sql_cache", + "args", + "auto", + "default", + "reverse", + "composite_keys", + "column", + "columns", + "col_paths", + "_columns_checked", + "converters", + "kwargs", + "cascade_delete", + "index", + "reverse_index", + "original_default", + "sql_default", + "py_check", + "hidden", + "optimistic", + "fk_name", + "type_has_empty_value", + "interleave", + ) + nullable: bool | None + is_required: bool + is_discriminator: bool + is_unique: bool | None + is_part_of_unique_index: bool | None + is_pk: bool + is_collection: bool + is_relation: bool + is_basic: bool + is_string: bool + is_volatile: bool + is_implicit: bool + id: int + pk_offset: int | None + pk_columns_offset: int + py_type: type | str | types.FunctionType | Array + sql_type: Incomplete + entity: Incomplete + name: Incomplete + lazy: bool + lazy_sql_cache: Incomplete + args: tuple[Incomplete, ...] + auto: bool + default: Incomplete + reverse: str | Attribute | None + composite_keys: list[tuple[Incomplete, int]] + column: str | None + columns: list[str] | tuple[str, ...] + col_paths: list[Incomplete] + converters: list[Incomplete] + kwargs: dict[str, Incomplete] + cascade_delete: bool | None + index: str | bool | None + reverse_index: Incomplete + original_default: Incomplete + sql_default: str | bool | None + py_check: Callable[..., bool] | None + hidden: bool + optimistic: bool | None + fk_name: str | None + type_has_empty_value: bool + interleave: bool | None + def __deepcopy__(attr, memo): ... + def __init__(attr, py_type: type | str | types.FunctionType | Array, *args, **kwargs) -> None: ... + def linked(attr) -> None: ... + def __lt__(attr, other): ... + def validate(attr, val, obj=None, entity=None, from_db: bool = False): ... + def parse_value(attr, row, offsets, dbvals_deduplication_cache): ... + def load(attr, obj: Entity): ... + def __get__(attr, obj, cls=None): ... + def get(attr, obj): ... + def __set__(attr, obj, new_val, undo_funcs=None) -> None: ... + def db_set(attr, obj, new_dbval, is_reverse_call: bool = False) -> None: ... + def update_reverse(attr, obj, old_val, new_val, undo_funcs) -> None: ... + def db_update_reverse(attr, obj, old_dbval, new_dbval) -> None: ... + def __delete__(attr, obj) -> None: ... + def get_raw_values(attr, val): ... + def get_columns(attr) -> list[str] | tuple[str, ...]: ... + @property + def asc(attr) -> Self: ... + @property + def desc(attr) -> DescWrapper: ... + def describe(attr) -> str: ... + +class Optional(Attribute): + __slots__: list[str] = [] + +class Required(Attribute): + __slots__: list[str] = [] + def validate(attr, val, obj=None, entity=None, from_db: bool = False): ... + +class Discriminator(Required): + __slots__ = ["code2cls"] + code2cls: dict[Incomplete, Incomplete] + def __init__(attr, py_type, *args, **kwargs) -> None: ... + @staticmethod + def create_default_attr(entity) -> None: ... + def process_entity_inheritance(attr, entity) -> None: ... + def validate(attr, val, obj=None, entity=None, from_db: bool = False): ... + def load(attr, obj) -> None: ... + def __get__(attr, obj, cls=None): ... + def __set__(attr, obj, new_val) -> None: ... # type: ignore[override] + def db_set(attr, obj, new_dbval) -> None: ... # type: ignore[override] + def update_reverse(attr, obj, old_val, new_val, undo_funcs) -> None: ... + +class Index: + __slots__ = ("entity", "attrs", "is_pk", "is_unique") + entity: Incomplete + attrs: list[Incomplete] + is_pk: bool + is_unique: bool + def __init__(index, *attrs, **options) -> None: ... + +def composite_index(*attrs) -> None: ... +def composite_key(*attrs) -> None: ... + +class PrimaryKey(Required): + __slots__: list[str] = [] + def __new__(cls, *args, **kwargs): ... + +class Collection(Attribute): + __slots__ = ( + "table", + "wrapper_class", + "symmetric", + "reverse_column", + "reverse_columns", + "nplus1_threshold", + "cached_load_sql", + "cached_add_m2m_sql", + "cached_remove_m2m_sql", + "cached_count_sql", + "cached_empty_sql", + "reverse_fk_name", + ) + table: str | list[str] | tuple[str, ...] | None + wrapper_class: Incomplete + symmetric: bool + reverse_column: Incomplete + reverse_columns: Incomplete + nplus1_threshold: int + cached_load_sql: dict[int, Incomplete] + cached_add_m2m_sql: tuple[Incomplete, Incomplete] | None + cached_remove_m2m_sql: tuple[Incomplete, Incomplete] | None + cached_count_sql: tuple[Incomplete, Incomplete] | None + cached_empty_sql: tuple[Incomplete, Incomplete, Incomplete] | None + reverse_fk_name: Incomplete + def __init__(attr, py_type, *args, **kwargs) -> None: ... + def load(attr, obj) -> None: ... + def __get__(attr, obj, cls=None) -> None: ... + def __set__(attr, obj, val) -> None: ... # type: ignore[override] + def __delete__(attr, obj) -> None: ... + def prepare(attr, obj, val, fromdb: bool = False) -> None: ... + def set(attr, obj, val, fromdb: bool = False) -> None: ... + +class SetData(set[Incomplete]): + __slots__ = ("is_fully_loaded", "added", "removed", "absent", "count") + is_fully_loaded: bool + added: Incomplete + removed: Incomplete + absent: Incomplete + count: int | None + def __init__(setdata) -> None: ... + +def construct_batchload_criteria_list( + alias, columns, converters, batch_size, row_value_syntax, start: int = 0, from_seeds: bool = True +): ... + +class Set(Collection): + __slots__: list[str] = [] + def validate(attr, val, obj=None, entity=None, from_db: bool = False): ... + def prefetch_load_all(attr, objects): ... + def load(attr, obj, items=None): ... + def construct_sql_m2m(attr, batch_size: int = 1, items_count: int = 0): ... + def copy(attr, obj): ... + def __get__(attr, obj, cls=None): ... + def __set__(attr, obj, new_items, undo_funcs=None) -> None: ... + def __delete__(attr, obj) -> None: ... + def reverse_add(attr, objects, item, undo_funcs) -> None: ... + def db_reverse_add(attr, objects, item) -> None: ... + def reverse_remove(attr, objects, item, undo_funcs) -> None: ... + def db_reverse_remove(attr, objects, item) -> None: ... + def get_m2m_columns(attr, is_reverse: bool = False): ... + def remove_m2m(attr, removed) -> None: ... + def add_m2m(attr, added) -> None: ... + def drop_table(attr, with_all_data: bool = False) -> None: ... + +def unpickle_setwrapper(obj, attrname, items): ... + +class SetIterator: + def __init__(self, wrapper) -> None: ... + def __iter__(self): ... + def next(self): ... + __next__ = next + +class SetInstance: + __slots__ = ("_obj_", "_attr_", "_attrnames_") + def __init__(wrapper, obj, attr) -> None: ... + def __reduce__(wrapper): ... + def copy(wrapper): ... + def __nonzero__(wrapper): ... + def is_empty(wrapper): ... + def __len__(wrapper) -> int: ... + def count(wrapper): ... + def __iter__(wrapper): ... + def __eq__(wrapper, other): ... + def __ne__(wrapper, other): ... + def __add__(wrapper, new_items): ... + def __sub__(wrapper, items): ... + def __contains__(wrapper, item) -> bool: ... + def create(wrapper, **kwargs): ... + def add(wrapper, new_items) -> None: ... + def __iadd__(wrapper, items): ... + def remove(wrapper, items) -> None: ... + def __isub__(wrapper, items): ... + def clear(wrapper) -> None: ... + def load(wrapper) -> None: ... + def select(wrapper, *args, **kwargs): ... + filter = select + def limit(wrapper, limit=None, offset=None): ... + def page(wrapper, pagenum, pagesize: int = 10): ... + def order_by(wrapper, *args): ... + def sort_by(wrapper, *args): ... + def random(wrapper, limit): ... + +def unpickle_multiset(obj, attrnames, items): ... + +class Multiset: + __slots__ = ["_obj_", "_attrnames_", "_items_"] + def __init__(multiset, obj, attrnames, items) -> None: ... + def __reduce__(multiset): ... + def distinct(multiset): ... + def __nonzero__(multiset): ... + def __len__(multiset) -> int: ... + def __iter__(multiset): ... + def __eq__(multiset, other): ... + def __ne__(multiset, other): ... + def __contains__(multiset, item) -> bool: ... + +class EntityIter: + entity: Incomplete + def __init__(self, entity) -> None: ... + def next(self) -> None: ... + __next__ = next + +entity_id_counter: itertools.count[int] +new_instance_id_counter: itertools.count[int] +select_re: re.Pattern[str] +lambda_re: re.Pattern[str] + +class EntityMeta(type): + def __new__(meta, name, bases, cls_dict): ... + def __init__(entity, name, bases, cls_dict) -> None: ... + def __iter__(entity): ... + def __getitem__(entity, key): ... + def exists(entity, *args, **kwargs): ... + def get(entity, *args, **kwargs): ... + def get_for_update(entity, *args, **kwargs): ... + def get_by_sql(entity, sql, globals=None, locals=None): ... + def select(entity, *args, **kwargs): ... + def select_by_sql(entity, sql, globals=None, locals=None): ... + def select_random(entity, limit): ... + def describe(entity) -> str: ... + def drop_table(entity, with_all_data: bool = False) -> None: ... + +def populate_criteria_list( + criteria_list, columns, converters, operations, params_count: int = 0, table_alias=None, optimistic: bool = False +) -> int: ... + +statuses: set[str] +del_statuses: set[str] +created_or_deleted_statuses: set[str] +saved_statuses: set[str] + +def throw_object_was_deleted(obj: Entity) -> Never: ... +def unpickle_entity(d): ... +def safe_repr(obj: Entity) -> str: ... +def make_proxy(obj: Entity) -> EntityProxy: ... + +class EntityProxy: + def __init__(self, obj: Entity) -> None: ... + def __getattr__(self, name: str): ... + def __setattr__(self, name: str, value) -> None: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + +class Entity(metaclass=EntityMeta): + __slots__ = ( + "_session_cache_", + "_status_", + "_pkval_", + "_newid_", + "_dbvals_", + "_vals_", + "_rbits_", + "_wbits_", + "_save_pos_", + "__weakref__", + ) + def __reduce__(obj): ... + def __init__(obj, *args, **kwargs) -> None: ... + def get_pk(obj): ... + def __lt__(entity, other): ... + def __le__(entity, other): ... + def __gt__(entity, other): ... + def __ge__(entity, other): ... + def load(obj, *attrs) -> None: ... + def delete(obj) -> None: ... + def set(obj, **kwargs) -> None: ... + def find_updated_attributes(obj): ... + def flush(obj) -> None: ... + def before_insert(obj) -> None: ... + def before_update(obj) -> None: ... + def before_delete(obj) -> None: ... + def after_insert(obj) -> None: ... + def after_update(obj) -> None: ... + def after_delete(obj) -> None: ... + def to_dict( + obj, only=None, exclude=None, with_collections: bool = False, with_lazy: bool = False, related_objects: bool = False + ): ... + def to_json(obj, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + +def string2ast(s: str) -> ast.Expr: ... +def get_globals_and_locals(args, kwargs, frame_depth, from_generator=False): ... +def make_query(args, frame_depth, left_join: bool = False) -> Query: ... +def select(*args): ... +def left_join(*args): ... +def get(*args): ... +def exists(*args): ... +def delete(*args): ... +def make_aggrfunc(std_func): ... + +count: Incomplete +sum: Incomplete +min: Incomplete +max: Incomplete +avg: Incomplete +group_concat: Incomplete +distinct: Incomplete + +def JOIN(expr: _T) -> _T: ... +def desc(expr): ... +def extract_vars(code_key, filter_num, extractors, globals, locals, cells=None): ... +def unpickle_query(query_result: _T) -> _T: ... + +class Query: + def __init__(query, code_key, tree, globals, locals, cells=None, left_join: bool = False) -> None: ... + def __reduce__(query): ... + def get_sql(query): ... + def prefetch(query, *args): ... + def show(query, width=None, stream=None) -> None: ... + def get(query): ... + def first(query): ... + def without_distinct(query): ... + def distinct(query): ... + def exists(query): ... + def delete(query, bulk=None): ... + def __len__(query) -> int: ... + def __iter__(query): ... + def order_by(query, *args): ... + def sort_by(query, *args): ... + def filter(query, *args, **kwargs): ... + def where(query, *args, **kwargs): ... + def __getitem__(query, key): ... + def fetch(query, limit=None, offset=None): ... + def limit(query, limit=None, offset=None): ... + def page(query, pagenum, pagesize: int = 10): ... + def sum(query, distinct=None): ... + def avg(query, distinct=None): ... + def group_concat(query, sep=None, distinct=None): ... + def min(query): ... + def max(query): ... + def count(query, distinct=None): ... + def for_update(query, nowait: bool = False, skip_locked: bool = False): ... + def random(query, limit): ... + def to_json(query, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + +class QueryResultIterator: + __slots__ = ("_query_result", "_position") + def __init__(self, query_result) -> None: ... + def next(self): ... + __next__ = next + def __length_hint__(self) -> int: ... + +def make_query_result_method_error_stub(name: str, title: str | None = None) -> Callable[..., Never]: ... + +class QueryResult: + __slots__ = ("_query", "_limit", "_offset", "_items", "_expr_type", "_col_names") + def __init__(self, query, limit, offset, lazy) -> None: ... + def __iter__(self): ... + def __len__(self) -> int: ... + def __getitem__(self, key): ... + def __contains__(self, item) -> bool: ... + def index(self, item): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __reversed__(self): ... + def reverse(self) -> None: ... + def sort(self, *args, **kwargs) -> None: ... + def shuffle(self) -> None: ... + def show(self, width=None, stream=None): ... + def to_json(self, include=(), exclude=(), converter=None, with_schema: bool = True, schema_hash=None): ... + def __add__(self, other): ... + def __radd__(self, other): ... + def to_list(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + __iadd__: Incomplete + __imul__: Incomplete + __mul__: Incomplete + __rmul__: Incomplete + append: Incomplete + clear: Incomplete + extend: Incomplete + insert: Incomplete + pop: Incomplete + remove: Incomplete + +def strcut(s: str, width: int) -> str: ... +def show(entity) -> None: ... + +special_functions: set[Incomplete] +const_functions: set[type] diff --git a/stubs/pony/pony/orm/dbapiprovider.pyi b/stubs/pony/pony/orm/dbapiprovider.pyi new file mode 100644 index 000000000000..ce0c0a5e3eff --- /dev/null +++ b/stubs/pony/pony/orm/dbapiprovider.pyi @@ -0,0 +1,216 @@ +import json +import re +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +from pony.utils import localbase + +class DBException(Exception): + def __init__(exc, original_exc, *args) -> None: ... + +class Warning(DBException): ... +class Error(DBException): ... +class InterfaceError(Error): ... +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... + +def wrap_dbapi_exceptions(func, provider, *args, **kwargs): ... +def unexpected_args(attr, args) -> None: ... + +version_re: re.Pattern[str] + +def get_version_tuple(s: str): ... + +class DBAPIProvider: + paramstyle: ClassVar[str] + quote_char: ClassVar[str] + max_params_count: ClassVar[int] + max_name_len: ClassVar[int] + table_if_not_exists_syntax: ClassVar[bool] + index_if_not_exists_syntax: ClassVar[bool] + max_time_precision: ClassVar[int] + default_time_precision: ClassVar[int] + uint64_support: ClassVar[bool] + varchar_default_max_len: ClassVar[int | None] + dialect: ClassVar[str | None] + dbapi_module: ClassVar[types.ModuleType | None] + dbschema_cls: ClassVar[type | None] + translator_cls: ClassVar[type | None] + sqlbuilder_cls: ClassVar[type | None] + array_converter_cls: ClassVar[type | None] + name_before_table: ClassVar[str] + default_schema_name: ClassVar[str | None] + fk_types: ClassVar[dict[str, str]] + converter_classes: Incomplete + def __init__(provider, _database, *args, **kwargs) -> None: ... + def inspect_connection(provider, connection) -> None: ... + def normalize_name(provider, name): ... + def get_default_entity_table_name(provider, entity): ... + def get_default_m2m_table_name(provider, attr, reverse): ... + def get_default_column_names(provider, attr, reverse_pk_columns=None): ... + def get_default_m2m_column_names(provider, entity): ... + def get_default_index_name( + provider, table_name, column_names, is_pk: bool = False, is_unique: bool = False, m2m: bool = False + ): ... + def get_default_fk_name(provider, child_table_name, parent_table_name, child_column_names): ... + def split_table_name(provider, table_name): ... + def base_name(provider, name): ... + def quote_name(provider, name: str | Iterable[str]) -> str: ... + def format_table_name(provider, name): ... + def normalize_vars(provider, vars, vartypes) -> None: ... + def ast2sql(provider, ast): ... + def should_reconnect(provider, exc): ... + def connect(provider): ... + def set_transaction_mode(provider, connection, cache) -> None: ... + def commit(provider, connection, cache=None) -> None: ... + def rollback(provider, connection, cache=None) -> None: ... + def release(provider, connection, cache=None) -> None: ... + def drop(provider, connection, cache=None) -> None: ... + def disconnect(provider) -> None: ... + def execute(provider, cursor, sql, arguments=None, returning_id: bool = False): ... + def get_converter_by_py_type(provider, py_type): ... + def get_converter_by_attr(provider, attr): ... + def get_pool(provider, *args, **kwargs): ... + def table_exists(provider, connection, table_name, case_sensitive: bool = True) -> None: ... + def index_exists(provider, connection, table_name, index_name, case_sensitive: bool = True) -> None: ... + def fk_exists(provider, connection, table_name, fk_name, case_sensitive: bool = True) -> None: ... + def table_has_data(provider, connection, table_name): ... + def disable_fk_checks(provider, connection) -> None: ... + def enable_fk_checks(provider, connection, prev_state) -> None: ... + def drop_table(provider, connection, table_name) -> None: ... + +class Pool(localbase): + forked_connections: list[tuple[Incomplete, int | None]] + dbapi_module: types.ModuleType + args: tuple[Incomplete, ...] + kwargs: dict[str, Incomplete] + con: Incomplete + pid: int | None + def __init__(pool, dbapi_module: types.ModuleType, *args, **kwargs) -> None: ... + def connect(pool) -> tuple[Incomplete, bool]: ... + def release(pool, con) -> None: ... + def drop(pool, con) -> None: ... + def disconnect(pool) -> None: ... + +class Converter: + EQ: str + NE: str + optimistic: bool + def __deepcopy__(converter, memo): ... + def __init__(converter, provider, py_type, attr=None) -> None: ... + def init(converter, kwargs) -> None: ... + def validate(converter, val, obj=None): ... + def py2sql(converter, val): ... + def sql2py(converter, val): ... + def val2dbval(self, val, obj=None): ... + def dbval2val(self, dbval, obj=None): ... + def dbvals_equal(self, x, y): ... + def get_sql_type(converter, attr=None): ... + def get_fk_type(converter, sql_type): ... + +class NoneConverter(Converter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def get_sql_type(converter, attr=None) -> None: ... + def get_fk_type(converter, sql_type) -> None: ... + +class BoolConverter(Converter): + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class StrConverter(Converter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def init(converter, kwargs) -> None: ... + def validate(converter, val, obj=None): ... + def sql_type(converter): ... + +class IntConverter(Converter): + signed_types: Incomplete + unsigned_types: Incomplete + def init(converter, kwargs) -> None: ... + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class RealConverter(Converter): + EQ: str + NE: str + default_tolerance: float + optimistic: bool + def init(converter, kwargs) -> None: ... + def validate(converter, val, obj=None): ... + def dbvals_equal(converter, x, y): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class DecimalConverter(Converter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def init(converter, kwargs) -> None: ... + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class BlobConverter(Converter): + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class DateConverter(Converter): + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class ConverterWithMicroseconds(Converter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def init(converter, kwargs) -> None: ... + def round_microseconds_to_precision(converter, microseconds, precision): ... + def sql_type(converter): ... + +class TimeConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + +class TimedeltaConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + +class DatetimeConverter(ConverterWithMicroseconds): + sql_type_name: ClassVar[str] + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + +class UuidConverter(Converter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def validate(converter, val, obj=None): ... + def py2sql(converter, val): ... + sql2py = validate + def sql_type(converter): ... + +class JsonConverter(Converter): + json_kwargs: Incomplete + + class JsonEncoder(json.JSONEncoder): + def default(converter, obj): ... + + def validate(converter, val, obj=None): ... + def val2dbval(converter, val, obj=None): ... + def dbval2val(converter, dbval, obj=None): ... + def dbvals_equal(converter, x, y): ... + def sql_type(converter): ... + +class ArrayConverter(Converter): + array_types: Incomplete + def __init__(converter, provider, py_type, attr=None) -> None: ... + def validate(converter, val, obj=None): ... + def dbval2val(converter, dbval, obj=None): ... + def val2dbval(converter, val, obj=None): ... + def sql_type(converter): ... diff --git a/stubs/pony/pony/orm/dbproviders/__init__.pyi b/stubs/pony/pony/orm/dbproviders/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/dbproviders/cockroach.pyi b/stubs/pony/pony/orm/dbproviders/cockroach.pyi new file mode 100644 index 000000000000..2a3cfa5c7a2d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/cockroach.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider +from pony.orm.dbproviders.postgres import ( + PGArrayConverter, + PGBlobConverter, + PGColumn, + PGIntConverter, + PGProvider, + PGSchema, + PGSQLBuilder, + PGTimedeltaConverter, + PGTranslator, +) + +NoneType: type[None] + +class CRColumn(PGColumn): + auto_template: ClassVar[str] + +class CRSchema(PGSchema): + column_class: ClassVar[type[CRColumn]] + +class CRTranslator(PGTranslator): ... +class CRSQLBuilder(PGSQLBuilder): ... + +class CRIntConverter(PGIntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + +class CRBlobConverter(PGBlobConverter): + def sql_type(converter): ... + +class CRTimedeltaConverter(PGTimedeltaConverter): ... + +class PGUuidConverter(dbapiprovider.UuidConverter): + def py2sql(converter, val): ... + +class CRArrayConverter(PGArrayConverter): + array_types: Incomplete + +class CRProvider(PGProvider): + dbschema_cls: ClassVar[type[CRSchema]] + translator_cls: ClassVar[type[CRTranslator]] + sqlbuilder_cls: ClassVar[type[CRSQLBuilder]] + array_converter_cls: ClassVar[type[CRArrayConverter]] + +provider_cls = CRProvider diff --git a/stubs/pony/pony/orm/dbproviders/mysql.pyi b/stubs/pony/pony/orm/dbproviders/mysql.pyi new file mode 100644 index 000000000000..79e9dbc4ed09 --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/mysql.pyi @@ -0,0 +1,102 @@ +import types +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator + +NoneType: type[None] +mysql_module_name: str + +class MySQLColumn(dbschema.Column): + auto_template: ClassVar[str] + +class MySQLSchema(dbschema.DBSchema): + dialect: ClassVar[str] + column_class: ClassVar[type[MySQLColumn]] + +class MySQLTranslator(SQLTranslator): + dialect: ClassVar[str] + +class MySQLValue(Value): + __slots__: list[str] = [] + +class MySQLBuilder(SQLBuilder): + dialect: ClassVar[str] + value_class: ClassVar[type[MySQLValue]] + def CONCAT(builder, *args): ... + def TRIM(builder, expr, chars=None): ... + def LTRIM(builder, expr, chars=None): ... + def RTRIM(builder, expr, chars=None): ... + def TO_INT(builder, expr): ... + def TO_REAL(builder, expr): ... + def TO_STR(builder, expr): ... + def YEAR(builder, expr): ... + def MONTH(builder, expr): ... + def DAY(builder, expr): ... + def HOUR(builder, expr): ... + def MINUTE(builder, expr): ... + def SECOND(builder, expr): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def JSON_QUERY(builder, expr, path): ... + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_ARRAY_LENGTH(builder, value): ... + def JSON_EQ(builder, left, right): ... + def JSON_NE(builder, left, right): ... + def JSON_CONTAINS(builder, expr, path, key): ... + @classmethod + def wrap_param_to_json_array(cls, values): ... + def JSON_PARAM(builder, expr): ... + +class MySQLStrConverter(dbapiprovider.StrConverter): + def sql_type(converter): ... + +class MySQLRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class MySQLBlobConverter(dbapiprovider.BlobConverter): + def sql_type(converter): ... + +class MySQLTimeConverter(dbapiprovider.TimeConverter): + def sql2py(converter, val): ... + +class MySQLTimedeltaConverter(dbapiprovider.TimedeltaConverter): ... + +class MySQLUuidConverter(dbapiprovider.UuidConverter): + def sql_type(converter): ... + +class MySQLJsonConverter(dbapiprovider.JsonConverter): + EQ: str + NE: str + def init(self, kwargs) -> None: ... + +class MySQLProvider(DBAPIProvider): + dialect: ClassVar[str] + varchar_default_max_len: ClassVar[int] + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[MySQLSchema]] + translator_cls: ClassVar[type[MySQLTranslator]] + sqlbuilder_cls: ClassVar[type[MySQLBuilder]] + fk_types: ClassVar[dict[str, str]] + converter_classes: Incomplete + def normalize_name(provider, name): ... + def inspect_connection(provider, connection) -> None: ... + def should_reconnect(provider, exc): ... + def get_pool(provider, *args, **kwargs): ... + def set_transaction_mode(provider, connection, cache) -> None: ... + def release(provider, connection, cache=None) -> None: ... + def table_exists(provider, connection, table_name, case_sensitive: bool = True): ... + def index_exists(provider, connection, table_name, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection, table_name, fk_name, case_sensitive: bool = True): ... + +provider_cls = MySQLProvider + +def str2datetime(s): ... diff --git a/stubs/pony/pony/orm/dbproviders/oracle.pyi b/stubs/pony/pony/orm/dbproviders/oracle.pyi new file mode 100644 index 000000000000..220e58f4099d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/oracle.pyi @@ -0,0 +1,159 @@ +import re +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm import dbapiprovider, sqltranslation +from pony.orm.dbapiprovider import DBAPIProvider +from pony.orm.dbschema import Column, DBObject, DBSchema, Table +from pony.orm.sqlbuilding import SQLBuilder + +NoneType: type[None] + +class OraTable(Table): + def get_objects_to_create(table, created_tables=None): ... + +class OraSequence(DBObject): + typename: ClassVar[str] + def __init__(sequence, table, name=None) -> None: ... + def exists(sequence, provider, connection, case_sensitive: bool = True): ... + def get_create_command(sequence): ... + +trigger_template: str + +class OraTrigger(DBObject): + typename: ClassVar[str] + def __init__(trigger, table, column, sequence) -> None: ... + def exists(trigger, provider, connection, case_sensitive: bool = True): ... + def get_create_command(trigger): ... + +class OraColumn(Column): + auto_template: ClassVar[None] # type: ignore[assignment] + +class OraSchema(DBSchema): + dialect: ClassVar[str] + table_class: ClassVar[type[OraTable]] + column_class: ClassVar[type[OraColumn]] + +class OraNoneMonad(sqltranslation.NoneMonad): + def __init__(monad, value=None) -> None: ... + +class OraConstMonad(sqltranslation.ConstMonad): + @staticmethod + def new(value): ... + +class OraTranslator(sqltranslation.SQLTranslator): + dialect: ClassVar[str] + NoneMonad = OraNoneMonad + ConstMonad = OraConstMonad + +class OraBuilder(SQLBuilder): + dialect: ClassVar[str] + def INSERT(builder, table_name, columns, values, returning=None): ... + def SELECT_FOR_UPDATE(builder, nowait, skip_locked, *sections): ... + def SELECT(builder, *sections): ... + def ROWID(builder, *expr_list): ... + def LIMIT(builder, limit, offset=None) -> None: ... + def TO_REAL(builder, expr): ... + def TO_STR(builder, expr): ... + def DATE(builder, expr): ... + def RANDOM(builder): ... + def MOD(builder, a, b): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def build_json_path(builder, path): ... + def JSON_QUERY(builder, expr, path): ... + json_value_type_mapping: Incomplete + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_CONTAINS(builder, expr, path, key): ... + def JSON_ARRAY_LENGTH(builder, value) -> None: ... + def GROUP_CONCAT(builder, distinct, expr, sep=None): ... + +json_item_re: re.Pattern[str] + +class OraBoolConverter(dbapiprovider.BoolConverter): + def py2sql(converter, val): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class OraStrConverter(dbapiprovider.StrConverter): + def validate(converter, val, obj=None): ... + def sql2py(converter, val): ... + def sql_type(converter): ... + +class OraIntConverter(dbapiprovider.IntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + def init(self, kwargs) -> None: ... + +class OraRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class OraDecimalConverter(dbapiprovider.DecimalConverter): + def sql_type(converter): ... + +class OraBlobConverter(dbapiprovider.BlobConverter): + def sql2py(converter, val): ... + +class OraDateConverter(dbapiprovider.DateConverter): + def sql2py(converter, val): ... + +class OraTimeConverter(dbapiprovider.TimeConverter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class OraTimedeltaConverter(dbapiprovider.TimedeltaConverter): + def __init__(converter, provider, py_type, attr=None) -> None: ... + +class OraDatetimeConverter(dbapiprovider.DatetimeConverter): ... + +class OraUuidConverter(dbapiprovider.UuidConverter): + def sql_type(converter): ... + +class OraJsonConverter(dbapiprovider.JsonConverter): + json_kwargs: Incomplete + optimistic: bool + def sql2py(converter, dbval): ... + def sql_type(converter): ... + +class OraProvider(DBAPIProvider): + dialect: ClassVar[str] + varchar_default_max_len: ClassVar[int] + dbschema_cls: ClassVar[type[OraSchema]] + translator_cls: ClassVar[type[OraTranslator]] + sqlbuilder_cls: ClassVar[type[OraBuilder]] + converter_classes: Incomplete + def inspect_connection(provider, connection) -> None: ... + def should_reconnect(provider, exc): ... + def normalize_name(provider, name): ... + def normalize_vars(provider, vars, vartypes) -> None: ... + def set_transaction_mode(provider, connection, cache) -> None: ... + def execute(provider, cursor, sql, arguments=None, returning_id: bool = False): ... + def get_pool(provider, *args, **kwargs): ... + def table_exists(provider, connection, table_name, case_sensitive: bool = True): ... + def index_exists(provider, connection, table_name, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection, table_name, fk_name, case_sensitive: bool = True): ... + def table_has_data(provider, connection, table_name): ... + def drop_table(provider, connection, table_name) -> None: ... + +provider_cls = OraProvider + +def to_int_or_decimal(val): ... +def to_decimal(val): ... +def output_type_handler(cursor, name, defaultType, size, precision, scale): ... + +class OraPool: + forked_pools: Incomplete + def __init__(pool, **kwargs) -> None: ... + def connect(pool): ... + def release(pool, con) -> None: ... + def drop(pool, con) -> None: ... + def disconnect(pool) -> None: ... + +def get_inputsize(arg): ... +def set_input_sizes(cursor, arguments) -> None: ... diff --git a/stubs/pony/pony/orm/dbproviders/postgres.pyi b/stubs/pony/pony/orm/dbproviders/postgres.pyi new file mode 100644 index 000000000000..a2f472c3890d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/postgres.pyi @@ -0,0 +1,106 @@ +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider, Pool +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator +from psycopg2._psycopg import _Connection + +NoneType: type[None] + +class PGColumn(dbschema.Column): + auto_template: ClassVar[str] + +class PGSchema(dbschema.DBSchema): + dialect: ClassVar[str] + column_class: ClassVar[type[PGColumn]] + +class PGTranslator(SQLTranslator): + dialect: ClassVar[str] + +class PGValue(Value): + __slots__: list[str] = [] + +class PGSQLBuilder(SQLBuilder): + dialect: ClassVar[str] + value_class: ClassVar[type[PGValue]] + def INSERT(builder, table_name, columns, values, returning=None): ... + def TO_INT(builder, expr): ... + def TO_STR(builder, expr): ... + def TO_REAL(builder, expr): ... + def DATE(builder, expr): ... + def RANDOM(builder): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def eval_json_path(builder, values: Iterable[int | str]) -> str: ... # type: ignore[override] + def JSON_QUERY(builder, expr, path): ... + json_value_type_mapping: dict[type, str] + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_CONCAT(builder, left, right): ... + def JSON_CONTAINS(builder, expr, path, key): ... + def JSON_ARRAY_LENGTH(builder, value): ... + def GROUP_CONCAT(builder, distinct, expr, sep=None): ... + def ARRAY_INDEX(builder, col, index): ... + def ARRAY_CONTAINS(builder, key, not_in, col): ... + def ARRAY_SUBSET(builder, array1, not_in, array2): ... + def ARRAY_LENGTH(builder, array): ... + def ARRAY_SLICE(builder, array, start, stop): ... + def MAKE_ARRAY(builder, *items): ... + +class PGIntConverter(dbapiprovider.IntConverter): + signed_types: Incomplete + unsigned_types: Incomplete + +class PGRealConverter(dbapiprovider.RealConverter): + def sql_type(converter): ... + +class PGBlobConverter(dbapiprovider.BlobConverter): + def sql_type(converter): ... + +class PGTimedeltaConverter(dbapiprovider.TimedeltaConverter): ... +class PGDatetimeConverter(dbapiprovider.DatetimeConverter): ... + +class PGUuidConverter(dbapiprovider.UuidConverter): + def py2sql(converter, val): ... + +class PGJsonConverter(dbapiprovider.JsonConverter): + def sql_type(self): ... + +class PGArrayConverter(dbapiprovider.ArrayConverter): + array_types: dict[type, tuple[str, type]] + +class PGPool(Pool): + def release(pool, con) -> None: ... + +ADMIN_SHUTDOWN: str + +class PGProvider(DBAPIProvider): + dialect: ClassVar[str] + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[PGSchema]] + translator_cls: ClassVar[type[PGTranslator]] + sqlbuilder_cls: ClassVar[type[PGSQLBuilder]] + array_converter_cls: ClassVar[type[PGArrayConverter]] + default_schema_name: ClassVar[str] + fk_types: ClassVar[dict[str, str]] + converter_classes: list[tuple[type | tuple[type], type]] + def normalize_name(provider, name: str) -> str: ... + def inspect_connection(provider, connection: _Connection) -> None: ... + def should_reconnect(provider, exc: BaseException | None) -> bool: ... + def get_pool(provider, *args, **kwargs) -> PGPool: ... + def set_transaction_mode(provider, connection: _Connection, cache) -> None: ... + def execute(provider, cursor, sql, arguments=None, returning_id: bool = False): ... + def table_exists(provider, connection: _Connection, table_name: str, case_sensitive: bool = True): ... + def index_exists(provider, connection: _Connection, table_name: str, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection: _Connection, table_name: str, fk_name, case_sensitive: bool = True): ... + def drop_table(provider, connection: _Connection, table_name: str) -> None: ... + +provider_cls = PGProvider diff --git a/stubs/pony/pony/orm/dbproviders/sqlite.pyi b/stubs/pony/pony/orm/dbproviders/sqlite.pyi new file mode 100644 index 000000000000..d7b984d30c5d --- /dev/null +++ b/stubs/pony/pony/orm/dbproviders/sqlite.pyi @@ -0,0 +1,221 @@ +import re +import sys +import types +from _typeshed import Incomplete, StrOrBytesPath +from sqlite3 import Connection as _Connection +from typing import Any, ClassVar, overload + +from pony.orm import dbapiprovider, dbschema +from pony.orm.dbapiprovider import DBAPIProvider, Pool +from pony.orm.sqlbuilding import SQLBuilder, Value +from pony.orm.sqltranslation import SQLTranslator +from pony.utils import localbase + +class SqliteExtensionUnavailable(Exception): ... + +NoneType: type[None] + +class SQLiteForeignKey(dbschema.ForeignKey): + def get_create_command(foreign_key) -> None: ... + +class SQLiteSchema(dbschema.DBSchema): + dialect: ClassVar[str] + fk_class: ClassVar[type[SQLiteForeignKey]] + +def make_overriden_string_func(sqlop): ... + +class SQLiteTranslator(SQLTranslator): + dialect: ClassVar[str] + sqlite_version: tuple[int, int, int] + StringMixin_UPPER: Incomplete + StringMixin_LOWER: Incomplete + +class SQLiteValue(Value): + __slots__: list[str] = [] + +class SQLiteBuilder(SQLBuilder): + dialect: ClassVar[str] + least_func_name: ClassVar[str] + greatest_func_name: ClassVar[str] + value_class: ClassVar[type[SQLiteValue]] + def __init__(builder, provider, ast) -> None: ... + def SELECT_FOR_UPDATE(builder, nowait, skip_locked, *sections): ... + def INSERT(builder, table_name, columns, values, returning=None): ... + def STRING_SLICE(builder, expr, start, stop): ... + def IN(builder, expr1, x): ... + def NOT_IN(builder, expr1, x): ... + def TODAY(builder): ... + def NOW(builder): ... + def YEAR(builder, expr): ... + def MONTH(builder, expr): ... + def DAY(builder, expr): ... + def HOUR(builder, expr): ... + def MINUTE(builder, expr): ... + def SECOND(builder, expr): ... + def datetime_add(builder, funcname, expr, td): ... + def DATE_ADD(builder, expr, delta): ... + def DATE_SUB(builder, expr, delta): ... + def DATE_DIFF(builder, expr1, expr2): ... + def DATETIME_ADD(builder, expr, delta): ... + def DATETIME_SUB(builder, expr, delta): ... + def DATETIME_DIFF(builder, expr1, expr2): ... + def RANDOM(builder): ... + PY_UPPER: Incomplete + PY_LOWER: Incomplete + def FLOAT_EQ(builder, a, b): ... + def FLOAT_NE(builder, a, b): ... + def JSON_QUERY(builder, expr, path): ... + json_value_type_mapping: Incomplete + def JSON_VALUE(builder, expr, path, type): ... + def JSON_NONZERO(builder, expr): ... + def JSON_ARRAY_LENGTH(builder, value): ... + def JSON_CONTAINS(builder, expr, path, key): ... + def ARRAY_INDEX(builder, col, index): ... + def ARRAY_CONTAINS(builder, key, not_in, col): ... + def ARRAY_SUBSET(builder, array1, not_in, array2): ... + def ARRAY_LENGTH(builder, array): ... + def ARRAY_SLICE(builder, array, start, stop): ... + def MAKE_ARRAY(builder, *items): ... + +class SQLiteIntConverter(dbapiprovider.IntConverter): + def sql_type(converter): ... + +class SQLiteDecimalConverter(dbapiprovider.DecimalConverter): + inf: Incomplete + neg_inf: Incomplete + NaN: Incomplete + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class SQLiteDateConverter(dbapiprovider.DateConverter): + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class SQLiteTimeConverter(dbapiprovider.TimeConverter): + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class SQLiteTimedeltaConverter(dbapiprovider.TimedeltaConverter): + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class SQLiteDatetimeConverter(dbapiprovider.DatetimeConverter): + def sql2py(converter, val): ... + def py2sql(converter, val): ... + +class SQLiteJsonConverter(dbapiprovider.JsonConverter): + json_kwargs: Incomplete + +def dumps(items): ... + +class SQLiteArrayConverter(dbapiprovider.ArrayConverter): + array_types: Incomplete + def dbval2val(converter, dbval, obj=None): ... + def val2dbval(converter, val, obj=None): ... + +class LocalExceptions(localbase): + exc_info: Incomplete + keep_traceback: bool + def __init__(self) -> None: ... + +local_exceptions: LocalExceptions + +def keep_exception(func): ... + +class SQLiteProvider(DBAPIProvider): + dialect: ClassVar[str] + local_exceptions: LocalExceptions + dbapi_module: ClassVar[types.ModuleType] + dbschema_cls: ClassVar[type[SQLiteSchema]] + translator_cls: ClassVar[type[SQLiteTranslator]] + sqlbuilder_cls: ClassVar[type[SQLiteBuilder]] + array_converter_cls: ClassVar[type[SQLiteArrayConverter]] + server_version: tuple[int, int, int] + converter_classes: Incomplete + def __init__(provider, database, filename, **kwargs) -> None: ... + def inspect_connection(provider, conn) -> None: ... + def restore_exception(provider) -> None: ... + def acquire_lock(provider) -> None: ... + def release_lock(provider) -> None: ... + def set_transaction_mode(provider, connection: _Connection, cache) -> None: ... + def commit(provider, connection: _Connection, cache=None) -> None: ... + def rollback(provider, connection: _Connection, cache=None) -> None: ... + def drop(provider, connection: _Connection, cache=None) -> None: ... + def release(provider, connection: _Connection, cache=None) -> None: ... + def get_pool(provider, is_shared_memory_db, filename, create_db: bool = False, **kwargs): ... + def table_exists(provider, connection: _Connection, table_name: str, case_sensitive: bool = True): ... + def index_exists(provider, connection: _Connection, table_name: str, index_name, case_sensitive: bool = True): ... + def fk_exists(provider, connection: _Connection, table_name: str, fk_name) -> None: ... # type: ignore[override] + def check_json1(provider, connection: _Connection) -> bool: ... + +provider_cls = SQLiteProvider + +def make_string_function(name, base_func): ... + +py_upper: Incomplete +py_lower: Incomplete + +@overload +def py_json_unwrap(value: str) -> str | None: ... +@overload +def py_json_unwrap(value: Any) -> None: ... + +path_cache: Incomplete +json_path_re: re.Pattern[str] + +def py_json_extract(expr, *paths): ... +def py_json_query(expr, path, with_wrapper): ... +def py_json_value(expr, path): ... +def py_json_contains(expr, path, key): ... +def py_json_nonzero(expr, path): ... +def py_json_array_length(expr, path=None): ... +def wrap_array_func(func): ... +def py_array_index(array, index): ... +def py_array_contains(array, item): ... +def py_array_subset(array, items): ... +def py_array_length(array): ... +def py_array_slice(array, start, stop): ... +def py_make_array(*items): ... + +@overload +def py_string_slice(s: None, start: str | int | None, end: str | int | None) -> None: ... +@overload +def py_string_slice(s: str, start: str | int | None, end: str | int | None) -> str: ... + +class SQLitePool(Pool): + is_shared_memory_db: bool | None + filename: StrOrBytesPath + create_db: bool | None + kwargs: dict[str, Incomplete] + if sys.version_info >= (3, 12): + def __init__( + pool, + is_shared_memory_db: bool | None, + filename: StrOrBytesPath, + create_db: bool | None, + *, + timeout: float = 5.0, + detect_types: int = 0, + check_same_thread: bool = True, + factory: type[_Connection], + cached_statements: int = 128, + uri: bool = False, + autocommit: bool = ..., + ) -> None: ... + else: + def __init__( + pool, + is_shared_memory_db: bool | None, + filename: StrOrBytesPath, + create_db: bool | None, + *, + timeout: float = 5.0, + detect_types: int = 0, + check_same_thread: bool = True, + factory: type[_Connection], + cached_statements: int = 128, + uri: bool = False, + ) -> None: ... + + def disconnect(pool) -> None: ... + def drop(pool, con: _Connection) -> None: ... diff --git a/stubs/pony/pony/orm/dbschema.pyi b/stubs/pony/pony/orm/dbschema.pyi new file mode 100644 index 000000000000..686ca5f2dc7e --- /dev/null +++ b/stubs/pony/pony/orm/dbschema.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from pony.orm.dbapiprovider import DBAPIProvider + +class DBSchema: + dialect: ClassVar[str | None] + inline_fk_syntax: ClassVar[bool] + named_foreign_keys: ClassVar[bool] + table_class: ClassVar[type[Table]] + column_class: ClassVar[type[Column]] + index_class: ClassVar[type[DBIndex]] + fk_class: ClassVar[type[ForeignKey]] + provider: DBAPIProvider + tables: dict[Incomplete, Incomplete] + constraints: dict[Incomplete, Incomplete] + indent: str + command_separator: str + uppercase: bool + names: dict[Incomplete, Incomplete] + def __init__(schema, provider: DBAPIProvider, uppercase: bool = True) -> None: ... + def column_list(schema, columns): ... + def case(schema, s: str) -> str: ... + def add_table(schema, table_name, entity=None): ... + def order_tables_to_create(schema): ... + def generate_create_script(schema): ... + def create_tables(schema, provider: DBAPIProvider, connection) -> None: ... + def check_tables(schema, provider: DBAPIProvider, connection) -> None: ... + +class DBObject: + def create(table, provider, connection) -> None: ... + +class Table(DBObject): + typename: ClassVar[str] + def __init__(table, name, schema, entity=None) -> None: ... + def add_entity(table, entity) -> None: ... + def exists(table, provider: DBAPIProvider, connection, case_sensitive: bool = True): ... + def get_create_command(table): ... + def format_option(table, name, value): ... + def get_objects_to_create(table, created_tables: set[Table] | None = None) -> list[Table]: ... + def add_column(table, column_name, sql_type, converter, is_not_null: bool | None = None, sql_default=None): ... + def add_index(table, index_name, columns, is_pk: bool = False, is_unique=None, m2m: bool = False): ... + def add_foreign_key( + table, + fk_name, + child_columns, + parent_table, + parent_columns, + index_name=None, + on_delete: bool = False, + interleave: bool = False, + ): ... + +class Column: + auto_template: ClassVar[str] + def __init__(column, name, table, sql_type, converter, is_not_null: bool | None = None, sql_default=None) -> None: ... + def get_sql(column) -> str: ... + +class Constraint(DBObject): + schema: DBSchema + name: str | None + def __init__(constraint, name: str | None, schema: DBSchema) -> None: ... + +class DBIndex(Constraint): + typename: ClassVar[str] + def __init__(index, name: str | None, table, columns, is_pk: bool = False, is_unique=None) -> None: ... + def exists(index, provider, connection, case_sensitive: bool = True): ... + def get_sql(index) -> str: ... + def get_create_command(index): ... + +class ForeignKey(Constraint): + typename: ClassVar[str] + def __init__( + foreign_key, + name, + child_table, + child_columns, + parent_table, + parent_columns, + index_name, + on_delete, + interleave: bool = False, + ) -> None: ... + def exists(foreign_key, provider, connection, case_sensitive: bool = True): ... + def get_sql(foreign_key) -> str: ... + def get_create_command(foreign_key): ... diff --git a/stubs/pony/pony/orm/decompiling.pyi b/stubs/pony/pony/orm/decompiling.pyi new file mode 100644 index 000000000000..4fe1eb5a6280 --- /dev/null +++ b/stubs/pony/pony/orm/decompiling.pyi @@ -0,0 +1,135 @@ +import ast +from _typeshed import Incomplete + +class DecompileError(NotImplementedError): ... + +ast_cache: dict[int, tuple[Incomplete | None, set[Incomplete]]] + +def decompile(x): ... +def simplify(clause): ... + +class InvalidQuery(Exception): ... + +def binop(node_type): ... + +operator_mapping: dict[str, type[ast.cmpop]] + +def clean_assign(node): ... +def make_const(value): ... +def is_const(value) -> bool: ... +def unwrap_str(key) -> str: ... + +class Decompiler: + def __init__(decompiler, code, start: int = 0, end=None) -> None: ... + def get_instructions(decompiler) -> None: ... + def analyze_jumps(decompiler) -> None: ... + def decompile(decompiler) -> None: ... + def pop_items(decompiler, size): ... + def store(decompiler, node) -> None: ... + BINARY_POWER: Incomplete + BINARY_MULTIPLY: Incomplete + BINARY_DIVIDE: Incomplete + BINARY_FLOOR_DIVIDE: Incomplete + BINARY_ADD: Incomplete + BINARY_SUBTRACT: Incomplete + BINARY_LSHIFT: Incomplete + BINARY_RSHIFT: Incomplete + BINARY_AND: Incomplete + BINARY_XOR: Incomplete + BINARY_OR: Incomplete + BINARY_TRUE_DIVIDE = BINARY_DIVIDE # pyrefly: ignore [unknown-name] + BINARY_MODULO: Incomplete + def BINARY_OP(decompiler, opcode): ... + def BINARY_SLICE(decompiler): ... + def BINARY_SUBSCR(decompiler): ... + def BUILD_CONST_KEY_MAP(decompiler, length): ... + def BUILD_LIST(decompiler, size): ... + def BUILD_MAP(decompiler, length): ... + def BUILD_SET(decompiler, size): ... + def BUILD_SLICE(decompiler, size): ... + def BUILD_TUPLE(decompiler, size): ... + def BUILD_STRING(decompiler, count): ... + def CALL_FUNCTION(decompiler, argc, star=None, star2=None): ... + def CACHE(decompiler) -> None: ... + def CALL(decompiler, argc): ... + def CALL_FUNCTION_VAR(decompiler, argc): ... + def CALL_FUNCTION_KW(decompiler, argc): ... + def CALL_FUNCTION_VAR_KW(decompiler, argc): ... + def CALL_FUNCTION_EX(decompiler, argc): ... + def CALL_METHOD(decompiler, argc): ... + def COMPARE_OP(decompiler, op): ... + def COPY(decompiler, _) -> None: ... + def COPY_FREE_VARS(decompiler, n) -> None: ... + def CONTAINS_OP(decompiler, invert): ... + def DUP_TOP(decompiler): ... + def FOR_ITER(decompiler, endpos): ... + def FORMAT_VALUE(decompiler, flags): ... + def GEN_START(decompiler, kind) -> None: ... + def GET_ITER(decompiler) -> None: ... + def JUMP_IF_FALSE(decompiler, endpos): ... + JUMP_IF_FALSE_OR_POP = JUMP_IF_FALSE + def JUMP_IF_NOT_EXC_MATCH(decompiler, endpos) -> None: ... + def JUMP_IF_TRUE(decompiler, endpos): ... + JUMP_IF_TRUE_OR_POP = JUMP_IF_TRUE + def conditional_jump(decompiler, endpos, if_true): ... + def conditional_jump_old(decompiler, endpos, if_true): ... + def conditional_jump_new(decompiler, endpos, if_true): ... + def conditional_jump_none_impl(decompiler, endpos, negate): ... + def jump_if_none(decompiler, endpos): ... + def jump_if_not_none(decompiler, endpos): ... + def process_target(decompiler, pos, partial: bool = False) -> None: ... + def JUMP_FORWARD(decompiler, endpos): ... + def KW_NAMES(decompiler, kw_names) -> None: ... + def IS_OP(decompiler, invert): ... + def LIST_APPEND(decompiler, offset) -> None: ... + def LIST_EXTEND(decompiler, offset): ... + def LIST_TO_TUPLE(decompiler): ... + def LOAD_ATTR(decompiler, attr_name, push_null): ... + def LOAD_CLOSURE(decompiler, freevar): ... + def LOAD_CONST(decompiler, const_value): ... + def LOAD_DEREF(decompiler, freevar): ... + def LOAD_FAST(decompiler, varname): ... + LOAD_FAST_AND_CLEAR = LOAD_FAST + def LOAD_GLOBAL(decompiler, varname, push_null): ... + def LOAD_METHOD(decompiler, methname): ... + LOOKUP_METHOD = LOAD_METHOD + def LOAD_NAME(decompiler, varname): ... + def MAKE_CELL(decompiler, freevar) -> None: ... + def MAKE_CLOSURE(decompiler, argc): ... + def MAKE_FUNCTION(decompiler, argc): ... + POP_JUMP_BACKWARD_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_BACKWARD_IF_TRUE = JUMP_IF_TRUE + POP_JUMP_FORWARD_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_FORWARD_IF_TRUE = JUMP_IF_TRUE + POP_JUMP_IF_FALSE = JUMP_IF_FALSE + POP_JUMP_IF_TRUE = JUMP_IF_TRUE + POP_JUMP_BACKWARD_IF_NONE = jump_if_none + POP_JUMP_BACKWARD_IF_NOT_NONE = jump_if_not_none + POP_JUMP_FORWARD_IF_NONE = jump_if_none + POP_JUMP_FORWARD_IF_NOT_NONE = jump_if_not_none + def POP_TOP(decompiler) -> None: ... + def PRECALL(decompiler, argc) -> None: ... + def PUSH_NULL(decompiler) -> None: ... + def RETURN_VALUE(decompiler): ... + def RETURN_CONST(decompiler, val): ... + def RETURN_GENERATOR(decompiler) -> None: ... + def RESUME(decompiler, where) -> None: ... + def ROT_TWO(decompiler) -> None: ... + def ROT_THREE(decompiler) -> None: ... + def SETUP_LOOP(decompiler, endpos) -> None: ... + def STORE_ATTR(decompiler, attrname) -> None: ... + def STORE_DEREF(decompiler, freevar) -> None: ... + def STORE_FAST(decompiler, varname) -> None: ... + def STORE_MAP(decompiler) -> None: ... + def STORE_SUBSCR(decompiler) -> None: ... + def SWAP(decompiler, _) -> None: ... + def UNARY_POSITIVE(decompiler): ... + def UNARY_NEGATIVE(decompiler): ... + def UNARY_NOT(decompiler): ... + def UNARY_INVERT(decompiler): ... + def UNPACK_SEQUENCE(decompiler, count): ... + def YIELD_VALUE(decompiler, _=None): ... + +test_lines: str + +def test(test_line=None) -> None: ... diff --git a/stubs/pony/pony/orm/examples/__init__.pyi b/stubs/pony/pony/orm/examples/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/examples/alessandro_bug.pyi b/stubs/pony/pony/orm/examples/alessandro_bug.pyi new file mode 100644 index 000000000000..f8e36522aaf7 --- /dev/null +++ b/stubs/pony/pony/orm/examples/alessandro_bug.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete + +from pony.orm import * +from pony.orm.core import Database, Entity + +database: Database + +class User(Entity): + __slots__ = () + user_id: PrimaryKey + owned_pokemons: Incomplete + is_admin: Incomplete + is_banned: Incomplete + @staticmethod + def get_or_create(user_id: int) -> User: ... + @staticmethod + def get_by_id(user_id: int) -> User: ... + def catch_pokemon(self, pokemon: Pokemon): ... + def remove_pokemon(self, pokemon: Pokemon): ... + favorite_color: Incomplete + def set_favorite_color(self, color: tuple[Incomplete, ...]): ... + +class Pokemon(Entity): + __slots__ = () + name: Incomplete + pokemon_id: Incomplete + sprite: Incomplete + is_shiny: Incomplete + owner: Incomplete + spawned_chat_id: Incomplete + spawned_message_id: Incomplete + @property + def captured(self) -> bool: ... + def caught_by(self, user: User): ... + +class Chat(Entity): + __slots__ = () + chat_id: Incomplete + active: Incomplete + def activate(self) -> None: ... + def deactivate(self) -> None: ... + @staticmethod + def get_or_create(chat_id: int) -> Chat: ... + @staticmethod + def get_by_id(chat_id: int) -> Chat: ... + +def spawn_pokemon( + chat_id: int, message_id: int, pokemon_json: dict[Incomplete, Incomplete], is_shiny: bool = False +) -> Pokemon: ... +def get_spawned_pokemon(chat_id: int, message_id: int) -> Pokemon | None: ... +def setup() -> None: ... diff --git a/stubs/pony/pony/orm/examples/bottle_example.pyi b/stubs/pony/pony/orm/examples/bottle_example.pyi new file mode 100644 index 000000000000..5ea35b2aacd0 --- /dev/null +++ b/stubs/pony/pony/orm/examples/bottle_example.pyi @@ -0,0 +1,6 @@ +from pony.orm.examples.estore import * + +def all_products() -> str: ... +def show_product(id: int) -> str: ... +def edit_product(id: int) -> str: ... +def save_product(id: int) -> None: ... diff --git a/stubs/pony/pony/orm/examples/bug_ben.pyi b/stubs/pony/pony/orm/examples/bug_ben.pyi new file mode 100644 index 000000000000..3b7ecb074f0e --- /dev/null +++ b/stubs/pony/pony/orm/examples/bug_ben.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class ReconciledPayments(Entity): + id: Incomplete + foo: Incomplete + add_on_id: Incomplete + +class ContractAddOns(Entity): + id: Incomplete + reconciled_payments: Incomplete + +r1: ReconciledPayments +r2: ReconciledPayments +c1: ContractAddOns +old_val: Incomplete diff --git a/stubs/pony/pony/orm/examples/compositekeys.pyi b/stubs/pony/pony/orm/examples/compositekeys.pyi new file mode 100644 index 000000000000..1d48e601587f --- /dev/null +++ b/stubs/pony/pony/orm/examples/compositekeys.pyi @@ -0,0 +1,89 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Group(Entity): + __slots__ = () + dept: Incomplete + year: Incomplete + spec: Incomplete + students: Incomplete + courses: Incomplete + lessons: Incomplete + +class Department(Entity): + __slots__ = () + number: Incomplete + faculty: Incomplete + name: Incomplete + groups: Incomplete + teachers: Incomplete + +class Faculty(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + depts: Incomplete + +class Student(Entity): + __slots__ = () + name: Incomplete + group: Incomplete + dob: Incomplete + grades: Incomplete + +class Grade(Entity): + __slots__ = () + student: Incomplete + task: Incomplete + date: Incomplete + value: Incomplete + +class Task(Entity): + __slots__ = () + course: Incomplete + type: Incomplete + number: Incomplete + descr: Incomplete + grades: Incomplete + +class Course(Entity): + __slots__ = () + subject: Incomplete + semester: Incomplete + groups: Incomplete + tasks: Incomplete + lessons: Incomplete + teachers: Incomplete + +class Subject(Entity): + __slots__ = () + name: Incomplete + descr: Incomplete + courses: Incomplete + +class Room(Entity): + __slots__ = () + building: Incomplete + number: Incomplete + floor: Incomplete + schedules: Incomplete + +class Teacher(Entity): + __slots__ = () + dept: Incomplete + name: Incomplete + courses: Incomplete + lessons: Incomplete + +class Lesson(Entity): + __slots__ = () + groups: Incomplete + course: Incomplete + room: Incomplete + teacher: Incomplete + date: Incomplete + +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/demo.pyi b/stubs/pony/pony/orm/examples/demo.pyi new file mode 100644 index 000000000000..b2b31939bb9b --- /dev/null +++ b/stubs/pony/pony/orm/examples/demo.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Customer(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + email: Incomplete + orders: Incomplete + +class Order(Entity): + __slots__ = () + id: Incomplete + total_price: Incomplete + customer: Incomplete + items: Incomplete + +class Product(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + price: Incomplete + items: Incomplete + +class OrderItem(Entity): + __slots__ = () + quantity: Incomplete + order: Incomplete + product: Incomplete + +def populate_database() -> None: ... diff --git a/stubs/pony/pony/orm/examples/estore.pyi b/stubs/pony/pony/orm/examples/estore.pyi new file mode 100644 index 000000000000..8fdc234bab8d --- /dev/null +++ b/stubs/pony/pony/orm/examples/estore.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Customer(Entity): + __slots__ = () + email: Incomplete + password: Incomplete + name: Incomplete + country: Incomplete + address: Incomplete + cart_items: Incomplete + orders: Incomplete + +class Product(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + categories: Incomplete + description: Incomplete + picture: Incomplete + price: Incomplete + quantity: Incomplete + cart_items: Incomplete + order_items: Incomplete + +class CartItem(Entity): + __slots__ = () + quantity: Incomplete + customer: Incomplete + product: Incomplete + +class OrderItem(Entity): + __slots__ = () + quantity: Incomplete + price: Incomplete + order: Incomplete + product: Incomplete + +class Order(Entity): + __slots__ = () + id: Incomplete + state: Incomplete + date_created: Incomplete + date_shipped: Incomplete + date_delivered: Incomplete + total_price: Incomplete + customer: Incomplete + items: Incomplete + +class Category(Entity): + __slots__ = () + name: Incomplete + products: Incomplete + +CREATED: str +SHIPPED: str +DELIVERED: str +CANCELLED: str + +def populate_database() -> None: ... +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/inheritance1.pyi b/stubs/pony/pony/orm/examples/inheritance1.pyi new file mode 100644 index 000000000000..24518002ee50 --- /dev/null +++ b/stubs/pony/pony/orm/examples/inheritance1.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Person(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + dob: Incomplete + ssn: Incomplete + +class Student(Person): + __slots__ = () + group: Incomplete + mentor: Incomplete + attend_courses: Incomplete + +class Teacher(Person): + __slots__ = () + teach_courses: Incomplete + apprentices: Incomplete + salary: Incomplete + +class Assistant(Student, Teacher): + __slots__ = () + +class Professor(Teacher): + __slots__ = () + position: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + students: Incomplete + +class Course(Entity): + __slots__ = () + name: Incomplete + semester: Incomplete + students: Incomplete + teachers: Incomplete + +def populate_database() -> None: ... +def show_all_persons() -> None: ... diff --git a/stubs/pony/pony/orm/examples/numbers.pyi b/stubs/pony/pony/orm/examples/numbers.pyi new file mode 100644 index 000000000000..ab8105fc29c9 --- /dev/null +++ b/stubs/pony/pony/orm/examples/numbers.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Numbers(Entity): + __slots__ = () + id: Incomplete + int8: Incomplete + int16: Incomplete + int24: Incomplete + int32: Incomplete + int64: Incomplete + uint8: Incomplete + uint16: Incomplete + uint24: Incomplete + uint32: Incomplete + +def populate_database() -> None: ... +def test_data() -> None: ... diff --git a/stubs/pony/pony/orm/examples/session01.pyi b/stubs/pony/pony/orm/examples/session01.pyi new file mode 100644 index 000000000000..418f87b14dd5 --- /dev/null +++ b/stubs/pony/pony/orm/examples/session01.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Person(Entity): + name: str + age: int + +p1: Person +p2: Person +x: int +y: int +q: Incomplete diff --git a/stubs/pony/pony/orm/examples/university1.pyi b/stubs/pony/pony/orm/examples/university1.pyi new file mode 100644 index 000000000000..ced29c56889d --- /dev/null +++ b/stubs/pony/pony/orm/examples/university1.pyi @@ -0,0 +1,47 @@ +from _typeshed import Incomplete +from decimal import Decimal as Decimal + +from pony.orm.core import Database, Entity + +db: Database + +class Department(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + groups: Incomplete + courses: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + major: Incomplete + dept: Incomplete + students: Incomplete + +class Course(Entity): + __slots__ = () + name: Incomplete + semester: Incomplete + lect_hours: Incomplete + lab_hours: Incomplete + credits: Incomplete + dept: Incomplete + students: Incomplete + +class Student(Entity): + __slots__ = () + id: Incomplete + name: Incomplete + dob: Incomplete + tel: Incomplete + picture: Incomplete + gpa: Incomplete + group: Incomplete + courses: Incomplete + +params: dict[str, dict[str, str | bool] | dict[str, str | int]] + +def populate_database() -> None: ... +def print_students(students) -> None: ... +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/examples/university2.pyi b/stubs/pony/pony/orm/examples/university2.pyi new file mode 100644 index 000000000000..cc5baed9e4f0 --- /dev/null +++ b/stubs/pony/pony/orm/examples/university2.pyi @@ -0,0 +1,99 @@ +from _typeshed import Incomplete + +from pony.orm.core import Database, Entity + +db: Database + +class Faculty(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + departments: Incomplete + +class Department(Entity): + __slots__ = () + number: Incomplete + name: Incomplete + faculty: Incomplete + teachers: Incomplete + majors: Incomplete + groups: Incomplete + +class Group(Entity): + __slots__ = () + number: Incomplete + grad_year: Incomplete + department: Incomplete + lessons: Incomplete + students: Incomplete + +class Student(Entity): + __slots__ = () + name: Incomplete + scholarship: Incomplete + group: Incomplete + grades: Incomplete + +class Major(Entity): + __slots__ = () + name: Incomplete + department: Incomplete + courses: Incomplete + +class Subject(Entity): + __slots__ = () + name: Incomplete + courses: Incomplete + teachers: Incomplete + +class Course(Entity): + __slots__ = () + major: Incomplete + subject: Incomplete + semester: Incomplete + lect_hours: Incomplete + pract_hours: Incomplete + credit: Incomplete + lessons: Incomplete + grades: Incomplete + +class Lesson(Entity): + __slots__ = () + day_of_week: Incomplete + meeting_time: Incomplete + classroom: Incomplete + course: Incomplete + teacher: Incomplete + groups: Incomplete + +class Grade(Entity): + __slots__ = () + student: Incomplete + course: Incomplete + teacher: Incomplete + date: Incomplete + value: Incomplete + +class Teacher(Entity): + __slots__ = () + name: Incomplete + degree: Incomplete + department: Incomplete + subjects: Incomplete + lessons: Incomplete + grades: Incomplete + +class Building(Entity): + __slots__ = () + number: Incomplete + description: Incomplete + classrooms: Incomplete + +class Classroom(Entity): + __slots__ = () + building: Incomplete + number: Incomplete + description: Incomplete + lessons: Incomplete + +def test_queries() -> None: ... diff --git a/stubs/pony/pony/orm/integration/__init__.pyi b/stubs/pony/pony/orm/integration/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/orm/integration/bottle_plugin.pyi b/stubs/pony/pony/orm/integration/bottle_plugin.pyi new file mode 100644 index 000000000000..d8bf1727386c --- /dev/null +++ b/stubs/pony/pony/orm/integration/bottle_plugin.pyi @@ -0,0 +1,6 @@ +def is_allowed_exception(e: BaseException | None) -> bool: ... + +class PonyPlugin: + name: str + api: int + def apply(self, callback, route): ... diff --git a/stubs/pony/pony/orm/ormtypes.pyi b/stubs/pony/pony/orm/ormtypes.pyi new file mode 100644 index 000000000000..6ae9e0566dba --- /dev/null +++ b/stubs/pony/pony/orm/ormtypes.pyi @@ -0,0 +1,156 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import Any +from typing_extensions import Self + +NoneType: type[None] + +class LongStr(str): + lazy: bool + +LongUnicode = LongStr + +class SetType: + __slots__ = "item_type" + def __deepcopy__(self, memo) -> Self: ... + item_type: Incomplete + def __init__(self, item_type) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +class FuncType: + __slots__ = "func" + def __deepcopy__(self, memo) -> Self: ... + func: Incomplete + def __init__(self, func) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +class MethodType: + __slots__ = ("obj", "func") + def __deepcopy__(self, memo) -> Self: ... + obj: Incomplete + func: Incomplete + def __init__(self, method) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __hash__(self) -> int: ... + +raw_sql_cache: dict[str, Incomplete] + +def parse_raw_sql(sql: str): ... +def raw_sql(sql: str, result_type=None) -> RawSQL: ... + +class RawSQL: + def __deepcopy__(self, memo) -> None: ... + sql: str + result_type: Incomplete + def __init__( + self, sql: str, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None, result_type=None + ) -> None: ... + +class RawSQLType: + def __deepcopy__(self, memo) -> Self: ... + sql: str + items: Incomplete + types: Incomplete + result_type: Incomplete + def __init__(self, sql: str, items, types, result_type) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + +class QueryType: + query_key: Incomplete + translator: Incomplete + limit: Incomplete + offset: Incomplete + def __init__(self, query, limit=None, offset=None) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + +def normalize(value): ... +def normalize_type(t): ... + +coercions: Incomplete + +def coerce_types(t1, t2): ... +def are_comparable_types(t1, t2, op: str = "=="): ... + +class TrackedValue: + obj_ref: Incomplete + attr: Incomplete + def __init__(self, obj, attr) -> None: ... + @classmethod + def make(cls, obj, attr, value): ... + def get_untracked(self) -> None: ... + +def tracked_method(func): ... + +class TrackedDict(TrackedValue, dict[Incomplete, Incomplete]): + def __init__(self, obj, attr, value) -> None: ... + def __reduce__(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + def update(self, *args, **kwargs): ... + setdefault: Incomplete + pop: Incomplete + popitem: Incomplete + clear: Incomplete + def get_untracked(self): ... + +class TrackedList(TrackedValue, list[Incomplete]): + def __init__(self, obj, attr, value) -> None: ... + def __reduce__(self): ... + __setitem__: Incomplete + __delitem__: Incomplete + extend: Incomplete + append: Incomplete + pop: Incomplete + remove: Incomplete + insert: Incomplete + reverse: Incomplete + sort: Incomplete + clear: Incomplete + def get_untracked(self): ... + +def validate_item(item_type, item): ... + +class TrackedArray(TrackedList): + item_type: Incomplete + def __init__(self, obj, attr, value) -> None: ... + def extend(self, items) -> None: ... + def append(self, item) -> None: ... + def insert(self, index, item) -> None: ... + def __setitem__(self, index, item) -> None: ... + def __contains__(self, item) -> bool: ... + +class Json: + @classmethod + def default_empty_value(cls): ... + wrapped: Incomplete + def __init__(self, wrapped) -> None: ... + +class Array: + item_type: type | None + @classmethod + def default_empty_value(cls): ... + +class IntArray(Array): + item_type: type[int] + +class StrArray(Array): + item_type: type[str] + +class FloatArray(Array): + item_type: type[float] + +numeric_types: set[type] +comparable_types: set[type] +primitive_types: set[type] +function_types: set[type] +type_normalization_dict: dict[type, type] +array_types: dict[type, type[Array]] diff --git a/stubs/pony/pony/orm/serialization.pyi b/stubs/pony/pony/orm/serialization.pyi new file mode 100644 index 000000000000..b8acc580ce37 --- /dev/null +++ b/stubs/pony/pony/orm/serialization.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Iterable +from datetime import date, datetime +from decimal import Decimal + +from pony.orm.core import Database, Entity + +class Bag: + database: Database + session_cache: Incomplete + entity_configs: dict[Entity, tuple[Incomplete, bool]] + objects: defaultdict[type[Entity], set[Entity]] + vars: dict[Incomplete, Incomplete] + dicts: defaultdict[Incomplete, dict[Incomplete, Incomplete]] + def __init__(bag, database: Database) -> None: ... + def config( + bag, + entity: Entity, + only=None, + exclude=None, + with_collections: bool = True, + with_lazy: bool = False, + related_objects: bool = True, + ) -> tuple[Incomplete, bool]: ... + def put(bag, x: Entity | Iterable[Entity]) -> None: ... + def to_dict(bag): ... + def to_json(bag) -> str: ... + +def to_dict(objects): ... +def to_json(objects) -> str: ... +def json_converter(x: datetime | date | Decimal) -> str: ... diff --git a/stubs/pony/pony/orm/sqlbuilding.pyi b/stubs/pony/pony/orm/sqlbuilding.pyi new file mode 100644 index 000000000000..e123d2be9993 --- /dev/null +++ b/stubs/pony/pony/orm/sqlbuilding.pyi @@ -0,0 +1,159 @@ +import types +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar + +class AstError(Exception): ... + +class Param: + __slots__ = ("style", "id", "paramkey", "converter", "optimistic") + style: Incomplete + id: Incomplete + paramkey: Incomplete + converter: Incomplete + optimistic: bool + def __init__(param, paramstyle, paramkey, converter=None, optimistic: bool = False) -> None: ... + def eval(param, values): ... + +class CompositeParam(Param): + __slots__ = ("items", "func") + items: Iterable[Param | Value] + func: Incomplete + def __init__(param, paramstyle, paramkey, items: Iterable[Param | Value], func) -> None: ... + def eval(param, values): ... + +class Value: + __slots__ = ("paramstyle", "value") + paramstyle: Incomplete + value: Incomplete + def __init__(self, paramstyle, value) -> None: ... + def quote_str(self, s: str) -> str: ... + +def flat(tree): ... +def flat_conditions(conditions): ... +def join(delimiter, items): ... +def move_conditions_from_inner_join_to_where(sections): ... +def make_binary_op(symbol, default_parentheses: bool = False): ... +def make_unary_func(symbol): ... +def indentable(method): ... + +class SQLBuilder: + dialect: ClassVar[str | None] + param_class: ClassVar[type[Param]] + composite_param_class: ClassVar[type[CompositeParam]] + value_class: ClassVar[type[Value]] + indent_spaces: ClassVar[str] + least_func_name: ClassVar[str] + greatest_func_name: ClassVar[str] + def __init__(builder, provider, ast) -> None: ... + def __call__(builder, ast): ... + def INSERT(builder, table_name, columns, values, returning=None): ... + def DEFAULT(builder): ... + def UPDATE(builder, table_name, pairs, where=None): ... + def DELETE(builder, alias, from_ast, where=None): ... + def SELECT(builder, *sections): ... + def SELECT_FOR_UPDATE(builder, nowait, skip_locked, *sections): ... + def EXISTS(builder, *sections): ... + def NOT_EXISTS(builder, *sections): ... + def ALL(builder, *expr_list): ... + def DISTINCT(builder, *expr_list): ... + def AGGREGATES(builder, *expr_list): ... + def AS(builder, expr, alias): ... + def compound_name(builder, name_parts): ... + def sql_join(builder, join_type, sources): ... + def FROM(builder, *sources): ... + def INNER_JOIN(builder, *sources): ... + def LEFT_JOIN(builder, *sources): ... + def WHERE(builder, *conditions): ... + def HAVING(builder, *conditions): ... + def GROUP_BY(builder, *expr_list): ... + def UNION(builder, kind, *sections): ... + def INTERSECT(builder, *sections): ... + def EXCEPT(builder, *sections): ... + def ORDER_BY(builder, *order_list): ... + def DESC(builder, expr): ... + def LIMIT(builder, limit, offset=None): ... + def COLUMN(builder, table_alias, col_name): ... + def PARAM(builder, paramkey, converter=None, optimistic: bool = False): ... + def make_param(builder, param_class, paramkey, *args): ... + def make_composite_param(builder, paramkey, items, func): ... + def STAR(builder, table_alias): ... + def ROW(builder, *items): ... + def VALUE(builder, value): ... + def AND(builder, *cond_list): ... + def OR(builder, *cond_list): ... + def NOT(builder, condition): ... + def POW(builder, expr1, expr2): ... + EQ: Incomplete + NE: Incomplete + LT: Incomplete + LE: Incomplete + GT: Incomplete + GE: Incomplete + ADD: Incomplete + SUB: Incomplete + MUL: Incomplete + DIV: Incomplete + FLOORDIV: Incomplete + def MOD(builder, a, b): ... + def FLOAT_EQ(builder, a, b): ... + def FLOAT_NE(builder, a, b): ... + def CONCAT(builder, *args): ... + def NEG(builder, expr): ... + def IS_NULL(builder, expr): ... + def IS_NOT_NULL(builder, expr): ... + def LIKE(builder, expr, template, escape=None): ... + def NOT_LIKE(builder, expr, template, escape=None): ... + def BETWEEN(builder, expr1, expr2, expr3): ... + def NOT_BETWEEN(builder, expr1, expr2, expr3): ... + def IN(builder, expr1, x): ... + def NOT_IN(builder, expr1, x): ... + def COUNT(builder, distinct, *expr_list): ... + def SUM(builder, distinct, expr): ... + def AVG(builder, distinct, expr): ... + def GROUP_CONCAT(builder, distinct, expr, sep=None): ... + UPPER: Incomplete + LOWER: Incomplete + LENGTH: Incomplete + ABS: Incomplete + def COALESCE(builder, *args): ... + def MIN(builder, distinct, *args): ... + def MAX(builder, distinct, *args): ... + def SUBSTR(builder, expr, start, len=None): ... + def STRING_SLICE(builder, expr, start, stop): ... + def CASE(builder, expr, cases, default=None): ... + def IF(builder, cond, then, else_): ... + def TRIM(builder, expr, chars=None): ... + def LTRIM(builder, expr, chars=None): ... + def RTRIM(builder, expr, chars=None): ... + def REPLACE(builder, str, from_, to): ... + def TO_INT(builder, expr): ... + def TO_STR(builder, expr): ... + def TO_REAL(builder, expr): ... + def TODAY(builder): ... + def NOW(builder): ... + def DATE(builder, expr): ... + def YEAR(builder, expr): ... + def MONTH(builder, expr): ... + def DAY(builder, expr): ... + def HOUR(builder, expr): ... + def MINUTE(builder, expr): ... + def SECOND(builder, expr): ... + def RANDOM(builder): ... + def RAWSQL(builder, sql): ... + def build_json_path(builder, path): ... + @classmethod + def eval_json_path(cls, values: Iterable[int | str | types.EllipsisType | slice]) -> str: ... + def JSON_QUERY(builder, expr, path) -> None: ... + def JSON_VALUE(builder, expr, path, type) -> None: ... + def JSON_NONZERO(builder, expr) -> None: ... + def JSON_CONCAT(builder, left, right) -> None: ... + def JSON_CONTAINS(builder, expr, path, key) -> None: ... + def JSON_ARRAY_LENGTH(builder, value) -> None: ... + def JSON_PARAM(builder, expr): ... + def ARRAY_INDEX(builder, col, index) -> None: ... + def ARRAY_CONTAINS(builder, key, not_in, col) -> None: ... + def ARRAY_SUBSET(builder, array1, not_in, array2) -> None: ... + def ARRAY_LENGTH(builder, array) -> None: ... + def ARRAY_SLICE(builder, array, start, stop) -> None: ... + def MAKE_ARRAY(builder, *items) -> None: ... diff --git a/stubs/pony/pony/orm/sqlsymbols.pyi b/stubs/pony/pony/orm/sqlsymbols.pyi new file mode 100644 index 000000000000..237991537b91 --- /dev/null +++ b/stubs/pony/pony/orm/sqlsymbols.pyi @@ -0,0 +1,88 @@ +from typing import Final + +symbols: Final[list[str]] +SELECT: Final = "SELECT" +INSERT: Final = "INSERT" +UPDATE: Final = "UPDATE" +DELETE: Final = "DELETE" +SELECT_FOR_UPDATE: Final = "SELECT_FOR_UPDATE" +FROM: Final = "FROM" +INNER_JOIN: Final = "INNER_JOIN" +LEFT_JOIN: Final = "LEFT_JOIN" +WHERE: Final = "WHERE" +GROUP_BY: Final = "GROUP_BY" +HAVING: Final = "HAVING" +UNION: Final = "UNION" +INTERSECT: Final = "INTERSECT" +EXCEPT: Final = "EXCEPT" +ORDER_BY: Final = "ORDER_BY" +LIMIT: Final = "LIMIT" +ASC: Final = "ASC" +DESC: Final = "DESC" +DISTINCT: Final = "DISTINCT" +ALL: Final = "ALL" +AGGREGATES: Final = "AGGREGATES" +AS: Final = "AS" +COUNT: Final = "COUNT" +SUM: Final = "SUM" +MIN: Final = "MIN" +MAX: Final = "MAX" +AVG: Final = "AVG" +TABLE: Final = "TABLE" +COLUMN: Final = "COLUMN" +PARAM: Final = "PARAM" +VALUE: Final = "VALUE" +AND: Final = "AND" +OR: Final = "OR" +NOT: Final = "NOT" +EQ: Final = "EQ" +NE: Final = "NE" +LT: Final = "LT" +LE: Final = "LE" +GT: Final = "GT" +GE: Final = "GE" +IS_NULL: Final = "IS_NULL" +IS_NOT_NULL: Final = "IS_NOT_NULL" +LIKE: Final = "LIKE" +NOT_LIKE: Final = "NOT_LIKE" +BETWEEN: Final = "BETWEEN" +NOT_BETWEEN: Final = "NOT_BETWEEN" +IN: Final = "IN" +NOT_IN: Final = "NOT_IN" +EXISTS: Final = "EXISTS" +NOT_EXISTS: Final = "NOT_EXISTS" +ROW: Final = "ROW" +ADD: Final = "ADD" +SUB: Final = "SUB" +MUL: Final = "MUL" +DIV: Final = "DIV" +POW: Final = "POW" +NEG: Final = "NEG" +ABS: Final = "ABS" +UPPER: Final = "UPPER" +LOWER: Final = "LOWER" +CONCAT: Final = "CONCAT" +STRIN: Final = "STRIN" +SUBSTR: Final = "SUBSTR" +LENGTH: Final = "LENGTH" +TRIM: Final = "TRIM" +LTRIM: Final = "LTRIM" +RTRIM: Final = "RTRIM" +REPLACE: Final = "REPLACE" +CASE: Final = "CASE" +COALESCE: Final = "COALESCE" +TO_INT: Final = "TO_INT" +RANDOM: Final = "RANDOM" +DATE: Final = "DATE" +YEAR: Final = "YEAR" +MONTH: Final = "MONTH" +DAY: Final = "DAY" +HOUR: Final = "HOUR" +MINUTE: Final = "MINUTE" +SECOND: Final = "SECOND" +TODAY: Final = "TODAY" +NOW: Final = "NOW" +DATE_ADD: Final = "DATE_ADD" +DATE_SUB: Final = "DATE_SUB" +DATETIME_ADD: Final = "DATETIME_ADD" +DATETIME_SUB: Final = "DATETIME_SUB" diff --git a/stubs/pony/pony/orm/sqltranslation.pyi b/stubs/pony/pony/orm/sqltranslation.pyi new file mode 100644 index 000000000000..e2454f8d81df --- /dev/null +++ b/stubs/pony/pony/orm/sqltranslation.pyi @@ -0,0 +1,773 @@ +import ast +import itertools +import re +import sys +import types +from _typeshed import Incomplete +from collections.abc import Generator, Iterable, Sequence +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from random import random +from typing import Any, ClassVar +from typing_extensions import Never, Self + +from pony.orm import core +from pony.orm.asttranslation import ASTTranslator +from pony.orm.ormtypes import raw_sql +from pony.utils import between, coalesce, concat, localbase + +NoneType: type[None] + +def check_comparable(left_monad: Monad, right_monad: Monad, op: str = "==") -> None: ... + +class IncomparableTypesError(TypeError): + type1: Incomplete + type2: Incomplete + def __init__(exc, type1, type2) -> None: ... + +def sqland(items): ... +def sqlor(items): ... +def join_tables(alias1, alias2, columns1, columns2): ... +def type2str(t) -> str: ... + +class Local(localbase): + translators: list[SQLTranslator] + def __init__(local) -> None: ... + @property + def translator(self) -> SQLTranslator: ... + +translator_counter: itertools.count[int] +local: Local + +class SQLTranslator(ASTTranslator): + dialect: ClassVar[str | None] + row_value_syntax: ClassVar[bool] + json_path_wildcard_syntax: ClassVar[bool] + json_values_are_comparable: ClassVar[bool] + rowid_support: ClassVar[bool] + registered_functions: dict[types.FunctionType, type[FuncMonad]] + def __enter__(translator) -> None: ... + def __exit__(translator, exc_type, exc_val, exc_tb) -> None: ... + def default_post(translator, node) -> None: ... + def dispatch(translator, node): ... + def dispatch_external(translator, node) -> None: ... + def call(translator, method, node): ... + def deepcopy(translator): ... + def __init__( + translator, + tree, + parent_translator, + code_key=None, + filter_num=None, + extractors=None, + vars=None, + vartypes=None, + left_join: bool = False, + optimize=None, + ) -> None: ... + def init( + translator, + tree, + parent_translator, + code_key=None, + filter_num=None, + extractors=None, + vars=None, + vartypes=None, + left_join: bool = False, + optimize=None, + ): ... + @property + def namespace(translator): ... + def can_be_optimized(translator): ... + def process_query_qual( + translator, prev_translator, prev_limit, prev_offset, names, try_extend_prev_query: bool = False + ) -> None: ... + def construct_subquery_ast( + translator, limit=None, offset=None, aliases=None, star=None, distinct=None, is_not_null_checks: bool = False + ): ... + def construct_sql_ast( + translator, + limit=None, + offset=None, + distinct=None, + aggr_func_name=None, + aggr_func_distinct=None, + sep=None, + for_update: bool = False, + nowait: bool = False, + skip_locked: bool = False, + is_not_null_checks: bool = False, + ): ... + def construct_delete_sql_ast(translator): ... + def get_used_attrs(translator): ... + def without_order(translator) -> Self: ... + def order_by_numbers(translator, numbers: Iterable[int]) -> Self: ... + def order_by_attributes(translator, attrs: Iterable[core.DescWrapper | core.Attribute]) -> Self: ... + def apply_kwfilters(translator, filterattrs, original_names: bool = False) -> Self: ... + def apply_lambda( + translator, func_id, filter_num, order_by, func_ast, argnames, original_names, extractors, vars, vartypes + ) -> Self: ... + def preGeneratorExp(translator, node: ast.GeneratorExp) -> QuerySetMonad: ... + def postExpr(translator, node: ast.Expr): ... + def preCompare(translator, node: ast.Compare): ... + def postConstant(translator, node: ast.Constant) -> ConstMonad: ... + if sys.version_info >= (3, 14): + def postNameConstant(translator, node: ast.Constant): ... + def postNum(translator, node: ast.Constant) -> ConstMonad: ... + def postStr(translator, node: ast.Constant) -> ConstMonad: ... + def postBytes(translator, node: ast.Constant) -> ConstMonad: ... + else: + def postNameConstant(translator, node: ast.NameConstant): ... + def postNum(translator, node: ast.Num) -> ConstMonad: ... + def postStr(translator, node: ast.Str) -> ConstMonad: ... + def postBytes(translator, node: ast.Bytes) -> ConstMonad: ... + + def postList(translator, node: ast.List) -> ListMonad: ... + def postTuple(translator, node: ast.Tuple) -> ListMonad: ... + def postName(translator, node: ast.Name) -> Monad: ... + def resolve_name(translator, name) -> Monad: ... + def postAdd(translator, node: ast.Add): ... + def postSub(translator, node: ast.Sub): ... + def postMult(translator, node: ast.Mult): ... + def postMatMult(translator, node: ast.MatMult) -> Never: ... + def postDiv(translator, node: ast.Div): ... + def postFloorDiv(translator, node: ast.FloorDiv): ... + def postMod(translator, node: ast.Mod): ... + def postLShift(translator, node: ast.LShift) -> Never: ... + def postRShift(translator, node: ast.RShift) -> Never: ... + def postPow(translator, node: ast.Pow): ... + def postUSub(translator, node: ast.USub): ... + def postAttribute(translator, node: ast.Attribute): ... + def postAnd(translator, node: ast.And) -> AndMonad: ... + def postOr(translator, node: ast.Or) -> OrMonad: ... + def postBitOr(translator, node: ast.BitOr): ... + def postBitAnd(translator, node: ast.BitAnd): ... + def postBitXor(translator, node: ast.BitXor): ... + def postNot(translator, node: ast.Not): ... + def preCall(translator, node: ast.Call): ... + def postCall(translator, node: ast.Call): ... + def postkeyword(translator, node: ast.keyword) -> None: ... + def postSubscript(translator, node: ast.Subscript): ... + def postSlice(translator, node: ast.Slice) -> None: ... + def postIndex(translator, node: ast.Index): ... + def postIfExp(translator, node: ast.IfExp) -> ExprMonad: ... + def postJoinedStr(translator, node: ast.JoinedStr) -> StringExprMonad: ... + def postFormattedValue(translator, node: ast.FormattedValue): ... + +def combine_limit_and_offset(limit, offset, limit2, offset2) -> tuple[Incomplete, Incomplete]: ... +def coerce_monads(m1, m2, for_comparison: bool = False): ... + +max_alias_length: int + +class SqlQuery: + translator: Incomplete + parent_sqlquery: SqlQuery | None + left_join: bool + from_ast: list[Incomplete] + conditions: list[Incomplete] + outer_conditions: list[Incomplete] + tablerefs: dict[Incomplete, Incomplete] + alias_counters: dict[Incomplete, Incomplete] + expr_counter: itertools.count[int] + used_from_subquery: bool + def __init__(sqlquery, translator, parent_sqlquery: SqlQuery | None = None, left_join: bool = False) -> None: ... + def get_tableref(sqlquery, name_path): ... + def add_tableref(sqlquery, name_path, parent_tableref, attr) -> JoinedTableRef: ... + def make_alias(sqlquery, name: str) -> str: ... + def join_table(sqlquery, parent_alias, alias, table_name, join_cond) -> None: ... + +class TableRef: + sqlquery: SqlQuery + alias: str + name_path: str + entity: Incomplete + joined: bool + can_affect_distinct: bool + used_attrs: set[Incomplete] + def __init__(tableref, sqlquery: SqlQuery, name: str, entity) -> None: ... + def make_join(tableref, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class ExprTableRef(TableRef): + def __init__(tableref, sqlquery: SqlQuery, name: str, subquery_ast, expr_names, expr_aliases) -> None: ... + def make_join(tableref, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class StarTableRef(TableRef): + def __init__(tableref, sqlquery: SqlQuery, name: str, entity, subquery_ast) -> None: ... + def make_join(tableref, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class ExprJoinedTableRef: + def __init__(tableref, sqlquery: SqlQuery, parent_tableref, parent_columns, name, entity) -> None: ... + def make_join(tableref, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +class JoinedTableRef: + sqlquery: SqlQuery + name_path: str + var_name: str | None + alias: str | None + optimized: bool | None + parent_tableref: Incomplete + attr: Incomplete + entity: Incomplete + joined: bool + can_affect_distinct: bool + used_attrs: set[Incomplete] + def __init__(tableref, sqlquery: SqlQuery, name_path: str, parent_tableref, attr) -> None: ... + def make_join(tableref, pk_only: bool = False) -> tuple[str, Incomplete]: ... + +def wrap_monad_method(cls_name: str, func: types.FunctionType): ... + +class MonadMeta(type): + def __new__(meta, cls_name: str, bases: tuple[type, ...], cls_dict: dict[str, Any]): ... + +class MonadMixin(metaclass=MonadMeta): ... + +class Monad(metaclass=MonadMeta): + disable_distinct: ClassVar[bool] + disable_ordering: ClassVar[bool] + node: Incomplete + translator: SQLTranslator + type: Incomplete + nullable: bool + def __init__(monad, type, nullable: bool = True) -> None: ... + def mixin_init(monad) -> None: ... + def to_single_cell_value(monad): ... + def cmp(monad, op, monad2): ... + def contains(monad, item, not_in: bool = False) -> None: ... + def nonzero(monad): ... + def negate(monad): ... + def getattr(monad, attrname): ... + def len(monad) -> None: ... + def count(monad, distinct=None): ... + def aggregate(monad, func_name, distinct=None, sep=None): ... + def __call__(monad, *args, **kwargs) -> None: ... + def __getitem__(monad, key) -> None: ... + def __add__(monad, monad2) -> None: ... + def __sub__(monad, monad2) -> None: ... + def __mul__(monad, monad2) -> None: ... + def __truediv__(monad, monad2) -> None: ... + def __floordiv__(monad, monad2) -> None: ... + def __pow__(monad, monad2) -> None: ... + def __neg__(monad) -> None: ... + def __or__(monad, monad2) -> None: ... + def __and__(monad, monad2) -> None: ... + def __xor__(monad, monad2) -> None: ... + def abs(monad) -> None: ... + def cast_from_json(monad, type) -> None: ... + def to_int(monad): ... + def to_str(monad): ... + def to_real(monad): ... + +def distinct_from_monad(distinct, default=None): ... + +class RawSQLMonad(Monad): + def __init__(monad, rawtype, varkey, nullable: bool = True) -> None: ... + def contains(monad, item, not_in: bool = False): ... + def nonzero(monad): ... + def getsql(monad, sqlquery=None): ... + +typeerror_re_1: re.Pattern[str] +typeerror_re_2: re.Pattern[str] + +def reraise_improved_typeerror(exc: Exception, func_name: str | tuple[str, ...], orig_func_name: str) -> Never: ... +def raise_forgot_parentheses(monad: Monad) -> Never: ... + +class MethodMonad(Monad): + def __init__(monad, parent, attrname) -> None: ... + def getattr(monad, attrname) -> None: ... + def __call__(monad, *args, **kwargs): ... + def contains(monad, item, not_in: bool = False) -> None: ... + def nonzero(monad) -> None: ... + def negate(monad) -> None: ... + def aggregate(monad, func_name, distinct=None, sep=None) -> None: ... + def __getitem__(monad, key) -> None: ... + def __add__(monad, monad2) -> None: ... + def __sub__(monad, monad2) -> None: ... + def __mul__(monad, monad2) -> None: ... + def __truediv__(monad, monad2) -> None: ... + def __floordiv__(monad, monad2) -> None: ... + def __pow__(monad, monad2) -> None: ... + def __neg__(monad) -> None: ... + def abs(monad) -> None: ... + +class EntityMonad(Monad): + def __init__(monad, entity) -> None: ... + def __getitem__(monad, *args) -> None: ... + +class ListMonad(Monad): + def __init__(monad, items) -> None: ... + def contains(monad, x, not_in: bool = False): ... + def getsql(monad, sqlquery=None): ... + +class BufferMixin(MonadMixin): ... +class UuidMixin(MonadMixin): ... + +def make_numeric_binop(op, sqlop): ... + +class NumericMixin(MonadMixin): + def mixin_init(monad) -> None: ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + __mod__: Incomplete + __and__: Incomplete + __or__: Incomplete + __xor__: Incomplete + def __pow__(monad, monad2): ... + def __neg__(monad): ... + def abs(monad): ... + def nonzero(monad): ... + def negate(monad): ... + +def numeric_attr_factory(name): ... +def make_datetime_binop(op, sqlop): ... + +class DateMixin(MonadMixin): + def mixin_init(monad) -> None: ... + attr_year: Incomplete + attr_month: Incomplete + attr_day: Incomplete + def __add__(monad, other): ... + def __sub__(monad, other): ... + +class TimeMixin(MonadMixin): + def mixin_init(monad) -> None: ... + attr_hour: Incomplete + attr_minute: Incomplete + attr_second: Incomplete + +class TimedeltaMixin(MonadMixin): + def mixin_init(monad) -> None: ... + +class DatetimeMixin(DateMixin): + def mixin_init(monad) -> None: ... + def call_date(monad): ... + attr_hour: Incomplete + attr_minute: Incomplete + attr_second: Incomplete + def __add__(monad, other): ... + def __sub__(monad, other): ... + +def make_string_binop(op, sqlop): ... +def make_string_func(sqlop): ... + +class StringMixin(MonadMixin): + def mixin_init(monad) -> None: ... + __add__: Incomplete + def __getitem__(monad, index): ... + def negate(monad): ... + def nonzero(monad): ... + def len(monad): ... + def contains(monad, item, not_in: bool = False): ... + call_upper: Incomplete + call_lower: Incomplete + def call_startswith(monad, arg): ... + def call_endswith(monad, arg): ... + def strip(monad, chars, strip_type): ... + def call_strip(monad, chars=None): ... + def call_lstrip(monad, chars=None): ... + def call_rstrip(monad, chars=None): ... + +class JsonMixin: + disable_distinct: ClassVar[bool] + disable_ordering: ClassVar[bool] + def mixin_init(monad) -> None: ... + def get_path(monad): ... + def __getitem__(monad, key): ... + def contains(monad, key, not_in: bool = False): ... + def __or__(monad, other): ... + def len(monad): ... + def cast_from_json(monad, type): ... + def nonzero(monad): ... + +class ArrayMixin(MonadMixin): + def contains(monad, key, not_in: bool = False): ... + def len(monad): ... + def nonzero(monad): ... + def __getitem__(monad, index): ... + +class ObjectMixin(MonadMixin): + def mixin_init(monad) -> None: ... + def negate(monad): ... + def nonzero(monad): ... + def getattr(monad, attrname): ... + def requires_distinct(monad, joined: bool = False): ... + +class ObjectIterMonad(ObjectMixin, Monad): + def __init__(monad, tableref, entity) -> None: ... + def getsql(monad, sqlquery=None): ... + def requires_distinct(monad, joined: bool = False): ... + +class AttrMonad(Monad): + @staticmethod + def new(parent, attr, *args, **kwargs) -> AttrMonad: ... + def __new__(cls, parent, attr): ... + def __init__(monad, parent, attr) -> None: ... + def getsql(monad, sqlquery=None): ... + +class ObjectAttrMonad(ObjectMixin, AttrMonad): + def __init__(monad, parent, attr) -> None: ... + +class StringAttrMonad(StringMixin, AttrMonad): ... +class NumericAttrMonad(NumericMixin, AttrMonad): ... +class DateAttrMonad(DateMixin, AttrMonad): ... +class TimeAttrMonad(TimeMixin, AttrMonad): ... +class TimedeltaAttrMonad(TimedeltaMixin, AttrMonad): ... +class DatetimeAttrMonad(DatetimeMixin, AttrMonad): ... +class BufferAttrMonad(BufferMixin, AttrMonad): ... +class UuidAttrMonad(UuidMixin, AttrMonad): ... +class JsonAttrMonad(JsonMixin, AttrMonad): ... +class ArrayAttrMonad(ArrayMixin, AttrMonad): ... + +class ParamMonad(Monad): + @staticmethod + def new(t, paramkey) -> ParamMonad: ... + def __new__(cls, *args, **kwargs): ... + def __init__(monad, t, paramkey) -> None: ... + def getsql(monad, sqlquery=None): ... + +class ObjectParamMonad(ObjectMixin, ParamMonad): + def __init__(monad, entity, paramkey) -> None: ... + def getsql(monad, sqlquery=None): ... + def requires_distinct(monad, joined: bool = False) -> None: ... + +class StringParamMonad(StringMixin, ParamMonad): ... +class NumericParamMonad(NumericMixin, ParamMonad): ... +class DateParamMonad(DateMixin, ParamMonad): ... +class TimeParamMonad(TimeMixin, ParamMonad): ... +class TimedeltaParamMonad(TimedeltaMixin, ParamMonad): ... +class DatetimeParamMonad(DatetimeMixin, ParamMonad): ... +class BufferParamMonad(BufferMixin, ParamMonad): ... +class UuidParamMonad(UuidMixin, ParamMonad): ... + +class ArrayParamMonad(ArrayMixin, ParamMonad): + def __init__(monad, t, paramkey, list_monad=None) -> None: ... + def contains(monad, key, not_in: bool = False): ... + +class JsonParamMonad(JsonMixin, ParamMonad): + def getsql(monad, sqlquery=None): ... + +class ExprMonad(Monad): + @staticmethod + def new(t, sql, nullable: bool = True) -> ExprMonad: ... + def __new__(cls, *args, **kwargs): ... + def __init__(monad, type, sql, nullable: bool = True) -> None: ... + def getsql(monad, sqlquery=None): ... + +class ObjectExprMonad(ObjectMixin, ExprMonad): + def getsql(monad, sqlquery=None): ... + +class StringExprMonad(StringMixin, ExprMonad): ... +class NumericExprMonad(NumericMixin, ExprMonad): ... +class DateExprMonad(DateMixin, ExprMonad): ... +class TimeExprMonad(TimeMixin, ExprMonad): ... +class TimedeltaExprMonad(TimedeltaMixin, ExprMonad): ... +class DatetimeExprMonad(DatetimeMixin, ExprMonad): ... +class JsonExprMonad(JsonMixin, ExprMonad): ... +class ArrayExprMonad(ArrayMixin, ExprMonad): ... + +class JsonItemMonad(JsonMixin, Monad): # pyrefly: ignore [inconsistent-inheritance] + def __init__(monad, parent, key) -> None: ... + def get_path(monad): ... + def to_int(monad): ... + def to_str(monad): ... + def to_real(monad): ... + def cast_from_json(monad, type): ... + def getsql(monad): ... + +class ConstMonad(Monad): + @staticmethod + def new(value) -> ConstMonad: ... + def __new__(cls, value): ... + def __init__(monad, value) -> None: ... + def getsql(monad, sqlquery=None): ... + +class NoneMonad(ConstMonad): + type = NoneType + def __new__(cls, value=None): ... + def __init__(monad, value=None) -> None: ... + def cmp(monad, op, monad2): ... + def contains(monad, item, not_in: bool = False): ... + def nonzero(monad): ... + def negate(monad): ... + def getattr(monad, attrname): ... + def len(monad): ... + def count(monad, distinct=None): ... + def aggregate(monad, func_name, distinct=None, sep=None): ... + def __call__(monad, *args, **kwargs): ... + def __getitem__(monad, key): ... + def __add__(monad, monad2): ... + def __sub__(monad, monad2): ... + def __mul__(monad, monad2): ... + def __truediv__(monad, monad2): ... + def __floordiv__(monad, monad2): ... + def __pow__(monad, monad2): ... + def __neg__(monad): ... + def __or__(monad, monad2): ... + def __and__(monad, monad2): ... + def __xor__(monad, monad2): ... + def abs(monad): ... + def to_int(monad): ... + def to_str(monad): ... + def to_real(monad): ... + +class EllipsisMonad(ConstMonad): ... + +class StringConstMonad(StringMixin, ConstMonad): + def len(monad): ... + +class JsonConstMonad(JsonMixin, ConstMonad): ... +class BufferConstMonad(BufferMixin, ConstMonad): ... +class NumericConstMonad(NumericMixin, ConstMonad): ... +class DateConstMonad(DateMixin, ConstMonad): ... +class TimeConstMonad(TimeMixin, ConstMonad): ... +class TimedeltaConstMonad(TimedeltaMixin, ConstMonad): ... +class DatetimeConstMonad(DatetimeMixin, ConstMonad): ... + +class BoolMonad(Monad): + def __init__(monad, nullable: bool = True) -> None: ... + def nonzero(monad): ... + +sql_negation: dict[str, str] + +class BoolExprMonad(BoolMonad): + def __init__(monad, sql, nullable: bool = True) -> None: ... + def getsql(monad, sqlquery=None): ... + def negate(monad): ... + +cmp_ops: dict[str, str] +cmp_negate: dict[str, str] + +class CmpMonad(BoolMonad): + EQ: str + NE: str + def __init__(monad, op: str, left, right) -> None: ... + def negate(monad): ... + def getsql(monad, sqlquery=None): ... + +class LogicalBinOpMonad(BoolMonad): + def __init__(monad, operands) -> None: ... + def getsql(monad, sqlquery=None): ... + +class AndMonad(LogicalBinOpMonad): + binop: str + +class OrMonad(LogicalBinOpMonad): + binop: str + +class NotMonad(BoolMonad): + def __init__(monad, operand) -> None: ... + def negate(monad): ... + def getsql(monad, sqlquery=None): ... + +class HybridFuncMonad(Monad): + def __init__(monad, func_type, func_name, *params) -> None: ... + def __call__(monad, *args, **kwargs): ... + +class HybridMethodMonad(HybridFuncMonad): + def __init__(monad, parent, attrname, func) -> None: ... + +registered_functions: dict[types.FunctionType, type[FuncMonad]] + +class FuncMonadMeta(MonadMeta): + def __new__(meta, cls_name: str, bases: tuple[type, ...], cls_dict: dict[str, Any]): ... + +class FuncMonad(Monad, metaclass=FuncMonadMeta): + def __call__(monad, *args, **kwargs): ... + +def get_classes(classinfo) -> Generator[Incomplete]: ... + +class FuncIsinstanceMonad(FuncMonad): + func = isinstance + def call(monad, obj, classinfo): ... + +class FuncBufferMonad(FuncMonad): + func: type[bytes] + def call(monad, source, encoding=None, errors=None): ... + +class FuncBoolMonad(FuncMonad): + func: type[bool] + def call(monad, x): ... + +class FuncIntMonad(FuncMonad): + func: type[int] + def call(monad, x): ... + +class FuncStrMonad(FuncMonad): + func: type[str] + def call(monad, x): ... + +class FuncFloatMonad(FuncMonad): + func: type[float] + def call(monad, x): ... + +class FuncDecimalMonad(FuncMonad): + func: type[Decimal] + def call(monad, x): ... + +class FuncDateMonad(FuncMonad): + func: type[date] + def call(monad, year, month, day): ... + def call_today(monad): ... + +class FuncTimeMonad(FuncMonad): + func: type[time] + def call(monad, *args): ... + +class FuncTimedeltaMonad(FuncMonad): + func: type[timedelta] + def call(monad, days=None, seconds=None, microseconds=None, milliseconds=None, minutes=None, hours=None, weeks=None): ... + +class FuncDatetimeMonad(FuncDateMonad): + func: type[datetime] + def call(monad, year, month, day, hour=None, minute=None, second=None, microsecond=None): ... + def call_now(monad): ... + +class FuncBetweenMonad(FuncMonad): + func = between + def call(monad, x, a, b): ... + +class FuncConcatMonad(FuncMonad): + func = concat + def call(monad, *args): ... + +class FuncLenMonad(FuncMonad): + func = len + def call(monad, x): ... + +class FuncGetattrMonad(FuncMonad): + func = getattr + def call(monad, obj_monad, name_monad): ... + +class FuncRawSQLMonad(FuncMonad): + func = raw_sql + def call(monad, *args) -> None: ... + +class FuncCountMonad(FuncMonad): + func: Incomplete + def call(monad, x=None, distinct=None): ... + +class FuncAbsMonad(FuncMonad): + func = abs + def call(monad, x): ... + +class FuncSumMonad(FuncMonad): + func: Incomplete + def call(monad, x, distinct=None): ... + +class FuncAvgMonad(FuncMonad): + func: Incomplete + def call(monad, x, distinct=None): ... + +class FuncGroupConcatMonad(FuncMonad): + func: Incomplete + def call(monad, x, sep=None, distinct=None): ... + +class FuncCoalesceMonad(FuncMonad): + func = coalesce + def call(monad, *args): ... + +class FuncDistinctMonad(FuncMonad): + func: Incomplete + def call(monad, x): ... + +class FuncMinMonad(FuncMonad): + func: Incomplete + def call(monad, *args): ... + +class FuncMaxMonad(FuncMonad): + func: Incomplete + def call(monad, *args): ... + +def minmax(monad, sqlop, *args): ... + +class FuncSelectMonad(FuncMonad): + func = core.select + def call(monad, queryset): ... + +class FuncExistsMonad(FuncMonad): + func = core.exists + def call(monad, arg): ... + +class FuncDescMonad(FuncMonad): + func = core.desc + def call(monad, expr): ... + +class DescMonad(Monad): + def __init__(monad, expr) -> None: ... + def getsql(monad): ... + +class JoinMonad(Monad): + def __init__(monad, type) -> None: ... + def __call__(monad, x): ... + +class FuncRandomMonad(FuncMonad): + func = random + def __init__(monad, type) -> None: ... + def __call__(monad): ... + +class SetMixin(MonadMixin): + forced_distinct: bool + def call_distinct(monad): ... + +def make_attrset_binop(op, sqlop): ... + +class AttrSetMonad(SetMixin, Monad): + def __init__(monad, parent, attr) -> None: ... + def cmp(monad, op, monad2) -> None: ... + def contains(monad, item, not_in: bool = False): ... + def getattr(monad, name): ... + def call_select(monad): ... + call_filter = call_select + def call_exists(monad): ... + def requires_distinct(monad, joined: bool = False, for_count: bool = False): ... + def count(monad, distinct=None): ... + len = count + def aggregate(monad, func_name, distinct=None, sep=None): ... + def nonzero(monad): ... + def negate(monad): ... + call_is_empty = negate + def make_tableref(monad, sqlquery): ... + def make_expr_list(monad): ... + def getsql(monad, sqlquery=None): ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + +def make_numericset_binop(op, sqlop): ... + +class NumericSetExprMonad(SetMixin, Monad): + def __init__(monad, op, sqlop, left, right) -> None: ... + def aggregate(monad, func_name, distinct=None, sep=None): ... + def getsql(monad, sqlquery=None): ... + __add__: Incomplete + __sub__: Incomplete + __mul__: Incomplete + __truediv__: Incomplete + __floordiv__: Incomplete + +class QuerySetMonad(SetMixin, Monad): + nogroup: bool + def __init__(monad, subtranslator) -> None: ... + def to_single_cell_value(monad): ... + def requires_distinct(monad, joined: bool = False) -> None: ... + def call_limit(monad, limit=None, offset=None): ... + def contains(monad, item, not_in: bool = False): ... + def nonzero(monad): ... + def negate(monad): ... + def count(monad, distinct=None): ... + len = count + def aggregate(monad, func_name, distinct=None, sep=None): ... + def call_count(monad, distinct=None): ... + def call_sum(monad, distinct=None): ... + def call_min(monad): ... + def call_max(monad): ... + def call_avg(monad, distinct=None): ... + def call_group_concat(monad, sep=None, distinct=None): ... + def getsql(monad): ... + +def find_or_create_having_ast(sections: list[Sequence[str]]): ... diff --git a/stubs/pony/pony/py23compat.pyi b/stubs/pony/pony/py23compat.pyi new file mode 100644 index 000000000000..0854571aa135 --- /dev/null +++ b/stubs/pony/pony/py23compat.pyi @@ -0,0 +1,13 @@ +PYPY: bool +PY36: bool +PY37: bool +PY38: bool +PY39: bool +PY310: bool +PY311: bool +PY312: bool +unicode = str +buffer = bytes +int_types: tuple[type[int]] + +def cmp(a, b): ... diff --git a/stubs/pony/pony/thirdparty/__init__.pyi b/stubs/pony/pony/thirdparty/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pony/pony/thirdparty/decorator.pyi b/stubs/pony/pony/thirdparty/decorator.pyi new file mode 100644 index 000000000000..1f521275e4a8 --- /dev/null +++ b/stubs/pony/pony/thirdparty/decorator.pyi @@ -0,0 +1,31 @@ +import re +from _typeshed import Incomplete +from collections.abc import Callable +from inspect import getfullargspec as getfullargspec +from typing import Final + +__version__: Final[str] +__all__ = ["decorator", "FunctionMaker", "contextmanager"] + +def get_init(cls: object) -> Callable[..., None]: ... + +DEF: re.Pattern[str] + +class FunctionMaker: + shortsignature: Incomplete + name: Incomplete + doc: Incomplete + module: Incomplete + annotations: Incomplete + signature: Incomplete + dict: Incomplete + defaults: Incomplete + def __init__(self, func=None, name=None, signature=None, defaults=None, doc=None, module=None, funcdict=None) -> None: ... + def update(self, func, **kw) -> None: ... + def make(self, src_templ, evaldict=None, addsource: bool = False, **attrs): ... + @classmethod + def create(cls, obj, body, evaldict, defaults=None, doc=None, module=None, addsource: bool = True, **attrs): ... + +def decorator(caller, func=None): ... + +contextmanager: Incomplete diff --git a/stubs/pony/pony/utils/__init__.pyi b/stubs/pony/pony/utils/__init__.pyi new file mode 100644 index 000000000000..f08d95e954ed --- /dev/null +++ b/stubs/pony/pony/utils/__init__.pyi @@ -0,0 +1,2 @@ +from .properties import * +from .utils import * diff --git a/stubs/pony/pony/utils/properties.pyi b/stubs/pony/pony/utils/properties.pyi new file mode 100644 index 000000000000..912a26d34900 --- /dev/null +++ b/stubs/pony/pony/utils/properties.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete + +class cached_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, cls): ... + +class class_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, instance, cls): ... + +class class_cached_property: + func: Incomplete + def __init__(self, func) -> None: ... + def __get__(self, obj, cls): ... diff --git a/stubs/pony/pony/utils/utils.pyi b/stubs/pony/pony/utils/utils.pyi new file mode 100644 index 000000000000..ffe7c493afff --- /dev/null +++ b/stubs/pony/pony/utils/utils.pyi @@ -0,0 +1,90 @@ +import ast +import io +import re +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Iterable +from datetime import datetime +from threading import local as _localbase +from types import CodeType, FunctionType, TracebackType +from typing import Any, overload +from typing_extensions import Never + +localbase = _localbase + +class PonyDeprecationWarning(DeprecationWarning): ... + +def deprecated(stacklevel: int, message: str) -> None: ... +def decorator(caller, func=None): ... +def decorator_with_params(dec): ... +def cut_traceback(func): ... + +cut_traceback_depth: int + +@overload +def reraise(exc_type: Unused, exc: None, tb: TracebackType | None) -> None: ... +@overload +def reraise(exc_type: Unused, exc: BaseException, tb: TracebackType | None) -> Never: ... + +def throw(exc_type: Exception | Callable[..., Exception], *args, **kwargs) -> Never: ... +def truncate_repr(s: object, max_len: int = 100) -> str: ... + +codeobjects: dict[int, CodeType] + +def get_codeobject_id(codeobject: CodeType) -> int: ... + +lambda_args_cache: dict[int | ast.Lambda, list[str]] + +def get_lambda_args(func: FunctionType | ast.Lambda) -> list[str]: ... +def error_method(*args: Unused, **kwargs: Unused) -> Never: ... +def is_ident(string: str) -> bool: ... +def split_name(name: str) -> list[str]: ... +def uppercase_name(name: str) -> str: ... +def lowercase_name(name: str) -> str: ... +def camelcase_name(name: str) -> str: ... +def mixedcase_name(name: str) -> str: ... +def import_module(name: str): ... +def is_absolute_path(filename: str) -> bool: ... +def absolutize_path(filename: str, frame_depth: int) -> str: ... +def current_timestamp() -> str: ... +def datetime2timestamp(d: datetime) -> str: ... +def timestamp2datetime(t: str) -> datetime: ... + +expr1_re: re.Pattern[str] +expr2_re: re.Pattern[str] +expr3_re: re.Pattern[str] + +def parse_expr(s: str, pos: int = 0) -> tuple[str, bool]: ... +def tostring(x): ... +def strjoin( + sep: str, strings: Iterable[str], source_encoding: str = "ascii", dest_encoding: str | None = None +) -> str | bytes: ... +def count(*args, **kwargs): ... +def avg(iter: Iterable[float | None]) -> float | None: ... + +@overload +def group_concat(items: None, sep: str = ",") -> None: ... +@overload +def group_concat(items: Iterable[object], sep: str = ",") -> str: ... + +def coalesce(*args: Any) -> Any: ... +def distinct(iter): ... +def concat(*args) -> str: ... +def between(x: float, a: float, b: float) -> bool: ... +def is_utf8(encoding: str) -> bool: ... +def pickle_ast(val): ... +def unpickle_ast(pickled: io.BytesIO): ... +def copy_ast(tree): ... + +class HashableDict(dict[Incomplete, Incomplete]): + def __hash__(self) -> int: ... # type: ignore[override] + def __deepcopy__(self, memo): ... + __setitem__: Incomplete + __delitem__: Incomplete + clear: Incomplete + pop: Incomplete + popitem: Incomplete + setdefault: Incomplete + update: Incomplete + +def deref_proxy(value): ... +def deduplicate(value, deduplication_cache): ... diff --git a/stubs/portpicker/METADATA.toml b/stubs/portpicker/METADATA.toml new file mode 100644 index 000000000000..17d27f8a5e10 --- /dev/null +++ b/stubs/portpicker/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.6.*" +upstream-repository = "https://github.com/google/python_portpicker" diff --git a/stubs/portpicker/portpicker.pyi b/stubs/portpicker/portpicker.pyi new file mode 100644 index 000000000000..9162cfa9874a --- /dev/null +++ b/stubs/portpicker/portpicker.pyi @@ -0,0 +1,21 @@ +import socket +from typing import TypeAlias + +_Port: TypeAlias = int + +__all__ = ("bind", "is_port_free", "pick_unused_port", "return_port", "add_reserved_port", "get_port_from_port_server") + +class NoFreePortFoundError(Exception): ... + +def add_reserved_port(port: _Port) -> None: ... +def return_port(port: _Port) -> None: ... +def bind(port: _Port, socket_type: socket.SocketKind, socket_proto: int) -> _Port | None: ... +def is_port_free(port: _Port) -> bool: ... +def pick_unused_port(pid: int | None = None, portserver_address: str | None = None) -> _Port: ... +def get_port_from_port_server(portserver_address: str, pid: int | None = None) -> _Port | None: ... + +# legacy aliases +Bind = bind +GetPortFromPortServer = get_port_from_port_server +IsPortFree = is_port_free +PickUnusedPort = pick_unused_port diff --git a/stubs/protobuf/@tests/stubtest_allowlist.txt b/stubs/protobuf/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..38356350e0ca --- /dev/null +++ b/stubs/protobuf/@tests/stubtest_allowlist.txt @@ -0,0 +1,34 @@ +# Generated pb2 methods diverge for a variety of reasons. They are tested +# carefully in mypy-protobuf which internally runs stubtest. Skip those here. +google.protobuf\..*_pb2\..* + +# While Message and Descriptor are both defined with a null DESCRIPTOR, +# subclasses of Message and instances of EnumTypeWrapper require this value to +# be set, and since these type stubs are intended for use with protoc-generated +# python it's more accurate to make them non-nullable. +google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper.DESCRIPTOR +google.protobuf.message.Message.DESCRIPTOR + +# Exists at runtime, but via a __getitem__/__setitem__ hack +# See https://github.com/protocolbuffers/protobuf/blob/3ea30d80847cd9561db570ae7f673afc15523545/python/google/protobuf/message.py#L67 +google.protobuf.message.Message.Extensions + +# Has *args that would fail at runtime with any positional argument +google.protobuf.internal.containers.BaseContainer.sort + +# These are deliberately omitted in the stub. +# The classes can't be constructed directly anyway, +# so the signatures of their constructors are somewhat irrelevant. +google.protobuf.descriptor.Descriptor.__new__ +google.protobuf.descriptor.ServiceDescriptor.__new__ + +# Set to None at runtime - which doesn't match the Sequence base class. +# It's a hack - just allow it. +google.protobuf.internal.containers.BaseContainer.__hash__ + +# Runtime does not have __iter__ (yet...): hack in spirit of https://github.com/python/typeshed/issues/7813 +google.protobuf.internal.well_known_types.ListValue.__iter__ + +# It's a list at runtime, but if we do that pyright complains about incompatible overrides +# in subclasses that use a tuple for __slots__. +google.protobuf.message.Message.__slots__ diff --git a/stubs/protobuf/@tests/test_cases/check_struct.py b/stubs/protobuf/@tests/test_cases/check_struct.py new file mode 100644 index 000000000000..d3679af470cd --- /dev/null +++ b/stubs/protobuf/@tests/test_cases/check_struct.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from google.protobuf.struct_pb2 import ListValue, Struct + +list_value = ListValue() + +lst = list(list_value) # Ensure type checkers recognise that the class is iterable (doesn't have an `__iter__` method at runtime) + +list_value[0] = 42.42 +list_value[0] = "42" +list_value[0] = None +list_value[0] = True +list_value[0] = [42.42, "42", None, True, [42.42, "42", None, True], {"42": 42}] +list_value[0] = ListValue() +list_value[0] = Struct() + +list_element = list_value[0] diff --git a/stubs/protobuf/METADATA.toml b/stubs/protobuf/METADATA.toml new file mode 100644 index 000000000000..78387ac33475 --- /dev/null +++ b/stubs/protobuf/METADATA.toml @@ -0,0 +1,9 @@ +# Using an exact number in the specifier for scripts/sync_protobuf/google_protobuf.py +# When updating, also re-run the script +version = "~=7.34.1" +upstream-repository = "https://github.com/protocolbuffers/protobuf" +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 34.1 on [protobuf v34.1](https://github.com/protocolbuffers/protobuf/releases/tag/v34.1) (python `protobuf==7.34.1`)." +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true diff --git a/stubs/protobuf/google/_upb/_message.pyi b/stubs/protobuf/google/_upb/_message.pyi new file mode 100644 index 000000000000..454b93febff5 --- /dev/null +++ b/stubs/protobuf/google/_upb/_message.pyi @@ -0,0 +1,334 @@ +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, ClassVar, final +from typing_extensions import Self, disjoint_base + +from google.protobuf.descriptor_pb2 import ( + DescriptorProto, + EnumDescriptorProto, + EnumOptions, + EnumValueOptions, + FeatureSetDefaults, + FieldOptions, + FileDescriptorProto, + FileOptions, + MessageOptions, + MethodDescriptorProto, + MethodOptions, + OneofOptions, + ServiceDescriptorProto, + ServiceOptions, +) + +default_pool: DescriptorPool + +@final +class Arena: ... + +@final +class Descriptor: + containing_type: Descriptor | None + enum_types: Sequence[EnumDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + enum_values_by_name: dict[str, EnumValueDescriptor] + extension_ranges: list[tuple[int, int]] + extensions: Sequence[FieldDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + fields: Sequence[FieldDescriptor] + fields_by_camelcase_name: Mapping[str, FieldDescriptor] + fields_by_name: Mapping[str, FieldDescriptor] + fields_by_number: Mapping[int, FieldDescriptor] + file: FileDescriptor + full_name: str + has_options: bool + is_extendable: bool + name: str + nested_types: Sequence[Descriptor] + nested_types_by_name: Mapping[str, Descriptor] + oneofs: Sequence[OneofDescriptor] + oneofs_by_name: Mapping[str, OneofDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: DescriptorProto, /) -> None: ... + def EnumValueName(self, enum: str, value: int) -> str: ... + def GetOptions(self) -> MessageOptions: ... + +@final +class DescriptorPool: + def __new__(cls, *args, **kwargs) -> Self: ... + def Add(self, file_desc_proto: FileDescriptorProto, /) -> None: ... + def AddSerializedFile(self, serialized_file_desc_proto: bytes, /) -> FileDescriptor: ... + def FindAllExtensions(self, message_descriptor: Descriptor, /) -> list[FieldDescriptor]: ... + def FindEnumTypeByName(self, full_name: str, /) -> EnumDescriptor: ... + def FindExtensionByName(self, full_name: str, /) -> FieldDescriptor: ... + def FindExtensionByNumber(self, message_descriptor: Descriptor, number: int, /) -> FieldDescriptor: ... + def FindFieldByName(self, full_name: str, /) -> FieldDescriptor: ... + def FindFileByName(self, file_name: str, /) -> FileDescriptor: ... + def FindFileContainingSymbol(self, symbol: str, /) -> FileDescriptor: ... + def FindMessageTypeByName(self, full_name: str, /) -> Descriptor: ... + def FindMethodByName(self, full_name: str, /) -> MethodDescriptor: ... + def FindOneofByName(self, full_name: str, /) -> OneofDescriptor: ... + def FindServiceByName(self, full_name: str, /) -> ServiceDescriptor: ... + def SetFeatureSetDefaults(self, defaults: FeatureSetDefaults, /) -> None: ... + +@final +class EnumDescriptor: + containing_type: Descriptor | None + file: FileDescriptor + full_name: str + has_options: bool + is_closed: bool + name: str + values: Sequence[EnumValueDescriptor] + values_by_name: Mapping[str, EnumValueDescriptor] + values_by_number: Mapping[int, EnumValueDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: EnumDescriptorProto, /) -> None: ... + def GetOptions(self) -> EnumOptions: ... + +@final +class EnumValueDescriptor: + has_options: bool + index: int + name: str + number: int + type: EnumDescriptor + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> EnumValueOptions: ... + +@final +class ExtensionDict: + def __contains__(self, extension_handle: FieldDescriptor, /) -> bool: ... + def __delitem__(self, extension_handle: FieldDescriptor, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, extension_handle: FieldDescriptor, /) -> Any: ... # Any: Message, scalar, or container + def __gt__(self, other: object, /) -> bool: ... + def __iter__(self) -> ExtensionIterator: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setitem__(self, extension_handle: FieldDescriptor, value: Any, /) -> None: ... # Any: Message, scalar, or container + +@final +class ExtensionIterator: + def __iter__(self) -> Self: ... + def __next__(self) -> FieldDescriptor: ... + +@final +class FieldDescriptor: + CPPTYPE_BOOL: ClassVar[int] = ... + CPPTYPE_BYTES: ClassVar[int] = ... + CPPTYPE_DOUBLE: ClassVar[int] = ... + CPPTYPE_ENUM: ClassVar[int] = ... + CPPTYPE_FLOAT: ClassVar[int] = ... + CPPTYPE_INT32: ClassVar[int] = ... + CPPTYPE_INT64: ClassVar[int] = ... + CPPTYPE_MESSAGE: ClassVar[int] = ... + CPPTYPE_STRING: ClassVar[int] = ... + CPPTYPE_UINT32: ClassVar[int] = ... + CPPTYPE_UINT64: ClassVar[int] = ... + LABEL_OPTIONAL: ClassVar[int] = ... + LABEL_REPEATED: ClassVar[int] = ... + LABEL_REQUIRED: ClassVar[int] = ... + TYPE_BOOL: ClassVar[int] = ... + TYPE_BYTES: ClassVar[int] = ... + TYPE_DOUBLE: ClassVar[int] = ... + TYPE_ENUM: ClassVar[int] = ... + TYPE_FIXED32: ClassVar[int] = ... + TYPE_FIXED64: ClassVar[int] = ... + TYPE_FLOAT: ClassVar[int] = ... + TYPE_GROUP: ClassVar[int] = ... + TYPE_INT32: ClassVar[int] = ... + TYPE_INT64: ClassVar[int] = ... + TYPE_MESSAGE: ClassVar[int] = ... + TYPE_SFIXED32: ClassVar[int] = ... + TYPE_SFIXED64: ClassVar[int] = ... + TYPE_SINT32: ClassVar[int] = ... + TYPE_SINT64: ClassVar[int] = ... + TYPE_STRING: ClassVar[int] = ... + TYPE_UINT32: ClassVar[int] = ... + TYPE_UINT64: ClassVar[int] = ... + camelcase_name: str + containing_oneof: OneofDescriptor | None + containing_type: Descriptor | None + cpp_type: int + default_value: Any # Any: str, int, float, bytes, or bool + enum_type: EnumDescriptor | None + extension_scope: Descriptor | None + file: FileDescriptor + full_name: str + has_default_value: bool + has_options: bool + has_presence: bool + index: int + is_extension: bool + is_packed: bool + is_repeated: bool + is_required: bool + json_name: str + message_type: Descriptor | None + name: str + number: int + type: int + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> FieldOptions: ... + +@final +class FileDescriptor: + dependencies: Sequence[FileDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + has_options: bool + message_types_by_name: Mapping[str, Descriptor] + name: str + package: str + pool: DescriptorPool + public_dependencies: Sequence[FileDescriptor] + serialized_pb: bytes + services_by_name: Mapping[str, ServiceDescriptor] + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: FileDescriptorProto, /) -> None: ... + def GetOptions(self) -> FileOptions: ... + +@final +class MapIterator: + def __iter__(self) -> Self: ... + def __next__(self) -> bool | int | str: ... + +@final +class Message: + Extensions: ExtensionDict + def __init__(self, *args, **kwargs) -> None: ... + def __contains__(self, field_name_or_key: str, /) -> bool: ... + def __deepcopy__(self, memo: Any = None) -> Self: ... + def __delattr__(self, name: str, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... # Any: str, int, float, bytes, bool, or Message + def MergeFrom(self, other_msg: Message, /) -> None: ... + def CopyFrom(self, other_msg: Message, /) -> None: ... + def Clear(self) -> None: ... + def SetInParent(self) -> None: ... + def IsInitialized(self, errors: list[str] | None = None) -> bool: ... + def MergeFromString(self, serialized: bytes, /) -> int: ... + def ParseFromString(self, serialized: bytes, /) -> int: ... + def SerializeToString(self, *, deterministic: bool = ...) -> bytes: ... + def SerializePartialToString(self, *, deterministic: bool = ...) -> bytes: ... + def ListFields(self) -> list[tuple[FieldDescriptor, Any]]: ... # Any: str, int, float, bytes, bool, or Message + def HasField(self, field_name: str, /) -> bool: ... + def ClearField(self, field_name: str, /) -> None: ... + def WhichOneof(self, oneof_group: str, /) -> str | None: ... + def HasExtension(self, field_descriptor: FieldDescriptor, /) -> bool: ... + def ClearExtension(self, field_descriptor: FieldDescriptor, /) -> None: ... + def UnknownFields(self) -> UnknownFieldSet: ... + def DiscardUnknownFields(self) -> None: ... + def ByteSize(self) -> int: ... + @classmethod + def FromString(cls, s: bytes, /) -> Self: ... + def FindInitializationErrors(self) -> list[str]: ... + +@disjoint_base +class MessageMeta(type): ... + +@final +class MethodDescriptor: + client_streaming: bool + containing_service: ServiceDescriptor + full_name: str + has_options: bool + index: int + input_type: Descriptor + name: str + output_type: Descriptor + server_streaming: bool + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: MethodDescriptorProto, /) -> None: ... + def GetOptions(self) -> MethodOptions: ... + +@final +class OneofDescriptor: + containing_type: Descriptor + fields: Sequence[FieldDescriptor] + full_name: str + has_options: bool + index: int + name: str + def __new__(cls, *args, **kwargs) -> Self: ... + def GetOptions(self) -> OneofOptions: ... + +@final +class RepeatedCompositeContainer: + def __new__(cls, *args, **kwargs) -> Self: ... + def MergeFrom(self, other: RepeatedCompositeContainer | Iterable[Message], /) -> None: ... + def add(self, **kwargs: Any) -> Message: ... # Any: field names and values + def append(self, value: Message, /) -> None: ... + def extend(self, values: Iterable[Message], /) -> None: ... + def insert(self, key: int, value: Message, /) -> None: ... + def pop(self, key: int = -1, /) -> Message: ... + def remove(self, value: Message, /) -> None: ... + def reverse(self) -> None: ... + def sort(self, *, key: Callable[[Any], Any] | None = None, reverse: bool = False) -> None: ... + def clear(self) -> None: ... + def __deepcopy__(self, memo: Any = None) -> RepeatedCompositeContainer: ... + def __delitem__(self, key: int | slice, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, index: int | slice, /) -> Message: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __setitem__(self, index: int | slice, value: Message, /) -> None: ... + +@final +class RepeatedScalarContainer: + def __new__(cls, *args, **kwargs) -> Self: ... + def MergeFrom(self, other: Any, /) -> None: ... # Any: bool, int, float, str, or bytes + def append(self, value: Any, /) -> None: ... + def extend(self, values: Any, /) -> None: ... + def insert(self, key: int, value: Any, /) -> None: ... + def pop(self, key: int = -1, /) -> Any: ... + def remove(self, value: Any, /) -> None: ... + def reverse(self) -> None: ... + def sort(self, *, key: Callable[[Any], Any] | None = None, reverse: bool = False) -> None: ... + def clear(self) -> None: ... + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: ... # Any: numpy types + def __deepcopy__(self, memo: Any = None) -> RepeatedScalarContainer: ... + def __delitem__(self, key: int | slice, /) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + def __ge__(self, other: object, /) -> bool: ... + def __getitem__(self, index: int | slice, /) -> Any: ... + def __gt__(self, other: object, /) -> bool: ... + def __le__(self, other: object, /) -> bool: ... + def __len__(self) -> int: ... + def __lt__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __reduce__(self) -> tuple[Any, ...]: ... + def __setitem__(self, index: int | slice, value: Any, /) -> None: ... + +@final +class ServiceDescriptor: + file: FileDescriptor + full_name: str + has_options: bool + index: int + methods: Sequence[MethodDescriptor] + methods_by_name: Mapping[str, MethodDescriptor] + name: str + def __new__(cls, *args, **kwargs) -> Self: ... + def CopyToProto(self, proto: ServiceDescriptorProto, /) -> None: ... + def FindMethodByName(self, name: str, /) -> MethodDescriptor: ... + def GetOptions(self) -> ServiceOptions: ... + +@final +class UnknownFieldSet: + def __new__(cls, *args, **kwargs) -> Self: ... + def __getitem__(self, index: int, /) -> Any: ... # Any: internal unknown field object + def __len__(self) -> int: ... + +def SetAllowOversizeProtos(allow: bool, /) -> None: ... diff --git a/stubs/protobuf/google/protobuf/__init__.pyi b/stubs/protobuf/google/protobuf/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/protobuf/google/protobuf/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/protobuf/google/protobuf/any.pyi b/stubs/protobuf/google/protobuf/any.pyi new file mode 100644 index 000000000000..72be6e49e191 --- /dev/null +++ b/stubs/protobuf/google/protobuf/any.pyi @@ -0,0 +1,13 @@ +from typing import TypeVar + +from google.protobuf.any_pb2 import Any +from google.protobuf.descriptor import Descriptor +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def pack(msg: Message, type_url_prefix: str | None = "type.googleapis.com/", deterministic: bool | None = None) -> Any: ... +def unpack(any_msg: Any, msg: Message) -> bool: ... +def unpack_as(any_msg: Any, message_type: type[_MessageT]) -> _MessageT: ... +def type_name(any_msg: Any) -> str: ... +def is_type(any_msg: Any, des: Descriptor) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/any_pb2.pyi b/stubs/protobuf/google/protobuf/any_pb2.pyi new file mode 100644 index 000000000000..c12c7e4a8133 --- /dev/null +++ b/stubs/protobuf/google/protobuf/any_pb2.pyi @@ -0,0 +1,172 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.well_known_types +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Any(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Any): + """`Any` contains an arbitrary serialized protocol buffer message along with a + URL that describes the type of the serialized message. + + Protobuf library provides support to pack/unpack Any values in the form + of utility functions or additional generated methods of the Any type. + + Example 1: Pack and unpack a message in C++. + + Foo foo = ...; + Any any; + any.PackFrom(foo); + ... + if (any.UnpackTo(&foo)) { + ... + } + + Example 2: Pack and unpack a message in Java. + + Foo foo = ...; + Any any = Any.pack(foo); + ... + if (any.is(Foo.class)) { + foo = any.unpack(Foo.class); + } + // or ... + if (any.isSameTypeAs(Foo.getDefaultInstance())) { + foo = any.unpack(Foo.getDefaultInstance()); + } + + Example 3: Pack and unpack a message in Python. + + foo = Foo(...) + any = Any() + any.Pack(foo) + ... + if any.Is(Foo.DESCRIPTOR): + any.Unpack(foo) + ... + + Example 4: Pack and unpack a message in Go + + foo := &pb.Foo{...} + any, err := anypb.New(foo) + if err != nil { + ... + } + ... + foo := &pb.Foo{} + if err := any.UnmarshalTo(foo); err != nil { + ... + } + + The pack methods provided by protobuf library will by default use + 'type.googleapis.com/full.type.name' as the type URL and the unpack + methods only use the fully qualified type name after the last '/' + in the type URL, for example "foo.bar.com/x/y.z" will yield type + name "y.z". + + JSON + ==== + The JSON representation of an `Any` value uses the regular + representation of the deserialized, embedded message, with an + additional field `@type` which contains the type URL. Example: + + package google.profile; + message Person { + string first_name = 1; + string last_name = 2; + } + + { + "@type": "type.googleapis.com/google.profile.Person", + "firstName": , + "lastName": + } + + If the embedded message type is well-known and has a custom JSON + representation, that representation will be embedded adding a field + `value` which holds the custom JSON in addition to the `@type` + field. Example (for message [google.protobuf.Duration][]): + + { + "@type": "type.googleapis.com/google.protobuf.Duration", + "value": "1.212s" + } + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TYPE_URL_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + type_url: builtins.str + """A URL/resource name that uniquely identifies the type of the serialized + protocol buffer message. This string must contain at least + one "/" character. The last segment of the URL's path must represent + the fully qualified name of the type (as in + `path/google.protobuf.Duration`). The name should be in a canonical form + (e.g., leading "." is not accepted). + + In practice, teams usually precompile into the binary all types that they + expect it to use in the context of Any. However, for URLs which use the + scheme `http`, `https`, or no scheme, one can optionally set up a type + server that maps type URLs to message definitions as follows: + + * If no scheme is provided, `https` is assumed. + * An HTTP GET on the URL must yield a [google.protobuf.Type][] + value in binary format, or produce an error. + * Applications are allowed to cache lookup results based on the + URL, or have them precompiled into a binary to avoid any + lookup. Therefore, binary compatibility needs to be preserved + on changes to types. (Use versioned type names to manage + breaking changes.) + + Note: this functionality is not currently available in the official + protobuf release, and it is not used for type URLs beginning with + type.googleapis.com. As of May 2023, there are no widely used type server + implementations and no plans to implement one. + + Schemes other than `http`, `https` (or the empty scheme) might be + used with implementation specific semantics. + """ + value: builtins.bytes + """Must be a valid serialized protocol buffer of the above specified type.""" + def __init__(self, *, type_url: builtins.str | None = ..., value: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["type_url", b"type_url", "value", b"value"]) -> None: ... + +global___Any = Any diff --git a/stubs/protobuf/google/protobuf/api_pb2.pyi b/stubs/protobuf/google/protobuf/api_pb2.pyi new file mode 100644 index 000000000000..9c65bc6ac8fc --- /dev/null +++ b/stubs/protobuf/google/protobuf/api_pb2.pyi @@ -0,0 +1,336 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import google.protobuf.source_context_pb2 +import google.protobuf.type_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Api(google.protobuf.message.Message): + """Api is a light-weight descriptor for an API Interface. + + Interfaces are also described as "protocol buffer services" in some contexts, + such as by the "service" keyword in a .proto file, but they are different + from API Services, which represent a concrete implementation of an interface + as opposed to simply a description of methods and bindings. They are also + sometimes simply referred to as "APIs" in other contexts, such as the name of + this message itself. See https://cloud.google.com/apis/design/glossary for + detailed terminology. + + New usages of this message as an alternative to ServiceDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + METHODS_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + VERSION_FIELD_NUMBER: builtins.int + SOURCE_CONTEXT_FIELD_NUMBER: builtins.int + MIXINS_FIELD_NUMBER: builtins.int + SYNTAX_FIELD_NUMBER: builtins.int + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str + """The fully qualified name of this interface, including package name + followed by the interface's simple name. + """ + version: builtins.str + """A version string for this interface. If specified, must have the form + `major-version.minor-version`, as in `1.10`. If the minor version is + omitted, it defaults to zero. If the entire version field is empty, the + major version is derived from the package name, as outlined below. If the + field is not empty, the version in the package name will be verified to be + consistent with what is provided here. + + The versioning schema uses [semantic + versioning](http://semver.org) where the major version number + indicates a breaking change and the minor version an additive, + non-breaking change. Both version numbers are signals to users + what to expect from different versions, and should be carefully + chosen based on the product plan. + + The major version is also reflected in the package name of the + interface, which must end in `v`, as in + `google.feature.v1`. For major versions 0 and 1, the suffix can + be omitted. Zero major versions must only be used for + experimental, non-GA interfaces. + """ + syntax: google.protobuf.type_pb2.Syntax.ValueType + """The source syntax of the service.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" + @property + def methods(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Method]: + """The methods of this interface, in unspecified order.""" + + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.type_pb2.Option]: + """Any metadata attached to the interface.""" + + @property + def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: + """Source context for the protocol buffer service represented by this + message. + """ + + @property + def mixins(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Mixin]: + """Included interfaces. See [Mixin][].""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + methods: collections.abc.Iterable[global___Method] | None = ..., + options: collections.abc.Iterable[google.protobuf.type_pb2.Option] | None = ..., + version: builtins.str | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + mixins: collections.abc.Iterable[global___Mixin] | None = ..., + syntax: google.protobuf.type_pb2.Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "methods", + b"methods", + "mixins", + b"mixins", + "name", + b"name", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + "version", + b"version", + ], + ) -> None: ... + +global___Api = Api + +@typing.final +class Method(google.protobuf.message.Message): + """Method represents a method of an API interface. + + New usages of this message as an alternative to MethodDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + REQUEST_TYPE_URL_FIELD_NUMBER: builtins.int + REQUEST_STREAMING_FIELD_NUMBER: builtins.int + RESPONSE_TYPE_URL_FIELD_NUMBER: builtins.int + RESPONSE_STREAMING_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SYNTAX_FIELD_NUMBER: builtins.int + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str + """The simple name of this method.""" + request_type_url: builtins.str + """A URL of the input message type.""" + request_streaming: builtins.bool + """If true, the request is streamed.""" + response_type_url: builtins.str + """The URL of the output message type.""" + response_streaming: builtins.bool + """If true, the response is streamed.""" + syntax: google.protobuf.type_pb2.Syntax.ValueType + """The source syntax of this method. + + This field should be ignored, instead the syntax should be inherited from + Api. This is similar to Field and EnumValue. + """ + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS. + + This field should be ignored, instead the edition should be inherited from + Api. This is similar to Field and EnumValue. + """ + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.type_pb2.Option]: + """Any metadata attached to the method.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + request_type_url: builtins.str | None = ..., + request_streaming: builtins.bool | None = ..., + response_type_url: builtins.str | None = ..., + response_streaming: builtins.bool | None = ..., + options: collections.abc.Iterable[google.protobuf.type_pb2.Option] | None = ..., + syntax: google.protobuf.type_pb2.Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "name", + b"name", + "options", + b"options", + "request_streaming", + b"request_streaming", + "request_type_url", + b"request_type_url", + "response_streaming", + b"response_streaming", + "response_type_url", + b"response_type_url", + "syntax", + b"syntax", + ], + ) -> None: ... + +global___Method = Method + +@typing.final +class Mixin(google.protobuf.message.Message): + """Declares an API Interface to be included in this interface. The including + interface must redeclare all the methods from the included interface, but + documentation and options are inherited as follows: + + - If after comment and whitespace stripping, the documentation + string of the redeclared method is empty, it will be inherited + from the original method. + + - Each annotation belonging to the service config (http, + visibility) which is not set in the redeclared method will be + inherited. + + - If an http annotation is inherited, the path pattern will be + modified as follows. Any version prefix will be replaced by the + version of the including interface plus the [root][] path if + specified. + + Example of a simple mixin: + + package google.acl.v1; + service AccessControl { + // Get the underlying ACL object. + rpc GetAcl(GetAclRequest) returns (Acl) { + option (google.api.http).get = "/v1/{resource=**}:getAcl"; + } + } + + package google.storage.v2; + service Storage { + rpc GetAcl(GetAclRequest) returns (Acl); + + // Get a data record. + rpc GetData(GetDataRequest) returns (Data) { + option (google.api.http).get = "/v2/{resource=**}"; + } + } + + Example of a mixin configuration: + + apis: + - name: google.storage.v2.Storage + mixins: + - name: google.acl.v1.AccessControl + + The mixin construct implies that all methods in `AccessControl` are + also declared with same name and request/response types in + `Storage`. A documentation generator or annotation processor will + see the effective `Storage.GetAcl` method after inheriting + documentation and annotations as follows: + + service Storage { + // Get the underlying ACL object. + rpc GetAcl(GetAclRequest) returns (Acl) { + option (google.api.http).get = "/v2/{resource=**}:getAcl"; + } + ... + } + + Note how the version in the path pattern changed from `v1` to `v2`. + + If the `root` field in the mixin is specified, it should be a + relative path under which inherited HTTP paths are placed. Example: + + apis: + - name: google.storage.v2.Storage + mixins: + - name: google.acl.v1.AccessControl + root: acls + + This implies the following inherited HTTP annotation: + + service Storage { + // Get the underlying ACL object. + rpc GetAcl(GetAclRequest) returns (Acl) { + option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; + } + ... + } + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + ROOT_FIELD_NUMBER: builtins.int + name: builtins.str + """The fully qualified name of the interface which is included.""" + root: builtins.str + """If non-empty specifies a path under which inherited HTTP paths + are rooted. + """ + def __init__(self, *, name: builtins.str | None = ..., root: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "root", b"root"]) -> None: ... + +global___Mixin = Mixin diff --git a/stubs/protobuf/google/protobuf/compiler/__init__.pyi b/stubs/protobuf/google/protobuf/compiler/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi b/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi new file mode 100644 index 000000000000..a6f744c26074 --- /dev/null +++ b/stubs/protobuf/google/protobuf/compiler/plugin_pb2.pyi @@ -0,0 +1,362 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Author: kenton@google.com (Kenton Varda) + +protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is +just a program that reads a CodeGeneratorRequest from stdin and writes a +CodeGeneratorResponse to stdout. + +Plugins written using C++ can use google/protobuf/compiler/plugin.h instead +of dealing with the raw protocol defined here. + +A plugin executable needs only to be placed somewhere in the path. The +plugin should be named "protoc-gen-$NAME", and will then be used when the +flag "--${NAME}_out" is passed to protoc. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.descriptor_pb2 +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Version(google.protobuf.message.Message): + """The version number of protocol compiler.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAJOR_FIELD_NUMBER: builtins.int + MINOR_FIELD_NUMBER: builtins.int + PATCH_FIELD_NUMBER: builtins.int + SUFFIX_FIELD_NUMBER: builtins.int + major: builtins.int + minor: builtins.int + patch: builtins.int + suffix: builtins.str + """A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should + be empty for mainline stable releases. + """ + def __init__( + self, + *, + major: builtins.int | None = ..., + minor: builtins.int | None = ..., + patch: builtins.int | None = ..., + suffix: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["major", b"major", "minor", b"minor", "patch", b"patch", "suffix", b"suffix"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["major", b"major", "minor", b"minor", "patch", b"patch", "suffix", b"suffix"] + ) -> None: ... + +global___Version = Version + +@typing.final +class CodeGeneratorRequest(google.protobuf.message.Message): + """An encoded CodeGeneratorRequest is written to the plugin's stdin.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_TO_GENERATE_FIELD_NUMBER: builtins.int + PARAMETER_FIELD_NUMBER: builtins.int + PROTO_FILE_FIELD_NUMBER: builtins.int + SOURCE_FILE_DESCRIPTORS_FIELD_NUMBER: builtins.int + COMPILER_VERSION_FIELD_NUMBER: builtins.int + parameter: builtins.str + """The generator parameter passed on the command-line.""" + @property + def file_to_generate(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """The .proto files that were explicitly listed on the command-line. The + code generator should generate code only for these files. Each file's + descriptor will be included in proto_file, below. + """ + + @property + def proto_file( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.descriptor_pb2.FileDescriptorProto]: + """FileDescriptorProtos for all files in files_to_generate and everything + they import. The files will appear in topological order, so each file + appears before any file that imports it. + + Note: the files listed in files_to_generate will include runtime-retention + options only, but all other files will include source-retention options. + The source_file_descriptors field below is available in case you need + source-retention options for files_to_generate. + + protoc guarantees that all proto_files will be written after + the fields above, even though this is not technically guaranteed by the + protobuf wire format. This theoretically could allow a plugin to stream + in the FileDescriptorProtos and handle them one by one rather than read + the entire set into memory at once. However, as of this writing, this + is not similarly optimized on protoc's end -- it will store all fields in + memory at once before sending them to the plugin. + + Type names of fields and extensions in the FileDescriptorProto are always + fully qualified. + """ + + @property + def source_file_descriptors( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.descriptor_pb2.FileDescriptorProto]: + """File descriptors with all options, including source-retention options. + These descriptors are only provided for the files listed in + files_to_generate. + """ + + @property + def compiler_version(self) -> global___Version: + """The version number of protocol compiler.""" + + def __init__( + self, + *, + file_to_generate: collections.abc.Iterable[builtins.str] | None = ..., + parameter: builtins.str | None = ..., + proto_file: collections.abc.Iterable[google.protobuf.descriptor_pb2.FileDescriptorProto] | None = ..., + source_file_descriptors: collections.abc.Iterable[google.protobuf.descriptor_pb2.FileDescriptorProto] | None = ..., + compiler_version: global___Version | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["compiler_version", b"compiler_version", "parameter", b"parameter"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "compiler_version", + b"compiler_version", + "file_to_generate", + b"file_to_generate", + "parameter", + b"parameter", + "proto_file", + b"proto_file", + "source_file_descriptors", + b"source_file_descriptors", + ], + ) -> None: ... + +global___CodeGeneratorRequest = CodeGeneratorRequest + +@typing.final +class CodeGeneratorResponse(google.protobuf.message.Message): + """The plugin writes an encoded CodeGeneratorResponse to stdout.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Feature: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FeatureEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CodeGeneratorResponse._Feature.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FEATURE_NONE: CodeGeneratorResponse._Feature.ValueType # 0 + FEATURE_PROTO3_OPTIONAL: CodeGeneratorResponse._Feature.ValueType # 1 + FEATURE_SUPPORTS_EDITIONS: CodeGeneratorResponse._Feature.ValueType # 2 + + class Feature(_Feature, metaclass=_FeatureEnumTypeWrapper): + """Sync with code_generator.h.""" + + FEATURE_NONE: CodeGeneratorResponse.Feature.ValueType # 0 + FEATURE_PROTO3_OPTIONAL: CodeGeneratorResponse.Feature.ValueType # 1 + FEATURE_SUPPORTS_EDITIONS: CodeGeneratorResponse.Feature.ValueType # 2 + + @typing.final + class File(google.protobuf.message.Message): + """Represents a single generated file.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + INSERTION_POINT_FIELD_NUMBER: builtins.int + CONTENT_FIELD_NUMBER: builtins.int + GENERATED_CODE_INFO_FIELD_NUMBER: builtins.int + name: builtins.str + """The file name, relative to the output directory. The name must not + contain "." or ".." components and must be relative, not be absolute (so, + the file cannot lie outside the output directory). "/" must be used as + the path separator, not "\\". + + If the name is omitted, the content will be appended to the previous + file. This allows the generator to break large files into small chunks, + and allows the generated text to be streamed back to protoc so that large + files need not reside completely in memory at one time. Note that as of + this writing protoc does not optimize for this -- it will read the entire + CodeGeneratorResponse before writing files to disk. + """ + insertion_point: builtins.str + """If non-empty, indicates that the named file should already exist, and the + content here is to be inserted into that file at a defined insertion + point. This feature allows a code generator to extend the output + produced by another code generator. The original generator may provide + insertion points by placing special annotations in the file that look + like: + @@protoc_insertion_point(NAME) + The annotation can have arbitrary text before and after it on the line, + which allows it to be placed in a comment. NAME should be replaced with + an identifier naming the point -- this is what other generators will use + as the insertion_point. Code inserted at this point will be placed + immediately above the line containing the insertion point (thus multiple + insertions to the same point will come out in the order they were added). + The double-@ is intended to make it unlikely that the generated code + could contain things that look like insertion points by accident. + + For example, the C++ code generator places the following line in the + .pb.h files that it generates: + // @@protoc_insertion_point(namespace_scope) + This line appears within the scope of the file's package namespace, but + outside of any particular class. Another plugin can then specify the + insertion_point "namespace_scope" to generate additional classes or + other declarations that should be placed in this scope. + + Note that if the line containing the insertion point begins with + whitespace, the same whitespace will be added to every line of the + inserted text. This is useful for languages like Python, where + indentation matters. In these languages, the insertion point comment + should be indented the same amount as any inserted code will need to be + in order to work correctly in that context. + + The code generator that generates the initial file and the one which + inserts into it must both run as part of a single invocation of protoc. + Code generators are executed in the order in which they appear on the + command line. + + If |insertion_point| is present, |name| must also be present. + """ + content: builtins.str + """The file contents.""" + @property + def generated_code_info(self) -> google.protobuf.descriptor_pb2.GeneratedCodeInfo: + """Information describing the file content being inserted. If an insertion + point is used, this information will be appropriately offset and inserted + into the code generation metadata for the generated files. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + insertion_point: builtins.str | None = ..., + content: builtins.str | None = ..., + generated_code_info: google.protobuf.descriptor_pb2.GeneratedCodeInfo | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "content", + b"content", + "generated_code_info", + b"generated_code_info", + "insertion_point", + b"insertion_point", + "name", + b"name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "content", + b"content", + "generated_code_info", + b"generated_code_info", + "insertion_point", + b"insertion_point", + "name", + b"name", + ], + ) -> None: ... + + ERROR_FIELD_NUMBER: builtins.int + SUPPORTED_FEATURES_FIELD_NUMBER: builtins.int + MINIMUM_EDITION_FIELD_NUMBER: builtins.int + MAXIMUM_EDITION_FIELD_NUMBER: builtins.int + FILE_FIELD_NUMBER: builtins.int + error: builtins.str + """Error message. If non-empty, code generation failed. The plugin process + should exit with status code zero even if it reports an error in this way. + + This should be used to indicate errors in .proto files which prevent the + code generator from generating correct code. Errors which indicate a + problem in protoc itself -- such as the input CodeGeneratorRequest being + unparseable -- should be reported by writing a message to stderr and + exiting with a non-zero status code. + """ + supported_features: builtins.int + """A bitmask of supported features that the code generator supports. + This is a bitwise "or" of values from the Feature enum. + """ + minimum_edition: builtins.int + """The minimum edition this plugin supports. This will be treated as an + Edition enum, but we want to allow unknown values. It should be specified + according the edition enum value, *not* the edition number. Only takes + effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + """ + maximum_edition: builtins.int + """The maximum edition this plugin supports. This will be treated as an + Edition enum, but we want to allow unknown values. It should be specified + according the edition enum value, *not* the edition number. Only takes + effect for plugins that have FEATURE_SUPPORTS_EDITIONS set. + """ + @property + def file( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CodeGeneratorResponse.File]: ... + def __init__( + self, + *, + error: builtins.str | None = ..., + supported_features: builtins.int | None = ..., + minimum_edition: builtins.int | None = ..., + maximum_edition: builtins.int | None = ..., + file: collections.abc.Iterable[global___CodeGeneratorResponse.File] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "error", + b"error", + "maximum_edition", + b"maximum_edition", + "minimum_edition", + b"minimum_edition", + "supported_features", + b"supported_features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "error", + b"error", + "file", + b"file", + "maximum_edition", + b"maximum_edition", + "minimum_edition", + b"minimum_edition", + "supported_features", + b"supported_features", + ], + ) -> None: ... + +global___CodeGeneratorResponse = CodeGeneratorResponse diff --git a/stubs/protobuf/google/protobuf/descriptor.pyi b/stubs/protobuf/google/protobuf/descriptor.pyi new file mode 100644 index 000000000000..c1fdd5701614 --- /dev/null +++ b/stubs/protobuf/google/protobuf/descriptor.pyi @@ -0,0 +1,382 @@ +from collections.abc import Mapping, Sequence +from typing import Any + +from .descriptor_pb2 import ( + DescriptorProto, + EnumDescriptorProto, + EnumOptions, + EnumValueOptions, + FieldOptions, + FileDescriptorProto, + FileOptions, + MessageOptions, + MethodDescriptorProto, + MethodOptions, + OneofOptions, + ServiceDescriptorProto, + ServiceOptions, +) +from .descriptor_pool import DescriptorPool +from .message import Message + +class Error(Exception): ... +class TypeTransformationError(Error): ... + +class DescriptorMetaclass(type): + def __instancecheck__(cls, obj: object) -> bool: ... + +_internal_create_key: object +_USE_C_DESCRIPTORS: bool + +class DescriptorBase(metaclass=DescriptorMetaclass): + has_options: bool + def __init__(self, file, options, serialized_options, options_class_name) -> None: ... + def GetOptions(self) -> Any: ... # Any: overridden with specific *Options in subclasses + +class _NestedDescriptorBase(DescriptorBase): + name: str + full_name: str + file: FileDescriptor + containing_type: Descriptor | None + def __init__( + self, + options, + options_class_name, + name, + full_name, + file, + containing_type, + serialized_start=None, + serialized_end=None, + serialized_options=None, + ) -> None: ... + def CopyToProto(self, proto: Any) -> None: ... # Any: overridden with specific *Proto in subclasses + +class Descriptor(_NestedDescriptorBase): + fields: Sequence[FieldDescriptor] + fields_by_number: Mapping[int, FieldDescriptor] + fields_by_name: Mapping[str, FieldDescriptor] + @property + def fields_by_camelcase_name(self) -> Mapping[str, FieldDescriptor]: ... + nested_types: Sequence[Descriptor] + nested_types_by_name: Mapping[str, Descriptor] + enum_types: Sequence[EnumDescriptor] + enum_types_by_name: Mapping[str, EnumDescriptor] + enum_values_by_name: dict[str, EnumValueDescriptor] + extensions: Sequence[FieldDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + is_extendable: bool + extension_ranges: list[tuple[int, int]] + oneofs: Sequence[OneofDescriptor] + oneofs_by_name: Mapping[str, OneofDescriptor] + def __init__( + self, + name: str, + full_name: str, + filename: str | None, + containing_type: Descriptor | None, + fields: list[FieldDescriptor], + nested_types: list[FieldDescriptor], + enum_types: list[EnumDescriptor], + extensions: list[FieldDescriptor], + options: MessageOptions | None = None, + serialized_options: bytes | None = None, + is_extendable: bool | None = True, + extension_ranges: list[tuple[int, int]] | None = None, + oneofs: list[OneofDescriptor] | None = None, + file: FileDescriptor | None = None, + serialized_start: int | None = None, + serialized_end: int | None = None, + syntax: str | None = None, + is_map_entry: bool = False, + create_key: object | None = None, + ): ... + def EnumValueName(self, enum: str, value: int) -> str: ... + def CopyToProto(self, proto: DescriptorProto) -> None: ... + def GetOptions(self) -> MessageOptions: ... + +class FieldDescriptor(DescriptorBase): + TYPE_DOUBLE: int + TYPE_FLOAT: int + TYPE_INT64: int + TYPE_UINT64: int + TYPE_INT32: int + TYPE_FIXED64: int + TYPE_FIXED32: int + TYPE_BOOL: int + TYPE_STRING: int + TYPE_GROUP: int + TYPE_MESSAGE: int + TYPE_BYTES: int + TYPE_UINT32: int + TYPE_ENUM: int + TYPE_SFIXED32: int + TYPE_SFIXED64: int + TYPE_SINT32: int + TYPE_SINT64: int + MAX_TYPE: int + CPPTYPE_INT32: int + CPPTYPE_INT64: int + CPPTYPE_UINT32: int + CPPTYPE_UINT64: int + CPPTYPE_DOUBLE: int + CPPTYPE_FLOAT: int + CPPTYPE_BOOL: int + CPPTYPE_ENUM: int + CPPTYPE_STRING: int + CPPTYPE_MESSAGE: int + MAX_CPPTYPE: int + LABEL_OPTIONAL: int + LABEL_REQUIRED: int + LABEL_REPEATED: int + MAX_LABEL: int + MAX_FIELD_NUMBER: int + FIRST_RESERVED_FIELD_NUMBER: int + LAST_RESERVED_FIELD_NUMBER: int + def __new__( + cls, + name, + full_name, + index, + number, + type, + cpp_type, + label, + default_value, + message_type, + enum_type, + containing_type, + is_extension, + extension_scope, + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, + ): ... + name: str + full_name: str + index: int + number: int + type: int + cpp_type: int + @property + def is_required(self) -> bool: ... + @property + def is_repeated(self) -> bool: ... + @property + def camelcase_name(self) -> str: ... + @property + def has_presence(self) -> bool: ... + @property + def is_packed(self) -> bool: ... + has_default_value: bool + default_value: Any # Any: str, int, float, bytes, or bool + containing_type: Descriptor | None + message_type: Descriptor | None + enum_type: EnumDescriptor | None + is_extension: bool + extension_scope: Descriptor | None + containing_oneof: OneofDescriptor | None + json_name: str + def __init__( + self, + name, + full_name, + index, + number, + type, + cpp_type, + label, + default_value, + message_type, + enum_type, + containing_type, + is_extension, + extension_scope, + options=None, + serialized_options=None, + has_default_value=True, + containing_oneof=None, + json_name=None, + file=None, + create_key=None, + ) -> None: ... + @staticmethod + def ProtoTypeToCppProtoType(proto_type: int) -> int: ... + def GetOptions(self) -> FieldOptions: ... + +class EnumDescriptor(_NestedDescriptorBase): + def __new__( + cls, + name, + full_name, + filename, + values, + containing_type=None, + options=None, + serialized_options=None, + file=None, + serialized_start=None, + serialized_end=None, + create_key=None, + ): ... + values: Sequence[EnumValueDescriptor] + values_by_name: Mapping[str, EnumValueDescriptor] + values_by_number: Mapping[int, EnumValueDescriptor] + def __init__( + self, + name, + full_name, + filename, + values, + containing_type=None, + options=None, + serialized_options=None, + file=None, + serialized_start=None, + serialized_end=None, + create_key=None, + ) -> None: ... + @property + def is_closed(self) -> bool: ... + def CopyToProto(self, proto: EnumDescriptorProto) -> None: ... + def GetOptions(self) -> EnumOptions: ... + +class EnumValueDescriptor(DescriptorBase): + def __new__(cls, name, index, number, type=None, options=None, serialized_options=None, create_key=None): ... + name: str + index: int + number: int + type: EnumDescriptor + def __init__(self, name, index, number, type=None, options=None, serialized_options=None, create_key=None) -> None: ... + def GetOptions(self) -> EnumValueOptions: ... + +class OneofDescriptor(DescriptorBase): + def __new__(cls, name, full_name, index, containing_type, fields, options=None, serialized_options=None, create_key=None): ... + name: str + full_name: str + index: int + containing_type: Descriptor + fields: Sequence[FieldDescriptor] + def __init__( + self, name, full_name, index, containing_type, fields, options=None, serialized_options=None, create_key=None + ) -> None: ... + def GetOptions(self) -> OneofOptions: ... + +class ServiceDescriptor(_NestedDescriptorBase): + index: int + methods: Sequence[MethodDescriptor] + methods_by_name: Mapping[str, MethodDescriptor] + def __init__( + self, + name: str, + full_name: str, + index: int, + methods: list[MethodDescriptor], + options: ServiceOptions | None = None, + serialized_options: bytes | None = None, + file: FileDescriptor | None = None, + serialized_start: int | None = None, + serialized_end: int | None = None, + create_key: object | None = None, + ): ... + def FindMethodByName(self, name: str) -> MethodDescriptor: ... + def CopyToProto(self, proto: ServiceDescriptorProto) -> None: ... + def GetOptions(self) -> ServiceOptions: ... + +class MethodDescriptor(DescriptorBase): + def __new__( + cls, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, + ): ... + name: str + full_name: str + index: int + containing_service: ServiceDescriptor + input_type: Descriptor + output_type: Descriptor + client_streaming: bool + server_streaming: bool + def __init__( + self, + name, + full_name, + index, + containing_service, + input_type, + output_type, + client_streaming=False, + server_streaming=False, + options=None, + serialized_options=None, + create_key=None, + ) -> None: ... + def CopyToProto(self, proto: MethodDescriptorProto) -> None: ... + def GetOptions(self) -> MethodOptions: ... + +class FileDescriptor(DescriptorBase): + def __new__( + cls, + name, + package, + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, + ): ... + _options: Any + _loaded_options: Any + pool: DescriptorPool + message_types_by_name: Mapping[str, Descriptor] + name: str + package: str + serialized_pb: bytes + enum_types_by_name: Mapping[str, EnumDescriptor] + extensions_by_name: Mapping[str, FieldDescriptor] + services_by_name: Mapping[str, ServiceDescriptor] + dependencies: Sequence[FileDescriptor] + public_dependencies: Sequence[FileDescriptor] + def __init__( + self, + name, + package, + options=None, + serialized_options=None, + serialized_pb=None, + dependencies=None, + public_dependencies=None, + syntax=None, + edition=None, + pool=None, + create_key=None, + ) -> None: ... + def CopyToProto(self, proto: FileDescriptorProto) -> None: ... + def GetOptions(self) -> FileOptions: ... + +def _ParseOptions(message: Message, string: bytes) -> Message: ... +def MakeDescriptor( + desc_proto: DescriptorProto, + package: str = "", + build_file_if_cpp: bool = True, + syntax: str | None = None, + edition: str | None = None, + file_desc: FileDescriptor | None = None, +) -> Descriptor: ... diff --git a/stubs/protobuf/google/protobuf/descriptor_database.pyi b/stubs/protobuf/google/protobuf/descriptor_database.pyi new file mode 100644 index 000000000000..8f0b1927b502 --- /dev/null +++ b/stubs/protobuf/google/protobuf/descriptor_database.pyi @@ -0,0 +1,16 @@ +from typing import Final + +from google.protobuf.descriptor_pb2 import FileDescriptorProto + +__author__: Final[str] + +class Error(Exception): ... +class DescriptorDatabaseConflictingDefinitionError(Error): ... + +class DescriptorDatabase: + def __init__(self) -> None: ... + def Add(self, file_desc_proto: FileDescriptorProto) -> None: ... + def FindFileByName(self, name: str) -> FileDescriptorProto: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptorProto: ... + def FindFileContainingExtension(self, extendee_name: str, extension_number: int) -> FileDescriptorProto | None: ... + def FindAllExtensionNumbers(self, extendee_name: str) -> list[int]: ... diff --git a/stubs/protobuf/google/protobuf/descriptor_pb2.pyi b/stubs/protobuf/google/protobuf/descriptor_pb2.pyi new file mode 100644 index 000000000000..d1150c0618d1 --- /dev/null +++ b/stubs/protobuf/google/protobuf/descriptor_pb2.pyi @@ -0,0 +1,2959 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Author: kenton@google.com (Kenton Varda) + Based on original Protocol Buffers design by + Sanjay Ghemawat, Jeff Dean, and others. + +The messages in this file describe the definitions found in .proto files. +A valid .proto file can be translated directly to a FileDescriptorProto +without any other information (e.g. without reading its imports). +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Edition: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _EditionEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Edition.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + EDITION_UNKNOWN: _Edition.ValueType # 0 + """A placeholder for an unknown edition value.""" + EDITION_LEGACY: _Edition.ValueType # 900 + """A placeholder edition for specifying default behaviors *before* a feature + was first introduced. This is effectively an "infinite past". + """ + EDITION_PROTO2: _Edition.ValueType # 998 + """Legacy syntax "editions". These pre-date editions, but behave much like + distinct editions. These can't be used to specify the edition of proto + files, but feature definitions must supply proto2/proto3 defaults for + backwards compatibility. + """ + EDITION_PROTO3: _Edition.ValueType # 999 + EDITION_2023: _Edition.ValueType # 1000 + """Editions that have been released. The specific values are arbitrary and + should not be depended on, but they will always be time-ordered for easy + comparison. + """ + EDITION_2024: _Edition.ValueType # 1001 + EDITION_1_TEST_ONLY: _Edition.ValueType # 1 + """Placeholder editions for testing feature resolution. These should not be + used or relied on outside of tests. + """ + EDITION_2_TEST_ONLY: _Edition.ValueType # 2 + EDITION_99997_TEST_ONLY: _Edition.ValueType # 99997 + EDITION_99998_TEST_ONLY: _Edition.ValueType # 99998 + EDITION_99999_TEST_ONLY: _Edition.ValueType # 99999 + EDITION_MAX: _Edition.ValueType # 2147483647 + """Placeholder for specifying unbounded edition support. This should only + ever be used by plugins that can expect to never require any changes to + support a new edition. + """ + +class Edition(_Edition, metaclass=_EditionEnumTypeWrapper): + """The full set of known editions.""" + +EDITION_UNKNOWN: Edition.ValueType # 0 +"""A placeholder for an unknown edition value.""" +EDITION_LEGACY: Edition.ValueType # 900 +"""A placeholder edition for specifying default behaviors *before* a feature +was first introduced. This is effectively an "infinite past". +""" +EDITION_PROTO2: Edition.ValueType # 998 +"""Legacy syntax "editions". These pre-date editions, but behave much like +distinct editions. These can't be used to specify the edition of proto +files, but feature definitions must supply proto2/proto3 defaults for +backwards compatibility. +""" +EDITION_PROTO3: Edition.ValueType # 999 +EDITION_2023: Edition.ValueType # 1000 +"""Editions that have been released. The specific values are arbitrary and +should not be depended on, but they will always be time-ordered for easy +comparison. +""" +EDITION_2024: Edition.ValueType # 1001 +EDITION_1_TEST_ONLY: Edition.ValueType # 1 +"""Placeholder editions for testing feature resolution. These should not be +used or relied on outside of tests. +""" +EDITION_2_TEST_ONLY: Edition.ValueType # 2 +EDITION_99997_TEST_ONLY: Edition.ValueType # 99997 +EDITION_99998_TEST_ONLY: Edition.ValueType # 99998 +EDITION_99999_TEST_ONLY: Edition.ValueType # 99999 +EDITION_MAX: Edition.ValueType # 2147483647 +"""Placeholder for specifying unbounded edition support. This should only +ever be used by plugins that can expect to never require any changes to +support a new edition. +""" +global___Edition = Edition + +class _SymbolVisibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _SymbolVisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_SymbolVisibility.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + VISIBILITY_UNSET: _SymbolVisibility.ValueType # 0 + VISIBILITY_LOCAL: _SymbolVisibility.ValueType # 1 + VISIBILITY_EXPORT: _SymbolVisibility.ValueType # 2 + +class SymbolVisibility(_SymbolVisibility, metaclass=_SymbolVisibilityEnumTypeWrapper): + """Describes the 'visibility' of a symbol with respect to the proto import + system. Symbols can only be imported when the visibility rules do not prevent + it (ex: local symbols cannot be imported). Visibility modifiers can only set + on `message` and `enum` as they are the only types available to be referenced + from other files. + """ + +VISIBILITY_UNSET: SymbolVisibility.ValueType # 0 +VISIBILITY_LOCAL: SymbolVisibility.ValueType # 1 +VISIBILITY_EXPORT: SymbolVisibility.ValueType # 2 +global___SymbolVisibility = SymbolVisibility + +@typing.final +class FileDescriptorSet(google.protobuf.message.Message): + """The protocol compiler can output a FileDescriptorSet containing the .proto + files it parses. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_FIELD_NUMBER: builtins.int + @property + def file(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FileDescriptorProto]: ... + def __init__(self, *, file: collections.abc.Iterable[global___FileDescriptorProto] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["file", b"file"]) -> None: ... + +global___FileDescriptorSet = FileDescriptorSet + +@typing.final +class FileDescriptorProto(google.protobuf.message.Message): + """Describes a complete .proto file.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + PACKAGE_FIELD_NUMBER: builtins.int + DEPENDENCY_FIELD_NUMBER: builtins.int + PUBLIC_DEPENDENCY_FIELD_NUMBER: builtins.int + WEAK_DEPENDENCY_FIELD_NUMBER: builtins.int + OPTION_DEPENDENCY_FIELD_NUMBER: builtins.int + MESSAGE_TYPE_FIELD_NUMBER: builtins.int + ENUM_TYPE_FIELD_NUMBER: builtins.int + SERVICE_FIELD_NUMBER: builtins.int + EXTENSION_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SOURCE_CODE_INFO_FIELD_NUMBER: builtins.int + SYNTAX_FIELD_NUMBER: builtins.int + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str + """file name, relative to root of source tree""" + package: builtins.str + """e.g. "foo", "foo.bar", etc.""" + syntax: builtins.str + """The syntax of the proto file. + The supported values are "proto2", "proto3", and "editions". + + If `edition` is present, this value must be "editions". + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + edition: global___Edition.ValueType + """The edition of the proto file. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + @property + def dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Names of files imported by this file.""" + + @property + def public_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Indexes of the public imported files in the dependency list above.""" + + @property + def weak_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Indexes of the weak imported files in the dependency list. + For Google-internal migration only. Do not use. + """ + + @property + def option_dependency(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Names of files imported by this file purely for the purpose of providing + option extensions. These are excluded from the dependency list above. + """ + + @property + def message_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto]: + """All top-level definitions in this file.""" + + @property + def enum_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto]: ... + @property + def service(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ServiceDescriptorProto]: ... + @property + def extension(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldDescriptorProto]: ... + @property + def options(self) -> global___FileOptions: ... + @property + def source_code_info(self) -> global___SourceCodeInfo: + """This field contains optional information about the original source code. + You may safely remove this entire field without harming runtime + functionality of the descriptors -- the information is needed only by + development tools. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + package: builtins.str | None = ..., + dependency: collections.abc.Iterable[builtins.str] | None = ..., + public_dependency: collections.abc.Iterable[builtins.int] | None = ..., + weak_dependency: collections.abc.Iterable[builtins.int] | None = ..., + option_dependency: collections.abc.Iterable[builtins.str] | None = ..., + message_type: collections.abc.Iterable[global___DescriptorProto] | None = ..., + enum_type: collections.abc.Iterable[global___EnumDescriptorProto] | None = ..., + service: collections.abc.Iterable[global___ServiceDescriptorProto] | None = ..., + extension: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + options: global___FileOptions | None = ..., + source_code_info: global___SourceCodeInfo | None = ..., + syntax: builtins.str | None = ..., + edition: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "name", + b"name", + "options", + b"options", + "package", + b"package", + "source_code_info", + b"source_code_info", + "syntax", + b"syntax", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dependency", + b"dependency", + "edition", + b"edition", + "enum_type", + b"enum_type", + "extension", + b"extension", + "message_type", + b"message_type", + "name", + b"name", + "option_dependency", + b"option_dependency", + "options", + b"options", + "package", + b"package", + "public_dependency", + b"public_dependency", + "service", + b"service", + "source_code_info", + b"source_code_info", + "syntax", + b"syntax", + "weak_dependency", + b"weak_dependency", + ], + ) -> None: ... + +global___FileDescriptorProto = FileDescriptorProto + +@typing.final +class DescriptorProto(google.protobuf.message.Message): + """Describes a message type.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ExtensionRange(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_FIELD_NUMBER: builtins.int + END_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + start: builtins.int + """Inclusive.""" + end: builtins.int + """Exclusive.""" + @property + def options(self) -> global___ExtensionRangeOptions: ... + def __init__( + self, + *, + start: builtins.int | None = ..., + end: builtins.int | None = ..., + options: global___ExtensionRangeOptions | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["end", b"end", "options", b"options", "start", b"start"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "options", b"options", "start", b"start"]) -> None: ... + + @typing.final + class ReservedRange(google.protobuf.message.Message): + """Range of reserved tag numbers. Reserved tag numbers may not be used by + fields or extension ranges in the same message. Reserved ranges may + not overlap. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_FIELD_NUMBER: builtins.int + END_FIELD_NUMBER: builtins.int + start: builtins.int + """Inclusive.""" + end: builtins.int + """Exclusive.""" + def __init__(self, *, start: builtins.int | None = ..., end: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + FIELD_FIELD_NUMBER: builtins.int + EXTENSION_FIELD_NUMBER: builtins.int + NESTED_TYPE_FIELD_NUMBER: builtins.int + ENUM_TYPE_FIELD_NUMBER: builtins.int + EXTENSION_RANGE_FIELD_NUMBER: builtins.int + ONEOF_DECL_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + RESERVED_RANGE_FIELD_NUMBER: builtins.int + RESERVED_NAME_FIELD_NUMBER: builtins.int + VISIBILITY_FIELD_NUMBER: builtins.int + name: builtins.str + visibility: global___SymbolVisibility.ValueType + """Support for `export` and `local` keywords on enums.""" + @property + def field(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldDescriptorProto]: ... + @property + def extension(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldDescriptorProto]: ... + @property + def nested_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto]: ... + @property + def enum_type(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto]: ... + @property + def extension_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ExtensionRange]: ... + @property + def oneof_decl( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OneofDescriptorProto]: ... + @property + def options(self) -> global___MessageOptions: ... + @property + def reserved_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DescriptorProto.ReservedRange]: ... + @property + def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Reserved field names, which may not be used by fields in the same message. + A given name may only be reserved once. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + field: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + extension: collections.abc.Iterable[global___FieldDescriptorProto] | None = ..., + nested_type: collections.abc.Iterable[global___DescriptorProto] | None = ..., + enum_type: collections.abc.Iterable[global___EnumDescriptorProto] | None = ..., + extension_range: collections.abc.Iterable[global___DescriptorProto.ExtensionRange] | None = ..., + oneof_decl: collections.abc.Iterable[global___OneofDescriptorProto] | None = ..., + options: global___MessageOptions | None = ..., + reserved_range: collections.abc.Iterable[global___DescriptorProto.ReservedRange] | None = ..., + reserved_name: collections.abc.Iterable[builtins.str] | None = ..., + visibility: global___SymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "options", b"options", "visibility", b"visibility"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "enum_type", + b"enum_type", + "extension", + b"extension", + "extension_range", + b"extension_range", + "field", + b"field", + "name", + b"name", + "nested_type", + b"nested_type", + "oneof_decl", + b"oneof_decl", + "options", + b"options", + "reserved_name", + b"reserved_name", + "reserved_range", + b"reserved_range", + "visibility", + b"visibility", + ], + ) -> None: ... + +global___DescriptorProto = DescriptorProto + +@typing.final +class ExtensionRangeOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _VerificationState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _VerificationStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ExtensionRangeOptions._VerificationState.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DECLARATION: ExtensionRangeOptions._VerificationState.ValueType # 0 + """All the extensions of the range must be declared.""" + UNVERIFIED: ExtensionRangeOptions._VerificationState.ValueType # 1 + + class VerificationState(_VerificationState, metaclass=_VerificationStateEnumTypeWrapper): + """The verification state of the extension range.""" + + DECLARATION: ExtensionRangeOptions.VerificationState.ValueType # 0 + """All the extensions of the range must be declared.""" + UNVERIFIED: ExtensionRangeOptions.VerificationState.ValueType # 1 + + @typing.final + class Declaration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUMBER_FIELD_NUMBER: builtins.int + FULL_NAME_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + RESERVED_FIELD_NUMBER: builtins.int + REPEATED_FIELD_NUMBER: builtins.int + number: builtins.int + """The extension number declared within the extension range.""" + full_name: builtins.str + """The fully-qualified name of the extension field. There must be a leading + dot in front of the full name. + """ + type: builtins.str + """The fully-qualified type name of the extension field. Unlike + Metadata.type, Declaration.type must have a leading dot for messages + and enums. + """ + reserved: builtins.bool + """If true, indicates that the number is reserved in the extension range, + and any extension field with the number will fail to compile. Set this + when a declared extension field is deleted. + """ + repeated: builtins.bool + """If true, indicates that the extension must be defined as repeated. + Otherwise the extension must be defined as optional. + """ + def __init__( + self, + *, + number: builtins.int | None = ..., + full_name: builtins.str | None = ..., + type: builtins.str | None = ..., + reserved: builtins.bool | None = ..., + repeated: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "full_name", b"full_name", "number", b"number", "repeated", b"repeated", "reserved", b"reserved", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "full_name", b"full_name", "number", b"number", "repeated", b"repeated", "reserved", b"reserved", "type", b"type" + ], + ) -> None: ... + + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + DECLARATION_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + VERIFICATION_FIELD_NUMBER: builtins.int + verification: global___ExtensionRangeOptions.VerificationState.ValueType + """The verification state of the range. + TODO: flip the default to DECLARATION once all empty ranges + are marked as UNVERIFIED. + """ + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + @property + def declaration( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ExtensionRangeOptions.Declaration]: + """For external users: DO NOT USE. We are in the process of open sourcing + extension declaration and executing internal cleanups before it can be + used externally. + """ + + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition.""" + + def __init__( + self, + *, + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + declaration: collections.abc.Iterable[global___ExtensionRangeOptions.Declaration] | None = ..., + features: global___FeatureSet | None = ..., + verification: global___ExtensionRangeOptions.VerificationState.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features", "verification", b"verification"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "declaration", + b"declaration", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + "verification", + b"verification", + ], + ) -> None: ... + +global___ExtensionRangeOptions = ExtensionRangeOptions + +@typing.final +class FieldDescriptorProto(google.protobuf.message.Message): + """Describes a field within a message.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldDescriptorProto._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TYPE_DOUBLE: FieldDescriptorProto._Type.ValueType # 1 + """0 is reserved for errors. + Order is weird for historical reasons. + """ + TYPE_FLOAT: FieldDescriptorProto._Type.ValueType # 2 + TYPE_INT64: FieldDescriptorProto._Type.ValueType # 3 + """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + negative values are likely. + """ + TYPE_UINT64: FieldDescriptorProto._Type.ValueType # 4 + TYPE_INT32: FieldDescriptorProto._Type.ValueType # 5 + """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + negative values are likely. + """ + TYPE_FIXED64: FieldDescriptorProto._Type.ValueType # 6 + TYPE_FIXED32: FieldDescriptorProto._Type.ValueType # 7 + TYPE_BOOL: FieldDescriptorProto._Type.ValueType # 8 + TYPE_STRING: FieldDescriptorProto._Type.ValueType # 9 + TYPE_GROUP: FieldDescriptorProto._Type.ValueType # 10 + """Tag-delimited aggregate. + Group type is deprecated and not supported after google.protobuf. However, Proto3 + implementations should still be able to parse the group wire format and + treat group fields as unknown fields. In Editions, the group wire format + can be enabled via the `message_encoding` feature. + """ + TYPE_MESSAGE: FieldDescriptorProto._Type.ValueType # 11 + """Length-delimited aggregate.""" + TYPE_BYTES: FieldDescriptorProto._Type.ValueType # 12 + """New in version 2.""" + TYPE_UINT32: FieldDescriptorProto._Type.ValueType # 13 + TYPE_ENUM: FieldDescriptorProto._Type.ValueType # 14 + TYPE_SFIXED32: FieldDescriptorProto._Type.ValueType # 15 + TYPE_SFIXED64: FieldDescriptorProto._Type.ValueType # 16 + TYPE_SINT32: FieldDescriptorProto._Type.ValueType # 17 + """Uses ZigZag encoding.""" + TYPE_SINT64: FieldDescriptorProto._Type.ValueType # 18 + """Uses ZigZag encoding.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + TYPE_DOUBLE: FieldDescriptorProto.Type.ValueType # 1 + """0 is reserved for errors. + Order is weird for historical reasons. + """ + TYPE_FLOAT: FieldDescriptorProto.Type.ValueType # 2 + TYPE_INT64: FieldDescriptorProto.Type.ValueType # 3 + """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + negative values are likely. + """ + TYPE_UINT64: FieldDescriptorProto.Type.ValueType # 4 + TYPE_INT32: FieldDescriptorProto.Type.ValueType # 5 + """Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + negative values are likely. + """ + TYPE_FIXED64: FieldDescriptorProto.Type.ValueType # 6 + TYPE_FIXED32: FieldDescriptorProto.Type.ValueType # 7 + TYPE_BOOL: FieldDescriptorProto.Type.ValueType # 8 + TYPE_STRING: FieldDescriptorProto.Type.ValueType # 9 + TYPE_GROUP: FieldDescriptorProto.Type.ValueType # 10 + """Tag-delimited aggregate. + Group type is deprecated and not supported after google.protobuf. However, Proto3 + implementations should still be able to parse the group wire format and + treat group fields as unknown fields. In Editions, the group wire format + can be enabled via the `message_encoding` feature. + """ + TYPE_MESSAGE: FieldDescriptorProto.Type.ValueType # 11 + """Length-delimited aggregate.""" + TYPE_BYTES: FieldDescriptorProto.Type.ValueType # 12 + """New in version 2.""" + TYPE_UINT32: FieldDescriptorProto.Type.ValueType # 13 + TYPE_ENUM: FieldDescriptorProto.Type.ValueType # 14 + TYPE_SFIXED32: FieldDescriptorProto.Type.ValueType # 15 + TYPE_SFIXED64: FieldDescriptorProto.Type.ValueType # 16 + TYPE_SINT32: FieldDescriptorProto.Type.ValueType # 17 + """Uses ZigZag encoding.""" + TYPE_SINT64: FieldDescriptorProto.Type.ValueType # 18 + """Uses ZigZag encoding.""" + + class _Label: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _LabelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldDescriptorProto._Label.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + LABEL_OPTIONAL: FieldDescriptorProto._Label.ValueType # 1 + """0 is reserved for errors""" + LABEL_REPEATED: FieldDescriptorProto._Label.ValueType # 3 + LABEL_REQUIRED: FieldDescriptorProto._Label.ValueType # 2 + """The required label is only allowed in google.protobuf. In proto3 and Editions + it's explicitly prohibited. In Editions, the `field_presence` feature + can be used to get this behavior. + """ + + class Label(_Label, metaclass=_LabelEnumTypeWrapper): ... + LABEL_OPTIONAL: FieldDescriptorProto.Label.ValueType # 1 + """0 is reserved for errors""" + LABEL_REPEATED: FieldDescriptorProto.Label.ValueType # 3 + LABEL_REQUIRED: FieldDescriptorProto.Label.ValueType # 2 + """The required label is only allowed in google.protobuf. In proto3 and Editions + it's explicitly prohibited. In Editions, the `field_presence` feature + can be used to get this behavior. + """ + + NAME_FIELD_NUMBER: builtins.int + NUMBER_FIELD_NUMBER: builtins.int + LABEL_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + TYPE_NAME_FIELD_NUMBER: builtins.int + EXTENDEE_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + ONEOF_INDEX_FIELD_NUMBER: builtins.int + JSON_NAME_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + PROTO3_OPTIONAL_FIELD_NUMBER: builtins.int + name: builtins.str + number: builtins.int + label: global___FieldDescriptorProto.Label.ValueType + type: global___FieldDescriptorProto.Type.ValueType + """If type_name is set, this need not be set. If both this and type_name + are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + """ + type_name: builtins.str + """For message and enum types, this is the name of the type. If the name + starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + rules are used to find the type (i.e. first the nested types within this + message are searched, then within the parent, on up to the root + namespace). + """ + extendee: builtins.str + """For extensions, this is the name of the type being extended. It is + resolved in the same manner as type_name. + """ + default_value: builtins.str + """For numeric types, contains the original text representation of the value. + For booleans, "true" or "false". + For strings, contains the default text contents (not escaped in any way). + For bytes, contains the C escaped value. All bytes >= 128 are escaped. + """ + oneof_index: builtins.int + """If set, gives the index of a oneof in the containing type's oneof_decl + list. This field is a member of that oneof. + """ + json_name: builtins.str + """JSON name of this field. The value is set by protocol compiler. If the + user has set a "json_name" option on this field, that option's value + will be used. Otherwise, it's deduced from the field's name by converting + it to camelCase. + """ + proto3_optional: builtins.bool + """If true, this is a proto3 "optional". When a proto3 field is optional, it + tracks presence regardless of field type. + + When proto3_optional is true, this field must belong to a oneof to signal + to old proto3 clients that presence is tracked for this field. This oneof + is known as a "synthetic" oneof, and this field must be its sole member + (each proto3 optional field gets its own synthetic oneof). Synthetic oneofs + exist in the descriptor only, and do not generate any API. Synthetic oneofs + must be ordered after all "real" oneofs. + + For message fields, proto3_optional doesn't create any semantic change, + since non-repeated message fields always track presence. However it still + indicates the semantic detail of whether the user wrote "optional" or not. + This can be useful for round-tripping the .proto file. For consistency we + give message fields a synthetic oneof also, even though it is not required + to track presence. This is especially important because the parser can't + tell if a field is a message or an enum, so it must always create a + synthetic oneof. + + Proto2 optional fields do not set this flag, because they already indicate + optional with `LABEL_OPTIONAL`. + """ + @property + def options(self) -> global___FieldOptions: ... + def __init__( + self, + *, + name: builtins.str | None = ..., + number: builtins.int | None = ..., + label: global___FieldDescriptorProto.Label.ValueType | None = ..., + type: global___FieldDescriptorProto.Type.ValueType | None = ..., + type_name: builtins.str | None = ..., + extendee: builtins.str | None = ..., + default_value: builtins.str | None = ..., + oneof_index: builtins.int | None = ..., + json_name: builtins.str | None = ..., + options: global___FieldOptions | None = ..., + proto3_optional: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "extendee", + b"extendee", + "json_name", + b"json_name", + "label", + b"label", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "proto3_optional", + b"proto3_optional", + "type", + b"type", + "type_name", + b"type_name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "extendee", + b"extendee", + "json_name", + b"json_name", + "label", + b"label", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "proto3_optional", + b"proto3_optional", + "type", + b"type", + "type_name", + b"type_name", + ], + ) -> None: ... + +global___FieldDescriptorProto = FieldDescriptorProto + +@typing.final +class OneofDescriptorProto(google.protobuf.message.Message): + """Describes a oneof.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def options(self) -> global___OneofOptions: ... + def __init__(self, *, name: builtins.str | None = ..., options: global___OneofOptions | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> None: ... + +global___OneofDescriptorProto = OneofDescriptorProto + +@typing.final +class EnumDescriptorProto(google.protobuf.message.Message): + """Describes an enum type.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class EnumReservedRange(google.protobuf.message.Message): + """Range of reserved numeric values. Reserved values may not be used by + entries in the same enum. Reserved ranges may not overlap. + + Note that this is distinct from DescriptorProto.ReservedRange in that it + is inclusive such that it can appropriately represent the entire int32 + domain. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_FIELD_NUMBER: builtins.int + END_FIELD_NUMBER: builtins.int + start: builtins.int + """Inclusive.""" + end: builtins.int + """Inclusive.""" + def __init__(self, *, start: builtins.int | None = ..., end: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end", b"end", "start", b"start"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + RESERVED_RANGE_FIELD_NUMBER: builtins.int + RESERVED_NAME_FIELD_NUMBER: builtins.int + VISIBILITY_FIELD_NUMBER: builtins.int + name: builtins.str + visibility: global___SymbolVisibility.ValueType + """Support for `export` and `local` keywords on enums.""" + @property + def value(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumValueDescriptorProto]: ... + @property + def options(self) -> global___EnumOptions: ... + @property + def reserved_range( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumDescriptorProto.EnumReservedRange]: + """Range of reserved numeric values. Reserved numeric values may not be used + by enum values in the same enum declaration. Reserved ranges may not + overlap. + """ + + @property + def reserved_name(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Reserved enum value names, which may not be reused. A given name may only + be reserved once. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + value: collections.abc.Iterable[global___EnumValueDescriptorProto] | None = ..., + options: global___EnumOptions | None = ..., + reserved_range: collections.abc.Iterable[global___EnumDescriptorProto.EnumReservedRange] | None = ..., + reserved_name: collections.abc.Iterable[builtins.str] | None = ..., + visibility: global___SymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "options", b"options", "visibility", b"visibility"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "name", + b"name", + "options", + b"options", + "reserved_name", + b"reserved_name", + "reserved_range", + b"reserved_range", + "value", + b"value", + "visibility", + b"visibility", + ], + ) -> None: ... + +global___EnumDescriptorProto = EnumDescriptorProto + +@typing.final +class EnumValueDescriptorProto(google.protobuf.message.Message): + """Describes a value within an enum.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + NUMBER_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + name: builtins.str + number: builtins.int + @property + def options(self) -> global___EnumValueOptions: ... + def __init__( + self, + *, + name: builtins.str | None = ..., + number: builtins.int | None = ..., + options: global___EnumValueOptions | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"]) -> None: ... + +global___EnumValueDescriptorProto = EnumValueDescriptorProto + +@typing.final +class ServiceDescriptorProto(google.protobuf.message.Message): + """Describes a service.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + METHOD_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def method(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MethodDescriptorProto]: ... + @property + def options(self) -> global___ServiceOptions: ... + def __init__( + self, + *, + name: builtins.str | None = ..., + method: collections.abc.Iterable[global___MethodDescriptorProto] | None = ..., + options: global___ServiceOptions | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["name", b"name", "options", b"options"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["method", b"method", "name", b"name", "options", b"options"]) -> None: ... + +global___ServiceDescriptorProto = ServiceDescriptorProto + +@typing.final +class MethodDescriptorProto(google.protobuf.message.Message): + """Describes a method of a service.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + INPUT_TYPE_FIELD_NUMBER: builtins.int + OUTPUT_TYPE_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + CLIENT_STREAMING_FIELD_NUMBER: builtins.int + SERVER_STREAMING_FIELD_NUMBER: builtins.int + name: builtins.str + input_type: builtins.str + """Input and output type names. These are resolved in the same way as + FieldDescriptorProto.type_name, but must refer to a message type. + """ + output_type: builtins.str + client_streaming: builtins.bool + """Identifies if client streams multiple client messages""" + server_streaming: builtins.bool + """Identifies if server streams multiple server messages""" + @property + def options(self) -> global___MethodOptions: ... + def __init__( + self, + *, + name: builtins.str | None = ..., + input_type: builtins.str | None = ..., + output_type: builtins.str | None = ..., + options: global___MethodOptions | None = ..., + client_streaming: builtins.bool | None = ..., + server_streaming: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "client_streaming", + b"client_streaming", + "input_type", + b"input_type", + "name", + b"name", + "options", + b"options", + "output_type", + b"output_type", + "server_streaming", + b"server_streaming", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "client_streaming", + b"client_streaming", + "input_type", + b"input_type", + "name", + b"name", + "options", + b"options", + "output_type", + b"output_type", + "server_streaming", + b"server_streaming", + ], + ) -> None: ... + +global___MethodDescriptorProto = MethodDescriptorProto + +@typing.final +class FileOptions(google.protobuf.message.Message): + """Each of the definitions above may have "options" attached. These are + just annotations which may cause code to be generated slightly differently + or may contain hints for code that manipulates protocol messages. + + Clients may define custom options as extensions of the *Options messages. + These extensions may not yet be known at parsing time, so the parser cannot + store the values in them. Instead it stores them in a field in the *Options + message called uninterpreted_option. This field must have the same name + across all *Options messages. We then use this field to populate the + extensions when we build a descriptor, at which point all protos have been + parsed and so all extensions are known. + + Extension numbers for custom options may be chosen as follows: + * For options which will only be used within a single application or + organization, or for experimental options, use field numbers 50000 + through 99999. It is up to you to ensure that you do not use the + same number for multiple options. + * For options which will be published and used publicly by multiple + independent entities, e-mail protobuf-global-extension-registry@google.com + to reserve extension numbers. Simply provide your project name (e.g. + Objective-C plugin) and your project website (if available) -- there's no + need to explain how you intend to use them. Usually you only need one + extension number. You can declare multiple options with only one extension + number by putting them in a sub-message. See the Custom Options section of + the docs for examples: + https://developers.google.com/protocol-buffers/docs/proto#options + If this turns out to be popular, a web service will be set up + to automatically assign option numbers. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _OptimizeMode: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptimizeModeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FileOptions._OptimizeMode.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SPEED: FileOptions._OptimizeMode.ValueType # 1 + """Generate complete code for parsing, serialization,""" + CODE_SIZE: FileOptions._OptimizeMode.ValueType # 2 + """etc. + Use ReflectionOps to implement these methods. + """ + LITE_RUNTIME: FileOptions._OptimizeMode.ValueType # 3 + """Generate code using MessageLite and the lite runtime.""" + + class OptimizeMode(_OptimizeMode, metaclass=_OptimizeModeEnumTypeWrapper): + """Generated classes can be optimized for speed or code size.""" + + SPEED: FileOptions.OptimizeMode.ValueType # 1 + """Generate complete code for parsing, serialization,""" + CODE_SIZE: FileOptions.OptimizeMode.ValueType # 2 + """etc. + Use ReflectionOps to implement these methods. + """ + LITE_RUNTIME: FileOptions.OptimizeMode.ValueType # 3 + """Generate code using MessageLite and the lite runtime.""" + + JAVA_PACKAGE_FIELD_NUMBER: builtins.int + JAVA_OUTER_CLASSNAME_FIELD_NUMBER: builtins.int + JAVA_MULTIPLE_FILES_FIELD_NUMBER: builtins.int + JAVA_GENERATE_EQUALS_AND_HASH_FIELD_NUMBER: builtins.int + JAVA_STRING_CHECK_UTF8_FIELD_NUMBER: builtins.int + OPTIMIZE_FOR_FIELD_NUMBER: builtins.int + GO_PACKAGE_FIELD_NUMBER: builtins.int + CC_GENERIC_SERVICES_FIELD_NUMBER: builtins.int + JAVA_GENERIC_SERVICES_FIELD_NUMBER: builtins.int + PY_GENERIC_SERVICES_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + CC_ENABLE_ARENAS_FIELD_NUMBER: builtins.int + OBJC_CLASS_PREFIX_FIELD_NUMBER: builtins.int + CSHARP_NAMESPACE_FIELD_NUMBER: builtins.int + SWIFT_PREFIX_FIELD_NUMBER: builtins.int + PHP_CLASS_PREFIX_FIELD_NUMBER: builtins.int + PHP_NAMESPACE_FIELD_NUMBER: builtins.int + PHP_METADATA_NAMESPACE_FIELD_NUMBER: builtins.int + RUBY_PACKAGE_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + java_package: builtins.str + """Sets the Java package where classes generated from this .proto will be + placed. By default, the proto package is used, but this is often + inappropriate because proto packages do not normally start with backwards + domain names. + """ + java_outer_classname: builtins.str + """Controls the name of the wrapper Java class generated for the .proto file. + That class will always contain the .proto file's getDescriptor() method as + well as any top-level extensions defined in the .proto file. + If java_multiple_files is disabled, then all the other classes from the + .proto file will be nested inside the single wrapper outer class. + """ + java_multiple_files: builtins.bool + """If enabled, then the Java code generator will generate a separate .java + file for each top-level message, enum, and service defined in the .proto + file. Thus, these types will *not* be nested inside the wrapper class + named by java_outer_classname. However, the wrapper class will still be + generated to contain the file's getDescriptor() method as well as any + top-level extensions defined in the file. + """ + java_generate_equals_and_hash: builtins.bool + """This option does nothing.""" + java_string_check_utf8: builtins.bool + """A proto2 file can set this to true to opt in to UTF-8 checking for Java, + which will throw an exception if invalid UTF-8 is parsed from the wire or + assigned to a string field. + + TODO: clarify exactly what kinds of field types this option + applies to, and update these docs accordingly. + + Proto3 files already perform these checks. Setting the option explicitly to + false has no effect: it cannot be used to opt proto3 files out of UTF-8 + checks. + """ + optimize_for: global___FileOptions.OptimizeMode.ValueType + go_package: builtins.str + """Sets the Go package where structs generated from this .proto will be + placed. If omitted, the Go package will be derived from the following: + - The basename of the package import path, if provided. + - Otherwise, the package statement in the .proto file, if present. + - Otherwise, the basename of the .proto file, without extension. + """ + cc_generic_services: builtins.bool + """Should generic services be generated in each language? "Generic" services + are not specific to any particular RPC system. They are generated by the + main code generators in each language (without additional plugins). + Generic services were the only kind of service generation supported by + early versions of google.protobuf. + + Generic services are now considered deprecated in favor of using plugins + that generate code specific to your particular RPC system. Therefore, + these default to false. Old code which depends on generic services should + explicitly set them to true. + """ + java_generic_services: builtins.bool + py_generic_services: builtins.bool + deprecated: builtins.bool + """Is this file deprecated? + Depending on the target platform, this can emit Deprecated annotations + for everything in the file, or it will be completely ignored; in the very + least, this is a formalization for deprecating files. + """ + cc_enable_arenas: builtins.bool + """Enables the use of arenas for the proto messages in this file. This applies + only to generated classes for C++. + """ + objc_class_prefix: builtins.str + """Sets the objective c class prefix which is prepended to all objective c + generated classes from this .proto. There is no default. + """ + csharp_namespace: builtins.str + """Namespace for generated classes; defaults to the package.""" + swift_prefix: builtins.str + """By default Swift generators will take the proto package and CamelCase it + replacing '.' with underscore and use that to prefix the types/symbols + defined. When this options is provided, they will use this value instead + to prefix the types/symbols defined. + """ + php_class_prefix: builtins.str + """Sets the php class prefix which is prepended to all php generated classes + from this .proto. Default is empty. + """ + php_namespace: builtins.str + """Use this option to change the namespace of php generated classes. Default + is empty. When this option is empty, the package name will be used for + determining the namespace. + """ + php_metadata_namespace: builtins.str + """Use this option to change the namespace of php generated metadata classes. + Default is empty. When this option is empty, the proto file name will be + used for determining the namespace. + """ + ruby_package: builtins.str + """Use this option to change the package of ruby generated classes. Default + is empty. When this option is not set, the package name will be used for + determining the ruby package. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. + See the documentation for the "Options" section above. + """ + + def __init__( + self, + *, + java_package: builtins.str | None = ..., + java_outer_classname: builtins.str | None = ..., + java_multiple_files: builtins.bool | None = ..., + java_generate_equals_and_hash: builtins.bool | None = ..., + java_string_check_utf8: builtins.bool | None = ..., + optimize_for: global___FileOptions.OptimizeMode.ValueType | None = ..., + go_package: builtins.str | None = ..., + cc_generic_services: builtins.bool | None = ..., + java_generic_services: builtins.bool | None = ..., + py_generic_services: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + cc_enable_arenas: builtins.bool | None = ..., + objc_class_prefix: builtins.str | None = ..., + csharp_namespace: builtins.str | None = ..., + swift_prefix: builtins.str | None = ..., + php_class_prefix: builtins.str | None = ..., + php_namespace: builtins.str | None = ..., + php_metadata_namespace: builtins.str | None = ..., + ruby_package: builtins.str | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cc_enable_arenas", + b"cc_enable_arenas", + "cc_generic_services", + b"cc_generic_services", + "csharp_namespace", + b"csharp_namespace", + "deprecated", + b"deprecated", + "features", + b"features", + "go_package", + b"go_package", + "java_generate_equals_and_hash", + b"java_generate_equals_and_hash", + "java_generic_services", + b"java_generic_services", + "java_multiple_files", + b"java_multiple_files", + "java_outer_classname", + b"java_outer_classname", + "java_package", + b"java_package", + "java_string_check_utf8", + b"java_string_check_utf8", + "objc_class_prefix", + b"objc_class_prefix", + "optimize_for", + b"optimize_for", + "php_class_prefix", + b"php_class_prefix", + "php_metadata_namespace", + b"php_metadata_namespace", + "php_namespace", + b"php_namespace", + "py_generic_services", + b"py_generic_services", + "ruby_package", + b"ruby_package", + "swift_prefix", + b"swift_prefix", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "cc_enable_arenas", + b"cc_enable_arenas", + "cc_generic_services", + b"cc_generic_services", + "csharp_namespace", + b"csharp_namespace", + "deprecated", + b"deprecated", + "features", + b"features", + "go_package", + b"go_package", + "java_generate_equals_and_hash", + b"java_generate_equals_and_hash", + "java_generic_services", + b"java_generic_services", + "java_multiple_files", + b"java_multiple_files", + "java_outer_classname", + b"java_outer_classname", + "java_package", + b"java_package", + "java_string_check_utf8", + b"java_string_check_utf8", + "objc_class_prefix", + b"objc_class_prefix", + "optimize_for", + b"optimize_for", + "php_class_prefix", + b"php_class_prefix", + "php_metadata_namespace", + b"php_metadata_namespace", + "php_namespace", + b"php_namespace", + "py_generic_services", + b"py_generic_services", + "ruby_package", + b"ruby_package", + "swift_prefix", + b"swift_prefix", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + +global___FileOptions = FileOptions + +@typing.final +class MessageOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MESSAGE_SET_WIRE_FORMAT_FIELD_NUMBER: builtins.int + NO_STANDARD_DESCRIPTOR_ACCESSOR_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + MAP_ENTRY_FIELD_NUMBER: builtins.int + DEPRECATED_LEGACY_JSON_FIELD_CONFLICTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + message_set_wire_format: builtins.bool + """Set true to use the old proto1 MessageSet wire format for extensions. + This is provided for backwards-compatibility with the MessageSet wire + format. You should not use this for any other reason: It's less + efficient, has fewer features, and is more complicated. + + The message must be defined exactly as follows: + message Foo { + option message_set_wire_format = true; + extensions 4 to max; + } + Note that the message cannot have any defined fields; MessageSets only + have extensions. + + All extensions of your type must be singular messages; e.g. they cannot + be int32s, enums, or repeated messages. + + Because this is an option, the above two restrictions are not enforced by + the protocol compiler. + """ + no_standard_descriptor_accessor: builtins.bool + """Disables the generation of the standard "descriptor()" accessor, which can + conflict with a field of the same name. This is meant to make migration + from proto1 easier; new code should avoid fields named "descriptor". + """ + deprecated: builtins.bool + """Is this message deprecated? + Depending on the target platform, this can emit Deprecated annotations + for the message, or it will be completely ignored; in the very least, + this is a formalization for deprecating messages. + """ + map_entry: builtins.bool + """Whether the message is an automatically generated map entry type for the + maps field. + + For maps fields: + map map_field = 1; + The parsed descriptor looks like: + message MapFieldEntry { + option map_entry = true; + optional KeyType key = 1; + optional ValueType value = 2; + } + repeated MapFieldEntry map_field = 1; + + Implementations may choose not to generate the map_entry=true message, but + use a native map in the target language to hold the keys and values. + The reflection APIs in such implementations still need to work as + if the field is a repeated message field. + + NOTE: Do not set the option in .proto files. Always use the maps syntax + instead. The option should only be implicitly set by the proto compiler + parser. + """ + deprecated_legacy_json_field_conflicts: builtins.bool + """Enable the legacy handling of JSON field name conflicts. This lowercases + and strips underscored from the fields before comparison in proto3 only. + The new behavior takes `json_name` into account and applies to proto2 as + well. + + This should only be used as a temporary measure against broken builds due + to the change in behavior for JSON field name conflicts. + + TODO This is legacy behavior we plan to remove once downstream + teams have had time to migrate. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + message_set_wire_format: builtins.bool | None = ..., + no_standard_descriptor_accessor: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + map_entry: builtins.bool | None = ..., + deprecated_legacy_json_field_conflicts: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "map_entry", + b"map_entry", + "message_set_wire_format", + b"message_set_wire_format", + "no_standard_descriptor_accessor", + b"no_standard_descriptor_accessor", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "map_entry", + b"map_entry", + "message_set_wire_format", + b"message_set_wire_format", + "no_standard_descriptor_accessor", + b"no_standard_descriptor_accessor", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + +global___MessageOptions = MessageOptions + +@typing.final +class FieldOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _CType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._CType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + STRING: FieldOptions._CType.ValueType # 0 + """Default mode.""" + CORD: FieldOptions._CType.ValueType # 1 + """The option [ctype=CORD] may be applied to a non-repeated field of type + "bytes". It indicates that in C++, the data should be stored in a Cord + instead of a string. For very large strings, this may reduce memory + fragmentation. It may also allow better performance when parsing from a + Cord, or when parsing with aliasing enabled, as the parsed Cord may then + alias the original buffer. + """ + STRING_PIECE: FieldOptions._CType.ValueType # 2 + + class CType(_CType, metaclass=_CTypeEnumTypeWrapper): ... + STRING: FieldOptions.CType.ValueType # 0 + """Default mode.""" + CORD: FieldOptions.CType.ValueType # 1 + """The option [ctype=CORD] may be applied to a non-repeated field of type + "bytes". It indicates that in C++, the data should be stored in a Cord + instead of a string. For very large strings, this may reduce memory + fragmentation. It may also allow better performance when parsing from a + Cord, or when parsing with aliasing enabled, as the parsed Cord may then + alias the original buffer. + """ + STRING_PIECE: FieldOptions.CType.ValueType # 2 + + class _JSType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _JSTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._JSType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + JS_NORMAL: FieldOptions._JSType.ValueType # 0 + """Use the default type.""" + JS_STRING: FieldOptions._JSType.ValueType # 1 + """Use JavaScript strings.""" + JS_NUMBER: FieldOptions._JSType.ValueType # 2 + """Use JavaScript numbers.""" + + class JSType(_JSType, metaclass=_JSTypeEnumTypeWrapper): ... + JS_NORMAL: FieldOptions.JSType.ValueType # 0 + """Use the default type.""" + JS_STRING: FieldOptions.JSType.ValueType # 1 + """Use JavaScript strings.""" + JS_NUMBER: FieldOptions.JSType.ValueType # 2 + """Use JavaScript numbers.""" + + class _OptionRetention: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptionRetentionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._OptionRetention.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RETENTION_UNKNOWN: FieldOptions._OptionRetention.ValueType # 0 + RETENTION_RUNTIME: FieldOptions._OptionRetention.ValueType # 1 + RETENTION_SOURCE: FieldOptions._OptionRetention.ValueType # 2 + + class OptionRetention(_OptionRetention, metaclass=_OptionRetentionEnumTypeWrapper): + """If set to RETENTION_SOURCE, the option will be omitted from the binary.""" + + RETENTION_UNKNOWN: FieldOptions.OptionRetention.ValueType # 0 + RETENTION_RUNTIME: FieldOptions.OptionRetention.ValueType # 1 + RETENTION_SOURCE: FieldOptions.OptionRetention.ValueType # 2 + + class _OptionTargetType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _OptionTargetTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FieldOptions._OptionTargetType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TARGET_TYPE_UNKNOWN: FieldOptions._OptionTargetType.ValueType # 0 + TARGET_TYPE_FILE: FieldOptions._OptionTargetType.ValueType # 1 + TARGET_TYPE_EXTENSION_RANGE: FieldOptions._OptionTargetType.ValueType # 2 + TARGET_TYPE_MESSAGE: FieldOptions._OptionTargetType.ValueType # 3 + TARGET_TYPE_FIELD: FieldOptions._OptionTargetType.ValueType # 4 + TARGET_TYPE_ONEOF: FieldOptions._OptionTargetType.ValueType # 5 + TARGET_TYPE_ENUM: FieldOptions._OptionTargetType.ValueType # 6 + TARGET_TYPE_ENUM_ENTRY: FieldOptions._OptionTargetType.ValueType # 7 + TARGET_TYPE_SERVICE: FieldOptions._OptionTargetType.ValueType # 8 + TARGET_TYPE_METHOD: FieldOptions._OptionTargetType.ValueType # 9 + + class OptionTargetType(_OptionTargetType, metaclass=_OptionTargetTypeEnumTypeWrapper): + """This indicates the types of entities that the field may apply to when used + as an option. If it is unset, then the field may be freely used as an + option on any kind of entity. + """ + + TARGET_TYPE_UNKNOWN: FieldOptions.OptionTargetType.ValueType # 0 + TARGET_TYPE_FILE: FieldOptions.OptionTargetType.ValueType # 1 + TARGET_TYPE_EXTENSION_RANGE: FieldOptions.OptionTargetType.ValueType # 2 + TARGET_TYPE_MESSAGE: FieldOptions.OptionTargetType.ValueType # 3 + TARGET_TYPE_FIELD: FieldOptions.OptionTargetType.ValueType # 4 + TARGET_TYPE_ONEOF: FieldOptions.OptionTargetType.ValueType # 5 + TARGET_TYPE_ENUM: FieldOptions.OptionTargetType.ValueType # 6 + TARGET_TYPE_ENUM_ENTRY: FieldOptions.OptionTargetType.ValueType # 7 + TARGET_TYPE_SERVICE: FieldOptions.OptionTargetType.ValueType # 8 + TARGET_TYPE_METHOD: FieldOptions.OptionTargetType.ValueType # 9 + + @typing.final + class EditionDefault(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + edition: global___Edition.ValueType + value: builtins.str + """Textproto value.""" + def __init__(self, *, edition: global___Edition.ValueType | None = ..., value: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["edition", b"edition", "value", b"value"]) -> None: ... + + @typing.final + class FeatureSupport(google.protobuf.message.Message): + """Information about the support window of a feature.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_INTRODUCED_FIELD_NUMBER: builtins.int + EDITION_DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATION_WARNING_FIELD_NUMBER: builtins.int + EDITION_REMOVED_FIELD_NUMBER: builtins.int + edition_introduced: global___Edition.ValueType + """The edition that this feature was first available in. In editions + earlier than this one, the default assigned to EDITION_LEGACY will be + used, and proto files will not be able to override it. + """ + edition_deprecated: global___Edition.ValueType + """The edition this feature becomes deprecated in. Using this after this + edition may trigger warnings. + """ + deprecation_warning: builtins.str + """The deprecation warning text if this feature is used after the edition it + was marked deprecated in. + """ + edition_removed: global___Edition.ValueType + """The edition this feature is no longer available in. In editions after + this one, the last default assigned will be used, and proto files will + not be able to override it. + """ + def __init__( + self, + *, + edition_introduced: global___Edition.ValueType | None = ..., + edition_deprecated: global___Edition.ValueType | None = ..., + deprecation_warning: builtins.str | None = ..., + edition_removed: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecation_warning", + b"deprecation_warning", + "edition_deprecated", + b"edition_deprecated", + "edition_introduced", + b"edition_introduced", + "edition_removed", + b"edition_removed", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecation_warning", + b"deprecation_warning", + "edition_deprecated", + b"edition_deprecated", + "edition_introduced", + b"edition_introduced", + "edition_removed", + b"edition_removed", + ], + ) -> None: ... + + CTYPE_FIELD_NUMBER: builtins.int + PACKED_FIELD_NUMBER: builtins.int + JSTYPE_FIELD_NUMBER: builtins.int + LAZY_FIELD_NUMBER: builtins.int + UNVERIFIED_LAZY_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + WEAK_FIELD_NUMBER: builtins.int + DEBUG_REDACT_FIELD_NUMBER: builtins.int + RETENTION_FIELD_NUMBER: builtins.int + TARGETS_FIELD_NUMBER: builtins.int + EDITION_DEFAULTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + ctype: global___FieldOptions.CType.ValueType + """NOTE: ctype is deprecated. Use `features.(pb.cpp).string_type` instead. + The ctype option instructs the C++ code generator to use a different + representation of the field than it normally would. See the specific + options below. This option is only implemented to support use of + [ctype=CORD] and [ctype=STRING] (the default) on non-repeated fields of + type "bytes" in the open source release. + TODO: make ctype actually deprecated. + """ + packed: builtins.bool + """The packed option can be enabled for repeated primitive fields to enable + a more efficient representation on the wire. Rather than repeatedly + writing the tag and type for each element, the entire array is encoded as + a single length-delimited blob. In proto3, only explicit setting it to + false will avoid using packed encoding. This option is prohibited in + Editions, but the `repeated_field_encoding` feature can be used to control + the behavior. + """ + jstype: global___FieldOptions.JSType.ValueType + """The jstype option determines the JavaScript type used for values of the + field. The option is permitted only for 64 bit integral and fixed types + (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + is represented as JavaScript string, which avoids loss of precision that + can happen when a large value is converted to a floating point JavaScript. + Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + use the JavaScript "number" type. The behavior of the default option + JS_NORMAL is implementation dependent. + + This option is an enum to permit additional types to be added, e.g. + goog.math.Integer. + """ + lazy: builtins.bool + """Should this field be parsed lazily? Lazy applies only to message-type + fields. It means that when the outer message is initially parsed, the + inner message's contents will not be parsed but instead stored in encoded + form. The inner message will actually be parsed when it is first accessed. + + This is only a hint. Implementations are free to choose whether to use + eager or lazy parsing regardless of the value of this option. However, + setting this option true suggests that the protocol author believes that + using lazy parsing on this field is worth the additional bookkeeping + overhead typically needed to implement it. + + This option does not affect the public interface of any generated code; + all method signatures remain the same. Furthermore, thread-safety of the + interface is not affected by this option; const methods remain safe to + call from multiple threads concurrently, while non-const methods continue + to require exclusive access. + + Note that lazy message fields are still eagerly verified to check + ill-formed wireformat or missing required fields. Calling IsInitialized() + on the outer message would fail if the inner message has missing required + fields. Failed verification would result in parsing failure (except when + uninitialized messages are acceptable). + """ + unverified_lazy: builtins.bool + """unverified_lazy does no correctness checks on the byte stream. This should + only be used where lazy with verification is prohibitive for performance + reasons. + """ + deprecated: builtins.bool + """Is this field deprecated? + Depending on the target platform, this can emit Deprecated annotations + for accessors, or it will be completely ignored; in the very least, this + is a formalization for deprecating fields. + """ + weak: builtins.bool + """DEPRECATED. DO NOT USE! + For Google-internal migration only. Do not use. + """ + debug_redact: builtins.bool + """Indicate that the field value should not be printed out when using debug + formats, e.g. when the field contains sensitive credentials. + """ + retention: global___FieldOptions.OptionRetention.ValueType + @property + def targets( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___FieldOptions.OptionTargetType.ValueType]: ... + @property + def edition_defaults( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___FieldOptions.EditionDefault]: ... + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def feature_support(self) -> global___FieldOptions.FeatureSupport: ... + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + ctype: global___FieldOptions.CType.ValueType | None = ..., + packed: builtins.bool | None = ..., + jstype: global___FieldOptions.JSType.ValueType | None = ..., + lazy: builtins.bool | None = ..., + unverified_lazy: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + weak: builtins.bool | None = ..., + debug_redact: builtins.bool | None = ..., + retention: global___FieldOptions.OptionRetention.ValueType | None = ..., + targets: collections.abc.Iterable[global___FieldOptions.OptionTargetType.ValueType] | None = ..., + edition_defaults: collections.abc.Iterable[global___FieldOptions.EditionDefault] | None = ..., + features: global___FeatureSet | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ctype", + b"ctype", + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + "jstype", + b"jstype", + "lazy", + b"lazy", + "packed", + b"packed", + "retention", + b"retention", + "unverified_lazy", + b"unverified_lazy", + "weak", + b"weak", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ctype", + b"ctype", + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "edition_defaults", + b"edition_defaults", + "feature_support", + b"feature_support", + "features", + b"features", + "jstype", + b"jstype", + "lazy", + b"lazy", + "packed", + b"packed", + "retention", + b"retention", + "targets", + b"targets", + "uninterpreted_option", + b"uninterpreted_option", + "unverified_lazy", + b"unverified_lazy", + "weak", + b"weak", + ], + ) -> None: ... + +global___FieldOptions = FieldOptions + +@typing.final +class OneofOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["features", b"features", "uninterpreted_option", b"uninterpreted_option"] + ) -> None: ... + +global___OneofOptions = OneofOptions + +@typing.final +class EnumOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ALLOW_ALIAS_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATED_LEGACY_JSON_FIELD_CONFLICTS_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + allow_alias: builtins.bool + """Set this option to true to allow mapping different tag names to the same + value. + """ + deprecated: builtins.bool + """Is this enum deprecated? + Depending on the target platform, this can emit Deprecated annotations + for the enum, or it will be completely ignored; in the very least, this + is a formalization for deprecating enums. + """ + deprecated_legacy_json_field_conflicts: builtins.bool + """Enable the legacy handling of JSON field name conflicts. This lowercases + and strips underscored from the fields before comparison in proto3 only. + The new behavior takes `json_name` into account and applies to proto2 as + well. + TODO Remove this legacy behavior once downstream teams have + had time to migrate. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + allow_alias: builtins.bool | None = ..., + deprecated: builtins.bool | None = ..., + deprecated_legacy_json_field_conflicts: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "allow_alias", + b"allow_alias", + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allow_alias", + b"allow_alias", + "deprecated", + b"deprecated", + "deprecated_legacy_json_field_conflicts", + b"deprecated_legacy_json_field_conflicts", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + +global___EnumOptions = EnumOptions + +@typing.final +class EnumValueOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEPRECATED_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + DEBUG_REDACT_FIELD_NUMBER: builtins.int + FEATURE_SUPPORT_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + deprecated: builtins.bool + """Is this enum value deprecated? + Depending on the target platform, this can emit Deprecated annotations + for the enum value, or it will be completely ignored; in the very least, + this is a formalization for deprecating enum values. + """ + debug_redact: builtins.bool + """Indicate that fields annotated with this enum value should not be printed + out when using debug formats, e.g. when the field contains sensitive + credentials. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def feature_support(self) -> global___FieldOptions.FeatureSupport: + """Information about the support window of a feature value.""" + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + deprecated: builtins.bool | None = ..., + features: global___FeatureSet | None = ..., + debug_redact: builtins.bool | None = ..., + feature_support: global___FieldOptions.FeatureSupport | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "debug_redact", + b"debug_redact", + "deprecated", + b"deprecated", + "feature_support", + b"feature_support", + "features", + b"features", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + +global___EnumValueOptions = EnumValueOptions + +@typing.final +class ServiceOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + deprecated: builtins.bool + """Note: Field numbers 1 through 32 are reserved for Google's internal RPC + framework. We apologize for hoarding these numbers to ourselves, but + we were already using them long before we decided to release Protocol + Buffers. + + Is this service deprecated? + Depending on the target platform, this can emit Deprecated annotations + for the service, or it will be completely ignored; in the very least, + this is a formalization for deprecating services. + """ + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + features: global___FeatureSet | None = ..., + deprecated: builtins.bool | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["deprecated", b"deprecated", "features", b"features"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "features", b"features", "uninterpreted_option", b"uninterpreted_option" + ], + ) -> None: ... + +global___ServiceOptions = ServiceOptions + +@typing.final +class MethodOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _IdempotencyLevel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _IdempotencyLevelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[MethodOptions._IdempotencyLevel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + IDEMPOTENCY_UNKNOWN: MethodOptions._IdempotencyLevel.ValueType # 0 + NO_SIDE_EFFECTS: MethodOptions._IdempotencyLevel.ValueType # 1 + """implies idempotent""" + IDEMPOTENT: MethodOptions._IdempotencyLevel.ValueType # 2 + """idempotent, but may have side effects""" + + class IdempotencyLevel(_IdempotencyLevel, metaclass=_IdempotencyLevelEnumTypeWrapper): + """Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + or neither? HTTP based RPC implementation may choose GET verb for safe + methods, and PUT verb for idempotent methods instead of the default POST. + """ + + IDEMPOTENCY_UNKNOWN: MethodOptions.IdempotencyLevel.ValueType # 0 + NO_SIDE_EFFECTS: MethodOptions.IdempotencyLevel.ValueType # 1 + """implies idempotent""" + IDEMPOTENT: MethodOptions.IdempotencyLevel.ValueType # 2 + """idempotent, but may have side effects""" + + DEPRECATED_FIELD_NUMBER: builtins.int + IDEMPOTENCY_LEVEL_FIELD_NUMBER: builtins.int + FEATURES_FIELD_NUMBER: builtins.int + UNINTERPRETED_OPTION_FIELD_NUMBER: builtins.int + deprecated: builtins.bool + """Note: Field numbers 1 through 32 are reserved for Google's internal RPC + framework. We apologize for hoarding these numbers to ourselves, but + we were already using them long before we decided to release Protocol + Buffers. + + Is this method deprecated? + Depending on the target platform, this can emit Deprecated annotations + for the method, or it will be completely ignored; in the very least, + this is a formalization for deprecating methods. + """ + idempotency_level: global___MethodOptions.IdempotencyLevel.ValueType + @property + def features(self) -> global___FeatureSet: + """Any features defined in the specific edition. + WARNING: This field should only be used by protobuf plugins or special + cases like the proto compiler. Other uses are discouraged and + developers should rely on the protoreflect APIs for their client language. + """ + + @property + def uninterpreted_option( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption]: + """The parser stores options it doesn't recognize here. See above.""" + + def __init__( + self, + *, + deprecated: builtins.bool | None = ..., + idempotency_level: global___MethodOptions.IdempotencyLevel.ValueType | None = ..., + features: global___FeatureSet | None = ..., + uninterpreted_option: collections.abc.Iterable[global___UninterpretedOption] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "features", b"features", "idempotency_level", b"idempotency_level" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", + b"deprecated", + "features", + b"features", + "idempotency_level", + b"idempotency_level", + "uninterpreted_option", + b"uninterpreted_option", + ], + ) -> None: ... + +global___MethodOptions = MethodOptions + +@typing.final +class UninterpretedOption(google.protobuf.message.Message): + """A message representing a option the parser does not recognize. This only + appears in options protos created by the compiler::Parser class. + DescriptorPool resolves these when building Descriptor objects. Therefore, + options protos in descriptor objects (e.g. returned by Descriptor::options(), + or produced by Descriptor::CopyTo()) will never have UninterpretedOptions + in them. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class NamePart(google.protobuf.message.Message): + """The name of the uninterpreted option. Each string represents a segment in + a dot-separated name. is_extension is true iff a segment represents an + extension (denoted with parentheses in options specs in .proto files). + E.g.,{ ["foo", false], ["bar.baz", true], ["moo", false] } represents + "foo.(bar.baz).moo". + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_PART_FIELD_NUMBER: builtins.int + IS_EXTENSION_FIELD_NUMBER: builtins.int + name_part: builtins.str + is_extension: builtins.bool + def __init__(self, *, name_part: builtins.str | None = ..., is_extension: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["is_extension", b"is_extension", "name_part", b"name_part"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["is_extension", b"is_extension", "name_part", b"name_part"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + IDENTIFIER_VALUE_FIELD_NUMBER: builtins.int + POSITIVE_INT_VALUE_FIELD_NUMBER: builtins.int + NEGATIVE_INT_VALUE_FIELD_NUMBER: builtins.int + DOUBLE_VALUE_FIELD_NUMBER: builtins.int + STRING_VALUE_FIELD_NUMBER: builtins.int + AGGREGATE_VALUE_FIELD_NUMBER: builtins.int + identifier_value: builtins.str + """The value of the uninterpreted option, in whatever type the tokenizer + identified it as during parsing. Exactly one of these should be set. + """ + positive_int_value: builtins.int + negative_int_value: builtins.int + double_value: builtins.float + string_value: builtins.bytes + aggregate_value: builtins.str + @property + def name( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UninterpretedOption.NamePart]: ... + def __init__( + self, + *, + name: collections.abc.Iterable[global___UninterpretedOption.NamePart] | None = ..., + identifier_value: builtins.str | None = ..., + positive_int_value: builtins.int | None = ..., + negative_int_value: builtins.int | None = ..., + double_value: builtins.float | None = ..., + string_value: builtins.bytes | None = ..., + aggregate_value: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "aggregate_value", + b"aggregate_value", + "double_value", + b"double_value", + "identifier_value", + b"identifier_value", + "negative_int_value", + b"negative_int_value", + "positive_int_value", + b"positive_int_value", + "string_value", + b"string_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "aggregate_value", + b"aggregate_value", + "double_value", + b"double_value", + "identifier_value", + b"identifier_value", + "name", + b"name", + "negative_int_value", + b"negative_int_value", + "positive_int_value", + b"positive_int_value", + "string_value", + b"string_value", + ], + ) -> None: ... + +global___UninterpretedOption = UninterpretedOption + +@typing.final +class FeatureSet(google.protobuf.message.Message): + """=================================================================== + Features + + TODO Enums in C++ gencode (and potentially other languages) are + not well scoped. This means that each of the feature enums below can clash + with each other. The short names we've chosen maximize call-site + readability, but leave us very open to this scenario. A future feature will + be designed and implemented to handle this, hopefully before we ever hit a + conflict here. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _FieldPresence: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FieldPresenceEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._FieldPresence.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FIELD_PRESENCE_UNKNOWN: FeatureSet._FieldPresence.ValueType # 0 + EXPLICIT: FeatureSet._FieldPresence.ValueType # 1 + IMPLICIT: FeatureSet._FieldPresence.ValueType # 2 + LEGACY_REQUIRED: FeatureSet._FieldPresence.ValueType # 3 + + class FieldPresence(_FieldPresence, metaclass=_FieldPresenceEnumTypeWrapper): ... + FIELD_PRESENCE_UNKNOWN: FeatureSet.FieldPresence.ValueType # 0 + EXPLICIT: FeatureSet.FieldPresence.ValueType # 1 + IMPLICIT: FeatureSet.FieldPresence.ValueType # 2 + LEGACY_REQUIRED: FeatureSet.FieldPresence.ValueType # 3 + + class _EnumType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EnumTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._EnumType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ENUM_TYPE_UNKNOWN: FeatureSet._EnumType.ValueType # 0 + OPEN: FeatureSet._EnumType.ValueType # 1 + CLOSED: FeatureSet._EnumType.ValueType # 2 + + class EnumType(_EnumType, metaclass=_EnumTypeEnumTypeWrapper): ... + ENUM_TYPE_UNKNOWN: FeatureSet.EnumType.ValueType # 0 + OPEN: FeatureSet.EnumType.ValueType # 1 + CLOSED: FeatureSet.EnumType.ValueType # 2 + + class _RepeatedFieldEncoding: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _RepeatedFieldEncodingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._RepeatedFieldEncoding.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + REPEATED_FIELD_ENCODING_UNKNOWN: FeatureSet._RepeatedFieldEncoding.ValueType # 0 + PACKED: FeatureSet._RepeatedFieldEncoding.ValueType # 1 + EXPANDED: FeatureSet._RepeatedFieldEncoding.ValueType # 2 + + class RepeatedFieldEncoding(_RepeatedFieldEncoding, metaclass=_RepeatedFieldEncodingEnumTypeWrapper): ... + REPEATED_FIELD_ENCODING_UNKNOWN: FeatureSet.RepeatedFieldEncoding.ValueType # 0 + PACKED: FeatureSet.RepeatedFieldEncoding.ValueType # 1 + EXPANDED: FeatureSet.RepeatedFieldEncoding.ValueType # 2 + + class _Utf8Validation: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _Utf8ValidationEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._Utf8Validation.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UTF8_VALIDATION_UNKNOWN: FeatureSet._Utf8Validation.ValueType # 0 + VERIFY: FeatureSet._Utf8Validation.ValueType # 2 + NONE: FeatureSet._Utf8Validation.ValueType # 3 + + class Utf8Validation(_Utf8Validation, metaclass=_Utf8ValidationEnumTypeWrapper): ... + UTF8_VALIDATION_UNKNOWN: FeatureSet.Utf8Validation.ValueType # 0 + VERIFY: FeatureSet.Utf8Validation.ValueType # 2 + NONE: FeatureSet.Utf8Validation.ValueType # 3 + + class _MessageEncoding: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _MessageEncodingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._MessageEncoding.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MESSAGE_ENCODING_UNKNOWN: FeatureSet._MessageEncoding.ValueType # 0 + LENGTH_PREFIXED: FeatureSet._MessageEncoding.ValueType # 1 + DELIMITED: FeatureSet._MessageEncoding.ValueType # 2 + + class MessageEncoding(_MessageEncoding, metaclass=_MessageEncodingEnumTypeWrapper): ... + MESSAGE_ENCODING_UNKNOWN: FeatureSet.MessageEncoding.ValueType # 0 + LENGTH_PREFIXED: FeatureSet.MessageEncoding.ValueType # 1 + DELIMITED: FeatureSet.MessageEncoding.ValueType # 2 + + class _JsonFormat: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _JsonFormatEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._JsonFormat.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + JSON_FORMAT_UNKNOWN: FeatureSet._JsonFormat.ValueType # 0 + ALLOW: FeatureSet._JsonFormat.ValueType # 1 + LEGACY_BEST_EFFORT: FeatureSet._JsonFormat.ValueType # 2 + + class JsonFormat(_JsonFormat, metaclass=_JsonFormatEnumTypeWrapper): ... + JSON_FORMAT_UNKNOWN: FeatureSet.JsonFormat.ValueType # 0 + ALLOW: FeatureSet.JsonFormat.ValueType # 1 + LEGACY_BEST_EFFORT: FeatureSet.JsonFormat.ValueType # 2 + + class _EnforceNamingStyle: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EnforceNamingStyleEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[FeatureSet._EnforceNamingStyle.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ENFORCE_NAMING_STYLE_UNKNOWN: FeatureSet._EnforceNamingStyle.ValueType # 0 + STYLE2024: FeatureSet._EnforceNamingStyle.ValueType # 1 + STYLE_LEGACY: FeatureSet._EnforceNamingStyle.ValueType # 2 + + class EnforceNamingStyle(_EnforceNamingStyle, metaclass=_EnforceNamingStyleEnumTypeWrapper): ... + ENFORCE_NAMING_STYLE_UNKNOWN: FeatureSet.EnforceNamingStyle.ValueType # 0 + STYLE2024: FeatureSet.EnforceNamingStyle.ValueType # 1 + STYLE_LEGACY: FeatureSet.EnforceNamingStyle.ValueType # 2 + + @typing.final + class VisibilityFeature(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _DefaultSymbolVisibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _DefaultSymbolVisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ + FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType + ], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 0 + EXPORT_ALL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 1 + """Default pre-EDITION_2024, all UNSET visibility are export.""" + EXPORT_TOP_LEVEL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 2 + """All top-level symbols default to export, nested default to local.""" + LOCAL_ALL: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 3 + """All symbols default to local.""" + STRICT: FeatureSet.VisibilityFeature._DefaultSymbolVisibility.ValueType # 4 + """All symbols local by default. Nested types cannot be exported. + With special case caveat for message { enum {} reserved 1 to max; } + This is the recommended setting for new protos. + """ + + class DefaultSymbolVisibility(_DefaultSymbolVisibility, metaclass=_DefaultSymbolVisibilityEnumTypeWrapper): ... + DEFAULT_SYMBOL_VISIBILITY_UNKNOWN: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 0 + EXPORT_ALL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 1 + """Default pre-EDITION_2024, all UNSET visibility are export.""" + EXPORT_TOP_LEVEL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 2 + """All top-level symbols default to export, nested default to local.""" + LOCAL_ALL: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 3 + """All symbols default to local.""" + STRICT: FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType # 4 + """All symbols local by default. Nested types cannot be exported. + With special case caveat for message { enum {} reserved 1 to max; } + This is the recommended setting for new protos. + """ + + def __init__(self) -> None: ... + + FIELD_PRESENCE_FIELD_NUMBER: builtins.int + ENUM_TYPE_FIELD_NUMBER: builtins.int + REPEATED_FIELD_ENCODING_FIELD_NUMBER: builtins.int + UTF8_VALIDATION_FIELD_NUMBER: builtins.int + MESSAGE_ENCODING_FIELD_NUMBER: builtins.int + JSON_FORMAT_FIELD_NUMBER: builtins.int + ENFORCE_NAMING_STYLE_FIELD_NUMBER: builtins.int + DEFAULT_SYMBOL_VISIBILITY_FIELD_NUMBER: builtins.int + field_presence: global___FeatureSet.FieldPresence.ValueType + enum_type: global___FeatureSet.EnumType.ValueType + repeated_field_encoding: global___FeatureSet.RepeatedFieldEncoding.ValueType + utf8_validation: global___FeatureSet.Utf8Validation.ValueType + message_encoding: global___FeatureSet.MessageEncoding.ValueType + json_format: global___FeatureSet.JsonFormat.ValueType + enforce_naming_style: global___FeatureSet.EnforceNamingStyle.ValueType + default_symbol_visibility: global___FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType + def __init__( + self, + *, + field_presence: global___FeatureSet.FieldPresence.ValueType | None = ..., + enum_type: global___FeatureSet.EnumType.ValueType | None = ..., + repeated_field_encoding: global___FeatureSet.RepeatedFieldEncoding.ValueType | None = ..., + utf8_validation: global___FeatureSet.Utf8Validation.ValueType | None = ..., + message_encoding: global___FeatureSet.MessageEncoding.ValueType | None = ..., + json_format: global___FeatureSet.JsonFormat.ValueType | None = ..., + enforce_naming_style: global___FeatureSet.EnforceNamingStyle.ValueType | None = ..., + default_symbol_visibility: global___FeatureSet.VisibilityFeature.DefaultSymbolVisibility.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "default_symbol_visibility", + b"default_symbol_visibility", + "enforce_naming_style", + b"enforce_naming_style", + "enum_type", + b"enum_type", + "field_presence", + b"field_presence", + "json_format", + b"json_format", + "message_encoding", + b"message_encoding", + "repeated_field_encoding", + b"repeated_field_encoding", + "utf8_validation", + b"utf8_validation", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_symbol_visibility", + b"default_symbol_visibility", + "enforce_naming_style", + b"enforce_naming_style", + "enum_type", + b"enum_type", + "field_presence", + b"field_presence", + "json_format", + b"json_format", + "message_encoding", + b"message_encoding", + "repeated_field_encoding", + b"repeated_field_encoding", + "utf8_validation", + b"utf8_validation", + ], + ) -> None: ... + +global___FeatureSet = FeatureSet + +@typing.final +class FeatureSetDefaults(google.protobuf.message.Message): + """A compiled specification for the defaults of a set of features. These + messages are generated from FeatureSet extensions and can be used to seed + feature resolution. The resolution with this object becomes a simple search + for the closest matching edition, followed by proto merges. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureSetEditionDefault(google.protobuf.message.Message): + """A map from every known edition with a unique set of defaults to its + defaults. Not all editions may be contained here. For a given edition, + the defaults at the closest matching edition ordered at or before it should + be used. This field must be in strict ascending order by edition. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDITION_FIELD_NUMBER: builtins.int + OVERRIDABLE_FEATURES_FIELD_NUMBER: builtins.int + FIXED_FEATURES_FIELD_NUMBER: builtins.int + edition: global___Edition.ValueType + @property + def overridable_features(self) -> global___FeatureSet: + """Defaults of features that can be overridden in this edition.""" + + @property + def fixed_features(self) -> global___FeatureSet: + """Defaults of features that can't be overridden in this edition.""" + + def __init__( + self, + *, + edition: global___Edition.ValueType | None = ..., + overridable_features: global___FeatureSet | None = ..., + fixed_features: global___FeatureSet | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", b"edition", "fixed_features", b"fixed_features", "overridable_features", b"overridable_features" + ], + ) -> None: ... + + DEFAULTS_FIELD_NUMBER: builtins.int + MINIMUM_EDITION_FIELD_NUMBER: builtins.int + MAXIMUM_EDITION_FIELD_NUMBER: builtins.int + minimum_edition: global___Edition.ValueType + """The minimum supported edition (inclusive) when this was constructed. + Editions before this will not have defaults. + """ + maximum_edition: global___Edition.ValueType + """The maximum known edition (inclusive) when this was constructed. Editions + after this will not have reliable defaults. + """ + @property + def defaults( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___FeatureSetDefaults.FeatureSetEditionDefault + ]: ... + def __init__( + self, + *, + defaults: collections.abc.Iterable[global___FeatureSetDefaults.FeatureSetEditionDefault] | None = ..., + minimum_edition: global___Edition.ValueType | None = ..., + maximum_edition: global___Edition.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["maximum_edition", b"maximum_edition", "minimum_edition", b"minimum_edition"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "defaults", b"defaults", "maximum_edition", b"maximum_edition", "minimum_edition", b"minimum_edition" + ], + ) -> None: ... + +global___FeatureSetDefaults = FeatureSetDefaults + +@typing.final +class SourceCodeInfo(google.protobuf.message.Message): + """=================================================================== + Optional source code info + + Encapsulates information about the original source file from which a + FileDescriptorProto was generated. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Location(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATH_FIELD_NUMBER: builtins.int + SPAN_FIELD_NUMBER: builtins.int + LEADING_COMMENTS_FIELD_NUMBER: builtins.int + TRAILING_COMMENTS_FIELD_NUMBER: builtins.int + LEADING_DETACHED_COMMENTS_FIELD_NUMBER: builtins.int + leading_comments: builtins.str + """If this SourceCodeInfo represents a complete declaration, these are any + comments appearing before and after the declaration which appear to be + attached to the declaration. + + A series of line comments appearing on consecutive lines, with no other + tokens appearing on those lines, will be treated as a single comment. + + leading_detached_comments will keep paragraphs of comments that appear + before (but not connected to) the current element. Each paragraph, + separated by empty lines, will be one comment element in the repeated + field. + + Only the comment content is provided; comment markers (e.g. //) are + stripped out. For block comments, leading whitespace and an asterisk + will be stripped from the beginning of each line other than the first. + Newlines are included in the output. + + Examples: + + optional int32 foo = 1; // Comment attached to foo. + // Comment attached to bar. + optional int32 bar = 2; + + optional string baz = 3; + // Comment attached to baz. + // Another line attached to baz. + + // Comment attached to moo. + // + // Another line attached to moo. + optional double moo = 4; + + // Detached comment for corge. This is not leading or trailing comments + // to moo or corge because there are blank lines separating it from + // both. + + // Detached comment for corge paragraph 2. + + optional string corge = 5; + /* Block comment attached + * to corge. Leading asterisks + * will be removed. */ + /* Block comment attached to + * grault. */ + optional int32 grault = 6; + + // ignored detached comments. + """ + trailing_comments: builtins.str + @property + def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Identifies which part of the FileDescriptorProto was defined at this + location. + + Each element is a field number or an index. They form a path from + the root FileDescriptorProto to the place where the definition appears. + For example, this path: + [ 4, 3, 2, 7, 1 ] + refers to: + file.message_type(3) // 4, 3 + .field(7) // 2, 7 + .name() // 1 + This is because FileDescriptorProto.message_type has field number 4: + repeated DescriptorProto message_type = 4; + and DescriptorProto.field has field number 2: + repeated FieldDescriptorProto field = 2; + and FieldDescriptorProto.name has field number 1: + optional string name = 1; + + Thus, the above path gives the location of a field name. If we removed + the last element: + [ 4, 3, 2, 7 ] + this path refers to the whole field declaration (from the beginning + of the label to the terminating semicolon). + """ + + @property + def span(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Always has exactly three or four elements: start line, start column, + end line (optional, otherwise assumed same as start line), end column. + These are packed into a single field for efficiency. Note that line + and column numbers are zero-based -- typically you will want to add + 1 to each before displaying to a user. + """ + + @property + def leading_detached_comments(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + def __init__( + self, + *, + path: collections.abc.Iterable[builtins.int] | None = ..., + span: collections.abc.Iterable[builtins.int] | None = ..., + leading_comments: builtins.str | None = ..., + trailing_comments: builtins.str | None = ..., + leading_detached_comments: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["leading_comments", b"leading_comments", "trailing_comments", b"trailing_comments"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "leading_comments", + b"leading_comments", + "leading_detached_comments", + b"leading_detached_comments", + "path", + b"path", + "span", + b"span", + "trailing_comments", + b"trailing_comments", + ], + ) -> None: ... + + LOCATION_FIELD_NUMBER: builtins.int + @property + def location(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SourceCodeInfo.Location]: + """A Location identifies a piece of source code in a .proto file which + corresponds to a particular definition. This information is intended + to be useful to IDEs, code indexers, documentation generators, and similar + tools. + + For example, say we have a file like: + message Foo { + optional string foo = 1; + } + Let's look at just the field definition: + optional string foo = 1; + ^ ^^ ^^ ^ ^^^ + a bc de f ghi + We have the following locations: + span path represents + [a,i) [ 4, 0, 2, 0 ] The whole field definition. + [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + + Notes: + - A location may refer to a repeated field itself (i.e. not to any + particular index within it). This is used whenever a set of elements are + logically enclosed in a single code segment. For example, an entire + extend block (possibly containing multiple extension definitions) will + have an outer location whose path refers to the "extensions" repeated + field without an index. + - Multiple locations may have the same path. This happens when a single + logical declaration is spread out across multiple places. The most + obvious example is the "extend" block again -- there may be multiple + extend blocks in the same scope, each of which will have the same path. + - A location's span is not always a subset of its parent's span. For + example, the "extendee" of an extension declaration appears at the + beginning of the "extend" block and is shared by all extensions within + the block. + - Just because a location's span is a subset of some other location's span + does not mean that it is a descendant. For example, a "group" defines + both a type and a field in a single declaration. Thus, the locations + corresponding to the type and field and their components will overlap. + - Code which tries to interpret locations should probably be designed to + ignore those that it doesn't understand, as more types of locations could + be recorded in the future. + """ + + def __init__(self, *, location: collections.abc.Iterable[global___SourceCodeInfo.Location] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["location", b"location"]) -> None: ... + +global___SourceCodeInfo = SourceCodeInfo + +@typing.final +class GeneratedCodeInfo(google.protobuf.message.Message): + """Describes the relationship between generated code and its original source + file. A GeneratedCodeInfo message is associated with only one generated + source file, but may contain references to different source .proto files. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Annotation(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Semantic: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _SemanticEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[GeneratedCodeInfo.Annotation._Semantic.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NONE: GeneratedCodeInfo.Annotation._Semantic.ValueType # 0 + """There is no effect or the effect is indescribable.""" + SET: GeneratedCodeInfo.Annotation._Semantic.ValueType # 1 + """The element is set or otherwise mutated.""" + ALIAS: GeneratedCodeInfo.Annotation._Semantic.ValueType # 2 + """An alias to the element is returned.""" + + class Semantic(_Semantic, metaclass=_SemanticEnumTypeWrapper): + """Represents the identified object's effect on the element in the original + .proto file. + """ + + NONE: GeneratedCodeInfo.Annotation.Semantic.ValueType # 0 + """There is no effect or the effect is indescribable.""" + SET: GeneratedCodeInfo.Annotation.Semantic.ValueType # 1 + """The element is set or otherwise mutated.""" + ALIAS: GeneratedCodeInfo.Annotation.Semantic.ValueType # 2 + """An alias to the element is returned.""" + + PATH_FIELD_NUMBER: builtins.int + SOURCE_FILE_FIELD_NUMBER: builtins.int + BEGIN_FIELD_NUMBER: builtins.int + END_FIELD_NUMBER: builtins.int + SEMANTIC_FIELD_NUMBER: builtins.int + source_file: builtins.str + """Identifies the filesystem path to the original source .proto.""" + begin: builtins.int + """Identifies the starting offset in bytes in the generated code + that relates to the identified object. + """ + end: builtins.int + """Identifies the ending offset in bytes in the generated code that + relates to the identified object. The end offset should be one past + the last relevant byte (so the length of the text = end - begin). + """ + semantic: global___GeneratedCodeInfo.Annotation.Semantic.ValueType + @property + def path(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Identifies the element in the original source .proto file. This field + is formatted the same as SourceCodeInfo.Location.path. + """ + + def __init__( + self, + *, + path: collections.abc.Iterable[builtins.int] | None = ..., + source_file: builtins.str | None = ..., + begin: builtins.int | None = ..., + end: builtins.int | None = ..., + semantic: global___GeneratedCodeInfo.Annotation.Semantic.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["begin", b"begin", "end", b"end", "semantic", b"semantic", "source_file", b"source_file"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "begin", b"begin", "end", b"end", "path", b"path", "semantic", b"semantic", "source_file", b"source_file" + ], + ) -> None: ... + + ANNOTATION_FIELD_NUMBER: builtins.int + @property + def annotation( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___GeneratedCodeInfo.Annotation]: + """An Annotation connects some span of text in generated code to an element + of its generating .proto file. + """ + + def __init__(self, *, annotation: collections.abc.Iterable[global___GeneratedCodeInfo.Annotation] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["annotation", b"annotation"]) -> None: ... + +global___GeneratedCodeInfo = GeneratedCodeInfo diff --git a/stubs/protobuf/google/protobuf/descriptor_pool.pyi b/stubs/protobuf/google/protobuf/descriptor_pool.pyi new file mode 100644 index 000000000000..59767efd7817 --- /dev/null +++ b/stubs/protobuf/google/protobuf/descriptor_pool.pyi @@ -0,0 +1,36 @@ +from _typeshed import Unused +from typing import Any +from typing_extensions import Self + +from .descriptor import ( + Descriptor, + EnumDescriptor, + FieldDescriptor, + FileDescriptor, + MethodDescriptor, + OneofDescriptor, + ServiceDescriptor, +) +from .descriptor_pb2 import FeatureSetDefaults, FileDescriptorProto + +class DescriptorPool: + def __new__(cls, descriptor_db: Any = None) -> Self: ... + def __init__( # pyright: ignore[reportInconsistentConstructor] + self, descriptor_db: Any = None, use_deprecated_legacy_json_field_conflicts: Unused = False + ) -> None: ... + def Add(self, file_desc_proto: FileDescriptorProto) -> None: ... + def AddSerializedFile(self, serialized_file_desc_proto: bytes) -> FileDescriptor: ... + def FindFileByName(self, file_name: str) -> FileDescriptor: ... + def FindFileContainingSymbol(self, symbol: str) -> FileDescriptor: ... + def FindMessageTypeByName(self, full_name: str) -> Descriptor: ... + def FindEnumTypeByName(self, full_name: str) -> EnumDescriptor: ... + def FindFieldByName(self, full_name: str) -> FieldDescriptor: ... + def FindOneofByName(self, full_name: str) -> OneofDescriptor: ... + def FindExtensionByName(self, full_name: str) -> FieldDescriptor: ... + def FindExtensionByNumber(self, message_descriptor: Descriptor, number: int) -> FieldDescriptor: ... + def FindAllExtensions(self, message_descriptor: Descriptor) -> list[FieldDescriptor]: ... + def FindServiceByName(self, full_name: str) -> ServiceDescriptor: ... + def FindMethodByName(self, full_name: str) -> MethodDescriptor: ... + def SetFeatureSetDefaults(self, defaults: FeatureSetDefaults) -> None: ... + +def Default() -> DescriptorPool: ... diff --git a/stubs/protobuf/google/protobuf/duration.pyi b/stubs/protobuf/google/protobuf/duration.pyi new file mode 100644 index 000000000000..c7e858fedbf3 --- /dev/null +++ b/stubs/protobuf/google/protobuf/duration.pyi @@ -0,0 +1,16 @@ +from datetime import timedelta + +from google.protobuf.duration_pb2 import Duration + +def from_json_string(value: str) -> Duration: ... +def from_microseconds(micros: float) -> Duration: ... +def from_milliseconds(millis: float) -> Duration: ... +def from_nanoseconds(nanos: float) -> Duration: ... +def from_seconds(seconds: float) -> Duration: ... +def from_timedelta(td: timedelta) -> Duration: ... +def to_json_string(duration: Duration) -> str: ... +def to_microseconds(duration: Duration) -> int: ... +def to_milliseconds(duration: Duration) -> int: ... +def to_nanoseconds(duration: Duration) -> int: ... +def to_seconds(duration: Duration) -> int: ... +def to_timedelta(duration: Duration) -> timedelta: ... diff --git a/stubs/protobuf/google/protobuf/duration_pb2.pyi b/stubs/protobuf/google/protobuf/duration_pb2.pyi new file mode 100644 index 000000000000..2cb846889f4d --- /dev/null +++ b/stubs/protobuf/google/protobuf/duration_pb2.pyi @@ -0,0 +1,126 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.well_known_types +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Duration(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Duration): + """A Duration represents a signed, fixed-length span of time represented + as a count of seconds and fractions of seconds at nanosecond + resolution. It is independent of any calendar and concepts like "day" + or "month". It is related to Timestamp in that the difference between + two Timestamp values is a Duration and it can be added or subtracted + from a Timestamp. Range is approximately +-10,000 years. + + # Examples + + Example 1: Compute Duration from two Timestamps in pseudo code. + + Timestamp start = ...; + Timestamp end = ...; + Duration duration = ...; + + duration.seconds = end.seconds - start.seconds; + duration.nanos = end.nanos - start.nanos; + + if (duration.seconds < 0 && duration.nanos > 0) { + duration.seconds += 1; + duration.nanos -= 1000000000; + } else if (duration.seconds > 0 && duration.nanos < 0) { + duration.seconds -= 1; + duration.nanos += 1000000000; + } + + Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. + + Timestamp start = ...; + Duration duration = ...; + Timestamp end = ...; + + end.seconds = start.seconds + duration.seconds; + end.nanos = start.nanos + duration.nanos; + + if (end.nanos < 0) { + end.seconds -= 1; + end.nanos += 1000000000; + } else if (end.nanos >= 1000000000) { + end.seconds += 1; + end.nanos -= 1000000000; + } + + Example 3: Compute Duration from datetime.timedelta in Python. + + td = datetime.timedelta(days=3, minutes=10) + duration = Duration() + duration.FromTimedelta(td) + + # JSON Mapping + + In JSON format, the Duration type is encoded as a string rather than an + object, where the string ends in the suffix "s" (indicating seconds) and + is preceded by the number of seconds, with nanoseconds expressed as + fractional seconds. For example, 3 seconds with 0 nanoseconds should be + encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should + be expressed in JSON format as "3.000000001s", and 3 seconds and 1 + microsecond should be expressed in JSON format as "3.000001s". + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SECONDS_FIELD_NUMBER: builtins.int + NANOS_FIELD_NUMBER: builtins.int + seconds: builtins.int + """Signed seconds of the span of time. Must be from -315,576,000,000 + to +315,576,000,000 inclusive. Note: these bounds are computed from: + 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years + """ + nanos: builtins.int + """Signed fractions of a second at nanosecond resolution of the span + of time. Durations less than one second are represented with a 0 + `seconds` field and a positive or negative `nanos` field. For durations + of one second or more, a non-zero value for the `nanos` field must be + of the same sign as the `seconds` field. Must be from -999,999,999 + to +999,999,999 inclusive. + """ + def __init__(self, *, seconds: builtins.int | None = ..., nanos: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["nanos", b"nanos", "seconds", b"seconds"]) -> None: ... + +global___Duration = Duration diff --git a/stubs/protobuf/google/protobuf/empty_pb2.pyi b/stubs/protobuf/google/protobuf/empty_pb2.pyi new file mode 100644 index 000000000000..317979279540 --- /dev/null +++ b/stubs/protobuf/google/protobuf/empty_pb2.pyi @@ -0,0 +1,57 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Empty(google.protobuf.message.Message): + """A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to use it as the request + or the response type of an API method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___Empty = Empty diff --git a/stubs/protobuf/google/protobuf/field_mask_pb2.pyi b/stubs/protobuf/google/protobuf/field_mask_pb2.pyi new file mode 100644 index 000000000000..82dea7a11b56 --- /dev/null +++ b/stubs/protobuf/google/protobuf/field_mask_pb2.pyi @@ -0,0 +1,259 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.well_known_types +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class FieldMask(google.protobuf.message.Message, google.protobuf.internal.well_known_types.FieldMask): + """`FieldMask` represents a set of symbolic field paths, for example: + + paths: "f.a" + paths: "f.b.d" + + Here `f` represents a field in some root message, `a` and `b` + fields in the message found in `f`, and `d` a field found in the + message in `f.b`. + + Field masks are used to specify a subset of fields that should be + returned by a get operation or modified by an update operation. + Field masks also have a custom JSON encoding (see below). + + # Field Masks in Projections + + When used in the context of a projection, a response message or + sub-message is filtered by the API to only contain those fields as + specified in the mask. For example, if the mask in the previous + example is applied to a response message as follows: + + f { + a : 22 + b { + d : 1 + x : 2 + } + y : 13 + } + z: 8 + + The result will not contain specific values for fields x,y and z + (their value will be set to the default, and omitted in proto text + output): + + + f { + a : 22 + b { + d : 1 + } + } + + A repeated field is not allowed except at the last position of a + paths string. + + If a FieldMask object is not present in a get operation, the + operation applies to all fields (as if a FieldMask of all fields + had been specified). + + Note that a field mask does not necessarily apply to the + top-level response message. In case of a REST get operation, the + field mask applies directly to the response, but in case of a REST + list operation, the mask instead applies to each individual message + in the returned resource list. In case of a REST custom method, + other definitions may be used. Where the mask applies will be + clearly documented together with its declaration in the API. In + any case, the effect on the returned resource/resources is required + behavior for APIs. + + # Field Masks in Update Operations + + A field mask in update operations specifies which fields of the + targeted resource are going to be updated. The API is required + to only change the values of the fields as specified in the mask + and leave the others untouched. If a resource is passed in to + describe the updated values, the API ignores the values of all + fields not covered by the mask. + + If a repeated field is specified for an update operation, new values will + be appended to the existing repeated field in the target resource. Note that + a repeated field is only allowed in the last position of a `paths` string. + + If a sub-message is specified in the last position of the field mask for an + update operation, then new value will be merged into the existing sub-message + in the target resource. + + For example, given the target message: + + f { + b { + d: 1 + x: 2 + } + c: [1] + } + + And an update message: + + f { + b { + d: 10 + } + c: [2] + } + + then if the field mask is: + + paths: ["f.b", "f.c"] + + then the result will be: + + f { + b { + d: 10 + x: 2 + } + c: [1, 2] + } + + An implementation may provide options to override this default behavior for + repeated and message fields. + + In order to reset a field's value to the default, the field must + be in the mask and set to the default value in the provided resource. + Hence, in order to reset all fields of a resource, provide a default + instance of the resource and set all fields in the mask, or do + not provide a mask as described below. + + If a field mask is not present on update, the operation applies to + all fields (as if a field mask of all fields has been specified). + Note that in the presence of schema evolution, this may mean that + fields the client does not know and has therefore not filled into + the request will be reset to their default. If this is unwanted + behavior, a specific service may require a client to always specify + a field mask, producing an error if not. + + As with get operations, the location of the resource which + describes the updated values in the request message depends on the + operation kind. In any case, the effect of the field mask is + required to be honored by the API. + + ## Considerations for HTTP REST + + The HTTP kind of an update operation which uses a field mask must + be set to PATCH instead of PUT in order to satisfy HTTP semantics + (PUT must only be used for full updates). + + # JSON Encoding of Field Masks + + In JSON, a field mask is encoded as a single string where paths are + separated by a comma. Fields name in each path are converted + to/from lower-camel naming conventions. + + As an example, consider the following message declarations: + + message Profile { + User user = 1; + Photo photo = 2; + } + message User { + string display_name = 1; + string address = 2; + } + + In proto a field mask for `Profile` may look as such: + + mask { + paths: "user.display_name" + paths: "photo" + } + + In JSON, the same mask is represented as below: + + { + mask: "user.displayName,photo" + } + + # Field Masks and Oneof Fields + + Field masks treat fields in oneofs just as regular fields. Consider the + following message: + + message SampleMessage { + oneof test_oneof { + string name = 4; + SubMessage sub_message = 9; + } + } + + The field mask can be: + + mask { + paths: "name" + } + + Or: + + mask { + paths: "sub_message" + } + + Note that oneof type names ("test_oneof" in this case) cannot be used in + paths. + + ## Field Mask Verification + + The implementation of any API method which has a FieldMask type field in the + request should verify the included field paths, and return an + `INVALID_ARGUMENT` error if any path is unmappable. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATHS_FIELD_NUMBER: builtins.int + @property + def paths(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """The set of field mask paths.""" + + def __init__(self, *, paths: collections.abc.Iterable[builtins.str] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["paths", b"paths"]) -> None: ... + +global___FieldMask = FieldMask diff --git a/stubs/protobuf/google/protobuf/internal/__init__.pyi b/stubs/protobuf/google/protobuf/internal/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/protobuf/google/protobuf/internal/api_implementation.pyi b/stubs/protobuf/google/protobuf/internal/api_implementation.pyi new file mode 100644 index 000000000000..1cab529368a5 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/api_implementation.pyi @@ -0,0 +1,2 @@ +def Type() -> str: ... +def IsPythonDefaultSerializationDeterministic() -> bool: ... diff --git a/stubs/protobuf/google/protobuf/internal/builder.pyi b/stubs/protobuf/google/protobuf/internal/builder.pyi new file mode 100644 index 000000000000..a183f4c16d13 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/builder.pyi @@ -0,0 +1,9 @@ +from types import ModuleType +from typing import Any + +from google.protobuf.descriptor import FileDescriptor + +def BuildMessageAndEnumDescriptors(file_des: FileDescriptor, module: dict[str, Any]) -> None: ... +def BuildTopDescriptorsAndMessages(file_des: FileDescriptor, module_name: str, module: dict[str, Any]) -> None: ... +def AddHelpersToExtensions(file_des: FileDescriptor) -> None: ... +def BuildServices(file_des: FileDescriptor, module_name: str, module: ModuleType) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/containers.pyi b/stubs/protobuf/google/protobuf/internal/containers.pyi new file mode 100644 index 000000000000..bb48c5bb6ddd --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/containers.pyi @@ -0,0 +1,149 @@ +from collections.abc import Callable, Iterable, Iterator, MutableMapping, MutableSequence, Sequence +from typing import Any, Protocol, SupportsIndex, TypeVar, overload, type_check_only + +from google.protobuf.descriptor import Descriptor, FieldDescriptor +from google.protobuf.internal.message_listener import MessageListener +from google.protobuf.internal.python_message import GeneratedProtocolMessageType +from google.protobuf.message import Message + +_T = TypeVar("_T") +_K = TypeVar("_K", bound=bool | int | str) +_ScalarV = TypeVar("_ScalarV", bound=bool | int | float | str | bytes) +_MessageV = TypeVar("_MessageV", bound=Message) + +@type_check_only +class _ValueChecker(Protocol[_T]): + def CheckValue(self, proposed_value: _T) -> _T: ... + def DefaultValue(self) -> _T: ... + +class BaseContainer(Sequence[_T]): + __slots__ = ["_message_listener", "_values"] + def __init__(self, message_listener: MessageListener) -> None: ... + + @overload + def __getitem__(self, key: SupportsIndex) -> _T: ... + @overload + def __getitem__(self, key: slice) -> list[_T]: ... + + def __len__(self) -> int: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + # Same as list.sort, the extra sort_function kwarg errors in Python 3 + def sort(self, *, key: Callable[[_T], Any] | None = None, reverse: bool = False) -> None: ... + def reverse(self) -> None: ... + +class RepeatedScalarFieldContainer(BaseContainer[_ScalarV], MutableSequence[_ScalarV]): + __slots__ = ["_type_checker"] + def __init__( + self, message_listener: MessageListener, type_checker: _ValueChecker[_ScalarV], field: FieldDescriptor | None = None + ) -> None: ... + def append(self, value: _ScalarV) -> None: ... + def insert(self, key: int, value: _ScalarV) -> None: ... + def extend(self, elem_seq: Iterable[_ScalarV] | None) -> None: ... + def MergeFrom(self, other: RepeatedScalarFieldContainer[_ScalarV] | Iterable[_ScalarV]) -> None: ... + def remove(self, elem: _ScalarV) -> None: ... + def pop(self, key: int = -1) -> _ScalarV: ... + + @overload + def __setitem__(self, key: int, value: _ScalarV) -> None: ... + @overload + def __setitem__(self, key: slice, value: Iterable[_ScalarV]) -> None: ... + + def __delitem__(self, key: int | slice) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __deepcopy__(self, unused_memo: Any = None) -> RepeatedScalarFieldContainer[_ScalarV]: ... + def __array__(self, dtype: Any = None, copy: bool | None = None) -> Any: ... # Any: numpy types + +class RepeatedCompositeFieldContainer(BaseContainer[_MessageV], MutableSequence[_MessageV]): + __slots__ = ["_message_descriptor"] + def __init__(self, message_listener: MessageListener, message_descriptor: Descriptor) -> None: ... + def add(self, **kwargs: Any) -> _MessageV: ... # Any: field names and values + def append(self, value: _MessageV) -> None: ... + def insert(self, key: int, value: _MessageV) -> None: ... + def extend(self, elem_seq: Iterable[_MessageV]) -> None: ... + def MergeFrom(self, other: RepeatedCompositeFieldContainer[_MessageV] | Iterable[_MessageV]) -> None: ... + def remove(self, elem: _MessageV) -> None: ... + def pop(self, key: int = -1) -> _MessageV: ... + + @overload + def __setitem__(self, key: int, value: _MessageV) -> None: ... + @overload + def __setitem__(self, key: slice, value: Iterable[_MessageV]) -> None: ... + + def __delitem__(self, key: int | slice) -> None: ... + def __eq__(self, other: object) -> bool: ... + +class ScalarMap(MutableMapping[_K, _ScalarV]): + __slots__ = ["_key_checker", "_value_checker", "_values", "_message_listener", "_entry_descriptor"] + def __init__( + self, + message_listener: MessageListener, + key_checker: _ValueChecker[_K], + value_checker: _ValueChecker[_ScalarV], + entry_descriptor: Descriptor, + ) -> None: ... + def __getitem__(self, key: _K) -> _ScalarV: ... + + @overload + def get(self, key: _K, default: None = None) -> _ScalarV | None: ... + @overload + def get(self, key: _K, default: _ScalarV) -> _ScalarV: ... + @overload + def get(self, key: _K, default: _T) -> _ScalarV | _T: ... + + def __setitem__(self, key: _K, value: _ScalarV) -> None: ... + def __delitem__(self, key: _K) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_K]: ... + def __eq__(self, other: object) -> bool: ... + def setdefault(self, key: _K, value: _ScalarV | None = None) -> _ScalarV: ... + def MergeFrom(self, other: ScalarMap[_K, _ScalarV]) -> None: ... + def InvalidateIterators(self) -> None: ... + def clear(self) -> None: ... + def GetEntryClass(self) -> GeneratedProtocolMessageType: ... + +class MessageMap(MutableMapping[_K, _MessageV]): + __slots__ = ["_key_checker", "_values", "_message_listener", "_message_descriptor", "_entry_descriptor"] + def __init__( + self, + message_listener: MessageListener, + message_descriptor: Descriptor, + key_checker: _ValueChecker[_K], + entry_descriptor: Descriptor, + ) -> None: ... + def __getitem__(self, key: _K) -> _MessageV: ... + def get_or_create(self, key: _K) -> _MessageV: ... + + @overload + def get(self, key: _K, default: None = None) -> _MessageV | None: ... + @overload + def get(self, key: _K, default: _MessageV) -> _MessageV: ... + @overload + def get(self, key: _K, default: _T) -> _MessageV | _T: ... + + def __setitem__(self, key: _K, value: _MessageV) -> None: ... + def __delitem__(self, key: _K) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_K]: ... + def __eq__(self, other: object) -> bool: ... + def setdefault(self, key: _K, value: _MessageV | None = None) -> _MessageV: ... + def MergeFrom(self, other: MessageMap[_K, _MessageV]) -> None: ... + def InvalidateIterators(self) -> None: ... + def clear(self) -> None: ... + def GetEntryClass(self) -> GeneratedProtocolMessageType: ... + +class UnknownFieldRef: + def __init__(self, parent: UnknownFieldSet, index: int) -> None: ... + @property + def field_number(self) -> int: ... + @property + def wire_type(self) -> int: ... + @property + def data(self) -> Any: ... # Any: int, bytes, or UnknownFieldSet + +class UnknownFieldSet: + __slots__ = ["_values"] + def __init__(self) -> None: ... + def __getitem__(self, index: int) -> UnknownFieldRef: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[UnknownFieldRef]: ... diff --git a/stubs/protobuf/google/protobuf/internal/decoder.pyi b/stubs/protobuf/google/protobuf/internal/decoder.pyi new file mode 100644 index 000000000000..76cd1e4f3b18 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/decoder.pyi @@ -0,0 +1,67 @@ +from collections.abc import Callable +from typing import Any, TypeAlias + +from google.protobuf.descriptor import Descriptor, FieldDescriptor +from google.protobuf.message import Message + +_Decoder: TypeAlias = Callable[[str, int, int, Message, dict[FieldDescriptor, Any]], int] +_NewDefault: TypeAlias = Callable[[Message], Message] + +def IsDefaultScalarValue(value: Any) -> bool: ... +def ReadTag(buffer: bytes, pos: int) -> tuple[bytes, int]: ... +def DecodeTag(tag_bytes: bytes) -> tuple[int, int]: ... +def EnumDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... + +Int32Decoder: _Decoder +Int64Decoder: _Decoder +UInt32Decoder: _Decoder +UInt64Decoder: _Decoder +SInt32Decoder: _Decoder +SInt64Decoder: _Decoder +Fixed32Decoder: _Decoder +Fixed64Decoder: _Decoder +SFixed32Decoder: _Decoder +SFixed64Decoder: _Decoder +FloatDecoder: _Decoder +DoubleDecoder: _Decoder +BoolDecoder: _Decoder + +def StringDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def BytesDecoder( + field_number: int, + is_repeated: bool, + is_packed: bool, + key: FieldDescriptor, + new_default: _NewDefault, + clear_if_default: bool = False, +) -> _Decoder: ... +def GroupDecoder( + field_number: int, is_repeated: bool, is_packed: bool, key: FieldDescriptor, new_default: _NewDefault +) -> _Decoder: ... +def MessageDecoder( + field_number: int, is_repeated: bool, is_packed: bool, key: FieldDescriptor, new_default: _NewDefault +) -> _Decoder: ... + +MESSAGE_SET_ITEM_TAG: bytes + +def MessageSetItemDecoder(descriptor: Descriptor) -> _Decoder: ... +def UnknownMessageSetItemDecoder() -> _Decoder: ... +def MapDecoder(field_descriptor: FieldDescriptor, new_default: _NewDefault, is_message_map: bool) -> _Decoder: ... + +DEFAULT_RECURSION_LIMIT: int + +def SetRecursionLimit(new_limit: int) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/encoder.pyi b/stubs/protobuf/google/protobuf/internal/encoder.pyi new file mode 100644 index 000000000000..4b481b9d4b23 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/encoder.pyi @@ -0,0 +1,53 @@ +from collections.abc import Callable +from typing import TypeAlias + +from google.protobuf.descriptor import FieldDescriptor + +_Sizer: TypeAlias = Callable[[int, bool, bool], int] + +Int32Sizer: _Sizer +Int64Sizer: _Sizer +EnumSizer: _Sizer +UInt32Sizer: _Sizer +UInt64Sizer: _Sizer +SInt32Sizer: _Sizer +SInt64Sizer: _Sizer +Fixed32Sizer: _Sizer +SFixed32Sizer: _Sizer +FloatSizer: _Sizer +Fixed64Sizer: _Sizer +SFixed64Sizer: _Sizer +DoubleSizer: _Sizer +BoolSizer: _Sizer + +def StringSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def BytesSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def GroupSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def MessageSizer(field_number: int, is_repeated: bool, is_packed: bool) -> _Sizer: ... +def MessageSetItemSizer(field_number: int) -> _Sizer: ... +def MapSizer(field_descriptor: FieldDescriptor, is_message_map: bool) -> _Sizer: ... +def TagBytes(field_number: int, wire_type: int) -> bytes: ... + +_Encoder: TypeAlias = Callable[[Callable[[bytes], int], bytes, bool], int] + +Int32Encoder: _Encoder +Int64Encoder: _Encoder +EnumEncoder: _Encoder +UInt32Encoder: _Encoder +UInt64Encoder: _Encoder +SInt32Encoder: _Encoder +SInt64Encoder: _Encoder +Fixed32Encoder: _Encoder +Fixed64Encoder: _Encoder +SFixed32Encoder: _Encoder +SFixed64Encoder: _Encoder +FloatEncoder: _Encoder +DoubleEncoder: _Encoder + +def BoolEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def StringEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def BytesEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def GroupEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def MessageEncoder(field_number: int, is_repeated: bool, is_packed: bool) -> _Encoder: ... +def MessageSetItemEncoder(field_number: int) -> _Encoder: ... +def MapEncoder(field_descriptor: FieldDescriptor) -> _Encoder: ... diff --git a/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi b/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi new file mode 100644 index 000000000000..6573a8262a81 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi @@ -0,0 +1,23 @@ +from typing import Generic, TypeVar, type_check_only + +from google.protobuf.descriptor import EnumDescriptor + +_V = TypeVar("_V", bound=int) + +# Expose a generic version so that those using mypy-protobuf +# can get autogenerated NewType wrapper around the int values +# NOTE: this doesn't actually inherit from type, +# but mypy doesn't support metaclasses that don't inherit from type, +# so we pretend it does in the stubs... +@type_check_only +class _EnumTypeWrapper(type, Generic[_V]): + DESCRIPTOR: EnumDescriptor + def __init__(self, enum_type: EnumDescriptor) -> None: ... + def Name(self, number: _V) -> str: ... + def Value(self, name: str | bytes) -> _V: ... + def keys(self) -> list[str]: ... + def values(self) -> list[_V]: ... + def items(self) -> list[tuple[str, _V]]: ... + +class EnumTypeWrapper(_EnumTypeWrapper[int]): + ValueType = int diff --git a/stubs/protobuf/google/protobuf/internal/extension_dict.pyi b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi new file mode 100644 index 000000000000..f2a4c1290a8e --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/extension_dict.pyi @@ -0,0 +1,28 @@ +from collections.abc import Iterator +from typing import Any, Generic, TypeVar, type_check_only + +from google.protobuf.descriptor import FieldDescriptor +from google.protobuf.internal.containers import RepeatedCompositeFieldContainer, RepeatedScalarFieldContainer +from google.protobuf.message import Message + +_ContainerMessageT = TypeVar("_ContainerMessageT", bound=Message) +_ExtenderMessageT = TypeVar( + "_ExtenderMessageT", + bound=Message | RepeatedScalarFieldContainer[Any] | RepeatedCompositeFieldContainer[Any] | bool | float | str | bytes, +) + +@type_check_only +class _ExtensionFieldDescriptor(FieldDescriptor, Generic[_ContainerMessageT, _ExtenderMessageT]): ... + +class _ExtensionDict(Generic[_ContainerMessageT]): + def __init__(self, extended_message: _ContainerMessageT) -> None: ... + def __getitem__( + self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT] + ) -> _ExtenderMessageT: ... + def __len__(self) -> int: ... + def __setitem__( + self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT], value: _ExtenderMessageT + ) -> None: ... + def __delitem__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> None: ... + def __iter__(self) -> Iterator[_ExtensionFieldDescriptor[_ContainerMessageT, Any]]: ... + def __contains__(self, extension_handle: _ExtensionFieldDescriptor[_ContainerMessageT, _ExtenderMessageT]) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/internal/field_mask.pyi b/stubs/protobuf/google/protobuf/internal/field_mask.pyi new file mode 100644 index 000000000000..bd0c7f9aef77 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/field_mask.pyi @@ -0,0 +1,14 @@ +from google.protobuf.descriptor import Descriptor, FieldDescriptor as FieldDescriptor +from google.protobuf.message import Message + +class FieldMask: + def ToJsonString(self) -> str: ... + def FromJsonString(self, value: str) -> None: ... + def IsValidForDescriptor(self, message_descriptor: Descriptor) -> bool: ... + def AllFieldsFromDescriptor(self, message_descriptor: Descriptor) -> None: ... + def CanonicalFormFromMask(self, mask: FieldMask) -> None: ... + def Union(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def Intersect(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def MergeMessage( + self, source: Message, destination: Message, replace_message_field: bool = False, replace_repeated_field: bool = False + ) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/message_listener.pyi b/stubs/protobuf/google/protobuf/internal/message_listener.pyi new file mode 100644 index 000000000000..c1c9d3632b4f --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/message_listener.pyi @@ -0,0 +1,5 @@ +class MessageListener: + def Modified(self) -> None: ... + +class NullMessageListener: + def Modified(self) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/python_edition_defaults.pyi b/stubs/protobuf/google/protobuf/internal/python_edition_defaults.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/protobuf/google/protobuf/internal/python_message.pyi b/stubs/protobuf/google/protobuf/internal/python_message.pyi new file mode 100644 index 000000000000..2b37dda98989 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/python_message.pyi @@ -0,0 +1,5 @@ +from typing import Any + +class GeneratedProtocolMessageType(type): + def __new__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> GeneratedProtocolMessageType: ... + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... diff --git a/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi b/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi new file mode 100644 index 000000000000..f77663b566b6 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/testing_refleaks.pyi @@ -0,0 +1,21 @@ +from _typeshed import OptExcInfo +from collections.abc import Callable +from typing import TypeVar +from unittest import TestCase as _TestCase, TestResult + +_T = TypeVar("_T") + +class LocalTestResult(TestResult): + parent_result: TestResult + def __init__(self, parent_result: TestResult) -> None: ... + def addError(self, test: _TestCase, error: OptExcInfo) -> None: ... + def addFailure(self, test: _TestCase, error: OptExcInfo) -> None: ... + def addSkip(self, test: _TestCase, reason: str) -> None: ... + def addDuration(self, test: _TestCase, duration: float) -> None: ... + +class ReferenceLeakCheckerMixin: + NB_RUNS: int + def run(self, result: TestResult | None = None) -> TestResult: ... + +def SkipReferenceLeakChecker(reason: str) -> Callable[[_T], _T]: ... +def TestCase(test_class: _T) -> _T: ... diff --git a/stubs/protobuf/google/protobuf/internal/type_checkers.pyi b/stubs/protobuf/google/protobuf/internal/type_checkers.pyi new file mode 100644 index 000000000000..6486de0124b5 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/type_checkers.pyi @@ -0,0 +1,55 @@ +from collections.abc import Callable +from typing import Any, Generic, TypeVar + +from google.protobuf.descriptor import EnumDescriptor, FieldDescriptor + +_T = TypeVar("_T") + +def TruncateToFourByteFloat(original: float) -> float: ... +def ToShortestFloat(original: float) -> float: ... +def GetTypeChecker( + field: FieldDescriptor, +) -> TypeChecker[Any] | IntValueChecker | EnumValueChecker | UnicodeValueChecker | DoubleValueChecker | BoolValueChecker: ... + +class TypeChecker(Generic[_T]): + def __init__(self, *acceptable_types: _T): ... + def CheckValue(self, proposed_value: _T) -> _T: ... + +class TypeCheckerWithDefault(TypeChecker[_T]): + def __init__(self, default_value: _T, *acceptable_types: _T): ... + def DefaultValue(self) -> _T: ... + +class BoolValueChecker: + def CheckValue(self, proposed_value: bool) -> bool: ... + def DefaultValue(self) -> bool: ... + +class IntValueChecker: + def CheckValue(self, proposed_value: int) -> int: ... + def DefaultValue(self) -> int: ... + +class EnumValueChecker: + def __init__(self, enum_type: EnumDescriptor) -> None: ... + def CheckValue(self, proposed_value: int) -> int: ... + def DefaultValue(self) -> int: ... + +class UnicodeValueChecker: + def CheckValue(self, proposed_value: str) -> str: ... + def DefaultValue(self) -> str: ... + +class Int32ValueChecker(IntValueChecker): ... +class Uint32ValueChecker(IntValueChecker): ... +class Int64ValueChecker(IntValueChecker): ... +class Uint64ValueChecker(IntValueChecker): ... + +class DoubleValueChecker: + def CheckValue(self, proposed_value: float) -> float: ... + def DefaultValue(self) -> float: ... + +class FloatValueChecker(DoubleValueChecker): + def CheckValue(self, proposed_value: float) -> float: ... + +TYPE_TO_BYTE_SIZE_FN: dict[int, Callable[..., int]] +TYPE_TO_ENCODER: dict[int, Callable[..., Any]] +TYPE_TO_SIZER: dict[int, Callable[..., Any]] +TYPE_TO_DECODER: dict[int, Callable[..., Any]] +FIELD_TYPE_TO_WIRE_TYPE: dict[int, int] diff --git a/stubs/protobuf/google/protobuf/internal/well_known_types.pyi b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi new file mode 100644 index 000000000000..6324155b8568 --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/well_known_types.pyi @@ -0,0 +1,106 @@ +from _typeshed import SupportsItems +from collections.abc import Iterable, Iterator, KeysView, Mapping, Sequence +from datetime import datetime, timedelta, tzinfo +from typing import Any as tAny, TypeAlias + +from google.protobuf import struct_pb2 +from google.protobuf.descriptor import Descriptor +from google.protobuf.message import Message as _Message + +class Any: + __slots__ = () + type_url: str + value: bytes + def Pack(self, msg: _Message, type_url_prefix: str = "type.googleapis.com/", deterministic: bool | None = None) -> None: ... + def Unpack(self, msg: _Message) -> bool: ... + def TypeName(self) -> str: ... + def Is(self, descriptor: Descriptor) -> bool: ... + +class Timestamp: + __slots__ = () + def ToJsonString(self) -> str: ... + seconds: int + nanos: int + def FromJsonString(self, value: str) -> None: ... + def GetCurrentTime(self) -> None: ... + def ToNanoseconds(self) -> int: ... + def ToMicroseconds(self) -> int: ... + def ToMilliseconds(self) -> int: ... + def ToSeconds(self) -> int: ... + def FromNanoseconds(self, nanos: int) -> None: ... + def FromMicroseconds(self, micros: int) -> None: ... + def FromMilliseconds(self, millis: int) -> None: ... + def FromSeconds(self, seconds: int) -> None: ... + def ToDatetime(self, tzinfo: tzinfo | None = None) -> datetime: ... + def FromDatetime(self, dt: datetime) -> None: ... + def __add__(self, value: Duration | timedelta) -> datetime: ... + def __radd__(self, value: tAny) -> datetime: ... + def __sub__(self, value: Timestamp | Duration | timedelta) -> datetime | timedelta: ... + def __rsub__(self, dt: datetime) -> timedelta: ... + +class Duration: + __slots__ = () + def ToJsonString(self) -> str: ... + seconds: int + nanos: int + def FromJsonString(self, value: str) -> None: ... + def ToNanoseconds(self) -> int: ... + def ToMicroseconds(self) -> int: ... + def ToMilliseconds(self) -> int: ... + def ToSeconds(self) -> int: ... + def FromNanoseconds(self, nanos: int) -> None: ... + def FromMicroseconds(self, micros: int) -> None: ... + def FromMilliseconds(self, millis: int) -> None: ... + def FromSeconds(self, seconds: int) -> None: ... + def ToTimedelta(self) -> timedelta: ... + def FromTimedelta(self, td: timedelta) -> None: ... + def __add__(self, value: Timestamp | timedelta) -> datetime | timedelta: ... + def __radd__(self, value: tAny) -> datetime | timedelta: ... + def __sub__(self, value: Duration | timedelta) -> timedelta: ... + def __rsub__(self, value: datetime | timedelta) -> datetime | timedelta: ... + +class FieldMask: + __slots__ = () + def ToJsonString(self) -> str: ... + def FromJsonString(self, value: str) -> None: ... + def IsValidForDescriptor(self, message_descriptor: Descriptor) -> bool: ... + def AllFieldsFromDescriptor(self, message_descriptor: Descriptor) -> None: ... + def CanonicalFormFromMask(self, mask: FieldMask) -> None: ... + def Union(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def Intersect(self, mask1: FieldMask, mask2: FieldMask) -> None: ... + def MergeMessage( + self, source: _Message, destination: _Message, replace_message_field: bool = False, replace_repeated_field: bool = False + ) -> None: ... + +_StructValue: TypeAlias = struct_pb2.Struct | struct_pb2.ListValue | str | float | bool | None +_StructValueArg: TypeAlias = _StructValue | Mapping[str, _StructValueArg] | Sequence[_StructValueArg] + +class Struct: + __slots__: tuple[str, ...] = () + def __getitem__(self, key: str) -> _StructValue: ... + def __setitem__(self, key: str, value: _StructValueArg) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> list[_StructValue]: ... + def items(self) -> list[tuple[str, _StructValue]]: ... + def get_or_create_list(self, key: str) -> struct_pb2.ListValue: ... + def get_or_create_struct(self, key: str) -> struct_pb2.Struct: ... + def update(self, dictionary: SupportsItems[str, _StructValueArg]) -> None: ... + +class ListValue: + __slots__: tuple[str, ...] = () + def __len__(self) -> int: ... + def append(self, value: _StructValue) -> None: ... + def extend(self, elem_seq: Iterable[_StructValue]) -> None: ... + def __getitem__(self, index: int) -> _StructValue: ... + def __setitem__(self, index: int, value: _StructValueArg) -> None: ... + def __delitem__(self, key: int) -> None: ... + # Doesn't actually exist at runtime; needed so type checkers understand the class is iterable + def __iter__(self) -> Iterator[_StructValue]: ... + def items(self) -> Iterator[_StructValue]: ... + def add_struct(self) -> struct_pb2.Struct: ... + def add_list(self) -> struct_pb2.ListValue: ... + +WKTBASES: dict[str, type[tAny]] diff --git a/stubs/protobuf/google/protobuf/internal/wire_format.pyi b/stubs/protobuf/google/protobuf/internal/wire_format.pyi new file mode 100644 index 000000000000..0d4aa04031ec --- /dev/null +++ b/stubs/protobuf/google/protobuf/internal/wire_format.pyi @@ -0,0 +1,50 @@ +from google.protobuf.message import Message + +TAG_TYPE_BITS: int +TAG_TYPE_MASK: int +WIRETYPE_VARINT: int +WIRETYPE_FIXED64: int +WIRETYPE_LENGTH_DELIMITED: int +WIRETYPE_START_GROUP: int +WIRETYPE_END_GROUP: int +WIRETYPE_FIXED32: int +INT32_MAX: int +INT32_MIN: int +UINT32_MAX: int +INT64_MAX: int +INT64_MIN: int +UINT64_MAX: int +FORMAT_UINT32_LITTLE_ENDIAN: str +FORMAT_UINT64_LITTLE_ENDIAN: str +FORMAT_FLOAT_LITTLE_ENDIAN: str +FORMAT_DOUBLE_LITTLE_ENDIAN: str + +def PackTag(field_number: int, wire_type: int) -> int: ... +def UnpackTag(tag: int) -> tuple[int, int]: ... +def ZigZagEncode(value: int) -> int: ... +def ZigZagDecode(value: int) -> int: ... +def Int32ByteSize(field_number: int, int32: int) -> int: ... +def Int32ByteSizeNoTag(int32: int) -> int: ... +def Int64ByteSize(field_number: int, int64: int) -> int: ... +def UInt32ByteSize(field_number: int, uint32: int) -> int: ... +def UInt64ByteSize(field_number: int, uint64: int) -> int: ... +def SInt32ByteSize(field_number: int, int32: int) -> int: ... +def SInt64ByteSize(field_number: int, int64: int) -> int: ... +def Fixed32ByteSize(field_number: int, fixed32: int) -> int: ... +def Fixed64ByteSize(field_number: int, fixed64: int) -> int: ... +def SFixed32ByteSize(field_number: int, sfixed32: int) -> int: ... +def SFixed64ByteSize(field_number: int, sfixed64: int) -> int: ... +def FloatByteSize(field_number: int, flt: float) -> int: ... +def DoubleByteSize(field_number: int, double: float) -> int: ... +def BoolByteSize(field_number: int, b: bool) -> int: ... +def EnumByteSize(field_number: int, enum: int) -> int: ... +def StringByteSize(field_number: int, string: str) -> int: ... +def BytesByteSize(field_number: int, b: bytes) -> int: ... +def GroupByteSize(field_number: int, message: Message) -> int: ... +def MessageByteSize(field_number: int, message: Message) -> int: ... +def MessageSetItemByteSize(field_number: int, msg: Message) -> int: ... +def TagByteSize(field_number: int) -> int: ... + +NON_PACKABLE_TYPES: tuple[int, ...] + +def IsTypePackable(field_type: int) -> bool: ... diff --git a/stubs/protobuf/google/protobuf/json_format.pyi b/stubs/protobuf/google/protobuf/json_format.pyi new file mode 100644 index 000000000000..44a21b5a34f9 --- /dev/null +++ b/stubs/protobuf/google/protobuf/json_format.pyi @@ -0,0 +1,43 @@ +from typing import Any, TypeVar + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +class Error(Exception): ... +class SerializeToJsonError(Error): ... +class ParseError(Error): ... +class EnumStringValueParseError(ParseError): ... + +def MessageToJson( + message: Message, + preserving_proto_field_name: bool = False, + indent: int | None = 2, + sort_keys: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, + ensure_ascii: bool = True, + always_print_fields_with_no_presence: bool = False, +) -> str: ... +def MessageToDict( + message: Message, + always_print_fields_with_no_presence: bool = False, + preserving_proto_field_name: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, +) -> dict[str, Any]: ... +def Parse( + text: bytes | str, + message: _MessageT, + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, +) -> _MessageT: ... +def ParseDict( + js_dict: dict[str, Any], + message: _MessageT, + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, +) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/message.pyi b/stubs/protobuf/google/protobuf/message.pyi new file mode 100644 index 000000000000..bca40ddb4667 --- /dev/null +++ b/stubs/protobuf/google/protobuf/message.pyi @@ -0,0 +1,49 @@ +from collections.abc import Sequence +from typing import Any +from typing_extensions import Self + +from google._upb._message import Descriptor as _upb_Descriptor + +from .descriptor import Descriptor, FieldDescriptor +from .internal.extension_dict import _ExtensionDict, _ExtensionFieldDescriptor + +class Error(Exception): ... +class DecodeError(Error): ... +class EncodeError(Error): ... + +class Message: + __slots__: tuple[str, ...] = () + DESCRIPTOR: Descriptor | _upb_Descriptor + def __deepcopy__(self, memo: Any = None) -> Self: ... + def __eq__(self, other_msg: object) -> bool: ... + def __ne__(self, other_msg: object) -> bool: ... + def __contains__(self, field_name_or_key: str) -> bool: ... + def MergeFrom(self, other_msg: Self) -> None: ... + def CopyFrom(self, other_msg: Self) -> None: ... + def Clear(self) -> None: ... + def SetInParent(self) -> None: ... + def IsInitialized(self) -> bool: ... + def MergeFromString(self, serialized: bytes) -> int: ... + def ParseFromString(self, serialized: bytes) -> int: ... + def SerializeToString(self, *, deterministic: bool = ...) -> bytes: ... + def SerializePartialToString(self, *, deterministic: bool = ...) -> bytes: ... + def ListFields(self) -> Sequence[tuple[FieldDescriptor, Any]]: ... # Any: str, int, float, bytes, bool, or Message + # Intentionally left out typing on these three methods, because they are + # stringly typed and it is not useful to call them on a Message directly. + # We prefer more specific typing on individual subclasses of Message + # See https://github.com/dropbox/mypy-protobuf/issues/62 for details + def HasField(self, field_name: Any) -> bool: ... + def ClearField(self, field_name: Any) -> None: ... + def WhichOneof(self, oneof_group: Any) -> Any: ... + def HasExtension(self, field_descriptor: _ExtensionFieldDescriptor[Self, Any]) -> bool: ... + def ClearExtension(self, field_descriptor: _ExtensionFieldDescriptor[Self, Any]) -> None: ... + # The TypeVar must be bound to `Message` or we get mypy errors, so we cannot use `Self` for `Extensions` + @property + def Extensions(self) -> _ExtensionDict[Self]: ... + def UnknownFields(self) -> Any: ... # Any: subclasses return UnknownFieldSet + def DiscardUnknownFields(self) -> None: ... + def ByteSize(self) -> int: ... + @classmethod + def FromString(cls, s: bytes) -> Self: ... + # TODO: check kwargs + def __new__(cls, *args, **kwargs) -> Self: ... diff --git a/stubs/protobuf/google/protobuf/message_factory.pyi b/stubs/protobuf/google/protobuf/message_factory.pyi new file mode 100644 index 000000000000..8a902254d2d9 --- /dev/null +++ b/stubs/protobuf/google/protobuf/message_factory.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable + +from google.protobuf.descriptor import Descriptor +from google.protobuf.descriptor_pb2 import FileDescriptorProto +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +def GetMessageClass(descriptor: Descriptor) -> type[Message]: ... +def GetMessageClassesForFiles(files: Iterable[str], pool: DescriptorPool) -> dict[str, type[Message]]: ... + +class MessageFactory: + pool: DescriptorPool + def __init__(self, pool: DescriptorPool | None = None) -> None: ... + +def GetMessages(file_protos: Iterable[FileDescriptorProto], pool: DescriptorPool | None = None) -> dict[str, type[Message]]: ... diff --git a/stubs/protobuf/google/protobuf/proto.pyi b/stubs/protobuf/google/protobuf/proto.pyi new file mode 100644 index 000000000000..1f1cb47037cc --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto.pyi @@ -0,0 +1,14 @@ +from io import BytesIO +from typing import TypeVar + +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def serialize(message: Message, deterministic: bool | None = None) -> bytes: ... +def parse(message_class: type[_MessageT], payload: bytes) -> _MessageT: ... +def serialize_length_prefixed(message: Message, output: BytesIO) -> None: ... +def parse_length_prefixed(message_class: type[_MessageT], input_bytes: BytesIO) -> _MessageT: ... +def byte_size(message: Message) -> int: ... +def clear_message(message: Message) -> None: ... +def clear_field(message: Message, field_name: str) -> None: ... diff --git a/stubs/protobuf/google/protobuf/proto_builder.pyi b/stubs/protobuf/google/protobuf/proto_builder.pyi new file mode 100644 index 000000000000..b204ba32eb69 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_builder.pyi @@ -0,0 +1,8 @@ +from collections import OrderedDict + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +def MakeSimpleProtoClass( + fields: dict[str, int] | OrderedDict[str, int], full_name: str | None = None, pool: DescriptorPool | None = None +) -> type[Message]: ... diff --git a/stubs/protobuf/google/protobuf/proto_json.pyi b/stubs/protobuf/google/protobuf/proto_json.pyi new file mode 100644 index 000000000000..9a63de676bb1 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_json.pyi @@ -0,0 +1,21 @@ +from typing import Any, TypeVar + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) + +def serialize( + message: Message, + always_print_fields_with_no_presence: bool = False, + preserving_proto_field_name: bool = False, + use_integers_for_enums: bool = False, + descriptor_pool: DescriptorPool | None = None, +) -> dict[str, Any]: ... +def parse( + message_class: type[_MessageT], + js_dict: dict[str, Any], + ignore_unknown_fields: bool = False, + descriptor_pool: DescriptorPool | None = None, + max_recursion_depth: int = 100, +) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/proto_text.pyi b/stubs/protobuf/google/protobuf/proto_text.pyi new file mode 100644 index 000000000000..7ddff9c19e89 --- /dev/null +++ b/stubs/protobuf/google/protobuf/proto_text.pyi @@ -0,0 +1,31 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar + +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +_MessageT = TypeVar("_MessageT", bound=Message) +_MsgFormatter: TypeAlias = Callable[[Message, int, bool], str | None] + +def serialize( + message: Message, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MsgFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> str: ... +def parse( + message_class: type[_MessageT], + text: str | bytes, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, +) -> _MessageT: ... diff --git a/stubs/protobuf/google/protobuf/reflection.pyi b/stubs/protobuf/google/protobuf/reflection.pyi new file mode 100644 index 000000000000..0c700523e712 --- /dev/null +++ b/stubs/protobuf/google/protobuf/reflection.pyi @@ -0,0 +1,10 @@ +from typing import Any + +from google._upb._message import MessageMeta + +MESSAGE_CLASS_CACHE: dict[str, Any] + +class GeneratedProtocolMessageType(MessageMeta): + def __new__( # noqa: Y034 + cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any] + ) -> GeneratedProtocolMessageType: ... diff --git a/stubs/protobuf/google/protobuf/runtime_version.pyi b/stubs/protobuf/google/protobuf/runtime_version.pyi new file mode 100644 index 000000000000..c6e1f8406216 --- /dev/null +++ b/stubs/protobuf/google/protobuf/runtime_version.pyi @@ -0,0 +1,23 @@ +from enum import Enum +from typing import Final + +class Domain(Enum): + GOOGLE_INTERNAL = 1 + PUBLIC = 2 + +OSS_DOMAIN: Final[Domain] +OSS_MAJOR: Final[int] +OSS_MINOR: Final[int] +OSS_PATCH: Final[int] +OSS_SUFFIX: Final[str] +DOMAIN: Final[Domain] +MAJOR: Final[int] +MINOR: Final[int] +PATCH: Final[int] +SUFFIX: Final[str] + +class VersionError(Exception): ... + +def ValidateProtobufRuntimeVersion( + gen_domain: Domain, gen_major: int, gen_minor: int, gen_patch: int, gen_suffix: str, location: str +) -> None: ... diff --git a/stubs/protobuf/google/protobuf/service_reflection.pyi b/stubs/protobuf/google/protobuf/service_reflection.pyi new file mode 100644 index 000000000000..c9949d13baca --- /dev/null +++ b/stubs/protobuf/google/protobuf/service_reflection.pyi @@ -0,0 +1,7 @@ +from typing import Any + +class GeneratedServiceType(type): + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... + +class GeneratedServiceStubType(GeneratedServiceType): + def __init__(cls, name: str, bases: tuple[type, ...], dictionary: dict[str, Any]) -> None: ... diff --git a/stubs/protobuf/google/protobuf/source_context_pb2.pyi b/stubs/protobuf/google/protobuf/source_context_pb2.pyi new file mode 100644 index 000000000000..9d74fb3d5926 --- /dev/null +++ b/stubs/protobuf/google/protobuf/source_context_pb2.pyi @@ -0,0 +1,59 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class SourceContext(google.protobuf.message.Message): + """`SourceContext` represents information about the source of a + protobuf element, like the file in which it is defined. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_NAME_FIELD_NUMBER: builtins.int + file_name: builtins.str + """The path-qualified name of the .proto file that contained the associated + protobuf element. For example: `"google/protobuf/source_context.proto"`. + """ + def __init__(self, *, file_name: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["file_name", b"file_name"]) -> None: ... + +global___SourceContext = SourceContext diff --git a/stubs/protobuf/google/protobuf/struct_pb2.pyi b/stubs/protobuf/google/protobuf/struct_pb2.pyi new file mode 100644 index 000000000000..8e63dabfc2f1 --- /dev/null +++ b/stubs/protobuf/google/protobuf/struct_pb2.pyi @@ -0,0 +1,215 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.internal.well_known_types +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _NullValue: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _NullValueEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_NullValue.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NULL_VALUE: _NullValue.ValueType # 0 + """Null value.""" + +class NullValue(_NullValue, metaclass=_NullValueEnumTypeWrapper): + """`NullValue` is a singleton enumeration to represent the null value for the + `Value` type union. + + The JSON representation for `NullValue` is JSON `null`. + """ + +NULL_VALUE: NullValue.ValueType # 0 +"""Null value.""" +global___NullValue = NullValue + +@typing.final +class Struct(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Struct): + """`Struct` represents a structured data value, consisting of fields + which map to dynamically typed values. In some languages, `Struct` + might be supported by a native representation. For example, in + scripting languages like JS a struct is represented as an + object. The details of that representation are described together + with the proto support for the language. + + The JSON representation for `Struct` is JSON object. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FieldsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___Value: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___Value | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FIELDS_FIELD_NUMBER: builtins.int + @property + def fields(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Value]: + """Unordered map of dynamically typed values.""" + + def __init__(self, *, fields: collections.abc.Mapping[builtins.str, global___Value] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["fields", b"fields"]) -> None: ... + +global___Struct = Struct + +@typing.final +class Value(google.protobuf.message.Message): + """`Value` represents a dynamically typed value which can be either + null, a number, a string, a boolean, a recursive struct value, or a + list of values. A producer of value is expected to set one of these + variants. Absence of any variant indicates an error. + + The JSON representation for `Value` is JSON value. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NULL_VALUE_FIELD_NUMBER: builtins.int + NUMBER_VALUE_FIELD_NUMBER: builtins.int + STRING_VALUE_FIELD_NUMBER: builtins.int + BOOL_VALUE_FIELD_NUMBER: builtins.int + STRUCT_VALUE_FIELD_NUMBER: builtins.int + LIST_VALUE_FIELD_NUMBER: builtins.int + null_value: global___NullValue.ValueType + """Represents a null value.""" + number_value: builtins.float + """Represents a double value.""" + string_value: builtins.str + """Represents a string value.""" + bool_value: builtins.bool + """Represents a boolean value.""" + @property + def struct_value(self) -> global___Struct: + """Represents a structured value.""" + + @property + def list_value(self) -> global___ListValue: + """Represents a repeated `Value`.""" + + def __init__( + self, + *, + null_value: global___NullValue.ValueType | None = ..., + number_value: builtins.float | None = ..., + string_value: builtins.str | None = ..., + bool_value: builtins.bool | None = ..., + struct_value: global___Struct | None = ..., + list_value: global___ListValue | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "bool_value", + b"bool_value", + "kind", + b"kind", + "list_value", + b"list_value", + "null_value", + b"null_value", + "number_value", + b"number_value", + "string_value", + b"string_value", + "struct_value", + b"struct_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bool_value", + b"bool_value", + "kind", + b"kind", + "list_value", + b"list_value", + "null_value", + b"null_value", + "number_value", + b"number_value", + "string_value", + b"string_value", + "struct_value", + b"struct_value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["null_value", "number_value", "string_value", "bool_value", "struct_value", "list_value"] | None: ... + +global___Value = Value + +@typing.final +class ListValue(google.protobuf.message.Message, google.protobuf.internal.well_known_types.ListValue): + """`ListValue` is a wrapper around a repeated field of values. + + The JSON representation for `ListValue` is JSON array. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUES_FIELD_NUMBER: builtins.int + @property + def values(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Value]: + """Repeated field of dynamically typed values.""" + + def __init__(self, *, values: collections.abc.Iterable[global___Value] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["values", b"values"]) -> None: ... + +global___ListValue = ListValue diff --git a/stubs/protobuf/google/protobuf/symbol_database.pyi b/stubs/protobuf/google/protobuf/symbol_database.pyi new file mode 100644 index 000000000000..6fda0df00fd4 --- /dev/null +++ b/stubs/protobuf/google/protobuf/symbol_database.pyi @@ -0,0 +1,17 @@ +from collections.abc import Iterable + +from google.protobuf.descriptor import Descriptor, EnumDescriptor, FileDescriptor, ServiceDescriptor +from google.protobuf.descriptor_pool import DescriptorPool +from google.protobuf.message import Message + +class SymbolDatabase: + def __init__(self, pool: DescriptorPool | None = None) -> None: ... + def RegisterMessage(self, message: type[Message] | Message) -> type[Message] | Message: ... + def RegisterMessageDescriptor(self, message_descriptor: Descriptor) -> None: ... + def RegisterEnumDescriptor(self, enum_descriptor: EnumDescriptor) -> EnumDescriptor: ... + def RegisterServiceDescriptor(self, service_descriptor: ServiceDescriptor) -> None: ... + def RegisterFileDescriptor(self, file_descriptor: FileDescriptor) -> None: ... + def GetSymbol(self, symbol: str) -> type[Message]: ... + def GetMessages(self, files: Iterable[str]) -> dict[str, type[Message]]: ... + +def Default() -> SymbolDatabase: ... diff --git a/stubs/protobuf/google/protobuf/text_encoding.pyi b/stubs/protobuf/google/protobuf/text_encoding.pyi new file mode 100644 index 000000000000..69a69bf0e9e6 --- /dev/null +++ b/stubs/protobuf/google/protobuf/text_encoding.pyi @@ -0,0 +1,2 @@ +def CEscape(text: bytes, as_utf8: bool) -> str: ... +def CUnescape(text: str) -> bytes: ... diff --git a/stubs/protobuf/google/protobuf/text_format.pyi b/stubs/protobuf/google/protobuf/text_format.pyi new file mode 100644 index 000000000000..d95463b367c6 --- /dev/null +++ b/stubs/protobuf/google/protobuf/text_format.pyi @@ -0,0 +1,207 @@ +from _typeshed import SupportsWrite +from collections.abc import Callable, Iterable +from typing import Any, TypeAlias, TypeVar + +from .descriptor import FieldDescriptor +from .descriptor_pool import DescriptorPool +from .message import Message + +_M = TypeVar("_M", bound=Message) # message type (of self) + +__all__ = ["MessageToString", "Parse", "PrintMessage", "PrintField", "PrintFieldValue", "Merge", "MessageToBytes"] + +class Error(Exception): ... + +class ParseError(Error): + def __init__(self, message: str | None = None, line: int | None = None, column: int | None = None) -> None: ... + def GetLine(self) -> int | None: ... + def GetColumn(self) -> int | None: ... + +class TextWriter: + def __init__(self, as_utf8: bool) -> None: ... + def write(self, val: str) -> int: ... + def close(self) -> None: ... + def getvalue(self) -> str: ... + +_MessageFormatter: TypeAlias = Callable[[Message, int, bool], str | None] + +def MessageToString( + message: Message, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> str: ... +def MessageToBytes( + message: Message, + *, + # Same kwargs as MessageToString + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + indent: int = 0, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> bytes: ... +def PrintMessage( + message: Message, + out: SupportsWrite[str], + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> None: ... +def PrintField( + field: FieldDescriptor, + value: Any, + out: SupportsWrite[str], + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> None: ... +def PrintFieldValue( + field: FieldDescriptor, + value: Any, + out: SupportsWrite[str], + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, +) -> None: ... + +class _Printer: + out: SupportsWrite[str] + indent: int + as_utf8: bool + as_one_line: bool + use_short_repeated_primitives: bool + pointy_brackets: bool + use_index_order: bool + use_field_number: bool + descriptor_pool: DescriptorPool | None + message_formatter: _MessageFormatter | None + print_unknown_fields: bool + force_colon: bool + def __init__( + self, + out: SupportsWrite[str], + indent: int = 0, + as_utf8: bool = True, + as_one_line: bool = False, + use_short_repeated_primitives: bool = False, + pointy_brackets: bool = False, + use_index_order: bool = False, + use_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + message_formatter: _MessageFormatter | None = None, + print_unknown_fields: bool = False, + force_colon: bool = False, + ) -> None: ... + def PrintMessage(self, message: Message) -> None: ... + def PrintField(self, field: FieldDescriptor, value: Any) -> None: ... + def PrintFieldValue(self, field: FieldDescriptor, value: Any) -> None: ... + +def Parse( + text: str | bytes, + message: _M, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, +) -> _M: ... +def Merge( + text: str | bytes, + message: _M, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, +) -> _M: ... +def MergeLines( + lines: Iterable[str | bytes], + message: _M, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, +) -> _M: ... + +class _Parser: + allow_unknown_extension: bool + allow_field_number: bool + descriptor_pool: DescriptorPool | None + allow_unknown_field: bool + def __init__( + self, + allow_unknown_extension: bool = False, + allow_field_number: bool = False, + descriptor_pool: DescriptorPool | None = None, + allow_unknown_field: bool = False, + ) -> None: ... + def ParseLines(self, lines: Iterable[str | bytes], message: _M) -> _M: ... + def MergeLines(self, lines: Iterable[str | bytes], message: _M) -> _M: ... + +_ParseError: TypeAlias = ParseError + +class Tokenizer: + token: str + def __init__(self, lines: Iterable[str], skip_comments: bool = True) -> None: ... + def LookingAt(self, token: str) -> bool: ... + def AtEnd(self) -> bool: ... + def TryConsume(self, token: str) -> bool: ... + def Consume(self, token: str) -> None: ... + def ConsumeComment(self) -> str: ... + def ConsumeCommentOrTrailingComment(self) -> tuple[bool, str]: ... + def TryConsumeIdentifier(self) -> bool: ... + def ConsumeIdentifier(self) -> str: ... + def TryConsumeIdentifierOrNumber(self) -> bool: ... + def ConsumeIdentifierOrNumber(self) -> str: ... + def TryConsumeInteger(self) -> bool: ... + def ConsumeInteger(self) -> int: ... + def TryConsumeFloat(self) -> bool: ... + def ConsumeFloat(self) -> float: ... + def ConsumeBool(self) -> bool: ... + def TryConsumeByteString(self) -> bool: ... + def ConsumeString(self) -> str: ... + def ConsumeByteString(self) -> bytes: ... + def ConsumeEnum(self, field: FieldDescriptor) -> int: ... + def ConsumeUrlChars(self) -> str: ... + def TryConsumeUrlChars(self) -> bool: ... + def ParseErrorPreviousToken(self, message: Message) -> _ParseError: ... + def ParseError(self, message: Message) -> _ParseError: ... + def NextToken(self) -> None: ... + +def ParseInteger(text: str, is_signed: bool = False, is_long: bool = False) -> int: ... +def ParseFloat(text: str) -> float: ... +def ParseBool(text: str) -> bool: ... +def ParseEnum(field: FieldDescriptor, value: str) -> int: ... diff --git a/stubs/protobuf/google/protobuf/timestamp.pyi b/stubs/protobuf/google/protobuf/timestamp.pyi new file mode 100644 index 000000000000..b6687a744e45 --- /dev/null +++ b/stubs/protobuf/google/protobuf/timestamp.pyi @@ -0,0 +1,16 @@ +from datetime import datetime, tzinfo + +from google.protobuf.timestamp_pb2 import Timestamp + +def from_json_string(value: str) -> Timestamp: ... +def from_microseconds(micros: float) -> Timestamp: ... +def from_milliseconds(millis: float) -> Timestamp: ... +def from_nanoseconds(nanos: float) -> Timestamp: ... +def from_seconds(seconds: float) -> Timestamp: ... +def from_current_time() -> Timestamp: ... +def to_json_string(ts: Timestamp) -> str: ... +def to_microseconds(ts: Timestamp) -> int: ... +def to_milliseconds(ts: Timestamp) -> int: ... +def to_nanoseconds(ts: Timestamp) -> int: ... +def to_seconds(ts: Timestamp) -> int: ... +def to_datetime(ts: Timestamp, tz: tzinfo | None = None) -> datetime: ... diff --git a/stubs/protobuf/google/protobuf/timestamp_pb2.pyi b/stubs/protobuf/google/protobuf/timestamp_pb2.pyi new file mode 100644 index 000000000000..52daff363ddf --- /dev/null +++ b/stubs/protobuf/google/protobuf/timestamp_pb2.pyi @@ -0,0 +1,155 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.well_known_types +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Timestamp(google.protobuf.message.Message, google.protobuf.internal.well_known_types.Timestamp): + """A Timestamp represents a point in time independent of any time zone or local + calendar, encoded as a count of seconds and fractions of seconds at + nanosecond resolution. The count is relative to an epoch at UTC midnight on + January 1, 1970, in the proleptic Gregorian calendar which extends the + Gregorian calendar backwards to year one. + + All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap + second table is needed for interpretation, using a [24-hour linear + smear](https://developers.google.com/time/smear). + + The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By + restricting to that range, we ensure that we can convert to and from [RFC + 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. + + # Examples + + Example 1: Compute Timestamp from POSIX `time()`. + + Timestamp timestamp; + timestamp.set_seconds(time(NULL)); + timestamp.set_nanos(0); + + Example 2: Compute Timestamp from POSIX `gettimeofday()`. + + struct timeval tv; + gettimeofday(&tv, NULL); + + Timestamp timestamp; + timestamp.set_seconds(tv.tv_sec); + timestamp.set_nanos(tv.tv_usec * 1000); + + Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. + + FILETIME ft; + GetSystemTimeAsFileTime(&ft); + UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; + + // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z + // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. + Timestamp timestamp; + timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); + timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); + + Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. + + long millis = System.currentTimeMillis(); + + Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) + .setNanos((int) ((millis % 1000) * 1000000)).build(); + + Example 5: Compute Timestamp from Java `Instant.now()`. + + Instant now = Instant.now(); + + Timestamp timestamp = + Timestamp.newBuilder().setSeconds(now.getEpochSecond()) + .setNanos(now.getNano()).build(); + + Example 6: Compute Timestamp from current time in Python. + + timestamp = Timestamp() + timestamp.GetCurrentTime() + + # JSON Mapping + + In JSON format, the Timestamp type is encoded as a string in the + [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the + format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" + where {year} is always expressed using four digits while {month}, {day}, + {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional + seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), + are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone + is required. A proto3 JSON serializer should always use UTC (as indicated by + "Z") when printing the Timestamp type and a proto3 JSON parser should be + able to accept both UTC and other timezones (as indicated by an offset). + + For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past + 01:30 UTC on January 15, 2017. + + In JavaScript, one can convert a Date object to this format using the + standard + [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) + method. In Python, a standard `datetime.datetime` object can be converted + to this format using + [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with + the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use + the Joda Time's [`ISODateTimeFormat.dateTime()`]( + http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() + ) to obtain a formatter capable of generating timestamps in this format. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SECONDS_FIELD_NUMBER: builtins.int + NANOS_FIELD_NUMBER: builtins.int + seconds: builtins.int + """Represents seconds of UTC time since Unix epoch + 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + 9999-12-31T23:59:59Z inclusive. + """ + nanos: builtins.int + """Non-negative fractions of a second at nanosecond resolution. Negative + second values with fractions must still have non-negative nanos values + that count forward in time. Must be from 0 to 999,999,999 + inclusive. + """ + def __init__(self, *, seconds: builtins.int | None = ..., nanos: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["nanos", b"nanos", "seconds", b"seconds"]) -> None: ... + +global___Timestamp = Timestamp diff --git a/stubs/protobuf/google/protobuf/type_pb2.pyi b/stubs/protobuf/google/protobuf/type_pb2.pyi new file mode 100644 index 000000000000..a8a7eb07c778 --- /dev/null +++ b/stubs/protobuf/google/protobuf/type_pb2.pyi @@ -0,0 +1,492 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import google.protobuf.source_context_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Syntax: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _SyntaxEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Syntax.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SYNTAX_PROTO2: _Syntax.ValueType # 0 + """Syntax `proto2`.""" + SYNTAX_PROTO3: _Syntax.ValueType # 1 + """Syntax `proto3`.""" + SYNTAX_EDITIONS: _Syntax.ValueType # 2 + """Syntax `editions`.""" + +class Syntax(_Syntax, metaclass=_SyntaxEnumTypeWrapper): + """The syntax in which a protocol buffer element is defined.""" + +SYNTAX_PROTO2: Syntax.ValueType # 0 +"""Syntax `proto2`.""" +SYNTAX_PROTO3: Syntax.ValueType # 1 +"""Syntax `proto3`.""" +SYNTAX_EDITIONS: Syntax.ValueType # 2 +"""Syntax `editions`.""" +global___Syntax = Syntax + +@typing.final +class Type(google.protobuf.message.Message): + """A protocol buffer message type. + + New usages of this message as an alternative to DescriptorProto are strongly + discouraged. This message does not reliability preserve all information + necessary to model the schema and preserve semantics. Instead make use of + FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + FIELDS_FIELD_NUMBER: builtins.int + ONEOFS_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SOURCE_CONTEXT_FIELD_NUMBER: builtins.int + SYNTAX_FIELD_NUMBER: builtins.int + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str + """The fully qualified message name.""" + syntax: global___Syntax.ValueType + """The source syntax.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" + @property + def fields(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Field]: + """The list of fields.""" + + @property + def oneofs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """The list of types appearing in `oneof` definitions in this type.""" + + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: + """The protocol buffer options.""" + + @property + def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: + """The source context.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + fields: collections.abc.Iterable[global___Field] | None = ..., + oneofs: collections.abc.Iterable[builtins.str] | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + syntax: global___Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "fields", + b"fields", + "name", + b"name", + "oneofs", + b"oneofs", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + ], + ) -> None: ... + +global___Type = Type + +@typing.final +class Field(google.protobuf.message.Message): + """A single field of a message type. + + New usages of this message as an alternative to FieldDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Kind: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _KindEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Field._Kind.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TYPE_UNKNOWN: Field._Kind.ValueType # 0 + """Field type unknown.""" + TYPE_DOUBLE: Field._Kind.ValueType # 1 + """Field type double.""" + TYPE_FLOAT: Field._Kind.ValueType # 2 + """Field type float.""" + TYPE_INT64: Field._Kind.ValueType # 3 + """Field type int64.""" + TYPE_UINT64: Field._Kind.ValueType # 4 + """Field type uint64.""" + TYPE_INT32: Field._Kind.ValueType # 5 + """Field type int32.""" + TYPE_FIXED64: Field._Kind.ValueType # 6 + """Field type fixed64.""" + TYPE_FIXED32: Field._Kind.ValueType # 7 + """Field type fixed32.""" + TYPE_BOOL: Field._Kind.ValueType # 8 + """Field type bool.""" + TYPE_STRING: Field._Kind.ValueType # 9 + """Field type string.""" + TYPE_GROUP: Field._Kind.ValueType # 10 + """Field type group. Proto2 syntax only, and deprecated.""" + TYPE_MESSAGE: Field._Kind.ValueType # 11 + """Field type message.""" + TYPE_BYTES: Field._Kind.ValueType # 12 + """Field type bytes.""" + TYPE_UINT32: Field._Kind.ValueType # 13 + """Field type uint32.""" + TYPE_ENUM: Field._Kind.ValueType # 14 + """Field type enum.""" + TYPE_SFIXED32: Field._Kind.ValueType # 15 + """Field type sfixed32.""" + TYPE_SFIXED64: Field._Kind.ValueType # 16 + """Field type sfixed64.""" + TYPE_SINT32: Field._Kind.ValueType # 17 + """Field type sint32.""" + TYPE_SINT64: Field._Kind.ValueType # 18 + """Field type sint64.""" + + class Kind(_Kind, metaclass=_KindEnumTypeWrapper): + """Basic field types.""" + + TYPE_UNKNOWN: Field.Kind.ValueType # 0 + """Field type unknown.""" + TYPE_DOUBLE: Field.Kind.ValueType # 1 + """Field type double.""" + TYPE_FLOAT: Field.Kind.ValueType # 2 + """Field type float.""" + TYPE_INT64: Field.Kind.ValueType # 3 + """Field type int64.""" + TYPE_UINT64: Field.Kind.ValueType # 4 + """Field type uint64.""" + TYPE_INT32: Field.Kind.ValueType # 5 + """Field type int32.""" + TYPE_FIXED64: Field.Kind.ValueType # 6 + """Field type fixed64.""" + TYPE_FIXED32: Field.Kind.ValueType # 7 + """Field type fixed32.""" + TYPE_BOOL: Field.Kind.ValueType # 8 + """Field type bool.""" + TYPE_STRING: Field.Kind.ValueType # 9 + """Field type string.""" + TYPE_GROUP: Field.Kind.ValueType # 10 + """Field type group. Proto2 syntax only, and deprecated.""" + TYPE_MESSAGE: Field.Kind.ValueType # 11 + """Field type message.""" + TYPE_BYTES: Field.Kind.ValueType # 12 + """Field type bytes.""" + TYPE_UINT32: Field.Kind.ValueType # 13 + """Field type uint32.""" + TYPE_ENUM: Field.Kind.ValueType # 14 + """Field type enum.""" + TYPE_SFIXED32: Field.Kind.ValueType # 15 + """Field type sfixed32.""" + TYPE_SFIXED64: Field.Kind.ValueType # 16 + """Field type sfixed64.""" + TYPE_SINT32: Field.Kind.ValueType # 17 + """Field type sint32.""" + TYPE_SINT64: Field.Kind.ValueType # 18 + """Field type sint64.""" + + class _Cardinality: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CardinalityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Field._Cardinality.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CARDINALITY_UNKNOWN: Field._Cardinality.ValueType # 0 + """For fields with unknown cardinality.""" + CARDINALITY_OPTIONAL: Field._Cardinality.ValueType # 1 + """For optional fields.""" + CARDINALITY_REQUIRED: Field._Cardinality.ValueType # 2 + """For required fields. Proto2 syntax only.""" + CARDINALITY_REPEATED: Field._Cardinality.ValueType # 3 + """For repeated fields.""" + + class Cardinality(_Cardinality, metaclass=_CardinalityEnumTypeWrapper): + """Whether a field is optional, required, or repeated.""" + + CARDINALITY_UNKNOWN: Field.Cardinality.ValueType # 0 + """For fields with unknown cardinality.""" + CARDINALITY_OPTIONAL: Field.Cardinality.ValueType # 1 + """For optional fields.""" + CARDINALITY_REQUIRED: Field.Cardinality.ValueType # 2 + """For required fields. Proto2 syntax only.""" + CARDINALITY_REPEATED: Field.Cardinality.ValueType # 3 + """For repeated fields.""" + + KIND_FIELD_NUMBER: builtins.int + CARDINALITY_FIELD_NUMBER: builtins.int + NUMBER_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + TYPE_URL_FIELD_NUMBER: builtins.int + ONEOF_INDEX_FIELD_NUMBER: builtins.int + PACKED_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + JSON_NAME_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + kind: global___Field.Kind.ValueType + """The field type.""" + cardinality: global___Field.Cardinality.ValueType + """The field cardinality.""" + number: builtins.int + """The field number.""" + name: builtins.str + """The field name.""" + type_url: builtins.str + """The field type URL, without the scheme, for message or enumeration + types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. + """ + oneof_index: builtins.int + """The index of the field type in `Type.oneofs`, for message or enumeration + types. The first type has index 1; zero means the type is not in the list. + """ + packed: builtins.bool + """Whether to use alternative packed wire representation.""" + json_name: builtins.str + """The field JSON name.""" + default_value: builtins.str + """The string value of the default value of this field. Proto2 syntax only.""" + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: + """The protocol buffer options.""" + + def __init__( + self, + *, + kind: global___Field.Kind.ValueType | None = ..., + cardinality: global___Field.Cardinality.ValueType | None = ..., + number: builtins.int | None = ..., + name: builtins.str | None = ..., + type_url: builtins.str | None = ..., + oneof_index: builtins.int | None = ..., + packed: builtins.bool | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + json_name: builtins.str | None = ..., + default_value: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cardinality", + b"cardinality", + "default_value", + b"default_value", + "json_name", + b"json_name", + "kind", + b"kind", + "name", + b"name", + "number", + b"number", + "oneof_index", + b"oneof_index", + "options", + b"options", + "packed", + b"packed", + "type_url", + b"type_url", + ], + ) -> None: ... + +global___Field = Field + +@typing.final +class Enum(google.protobuf.message.Message): + """Enum type definition. + + New usages of this message as an alternative to EnumDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + ENUMVALUE_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SOURCE_CONTEXT_FIELD_NUMBER: builtins.int + SYNTAX_FIELD_NUMBER: builtins.int + EDITION_FIELD_NUMBER: builtins.int + name: builtins.str + """Enum type name.""" + syntax: global___Syntax.ValueType + """The source syntax.""" + edition: builtins.str + """The source edition string, only valid when syntax is SYNTAX_EDITIONS.""" + @property + def enumvalue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___EnumValue]: + """Enum value definitions.""" + + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: + """Protocol buffer options.""" + + @property + def source_context(self) -> google.protobuf.source_context_pb2.SourceContext: + """The source context.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + enumvalue: collections.abc.Iterable[global___EnumValue] | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + source_context: google.protobuf.source_context_pb2.SourceContext | None = ..., + syntax: global___Syntax.ValueType | None = ..., + edition: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["source_context", b"source_context"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "edition", + b"edition", + "enumvalue", + b"enumvalue", + "name", + b"name", + "options", + b"options", + "source_context", + b"source_context", + "syntax", + b"syntax", + ], + ) -> None: ... + +global___Enum = Enum + +@typing.final +class EnumValue(google.protobuf.message.Message): + """Enum value definition. + + New usages of this message as an alternative to EnumValueDescriptorProto are + strongly discouraged. This message does not reliability preserve all + information necessary to model the schema and preserve semantics. Instead + make use of FileDescriptorSet which preserves the necessary information. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + NUMBER_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + name: builtins.str + """Enum value name.""" + number: builtins.int + """Enum value number.""" + @property + def options(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Option]: + """Protocol buffer options.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + number: builtins.int | None = ..., + options: collections.abc.Iterable[global___Option] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "number", b"number", "options", b"options"]) -> None: ... + +global___EnumValue = EnumValue + +@typing.final +class Option(google.protobuf.message.Message): + """A protocol buffer option, which can be attached to a message, field, + enumeration, etc. + + New usages of this message as an alternative to FileOptions, MessageOptions, + FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions + are strongly discouraged. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + name: builtins.str + """The option's name. For protobuf built-in options (options defined in + descriptor.proto), this is the short name. For example, `"map_entry"`. + For custom options, it should be the fully-qualified name. For example, + `"google.api.http"`. + """ + @property + def value(self) -> google.protobuf.any_pb2.Any: + """The option's value packed in an Any message. If the value is a primitive, + the corresponding wrapper type defined in google/protobuf/wrappers.proto + should be used. If the value is an enum, it should be stored as an int32 + value using the google.protobuf.Int32Value type. + """ + + def __init__(self, *, name: builtins.str | None = ..., value: google.protobuf.any_pb2.Any | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["name", b"name", "value", b"value"]) -> None: ... + +global___Option = Option diff --git a/stubs/protobuf/google/protobuf/unknown_fields.pyi b/stubs/protobuf/google/protobuf/unknown_fields.pyi new file mode 100644 index 000000000000..7329b00a4128 --- /dev/null +++ b/stubs/protobuf/google/protobuf/unknown_fields.pyi @@ -0,0 +1,9 @@ +from typing import Any, final + +from google.protobuf.message import Message + +@final +class UnknownFieldSet: + def __new__(cls, msg: Message) -> UnknownFieldSet: ... # noqa: Y034 + def __getitem__(self, index: int, /) -> Any: ... # Any: internal unknown field object + def __len__(self) -> int: ... diff --git a/stubs/protobuf/google/protobuf/util/__init__.pyi b/stubs/protobuf/google/protobuf/util/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/protobuf/google/protobuf/wrappers_pb2.pyi b/stubs/protobuf/google/protobuf/wrappers_pb2.pyi new file mode 100644 index 000000000000..b3d875bccf67 --- /dev/null +++ b/stubs/protobuf/google/protobuf/wrappers_pb2.pyi @@ -0,0 +1,238 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol Buffers - Google's data interchange format +Copyright 2008 Google Inc. All rights reserved. +https://developers.google.com/protocol-buffers/ + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Wrappers for primitive (non-message) types. These types were needed +for legacy reasons and are not recommended for use in new APIs. + +Historically these wrappers were useful to have presence on proto3 primitive +fields, but proto3 syntax has been updated to support the `optional` keyword. +Using that keyword is now the strongly preferred way to add presence to +proto3 primitive fields. + +A secondary usecase was to embed primitives in the `google.protobuf.Any` +type: it is now recommended that you embed your value in your own wrapper +message which can be specifically documented. + +These wrappers have no meaningful use within repeated fields as they lack +the ability to detect presence on individual elements. +These wrappers have no meaningful use within a map or a oneof since +individual entries of a map or fields of a oneof can already detect presence. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class DoubleValue(google.protobuf.message.Message): + """Wrapper message for `double`. + + The JSON representation for `DoubleValue` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.float + """The double value.""" + def __init__(self, *, value: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___DoubleValue = DoubleValue + +@typing.final +class FloatValue(google.protobuf.message.Message): + """Wrapper message for `float`. + + The JSON representation for `FloatValue` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.float + """The float value.""" + def __init__(self, *, value: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___FloatValue = FloatValue + +@typing.final +class Int64Value(google.protobuf.message.Message): + """Wrapper message for `int64`. + + The JSON representation for `Int64Value` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.int + """The int64 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___Int64Value = Int64Value + +@typing.final +class UInt64Value(google.protobuf.message.Message): + """Wrapper message for `uint64`. + + The JSON representation for `UInt64Value` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.int + """The uint64 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___UInt64Value = UInt64Value + +@typing.final +class Int32Value(google.protobuf.message.Message): + """Wrapper message for `int32`. + + The JSON representation for `Int32Value` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.int + """The int32 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___Int32Value = Int32Value + +@typing.final +class UInt32Value(google.protobuf.message.Message): + """Wrapper message for `uint32`. + + The JSON representation for `UInt32Value` is JSON number. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.int + """The uint32 value.""" + def __init__(self, *, value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___UInt32Value = UInt32Value + +@typing.final +class BoolValue(google.protobuf.message.Message): + """Wrapper message for `bool`. + + The JSON representation for `BoolValue` is JSON `true` and `false`. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.bool + """The bool value.""" + def __init__(self, *, value: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___BoolValue = BoolValue + +@typing.final +class StringValue(google.protobuf.message.Message): + """Wrapper message for `string`. + + The JSON representation for `StringValue` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.str + """The string value.""" + def __init__(self, *, value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___StringValue = StringValue + +@typing.final +class BytesValue(google.protobuf.message.Message): + """Wrapper message for `bytes`. + + The JSON representation for `BytesValue` is JSON string. + + Not recommended for use in new APIs, but still useful for legacy APIs and + has no plan to be removed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + value: builtins.bytes + """The bytes value.""" + def __init__(self, *, value: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___BytesValue = BytesValue diff --git a/stubs/psutil/@tests/stubtest_allowlist.txt b/stubs/psutil/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..785a98e07685 --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist.txt @@ -0,0 +1,10 @@ +# TODO: missing from stub +psutil.__all__ + +# Stubtest does not support these platforms +psutil._psaix +psutil._psbsd +psutil._pssunos +psutil._psutil_aix +psutil._psutil_bsd +psutil._psutil_sunos diff --git a/stubs/psutil/@tests/stubtest_allowlist_darwin.txt b/stubs/psutil/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..2606ecbdf50b --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,8 @@ +psutil._pslinux +psutil._pswindows +psutil._psutil_linux +psutil._psutil_windows + +# not always available on ARM64, but we test there +psutil.cpu_freq +psutil._psosx.cpu_freq diff --git a/stubs/psutil/@tests/stubtest_allowlist_linux.txt b/stubs/psutil/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..5433c30009cc --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,4 @@ +psutil._psosx +psutil._pswindows +psutil._psutil_osx +psutil._psutil_windows diff --git a/stubs/psutil/@tests/stubtest_allowlist_win32.txt b/stubs/psutil/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..1e781db20233 --- /dev/null +++ b/stubs/psutil/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,4 @@ +psutil._psosx +psutil._pslinux +psutil._psutil_osx +psutil._psutil_linux diff --git a/stubs/psutil/@tests/test_cases/check_process_iter.py b/stubs/psutil/@tests/test_cases/check_process_iter.py new file mode 100644 index 000000000000..b31fe9d7eefe --- /dev/null +++ b/stubs/psutil/@tests/test_cases/check_process_iter.py @@ -0,0 +1,16 @@ +"""Test cases for psutil.process_iter and its cache_clear method.""" + +from __future__ import annotations + +import psutil + +# Test that process_iter can be called as a function +for proc in psutil.process_iter(): + break + +# Test that process_iter has cache_clear method +psutil.process_iter.cache_clear() + +# Test that cache_clear is callable +clear_method = psutil.process_iter.cache_clear +clear_method() diff --git a/stubs/psutil/METADATA.toml b/stubs/psutil/METADATA.toml new file mode 100644 index 000000000000..4700066c4768 --- /dev/null +++ b/stubs/psutil/METADATA.toml @@ -0,0 +1,5 @@ +version = "7.2.2" +upstream-repository = "https://github.com/giampaolo/psutil" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/psutil/psutil/__init__.pyi b/stubs/psutil/psutil/__init__.pyi new file mode 100644 index 000000000000..b49b1a1fb3d4 --- /dev/null +++ b/stubs/psutil/psutil/__init__.pyi @@ -0,0 +1,343 @@ +import sys +from _typeshed import Incomplete, StrOrBytesPath +from collections.abc import Callable, Collection, Iterable, Iterator +from contextlib import AbstractContextManager +from subprocess import _CMD, _ENV, _FILE +from types import TracebackType +from typing import Any, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated + +from psutil._common import ( + AIX as AIX, + BSD as BSD, + CONN_CLOSE as CONN_CLOSE, + CONN_CLOSE_WAIT as CONN_CLOSE_WAIT, + CONN_CLOSING as CONN_CLOSING, + CONN_ESTABLISHED as CONN_ESTABLISHED, + CONN_FIN_WAIT1 as CONN_FIN_WAIT1, + CONN_FIN_WAIT2 as CONN_FIN_WAIT2, + CONN_LAST_ACK as CONN_LAST_ACK, + CONN_LISTEN as CONN_LISTEN, + CONN_NONE as CONN_NONE, + CONN_SYN_RECV as CONN_SYN_RECV, + CONN_SYN_SENT as CONN_SYN_SENT, + CONN_TIME_WAIT as CONN_TIME_WAIT, + FREEBSD as FREEBSD, + LINUX as LINUX, + MACOS as MACOS, + NETBSD as NETBSD, + NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, + NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, + NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, + OPENBSD as OPENBSD, + OSX as OSX, + POSIX as POSIX, + POWER_TIME_UNKNOWN as POWER_TIME_UNKNOWN, + POWER_TIME_UNLIMITED as POWER_TIME_UNLIMITED, + STATUS_DEAD as STATUS_DEAD, + STATUS_DISK_SLEEP as STATUS_DISK_SLEEP, + STATUS_IDLE as STATUS_IDLE, + STATUS_LOCKED as STATUS_LOCKED, + STATUS_PARKED as STATUS_PARKED, + STATUS_RUNNING as STATUS_RUNNING, + STATUS_SLEEPING as STATUS_SLEEPING, + STATUS_STOPPED as STATUS_STOPPED, + STATUS_TRACING_STOP as STATUS_TRACING_STOP, + STATUS_WAITING as STATUS_WAITING, + STATUS_WAKING as STATUS_WAKING, + STATUS_ZOMBIE as STATUS_ZOMBIE, + SUNOS as SUNOS, + WINDOWS as WINDOWS, + AccessDenied as AccessDenied, + Error as Error, + NoSuchProcess as NoSuchProcess, + TimeoutExpired as TimeoutExpired, + ZombieProcess as ZombieProcess, +) + +from . import _ntuples as _ntp + +if sys.platform == "linux": + from ._pslinux import ( + IOPRIO_CLASS_BE as IOPRIO_CLASS_BE, + IOPRIO_CLASS_IDLE as IOPRIO_CLASS_IDLE, + IOPRIO_CLASS_NONE as IOPRIO_CLASS_NONE, + IOPRIO_CLASS_RT as IOPRIO_CLASS_RT, + ) + def sensors_temperatures(fahrenheit: bool = False) -> dict[str, list[_ntp.shwtemp]]: ... + def sensors_fans() -> dict[str, list[_ntp.sfan]]: ... + PROCFS_PATH: str + RLIMIT_AS: int + RLIMIT_CORE: int + RLIMIT_CPU: int + RLIMIT_DATA: int + RLIMIT_FSIZE: int + RLIMIT_LOCKS: int + RLIMIT_MEMLOCK: int + RLIMIT_MSGQUEUE: int + RLIMIT_NICE: int + RLIMIT_NOFILE: int + RLIMIT_NPROC: int + RLIMIT_RSS: int + RLIMIT_RTPRIO: int + RLIMIT_RTTIME: int + RLIMIT_SIGPENDING: int + RLIMIT_STACK: int + RLIM_INFINITY: int +if sys.platform == "win32": + from ._psutil_windows import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + ) + from ._pswindows import ( + CONN_DELETE_TCB as CONN_DELETE_TCB, + IOPRIO_HIGH as IOPRIO_HIGH, + IOPRIO_LOW as IOPRIO_LOW, + IOPRIO_NORMAL as IOPRIO_NORMAL, + IOPRIO_VERYLOW as IOPRIO_VERYLOW, + win_service_get as win_service_get, + win_service_iter as win_service_iter, + ) + +# Linux + glibc, Windows, macOS, FreeBSD, NetBSD: +def heap_info() -> _ntp.pheap: ... +def heap_trim() -> None: ... + +if sys.platform == "linux": + from ._pslinux import sensors_battery as sensors_battery +elif sys.platform == "darwin": + from ._psosx import sensors_battery as sensors_battery +elif sys.platform == "win32": + from ._pswindows import sensors_battery as sensors_battery +else: + def sensors_battery(): ... + +AF_LINK: int +version_info: tuple[int, int, int] +__version__: str +__author__: str + +_Status: TypeAlias = Literal[ + "running", + "sleeping", + "disk-sleep", + "stopped", + "tracing-stop", + "zombie", + "dead", + "wake-kill", + "waking", + "idle", + "locked", + "waiting", + "suspended", + "parked", +] + +class Process: + def __init__(self, pid: int | None = None) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + @property + def pid(self) -> int: ... + # Only present if attrs argument is passed to process_iter + info: dict[str, Incomplete] + def oneshot(self) -> AbstractContextManager[None]: ... + def as_dict( + self, attrs: list[str] | tuple[str, ...] | set[str] | frozenset[str] | None = None, ad_value=None + ) -> dict[str, Incomplete]: ... + def parent(self) -> Process | None: ... + def parents(self) -> list[Process]: ... + def is_running(self) -> bool: ... + def ppid(self) -> int: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def status(self) -> _Status: ... + def username(self) -> str: ... + def create_time(self) -> float: ... + def cwd(self) -> str: ... + def nice(self, value: int | None = None) -> int: ... + if sys.platform != "win32": + def uids(self) -> _ntp.puids: ... + def gids(self) -> _ntp.pgids: ... + def terminal(self) -> str: ... + def num_fds(self) -> int: ... + if sys.platform != "darwin": + def io_counters(self) -> _ntp.pio: ... + def ionice(self, ioclass: int | None = None, value: int | None = None) -> _ntp.pionice: ... + + @overload + def cpu_affinity(self, cpus: None = None) -> list[int]: ... + @overload + def cpu_affinity(self, cpus: list[int]) -> None: ... + + def memory_maps(self, grouped: bool = True) -> list[Incomplete]: ... + if sys.platform == "linux": + def rlimit(self, resource: int, limits: tuple[int, int] | None = None) -> tuple[int, int]: ... + def cpu_num(self) -> int: ... + + def environ(self) -> dict[str, str]: ... + if sys.platform == "win32": + def num_handles(self) -> int: ... + + def num_ctx_switches(self) -> _ntp.pctxsw: ... + def num_threads(self) -> int: ... + def threads(self) -> list[_ntp.pthread]: ... + def children(self, recursive: bool = False) -> list[Process]: ... + def cpu_percent(self, interval: float | None = None) -> float: ... + def cpu_times(self) -> _ntp.pcputimes: ... + def memory_info(self) -> _ntp.pmem: ... + def memory_full_info(self) -> _ntp.pfullmem: ... + def memory_percent(self, memtype: str = "rss") -> float: ... + def open_files(self) -> list[_ntp.popenfile]: ... + @deprecated('use "net_connections" method instead') + def connections(self, kind: str = "inet") -> list[_ntp.pconn]: ... + def send_signal(self, sig: int) -> None: ... + def suspend(self) -> None: ... + def resume(self) -> None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def wait(self, timeout: float | None = None) -> int: ... + def net_connections(self, kind: str = "inet") -> list[_ntp.pconn]: ... + +class Popen(Process): + # sync with subprocess.Popen.__init__: + if sys.version_info >= (3, 11): + def __init__( + self, + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + process_group: int | None = None, + ) -> None: ... + else: + def __init__( + self, + args: _CMD, + bufsize: int = -1, + executable: StrOrBytesPath | None = None, + stdin: _FILE | None = None, + stdout: _FILE | None = None, + stderr: _FILE | None = None, + preexec_fn: Callable[[], object] | None = None, + close_fds: bool = True, + shell: bool = False, + cwd: StrOrBytesPath | None = None, + env: _ENV | None = None, + universal_newlines: bool | None = None, + startupinfo: Any | None = None, + creationflags: int = 0, + restore_signals: bool = True, + start_new_session: bool = False, + pass_fds: Collection[int] = (), + *, + text: bool | None = None, + encoding: str | None = None, + errors: str | None = None, + user: str | int | None = None, + group: str | int | None = None, + extra_groups: Iterable[str | int] | None = None, + umask: int = -1, + pipesize: int = -1, + ) -> None: ... + + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __getattribute__(self, name: str) -> Any: ... + def __dir__(self) -> list[str]: ... + +@type_check_only +class _ProcessIterCallable(Protocol): + def __call__( + self, attrs: list[str] | tuple[str, ...] | set[str] | frozenset[str] | None = None, ad_value=None + ) -> Iterator[Process]: ... + def cache_clear(self) -> None: ... + +def pids() -> list[int]: ... +def pid_exists(pid: int) -> bool: ... + +process_iter: _ProcessIterCallable + +def wait_procs( + procs: Iterable[Process], timeout: float | None = None, callback: Callable[[Process], object] | None = None +) -> tuple[list[Process], list[Process]]: ... +def cpu_count(logical: bool = True) -> int | None: ... + +@overload +def cpu_freq(percpu: Literal[False] = False) -> _ntp.scpufreq: ... +@overload +def cpu_freq(percpu: Literal[True]) -> list[_ntp.scpufreq]: ... + +@overload +def cpu_times(percpu: Literal[False] = False) -> _ntp.scputimes: ... +@overload +def cpu_times(percpu: Literal[True]) -> list[_ntp.scputimes]: ... + +@overload +def cpu_percent(interval: float | None = None, percpu: Literal[False] = False) -> float: ... +@overload +def cpu_percent(interval: float | None, percpu: Literal[True]) -> list[float]: ... +@overload +def cpu_percent(*, percpu: Literal[True]) -> list[float]: ... + +@overload +def cpu_times_percent(interval: float | None = None, percpu: Literal[False] = False) -> _ntp.scputimes: ... +@overload +def cpu_times_percent(interval: float | None, percpu: Literal[True]) -> list[_ntp.scputimes]: ... +@overload +def cpu_times_percent(*, percpu: Literal[True]) -> list[_ntp.scputimes]: ... + +def cpu_stats() -> _ntp.scpustats: ... +def getloadavg() -> tuple[float, float, float]: ... +def virtual_memory() -> _ntp.svmem: ... +def swap_memory() -> _ntp.sswap: ... +def disk_usage(path: str) -> _ntp.sdiskusage: ... +def disk_partitions(all: bool = False) -> list[_ntp.sdiskpart]: ... + +# TODO: Incorrect sdiskio for BSD systems: +@overload +def disk_io_counters(perdisk: Literal[False] = False, nowrap: bool = True) -> _ntp.sdiskio | None: ... +@overload +def disk_io_counters(perdisk: Literal[True], nowrap: bool = True) -> dict[str, _ntp.sdiskio]: ... + +@overload +def net_io_counters(pernic: Literal[False] = False, nowrap: bool = True) -> _ntp.snetio: ... +@overload +def net_io_counters(pernic: Literal[True], nowrap: bool = True) -> dict[str, _ntp.snetio]: ... + +def net_connections(kind: str = "inet") -> list[_ntp.sconn]: ... +def net_if_addrs() -> dict[str, list[_ntp.snicaddr]]: ... +def net_if_stats() -> dict[str, _ntp.snicstats]: ... +def boot_time() -> float: ... +def users() -> list[_ntp.suser]: ... diff --git a/stubs/psutil/psutil/_common.pyi b/stubs/psutil/psutil/_common.pyi new file mode 100644 index 000000000000..e7a974bc77cc --- /dev/null +++ b/stubs/psutil/psutil/_common.pyi @@ -0,0 +1,253 @@ +import enum +import io +import sys +import threading +from _typeshed import ConvertibleToFloat, FileDescriptorOrPath, Incomplete, StrOrBytesPath, SupportsWrite +from collections import defaultdict +from collections.abc import Callable +from socket import AF_INET6 as AF_INET6, AddressFamily, SocketKind +from typing import BinaryIO, Final, ParamSpec, SupportsIndex, TypeVar, overload + +from . import _ntuples as ntp + +POSIX: Final[bool] +WINDOWS: Final[bool] +LINUX: Final[bool] +MACOS: Final[bool] +OSX: Final[bool] +FREEBSD: Final[bool] +OPENBSD: Final[bool] +NETBSD: Final[bool] +BSD: Final[bool] +SUNOS: Final[bool] +AIX: Final[bool] + +STATUS_RUNNING: Final = "running" +STATUS_SLEEPING: Final = "sleeping" +STATUS_DISK_SLEEP: Final = "disk-sleep" +STATUS_STOPPED: Final = "stopped" +STATUS_TRACING_STOP: Final = "tracing-stop" +STATUS_ZOMBIE: Final = "zombie" +STATUS_DEAD: Final = "dead" +STATUS_WAKE_KILL: Final = "wake-kill" +STATUS_WAKING: Final = "waking" +STATUS_IDLE: Final = "idle" +STATUS_LOCKED: Final = "locked" +STATUS_WAITING: Final = "waiting" +STATUS_SUSPENDED: Final = "suspended" +STATUS_PARKED: Final = "parked" + +CONN_ESTABLISHED: Final = "ESTABLISHED" +CONN_SYN_SENT: Final = "SYN_SENT" +CONN_SYN_RECV: Final = "SYN_RECV" +CONN_FIN_WAIT1: Final = "FIN_WAIT1" +CONN_FIN_WAIT2: Final = "FIN_WAIT2" +CONN_TIME_WAIT: Final = "TIME_WAIT" +CONN_CLOSE: Final = "CLOSE" +CONN_CLOSE_WAIT: Final = "CLOSE_WAIT" +CONN_LAST_ACK: Final = "LAST_ACK" +CONN_LISTEN: Final = "LISTEN" +CONN_CLOSING: Final = "CLOSING" +CONN_NONE: Final = "NONE" + +class NicDuplex(enum.IntEnum): + NIC_DUPLEX_FULL = 2 + NIC_DUPLEX_HALF = 1 + NIC_DUPLEX_UNKNOWN = 0 + +NIC_DUPLEX_FULL: Final = NicDuplex.NIC_DUPLEX_FULL +NIC_DUPLEX_HALF: Final = NicDuplex.NIC_DUPLEX_HALF +NIC_DUPLEX_UNKNOWN: Final = NicDuplex.NIC_DUPLEX_UNKNOWN + +class BatteryTime(enum.IntEnum): + POWER_TIME_UNKNOWN = -1 + POWER_TIME_UNLIMITED = -2 + +POWER_TIME_UNKNOWN: Final = BatteryTime.POWER_TIME_UNKNOWN +POWER_TIME_UNLIMITED: Final = BatteryTime.POWER_TIME_UNLIMITED + +ENCODING: Final[str] +ENCODING_ERRS: Final[str] + +conn_tmap: dict[str, tuple[list[AddressFamily], list[SocketKind]]] + +class Error(Exception): ... + +class NoSuchProcess(Error): + pid: int + name: str | None + msg: str + def __init__(self, pid: int, name: str | None = None, msg: str | None = None) -> None: ... + +class ZombieProcess(NoSuchProcess): + ppid: int | None + def __init__(self, pid: int, name: str | None = None, ppid: int | None = None, msg: str | None = None) -> None: ... + +class AccessDenied(Error): + pid: int | None + name: str | None + msg: str + def __init__(self, pid: int | None = None, name: str | None = None, msg: str | None = None) -> None: ... + +class TimeoutExpired(Error): + seconds: float + pid: int | None + name: str | None + msg: str + def __init__(self, seconds: float, pid: int | None = None, name: str | None = None) -> None: ... + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_T = TypeVar("_T") + +def usage_percent(used: ConvertibleToFloat, total: float, round_: SupportsIndex | None = None) -> float: ... + +# returned function has `cache_clear()` attribute: +def memoize(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + +# returned function has `cache_activate(proc)` and `cache_deactivate(proc)` attributes: +def memoize_when_activated(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... +def isfile_strict(path: StrOrBytesPath) -> bool: ... +def path_exists_strict(path: StrOrBytesPath) -> bool: ... +def supports_ipv6() -> bool: ... +def parse_environ_block(data: str) -> dict[str, str]: ... +def sockfam_to_enum(num: int) -> AddressFamily: ... +def socktype_to_enum(num: int) -> SocketKind: ... + +@overload +def conn_to_ntuple( + fd: int, + fam: int, + type_: int, + laddr: ntp.addr | tuple[str, int] | tuple[()], + raddr: ntp.addr | tuple[str, int] | tuple[()], + status: int | str, + status_map: dict[int, str] | dict[str, str], + pid: int, +) -> ntp.sconn: ... +@overload +def conn_to_ntuple( + fd: int, + fam: int, + type_: int, + laddr: ntp.addr | tuple[str, int] | tuple[()], + raddr: ntp.addr | tuple[str, int] | tuple[()], + status: int | str, + status_map: dict[int, str] | dict[str, str], + pid: None = None, +) -> ntp.pconn: ... + +def deprecated_method(replacement: str) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ... + +class _WrapNumbers: + lock: threading.Lock + cache: dict[str, dict[str, tuple[int, ...]]] + reminders: dict[str, defaultdict[Incomplete, int]] + reminder_keys: dict[str, defaultdict[Incomplete, set[Incomplete]]] + def __init__(self) -> None: ... + def run(self, input_dict: dict[str, tuple[int, ...]], name: str) -> dict[str, tuple[int, ...]]: ... + def cache_clear(self, name: str | None = None) -> None: ... + def cache_info( + self, + ) -> tuple[ + dict[str, dict[str, tuple[int, ...]]], + dict[str, defaultdict[Incomplete, int]], + dict[str, defaultdict[Incomplete, set[Incomplete]]], + ]: ... + +def wrap_numbers(input_dict: dict[str, tuple[int, ...]], name: str) -> dict[str, tuple[int, ...]]: ... +def open_binary(fname: FileDescriptorOrPath) -> BinaryIO: ... +def open_text(fname: FileDescriptorOrPath) -> io.TextIOWrapper: ... + +@overload +def cat(fname: FileDescriptorOrPath, _open: Callable[[FileDescriptorOrPath], io.TextIOWrapper] = ...) -> str: ... +@overload +def cat( + fname: FileDescriptorOrPath, fallback: _T = ..., _open: Callable[[FileDescriptorOrPath], io.TextIOWrapper] = ... +) -> str | _T: ... + +@overload +def bcat(fname: FileDescriptorOrPath) -> str: ... +@overload +def bcat(fname: FileDescriptorOrPath, fallback: _T = ...) -> str | _T: ... + +def bytes2human(n: int, format: str = "%(value).1f%(symbol)s") -> str: ... +def get_procfs_path() -> str: ... +def decode(s: bytes) -> str: ... +def term_supports_colors(file: SupportsWrite[str] = sys.stdout) -> bool: ... +def hilite(s: str, color: str | None = None, bold: bool = False) -> str: ... +def print_color(s: str, color: str | None = None, bold: bool = False, file: SupportsWrite[str] = sys.stdout) -> None: ... +def debug(msg: str | Exception) -> None: ... + +__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", + # 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", +] diff --git a/stubs/psutil/psutil/_ntuples.pyi b/stubs/psutil/psutil/_ntuples.pyi new file mode 100644 index 000000000000..b61b6ac2db36 --- /dev/null +++ b/stubs/psutil/psutil/_ntuples.pyi @@ -0,0 +1,384 @@ +import sys +from _typeshed import Incomplete +from socket import AddressFamily, SocketKind +from typing import Any, NamedTuple + +# All named tuples are defined in this file, but due to the inability to detect some platforms, +# it was decided to store the correct named tuples inside platform-specific files. + +class sswap(NamedTuple): + total: int + used: int + free: int + percent: float + sin: int + sout: int + +class sdiskusage(NamedTuple): + total: int + used: int + free: int + percent: float + +# redefine for linux: +if sys.platform != "linux": + class sdiskio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_time: int + write_time: int + +class sdiskpart(NamedTuple): + device: str + mountpoint: str + fstype: str + opts: str + +class snetio(NamedTuple): + bytes_sent: int + bytes_recv: int + packets_sent: int + packets_recv: int + errin: int + errout: int + dropin: int + dropout: int + +class suser(NamedTuple): + name: str + terminal: str | None + host: str | None + started: float + pid: str + +class sconn(NamedTuple): + fd: int + family: AddressFamily + type: SocketKind + laddr: addr | tuple[()] + raddr: addr | tuple[()] + status: str + pid: int | None + +class snicaddr(NamedTuple): + family: AddressFamily + address: str + netmask: str | None + broadcast: str | None + ptp: str | None + +class snicstats(NamedTuple): + isup: bool + duplex: int + speed: int + mtu: int + flags: str + +class scpustats(NamedTuple): + ctx_switches: int + interrupts: int + soft_interrupts: int + syscalls: int + +class scpufreq(NamedTuple): + current: float + min: float + max: float + +class shwtemp(NamedTuple): + label: str + current: float + high: float | None + critical: float | None + +class sbattery(NamedTuple): + percent: int + secsleft: int + power_plugged: bool + +class sfan(NamedTuple): + label: str + current: int + +if sys.platform == "win32": + class pheap(NamedTuple): + heap_used: Incomplete + mmap_used: Incomplete + heap_count: Incomplete + +else: + # if LINUX or MACOS or BSD: + class pheap(NamedTuple): + heap_used: Incomplete + mmap_used: Incomplete + +# redefine for linux: +if sys.platform != "linux": + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class popenfile(NamedTuple): + path: str + fd: int + +class pthread(NamedTuple): + id: int + user_time: float + system_time: float + +class puids(NamedTuple): + real: int + effective: int + saved: int + +class pgids(NamedTuple): + real: int + effective: int + saved: int + +# redefine for linux and windows: +if sys.platform != "linux" and sys.platform != "win32": + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + +class pionice(NamedTuple): + ioclass: int + value: int + +class pctxsw(NamedTuple): + voluntary: int + involuntary: int + +class pconn(NamedTuple): + fd: int + family: AddressFamily + type: SocketKind + laddr: addr + raddr: addr + status: str + +class addr(NamedTuple): + ip: str + port: int + +if sys.platform == "linux": + class scputimes(NamedTuple): + # Note: scputimes has different fields depending on exactly how Linux + # is setup, but we'll include the "complete" set of fields + user: float + nice: float + system: float + idle: float + iowait: float + irq: float + softirq: float + steal: float + guest: float + guest_nice: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + buffers: int + cached: int + shared: int + slab: int + + class sdiskio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_time: int + write_time: int + read_merged_count: int + write_merged_count: int + busy_time: int + + class popenfile(NamedTuple): + path: str + fd: int + position: int + mode: str + flags: int + + class pmem(NamedTuple): + rss: int + vms: int + shared: int + text: int + lib: int + data: int + dirty: int + + class pfullmem(NamedTuple): + rss: int + vms: int + shared: int + text: int + lib: int + data: int + dirty: int + uss: int + pss: int + swap: int + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + size: Incomplete + pss: Incomplete + shared_clean: Incomplete + shared_dirty: Incomplete + private_clean: Incomplete + private_dirty: Incomplete + referenced: Incomplete + anonymous: Incomplete + swap: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + size: Incomplete + pss: Incomplete + shared_clean: Incomplete + shared_dirty: Incomplete + private_clean: Incomplete + private_dirty: Incomplete + referenced: Incomplete + anonymous: Incomplete + swap: Incomplete + + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + read_chars: int + write_chars: int + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + iowait: float + +elif sys.platform == "win32": + class scputimes(NamedTuple): + user: float + system: float + idle: float + interrupt: float + dpc: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + class pmem(NamedTuple): + rss: int + vms: int + num_page_faults: int + peak_wset: int + wset: int + peak_paged_pool: int + paged_pool: int + peak_nonpaged_pool: int + nonpaged_pool: int + pagefile: int + peak_pagefile: int + private: int + + class pfullmem(NamedTuple): + rss: int + vms: int + num_page_faults: int + peak_wset: int + wset: int + peak_paged_pool: int + paged_pool: int + peak_nonpaged_pool: int + nonpaged_pool: int + pagefile: int + peak_pagefile: int + private: int + uss: int + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + + class pio(NamedTuple): + read_count: int + write_count: int + read_bytes: int + write_bytes: int + other_count: int + other_bytes: int + +elif sys.platform == "darwin": + class scputimes(NamedTuple): + user: float + nice: float + system: float + idle: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + wired: int + + class pmem(NamedTuple): + rss: int + vms: int + pfaults: int + pageins: int + + class pfullmem(NamedTuple): + rss: int + vms: int + pfaults: int + pageins: int + uss: int + +else: + # See _psbsd.pyi, _pssunos.pyi or _psaix.pyi + # BSD: svmem, scputimes, pmem, pfullmem, pcputimes, pmmap_grouped, pmmap_ext, sdiskio + # SUNOS: scputimes, pcputimes, svmem, pmem, pfullmem, pmmap_grouped, pmmap_ext + # AIX: pmem, pfullmem, scputimes, svmem + + scputimes = Incomplete + + class pmem(Any): ... + class pfullmem(Any): ... + class svmem(Any): ... diff --git a/stubs/psutil/psutil/_psaix.pyi b/stubs/psutil/psutil/_psaix.pyi new file mode 100644 index 000000000000..195fd25591e2 --- /dev/null +++ b/stubs/psutil/psutil/_psaix.pyi @@ -0,0 +1,112 @@ +import sys + +# sys.platform.startswith("aix"): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from collections.abc import Callable + from typing import Final, Literal, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, + NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, + NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_to_ntuple as conn_to_ntuple, + get_procfs_path as get_procfs_path, + memoize_when_activated as memoize_when_activated, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_aix + + __extra__all__: Final[list[str]] + HAS_THREADS: Final[bool] + HAS_NET_IO_COUNTERS: Final[bool] + HAS_PROC_IO_COUNTERS: Final[bool] + PAGE_SIZE: Final[int] + AF_LINK: Final = 18 + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + proc_info_map: Final[dict[str, int]] + + class pmem(NamedTuple): + rss: int + vms: int + + pfullmem = pmem + + class scputimes(NamedTuple): + user: float + system: float + idle: float + iowait: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + + disk_io_counters = _psutil_aix.disk_io_counters + disk_usage = _psposix.disk_usage + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + net_if_addrs = _psutil_aix.net_if_addrs + net_io_counters = _psutil_aix.net_io_counters + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + def pid_exists(pid: int | str) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def create_time(self) -> float: ... + def num_threads(self) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def terminal(self) -> str | None: ... + def cwd(self) -> str: ... + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def status(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def num_fds(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def io_counters(self) -> ntp.pio: ... diff --git a/stubs/psutil/psutil/_psbsd.pyi b/stubs/psutil/psutil/_psbsd.pyi new file mode 100644 index 000000000000..7b7a18140705 --- /dev/null +++ b/stubs/psutil/psutil/_psbsd.pyi @@ -0,0 +1,213 @@ +import sys + +# sys.platform.startswith(("freebsd", "midnightbsd", "openbsd", "netbsd")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _typeshed import Incomplete + from collections import defaultdict + from collections.abc import Callable + from contextlib import AbstractContextManager + from typing import Final, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + FREEBSD as FREEBSD, + NETBSD as NETBSD, + OPENBSD as OPENBSD, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + memoize as memoize, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_bsd + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + PAGESIZE: Final[int] + AF_LINK: Final = _psutil_bsd.AF_LINK + HAS_PROC_NUM_THREADS: Final[bool] + kinfo_proc_map: Final[dict[str, int]] + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + active: int + inactive: int + buffers: int + cached: int + shared: int + wired: int + + class scputimes(NamedTuple): + user: float + nice: float + system: float + idle: float + irq: float + + class pmem(NamedTuple): + rss: int + vms: int + text: int + data: int + stack: int + + pfullmem = pmem + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class sdiskio(NamedTuple): + read_count: Incomplete + write_count: Incomplete + read_bytes: Incomplete + write_bytes: Incomplete + read_time: Incomplete + write_time: Incomplete + busy_time: Incomplete + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_bsd.heap_info # only FreeBSD and NetBSD + heap_trim = _psutil_bsd.heap_trim # only FreeBSD and NetBSD + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + disk_usage = _psposix.disk_usage + disk_io_counters = _psutil_bsd.disk_io_counters + net_io_counters = _psutil_bsd.net_io_counters + net_if_addrs = _psutil_bsd.net_if_addrs + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def net_connections(kind: str) -> list[ntp.sconn]: ... + def sensors_battery() -> ntp.sbattery | None: ... # only FreeBSD + def sensors_temperatures() -> defaultdict[str, list[ntp.shwtemp]]: ... # only FreeBSD + def cpu_freq() -> list[ntp.scpufreq]: ... # only FreeBSD and OpenBSD + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + + INIT_BOOT_TIME: Final[float] # only NetBSD + + def adjust_proc_create_time(ctime: float) -> float: ... # only NetBSD + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + def wrap_exceptions_procfs(inst: Process) -> AbstractContextManager[None]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot( + self, + ) -> tuple[ + int, + int, + int, + int, + int, + int, + int, + int, + int, + float, + int, + int, + int, + int, + float, + float, + float, + float, + int, + int, + int, + int, + int, + int, + str, + ]: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def terminal(self) -> str | None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.pgids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... # only FreeBSD + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def create_time(self, monotonic: bool = False) -> float: ... + def num_threads(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def threads(self) -> list[ntp.pthread]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def status(self) -> str: ... + def io_counters(self) -> ntp.pio: ... + def cwd(self) -> str: ... + + class nt_mmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + class nt_mmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + private: Incomplete + ref_count: Incomplete + shadow_count: Incomplete + + def open_files(self) -> list[ntp.popenfile]: ... + def num_fds(self) -> int: ... + def cpu_affinity_get(self) -> list[int]: ... # only FreeBSD + def cpu_affinity_set(self, cpus: list[int]) -> None: ... # only FreeBSD + def memory_maps(self) -> list[tuple[str, str, str, int, int, int, int]]: ... # only FreeBSD + + @overload + def rlimit(self, resource: int, limits: tuple[int, int]) -> None: ... # only FreeBSD + @overload + def rlimit(self, resource: int, limits: None = None) -> tuple[int, int]: ... # only FreeBSD diff --git a/stubs/psutil/psutil/_pslinux.pyi b/stubs/psutil/psutil/_pslinux.pyi new file mode 100644 index 000000000000..34bb16456b44 --- /dev/null +++ b/stubs/psutil/psutil/_pslinux.pyi @@ -0,0 +1,183 @@ +import sys + +if sys.platform == "linux": + import enum + import re + from _typeshed import FileDescriptorOrPath + from collections import defaultdict + from collections.abc import Callable, Generator, Sequence + from typing import Final, ParamSpec, TypeVar, overload + + from psutil._common import ( + ENCODING as ENCODING, + NIC_DUPLEX_FULL as NIC_DUPLEX_FULL, + NIC_DUPLEX_HALF as NIC_DUPLEX_HALF, + NIC_DUPLEX_UNKNOWN as NIC_DUPLEX_UNKNOWN, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + bcat as bcat, + cat as cat, + debug as debug, + decode as decode, + get_procfs_path as get_procfs_path, + isfile_strict as isfile_strict, + memoize as memoize, + memoize_when_activated as memoize_when_activated, + open_binary as open_binary, + open_text as open_text, + parse_environ_block as parse_environ_block, + path_exists_strict as path_exists_strict, + supports_ipv6 as supports_ipv6, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_linux + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + POWER_SUPPLY_PATH: Final = "/sys/class/power_supply" + HAS_PROC_SMAPS: Final[bool] + HAS_PROC_SMAPS_ROLLUP: Final[bool] + HAS_PROC_IO_PRIORITY: Final[bool] + HAS_CPU_AFFINITY: Final[bool] + CLOCK_TICKS: Final[int] + PAGESIZE: Final[int] + LITTLE_ENDIAN: Final[bool] + UNSET: object + DISK_SECTOR_SIZE: Final = 512 + + class AddressFamily(enum.IntEnum): + AF_LINK = 17 # = socket.AF_PACKET + + AF_LINK: Final = AddressFamily.AF_LINK + + class IOPriority(enum.IntEnum): + IOPRIO_CLASS_NONE = 0 + IOPRIO_CLASS_RT = 1 + IOPRIO_CLASS_BE = 2 + IOPRIO_CLASS_IDLE = 3 + + IOPRIO_CLASS_NONE: Final = IOPriority.IOPRIO_CLASS_NONE + IOPRIO_CLASS_RT: Final = IOPriority.IOPRIO_CLASS_RT + IOPRIO_CLASS_BE: Final = IOPriority.IOPRIO_CLASS_BE + IOPRIO_CLASS_IDLE: Final = IOPriority.IOPRIO_CLASS_IDLE + + PROC_STATUSES: Final[dict[str, str]] + TCP_STATUSES: Final[dict[str, str]] + + def readlink(path: str) -> str: ... + def file_flags_to_mode(flags: int) -> str: ... + def is_storage_device(name: str) -> bool: ... + def _scputimes_ntuple(procfs_path: str) -> type[ntp.scputimes]: ... + scputimes = ntp.scputimes + def calculate_avail_vmem(mems: dict[bytes, int]) -> int: ... + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_linux.heap_info + heap_trim = _psutil_linux.heap_trim + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... + + net_if_addrs = _psutil_linux.net_if_addrs + + class _Ipv6UnsupportedError(Exception): ... + + class NetConnections: + tmap: dict[str, tuple[tuple[str, int, int | None], ...]] + def __init__(self) -> None: ... + def get_proc_inodes(self, pid: int) -> defaultdict[str, list[tuple[int, int]]]: ... + def get_all_inodes(self) -> dict[str, list[tuple[int, int]]]: ... + @staticmethod + def decode_address(addr: str, family: int) -> ntp.addr | tuple[()]: ... + @staticmethod + def process_inet( + file: str, family: int, type_: int, inodes: dict[str, list[tuple[int, int]]], filter_pid: int | None = None + ) -> Generator[tuple[int, int, int, ntp.addr | tuple[()], ntp.addr | tuple[()], str, int | None]]: ... + @staticmethod + def process_unix( + file: FileDescriptorOrPath, family: int, inodes: dict[str, list[tuple[int, int]]], filter_pid: int | None = None + ) -> Generator[tuple[int, int, int, str, str, str, int | None]]: ... + + @overload + def retrieve(self, kind: str, pid: int) -> list[ntp.pconn]: ... + @overload + def retrieve(self, kind: str, pid: None = None) -> list[ntp.sconn]: ... + + def net_connections(kind: str = "inet") -> list[ntp.sconn]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def net_if_stats() -> dict[str, ntp.snicstats]: ... + + disk_usage = _psposix.disk_usage + + def disk_io_counters(perdisk: bool = False) -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + + class RootFsDeviceFinder: + __slots__ = ["major", "minor"] + major: int + minor: int + def __init__(self) -> None: ... + def ask_proc_partitions(self) -> str | None: ... + def ask_sys_dev_block(self) -> str | None: ... + def ask_sys_class_block(self) -> str | None: ... + def find(self) -> str | None: ... + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + def sensors_temperatures() -> dict[str, list[tuple[str, float, float | None, float | None]]]: ... + def sensors_fans() -> dict[str, list[ntp.sfan]]: ... + def sensors_battery() -> ntp.sbattery | None: ... + def users() -> list[ntp.suser]: ... + def boot_time() -> float: ... + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def ppid_map() -> dict[int, int]: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_ctime", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def terminal(self) -> str | None: ... + def io_counters(self) -> ntp.pio: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def create_time(self, monotonic: bool = False) -> float: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def memory_maps(self) -> list[tuple[str, str, str, int, int, int, int, int, int, int, int, int, int]]: ... + def cwd(self) -> str: ... + def num_ctx_switches(self, _ctxsw_re: re.Pattern[bytes] = ...) -> ntp.pctxsw: ... + def num_threads(self, _num_threads_re: re.Pattern[bytes] = ...) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def cpu_affinity_get(self) -> list[int]: ... + def cpu_affinity_set(self, cpus: Sequence[int]) -> None: ... + def ionice_get(self) -> ntp.pionice: ... + def ionice_set(self, ioclass: int, value: int | None) -> None: ... + + @overload + def rlimit(self, resource_: int, limits: tuple[int, int]) -> None: ... + @overload + def rlimit(self, resource_: int, limits: None = None) -> tuple[int, int]: ... + + def status(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def num_fds(self) -> int: ... + def ppid(self) -> int: ... + def uids(self, _uids_re: re.Pattern[bytes] = ...) -> ntp.puids: ... + def gids(self, _gids_re: re.Pattern[bytes] = ...) -> ntp.pgids: ... diff --git a/stubs/psutil/psutil/_psosx.pyi b/stubs/psutil/psutil/_psosx.pyi new file mode 100644 index 000000000000..b8f5cbce2acc --- /dev/null +++ b/stubs/psutil/psutil/_psosx.pyi @@ -0,0 +1,89 @@ +import sys + +if sys.platform == "darwin": + from collections.abc import Callable + from typing import Final, ParamSpec, TypeVar + + from psutil._common import ( + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + debug as debug, + isfile_strict as isfile_strict, + memoize_when_activated as memoize_when_activated, + parse_environ_block as parse_environ_block, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_osx + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + PAGESIZE: Final[int] + AF_LINK: Final[int] + TCP_STATUSES: Final[dict[int, str]] + PROC_STATUSES: Final[dict[int, str]] + kinfo_proc_map: Final[dict[str, int]] + pidtaskinfo_map: Final[dict[str, int]] + + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + heap_info = _psutil_osx.heap_info + heap_trim = _psutil_osx.heap_trim + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... + + disk_usage = _psposix.disk_usage + disk_io_counters = _psutil_osx.disk_io_counters + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + def sensors_battery() -> ntp.sbattery | None: ... + + net_io_counters = _psutil_osx.net_io_counters + net_if_addrs = _psutil_osx.net_if_addrs + def net_connections(kind: str = "inet") -> list[ntp.sconn]: ... + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + INIT_BOOT_TIME: float + def adjust_proc_create_time(ctime: float) -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + pid_exists = _psposix.pid_exists + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def ppid(self) -> int: ... + def cwd(self) -> str: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def terminal(self) -> str | None: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def cpu_times(self) -> ntp.pcputimes: ... + def create_time(self, monotonic: bool = False) -> float: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def num_threads(self) -> int: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def num_fds(self) -> int: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def status(self) -> str: ... + def threads(self) -> list[ntp.pthread]: ... diff --git a/stubs/psutil/psutil/_psposix.pyi b/stubs/psutil/psutil/_psposix.pyi new file mode 100644 index 000000000000..69694bfa4490 --- /dev/null +++ b/stubs/psutil/psutil/_psposix.pyi @@ -0,0 +1,85 @@ +import enum +import sys +from _typeshed import FileDescriptorOrPath, Incomplete, StrOrBytesPath, Unused +from collections.abc import Callable + +from . import _ntuples as ntp + +def pid_exists(pid: int) -> bool: ... + +# Sync with `signal.Signals`, but with opposite values: +class Negsignal(enum.IntEnum): + SIGABRT = -6 + SIGFPE = -8 + SIGILL = -4 + SIGINT = -2 + SIGSEGV = -11 + SIGTERM = -15 + + if sys.platform == "win32": + SIGBREAK = -21 + CTRL_C_EVENT = 0 + CTRL_BREAK_EVENT = -1 + else: + SIGALRM = -14 + SIGBUS = -7 + SIGCHLD = -17 + SIGCONT = -18 + SIGHUP = -1 + SIGIO = -29 + SIGIOT = -6 + SIGKILL = -9 + SIGPIPE = -13 + SIGPROF = -27 + SIGQUIT = -3 + SIGSTOP = -19 + SIGSYS = -31 + SIGTRAP = -5 + SIGTSTP = -20 + SIGTTIN = -21 + SIGTTOU = -22 + SIGURG = -23 + SIGUSR1 = -10 + SIGUSR2 = -12 + SIGVTALRM = -26 + SIGWINCH = -28 + SIGXCPU = -24 + SIGXFSZ = -25 + if sys.platform != "linux": + SIGEMT = -7 + SIGINFO = -29 + if sys.platform != "darwin": + SIGCLD = -17 + SIGPOLL = -29 + SIGPWR = -30 + SIGRTMAX = -64 + SIGRTMIN = -34 + if sys.version_info >= (3, 11): + SIGSTKFLT = -16 + +def negsig_to_enum(num: int) -> int: ... +def convert_exit_code(status: int) -> int: ... +def wait_pid_posix( + pid: int, + timeout: float | None = None, + _waitpid: Unused = ..., + _timer: Callable[[], float] = ..., + _min: Callable[..., Incomplete] = ..., + _sleep: Callable[[float], None] = ..., + _pid_exists: Callable[[int], bool] = ..., +) -> int | None: ... +def wait_pid_pidfd_open(pid: int, timeout: float | None = None) -> int | None: ... +def wait_pid_kqueue(pid: int, timeout: float | None = None) -> int | None: ... +def can_use_pidfd_open() -> bool: ... +def can_use_kqueue() -> bool: ... +def wait_pid(pid: int, timeout: float | None = None) -> int | None: ... + +if sys.platform == "darwin": + def disk_usage(path: StrOrBytesPath) -> ntp.sdiskusage: ... + +else: + def disk_usage(path: FileDescriptorOrPath) -> ntp.sdiskusage: ... + +def get_terminal_map() -> dict[int, str]: ... + +__all__ = ["pid_exists", "wait_pid", "disk_usage", "get_terminal_map"] diff --git a/stubs/psutil/psutil/_pssunos.pyi b/stubs/psutil/psutil/_pssunos.pyi new file mode 100644 index 000000000000..d1e3b6dba4aa --- /dev/null +++ b/stubs/psutil/psutil/_pssunos.pyi @@ -0,0 +1,151 @@ +import sys + +# sys.platform.startswith(("sunos", "solaris")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from _typeshed import Incomplete + from collections.abc import Callable + from typing import Final, Literal, NamedTuple, ParamSpec, TypeVar, overload + + from psutil._common import ( + AF_INET6 as AF_INET6, + ENCODING as ENCODING, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + ZombieProcess as ZombieProcess, + debug as debug, + get_procfs_path as get_procfs_path, + isfile_strict as isfile_strict, + memoize_when_activated as memoize_when_activated, + sockfam_to_enum as sockfam_to_enum, + socktype_to_enum as socktype_to_enum, + usage_percent as usage_percent, + ) + + from . import _ntuples as ntp, _psposix, _psutil_sunos + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + __extra__all__: Final[list[str]] + PAGE_SIZE: Final[int] + AF_LINK: Final[int] + IS_64_BIT: Final[bool] + CONN_IDLE: Final = "IDLE" + CONN_BOUND: Final = "BOUND" + PROC_STATUSES: Final[dict[int, str]] + TCP_STATUSES: Final[dict[int, str]] + proc_info_map: Final[dict[str, int]] + + class scputimes(NamedTuple): + user: float + system: float + idle: float + iowait: float + + class pcputimes(NamedTuple): + user: float + system: float + children_user: float + children_system: float + + class svmem(NamedTuple): + total: int + available: int + percent: float + used: int + free: int + + class pmem(NamedTuple): + rss: int + vms: int + + pfullmem = pmem + + class pmmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + anonymous: Incomplete + locked: Incomplete + + class pmmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + anonymous: Incomplete + locked: Incomplete + + def virtual_memory() -> svmem: ... + def swap_memory() -> ntp.sswap: ... + def cpu_times() -> scputimes: ... + def per_cpu_times() -> list[scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + + disk_io_counters = _psutil_sunos.disk_io_counters + disk_usage = _psposix.disk_usage + + def disk_partitions(all: bool = False) -> list[ntp.sdiskpart]: ... + + net_io_counters = _psutil_sunos.net_io_counters + net_if_addrs = _psutil_sunos.net_if_addrs + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def pids() -> list[int]: ... + def pid_exists(pid: int) -> bool: ... + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str] | None: ... + def environ(self) -> dict[str, str]: ... + def create_time(self) -> float: ... + def num_threads(self) -> int: ... + def nice_get(self) -> int: ... + def nice_set(self, value: int) -> None: ... + def ppid(self) -> int: ... + def uids(self) -> ntp.puids: ... + def gids(self) -> ntp.puids: ... + def cpu_times(self) -> ntp.pcputimes: ... + def cpu_num(self) -> int: ... + def terminal(self) -> str | None: ... + def cwd(self) -> str: ... + def memory_info(self) -> pmem: ... + memory_full_info = memory_info + def status(self) -> str: ... + def threads(self) -> list[ntp.pthread]: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + + class nt_mmap_grouped(NamedTuple): + path: Incomplete + rss: Incomplete + anon: Incomplete + locked: Incomplete + + class nt_mmap_ext(NamedTuple): + addr: Incomplete + perms: Incomplete + path: Incomplete + rss: Incomplete + anon: Incomplete + locked: Incomplete + + def memory_maps(self) -> list[tuple[str, str, str, int, int, int]]: ... + def num_fds(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... + def wait(self, timeout: float | None = None) -> int | None: ... diff --git a/stubs/psutil/psutil/_psutil_aix.pyi b/stubs/psutil/psutil/_psutil_aix.pyi new file mode 100644 index 000000000000..17977e3eadcb --- /dev/null +++ b/stubs/psutil/psutil/_psutil_aix.pyi @@ -0,0 +1,58 @@ +import sys + +# sys.platform.startswith("aix"): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from typing import Final + + AF_LINK: Final = 18 + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + + version: Final[int] + SIDL: Final[int] + SZOMB: Final[int] + SACTIVE: Final[int] + SSWAP: Final[int] + SSTOP: Final[int] + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RCVD: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_args(pid: int, /) -> list[str]: ... + def proc_basic_info(pid: int, procfs_path: str, /) -> tuple[int, int, int, float, int, int, int, int]: ... + def proc_cpu_times(pid: int, procfs_path: str, /) -> tuple[float, float, float, float]: ... + def proc_cred(pid: int, procfs_path: str, /) -> tuple[int, int, int, int, int, int]: ... + def proc_environ(pid: int, /) -> dict[str, str]: ... + def proc_name(pid: int, procfs_path: str, /) -> str: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_io_counters(pid: int, /) -> tuple[int, int, int, int]: ... + def proc_num_ctx_switches(requested_pid: int, /) -> tuple[int, int]: ... + def boot_time() -> float: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def swap_mem() -> tuple[int, int, int, int]: ... + def virtual_mem() -> tuple[int, int, int, int, int]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def net_connections( + requested_pid: int, / + ) -> list[tuple[int, int, int, str | tuple[str, int], str | tuple[str, int] | tuple[()], int, int]]: ... + def net_if_stats(nic_name: str, /) -> tuple[bool, int]: ... # It's actually list of 2 elements + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_bsd.pyi b/stubs/psutil/psutil/_psutil_bsd.pyi new file mode 100644 index 000000000000..9aabf5116d03 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_bsd.pyi @@ -0,0 +1,145 @@ +import sys + +# sys.platform.startswith(("freebsd", "midnightbsd", "openbsd", "netbsd")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final, overload + + AF_LINK: Final[int] + RLIMIT_AS: Final[int] # only FreeBSD + RLIMIT_CORE: Final[int] # only FreeBSD + RLIMIT_CPU: Final[int] # only FreeBSD + RLIMIT_DATA: Final[int] # only FreeBSD + RLIMIT_FSIZE: Final[int] # only FreeBSD + RLIMIT_MEMLOCK: Final[int] # only FreeBSD + RLIMIT_NOFILE: Final[int] # only FreeBSD + RLIMIT_NPROC: Final[int] # only FreeBSD + RLIMIT_RSS: Final[int] # only FreeBSD + RLIMIT_STACK: Final[int] # only FreeBSD + RLIMIT_SWAP: Final[int] # only FreeBSD + RLIMIT_SBSIZE: Final[int] # only FreeBSD + RLIMIT_NPTS: Final[int] # only FreeBSD + RLIM_INFINITY: Final[int] # only FreeBSD + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def proc_is_zombie(pid: int, /) -> bool: ... + + version: Final[int] + SIDL: Final[int] + SRUN: Final[int] + SSLEEP: Final[int] + SSTOP: Final[int] + SZOMB: Final[int] + SWAIT: Final[int] # only FreeBSD + SLOCK: Final[int] # only FreeBSD + SDEAD: Final[int] # only OpenBSD and NetBSD + SONPROC: Final[int] # only OpenBSD and NetBSD + SSUSPENDED: Final[int] # only NetBSD + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RECEIVED: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_cmdline(pid: int, /) -> list[str]: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> dict[str, str]: ... + def proc_name(pid: int, /) -> str: ... + def proc_num_fds(pid: int, /) -> int: ... + def proc_oneshot_info( + pid: int, / + ) -> tuple[ + int, + int, + int, + int, + int, + int, + int, + int, + int, + float, + int, + int, + int, + int, + float, + float, + float, + float, + int, + int, + int, + int, + int, + int, + str, + ]: ... + def proc_open_files(pid: int, /) -> list[tuple[str, int]]: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_num_threads(pid: int, /) -> int: ... # only FreeBSD and NetBSD + def proc_cpu_affinity_get(pid: int, /) -> list[int]: ... # only FreeBSD + def proc_cpu_affinity_set(pid: int, cpu_set: Sequence[int], /) -> None: ... # only FreeBSD + def proc_exe(pid: int, /) -> str: ... # only FreeBSD + def proc_getrlimit(pid: int, resource: int, /) -> tuple[int, int]: ... # only FreeBSD + def proc_memory_maps(pid: int, /) -> list[tuple[str, str, str, int, int, int, int]]: ... # only FreeBSD + def proc_net_connections( # only FreeBSD + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int] | tuple[int, int, int, str, str, int]]: ... + def proc_setrlimit(pid: int, resource: int, soft: int, hard: int, /) -> None: ... # only FreeBSD + def boot_time() -> float: ... + def cpu_count_logical() -> int | None: ... + def cpu_stats() -> tuple[int, ...]: ... # tuple's length depends on OS + def cpu_times() -> tuple[float, float, float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, ...]]: ... # tuple's length depends on OS + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + + @overload # for FreeBSD + def net_connections( + af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int] | tuple[int, int, int, str, str, int, int] + ]: ... + @overload # for OpenBSD + def net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int] | tuple[int, int, int, str, str, int, int] + ]: ... + @overload # for NetBSD + def net_connections(pid: int, kind: str, /) -> list[tuple[int, int, int, str, str, int, int]]: ... + + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float, float]]: ... + def pids() -> list[int]: ... + def swap_mem() -> tuple[int, int, int, int, int]: ... + def heap_info() -> tuple[int, int]: ... # only FreeBSD and NetBSD + def heap_trim() -> None: ... # only FreeBSD and NetBSD + def users() -> list[tuple[str, str, str, float, int | None]]: ... # returns None only in OpenBSD + def virtual_mem() -> tuple[int, ...]: ... # tuple's length depends on OS + + @overload + def cpu_freq() -> int: ... # only OpenBSD + @overload + def cpu_freq(core: int, /) -> tuple[int, str]: ... # only FreeBSD + + def cpu_topology() -> str | None: ... # only FreeBSD + def sensors_battery() -> tuple[int, int, int]: ... # only FreeBSD + def sensors_cpu_temperature(core: int, /) -> tuple[int, int]: ... # only FreeBSD + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_linux.pyi b/stubs/psutil/psutil/_psutil_linux.pyi new file mode 100644 index 000000000000..d24279961311 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_linux.pyi @@ -0,0 +1,49 @@ +import sys + +if sys.platform == "linux": + from collections.abc import Sequence + from typing import Final + + RLIMIT_AS: Final[int] + RLIMIT_CORE: Final[int] + RLIMIT_CPU: Final[int] + RLIMIT_DATA: Final[int] + RLIMIT_FSIZE: Final[int] + RLIMIT_MEMLOCK: Final[int] + RLIMIT_NOFILE: Final[int] + RLIMIT_NPROC: Final[int] + RLIMIT_RSS: Final[int] + RLIMIT_STACK: Final[int] + RLIMIT_LOCKS: Final[int] + RLIMIT_MSGQUEUE: Final[int] + RLIMIT_NICE: Final[int] + RLIMIT_RTPRIO: Final[int] + RLIMIT_RTTIME: Final[int] + RLIMIT_SIGPENDING: Final[int] + RLIM_INFINITY: Final[int] + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def users() -> list[tuple[str, str, str, float, int]]: ... + + version: Final[int] + DUPLEX_FULL: Final[int] + DUPLEX_HALF: Final[int] + DUPLEX_UNKNOWN: Final[int] + + def proc_ioprio_get(pid: int, /) -> tuple[int, int]: ... + def proc_ioprio_set(pid: int, ioclass: int, iodata: int, /) -> None: ... + def proc_cpu_affinity_get(pid: int, /) -> list[int]: ... + def proc_cpu_affinity_set(pid: int, cpu_set: Sequence[int], /) -> None: ... + def disk_partitions(mtab_path: str, /) -> list[tuple[str, str, str, str]]: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def heap_info() -> tuple[int, int]: ... + def heap_trim() -> bool: ... + def linux_sysinfo() -> tuple[int, int, int, int, int, int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_osx.pyi b/stubs/psutil/psutil/_psutil_osx.pyi new file mode 100644 index 000000000000..2ea2baca3d05 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_osx.pyi @@ -0,0 +1,79 @@ +import sys + +if sys.platform == "darwin": + from _typeshed import StrOrBytesPath + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final, TypeVar + + _T = TypeVar("_T") + + AF_LINK: Final = 18 + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def net_if_duplex_speed(nic_name: str, /) -> tuple[int, int]: ... # It's actually list of 2 elements + def users() -> list[tuple[str, str, str, float, int]]: ... + def proc_is_zombie(pid: int, /) -> bool: ... + + version: Final[int] + SIDL: Final = 1 + SRUN: Final = 2 + SSLEEP: Final = 3 + SSTOP: Final = 4 + SZOMB: Final = 5 + TCPS_CLOSED: Final = 0 + TCPS_CLOSING: Final = 7 + TCPS_CLOSE_WAIT: Final = 5 + TCPS_LISTEN: Final = 1 + TCPS_ESTABLISHED: Final = 4 + TCPS_SYN_SENT: Final = 2 + TCPS_SYN_RECEIVED: Final = 3 + TCPS_FIN_WAIT_1: Final = 6 + TCPS_FIN_WAIT_2: Final = 9 + TCPS_LAST_ACK: Final = 8 + TCPS_TIME_WAIT: Final = 10 + PSUTIL_CONN_NONE: Final = 128 + + def proc_cmdline(pid: int, /) -> list[str]: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> str: ... + def proc_exe(pid: int, /) -> str: ... + def proc_kinfo_oneshot(pid: int, /) -> tuple[int, int, int, int, int, int, int, float, int, str]: ... + def proc_memory_uss(pid: int, /) -> int: ... + def proc_name(pid: int, /) -> str: ... + def proc_net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[ + tuple[int, int, int, tuple[str | None, int], tuple[str | None, int] | tuple[()], int] + | tuple[int, int, int, str, str, int] + ]: ... + def proc_num_fds(pid: int, /) -> int: ... + def proc_open_files(pid: int, /) -> list[tuple[str, int]]: ... + def proc_pidtaskinfo_oneshot(pid: int, /) -> tuple[float, float, int, int, int, int, int, int]: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def boot_time() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_count_logical() -> int | None: ... + def cpu_freq() -> tuple[int, int, int]: ... + def cpu_stats() -> tuple[int, int, int, int, int]: ... + def cpu_times() -> tuple[float, float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def disk_usage_used(mount_point: StrOrBytesPath, default: _T, /) -> int | _T: ... + def has_cpu_freq() -> bool: ... + def heap_info() -> tuple[int, int]: ... + def heap_trim() -> None: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def pids() -> list[int]: ... + def sensors_battery() -> tuple[int, int, int]: ... + def swap_mem() -> tuple[int, int, int, int, int]: ... + def virtual_mem() -> tuple[int, int, int, int, int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_sunos.pyi b/stubs/psutil/psutil/_psutil_sunos.pyi new file mode 100644 index 000000000000..fe56efa827ba --- /dev/null +++ b/stubs/psutil/psutil/_psutil_sunos.pyi @@ -0,0 +1,63 @@ +import sys + +# sys.platform.startswith(("sunos", "solaris")): +if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin": + from typing import Final + + AF_LINK: Final[int] + + def getpagesize() -> int: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, str | None, str | None]]: ... + def net_if_flags(nic_name: str, /) -> list[str]: ... + def net_if_is_running(nic_name: str, /) -> bool: ... + def net_if_mtu(nic_name: str, /) -> int: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def users() -> list[tuple[str, str, str, float, int]]: ... + + version: Final[int] + # They could be different between different versions of SunOS/Solaris: + SSLEEP: Final[int] + SRUN: Final[int] + SZOMB: Final[int] + SSTOP: Final[int] + SIDL: Final[int] + SONPROC: Final[int] + SWAIT: Final[int] + PRNODEV: Final[int] + TCPS_CLOSED: Final[int] + TCPS_CLOSING: Final[int] + TCPS_CLOSE_WAIT: Final[int] + TCPS_LISTEN: Final[int] + TCPS_ESTABLISHED: Final[int] + TCPS_SYN_SENT: Final[int] + TCPS_SYN_RCVD: Final[int] + TCPS_FIN_WAIT_1: Final[int] + TCPS_FIN_WAIT_2: Final[int] + TCPS_LAST_ACK: Final[int] + TCPS_TIME_WAIT: Final[int] + TCPS_IDLE: Final[int] + TCPS_BOUND: Final[int] + PSUTIL_CONN_NONE: Final = 128 + + def proc_basic_info(pid: int, procfs_path: str, /) -> tuple[int, int, int, float, int, int, int, int, int, int, int, int]: ... + def proc_cpu_num(pid: int, procfs_path: str, /) -> int: ... + def proc_cpu_times(pid: int, procfs_path: str, /) -> tuple[float, float, float, float]: ... + def proc_cred(pid: int, procfs_path: str, /) -> tuple[int, int, int, int, int, int]: ... + def proc_environ(pid: int, procfs_path: str, /) -> dict[str, str]: ... + def proc_memory_maps(pid: int, procfs_path: str, /) -> list[tuple[int, int, str, str, int, int, int]]: ... + def proc_name_and_args(pid: int, procfs_path: str, /) -> tuple[str, list[str] | None]: ... + def proc_num_ctx_switches(pid: int, procfs_path: str, /) -> tuple[int, int]: ... + def query_process_thread(pid: int, tid: int, procfs_path: str, /) -> tuple[float, float]: ... + def boot_time() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions() -> list[tuple[str, str, str, str]]: ... + def net_connections(pid: int, /) -> list[tuple[int, int, int, tuple[str, int], tuple[str, int] | tuple[()], int, int]]: ... + def net_if_stats() -> dict[str, tuple[bool, int, int, int]]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float]]: ... + def swap_mem() -> tuple[int, int]: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_psutil_windows.pyi b/stubs/psutil/psutil/_psutil_windows.pyi new file mode 100644 index 000000000000..f48ed77998b2 --- /dev/null +++ b/stubs/psutil/psutil/_psutil_windows.pyi @@ -0,0 +1,105 @@ +import sys + +if sys.platform == "win32": + from collections.abc import Sequence + from socket import AddressFamily, SocketKind + from typing import Final + + version: Final[int] + ABOVE_NORMAL_PRIORITY_CLASS: Final = 32768 + BELOW_NORMAL_PRIORITY_CLASS: Final = 16384 + HIGH_PRIORITY_CLASS: Final = 128 + IDLE_PRIORITY_CLASS: Final = 64 + NORMAL_PRIORITY_CLASS: Final = 32 + REALTIME_PRIORITY_CLASS: Final = 256 + MIB_TCP_STATE_CLOSED: Final = 1 + MIB_TCP_STATE_CLOSING: Final = 9 + MIB_TCP_STATE_CLOSE_WAIT: Final = 8 + MIB_TCP_STATE_LISTEN: Final = 2 + MIB_TCP_STATE_ESTAB: Final = 5 + MIB_TCP_STATE_SYN_SENT: Final = 3 + MIB_TCP_STATE_SYN_RCVD: Final = 4 + MIB_TCP_STATE_FIN_WAIT1: Final = 6 + MIB_TCP_STATE_FIN_WAIT2: Final = 7 + MIB_TCP_STATE_LAST_ACK: Final = 10 + MIB_TCP_STATE_TIME_WAIT: Final = 11 + MIB_TCP_STATE_DELETE_TCB: Final = 12 + PSUTIL_CONN_NONE: Final = 128 + INFINITE: Final[int] + ERROR_ACCESS_DENIED: Final = 5 + ERROR_INVALID_NAME: Final = 123 + ERROR_SERVICE_DOES_NOT_EXIST: Final = 1060 + ERROR_PRIVILEGE_NOT_HELD: Final = 1314 + WINVER: Final[int] + WINDOWS_VISTA: Final = 60 + WINDOWS_7: Final = 61 + WINDOWS_8: Final = 62 + WINDOWS_8_1: Final = 63 + WINDOWS_10: Final = 100 + + class TimeoutAbandoned(Exception): ... + class TimeoutExpired(Exception): ... + + def proc_cmdline(pid: int, use_peb: bool = True) -> list[str]: ... + def proc_cpu_affinity_get(pid: int, /) -> int: ... + def proc_cpu_affinity_set(pid: int, mask: int, /) -> None: ... + def proc_cwd(pid: int, /) -> str: ... + def proc_environ(pid: int, /) -> str: ... + def proc_exe(pid: int, /) -> str: ... + def proc_io_counters(pid: int, /) -> tuple[int, int, int, int, int, int]: ... + def proc_io_priority_get(pid: int, /) -> int: ... + def proc_io_priority_set(pid: int, priority: int, /) -> None: ... + def proc_is_suspended(pid: int, /) -> bool: ... + def proc_kill(pid: int, /) -> None: ... + def proc_memory_info(pid: int, /) -> tuple[int, int, int, int, int, int, int, int, int, int]: ... + def proc_memory_maps(pid: int, /) -> list[tuple[int, str, str, int]]: ... + def proc_memory_uss(pid: int, /) -> int: ... + def proc_num_handles(pid: int, /) -> int: ... + def proc_open_files(pid: int, /) -> list[str]: ... + def proc_priority_get(pid: int, /) -> int: ... + def proc_priority_set(pid: int, priority: int, /) -> None: ... + def proc_suspend_or_resume(pid: int, suspend: bool | None, /) -> None: ... + def proc_threads(pid: int, /) -> list[tuple[int, float, float]]: ... + def proc_times(pid: int, /) -> tuple[float, float, float]: ... + def proc_username(pid: int, /) -> tuple[str, str]: ... + def proc_wait(pid: int, timeout: int, /) -> int | None: ... + def proc_info( + pid: int, / + ) -> tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int]: ... + def uptime() -> float: ... + def cpu_count_cores() -> int | None: ... + def cpu_count_logical() -> int | None: ... + def cpu_freq() -> tuple[int, int]: ... + def cpu_stats() -> tuple[int, int, int, int]: ... + def cpu_times() -> tuple[float, float, float]: ... + def disk_io_counters() -> dict[str, tuple[int, int, int, int, int, int]]: ... + def disk_partitions(all: bool, /) -> list[tuple[str, str, str, str]]: ... + def disk_usage(path: str, /) -> tuple[int, int, int]: ... + def getloadavg() -> tuple[float, float, float]: ... + def getpagesize() -> int: ... + def swap_percent() -> float: ... + def init_loadavg_counter() -> None: ... + def heap_info() -> tuple[int, int, int]: ... + def heap_trim() -> int: ... + def net_connections( + pid: int, af_filter: Sequence[AddressFamily | int | None], type_filter: Sequence[SocketKind | int | None], / + ) -> list[tuple[int, int, int, tuple[str | None, int], tuple[str | None, int], int, int]]: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, None, None]]: ... + def net_if_stats() -> dict[str, tuple[bool, int, int, int]]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def per_cpu_times() -> list[tuple[float, float, float, float, float]]: ... + def pid_exists(pid: int, /) -> bool: ... + def pids() -> list[int]: ... + def ppid_map() -> dict[int, int]: ... + def sensors_battery() -> tuple[int, int, int, int]: ... + def users() -> list[tuple[str, str | None, float]]: ... + def virtual_mem() -> tuple[int, int, int, int]: ... + def winservice_enumerate() -> list[tuple[str, str]]: ... + def winservice_query_config(service_name: str, /) -> tuple[str, str, str, str]: ... + def winservice_query_descr(service_name: str, /) -> str: ... + def winservice_query_status(service_name: str, /) -> tuple[str, int] | str: ... + def winservice_start(service_name: str, /) -> None: ... + def winservice_stop(service_name: str, /) -> None: ... + def QueryDosDevice(device_path: str, /) -> str: ... + def check_pid_range(pid: int, /) -> None: ... + def set_debug(value: bool, /) -> None: ... diff --git a/stubs/psutil/psutil/_pswindows.pyi b/stubs/psutil/psutil/_pswindows.pyi new file mode 100644 index 000000000000..8d9d89e1d783 --- /dev/null +++ b/stubs/psutil/psutil/_pswindows.pyi @@ -0,0 +1,179 @@ +import sys + +if sys.platform == "win32": + import enum + from collections.abc import Callable, Iterable, Iterator + from signal import Signals + from typing import Final, Literal, ParamSpec, TypedDict, TypeVar, overload, type_check_only + + from psutil import _psutil_windows + from psutil._common import ( + ENCODING as ENCODING, + AccessDenied as AccessDenied, + NoSuchProcess as NoSuchProcess, + TimeoutExpired as TimeoutExpired, + conn_tmap as conn_tmap, + conn_to_ntuple as conn_to_ntuple, + debug as debug, + isfile_strict as isfile_strict, + memoize as memoize, + memoize_when_activated as memoize_when_activated, + parse_environ_block as parse_environ_block, + usage_percent as usage_percent, + ) + from psutil._psutil_windows import ( + ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS, + BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS, + HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS, + IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS, + NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS, + REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS, + ) + + from . import _ntuples as ntp + + __extra__all__: Final[list[str]] + CONN_DELETE_TCB: Final = "DELETE_TCB" + ERROR_PARTIAL_COPY: Final = 299 + PYPY: Final[bool] + + class AddressFamily(enum.IntEnum): + AF_LINK = -1 + + AF_LINK: Final = AddressFamily.AF_LINK + TCP_STATUSES: Final[dict[int, str]] + + # These noqas workaround https://github.com/astral-sh/ruff/issues/10874 + class Priority(enum.IntEnum): + ABOVE_NORMAL_PRIORITY_CLASS = _psutil_windows.ABOVE_NORMAL_PRIORITY_CLASS + BELOW_NORMAL_PRIORITY_CLASS = _psutil_windows.BELOW_NORMAL_PRIORITY_CLASS + HIGH_PRIORITY_CLASS = _psutil_windows.HIGH_PRIORITY_CLASS + IDLE_PRIORITY_CLASS = _psutil_windows.IDLE_PRIORITY_CLASS + NORMAL_PRIORITY_CLASS = _psutil_windows.NORMAL_PRIORITY_CLASS + REALTIME_PRIORITY_CLASS = _psutil_windows.REALTIME_PRIORITY_CLASS + + class IOPriority(enum.IntEnum): + IOPRIO_VERYLOW = 0 + IOPRIO_LOW = 1 + IOPRIO_NORMAL = 2 + IOPRIO_HIGH = 3 + + IOPRIO_VERYLOW: Final = IOPriority.IOPRIO_VERYLOW + IOPRIO_LOW: Final = IOPriority.IOPRIO_LOW + IOPRIO_NORMAL: Final = IOPriority.IOPRIO_NORMAL + IOPRIO_HIGH: Final = IOPriority.IOPRIO_HIGH + + pinfo_map: Final[dict[str, int]] + + _P = ParamSpec("_P") + _R = TypeVar("_R") + + def convert_dos_path(s: str) -> str: ... + def getpagesize() -> int: ... + def virtual_memory() -> ntp.svmem: ... + def swap_memory() -> ntp.sswap: ... + + heap_info = _psutil_windows.heap_info + heap_trim = _psutil_windows.heap_trim + disk_io_counters = _psutil_windows.disk_io_counters + + def disk_usage(path: str) -> ntp.sdiskusage: ... + def disk_partitions(all: bool) -> list[ntp.sdiskpart]: ... + def cpu_times() -> ntp.scputimes: ... + def per_cpu_times() -> list[ntp.scputimes]: ... + def cpu_count_logical() -> int | None: ... + def cpu_count_cores() -> int | None: ... + def cpu_stats() -> ntp.scpustats: ... + def cpu_freq() -> list[ntp.scpufreq]: ... + def getloadavg() -> tuple[float, float, float]: ... + + @overload + def net_connections(kind: str, _pid: Literal[-1] = -1) -> list[ntp.sconn]: ... + @overload + def net_connections(kind: str, _pid: int = -1) -> list[ntp.pconn]: ... + + def net_if_stats() -> dict[str, ntp.snicstats]: ... + def net_io_counters() -> dict[str, tuple[int, int, int, int, int, int, int, int]]: ... + def net_if_addrs() -> list[tuple[str, int, str, str | None, None, None]]: ... + def sensors_battery() -> ntp.sbattery | None: ... + def boot_time() -> float: ... + def users() -> list[ntp.suser]: ... + def win_service_iter() -> Iterator[WindowsService]: ... + def win_service_get(name: str) -> WindowsService: ... + + @type_check_only + class _WindowsServiceAttrs(TypedDict): + name: str + display_name: str | None + description: str + binpath: str + username: str + start_type: str + status: str + pid: int | None + + class WindowsService: + def __init__(self, name: str, display_name: str | None) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def name(self) -> str: ... + def display_name(self) -> str | None: ... + def binpath(self) -> str: ... + def username(self) -> str: ... + def start_type(self) -> str: ... + def pid(self) -> int: ... + def status(self) -> str: ... + def description(self) -> str: ... + def as_dict(self) -> _WindowsServiceAttrs: ... + + pids = _psutil_windows.pids + pid_exists = _psutil_windows.pid_exists + ppid_map = _psutil_windows.ppid_map + + def is_permission_err(exc: OSError) -> bool: ... + + @overload + def convert_oserror(exc: PermissionError, pid: int | None = None, name: str | None = None) -> AccessDenied: ... + @overload + def convert_oserror(exc: OSError, pid: int | None = None, name: str | None = None) -> AccessDenied | NoSuchProcess: ... + + def wrap_exceptions(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + def retry_error_partial_copy(fun: Callable[_P, _R]) -> Callable[_P, _R]: ... + + class Process: + __slots__ = ["_cache", "_name", "_ppid", "pid"] + pid: int + def __init__(self, pid: int) -> None: ... + def oneshot_enter(self) -> None: ... + def oneshot_exit(self) -> None: ... + def name(self) -> str: ... + def exe(self) -> str: ... + def cmdline(self) -> list[str]: ... + def environ(self) -> dict[str, str]: ... + def ppid(self) -> int: ... + def memory_info(self) -> ntp.pmem: ... + def memory_full_info(self) -> ntp.pfullmem: ... + def memory_maps(self) -> Iterator[tuple[str, str, str, int]]: ... + def kill(self) -> None: ... + def send_signal(self, sig: Literal[Signals.SIGTERM, Signals.CTRL_C_EVENT, Signals.CTRL_BREAK_EVENT]) -> None: ... + def wait(self, timeout: float | None = None) -> int | None: ... + def username(self) -> str: ... + def create_time(self, fast_only: bool = False) -> float: ... + def num_threads(self) -> int: ... + def threads(self) -> list[ntp.pthread]: ... + def cpu_times(self) -> ntp.pcputimes: ... + def suspend(self) -> None: ... + def resume(self) -> None: ... + def cwd(self) -> str: ... + def open_files(self) -> list[ntp.popenfile]: ... + def net_connections(self, kind: str = "inet") -> list[ntp.pconn]: ... + def nice_get(self) -> Priority: ... + def nice_set(self, value: int) -> None: ... + def ionice_get(self) -> IOPriority: ... + def ionice_set(self, ioclass: int, value: None) -> None: ... + def io_counters(self) -> ntp.pio: ... + def status(self) -> Literal["stopped", "running"]: ... + def cpu_affinity_get(self) -> list[int]: ... + def cpu_affinity_set(self, value: Iterable[int]) -> None: ... + def num_handles(self) -> int: ... + def num_ctx_switches(self) -> ntp.pctxsw: ... diff --git a/stubs/psycopg2/@tests/stubtest_allowlist.txt b/stubs/psycopg2/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..685b7d8f6f55 --- /dev/null +++ b/stubs/psycopg2/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +psycopg2.pool.AbstractConnectionPool.(closeall|getconn|putconn) +psycopg2.(_psycopg|extensions).connection.async # async is a reserved keyword diff --git a/stubs/psycopg2/@tests/test_cases/check_connect.py b/stubs/psycopg2/@tests/test_cases/check_connect.py new file mode 100644 index 000000000000..527ba9d3d88a --- /dev/null +++ b/stubs/psycopg2/@tests/test_cases/check_connect.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +import psycopg2 +from psycopg2.extensions import connection, cursor + + +class MyCursor(cursor): + pass + + +class MyConnection(connection): + pass + + +def custom_connection(dsn: str) -> MyConnection: + return MyConnection(dsn, async_=0) + + +# -> psycopg2.extensions.connection +assert_type(psycopg2.connect(), connection) +assert_type(psycopg2.connect("test-conn"), connection) +assert_type(psycopg2.connect(None), connection) +assert_type(psycopg2.connect("test-conn", connection_factory=None), connection) + +assert_type(psycopg2.connect(cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect("test-conn", cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect(None, cursor_factory=MyCursor), connection) +assert_type(psycopg2.connect("test-conn", connection_factory=None, cursor_factory=MyCursor), connection) + +# -> custom_connection +assert_type(psycopg2.connect(connection_factory=MyConnection), MyConnection) +assert_type(psycopg2.connect("test-conn", connection_factory=MyConnection), MyConnection) +assert_type(psycopg2.connect("test-conn", MyConnection), MyConnection) +assert_type(psycopg2.connect(connection_factory=custom_connection), MyConnection) + +assert_type(psycopg2.connect(connection_factory=MyConnection, cursor_factory=MyCursor), MyConnection) +assert_type(psycopg2.connect("test-conn", connection_factory=MyConnection, cursor_factory=MyCursor), MyConnection) +assert_type(psycopg2.connect(connection_factory=custom_connection, cursor_factory=MyCursor), MyConnection) diff --git a/stubs/psycopg2/@tests/test_cases/check_extensions.py b/stubs/psycopg2/@tests/test_cases/check_extensions.py new file mode 100644 index 000000000000..d8a2fb8d1d8e --- /dev/null +++ b/stubs/psycopg2/@tests/test_cases/check_extensions.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +import io +from typing_extensions import assert_type + +import psycopg2.extensions +import psycopg2.extras +from psycopg2.extensions import make_dsn + +# make_dsn +# -------- + +# (None) -> str +assert_type(make_dsn(), str) +assert_type(make_dsn(None), str) +assert_type(make_dsn(dsn=None), str) + +# (bytes) -> bytes +assert_type(make_dsn(b""), bytes) +assert_type(make_dsn(dsn=b""), bytes) + +# (bytes, **Kwargs) -> str +assert_type(make_dsn(b"", database=""), str) +assert_type(make_dsn(dsn=b"", database=""), str) + +# (str, **OptionalKwargs) -> str +assert_type(make_dsn(""), str) +assert_type(make_dsn(dsn=""), str) +assert_type(make_dsn("", database=None), str) +assert_type(make_dsn(dsn="", database=None), str) + + +# connection.cursor +# ----------------- + +# (name?, None?, ...) -> psycopg2.extensions.cursor +conn = psycopg2.connect("test-conn") +assert_type(conn.cursor(), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur"), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur", None), psycopg2.extensions.cursor) +assert_type(conn.cursor("test-cur", cursor_factory=None), psycopg2.extensions.cursor) + + +# (name?, cursor_factory(), ...) -> custom_cursor +class MyCursor(psycopg2.extensions.cursor): + pass + + +assert_type(conn.cursor("test-cur", cursor_factory=MyCursor), MyCursor) +assert_type(conn.cursor("test-cur", cursor_factory=lambda c, n: MyCursor(c, n)), MyCursor) + +dconn = psycopg2.extras.DictConnection("test-dconn") +assert_type(dconn.cursor(), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur"), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", None), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", cursor_factory=None), psycopg2.extras.DictCursor) +assert_type(dconn.cursor("test-dcur", cursor_factory=MyCursor), MyCursor) + +# file protocols +# -------------- +cur = conn.cursor() +cur.copy_from(io.StringIO(), "table") diff --git a/stubs/psycopg2/METADATA.toml b/stubs/psycopg2/METADATA.toml new file mode 100644 index 000000000000..9c65ea123bb3 --- /dev/null +++ b/stubs/psycopg2/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.9.12" +upstream-repository = "https://github.com/psycopg/psycopg2" +partial-stub = false diff --git a/stubs/psycopg2/psycopg2/__init__.pyi b/stubs/psycopg2/psycopg2/__init__.pyi new file mode 100644 index 000000000000..501a3d0f6ecc --- /dev/null +++ b/stubs/psycopg2/psycopg2/__init__.pyi @@ -0,0 +1,59 @@ +from collections.abc import Callable +from typing import Any, TypeVar, overload + +from psycopg2 import errors as errors, extensions as extensions +from psycopg2._psycopg import ( + BINARY as BINARY, + DATETIME as DATETIME, + NUMBER as NUMBER, + ROWID as ROWID, + STRING as STRING, + Binary as Binary, + DatabaseError as DatabaseError, + DataError as DataError, + Date as Date, + DateFromTicks as DateFromTicks, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + Time as Time, + TimeFromTicks as TimeFromTicks, + Timestamp as Timestamp, + TimestampFromTicks as TimestampFromTicks, + Warning as Warning, + __libpq_version__ as __libpq_version__, + apilevel as apilevel, + connection, + cursor, + paramstyle as paramstyle, + threadsafety as threadsafety, +) + +_T_conn = TypeVar("_T_conn", bound=connection) + +@overload +def connect( + dsn: str | None, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, +) -> _T_conn: ... +@overload +def connect( + dsn: str | None = None, + *, + connection_factory: Callable[..., _T_conn], + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, +) -> _T_conn: ... +@overload +def connect( + dsn: str | None = None, + connection_factory: Callable[..., connection] | None = None, + cursor_factory: Callable[[connection, str | bytes | None], cursor] | None = None, + **kwargs: Any, +) -> connection: ... diff --git a/stubs/psycopg2/psycopg2/_ipaddress.pyi b/stubs/psycopg2/psycopg2/_ipaddress.pyi new file mode 100644 index 000000000000..60085a3beb22 --- /dev/null +++ b/stubs/psycopg2/psycopg2/_ipaddress.pyi @@ -0,0 +1,9 @@ +import ipaddress as ipaddress +from _typeshed import Unused + +from psycopg2._psycopg import QuotedString, connection, cursor + +def register_ipaddress(conn_or_curs: connection | cursor | None = None) -> None: ... +def cast_interface(s: str, cur: Unused = None) -> ipaddress.IPv4Interface | ipaddress.IPv6Interface | None: ... +def cast_network(s: str, cur: Unused = None) -> ipaddress.IPv4Network | ipaddress.IPv6Network | None: ... +def adapt_ipaddress(obj: object) -> QuotedString: ... diff --git a/stubs/psycopg2/psycopg2/_json.pyi b/stubs/psycopg2/psycopg2/_json.pyi new file mode 100644 index 000000000000..40ce54d4aef8 --- /dev/null +++ b/stubs/psycopg2/psycopg2/_json.pyi @@ -0,0 +1,33 @@ +from collections.abc import Callable +from typing import Any +from typing_extensions import Self + +from psycopg2._psycopg import _type, connection, cursor + +JSON_OID: int +JSONARRAY_OID: int +JSONB_OID: int +JSONBARRAY_OID: int + +class Json: + adapted: Any + def __init__(self, adapted: Any, dumps: Callable[..., str] | None = None) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def dumps(self, obj: Any) -> str: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... + +def register_json( + conn_or_curs: connection | cursor | None = None, + globally: bool = False, + loads: Callable[..., Any] | None = None, + oid: int | None = None, + array_oid: int | None = None, + name: str = "json", +) -> tuple[_type, _type | None]: ... +def register_default_json( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... +def register_default_jsonb( + conn_or_curs: connection | cursor | None = None, globally: bool = False, loads: Callable[..., Any] | None = None +) -> tuple[_type, _type | None]: ... diff --git a/stubs/psycopg2/psycopg2/_psycopg.pyi b/stubs/psycopg2/psycopg2/_psycopg.pyi new file mode 100644 index 000000000000..91e51a53a012 --- /dev/null +++ b/stubs/psycopg2/psycopg2/_psycopg.pyi @@ -0,0 +1,640 @@ +import datetime as dt +from _typeshed import ConvertibleToInt, Incomplete, SupportsRead, SupportsReadline, SupportsWrite, Unused +from collections.abc import Callable, Iterable, Mapping, Sequence +from types import TracebackType +from typing import Any, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base + +from psycopg2.extras import ReplicationCursor as extras_ReplicationCursor +from psycopg2.sql import Composable + +_Vars: TypeAlias = Sequence[Any] | Mapping[str, Any] | None + +@type_check_only +class _type: + # The class doesn't exist at runtime but following attributes have type "psycopg2._psycopg.type" + name: str + values: tuple[int, ...] + def __call__(self, value: str | bytes | None, cur: cursor | None, /) -> Any: ... + +BINARY: _type +BINARYARRAY: _type +BOOLEAN: _type +BOOLEANARRAY: _type +BYTES: _type +BYTESARRAY: _type +CIDRARRAY: _type +DATE: _type +DATEARRAY: _type +DATETIME: _type +DATETIMEARRAY: _type +DATETIMETZ: _type +DATETIMETZARRAY: _type +DECIMAL: _type +DECIMALARRAY: _type +FLOAT: _type +FLOATARRAY: _type +INETARRAY: _type +INTEGER: _type +INTEGERARRAY: _type +INTERVAL: _type +INTERVALARRAY: _type +LONGINTEGER: _type +LONGINTEGERARRAY: _type +MACADDRARRAY: _type +NUMBER: _type +PYDATE: _type +PYDATEARRAY: _type +PYDATETIME: _type +PYDATETIMEARRAY: _type +PYDATETIMETZ: _type +PYDATETIMETZARRAY: _type +PYINTERVAL: _type +PYINTERVALARRAY: _type +PYTIME: _type +PYTIMEARRAY: _type +ROWID: _type +ROWIDARRAY: _type +STRING: _type +STRINGARRAY: _type +TIME: _type +TIMEARRAY: _type +UNICODE: _type +UNICODEARRAY: _type +UNKNOWN: _type + +REPLICATION_LOGICAL: int +REPLICATION_PHYSICAL: int + +@type_check_only +class _ISQLQuoteProto(Protocol): + # Objects conforming this protocol should implement a getquoted() and optionally a prepare() method. + # The real ISQLQuote class is implemented below with more stuff. + def getquoted(self) -> bytes: ... + # def prepare(self, __conn: connection) -> None: ... # optional + +adapters: dict[tuple[type[Any], type[ISQLQuote]], Callable[[Any], _ISQLQuoteProto]] +apilevel: str +binary_types: dict[Any, Any] +encodings: dict[str, str] +paramstyle: str +sqlstate_errors: dict[str, type[Error]] +string_types: dict[int, _type] +threadsafety: int + +__libpq_version__: int + +_T_co = TypeVar("_T_co", covariant=True) + +@type_check_only +class _SupportsReadAndReadline(SupportsRead[_T_co], SupportsReadline[_T_co], Protocol[_T_co]): ... + +@disjoint_base +class cursor: + arraysize: int + binary_types: Incomplete | None + connection: _Connection + itersize: int + row_factory: Incomplete | None + scrollable: bool | None + string_types: Incomplete | None + tzinfo_factory: Callable[..., dt.tzinfo] + withhold: bool + def __init__(self, conn: _Connection, name: str | bytes | None = None) -> None: ... + @property + def closed(self) -> bool: ... + @property + def lastrowid(self) -> int: ... + @property + def name(self) -> Incomplete | None: ... + @property + def query(self) -> bytes | None: ... + @property + def description(self) -> tuple[Column, ...] | None: ... + @property + def rowcount(self) -> int: ... + @property + def rownumber(self) -> int: ... + @property + def typecaster(self) -> Incomplete | None: ... + @property + def statusmessage(self) -> str | None: ... + @property + def pgresult_ptr(self) -> int | None: ... + def callproc(self, procname: str | bytes, parameters: _Vars = None, /) -> None: ... + def cast(self, oid: int, s: str | bytes, /) -> Any: ... + def close(self) -> None: ... + def copy_expert( + self, + sql: str | bytes | Composable, + file: _SupportsReadAndReadline[bytes] | SupportsWrite[bytes] | TextIO, + size: int = 8192, + ) -> None: ... + def copy_from( + self, + file: _SupportsReadAndReadline[bytes] | _SupportsReadAndReadline[str], + table: str, + sep: str = "\t", + null: str = "\\N", + size: int = 8192, + columns: Iterable[str] | None = None, + ) -> None: ... + def copy_to( + self, + file: SupportsWrite[bytes] | TextIO, + table: str, + sep: str = "\t", + null: str = "\\N", + columns: Iterable[str] | None = None, + ) -> None: ... + def execute(self, query: str | bytes | Composable, vars: _Vars = None) -> None: ... + def executemany(self, query: str | bytes | Composable, vars_list: Iterable[_Vars]) -> None: ... + def fetchall(self) -> list[tuple[Any, ...]]: ... + def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]: ... + def fetchone(self) -> tuple[Any, ...] | None: ... + def mogrify(self, query: str | bytes | Composable, vars: _Vars | None = None) -> bytes: ... + def nextset(self) -> Never: ... # not supported + def scroll(self, value: int, mode: Literal["absolute", "relative"] = "relative") -> None: ... + def setinputsizes(self, sizes: Unused) -> None: ... + def setoutputsize(self, size: int, column: int = ..., /) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> tuple[Any, ...]: ... + +_Cursor: TypeAlias = cursor + +@disjoint_base +class AsIs: + def __init__(self, obj: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Binary: + def __init__(self, str: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Boolean: + def __init__(self, obj: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Column: + display_size: Any + internal_size: Any + name: Any + null_ok: Any + precision: Any + scale: Any + table_column: Any + table_oid: Any + type_code: Any + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... + def __getstate__(self): ... + def __gt__(self, other, /): ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + def __setstate__(self, state, /): ... + +@disjoint_base +class ConnectionInfo: + # Note: the following properties can be None if their corresponding libpq function + # returns NULL. They're not annotated as such, because this is very unlikely in + # practice---the psycopg2 docs [1] don't even mention this as a possibility! + # + # - db_name + # - user + # - password + # - host + # - port + # - options + # + # (To prove this, one needs to inspect the psycopg2 source code [2], plus the + # documentation [3] and source code [4] of the corresponding libpq calls.) + # + # [1]: https://www.psycopg.org/docs/extensions.html#psycopg2.extensions.ConnectionInfo + # [2]: https://github.com/psycopg/psycopg2/blob/1d3a89a0bba621dc1cc9b32db6d241bd2da85ad1/psycopg/conninfo_type.c#L52 and below + # [3]: https://www.postgresql.org/docs/current/libpq-status.html + # [4]: https://github.com/postgres/postgres/blob/b39838889e76274b107935fa8e8951baf0e8b31b/src/interfaces/libpq/fe-connect.c#L6754 and below # noqa: E501 + @property + def backend_pid(self) -> int: ... + @property + def dbname(self) -> str: ... + @property + def dsn_parameters(self) -> dict[str, str]: ... + @property + def error_message(self) -> str | None: ... + @property + def host(self) -> str: ... + @property + def needs_password(self) -> bool: ... + @property + def options(self) -> str: ... + @property + def password(self) -> str: ... + @property + def port(self) -> int: ... + @property + def protocol_version(self) -> int: ... + @property + def server_version(self) -> int: ... + @property + def socket(self) -> int: ... + @property + def ssl_attribute_names(self) -> list[str]: ... + @property + def ssl_in_use(self) -> bool: ... + @property + def status(self) -> int: ... + @property + def transaction_status(self) -> int: ... + @property + def used_password(self) -> bool: ... + @property + def user(self) -> str: ... + def __init__(self, *args, **kwargs) -> None: ... + def parameter_status(self, name: str) -> str | None: ... + def ssl_attribute(self, name: str) -> str | None: ... + +@disjoint_base +class Error(Exception): + cursor: _Cursor | None + diag: Diagnostics + pgcode: str | None + pgerror: str | None + def __init__(self, *args, **kwargs) -> None: ... + def __reduce__(self): ... + def __setstate__(self, state, /): ... + +class DatabaseError(Error): ... +class DataError(DatabaseError): ... +class IntegrityError(DatabaseError): ... +class InternalError(DatabaseError): ... +class NotSupportedError(DatabaseError): ... +class OperationalError(DatabaseError): ... +class ProgrammingError(DatabaseError): ... +class QueryCanceledError(OperationalError): ... +class TransactionRollbackError(OperationalError): ... +class InterfaceError(Error): ... +class Warning(Exception): ... + +@disjoint_base +class ISQLQuote: + _wrapped: Any + def __init__(self, wrapped: object, /, **kwargs) -> None: ... + def getbinary(self): ... + def getbuffer(self): ... + def getquoted(self) -> bytes: ... + +@disjoint_base +class Decimal: + def __init__(self, value: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Diagnostics: + column_name: str | None + constraint_name: str | None + context: str | None + datatype_name: str | None + internal_position: str | None + internal_query: str | None + message_detail: str | None + message_hint: str | None + message_primary: str | None + schema_name: str | None + severity: str | None + severity_nonlocalized: str | None + source_file: str | None + source_function: str | None + source_line: str | None + sqlstate: str | None + statement_position: str | None + table_name: str | None + def __init__(self, err: Error, /) -> None: ... + +@disjoint_base +class Float: + def __init__(self, value: float, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> float: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Int: + def __init__(self, value: ConvertibleToInt, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class List: + def __init__(self, objs: list[object], /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> list[Any]: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class Notify: + channel: Any + payload: Any + pid: Any + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other, /): ... + def __ge__(self, other, /): ... + def __getitem__(self, index, /): ... + def __gt__(self, other, /): ... + def __hash__(self) -> int: ... + def __le__(self, other, /): ... + def __len__(self) -> int: ... + def __lt__(self, other, /): ... + def __ne__(self, other, /): ... + +@disjoint_base +class QuotedString: + encoding: str + def __init__(self, str: object, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def buffer(self) -> Any: ... + def getquoted(self) -> bytes: ... + def prepare(self, conn: connection, /) -> None: ... + def __conform__(self, proto, /) -> Self | None: ... + +@disjoint_base +class ReplicationCursor(cursor): + feedback_timestamp: Any + io_timestamp: Any + wal_end: Any + def __init__(self, *args, **kwargs) -> None: ... + def consume_stream(self, consumer, keepalive_interval=...): ... + def read_message(self) -> Incomplete | None: ... + def send_feedback(self, write_lsn=..., flush_lsn=..., apply_lsn=..., reply=..., force=...): ... + def start_replication_expert(self, command, decode=..., status_interval=...): ... + +@disjoint_base +class ReplicationMessage: + cursor: Any + data_size: Any + data_start: Any + payload: Any + send_time: Any + wal_end: Any + def __init__(self, *args, **kwargs) -> None: ... + +@disjoint_base +class Xid: + bqual: Any + database: Any + format_id: Any + gtrid: Any + owner: Any + prepared: Any + def __init__(self, *args, **kwargs) -> None: ... + def from_string(self, *args, **kwargs): ... + def __getitem__(self, index, /): ... + def __len__(self) -> int: ... + +_T_cur = TypeVar("_T_cur", bound=cursor) +_Lobject: TypeAlias = lobject + +@disjoint_base +class connection: + DataError: type[DataError] + DatabaseError: type[DatabaseError] + Error: type[Error] + IntegrityError: type[IntegrityError] + InterfaceError: type[InterfaceError] + InternalError: type[InternalError] + NotSupportedError: type[NotSupportedError] + OperationalError: type[OperationalError] + ProgrammingError: type[ProgrammingError] + Warning: type[Warning] + @property + def async_(self) -> int: ... + autocommit: bool + @property + def binary_types(self) -> dict[Incomplete, Incomplete]: ... + @property + def closed(self) -> int: ... + cursor_factory: Callable[[connection, str | bytes | None], _Cursor] + @property + def dsn(self) -> str: ... + @property + def encoding(self) -> str: ... + @property + def info(self) -> ConnectionInfo: ... + + @property + def isolation_level(self) -> int | None: ... + @isolation_level.setter + def isolation_level(self, value: str | bytes | int | None, /) -> None: ... + + notices: list[str] + notifies: list[Notify] + @property + def pgconn_ptr(self) -> int | None: ... + @property + def protocol_version(self) -> int: ... + + @property + def deferrable(self) -> bool | None: ... + @deferrable.setter + def deferrable(self, value: Literal["default"] | bool | None, /) -> None: ... + + @property + def readonly(self) -> bool | None: ... + @readonly.setter + def readonly(self, value: Literal["default"] | bool | None, /) -> None: ... + + @property + def server_version(self) -> int: ... + @property + def status(self) -> int: ... + @property + def string_types(self) -> dict[Incomplete, Incomplete]: ... + # Really it's dsn: str, async: int = 0, async_: int = 0, but + # that would be a syntax error. + def __init__(self, dsn: str, *, async_: int = 0) -> None: ... + def cancel(self) -> None: ... + def close(self) -> None: ... + def commit(self) -> None: ... + + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> _Cursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + + def fileno(self) -> int: ... + def get_backend_pid(self) -> int: ... + def get_dsn_parameters(self) -> dict[str, str]: ... + def get_native_connection(self): ... + def get_parameter_status(self, parameter: str) -> str | None: ... + def get_transaction_status(self) -> int: ... + def isexecuting(self) -> bool: ... + def lobject( + self, + oid: int = ..., + mode: str | None = ..., + new_oid: int = ..., + new_file: str | None = ..., + lobject_factory: type[_Lobject] = ..., + ) -> _Lobject: ... + def poll(self) -> int: ... + def reset(self) -> None: ... + def rollback(self) -> None: ... + def set_client_encoding(self, encoding: str) -> None: ... + def set_isolation_level(self, level: int | None) -> None: ... + def set_session( + self, + isolation_level: str | bytes | int | None = ..., + readonly: bool | Literal["default", b"default"] | None = ..., + deferrable: bool | Literal["default", b"default"] | None = ..., + autocommit: bool = ..., + ) -> None: ... + def tpc_begin(self, xid: str | bytes | Xid) -> None: ... + def tpc_commit(self, xid: str | bytes | Xid = ..., /) -> None: ... + def tpc_prepare(self) -> None: ... + def tpc_recover(self) -> list[Xid]: ... + def tpc_rollback(self, xid: str | bytes | Xid = ..., /) -> None: ... + def xid(self, format_id, gtrid, bqual) -> Xid: ... + def __enter__(self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, name: BaseException | None, tb: TracebackType | None, /) -> None: ... + +_Connection: TypeAlias = connection + +@disjoint_base +class ReplicationConnection(connection): + autocommit: Any + isolation_level: Any + replication_type: Any + reset: Any + set_isolation_level: Any + set_session: Any + def __init__(self, *args, **kwargs) -> None: ... + + # https://github.com/python/typeshed/issues/11282 + # The return type should be exactly extras.ReplicationCursor (not _psycopg.ReplicationCursor) + # See the C code: replicationConnection_init(), psyco_conn_cursor() + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> extras_ReplicationCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + +@disjoint_base +class lobject: + closed: Any + mode: Any + oid: Any + def __init__(self, *args, **kwargs) -> None: ... + def close(self): ... + def export(self, filename): ... + def read(self, size=...): ... + def seek(self, offset, whence=...): ... + def tell(self): ... + def truncate(self, len=...): ... + def unlink(self): ... + def write(self, str): ... + +@type_check_only +class _datetime: + # The class doesn't exist at runtime but functions below return "psycopg2._psycopg.datetime" objects + # XXX: This and other classes that implement the `ISQLQuote` protocol could be made generic + # in the return type of their `adapted` property if someone asks for it. + def __init__(self, obj: object, type: int = -1, /, **kwargs: Unused) -> None: ... + @property + def adapted(self) -> Any: ... + @property + def type(self) -> int: ... + def getquoted(self) -> bytes: ... + def __conform__(self, proto, /) -> Self | None: ... + +def Date(year: int, month: int, day: int, /) -> _datetime: ... +def DateFromPy(date: dt.date, /) -> _datetime: ... +def DateFromTicks(ticks: float, /) -> _datetime: ... +def IntervalFromPy(interval: dt.timedelta, /) -> _datetime: ... +def Time(hour: int, minutes: int, seconds: float, tzinfo: dt.tzinfo | None = None, /) -> _datetime: ... +def TimeFromPy(time: dt.time, /) -> _datetime: ... +def TimeFromTicks(ticks: float, /) -> _datetime: ... +def Timestamp( + year: int, month: int, day: int, hour: int = 0, minutes: int = 0, seconds: float = 0, tzinfo: dt.tzinfo | None = None, / +) -> _datetime: ... +def TimestampFromPy(datetime: dt.datetime, /) -> _datetime: ... +def TimestampFromTicks(ticks: float, /) -> _datetime: ... +def _connect(*args, **kwargs): ... +def adapt(obj: object, protocol=..., alternate=..., /) -> Any: ... +def encrypt_password( + password: str | bytes, user: str | bytes, scope: connection | cursor | None = None, algorithm: str | None = None +) -> str: ... +def get_wait_callback() -> Incomplete | None: ... +def libpq_version() -> int: ... +def new_array_type(values: tuple[int, ...], name: str, baseobj: _type) -> _type: ... +def new_type( + values: tuple[int, ...], name: str, castobj: Callable[[str | bytes | None, cursor], Any] | None = None, baseobj=None +) -> _type: ... +def parse_dsn(dsn: str | bytes) -> dict[str, Any]: ... +def quote_ident(ident: str | bytes, scope) -> str: ... +def register_type(obj: _type, conn_or_curs: connection | cursor | None = None, /) -> None: ... +def set_wait_callback(none: Callable[..., Incomplete] | None, /) -> None: ... diff --git a/stubs/psycopg2/psycopg2/_range.pyi b/stubs/psycopg2/psycopg2/_range.pyi new file mode 100644 index 000000000000..254aadd5516e --- /dev/null +++ b/stubs/psycopg2/psycopg2/_range.pyi @@ -0,0 +1,86 @@ +import datetime as dt +from _typeshed import SupportsAllComparisons +from typing import Any, Generic, TypeVar, overload +from typing_extensions import Self + +from psycopg2._psycopg import _type, connection, cursor + +_T_co = TypeVar("_T_co", covariant=True) + +class Range(Generic[_T_co]): + __slots__ = ("_lower", "_upper", "_bounds") + def __init__( + self, lower: _T_co | None = None, upper: _T_co | None = None, bounds: str = "[)", empty: bool = False + ) -> None: ... + @property + def lower(self) -> _T_co | None: ... + @property + def upper(self) -> _T_co | None: ... + @property + def isempty(self) -> bool: ... + @property + def lower_inf(self) -> bool: ... + @property + def upper_inf(self) -> bool: ... + @property + def lower_inc(self) -> bool: ... + @property + def upper_inc(self) -> bool: ... + def __contains__(self, x: SupportsAllComparisons) -> bool: ... + def __bool__(self) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def __lt__(self, other: Range[_T_co]) -> bool: ... + def __le__(self, other: Range[_T_co]) -> bool: ... + def __gt__(self, other: Range[_T_co]) -> bool: ... + def __ge__(self, other: Range[_T_co]) -> bool: ... + +def register_range( + pgrange: str, pyrange: str | type[Range[Any]], conn_or_curs: connection | cursor, globally: bool = False +) -> RangeCaster: ... + +class RangeAdapter: + name: str | None = None + adapted: Range[Any] + def __init__(self, adapted: Range[Any]) -> None: ... + def __conform__(self, proto) -> Self | None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... + +class RangeCaster: + adapter: type[RangeAdapter] + range: type[Range[Any]] + subtype_oid: int + typecaster: _type + array_typecaster: _type | None + def __init__( + self, + pgrange: str | type[RangeAdapter], + pyrange: str | type[Range[Any]], + oid: int, + subtype_oid: int, + array_oid: int | None = None, + ) -> None: ... + + @overload + def parse(self, s: None, cur: cursor | None = None) -> None: ... + @overload + def parse(self, s: str, cur: cursor | None = None) -> Range[Any]: ... + @overload + def parse(self, s: str | None, cur: cursor | None = None) -> Range[Any] | None: ... + +class NumericRange(Range[float]): ... +class DateRange(Range[dt.date]): ... +class DateTimeRange(Range[dt.datetime]): ... +class DateTimeTZRange(Range[dt.datetime]): ... + +class NumberRangeAdapter(RangeAdapter): + def getquoted(self) -> bytes: ... + +int4range_caster: RangeCaster +int8range_caster: RangeCaster +numrange_caster: RangeCaster +daterange_caster: RangeCaster +tsrange_caster: RangeCaster +tstzrange_caster: RangeCaster diff --git a/stubs/psycopg2/psycopg2/errorcodes.pyi b/stubs/psycopg2/psycopg2/errorcodes.pyi new file mode 100644 index 000000000000..aecb7fc53f0b --- /dev/null +++ b/stubs/psycopg2/psycopg2/errorcodes.pyi @@ -0,0 +1,312 @@ +from typing import Final + +def lookup(code: str, _cache: dict[str, str] = {}) -> str: ... + +CLASS_SUCCESSFUL_COMPLETION: Final[str] +CLASS_WARNING: Final[str] +CLASS_NO_DATA: Final[str] +CLASS_SQL_STATEMENT_NOT_YET_COMPLETE: Final[str] +CLASS_CONNECTION_EXCEPTION: Final[str] +CLASS_TRIGGERED_ACTION_EXCEPTION: Final[str] +CLASS_FEATURE_NOT_SUPPORTED: Final[str] +CLASS_INVALID_TRANSACTION_INITIATION: Final[str] +CLASS_LOCATOR_EXCEPTION: Final[str] +CLASS_INVALID_GRANTOR: Final[str] +CLASS_INVALID_ROLE_SPECIFICATION: Final[str] +CLASS_DIAGNOSTICS_EXCEPTION: Final[str] +CLASS_XQUERY_ERROR: Final[str] +CLASS_CASE_NOT_FOUND: Final[str] +CLASS_CARDINALITY_VIOLATION: Final[str] +CLASS_DATA_EXCEPTION: Final[str] +CLASS_INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +CLASS_INVALID_CURSOR_STATE: Final[str] +CLASS_INVALID_TRANSACTION_STATE: Final[str] +CLASS_INVALID_SQL_STATEMENT_NAME: Final[str] +CLASS_TRIGGERED_DATA_CHANGE_VIOLATION: Final[str] +CLASS_INVALID_AUTHORIZATION_SPECIFICATION: Final[str] +CLASS_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: Final[str] +CLASS_INVALID_TRANSACTION_TERMINATION: Final[str] +CLASS_SQL_ROUTINE_EXCEPTION: Final[str] +CLASS_INVALID_CURSOR_NAME: Final[str] +CLASS_EXTERNAL_ROUTINE_EXCEPTION: Final[str] +CLASS_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: Final[str] +CLASS_SAVEPOINT_EXCEPTION: Final[str] +CLASS_INVALID_CATALOG_NAME: Final[str] +CLASS_INVALID_SCHEMA_NAME: Final[str] +CLASS_TRANSACTION_ROLLBACK: Final[str] +CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: Final[str] +CLASS_WITH_CHECK_OPTION_VIOLATION: Final[str] +CLASS_INSUFFICIENT_RESOURCES: Final[str] +CLASS_PROGRAM_LIMIT_EXCEEDED: Final[str] +CLASS_OBJECT_NOT_IN_PREREQUISITE_STATE: Final[str] +CLASS_OPERATOR_INTERVENTION: Final[str] +CLASS_SYSTEM_ERROR: Final[str] +CLASS_SNAPSHOT_FAILURE: Final[str] +CLASS_CONFIGURATION_FILE_ERROR: Final[str] +CLASS_FOREIGN_DATA_WRAPPER_ERROR: Final[str] +CLASS_PL_PGSQL_ERROR: Final[str] +CLASS_INTERNAL_ERROR: Final[str] +SUCCESSFUL_COMPLETION: Final[str] +WARNING: Final[str] +NULL_VALUE_ELIMINATED_IN_SET_FUNCTION: Final[str] +STRING_DATA_RIGHT_TRUNCATION_: Final[str] +PRIVILEGE_NOT_REVOKED: Final[str] +PRIVILEGE_NOT_GRANTED: Final[str] +IMPLICIT_ZERO_BIT_PADDING: Final[str] +DYNAMIC_RESULT_SETS_RETURNED: Final[str] +DEPRECATED_FEATURE: Final[str] +NO_DATA: Final[str] +NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED: Final[str] +SQL_STATEMENT_NOT_YET_COMPLETE: Final[str] +CONNECTION_EXCEPTION: Final[str] +SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION: Final[str] +CONNECTION_DOES_NOT_EXIST: Final[str] +SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION: Final[str] +CONNECTION_FAILURE: Final[str] +TRANSACTION_RESOLUTION_UNKNOWN: Final[str] +PROTOCOL_VIOLATION: Final[str] +TRIGGERED_ACTION_EXCEPTION: Final[str] +FEATURE_NOT_SUPPORTED: Final[str] +INVALID_TRANSACTION_INITIATION: Final[str] +LOCATOR_EXCEPTION: Final[str] +INVALID_LOCATOR_SPECIFICATION: Final[str] +INVALID_GRANTOR: Final[str] +INVALID_GRANT_OPERATION: Final[str] +INVALID_ROLE_SPECIFICATION: Final[str] +DIAGNOSTICS_EXCEPTION: Final[str] +STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER: Final[str] +INVALID_ARGUMENT_FOR_XQUERY: Final[str] +CASE_NOT_FOUND: Final[str] +CARDINALITY_VIOLATION: Final[str] +DATA_EXCEPTION: Final[str] +STRING_DATA_RIGHT_TRUNCATION: Final[str] +NULL_VALUE_NO_INDICATOR_PARAMETER: Final[str] +NUMERIC_VALUE_OUT_OF_RANGE: Final[str] +NULL_VALUE_NOT_ALLOWED_: Final[str] +ERROR_IN_ASSIGNMENT: Final[str] +INVALID_DATETIME_FORMAT: Final[str] +DATETIME_FIELD_OVERFLOW: Final[str] +INVALID_TIME_ZONE_DISPLACEMENT_VALUE: Final[str] +ESCAPE_CHARACTER_CONFLICT: Final[str] +INVALID_USE_OF_ESCAPE_CHARACTER: Final[str] +INVALID_ESCAPE_OCTET: Final[str] +ZERO_LENGTH_CHARACTER_STRING: Final[str] +MOST_SPECIFIC_TYPE_MISMATCH: Final[str] +SEQUENCE_GENERATOR_LIMIT_EXCEEDED: Final[str] +NOT_AN_XML_DOCUMENT: Final[str] +INVALID_XML_DOCUMENT: Final[str] +INVALID_XML_CONTENT: Final[str] +INVALID_XML_COMMENT: Final[str] +INVALID_XML_PROCESSING_INSTRUCTION: Final[str] +INVALID_INDICATOR_PARAMETER_VALUE: Final[str] +SUBSTRING_ERROR: Final[str] +DIVISION_BY_ZERO: Final[str] +INVALID_PRECEDING_OR_FOLLOWING_SIZE: Final[str] +INVALID_ARGUMENT_FOR_NTILE_FUNCTION: Final[str] +INTERVAL_FIELD_OVERFLOW: Final[str] +INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION: Final[str] +INVALID_CHARACTER_VALUE_FOR_CAST: Final[str] +INVALID_ESCAPE_CHARACTER: Final[str] +INVALID_REGULAR_EXPRESSION: Final[str] +INVALID_ARGUMENT_FOR_LOGARITHM: Final[str] +INVALID_ARGUMENT_FOR_POWER_FUNCTION: Final[str] +INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION: Final[str] +INVALID_ROW_COUNT_IN_LIMIT_CLAUSE: Final[str] +INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE: Final[str] +INVALID_LIMIT_VALUE: Final[str] +CHARACTER_NOT_IN_REPERTOIRE: Final[str] +INDICATOR_OVERFLOW: Final[str] +INVALID_PARAMETER_VALUE: Final[str] +UNTERMINATED_C_STRING: Final[str] +INVALID_ESCAPE_SEQUENCE: Final[str] +STRING_DATA_LENGTH_MISMATCH: Final[str] +TRIM_ERROR: Final[str] +ARRAY_SUBSCRIPT_ERROR: Final[str] +INVALID_TABLESAMPLE_REPEAT: Final[str] +INVALID_TABLESAMPLE_ARGUMENT: Final[str] +DUPLICATE_JSON_OBJECT_KEY_VALUE: Final[str] +INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION: Final[str] +INVALID_JSON_TEXT: Final[str] +INVALID_SQL_JSON_SUBSCRIPT: Final[str] +MORE_THAN_ONE_SQL_JSON_ITEM: Final[str] +NO_SQL_JSON_ITEM: Final[str] +NON_NUMERIC_SQL_JSON_ITEM: Final[str] +NON_UNIQUE_KEYS_IN_A_JSON_OBJECT: Final[str] +SINGLETON_SQL_JSON_ITEM_REQUIRED: Final[str] +SQL_JSON_ARRAY_NOT_FOUND: Final[str] +SQL_JSON_MEMBER_NOT_FOUND: Final[str] +SQL_JSON_NUMBER_NOT_FOUND: Final[str] +SQL_JSON_OBJECT_NOT_FOUND: Final[str] +TOO_MANY_JSON_ARRAY_ELEMENTS: Final[str] +TOO_MANY_JSON_OBJECT_MEMBERS: Final[str] +SQL_JSON_SCALAR_REQUIRED: Final[str] +FLOATING_POINT_EXCEPTION: Final[str] +INVALID_TEXT_REPRESENTATION: Final[str] +INVALID_BINARY_REPRESENTATION: Final[str] +BAD_COPY_FILE_FORMAT: Final[str] +UNTRANSLATABLE_CHARACTER: Final[str] +NONSTANDARD_USE_OF_ESCAPE_CHARACTER: Final[str] +INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +RESTRICT_VIOLATION: Final[str] +NOT_NULL_VIOLATION: Final[str] +FOREIGN_KEY_VIOLATION: Final[str] +UNIQUE_VIOLATION: Final[str] +CHECK_VIOLATION: Final[str] +EXCLUSION_VIOLATION: Final[str] +INVALID_CURSOR_STATE: Final[str] +INVALID_TRANSACTION_STATE: Final[str] +ACTIVE_SQL_TRANSACTION: Final[str] +BRANCH_TRANSACTION_ALREADY_ACTIVE: Final[str] +INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION: Final[str] +INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION: Final[str] +NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION: Final[str] +READ_ONLY_SQL_TRANSACTION: Final[str] +SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED: Final[str] +HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL: Final[str] +NO_ACTIVE_SQL_TRANSACTION: Final[str] +IN_FAILED_SQL_TRANSACTION: Final[str] +IDLE_IN_TRANSACTION_SESSION_TIMEOUT: Final[str] +INVALID_SQL_STATEMENT_NAME: Final[str] +TRIGGERED_DATA_CHANGE_VIOLATION: Final[str] +INVALID_AUTHORIZATION_SPECIFICATION: Final[str] +INVALID_PASSWORD: Final[str] +DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST: Final[str] +DEPENDENT_OBJECTS_STILL_EXIST: Final[str] +INVALID_TRANSACTION_TERMINATION: Final[str] +SQL_ROUTINE_EXCEPTION: Final[str] +MODIFYING_SQL_DATA_NOT_PERMITTED_: Final[str] +PROHIBITED_SQL_STATEMENT_ATTEMPTED_: Final[str] +READING_SQL_DATA_NOT_PERMITTED_: Final[str] +FUNCTION_EXECUTED_NO_RETURN_STATEMENT: Final[str] +INVALID_CURSOR_NAME: Final[str] +EXTERNAL_ROUTINE_EXCEPTION: Final[str] +CONTAINING_SQL_NOT_PERMITTED: Final[str] +MODIFYING_SQL_DATA_NOT_PERMITTED: Final[str] +PROHIBITED_SQL_STATEMENT_ATTEMPTED: Final[str] +READING_SQL_DATA_NOT_PERMITTED: Final[str] +EXTERNAL_ROUTINE_INVOCATION_EXCEPTION: Final[str] +INVALID_SQLSTATE_RETURNED: Final[str] +NULL_VALUE_NOT_ALLOWED: Final[str] +TRIGGER_PROTOCOL_VIOLATED: Final[str] +SRF_PROTOCOL_VIOLATED: Final[str] +EVENT_TRIGGER_PROTOCOL_VIOLATED: Final[str] +SAVEPOINT_EXCEPTION: Final[str] +INVALID_SAVEPOINT_SPECIFICATION: Final[str] +INVALID_CATALOG_NAME: Final[str] +INVALID_SCHEMA_NAME: Final[str] +TRANSACTION_ROLLBACK: Final[str] +SERIALIZATION_FAILURE: Final[str] +TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION: Final[str] +STATEMENT_COMPLETION_UNKNOWN: Final[str] +DEADLOCK_DETECTED: Final[str] +SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION: Final[str] +INSUFFICIENT_PRIVILEGE: Final[str] +SYNTAX_ERROR: Final[str] +INVALID_NAME: Final[str] +INVALID_COLUMN_DEFINITION: Final[str] +NAME_TOO_LONG: Final[str] +DUPLICATE_COLUMN: Final[str] +AMBIGUOUS_COLUMN: Final[str] +UNDEFINED_COLUMN: Final[str] +UNDEFINED_OBJECT: Final[str] +DUPLICATE_OBJECT: Final[str] +DUPLICATE_ALIAS: Final[str] +DUPLICATE_FUNCTION: Final[str] +AMBIGUOUS_FUNCTION: Final[str] +GROUPING_ERROR: Final[str] +DATATYPE_MISMATCH: Final[str] +WRONG_OBJECT_TYPE: Final[str] +INVALID_FOREIGN_KEY: Final[str] +CANNOT_COERCE: Final[str] +UNDEFINED_FUNCTION: Final[str] +GENERATED_ALWAYS: Final[str] +RESERVED_NAME: Final[str] +UNDEFINED_TABLE: Final[str] +UNDEFINED_PARAMETER: Final[str] +DUPLICATE_CURSOR: Final[str] +DUPLICATE_DATABASE: Final[str] +DUPLICATE_PREPARED_STATEMENT: Final[str] +DUPLICATE_SCHEMA: Final[str] +DUPLICATE_TABLE: Final[str] +AMBIGUOUS_PARAMETER: Final[str] +AMBIGUOUS_ALIAS: Final[str] +INVALID_COLUMN_REFERENCE: Final[str] +INVALID_CURSOR_DEFINITION: Final[str] +INVALID_DATABASE_DEFINITION: Final[str] +INVALID_FUNCTION_DEFINITION: Final[str] +INVALID_PREPARED_STATEMENT_DEFINITION: Final[str] +INVALID_SCHEMA_DEFINITION: Final[str] +INVALID_TABLE_DEFINITION: Final[str] +INVALID_OBJECT_DEFINITION: Final[str] +INDETERMINATE_DATATYPE: Final[str] +INVALID_RECURSION: Final[str] +WINDOWING_ERROR: Final[str] +COLLATION_MISMATCH: Final[str] +INDETERMINATE_COLLATION: Final[str] +WITH_CHECK_OPTION_VIOLATION: Final[str] +INSUFFICIENT_RESOURCES: Final[str] +DISK_FULL: Final[str] +OUT_OF_MEMORY: Final[str] +TOO_MANY_CONNECTIONS: Final[str] +CONFIGURATION_LIMIT_EXCEEDED: Final[str] +PROGRAM_LIMIT_EXCEEDED: Final[str] +STATEMENT_TOO_COMPLEX: Final[str] +TOO_MANY_COLUMNS: Final[str] +TOO_MANY_ARGUMENTS: Final[str] +OBJECT_NOT_IN_PREREQUISITE_STATE: Final[str] +OBJECT_IN_USE: Final[str] +CANT_CHANGE_RUNTIME_PARAM: Final[str] +LOCK_NOT_AVAILABLE: Final[str] +UNSAFE_NEW_ENUM_VALUE_USAGE: Final[str] +OPERATOR_INTERVENTION: Final[str] +QUERY_CANCELED: Final[str] +ADMIN_SHUTDOWN: Final[str] +CRASH_SHUTDOWN: Final[str] +CANNOT_CONNECT_NOW: Final[str] +DATABASE_DROPPED: Final[str] +SYSTEM_ERROR: Final[str] +IO_ERROR: Final[str] +UNDEFINED_FILE: Final[str] +DUPLICATE_FILE: Final[str] +FILE_NAME_TOO_LONG: Final[str] +SNAPSHOT_TOO_OLD: Final[str] +CONFIG_FILE_ERROR: Final[str] +LOCK_FILE_EXISTS: Final[str] +FDW_ERROR: Final[str] +FDW_OUT_OF_MEMORY: Final[str] +FDW_DYNAMIC_PARAMETER_VALUE_NEEDED: Final[str] +FDW_INVALID_DATA_TYPE: Final[str] +FDW_COLUMN_NAME_NOT_FOUND: Final[str] +FDW_INVALID_DATA_TYPE_DESCRIPTORS: Final[str] +FDW_INVALID_COLUMN_NAME: Final[str] +FDW_INVALID_COLUMN_NUMBER: Final[str] +FDW_INVALID_USE_OF_NULL_POINTER: Final[str] +FDW_INVALID_STRING_FORMAT: Final[str] +FDW_INVALID_HANDLE: Final[str] +FDW_INVALID_OPTION_INDEX: Final[str] +FDW_INVALID_OPTION_NAME: Final[str] +FDW_OPTION_NAME_NOT_FOUND: Final[str] +FDW_REPLY_HANDLE: Final[str] +FDW_UNABLE_TO_CREATE_EXECUTION: Final[str] +FDW_UNABLE_TO_CREATE_REPLY: Final[str] +FDW_UNABLE_TO_ESTABLISH_CONNECTION: Final[str] +FDW_NO_SCHEMAS: Final[str] +FDW_SCHEMA_NOT_FOUND: Final[str] +FDW_TABLE_NOT_FOUND: Final[str] +FDW_FUNCTION_SEQUENCE_ERROR: Final[str] +FDW_TOO_MANY_HANDLES: Final[str] +FDW_INCONSISTENT_DESCRIPTOR_INFORMATION: Final[str] +FDW_INVALID_ATTRIBUTE_VALUE: Final[str] +FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH: Final[str] +FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER: Final[str] +PLPGSQL_ERROR: Final[str] +RAISE_EXCEPTION: Final[str] +NO_DATA_FOUND: Final[str] +TOO_MANY_ROWS: Final[str] +ASSERT_FAILURE: Final[str] +INTERNAL_ERROR: Final[str] +DATA_CORRUPTED: Final[str] +INDEX_CORRUPTED: Final[str] +IDLE_SESSION_TIMEOUT: Final[str] +SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE: Final[str] +TRANSACTION_TIMEOUT: Final[str] diff --git a/stubs/psycopg2/psycopg2/errors.pyi b/stubs/psycopg2/psycopg2/errors.pyi new file mode 100644 index 000000000000..4c48e32c568e --- /dev/null +++ b/stubs/psycopg2/psycopg2/errors.pyi @@ -0,0 +1,269 @@ +from psycopg2._psycopg import ( + DatabaseError as DatabaseError, + DataError as DataError, + Error as Error, + IntegrityError as IntegrityError, + InterfaceError as InterfaceError, + InternalError as InternalError, + NotSupportedError as NotSupportedError, + OperationalError as OperationalError, + ProgrammingError as ProgrammingError, + QueryCanceledError as QueryCanceledError, + TransactionRollbackError as TransactionRollbackError, + Warning as Warning, +) + +class DiagnosticsException(DatabaseError): ... +class InvalidGrantOperation(DatabaseError): ... +class InvalidGrantor(DatabaseError): ... +class InvalidLocatorSpecification(DatabaseError): ... +class InvalidRoleSpecification(DatabaseError): ... +class InvalidTransactionInitiation(DatabaseError): ... +class LocatorException(DatabaseError): ... +class NoAdditionalDynamicResultSetsReturned(DatabaseError): ... +class NoData(DatabaseError): ... +class SnapshotTooOld(DatabaseError): ... +class SqlStatementNotYetComplete(DatabaseError): ... +class StackedDiagnosticsAccessedWithoutActiveHandler(DatabaseError): ... +class TriggeredActionException(DatabaseError): ... +class ActiveSqlTransaction(InternalError): ... +class AdminShutdown(OperationalError): ... +class AmbiguousAlias(ProgrammingError): ... +class AmbiguousColumn(ProgrammingError): ... +class AmbiguousFunction(ProgrammingError): ... +class AmbiguousParameter(ProgrammingError): ... +class ArraySubscriptError(DataError): ... +class AssertFailure(InternalError): ... +class BadCopyFileFormat(DataError): ... +class BranchTransactionAlreadyActive(InternalError): ... +class CannotCoerce(ProgrammingError): ... +class CannotConnectNow(OperationalError): ... +class CantChangeRuntimeParam(OperationalError): ... +class CardinalityViolation(ProgrammingError): ... +class CaseNotFound(ProgrammingError): ... +class CharacterNotInRepertoire(DataError): ... +class CheckViolation(IntegrityError): ... +class CollationMismatch(ProgrammingError): ... +class ConfigFileError(InternalError): ... +class ConfigurationLimitExceeded(OperationalError): ... +class ConnectionDoesNotExist(OperationalError): ... +class ConnectionException(OperationalError): ... +class ConnectionFailure(OperationalError): ... +class ContainingSqlNotPermitted(InternalError): ... +class CrashShutdown(OperationalError): ... +class DataCorrupted(InternalError): ... +class DataException(DataError): ... +class DatabaseDropped(OperationalError): ... +class DatatypeMismatch(ProgrammingError): ... +class DatetimeFieldOverflow(DataError): ... +class DependentObjectsStillExist(InternalError): ... +class DependentPrivilegeDescriptorsStillExist(InternalError): ... +class DiskFull(OperationalError): ... +class DivisionByZero(DataError): ... +class DuplicateAlias(ProgrammingError): ... +class DuplicateColumn(ProgrammingError): ... +class DuplicateCursor(ProgrammingError): ... +class DuplicateDatabase(ProgrammingError): ... +class DuplicateFile(OperationalError): ... +class DuplicateFunction(ProgrammingError): ... +class DuplicateJsonObjectKeyValue(DataError): ... +class DuplicateObject(ProgrammingError): ... +class DuplicatePreparedStatement(ProgrammingError): ... +class DuplicateSchema(ProgrammingError): ... +class DuplicateTable(ProgrammingError): ... +class ErrorInAssignment(DataError): ... +class EscapeCharacterConflict(DataError): ... +class EventTriggerProtocolViolated(InternalError): ... +class ExclusionViolation(IntegrityError): ... +class ExternalRoutineException(InternalError): ... +class ExternalRoutineInvocationException(InternalError): ... +class FdwColumnNameNotFound(OperationalError): ... +class FdwDynamicParameterValueNeeded(OperationalError): ... +class FdwError(OperationalError): ... +class FdwFunctionSequenceError(OperationalError): ... +class FdwInconsistentDescriptorInformation(OperationalError): ... +class FdwInvalidAttributeValue(OperationalError): ... +class FdwInvalidColumnName(OperationalError): ... +class FdwInvalidColumnNumber(OperationalError): ... +class FdwInvalidDataType(OperationalError): ... +class FdwInvalidDataTypeDescriptors(OperationalError): ... +class FdwInvalidDescriptorFieldIdentifier(OperationalError): ... +class FdwInvalidHandle(OperationalError): ... +class FdwInvalidOptionIndex(OperationalError): ... +class FdwInvalidOptionName(OperationalError): ... +class FdwInvalidStringFormat(OperationalError): ... +class FdwInvalidStringLengthOrBufferLength(OperationalError): ... +class FdwInvalidUseOfNullPointer(OperationalError): ... +class FdwNoSchemas(OperationalError): ... +class FdwOptionNameNotFound(OperationalError): ... +class FdwOutOfMemory(OperationalError): ... +class FdwReplyHandle(OperationalError): ... +class FdwSchemaNotFound(OperationalError): ... +class FdwTableNotFound(OperationalError): ... +class FdwTooManyHandles(OperationalError): ... +class FdwUnableToCreateExecution(OperationalError): ... +class FdwUnableToCreateReply(OperationalError): ... +class FdwUnableToEstablishConnection(OperationalError): ... +class FeatureNotSupported(NotSupportedError): ... +class FloatingPointException(DataError): ... +class ForeignKeyViolation(IntegrityError): ... +class FunctionExecutedNoReturnStatement(InternalError): ... +class GeneratedAlways(ProgrammingError): ... +class GroupingError(ProgrammingError): ... +class HeldCursorRequiresSameIsolationLevel(InternalError): ... +class IdleInTransactionSessionTimeout(InternalError): ... +class InFailedSqlTransaction(InternalError): ... +class InappropriateAccessModeForBranchTransaction(InternalError): ... +class InappropriateIsolationLevelForBranchTransaction(InternalError): ... +class IndeterminateCollation(ProgrammingError): ... +class IndeterminateDatatype(ProgrammingError): ... +class IndexCorrupted(InternalError): ... +class IndicatorOverflow(DataError): ... +class InsufficientPrivilege(ProgrammingError): ... +class InsufficientResources(OperationalError): ... +class IntegrityConstraintViolation(IntegrityError): ... +class InternalError_(InternalError): ... +class IntervalFieldOverflow(DataError): ... +class InvalidArgumentForLogarithm(DataError): ... +class InvalidArgumentForNthValueFunction(DataError): ... +class InvalidArgumentForNtileFunction(DataError): ... +class InvalidArgumentForPowerFunction(DataError): ... +class InvalidArgumentForSqlJsonDatetimeFunction(DataError): ... +class InvalidArgumentForWidthBucketFunction(DataError): ... +class InvalidAuthorizationSpecification(OperationalError): ... +class InvalidBinaryRepresentation(DataError): ... +class InvalidCatalogName(ProgrammingError): ... +class InvalidCharacterValueForCast(DataError): ... +class InvalidColumnDefinition(ProgrammingError): ... +class InvalidColumnReference(ProgrammingError): ... +class InvalidCursorDefinition(ProgrammingError): ... +class InvalidCursorName(OperationalError): ... +class InvalidCursorState(InternalError): ... +class InvalidDatabaseDefinition(ProgrammingError): ... +class InvalidDatetimeFormat(DataError): ... +class InvalidEscapeCharacter(DataError): ... +class InvalidEscapeOctet(DataError): ... +class InvalidEscapeSequence(DataError): ... +class InvalidForeignKey(ProgrammingError): ... +class InvalidFunctionDefinition(ProgrammingError): ... +class InvalidIndicatorParameterValue(DataError): ... +class InvalidJsonText(DataError): ... +class InvalidName(ProgrammingError): ... +class InvalidObjectDefinition(ProgrammingError): ... +class InvalidParameterValue(DataError): ... +class InvalidPassword(OperationalError): ... +class InvalidPrecedingOrFollowingSize(DataError): ... +class InvalidPreparedStatementDefinition(ProgrammingError): ... +class InvalidRecursion(ProgrammingError): ... +class InvalidRegularExpression(DataError): ... +class InvalidRowCountInLimitClause(DataError): ... +class InvalidRowCountInResultOffsetClause(DataError): ... +class InvalidSavepointSpecification(InternalError): ... +class InvalidSchemaDefinition(ProgrammingError): ... +class InvalidSchemaName(ProgrammingError): ... +class InvalidSqlJsonSubscript(DataError): ... +class InvalidSqlStatementName(OperationalError): ... +class InvalidSqlstateReturned(InternalError): ... +class InvalidTableDefinition(ProgrammingError): ... +class InvalidTablesampleArgument(DataError): ... +class InvalidTablesampleRepeat(DataError): ... +class InvalidTextRepresentation(DataError): ... +class InvalidTimeZoneDisplacementValue(DataError): ... +class InvalidTransactionState(InternalError): ... +class InvalidTransactionTermination(InternalError): ... +class InvalidUseOfEscapeCharacter(DataError): ... +class InvalidXmlComment(DataError): ... +class InvalidXmlContent(DataError): ... +class InvalidXmlDocument(DataError): ... +class InvalidXmlProcessingInstruction(DataError): ... +class IoError(OperationalError): ... +class LockFileExists(InternalError): ... +class LockNotAvailable(OperationalError): ... +class ModifyingSqlDataNotPermitted(InternalError): ... +class ModifyingSqlDataNotPermittedExt(InternalError): ... +class MoreThanOneSqlJsonItem(DataError): ... +class MostSpecificTypeMismatch(DataError): ... +class NameTooLong(ProgrammingError): ... +class NoActiveSqlTransaction(InternalError): ... +class NoActiveSqlTransactionForBranchTransaction(InternalError): ... +class NoDataFound(InternalError): ... +class NoSqlJsonItem(DataError): ... +class NonNumericSqlJsonItem(DataError): ... +class NonUniqueKeysInAJsonObject(DataError): ... +class NonstandardUseOfEscapeCharacter(DataError): ... +class NotAnXmlDocument(DataError): ... +class NotNullViolation(IntegrityError): ... +class NullValueNoIndicatorParameter(DataError): ... +class NullValueNotAllowed(DataError): ... +class NullValueNotAllowedExt(InternalError): ... +class NumericValueOutOfRange(DataError): ... +class ObjectInUse(OperationalError): ... +class ObjectNotInPrerequisiteState(OperationalError): ... +class OperatorIntervention(OperationalError): ... +class OutOfMemory(OperationalError): ... +class PlpgsqlError(InternalError): ... +class ProgramLimitExceeded(OperationalError): ... +class ProhibitedSqlStatementAttempted(InternalError): ... +class ProhibitedSqlStatementAttemptedExt(InternalError): ... +class ProtocolViolation(OperationalError): ... +class RaiseException(InternalError): ... +class ReadOnlySqlTransaction(InternalError): ... +class ReadingSqlDataNotPermitted(InternalError): ... +class ReadingSqlDataNotPermittedExt(InternalError): ... +class ReservedName(ProgrammingError): ... +class RestrictViolation(IntegrityError): ... +class SavepointException(InternalError): ... +class SchemaAndDataStatementMixingNotSupported(InternalError): ... +class SequenceGeneratorLimitExceeded(DataError): ... +class SingletonSqlJsonItemRequired(DataError): ... +class SqlJsonArrayNotFound(DataError): ... +class SqlJsonMemberNotFound(DataError): ... +class SqlJsonNumberNotFound(DataError): ... +class SqlJsonObjectNotFound(DataError): ... +class SqlJsonScalarRequired(DataError): ... +class SqlRoutineException(InternalError): ... +class SqlclientUnableToEstablishSqlconnection(OperationalError): ... +class SqlserverRejectedEstablishmentOfSqlconnection(OperationalError): ... +class SrfProtocolViolated(InternalError): ... +class StatementTooComplex(OperationalError): ... +class StringDataLengthMismatch(DataError): ... +class StringDataRightTruncation(DataError): ... +class SubstringError(DataError): ... +class SyntaxError(ProgrammingError): ... +class SyntaxErrorOrAccessRuleViolation(ProgrammingError): ... +class SystemError(OperationalError): ... +class TooManyArguments(OperationalError): ... +class TooManyColumns(OperationalError): ... +class TooManyConnections(OperationalError): ... +class TooManyJsonArrayElements(DataError): ... +class TooManyJsonObjectMembers(DataError): ... +class TooManyRows(InternalError): ... +class TransactionResolutionUnknown(OperationalError): ... +class TransactionTimeout(InternalError): ... +class TriggerProtocolViolated(InternalError): ... +class TriggeredDataChangeViolation(OperationalError): ... +class TrimError(DataError): ... +class UndefinedColumn(ProgrammingError): ... +class UndefinedFile(OperationalError): ... +class UndefinedFunction(ProgrammingError): ... +class UndefinedObject(ProgrammingError): ... +class UndefinedParameter(ProgrammingError): ... +class UndefinedTable(ProgrammingError): ... +class UniqueViolation(IntegrityError): ... +class UnsafeNewEnumValueUsage(OperationalError): ... +class UnterminatedCString(DataError): ... +class UntranslatableCharacter(DataError): ... +class WindowingError(ProgrammingError): ... +class WithCheckOptionViolation(ProgrammingError): ... +class WrongObjectType(ProgrammingError): ... +class ZeroLengthCharacterString(DataError): ... +class DeadlockDetected(TransactionRollbackError): ... +class QueryCanceled(QueryCanceledError): ... +class SerializationFailure(TransactionRollbackError): ... +class StatementCompletionUnknown(TransactionRollbackError): ... +class TransactionIntegrityConstraintViolation(TransactionRollbackError): ... +class TransactionRollback(TransactionRollbackError): ... +class IdleSessionTimeout(OperationalError): ... +class SqlJsonItemCannotBeCastToTargetType(DataError): ... + +def lookup(code: str) -> type[Error]: ... diff --git a/stubs/psycopg2/psycopg2/extensions.pyi b/stubs/psycopg2/psycopg2/extensions.pyi new file mode 100644 index 000000000000..77e12076674f --- /dev/null +++ b/stubs/psycopg2/psycopg2/extensions.pyi @@ -0,0 +1,125 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable +from typing import Any, TypeVar, overload + +from psycopg2._psycopg import ( + BINARYARRAY as BINARYARRAY, + BOOLEAN as BOOLEAN, + BOOLEANARRAY as BOOLEANARRAY, + BYTES as BYTES, + BYTESARRAY as BYTESARRAY, + DATE as DATE, + DATEARRAY as DATEARRAY, + DATETIMEARRAY as DATETIMEARRAY, + DECIMAL as DECIMAL, + DECIMALARRAY as DECIMALARRAY, + FLOAT as FLOAT, + FLOATARRAY as FLOATARRAY, + INTEGER as INTEGER, + INTEGERARRAY as INTEGERARRAY, + INTERVAL as INTERVAL, + INTERVALARRAY as INTERVALARRAY, + LONGINTEGER as LONGINTEGER, + LONGINTEGERARRAY as LONGINTEGERARRAY, + PYDATE as PYDATE, + PYDATEARRAY as PYDATEARRAY, + PYDATETIME as PYDATETIME, + PYDATETIMEARRAY as PYDATETIMEARRAY, + PYDATETIMETZ as PYDATETIMETZ, + PYDATETIMETZARRAY as PYDATETIMETZARRAY, + PYINTERVAL as PYINTERVAL, + PYINTERVALARRAY as PYINTERVALARRAY, + PYTIME as PYTIME, + PYTIMEARRAY as PYTIMEARRAY, + ROWIDARRAY as ROWIDARRAY, + STRINGARRAY as STRINGARRAY, + TIME as TIME, + TIMEARRAY as TIMEARRAY, + UNICODE as UNICODE, + UNICODEARRAY as UNICODEARRAY, + AsIs as AsIs, + Binary as Binary, + Boolean as Boolean, + Column as Column, + ConnectionInfo as ConnectionInfo, + DateFromPy as DateFromPy, + Diagnostics as Diagnostics, + Float as Float, + Int as Int, + IntervalFromPy as IntervalFromPy, + ISQLQuote as ISQLQuote, + Notify as Notify, + QueryCanceledError as QueryCanceledError, + QuotedString as QuotedString, + TimeFromPy as TimeFromPy, + TimestampFromPy as TimestampFromPy, + TransactionRollbackError as TransactionRollbackError, + Xid as Xid, + _ISQLQuoteProto, + _type, + adapt as adapt, + adapters as adapters, + binary_types as binary_types, + connection as connection, + cursor as cursor, + encodings as encodings, + encrypt_password as encrypt_password, + get_wait_callback as get_wait_callback, + libpq_version as libpq_version, + lobject as lobject, + new_array_type as new_array_type, + new_type as new_type, + parse_dsn as parse_dsn, + quote_ident as quote_ident, + register_type as register_type, + set_wait_callback as set_wait_callback, + string_types as string_types, +) + +ISOLATION_LEVEL_AUTOCOMMIT: int +ISOLATION_LEVEL_READ_UNCOMMITTED: int +ISOLATION_LEVEL_READ_COMMITTED: int +ISOLATION_LEVEL_REPEATABLE_READ: int +ISOLATION_LEVEL_SERIALIZABLE: int +ISOLATION_LEVEL_DEFAULT: Any +STATUS_SETUP: int +STATUS_READY: int +STATUS_BEGIN: int +STATUS_SYNC: int +STATUS_ASYNC: int +STATUS_PREPARED: int +STATUS_IN_TRANSACTION: int +POLL_OK: int +POLL_READ: int +POLL_WRITE: int +POLL_ERROR: int +TRANSACTION_STATUS_IDLE: int +TRANSACTION_STATUS_ACTIVE: int +TRANSACTION_STATUS_INTRANS: int +TRANSACTION_STATUS_INERROR: int +TRANSACTION_STATUS_UNKNOWN: int + +_T = TypeVar("_T") + +def register_adapter(typ: type[_T], callable: Callable[[_T], _ISQLQuoteProto]) -> None: ... + +class SQL_IN: + def __init__(self, seq: Iterable[object]) -> None: ... + def prepare(self, conn: connection | None) -> None: ... + def getquoted(self) -> bytes: ... + +class NoneAdapter: + def __init__(self, obj: Unused) -> None: ... + def getquoted(self, _null: bytes = b"NULL") -> bytes: ... + +@overload +def make_dsn(dsn: bytes) -> bytes: ... # type: ignore[overload-overlap] +@overload +def make_dsn(dsn: None = None) -> str: ... +@overload +def make_dsn(dsn: str | bytes | None = None, **kwargs: Any) -> str: ... + +JSON: _type +JSONARRAY: _type | None +JSONB: _type +JSONBARRAY: _type | None diff --git a/stubs/psycopg2/psycopg2/extras.pyi b/stubs/psycopg2/psycopg2/extras.pyi new file mode 100644 index 000000000000..1820c9c0f055 --- /dev/null +++ b/stubs/psycopg2/psycopg2/extras.pyi @@ -0,0 +1,252 @@ +from collections import OrderedDict +from collections.abc import Callable +from typing import Any, NamedTuple, TypeVar, overload + +from psycopg2._ipaddress import register_ipaddress as register_ipaddress +from psycopg2._json import ( + Json as Json, + register_default_json as register_default_json, + register_default_jsonb as register_default_jsonb, + register_json as register_json, +) +from psycopg2._psycopg import ( + REPLICATION_LOGICAL as REPLICATION_LOGICAL, + REPLICATION_PHYSICAL as REPLICATION_PHYSICAL, + ReplicationConnection as _replicationConnection, + ReplicationCursor as _replicationCursor, + ReplicationMessage as ReplicationMessage, + _Vars, + connection as _connection, + cursor as _cursor, + quote_ident as quote_ident, +) +from psycopg2._range import ( + DateRange as DateRange, + DateTimeRange as DateTimeRange, + DateTimeTZRange as DateTimeTZRange, + NumericRange as NumericRange, + Range as Range, + RangeAdapter as RangeAdapter, + RangeCaster as RangeCaster, + register_range as register_range, +) +from psycopg2.sql import Composable + +_T_cur = TypeVar("_T_cur", bound=_cursor) + +class DictCursorBase(_cursor): + def __init__(self, *args, **kwargs) -> None: ... + +class DictConnection(_connection): + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> DictCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + +class DictCursor(DictCursorBase): + def __init__(self, *args, **kwargs) -> None: ... + index: Any + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> DictRow | None: ... # type: ignore[override] + def fetchmany(self, size: int | None = None) -> list[DictRow]: ... # type: ignore[override] + def fetchall(self) -> list[DictRow]: ... # type: ignore[override] + def __next__(self) -> DictRow: ... # type: ignore[override] + +class DictRow(list[Any]): + __slots__ = ("_index",) + def __init__(self, cursor) -> None: ... + def __getitem__(self, x): ... + def __setitem__(self, x, v) -> None: ... + def items(self): ... + def keys(self): ... + def values(self): ... + def get(self, x, default=None): ... + def copy(self): ... + def __contains__(self, x): ... + def __reduce__(self): ... + +class RealDictConnection(_connection): + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> RealDictCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + +class RealDictCursor(DictCursorBase): + def __init__(self, *args, **kwargs) -> None: ... + column_mapping: Any + def execute(self, query: str | bytes | Composable, vars: _Vars = None) -> None: ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> RealDictRow | None: ... # type: ignore[override] + def fetchmany(self, size: int | None = None) -> list[RealDictRow]: ... # type: ignore[override] + def fetchall(self) -> list[RealDictRow]: ... # type: ignore[override] + def __next__(self) -> RealDictRow: ... # type: ignore[override] + +class RealDictRow(OrderedDict[Any, Any]): + def __init__(self, *args, **kwargs) -> None: ... + def __setitem__(self, key, value) -> None: ... + +class NamedTupleConnection(_connection): + @overload + def cursor( + self, name: str | bytes | None = None, cursor_factory: None = None, withhold: bool = False, scrollable: bool | None = None + ) -> NamedTupleCursor: ... + @overload + def cursor( + self, + name: str | bytes | None = None, + *, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + @overload + def cursor( + self, + name: str | bytes | None, + cursor_factory: Callable[[_connection, str | bytes | None], _T_cur], + withhold: bool = False, + scrollable: bool | None = None, + ) -> _T_cur: ... + +class NamedTupleCursor(_cursor): + Record: Any + MAX_CACHE: int + def execute(self, query, vars=None): ... + def executemany(self, query, vars): ... + def callproc(self, procname, vars=None): ... + def fetchone(self) -> NamedTuple | None: ... + def fetchmany(self, size: int | None = None) -> list[NamedTuple]: ... # type: ignore[override] + def fetchall(self) -> list[NamedTuple]: ... # type: ignore[override] + def __next__(self) -> NamedTuple: ... + +class LoggingConnection(_connection): + log: Any + def initialize(self, logobj) -> None: ... + def filter(self, msg, curs): ... + def cursor(self, *args, **kwargs): ... + +class LoggingCursor(_cursor): + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... + +class MinTimeLoggingConnection(LoggingConnection): + def initialize(self, logobj, mintime: int = 0) -> None: ... + def filter(self, msg, curs): ... + def cursor(self, *args, **kwargs): ... + +class MinTimeLoggingCursor(LoggingCursor): + timestamp: Any + def execute(self, query, vars=None): ... + def callproc(self, procname, vars=None): ... + +class LogicalReplicationConnection(_replicationConnection): + def __init__(self, *args, **kwargs) -> None: ... + +class PhysicalReplicationConnection(_replicationConnection): + def __init__(self, *args, **kwargs) -> None: ... + +class StopReplication(Exception): ... + +class ReplicationCursor(_replicationCursor): + def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None) -> None: ... + def drop_replication_slot(self, slot_name) -> None: ... + def start_replication( + self, + slot_name=None, + slot_type=None, + start_lsn: int = 0, + timeline: int = 0, + options=None, + decode: bool = False, + status_interval: int = 10, + ) -> None: ... + def fileno(self): ... + def consume_stream( + self, consume: Callable[[ReplicationMessage], object], keepalive_interval: float | None = None + ) -> None: ... + +class UUID_adapter: + def __init__(self, uuid) -> None: ... + def __conform__(self, proto): ... + def getquoted(self): ... + +def register_uuid(oids=None, conn_or_curs=None): ... + +class Inet: + addr: Any + def __init__(self, addr) -> None: ... + def prepare(self, conn) -> None: ... + def getquoted(self): ... + def __conform__(self, proto): ... + +def register_inet(oid=None, conn_or_curs=None): ... +def wait_select(conn) -> None: ... + +class HstoreAdapter: + wrapped: Any + def __init__(self, wrapped) -> None: ... + conn: Any + getquoted: Any + def prepare(self, conn) -> None: ... + @classmethod + def parse(cls, s, cur, _bsdec=...): ... + @classmethod + def parse_unicode(cls, s, cur): ... + @classmethod + def get_oids(cls, conn_or_curs): ... + +def register_hstore(conn_or_curs, globally: bool = False, unicode: bool = False, oid=None, array_oid=None) -> None: ... + +class CompositeCaster: + name: Any + schema: Any + oid: Any + array_oid: Any + attnames: Any + atttypes: Any + typecaster: Any + array_typecaster: Any + def __init__(self, name, oid, attrs, array_oid=None, schema=None) -> None: ... + def parse(self, s, curs): ... + def make(self, values): ... + @classmethod + def tokenize(cls, s): ... + +def register_composite(name, conn_or_curs, globally: bool = False, factory=None): ... +def execute_batch(cur, sql, argslist, page_size: int = 100) -> None: ... +def execute_values(cur, sql, argslist, template=None, page_size: int = 100, fetch: bool = False): ... diff --git a/stubs/psycopg2/psycopg2/pool.pyi b/stubs/psycopg2/psycopg2/pool.pyi new file mode 100644 index 000000000000..a883d74f0ed8 --- /dev/null +++ b/stubs/psycopg2/psycopg2/pool.pyi @@ -0,0 +1,25 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Hashable + +import psycopg2 +from psycopg2.extensions import connection + +class PoolError(psycopg2.Error): ... + +class AbstractConnectionPool: + minconn: int + maxconn: int + closed: bool + def __init__(self, minconn: ConvertibleToInt, maxconn: ConvertibleToInt, *args, **kwargs) -> None: ... + # getconn, putconn and closeall are officially documented as methods of the + # abstract base class, but in reality, they only exist on the children classes + def getconn(self, key: Hashable | None = None) -> connection: ... + def putconn(self, conn: connection, key: Hashable | None = None, close: bool = False) -> None: ... + def closeall(self) -> None: ... + +class SimpleConnectionPool(AbstractConnectionPool): ... + +class ThreadedConnectionPool(AbstractConnectionPool): + # This subclass has a default value for conn which doesn't exist + # in the SimpleConnectionPool class, nor in the documentation + def putconn(self, conn: connection | None = None, key: Hashable | None = None, close: bool = False) -> None: ... diff --git a/stubs/psycopg2/psycopg2/sql.pyi b/stubs/psycopg2/psycopg2/sql.pyi new file mode 100644 index 000000000000..60f7d8714223 --- /dev/null +++ b/stubs/psycopg2/psycopg2/sql.pyi @@ -0,0 +1,49 @@ +from collections.abc import Iterable, Iterator +from typing import Any, Generic, TypeVar + +from psycopg2._psycopg import connection, cursor + +_T = TypeVar("_T") + +class Composable: + def __init__(self, wrapped: Any) -> None: ... + def as_string(self, context: connection | cursor) -> str: ... + def __add__(self, other: Composable) -> Composed: ... + def __mul__(self, n: int) -> Composed: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class Composed(Composable): + def __init__(self, seq: Iterable[Composable]) -> None: ... + @property + def seq(self) -> list[Composable]: ... + def __iter__(self) -> Iterator[Composable]: ... + def __add__(self, other: Composable) -> Composed: ... + def join(self, joiner: str | SQL) -> Composed: ... + +class SQL(Composable): + def __init__(self, string: str) -> None: ... + @property + def string(self) -> str: ... + def format(self, *args: Composable, **kwargs: Composable) -> Composed: ... + def join(self, seq: Iterable[Composable]) -> Composed: ... + +class Identifier(Composable): + def __init__(self, *strings: str) -> None: ... + @property + def strings(self) -> tuple[str, ...]: ... + @property + def string(self) -> str: ... + +class Literal(Composable, Generic[_T]): + def __init__(self, wrapped: _T) -> None: ... + @property + def wrapped(self) -> _T: ... + +class Placeholder(Composable): + def __init__(self, name: str | None = None) -> None: ... + @property + def name(self) -> str | None: ... + +NULL: SQL +DEFAULT: SQL diff --git a/stubs/psycopg2/psycopg2/tz.pyi b/stubs/psycopg2/psycopg2/tz.pyi new file mode 100644 index 000000000000..75d1484805f7 --- /dev/null +++ b/stubs/psycopg2/psycopg2/tz.pyi @@ -0,0 +1,26 @@ +import datetime +from typing import Any +from typing_extensions import Self + +ZERO: datetime.timedelta + +class FixedOffsetTimezone(datetime.tzinfo): + def __init__(self, offset: datetime.timedelta | float | None = None, name: str | None = None) -> None: ... + def __new__(cls, offset: datetime.timedelta | float | None = None, name: str | None = None) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __getinitargs__(self) -> tuple[Any, ...]: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +STDOFFSET: datetime.timedelta +DSTOFFSET: datetime.timedelta +DSTDIFF: datetime.timedelta + +class LocalTimezone(datetime.tzinfo): + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def tzname(self, dt: datetime.datetime) -> str: ... # type: ignore[override] + +LOCAL: LocalTimezone diff --git a/stubs/punq/@tests/stubtest_allowlist.txt b/stubs/punq/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9a0d8e0f9e3a --- /dev/null +++ b/stubs/punq/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +punq._Empty.__init__ +punq._Registration.__class_getitem__ diff --git a/stubs/punq/METADATA.toml b/stubs/punq/METADATA.toml new file mode 100644 index 000000000000..0c3e8e97fbb8 --- /dev/null +++ b/stubs/punq/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.8.*" +upstream-repository = "https://github.com/bobthemighty/punq" diff --git a/stubs/punq/punq/__init__.pyi b/stubs/punq/punq/__init__.pyi new file mode 100644 index 000000000000..1fb20df72028 --- /dev/null +++ b/stubs/punq/punq/__init__.pyi @@ -0,0 +1,138 @@ +from _typeshed import Incomplete +from collections import defaultdict +from collections.abc import Callable +from enum import Enum, unique +from typing import Any, Final, Generic, NamedTuple, NewType, TypeVar, overload +from typing_extensions import Self, deprecated + +_T = TypeVar("_T", default=Any) + +__version__: Final[str] + +@deprecated("Deprecated alias for `MissingDependencyError`.") +class MissingDependencyException(Exception): ... + +class MissingDependencyError(MissingDependencyException): ... + +@deprecated("Deprecated alias for `InvalidRegistrationError`.") +class InvalidRegistrationException(Exception): ... + +class InvalidRegistrationError(InvalidRegistrationException): ... + +class InvalidFactoryError(InvalidRegistrationError): + def __init__(self, service, factory) -> None: ... + +class InvalidSelfRegistrationError(InvalidRegistrationError): + def __init__(self, service) -> None: ... + +@deprecated("Deprecated alias for `InvalidForwardReferenceError`.") +class InvalidForwardReferenceException(Exception): ... + +class InvalidForwardReferenceError(InvalidForwardReferenceException): ... + +# TODO: Make this class Generic +class RegistrationScope: + parent: RegistrationScope | None + entries: defaultdict[Incomplete, list[Incomplete]] + def __init__(self, parent: RegistrationScope | None = None) -> None: ... + def child(self) -> Self: ... + def append(self, key, value) -> None: ... + def get(self, key) -> list[Incomplete]: ... + +@unique +class Scope(Enum): + transient = 0 + singleton = 1 + +class _Registration(NamedTuple, Generic[_T]): + service: type[_T] | str + scope: Scope + builder: Callable[..., _T] + needs: dict[str, Any] # the type hints of the builder's parameters + args: dict[str, Any] # passed to builder at instantiation time + cache: bool + +_Empty = NewType("_Empty", object) # a class at runtime +empty: Final[_Empty] + +class _Registry: + def __init__(self, parent: _Registry | None = None) -> None: ... + def register_service_and_impl( + self, + service: type[_T] | str, + scope: Scope, + impl: type[_T], + resolve_args: dict[str, Any], # forwarded to _Registration.builder + cache: bool = True, + ) -> None: ... + def register_service_and_instance(self, service: type[_T] | str, instance: _T) -> None: ... + def register_concrete_service( + self, + service: type | str, + scope: Scope, + resolve_args: dict[str, Any] | None = None, # forwarded to _Registration.builder + cache: bool = True, + ) -> None: ... + def build_context(self, key: type | str, existing: _ResolutionContext | None = None) -> _ResolutionContext: ... + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + instance: _T | _Empty = ..., + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, # forwarded to _Registration.builder + ) -> None: ... + +class _ResolutionTarget(Generic[_T]): + service: type[_T] | str + impls: list[_Registration[_T]] + def __init__(self, key: type[_T] | str, impls: list[_Registration[_T]]) -> None: ... + def is_generic_list(self) -> bool: ... + @property + def generic_parameter(self) -> Any: ... # returns the first annotated generic parameter of the service + def next_impl(self) -> _Registration[_T] | None: ... + +class _ResolutionContext: + targets: dict[type | str, _ResolutionTarget[Any]] + cache: dict[type | str, Any] # resolved objects during this resolution + service: type | str + def __init__(self, key: type | str, impls: list[_Registration[Any]]) -> None: ... + def target(self, key: type[_T] | str) -> _ResolutionTarget[_T]: ... + def has_cached(self, key: type | str) -> bool: ... + def __getitem__(self, key: type[_T] | str) -> _T: ... + def __setitem__(self, key: type[_T] | str, value: _T) -> None: ... + def all_registrations(self, service: type[_T] | str) -> list[_Registration[_T]]: ... + +class Container: + registrations: _Registry + def __init__(self, registrations: _Registry | None = None, auto_register: bool = False) -> None: ... + + # all kwargs are forwarded to _Registration.builder + @overload + def register(self, service: type[_T] | str, *, instance: _T, cache: bool = True, **kwargs: Any) -> Self: ... + @overload + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + *, + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, + ) -> Self: ... + @overload + def register( + self, + service: type[_T] | str, + factory: Callable[..., _T] | _Empty = ..., + instance: _T | _Empty = ..., + scope: Scope = Scope.transient, + cache: bool = True, + **kwargs: Any, + ) -> Self: ... + + def resolve_all(self, service: type[_T] | str, **kwargs: Any) -> list[_T]: ... + def resolve(self, service_key: type[_T] | str, **kwargs: Any) -> _T: ... + def instantiate(self, service_key: type[_T] | str, **kwargs: Any) -> _T: ... + def child(self) -> Self: ... diff --git a/stubs/pyasn1/METADATA.toml b/stubs/pyasn1/METADATA.toml new file mode 100644 index 000000000000..c9d5651dfeeb --- /dev/null +++ b/stubs/pyasn1/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.6.*" +upstream-repository = "https://github.com/pyasn1/pyasn1" diff --git a/stubs/pyasn1/pyasn1/__init__.pyi b/stubs/pyasn1/pyasn1/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyasn1/pyasn1/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyasn1/pyasn1/codec/__init__.pyi b/stubs/pyasn1/pyasn1/codec/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/ber/__init__.pyi b/stubs/pyasn1/pyasn1/codec/ber/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi b/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi new file mode 100644 index 000000000000..587e25b84992 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/decoder.pyi @@ -0,0 +1,356 @@ +from _typeshed import Incomplete, Unused +from abc import ABCMeta, abstractmethod +from collections.abc import Callable + +from pyasn1.type import base, char, univ, useful +from pyasn1.type.base import Asn1Type +from pyasn1.type.tag import TagSet + +__all__ = ["StreamingDecoder", "Decoder", "decode"] + +class AbstractPayloadDecoder: + protoComponent: Asn1Type | None + @abstractmethod + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ) -> None: ... + # Abstract, but implementation is optional + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ) -> None: ... + +class AbstractSimplePayloadDecoder(AbstractPayloadDecoder, metaclass=ABCMeta): + @staticmethod + def substrateCollector(asn1Object, substrate, length, options): ... + +class RawPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Any + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class IntegerPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Integer + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class BooleanPayloadDecoder(IntegerPayloadDecoder): + protoComponent: univ.Boolean + +class BitStringPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.BitString + supportConstructedForm: bool + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class OctetStringPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.OctetString + supportConstructedForm: bool + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class NullPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Null + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class ObjectIdentifierPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.ObjectIdentifier + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class RealPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Real + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +class AbstractConstructedPayloadDecoder(AbstractPayloadDecoder, metaclass=ABCMeta): + protoComponent: base.ConstructedAsn1Type | None + +class ConstructedPayloadDecoderBase(AbstractConstructedPayloadDecoder): + protoRecordComponent: univ.SequenceAndSetBase | None + protoSequenceComponent: univ.SequenceOfAndSetOfBase | None + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class SequenceOrSequenceOfPayloadDecoder(ConstructedPayloadDecoderBase): + protoRecordComponent: univ.Sequence + protoSequenceComponent: univ.SequenceOf + +class SequencePayloadDecoder(SequenceOrSequenceOfPayloadDecoder): + protoComponent: univ.Sequence + +class SequenceOfPayloadDecoder(SequenceOrSequenceOfPayloadDecoder): + protoComponent: univ.SequenceOf + +class SetOrSetOfPayloadDecoder(ConstructedPayloadDecoderBase): + protoRecordComponent: univ.Set + protoSequenceComponent: univ.SetOf + +class SetPayloadDecoder(SetOrSetOfPayloadDecoder): + protoComponent: univ.Set + +class SetOfPayloadDecoder(SetOrSetOfPayloadDecoder): + protoComponent: univ.SetOf + +class ChoicePayloadDecoder(AbstractConstructedPayloadDecoder): + protoComponent: univ.Choice + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state=None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class AnyPayloadDecoder(AbstractSimplePayloadDecoder): + protoComponent: univ.Any + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + def indefLenValueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Callable[..., Incomplete] | None = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +class UTF8StringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.UTF8String + +class NumericStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.NumericString + +class PrintableStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.PrintableString + +class TeletexStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.TeletexString + +class VideotexStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.VideotexString + +class IA5StringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.IA5String + +class GraphicStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.GraphicString + +class VisibleStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.VisibleString + +class GeneralStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.GeneralString + +class UniversalStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.UniversalString + +class BMPStringPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: char.BMPString + +class ObjectDescriptorPayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.ObjectDescriptor + +class GeneralizedTimePayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.GeneralizedTime + +class UTCTimePayloadDecoder(OctetStringPayloadDecoder): + protoComponent: useful.UTCTime + +TAG_MAP: dict[TagSet, AbstractPayloadDecoder] +TYPE_MAP: dict[int, AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder: + defaultErrorState: int + defaultRawDecoder: AnyPayloadDecoder + supportIndefLength: bool + TAG_MAP: dict[TagSet, AbstractPayloadDecoder] + TYPE_MAP: dict[int, AbstractPayloadDecoder] + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__( + self, + substrate, + asn1Spec: Asn1Type | None = None, + tagSet: TagSet | None = None, + length: int | None = None, + state=0, + decodeFun: Unused = None, + substrateFun: Callable[..., Incomplete] | None = None, + **options, + ): ... + +decode: Decoder + +class StreamingDecoder: + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + + def __init__(self, substrate, asn1Spec=None, *, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __iter__(self): ... + +class Decoder: + STREAMING_DECODER: type[StreamingDecoder] + + @classmethod + def __call__(cls, substrate, asn1Spec=None, *, tagMap=..., typeMap=..., **ignored: Unused): ... diff --git a/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi b/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi new file mode 100644 index 000000000000..58a9193b1a17 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/encoder.pyi @@ -0,0 +1,84 @@ +from _typeshed import Unused +from abc import abstractmethod + +from pyasn1.type.base import Asn1Type +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class AbstractItemEncoder: + supportIndefLenMode: bool + eooIntegerSubstrate: tuple[int, int] + eooOctetsSubstrate: bytes + def encodeTag(self, singleTag, isConstructed): ... + def encodeLength(self, length, defMode): ... + @abstractmethod + def encodeValue(self, value, asn1Spec, encodeFun, **options) -> None: ... + def encode(self, value, asn1Spec: Asn1Type | None = None, encodeFun=None, **options): ... + +class EndOfOctetsEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class BooleanEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class IntegerEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + supportCompactZero: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class BitStringEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class OctetStringEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class NullEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class ObjectIdentifierEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class RealEncoder(AbstractItemEncoder): + supportIndefLenMode: bool + binEncBase: int + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceEncoder(AbstractItemEncoder): + omitEmptyOptionals: bool + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceOfEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class ChoiceEncoder(AbstractItemEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class AnyEncoder(OctetStringEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder: + fixedDefLengthMode: bool | None + fixedChunkSize: int | None + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, value, asn1Spec: Asn1Type | None = None, **options): ... + +class Encoder: + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **options: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec: Asn1Type | None = None, **options): ... + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi b/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi new file mode 100644 index 000000000000..00375f576216 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/ber/eoo.pyi @@ -0,0 +1,11 @@ +from pyasn1.type import base +from pyasn1.type.tag import TagSet + +__all__ = ["endOfOctets"] + +class EndOfOctets(base.SimpleAsn1Type): + defaultValue: int + tagSet: TagSet + def __new__(cls, *args, **kwargs): ... + +endOfOctets: EndOfOctets diff --git a/stubs/pyasn1/pyasn1/codec/cer/__init__.pyi b/stubs/pyasn1/pyasn1/codec/cer/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi b/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi new file mode 100644 index 000000000000..f847313ad438 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/cer/decoder.pyi @@ -0,0 +1,43 @@ +from _typeshed import Unused + +from pyasn1.codec.ber import decoder +from pyasn1.type import univ +from pyasn1.type.tag import TagSet + +__all__ = ["decode", "StreamingDecoder"] + +class BooleanPayloadDecoder(decoder.AbstractSimplePayloadDecoder): + protoComponent: univ.Boolean + def valueDecoder( + self, + substrate, + asn1Spec, + tagSet: TagSet | None = None, + length: int | None = None, + state: Unused = None, + decodeFun: Unused = None, + substrateFun: Unused = None, + **options, + ): ... + +BitStringPayloadDecoder = decoder.BitStringPayloadDecoder +OctetStringPayloadDecoder = decoder.OctetStringPayloadDecoder +RealPayloadDecoder = decoder.RealPayloadDecoder + +TAG_MAP: dict[TagSet, decoder.AbstractPayloadDecoder] +TYPE_MAP: dict[int, decoder.AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder(decoder.SingleItemDecoder): + TAG_MAP: dict[TagSet, decoder.AbstractPayloadDecoder] + TYPE_MAP: dict[int, decoder.AbstractPayloadDecoder] + +class StreamingDecoder(decoder.StreamingDecoder): + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + +class Decoder(decoder.Decoder): + STREAMING_DECODER: type[StreamingDecoder] + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi b/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi new file mode 100644 index 000000000000..25552d917862 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/cer/encoder.pyi @@ -0,0 +1,55 @@ +from typing import ClassVar + +from pyasn1.codec.ber import encoder +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class BooleanEncoder(encoder.IntegerEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class RealEncoder(encoder.RealEncoder): ... + +class TimeEncoderMixIn: + Z_CHAR: ClassVar[int] + PLUS_CHAR: ClassVar[int] + MINUS_CHAR: ClassVar[int] + COMMA_CHAR: ClassVar[int] + DOT_CHAR: ClassVar[int] + ZERO_CHAR: ClassVar[int] + MIN_LENGTH: ClassVar[int] + MAX_LENGTH: ClassVar[int] + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class GeneralizedTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): ... +class UTCTimeEncoder(TimeEncoderMixIn, encoder.OctetStringEncoder): ... + +class SetOfEncoder(encoder.SequenceOfEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceOfEncoder(encoder.SequenceOfEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SetEncoder(encoder.SequenceEncoder): + def encodeValue(self, value, asn1Spec, encodeFun, **options): ... + +class SequenceEncoder(encoder.SequenceEncoder): + omitEmptyOptionals: bool + +TAG_MAP: dict[TagSet, encoder.AbstractItemEncoder] +TYPE_MAP: dict[int, encoder.AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder(encoder.SingleItemEncoder): + fixedDefLengthMode: bool + fixedChunkSize: int + + TAG_MAP: dict[TagSet, encoder.AbstractItemEncoder] + TYPE_MAP: dict[int, encoder.AbstractItemEncoder] + +class Encoder(encoder.Encoder): + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/der/__init__.pyi b/stubs/pyasn1/pyasn1/codec/der/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/der/decoder.pyi b/stubs/pyasn1/pyasn1/codec/der/decoder.pyi new file mode 100644 index 000000000000..042470f21b68 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/der/decoder.pyi @@ -0,0 +1,33 @@ +from pyasn1.codec.ber.decoder import AbstractPayloadDecoder +from pyasn1.codec.cer import decoder +from pyasn1.type.tag import TagSet + +__all__ = ["decode", "StreamingDecoder"] + +class BitStringPayloadDecoder(decoder.BitStringPayloadDecoder): + supportConstructedForm: bool + +class OctetStringPayloadDecoder(decoder.OctetStringPayloadDecoder): + supportConstructedForm: bool + +RealPayloadDecoder = decoder.RealPayloadDecoder + +TAG_MAP: dict[TagSet, AbstractPayloadDecoder] +TYPE_MAP: dict[int, AbstractPayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder(decoder.SingleItemDecoder): + TAG_MAP: dict[TagSet, AbstractPayloadDecoder] + TYPE_MAP: dict[int, AbstractPayloadDecoder] + + supportIndefLength: bool + +class StreamingDecoder(decoder.StreamingDecoder): + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + +class Decoder(decoder.Decoder): + STREAMING_DECODER: type[StreamingDecoder] + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/der/encoder.pyi b/stubs/pyasn1/pyasn1/codec/der/encoder.pyi new file mode 100644 index 000000000000..3b1b5a4a6d9e --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/der/encoder.pyi @@ -0,0 +1,25 @@ +from pyasn1.codec.ber.encoder import AbstractItemEncoder +from pyasn1.codec.cer import encoder +from pyasn1.type.tag import TagSet + +__all__ = ["Encoder", "encode"] + +class SetEncoder(encoder.SetEncoder): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder(encoder.SingleItemEncoder): + fixedDefLengthMode: bool + fixedChunkSize: int + + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + +class Encoder(encoder.Encoder): + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + +encode: Encoder diff --git a/stubs/pyasn1/pyasn1/codec/native/__init__.pyi b/stubs/pyasn1/pyasn1/codec/native/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/codec/native/decoder.pyi b/stubs/pyasn1/pyasn1/codec/native/decoder.pyi new file mode 100644 index 000000000000..ecc906bf43b8 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/native/decoder.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable + +from pyasn1.type.tag import TagSet + +__all__ = ["decode"] + +class AbstractScalarPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Unused = None, **options): ... + +class BitStringPayloadDecoder(AbstractScalarPayloadDecoder): + def __call__(self, pyObject, asn1Spec, decodeFun: Unused = None, **options): ... + +class SequenceOrSetPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +class SequenceOfOrSetOfPayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +class ChoicePayloadDecoder: + def __call__(self, pyObject, asn1Spec, decodeFun: Callable[..., Incomplete] | None = None, **options): ... + +TAG_MAP: dict[TagSet, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] +TYPE_MAP: dict[int, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemDecoder: + TAG_MAP: dict[TagSet, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] + TYPE_MAP: dict[int, AbstractScalarPayloadDecoder | SequenceOrSetPayloadDecoder | ChoicePayloadDecoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec, **options): ... + +class Decoder: + SINGLE_ITEM_DECODER: type[SingleItemDecoder] + + def __init__(self, *, tagMap=..., typeMap=..., **options: Unused) -> None: ... + def __call__(self, pyObject, asn1Spec=None, **kwargs): ... + +decode: Decoder diff --git a/stubs/pyasn1/pyasn1/codec/native/encoder.pyi b/stubs/pyasn1/pyasn1/codec/native/encoder.pyi new file mode 100644 index 000000000000..83abcc3b4a78 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/native/encoder.pyi @@ -0,0 +1,71 @@ +from _typeshed import Unused +from abc import abstractmethod +from collections import OrderedDict + +from pyasn1.type.tag import TagSet + +__all__ = ["encode"] + +class AbstractItemEncoder: + @abstractmethod + def encode(self, value, encodeFun, **options) -> None: ... + +class BooleanEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class IntegerEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class BitStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class OctetStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class TextStringEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class NullEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options) -> None: ... + +class ObjectIdentifierEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class RealEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class SetEncoder(AbstractItemEncoder): + protoDict = dict + def encode(self, value, encodeFun, **options): ... + +class SequenceEncoder(SetEncoder): + protoDict = OrderedDict + +class SequenceOfEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +class ChoiceEncoder(SequenceEncoder): ... + +class AnyEncoder(AbstractItemEncoder): + def encode(self, value, encodeFun, **options): ... + +TAG_MAP: dict[TagSet, AbstractItemEncoder] +TYPE_MAP: dict[int, AbstractItemEncoder] +# deprecated aliases +tagMap = TAG_MAP +typeMap = TYPE_MAP + +class SingleItemEncoder: + TAG_MAP: dict[TagSet, AbstractItemEncoder] + TYPE_MAP: dict[int, AbstractItemEncoder] + + def __init__(self, tagMap=..., typeMap=..., **ignored: Unused) -> None: ... + def __call__(self, value, **options): ... + +class Encoder: + SINGLE_ITEM_ENCODER: type[SingleItemEncoder] + + def __init__(self, *, tagMap=..., typeMap=..., **options: Unused): ... + def __call__(self, pyObject, asn1Spec=None, **options): ... + +encode: SingleItemEncoder diff --git a/stubs/pyasn1/pyasn1/codec/streaming.pyi b/stubs/pyasn1/pyasn1/codec/streaming.pyi new file mode 100644 index 000000000000..b9ff83bec767 --- /dev/null +++ b/stubs/pyasn1/pyasn1/codec/streaming.pyi @@ -0,0 +1,21 @@ +import io +from _typeshed import Incomplete +from collections.abc import Generator + +from pyasn1 import error as error +from pyasn1.type import univ as univ + +class CachingStreamWrapper(io.IOBase): + def __init__(self, raw) -> None: ... + def peek(self, n): ... + def seekable(self): ... + def seek(self, n: int = -1, whence=0): ... + def read(self, n: int = -1): ... + @property + def markedPosition(self): ... + def tell(self): ... + +def asSeekableStream(substrate): ... +def isEndOfStream(substrate) -> Generator[Incomplete]: ... +def peekIntoStream(substrate, size: int = -1) -> Generator[Incomplete]: ... +def readFromStream(substrate, size: int = -1, context=None) -> Generator[Incomplete]: ... diff --git a/stubs/pyasn1/pyasn1/compat/__init__.pyi b/stubs/pyasn1/pyasn1/compat/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/compat/integer.pyi b/stubs/pyasn1/pyasn1/compat/integer.pyi new file mode 100644 index 000000000000..ecc0e4208a9a --- /dev/null +++ b/stubs/pyasn1/pyasn1/compat/integer.pyi @@ -0,0 +1 @@ +def to_bytes(value: int, signed: bool = False, length: int = 0) -> bytes: ... diff --git a/stubs/pyasn1/pyasn1/debug.pyi b/stubs/pyasn1/pyasn1/debug.pyi new file mode 100644 index 000000000000..b0060f42bcb4 --- /dev/null +++ b/stubs/pyasn1/pyasn1/debug.pyi @@ -0,0 +1,28 @@ +import logging +from typing import TextIO + +__all__ = ["Debug", "setLogger", "hexdump"] + +class Printer: + def __init__( + self, + logger: logging.Logger | None = None, + handler: logging.StreamHandler[TextIO] | None = None, + formatter: logging.Formatter | None = None, + ) -> None: ... + def __call__(self, msg) -> None: ... + +class Debug: + defaultPrinter: Printer + def __init__(self, *flags, **options) -> None: ... + def __call__(self, msg) -> None: ... + def __and__(self, flag): ... + def __rand__(self, flag): ... + +def setLogger(userLogger) -> None: ... +def hexdump(octets): ... + +class Scope: + def __init__(self) -> None: ... + def push(self, token) -> None: ... + def pop(self): ... diff --git a/stubs/pyasn1/pyasn1/error.pyi b/stubs/pyasn1/pyasn1/error.pyi new file mode 100644 index 000000000000..2625bb2cdc06 --- /dev/null +++ b/stubs/pyasn1/pyasn1/error.pyi @@ -0,0 +1,15 @@ +class PyAsn1Error(Exception): + def __init__(self, *args, **kwargs) -> None: ... + @property + def context(self): ... + +class ValueConstraintError(PyAsn1Error): ... +class SubstrateUnderrunError(PyAsn1Error): ... +class EndOfStreamError(SubstrateUnderrunError): ... +class UnsupportedSubstrateError(PyAsn1Error): ... + +class PyAsn1UnicodeError(PyAsn1Error, UnicodeError): + def __init__(self, message, unicode_error: UnicodeError | None = None) -> None: ... + +class PyAsn1UnicodeDecodeError(PyAsn1UnicodeError, UnicodeDecodeError): ... +class PyAsn1UnicodeEncodeError(PyAsn1UnicodeError, UnicodeEncodeError): ... diff --git a/stubs/pyasn1/pyasn1/type/__init__.pyi b/stubs/pyasn1/pyasn1/type/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyasn1/pyasn1/type/base.pyi b/stubs/pyasn1/pyasn1/type/base.pyi new file mode 100644 index 000000000000..0e2da760e4e4 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/base.pyi @@ -0,0 +1,151 @@ +from _typeshed import Incomplete, Unused +from typing import final, type_check_only +from typing_extensions import Never + +from pyasn1.type import constraint, namedtype +from pyasn1.type.tag import TagSet + +__all__ = ["Asn1Item", "Asn1Type", "SimpleAsn1Type", "ConstructedAsn1Type"] + +class Asn1Item: + @classmethod + def getTypeId(cls, increment: int = 1): ... + +class Asn1Type(Asn1Item): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int | None + def __init__(self, **kwargs) -> None: ... + def __setattr__(self, name, value) -> None: ... + @property + def readOnly(self): ... + @property + def effectiveTagSet(self): ... + @property + def tagMap(self): ... + def isSameTypeWith(self, other, matchTags: bool = True, matchConstraints: bool = True): ... + def isSuperTypeOf(self, other, matchTags: bool = True, matchConstraints: bool = True): ... + @staticmethod + def isNoValue(*values): ... + def prettyPrint(self, scope: int = 0) -> None: ... + def getTagSet(self): ... + def getEffectiveTagSet(self): ... + def getTagMap(self): ... + def getSubtypeSpec(self): ... + def hasValue(self): ... + +Asn1ItemBase = Asn1Type + +@final +class NoValue: + skipMethods: set[str] + def __new__(cls): ... + def __getattr__(self, attr) -> None: ... + # def __new__..getPlug..plug + @type_check_only + def plug(self, *args: Unused, **kw: Unused) -> Never: ... + # Magic methods assigned dynamically, priority from right to left: plug < str < int < list < dict + __abs__ = int.__abs__ + __add__ = list.__add__ + __and__ = int.__and__ + __bool__ = int.__bool__ + __ceil__ = int.__ceil__ + __class_getitem__ = plug + __contains__ = dict.__contains__ + __delitem__ = dict.__delitem__ + __dir__ = plug + __divmod__ = int.__divmod__ + __float__ = int.__float__ + __floor__ = int.__floor__ + __floordiv__ = int.__floordiv__ + __ge__ = list.__ge__ + __getitem__ = dict.__getitem__ + __gt__ = list.__gt__ + __iadd__ = list.__iadd__ + __imul__ = list.__imul__ + __index__ = int.__index__ + # self instead of cls + __init_subclass__ = plug # pyright: ignore[reportAssignmentType] + __int__ = int.__int__ + __invert__ = int.__invert__ + __ior__ = plug + __iter__ = dict.__iter__ + __le__ = list.__le__ + __len__ = dict.__len__ + __lshift__ = int.__lshift__ + __lt__ = list.__lt__ + __mod__ = int.__mod__ + __mul__ = list.__mul__ + __neg__ = int.__neg__ + __or__ = int.__or__ + __pos__ = int.__pos__ + __pow__ = int.__pow__ + __radd__ = int.__radd__ + __rand__ = int.__rand__ + __rdivmod__ = int.__rdivmod__ + __reversed__ = list.__reversed__ + __rfloordiv__ = int.__rfloordiv__ + __rlshift__ = int.__rlshift__ + __rmod__ = int.__rmod__ + __rmul__ = list.__rmul__ + __ror__ = int.__ror__ + __round__ = int.__round__ + __rpow__ = int.__rpow__ + __rrshift__ = int.__rrshift__ + __rshift__ = int.__rshift__ + __rsub__ = int.__rsub__ + __rtruediv__ = int.__rtruediv__ + __rxor__ = int.__rxor__ + __setitem__ = list.__setitem__ + __str__ = plug + __sub__ = int.__sub__ + __truediv__ = int.__truediv__ + __trunc__ = int.__trunc__ + __xor__ = int.__xor__ + +class SimpleAsn1Type(Asn1Type): + defaultValue: Incomplete | NoValue + def __init__(self, value=..., **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __hash__(self): ... + @property + def isValue(self): ... + def clone(self, value=..., **kwargs): ... + def subtype(self, value=..., **kwargs): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + +AbstractSimpleAsn1Item = SimpleAsn1Type + +class ConstructedAsn1Type(Asn1Type): + strictConstraints: bool + componentType: namedtype.NamedTypes | Asn1Type | None + sizeSpec: constraint.ConstraintsIntersection + def __init__(self, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + @property + def components(self) -> None: ... + def clone(self, **kwargs): ... + def subtype(self, **kwargs): ... + def getComponentByPosition(self, idx) -> None: ... + def setComponentByPosition(self, idx, value, verifyConstraints: bool = True) -> None: ... + def setComponents(self, *args, **kwargs): ... + def setDefaultComponents(self) -> None: ... + def getComponentType(self): ... + def verifySizeSpec(self) -> None: ... + +AbstractConstructedAsn1Item = ConstructedAsn1Type diff --git a/stubs/pyasn1/pyasn1/type/char.pyi b/stubs/pyasn1/pyasn1/type/char.pyi new file mode 100644 index 000000000000..8791c07abcfb --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/char.pyi @@ -0,0 +1,88 @@ +from pyasn1.type import univ +from pyasn1.type.tag import TagSet + +__all__ = [ + "NumericString", + "PrintableString", + "TeletexString", + "T61String", + "VideotexString", + "IA5String", + "GraphicString", + "VisibleString", + "ISO646String", + "GeneralString", + "UniversalString", + "BMPString", + "UTF8String", +] + +class AbstractCharacterString(univ.OctetString): + def __bytes__(self) -> bytes: ... + def prettyIn(self, value): ... + def asOctets(self, padding: bool = True): ... + def asNumbers(self, padding: bool = True): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + def __reversed__(self): ... + +class NumericString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class PrintableString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class TeletexString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class T61String(TeletexString): + typeId: int + +class VideotexString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class IA5String(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class GraphicString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class VisibleString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class ISO646String(VisibleString): + typeId: int + +class GeneralString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class UniversalString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class BMPString(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int + +class UTF8String(AbstractCharacterString): + tagSet: TagSet + encoding: str + typeId: int diff --git a/stubs/pyasn1/pyasn1/type/constraint.pyi b/stubs/pyasn1/pyasn1/type/constraint.pyi new file mode 100644 index 000000000000..df8d2c55806b --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/constraint.pyi @@ -0,0 +1,52 @@ +__all__ = [ + "SingleValueConstraint", + "ContainedSubtypeConstraint", + "ValueRangeConstraint", + "ValueSizeConstraint", + "PermittedAlphabetConstraint", + "InnerTypeConstraint", + "ConstraintsExclusion", + "ConstraintsIntersection", + "ConstraintsUnion", +] + +class AbstractConstraint: + def __init__(self, *values) -> None: ... + def __call__(self, value, idx: int | None = None) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __hash__(self): ... + def getValueMap(self): ... + def isSuperTypeOf(self, otherConstraint): ... + def isSubTypeOf(self, otherConstraint): ... + +class SingleValueConstraint(AbstractConstraint): + def __contains__(self, item) -> bool: ... + def __iter__(self): ... + def __add__(self, constraint): ... + def __sub__(self, constraint): ... + +class ContainedSubtypeConstraint(AbstractConstraint): ... +class ValueRangeConstraint(AbstractConstraint): ... +class ValueSizeConstraint(ValueRangeConstraint): ... +class PermittedAlphabetConstraint(SingleValueConstraint): ... +class ComponentPresentConstraint(AbstractConstraint): ... +class ComponentAbsentConstraint(AbstractConstraint): ... +class WithComponentsConstraint(AbstractConstraint): ... +class InnerTypeConstraint(AbstractConstraint): ... +class ConstraintsExclusion(AbstractConstraint): ... + +class AbstractConstraintSet(AbstractConstraint): + def __getitem__(self, idx): ... + def __iter__(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __len__(self) -> int: ... + +class ConstraintsIntersection(AbstractConstraintSet): ... +class ConstraintsUnion(AbstractConstraintSet): ... diff --git a/stubs/pyasn1/pyasn1/type/error.pyi b/stubs/pyasn1/pyasn1/type/error.pyi new file mode 100644 index 000000000000..b2562205991b --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/error.pyi @@ -0,0 +1,3 @@ +from pyasn1.error import PyAsn1Error + +class ValueConstraintError(PyAsn1Error): ... diff --git a/stubs/pyasn1/pyasn1/type/namedtype.pyi b/stubs/pyasn1/pyasn1/type/namedtype.pyi new file mode 100644 index 000000000000..c8d12b5de381 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/namedtype.pyi @@ -0,0 +1,73 @@ +__all__ = ["NamedType", "OptionalNamedType", "DefaultedNamedType", "NamedTypes"] + +class NamedType: + isOptional: bool + isDefaulted: bool + def __init__(self, name, asn1Object, openType: type | None = None) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __iter__(self): ... + @property + def name(self): ... + @property + def asn1Object(self): ... + @property + def openType(self): ... + def getName(self): ... + def getType(self): ... + +class OptionalNamedType(NamedType): + isOptional: bool + +class DefaultedNamedType(NamedType): + isDefaulted: bool + +class NamedTypes: + def __init__(self, *namedTypes, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def values(self): ... + def keys(self): ... + def items(self): ... + def clone(self): ... + + class PostponedError: + def __init__(self, errorMsg) -> None: ... + def __getitem__(self, item) -> None: ... + + def getTypeByPosition(self, idx): ... + def getPositionByType(self, tagSet): ... + def getNameByPosition(self, idx): ... + def getPositionByName(self, name): ... + def getTagMapNearPosition(self, idx): ... + def getPositionNearType(self, tagSet, idx): ... + @property + def minTagSet(self): ... + @property + def tagMap(self): ... + @property + def tagMapUnique(self): ... + @property + def hasOptionalOrDefault(self): ... + @property + def hasOpenTypes(self): ... + @property + def namedTypes(self): ... + @property + def requiredComponents(self): ... diff --git a/stubs/pyasn1/pyasn1/type/namedval.pyi b/stubs/pyasn1/pyasn1/type/namedval.pyi new file mode 100644 index 000000000000..1f638b960f6d --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/namedval.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +__all__ = ["NamedValues"] + +class NamedValues: + def __init__(self, *args, **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, key): ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def values(self): ... + def keys(self): ... + def items(self) -> Generator[Incomplete]: ... + def __add__(self, namedValues): ... + def clone(self, *args, **kwargs): ... + def getName(self, value): ... + def getValue(self, name): ... + def getValues(self, *names): ... diff --git a/stubs/pyasn1/pyasn1/type/opentype.pyi b/stubs/pyasn1/pyasn1/type/opentype.pyi new file mode 100644 index 000000000000..8317aa0dbf9c --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/opentype.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Mapping + +from pyasn1.type.base import Asn1Type + +__all__ = ["OpenType"] + +class OpenType: + def __init__(self, name, typeMap: Mapping[Incomplete, Asn1Type] | None = None) -> None: ... + @property + def name(self): ... + def values(self): ... + def keys(self): ... + def items(self): ... + def __contains__(self, key) -> bool: ... + def __getitem__(self, key): ... + def __iter__(self): ... diff --git a/stubs/pyasn1/pyasn1/type/tag.pyi b/stubs/pyasn1/pyasn1/type/tag.pyi new file mode 100644 index 000000000000..15d26de05087 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/tag.pyi @@ -0,0 +1,64 @@ +__all__ = [ + "tagClassUniversal", + "tagClassApplication", + "tagClassContext", + "tagClassPrivate", + "tagFormatSimple", + "tagFormatConstructed", + "tagCategoryImplicit", + "tagCategoryExplicit", + "tagCategoryUntagged", + "Tag", + "TagSet", +] +tagClassUniversal: int +tagClassApplication: int +tagClassContext: int +tagClassPrivate: int +tagFormatSimple: int +tagFormatConstructed: int +tagCategoryImplicit: int +tagCategoryExplicit: int +tagCategoryUntagged: int + +class Tag: + def __init__(self, tagClass, tagFormat, tagId) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __getitem__(self, idx): ... + def __iter__(self): ... + def __and__(self, otherTag): ... + def __or__(self, otherTag): ... + @property + def tagClass(self): ... + @property + def tagFormat(self): ... + @property + def tagId(self): ... + +class TagSet: + def __init__(self, baseTag=(), *superTags) -> None: ... + def __add__(self, superTag): ... + def __radd__(self, superTag): ... + def __getitem__(self, i): ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __hash__(self): ... + def __len__(self) -> int: ... + @property + def baseTag(self): ... + @property + def superTags(self): ... + def tagExplicitly(self, superTag): ... + def tagImplicitly(self, superTag): ... + def isSuperTagSetOf(self, tagSet): ... + def getBaseTag(self): ... diff --git a/stubs/pyasn1/pyasn1/type/tagmap.pyi b/stubs/pyasn1/pyasn1/type/tagmap.pyi new file mode 100644 index 000000000000..b842e0a4a5c1 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/tagmap.pyi @@ -0,0 +1,25 @@ +from collections.abc import Container, Mapping + +from pyasn1.type.base import Asn1Type + +__all__ = ["TagMap"] + +class TagMap: + def __init__( + self, + presentTypes: Mapping[TagMap, Asn1Type] | None = None, + skipTypes: Container[TagMap] | None = None, + defaultType: Asn1Type | None = None, + ) -> None: ... + def __contains__(self, tagSet) -> bool: ... + def __getitem__(self, tagSet): ... + def __iter__(self): ... + @property + def presentTypes(self): ... + @property + def skipTypes(self): ... + @property + def defaultType(self): ... + def getPosMap(self): ... + def getNegMap(self): ... + def getDef(self): ... diff --git a/stubs/pyasn1/pyasn1/type/univ.pyi b/stubs/pyasn1/pyasn1/type/univ.pyi new file mode 100644 index 000000000000..ad2a65391381 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/univ.pyi @@ -0,0 +1,398 @@ +from _typeshed import ConvertibleToInt, Incomplete, SupportsRichComparison +from collections.abc import Callable, Generator +from typing_extensions import Self + +from pyasn1.type import base, constraint, namedtype, namedval +from pyasn1.type.tag import TagSet + +__all__ = [ + "Integer", + "Boolean", + "BitString", + "OctetString", + "Null", + "ObjectIdentifier", + "Real", + "Enumerated", + "SequenceOfAndSetOfBase", + "SequenceOf", + "SetOf", + "SequenceAndSetBase", + "Sequence", + "Set", + "Choice", + "Any", + "NoValue", + "noValue", +] + +NoValue = base.NoValue +noValue: NoValue + +class Integer(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + def __init__(self, value=..., **kwargs) -> None: ... + def __and__(self, value): ... + def __rand__(self, value): ... + def __or__(self, value): ... + def __ror__(self, value): ... + def __xor__(self, value): ... + def __rxor__(self, value): ... + def __lshift__(self, value): ... + def __rshift__(self, value): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __sub__(self, value): ... + def __rsub__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __mod__(self, value): ... + def __rmod__(self, value): ... + # Accepts everything builtins.pow does + def __pow__(self, value: complex, modulo: int | None = None) -> Self: ... + def __rpow__(self, value): ... + def __floordiv__(self, value): ... + def __rfloordiv__(self, value): ... + def __truediv__(self, value): ... + def __rtruediv__(self, value): ... + def __divmod__(self, value): ... + def __rdivmod__(self, value): ... + __hash__ = base.SimpleAsn1Type.__hash__ + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self): ... + def __index__(self) -> int: ... + def __pos__(self): ... + def __neg__(self): ... + def __invert__(self): ... + def __round__(self, n: int = 0): ... + def __floor__(self): ... + def __ceil__(self): ... + def __trunc__(self): ... + def __lt__(self, value): ... + def __le__(self, value): ... + def __eq__(self, value): ... + def __ne__(self, value): ... + def __gt__(self, value): ... + def __ge__(self, value): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + def getNamedValues(self): ... + +class Boolean(Integer): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + +class SizedInteger(int): + bitLength: int | None + leadingZeroBits: int | None + def setBitLength(self, bitLength): ... + def __len__(self) -> int: ... + +class BitString(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + namedValues: namedval.NamedValues + typeId: int + defaultBinValue: str | base.NoValue + defaultHexValue: str | base.NoValue + def __init__(self, value=..., **kwargs) -> None: ... + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __reversed__(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __lshift__(self, count): ... + def __rshift__(self, count): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def asNumbers(self): ... + def asOctets(self): ... + def asInteger(self): ... + def asBinary(self): ... + @classmethod + def fromHexString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None): ... + @classmethod + def fromBinaryString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None): ... + @classmethod + def fromOctetString(cls, value, internalFormat: bool = False, prepend: ConvertibleToInt | None = None, padding: int = 0): ... + def prettyIn(self, value): ... + +class OctetString(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + defaultBinValue: str | base.NoValue + defaultHexValue: str | base.NoValue + encoding: str + def __init__(self, value=..., **kwargs) -> None: ... + def prettyIn(self, value): ... + def __bytes__(self) -> bytes: ... + def asOctets(self): ... + def asNumbers(self): ... + def prettyOut(self, value): ... + def prettyPrint(self, scope: int = 0): ... + @staticmethod + def fromBinaryString(value): ... + @staticmethod + def fromHexString(value): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, value) -> bool: ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __reversed__(self): ... + +class Null(OctetString): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def prettyIn(self, value): ... + +class ObjectIdentifier(base.SimpleAsn1Type): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def __add__(self, other): ... + def __radd__(self, other): ... + def asTuple(self): ... + def __len__(self) -> int: ... + def __getitem__(self, i): ... + def __iter__(self): ... + def __contains__(self, value) -> bool: ... + def index(self, suboid): ... + def isPrefixOf(self, other): ... + def prettyIn(self, value): ... + def prettyOut(self, value): ... + +class Real(base.SimpleAsn1Type): + binEncBase: int | None + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def prettyIn(self, value): ... + def prettyPrint(self, scope: int = 0): ... + @property + def isPlusInf(self): ... + @property + def isMinusInf(self): ... + @property + def isInf(self): ... + def __add__(self, value): ... + def __radd__(self, value): ... + def __mul__(self, value): ... + def __rmul__(self, value): ... + def __sub__(self, value): ... + def __rsub__(self, value): ... + def __mod__(self, value): ... + def __rmod__(self, value): ... + # Accepts everything builtins.pow with a float base does + def __pow__(self, value: complex, modulo: int | None = None) -> Self: ... + def __rpow__(self, value): ... + def __truediv__(self, value): ... + def __rtruediv__(self, value): ... + def __divmod__(self, value): ... + def __rdivmod__(self, value): ... + def __int__(self) -> int: ... + def __float__(self) -> float: ... + def __abs__(self): ... + def __pos__(self): ... + def __neg__(self): ... + def __round__(self, n: int = 0): ... + def __floor__(self): ... + def __ceil__(self): ... + def __trunc__(self): ... + def __lt__(self, value): ... + def __le__(self, value): ... + def __eq__(self, value): ... + def __ne__(self, value): ... + def __gt__(self, value): ... + def __ge__(self, value): ... + def __bool__(self) -> bool: ... + __hash__ = base.SimpleAsn1Type.__hash__ + def __getitem__(self, idx): ... + def isPlusInfinity(self): ... + def isMinusInfinity(self): ... + def isInfinity(self): ... + +class Enumerated(Integer): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + namedValues: namedval.NamedValues + +class SequenceOfAndSetOfBase(base.ConstructedAsn1Type): + componentType: base.Asn1Type | None + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + def __init__( + self, + *args, + componentType: base.Asn1Type | None = ..., + tagSet: TagSet = ..., + subtypeSpec: constraint.ConstraintsIntersection = ..., + ) -> None: ... + def __getitem__(self, idx): ... + def __setitem__(self, idx, value) -> None: ... + def append(self, value) -> None: ... + def count(self, value): ... + def extend(self, values) -> None: ... + def index(self, value, start: int = 0, stop: int | None = None): ... + def reverse(self) -> None: ... + def sort(self, key: Callable[[Incomplete], SupportsRichComparison] | None = None, reverse: bool = False) -> None: ... + def __len__(self) -> int: ... + def __iter__(self): ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def componentTagMap(self): ... + @property + def components(self): ... + def clear(self): ... + def reset(self): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + @property + def isValue(self): ... + @property + def isInconsistent(self): ... + +class SequenceOf(SequenceOfAndSetOfBase): + typeId: int + +class SetOf(SequenceOfAndSetOfBase): + typeId: int + +class SequenceAndSetBase(base.ConstructedAsn1Type): + componentType: namedtype.NamedTypes + + class DynamicNames: + def __init__(self) -> None: ... + def __len__(self) -> int: ... + def __contains__(self, item) -> bool: ... + def __iter__(self): ... + def __getitem__(self, item): ... + def getNameByPosition(self, idx): ... + def getPositionByName(self, name): ... + def addField(self, idx) -> None: ... + + def __init__(self, **kwargs) -> None: ... + def __getitem__(self, idx): ... + def __setitem__(self, idx, value) -> None: ... + def __contains__(self, key) -> bool: ... + def __len__(self) -> int: ... + def __iter__(self): ... + def values(self) -> Generator[Incomplete]: ... + def keys(self): ... + def items(self) -> Generator[Incomplete]: ... + def update(self, *iterValue, **mappingValue) -> None: ... + def clear(self): ... + def reset(self): ... + @property + def components(self): ... + def getComponentByName(self, name, default=..., instantiate: bool = True): ... + def setComponentByName( + self, name, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def isValue(self): ... + @property + def isInconsistent(self): ... + def prettyPrint(self, scope: int = 0): ... + def prettyPrintType(self, scope: int = 0): ... + def setDefaultComponents(self): ... + def getComponentType(self): ... + def getNameByPosition(self, idx): ... + +class Sequence(SequenceAndSetBase): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + componentType: namedtype.NamedTypes + typeId: int + def getComponentTagMapNearPosition(self, idx): ... + def getComponentPositionNearType(self, tagSet, idx): ... + +class Set(SequenceAndSetBase): + tagSet: TagSet + componentType: namedtype.NamedTypes + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def getComponent(self, innerFlag: bool = False): ... + def getComponentByType(self, tagSet, default=..., instantiate: bool = True, innerFlag: bool = False): ... + def setComponentByType( + self, + tagSet, + value=..., + verifyConstraints: bool = True, + matchTags: bool = True, + matchConstraints: bool = True, + innerFlag: bool = False, + ): ... + @property + def componentTagMap(self): ... + +class Choice(Set): + tagSet: TagSet + componentType: namedtype.NamedTypes + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + def __eq__(self, other): ... + def __ne__(self, other): ... + def __lt__(self, other): ... + def __le__(self, other): ... + def __gt__(self, other): ... + def __ge__(self, other): ... + def __bool__(self) -> bool: ... + def __len__(self) -> int: ... + def __contains__(self, key) -> bool: ... + def __iter__(self): ... + def values(self) -> Generator[Incomplete]: ... + def keys(self) -> Generator[Incomplete]: ... + def items(self) -> Generator[Incomplete]: ... + def checkConsistency(self) -> None: ... + def getComponentByPosition(self, idx, default=..., instantiate: bool = True): ... + def setComponentByPosition( + self, idx, value=..., verifyConstraints: bool = True, matchTags: bool = True, matchConstraints: bool = True + ): ... + @property + def effectiveTagSet(self): ... + @property + def tagMap(self): ... + def getComponent(self, innerFlag: bool = False): ... + def getName(self, innerFlag: bool = False): ... + @property + def isValue(self): ... + def clear(self): ... + def getMinTagSet(self): ... + +class Any(OctetString): + tagSet: TagSet + subtypeSpec: constraint.ConstraintsIntersection + typeId: int + @property + def tagMap(self): ... diff --git a/stubs/pyasn1/pyasn1/type/useful.pyi b/stubs/pyasn1/pyasn1/type/useful.pyi new file mode 100644 index 000000000000..559d7f0847d0 --- /dev/null +++ b/stubs/pyasn1/pyasn1/type/useful.pyi @@ -0,0 +1,31 @@ +import datetime + +from pyasn1.type import char +from pyasn1.type.tag import TagSet + +__all__ = ["ObjectDescriptor", "GeneralizedTime", "UTCTime"] + +class ObjectDescriptor(char.GraphicString): + tagSet: TagSet + typeId: int + +class TimeMixIn: + class FixedOffset(datetime.tzinfo): + def __init__(self, offset: int = 0, name: str = "UTC") -> None: ... + def utcoffset(self, dt): ... + def tzname(self, dt): ... + def dst(self, dt): ... + + UTC: FixedOffset + @property + def asDateTime(self): ... + @classmethod + def fromDateTime(cls, dt): ... + +class GeneralizedTime(char.VisibleString, TimeMixIn): + tagSet: TagSet + typeId: int + +class UTCTime(char.VisibleString, TimeMixIn): + tagSet: TagSet + typeId: int diff --git a/stubs/pyaudio/METADATA.toml b/stubs/pyaudio/METADATA.toml new file mode 100644 index 000000000000..29a84c09f459 --- /dev/null +++ b/stubs/pyaudio/METADATA.toml @@ -0,0 +1,9 @@ +version = "0.2.*" +# There is no web portal for the source, this is the official source link: +# upstream-repository = "https://people.csail.mit.edu/hubert/pyaudio/#sources" + +[tool.stubtest] +# linux and win32 are equivalent +ci-platforms = ["darwin", "linux"] +apt-dependencies = ["portaudio19-dev"] +brew-dependencies = ["portaudio"] diff --git a/stubs/pyaudio/pyaudio.pyi b/stubs/pyaudio/pyaudio.pyi new file mode 100644 index 000000000000..8df1043bb36b --- /dev/null +++ b/stubs/pyaudio/pyaudio.pyi @@ -0,0 +1,178 @@ +import sys +from collections.abc import Callable, Mapping, Sequence +from typing import ClassVar, Final, TypeAlias + +__docformat__: str + +paFloat32: Final[int] +paInt32: Final[int] +paInt24: Final[int] +paInt16: Final[int] +paInt8: Final[int] +paUInt8: Final[int] +paCustomFormat: Final[int] + +paInDevelopment: Final[int] +paDirectSound: Final[int] +paMME: Final[int] +paASIO: Final[int] +paSoundManager: Final[int] +paCoreAudio: Final[int] +paOSS: Final[int] +paALSA: Final[int] +paAL: Final[int] +paBeOS: Final[int] +paWDMKS: Final[int] +paJACK: Final[int] +paWASAPI: Final[int] +paNoDevice: Final[int] + +paNoError: Final[int] +paNotInitialized: Final[int] +paUnanticipatedHostError: Final[int] +paInvalidChannelCount: Final[int] +paInvalidSampleRate: Final[int] +paInvalidDevice: Final[int] +paInvalidFlag: Final[int] +paSampleFormatNotSupported: Final[int] +paBadIODeviceCombination: Final[int] +paInsufficientMemory: Final[int] +paBufferTooBig: Final[int] +paBufferTooSmall: Final[int] +paNullCallback: Final[int] +paBadStreamPtr: Final[int] +paTimedOut: Final[int] +paInternalError: Final[int] +paDeviceUnavailable: Final[int] +paIncompatibleHostApiSpecificStreamInfo: Final[int] +paStreamIsStopped: Final[int] +paStreamIsNotStopped: Final[int] +paInputOverflowed: Final[int] +paOutputUnderflowed: Final[int] +paHostApiNotFound: Final[int] +paInvalidHostApi: Final[int] +paCanNotReadFromACallbackStream: Final[int] +paCanNotWriteToACallbackStream: Final[int] +paCanNotReadFromAnOutputOnlyStream: Final[int] +paCanNotWriteToAnInputOnlyStream: Final[int] +paIncompatibleStreamHostApi: Final[int] + +paContinue: Final[int] +paComplete: Final[int] +paAbort: Final[int] + +paInputUnderflow: Final[int] +paInputOverflow: Final[int] +paOutputUnderflow: Final[int] +paOutputOverflow: Final[int] +paPrimingOutput: Final[int] + +paFramesPerBufferUnspecified: Final[int] + +if sys.platform == "darwin": + class PaMacCoreStreamInfo: + paMacCoreChangeDeviceParameters: Final[int] + paMacCoreFailIfConversionRequired: Final[int] + paMacCoreConversionQualityMin: Final[int] + paMacCoreConversionQualityMedium: Final[int] + paMacCoreConversionQualityLow: Final[int] + paMacCoreConversionQualityHigh: Final[int] + paMacCoreConversionQualityMax: Final[int] + paMacCorePlayNice: Final[int] + paMacCorePro: Final[int] + paMacCoreMinimizeCPUButPlayNice: Final[int] + paMacCoreMinimizeCPU: Final[int] + def __init__(self, flags: int | None = ..., channel_map: _ChannelMap | None = ...) -> None: ... + def get_flags(self) -> int: ... + def get_channel_map(self) -> _ChannelMap | None: ... + + _PaMacCoreStreamInfo: TypeAlias = PaMacCoreStreamInfo +else: + _PaMacCoreStreamInfo: TypeAlias = None + +# Auxiliary types +_ChannelMap: TypeAlias = Sequence[int] +_PaHostApiInfo: TypeAlias = Mapping[str, str | int] +_PaDeviceInfo: TypeAlias = Mapping[str, str | int | float] +_StreamCallback: TypeAlias = Callable[[bytes | None, int, Mapping[str, float], int], tuple[bytes | None, int]] + +def get_format_from_width(width: int, unsigned: bool = ...) -> int: ... +def get_portaudio_version() -> int: ... +def get_portaudio_version_text() -> str: ... +def get_sample_size(format: int) -> int: ... + +class Stream: + def __init__( + self, + PA_manager: PyAudio, + rate: int, + channels: int, + format: int, + input: bool = ..., + output: bool = ..., + input_device_index: int | None = ..., + output_device_index: int | None = ..., + frames_per_buffer: int = ..., + start: bool = ..., + input_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + output_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + stream_callback: _StreamCallback | None = ..., + ) -> None: ... + def close(self) -> None: ... + def get_cpu_load(self) -> float: ... + def get_input_latency(self) -> float: ... + def get_output_latency(self) -> float: ... + def get_read_available(self) -> int: ... + def get_time(self) -> float: ... + def get_write_available(self) -> int: ... + def is_active(self) -> bool: ... + def is_stopped(self) -> bool: ... + def read(self, num_frames: int, exception_on_overflow: bool = ...) -> bytes: ... + def start_stream(self) -> None: ... + def stop_stream(self) -> None: ... + def write(self, frames: bytes, num_frames: int | None = ..., exception_on_underflow: bool = ...) -> None: ... + +# Use an alias to workaround pyright complaints about recursive definitions in the PyAudio class +_Stream = Stream + +class PyAudio: + Stream: ClassVar[type[_Stream]] + def __init__(self) -> None: ... + def close(self, stream: _Stream) -> None: ... + def get_default_host_api_info(self) -> _PaHostApiInfo: ... + def get_default_input_device_info(self) -> _PaDeviceInfo: ... + def get_default_output_device_info(self) -> _PaDeviceInfo: ... + def get_device_count(self) -> int: ... + def get_device_info_by_host_api_device_index(self, host_api_index: int, host_api_device_index: int) -> _PaDeviceInfo: ... + def get_device_info_by_index(self, device_index: int) -> _PaDeviceInfo: ... + def get_format_from_width(self, width: int, unsigned: bool = ...) -> int: ... + def get_host_api_count(self) -> int: ... + def get_host_api_info_by_index(self, host_api_index: int) -> _PaHostApiInfo: ... + def get_host_api_info_by_type(self, host_api_type: int) -> _PaHostApiInfo: ... + def get_sample_size(self, format: int) -> int: ... + def is_format_supported( + self, + rate: int, + input_device: int | None = ..., + input_channels: int | None = ..., + input_format: int | None = ..., + output_device: int | None = ..., + output_channels: int | None = ..., + output_format: int | None = ..., + ) -> bool: ... + def open( + self, + rate: int, + channels: int, + format: int, + input: bool = ..., + output: bool = ..., + input_device_index: int | None = ..., + output_device_index: int | None = ..., + frames_per_buffer: int = ..., + start: bool = ..., + input_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + output_host_api_specific_stream_info: _PaMacCoreStreamInfo | None = ..., + stream_callback: _StreamCallback | None = ..., + ) -> _Stream: ... + def terminate(self) -> None: ... diff --git a/stubs/pycocotools/METADATA.toml b/stubs/pycocotools/METADATA.toml new file mode 100644 index 000000000000..672320ca392c --- /dev/null +++ b/stubs/pycocotools/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.0.*" +upstream-repository = "https://github.com/ppwwyyxx/cocoapi" +dependencies = ["numpy>=2.0.0rc1"] diff --git a/stubs/pycocotools/pycocotools/__init__.pyi b/stubs/pycocotools/pycocotools/__init__.pyi new file mode 100644 index 000000000000..129b5a07c312 --- /dev/null +++ b/stubs/pycocotools/pycocotools/__init__.pyi @@ -0,0 +1,7 @@ +from typing import TypedDict, type_check_only + +# Unused in this module, but imported in multiple submodules. +@type_check_only +class _EncodedRLE(TypedDict): # noqa: Y049 + size: list[int] + counts: str | bytes diff --git a/stubs/pycocotools/pycocotools/coco.pyi b/stubs/pycocotools/pycocotools/coco.pyi new file mode 100644 index 000000000000..6e5af237bddb --- /dev/null +++ b/stubs/pycocotools/pycocotools/coco.pyi @@ -0,0 +1,96 @@ +from collections.abc import Collection, Sequence +from pathlib import Path +from typing import Generic, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only + +import numpy as np +import numpy.typing as npt + +from . import _EncodedRLE + +PYTHON_VERSION: int + +@type_check_only +class _Image(TypedDict): + id: int + width: int + height: int + file_name: str + +_TPolygonSegmentation: TypeAlias = list[list[float]] + +@type_check_only +class _RLE(TypedDict): + size: list[int] + counts: list[int] + +@type_check_only +class _Annotation(TypedDict): + id: int + image_id: int + category_id: int + segmentation: _TPolygonSegmentation | _RLE | _EncodedRLE + area: float + bbox: list[float] + iscrowd: int + +_TSeg = TypeVar("_TSeg", _TPolygonSegmentation, _RLE, _EncodedRLE) + +@type_check_only +class _AnnotationG(TypedDict, Generic[_TSeg]): + id: int + image_id: int + category_id: int + segmentation: _TSeg + area: float + bbox: list[float] + iscrowd: int + +@type_check_only +class _Category(TypedDict): + id: int + name: str + supercategory: str + +@type_check_only +class _Dataset(TypedDict): + images: list[_Image] + annotations: list[_Annotation] + categories: list[_Category] + +class COCO: + anns: dict[int, _Annotation] + dataset: _Dataset + cats: dict[int, _Category] + imgs: dict[int, _Image] + imgToAnns: dict[int, list[_Annotation]] + catToImgs: dict[int, list[int]] + def __init__(self, annotation_file: str | Path | None = None) -> None: ... + def createIndex(self) -> None: ... + def info(self) -> None: ... + def getAnnIds( + self, + imgIds: Collection[int] | int = [], + catIds: Collection[int] | int = [], + areaRng: Sequence[float] = [], + iscrowd: bool | None = None, + ) -> list[int]: ... + def getCatIds( + self, catNms: Collection[str] | str = [], supNms: Collection[str] | str = [], catIds: Collection[int] | int = [] + ) -> list[int]: ... + def getImgIds(self, imgIds: Collection[int] | int = [], catIds: list[int] | int = []) -> list[int]: ... + def loadAnns(self, ids: Collection[int] | int = []) -> list[_Annotation]: ... + def loadCats(self, ids: Collection[int] | int = []) -> list[_Category]: ... + def loadImgs(self, ids: Collection[int] | int = []) -> list[_Image]: ... + def showAnns(self, anns: Sequence[_Annotation], draw_bbox: bool = False) -> None: ... + def loadRes(self, resFile: str) -> COCO: ... + def download(self, tarDir: str | None = None, imgIds: Collection[int] = []) -> Literal[-1] | None: ... + def loadNumpyAnnotations(self, data: npt.NDArray[np.float64]) -> list[_Annotation]: ... + + @overload + def annToRLE(self, ann: _AnnotationG[_RLE]) -> _RLE: ... + @overload + def annToRLE(self, ann: _AnnotationG[_EncodedRLE]) -> _EncodedRLE: ... + @overload + def annToRLE(self, ann: _AnnotationG[_TPolygonSegmentation]) -> _EncodedRLE: ... + + def annToMask(self, ann: _Annotation) -> npt.NDArray[np.uint8]: ... diff --git a/stubs/pycocotools/pycocotools/cocoeval.pyi b/stubs/pycocotools/pycocotools/cocoeval.pyi new file mode 100644 index 000000000000..ab763578101a --- /dev/null +++ b/stubs/pycocotools/pycocotools/cocoeval.pyi @@ -0,0 +1,64 @@ +from typing import Literal, TypeAlias, TypedDict, type_check_only + +import numpy as np +import numpy.typing as npt + +from .coco import COCO + +_NDFloatArray: TypeAlias = npt.NDArray[np.float64] +_TIOU: TypeAlias = Literal["segm", "bbox", "keypoints"] + +@type_check_only +class _ImageEvaluationResult(TypedDict): + image_id: int + category_id: int + aRng: list[int] + maxDet: int + dtIds: list[int] + gtIds: list[int] + dtMatches: _NDFloatArray + gtMatches: _NDFloatArray + dtScores: list[float] + gtIgnore: _NDFloatArray + dtIgnore: _NDFloatArray + +@type_check_only +class _EvaluationResult(TypedDict): + params: Params + counts: list[int] + date: str + precision: _NDFloatArray + recall: _NDFloatArray + scores: _NDFloatArray + +class COCOeval: + cocoGt: COCO + cocoDt: COCO + evalImgs: list[_ImageEvaluationResult] + eval: _EvaluationResult + params: Params + stats: _NDFloatArray + ious: dict[tuple[int, int], list[float]] + def __init__(self, cocoGt: COCO | None = None, cocoDt: COCO | None = None, iouType: _TIOU = "segm") -> None: ... + def evaluate(self) -> None: ... + def computeIoU(self, imgId: int, catId: int) -> list[float]: ... + def computeOks(self, imgId: int, catId: int) -> _NDFloatArray: ... + def evaluateImg(self, imgId: int, catId: int, aRng: list[int], maxDet: int) -> _ImageEvaluationResult: ... + def accumulate(self, p: Params | None = None) -> None: ... + def summarize(self) -> None: ... + +class Params: + imgIds: list[int] + catIds: list[int] + iouThrs: _NDFloatArray + recThrs: _NDFloatArray + maxDets: list[int] + areaRng: list[list[float]] + areaRngLbl: list[str] + useCats: int + kpt_oks_sigmas: _NDFloatArray + iouType: _TIOU + useSegm: int | None + def __init__(self, iouType: _TIOU = "segm") -> None: ... + def setDetParams(self) -> None: ... + def setKpParams(self) -> None: ... diff --git a/stubs/pycocotools/pycocotools/mask.pyi b/stubs/pycocotools/pycocotools/mask.pyi new file mode 100644 index 000000000000..84e85c3bf215 --- /dev/null +++ b/stubs/pycocotools/pycocotools/mask.pyi @@ -0,0 +1,29 @@ +from typing import Any, TypeAlias, overload + +import numpy as np +import numpy.typing as npt + +from . import _EncodedRLE + +_NPUInt32: TypeAlias = np.uint32 +_NDArrayUInt8: TypeAlias = npt.NDArray[np.uint8] +_NDArrayUInt32: TypeAlias = npt.NDArray[np.uint32] +_NDArrayFloat64: TypeAlias = npt.NDArray[np.float64] + +def iou( + dt: _NDArrayUInt32 | list[float] | list[_EncodedRLE], + gt: _NDArrayUInt32 | list[float] | list[_EncodedRLE], + pyiscrowd: list[int] | _NDArrayUInt8, +) -> list[Any] | _NDArrayFloat64: ... +def merge(rleObjs: list[_EncodedRLE], intersect: int = 0) -> _EncodedRLE: ... + +# ignore an "overlapping overloads" error due to _NDArrayInt32 being an alias for `Incomplete` for now +@overload +def frPyObjects(pyobj: _NDArrayUInt32 | list[list[int]] | list[_EncodedRLE], h: int, w: int) -> list[_EncodedRLE]: ... +@overload +def frPyObjects(pyobj: list[int] | _EncodedRLE, h: int, w: int) -> _EncodedRLE: ... + +def encode(bimask: _NDArrayUInt8) -> _EncodedRLE: ... +def decode(rleObjs: _EncodedRLE) -> _NDArrayUInt8: ... +def area(rleObjs: _EncodedRLE) -> _NPUInt32: ... +def toBbox(rleObjs: _EncodedRLE) -> _NDArrayFloat64: ... diff --git a/stubs/pycups/METADATA.toml b/stubs/pycups/METADATA.toml new file mode 100644 index 000000000000..e8cde2087247 --- /dev/null +++ b/stubs/pycups/METADATA.toml @@ -0,0 +1,5 @@ +version = "2.0.*" +upstream-repository = "https://github.com/OpenPrinting/pycups" + +[tool.stubtest] +apt-dependencies = ["libcups2-dev"] diff --git a/stubs/pycups/cups.pyi b/stubs/pycups/cups.pyi new file mode 100644 index 000000000000..3ccf11bcbd8c --- /dev/null +++ b/stubs/pycups/cups.pyi @@ -0,0 +1,899 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from io import IOBase +from typing import Final, Literal, TypeAlias, TypedDict, TypeVar, final, overload, type_check_only +from typing_extensions import NotRequired + +_T = TypeVar("_T") + +_FileOrFd: TypeAlias = IOBase | int + +_CupsDevice = TypedDict( + "_CupsDevice", + {"device-class": str, "device-info": str, "device-make-and-model": str, "device-id": str, "device-location": str}, +) + +_CupsDocument = TypedDict("_CupsDocument", {"file": str, "document-format": NotRequired[str], "document-name": NotRequired[str]}) + +_CupsPPD = TypedDict( + "_CupsPPD", + { + "ppd-natural-language": str, + "ppd-make": str, + "ppd-make-and-model": str, + "ppd-device-id": str, + "ppd-product": str, + "ppd-psversion": str, + "ppd-type": str, + "ppd-model-number": int, + }, +) + +_CupsPPD2 = TypedDict( + "_CupsPPD2", + { + "ppd-natural-language": list[str], + "ppd-make": list[str], + "ppd-make-and-model": list[str], + "ppd-device-id": list[str], + "ppd-product": list[str], + "ppd-psversion": list[str], + "ppd-type": list[str], + "ppd-model-number": list[int], + }, +) + +_CupsJob = TypedDict( + "_CupsJob", + { + "number-of-documents": int, + "job-media-progress": int, + "job-more-info": str, + "job-preserved": bool, + "job-printer-up-time": int, + "job-printer-uri": str, + "job-uri": str, + "printer-uri": str, + "document-format-detected": str, + "document-format": str, + "job-priority": int, + "job-uuid": str, + "date-time-at-completed": str, + "date-time-at-creation": str, + "date-time-at-processing": str, + "time-at-completed": int, + "time-at-creation": int, + "time-at-processing": int, + "job-state": int, + "job-state-reasons": str, + "job-impressions-completed": int, + "job-media-sheets-completed": int, + "job-k-octets": int, + "job-hold-until": str, + "job-sheets": list[str], + "job-printer-state-message": str, + "job-printer-state-reasons": str, + "job-name": str, + "job-originating-user-name": str, + }, +) + +_CupsAttributeInfo = TypedDict( + "_CupsAttributeInfo", {"attributes-charset": str, "attributes-natural-language": str, "job-id": int} +) + +@type_check_only +class _CupsOptionChoice(TypedDict): + choice: str + text: str + marked: bool + +@type_check_only +class _CupsJobWithAttributeInfo(_CupsJob, _CupsAttributeInfo): ... + +_CupsEvent = TypedDict( # noqa: Y049 + "_CupsEvent", + { + "notify-charset": str, + "notify-natural-language": str, + "notify-subscription-id": int, + "notify-sequence-number": int, + "notify-subscribed-event": str, + "printer-up-time": int, + "notify-text": str, + "notify-printer-uri": str, + "printer-name": str, + "printer-state": int, + "printer-state-reasons": list[str], + "printer-is-accepting-jobs": bool, + "notify-job-id": int, + "job-state": int, + "job-name": str, + "job-state-reasons": str, + "job-impressions-completed": int, + }, +) + +_CupsNotifications = TypedDict( + "_CupsNotifications", {"notify-get-interval": int, "printer-up-time": int, "events": list[_CupsEvent]} +) + +_CupsPrinter = TypedDict( + "_CupsPrinter", + { + "marker-change-time": int, + "printer-config-change-date-time": str, + "printer-config-change-time": int, + "printer-current-time": str, + "printer-dns-sd-name": str | None, + "printer-error-policy": str, + "printer-error-policy-supported": list[str], + "printer-icons": str, + "printer-is-accepting-jobs": bool, + "printer-is-shared": bool, + "printer-is-temporary": bool, + "printer-more-info": str, + "printer-op-policy": str, + "printer-state": int, + "printer-state-change-date-time": str, + "printer-state-change-time": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-strings-uri": str, + "printer-type": int, + "printer-up-time": int, + "printer-uri-supported": list[str], + "queued-job-count": int, + "uri-security-supported": list[str], + "uri-authentication-supported": list[str], + "printer-id": int, + "printer-name": str, + "printer-location": str, + "printer-geo-location": str, + "printer-info": str, + "printer-organization": str, + "printer-organizational-unit": str, + "printer-uuid": str, + "job-quota-period": int, + "job-k-limit": int, + "job-page-limit": int, + "job-sheets-default": tuple[str, str], + "device-uri": str, + "document-format-supported": list[str], + "copies-default": int, + "document-format-default": str, + "job-cancel-after-default": int, + "job-hold-until-default": str, + "job-priority-default": int, + "number-up-default": int, + "notify-lease-duration-default": int, + "notify-events-default": list[str], + "orientation-requested-default": int | None, + "print-color-mode-default": str, + "print-quality-default": int, + "copies-supported": tuple[int, int], + "ipp-features-supported": list[str], + "job-creation-attributes-supported": list[str], + "printer-make-and-model": str, + "finishings-supported": list[int], + "finishings-default": int, + "charset-configured": str, + "charset-supported": list[str], + "compression-supported": list[str], + "cups-version": str, + "generated-natural-language-supported": list[str], + "ipp-versions-supported": list[str], + "ippget-event-life": int, + "job-cancel-after-supported": tuple[int, int], + "job-hold-until-supported": list[str], + "job-ids-supported": bool, + "job-k-octets-supported": tuple[int, int], + "job-priority-supported": list[int], + "job-settable-attributes-supported": list[str], + "job-sheets-supported": list[str], + "jpeg-k-octets-supported": tuple[int, int], + "jpeg-x-dimension-supported": tuple[int, int], + "jpeg-y-dimension-supported": tuple[int, int], + "media-col-supported": list[str], + "multiple-document-handling-supported": list[str], + "multiple-document-jobs-supported": bool, + "multiple-operation-time-out": int, + "multiple-operation-time-out-action": str, + "natural-language-configured": str, + "notify-attributes-supported": list[str], + "notify-lease-duration-supported": tuple[int, int], + "notify-max-events-supported": list[int], + "notify-events-supported": list[str], + "notify-pull-method-supported": list[str], + "notify-schemes-supported": list[str], + "number-up-supported": list[int], + "number-up-layout-supported": list[str], + "operations-supported": list[int], + "orientation-requested-supported": list[int], + "page-delivery-supported": list[str], + "page-ranges-supported": bool, + "pdf-k-octets-supported": tuple[int, int], + "pdf-versions-supported": list[str], + "pdl-override-supported": list[str], + "print-scaling-supported": list[str], + "printer-get-attributes-supported": list[str], + "printer-op-policy-supported": list[str], + "printer-settable-attributes-supported": list[str], + "server-is-sharing-printers": bool, + "which-jobs-supported": list[str], + }, +) + +_CupsPrinterSimple = TypedDict( + "_CupsPrinterSimple", + { + "printer-is-shared": bool, + "printer-state": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-type": int, + "printer-uri-supported": str, + "printer-location": str, + "printer-info": str, + "device-uri": str, + "printer-make-and-model": str, + }, +) + +_CupsSubscription = TypedDict( + "_CupsSubscription", + { + "notify-events": list[str], + "notify-lease-duration": int, + "notify-pull-method": NotRequired[str], + "notify-recipient-uri": NotRequired[str], + "notify-subscriber-user-name": str, + "notify-time-interval": int, + "notify-subscription-id": int, + }, +) + +CUPS_DEST_FLAGS_CANCELED: Final[int] +CUPS_DEST_FLAGS_CONNECTING: Final[int] +CUPS_DEST_FLAGS_ERROR: Final[int] +CUPS_DEST_FLAGS_MORE: Final[int] +CUPS_DEST_FLAGS_NONE: Final[int] +CUPS_DEST_FLAGS_REMOVED: Final[int] +CUPS_DEST_FLAGS_RESOLVING: Final[int] +CUPS_DEST_FLAGS_UNCONNECTED: Final[int] +CUPS_FORMAT_AUTO: Final[str] +CUPS_FORMAT_COMMAND: Final[str] +CUPS_FORMAT_PDF: Final[str] +CUPS_FORMAT_POSTSCRIPT: Final[str] +CUPS_FORMAT_RAW: Final[str] +CUPS_FORMAT_TEXT: Final[str] +CUPS_PRINTER_AUTHENTICATED: Final[int] +CUPS_PRINTER_BIND: Final[int] +CUPS_PRINTER_BW: Final[int] +CUPS_PRINTER_CLASS: Final[int] +CUPS_PRINTER_COLLATE: Final[int] +CUPS_PRINTER_COLOR: Final[int] +CUPS_PRINTER_COMMANDS: Final[int] +CUPS_PRINTER_COPIES: Final[int] +CUPS_PRINTER_COVER: Final[int] +CUPS_PRINTER_DEFAULT: Final[int] +CUPS_PRINTER_DELETE: Final[int] +CUPS_PRINTER_DISCOVERED: Final[int] +CUPS_PRINTER_DUPLEX: Final[int] +CUPS_PRINTER_FAX: Final[int] +CUPS_PRINTER_IMPLICIT: Final[int] +CUPS_PRINTER_LARGE: Final[int] +CUPS_PRINTER_LOCAL: Final[int] +CUPS_PRINTER_MEDIUM: Final[int] +CUPS_PRINTER_NOT_SHARED: Final[int] +CUPS_PRINTER_OPTIONS: Final[int] +CUPS_PRINTER_PUNCH: Final[int] +CUPS_PRINTER_REJECTING: Final[int] +CUPS_PRINTER_REMOTE: Final[int] +CUPS_PRINTER_SMALL: Final[int] +CUPS_PRINTER_SORT: Final[int] +CUPS_PRINTER_STAPLE: Final[int] +CUPS_PRINTER_VARIABLE: Final[int] +CUPS_SERVER_DEBUG_LOGGING: Final[str] +CUPS_SERVER_REMOTE_ADMIN: Final[str] +CUPS_SERVER_REMOTE_ANY: Final[str] +CUPS_SERVER_REMOTE_PRINTERS: Final[str] +CUPS_SERVER_SHARE_PRINTERS: Final[str] +CUPS_SERVER_USER_CANCEL_ANY: Final[str] +HTTP_AUTHORIZATION_CANCELED: Final[int] +HTTP_BAD_GATEWAY: Final[int] +HTTP_BAD_REQUEST: Final[int] +HTTP_ENCRYPT_ALWAYS: Final[int] +HTTP_ENCRYPT_IF_REQUESTED: Final[int] +HTTP_ENCRYPT_NEVER: Final[int] +HTTP_ENCRYPT_REQUIRED: Final[int] +HTTP_ERROR: Final[int] +HTTP_FORBIDDEN: Final[int] +HTTP_GATEWAY_TIMEOUT: Final[int] +HTTP_NOT_FOUND: Final[int] +HTTP_NOT_IMPLEMENTED: Final[int] +HTTP_NOT_MODIFIED: Final[int] +HTTP_NOT_SUPPORTED: Final[int] +HTTP_OK: Final[int] +HTTP_PKI_ERROR: Final[int] +HTTP_REQUEST_TIMEOUT: Final[int] +HTTP_SERVER_ERROR: Final[int] +HTTP_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_BAD_GATEWAY: Final[int] +HTTP_STATUS_BAD_REQUEST: Final[int] +HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED: Final[int] +HTTP_STATUS_CUPS_PKI_ERROR: Final[int] +HTTP_STATUS_ERROR: Final[int] +HTTP_STATUS_FORBIDDEN: Final[int] +HTTP_STATUS_GATEWAY_TIMEOUT: Final[int] +HTTP_STATUS_NOT_FOUND: Final[int] +HTTP_STATUS_NOT_IMPLEMENTED: Final[int] +HTTP_STATUS_NOT_MODIFIED: Final[int] +HTTP_STATUS_NOT_SUPPORTED: Final[int] +HTTP_STATUS_OK: Final[int] +HTTP_STATUS_REQUEST_TIMEOUT: Final[int] +HTTP_STATUS_SERVER_ERROR: Final[int] +HTTP_STATUS_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_UNAUTHORIZED: Final[int] +HTTP_STATUS_UPGRADE_REQUIRED: Final[int] +HTTP_UNAUTHORIZED: Final[int] +HTTP_UPGRADE_REQUIRED: Final[int] +IPP_ATTRIBUTE: Final[int] +IPP_ATTRIBUTES: Final[int] +IPP_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_AUTHENTICATION_CANCELED: Final[int] +IPP_BAD_REQUEST: Final[int] +IPP_CHARSET: Final[int] +IPP_COMPRESSION_ERROR: Final[int] +IPP_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_CONFLICT: Final[int] +IPP_CREATE_JOB_SUBSCRIPTION: Final[int] +IPP_CREATE_PRINTER_SUBSCRIPTION: Final[int] +IPP_DATA: Final[int] +IPP_DEVICE_ERROR: Final[int] +IPP_DOCUMENT_ACCESS_ERROR: Final[int] +IPP_DOCUMENT_FORMAT: Final[int] +IPP_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_ERROR: Final[int] +IPP_ERROR_JOB_CANCELED: Final[int] +IPP_FINISHINGS_BALE: Final[int] +IPP_FINISHINGS_BIND: Final[int] +IPP_FINISHINGS_BIND_BOTTOM: Final[int] +IPP_FINISHINGS_BIND_LEFT: Final[int] +IPP_FINISHINGS_BIND_RIGHT: Final[int] +IPP_FINISHINGS_BIND_TOP: Final[int] +IPP_FINISHINGS_BOOKLET_MAKER: Final[int] +IPP_FINISHINGS_COVER: Final[int] +IPP_FINISHINGS_EDGE_STITCH: Final[int] +IPP_FINISHINGS_EDGE_STITCH_BOTTOM: Final[int] +IPP_FINISHINGS_EDGE_STITCH_LEFT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_RIGHT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_TOP: Final[int] +IPP_FINISHINGS_FOLD: Final[int] +IPP_FINISHINGS_JOB_OFFSET: Final[int] +IPP_FINISHINGS_NONE: Final[int] +IPP_FINISHINGS_PUNCH: Final[int] +IPP_FINISHINGS_SADDLE_STITCH: Final[int] +IPP_FINISHINGS_STAPLE: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_BOTTOM: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_TOP: Final[int] +IPP_FINISHINGS_STAPLE_TOP_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_TOP_RIGHT: Final[int] +IPP_FINISHINGS_TRIM: Final[int] +IPP_FORBIDDEN: Final[int] +IPP_GONE: Final[int] +IPP_HEADER: Final[int] +IPP_IDLE: Final[int] +IPP_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_INTERNAL_ERROR: Final[int] +IPP_JOB_ABORTED: Final[int] +IPP_JOB_CANCELED: Final[int] +IPP_JOB_COMPLETED: Final[int] +IPP_JOB_HELD: Final[int] +IPP_JOB_PENDING: Final[int] +IPP_JOB_PROCESSING: Final[int] +IPP_JOB_STOPPED: Final[int] +IPP_LANDSCAPE: Final[int] +IPP_MAX_NAME: Final[int] +IPP_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_NOT_ACCEPTING: Final[int] +IPP_NOT_AUTHENTICATED: Final[int] +IPP_NOT_AUTHORIZED: Final[int] +IPP_NOT_FOUND: Final[int] +IPP_NOT_POSSIBLE: Final[int] +IPP_OK: Final[int] +IPP_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_OK_CONFLICT: Final[int] +IPP_OK_EVENTS_COMPLETE: Final[int] +IPP_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_OK_SUBST: Final[int] +IPP_OK_TOO_MANY_EVENTS: Final[int] +IPP_OPERATION_NOT_SUPPORTED: Final[int] +IPP_OP_ACTIVATE_PRINTER: Final[int] +IPP_OP_CANCEL_CURRENT_JOB: Final[int] +IPP_OP_CANCEL_JOB: Final[int] +IPP_OP_CANCEL_JOBS: Final[int] +IPP_OP_CANCEL_MY_JOBS: Final[int] +IPP_OP_CANCEL_SUBSCRIPTION: Final[int] +IPP_OP_CLOSE_JOB: Final[int] +IPP_OP_CREATE_JOB: Final[int] +IPP_OP_CREATE_JOB_SUBSCRIPTIONS: Final[int] +IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS: Final[int] +IPP_OP_CUPS_ACCEPT_JOBS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_CLASS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_PRINTER: Final[int] +IPP_OP_CUPS_AUTHENTICATE_JOB: Final[int] +IPP_OP_CUPS_DELETE_CLASS: Final[int] +IPP_OP_CUPS_DELETE_PRINTER: Final[int] +IPP_OP_CUPS_GET_CLASSES: Final[int] +IPP_OP_CUPS_GET_DEFAULT: Final[int] +IPP_OP_CUPS_GET_DOCUMENT: Final[int] +IPP_OP_CUPS_GET_PPD: Final[int] +IPP_OP_CUPS_GET_PPDS: Final[int] +IPP_OP_CUPS_GET_PRINTERS: Final[int] +IPP_OP_CUPS_MOVE_JOB: Final[int] +IPP_OP_CUPS_REJECT_JOBS: Final[int] +IPP_OP_CUPS_SET_DEFAULT: Final[int] +IPP_OP_DEACTIVATE_PRINTER: Final[int] +IPP_OP_DISABLE_PRINTER: Final[int] +IPP_OP_ENABLE_PRINTER: Final[int] +IPP_OP_GET_JOBS: Final[int] +IPP_OP_GET_JOB_ATTRIBUTES: Final[int] +IPP_OP_GET_NOTIFICATIONS: Final[int] +IPP_OP_GET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_GET_PRINTER_SUPPORTED_VALUES: Final[int] +IPP_OP_GET_PRINT_SUPPORT_FILES: Final[int] +IPP_OP_GET_RESOURCES: Final[int] +IPP_OP_GET_RESOURCE_ATTRIBUTES: Final[int] +IPP_OP_GET_RESOURCE_DATA: Final[int] +IPP_OP_GET_SUBSCRIPTIONS: Final[int] +IPP_OP_HOLD_JOB: Final[int] +IPP_OP_HOLD_NEW_JOBS: Final[int] +IPP_OP_IDENTIFY_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER_AFTER_CURRENT_JOB: Final[int] +IPP_OP_PRINT_JOB: Final[int] +IPP_OP_PRINT_URI: Final[int] +IPP_OP_PROMOTE_JOB: Final[int] +IPP_OP_PURGE_JOBS: Final[int] +IPP_OP_RELEASE_HELD_NEW_JOBS: Final[int] +IPP_OP_RELEASE_JOB: Final[int] +IPP_OP_RENEW_SUBSCRIPTION: Final[int] +IPP_OP_REPROCESS_JOB: Final[int] +IPP_OP_RESTART_JOB: Final[int] +IPP_OP_RESTART_PRINTER: Final[int] +IPP_OP_RESUBMIT_JOB: Final[int] +IPP_OP_RESUME_JOB: Final[int] +IPP_OP_RESUME_PRINTER: Final[int] +IPP_OP_SCHEDULE_JOB_AFTER: Final[int] +IPP_OP_SEND_DOCUMENT: Final[int] +IPP_OP_SEND_HARDCOPY_DOCUMENT: Final[int] +IPP_OP_SEND_NOTIFICATIONS: Final[int] +IPP_OP_SEND_URI: Final[int] +IPP_OP_SET_JOB_ATTRIBUTES: Final[int] +IPP_OP_SET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_SHUTDOWN_PRINTER: Final[int] +IPP_OP_STARTUP_PRINTER: Final[int] +IPP_OP_SUSPEND_CURRENT_JOB: Final[int] +IPP_OP_VALIDATE_DOCUMENT: Final[int] +IPP_OP_VALIDATE_JOB: Final[int] +IPP_ORIENT_LANDSCAPE: Final[int] +IPP_ORIENT_PORTRAIT: Final[int] +IPP_ORIENT_REVERSE_LANDSCAPE: Final[int] +IPP_ORIENT_REVERSE_PORTRAIT: Final[int] +IPP_PKI_ERROR: Final[int] +IPP_PORTRAIT: Final[int] +IPP_PRINTER_BUSY: Final[int] +IPP_PRINTER_IDLE: Final[int] +IPP_PRINTER_IS_DEACTIVATED: Final[int] +IPP_PRINTER_PROCESSING: Final[int] +IPP_PRINTER_STOPPED: Final[int] +IPP_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_QUALITY_DRAFT: Final[int] +IPP_QUALITY_HIGH: Final[int] +IPP_QUALITY_NORMAL: Final[int] +IPP_REDIRECTION_OTHER_SITE: Final[int] +IPP_REQUEST_ENTITY: Final[int] +IPP_REQUEST_VALUE: Final[int] +IPP_RES_PER_CM: Final[int] +IPP_RES_PER_INCH: Final[int] +IPP_REVERSE_LANDSCAPE: Final[int] +IPP_REVERSE_PORTRAIT: Final[int] +IPP_SERVICE_UNAVAILABLE: Final[int] +IPP_STATE_ATTRIBUTE: Final[int] +IPP_STATE_DATA: Final[int] +IPP_STATE_ERROR: Final[int] +IPP_STATE_HEADER: Final[int] +IPP_STATE_IDLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES: Final[int] +IPP_STATUS_ERROR_BAD_REQUEST: Final[int] +IPP_STATUS_ERROR_BUSY: Final[int] +IPP_STATUS_ERROR_CHARSET: Final[int] +IPP_STATUS_ERROR_COMPRESSION_ERROR: Final[int] +IPP_STATUS_ERROR_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_CONFLICTING: Final[int] +IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED: Final[int] +IPP_STATUS_ERROR_CUPS_PKI: Final[int] +IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED: Final[int] +IPP_STATUS_ERROR_DEVICE: Final[int] +IPP_STATUS_ERROR_DOCUMENT_ACCESS: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_FORBIDDEN: Final[int] +IPP_STATUS_ERROR_GONE: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_INTERNAL: Final[int] +IPP_STATUS_ERROR_JOB_CANCELED: Final[int] +IPP_STATUS_ERROR_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_NOT_ACCEPTING_JOBS: Final[int] +IPP_STATUS_ERROR_NOT_AUTHENTICATED: Final[int] +IPP_STATUS_ERROR_NOT_AUTHORIZED: Final[int] +IPP_STATUS_ERROR_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_NOT_POSSIBLE: Final[int] +IPP_STATUS_ERROR_OPERATION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_PRINTER_IS_DEACTIVATED: Final[int] +IPP_STATUS_ERROR_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_REQUEST_ENTITY: Final[int] +IPP_STATUS_ERROR_REQUEST_VALUE: Final[int] +IPP_STATUS_ERROR_SERVICE_UNAVAILABLE: Final[int] +IPP_STATUS_ERROR_TEMPORARY: Final[int] +IPP_STATUS_ERROR_TIMEOUT: Final[int] +IPP_STATUS_ERROR_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_URI_SCHEME: Final[int] +IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_OK: Final[int] +IPP_STATUS_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_STATUS_OK_CONFLICTING: Final[int] +IPP_STATUS_OK_EVENTS_COMPLETE: Final[int] +IPP_STATUS_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED: Final[int] +IPP_STATUS_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_STATUS_OK_TOO_MANY_EVENTS: Final[int] +IPP_STATUS_REDIRECTION_OTHER_SITE: Final[int] +IPP_TAG_BOOLEAN: Final[int] +IPP_TAG_CHARSET: Final[int] +IPP_TAG_ENUM: Final[int] +IPP_TAG_INTEGER: Final[int] +IPP_TAG_JOB: Final[int] +IPP_TAG_KEYWORD: Final[int] +IPP_TAG_LANGUAGE: Final[int] +IPP_TAG_MIMETYPE: Final[int] +IPP_TAG_NAME: Final[int] +IPP_TAG_OPERATION: Final[int] +IPP_TAG_PRINTER: Final[int] +IPP_TAG_RANGE: Final[int] +IPP_TAG_STRING: Final[int] +IPP_TAG_TEXT: Final[int] +IPP_TAG_URI: Final[int] +IPP_TAG_ZERO: Final[int] +IPP_TEMPORARY_ERROR: Final[int] +IPP_TIMEOUT: Final[int] +IPP_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_UPGRADE_REQUIRED: Final[int] +IPP_URI_SCHEME: Final[int] +IPP_VERSION_NOT_SUPPORTED: Final[int] +PPD_CONFORM_RELAXED: Final[int] +PPD_CONFORM_STRICT: Final[int] +PPD_ORDER_ANY: Final[int] +PPD_ORDER_DOCUMENT: Final[int] +PPD_ORDER_EXIT: Final[int] +PPD_ORDER_JCL: Final[int] +PPD_ORDER_PAGE: Final[int] +PPD_ORDER_PROLOG: Final[int] +PPD_UI_BOOLEAN: Final[int] +PPD_UI_PICKMANY: Final[int] +PPD_UI_PICKONE: Final[int] + +@final +class Attribute: + @property + def name(self) -> str: ... + @property + def spec(self) -> str: ... + @property + def text(self) -> str: ... + @property + def value(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Connection: + def __init__(self, host: str = ..., port: int = ..., encryption: int = ...) -> None: ... + def acceptJobs(self, name: str, /) -> None: ... + + @overload + def addPrinter(self, name: str, filename: str = ..., *, info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, ppdname: str = ..., info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, info: str = ..., location: str = ..., device: str = ..., ppd: PPD = ...) -> None: ... + + def addPrinterOptionDefault(self, name: str, option: str, value: str | int | Sequence[str | int], /) -> None: ... + def addPrinterToClass(self, name: str, _class: str, /) -> None: ... + def adminExportSamba(self, name: str, server: str, user: str, password: str, /): ... + def adminGetServerSettings(self) -> dict[str, str]: ... + def adminSetServerSettings(self, settings: dict[str, str], /) -> None: ... + def authenticateJob(self, jobid: int, auth_info: list[str] = ..., /) -> None: ... + + @overload + def cancelAllJobs(self, name: str, *, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + @overload + def cancelAllJobs(self, *, uri: str, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + + def cancelJob(self, job_id: int, purge_job: bool = False) -> None: ... + def cancelSubscription(self, id: int, /) -> None: ... + def createJob(self, printer: str, title: str, options: dict[str, str]) -> int: ... + def createSubscription( + self, + uri: str, + events: list[str] = ..., + job_id: int = ..., + recipient_uri: str = ..., + lease_duration: int = ..., + time_interval: int = ..., + user_data: str = ..., + ) -> int: ... + def deleteClass(self, _class: str, /) -> None: ... + def deletePrinter(self, name: str, /) -> None: ... + def deletePrinterFromClass(self, name: str, _class: str, /) -> None: ... + def deletePrinterOptionDefault(self, name: str, option: str, /) -> None: ... + def disablePrinter(self, name: str, reason: str = ...) -> None: ... + def enablePrinter(self, name: str, /) -> None: ... + def finishDocument(self, printer: str) -> int: ... + def getClasses(self) -> dict[str, str | list[str]]: ... + def getDefault(self) -> str | None: ... + def getDests(self) -> dict[tuple[str, str] | tuple[None, None], Dest]: ... + def getDevices( + self, limit: int = 0, exclude_schemes: list[str] = ..., include_schemes: list[str] = ..., timeout: int = 0 + ) -> dict[str, _CupsDevice]: ... + def getDocument(self, printer_uri: str, job_id: int, document_number: int, /) -> _CupsDocument: ... + + @overload + def getFile(self, resource: str, filename: str = ...) -> None: ... + @overload + def getFile(self, resource: str, *, fd: int) -> None: ... + @overload + def getFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def getJobAttributes(self, job_id: int, requested_attributes: list[str] = ...) -> _CupsJobWithAttributeInfo: ... + def getJobs( + self, + which_jobs: Literal["completed", "not-completed", "all"] = "not-completed", + my_jobs: bool = False, + limit: int = ..., + first_job_id: int = ..., + requested_attributes: list[str] = ["job-id", "job-uri"], + ) -> dict[int, _CupsJob]: ... + def getNotifications(self, subscription_ids: list[int], sequence_numbers: list[int] = ...) -> _CupsNotifications: ... + def getPPD(self, name: str, /) -> str: ... + def getPPD3(self, name: str, modtime: float = ..., filename: str = ...) -> tuple[int, float, str]: ... + def getPPDs( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD]: ... + def getPPDs2( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD2]: ... + + @overload + def getPrinterAttributes(self, name: str, *, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + @overload + def getPrinterAttributes(self, *, uri: str, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + + def getPrinters(self) -> dict[str, _CupsPrinterSimple]: ... + def getServerPPD(self, ppd_name: str, /) -> str: ... + def getSubscriptions(self, uri: str, my_subscriptions: bool = False, job_id: int = ...) -> list[_CupsSubscription]: ... + + @overload + def moveJob(self, printer_uri: str, job_id: int, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, printer_uri: str, *, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, *, job_id: int, job_printer_uri: str) -> None: ... + + def printFile(self, printer: str, filename: str, title: str, options: dict[str, str]) -> int: ... + def printFiles(self, printer: str, filenames: list[str], title: str, options: dict[str, str]) -> int: ... + def printTestPage(self, name: str) -> int: ... + + @overload + def putFile(self, resource: str, filename: str) -> None: ... + @overload + def putFile(self, resource: str, *, fd: int) -> None: ... + @overload + def putFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def rejectJobs(self, name: str, reason: str = ...) -> None: ... + def renewSubscription(self, id: int, lease_duration: int = ...) -> None: ... + def restartJob(self, job_id: int, job_hold_until: str = ...) -> None: ... + def setDefault(self, name: str, /) -> None: ... + def setJobHoldUntil(self, job_id: int, job_hold_until: str, /) -> None: ... + def setPrinterDevice(self, name: str, device_uri: str, /) -> None: ... + def setPrinterErrorPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterInfo(self, name: str, info: str, /) -> None: ... + def setPrinterJobSheets(self, name: str, start: str, end: str, /) -> None: ... + def setPrinterLocation(self, name: str, location: str, /) -> None: ... + def setPrinterOpPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterShared(self, name: str, shared: bool, /) -> None: ... + def setPrinterUsersAllowed(self, name: str, allowed: list[str], /) -> None: ... + def setPrinterUsersDenied(self, name: str, denied: list[str], /) -> None: ... + def startDocument(self, printer: str, job_id: int, doc_name: str, format: str, last_document: bool) -> int: ... + def writeRequestData(self, buffer: bytes, length: int) -> int: ... + +@final +class Constraint: + @property + def choice1(self) -> str: ... + @property + def choice2(self) -> str: ... + @property + def option1(self) -> str: ... + @property + def option2(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Dest: + @property + def instance(self) -> str | None: ... + @property + def is_default(self) -> bool: ... + @property + def name(self) -> str: ... + @property + def options(self) -> dict[str, str]: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Group: + @property + def name(self) -> str: ... + @property + def options(self) -> list[Option]: ... + @property + def subgroups(self) -> list[Group]: ... + @property + def text(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +class HTTPError(Exception): ... + +@final +class IPPAttribute: + @property + def group_tag(self) -> int: ... + @property + def name(self) -> str: ... + @property + def value_tag(self) -> int: ... + @property + def values(self) -> list[int | str | bool]: ... + def __init__(self, group_tag: int, value_tag: int, name: str, value: str = ..., /) -> None: ... + +class IPPError(Exception): ... + +@final +class IPPRequest: + @property + def attributes(self) -> list[IPPAttribute]: ... + @property + def operation(self) -> int: ... + + @property + def state(self) -> int: ... + @state.setter + def state(self, value: int) -> None: ... + + @property + def statuscode(self) -> int: ... + @statuscode.setter + def statuscode(self, value: int) -> None: ... + + def __init__(self, op: int = ..., /) -> None: ... + def add(self, attr: IPPAttribute, /) -> IPPAttribute: ... + def addSeparator(self) -> IPPAttribute: ... + def readIO(self, read_fn: Callable[[int], int], blocking: bool = True) -> int: ... + def writeIO(self, write_fn: Callable[[bytes], int], blocking: bool = True) -> int: ... + +@final +class Option: + @property + def choices(self) -> list[_CupsOptionChoice]: ... + @property + def conflicted(self) -> bool: ... + @property + def defchoice(self) -> str: ... + @property + def keyword(self) -> str: ... + @property + def text(self) -> str: ... + @property + def ui(self) -> int: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class PPD: + @property + def attributes(self) -> list[Attribute]: ... + @property + def constraints(self) -> list[Constraint]: ... + @property + def optionGroups(self) -> list[Group]: ... + def __init__(self, filename: str, /) -> None: ... + def conflicts(self) -> int: ... + def emit(self, file: _FileOrFd, section: int, /) -> None: ... + def emitAfterOrder(self, file: _FileOrFd, section: int, limit: int, min_order: float, /) -> None: ... + def emitFd(self, fd: int, section: int, /) -> None: ... + def emitJCL(self, file: _FileOrFd, job_id: int, user: str, title: str, /) -> None: ... + def emitJCLEnd(self, file: _FileOrFd, /) -> None: ... + def emitString(self, section: int, min_order: float, /) -> str: ... + def findAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findNextAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findOption(self, name: str, /) -> Option | None: ... + def localize(self) -> None: ... + def localizeIPPReason(self, reason: str, scheme: str = ...) -> str | None: ... + def localizeMarkerName(self, name: str, /) -> str | None: ... + def markDefaults(self) -> None: ... + def markOption(self, option: str, choice: str, /) -> int: ... + def nondefaultsMarked(self) -> bool: ... + def writeFd(self, fd: int, /) -> None: ... + +def connectDest( + dest: Dest, cb: Callable[[_T, int, Dest], Literal[0, 1]], flags: int = 0, msec: int = -1, user_data: _T = ... +) -> tuple[Connection, str]: ... +def enumDests( + cb: Callable[[_T, int, Dest], Literal[0, 1]], + flags: int = 0, + msec: int = -1, + type: int = 0, + mask: int = 0, + user_data: _T = ..., +) -> None: ... +def getEncryption() -> int: ... +def getPort() -> int: ... +def getServer() -> str: ... +def getUser() -> str: ... +def ippErrorString(status_code: int, /) -> str: ... +def ippOpString(op: int, /) -> str: ... +def modelSort(s1: str, s2: str, /) -> Literal[-1, 0, 1]: ... +def ppdSetConformance(level: int, /) -> None: ... +def require(version: str, /) -> None: ... +def setEncryption(policy: int, /) -> None: ... +def setPasswordCB(fn: Callable[[str], str | None], /) -> None: ... + +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str], str | None] | None, /) -> None: ... +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str, _T], str | None], context: _T = ..., /) -> None: ... + +def setPort(port: int, /) -> None: ... +def setServer(server: str, /) -> None: ... +def setUser(user: str, /) -> None: ... diff --git a/stubs/pycurl/@tests/stubtest_allowlist.txt b/stubs/pycurl/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5db17c304cd3 --- /dev/null +++ b/stubs/pycurl/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# The runtime computes __all__ dynamically (dir(_pycurl) + AsyncCurlMulti), so +# its exact contents depend on the libcurl feature set pycurl was built against. +pycurl.__all__ diff --git a/stubs/pycurl/METADATA.toml b/stubs/pycurl/METADATA.toml new file mode 100644 index 000000000000..75b538b77452 --- /dev/null +++ b/stubs/pycurl/METADATA.toml @@ -0,0 +1,5 @@ +version = "7.47.0" +upstream-repository = "https://github.com/pycurl/pycurl" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/pycurl/pycurl/__init__.pyi b/stubs/pycurl/pycurl/__init__.pyi new file mode 100644 index 000000000000..43856c3618eb --- /dev/null +++ b/stubs/pycurl/pycurl/__init__.pyi @@ -0,0 +1,2 @@ +from pycurl._pycurl import * +from pycurl.async_multi import AsyncCurlMulti as AsyncCurlMulti diff --git a/stubs/pycurl/pycurl/_pycurl.pyi b/stubs/pycurl/pycurl/_pycurl.pyi new file mode 100644 index 000000000000..fb200d812511 --- /dev/null +++ b/stubs/pycurl/pycurl/_pycurl.pyi @@ -0,0 +1,926 @@ +# Stub for the pycurl C extension (imported at runtime as `pycurl._pycurl`). +import sys +from _typeshed import ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from datetime import datetime +from types import TracebackType +from typing import Any, Final, Literal, NamedTuple +from typing_extensions import Self, disjoint_base + +version: str + +def global_init(option: int) -> None: ... +def global_cleanup() -> None: ... +def version_info( + stamp: int = ..., +) -> tuple[int, str, int, str, int, str, int, str, tuple[str, ...], str | None, int, str | None]: ... +def easy_strerror(errornum: int) -> str: ... +def multi_strerror(errornum: int) -> str: ... +def share_strerror(errornum: int) -> str: ... +def url_strerror(errornum: int) -> str: ... + +class error(Exception): + # libcurl protocol errors raise (code, message); arg-parse errors raise (message,). + args: tuple[int, str] | tuple[str] + +class WsFrame(NamedTuple): + age: int + flags: int + offset: int + bytesleft: int + len: int + +class HstsEntry(NamedTuple): + host: bytes + expire: datetime | None + include_subdomains: bool + +class HstsIndex(NamedTuple): + idx: int + total: int + +class KhKey(NamedTuple): + key: bytes + keytype: int + +class CurlSockAddr(NamedTuple): + family: int + socktype: int + protocol: int + addr: tuple[str, int] | tuple[str, int, int, int] | bytes + +@disjoint_base +class Curl: + USERPWD: int + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + # For `setopt()` the exact `value` type depends on the passed `option`; `None` used to unassign: + # http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.setopt + def setopt(self, option: int, value: Any | None, *, use_memoryview: bool = False) -> None: ... + def setopt_string(self, option: int, value: str) -> None: ... + def perform(self) -> None: ... + def perform_rb(self) -> bytes: ... + def perform_rs(self) -> str: ... + # For getinfo and getinfo_raw, the exact return type depends on the passed value: + # http://pycurl.io/docs/latest/curlobject.html#pycurl.Curl.getinfo + def getinfo(self, info: int) -> Any: ... + def getinfo_raw(self, info: int) -> Any: ... + def reset(self) -> None: ... + def unsetopt(self, option: int) -> None: ... + def pause(self, bitmask: int = ...) -> None: ... + def unpause(self) -> None: ... + def errstr(self) -> str: ... + def duphandle(self) -> Self: ... + def errstr_raw(self) -> bytes: ... + def multi(self) -> CurlMulti | None: ... + def share(self) -> CurlShare | None: ... + def recv(self, buffersize: int, /) -> bytes: ... + def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0) -> int: ... + def send(self, data: ReadableBuffer, /) -> int: ... + def ws_send( + self, data: ReadableBuffer | str, flags: int | None = None, fragsize: int = 0, encoding: str = "utf-8" + ) -> int: ... + def ws_recv(self, buffersize: int, /) -> tuple[bytes, WsFrame]: ... + def ws_recv_into(self, buffer: WriteableBuffer, nbytes: int = 0) -> tuple[int, WsFrame]: ... + def ws_meta(self) -> WsFrame | None: ... + def ws_close(self, code: int | None = None, reason: ReadableBuffer | str | None = None, encoding: str = "utf-8") -> int: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + if sys.platform == "linux" or sys.platform == "darwin": + def set_ca_certs(self, value: str | bytes, /) -> None: ... + +@disjoint_base +class CurlMulti: + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def add_handle(self, obj: Curl) -> None: ... + def remove_handle(self, obj: Curl) -> None: ... + def setopt( + self, + option: int, + value: ( + bool + | int + | list[str | bytes] + | tuple[str | bytes, ...] + | Callable[[int], Literal[-1, 0] | None] + | Callable[[int, int, Self, Any | None], Literal[-1, 0] | None] # See `assign()` below for `Any | None` + | Callable[[int, Curl | None], object] # `M_NOTIFYFUNCTION` (notify) callback; return value ignored + | None + ), + ) -> None: ... + def perform(self) -> tuple[int, int]: ... + def fdset(self) -> tuple[list[int], list[int], list[int]]: ... + def select(self, timeout: float) -> int: ... + def info_read(self, max_objects: int = ...) -> tuple[int, list[Curl], list[tuple[Curl, int, str]]]: ... + def socket_action(self, sockfd: int, ev_bitmask: int) -> tuple[int, int]: ... + # `assign()` accepts literally any object, it's only passed to callbacks and not processed; `None` used to unassign + def assign(self, sockfd: int, obj: Any | None, /) -> None: ... + def unassign(self, sock_fd: int, /) -> None: ... + def notify_enable(self, *notifications: int) -> None: ... + def notify_disable(self, *notifications: int) -> None: ... + def socket_all(self) -> tuple[int, int]: ... + def timeout(self) -> int: ... + def __contains__(self, key: Curl, /) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlShare: + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + # Currently this `setopt()` is very limited; `None` to unset is also not accepted: + # http://pycurl.io/docs/latest/curlshareobject.html#pycurl.CurlShare.setopt + def setopt(self, option: int, value: int) -> None: ... + def share(self, *lock_data: int) -> None: ... + def unshare(self, *lock_data: int) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlMime: + def __new__(cls, curl: Curl) -> Self: ... + def add( + self, + name: str | bytes | None = None, + data: ReadableBuffer | str | None = None, + file: str | bytes | None = None, + filename: str | bytes | None = None, + content_type: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + encoder: str | bytes | None = None, + ) -> CurlMimePart: ... + def add_field( + self, + name: str | bytes, + value: str | bytes, + content_type: str | bytes | None = None, + encoder: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + ) -> CurlMimePart: ... + def add_file( + self, + name: str | bytes, + path: str | bytes, + filename: str | bytes | None = None, + content_type: str | bytes | None = None, + headers: list[str | bytes] | tuple[str | bytes, ...] | None = None, + encoder: str | bytes | None = None, + ) -> CurlMimePart: ... + def add_multipart(self, name: str | bytes | None = None, subtype: str | bytes | None = None) -> CurlMime: ... + def addpart(self) -> CurlMimePart: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / + ) -> None: ... + +@disjoint_base +class CurlMimePart: + def name(self, name: str | bytes, /) -> None: ... + def data(self, data: ReadableBuffer | str, /) -> None: ... + def data_cb( + self, + datasize: int | None, + read: Callable[[Any, int], ReadableBuffer | str | int], + seek: Callable[[Any, int, int], int | None] | None = None, + free: Callable[[Any], object] | None = None, + userdata: Any = None, + ) -> None: ... + def filedata(self, path: str | bytes, /) -> None: ... + def filename(self, name: str | bytes, /) -> None: ... + def type(self, content_type: str | bytes, /) -> None: ... + def encoder(self, name: str | bytes, /) -> None: ... + def headers(self, headers: list[str | bytes] | tuple[str | bytes, ...] | None, /) -> None: ... + def subparts(self, mime: CurlMime, /) -> None: ... + +APPCONNECT_TIME_T: Final[int] = ... +CONNECT_TIME_T: Final[int] = ... +CONTENT_LENGTH_DOWNLOAD_T: Final[int] = ... +CONTENT_LENGTH_UPLOAD_T: Final[int] = ... +EARLYDATA_SENT_T: Final[int] = ... +FILETIME_T: Final[int] = ... +NAMELOOKUP_TIME_T: Final[int] = ... +POSTTRANSFER_TIME_T: Final[int] = ... +PRETRANSFER_TIME_T: Final[int] = ... +QUEUE_TIME_T: Final[int] = ... +REDIRECT_TIME_T: Final[int] = ... +SIZE_DOWNLOAD_T: Final[int] = ... +SIZE_UPLOAD_T: Final[int] = ... +SPEED_DOWNLOAD_T: Final[int] = ... +SPEED_UPLOAD_T: Final[int] = ... +STARTTRANSFER_TIME_T: Final[int] = ... +TOTAL_TIME_T: Final[int] = ... + +ACCEPTTIMEOUT_MS: Final = 212 +ACCEPT_ENCODING: Final = 10102 +ACTIVESOCKET: Final[int] +ADDRESS_SCOPE: Final = 171 +APPCONNECT_TIME: Final = 3145761 +APPEND: Final = 50 +AUTOREFERER: Final = 58 +AWS_SIGV4: Final = 10305 +BUFFERSIZE: Final = 98 +CAINFO: Final = 10065 +CAINFO_BLOB: Final = 40309 +CAPATH: Final = 10097 +CLOSESOCKETFUNCTION: Final = 20208 +COMPILE_LIBCURL_VERSION_NUM: Final[int] +COMPILE_PY_VERSION_HEX: Final[int] +COMPILE_SSL_LIB: Final[str] +CONDITION_UNMET: Final = 2097187 +CONNECTTIMEOUT: Final = 78 +CONNECTTIMEOUT_MS: Final = 156 +CONNECT_ONLY: Final = 141 +CONNECT_TIME: Final = 3145733 +CONNECT_TO: Final = 10243 +CONTENT_LENGTH_DOWNLOAD: Final = 3145743 +CONTENT_LENGTH_UPLOAD: Final = 3145744 +CONTENT_TYPE: Final = 1048594 +COOKIE: Final = 10022 +COOKIEFILE: Final = 10031 +COOKIEJAR: Final = 10082 +COOKIELIST: Final = 10135 +COOKIESESSION: Final = 96 +COPYPOSTFIELDS: Final = 10165 +CRLF: Final = 27 +CRLFILE: Final = 10169 +CSELECT_ERR: Final = 4 +CSELECT_IN: Final = 1 +CSELECT_OUT: Final = 2 +CURLHSTS_ENABLE: Final[int] +CURLHSTS_READONLYFILE: Final[int] +CURLSTS_DONE: Final[int] +CURLSTS_FAIL: Final[int] +CURLSTS_OK: Final[int] +CURL_HTTP_VERSION_1_0: Final = 1 +CURL_HTTP_VERSION_1_1: Final = 2 +CURL_HTTP_VERSION_2: Final = 3 +CURL_HTTP_VERSION_2TLS: Final = 4 +CURL_HTTP_VERSION_2_0: Final = 3 +CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE: Final = 5 +CURL_HTTP_VERSION_3: Final = 30 +CURL_HTTP_VERSION_3ONLY: Final = 31 +CURL_HTTP_VERSION_LAST: Final = 32 +CURL_HTTP_VERSION_NONE: Final = 0 +CURL_VERSION_ALTSVC: Final = 16777216 +CURL_VERSION_BROTLI: Final = 8388608 +CURL_VERSION_GSASL: Final = 536870912 +CURL_VERSION_HSTS: Final = 268435456 +CURL_VERSION_HTTP3: Final = 33554432 +CURL_VERSION_HTTPS_PROXY: Final = 2097152 +CURL_VERSION_MULTI_SSL: Final = 4194304 +CURL_VERSION_UNICODE: Final = 134217728 +CURL_VERSION_ZSTD: Final = 67108864 +CUSTOMREQUEST: Final = 10036 +DEBUGFUNCTION: Final = 20094 +DEFAULT_PROTOCOL: Final = 10238 +DIRLISTONLY: Final = 48 +DNS_CACHE_TIMEOUT: Final = 92 +DNS_SERVERS: Final = 10211 +DNS_USE_GLOBAL_CACHE: Final = 91 +DOH_URL: Final = 10279 +EFFECTIVE_URL: Final = 1048577 +EFFECTIVE_METHOD: Final = 1048634 +EGDSOCKET: Final = 10077 +ENCODING: Final = 10102 +EXPECT_100_TIMEOUT_MS: Final = 227 +E_ABORTED_BY_CALLBACK: Final = 42 +E_AGAIN: Final = 81 +E_ALREADY_COMPLETE: Final = 99999 +E_BAD_CALLING_ORDER: Final = 44 +E_BAD_CONTENT_ENCODING: Final = 61 +E_BAD_DOWNLOAD_RESUME: Final = 36 +E_BAD_FUNCTION_ARGUMENT: Final = 43 +E_BAD_PASSWORD_ENTERED: Final = 46 +E_CALL_MULTI_PERFORM: Final = -1 +E_CHUNK_FAILED: Final = 88 +E_CONV_FAILED: Final = 75 +E_CONV_REQD: Final = 76 +E_COULDNT_CONNECT: Final = 7 +E_COULDNT_RESOLVE_HOST: Final = 6 +E_COULDNT_RESOLVE_PROXY: Final = 5 +E_FAILED_INIT: Final = 2 +E_FILESIZE_EXCEEDED: Final = 63 +E_FILE_COULDNT_READ_FILE: Final = 37 +E_FTP_ACCEPT_FAILED: Final = 10 +E_FTP_ACCEPT_TIMEOUT: Final = 12 +E_FTP_ACCESS_DENIED: Final = 9 +E_FTP_BAD_DOWNLOAD_RESUME: Final = 36 +E_FTP_BAD_FILE_LIST: Final = 87 +E_FTP_CANT_GET_HOST: Final = 15 +E_FTP_CANT_RECONNECT: Final = 16 +E_FTP_COULDNT_GET_SIZE: Final = 32 +E_FTP_COULDNT_RETR_FILE: Final = 19 +E_FTP_COULDNT_SET_ASCII: Final = 29 +E_FTP_COULDNT_SET_BINARY: Final = 17 +E_FTP_COULDNT_SET_TYPE: Final = 17 +E_FTP_COULDNT_STOR_FILE: Final = 25 +E_FTP_COULDNT_USE_REST: Final = 31 +E_FTP_PARTIAL_FILE: Final = 18 +E_FTP_PORT_FAILED: Final = 30 +E_FTP_PRET_FAILED: Final = 84 +E_FTP_QUOTE_ERROR: Final = 21 +E_FTP_SSL_FAILED: Final = 64 +E_FTP_USER_PASSWORD_INCORRECT: Final = 10 +E_FTP_WEIRD_227_FORMAT: Final = 14 +E_FTP_WEIRD_PASS_REPLY: Final = 11 +E_FTP_WEIRD_PASV_REPLY: Final = 13 +E_FTP_WEIRD_SERVER_REPLY: Final = 8 +E_FTP_WEIRD_USER_REPLY: Final = 12 +E_FTP_WRITE_ERROR: Final = 20 +E_FUNCTION_NOT_FOUND: Final = 41 +E_GOT_NOTHING: Final = 52 +E_HTTP2: Final = 16 +E_HTTP_NOT_FOUND: Final = 22 +E_HTTP_PORT_FAILED: Final = 45 +E_HTTP_POST_ERROR: Final = 34 +E_HTTP_RANGE_ERROR: Final = 33 +E_HTTP_RETURNED_ERROR: Final = 22 +E_INTERFACE_FAILED: Final = 45 +E_LDAP_CANNOT_BIND: Final = 38 +E_LDAP_INVALID_URL: Final = 62 +E_LDAP_SEARCH_FAILED: Final = 39 +E_LIBRARY_NOT_FOUND: Final = 40 +E_LOGIN_DENIED: Final = 67 +E_MALFORMAT_USER: Final = 24 +E_MULTI_ADDED_ALREADY: Final = 7 +E_MULTI_BAD_EASY_HANDLE: Final = 2 +E_MULTI_BAD_HANDLE: Final = 1 +E_MULTI_BAD_SOCKET: Final = 5 +E_MULTI_CALL_MULTI_PERFORM: Final = -1 +E_MULTI_CALL_MULTI_SOCKET: Final = -1 +E_MULTI_INTERNAL_ERROR: Final = 4 +E_MULTI_OK: Final = 0 +E_MULTI_OUT_OF_MEMORY: Final = 3 +E_MULTI_UNKNOWN_OPTION: Final = 6 +E_NOT_BUILT_IN: Final = 4 +E_NO_CONNECTION_AVAILABLE: Final = 89 +E_OK: Final = 0 +E_OPERATION_TIMEDOUT: Final = 28 +E_OPERATION_TIMEOUTED: Final = 28 +E_OUT_OF_MEMORY: Final = 27 +E_PARTIAL_FILE: Final = 18 +E_PEER_FAILED_VERIFICATION: Final = 60 +E_QUOTE_ERROR: Final = 21 +E_RANGE_ERROR: Final = 33 +E_READ_ERROR: Final = 26 +E_RECV_ERROR: Final = 56 +E_REMOTE_ACCESS_DENIED: Final = 9 +E_REMOTE_DISK_FULL: Final = 70 +E_REMOTE_FILE_EXISTS: Final = 73 +E_REMOTE_FILE_NOT_FOUND: Final = 78 +E_RTSP_CSEQ_ERROR: Final = 85 +E_RTSP_SESSION_ERROR: Final = 86 +E_SEND_ERROR: Final = 55 +E_SEND_FAIL_REWIND: Final = 65 +E_SHARE_IN_USE: Final = 57 +E_SSH: Final = 79 +E_SSL_CACERT: Final = 60 +E_SSL_CACERT_BADFILE: Final = 77 +E_SSL_CERTPROBLEM: Final = 58 +E_SSL_CIPHER: Final = 59 +E_SSL_CONNECT_ERROR: Final = 35 +E_SSL_CRL_BADFILE: Final = 82 +E_SSL_ENGINE_INITFAILED: Final = 66 +E_SSL_ENGINE_NOTFOUND: Final = 53 +E_SSL_ENGINE_SETFAILED: Final = 54 +E_SSL_INVALIDCERTSTATUS: Final = 91 +E_SSL_ISSUER_ERROR: Final = 83 +E_SSL_PEER_CERTIFICATE: Final = 60 +E_SSL_PINNEDPUBKEYNOTMATCH: Final = 90 +E_SSL_SHUTDOWN_FAILED: Final = 80 +E_TELNET_OPTION_SYNTAX: Final = 49 +E_TFTP_DISKFULL: Final = 70 +E_TFTP_EXISTS: Final = 73 +E_TFTP_ILLEGAL: Final = 71 +E_TFTP_NOSUCHUSER: Final = 74 +E_TFTP_NOTFOUND: Final = 68 +E_TFTP_PERM: Final = 69 +E_TFTP_UNKNOWNID: Final = 72 +E_TOO_MANY_REDIRECTS: Final = 47 +E_UNKNOWN_OPTION: Final = 48 +E_UNKNOWN_TELNET_OPTION: Final = 48 +E_UNSUPPORTED_PROTOCOL: Final = 1 +E_UPLOAD_FAILED: Final = 25 +E_URL_MALFORMAT: Final = 3 +E_URL_MALFORMAT_USER: Final = 4 +E_USE_SSL_FAILED: Final = 64 +E_WRITE_ERROR: Final = 23 +FAILONERROR: Final = 45 +FILE: Final = 10001 +FNMATCHFUNC_FAIL: Final[int] +FNMATCHFUNC_MATCH: Final[int] +FNMATCHFUNC_NOMATCH: Final[int] +FNMATCH_DATA: Final[int] +FNMATCH_FUNCTION: Final[int] +FOLLOWLOCATION: Final = 52 +FORBID_REUSE: Final = 75 +FORM_BUFFER: Final = 11 +FORM_BUFFERPTR: Final = 12 +FORM_CONTENTS: Final = 4 +FORM_CONTENTTYPE: Final = 14 +FORM_FILE: Final = 10 +FORM_FILENAME: Final = 16 +FRESH_CONNECT: Final = 74 +FTPAPPEND: Final = 50 +FTPAUTH_DEFAULT: Final = 0 +FTPAUTH_SSL: Final = 1 +FTPAUTH_TLS: Final = 2 +FTPLISTONLY: Final = 48 +FTPMETHOD_DEFAULT: Final = 0 +FTPMETHOD_MULTICWD: Final = 1 +FTPMETHOD_NOCWD: Final = 2 +FTPMETHOD_SINGLECWD: Final = 3 +FTPPORT: Final = 10017 +FTPSSLAUTH: Final = 129 +FTPSSL_ALL: Final = 3 +FTPSSL_CONTROL: Final = 2 +FTPSSL_NONE: Final = 0 +FTPSSL_TRY: Final = 1 +FTP_ACCOUNT: Final = 10134 +FTP_ALTERNATIVE_TO_USER: Final = 10147 +FTP_CREATE_MISSING_DIRS: Final = 110 +FTP_ENTRY_PATH: Final = 1048606 +FTP_FILEMETHOD: Final = 138 +FTP_RESPONSE_TIMEOUT: Final = 112 +FTP_SKIP_PASV_IP: Final = 137 +FTP_SSL: Final = 119 +FTP_SSL_CCC: Final = 154 +FTP_USE_EPRT: Final = 106 +FTP_USE_EPSV: Final = 85 +FTP_USE_PRET: Final = 188 +GLOBAL_ACK_EINTR: Final = 4 +GLOBAL_ALL: Final = 3 +GLOBAL_DEFAULT: Final = 3 +GLOBAL_NOTHING: Final = 0 +GLOBAL_SSL: Final = 1 +GLOBAL_WIN32: Final = 2 +GSSAPI_DELEGATION: Final = 210 +GSSAPI_DELEGATION_FLAG: Final = 2 +GSSAPI_DELEGATION_NONE: Final = 0 +GSSAPI_DELEGATION_POLICY_FLAG: Final = 1 +HAPROXYPROTOCOL: Final = 274 +HAPROXY_CLIENT_IP: Final = 10323 +ECH: Final = 10325 +HEADER: Final = 42 +HEADERFUNCTION: Final = 20079 +HEADEROPT: Final = 229 +HEADER_SEPARATE: Final = 1 +HEADER_SIZE: Final = 2097163 +HEADER_UNIFIED: Final = 0 +HSTS: Final[int] +HSTSREADDATA: Final[int] +HSTSREADFUNCTION: Final[int] +HSTSWRITEDATA: Final[int] +HSTSWRITEFUNCTION: Final[int] +HSTS_CTRL: Final[int] +HTTP09_ALLOWED: Final = 285 +HTTP200ALIASES: Final = 10104 +HTTPAUTH: Final = 107 +HTTPAUTH_ANY: Final[int] +HTTPAUTH_ANYSAFE: Final[int] +HTTPAUTH_AVAIL: Final = 2097175 +HTTPAUTH_BASIC: Final = 1 +HTTPAUTH_DIGEST: Final = 2 +HTTPAUTH_DIGEST_IE: Final = 16 +HTTPAUTH_GSSNEGOTIATE: Final = 4 +HTTPAUTH_NEGOTIATE: Final = 4 +HTTPAUTH_NONE: Final = 0 +HTTPAUTH_NTLM: Final = 8 +HTTPAUTH_NTLM_WB: Final = 32 +HTTPAUTH_ONLY: Final[int] +HTTPGET: Final = 80 +HTTPHEADER: Final = 10023 +HTTPPOST: Final = 10024 +HTTPPROXYTUNNEL: Final = 61 +HTTP_CODE: Final = 2097154 +HTTP_CONNECTCODE: Final = 2097174 +HTTP_CONTENT_DECODING: Final = 158 +HTTP_TRANSFER_DECODING: Final = 157 +HTTP_VERSION: Final = 84 +IGNORE_CONTENT_LENGTH: Final = 136 +INFILE: Final = 10009 +INFILESIZE: Final = 30115 +INFILESIZE_LARGE: Final = 30115 +INFOTYPE_DATA_IN: Final = 3 +INFOTYPE_DATA_OUT: Final = 4 +INFOTYPE_HEADER_IN: Final = 1 +INFOTYPE_HEADER_OUT: Final = 2 +INFOTYPE_SSL_DATA_IN: Final = 5 +INFOTYPE_SSL_DATA_OUT: Final = 6 +INFOTYPE_TEXT: Final = 0 +INFO_CERTINFO: Final = 4194338 +INFO_COOKIELIST: Final = 4194332 +INFO_FILETIME: Final = 2097166 +INFO_HTTP_VERSION: Final = 2097198 +INFO_RTSP_CLIENT_CSEQ: Final = 2097189 +INFO_RTSP_CSEQ_RECV: Final = 2097191 +INFO_RTSP_SERVER_CSEQ: Final = 2097190 +INFO_RTSP_SESSION_ID: Final = 1048612 +INTERFACE: Final = 10062 +IOCMD_NOP: Final = 0 +IOCMD_RESTARTREAD: Final = 1 +IOCTLFUNCTION: Final = 20130 +IOE_FAILRESTART: Final = 2 +IOE_OK: Final = 0 +IOE_UNKNOWNCMD: Final = 1 +IPRESOLVE: Final = 113 +IPRESOLVE_V4: Final = 1 +IPRESOLVE_V6: Final = 2 +IPRESOLVE_WHATEVER: Final = 0 +ISSUERCERT: Final = 10170 +ISSUERCERT_BLOB: Final = 40295 +KEYPASSWD: Final = 10026 +KHMATCH_MISMATCH: Final = 1 +KHMATCH_MISSING: Final = 2 +KHMATCH_OK: Final = 0 +KHSTAT_DEFER: Final = 3 +KHSTAT_FINE: Final = 1 +KHSTAT_FINE_ADD_TO_FILE: Final = 0 +KHSTAT_REJECT: Final = 2 +KHTYPE_DSS: Final = 3 +KHTYPE_RSA: Final = 2 +KHTYPE_RSA1: Final = 1 +KHTYPE_UNKNOWN: Final = 0 +KRB4LEVEL: Final = 10063 +KRBLEVEL: Final = 10063 +LASTSOCKET: Final = 2097181 +LOCALPORT: Final = 139 +LOCALPORTRANGE: Final = 140 +LOCAL_IP: Final = 1048617 +LOCAL_PORT: Final = 2097194 +LOCK_DATA_CONNECT: Final = 5 +LOCK_DATA_COOKIE: Final = 2 +LOCK_DATA_DNS: Final = 3 +LOCK_DATA_PSL: Final = 6 +LOCK_DATA_SSL_SESSION: Final = 4 +LOGIN_OPTIONS: Final = 10224 +LOW_SPEED_LIMIT: Final = 19 +LOW_SPEED_TIME: Final = 20 +MAIL_AUTH: Final = 10217 +MAIL_FROM: Final = 10186 +MAIL_RCPT: Final = 10187 +MAXAGE_CONN: Final = 288 +MAXCONNECTS: Final = 71 +MAXFILESIZE: Final = 30117 +MAXFILESIZE_LARGE: Final = 30117 +MAXLIFETIME_CONN: Final = 314 +PREREQFUNCTION: Final = 20312 +PREREQFUNC_OK: Final = 0 +PREREQFUNC_ABORT: Final = 1 +MAXREDIRS: Final = 68 +MAX_RECV_SPEED_LARGE: Final = 30146 +MAX_SEND_SPEED_LARGE: Final = 30145 +MIMEPOST: Final[int] +M_CHUNK_LENGTH_PENALTY_SIZE: Final = 30010 +M_CONTENT_LENGTH_PENALTY_SIZE: Final = 30009 +M_MAXCONNECTS: Final = 6 +M_MAX_CONCURRENT_STREAMS: Final = 16 +M_MAX_HOST_CONNECTIONS: Final = 7 +M_MAX_PIPELINE_LENGTH: Final = 8 +M_MAX_TOTAL_CONNECTIONS: Final = 13 +M_NOTIFYFUNCTION: Final[int] +M_NOTIFY_EASY_DONE: Final[int] +M_NOTIFY_INFO_READ: Final[int] +M_PIPELINING: Final = 3 +M_PIPELINING_SERVER_BL: Final = 10012 +M_PIPELINING_SITE_BL: Final = 10011 +M_SOCKETFUNCTION: Final = 20001 +M_TIMERFUNCTION: Final = 20004 +NAMELOOKUP_TIME: Final = 3145732 +NETRC: Final = 51 +NETRC_FILE: Final = 10118 +NETRC_IGNORED: Final = 0 +NETRC_OPTIONAL: Final = 1 +NETRC_REQUIRED: Final = 2 +NEW_DIRECTORY_PERMS: Final = 160 +NEW_FILE_PERMS: Final = 159 +NOBODY: Final = 44 +NOPROGRESS: Final = 43 +NOPROXY: Final = 10177 +NOSIGNAL: Final = 99 +NUM_CONNECTS: Final = 2097178 +OPENSOCKETFUNCTION: Final = 20163 +OPT_CERTINFO: Final = 172 +OPT_COOKIELIST: Final = 10135 +OPT_FILETIME: Final = 69 +OPT_RTSP_CLIENT_CSEQ: Final = 193 +OPT_RTSP_REQUEST: Final = 189 +OPT_RTSP_SERVER_CSEQ: Final = 194 +OPT_RTSP_SESSION_ID: Final = 10190 +OPT_RTSP_STREAM_URI: Final = 10191 +OPT_RTSP_TRANSPORT: Final = 10192 +OS_ERRNO: Final = 2097177 +PASSWORD: Final = 10174 +PATH_AS_IS: Final = 234 +PAUSE_ALL: Final = 5 +PAUSE_CONT: Final = 0 +PAUSE_RECV: Final = 1 +PAUSE_SEND: Final = 4 +PINNEDPUBLICKEY: Final = 10230 +PIPEWAIT: Final = 237 +PIPE_HTTP1: Final = 1 +PIPE_MULTIPLEX: Final = 2 +PIPE_NOTHING: Final = 0 +POLL_IN: Final = 1 +POLL_INOUT: Final = 3 +POLL_NONE: Final = 0 +POLL_OUT: Final = 2 +POLL_REMOVE: Final = 4 +PORT: Final = 3 +POST: Final = 47 +POST301: Final = 161 +POSTFIELDS: Final = 10015 +POSTFIELDSIZE: Final = 30120 +POSTFIELDSIZE_LARGE: Final = 30120 +POSTQUOTE: Final = 10039 +POSTREDIR: Final = 161 +PREQUOTE: Final = 10093 +PRETRANSFER_TIME: Final = 3145734 +PRE_PROXY: Final = 10262 +PRIMARY_IP: Final = 1048608 +PRIMARY_PORT: Final = 2097192 +PROGRESSFUNCTION: Final = 20056 +PROTOCOLS: Final = 181 +PROTO_ALL: Final[int] +PROTO_DICT: Final = 512 +PROTO_FILE: Final = 1024 +PROTO_FTP: Final = 4 +PROTO_FTPS: Final = 8 +PROTO_GOPHER: Final = 33554432 +PROTO_HTTP: Final = 1 +PROTO_HTTPS: Final = 2 +PROTO_IMAP: Final = 4096 +PROTO_IMAPS: Final = 8192 +PROTO_LDAP: Final = 128 +PROTO_LDAPS: Final = 256 +PROTO_POP3: Final = 16384 +PROTO_POP3S: Final = 32768 +PROTO_RTMP: Final = 524288 +PROTO_RTMPE: Final = 2097152 +PROTO_RTMPS: Final = 8388608 +PROTO_RTMPT: Final = 1048576 +PROTO_RTMPTE: Final = 4194304 +PROTO_RTMPTS: Final = 16777216 +PROTO_RTSP: Final = 262144 +PROTO_SCP: Final = 16 +PROTO_SFTP: Final = 32 +PROTO_SMB: Final = 67108864 +PROTO_SMBS: Final = 134217728 +PROTO_SMTP: Final = 65536 +PROTO_SMTPS: Final = 131072 +PROTO_TELNET: Final = 64 +PROTO_TFTP: Final = 2048 +PROXY: Final = 10004 +PROXYAUTH: Final = 111 +PROXYAUTH_AVAIL: Final = 2097176 +PROXYHEADER: Final = 10228 +PROXYPASSWORD: Final = 10176 +PROXYPORT: Final = 59 +PROXYTYPE: Final = 101 +PROXYTYPE_HTTP: Final = 0 +PROXYTYPE_HTTP_1_0: Final = 1 +PROXYTYPE_SOCKS4: Final = 4 +PROXYTYPE_SOCKS4A: Final = 6 +PROXYTYPE_SOCKS5: Final = 5 +PROXYTYPE_SOCKS5_HOSTNAME: Final = 7 +PROXYUSERNAME: Final = 10175 +PROXYUSERPWD: Final = 10006 +PROXY_CAINFO: Final = 10246 +PROXY_CAINFO_BLOB: Final = 40310 +PROXY_CAPATH: Final = 10247 +PROXY_CRLFILE: Final = 10260 +PROXY_ISSUERCERT: Final = 10296 +PROXY_ISSUERCERT_BLOB: Final = 40297 +PROXY_KEYPASSWD: Final = 10258 +PROXY_PINNEDPUBLICKEY: Final = 10263 +PROXY_SERVICE_NAME: Final = 10235 +PROXY_SSLCERT: Final = 10254 +PROXY_SSLCERTTYPE: Final = 10255 +PROXY_SSLCERT_BLOB: Final = 40293 +PROXY_SSLKEY: Final = 10256 +PROXY_SSLKEYTYPE: Final = 10257 +PROXY_SSLKEY_BLOB: Final = 40294 +PROXY_SSLVERSION: Final = 250 +PROXY_SSL_CIPHER_LIST: Final = 10259 +PROXY_SSL_OPTIONS: Final = 261 +PROXY_SSL_VERIFYHOST: Final = 249 +PROXY_SSL_VERIFYPEER: Final = 248 +PROXY_TLS13_CIPHERS: Final = 10277 +PROXY_TLSAUTH_PASSWORD: Final = 10252 +PROXY_TLSAUTH_TYPE: Final = 10253 +PROXY_TLSAUTH_USERNAME: Final = 10251 +PROXY_TRANSFER_MODE: Final = 166 +PUT: Final = 54 +QUOTE: Final = 10028 +RANDOM_FILE: Final = 10076 +RANGE: Final = 10007 +READDATA: Final = 10009 +READFUNCTION: Final = 20012 +READFUNC_ABORT: Final = 268435456 +READFUNC_PAUSE: Final = 268435457 +REDIRECT_COUNT: Final = 2097172 +REDIRECT_TIME: Final = 3145747 +REDIRECT_URL: Final = 1048607 +REDIR_POST_301: Final = 1 +REDIR_POST_302: Final = 2 +REDIR_POST_303: Final = 4 +REDIR_POST_ALL: Final = 7 +REDIR_PROTOCOLS: Final = 182 +REFERER: Final = 10016 +REQUEST_SIZE: Final = 2097164 +REQUEST_TARGET: Final = 10266 +RESOLVE: Final = 10203 +RESOLVER_START_DATA: Final[int] +RESOLVER_START_FUNCTION: Final[int] +RESPONSE_CODE: Final = 2097154 +RESUME_FROM: Final = 30116 +RESUME_FROM_LARGE: Final = 30116 +RTSPREQ_ANNOUNCE: Final = 3 +RTSPREQ_DESCRIBE: Final = 2 +RTSPREQ_GET_PARAMETER: Final = 8 +RTSPREQ_LAST: Final = 12 +RTSPREQ_NONE: Final = 0 +RTSPREQ_OPTIONS: Final = 1 +RTSPREQ_PAUSE: Final = 6 +RTSPREQ_PLAY: Final = 5 +RTSPREQ_RECEIVE: Final = 11 +RTSPREQ_RECORD: Final = 10 +RTSPREQ_SETUP: Final = 4 +RTSPREQ_SET_PARAMETER: Final = 9 +RTSPREQ_TEARDOWN: Final = 7 +SASL_IR: Final = 218 +SEEKFUNCTION: Final = 20167 +SEEKFUNC_CANTSEEK: Final = 2 +SEEKFUNC_FAIL: Final = 1 +SEEKFUNC_OK: Final = 0 +SERVICE_NAME: Final = 10236 +SHARE: Final = 10100 +SH_SHARE: Final = 1 +SH_UNSHARE: Final = 2 +SIZE_DOWNLOAD: Final = 3145736 +SIZE_UPLOAD: Final = 3145735 +SOCKET_BAD: Final = -1 +SOCKET_TIMEOUT: Final = -1 +SOCKOPTFUNCTION: Final = 20148 +SOCKOPT_ALREADY_CONNECTED: Final = 2 +SOCKOPT_ERROR: Final = 1 +SOCKOPT_OK: Final = 0 +SOCKS5_GSSAPI_NEC: Final = 180 +SOCKS5_GSSAPI_SERVICE: Final = 10179 +SOCKTYPE_ACCEPT: Final = 1 +SOCKTYPE_IPCXN: Final = 0 +SPEED_DOWNLOAD: Final = 3145737 +SPEED_UPLOAD: Final = 3145738 +SSH_AUTH_AGENT: Final = 16 +SSH_AUTH_ANY: Final[int] +SSH_AUTH_DEFAULT: Final[int] +SSH_AUTH_HOST: Final = 4 +SSH_AUTH_KEYBOARD: Final = 8 +SSH_AUTH_NONE: Final = 0 +SSH_AUTH_PASSWORD: Final = 2 +SSH_AUTH_PUBLICKEY: Final = 1 +SSH_AUTH_TYPES: Final = 151 +SSH_HOST_PUBLIC_KEY_MD5: Final = 10162 +SSH_KEYFUNCTION: Final = 20184 +SSH_KNOWNHOSTS: Final = 10183 +SSH_PRIVATE_KEYFILE: Final = 10153 +SSH_PUBLIC_KEYFILE: Final = 10152 +SSLCERT: Final = 10025 +SSLCERTPASSWD: Final = 10026 +SSLCERTTYPE: Final = 10086 +SSLCERT_BLOB: Final = 40291 +SSLENGINE: Final = 10089 +SSLENGINE_DEFAULT: Final = 90 +SSLKEY: Final = 10087 +SSLKEYPASSWD: Final = 10026 +SSLKEYTYPE: Final = 10088 +SSLKEY_BLOB: Final = 40292 +SSLOPT_ALLOW_BEAST: Final = 1 +SSLOPT_NO_REVOKE: Final = 2 +SSLVERSION: Final = 32 +SSLVERSION_DEFAULT: Final = 0 +SSLVERSION_MAX_DEFAULT: Final = 65536 +SSLVERSION_MAX_TLSv1_0: Final = 262144 +SSLVERSION_MAX_TLSv1_1: Final = 327680 +SSLVERSION_MAX_TLSv1_2: Final = 393216 +SSLVERSION_MAX_TLSv1_3: Final = 458752 +SSLVERSION_SSLv2: Final = 2 +SSLVERSION_SSLv3: Final = 3 +SSLVERSION_TLSv1: Final = 1 +SSLVERSION_TLSv1_0: Final = 4 +SSLVERSION_TLSv1_1: Final = 5 +SSLVERSION_TLSv1_2: Final = 6 +SSLVERSION_TLSv1_3: Final = 7 +SSL_CIPHER_LIST: Final = 10083 +SSL_ENABLE_ALPN: Final = 226 +SSL_ENABLE_NPN: Final = 225 +SSL_ENGINES: Final = 4194331 +SSL_FALSESTART: Final = 233 +SSL_OPTIONS: Final = 216 +SSL_SESSIONID_CACHE: Final = 150 +SSL_VERIFYHOST: Final = 81 +SSL_VERIFYPEER: Final = 64 +SSL_VERIFYRESULT: Final = 2097165 +SSL_VERIFYSTATUS: Final = 232 +STARTTRANSFER_TIME: Final = 3145745 +STDERR: Final = 10037 +TCP_FASTOPEN: Final = 244 +TCP_KEEPALIVE: Final = 213 +TCP_KEEPIDLE: Final = 214 +TCP_KEEPINTVL: Final = 215 +TCP_NODELAY: Final = 121 +TELNETOPTIONS: Final = 10070 +TFTP_BLKSIZE: Final = 178 +TIMECONDITION: Final = 33 +TIMECONDITION_IFMODSINCE: Final = 1 +TIMECONDITION_IFUNMODSINCE: Final = 2 +TIMECONDITION_LASTMOD: Final = 3 +TIMECONDITION_NONE: Final = 0 +TIMEOUT: Final = 13 +TIMEOUT_MS: Final = 155 +TIMEVALUE: Final = 34 +TLS13_CIPHERS: Final = 10276 +TLSAUTH_PASSWORD: Final = 10205 +TLSAUTH_TYPE: Final = 10206 +TLSAUTH_USERNAME: Final = 10204 +TOTAL_TIME: Final = 3145731 +TRAILERDATA: Final[int] +TRAILERFUNCTION: Final[int] +TRAILERFUNC_ABORT: Final[int] +TRAILERFUNC_OK: Final[int] +TRANSFERTEXT: Final = 53 +TRANSFER_ENCODING: Final = 207 +UNIX_SOCKET_PATH: Final = 10231 +UNRESTRICTED_AUTH: Final = 105 +UPLOAD: Final = 46 +UPLOAD_BUFFERSIZE: Final = 280 +URL: Final = 10002 +USERAGENT: Final = 10018 +USERNAME: Final = 10173 +USERPWD: Final = 10005 +USESSL_ALL: Final = 3 +USESSL_CONTROL: Final = 2 +USESSL_NONE: Final = 0 +USESSL_TRY: Final = 1 +USE_SSL: Final = 119 +VERBOSE: Final = 41 +VERSION_ALTSVC: Final = 16777216 +VERSION_ASYNCHDNS: Final = 128 +VERSION_BROTLI: Final = 8388608 +VERSION_CONV: Final = 4096 +VERSION_CURLDEBUG: Final = 8192 +VERSION_DEBUG: Final = 64 +VERSION_GSASL: Final = 536870912 +VERSION_GSSAPI: Final = 131072 +VERSION_GSSNEGOTIATE: Final = 32 +VERSION_HSTS: Final = 268435456 +VERSION_HTTP2: Final = 65536 +VERSION_HTTP3: Final = 33554432 +VERSION_HTTPS_PROXY: Final = 2097152 +VERSION_IDN: Final = 1024 +VERSION_IPV6: Final = 1 +VERSION_KERBEROS4: Final = 2 +VERSION_KERBEROS5: Final = 262144 +VERSION_LARGEFILE: Final = 512 +VERSION_LIBZ: Final = 8 +VERSION_MULTI_SSL: Final = 4194304 +VERSION_NTLM: Final = 16 +VERSION_NTLM_WB: Final = 32768 +VERSION_PSL: Final = 1048576 +VERSION_SPNEGO: Final = 256 +VERSION_SSL: Final = 4 +VERSION_SSPI: Final = 2048 +VERSION_TLSAUTH_SRP: Final = 16384 +VERSION_UNICODE: Final = 134217728 +VERSION_UNIX_SOCKETS: Final = 524288 +VERSION_ZSTD: Final = 67108864 +WILDCARDMATCH: Final = 197 +WRITEDATA: Final = 10001 +WRITEFUNCTION: Final = 20011 +WRITEFUNC_PAUSE: Final = 268435457 +WRITEHEADER: Final = 10029 +WS_BINARY: Final[int] +WS_CLOSE: Final[int] +WS_CONT: Final[int] +WS_NOAUTOPONG: Final[int] +WS_OFFSET: Final[int] +WS_OPTIONS: Final[int] +WS_PING: Final[int] +WS_PONG: Final[int] +WS_RAW_MODE: Final[int] +WS_TEXT: Final[int] +XFERINFOFUNCTION: Final = 20219 +XOAUTH2_BEARER: Final = 10220 diff --git a/stubs/pycurl/pycurl/async_multi.pyi b/stubs/pycurl/pycurl/async_multi.pyi new file mode 100644 index 000000000000..0d1868bae07b --- /dev/null +++ b/stubs/pycurl/pycurl/async_multi.pyi @@ -0,0 +1,22 @@ +import asyncio +from collections.abc import Iterable +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from pycurl._pycurl import Curl + +class AsyncCurlMulti: + def __init__(self, close_handles: bool = False) -> None: ... + def setopt(self, option: int, value: Any) -> None: ... # type of value depends on the option + def add_handle(self, curl: Curl) -> asyncio.Future[Curl]: ... + def remove_handle(self, curl: Curl) -> None: ... + async def perform(self, curl: Curl) -> Curl: ... + def futures(self, curls: Iterable[Curl] | None = None) -> tuple[asyncio.Future[Curl], ...]: ... + @property + def closed(self) -> bool: ... + async def aclose(self) -> None: ... + async def __aenter__(self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... diff --git a/stubs/pyfarmhash/METADATA.toml b/stubs/pyfarmhash/METADATA.toml new file mode 100644 index 000000000000..3160c1245acf --- /dev/null +++ b/stubs/pyfarmhash/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.4.*" +upstream-repository = "https://github.com/veelion/python-farmhash" diff --git a/stubs/pyfarmhash/farmhash.pyi b/stubs/pyfarmhash/farmhash.pyi new file mode 100644 index 000000000000..cdb08e53a3c3 --- /dev/null +++ b/stubs/pyfarmhash/farmhash.pyi @@ -0,0 +1,9 @@ +def fingerprint128(a: str, /) -> tuple[int, int]: ... +def fingerprint32(a: str, /) -> int: ... +def fingerprint64(a: str, /) -> int: ... +def hash128(a: str, /) -> tuple[int, int]: ... +def hash128withseed(a: str, seed_low: int, seed_high: int, /) -> tuple[int, int]: ... +def hash32(a: str, /) -> int: ... +def hash32withseed(a: str, seed: int, /) -> int: ... +def hash64(a: str, /) -> int: ... +def hash64withseed(a: str, seed: int, /) -> int: ... diff --git a/stubs/pyflakes/@tests/stubtest_allowlist.txt b/stubs/pyflakes/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..109ee305c802 --- /dev/null +++ b/stubs/pyflakes/@tests/stubtest_allowlist.txt @@ -0,0 +1,30 @@ +# These all have class-level defaults that differ from the instance attributes +pyflakes.messages.DuplicateArgument.message_args +pyflakes.messages.ForwardAnnotationSyntaxError.message_args +pyflakes.messages.FutureFeatureNotDefined.message_args +pyflakes.messages.ImportShadowedByLoopVar.message_args +pyflakes.messages.ImportStarNotPermitted.message_args +pyflakes.messages.ImportStarUsage.message_args +pyflakes.messages.ImportStarUsed.message_args +pyflakes.messages.MultiValueRepeatedKeyLiteral.message_args +pyflakes.messages.MultiValueRepeatedKeyVariable.message_args +pyflakes.messages.PercentFormatExtraNamedArguments.message_args +pyflakes.messages.PercentFormatInvalidFormat.message_args +pyflakes.messages.PercentFormatMissingArgument.message_args +pyflakes.messages.PercentFormatPositionalCountMismatch.message_args +pyflakes.messages.PercentFormatUnsupportedFormatCharacter.message_args +pyflakes.messages.RedefinedWhileUnused.message_args +pyflakes.messages.StringDotFormatExtraNamedArguments.message_args +pyflakes.messages.StringDotFormatExtraPositionalArguments.message_args +pyflakes.messages.StringDotFormatInvalidFormat.message_args +pyflakes.messages.StringDotFormatMissingArgument.message_args +pyflakes.messages.UndefinedExport.message_args +pyflakes.messages.UndefinedLocal.message_args +pyflakes.messages.UndefinedName.message_args +pyflakes.messages.UnusedAnnotation.message_args +pyflakes.messages.UnusedImport.message_args +pyflakes.messages.UnusedIndirectAssignment.message_args +pyflakes.messages.UnusedVariable.message_args + +# Tests are not included: +pyflakes.test.* diff --git a/stubs/pyflakes/METADATA.toml b/stubs/pyflakes/METADATA.toml new file mode 100644 index 000000000000..4619a579594b --- /dev/null +++ b/stubs/pyflakes/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.4.*" +upstream-repository = "https://github.com/PyCQA/pyflakes" diff --git a/stubs/pyflakes/pyflakes/__init__.pyi b/stubs/pyflakes/pyflakes/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyflakes/pyflakes/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyflakes/pyflakes/__main__.pyi b/stubs/pyflakes/pyflakes/__main__.pyi new file mode 100644 index 000000000000..e70d627ae91d --- /dev/null +++ b/stubs/pyflakes/pyflakes/__main__.pyi @@ -0,0 +1 @@ +from pyflakes.api import main as main diff --git a/stubs/pyflakes/pyflakes/api.pyi b/stubs/pyflakes/pyflakes/api.pyi new file mode 100644 index 000000000000..c3e9477ab53e --- /dev/null +++ b/stubs/pyflakes/pyflakes/api.pyi @@ -0,0 +1,18 @@ +from _typeshed import GenericPath +from collections.abc import Iterable, Iterator, Sequence +from re import Pattern +from typing import Final +from typing_extensions import Never + +from pyflakes.reporter import Reporter + +__all__ = ["check", "checkPath", "checkRecursive", "iterSourceCode", "main"] + +PYTHON_SHEBANG_REGEX: Final[Pattern[bytes]] + +def check(codeString: str, filename: str, reporter: Reporter | None = None) -> int: ... +def checkPath(filename: str, reporter: Reporter | None = None) -> int: ... +def isPythonFile(filename: str) -> bool: ... +def iterSourceCode(paths: Iterable[GenericPath[str]]) -> Iterator[GenericPath[str]]: ... +def checkRecursive(paths: Iterable[GenericPath[str]], reporter: Reporter) -> int: ... +def main(prog: str | None = None, args: Sequence[str] | None = None) -> Never: ... diff --git a/stubs/pyflakes/pyflakes/checker.pyi b/stubs/pyflakes/pyflakes/checker.pyi new file mode 100644 index 000000000000..4e7bc16642cb --- /dev/null +++ b/stubs/pyflakes/pyflakes/checker.pyi @@ -0,0 +1,343 @@ +import ast +import sys +from _typeshed import StrOrLiteralStr, Unused +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from re import Pattern +from typing import Any, ClassVar, Final, Literal, ParamSpec, TypeAlias, TypeVar, overload +from typing_extensions import Never + +from pyflakes.messages import Message + +_F = TypeVar("_F", bound=Callable[..., Any]) +_P = ParamSpec("_P") + +PYPY: Final[bool] +builtin_vars: Final[list[str]] + +def parse_format_string( + format_string: StrOrLiteralStr, +) -> Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]: ... +def getAlternatives(n: ast.If | ast.Try | ast.Match) -> list[ast.AST]: ... + +FOR_TYPES: Final[tuple[type[ast.For], type[ast.AsyncFor]]] +MAPPING_KEY_RE: Final[Pattern[str]] +CONVERSION_FLAG_RE: Final[Pattern[str]] +WIDTH_RE: Final[Pattern[str]] +PRECISION_RE: Final[Pattern[str]] +LENGTH_RE: Final[Pattern[str]] +VALID_CONVERSIONS: frozenset[str] + +_FormatType: TypeAlias = tuple[str | None, str | None, str | None, str | None, str] +_PercentFormat: TypeAlias = tuple[str, _FormatType | None] + +def parse_percent_format(s: str) -> tuple[_PercentFormat, ...]: ... + +class _FieldsOrder(dict[type[ast.AST], tuple[str, ...]]): + def __missing__(self, node_class: type[ast.AST]) -> tuple[str, ...]: ... + +_OmitType: TypeAlias = str | tuple[str, ...] | None + +def iter_child_nodes(node: ast.AST, omit: _OmitType = None, _fields_order: _FieldsOrder = ...) -> Iterator[ast.AST]: ... + +@overload +def convert_to_value(item: ast.Constant) -> Any: ... # type: ignore[overload-overlap] # See ast.Constant.value for possible return types +@overload +def convert_to_value(item: ast.Tuple) -> tuple[Any, ...]: ... # type: ignore[overload-overlap] # Tuple items depend on their ast type +@overload +def convert_to_value(item: ast.Name) -> VariableKey: ... # type: ignore[overload-overlap] +@overload +def convert_to_value(item: ast.AST) -> UnhandledKeyType: ... + +def is_notimplemented_name_node(node: ast.AST) -> bool: ... + +class Binding: + name: str + source: ast.AST | None + used: Literal[False] | tuple[Scope, ast.AST] + def __init__(self, name: str, source: ast.AST | None) -> None: ... + def redefines(self, other: Binding) -> bool: ... + +class Definition(Binding): ... + +class Builtin(Definition): + def __init__(self, name: str) -> None: ... + +class UnhandledKeyType: ... + +class VariableKey: + name: str + def __init__(self, item: ast.Name) -> None: ... + def __eq__(self, compare: object) -> bool: ... + def __hash__(self) -> int: ... + +class Importation(Definition): + fullName: str + redefined: list[ast.AST] + def __init__(self, name: str, source: ast.AST | None, full_name: str | None = None) -> None: ... + @property + def source_statement(self) -> str: ... + +class SubmoduleImportation(Importation): + def __init__(self, name: str, source: ast.Import | None) -> None: ... + +class ImportationFrom(Importation): + module: str + real_name: str + def __init__(self, name: str, source: ast.AST, module: str, real_name: str | None = None) -> None: ... + +class StarImportation(Importation): + def __init__(self, name: str, source: ast.AST) -> None: ... + +class FutureImportation(ImportationFrom): + used: tuple[Scope, ast.AST] + def __init__(self, name: str, source: ast.AST, scope: Scope) -> None: ... + +class Argument(Binding): ... +class Assignment(Binding): ... +class NamedExprAssignment(Assignment): ... + +class Annotation(Binding): + def redefines(self, other: Binding) -> Literal[False]: ... + +class FunctionDefinition(Definition): ... +class ClassDefinition(Definition): ... + +class ExportBinding(Binding): + names: list[str] + def __init__(self, name: str, source: ast.AST, scope: Scope) -> None: ... + +class Scope(dict[str, Binding]): + importStarred: bool + +class ClassScope(Scope): + def __init__(self) -> None: ... + +class FunctionScope(Scope): + usesLocals: bool + alwaysUsed: ClassVar[set[str]] + globals: set[str] + returnValue: ast.expr | None + isGenerator: bool + def __init__(self) -> None: ... + def unused_assignments(self) -> Iterator[tuple[str, Binding]]: ... + def unused_annotations(self) -> Iterator[tuple[str, Annotation]]: ... + +class TypeScope(Scope): ... +class GeneratorScope(Scope): ... +class ModuleScope(Scope): ... +class DoctestScope(ModuleScope): ... + +class DetectClassScopedMagic: + names: list[str] + +def getNodeName(node: ast.AST) -> str: ... + +TYPING_MODULES: frozenset[Literal["typing", "typing_extensions"]] + +def is_typing_overload(value: Binding, scope_stack: Sequence[Scope]) -> bool: ... + +class AnnotationState: + NONE: ClassVar[Literal[0]] + STRING: ClassVar[Literal[1]] + BARE: ClassVar[Literal[2]] + +def in_annotation(func: _F) -> _F: ... +def in_string_annotation(func: _F) -> _F: ... + +if sys.version_info >= (3, 12): + _TypeVar: TypeAlias = ast.TypeVar + _ParamSpec: TypeAlias = ast.ParamSpec + _TypeVarTuple: TypeAlias = ast.TypeVarTuple + _TypeAlias: TypeAlias = ast.TypeAlias +else: + # The methods using these should never be called on Python < 3.12. + _TypeVar: TypeAlias = Never + _ParamSpec: TypeAlias = Never + _TypeVarTuple: TypeAlias = Never + _TypeAlias: TypeAlias = Never + +if sys.version_info >= (3, 14): + _NameConstant: TypeAlias = Never + _TemplateStr: TypeAlias = ast.TemplateStr + _Interpolation: TypeAlias = ast.Interpolation +else: + _NameConstant: TypeAlias = ast.NameConstant + # The methods using these should never be called on Python < 3.14. + _TemplateStr: TypeAlias = Never + _Interpolation: TypeAlias = Never + +class Checker: + nodeDepth: int + offset: tuple[int, int] | None + builtIns: set[str] + deadScopes: list[Scope] + messages: list[Message] + filename: str + withDoctest: bool + scopeStack: list[Scope] + exceptHandlers: list[tuple[()] | str] + root: ast.AST + def __init__( + self, + tree: ast.AST, + filename: str = "(none)", + builtins: Iterable[str] | None = None, + withDoctest: bool = False, + file_tokens: Unused = (), + ) -> None: ... + def deferFunction(self, callable: Callable[..., Any]) -> None: ... + + @property + def futuresAllowed(self) -> bool: ... + @futuresAllowed.setter + def futuresAllowed(self, value: Literal[False]) -> None: ... + + @property + def annotationsFutureEnabled(self) -> bool: ... + @annotationsFutureEnabled.setter + def annotationsFutureEnabled(self, value: Literal[True]) -> None: ... + + @property + def scope(self) -> Scope: ... + @contextmanager + def in_scope(self, cls: Callable[[], Scope]) -> Generator[None]: ... + def checkDeadScopes(self) -> None: ... + def report(self, messageClass: Callable[_P, Message], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + def getParent(self, node: ast.AST) -> ast.AST: ... + def getCommonAncestor(self, lnode: ast.AST, rnode: ast.AST, stop: ast.AST) -> ast.AST: ... + def descendantOf(self, node: ast.AST, ancestors: ast.AST, stop: ast.AST) -> bool: ... + def getScopeNode(self, node: ast.AST) -> ast.AST | None: ... + def differentForks(self, lnode: ast.AST, rnode: ast.AST) -> bool: ... + def addBinding(self, node: ast.AST, value: Binding) -> None: ... + def getNodeHandler(self, node_class: type[ast.AST]) -> Callable[[ast.AST], None]: ... + def handleNodeLoad(self, node: ast.AST, parent: ast.AST | None) -> None: ... + def handleNodeStore(self, node: ast.AST) -> None: ... + def handleNodeDelete(self, node: ast.AST) -> None: ... + def handleChildren(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def isLiteralTupleUnpacking(self, node: ast.AST) -> bool | None: ... + def isDocstring(self, node: ast.AST) -> bool: ... + def getDocstring(self, node: ast.AST) -> tuple[str, int] | tuple[None, None]: ... + def handleNode(self, node: ast.AST | None, parent: ast.AST | None) -> None: ... + def handleDoctests(self, node: ast.AST) -> None: ... + def handleStringAnnotation(self, s: str, node: ast.AST, ref_lineno: int, ref_col_offset: int, err: type[Message]) -> None: ... + def handle_annotation_always_deferred(self, annotation: ast.AST, parent: ast.AST) -> None: ... + def handleAnnotation(self, annotation: ast.AST, node: ast.AST) -> None: ... + def ignore(self, node: ast.AST) -> None: ... + def DELETE(self, tree: ast.Delete, omit: _OmitType = None) -> None: ... + def FOR(self, tree: ast.For, omit: _OmitType = None) -> None: ... + def ASYNCFOR(self, tree: ast.AsyncFor, omit: _OmitType = None) -> None: ... + def WHILE(self, tree: ast.While, omit: _OmitType = None) -> None: ... + def WITH(self, tree: ast.With, omit: _OmitType = None) -> None: ... + def WITHITEM(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def ASYNCWITH(self, tree: ast.AsyncWith, omit: _OmitType = None) -> None: ... + def EXPR(self, tree: ast.AST, omit: _OmitType = None) -> None: ... + def ASSIGN(self, tree: ast.Assign, omit: _OmitType = None) -> None: ... + def PASS(self, node: ast.AST) -> None: ... + def BOOLOP(self, tree: ast.BoolOp, omit: _OmitType = None) -> None: ... + def UNARYOP(self, tree: ast.UnaryOp, omit: _OmitType = None) -> None: ... + def SET(self, tree: ast.Set, omit: _OmitType = None) -> None: ... + def ATTRIBUTE(self, tree: ast.Attribute, omit: _OmitType = None) -> None: ... + def STARRED(self, tree: ast.Starred, omit: _OmitType = None) -> None: ... + def NAMECONSTANT(self, tree: _NameConstant, omit: _OmitType = None) -> None: ... + def NAMEDEXPR(self, tree: ast.NamedExpr, omit: _OmitType = None) -> None: ... + def SUBSCRIPT(self, node: ast.Subscript) -> None: ... + def CALL(self, node: ast.Call) -> None: ... + def BINOP(self, node: ast.BinOp) -> None: ... + def CONSTANT(self, node: ast.Constant) -> None: ... + def SLICE(self, tree: ast.Slice, omit: _OmitType = None) -> None: ... + def EXTSLICE(self, tree: ast.ExtSlice, omit: _OmitType = None) -> None: ... + def INDEX(self, tree: ast.Index, omit: _OmitType = None) -> None: ... + def LOAD(self, node: ast.Load) -> None: ... + def STORE(self, node: ast.Store) -> None: ... + def DEL(self, node: ast.Del) -> None: ... + def AUGLOAD(self, node: ast.AugLoad) -> None: ... + def AUGSTORE(self, node: ast.AugStore) -> None: ... + def PARAM(self, node: ast.Param) -> None: ... + def AND(self, node: ast.And) -> None: ... + def OR(self, node: ast.Or) -> None: ... + def ADD(self, node: ast.Add) -> None: ... + def SUB(self, node: ast.Sub) -> None: ... + def MULT(self, node: ast.Mult) -> None: ... + def DIV(self, node: ast.Div) -> None: ... + def MOD(self, node: ast.Mod) -> None: ... + def POW(self, node: ast.Pow) -> None: ... + def LSHIFT(self, node: ast.LShift) -> None: ... + def RSHIFT(self, node: ast.RShift) -> None: ... + def BITOR(self, node: ast.BitOr) -> None: ... + def BITXOR(self, node: ast.BitXor) -> None: ... + def BITAND(self, node: ast.BitAnd) -> None: ... + def FLOORDIV(self, node: ast.FloorDiv) -> None: ... + def INVERT(self, node: ast.Invert) -> None: ... + def NOT(self, node: ast.Not) -> None: ... + def UADD(self, node: ast.UAdd) -> None: ... + def USUB(self, node: ast.USub) -> None: ... + def EQ(self, node: ast.Eq) -> None: ... + def NOTEQ(self, node: ast.NotEq) -> None: ... + def LT(self, node: ast.Lt) -> None: ... + def LTE(self, node: ast.LtE) -> None: ... + def GT(self, node: ast.Gt) -> None: ... + def GTE(self, node: ast.GtE) -> None: ... + def IS(self, node: ast.Is) -> None: ... + def ISNOT(self, node: ast.IsNot) -> None: ... + def IN(self, node: ast.In) -> None: ... + def NOTIN(self, node: ast.NotIn) -> None: ... + def MATMULT(self, node: ast.MatMult) -> None: ... + def RAISE(self, node: ast.Raise) -> None: ... + def COMPREHENSION(self, tree: ast.comprehension, omit: _OmitType = None) -> None: ... + def KEYWORD(self, tree: ast.keyword, omit: _OmitType = None) -> None: ... + def FORMATTEDVALUE(self, tree: ast.FormattedValue, omit: _OmitType = None) -> None: ... + def JOINEDSTR(self, node: ast.AST) -> None: ... + def TEMPLATESTR(self, node: _TemplateStr) -> None: ... + def INTERPOLATION(self, tree: _Interpolation, omit: _OmitType = None) -> None: ... + def DICT(self, node: ast.Dict) -> None: ... + def IF(self, node: ast.If) -> None: ... + def IFEXP(self, node: ast.If) -> None: ... + def ASSERT(self, node: ast.Assert) -> None: ... + def GLOBAL(self, node: ast.Global) -> None: ... + def NONLOCAL(self, node: ast.Nonlocal) -> None: ... + def GENERATOREXP(self, node: ast.GeneratorExp) -> None: ... + def LISTCOMP(self, node: ast.ListComp) -> None: ... + def DICTCOMP(self, node: ast.DictComp) -> None: ... + def SETCOMP(self, node: ast.SetComp) -> None: ... + def NAME(self, node: ast.Name) -> None: ... + def CONTINUE(self, node: ast.Continue) -> None: ... + def BREAK(self, node: ast.Break) -> None: ... + def RETURN(self, node: ast.Return) -> None: ... + def YIELD(self, node: ast.Yield) -> None: ... + def AWAIT(self, node: ast.Await) -> None: ... + def YIELDFROM(self, node: ast.YieldFrom) -> None: ... + def FUNCTIONDEF(self, node: ast.FunctionDef) -> None: ... + def ASYNCFUNCTIONDEF(self, node: ast.AsyncFunctionDef) -> None: ... + def LAMBDA(self, node: ast.Lambda) -> None: ... + def ARGUMENTS(self, node: ast.arguments) -> None: ... + def ARG(self, node: ast.arg) -> None: ... + def CLASSDEF(self, node: ast.ClassDef) -> None: ... + def AUGASSIGN(self, node: ast.AugAssign) -> None: ... + def TUPLE(self, node: ast.Tuple) -> None: ... + def LIST(self, node: ast.List) -> None: ... + def IMPORT(self, node: ast.Import) -> None: ... + def IMPORTFROM(self, node: ast.ImportFrom) -> None: ... + def TRY(self, node: ast.Try) -> None: ... + if sys.version_info >= (3, 11): + def TRYSTAR(self, node: ast.TryStar) -> None: ... + else: + def TRYSTAR(self, node: ast.Try) -> None: ... + + def EXCEPTHANDLER(self, node: ast.ExceptHandler) -> None: ... + def ANNASSIGN(self, node: ast.AnnAssign) -> None: ... + def COMPARE(self, node: ast.Compare) -> None: ... + def MATCH(self, tree: ast.Match, omit: _OmitType = None) -> None: ... + def MATCH_CASE(self, tree: ast.match_case, omit: _OmitType = None) -> None: ... + def MATCHCLASS(self, tree: ast.MatchClass, omit: _OmitType = None) -> None: ... + def MATCHOR(self, tree: ast.MatchOr, omit: _OmitType = None) -> None: ... + def MATCHSEQUENCE(self, tree: ast.MatchSequence, omit: _OmitType = None) -> None: ... + def MATCHSINGLETON(self, tree: ast.MatchSingleton, omit: _OmitType = None) -> None: ... + def MATCHVALUE(self, tree: ast.MatchValue, omit: _OmitType = None) -> None: ... + def MATCHAS(self, node: ast.MatchAs) -> None: ... + def MATCHMAPPING(self, node: ast.MatchMapping) -> None: ... + def MATCHSTAR(self, node: ast.MatchStar) -> None: ... + def TYPEVAR(self, node: _TypeVar) -> None: ... + def PARAMSPEC(self, node: _ParamSpec) -> None: ... + def TYPEVARTUPLE(self, node: _TypeVarTuple) -> None: ... + def TYPEALIAS(self, node: _TypeAlias) -> None: ... diff --git a/stubs/pyflakes/pyflakes/messages.pyi b/stubs/pyflakes/pyflakes/messages.pyi new file mode 100644 index 000000000000..4db703f30c7c --- /dev/null +++ b/stubs/pyflakes/pyflakes/messages.pyi @@ -0,0 +1,148 @@ +import ast +from typing import Any, ClassVar + +class Message: + message: ClassVar[str] + message_args: tuple[Any, ...] # Tuple types differ between sub-classes. + filename: str + lineno: int + col: int + def __init__(self, filename: str, loc: ast.AST) -> None: ... + +class UnusedImport(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class RedefinedWhileUnused(Message): + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class ImportShadowedByLoopVar(Message): + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class ImportStarNotPermitted(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, modname: str) -> None: ... + +class ImportStarUsed(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, modname: str) -> None: ... + +class ImportStarUsage(Message): + message_args: tuple[str, str] + def __init__(self, filename: str, loc: ast.AST, name: str, from_list: str) -> None: ... + +class UndefinedName(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class DoctestSyntaxError(Message): + message_args: tuple[()] + def __init__(self, filename: str, loc: ast.AST, position: tuple[int, int] | None = None) -> None: ... + +class UndefinedExport(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class UndefinedLocal(Message): + default: ClassVar[str] + builtin: ClassVar[str] + message_args: tuple[str, int] + def __init__(self, filename: str, loc: ast.AST, name: str, orig_loc: ast.AST) -> None: ... + +class DuplicateArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class MultiValueRepeatedKeyLiteral(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, key: str) -> None: ... + +class MultiValueRepeatedKeyVariable(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, key: str) -> None: ... + +class LateFutureImport(Message): + message_args: tuple[()] + def __init__(self, filename: str, loc: ast.AST) -> None: ... + +class FutureFeatureNotDefined(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class UnusedVariable(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, names: str) -> None: ... + +class UnusedAnnotation(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, names: str) -> None: ... + +class UnusedIndirectAssignment(Message): + message_args: tuple[str, str] + def __init__(self, filename: str, loc: ast.AST, name: str) -> None: ... + +class ReturnOutsideFunction(Message): ... +class YieldOutsideFunction(Message): ... +class ContinueOutsideLoop(Message): ... +class BreakOutsideLoop(Message): ... +class DefaultExceptNotLast(Message): ... +class TwoStarredExpressions(Message): ... +class TooManyExpressionsInStarredAssignment(Message): ... +class IfTuple(Message): ... +class AssertTuple(Message): ... + +class ForwardAnnotationSyntaxError(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, annotation: str) -> None: ... + +class RaiseNotImplemented(Message): ... +class InvalidPrintSyntax(Message): ... +class IsLiteral(Message): ... +class FStringMissingPlaceholders(Message): ... +class TStringMissingPlaceholders(Message): ... + +class StringDotFormatExtraPositionalArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_positions: str) -> None: ... + +class StringDotFormatExtraNamedArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_keywords: str) -> None: ... + +class StringDotFormatMissingArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, missing_arguments: str) -> None: ... + +class StringDotFormatMixingAutomatic(Message): ... + +class StringDotFormatInvalidFormat(Message): + message_args: tuple[str] | tuple[Exception] + def __init__(self, filename: str, loc: ast.AST, error: str | Exception) -> None: ... + +class PercentFormatInvalidFormat(Message): + message_args: tuple[str] | tuple[Exception] + def __init__(self, filename: str, loc: ast.AST, error: str | Exception) -> None: ... + +class PercentFormatMixedPositionalAndNamed(Message): ... + +class PercentFormatUnsupportedFormatCharacter(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, c: str) -> None: ... + +class PercentFormatPositionalCountMismatch(Message): + message_args: tuple[int, int] + def __init__(self, filename: str, loc: ast.AST, n_placeholders: int, n_substitutions: int) -> None: ... + +class PercentFormatExtraNamedArguments(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, extra_keywords: str) -> None: ... + +class PercentFormatMissingArgument(Message): + message_args: tuple[str] + def __init__(self, filename: str, loc: ast.AST, missing_arguments: str) -> None: ... + +class PercentFormatExpectedMapping(Message): ... +class PercentFormatExpectedSequence(Message): ... +class PercentFormatStarRequiresSequence(Message): ... diff --git a/stubs/pyflakes/pyflakes/reporter.pyi b/stubs/pyflakes/pyflakes/reporter.pyi new file mode 100644 index 000000000000..f6470e8c298e --- /dev/null +++ b/stubs/pyflakes/pyflakes/reporter.pyi @@ -0,0 +1,9 @@ +from _typeshed import SupportsWrite + +from .messages import Message + +class Reporter: + def __init__(self, warningStream: SupportsWrite[str], errorStream: SupportsWrite[str]) -> None: ... + def unexpectedError(self, filename: str, msg: str) -> None: ... + def syntaxError(self, filename: str, msg: str, lineno: int, offset: int | None, text: str | None) -> None: ... + def flake(self, message: Message) -> None: ... diff --git a/stubs/pyflakes/pyflakes/scripts/__init__.pyi b/stubs/pyflakes/pyflakes/scripts/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi b/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi new file mode 100644 index 000000000000..233bdc97b39f --- /dev/null +++ b/stubs/pyflakes/pyflakes/scripts/pyflakes.pyi @@ -0,0 +1,8 @@ +__all__ = ["check", "checkPath", "checkRecursive", "iterSourceCode", "main"] +from pyflakes.api import ( + check as check, + checkPath as checkPath, + checkRecursive as checkRecursive, + iterSourceCode as iterSourceCode, + main as main, +) diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist.txt b/stubs/pyinstaller/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f04987c54a02 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist.txt @@ -0,0 +1,53 @@ +# fake module, only exists once the app is frozen +pyi_splash + +# Undocumented and clearly not meant to be exposed +PyInstaller\..+?\.logger +PyInstaller.__main__.generate_parser +PyInstaller.__main__.run_build +PyInstaller.__main__.run_makespec +PyInstaller.utils.hooks.conda.lib_dir + +# A mix of modules meant to be private, and shallow incomplete type references for other modules +PyInstaller\.building\.build_main\..* +PyInstaller.building.datastruct.unique_name +PyInstaller\.depend\.analysis\..* +PyInstaller\.isolated\._parent\..* +PyInstaller\.lib\.modulegraph\.modulegraph\.\w+? + +# Most modules are not meant to be used, yet are not marked as private +PyInstaller\.archive(\.\w+)* +PyInstaller.building.icon +PyInstaller.building.makespec +PyInstaller.building.osx +PyInstaller.building.splash_templates +PyInstaller.building.templates +PyInstaller.building.utils +PyInstaller.config +PyInstaller.configure +PyInstaller.depend.bindepend +PyInstaller.depend.bytecode +PyInstaller.depend.dylib +PyInstaller.depend.imphook +PyInstaller.depend.utils +PyInstaller.exceptions +PyInstaller\.hooks(\.[\w-]+)* # weird hyphens in runtime module names +PyInstaller.lib.modulegraph.__main__ +PyInstaller.lib.modulegraph.find_modules +PyInstaller.lib.modulegraph.util +PyInstaller\.loader(\.\w+)* +PyInstaller.log +PyInstaller\.utils\.cliutils(\.\w+)* +PyInstaller.utils.conftest +PyInstaller.utils.hooks.django +PyInstaller.utils.hooks.gi +PyInstaller.utils.hooks.qt +PyInstaller.utils.hooks.setuptools +PyInstaller.utils.misc +PyInstaller.utils.osx +PyInstaller.utils.run_tests +PyInstaller.utils.tests +PyInstaller.utils.win32.icon +PyInstaller.utils.win32.winmanifest +PyInstaller.utils.win32.winresource +PyInstaller.utils.win32.winutils diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..93e1392cfd96 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,2 @@ +# Module can't be imported at runtime on non-win32 platforms +PyInstaller.utils.win32.versioninfo diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..93e1392cfd96 --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,2 @@ +# Module can't be imported at runtime on non-win32 platforms +PyInstaller.utils.win32.versioninfo diff --git a/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt b/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..72a93bf6d30a --- /dev/null +++ b/stubs/pyinstaller/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1 @@ +PyInstaller\.utils\.win32\.versioninfo\.\w+? diff --git a/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py b/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py new file mode 100644 index 000000000000..dc16ebe27d98 --- /dev/null +++ b/stubs/pyinstaller/@tests/test_cases/check_versioninfo.py @@ -0,0 +1,63 @@ +from PyInstaller.utils.win32.versioninfo import ( + FixedFileInfo, + StringFileInfo, + StringStruct, + StringTable, + VarFileInfo, + VarStruct, + VSVersionInfo, +) + +# Everything below this line is the content from running `pyi-grab_version python3` +# ============================================================================== + +# UTF-8 +# +# For more details about fixed file info 'ffi' see: +# http://msdn.microsoft.com/en-us/library/ms646997.aspx +VSVersionInfo( + ffi=FixedFileInfo( + # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) + # Set not needed items to zero 0. + filevers=(3, 13, 1150, 1013), + prodvers=(3, 13, 1150, 1013), + # Contains a bitmask that specifies the valid bits 'flags'r + mask=0x3F, + # Contains a bitmask that specifies the Boolean attributes of the file. + flags=0x0, + # The operating system for which this file was designed. + # 0x4 - NT and there is no need to change it. + OS=0x4, + # The general type of file. + # 0x1 - the file is an application. + fileType=0x2, + # The function of the file. + # 0x0 - the function is not defined for this fileType + subtype=0x0, + # Creation date and time stamp. + date=(0, 0), + ), + kids=[ + StringFileInfo( + [ + StringTable( + "000004b0", + [ + StringStruct("CompanyName", "Python Software Foundation"), + StringStruct("FileDescription", "Python Core"), + StringStruct("FileVersion", "3.13.1"), + StringStruct("InternalName", "Python DLL"), + StringStruct( + "LegalCopyright", + "Copyright © 2001-2024 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.", + ), + StringStruct("OriginalFilename", "python3.dll"), + StringStruct("ProductName", "Python"), + StringStruct("ProductVersion", "3.13.1"), + ], + ) + ] + ), + VarFileInfo([VarStruct("Translation", [0, 1200])]), + ], +) diff --git a/stubs/pyinstaller/METADATA.toml b/stubs/pyinstaller/METADATA.toml new file mode 100644 index 000000000000..909efab1715d --- /dev/null +++ b/stubs/pyinstaller/METADATA.toml @@ -0,0 +1,2 @@ +version = "6.21.*" +upstream-repository = "https://github.com/pyinstaller/pyinstaller" diff --git a/stubs/pyinstaller/PyInstaller/__init__.pyi b/stubs/pyinstaller/PyInstaller/__init__.pyi new file mode 100644 index 000000000000..a36cbd690d8b --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/__init__.pyi @@ -0,0 +1,12 @@ +from typing import Final +from typing_extensions import LiteralString + +from PyInstaller import compat as compat + +__all__ = ("HOMEPATH", "PLATFORM", "__version__", "DEFAULT_DISTPATH", "DEFAULT_SPECPATH", "DEFAULT_WORKPATH") +__version__: Final[str] +HOMEPATH: Final[str] +DEFAULT_SPECPATH: Final[str] +DEFAULT_DISTPATH: Final[str] +DEFAULT_WORKPATH: Final[str] +PLATFORM: Final[LiteralString] diff --git a/stubs/pyinstaller/PyInstaller/__main__.pyi b/stubs/pyinstaller/PyInstaller/__main__.pyi new file mode 100644 index 000000000000..9f6397bdab29 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/__main__.pyi @@ -0,0 +1,12 @@ +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import TypeAlias + +# Used to update PyInstaller.config.CONF +_PyIConfig: TypeAlias = ( + SupportsKeysAndGetItem[str, bool | str | list[str] | None] | Iterable[tuple[str, bool | str | list[str] | None]] +) + +# https://pyinstaller.org/en/stable/usage.html#running-pyinstaller-from-python-code +def run(pyi_args: Iterable[str] | None = None, pyi_config: _PyIConfig | None = None) -> None: ... +def check_unsafe_privileges() -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/building/__init__.pyi b/stubs/pyinstaller/PyInstaller/building/__init__.pyi new file mode 100644 index 000000000000..bf87a78779b4 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/__init__.pyi @@ -0,0 +1,7 @@ +from typing import TypeAlias + +# PyiBlockCipher is deprecated and misleads users into thinking it adds any security. Runtime deprecation warning: +# DEPRECATION: Bytecode encryption will be removed in PyInstaller v6. +# Please remove cipher and block_cipher parameters from your spec file to avoid breakages on upgrade. +# For the rationale/alternatives see https://github.com/pyinstaller/pyinstaller/pull/6999 +_PyiBlockCipher: TypeAlias = None # noqa: Y047 # Used by other modules diff --git a/stubs/pyinstaller/PyInstaller/building/api.pyi b/stubs/pyinstaller/PyInstaller/building/api.pyi new file mode 100644 index 000000000000..97e2c340c5a9 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/api.pyi @@ -0,0 +1,175 @@ +# PYZ, EXE and COLLECT referenced in https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation +# MERGE is referenced in https://pyinstaller.org/en/stable/spec-files.html#example-merge-spec-file +# hide_console referenced in https://pyinstaller.org/en/stable/feature-notes.html#automatic-hiding-and-minimization-of-console-window-under-windows +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +import sys +from _typeshed import FileDescriptorOrPath, StrOrBytesPath, StrPath, Unused +from collections.abc import Iterable, Mapping, Sequence +from types import CodeType +from typing import ClassVar, Final, Literal, TypeAlias + +from PyInstaller.building import _PyiBlockCipher +from PyInstaller.building.build_main import Analysis +from PyInstaller.building.datastruct import Target, _TOCTuple +from PyInstaller.building.splash import Splash +from PyInstaller.utils.win32.versioninfo import VSVersionInfo + +if sys.platform == "darwin": + _TargetArch: TypeAlias = Literal["x86_64", "arm64", "universal2"] + _SupportedTargetArchParam: TypeAlias = _TargetArch | None + _CodesignIdentity: TypeAlias = str | None + _CodesignIdentityParam: TypeAlias = str | None +else: + _TargetArch: TypeAlias = None + _SupportedTargetArchParam: TypeAlias = Unused + _CodesignIdentity: TypeAlias = None + _CodesignIdentityParam: TypeAlias = Unused + +if sys.platform == "win32": + _Icon: TypeAlias = list[StrPath] | str + _IconParam: TypeAlias = StrPath | list[StrPath] | None +elif sys.platform == "darwin": + _Icon: TypeAlias = list[StrPath] | None + _IconParam: TypeAlias = StrPath | list[StrPath] | None +else: + _Icon: TypeAlias = None + _IconParam: TypeAlias = Unused + +if sys.platform == "win32": + _VersionSrc: TypeAlias = VSVersionInfo | None + _VersionParam: TypeAlias = VSVersionInfo | StrOrBytesPath | None + _Manifest: TypeAlias = bytes + _ManifestParam: TypeAlias = str | None +else: + _VersionSrc: TypeAlias = None + _VersionParam: TypeAlias = Unused + _Manifest: TypeAlias = None + _ManifestParam: TypeAlias = Unused + +_HideConsole: TypeAlias = Literal["hide-early", "minimize-early", "hide-late", "minimize-late"] | None + +class PYZ(Target): + name: str + cipher: _PyiBlockCipher + dependencies: list[_TOCTuple] + toc: list[_TOCTuple] + code_dict: dict[str, CodeType] + def __init__(self, *tocs: Iterable[_TOCTuple], name: str | None = None, cipher: _PyiBlockCipher = None) -> None: ... + def assemble(self) -> None: ... + +class PKG(Target): + xformdict: ClassVar[dict[str, str]] + toc: list[_TOCTuple] + cdict: Mapping[str, bool] + python_lib_name: str + name: str + exclude_binaries: bool + strip_binaries: bool + upx_binaries: bool + upx_exclude: Iterable[str] + target_arch: _TargetArch | None + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + def __init__( + self, + toc: Iterable[_TOCTuple], + python_lib_name: str, + name: str | None = None, + cdict: Mapping[str, bool] | None = None, + exclude_binaries: bool = False, + strip_binaries: bool = False, + upx_binaries: bool = False, + upx_exclude: Iterable[str] | None = None, + target_arch: _SupportedTargetArchParam = None, + codesign_identity: _CodesignIdentityParam = None, + entitlements_file: FileDescriptorOrPath | None = None, + ) -> None: ... + def assemble(self) -> None: ... + +class EXE(Target): + exclude_binaries: bool + bootloader_ignore_signals: bool + console: bool + hide_console: _HideConsole + disable_windowed_traceback: bool + debug: bool + name: str + icon: _Icon + versrsrc: _VersionSrc + manifest: _Manifest + embed_manifest: bool + resources: Sequence[str] + strip: bool + upx_exclude: Iterable[str] + runtime_tmpdir: str | None + contents_directory: str | None + append_pkg: bool + uac_admin: bool + uac_uiaccess: bool + argv_emulation: bool + target_arch: _TargetArch + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + upx: bool + pkgname: str + toc: list[_TOCTuple] + pkg: PKG + dependencies: list[_TOCTuple] + exefiles: list[_TOCTuple] + def __init__( + self, + *args: Iterable[_TOCTuple] | PYZ | Splash, + exclude_binaries: bool = False, + bootloader_ignore_signals: bool = False, + console: bool = True, + hide_console: _HideConsole = None, + disable_windowed_traceback: bool = False, + debug: bool = False, + name: str | None = None, + icon: _IconParam = None, + version: _VersionParam = None, + manifest: _ManifestParam = None, + embed_manifest: Literal[True] = True, + resources: Sequence[str] = ..., + strip: bool = False, + upx_exclude: Iterable[str] = ..., + runtime_tmpdir: str | None = None, + contents_directory: str = "_internal", + append_pkg: bool = True, + uac_admin: bool = False, + uac_uiaccess: bool = False, + argv_emulation: bool = False, + target_arch: _SupportedTargetArchParam = None, + codesign_identity: _CodesignIdentityParam = None, + entitlements_file: FileDescriptorOrPath | None = None, + upx: bool = False, + cdict: Mapping[str, bool] | None = None, + ) -> None: ... + mtm: float + def assemble(self) -> None: ... + +class COLLECT(Target): + strip_binaries: bool + upx_exclude: Iterable[str] + console: bool + target_arch: _TargetArch | None + codesign_identity: _CodesignIdentity + entitlements_file: FileDescriptorOrPath | None + upx_binaries: bool + name: str + toc: list[_TOCTuple] + def __init__( + self, + *args: Iterable[_TOCTuple] | EXE, + strip: bool = False, + upx_exclude: Iterable[str] = ..., + upx: bool = False, + name: str, + ) -> None: ... + def assemble(self) -> None: ... + +class MERGE: + def __init__(self, *args: tuple[Analysis, Unused, str]) -> None: ... + +UNCOMPRESSED: Final = False +COMPRESSED: Final = True diff --git a/stubs/pyinstaller/PyInstaller/building/build_main.pyi b/stubs/pyinstaller/PyInstaller/building/build_main.pyi new file mode 100644 index 000000000000..a5d93774a9f7 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/build_main.pyi @@ -0,0 +1,55 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from typing import Any, Literal + +from PyInstaller.building import _PyiBlockCipher +from PyInstaller.building.datastruct import Target, _TOCTuple + +# Referenced in: https://pyinstaller.org/en/stable/hooks.html#PyInstaller.utils.hooks.get_hook_config +# Not to be imported during runtime, but is the type reference for hooks and analysis configuration +# Also referenced in https://pyinstaller.org/en/stable/spec-files.html +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +class Analysis(Target): + # https://pyinstaller.org/en/stable/hooks-config.html#hook-configuration-options + hooksconfig: dict[str, dict[str, object]] + # https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation + # https://pyinstaller.org/en/stable/feature-notes.html + pure: list[_TOCTuple] + zipped_data: list[_TOCTuple] + # https://pyinstaller.org/en/stable/spec-files.html#giving-run-time-python-options + # https://pyinstaller.org/en/stable/spec-files.html#the-splash-target + scripts: list[_TOCTuple] + # https://pyinstaller.org/en/stable/feature-notes.html#practical-examples + binaries: list[_TOCTuple] + zipfiles: list[_TOCTuple] + datas: list[_TOCTuple] + + inputs: list[str] + dependencies: list[_TOCTuple] + noarchive: bool + optimize: int + pathex: list[StrPath] + hiddenimports: list[str] + hookspath: list[tuple[StrPath, int]] + excludes: list[str] + custom_runtime_hooks: list[StrPath] + # https://pyinstaller.org/en/stable/hooks.html#hook-global-variables + module_collection_mode: dict[str, str] + def __init__( + self, + scripts: Iterable[StrPath], + pathex: Iterable[StrPath] | None = None, + binaries: Iterable[tuple[StrPath, StrPath]] | None = None, + datas: Iterable[tuple[StrPath, StrPath]] | None = None, + hiddenimports: Iterable[str] | None = None, + hookspath: Iterable[StrPath] | None = None, + hooksconfig: dict[str, dict[str, Any]] | None = None, + excludes: Iterable[str] | None = None, + runtime_hooks: Iterable[StrPath] | None = None, + cipher: _PyiBlockCipher = None, + win_no_prefer_redirects: bool = False, + win_private_assemblies: bool = False, + noarchive: bool = False, + module_collection_mode: dict[str, str] | None = None, + optimize: Literal[-1, 0, 1, 2] | None = -1, + ) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/building/datastruct.pyi b/stubs/pyinstaller/PyInstaller/building/datastruct.pyi new file mode 100644 index 000000000000..0c3878a0b9ce --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/datastruct.pyi @@ -0,0 +1,47 @@ +# https://pyinstaller.org/en/stable/advanced-topics.html#the-toc-and-tree-classes +from collections.abc import Iterable, Sequence +from typing import ClassVar, Literal, SupportsIndex, TypeAlias +from typing_extensions import LiteralString, Self + +_TypeCode: TypeAlias = Literal["DEPENDENCY", "SYMLINK", "DATA", "BINARY", "EXECUTABLE", "EXTENSION", "OPTION"] +_TOCTuple: TypeAlias = tuple[str, str | None, _TypeCode | None] + +class TOC(list[_TOCTuple]): + filenames: set[str] + def __init__(self, initlist: Iterable[_TOCTuple] | None = None) -> None: ... + def append(self, entry: _TOCTuple) -> None: ... + def insert(self, pos: SupportsIndex, entry: _TOCTuple) -> None: ... + def __add__(self, other: Iterable[_TOCTuple]) -> TOC: ... # type: ignore[override] + def __radd__(self, other: Iterable[_TOCTuple]) -> TOC: ... + def __iadd__(self, other: Iterable[_TOCTuple]) -> Self: ... # type: ignore[override] + def extend(self, other: Iterable[_TOCTuple]) -> None: ... + def __sub__(self, other: Iterable[_TOCTuple]) -> TOC: ... + def __rsub__(self, other: Iterable[_TOCTuple]) -> TOC: ... + # slicing a TOC is not supported, but has a special case for slice(None, None, None) + def __setitem__(self, key: int | slice, value: Iterable[_TOCTuple]) -> None: ... # type: ignore[override] + +class Target: + invcnum: ClassVar[int] + tocfilename: LiteralString + tocbasename: LiteralString + dependencies: list[_TOCTuple] + def __init__(self) -> None: ... + def __postinit__(self) -> None: ... + +class Tree(Target, list[_TOCTuple]): + root: str | None + prefix: str | None + excludes: Sequence[str] + typecode: _TypeCode + def __init__( + self, + root: str | None = None, + prefix: str | None = None, + excludes: Sequence[str] | None = None, + typecode: _TypeCode = "DATA", + ) -> None: ... + def assemble(self) -> None: ... + +def normalize_toc(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... +def normalize_pyz_toc(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... +def toc_process_symbolic_links(toc: Iterable[_TOCTuple]) -> list[_TOCTuple]: ... diff --git a/stubs/pyinstaller/PyInstaller/building/splash.pyi b/stubs/pyinstaller/PyInstaller/building/splash.pyi new file mode 100644 index 000000000000..d7723bc76f53 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/building/splash.pyi @@ -0,0 +1,49 @@ +from _typeshed import StrPath + +from PyInstaller.building.datastruct import Target, _TOCTuple +from PyInstaller.utils.hooks.tcl_tk import TclTkInfo + +# Referenced in https://pyinstaller.org/en/stable/spec-files.html#example-merge-spec-file +# Not to be imported during runtime, but is the type reference for spec files which are executed as python code +class Splash(Target): + image_file: str + full_tk: bool + tcl_lib: str + tk_lib: str + name: str + script_name: StrPath + minify_script: bool + max_img_size: tuple[int, int] + text_pos: tuple[int, int] | None + text_size: int + text_font: str + text_color: str + text_default: str + always_on_top: bool + uses_tkinter: bool + script: str + splash_requirements: set[str] + binaries: list[_TOCTuple] + def __init__( + self, + image_file: StrPath, + binaries: list[_TOCTuple], + datas: list[_TOCTuple], + *, + text_pos: tuple[int, int] | None = ..., + text_size: int = 12, + text_font: str = ..., + text_color: str = "black", + text_default: str = "Initializing", + full_tk: bool = False, + minify_script: bool = True, + name: str = ..., + script_name: StrPath = ..., + max_img_size: tuple[int, int] | None = (760, 480), + always_on_top: bool = True, + ) -> None: ... + def assemble(self) -> None: ... + # This private method is the only way to match Splash Screen support validation without triggering an actual build + @staticmethod + def _check_tcl_tk_compatibility(tcltk_info: TclTkInfo) -> None: ... + def generate_script(self) -> str: ... diff --git a/stubs/pyinstaller/PyInstaller/compat.pyi b/stubs/pyinstaller/PyInstaller/compat.pyi new file mode 100644 index 000000000000..02a3113ffe6f --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/compat.pyi @@ -0,0 +1,87 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.compat +from _typeshed import FileDescriptorOrPath +from collections.abc import Iterable +from types import ModuleType +from typing import Final, Literal, overload + +strict_collect_mode: bool +is_64bits: Final[bool] +is_py35: Final = True +is_py36: Final = True +is_py37: Final = True +is_py38: Final = True +is_py39: Final = True +is_py310: Final = True +is_py311: Final[bool] +is_py312: Final[bool] +is_py313: Final[bool] +is_py314: Final[bool] +is_py315: Final[bool] +is_win: Final[bool] +is_win_10: Final[bool] +is_win_11: Final[bool] +is_win_wine: Final[bool] +is_cygwin: Final[bool] +is_darwin: Final[bool] +is_android: Final[bool] +is_linux: Final[bool] +is_solar: Final[bool] +is_aix: Final[bool] +is_freebsd: Final[bool] +is_openbsd: Final[bool] +is_hpux: Final[bool] +is_unix: Final[bool] +is_musl: Final[bool] +is_termux: Final[bool] +is_macos_11_compat: Final[bool] +is_macos_11_native: Final[bool] +is_macos_11: Final[bool] +is_nogil: Final[bool] +base_prefix: Final[str] +is_venv: Final[bool] +is_virtualenv: Final[bool] +is_conda: Final[bool] +is_pure_conda: Final[bool] +python_executable: Final[str] +is_ms_app_store: Final[bool] +BYTECODE_MAGIC: Final[bytes] +EXTENSION_SUFFIXES: Final[list[str]] +ALL_SUFFIXES: Final[list[str]] + +architecture: Final[Literal["64bit", "n32bit", "32bit"]] +system: Final[Literal["Cygwin", "Linux", "Darwin", "Java", "Windows"]] +machine: Final[ + Literal["AMD64", "x86", "ARM64", "sw_64", "loongarch64", "arm", "intel", "ppc", "mips", "riscv", "s390x", "unknown"] | None +] + +def is_wine_dll(filename: FileDescriptorOrPath) -> bool: ... + +@overload +def getenv(name: str, default: str) -> str: ... +@overload +def getenv(name: str, default: None = None) -> str | None: ... + +def setenv(name: str, value: str) -> None: ... +def unsetenv(name: str) -> None: ... +def exec_command( + *cmdargs: str, encoding: str | None = None, raise_enoent: bool | None = None, **kwargs: int | bool | Iterable[int] | None +) -> str: ... +def exec_command_rc(*cmdargs: str, **kwargs: float | bool | Iterable[int] | None) -> int: ... +def exec_command_all( + *cmdargs: str, encoding: str | None = None, **kwargs: int | bool | Iterable[int] | None +) -> tuple[int, str, str]: ... +def exec_python(*args: str, **kwargs: str | None) -> str: ... +def exec_python_rc(*args: str, **kwargs: str | None) -> int: ... +def getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ... +def importlib_load_source(name: str, pathname: str) -> ModuleType: ... + +PY3_BASE_MODULES: Final[set[str]] +PURE_PYTHON_MODULE_TYPES: Final[set[str]] +SPECIAL_MODULE_TYPES: Final[set[str]] +BINARY_MODULE_TYPES: Final[set[str]] +VALID_MODULE_TYPES: Final[set[str]] +BAD_MODULE_TYPES: Final[set[str]] +ALL_MODULE_TYPES: Final[set[str]] +MODULE_TYPES_TO_TOC_DICT: Final[dict[str, str]] + +def check_requirements() -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/depend/__init__.pyi b/stubs/pyinstaller/PyInstaller/depend/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/depend/analysis.pyi b/stubs/pyinstaller/PyInstaller/depend/analysis.pyi new file mode 100644 index 000000000000..8e6f37c238d3 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/depend/analysis.pyi @@ -0,0 +1,27 @@ +# https://pyinstaller.org/en/stable/hooks.html#the-pre-safe-import-module-psim-api-method + +# The documentation explicitly mentions that "Normally you do not need to know about the module-graph." +# However, some PyiModuleGraph typed class attributes are still documented as existing in imphookapi. +from _typeshed import Incomplete, StrPath, SupportsKeysAndGetItem +from collections.abc import Iterable +from typing import TypeAlias + +from PyInstaller.lib.modulegraph.modulegraph import Alias, Node + +_LazyNode: TypeAlias = Iterable[Node] | Iterable[str] | Alias | None +# from altgraph.Graph import Graph +_Graph: TypeAlias = Incomplete + +class PyiModuleGraph: # incomplete + def __init__( + self, + pyi_homepath: str, + user_hook_dirs: Iterable[StrPath] = (), + excludes: Iterable[str] = (), + *, + path: Iterable[str] | None = None, + replace_paths: Iterable[tuple[StrPath, StrPath]] = ..., + implies: SupportsKeysAndGetItem[str, _LazyNode] | Iterable[tuple[str, _LazyNode]] = ..., + graph: _Graph | None = None, + debug: bool = False, + ) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi b/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi new file mode 100644 index 000000000000..286aac070973 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/depend/imphookapi.pyi @@ -0,0 +1,71 @@ +# https://pyinstaller.org/en/stable/hooks-config.html#adding-an-option-to-the-hook `hook_api` is a PostGraphAPI +# Nothing in this module is meant to be initialized externally. +# Instances are exposed through hooks during build. + +from _typeshed import StrOrBytesPath +from collections.abc import Generator, Iterable +from types import CodeType +from typing import Literal + +from PyInstaller.building.build_main import Analysis +from PyInstaller.building.datastruct import TOC +from PyInstaller.depend.analysis import PyiModuleGraph +from PyInstaller.lib.modulegraph.modulegraph import Package + +# https://pyinstaller.org/en/stable/hooks.html#the-pre-safe-import-module-psim-api-method +class PreSafeImportModuleAPI: + module_basename: str + module_name: str + def __init__( + self, module_graph: PyiModuleGraph, module_basename: str, module_name: str, parent_package: Package | None + ) -> None: ... + @property + def module_graph(self) -> PyiModuleGraph: ... + @property + def parent_package(self) -> Package | None: ... + def add_runtime_module(self, module_name: str) -> None: ... + def add_runtime_package(self, package_name: str) -> None: ... + def add_alias_module(self, real_module_name: str, alias_module_name: str) -> None: ... + def append_package_path(self, directory: str) -> None: ... + +# https://pyinstaller.org/en/stable/hooks.html#the-pre-find-module-path-pfmp-api-method +class PreFindModulePathAPI: + search_dirs: Iterable[StrOrBytesPath] + def __init__(self, module_graph: PyiModuleGraph, module_name: str, search_dirs: Iterable[StrOrBytesPath]) -> None: ... + @property + def module_graph(self) -> PyiModuleGraph: ... + @property + def module_name(self) -> str: ... + +# https://pyinstaller.org/en/stable/hooks.html#the-hook-hook-api-function +class PostGraphAPI: + module_graph: PyiModuleGraph + module: Package + def __init__(self, module_name: str, module_graph: PyiModuleGraph, analysis: Analysis) -> None: ... + @property + def __file__(self) -> str: ... + @property + def __path__(self) -> tuple[str, ...] | None: ... + @property + def __name__(self) -> str: ... + # Compiled code. See stdlib.builtins.compile + @property + def co(self) -> CodeType: ... + @property + def analysis(self) -> Analysis: ... + @property + def name(self) -> str: ... + @property + def graph(self) -> PyiModuleGraph: ... + @property + def node(self) -> Package: ... + @property + def imports(self) -> Generator[Package]: ... + def add_imports(self, *module_names: str) -> None: ... + def del_imports(self, *module_names: str) -> None: ... + def add_binaries(self, binaries: TOC | Iterable[tuple[StrOrBytesPath, StrOrBytesPath]]) -> None: ... + def add_datas(self, datas: TOC | Iterable[tuple[StrOrBytesPath, StrOrBytesPath]]) -> None: ... + def set_module_collection_mode( + self, name: str | None, mode: Literal["pyz", "pyc", "py", "pyz+py", "py+pyz"] | None + ) -> None: ... + def add_bindepend_symlink_suppression_pattern(self, pattern: str) -> None: ... diff --git a/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi b/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi new file mode 100644 index 000000000000..6f084bfc40ea --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/isolated/__init__.pyi @@ -0,0 +1,2 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.isolated +from PyInstaller.isolated._parent import Python as Python, call as call, decorate as decorate diff --git a/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi b/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi new file mode 100644 index 000000000000..78b20d73f9cb --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/isolated/_parent.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable +from types import TracebackType +from typing import ParamSpec, TypeVar +from typing_extensions import Self + +_AC = TypeVar("_AC", bound=Callable[..., object]) +_R = TypeVar("_R") +_P = ParamSpec("_P") + +class Python: + def __init__(self, strict_mode: bool | None = None) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def call(self, function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + +def call(function: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... +def decorate(function: _AC) -> _AC: ... diff --git a/stubs/pyinstaller/PyInstaller/lib/__init__.pyi b/stubs/pyinstaller/PyInstaller/lib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/lib/modulegraph/__init__.pyi b/stubs/pyinstaller/PyInstaller/lib/modulegraph/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi b/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi new file mode 100644 index 000000000000..2783e2249008 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/lib/modulegraph/modulegraph.pyi @@ -0,0 +1,57 @@ +# Partial typing of the vendored modulegraph package. +# We reference the vendored package rather than depending on the original untyped module. +# Anything not referenced in the PyInstaller stubs doesn't need to be added here. + +from types import CodeType +from typing import Protocol, type_check_only + +@type_check_only +class _SupportsGraphident(Protocol): + graphident: str + +# code, filename and packagepath are always initialized to None. But they can be given a value later. +class Node: + # Compiled code. See stdlib.builtins.compile + __slots__ = [ + "code", + "filename", + "graphident", + "identifier", + "packagepath", + "_deferred_imports", + "_global_attr_names", + "_starimported_ignored_module_names", + "_submodule_basename_to_node", + ] + code: CodeType | None + filename: str | None + graphident: str + identifier: str + packagepath: str | None + def __init__(self, identifier: str) -> None: ... + def is_global_attr(self, attr_name: str) -> bool: ... + def is_submodule(self, submodule_basename: str) -> bool: ... + def add_global_attr(self, attr_name: str) -> None: ... + def add_global_attrs_from_module(self, target_module: Node) -> None: ... + def add_submodule(self, submodule_basename: str, submodule_node: Node) -> None: ... + def get_submodule(self, submodule_basename: str) -> Node: ... + def get_submodule_or_none(self, submodule_basename: str) -> Node | None: ... + def remove_global_attr_if_found(self, attr_name: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: _SupportsGraphident) -> bool: ... + def __le__(self, other: _SupportsGraphident) -> bool: ... + def __gt__(self, other: _SupportsGraphident) -> bool: ... + def __ge__(self, other: _SupportsGraphident) -> bool: ... + def infoTuple(self) -> tuple[str]: ... + +class Alias(str): ... + +class BaseModule(Node): + filename: str + packagepath: str + def __init__(self, name: str, filename: str | None = None, path: str | None = None) -> None: ... + # Returns a tuple of length 0, 1, 2, or 3 + def infoTuple(self) -> tuple[str, ...]: ... # type: ignore[override] + +class Package(BaseModule): ... diff --git a/stubs/pyinstaller/PyInstaller/utils/__init__.pyi b/stubs/pyinstaller/PyInstaller/utils/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi new file mode 100644 index 000000000000..bab6ffebfa1b --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/__init__.pyi @@ -0,0 +1,76 @@ +# https://pyinstaller.org/en/stable/hooks.html + +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Callable, Iterable +from typing import Any, Final, Literal + +from PyInstaller import HOMEPATH as HOMEPATH +from PyInstaller.depend.imphookapi import PostGraphAPI +from PyInstaller.utils.hooks import conda + +conda_support = conda + +PY_IGNORE_EXTENSIONS: Final[set[str]] +hook_variables: dict[str, str] + +def exec_statement(statement: str) -> str | int: ... +def exec_statement_rc(statement: str) -> str | int: ... +def eval_statement(statement: str) -> Any | Literal[""]: ... +def get_pyextension_imports(module_name: str) -> list[str]: ... +def get_homebrew_path(formula: str = "") -> str | None: ... +def remove_prefix(string: str, prefix: str) -> str: ... +def remove_suffix(string: str, suffix: str) -> str: ... +def remove_file_extension(filename: str) -> str: ... +def can_import_module(module_name: str) -> bool: ... +def get_module_attribute(module_name: str, attr_name: str) -> Any: ... +def get_module_file_attribute(package: str) -> str | None: ... +def get_pywin32_module_file_attribute(module_name: str) -> str | None: ... +def check_requirement(requirement: str) -> bool: ... +def is_module_satisfies(requirements: str, version: None = None, version_attr: None = None) -> bool: ... +def is_package(module_name: str) -> bool: ... +def get_all_package_paths(package: str) -> list[str]: ... +def package_base_path(package_path: str, package: str) -> str: ... +def get_package_paths(package: str) -> tuple[str, str]: ... +def collect_submodules( + package: str, filter: Callable[[str], bool] = ..., on_error: Literal["ignore", "warn once", "warn", "raise"] = "warn once" +) -> list[str]: ... +def is_module_or_submodule(name: str, mod_or_submod: str) -> bool: ... + +PY_DYLIB_PATTERNS: Final[list[str]] + +def collect_dynamic_libs( + package: str, destdir: object = None, search_patterns: Iterable[str] = ["*.dll", "*.dylib", "lib*.so"] +) -> list[tuple[str, str]]: ... +def collect_data_files( + package: str, + include_py_files: bool = False, + subdir: StrPath | None = None, + excludes: Iterable[str] | None = None, + includes: Iterable[str] | None = None, +) -> list[tuple[str, str]]: ... +def collect_system_data_files( + path: str, destdir: StrPath | None = None, include_py_files: bool = False +) -> list[tuple[str, str]]: ... +def copy_metadata(package_name: str, recursive: bool = False) -> list[tuple[str, str]]: ... +def get_installer(dist_name: str) -> str | None: ... +def collect_all( + package_name: str, + include_py_files: bool = True, + filter_submodules: Callable[[str], bool] = ..., + exclude_datas: Iterable[str] | None = None, + include_datas: Iterable[str] | None = None, + on_error: Literal["ignore", "warn once", "warn", "raise"] = "warn once", +) -> tuple[list[tuple[str, str]], list[tuple[str, str]], list[str]]: ... +def collect_entry_point(name: str) -> tuple[list[tuple[str, str]], list[str]]: ... +def get_hook_config(hook_api: PostGraphAPI, module_name: str, key: str) -> None: ... +def include_or_exclude_file( + filename: StrOrBytesPath, + include_list: Iterable[StrOrBytesPath] | None = None, + exclude_list: Iterable[StrOrBytesPath] | None = None, +) -> bool: ... +def collect_delvewheel_libs_directory( + package_name: str, + libdir_name: StrPath | None = None, + datas: list[tuple[str, str]] | None = None, + binaries: list[tuple[str, str]] | None = None, +) -> tuple[list[tuple[str, str]], list[tuple[str, str]]]: ... diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi new file mode 100644 index 000000000000..0fc169607cc0 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/conda.pyi @@ -0,0 +1,48 @@ +# https://pyinstaller.org/en/stable/hooks.html#module-PyInstaller.utils.hooks.conda + +from _typeshed import StrOrBytesPath +from collections.abc import Iterable +from importlib.metadata import PackagePath as _PackagePath +from pathlib import Path +from typing import Final, TypedDict, type_check_only + +CONDA_ROOT: Final[Path] +CONDA_META_DIR: Final[Path] +PYTHONPATH_PREFIXES: Final[list[Path]] + +@type_check_only +class _RawDict(TypedDict): + name: str + version: str + files: list[StrOrBytesPath] + depends: list[str] + +class Distribution: + raw: _RawDict + name: str + version: str + files: list[PackagePath] + dependencies: list[str] + packages: list[str] + def __init__(self, json_path: str) -> None: ... + @classmethod + def from_name(cls, name: str) -> Distribution: ... + @classmethod + def from_package_name(cls, name: str) -> Distribution: ... + +# distribution and package_distribution are meant to be used and are not internal helpers +distribution = Distribution.from_name +package_distribution = Distribution.from_package_name + +class PackagePath(_PackagePath): + def locate(self) -> Path: ... + +def walk_dependency_tree(initial: str, excludes: Iterable[str] | None = None) -> dict[str, Distribution]: ... +def requires(name: str, strip_versions: bool = False) -> list[str]: ... +def files(name: str, dependencies: bool = False, excludes: Iterable[str] | None = None) -> list[PackagePath]: ... +def collect_dynamic_libs( + name: str, dest: str = ".", dependencies: bool = True, excludes: Iterable[str] | None = None +) -> list[tuple[str, str]]: ... + +distributions: dict[str, Distribution] +distributions_by_package: dict[str | None, Distribution] diff --git a/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi b/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi new file mode 100644 index 000000000000..1a3f196f8f02 --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/hooks/tcl_tk.pyi @@ -0,0 +1,20 @@ +from typing import Final + +class TclTkInfo: + TCL_ROOTNAME: Final = "_tcl_data" + TK_ROOTNAME: Final = "_tk_data" + def __init__(self) -> None: ... + available: bool + tkinter_extension_file: str | None + tcl_version: tuple[int, int] | None + tk_version: tuple[int, int] | None + tcl_threaded: bool + tcl_data_dir: str | None + tk_data_dir: str | None + tcl_module_dir: str | None + is_macos_system_framework: bool + tcl_shared_library: str | None + tk_shared_library: str | None + data_files: list[tuple[str, str, str]] + +tcltk_info: TclTkInfo diff --git a/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi b/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi new file mode 100644 index 000000000000..1e2e7c6425ef --- /dev/null +++ b/stubs/pyinstaller/PyInstaller/utils/win32/versioninfo.pyi @@ -0,0 +1,98 @@ +from _typeshed import SliceableBuffer, Unused +from collections.abc import Sequence +from typing import Any, Protocol, TypeAlias, type_check_only + +_FourIntSequence: TypeAlias = Sequence[int] +_TwoIntSequence: TypeAlias = Sequence[int] + +@type_check_only +class _Kid(Protocol): + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "", /) -> str: ... + +# All the classes below are used in version_file_info generated by `pyi-grab_version` +# See: https://pyinstaller.org/en/stable/usage.html#capturing-windows-version-data + +# VSVersionInfo is also by other types referenced in https://pyinstaller.org/en/stable/spec-files.html#spec-file-operation +class VSVersionInfo: + ffi: FixedFileInfo | None + kids: list[_Kid] + def __init__(self, ffi: FixedFileInfo | None = None, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class FixedFileInfo: + sig: int + strucVersion: int + fileVersionMS: int + fileVersionLS: int + productVersionMS: int + productVersionLS: int + fileFlagsMask: int + fileFlags: int + fileOS: int + fileType: int + fileSubtype: int + fileDateMS: int + fileDateLS: int + def __init__( + self, + filevers: _FourIntSequence = (0, 0, 0, 0), + prodvers: _FourIntSequence = (0, 0, 0, 0), + mask: int = 0x3F, + flags: int = 0x0, + OS: int = 0x40004, + fileType: int = 0x1, + subtype: int = 0x0, + date: _TwoIntSequence = (0, 0), + ) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringFileInfo: + name: str + kids: list[_Kid] + def __init__(self, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, sublen: Unused, vallen: Unused, name: str, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringTable: + name: str + kids: list[_Kid] + def __init__(self, name: str | None = None, kids: list[_Kid] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class StringStruct: + name: str + val: str + def __init__(self, name: str | None = None, val: str | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: int) -> int: ... + def toRaw(self) -> bytes: ... + def __str__(self, indent: Unused = "") -> str: ... + +class VarFileInfo: + kids: list[_Kid] + def __init__(self, kids: list[_Kid] | None = None) -> None: ... + sublen: int + vallen: int + name: str + def fromRaw(self, sublen: int, vallen: int, name: str, data: SliceableBuffer, i: int, limit: int) -> int: ... + wType: int + def toRaw(self) -> bytes: ... + def __str__(self, indent: str = "") -> str: ... + +class VarStruct: + name: str + kids: list[Any] # Whatever can be passed to struct.pack + def __init__(self, name: str | None = None, kids: list[Any] | None = None) -> None: ... + def fromRaw(self, data: SliceableBuffer, i: int, limit: Unused) -> int: ... + wValueLength: int + wType: int + sublen: int + def toRaw(self) -> bytes: ... + def __str__(self, indent: Unused = "") -> str: ... diff --git a/stubs/pyinstaller/pyi_splash/__init__.pyi b/stubs/pyinstaller/pyi_splash/__init__.pyi new file mode 100644 index 000000000000..6be5e623decc --- /dev/null +++ b/stubs/pyinstaller/pyi_splash/__init__.pyi @@ -0,0 +1,13 @@ +# Referenced in: https://pyinstaller.org/en/stable/advanced-topics.html#module-pyi_splash +# Source: https://github.com/pyinstaller/pyinstaller/blob/develop/PyInstaller/fake-modules/pyi_splash.py + +from typing import Final + +__all__ = ["CLOSE_CONNECTION", "FLUSH_CHARACTER", "is_alive", "close", "update_text"] + +def is_alive() -> bool: ... +def update_text(msg: str) -> None: ... +def close() -> None: ... + +CLOSE_CONNECTION: Final = b"\x04" +FLUSH_CHARACTER: Final = b"\x0d" diff --git a/stubs/pyjks/@tests/stubtest_allowlist.txt b/stubs/pyjks/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ad6b02338ea7 --- /dev/null +++ b/stubs/pyjks/@tests/stubtest_allowlist.txt @@ -0,0 +1,35 @@ +# Attributes implemented by __getattr__ +jks.jks.PrivateKeyEntry.algorithm_oid +jks.jks.PrivateKeyEntry.pkey +jks.jks.PrivateKeyEntry.pkey_pkcs8 +jks.jks.SecretKeyEntry.algorithm +jks.jks.SecretKeyEntry.key +jks.jks.SecretKeyEntry.key_size + +# Implicit imports, not re-exported +jks.DSA_OID +jks.DSA_WITH_SHA1_OID +jks.ENTRY_TYPE_CERTIFICATE +jks.ENTRY_TYPE_KEY +jks.ENTRY_TYPE_SEALED +jks.ENTRY_TYPE_SECRET +jks.KEY_TYPE_PRIVATE +jks.KEY_TYPE_PUBLIC +jks.KEY_TYPE_SECRET +jks.MAGIC_NUMBER_JCEKS +jks.MAGIC_NUMBER_JKS +jks.RSA_ENCRYPTION_OID +jks.SIGNATURE_WHITENING +jks.py23basestring +jks.bks.DSA_OID +jks.bks.DSA_WITH_SHA1_OID +jks.bks.RSA_ENCRYPTION_OID +jks.bks.py23basestring +jks.jks.DSA_OID +jks.jks.DSA_WITH_SHA1_OID +jks.jks.RSA_ENCRYPTION_OID +jks.jks.py23basestring +jks.sun_crypto.DSA_OID +jks.sun_crypto.DSA_WITH_SHA1_OID +jks.sun_crypto.RSA_ENCRYPTION_OID +jks.sun_crypto.py23basestring diff --git a/stubs/pyjks/METADATA.toml b/stubs/pyjks/METADATA.toml new file mode 100644 index 000000000000..20eeae1e0c06 --- /dev/null +++ b/stubs/pyjks/METADATA.toml @@ -0,0 +1,3 @@ +version = "20.0.*" +upstream-repository = "https://github.com/kurtbrose/pyjks" +dependencies = ["types-pyasn1"] diff --git a/stubs/pyjks/jks/__init__.pyi b/stubs/pyjks/jks/__init__.pyi new file mode 100644 index 000000000000..26eee4cd284a --- /dev/null +++ b/stubs/pyjks/jks/__init__.pyi @@ -0,0 +1,48 @@ +# pyjks exports lots of junk such as jks.jks.SIGNATURE_WHITENING, jks.util.b8 etc. +# We don't mark those as re-exported as those don't seem like intended part of the public API. +from .bks import ( + AbstractBksEntry as AbstractBksEntry, + BksKeyEntry as BksKeyEntry, + BksKeyStore as BksKeyStore, + BksSealedKeyEntry as BksSealedKeyEntry, + BksSecretKeyEntry as BksSecretKeyEntry, + BksTrustedCertEntry as BksTrustedCertEntry, + UberKeyStore as UberKeyStore, +) +from .jks import ( + KeyStore as KeyStore, + PrivateKeyEntry as PrivateKeyEntry, + SecretKeyEntry as SecretKeyEntry, + TrustedCertEntry as TrustedCertEntry, + __version__ as __version__, + __version_info__ as __version_info__, +) +from .util import ( + AbstractKeystore as AbstractKeystore, + AbstractKeystoreEntry as AbstractKeystoreEntry, + BadDataLengthException as BadDataLengthException, + BadHashCheckException as BadHashCheckException, + BadKeystoreFormatException as BadKeystoreFormatException, + BadPaddingException as BadPaddingException, + DecryptionFailureException as DecryptionFailureException, + DuplicateAliasException as DuplicateAliasException, + KeystoreException as KeystoreException, + KeystoreSignatureException as KeystoreSignatureException, + NotYetDecryptedException as NotYetDecryptedException, + UnexpectedAlgorithmException as UnexpectedAlgorithmException, + UnexpectedJavaTypeException as UnexpectedJavaTypeException, + UnexpectedKeyEncodingException as UnexpectedKeyEncodingException, + UnsupportedKeyFormatException as UnsupportedKeyFormatException, + UnsupportedKeystoreEntryTypeException as UnsupportedKeystoreEntryTypeException, + UnsupportedKeystoreTypeException as UnsupportedKeystoreTypeException, + UnsupportedKeystoreVersionException as UnsupportedKeystoreVersionException, + add_pkcs7_padding as add_pkcs7_padding, + as_hex as as_hex, + as_pem as as_pem, + bitstring_to_bytes as bitstring_to_bytes, + pkey_as_pem as pkey_as_pem, + print_pem as print_pem, + strip_pkcs5_padding as strip_pkcs5_padding, + strip_pkcs7_padding as strip_pkcs7_padding, + xor_bytearrays as xor_bytearrays, +) diff --git a/stubs/pyjks/jks/bks.pyi b/stubs/pyjks/jks/bks.pyi new file mode 100644 index 000000000000..d083d6b95d2f --- /dev/null +++ b/stubs/pyjks/jks/bks.pyi @@ -0,0 +1,125 @@ +from _typeshed import SupportsKeysAndGetItem, Unused +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +from .jks import TrustedCertEntry +from .util import AbstractKeystore, AbstractKeystoreEntry + +_BksType: TypeAlias = Literal["bks", "uber"] +_CertType: TypeAlias = Literal["X.509"] +_EntryFormat: TypeAlias = Literal["PKCS8", "PKCS#8", "X.509", "X509", "RAW"] +_BksVersion: TypeAlias = Literal[1, 2] + +ENTRY_TYPE_CERTIFICATE: Final = 1 +ENTRY_TYPE_KEY: Final = 2 +ENTRY_TYPE_SECRET: Final = 3 +ENTRY_TYPE_SEALED: Final = 4 + +KEY_TYPE_PRIVATE: Final = 0 +KEY_TYPE_PUBLIC: Final = 1 +KEY_TYPE_SECRET: Final = 2 +_KeyType: TypeAlias = Literal[0, 1, 2] + +class AbstractBksEntry(AbstractKeystoreEntry): + store_type: _BksType | None + cert_chain: list[tuple[_CertType, bytes]] + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]] = ..., + encrypted: bytes | None = None, + store_type: _BksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + +class BksTrustedCertEntry(TrustedCertEntry): + store_type: _BksType | None # type: ignore[assignment] + +class BksKeyEntry(AbstractBksEntry): + type: _KeyType + format: _EntryFormat + algorithm: str + encoded: bytes + # type == KEY_TYPE_PRIVATE + pkey_pkcs8: bytes + pkey: bytes + algorithm_oid: tuple[int, ...] + # type == KEY_TYPE_PUBLIC + public_key_info: bytes + public_key: bytes + # type == KEY_TYPE_SECRET + key: bytes + key_size: int + def __init__( + self, + type: _KeyType, + format: _EntryFormat, + algorithm: str, + encoded: bytes, + *, + cert_chain: list[tuple[_CertType, bytes]] = ..., + encrypted: bytes | None = None, + store_type: _BksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @classmethod + def type2str(cls, t: _KeyType) -> Literal["PRIVATE", "PUBLIC", "SECRET"]: ... + def is_decrypted(self) -> Literal[True]: ... + +class BksSecretKeyEntry(AbstractBksEntry): + key: bytes + def is_decrypted(self) -> Literal[True]: ... + +class BksSealedKeyEntry(AbstractBksEntry): + # Properties provided by __getattr__ + nested: BksKeyEntry | None + # __getattr__ proxies all attributes of nested BksKeyEntry after decrypting + type: _KeyType + format: _EntryFormat + algorithm: str + encoded: bytes + # if type == KEY_TYPE_PRIVATE + pkey_pkcs8: bytes + pkey: bytes + algorithm_oid: tuple[int, ...] + # if type == KEY_TYPE_PUBLIC + public_key_info: bytes + public_key: bytes + # if type == KEY_TYPE_SECRET + key: bytes + key_size: int + +class BksKeyStore(AbstractKeystore): + store_type: Literal["bks"] + entries: dict[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry] # type: ignore[assignment] + version: _BksVersion + def __init__( + self, + store_type: Literal["bks"], + entries: SupportsKeysAndGetItem[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry], + version: _BksVersion = 2, + ) -> None: ... + @property + def certs(self) -> dict[str, BksTrustedCertEntry]: ... + @property + def plain_keys(self) -> dict[str, BksKeyEntry]: ... + @property + def sealed_keys(self) -> dict[str, BksSealedKeyEntry]: ... + @property + def secret_keys(self) -> dict[str, BksSecretKeyEntry]: ... + @classmethod + def loads(cls, data: bytes, store_password: str, try_decrypt_keys: bool = True) -> Self: ... + +class UberKeyStore(BksKeyStore): + store_type: Literal["uber"] # type: ignore[assignment] + version: Literal[1] + def __init__( + self, + store_type: Literal["uber"], + entries: SupportsKeysAndGetItem[str, BksTrustedCertEntry | BksKeyEntry | BksSealedKeyEntry | BksSecretKeyEntry], + version: Literal[1] = 1, + ) -> None: ... diff --git a/stubs/pyjks/jks/jks.pyi b/stubs/pyjks/jks/jks.pyi new file mode 100644 index 000000000000..d6c22d6e2998 --- /dev/null +++ b/stubs/pyjks/jks/jks.pyi @@ -0,0 +1,131 @@ +from _typeshed import SupportsKeysAndGetItem, Unused +from collections.abc import Iterable +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Never, Self + +from .util import AbstractKeystore, AbstractKeystoreEntry + +__version_info__: Final[tuple[int, int, int] | tuple[int, int, int, str]] +__version__: Final[str] +MAGIC_NUMBER_JKS: Final[bytes] +MAGIC_NUMBER_JCEKS: Final[bytes] +SIGNATURE_WHITENING: Final[bytes] + +_JksType: TypeAlias = Literal["jks", "jceks"] +_CertType: TypeAlias = Literal["X.509"] +_KeyFormat: TypeAlias = Literal["pkcs8", "rsa_raw"] + +class TrustedCertEntry(AbstractKeystoreEntry): + store_type: _JksType | None + type: _CertType | None + cert: bytes + # NB! For most use cases, use TrustedCertEntry.new() classmethod. + def __init__( + self, + *, + type: _CertType | None = None, + cert: bytes, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @classmethod + def new(cls, alias: str, cert: bytes) -> Self: ... # type: ignore[override] + def is_decrypted(self) -> Literal[True]: ... + +class PrivateKeyEntry(AbstractKeystoreEntry): + store_type: _JksType | None + cert_chain: list[tuple[_CertType, bytes]] + # Properties provided by __getattr__ after decryption + @property + def pkey(self) -> bytes: ... + @property + def pkey_pkcs8(self) -> bytes: ... + @property + def algorithm_oid(self) -> tuple[int, ...]: ... + + # NB! For most use cases, use PrivateKeyEntry.new() classmethod. + # Overloaded: must provide `encrypted` OR `pkey`, `pkey_pkcs8`, `algorithm_oid` + @overload + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]], + encrypted: bytes, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + @overload + def __init__( + self, + *, + cert_chain: list[tuple[_CertType, bytes]], + pkey: bytes, + pkey_pkcs8: bytes, + algorithm_oid: tuple[int, ...], + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + + @classmethod + def new( # type: ignore[override] + cls, alias: str, certs: Iterable[bytes], key: bytes, key_format: _KeyFormat = "pkcs8" + ) -> Self: ... + +class SecretKeyEntry(AbstractKeystoreEntry): + store_type: _JksType | None + # Properties provided by __getattr__ + @property + def algorithm(self) -> str: ... + @property + def key(self) -> bytes: ... + @property + def key_size(self) -> int: ... + + # Overloaded: must provide `sealed_obj` OR `algorithm`, `key`, `key_size` + @overload + def __init__( + self, *, sealed_obj: bytes, store_type: _JksType | None = None, alias: str, timestamp: int, **kwargs: Unused + ) -> None: ... + @overload + def __init__( + self, + *, + algorithm: str, + key: bytes, + key_size: int, + store_type: _JksType | None = None, + alias: str, + timestamp: int, + **kwargs: Unused, + ) -> None: ... + + # Not implemented by pyjks + @classmethod + def new(cls, alias: str, sealed_obj: bool, algorithm: str, key: bytes, key_size: int) -> Never: ... # type: ignore[override] + # Not implemented by pyjks + def encrypt(self, key_password: str) -> Never: ... + +class KeyStore(AbstractKeystore): + entries: dict[str, TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry] # type: ignore[assignment] + store_type: _JksType + @classmethod + def new(cls, store_type: _JksType, store_entries: Iterable[TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry]) -> Self: ... + @classmethod + def loads(cls, data: bytes, store_password: str | None, try_decrypt_keys: bool = True) -> Self: ... + def saves(self, store_password: str) -> bytes: ... + # NB! For most use cases, use KeyStore.new() classmethod. + def __init__( + self, store_type: _JksType, entries: SupportsKeysAndGetItem[str, TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry] + ) -> None: ... + @property + def certs(self) -> dict[str, TrustedCertEntry]: ... + @property + def secret_keys(self) -> dict[str, SecretKeyEntry]: ... + @property + def private_keys(self) -> dict[str, PrivateKeyEntry]: ... diff --git a/stubs/pyjks/jks/rfc2898.pyi b/stubs/pyjks/jks/rfc2898.pyi new file mode 100644 index 000000000000..b6711c502262 --- /dev/null +++ b/stubs/pyjks/jks/rfc2898.pyi @@ -0,0 +1,5 @@ +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Sequence + +class PBEParameter(Sequence): + componentType: NamedTypes diff --git a/stubs/pyjks/jks/rfc7292.pyi b/stubs/pyjks/jks/rfc7292.pyi new file mode 100644 index 000000000000..400f6d577568 --- /dev/null +++ b/stubs/pyjks/jks/rfc7292.pyi @@ -0,0 +1,28 @@ +from hashlib import _Hash +from typing import Final, Literal, TypeAlias + +from pyasn1.type.namedtype import NamedTypes +from pyasn1.type.univ import Sequence + +PBE_WITH_SHA1_AND_TRIPLE_DES_CBC_OID: Final[tuple[int, ...]] +PURPOSE_KEY_MATERIAL: Final = 1 +PURPOSE_IV_MATERIAL: Final = 2 +PURPOSE_MAC_MATERIAL: Final = 3 + +_Purpose: TypeAlias = Literal[1, 2, 3] + +class Pkcs12PBEParams(Sequence): + componentType: NamedTypes + +def derive_key( + hashfn: _Hash, purpose_byte: _Purpose, password_str: str, salt: bytes, iteration_count: int, desired_key_size: int +) -> bytes: ... +def decrypt_PBEWithSHAAnd3KeyTripleDESCBC( + data: bytes | bytearray, password_str: str, salt: bytes, iteration_count: int +) -> bytes: ... +def decrypt_PBEWithSHAAndTwofishCBC( + encrypted_data: bytes | bytearray, password: str, salt: bytes, iteration_count: int +) -> bytes: ... +def encrypt_PBEWithSHAAndTwofishCBC( + plaintext_data: bytes | bytearray, password: str, salt: bytes, iteration_count: int +) -> bytes: ... diff --git a/stubs/pyjks/jks/sun_crypto.pyi b/stubs/pyjks/jks/sun_crypto.pyi new file mode 100644 index 000000000000..94ae49d4b828 --- /dev/null +++ b/stubs/pyjks/jks/sun_crypto.pyi @@ -0,0 +1,8 @@ +from typing import Final + +SUN_JKS_ALGO_ID: Final[tuple[int, ...]] +SUN_JCE_ALGO_ID: Final[tuple[int, ...]] + +def jks_pkey_encrypt(key: bytes | bytearray, password_str: str) -> bytes: ... +def jks_pkey_decrypt(data: bytes | bytearray, password_str: str) -> bytes: ... +def jce_pbe_decrypt(data: bytes | bytearray, password: str, salt: bytes, iteration_count: int) -> bytes: ... diff --git a/stubs/pyjks/jks/util.pyi b/stubs/pyjks/jks/util.pyi new file mode 100644 index 000000000000..8e913d36654c --- /dev/null +++ b/stubs/pyjks/jks/util.pyi @@ -0,0 +1,66 @@ +from _typeshed import FileDescriptorOrPath, SupportsKeysAndGetItem, Unused +from collections.abc import Iterable +from struct import Struct +from typing import Final, Literal, TypeAlias +from typing_extensions import Self + +from .bks import BksKeyEntry +from .jks import PrivateKeyEntry + +b8: Final[Struct] +b4: Final[Struct] +b2: Final[Struct] +b1: Final[Struct] +py23basestring: Final[tuple[type[str], type[str]]] +RSA_ENCRYPTION_OID: Final[tuple[int, ...]] +DSA_OID: Final[tuple[int, ...]] +DSA_WITH_SHA1_OID: Final[tuple[int, ...]] + +_KeystoreType: TypeAlias = Literal["jks", "jceks", "bks", "uber"] +_PemType: TypeAlias = Literal["CERTIFICATE", "PUBLIC KEY", "PRIVATE KEY", "RSA PRIVATE KEY"] + +class KeystoreException(Exception): ... +class KeystoreSignatureException(KeystoreException): ... +class DuplicateAliasException(KeystoreException): ... +class NotYetDecryptedException(KeystoreException): ... +class BadKeystoreFormatException(KeystoreException): ... +class BadDataLengthException(KeystoreException): ... +class BadPaddingException(KeystoreException): ... +class BadHashCheckException(KeystoreException): ... +class DecryptionFailureException(KeystoreException): ... +class UnsupportedKeystoreVersionException(KeystoreException): ... +class UnexpectedJavaTypeException(KeystoreException): ... +class UnexpectedAlgorithmException(KeystoreException): ... +class UnexpectedKeyEncodingException(KeystoreException): ... +class UnsupportedKeystoreTypeException(KeystoreException): ... +class UnsupportedKeystoreEntryTypeException(KeystoreException): ... +class UnsupportedKeyFormatException(KeystoreException): ... + +class AbstractKeystore: + store_type: _KeystoreType + entries: dict[str, AbstractKeystoreEntry] + def __init__(self, store_type: _KeystoreType, entries: SupportsKeysAndGetItem[str, AbstractKeystoreEntry]) -> None: ... + @classmethod + def load(cls, filename: FileDescriptorOrPath, store_password: str | None, try_decrypt_keys: bool = True) -> Self: ... + def save(self, filename: FileDescriptorOrPath, store_password: str) -> None: ... + +class AbstractKeystoreEntry: + store_type: _KeystoreType | None + alias: str + timestamp: int + def __init__(self, *, store_type: _KeystoreType | None = None, alias: str, timestamp: int, **kwargs: Unused) -> None: ... + @classmethod + def new(cls, alias: str) -> Self: ... + def is_decrypted(self) -> bool: ... + def decrypt(self, key_password: str) -> None: ... + def encrypt(self, key_password: str) -> None: ... + +def as_hex(ba: bytes | bytearray) -> str: ... +def as_pem(der_bytes: bytes, type: _PemType) -> str: ... +def bitstring_to_bytes(bitstr: Iterable[int]) -> bytes: ... +def xor_bytearrays(a: bytes | bytearray, b: bytes | bytearray) -> bytearray: ... +def print_pem(der_bytes: bytes, type: _PemType) -> None: ... +def pkey_as_pem(pk: PrivateKeyEntry | BksKeyEntry) -> str: ... +def strip_pkcs5_padding(m: bytes | bytearray) -> bytes: ... +def strip_pkcs7_padding(m: bytes | bytearray, block_size: int) -> bytes: ... +def add_pkcs7_padding(m: bytes | bytearray, block_size: int) -> bytes: ... diff --git a/stubs/pyluach/@tests/stubtest_allowlist.txt b/stubs/pyluach/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7d6b35fd3a3a --- /dev/null +++ b/stubs/pyluach/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Module with no public API, for internal use only: +pyluach.gematria diff --git a/stubs/pyluach/METADATA.toml b/stubs/pyluach/METADATA.toml new file mode 100644 index 000000000000..102e7dfd01db --- /dev/null +++ b/stubs/pyluach/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.3.*" +upstream-repository = "https://github.com/simlist/pyluach" diff --git a/stubs/pyluach/pyluach/__init__.pyi b/stubs/pyluach/pyluach/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/pyluach/pyluach/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/pyluach/pyluach/dates.pyi b/stubs/pyluach/pyluach/dates.pyi new file mode 100644 index 000000000000..3cc936a8c592 --- /dev/null +++ b/stubs/pyluach/pyluach/dates.pyi @@ -0,0 +1,109 @@ +import abc +import builtins +import datetime +from collections.abc import Generator +from enum import Enum +from typing import TypedDict, overload, type_check_only +from typing_extensions import Self + +@type_check_only +class _DateDict(TypedDict): + year: int + month: int + day: int + +class Rounding(Enum): + PREVIOUS_DAY = 1 + NEXT_DAY = 2 + EXCEPTION = 3 + +class BaseDate(abc.ABC, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def jd(self) -> float: ... + @abc.abstractmethod + def to_heb(self) -> HebrewDate: ... + def __hash__(self) -> int: ... + def __add__(self, other: float) -> BaseDate: ... + + @overload + def __sub__(self, other: float) -> BaseDate: ... + @overload + def __sub__(self, other: BaseDate) -> int: ... + + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def weekday(self) -> int: ... + def isoweekday(self) -> int: ... + def shabbos(self) -> Self: ... + def fast_day(self, hebrew: bool = False) -> str | None: ... + def festival( + self, israel: bool = False, hebrew: bool = False, include_working_days: bool = True, prefix_day: bool = False + ) -> str | None: ... + def holiday(self, israel: bool = False, hebrew: bool = False, prefix_day: bool = False) -> str | None: ... + +class CalendarDateMixin: + year: int + month: int + day: int + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __iter__(self) -> Generator[int]: ... + def tuple(self) -> builtins.tuple[int, int, int]: ... + def dict(self) -> _DateDict: ... + def replace(self, year: int | None = None, month: int | None = None, day: int | None = None) -> Self: ... + +class JulianDay(BaseDate): + day: float + def __init__(self, day: float) -> None: ... + @property + def jd(self) -> float: ... + @staticmethod + def from_pydate(pydate: datetime.date) -> JulianDay: ... + @staticmethod + def today() -> JulianDay: ... + def to_greg(self) -> GregorianDate: ... + def to_heb(self) -> HebrewDate: ... + def to_pydate(self) -> datetime.date: ... + +class GregorianDate(BaseDate, CalendarDateMixin): + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __format__(self, fmt: str) -> str: ... + def strftime(self, fmt: str) -> str: ... + @property + def jd(self) -> float: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Self: ... + @staticmethod + def today() -> GregorianDate: ... + def is_leap(self) -> bool: ... + def to_jd(self) -> JulianDay: ... + def to_heb(self) -> HebrewDate: ... + def to_pydate(self) -> datetime.date: ... + +class HebrewDate(BaseDate, CalendarDateMixin): + def __init__(self, year: int, month: int, day: int, jd: float | None = None) -> None: ... + def __format__(self, fmt: str) -> str: ... + @property + def jd(self) -> float: ... + @staticmethod + def from_pydate(pydate: datetime.date) -> HebrewDate: ... + @staticmethod + def today() -> HebrewDate: ... + def to_jd(self) -> JulianDay: ... + def to_greg(self) -> GregorianDate: ... + def to_pydate(self) -> datetime.date: ... + def to_heb(self) -> HebrewDate: ... + def month_name(self, hebrew: bool = False) -> str: ... + def hebrew_day(self, withgershayim: bool = True) -> str: ... + def hebrew_year(self, thousands: bool = False, withgershayim: bool = True) -> str: ... + def hebrew_date_string(self, thousands: bool = False) -> str: ... + def add( + self, years: int = 0, months: int = 0, days: int = 0, adar1: bool | None = False, rounding: Rounding = Rounding.NEXT_DAY + ) -> HebrewDate: ... + def subtract( + self, years: int = 0, months: int = 0, days: int = 0, adar1: bool | None = False, rounding: Rounding = Rounding.NEXT_DAY + ) -> HebrewDate: ... diff --git a/stubs/pyluach/pyluach/hebrewcal.pyi b/stubs/pyluach/pyluach/hebrewcal.pyi new file mode 100644 index 000000000000..925354719149 --- /dev/null +++ b/stubs/pyluach/pyluach/hebrewcal.pyi @@ -0,0 +1,147 @@ +import calendar +import datetime +from collections.abc import Generator +from typing import Literal, TypedDict, overload, type_check_only +from typing_extensions import Self + +from .dates import BaseDate, HebrewDate + +@type_check_only +class _MoladDict(TypedDict): + weekday: int + hours: int + parts: int + +@type_check_only +class _MoladAnnouncementDict(TypedDict): + weekday: int + hour: int + minutes: int + parts: int + +class IllegalMonthError(ValueError): + month: int + def __init__(self, month: int) -> None: ... + +class IllegalWeekdayError(ValueError): + weekday: int + def __init__(self, weekday: int) -> None: ... + +class Year: + year: int + leap: bool + def __init__(self, year: int) -> None: ... + def __len__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: int) -> Year: ... + + @overload + def __sub__(self, other: int) -> Year: ... + @overload + def __sub__(self, other: Year) -> int: ... + + def __gt__(self, other: Year) -> bool: ... + def __ge__(self, other: Year) -> bool: ... + def __lt__(self, other: Year) -> bool: ... + def __le__(self, other: Year) -> bool: ... + def __iter__(self) -> Generator[int]: ... + def monthscount(self) -> Literal[12, 13]: ... + def itermonths(self) -> Generator[Month]: ... + def iterdays(self) -> Generator[int]: ... + def iterdates(self) -> Generator[HebrewDate]: ... + @classmethod + def from_date(cls, date: BaseDate) -> Self: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Self: ... + def year_string(self, thousands: bool = False) -> str: ... + +class Month: + year: int + month: int + def __init__(self, year: int, month: int) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Generator[int]: ... + def __eq__(self, other: object) -> bool: ... + def __add__(self, other: int) -> Month: ... + + @overload + def __sub__(self, other: int) -> Month: ... + @overload + def __sub__(self, other: Month) -> int: ... + + def __gt__(self, other: Month) -> bool: ... + def __ge__(self, other: Month) -> bool: ... + def __lt__(self, other: Month) -> bool: ... + def __le__(self, other: Month) -> bool: ... + @classmethod + def from_date(cls, date: BaseDate) -> Month: ... + @classmethod + def from_pydate(cls, pydate: datetime.date) -> Month: ... + def month_name(self, hebrew: bool = False) -> str: ... + def month_string(self, thousands: bool = False) -> str: ... + def starting_weekday(self) -> int: ... + def iterdates(self) -> Generator[HebrewDate]: ... + def molad(self) -> _MoladDict: ... + def molad_announcement(self) -> _MoladAnnouncementDict: ... + +def to_hebrew_numeral(num: int, thousands: bool = False, withgershayim: bool = True) -> str: ... + +class HebrewCalendar(calendar.Calendar): + hebrewnumerals: bool + hebrewweekdays: bool + hebrewmonths: bool + hebrewyear: bool + def __init__( + self, + firstweekday: int = 1, + hebrewnumerals: bool = True, + hebrewweekdays: bool = False, + hebrewmonths: bool = False, + hebrewyear: bool = False, + ) -> None: ... + + @property + def firstweekday(self) -> int: ... + @firstweekday.setter + def firstweekday(self, thefirstweekday: int) -> None: ... + + def iterweekdays(self) -> Generator[int]: ... + def itermonthdates(self, year: int, month: int) -> Generator[HebrewDate]: ... # type: ignore[override] + def itermonthdays(self, year: int, month: int) -> Generator[int]: ... + def itermonthdays2(self, year: int, month: int) -> Generator[tuple[int, int]]: ... + def itermonthdays3(self, year: int, month: int) -> Generator[tuple[int, int, int]]: ... + def itermonthdays4(self, year: int, month: int) -> Generator[tuple[int, int, int, int]]: ... + def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[HebrewDate]]]]: ... # type: ignore[override] + def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: ... + def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: ... + def monthdatescalendar(self, year: int, month: int) -> list[list[HebrewDate]]: ... # type: ignore[override] + +class HebrewHTMLCalendar(HebrewCalendar, calendar.HTMLCalendar): + rtl: bool + def __init__( + self, + firstweekday: int = 1, + hebrewnumerals: bool = True, + hebrewweekdays: bool = False, + hebrewmonths: bool = False, + hebrewyear: bool = False, + rtl: bool = False, + ) -> None: ... + def formatday(self, day: int, weekday: int) -> str: ... + def formatweekday(self, day: int) -> str: ... + def formatyearnumber(self, theyear: int) -> int | str: ... + def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + def formatyear(self, theyear: int, width: int = 3) -> str: ... + +class HebrewTextCalendar(HebrewCalendar, calendar.TextCalendar): + def formatday(self, day: int, weekday: int, width: int) -> str: ... + def formatweekday(self, day: int, width: int) -> str: ... + def formatmonthname(self, theyear: int, themonth: int, width: int = 0, withyear: bool = True) -> str: ... + def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ... + +def fast_day(date: BaseDate, hebrew: bool = False) -> str | None: ... +def festival( + date: BaseDate, israel: bool = False, hebrew: bool = False, include_working_days: bool = True, prefix_day: bool = False +) -> str | None: ... +def holiday(date: BaseDate, israel: bool = False, hebrew: bool = False, prefix_day: bool = False) -> str | None: ... diff --git a/stubs/pyluach/pyluach/parshios.pyi b/stubs/pyluach/pyluach/parshios.pyi new file mode 100644 index 000000000000..ff1a4d8c4b20 --- /dev/null +++ b/stubs/pyluach/pyluach/parshios.pyi @@ -0,0 +1,14 @@ +from collections import OrderedDict +from collections.abc import Generator +from typing import Final + +from .dates import BaseDate, HebrewDate + +PARSHIOS: Final[list[str]] +PARSHIOS_HEBREW: Final[list[str]] + +def getparsha(date: BaseDate, israel: bool = False) -> list[int] | None: ... +def getparsha_string(date: BaseDate, israel: bool = False, hebrew: bool = False) -> str | None: ... +def iterparshios(year: int, israel: bool = False) -> Generator[list[int] | None]: ... +def parshatable(year: int, israel: bool = False) -> OrderedDict[HebrewDate, list[int] | None]: ... +def four_parshios(date: BaseDate, hebrew: bool = False) -> str: ... diff --git a/stubs/pyluach/pyluach/utils.pyi b/stubs/pyluach/pyluach/utils.pyi new file mode 100644 index 000000000000..2c0f3e71e30f --- /dev/null +++ b/stubs/pyluach/pyluach/utils.pyi @@ -0,0 +1,32 @@ +from enum import Enum +from typing import Final + +class _Days(Enum): + ROSH_HASHANA = "Rosh Hashana" + YOM_KIPPUR = "Yom Kippur" + SUCCOS = "Succos" + SHMINI_ATZERES = "Shmini Atzeres" + SIMCHAS_TORAH = "Simchas Torah" + CHANUKA = "Chanuka" + TU_BSHVAT = "Tu B'shvat" + PURIM_KATAN = "Purim Katan" + PURIM = "Purim" + SHUSHAN_PURIM = "Shushan Purim" + PESACH = "Pesach" + PESACH_SHENI = "Pesach Sheni" + LAG_BAOMER = "Lag Ba'omer" + SHAVUOS = "Shavuos" + TU_BAV = "Tu B'av" + TZOM_GEDALIA = "Tzom Gedalia" + TENTH_OF_TEVES = "10 of Teves" + TAANIS_ESTHER = "Taanis Esther" + SEVENTEENTH_OF_TAMUZ = "17 of Tamuz" + NINTH_OF_AV = "9 of Av" + +MONTH_NAMES: Final[list[str]] +MONTH_NAMES_HEBREW: Final[list[str]] +FAST_DAYS: Final[list[str]] +FAST_DAYS_HEBREW: Final[list[str]] +FESTIVALS: Final[list[str]] +FESTIVALS_HEBREW: Final[list[str]] +WEEKDAYS: Final[dict[int, str]] diff --git a/stubs/pynput/@tests/stubtest_allowlist.txt b/stubs/pynput/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..415752653a84 --- /dev/null +++ b/stubs/pynput/@tests/stubtest_allowlist.txt @@ -0,0 +1,8 @@ +# Platform specific private utils: +pynput._util.xorg_keysyms +pynput._util.xorg +pynput._util.win32_vks +pynput._util.win32 +pynput._util.uinput +pynput._util.darwin_vks +pynput._util.darwin diff --git a/stubs/pynput/METADATA.toml b/stubs/pynput/METADATA.toml new file mode 100644 index 000000000000..66307d3bc98e --- /dev/null +++ b/stubs/pynput/METADATA.toml @@ -0,0 +1,5 @@ +version = "~=1.8.1" +upstream-repository = "https://github.com/moses-palmer/pynput" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] diff --git a/stubs/pynput/pynput/__init__.pyi b/stubs/pynput/pynput/__init__.pyi new file mode 100644 index 000000000000..1b92738f9891 --- /dev/null +++ b/stubs/pynput/pynput/__init__.pyi @@ -0,0 +1 @@ +from . import keyboard as keyboard, mouse as mouse diff --git a/stubs/pynput/pynput/_info.pyi b/stubs/pynput/pynput/_info.pyi new file mode 100644 index 000000000000..e6655bdd2e3d --- /dev/null +++ b/stubs/pynput/pynput/_info.pyi @@ -0,0 +1,2 @@ +__author__: str +__version__: tuple[int, int, int] diff --git a/stubs/pynput/pynput/_util.pyi b/stubs/pynput/pynput/_util.pyi new file mode 100644 index 000000000000..675a633379fd --- /dev/null +++ b/stubs/pynput/pynput/_util.pyi @@ -0,0 +1,73 @@ +import threading +from _typeshed import OptExcInfo +from collections.abc import Callable +from queue import Queue +from types import ModuleType, TracebackType +from typing import Any, ClassVar, Generic, ParamSpec, TypedDict, TypeVar, type_check_only +from typing_extensions import Self + +_T = TypeVar("_T") +_AbstractListenerT = TypeVar("_AbstractListenerT", bound=AbstractListener) +_P = ParamSpec("_P") + +@type_check_only +class _RESOLUTIONS(TypedDict): + darwin: str + uinput: str + xorg: str + +RESOLUTIONS: _RESOLUTIONS + +def backend(package: str) -> ModuleType: ... +def prefix(base: type | tuple[type | tuple[Any, ...], ...], cls: type) -> str | None: ... + +class AbstractListener(threading.Thread): + class StopException(Exception): ... + _HANDLED_EXCEPTIONS: ClassVar[tuple[type | tuple[Any, ...], ...]] # undocumented + _suppress: bool # undocumented + _running: bool # undocumented + _thread: threading.Thread # undocumented + _condition: threading.Condition # undocumented + _ready: bool # undocumented + _queue: Queue[OptExcInfo | None] # undocumented + daemon: bool + def __init__(self, suppress: bool = False, **kwargs: Callable[..., bool | None] | None) -> None: ... + @property + def suppress(self) -> bool: ... + @property + def running(self) -> bool: ... + def stop(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def wait(self) -> None: ... + def run(self) -> None: ... + @classmethod + def _emitter(cls, f: Callable[_P, _T]) -> Callable[_P, _T]: ... # undocumented + def _mark_ready(self) -> None: ... # undocumented + def _run(self) -> None: ... # undocumented + def _stop_platform(self) -> None: ... # undocumented + def join(self, timeout: float | None = None, *args: Any) -> None: ... + +class Events(Generic[_T, _AbstractListenerT]): + _Listener: type[_AbstractListenerT] | None # undocumented + + class Event: + def __eq__(self, other: object) -> bool: ... + + _event_queue: Queue[_T] # undocumented + _sentinel: object # undocumented + _listener: _AbstractListenerT # undocumented + start: Callable[[], None] + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + def get(self, timeout: float | None = None) -> _T | None: ... + def _event_mapper(self, event: Callable[_P, object]) -> Callable[_P, None]: ... + +class NotifierMixin: ... diff --git a/stubs/pynput/pynput/keyboard/__init__.pyi b/stubs/pynput/pynput/keyboard/__init__.pyi new file mode 100644 index 000000000000..8d553e0087f9 --- /dev/null +++ b/stubs/pynput/pynput/keyboard/__init__.pyi @@ -0,0 +1,32 @@ +from _typeshed import SupportsItems +from collections.abc import Callable +from typing import Any + +from pynput import _util + +from ._base import Controller as Controller, Key as Key, KeyCode as KeyCode, Listener as Listener + +class Events(_util.Events[Any, Listener]): + class Press(_util.Events.Event): + key: Key | KeyCode | None + injected: bool + def __init__(self, key: Key | KeyCode | None, injected: bool) -> None: ... + + class Release(_util.Events.Event): + key: Key | KeyCode | None + injected: bool + def __init__(self, key: Key | KeyCode | None, injected: bool) -> None: ... + + def __init__(self) -> None: ... + def __next__(self) -> Press | Release: ... + def get(self, timeout: float | None = None) -> Press | Release | None: ... + +class HotKey: + def __init__(self, keys: list[KeyCode], on_activate: Callable[[], object]) -> None: ... + @staticmethod + def parse(keys: str) -> list[KeyCode]: ... + def press(self, key: Key | KeyCode) -> None: ... + def release(self, key: Key | KeyCode) -> None: ... + +class GlobalHotKeys(Listener): + def __init__(self, hotkeys: SupportsItems[str, Callable[[], None]], *args: Any, **kwargs: Any) -> None: ... diff --git a/stubs/pynput/pynput/keyboard/_base.pyi b/stubs/pynput/pynput/keyboard/_base.pyi new file mode 100644 index 000000000000..fee88c0135dd --- /dev/null +++ b/stubs/pynput/pynput/keyboard/_base.pyi @@ -0,0 +1,146 @@ +import builtins +import contextlib +import enum +import sys +from collections.abc import Callable, Generator, Iterable, Iterator +from typing import Any, ClassVar, cast +from typing_extensions import Self + +from pynput._util import AbstractListener + +class KeyCode: + _PLATFORM_EXTENSIONS: ClassVar[Iterable[str]] # undocumented + vk: int | None + char: str | None + is_dead: bool | None + combining: str | None + def __init__(self, vk: str | None = None, char: str | None = None, is_dead: bool = False, **kwargs: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def join(self, key: Self) -> Self: ... + @classmethod + def from_vk(cls, vk: int, **kwargs: Any) -> Self: ... + @classmethod + def from_char(cls, char: str, **kwargs: Any) -> Self: ... + @classmethod + def from_dead(cls, char: str, **kwargs: Any) -> Self: ... + +class Key(enum.Enum): + alt = cast(KeyCode, ...) + alt_l = cast(KeyCode, ...) + alt_r = cast(KeyCode, ...) + alt_gr = cast(KeyCode, ...) + backspace = cast(KeyCode, ...) + caps_lock = cast(KeyCode, ...) + cmd = cast(KeyCode, ...) + cmd_l = cast(KeyCode, ...) + cmd_r = cast(KeyCode, ...) + ctrl = cast(KeyCode, ...) + ctrl_l = cast(KeyCode, ...) + ctrl_r = cast(KeyCode, ...) + delete = cast(KeyCode, ...) + down = cast(KeyCode, ...) + end = cast(KeyCode, ...) + enter = cast(KeyCode, ...) + esc = cast(KeyCode, ...) + f1 = cast(KeyCode, ...) + f2 = cast(KeyCode, ...) + f3 = cast(KeyCode, ...) + f4 = cast(KeyCode, ...) + f5 = cast(KeyCode, ...) + f6 = cast(KeyCode, ...) + f7 = cast(KeyCode, ...) + f8 = cast(KeyCode, ...) + f9 = cast(KeyCode, ...) + f10 = cast(KeyCode, ...) + f11 = cast(KeyCode, ...) + f12 = cast(KeyCode, ...) + f13 = cast(KeyCode, ...) + f14 = cast(KeyCode, ...) + f15 = cast(KeyCode, ...) + f16 = cast(KeyCode, ...) + f17 = cast(KeyCode, ...) + f18 = cast(KeyCode, ...) + f19 = cast(KeyCode, ...) + f20 = cast(KeyCode, ...) + if sys.platform == "win32": + f21 = cast(KeyCode, ...) + f22 = cast(KeyCode, ...) + f23 = cast(KeyCode, ...) + f24 = cast(KeyCode, ...) + home = cast(KeyCode, ...) + left = cast(KeyCode, ...) + page_down = cast(KeyCode, ...) + page_up = cast(KeyCode, ...) + right = cast(KeyCode, ...) + shift = cast(KeyCode, ...) + shift_l = cast(KeyCode, ...) + shift_r = cast(KeyCode, ...) + space = cast(KeyCode, ...) + tab = cast(KeyCode, ...) + up = cast(KeyCode, ...) + media_play_pause = cast(KeyCode, ...) + media_stop = cast(KeyCode, ...) + media_volume_mute = cast(KeyCode, ...) + media_volume_down = cast(KeyCode, ...) + media_volume_up = cast(KeyCode, ...) + media_previous = cast(KeyCode, ...) + media_next = cast(KeyCode, ...) + if sys.platform == "darwin": + media_eject = cast(KeyCode, ...) + insert = cast(KeyCode, ...) + menu = cast(KeyCode, ...) + num_lock = cast(KeyCode, ...) + pause = cast(KeyCode, ...) + print_screen = cast(KeyCode, ...) + scroll_lock = cast(KeyCode, ...) + +class Controller: + _KeyCode: ClassVar[builtins.type[KeyCode]] # undocumented + _Key: ClassVar[builtins.type[Key]] # undocumented + + if sys.platform == "linux": + CTRL_MASK: ClassVar[int] + SHIFT_MASK: ClassVar[int] + + class InvalidKeyException(Exception): ... + class InvalidCharacterException(Exception): ... + + def __init__(self) -> None: ... + def press(self, key: str | Key | KeyCode) -> None: ... + def release(self, key: str | Key | KeyCode) -> None: ... + def tap(self, key: str | Key | KeyCode) -> None: ... + def touch(self, key: str | Key | KeyCode, is_press: bool) -> None: ... + @contextlib.contextmanager + def pressed(self, *args: str | Key | KeyCode) -> Generator[None]: ... + def type(self, string: str) -> None: ... + @property + def modifiers(self) -> contextlib.AbstractContextManager[Iterator[set[Key]]]: ... + @property + def alt_pressed(self) -> bool: ... + @property + def alt_gr_pressed(self) -> bool: ... + @property + def ctrl_pressed(self) -> bool: ... + @property + def shift_pressed(self) -> bool: ... + +class Listener(AbstractListener): + def __init__( + self, + on_press: ( + Callable[[], bool | None] + | Callable[[Key | KeyCode | None], bool | None] + | Callable[[Key | KeyCode | None, bool], bool | None] + | None + ) = None, + on_release: ( + Callable[[], bool | None] + | Callable[[Key | KeyCode | None], bool | None] + | Callable[[Key | KeyCode | None, bool], bool | None] + | None + ) = None, + suppress: bool = False, + **kwargs: Any, + ) -> None: ... + def canonical(self, key: Key | KeyCode) -> Key | KeyCode: ... diff --git a/stubs/pynput/pynput/keyboard/_dummy.pyi b/stubs/pynput/pynput/keyboard/_dummy.pyi new file mode 100644 index 000000000000..f49ca47776ea --- /dev/null +++ b/stubs/pynput/pynput/keyboard/_dummy.pyi @@ -0,0 +1 @@ +from ._base import Controller as Controller, Key as Key, KeyCode as KeyCode, Listener as Listener diff --git a/stubs/pynput/pynput/mouse/__init__.pyi b/stubs/pynput/pynput/mouse/__init__.pyi new file mode 100644 index 000000000000..42738f852a09 --- /dev/null +++ b/stubs/pynput/pynput/mouse/__init__.pyi @@ -0,0 +1,32 @@ +from typing import Any + +from pynput import _util + +from ._base import Button as Button, Controller as Controller, Listener as Listener + +class Events(_util.Events[Any, Listener]): + class Move(_util.Events.Event): + x: int + y: int + injected: bool + def __init__(self, x: int, y: int, injected: bool) -> None: ... + + class Click(_util.Events.Event): + x: int + y: int + button: Button + pressed: bool + injected: bool + def __init__(self, x: int, y: int, button: Button, pressed: bool, injected: bool) -> None: ... + + class Scroll(_util.Events.Event): + x: int + y: int + dx: int + dy: int + injected: bool + def __init__(self, x: int, y: int, dx: int, dy: int, injected: bool) -> None: ... + + def __init__(self) -> None: ... + def __next__(self) -> Move | Click | Scroll: ... + def get(self, timeout: float | None = None) -> Move | Click | Scroll | None: ... diff --git a/stubs/pynput/pynput/mouse/_base.pyi b/stubs/pynput/pynput/mouse/_base.pyi new file mode 100644 index 000000000000..69cfd78ac520 --- /dev/null +++ b/stubs/pynput/pynput/mouse/_base.pyi @@ -0,0 +1,118 @@ +import enum +import sys +from collections.abc import Callable +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from pynput._util import AbstractListener + +class Button(enum.Enum): + unknown = 0 + left = 1 + middle = 2 + right = 3 + if sys.platform == "linux": + button8 = 8 + button9 = 9 + button10 = 10 + button11 = 11 + button12 = 12 + button13 = 13 + button14 = 14 + button15 = 15 + button16 = 16 + button17 = 17 + button18 = 18 + button19 = 19 + button20 = 20 + button21 = 21 + button22 = 22 + button23 = 23 + button24 = 24 + button25 = 25 + button26 = 26 + button27 = 27 + button28 = 28 + button29 = 29 + button30 = 30 + scroll_down = 5 + scroll_left = 6 + scroll_right = 7 + scroll_up = 4 + if sys.platform == "win32": + x1 = 0 # Value unknown + x2 = 0 # Value unknown + +class Controller: + def __init__(self) -> None: ... + + @property + def position(self) -> tuple[int, int]: ... + @position.setter + def position(self, position: tuple[int, int]) -> None: ... + + def scroll(self, dx: int, dy: int) -> None: ... + def press(self, button: Button) -> None: ... + def release(self, button: Button) -> None: ... + def move(self, dx: int, dy: int) -> None: ... + def click(self, button: Button, count: int = 1) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +class Listener(AbstractListener): + if sys.platform == "win32": + WM_LBUTTONDOWN: int + WM_LBUTTONUP: int + WM_MBUTTONDOWN: int + WM_MBUTTONUP: int + WM_MOUSEMOVE: int + WM_MOUSEWHEEL: int + WM_MOUSEHWHEEL: int + WM_RBUTTONDOWN: int + WM_RBUTTONUP: int + WM_XBUTTONDOWN: int + WM_XBUTTONUP: int + + MK_XBUTTON1: int + MK_XBUTTON2: int + + XBUTTON1: int + XBUTTON2: int + + CLICK_BUTTONS: dict[int, tuple[Button, bool]] + X_BUTTONS: dict[int, dict[int, tuple[Button, bool]]] + SCROLL_BUTTONS: dict[int, tuple[int, int]] + + def __init__( + self, + on_move: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, bool], bool | None] + | None + ) = None, + on_click: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, Button], bool | None] + | Callable[[int, int, Button, bool], bool | None] + | Callable[[int, int, Button, bool, bool], bool | None] + | None + ) = None, + on_scroll: ( + Callable[[], bool | None] + | Callable[[int], bool | None] + | Callable[[int, int], bool | None] + | Callable[[int, int, int], bool | None] + | Callable[[int, int, int, int], bool | None] + | Callable[[int, int, int, int, bool], bool | None] + | None + ) = None, + suppress: bool = False, + **kwargs: Any, + ) -> None: ... diff --git a/stubs/pynput/pynput/mouse/_dummy.pyi b/stubs/pynput/pynput/mouse/_dummy.pyi new file mode 100644 index 000000000000..c799f582b620 --- /dev/null +++ b/stubs/pynput/pynput/mouse/_dummy.pyi @@ -0,0 +1 @@ +from ._base import Button as Button, Controller as Controller, Listener as Listener diff --git a/stubs/pyogrio/@tests/stubtest_allowlist.txt b/stubs/pyogrio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9ac53dcdeb3e --- /dev/null +++ b/stubs/pyogrio/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +pyogrio\.tests(\..*)? +pyogrio\._typing # stubs only module diff --git a/stubs/pyogrio/METADATA.toml b/stubs/pyogrio/METADATA.toml new file mode 100644 index 000000000000..a5b8927e9444 --- /dev/null +++ b/stubs/pyogrio/METADATA.toml @@ -0,0 +1,5 @@ +version = "0.13.*" +upstream-repository = "https://github.com/geopandas/pyogrio" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] +optional-dependencies = ["types-geopandas"] diff --git a/stubs/pyogrio/pyogrio/__init__.pyi b/stubs/pyogrio/pyogrio/__init__.pyi new file mode 100644 index 000000000000..22149bb24903 --- /dev/null +++ b/stubs/pyogrio/pyogrio/__init__.pyi @@ -0,0 +1,47 @@ +from .core import ( + __gdal_geos_version__ as __gdal_geos_version__, + __gdal_version__ as __gdal_version__, + __gdal_version_string__ as __gdal_version_string__, + detect_write_driver as detect_write_driver, + get_gdal_config_option as get_gdal_config_option, + get_gdal_data_path as get_gdal_data_path, + list_drivers as list_drivers, + list_drivers_details as list_drivers_details, + list_layers as list_layers, + read_bounds as read_bounds, + read_info as read_info, + set_gdal_config_options as set_gdal_config_options, + vsi_curl_clear_cache as vsi_curl_clear_cache, + vsi_listtree as vsi_listtree, + vsi_rmtree as vsi_rmtree, + vsi_unlink as vsi_unlink, +) +from .geopandas import read_dataframe as read_dataframe, write_dataframe as write_dataframe +from .raw import open_arrow as open_arrow, read_arrow as read_arrow, write_arrow as write_arrow + +__all__ = [ + "__gdal_geos_version__", + "__gdal_version__", + "__gdal_version_string__", + "__version__", + "detect_write_driver", + "get_gdal_config_option", + "get_gdal_data_path", + "list_drivers", + "list_drivers_details", + "list_layers", + "open_arrow", + "read_arrow", + "read_bounds", + "read_dataframe", + "read_info", + "set_gdal_config_options", + "vsi_curl_clear_cache", + "vsi_listtree", + "vsi_rmtree", + "vsi_unlink", + "write_arrow", + "write_dataframe", +] + +__version__: str diff --git a/stubs/pyogrio/pyogrio/_typing.pyi b/stubs/pyogrio/pyogrio/_typing.pyi new file mode 100644 index 000000000000..ac1e0f912d6a --- /dev/null +++ b/stubs/pyogrio/pyogrio/_typing.pyi @@ -0,0 +1,28 @@ +import io +from _typeshed import SupportsRead +from collections.abc import Collection +from pathlib import Path +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import CapsuleType + +import numpy as np + +_T = TypeVar("_T") +_G = TypeVar("_G", bound=np.generic) +_G_co = TypeVar("_G_co", bound=np.generic, covariant=True) + +@type_check_only +class SupportsArrowCStream(Protocol): + def __arrow_c_stream__(self, requested_schema: object | None = None) -> CapsuleType: ... + +@type_check_only +class SupportsArray(Protocol[_G_co]): + def __array__(self) -> np.ndarray[Any, np.dtype[_G_co]]: ... + +Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_G]] +Array2D: TypeAlias = np.ndarray[tuple[int, int], np.dtype[_G]] +ReadPathOrBuffer: TypeAlias = str | Path | bytes | SupportsRead[bytes] +WritePathOrBuffer: TypeAlias = str | Path | io.BytesIO + +DualArrayLike: TypeAlias = SupportsArray[_G] | Collection[_T] | _T +ArrayLikeInt: TypeAlias = DualArrayLike[np.bool | np.integer, int] diff --git a/stubs/pyogrio/pyogrio/core.pyi b/stubs/pyogrio/pyogrio/core.pyi new file mode 100644 index 000000000000..a3b0264eebc6 --- /dev/null +++ b/stubs/pyogrio/pyogrio/core.pyi @@ -0,0 +1,82 @@ +from pathlib import Path +from typing import Any, Literal, TypedDict, type_check_only + +import numpy as np +import shapely as shp + +from ._typing import Array1D, Array2D, ReadPathOrBuffer + +__gdal_version__: tuple[int, int, int] +__gdal_version_string__: str +__gdal_geos_version__: tuple[int, int, int] | None + +@type_check_only +class _Capabilities(TypedDict): + random_read: bool + fast_set_next_by_index: bool + fast_spatial_filter: bool + fast_feature_count: bool + fast_total_bounds: bool + +@type_check_only +class _LayerInfo(TypedDict): + layer_name: str + # crs is `None` for non-spatial layers + crs: str | None + fields: Array1D[np.object_] # field names (strings) + dtypes: Array1D[np.object_] # field dtypes (strings) + ogr_types: list[str] + ogr_subtypes: list[str] + encoding: str + fid_column: str + geometry_name: str + # geometry_type is `None` for non-spatial layers + geometry_type: str | None + features: int + # total_bounds is `None` for non-spatial layers or if expensive to compute + total_bounds: tuple[float, float, float, float] | None + driver: str + capabilities: _Capabilities + dataset_metadata: dict[str, str] | None + layer_metadata: dict[str, str] | None + +@type_check_only +class _DriverDetails(TypedDict): + long_name: str + read: bool + append: bool + write: bool + supports_vsi: bool + help_topic_url: str | None + extensions: list[str] | None + +def list_drivers(read: bool = False, write: bool = False, append: bool = False) -> dict[str, Literal["r", "rw"]]: ... +def list_drivers_details() -> dict[str, _DriverDetails]: ... +def detect_write_driver(path: str | Path) -> str: ... # `path` is coerced to string internally +def list_layers(path_or_buffer: ReadPathOrBuffer, /) -> Array2D[np.object_]: ... +def read_bounds( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, +) -> tuple[Array1D[np.int64], Array2D[np.float64]]: ... +def read_info( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + force_feature_count: bool = False, + force_total_bounds: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> _LayerInfo: ... +def set_gdal_config_options(options: dict[str, Any]) -> None: ... +def get_gdal_config_option(name: str) -> Any: ... # Could return str, int, bool, or None +def get_gdal_data_path() -> str: ... +def vsi_listtree(path: str | Path, pattern: str | None = None) -> list[str]: ... +def vsi_rmtree(path: str | Path) -> None: ... +def vsi_unlink(path: str | Path) -> None: ... +def vsi_curl_clear_cache(prefix: str | Path = "") -> None: ... diff --git a/stubs/pyogrio/pyogrio/errors.pyi b/stubs/pyogrio/pyogrio/errors.pyi new file mode 100644 index 000000000000..38f893ce66c9 --- /dev/null +++ b/stubs/pyogrio/pyogrio/errors.pyi @@ -0,0 +1,6 @@ +class DataSourceError(RuntimeError): ... +class DataLayerError(RuntimeError): ... +class CRSError(DataLayerError): ... +class FeatureError(DataLayerError): ... +class GeometryError(DataLayerError): ... +class FieldError(DataLayerError): ... diff --git a/stubs/pyogrio/pyogrio/geopandas.pyi b/stubs/pyogrio/pyogrio/geopandas.pyi new file mode 100644 index 000000000000..ec6f67fb1829 --- /dev/null +++ b/stubs/pyogrio/pyogrio/geopandas.pyi @@ -0,0 +1,80 @@ +import os +from collections.abc import Collection, Mapping +from typing import Any, Literal, overload + +import geopandas as gpd +import pandas as pd +import shapely as shp + +from ._typing import ArrayLikeInt, ReadPathOrBuffer, WritePathOrBuffer + +@overload +def read_dataframe( + path_or_buffer: ReadPathOrBuffer | os.PathLike[str], + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: Literal[True] = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + fid_as_index: bool = False, + use_arrow: bool | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + arrow_to_pandas_kwargs: Mapping[str, Any] | None = None, + datetime_as_string: bool = False, + mixed_offsets_as_utc: bool = True, + **kwargs: Any, # Dataset open options passed to OGR +) -> gpd.GeoDataFrame: ... +@overload +def read_dataframe( + path_or_buffer: ReadPathOrBuffer | os.PathLike[str], + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + *, + read_geometry: Literal[False], + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + fid_as_index: bool = False, + use_arrow: bool | None = None, + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + arrow_to_pandas_kwargs: Mapping[str, Any] | None = None, + datetime_as_string: bool = False, + mixed_offsets_as_utc: bool = True, + **kwargs: Any, # Dataset open options passed to OGR +) -> pd.DataFrame: ... + +def write_dataframe( + df: pd.DataFrame, + path: WritePathOrBuffer, + layer: str | None = None, + driver: str | None = None, + encoding: str | None = None, + geometry_type: str | None = None, + promote_to_multi: bool | None = None, + nan_as_null: bool = True, + append: bool = False, + use_arrow: bool | None = None, + dataset_metadata: dict[str, Any] | None = None, + layer_metadata: dict[str, Any] | None = None, + metadata: dict[str, Any] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... diff --git a/stubs/pyogrio/pyogrio/raw.pyi b/stubs/pyogrio/pyogrio/raw.pyi new file mode 100644 index 000000000000..2271f506f985 --- /dev/null +++ b/stubs/pyogrio/pyogrio/raw.pyi @@ -0,0 +1,179 @@ +from collections.abc import Collection, Iterable +from contextlib import AbstractContextManager +from typing import Any, Literal, TypedDict, overload, type_check_only + +import numpy as np +import pyarrow as pa # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] # ty:ignore[unresolved-import] # pyrefly: ignore [missing-import] +import shapely as shp + +from ._typing import Array1D, ArrayLikeInt, ReadPathOrBuffer, SupportsArrowCStream, WritePathOrBuffer + +DRIVERS_NO_MIXED_SINGLE_MULTI: set[str] +DRIVERS_NO_MIXED_DIMENSIONS: set[str] + +@type_check_only +class _Meta(TypedDict): + crs: str + fields: Array1D[np.object_] + dtypes: Array1D[np.object_] + ogr_types: list[str] + ogr_subtypes: list[str] + encoding: str + geometry_type: str + geometry_name: str + fid_column: str + +@overload +def read( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: Literal[False] = False, + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, None, Array1D[np.object_] | None, list[np.ndarray]]: ... +@overload +def read( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + *, + return_fids: Literal[True], + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, Array1D[np.int64], Array1D[np.object_] | None, list[np.ndarray]]: ... + +def read_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + datetime_as_string: bool = False, + *, + batch_size: int = 65536, # Extracted from kwargs + **kwargs: Any, # Dataset open options passed to OGR +) -> tuple[_Meta, pa.Table]: ... + +@overload +def open_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + batch_size: int = 65536, + use_pyarrow: Literal[False] = False, + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> AbstractContextManager[tuple[_Meta, SupportsArrowCStream]]: ... +@overload +def open_arrow( + path_or_buffer: ReadPathOrBuffer, + /, + layer: int | str | None = None, + encoding: str | None = None, + columns: Collection[str] | None = None, + read_geometry: bool = True, + force_2d: bool = False, + skip_features: int = 0, + max_features: int | None = None, + where: str | None = None, + bbox: tuple[float, float, float, float] | None = None, + mask: shp.Geometry | None = None, + fids: ArrayLikeInt | None = None, + sql: str | None = None, + sql_dialect: str | None = None, + return_fids: bool = False, + batch_size: int = 65536, + *, + use_pyarrow: Literal[True], + datetime_as_string: bool = False, + **kwargs: Any, # Dataset open options passed to OGR +) -> AbstractContextManager[tuple[_Meta, pa.RecordBatchReader]]: ... + +def write( + path: WritePathOrBuffer, + geometry: np.ndarray | None, # ndarray of WKB encoded geometries or None + field_data: Iterable[np.ndarray] | None, + fields: Iterable[str], + field_mask: Iterable[np.ndarray | None] | None = None, + layer: str | None = None, + driver: str | None = None, + geometry_type: str | None = None, + crs: str | None = None, + encoding: str | None = None, + promote_to_multi: bool | None = None, + nan_as_null: bool = True, + append: bool = False, + dataset_metadata: dict[str, str] | None = None, + layer_metadata: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + gdal_tz_offsets: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... +def write_arrow( + arrow_obj: SupportsArrowCStream, + path: WritePathOrBuffer, + layer: str | None = None, + driver: str | None = None, + geometry_name: str | None = None, + geometry_type: str | None = None, + crs: str | None = None, + encoding: str | None = None, + append: bool = False, + dataset_metadata: dict[str, str] | None = None, + layer_metadata: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + dataset_options: dict[str, Any] | None = None, + layer_options: dict[str, Any] | None = None, + **kwargs: Any, # Additional driver-specific dataset or layer creation options passed to OGR +) -> None: ... diff --git a/stubs/pyogrio/pyogrio/util.pyi b/stubs/pyogrio/pyogrio/util.pyi new file mode 100644 index 000000000000..758089b2791a --- /dev/null +++ b/stubs/pyogrio/pyogrio/util.pyi @@ -0,0 +1,11 @@ +from pathlib import Path + +from ._typing import ReadPathOrBuffer + +def get_vsi_path_or_buffer(path_or_buffer: ReadPathOrBuffer) -> str | bytes: ... +def vsi_path(path: str | Path) -> str: ... + +SCHEMES: dict[str, str] +CURLSCHEMES: set[str] + +def vsimem_rmtree_toplevel(path: str | Path) -> None: ... diff --git a/stubs/pyperclip/@tests/stubtest_allowlist.txt b/stubs/pyperclip/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..096a897229c8 --- /dev/null +++ b/stubs/pyperclip/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +pyperclip.__main__ diff --git a/stubs/pyperclip/METADATA.toml b/stubs/pyperclip/METADATA.toml new file mode 100644 index 000000000000..a2f5db7c354d --- /dev/null +++ b/stubs/pyperclip/METADATA.toml @@ -0,0 +1,6 @@ +version = "1.11.*" +upstream-repository = "https://github.com/asweigart/pyperclip" + +[tool.stubtest] +ci-platforms = ["win32", "linux", "darwin"] +apt-dependencies = ["xclip"] diff --git a/stubs/pyperclip/pyperclip/__init__.pyi b/stubs/pyperclip/pyperclip/__init__.pyi new file mode 100644 index 000000000000..28ac5248078d --- /dev/null +++ b/stubs/pyperclip/pyperclip/__init__.pyi @@ -0,0 +1,23 @@ +__all__ = ["copy", "paste", "set_clipboard", "determine_clipboard"] + +from collections.abc import Callable +from typing import Literal, TypeAlias + +class PyperclipException(RuntimeError): ... + +class PyperclipWindowsException(PyperclipException): + def __init__(self, message: str) -> None: ... + +class PyperclipTimeoutException(PyperclipException): ... + +_ClipboardMechanismName: TypeAlias = Literal[ + "pbcopy", "pyobjc", "qt", "xclip", "xsel", "wl-clipboard", "klipper", "windows", "no" +] +_ClipboardCopyMechanism: TypeAlias = Callable[[str], None] +_ClipboardPasteMechanism: TypeAlias = Callable[[], str] + +def copy(text: str) -> None: ... +def paste() -> str: ... +def set_clipboard(clipboard: _ClipboardMechanismName) -> None: ... +def determine_clipboard() -> tuple[_ClipboardCopyMechanism, _ClipboardPasteMechanism]: ... +def is_available() -> bool: ... diff --git a/stubs/pyphen/METADATA.toml b/stubs/pyphen/METADATA.toml new file mode 100644 index 000000000000..f6b2d875f6b8 --- /dev/null +++ b/stubs/pyphen/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.17.2" +upstream-repository = "https://github.com/Kozea/Pyphen" diff --git a/stubs/pyphen/pyphen/__init__.pyi b/stubs/pyphen/pyphen/__init__.pyi new file mode 100644 index 000000000000..157358ea6fda --- /dev/null +++ b/stubs/pyphen/pyphen/__init__.pyi @@ -0,0 +1,43 @@ +from collections.abc import Generator +from pathlib import Path +from typing import SupportsInt, TypeAlias +from typing_extensions import Self + +__all__ = ("LANGUAGES", "Pyphen", "language_fallback") +LANGUAGES: dict[str, Path] +_Data: TypeAlias = tuple[str, int, int] + +def language_fallback(language: str) -> str: ... + +class AlternativeParser: + change: str + index: int + cut: int + + def __init__(self, pattern: str, alternative: str) -> None: ... + def __call__(self, value: str | SupportsInt) -> int: ... + +class DataInt(int): + data: _Data | None + + def __new__(cls, value: int, data: _Data | None = ..., reference: DataInt | None = ...) -> Self: ... + +class HyphDict: + patterns: dict[str, tuple[int, tuple[int, ...]]] + cache: dict[str, list[DataInt]] + maxlen: int + + def __init__(self, path: Path) -> None: ... + def positions(self, word: str) -> list[DataInt]: ... + +class Pyphen: + hd: HyphDict + + def __init__( + self, filename: str | Path | None = ..., lang: str | None = ..., left: int = 2, right: int = 2, cache: bool = True + ) -> None: ... + def positions(self, word: str) -> list[DataInt]: ... + def iterate(self, word: str) -> Generator[tuple[str, str]]: ... + def wrap(self, word: str, width: int, hyphen: str = "-") -> tuple[str, str] | None: ... + def inserted(self, word: str, hyphen: str = "-") -> str: ... + __call__ = iterate diff --git a/stubs/pyserial/@tests/stubtest_allowlist.txt b/stubs/pyserial/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..69717d5f7fd3 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist.txt @@ -0,0 +1,48 @@ +# Error: failed to import +# ======================= +serial.__main__ # SystemExit +serial.serialcli # (IronPython) ModuleNotFoundError: No module named 'System' +serial.serialjava # No Java Communications API implementation found + +# Error: is inconsistent +# ====================== +# These are positional only argument in the stub because they inherit from io.RawIOBase +# but at runtime they are normal arguments that don't have consistent names. +serial.serialutil.SerialBase.readinto +serial.rfc2217.Serial.write +serial.rs485.RS485.write +serial.urlhandler.protocol_cp2110.Serial.write +serial.urlhandler.protocol_loop.Serial.write +serial.urlhandler.protocol_socket.Serial.write +serial.urlhandler.protocol_spy.Serial.write + +# Error: is not present in stub +# ============================= +# Python 2 compatibility +serial.basestring +serial.serialutil.basestring +serial.serialutil.iterbytes +serial.serialutil.to_bytes +serial.serialutil.unicode +serial.tools.hexlify_codec.unicode +serial.tools.miniterm.raw_input +serial.tools.miniterm.unichr +serial.urlhandler.protocol_hwgrep.basestring + +# Deprecated aliases +serial.serialutil.SerialBase.applySettingsDict +serial.serialutil.SerialBase.flushInput +serial.serialutil.SerialBase.flushOutput +serial.serialutil.SerialBase.getCD +serial.serialutil.SerialBase.getCTS +serial.serialutil.SerialBase.getDSR +serial.serialutil.SerialBase.getRI +serial.serialutil.SerialBase.getSettingsDict +serial.serialutil.SerialBase.inWaiting +serial.serialutil.SerialBase.interCharTimeout +serial.serialutil.SerialBase.isOpen +serial.serialutil.SerialBase.sendBreak +serial.serialutil.SerialBase.setDTR +serial.serialutil.SerialBase.setPort +serial.serialutil.SerialBase.setRTS +serial.serialutil.SerialBase.writeTimeout diff --git a/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt b/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..ebfc25005da3 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,16 @@ +# Error: failed to import +# ======================= +serial.serialwin32 # Windows only +serial.win32 # Windows only +serial.tools.list_ports_windows # Windows only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialposix.Serial.write + +# intended to be private aliases +serial.tools.list_ports_posix.plat +serial.serialposix.plat diff --git a/stubs/pyserial/@tests/stubtest_allowlist_linux.txt b/stubs/pyserial/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..6de3777701dd --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,18 @@ +# Error: failed to import +# ======================= +serial.serialwin32 # Windows only +serial.win32 # Windows only +serial.tools.list_ports_osx # Mac only +serial.tools.list_ports_windows # Windows only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialposix.Serial.write + +# Error: is missing from the stub (intended to be private aliases) +# ================================================================ +serial.tools.list_ports_posix.plat +serial.serialposix.plat diff --git a/stubs/pyserial/@tests/stubtest_allowlist_win32.txt b/stubs/pyserial/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..7ba9097251f6 --- /dev/null +++ b/stubs/pyserial/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,16 @@ +# Error: failed to import +# ======================= +serial.serialposix # Posix only +serial.tools.list_ports_osx # Mac only +serial.tools.list_ports_posix # Posix only + +# Error: is inconsistent +# ====================== +# Methods defined with positional-only argument in the stub because they inherit from +# io.RawIOBase but at runtime they are normal arguments that don't have consistent +# names. +serial.serialwin32.Serial.write + +# Depending on the Windows variant, ULONG_PTR is either c_longlong or c_ulong, +# but when running stubtest, only one of these is seen. +serial.win32.ULONG_PTR diff --git a/stubs/pyserial/METADATA.toml b/stubs/pyserial/METADATA.toml new file mode 100644 index 000000000000..3726b119da44 --- /dev/null +++ b/stubs/pyserial/METADATA.toml @@ -0,0 +1,6 @@ +version = "3.5.*" +upstream-repository = "https://github.com/pyserial/pyserial" + +[tool.stubtest] +ci-platforms = ["darwin", "linux", "win32"] +extras = ["cp2110"] diff --git a/stubs/pyserial/serial/__init__.pyi b/stubs/pyserial/serial/__init__.pyi new file mode 100644 index 000000000000..7677f130ed41 --- /dev/null +++ b/stubs/pyserial/serial/__init__.pyi @@ -0,0 +1,30 @@ +import sys + +from serial.serialutil import * + +if sys.platform == "win32": + from serial.serialwin32 import Serial as Serial +else: + from serial.serialposix import PosixPollSerial as PosixPollSerial, Serial as Serial, VTIMESerial as VTIMESerial +# TODO: java? cli? These platforms raise flake8-pyi Y008. Should they be included with a noqa? + +__version__: str +VERSION: str +protocol_handler_packages: list[str] + +def serial_for_url( + url: str | None, + baudrate: int = ..., + bytesize: int = ..., + parity: str = ..., + stopbits: float = ..., + timeout: float | None = ..., + xonxoff: bool = ..., + rtscts: bool = ..., + write_timeout: float | None = ..., + dsrdtr: bool = ..., + inter_byte_timeout: float | None = ..., + exclusive: float | None = ..., + *, + do_not_open: bool = ..., +) -> Serial: ... diff --git a/stubs/pyserial/serial/__main__.pyi b/stubs/pyserial/serial/__main__.pyi new file mode 100644 index 000000000000..195cbe7140dc --- /dev/null +++ b/stubs/pyserial/serial/__main__.pyi @@ -0,0 +1 @@ +from serial.tools import miniterm as miniterm diff --git a/stubs/pyserial/serial/rfc2217.pyi b/stubs/pyserial/serial/rfc2217.pyi new file mode 100644 index 000000000000..39275b8b7e8f --- /dev/null +++ b/stubs/pyserial/serial/rfc2217.pyi @@ -0,0 +1,187 @@ +import logging +from _typeshed import ReadableBuffer +from collections.abc import Callable, Generator +from typing import Any + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] +SE: bytes +NOP: bytes +DM: bytes +BRK: bytes +IP: bytes +AO: bytes +AYT: bytes +EC: bytes +EL: bytes +GA: bytes +SB: bytes +WILL: bytes +WONT: bytes +DO: bytes +DONT: bytes +IAC: bytes +IAC_DOUBLED: bytes +BINARY: bytes +ECHO: bytes +SGA: bytes +COM_PORT_OPTION: bytes +SET_BAUDRATE: bytes +SET_DATASIZE: bytes +SET_PARITY: bytes +SET_STOPSIZE: bytes +SET_CONTROL: bytes +NOTIFY_LINESTATE: bytes +NOTIFY_MODEMSTATE: bytes +FLOWCONTROL_SUSPEND: bytes +FLOWCONTROL_RESUME: bytes +SET_LINESTATE_MASK: bytes +SET_MODEMSTATE_MASK: bytes +PURGE_DATA: bytes +SERVER_SET_BAUDRATE: bytes +SERVER_SET_DATASIZE: bytes +SERVER_SET_PARITY: bytes +SERVER_SET_STOPSIZE: bytes +SERVER_SET_CONTROL: bytes +SERVER_NOTIFY_LINESTATE: bytes +SERVER_NOTIFY_MODEMSTATE: bytes +SERVER_FLOWCONTROL_SUSPEND: bytes +SERVER_FLOWCONTROL_RESUME: bytes +SERVER_SET_LINESTATE_MASK: bytes +SERVER_SET_MODEMSTATE_MASK: bytes +SERVER_PURGE_DATA: bytes +RFC2217_ANSWER_MAP: dict[bytes, bytes] +SET_CONTROL_REQ_FLOW_SETTING: bytes +SET_CONTROL_USE_NO_FLOW_CONTROL: bytes +SET_CONTROL_USE_SW_FLOW_CONTROL: bytes +SET_CONTROL_USE_HW_FLOW_CONTROL: bytes +SET_CONTROL_REQ_BREAK_STATE: bytes +SET_CONTROL_BREAK_ON: bytes +SET_CONTROL_BREAK_OFF: bytes +SET_CONTROL_REQ_DTR: bytes +SET_CONTROL_DTR_ON: bytes +SET_CONTROL_DTR_OFF: bytes +SET_CONTROL_REQ_RTS: bytes +SET_CONTROL_RTS_ON: bytes +SET_CONTROL_RTS_OFF: bytes +SET_CONTROL_REQ_FLOW_SETTING_IN: bytes +SET_CONTROL_USE_NO_FLOW_CONTROL_IN: bytes +SET_CONTROL_USE_SW_FLOW_CONTOL_IN: bytes +SET_CONTROL_USE_HW_FLOW_CONTOL_IN: bytes +SET_CONTROL_USE_DCD_FLOW_CONTROL: bytes +SET_CONTROL_USE_DTR_FLOW_CONTROL: bytes +SET_CONTROL_USE_DSR_FLOW_CONTROL: bytes +LINESTATE_MASK_TIMEOUT: int +LINESTATE_MASK_SHIFTREG_EMPTY: int +LINESTATE_MASK_TRANSREG_EMPTY: int +LINESTATE_MASK_BREAK_DETECT: int +LINESTATE_MASK_FRAMING_ERROR: int +LINESTATE_MASK_PARTIY_ERROR: int +LINESTATE_MASK_OVERRUN_ERROR: int +LINESTATE_MASK_DATA_READY: int +MODEMSTATE_MASK_CD: int +MODEMSTATE_MASK_RI: int +MODEMSTATE_MASK_DSR: int +MODEMSTATE_MASK_CTS: int +MODEMSTATE_MASK_CD_CHANGE: int +MODEMSTATE_MASK_RI_CHANGE: int +MODEMSTATE_MASK_DSR_CHANGE: int +MODEMSTATE_MASK_CTS_CHANGE: int +PURGE_RECEIVE_BUFFER: bytes +PURGE_TRANSMIT_BUFFER: bytes +PURGE_BOTH_BUFFERS: bytes +RFC2217_PARITY_MAP: dict[str, int] +RFC2217_REVERSE_PARITY_MAP: dict[int, str] +RFC2217_STOPBIT_MAP: dict[int | float, int] +RFC2217_REVERSE_STOPBIT_MAP: dict[int, int | float] +M_NORMAL: int +M_IAC_SEEN: int +M_NEGOTIATE: int +REQUESTED: str +ACTIVE: str +INACTIVE: str +REALLY_INACTIVE: str + +class TelnetOption: + connection: Serial + name: str + option: bytes + send_yes: bytes + send_no: bytes + ack_yes: bytes + ack_no: bytes + state: str + active: bool + activation_callback: Callable[[], Any] + + def __init__( + self, + connection: Serial, + name: str, + option: bytes, + send_yes: bytes, + send_no: bytes, + ack_yes: bytes, + ack_no: bytes, + initial_state: str, + activation_callback: Callable[[], Any] | None = None, + ) -> None: ... + def process_incoming(self, command: bytes) -> None: ... + +class TelnetSubnegotiation: + connection: Serial + name: str + option: bytes + value: bytes | None + ack_option: bytes + state: str + def __init__(self, connection: Serial, name: str, option: bytes, ack_option: bytes | None = None) -> None: ... + def set(self, value: bytes) -> None: ... + def is_ready(self) -> bool: ... + @property + def active(self) -> bool: ... + def wait(self, timeout: float = 3) -> None: ... + def check_answer(self, suboption: bytes) -> None: ... + +class Serial(SerialBase): + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> tuple[str, int]: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + def telnet_send_option(self, action: bytes, option: bytes) -> None: ... + def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... + def rfc2217_send_purge(self, value: bytes) -> None: ... + def rfc2217_set_control(self, value: bytes) -> None: ... + def rfc2217_flow_server_ready(self) -> None: ... + def get_modem_state(self) -> int: ... + +class PortManager: + serial: Serial + connection: Serial + logger: logging.Logger | None + mode: int + suboption: bytes | None + telnet_command: bytes | None + modemstate_mask: int + last_modemstate: int | None + linstate_mask: int + def __init__(self, serial_port: Serial, connection: Serial, logger: logging.Logger | None = None) -> None: ... + def telnet_send_option(self, action: bytes, option: bytes) -> None: ... + def rfc2217_send_subnegotiation(self, option: bytes, value: bytes = b"") -> None: ... + def check_modem_lines(self, force_notification: bool = False) -> None: ... + def escape(self, data: bytes) -> Generator[bytes]: ... + def filter(self, data: bytes) -> Generator[bytes]: ... diff --git a/stubs/pyserial/serial/rs485.pyi b/stubs/pyserial/serial/rs485.pyi new file mode 100644 index 000000000000..b76617efb818 --- /dev/null +++ b/stubs/pyserial/serial/rs485.pyi @@ -0,0 +1,18 @@ +import serial + +class RS485Settings: + rts_level_for_tx: bool + rts_level_for_rx: bool + loopback: bool + delay_before_tx: float | None + delay_before_rx: float | None + def __init__( + self, + rts_level_for_tx: bool = True, + rts_level_for_rx: bool = False, + loopback: bool = False, + delay_before_tx: float | None = None, + delay_before_rx: float | None = None, + ) -> None: ... + +class RS485(serial.Serial): ... diff --git a/stubs/pyserial/serial/serialcli.pyi b/stubs/pyserial/serial/serialcli.pyi new file mode 100644 index 000000000000..f243980d4c03 --- /dev/null +++ b/stubs/pyserial/serial/serialcli.pyi @@ -0,0 +1,25 @@ +from _typeshed import ReadableBuffer +from typing import Any + +from serial.serialutil import * + +sab: Any # IronPython object + +def as_byte_array(string: bytes) -> Any: ... # IronPython object + +class Serial(SerialBase): + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/serialjava.pyi b/stubs/pyserial/serial/serialjava.pyi new file mode 100644 index 000000000000..de4dcd57e6fc --- /dev/null +++ b/stubs/pyserial/serial/serialjava.pyi @@ -0,0 +1,30 @@ +from _typeshed import ReadableBuffer +from collections.abc import Iterable +from typing import Any + +from serial.serialutil import * + +def my_import(name: str) -> Any: ... # Java object +def detect_java_comm(names: Iterable[str]) -> Any: ... # Java object + +comm: Any # Java object + +def device(portnumber: int) -> str: ... + +class Serial(SerialBase): + sPort: Any # Java object + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/serialposix.pyi b/stubs/pyserial/serial/serialposix.pyi new file mode 100644 index 000000000000..2313419ca368 --- /dev/null +++ b/stubs/pyserial/serial/serialposix.pyi @@ -0,0 +1,88 @@ +import sys +from _typeshed import ReadableBuffer +from typing_extensions import Never + +from serial.serialutil import SerialBase + +class PlatformSpecificBase: + BAUDRATE_CONSTANTS: dict[int, int] + def set_low_latency_mode(self, low_latency_settings: bool) -> None: ... + +CMSPAR: int +if sys.platform == "linux": + TCGETS2: int + TCSETS2: int + BOTHER: int + TIOCGRS485: int + TIOCSRS485: int + SER_RS485_ENABLED: int + SER_RS485_RTS_ON_SEND: int + SER_RS485_RTS_AFTER_SEND: int + SER_RS485_RX_DURING_TX: int + +if sys.platform == "darwin": + IOSSIOSPEED: int + + class PlatformSpecific(PlatformSpecificBase): + osx_version: list[str] + TIOCSBRK: int + TIOCCBRK: int + +else: + class PlatformSpecific(PlatformSpecificBase): ... + +TIOCMGET: int +TIOCMBIS: int +TIOCMBIC: int +TIOCMSET: int +TIOCM_DTR: int +TIOCM_RTS: int +TIOCM_CTS: int +TIOCM_CAR: int +TIOCM_RNG: int +TIOCM_DSR: int +TIOCM_CD: int +TIOCM_RI: int +TIOCINQ: int +TIOCOUTQ: int +TIOCM_zero_str: bytes +TIOCM_RTS_str: bytes +TIOCM_DTR_str: bytes +TIOCSBRK: int +TIOCCBRK: int + +class Serial(SerialBase, PlatformSpecific): + fd: int | None + pipe_abort_read_w: int | None + pipe_abort_read_r: int | None + pipe_abort_write_w: int | None + pipe_abort_write_r: int | None + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + def send_break(self, duration: float = 0.25) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + @property + def out_waiting(self) -> int: ... + def set_input_flow_control(self, enable: bool = True) -> None: ... + def set_output_flow_control(self, enable: bool = True) -> None: ... + def nonblocking(self) -> None: ... + +class PosixPollSerial(Serial): ... + +class VTIMESerial(Serial): + @property + def cancel_read(self) -> Never: ... diff --git a/stubs/pyserial/serial/serialutil.pyi b/stubs/pyserial/serial/serialutil.pyi new file mode 100644 index 000000000000..a21681d688e7 --- /dev/null +++ b/stubs/pyserial/serial/serialutil.pyi @@ -0,0 +1,169 @@ +import io +from _typeshed import ReadableBuffer, WriteableBuffer +from abc import abstractmethod +from collections.abc import Callable, Generator +from typing import Any, Final + +from serial.rs485 import RS485Settings + +XON: Final = b"\x11" +XOFF: Final = b"\x13" +CR: Final = b"\r" +LF: Final = b"\n" +PARITY_NONE: Final = "N" +PARITY_EVEN: Final = "E" +PARITY_ODD: Final = "O" +PARITY_MARK: Final = "M" +PARITY_SPACE: Final = "S" +STOPBITS_ONE: Final = 1 +STOPBITS_ONE_POINT_FIVE: float +STOPBITS_TWO: Final = 2 +FIVEBITS: Final = 5 +SIXBITS: Final = 6 +SEVENBITS: Final = 7 +EIGHTBITS: Final = 8 +PARITY_NAMES: dict[str, str] + +class SerialException(OSError): ... +class SerialTimeoutException(SerialException): ... + +class PortNotOpenError(SerialException): + def __init__(self) -> None: ... + +class Timeout: + TIME: Callable[[], float] + is_infinite: bool + is_non_blocking: bool + duration: float + target_time: float + def __init__(self, duration: float) -> None: ... + def expired(self) -> bool: ... + def time_left(self) -> float: ... + def restart(self, duration: float) -> None: ... + +class SerialBase(io.RawIOBase): + BAUDRATES: tuple[int, ...] + BYTESIZES: tuple[int, ...] + PARITIES: tuple[str, ...] + STOPBITS: tuple[int, float, int] + is_open: bool + portstr: str | None + name: str | None + def __init__( + self, + port: str | None = None, + baudrate: int = 9600, + bytesize: int = 8, + parity: str = "N", + stopbits: float = 1, + timeout: float | None = None, + xonxoff: bool = False, + rtscts: bool = False, + write_timeout: float | None = None, + dsrdtr: bool = False, + inter_byte_timeout: float | None = None, + exclusive: bool | None = None, + ) -> None: ... + + # Return type: + # ------------ + # `io.RawIOBase`, the super class, declares the return type of read as `-> bytes | None`. + # `SerialBase` does not define `read` at runtime but REQUIRES subclasses to implement it and + # require it to return `bytes`. + # Abstract: + # --------- + # `io.RawIOBase` implements `read` in terms of `readinto`. `SerialBase` implements `readinto` + # in terms of `read`. If subclasses do not implement `read`, any call to `read` or `read_into` + # will fail at runtime with a `RecursionError`. + @abstractmethod + def read(self, size: int = -1, /) -> bytes: ... + @abstractmethod + def write(self, b: ReadableBuffer, /) -> int | None: ... + + @property + def port(self) -> str | None: ... + @port.setter + def port(self, port: str | None) -> None: ... + + @property + def baudrate(self) -> int: ... + @baudrate.setter + def baudrate(self, baudrate: int) -> None: ... + + @property + def bytesize(self) -> int: ... + @bytesize.setter + def bytesize(self, bytesize: int) -> None: ... + + @property + def exclusive(self) -> bool | None: ... + @exclusive.setter + def exclusive(self, exclusive: bool | None) -> None: ... + + @property + def parity(self) -> str: ... + @parity.setter + def parity(self, parity: str) -> None: ... + + @property + def stopbits(self) -> float: ... + @stopbits.setter + def stopbits(self, stopbits: float) -> None: ... + + @property + def timeout(self) -> float | None: ... + @timeout.setter + def timeout(self, timeout: float | None) -> None: ... + + @property + def write_timeout(self) -> float | None: ... + @write_timeout.setter + def write_timeout(self, timeout: float | None) -> None: ... + + @property + def inter_byte_timeout(self) -> float | None: ... + @inter_byte_timeout.setter + def inter_byte_timeout(self, ic_timeout: float | None) -> None: ... + + @property + def xonxoff(self) -> bool: ... + @xonxoff.setter + def xonxoff(self, xonxoff: bool) -> None: ... + + @property + def rtscts(self) -> bool: ... + @rtscts.setter + def rtscts(self, rtscts: bool) -> None: ... + + @property + def dsrdtr(self) -> bool: ... + @dsrdtr.setter + def dsrdtr(self, dsrdtr: bool | None = ...) -> None: ... + + @property + def rts(self) -> bool: ... + @rts.setter + def rts(self, value: bool) -> None: ... + + @property + def dtr(self) -> bool: ... + @dtr.setter + def dtr(self, value: bool) -> None: ... + + @property + def break_condition(self) -> bool: ... + @break_condition.setter + def break_condition(self, value: bool) -> None: ... + + @property + def rs485_mode(self) -> RS485Settings | None: ... + @rs485_mode.setter + def rs485_mode(self, rs485_settings: RS485Settings | None) -> None: ... + + def get_settings(self) -> dict[str, Any]: ... + def apply_settings(self, d: dict[str, Any]) -> None: ... + def readinto(self, buffer: WriteableBuffer, /) -> int: ... # returns int unlike `io.RawIOBase` + def send_break(self, duration: float = 0.25) -> None: ... + def read_all(self) -> bytes: ... + def read_until(self, expected: bytes = b"\n", size: int | None = None) -> bytes: ... + def iread_until(self, expected: bytes = ..., size: int | None = ...) -> Generator[bytes]: ... diff --git a/stubs/pyserial/serial/serialwin32.pyi b/stubs/pyserial/serial/serialwin32.pyi new file mode 100644 index 000000000000..8fb2e3ba38d6 --- /dev/null +++ b/stubs/pyserial/serial/serialwin32.pyi @@ -0,0 +1,26 @@ +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +class Serial(SerialBase): + def open(self) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... + def set_buffer_size(self, rx_size: int = 4096, tx_size: int | None = None) -> None: ... + def set_output_flow_control(self, enable: bool = True) -> None: ... + @property + def out_waiting(self) -> int: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... diff --git a/stubs/pyserial/serial/threaded/__init__.pyi b/stubs/pyserial/serial/threaded/__init__.pyi new file mode 100644 index 000000000000..4cc3c15648ee --- /dev/null +++ b/stubs/pyserial/serial/threaded/__init__.pyi @@ -0,0 +1,51 @@ +import threading +from _typeshed import ReadableBuffer +from collections.abc import Callable +from types import TracebackType +from typing import Generic, TypeVar +from typing_extensions import Self + +from serial import Serial + +_P = TypeVar("_P", bound=Protocol, default=Protocol) + +class Protocol: + def connection_made(self, transport: ReaderThread[Self]) -> None: ... + def data_received(self, data: bytes) -> None: ... + def connection_lost(self, exc: BaseException | None) -> None: ... + +class Packetizer(Protocol): + TERMINATOR: bytes + buffer: bytearray + transport: ReaderThread[Self] | None + def handle_packet(self, packet: bytes) -> None: ... + +class FramedPacket(Protocol): + START: bytes + STOP: bytes + packet: bytearray + in_packet: bool + transport: ReaderThread[Self] | None + def handle_packet(self, packet: bytes) -> None: ... + def handle_out_of_packet_data(self, data: bytes) -> None: ... + +class LineReader(Packetizer): + ENCODING: str + UNICODE_HANDLING: str + def handle_line(self, line: str) -> None: ... + def write_line(self, text: str) -> None: ... + +class ReaderThread(threading.Thread, Generic[_P]): + serial: Serial + protocol_factory: Callable[[], _P] + alive: bool + protocol: _P + def __init__(self, serial_instance: Serial, protocol_factory: Callable[[], _P]) -> None: ... + def stop(self) -> None: ... + def write(self, data: ReadableBuffer) -> int: ... + def close(self) -> None: ... + def connect(self) -> tuple[Self, _P]: ... + def __enter__(self) -> _P: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / + ) -> None: ... diff --git a/stubs/pyserial/serial/tools/__init__.pyi b/stubs/pyserial/serial/tools/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyserial/serial/tools/hexlify_codec.pyi b/stubs/pyserial/serial/tools/hexlify_codec.pyi new file mode 100644 index 000000000000..10e43143ee48 --- /dev/null +++ b/stubs/pyserial/serial/tools/hexlify_codec.pyi @@ -0,0 +1,23 @@ +import codecs +from _typeshed import ReadableBuffer + +HEXDIGITS: str + +def hex_encode(data: str, errors: str = "strict") -> tuple[bytes, int]: ... +def hex_decode(data: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class Codec(codecs.Codec): + def encode(self, data: str, errors: str = "strict") -> tuple[bytes, int]: ... + def decode(self, data: bytes, errors: str = "strict") -> tuple[str, int]: ... + +class IncrementalEncoder(codecs.IncrementalEncoder): + state: int + def encode(self, data: str, final: bool = False) -> bytes: ... + +class IncrementalDecoder(codecs.IncrementalDecoder): + def decode(self, data: ReadableBuffer, final: bool = False) -> str: ... + +class StreamWriter(Codec, codecs.StreamWriter): ... +class StreamReader(Codec, codecs.StreamReader): ... + +def getregentry() -> codecs.CodecInfo: ... diff --git a/stubs/pyserial/serial/tools/list_ports.pyi b/stubs/pyserial/serial/tools/list_ports.pyi new file mode 100644 index 000000000000..be96fdc686fb --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports.pyi @@ -0,0 +1,13 @@ +import re +import sys +from collections.abc import Generator + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "win32": + from serial.tools.list_ports_windows import comports as comports +else: + from serial.tools.list_ports_posix import comports as comports + +def grep(regexp: str | re.Pattern[str], include_links: bool = False) -> Generator[ListPortInfo]: ... +def main() -> None: ... diff --git a/stubs/pyserial/serial/tools/list_ports_common.pyi b/stubs/pyserial/serial/tools/list_ports_common.pyi new file mode 100644 index 000000000000..465bb04062aa --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_common.pyi @@ -0,0 +1,33 @@ +from collections.abc import Collection +from typing import Any + +def numsplit(text: str) -> list[str | int]: ... + +class ListPortInfo: + device: str + name: str + description: str + hwid: str + # USB specific data: the vid and pid attributes below are specific to USB devices only and + # should be marked as Optional. Since the majority of the serial devices nowadays are USB + # devices, typing them as Optional will be unnecessarily annoying. We type them with as + # `int | Any` so that obvious typing errors like ListPortInfo.pid + "str" are flagged. + # As desired, this will cause a false negative if the value is ever None, but may also cause + # other false negatives from the Any proliferating. The other USB attributes are correctly + # typed as Optional because they may be `None` even for USB devices + # Original discussion at https://github.com/python/typeshed/pull/9347#issuecomment-1358245865. + vid: int | Any + pid: int | Any + serial_number: str | None + location: str | None + manufacturer: str | None + product: str | None + interface: str | None + def __init__(self, device: str, skip_link_detection: bool = False) -> None: ... + def usb_description(self) -> str: ... + def usb_info(self) -> str: ... + def apply_usb_info(self) -> None: ... + def __lt__(self, other: ListPortInfo) -> bool: ... + def __getitem__(self, index: int) -> str: ... + +def list_links(devices: Collection[str]) -> list[str]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_linux.pyi b/stubs/pyserial/serial/tools/list_ports_linux.pyi new file mode 100644 index 000000000000..a56d2c581132 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_linux.pyi @@ -0,0 +1,11 @@ +from serial.tools.list_ports_common import ListPortInfo + +class SysFS(ListPortInfo): + usb_device_path: str | None + device_path: str | None + subsystem: str | None + usb_interface_path: str | None + def __init__(self, device: str) -> None: ... + def read_line(self, *args: str) -> str | None: ... + +def comports(include_links: bool = False) -> list[SysFS]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_osx.pyi b/stubs/pyserial/serial/tools/list_ports_osx.pyi new file mode 100644 index 000000000000..49746028a3f7 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_osx.pyi @@ -0,0 +1,36 @@ +import ctypes +import sys + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "darwin": + iokit: ctypes.CDLL + cf: ctypes.CDLL + kIOMasterPortDefault: int + kCFAllocatorDefault: ctypes.c_void_p + kCFStringEncodingMacRoman: int + kCFStringEncodingUTF8: int + kUSBVendorString: str + kUSBSerialNumberString: str + io_name_size: int + KERN_SUCCESS: int + kern_return_t = ctypes.c_int + kCFNumberSInt8Type: int + kCFNumberSInt16Type: int + kCFNumberSInt32Type: int + kCFNumberSInt64Type: int + + def get_string_property(device_type: ctypes._CData, property: str) -> str | None: ... + def get_int_property(device_type: ctypes._CData, property: str, cf_number_type: int) -> int | None: ... + def IORegistryEntryGetName(device: ctypes._CData) -> str | None: ... + def IOObjectGetClass(device: ctypes._CData) -> bytes: ... + def GetParentDeviceByType(device: ctypes._CData, parent_type: str) -> ctypes._CData | None: ... + def GetIOServicesByType(service_type: str) -> list[ctypes._CData]: ... + def location_to_string(locationID: int) -> str: ... + + # `SuitableSerialInterface` has required attributes `id: int` and `name: str` but they are not defined on the class + class SuitableSerialInterface: ... + + def scan_interfaces() -> list[SuitableSerialInterface]: ... + def search_for_locationID_in_interfaces(serial_interfaces: list[SuitableSerialInterface], locationID: int) -> str | None: ... + def comports(include_links: bool = False) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_posix.pyi b/stubs/pyserial/serial/tools/list_ports_posix.pyi new file mode 100644 index 000000000000..969dfd42ef45 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_posix.pyi @@ -0,0 +1,11 @@ +import sys + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform != "win32": + if sys.platform == "linux": + from serial.tools.list_ports_linux import comports as comports + elif sys.platform == "darwin": + from serial.tools.list_ports_osx import comports as comports + else: + def comports(include_links: bool = ...) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/list_ports_windows.pyi b/stubs/pyserial/serial/tools/list_ports_windows.pyi new file mode 100644 index 000000000000..b5ba02fc7714 --- /dev/null +++ b/stubs/pyserial/serial/tools/list_ports_windows.pyi @@ -0,0 +1,78 @@ +import ctypes +import sys +from _typeshed import Incomplete +from collections.abc import Generator +from ctypes.wintypes import DWORD + +from serial.tools.list_ports_common import ListPortInfo + +if sys.platform == "win32": + + def ValidHandle( + value: type[ctypes._CData] | None, func: ctypes._FuncPointer, arguments: tuple[ctypes._CData, ...] + ) -> ctypes._CData: ... + + NULL: int + HDEVINFO = ctypes.c_void_p + LPCTSTR = ctypes.c_wchar_p + PCTSTR = ctypes.c_wchar_p + PTSTR = ctypes.c_wchar_p + LPDWORD: ctypes._Pointer[DWORD] + PDWORD: ctypes._Pointer[DWORD] + LPBYTE = ctypes.c_void_p + PBYTE = ctypes.c_void_p + ACCESS_MASK = DWORD + REGSAM = ACCESS_MASK + + class GUID(ctypes.Structure): + Data1: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data2: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data3: ctypes._CField[Incomplete, Incomplete, Incomplete] + Data4: ctypes._CField[Incomplete, Incomplete, Incomplete] + + class SP_DEVINFO_DATA(ctypes.Structure): + cbSize: ctypes._CField[Incomplete, Incomplete, Incomplete] + ClassGuid: ctypes._CField[Incomplete, Incomplete, Incomplete] + DevInst: ctypes._CField[Incomplete, Incomplete, Incomplete] + Reserved: ctypes._CField[Incomplete, Incomplete, Incomplete] + + PSP_DEVINFO_DATA: type[ctypes._Pointer[SP_DEVINFO_DATA]] + PSP_DEVICE_INTERFACE_DETAIL_DATA = ctypes.c_void_p + setupapi: ctypes.WinDLL + SetupDiDestroyDeviceInfoList: ctypes._NamedFuncPointer + SetupDiClassGuidsFromName: ctypes._NamedFuncPointer + SetupDiEnumDeviceInfo: ctypes._NamedFuncPointer + SetupDiGetClassDevs: ctypes._NamedFuncPointer + SetupDiGetDeviceRegistryProperty: ctypes._NamedFuncPointer + SetupDiGetDeviceInstanceId: ctypes._NamedFuncPointer + SetupDiOpenDevRegKey: ctypes._NamedFuncPointer + advapi32: ctypes.WinDLL + RegCloseKey: ctypes._NamedFuncPointer + RegQueryValueEx: ctypes._NamedFuncPointer + cfgmgr32: ctypes.WinDLL + CM_Get_Parent: ctypes._NamedFuncPointer + CM_Get_Device_IDW: ctypes._NamedFuncPointer + CM_MapCrToWin32Err: ctypes._NamedFuncPointer + DIGCF_PRESENT: int + DIGCF_DEVICEINTERFACE: int + INVALID_HANDLE_VALUE: int + ERROR_INSUFFICIENT_BUFFER: int + ERROR_NOT_FOUND: int + SPDRP_HARDWAREID: int + SPDRP_FRIENDLYNAME: int + SPDRP_LOCATION_PATHS: int + SPDRP_MFG: int + DICS_FLAG_GLOBAL: int + DIREG_DEV: int + KEY_READ: int + MAX_USB_DEVICE_TREE_TRAVERSAL_DEPTH: int + + def get_parent_serial_number( + child_devinst: ctypes._CData, + child_vid: int | None, + child_pid: int | None, + depth: int = 0, + last_serial_number: str | None = None, + ) -> str: ... + def iterate_comports() -> Generator[ListPortInfo]: ... + def comports(include_links: bool = False) -> list[ListPortInfo]: ... diff --git a/stubs/pyserial/serial/tools/miniterm.pyi b/stubs/pyserial/serial/tools/miniterm.pyi new file mode 100644 index 000000000000..2d541ea056ba --- /dev/null +++ b/stubs/pyserial/serial/tools/miniterm.pyi @@ -0,0 +1,122 @@ +import codecs +import sys +import threading +from _typeshed import SupportsFlush, SupportsWrite, Unused +from collections.abc import Iterable +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from serial import Serial + +_AnyStrT_contra = TypeVar("_AnyStrT_contra", contravariant=True) + +@type_check_only +class _SupportsWriteAndFlush(SupportsWrite[_AnyStrT_contra], SupportsFlush, Protocol): ... + +@type_check_only +class _SupportsRead(Protocol): + def read(self, n: int, /) -> str: ... + +def key_description(character: str) -> str: ... + +class ConsoleBase: + byte_output: _SupportsWriteAndFlush[bytes] + output: _SupportsWriteAndFlush[str] + def __init__(self) -> None: ... + def setup(self) -> None: ... + def cleanup(self) -> None: ... + def getkey(self) -> None: ... + def write_bytes(self, byte_string: bytes) -> None: ... + def write(self, text: str) -> None: ... + def cancel(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused, **kwargs: Unused) -> None: ... + +if sys.platform == "win32": + class Out: + fd: int + def __init__(self, fd: int) -> None: ... + def flush(self) -> None: ... + def write(self, s: bytes) -> None: ... + + class Console(ConsoleBase): + fncodes: dict[str, str] + navcodes: dict[str, str] + def __del__(self) -> None: ... + +else: + class Console(ConsoleBase): + fd: int + old: list[Any] # return type of termios.tcgetattr() + enc_stdin: _SupportsRead + +class Transform: + def rx(self, text: str) -> str: ... + def tx(self, text: str) -> str: ... + def echo(self, text: str) -> str: ... + +class CRLF(Transform): ... +class CR(Transform): ... +class LF(Transform): ... + +class NoTerminal(Transform): + REPLACEMENT_MAP: dict[int, int] + +class NoControls(NoTerminal): + REPLACEMENT_MAP: dict[int, int] + +class Printable(Transform): ... + +class Colorize(Transform): + input_color: str + echo_color: str + +class DebugIO(Transform): ... + +EOL_TRANSFORMATIONS: dict[str, type[Transform]] +TRANSFORMATIONS: dict[str, type[Transform]] + +def ask_for_port() -> str: ... + +class Miniterm: + console: Console + serial: Serial + echo: bool + raw: bool + input_encoding: str + output_encoding: str + eol: str + filters: Iterable[str] + exit_character: str + menu_character: str + alive: bool | None + receiver_thread: threading.Thread | None + rx_decoder: codecs.IncrementalDecoder | None + tx_decoder: codecs.IncrementalDecoder | None + tx_encoder: codecs.IncrementalEncoder | None + def __init__(self, serial_instance: Serial, echo: bool = False, eol: str = "crlf", filters: Iterable[str] = ()) -> None: ... + transmitter_thread: threading.Thread + def start(self) -> None: ... + def stop(self) -> None: ... + def join(self, transmit_only: bool = False) -> None: ... + def close(self) -> None: ... + tx_transformations: list[Transform] + rx_transformations: list[Transform] + def update_transformations(self) -> None: ... + def set_rx_encoding(self, encoding: str, errors: str = "replace") -> None: ... + def set_tx_encoding(self, encoding: str, errors: str = "replace") -> None: ... + def dump_port_settings(self) -> None: ... + def reader(self) -> None: ... + def writer(self) -> None: ... + def handle_menu_key(self, c: str) -> None: ... + def upload_file(self) -> None: ... + def change_filter(self) -> None: ... + def change_encoding(self) -> None: ... + def change_baudrate(self) -> None: ... + def change_port(self) -> None: ... + def suspend_port(self) -> None: ... + def get_help_text(self) -> str: ... + +def main( + default_port: str | None = None, default_baudrate: int = 9600, default_rts: int | None = None, default_dtr: int | None = None +) -> None: ... diff --git a/stubs/pyserial/serial/urlhandler/__init__.pyi b/stubs/pyserial/serial/urlhandler/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pyserial/serial/urlhandler/protocol_alt.pyi b/stubs/pyserial/serial/urlhandler/protocol_alt.pyi new file mode 100644 index 000000000000..9711af93c435 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_alt.pyi @@ -0,0 +1,3 @@ +from serial import Serial + +def serial_class_for_url(url: str) -> tuple[str, Serial]: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi b/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi new file mode 100644 index 000000000000..661e9d3830a4 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_cp2110.pyi @@ -0,0 +1,13 @@ +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +class Serial(SerialBase): + def open(self) -> None: ... + def from_url(self, url: str) -> bytes: ... + @property + def in_waiting(self) -> int: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi b/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi new file mode 100644 index 000000000000..93dc1402ae55 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_hwgrep.pyi @@ -0,0 +1,4 @@ +import serial + +class Serial(serial.Serial): + def from_url(self, url: str) -> str: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_loop.pyi b/stubs/pyserial/serial/urlhandler/protocol_loop.pyi new file mode 100644 index 000000000000..97db0d4dfcf1 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_loop.pyi @@ -0,0 +1,32 @@ +import logging +import queue as _queue +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] + +class Serial(SerialBase): + buffer_size: int + queue: _queue.Queue[bytes | None] | None + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> None: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def cancel_read(self) -> None: ... + def cancel_write(self) -> None: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def out_waiting(self) -> int: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi b/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi new file mode 100644 index 000000000000..82903b51464b --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_rfc2217.pyi @@ -0,0 +1 @@ +from serial.rfc2217 import Serial as Serial diff --git a/stubs/pyserial/serial/urlhandler/protocol_socket.pyi b/stubs/pyserial/serial/urlhandler/protocol_socket.pyi new file mode 100644 index 000000000000..9ac407eb76db --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_socket.pyi @@ -0,0 +1,26 @@ +import logging +from _typeshed import ReadableBuffer + +from serial.serialutil import SerialBase + +LOGGER_LEVELS: dict[str, int] +POLL_TIMEOUT: float + +class Serial(SerialBase): + logger: logging.Logger | None + def open(self) -> None: ... + def from_url(self, url: str) -> tuple[str, int]: ... + @property + def in_waiting(self) -> int: ... + def read(self, size: int = 1) -> bytes: ... + def write(self, b: ReadableBuffer, /) -> int | None: ... + def reset_input_buffer(self) -> None: ... + def reset_output_buffer(self) -> None: ... + @property + def cts(self) -> bool: ... + @property + def dsr(self) -> bool: ... + @property + def ri(self) -> bool: ... + @property + def cd(self) -> bool: ... diff --git a/stubs/pyserial/serial/urlhandler/protocol_spy.pyi b/stubs/pyserial/serial/urlhandler/protocol_spy.pyi new file mode 100644 index 000000000000..29b45167dc76 --- /dev/null +++ b/stubs/pyserial/serial/urlhandler/protocol_spy.pyi @@ -0,0 +1,35 @@ +from collections.abc import Generator +from typing import TextIO, type_check_only + +import serial + +def sixteen(data: bytes) -> Generator[tuple[str, str] | tuple[None, None]]: ... +def hexdump(data: bytes) -> Generator[tuple[int, str]]: ... + +@type_check_only +class _Formatter: + def rx(self, data: bytes) -> None: ... + def tx(self, data: bytes) -> None: ... + def control(self, name: str, value: str) -> None: ... + +class FormatRaw(_Formatter): + output: TextIO + color: bool + rx_color: str + tx_color: str + def __init__(self, output: TextIO, color: bool) -> None: ... + +class FormatHexdump(_Formatter): + start_time: float + output: TextIO + color: bool + rx_color: str + tx_color: str + control_color: str + def __init__(self, output: TextIO, color: bool) -> None: ... + def write_line(self, timestamp: float, label: str, value: str, value2: str = "") -> None: ... + +class Serial(serial.Serial): + formatter: FormatRaw | FormatHexdump | None + show_all: bool + def from_url(self, url: str) -> str: ... diff --git a/stubs/pyserial/serial/win32.pyi b/stubs/pyserial/serial/win32.pyi new file mode 100644 index 000000000000..807f2679c4e5 --- /dev/null +++ b/stubs/pyserial/serial/win32.pyi @@ -0,0 +1,253 @@ +import sys +from _typeshed import Incomplete +from ctypes import Structure, Union, _CField, _NamedFuncPointer, _Pointer, c_int64, c_ulong, c_void_p +from ctypes.wintypes import DWORD +from typing import TypeAlias + +if sys.platform == "win32": + def is_64bit() -> bool: ... + + ULONG_PTR: type[c_int64 | c_ulong] + + class _SECURITY_ATTRIBUTES(Structure): + nLength: _CField[Incomplete, Incomplete, Incomplete] + lpSecurityDescriptor: _CField[Incomplete, Incomplete, Incomplete] + bInheritHandle: _CField[Incomplete, Incomplete, Incomplete] + + LPSECURITY_ATTRIBUTES: type[_Pointer[_SECURITY_ATTRIBUTES]] + CreateEvent: _NamedFuncPointer + CreateFile: _NamedFuncPointer + # The following are included in __all__ but their existence is not guaranteed as + # they are defined in a try/except block. Their aliases above are always defined. + CreateEventW: _NamedFuncPointer + CreateFileW: _NamedFuncPointer + + class _OVERLAPPED(Structure): + Internal: _CField[Incomplete, Incomplete, Incomplete] + InternalHigh: _CField[Incomplete, Incomplete, Incomplete] + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] + hEvent: _CField[Incomplete, Incomplete, Incomplete] + + OVERLAPPED: TypeAlias = _OVERLAPPED + + class _COMSTAT(Structure): + fCtsHold: _CField[Incomplete, Incomplete, Incomplete] + fDsrHold: _CField[Incomplete, Incomplete, Incomplete] + fRlsdHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffHold: _CField[Incomplete, Incomplete, Incomplete] + fXoffSent: _CField[Incomplete, Incomplete, Incomplete] + fEof: _CField[Incomplete, Incomplete, Incomplete] + fTxim: _CField[Incomplete, Incomplete, Incomplete] + fReserved: _CField[Incomplete, Incomplete, Incomplete] + cbInQue: _CField[Incomplete, Incomplete, Incomplete] + cbOutQue: _CField[Incomplete, Incomplete, Incomplete] + + COMSTAT: TypeAlias = _COMSTAT + + class _DCB(Structure): + DCBlength: _CField[Incomplete, Incomplete, Incomplete] + BaudRate: _CField[Incomplete, Incomplete, Incomplete] + fBinary: _CField[Incomplete, Incomplete, Incomplete] + fParity: _CField[Incomplete, Incomplete, Incomplete] + fOutxCtsFlow: _CField[Incomplete, Incomplete, Incomplete] + fOutxDsrFlow: _CField[Incomplete, Incomplete, Incomplete] + fDtrControl: _CField[Incomplete, Incomplete, Incomplete] + fDsrSensitivity: _CField[Incomplete, Incomplete, Incomplete] + fTXContinueOnXoff: _CField[Incomplete, Incomplete, Incomplete] + fOutX: _CField[Incomplete, Incomplete, Incomplete] + fInX: _CField[Incomplete, Incomplete, Incomplete] + fErrorChar: _CField[Incomplete, Incomplete, Incomplete] + fNull: _CField[Incomplete, Incomplete, Incomplete] + fRtsControl: _CField[Incomplete, Incomplete, Incomplete] + fAbortOnError: _CField[Incomplete, Incomplete, Incomplete] + fDummy2: _CField[Incomplete, Incomplete, Incomplete] + wReserved: _CField[Incomplete, Incomplete, Incomplete] + XonLim: _CField[Incomplete, Incomplete, Incomplete] + XoffLim: _CField[Incomplete, Incomplete, Incomplete] + ByteSize: _CField[Incomplete, Incomplete, Incomplete] + Parity: _CField[Incomplete, Incomplete, Incomplete] + StopBits: _CField[Incomplete, Incomplete, Incomplete] + XonChar: _CField[Incomplete, Incomplete, Incomplete] + XoffChar: _CField[Incomplete, Incomplete, Incomplete] + ErrorChar: _CField[Incomplete, Incomplete, Incomplete] + EofChar: _CField[Incomplete, Incomplete, Incomplete] + EvtChar: _CField[Incomplete, Incomplete, Incomplete] + wReserved1: _CField[Incomplete, Incomplete, Incomplete] + + DCB: TypeAlias = _DCB + + class _COMMTIMEOUTS(Structure): + ReadIntervalTimeout: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + ReadTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutMultiplier: _CField[Incomplete, Incomplete, Incomplete] + WriteTotalTimeoutConstant: _CField[Incomplete, Incomplete, Incomplete] + + COMMTIMEOUTS: TypeAlias = _COMMTIMEOUTS + + GetLastError: _NamedFuncPointer + LPOVERLAPPED: type[_Pointer[_OVERLAPPED]] + LPDWORD: type[_Pointer[DWORD]] + GetOverlappedResult: _NamedFuncPointer + ResetEvent: _NamedFuncPointer + LPCVOID = c_void_p + WriteFile: _NamedFuncPointer + LPVOID = c_void_p + ReadFile: _NamedFuncPointer + CloseHandle: _NamedFuncPointer + ClearCommBreak: _NamedFuncPointer + LPCOMSTAT: type[_Pointer[_COMSTAT]] + ClearCommError: _NamedFuncPointer + SetupComm: _NamedFuncPointer + EscapeCommFunction: _NamedFuncPointer + GetCommModemStatus: _NamedFuncPointer + LPDCB: type[_Pointer[_DCB]] + GetCommState: _NamedFuncPointer + LPCOMMTIMEOUTS: type[_Pointer[_COMMTIMEOUTS]] + GetCommTimeouts: _NamedFuncPointer + PurgeComm: _NamedFuncPointer + SetCommBreak: _NamedFuncPointer + SetCommMask: _NamedFuncPointer + SetCommState: _NamedFuncPointer + SetCommTimeouts: _NamedFuncPointer + WaitForSingleObject: _NamedFuncPointer + WaitCommEvent: _NamedFuncPointer + CancelIoEx: _NamedFuncPointer + + ONESTOPBIT: int + TWOSTOPBITS: int + NOPARITY: int + ODDPARITY: int + EVENPARITY: int + RTS_CONTROL_HANDSHAKE: int + RTS_CONTROL_ENABLE: int + DTR_CONTROL_HANDSHAKE: int + DTR_CONTROL_ENABLE: int + MS_DSR_ON: int + EV_RING: int + EV_PERR: int + EV_ERR: int + SETXOFF: int + EV_RXCHAR: int + GENERIC_WRITE: int + PURGE_TXCLEAR: int + FILE_FLAG_OVERLAPPED: int + EV_DSR: int + MAXDWORD: int + EV_RLSD: int + ERROR_IO_PENDING: int + MS_CTS_ON: int + EV_EVENT1: int + EV_RX80FULL: int + PURGE_RXABORT: int + FILE_ATTRIBUTE_NORMAL: int + PURGE_TXABORT: int + SETXON: int + OPEN_EXISTING: int + MS_RING_ON: int + EV_TXEMPTY: int + EV_RXFLAG: int + MS_RLSD_ON: int + GENERIC_READ: int + EV_EVENT2: int + EV_CTS: int + EV_BREAK: int + PURGE_RXCLEAR: int + + class N11_OVERLAPPED4DOLLAR_48E(Union): + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + Pointer: _CField[Incomplete, Incomplete, Incomplete] + + class N11_OVERLAPPED4DOLLAR_484DOLLAR_49E(Structure): + Offset: _CField[Incomplete, Incomplete, Incomplete] + OffsetHigh: _CField[Incomplete, Incomplete, Incomplete] + + PVOID: TypeAlias = c_void_p + + __all__ = [ + "GetLastError", + "MS_CTS_ON", + "FILE_ATTRIBUTE_NORMAL", + "DTR_CONTROL_ENABLE", + "_COMSTAT", + "MS_RLSD_ON", + "GetOverlappedResult", + "SETXON", + "PURGE_TXABORT", + "PurgeComm", + "N11_OVERLAPPED4DOLLAR_48E", + "EV_RING", + "ONESTOPBIT", + "SETXOFF", + "PURGE_RXABORT", + "GetCommState", + "RTS_CONTROL_ENABLE", + "_DCB", + "CreateEvent", + "_COMMTIMEOUTS", + "_SECURITY_ATTRIBUTES", + "EV_DSR", + "EV_PERR", + "EV_RXFLAG", + "OPEN_EXISTING", + "DCB", + "FILE_FLAG_OVERLAPPED", + "EV_CTS", + "SetupComm", + "LPOVERLAPPED", + "EV_TXEMPTY", + "ClearCommBreak", + "LPSECURITY_ATTRIBUTES", + "SetCommBreak", + "SetCommTimeouts", + "COMMTIMEOUTS", + "ODDPARITY", + "EV_RLSD", + "GetCommModemStatus", + "EV_EVENT2", + "PURGE_TXCLEAR", + "EV_BREAK", + "EVENPARITY", + "LPCVOID", + "COMSTAT", + "ReadFile", + "PVOID", + "_OVERLAPPED", + "WriteFile", + "GetCommTimeouts", + "ResetEvent", + "EV_RXCHAR", + "LPCOMSTAT", + "ClearCommError", + "ERROR_IO_PENDING", + "EscapeCommFunction", + "GENERIC_READ", + "RTS_CONTROL_HANDSHAKE", + "OVERLAPPED", + "DTR_CONTROL_HANDSHAKE", + "PURGE_RXCLEAR", + "GENERIC_WRITE", + "LPDCB", + "CreateEventW", + "SetCommMask", + "EV_EVENT1", + "SetCommState", + "LPVOID", + "CreateFileW", + "LPDWORD", + "EV_RX80FULL", + "TWOSTOPBITS", + "LPCOMMTIMEOUTS", + "MAXDWORD", + "MS_DSR_ON", + "MS_RING_ON", + "N11_OVERLAPPED4DOLLAR_484DOLLAR_49E", + "EV_ERR", + "ULONG_PTR", + "CreateFile", + "NOPARITY", + "CloseHandle", + ] diff --git a/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt b/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7d0609ba5797 --- /dev/null +++ b/stubs/pytest-lazy-fixture/@tests/stubtest_allowlist.txt @@ -0,0 +1,13 @@ +# Part of the pytest API, which is internal: +pytest_lazyfixture.pytest_.* + +# Internal undocumented API: +pytest_lazyfixture.fillfixtures +pytest_lazyfixture.normalize_call +pytest_lazyfixture.normalize_metafunc_calls +pytest_lazyfixture.sorted_by_dependency +pytest_lazyfixture.copy_metafunc + +# Compat: +pytest_lazyfixture.PY3 +pytest_lazyfixture.string_type diff --git a/stubs/pytest-lazy-fixture/METADATA.toml b/stubs/pytest-lazy-fixture/METADATA.toml new file mode 100644 index 000000000000..60f7b81673f3 --- /dev/null +++ b/stubs/pytest-lazy-fixture/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.6.*" +upstream-repository = "https://github.com/tvorog/pytest-lazy-fixture" diff --git a/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi b/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi new file mode 100644 index 000000000000..3f9f07febe87 --- /dev/null +++ b/stubs/pytest-lazy-fixture/pytest_lazyfixture.pyi @@ -0,0 +1,15 @@ +from collections.abc import Iterable +from typing import Any, overload +from typing_extensions import TypeIs + +class LazyFixture: + name: str + def __init__(self, name: str) -> None: ... + def __eq__(self, other: object) -> bool: ... + +@overload +def lazy_fixture(names: str) -> LazyFixture: ... +@overload +def lazy_fixture(names: Iterable[str]) -> list[LazyFixture] | Any: ... + +def is_lazy_fixture(val: object) -> TypeIs[LazyFixture]: ... diff --git a/stubs/python-crontab/@tests/stubtest_allowlist.txt b/stubs/python-crontab/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..51b8a2b6fb81 --- /dev/null +++ b/stubs/python-crontab/@tests/stubtest_allowlist.txt @@ -0,0 +1,5 @@ +# Runtime only-hack that doesn't affect typing: +crontabs.CronTabs.__new__ +# stub does not have *args argument "args", but function doesn't actually accept positional args +crontab.CronTab.remove_all +crontab.OrderedVariableList.__init__ diff --git a/stubs/python-crontab/METADATA.toml b/stubs/python-crontab/METADATA.toml new file mode 100644 index 000000000000..6a47d346981a --- /dev/null +++ b/stubs/python-crontab/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.3.*" +upstream-repository = "https://gitlab.com/doctormo/python-crontab" +dependencies = ["types-croniter"] diff --git a/stubs/python-crontab/cronlog.pyi b/stubs/python-crontab/cronlog.pyi new file mode 100644 index 000000000000..2d5d5b8ac5aa --- /dev/null +++ b/stubs/python-crontab/cronlog.pyi @@ -0,0 +1,36 @@ +from _typeshed import StrOrBytesPath +from codecs import StreamReaderWriter +from collections.abc import Generator, Iterator +from datetime import datetime +from types import TracebackType +from typing_extensions import Self + +MATCHER: str + +class LogReader: + filename: StrOrBytesPath + mass: int + size: int + read: int + pipe: StreamReaderWriter | None + def __init__(self, filename: StrOrBytesPath, mass: int = 4096) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, error_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def readlines(self, until: int = 0) -> Generator[tuple[int, str]]: ... + +def cron_date_to_datetime(cron_str: str) -> datetime: ... + +class CronLog(LogReader): + user: str | None + def __init__(self, filename: StrOrBytesPath = "/var/log/syslog", user: str | None = None) -> None: ... + def for_program(self, command: str) -> ProgramLog: ... + def __iter__(self) -> dict[str, str | None]: ... # type: ignore[override] + +class ProgramLog: + log: CronLog + command: str + def __init__(self, log: CronLog, command: str) -> None: ... + def __iter__(self) -> dict[str, str | None]: ... diff --git a/stubs/python-crontab/crontab.pyi b/stubs/python-crontab/crontab.pyi new file mode 100644 index 000000000000..2bd4d755e389 --- /dev/null +++ b/stubs/python-crontab/crontab.pyi @@ -0,0 +1,331 @@ +import re +import subprocess +from _typeshed import StrPath +from builtins import range as _range +from collections import OrderedDict +from collections.abc import Callable, Generator, Iterable, Iterator +from datetime import datetime +from logging import Logger +from types import TracebackType +from typing import Any, Final, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +from croniter.croniter import croniter +from cronlog import CronLog + +_User: TypeAlias = str | bool | None +_K = TypeVar("_K") +_V = TypeVar("_V") + +# cron_descriptor.Options class +@type_check_only +class _Options(Protocol): + casing_type: Literal[1, 2, 3] + verbose: bool + day_of_week_start_index_zero: bool + use_24hour_time_format: bool + locale_location: StrPath | None + locale_code: str | None + def __init__(self) -> None: ... + +__pkgname__: Final[str] +__version__: Final[str] +ITEMREX: Final[re.Pattern[str]] +SPECREX: Final[re.Pattern[str]] +DEVNULL: Final[str] +WEEK_ENUM: Final[list[str]] +MONTH_ENUM: Final[list[str | None]] +SPECIALS_CONVERSION: Final[bool] +SPECIALS: Final[dict[str, str]] +SPECIAL_IGNORE: Final[list[str]] +S_INFO: Final[list[dict[str, str | int | list[str] | list[str | None]]]] +WINOS: Final[bool] +POSIX: Final[bool] +SYSTEMV: Final[bool] +ZERO_PAD: Final[bool] +LOG: Logger +CRON_COMMAND: Final[str] +SHELL: Final[str] +current_user: Callable[[], str | None] + +class Process: + env: subprocess._ENV | None + args: tuple[str, ...] + has_run: bool + stdout: str | None + stderr: str | None + returncode: int | None + # `posix` and `env` are known special kwargs: + def __init__(self, cmd: str, *args: str, posix: bool = ..., env: subprocess._ENV | None = None, **flags: object) -> None: ... + def run(self) -> Self: ... + def __int__(self) -> int: ... # technically, it can return `None` before `run` is called + def __eq__(self, other: object) -> bool: ... + +class CronTab: + lines: list[str | CronItem] | None + crons: list[CronItem] | None + filen: str | None + cron_command: str + env: OrderedVariableList[str, str] | None + root: bool + intab: str | None + tabfile: str | None + def __init__( + self, user: _User = None, tab: str | None = None, tabfile: str | None = None, log: CronLog | str | None = None + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + @property + def log(self) -> CronLog: ... + @property + def user(self) -> _User: ... + @property + def user_opt(self) -> dict[str, str]: ... + def read(self, filename: str | None = None) -> None: ... + def append( + self, + item: CronItem, + line: str = "", + read: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, + ) -> None: ... + def write(self, filename: str | None = None, user: _User = None, errors: bool = False) -> None: ... + def write_to_user(self, user: bool | str = True) -> None: ... + # Usually `kwargs` are just `now: datetime | None`, but technically this can + # work for `CronItem` subclasses, which might define other kwargs. + def run_pending(self, *, now: datetime | None = None, **kwargs: Any) -> Iterator[str]: ... + def run_scheduler(self, timeout: int = -1, cadence: int = 60, warp: bool = False) -> Iterator[str]: ... + def render(self, errors: bool = False) -> str: ... + def new( + self, + command: str = "", + comment: str = "", + user: str | None = None, + pre_comment: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, + ) -> CronItem: ... + def find_command(self, command: str | re.Pattern[str]) -> Iterator[CronItem]: ... + def find_comment(self, comment: str | re.Pattern[str]) -> Iterator[CronItem]: ... + def find_time(self, *args: Any) -> Iterator[CronItem]: ... + @property + def commands(self) -> Iterator[str]: ... + @property + def comments(self) -> Iterator[str]: ... + # You cannot actually pass `*args`, it will raise an exception, + # also known kwargs are added: + def remove_all( + self, *, command: str | re.Pattern[str] = ..., comment: str | re.Pattern[str] = ..., time: Any = ..., **kwargs: object + ) -> int: ... + def remove(self, *items: CronItem | Iterable[CronItem]) -> int: ... + def __iter__(self) -> Iterator[CronItem]: ... + def __getitem__(self, i: SupportsIndex) -> CronItem: ... + def __len__(self) -> int: ... + +class CronItem: + cron: CronTab | None + user: _User + valid: bool + enabled: bool + special: bool + comment: str + command: str | None + last_run: datetime | None + env: OrderedVariableList[str, str] + pre_comment: bool + marker: str | None + stdin: str | None + slices: CronSlices + def __init__(self, command: str = "", comment: str = "", user: _User = None, pre_comment: bool = False) -> None: ... + def __hash__(self) -> int: ... + def __eq__(self, other: object) -> bool: ... + @classmethod + def from_line(cls, line: str, user: str | None = None, cron: CronTab | None = None) -> Self: ... + def delete(self) -> None: ... + def set_command(self, cmd: str, parse_stdin: bool = False) -> None: ... + def set_comment(self, cmt: str, pre_comment: bool = False) -> None: ... + def parse(self, line: str) -> None: ... + def enable(self, enabled: bool = True) -> bool: ... + def is_enabled(self) -> bool: ... + def is_valid(self) -> bool: ... + def render(self) -> str: ... + def every_reboot(self) -> None: ... + def every(self, unit: int = 1) -> Every: ... + def setall(self, *args: Any) -> None: ... + def clear(self) -> None: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... + def frequency_per_day(self) -> int: ... + def frequency_per_hour(self) -> int: ... + def frequency_at_year(self, year: int | None = None) -> int: ... + + @overload + def frequency_at_month(self, year: int, month: int) -> int: ... + @overload + def frequency_at_month(self, year: None = None, month: None = None) -> int: ... + + @overload + def frequency_at_day(self, year: int, month: int, day: int) -> int: ... + @overload + def frequency_at_day(self, year: None = None, month: None = None, day: None = None) -> int: ... + + @overload + def frequency_at_hour(self, year: int, month: int, day: int, hour: int) -> int: ... + @overload + def frequency_at_hour(self, year: None = None, month: None = None, day: None = None, hour: None = None) -> int: ... + + def run_pending(self, now: datetime | None = None) -> int | str: ... + def run(self) -> str: ... + def schedule(self, date_from: datetime | None = None) -> croniter: ... + def description( + self, + *, + options: _Options | None = None, + casing_type: Literal[1, 2, 3] = 2, + verbose: bool = False, + day_of_week_start_index_zero: bool = True, + use_24hour_time_format: bool = ..., + locale_location: StrPath | None = None, + locale_code: str | None = ..., + ) -> str | None: ... + @property + def log(self) -> CronLog: ... + @property + def minute(self) -> int | str: ... + @property + def minutes(self) -> int | str: ... + @property + def hour(self) -> int | str: ... + @property + def hours(self) -> int | str: ... + @property + def day(self) -> int | str: ... + @property + def dom(self) -> int | str: ... + @property + def month(self) -> int | str: ... + @property + def months(self) -> int | str: ... + @property + def dow(self) -> int | str: ... + def __len__(self) -> int: ... + def __getitem__(self, key: int | str) -> int | str: ... + def __lt__(self, value: object) -> bool: ... + def __gt__(self, value: object) -> bool: ... + +class Every: + slices: CronSlices + unit: int + # TODO: add generated attributes + def __init__(self, item: CronSlices, units: int) -> None: ... + def set_attr(self, target: int) -> Callable[[], None]: ... + def year(self) -> None: ... + +class CronSlices(list[CronSlice]): + special: bool | None + def __init__(self, *args: Any) -> None: ... + def is_self_valid(self, *args: Any) -> bool: ... + @classmethod + def is_valid(cls, *args: Any) -> bool: ... + def setall(self, *slices: str) -> None: ... + def clean_render(self) -> str: ... + def render(self) -> str: ... + def clear(self) -> None: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... + def frequency_per_day(self) -> int: ... + def frequency_per_hour(self) -> int: ... + def frequency_at_year(self, year: int | None = None) -> int: ... + + @overload + def frequency_at_month(self, year: int, month: int) -> int: ... + @overload + def frequency_at_month(self, year: None = None, month: None = None) -> int: ... + + @overload + def frequency_at_day(self, year: int, month: int, day: int) -> int: ... + @overload + def frequency_at_day(self, year: None = None, month: None = None, day: None = None) -> int: ... + + @overload + def frequency_at_hour(self, year: int, month: int, day: int, hour: int) -> int: ... + @overload + def frequency_at_hour(self, year: None = None, month: None = None, day: None = None, hour: None = None) -> int: ... + + def __eq__(self, arg: object) -> bool: ... + +class SundayError(KeyError): ... + +class Also: + obj: CronSlice + def __init__(self, obj: CronSlice) -> None: ... + # These method actually use `*args`, but pass them to `CronSlice` methods, + # this is why they are typed as `Any`. + def every(self, *a: Any) -> _Part: ... + def on(self, *a: Any) -> list[_Part]: ... + def during(self, *a: Any) -> _Part: ... + +_Part: TypeAlias = int | CronValue | CronRange + +class CronSlice: + min: int | None + max: int | None + name: str | None + enum: list[str | None] | None + parts: list[_Part] + def __init__(self, info: int | dict[str, Any], value: str | None = None) -> None: ... + def __hash__(self) -> int: ... + def parse(self, value: str | None) -> None: ... + def render(self, resolve: bool = False) -> str: ... + def __eq__(self, arg: object) -> bool: ... + def every(self, n_value: int, also: bool = False) -> _Part: ... + # The only known kwarg, others are unused, + # `*args`` are passed to `parse_value`, so they are `Any` + def on(self, *n_value: Any, also: bool = False) -> list[_Part]: ... + def during(self, vfrom: int | str, vto: int | str, also: bool = False) -> _Part: ... + @property + def also(self) -> Also: ... + def clear(self) -> None: ... + def get_range(self, *vrange: int | str | CronValue) -> list[int | CronRange]: ... + def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... + def parse_value(self, val: str, sunday: int | None = None) -> int | CronValue: ... + def test_value(self, value: str, sunday: int | None = None) -> str: ... + +def get_cronvalue(value: int, enums: list[str]) -> int | CronValue: ... + +class CronValue: + text: str + value: int + def __init__(self, value: str, enums: list[str]) -> None: ... + def __lt__(self, value: object) -> bool: ... + def __int__(self) -> int: ... + +class CronRange: + dangling: int | None + slice: str + cron: CronTab | None + seq: int + def __init__(self, vslice: str, *vrange: int | str | CronValue) -> None: ... + # Are not set in `__init__`: + vfrom: int | CronValue + vto: int | CronValue + def parse(self, value: str) -> None: ... + def all(self) -> None: ... + def render(self, resolve: bool = False) -> str: ... + def range(self) -> _range: ... + def every(self, value: int | str) -> None: ... + def __lt__(self, value: object) -> bool: ... + def __gt__(self, value: object) -> bool: ... + def __int__(self) -> int: ... + +class OrderedVariableList(OrderedDict[_K, _V]): + job: CronItem | None + # You cannot actually pass `*args`, it will raise an exception, + # also known kwargs are added: + def __init__(self, *, job: CronItem | None = None, **kw: _V) -> None: ... + @property + def previous(self) -> Self | None: ... + def all(self) -> Self: ... + def __getitem__(self, key: _K) -> _V: ... diff --git a/stubs/python-crontab/crontabs.pyi b/stubs/python-crontab/crontabs.pyi new file mode 100644 index 000000000000..fcdfb77d8e42 --- /dev/null +++ b/stubs/python-crontab/crontabs.pyi @@ -0,0 +1,24 @@ +from typing import Any + +from crontab import CronTab + +class UserSpool(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + def listdir(self, loc: str) -> list[str]: ... + def get_owner(self, path: str) -> str: ... + def generate(self, loc: str, username: str) -> CronTab: ... + +class SystemTab(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + +class AnaCronTab(list[CronTab]): + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... + def add(self, loc: str, item: str, anajob: CronTab) -> CronTab: ... + +KNOWN_LOCATIONS: list[tuple[UserSpool | SystemTab | AnaCronTab, str]] + +class CronTabs(list[UserSpool | SystemTab | AnaCronTab]): + def __init__(self) -> None: ... + def add(self, cls: type[UserSpool | SystemTab | AnaCronTab], *args: Any) -> None: ... + @property + def all(self) -> CronTab: ... diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist.txt b/stubs/python-dateutil/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..8484bd3fe67d --- /dev/null +++ b/stubs/python-dateutil/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +dateutil.rrule.weekday.__init__ +dateutil.tz.tz.tzoffset.instance +dateutil.tz.tz.tzstr.instance + +# Metaclass differs: +dateutil.tz.tz.tzoffset +dateutil.tz.tz.tzutc diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt b/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt new file mode 100644 index 000000000000..b667fc149971 --- /dev/null +++ b/stubs/python-dateutil/@tests/stubtest_allowlist_darwin.txt @@ -0,0 +1,3 @@ +# Cannot import these Windows packages at stubtest runtime: +dateutil.tzwin +dateutil.tz.win diff --git a/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt b/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt new file mode 100644 index 000000000000..b667fc149971 --- /dev/null +++ b/stubs/python-dateutil/@tests/stubtest_allowlist_linux.txt @@ -0,0 +1,3 @@ +# Cannot import these Windows packages at stubtest runtime: +dateutil.tzwin +dateutil.tz.win diff --git a/stubs/python-dateutil/@tests/test_cases/check_inheritance.py b/stubs/python-dateutil/@tests/test_cases/check_inheritance.py new file mode 100644 index 000000000000..3ab5a78cdda2 --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_inheritance.py @@ -0,0 +1,21 @@ +from datetime import date, datetime +from typing_extensions import assert_type + +from dateutil.relativedelta import relativedelta + + +class MyDateTime(datetime): + pass + + +d = MyDateTime.now() +x = d - relativedelta(days=1) +assert_type(x, MyDateTime) + +d3 = datetime.today() +x3 = d3 - relativedelta(days=1) +assert_type(x3, datetime) + +d2 = date.today() +x2 = d2 - relativedelta(days=1) +assert_type(x2, date) diff --git a/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py b/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py new file mode 100644 index 000000000000..8e83759df123 --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_relativedelta.py @@ -0,0 +1,9 @@ +from __future__ import annotations + +from dateutil import relativedelta + + +# An illustrative example for why we re-export dateutil._common.weekday from dateutil.relativedelta in the stub +class Calendar: + def __init__(self, week_start: relativedelta.weekday = relativedelta.MO) -> None: + self.week_start = week_start diff --git a/stubs/python-dateutil/@tests/test_cases/check_rrule.py b/stubs/python-dateutil/@tests/test_cases/check_rrule.py new file mode 100644 index 000000000000..db0810b38cdb --- /dev/null +++ b/stubs/python-dateutil/@tests/test_cases/check_rrule.py @@ -0,0 +1,13 @@ +from typing import Union +from typing_extensions import assert_type + +from dateutil.rrule import rrule, rruleset, rrulestr + +rs1 = rrulestr("", forceset=True) +assert_type(rs1, rruleset) + +rs2 = rrulestr("", compatible=True) +assert_type(rs2, rruleset) + +rs3 = rrulestr("") +assert_type(rs3, Union[rrule, rruleset]) diff --git a/stubs/python-dateutil/METADATA.toml b/stubs/python-dateutil/METADATA.toml new file mode 100644 index 000000000000..995b1aa6aa82 --- /dev/null +++ b/stubs/python-dateutil/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.9.*" +upstream-repository = "https://github.com/dateutil/dateutil" diff --git a/stubs/python-dateutil/dateutil/__init__.pyi b/stubs/python-dateutil/dateutil/__init__.pyi new file mode 100644 index 000000000000..9fb5d4b1fe59 --- /dev/null +++ b/stubs/python-dateutil/dateutil/__init__.pyi @@ -0,0 +1,5 @@ +from dateutil import easter, parser, relativedelta, rrule, tz, utils, zoneinfo + +__all__ = ["easter", "parser", "relativedelta", "rrule", "tz", "utils", "zoneinfo"] + +def __dir__() -> list[str]: ... diff --git a/stubs/python-dateutil/dateutil/_common.pyi b/stubs/python-dateutil/dateutil/_common.pyi new file mode 100644 index 000000000000..af892a5d7a0d --- /dev/null +++ b/stubs/python-dateutil/dateutil/_common.pyi @@ -0,0 +1,10 @@ +from typing_extensions import Self + +class weekday: + __slots__ = ["weekday", "n"] + def __init__(self, weekday: int, n: int | None = None) -> None: ... + def __call__(self, n: int) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + weekday: int + n: int diff --git a/stubs/python-dateutil/dateutil/_version.pyi b/stubs/python-dateutil/dateutil/_version.pyi new file mode 100644 index 000000000000..840633ef6e91 --- /dev/null +++ b/stubs/python-dateutil/dateutil/_version.pyi @@ -0,0 +1,6 @@ +from typing import Final + +__version__: Final[str] +version: Final[str] +__version_tuple__: Final[tuple[int, int, int]] +version_tuple: Final[tuple[int, int, int]] diff --git a/stubs/python-dateutil/dateutil/easter.pyi b/stubs/python-dateutil/dateutil/easter.pyi new file mode 100644 index 000000000000..695faa222541 --- /dev/null +++ b/stubs/python-dateutil/dateutil/easter.pyi @@ -0,0 +1,10 @@ +from datetime import date +from typing import Final, Literal + +__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] + +EASTER_JULIAN: Final = 1 +EASTER_ORTHODOX: Final = 2 +EASTER_WESTERN: Final = 3 + +def easter(year: int, method: Literal[1, 2, 3] = 3) -> date: ... diff --git a/stubs/python-dateutil/dateutil/parser/__init__.pyi b/stubs/python-dateutil/dateutil/parser/__init__.pyi new file mode 100644 index 000000000000..1041c050d7a7 --- /dev/null +++ b/stubs/python-dateutil/dateutil/parser/__init__.pyi @@ -0,0 +1,12 @@ +from ._parser import ( + DEFAULTPARSER as DEFAULTPARSER, + DEFAULTTZPARSER as DEFAULTTZPARSER, + ParserError as ParserError, + UnknownTimezoneWarning as UnknownTimezoneWarning, + parse as parse, + parser as parser, + parserinfo as parserinfo, +) +from .isoparser import isoparse as isoparse, isoparser as isoparser + +__all__ = ["parse", "parser", "parserinfo", "isoparse", "isoparser", "ParserError", "UnknownTimezoneWarning"] diff --git a/stubs/python-dateutil/dateutil/parser/_parser.pyi b/stubs/python-dateutil/dateutil/parser/_parser.pyi new file mode 100644 index 000000000000..700b9fad63c1 --- /dev/null +++ b/stubs/python-dateutil/dateutil/parser/_parser.pyi @@ -0,0 +1,164 @@ +import re +from _typeshed import SupportsRead +from collections.abc import Callable, Mapping +from datetime import _TzInfo, datetime +from io import StringIO +from typing import IO, Any, Literal, TypeAlias, overload +from typing_extensions import Self + +_FileOrStr: TypeAlias = bytes | str | IO[str] | IO[Any] +_TzData: TypeAlias = _TzInfo | int | str | None +_TzInfos: TypeAlias = Mapping[str, _TzData] | Callable[[str, int], _TzData] + +__all__ = ["parse", "parserinfo", "ParserError"] + +class _timelex: + _split_decimal: re.Pattern[str] + instream: StringIO | SupportsRead[str] + charstack: list[str] + tokenstack: list[str] + eof: bool + def __init__(self, instream: str | bytes | bytearray | SupportsRead[str]) -> None: ... + def get_token(self) -> str | None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> str: ... + def next(self) -> str: ... + @classmethod + def split(cls, s: str) -> list[str]: ... + @classmethod + def isword(cls, nextchar: str) -> bool: ... + @classmethod + def isnum(cls, nextchar: str) -> bool: ... + @classmethod + def isspace(cls, nextchar: str) -> bool: ... + +class _resultbase: + def __init__(self) -> None: ... + def _repr(self, classname: str) -> str: ... + def __len__(self) -> int: ... + +class parserinfo: + JUMP: list[str] + WEEKDAYS: list[tuple[str, str]] + MONTHS: list[tuple[str, str] | tuple[str, str, str]] + HMS: list[tuple[str, str, str]] + AMPM: list[tuple[str, str]] + UTCZONE: list[str] + PERTAIN: list[str] + TZOFFSET: dict[str, int] + def __init__(self, dayfirst: bool = False, yearfirst: bool = False) -> None: ... + def jump(self, name: str) -> bool: ... + def weekday(self, name: str) -> int | None: ... + def month(self, name: str) -> int | None: ... + def hms(self, name: str) -> int | None: ... + def ampm(self, name: str) -> int | None: ... + def pertain(self, name: str) -> bool: ... + def utczone(self, name: str) -> bool: ... + def tzoffset(self, name: str) -> int | None: ... + def convertyear(self, year: int, century_specified: bool = False) -> int: ... + def validate(self, res: datetime) -> bool: ... + +class _ymd(list[int]): + century_specified: bool + dstridx: int | None + mstridx: int | None + ystridx: int | None + @property + def has_year(self) -> bool: ... + @property + def has_month(self) -> bool: ... + @property + def has_day(self) -> bool: ... + def could_be_day(self, value: int) -> bool: ... + def append(self, val: str | int, label: str | None = None) -> None: ... + def _resolve_from_stridxs(self, strids: dict[str, int]) -> tuple[int, int, int]: ... + def resolve_ymd(self, yearfirst: bool | None, dayfirst: bool | None) -> tuple[int, int, int]: ... + +class parser: + info: parserinfo + def __init__(self, info: parserinfo | None = None) -> None: ... + + @overload + def parse( + self, + timestr: _FileOrStr, + default: datetime | None = None, + ignoretz: bool = False, + tzinfos: _TzInfos | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[False] = False, + ) -> datetime: ... + @overload + def parse( + self, + timestr: _FileOrStr, + default: datetime | None = None, + ignoretz: bool = False, + tzinfos: _TzInfos | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[True], + ) -> tuple[datetime, tuple[str, ...]]: ... + +DEFAULTPARSER: parser + +@overload +def parse( + timestr: _FileOrStr, + parserinfo: parserinfo | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + ignoretz: bool = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[False] = False, + default: datetime | None = ..., + tzinfos: _TzInfos | None = ..., +) -> datetime: ... +@overload +def parse( + timestr: _FileOrStr, + parserinfo: parserinfo | None = None, + *, + dayfirst: bool | None = ..., + yearfirst: bool | None = ..., + ignoretz: bool = ..., + fuzzy: bool = ..., + fuzzy_with_tokens: Literal[True], + default: datetime | None = ..., + tzinfos: _TzInfos | None = ..., +) -> tuple[datetime, tuple[str, ...]]: ... + +class _tzparser: + class _result(_resultbase): + __slots__ = ["stdabbr", "stdoffset", "dstabbr", "dstoffset", "start", "end"] + stdabbr: str | None + stdoffset: int | None + dstabbr: str | None + dstoffset: int | None + start: _attr # pyrefly: ignore [unknown-name] + end: _attr # pyrefly: ignore [unknown-name] + + class _attr(_resultbase): + __slots__ = ["month", "week", "weekday", "yday", "jyday", "day", "time"] + month: int | None + week: int | None + weekday: int | None + yday: int | None + jyday: int | None + day: int | None + time: int | None + + def __init__(self) -> None: ... + + def parse(self, tzstr: str | re.Pattern[str]) -> _result | None: ... + +DEFAULTTZPARSER: _tzparser + +class ParserError(ValueError): ... +class UnknownTimezoneWarning(RuntimeWarning): ... diff --git a/stubs/python-dateutil/dateutil/parser/isoparser.pyi b/stubs/python-dateutil/dateutil/parser/isoparser.pyi new file mode 100644 index 000000000000..bf589f592296 --- /dev/null +++ b/stubs/python-dateutil/dateutil/parser/isoparser.pyi @@ -0,0 +1,17 @@ +from _typeshed import SupportsRead +from datetime import date, datetime, time, tzinfo +from typing import TypeAlias + +_Readable: TypeAlias = SupportsRead[str | bytes] +_TakesAscii: TypeAlias = str | bytes | _Readable + +__all__ = ["isoparse", "isoparser"] + +class isoparser: + def __init__(self, sep: str | bytes | None = None) -> None: ... + def isoparse(self, dt_str: _TakesAscii) -> datetime: ... + def parse_isodate(self, datestr: _TakesAscii) -> date: ... + def parse_isotime(self, timestr: _TakesAscii) -> time: ... + def parse_tzstr(self, tzstr: _TakesAscii, zero_as_utc: bool = True) -> tzinfo: ... + +def isoparse(dt_str: _TakesAscii) -> datetime: ... diff --git a/stubs/python-dateutil/dateutil/relativedelta.pyi b/stubs/python-dateutil/dateutil/relativedelta.pyi new file mode 100644 index 000000000000..e8f2528a9ac6 --- /dev/null +++ b/stubs/python-dateutil/dateutil/relativedelta.pyi @@ -0,0 +1,97 @@ +from datetime import date, timedelta +from typing import SupportsFloat, TypeAlias, TypeVar, overload +from typing_extensions import Self + +# See #9817 for why we reexport this here +from ._common import weekday as weekday + +_DateT = TypeVar("_DateT", bound=date) +# Work around attribute and type having the same name. +_Weekday: TypeAlias = weekday + +MO: weekday +TU: weekday +WE: weekday +TH: weekday +FR: weekday +SA: weekday +SU: weekday + +__all__ = ["relativedelta", "MO", "TU", "WE", "TH", "FR", "SA", "SU"] + +class relativedelta: + years: int + months: int + days: int + leapdays: int + hours: int + minutes: int + seconds: int + microseconds: int + year: int | None + month: int | None + weekday: _Weekday | None + day: int | None + hour: int | None + minute: int | None + second: int | None + microsecond: int | None + def __init__( + self, + dt1: date | None = None, + dt2: date | None = None, + years: int = 0, + months: int = 0, + days: int = 0, + leapdays: int = 0, + weeks: int = 0, + hours: int = 0, + minutes: int = 0, + seconds: int = 0, + microseconds: int = 0, + year: int | None = None, + month: int | None = None, + day: int | None = None, + weekday: int | _Weekday | None = None, + yearday: int | None = None, + nlyearday: int | None = None, + hour: int | None = None, + minute: int | None = None, + second: int | None = None, + microsecond: int | None = None, + ) -> None: ... + + @property + def weeks(self) -> int: ... + @weeks.setter + def weeks(self, value: int) -> None: ... + + def normalized(self) -> Self: ... + + @overload + def __add__(self, other: timedelta | relativedelta) -> Self: ... + @overload + def __add__(self, other: _DateT) -> _DateT: ... + + @overload + def __radd__(self, other: timedelta | relativedelta) -> Self: ... + @overload + def __radd__(self, other: _DateT) -> _DateT: ... + + @overload + def __rsub__(self, other: timedelta | relativedelta) -> Self: ... + @overload + def __rsub__(self, other: _DateT) -> _DateT: ... + + def __sub__(self, other: relativedelta) -> Self: ... + def __neg__(self) -> Self: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __mul__(self, other: SupportsFloat) -> Self: ... + def __rmul__(self, other: SupportsFloat) -> Self: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __div__(self, other: SupportsFloat) -> Self: ... + def __truediv__(self, other: SupportsFloat) -> Self: ... + def __abs__(self) -> Self: ... + def __hash__(self) -> int: ... diff --git a/stubs/python-dateutil/dateutil/rrule.pyi b/stubs/python-dateutil/dateutil/rrule.pyi new file mode 100644 index 000000000000..64cf1ef8e1cb --- /dev/null +++ b/stubs/python-dateutil/dateutil/rrule.pyi @@ -0,0 +1,223 @@ +import datetime +from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self + +from dateutil.parser._parser import _TzInfos + +from ._common import weekday as weekdaybase + +__all__ = [ + "rrule", + "rruleset", + "rrulestr", + "YEARLY", + "MONTHLY", + "WEEKLY", + "DAILY", + "HOURLY", + "MINUTELY", + "SECONDLY", + "MO", + "TU", + "WE", + "TH", + "FR", + "SA", + "SU", +] + +M366MASK: Final[tuple[int, ...]] +MDAY366MASK: Final[tuple[int, ...]] +MDAY365MASK: Final[tuple[int, ...]] +NMDAY366MASK: Final[tuple[int, ...]] +NMDAY365MASK: Final[list[int]] +M366RANGE: Final[tuple[int, ...]] +M365RANGE: Final[tuple[int, ...]] +WDAYMASK: Final[list[int]] +M365MASK: Final[tuple[int, ...]] +FREQNAMES: Final[list[str]] +YEARLY: Final = 0 +MONTHLY: Final = 1 +WEEKLY: Final = 2 +DAILY: Final = 3 +HOURLY: Final = 4 +MINUTELY: Final = 5 +SECONDLY: Final = 6 + +class weekday(weekdaybase): ... + +weekdays: tuple[weekday, weekday, weekday, weekday, weekday, weekday, weekday] +MO: weekday +TU: weekday +WE: weekday +TH: weekday +FR: weekday +SA: weekday +SU: weekday + +class rrulebase: + def __init__(self, cache: bool | None = False) -> None: ... + def __iter__(self) -> Iterator[datetime.datetime]: ... + def __getitem__(self, item: int | slice) -> datetime.datetime: ... + def __contains__(self, item: datetime.datetime) -> bool: ... + def count(self) -> int | None: ... + def before(self, dt: datetime.datetime, inc: bool = False) -> datetime.datetime | None: ... + def after(self, dt: datetime.datetime, inc: bool = False) -> datetime.datetime | None: ... + def xafter(self, dt: datetime.datetime, count: int | None = None, inc: bool = False) -> Generator[datetime.datetime]: ... + def between( + self, after: datetime.datetime, before: datetime.datetime, inc: bool = False, count: int = 1 + ) -> list[datetime.datetime]: ... + +class rrule(rrulebase): + def __init__( + self, + freq: Literal[0, 1, 2, 3, 4, 5, 6], + dtstart: datetime.date | None = None, + interval: int = 1, + wkst: weekday | int | None = None, + count: int | None = None, + until: datetime.date | int | None = None, + bysetpos: int | Iterable[int] | None = None, + bymonth: int | Iterable[int] | None = None, + bymonthday: int | Iterable[int] | None = None, + byyearday: int | Iterable[int] | None = None, + byeaster: int | Iterable[int] | None = None, + byweekno: int | Iterable[int] | None = None, + byweekday: int | weekday | Iterable[int] | Iterable[weekday] | None = None, + byhour: int | Iterable[int] | None = None, + byminute: int | Iterable[int] | None = None, + bysecond: int | Iterable[int] | None = None, + cache: bool | None = False, + ) -> None: ... + def replace( + self, + *, + freq: Literal[0, 1, 2, 3, 4, 5, 6] = ..., + dtstart: datetime.date | None = ..., + interval: int = ..., + wkst: weekday | int | None = ..., + count: int | None = ..., + until: datetime.date | int | None = ..., + bysetpos: int | Iterable[int] | None = None, + bymonth: int | Iterable[int] | None = None, + bymonthday: int | Iterable[int] | None = None, + byyearday: int | Iterable[int] | None = None, + byeaster: int | Iterable[int] | None = None, + byweekno: int | Iterable[int] | None = None, + byweekday: int | weekday | Iterable[int] | Iterable[weekday] | None = None, + byhour: int | Iterable[int] | None = None, + byminute: int | Iterable[int] | None = None, + bysecond: int | Iterable[int] | None = None, + cache: bool | None = ..., + ) -> Self: ... + +_RRule: TypeAlias = rrule + +class _iterinfo: + __slots__ = [ + "rrule", + "lastyear", + "lastmonth", + "yearlen", + "nextyearlen", + "yearordinal", + "yearweekday", + "mmask", + "mrange", + "mdaymask", + "nmdaymask", + "wdaymask", + "wnomask", + "nwdaymask", + "eastermask", + ] + rrule: _RRule + def __init__(self, rrule: _RRule) -> None: ... + yearlen: int | None + nextyearlen: int | None + yearordinal: int | None + yearweekday: int | None + mmask: Sequence[int] | None + mdaymask: Sequence[int] | None + nmdaymask: Sequence[int] | None + wdaymask: Sequence[int] | None + mrange: Sequence[int] | None + wnomask: Sequence[int] | None + nwdaymask: Sequence[int] | None + eastermask: Sequence[int] | None + lastyear: int | None + lastmonth: int | None + def rebuild(self, year: int, month: int) -> None: ... + def ydayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def mdayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def wdayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def ddayset(self, year: int, month: int, day: int) -> tuple[Iterable[int | None], int, int]: ... + def htimeset(self, hour: int, minute: int, second: int) -> list[datetime.time]: ... + def mtimeset(self, hour: int, minute: int, second: int) -> list[datetime.time]: ... + def stimeset(self, hour: int, minute: int, second: int) -> tuple[datetime.time, ...]: ... + +class rruleset(rrulebase): + class _genitem: + dt: datetime.datetime + genlist: list[Self] + gen: Iterator[datetime.datetime] + def __init__(self, genlist: list[Self], gen: Iterator[datetime.datetime]) -> None: ... + def __next__(self) -> None: ... + next = __next__ + def __lt__(self, other: Self) -> bool: ... + def __gt__(self, other: Self) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + + def __init__(self, cache: bool | None = False) -> None: ... + def rrule(self, rrule: _RRule) -> None: ... + def rdate(self, rdate: datetime.datetime) -> None: ... + def exrule(self, exrule: _RRule) -> None: ... + def exdate(self, exdate: datetime.datetime) -> None: ... + +class _rrulestr: + @overload + def __call__( + self, + s: str, + *, + forceset: Literal[True], + dtstart: datetime.date | None = None, + cache: bool | None = None, + unfold: bool = False, + compatible: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rruleset: ... + @overload + def __call__( + self, + s: str, + *, + compatible: Literal[True], + dtstart: datetime.date | None = None, + cache: bool | None = None, + unfold: bool = False, + forceset: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rruleset: ... + @overload + def __call__( + self, + s: str, + *, + dtstart: datetime.date | None = None, + cache: bool | None = False, + unfold: bool = False, + forceset: bool = False, + compatible: bool = False, + ignoretz: bool = False, + tzids: Callable[[str], datetime.tzinfo] | Mapping[str, datetime.tzinfo] | None = None, + tzinfos: _TzInfos | None = None, + ) -> rrule | rruleset: ... + +rrulestr: _rrulestr diff --git a/stubs/python-dateutil/dateutil/tz/__init__.pyi b/stubs/python-dateutil/dateutil/tz/__init__.pyi new file mode 100644 index 000000000000..406980bdfdab --- /dev/null +++ b/stubs/python-dateutil/dateutil/tz/__init__.pyi @@ -0,0 +1,68 @@ +import builtins +import sys +from datetime import datetime +from typing_extensions import Self + +from ._common import tzrangebase +from .tz import ( + datetime_ambiguous as datetime_ambiguous, + datetime_exists as datetime_exists, + enfold as enfold, + gettz as gettz, + resolve_imaginary as resolve_imaginary, + tzfile as tzfile, + tzical as tzical, + tzlocal as tzlocal, + tzoffset as tzoffset, + tzrange as tzrange, + tzstr as tzstr, + tzutc as tzutc, +) + +# UTC, tzwin, tzwinlocal are defined in this class +# otherwise pyright complains about unknown import symbol: +if sys.platform == "win32": + class tzwinbase(tzrangebase): + hasdst: bool + def __eq__(self, other: tzwinbase) -> bool: ... # type: ignore[override] + @staticmethod + def list() -> builtins.list[str]: ... + def display(self) -> str | None: ... + def transitions(self, year: int) -> tuple[datetime, datetime] | None: ... + + class tzwin(tzwinbase): + hasdst: bool + def __init__(self, name: str) -> None: ... + def __reduce__(self) -> tuple[type[Self], tuple[str, ...]]: ... # type: ignore[override] + + class tzwinlocal(tzwinbase): + hasdst: bool + def __init__(self) -> None: ... + def __reduce__(self) -> tuple[type[Self], tuple[str, ...]]: ... # type: ignore[override] + +else: + tzwin: None + tzwinlocal: None + +UTC: tzutc + +__all__ = [ + "tzutc", + "tzoffset", + "tzlocal", + "tzfile", + "tzrange", + "tzstr", + "tzical", + "tzwin", + "tzwinlocal", + "gettz", + "enfold", + "datetime_ambiguous", + "datetime_exists", + "resolve_imaginary", + "UTC", + "DeprecatedTzFormatWarning", +] + +class DeprecatedTzFormatWarning(Warning): ... diff --git a/stubs/python-dateutil/dateutil/tz/_common.pyi b/stubs/python-dateutil/dateutil/tz/_common.pyi new file mode 100644 index 000000000000..b160d0bc7398 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tz/_common.pyi @@ -0,0 +1,33 @@ +import abc +from collections.abc import Callable +from datetime import datetime, timedelta, tzinfo +from typing import ClassVar, ParamSpec, TypeVar + +ZERO: timedelta + +__all__ = ["tzname_in_python2", "enfold"] + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +def tzname_in_python2(namefunc: Callable[_P, _R]) -> Callable[_P, _R]: ... +def enfold(dt: _DateTimeT, fold: int = 1) -> _DateTimeT: ... + +# Doesn't actually have ABCMeta as the metaclass at runtime, +# but mypy complains if we don't have it in the stub. +# See discussion in #8908 +class _tzinfo(tzinfo, metaclass=abc.ABCMeta): + def is_ambiguous(self, dt: datetime) -> bool: ... + def fromutc(self, dt: datetime) -> datetime: ... + +class tzrangebase(_tzinfo): + def __init__(self) -> None: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def fromutc(self, dt: datetime) -> datetime: ... + def is_ambiguous(self, dt: datetime) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ diff --git a/stubs/python-dateutil/dateutil/tz/tz.pyi b/stubs/python-dateutil/dateutil/tz/tz.pyi new file mode 100644 index 000000000000..fe2eaf50ee22 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tz/tz.pyi @@ -0,0 +1,139 @@ +import sys +from _typeshed import Unused +from datetime import datetime, timedelta, tzinfo +from typing import Any, ClassVar, Literal, Protocol, TypeVar, type_check_only +from typing_extensions import Self + +from ..relativedelta import relativedelta +from ._common import _tzinfo, enfold as enfold, tzrangebase + +if sys.platform == "win32": + from .win import tzwin as tzwin, tzwinlocal as tzwinlocal +else: + tzwin: None + tzwinlocal: None + +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +ZERO: timedelta +EPOCH: datetime +EPOCHORDINAL: int + +class tzutc(tzinfo): + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def fromutc(self, dt: _DateTimeT) -> _DateTimeT: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ + +UTC: tzutc + +class tzoffset(tzinfo): + def __init__(self, name: str | None, offset: float | timedelta) -> None: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def tzname(self, dt: datetime | None) -> str: ... + def fromutc(self, dt: _DateTimeT) -> _DateTimeT: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ + @classmethod + def instance(cls, name: str | None, offset: float | timedelta) -> tzoffset: ... + +class tzlocal(_tzinfo): + def __init__(self) -> None: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def is_ambiguous(self, dt: datetime | None) -> bool: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + __reduce__ = object.__reduce__ + +class _ttinfo: + __slots__ = ["offset", "delta", "isdst", "abbr", "isstd", "isgmt", "dstoffset"] + offset: float + delta: timedelta + isdst: bool + abbr: str + isstd: bool + isgmt: bool + dstoffset: timedelta + def __init__(self) -> None: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + +@type_check_only +class _TZFileReader(Protocol): + # optional attribute: + # name: str + def read(self, size: int, /) -> bytes: ... + def seek(self, target: int, whence: Literal[1], /) -> object: ... + +class tzfile(_tzinfo): + def __init__(self, fileobj: str | _TZFileReader, filename: str | None = None) -> None: ... + def is_ambiguous(self, dt: datetime | None, idx: int | None = None) -> bool: ... + def utcoffset(self, dt: datetime | None) -> timedelta | None: ... + def dst(self, dt: datetime | None) -> timedelta | None: ... + def tzname(self, dt: datetime | None) -> str: ... + def __eq__(self, other: object) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] + def __ne__(self, other: object) -> bool: ... + def __reduce__(self) -> tuple[type[Self], tuple[None, str], dict[str, Any]]: ... + def __reduce_ex__(self, protocol: Unused) -> tuple[type[Self], tuple[None, str], dict[str, Any]]: ... + +class tzrange(tzrangebase): + hasdst: bool + def __init__( + self, + stdabbr: str, + stdoffset: int | timedelta | None = None, + dstabbr: str | None = None, + dstoffset: int | timedelta | None = None, + start: relativedelta | None = None, + end: relativedelta | None = None, + ) -> None: ... + def transitions(self, year: int) -> tuple[datetime, datetime]: ... + def __eq__(self, other: object) -> bool: ... + +class tzstr(tzrange): + hasdst: bool + def __init__(self, s: str, posix_offset: bool = False) -> None: ... + @classmethod + def instance(cls, name: str | None, offset: float | timedelta) -> tzoffset: ... + +@type_check_only +class _ICalReader(Protocol): + # optional attribute: + # name: str + def read(self) -> str: ... + +class tzical: + def __init__(self, fileobj: str | _ICalReader) -> None: ... + def keys(self) -> list[str]: ... + def get(self, tzid: str | None = None) -> tzinfo | None: ... + +TZFILES: list[str] +TZPATHS: list[str] + +def datetime_exists(dt: datetime, tz: tzinfo | None = None) -> bool: ... +def datetime_ambiguous(dt: datetime, tz: tzinfo | None = None) -> bool: ... +def resolve_imaginary(dt: _DateTimeT) -> _DateTimeT: ... + +# Singleton type defined locally in a function. Calls itself "GettzFunc". +@type_check_only +class _GetTZ: + def __call__(self, name: str | None = None) -> tzinfo | None: ... + def set_cache_size(self, size: int) -> None: ... + def cache_clear(self) -> None: ... + def nocache(self, name: str | None) -> tzinfo | None: ... + +gettz: _GetTZ diff --git a/stubs/python-dateutil/dateutil/tz/win.pyi b/stubs/python-dateutil/dateutil/tz/win.pyi new file mode 100644 index 000000000000..8d02d23acb01 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tz/win.pyi @@ -0,0 +1,27 @@ +import sys +from ctypes import _NameTypes, _Pointer, c_wchar +from datetime import datetime, timedelta +from typing import Any, ClassVar, Final + +from dateutil.tz import tzwin as tzwin, tzwinlocal as tzwinlocal + +if sys.platform == "win32": + from winreg import _KeyType + + __all__ = ["tzwin", "tzwinlocal", "tzres"] + + ONEWEEK: timedelta + TZKEYNAMENT: Final[str] + TZKEYNAME9X: Final[str] + TZLOCALKEYNAME: Final[str] + TZKEYNAME: Final[str] + + class tzres: + p_wchar: ClassVar[type[_Pointer[c_wchar]]] + tzres_loc: _NameTypes + def __init__(self, tzres_loc: _NameTypes = "tzres.dll") -> None: ... + def load_name(self, offset: int) -> str: ... + def name_from_string(self, tzname_str: str) -> str: ... + + def picknthweekday(year: int, month: int, dayofweek: int, hour: int, minute: int, whichweek: int) -> datetime: ... + def valuestodict(key: _KeyType) -> dict[str, Any]: ... # keys and values in dict are results of winreg.EnumValue() function diff --git a/stubs/python-dateutil/dateutil/tzwin.pyi b/stubs/python-dateutil/dateutil/tzwin.pyi new file mode 100644 index 000000000000..f021d35938e6 --- /dev/null +++ b/stubs/python-dateutil/dateutil/tzwin.pyi @@ -0,0 +1,4 @@ +import sys + +if sys.platform == "win32": + from .tz.win import tzres as tzres, tzwin as tzwin, tzwinlocal as tzwinlocal diff --git a/stubs/python-dateutil/dateutil/utils.pyi b/stubs/python-dateutil/dateutil/utils.pyi new file mode 100644 index 000000000000..ce4d8d38ccc0 --- /dev/null +++ b/stubs/python-dateutil/dateutil/utils.pyi @@ -0,0 +1,8 @@ +from datetime import _TzInfo, datetime, timedelta +from typing import TypeVar + +_DateTimeT = TypeVar("_DateTimeT", bound=datetime) + +def today(tzinfo: _TzInfo | None = None) -> datetime: ... +def default_tzinfo(dt: _DateTimeT, tzinfo: _TzInfo) -> _DateTimeT: ... +def within_delta(dt1: datetime, dt2: datetime, delta: timedelta) -> bool: ... diff --git a/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi b/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi new file mode 100644 index 000000000000..adee85032da2 --- /dev/null +++ b/stubs/python-dateutil/dateutil/zoneinfo/__init__.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from io import BytesIO +from tarfile import _Fileobj +from typing import Final, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated + +from dateutil.tz import tzfile as _tzfile + +_T = TypeVar("_T") +_MetadataType: TypeAlias = dict[str, Incomplete] + +__all__ = ["get_zonefile_instance", "gettz", "gettz_db_metadata"] + +ZONEFILENAME: Final[str] +METADATA_FN: Final[str] + +class tzfile(_tzfile): + # source code does this override, changing the type + def __reduce__(self) -> tuple[Callable[[str], Self], tuple[str]]: ... # type: ignore[override] + +def getzoneinfofile_stream() -> BytesIO | None: ... + +class ZoneInfoFile: + zones: dict[str, _tzfile] + metadata: _MetadataType | None + def __init__(self, zonefile_stream: _Fileobj | None = None) -> None: ... + + @overload + def get(self, name: str, default: None = None) -> _tzfile | None: ... + @overload + def get(self, name: str, default: _tzfile) -> _tzfile: ... + @overload + def get(self, name: str, default: _T) -> _tzfile | _T: ... + +def get_zonefile_instance(new_instance: bool = False) -> ZoneInfoFile: ... +@deprecated( + "zoneinfo.gettz() will be removed in future versions, to use the dateutil-provided " + "zoneinfo files, instantiate a ZoneInfoFile object and use ZoneInfoFile.zones.get() instead." +) +def gettz(name: str) -> _tzfile: ... +@deprecated( + "zoneinfo.gettz_db_metadata() will be removed in future versions, to use the " + "dateutil-provided zoneinfo files, ZoneInfoFile object and query the 'metadata' attribute instead." +) +def gettz_db_metadata() -> _MetadataType: ... diff --git a/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi b/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi new file mode 100644 index 000000000000..325950a2eea3 --- /dev/null +++ b/stubs/python-dateutil/dateutil/zoneinfo/rebuild.pyi @@ -0,0 +1,12 @@ +from _typeshed import StrOrBytesPath, Unused +from collections.abc import Iterable + +from ..zoneinfo import _MetadataType + +def rebuild( + filename: StrOrBytesPath, + tag: Unused | None = None, + format: str = "gz", + zonegroups: Iterable[str] = [], + metadata: _MetadataType | None = None, +) -> None: ... diff --git a/stubs/python-http-client/@tests/stubtest_allowlist.txt b/stubs/python-http-client/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..f1c4ead36ecf --- /dev/null +++ b/stubs/python-http-client/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +python_http_client.version_file diff --git a/stubs/python-http-client/METADATA.toml b/stubs/python-http-client/METADATA.toml new file mode 100644 index 000000000000..f93b0770d472 --- /dev/null +++ b/stubs/python-http-client/METADATA.toml @@ -0,0 +1,2 @@ +version = "3.3.7" +upstream-repository = "https://github.com/sendgrid/python-http-client" diff --git a/stubs/python-http-client/python_http_client/__init__.pyi b/stubs/python-http-client/python_http_client/__init__.pyi new file mode 100644 index 000000000000..1c17420c7594 --- /dev/null +++ b/stubs/python-http-client/python_http_client/__init__.pyi @@ -0,0 +1,20 @@ +from typing import Final + +from .client import Client as Client +from .exceptions import ( + BadRequestsError as BadRequestsError, + ForbiddenError as ForbiddenError, + GatewayTimeoutError as GatewayTimeoutError, + HTTPError as HTTPError, + InternalServerError as InternalServerError, + MethodNotAllowedError as MethodNotAllowedError, + NotFoundError as NotFoundError, + PayloadTooLargeError as PayloadTooLargeError, + ServiceUnavailableError as ServiceUnavailableError, + TooManyRequestsError as TooManyRequestsError, + UnauthorizedError as UnauthorizedError, + UnsupportedMediaTypeError as UnsupportedMediaTypeError, +) + +dir_path: Final[str] +__version__: Final[str] diff --git a/stubs/python-http-client/python_http_client/client.pyi b/stubs/python-http-client/python_http_client/client.pyi new file mode 100644 index 000000000000..aceb5f6cbaa8 --- /dev/null +++ b/stubs/python-http-client/python_http_client/client.pyi @@ -0,0 +1,32 @@ +from email.message import Message +from http.client import HTTPResponse +from typing import Any, Final + +class Response: + def __init__(self, response: HTTPResponse) -> None: ... + @property + def status_code(self) -> int: ... + @property + def body(self) -> bytes: ... + @property + def headers(self) -> Message: ... + @property + def to_dict(self) -> dict[str, Any] | None: ... # dict of response from API if body is not empty + +class Client: + methods: Final[set[str]] + host: str + request_headers: dict[str, str] + append_slash: bool + timeout: int + def __init__( + self, + host: str, + request_headers: dict[str, str] | None = None, + version: int | None = None, + url_path: list[str] | None = None, + append_slash: bool = False, + timeout: int | None = None, + ) -> None: ... + def _(self, name: str) -> Client: ... + def __getattr__(self, name: str) -> Client | Response: ... diff --git a/stubs/python-http-client/python_http_client/exceptions.pyi b/stubs/python-http-client/python_http_client/exceptions.pyi new file mode 100644 index 000000000000..6fc504b17b57 --- /dev/null +++ b/stubs/python-http-client/python_http_client/exceptions.pyi @@ -0,0 +1,34 @@ +from email.message import Message +from typing import Any, Final, overload +from urllib.error import HTTPError as _HTTPError + +class HTTPError(Exception): + status_code: int + reason: str + body: bytes + headers: Message + + @overload + def __init__(self, status_code: int, reason: str, body: bytes, headers: Message, /) -> None: ... + @overload + def __init__(self, http_error: _HTTPError, /) -> None: ... + + def __reduce__(self) -> tuple[type[HTTPError], tuple[int, str, bytes, Message]]: ... + @property + def to_dict(self) -> dict[str, Any]: ... # dict of response error from the API + +class BadRequestsError(HTTPError): ... +class UnauthorizedError(HTTPError): ... +class ForbiddenError(HTTPError): ... +class NotFoundError(HTTPError): ... +class MethodNotAllowedError(HTTPError): ... +class PayloadTooLargeError(HTTPError): ... +class UnsupportedMediaTypeError(HTTPError): ... +class TooManyRequestsError(HTTPError): ... +class InternalServerError(HTTPError): ... +class ServiceUnavailableError(HTTPError): ... +class GatewayTimeoutError(HTTPError): ... + +err_dict: Final[dict[int, type[HTTPError]]] + +def handle_error(error: _HTTPError) -> HTTPError: ... diff --git a/stubs/python-jenkins/@tests/stubtest_allowlist.txt b/stubs/python-jenkins/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..787864001fed --- /dev/null +++ b/stubs/python-jenkins/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# The default value for the timeout parameter is a token from urllib3 which is private and should not be used by end-users +jenkins.Jenkins.__init__ diff --git a/stubs/python-jenkins/METADATA.toml b/stubs/python-jenkins/METADATA.toml new file mode 100644 index 000000000000..2f60657ee621 --- /dev/null +++ b/stubs/python-jenkins/METADATA.toml @@ -0,0 +1,3 @@ +version = "~=1.8.3" +upstream-repository = "https://opendev.org/jjb/python-jenkins" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/python-jenkins/jenkins/__init__.pyi b/stubs/python-jenkins/jenkins/__init__.pyi new file mode 100644 index 000000000000..1f392073916e --- /dev/null +++ b/stubs/python-jenkins/jenkins/__init__.pyi @@ -0,0 +1,254 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, MutableMapping, Sequence +from re import Pattern +from typing import Any, Final, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Required, deprecated + +import requests +from requests._types import AuthType +from requests.models import Request, Response + +LAUNCHER_SSH: Final[str] +LAUNCHER_COMMAND: Final[str] +LAUNCHER_JNLP: Final[str] +LAUNCHER_WINDOWS_SERVICE: Final[str] +DEFAULT_HEADERS: Final[dict[str, str]] +DEFAULT_TIMEOUT: Final[float] +DEFAULT_RETRIES: Final = 0 +INFO: Final[str] +PLUGIN_INFO: Final[str] +CRUMB_URL: Final[str] +WHOAMI_URL: Final[str] +JOBS_QUERY: Final[str] +JOBS_QUERY_TREE: Final[str] +JOB_INFO: Final[str] +JOB_NAME: Final[str] +ALL_BUILDS: Final[str] +Q_INFO: Final[str] +Q_ITEM: Final[str] +CANCEL_QUEUE: Final[str] +CREATE_JOB: Final[str] +CONFIG_JOB: Final[str] +DELETE_JOB: Final[str] +ENABLE_JOB: Final[str] +DISABLE_JOB: Final[str] +CHECK_JENKINSFILE_SYNTAX: Final[str] +SET_JOB_BUILD_NUMBER: Final[str] +COPY_JOB: Final[str] +RENAME_JOB: Final[str] +BUILD_JOB: Final[str] +STOP_BUILD: Final[str] +BUILD_WITH_PARAMS_JOB: Final[str] +BUILD_INFO: Final[str] +BUILD_CONSOLE_OUTPUT: Final[str] +BUILD_ENV_VARS: Final[str] +BUILD_TEST_REPORT: Final[str] +BUILD_ARTIFACT: Final[str] +BUILD_STAGES: Final[str] +DELETE_BUILD: Final[str] +WIPEOUT_JOB_WORKSPACE: Final[str] +NODE_LIST: Final[str] +CREATE_NODE: Final[str] +DELETE_NODE: Final[str] +NODE_INFO: Final[str] +NODE_TYPE: Final[str] +TOGGLE_OFFLINE: Final[str] +CONFIG_NODE: Final[str] +VIEW_NAME: Final[str] +VIEW_JOBS: Final[str] +CREATE_VIEW: Final[str] +CONFIG_VIEW: Final[str] +DELETE_VIEW: Final[str] +SCRIPT_TEXT: Final[str] +NODE_SCRIPT_TEXT: Final[str] +PROMOTION_NAME: Final[str] +PROMOTION_INFO: Final[str] +DELETE_PROMOTION: Final[str] +CREATE_PROMOTION: Final[str] +CONFIG_PROMOTION: Final[str] +LIST_CREDENTIALS: Final[str] +CREATE_CREDENTIAL: Final[str] +CONFIG_CREDENTIAL: Final[str] +CREDENTIAL_INFO: Final[str] +QUIET_DOWN: Final[str] +EMPTY_CONFIG_XML: Final[str] +EMPTY_FOLDER_XML: Final[str] +RECONFIG_XML: Final[str] +EMPTY_VIEW_CONFIG_XML: Final[str] +EMPTY_PROMO_CONFIG_XML: Final[str] +PROMO_RECONFIG_XML: Final[str] + +class JenkinsException(Exception): ... +class NotFoundException(JenkinsException): ... +class EmptyResponseException(JenkinsException): ... +class BadHTTPException(JenkinsException): ... +class TimeoutException(JenkinsException): ... + +class WrappedSession(requests.Session): + # merge_environment_settings wraps requests.Session.merge_environment_settings + # w/o changing the type signature + ... + +_JSONValue: TypeAlias = Any # too many possibilities to express +_JSON: TypeAlias = dict[str, _JSONValue] + +@type_check_only +class _Job(TypedDict, total=False): + _class: Required[str] + url: Required[str] + color: str + name: Required[str] + fullname: Required[str] + jobs: list[_Job] + +class Jenkins: + server: str + auth: AuthType | None + crumb: Mapping[str, Incomplete] | bool | Incomplete + timeout: int + def __init__( + self, url: str, username: str | None = None, password: str | None = None, timeout: int = ..., retries: int = 0 + ) -> None: ... + def maybe_add_crumb(self, req: Request) -> None: ... + def get_job_info(self, name: str, depth: int = 0, fetch_all_builds: bool = False) -> _JSON: ... + def get_job_info_regex( + self, pattern: str | Pattern[str], depth: int = 0, folder_depth: int = 0, folder_depth_per_request: int = 10 + ) -> list[_JSON]: ... + def get_job_name(self, name: str) -> str | None: ... + def debug_job_info(self, job_name: str) -> None: ... + def jenkins_open(self, req: Request, add_crumb: bool = True, resolve_auth: bool = True) -> str: ... + def jenkins_open_stream(self, req: Request, add_crumb: bool = True, resolve_auth: bool = True) -> Response: ... + def jenkins_request( + self, req: Request, add_crumb: bool = True, resolve_auth: bool = True, stream: bool | None = None + ) -> Response: ... + def get_queue_item(self, number: int, depth: int = 0) -> _JSON: ... + def get_build_info(self, name: str, number: int, depth: int = 0) -> _JSON: ... + def get_build_env_vars(self, name: str, number: int, depth: int = 0) -> _JSON | None: ... + def get_build_test_report(self, name: str, number: int, depth: int = 0, tree: str | None = None) -> _JSON | None: ... + def get_build_artifact(self, name: str, number: int, artifact: str) -> _JSON: ... + def get_build_artifact_as_bytes(self, name: str, number: int, artifact: str) -> bytes: ... + def get_build_stages(self, name: str, number: int) -> _JSON: ... + def get_queue_info(self) -> _JSON: ... + def cancel_queue(self, id: int) -> None: ... + def get_info(self, item: str = "", query: str | None = None) -> _JSON: ... + def get_whoami(self, depth: int = 0) -> _JSON: ... + def get_version(self) -> str: ... + @deprecated("Deprecated since 0.4.9. Use `get_plugins` instead.") + def get_plugins_info(self, depth: int = 2) -> _JSON: ... + def get_plugin_info(self, name: str, depth: int = 2) -> _JSON: ... + def get_plugins(self, depth: int = 2) -> _JSON: ... + def get_jobs(self, folder_depth: int = 0, folder_depth_per_request: int = 10, view_name: str | None = None) -> list[_Job]: ... + def get_all_jobs(self, folder_depth: int | None = None, folder_depth_per_request: int = 10) -> list[_Job]: ... + def copy_job(self, from_name: str, to_name: str) -> None: ... + def rename_job(self, from_name: str, to_name: str) -> None: ... + def delete_job(self, name: str) -> None: ... + def enable_job(self, name: str) -> None: ... + def disable_job(self, name: str) -> None: ... + def set_next_build_number(self, name: str, number: int) -> None: ... + def job_exists(self, name: str) -> bool: ... + def jobs_count(self) -> int: ... + def assert_job_exists(self, name: str, exception_message: str = "job[%s] does not exist") -> None: ... + def create_folder(self, folder_name: str, ignore_failures: bool = False) -> None: ... + def upsert_job(self, name: str, config_xml: str) -> None: ... + def check_jenkinsfile_syntax(self, jenkinsfile: str) -> list[str]: ... + def create_job(self, name: str, config_xml: str) -> None: ... + def get_job_config(self, name: str) -> str: ... + def reconfig_job(self, name: str, config_xml: str) -> None: ... + + @overload + def build_job_url( + self, + name: str, + parameters: Mapping[str, Incomplete] | Sequence[tuple[str, Incomplete]] | None = None, + token: Literal[""] | None = None, + ) -> str: ... + @overload + def build_job_url( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None, token: str + ) -> str: ... + @overload + def build_job_url( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None = None, *, token: str + ) -> str: ... + + @overload + def build_job( + self, + name: str, + parameters: Mapping[str, Incomplete] | Sequence[tuple[str, Incomplete]] | None = None, + token: Literal[""] | None = None, + ) -> int: ... + @overload + def build_job( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None, token: str + ) -> int: ... + @overload + def build_job( + self, name: str, parameters: dict[str, Incomplete] | list[tuple[str, Incomplete]] | None = None, *, token: str + ) -> int: ... + + def run_script(self, script: str, node: str | None = None) -> str: ... + def install_plugin(self, name: str, include_dependencies: bool = True) -> bool: ... + def stop_build(self, name: str, number: int) -> None: ... + def delete_build(self, name: str, number: int) -> None: ... + def wipeout_job_workspace(self, name: str) -> None: ... + def get_running_builds(self) -> list[_JSON]: ... + def get_nodes_with_info(self, depth: int = 0) -> list[_JSON]: ... + def get_nodes(self, depth: int = 0) -> list[_JSON]: ... + def get_node_info(self, name: str, depth: int = 0) -> _JSON: ... + def node_exists(self, name: str) -> bool: ... + def assert_node_exists(self, name: str, exception_message: str = "node[%s] does not exist") -> None: ... + def delete_node(self, name: str) -> None: ... + def disable_node(self, name: str, msg: str = "") -> None: ... + def enable_node(self, name: str) -> None: ... + def create_node( + self, + name: str, + numExecutors: int = 2, + nodeDescription: str | None = None, + remoteFS: str = "/var/lib/jenkins", + labels: str | None = None, + exclusive: bool = False, + launcher: str = "hudson.slaves.CommandLauncher", + launcher_params: MutableMapping[str, Incomplete] = {}, + ) -> None: ... + def get_node_config(self, name: str) -> str: ... + def reconfig_node(self, name: str, config_xml: str) -> None: ... + def get_build_console_output(self, name: str, number: int) -> str: ... + def get_view_name(self, name: str) -> str | None: ... + def assert_view_exists(self, name: str, exception_message: str = "view[%s] does not exist") -> None: ... + def view_exists(self, name: str) -> bool: ... + def get_views(self) -> list[_JSON]: ... + def delete_view(self, name: str) -> None: ... + def create_view(self, name: str, config_xml: str) -> None: ... + def reconfig_view(self, name: str, config_xml: str) -> None: ... + def get_view_config(self, name: str) -> str: ... + def get_promotion_name(self, name: str, job_name: str) -> str | None: ... + def assert_promotion_exists( + self, name: str, job_name: str, exception_message: str = "promotion[%s] does not exist for job[%s]" + ) -> None: ... + def promotion_exists(self, name: str, job_name: str) -> bool: ... + def get_promotions_info(self, job_name: str, depth: int = 0) -> _JSON: ... + def get_promotions(self, job_name: str) -> list[_JSON]: ... + def delete_promotion(self, name: str, job_name: str) -> None: ... + def create_promotion(self, name: str, job_name: str, config_xml: str) -> None: ... + def reconfig_promotion(self, name: str, job_name: str, config_xml: str) -> None: ... + def get_promotion_config(self, name: str, job_name: str) -> str: ... + def assert_folder(self, name: str, exception_message: str = "job[%s] is not a folder") -> None: ... + def is_folder(self, name: str) -> bool: ... + def assert_credential_exists( + self, + name: str, + folder_name: str, + domain_name: str = "_", + exception_message: str = "credential[%s] does not exist in the domain[%s] of [%s]", # noqa: Y053 + ) -> None: ... + def credential_exists(self, name: str, folder_name: str, domain_name: str = "_") -> bool: ... + def get_credential_info(self, name: str, folder_name: str, domain_name: str = "_") -> _JSON: ... + def get_credential_config(self, name: str, folder_name: str, domain_name: str = "_") -> str: ... + def create_credential(self, folder_name: str, config_xml: str, domain_name: str = "_") -> None: ... + def delete_credential(self, name: str, folder_name: str, domain_name: str = "_") -> None: ... + def reconfig_credential(self, folder_name: str, config_xml: str, domain_name: str = "_") -> None: ... + def list_credentials(self, folder_name: str, domain_name: str = "_") -> list[Incomplete]: ... + def quiet_down(self) -> None: ... + def wait_for_normal_op(self, timeout: int) -> bool: ... diff --git a/stubs/python-jenkins/jenkins/plugins.pyi b/stubs/python-jenkins/jenkins/plugins.pyi new file mode 100644 index 000000000000..aa3ce52a1da9 --- /dev/null +++ b/stubs/python-jenkins/jenkins/plugins.pyi @@ -0,0 +1,15 @@ +from typing import Any + +# Any: Union of possible plugin values is too complex +class Plugin(dict[str, Any]): + # __init__ wraps dict.__init__ w/o changing the type signature + def __setitem__(self, key: str, value: Any) -> None: ... + +class PluginVersion(str): + def __init__(self, version: str) -> None: ... + def __le__(self, version: object) -> bool: ... + def __lt__(self, version: object) -> bool: ... + def __ge__(self, version: object) -> bool: ... + def __gt__(self, version: object) -> bool: ... + def __eq__(self, version: object) -> bool: ... + def __ne__(self, version: object) -> bool: ... diff --git a/stubs/python-jenkins/jenkins/version.pyi b/stubs/python-jenkins/jenkins/version.pyi new file mode 100644 index 000000000000..7b63c09e3d72 --- /dev/null +++ b/stubs/python-jenkins/jenkins/version.pyi @@ -0,0 +1,3 @@ +from _typeshed import Incomplete + +version_info: Incomplete # pbr.version.VersionInfo diff --git a/stubs/python-jose/@tests/stubtest_allowlist.txt b/stubs/python-jose/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b0c651965b8a --- /dev/null +++ b/stubs/python-jose/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +jose.backends.cryptography_backend diff --git a/stubs/python-jose/METADATA.toml b/stubs/python-jose/METADATA.toml new file mode 100644 index 000000000000..5248bfa71dfb --- /dev/null +++ b/stubs/python-jose/METADATA.toml @@ -0,0 +1,3 @@ +version = "3.5.*" +upstream-repository = "https://github.com/mpdavis/python-jose" +dependencies = ["types-pyasn1"] # excluding pyrsa, cryptography until typing is available diff --git a/stubs/python-jose/jose/__init__.pyi b/stubs/python-jose/jose/__init__.pyi new file mode 100644 index 000000000000..dcd21e1f413b --- /dev/null +++ b/stubs/python-jose/jose/__init__.pyi @@ -0,0 +1,11 @@ +from .exceptions import ( + ExpiredSignatureError as ExpiredSignatureError, + JOSEError as JOSEError, + JWSError as JWSError, + JWTError as JWTError, +) + +__version__: str +__author__: str +__license__: str +__copyright__: str diff --git a/stubs/python-jose/jose/backends/__init__.pyi b/stubs/python-jose/jose/backends/__init__.pyi new file mode 100644 index 000000000000..9aae87f033e7 --- /dev/null +++ b/stubs/python-jose/jose/backends/__init__.pyi @@ -0,0 +1,18 @@ +from .base import DIRKey as DIRKey +from .cryptography_backend import ( + CryptographyAESKey as CryptographyAESKey, + CryptographyECKey as CryptographyECKey, + CryptographyHMACKey as CryptographyHMACKey, + CryptographyRSAKey as CryptographyRSAKey, +) +from .ecdsa_backend import ECDSAECKey as ECDSAECKey +from .native import HMACKey as NativeHMACKey, get_random_bytes as get_random_bytes +from .rsa_backend import RSAKey as BackendRSAKey + +# python-jose relies on importing from cryptography_backend +# then falling back on other imports +# these are all the potential options +AESKey: type[CryptographyAESKey] | None +HMACKey: type[CryptographyHMACKey | NativeHMACKey] +RSAKey: type[CryptographyRSAKey | BackendRSAKey] | None +ECKey: type[CryptographyECKey | ECDSAECKey] diff --git a/stubs/python-jose/jose/backends/_asn1.pyi b/stubs/python-jose/jose/backends/_asn1.pyi new file mode 100644 index 000000000000..b4fce464ced1 --- /dev/null +++ b/stubs/python-jose/jose/backends/_asn1.pyi @@ -0,0 +1,17 @@ +from pyasn1.type import namedtype, univ + +RSA_ENCRYPTION_ASN1_OID: str + +class RsaAlgorithmIdentifier(univ.Sequence): + componentType: namedtype.NamedTypes + +class PKCS8PrivateKey(univ.Sequence): + componentType: namedtype.NamedTypes + +class PublicKeyInfo(univ.Sequence): + componentType: namedtype.NamedTypes + +def rsa_private_key_pkcs8_to_pkcs1(pkcs8_key) -> bytes: ... +def rsa_private_key_pkcs1_to_pkcs8(pkcs1_key) -> bytes: ... +def rsa_public_key_pkcs1_to_pkcs8(pkcs1_key) -> bytes: ... +def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key) -> bytes: ... diff --git a/stubs/python-jose/jose/backends/base.pyi b/stubs/python-jose/jose/backends/base.pyi new file mode 100644 index 000000000000..f13da256d148 --- /dev/null +++ b/stubs/python-jose/jose/backends/base.pyi @@ -0,0 +1,23 @@ +from typing import Any +from typing_extensions import Self + +class Key: + # Enable when we can use stubs from installed dependencies, + # as `key` can be of type cryptography.x509.base.Certificate: + # from cryptography.x509 import Certificate + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg: bytes) -> bytes: ... + def verify(self, msg: bytes, sig: bytes) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self) -> bytes: ... + def to_dict(self) -> dict[str, Any]: ... + def encrypt(self, plain_text: str | bytes, aad: bytes | None = None) -> tuple[bytes, bytes, bytes | None]: ... + def decrypt( + self, cipher_text: str | bytes, iv: str | bytes | None = None, aad: bytes | None = None, tag: bytes | None = None + ) -> bytes: ... + def wrap_key(self, key_data: bytes) -> bytes: ... + def unwrap_key(self, wrapped_key: bytes) -> bytes: ... + +class DIRKey(Key): + def __init__(self, key_data: str | bytes, algorithm: str) -> None: ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/cryptography_backend.pyi b/stubs/python-jose/jose/backends/cryptography_backend.pyi new file mode 100644 index 000000000000..dce249e54bf3 --- /dev/null +++ b/stubs/python-jose/jose/backends/cryptography_backend.pyi @@ -0,0 +1,66 @@ +from typing import Any, ClassVar + +from . import get_random_bytes as get_random_bytes +from .base import Key + +# Enable when we can use stubs from installed dependencies: +# from cryptography.hazmat import backends +class CryptographyECKey(Key): + SHA256: Any + SHA384: Any + SHA512: Any + hash_alg: Any + cryptography_backend: Any + prepared_key: Any + def __init__(self, key, algorithm, cryptography_backend=...) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self): ... + def public_key(self): ... + def to_pem(self): ... + def to_dict(self): ... + +class CryptographyRSAKey(Key): + SHA256: Any + SHA384: Any + SHA512: Any + RSA1_5: Any + RSA_OAEP: Any + RSA_OAEP_256: Any + hash_alg: Any + padding: Any + cryptography_backend: Any + prepared_key: Any + def __init__(self, key, algorithm, cryptography_backend=...) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self): ... + def public_key(self): ... + def to_pem(self, pem_format: str = "PKCS8"): ... + def to_dict(self): ... + def wrap_key(self, key_data): ... + def unwrap_key(self, wrapped_key): ... + +class CryptographyAESKey(Key): + KEY_128: Any + KEY_192: Any + KEY_256: Any + KEY_384: Any + KEY_512: Any + AES_KW_ALGS: Any + MODES: Any + IV_BYTE_LENGTH_MODE_MAP: ClassVar[dict[str, int]] + def __init__(self, key, algorithm) -> None: ... + def to_dict(self): ... + def encrypt(self, plain_text, aad=None): ... + def decrypt(self, cipher_text, iv=None, aad=None, tag=None): ... + def wrap_key(self, key_data): ... + def unwrap_key(self, wrapped_key): ... + +class CryptographyHMACKey(Key): + ALG_MAP: Any + prepared_key: Any + def __init__(self, key, algorithm) -> None: ... + def to_dict(self): ... + def sign(self, msg): ... + def verify(self, msg, sig): ... diff --git a/stubs/python-jose/jose/backends/ecdsa_backend.pyi b/stubs/python-jose/jose/backends/ecdsa_backend.pyi new file mode 100644 index 000000000000..fea488c785ad --- /dev/null +++ b/stubs/python-jose/jose/backends/ecdsa_backend.pyi @@ -0,0 +1,25 @@ +from collections.abc import Callable +from hashlib import _Hash +from typing import Any +from typing_extensions import Self + +from .base import Key + +# Enable when we can use stubs from installed dependencies: +# from ecdsa.curves import Curve +class ECDSAECKey(Key): + SHA256: Callable[[bytes], _Hash] + SHA384: Callable[[bytes], _Hash] + SHA512: Callable[[bytes], _Hash] + CURVE_MAP: Any + CURVE_NAMES: Any + hash_alg: Any + curve: Any + prepared_key: Any + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg): ... + def verify(self, msg, sig): ... + def is_public(self) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self): ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/native.pyi b/stubs/python-jose/jose/backends/native.pyi new file mode 100644 index 000000000000..8c1626b59089 --- /dev/null +++ b/stubs/python-jose/jose/backends/native.pyi @@ -0,0 +1,21 @@ +from _typeshed import ReadableBuffer +from collections.abc import Callable +from hashlib import _Hash +from typing import Any + +from .base import Key + +def get_random_bytes(num_bytes: int) -> bytes: ... + +class HMACKey(Key): + HASHES: dict[str, Callable[[bytes], _Hash]] + prepared_key: bytes + def __init__( + self, + # explicitly checks for key_data as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any], + algorithm: str, + ) -> None: ... + def sign(self, msg: ReadableBuffer | None) -> bytes: ... + def verify(self, msg: ReadableBuffer | None, sig: str | bytes) -> bool: ... + def to_dict(self) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/backends/rsa_backend.pyi b/stubs/python-jose/jose/backends/rsa_backend.pyi new file mode 100644 index 000000000000..495b39a4fb0b --- /dev/null +++ b/stubs/python-jose/jose/backends/rsa_backend.pyi @@ -0,0 +1,27 @@ +from typing import Any +from typing_extensions import Self + +from .base import Key + +LEGACY_INVALID_PKCS8_RSA_HEADER: bytes +ASN1_SEQUENCE_ID: bytes +RSA_ENCRYPTION_ASN1_OID: str + +# Enable when we can use stubs from installed dependencies: +# from rsa import PublicKey +def pem_to_spki(pem, fmt: str = "PKCS8"): ... + +class RSAKey(Key): + SHA256: str + SHA384: str + SHA512: str + hash_alg: str + def __init__(self, key, algorithm) -> None: ... + def sign(self, msg: bytes) -> bytes: ... + def verify(self, msg: bytes, sig: bytes) -> bool: ... + def is_public(self) -> bool: ... + def public_key(self) -> Self: ... + def to_pem(self, pem_format: str = "PKCS8") -> bytes: ... + def to_dict(self) -> dict[str, Any]: ... + def wrap_key(self, key_data: bytes) -> bytes: ... + def unwrap_key(self, wrapped_key: bytes) -> bytes: ... diff --git a/stubs/python-jose/jose/constants.pyi b/stubs/python-jose/jose/constants.pyi new file mode 100644 index 000000000000..a8df8f155333 --- /dev/null +++ b/stubs/python-jose/jose/constants.pyi @@ -0,0 +1,75 @@ +from collections.abc import Callable, Mapping +from hashlib import _Hash +from typing import Final + +from .backends.base import Key + +class Algorithms: + NONE: str + HS256: str + HS384: str + HS512: str + RS256: str + RS384: str + RS512: str + ES256: str + ES384: str + ES512: str + A128CBC_HS256: str + A192CBC_HS384: str + A256CBC_HS512: str + A128GCM: str + A192GCM: str + A256GCM: str + A128CBC: str + A192CBC: str + A256CBC: str + DIR: str + RSA1_5: str + RSA_OAEP: str + RSA_OAEP_256: str + A128KW: str + A192KW: str + A256KW: str + ECDH_ES: str + ECDH_ES_A128KW: str + ECDH_ES_A192KW: str + ECDH_ES_A256KW: str + A128GCMKW: str + A192GCMKW: str + A256GCMKW: str + PBES2_HS256_A128KW: str + PBES2_HS384_A192KW: str + PBES2_HS512_A256KW: str + DEF: str + HMAC: set[str] + RSA_DS: set[str] + RSA_KW: set[str] + RSA: set[str] + EC_DS: set[str] + EC_KW: set[str] + EC: set[str] + AES_PSEUDO: set[str] + AES_JWE_ENC: set[str] + AES_ENC: set[str] + AES_KW: set[str] + AEC_GCM_KW: set[str] + AES: set[str] + PBES2_KW: set[str] + HMAC_AUTH_TAG: set[str] + GCM: set[str] + SUPPORTED: set[str] + ALL: set[str] + HASHES: Mapping[str, Callable[[bytes], _Hash]] + KEYS: Mapping[str, type[Key]] + +ALGORITHMS: Algorithms + +class Zips: + DEF: str + NONE: None + SUPPORTED: set[str | None] + +ZIPS: Zips + +JWE_SIZE_LIMIT: Final[int] diff --git a/stubs/python-jose/jose/exceptions.pyi b/stubs/python-jose/jose/exceptions.pyi new file mode 100644 index 000000000000..d7ab2176ce06 --- /dev/null +++ b/stubs/python-jose/jose/exceptions.pyi @@ -0,0 +1,12 @@ +class JOSEError(Exception): ... +class JWSError(JOSEError): ... +class JWSSignatureError(JWSError): ... +class JWSAlgorithmError(JWSError): ... +class JWTError(JOSEError): ... +class JWTClaimsError(JWTError): ... +class ExpiredSignatureError(JWTError): ... +class JWKError(JOSEError): ... +class JWEError(JOSEError): ... +class JWEParseError(JWEError): ... +class JWEInvalidAuth(JWEError): ... +class JWEAlgorithmUnsupportedError(JWEError): ... diff --git a/stubs/python-jose/jose/jwe.pyi b/stubs/python-jose/jose/jwe.pyi new file mode 100644 index 000000000000..e49a1cb093d7 --- /dev/null +++ b/stubs/python-jose/jose/jwe.pyi @@ -0,0 +1,22 @@ +from typing import Any + +from .backends.base import Key + +def encrypt( + plaintext: str | bytes, + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, + encryption: str = "A256GCM", + algorithm: str = "dir", + zip: str | None = None, + cty: str | None = None, + kid: str | None = None, +) -> bytes: ... +def decrypt( + jwe_str: str | bytes, + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, +) -> bytes | None: ... +def get_unverified_header(jwe_str: str | bytes | None) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/jwk.pyi b/stubs/python-jose/jose/jwk.pyi new file mode 100644 index 000000000000..27df5ef42b9d --- /dev/null +++ b/stubs/python-jose/jose/jwk.pyi @@ -0,0 +1,12 @@ +from typing import Any, Literal + +from .backends import AESKey as AESKey, ECKey as ECKey, HMACKey as HMACKey, RSAKey as RSAKey +from .backends.base import DIRKey as DIRKey, Key + +def get_key(algorithm: str) -> type[Key] | None: ... +def register_key(algorithm: str, key_class: type[Key]) -> Literal[True]: ... +def construct( + # explicitly checks for key_data as dict instance, instead of a Mapping + key_data: str | bytes | dict[str, Any] | Key, + algorithm: str | None = None, +) -> Key: ... diff --git a/stubs/python-jose/jose/jws.pyi b/stubs/python-jose/jose/jws.pyi new file mode 100644 index 000000000000..3f8194f6f243 --- /dev/null +++ b/stubs/python-jose/jose/jws.pyi @@ -0,0 +1,24 @@ +from collections.abc import Container, Iterable, Mapping +from typing import Any + +from .backends.base import Key + +def sign( + payload: bytes | Mapping[str, Any], + # Internally it's passed down to jwk.construct(), which explicitly checks for + # key as dict instance, instead of a Mapping + key: str | bytes | dict[str, Any] | Key, + headers: Mapping[str, Any] | None = None, + algorithm: str = "HS256", +) -> str: ... +def verify( + token: str | bytes, + key: str | bytes | Mapping[str, Any] | Key | Iterable[str], + # Callers of this function, like jwt.decode(), and functions called internally, + # like jws._verify_signature(), use and accept algorithms=None + algorithms: str | Container[str] | None, + verify: bool = True, +) -> bytes: ... +def get_unverified_header(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_headers(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_claims(token: str | bytes) -> bytes: ... diff --git a/stubs/python-jose/jose/jwt.pyi b/stubs/python-jose/jose/jwt.pyi new file mode 100644 index 000000000000..1f4254ac48b3 --- /dev/null +++ b/stubs/python-jose/jose/jwt.pyi @@ -0,0 +1,29 @@ +from collections.abc import Container, Iterable, Mapping, MutableMapping +from datetime import timezone +from typing import Any + +from .backends.base import Key + +UTC: timezone + +def encode( + claims: MutableMapping[str, Any], + # Internally it calls jws.sign() that expects a key dict instance instead of Mapping + key: str | bytes | dict[str, Any] | Key, + algorithm: str = "HS256", + headers: Mapping[str, Any] | None = None, + access_token: str | None = None, +) -> str: ... +def decode( + token: str | bytes, + key: str | bytes | Mapping[str, Any] | Key | Iterable[str], + algorithms: str | Container[str] | None = None, + options: Mapping[str, Any] | None = None, + audience: str | None = None, + issuer: str | Iterable[str] | None = None, + subject: str | None = None, + access_token: str | None = None, +) -> dict[str, Any]: ... +def get_unverified_header(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_headers(token: str | bytes) -> dict[str, Any]: ... +def get_unverified_claims(token: str | bytes) -> dict[str, Any]: ... diff --git a/stubs/python-jose/jose/utils.pyi b/stubs/python-jose/jose/utils.pyi new file mode 100644 index 000000000000..52db52b82809 --- /dev/null +++ b/stubs/python-jose/jose/utils.pyi @@ -0,0 +1,16 @@ +from collections.abc import Callable, Iterable +from datetime import timedelta +from hashlib import _Hash +from typing import Any + +def long_to_bytes(n: int, blocksize: int | None = 0) -> bytes: ... +def long_to_base64(data: int, size: int | None = 0) -> bytes: ... +def int_arr_to_long(arr: Iterable[Any]) -> int: ... +def base64_to_long(data: str | bytes) -> int: ... +def calculate_at_hash(access_token: str, hash_alg: Callable[[bytes], _Hash]) -> str: ... +def base64url_decode(input: bytes) -> bytes: ... +def base64url_encode(input: bytes) -> bytes: ... +def timedelta_total_seconds(delta: timedelta) -> int: ... +def ensure_binary(s: str | bytes) -> bytes: ... +def is_pem_format(key: bytes) -> bool: ... +def is_ssh_key(key: bytes) -> bool: ... diff --git a/stubs/python-nmap/@tests/stubtest_allowlist.txt b/stubs/python-nmap/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7e144572d598 --- /dev/null +++ b/stubs/python-nmap/@tests/stubtest_allowlist.txt @@ -0,0 +1 @@ +nmap.test_nmap diff --git a/stubs/python-nmap/METADATA.toml b/stubs/python-nmap/METADATA.toml new file mode 100644 index 000000000000..5adab60f78fd --- /dev/null +++ b/stubs/python-nmap/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.7.*" +upstream-repository = "https://bitbucket.org/xael/python-nmap" diff --git a/stubs/python-nmap/nmap/__init__.pyi b/stubs/python-nmap/nmap/__init__.pyi new file mode 100644 index 000000000000..d2e6aef65bb4 --- /dev/null +++ b/stubs/python-nmap/nmap/__init__.pyi @@ -0,0 +1,2 @@ +from .nmap import * +from .nmap import __author__ as __author__, __last_modification__ as __last_modification__, __version__ as __version__ diff --git a/stubs/python-nmap/nmap/nmap.pyi b/stubs/python-nmap/nmap/nmap.pyi new file mode 100644 index 000000000000..740467d72e55 --- /dev/null +++ b/stubs/python-nmap/nmap/nmap.pyi @@ -0,0 +1,142 @@ +from collections.abc import Callable, Iterable, Iterator +from typing import Any, TypeAlias, TypedDict, TypeVar, type_check_only + +_T = TypeVar("_T") +_Callback: TypeAlias = Callable[[str, _Result], object] + +@type_check_only +class _Result(TypedDict): + nmap: _ResultNmap + scan: dict[str, PortScannerHostDict] + +@type_check_only +class _ResultNmap(TypedDict): + command_line: str + scaninfo: _ResultNmapInfo + scanstats: _ResultNampStats + +@type_check_only +class _ResultNmapInfo(TypedDict, total=False): + error: str + warning: str + protocol: _ResultNampInfoProtocol + +@type_check_only +class _ResultNampInfoProtocol(TypedDict): + method: str + services: str + +@type_check_only +class _ResultNampStats(TypedDict): + timestr: str + elapsed: str + uphosts: str + downhosts: str + totalhosts: str + +@type_check_only +class _ResulHostUptime(TypedDict): + seconds: str + lastboot: str + +@type_check_only +class _ResultHostNames(TypedDict): + type: str + name: str + +@type_check_only +class _ResultHostPort(TypedDict): + conf: str + cpe: str + extrainfo: str + name: str + product: str + reason: str + state: str + version: str + +__last_modification__: str +__author__: str +__version__: str + +class PortScanner: + def __init__( + self, + nmap_search_path: Iterable[str] = ("nmap", "/usr/bin/nmap", "/usr/local/bin/nmap", "/sw/bin/nmap", "/opt/local/bin/nmap"), + ) -> None: ... + def get_nmap_last_output(self) -> str: ... + def nmap_version(self) -> tuple[int, int]: ... + def listscan(self, hosts: str = "127.0.0.1") -> list[str]: ... + def scan( + self, hosts: str = "127.0.0.1", ports: str | None = None, arguments: str = "-sV", sudo: bool = False, timeout: int = 0 + ) -> _Result: ... + def analyse_nmap_xml_scan( + self, + nmap_xml_output: str | None = None, + nmap_err: str = "", + nmap_err_keep_trace: str = "", + nmap_warn_keep_trace: str = "", + ) -> _Result: ... + def __getitem__(self, host: str) -> PortScannerHostDict: ... + def all_hosts(self) -> list[str]: ... + def command_line(self) -> str: ... + def scaninfo(self) -> _ResultNmapInfo: ... + def scanstats(self) -> _ResultNampStats: ... + def has_host(self, host: str) -> bool: ... + def csv(self) -> str: ... + +def __scan_progressive__( + self: object, hosts: str, ports: str, arguments: str, callback: _Callback | None, sudo: bool, timeout: int +) -> None: ... + +class PortScannerAsync: + def __init__(self) -> None: ... + def __del__(self) -> None: ... + def scan( + self, + hosts: str = "127.0.0.1", + ports: str | None = None, + arguments: str = "-sV", + callback: _Callback | None = None, + sudo: bool = False, + timeout: int = 0, + ) -> None: ... + def stop(self) -> None: ... + def wait(self, timeout: int | None = None) -> None: ... + def still_scanning(self) -> bool: ... + +class PortScannerYield(PortScannerAsync): + def __init__(self) -> None: ... + def scan( # type: ignore[override] + self, hosts: str = "127.0.0.1", ports: str | None = None, arguments: str = "-sV", sudo: bool = False, timeout: int = 0 + ) -> Iterator[tuple[str, _Result]]: ... + def stop(self) -> None: ... + def wait(self, timeout: int | None = None) -> None: ... + def still_scanning(self) -> None: ... # type: ignore[override] + +class PortScannerHostDict(dict[str, Any]): + def hostnames(self) -> list[_ResultHostNames]: ... + def hostname(self) -> str: ... + def state(self) -> str: ... + def uptime(self) -> _ResulHostUptime: ... + def all_protocols(self) -> list[str]: ... + def all_tcp(self) -> list[int]: ... + def has_tcp(self, port: int) -> bool: ... + def tcp(self, port: int) -> _ResultHostPort: ... + def all_udp(self) -> list[int]: ... + def has_udp(self, port: int) -> bool: ... + def udp(self, port: int) -> _ResultHostPort: ... + def all_ip(self) -> list[int]: ... + def has_ip(self, port: int) -> bool: ... + def ip(self, port: int) -> _ResultHostPort: ... + def all_sctp(self) -> list[int]: ... + def has_sctp(self, port: int) -> bool: ... + def sctp(self, port: int) -> _ResultHostPort: ... + +class PortScannerError(Exception): + value: str + def __init__(self, value: str) -> None: ... + +class PortScannerTimeout(PortScannerError): ... + +def convert_nmap_output_to_encoding(value: _T, code: str = "ascii") -> _T: ... diff --git a/stubs/python-xlib/@tests/stubtest_allowlist.txt b/stubs/python-xlib/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..731b14c8c3df --- /dev/null +++ b/stubs/python-xlib/@tests/stubtest_allowlist.txt @@ -0,0 +1,25 @@ +# Type helpers +Xlib._typing + +# __all__ is a map at runtime +# https://github.com/python-xlib/python-xlib/pull/238 +Xlib.ext(\.__all__)? + +# These will unconditionally fail at runtime +# See: https://github.com/python-xlib/python-xlib/issues/253 +Xlib.protocol.rq.DictWrapper.__gt__ +Xlib.protocol.rq.DictWrapper.__lt__ +Xlib.protocol.rq.Event.__gt__ +Xlib.protocol.rq.Event.__lt__ + +# should allow setting any attribute +Xlib.protocol.rq.GetAttrData.__setattr__ + +# Can be None or str once instantiated +Xlib.protocol.rq.*.structcode +# Should only ever be str once instantiated +Xlib.protocol.rq.*.name + +# Iteration variable that bleeds into the global scope +Xlib.protocol.rq.c +Xlib.protocol.rq.size diff --git a/stubs/python-xlib/METADATA.toml b/stubs/python-xlib/METADATA.toml new file mode 100644 index 000000000000..8bb5fab0a6bd --- /dev/null +++ b/stubs/python-xlib/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.33.*" +upstream-repository = "https://github.com/python-xlib/python-xlib" diff --git a/stubs/python-xlib/Xlib/X.pyi b/stubs/python-xlib/Xlib/X.pyi new file mode 100644 index 000000000000..cef7a5cdfced --- /dev/null +++ b/stubs/python-xlib/Xlib/X.pyi @@ -0,0 +1,347 @@ +from typing import Final + +NONE: Final = 0 +ParentRelative: Final = 1 +CopyFromParent: Final = 0 +PointerWindow: Final = 0 +InputFocus: Final = 1 +PointerRoot: Final = 1 +AnyPropertyType: Final = 0 +AnyKey: Final = 0 +AnyButton: Final = 0 +AllTemporary: Final = 0 +CurrentTime: Final = 0 +NoSymbol: Final = 0 +NoEventMask: Final = 0x0000000 +KeyPressMask: Final = 0x0000001 +KeyReleaseMask: Final = 0x0000002 +ButtonPressMask: Final = 0x0000004 +ButtonReleaseMask: Final = 0x0000008 +EnterWindowMask: Final = 0x0000010 +LeaveWindowMask: Final = 0x0000020 +PointerMotionMask: Final = 0x0000040 +PointerMotionHintMask: Final = 0x0000080 +Button1MotionMask: Final = 0x0000100 +Button2MotionMask: Final = 0x0000200 +Button3MotionMask: Final = 0x0000400 +Button4MotionMask: Final = 0x0000800 +Button5MotionMask: Final = 0x0001000 +ButtonMotionMask: Final = 0x0002000 +KeymapStateMask: Final = 0x0004000 +ExposureMask: Final = 0x0008000 +VisibilityChangeMask: Final = 0x0010000 +StructureNotifyMask: Final = 0x0020000 +ResizeRedirectMask: Final = 0x0040000 +SubstructureNotifyMask: Final = 0x0080000 +SubstructureRedirectMask: Final = 0x0100000 +FocusChangeMask: Final = 0x0200000 +PropertyChangeMask: Final = 0x0400000 +ColormapChangeMask: Final = 0x0800000 +OwnerGrabButtonMask: Final = 0x1000000 +KeyPress: Final = 2 +KeyRelease: Final = 3 +ButtonPress: Final = 4 +ButtonRelease: Final = 5 +MotionNotify: Final = 6 +EnterNotify: Final = 7 +LeaveNotify: Final = 8 +FocusIn: Final = 9 +FocusOut: Final = 10 +KeymapNotify: Final = 11 +Expose: Final = 12 +GraphicsExpose: Final = 13 +NoExpose: Final = 14 +VisibilityNotify: Final = 15 +CreateNotify: Final = 16 +DestroyNotify: Final = 17 +UnmapNotify: Final = 18 +MapNotify: Final = 19 +MapRequest: Final = 20 +ReparentNotify: Final = 21 +ConfigureNotify: Final = 22 +ConfigureRequest: Final = 23 +GravityNotify: Final = 24 +ResizeRequest: Final = 25 +CirculateNotify: Final = 26 +CirculateRequest: Final = 27 +PropertyNotify: Final = 28 +SelectionClear: Final = 29 +SelectionRequest: Final = 30 +SelectionNotify: Final = 31 +ColormapNotify: Final = 32 +ClientMessage: Final = 33 +MappingNotify: Final = 34 +LASTEvent: Final = 35 +ShiftMapIndex: Final = 0 +LockMapIndex: Final = 1 +ControlMapIndex: Final = 2 +Mod1MapIndex: Final = 3 +Mod2MapIndex: Final = 4 +Mod3MapIndex: Final = 5 +Mod4MapIndex: Final = 6 +Mod5MapIndex: Final = 7 +ShiftMask: Final = 0x0001 +LockMask: Final = 0x0002 +ControlMask: Final = 0x0004 +Mod1Mask: Final = 0x0008 +Mod2Mask: Final = 0x0010 +Mod3Mask: Final = 0x0020 +Mod4Mask: Final = 0x0040 +Mod5Mask: Final = 0x0080 +Button1Mask: Final = 0x0100 +Button2Mask: Final = 0x0200 +Button3Mask: Final = 0x0400 +Button4Mask: Final = 0x0800 +Button5Mask: Final = 0x1000 +AnyModifier: Final = 0x8000 +Button1: Final = 1 +Button2: Final = 2 +Button3: Final = 3 +Button4: Final = 4 +Button5: Final = 5 +NotifyNormal: Final = 0 +NotifyGrab: Final = 1 +NotifyUngrab: Final = 2 +NotifyWhileGrabbed: Final = 3 +NotifyHint: Final = 1 +NotifyAncestor: Final = 0 +NotifyVirtual: Final = 1 +NotifyInferior: Final = 2 +NotifyNonlinear: Final = 3 +NotifyNonlinearVirtual: Final = 4 +NotifyPointer: Final = 5 +NotifyPointerRoot: Final = 6 +NotifyDetailNone: Final = 7 +VisibilityUnobscured: Final = 0 +VisibilityPartiallyObscured: Final = 1 +VisibilityFullyObscured: Final = 2 +PlaceOnTop: Final = 0 +PlaceOnBottom: Final = 1 +FamilyInternet: Final = 0 +FamilyDECnet: Final = 1 +FamilyChaos: Final = 2 +FamilyServerInterpreted: Final = 5 +FamilyInternetV6: Final = 6 +PropertyNewValue: Final = 0 +PropertyDelete: Final = 1 +ColormapUninstalled: Final = 0 +ColormapInstalled: Final = 1 +GrabModeSync: Final = 0 +GrabModeAsync: Final = 1 +GrabSuccess: Final = 0 +AlreadyGrabbed: Final = 1 +GrabInvalidTime: Final = 2 +GrabNotViewable: Final = 3 +GrabFrozen: Final = 4 +AsyncPointer: Final = 0 +SyncPointer: Final = 1 +ReplayPointer: Final = 2 +AsyncKeyboard: Final = 3 +SyncKeyboard: Final = 4 +ReplayKeyboard: Final = 5 +AsyncBoth: Final = 6 +SyncBoth: Final = 7 +RevertToNone: Final = 0 +RevertToPointerRoot: Final = PointerRoot +RevertToParent: Final = 2 +Success: Final = 0 +BadRequest: Final = 1 +BadValue: Final = 2 +BadWindow: Final = 3 +BadPixmap: Final = 4 +BadAtom: Final = 5 +BadCursor: Final = 6 +BadFont: Final = 7 +BadMatch: Final = 8 +BadDrawable: Final = 9 +BadAccess: Final = 10 +BadAlloc: Final = 11 +BadColor: Final = 12 +BadGC: Final = 13 +BadIDChoice: Final = 14 +BadName: Final = 15 +BadLength: Final = 16 +BadImplementation: Final = 17 +FirstExtensionError: Final = 128 +LastExtensionError: Final = 255 +InputOutput: Final = 1 +InputOnly: Final = 2 +CWBackPixmap: Final = 0x0001 +CWBackPixel: Final = 0x0002 +CWBorderPixmap: Final = 0x0004 +CWBorderPixel: Final = 0x0008 +CWBitGravity: Final = 0x0010 +CWWinGravity: Final = 0x0020 +CWBackingStore: Final = 0x0040 +CWBackingPlanes: Final = 0x0080 +CWBackingPixel: Final = 0x0100 +CWOverrideRedirect: Final = 0x0200 +CWSaveUnder: Final = 0x0400 +CWEventMask: Final = 0x0800 +CWDontPropagate: Final = 0x1000 +CWColormap: Final = 0x2000 +CWCursor: Final = 0x4000 +CWX: Final = 0x01 +CWY: Final = 0x02 +CWWidth: Final = 0x04 +CWHeight: Final = 0x08 +CWBorderWidth: Final = 0x10 +CWSibling: Final = 0x20 +CWStackMode: Final = 0x40 +ForgetGravity: Final = 0 +NorthWestGravity: Final = 1 +NorthGravity: Final = 2 +NorthEastGravity: Final = 3 +WestGravity: Final = 4 +CenterGravity: Final = 5 +EastGravity: Final = 6 +SouthWestGravity: Final = 7 +SouthGravity: Final = 8 +SouthEastGravity: Final = 9 +StaticGravity: Final = 10 +UnmapGravity: Final = 0 +NotUseful: Final = 0 +WhenMapped: Final = 1 +Always: Final = 2 +IsUnmapped: Final = 0 +IsUnviewable: Final = 1 +IsViewable: Final = 2 +SetModeInsert: Final = 0 +SetModeDelete: Final = 1 +DestroyAll: Final = 0 +RetainPermanent: Final = 1 +RetainTemporary: Final = 2 +Above: Final = 0 +Below: Final = 1 +TopIf: Final = 2 +BottomIf: Final = 3 +Opposite: Final = 4 +RaiseLowest: Final = 0 +LowerHighest: Final = 1 +PropModeReplace: Final = 0 +PropModePrepend: Final = 1 +PropModeAppend: Final = 2 +GXclear: Final = 0x0 +GXand: Final = 0x1 +GXandReverse: Final = 0x2 +GXcopy: Final = 0x3 +GXandInverted: Final = 0x4 +GXnoop: Final = 0x5 +GXxor: Final = 0x6 +GXor: Final = 0x7 +GXnor: Final = 0x8 +GXequiv: Final = 0x9 +GXinvert: Final = 0xA +GXorReverse: Final = 0xB +GXcopyInverted: Final = 0xC +GXorInverted: Final = 0xD +GXnand: Final = 0xE +GXset: Final = 0xF +LineSolid: Final = 0 +LineOnOffDash: Final = 1 +LineDoubleDash: Final = 2 +CapNotLast: Final = 0 +CapButt: Final = 1 +CapRound: Final = 2 +CapProjecting: Final = 3 +JoinMiter: Final = 0 +JoinRound: Final = 1 +JoinBevel: Final = 2 +FillSolid: Final = 0 +FillTiled: Final = 1 +FillStippled: Final = 2 +FillOpaqueStippled: Final = 3 +EvenOddRule: Final = 0 +WindingRule: Final = 1 +ClipByChildren: Final = 0 +IncludeInferiors: Final = 1 +Unsorted: Final = 0 +YSorted: Final = 1 +YXSorted: Final = 2 +YXBanded: Final = 3 +CoordModeOrigin: Final = 0 +CoordModePrevious: Final = 1 +Complex: Final = 0 +Nonconvex: Final = 1 +Convex: Final = 2 +ArcChord: Final = 0 +ArcPieSlice: Final = 1 +GCFunction: Final = 0x000001 +GCPlaneMask: Final = 0x000002 +GCForeground: Final = 0x000004 +GCBackground: Final = 0x000008 +GCLineWidth: Final = 0x000010 +GCLineStyle: Final = 0x000020 +GCCapStyle: Final = 0x000040 +GCJoinStyle: Final = 0x000080 +GCFillStyle: Final = 0x000100 +GCFillRule: Final = 0x000200 +GCTile: Final = 0x000400 +GCStipple: Final = 0x000800 +GCTileStipXOrigin: Final = 0x001000 +GCTileStipYOrigin: Final = 0x002000 +GCFont: Final = 0x004000 +GCSubwindowMode: Final = 0x008000 +GCGraphicsExposures: Final = 0x010000 +GCClipXOrigin: Final = 0x020000 +GCClipYOrigin: Final = 0x040000 +GCClipMask: Final = 0x080000 +GCDashOffset: Final = 0x100000 +GCDashList: Final = 0x200000 +GCArcMode: Final = 0x400000 +GCLastBit: Final = 22 +FontLeftToRight: Final = 0 +FontRightToLeft: Final = 1 +FontChange: Final = 255 +XYBitmap: Final = 0 +XYPixmap: Final = 1 +ZPixmap: Final = 2 +AllocNone: Final = 0 +AllocAll: Final = 1 +DoRed: Final = 0x1 +DoGreen: Final = 0x2 +DoBlue: Final = 0x4 +CursorShape: Final = 0 +TileShape: Final = 1 +StippleShape: Final = 2 +AutoRepeatModeOff: Final = 0 +AutoRepeatModeOn: Final = 1 +AutoRepeatModeDefault: Final = 2 +LedModeOff: Final = 0 +LedModeOn: Final = 1 +KBKeyClickPercent: Final = 0x01 +KBBellPercent: Final = 0x02 +KBBellPitch: Final = 0x04 +KBBellDuration: Final = 0x08 +KBLed: Final = 0x10 +KBLedMode: Final = 0x20 +KBKey: Final = 0x40 +KBAutoRepeatMode: Final = 0x80 +MappingSuccess: Final = 0 +MappingBusy: Final = 1 +MappingFailed: Final = 2 +MappingModifier: Final = 0 +MappingKeyboard: Final = 1 +MappingPointer: Final = 2 +DontPreferBlanking: Final = 0 +PreferBlanking: Final = 1 +DefaultBlanking: Final = 2 +DisableScreenSaver: Final = 0 +DisableScreenInterval: Final = 0 +DontAllowExposures: Final = 0 +AllowExposures: Final = 1 +DefaultExposures: Final = 2 +ScreenSaverReset: Final = 0 +ScreenSaverActive: Final = 1 +HostInsert: Final = 0 +HostDelete: Final = 1 +EnableAccess: Final = 1 +DisableAccess: Final = 0 +StaticGray: Final = 0 +GrayScale: Final = 1 +StaticColor: Final = 2 +PseudoColor: Final = 3 +TrueColor: Final = 4 +DirectColor: Final = 5 +LSBFirst: Final = 0 +MSBFirst: Final = 1 diff --git a/stubs/python-xlib/Xlib/XK.pyi b/stubs/python-xlib/Xlib/XK.pyi new file mode 100644 index 000000000000..01ad548182df --- /dev/null +++ b/stubs/python-xlib/Xlib/XK.pyi @@ -0,0 +1,7 @@ +from Xlib.keysymdef.latin1 import * +from Xlib.keysymdef.miscellany import * +from Xlib.X import NoSymbol as NoSymbol + +def string_to_keysym(keysym: str) -> int: ... +def load_keysym_group(group: str) -> None: ... +def keysym_to_string(keysym: int) -> str | None: ... diff --git a/stubs/python-xlib/Xlib/Xatom.pyi b/stubs/python-xlib/Xlib/Xatom.pyi new file mode 100644 index 000000000000..5f71b24f0d92 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xatom.pyi @@ -0,0 +1,71 @@ +from typing import Final + +PRIMARY: Final = 1 +SECONDARY: Final = 2 +ARC: Final = 3 +ATOM: Final = 4 +BITMAP: Final = 5 +CARDINAL: Final = 6 +COLORMAP: Final = 7 +CURSOR: Final = 8 +CUT_BUFFER0: Final = 9 +CUT_BUFFER1: Final = 10 +CUT_BUFFER2: Final = 11 +CUT_BUFFER3: Final = 12 +CUT_BUFFER4: Final = 13 +CUT_BUFFER5: Final = 14 +CUT_BUFFER6: Final = 15 +CUT_BUFFER7: Final = 16 +DRAWABLE: Final = 17 +FONT: Final = 18 +INTEGER: Final = 19 +PIXMAP: Final = 20 +POINT: Final = 21 +RECTANGLE: Final = 22 +RESOURCE_MANAGER: Final = 23 +RGB_COLOR_MAP: Final = 24 +RGB_BEST_MAP: Final = 25 +RGB_BLUE_MAP: Final = 26 +RGB_DEFAULT_MAP: Final = 27 +RGB_GRAY_MAP: Final = 28 +RGB_GREEN_MAP: Final = 29 +RGB_RED_MAP: Final = 30 +STRING: Final = 31 +VISUALID: Final = 32 +WINDOW: Final = 33 +WM_COMMAND: Final = 34 +WM_HINTS: Final = 35 +WM_CLIENT_MACHINE: Final = 36 +WM_ICON_NAME: Final = 37 +WM_ICON_SIZE: Final = 38 +WM_NAME: Final = 39 +WM_NORMAL_HINTS: Final = 40 +WM_SIZE_HINTS: Final = 41 +WM_ZOOM_HINTS: Final = 42 +MIN_SPACE: Final = 43 +NORM_SPACE: Final = 44 +MAX_SPACE: Final = 45 +END_SPACE: Final = 46 +SUPERSCRIPT_X: Final = 47 +SUPERSCRIPT_Y: Final = 48 +SUBSCRIPT_X: Final = 49 +SUBSCRIPT_Y: Final = 50 +UNDERLINE_POSITION: Final = 51 +UNDERLINE_THICKNESS: Final = 52 +STRIKEOUT_ASCENT: Final = 53 +STRIKEOUT_DESCENT: Final = 54 +ITALIC_ANGLE: Final = 55 +X_HEIGHT: Final = 56 +QUAD_WIDTH: Final = 57 +WEIGHT: Final = 58 +POINT_SIZE: Final = 59 +RESOLUTION: Final = 60 +COPYRIGHT: Final = 61 +NOTICE: Final = 62 +FONT_NAME: Final = 63 +FAMILY_NAME: Final = 64 +FULL_NAME: Final = 65 +CAP_HEIGHT: Final = 66 +WM_CLASS: Final = 67 +WM_TRANSIENT_FOR: Final = 68 +LAST_PREDEFINED: Final = 68 diff --git a/stubs/python-xlib/Xlib/Xcursorfont.pyi b/stubs/python-xlib/Xlib/Xcursorfont.pyi new file mode 100644 index 000000000000..a4d20b804d48 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xcursorfont.pyi @@ -0,0 +1,80 @@ +from typing import Final + +num_glyphs: Final = 154 +X_cursor: Final = 0 +arrow: Final = 2 +based_arrow_down: Final = 4 +based_arrow_up: Final = 6 +boat: Final = 8 +bogosity: Final = 10 +bottom_left_corner: Final = 12 +bottom_right_corner: Final = 14 +bottom_side: Final = 16 +bottom_tee: Final = 18 +box_spiral: Final = 20 +center_ptr: Final = 22 +circle: Final = 24 +clock: Final = 26 +coffee_mug: Final = 28 +cross: Final = 30 +cross_reverse: Final = 32 +crosshair: Final = 34 +diamond_cross: Final = 36 +dot: Final = 38 +dotbox: Final = 40 +double_arrow: Final = 42 +draft_large: Final = 44 +draft_small: Final = 46 +draped_box: Final = 48 +exchange: Final = 50 +fleur: Final = 52 +gobbler: Final = 54 +gumby: Final = 56 +hand1: Final = 58 +hand2: Final = 60 +heart: Final = 62 +icon: Final = 64 +iron_cross: Final = 66 +left_ptr: Final = 68 +left_side: Final = 70 +left_tee: Final = 72 +leftbutton: Final = 74 +ll_angle: Final = 76 +lr_angle: Final = 78 +man: Final = 80 +middlebutton: Final = 82 +mouse: Final = 84 +pencil: Final = 86 +pirate: Final = 88 +plus: Final = 90 +question_arrow: Final = 92 +right_ptr: Final = 94 +right_side: Final = 96 +right_tee: Final = 98 +rightbutton: Final = 100 +rtl_logo: Final = 102 +sailboat: Final = 104 +sb_down_arrow: Final = 106 +sb_h_double_arrow: Final = 108 +sb_left_arrow: Final = 110 +sb_right_arrow: Final = 112 +sb_up_arrow: Final = 114 +sb_v_double_arrow: Final = 116 +shuttle: Final = 118 +sizing: Final = 120 +spider: Final = 122 +spraycan: Final = 124 +star: Final = 126 +target: Final = 128 +tcross: Final = 130 +top_left_arrow: Final = 132 +top_left_corner: Final = 134 +top_right_corner: Final = 136 +top_side: Final = 138 +top_tee: Final = 140 +trek: Final = 142 +ul_angle: Final = 144 +umbrella: Final = 146 +ur_angle: Final = 148 +watch: Final = 150 +xterm: Final = 152 diff --git a/stubs/python-xlib/Xlib/Xutil.pyi b/stubs/python-xlib/Xlib/Xutil.pyi new file mode 100644 index 000000000000..71ee250b8ce3 --- /dev/null +++ b/stubs/python-xlib/Xlib/Xutil.pyi @@ -0,0 +1,59 @@ +from typing import Final + +NoValue: Final = 0x0000 +XValue: Final = 0x0001 +YValue: Final = 0x0002 +WidthValue: Final = 0x0004 +HeightValue: Final = 0x0008 +AllValues: Final = 0x000F +XNegative: Final = 0x0010 +YNegative: Final = 0x0020 +USPosition: Final = 0x001 +USSize: Final = 0x002 +PPosition: Final = 0x004 +PSize: Final = 0x008 +PMinSize: Final = 0x010 +PMaxSize: Final = 0x020 +PResizeInc: Final = 0x040 +PAspect: Final = 0x080 +PBaseSize: Final = 0x100 +PWinGravity: Final = 0x200 +PAllHints: Final = 252 +InputHint: Final = 0x001 +StateHint: Final = 0x002 +IconPixmapHint: Final = 0x004 +IconWindowHint: Final = 0x008 +IconPositionHint: Final = 0x010 +IconMaskHint: Final = 0x020 +WindowGroupHint: Final = 0x040 +MessageHint: Final = 0x080 +UrgencyHint: Final = 0x100 +AllHints: Final = 511 +WithdrawnState: Final = 0 +NormalState: Final = 1 +IconicState: Final = 3 +DontCareState: Final = 0 +ZoomState: Final = 2 +InactiveState: Final = 4 +RectangleOut: Final = 0 +RectangleIn: Final = 1 +RectanglePart: Final = 2 +VisualNoMask: Final = 0x0 +VisualIDMask: Final = 0x1 +VisualScreenMask: Final = 0x2 +VisualDepthMask: Final = 0x4 +VisualClassMask: Final = 0x8 +VisualRedMaskMask: Final = 0x10 +VisualGreenMaskMask: Final = 0x20 +VisualBlueMaskMask: Final = 0x40 +VisualColormapSizeMask: Final = 0x80 +VisualBitsPerRGBMask: Final = 0x100 +VisualAllMask: Final = 0x1FF +ReleaseByFreeingColormap: Final = 1 +BitmapSuccess: Final = 0 +BitmapOpenFailed: Final = 1 +BitmapFileInvalid: Final = 2 +BitmapNoMemory: Final = 3 +XCSUCCESS: Final = 0 +XCNOMEM: Final = 1 +XCNOENT: Final = 2 diff --git a/stubs/python-xlib/Xlib/__init__.pyi b/stubs/python-xlib/Xlib/__init__.pyi new file mode 100644 index 000000000000..988134c01302 --- /dev/null +++ b/stubs/python-xlib/Xlib/__init__.pyi @@ -0,0 +1,14 @@ +from Xlib import ( + XK as XK, + X as X, + Xatom as Xatom, + Xcursorfont as Xcursorfont, + Xutil as Xutil, + display as display, + error as error, + rdb as rdb, +) + +__all__ = ["X", "XK", "Xatom", "Xcursorfont", "Xutil", "display", "error", "rdb"] + +# Shared types throughout the stub diff --git a/stubs/python-xlib/Xlib/_typing.pyi b/stubs/python-xlib/Xlib/_typing.pyi new file mode 100644 index 000000000000..90f05ff16109 --- /dev/null +++ b/stubs/python-xlib/Xlib/_typing.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from typing import TypeAlias, TypeVar + +from Xlib.error import XError +from Xlib.protocol.rq import Request + +_T = TypeVar("_T") +ErrorHandler: TypeAlias = Callable[[XError, Request | None], _T] diff --git a/stubs/python-xlib/Xlib/display.pyi b/stubs/python-xlib/Xlib/display.pyi new file mode 100644 index 000000000000..c1cda16e88bf --- /dev/null +++ b/stubs/python-xlib/Xlib/display.pyi @@ -0,0 +1,164 @@ +from collections.abc import Callable, Iterable, Sequence +from re import Pattern +from types import FunctionType, MethodType +from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only + +from Xlib import error +from Xlib._typing import ErrorHandler +from Xlib.protocol import display, request, rq +from Xlib.xobject import colormap, cursor, drawable, fontable, resource + +_ResourceBaseClass: TypeAlias = ( + resource.Resource + | drawable.Drawable + | drawable.Window + | drawable.Pixmap + | fontable.Fontable + | fontable.Font + | fontable.GC + | colormap.Colormap + | cursor.Cursor +) + +# Is the type of the `_resource_baseclasses` variable, defined in this file at runtime +@type_check_only +class _ResourceBaseClassesType(TypedDict): # noqa: Y049 + resource: type[resource.Resource] + drawable: type[drawable.Drawable] + window: type[drawable.Window] + pixmap: type[drawable.Pixmap] + fontable: type[fontable.Fontable] + font: type[fontable.Font] + gc: type[fontable.GC] + colormap: type[colormap.Colormap] + cursor: type[cursor.Cursor] + +class _BaseDisplay(display.Display): + def __init__(self, display: str | None = None) -> None: ... + def get_atom(self, atomname: str, only_if_exists: bool = False) -> int: ... + +class Display: + display: _BaseDisplay + keysym_translations: dict[int, str] + extensions: list[str] + class_extension_dicts: dict[str, dict[str, FunctionType]] + display_extension_methods: dict[str, Callable[..., Any]] + extension_event: rq.DictWrapper + def __init__(self, display: str | None = None) -> None: ... + def get_display_name(self) -> str: ... + def fileno(self) -> int: ... + def close(self) -> None: ... + def set_error_handler(self, handler: ErrorHandler[object] | None) -> None: ... + def flush(self) -> None: ... + def sync(self) -> None: ... + def next_event(self) -> rq.Event: ... + def pending_events(self) -> int: ... + def has_extension(self, extension: str) -> bool: ... + + @overload + def create_resource_object(self, type: Literal["resource"], id: int) -> resource.Resource: ... + @overload + def create_resource_object(self, type: Literal["drawable"], id: int) -> drawable.Drawable: ... + @overload + def create_resource_object(self, type: Literal["window"], id: int) -> drawable.Window: ... + @overload + def create_resource_object(self, type: Literal["pixmap"], id: int) -> drawable.Pixmap: ... + @overload + def create_resource_object(self, type: Literal["fontable"], id: int) -> fontable.Fontable: ... + @overload + def create_resource_object(self, type: Literal["font"], id: int) -> fontable.Font: ... + @overload + def create_resource_object(self, type: Literal["gc"], id: int) -> fontable.GC: ... + @overload + def create_resource_object(self, type: Literal["colormap"], id: int) -> colormap.Colormap: ... + @overload + def create_resource_object(self, type: Literal["cursor"], id: int) -> cursor.Cursor: ... + @overload + def create_resource_object(self, type: str, id: int) -> resource.Resource: ... + + def __getattr__(self, attr: str) -> MethodType: ... + def screen(self, sno: int | None = None) -> rq.Struct: ... + def screen_count(self) -> int: ... + def get_default_screen(self) -> int: ... + def extension_add_method(self, object: str, name: str, function: Callable[..., Any]) -> None: ... + def extension_add_event(self, code: int, evt: type, name: str | None = None) -> None: ... + def extension_add_subevent(self, code: int, subcode: int | None, evt: type[rq.Event], name: str | None = None) -> None: ... + def extension_add_error(self, code: int, err: type[error.XError]) -> None: ... + def keycode_to_keysym(self, keycode: int, index: int) -> int: ... + def keysym_to_keycode(self, keysym: int) -> int: ... + def keysym_to_keycodes(self, keysym: int) -> Iterable[tuple[int, int]]: ... + def refresh_keyboard_mapping(self, evt: rq.Event) -> None: ... + def lookup_string(self, keysym: int) -> str | None: ... + def rebind_string(self, keysym: int, newstring: str | None) -> None: ... + def intern_atom(self, name: str, only_if_exists: bool = False) -> int: ... + def get_atom(self, atom: str, only_if_exists: bool = False) -> int: ... + def get_atom_name(self, atom: int) -> str: ... + def get_selection_owner(self, selection: int) -> int: ... + def send_event( + self, + destination: int, + event: rq.Event, + event_mask: int = 0, + propagate: bool = False, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_pointer(self, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_active_pointer_grab( + self, event_mask: int, cursor: cursor.Cursor, time: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def ungrab_keyboard(self, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def allow_events(self, mode: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def grab_server(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def ungrab_server(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def warp_pointer( + self, + x: int, + y: int, + src_window: int = 0, + src_x: int = 0, + src_y: int = 0, + src_width: int = 0, + src_height: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def set_input_focus(self, focus: int, revert_to: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_input_focus(self) -> request.GetInputFocus: ... + def query_keymap(self) -> bytes: ... # TODO: Validate if this is correct + def open_font(self, name: str) -> _ResourceBaseClass | None: ... + def list_fonts(self, pattern: Pattern[str] | str, max_names: int) -> list[str]: ... + def list_fonts_with_info(self, pattern: Pattern[str] | str, max_names: int) -> request.ListFontsWithInfo: ... + def set_font_path(self, path: Sequence[str], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_font_path(self) -> list[str]: ... + def query_extension(self, name: str) -> request.QueryExtension | None: ... + def list_extensions(self) -> list[str]: ... + def change_keyboard_mapping( + self, first_keycode: int, keysyms: Sequence[Sequence[int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_keyboard_mapping(self, first_keycode: int, count: int) -> list[tuple[int, ...]]: ... + def change_keyboard_control(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def get_keyboard_control(self) -> request.GetKeyboardControl: ... + def bell(self, percent: int = 0, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_pointer_control( + self, accel: tuple[int, int] | None = None, threshold: int | None = None, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_pointer_control(self) -> request.GetPointerControl: ... + def set_screen_saver( + self, timeout: int, interval: int, prefer_blank: int, allow_exposures: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def get_screen_saver(self) -> request.GetScreenSaver: ... + def change_hosts( + self, + mode: int, + host_family: int, + host: Sequence[int] | Sequence[bytes], # TODO: validate + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def list_hosts(self) -> request.ListHosts: ... + def set_access_control(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_close_down_mode(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def force_screen_saver(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_pointer_mapping(self, map: Sequence[int]) -> int: ... + def get_pointer_mapping(self) -> list[int]: ... + def set_modifier_mapping(self, keycodes: rq._ModifierMappingList8Elements) -> int: ... + def get_modifier_mapping(self) -> Sequence[Sequence[int]]: ... + def no_operation(self, onerror: ErrorHandler[object] | None = None) -> None: ... diff --git a/stubs/python-xlib/Xlib/error.pyi b/stubs/python-xlib/Xlib/error.pyi new file mode 100644 index 000000000000..e78f9130f896 --- /dev/null +++ b/stubs/python-xlib/Xlib/error.pyi @@ -0,0 +1,57 @@ +from _typeshed import SliceableBuffer +from typing import Final, Literal + +from Xlib.protocol import display, rq + +class DisplayError(Exception): + display: object + def __init__(self, display: object) -> None: ... + +class DisplayNameError(DisplayError): ... + +class DisplayConnectionError(DisplayError): + display: object + msg: object + def __init__(self, display: object, msg: object) -> None: ... + +class ConnectionClosedError(Exception): + whom: object + def __init__(self, whom: object) -> None: ... + +class XauthError(Exception): ... +class XNoAuthError(Exception): ... +class ResourceIDError(Exception): ... + +class XError(rq.GetAttrData, Exception): + def __init__(self, display: display.Display, data: SliceableBuffer) -> None: ... + +class XResourceError(XError): ... +class BadRequest(XError): ... +class BadValue(XError): ... +class BadWindow(XResourceError): ... +class BadPixmap(XResourceError): ... +class BadAtom(XError): ... +class BadCursor(XResourceError): ... +class BadFont(XResourceError): ... +class BadMatch(XError): ... +class BadDrawable(XResourceError): ... +class BadAccess(XError): ... +class BadAlloc(XError): ... +class BadColor(XResourceError): ... +class BadGC(XResourceError): ... +class BadIDChoice(XResourceError): ... +class BadName(XError): ... +class BadLength(XError): ... +class BadImplementation(XError): ... + +xerror_class: Final[dict[int, type[XError]]] + +class CatchError: + error_types: tuple[type[XError], ...] + error: XError | None + request: rq.Request | None + def __init__(self, *errors: type[XError]) -> None: ... + def __call__(self, error: XError, request: rq.Request | None) -> Literal[0, 1]: ... + def get_error(self) -> XError | None: ... + def get_request(self) -> rq.Request | None: ... + def reset(self) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/__init__.pyi b/stubs/python-xlib/Xlib/ext/__init__.pyi new file mode 100644 index 000000000000..17afcdcac8f2 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/__init__.pyi @@ -0,0 +1,35 @@ +from Xlib.ext import ( + composite as composite, + damage as damage, + dpms as dpms, + ge as ge, + nvcontrol as nvcontrol, + randr as randr, + record as record, + res as res, + screensaver as screensaver, + security as security, + shape as shape, + xfixes as xfixes, + xinerama as xinerama, + xinput as xinput, + xtest as xtest, +) + +__all__ = [ + "ge", + "xtest", + "shape", + "xinerama", + "record", + "composite", + "randr", + "xfixes", + "security", + "xinput", + "nvcontrol", + "damage", + "dpms", + "res", + "screensaver", +] diff --git a/stubs/python-xlib/Xlib/ext/composite.pyi b/stubs/python-xlib/Xlib/ext/composite.pyi new file mode 100644 index 000000000000..9582ae777e6c --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/composite.pyi @@ -0,0 +1,47 @@ +from _typeshed import Unused +from collections.abc import Callable +from typing import Any, Final, TypeAlias + +from Xlib._typing import ErrorHandler +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import drawable, resource + +_Update: TypeAlias = Callable[[rq.DictWrapper | dict[str, Any]], object] + +extname: Final = "Composite" +RedirectAutomatic: Final = 0 +RedirectManual: Final = 1 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class RedirectWindow(rq.Request): ... + +def redirect_window(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class RedirectSubwindows(rq.Request): ... + +def redirect_subwindows(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class UnredirectWindow(rq.Request): ... + +def unredirect_window(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class UnredirectSubindows(rq.Request): ... + +def unredirect_subwindows(self: drawable.Window, update: _Update, onerror: ErrorHandler[object] | None = None) -> None: ... + +class CreateRegionFromBorderClip(rq.Request): ... + +def create_region_from_border_clip(self: drawable.Window, onerror: ErrorHandler[object] | None = None) -> int: ... + +class NameWindowPixmap(rq.Request): ... + +def name_window_pixmap(self: Display | resource.Resource, onerror: ErrorHandler[object] | None = None) -> drawable.Pixmap: ... + +class GetOverlayWindow(rq.ReplyRequest): ... + +def get_overlay_window(self: Display) -> GetOverlayWindow: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/damage.pyi b/stubs/python-xlib/Xlib/ext/damage.pyi new file mode 100644 index 000000000000..27320b17e444 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/damage.pyi @@ -0,0 +1,41 @@ +from typing import Final, Literal + +from Xlib.display import Display +from Xlib.error import XError +from Xlib.protocol import request, rq +from Xlib.xobject import resource + +extname: Final = "DAMAGE" +DamageNotifyCode: Final = 0 +BadDamageCode: Final = 0 +DamageReportRawRectangles: Final = 0 +DamageReportDeltaRectangles: Final = 1 +DamageReportBoundingBox: Final = 2 +DamageReportNonEmpty: Final = 3 +DamageReportLevel: Final[tuple[Literal[0], Literal[1], Literal[2], Literal[3]]] +DAMAGE = rq.Card32 + +class BadDamageError(XError): ... +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class DamageCreate(rq.Request): ... + +def damage_create(self: Display | resource.Resource, level: int) -> int: ... + +class DamageDestroy(rq.Request): ... + +def damage_destroy(self: Display | resource.Resource, damage: int) -> None: ... + +class DamageSubtract(rq.Request): ... + +def damage_subtract(self: Display | resource.Resource, damage: int, repair: int = 0, parts: int = 0) -> None: ... + +class DamageAdd(rq.Request): ... + +def damage_add(self: Display | resource.Resource, repair: int, parts: int) -> None: ... + +class DamageNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/dpms.pyi b/stubs/python-xlib/Xlib/ext/dpms.pyi new file mode 100644 index 000000000000..1319a5c88442 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/dpms.pyi @@ -0,0 +1,48 @@ +from _typeshed import Unused +from typing import Final, Literal + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "DPMS" +DPMSModeOn: Final = 0 +DPMSModeStandby: Final = 1 +DPMSModeSuspend: Final = 2 +DPMSModeOff: Final = 3 +DPMSPowerLevel: Final[tuple[Literal[0], Literal[1], Literal[2], Literal[3]]] + +class DPMSGetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource) -> DPMSGetVersion: ... + +class DPMSCapable(rq.ReplyRequest): ... + +def capable(self: Display | resource.Resource) -> DPMSCapable: ... + +class DPMSGetTimeouts(rq.ReplyRequest): ... + +def get_timeouts(self: Display | resource.Resource) -> DPMSGetTimeouts: ... + +class DPMSSetTimeouts(rq.Request): ... + +def set_timeouts( + self: Display | resource.Resource, standby_timeout: int, suspend_timeout: int, off_timeout: int +) -> DPMSSetTimeouts: ... + +class DPMSEnable(rq.Request): ... + +def enable(self: Display | resource.Resource) -> DPMSEnable: ... + +class DPMSDisable(rq.Request): ... + +def disable(self: Display | resource.Resource) -> DPMSDisable: ... + +class DPMSForceLevel(rq.Request): ... + +def force_level(self: Display | resource.Resource, power_level: int) -> DPMSForceLevel: ... + +class DPMSInfo(rq.ReplyRequest): ... + +def info(self: Display | resource.Resource) -> DPMSInfo: ... +def init(disp: Display, _info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/ge.pyi b/stubs/python-xlib/Xlib/ext/ge.pyi new file mode 100644 index 000000000000..1689e2af60c8 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/ge.pyi @@ -0,0 +1,18 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "Generic Event Extension" +GenericEventCode: Final = 35 + +class GEQueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> GEQueryVersion: ... + +class GenericEvent(rq.Event): ... + +def add_event_data(self: Display | resource.Resource, extension: int, evtype: int, estruct: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/nvcontrol.pyi b/stubs/python-xlib/Xlib/ext/nvcontrol.pyi new file mode 100644 index 000000000000..e8087a1ee37b --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/nvcontrol.pyi @@ -0,0 +1,1065 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "NV-CONTROL" + +def query_target_count(self: Display | resource.Resource, target: Target) -> int: ... +def query_int_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> int | None: ... +def set_int_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int, value: int) -> bool: ... +def query_string_attribute(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> str | None: ... +def query_valid_attr_values( + self: Display | resource.Resource, target: Target, display_mask: int, attr: int +) -> tuple[int, int] | None: ... +def query_binary_data(self: Display | resource.Resource, target: Target, display_mask: int, attr: int) -> bytes | None: ... +def get_coolers_used_by_gpu(self: Display | resource.Resource, target: Target) -> list[int] | None: ... +def get_gpu_count(self: Display | resource.Resource) -> int: ... +def get_name(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_driver_version(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_vbios_version(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_gpu_uuid(self: Display | resource.Resource, target: Target) -> str | None: ... +def get_utilization_rates(self: Display | resource.Resource, target: Target) -> dict[str, str | int]: ... +def get_performance_modes(self: Display | resource.Resource, target: Target) -> list[dict[str, str | int]]: ... +def get_clock_info(self: Display | resource.Resource, target: Target) -> dict[str, str | int]: ... +def get_vram(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_irq(self: Display | resource.Resource, target: Target) -> int | None: ... +def supports_framelock(self: Display | resource.Resource, target: Target) -> int | None: ... +def gvo_supported(self: Display | resource.Resource, screen: Target) -> int | None: ... +def get_core_temp(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_default_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_core_threshold(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_ambient_temp(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_cuda_cores(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_memory_bus_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_total_dedicated_gpu_memory(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_used_dedicated_gpu_memory(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_curr_pcie_link_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_pcie_link_width(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_curr_pcie_link_generation(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_encoder_utilization(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_decoder_utilization(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_current_performance_level(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_gpu_nvclock_offset(self: Display | resource.Resource, target: Target, perf_level: int) -> int | None: ... +def set_gpu_nvclock_offset(self: Display | resource.Resource, target: Target, perf_level: int, offset: int) -> bool: ... +def set_gpu_nvclock_offset_all_levels(self: Display | resource.Resource, target: Target, offset: int) -> bool: ... +def get_gpu_nvclock_offset_range( + self: Display | resource.Resource, target: Target, perf_level: int +) -> tuple[int, int] | None: ... +def get_mem_transfer_rate_offset(self: Display | resource.Resource, target: Target, perf_level: int) -> int | None: ... +def set_mem_transfer_rate_offset(self: Display | resource.Resource, target: Target, perf_level: int, offset: int) -> bool: ... +def set_mem_transfer_rate_offset_all_levels(self: Display | resource.Resource, target: Target, offset: int) -> bool: ... +def get_mem_transfer_rate_offset_range( + self: Display | resource.Resource, target: Target, perf_level: int +) -> tuple[int, int] | None: ... +def get_cooler_manual_control_enabled(self: Display | resource.Resource, target: Target) -> int | None: ... +def set_cooler_manual_control_enabled(self: Display | resource.Resource, target: Target, enabled: bool) -> bool: ... +def get_fan_duty(self: Display | resource.Resource, target: Target) -> int | None: ... +def set_fan_duty(self: Display | resource.Resource, cooler: Target, speed: int) -> bool: ... +def get_fan_rpm(self: Display | resource.Resource, target: Target) -> int | None: ... +def get_max_displays(self: Display | resource.Resource, target: Target) -> int | None: ... +def init(disp: Display, info: Unused) -> None: ... + +NV_CTRL_FLATPANEL_SCALING: Final = 2 +NV_CTRL_FLATPANEL_SCALING_DEFAULT: Final = 0 +NV_CTRL_FLATPANEL_SCALING_NATIVE: Final = 1 +NV_CTRL_FLATPANEL_SCALING_SCALED: Final = 2 +NV_CTRL_FLATPANEL_SCALING_CENTERED: Final = 3 +NV_CTRL_FLATPANEL_SCALING_ASPECT_SCALED: Final = 4 +NV_CTRL_FLATPANEL_DITHERING: Final = 3 +NV_CTRL_FLATPANEL_DITHERING_DEFAULT: Final = 0 +NV_CTRL_FLATPANEL_DITHERING_ENABLED: Final = 1 +NV_CTRL_FLATPANEL_DITHERING_DISABLED: Final = 2 +NV_CTRL_DITHERING: Final = 3 +NV_CTRL_DITHERING_AUTO: Final = 0 +NV_CTRL_DITHERING_ENABLED: Final = 1 +NV_CTRL_DITHERING_DISABLED: Final = 2 +NV_CTRL_DIGITAL_VIBRANCE: Final = 4 +NV_CTRL_BUS_TYPE: Final = 5 +NV_CTRL_BUS_TYPE_AGP: Final = 0 +NV_CTRL_BUS_TYPE_PCI: Final = 1 +NV_CTRL_BUS_TYPE_PCI_EXPRESS: Final = 2 +NV_CTRL_BUS_TYPE_INTEGRATED: Final = 3 +NV_CTRL_TOTAL_GPU_MEMORY: Final = 6 +NV_CTRL_VIDEO_RAM: Final = NV_CTRL_TOTAL_GPU_MEMORY +NV_CTRL_IRQ: Final = 7 +NV_CTRL_OPERATING_SYSTEM: Final = 8 +NV_CTRL_OPERATING_SYSTEM_LINUX: Final = 0 +NV_CTRL_OPERATING_SYSTEM_FREEBSD: Final = 1 +NV_CTRL_OPERATING_SYSTEM_SUNOS: Final = 2 +NV_CTRL_SYNC_TO_VBLANK: Final = 9 +NV_CTRL_SYNC_TO_VBLANK_OFF: Final = 0 +NV_CTRL_SYNC_TO_VBLANK_ON: Final = 1 +NV_CTRL_LOG_ANISO: Final = 10 +NV_CTRL_FSAA_MODE: Final = 11 +NV_CTRL_FSAA_MODE_NONE: Final = 0 +NV_CTRL_FSAA_MODE_2x: Final = 1 +NV_CTRL_FSAA_MODE_2x_5t: Final = 2 +NV_CTRL_FSAA_MODE_15x15: Final = 3 +NV_CTRL_FSAA_MODE_2x2: Final = 4 +NV_CTRL_FSAA_MODE_4x: Final = 5 +NV_CTRL_FSAA_MODE_4x_9t: Final = 6 +NV_CTRL_FSAA_MODE_8x: Final = 7 +NV_CTRL_FSAA_MODE_16x: Final = 8 +NV_CTRL_FSAA_MODE_8xS: Final = 9 +NV_CTRL_FSAA_MODE_8xQ: Final = 10 +NV_CTRL_FSAA_MODE_16xS: Final = 11 +NV_CTRL_FSAA_MODE_16xQ: Final = 12 +NV_CTRL_FSAA_MODE_32xS: Final = 13 +NV_CTRL_FSAA_MODE_32x: Final = 14 +NV_CTRL_FSAA_MODE_64xS: Final = 15 +NV_CTRL_FSAA_MODE_MAX: Final = NV_CTRL_FSAA_MODE_64xS +NV_CTRL_UBB: Final = 13 +NV_CTRL_UBB_OFF: Final = 0 +NV_CTRL_UBB_ON: Final = 1 +NV_CTRL_OVERLAY: Final = 14 +NV_CTRL_OVERLAY_OFF: Final = 0 +NV_CTRL_OVERLAY_ON: Final = 1 +NV_CTRL_STEREO: Final = 16 +NV_CTRL_STEREO_OFF: Final = 0 +NV_CTRL_STEREO_DDC: Final = 1 +NV_CTRL_STEREO_BLUELINE: Final = 2 +NV_CTRL_STEREO_DIN: Final = 3 +NV_CTRL_STEREO_PASSIVE_EYE_PER_DPY: Final = 4 +NV_CTRL_STEREO_VERTICAL_INTERLACED: Final = 5 +NV_CTRL_STEREO_COLOR_INTERLACED: Final = 6 +NV_CTRL_STEREO_HORIZONTAL_INTERLACED: Final = 7 +NV_CTRL_STEREO_CHECKERBOARD_PATTERN: Final = 8 +NV_CTRL_STEREO_INVERSE_CHECKERBOARD_PATTERN: Final = 9 +NV_CTRL_STEREO_3D_VISION: Final = 10 +NV_CTRL_STEREO_3D_VISION_PRO: Final = 11 +NV_CTRL_STEREO_HDMI_3D: Final = 12 +NV_CTRL_STEREO_TRIDELITY_SL: Final = 13 +NV_CTRL_STEREO_INBAND_STEREO_SIGNALING: Final = 14 +NV_CTRL_STEREO_MAX: Final = NV_CTRL_STEREO_INBAND_STEREO_SIGNALING +NV_CTRL_EMULATE: Final = 17 +NV_CTRL_EMULATE_NONE: Final = 0 +NV_CTRL_TWINVIEW: Final = 18 +NV_CTRL_TWINVIEW_NOT_ENABLED: Final = 0 +NV_CTRL_TWINVIEW_ENABLED: Final = 1 +NV_CTRL_CONNECTED_DISPLAYS: Final = 19 +NV_CTRL_ENABLED_DISPLAYS: Final = 20 +NV_CTRL_FRAMELOCK: Final = 21 +NV_CTRL_FRAMELOCK_NOT_SUPPORTED: Final = 0 +NV_CTRL_FRAMELOCK_SUPPORTED: Final = 1 +NV_CTRL_FRAMELOCK_MASTER: Final = 22 +NV_CTRL_FRAMELOCK_MASTER_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_MASTER_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_POLARITY: Final = 23 +NV_CTRL_FRAMELOCK_POLARITY_RISING_EDGE: Final = 0x1 +NV_CTRL_FRAMELOCK_POLARITY_FALLING_EDGE: Final = 0x2 +NV_CTRL_FRAMELOCK_POLARITY_BOTH_EDGES: Final = 0x3 +NV_CTRL_FRAMELOCK_SYNC_DELAY: Final = 24 +NV_CTRL_FRAMELOCK_SYNC_DELAY_MAX: Final = 2047 +NV_CTRL_FRAMELOCK_SYNC_DELAY_FACTOR: Final[float] +NV_CTRL_FRAMELOCK_SYNC_INTERVAL: Final = 25 +NV_CTRL_FRAMELOCK_PORT0_STATUS: Final = 26 +NV_CTRL_FRAMELOCK_PORT0_STATUS_INPUT: Final = 0 +NV_CTRL_FRAMELOCK_PORT0_STATUS_OUTPUT: Final = 1 +NV_CTRL_FRAMELOCK_PORT1_STATUS: Final = 27 +NV_CTRL_FRAMELOCK_PORT1_STATUS_INPUT: Final = 0 +NV_CTRL_FRAMELOCK_PORT1_STATUS_OUTPUT: Final = 1 +NV_CTRL_FRAMELOCK_HOUSE_STATUS: Final = 28 +NV_CTRL_FRAMELOCK_HOUSE_STATUS_NOT_DETECTED: Final = 0 +NV_CTRL_FRAMELOCK_HOUSE_STATUS_DETECTED: Final = 1 +NV_CTRL_FRAMELOCK_SYNC: Final = 29 +NV_CTRL_FRAMELOCK_SYNC_DISABLE: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_SYNC_READY: Final = 30 +NV_CTRL_FRAMELOCK_SYNC_READY_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_READY_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_STEREO_SYNC: Final = 31 +NV_CTRL_FRAMELOCK_STEREO_SYNC_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_STEREO_SYNC_TRUE: Final = 1 +NV_CTRL_FRAMELOCK_TEST_SIGNAL: Final = 32 +NV_CTRL_FRAMELOCK_TEST_SIGNAL_DISABLE: Final = 0 +NV_CTRL_FRAMELOCK_TEST_SIGNAL_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED: Final = 33 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_NONE: Final = 0 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_PORT0: Final = 0x1 +NV_CTRL_FRAMELOCK_ETHERNET_DETECTED_PORT1: Final = 0x2 +NV_CTRL_FRAMELOCK_VIDEO_MODE: Final = 34 +NV_CTRL_FRAMELOCK_VIDEO_MODE_NONE: Final = 0 +NV_CTRL_FRAMELOCK_VIDEO_MODE_TTL: Final = 1 +NV_CTRL_FRAMELOCK_VIDEO_MODE_NTSCPALSECAM: Final = 2 +NV_CTRL_FRAMELOCK_VIDEO_MODE_HDTV: Final = 3 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_AUTO: Final = 0 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_BI_LEVEL: Final = 2 +NV_CTRL_FRAMELOCK_VIDEO_MODE_COMPOSITE_TRI_LEVEL: Final = 3 +NV_CTRL_FRAMELOCK_SYNC_RATE: Final = 35 +NV_CTRL_FORCE_GENERIC_CPU: Final = 37 +NV_CTRL_FORCE_GENERIC_CPU_DISABLE: Final = 0 +NV_CTRL_FORCE_GENERIC_CPU_ENABLE: Final = 1 +NV_CTRL_OPENGL_AA_LINE_GAMMA: Final = 38 +NV_CTRL_OPENGL_AA_LINE_GAMMA_DISABLE: Final = 0 +NV_CTRL_OPENGL_AA_LINE_GAMMA_ENABLE: Final = 1 +NV_CTRL_FRAMELOCK_TIMING: Final = 39 +NV_CTRL_FRAMELOCK_TIMING_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_TIMING_TRUE: Final = 1 +NV_CTRL_FLIPPING_ALLOWED: Final = 40 +NV_CTRL_FLIPPING_ALLOWED_FALSE: Final = 0 +NV_CTRL_FLIPPING_ALLOWED_TRUE: Final = 1 +NV_CTRL_ARCHITECTURE: Final = 41 +NV_CTRL_ARCHITECTURE_X86: Final = 0 +NV_CTRL_ARCHITECTURE_X86_64: Final = 1 +NV_CTRL_ARCHITECTURE_IA64: Final = 2 +NV_CTRL_ARCHITECTURE_ARM: Final = 3 +NV_CTRL_ARCHITECTURE_AARCH64: Final = 4 +NV_CTRL_ARCHITECTURE_PPC64LE: Final = 5 +NV_CTRL_TEXTURE_CLAMPING: Final = 42 +NV_CTRL_TEXTURE_CLAMPING_EDGE: Final = 0 +NV_CTRL_TEXTURE_CLAMPING_SPEC: Final = 1 +NV_CTRL_CURSOR_SHADOW: Final = 43 +NV_CTRL_CURSOR_SHADOW_DISABLE: Final = 0 +NV_CTRL_CURSOR_SHADOW_ENABLE: Final = 1 +NV_CTRL_CURSOR_SHADOW_ALPHA: Final = 44 +NV_CTRL_CURSOR_SHADOW_RED: Final = 45 +NV_CTRL_CURSOR_SHADOW_GREEN: Final = 46 +NV_CTRL_CURSOR_SHADOW_BLUE: Final = 47 +NV_CTRL_CURSOR_SHADOW_X_OFFSET: Final = 48 +NV_CTRL_CURSOR_SHADOW_Y_OFFSET: Final = 49 +NV_CTRL_FSAA_APPLICATION_CONTROLLED: Final = 50 +NV_CTRL_FSAA_APPLICATION_CONTROLLED_ENABLED: Final = 1 +NV_CTRL_FSAA_APPLICATION_CONTROLLED_DISABLED: Final = 0 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED: Final = 51 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED_ENABLED: Final = 1 +NV_CTRL_LOG_ANISO_APPLICATION_CONTROLLED_DISABLED: Final = 0 +NV_CTRL_IMAGE_SHARPENING: Final = 52 +NV_CTRL_TV_OVERSCAN: Final = 53 +NV_CTRL_TV_FLICKER_FILTER: Final = 54 +NV_CTRL_TV_BRIGHTNESS: Final = 55 +NV_CTRL_TV_HUE: Final = 56 +NV_CTRL_TV_CONTRAST: Final = 57 +NV_CTRL_TV_SATURATION: Final = 58 +NV_CTRL_TV_RESET_SETTINGS: Final = 59 +NV_CTRL_GPU_CORE_TEMPERATURE: Final = 60 +NV_CTRL_GPU_CORE_THRESHOLD: Final = 61 +NV_CTRL_GPU_DEFAULT_CORE_THRESHOLD: Final = 62 +NV_CTRL_GPU_MAX_CORE_THRESHOLD: Final = 63 +NV_CTRL_AMBIENT_TEMPERATURE: Final = 64 +NV_CTRL_PBUFFER_SCANOUT_SUPPORTED: Final = 65 +NV_CTRL_PBUFFER_SCANOUT_FALSE: Final = 0 +NV_CTRL_PBUFFER_SCANOUT_TRUE: Final = 1 +NV_CTRL_PBUFFER_SCANOUT_XID: Final = 66 +NV_CTRL_GVO_SUPPORTED: Final = 67 +NV_CTRL_GVO_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GVO_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GVO_SYNC_MODE: Final = 68 +NV_CTRL_GVO_SYNC_MODE_FREE_RUNNING: Final = 0 +NV_CTRL_GVO_SYNC_MODE_GENLOCK: Final = 1 +NV_CTRL_GVO_SYNC_MODE_FRAMELOCK: Final = 2 +NV_CTRL_GVO_SYNC_SOURCE: Final = 69 +NV_CTRL_GVO_SYNC_SOURCE_COMPOSITE: Final = 0 +NV_CTRL_GVO_SYNC_SOURCE_SDI: Final = 1 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT: Final = 70 +NV_CTRL_GVIO_VIDEO_FORMAT_NONE: Final = 0 +NV_CTRL_GVIO_VIDEO_FORMAT_487I_59_94_SMPTE259_NTSC: Final = 1 +NV_CTRL_GVIO_VIDEO_FORMAT_576I_50_00_SMPTE259_PAL: Final = 2 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_59_94_SMPTE296: Final = 3 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_60_00_SMPTE296: Final = 4 +NV_CTRL_GVIO_VIDEO_FORMAT_1035I_59_94_SMPTE260: Final = 5 +NV_CTRL_GVIO_VIDEO_FORMAT_1035I_60_00_SMPTE260: Final = 6 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_SMPTE295: Final = 7 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_SMPTE274: Final = 8 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_59_94_SMPTE274: Final = 9 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_60_00_SMPTE274: Final = 10 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_23_976_SMPTE274: Final = 11 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_24_00_SMPTE274: Final = 12 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_25_00_SMPTE274: Final = 13 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_29_97_SMPTE274: Final = 14 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_30_00_SMPTE274: Final = 15 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_50_00_SMPTE296: Final = 16 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_48_00_SMPTE274: Final = 17 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_47_96_SMPTE274: Final = 18 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_30_00_SMPTE296: Final = 19 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_29_97_SMPTE296: Final = 20 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_25_00_SMPTE296: Final = 21 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_24_00_SMPTE296: Final = 22 +NV_CTRL_GVIO_VIDEO_FORMAT_720P_23_98_SMPTE296: Final = 23 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_25_00_SMPTE274: Final = 24 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_29_97_SMPTE274: Final = 25 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_30_00_SMPTE274: Final = 26 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_24_00_SMPTE274: Final = 27 +NV_CTRL_GVIO_VIDEO_FORMAT_1080PSF_23_98_SMPTE274: Final = 28 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_30_00_SMPTE372: Final = 29 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_29_97_SMPTE372: Final = 30 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_60_00_SMPTE372: Final = 31 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_59_94_SMPTE372: Final = 32 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_25_00_SMPTE372: Final = 33 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_50_00_SMPTE372: Final = 34 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_24_00_SMPTE372: Final = 35 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_23_98_SMPTE372: Final = 36 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_48_00_SMPTE372: Final = 37 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_47_96_SMPTE372: Final = 38 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_50_00_3G_LEVEL_A_SMPTE274: Final = 39 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_59_94_3G_LEVEL_A_SMPTE274: Final = 40 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_60_00_3G_LEVEL_A_SMPTE274: Final = 41 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_60_00_3G_LEVEL_B_SMPTE274: Final = 42 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_60_00_3G_LEVEL_B_SMPTE274: Final = 43 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_60_00_3G_LEVEL_B_SMPTE372: Final = 44 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_50_00_3G_LEVEL_B_SMPTE274: Final = 45 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_50_00_3G_LEVEL_B_SMPTE274: Final = 46 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_50_00_3G_LEVEL_B_SMPTE372: Final = 47 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_30_00_3G_LEVEL_B_SMPTE274: Final = 48 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_30_00_3G_LEVEL_B_SMPTE372: Final = 49 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_25_00_3G_LEVEL_B_SMPTE274: Final = 50 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_25_00_3G_LEVEL_B_SMPTE372: Final = 51 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_24_00_3G_LEVEL_B_SMPTE274: Final = 52 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_24_00_3G_LEVEL_B_SMPTE372: Final = 53 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_48_00_3G_LEVEL_B_SMPTE274: Final = 54 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_48_00_3G_LEVEL_B_SMPTE372: Final = 55 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_59_94_3G_LEVEL_B_SMPTE274: Final = 56 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_59_94_3G_LEVEL_B_SMPTE274: Final = 57 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_59_94_3G_LEVEL_B_SMPTE372: Final = 58 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_29_97_3G_LEVEL_B_SMPTE274: Final = 59 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_29_97_3G_LEVEL_B_SMPTE372: Final = 60 +NV_CTRL_GVIO_VIDEO_FORMAT_1080P_23_98_3G_LEVEL_B_SMPTE274: Final = 61 +NV_CTRL_GVIO_VIDEO_FORMAT_2048P_23_98_3G_LEVEL_B_SMPTE372: Final = 62 +NV_CTRL_GVIO_VIDEO_FORMAT_1080I_47_96_3G_LEVEL_B_SMPTE274: Final = 63 +NV_CTRL_GVIO_VIDEO_FORMAT_2048I_47_96_3G_LEVEL_B_SMPTE372: Final = 64 +NV_CTRL_GVO_OUTPUT_VIDEO_FORMAT: Final = 70 +NV_CTRL_GVO_VIDEO_FORMAT_NONE: Final = 0 +NV_CTRL_GVO_VIDEO_FORMAT_487I_59_94_SMPTE259_NTSC: Final = 1 +NV_CTRL_GVO_VIDEO_FORMAT_576I_50_00_SMPTE259_PAL: Final = 2 +NV_CTRL_GVO_VIDEO_FORMAT_720P_59_94_SMPTE296: Final = 3 +NV_CTRL_GVO_VIDEO_FORMAT_720P_60_00_SMPTE296: Final = 4 +NV_CTRL_GVO_VIDEO_FORMAT_1035I_59_94_SMPTE260: Final = 5 +NV_CTRL_GVO_VIDEO_FORMAT_1035I_60_00_SMPTE260: Final = 6 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_50_00_SMPTE295: Final = 7 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_50_00_SMPTE274: Final = 8 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_59_94_SMPTE274: Final = 9 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_60_00_SMPTE274: Final = 10 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_23_976_SMPTE274: Final = 11 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_24_00_SMPTE274: Final = 12 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_25_00_SMPTE274: Final = 13 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_29_97_SMPTE274: Final = 14 +NV_CTRL_GVO_VIDEO_FORMAT_1080P_30_00_SMPTE274: Final = 15 +NV_CTRL_GVO_VIDEO_FORMAT_720P_50_00_SMPTE296: Final = 16 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_48_00_SMPTE274: Final = 17 +NV_CTRL_GVO_VIDEO_FORMAT_1080I_47_96_SMPTE274: Final = 18 +NV_CTRL_GVO_VIDEO_FORMAT_720P_30_00_SMPTE296: Final = 19 +NV_CTRL_GVO_VIDEO_FORMAT_720P_29_97_SMPTE296: Final = 20 +NV_CTRL_GVO_VIDEO_FORMAT_720P_25_00_SMPTE296: Final = 21 +NV_CTRL_GVO_VIDEO_FORMAT_720P_24_00_SMPTE296: Final = 22 +NV_CTRL_GVO_VIDEO_FORMAT_720P_23_98_SMPTE296: Final = 23 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_25_00_SMPTE274: Final = 24 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_29_97_SMPTE274: Final = 25 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_30_00_SMPTE274: Final = 26 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_24_00_SMPTE274: Final = 27 +NV_CTRL_GVO_VIDEO_FORMAT_1080PSF_23_98_SMPTE274: Final = 28 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_30_00_SMPTE372: Final = 29 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_29_97_SMPTE372: Final = 30 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_60_00_SMPTE372: Final = 31 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_59_94_SMPTE372: Final = 32 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_25_00_SMPTE372: Final = 33 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_50_00_SMPTE372: Final = 34 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_24_00_SMPTE372: Final = 35 +NV_CTRL_GVO_VIDEO_FORMAT_2048P_23_98_SMPTE372: Final = 36 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_48_00_SMPTE372: Final = 37 +NV_CTRL_GVO_VIDEO_FORMAT_2048I_47_96_SMPTE372: Final = 38 +NV_CTRL_GVIO_DETECTED_VIDEO_FORMAT: Final = 71 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT: Final = 71 +NV_CTRL_GVO_DATA_FORMAT: Final = 72 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_YCRCB444: Final = 0 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_YCRCBA4444: Final = 1 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_YCRCBZ4444: Final = 2 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_YCRCB422: Final = 3 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_YCRCBA4224: Final = 4 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_YCRCBZ4224: Final = 5 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8_TO_RGB444: Final = 6 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8_444_PASSTHRU: Final = 6 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8A8_TO_RGBA4444: Final = 7 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8A8_4444_PASSTHRU: Final = 7 +NV_CTRL_GVO_DATA_FORMAT_R8G8B8Z10_TO_RGBZ4444: Final = 8 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8Z8_4444_PASSTHRU: Final = 8 +NV_CTRL_GVO_DATA_FORMAT_Y10CR10CB10_TO_YCRCB444: Final = 9 +NV_CTRL_GVO_DATA_FORMAT_X10X10X10_444_PASSTHRU: Final = 9 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8_TO_YCRCB444: Final = 10 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8_444_PASSTHRU: Final = 10 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8A10_TO_YCRCBA4444: Final = 11 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8A10_4444_PASSTHRU: Final = 11 +NV_CTRL_GVO_DATA_FORMAT_Y10CR8CB8Z10_TO_YCRCBZ4444: Final = 12 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8Z10_4444_PASSTHRU: Final = 12 +NV_CTRL_GVO_DATA_FORMAT_DUAL_R8G8B8_TO_DUAL_YCRCB422: Final = 13 +NV_CTRL_GVO_DATA_FORMAT_DUAL_Y8CR8CB8_TO_DUAL_YCRCB422: Final = 14 +NV_CTRL_GVO_DATA_FORMAT_DUAL_X8X8X8_TO_DUAL_422_PASSTHRU: Final = 14 +NV_CTRL_GVO_DATA_FORMAT_R10G10B10_TO_YCRCB422: Final = 15 +NV_CTRL_GVO_DATA_FORMAT_R10G10B10_TO_YCRCB444: Final = 16 +NV_CTRL_GVO_DATA_FORMAT_Y12CR12CB12_TO_YCRCB444: Final = 17 +NV_CTRL_GVO_DATA_FORMAT_X12X12X12_444_PASSTHRU: Final = 17 +NV_CTRL_GVO_DATA_FORMAT_R12G12B12_TO_YCRCB444: Final = 18 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8_422_PASSTHRU: Final = 19 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8A8_4224_PASSTHRU: Final = 20 +NV_CTRL_GVO_DATA_FORMAT_X8X8X8Z8_4224_PASSTHRU: Final = 21 +NV_CTRL_GVO_DATA_FORMAT_X10X10X10_422_PASSTHRU: Final = 22 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8_422_PASSTHRU: Final = 23 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8A10_4224_PASSTHRU: Final = 24 +NV_CTRL_GVO_DATA_FORMAT_X10X8X8Z10_4224_PASSTHRU: Final = 25 +NV_CTRL_GVO_DATA_FORMAT_X12X12X12_422_PASSTHRU: Final = 26 +NV_CTRL_GVO_DATA_FORMAT_R12G12B12_TO_YCRCB422: Final = 27 +NV_CTRL_GVO_DISPLAY_X_SCREEN: Final = 73 +NV_CTRL_GVO_DISPLAY_X_SCREEN_ENABLE: Final = 1 +NV_CTRL_GVO_DISPLAY_X_SCREEN_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED: Final = 74 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED_FALSE: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECTED_TRUE: Final = 1 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE: Final = 75 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_AUTO: Final = 0 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_BI_LEVEL: Final = 1 +NV_CTRL_GVO_COMPOSITE_SYNC_INPUT_DETECT_MODE_TRI_LEVEL: Final = 2 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED: Final = 76 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_NONE: Final = 0 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_HD: Final = 1 +NV_CTRL_GVO_SDI_SYNC_INPUT_DETECTED_SD: Final = 2 +NV_CTRL_GVO_VIDEO_OUTPUTS: Final = 77 +NV_CTRL_GVO_VIDEO_OUTPUTS_NONE: Final = 0 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO1: Final = 1 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO2: Final = 2 +NV_CTRL_GVO_VIDEO_OUTPUTS_VIDEO_BOTH: Final = 3 +NV_CTRL_GVO_FIRMWARE_VERSION: Final = 78 +NV_CTRL_GVO_SYNC_DELAY_PIXELS: Final = 79 +NV_CTRL_GVO_SYNC_DELAY_LINES: Final = 80 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE: Final = 81 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE_FALSE: Final = 0 +NV_CTRL_GVO_INPUT_VIDEO_FORMAT_REACQUIRE_TRUE: Final = 1 +NV_CTRL_GVO_GLX_LOCKED: Final = 82 +NV_CTRL_GVO_GLX_LOCKED_FALSE: Final = 0 +NV_CTRL_GVO_GLX_LOCKED_TRUE: Final = 1 +NV_CTRL_GVIO_VIDEO_FORMAT_WIDTH: Final = 83 +NV_CTRL_GVIO_VIDEO_FORMAT_HEIGHT: Final = 84 +NV_CTRL_GVIO_VIDEO_FORMAT_REFRESH_RATE: Final = 85 +NV_CTRL_GVO_VIDEO_FORMAT_WIDTH: Final = 83 +NV_CTRL_GVO_VIDEO_FORMAT_HEIGHT: Final = 84 +NV_CTRL_GVO_VIDEO_FORMAT_REFRESH_RATE: Final = 85 +NV_CTRL_GVO_X_SCREEN_PAN_X: Final = 86 +NV_CTRL_GVO_X_SCREEN_PAN_Y: Final = 87 +NV_CTRL_GPU_OVERCLOCKING_STATE: Final = 88 +NV_CTRL_GPU_OVERCLOCKING_STATE_NONE: Final = 0 +NV_CTRL_GPU_OVERCLOCKING_STATE_MANUAL: Final = 1 +NV_CTRL_GPU_2D_CLOCK_FREQS: Final = 89 +NV_CTRL_GPU_3D_CLOCK_FREQS: Final = 90 +NV_CTRL_GPU_DEFAULT_2D_CLOCK_FREQS: Final = 91 +NV_CTRL_GPU_DEFAULT_3D_CLOCK_FREQS: Final = 92 +NV_CTRL_GPU_CURRENT_CLOCK_FREQS: Final = 93 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS: Final = 94 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_INVALID: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION: Final = 95 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_START: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_CANCEL: Final = 1 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE: Final = 96 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE_IDLE: Final = 0 +NV_CTRL_GPU_OPTIMAL_CLOCK_FREQS_DETECTION_STATE_BUSY: Final = 1 +NV_CTRL_FLATPANEL_CHIP_LOCATION: Final = 215 +NV_CTRL_FLATPANEL_CHIP_LOCATION_INTERNAL: Final = 0 +NV_CTRL_FLATPANEL_CHIP_LOCATION_EXTERNAL: Final = 1 +NV_CTRL_FLATPANEL_LINK: Final = 216 +NV_CTRL_FLATPANEL_LINK_SINGLE: Final = 0 +NV_CTRL_FLATPANEL_LINK_DUAL: Final = 1 +NV_CTRL_FLATPANEL_LINK_QUAD: Final = 3 +NV_CTRL_FLATPANEL_SIGNAL: Final = 217 +NV_CTRL_FLATPANEL_SIGNAL_LVDS: Final = 0 +NV_CTRL_FLATPANEL_SIGNAL_TMDS: Final = 1 +NV_CTRL_FLATPANEL_SIGNAL_DISPLAYPORT: Final = 2 +NV_CTRL_USE_HOUSE_SYNC: Final = 218 +NV_CTRL_USE_HOUSE_SYNC_DISABLED: Final = 0 +NV_CTRL_USE_HOUSE_SYNC_INPUT: Final = 1 +NV_CTRL_USE_HOUSE_SYNC_OUTPUT: Final = 2 +NV_CTRL_USE_HOUSE_SYNC_FALSE: Final = 0 +NV_CTRL_USE_HOUSE_SYNC_TRUE: Final = 1 +NV_CTRL_EDID_AVAILABLE: Final = 219 +NV_CTRL_EDID_AVAILABLE_FALSE: Final = 0 +NV_CTRL_EDID_AVAILABLE_TRUE: Final = 1 +NV_CTRL_FORCE_STEREO: Final = 220 +NV_CTRL_FORCE_STEREO_FALSE: Final = 0 +NV_CTRL_FORCE_STEREO_TRUE: Final = 1 +NV_CTRL_IMAGE_SETTINGS: Final = 221 +NV_CTRL_IMAGE_SETTINGS_HIGH_QUALITY: Final = 0 +NV_CTRL_IMAGE_SETTINGS_QUALITY: Final = 1 +NV_CTRL_IMAGE_SETTINGS_PERFORMANCE: Final = 2 +NV_CTRL_IMAGE_SETTINGS_HIGH_PERFORMANCE: Final = 3 +NV_CTRL_XINERAMA: Final = 222 +NV_CTRL_XINERAMA_OFF: Final = 0 +NV_CTRL_XINERAMA_ON: Final = 1 +NV_CTRL_XINERAMA_STEREO: Final = 223 +NV_CTRL_XINERAMA_STEREO_FALSE: Final = 0 +NV_CTRL_XINERAMA_STEREO_TRUE: Final = 1 +NV_CTRL_BUS_RATE: Final = 224 +NV_CTRL_GPU_PCIE_MAX_LINK_WIDTH: Final = NV_CTRL_BUS_RATE +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR: Final = 225 +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_SHOW_SLI_HUD: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR +NV_CTRL_SHOW_SLI_HUD_FALSE: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_FALSE +NV_CTRL_SHOW_SLI_HUD_TRUE: Final = NV_CTRL_SHOW_SLI_VISUAL_INDICATOR_TRUE +NV_CTRL_XV_SYNC_TO_DISPLAY: Final = 226 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT2: Final = 227 +NV_CTRL_GVO_OUTPUT_VIDEO_FORMAT2: Final = 227 +NV_CTRL_GVO_OVERRIDE_HW_CSC: Final = 228 +NV_CTRL_GVO_OVERRIDE_HW_CSC_FALSE: Final = 0 +NV_CTRL_GVO_OVERRIDE_HW_CSC_TRUE: Final = 1 +NV_CTRL_GVO_CAPABILITIES: Final = 229 +NV_CTRL_GVO_CAPABILITIES_APPLY_CSC_IMMEDIATELY: Final = 0x00000001 +NV_CTRL_GVO_CAPABILITIES_APPLY_CSC_TO_X_SCREEN: Final = 0x00000002 +NV_CTRL_GVO_CAPABILITIES_COMPOSITE_TERMINATION: Final = 0x00000004 +NV_CTRL_GVO_CAPABILITIES_SHARED_SYNC_BNC: Final = 0x00000008 +NV_CTRL_GVO_CAPABILITIES_MULTIRATE_SYNC: Final = 0x00000010 +NV_CTRL_GVO_CAPABILITIES_ADVANCE_SYNC_SKEW: Final = 0x00000020 +NV_CTRL_GVO_COMPOSITE_TERMINATION: Final = 230 +NV_CTRL_GVO_COMPOSITE_TERMINATION_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_TERMINATION_DISABLE: Final = 0 +NV_CTRL_ASSOCIATED_DISPLAY_DEVICES: Final = 231 +NV_CTRL_FRAMELOCK_SLAVES: Final = 232 +NV_CTRL_FRAMELOCK_MASTERABLE: Final = 233 +NV_CTRL_PROBE_DISPLAYS: Final = 234 +NV_CTRL_REFRESH_RATE: Final = 235 +NV_CTRL_GVO_FLIP_QUEUE_SIZE: Final = 236 +NV_CTRL_CURRENT_SCANLINE: Final = 237 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT: Final = 238 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_FORCE_SYSMEM: Final = 0 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_SYSMEM: Final = 1 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_VIDMEM: Final = 2 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_RESERVED: Final = 3 +NV_CTRL_INITIAL_PIXMAP_PLACEMENT_GPU_SYSMEM: Final = 4 +NV_CTRL_PCI_BUS: Final = 239 +NV_CTRL_PCI_DEVICE: Final = 240 +NV_CTRL_PCI_FUNCTION: Final = 241 +NV_CTRL_FRAMELOCK_FPGA_REVISION: Final = 242 +NV_CTRL_MAX_SCREEN_WIDTH: Final = 243 +NV_CTRL_MAX_SCREEN_HEIGHT: Final = 244 +NV_CTRL_MAX_DISPLAYS: Final = 245 +NV_CTRL_DYNAMIC_TWINVIEW: Final = 246 +NV_CTRL_MULTIGPU_DISPLAY_OWNER: Final = 247 +NV_CTRL_GPU_SCALING: Final = 248 +NV_CTRL_GPU_SCALING_TARGET_INVALID: Final = 0 +NV_CTRL_GPU_SCALING_TARGET_FLATPANEL_BEST_FIT: Final = 1 +NV_CTRL_GPU_SCALING_TARGET_FLATPANEL_NATIVE: Final = 2 +NV_CTRL_GPU_SCALING_METHOD_INVALID: Final = 0 +NV_CTRL_GPU_SCALING_METHOD_STRETCHED: Final = 1 +NV_CTRL_GPU_SCALING_METHOD_CENTERED: Final = 2 +NV_CTRL_GPU_SCALING_METHOD_ASPECT_SCALED: Final = 3 +NV_CTRL_FRONTEND_RESOLUTION: Final = 249 +NV_CTRL_BACKEND_RESOLUTION: Final = 250 +NV_CTRL_FLATPANEL_NATIVE_RESOLUTION: Final = 251 +NV_CTRL_FLATPANEL_BEST_FIT_RESOLUTION: Final = 252 +NV_CTRL_GPU_SCALING_ACTIVE: Final = 253 +NV_CTRL_DFP_SCALING_ACTIVE: Final = 254 +NV_CTRL_FSAA_APPLICATION_ENHANCED: Final = 255 +NV_CTRL_FSAA_APPLICATION_ENHANCED_ENABLED: Final = 1 +NV_CTRL_FSAA_APPLICATION_ENHANCED_DISABLED: Final = 0 +NV_CTRL_FRAMELOCK_SYNC_RATE_4: Final = 256 +NV_CTRL_GVO_LOCK_OWNER: Final = 257 +NV_CTRL_GVO_LOCK_OWNER_NONE: Final = 0 +NV_CTRL_GVO_LOCK_OWNER_GLX: Final = 1 +NV_CTRL_GVO_LOCK_OWNER_CLONE: Final = 2 +NV_CTRL_GVO_LOCK_OWNER_X_SCREEN: Final = 3 +NV_CTRL_HWOVERLAY: Final = 258 +NV_CTRL_HWOVERLAY_FALSE: Final = 0 +NV_CTRL_HWOVERLAY_TRUE: Final = 1 +NV_CTRL_NUM_GPU_ERRORS_RECOVERED: Final = 259 +NV_CTRL_REFRESH_RATE_3: Final = 260 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS: Final = 261 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS_OFF: Final = 0 +NV_CTRL_ONDEMAND_VBLANK_INTERRUPTS_ON: Final = 1 +NV_CTRL_GPU_POWER_SOURCE: Final = 262 +NV_CTRL_GPU_POWER_SOURCE_AC: Final = 0 +NV_CTRL_GPU_POWER_SOURCE_BATTERY: Final = 1 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE: Final = 263 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE_DESKTOP: Final = 0 +NV_CTRL_GPU_CURRENT_PERFORMANCE_MODE_MAXPERF: Final = 1 +NV_CTRL_GLYPH_CACHE: Final = 264 +NV_CTRL_GLYPH_CACHE_DISABLED: Final = 0 +NV_CTRL_GLYPH_CACHE_ENABLED: Final = 1 +NV_CTRL_GPU_CURRENT_PERFORMANCE_LEVEL: Final = 265 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE: Final = 266 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE_DISABLED: Final = 0 +NV_CTRL_GPU_ADAPTIVE_CLOCK_STATE_ENABLED: Final = 1 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED: Final = 267 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED_FALSE: Final = 0 +NV_CTRL_GVO_OUTPUT_VIDEO_LOCKED_TRUE: Final = 1 +NV_CTRL_GVO_SYNC_LOCK_STATUS: Final = 268 +NV_CTRL_GVO_SYNC_LOCK_STATUS_UNLOCKED: Final = 0 +NV_CTRL_GVO_SYNC_LOCK_STATUS_LOCKED: Final = 1 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION: Final = 269 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION_DISABLE: Final = 0 +NV_CTRL_GVO_ANC_TIME_CODE_GENERATION_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE: Final = 270 +NV_CTRL_GVO_COMPOSITE_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY: Final = 271 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY_DISABLE: Final = 0 +NV_CTRL_GVO_COMPOSITE_ALPHA_KEY_ENABLE: Final = 1 +NV_CTRL_GVO_COMPOSITE_LUMA_KEY_RANGE: Final = 272 +NV_CTRL_GVO_COMPOSITE_CR_KEY_RANGE: Final = 273 +NV_CTRL_GVO_COMPOSITE_CB_KEY_RANGE: Final = 274 +NV_CTRL_GVO_COMPOSITE_NUM_KEY_RANGES: Final = 275 +NV_CTRL_SWITCH_TO_DISPLAYS: Final = 276 +NV_CTRL_NOTEBOOK_DISPLAY_CHANGE_LID_EVENT: Final = 277 +NV_CTRL_NOTEBOOK_INTERNAL_LCD: Final = 278 +NV_CTRL_DEPTH_30_ALLOWED: Final = 279 +NV_CTRL_MODE_SET_EVENT: Final = 280 +NV_CTRL_OPENGL_AA_LINE_GAMMA_VALUE: Final = 281 +NV_CTRL_VCSC_HIGH_PERF_MODE: Final = 282 +NV_CTRL_VCSC_HIGH_PERF_MODE_DISABLE: Final = 0 +NV_CTRL_VCSC_HIGH_PERF_MODE_ENABLE: Final = 1 +NV_CTRL_DISPLAYPORT_LINK_RATE: Final = 291 +NV_CTRL_DISPLAYPORT_LINK_RATE_DISABLED: Final = 0x0 +NV_CTRL_DISPLAYPORT_LINK_RATE_1_62GBPS: Final = 0x6 +NV_CTRL_DISPLAYPORT_LINK_RATE_2_70GBPS: Final = 0xA +NV_CTRL_STEREO_EYES_EXCHANGE: Final = 292 +NV_CTRL_STEREO_EYES_EXCHANGE_OFF: Final = 0 +NV_CTRL_STEREO_EYES_EXCHANGE_ON: Final = 1 +NV_CTRL_NO_SCANOUT: Final = 293 +NV_CTRL_NO_SCANOUT_DISABLED: Final = 0 +NV_CTRL_NO_SCANOUT_ENABLED: Final = 1 +NV_CTRL_GVO_CSC_CHANGED_EVENT: Final = 294 +NV_CTRL_FRAMELOCK_SLAVEABLE: Final = 295 +NV_CTRL_GVO_SYNC_TO_DISPLAY: Final = 296 +NV_CTRL_GVO_SYNC_TO_DISPLAY_DISABLE: Final = 0 +NV_CTRL_GVO_SYNC_TO_DISPLAY_ENABLE: Final = 1 +NV_CTRL_X_SERVER_UNIQUE_ID: Final = 297 +NV_CTRL_PIXMAP_CACHE: Final = 298 +NV_CTRL_PIXMAP_CACHE_DISABLE: Final = 0 +NV_CTRL_PIXMAP_CACHE_ENABLE: Final = 1 +NV_CTRL_PIXMAP_CACHE_ROUNDING_SIZE_KB: Final = 299 +NV_CTRL_IS_GVO_DISPLAY: Final = 300 +NV_CTRL_IS_GVO_DISPLAY_FALSE: Final = 0 +NV_CTRL_IS_GVO_DISPLAY_TRUE: Final = 1 +NV_CTRL_PCI_ID: Final = 301 +NV_CTRL_GVO_FULL_RANGE_COLOR: Final = 302 +NV_CTRL_GVO_FULL_RANGE_COLOR_DISABLED: Final = 0 +NV_CTRL_GVO_FULL_RANGE_COLOR_ENABLED: Final = 1 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE: Final = 303 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE_FALSE: Final = 0 +NV_CTRL_SLI_MOSAIC_MODE_AVAILABLE_TRUE: Final = 1 +NV_CTRL_GVO_ENABLE_RGB_DATA: Final = 304 +NV_CTRL_GVO_ENABLE_RGB_DATA_DISABLE: Final = 0 +NV_CTRL_GVO_ENABLE_RGB_DATA_ENABLE: Final = 1 +NV_CTRL_IMAGE_SHARPENING_DEFAULT: Final = 305 +NV_CTRL_PCI_DOMAIN: Final = 306 +NV_CTRL_GVI_NUM_JACKS: Final = 307 +NV_CTRL_GVI_MAX_LINKS_PER_STREAM: Final = 308 +NV_CTRL_GVI_DETECTED_CHANNEL_BITS_PER_COMPONENT: Final = 309 +NV_CTRL_GVI_BITS_PER_COMPONENT_UNKNOWN: Final = 0 +NV_CTRL_GVI_BITS_PER_COMPONENT_8: Final = 1 +NV_CTRL_GVI_BITS_PER_COMPONENT_10: Final = 2 +NV_CTRL_GVI_BITS_PER_COMPONENT_12: Final = 3 +NV_CTRL_GVI_REQUESTED_STREAM_BITS_PER_COMPONENT: Final = 310 +NV_CTRL_GVI_DETECTED_CHANNEL_COMPONENT_SAMPLING: Final = 311 +NV_CTRL_GVI_COMPONENT_SAMPLING_UNKNOWN: Final = 0 +NV_CTRL_GVI_COMPONENT_SAMPLING_4444: Final = 1 +NV_CTRL_GVI_COMPONENT_SAMPLING_4224: Final = 2 +NV_CTRL_GVI_COMPONENT_SAMPLING_444: Final = 3 +NV_CTRL_GVI_COMPONENT_SAMPLING_422: Final = 4 +NV_CTRL_GVI_COMPONENT_SAMPLING_420: Final = 5 +NV_CTRL_GVI_REQUESTED_STREAM_COMPONENT_SAMPLING: Final = 312 +NV_CTRL_GVI_REQUESTED_STREAM_CHROMA_EXPAND: Final = 313 +NV_CTRL_GVI_CHROMA_EXPAND_FALSE: Final = 0 +NV_CTRL_GVI_CHROMA_EXPAND_TRUE: Final = 1 +NV_CTRL_GVI_DETECTED_CHANNEL_COLOR_SPACE: Final = 314 +NV_CTRL_GVI_COLOR_SPACE_UNKNOWN: Final = 0 +NV_CTRL_GVI_COLOR_SPACE_GBR: Final = 1 +NV_CTRL_GVI_COLOR_SPACE_GBRA: Final = 2 +NV_CTRL_GVI_COLOR_SPACE_GBRD: Final = 3 +NV_CTRL_GVI_COLOR_SPACE_YCBCR: Final = 4 +NV_CTRL_GVI_COLOR_SPACE_YCBCRA: Final = 5 +NV_CTRL_GVI_COLOR_SPACE_YCBCRD: Final = 6 +NV_CTRL_GVI_DETECTED_CHANNEL_LINK_ID: Final = 315 +NV_CTRL_GVI_LINK_ID_UNKNOWN: Final = 0xFFFF +NV_CTRL_GVI_DETECTED_CHANNEL_SMPTE352_IDENTIFIER: Final = 316 +NV_CTRL_GVI_GLOBAL_IDENTIFIER: Final = 317 +NV_CTRL_FRAMELOCK_SYNC_DELAY_RESOLUTION: Final = 318 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL: Final = 319 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL_FALSE: Final = 0 +NV_CTRL_GPU_COOLER_MANUAL_CONTROL_TRUE: Final = 1 +NV_CTRL_THERMAL_COOLER_LEVEL: Final = 320 +NV_CTRL_THERMAL_COOLER_LEVEL_SET_DEFAULT: Final = 321 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE: Final = 322 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_NONE: Final = 0 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_TOGGLE: Final = 1 +NV_CTRL_THERMAL_COOLER_CONTROL_TYPE_VARIABLE: Final = 2 +NV_CTRL_THERMAL_COOLER_TARGET: Final = 323 +NV_CTRL_THERMAL_COOLER_TARGET_NONE: Final = 0 +NV_CTRL_THERMAL_COOLER_TARGET_GPU: Final = 1 +NV_CTRL_THERMAL_COOLER_TARGET_MEMORY: Final = 2 +NV_CTRL_THERMAL_COOLER_TARGET_POWER_SUPPLY: Final = 4 +NV_CTRL_THERMAL_COOLER_TARGET_GPU_RELATED: Final = 7 +NV_CTRL_GPU_ECC_SUPPORTED: Final = 324 +NV_CTRL_GPU_ECC_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_ECC_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GPU_ECC_STATUS: Final = 325 +NV_CTRL_GPU_ECC_STATUS_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_STATUS_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED: Final = 326 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_ECC_CONFIGURATION_SUPPORTED_TRUE: Final = 1 +NV_CTRL_GPU_ECC_CONFIGURATION: Final = 327 +NV_CTRL_GPU_ECC_CONFIGURATION_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_CONFIGURATION_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION: Final = 328 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION_DISABLED: Final = 0 +NV_CTRL_GPU_ECC_DEFAULT_CONFIGURATION_ENABLED: Final = 1 +NV_CTRL_GPU_ECC_SINGLE_BIT_ERRORS: Final = 329 +NV_CTRL_GPU_ECC_DOUBLE_BIT_ERRORS: Final = 330 +NV_CTRL_GPU_ECC_AGGREGATE_SINGLE_BIT_ERRORS: Final = 331 +NV_CTRL_GPU_ECC_AGGREGATE_DOUBLE_BIT_ERRORS: Final = 332 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS: Final = 333 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS_VOLATILE: Final = 0x00000001 +NV_CTRL_GPU_ECC_RESET_ERROR_STATUS_AGGREGATE: Final = 0x00000002 +NV_CTRL_GPU_POWER_MIZER_MODE: Final = 334 +NV_CTRL_GPU_POWER_MIZER_MODE_ADAPTIVE: Final = 0 +NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE: Final = 1 +NV_CTRL_GPU_POWER_MIZER_MODE_AUTO: Final = 2 +NV_CTRL_GPU_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE: Final = 3 +NV_CTRL_GVI_SYNC_OUTPUT_FORMAT: Final = 335 +NV_CTRL_GVI_MAX_CHANNELS_PER_JACK: Final = 336 +NV_CTRL_GVI_MAX_STREAMS: Final = 337 +NV_CTRL_GVI_NUM_CAPTURE_SURFACES: Final = 338 +NV_CTRL_OVERSCAN_COMPENSATION: Final = 339 +NV_CTRL_GPU_PCIE_GENERATION: Final = 341 +NV_CTRL_GPU_PCIE_GENERATION1: Final = 0x00000001 +NV_CTRL_GPU_PCIE_GENERATION2: Final = 0x00000002 +NV_CTRL_GPU_PCIE_GENERATION3: Final = 0x00000003 +NV_CTRL_GVI_BOUND_GPU: Final = 342 +NV_CTRL_GVIO_REQUESTED_VIDEO_FORMAT3: Final = 343 +NV_CTRL_ACCELERATE_TRAPEZOIDS: Final = 344 +NV_CTRL_ACCELERATE_TRAPEZOIDS_DISABLE: Final = 0 +NV_CTRL_ACCELERATE_TRAPEZOIDS_ENABLE: Final = 1 +NV_CTRL_GPU_CORES: Final = 345 +NV_CTRL_GPU_MEMORY_BUS_WIDTH: Final = 346 +NV_CTRL_GVI_TEST_MODE: Final = 347 +NV_CTRL_GVI_TEST_MODE_DISABLE: Final = 0 +NV_CTRL_GVI_TEST_MODE_ENABLE: Final = 1 +NV_CTRL_COLOR_SPACE: Final = 348 +NV_CTRL_COLOR_SPACE_RGB: Final = 0 +NV_CTRL_COLOR_SPACE_YCbCr422: Final = 1 +NV_CTRL_COLOR_SPACE_YCbCr444: Final = 2 +NV_CTRL_COLOR_RANGE: Final = 349 +NV_CTRL_COLOR_RANGE_FULL: Final = 0 +NV_CTRL_COLOR_RANGE_LIMITED: Final = 1 +NV_CTRL_GPU_SCALING_DEFAULT_TARGET: Final = 350 +NV_CTRL_GPU_SCALING_DEFAULT_METHOD: Final = 351 +NV_CTRL_DITHERING_MODE: Final = 352 +NV_CTRL_DITHERING_MODE_AUTO: Final = 0 +NV_CTRL_DITHERING_MODE_DYNAMIC_2X2: Final = 1 +NV_CTRL_DITHERING_MODE_STATIC_2X2: Final = 2 +NV_CTRL_DITHERING_MODE_TEMPORAL: Final = 3 +NV_CTRL_CURRENT_DITHERING: Final = 353 +NV_CTRL_CURRENT_DITHERING_DISABLED: Final = 0 +NV_CTRL_CURRENT_DITHERING_ENABLED: Final = 1 +NV_CTRL_CURRENT_DITHERING_MODE: Final = 354 +NV_CTRL_CURRENT_DITHERING_MODE_NONE: Final = 0 +NV_CTRL_CURRENT_DITHERING_MODE_DYNAMIC_2X2: Final = 1 +NV_CTRL_CURRENT_DITHERING_MODE_STATIC_2X2: Final = 2 +NV_CTRL_CURRENT_DITHERING_MODE_TEMPORAL: Final = 3 +NV_CTRL_THERMAL_SENSOR_READING: Final = 355 +NV_CTRL_THERMAL_SENSOR_PROVIDER: Final = 356 +NV_CTRL_THERMAL_SENSOR_PROVIDER_NONE: Final = 0 +NV_CTRL_THERMAL_SENSOR_PROVIDER_GPU_INTERNAL: Final = 1 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADM1032: Final = 2 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADT7461: Final = 3 +NV_CTRL_THERMAL_SENSOR_PROVIDER_MAX6649: Final = 4 +NV_CTRL_THERMAL_SENSOR_PROVIDER_MAX1617: Final = 5 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM99: Final = 6 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM89: Final = 7 +NV_CTRL_THERMAL_SENSOR_PROVIDER_LM64: Final = 8 +NV_CTRL_THERMAL_SENSOR_PROVIDER_G781: Final = 9 +NV_CTRL_THERMAL_SENSOR_PROVIDER_ADT7473: Final = 10 +NV_CTRL_THERMAL_SENSOR_PROVIDER_SBMAX6649: Final = 11 +NV_CTRL_THERMAL_SENSOR_PROVIDER_VBIOSEVT: Final = 12 +NV_CTRL_THERMAL_SENSOR_PROVIDER_OS: Final = 13 +NV_CTRL_THERMAL_SENSOR_PROVIDER_UNKNOWN: Final = 0xFFFFFFFF +NV_CTRL_THERMAL_SENSOR_TARGET: Final = 357 +NV_CTRL_THERMAL_SENSOR_TARGET_NONE: Final = 0 +NV_CTRL_THERMAL_SENSOR_TARGET_GPU: Final = 1 +NV_CTRL_THERMAL_SENSOR_TARGET_MEMORY: Final = 2 +NV_CTRL_THERMAL_SENSOR_TARGET_POWER_SUPPLY: Final = 4 +NV_CTRL_THERMAL_SENSOR_TARGET_BOARD: Final = 8 +NV_CTRL_THERMAL_SENSOR_TARGET_UNKNOWN: Final = 0xFFFFFFFF +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR: Final = 358 +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_MULTIGPU_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_GPU_CURRENT_PROCESSOR_CLOCK_FREQS: Final = 359 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS: Final = 360 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_NONE: Final = 0x00000000 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_INTERLACED: Final = 0x00000001 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_PROGRESSIVE: Final = 0x00000002 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_PSF: Final = 0x00000004 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_LEVEL_A: Final = 0x00000008 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_LEVEL_B: Final = 0x00000010 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G: Final = 24 +NV_CTRL_GVIO_VIDEO_FORMAT_FLAGS_3G_1080P_NO_12BPC: Final = 0x00000020 +NV_CTRL_GPU_PCIE_MAX_LINK_SPEED: Final = 361 +NV_CTRL_3D_VISION_PRO_RESET_TRANSCEIVER_TO_FACTORY_SETTINGS: Final = 363 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL: Final = 364 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE: Final = 365 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_INVALID: Final = 0 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_LOW_RANGE: Final = 1 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_MEDIUM_RANGE: Final = 2 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_HIGH_RANGE: Final = 3 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_MODE_COUNT: Final = 4 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES: Final = 367 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES_DISABLE: Final = 0 +NV_CTRL_SYNCHRONOUS_PALETTE_UPDATES_ENABLE: Final = 1 +NV_CTRL_DITHERING_DEPTH: Final = 368 +NV_CTRL_DITHERING_DEPTH_AUTO: Final = 0 +NV_CTRL_DITHERING_DEPTH_6_BITS: Final = 1 +NV_CTRL_DITHERING_DEPTH_8_BITS: Final = 2 +NV_CTRL_CURRENT_DITHERING_DEPTH: Final = 369 +NV_CTRL_CURRENT_DITHERING_DEPTH_NONE: Final = 0 +NV_CTRL_CURRENT_DITHERING_DEPTH_6_BITS: Final = 1 +NV_CTRL_CURRENT_DITHERING_DEPTH_8_BITS: Final = 2 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_FREQUENCY: Final = 370 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_QUALITY: Final = 371 +NV_CTRL_3D_VISION_PRO_TRANSCEIVER_CHANNEL_COUNT: Final = 372 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES: Final = 373 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES_STOP: Final = 0 +NV_CTRL_3D_VISION_PRO_PAIR_GLASSES_BEACON: Final = 0xFFFFFFFF +NV_CTRL_3D_VISION_PRO_UNPAIR_GLASSES: Final = 374 +NV_CTRL_3D_VISION_PRO_DISCOVER_GLASSES: Final = 375 +NV_CTRL_3D_VISION_PRO_IDENTIFY_GLASSES: Final = 376 +NV_CTRL_3D_VISION_PRO_GLASSES_SYNC_CYCLE: Final = 378 +NV_CTRL_3D_VISION_PRO_GLASSES_MISSED_SYNC_CYCLES: Final = 379 +NV_CTRL_3D_VISION_PRO_GLASSES_BATTERY_LEVEL: Final = 380 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION: Final = 381 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_AUTO: Final = 0 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_ON: Final = 1 +NV_CTRL_GVO_ANC_PARITY_COMPUTATION_OFF: Final = 2 +NV_CTRL_3D_VISION_PRO_GLASSES_PAIR_EVENT: Final = 382 +NV_CTRL_3D_VISION_PRO_GLASSES_UNPAIR_EVENT: Final = 383 +NV_CTRL_GPU_PCIE_CURRENT_LINK_WIDTH: Final = 384 +NV_CTRL_GPU_PCIE_CURRENT_LINK_SPEED: Final = 385 +NV_CTRL_GVO_AUDIO_BLANKING: Final = 386 +NV_CTRL_GVO_AUDIO_BLANKING_DISABLE: Final = 0 +NV_CTRL_GVO_AUDIO_BLANKING_ENABLE: Final = 1 +NV_CTRL_CURRENT_METAMODE_ID: Final = 387 +NV_CTRL_DISPLAY_ENABLED: Final = 388 +NV_CTRL_DISPLAY_ENABLED_TRUE: Final = 1 +NV_CTRL_DISPLAY_ENABLED_FALSE: Final = 0 +NV_CTRL_FRAMELOCK_INCOMING_HOUSE_SYNC_RATE: Final = 389 +NV_CTRL_FXAA: Final = 390 +NV_CTRL_FXAA_DISABLE: Final = 0 +NV_CTRL_FXAA_ENABLE: Final = 1 +NV_CTRL_DISPLAY_RANDR_OUTPUT_ID: Final = 391 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG: Final = 392 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_DISABLED: Final = 0 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_CLIENT: Final = 1 +NV_CTRL_FRAMELOCK_DISPLAY_CONFIG_SERVER: Final = 2 +NV_CTRL_TOTAL_DEDICATED_GPU_MEMORY: Final = 393 +NV_CTRL_USED_DEDICATED_GPU_MEMORY: Final = 394 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE: Final = 395 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE_DISABLED: Final = 0 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_IMMEDIATE_ENABLED: Final = 1 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT: Final = 396 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT_DISABLED: Final = 0 +NV_CTRL_GPU_DOUBLE_PRECISION_BOOST_REBOOT_ENALED: Final = 1 +NV_CTRL_DPY_HDMI_3D: Final = 397 +NV_CTRL_DPY_HDMI_3D_DISABLED: Final = 0 +NV_CTRL_DPY_HDMI_3D_ENABLED: Final = 1 +NV_CTRL_BASE_MOSAIC: Final = 398 +NV_CTRL_BASE_MOSAIC_DISABLED: Final = 0 +NV_CTRL_BASE_MOSAIC_FULL: Final = 1 +NV_CTRL_BASE_MOSAIC_LIMITED: Final = 2 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE: Final = 399 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE_FALSE: Final = 0 +NV_CTRL_MULTIGPU_MASTER_POSSIBLE_TRUE: Final = 1 +NV_CTRL_GPU_POWER_MIZER_DEFAULT_MODE: Final = 400 +NV_CTRL_XV_SYNC_TO_DISPLAY_ID: Final = 401 +NV_CTRL_XV_SYNC_TO_DISPLAY_ID_AUTO: Final = 0xFFFFFFFF +NV_CTRL_BACKLIGHT_BRIGHTNESS: Final = 402 +NV_CTRL_GPU_LOGO_BRIGHTNESS: Final = 403 +NV_CTRL_GPU_SLI_LOGO_BRIGHTNESS: Final = 404 +NV_CTRL_THERMAL_COOLER_SPEED: Final = 405 +NV_CTRL_PALETTE_UPDATE_EVENT: Final = 406 +NV_CTRL_VIDEO_ENCODER_UTILIZATION: Final = 407 +NV_CTRL_GSYNC_ALLOWED: Final = 408 +NV_CTRL_GSYNC_ALLOWED_FALSE: Final = 0 +NV_CTRL_GSYNC_ALLOWED_TRUE: Final = 1 +NV_CTRL_GPU_NVCLOCK_OFFSET: Final = 409 +NV_CTRL_GPU_MEM_TRANSFER_RATE_OFFSET: Final = 410 +NV_CTRL_VIDEO_DECODER_UTILIZATION: Final = 411 +NV_CTRL_GPU_OVER_VOLTAGE_OFFSET: Final = 412 +NV_CTRL_GPU_CURRENT_CORE_VOLTAGE: Final = 413 +NV_CTRL_CURRENT_COLOR_SPACE: Final = 414 +NV_CTRL_CURRENT_COLOR_SPACE_RGB: Final = 0 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr422: Final = 1 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr444: Final = 2 +NV_CTRL_CURRENT_COLOR_SPACE_YCbCr420: Final = 3 +NV_CTRL_CURRENT_COLOR_RANGE: Final = 415 +NV_CTRL_CURRENT_COLOR_RANGE_FULL: Final = 0 +NV_CTRL_CURRENT_COLOR_RANGE_LIMITED: Final = 1 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR: Final = 416 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_GSYNC_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_THERMAL_COOLER_CURRENT_LEVEL: Final = 417 +NV_CTRL_STEREO_SWAP_MODE: Final = 418 +NV_CTRL_STEREO_SWAP_MODE_APPLICATION_CONTROL: Final = 0 +NV_CTRL_STEREO_SWAP_MODE_PER_EYE: Final = 1 +NV_CTRL_STEREO_SWAP_MODE_PER_EYE_PAIR: Final = 2 +NV_CTRL_CURRENT_XV_SYNC_TO_DISPLAY_ID: Final = 419 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED: Final = 420 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED_FALSE: Final = 0 +NV_CTRL_GPU_FRAMELOCK_FIRMWARE_UNSUPPORTED_TRUE: Final = 1 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE: Final = 421 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_UNKNOWN: Final = 0 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_DISPLAYPORT: Final = 1 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_HDMI: Final = 2 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_DVI: Final = 3 +NV_CTRL_DISPLAYPORT_CONNECTOR_TYPE_VGA: Final = 4 +NV_CTRL_DISPLAYPORT_IS_MULTISTREAM: Final = 422 +NV_CTRL_DISPLAYPORT_SINK_IS_AUDIO_CAPABLE: Final = 423 +NV_CTRL_GPU_NVCLOCK_OFFSET_ALL_PERFORMANCE_LEVELS: Final = 424 +NV_CTRL_GPU_MEM_TRANSFER_RATE_OFFSET_ALL_PERFORMANCE_LEVELS: Final = 425 +NV_CTRL_FRAMELOCK_FIRMWARE_VERSION: Final = 426 +NV_CTRL_FRAMELOCK_FIRMWARE_MINOR_VERSION: Final = 427 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR: Final = 428 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR_FALSE: Final = 0 +NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR_TRUE: Final = 1 +NV_CTRL_LAST_ATTRIBUTE: Final = NV_CTRL_SHOW_GRAPHICS_VISUAL_INDICATOR +NV_CTRL_STRING_PRODUCT_NAME: Final = 0 +NV_CTRL_STRING_VBIOS_VERSION: Final = 1 +NV_CTRL_STRING_NVIDIA_DRIVER_VERSION: Final = 3 +NV_CTRL_STRING_DISPLAY_DEVICE_NAME: Final = 4 +NV_CTRL_STRING_TV_ENCODER_NAME: Final = 5 +NV_CTRL_STRING_GVIO_FIRMWARE_VERSION: Final = 8 +NV_CTRL_STRING_GVO_FIRMWARE_VERSION: Final = 8 +NV_CTRL_STRING_CURRENT_MODELINE: Final = 9 +NV_CTRL_STRING_ADD_MODELINE: Final = 10 +NV_CTRL_STRING_DELETE_MODELINE: Final = 11 +NV_CTRL_STRING_CURRENT_METAMODE: Final = 12 +NV_CTRL_STRING_CURRENT_METAMODE_VERSION_1: Final = NV_CTRL_STRING_CURRENT_METAMODE +NV_CTRL_STRING_ADD_METAMODE: Final = 13 +NV_CTRL_STRING_DELETE_METAMODE: Final = 14 +NV_CTRL_STRING_VCSC_PRODUCT_NAME: Final = 15 +NV_CTRL_STRING_VCSC_PRODUCT_ID: Final = 16 +NV_CTRL_STRING_VCSC_SERIAL_NUMBER: Final = 17 +NV_CTRL_STRING_VCSC_BUILD_DATE: Final = 18 +NV_CTRL_STRING_VCSC_FIRMWARE_VERSION: Final = 19 +NV_CTRL_STRING_VCSC_FIRMWARE_REVISION: Final = 20 +NV_CTRL_STRING_VCSC_HARDWARE_VERSION: Final = 21 +NV_CTRL_STRING_VCSC_HARDWARE_REVISION: Final = 22 +NV_CTRL_STRING_MOVE_METAMODE: Final = 23 +NV_CTRL_STRING_VALID_HORIZ_SYNC_RANGES: Final = 24 +NV_CTRL_STRING_VALID_VERT_REFRESH_RANGES: Final = 25 +NV_CTRL_STRING_SCREEN_RECTANGLE: Final = 26 +NV_CTRL_STRING_XINERAMA_SCREEN_INFO: Final = 26 +NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER: Final = 27 +NV_CTRL_STRING_TWINVIEW_XINERAMA_INFO_ORDER: Final = NV_CTRL_STRING_NVIDIA_XINERAMA_INFO_ORDER +NV_CTRL_STRING_SLI_MODE: Final = 28 +NV_CTRL_STRING_PERFORMANCE_MODES: Final = 29 +NV_CTRL_STRING_VCSC_FAN_STATUS: Final = 30 +NV_CTRL_STRING_VCSC_TEMPERATURES: Final = 31 +NV_CTRL_STRING_VCSC_PSU_INFO: Final = 32 +NV_CTRL_STRING_GVIO_VIDEO_FORMAT_NAME: Final = 33 +NV_CTRL_STRING_GVO_VIDEO_FORMAT_NAME: Final = 33 +NV_CTRL_STRING_GPU_CURRENT_CLOCK_FREQS: Final = 34 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_HARDWARE_REVISION: Final = 35 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_VERSION_A: Final = 36 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_DATE_A: Final = 37 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_VERSION_B: Final = 38 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_FIRMWARE_DATE_B: Final = 39 +NV_CTRL_STRING_3D_VISION_PRO_TRANSCEIVER_ADDRESS: Final = 40 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_FIRMWARE_VERSION_A: Final = 41 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_FIRMWARE_DATE_A: Final = 42 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_ADDRESS: Final = 43 +NV_CTRL_STRING_3D_VISION_PRO_GLASSES_NAME: Final = 44 +NV_CTRL_STRING_CURRENT_METAMODE_VERSION_2: Final = 45 +NV_CTRL_STRING_DISPLAY_NAME_TYPE_BASENAME: Final = 46 +NV_CTRL_STRING_DISPLAY_NAME_TYPE_ID: Final = 47 +NV_CTRL_STRING_DISPLAY_NAME_DP_GUID: Final = 48 +NV_CTRL_STRING_DISPLAY_NAME_EDID_HASH: Final = 49 +NV_CTRL_STRING_DISPLAY_NAME_TARGET_INDEX: Final = 50 +NV_CTRL_STRING_DISPLAY_NAME_RANDR: Final = 51 +NV_CTRL_STRING_GPU_UUID: Final = 52 +NV_CTRL_STRING_GPU_UTILIZATION: Final = 53 +NV_CTRL_STRING_MULTIGPU_MODE: Final = 54 +NV_CTRL_STRING_PRIME_OUTPUTS_DATA: Final = 55 +NV_CTRL_STRING_LAST_ATTRIBUTE: Final = NV_CTRL_STRING_PRIME_OUTPUTS_DATA +NV_CTRL_BINARY_DATA_EDID: Final = 0 +NV_CTRL_BINARY_DATA_MODELINES: Final = 1 +NV_CTRL_BINARY_DATA_METAMODES: Final = 2 +NV_CTRL_BINARY_DATA_METAMODES_VERSION_1: Final = NV_CTRL_BINARY_DATA_METAMODES +NV_CTRL_BINARY_DATA_XSCREENS_USING_GPU: Final = 3 +NV_CTRL_BINARY_DATA_GPUS_USED_BY_XSCREEN: Final = 4 +NV_CTRL_BINARY_DATA_GPUS_USING_FRAMELOCK: Final = 5 +NV_CTRL_BINARY_DATA_DISPLAY_VIEWPORT: Final = 6 +NV_CTRL_BINARY_DATA_FRAMELOCKS_USED_BY_GPU: Final = 7 +NV_CTRL_BINARY_DATA_GPUS_USING_VCSC: Final = 8 +NV_CTRL_BINARY_DATA_VCSCS_USED_BY_GPU: Final = 9 +NV_CTRL_BINARY_DATA_COOLERS_USED_BY_GPU: Final = 10 +NV_CTRL_BINARY_DATA_GPUS_USED_BY_LOGICAL_XSCREEN: Final = 11 +NV_CTRL_BINARY_DATA_THERMAL_SENSORS_USED_BY_GPU: Final = 12 +NV_CTRL_BINARY_DATA_GLASSES_PAIRED_TO_3D_VISION_PRO_TRANSCEIVER: Final = 13 +NV_CTRL_BINARY_DATA_DISPLAY_TARGETS: Final = 14 +NV_CTRL_BINARY_DATA_DISPLAYS_CONNECTED_TO_GPU: Final = 15 +NV_CTRL_BINARY_DATA_METAMODES_VERSION_2: Final = 16 +NV_CTRL_BINARY_DATA_DISPLAYS_ENABLED_ON_XSCREEN: Final = 17 +NV_CTRL_BINARY_DATA_DISPLAYS_ASSIGNED_TO_XSCREEN: Final = 18 +NV_CTRL_BINARY_DATA_GPU_FLAGS: Final = 19 +NV_CTRL_BINARY_DATA_GPU_FLAGS_STEREO_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 0 +NV_CTRL_BINARY_DATA_GPU_FLAGS_OVERLAY_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 1 +NV_CTRL_BINARY_DATA_GPU_FLAGS_DEPTH_8_DISPLAY_TRANSFORM_EXCLUSIVE: Final = 2 +NV_CTRL_BINARY_DATA_DISPLAYS_ON_GPU: Final = 20 +NV_CTRL_BINARY_DATA_LAST_ATTRIBUTE: Final = NV_CTRL_BINARY_DATA_DISPLAYS_ON_GPU +NV_CTRL_STRING_OPERATION_ADD_METAMODE: Final = 0 +NV_CTRL_STRING_OPERATION_GTF_MODELINE: Final = 1 +NV_CTRL_STRING_OPERATION_CVT_MODELINE: Final = 2 +NV_CTRL_STRING_OPERATION_BUILD_MODEPOOL: Final = 3 +NV_CTRL_STRING_OPERATION_GVI_CONFIGURE_STREAMS: Final = 4 +NV_CTRL_STRING_OPERATION_PARSE_METAMODE: Final = 5 +NV_CTRL_STRING_OPERATION_LAST_ATTRIBUTE: Final = NV_CTRL_STRING_OPERATION_PARSE_METAMODE +X_nvCtrlQueryExtension: Final = 0 +X_nvCtrlQueryAttribute: Final = 2 +X_nvCtrlQueryStringAttribute: Final = 4 +X_nvCtrlQueryValidAttributeValues: Final = 5 +X_nvCtrlSetStringAttribute: Final = 9 +X_nvCtrlSetAttributeAndGetStatus: Final = 19 +X_nvCtrlQueryBinaryData: Final = 20 +X_nvCtrlQueryTargetCount: Final = 24 +X_nvCtrlStringOperation: Final = 25 +ATTRIBUTE_TYPE_UNKNOWN: Final = 0 +ATTRIBUTE_TYPE_INTEGER: Final = 1 +ATTRIBUTE_TYPE_BITMASK: Final = 2 +ATTRIBUTE_TYPE_BOOL: Final = 3 +ATTRIBUTE_TYPE_RANGE: Final = 4 +ATTRIBUTE_TYPE_INT_BITS: Final = 5 +ATTRIBUTE_TYPE_READ: Final = 0x01 +ATTRIBUTE_TYPE_WRITE: Final = 0x02 +ATTRIBUTE_TYPE_DISPLAY: Final = 0x04 +ATTRIBUTE_TYPE_GPU: Final = 0x08 +ATTRIBUTE_TYPE_FRAMELOCK: Final = 0x10 +ATTRIBUTE_TYPE_X_SCREEN: Final = 0x20 +ATTRIBUTE_TYPE_XINERAMA: Final = 0x40 +ATTRIBUTE_TYPE_VCSC: Final = 0x80 +NV_CTRL_TARGET_TYPE_X_SCREEN: Final = 0 +NV_CTRL_TARGET_TYPE_GPU: Final = 1 +NV_CTRL_TARGET_TYPE_FRAMELOCK: Final = 2 +NV_CTRL_TARGET_TYPE_VCSC: Final = 3 +NV_CTRL_TARGET_TYPE_GVI: Final = 4 +NV_CTRL_TARGET_TYPE_COOLER: Final = 5 +NV_CTRL_TARGET_TYPE_THERMAL_SENSOR: Final = 6 +NV_CTRL_TARGET_TYPE_3D_VISION_PRO_TRANSCEIVER: Final = 7 +NV_CTRL_TARGET_TYPE_DISPLAY: Final = 8 + +class Target: + def id(self) -> int: ... + def type(self) -> int: ... + +class Gpu(Target): + def __init__(self, ngpu: int = 0) -> None: ... + +class Screen(Target): + def __init__(self, nscr: int = 0) -> None: ... + +class Cooler(Target): + def __init__(self, nfan: int = 0) -> None: ... + +class NVCtrlQueryTargetCountReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryAttributeReplyRequest(rq.ReplyRequest): ... +class NVCtrlSetAttributeAndGetStatusReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryStringAttributeReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryValidAttributeValuesReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryBinaryDataReplyRequest(rq.ReplyRequest): ... +class NVCtrlQueryListCard32ReplyRequest(rq.ReplyRequest): ... diff --git a/stubs/python-xlib/Xlib/ext/randr.pyi b/stubs/python-xlib/Xlib/ext/randr.pyi new file mode 100644 index 000000000000..9aac2eee1301 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/randr.pyi @@ -0,0 +1,261 @@ +from collections.abc import Sequence +from typing import Final, TypeAlias + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable, resource + +_RandRModeInfo13IntSequence: TypeAlias = Sequence[int] + +extname: Final = "RANDR" +RRScreenChangeNotify: Final = 0 +RRNotify: Final = 1 +RRNotify_CrtcChange: Final = 0 +RRNotify_OutputChange: Final = 1 +RRNotify_OutputProperty: Final = 2 +RRScreenChangeNotifyMask: Final = 0x1 +RRCrtcChangeNotifyMask: Final = 0x2 +RROutputChangeNotifyMask: Final = 0x4 +RROutputPropertyNotifyMask: Final = 0x8 +SetConfigSuccess: Final = 0 +SetConfigInvalidConfigTime: Final = 1 +SetConfigInvalidTime: Final = 2 +SetConfigFailed: Final = 3 +Rotate_0: Final = 1 +Rotate_90: Final = 2 +Rotate_180: Final = 4 +Rotate_270: Final = 8 +Reflect_X: Final = 16 +Reflect_Y: Final = 32 +HSyncPositive: Final = 0x00000001 +HSyncNegative: Final = 0x00000002 +VSyncPositive: Final = 0x00000004 +VSyncNegative: Final = 0x00000008 +Interlace: Final = 0x00000010 +DoubleScan: Final = 0x00000020 +CSync: Final = 0x00000040 +CSyncPositive: Final = 0x00000080 +CSyncNegative: Final = 0x00000100 +HSkewPresent: Final = 0x00000200 +BCast: Final = 0x00000400 +PixelMultiplex: Final = 0x00000800 +DoubleClock: Final = 0x00001000 +ClockDivideBy2: Final = 0x00002000 +Connected: Final = 0 +Disconnected: Final = 1 +UnknownConnection: Final = 2 +PROPERTY_RANDR_EDID: Final = "EDID" +PROPERTY_SIGNAL_FORMAT: Final = "SignalFormat" +PROPERTY_SIGNAL_PROPERTIES: Final = "SignalProperties" +PROPERTY_CONNECTOR_TYPE: Final = "ConnectorType" +PROPERTY_CONNECTOR_NUMBER: Final = "ConnectorNumber" +PROPERTY_COMPATIBILITY_LIST: Final = "CompatibilityList" +PROPERTY_CLONE_LIST: Final = "CloneList" +SubPixelUnknown: Final = 0 +SubPixelHorizontalRGB: Final = 1 +SubPixelHorizontalBGR: Final = 2 +SubPixelVerticalRGB: Final = 3 +SubPixelVerticalBGR: Final = 4 +SubPixelNone: Final = 5 +BadRROutput: Final = 0 +BadRRCrtc: Final = 1 +BadRRMode: Final = 2 + +class BadRROutputError(Exception): ... +class BadRRCrtcError(Exception): ... +class BadRRModeError(Exception): ... + +RandR_ScreenSizes: rq.Struct +RandR_ModeInfo: rq.Struct +RandR_Rates: rq.Struct +Render_Transform: rq.Struct +MonitorInfo: rq.Struct + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class _1_0SetScreenConfig(rq.ReplyRequest): ... +class SetScreenConfig(rq.ReplyRequest): ... + +def set_screen_config( + self: drawable.Drawable, size_id: int, rotation: int, config_timestamp: int, rate: int = 0, timestamp: int = 0 +) -> SetScreenConfig: ... + +class SelectInput(rq.Request): ... + +def select_input(self: drawable.Window, mask: int) -> SelectInput: ... + +class GetScreenInfo(rq.ReplyRequest): ... + +def get_screen_info(self: drawable.Window) -> GetScreenInfo: ... + +class GetScreenSizeRange(rq.ReplyRequest): ... + +def get_screen_size_range(self: drawable.Window) -> GetScreenSizeRange: ... + +class SetScreenSize(rq.Request): ... + +def set_screen_size( + self: drawable.Window, + width: int, + height: int, + width_in_millimeters: int | None = None, + height_in_millimeters: int | None = None, +) -> SetScreenSize: ... + +class GetScreenResources(rq.ReplyRequest): ... + +def get_screen_resources(self: drawable.Window) -> GetScreenResources: ... + +class GetOutputInfo(rq.ReplyRequest): ... + +def get_output_info(self: Display | resource.Resource, output: int, config_timestamp: int) -> GetOutputInfo: ... + +class ListOutputProperties(rq.ReplyRequest): ... + +def list_output_properties(self: Display | resource.Resource, output: int) -> ListOutputProperties: ... + +class QueryOutputProperty(rq.ReplyRequest): ... + +def query_output_property(self: Display | resource.Resource, output: int, property: int) -> QueryOutputProperty: ... + +class ConfigureOutputProperty(rq.Request): ... + +def configure_output_property(self: Display | resource.Resource, output: int, property: int) -> ConfigureOutputProperty: ... + +class ChangeOutputProperty(rq.Request): ... + +def change_output_property( + self: Display | resource.Resource, output: int, property: int, type: int, mode: int, value: Sequence[float] | Sequence[str] +) -> ChangeOutputProperty: ... + +class DeleteOutputProperty(rq.Request): ... + +def delete_output_property(self: Display | resource.Resource, output: int, property: int) -> DeleteOutputProperty: ... + +class GetOutputProperty(rq.ReplyRequest): ... + +def get_output_property( + self: Display | resource.Resource, + output: int, + property: int, + type: int, + long_offset: int, + long_length: int, + delete: bool = False, + pending: bool = False, +) -> GetOutputProperty: ... + +class CreateMode(rq.ReplyRequest): ... + +def create_mode(self: drawable.Window, mode: _RandRModeInfo13IntSequence, name: str) -> CreateMode: ... + +class DestroyMode(rq.Request): ... + +def destroy_mode(self: Display | resource.Resource, mode: int) -> DestroyMode: ... + +class AddOutputMode(rq.Request): ... + +def add_output_mode(self: Display | resource.Resource, output: int, mode: int) -> AddOutputMode: ... + +class DeleteOutputMode(rq.Request): ... + +def delete_output_mode(self: Display | resource.Resource, output: int, mode: int) -> DeleteOutputMode: ... + +class GetCrtcInfo(rq.ReplyRequest): ... + +def get_crtc_info(self: Display | resource.Resource, crtc: int, config_timestamp: int) -> GetCrtcInfo: ... + +class SetCrtcConfig(rq.ReplyRequest): ... + +def set_crtc_config( + self: Display | resource.Resource, + crtc: int, + config_timestamp: int, + x: int, + y: int, + mode: int, + rotation: int, + outputs: Sequence[int], + timestamp: int = 0, +) -> SetCrtcConfig: ... + +class GetCrtcGammaSize(rq.ReplyRequest): ... + +def get_crtc_gamma_size(self: Display | resource.Resource, crtc: int) -> GetCrtcGammaSize: ... + +class GetCrtcGamma(rq.ReplyRequest): ... + +def get_crtc_gamma(self: Display | resource.Resource, crtc: int) -> GetCrtcGamma: ... + +class SetCrtcGamma(rq.Request): ... + +def set_crtc_gamma( + self: Display | resource.Resource, crtc: int, size: int, red: Sequence[int], green: Sequence[int], blue: Sequence[int] +) -> SetCrtcGamma: ... + +class GetScreenResourcesCurrent(rq.ReplyRequest): ... + +def get_screen_resources_current(self: drawable.Window) -> GetScreenResourcesCurrent: ... + +class SetCrtcTransform(rq.Request): ... + +def set_crtc_transform(self: Display | resource.Resource, crtc: int, n_bytes_filter: Sequence[int]) -> SetCrtcTransform: ... + +class GetCrtcTransform(rq.ReplyRequest): ... + +def get_crtc_transform(self: Display | resource.Resource, crtc: int) -> GetCrtcTransform: ... + +class GetPanning(rq.ReplyRequest): ... + +def get_panning(self: Display | resource.Resource, crtc: int) -> GetPanning: ... + +class SetPanning(rq.ReplyRequest): ... + +def set_panning( + self: Display | resource.Resource, + crtc: int, + left: int, + top: int, + width: int, + height: int, + track_left: int, + track_top: int, + track_width: int, + track_height: int, + border_left: int, + border_top: int, + border_width: int, + border_height: int, + timestamp: int = 0, +) -> SetPanning: ... + +class SetOutputPrimary(rq.Request): ... + +def set_output_primary(self: drawable.Window, output: int) -> SetOutputPrimary: ... + +class GetOutputPrimary(rq.ReplyRequest): ... + +def get_output_primary(self: drawable.Window) -> GetOutputPrimary: ... + +class GetMonitors(rq.ReplyRequest): ... + +def get_monitors(self: drawable.Window, is_active: bool = True) -> GetMonitors: ... + +class SetMonitor(rq.Request): ... + +def set_monitor( + self: drawable.Window, monitor_info: tuple[int, bool, bool, Sequence[int], int, int, int, int, int] +) -> SetMonitor: ... + +class DeleteMonitor(rq.Request): ... + +def delete_monitor(self: Display | resource.Resource, name: str) -> DeleteMonitor: ... + +class ScreenChangeNotify(rq.Event): ... +class CrtcChangeNotify(rq.Event): ... +class OutputChangeNotify(rq.Event): ... +class OutputPropertyNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/record.pyi b/stubs/python-xlib/Xlib/ext/record.pyi new file mode 100644 index 000000000000..4cac2039e09f --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/record.pyi @@ -0,0 +1,115 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence, Sized +from typing import Any, Final, Literal, TypeVar + +from Xlib.display import Display +from Xlib.protocol import display, rq +from Xlib.xobject import resource + +_T = TypeVar("_T") +_S = TypeVar("_S", bound=Sized) + +extname: Final = "RECORD" + +FromServerTime: Final = 0x01 +FromClientTime: Final = 0x02 +FromClientSequence: Final = 0x04 + +CurrentClients: Final = 1 +FutureClients: Final = 2 +AllClients: Final = 3 + +FromServer: Final = 0 +FromClient: Final = 1 +ClientStarted: Final = 2 +ClientDied: Final = 3 +StartOfData: Final = 4 +EndOfData: Final = 5 +Record_Range8: rq.Struct +Record_Range16: rq.Struct +Record_ExtRange: rq.Struct +Record_Range: rq.Struct +Record_ClientInfo: rq.Struct + +class RawField(rq.ValueField): + structcode: None + def pack_value(self, val: _S) -> tuple[_S, int, None]: ... # type: ignore[override] + def parse_binary_value(self, data: _T, display: Unused, length: Unused, format: Unused) -> tuple[_T, Literal[""]]: ... # type: ignore[override] # See: https://github.com/python-xlib/python-xlib/pull/249 + +class GetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource, major: int, minor: int) -> GetVersion: ... + +class CreateContext(rq.Request): ... + +def create_context( + self: Display | resource.Resource, + datum_flags: int, + clients: Sequence[int], + ranges: Sequence[ + tuple[ + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + bool, + bool, + ] + ], +) -> int: ... + +class RegisterClients(rq.Request): ... + +def register_clients( + self: Display | resource.Resource, + context: int, + element_header: int, + clients: int, + ranges: Sequence[ + tuple[ + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + tuple[int, int], + bool, + bool, + ] + ], +) -> None: ... + +class UnregisterClients(rq.Request): ... + +def unregister_clients(self: Display | resource.Resource, context: int, clients: Sequence[int]) -> None: ... + +class GetContext(rq.ReplyRequest): ... + +def get_context(self: Display | resource.Resource, context: int) -> GetContext: ... + +class EnableContext(rq.ReplyRequest): + def __init__( + self, + callback: Callable[[rq.DictWrapper | dict[str, Any]], Any], + display: display.Display, + defer: bool = False, + *args: object | bool, + **keys: object | bool, + ) -> None: ... + +def enable_context( + self: Display | resource.Resource, context: int, callback: Callable[[rq.DictWrapper | dict[str, Any]], Any] +) -> None: ... + +class DisableContext(rq.Request): ... + +def disable_context(self: Display | resource.Resource, context: int) -> None: ... + +class FreeContext(rq.Request): ... + +def free_context(self: Display | resource.Resource, context: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/res.pyi b/stubs/python-xlib/Xlib/ext/res.pyi new file mode 100644 index 000000000000..27df703789fa --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/res.pyi @@ -0,0 +1,62 @@ +from _typeshed import Unused +from collections.abc import Sequence +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +RES_MAJOR_VERSION: Final = 1 +RES_MINOR_VERSION: Final = 2 +extname: Final = "X-Resource" +ResQueryVersion: Final = 0 +ResQueryClients: Final = 1 +ResQueryClientResources: Final = 2 +ResQueryClientPixmapBytes: Final = 3 +ResQueryClientIds: Final = 4 +ResQueryResourceBytes: Final = 5 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource, client_major: int = 1, client_minor: int = 2) -> QueryVersion: ... + +Client: rq.Struct + +class QueryClients(rq.ReplyRequest): ... + +def query_clients(self: Display | resource.Resource) -> QueryClients: ... + +Type: rq.Struct + +class QueryClientResources(rq.ReplyRequest): ... + +def query_client_resources(self: Display | resource.Resource, client: int) -> QueryClientResources: ... + +class QueryClientPixmapBytes(rq.ReplyRequest): ... + +def query_client_pixmap_bytes(self: Display | resource.Resource, client: int) -> QueryClientPixmapBytes: ... + +class SizeOf(rq.LengthOf): + item_size: int + def __init__(self, name: str | list[str] | tuple[str, ...], size: int, item_size: int) -> None: ... + def parse_value(self, length: int, display: Unused) -> int: ... # type: ignore[override] + +ClientXIDMask: Final = 0x1 +LocalClientPIDMask: Final = 0x2 +ClientIdSpec: rq.Struct +ClientIdValue: rq.Struct + +class QueryClientIds(rq.ReplyRequest): ... + +def query_client_ids(self: Display | resource.Resource, specs: Sequence[tuple[int, int]]) -> QueryClientIds: ... + +ResourceIdSpec: rq.Struct +ResourceSizeSpec: rq.Struct +ResourceSizeValue: rq.Struct + +class QueryResourceBytes(rq.ReplyRequest): ... + +def query_resource_bytes( + self: Display | resource.Resource, client: int, specs: Sequence[tuple[int, int]] +) -> QueryResourceBytes: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/screensaver.pyi b/stubs/python-xlib/Xlib/ext/screensaver.pyi new file mode 100644 index 000000000000..24ac6750bb89 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/screensaver.pyi @@ -0,0 +1,52 @@ +from typing import Final + +from Xlib._typing import ErrorHandler +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable + +extname: Final = "MIT-SCREEN-SAVER" +NotifyMask: Final = 1 +CycleMask: Final = 2 +StateOff: Final = 0 +StateOn: Final = 1 +StateCycle: Final = 2 +KindBlanked: Final = 0 +KindInternal: Final = 1 +KindExternal: Final = 2 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: drawable.Drawable) -> QueryVersion: ... + +class QueryInfo(rq.ReplyRequest): ... + +def query_info(self: drawable.Drawable) -> QueryInfo: ... + +class SelectInput(rq.Request): ... + +def select_input(self: drawable.Drawable, mask: int) -> SelectInput: ... + +class SetAttributes(rq.Request): ... + +def set_attributes( + self: drawable.Drawable, + x: int, + y: int, + width: int, + height: int, + border_width: int, + window_class: int = 0, + depth: int = 0, + visual: int = 0, + onerror: ErrorHandler[object] | None = None, + **keys: object, +) -> SetAttributes: ... + +class UnsetAttributes(rq.Request): ... + +def unset_attributes(self: drawable.Drawable, onerror: ErrorHandler[object] | None = None) -> UnsetAttributes: ... + +class Notify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/security.pyi b/stubs/python-xlib/Xlib/ext/security.pyi new file mode 100644 index 000000000000..b8445fe245ea --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/security.pyi @@ -0,0 +1,33 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "SECURITY" +SecurityClientTrusted: Final = 0 +SecurityClientUntrusted: Final = 1 +SecurityAuthorizationRevokedMask: Final = 1 +AUTHID = rq.Card32 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class SecurityGenerateAuthorization(rq.ReplyRequest): ... + +def generate_authorization( + self: Display | resource.Resource, + auth_proto: str, + auth_data: bytes | bytearray = b"", + timeout: int | None = None, + trust_level: int | None = None, + group: int | None = None, + event_mask: int | None = None, +) -> SecurityGenerateAuthorization: ... + +class SecurityRevokeAuthorization(rq.Request): ... + +def revoke_authorization(self: Display | resource.Resource, authid: int) -> SecurityRevokeAuthorization: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/shape.pyi b/stubs/python-xlib/Xlib/ext/shape.pyi new file mode 100644 index 000000000000..9a72b1f1736a --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/shape.pyi @@ -0,0 +1,62 @@ +from collections.abc import Sequence +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.protocol.structs import _Rectangle4IntSequence +from Xlib.xobject import drawable, resource + +extname: Final = "SHAPE" +OP = rq.Card8 + +class SO: + Set: int + Union: int + Intersect: int + Subtract: int + Invert: int + +class SK: + Bounding: int + Clip: int + Input: int + +class KIND(rq.Set): + def __init__(self, name: str) -> None: ... + +class NotifyEventData(rq.Event): ... +class QueryVersion(rq.ReplyRequest): ... +class Rectangles(rq.Request): ... +class Mask(rq.Request): ... +class Combine(rq.Request): ... +class Offset(rq.Request): ... +class QueryExtents(rq.ReplyRequest): ... +class SelectInput(rq.Request): ... +class InputSelected(rq.ReplyRequest): ... +class GetRectangles(rq.ReplyRequest): ... + +class Event: + Notify: int + +def combine( + self: drawable.Window, operation: int, destination_kind: int, source_kind: int, x_offset: int, y_offset: int +) -> None: ... +def get_rectangles(self: drawable.Window, source_kind: int) -> GetRectangles: ... +def input_selected(self: drawable.Window) -> InputSelected: ... +def mask( + self: drawable.Window, operation: int, destination_kind: int, x_offset: int, y_offset: int, source_bitmap: int +) -> None: ... +def offset(self: drawable.Window, destination_kind: int, x_offset: int, y_offset: int) -> None: ... +def query_extents(self: drawable.Window) -> QueryExtents: ... +def query_version(self: Display | resource.Resource) -> QueryVersion: ... +def rectangles( + self: drawable.Window, + operation: int, + destination_kind: int, + ordering: int, + x_offset: int, + y_offset: int, + rectangles: Sequence[_Rectangle4IntSequence], +) -> None: ... +def select_input(self: drawable.Window, enable: int) -> None: ... +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xfixes.pyi b/stubs/python-xlib/Xlib/ext/xfixes.pyi new file mode 100644 index 000000000000..cb9bdc42cd48 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xfixes.pyi @@ -0,0 +1,50 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import request, rq +from Xlib.xobject import drawable, resource + +extname: Final = "XFIXES" +XFixesSelectionNotify: Final = 0 +XFixesCursorNotify: Final = 1 +XFixesSetSelectionOwnerNotifyMask: Final = 0x1 +XFixesSelectionWindowDestroyNotifyMask: Final = 0x2 +XFixesSelectionClientCloseNotifyMask: Final = 0x4 +XFixesDisplayCursorNotifyMask: Final = 0x1 +XFixesSetSelectionOwnerNotify: Final = 0 +XFixesSelectionWindowDestroyNotify: Final = 1 +XFixesSelectionClientCloseNotify: Final = 2 +XFixesDisplayCursorNotify: Final = 0 + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class HideCursor(rq.Request): ... + +def hide_cursor(self: drawable.Window) -> None: ... + +class ShowCursor(rq.Request): ... + +def show_cursor(self: drawable.Window) -> None: ... + +class SelectSelectionInput(rq.Request): ... + +def select_selection_input(self: Display | resource.Resource, window: int, selection: int, mask: int) -> SelectSelectionInput: ... + +class SelectionNotify(rq.Event): ... +class SetSelectionOwnerNotify(SelectionNotify): ... +class SelectionWindowDestroyNotify(SelectionNotify): ... +class SelectionClientCloseNotify(SelectionNotify): ... +class SelectCursorInput(rq.Request): ... + +def select_cursor_input(self: Display | resource.Resource, window: int, mask: int) -> SelectCursorInput: ... + +class GetCursorImage(rq.ReplyRequest): ... + +def get_cursor_image(self: Display | resource.Resource, window: Unused) -> GetCursorImage: ... + +class DisplayCursorNotify(rq.Event): ... + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xinerama.pyi b/stubs/python-xlib/Xlib/ext/xinerama.pyi new file mode 100644 index 000000000000..e47a080ac65a --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xinerama.pyi @@ -0,0 +1,37 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import drawable, resource + +extname: Final = "XINERAMA" + +class QueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> QueryVersion: ... + +class GetState(rq.ReplyRequest): ... + +def get_state(self: drawable.Window) -> GetState: ... + +class GetScreenCount(rq.ReplyRequest): ... + +def get_screen_count(self: drawable.Window) -> GetScreenCount: ... + +class GetScreenSize(rq.ReplyRequest): ... + +def get_screen_size(self: drawable.Window, screen_no: int) -> GetScreenSize: ... + +class IsActive(rq.ReplyRequest): ... + +def is_active(self: Display | resource.Resource) -> int: ... + +class QueryScreens(rq.ReplyRequest): ... + +def query_screens(self: Display | resource.Resource) -> QueryScreens: ... + +class GetInfo(rq.ReplyRequest): ... + +def get_info(self: Display | resource.Resource, visual: int) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xinput.pyi b/stubs/python-xlib/Xlib/ext/xinput.pyi new file mode 100644 index 000000000000..6711faef3570 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xinput.pyi @@ -0,0 +1,249 @@ +from _typeshed import ConvertibleToFloat, SliceableBuffer, Unused +from collections.abc import Iterable, Sequence +from typing import Final, TypeVar + +from Xlib.display import Display +from Xlib.protocol import display, request, rq +from Xlib.xobject import drawable, resource + +_T = TypeVar("_T") + +extname: Final = "XInputExtension" +PropertyDeleted: Final = 0 +PropertyCreated: Final = 1 +PropertyModified: Final = 2 +NotifyNormal: Final = 0 +NotifyGrab: Final = 1 +NotifyUngrab: Final = 2 +NotifyWhileGrabbed: Final = 3 +NotifyPassiveGrab: Final = 4 +NotifyPassiveUngrab: Final = 5 +NotifyAncestor: Final = 0 +NotifyVirtual: Final = 1 +NotifyInferior: Final = 2 +NotifyNonlinear: Final = 3 +NotifyNonlinearVirtual: Final = 4 +NotifyPointer: Final = 5 +NotifyPointerRoot: Final = 6 +NotifyDetailNone: Final = 7 +GrabtypeButton: Final = 0 +GrabtypeKeycode: Final = 1 +GrabtypeEnter: Final = 2 +GrabtypeFocusIn: Final = 3 +GrabtypeTouchBegin: Final = 4 +AnyModifier: Final = 0x80000000 +AnyButton: Final = 0 +AnyKeycode: Final = 0 +AsyncDevice: Final = 0 +SyncDevice: Final = 1 +ReplayDevice: Final = 2 +AsyncPairedDevice: Final = 3 +AsyncPair: Final = 4 +SyncPair: Final = 5 +SlaveSwitch: Final = 1 +DeviceChange: Final = 2 +MasterAdded: Final = 0x01 +MasterRemoved: Final = 0x02 +SlaveAdded: Final = 0x04 +SlaveRemoved: Final = 0x08 +SlaveAttached: Final = 0x10 +SlaveDetached: Final = 0x20 +DeviceEnabled: Final = 0x40 +DeviceDisabled: Final = 0x80 +AddMaster: Final = 1 +RemoveMaster: Final = 2 +AttachSlave: Final = 3 +DetachSlave: Final = 4 +AttachToMaster: Final = 1 +Floating: Final = 2 +ModeRelative: Final = 0 +ModeAbsolute: Final = 1 +MasterPointer: Final = 1 +MasterKeyboard: Final = 2 +SlavePointer: Final = 3 +SlaveKeyboard: Final = 4 +FloatingSlave: Final = 5 +KeyClass: Final = 0 +ButtonClass: Final = 1 +ValuatorClass: Final = 2 +ScrollClass: Final = 3 +TouchClass: Final = 8 +KeyRepeat: Final = 0x10000 +AllDevices: Final = 0 +AllMasterDevices: Final = 1 +DeviceChanged: Final = 1 +KeyPress: Final = 2 +KeyRelease: Final = 3 +ButtonPress: Final = 4 +ButtonRelease: Final = 5 +Motion: Final = 6 +Enter: Final = 7 +Leave: Final = 8 +FocusIn: Final = 9 +FocusOut: Final = 10 +HierarchyChanged: Final = 11 +PropertyEvent: Final = 12 +RawKeyPress: Final = 13 +RawKeyRelease: Final = 14 +RawButtonPress: Final = 15 +RawButtonRelease: Final = 16 +RawMotion: Final = 17 +DeviceChangedMask: Final = 0x00002 +KeyPressMask: Final = 0x00004 +KeyReleaseMask: Final = 0x00008 +ButtonPressMask: Final = 0x00010 +ButtonReleaseMask: Final = 0x00020 +MotionMask: Final = 0x00040 +EnterMask: Final = 0x00080 +LeaveMask: Final = 0x00100 +FocusInMask: Final = 0x00200 +FocusOutMask: Final = 0x00400 +HierarchyChangedMask: Final = 0x00800 +PropertyEventMask: Final = 0x01000 +RawKeyPressMask: Final = 0x02000 +RawKeyReleaseMask: Final = 0x04000 +RawButtonPressMask: Final = 0x08000 +RawButtonReleaseMask: Final = 0x10000 +RawMotionMask: Final = 0x20000 +GrabModeSync: Final = 0 +GrabModeAsync: Final = 1 +GrabModeTouch: Final = 2 +DEVICEID = rq.Card16 +DEVICE = rq.Card16 +DEVICEUSE = rq.Card8 +PROPERTY_TYPE_FLOAT: Final = "FLOAT" + +# ignore[override] because of Liskov substitution principle violations +class FP1616(rq.Int32): + def check_value(self, value: float) -> int: ... # type: ignore[override] + def parse_value(self, value: ConvertibleToFloat, display: Unused) -> float: ... # type: ignore[override] + +class FP3232(rq.ValueField): + structcode: str + def check_value(self, value: _T) -> _T: ... # type: ignore[override] + def parse_value(self, value: tuple[ConvertibleToFloat, ConvertibleToFloat], display: Unused) -> float: ... # type: ignore[override] + +class XIQueryVersion(rq.ReplyRequest): ... + +def query_version(self: Display | resource.Resource) -> XIQueryVersion: ... + +class Mask(rq.List): + def __init__(self, name: str) -> None: ... + def pack_value(self, val: int | Iterable[int]) -> tuple[bytes, int, None]: ... # type: ignore[override] + +EventMask: rq.Struct + +class XISelectEvents(rq.Request): ... + +def select_events(self: drawable.Window, event_masks: Sequence[tuple[int, Sequence[int]]]) -> XISelectEvents: ... + +AnyInfo: rq.Struct + +class ButtonMask: + def __init__(self, value: int, length: int) -> None: ... + def __getitem__(self, key: int) -> int: ... + def __len__(self) -> int: ... + +class ButtonState(rq.ValueField): + structcode: None + def __init__(self, name: str) -> None: ... + def parse_binary_value( # type: ignore[override] # length: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + self, data: SliceableBuffer, display: Unused, length: int, fmt: Unused + ) -> tuple[ButtonMask, SliceableBuffer]: ... + +ButtonInfo: rq.Struct +KeyInfo: rq.Struct +ValuatorInfo: rq.Struct +ScrollInfo: rq.Struct +TouchInfo: rq.Struct +INFO_CLASSES: Final[dict[int, rq.Struct]] + +class ClassInfoClass: + structcode: None + def parse_binary(self, data: SliceableBuffer, display: display.Display | None) -> tuple[rq.DictWrapper, SliceableBuffer]: ... + +ClassInfo: ClassInfoClass +DeviceInfo: rq.Struct + +class XIQueryDevice(rq.ReplyRequest): ... + +def query_device(self: Display | resource.Resource, deviceid: int) -> XIQueryDevice: ... + +class XIListProperties(rq.ReplyRequest): ... + +def list_device_properties(self: Display | resource.Resource, deviceid: int) -> XIListProperties: ... + +class XIGetProperty(rq.ReplyRequest): ... + +def get_device_property( + self: Display | resource.Resource, deviceid: int, property: int, type: int, offset: int, length: int, delete: bool = False +) -> XIGetProperty: ... + +class XIChangeProperty(rq.Request): ... + +def change_device_property( + self: Display | resource.Resource, deviceid: int, property: int, type: int, mode: int, value: Sequence[float] | Sequence[str] +) -> XIChangeProperty: ... + +class XIDeleteProperty(rq.Request): ... + +def delete_device_property(self: Display | resource.Resource, deviceid: int, property: int) -> XIDeleteProperty: ... + +class XIGrabDevice(rq.ReplyRequest): ... + +def grab_device( + self: drawable.Window, + deviceid: int, + time: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], +) -> XIGrabDevice: ... + +class XIUngrabDevice(rq.Request): ... + +def ungrab_device(self: Display | resource.Resource, deviceid: int, time: int) -> XIUngrabDevice: ... + +class XIPassiveGrabDevice(rq.ReplyRequest): ... + +def passive_grab_device( + self: drawable.Window, + deviceid: int, + time: int, + detail: int, + grab_type: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], + modifiers: Sequence[int], +) -> XIPassiveGrabDevice: ... +def grab_keycode( + self: drawable.Window, + deviceid: int, + time: int, + keycode: int, + grab_mode: int, + paired_device_mode: int, + owner_events: bool, + event_mask: Sequence[int], + modifiers: Sequence[int], +) -> XIPassiveGrabDevice: ... + +class XIPassiveUngrabDevice(rq.Request): ... + +def passive_ungrab_device( + self: drawable.Window, deviceid: int, detail: int, grab_type: int, modifiers: Sequence[int] +) -> XIPassiveUngrabDevice: ... +def ungrab_keycode(self: drawable.Window, deviceid: int, keycode: int, modifiers: Sequence[int]) -> XIPassiveUngrabDevice: ... + +HierarchyInfo: rq.Struct +HierarchyEventData: rq.Struct +ModifierInfo: rq.Struct +GroupInfo: rq.Struct +DeviceEventData: rq.Struct +DeviceChangedEventData: rq.Struct +PropertyEventData: rq.Struct + +def init(disp: Display, info: request.QueryExtension) -> None: ... diff --git a/stubs/python-xlib/Xlib/ext/xtest.pyi b/stubs/python-xlib/Xlib/ext/xtest.pyi new file mode 100644 index 000000000000..5734b7195f51 --- /dev/null +++ b/stubs/python-xlib/Xlib/ext/xtest.pyi @@ -0,0 +1,28 @@ +from _typeshed import Unused +from typing import Final + +from Xlib.display import Display +from Xlib.protocol import rq +from Xlib.xobject import resource + +extname: Final = "XTEST" +CurrentCursor: Final = 1 + +class GetVersion(rq.ReplyRequest): ... + +def get_version(self: Display | resource.Resource, major: int, minor: int) -> GetVersion: ... + +class CompareCursor(rq.ReplyRequest): ... + +def compare_cursor(self: Display | resource.Resource, cursor: int) -> int: ... + +class FakeInput(rq.Request): ... + +def fake_input( + self: Display | resource.Resource, event_type: int, detail: int = 0, time: int = 0, root: int = 0, x: int = 0, y: int = 0 +) -> None: ... + +class GrabControl(rq.Request): ... + +def grab_control(self: Display | resource.Resource, impervious: bool) -> None: ... +def init(disp: Display, info: Unused) -> None: ... diff --git a/stubs/python-xlib/Xlib/keysymdef/__init__.pyi b/stubs/python-xlib/Xlib/keysymdef/__init__.pyi new file mode 100644 index 000000000000..ca535d0ea135 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/__init__.pyi @@ -0,0 +1,43 @@ +from Xlib.keysymdef import ( + apl as apl, + arabic as arabic, + cyrillic as cyrillic, + greek as greek, + hebrew as hebrew, + katakana as katakana, + korean as korean, + latin1 as latin1, + latin2 as latin2, + latin3 as latin3, + latin4 as latin4, + miscellany as miscellany, + publishing as publishing, + special as special, + technical as technical, + thai as thai, + xf86 as xf86, + xk3270 as xk3270, + xkb as xkb, +) + +__all__ = [ + "apl", + "arabic", + "cyrillic", + "greek", + "hebrew", + "katakana", + "korean", + "latin1", + "latin2", + "latin3", + "latin4", + "miscellany", + "publishing", + "special", + "technical", + "thai", + "xf86", + "xk3270", + "xkb", +] diff --git a/stubs/python-xlib/Xlib/keysymdef/apl.pyi b/stubs/python-xlib/Xlib/keysymdef/apl.pyi new file mode 100644 index 000000000000..869a0592657b --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/apl.pyi @@ -0,0 +1,21 @@ +from typing import Final + +XK_leftcaret: Final = 0xBA3 +XK_rightcaret: Final = 0xBA6 +XK_downcaret: Final = 0xBA8 +XK_upcaret: Final = 0xBA9 +XK_overbar: Final = 0xBC0 +XK_downtack: Final = 0xBC2 +XK_upshoe: Final = 0xBC3 +XK_downstile: Final = 0xBC4 +XK_underbar: Final = 0xBC6 +XK_jot: Final = 0xBCA +XK_quad: Final = 0xBCC +XK_uptack: Final = 0xBCE +XK_circle: Final = 0xBCF +XK_upstile: Final = 0xBD3 +XK_downshoe: Final = 0xBD6 +XK_rightshoe: Final = 0xBD8 +XK_leftshoe: Final = 0xBDA +XK_lefttack: Final = 0xBDC +XK_righttack: Final = 0xBFC diff --git a/stubs/python-xlib/Xlib/keysymdef/arabic.pyi b/stubs/python-xlib/Xlib/keysymdef/arabic.pyi new file mode 100644 index 000000000000..6823007c72ec --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/arabic.pyi @@ -0,0 +1,52 @@ +from typing import Final + +XK_Arabic_comma: Final = 0x5AC +XK_Arabic_semicolon: Final = 0x5BB +XK_Arabic_question_mark: Final = 0x5BF +XK_Arabic_hamza: Final = 0x5C1 +XK_Arabic_maddaonalef: Final = 0x5C2 +XK_Arabic_hamzaonalef: Final = 0x5C3 +XK_Arabic_hamzaonwaw: Final = 0x5C4 +XK_Arabic_hamzaunderalef: Final = 0x5C5 +XK_Arabic_hamzaonyeh: Final = 0x5C6 +XK_Arabic_alef: Final = 0x5C7 +XK_Arabic_beh: Final = 0x5C8 +XK_Arabic_tehmarbuta: Final = 0x5C9 +XK_Arabic_teh: Final = 0x5CA +XK_Arabic_theh: Final = 0x5CB +XK_Arabic_jeem: Final = 0x5CC +XK_Arabic_hah: Final = 0x5CD +XK_Arabic_khah: Final = 0x5CE +XK_Arabic_dal: Final = 0x5CF +XK_Arabic_thal: Final = 0x5D0 +XK_Arabic_ra: Final = 0x5D1 +XK_Arabic_zain: Final = 0x5D2 +XK_Arabic_seen: Final = 0x5D3 +XK_Arabic_sheen: Final = 0x5D4 +XK_Arabic_sad: Final = 0x5D5 +XK_Arabic_dad: Final = 0x5D6 +XK_Arabic_tah: Final = 0x5D7 +XK_Arabic_zah: Final = 0x5D8 +XK_Arabic_ain: Final = 0x5D9 +XK_Arabic_ghain: Final = 0x5DA +XK_Arabic_tatweel: Final = 0x5E0 +XK_Arabic_feh: Final = 0x5E1 +XK_Arabic_qaf: Final = 0x5E2 +XK_Arabic_kaf: Final = 0x5E3 +XK_Arabic_lam: Final = 0x5E4 +XK_Arabic_meem: Final = 0x5E5 +XK_Arabic_noon: Final = 0x5E6 +XK_Arabic_ha: Final = 0x5E7 +XK_Arabic_heh: Final = 0x5E7 +XK_Arabic_waw: Final = 0x5E8 +XK_Arabic_alefmaksura: Final = 0x5E9 +XK_Arabic_yeh: Final = 0x5EA +XK_Arabic_fathatan: Final = 0x5EB +XK_Arabic_dammatan: Final = 0x5EC +XK_Arabic_kasratan: Final = 0x5ED +XK_Arabic_fatha: Final = 0x5EE +XK_Arabic_damma: Final = 0x5EF +XK_Arabic_kasra: Final = 0x5F0 +XK_Arabic_shadda: Final = 0x5F1 +XK_Arabic_sukun: Final = 0x5F2 +XK_Arabic_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi b/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi new file mode 100644 index 000000000000..4ad19a16ea64 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/cyrillic.pyi @@ -0,0 +1,109 @@ +from typing import Final + +XK_Serbian_dje: Final = 0x6A1 +XK_Macedonia_gje: Final = 0x6A2 +XK_Cyrillic_io: Final = 0x6A3 +XK_Ukrainian_ie: Final = 0x6A4 +XK_Ukranian_je: Final = 0x6A4 +XK_Macedonia_dse: Final = 0x6A5 +XK_Ukrainian_i: Final = 0x6A6 +XK_Ukranian_i: Final = 0x6A6 +XK_Ukrainian_yi: Final = 0x6A7 +XK_Ukranian_yi: Final = 0x6A7 +XK_Cyrillic_je: Final = 0x6A8 +XK_Serbian_je: Final = 0x6A8 +XK_Cyrillic_lje: Final = 0x6A9 +XK_Serbian_lje: Final = 0x6A9 +XK_Cyrillic_nje: Final = 0x6AA +XK_Serbian_nje: Final = 0x6AA +XK_Serbian_tshe: Final = 0x6AB +XK_Macedonia_kje: Final = 0x6AC +XK_Byelorussian_shortu: Final = 0x6AE +XK_Cyrillic_dzhe: Final = 0x6AF +XK_Serbian_dze: Final = 0x6AF +XK_numerosign: Final = 0x6B0 +XK_Serbian_DJE: Final = 0x6B1 +XK_Macedonia_GJE: Final = 0x6B2 +XK_Cyrillic_IO: Final = 0x6B3 +XK_Ukrainian_IE: Final = 0x6B4 +XK_Ukranian_JE: Final = 0x6B4 +XK_Macedonia_DSE: Final = 0x6B5 +XK_Ukrainian_I: Final = 0x6B6 +XK_Ukranian_I: Final = 0x6B6 +XK_Ukrainian_YI: Final = 0x6B7 +XK_Ukranian_YI: Final = 0x6B7 +XK_Cyrillic_JE: Final = 0x6B8 +XK_Serbian_JE: Final = 0x6B8 +XK_Cyrillic_LJE: Final = 0x6B9 +XK_Serbian_LJE: Final = 0x6B9 +XK_Cyrillic_NJE: Final = 0x6BA +XK_Serbian_NJE: Final = 0x6BA +XK_Serbian_TSHE: Final = 0x6BB +XK_Macedonia_KJE: Final = 0x6BC +XK_Byelorussian_SHORTU: Final = 0x6BE +XK_Cyrillic_DZHE: Final = 0x6BF +XK_Serbian_DZE: Final = 0x6BF +XK_Cyrillic_yu: Final = 0x6C0 +XK_Cyrillic_a: Final = 0x6C1 +XK_Cyrillic_be: Final = 0x6C2 +XK_Cyrillic_tse: Final = 0x6C3 +XK_Cyrillic_de: Final = 0x6C4 +XK_Cyrillic_ie: Final = 0x6C5 +XK_Cyrillic_ef: Final = 0x6C6 +XK_Cyrillic_ghe: Final = 0x6C7 +XK_Cyrillic_ha: Final = 0x6C8 +XK_Cyrillic_i: Final = 0x6C9 +XK_Cyrillic_shorti: Final = 0x6CA +XK_Cyrillic_ka: Final = 0x6CB +XK_Cyrillic_el: Final = 0x6CC +XK_Cyrillic_em: Final = 0x6CD +XK_Cyrillic_en: Final = 0x6CE +XK_Cyrillic_o: Final = 0x6CF +XK_Cyrillic_pe: Final = 0x6D0 +XK_Cyrillic_ya: Final = 0x6D1 +XK_Cyrillic_er: Final = 0x6D2 +XK_Cyrillic_es: Final = 0x6D3 +XK_Cyrillic_te: Final = 0x6D4 +XK_Cyrillic_u: Final = 0x6D5 +XK_Cyrillic_zhe: Final = 0x6D6 +XK_Cyrillic_ve: Final = 0x6D7 +XK_Cyrillic_softsign: Final = 0x6D8 +XK_Cyrillic_yeru: Final = 0x6D9 +XK_Cyrillic_ze: Final = 0x6DA +XK_Cyrillic_sha: Final = 0x6DB +XK_Cyrillic_e: Final = 0x6DC +XK_Cyrillic_shcha: Final = 0x6DD +XK_Cyrillic_che: Final = 0x6DE +XK_Cyrillic_hardsign: Final = 0x6DF +XK_Cyrillic_YU: Final = 0x6E0 +XK_Cyrillic_A: Final = 0x6E1 +XK_Cyrillic_BE: Final = 0x6E2 +XK_Cyrillic_TSE: Final = 0x6E3 +XK_Cyrillic_DE: Final = 0x6E4 +XK_Cyrillic_IE: Final = 0x6E5 +XK_Cyrillic_EF: Final = 0x6E6 +XK_Cyrillic_GHE: Final = 0x6E7 +XK_Cyrillic_HA: Final = 0x6E8 +XK_Cyrillic_I: Final = 0x6E9 +XK_Cyrillic_SHORTI: Final = 0x6EA +XK_Cyrillic_KA: Final = 0x6EB +XK_Cyrillic_EL: Final = 0x6EC +XK_Cyrillic_EM: Final = 0x6ED +XK_Cyrillic_EN: Final = 0x6EE +XK_Cyrillic_O: Final = 0x6EF +XK_Cyrillic_PE: Final = 0x6F0 +XK_Cyrillic_YA: Final = 0x6F1 +XK_Cyrillic_ER: Final = 0x6F2 +XK_Cyrillic_ES: Final = 0x6F3 +XK_Cyrillic_TE: Final = 0x6F4 +XK_Cyrillic_U: Final = 0x6F5 +XK_Cyrillic_ZHE: Final = 0x6F6 +XK_Cyrillic_VE: Final = 0x6F7 +XK_Cyrillic_SOFTSIGN: Final = 0x6F8 +XK_Cyrillic_YERU: Final = 0x6F9 +XK_Cyrillic_ZE: Final = 0x6FA +XK_Cyrillic_SHA: Final = 0x6FB +XK_Cyrillic_E: Final = 0x6FC +XK_Cyrillic_SHCHA: Final = 0x6FD +XK_Cyrillic_CHE: Final = 0x6FE +XK_Cyrillic_HARDSIGN: Final = 0x6FF diff --git a/stubs/python-xlib/Xlib/keysymdef/greek.pyi b/stubs/python-xlib/Xlib/keysymdef/greek.pyi new file mode 100644 index 000000000000..2da0ef6907e3 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/greek.pyi @@ -0,0 +1,76 @@ +from typing import Final + +XK_Greek_ALPHAaccent: Final = 0x7A1 +XK_Greek_EPSILONaccent: Final = 0x7A2 +XK_Greek_ETAaccent: Final = 0x7A3 +XK_Greek_IOTAaccent: Final = 0x7A4 +XK_Greek_IOTAdiaeresis: Final = 0x7A5 +XK_Greek_OMICRONaccent: Final = 0x7A7 +XK_Greek_UPSILONaccent: Final = 0x7A8 +XK_Greek_UPSILONdieresis: Final = 0x7A9 +XK_Greek_OMEGAaccent: Final = 0x7AB +XK_Greek_accentdieresis: Final = 0x7AE +XK_Greek_horizbar: Final = 0x7AF +XK_Greek_alphaaccent: Final = 0x7B1 +XK_Greek_epsilonaccent: Final = 0x7B2 +XK_Greek_etaaccent: Final = 0x7B3 +XK_Greek_iotaaccent: Final = 0x7B4 +XK_Greek_iotadieresis: Final = 0x7B5 +XK_Greek_iotaaccentdieresis: Final = 0x7B6 +XK_Greek_omicronaccent: Final = 0x7B7 +XK_Greek_upsilonaccent: Final = 0x7B8 +XK_Greek_upsilondieresis: Final = 0x7B9 +XK_Greek_upsilonaccentdieresis: Final = 0x7BA +XK_Greek_omegaaccent: Final = 0x7BB +XK_Greek_ALPHA: Final = 0x7C1 +XK_Greek_BETA: Final = 0x7C2 +XK_Greek_GAMMA: Final = 0x7C3 +XK_Greek_DELTA: Final = 0x7C4 +XK_Greek_EPSILON: Final = 0x7C5 +XK_Greek_ZETA: Final = 0x7C6 +XK_Greek_ETA: Final = 0x7C7 +XK_Greek_THETA: Final = 0x7C8 +XK_Greek_IOTA: Final = 0x7C9 +XK_Greek_KAPPA: Final = 0x7CA +XK_Greek_LAMDA: Final = 0x7CB +XK_Greek_LAMBDA: Final = 0x7CB +XK_Greek_MU: Final = 0x7CC +XK_Greek_NU: Final = 0x7CD +XK_Greek_XI: Final = 0x7CE +XK_Greek_OMICRON: Final = 0x7CF +XK_Greek_PI: Final = 0x7D0 +XK_Greek_RHO: Final = 0x7D1 +XK_Greek_SIGMA: Final = 0x7D2 +XK_Greek_TAU: Final = 0x7D4 +XK_Greek_UPSILON: Final = 0x7D5 +XK_Greek_PHI: Final = 0x7D6 +XK_Greek_CHI: Final = 0x7D7 +XK_Greek_PSI: Final = 0x7D8 +XK_Greek_OMEGA: Final = 0x7D9 +XK_Greek_alpha: Final = 0x7E1 +XK_Greek_beta: Final = 0x7E2 +XK_Greek_gamma: Final = 0x7E3 +XK_Greek_delta: Final = 0x7E4 +XK_Greek_epsilon: Final = 0x7E5 +XK_Greek_zeta: Final = 0x7E6 +XK_Greek_eta: Final = 0x7E7 +XK_Greek_theta: Final = 0x7E8 +XK_Greek_iota: Final = 0x7E9 +XK_Greek_kappa: Final = 0x7EA +XK_Greek_lamda: Final = 0x7EB +XK_Greek_lambda: Final = 0x7EB +XK_Greek_mu: Final = 0x7EC +XK_Greek_nu: Final = 0x7ED +XK_Greek_xi: Final = 0x7EE +XK_Greek_omicron: Final = 0x7EF +XK_Greek_pi: Final = 0x7F0 +XK_Greek_rho: Final = 0x7F1 +XK_Greek_sigma: Final = 0x7F2 +XK_Greek_finalsmallsigma: Final = 0x7F3 +XK_Greek_tau: Final = 0x7F4 +XK_Greek_upsilon: Final = 0x7F5 +XK_Greek_phi: Final = 0x7F6 +XK_Greek_chi: Final = 0x7F7 +XK_Greek_psi: Final = 0x7F8 +XK_Greek_omega: Final = 0x7F9 +XK_Greek_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi b/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi new file mode 100644 index 000000000000..a5db68c6c317 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/hebrew.pyi @@ -0,0 +1,42 @@ +from typing import Final + +XK_hebrew_doublelowline: Final = 0xCDF +XK_hebrew_aleph: Final = 0xCE0 +XK_hebrew_bet: Final = 0xCE1 +XK_hebrew_beth: Final = 0xCE1 +XK_hebrew_gimel: Final = 0xCE2 +XK_hebrew_gimmel: Final = 0xCE2 +XK_hebrew_dalet: Final = 0xCE3 +XK_hebrew_daleth: Final = 0xCE3 +XK_hebrew_he: Final = 0xCE4 +XK_hebrew_waw: Final = 0xCE5 +XK_hebrew_zain: Final = 0xCE6 +XK_hebrew_zayin: Final = 0xCE6 +XK_hebrew_chet: Final = 0xCE7 +XK_hebrew_het: Final = 0xCE7 +XK_hebrew_tet: Final = 0xCE8 +XK_hebrew_teth: Final = 0xCE8 +XK_hebrew_yod: Final = 0xCE9 +XK_hebrew_finalkaph: Final = 0xCEA +XK_hebrew_kaph: Final = 0xCEB +XK_hebrew_lamed: Final = 0xCEC +XK_hebrew_finalmem: Final = 0xCED +XK_hebrew_mem: Final = 0xCEE +XK_hebrew_finalnun: Final = 0xCEF +XK_hebrew_nun: Final = 0xCF0 +XK_hebrew_samech: Final = 0xCF1 +XK_hebrew_samekh: Final = 0xCF1 +XK_hebrew_ayin: Final = 0xCF2 +XK_hebrew_finalpe: Final = 0xCF3 +XK_hebrew_pe: Final = 0xCF4 +XK_hebrew_finalzade: Final = 0xCF5 +XK_hebrew_finalzadi: Final = 0xCF5 +XK_hebrew_zade: Final = 0xCF6 +XK_hebrew_zadi: Final = 0xCF6 +XK_hebrew_qoph: Final = 0xCF7 +XK_hebrew_kuf: Final = 0xCF7 +XK_hebrew_resh: Final = 0xCF8 +XK_hebrew_shin: Final = 0xCF9 +XK_hebrew_taw: Final = 0xCFA +XK_hebrew_taf: Final = 0xCFA +XK_Hebrew_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/katakana.pyi b/stubs/python-xlib/Xlib/keysymdef/katakana.pyi new file mode 100644 index 000000000000..bf83f8c053e6 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/katakana.pyi @@ -0,0 +1,72 @@ +from typing import Final + +XK_overline: Final = 0x47E +XK_kana_fullstop: Final = 0x4A1 +XK_kana_openingbracket: Final = 0x4A2 +XK_kana_closingbracket: Final = 0x4A3 +XK_kana_comma: Final = 0x4A4 +XK_kana_conjunctive: Final = 0x4A5 +XK_kana_middledot: Final = 0x4A5 +XK_kana_WO: Final = 0x4A6 +XK_kana_a: Final = 0x4A7 +XK_kana_i: Final = 0x4A8 +XK_kana_u: Final = 0x4A9 +XK_kana_e: Final = 0x4AA +XK_kana_o: Final = 0x4AB +XK_kana_ya: Final = 0x4AC +XK_kana_yu: Final = 0x4AD +XK_kana_yo: Final = 0x4AE +XK_kana_tsu: Final = 0x4AF +XK_kana_tu: Final = 0x4AF +XK_prolongedsound: Final = 0x4B0 +XK_kana_A: Final = 0x4B1 +XK_kana_I: Final = 0x4B2 +XK_kana_U: Final = 0x4B3 +XK_kana_E: Final = 0x4B4 +XK_kana_O: Final = 0x4B5 +XK_kana_KA: Final = 0x4B6 +XK_kana_KI: Final = 0x4B7 +XK_kana_KU: Final = 0x4B8 +XK_kana_KE: Final = 0x4B9 +XK_kana_KO: Final = 0x4BA +XK_kana_SA: Final = 0x4BB +XK_kana_SHI: Final = 0x4BC +XK_kana_SU: Final = 0x4BD +XK_kana_SE: Final = 0x4BE +XK_kana_SO: Final = 0x4BF +XK_kana_TA: Final = 0x4C0 +XK_kana_CHI: Final = 0x4C1 +XK_kana_TI: Final = 0x4C1 +XK_kana_TSU: Final = 0x4C2 +XK_kana_TU: Final = 0x4C2 +XK_kana_TE: Final = 0x4C3 +XK_kana_TO: Final = 0x4C4 +XK_kana_NA: Final = 0x4C5 +XK_kana_NI: Final = 0x4C6 +XK_kana_NU: Final = 0x4C7 +XK_kana_NE: Final = 0x4C8 +XK_kana_NO: Final = 0x4C9 +XK_kana_HA: Final = 0x4CA +XK_kana_HI: Final = 0x4CB +XK_kana_FU: Final = 0x4CC +XK_kana_HU: Final = 0x4CC +XK_kana_HE: Final = 0x4CD +XK_kana_HO: Final = 0x4CE +XK_kana_MA: Final = 0x4CF +XK_kana_MI: Final = 0x4D0 +XK_kana_MU: Final = 0x4D1 +XK_kana_ME: Final = 0x4D2 +XK_kana_MO: Final = 0x4D3 +XK_kana_YA: Final = 0x4D4 +XK_kana_YU: Final = 0x4D5 +XK_kana_YO: Final = 0x4D6 +XK_kana_RA: Final = 0x4D7 +XK_kana_RI: Final = 0x4D8 +XK_kana_RU: Final = 0x4D9 +XK_kana_RE: Final = 0x4DA +XK_kana_RO: Final = 0x4DB +XK_kana_WA: Final = 0x4DC +XK_kana_N: Final = 0x4DD +XK_voicedsound: Final = 0x4DE +XK_semivoicedsound: Final = 0x4DF +XK_kana_switch: Final = 0xFF7E diff --git a/stubs/python-xlib/Xlib/keysymdef/korean.pyi b/stubs/python-xlib/Xlib/keysymdef/korean.pyi new file mode 100644 index 000000000000..492965233730 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/korean.pyi @@ -0,0 +1,109 @@ +from typing import Final + +XK_Hangul: Final = 0xFF31 +XK_Hangul_Start: Final = 0xFF32 +XK_Hangul_End: Final = 0xFF33 +XK_Hangul_Hanja: Final = 0xFF34 +XK_Hangul_Jamo: Final = 0xFF35 +XK_Hangul_Romaja: Final = 0xFF36 +XK_Hangul_Codeinput: Final = 0xFF37 +XK_Hangul_Jeonja: Final = 0xFF38 +XK_Hangul_Banja: Final = 0xFF39 +XK_Hangul_PreHanja: Final = 0xFF3A +XK_Hangul_PostHanja: Final = 0xFF3B +XK_Hangul_SingleCandidate: Final = 0xFF3C +XK_Hangul_MultipleCandidate: Final = 0xFF3D +XK_Hangul_PreviousCandidate: Final = 0xFF3E +XK_Hangul_Special: Final = 0xFF3F +XK_Hangul_switch: Final = 0xFF7E +XK_Hangul_Kiyeog: Final = 0xEA1 +XK_Hangul_SsangKiyeog: Final = 0xEA2 +XK_Hangul_KiyeogSios: Final = 0xEA3 +XK_Hangul_Nieun: Final = 0xEA4 +XK_Hangul_NieunJieuj: Final = 0xEA5 +XK_Hangul_NieunHieuh: Final = 0xEA6 +XK_Hangul_Dikeud: Final = 0xEA7 +XK_Hangul_SsangDikeud: Final = 0xEA8 +XK_Hangul_Rieul: Final = 0xEA9 +XK_Hangul_RieulKiyeog: Final = 0xEAA +XK_Hangul_RieulMieum: Final = 0xEAB +XK_Hangul_RieulPieub: Final = 0xEAC +XK_Hangul_RieulSios: Final = 0xEAD +XK_Hangul_RieulTieut: Final = 0xEAE +XK_Hangul_RieulPhieuf: Final = 0xEAF +XK_Hangul_RieulHieuh: Final = 0xEB0 +XK_Hangul_Mieum: Final = 0xEB1 +XK_Hangul_Pieub: Final = 0xEB2 +XK_Hangul_SsangPieub: Final = 0xEB3 +XK_Hangul_PieubSios: Final = 0xEB4 +XK_Hangul_Sios: Final = 0xEB5 +XK_Hangul_SsangSios: Final = 0xEB6 +XK_Hangul_Ieung: Final = 0xEB7 +XK_Hangul_Jieuj: Final = 0xEB8 +XK_Hangul_SsangJieuj: Final = 0xEB9 +XK_Hangul_Cieuc: Final = 0xEBA +XK_Hangul_Khieuq: Final = 0xEBB +XK_Hangul_Tieut: Final = 0xEBC +XK_Hangul_Phieuf: Final = 0xEBD +XK_Hangul_Hieuh: Final = 0xEBE +XK_Hangul_A: Final = 0xEBF +XK_Hangul_AE: Final = 0xEC0 +XK_Hangul_YA: Final = 0xEC1 +XK_Hangul_YAE: Final = 0xEC2 +XK_Hangul_EO: Final = 0xEC3 +XK_Hangul_E: Final = 0xEC4 +XK_Hangul_YEO: Final = 0xEC5 +XK_Hangul_YE: Final = 0xEC6 +XK_Hangul_O: Final = 0xEC7 +XK_Hangul_WA: Final = 0xEC8 +XK_Hangul_WAE: Final = 0xEC9 +XK_Hangul_OE: Final = 0xECA +XK_Hangul_YO: Final = 0xECB +XK_Hangul_U: Final = 0xECC +XK_Hangul_WEO: Final = 0xECD +XK_Hangul_WE: Final = 0xECE +XK_Hangul_WI: Final = 0xECF +XK_Hangul_YU: Final = 0xED0 +XK_Hangul_EU: Final = 0xED1 +XK_Hangul_YI: Final = 0xED2 +XK_Hangul_I: Final = 0xED3 +XK_Hangul_J_Kiyeog: Final = 0xED4 +XK_Hangul_J_SsangKiyeog: Final = 0xED5 +XK_Hangul_J_KiyeogSios: Final = 0xED6 +XK_Hangul_J_Nieun: Final = 0xED7 +XK_Hangul_J_NieunJieuj: Final = 0xED8 +XK_Hangul_J_NieunHieuh: Final = 0xED9 +XK_Hangul_J_Dikeud: Final = 0xEDA +XK_Hangul_J_Rieul: Final = 0xEDB +XK_Hangul_J_RieulKiyeog: Final = 0xEDC +XK_Hangul_J_RieulMieum: Final = 0xEDD +XK_Hangul_J_RieulPieub: Final = 0xEDE +XK_Hangul_J_RieulSios: Final = 0xEDF +XK_Hangul_J_RieulTieut: Final = 0xEE0 +XK_Hangul_J_RieulPhieuf: Final = 0xEE1 +XK_Hangul_J_RieulHieuh: Final = 0xEE2 +XK_Hangul_J_Mieum: Final = 0xEE3 +XK_Hangul_J_Pieub: Final = 0xEE4 +XK_Hangul_J_PieubSios: Final = 0xEE5 +XK_Hangul_J_Sios: Final = 0xEE6 +XK_Hangul_J_SsangSios: Final = 0xEE7 +XK_Hangul_J_Ieung: Final = 0xEE8 +XK_Hangul_J_Jieuj: Final = 0xEE9 +XK_Hangul_J_Cieuc: Final = 0xEEA +XK_Hangul_J_Khieuq: Final = 0xEEB +XK_Hangul_J_Tieut: Final = 0xEEC +XK_Hangul_J_Phieuf: Final = 0xEED +XK_Hangul_J_Hieuh: Final = 0xEEE +XK_Hangul_RieulYeorinHieuh: Final = 0xEEF +XK_Hangul_SunkyeongeumMieum: Final = 0xEF0 +XK_Hangul_SunkyeongeumPieub: Final = 0xEF1 +XK_Hangul_PanSios: Final = 0xEF2 +XK_Hangul_KkogjiDalrinIeung: Final = 0xEF3 +XK_Hangul_SunkyeongeumPhieuf: Final = 0xEF4 +XK_Hangul_YeorinHieuh: Final = 0xEF5 +XK_Hangul_AraeA: Final = 0xEF6 +XK_Hangul_AraeAE: Final = 0xEF7 +XK_Hangul_J_PanSios: Final = 0xEF8 +XK_Hangul_J_KkogjiDalrinIeung: Final = 0xEF9 +XK_Hangul_J_YeorinHieuh: Final = 0xEFA +XK_Korean_Won: Final = 0xEFF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin1.pyi b/stubs/python-xlib/Xlib/keysymdef/latin1.pyi new file mode 100644 index 000000000000..2659a0a55b63 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin1.pyi @@ -0,0 +1,197 @@ +from typing import Final + +XK_space: Final = 0x020 +XK_exclam: Final = 0x021 +XK_quotedbl: Final = 0x022 +XK_numbersign: Final = 0x023 +XK_dollar: Final = 0x024 +XK_percent: Final = 0x025 +XK_ampersand: Final = 0x026 +XK_apostrophe: Final = 0x027 +XK_quoteright: Final = 0x027 +XK_parenleft: Final = 0x028 +XK_parenright: Final = 0x029 +XK_asterisk: Final = 0x02A +XK_plus: Final = 0x02B +XK_comma: Final = 0x02C +XK_minus: Final = 0x02D +XK_period: Final = 0x02E +XK_slash: Final = 0x02F +XK_0: Final = 0x030 +XK_1: Final = 0x031 +XK_2: Final = 0x032 +XK_3: Final = 0x033 +XK_4: Final = 0x034 +XK_5: Final = 0x035 +XK_6: Final = 0x036 +XK_7: Final = 0x037 +XK_8: Final = 0x038 +XK_9: Final = 0x039 +XK_colon: Final = 0x03A +XK_semicolon: Final = 0x03B +XK_less: Final = 0x03C +XK_equal: Final = 0x03D +XK_greater: Final = 0x03E +XK_question: Final = 0x03F +XK_at: Final = 0x040 +XK_A: Final = 0x041 +XK_B: Final = 0x042 +XK_C: Final = 0x043 +XK_D: Final = 0x044 +XK_E: Final = 0x045 +XK_F: Final = 0x046 +XK_G: Final = 0x047 +XK_H: Final = 0x048 +XK_I: Final = 0x049 +XK_J: Final = 0x04A +XK_K: Final = 0x04B +XK_L: Final = 0x04C +XK_M: Final = 0x04D +XK_N: Final = 0x04E +XK_O: Final = 0x04F +XK_P: Final = 0x050 +XK_Q: Final = 0x051 +XK_R: Final = 0x052 +XK_S: Final = 0x053 +XK_T: Final = 0x054 +XK_U: Final = 0x055 +XK_V: Final = 0x056 +XK_W: Final = 0x057 +XK_X: Final = 0x058 +XK_Y: Final = 0x059 +XK_Z: Final = 0x05A +XK_bracketleft: Final = 0x05B +XK_backslash: Final = 0x05C +XK_bracketright: Final = 0x05D +XK_asciicircum: Final = 0x05E +XK_underscore: Final = 0x05F +XK_grave: Final = 0x060 +XK_quoteleft: Final = 0x060 +XK_a: Final = 0x061 +XK_b: Final = 0x062 +XK_c: Final = 0x063 +XK_d: Final = 0x064 +XK_e: Final = 0x065 +XK_f: Final = 0x066 +XK_g: Final = 0x067 +XK_h: Final = 0x068 +XK_i: Final = 0x069 +XK_j: Final = 0x06A +XK_k: Final = 0x06B +XK_l: Final = 0x06C +XK_m: Final = 0x06D +XK_n: Final = 0x06E +XK_o: Final = 0x06F +XK_p: Final = 0x070 +XK_q: Final = 0x071 +XK_r: Final = 0x072 +XK_s: Final = 0x073 +XK_t: Final = 0x074 +XK_u: Final = 0x075 +XK_v: Final = 0x076 +XK_w: Final = 0x077 +XK_x: Final = 0x078 +XK_y: Final = 0x079 +XK_z: Final = 0x07A +XK_braceleft: Final = 0x07B +XK_bar: Final = 0x07C +XK_braceright: Final = 0x07D +XK_asciitilde: Final = 0x07E +XK_nobreakspace: Final = 0x0A0 +XK_exclamdown: Final = 0x0A1 +XK_cent: Final = 0x0A2 +XK_sterling: Final = 0x0A3 +XK_currency: Final = 0x0A4 +XK_yen: Final = 0x0A5 +XK_brokenbar: Final = 0x0A6 +XK_section: Final = 0x0A7 +XK_diaeresis: Final = 0x0A8 +XK_copyright: Final = 0x0A9 +XK_ordfeminine: Final = 0x0AA +XK_guillemotleft: Final = 0x0AB +XK_notsign: Final = 0x0AC +XK_hyphen: Final = 0x0AD +XK_registered: Final = 0x0AE +XK_macron: Final = 0x0AF +XK_degree: Final = 0x0B0 +XK_plusminus: Final = 0x0B1 +XK_twosuperior: Final = 0x0B2 +XK_threesuperior: Final = 0x0B3 +XK_acute: Final = 0x0B4 +XK_mu: Final = 0x0B5 +XK_paragraph: Final = 0x0B6 +XK_periodcentered: Final = 0x0B7 +XK_cedilla: Final = 0x0B8 +XK_onesuperior: Final = 0x0B9 +XK_masculine: Final = 0x0BA +XK_guillemotright: Final = 0x0BB +XK_onequarter: Final = 0x0BC +XK_onehalf: Final = 0x0BD +XK_threequarters: Final = 0x0BE +XK_questiondown: Final = 0x0BF +XK_Agrave: Final = 0x0C0 +XK_Aacute: Final = 0x0C1 +XK_Acircumflex: Final = 0x0C2 +XK_Atilde: Final = 0x0C3 +XK_Adiaeresis: Final = 0x0C4 +XK_Aring: Final = 0x0C5 +XK_AE: Final = 0x0C6 +XK_Ccedilla: Final = 0x0C7 +XK_Egrave: Final = 0x0C8 +XK_Eacute: Final = 0x0C9 +XK_Ecircumflex: Final = 0x0CA +XK_Ediaeresis: Final = 0x0CB +XK_Igrave: Final = 0x0CC +XK_Iacute: Final = 0x0CD +XK_Icircumflex: Final = 0x0CE +XK_Idiaeresis: Final = 0x0CF +XK_ETH: Final = 0x0D0 +XK_Eth: Final = 0x0D0 +XK_Ntilde: Final = 0x0D1 +XK_Ograve: Final = 0x0D2 +XK_Oacute: Final = 0x0D3 +XK_Ocircumflex: Final = 0x0D4 +XK_Otilde: Final = 0x0D5 +XK_Odiaeresis: Final = 0x0D6 +XK_multiply: Final = 0x0D7 +XK_Ooblique: Final = 0x0D8 +XK_Ugrave: Final = 0x0D9 +XK_Uacute: Final = 0x0DA +XK_Ucircumflex: Final = 0x0DB +XK_Udiaeresis: Final = 0x0DC +XK_Yacute: Final = 0x0DD +XK_THORN: Final = 0x0DE +XK_Thorn: Final = 0x0DE +XK_ssharp: Final = 0x0DF +XK_agrave: Final = 0x0E0 +XK_aacute: Final = 0x0E1 +XK_acircumflex: Final = 0x0E2 +XK_atilde: Final = 0x0E3 +XK_adiaeresis: Final = 0x0E4 +XK_aring: Final = 0x0E5 +XK_ae: Final = 0x0E6 +XK_ccedilla: Final = 0x0E7 +XK_egrave: Final = 0x0E8 +XK_eacute: Final = 0x0E9 +XK_ecircumflex: Final = 0x0EA +XK_ediaeresis: Final = 0x0EB +XK_igrave: Final = 0x0EC +XK_iacute: Final = 0x0ED +XK_icircumflex: Final = 0x0EE +XK_idiaeresis: Final = 0x0EF +XK_eth: Final = 0x0F0 +XK_ntilde: Final = 0x0F1 +XK_ograve: Final = 0x0F2 +XK_oacute: Final = 0x0F3 +XK_ocircumflex: Final = 0x0F4 +XK_otilde: Final = 0x0F5 +XK_odiaeresis: Final = 0x0F6 +XK_division: Final = 0x0F7 +XK_oslash: Final = 0x0F8 +XK_ugrave: Final = 0x0F9 +XK_uacute: Final = 0x0FA +XK_ucircumflex: Final = 0x0FB +XK_udiaeresis: Final = 0x0FC +XK_yacute: Final = 0x0FD +XK_thorn: Final = 0x0FE +XK_ydiaeresis: Final = 0x0FF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin2.pyi b/stubs/python-xlib/Xlib/keysymdef/latin2.pyi new file mode 100644 index 000000000000..f867732c6158 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin2.pyi @@ -0,0 +1,59 @@ +from typing import Final + +XK_Aogonek: Final = 0x1A1 +XK_breve: Final = 0x1A2 +XK_Lstroke: Final = 0x1A3 +XK_Lcaron: Final = 0x1A5 +XK_Sacute: Final = 0x1A6 +XK_Scaron: Final = 0x1A9 +XK_Scedilla: Final = 0x1AA +XK_Tcaron: Final = 0x1AB +XK_Zacute: Final = 0x1AC +XK_Zcaron: Final = 0x1AE +XK_Zabovedot: Final = 0x1AF +XK_aogonek: Final = 0x1B1 +XK_ogonek: Final = 0x1B2 +XK_lstroke: Final = 0x1B3 +XK_lcaron: Final = 0x1B5 +XK_sacute: Final = 0x1B6 +XK_caron: Final = 0x1B7 +XK_scaron: Final = 0x1B9 +XK_scedilla: Final = 0x1BA +XK_tcaron: Final = 0x1BB +XK_zacute: Final = 0x1BC +XK_doubleacute: Final = 0x1BD +XK_zcaron: Final = 0x1BE +XK_zabovedot: Final = 0x1BF +XK_Racute: Final = 0x1C0 +XK_Abreve: Final = 0x1C3 +XK_Lacute: Final = 0x1C5 +XK_Cacute: Final = 0x1C6 +XK_Ccaron: Final = 0x1C8 +XK_Eogonek: Final = 0x1CA +XK_Ecaron: Final = 0x1CC +XK_Dcaron: Final = 0x1CF +XK_Dstroke: Final = 0x1D0 +XK_Nacute: Final = 0x1D1 +XK_Ncaron: Final = 0x1D2 +XK_Odoubleacute: Final = 0x1D5 +XK_Rcaron: Final = 0x1D8 +XK_Uring: Final = 0x1D9 +XK_Udoubleacute: Final = 0x1DB +XK_Tcedilla: Final = 0x1DE +XK_racute: Final = 0x1E0 +XK_abreve: Final = 0x1E3 +XK_lacute: Final = 0x1E5 +XK_cacute: Final = 0x1E6 +XK_ccaron: Final = 0x1E8 +XK_eogonek: Final = 0x1EA +XK_ecaron: Final = 0x1EC +XK_dcaron: Final = 0x1EF +XK_dstroke: Final = 0x1F0 +XK_nacute: Final = 0x1F1 +XK_ncaron: Final = 0x1F2 +XK_odoubleacute: Final = 0x1F5 +XK_udoubleacute: Final = 0x1FB +XK_rcaron: Final = 0x1F8 +XK_uring: Final = 0x1F9 +XK_tcedilla: Final = 0x1FE +XK_abovedot: Final = 0x1FF diff --git a/stubs/python-xlib/Xlib/keysymdef/latin3.pyi b/stubs/python-xlib/Xlib/keysymdef/latin3.pyi new file mode 100644 index 000000000000..acd840e78847 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin3.pyi @@ -0,0 +1,24 @@ +from typing import Final + +XK_Hstroke: Final = 0x2A1 +XK_Hcircumflex: Final = 0x2A6 +XK_Iabovedot: Final = 0x2A9 +XK_Gbreve: Final = 0x2AB +XK_Jcircumflex: Final = 0x2AC +XK_hstroke: Final = 0x2B1 +XK_hcircumflex: Final = 0x2B6 +XK_idotless: Final = 0x2B9 +XK_gbreve: Final = 0x2BB +XK_jcircumflex: Final = 0x2BC +XK_Cabovedot: Final = 0x2C5 +XK_Ccircumflex: Final = 0x2C6 +XK_Gabovedot: Final = 0x2D5 +XK_Gcircumflex: Final = 0x2D8 +XK_Ubreve: Final = 0x2DD +XK_Scircumflex: Final = 0x2DE +XK_cabovedot: Final = 0x2E5 +XK_ccircumflex: Final = 0x2E6 +XK_gabovedot: Final = 0x2F5 +XK_gcircumflex: Final = 0x2F8 +XK_ubreve: Final = 0x2FD +XK_scircumflex: Final = 0x2FE diff --git a/stubs/python-xlib/Xlib/keysymdef/latin4.pyi b/stubs/python-xlib/Xlib/keysymdef/latin4.pyi new file mode 100644 index 000000000000..5b7a58c9f8d7 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/latin4.pyi @@ -0,0 +1,38 @@ +from typing import Final + +XK_kra: Final = 0x3A2 +XK_kappa: Final = 0x3A2 +XK_Rcedilla: Final = 0x3A3 +XK_Itilde: Final = 0x3A5 +XK_Lcedilla: Final = 0x3A6 +XK_Emacron: Final = 0x3AA +XK_Gcedilla: Final = 0x3AB +XK_Tslash: Final = 0x3AC +XK_rcedilla: Final = 0x3B3 +XK_itilde: Final = 0x3B5 +XK_lcedilla: Final = 0x3B6 +XK_emacron: Final = 0x3BA +XK_gcedilla: Final = 0x3BB +XK_tslash: Final = 0x3BC +XK_ENG: Final = 0x3BD +XK_eng: Final = 0x3BF +XK_Amacron: Final = 0x3C0 +XK_Iogonek: Final = 0x3C7 +XK_Eabovedot: Final = 0x3CC +XK_Imacron: Final = 0x3CF +XK_Ncedilla: Final = 0x3D1 +XK_Omacron: Final = 0x3D2 +XK_Kcedilla: Final = 0x3D3 +XK_Uogonek: Final = 0x3D9 +XK_Utilde: Final = 0x3DD +XK_Umacron: Final = 0x3DE +XK_amacron: Final = 0x3E0 +XK_iogonek: Final = 0x3E7 +XK_eabovedot: Final = 0x3EC +XK_imacron: Final = 0x3EF +XK_ncedilla: Final = 0x3F1 +XK_omacron: Final = 0x3F2 +XK_kcedilla: Final = 0x3F3 +XK_uogonek: Final = 0x3F9 +XK_utilde: Final = 0x3FD +XK_umacron: Final = 0x3FE diff --git a/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi b/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi new file mode 100644 index 000000000000..70b11a05430d --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/miscellany.pyi @@ -0,0 +1,171 @@ +from typing import Final + +XK_BackSpace: Final = 0xFF08 +XK_Tab: Final = 0xFF09 +XK_Linefeed: Final = 0xFF0A +XK_Clear: Final = 0xFF0B +XK_Return: Final = 0xFF0D +XK_Pause: Final = 0xFF13 +XK_Scroll_Lock: Final = 0xFF14 +XK_Sys_Req: Final = 0xFF15 +XK_Escape: Final = 0xFF1B +XK_Delete: Final = 0xFFFF +XK_Multi_key: Final = 0xFF20 +XK_SingleCandidate: Final = 0xFF3C +XK_MultipleCandidate: Final = 0xFF3D +XK_PreviousCandidate: Final = 0xFF3E +XK_Kanji: Final = 0xFF21 +XK_Muhenkan: Final = 0xFF22 +XK_Henkan_Mode: Final = 0xFF23 +XK_Henkan: Final = 0xFF23 +XK_Romaji: Final = 0xFF24 +XK_Hiragana: Final = 0xFF25 +XK_Katakana: Final = 0xFF26 +XK_Hiragana_Katakana: Final = 0xFF27 +XK_Zenkaku: Final = 0xFF28 +XK_Hankaku: Final = 0xFF29 +XK_Zenkaku_Hankaku: Final = 0xFF2A +XK_Touroku: Final = 0xFF2B +XK_Massyo: Final = 0xFF2C +XK_Kana_Lock: Final = 0xFF2D +XK_Kana_Shift: Final = 0xFF2E +XK_Eisu_Shift: Final = 0xFF2F +XK_Eisu_toggle: Final = 0xFF30 +XK_Zen_Koho: Final = 0xFF3D +XK_Mae_Koho: Final = 0xFF3E +XK_Home: Final = 0xFF50 +XK_Left: Final = 0xFF51 +XK_Up: Final = 0xFF52 +XK_Right: Final = 0xFF53 +XK_Down: Final = 0xFF54 +XK_Prior: Final = 0xFF55 +XK_Page_Up: Final = 0xFF55 +XK_Next: Final = 0xFF56 +XK_Page_Down: Final = 0xFF56 +XK_End: Final = 0xFF57 +XK_Begin: Final = 0xFF58 +XK_Select: Final = 0xFF60 +XK_Print: Final = 0xFF61 +XK_Execute: Final = 0xFF62 +XK_Insert: Final = 0xFF63 +XK_Undo: Final = 0xFF65 +XK_Redo: Final = 0xFF66 +XK_Menu: Final = 0xFF67 +XK_Find: Final = 0xFF68 +XK_Cancel: Final = 0xFF69 +XK_Help: Final = 0xFF6A +XK_Break: Final = 0xFF6B +XK_Mode_switch: Final = 0xFF7E +XK_script_switch: Final = 0xFF7E +XK_Num_Lock: Final = 0xFF7F +XK_KP_Space: Final = 0xFF80 +XK_KP_Tab: Final = 0xFF89 +XK_KP_Enter: Final = 0xFF8D +XK_KP_F1: Final = 0xFF91 +XK_KP_F2: Final = 0xFF92 +XK_KP_F3: Final = 0xFF93 +XK_KP_F4: Final = 0xFF94 +XK_KP_Home: Final = 0xFF95 +XK_KP_Left: Final = 0xFF96 +XK_KP_Up: Final = 0xFF97 +XK_KP_Right: Final = 0xFF98 +XK_KP_Down: Final = 0xFF99 +XK_KP_Prior: Final = 0xFF9A +XK_KP_Page_Up: Final = 0xFF9A +XK_KP_Next: Final = 0xFF9B +XK_KP_Page_Down: Final = 0xFF9B +XK_KP_End: Final = 0xFF9C +XK_KP_Begin: Final = 0xFF9D +XK_KP_Insert: Final = 0xFF9E +XK_KP_Delete: Final = 0xFF9F +XK_KP_Equal: Final = 0xFFBD +XK_KP_Multiply: Final = 0xFFAA +XK_KP_Add: Final = 0xFFAB +XK_KP_Separator: Final = 0xFFAC +XK_KP_Subtract: Final = 0xFFAD +XK_KP_Decimal: Final = 0xFFAE +XK_KP_Divide: Final = 0xFFAF +XK_KP_0: Final = 0xFFB0 +XK_KP_1: Final = 0xFFB1 +XK_KP_2: Final = 0xFFB2 +XK_KP_3: Final = 0xFFB3 +XK_KP_4: Final = 0xFFB4 +XK_KP_5: Final = 0xFFB5 +XK_KP_6: Final = 0xFFB6 +XK_KP_7: Final = 0xFFB7 +XK_KP_8: Final = 0xFFB8 +XK_KP_9: Final = 0xFFB9 +XK_F1: Final = 0xFFBE +XK_F2: Final = 0xFFBF +XK_F3: Final = 0xFFC0 +XK_F4: Final = 0xFFC1 +XK_F5: Final = 0xFFC2 +XK_F6: Final = 0xFFC3 +XK_F7: Final = 0xFFC4 +XK_F8: Final = 0xFFC5 +XK_F9: Final = 0xFFC6 +XK_F10: Final = 0xFFC7 +XK_F11: Final = 0xFFC8 +XK_L1: Final = 0xFFC8 +XK_F12: Final = 0xFFC9 +XK_L2: Final = 0xFFC9 +XK_F13: Final = 0xFFCA +XK_L3: Final = 0xFFCA +XK_F14: Final = 0xFFCB +XK_L4: Final = 0xFFCB +XK_F15: Final = 0xFFCC +XK_L5: Final = 0xFFCC +XK_F16: Final = 0xFFCD +XK_L6: Final = 0xFFCD +XK_F17: Final = 0xFFCE +XK_L7: Final = 0xFFCE +XK_F18: Final = 0xFFCF +XK_L8: Final = 0xFFCF +XK_F19: Final = 0xFFD0 +XK_L9: Final = 0xFFD0 +XK_F20: Final = 0xFFD1 +XK_L10: Final = 0xFFD1 +XK_F21: Final = 0xFFD2 +XK_R1: Final = 0xFFD2 +XK_F22: Final = 0xFFD3 +XK_R2: Final = 0xFFD3 +XK_F23: Final = 0xFFD4 +XK_R3: Final = 0xFFD4 +XK_F24: Final = 0xFFD5 +XK_R4: Final = 0xFFD5 +XK_F25: Final = 0xFFD6 +XK_R5: Final = 0xFFD6 +XK_F26: Final = 0xFFD7 +XK_R6: Final = 0xFFD7 +XK_F27: Final = 0xFFD8 +XK_R7: Final = 0xFFD8 +XK_F28: Final = 0xFFD9 +XK_R8: Final = 0xFFD9 +XK_F29: Final = 0xFFDA +XK_R9: Final = 0xFFDA +XK_F30: Final = 0xFFDB +XK_R10: Final = 0xFFDB +XK_F31: Final = 0xFFDC +XK_R11: Final = 0xFFDC +XK_F32: Final = 0xFFDD +XK_R12: Final = 0xFFDD +XK_F33: Final = 0xFFDE +XK_R13: Final = 0xFFDE +XK_F34: Final = 0xFFDF +XK_R14: Final = 0xFFDF +XK_F35: Final = 0xFFE0 +XK_R15: Final = 0xFFE0 +XK_Shift_L: Final = 0xFFE1 +XK_Shift_R: Final = 0xFFE2 +XK_Control_L: Final = 0xFFE3 +XK_Control_R: Final = 0xFFE4 +XK_Caps_Lock: Final = 0xFFE5 +XK_Shift_Lock: Final = 0xFFE6 +XK_Meta_L: Final = 0xFFE7 +XK_Meta_R: Final = 0xFFE8 +XK_Alt_L: Final = 0xFFE9 +XK_Alt_R: Final = 0xFFEA +XK_Super_L: Final = 0xFFEB +XK_Super_R: Final = 0xFFEC +XK_Hyper_L: Final = 0xFFED +XK_Hyper_R: Final = 0xFFEE diff --git a/stubs/python-xlib/Xlib/keysymdef/publishing.pyi b/stubs/python-xlib/Xlib/keysymdef/publishing.pyi new file mode 100644 index 000000000000..3c7e8f8cdb5f --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/publishing.pyi @@ -0,0 +1,85 @@ +from typing import Final + +XK_emspace: Final = 0xAA1 +XK_enspace: Final = 0xAA2 +XK_em3space: Final = 0xAA3 +XK_em4space: Final = 0xAA4 +XK_digitspace: Final = 0xAA5 +XK_punctspace: Final = 0xAA6 +XK_thinspace: Final = 0xAA7 +XK_hairspace: Final = 0xAA8 +XK_emdash: Final = 0xAA9 +XK_endash: Final = 0xAAA +XK_signifblank: Final = 0xAAC +XK_ellipsis: Final = 0xAAE +XK_doubbaselinedot: Final = 0xAAF +XK_onethird: Final = 0xAB0 +XK_twothirds: Final = 0xAB1 +XK_onefifth: Final = 0xAB2 +XK_twofifths: Final = 0xAB3 +XK_threefifths: Final = 0xAB4 +XK_fourfifths: Final = 0xAB5 +XK_onesixth: Final = 0xAB6 +XK_fivesixths: Final = 0xAB7 +XK_careof: Final = 0xAB8 +XK_figdash: Final = 0xABB +XK_leftanglebracket: Final = 0xABC +XK_decimalpoint: Final = 0xABD +XK_rightanglebracket: Final = 0xABE +XK_marker: Final = 0xABF +XK_oneeighth: Final = 0xAC3 +XK_threeeighths: Final = 0xAC4 +XK_fiveeighths: Final = 0xAC5 +XK_seveneighths: Final = 0xAC6 +XK_trademark: Final = 0xAC9 +XK_signaturemark: Final = 0xACA +XK_trademarkincircle: Final = 0xACB +XK_leftopentriangle: Final = 0xACC +XK_rightopentriangle: Final = 0xACD +XK_emopencircle: Final = 0xACE +XK_emopenrectangle: Final = 0xACF +XK_leftsinglequotemark: Final = 0xAD0 +XK_rightsinglequotemark: Final = 0xAD1 +XK_leftdoublequotemark: Final = 0xAD2 +XK_rightdoublequotemark: Final = 0xAD3 +XK_prescription: Final = 0xAD4 +XK_minutes: Final = 0xAD6 +XK_seconds: Final = 0xAD7 +XK_latincross: Final = 0xAD9 +XK_hexagram: Final = 0xADA +XK_filledrectbullet: Final = 0xADB +XK_filledlefttribullet: Final = 0xADC +XK_filledrighttribullet: Final = 0xADD +XK_emfilledcircle: Final = 0xADE +XK_emfilledrect: Final = 0xADF +XK_enopencircbullet: Final = 0xAE0 +XK_enopensquarebullet: Final = 0xAE1 +XK_openrectbullet: Final = 0xAE2 +XK_opentribulletup: Final = 0xAE3 +XK_opentribulletdown: Final = 0xAE4 +XK_openstar: Final = 0xAE5 +XK_enfilledcircbullet: Final = 0xAE6 +XK_enfilledsqbullet: Final = 0xAE7 +XK_filledtribulletup: Final = 0xAE8 +XK_filledtribulletdown: Final = 0xAE9 +XK_leftpointer: Final = 0xAEA +XK_rightpointer: Final = 0xAEB +XK_club: Final = 0xAEC +XK_diamond: Final = 0xAED +XK_heart: Final = 0xAEE +XK_maltesecross: Final = 0xAF0 +XK_dagger: Final = 0xAF1 +XK_doubledagger: Final = 0xAF2 +XK_checkmark: Final = 0xAF3 +XK_ballotcross: Final = 0xAF4 +XK_musicalsharp: Final = 0xAF5 +XK_musicalflat: Final = 0xAF6 +XK_malesymbol: Final = 0xAF7 +XK_femalesymbol: Final = 0xAF8 +XK_telephone: Final = 0xAF9 +XK_telephonerecorder: Final = 0xAFA +XK_phonographcopyright: Final = 0xAFB +XK_caret: Final = 0xAFC +XK_singlelowquotemark: Final = 0xAFD +XK_doublelowquotemark: Final = 0xAFE +XK_cursor: Final = 0xAFF diff --git a/stubs/python-xlib/Xlib/keysymdef/special.pyi b/stubs/python-xlib/Xlib/keysymdef/special.pyi new file mode 100644 index 000000000000..7a3897ce4656 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/special.pyi @@ -0,0 +1,26 @@ +from typing import Final + +XK_blank: Final = 0x9DF +XK_soliddiamond: Final = 0x9E0 +XK_checkerboard: Final = 0x9E1 +XK_ht: Final = 0x9E2 +XK_ff: Final = 0x9E3 +XK_cr: Final = 0x9E4 +XK_lf: Final = 0x9E5 +XK_nl: Final = 0x9E8 +XK_vt: Final = 0x9E9 +XK_lowrightcorner: Final = 0x9EA +XK_uprightcorner: Final = 0x9EB +XK_upleftcorner: Final = 0x9EC +XK_lowleftcorner: Final = 0x9ED +XK_crossinglines: Final = 0x9EE +XK_horizlinescan1: Final = 0x9EF +XK_horizlinescan3: Final = 0x9F0 +XK_horizlinescan5: Final = 0x9F1 +XK_horizlinescan7: Final = 0x9F2 +XK_horizlinescan9: Final = 0x9F3 +XK_leftt: Final = 0x9F4 +XK_rightt: Final = 0x9F5 +XK_bott: Final = 0x9F6 +XK_topt: Final = 0x9F7 +XK_vertbar: Final = 0x9F8 diff --git a/stubs/python-xlib/Xlib/keysymdef/technical.pyi b/stubs/python-xlib/Xlib/keysymdef/technical.pyi new file mode 100644 index 000000000000..02038da50954 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/technical.pyi @@ -0,0 +1,51 @@ +from typing import Final + +XK_leftradical: Final = 0x8A1 +XK_topleftradical: Final = 0x8A2 +XK_horizconnector: Final = 0x8A3 +XK_topintegral: Final = 0x8A4 +XK_botintegral: Final = 0x8A5 +XK_vertconnector: Final = 0x8A6 +XK_topleftsqbracket: Final = 0x8A7 +XK_botleftsqbracket: Final = 0x8A8 +XK_toprightsqbracket: Final = 0x8A9 +XK_botrightsqbracket: Final = 0x8AA +XK_topleftparens: Final = 0x8AB +XK_botleftparens: Final = 0x8AC +XK_toprightparens: Final = 0x8AD +XK_botrightparens: Final = 0x8AE +XK_leftmiddlecurlybrace: Final = 0x8AF +XK_rightmiddlecurlybrace: Final = 0x8B0 +XK_topleftsummation: Final = 0x8B1 +XK_botleftsummation: Final = 0x8B2 +XK_topvertsummationconnector: Final = 0x8B3 +XK_botvertsummationconnector: Final = 0x8B4 +XK_toprightsummation: Final = 0x8B5 +XK_botrightsummation: Final = 0x8B6 +XK_rightmiddlesummation: Final = 0x8B7 +XK_lessthanequal: Final = 0x8BC +XK_notequal: Final = 0x8BD +XK_greaterthanequal: Final = 0x8BE +XK_integral: Final = 0x8BF +XK_therefore: Final = 0x8C0 +XK_variation: Final = 0x8C1 +XK_infinity: Final = 0x8C2 +XK_nabla: Final = 0x8C5 +XK_approximate: Final = 0x8C8 +XK_similarequal: Final = 0x8C9 +XK_ifonlyif: Final = 0x8CD +XK_implies: Final = 0x8CE +XK_identical: Final = 0x8CF +XK_radical: Final = 0x8D6 +XK_includedin: Final = 0x8DA +XK_includes: Final = 0x8DB +XK_intersection: Final = 0x8DC +XK_union: Final = 0x8DD +XK_logicaland: Final = 0x8DE +XK_logicalor: Final = 0x8DF +XK_partialderivative: Final = 0x8EF +XK_function: Final = 0x8F6 +XK_leftarrow: Final = 0x8FB +XK_uparrow: Final = 0x8FC +XK_rightarrow: Final = 0x8FD +XK_downarrow: Final = 0x8FE diff --git a/stubs/python-xlib/Xlib/keysymdef/thai.pyi b/stubs/python-xlib/Xlib/keysymdef/thai.pyi new file mode 100644 index 000000000000..2d652844b333 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/thai.pyi @@ -0,0 +1,86 @@ +from typing import Final + +XK_Thai_kokai: Final = 0xDA1 +XK_Thai_khokhai: Final = 0xDA2 +XK_Thai_khokhuat: Final = 0xDA3 +XK_Thai_khokhwai: Final = 0xDA4 +XK_Thai_khokhon: Final = 0xDA5 +XK_Thai_khorakhang: Final = 0xDA6 +XK_Thai_ngongu: Final = 0xDA7 +XK_Thai_chochan: Final = 0xDA8 +XK_Thai_choching: Final = 0xDA9 +XK_Thai_chochang: Final = 0xDAA +XK_Thai_soso: Final = 0xDAB +XK_Thai_chochoe: Final = 0xDAC +XK_Thai_yoying: Final = 0xDAD +XK_Thai_dochada: Final = 0xDAE +XK_Thai_topatak: Final = 0xDAF +XK_Thai_thothan: Final = 0xDB0 +XK_Thai_thonangmontho: Final = 0xDB1 +XK_Thai_thophuthao: Final = 0xDB2 +XK_Thai_nonen: Final = 0xDB3 +XK_Thai_dodek: Final = 0xDB4 +XK_Thai_totao: Final = 0xDB5 +XK_Thai_thothung: Final = 0xDB6 +XK_Thai_thothahan: Final = 0xDB7 +XK_Thai_thothong: Final = 0xDB8 +XK_Thai_nonu: Final = 0xDB9 +XK_Thai_bobaimai: Final = 0xDBA +XK_Thai_popla: Final = 0xDBB +XK_Thai_phophung: Final = 0xDBC +XK_Thai_fofa: Final = 0xDBD +XK_Thai_phophan: Final = 0xDBE +XK_Thai_fofan: Final = 0xDBF +XK_Thai_phosamphao: Final = 0xDC0 +XK_Thai_moma: Final = 0xDC1 +XK_Thai_yoyak: Final = 0xDC2 +XK_Thai_rorua: Final = 0xDC3 +XK_Thai_ru: Final = 0xDC4 +XK_Thai_loling: Final = 0xDC5 +XK_Thai_lu: Final = 0xDC6 +XK_Thai_wowaen: Final = 0xDC7 +XK_Thai_sosala: Final = 0xDC8 +XK_Thai_sorusi: Final = 0xDC9 +XK_Thai_sosua: Final = 0xDCA +XK_Thai_hohip: Final = 0xDCB +XK_Thai_lochula: Final = 0xDCC +XK_Thai_oang: Final = 0xDCD +XK_Thai_honokhuk: Final = 0xDCE +XK_Thai_paiyannoi: Final = 0xDCF +XK_Thai_saraa: Final = 0xDD0 +XK_Thai_maihanakat: Final = 0xDD1 +XK_Thai_saraaa: Final = 0xDD2 +XK_Thai_saraam: Final = 0xDD3 +XK_Thai_sarai: Final = 0xDD4 +XK_Thai_saraii: Final = 0xDD5 +XK_Thai_saraue: Final = 0xDD6 +XK_Thai_sarauee: Final = 0xDD7 +XK_Thai_sarau: Final = 0xDD8 +XK_Thai_sarauu: Final = 0xDD9 +XK_Thai_phinthu: Final = 0xDDA +XK_Thai_maihanakat_maitho: Final = 0xDDE +XK_Thai_baht: Final = 0xDDF +XK_Thai_sarae: Final = 0xDE0 +XK_Thai_saraae: Final = 0xDE1 +XK_Thai_sarao: Final = 0xDE2 +XK_Thai_saraaimaimuan: Final = 0xDE3 +XK_Thai_saraaimaimalai: Final = 0xDE4 +XK_Thai_lakkhangyao: Final = 0xDE5 +XK_Thai_maiyamok: Final = 0xDE6 +XK_Thai_maitaikhu: Final = 0xDE7 +XK_Thai_maiek: Final = 0xDE8 +XK_Thai_maitho: Final = 0xDE9 +XK_Thai_maitri: Final = 0xDEA +XK_Thai_maichattawa: Final = 0xDEB +XK_Thai_thanthakhat: Final = 0xDEC +XK_Thai_nikhahit: Final = 0xDED +XK_Thai_leksun: Final = 0xDF0 +XK_Thai_leknung: Final = 0xDF1 +XK_Thai_leksong: Final = 0xDF2 +XK_Thai_leksam: Final = 0xDF3 +XK_Thai_leksi: Final = 0xDF4 +XK_Thai_lekha: Final = 0xDF5 +XK_Thai_lekhok: Final = 0xDF6 +XK_Thai_lekchet: Final = 0xDF7 +XK_Thai_lekpaet: Final = 0xDF8 +XK_Thai_lekkao: Final = 0xDF9 diff --git a/stubs/python-xlib/Xlib/keysymdef/xf86.pyi b/stubs/python-xlib/Xlib/keysymdef/xf86.pyi new file mode 100644 index 000000000000..7f2d9d330880 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xf86.pyi @@ -0,0 +1,186 @@ +from typing import Final + +XK_XF86_ModeLock: Final = 0x1008FF01 +XK_XF86_MonBrightnessUp: Final = 0x1008FF02 +XK_XF86_MonBrightnessDown: Final = 0x1008FF03 +XK_XF86_KbdLightOnOff: Final = 0x1008FF04 +XK_XF86_KbdBrightnessUp: Final = 0x1008FF05 +XK_XF86_KbdBrightnessDown: Final = 0x1008FF06 +XK_XF86_MonBrightnessCycle: Final = 0x1008FF07 +XK_XF86_Standby: Final = 0x1008FF10 +XK_XF86_AudioLowerVolume: Final = 0x1008FF11 +XK_XF86_AudioMute: Final = 0x1008FF12 +XK_XF86_AudioRaiseVolume: Final = 0x1008FF13 +XK_XF86_AudioPlay: Final = 0x1008FF14 +XK_XF86_AudioStop: Final = 0x1008FF15 +XK_XF86_AudioPrev: Final = 0x1008FF16 +XK_XF86_AudioNext: Final = 0x1008FF17 +XK_XF86_HomePage: Final = 0x1008FF18 +XK_XF86_Mail: Final = 0x1008FF19 +XK_XF86_Start: Final = 0x1008FF1A +XK_XF86_Search: Final = 0x1008FF1B +XK_XF86_AudioRecord: Final = 0x1008FF1C +XK_XF86_Calculator: Final = 0x1008FF1D +XK_XF86_Memo: Final = 0x1008FF1E +XK_XF86_ToDoList: Final = 0x1008FF1F +XK_XF86_Calendar: Final = 0x1008FF20 +XK_XF86_PowerDown: Final = 0x1008FF21 +XK_XF86_ContrastAdjust: Final = 0x1008FF22 +XK_XF86_RockerUp: Final = 0x1008FF23 +XK_XF86_RockerDown: Final = 0x1008FF24 +XK_XF86_RockerEnter: Final = 0x1008FF25 +XK_XF86_Back: Final = 0x1008FF26 +XK_XF86_Forward: Final = 0x1008FF27 +XK_XF86_Stop: Final = 0x1008FF28 +XK_XF86_Refresh: Final = 0x1008FF29 +XK_XF86_PowerOff: Final = 0x1008FF2A +XK_XF86_WakeUp: Final = 0x1008FF2B +XK_XF86_Eject: Final = 0x1008FF2C +XK_XF86_ScreenSaver: Final = 0x1008FF2D +XK_XF86_WWW: Final = 0x1008FF2E +XK_XF86_Sleep: Final = 0x1008FF2F +XK_XF86_Favorites: Final = 0x1008FF30 +XK_XF86_AudioPause: Final = 0x1008FF31 +XK_XF86_AudioMedia: Final = 0x1008FF32 +XK_XF86_MyComputer: Final = 0x1008FF33 +XK_XF86_VendorHome: Final = 0x1008FF34 +XK_XF86_LightBulb: Final = 0x1008FF35 +XK_XF86_Shop: Final = 0x1008FF36 +XK_XF86_History: Final = 0x1008FF37 +XK_XF86_OpenURL: Final = 0x1008FF38 +XK_XF86_AddFavorite: Final = 0x1008FF39 +XK_XF86_HotLinks: Final = 0x1008FF3A +XK_XF86_BrightnessAdjust: Final = 0x1008FF3B +XK_XF86_Finance: Final = 0x1008FF3C +XK_XF86_Community: Final = 0x1008FF3D +XK_XF86_AudioRewind: Final = 0x1008FF3E +XK_XF86_XF86BackForward: Final = 0x1008FF3F +XK_XF86_Launch0: Final = 0x1008FF40 +XK_XF86_Launch1: Final = 0x1008FF41 +XK_XF86_Launch2: Final = 0x1008FF42 +XK_XF86_Launch3: Final = 0x1008FF43 +XK_XF86_Launch4: Final = 0x1008FF44 +XK_XF86_Launch5: Final = 0x1008FF45 +XK_XF86_Launch6: Final = 0x1008FF46 +XK_XF86_Launch7: Final = 0x1008FF47 +XK_XF86_Launch8: Final = 0x1008FF48 +XK_XF86_Launch9: Final = 0x1008FF49 +XK_XF86_LaunchA: Final = 0x1008FF4A +XK_XF86_LaunchB: Final = 0x1008FF4B +XK_XF86_LaunchC: Final = 0x1008FF4C +XK_XF86_LaunchD: Final = 0x1008FF4D +XK_XF86_LaunchE: Final = 0x1008FF4E +XK_XF86_LaunchF: Final = 0x1008FF4F +XK_XF86_ApplicationLeft: Final = 0x1008FF50 +XK_XF86_ApplicationRight: Final = 0x1008FF51 +XK_XF86_Book: Final = 0x1008FF52 +XK_XF86_CD: Final = 0x1008FF53 +XK_XF86_Calculater: Final = 0x1008FF54 +XK_XF86_Clear: Final = 0x1008FF55 +XK_XF86_Close: Final = 0x1008FF56 +XK_XF86_Copy: Final = 0x1008FF57 +XK_XF86_Cut: Final = 0x1008FF58 +XK_XF86_Display: Final = 0x1008FF59 +XK_XF86_DOS: Final = 0x1008FF5A +XK_XF86_Documents: Final = 0x1008FF5B +XK_XF86_Excel: Final = 0x1008FF5C +XK_XF86_Explorer: Final = 0x1008FF5D +XK_XF86_Game: Final = 0x1008FF5E +XK_XF86_Go: Final = 0x1008FF5F +XK_XF86_iTouch: Final = 0x1008FF60 +XK_XF86_LogOff: Final = 0x1008FF61 +XK_XF86_Market: Final = 0x1008FF62 +XK_XF86_Meeting: Final = 0x1008FF63 +XK_XF86_MenuKB: Final = 0x1008FF65 +XK_XF86_MenuPB: Final = 0x1008FF66 +XK_XF86_MySites: Final = 0x1008FF67 +XK_XF86_New: Final = 0x1008FF68 +XK_XF86_News: Final = 0x1008FF69 +XK_XF86_OfficeHome: Final = 0x1008FF6A +XK_XF86_Open: Final = 0x1008FF6B +XK_XF86_Option: Final = 0x1008FF6C +XK_XF86_Paste: Final = 0x1008FF6D +XK_XF86_Phone: Final = 0x1008FF6E +XK_XF86_Q: Final = 0x1008FF70 +XK_XF86_Reply: Final = 0x1008FF72 +XK_XF86_Reload: Final = 0x1008FF73 +XK_XF86_RotateWindows: Final = 0x1008FF74 +XK_XF86_RotationPB: Final = 0x1008FF75 +XK_XF86_RotationKB: Final = 0x1008FF76 +XK_XF86_Save: Final = 0x1008FF77 +XK_XF86_ScrollUp: Final = 0x1008FF78 +XK_XF86_ScrollDown: Final = 0x1008FF79 +XK_XF86_ScrollClick: Final = 0x1008FF7A +XK_XF86_Send: Final = 0x1008FF7B +XK_XF86_Spell: Final = 0x1008FF7C +XK_XF86_SplitScreen: Final = 0x1008FF7D +XK_XF86_Support: Final = 0x1008FF7E +XK_XF86_TaskPane: Final = 0x1008FF7F +XK_XF86_Terminal: Final = 0x1008FF80 +XK_XF86_Tools: Final = 0x1008FF81 +XK_XF86_Travel: Final = 0x1008FF82 +XK_XF86_UserPB: Final = 0x1008FF84 +XK_XF86_User1KB: Final = 0x1008FF85 +XK_XF86_User2KB: Final = 0x1008FF86 +XK_XF86_Video: Final = 0x1008FF87 +XK_XF86_WheelButton: Final = 0x1008FF88 +XK_XF86_Word: Final = 0x1008FF89 +XK_XF86_Xfer: Final = 0x1008FF8A +XK_XF86_ZoomIn: Final = 0x1008FF8B +XK_XF86_ZoomOut: Final = 0x1008FF8C +XK_XF86_Away: Final = 0x1008FF8D +XK_XF86_Messenger: Final = 0x1008FF8E +XK_XF86_WebCam: Final = 0x1008FF8F +XK_XF86_MailForward: Final = 0x1008FF90 +XK_XF86_Pictures: Final = 0x1008FF91 +XK_XF86_Music: Final = 0x1008FF92 +XK_XF86_Battery: Final = 0x1008FF93 +XK_XF86_Bluetooth: Final = 0x1008FF94 +XK_XF86_WLAN: Final = 0x1008FF95 +XK_XF86_UWB: Final = 0x1008FF96 +XK_XF86_AudioForward: Final = 0x1008FF97 +XK_XF86_AudioRepeat: Final = 0x1008FF98 +XK_XF86_AudioRandomPlay: Final = 0x1008FF99 +XK_XF86_Subtitle: Final = 0x1008FF9A +XK_XF86_AudioCycleTrack: Final = 0x1008FF9B +XK_XF86_CycleAngle: Final = 0x1008FF9C +XK_XF86_FrameBack: Final = 0x1008FF9D +XK_XF86_FrameForward: Final = 0x1008FF9E +XK_XF86_Time: Final = 0x1008FF9F +XK_XF86_Select: Final = 0x1008FFA0 +XK_XF86_View: Final = 0x1008FFA1 +XK_XF86_TopMenu: Final = 0x1008FFA2 +XK_XF86_Red: Final = 0x1008FFA3 +XK_XF86_Green: Final = 0x1008FFA4 +XK_XF86_Yellow: Final = 0x1008FFA5 +XK_XF86_Blue: Final = 0x1008FFA6 +XK_XF86_Suspend: Final = 0x1008FFA7 +XK_XF86_Hibernate: Final = 0x1008FFA8 +XK_XF86_TouchpadToggle: Final = 0x1008FFA9 +XK_XF86_TouchpadOn: Final = 0x1008FFB0 +XK_XF86_TouchpadOff: Final = 0x1008FFB1 +XK_XF86_AudioMicMute: Final = 0x1008FFB2 +XK_XF86_Keyboard: Final = 0x1008FFB3 +XK_XF86_WWAN: Final = 0x1008FFB4 +XK_XF86_RFKill: Final = 0x1008FFB5 +XK_XF86_AudioPreset: Final = 0x1008FFB6 +XK_XF86_RotationLockToggle: Final = 0x1008FFB7 +XK_XF86_FullScreen: Final = 0x1008FFB8 +XK_XF86_Switch_VT_1: Final = 0x1008FE01 +XK_XF86_Switch_VT_2: Final = 0x1008FE02 +XK_XF86_Switch_VT_3: Final = 0x1008FE03 +XK_XF86_Switch_VT_4: Final = 0x1008FE04 +XK_XF86_Switch_VT_5: Final = 0x1008FE05 +XK_XF86_Switch_VT_6: Final = 0x1008FE06 +XK_XF86_Switch_VT_7: Final = 0x1008FE07 +XK_XF86_Switch_VT_8: Final = 0x1008FE08 +XK_XF86_Switch_VT_9: Final = 0x1008FE09 +XK_XF86_Switch_VT_10: Final = 0x1008FE0A +XK_XF86_Switch_VT_11: Final = 0x1008FE0B +XK_XF86_Switch_VT_12: Final = 0x1008FE0C +XK_XF86_Ungrab: Final = 0x1008FE20 +XK_XF86_ClearGrab: Final = 0x1008FE21 +XK_XF86_Next_VMode: Final = 0x1008FE22 +XK_XF86_Prev_VMode: Final = 0x1008FE23 +XK_XF86_LogWindowTree: Final = 0x1008FE24 +XK_XF86_LogGrabInfo: Final = 0x1008FE25 diff --git a/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi b/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi new file mode 100644 index 000000000000..92741d4b0563 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xk3270.pyi @@ -0,0 +1,32 @@ +from typing import Final + +XK_3270_Duplicate: Final = 0xFD01 +XK_3270_FieldMark: Final = 0xFD02 +XK_3270_Right2: Final = 0xFD03 +XK_3270_Left2: Final = 0xFD04 +XK_3270_BackTab: Final = 0xFD05 +XK_3270_EraseEOF: Final = 0xFD06 +XK_3270_EraseInput: Final = 0xFD07 +XK_3270_Reset: Final = 0xFD08 +XK_3270_Quit: Final = 0xFD09 +XK_3270_PA1: Final = 0xFD0A +XK_3270_PA2: Final = 0xFD0B +XK_3270_PA3: Final = 0xFD0C +XK_3270_Test: Final = 0xFD0D +XK_3270_Attn: Final = 0xFD0E +XK_3270_CursorBlink: Final = 0xFD0F +XK_3270_AltCursor: Final = 0xFD10 +XK_3270_KeyClick: Final = 0xFD11 +XK_3270_Jump: Final = 0xFD12 +XK_3270_Ident: Final = 0xFD13 +XK_3270_Rule: Final = 0xFD14 +XK_3270_Copy: Final = 0xFD15 +XK_3270_Play: Final = 0xFD16 +XK_3270_Setup: Final = 0xFD17 +XK_3270_Record: Final = 0xFD18 +XK_3270_ChangeScreen: Final = 0xFD19 +XK_3270_DeleteWord: Final = 0xFD1A +XK_3270_ExSelect: Final = 0xFD1B +XK_3270_CursorSelect: Final = 0xFD1C +XK_3270_PrintScreen: Final = 0xFD1D +XK_3270_Enter: Final = 0xFD1E diff --git a/stubs/python-xlib/Xlib/keysymdef/xkb.pyi b/stubs/python-xlib/Xlib/keysymdef/xkb.pyi new file mode 100644 index 000000000000..f72fa6704cd7 --- /dev/null +++ b/stubs/python-xlib/Xlib/keysymdef/xkb.pyi @@ -0,0 +1,102 @@ +from typing import Final + +XK_ISO_Lock: Final = 0xFE01 +XK_ISO_Level2_Latch: Final = 0xFE02 +XK_ISO_Level3_Shift: Final = 0xFE03 +XK_ISO_Level3_Latch: Final = 0xFE04 +XK_ISO_Level3_Lock: Final = 0xFE05 +XK_ISO_Group_Shift: Final = 0xFF7E +XK_ISO_Group_Latch: Final = 0xFE06 +XK_ISO_Group_Lock: Final = 0xFE07 +XK_ISO_Next_Group: Final = 0xFE08 +XK_ISO_Next_Group_Lock: Final = 0xFE09 +XK_ISO_Prev_Group: Final = 0xFE0A +XK_ISO_Prev_Group_Lock: Final = 0xFE0B +XK_ISO_First_Group: Final = 0xFE0C +XK_ISO_First_Group_Lock: Final = 0xFE0D +XK_ISO_Last_Group: Final = 0xFE0E +XK_ISO_Last_Group_Lock: Final = 0xFE0F +XK_ISO_Left_Tab: Final = 0xFE20 +XK_ISO_Move_Line_Up: Final = 0xFE21 +XK_ISO_Move_Line_Down: Final = 0xFE22 +XK_ISO_Partial_Line_Up: Final = 0xFE23 +XK_ISO_Partial_Line_Down: Final = 0xFE24 +XK_ISO_Partial_Space_Left: Final = 0xFE25 +XK_ISO_Partial_Space_Right: Final = 0xFE26 +XK_ISO_Set_Margin_Left: Final = 0xFE27 +XK_ISO_Set_Margin_Right: Final = 0xFE28 +XK_ISO_Release_Margin_Left: Final = 0xFE29 +XK_ISO_Release_Margin_Right: Final = 0xFE2A +XK_ISO_Release_Both_Margins: Final = 0xFE2B +XK_ISO_Fast_Cursor_Left: Final = 0xFE2C +XK_ISO_Fast_Cursor_Right: Final = 0xFE2D +XK_ISO_Fast_Cursor_Up: Final = 0xFE2E +XK_ISO_Fast_Cursor_Down: Final = 0xFE2F +XK_ISO_Continuous_Underline: Final = 0xFE30 +XK_ISO_Discontinuous_Underline: Final = 0xFE31 +XK_ISO_Emphasize: Final = 0xFE32 +XK_ISO_Center_Object: Final = 0xFE33 +XK_ISO_Enter: Final = 0xFE34 +XK_dead_grave: Final = 0xFE50 +XK_dead_acute: Final = 0xFE51 +XK_dead_circumflex: Final = 0xFE52 +XK_dead_tilde: Final = 0xFE53 +XK_dead_macron: Final = 0xFE54 +XK_dead_breve: Final = 0xFE55 +XK_dead_abovedot: Final = 0xFE56 +XK_dead_diaeresis: Final = 0xFE57 +XK_dead_abovering: Final = 0xFE58 +XK_dead_doubleacute: Final = 0xFE59 +XK_dead_caron: Final = 0xFE5A +XK_dead_cedilla: Final = 0xFE5B +XK_dead_ogonek: Final = 0xFE5C +XK_dead_iota: Final = 0xFE5D +XK_dead_voiced_sound: Final = 0xFE5E +XK_dead_semivoiced_sound: Final = 0xFE5F +XK_dead_belowdot: Final = 0xFE60 +XK_First_Virtual_Screen: Final = 0xFED0 +XK_Prev_Virtual_Screen: Final = 0xFED1 +XK_Next_Virtual_Screen: Final = 0xFED2 +XK_Last_Virtual_Screen: Final = 0xFED4 +XK_Terminate_Server: Final = 0xFED5 +XK_AccessX_Enable: Final = 0xFE70 +XK_AccessX_Feedback_Enable: Final = 0xFE71 +XK_RepeatKeys_Enable: Final = 0xFE72 +XK_SlowKeys_Enable: Final = 0xFE73 +XK_BounceKeys_Enable: Final = 0xFE74 +XK_StickyKeys_Enable: Final = 0xFE75 +XK_MouseKeys_Enable: Final = 0xFE76 +XK_MouseKeys_Accel_Enable: Final = 0xFE77 +XK_Overlay1_Enable: Final = 0xFE78 +XK_Overlay2_Enable: Final = 0xFE79 +XK_AudibleBell_Enable: Final = 0xFE7A +XK_Pointer_Left: Final = 0xFEE0 +XK_Pointer_Right: Final = 0xFEE1 +XK_Pointer_Up: Final = 0xFEE2 +XK_Pointer_Down: Final = 0xFEE3 +XK_Pointer_UpLeft: Final = 0xFEE4 +XK_Pointer_UpRight: Final = 0xFEE5 +XK_Pointer_DownLeft: Final = 0xFEE6 +XK_Pointer_DownRight: Final = 0xFEE7 +XK_Pointer_Button_Dflt: Final = 0xFEE8 +XK_Pointer_Button1: Final = 0xFEE9 +XK_Pointer_Button2: Final = 0xFEEA +XK_Pointer_Button3: Final = 0xFEEB +XK_Pointer_Button4: Final = 0xFEEC +XK_Pointer_Button5: Final = 0xFEED +XK_Pointer_DblClick_Dflt: Final = 0xFEEE +XK_Pointer_DblClick1: Final = 0xFEEF +XK_Pointer_DblClick2: Final = 0xFEF0 +XK_Pointer_DblClick3: Final = 0xFEF1 +XK_Pointer_DblClick4: Final = 0xFEF2 +XK_Pointer_DblClick5: Final = 0xFEF3 +XK_Pointer_Drag_Dflt: Final = 0xFEF4 +XK_Pointer_Drag1: Final = 0xFEF5 +XK_Pointer_Drag2: Final = 0xFEF6 +XK_Pointer_Drag3: Final = 0xFEF7 +XK_Pointer_Drag4: Final = 0xFEF8 +XK_Pointer_Drag5: Final = 0xFEFD +XK_Pointer_EnableKeys: Final = 0xFEF9 +XK_Pointer_Accelerate: Final = 0xFEFA +XK_Pointer_DfltBtnNext: Final = 0xFEFB +XK_Pointer_DfltBtnPrev: Final = 0xFEFC diff --git a/stubs/python-xlib/Xlib/protocol/__init__.pyi b/stubs/python-xlib/Xlib/protocol/__init__.pyi new file mode 100644 index 000000000000..1252a6dc5030 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/__init__.pyi @@ -0,0 +1,3 @@ +from Xlib.protocol import display as display, event as event, request as request, rq as rq, structs as structs + +__all__ = ["display", "event", "request", "rq", "structs"] diff --git a/stubs/python-xlib/Xlib/protocol/display.pyi b/stubs/python-xlib/Xlib/protocol/display.pyi new file mode 100644 index 000000000000..b099d6463f0a --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/display.pyi @@ -0,0 +1,122 @@ +from _typeshed import SizedBuffer +from socket import socket +from typing import Literal, TypeVar, overload + +from Xlib import error +from Xlib._typing import ErrorHandler +from Xlib.display import _ResourceBaseClass, _ResourceBaseClassesType +from Xlib.protocol import rq +from Xlib.support import lock +from Xlib.xobject import colormap, cursor, drawable, fontable, resource + +_T = TypeVar("_T") + +class bytesview: + view: memoryview + + @overload + def __init__(self, data: bytes | bytesview, offset: int, size: int) -> None: ... + @overload + def __init__(self, data: SizedBuffer, offset: int = 0, size: int | None = None) -> None: ... + + @overload + def __getitem__(self, key: slice) -> bytes: ... + @overload + def __getitem__(self, key: int) -> int: ... + + def __len__(self) -> int: ... + +class Display: + extension_major_opcodes: dict[str, int] + error_classes: dict[int, type[error.XError]] + event_classes: dict[int, type[rq.Event] | dict[int, type[rq.Event]]] + resource_classes: _ResourceBaseClassesType | None + display_name: str + default_screen: int + socket: socket + socket_error_lock: lock._DummyLock + socket_error: Exception | None + event_queue_read_lock: lock._DummyLock + event_queue_write_lock: lock._DummyLock + event_queue: list[rq.Event] + request_queue_lock: lock._DummyLock + request_serial: int + request_queue: list[tuple[rq.Request | rq.ReplyRequest | ConnectionSetupRequest, int]] + send_recv_lock: lock._DummyLock + send_active: int + recv_active: int + event_waiting: int + event_wait_lock: lock._DummyLock + request_waiting: int + request_wait_lock: lock._DummyLock + recv_buffer_size: int + sent_requests: list[rq.Request | rq.ReplyRequest | ConnectionSetupRequest] + recv_packet_len: int + data_send: bytes + data_recv: bytes + data_sent_bytes: int + resource_id_lock: lock._DummyLock + resource_ids: dict[int, None] + last_resource_id: int + error_handler: ErrorHandler[object] | None + big_endian: bool + info: ConnectionSetupRequest + def __init__(self, display: str | None = None) -> None: ... + def get_display_name(self) -> str: ... + def get_default_screen(self) -> int: ... + def fileno(self) -> int: ... + def next_event(self) -> rq.Event: ... + def pending_events(self) -> int: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def set_error_handler(self, handler: ErrorHandler[object] | None) -> None: ... + def allocate_resource_id(self) -> int: ... + def free_resource_id(self, rid: int) -> None: ... + + @overload + def get_resource_class(self, class_name: Literal["resource"], default: object = None) -> type[resource.Resource]: ... + @overload + def get_resource_class(self, class_name: Literal["drawable"], default: object = None) -> type[drawable.Drawable]: ... + @overload + def get_resource_class(self, class_name: Literal["window"], default: object = None) -> type[drawable.Window]: ... + @overload + def get_resource_class(self, class_name: Literal["pixmap"], default: object = None) -> type[drawable.Pixmap]: ... + @overload + def get_resource_class(self, class_name: Literal["fontable"], default: object = None) -> type[fontable.Fontable]: ... + @overload + def get_resource_class(self, class_name: Literal["font"], default: object = None) -> type[fontable.Font]: ... + @overload + def get_resource_class(self, class_name: Literal["gc"], default: object = None) -> type[fontable.GC]: ... + @overload + def get_resource_class(self, class_name: Literal["colormap"], default: object = None) -> type[colormap.Colormap]: ... + @overload + def get_resource_class(self, class_name: Literal["cursor"], default: object) -> type[cursor.Cursor]: ... + @overload + def get_resource_class(self, class_name: str, default: _T) -> type[_ResourceBaseClass] | _T: ... + @overload + def get_resource_class(self, class_name: str, default: None = None) -> type[_ResourceBaseClass] | None: ... + + def set_extension_major(self, extname: str, major: int) -> None: ... + def get_extension_major(self, extname: str) -> int: ... + def add_extension_event(self, code: int, evt: type[rq.Event], subcode: int | None = None) -> None: ... + def add_extension_error(self, code: int, err: type[error.XError]) -> None: ... + def check_for_error(self) -> None: ... + def send_request(self, request: rq.Request | rq.ReplyRequest | ConnectionSetupRequest, wait_for_response: bool) -> None: ... + def close_internal(self, whom: object) -> None: ... + def send_and_recv(self, flush: bool = False, event: bool = False, request: int | None = None, recv: bool = False) -> None: ... + def parse_response(self, request: int) -> bool: ... + def parse_error_response(self, request: int) -> bool: ... + def default_error_handler(self, err: object) -> None: ... + def parse_request_response(self, request: int) -> bool: ... + def parse_event_response(self, etype: int) -> None: ... + def get_waiting_request(self, sno: int) -> rq.ReplyRequest | ConnectionSetupRequest | None: ... + def get_waiting_replyrequest(self) -> rq.ReplyRequest | ConnectionSetupRequest: ... + def parse_connection_setup(self) -> bool: ... + +PixmapFormat: rq.Struct +VisualType: rq.Struct +Depth: rq.Struct +Screen: rq.Struct + +class ConnectionSetupRequest(rq.GetAttrData): + def __init__(self, display: Display, *args: object, **keys: object) -> None: ... diff --git a/stubs/python-xlib/Xlib/protocol/event.pyi b/stubs/python-xlib/Xlib/protocol/event.pyi new file mode 100644 index 000000000000..f033a985b030 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/event.pyi @@ -0,0 +1,82 @@ +from typing import Final, TypeAlias + +from Xlib.protocol import rq + +class AnyEvent(rq.Event): ... +class KeyButtonPointer(rq.Event): ... +class KeyPress(KeyButtonPointer): ... +class KeyRelease(KeyButtonPointer): ... +class ButtonPress(KeyButtonPointer): ... +class ButtonRelease(KeyButtonPointer): ... +class MotionNotify(KeyButtonPointer): ... +class EnterLeave(rq.Event): ... +class EnterNotify(EnterLeave): ... +class LeaveNotify(EnterLeave): ... +class Focus(rq.Event): ... +class FocusIn(Focus): ... +class FocusOut(Focus): ... +class Expose(rq.Event): ... +class GraphicsExpose(rq.Event): ... +class NoExpose(rq.Event): ... +class VisibilityNotify(rq.Event): ... +class CreateNotify(rq.Event): ... +class DestroyNotify(rq.Event): ... +class UnmapNotify(rq.Event): ... +class MapNotify(rq.Event): ... +class MapRequest(rq.Event): ... +class ReparentNotify(rq.Event): ... +class ConfigureNotify(rq.Event): ... +class ConfigureRequest(rq.Event): ... +class GravityNotify(rq.Event): ... +class ResizeRequest(rq.Event): ... +class Circulate(rq.Event): ... +class CirculateNotify(Circulate): ... +class CirculateRequest(Circulate): ... +class PropertyNotify(rq.Event): ... +class SelectionClear(rq.Event): ... +class SelectionRequest(rq.Event): ... +class SelectionNotify(rq.Event): ... +class ColormapNotify(rq.Event): ... +class MappingNotify(rq.Event): ... +class ClientMessage(rq.Event): ... +class KeymapNotify(rq.Event): ... + +_EventClass: TypeAlias = dict[ + int, + type[ + KeyPress + | KeyRelease + | ButtonPress + | ButtonRelease + | MotionNotify + | EnterNotify + | LeaveNotify + | FocusIn + | FocusOut + | KeymapNotify + | Expose + | GraphicsExpose + | NoExpose + | VisibilityNotify + | CreateNotify + | DestroyNotify + | UnmapNotify + | MapNotify + | MapRequest + | ReparentNotify + | ConfigureNotify + | ConfigureRequest + | GravityNotify + | ResizeRequest + | CirculateNotify + | CirculateRequest + | PropertyNotify + | SelectionClear + | SelectionRequest + | SelectionNotify + | ColormapNotify + | ClientMessage + | MappingNotify + ], +] +event_class: Final[_EventClass] diff --git a/stubs/python-xlib/Xlib/protocol/request.pyi b/stubs/python-xlib/Xlib/protocol/request.pyi new file mode 100644 index 000000000000..1095bbad5cff --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/request.pyi @@ -0,0 +1,134 @@ +from typing import Final +from typing_extensions import Never + +from Xlib import display +from Xlib.protocol import rq + +class CreateWindow(rq.Request): ... +class ChangeWindowAttributes(rq.Request): ... +class GetWindowAttributes(rq.ReplyRequest): ... +class DestroyWindow(rq.Request): ... +class DestroySubWindows(rq.Request): ... +class ChangeSaveSet(rq.Request): ... +class ReparentWindow(rq.Request): ... +class MapWindow(rq.Request): ... +class MapSubwindows(rq.Request): ... +class UnmapWindow(rq.Request): ... +class UnmapSubwindows(rq.Request): ... +class ConfigureWindow(rq.Request): ... +class CirculateWindow(rq.Request): ... +class GetGeometry(rq.ReplyRequest): ... +class QueryTree(rq.ReplyRequest): ... +class InternAtom(rq.ReplyRequest): ... +class GetAtomName(rq.ReplyRequest): ... +class ChangeProperty(rq.Request): ... +class DeleteProperty(rq.Request): ... +class GetProperty(rq.ReplyRequest): ... +class ListProperties(rq.ReplyRequest): ... +class SetSelectionOwner(rq.Request): ... +class GetSelectionOwner(rq.ReplyRequest): ... +class ConvertSelection(rq.Request): ... +class SendEvent(rq.Request): ... +class GrabPointer(rq.ReplyRequest): ... +class UngrabPointer(rq.Request): ... +class GrabButton(rq.Request): ... +class UngrabButton(rq.Request): ... +class ChangeActivePointerGrab(rq.Request): ... +class GrabKeyboard(rq.ReplyRequest): ... +class UngrabKeyboard(rq.Request): ... +class GrabKey(rq.Request): ... +class UngrabKey(rq.Request): ... +class AllowEvents(rq.Request): ... +class GrabServer(rq.Request): ... +class UngrabServer(rq.Request): ... +class QueryPointer(rq.ReplyRequest): ... +class GetMotionEvents(rq.ReplyRequest): ... +class TranslateCoords(rq.ReplyRequest): ... +class WarpPointer(rq.Request): ... +class SetInputFocus(rq.Request): ... +class GetInputFocus(rq.ReplyRequest): ... +class QueryKeymap(rq.ReplyRequest): ... +class OpenFont(rq.Request): ... +class CloseFont(rq.Request): ... +class QueryFont(rq.ReplyRequest): ... +class QueryTextExtents(rq.ReplyRequest): ... +class ListFonts(rq.ReplyRequest): ... + +class ListFontsWithInfo(rq.ReplyRequest): + def __init__(self, display: display.Display, defer: bool = False, *args: object, **keys: object) -> None: ... + def __getattr__(self, attr: object) -> Never: ... + def __getitem__(self, item: str) -> object: ... + def __len__(self) -> int: ... + +class SetFontPath(rq.Request): ... +class GetFontPath(rq.ReplyRequest): ... +class CreatePixmap(rq.Request): ... +class FreePixmap(rq.Request): ... +class CreateGC(rq.Request): ... +class ChangeGC(rq.Request): ... +class CopyGC(rq.Request): ... +class SetDashes(rq.Request): ... +class SetClipRectangles(rq.Request): ... +class FreeGC(rq.Request): ... +class ClearArea(rq.Request): ... +class CopyArea(rq.Request): ... +class CopyPlane(rq.Request): ... +class PolyPoint(rq.Request): ... +class PolyLine(rq.Request): ... +class PolySegment(rq.Request): ... +class PolyRectangle(rq.Request): ... +class PolyArc(rq.Request): ... +class FillPoly(rq.Request): ... +class PolyFillRectangle(rq.Request): ... +class PolyFillArc(rq.Request): ... +class PutImage(rq.Request): ... +class GetImage(rq.ReplyRequest): ... +class PolyText8(rq.Request): ... +class PolyText16(rq.Request): ... +class ImageText8(rq.Request): ... +class ImageText16(rq.Request): ... +class CreateColormap(rq.Request): ... +class FreeColormap(rq.Request): ... +class CopyColormapAndFree(rq.Request): ... +class InstallColormap(rq.Request): ... +class UninstallColormap(rq.Request): ... +class ListInstalledColormaps(rq.ReplyRequest): ... +class AllocColor(rq.ReplyRequest): ... +class AllocNamedColor(rq.ReplyRequest): ... +class AllocColorCells(rq.ReplyRequest): ... +class AllocColorPlanes(rq.ReplyRequest): ... +class FreeColors(rq.Request): ... +class StoreColors(rq.Request): ... +class StoreNamedColor(rq.Request): ... +class QueryColors(rq.ReplyRequest): ... +class LookupColor(rq.ReplyRequest): ... +class CreateCursor(rq.Request): ... +class CreateGlyphCursor(rq.Request): ... +class FreeCursor(rq.Request): ... +class RecolorCursor(rq.Request): ... +class QueryBestSize(rq.ReplyRequest): ... +class QueryExtension(rq.ReplyRequest): ... +class ListExtensions(rq.ReplyRequest): ... +class ChangeKeyboardMapping(rq.Request): ... +class GetKeyboardMapping(rq.ReplyRequest): ... +class ChangeKeyboardControl(rq.Request): ... +class GetKeyboardControl(rq.ReplyRequest): ... +class Bell(rq.Request): ... +class ChangePointerControl(rq.Request): ... +class GetPointerControl(rq.ReplyRequest): ... +class SetScreenSaver(rq.Request): ... +class GetScreenSaver(rq.ReplyRequest): ... +class ChangeHosts(rq.Request): ... +class ListHosts(rq.ReplyRequest): ... +class SetAccessControl(rq.Request): ... +class SetCloseDownMode(rq.Request): ... +class KillClient(rq.Request): ... +class RotateProperties(rq.Request): ... +class ForceScreenSaver(rq.Request): ... +class SetPointerMapping(rq.ReplyRequest): ... +class GetPointerMapping(rq.ReplyRequest): ... +class SetModifierMapping(rq.ReplyRequest): ... +class GetModifierMapping(rq.ReplyRequest): ... +class NoOperation(rq.Request): ... + +major_codes: Final[dict[int, type[rq.Request]]] diff --git a/stubs/python-xlib/Xlib/protocol/rq.pyi b/stubs/python-xlib/Xlib/protocol/rq.pyi new file mode 100644 index 000000000000..1c89b6964ed0 --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/rq.pyi @@ -0,0 +1,400 @@ +from _typeshed import ConvertibleToInt, SliceableBuffer, Unused +from array import array + +# Avoid name collision with List.type +from builtins import type as Type +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import LiteralString + +from Xlib._typing import ErrorHandler +from Xlib.display import _BaseDisplay, _ResourceBaseClass +from Xlib.error import XError +from Xlib.ext.xinput import ClassInfoClass +from Xlib.protocol import display + +_T = TypeVar("_T") +_ModifierMappingList8Elements: TypeAlias = Sequence[Sequence[int]] + +def decode_string(bs: bytes | bytearray) -> str: ... +def encode_array(a: array[Any] | memoryview) -> str: ... + +class BadDataError(Exception): ... + +signed_codes: Final[dict[int, str]] +unsigned_codes: Final[dict[int, str]] +array_unsigned_codes: Final[dict[int, LiteralString]] +struct_to_array_codes: Final[dict[str, LiteralString]] + +class Field: + name: str + default: int | None + pack_value: Callable[[Any], tuple[Any, int | None, int | None]] | None + structcode: str | None + structvalues: int + check_value: Callable[[Any], Any] | None + parse_value: Callable[[Any, Any], Any] | None + keyword_args: int + + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: int | None, format: int + ) -> tuple[Any, SliceableBuffer]: ... + +class Pad(Field): + size: int + value: bytes + structcode: str + def __init__(self, size: int) -> None: ... + +class ConstantField(Field): + value: int + def __init__(self, value: int) -> None: ... + +class Opcode(ConstantField): + structcode: str + +class ReplyCode(ConstantField): + structcode: str + value: int + def __init__(self) -> None: ... + +class LengthField(Field): + structcode: str + other_fields: list[str] | tuple[str, ...] | None + def calc_length(self, length: int) -> int: ... + +class TotalLengthField(LengthField): ... +class RequestLength(TotalLengthField): ... +class ReplyLength(TotalLengthField): ... + +class LengthOf(LengthField): + other_fields: list[str] | tuple[str, ...] | None + def __init__(self, name: str | list[str] | tuple[str, ...], size: int) -> None: ... + +class OddLength(LengthField): + def __init__(self, name: str) -> None: ... + def parse_value(self, value: int, display: Unused) -> Literal["even", "odd"]: ... # type: ignore[override] + +class FormatField(Field): + structcode: str + def __init__(self, name: str, size: int) -> None: ... + +Format = FormatField + +class ValueField(Field): + def __init__(self, name: str, default: int | None = None) -> None: ... + +class Int8(ValueField): + structcode: str + +class Int16(ValueField): + structcode: str + +class Int32(ValueField): + structcode: str + +class Card8(ValueField): + structcode: str + +class Card16(ValueField): + structcode: str + +class Card32(ValueField): + structcode: str + +class Resource(Card32): + cast_function: str + class_name: str + codes: tuple[int, ...] + def __init__(self, name: str, codes: tuple[int, ...] = (), default: int | None = None) -> None: ... + + @overload # type: ignore[override] + def check_value(self, value: Callable[[], _T]) -> _T: ... + @overload + def check_value(self, value: _T) -> _T: ... + + def parse_value(self, value: int, display: _BaseDisplay) -> int: ... # type: ignore[override] # display: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + +class Window(Resource): + cast_function: str + class_name: str + +class Pixmap(Resource): + cast_function: str + class_name: str + +class Drawable(Resource): + cast_function: str + class_name: str + +class Fontable(Resource): + cast_function: str + class_name: str + +class Font(Resource): + cast_function: str + class_name: str + +class GC(Resource): + cast_function: str + class_name: str + +class Colormap(Resource): + cast_function: str + class_name: str + +class Cursor(Resource): + cast_function: str + class_name: str + +class Bool(ValueField): + structcode: str + def check_value(self, value: object) -> bool: ... # type: ignore[override] + +class Set(ValueField): + structcode: str + values: Sequence[object] + def __init__(self, name: str, size: int, values: Sequence[object], default: int | None = None) -> None: ... + def check_value(self, val: _T) -> _T: ... # type: ignore[override] + +class Gravity(Set): + def __init__(self, name: str) -> None: ... + +class FixedBinary(ValueField): + structcode: str + def __init__(self, name: str, size: int) -> None: ... + +class Binary(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value( # type: ignore[override] # Override Callable + self, val: bytes | bytearray + ) -> tuple[bytes | bytearray, int, None]: ... + + @overload # type: ignore[override] # Overload for specific values + def parse_binary_value(self, data: _T, display: Unused, length: None, format: Unused) -> tuple[_T, Literal[b""]]: ... + @overload + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int, format: Unused + ) -> tuple[SliceableBuffer, SliceableBuffer]: ... + +class String8(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value(self, val: bytes | str) -> tuple[bytes, int, None]: ... # type: ignore[override] # Override Callable + + @overload # type: ignore[override] # Overload for specific values + def parse_binary_value( + self, data: bytes | bytearray, display: Unused, length: None, format: Unused + ) -> tuple[str, Literal[b""]]: ... + @overload + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int, format: Unused + ) -> tuple[str, SliceableBuffer]: ... + +class String16(ValueField): + structcode: None + pad: int + def __init__(self, name: str, pad: int = 1) -> None: ... + def pack_value(self, val: Sequence[object]) -> tuple[bytes, int, None]: ... # type: ignore[override] # Override Callable + def parse_binary_value( # type: ignore[override] # length: None will error. See: https://github.com/python-xlib/python-xlib/pull/248 + self, data: SliceableBuffer, display: Unused, length: int | Literal["odd", "even"], format: Unused + ) -> tuple[tuple[Any, ...], SliceableBuffer]: ... + +class List(ValueField): + structcode: None + type: Struct | ScalarObj | ResourceObj | ClassInfoClass | Type[ValueField] + pad: int + def __init__( + self, name: str, type: Struct | ScalarObj | ResourceObj | ClassInfoClass | Type[ValueField], pad: int = 1 + ) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: SupportsIndex | None, format: Unused + ) -> tuple[list[DictWrapper | None], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, val: Sequence[object] | dict[str, Any] + ) -> tuple[bytes, int, None]: ... + +class FixedList(List): + size: int + def __init__(self, name: str, size: int, type: Struct | ScalarObj, pad: int = 1) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[list[DictWrapper | None], SliceableBuffer]: ... + +class Object(ValueField): + type: Struct + structcode: str | None + def __init__(self, name: str, type: Struct, default: int | None = None) -> None: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[DictWrapper, SliceableBuffer]: ... + def parse_value(self, val: SliceableBuffer, display: display.Display | None) -> DictWrapper: ... # type: ignore[override] + def pack_value( # type: ignore[override] # Override Callable + self, val: tuple[object, ...] | dict[str, Any] | DictWrapper + ) -> bytes: ... + def check_value(self, val: tuple[_T, ...] | dict[str, _T] | DictWrapper) -> list[_T]: ... # type: ignore[override] + +class PropertyData(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: ConvertibleToInt | None, format: int + ) -> tuple[tuple[int, SliceableBuffer] | None, SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: tuple[int, Sequence[float] | Sequence[str]] + ) -> tuple[bytes, int, Literal[8, 16, 32]]: ... + +class FixedPropertyData(PropertyData): + size: int + def __init__(self, name: str, size: int) -> None: ... + +class ValueList(Field): + structcode: None + keyword_args: int + default: str # type: ignore[assignment] # Actually different from base class + maskcode: bytes + maskcodelen: int + fields: list[tuple[Field, int]] + def __init__(self, name: str, mask: int, pad: int, *fields: Field) -> None: ... + def pack_value( # type: ignore[override] # Override Callable + self, arg: str | dict[str, Any], keys: dict[str, Any] + ) -> tuple[bytes, None, None]: ... + def parse_binary_value( + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[DictWrapper, SliceableBuffer]: ... + +class KeyboardMapping(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: int | None, format: int + ) -> tuple[list[int], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: Sequence[Sequence[object]] + ) -> tuple[bytes, int, int]: ... + +class ModifierMapping(ValueField): + structcode: None + def parse_binary_value( + self, data: SliceableBuffer, display: Unused, length: Unused, format: int + ) -> tuple[list[array[int]], SliceableBuffer]: ... + def pack_value( # type: ignore[override] # Override Callable + self, value: _ModifierMappingList8Elements + ) -> tuple[bytes, int, int]: ... + +class EventField(ValueField): + structcode: None + def pack_value(self, value: Event) -> tuple[SliceableBuffer, None, None]: ... # type: ignore[override] # Override Callable + def parse_binary_value( # type: ignore[override] + self, data: SliceableBuffer, display: display.Display, length: Unused, format: Unused + ) -> tuple[Event, SliceableBuffer]: ... + +class ScalarObj: + structcode: str + structvalues: int + parse_value: None + check_value: None + def __init__(self, code: str) -> None: ... + +Card8Obj: ScalarObj +Card16Obj: ScalarObj +Card32Obj: ScalarObj + +class ResourceObj: + structcode: str + structvalues: int + class_name: str + check_value: None + def __init__(self, class_name: str) -> None: ... + def parse_value(self, value: int, display: _BaseDisplay) -> int | _ResourceBaseClass: ... + +WindowObj: ResourceObj +ColormapObj: ResourceObj + +class StrClass: + structcode: None + def pack_value(self, val: str) -> bytes: ... + def parse_binary(self, data: bytes | bytearray, display: Unused) -> tuple[str, bytes | bytearray]: ... + +Str: StrClass + +class Struct: + name: str + check_value: Callable[[Any], Any] | None + keyword_args: bool + fields: tuple[Field] + static_codes: str + static_values: int + static_fields: list[Field] + static_size: int + var_fields: list[Field] + structcode: str | None + structvalues: int + def __init__(self, *fields: Field) -> None: ... + def to_binary(self, *varargs: object, **keys: object) -> bytes: ... + def pack_value(self, value: tuple[object, ...] | dict[str, Any] | DictWrapper) -> bytes: ... + + @overload + def parse_value(self, val: SliceableBuffer, display: display.Display | None, rawdict: Literal[True]) -> dict[str, Any]: ... + @overload + def parse_value( + self, val: SliceableBuffer, display: display.Display | None, rawdict: Literal[False] = False + ) -> DictWrapper: ... + + @overload + def parse_binary( + self, data: SliceableBuffer, display: display.Display | None, rawdict: Literal[True] + ) -> tuple[dict[str, Any], SliceableBuffer]: ... + @overload + def parse_binary( + self, data: SliceableBuffer, display: display.Display | None, rawdict: Literal[False] = False + ) -> tuple[DictWrapper, SliceableBuffer]: ... + + # Structs generate their attributes + # TODO: Create a specific type-only class for all instances of `Struct` + @type_check_only + def __getattr__(self, name: str, /) -> Any: ... + +class TextElements8(ValueField): + string_textitem: Struct + def pack_value( # type: ignore[override] # Override Callable + self, value: Iterable[Field | str | bytes | tuple[Sequence[object], ...] | dict[str, Sequence[object]] | DictWrapper] + ) -> tuple[bytes, None, None]: ... + def parse_binary_value( # type: ignore[override] # See: https://github.com/python-xlib/python-xlib/pull/249 + self, data: SliceableBuffer, display: display.Display | None, length: Unused, format: Unused + ) -> tuple[list[DictWrapper], Literal[""]]: ... + +class TextElements16(TextElements8): + string_textitem: Struct + +class GetAttrData: + # GetAttrData classes get their attributes dynamically + # TODO: Complete all classes inheriting from GetAttrData + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... + +class DictWrapper(GetAttrData): + def __init__(self, dict: dict[str, Any]) -> None: ... + def __getitem__(self, key: str) -> object: ... + def __setitem__(self, key: str, value: object) -> None: ... + def __delitem__(self, key: str) -> None: ... + def __setattr__(self, key: str, value: object) -> None: ... + +class Request: + def __init__( + self, display: _BaseDisplay, onerror: ErrorHandler[object] | None = None, *args: object, **keys: object + ) -> None: ... + +class ReplyRequest(GetAttrData): + def __init__(self, display: display.Display, defer: bool = False, *args: object, **keys: object) -> None: ... + def reply(self) -> None: ... + +class Event(GetAttrData): + def __init__( + self, binarydata: SliceableBuffer | None = None, display: display.Display | None = None, **keys: object + ) -> None: ... + +def call_error_handler( + handler: Callable[[XError, Request | None], _T], error: XError, request: Request | None +) -> _T | Literal[0]: ... diff --git a/stubs/python-xlib/Xlib/protocol/structs.pyi b/stubs/python-xlib/Xlib/protocol/structs.pyi new file mode 100644 index 000000000000..47508e6a636c --- /dev/null +++ b/stubs/python-xlib/Xlib/protocol/structs.pyi @@ -0,0 +1,26 @@ +from collections.abc import Iterable, Sequence +from typing import TypeAlias + +from Xlib.protocol import rq + +# Aliases used in other modules +_RGB3IntIterable: TypeAlias = Iterable[int] # noqa: Y047 +_Rectangle4IntSequence: TypeAlias = Sequence[int] # noqa: Y047 +_Segment4IntSequence: TypeAlias = Sequence[int] # noqa: Y047 +_Arc6IntSequence: TypeAlias = Sequence[int] # noqa: Y047 + +# TODO: Complete all classes using WindowValues and GCValues +# Currently *object is used to represent the ValueList instead of the possible attribute types +def WindowValues(arg: str) -> rq.ValueList: ... +def GCValues(arg: str) -> rq.ValueList: ... + +TimeCoord: rq.Struct +Host: rq.Struct +CharInfo: rq.Struct +FontProp: rq.Struct +ColorItem: rq.Struct +RGB: rq.Struct +Point: rq.Struct +Segment: rq.Struct +Rectangle: rq.Struct +Arc: rq.Struct diff --git a/stubs/python-xlib/Xlib/rdb.pyi b/stubs/python-xlib/Xlib/rdb.pyi new file mode 100644 index 000000000000..4c0ed9cdaab0 --- /dev/null +++ b/stubs/python-xlib/Xlib/rdb.pyi @@ -0,0 +1,99 @@ +from _typeshed import SupportsDunderGT, SupportsDunderLT, SupportsRead +from collections.abc import Iterable, Mapping, Sequence +from re import Pattern +from typing import Any, Final, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from Xlib.display import Display +from Xlib.support.lock import _DummyLock + +_T = TypeVar("_T") +_T_contra = TypeVar("_T_contra", contravariant=True) + +_DB: TypeAlias = dict[str, tuple[_DB, ...]] +# A recursive type can be a bit annoying due to dict invariance, +# so this is a slightly less precise version of the _DB alias for parameter annotations +_DB_Param: TypeAlias = dict[str, Any] + +@type_check_only +class _SupportsComparisons(SupportsDunderLT[_T_contra], SupportsDunderGT[_T_contra], Protocol[_T_contra]): ... + +comment_re: Final[Pattern[str]] +resource_spec_re: Final[Pattern[str]] +value_escape_re: Final[Pattern[str]] +resource_parts_re: Final[Pattern[str]] +NAME_MATCH: Final = 0 +CLASS_MATCH: Final = 2 +WILD_MATCH: Final = 4 +MATCH_SKIP: Final = 6 + +class OptionError(Exception): ... + +class ResourceDB: + db: _DB + lock: _DummyLock + def __init__( + self, + file: bytes | SupportsRead[str] | None = None, + string: str | None = None, + resources: Iterable[tuple[str, object]] | None = None, + ) -> None: ... + def insert_file(self, file: bytes | SupportsRead[str]) -> None: ... + def insert_string(self, data: str) -> None: ... + def insert_resources(self, resources: Iterable[tuple[str, object]]) -> None: ... + def insert(self, resource: str, value: object) -> None: ... + def __getitem__(self, keys_tuple: tuple[str, str]) -> Any: ... + + @overload + def get(self, res: str, cls: str, default: None = None) -> Any: ... + @overload + def get(self, res: str, cls: str, default: _T) -> _T: ... + + def update(self, db: ResourceDB) -> None: ... + def output(self) -> str: ... + def getopt(self, name: str, argv: Sequence[str], opts: Mapping[str, Option]) -> Sequence[str]: ... + +def bin_insert(list: list[_SupportsComparisons[_T]], element: _SupportsComparisons[_T]) -> None: ... +def update_db(dest: _DB_Param, src: _DB_Param) -> None: ... +def copy_group(group: tuple[_DB_Param, ...]) -> tuple[_DB, ...]: ... +def copy_db(db: _DB_Param) -> _DB: ... +def output_db(prefix: str, db: _DB_Param) -> str: ... +def output_escape(value: object) -> str: ... + +class Option: + def parse(self, name: str, db: ResourceDB, args: Sequence[_T]) -> Sequence[_T]: ... + +class NoArg(Option): + specifier: str + value: object + def __init__(self, specifier: str, value: object) -> None: ... + +class IsArg(Option): + specifier: str + def __init__(self, specifier: str) -> None: ... + +class SepArg(Option): + specifier: str + def __init__(self, specifier: str) -> None: ... + +class ResArgClass(Option): + def parse(self, name: str, db: ResourceDB, args: Sequence[str]) -> Sequence[str]: ... # type: ignore[override] + +ResArg: ResArgClass + +class SkipArgClass(Option): ... + +SkipArg: SkipArgClass + +class SkipLineClass(Option): ... + +SkipLine: SkipLineClass + +class SkipNArgs(Option): + count: int + def __init__(self, count: int) -> None: ... + +def get_display_opts( + options: Mapping[str, Option], argv: Sequence[str] = ... +) -> tuple[Display, str, ResourceDB, Sequence[str]]: ... + +stdopts: Final[dict[str, SepArg | NoArg | ResArgClass]] diff --git a/stubs/python-xlib/Xlib/support/__init__.pyi b/stubs/python-xlib/Xlib/support/__init__.pyi new file mode 100644 index 000000000000..63adc8192d7e --- /dev/null +++ b/stubs/python-xlib/Xlib/support/__init__.pyi @@ -0,0 +1,3 @@ +from Xlib.support import connect as connect, lock as lock + +__all__ = ["lock", "connect"] diff --git a/stubs/python-xlib/Xlib/support/connect.pyi b/stubs/python-xlib/Xlib/support/connect.pyi new file mode 100644 index 000000000000..7aa8e41c5baf --- /dev/null +++ b/stubs/python-xlib/Xlib/support/connect.pyi @@ -0,0 +1,6 @@ +# Ignore OpenVMS in typeshed +from typing import Final + +from Xlib.support.unix_connect import get_auth as get_auth, get_display as get_display, get_socket as get_socket + +platform: Final[str] diff --git a/stubs/python-xlib/Xlib/support/lock.pyi b/stubs/python-xlib/Xlib/support/lock.pyi new file mode 100644 index 000000000000..236e96e502f1 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/lock.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable + +class _DummyLock: + acquire: Callable[..., None] + release: Callable[..., None] + locked: Callable[..., None] + +def allocate_lock() -> _DummyLock: ... diff --git a/stubs/python-xlib/Xlib/support/unix_connect.pyi b/stubs/python-xlib/Xlib/support/unix_connect.pyi new file mode 100644 index 000000000000..74e6a749ff91 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/unix_connect.pyi @@ -0,0 +1,24 @@ +import sys +from _socket import _Address +from _typeshed import Unused +from platform import uname_result +from re import Pattern +from socket import socket +from typing import Final, Literal, TypeAlias + +if sys.platform == "darwin": + SUPPORTED_PROTOCOLS: Final[tuple[None, Literal["tcp"], Literal["unix"], Literal["darwin"]]] + _Protocol: TypeAlias = Literal["tcp", "unix", "darwin"] | None + DARWIN_DISPLAY_RE: Final[Pattern[str]] +else: + SUPPORTED_PROTOCOLS: Final[tuple[None, Literal["tcp"], Literal["unix"]]] + _Protocol: TypeAlias = Literal["tcp", "unix"] | None +uname: uname_result +DISPLAY_RE: Final[Pattern[str]] + +def get_display(display: str | None) -> tuple[str, str | None, str | None, int, int]: ... +def get_socket(dname: _Address, protocol: _Protocol, host: _Address | None, dno: int) -> socket: ... +def new_get_auth(sock: socket, dname: Unused, protocol: _Protocol, host: Unused, dno: int) -> tuple[bytes, bytes]: ... +def old_get_auth(sock: Unused, dname: _Address, host: Unused, dno: Unused) -> tuple[str | Literal[b""], bytes]: ... + +get_auth = new_get_auth diff --git a/stubs/python-xlib/Xlib/support/vms_connect.pyi b/stubs/python-xlib/Xlib/support/vms_connect.pyi new file mode 100644 index 000000000000..f812f2be8320 --- /dev/null +++ b/stubs/python-xlib/Xlib/support/vms_connect.pyi @@ -0,0 +1,11 @@ +from _socket import _Address +from _typeshed import Unused +from re import Pattern +from socket import socket +from typing import Final + +display_re: Final[Pattern[str]] + +def get_display(display: str | None) -> tuple[str, None, str, int, int]: ... +def get_socket(dname: _Address, protocol: Unused, host: _Address, dno: int) -> socket: ... +def get_auth(sock: Unused, dname: Unused, host: Unused, dno: Unused) -> tuple[str, str]: ... diff --git a/stubs/python-xlib/Xlib/threaded.pyi b/stubs/python-xlib/Xlib/threaded.pyi new file mode 100644 index 000000000000..c7314799e154 --- /dev/null +++ b/stubs/python-xlib/Xlib/threaded.pyi @@ -0,0 +1,4 @@ +# This isn't just a re-export from from Xlib.support import lock +# Importing from this module will cause the lock.allocate_lock function to +# return a basic Python lock, instead of the default dummy lock +from Xlib.support import lock as lock diff --git a/stubs/python-xlib/Xlib/xauth.pyi b/stubs/python-xlib/Xlib/xauth.pyi new file mode 100644 index 000000000000..e6490c569673 --- /dev/null +++ b/stubs/python-xlib/Xlib/xauth.pyi @@ -0,0 +1,21 @@ +from _typeshed import FileDescriptorOrPath +from typing import Final + +from Xlib.X import ( + FamilyChaos as FamilyChaos, + FamilyDECnet as FamilyDECnet, + FamilyInternet as FamilyInternet, + FamilyInternetV6 as FamilyInternetV6, + FamilyServerInterpreted as FamilyServerInterpreted, +) + +FamilyLocal: Final = 256 + +class Xauthority: + entries: list[tuple[bytes, bytes, bytes, bytes, bytes]] + def __init__(self, filename: FileDescriptorOrPath | None = None) -> None: ... + def __len__(self) -> int: ... + def __getitem__(self, i: int) -> tuple[bytes, bytes, bytes, bytes, bytes]: ... + def get_best_auth( + self, family: bytes, address: bytes, dispno: bytes, types: tuple[bytes, ...] = (b"MIT-MAGIC-COOKIE-1",) + ) -> tuple[bytes, bytes]: ... diff --git a/stubs/python-xlib/Xlib/xobject/__init__.pyi b/stubs/python-xlib/Xlib/xobject/__init__.pyi new file mode 100644 index 000000000000..5d06a9d37e44 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/__init__.pyi @@ -0,0 +1,10 @@ +from Xlib.xobject import ( + colormap as colormap, + cursor as cursor, + drawable as drawable, + fontable as fontable, + icccm as icccm, + resource as resource, +) + +__all__ = ["colormap", "cursor", "drawable", "fontable", "icccm", "resource"] diff --git a/stubs/python-xlib/Xlib/xobject/colormap.pyi b/stubs/python-xlib/Xlib/xobject/colormap.pyi new file mode 100644 index 000000000000..a38c9b0dea36 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/colormap.pyi @@ -0,0 +1,25 @@ +from collections.abc import Sequence +from re import Pattern +from typing import Final + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request, rq +from Xlib.xobject import resource + +rgb_res: Final[list[Pattern[str]]] + +class Colormap(resource.Resource): + __colormap__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def copy_colormap_and_free(self, scr_cmap: int) -> Colormap: ... + def install_colormap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def uninstall_colormap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def alloc_color(self, red: int, green: int, blue: int) -> request.AllocColor: ... + def alloc_named_color(self, name: str) -> request.AllocColor | request.AllocNamedColor | None: ... + def alloc_color_cells(self, contiguous: bool, colors: int, planes: int) -> request.AllocColorCells: ... + def alloc_color_planes(self, contiguous: bool, colors: int, red: int, green: int, blue: int) -> request.AllocColorPlanes: ... + def free_colors(self, pixels: Sequence[int], plane_mask: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def store_colors(self, items: dict[str, int], onerror: ErrorHandler[object] | None = None) -> None: ... + def store_named_color(self, name: str, pixel: int, flags: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_colors(self, pixels: Sequence[int]) -> rq.Struct: ... + def lookup_color(self, name: str) -> request.LookupColor: ... diff --git a/stubs/python-xlib/Xlib/xobject/cursor.pyi b/stubs/python-xlib/Xlib/xobject/cursor.pyi new file mode 100644 index 000000000000..3d6952cebdc2 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/cursor.pyi @@ -0,0 +1,10 @@ +from Xlib._typing import ErrorHandler +from Xlib.protocol.structs import _RGB3IntIterable +from Xlib.xobject import resource + +class Cursor(resource.Resource): + __cursor__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def recolor( + self, foreground: _RGB3IntIterable, background: _RGB3IntIterable, onerror: ErrorHandler[object] | None = None + ) -> None: ... diff --git a/stubs/python-xlib/Xlib/xobject/drawable.pyi b/stubs/python-xlib/Xlib/xobject/drawable.pyi new file mode 100644 index 000000000000..5aa7fadf3ef2 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/drawable.pyi @@ -0,0 +1,274 @@ +from collections.abc import Iterable, Sequence +from typing import Any, Literal, Protocol, type_check_only + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request, rq +from Xlib.protocol.structs import _Arc6IntSequence, _Rectangle4IntSequence, _RGB3IntIterable, _Segment4IntSequence +from Xlib.xobject import colormap, cursor, fontable, resource + +# Protocol for the parts of PIL.Image.Image used by python-xlib. +@type_check_only +class _PilImage(Protocol): + @property + def mode(self) -> str: ... + @property + def size(self) -> tuple[int, int]: ... + def crop(self, box: tuple[int, int, int, int], /) -> _PilImage: ... + def tobytes(self, encoder_name: Literal["raw"], rawmode: str, stride: int, x: Literal[0], /) -> bytes: ... + +class Drawable(resource.Resource): + __drawable__ = resource.Resource.__resource__ + def get_geometry(self) -> request.GetGeometry: ... + def create_pixmap(self, width: int, height: int, depth: int) -> Pixmap: ... + def create_gc(self, **keys: object) -> fontable.GC: ... + def copy_area( + self, + gc: int, + src_drawable: int, + src_x: int, + src_y: int, + width: int, + height: int, + dst_x: int, + dst_y: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def copy_plane( + self, + gc: int, + src_drawable: int, + src_x: int, + src_y: int, + width: int, + height: int, + dst_x: int, + dst_y: int, + bit_plane: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def poly_point( + self, gc: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def point(self, gc: int, x: int, y: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def poly_line( + self, gc: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def line(self, gc: int, x1: int, y1: int, x2: int, y2: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def poly_segment( + self, gc: int, segments: Sequence[_Segment4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_rectangle( + self, gc: int, rectangles: Sequence[_Rectangle4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def rectangle( + self, gc: int, x: int, y: int, width: int, height: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_arc(self, gc: int, arcs: Sequence[_Arc6IntSequence], onerror: ErrorHandler[object] | None = None) -> None: ... + def arc( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + angle1: int, + angle2: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def fill_poly( + self, gc: int, shape: int, coord_mode: int, points: Sequence[tuple[int, int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_fill_rectangle( + self, gc: int, rectangles: Sequence[_Rectangle4IntSequence], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def fill_rectangle( + self, gc: int, x: int, y: int, width: int, height: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_fill_arc(self, gc: int, arcs: Sequence[_Arc6IntSequence], onerror: ErrorHandler[object] | None = None) -> None: ... + def fill_arc( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + angle1: int, + angle2: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def put_image( + self, + gc: int, + x: int, + y: int, + width: int, + height: int, + format: int, + depth: int, + left_pad: int, + data: bytes | bytearray, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def put_pil_image(self, gc: int, x: int, y: int, image: _PilImage, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_image(self, x: int, y: int, width: int, height: int, format: int, plane_mask: int) -> request.GetImage: ... + def draw_text( + self, gc: int, x: int, y: int, text: dict[str, str | int], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_text( + self, gc: int, x: int, y: int, items: Sequence[dict[str, str | int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def poly_text_16( + self, gc: int, x: int, y: int, items: Sequence[dict[str, str | int]], onerror: ErrorHandler[object] | None = None + ) -> None: ... + def image_text(self, gc: int, x: int, y: int, string: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def image_text_16(self, gc: int, x: int, y: int, string: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_best_size(self, item_class: int, width: int, height: int) -> request.QueryBestSize: ... + +class Window(Drawable): + __window__ = resource.Resource.__resource__ + def create_window( + self, + x: int, + y: int, + width: int, + height: int, + border_width: int, + depth: int, + window_class: int = 0, + visual: int = 0, + onerror: ErrorHandler[object] | None = None, + **keys: object, + ) -> Window: ... + def change_attributes(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def get_attributes(self) -> request.GetWindowAttributes: ... + def destroy(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def destroy_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def change_save_set(self, mode: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def reparent(self, parent: int, x: int, y: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def map(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def map_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def unmap(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def unmap_sub_windows(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def configure(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def circulate(self, direction: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def raise_window(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_tree(self) -> request.QueryTree: ... + def change_property( + self, + property: int, + property_type: int, + format: int, + data: Sequence[float] | Sequence[str], + mode: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def change_text_property( + self, property: int, property_type: int, data: bytes | str, mode: int = 0, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def delete_property(self, property: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_property( + self, property: int, property_type: int, offset: int, length: int, delete: bool = False + ) -> request.GetProperty | None: ... + def get_full_property(self, property: int, property_type: int, sizehint: int = 10) -> request.GetProperty | None: ... + def get_full_text_property(self, property: int, property_type: int = 0, sizehint: int = 10) -> str | None: ... + def list_properties(self) -> list[int]: ... + def set_selection_owner(self, selection: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def convert_selection( + self, selection: int, target: int, property: int, time: int, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def send_event( + self, event: rq.Event, event_mask: int = 0, propagate: bool = False, onerror: ErrorHandler[object] | None = None + ) -> None: ... + def grab_pointer( + self, owner_events: bool, event_mask: int, pointer_mode: int, keyboard_mode: int, confine_to: int, cursor: int, time: int + ) -> int: ... + def grab_button( + self, + button: int, + modifiers: int, + owner_events: bool, + event_mask: int, + pointer_mode: int, + keyboard_mode: int, + confine_to: int, + cursor: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_button(self, button: int, modifiers: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def grab_keyboard(self, owner_events: bool, pointer_mode: int, keyboard_mode: int, time: int) -> int: ... + def grab_key( + self, + key: int, + modifiers: int, + owner_events: bool, + pointer_mode: int, + keyboard_mode: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def ungrab_key(self, key: int, modifiers: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def query_pointer(self) -> request.QueryPointer: ... + def get_motion_events(self, start: int, stop: int) -> rq.Struct: ... + def translate_coords(self, src_window: int, src_x: int, src_y: int) -> request.TranslateCoords: ... + def warp_pointer( + self, + x: int, + y: int, + src_window: int = 0, + src_x: int = 0, + src_y: int = 0, + src_width: int = 0, + src_height: int = 0, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def set_input_focus(self, revert_to: int, time: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def clear_area( + self, + x: int = 0, + y: int = 0, + width: int = 0, + height: int = 0, + exposures: bool = False, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def create_colormap(self, visual: int, alloc: int) -> colormap.Colormap: ... + def list_installed_colormaps(self) -> list[colormap.Colormap]: ... + def rotate_properties(self, properties: Sequence[int], delta: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_wm_name(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_name(self) -> str | None: ... + def set_wm_icon_name(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_icon_name(self) -> str | None: ... + def set_wm_class(self, inst: str, cls: str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_class(self) -> tuple[str, str] | None: ... + def set_wm_transient_for(self, window: Window, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_transient_for(self) -> Window | None: ... + def set_wm_protocols(self, protocols: Iterable[int], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_protocols(self) -> list[int]: ... + def set_wm_colormap_windows(self, windows: Iterable[Window], onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_colormap_windows(self) -> Iterable[Window]: ... + def set_wm_client_machine(self, name: bytes | str, onerror: ErrorHandler[object] | None = None) -> None: ... + def get_wm_client_machine(self) -> str | None: ... + def set_wm_normal_hints( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_normal_hints(self) -> rq.DictWrapper | None: ... + def set_wm_hints( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_hints(self) -> rq.DictWrapper | None: ... + def set_wm_state( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_state(self) -> rq.DictWrapper | None: ... + def set_wm_icon_size( + self, hints: rq.DictWrapper | dict[str, Any] = {}, onerror: ErrorHandler[object] | None = None, **keys: object + ) -> None: ... + def get_wm_icon_size(self) -> rq.DictWrapper | None: ... + +class Pixmap(Drawable): + __pixmap__ = resource.Resource.__resource__ + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def create_cursor( + self, mask: int, foreground: _RGB3IntIterable, background: _RGB3IntIterable, x: int, y: int + ) -> cursor.Cursor: ... + +def roundup(value: int, unit: int) -> int: ... diff --git a/stubs/python-xlib/Xlib/xobject/fontable.pyi b/stubs/python-xlib/Xlib/xobject/fontable.pyi new file mode 100644 index 000000000000..2f3c57844e73 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/fontable.pyi @@ -0,0 +1,33 @@ +from collections.abc import Sequence + +from Xlib._typing import ErrorHandler +from Xlib.protocol import request +from Xlib.protocol.structs import _RGB3IntIterable +from Xlib.xobject import cursor, resource + +class Fontable(resource.Resource): + __fontable__ = resource.Resource.__resource__ + def query(self) -> request.QueryFont: ... + def query_text_extents(self, string: str) -> request.QueryTextExtents: ... + +class GC(Fontable): + __gc__ = resource.Resource.__resource__ + def change(self, onerror: ErrorHandler[object] | None = None, **keys: object) -> None: ... + def copy(self, src_gc: int, mask: int, onerror: ErrorHandler[object] | None = None) -> None: ... + def set_dashes(self, offset: int, dashes: Sequence[int], onerror: ErrorHandler[object] | None = None) -> None: ... + def set_clip_rectangles( + self, + x_origin: int, + y_origin: int, + rectangles: Sequence[dict[str, int]], + ordering: int, + onerror: ErrorHandler[object] | None = None, + ) -> None: ... + def free(self, onerror: ErrorHandler[object] | None = None) -> None: ... + +class Font(Fontable): + __font__ = resource.Resource.__resource__ + def close(self, onerror: ErrorHandler[object] | None = None) -> None: ... + def create_glyph_cursor( + self, mask: Font, source_char: int, mask_char: int, foreground: _RGB3IntIterable, background: _RGB3IntIterable + ) -> cursor.Cursor: ... diff --git a/stubs/python-xlib/Xlib/xobject/icccm.pyi b/stubs/python-xlib/Xlib/xobject/icccm.pyi new file mode 100644 index 000000000000..8f64f1b06009 --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/icccm.pyi @@ -0,0 +1,7 @@ +from Xlib.protocol import rq + +Aspect: rq.Struct +WMNormalHints: rq.Struct +WMHints: rq.Struct +WMState: rq.Struct +WMIconSize: rq.Struct diff --git a/stubs/python-xlib/Xlib/xobject/resource.pyi b/stubs/python-xlib/Xlib/xobject/resource.pyi new file mode 100644 index 000000000000..9ef991b6c91e --- /dev/null +++ b/stubs/python-xlib/Xlib/xobject/resource.pyi @@ -0,0 +1,10 @@ +from Xlib._typing import ErrorHandler +from Xlib.display import _BaseDisplay + +class Resource: + display: _BaseDisplay + id: int + owner: int + def __init__(self, display: _BaseDisplay, rid: int, owner: int = 0) -> None: ... + def __resource__(self) -> int: ... + def kill_client(self, onerror: ErrorHandler[object] | None = None) -> None: ... diff --git a/stubs/pytz/@tests/stubtest_allowlist.txt b/stubs/pytz/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..564e96683da3 --- /dev/null +++ b/stubs/pytz/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# "Abstract" methods, see the .pyi file for more details. +pytz.tzinfo.BaseTzInfo.localize +pytz.tzinfo.BaseTzInfo.normalize diff --git a/stubs/pytz/METADATA.toml b/stubs/pytz/METADATA.toml new file mode 100644 index 000000000000..7af2a69d8106 --- /dev/null +++ b/stubs/pytz/METADATA.toml @@ -0,0 +1,3 @@ +# This is a mirror of https://git.launchpad.net/pytz/tree, see https://pythonhosted.org/pytz/#latest-versions +version = "2026.3.post1" +upstream-repository = "https://github.com/stub42/pytz" diff --git a/stubs/pytz/pytz/__init__.pyi b/stubs/pytz/pytz/__init__.pyi new file mode 100644 index 000000000000..2f243cbb3bf4 --- /dev/null +++ b/stubs/pytz/pytz/__init__.pyi @@ -0,0 +1,64 @@ +import datetime +from _typeshed import Unused +from collections.abc import Mapping +from typing import ClassVar, type_check_only + +from .exceptions import ( + AmbiguousTimeError as AmbiguousTimeError, + InvalidTimeError as InvalidTimeError, + NonExistentTimeError as NonExistentTimeError, + UnknownTimeZoneError as UnknownTimeZoneError, +) +from .tzinfo import BaseTzInfo as BaseTzInfo, DstTzInfo, StaticTzInfo + +# Actually named UTC and then masked with a singleton with the same name +@type_check_only +class _UTCclass(BaseTzInfo): + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +utc: _UTCclass +UTC: _UTCclass + +def timezone(zone: str) -> _UTCclass | StaticTzInfo | DstTzInfo: ... + +class _FixedOffset(datetime.tzinfo): + zone: ClassVar[None] + def __init__(self, minutes: int) -> None: ... + def utcoffset(self, dt: Unused) -> datetime.timedelta | None: ... + def dst(self, dt: Unused) -> datetime.timedelta: ... + def tzname(self, dt: Unused) -> None: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + +def FixedOffset(offset: int, _tzinfos: dict[int, _FixedOffset] = {}) -> _UTCclass | _FixedOffset: ... + +all_timezones: list[str] +all_timezones_set: set[str] +common_timezones: list[str] +common_timezones_set: set[str] +country_timezones: Mapping[str, list[str]] +country_names: Mapping[str, str] +ZERO: datetime.timedelta +HOUR: datetime.timedelta +VERSION: str + +__all__ = [ + "timezone", + "utc", + "country_timezones", + "country_names", + "AmbiguousTimeError", + "InvalidTimeError", + "NonExistentTimeError", + "UnknownTimeZoneError", + "all_timezones", + "all_timezones_set", + "common_timezones", + "common_timezones_set", + "BaseTzInfo", + "FixedOffset", +] diff --git a/stubs/pytz/pytz/exceptions.pyi b/stubs/pytz/pytz/exceptions.pyi new file mode 100644 index 000000000000..1880e442ac57 --- /dev/null +++ b/stubs/pytz/pytz/exceptions.pyi @@ -0,0 +1,7 @@ +__all__ = ["UnknownTimeZoneError", "InvalidTimeError", "AmbiguousTimeError", "NonExistentTimeError"] + +class Error(Exception): ... +class UnknownTimeZoneError(KeyError, Error): ... +class InvalidTimeError(Error): ... +class AmbiguousTimeError(InvalidTimeError): ... +class NonExistentTimeError(InvalidTimeError): ... diff --git a/stubs/pytz/pytz/lazy.pyi b/stubs/pytz/pytz/lazy.pyi new file mode 100644 index 000000000000..b0b5ca565aa2 --- /dev/null +++ b/stubs/pytz/pytz/lazy.pyi @@ -0,0 +1,20 @@ +from collections.abc import Iterator, Mapping as DictMixin +from typing import TypeVar + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +class LazyDict(DictMixin[str, _VT]): + data: dict[str, _VT] | None + def __getitem__(self, key: str) -> _VT: ... + def __contains__(self, key: object) -> bool: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + +class LazyList(list[_T]): + # does not return `Self` type: + def __new__(cls, fill_iter: _T | None = None) -> LazyList[_T]: ... + +class LazySet(set[_T]): + # does not return `Self` type: + def __new__(cls, fill_iter: _T | None = None) -> LazySet[_T]: ... diff --git a/stubs/pytz/pytz/reference.pyi b/stubs/pytz/pytz/reference.pyi new file mode 100644 index 000000000000..be187db03f33 --- /dev/null +++ b/stubs/pytz/pytz/reference.pyi @@ -0,0 +1,40 @@ +import datetime + +from pytz import UTC as UTC + +class FixedOffset(datetime.tzinfo): + def __init__(self, offset: float, name: str) -> None: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +STDOFFSET: datetime.timedelta +DSTOFFSET: datetime.timedelta + +class LocalTimezone(datetime.tzinfo): + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... # type: ignore[override] + def tzname(self, dt: datetime.datetime) -> str: ... # type: ignore[override] + +Local: LocalTimezone +DSTSTART: datetime.datetime +DSTEND: datetime.datetime + +def first_sunday_on_or_after(dt: datetime.datetime) -> datetime.datetime: ... + +class USTimeZone(datetime.tzinfo): + stdoffset: datetime.timedelta + reprname: str + stdname: str + dstname: str + def __init__(self, hours: float, reprname: str, stdname: str, dstname: str) -> None: ... + def tzname(self, dt: datetime.datetime | None) -> str: ... + def utcoffset(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + def dst(self, dt: datetime.datetime | None) -> datetime.timedelta: ... + +Eastern: USTimeZone +Central: USTimeZone +Mountain: USTimeZone +Pacific: USTimeZone + +__all__ = ["FixedOffset", "LocalTimezone", "USTimeZone", "Eastern", "Central", "Mountain", "Pacific", "UTC"] diff --git a/stubs/pytz/pytz/tzfile.pyi b/stubs/pytz/pytz/tzfile.pyi new file mode 100644 index 000000000000..db28b7573915 --- /dev/null +++ b/stubs/pytz/pytz/tzfile.pyi @@ -0,0 +1,5 @@ +from typing import IO + +from pytz.tzinfo import DstTzInfo + +def build_tzinfo(zone: str, fp: IO[bytes]) -> DstTzInfo: ... diff --git a/stubs/pytz/pytz/tzinfo.pyi b/stubs/pytz/pytz/tzinfo.pyi new file mode 100644 index 000000000000..115dbc76a032 --- /dev/null +++ b/stubs/pytz/pytz/tzinfo.pyi @@ -0,0 +1,45 @@ +import datetime +from abc import abstractmethod +from typing import Any, overload + +class BaseTzInfo(datetime.tzinfo): + _utcoffset: datetime.timedelta | None + _tzname: str | None + zone: str | None # Actually None but should be set on concrete subclasses + # The following abstract methods don't exist in the implementation, but + # are implemented by all sub-classes. + @abstractmethod + def localize(self, dt: datetime.datetime, is_dst: bool | None = ...) -> datetime.datetime: ... + @abstractmethod + def normalize(self, dt: datetime.datetime) -> datetime.datetime: ... + @abstractmethod + def tzname(self, dt: datetime.datetime | None, /) -> str: ... + @abstractmethod + def utcoffset(self, dt: datetime.datetime | None, /) -> datetime.timedelta | None: ... + @abstractmethod + def dst(self, dt: datetime.datetime | None, /) -> datetime.timedelta | None: ... + +class StaticTzInfo(BaseTzInfo): + def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> str: ... + def utcoffset(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta: ... + def dst(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta: ... + +class DstTzInfo(BaseTzInfo): + def __init__(self, _inf: Any = None, _tzinfos: Any = None) -> None: ... + def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ... + def localize(self, dt: datetime.datetime, is_dst: bool | None = False) -> datetime.datetime: ... + def normalize(self, dt: datetime.datetime) -> datetime.datetime: ... + def tzname(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> str: ... + + # https://github.com/python/mypy/issues/12379 + @overload # type: ignore[override] + def utcoffset(self, dt: None, is_dst: bool | None = None) -> None: ... + @overload + def utcoffset(self, dt: datetime.datetime, is_dst: bool | None = None) -> datetime.timedelta: ... + + def dst(self, dt: datetime.datetime | None, is_dst: bool | None = None) -> datetime.timedelta | None: ... + +__all__: list[str] = [] diff --git a/stubs/pywin32/@tests/stubtest_allowlist_win32.txt b/stubs/pywin32/@tests/stubtest_allowlist_win32.txt new file mode 100644 index 000000000000..4ca47866f755 --- /dev/null +++ b/stubs/pywin32/@tests/stubtest_allowlist_win32.txt @@ -0,0 +1,51 @@ +# Not available at runtime. Contains type definitions that are otherwise not exposed +_win32typing + +# False-positive, stubtest shouldn't want to expose TYPE_CHECKING +(win32\.lib\.)?pywintypes\.TYPE_CHECKING + +# PyWin tool / debugger +pythonwin.start_pythonwin +pythonwin.pywin.* +win32com.client.combrowse +win32com.client.tlbrowse + +# Utilities to generate python bindings +win32com.client.CLSIDToClass +win32com.client.connect +win32com.client.genpy +win32com.client.makepy +win32com.client.selecttlb +win32com.client.util +win32com.makegw.* +(win32.lib.)?pywintypes.__import_pywin32_system_module__ + +# COM object servers scripts +win32com.servers.* +# Active X Scripts +win32com(ext)?.axscript.client.pyscript_rexec +win32com(ext)?.axscript.client.pyscript +win32com(ext)?.axscript.client.scriptdispatch + +# Demos, tests and debugging +win32com.demos.* +win32com.servers.test_pycomtest +win32com.test.* +win32com(ext)?.axdebug.dump +win32com(ext)?.axscript.client.pydumper +win32com(ext)?.directsound.test.* + +# Deprecated and makes a buffer of random junk. Use something like `b"\x00" * bufferSize` instead +# It's safer to not even expose this method as deprecated. +(win32.)?win32gui.PyMakeBuffer + +# failed to import, ImportError: DLL load failed while importing axdebug: The specified module could not be found. +win32com(ext)?.axdebug.adb +win32com(ext)?.axdebug.axdebug +win32com(ext)?.axdebug.codecontainer +win32com(ext)?.axdebug.contexts +win32com(ext)?.axdebug.debugger +win32com(ext)?.axdebug.documents +win32com(ext)?.axdebug.expressions +win32com(ext)?.axdebug.gateways +win32com(ext)?.axdebug.stackframe diff --git a/stubs/pywin32/METADATA.toml b/stubs/pywin32/METADATA.toml new file mode 100644 index 000000000000..05ca769e62be --- /dev/null +++ b/stubs/pywin32/METADATA.toml @@ -0,0 +1,6 @@ +version = "312.*" +upstream-repository = "https://github.com/mhammond/pywin32" + +[tool.stubtest] +supported-platforms = ["win32"] +ci-platforms = ["win32"] diff --git a/stubs/pywin32/_win32typing.pyi b/stubs/pywin32/_win32typing.pyi new file mode 100644 index 000000000000..4e61a1565645 --- /dev/null +++ b/stubs/pywin32/_win32typing.pyi @@ -0,0 +1,6327 @@ +# Not available at runtime. Contains type definitions that are otherwise not exposed and not part of a specific module. +from _typeshed import Incomplete, Unused +from collections.abc import Iterable, Sequence +from typing import Literal, SupportsIndex, TypeAlias, TypedDict, final, overload, type_check_only +from typing_extensions import Never, Required, Self, deprecated, disjoint_base + +from win32.lib.pywintypes import TimeType + +_TwoIntSequence: TypeAlias = Sequence[int] +_FourIntSequence: TypeAlias = Sequence[int] +# Is actually pywin.mfc.DocTemplate +DocTemplate: TypeAlias = Incomplete + +class ArgNotFound: ... +class PyOleEmpty: ... +class PyOleMissing: ... +class PyOleNothing: ... + +@disjoint_base +class PyDSCAPSType: + @property + def dwFlags(self): ... + @property + def dwFreeHw3DAllBuffers(self): ... + @property + def dwFreeHw3DStaticBuffers(self): ... + @property + def dwFreeHw3DStreamingBuffers(self): ... + @property + def dwFreeHwMemBytes(self): ... + @property + def dwFreeHwMixingAllBuffers(self): ... + @property + def dwFreeHwMixingStaticBuffers(self): ... + @property + def dwFreeHwMixingStreamingBuffers(self): ... + @property + def dwMaxContigFreeHwMemBytes(self): ... + @property + def dwMaxHw3DAllBuffers(self): ... + @property + def dwMaxHw3DStaticBuffers(self): ... + @property + def dwMaxHw3DStreamingBuffers(self): ... + @property + def dwMaxHwMixingAllBuffers(self): ... + @property + def dwMaxHwMixingStaticBuffers(self): ... + @property + def dwMaxHwMixingStreamingBuffers(self): ... + @property + def dwMaxSecondarySampleRate(self): ... + @property + def dwMinSecondarySampleRate(self): ... + @property + def dwPlayCpuOverheadSwBuffers(self): ... + @property + def dwPrimaryBuffers(self): ... + @property + def dwTotalHwMemBytes(self): ... + @property + def dwUnlockTransferRateHwBuffers(self): ... + +@disjoint_base +class PyDSCBCAPSType: + @property + def dwBufferBytes(self): ... + @property + def dwFlags(self): ... + +@disjoint_base +class PyDSCCAPSType: + @property + def dwChannels(self): ... + @property + def dwFlags(self): ... + @property + def dwFormats(self): ... + +@final +class PyNCB: + @property + def Bufflen(self): ... + + @property + def Callname(self) -> str: ... + @Callname.setter + def Callname(self, value: str | bytes) -> None: ... + + Cmd_cplt: int + Command: int + Event: int + Lana_num: int + Lsn: int + + @property + def Name(self) -> str: ... + @Name.setter + def Name(self, value: str | bytes) -> None: ... + + Num: int + Post: int + def Reset(self) -> None: ... + Retcode: int + Rto: int + Sto: int + +class COMMTIMEOUTS: ... +class CopyProgressRoutine: ... + +class DOCINFO: + @property + def DocName(self) -> str: ... + @property + def Output(self) -> str: ... + @property + def DataType(self) -> str: ... + @property + def Type(self): ... + +class ExportCallback: ... + +@type_check_only +class PrinterExtents(TypedDict): + Length: int + Width: int + +@type_check_only +class PrinterDpi(TypedDict): + xdpi: int + ydpi: int + +@type_check_only +class PrinterPaperSize(TypedDict): + x: int + y: int + +@type_check_only +class SizeL(TypedDict): + cx: int + cy: int + +@type_check_only +class RectL(TypedDict): + bottom: int + left: int + right: int + top: int + +@type_check_only +class FormInfo1(TypedDict): + Flags: int + Name: str + Size: SizeL + ImageableArea: RectL + +class ImportCallback: ... + +# Note: Don't use these, use `int` instead. Or an overload with a deprecation message on the tuple param. +# We're only keeping these here as a reminder when typing from source code. +# Deprecated: Support for passing 2 integers to create a 64bit value is deprecated - pass a long instead +LARGE_INTEGER: TypeAlias = int | tuple[int, int] +ULARGE_INTEGER: TypeAlias = int | tuple[int, int] + +class NCB: + @property + def Command(self): ... + @property + def Retcode(self): ... + @property + def Lsn(self): ... + @property + def Num(self): ... + @property + def Bufflen(self): ... + @property + def Callname(self) -> str: ... + @property + def Name(self) -> str: ... + @property + def Rto(self) -> str: ... + @property + def Sto(self) -> str: ... + @property + def Lana_num(self): ... + @property + def Cmd_cplt(self): ... + @property + def Event(self): ... + @property + def Post(self): ... + +@type_check_only +class PrinterDefaults(TypedDict, total=False): + pDataType: str | None + pDevMode: PyDEVMODEW | None + DesiredAccess: Required[int] + +@type_check_only +class PrinterInfo1(TypedDict): + Flags: int + pDescription: str + pName: str + pComment: str + +PrinterInfo1Tuple: TypeAlias = tuple[int, str, str, str] + +@type_check_only +class PrinterInfo2(TypedDict): + Attributes: int + AveragePPM: int + DefaultPriority: int + Priority: int + StartTime: int + Status: int + UntilTime: int + cJobs: int + pComment: str | None + pDatatype: str | None + pDevMode: PyDEVMODEW | None + pDriverName: str + pLocation: str | None + pParameters: str | None + pPortName: str + pPrintProcessor: str + pPrinterName: str + pSecurityDescriptor: PySECURITY_DESCRIPTOR | None + pSepFile: str | None + pServerName: str | None + pShareName: str | None + +PrinterInfo2Tuple: TypeAlias = tuple[ + str | None, # pServerName + str, # pPrinterName + str, # pShareName + str, # pPortName + str, # pDriverName + str, # pComment + str, # pLocation + None, # (always None) + str, # pSepFile + str, # pPrintProcessor + str, # pDatatype + str, # pParameters + None, # (always None) + int, # Attributes + int, # Priority + int, # DefaultPriority + int, # StartTime + int, # UntilTime + int, # Status + int, # cJobs + int, # AveragePPM +] + +@type_check_only +class PrinterInfo3(TypedDict): + pSecurityDescriptor: PySECURITY_DESCRIPTOR + +@type_check_only +class PrinterInfo4(TypedDict): + Attributes: int + pPrinterName: str + pServerName: str | None + +@type_check_only +class PrinterInfo5(TypedDict): + Attributes: int + DeviceNotSelectedTimeout: int + TransmissionRetryTimeout: int + pPortName: str + pPrinterName: str + +@type_check_only +class PrinterInfo6(TypedDict): + Status: int + +@type_check_only +class PrinterInfo7(TypedDict): + Action: int + ObjectGUID: str | None + +@type_check_only +class PrinterInfo89(TypedDict): + pDevMode: PyDEVMODEW | None + +@type_check_only +class JobInfo1(TypedDict): + JobId: int + pPrinterName: str + pMachineName: str + pUserName: str + pDocument: str + pDatatype: str + pStatus: str | None + Status: int + Priority: int + Position: int + TotalPages: int + PagesPrinted: int + Submitted: TimeType + +@type_check_only +class JobInfo2(JobInfo1): + pNotifyName: str + pPrintProcessor: str + pParameters: str + pDriverName: str + pDevMode: PyDEVMODEW + pSecurityDescriptor: PySECURITY_DESCRIPTOR | None + StartTime: int + UntilTime: int + Size: int + Time: int + +@type_check_only +class JobInfo3(TypedDict): + JobId: int + NextJobId: int + Reserved: int + +@type_check_only +class DriverInfo1(TypedDict): + Name: str + +MonitorInfo1: TypeAlias = DriverInfo1 +PortInfo1: TypeAlias = DriverInfo1 + +@type_check_only +class MonitorInfo2(MonitorInfo1): + DLLName: str + Environment: str + +@type_check_only +class PortInfo2(PortInfo1): + Description: str + MonitorName: str + PortType: int + Reserved: int + +@type_check_only +class DriverInfo2(DriverInfo1): + ConfigFile: str + DataFile: str + DriverPath: str + Environment: str + Version: int + +@type_check_only +class DriverInfo3(DriverInfo2): + DefaultDataType: str | None + DependentFiles: list[str] + HelpFile: str | None + MonitorName: str | None + +@type_check_only +class DriverInfo4(DriverInfo3): + PreviousNames: str | None + +@type_check_only +class DriverInfo5(DriverInfo2): + ConfigVersion: int + DriverAttributes: int + DriverVersion: int + +@type_check_only +class DriverInfo6(DriverInfo4): + MfgName: str + OEMUrl: str | None + Provider: str + DriverDate: TimeType + DriverVersion: int + +class PyACL: + def Initialize(self) -> None: ... + def IsValid(self) -> bool: ... + + @overload + @deprecated("""\ +Early versions of this function supported only two arguments. \ +This has been deprecated in preference of the three argument version, \ +which reflects the win32 API and the new functions in this module.""") + def AddAccessAllowedAce(self, access: int, sid: PySID, /) -> None: ... + @overload + def AddAccessAllowedAce(self, revision: int, access: int, sid: PySID, /) -> None: ... + + def AddAccessAllowedAceEx(self, revision: int, aceflags: int, access: int, sid: PySID, /) -> None: ... + def AddAccessAllowedObjectAce( + self, AceRevision, AceFlags, AccessMask, ObjectTypeGuid: PyIID, InheritedObjectTypeGuid: PyIID, sid: PySID, / + ) -> None: ... + + @overload + @deprecated("""\ +Early versions of this function supported only two arguments. \ +This has been deprecated in preference of the three argument version, \ +which reflects the win32 API and the new functions in this module.""") + def AddAccessDeniedAce(self, access: int, sid: PySID, /) -> None: ... + @overload + def AddAccessDeniedAce(self, revision: int, access: int, sid: PySID, /) -> None: ... + + def AddAccessDeniedAceEx(self, revision: int, aceflags: int, access: int, sid: PySID, /) -> None: ... + def AddMandatoryAce(self, AceRevision, AceFlags, MandatoryPolicy, LabelSid: PySID, /) -> None: ... + def AddAuditAccessAce(self, dwAceRevision, dwAccessMask, sid: PySID, bAuditSuccess, bAuditFailure, /) -> None: ... + def AddAuditAccessAceEx(self, dwAceRevision, AceFlags, dwAccessMask, sid: PySID, bAuditSuccess, bAuditFailure, /) -> None: ... + def AddAuditAccessObjectAce( + self, + dwAceRevision, + AceFlags, + dwAccessMask, + ObjectTypeGuid: PyIID, + InheritedObjectTypeGuid: PyIID, + sid: PySID, + bAuditSuccess, + bAuditFailure, + /, + ) -> None: ... + def GetAclSize(self): ... + def GetAclRevision(self): ... + def GetAceCount(self) -> int: ... + def GetAce(self, index: int, /) -> tuple[tuple[int, int], int, PySID]: ... + def DeleteAce(self, index: int, /) -> None: ... + def GetEffectiveRightsFromAcl(self, trustee: PyTRUSTEE | dict[str, int | PySID], /) -> int: ... + def GetAuditedPermissionsFromAcl(self, trustee: PyTRUSTEE, /) -> tuple[Incomplete, Incomplete]: ... + def SetEntriesInAcl(self, obexpl_list: tuple[dict[str, int | dict[str, int | PySID]], ...], /) -> PyACL: ... + def GetExplicitEntriesFromAcl(self) -> tuple[dict[str, int | dict[str, int | PySID]]] | None: ... + +class PyBITMAP: + @property + def bmType(self) -> int: ... + @property + def bmWidth(self) -> int: ... + @property + def bmHeight(self) -> int: ... + @property + def bmWidthBytes(self) -> int: ... + @property + def bmPlanes(self) -> int: ... + +class PyBLENDFUNCTION: ... +class PyCEHANDLE: ... + +class PyCERTSTORE: + @property + def HCERTSTORE(self): ... + + @overload + def CertCloseStore(self) -> None: ... + @overload + @deprecated("""\ +`Flags` argument has been deprecated as it is likely to crash the process if \ +`CERT_CLOSE_STORE_FORCE_FLAG` is specified. The underlying function is now \ +always called with `CERT_CLOSE_STORE_CHECK_FLAG`, and support for this \ +param will be dropped at some point in the future.""") + def CertCloseStore(self, Flags: int) -> None: ... + + def CertControlStore(self, Flags, CtrlType, CtrlPara: int) -> None: ... + def CertEnumCertificatesInStore(self) -> list[PyCERT_CONTEXT]: ... + def CertEnumCTLsInStore(self) -> list[PyCTL_CONTEXT]: ... + def CertSaveStore(self, MsgAndCertEncodingType, SaveAs, SaveTo, SaveToPara: str | int, Flags=...) -> None: ... + def CertAddEncodedCertificateToStore(self, CertEncodingType, CertEncoded, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCertificateContextToStore(self, CertContext: PyCERT_CONTEXT, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCertificateLinkToStore(self, CertContext: PyCERT_CONTEXT, AddDisposition) -> PyCERT_CONTEXT: ... + def CertAddCTLContextToStore(self, CtlContext: PyCTL_CONTEXT, AddDisposition) -> PyCTL_CONTEXT: ... + def CertAddCTLLinkToStore(self, CtlContext: PyCTL_CONTEXT, AddDisposition) -> PyCTL_CONTEXT: ... + def CertAddStoreToCollection(self, SiblingStore: PyCERTSTORE, UpdateFlag: int = ..., Priority: int = ...) -> None: ... + def CertRemoveStoreFromCollection(self, SiblingStore: PyCERTSTORE) -> None: ... + def PFXExportCertStoreEx(self, Password: Incomplete | None = ..., Flags=...): ... + +class PyCERT_ALT_NAME_ENTRY: ... +class PyCERT_ALT_NAME_INFO: ... + +class PyCERT_AUTHORITY_KEY_ID_INFO: + @property + def KeyId(self): ... + @property + def CertIssuer(self): ... + @property + def CertSerialNumber(self): ... + +class PyCERT_BASIC_CONSTRAINTS2_INFO: + @property + def fCA(self): ... + @property + def fPathLenConstraint(self): ... + @property + def PathLenConstraint(self): ... + +class PyCERT_BASIC_CONSTRAINTS_INFO: + @property + def SubjectType(self) -> PyCRYPT_BIT_BLOB: ... + @property + def fPathLenConstraint(self): ... + @property + def PathLenConstraint(self): ... + @property + def SubtreesConstraint(self): ... + +class PyCERT_CONTEXT: + @property + def HANDLE(self): ... + @property + def CertStore(self) -> PyCERTSTORE: ... + @property + def CertEncoded(self): ... + @property + def CertEncodingType(self): ... + @property + def Version(self): ... + @property + def Subject(self) -> str: ... + @property + def Issuer(self) -> str: ... + @property + def NotBefore(self) -> TimeType: ... + @property + def NotAfter(self) -> TimeType: ... + @property + def SignatureAlgorithm(self): ... + @property + def Extension(self) -> tuple[PyCERT_EXTENSION, ...]: ... + @property + def SubjectPublicKeyInfo(self) -> PyCERT_PUBLIC_KEY_INFO: ... + @property + def SerialNumber(self): ... + def CertFreeCertificateContext(self) -> None: ... + def CertEnumCertificateContextProperties(self) -> list[Incomplete]: ... + def CryptAcquireCertificatePrivateKey(self, Flags: int = ...) -> tuple[Incomplete, PyCRYPTPROV]: ... + def CertGetIntendedKeyUsage(self): ... + def CertGetEnhancedKeyUsage(self, Flags: int = ...): ... + def CertSerializeCertificateStoreElement(self, Flags: int = ...) -> str: ... + def CertVerifySubjectCertificateContext(self, Issuer: PyCERT_CONTEXT, Flags): ... + def CertDeleteCertificateFromStore(self) -> None: ... + def CertGetCertificateContextProperty(self, PropId): ... + def CertSetCertificateContextProperty(self, PropId, Data, Flags: int = ...) -> None: ... + +class PyCERT_EXTENSION: + @property + def ObjId(self): ... + @property + def Critical(self): ... + @property + def Value(self): ... + +class PyCERT_KEY_ATTRIBUTES_INFO: + @property + def KeyId(self): ... + @property + def IntendedKeyUsage(self) -> PyCRYPT_BIT_BLOB: ... + @property + def PrivateKeyUsagePeriod(self): ... + +class PyCERT_NAME_INFO: ... +class PyCERT_NAME_VALUE: ... +class PyCERT_OTHER_NAME: ... + +class PyCERT_POLICY_INFO: + @property + def PolicyIdentifier(self): ... + @property + def PolicyQualifier(self): ... + +class PyCERT_PUBLIC_KEY_INFO: + @property + def Algorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def PublicKey(self) -> PyCRYPT_BIT_BLOB: ... + +class PyCOMSTAT: + @property + def cbInQue(self) -> int: ... + @property + def cbOutQue(self) -> int: ... + @property + def fCtsHold(self) -> int: ... + @property + def fDsrHold(self) -> int: ... + @property + def fRlsdHold(self) -> int: ... + @property + def fXoffHold(self) -> int: ... + @property + def fXoffSent(self) -> int: ... + @property + def fEof(self) -> int: ... + @property + def fTxim(self) -> int: ... + @property + def fReserved(self) -> int: ... + +@final +class PyCOORD: + def __new__(self, X: int = ..., Y: int = ...) -> Self: ... + X: int + Y: int + +class PyCREDENTIAL: + @property + def Flags(self): ... + @property + def Type(self): ... + @property + def TargetName(self) -> str: ... + @property + def Comment(self) -> str: ... + @property + def LastWritten(self) -> TimeType: ... + @property + def CredentialBlob(self) -> str: ... + @property + def Persist(self): ... + @property + def Attributes(self): ... + @property + def TargetAlias(self) -> str: ... + @property + def UserName(self) -> str: ... + +class PyCREDENTIAL_ATTRIBUTE: + @property + def Keyword(self) -> str: ... + @property + def Flags(self): ... + @property + def Value(self): ... + +class PyCREDENTIAL_TARGET_INFORMATION: + @property + def TargetName(self) -> str: ... + @property + def NetbiosServerName(self) -> str: ... + @property + def DnsServerName(self) -> str: ... + @property + def NetbiosDomainName(self) -> str: ... + @property + def DnsDomainName(self) -> str: ... + @property + def DnsTreeName(self) -> str: ... + @property + def PackageName(self) -> str: ... + @property + def Flags(self): ... + @property + def CredTypes(self) -> tuple[Incomplete, ...]: ... + +class PyCREDUI_INFO: + @property + def Parent(self) -> int: ... + @property + def MessageText(self) -> str: ... + @property + def CaptionText(self) -> str: ... + @property + def Banner(self) -> int: ... + +class PyCRYPTHASH: + def CryptDestroyHash(self) -> None: ... + def CryptDuplicateHash(self, Flags: int = ...) -> PyCRYPTHASH: ... + def CryptHashData(self, Data: str, Flags: int = ...) -> None: ... + def CryptHashSessionKey(self, Key: PyCRYPTKEY, Flags: int = ...) -> None: ... + def CryptSignHash(self, KeySpec, Flags: int = ...) -> str: ... + def CryptVerifySignature(self, Signature: str, PubKey: PyCRYPTKEY, Flags: int = ...) -> None: ... + def CryptGetHashParam(self, Param, Flags: int = ...): ... + +class PyCRYPTKEY: + @property + def HCRYPTPROV(self): ... + @property + def HCRYPTKEY(self): ... + def CryptDestroyKey(self) -> None: ... + def CryptExportKey(self, ExpKey: PyCRYPTKEY, BlobType, Flags: int = ...): ... + def CryptGetKeyParam(self, Param, Flags: int = ...): ... + def CryptDuplicateKey(self, Reserved: int = ..., Flags: int = ...) -> PyCRYPTKEY: ... + def CryptEncrypt(self, Final, Data, Hash: PyCRYPTHASH | None = ..., Flags: int = ...): ... + def CryptDecrypt(self, Final, Data, Hash: PyCRYPTHASH | None = ..., Flags: int = ...): ... + +class PyCRYPTMSG: + @property + def HCRYPTMSG(self): ... + def CryptMsgClose(self) -> None: ... + +class PyCRYPTPROTECT_PROMPTSTRUCT: ... + +class PyCRYPTPROV: + def CryptReleaseContext(self, Flags: int = ...) -> None: ... + def CryptGenKey(self, Algid, Flags, KeyLen: int = ...) -> PyCRYPTKEY: ... + def CryptGetProvParam(self, Param, Flags: int = ...) -> None: ... + def CryptGetUserKey(self, KeySpec) -> PyCRYPTKEY: ... + def CryptGenRandom(self, Len, SeedData: str | None = ...) -> str: ... + def CryptCreateHash(self, Algid, Key: PyCRYPTKEY | None = ..., Flags: int = ...) -> PyCRYPTHASH: ... + def CryptImportKey(self, Data, PubKey: PyCRYPTKEY | None = ..., Flags: int = ...) -> PyCRYPTKEY: ... + def CryptExportPublicKeyInfo(self, KeySpec, CertEncodingType=...) -> PyCERT_PUBLIC_KEY_INFO: ... + def CryptImportPublicKeyInfo(self, Info, CertEncodingType=...) -> PyCRYPTKEY: ... + +class PyCRYPT_ALGORITHM_IDENTIFIER: + @property + def ObjId(self): ... + @property + def Parameters(self): ... + +class PyCRYPT_ATTRIBUTE: + @property + def ObjId(self): ... + @property + def Value(self) -> tuple[Incomplete, ...]: ... + +class PyCRYPT_BIT_BLOB: + @property + def Data(self): ... + @property + def UnusedBits(self): ... + +class PyCRYPT_DECRYPT_MESSAGE_PARA: + @property + def CertStores(self) -> tuple[Incomplete, ...]: ... + @property + def MsgAndCertEncodingType(self): ... + @property + def Flags(self): ... + +class PyCRYPT_ENCRYPT_MESSAGE_PARA: + @property + def ContentEncryptionAlgorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def CryptProv(self) -> PyCRYPTPROV: ... + @property + def EncryptionAuxInfo(self): ... + @property + def Flags(self): ... + @property + def InnerContentType(self): ... + @property + def MsgEncodingType(self): ... + +class PyCRYPT_SIGN_MESSAGE_PARA: + @property + def SigningCert(self) -> PyCERT_CONTEXT: ... + @property + def HashAlgorithm(self) -> PyCRYPT_ALGORITHM_IDENTIFIER: ... + @property + def HashAuxInfo(self): ... + @property + def MsgCert(self) -> tuple[PyCERT_CONTEXT, ...]: ... + @property + def MsgCrl(self) -> tuple[Incomplete, ...]: ... + @property + def AuthAttr(self) -> tuple[PyCRYPT_ATTRIBUTE, ...]: ... + @property + def UnauthAttr(self) -> tuple[PyCRYPT_ATTRIBUTE, ...]: ... + @property + def Flags(self): ... + @property + def InnerContentType(self): ... + @property + def MsgEncodingType(self): ... + +class PyCRYPT_VERIFY_MESSAGE_PARA: + @property + def MsgAndCertEncodingType(self): ... + @property + def CryptProv(self) -> PyCRYPTPROV: ... + @property + def PyGetSignerCertificate(self): ... + @property + def GetArg(self): ... + +class PyCTL_CONTEXT: + @property + def HCTL_CONTEXT(self): ... + def CertFreeCTLContext(self) -> None: ... + def CertEnumCTLContextProperties(self) -> tuple[Incomplete, ...]: ... + def CertEnumSubjectInSortedCTL(self) -> tuple[tuple[Incomplete, Incomplete], ...]: ... + def CertDeleteCTLFromStore(self) -> None: ... + def CertSerializeCTLStoreElement(self, Flags: int = ...) -> str: ... + +class PyCTL_USAGE: ... + +@final +class PyConsoleScreenBuffer: + def __new__(self, Handle) -> Self: ... + def SetConsoleActiveScreenBuffer(self) -> None: ... + def GetConsoleCursorInfo(self) -> tuple[Incomplete, Incomplete]: ... + def SetConsoleCursorInfo(self, Size, Visible) -> None: ... + def GetConsoleMode(self): ... + def SetConsoleMode(self, Mode) -> None: ... + def ReadConsole(self, NumberOfCharsToRead): ... + def WriteConsole(self, Buffer: str) -> int: ... + def FlushConsoleInputBuffer(self) -> None: ... + def SetConsoleTextAttribute(self, Attributes: int) -> None: ... + def SetConsoleCursorPosition(self, CursorPosition: PyCOORD) -> None: ... + def SetConsoleScreenBufferSize(self, Size: PyCOORD) -> None: ... + def SetConsoleWindowInfo(self, Absolute, ConsoleWindow: PySMALL_RECT) -> None: ... + def GetConsoleScreenBufferInfo(self): ... + def GetLargestConsoleWindowSize(self) -> PyCOORD: ... + def FillConsoleOutputAttribute(self, Attribute, Length, WriteCoord: PyCOORD): ... + def FillConsoleOutputCharacter(self, Character, Length, WriteCoord: PyCOORD): ... + def ReadConsoleOutputCharacter(self, Length, ReadCoord: PyCOORD) -> str: ... + def ReadConsoleOutputAttribute(self, Length, ReadCoord: PyCOORD) -> tuple[Incomplete, ...]: ... + def WriteConsoleOutputCharacter(self, Characters, WriteCoord: PyCOORD): ... + def WriteConsoleOutputAttribute(self, Attributes: tuple[Incomplete, ...], WriteCoord: PyCOORD): ... + def ScrollConsoleScreenBuffer( + self, ScrollRectangle: PySMALL_RECT, ClipRectangle: PySMALL_RECT, DestinationOrigin: PyCOORD, FillCharacter, FillAttribute + ) -> None: ... + def GetCurrentConsoleFont(self, MaximumWindow: bool = ...) -> tuple[int, PyCOORD]: ... + def GetConsoleFontSize(self, Font) -> PyCOORD: ... + def SetConsoleFont(self, Font) -> None: ... + def SetStdHandle(self, StdHandle) -> None: ... + def SetConsoleDisplayMode(self, Flags, NewScreenBufferDimensions: PyCOORD) -> None: ... + def WriteConsoleInput(self, Buffer: Iterable[PyINPUT_RECORD]): ... + def ReadConsoleInput(self, Length) -> tuple[PyINPUT_RECORD, ...]: ... + def PeekConsoleInput(self, Length) -> tuple[PyINPUT_RECORD, ...]: ... + def GetNumberOfConsoleInputEvents(self): ... + def Close(self) -> None: ... + def Detach(self) -> int: ... + +@disjoint_base +class PyCredHandle: + def Detach(self): ... + def FreeCredentialsHandle(self) -> None: ... + def QueryCredentialsAttributes(self, Attribute: int, /) -> str: ... + +@disjoint_base +class PyCtxtHandle: + def Detach(self): ... + def CompleteAuthToken(self, Token: PySecBufferDesc, /) -> None: ... + def QueryContextAttributes(self, Attribute, /) -> None: ... + def DeleteSecurityContext(self) -> None: ... + def QuerySecurityContextToken(self): ... + def MakeSignature(self, fqop, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def VerifySignature(self, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def EncryptMessage(self, fqop, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def DecryptMessage(self, Message: PySecBufferDesc, MessageSeqNo, /) -> None: ... + def ImpersonateSecurityContext(self) -> None: ... + def RevertSecurityContext(self) -> None: ... + +class PyDCB: + @property + def BaudRate(self) -> int: ... + @property + def wReserved(self) -> int: ... + @property + def XonLim(self) -> int: ... + @property + def XoffLim(self) -> int: ... + @property + def ByteSize(self) -> int: ... + @property + def Parity(self) -> int: ... + @property + def StopBits(self) -> int: ... + @property + def XonChar(self) -> str: ... + @property + def XoffChar(self) -> str: ... + @property + def ErrorChar(self) -> str: ... + @property + def EofChar(self) -> str: ... + @property + def EvtChar(self) -> str: ... + @property + def wReserved1(self) -> int: ... + @property + def fBinary(self) -> int: ... + @property + def fParity(self) -> int: ... + @property + def fOutxCtsFlow(self) -> int: ... + @property + def fOutxDsrFlow(self) -> int: ... + @property + def fDtrControl(self) -> int: ... + @property + def fDsrSensitivity(self) -> int: ... + @property + def fTXContinueOnXoff(self) -> int: ... + @property + def fOutX(self) -> int: ... + @property + def fInX(self) -> int: ... + @property + def fErrorChar(self) -> int: ... + @property + def fNull(self) -> int: ... + @property + def fRtsControl(self) -> int: ... + @property + def fAbortOnError(self) -> int: ... + @property + def fDummy2(self) -> int: ... + +@disjoint_base +class PyDEVMODEW: + def __new__(self, DriverExtra: int = 0) -> Self: ... + def Clear(self) -> None: ... + SpecVersion: int + DriverVersion: int + @property + def Size(self) -> int: ... + @property + def DriverExtra(self) -> int: ... + Fields: int + Orientation: int + PaperSize: int + PaperLength: int + PaperWidth: int + Position_x: int + Position_y: int + DisplayOrientation: int + DisplayFixedOutput: int + Scale: int + Copies: int + DefaultSource: int + PrintQuality: int + Color: int + Duplex: int + YResolution: int + TTOption: int + Collate: int + LogPixels: int + BitsPerPel: int + PelsWidth: int + PelsHeight: int + DisplayFlags: int + DisplayFrequency: int + ICMMethod: int + ICMIntent: int + MediaType: int + DitherType: int + Reserved1: int + Reserved2: int + Nup: int + PanningWidth: int + PanningHeight: int + DeviceName: str + FormName: str + + @property + def DriverData(self) -> bytes | None: ... + @DriverData.setter + def DriverData(self, value: bytes) -> None: ... + +@disjoint_base +class PyDISPLAY_DEVICE: + @property + def Size(self) -> int: ... + @property + def DeviceName(self) -> str: ... + @property + def DeviceString(self) -> str: ... + @property + def StateFlags(self) -> int: ... + @property + def DeviceID(self) -> str: ... + @property + def DeviceKey(self) -> str: ... + def Clear(self) -> None: ... + +class PyDLGITEMTEMPLATE: ... +class PyDLGTEMPLATE: ... +class PyDS_HANDLE: ... +class PyDS_NAME_RESULT_ITEM: ... +class PyDialogTemplate: ... +class PyEVTLOG_HANDLE: ... +class PyEVT_HANDLE: ... +class PyEVT_RPC_LOGIN: ... + +class PyEventLogRecord: + @property + def Reserved(self) -> int: ... + @property + def RecordNumber(self) -> int: ... + @property + def TimeGenerated(self) -> TimeType: ... + @property + def TimeWritten(self) -> TimeType: ... + @property + def EventID(self) -> int: ... + @property + def EventType(self) -> int: ... + @property + def EventCategory(self) -> int: ... + @property + def ReservedFlags(self) -> int: ... + @property + def ClosingRecordNumber(self) -> int: ... + @property + def SourceName(self) -> str: ... + @property + def StringInserts(self) -> tuple[str, ...]: ... + @property + def Sid(self) -> PySID | None: ... + @property + def Data(self) -> str: ... + @property + def ComputerName(self) -> str: ... + +class PyGROUP_INFO_0: + @property + def name(self) -> str: ... + +class PyGROUP_INFO_1: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + +class PyGROUP_INFO_1002: + @property + def comment(self) -> str: ... + +class PyGROUP_INFO_1005: + @property + def attributes(self): ... + +class PyGROUP_INFO_2: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def group_id(self): ... + @property + def attributes(self): ... + +class PyGROUP_USERS_INFO_0: + @property + def name(self) -> str: ... + +class PyGROUP_USERS_INFO_1: + @property + def name(self) -> str: ... + @property + def attributes(self): ... + +class PyGdiHANDLE: ... +class PyGetSignerCertificate: ... + +@disjoint_base +class PyHANDLE: # type: ignore[type-var] + def __new__(cls, *args: Never) -> Never: ... + @property + def handle(self) -> int: ... + def Close(self) -> None: ... + def close(self) -> None: ... + def Detach(self) -> Self: ... + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + # PyHANDLE sets a lot more dunder methods, only to make them all raise with `TypeError: bad operand type` + +@final +class PyHDESK: + def __new__(self, handle) -> Self: ... + def SetThreadDesktop(self) -> None: ... + def EnumDesktopWindows(self) -> tuple[int, ...]: ... + def SwitchDesktop(self) -> None: ... + def CloseDesktop(self) -> None: ... + def Detach(self) -> int: ... + +class PyHDEVNOTIFY: ... + +class PyHHNTRACK: + @property + def action(self): ... + @property + def hdr(self): ... + @property + def curUrl(self) -> str: ... + @property + def winType(self): ... + +class PyHHN_NOTIFY: + @property + def hdr(self): ... + @property + def url(self) -> str: ... + +class PyHH_AKLINK: + @property + def indexOnFail(self): ... + @property + def keywords(self) -> str: ... + @property + def url(self) -> str: ... + @property + def msgText(self) -> str: ... + @property + def msgTitle(self) -> str: ... + @property + def window(self) -> str: ... + +class PyHH_FTS_QUERY: + @property + def uniCodeStrings(self): ... + @property + def proximity(self): ... + @property + def stemmedSearch(self): ... + @property + def titleOnly(self): ... + @property + def execute(self): ... + @property + def searchQuery(self) -> str: ... + +class PyHH_POPUP: + @property + def hinst(self): ... + @property + def idString(self): ... + @property + def clrForeground(self): ... + @property + def clrBackground(self): ... + @property + def text(self) -> str: ... + @property + def font(self) -> str: ... + @property + def pt(self): ... + @property + def margins(self): ... + +class PyHH_WINTYPE: + @property + def uniCodeStrings(self): ... + @property + def validMembers(self): ... + @property + def winProperties(self): ... + @property + def styles(self): ... + @property + def exStyles(self): ... + @property + def showState(self): ... + @property + def hwndHelp(self): ... + @property + def hwndCaller(self): ... + @property + def hwndToolBar(self): ... + @property + def hwndNavigation(self): ... + @property + def hwndHTML(self): ... + @property + def navWidth(self): ... + @property + def toolBarFlags(self): ... + @property + def notExpanded(self): ... + @property + def curNavType(self): ... + @property + def idNotify(self): ... + @property + def typeName(self) -> str: ... + @property + def caption(self) -> str: ... + @property + def windowPos(self): ... + @property + def HTMLPos(self): ... + @property + def toc(self) -> str: ... + @property + def index(self) -> str: ... + @property + def file(self) -> str: ... + @property + def home(self) -> str: ... + @property + def jump1(self) -> str: ... + @property + def jump2(self) -> str: ... + @property + def urlJump1(self) -> str: ... + @property + def urlJump2(self) -> str: ... + +class PyHINTERNET: ... + +class PyHKEY: + def Close(self): ... + +class PyHTHEME: ... + +@final +class PyHWINSTA: + def __new__(self, handle) -> Self: ... + def EnumDesktops(self) -> tuple[Incomplete, ...]: ... + def SetProcessWindowStation(self) -> None: ... + def CloseWindowStation(self) -> None: ... + def Detach(self) -> int: ... + +class PyICONINFO: ... + +@final +class PyIID: ... + +@final +class PyINPUT_RECORD: + def __new__(self, EventType: int) -> Self: ... + EventType: int + KeyDown: int | bool + RepeatCount: int + VirtualKeyCode: int + VirtualScanCode: Incomplete + Char: str + ControlKeyState: int + ButtonState: int + EventFlags: int + MousePosition: PyCOORD + Size: PyCOORD + SetFocus: Incomplete + CommandId: Incomplete + +class PyLOCALGROUP_INFO_0: + @property + def name(self) -> str: ... + +class PyLOCALGROUP_INFO_1: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + +class PyLOCALGROUP_INFO_1002: + @property + def comment(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_0: + @property + def sid(self) -> PySID: ... + +class PyLOCALGROUP_MEMBERS_INFO_1: + @property + def sid(self) -> PySID: ... + @property + def sidusage(self): ... + @property + def name(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_2: + @property + def sid(self) -> PySID: ... + @property + def sidusage(self): ... + @property + def domainandname(self) -> str: ... + +class PyLOCALGROUP_MEMBERS_INFO_3: + @property + def domainandname(self) -> str: ... + +class PyLOGBRUSH: + @property + def Style(self): ... + @property + def Color(self): ... + @property + def Hatch(self) -> int: ... + +class PyLOGFONT: + @property + def lfHeight(self) -> int: ... + @property + def lfWidth(self) -> int: ... + @property + def lfEscapement(self) -> int: ... + @property + def lfOrientation(self) -> int: ... + @property + def lfWeight(self) -> int: ... + @property + def lfItalic(self) -> int: ... + @property + def lfUnderline(self) -> int: ... + @property + def lfStrikeOut(self) -> int: ... + @property + def lfCharSet(self) -> int: ... + @property + def lfOutPrecision(self) -> int: ... + @property + def lfClipPrecision(self) -> int: ... + @property + def lfQuality(self) -> int: ... + @property + def lfPitchAndFamily(self) -> int: ... + @property + def lfFaceName(self) -> str: ... + +class PyLSA_HANDLE: ... +class PyLUID_AND_ATTRIBUTES: ... +class PyLsaLogon_HANDLE: ... +class PyMSG: ... + +@final +class PyNETRESOURCE: + dwScope: int + dwType: int + dwDisplayType: int + dwUsage: int + lpComment: str | None + lpLocalName: str | None + lpProvider: str | None + lpRemoteName: str | None + +class PyNET_VALIDATE_AUTHENTICATION_INPUT_ARG: ... +class PyNET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG: ... +class PyNET_VALIDATE_PERSISTED_FIELDS: ... + +class PyNMHDR: + @property + def hwndFrom(self): ... + @property + def idFrom(self): ... + @property + def code(self): ... + +class PyNOTIFYICONDATA: ... + +class PyOVERLAPPED: + Offset: int + OffsetHigh: int + object: object + dword: int + hEvent: int + Internal: int + InternalHigh: int + +class PyOVERLAPPEDReadBuffer: ... + +class PyPERF_COUNTER_DEFINITION: + @property + def DefaultScale(self) -> int: ... + @property + def DetailLevel(self) -> int: ... + @property + def CounterType(self) -> int: ... + @property + def CounterNameTitleIndex(self) -> int: ... + @property + def CounterHelpTitleIndex(self) -> int: ... + def Increment(self) -> None: ... + def Decrement(self) -> None: ... + def Set(self) -> None: ... + def Get(self) -> None: ... + +class PyPERF_OBJECT_TYPE: + @property + def ObjectNameTitleIndex(self) -> int: ... + @property + def ObjectHelpTitleIndex(self) -> int: ... + @property + def DefaultCounterIndex(self) -> int: ... + def Close(self) -> None: ... + +class PyPOINT: ... + +class PyPROFILEINFO: + @property + def UserName(self) -> str: ... + @property + def Flags(self): ... + @property + def ProfilePath(self) -> str: ... + @property + def DefaultPath(self) -> str: ... + @property + def ServerName(self) -> str: ... + @property + def PolicyPath(self) -> str: ... + @property + def Profile(self) -> PyHKEY: ... + +class PyPerfMonManager: + def Close(self) -> None: ... + +class PyPrinterHANDLE(PyHANDLE): ... +class PyRECT: ... +class PyResourceId: ... +class PySCROLLINFO: ... +class PySC_HANDLE: ... + +class PySECURITY_ATTRIBUTES: + bInheritHandle: int + SECURITY_DESCRIPTOR: PySECURITY_DESCRIPTOR + +class PySECURITY_DESCRIPTOR: + def Initialize(self) -> None: ... + def GetSecurityDescriptorOwner(self) -> PySID: ... + def GetSecurityDescriptorDacl(self) -> PyACL: ... + def GetSecurityDescriptorSacl(self) -> PyACL: ... + def GetSecurityDescriptorControl(self) -> tuple[Incomplete, Incomplete]: ... + def SetSecurityDescriptorOwner(self, sid: PySID, bOwnerDefaulted: int | bool, /) -> None: ... + def SetSecurityDescriptorGroup(self, sid: PySID, bOwnerDefaulted, /): ... + def SetSecurityDescriptorDacl(self, bSaclPresent: int | bool, SACL: PyACL, bSaclDefaulted: int | bool, /) -> None: ... + def SetSecurityDescriptorSacl(self, bSaclPresent, SACL: PyACL, bSaclDefaulted, /) -> None: ... + def SetSecurityDescriptorControl(self, ControlBitsOfInterest, ControlBitsToSet, /) -> None: ... + def IsValid(self) -> bool: ... + def GetLength(self) -> None: ... + def IsSelfRelative(self) -> bool: ... + +class PySERVER_INFO_100: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + +class PySERVER_INFO_101: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + @property + def version_major(self): ... + @property + def version_minor(self): ... + @property + def type(self): ... + @property + def comment(self) -> str: ... + +class PySERVER_INFO_102: + @property + def platform_id(self): ... + @property + def name(self) -> str: ... + @property + def version_major(self): ... + @property + def version_minor(self): ... + @property + def type(self): ... + @property + def comment(self) -> str: ... + @property + def users(self): ... + @property + def disc(self): ... + @property + def hidden(self): ... + @property + def announce(self): ... + @property + def anndelta(self): ... + @property + def userpath(self) -> str: ... + +class PySERVER_INFO_402: + @property + def ulist_mtime(self): ... + @property + def glist_mtime(self): ... + @property + def alist_mtime(self): ... + @property + def security(self): ... + @property + def numadmin(self): ... + @property + def lanmask(self): ... + @property + def guestacct(self) -> str: ... + @property + def chdevs(self): ... + @property + def chdevq(self): ... + @property + def chdevjobs(self): ... + @property + def connections(self): ... + @property + def shares(self): ... + @property + def openfiles(self): ... + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def sessreqs(self): ... + @property + def opensearch(self): ... + @property + def activelocks(self): ... + @property + def numreqbuf(self): ... + @property + def sizreqbuf(self): ... + @property + def numbigbuf(self): ... + @property + def numfiletasks(self): ... + @property + def alertsched(self): ... + @property + def erroralert(self): ... + @property + def logonalert(self): ... + @property + def accessalert(self): ... + @property + def diskalert(self): ... + @property + def netioalert(self): ... + @property + def maxauditsz(self): ... + @property + def srvheuristics(self) -> str: ... + +class PySERVER_INFO_403: + @property + def ulist_mtime(self): ... + @property + def glist_mtime(self): ... + @property + def alist_mtime(self): ... + @property + def security(self): ... + @property + def numadmin(self): ... + @property + def lanmask(self): ... + @property + def guestacct(self) -> str: ... + @property + def chdevs(self): ... + @property + def chdevq(self): ... + @property + def chdevjobs(self): ... + @property + def connections(self): ... + @property + def shares(self): ... + @property + def openfiles(self): ... + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def sessreqs(self): ... + @property + def opensearch(self): ... + @property + def activelocks(self): ... + @property + def numreqbuf(self): ... + @property + def sizreqbuf(self): ... + @property + def numbigbuf(self): ... + @property + def numfiletasks(self): ... + @property + def alertsched(self): ... + @property + def erroralert(self): ... + @property + def logonalert(self): ... + @property + def accessalert(self): ... + @property + def diskalert(self): ... + @property + def netioalert(self): ... + @property + def maxauditsz(self): ... + @property + def srvheuristics(self) -> str: ... + @property + def auditedevents(self): ... + @property + def autoprofile(self): ... + @property + def autopath(self) -> str: ... + +class PySERVER_INFO_502: + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def opensearch(self): ... + @property + def sizreqbuf(self): ... + @property + def initworkitems(self): ... + @property + def maxworkitems(self): ... + @property + def rawworkitems(self): ... + @property + def irpstacksize(self): ... + @property + def maxrawbuflen(self): ... + @property + def sessusers(self): ... + @property + def sessconns(self): ... + @property + def maxpagedmemoryusage(self): ... + @property + def maxnonpagedmemoryusage(self): ... + @property + def enableforcedlogoff(self): ... + @property + def timesource(self): ... + @property + def acceptdownlevelapis(self): ... + @property + def lmannounce(self): ... + +class PySERVER_INFO_503: + @property + def sessopens(self): ... + @property + def sessvcs(self): ... + @property + def opensearch(self): ... + @property + def sizreqbuf(self): ... + @property + def initworkitems(self): ... + @property + def maxworkitems(self): ... + @property + def rawworkitems(self): ... + @property + def irpstacksize(self): ... + @property + def maxrawbuflen(self): ... + @property + def sessusers(self): ... + @property + def sessconns(self): ... + @property + def maxpagedmemoryusage(self): ... + @property + def maxnonpagedmemoryusage(self): ... + @property + def enableforcedlogoff(self): ... + @property + def timesource(self): ... + @property + def acceptdownlevelapis(self): ... + @property + def lmannounce(self): ... + @property + def domain(self) -> str: ... + @property + def maxkeepsearch(self): ... + @property + def scavtimeout(self): ... + @property + def minrcvqueue(self): ... + @property + def minfreeworkitems(self): ... + @property + def xactmemsize(self): ... + @property + def threadpriority(self): ... + @property + def maxmpxct(self): ... + @property + def oplockbreakwait(self): ... + @property + def oplockbreakresponsewait(self): ... + @property + def enableoplocks(self): ... + @property + def enablefcbopens(self): ... + @property + def enableraw(self): ... + @property + def enablesharednetdrives(self): ... + @property + def minfreeconnections(self): ... + @property + def maxfreeconnections(self): ... + +class PySHARE_INFO_0: + @property + def netname(self) -> str: ... + +class PySHARE_INFO_1: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + +class PySHARE_INFO_2: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def permissions(self): ... + @property + def max_uses(self): ... + @property + def current_uses(self): ... + @property + def path(self) -> str: ... + @property + def passwd(self) -> str: ... + +class PySHARE_INFO_501: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def flags(self): ... + +class PySHARE_INFO_502: + @property + def netname(self) -> str: ... + @property + def type(self): ... + @property + def remark(self) -> str: ... + @property + def permissions(self): ... + @property + def max_uses(self): ... + @property + def current_uses(self): ... + @property + def path(self) -> str: ... + @property + def passwd(self) -> str: ... + @property + def reserved(self): ... + @property + def security_descriptor(self) -> PySECURITY_DESCRIPTOR: ... + +class PySID: + def Initialize(self, idAuthority, numSubauthorities, /) -> None: ... + def IsValid(self) -> bool: ... + def SetSubAuthority(self, index, val, /) -> None: ... + def GetLength(self): ... + def GetSubAuthorityCount(self): ... + def GetSubAuthority(self): ... + def GetSidIdentifierAuthority(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... + +class PySID_AND_ATTRIBUTES: ... +class PySIZE: ... + +@final +class PySMALL_RECT: + def __new__(self, Left: int = ..., Top: int = ..., Right: int = ..., Bottom: int = ...) -> Self: ... + Left: int + Top: int + Right: int + Bottom: int + +class PySTARTUPINFO: + dwX: int + dwY: int + dwXSize: int + dwYSize: int + dwXCountChars: int + dwYCountChars: int + dwFillAttribute: int + dwFlags: int + wShowWindow: int + hStdInput: int + hStdOutput: int + hStdError: int + lpDesktop: str + lpTitle: str + +@disjoint_base +class PySecBuffer: + def __new__(self, BufferSize, BufferType) -> Self: ... + @property + def BufferType(self): ... + @property + def Buffer(self) -> str: ... + @property + def BufferSize(self): ... + @property + def MaxBufferSize(self): ... + def Clear(self) -> None: ... + +@disjoint_base +class PySecBufferDesc: + def __new__(self, Version=...) -> Self: ... + Version: Incomplete + Buffer: Incomplete + def append(self, buffer, /) -> None: ... + def __getitem__(self, index: SupportsIndex, /) -> PySecBuffer: ... + +class PyTOKEN_GROUPS: ... +class PyTOKEN_PRIVILEGES: ... + +class PyTRIVERTEX: + @property + def x(self): ... + @property + def y(self): ... + @property + def Red(self): ... + @property + def Green(self): ... + @property + def Blue(self): ... + @property + def Alpha(self): ... + +# Properties Multiple* are ignored +class PyTRUSTEE: + @property + def TrusteeForm(self) -> int: ... + @property + def TrusteeType(self) -> int: ... + @property + def Identifier(self) -> PySID: ... + @property + def MultipleTrustee(self) -> None: ... + @property + def MultipleTrusteeOperation(self) -> Literal[0]: ... + +class PyTS_HANDLE: ... + +class PyUSER_INFO_0: + @property + def name(self) -> str: ... + +class PyUSER_INFO_1: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + +class PyUSER_INFO_10: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def full_name(self) -> str: ... + +class PyUSER_INFO_1003: + @property + def password(self) -> str: ... + +class PyUSER_INFO_1005: + @property + def priv(self): ... + +class PyUSER_INFO_1006: + @property + def home_dir(self) -> str: ... + +class PyUSER_INFO_1007: + @property + def comment(self) -> str: ... + +class PyUSER_INFO_1008: + @property + def flags(self): ... + +class PyUSER_INFO_1009: + @property + def script_path(self) -> str: ... + +class PyUSER_INFO_1010: + @property + def auth_flags(self): ... + +class PyUSER_INFO_1011: + @property + def full_name(self) -> str: ... + +class PyUSER_INFO_11: + @property + def name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def full_name(self) -> str: ... + @property + def priv(self): ... + @property + def auth_flags(self): ... + @property + def password_age(self): ... + @property + def home_dir(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def workstations(self) -> str: ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def code_page(self): ... + +class PyUSER_INFO_2: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + +class PyUSER_INFO_20: + @property + def name(self) -> str: ... + @property + def full_name(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def user_id(self): ... + +class PyUSER_INFO_3: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + @property + def user_id(self): ... + @property + def primary_group_id(self): ... + @property + def profile(self) -> str: ... + @property + def home_dir_drive(self) -> str: ... + @property + def password_expired(self): ... + +class PyUSER_INFO_4: + @property + def name(self) -> str: ... + @property + def password(self) -> str: ... + @property + def password_age(self): ... + @property + def priv(self): ... + @property + def home_dir(self) -> str: ... + @property + def comment(self) -> str: ... + @property + def flags(self): ... + @property + def script_path(self) -> str: ... + @property + def auth_flags(self): ... + @property + def full_name(self) -> str: ... + @property + def usr_comment(self) -> str: ... + @property + def parms(self) -> str: ... + @property + def workstations(self) -> str: ... + @property + def last_logon(self): ... + @property + def last_logoff(self): ... + @property + def acct_expires(self): ... + @property + def max_storage(self): ... + @property + def units_per_week(self): ... + @property + def logon_hours(self) -> str: ... + @property + def bad_pw_count(self): ... + @property + def num_logons(self): ... + @property + def logon_server(self) -> str: ... + @property + def country_code(self): ... + @property + def code_page(self): ... + @property + def user_sid(self) -> PySID: ... + @property + def primary_group_id(self): ... + @property + def profile(self) -> str: ... + @property + def home_dir_drive(self) -> str: ... + @property + def password_expired(self): ... + +class PyUSER_MODALS_INFO_0: + @property + def min_passwd_len(self): ... + @property + def max_passwd_age(self): ... + @property + def min_passwd_age(self): ... + @property + def force_logoff(self): ... + @property + def password_hist_len(self): ... + +class PyUSER_MODALS_INFO_1: + @property + def role(self): ... + @property + def primary(self) -> str: ... + +class PyUSER_MODALS_INFO_2: + @property + def domain_name(self) -> str: ... + @property + def domain_id(self) -> PySID: ... + +class PyUSER_MODALS_INFO_3: + @property + def lockout_duration(self): ... + @property + def lockout_observation_window(self): ... + @property + def usrmod3_lockout_threshold(self): ... + +class PyUSE_INFO_0: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + +class PyUSE_INFO_1: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + +class PyUSE_INFO_2: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + @property + def username(self) -> str: ... + @property + def domainname(self) -> str: ... + +class PyUSE_INFO_3: + @property + def local(self) -> str: ... + @property + def remote(self) -> str: ... + @property + def password(self) -> str: ... + @property + def status(self): ... + @property + def asg_type(self): ... + @property + def refcount(self): ... + @property + def usecount(self): ... + @property + def username(self) -> str: ... + @property + def domainname(self) -> str: ... + @property + def flags(self): ... + +class PyUrlCacheHANDLE: ... + +class PyWAVEFORMATEX: + @property + def wFormatTag(self) -> int: ... + @property + def nChannels(self) -> int: ... + @property + def nSamplesPerSec(self) -> int: ... + @property + def nAvgBytesPerSec(self) -> int: ... + @property + def nBlockAlign(self) -> int: ... + @property + def wBitsPerSample(self) -> int: ... + +class PyWINHTTP_AUTOPROXY_OPTIONS: ... +class PyWINHTTP_PROXY_INFO: ... + +class PyWKSTA_INFO_100: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + +class PyWKSTA_INFO_101: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + @property + def lanroot(self) -> str: ... + +class PyWKSTA_INFO_102: + @property + def platform_id(self): ... + @property + def computername(self) -> str: ... + @property + def langroup(self) -> str: ... + @property + def ver_major(self): ... + @property + def ver_minor(self): ... + @property + def lanroot(self) -> str: ... + @property + def logged_on_users(self): ... + +class PyWKSTA_INFO_302: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self): ... + @property + def keep_conn(self): ... + @property + def keep_search(self): ... + @property + def max_cmds(self): ... + @property + def num_work_buf(self): ... + @property + def siz_work_buf(self): ... + @property + def max_wrk_cache(self): ... + @property + def siz_error(self): ... + @property + def num_alerts(self): ... + @property + def num_services(self): ... + @property + def errlog_sz(self): ... + @property + def print_buf_time(self): ... + @property + def num_char_buf(self): ... + @property + def siz_char_buf(self): ... + @property + def wrk_heuristics(self) -> str: ... + @property + def mailslots(self): ... + @property + def num_dgram_buf(self): ... + +class PyWKSTA_INFO_402: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self) -> str: ... + @property + def keep_conn(self): ... + @property + def keep_search(self): ... + @property + def max_cmds(self): ... + @property + def num_work_buf(self): ... + @property + def siz_work_buf(self): ... + @property + def max_wrk_cache(self): ... + @property + def sess_timeout(self): ... + @property + def siz_error(self): ... + @property + def num_alerts(self): ... + @property + def num_services(self): ... + @property + def errlog_sz(self): ... + @property + def print_buf_time(self): ... + @property + def num_char_buf(self): ... + @property + def siz_char_buf(self): ... + @property + def mailslots(self): ... + @property + def num_dgram_buf(self): ... + @property + def max_threads(self): ... + +class PyWKSTA_INFO_502: + @property + def char_wait(self): ... + @property + def collection_time(self): ... + @property + def maximum_collection_count(self): ... + @property + def keep_conn(self): ... + @property + def max_cmds(self): ... + @property + def max_wrk_cache(self): ... + @property + def siz_char_buf(self): ... + @property + def lock_quota(self): ... + @property + def lock_increment(self): ... + @property + def lock_maximum(self): ... + @property + def pipe_increment(self): ... + @property + def pipe_maximum(self): ... + @property + def cache_file_timeout(self): ... + @property + def dormant_file_limit(self): ... + @property + def read_ahead_throughput(self): ... + @property + def num_mailslot_buffers(self): ... + @property + def num_srv_announce_buffers(self): ... + @property + def max_illegal_datagram_events(self): ... + @property + def illegal_datagram_event_reset_frequency(self): ... + @property + def log_election_packets(self): ... + @property + def use_opportunistic_locking(self): ... + @property + def use_unlock_behind(self): ... + @property + def use_close_behind(self): ... + @property + def buf_named_pipes(self): ... + @property + def use_lock_read_unlock(self): ... + @property + def utilize_nt_caching(self): ... + @property + def use_raw_read(self): ... + @property + def use_raw_write(self): ... + @property + def use_write_raw_data(self): ... + @property + def use_encryption(self): ... + @property + def buf_files_deny_write(self): ... + @property + def buf_read_only_files(self): ... + @property + def force_core_create_mode(self): ... + @property + def use_512_byte_max_transfer(self): ... + +class PyWKSTA_TRANSPORT_INFO_0: + @property + def quality_of_service(self): ... + @property + def number_of_vcs(self): ... + @property + def transport_name(self) -> str: ... + @property + def transport_address(self) -> str: ... + @property + def wan_ish(self): ... + +class PyWKSTA_USER_INFO_0: + @property + def username(self) -> str: ... + +class PyWKSTA_USER_INFO_1: + @property + def username(self) -> str: ... + @property + def logon_domain(self) -> str: ... + @property + def oth_domains(self) -> str: ... + @property + def logon_server(self) -> str: ... + +class PyWNDCLASS: + @property + def style(self) -> int: ... + @property + def cbWndExtra(self) -> int: ... + @property + def hInstance(self) -> int: ... + @property + def hIcon(self) -> int: ... + @property + def hCursor(self) -> int: ... + @property + def hbrBackground(self) -> int: ... + @property + def lpszMenuName(self) -> str: ... + @property + def lpszClassName(self) -> str: ... + @property + def lpfnWndProc(self): ... + def SetDialogProc(self) -> None: ... + +class PyXFORM: + @property + def M11(self) -> float: ... + @property + def M12(self) -> float: ... + @property + def M21(self) -> float: ... + @property + def M22(self) -> float: ... + @property + def Dx(self) -> float: ... + @property + def Dy(self) -> float: ... + +class Pymmapfile: + def close(self) -> None: ... + def find(self, needle, start, /): ... + def flush(self, offset: int = ..., size: int = ..., /) -> None: ... + def move(self, dest, src, count, /) -> None: ... + def read(self, num_bytes, /): ... + def read_byte(self): ... + def read_line(self): ... + def resize(self, MaximumSize, FileOffset: int = ..., NumberOfBytesToMap: int = ...) -> None: ... + def seek(self, dist: int, how: int = ..., /) -> None: ... + def size(self): ... + def tell(self): ... + def write(self, data, /) -> None: ... + def write_byte(self, char, /) -> None: ... + +class RASDIALEXTENSIONS: + @property + def dwfOptions(self) -> int: ... + @property + def hwndParent(self) -> int: ... + @property + def reserved(self) -> int: ... + @property + def reserved1(self) -> int: ... + @property + def RasEapInfo(self): ... + +class RASDIALPARAMS: ... + +class SC_ACTION: + @property + def Type(self): ... + @property + def Delay(self): ... + +class SERVICE_FAILURE_ACTIONS: + @property + def ResetPeriod(self): ... + @property + def RebootMsg(self) -> str: ... + @property + def Command(self) -> str: ... + @property + def Actions(self): ... + +class SERVICE_STATUS: + def __getitem__(self, i: int, /) -> int: ... + +class TRACKMOUSEEVENT: ... +class WIN32_FIND_DATA: ... + +class connection: + def setautocommit(self, c, /) -> None: ... + def commit(self) -> None: ... + def rollback(self) -> None: ... + def cursor(self) -> None: ... + def close(self) -> None: ... + +class cursor: + def close(self) -> None: ... + def execute(self, sql: str, arg, /): ... + def fetchone(self): ... + def fetchmany(self) -> list[Incomplete]: ... + def fetchall(self) -> list[Incomplete]: ... + def setinputsizes(self) -> None: ... + def setoutputsize(self) -> None: ... + +class COMPONENT: + @property + def ID(self): ... + @property + def ComponentType(self): ... + @property + def Checked(self): ... + @property + def fDirty(self): ... + @property + def NoScroll(self): ... + @property + def Pos(self): ... + @property + def FriendlyName(self): ... + @property + def Source(self): ... + @property + def SubscribedURL(self): ... + @property + def CurItemState(self): ... + @property + def Original(self): ... + @property + def Restored(self): ... + @property + def Size(self): ... + +class COMPONENTSOPT: + @property + def EnableComponents(self): ... + @property + def ActiveDesktop(self): ... + @property + def Size(self): ... + +class COMPPOS: + @property + def Left(self): ... + @property + def Top(self): ... + @property + def Width(self): ... + @property + def Height(self): ... + @property + def Index(self): ... + @property + def CanResize(self): ... + @property + def CanResizeX(self): ... + @property + def CanResizeY(self): ... + @property + def PreferredLeftPercent(self): ... + @property + def PreferredTopPercent(self): ... + @property + def Size(self): ... + +class COMPSTATEINFO: + @property + def Left(self): ... + @property + def Top(self): ... + @property + def Width(self): ... + @property + def Height(self): ... + @property + def dwItemState(self): ... + @property + def Size(self): ... + +class DEFCONTENTMENU: ... +class ELEMDESC: ... + +class EXP_DARWIN_LINK: + @property + def Signature(self): ... + @property + def DarwinID(self): ... + @property + def wDarwinID(self): ... + @property + def Size(self): ... + +class EXP_SPECIAL_FOLDER: + @property + def Signature(self): ... + @property + def idSpecialFolder(self): ... + @property + def Offset(self): ... + @property + def Size(self): ... + +class EXP_SZ_LINK: + @property + def Signature(self): ... + @property + def Target(self): ... + @property + def wTarget(self): ... + @property + def Size(self): ... + +class FUNCDESC: + @property + def memid(self) -> int: ... + @property + def scodeArray(self) -> tuple[Incomplete, ...]: ... + @property + def args(self) -> tuple[ELEMDESC, ...]: ... + @property + def funckind(self): ... + @property + def invkind(self): ... + @property + def callconv(self): ... + @property + def cParamsOpt(self): ... + @property + def oVft(self): ... + @property + def rettype(self) -> ELEMDESC: ... + @property + def wFuncFlags(self): ... + +class IDLDESC: ... +class MAPIINIT_0: ... + +class NT_CONSOLE_PROPS: + @property + def Signature(self): ... + @property + def FillAttribute(self): ... + @property + def PopupFillAttribute(self): ... + @property + def ScreenBufferSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def WindowSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def WindowOrigin(self) -> tuple[Incomplete, Incomplete]: ... + @property + def nFont(self): ... + @property + def InputBufferSize(self): ... + @property + def FontSize(self) -> tuple[Incomplete, Incomplete]: ... + @property + def FontFamily(self): ... + @property + def FontWeight(self): ... + @property + def FaceName(self): ... + @property + def CursorSize(self): ... + @property + def FullScreen(self): ... + @property + def QuickEdit(self): ... + @property + def InsertMode(self): ... + @property + def AutoPosition(self): ... + @property + def HistoryBufferSize(self): ... + @property + def NumberOfHistoryBuffers(self): ... + @property + def HistoryNoDup(self): ... + @property + def ColorTable(self): ... + @property + def Size(self): ... + +class NT_FE_CONSOLE_PROPS: + @property + def Signature(self): ... + @property + def CodePage(self): ... + @property + def Size(self): ... + +class PROPSPEC: ... +class PyADSVALUE: ... + +class PyADS_ATTR_INFO: + @property + def AttrName(self): ... + @property + def ControlCode(self) -> int: ... + @property + def ADsType(self) -> int: ... + @property + def Values(self) -> list[Incomplete]: ... + +class PyADS_OBJECT_INFO: + @property + def RDN(self): ... + @property + def ObjectDN(self): ... + @property + def ParentDN(self): ... + @property + def ClassName(self): ... + +class PyADS_SEARCHPREF_INFO: ... + +class PyBIND_OPTS: + @property + def Flags(self): ... + @property + def Mode(self): ... + @property + def TickCountDeadline(self): ... + @property + def cbStruct(self): ... + +class PyCMINVOKECOMMANDINFO: ... + +@disjoint_base +class PyDSBCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwUnlockTransferRate(self) -> int: ... + @property + def dwBufferBytes(self): ... + @property + def dwPlayCpuOverhead(self): ... + +@disjoint_base +class PyDSBUFFERDESC: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + @property + def lpwfxFormat(self): ... + +@disjoint_base +class PyDSCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwMinSecondarySampleRate(self) -> int: ... + @property + def dwMaxSecondarySampleRate(self) -> int: ... + @property + def dwPrimaryBuffers(self) -> int: ... + @property + def dwMaxHwMixingAllBuffers(self) -> int: ... + @property + def dwMaxHwMixingStaticBuffers(self) -> int: ... + @property + def dwMaxHwMixingStreamingBuffers(self) -> int: ... + @property + def dwFreeHwMixingAllBuffers(self) -> int: ... + @property + def dwFreeHwMixingStaticBuffers(self) -> int: ... + @property + def dwFreeHwMixingStreamingBuffers(self) -> int: ... + @property + def dwMaxHw3DAllBuffers(self) -> int: ... + @property + def dwMaxHw3DStaticBuffers(self) -> int: ... + @property + def dwMaxHw3DStreamingBuffers(self) -> int: ... + @property + def dwFreeHw3DAllBuffers(self) -> int: ... + @property + def dwFreeHw3DStaticBuffers(self) -> int: ... + @property + def dwFreeHw3DStreamingBuffers(self) -> int: ... + @property + def dwTotalHwMemBytes(self) -> int: ... + @property + def dwFreeHwMemBytes(self) -> int: ... + @property + def dwMaxContigFreeHwMemBytes(self) -> int: ... + @property + def dwUnlockTransferRateHwBuffers(self) -> int: ... + @property + def dwPlayCpuOverheadSwBuffers(self) -> int: ... + +@disjoint_base +class PyDSCBCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + +@disjoint_base +class PyDSCBUFFERDESC: + @property + def dwFlags(self) -> int: ... + @property + def dwBufferBytes(self) -> int: ... + @property + def lpwfxFormat(self): ... + +@disjoint_base +class PyDSCCAPS: + @property + def dwFlags(self) -> int: ... + @property + def dwFormats(self) -> int: ... + @property + def dwChannels(self) -> int: ... + +class PyDSOP_FILTER_FLAGS: + @property + def uplevel(self) -> PyDSOP_UPLEVEL_FILTER_FLAGS: ... + @property + def downlevel(self): ... + +class PyDSOP_SCOPE_INIT_INFO: + @property + def type(self): ... + @property + def scope(self): ... + @property + def hr(self): ... + @property + def dcName(self) -> str: ... + @property + def filterFlags(self) -> PyDSOP_FILTER_FLAGS: ... + +@disjoint_base +class PyDSOP_SCOPE_INIT_INFOs: + def __new__(cls, size, /): ... + +class PyDSOP_UPLEVEL_FILTER_FLAGS: + @property + def bothModes(self): ... + @property + def mixedModeOnly(self): ... + @property + def nativeModeOnly(self): ... + +class PyFORMATETC: ... + +class PyGFileOperationProgressSink: + def StartOperations(self) -> None: ... + def FinishOperations(self, Result, /) -> None: ... + def PreRenameItem(self, Flags, Item: PyIShellItem, NewName, /) -> None: ... + def PostRenameItem(self, Flags, Item: PyIShellItem, NewName, hrRename, NewlyCreated: PyIShellItem, /) -> None: ... + def PreMoveItem(self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostMoveItem( + self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, hrMove, NewlyCreated: PyIShellItem, / + ) -> None: ... + def PreCopyItem(self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostCopyItem( + self, Flags, Item: PyIShellItem, DestinationFolder: PyIShellItem, NewName, hrCopy, NewlyCreated: PyIShellItem, / + ) -> None: ... + def PreDeleteItem(self, Flags, Item: PyIShellItem, /) -> None: ... + def PostDeleteItem(self, Flags, Item: PyIShellItem, hrDelete, NewlyCreated: PyIShellItem, /) -> None: ... + def PreNewItem(self, Flags, DestinationFolder: PyIShellItem, NewName, /) -> None: ... + def PostNewItem( + self, Flags, DestinationFolder: PyIShellItem, NewName, TemplateName, FileAttributes, hrNew, NewItem: PyIShellItem, / + ) -> None: ... + def UpdateProgress(self, WorkTotal, WorkSoFar, /) -> None: ... + def ResetTimer(self) -> None: ... + def PauseTimer(self) -> None: ... + def ResumeTimer(self) -> None: ... + +class PyGSecurityInformation: + def GetObjectInformation(self) -> SI_OBJECT_INFO: ... + def GetSecurity(self, RequestedInformation, Default, /) -> PySECURITY_DESCRIPTOR: ... + def SetSecurity(self, SecurityInformation, SecurityDescriptor: PySECURITY_DESCRIPTOR, /) -> None: ... + def GetAccessRights(self, ObjectType: PyIID, Flags, /) -> tuple[SI_ACCESS, Incomplete]: ... + def MapGeneric(self, ObjectType: PyIID, AceFlags, Mask, /): ... + def GetInheritTypes(self) -> tuple[SI_INHERIT_TYPE, ...]: ... + def PropertySheetPageCallback(self, hwnd: int, Msg, Page, /) -> None: ... + +class PyIADesktopP2: + def UpdateAllDesktopSubscriptions(self) -> None: ... + +class PyIADs: + @property + def ADsPath(self) -> str: ... + @property + def AdsPath(self) -> str: ... + @property + def Class(self) -> str: ... + @property + def GUID(self) -> str: ... + @property + def Name(self) -> str: ... + @property + def Parent(self) -> str: ... + @property + def Schema(self) -> str: ... + def GetInfo(self) -> None: ... + def SetInfo(self) -> None: ... + def Get(self, prop: str, /): ... + def Put(self, _property: str, val, /) -> None: ... + def get(self, prop: str, /): ... + def put(self, _property: str, val, /) -> None: ... + +class PyIADsContainer: + def GetObject(self, _class: str, relativeName: str, /) -> PyIDispatch: ... + def get_Count(self): ... + def get_Filter(self): ... + def put_Filter(self, val, /) -> None: ... + def get_Hints(self): ... + def put_Hints(self, val, /) -> None: ... + +class PyIADsUser: + def get_AccountDisabled(self): ... + def put_AccountDisabled(self, val, /) -> None: ... + def get_AccountExpirationDate(self): ... + def put_AccountExpirationDate(self, val: TimeType, /) -> None: ... + def get_BadLoginAddress(self): ... + def get_BadLoginCount(self): ... + def get_Department(self): ... + def put_Department(self, val, /) -> None: ... + def get_Description(self): ... + def put_Description(self, val, /) -> None: ... + def get_Division(self): ... + def put_Division(self, val, /) -> None: ... + def get_EmailAddress(self): ... + def put_EmailAddress(self, val, /) -> None: ... + def get_EmployeeID(self): ... + def put_EmployeeID(self, val, /) -> None: ... + def get_FirstName(self): ... + def put_FirstName(self, val, /) -> None: ... + def get_FullName(self): ... + def put_FullName(self, val, /) -> None: ... + def get_HomeDirectory(self): ... + def put_HomeDirectory(self, val, /) -> None: ... + def get_HomePage(self): ... + def put_HomePage(self, val, /) -> None: ... + def get_LoginScript(self): ... + def put_LoginScript(self, val, /) -> None: ... + def SetPassword(self, val, /) -> None: ... + def ChangePassword(self, oldval, newval, /) -> None: ... + +class PyIActiveDesktop: + def ApplyChanges(self, Flags, /) -> None: ... + def GetWallpaper(self, cchWallpaper, Reserved: int = ..., /): ... + def SetWallpaper(self, Wallpaper, Reserved: int = ..., /) -> None: ... + def GetWallpaperOptions(self, Reserved: int = ..., /): ... + def SetWallpaperOptions(self, Style, Reserved: int = ..., /) -> None: ... + def GetPattern(self, cchPattern: int = ..., Reserved: int = ..., /) -> None: ... + def SetPattern(self, Pattern, Reserved: int = ..., /) -> None: ... + def GetDesktopItemOptions(self): ... + def SetDesktopItemOptions(self, comp, Reserved: int = ..., /) -> None: ... + def AddDesktopItem(self, comp, Reserved: int = ..., /) -> None: ... + def AddDesktopItemWithUI(self, hwnd: int, comp, Flags, /) -> None: ... + def ModifyDesktopItem(self, comp, Flags, /) -> None: ... + def RemoveDesktopItem(self, comp, Reserved: int = ..., /) -> None: ... + def GetDesktopItemCount(self) -> None: ... + def GetDesktopItem(self, Component, Reserved: int = ..., /): ... + def GetDesktopItemByID(self, ID, reserved: int = ..., /): ... + def GenerateDesktopItemHtml(self, FileName, comp, Reserved: int = ..., /) -> None: ... + def AddUrl(self, hwnd: int, Source, comp, Flags, /) -> None: ... + def GetDesktopItemBySource(self, Source, Reserved: int = ..., /): ... + +class PyIActiveDesktopP: + def SetSafeMode(self, Flags, /) -> None: ... + +class PyIActiveScriptDebug: + def GetScriptTextAttributes(self, pstrCode: str, pstrDelimiter: str, dwFlags, /) -> tuple[Incomplete, ...]: ... + def GetScriptletTextAttributes(self, pstrCode: str, pstrDelimiter: str, dwFlags, /) -> None: ... + def EnumCodeContextsOfPosition(self, dwSourceContext, uCharacterOffset, uNumChars, /) -> None: ... + +class PyIActiveScriptError: + def GetExceptionInfo(self) -> None: ... + def GetSourcePosition(self) -> None: ... + def GetSourceLineText(self) -> None: ... + +class PyIActiveScriptErrorDebug: + def GetDocumentContext(self) -> None: ... + def GetStackFrame(self) -> None: ... + +class PyIActiveScriptParseProcedure: + def ParseProcedureText( + self, + pstrCode, + pstrFormalParams, + pstrProcedureName, + pstrItemName, + punkContext: PyIUnknown, + pstrDelimiter, + dwSourceContextCookie, + ulStartingLineNumber, + dwFlags, + /, + ) -> None: ... + +class PyIActiveScriptSite: + def GetLCID(self): ... + def GetItemInfo(self): ... + def GetDocVersionString(self): ... + def OnStateChange(self): ... + def OnEnterScript(self): ... + def OnLeaveScript(self): ... + def OnScriptError(self): ... + def OnScriptTerminate(self): ... + +class PyIActiveScriptSiteDebug: + def GetDocumentContextFromPosition(self, dwSourceContext, uCharacterOffset, uNumChars, /) -> None: ... + def GetApplication(self) -> None: ... + def GetRootApplicationNode(self) -> None: ... + def OnScriptErrorDebug(self) -> tuple[Incomplete, Incomplete]: ... + +class PyIAddrBook: + def ResolveName(self, uiParm, flags, entryTitle: str, ADRlist, /) -> None: ... + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + +class PyIApplicationDebugger: + def QueryAlive(self) -> None: ... + def CreateInstanceAtDebugger(self, rclsid: PyIID, pUnkOuter: PyIUnknown, dwClsContext, riid: PyIID, /) -> None: ... + def onDebugOutput(self, pstr, /) -> None: ... + def onHandleBreakPoint(self, prpt: PyIRemoteDebugApplicationThread, br, pError, /) -> None: ... + def onClose(self) -> None: ... + def onDebuggerEvent(self, guid: PyIID, uUnknown: PyIUnknown, /) -> None: ... + +class PyIApplicationDestinations: + def SetAppID(self, AppID, /) -> None: ... + def RemoveDestination(self, punk: PyIUnknown, /) -> None: ... + def RemoveAllDestinations(self) -> None: ... + +class PyIApplicationDocumentlists: + def SetAppID(self, AppID, /) -> None: ... + def Getlist(self, listType, riid: PyIID, ItemsDesired: int = ..., /) -> PyIEnumObjects: ... + +class PyIAsyncOperation: + def SetAsyncMode(self, fDoOpAsync, /) -> None: ... + def GetAsyncMode(self): ... + def StartOperation(self, pbcReserved: PyIBindCtx, /) -> None: ... + def InOperation(self) -> None: ... + def EndOperation(self, hResult, pbcReserved: PyIBindCtx, dwEffects, /) -> None: ... + +class PyIAttach: + def GetLastError(self, hr, flags, /): ... + +class PyIBindCtx: + def GetRunningObjectTable(self) -> PyIRunningObjectTable: ... + def GetBindOptions(self) -> PyBIND_OPTS: ... + def SetBindOptions(self, bindopts, /) -> None: ... + def RegisterObjectParam(self, Key: str, punk: PyIUnknown, /) -> None: ... + def RevokeObjectParam(self, Key: str, /) -> None: ... + def GetObjectParam(self, Key: str, /) -> PyIUnknown: ... + def EnumObjectParam(self) -> PyIEnumString: ... + +class PyIBrowserFrameOptions: + def GetFrameOptions(self, dwMask, /) -> None: ... + +class PyICancelMethodCalls: + def Cancel(self, Seconds, /) -> None: ... + def TestCancel(self): ... + +class PyICatInformation: + def EnumCategories(self, lcid: int = ..., /) -> PyIEnumCATEGORYINFO: ... + def GetCategoryDesc(self, lcid: int = ..., /) -> str: ... + def EnumClassesOfCategories( + self, listIIdImplemented: list[PyIID] | None = ..., listIIdRequired: Incomplete | None = ..., / + ) -> PyIEnumGUID: ... + +class PyICatRegister: + def RegisterCategories(self, arg: list[tuple[PyIID, Incomplete, str]], /) -> None: ... + def UnRegisterCategories(self, arg: list[PyIID], /) -> None: ... + def RegisterClassImplCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def UnRegisterClassImplCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def RegisterClassReqCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + def UnRegisterClassReqCategories(self, clsid: PyIID, arg: list[PyIID], /) -> None: ... + +class PyICategoryProvider: + def CanCategorizeOnSCID(self, pscid, /) -> None: ... + def GetDefaultCategory(self) -> None: ... + def GetCategoryForSCID(self, pscid, /) -> None: ... + def EnumCategories(self) -> None: ... + def GetCategoryName(self, guid: PyIID, /) -> None: ... + def CreateCategory(self, guid: PyIID, riid: PyIID, /) -> None: ... + +class PyIClassFactory: + def CreateInstance(self, outerUnknown: PyIUnknown, iid: PyIID, /) -> PyIUnknown: ... + def LockServer(self, bInc, /) -> None: ... + +class PyIClientSecurity: + def QueryBlanket(self, Proxy: PyIUnknown, /): ... + def SetBlanket( + self, Proxy: PyIUnknown, AuthnSvc, AuthzSvc, ServerPrincipalName: str, AuthnLevel, ImpLevel, AuthInfo, Capabilities, / + ) -> None: ... + def CopyProxy(self, Proxy: PyIUnknown, /) -> PyIUnknown: ... + +class PyIColumnProvider: + def Initialize(self, psci, /) -> None: ... + def GetColumnInfo(self, dwIndex, /) -> None: ... + def GetItemData(self, pscid, pscd, /) -> None: ... + +class PyIConnectionPoint: + def GetConnectionInterface(self) -> PyIID: ... + def GetConnectionPointContainer(self) -> PyIConnectionPointContainer: ... + def Advise(self, unk: PyIUnknown, /): ... + def Unadvise(self, cookie, /) -> None: ... + def EnumConnections(self) -> PyIEnumConnections: ... + +class PyIConnectionPointContainer: + def EnumConnectionPoints(self) -> PyIEnumConnectionPoints: ... + def FindConnectionPoint(self, iid: PyIID, /) -> PyIConnectionPoint: ... + +class PyIContext: + def SetProperty(self, rpolicyId: PyIID, flags, pUnk: PyIUnknown, /) -> None: ... + def RemoveProperty(self, rPolicyId: PyIID, /) -> None: ... + def GetProperty(self, rGuid: PyIID, /) -> tuple[Incomplete, PyIUnknown]: ... + def EnumContextProps(self) -> PyIEnumContextProps: ... + +class PyIContextMenu: + def QueryContextMenu(self, hmenu: int, indexMenu, idCmdFirst, idCmdLast, uFlags, /): ... + def InvokeCommand(self, pici: PyCMINVOKECOMMANDINFO, /) -> None: ... + def GetCommandString(self, idCmd, uType, cchMax: int = ..., /): ... + +class PyICopyHookA: + def CopyCallback(self, hwnd: int, wFunc, wFlags, srcFile: str, srcAttribs, destFile: str, destAttribs, /) -> None: ... + +class PyICopyHookW: + def CopyCallback(self, hwnd: int, wFunc, wFlags, srcFile: str, srcAttribs, destFile: str, destAttribs, /) -> None: ... + +class PyICreateTypeInfo: + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetTypeFlags(self, uTypeFlags, /) -> None: ... + def SetDocString(self, pStrDoc, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def AddRefTypeInfo(self, pTInfo: PyITypeInfo, /) -> None: ... + def AddFuncDesc(self, index, /) -> None: ... + def AddImplType(self, index, hRefType, /) -> None: ... + def SetImplTypeFlags(self, index, implTypeFlags, /) -> None: ... + def SetAlignment(self, cbAlignment, /) -> None: ... + def SetSchema(self, pStrSchema, /) -> None: ... + def AddVarDesc(self, index, /) -> None: ... + def SetFuncAndParamNames(self, index, rgszNames: tuple[Incomplete, ...], /) -> None: ... + def SetVarName(self, index, szName, /) -> None: ... + def SetTypeDescAlias(self) -> None: ... + def DefineFuncAsDllEntry(self, index, szDllName, szProcName, /) -> None: ... + def SetFuncDocString(self, index, szDocString, /) -> None: ... + def SetVarDocString(self, index, szDocString, /) -> None: ... + def SetFuncHelpContext(self, index, dwHelpContext, /) -> None: ... + def SetVarHelpContext(self, index, dwHelpContext, /) -> None: ... + def SetMops(self, index, bstrMops, /) -> None: ... + def LayOut(self) -> None: ... + +class PyICreateTypeLib: + def CreateTypeInfo(self, szName, /) -> None: ... + def SetName(self, szName, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetDocString(self, szDoc, /) -> None: ... + def SetHelpFileName(self, szHelpFileName, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetLcid(self) -> None: ... + def SetLibFlags(self, uLibFlags, /) -> None: ... + def SaveAllChanges(self) -> None: ... + +class PyICreateTypeLib2: + def CreateTypeInfo(self, szName, /) -> None: ... + def SetName(self, szName, /) -> None: ... + def SetVersion(self, wMajorVerNum, wMinorVerNum, /) -> None: ... + def SetGuid(self, guid: PyIID, /) -> None: ... + def SetDocString(self, szDoc, /) -> None: ... + def SetHelpFileName(self, szHelpFileName, /) -> None: ... + def SetHelpContext(self, dwHelpContext, /) -> None: ... + def SetLcid(self) -> None: ... + def SetLibFlags(self, uLibFlags, /) -> None: ... + def SaveAllChanges(self) -> None: ... + +class PyICurrentItem: ... + +class PyICustomDestinationlist: + def SetAppID(self, AppID, /) -> None: ... + def Beginlist(self, riid: PyIID, /) -> tuple[Incomplete, PyIObjectArray]: ... + def AppendCategory(self, Category, Items: PyIObjectArray, /) -> None: ... + def AppendKnownCategory(self, Category, /) -> None: ... + def AddUserTasks(self, Items: PyIObjectArray, /) -> None: ... + def Commitlist(self) -> None: ... + def GetRemovedDestinations(self, riid: PyIID, /) -> PyIObjectArray: ... + def Deletelist(self, AppID: Incomplete | None = ..., /) -> None: ... + def Abortlist(self) -> None: ... + +class PyIDL: ... + +class PyIDataObject: + def GetData(self, pformatetcIn: PyFORMATETC, /) -> PySTGMEDIUM: ... + def GetDataHere(self, pformatetcIn: PyFORMATETC, /) -> PySTGMEDIUM: ... + def QueryGetData(self, pformatetc: PyFORMATETC, /) -> None: ... + def GetCanonicalFormatEtc(self, pformatectIn: PyFORMATETC, /) -> PyFORMATETC: ... + def SetData(self, pformatetc: PyFORMATETC, pmedium: PySTGMEDIUM, fRelease, /) -> None: ... + def EnumFormatEtc(self, dwDirection, /) -> PyIEnumFORMATETC: ... + def DAdvise(self, pformatetc: PyFORMATETC, advf, pAdvSink, /): ... + def DUnadvise(self, dwConnection, /) -> None: ... + def EnumDAdvise(self): ... + +class PyIDebugApplication: + def SetName(self, pstrName, /) -> None: ... + def StepOutComplete(self) -> None: ... + def DebugOutput(self, pstr, /) -> None: ... + def StartDebugSession(self) -> None: ... + def HandleBreakPoint(self, br, /): ... + def Close(self) -> None: ... + def GetBreakFlags(self): ... + def GetCurrentThread(self) -> PyIDebugApplicationThread: ... + def CreateAsyncDebugOperation(self, psdo: PyIDebugSyncOperation, /) -> None: ... + def AddStackFrameSniffer(self, pdsfs: PyIDebugStackFrameSniffer, /): ... + def RemoveStackFrameSniffer(self, dwCookie, /) -> None: ... + def QueryCurrentThreadIsDebuggerThread(self) -> None: ... + def SynchronousCallInDebuggerThread(self, pptc, dwParam1, dwParam2, dwParam3, /) -> None: ... + def CreateApplicationNode(self) -> PyIDebugApplicationNode: ... + def FireDebuggerEvent(self, guid, unknown: PyIUnknown, /) -> None: ... + def HandleRuntimeError(self, pErrorDebug: PyIActiveScriptErrorDebug, pScriptSite: PyIActiveScriptSite, /) -> None: ... + def FCanJitDebug(self) -> None: ... + def FIsAutoJitDebugEnabled(self) -> None: ... + def AddGlobalExpressionContextProvider(self, pdsfs: PyIProvideExpressionContexts, /) -> None: ... + def RemoveGlobalExpressionContextProvider(self, dwCookie, /) -> None: ... + +class PyIDebugApplicationNode: + def EnumChildren(self) -> None: ... + def GetParent(self) -> PyIDebugApplicationNode: ... + def SetDocumentProvider(self, pddp: PyIDebugDocumentProvider, /) -> None: ... + def Close(self) -> None: ... + def Attach(self, pdanParent: PyIDebugApplicationNode, /) -> None: ... + def Detach(self) -> None: ... + +class PyIDebugApplicationNodeEvents: + def onAddChild(self, prddpChild: PyIDebugApplicationNode, /) -> None: ... + def onRemoveChild(self, prddpChild: PyIDebugApplicationNode, /) -> None: ... + def onDetach(self) -> None: ... + def onAttach(self, prddpParent: PyIDebugApplicationNode, /) -> None: ... + +class PyIDebugApplicationThread: + def SynchronousCallIntoThread(self, pstcb, dwParam1, dwParam2, dwParam3, /) -> None: ... + def QueryIsCurrentThread(self) -> None: ... + def QueryIsDebuggerThread(self) -> None: ... + +class PyIDebugCodeContext: + def GetDocumentContext(self) -> None: ... + def SetBreakPoint(self, bps, /) -> None: ... + +class PyIDebugDocument: ... + +class PyIDebugDocumentContext: + def GetDocument(self) -> None: ... + def EnumCodeContexts(self) -> None: ... + +class PyIDebugDocumentHelper: + def Init(self, pda: PyIDebugApplication, pszShortName, pszLongName, docAttr, /) -> None: ... + def Attach(self, pddhParent: PyIDebugDocumentHelper, /) -> None: ... + def Detach(self) -> None: ... + def AddUnicodeText(self, pszText, /) -> None: ... + def AddDBCSText(self) -> None: ... + def SetDebugDocumentHost(self, pddh: PyIDebugDocumentHost, /) -> None: ... + def AddDeferredText(self, cChars, dwTextStartCookie, /) -> None: ... + def DefineScriptBlock(self, ulCharOffset, cChars, pas, fScriptlet, /) -> None: ... + def SetDefaultTextAttr(self, staTextAttr, /) -> None: ... + def SetTextAttributes(self, ulCharOffset, obAttr, /) -> None: ... + def SetLongName(self, pszLongName, /) -> None: ... + def SetShortName(self, pszShortName, /) -> None: ... + def SetDocumentAttr(self, pszAttributes, /) -> None: ... + def GetDebugApplicationNode(self) -> None: ... + def GetScriptBlockInfo(self, dwSourceContext, /) -> None: ... + def CreateDebugDocumentContext(self, iCharPos, cChars, /) -> None: ... + def BringDocumentToTop(self) -> None: ... + def BringDocumentContextToTop(self, pddc: PyIDebugDocumentContext, /) -> None: ... + +class PyIDebugDocumentHost: + def GetDeferredText(self, dwTextStartCookie, cMaxChars, /) -> None: ... + def GetScriptTextAttributes(self, pstrCode, pstrDelimiter, dwFlags, /) -> None: ... + def OnCreateDocumentContext(self) -> None: ... + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class PyIDebugDocumentInfo: + def GetName(self) -> None: ... + def GetDocumentClassId(self) -> PyIID: ... + +class PyIDebugDocumentProvider: + def GetDocument(self) -> PyIDebugDocument: ... + +class PyIDebugDocumentText: + def GetDocumentAttributes(self) -> None: ... + def GetSize(self) -> None: ... + def GetPositionOfLine(self, cLineNumber, /) -> None: ... + def GetLineOfPosition(self, cCharacterPosition, /) -> None: ... + def GetText(self, cCharacterPosition, cMaxChars, bWantAttr: int = ..., /) -> None: ... + def GetPositionOfContext(self, psc: PyIDebugDocumentContext, /) -> None: ... + def GetContextOfPosition(self, cCharacterPosition, cNumChars, /) -> None: ... + +class PyIDebugDocumentTextAuthor: + def InsertText(self, cCharacterPosition, cNumToInsert, pcharText, /) -> None: ... + def RemoveText(self, cCharacterPosition, cNumToRemove, /) -> None: ... + def ReplaceText(self, cCharacterPosition, cNumToReplace, pcharText, /) -> None: ... + +class PyIDebugDocumentTextEvents: + def onDestroy(self) -> None: ... + def onInsertText(self, cCharacterPosition, cNumToInsert, /) -> None: ... + def onRemoveText(self, cCharacterPosition, cNumToRemove, /) -> None: ... + def onReplaceText(self, cCharacterPosition, cNumToReplace, /) -> None: ... + def onUpdateTextAttributes(self, cCharacterPosition, cNumToUpdate, /) -> None: ... + def onUpdateDocumentAttributes(self, textdocattr, /) -> None: ... + +class PyIDebugDocumentTextExternalAuthor: + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class PyIDebugExpression: + def Start(self, pdecb: PyIDebugExpressionCallBack, /) -> None: ... + def Abort(self) -> None: ... + def QueryIsComplete(self) -> None: ... + def GetResultAsString(self) -> None: ... + def GetResultAsDebugProperties(self) -> None: ... + +class PyIDebugExpressionCallBack: + def onComplete(self) -> None: ... + +class PyIDebugExpressionContext: + def ParseLanguageText(self, pstrCode, nRadix, pstrDelimiter, dwFlags, /) -> None: ... + def GetLanguageInfo(self) -> None: ... + +class PyIDebugProperty: + def GetPropertyInfo(self, dwFieldSpec, nRadix, /) -> None: ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, pszValue, nRadix, /) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, refiid: PyIID, /) -> None: ... + def GetParent(self) -> None: ... + +class PyIDebugSessionProvider: + def StartDebugSession(self, pda: PyIRemoteDebugApplication, /) -> None: ... + +class PyIDebugStackFrame: + def GetCodeContext(self) -> None: ... + def GetDescriptionString(self, fLong, /): ... + def GetLanguageString(self, fLong, /): ... + def GetThread(self) -> PyIDebugApplicationThread: ... + +class PyIDebugStackFrameSniffer: + def EnumStackFrames(self) -> None: ... + +class PyIDebugStackFrameSnifferEx: + def EnumStackFramesEx(self) -> None: ... + +class PyIDebugSyncOperation: + def GetTargetThread(self) -> None: ... + def Execute(self) -> None: ... + def InProgressAbort(self) -> None: ... + +class PyIDefaultExtractIconInit: + def SetFlags(self, uFlags, /) -> None: ... + def SetKey(self, hkey: PyHKEY, /) -> None: ... + def SetNormalIcon(self, pszFile, iIcon, /) -> None: ... + def SetOpenIcon(self, pszFile, iIcon, /) -> None: ... + def SetShortcutIcon(self, pszFile, iIcon, /) -> None: ... + def SetDefaultIcon(self, pszFile, iIcon, /) -> None: ... + +class PyIDirectSound: + def Initialize(self, guid: PyIID, /) -> None: ... + def SetCooperativeLevel(self, hwnd: int, level, /) -> None: ... + def CreateSoundBuffer(self, lpDSCBufferDesc: PyDSCBUFFERDESC, unk: Incomplete | None = ..., /) -> None: ... + def GetCaps(self) -> None: ... + def Compact(self) -> None: ... + +class PyIDirectSoundBuffer: + def Initialize(self) -> None: ... + def GetStatus(self) -> None: ... + def GetCaps(self) -> None: ... + def Restore(self) -> None: ... + def GetCurrentPosition(self) -> None: ... + def Play(self) -> None: ... + def SetCurrentPosition(self) -> None: ... + def Stop(self) -> None: ... + def GetFrequency(self) -> None: ... + def GetPan(self) -> None: ... + def GetVolume(self) -> None: ... + def SetFrequency(self) -> None: ... + def SetPan(self) -> None: ... + def SetVolume(self) -> None: ... + +class PyIDirectSoundCapture: + def Initialize(self) -> None: ... + def GetCaps(self) -> None: ... + +class PyIDirectSoundCaptureBuffer: + def Initialize(self) -> None: ... + def GetStatus(self) -> None: ... + def GetCurrentPosition(self) -> None: ... + def Stop(self) -> None: ... + +class PyIDirectSoundNotify: ... + +class PyIDirectoryObject: + def GetObjectInformation(self) -> PyADS_OBJECT_INFO: ... + def GetObjectAttributes(self, names: tuple[str, ...], /) -> tuple[PyADS_ATTR_INFO, ...]: ... + def SetObjectAttributes(self, attrs: tuple[PyADS_ATTR_INFO, ...], /): ... + def CreateDSObject(self, rdn: str, attrs: tuple[PyADS_ATTR_INFO, ...], /) -> PyIDispatch: ... + def DeleteDSObject(self, rdn: str, /) -> None: ... + +class PyIDirectorySearch: + def SetSearchPreference(self, prefs, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def ExecuteSearch(self, _filter: str, attrNames: list[str], /): ... + def GetNextRow(self, handle, /): ... + def GetFirstRow(self, handle, /): ... + def GetPreviousRow(self, handle, /): ... + def CloseSearchHandle(self, handle, /) -> None: ... + def AdandonSearch(self, handle, /) -> None: ... + def GetColumn(self, handle, name: str, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetNextColumnName(self) -> None: ... + +@final +class PyIDispatch: + def Invoke(self, dispid, lcid, flags, bResultWanted, arg: tuple[Incomplete, ...], /): ... + def InvokeTypes( + self, dispid, lcid, wFlags, resultTypeDesc, typeDescs: tuple[Incomplete, ...], args: tuple[Incomplete, ...], / + ): ... + def GetIDsOfNames(self, name: str, arg, /) -> tuple[Incomplete, Incomplete]: ... + def GetTypeInfo(self, locale, index: int = ..., /) -> PyITypeInfo: ... + def GetTypeInfoCount(self): ... + +class PyIDispatchEx: + def GetDispID(self, name: str, fdex, /): ... + def InvokeEx( + self, + dispid, + lcid, + flags, + args: list[Incomplete], + types: list[Incomplete] | None = ..., + returnDesc: int = ..., + serviceProvider: PyIServiceProvider | None = ..., + /, + ): ... + def DeleteMemberByName(self, name: str, fdex, /) -> None: ... + def DeleteMemberByDispID(self, dispid, /) -> None: ... + def GetMemberProperties(self, dispid, fdex, /): ... + def GetMemberName(self, dispid, /): ... + def GetNextDispID(self, fdex, dispid, /): ... + +class PyIDisplayItem: ... + +class PyIDocHostUIHandler: + def ShowContextMenu( + self, dwID, pt: tuple[Incomplete, Incomplete], pcmdtReserved: PyIUnknown, pdispReserved: PyIDispatch, / + ) -> None: ... + def GetHostInfo(self) -> None: ... + def ShowUI( + self, + dwID, + pActiveObject: PyIOleInPlaceActiveObject, + pCommandTarget: PyIOleCommandTarget, + pFrame: PyIOleInPlaceFrame, + pDoc: PyIOleInPlaceUIWindow, + /, + ) -> None: ... + def HideUI(self) -> None: ... + def UpdateUI(self) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + def OnDocWindowActivate(self, fActivate, /) -> None: ... + def OnFrameWindowActivate(self, fActivate, /) -> None: ... + def ResizeBorder( + self, prcBorder: tuple[Incomplete, Incomplete, Incomplete, Incomplete], pUIWindow: PyIOleInPlaceUIWindow, fRameWindow, / + ) -> None: ... + def TranslateAccelerator(self, lpMsg, pguidCmdGroup: PyIID, nCmdID, /) -> None: ... + def GetOptionKeyPath(self, dw, /) -> None: ... + def GetDropTarget(self, pDropTarget: PyIDropTarget, /) -> None: ... + def GetExternal(self) -> None: ... + def TranslateUrl(self, dwTranslate, pchURLIn, /) -> None: ... + def FilterDataObject(self, pDO: PyIDataObject, /) -> None: ... + +class PyIDropSource: + def QueryContinueDrag(self, fEscapePressed, grfKeyState, /) -> None: ... + def GiveFeedback(self, dwEffect, /) -> None: ... + +class PyIDropTarget: + def DragEnter(self, pDataObj: PyIDataObject, grfKeyState, pt: tuple[Incomplete, Incomplete], pdwEffect, /): ... + def DragOver(self, grfKeyState, pt: tuple[Incomplete, Incomplete], pdwEffect, /): ... + def DragLeave(self) -> None: ... + def Drop(self, pDataObj: PyIDataObject, grfKeyState, pt: tuple[Incomplete, Incomplete], dwEffect, /): ... + +class PyIDropTargetHelper: + def DragEnter(self, hwnd: int, pDataObj: PyIDataObject, pt: tuple[Incomplete, Incomplete], dwEffect, /) -> None: ... + def DragOver(self, hwnd: int, pt: tuple[Incomplete, Incomplete], pdwEffect, /) -> None: ... + def DragLeave(self) -> None: ... + def Drop(self, pDataObj: PyIDataObject, pt: tuple[Incomplete, Incomplete], dwEffect, /) -> None: ... + +class PyIDsObjectPicker: + def Initialize( + self, targetComputer: str, scopeInfos: PyDSOP_SCOPE_INIT_INFOs, options: int = ..., attrNames: list[str] | None = ..., / + ) -> None: ... + def InvokeDialog(self, hwnd: int, /) -> PyIDataObject: ... + +class PyIEmptyVolumeCache: ... +class PyIEmptyVolumeCache2: ... + +class PyIEmptyVolumeCacheCallBack: + def ScanProgress(self, dwlSpaceUsed, dwFlags, pcwszStatus, /) -> None: ... + def PurgeProgress(self, dwlSpaceFreed, spaceFreed, spaceToFree, flags, status, /) -> None: ... + +class PyIEnumCATEGORYINFO: + def Next(self, num: int = ..., /) -> tuple[tuple[PyIID, Incomplete, str], ...]: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumCATEGORYINFO: ... + +class PyIEnumConnectionPoints: + def Next(self, num: int = ..., /) -> tuple[PyIConnectionPoint, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumConnectionPoints: ... + +class PyIEnumConnections: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumConnections: ... + +class PyIEnumContextProps: + def Next(self, num: int = ..., /) -> tuple[tuple[PyIID, Incomplete, PyIUnknown], ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumContextProps: ... + +class PyIEnumDebugApplicationNodes: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugApplicationNodes: ... + +class PyIEnumDebugCodeContexts: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugCodeContexts: ... + +class PyIEnumDebugExpressionContexts: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugExpressionContexts: ... + +class PyIEnumDebugPropertyInfo: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugPropertyInfo: ... + def GetCount(self): ... + +class PyIEnumDebugStackFrames: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumDebugStackFrames: ... + +class PyIEnumExplorerCommand: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumExplorerCommand: ... + +class PyIEnumFORMATETC: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumFORMATETC: ... + +class PyIEnumGUID: + def Next(self, num: int = ..., /) -> tuple[PyIID, ...]: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumGUID: ... + +class PyIEnumIDlist: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumIDlist: ... + +class PyIEnumMoniker: + def Next(self, num: int = ..., /) -> PyIMoniker: ... + def Skip(self, num, /) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumMoniker: ... + +class PyIEnumObjects: + def Next(self, riid: PyIID, num: int = ..., /) -> tuple[PyIUnknown, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumObjects: ... + +class PyIEnumRemoteDebugApplicationThreads: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumRemoteDebugApplicationThreads: ... + +class PyIEnumRemoteDebugApplications: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumRemoteDebugApplications: ... + +class PyIEnumResources: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumResources: ... + +class PyIEnumSTATPROPSETSTG: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATPROPSETSTG: ... + +class PyIEnumSTATPROPSTG: + def Next(self, num: int = ..., /): ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATPROPSTG: ... + +class PyIEnumSTATSTG: + def Next(self, num: int = ..., /) -> tuple[STATSTG, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumSTATSTG: ... + +class PyIEnumShellItems: + def Next(self, num: int = ..., /) -> tuple[PyIShellItem, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumShellItems: ... + +class PyIEnumString: + def Next(self, num: int = ..., /) -> tuple[str, ...]: ... + def Skip(self) -> None: ... + def Reset(self) -> None: ... + def Clone(self) -> PyIEnumString: ... + +class PyIErrorLog: + def AddError(self, propName: str, excepInfo: Incomplete | None = ..., /) -> None: ... + +class PyIExplorerBrowser: + def Initialize(self, hwndParent, prc: PyRECT, pfs, /) -> None: ... + def Destroy(self) -> None: ... + def SetRect(self, hdwp, rcBrowser: PyRECT, /) -> int: ... + def SetPropertyBag(self, PropertyBag, /) -> None: ... + def SetEmptyText(self, EmptyText, /) -> None: ... + def SetFolderSettings(self, pfs, /) -> None: ... + def Advise(self, psbe: PyIExplorerBrowserEvents, /): ... + def Unadvise(self, dwCookie, /) -> None: ... + def SetOptions(self, dwFlag, /) -> None: ... + def GetOptions(self): ... + def BrowseToIDlist(self, pidl, uFlags, /) -> None: ... + def BrowseToObject(self, punk: PyIUnknown, uFlags, /) -> None: ... + def FillFromObject(self, punk: PyIUnknown, dwFlags, /) -> None: ... + def RemoveAll(self) -> None: ... + def GetCurrentView(self, riid: PyIID, /) -> PyIUnknown: ... + +class PyIExplorerBrowserEvents: + def OnNavigationPending(self, pidlFolder, /) -> None: ... + def OnViewCreated(self, psv: PyIShellView, /) -> None: ... + def OnNavigationComplete(self, pidlFolder, /) -> None: ... + def OnNavigationFailed(self, pidlFolder, /) -> None: ... + +class PyIExplorerCommand: + def GetTitle(self, psiItemArray: PyIShellItemArray, /): ... + def GetIcon(self, psiItemArray: PyIShellItemArray, /): ... + def GetToolTip(self, psiItemArray: PyIShellItemArray, /): ... + def GetCanonicalName(self) -> PyIID: ... + def GetState(self, psiItemArray: PyIShellItemArray, fOkToBeSlow, /): ... + def Invoke(self, psiItemArray: PyIShellItemArray, pbc: PyIBindCtx, /) -> None: ... + def GetFlags(self): ... + def EnumSubCommands(self) -> PyIEnumExplorerCommand: ... + +class PyIExplorerCommandProvider: ... +class PyIExplorerPaneVisibility: ... + +class PyIExternalConnection: + def AddConnection(self, extconn, reserved: int = ..., /): ... + def ReleaseConnection(self, extconn, reserved, fLastReleaseCloses, /): ... + +class PyIExtractIcon: + def Extract(self, pszFile, nIconIndex, nIconSize, /) -> None: ... + def GetIconLocation(self, uFlags, cchMax, /) -> None: ... + +class PyIExtractIconW: + def Extract(self, pszFile, nIconIndex, nIconSize, /) -> None: ... + def GetIconLocation(self, uFlags, cchMax, /) -> None: ... + +class PyIExtractImage: + def GetLocation(self, dwPriority, size: tuple[Incomplete, Incomplete], dwRecClrDepth, pdwFlags, /) -> None: ... + def Extract(self) -> None: ... + +class PyIFileOperation: + def Advise(self, Sink: PyGFileOperationProgressSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def SetOperationFlags(self, OperationFlags, /) -> None: ... + def SetProgressMessage(self, Message, /) -> None: ... + def SetProgressDialog(self, popd, /) -> None: ... + def SetProperties(self, proparray: PyIPropertyChangeArray, /) -> None: ... + def SetOwnerWindow(self, Owner: int, /) -> None: ... + def ApplyPropertiesToItem(self, Item: PyIShellItem, /) -> None: ... + def ApplyPropertiesToItems(self, Items: PyIUnknown, /) -> None: ... + def RenameItem(self, Item: PyIShellItem, NewName, Sink: PyGFileOperationProgressSink | None = ..., /) -> None: ... + def RenameItems(self, pUnkItems: PyIUnknown, NewName, /) -> None: ... + def MoveItem( + self, + Item: PyIShellItem, + DestinationFolder: PyIShellItem, + pszNewName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def MoveItems(self, Items: PyIUnknown, DestinationFolder: PyIShellItem, /) -> None: ... + def CopyItem( + self, + Item: PyIShellItem, + DestinationFolder: PyIShellItem, + CopyName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def CopyItems(self, Items: PyIUnknown, DestinationFolder: PyIShellItem, /) -> None: ... + def DeleteItem(self, Item: PyIShellItem, Sink: PyGFileOperationProgressSink | None = ..., /) -> None: ... + def DeleteItems(self, Items: PyIUnknown, /) -> None: ... + def NewItem( + self, + DestinationFolder: PyIShellItem, + FileAttributes, + Name, + TemplateName: Incomplete | None = ..., + Sink: PyGFileOperationProgressSink | None = ..., + /, + ) -> None: ... + def PerformOperations(self) -> None: ... + def GetAnyOperationsAborted(self): ... + +class PyIFolderView: + def GetCurrentViewMode(self): ... + def SetCurrentViewMode(self, ViewMode: int, /): ... + def GetFolder(self, riid: PyIID | None, /): ... + def Item(self, iItemIndex: int, /): ... + def ItemCount(self, uFlags: int, /): ... + def Items(self) -> Never: ... # Not Implemented + def GetSelectionMarkedItem(self): ... + def GetFocusedItem(self): ... + def GetItemPosition(self, pidl: PyIDL | None, /): ... + def GetSpacing(self, pt_x: int, pt_y: int, /): ... + def GetDefaultSpacing(self): ... + def GetAutoArrange(self): ... + def SelectItem(self, iItem: int, dwFlags: int, /): ... + def SelectAndPositionItems(self) -> Never: ... # Not Implemented + def SelectAndPositionItem(self, apidl: PyIDL | None, pt: tuple[int, int], dwFlags: int, /): ... + +class PyIIdentityName: ... + +class PyIInitializeWithFile: + def Initialize(self, FilePath, Mode, /) -> None: ... + +class PyIInitializeWithStream: + def Initialize(self, Stream: PyIStream, Mode, /) -> None: ... + +class PyIInputObject: + def TranslateAccelerator(self, pmsg, /) -> None: ... + def UIActivate(self, uState, /) -> None: ... + def HasFocusIO(self) -> None: ... + +class PyIInternetBindInfo: + def GetBindInfo(self) -> None: ... + def GetBindString(self) -> None: ... + +class PyIInternetPriority: + def SetPriority(self, nPriority, /) -> None: ... + def GetPriority(self) -> None: ... + +class PyIInternetProtocol: + def Read(self, cb, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def Seek(self, dlibMove: tuple[int, int], dwOrigin, /) -> None: ... + @overload + def Seek(self, dlibMove: int, dwOrigin, /) -> None: ... + + def LockRequest(self, dwOptions, /) -> None: ... + def UnlockRequest(self) -> None: ... + +class PyIInternetProtocolInfo: + def ParseUrl(self, pwzUrl, ParseAction, dwParseFlags, cchResult, dwReserved, /) -> None: ... + def CombineUrl(self, pwzBaseUrl, pwzRelativeUrl, dwCombineFlags, cchResult, dwReserved, /) -> None: ... + def CompareUrl(self, pwzUrl1, pwzUrl2, dwCompareFlags, /) -> None: ... + def QueryInfo(self, pwzUrl, OueryOption, dwQueryFlags, cbBuffer, dwReserved, /): ... + +class PyIInternetProtocolRoot: + def Start( + self, szUrl, pOIProtSink: PyIInternetProtocolSink, pOIBindInfo: PyIInternetBindInfo, grfPI, dwReserved, / + ) -> None: ... + def Continue(self) -> None: ... + def Abort(self, hrReason, dwOptions, /) -> None: ... + def Terminate(self, dwOptions, /) -> None: ... + def Suspend(self) -> None: ... + def Resume(self) -> None: ... + +class PyIInternetProtocolSink: + def Switch(self) -> None: ... + def ReportProgress(self, ulStatusCode, szStatusText, /) -> None: ... + def ReportData(self, grfBSCF, ulProgress, ulProgressMax, /) -> None: ... + def ReportResult(self, hrResult, dwError, szResult, /) -> None: ... + +class PyIInternetSecurityManager: + def SetSecuritySite(self, pSite, /) -> None: ... + def GetSecuritySite(self) -> None: ... + def MapUrlToZone(self, pwszUrl, dwFlags, /) -> None: ... + def GetSecurityId(self, pwszUrl, pcbSecurityId, /) -> None: ... + def ProcessUrlAction(self, pwszUrl, dwAction, context, dwFlags, /) -> None: ... + def SetZoneMapping(self, dwZone, lpszPattern, dwFlags, /) -> None: ... + def GetZoneMappings(self, dwZone, dwFlags, /) -> None: ... + +class PyIKnownFolder: + def GetId(self) -> PyIID: ... + def GetCategory(self): ... + def GetShellItem(self, riid: PyIID, Flags: int = ..., /) -> PyIShellItem: ... + def GetPath(self, Flags: int = ..., /): ... + def SetPath(self, Flags, Path, /) -> None: ... + def GetIDlist(self, Flags, /) -> PyIDL: ... + def GetFolderType(self) -> PyIID: ... + def GetRedirectionCapabilities(self): ... + def GetFolderDefinition(self): ... + +class PyIKnownFolderManager: + def FolderIdFromCsidl(self, Csidl, /) -> PyIID: ... + def FolderIdToCsidl(self, _id: PyIID, /): ... + def GetFolderIds(self) -> tuple[PyIID, ...]: ... + def GetFolder(self, _id: PyIID, /) -> PyIKnownFolder: ... + def GetFolderByName(self, Name, /) -> PyIKnownFolder: ... + def RegisterFolder(self, _id: PyIID, Definition, /) -> None: ... + def UnregisterFolder(self, _id: PyIID, /) -> None: ... + def FindFolderFromPath(self, Path, Mode, /) -> PyIKnownFolder: ... + def FindFolderFromIDlist(self, pidl: PyIDL, /) -> PyIKnownFolder: ... + def Redirect(self, _id: PyIID, hwnd: int, flags, TargetPath, Exclusion: tuple[PyIID, ...], /) -> None: ... + +class PyILockBytes: + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def ReadAt(self, ulOffset: tuple[int, int], cb, /) -> str: ... + @overload + def ReadAt(self, ulOffset: int, cb, /) -> str: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def WriteAt(self, ulOffset: tuple[int, int], data: str, /): ... + @overload + def WriteAt(self, ulOffset: int, data: str, /): ... + + def Flush(self) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def SetSize(self, cb: tuple[int, int], /) -> None: ... + @overload + def SetSize(self, cb: int, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def LockRegion(self, libOffset: tuple[int, int], cb: tuple[int, int], dwLockType, /) -> None: ... + @overload + def LockRegion(self, libOffset: int, cb: int, dwLockType, /) -> None: ... + + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def UnlockRegion(self, libOffset: tuple[int, int], cb: tuple[int, int], dwLockType, /) -> None: ... + @overload + def UnlockRegion(self, libOffset: int, cb: int, dwLockType, /) -> None: ... + +class PyIMAPIContainer: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def GetContentsTable(self, flags, /) -> PyIMAPITable: ... + def GetHierarchyTable(self, flags, /) -> PyIMAPITable: ... + +class PyIMAPIFolder: + def GetLastError(self, hr, flags, /): ... + def CreateFolder( + self, folderType, folderName: str, folderComment: str | None = ..., iid: PyIID | None = ..., flags=..., / + ) -> PyIMAPIFolder: ... + def CreateMessage(self, iid: PyIID, flags, /) -> PyIMessage: ... + def CopyMessages(self, msgs: PySBinaryArray, iid: PyIID, folder: PyIMAPIFolder, ulUIParam, progress, flags, /): ... + def DeleteFolder(self, entryId: str, uiParam, progress, /) -> None: ... + def DeleteMessages(self, msgs: PySBinaryArray, uiParam, progress, flags, /): ... + def EmptyFolder(self, uiParam, progress, flags, /): ... + def SetReadFlags(self, msgs: PySBinaryArray, uiParam, progress, flag, /) -> None: ... + +class PyIMAPIProp: + def GetProps(self, proplist: PySPropTagArray, flags: int = ..., /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def DeleteProps( + self, proplist: PySPropTagArray, wantProblems: bool = ..., / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def SetProps( + self, proplist: tuple[Incomplete, Incomplete], wantProblems: bool = ..., / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def CopyTo( + self, + IIDExcludelist: tuple[Incomplete, Incomplete], + propTags: PySPropTagArray, + uiParam, + progress, + resultIID: PyIID, + dest: PyIMAPIProp, + flags, + wantProblems: bool = ..., + /, + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def CopyProps( + self, + propTags: PySPropTagArray, + uiParam, + progress, + resultIID: PyIID, + dest: PyIMAPIProp, + flags, + wantProblems: bool = ..., + /, + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def OpenProperty(self, propTag, iid: PyIID, interfaceOptions, flags, /) -> PyIUnknown: ... + def GetIDsFromNames(self, nameIds: PyMAPINAMEIDArray, flags: int = ..., /) -> PySPropTagArray: ... + def GetNamesFromIDs( + self, propTags: PySPropTagArray, propSetGuid: PyIID | None = ..., flags=..., / + ) -> tuple[Incomplete, PySPropTagArray, PyMAPINAMEIDArray]: ... + def GetLastError(self, hr, flags, /): ... + def SaveChanges(self, flags, /) -> None: ... + def GetProplist(self, flags, /) -> PySPropTagArray: ... + +class PyIMAPISession: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def OpenMsgStore(self, uiParam, entryId: str, iid: PyIID, flags, /) -> PyIUnknown: ... + def QueryIdentity(self) -> str: ... + def Advise(self, entryId: str, mask, sink, /): ... + def Unadvise(self, connection, /) -> None: ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + def GetLastError(self, hr, flags, /): ... + def GetMsgStoresTable(self, flags, /) -> PyIMAPITable: ... + def GetStatusTable(self, flags, /) -> PyIMAPITable: ... + def Logoff(self, uiParm, flags, reserved, /) -> None: ... + def OpenAddressBook(self, uiParm, iid: PyIID, flags, /) -> PyIAddrBook: ... + def OpenProfileSection(self, iidSection: PyIID, iid: PyIID, flags, /): ... + def AdminServices(self, flags: int = ..., /) -> PyIMsgServiceAdmin: ... + +class PyIMAPIStatus: + def ChangePassword(self, oldPassword, newPassword, ulFlags, /) -> None: ... + def SettingsDialog(self, ulUIParam, ulFlags, /) -> None: ... + def ValidateState(self, ulUIParam, ulFlags, /) -> None: ... + def FlushQueues(self, ulUIParam, transport: str, ulFlags, /) -> None: ... + +class PyIMAPITable: + def GetLastError(self, hr, flags, /): ... + def Advise(self, eventMask, adviseSink, /): ... + def SeekRow(self, bookmark, rowCount, /): ... + def SeekRowApprox(self, numerator, denominator, /) -> None: ... + def GetRowCount(self, flags, /): ... + def QueryRows(self, rowCount, flags, /): ... + def SetColumns(self, propTags, flags, /) -> None: ... + def GetStatus(self) -> None: ... + def QueryPosition(self) -> None: ... + def QueryColumns(self, flags, /): ... + def Abort(self) -> None: ... + def FreeBookmark(self, bookmark, /) -> None: ... + def CreateBookmark(self): ... + def Restrict(self, restriction: PySRestriction, flags, /) -> None: ... + def FindRow(self, restriction: PySRestriction, bookmarkOrigin, flags, /) -> None: ... + def SortTable(self, sortOrderSet: PySSortOrderSet, flags, /) -> None: ... + def Unadvise(self, handle, /) -> None: ... + +class PyIMachineDebugManager: + def AddApplication(self, pda: PyIRemoteDebugApplication, /) -> None: ... + def RemoveApplication(self, dwAppCookie, /) -> None: ... + def EnumApplications(self) -> None: ... + +class PyIMachineDebugManagerEvents: + def onAddApplication(self, pda: PyIRemoteDebugApplication, dwAppCookie, /) -> None: ... + def onRemoveApplication(self, pda: PyIRemoteDebugApplication, dwAppCookie, /) -> None: ... + +class PyIMessage: + def SetReadFlag(self, flag, /) -> None: ... + def GetAttachmentTable(self, flags, /) -> PyIMAPITable: ... + def OpenAttach(self, attachmentNum, interface: PyIID, flags, /) -> PyIAttach: ... + def CreateAttach(self, interface: PyIID, flags, /) -> tuple[Incomplete, PyIAttach]: ... + def DeleteAttach(self, attachmentNum, ulUIParam, interface, flags, /) -> None: ... + def ModifyRecipients(self, flags, mods, /) -> None: ... + def GetRecipientTable(self, flags, /) -> PyIMAPITable: ... + def SubmitMessage(self, flags, /) -> None: ... + +class PyIMoniker: + def BindToObject(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, iidResult, /) -> PyIUnknown: ... + def BindToStorage(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, iidResult, /) -> PyIUnknown: ... + def GetDisplayName(self, bindCtx: PyIBindCtx, moniker: PyIMoniker, /) -> str: ... + def ComposeWith(self, mkRight: PyIMoniker, fOnlyIfNotGeneric, /) -> PyIMoniker: ... + def Enum(self, fForward: bool = ..., /) -> PyIEnumMoniker: ... + def IsEqual(self, other: PyIMoniker, /) -> bool: ... + def IsSystemMoniker(self) -> bool: ... + def Hash(self): ... + +class PyIMsgServiceAdmin: + def GetLastError(self, hr, flags, /): ... + def CreateMsgService(self, serviceName: str, displayName: str, flags, uiParam: int = ..., /) -> None: ... + def ConfigureMsgService(self, iid: PyIID, ulUIParam, ulFlags, arg: list[Incomplete], /) -> None: ... + def GetMsgServiceTable(self, flags, /) -> PyIMAPITable: ... + def GetProviderTable(self, flags, /) -> PyIMAPITable: ... + def DeleteMsgService(self, uuid: PyIID, /) -> None: ... + @deprecated("This is deprecated, and there is no replacement referenced to use instead.") + def RenameMsgService(self, uuid: PyIID, flags, newName: str, /) -> None: ... + def OpenProfileSection(self, uuid: PyIID, iid: PyIID, flags, /): ... + def AdminProviders(self, uuid: PyIID, flags, /): ... + +class PyIMsgStore: + def OpenEntry(self, entryId: str, iid: PyIID, flags, /): ... + def StoreLogoff(self, flags: int, /): ... + def GetReceiveFolder(self, messageClass: str | None = ..., flags: int = ..., /) -> tuple[PyIID, str]: ... + def GetReceiveFolderTable(self, flags, /) -> PyIMAPITable: ... + def CompareEntryIDs(self, entryId: str, entryId1: str, flags: int = ..., /): ... + def GetLastError(self, hr, flags, /): ... + def AbortSubmit(self, entryId: str, flags: int = ..., /): ... + def Advise(self, entryId: str, eventMask, adviseSink, /) -> None: ... + def Unadvise(self, connection, /) -> None: ... + +class PyINameSpaceTreeControl: + def Initialize(self, hwndParent, prc: tuple[Incomplete, Incomplete, Incomplete, Incomplete], nsctsFlags, /) -> None: ... + def TreeAdvise(self, punk: PyIUnknown, /) -> None: ... + def TreeUnadvise(self, dwCookie, /) -> None: ... + def AppendRoot(self, psiRoot: PyIShellItem, grfEnumFlags, grfRootStyle, pif, /) -> None: ... + def InsertRoot(self, iIndex, psiRoot: PyIShellItem, grfEnumFlags, grfRootStyle, pif, /) -> None: ... + def RemoveRoot(self, psiRoot: PyIShellItem, /) -> None: ... + def RemoveAllRoots(self) -> None: ... + def GetRootItems(self) -> None: ... + def SetItemState(self, psi: PyIShellItem, nstcisMask, nstcisFlags, /) -> None: ... + def GetItemState(self, psi: PyIShellItem, nstcisMask, /) -> None: ... + def GetSelectedItems(self) -> None: ... + def GetItemCustomState(self, psi: PyIShellItem, /) -> None: ... + def SetItemCustomState(self, psi: PyIShellItem, iStateNumber, /) -> None: ... + def EnsureItemVisible(self, psi: PyIShellItem, /) -> None: ... + def SetTheme(self, pszTheme, /) -> None: ... + def GetNextItem(self, psi: PyIShellItem, nstcgi, /) -> None: ... + def HitTest(self, pt: tuple[Incomplete, Incomplete], /) -> None: ... + def GetItemRect(self) -> None: ... + def CollapseAll(self) -> None: ... + +class PyINamedPropertyStore: + def GetNamedValue(self, Name, /) -> PyPROPVARIANT: ... + def SetNamedValue(self, propvar, /) -> None: ... + def GetNameCount(self): ... + def GetNameAt(self, Index, /): ... + +class PyIObjectArray: + def GetCount(self): ... + def GetAt(self, Index, riid: PyIID, /) -> PyIUnknown: ... + +class PyIObjectCollection: + def AddObject(self, punk: PyIUnknown, /) -> None: ... + def AddFromArray(self, Source: PyIObjectArray, /) -> None: ... + def RemoveObjectAt(self, Index, /) -> None: ... + def Clear(self) -> None: ... + +class PyIObjectWithPropertyKey: + def SetPropertyKey(self, key: PyPROPERTYKEY, /) -> None: ... + def GetPropertyKey(self) -> PyPROPERTYKEY: ... + +class PyIObjectWithSite: + def SetSite(self, pUnkSite, /) -> None: ... + def GetSite(self, riid: PyIID, /) -> None: ... + +class PyIOleClientSite: + def SaveObject(self) -> None: ... + def GetMoniker(self, dwAssign, dwWhichMoniker, /) -> None: ... + def GetContainer(self) -> None: ... + def ShowObject(self) -> None: ... + def OnShowWindow(self, fShow, /) -> None: ... + def RequestNewObjectLayout(self) -> None: ... + +class PyIOleCommandTarget: + def QueryStatus(self) -> None: ... + def Exec(self) -> None: ... + +class PyIOleControl: + def GetControlInfo(self) -> None: ... + def OnMnemonic(self, msg, /) -> None: ... + def OnAmbientPropertyChange(self, dispID, /) -> None: ... + def FreezeEvents(self, bFreeze, /) -> None: ... + +class PyIOleControlSite: + def OnControlInfoChanged(self) -> None: ... + def LockInPlaceActive(self, fLock, /) -> None: ... + def GetExtendedControl(self) -> None: ... + def TransformCoords( + self, PtlHimetric: tuple[Incomplete, Incomplete], pPtfContainer: tuple[float, float], dwFlags, / + ) -> None: ... + def TranslateAccelerator(self, pMsg: PyMSG, grfModifiers, /) -> None: ... + def OnFocus(self, fGotFocus, /) -> None: ... + def ShowPropertyFrame(self) -> None: ... + +class PyIOleInPlaceActiveObject: + def TranslateAccelerator(self, lpmsg: PyMSG, /) -> None: ... + def OnFrameWindowActivate(self, fActivate, /) -> None: ... + def OnDocWindowActivate(self, fActivate, /) -> None: ... + def ResizeBorder( + self, rcBorder: tuple[Incomplete, Incomplete, Incomplete, Incomplete], pUIWindow: PyIOleInPlaceUIWindow, fFrameWindow, / + ) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + +class PyIOleInPlaceFrame: + def InsertMenus(self, hmenuShared, menuWidths: PyOLEMENUGROUPWIDTHS, /) -> None: ... + def SetMenu(self, hmenuShared, holemenu, hwndActiveObject, /) -> None: ... + def RemoveMenus(self, hmenuShared, /) -> None: ... + def SetStatusText(self, pszStatusText, /) -> None: ... + def EnableModeless(self, fEnable, /) -> None: ... + def TranslateAccelerator(self, lpmsg: PyMSG, wID, /) -> None: ... + +class PyIOleInPlaceObject: + def InPlaceDeactivate(self) -> None: ... + def UIDeactivate(self) -> None: ... + def SetObjectRects(self) -> None: ... + def ReactivateAndUndo(self) -> None: ... + +class PyIOleInPlaceSite: + def CanInPlaceActivate(self) -> None: ... + def OnInPlaceActivate(self) -> None: ... + def OnUIActivate(self) -> None: ... + def GetWindowContext(self) -> None: ... + def Scroll(self) -> None: ... + def OnUIDeactivate(self, fUndoable, /) -> None: ... + def OnInPlaceDeactivate(self) -> None: ... + def DiscardUndoState(self) -> None: ... + def DeactivateAndUndo(self) -> None: ... + def OnPosRectChange(self) -> None: ... + +class PyIOleInPlaceSiteEx: + def OnInPlaceActivateEx(self, dwFlags, /) -> None: ... + def OnInPlaceDeactivateEx(self, fNoRedraw, /) -> None: ... + def RequestUIActivate(self) -> None: ... + +class PyIOleInPlaceSiteWindowless: + def CanWindowlessActivate(self) -> None: ... + def GetCapture(self) -> None: ... + def SetCapture(self, fCapture, /) -> None: ... + def GetFocus(self) -> None: ... + def SetFocus(self, fFocus, /) -> None: ... + def GetDC(self, grfFlags, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def ReleaseDC(self, hDC: PyCDC, /) -> None: ... + def InvalidateRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], fErase, /) -> None: ... + def InvalidateRgn(self, hRgn, fErase, /) -> None: ... + def ScrollRect(self, dx, dy, /) -> None: ... + def AdjustRect(self) -> None: ... + def OnDefWindowMessage(self, msg, wParam, lParam, /) -> None: ... + +class PyIOleInPlaceUIWindow: + def GetBorder(self) -> None: ... + def RequestBorderSpace(self, borderwidths: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def SetBorderSpace(self, borderwidths: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def SetActiveObject(self, pActiveObject: PyIOleInPlaceActiveObject, pszObjName, /) -> None: ... + +class PyIOleObject: + def SetClientSite(self, pClientSite: PyIOleClientSite, /) -> None: ... + def GetClientSite(self) -> None: ... + def SetHostNames(self, szContainerApp, szContainerObj, /) -> None: ... + def Close(self, dwSaveOption, /) -> None: ... + def SetMoniker(self, dwWhichMoniker, pmk: PyIMoniker, /) -> None: ... + def GetMoniker(self, dwAssign, dwWhichMoniker, /) -> None: ... + def InitFromData(self, pDataObject: PyIDataObject, fCreation, dwReserved, /) -> None: ... + def GetClipboardData(self, dwReserved, /) -> None: ... + def DoVerb( + self, + iVerb, + msg: PyMSG, + pActiveSite: PyIOleClientSite, + lindex, + hwndParent, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ) -> None: ... + def EnumVerbs(self) -> None: ... + def Update(self) -> None: ... + def IsUpToDate(self) -> bool: ... + def GetUserClassID(self) -> None: ... + def GetUserType(self, dwFormOfType, /) -> None: ... + def SetExtent(self, dwDrawAspect, size: tuple[Incomplete, Incomplete], /) -> None: ... + def GetExtent(self, dwDrawAspect, size: tuple[Incomplete, Incomplete], /) -> None: ... + def Advise(self, pAdvSink, /) -> None: ... + def Unadvise(self, dwConnection, /) -> None: ... + def EnumAdvise(self) -> None: ... + def GetMiscStatus(self, dwAspect, /) -> None: ... + def SetColorScheme(self) -> None: ... + +class PyIOleWindow: + def GetWindow(self) -> None: ... + def ContextSensitiveHelp(self, fEnterMode, /) -> None: ... + +class PyIPersist: + def GetClassID(self) -> PyIID: ... + +class PyIPersistFile: + def IsDirty(self) -> bool: ... + def Load(self, FileName, Mode, /) -> None: ... + def Save(self, FileName, fRemember, /) -> None: ... + def SaveCompleted(self, FileName, /) -> None: ... + def GetCurFile(self): ... + +class PyIPersistFolder: + def Initialize(self, pidl: PyIDL, /) -> None: ... + +class PyIPersistFolder2: + def GetCurFolder(self) -> None: ... + +class PyIPersistPropertyBag: + def InitNew(self) -> None: ... + def Load(self, bag: PyIPropertyBag, log: PyIErrorLog | None = ..., /) -> None: ... + def Save(self, bag: PyIPropertyBag, clearDirty, saveProperties, /) -> None: ... + +class PyIPersistSerializedPropStorage: + def SetFlags(self, flags, /) -> None: ... + def SetPropertyStorage(self, ps, /) -> None: ... + def GetPropertyStorage(self): ... + +class PyIPersistStorage: + def IsDirty(self) -> bool: ... + def InitNew(self, PyIStorage: PyIStorage, /) -> None: ... + def Load(self, storage: PyIStorage, /) -> None: ... + def Save(self, PyIStorage: PyIStorage, _int, /) -> None: ... + def SaveCompleted(self, PyIStorage: PyIStorage, /) -> None: ... + def HandsOffStorage(self) -> None: ... + +class PyIPersistStream: + def IsDirty(self) -> bool: ... + def Load(self, stream: PyIStream, /) -> None: ... + def Save(self, stream: PyIStream, bClearDirty, /) -> None: ... + def GetSizeMax(self) -> int: ... + +class PyIPersistStreamInit: + def InitNew(self) -> None: ... + +class PyIProcessDebugManager: + def CreateApplication(self) -> None: ... + def GetDefaultApplication(self) -> None: ... + def AddApplication(self, pda: PyIDebugApplication, /) -> None: ... + def RemoveApplication(self, dwAppCookie, /) -> None: ... + def CreateDebugDocumentHelper(self, unkOuter, /) -> None: ... + +class PyIProfAdmin: + def GetLastError(self, hr, flags, /): ... + def CreateProfile(self, oldProfileName: str, Password: str, uiParam: int = ..., flags: int = ..., /) -> None: ... + def DeleteProfile(self, oldProfileName: str, flags: int = ..., /) -> None: ... + def CopyProfile(self, oldProfileName: str, Password: str, newProfileName: str, uiParam: int = ..., flags=..., /) -> None: ... + def RenameProfile( + self, oldProfileName: str, Password: str, newProfileName: str, uiParam: int = ..., flags=..., / + ) -> None: ... + def SetDefaultProfile(self, profileName: str, flags: int = ..., /) -> None: ... + def AdminServices(self, profileName: str, Password: str | None = ..., uiParam: int = ..., flags=..., /) -> PyIProfAdmin: ... + +class PyIPropertyBag: + def Read(self, propName, propType, errorLog: PyIErrorLog | None = ..., /): ... + def Write(self, propName, value, /) -> None: ... + +class PyIPropertyChange: + def ApplyToPropVariant(self, OrigVal: PyPROPVARIANT, /) -> PyPROPVARIANT: ... + +class PyIPropertyChangeArray: + def GetCount(self): ... + def GetAt(self, Index, riid: PyIID, /) -> PyIPropertyChange: ... + def InsertAt(self, Index, PropChange: PyIPropertyChange, /) -> None: ... + def Append(self, PropChange: PyIPropertyChange, /) -> None: ... + def AppendOrReplace(self, PropChange: PyIPropertyChange, /) -> None: ... + def RemoveAt(self, Index, /) -> None: ... + def IsKeyInArray(self, key: PyPROPERTYKEY, /) -> bool: ... + +class PyIPropertyDescription: + def GetPropertyKey(self) -> PyPROPERTYKEY: ... + def GetCanonicalName(self): ... + def GetPropertyType(self): ... + def GetDisplayName(self): ... + def GetEditInvitation(self): ... + def GetTypeFlags(self, mask, /): ... + def GetViewFlags(self): ... + def GetDefaultColumnWidth(self): ... + def GetDisplayType(self): ... + def GetColumnState(self): ... + def GetGroupingRange(self): ... + def GetRelativeDescriptionType(self): ... + def GetRelativeDescription(self, var1: PyPROPVARIANT, var2: PyPROPVARIANT, /) -> tuple[Incomplete, Incomplete]: ... + def GetSortDescription(self): ... + def GetSortDescriptionLabel(self, Descending, /): ... + def GetAggregationType(self): ... + def GetConditionType(self) -> tuple[Incomplete, Incomplete]: ... + def GetEnumTypelist(self, riid: PyIID, /) -> PyIPropertyEnumTypelist: ... + def CoerceToCanonicalValue(self, Value: PyPROPVARIANT, /): ... + def FormatForDisplay(self, Value: PyPROPVARIANT, Flags, /): ... + def IsValueCanonical(self, Value, /) -> bool: ... + +class PyIPropertyDescriptionAliasInfo: + def GetSortByAlias(self, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetAdditionalSortByAliases(self, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + +class PyIPropertyDescriptionlist: + def GetCount(self): ... + def GetAt(self, Elem, riid: PyIID, /) -> PyIPropertyDescription: ... + +class PyIPropertyDescriptionSearchInfo: + def GetSearchInfoFlags(self): ... + def GetColumnIndexType(self): ... + def GetProjectionString(self): ... + def GetMaxSize(self): ... + +class PyIPropertyEnumType: + def GetEnumType(self): ... + def GetValue(self) -> PyPROPVARIANT: ... + def GetRangeMinValue(self) -> PyPROPVARIANT: ... + def GetRangeSetValue(self) -> PyPROPVARIANT: ... + def GetDisplayText(self) -> None: ... + +class PyIPropertyEnumTypelist: + def GetCount(self): ... + def GetAt(self, itype, riid: PyIID, /) -> PyIPropertyEnumType: ... + def FindMatchingIndex(self, Cmp: PyPROPVARIANT, /): ... + +class PyIPropertySetStorage: + def Create(self, fmtid: PyIID, clsid: PyIID, Flags, Mode, /) -> PyIPropertyStorage: ... + def Open(self, fmtid: PyIID, Mode, /) -> PyIPropertyStorage: ... + def Delete(self, fmtid: PyIID, /) -> None: ... + def Enum(self) -> PyIEnumSTATPROPSETSTG: ... + +class PyIPropertyStorage: + def ReadMultiple(self, props: tuple[PROPSPEC, ...], /) -> tuple[Incomplete, ...]: ... + def WriteMultiple( + self, props: tuple[PROPSPEC, ...], values: tuple[Incomplete, ...], propidNameFirst: int = ..., / + ) -> None: ... + def DeleteMultiple(self, props: tuple[PROPSPEC, ...], /) -> None: ... + def ReadPropertyNames(self, props: tuple[Incomplete, ...], /) -> tuple[Incomplete, ...]: ... + def WritePropertyNames(self, props: tuple[Incomplete, ...], names: tuple[str, ...], /) -> None: ... + def DeletePropertyNames(self, props: tuple[Incomplete, ...], /) -> None: ... + def Commit(self, CommitFlags, /) -> None: ... + def Revert(self) -> None: ... + def Enum(self) -> PyIEnumSTATPROPSTG: ... + def SetTimes(self, ctime: TimeType, atime: TimeType, mtime: TimeType, /) -> None: ... + def SetClass(self, clsid: PyIID, /) -> None: ... + def Stat(self): ... + +class PyIPropertyStore: + def GetCount(self): ... + def GetAt(self, iProp, /) -> PyPROPERTYKEY: ... + def GetValue(self, Key: PyPROPERTYKEY, /) -> PyPROPVARIANT: ... + def SetValue(self, Key: PyPROPERTYKEY, Value: PyPROPVARIANT, /) -> None: ... + def Commit(self) -> None: ... + +class PyIPropertyStoreCache: + def GetState(self, key: PyPROPERTYKEY, /): ... + def GetValueAndState(self, key: PyPROPERTYKEY, /) -> tuple[PyPROPVARIANT, Incomplete]: ... + def SetState(self, key: PyPROPERTYKEY, state, /) -> None: ... + def SetValueAndState(self, key: PyPROPERTYKEY, value: PyPROPVARIANT, state, /) -> None: ... + +class PyIPropertyStoreCapabilities: + def IsPropertyWritable(self, key: PyPROPERTYKEY, /) -> bool: ... + +class PyIPropertySystem: + def GetPropertyDescription(self, Key: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetPropertyDescriptionByName(self, CanonicalName, riid: PyIID, /) -> PyIPropertyDescription: ... + def GetPropertyDescriptionlistFromString(self, Proplist, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def EnumeratePropertyDescriptions(self, Filter, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def FormatForDisplay(self, Key: PyPROPERTYKEY, Value: PyPROPVARIANT, Flags, /): ... + def RegisterPropertySchema(self, Path, /) -> None: ... + def UnregisterPropertySchema(self, Path, /) -> None: ... + def RefreshPropertySchema(self) -> None: ... + +class PyIProvideClassInfo: + def GetClassInfo(self) -> PyITypeInfo: ... + +class PyIProvideClassInfo2: + def GetGUID(self, flags, /) -> PyIID: ... + +class PyIProvideExpressionContexts: + def EnumExpressionContexts(self) -> None: ... + +class PyIProvideTaskPage: + def GetPage(self, tpType, PersistChanges, /) -> None: ... + +class PyIQueryAssociations: + def Init(self, flags, assoc: str, hkeyProgId: PyHKEY | None = ..., hwnd: int | None = ..., /) -> None: ... + def GetKey(self, flags, assocKey, arg: str, /): ... + def GetString(self, flags, assocStr, arg: str, /): ... + +class PyIRelatedItem: + def GetItemIDlist(self) -> PyIDL: ... + def GetItem(self) -> PyIShellItem: ... + +class PyIRemoteDebugApplication: + def ResumeFromBreakPoint(self, prptFocus: PyIRemoteDebugApplicationThread, bra, era, /) -> None: ... + def CauseBreak(self) -> None: ... + def ConnectDebugger(self, pad: PyIApplicationDebugger, /) -> None: ... + def DisconnectDebugger(self) -> None: ... + def GetDebugger(self) -> PyIApplicationDebugger: ... + def CreateInstanceAtApplication(self, rclsid: PyIID, pUnkOuter: PyIUnknown, dwClsContext, riid: PyIID, /) -> PyIUnknown: ... + def QueryAlive(self) -> None: ... + def EnumThreads(self) -> PyIEnumRemoteDebugApplicationThreads: ... + def GetName(self) -> None: ... + def GetRootNode(self) -> PyIDebugApplicationNode: ... + def EnumGlobalExpressionContexts(self): ... + +class PyIRemoteDebugApplicationEvents: + def OnConnectDebugger(self, pad: PyIApplicationDebugger, /) -> None: ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, pstrName, /) -> None: ... + def OnDebugOutput(self, pstr, /) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnLeaveBreakPoint(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnCreateThread(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnDestroyThread(self, prdat: PyIRemoteDebugApplicationThread, /) -> None: ... + def OnBreakFlagChange(self, abf, prdatSteppingThread: PyIRemoteDebugApplicationThread, /) -> None: ... + +class PyIRemoteDebugApplicationThread: + def GetSystemThreadId(self) -> None: ... + def GetApplication(self) -> None: ... + def EnumStackFrames(self) -> None: ... + def GetDescription(self) -> None: ... + def SetNextStatement(self, pStackFrame: PyIDebugStackFrame, pCodeContext: PyIDebugCodeContext, /) -> None: ... + def GetState(self) -> None: ... + def Suspend(self) -> None: ... + def Resume(self) -> None: ... + def GetSuspendCount(self) -> None: ... + +class PyIRunningObjectTable: + def Register(self): ... + def Revoke(self): ... + def IsRunning(self, objectName: PyIMoniker, /) -> bool: ... + def GetObject(self, objectName: PyIMoniker, /) -> PyIUnknown: ... + def EnumRunning(self) -> PyIEnumMoniker: ... + +class PyIScheduledWorkItem: + def CreateTrigger(self) -> tuple[Incomplete, PyITaskTrigger]: ... + def DeleteTrigger(self, Trigger, /) -> None: ... + def GetTriggerCount(self): ... + def GetTrigger(self, iTrigger, /) -> PyITaskTrigger: ... + def GetTriggerString(self): ... + def GetRunTimes(self, Count, Begin: TimeType, End: TimeType, /) -> tuple[TimeType, Incomplete, Incomplete, Incomplete]: ... + def GetNextRunTime(self) -> TimeType: ... + def SetIdleWait(self, wIdleMinutes, wDeadlineMinutes, /) -> None: ... + def GetIdleWait(self) -> tuple[Incomplete, Incomplete]: ... + def Run(self) -> None: ... + def Terminate(self) -> None: ... + def EditWorkItem(self, hParent: int, dwReserved, /) -> None: ... + def GetMostRecentRunTime(self) -> TimeType: ... + def GetStatus(self): ... + def GetExitCode(self) -> tuple[Incomplete, Incomplete]: ... + def SetComment(self, Comment, /) -> None: ... + def GetComment(self) -> str: ... + def SetCreator(self, Creator, /) -> None: ... + def GetCreator(self) -> None: ... + def SetWorkItemData(self, Data: str, /) -> None: ... + def GetWorkItemData(self) -> str: ... + def SetErrorRetryCount(self, wRetryCount, /) -> None: ... + def GetErrorRetryCount(self) -> None: ... + def SetErrorRetryInterval(self, RetryInterval, /) -> None: ... + def GetErrorRetryInterval(self) -> None: ... + def SetFlags(self, dwFlags, /) -> None: ... + def GetFlags(self): ... + def SetAccountInformation(self, AccountName, Password, /) -> None: ... + def GetAccountInformation(self): ... + +class PyIServerSecurity: + def QueryBlanket(self, Capabilities: int = ..., /): ... + def ImpersonateClient(self) -> None: ... + def RevertToSelf(self) -> None: ... + def IsImpersonating(self) -> bool: ... + +class PyIServiceProvider: + def QueryService(self, clsid: PyIID, iid: PyIID, /) -> PyIUnknown: ... + +class PyIShellBrowser: + def InsertMenusSB(self, hmenuShared: int, lpMenuWidths: PyOLEMENUGROUPWIDTHS, /) -> PyOLEMENUGROUPWIDTHS: ... + def SetMenuSB(self, hmenuShared: int, holemenuRes: int, hwndActiveObject: int, /) -> None: ... + def RemoveMenusSB(self, hmenuShared: int, /) -> None: ... + def SetStatusTextSB(self, pszStatusText, /) -> None: ... + def EnableModelessSB(self, fEnable, /) -> None: ... + def TranslateAcceleratorSB(self, pmsg: PyMSG, wID, /) -> None: ... + def BrowseObject(self, pidl: PyIDL, wFlags, /) -> None: ... + def GetViewStateStream(self, grfMode, /) -> PyIStream: ... + def GetControlWindow(self, _id, /) -> None: ... + def SendControlMsg(self, _id, uMsg, wParam, lParam, /): ... + def QueryActiveShellView(self) -> PyIShellView: ... + def OnViewWindowActive(self, pshv: PyIShellView, /) -> None: ... + def SetToolbarItems(self, lpButtons, uFlags, /) -> None: ... + +class PyIShellExtInit: + def Initialize(self, pFolder: PyIDL, pDataObject: PyIDataObject, hkey: int, /) -> None: ... + +class PyIShellFolder: + def ParseDisplayName(self, hwndOwner: int, pbc: PyIBindCtx, DisplayName, Attributes: int = ..., /): ... + def EnumObjects(self, grfFlags, hwndOwner: int | None = ..., /) -> PyIEnumIDlist: ... + def BindToObject(self, pidl: PyIDL, pbc: PyIBindCtx, riid: PyIID, /) -> PyIShellFolder: ... + def BindToStorage(self, pidl: PyIDL, pbc: PyIBindCtx, riid: PyIID, /): ... + def CompareIDs(self, lparam, pidl1: PyIDL, pidl2: PyIDL, /): ... + def CreateViewObject(self, hwndOwner, riid: PyIID, /) -> PyIShellView: ... + def GetAttributesOf(self, pidl: tuple[PyIDL, ...], rgfInOut, /): ... + def GetUIObjectOf( + self, hwndOwner: int, pidl: tuple[PyIDL, ...], riid: PyIID, iidout: PyIID, Reserved=..., / + ) -> tuple[Incomplete, PyIUnknown]: ... + def GetDisplayNameOf(self, pidl: PyIDL, uFlags, /): ... + def SetNameOf(self, hwndOwner, pidl: PyIDL, Name, Flags, /) -> PyIDL: ... + +class PyIShellFolder2: + def GetDefaultSearchGUID(self, pguid: PyIID, /) -> PyIID: ... + def EnumSearches(self): ... + def GetDefaultColumn(self) -> tuple[Incomplete, Incomplete]: ... + def GetDefaultColumnState(self, iColumn, /): ... + def GetDetailsEx(self, pidl: PyIDL, pscid, /): ... + def GetDetailsOf(self, pidl: PyIDL, iColumn, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def MapColumnToSCID(self, Column, /): ... + +class PyIShellIcon: + def GetIconOf(self, pidl: PyIDL, /) -> None: ... + +class PyIShellIconOverlay: + def GetOverlayIndex(self, pidl: PyIDL, /) -> None: ... + def GetOverlayIconIndex(self, pidl: PyIDL, /) -> None: ... + +class PyIShellIconOverlayIdentifier: + def IsMemberOf(self, path: str, attrib, /) -> bool: ... + def GetOverlayInfo(self) -> tuple[str, Incomplete, Incomplete]: ... + def GetPriority(self): ... + +class PyIShellIconOverlayManager: + def GetFileOverlayInfo(self, path, attrib, flags, /): ... + def GetReservedOverlayInfo(self, path, attrib, flags, ireservedID, /) -> None: ... + def RefreshOverlayImages(self, flags, /) -> None: ... + def LoadNonloadedOverlayIdentifiers(self) -> None: ... + def OverlayIndexFromImageIndex(self, iImage, fAdd, /) -> None: ... + +class PyIShellItem: + def BindToHandler(self, pbc: PyIBindCtx, bhid: PyIID, riid: PyIID, /): ... + def GetParent(self) -> PyIShellItem: ... + def GetDisplayName(self, sigdnName, /): ... + def GetAttributes(self, Mask, /): ... + def Compare(self, psi: PyIShellItem, hint, /): ... + +class PyIShellItem2: + def GetPropertyStore(self, Flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyStoreForKeys(self, Keys: tuple[Incomplete, ...], Flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyStoreWithCreateObject(self, Flags, CreateObject: PyIUnknown, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyDescriptionlist(self, Type: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def Update(self, BindCtx: Incomplete | None = ..., /) -> None: ... + def GetProperty(self, key: PyPROPERTYKEY, /): ... + def GetCLSID(self, key: PyPROPERTYKEY, /) -> PyIID: ... + def GetFileTime(self, key: PyPROPERTYKEY, /) -> TimeType: ... + def GetInt32(self, key: PyPROPERTYKEY, /): ... + def GetString(self, key: PyPROPERTYKEY, /): ... + def GetUInt32(self, key: PyPROPERTYKEY, /): ... + def GetUInt64(self, key: PyPROPERTYKEY, /): ... + def GetBool(self, key: PyPROPERTYKEY, /): ... + +class PyIShellItemArray: + def BindToHandler(self, pbc: PyIBindCtx, rbhid: PyIID, riid: PyIID, /): ... + def GetPropertyStore(self, flags, riid: PyIID, /) -> PyIPropertyStore: ... + def GetPropertyDescriptionlist(self, Type: PyPROPERTYKEY, riid: PyIID, /) -> PyIPropertyDescriptionlist: ... + def GetAttributes(self, AttribFlags, Mask, /): ... + def GetCount(self): ... + def GetItemAt(self, dwIndex, /) -> PyIShellItem: ... + def EnumItems(self) -> PyIEnumShellItems: ... + +class PyIShellItemResources: + def GetAttributes(self) -> None: ... + def GetSize(self): ... + def GetTimes(self) -> None: ... + def SetTimes(self, pftCreation: TimeType, pftWrite: TimeType, pftAccess: TimeType, /) -> None: ... + def GetResourceDescription(self, pcsir: PySHELL_ITEM_RESOURCE, /) -> None: ... + def EnumResources(self) -> PyIEnumResources: ... + def SupportsResource(self, pcsir: PySHELL_ITEM_RESOURCE, /): ... + def OpenResource(self, pcsir: PySHELL_ITEM_RESOURCE, riid: PyIID, /) -> PyIUnknown: ... + def CreateResource(self, sir: PySHELL_ITEM_RESOURCE, riid: PyIID, /): ... + def MarkForDelete(self) -> None: ... + +class PyIShellLibrary: + def LoadLibraryFromItem(self, Library: PyIShellItem, Mode, /) -> None: ... + def LoadLibraryFromKnownFolder(self, Library: PyIID, Mode, /) -> None: ... + def AddFolder(self, Location: PyIShellItem, /) -> None: ... + def RemoveFolder(self, Location: PyIShellItem, /) -> None: ... + def GetFolders(self, Filter, riid: PyIID, /) -> PyIShellItemArray: ... + def ResolveFolder(self, FolderToResolve: PyIShellItem, Timeout, riid: PyIID, /) -> PyIShellItem: ... + def GetDefaultSaveFolder(self, Type, riid: PyIID, /) -> PyIShellItem: ... + def SetDefaultSaveFolder(self, Type, SaveFolder: PyIShellItem, /) -> None: ... + def GetOptions(self): ... + def SetOptions(self, Mask, Options, /) -> None: ... + def GetFolderType(self) -> PyIID: ... + def SetFolderType(self, Type: PyIID, /) -> None: ... + def GetIcon(self): ... + def SetIcon(self, Icon, /) -> None: ... + def Commit(self) -> None: ... + def Save(self, FolderToSaveIn: PyIShellItem, LibraryName, Flags, /) -> PyIShellItem: ... + def SaveInKnownFolder(self, FolderToSaveIn: PyIID, LibraryName, Flags, /) -> PyIShellItem: ... + +class PyIShellLink: + def GetPath(self, fFlags, cchMaxPath, /) -> tuple[Incomplete, WIN32_FIND_DATA]: ... + def GetIDlist(self) -> PyIDL: ... + def SetIDlist(self, pidl: PyIDL, /) -> None: ... + def GetDescription(self, cchMaxName: int = ..., /): ... + def SetDescription(self, Name, /) -> None: ... + def GetWorkingDirectory(self, cchMaxName: int = ..., /): ... + def SetWorkingDirectory(self, Dir, /) -> None: ... + def GetArguments(self, cchMaxName: int = ..., /): ... + def SetArguments(self, args, /) -> None: ... + def GetHotkey(self): ... + def SetHotkey(self, wHotkey, /) -> None: ... + def GetShowCmd(self): ... + def SetShowCmd(self, iShowCmd, /) -> None: ... + def GetIconLocation(self, cchMaxPath, /): ... + def SetIconLocation(self, iconPath: str, iIcon, /) -> None: ... + def SetRelativePath(self, relPath: str, reserved: int = ..., /) -> None: ... + def Resolve(self, hwnd: int, fFlags, /) -> None: ... + def SetPath(self, path: str, /) -> None: ... + +class PyIShellLinkDatalist: + def AddDataBlock(self, DataBlock, /) -> None: ... + def CopyDataBlock(self, Sig, /): ... + def GetFlags(self): ... + def RemoveDataBlock(self, Sig, /) -> None: ... + def SetFlags(self, Flags, /) -> None: ... + +class PyIShellView: + def TranslateAccelerator(self, pmsg, /): ... + def EnableModeless(self, fEnable, /) -> None: ... + def UIActivate(self, uState, /) -> None: ... + def Refresh(self) -> None: ... + def CreateViewWindow( + self, + psvPrevious: PyIShellView, + pfs: tuple[Incomplete, Incomplete], + psb: PyIShellBrowser, + prcView: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ): ... + def DestroyViewWindow(self) -> None: ... + def GetCurrentInfo(self): ... + def SaveViewState(self) -> None: ... + def SelectItem(self, pidlItem: PyIDL, uFlags, /) -> None: ... + def GetItemObject(self, uItem, riid: PyIID, /) -> PyIUnknown: ... + +class PyISpecifyPropertyPages: + def GetPages(self) -> None: ... + +class PyIStorage: + def CreateStream(self, Name, Mode, reserved1: int = ..., reserved2: int = ..., /) -> PyIStream: ... + def OpenStream(self, Name, reserved1, Mode, reserved2: int = ..., /) -> PyIStream: ... + def CreateStorage(self, Name, Mode, StgFmt, reserved2: int = ..., /) -> PyIStorage: ... + def OpenStorage(self, Name, Priority: PyIStorage, Mode, snbExclude, reserved=..., /) -> PyIStorage: ... + def CopyTo(self, rgiidExclude: tuple[Incomplete, Incomplete], snbExclude, stgDest: PyIStorage, /) -> None: ... + def MoveElementTo(self, Name, stgDest: PyIStorage, NewName, Flags, /) -> None: ... + def Commit(self, grfCommitFlags, /) -> None: ... + def Revert(self) -> None: ... + def EnumElements( + self, reserved1: int = ..., reserved2: Incomplete | None = ..., reserved3: int = ..., / + ) -> PyIEnumSTATSTG: ... + def DestroyElement(self, name: str, /) -> None: ... + def RenameElement(self, OldName, NewName, /) -> None: ... + def SetElementTimes(self, name, ctime: TimeType, atime: TimeType, mtime: TimeType, /) -> None: ... + def SetClass(self, clsid: PyIID, /) -> None: ... + def SetStateBits(self, grfStateBits, grfMask, /) -> None: ... + def Stat(self, grfStatFlag, /) -> STATSTG: ... + +class PyIStream: + def Read(self, numBytes, /) -> str: ... + def read(self, numBytes, /) -> str: ... + def Write(self, data: str, /) -> None: ... + def write(self, data: str, /) -> None: ... + + @overload + def Seek(self, offset: int, origin: int, /) -> int: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def Seek(self, offset: tuple[int, int], origin: int, /) -> int: ... + + @overload + def SetSize(self, newSize: int, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def SetSize(self, newSize: tuple[int, int], /) -> None: ... + + @overload + def CopyTo(self, stream: PyIStream, cb: int, /) -> int: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def CopyTo(self, stream: PyIStream, cb: tuple[int, int], /) -> int: ... + + def Commit(self, flags, /) -> None: ... + def Revert(self) -> None: ... + + @overload + def LockRegion(self, offset: int, cb: int, lockType, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def LockRegion(self, offset: tuple[int, int], cb: tuple[int, int], lockType, /) -> None: ... + + @overload + def UnLockRegion(self, offset: int, cb: int, lockType, /) -> None: ... + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def UnLockRegion(self, offset: tuple[int, int], cb: tuple[int, int], lockType, /) -> None: ... + + def Clone(self) -> PyIStream: ... + def Stat(self, grfStatFlag: int = ..., /) -> STATSTG: ... + +class PyITask: + def SetApplicationName(self, ApplicationName, /) -> None: ... + def GetApplicationName(self): ... + def SetParameters(self, Parameters, /) -> None: ... + def GetParameters(self): ... + def SetWorkingDirectory(self, WorkingDirectory, /) -> None: ... + def GetWorkingDirectory(self): ... + def SetPriority(self, Priority, /) -> None: ... + def GetPriority(self): ... + def SetTaskFlags(self, dwFlags, /) -> None: ... + def GetTaskFlags(self): ... + def SetMaxRunTime(self, MaxRunTimeMS, /) -> None: ... + def GetMaxRunTime(self): ... + +class PyITaskScheduler: + def SetTargetComputer(self, Computer, /) -> None: ... + def GetTargetComputer(self): ... + def Enum(self) -> tuple[str, ...]: ... + def Activate(self, Name, riid: PyIID, /) -> PyITask: ... + def Delete(self, TaskName, /) -> None: ... + def NewWorkItem(self, TaskName, rclsid: PyIID, riid: PyIID, /) -> PyITask: ... + def AddWorkItem(self, TaskName, WorkItem: PyITask, /) -> None: ... + def IsOfType(self, Name, riid: PyIID, /) -> bool: ... + +class PyITaskTrigger: + def SetTrigger(self, Trigger: PyTASK_TRIGGER, /) -> None: ... + def GetTrigger(self) -> PyTASK_TRIGGER: ... + def GetTriggerString(self) -> str: ... + +class PyITaskbarlist: + def HrInit(self) -> None: ... + def AddTab(self, hwnd: int, /) -> None: ... + def DeleteTab(self, hwnd: int, /) -> None: ... + def ActivateTab(self, hwnd: int, /) -> None: ... + def SetActiveAlt(self, hwnd: int, /) -> None: ... + +class PyITransferAdviseSink: + def UpdateProgress(self, SizeCurrent, SizeTotal, FilesCurrent, FilesTotal, FoldersCurrent, FoldersTotal, /) -> None: ... + def UpdateTransferState(self, State, /) -> None: ... + def ConfirmOverwrite(self, Source: PyIShellItem, DestParent: PyIShellItem, Name, /): ... + def ConfirmEncryptionLoss(self, Source: PyIShellItem, /): ... + def FileFailure(self, Item: PyIShellItem, ItemName, Error, /) -> tuple[Incomplete, Incomplete]: ... + def SubStreamFailure(self, Item: PyIShellItem, StreamName, Error, /): ... + def PropertyFailure(self, Item: PyIShellItem, key: PyPROPERTYKEY, Error, /): ... + +class PyITransferDestination: + def Advise(self, Sink: PyITransferAdviseSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def CreateItem( + self, Name, Attributes, Size, Flags, riidItem: PyIID, riidResources: PyIID, / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +class PyITransferMediumItem: ... + +class PyITransferSource: + def Advise(self, Sink: PyITransferAdviseSink, /): ... + def Unadvise(self, Cookie, /) -> None: ... + def SetProperties(self, proparray: PyIPropertyChangeArray, /) -> None: ... + def OpenItem(self, Item: PyIShellItem, flags, riid: PyIID, /) -> tuple[Incomplete, PyIShellItemResources]: ... + def MoveItem(self, Item: PyIShellItem, ParentDst: PyIShellItem, NameDst, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def RecycleItem(self, Source: PyIShellItem, ParentDest: PyIShellItem, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def RemoveItem(self, Source: PyIShellItem, flags, /): ... + def RenameItem(self, Source: PyIShellItem, NewName, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def LinkItem(self, Source: PyIShellItem, ParentDest: PyIShellItem, NewName, flags, /) -> tuple[Incomplete, PyIShellItem]: ... + def ApplyPropertiesToItem(self, Source: PyIShellItem, /) -> PyIShellItem: ... + def GetDefaultDestinationName(self, Source: PyIShellItem, ParentDest: PyIShellItem, /): ... + def EnterFolder(self, ChildFolderDest: PyIShellItem, /): ... + def LeaveFolder(self, ChildFolderDest: PyIShellItem, /): ... + +class PyITypeComp: + def Bind(self, szName: str, wflags: int = ..., /): ... + def BindType(self, szName: str, /): ... + +class PyITypeInfo: + def GetContainingTypeLib(self) -> tuple[PyITypeLib, Incomplete]: ... + def GetDocumentation(self, memberId, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetFuncDesc(self, memberId, /) -> FUNCDESC: ... + def GetImplTypeFlags(self, index, /): ... + def GetIDsOfNames(self): ... + def GetNames(self, memberId, /): ... + def GetTypeAttr(self) -> TYPEATTR: ... + def GetRefTypeInfo(self, hRefType, /) -> PyITypeInfo: ... + def GetRefTypeOfImplType(self, hRefType, /): ... + def GetVarDesc(self, memberId, /) -> VARDESC: ... + def GetTypeComp(self) -> PyITypeComp: ... + +class PyITypeLib: + def GetDocumentation(self, index, /): ... + def GetLibAttr(self) -> TLIBATTR: ... + def GetTypeComp(self) -> PyITypeComp: ... + def GetTypeInfo(self, index, /) -> PyITypeInfo: ... + def GetTypeInfoCount(self): ... + def GetTypeInfoOfGuid(self, iid: PyIID, /) -> PyITypeInfo: ... + def GetTypeInfoType(self, index, /): ... + +class PyIUniformResourceLocator: + def GetURL(self): ... + def SetURL(self, URL, InFlags: int = ..., /) -> None: ... + def InvokeCommand(self, Verb, Flags: int = ..., hwndParent: int = ..., /): ... + +@final +class PyIUnknown: + def QueryInterface(self, iid, useIID: Incomplete | None = ..., /) -> PyIUnknown: ... + +class PyIViewObject: + def Draw( + self, + dwDrawAspect, + lindex, + aspectFlags, + hdcTargetDev, + hdcDraw, + arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + funcContinue, + obContinue, + /, + ) -> None: ... + def GetColorSet(self, dwDrawAspect, lindex, aspectFlags, hicTargetDev, /) -> None: ... + def Freeze(self, dwDrawAspect, lindex, aspectFlags, /) -> None: ... + def Unfreeze(self, dwFreeze, /) -> None: ... + def SetAdvise(self, aspects, advf, pAdvSink, /) -> None: ... + def GetAdvise(self) -> None: ... + +class PyIViewObject2: + def GetExtent(self, dwDrawAspect, lindex, targetDevice, /) -> None: ... + +class PyMAPINAMEIDArray: ... +class PyOLEMENUGROUPWIDTHS: ... +class PyPROPERTYKEY: ... + +@final +class PyPROPVARIANT: + @overload + @deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") + def __new__(self, Value: tuple[int, int], Type=...) -> Self: ... + @overload + def __new__(self, Value, Type=...) -> Self: ... + + @property + def vt(self): ... + def GetValue(self): ... + def ToString(self): ... + def ChangeType(self, Type, Flags: int = ..., /) -> PyPROPVARIANT: ... + +class PySAndRestriction: ... +class PySBinaryArray: ... +class PySBitMaskRestriction: ... +class PySContentRestriction: ... +class PySExistRestriction: ... +class PySHELL_ITEM_RESOURCE: ... +class PySNotRestriction: ... +class PySOrRestriction: ... +class PySPropTagArray: ... +class PySPropValue: ... +class PySPropValueArray: ... +class PySPropertyRestriction: ... +class PySRestriction: ... +class PySRow: ... +class PySRowSet: ... +class PySSortOrderItem: ... +class PySSortOrderSet: ... + +class PySTGMEDIUM: + @property + def tymed(self): ... + @property + def data(self): ... + @property + def data_handle(self): ... + def set(self, tymed, data, /) -> None: ... + +class PyTASK_TRIGGER: ... +class RTF_WCSINFO: ... +class SHFILEINFO: ... +class SHFILEOPSTRUCT: ... +class SI_ACCESS: ... +class SI_INHERIT_TYPE: ... +class SI_OBJECT_INFO: ... + +STATSTG: TypeAlias = tuple[str | None, int, int, TimeType, TimeType, TimeType, int, int, PyIID, int, int] + +class TLIBATTR: ... + +class TYPEATTR: + @property + def iid(self) -> PyIID: ... + @property + def lcid(self): ... + @property + def memidConstructor(self): ... + @property + def memidDestructor(self): ... + @property + def cbSizeInstance(self): ... + @property + def typekind(self): ... + @property + def cFuncs(self): ... + @property + def cVars(self): ... + @property + def cImplTypes(self): ... + @property + def cbSizeVft(self): ... + @property + def cbAlignment(self): ... + @property + def wTypeFlags(self): ... + @property + def wMajorVerNum(self): ... + @property + def wMinorVerNum(self): ... + @property + def tdescAlias(self) -> TYPEDESC: ... + @property + def idldeskType(self) -> IDLDESC: ... + +class TYPEDESC: ... + +class VARDESC: + @property + def memid(self): ... + @property + def value(self): ... + @property + def elemdescVar(self) -> ELEMDESC: ... + @property + def varFlags(self): ... + @property + def varkind(self): ... + +class CHARFORMAT: ... +class CREATESTRUCT: ... +class LV_COLUMN: ... +class LV_ITEM: ... +class PARAFORMAT: ... +class PyAssocCObject: ... + +class PyAssocObject: + def AttachObject(self) -> None: ... + def GetAttachedObject(self): ... + +class PyCBitmap: + def CreateCompatibleBitmap(self, dc: PyCDC, width: int, height: int, /) -> None: ... + def GetSize(self) -> tuple[Incomplete, Incomplete]: ... + def GetHandle(self, *args: Unused) -> int: ... + def LoadBitmap(self, idRes, obDLL: PyDLL | None = ..., /) -> None: ... + def LoadBitmapFile(self, fileObject, /) -> None: ... + def LoadPPMFile(self, fileObject, cols, rows, /) -> None: ... + def Paint( + self, + dcObject: PyCDC, + arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + /, + ) -> None: ... + def GetInfo(self): ... + + @overload + def GetBitmapBits(self, asString: Literal[False] = False, /) -> tuple[int, ...]: ... + @overload + def GetBitmapBits(self, asString: Literal[True], /) -> bytes: ... + @overload + def GetBitmapBits(self, asString: bool, /) -> tuple[int, ...] | bytes: ... + + def SaveBitmapFile(self, dcObject: PyCDC, Filename: str, /): ... + +class PyCBrush: + def CreateSolidBrush(self, i: int) -> None: ... + def GetSafeHandle(self): ... + +class PyCButton: + def CreateWindow( + self, caption: str, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetBitmap(self): ... + def SetBitmap(self, hBitmap: int = ..., /): ... + def GetCheck(self): ... + def SetCheck(self, idCheck, /) -> None: ... + def GetState(self): ... + def SetState(self, bHighlight, /): ... + def GetButtonStyle(self): ... + def SetButtonStyle(self, style, bRedraw: int = ..., /): ... + +class PyCCmdTarget: + def BeginWaitCursor(self) -> None: ... + def EndWaitCursor(self) -> None: ... + def HookCommand(self, obHandler, _id, /): ... + def HookCommandUpdate(self, obHandler, _id, /): ... + def HookOleEvent(self): ... + def HookNotify(self, obHandler, _id, /): ... + def RestoreWaitCursor(self) -> None: ... + +class PyCCmdUI: + @property + def m_nIndex(self): ... + @property + def m_nID(self): ... + @property + def m_pMenu(self) -> PyCMenu: ... + @property + def m_pSubMenu(self) -> PyCMenu: ... + def Enable(self, bEnable: int = ..., /) -> None: ... + def SetCheck(self, state: int = ..., /) -> None: ... + def SetRadio(self, bOn: int = ..., /) -> None: ... + def SetText(self, text: str, /) -> None: ... + def ContinueRouting(self) -> None: ... + +class PyCColorDialog: + def GetColor(self): ... + def DoModal(self): ... + def GetSavedCustomColors(self): ... + def SetCurrentColor(self, color, /) -> None: ... + def SetCustomColors(self, colors: Sequence[int], /) -> None: ... + def GetCustomColors(self) -> tuple[Incomplete, ...]: ... + +class PyCComboBox: + def AddString(self, _object, /): ... + def DeleteString(self, pos, /): ... + def Dir(self, attr, wild: str, /): ... + def GetCount(self): ... + def GetCurSel(self): ... + def GetEditSel(self): ... + def GetExtendedUI(self): ... + def GetItemData(self, item, /): ... + def GetItemValue(self, item, /): ... + def GetLBText(self, index, /) -> str: ... + def GetLBTextLen(self, index, /): ... + def InsertString(self, pos, _object, /): ... + def LimitText(self, _max, /): ... + def ResetContent(self) -> None: ... + def SelectString(self, after, string: str, /) -> None: ... + def SetCurSel(self, index, /) -> None: ... + def SetEditSel(self, start, end, /) -> None: ... + def SetExtendedUI(self, bExtended: int = ..., /) -> None: ... + def SetItemData(self, item, Data, /): ... + def SetItemValue(self, item, data, /): ... + def ShowDropDown(self, bShowIt: int = ..., /) -> None: ... + +class PyCCommonDialog: ... +class PyCControl: ... + +class PyCControlBar: + @property + def dockSite(self) -> PyCFrameWnd: ... + @property + def dockBar(self) -> PyCWnd: ... + @property + def dockContext(self) -> PyCDockContext: ... + @property + def dwStyle(self): ... + @property + def dwDockStyle(self): ... + def CalcDynamicLayout(self, length, dwMode, /): ... + def CalcFixedLayout(self, bStretch, bHorz, /): ... + def EnableDocking(self, style, /) -> None: ... + def EraseNonClient(self) -> None: ... + def GetBarStyle(self): ... + def GetCount(self): ... + def GetDockingFrame(self) -> PyCFrameWnd: ... + def IsFloating(self) -> bool: ... + def SetBarStyle(self, style, /) -> None: ... + def ShowWindow(self): ... + +class PyCCtrlView: + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCDC: + def AbortDoc(self) -> None: ... + def Arc( + self, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + pointStart: tuple[Incomplete, Incomplete], + pointEnd: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def BeginPath(self) -> None: ... + def BitBlt( + self, destPos: tuple[int, int], size: tuple[int, int], dc: PyCDC, srcPos: tuple[int, int], rop: int, / + ) -> None: ... + def Chord( + self, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + pointStart: tuple[Incomplete, Incomplete], + pointEnd: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def CreateCompatibleDC(self, dcFrom: PyCDC | None = ..., /) -> PyCDC: ... + def CreatePrinterDC(self, printerName: str | None = ..., /) -> None: ... + def DeleteDC(self) -> None: ... + def DPtoLP(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def Draw3dRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], colorTopLeft, colorBotRight, /) -> None: ... + def DrawFocusRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def DrawFrameControl(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], typ, state, /) -> None: ... + def DrawIcon(self, point: tuple[Incomplete, Incomplete], hIcon: int, /) -> None: ... + def DrawText( + self, s: str, _tuple: tuple[Incomplete, Incomplete, Incomplete, Incomplete], _format, / + ) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def Ellipse(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def EndDoc(self) -> None: ... + def EndPage(self) -> None: ... + def EndPath(self) -> None: ... + def ExtTextOut( + self, + _int, + _int1, + _int2, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + string, + _tuple: tuple[tuple[Incomplete, Incomplete], ...], + /, + ) -> None: ... + def FillPath(self) -> None: ... + def FillRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], brush: PyCBrush, /) -> None: ... + def FillSolidRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], color, /) -> None: ... + def FrameRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], brush: PyCBrush, /) -> None: ... + def GetBrushOrg(self) -> tuple[Incomplete, Incomplete]: ... + def GetClipBox(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetCurrentPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetDeviceCaps(self, index, /): ... + def GetHandleAttrib(self): ... + def GetHandleOutput(self): ... + def GetMapMode(self): ... + def GetNearestColor(self, color, /): ... + def GetPixel(self, x, y, /) -> None: ... + def GetSafeHdc(self) -> int: ... + def GetTextExtent(self, text: str, /) -> tuple[Incomplete, Incomplete]: ... + def GetTextExtentPoint(self, text: str, /) -> tuple[Incomplete, Incomplete]: ... + def GetTextFace(self) -> str: ... + def GetTextMetrics(self): ... + def GetViewportExt(self) -> tuple[Incomplete, Incomplete]: ... + def GetViewportOrg(self) -> tuple[Incomplete, Incomplete]: ... + def GetWindowExt(self) -> tuple[Incomplete, Incomplete]: ... + def GetWindowOrg(self) -> tuple[Incomplete, Incomplete]: ... + def IntersectClipRect(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def IsPrinting(self) -> bool: ... + def LineTo(self, point: tuple[Incomplete, Incomplete], x, y, /) -> None: ... + def LPtoDP(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def MoveTo(self, point: tuple[Incomplete, Incomplete], x, y, /) -> tuple[Incomplete, Incomplete]: ... + def OffsetWindowOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def OffsetViewportOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def PatBlt(self, destPos: tuple[Incomplete, Incomplete], size: tuple[Incomplete, Incomplete], rop, /) -> None: ... + def Pie(self, x1, y1, x2, y2, x3, y3, x4, y4, /) -> None: ... + def PolyBezier(self) -> None: ... + def Polygon(self) -> None: ... + def Polyline(self, points: list[tuple[Incomplete, Incomplete]], /) -> None: ... + def RealizePalette(self): ... + def Rectangle(self): ... + def RectVisible(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /): ... + def RestoreDC(self, saved, /) -> None: ... + def SaveDC(self): ... + def ScaleWindowExt(self) -> tuple[Incomplete, Incomplete]: ... + def ScaleViewportExt(self) -> tuple[Incomplete, Incomplete]: ... + def SelectClipRgn(self): ... + def SelectObject(self, ob: PyCBitmap, /) -> PyCBitmap: ... + def SetBkColor(self, color, /): ... + def SetBkMode(self, mode, /): ... + def SetBrushOrg(self, point: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetGraphicsMode(self, mode, /): ... + def SetMapMode(self, newMode, /): ... + def SetPixel(self, x, y, color, /) -> None: ... + def SetPolyFillMode(self, point: tuple[Incomplete, Incomplete], /): ... + def SetROP2(self, mode, /): ... + def SetTextAlign(self, newFlags, /): ... + def SetTextColor(self, color, /): ... + def SetWindowExt(self, size: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetWindowOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetViewportExt(self, size: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetViewportOrg(self, arg: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... + def SetWorldTransform(self): ... + def StartDoc(self, docName: str, outputFile: str, /) -> None: ... + def StartPage(self) -> None: ... + def StretchBlt( + self, + destPos: tuple[Incomplete, Incomplete], + size: tuple[Incomplete, Incomplete], + dc: PyCDC, + srcPos: tuple[Incomplete, Incomplete], + size1: tuple[Incomplete, Incomplete], + rop, + /, + ) -> None: ... + def StrokeAndFillPath(self) -> None: ... + def StrokePath(self) -> None: ... + def TextOut(self, _int, _int1, string, /) -> None: ... + +class PyCDialog: + def CreateWindow(self, obParent: PyCWnd | None = ..., /) -> None: ... + def DoModal(self): ... + def EndDialog(self, result, /) -> None: ... + def GotoDlgCtrl(self, control: PyCWnd, /) -> None: ... + def MapDialogRect( + self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def OnCancel(self) -> None: ... + def OnOK(self) -> None: ... + def OnInitDialog(self): ... + +class PyCDialogBar: + def CreateWindow(self, parent: PyCWnd, template: PyResourceId, style, _id, /) -> None: ... + +class PyCDocTemplate: + def DoCreateDoc(self, fileName: str | None = ..., /) -> PyCDocument: ... + def FindOpenDocument(self, fileName: str, /) -> PyCDocument: ... + def GetDocString(self, docIndex, /) -> str: ... + def GetDocumentlist(self): ... + def GetResourceID(self) -> None: ... + def GetSharedMenu(self) -> PyCMenu: ... + def InitialUpdateFrame( + self, frame: PyCFrameWnd | None = ..., doc: PyCDocument | None = ..., bMakeVisible: int = ..., / + ) -> None: ... + def SetContainerInfo(self, _id, /) -> None: ... + def SetDocStrings(self, docStrings: str, /) -> None: ... + def OpenDocumentFile(self, filename: str, bMakeVisible: int = ..., /) -> PyCDocument | None: ... + +class PyCDockContext: + @property + def ptLast(self) -> tuple[Incomplete, Incomplete]: ... + @property + def rectLast(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def sizeLast(self) -> tuple[Incomplete, Incomplete]: ... + @property + def bDitherLast(self): ... + @property + def rectDragHorz(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectDragVert(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectFrameDragHorz(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def rectFrameDragVert(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def dwDockStyle(self): ... + @property + def dwOverDockStyle(self): ... + @property + def dwStyle(self): ... + @property + def bFlip(self): ... + @property + def bForceFrame(self): ... + @property + def bDragging(self): ... + @property + def nHitTest(self): ... + @property + def uMRUDockID(self): ... + @property + def rectMRUDockPos(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @property + def dwMRUFloatStyle(self): ... + @property + def ptMRUFloatPos(self) -> tuple[Incomplete, Incomplete]: ... + def EndDrag(self): ... + def StartDrag(self, pt: tuple[Incomplete, Incomplete], /): ... + def EndResize(self): ... + def StartResize(self, hittest, pt: tuple[Incomplete, Incomplete], /): ... + def ToggleDocking(self): ... + +class PyCDocument: + def DeleteContents(self) -> None: ... + def DoSave(self, fileName: str, bReplace: int = ..., /) -> None: ... + def DoFileSave(self) -> None: ... + def GetDocTemplate(self) -> PyCDocTemplate: ... + def GetAllViews(self) -> list[Incomplete]: ... + def GetFirstView(self) -> PyCView: ... + def GetPathName(self) -> str: ... + def GetTitle(self) -> str: ... + def IsModified(self) -> bool: ... + def OnChangedViewlist(self) -> None: ... + def OnCloseDocument(self) -> None: ... + def OnNewDocument(self) -> None: ... + def OnOpenDocument(self, pathName: str, /) -> None: ... + def OnSaveDocument(self, pathName: str, /) -> None: ... + def SetModifiedFlag(self, bModified: int = ..., /) -> None: ... + def SaveModified(self): ... + def SetPathName(self, path: str, /) -> None: ... + def SetTitle(self, title: str, /) -> None: ... + def UpdateAllViews(self, sender: PyCView, hint: Incomplete | None = ..., /) -> None: ... + +class PyCEdit: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Clear(self): ... + def Copy(self) -> None: ... + def Cut(self) -> None: ... + def FmtLines(self, bAddEOL, /): ... + def GetFirstVisibleLine(self): ... + def GetSel(self) -> tuple[Incomplete, Incomplete]: ... + def GetLine(self, lineNo, /): ... + def GetLineCount(self): ... + def LimitText(self, nChars: int = ..., /) -> None: ... + def LineFromChar(self, charNo: int = ..., /): ... + def LineIndex(self, lineNo: int = ..., /): ... + def LineScroll(self, nLines, nChars: int = ..., /): ... + def Paste(self) -> None: ... + def ReplaceSel(self, text: str, /) -> None: ... + def SetReadOnly(self, bReadOnly: int = ..., /) -> None: ... + def SetSel(self, start, end, arg, bNoScroll1, bNoScroll: int = ..., /) -> None: ... + +class PyCEditView: + def IsModified(self) -> bool: ... + def LoadFile(self, fileName: str, /) -> None: ... + def SetModifiedFlag(self, bModified: int = ..., /) -> None: ... + def GetEditCtrl(self): ... + def PreCreateWindow(self, createStruct, /): ... + def SaveFile(self, fileName: str, /) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCFileDialog: + def GetPathName(self) -> str: ... + def GetFileName(self) -> str: ... + def GetFileExt(self) -> str: ... + def GetFileTitle(self) -> str: ... + def GetPathNames(self) -> str: ... + def GetReadOnlyPref(self): ... + def SetOFNTitle(self, title: str, /) -> None: ... + def SetOFNInitialDir(self, title: str, /) -> None: ... + +class PyCFont: + def GetSafeHandle(self): ... + +class PyCFontDialog: + def DoModal(self): ... + def GetCurrentFont(self): ... + def GetCharFormat(self): ... + def GetColor(self): ... + def GetFaceName(self) -> str: ... + def GetStyleName(self) -> str: ... + def GetSize(self): ... + def GetWeight(self): ... + def IsStrikeOut(self) -> bool: ... + def IsUnderline(self) -> bool: ... + def IsBold(self) -> bool: ... + def IsItalic(self) -> bool: ... + +class PyCFormView: + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCFrameWnd: + def BeginModalState(self) -> None: ... + def CreateWindow( + self, + wndClass: str, + title: str, + style, + PyCWnd, + menuId, + styleEx, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., + createContext: Incomplete | None = ..., + /, + ): ... + def EndModalState(self) -> None: ... + def DockControlBar( + self, controlBar: PyCControlBar, arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], dockBarId: int = ..., / + ) -> None: ... + def EnableDocking(self, style, /) -> None: ... + def FloatControlBar(self, controlBar: PyCControlBar, arg: tuple[Incomplete, Incomplete], style, /) -> None: ... + def GetActiveDocument(self) -> PyCDocument: ... + def GetControlBar(self, _id, /) -> PyCControlBar: ... + def GetMessageString(self, _id, /) -> str: ... + def GetMessageBar(self) -> PyCWnd: ... + def IsTracking(self) -> bool: ... + def InModalState(self): ... + def LoadAccelTable(self, _id: PyResourceId, /) -> None: ... + def LoadFrame( + self, idResource, style: int = ..., wndParent: PyCWnd | None = ..., context: Incomplete | None = ..., / + ) -> None: ... + def LoadBarState(self, profileName: str, /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def SaveBarState(self, profileName: str, /) -> None: ... + def ShowControlBar(self, controlBar: PyCControlBar, bShow, bDelay, /) -> None: ... + def RecalcLayout(self, bNotify: int = ..., /) -> None: ... + def GetActiveView(self) -> PyCView: ... + def OnBarCheck(self, _id, /): ... + def OnUpdateControlBarMenu(self, cmdUI: PyCCmdUI, /): ... + def SetActiveView(self, view: PyCView, bNotify: int = ..., /) -> None: ... + +class PyCGdiObject: ... + +class PyCImagelist: + def Add(self, arg: tuple[Incomplete, Incomplete], bitmap, color, hIcon, /): ... + def Destroy(self) -> None: ... + def DeleteImagelist(self) -> None: ... + def GetBkColor(self): ... + def GetSafeHandle(self): ... + def GetImageCount(self): ... + def GetImageInfo(self, index, /): ... + def SetBkColor(self, color, /) -> None: ... + +class PyClistBox: + def AddString(self, _object, /): ... + def DeleteString(self, pos, /): ... + def Dir(self, attr, wild: str, /): ... + def GetCaretIndex(self): ... + def GetCount(self): ... + def GetCurSel(self): ... + def GetItemData(self, item, /): ... + def GetItemValue(self, item, /): ... + def GetSel(self, index, /): ... + def GetSelCount(self): ... + def GetSelItems(self): ... + def GetSelTextItems(self): ... + def GetTopIndex(self): ... + def GetText(self, index, /) -> str: ... + def GetTextLen(self, index, /): ... + def InsertString(self, pos, _object, /): ... + def ResetContent(self) -> None: ... + def SetCaretIndex(self, index, bScroll: int = ..., /) -> None: ... + def SelectString(self, after, string: str, /) -> None: ... + def SelItemRange(self, bSel, start, end, /) -> None: ... + def SetCurSel(self, index, /) -> None: ... + def SetItemData(self, item, Data, /): ... + def SetItemValue(self, item, data, /): ... + def SetSel(self, index, bSel: int = ..., /) -> None: ... + def SetTabStops(self, eachTabStop, tabStops, /) -> None: ... + def SetTopIndex(self, index, /) -> None: ... + +class PyClistCtrl: + def Arrange(self, code, /) -> None: ... + def CreateWindow(self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], PyCWnd, _id, /) -> None: ... + def DeleteAllItems(self) -> None: ... + def DeleteItem(self, item, /) -> None: ... + def GetTextColor(self): ... + def SetTextColor(self, color, /) -> None: ... + def GetBkColor(self): ... + def SetBkColor(self, color, /) -> None: ... + def GetItem(self, item, sub, /) -> LV_ITEM: ... + def GetItemCount(self): ... + def GetItemRect(self, item, bTextOnly, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetEditControl(self) -> PyCEdit: ... + def EditLabel(self, item, /) -> PyCEdit: ... + def EnsureVisible(self, item, bPartialOK, /): ... + def CreateDragImage(self, item, /) -> tuple[PyCImagelist, Incomplete, Incomplete]: ... + def GetImagelist(self, nImagelist, /) -> PyCImagelist: ... + def GetNextItem(self, item, flags, /): ... + def InsertColumn(self, colNo, item: LV_COLUMN, /): ... + def InsertItem(self, item: LV_ITEM, item1, text, image, item2, text1, /): ... + def SetImagelist(self, imagelist: PyCImagelist, imageType, /): ... + def GetColumn(self, column, /) -> LV_COLUMN: ... + def GetTextBkColor(self): ... + def SetTextBkColor(self, color, /) -> None: ... + def GetTopIndex(self): ... + def GetCountPerPage(self): ... + def GetSelectedCount(self): ... + def SetItem(self, item: LV_ITEM, /): ... + def SetItemState(self, item, state, mask, /): ... + def GetItemState(self, item, mask, /): ... + def SetItemData(self, item, Data, /): ... + def GetItemData(self, item, /): ... + def SetItemCount(self, count, /) -> None: ... + def SetItemText(self, item, sub, text: str, /): ... + def GetItemText(self, item, sub, /): ... + def RedrawItems(self, first, first1, /): ... + def Update(self, item, /) -> None: ... + def SetColumn(self, colNo, item: LV_COLUMN, /): ... + def DeleteColumn(self, first, /): ... + def GetColumnWidth(self, first, /): ... + def SetColumnWidth(self, first, first1, /): ... + def GetStringWidth(self, first, /): ... + def HitTest(self, arg, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetItemPosition(self, item, /) -> tuple[Incomplete, Incomplete]: ... + +class PyClistView: + def PreCreateWindow(self, createStruct, /): ... + def GetlistCtrl(self) -> PyClistCtrl: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCMDIChildWnd: + def ActivateFrame(self, cmdShow: int = ..., /) -> None: ... + def CreateWindow( + self, + wndClass: str, + title: str, + style, + PyCWnd, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., + createContext: Incomplete | None = ..., + /, + ): ... + def GetMDIFrame(self) -> None: ... + def MDIActivate(self, cmdShow: int = ..., /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def PreTranslateMessage(self) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def OnClose(self) -> None: ... + +class PyCMDIFrameWnd: + def GetMDIClient(self) -> PyCMDIFrameWnd: ... + def MDIGetActive(self) -> tuple[PyCMDIChildWnd, Incomplete]: ... + def MDIActivate(self, window: PyCWnd, /) -> PyCMDIFrameWnd: ... + def MDINext(self, fNext: int = ..., /) -> None: ... + def PreCreateWindow(self, createStruct, /): ... + def PreTranslateMessage(self) -> None: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def OnContextHelp(self): ... + def OnClose(self) -> None: ... + +class PyCMenu: + def AppendMenu(self, flags, _id: int = ..., value: str | None = ..., /) -> None: ... + def DeleteMenu(self, _id, flags, /) -> str: ... + def EnableMenuItem(self, _id, flags, /): ... + def GetMenuItemCount(self): ... + def GetMenuItemID(self, pos, /): ... + def GetMenuString(self, _id, arg, /) -> str: ... + def GetSubMenu(self, pos, /) -> PyCMenu: ... + def InsertMenu(self, pos, flags, _id: PyCMenu | int = ..., value: str | None = ..., /) -> None: ... + def ModifyMenu(self, pos, flags, _id: int = ..., value: str | None = ..., /) -> None: ... + def TrackPopupMenu(self, x_y: _TwoIntSequence, flags: int = ..., owner: PyCWnd = ..., /) -> None: ... + +class PyCOleClientItem: + def CreateNewItem(self) -> None: ... + def Close(self) -> None: ... + def DoVerb(self) -> None: ... + def Draw(self) -> None: ... + def GetActiveView(self) -> PyCView: ... + def GetDocument(self) -> PyCDocument: ... + def GetInPlaceWindow(self) -> PyCWnd: ... + def GetItemState(self) -> None: ... + def GetObject(self) -> PyIUnknown: ... + def GetStorage(self) -> None: ... + def OnActivate(self) -> None: ... + def OnChange(self) -> None: ... + def OnChangeItemPosition(self): ... + def OnDeactivateUI(self): ... + def Run(self) -> None: ... + def SetItemRects(self) -> None: ... + +class PyCOleDialog: ... + +class PyCOleDocument: + def EnableCompoundFile(self, bEnable: int = ..., /) -> None: ... + def GetStartPosition(self): ... + def GetNextItem(self, pos, /) -> tuple[Incomplete, PyCOleClientItem]: ... + def GetInPlaceActiveItem(self, wnd: PyCWnd, /) -> PyCOleClientItem: ... + +class PyCOleInsertDialog: + def GetClassID(self): ... + def GetSelectionType(self): ... + def GetPathName(self): ... + +class PyCPrintDialog: ... + +class PyCPrintInfo: + def DocObject(self) -> None: ... + def GetDwFlags(self) -> None: ... + def SetDwFlags(self) -> None: ... + def GetDocOffsetPage(self) -> None: ... + def SetDocOffsetPage(self) -> None: ... + def SetPrintDialog(self) -> None: ... + def GetDirect(self) -> None: ... + def SetDirect(self) -> None: ... + def GetPreview(self) -> None: ... + def SetPreview(self) -> None: ... + def GetContinuePrinting(self) -> None: ... + def SetContinuePrinting(self) -> None: ... + def GetCurPage(self) -> None: ... + def SetCurPage(self) -> None: ... + def GetNumPreviewPages(self) -> None: ... + def SetNumPreviewPages(self) -> None: ... + def GetUserData(self) -> None: ... + def SetUserData(self) -> None: ... + def GetDraw(self) -> None: ... + def SetDraw(self) -> None: ... + def GetPageDesc(self) -> None: ... + def SetPageDesc(self) -> None: ... + def GetMinPage(self) -> None: ... + def SetMinPage(self) -> None: ... + def GetMaxPage(self) -> None: ... + def SetMaxPage(self) -> None: ... + def GetOffsetPage(self) -> None: ... + def GetFromPage(self) -> None: ... + def GetToPage(self) -> None: ... + def SetHDC(self, hdc, /) -> None: ... + def CreatePrinterDC(self) -> None: ... + def DoModal(self) -> None: ... + def GetCopies(self) -> None: ... + def GetDefaults(self) -> None: ... + def FreeDefaults(self) -> None: ... + def GetDeviceName(self) -> None: ... + def GetDriverName(self) -> None: ... + def GetDlgFromPage(self) -> None: ... + def GetDlgToPage(self) -> None: ... + def GetPortName(self) -> None: ... + def GetPrinterDC(self) -> None: ... + def PrintAll(self) -> None: ... + def PrintCollate(self) -> None: ... + def PrintRange(self) -> None: ... + def PrintSelection(self) -> None: ... + def GetHDC(self) -> None: ... + def GetFlags(self) -> None: ... + def SetFlags(self) -> None: ... + def SetFromPage(self) -> None: ... + def SetToPage(self) -> None: ... + def GetPRINTDLGMinPage(self) -> None: ... + def SetPRINTDLGMinPage(self) -> None: ... + def GetPRINTDLGCopies(self) -> None: ... + def SetPRINTDLGCopies(self) -> None: ... + +class PyCProgressCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def SetRange(self, nLower: int = ..., nUpper: int = ..., /) -> None: ... + def SetPos(self, nPos: int = ..., /): ... + def OffsetPos(self, nPos: int = ..., /): ... + def SetStep(self, nStep: int = ..., /): ... + def StepIt(self): ... + +class PyCPropertyPage: + def CancelToClose(self) -> None: ... + def OnCancel(self) -> None: ... + def OnOK(self) -> None: ... + def OnApply(self) -> None: ... + def OnReset(self) -> None: ... + def OnQueryCancel(self) -> None: ... + def OnWizardBack(self) -> None: ... + def OnWizardNext(self) -> None: ... + def OnWizardFinish(self) -> None: ... + def OnSetActive(self): ... + def OnKillActive(self): ... + def SetModified(self, bChanged: int = ..., /) -> None: ... + def SetPSPBit(self, bitMask, bitValue, /) -> None: ... + +class PyCPropertySheet: + def AddPage(self, page: PyCPropertyPage, /) -> None: ... + def CreateWindow(self, style, exStyle, parent: PyCWnd | None = ..., /) -> None: ... + def DoModal(self): ... + def EnableStackedTabs(self, stacked, /) -> PyCPropertyPage: ... + def EndDialog(self, result, /) -> None: ... + def GetActiveIndex(self): ... + def GetActivePage(self) -> PyCPropertyPage: ... + def GetPage(self, pageNo, /) -> PyCPropertyPage: ... + def GetPageIndex(self, page: PyCPropertyPage, /): ... + def GetPageCount(self): ... + def GetTabCtrl(self) -> PyCTabCtrl: ... + def OnInitDialog(self): ... + def PressButton(self, button, /) -> None: ... + def RemovePage(self, offset, page, /) -> None: ... + def SetActivePage(self, page: PyCPropertyPage, /) -> None: ... + def SetTitle(self, title: str, /) -> None: ... + def SetFinishText(self, text: str, /) -> None: ... + def SetWizardMode(self) -> None: ... + def SetWizardButtons(self, flags, /) -> None: ... + def SetPSHBit(self, bitMask, bitValue, /) -> None: ... + +class PyCRect: ... +class PyCRgn: ... + +class PyCRichEditCtrl: + def Clear(self): ... + def Copy(self) -> None: ... + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Cut(self) -> None: ... + def FindText(self, charPos, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetCharPos(self, charPos, /): ... + def GetDefaultCharFormat(self): ... + def GetEventMask(self): ... + def GetSelectionCharFormat(self): ... + def GetFirstVisibleLine(self): ... + def GetParaFormat(self): ... + def GetSel(self) -> tuple[Incomplete, Incomplete]: ... + def GetSelText(self) -> str: ... + def GetTextLength(self): ... + def GetLine(self, lineNo, /): ... + def GetModify(self): ... + def GetLineCount(self): ... + def LimitText(self, nChars: int = ..., /) -> None: ... + def LineFromChar(self, charNo: int = ..., /): ... + def LineIndex(self, lineNo: int = ..., /): ... + def LineScroll(self, nLines, nChars: int = ..., /): ... + def Paste(self) -> None: ... + def ReplaceSel(self, text: str, /) -> None: ... + def SetBackgroundColor(self, bSysColor, cr: int = ..., /): ... + def SetDefaultCharFormat(self, charFormat, /) -> None: ... + def SetEventMask(self, eventMask, /): ... + def SetSelectionCharFormat(self, charFormat, /) -> None: ... + def SetModify(self, modified: int = ..., /) -> None: ... + def SetOptions(self, op, flags, /) -> None: ... + def SetParaFormat(self, paraFormat, /): ... + def SetReadOnly(self, bReadOnly: int = ..., /) -> None: ... + def SetSel(self, start, end, arg, /) -> None: ... + def SetSelAndCharFormat(self, charFormat, /) -> None: ... + def SetTargetDevice(self, dc: PyCDC, lineWidth, /) -> None: ... + def StreamIn(self, _format, method, /) -> tuple[Incomplete, Incomplete]: ... + def StreamOut(self, _format, method, /) -> tuple[Incomplete, Incomplete]: ... + +class PyCRichEditDoc: + def OnCloseDocument(self) -> None: ... + +class PyCRichEditDocTemplate: + def DoCreateRichEditDoc(self, fileName: str | None = ..., /) -> PyCRichEditDoc: ... + +class PyCRichEditView: + def GetRichEditCtrl(self) -> PyCRichEditCtrl: ... + def SetWordWrap(self, wordWrap, /): ... + def WrapChanged(self): ... + def SaveTextFile(self, FileName, /): ... + +class PyCScrollView: + def GetDeviceScrollPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetDC(self) -> PyCDC: ... + def GetScrollPosition(self) -> tuple[Incomplete, Incomplete]: ... + def GetTotalSize(self) -> tuple[Incomplete, Incomplete]: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + def ResizeParentToFit(self, bShrinkOnly: int = ..., /): ... + def SetScaleToFitSize(self, size: tuple[Incomplete, Incomplete], /) -> None: ... + def ScrollToPosition(self, position: tuple[Incomplete, Incomplete], /) -> None: ... + def SetScrollSizes( + self, + mapMode, + sizeTotal: tuple[Incomplete, Incomplete], + arg: tuple[Incomplete, Incomplete], + arg1: tuple[Incomplete, Incomplete], + /, + ) -> None: ... + def UpdateBars(self) -> None: ... + +class PyCSliderCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetLineSize(self): ... + def SetLineSize(self, nLineSize: int = ..., /): ... + def GetPageSize(self): ... + def SetPageSize(self, nPageSize: int = ..., /): ... + def GetRangeMax(self): ... + def GetRangeMin(self): ... + def GetRange(self): ... + def SetRange(self, nRangeMin: int = ..., nRangeMax: int = ..., bRedraw: int = ..., /): ... + def GetSelection(self): ... + def SetSelection(self, nRangeMin: int = ..., nRangeMax: int = ..., /): ... + def GetChannelRect(self): ... + def GetThumbRect(self): ... + def GetPos(self): ... + def SetPos(self, nPos: int = ..., /): ... + def GetNumTics(self): ... + def GetTicArray(self): ... + def GetTic(self, nTic: int = ..., /): ... + def GetTicPos(self, nTic: int = ..., /): ... + def SetTic(self, nTic: int = ..., /): ... + def SetTicFreq(self, nFreq: int = ..., /): ... + def ClearSel(self, bRedraw: int = ..., /): ... + def VerifyPos(self): ... + def ClearTics(self, bRedraw: int = ..., /): ... + +class PyCSpinButtonCtrl: + def GetPos(self): ... + def SetPos(self, pos, /): ... + def SetRange(self): ... + def SetRange32(self): ... + +class PyCSplitterWnd: # aka PyCSplitter + def GetPane(self, row, col, /) -> PyCWnd: ... + def CreateView(self, view: PyCView, row, col, arg: tuple[Incomplete, Incomplete], /) -> None: ... + def CreateStatic(self, parent: PyCSplitterWnd, rows, cols, style=..., _id=..., /) -> None: ... + def SetColumnInfo(self, column, ideal, _min, /) -> None: ... + def SetRowInfo(self, row, ideal, _min, /) -> None: ... + def IdFromRowCol(self, row, col, /) -> None: ... + def DoKeyboardSplit(self): ... + +class PyCStatusBar: + def GetPaneInfo(self, index, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetStatusBarCtrl(self) -> PyCStatusBarCtrl: ... + def SetIndicators(self, indicators, /) -> None: ... + def SetPaneInfo(self, index, _id, style, width, /) -> None: ... + +class PyCStatusBarCtrl: + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def GetBorders(self) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def GetParts(self, nParts, /): ... + def GetRect(self, nPane, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetText(self, nPane, /): ... + def GetTextAttr(self, nPane, /): ... + def GetTextLength(self, nPane, /): ... + def SetMinHeight(self, nHeight, /) -> None: ... + def SetParts(self, coord, /) -> None: ... + def SetText(self, text: str, nPane, nType, /) -> None: ... + def SetTipText(self, nPane, text: str, /) -> None: ... + +class PyCTabCtrl: + def GetCurSel(self): ... + def GetItemCountl(self): ... + def SetCurSel(self, index, /): ... + +class PyCToolBar: + def GetButtonStyle(self, index, /) -> None: ... + def GetButtonText(self, index, /) -> str: ... + def GetItemID(self, index, /) -> None: ... + def SetButtonInfo(self, index, ID, style, imageIx, /) -> None: ... + def GetToolBarCtrl(self) -> PyCToolBarCtrl: ... + def LoadBitmap(self, _id: PyResourceId, /) -> None: ... + def LoadToolBar(self, _id: PyResourceId, /) -> None: ... + def SetBarStyle(self, style, /) -> None: ... + def SetBitmap(self, hBitmap, /) -> None: ... + def SetButtons(self, buttons, numButtons, /) -> None: ... + def SetButtonStyle(self, index, style, /) -> None: ... + def SetHeight(self, height, /) -> None: ... + def SetSizes(self, sizeButton: tuple[Incomplete, Incomplete], sizeButton1: tuple[Incomplete, Incomplete], /) -> None: ... + +class PyCToolBarCtrl: + def AddBitmap(self, numButtons, bitmap, /): ... + def AddButtons(self): ... + def AddStrings(self, strings, /): ... + def AutoSize(self) -> None: ... + def CheckButton(self, nID, bCheck: int = ..., /): ... + def CommandToIndex(self, nID, /): ... + def CreateWindow( + self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], parent: PyCWnd, _id, / + ) -> None: ... + def Customize(self) -> None: ... + def DeleteButton(self, nID, /) -> None: ... + def EnableButton(self, nID, bEnable: int = ..., /) -> None: ... + def GetBitmapFlags(self): ... + def GetButton(self, nID, /): ... + def GetButtonCount(self): ... + def GetItemRect(self, nID, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetRows(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def HideButton(self, nID, bEnable: int = ..., /) -> None: ... + def Indeterminate(self, nID, bEnable: int = ..., /) -> None: ... + def InsertButton(self, nID, button: PyCToolBarCtrl, /): ... + def IsButtonChecked(self, nID, /) -> bool: ... + def IsButtonEnabled(self, nID, /) -> bool: ... + def IsButtonHidden(self, nID, /) -> bool: ... + def IsButtonIndeterminate(self, nID, /) -> bool: ... + def IsButtonPressed(self, nID, /) -> bool: ... + def PressButton(self, nID, bEnable: int = ..., /) -> None: ... + def SetBitmapSize(self, width1, height1, width: int = ..., height: int = ..., /) -> None: ... + def SetButtonSize(self, width1, height1, width: int = ..., height: int = ..., /) -> None: ... + def SetCmdID(self, nIndex, nID, /) -> None: ... + def SetRows(self, nRows, bLarger, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + +class PyCToolTipCtrl: + def CreateWindow(self, parent: PyCWnd, style, /) -> None: ... + def UpdateTipText(self, text: str, wnd: PyCWnd, _id, /) -> None: ... + def AddTool( + self, wnd: PyCWnd, text: str, _id, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., / + ) -> None: ... + def SetMaxTipWidth(self, width, /): ... + +class PyCTreeCtrl: + def CreateWindow(self, style, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], PyCWnd, _id, /) -> None: ... + def GetCount(self): ... + def GetIndent(self): ... + def SetIndent(self, indent, /) -> None: ... + def GetImagelist(self, nImagelist, /) -> PyCImagelist: ... + def SetImagelist(self, imagelist: PyCImagelist, imageType, /): ... + def GetNextItem(self, item, code, /): ... + def ItemHasChildren(self, item, /): ... + def GetChildItem(self, item, /): ... + def GetNextSiblingItem(self, item, /): ... + def GetPrevSiblingItem(self, item, /): ... + def GetParentItem(self, item, /): ... + def GetFirstVisibleItem(self): ... + def GetNextVisibleItem(self, item, /): ... + def GetSelectedItem(self): ... + def GetDropHilightItem(self): ... + def GetRootItem(self): ... + def GetToolTips(self): ... + def GetItem(self, item, arg, /) -> TV_ITEM: ... + def SetItem(self, item: TV_ITEM, /): ... + def GetItemState(self, item, stateMask, /) -> tuple[Incomplete, Incomplete]: ... + def SetItemState(self, item, state, stateMask, /) -> None: ... + def GetItemImage(self, item, /) -> tuple[Incomplete, Incomplete]: ... + def SetItemImage(self, item, iImage, iSelectedImage, /) -> None: ... + def SetItemText(self, item, text: str, /): ... + def GetItemText(self, item, /): ... + def GetItemData(self, item, /): ... + def SetItemData(self, item, Data, /): ... + def GetItemRect(self, item, bTextOnly, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetEditControl(self) -> PyCEdit: ... + def GetVisibleCount(self): ... + def InsertItem( + self, + hParent, + hInsertAfter, + item: TV_ITEM, + mask, + text, + image, + selectedImage, + state, + stateMask, + lParam, + parent, + parent1, + text1, + image1, + selectedImage1, + parent2, + insertAfter, + text2, + parent3, + parent4, + /, + ): ... + def DeleteItem(self, item, /) -> None: ... + def DeleteAllItems(self): ... + def Expand(self, item, code, /) -> None: ... + def Select(self, item, code, /) -> None: ... + def SelectItem(self, item, /) -> None: ... + def SelectDropTarget(self, item, /) -> None: ... + def SelectSetFirstVisible(self, item, /) -> None: ... + def EditLabel(self, item, /) -> PyCEdit: ... + def CreateDragImage(self, item, /) -> PyCImagelist: ... + def SortChildren(self, item, /) -> None: ... + def EnsureVisible(self, item, /): ... + def HitTest(self, arg, /) -> tuple[Incomplete, Incomplete]: ... + +class PyCTreeView: + def PreCreateWindow(self, createStruct, /): ... + def GetTreeCtrl(self) -> PyCTreeCtrl: ... + def OnCommand(self, wparam, lparam, /) -> None: ... + +class PyCView: + def CreateWindow(self, parent: PyCWnd, arg, arg1, arg2: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... + def GetDocument(self) -> PyCDocument: ... + def OnActivateView(self, activate, activateView: PyCView, DeactivateView: PyCView, /): ... + def OnInitialUpdate(self) -> None: ... + def OnMouseActivate(self, wnd: PyCWnd, hittest, message, /): ... + def PreCreateWindow(self, createStruct, /): ... + def OnFilePrint(self) -> None: ... + def DoPreparePrinting(self): ... + def OnBeginPrinting(self) -> None: ... + def OnEndPrinting(self) -> None: ... + +class PyCWinApp: + def AddDocTemplate(self, template: PyCDocTemplate | DocTemplate, /) -> None: ... + def FindOpenDocument(self, fileName: str, /) -> PyCDocument: ... + def GetDocTemplatelist(self) -> list[Incomplete]: ... + def InitDlgInstance(self, dialog: PyCDialog, /) -> None: ... + def LoadCursor(self, cursorId: PyResourceId, /): ... + def LoadStandardCursor(self, cursorId: PyResourceId, /): ... + def LoadOEMCursor(self, cursorId, /): ... + def LoadIcon(self, idResource: int, /) -> int: ... + def LoadStandardIcon(self, resourceName: PyResourceId, /): ... + def OpenDocumentFile(self, fileName: str, /) -> PyCDocument | None: ... + def OnFileNew(self) -> None: ... + def OnFileOpen(self) -> None: ... + def RemoveDocTemplate(self, template: PyCDocTemplate | DocTemplate, /) -> None: ... + def Run(self): ... + def IsInproc(self) -> bool: ... + +class PyCWinThread: + def CreateThread(self) -> None: ... + def PumpIdle(self) -> None: ... + def PumpMessages(self) -> None: ... + def Run(self): ... + def SetMainFrame(self, mainFrame: PyCWnd, /) -> None: ... + def SetThreadPriority(self, priority: PyCWnd, /) -> None: ... + +class PyCWnd: + def ActivateFrame(self, cmdShow, /) -> None: ... + def BringWindowToTop(self) -> None: ... + def BeginPaint(self) -> tuple[PyCDC, Incomplete]: ... + def CalcWindowRect( + self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], nAdjustType, / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def CenterWindow(self, altwin: PyCWnd | None = ..., /) -> None: ... + def CheckRadioButton(self, idFirst, idLast, idCheck, /) -> None: ... + def ChildWindowFromPoint(self, x, y, flag: int = ..., /) -> PyCWnd: ... + def ClientToScreen( + self, point: tuple[Incomplete, Incomplete], rect, / + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... + def CreateWindow( + self, + classId: str, + windowName: str, + style, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + parent: PyCWnd, + _id, + context: Incomplete | None = ..., + /, + ) -> None: ... + def CreateWindowEx( + self, + styleEx, + classId: str, + windowName: str, + style, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + parent: PyCWnd, + _id, + createStruct1, + createStruct: CREATESTRUCT | None = ..., + /, + ) -> None: ... + def DefWindowProc(self, message, idLast, idCheck, /): ... + def DestroyWindow(self) -> None: ... + def DlgDirlist(self, defPath: str, idlistbox, idStaticPath, fileType, /) -> None: ... + def DlgDirlistComboBox(self) -> None: ... + def DlgDirSelect(self, idlistbox, /) -> str: ... + def DlgDirSelectComboBox(self, idlistbox, /) -> str: ... + def DragAcceptFiles(self, bAccept: int = ..., /) -> None: ... + def DrawMenuBar(self) -> None: ... + def EnableWindow(self, bEnable: int = ..., /): ... + def EndModalLoop(self, result, /) -> None: ... + def EndPaint(self, paintStruct, /) -> None: ... + def GetCheckedRadioButton(self, idFirst, idLast, /): ... + def GetClientRect(self) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + def GetDC(self) -> PyCDC: ... + def GetDCEx(self) -> PyCDC: ... + def GetDlgCtrlID(self): ... + def GetDlgItem(self, idControl, /) -> PyCWnd: ... + def GetDlgItemInt(self, idControl, bUnsigned: int = ..., /): ... + def GetDlgItemText(self, idControl, /) -> str: ... + def GetLastActivePopup(self) -> PyCWnd: ... + def GetMenu(self) -> PyCMenu: ... + def GetParent(self) -> PyCWnd: ... + def GetParentFrame(self) -> PyCWnd: ... + def GetSafeHwnd(self): ... + def GetScrollInfo(self, nBar, mask, /): ... + def GetScrollPos(self, nBar, /): ... + def GetStyle(self): ... + def GetExStyle(self): ... + def GetSystemMenu(self) -> PyCMenu: ... + def GetTopLevelFrame(self) -> PyCWnd: ... + def GetTopLevelOwner(self) -> PyCWnd: ... + def GetTopLevelParent(self) -> PyCWnd: ... + def GetTopWindow(self) -> PyCWnd: ... + def GetWindow(self, _type, /) -> PyCWnd: ... + def GetWindowDC(self) -> PyCDC: ... + def GetWindowPlacement(self): ... + def GetWindowRect(self) -> tuple[int, int, int, int]: ... + def GetWindowText(self) -> str: ... + def HideCaret(self) -> None: ... + def HookAllKeyStrokes(self, obHandler, /) -> None: ... + def HookKeyStroke(self, obHandler, ch, /): ... + def HookMessage(self, obHandler, message, /): ... + def InvalidateRect(self, arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], bErase: int = ..., /) -> None: ... + def InvalidateRgn(self, region: PyCRgn, bErase: int = ..., /) -> None: ... + def IsChild(self, obWnd: PyCWnd, /) -> bool: ... + def IsDlgButtonChecked(self, idCtl, /) -> bool: ... + def IsIconic(self) -> bool: ... + def IsZoomed(self) -> bool: ... + def IsWindow(self) -> bool: ... + def IsWindowVisible(self) -> bool: ... + def KillTimer(self): ... + def LockWindowUpdate(self) -> None: ... + def MapWindowPoints(self, wnd: PyCWnd, points: list[tuple[Incomplete, Incomplete]], /) -> None: ... + def MouseCaptured(self): ... + def MessageBox(self, message: str, arg, title: str | None = ..., /) -> None: ... + def ModifyStyle(self, remove, add, flags: int = ..., /): ... + def ModifyStyleEx(self, remove, add, flags: int = ..., /): ... + def MoveWindow(self, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], bRepaint: int = ..., /) -> None: ... + def OnClose(self): ... + def OnCtlColor(self, dc: PyCDC, control, _type, /): ... + def OnEraseBkgnd(self, dc: PyCDC, /): ... + def OnNcHitTest(self, arg: tuple[Incomplete, Incomplete], /): ... + def OnPaint(self): ... + def OnQueryDragIcon(self): ... + def OnQueryNewPalette(self): ... + def OnSetCursor(self, wnd: PyCWnd, hittest, message, /): ... + def OnMouseActivate(self, wnd: PyCWnd, hittest, message, /): ... + def OnWndMsg(self, msg, wParam, lParam, /) -> tuple[Incomplete, Incomplete]: ... + def PreCreateWindow(self, createStruct, /): ... + def PumpWaitingMessages(self, firstMsg, lastMsg, /) -> None: ... + def RedrawWindow( + self, _object: PyCRgn, flags, rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None = ..., / + ) -> None: ... + def ReleaseCapture(self) -> None: ... + def ReleaseDC(self, dc: PyCDC, /) -> None: ... + def RepositionBars(self, idFirst, idLast, idLeftOver, /) -> None: ... + def RunModalLoop(self, flags, /): ... + def PostMessage(self, idMessage, wParam: int = ..., lParam: int = ..., /) -> None: ... + def SendMessageToDescendants(self, idMessage, wParam: int = ..., lParam: int = ..., bDeep: int = ..., /) -> None: ... + def SendMessage(self, idMessage, wParam: int = ..., lParam: int = ..., /) -> None: ... + def SetActiveWindow(self) -> PyCWnd: ... + def SetForegroundWindow(self) -> None: ... + def SetWindowPos( + self, hWndInsertAfter, position: tuple[Incomplete, Incomplete, Incomplete, Incomplete], flags, / + ) -> None: ... + + @overload + def ScreenToClient(self, rect: tuple[int, int], /) -> tuple[int, int]: ... + @overload + def ScreenToClient(self, rect: tuple[int, int, int, int], /) -> tuple[int, int, int, int]: ... + @overload + def ScreenToClient(self, rect: _TwoIntSequence | _FourIntSequence, /) -> tuple[int, int] | tuple[int, int, int, int]: ... + + def SetCapture(self) -> None: ... + def SetDlgItemText(self, idControl, text: str, /) -> None: ... + def SetFocus(self) -> None: ... + def SetFont(self, font: PyCFont, bRedraw: int = ..., /) -> None: ... + def SetIcon(self): ... + def SetMenu(self, menuObj: PyCMenu, /) -> None: ... + def SetRedraw(self, bState: int = ..., /) -> None: ... + def SetScrollPos(self, nBar, nPos, redraw: int = ..., /): ... + def SetScrollInfo(self, nBar, ScrollInfo, redraw: int = ..., /): ... + def SetTimer(self, idEvent, elapse, /): ... + def SetWindowPlacement(self, placement, /) -> None: ... + def SetWindowText(self, text: str, /) -> None: ... + def ShowCaret(self) -> None: ... + def ShowScrollBar(self, nBar, bShow: int = ..., /) -> None: ... + def ShowWindow(self, arg, /): ... + def UnLockWindowUpdate(self) -> None: ... + def UpdateData(self, bSaveAndValidate: int = ..., /): ... + def UpdateDialogControls(self, pTarget: PyCCmdTarget, disableIfNoHandler, /): ... + def UpdateWindow(self) -> None: ... + +class PyDDEConv: + def ConnectTo(self, service: str, topic: str, /) -> None: ... + def Connected(self) -> None: ... + def Exec(self, Cmd: str, /) -> None: ... + def Request(self) -> None: ... + def Poke(self) -> None: ... + +class PyDDEServer: + def AddTopic(self, topic: PyDDETopic, /) -> None: ... + def Create(self, name: str, filterFlags: int = ..., /) -> None: ... + def Destroy(self) -> None: ... + def GetLastError(self): ... + def Shutdown(self) -> None: ... + +class PyDDEStringItem: + def SetData(self, data: str, /) -> None: ... + +class PyDDETopic: + def AddItem(self, item, /) -> None: ... + def Destroy(self) -> None: ... + +class PyDLL: + def GetFileName(self) -> str: ... + def AttachToMFC(self) -> None: ... + +class SCROLLINFO: ... +class TV_ITEM: ... + +class EXTENSION_CONTROL_BLOCK: + @property + def Version(self) -> int: ... + @property + def TotalBytes(self): ... + @property + def AvailableBytes(self): ... + @property + def HttpStatusCode(self): ... + @property + def Method(self): ... + @property + def ConnID(self): ... + @property + def QueryString(self): ... + @property + def PathInfo(self): ... + @property + def PathTranslated(self): ... + @property + def AvailableData(self): ... + @property + def ContentType(self): ... + @property + def LogData(self): ... + def WriteClient(self, data: str, reserved: int = ..., /): ... + def GetServerVariable(self, variable: str, default, /) -> str: ... + def ReadClient(self, nbytes, /) -> str: ... + def SendResponseHeaders(self, reply: str, headers: str, keepAlive: bool = ..., /) -> None: ... + def SetFlushFlag(self, flag, /) -> None: ... + def TransmitFile(self, callback, param, hFile, statusCode: str, BytesToWrite, Offset, head: str, tail: str, flags, /): ... + def MapURLToPath(self) -> None: ... + def DoneWithSession(self, status, /) -> None: ... + def Redirect(self, url: str, /) -> None: ... + def IsKeepAlive(self) -> bool: ... + def GetAnonymousToken(self, metabase_path: str, /): ... + def GetImpersonationToken(self): ... + def IsKeepConn(self) -> bool: ... + def ExecURL(self, url: str, method: str, clientHeaders: str, info, entity, flags, /): ... + def GetExecURLStatus(self): ... + def IOCompletion(self, func, arg: Incomplete | None = ..., /): ... + def ReportUnhealthy(self, reason: str | None = ..., /): ... + def IOCallback(self, ecb: EXTENSION_CONTROL_BLOCK, arg, cbIO, dwError, /): ... + +class HSE_VERSION_INFO: + @property + def ExtensionDesc(self) -> str: ... + +class HTTP_FILTER_AUTHENT: + @property + def User(self) -> str: ... + @property + def Password(self) -> str: ... + +class HTTP_FILTER_CONTEXT: + @property + def Revision(self): ... + @property + def fIsSecurePort(self): ... + @property + def NotificationType(self): ... + @property + def FilterContext(self): ... + def GetData(self): ... + def GetServerVariable(self, variable: str, default, /) -> str: ... + def WriteClient(self, data: str, reserverd: int = ..., /) -> None: ... + def AddResponseHeaders(self, data: str, reserverd: int = ..., /) -> None: ... + def SendResponseHeader(self, status: str, header: str, /) -> None: ... + def DisableNotifications(self, flags, /) -> None: ... + +class HTTP_FILTER_LOG: + @property + def ClientHostName(self) -> str: ... + @property + def ClientUserName(self) -> str: ... + @property + def ServerName(self) -> str: ... + @property + def Operation(self) -> str: ... + @property + def Target(self) -> str: ... + @property + def Parameters(self) -> str: ... + @property + def HttpStatus(self): ... + +class HTTP_FILTER_PREPROC_HEADERS: + def GetHeader(self, header: str, default, /) -> str: ... + def SetHeader(self, name: str, val: str, /) -> None: ... + def AddHeader(self) -> None: ... + +class HTTP_FILTER_RAW_DATA: + @property + def InData(self) -> str: ... + +class HTTP_FILTER_URL_MAP: + @property + def URL(self) -> str: ... + @property + def PhysicalPath(self) -> str: ... + +class HTTP_FILTER_VERSION: + @property + def ServerFilterVersion(self): ... + @property + def FilterVersion(self): ... + @property + def Flags(self): ... + @property + def FilterDesc(self) -> str: ... + +class PySYSTEM_CPU_SET_INFORMATION: + Id: int + Group: int + LogicalProcessorIndex: int + CoreIndex: int + LastLevelCacheIndex: int + NumaNodeIndex: int + EfficiencyClass: int + SchedulingClass: int + AllocationTag: int diff --git a/stubs/pywin32/commctrl.pyi b/stubs/pywin32/commctrl.pyi new file mode 100644 index 000000000000..603c5703aff7 --- /dev/null +++ b/stubs/pywin32/commctrl.pyi @@ -0,0 +1 @@ +from win32.lib.commctrl import * diff --git a/stubs/pywin32/dde.pyi b/stubs/pywin32/dde.pyi new file mode 100644 index 000000000000..90a5be0f0c7f --- /dev/null +++ b/stubs/pywin32/dde.pyi @@ -0,0 +1 @@ +from pythonwin.dde import * diff --git a/stubs/pywin32/isapi/__init__.pyi b/stubs/pywin32/isapi/__init__.pyi new file mode 100644 index 000000000000..107d2b2c9e26 --- /dev/null +++ b/stubs/pywin32/isapi/__init__.pyi @@ -0,0 +1,9 @@ +class ISAPIError(Exception): + errno: int + strerror: str | None + funcname: str | None + def __init__(self, errno: int, strerror: str | None = None, funcname: str | None = None) -> None: ... + +class FilterError(ISAPIError): ... +class ExtensionError(ISAPIError): ... +class InternalReloadException(Exception): ... diff --git a/stubs/pywin32/isapi/install.pyi b/stubs/pywin32/isapi/install.pyi new file mode 100644 index 000000000000..ae3a54a2402f --- /dev/null +++ b/stubs/pywin32/isapi/install.pyi @@ -0,0 +1,101 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsGetItem, Unused +from collections.abc import Callable, Iterable, Mapping +from optparse import OptionParser +from typing import Final, Literal + +this_dir: str + +class FilterParameters: + Name: Incomplete + Description: Incomplete + Path: Incomplete + Server: Incomplete + AddExtensionFile: bool + AddExtensionFile_Enabled: bool + AddExtensionFile_GroupID: Incomplete + AddExtensionFile_CanDelete: bool + AddExtensionFile_Description: Incomplete + def __init__(self, **kw) -> None: ... + +class VirtualDirParameters: + Name: Incomplete + Description: Incomplete + AppProtection: Incomplete + Headers: Incomplete + Path: Incomplete + Type: Incomplete + AccessExecute: Incomplete + AccessRead: Incomplete + AccessWrite: Incomplete + AccessScript: Incomplete + ContentIndexed: Incomplete + EnableDirBrowsing: Incomplete + EnableDefaultDoc: Incomplete + DefaultDoc: Incomplete + ScriptMaps: list[ScriptMapParams] + ScriptMapUpdate: str + Server: Incomplete + def __init__(self, **kw) -> None: ... + def is_root(self) -> bool: ... + def split_path(self) -> list[str]: ... + +class ScriptMapParams: + Extension: Incomplete + Module: Incomplete + Flags: int + Verbs: str + AddExtensionFile: bool + AddExtensionFile_Enabled: bool + AddExtensionFile_GroupID: Incomplete + AddExtensionFile_CanDelete: bool + AddExtensionFile_Description: Incomplete + def __init__(self, **kw) -> None: ... + +class ISAPIParameters: + ServerName: Incomplete + Filters: list[FilterParameters] + VirtualDirs: list[VirtualDirParameters] + def __init__(self, **kw) -> None: ... + +verbose: int + +def log(level: int, what: object) -> None: ... + +class InstallationError(Exception): ... +class ItemNotFound(InstallationError): ... +class ConfigurationError(InstallationError): ... + +def FindPath(options, server: str | bytes | bytearray, name: str) -> str: ... +def LocateWebServerPath(description: str): ... +def GetWebServer(description: str | None = None): ... +def LoadWebServer(path): ... +def FindWebServer(options, server_desc: str | bytes | bytearray | None) -> str: ... +def split_path(path: str) -> list[str]: ... +def CreateDirectory(params, options): ... +def AssignScriptMaps(script_maps: Iterable[ScriptMapParams], target, update: str = "replace") -> None: ... +def get_unique_items(sequence, reference): ... +def CreateISAPIFilter(filterParams, options): ... +def DeleteISAPIFilter(filterParams, options) -> None: ... +def AddExtensionFiles(params, options) -> None: ... +def DeleteExtensionFileRecords(params, options) -> None: ... +def CheckLoaderModule(dll_name: StrOrBytesPath) -> None: ... +def Install(params, options) -> None: ... +def RemoveDirectory(params, options) -> None: ... +def RemoveScriptMaps(vd_params, options) -> None: ... +def Uninstall(params, options) -> None: ... +def GetLoaderModuleName(mod_name: StrPath, check_module: bool | None = None) -> str: ... +def InstallModule(conf_module_name: StrPath, params, options, log: Callable[[int, str], Unused] = ...) -> None: ... +def UninstallModule(conf_module_name: StrPath, params, options, log: Callable[[int, str], Unused] = ...) -> None: ... + +standard_arguments: Final[dict[Literal["install", "remove"], Callable[..., Incomplete]]] + +def build_usage(handler_map: Mapping[str, object]) -> str: ... +def MergeStandardOptions(options, params) -> None: ... +def HandleCommandLine( + params, + argv: SupportsGetItem[int, str] | None = None, + conf_module_name: str | None = None, + default_arg: str = "install", + opt_parser: OptionParser | None = None, + custom_arg_handlers: Mapping[str, object] = {}, +) -> None: ... diff --git a/stubs/pywin32/isapi/isapicon.pyi b/stubs/pywin32/isapi/isapicon.pyi new file mode 100644 index 000000000000..33ee18759595 --- /dev/null +++ b/stubs/pywin32/isapi/isapicon.pyi @@ -0,0 +1,86 @@ +from typing import Final + +HTTP_CONTINUE: Final = 100 +HTTP_SWITCHING_PROTOCOLS: Final = 101 +HTTP_PROCESSING: Final = 102 +HTTP_OK: Final = 200 +HTTP_CREATED: Final = 201 +HTTP_ACCEPTED: Final = 202 +HTTP_NON_AUTHORITATIVE: Final = 203 +HTTP_NO_CONTENT: Final = 204 +HTTP_RESET_CONTENT: Final = 205 +HTTP_PARTIAL_CONTENT: Final = 206 +HTTP_MULTI_STATUS: Final = 207 +HTTP_MULTIPLE_CHOICES: Final = 300 +HTTP_MOVED_PERMANENTLY: Final = 301 +HTTP_MOVED_TEMPORARILY: Final = 302 +HTTP_SEE_OTHER: Final = 303 +HTTP_NOT_MODIFIED: Final = 304 +HTTP_USE_PROXY: Final = 305 +HTTP_TEMPORARY_REDIRECT: Final = 307 +HTTP_BAD_REQUEST: Final = 400 +HTTP_UNAUTHORIZED: Final = 401 +HTTP_PAYMENT_REQUIRED: Final = 402 +HTTP_FORBIDDEN: Final = 403 +HTTP_NOT_FOUND: Final = 404 +HTTP_METHOD_NOT_ALLOWED: Final = 405 +HTTP_NOT_ACCEPTABLE: Final = 406 +HTTP_PROXY_AUTHENTICATION_REQUIRED: Final = 407 +HTTP_REQUEST_TIME_OUT: Final = 408 +HTTP_CONFLICT: Final = 409 +HTTP_GONE: Final = 410 +HTTP_LENGTH_REQUIRED: Final = 411 +HTTP_PRECONDITION_FAILED: Final = 412 +HTTP_REQUEST_ENTITY_TOO_LARGE: Final = 413 +HTTP_REQUEST_URI_TOO_LARGE: Final = 414 +HTTP_UNSUPPORTED_MEDIA_TYPE: Final = 415 +HTTP_RANGE_NOT_SATISFIABLE: Final = 416 +HTTP_EXPECTATION_FAILED: Final = 417 +HTTP_UNPROCESSABLE_ENTITY: Final = 422 +HTTP_INTERNAL_SERVER_ERROR: Final = 500 +HTTP_NOT_IMPLEMENTED: Final = 501 +HTTP_BAD_GATEWAY: Final = 502 +HTTP_SERVICE_UNAVAILABLE: Final = 503 +HTTP_GATEWAY_TIME_OUT: Final = 504 +HTTP_VERSION_NOT_SUPPORTED: Final = 505 +HTTP_VARIANT_ALSO_VARIES: Final = 506 +HSE_STATUS_SUCCESS: Final = 1 +HSE_STATUS_SUCCESS_AND_KEEP_CONN: Final = 2 +HSE_STATUS_PENDING: Final = 3 +HSE_STATUS_ERROR: Final = 4 +SF_NOTIFY_SECURE_PORT: Final = 0x00000001 +SF_NOTIFY_NONSECURE_PORT: Final = 0x00000002 +SF_NOTIFY_READ_RAW_DATA: Final = 0x00008000 +SF_NOTIFY_PREPROC_HEADERS: Final = 0x00004000 +SF_NOTIFY_AUTHENTICATION: Final = 0x00002000 +SF_NOTIFY_URL_MAP: Final = 0x00001000 +SF_NOTIFY_ACCESS_DENIED: Final = 0x00000800 +SF_NOTIFY_SEND_RESPONSE: Final = 0x00000040 +SF_NOTIFY_SEND_RAW_DATA: Final = 0x00000400 +SF_NOTIFY_LOG: Final = 0x00000200 +SF_NOTIFY_END_OF_REQUEST: Final = 0x00000080 +SF_NOTIFY_END_OF_NET_SESSION: Final = 0x00000100 +SF_NOTIFY_ORDER_HIGH: Final = 0x00080000 +SF_NOTIFY_ORDER_MEDIUM: Final = 0x00040000 +SF_NOTIFY_ORDER_LOW: Final = 0x00020000 +SF_NOTIFY_ORDER_DEFAULT: Final = SF_NOTIFY_ORDER_LOW +SF_NOTIFY_ORDER_MASK: Final = 917504 +SF_STATUS_REQ_FINISHED: Final = 134217728 +SF_STATUS_REQ_FINISHED_KEEP_CONN: Final = 134217729 +SF_STATUS_REQ_NEXT_NOTIFICATION: Final = 134217730 +SF_STATUS_REQ_HANDLED_NOTIFICATION: Final = 134217731 +SF_STATUS_REQ_ERROR: Final = 134217732 +SF_STATUS_REQ_READ_NEXT: Final = 134217733 +HSE_IO_SYNC: Final = 0x00000001 +HSE_IO_ASYNC: Final = 0x00000002 +HSE_IO_DISCONNECT_AFTER_SEND: Final = 0x00000004 +HSE_IO_SEND_HEADERS: Final = 0x00000008 +HSE_IO_NODELAY: Final = 0x00001000 +HSE_IO_FINAL_SEND: Final = 0x00000010 +HSE_IO_CACHE_RESPONSE: Final = 0x00000020 +HSE_EXEC_URL_NO_HEADERS: Final = 0x02 +HSE_EXEC_URL_IGNORE_CURRENT_INTERCEPTOR: Final = 0x04 +HSE_EXEC_URL_IGNORE_VALIDATION_AND_RANGE: Final = 0x10 +HSE_EXEC_URL_DISABLE_CUSTOM_ERROR: Final = 0x20 +HSE_EXEC_URL_SSI_CMD: Final = 0x40 +HSE_EXEC_URL_HTTP_CACHE_ELIGIBLE: Final = 0x80 diff --git a/stubs/pywin32/isapi/simple.pyi b/stubs/pywin32/isapi/simple.pyi new file mode 100644 index 000000000000..5d913c510d35 --- /dev/null +++ b/stubs/pywin32/isapi/simple.pyi @@ -0,0 +1,10 @@ +class SimpleExtension: + def GetExtensionVersion(self, vi) -> None: ... + def HttpExtensionProc(self, control_block) -> int | None: ... + def TerminateExtension(self, status) -> None: ... + +class SimpleFilter: + filter_flags: int | None + def GetFilterVersion(self, fv) -> None: ... + def HttpFilterProc(self, fc) -> None: ... + def TerminateFilter(self, status) -> None: ... diff --git a/stubs/pywin32/isapi/threaded_extension.pyi b/stubs/pywin32/isapi/threaded_extension.pyi new file mode 100644 index 000000000000..ead5c5ddcb1e --- /dev/null +++ b/stubs/pywin32/isapi/threaded_extension.pyi @@ -0,0 +1,29 @@ +import threading +from _typeshed import Unused +from collections.abc import Callable +from typing import Final + +import isapi.simple + +ISAPI_REQUEST: Final = 1 +ISAPI_SHUTDOWN: Final = 2 + +class WorkerThread(threading.Thread): + running: bool + io_req_port: int + extension: ThreadPoolExtension + def __init__(self, extension: ThreadPoolExtension, io_req_port: int) -> None: ... + def call_handler(self, cblock) -> None: ... + +class ThreadPoolExtension(isapi.simple.SimpleExtension): + max_workers: int + worker_shutdown_wait: int + workers: list[WorkerThread] + dispatch_map: dict[int, Callable[..., Unused]] + io_req_port: int + def GetExtensionVersion(self, vi) -> None: ... + def HttpExtensionProc(self, control_block) -> int: ... + def TerminateExtension(self, status) -> None: ... + def DispatchConnection(self, errCode, bytes, key, overlapped) -> None: ... + def Dispatch(self, ecb) -> None: ... + def HandleDispatchError(self, ecb) -> None: ... diff --git a/stubs/pywin32/mmapfile.pyi b/stubs/pywin32/mmapfile.pyi new file mode 100644 index 000000000000..0b18e7600318 --- /dev/null +++ b/stubs/pywin32/mmapfile.pyi @@ -0,0 +1 @@ +from win32.mmapfile import * diff --git a/stubs/pywin32/mmsystem.pyi b/stubs/pywin32/mmsystem.pyi new file mode 100644 index 000000000000..600475d287e2 --- /dev/null +++ b/stubs/pywin32/mmsystem.pyi @@ -0,0 +1 @@ +from win32.lib.mmsystem import * diff --git a/stubs/pywin32/ntsecuritycon.pyi b/stubs/pywin32/ntsecuritycon.pyi new file mode 100644 index 000000000000..0b23754827e0 --- /dev/null +++ b/stubs/pywin32/ntsecuritycon.pyi @@ -0,0 +1 @@ +from win32.lib.ntsecuritycon import * diff --git a/stubs/pywin32/odbc.pyi b/stubs/pywin32/odbc.pyi new file mode 100644 index 000000000000..4671d862c439 --- /dev/null +++ b/stubs/pywin32/odbc.pyi @@ -0,0 +1 @@ +from win32.odbc import * diff --git a/stubs/pywin32/perfmon.pyi b/stubs/pywin32/perfmon.pyi new file mode 100644 index 000000000000..eae890e08fbe --- /dev/null +++ b/stubs/pywin32/perfmon.pyi @@ -0,0 +1 @@ +from win32.perfmon import * diff --git a/stubs/pywin32/pythoncom.pyi b/stubs/pywin32/pythoncom.pyi new file mode 100644 index 000000000000..83404871ff7a --- /dev/null +++ b/stubs/pywin32/pythoncom.pyi @@ -0,0 +1,500 @@ +from _typeshed import Incomplete, Unused +from abc import abstractmethod +from collections.abc import Sequence +from typing import ClassVar, SupportsInt, TypeAlias, overload +from typing_extensions import deprecated, disjoint_base + +import _win32typing +from win32.lib.pywintypes import TimeType, com_error as com_error + +error: TypeAlias = com_error # noqa: Y042 + +class internal_error(Exception): ... + +@disjoint_base +class com_record: + @abstractmethod + def __init__(self, /, *args, **kwargs) -> None: ... + TLBID: ClassVar[str] + MJVER: ClassVar[int] + MNVER: ClassVar[int] + LCID: ClassVar[int] + GUID: ClassVar[str] + +def CoCreateFreeThreadedMarshaler(unk: _win32typing.PyIUnknown, /) -> _win32typing.PyIUnknown: ... +def CoCreateInstanceEx( + clsid: _win32typing.PyIID, + unkOuter: _win32typing.PyIUnknown, + context, + serverInfo: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + iids: list[_win32typing.PyIID], + /, +) -> _win32typing.PyIUnknown: ... +def CoCreateInstance( + clsid: _win32typing.PyIID, unkOuter: _win32typing.PyIUnknown | None, context: int, iid: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def CoFreeUnusedLibraries() -> None: ... +def CoInitialize() -> None: ... +def CoInitializeEx(flags, /) -> None: ... +def CoInitializeSecurity( + sd: _win32typing.PySECURITY_DESCRIPTOR, authSvc, reserved1, authnLevel, impLevel, authInfo, capabilities, reserved2, / +) -> None: ... +def CoGetInterfaceAndReleaseStream(stream: _win32typing.PyIStream, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def CoMarshalInterThreadInterfaceInStream(iid: _win32typing.PyIID, unk: _win32typing.PyIUnknown, /) -> _win32typing.PyIStream: ... +def CoMarshalInterface( + Stm: _win32typing.PyIStream, riid: _win32typing.PyIID, Unk: _win32typing.PyIUnknown, DestContext, flags, / +) -> None: ... +def CoUnmarshalInterface(Stm: _win32typing.PyIStream, riid: _win32typing.PyIID, /): ... +def CoReleaseMarshalData(Stm: _win32typing.PyIStream, /) -> None: ... +def CoGetObject(name: str, iid: _win32typing.PyIID, bindOpts: Incomplete | None = ..., /) -> _win32typing.PyIUnknown: ... +def CoUninitialize() -> None: ... +def CoRegisterClassObject(iid: _win32typing.PyIID, factory: _win32typing.PyIUnknown, context, flags, /) -> int: ... +def CoResumeClassObjects() -> None: ... +def CoRevokeClassObject(reg: int, /) -> None: ... +def CoTreatAsClass(clsidold: _win32typing.PyIID, clsidnew: _win32typing.PyIID, /) -> None: ... +def CoWaitForMultipleHandles(Flags, Timeout, Handles: list[int], /): ... +def Connect(cls, /) -> _win32typing.PyIDispatch: ... +def connect(cls, /) -> _win32typing.PyIDispatch: ... +def CreateGuid() -> _win32typing.PyIID: ... +def CreateBindCtx() -> _win32typing.PyIBindCtx: ... +def CreateFileMoniker(filename: str, /) -> _win32typing.PyIMoniker: ... +def CreateItemMoniker(delim: str, item: str, /) -> _win32typing.PyIMoniker: ... +def CreatePointerMoniker(IUnknown: _win32typing.PyIUnknown, /) -> _win32typing.PyIMoniker: ... +def CreateURLMonikerEx(Context, URL, Flags: int = ..., /): ... +def CreateTypeLib(): ... +def CreateTypeLib2(): ... +def CreateStreamOnHGlobal(hGlobal: int | None = ..., DeleteOnRelease: bool = ..., /) -> _win32typing.PyIStream: ... +def CreateILockBytesOnHGlobal(hGlobal: int | None = ..., DeleteOnRelease: bool = ..., /) -> _win32typing.PyILockBytes: ... +def EnableQuitMessage(threadId, /) -> None: ... +def FUNCDESC() -> _win32typing.FUNCDESC: ... +def GetActiveObject(cls, /) -> _win32typing.PyIUnknown: ... +def GetClassFile(fileName, /) -> _win32typing.PyIID: ... +def GetFacilityString(scode, /) -> str: ... +def GetRecordFromGuids( + iid: str | _win32typing.PyIID, + verMajor: int, + verMinor: int, + lcid: int, + infoIID: str | _win32typing.PyIID, + data: Incomplete | None = ..., + /, +): ... +def GetRecordFromTypeInfo(TypeInfo: _win32typing.PyITypeInfo, /): ... +def GetRunningObjectTable(reserved: int = ..., /) -> _win32typing.PyIRunningObjectTable: ... +def GetScodeString(scode, /) -> str: ... +def GetScodeRangeString(scode, /) -> str: ... +def GetSeverityString(scode, /) -> str: ... +def IsGatewayRegistered(iid: _win32typing.PyIID | None, /) -> int: ... +def LoadRegTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, /) -> _win32typing.PyITypeLib: ... +def LoadTypeLib(libFileName: str, /) -> _win32typing.PyITypeLib: ... +def MakePyFactory(iid: _win32typing.PyIID, /) -> _win32typing.PyIClassFactory: ... +@deprecated("Use pywintypes.IID() instead.") +def MakeIID(iidString: str, is_bytes: bool = ..., /) -> _win32typing.PyIID: ... +@deprecated("Use pywintypes.Time() instead.") +def MakeTime(timeRepr: SupportsInt | Sequence[SupportsInt] | TimeType, /) -> TimeType: ... +def MkParseDisplayName( + displayName: str, bindCtx: _win32typing.PyIBindCtx | None = ..., / +) -> tuple[_win32typing.PyIMoniker, Incomplete, _win32typing.PyIBindCtx]: ... +def new(iid: _win32typing.PyIID | str, /): ... +def New(cls, /) -> _win32typing.PyIDispatch: ... +def ObjectFromAddress(address, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def ObjectFromLresult(lresult, iid: _win32typing.PyIID, wparm, /) -> _win32typing.PyIUnknown: ... +def OleInitialize() -> None: ... +def OleGetClipboard() -> _win32typing.PyIDataObject: ... +def OleFlushClipboard() -> None: ... +def OleIsCurrentClipboard(dataObj: _win32typing.PyIDataObject, /): ... +def OleSetClipboard(dataObj: _win32typing.PyIDataObject, /) -> None: ... +def OleLoadFromStream(stream: _win32typing.PyIStream, iid: _win32typing.PyIID, /) -> None: ... +def OleSaveToStream(persist: _win32typing.PyIPersistStream, stream: _win32typing.PyIStream, /) -> None: ... +def OleLoad(storage: _win32typing.PyIStorage, iid: _win32typing.PyIID, site: _win32typing.PyIOleClientSite, /) -> None: ... +def ProgIDFromCLSID(clsid, /) -> str: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def PumpMessages() -> None: ... +def QueryPathOfRegTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, /) -> str: ... +def ReadClassStg(storage: _win32typing.PyIStorage, /) -> _win32typing.PyIID: ... +def ReadClassStm(Stm: _win32typing.PyIStream, /) -> _win32typing.PyIID: ... +def RegisterTypeLib(typelib: _win32typing.PyITypeLib, fullPath: str, lcid, helpDir: str | None = ..., /) -> None: ... +def UnRegisterTypeLib(iid: _win32typing.PyIID, versionMajor, versionMinor, lcid, syskind, /) -> str: ... +def RegisterActiveObject(obUnknown: _win32typing.PyIUnknown, clsid: _win32typing.PyIID, flags, /): ... +def RevokeActiveObject(handle, /) -> None: ... +def RegisterDragDrop(hwnd: int, dropTarget: _win32typing.PyIDropTarget, /) -> None: ... +def RevokeDragDrop(hwnd: int, /) -> None: ... +def DoDragDrop() -> None: ... +def StgCreateDocfile(name: str | None, mode: int, reserved: int = ..., /) -> _win32typing.PyIStorage: ... +def StgCreateDocfileOnILockBytes(lockBytes: _win32typing.PyILockBytes, mode, reserved=..., /) -> _win32typing.PyIStorage: ... +def StgOpenStorageOnILockBytes( + lockBytes: _win32typing.PyILockBytes, + stgPriority: _win32typing.PyIStorage, + mode, + snbExclude: Incomplete | None = ..., + reserved: int = ..., + /, +) -> _win32typing.PyIStorage: ... +def StgIsStorageFile(name: str, /): ... +def STGMEDIUM() -> _win32typing.PySTGMEDIUM: ... + +@overload +def StgOpenStorage( + name: str | None, other: _win32typing.PyIStorage, mode: int, snbExclude: Unused = ..., reserved: int = ..., / +) -> _win32typing.PyIStorage: ... +@overload +def StgOpenStorage( + name: str, other: _win32typing.PyIStorage | None, mode: int, snbExclude: Unused = ..., reserved: int = ..., / +) -> _win32typing.PyIStorage: ... + +def StgOpenStorageEx( + Name: str, Mode: int, stgfmt: int, Attrs: int, riid: _win32typing.PyIID, StgOptions: Incomplete | None = ... +) -> _win32typing.PyIStorage: ... +def StgCreateStorageEx( + Name: str, + Mode: int, + stgfmt: int, + Attrs: int, + riid: _win32typing.PyIID, + StgOptions: Incomplete | None = ..., + SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR | None = ..., +) -> _win32typing.PyIStorage: ... +def TYPEATTR() -> _win32typing.TYPEATTR: ... +def VARDESC() -> _win32typing.VARDESC: ... +def WrapObject(ob, gatewayIID: _win32typing.PyIID, interfaceIID: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def WriteClassStg(storage: _win32typing.PyIStorage, iid: _win32typing.PyIID, /) -> None: ... +def WriteClassStm(Stm: _win32typing.PyIStream, clsid: _win32typing.PyIID, /) -> None: ... +def UnwrapObject(ob: _win32typing.PyIUnknown, /) -> _win32typing.PyIDispatch: ... +def FmtIdToPropStgName(fmtid: _win32typing.PyIID, /): ... +def PropStgNameToFmtId(Name: str, /) -> _win32typing.PyIID: ... +def CoGetCallContext(riid: _win32typing.PyIID, /) -> _win32typing.PyIServerSecurity: ... +def CoGetObjectContext(riid: _win32typing.PyIID, /) -> _win32typing.PyIContext: ... +def CoGetCancelObject(riid: _win32typing.PyIID, ThreadID: int = ..., /) -> _win32typing.PyICancelMethodCalls: ... +def CoSetCancelObject(Unk: _win32typing.PyIUnknown, /) -> None: ... +def CoEnableCallCancellation() -> None: ... +def CoDisableCallCancellation() -> None: ... + +ACTIVEOBJECT_STRONG: int +ACTIVEOBJECT_WEAK: int +ArgNotFound: _win32typing.ArgNotFound +CLSCTX_ALL: int +CLSCTX_INPROC: int +CLSCTX_INPROC_HANDLER: int +CLSCTX_INPROC_SERVER: int +CLSCTX_LOCAL_SERVER: int +CLSCTX_REMOTE_SERVER: int +CLSCTX_SERVER: int +CLSID_DCOMAccessControl: _win32typing.PyIID +CLSID_StdComponentCategoriesMgr: _win32typing.PyIID +CLSID_StdGlobalInterfaceTable: _win32typing.PyIID +COINIT_APARTMENTTHREADED: int +COINIT_DISABLE_OLE1DDE: int +COINIT_MULTITHREADED: int +COINIT_SPEED_OVER_MEMORY: int +COWAIT_ALERTABLE: int +COWAIT_WAITALL: int +DATADIR_GET: int +DATADIR_SET: int +DESCKIND_FUNCDESC: int +DESCKIND_VARDESC: int +DISPATCH_METHOD: int +DISPATCH_PROPERTYGET: int +DISPATCH_PROPERTYPUT: int +DISPATCH_PROPERTYPUTREF: int +DISPID_COLLECT: int +DISPID_CONSTRUCTOR: int +DISPID_DESTRUCTOR: int +DISPID_EVALUATE: int +DISPID_NEWENUM: int +DISPID_PROPERTYPUT: int +DISPID_STARTENUM: int +DISPID_THIS: int +DISPID_UNKNOWN: int +DISPID_VALUE: int +DVASPECT_CONTENT: int +DVASPECT_DOCPRINT: int +DVASPECT_ICON: int +DVASPECT_THUMBNAIL: int +EOAC_ACCESS_CONTROL: int +EOAC_ANY_AUTHORITY: int +EOAC_APPID: int +EOAC_AUTO_IMPERSONATE: int +EOAC_DEFAULT: int +EOAC_DISABLE_AAA: int +EOAC_DYNAMIC: int +EOAC_DYNAMIC_CLOAKING: int +EOAC_MAKE_FULLSIC: int +EOAC_MUTUAL_AUTH: int +EOAC_NONE: int +EOAC_NO_CUSTOM_MARSHAL: int +EOAC_REQUIRE_FULLSIC: int +EOAC_SECURE_REFS: int +EOAC_STATIC_CLOAKING: int +EXTCONN_CALLABLE: int +EXTCONN_STRONG: int +EXTCONN_WEAK: int +Empty: _win32typing.PyOleEmpty +FMTID_DocSummaryInformation: _win32typing.PyIID +FMTID_SummaryInformation: _win32typing.PyIID +FMTID_UserDefinedProperties: _win32typing.PyIID +FUNCFLAG_FBINDABLE: int +FUNCFLAG_FDEFAULTBIND: int +FUNCFLAG_FDISPLAYBIND: int +FUNCFLAG_FHIDDEN: int +FUNCFLAG_FREQUESTEDIT: int +FUNCFLAG_FRESTRICTED: int +FUNCFLAG_FSOURCE: int +FUNCFLAG_FUSESGETLASTERROR: int +FUNC_DISPATCH: int +FUNC_NONVIRTUAL: int +FUNC_PUREVIRTUAL: int +FUNC_STATIC: int +FUNC_VIRTUAL: int +IDLFLAG_FIN: int +IDLFLAG_FLCID: int +IDLFLAG_FOUT: int +IDLFLAG_FRETVAL: int +IDLFLAG_NONE: int +IID_IBindCtx: _win32typing.PyIID +IID_ICancelMethodCalls: _win32typing.PyIID +IID_ICatInformation: _win32typing.PyIID +IID_ICatRegister: _win32typing.PyIID +IID_IClassFactory: _win32typing.PyIID +IID_IClientSecurity: _win32typing.PyIID +IID_IConnectionPoint: _win32typing.PyIID +IID_IConnectionPointContainer: _win32typing.PyIID +IID_IContext: _win32typing.PyIID +IID_ICreateTypeInfo: _win32typing.PyIID +IID_ICreateTypeLib: _win32typing.PyIID +IID_ICreateTypeLib2: _win32typing.PyIID +IID_IDataObject: _win32typing.PyIID +IID_IDispatch: _win32typing.PyIID +IID_IDispatchEx: _win32typing.PyIID +IID_IDropSource: _win32typing.PyIID +IID_IDropTarget: _win32typing.PyIID +IID_IEnumCATEGORYINFO: _win32typing.PyIID +IID_IEnumConnectionPoints: _win32typing.PyIID +IID_IEnumConnections: _win32typing.PyIID +IID_IEnumContextProps: _win32typing.PyIID +IID_IEnumFORMATETC: _win32typing.PyIID +IID_IEnumGUID: _win32typing.PyIID +IID_IEnumMoniker: _win32typing.PyIID +IID_IEnumSTATPROPSETSTG: _win32typing.PyIID +IID_IEnumSTATPROPSTG: _win32typing.PyIID +IID_IEnumSTATSTG: _win32typing.PyIID +IID_IEnumString: _win32typing.PyIID +IID_IEnumVARIANT: _win32typing.PyIID +IID_IErrorLog: _win32typing.PyIID +IID_IExternalConnection: _win32typing.PyIID +IID_IGlobalInterfaceTable: _win32typing.PyIID +IID_ILockBytes: _win32typing.PyIID +IID_IMarshal: _win32typing.PyIID +IID_IMoniker: _win32typing.PyIID +IID_IOleWindow: _win32typing.PyIID +IID_IPersist: _win32typing.PyIID +IID_IPersistFile: _win32typing.PyIID +IID_IPersistPropertyBag: _win32typing.PyIID +IID_IPersistStorage: _win32typing.PyIID +IID_IPersistStream: _win32typing.PyIID +IID_IPersistStreamInit: _win32typing.PyIID +IID_IPropertyBag: _win32typing.PyIID +IID_IPropertySetStorage: _win32typing.PyIID +IID_IPropertyStorage: _win32typing.PyIID +IID_IProvideClassInfo: _win32typing.PyIID +IID_IProvideClassInfo2: _win32typing.PyIID +IID_IRunningObjectTable: _win32typing.PyIID +IID_IServerSecurity: _win32typing.PyIID +IID_IServiceProvider: _win32typing.PyIID +IID_IStdMarshalInfo: _win32typing.PyIID +IID_IStorage: _win32typing.PyIID +IID_IStream: _win32typing.PyIID +IID_ITypeComp: _win32typing.PyIID +IID_ITypeInfo: _win32typing.PyIID +IID_ITypeLib: _win32typing.PyIID +IID_IUnknown: _win32typing.PyIID +IID_NULL: _win32typing.PyIID +IID_StdOle: _win32typing.PyIID +IMPLTYPEFLAG_FDEFAULT: int +IMPLTYPEFLAG_FRESTRICTED: int +IMPLTYPEFLAG_FSOURCE: int +INVOKE_FUNC: int +INVOKE_PROPERTYGET: int +INVOKE_PROPERTYPUT: int +INVOKE_PROPERTYPUTREF: int +InterfaceNames: dict[str, _win32typing.PyIID] +MKSYS_ANTIMONIKER: int +MKSYS_CLASSMONIKER: int +MKSYS_FILEMONIKER: int +MKSYS_GENERICCOMPOSITE: int +MKSYS_ITEMMONIKER: int +MKSYS_NONE: int +MKSYS_POINTERMONIKER: int +MSHCTX_DIFFERENTMACHINE: int +MSHCTX_INPROC: int +MSHCTX_LOCAL: int +MSHCTX_NOSHAREDMEM: int +MSHLFLAGS_NOPING: int +MSHLFLAGS_NORMAL: int +MSHLFLAGS_TABLESTRONG: int +MSHLFLAGS_TABLEWEAK: int +Missing: _win32typing.PyOleMissing +Nothing: _win32typing.PyOleNothing +PARAMFLAG_FHASDEFAULT: int +PARAMFLAG_FIN: int +PARAMFLAG_FLCID: int +PARAMFLAG_FOPT: int +PARAMFLAG_FOUT: int +PARAMFLAG_FRETVAL: int +PARAMFLAG_NONE: int +REGCLS_MULTIPLEUSE: int +REGCLS_MULTI_SEPARATE: int +REGCLS_SINGLEUSE: int +REGCLS_SUSPENDED: int +ROTFLAGS_ALLOWANYCLIENT: int +ROTFLAGS_REGISTRATIONKEEPSALIVE: int +RPC_C_AUTHN_DCE_PRIVATE: int +RPC_C_AUTHN_DCE_PUBLIC: int +RPC_C_AUTHN_DEC_PUBLIC: int +RPC_C_AUTHN_DEFAULT: int +RPC_C_AUTHN_DPA: int +RPC_C_AUTHN_GSS_KERBEROS: int +RPC_C_AUTHN_GSS_NEGOTIATE: int +RPC_C_AUTHN_GSS_SCHANNEL: int +RPC_C_AUTHN_LEVEL_CALL: int +RPC_C_AUTHN_LEVEL_CONNECT: int +RPC_C_AUTHN_LEVEL_DEFAULT: int +RPC_C_AUTHN_LEVEL_NONE: int +RPC_C_AUTHN_LEVEL_PKT: int +RPC_C_AUTHN_LEVEL_PKT_INTEGRITY: int +RPC_C_AUTHN_LEVEL_PKT_PRIVACY: int +RPC_C_AUTHN_MQ: int +RPC_C_AUTHN_MSN: int +RPC_C_AUTHN_NONE: int +RPC_C_AUTHN_WINNT: int +RPC_C_AUTHZ_DCE: int +RPC_C_AUTHZ_DEFAULT: int +RPC_C_AUTHZ_NAME: int +RPC_C_AUTHZ_NONE: int +RPC_C_IMP_LEVEL_ANONYMOUS: int +RPC_C_IMP_LEVEL_DEFAULT: int +RPC_C_IMP_LEVEL_DELEGATE: int +RPC_C_IMP_LEVEL_IDENTIFY: int +RPC_C_IMP_LEVEL_IMPERSONATE: int +STDOLE2_LCID: int +STDOLE2_MAJORVERNUM: int +STDOLE2_MINORVERNUM: int +STDOLE_LCID: int +STDOLE_MAJORVERNUM: int +STDOLE_MINORVERNUM: int +STREAM_SEEK_CUR: int +STREAM_SEEK_END: int +STREAM_SEEK_SET: int +SYS_MAC: int +SYS_WIN16: int +SYS_WIN32: int +ServerInterfaces: dict[_win32typing.PyIID, bytes] +TKIND_ALIAS: int +TKIND_COCLASS: int +TKIND_DISPATCH: int +TKIND_ENUM: int +TKIND_INTERFACE: int +TKIND_MODULE: int +TKIND_RECORD: int +TKIND_UNION: int +TYMED_ENHMF: int +TYMED_FILE: int +TYMED_GDI: int +TYMED_HGLOBAL: int +TYMED_ISTORAGE: int +TYMED_ISTREAM: int +TYMED_MFPICT: int +TYMED_NULL: int +TYPEFLAG_FAGGREGATABLE: int +TYPEFLAG_FAPPOBJECT: int +TYPEFLAG_FCANCREATE: int +TYPEFLAG_FCONTROL: int +TYPEFLAG_FDISPATCHABLE: int +TYPEFLAG_FDUAL: int +TYPEFLAG_FHIDDEN: int +TYPEFLAG_FLICENSED: int +TYPEFLAG_FNONEXTENSIBLE: int +TYPEFLAG_FOLEAUTOMATION: int +TYPEFLAG_FPREDECLID: int +TYPEFLAG_FREPLACEABLE: int +TYPEFLAG_FRESTRICTED: int +TYPEFLAG_FREVERSEBIND: int +RecordClasses: dict[str, com_record] +TypeIIDs: dict[_win32typing.PyIID, type] +URL_MK_LEGACY: int +URL_MK_UNIFORM: int +VARFLAG_FREADONLY: int +VAR_CONST: int +VAR_DISPATCH: int +VAR_PERINSTANCE: int +VAR_STATIC: int +VT_ARRAY: int +VT_BLOB: int +VT_BLOB_OBJECT: int +VT_BOOL: int +VT_BSTR: int +VT_BSTR_BLOB: int +VT_BYREF: int +VT_CARRAY: int +VT_CF: int +VT_CLSID: int +VT_CY: int +VT_DATE: int +VT_DECIMAL: int +VT_DISPATCH: int +VT_EMPTY: int +VT_ERROR: int +VT_FILETIME: int +VT_HRESULT: int +VT_I1: int +VT_I2: int +VT_I4: int +VT_I8: int +VT_ILLEGAL: int +VT_ILLEGALMASKED: int +VT_INT: int +VT_LPSTR: int +VT_LPWSTR: int +VT_NULL: int +VT_PTR: int +VT_R4: int +VT_R8: int +VT_RECORD: int +VT_RESERVED: int +VT_SAFEARRAY: int +VT_STORAGE: int +VT_STORED_OBJECT: int +VT_STREAM: int +VT_STREAMED_OBJECT: int +VT_TYPEMASK: int +VT_UI1: int +VT_UI2: int +VT_UI4: int +VT_UI8: int +VT_UINT: int +VT_UNKNOWN: int +VT_USERDEFINED: int +VT_VARIANT: int +VT_VECTOR: int +VT_VOID: int + +dcom: int +fdexNameCaseInsensitive: int +fdexNameCaseSensitive: int +fdexNameEnsure: int +fdexNameImplicit: int +fdexPropCanCall: int +fdexPropCanConstruct: int +fdexPropCanGet: int +fdexPropCanPut: int +fdexPropCanPutRef: int +fdexPropCanSourceEvents: int +fdexPropCannotCall: int +fdexPropCannotConstruct: int +fdexPropCannotGet: int +fdexPropCannotPut: int +fdexPropCannotPutRef: int +fdexPropCannotSourceEvents: int +fdexPropDynamicType: int +fdexPropNoSideEffects: int +# Deprecated: Use `getattr(sys, "frozen", False)` directly instead. +frozen: int diff --git a/stubs/pywin32/pythonwin/__init__.pyi b/stubs/pywin32/pythonwin/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/pythonwin/dde.pyi b/stubs/pywin32/pythonwin/dde.pyi new file mode 100644 index 000000000000..ed3e6d13e9f7 --- /dev/null +++ b/stubs/pywin32/pythonwin/dde.pyi @@ -0,0 +1,33 @@ +# Can't generate with stubgen because: +# "ImportError: This must be an MFC application - try 'import win32ui' first" +APPCLASS_MONITOR: int +APPCLASS_STANDARD: int +APPCMD_CLIENTONLY: int +APPCMD_FILTERINITS: int +CBF_FAIL_ADVISES: int +CBF_FAIL_ALLSVRXACTIONS: int +CBF_FAIL_CONNECTIONS: int +CBF_FAIL_EXECUTES: int +CBF_FAIL_POKES: int +CBF_FAIL_REQUESTS: int +CBF_FAIL_SELFCONNECTIONS: int +CBF_SKIP_ALLNOTIFICATIONS: int +CBF_SKIP_CONNECT_CONFIRMS: int +CBF_SKIP_DISCONNECTS: int +CBF_SKIP_REGISTRATIONS: int + +def CreateConversation(Server, /): ... +def CreateServer(): ... +def CreateServerSystemTopic(): ... +def CreateStringItem(name, /): ... +def CreateTopic(name, /): ... + +MF_CALLBACKS: int +MF_CONV: int +MF_ERRORS: int +MF_HSZ_INFO: int +MF_LINKS: int +MF_POSTMSGS: int +MF_SENDMSGS: int + +class error(Exception): ... diff --git a/stubs/pywin32/pythonwin/win32ui.pyi b/stubs/pywin32/pythonwin/win32ui.pyi new file mode 100644 index 000000000000..379cfbcbb7ce --- /dev/null +++ b/stubs/pywin32/pythonwin/win32ui.pyi @@ -0,0 +1,373 @@ +from _typeshed import Incomplete, OptExcInfo, Unused +from collections.abc import Callable + +import _win32typing + +class error(Exception): ... + +def ComparePath(path1: str, path2: str, /): ... +def CreateMDIFrame() -> _win32typing.PyCMDIFrameWnd: ... +def CreateMDIChild() -> _win32typing.PyCMDIChildWnd: ... +def CreateBitmap(*args: Unused) -> _win32typing.PyCBitmap: ... +def CreateBitmapFromHandle(): ... +def CreateBrush() -> _win32typing.PyCBrush: ... +def CreateButton() -> _win32typing.PyCButton: ... +def CreateColorDialog( + initColor: int = ..., flags: int = ..., parent: _win32typing.PyCWnd | None = ..., / +) -> _win32typing.PyCColorDialog: ... +def CreateControl( + classId: str, + windowName: str, + style, + rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], + parent: _win32typing.PyCWnd, + _id, + bStorage, + obPersist: Incomplete | None = ..., + licKey: str | None = ..., + /, +) -> _win32typing.PyCWnd: ... +def CreateControlBar() -> _win32typing.PyCControlBar: ... +def CreateCtrlView(doc: _win32typing.PyCDocument, className: str, style: int = ..., /) -> _win32typing.PyCCtrlView: ... +def CreateDC() -> None: ... +def CreateDCFromHandle(hwnd: int | _win32typing.PyHANDLE, /) -> _win32typing.PyCDC: ... +def CreateDialog(idRes, dll: _win32typing.PyDLL | None = ..., /) -> _win32typing.PyCDialog: ... +def CreateDialogBar() -> _win32typing.PyCDialogBar: ... +def CreateDialogIndirect(oblist, /) -> _win32typing.PyCDialog: ... +def CreatePrintDialog( + idRes, bPrintSetupOnly, dwFlags, parent: _win32typing.PyCWnd | None = ..., dll: _win32typing.PyDLL | None = ..., / +) -> _win32typing.PyCPrintDialog: ... +def CreateDocTemplate(idRes, /) -> _win32typing.PyCDocTemplate: ... +def CreateEdit() -> _win32typing.PyCEdit: ... +def CreateFileDialog( + bFileOpen, + arg, + defExt: str | None = ..., + fileName: str | None = ..., + _filter: str | None = ..., + parent: _win32typing.PyCWnd | None = ..., + /, +) -> _win32typing.PyCFileDialog: ... +def CreateFontDialog( + arg, font: Incomplete | None = ..., dcPrinter: _win32typing.PyCDC | None = ..., parent: _win32typing.PyCWnd | None = ..., / +) -> _win32typing.PyCFontDialog: ... +def CreateFormView(doc: _win32typing.PyCDocument, Template, /) -> _win32typing.PyCFormView: ... +def CreateFrame(): ... +def CreateTreeCtrl() -> _win32typing.PyCTreeCtrl: ... +def CreateTreeView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCTreeView: ... +def CreatePalette(lp, /): ... +def CreatePopupMenu() -> _win32typing.PyCMenu: ... +def CreateMenu() -> _win32typing.PyCMenu: ... +def CreatePen(style, width, color, /): ... +def CreateProgressCtrl() -> _win32typing.PyCProgressCtrl: ... +def CreatePropertyPage(resource: _win32typing.PyResourceId, caption: int = ..., /) -> _win32typing.PyCPropertyPage: ... +def CreatePropertyPageIndirect(resourcelist: _win32typing.PyDialogTemplate, caption=..., /) -> _win32typing.PyCPropertyPage: ... +def CreatePropertySheet( + caption: _win32typing.PyResourceId, parent: _win32typing.PyCWnd | None = ..., select=..., / +) -> _win32typing.PyCPropertySheet: ... +def CreateRgn() -> _win32typing.PyCRgn: ... +def CreateRichEditCtrl() -> _win32typing.PyCRichEditCtrl: ... +def CreateRichEditDocTemplate(idRes, /) -> _win32typing.PyCRichEditDocTemplate: ... +def CreateRichEditView(doc: _win32typing.PyCDocument | None = ..., /) -> _win32typing.PyCRichEditView: ... +def CreateSliderCtrl() -> _win32typing.PyCSliderCtrl: ... +def CreateSplitter() -> _win32typing.PyCSplitterWnd: ... +def CreateStatusBar( + parent: _win32typing.PyCWnd, style: int = ..., windowId: int = ..., ctrlStype: int = ..., / +) -> _win32typing.PyCStatusBar: ... +def CreateStatusBarCtrl() -> _win32typing.PyCStatusBarCtrl: ... +def CreateFont(properties, /) -> _win32typing.PyCFont: ... +def CreateToolBar(parent: _win32typing.PyCWnd, style: int, windowId: int = ..., /) -> _win32typing.PyCToolBar: ... +def CreateToolBarCtrl() -> _win32typing.PyCToolBarCtrl: ... +def CreateToolTipCtrl() -> _win32typing.PyCToolTipCtrl: ... +def CreateThread() -> _win32typing.PyCWinThread: ... +def CreateView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCScrollView: ... +def CreateEditView(doc: _win32typing.PyCDocument, /) -> _win32typing.PyCEditView: ... +def CreateDebuggerThread() -> None: ... +def CreateWindowFromHandle(hwnd: int, /) -> _win32typing.PyCWnd: ... +def CreateWnd() -> _win32typing.PyCWnd: ... +def DestroyDebuggerThread() -> None: ... +def DoWaitCursor(code, /) -> None: ... +def DisplayTraceback(exc_info: OptExcInfo, title: str, /) -> None: ... +def Enable3dControls(): ... +def FindWindow(className: str, windowName: str, /) -> _win32typing.PyCWnd: ... +def FindWindowEx( + parentWindow: _win32typing.PyCWnd, childAfter: _win32typing.PyCWnd, className: str, windowName: str, / +) -> _win32typing.PyCWnd: ... +def FullPath(path: str, /) -> str: ... +def GetActiveWindow() -> _win32typing.PyCWnd: ... +def GetApp() -> _win32typing.PyCWinApp: ... +def GetAppName(): ... +def GetAppRegistryKey() -> _win32typing.PyHKEY: ... +def GetBytes(address, size, /) -> str: ... +def GetCommandLine() -> str: ... +def GetDeviceCaps(hdc, index, /): ... +def GetFileTitle(fileName: str, /) -> str: ... +def GetFocus() -> _win32typing.PyCWnd: ... +def GetForegroundWindow() -> _win32typing.PyCWnd: ... +def GetHalftoneBrush() -> _win32typing.PyCBrush: ... +def GetInitialStateRequest(): ... +def GetMainFrame() -> _win32typing.PyCWnd: ... +def GetName() -> str: ... +def GetProfileFileName() -> str: ... +def GetProfileVal(section: str, entry: str, defValue: str, /) -> str: ... +def GetResource() -> _win32typing.PyDLL: ... +def GetThread() -> _win32typing.PyCWinApp: ... +def GetType(): ... +def InitRichEdit() -> str: ... +def InstallCallbackCaller(caller: Callable[..., Incomplete] | None): ... +def IsDebug() -> int: ... +def IsWin32s() -> int: ... +def IsObject(o: object, /) -> bool: ... +def LoadDialogResource(idRes, dll: _win32typing.PyDLL | None = ..., /): ... +def LoadLibrary(fileName: str, /) -> _win32typing.PyDLL: ... +def LoadMenu(_id, dll: _win32typing.PyDLL | None = ..., /) -> _win32typing.PyCMenu: ... +def LoadStdProfileSettings(maxFiles: int = ..., /) -> None: ... +def LoadString(stringId, /) -> str: ... +def MessageBox(message: str, title: str | None = ..., style=..., /): ... +def OutputDebugString(msg: str, /) -> None: ... +def EnableControlContainer(): ... +def PrintTraceback(tb, output, /) -> None: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def RegisterWndClass(style, hCursor: int = ..., hBrush: int = ..., hIcon=..., /) -> str: ... +def RemoveRecentFile(index: int = ..., /) -> None: ... +def SetAppHelpPath(): ... +def SetAppName(appName: str, /): ... +def SetCurrentInstanceHandle(newVal, /): ... +def SetCurrentResourceHandle(newVal, /): ... +def SetDialogBkColor(clrCtlBk: int = ..., clrCtlText: int = ..., /) -> None: ... +def SetProfileFileName(filename: str, /) -> None: ... +def SetRegistryKey(key: str, /) -> None: ... +def SetResource(dll, /) -> _win32typing.PyDLL: ... +def SetStatusText(msg: str, bForce: int = ..., /) -> None: ... +def StartDebuggerPump() -> None: ... +def StopDebuggerPump() -> None: ... +def TranslateMessage(): ... +def TranslateVirtualKey(vk, /) -> str: ... +def WinHelp(arg, data: str, /) -> None: ... +def WriteProfileVal(section: str, entry: str, value: str, /) -> None: ... +def AddToRecentFileList(fname, /): ... +def CreateImageList(cx, cy, mask, initial, grow, /): ... +def CreateListCtrl(): ... +def CreateListView(doc, /): ... +def CreateRectRgn(rect: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /): ... +def GetRecentFileList() -> list[Incomplete]: ... +def OutputDebug(msg: str, /) -> None: ... + +AFX_IDW_PANE_FIRST: int +AFX_IDW_PANE_LAST: int +AFX_WS_DEFAULT_VIEW: int +CDocTemplate_Confidence_maybeAttemptForeign: int +CDocTemplate_Confidence_maybeAttemptNative: int +CDocTemplate_Confidence_noAttempt: int +CDocTemplate_Confidence_yesAlreadyOpen: int +CDocTemplate_Confidence_yesAttemptForeign: int +CDocTemplate_Confidence_yesAttemptNative: int +CDocTemplate_docName: int +CDocTemplate_fileNewName: int +CDocTemplate_filterExt: int +CDocTemplate_filterName: int +CDocTemplate_regFileTypeId: int +CDocTemplate_regFileTypeName: int +CDocTemplate_windowTitle: int +CRichEditView_WrapNone: int +CRichEditView_WrapToTargetDevice: int +CRichEditView_WrapToWindow: int +debug: int +FWS_ADDTOTITLE: int +FWS_PREFIXTITLE: int +FWS_SNAPTOBARS: int +ID_APP_ABOUT: int +ID_APP_EXIT: int +ID_EDIT_CLEAR: int +ID_EDIT_CLEAR_ALL: int +ID_EDIT_COPY: int +ID_EDIT_CUT: int +ID_EDIT_FIND: int +ID_EDIT_GOTO_LINE: int +ID_EDIT_PASTE: int +ID_EDIT_REDO: int +ID_EDIT_REPEAT: int +ID_EDIT_REPLACE: int +ID_EDIT_SELECT_ALL: int +ID_EDIT_SELECT_BLOCK: int +ID_EDIT_UNDO: int +ID_FILE_CHECK: int +ID_FILE_CLOSE: int +ID_FILE_IMPORT: int +ID_FILE_LOCATE: int +ID_FILE_MRU_FILE1: int +ID_FILE_MRU_FILE2: int +ID_FILE_MRU_FILE3: int +ID_FILE_MRU_FILE4: int +ID_FILE_NEW: int +ID_FILE_OPEN: int +ID_FILE_PAGE_SETUP: int +ID_FILE_PRINT: int +ID_FILE_PRINT_PREVIEW: int +ID_FILE_PRINT_SETUP: int +ID_FILE_RUN: int +ID_FILE_SAVE: int +ID_FILE_SAVE_ALL: int +ID_FILE_SAVE_AS: int +ID_HELP_GUI_REF: int +ID_HELP_OTHER: int +ID_HELP_PYTHON: int +ID_INDICATOR_COLNUM: int +ID_INDICATOR_LINENUM: int +ID_NEXT_PANE: int +ID_PREV_PANE: int +ID_SEPARATOR: int +ID_VIEW_BROWSE: int +ID_VIEW_EOL: int +ID_VIEW_FIXED_FONT: int +ID_VIEW_FOLD_COLLAPSE: int +ID_VIEW_FOLD_COLLAPSE_ALL: int +ID_VIEW_FOLD_EXPAND: int +ID_VIEW_FOLD_EXPAND_ALL: int +ID_VIEW_INDENTATIONGUIDES: int +ID_VIEW_INTERACTIVE: int +ID_VIEW_OPTIONS: int +ID_VIEW_RIGHT_EDGE: int +ID_VIEW_STATUS_BAR: int +ID_VIEW_TOOLBAR: int +ID_VIEW_TOOLBAR_DBG: int +ID_VIEW_WHITESPACE: int +ID_WINDOW_ARRANGE: int +ID_WINDOW_CASCADE: int +ID_WINDOW_NEW: int +ID_WINDOW_SPLIT: int +ID_WINDOW_TILE_HORZ: int +ID_WINDOW_TILE_VERT: int +IDB_BROWSER_HIER: int +IDB_DEBUGGER_HIER: int +IDB_HIERFOLDERS: int +IDC_ABOUT_VERSION: int +IDC_AUTO_RELOAD: int +IDC_AUTOCOMPLETE: int +IDC_BUTTON1: int +IDC_BUTTON2: int +IDC_BUTTON3: int +IDC_BUTTON4: int +IDC_CALLTIPS: int +IDC_CHECK1: int +IDC_CHECK2: int +IDC_CHECK3: int +IDC_COMBO1: int +IDC_COMBO2: int +IDC_EDIT1: int +IDC_EDIT2: int +IDC_EDIT3: int +IDC_EDIT4: int +IDC_EDIT_TABS: int +IDC_INDENT_SIZE: int +IDC_KEYBOARD_CONFIG: int +IDC_PROMPT1: int +IDC_PROMPT2: int +IDC_PROMPT3: int +IDC_PROMPT4: int +IDC_PROMPT_TABS: int +IDC_RADIO1: int +IDC_RADIO2: int +IDC_RIGHTEDGE_COLUMN: int +IDC_RIGHTEDGE_DEFINE: int +IDC_RIGHTEDGE_ENABLE: int +IDC_RIGHTEDGE_SAMPLE: int +IDC_SPIN1: int +IDC_SPIN2: int +IDC_SPIN3: int +IDC_TAB_SIZE: int +IDC_USE_SMART_TABS: int +IDC_USE_TABS: int +IDC_VIEW_WHITESPACE: int +IDC_VSS_INTEGRATE: int +IDD_ABOUTBOX: int +IDD_DUMMYPROPPAGE: int +IDD_GENERAL_STATUS: int +IDD_LARGE_EDIT: int +IDD_PP_DEBUGGER: int +IDD_PP_EDITOR: int +IDD_PP_FORMAT: int +IDD_PP_IDE: int +IDD_PP_TABS: int +IDD_PP_TOOLMENU: int +IDD_PROPDEMO1: int +IDD_PROPDEMO2: int +IDD_RUN_SCRIPT: int +IDD_SET_TABSTOPS: int +IDD_SIMPLE_INPUT: int +IDD_TREE: int +IDD_TREE_MB: int +IDR_CNTR_INPLACE: int +IDR_DEBUGGER: int +IDR_MAINFRAME: int +IDR_PYTHONCONTYPE: int +IDR_PYTHONTYPE: int +IDR_PYTHONTYPE_CNTR_IP: int +IDR_TEXTTYPE: int +LM_COMMIT: int +LM_HORZ: int +LM_HORZDOCK: int +LM_LENGTHY: int +LM_MRUWIDTH: int +LM_STRETCH: int +LM_VERTDOCK: int +MFS_4THICKFRAME: int +MFS_BLOCKSYSMENU: int +MFS_MOVEFRAME: int +MFS_SYNCACTIVE: int +MFS_THICKFRAME: int +PD_ALLPAGES: int +PD_COLLATE: int +PD_DISABLEPRINTTOFILE: int +PD_ENABLEPRINTHOOK: int +PD_ENABLEPRINTTEMPLATE: int +PD_ENABLEPRINTTEMPLATEHANDLE: int +PD_ENABLESETUPHOOK: int +PD_ENABLESETUPTEMPLATE: int +PD_ENABLESETUPTEMPLATEHANDLE: int +PD_HIDEPRINTTOFILE: int +PD_NONETWORKBUTTON: int +PD_NOPAGENUMS: int +PD_NOSELECTION: int +PD_NOWARNING: int +PD_PAGENUMS: int +PD_PRINTSETUP: int +PD_PRINTTOFILE: int +PD_RETURNDC: int +PD_RETURNDEFAULT: int +PD_RETURNIC: int +PD_SELECTION: int +PD_SHOWHELP: int +PD_USEDEVMODECOPIES: int +PD_USEDEVMODECOPIESANDCOLLATE: int +PSWIZB_BACK: int +PSWIZB_DISABLEDFINISH: int +PSWIZB_FINISH: int +PSWIZB_NEXT: int +IDC_DBG_ADD: int +IDC_DBG_BREAKPOINTS: int +IDC_DBG_CLEAR: int +IDC_DBG_CLOSE: int +IDC_DBG_GO: int +IDC_DBG_STACK: int +IDC_DBG_STEP: int +IDC_DBG_STEPOUT: int +IDC_DBG_STEPOVER: int +IDC_DBG_WATCH: int +IDC_EDITOR_COLOR: int +IDC_FOLD_ENABLE: int +IDC_FOLD_ON_OPEN: int +IDC_FOLD_SHOW_LINES: int +IDC_LIST1: int +IDC_MARGIN_FOLD: int +IDC_MARGIN_LINENUMBER: int +IDC_MARGIN_MARKER: int +IDC_TABTIMMY_BG: int +IDC_TABTIMMY_IND: int +IDC_TABTIMMY_NONE: int +IDC_VIEW_EOL: int +IDC_VIEW_INDENTATIONGUIDES: int +ID_VIEW_FOLD_TOPLEVEL: int +copyright: str +dllhandle: int +types: dict[str, type] diff --git a/stubs/pywin32/pythonwin/win32uiole.pyi b/stubs/pywin32/pythonwin/win32uiole.pyi new file mode 100644 index 000000000000..01e3e02e5bf7 --- /dev/null +++ b/stubs/pywin32/pythonwin/win32uiole.pyi @@ -0,0 +1,27 @@ +import _win32typing + +def AfxOleInit(enabled, /) -> None: ... +def CreateInsertDialog() -> _win32typing.PyCOleInsertDialog: ... +def CreateOleClientItem() -> _win32typing.PyCOleClientItem: ... +def CreateOleDocument( + template: _win32typing.PyCDocTemplate | _win32typing.DocTemplate, fileName: str | None = ..., / +) -> _win32typing.PyCOleDocument: ... +def DaoGetEngine() -> _win32typing.PyIDispatch: ... +def GetIDispatchForWindow(Wnd, /) -> _win32typing.PyIDispatch: ... +def OleGetUserCtrl(): ... +def OleSetUserCtrl(bUserCtrl, /): ... +def SetMessagePendingDelay(delay, /) -> None: ... +def EnableNotRespondingDialog(enabled, /) -> None: ... +def EnableBusyDialog(enabled, /) -> None: ... + +COleClientItem_activeState: int +COleClientItem_activeUIState: int +COleClientItem_emptyState: int +COleClientItem_loadedState: int +COleClientItem_openState: int +OLE_CHANGED: int +OLE_CHANGED_ASPECT: int +OLE_CHANGED_STATE: int +OLE_CLOSED: int +OLE_RENAMED: int +OLE_SAVED: int diff --git a/stubs/pywin32/pywintypes.pyi b/stubs/pywin32/pywintypes.pyi new file mode 100644 index 000000000000..64c9f845cf94 --- /dev/null +++ b/stubs/pywin32/pywintypes.pyi @@ -0,0 +1 @@ +from win32.lib.pywintypes import * diff --git a/stubs/pywin32/regutil.pyi b/stubs/pywin32/regutil.pyi new file mode 100644 index 000000000000..ef4d7a48c231 --- /dev/null +++ b/stubs/pywin32/regutil.pyi @@ -0,0 +1 @@ +from win32.lib.regutil import * diff --git a/stubs/pywin32/servicemanager.pyi b/stubs/pywin32/servicemanager.pyi new file mode 100644 index 000000000000..91dbd289360e --- /dev/null +++ b/stubs/pywin32/servicemanager.pyi @@ -0,0 +1 @@ +from win32.servicemanager import * diff --git a/stubs/pywin32/sspicon.pyi b/stubs/pywin32/sspicon.pyi new file mode 100644 index 000000000000..0618e191ed7e --- /dev/null +++ b/stubs/pywin32/sspicon.pyi @@ -0,0 +1 @@ +from win32.lib.sspicon import * diff --git a/stubs/pywin32/timer.pyi b/stubs/pywin32/timer.pyi new file mode 100644 index 000000000000..d3d280166cc4 --- /dev/null +++ b/stubs/pywin32/timer.pyi @@ -0,0 +1 @@ +from win32.timer import * diff --git a/stubs/pywin32/win2kras.pyi b/stubs/pywin32/win2kras.pyi new file mode 100644 index 000000000000..e9b12664e3e3 --- /dev/null +++ b/stubs/pywin32/win2kras.pyi @@ -0,0 +1 @@ +from win32.lib.win2kras import * diff --git a/stubs/pywin32/win32/__init__.pyi b/stubs/pywin32/win32/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32/lib/__init__.pyi b/stubs/pywin32/win32/lib/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32/lib/commctrl.pyi b/stubs/pywin32/win32/lib/commctrl.pyi new file mode 100644 index 000000000000..d1e76bcbe1eb --- /dev/null +++ b/stubs/pywin32/win32/lib/commctrl.pyi @@ -0,0 +1,1522 @@ +from _typeshed import Incomplete + +WM_USER: int +ICC_LISTVIEW_CLASSES: int +ICC_TREEVIEW_CLASSES: int +ICC_BAR_CLASSES: int +ICC_TAB_CLASSES: int +ICC_UPDOWN_CLASS: int +ICC_PROGRESS_CLASS: int +ICC_HOTKEY_CLASS: int +ICC_ANIMATE_CLASS: int +ICC_WIN95_CLASSES: int +ICC_DATE_CLASSES: int +ICC_USEREX_CLASSES: int +ICC_COOL_CLASSES: int +ICC_INTERNET_CLASSES: int +ICC_PAGESCROLLER_CLASS: int +ICC_NATIVEFNTCTL_CLASS: int +ODT_HEADER: int +ODT_TAB: int +ODT_LISTVIEW: int +PY_0U: int +NM_FIRST: int +NM_LAST: Incomplete +LVN_FIRST: Incomplete +LVN_LAST: Incomplete +HDN_FIRST: Incomplete +HDN_LAST: Incomplete +TVN_FIRST: Incomplete +TVN_LAST: Incomplete +TTN_FIRST: Incomplete +TTN_LAST: Incomplete +TCN_FIRST: Incomplete +TCN_LAST: Incomplete +CDN_FIRST: Incomplete +CDN_LAST: Incomplete +TBN_FIRST: Incomplete +TBN_LAST: Incomplete +UDN_FIRST: Incomplete +UDN_LAST: Incomplete +MCN_FIRST: Incomplete +MCN_LAST: Incomplete +DTN_FIRST: Incomplete +DTN_LAST: Incomplete +CBEN_FIRST: Incomplete +CBEN_LAST: Incomplete +RBN_FIRST: Incomplete +RBN_LAST: Incomplete +IPN_FIRST: Incomplete +IPN_LAST: Incomplete +SBN_FIRST: Incomplete +SBN_LAST: Incomplete +PGN_FIRST: Incomplete +PGN_LAST: Incomplete +LVM_FIRST: int +TV_FIRST: int +HDM_FIRST: int +TCM_FIRST: int +PGM_FIRST: int +CCM_FIRST: int +CCM_SETBKCOLOR: Incomplete +CCM_SETCOLORSCHEME: Incomplete +CCM_GETCOLORSCHEME: Incomplete +CCM_GETDROPTARGET: Incomplete +CCM_SETUNICODEFORMAT: Incomplete +CCM_GETUNICODEFORMAT: Incomplete +INFOTIPSIZE: int +NM_OUTOFMEMORY: Incomplete +NM_CLICK: Incomplete +NM_DBLCLK: Incomplete +NM_RETURN: Incomplete +NM_RCLICK: Incomplete +NM_RDBLCLK: Incomplete +NM_SETFOCUS: Incomplete +NM_KILLFOCUS: Incomplete +NM_CUSTOMDRAW: Incomplete +NM_HOVER: Incomplete +NM_NCHITTEST: Incomplete +NM_KEYDOWN: Incomplete +NM_RELEASEDCAPTURE: Incomplete +NM_SETCURSOR: Incomplete +NM_CHAR: Incomplete +MSGF_COMMCTRL_BEGINDRAG: int +MSGF_COMMCTRL_SIZEHEADER: int +MSGF_COMMCTRL_DRAGSELECT: int +MSGF_COMMCTRL_TOOLBARCUST: int +CDRF_DODEFAULT: int +CDRF_NEWFONT: int +CDRF_SKIPDEFAULT: int +CDRF_NOTIFYPOSTPAINT: int +CDRF_NOTIFYITEMDRAW: int +CDRF_NOTIFYSUBITEMDRAW: int +CDRF_NOTIFYPOSTERASE: int +CDDS_PREPAINT: int +CDDS_POSTPAINT: int +CDDS_PREERASE: int +CDDS_POSTERASE: int +CDDS_ITEM: int +CDDS_ITEMPREPAINT: Incomplete +CDDS_ITEMPOSTPAINT: Incomplete +CDDS_ITEMPREERASE: Incomplete +CDDS_ITEMPOSTERASE: Incomplete +CDDS_SUBITEM: int +CDIS_SELECTED: int +CDIS_GRAYED: int +CDIS_DISABLED: int +CDIS_CHECKED: int +CDIS_FOCUS: int +CDIS_DEFAULT: int +CDIS_HOT: int +CDIS_MARKED: int +CDIS_INDETERMINATE: int +CLR_NONE: int +CLR_DEFAULT: int +ILC_MASK: int +ILC_COLOR: int +ILC_COLORDDB: int +ILC_COLOR4: int +ILC_COLOR8: int +ILC_COLOR16: int +ILC_COLOR24: int +ILC_COLOR32: int +ILC_PALETTE: int +ILD_NORMAL: int +ILD_TRANSPARENT: int +ILD_MASK: int +ILD_IMAGE: int +ILD_ROP: int +ILD_BLEND25: int +ILD_BLEND50: int +ILD_OVERLAYMASK: int +ILD_SELECTED: int +ILD_FOCUS: int +ILD_BLEND: int +CLR_HILIGHT: int +ILCF_MOVE: int +ILCF_SWAP: int +WC_HEADERA: str +WC_HEADER: str +HDS_HORZ: int +HDS_BUTTONS: int +HDS_HOTTRACK: int +HDS_HIDDEN: int +HDS_DRAGDROP: int +HDS_FULLDRAG: int +HDI_WIDTH: int +HDI_HEIGHT: int +HDI_TEXT: int +HDI_FORMAT: int +HDI_LPARAM: int +HDI_BITMAP: int +HDI_IMAGE: int +HDI_DI_SETITEM: int +HDI_ORDER: int +HDF_LEFT: int +HDF_RIGHT: int +HDF_CENTER: int +HDF_JUSTIFYMASK: int +HDF_RTLREADING: int +HDF_OWNERDRAW: int +HDF_STRING: int +HDF_BITMAP: int +HDF_BITMAP_ON_RIGHT: int +HDF_IMAGE: int +HDM_GETITEMCOUNT: Incomplete +HDM_INSERTITEMA: Incomplete +HDM_INSERTITEMW: Incomplete +HDM_INSERTITEM: Incomplete +HDM_DELETEITEM: Incomplete +HDM_GETITEMA: Incomplete +HDM_GETITEMW: Incomplete +HDM_GETITEM: Incomplete +HDM_SETITEMA: Incomplete +HDM_SETITEMW: Incomplete +HDM_SETITEM: Incomplete +HDM_LAYOUT: Incomplete +HHT_NOWHERE: int +HHT_ONHEADER: int +HHT_ONDIVIDER: int +HHT_ONDIVOPEN: int +HHT_ABOVE: int +HHT_BELOW: int +HHT_TORIGHT: int +HHT_TOLEFT: int +HDM_HITTEST: Incomplete +HDM_GETITEMRECT: Incomplete +HDM_SETIMAGELIST: Incomplete +HDM_GETIMAGELIST: Incomplete +HDM_ORDERTOINDEX: Incomplete +HDM_CREATEDRAGIMAGE: Incomplete +HDM_GETORDERARRAY: Incomplete +HDM_SETORDERARRAY: Incomplete +HDM_SETHOTDIVIDER: Incomplete +HDM_SETUNICODEFORMAT: Incomplete +HDM_GETUNICODEFORMAT: Incomplete +HDN_ITEMCHANGINGA: Incomplete +HDN_ITEMCHANGINGW: Incomplete +HDN_ITEMCHANGEDA: Incomplete +HDN_ITEMCHANGEDW: Incomplete +HDN_ITEMCLICKA: Incomplete +HDN_ITEMCLICKW: Incomplete +HDN_ITEMDBLCLICKA: Incomplete +HDN_ITEMDBLCLICKW: Incomplete +HDN_DIVIDERDBLCLICKA: Incomplete +HDN_DIVIDERDBLCLICKW: Incomplete +HDN_BEGINTRACKA: Incomplete +HDN_BEGINTRACKW: Incomplete +HDN_ENDTRACKA: Incomplete +HDN_ENDTRACKW: Incomplete +HDN_TRACKA: Incomplete +HDN_TRACKW: Incomplete +HDN_GETDISPINFOA: Incomplete +HDN_GETDISPINFOW: Incomplete +HDN_BEGINDRAG: Incomplete +HDN_ENDDRAG: Incomplete +HDN_ITEMCHANGING: Incomplete +HDN_ITEMCHANGED: Incomplete +HDN_ITEMCLICK: Incomplete +HDN_ITEMDBLCLICK: Incomplete +HDN_DIVIDERDBLCLICK: Incomplete +HDN_BEGINTRACK: Incomplete +HDN_ENDTRACK: Incomplete +HDN_TRACK: Incomplete +HDN_GETDISPINFO: Incomplete +TOOLBARCLASSNAMEA: str +TOOLBARCLASSNAME: str +CMB_MASKED: int +TBSTATE_CHECKED: int +TBSTATE_PRESSED: int +TBSTATE_ENABLED: int +TBSTATE_HIDDEN: int +TBSTATE_INDETERMINATE: int +TBSTATE_WRAP: int +TBSTATE_ELLIPSES: int +TBSTATE_MARKED: int +TBSTYLE_BUTTON: int +TBSTYLE_SEP: int +TBSTYLE_CHECK: int +TBSTYLE_GROUP: int +TBSTYLE_CHECKGROUP: Incomplete +TBSTYLE_DROPDOWN: int +TBSTYLE_AUTOSIZE: int +TBSTYLE_NOPREFIX: int +TBSTYLE_TOOLTIPS: int +TBSTYLE_WRAPABLE: int +TBSTYLE_ALTDRAG: int +TBSTYLE_FLAT: int +TBSTYLE_LIST: int +TBSTYLE_CUSTOMERASE: int +TBSTYLE_REGISTERDROP: int +TBSTYLE_TRANSPARENT: int +TBSTYLE_EX_DRAWDDARROWS: int +BTNS_BUTTON: int +BTNS_SEP: int +BTNS_CHECK: int +BTNS_GROUP: int +BTNS_CHECKGROUP: Incomplete +BTNS_DROPDOWN: int +BTNS_AUTOSIZE: int +BTNS_NOPREFIX: int +BTNS_SHOWTEXT: int +BTNS_WHOLEDROPDOWN: int +TBCDRF_NOEDGES: int +TBCDRF_HILITEHOTTRACK: int +TBCDRF_NOOFFSET: int +TBCDRF_NOMARK: int +TBCDRF_NOETCHEDEFFECT: int +TB_ENABLEBUTTON: Incomplete +TB_CHECKBUTTON: Incomplete +TB_PRESSBUTTON: Incomplete +TB_HIDEBUTTON: Incomplete +TB_INDETERMINATE: Incomplete +TB_MARKBUTTON: Incomplete +TB_ISBUTTONENABLED: Incomplete +TB_ISBUTTONCHECKED: Incomplete +TB_ISBUTTONPRESSED: Incomplete +TB_ISBUTTONHIDDEN: Incomplete +TB_ISBUTTONINDETERMINATE: Incomplete +TB_ISBUTTONHIGHLIGHTED: Incomplete +TB_SETSTATE: Incomplete +TB_GETSTATE: Incomplete +TB_ADDBITMAP: Incomplete +HINST_COMMCTRL: int +IDB_STD_SMALL_COLOR: int +IDB_STD_LARGE_COLOR: int +IDB_VIEW_SMALL_COLOR: int +IDB_VIEW_LARGE_COLOR: int +IDB_HIST_SMALL_COLOR: int +IDB_HIST_LARGE_COLOR: int +STD_CUT: int +STD_COPY: int +STD_PASTE: int +STD_UNDO: int +STD_REDOW: int +STD_DELETE: int +STD_FILENEW: int +STD_FILEOPEN: int +STD_FILESAVE: int +STD_PRINTPRE: int +STD_PROPERTIES: int +STD_HELP: int +STD_FIND: int +STD_REPLACE: int +STD_PRINT: int +VIEW_LARGEICONS: int +VIEW_SMALLICONS: int +VIEW_LIST: int +VIEW_DETAILS: int +VIEW_SORTNAME: int +VIEW_SORTSIZE: int +VIEW_SORTDATE: int +VIEW_SORTTYPE: int +VIEW_PARENTFOLDER: int +VIEW_NETCONNECT: int +VIEW_NETDISCONNECT: int +VIEW_NEWFOLDER: int +VIEW_VIEWMENU: int +HIST_BACK: int +HIST_FORWARD: int +HIST_FAVORITES: int +HIST_ADDTOFAVORITES: int +HIST_VIEWTREE: int +TB_ADDBUTTONSA: Incomplete +TB_INSERTBUTTONA: Incomplete +TB_ADDBUTTONS: Incomplete +TB_INSERTBUTTON: Incomplete +TB_DELETEBUTTON: Incomplete +TB_GETBUTTON: Incomplete +TB_BUTTONCOUNT: Incomplete +TB_COMMANDTOINDEX: Incomplete +TB_SAVERESTOREA: Incomplete +TB_SAVERESTOREW: Incomplete +TB_CUSTOMIZE: Incomplete +TB_ADDSTRINGA: Incomplete +TB_ADDSTRINGW: Incomplete +TB_GETITEMRECT: Incomplete +TB_BUTTONSTRUCTSIZE: Incomplete +TB_SETBUTTONSIZE: Incomplete +TB_SETBITMAPSIZE: Incomplete +TB_AUTOSIZE: Incomplete +TB_GETTOOLTIPS: Incomplete +TB_SETTOOLTIPS: Incomplete +TB_SETPARENT: Incomplete +TB_SETROWS: Incomplete +TB_GETROWS: Incomplete +TB_SETCMDID: Incomplete +TB_CHANGEBITMAP: Incomplete +TB_GETBITMAP: Incomplete +TB_GETBUTTONTEXTA: Incomplete +TB_GETBUTTONTEXTW: Incomplete +TB_REPLACEBITMAP: Incomplete +TB_SETINDENT: Incomplete +TB_SETIMAGELIST: Incomplete +TB_GETIMAGELIST: Incomplete +TB_LOADIMAGES: Incomplete +TB_GETRECT: Incomplete +TB_SETHOTIMAGELIST: Incomplete +TB_GETHOTIMAGELIST: Incomplete +TB_SETDISABLEDIMAGELIST: Incomplete +TB_GETDISABLEDIMAGELIST: Incomplete +TB_SETSTYLE: Incomplete +TB_GETSTYLE: Incomplete +TB_GETBUTTONSIZE: Incomplete +TB_SETBUTTONWIDTH: Incomplete +TB_SETMAXTEXTROWS: Incomplete +TB_GETTEXTROWS: Incomplete +TB_GETBUTTONTEXT: Incomplete +TB_SAVERESTORE: Incomplete +TB_ADDSTRING: Incomplete +TB_GETOBJECT: Incomplete +TB_GETHOTITEM: Incomplete +TB_SETHOTITEM: Incomplete +TB_SETANCHORHIGHLIGHT: Incomplete +TB_GETANCHORHIGHLIGHT: Incomplete +TB_MAPACCELERATORA: Incomplete +TBIMHT_AFTER: int +TBIMHT_BACKGROUND: int +TB_GETINSERTMARK: Incomplete +TB_SETINSERTMARK: Incomplete +TB_INSERTMARKHITTEST: Incomplete +TB_MOVEBUTTON: Incomplete +TB_GETMAXSIZE: Incomplete +TB_SETEXTENDEDSTYLE: Incomplete +TB_GETEXTENDEDSTYLE: Incomplete +TB_GETPADDING: Incomplete +TB_SETPADDING: Incomplete +TB_SETINSERTMARKCOLOR: Incomplete +TB_GETINSERTMARKCOLOR: Incomplete +TB_SETCOLORSCHEME: Incomplete +TB_GETCOLORSCHEME: Incomplete +TB_SETUNICODEFORMAT: Incomplete +TB_GETUNICODEFORMAT: Incomplete +TB_MAPACCELERATORW: Incomplete +TB_MAPACCELERATOR: Incomplete +TBBF_LARGE: int +TB_GETBITMAPFLAGS: Incomplete +TBIF_IMAGE: int +TBIF_TEXT: int +TBIF_STATE: int +TBIF_STYLE: int +TBIF_LPARAM: int +TBIF_COMMAND: int +TBIF_SIZE: int +TB_GETBUTTONINFOW: Incomplete +TB_SETBUTTONINFOW: Incomplete +TB_GETBUTTONINFOA: Incomplete +TB_SETBUTTONINFOA: Incomplete +TB_INSERTBUTTONW: Incomplete +TB_ADDBUTTONSW: Incomplete +TB_HITTEST: Incomplete +TB_SETDRAWTEXTFLAGS: Incomplete +TBN_GETBUTTONINFOA: Incomplete +TBN_GETBUTTONINFOW: Incomplete +TBN_BEGINDRAG: Incomplete +TBN_ENDDRAG: Incomplete +TBN_BEGINADJUST: Incomplete +TBN_ENDADJUST: Incomplete +TBN_RESET: Incomplete +TBN_QUERYINSERT: Incomplete +TBN_QUERYDELETE: Incomplete +TBN_TOOLBARCHANGE: Incomplete +TBN_CUSTHELP: Incomplete +TBN_DROPDOWN: Incomplete +TBN_GETOBJECT: Incomplete +HICF_OTHER: int +HICF_MOUSE: int +HICF_ARROWKEYS: int +HICF_ACCELERATOR: int +HICF_DUPACCEL: int +HICF_ENTERING: int +HICF_LEAVING: int +HICF_RESELECT: int +TBN_HOTITEMCHANGE: Incomplete +TBN_DRAGOUT: Incomplete +TBN_DELETINGBUTTON: Incomplete +TBN_GETDISPINFOA: Incomplete +TBN_GETDISPINFOW: Incomplete +TBN_GETINFOTIPA: Incomplete +TBN_GETINFOTIPW: Incomplete +TBN_GETINFOTIP: Incomplete +TBNF_IMAGE: int +TBNF_TEXT: int +TBNF_DI_SETITEM: int +TBN_GETDISPINFO: Incomplete +TBDDRET_DEFAULT: int +TBDDRET_NODEFAULT: int +TBDDRET_TREATPRESSED: int +TBN_GETBUTTONINFO: Incomplete +REBARCLASSNAMEA: str +REBARCLASSNAME: str +RBIM_IMAGELIST: int +RBS_TOOLTIPS: int +RBS_VARHEIGHT: int +RBS_BANDBORDERS: int +RBS_FIXEDORDER: int +RBS_REGISTERDROP: int +RBS_AUTOSIZE: int +RBS_VERTICALGRIPPER: int +RBS_DBLCLKTOGGLE: int +RBBS_BREAK: int +RBBS_FIXEDSIZE: int +RBBS_CHILDEDGE: int +RBBS_HIDDEN: int +RBBS_NOVERT: int +RBBS_FIXEDBMP: int +RBBS_VARIABLEHEIGHT: int +RBBS_GRIPPERALWAYS: int +RBBS_NOGRIPPER: int +RBBIM_STYLE: int +RBBIM_COLORS: int +RBBIM_TEXT: int +RBBIM_IMAGE: int +RBBIM_CHILD: int +RBBIM_CHILDSIZE: int +RBBIM_SIZE: int +RBBIM_BACKGROUND: int +RBBIM_ID: int +RBBIM_IDEALSIZE: int +RBBIM_LPARAM: int +RB_INSERTBANDA: Incomplete +RB_DELETEBAND: Incomplete +RB_GETBARINFO: Incomplete +RB_SETBARINFO: Incomplete +RB_SETBANDINFOA: Incomplete +RB_SETPARENT: Incomplete +RB_HITTEST: Incomplete +RB_GETRECT: Incomplete +RB_INSERTBANDW: Incomplete +RB_SETBANDINFOW: Incomplete +RB_GETBANDCOUNT: Incomplete +RB_GETROWCOUNT: Incomplete +RB_GETROWHEIGHT: Incomplete +RB_IDTOINDEX: Incomplete +RB_GETTOOLTIPS: Incomplete +RB_SETTOOLTIPS: Incomplete +RB_SETBKCOLOR: Incomplete +RB_GETBKCOLOR: Incomplete +RB_SETTEXTCOLOR: Incomplete +RB_GETTEXTCOLOR: Incomplete +RB_SIZETORECT: Incomplete +RB_SETCOLORSCHEME: Incomplete +RB_GETCOLORSCHEME: Incomplete +RB_INSERTBAND: Incomplete +RB_SETBANDINFO: Incomplete +RB_BEGINDRAG: Incomplete +RB_ENDDRAG: Incomplete +RB_DRAGMOVE: Incomplete +RB_GETBARHEIGHT: Incomplete +RB_GETBANDINFOW: Incomplete +RB_GETBANDINFOA: Incomplete +RB_GETBANDINFO: Incomplete +RB_MINIMIZEBAND: Incomplete +RB_MAXIMIZEBAND: Incomplete +RB_GETDROPTARGET: Incomplete +RB_GETBANDBORDERS: Incomplete +RB_SHOWBAND: Incomplete +RB_SETPALETTE: Incomplete +RB_GETPALETTE: Incomplete +RB_MOVEBAND: Incomplete +RB_SETUNICODEFORMAT: Incomplete +RB_GETUNICODEFORMAT: Incomplete +RBN_HEIGHTCHANGE: Incomplete +RBN_GETOBJECT: Incomplete +RBN_LAYOUTCHANGED: Incomplete +RBN_AUTOSIZE: Incomplete +RBN_BEGINDRAG: Incomplete +RBN_ENDDRAG: Incomplete +RBN_DELETINGBAND: Incomplete +RBN_DELETEDBAND: Incomplete +RBN_CHILDSIZE: Incomplete +RBNM_ID: int +RBNM_STYLE: int +RBNM_LPARAM: int +RBHT_NOWHERE: int +RBHT_CAPTION: int +RBHT_CLIENT: int +RBHT_GRABBER: int +TOOLTIPS_CLASSA: str +TOOLTIPS_CLASS: str +TTS_ALWAYSTIP: int +TTS_NOPREFIX: int +TTF_IDISHWND: int +TTF_CENTERTIP: int +TTF_RTLREADING: int +TTF_SUBCLASS: int +TTF_TRACK: int +TTF_ABSOLUTE: int +TTF_TRANSPARENT: int +TTF_DI_SETITEM: int +TTDT_AUTOMATIC: int +TTDT_RESHOW: int +TTDT_AUTOPOP: int +TTDT_INITIAL: int +TTM_ACTIVATE: Incomplete +TTM_SETDELAYTIME: Incomplete +TTM_ADDTOOLA: Incomplete +TTM_ADDTOOLW: Incomplete +TTM_DELTOOLA: Incomplete +TTM_DELTOOLW: Incomplete +TTM_NEWTOOLRECTA: Incomplete +TTM_NEWTOOLRECTW: Incomplete +TTM_RELAYEVENT: Incomplete +TTM_GETTOOLINFOA: Incomplete +TTM_GETTOOLINFOW: Incomplete +TTM_SETTOOLINFOA: Incomplete +TTM_SETTOOLINFOW: Incomplete +TTM_HITTESTA: Incomplete +TTM_HITTESTW: Incomplete +TTM_GETTEXTA: Incomplete +TTM_GETTEXTW: Incomplete +TTM_UPDATETIPTEXTA: Incomplete +TTM_UPDATETIPTEXTW: Incomplete +TTM_GETTOOLCOUNT: Incomplete +TTM_ENUMTOOLSA: Incomplete +TTM_ENUMTOOLSW: Incomplete +TTM_GETCURRENTTOOLA: Incomplete +TTM_GETCURRENTTOOLW: Incomplete +TTM_WINDOWFROMPOINT: Incomplete +TTM_TRACKACTIVATE: Incomplete +TTM_TRACKPOSITION: Incomplete +TTM_SETTIPBKCOLOR: Incomplete +TTM_SETTIPTEXTCOLOR: Incomplete +TTM_GETDELAYTIME: Incomplete +TTM_GETTIPBKCOLOR: Incomplete +TTM_GETTIPTEXTCOLOR: Incomplete +TTM_SETMAXTIPWIDTH: Incomplete +TTM_GETMAXTIPWIDTH: Incomplete +TTM_SETMARGIN: Incomplete +TTM_GETMARGIN: Incomplete +TTM_POP: Incomplete +TTM_UPDATE: Incomplete +TTM_ADDTOOL: Incomplete +TTM_DELTOOL: Incomplete +TTM_NEWTOOLRECT: Incomplete +TTM_GETTOOLINFO: Incomplete +TTM_SETTOOLINFO: Incomplete +TTM_HITTEST: Incomplete +TTM_GETTEXT: Incomplete +TTM_UPDATETIPTEXT: Incomplete +TTM_ENUMTOOLS: Incomplete +TTM_GETCURRENTTOOL: Incomplete +TTN_GETDISPINFOA: Incomplete +TTN_GETDISPINFOW: Incomplete +TTN_SHOW: Incomplete +TTN_POP: Incomplete +TTN_GETDISPINFO: Incomplete +TTN_NEEDTEXT: Incomplete +TTN_NEEDTEXTA: Incomplete +TTN_NEEDTEXTW: Incomplete +SBARS_SIZEGRIP: int +SBARS_TOOLTIPS: int +STATUSCLASSNAMEA: str +STATUSCLASSNAME: str +SB_SETTEXTA: Incomplete +SB_SETTEXTW: Incomplete +SB_GETTEXTA: Incomplete +SB_GETTEXTW: Incomplete +SB_GETTEXTLENGTHA: Incomplete +SB_GETTEXTLENGTHW: Incomplete +SB_GETTEXT: Incomplete +SB_SETTEXT: Incomplete +SB_GETTEXTLENGTH: Incomplete +SB_SETPARTS: Incomplete +SB_GETPARTS: Incomplete +SB_GETBORDERS: Incomplete +SB_SETMINHEIGHT: Incomplete +SB_SIMPLE: Incomplete +SB_GETRECT: Incomplete +SB_ISSIMPLE: Incomplete +SB_SETICON: Incomplete +SB_SETTIPTEXTA: Incomplete +SB_SETTIPTEXTW: Incomplete +SB_GETTIPTEXTA: Incomplete +SB_GETTIPTEXTW: Incomplete +SB_GETICON: Incomplete +SB_SETTIPTEXT: Incomplete +SB_GETTIPTEXT: Incomplete +SB_SETUNICODEFORMAT: Incomplete +SB_GETUNICODEFORMAT: Incomplete +SBT_OWNERDRAW: int +SBT_NOBORDERS: int +SBT_POPOUT: int +SBT_RTLREADING: int +SBT_NOTABPARSING: int +SBT_TOOLTIPS: int +SB_SETBKCOLOR: Incomplete +SBN_SIMPLEMODECHANGE: Incomplete +TRACKBAR_CLASSA: str +TRACKBAR_CLASS: str +TBS_AUTOTICKS: int +TBS_VERT: int +TBS_HORZ: int +TBS_TOP: int +TBS_BOTTOM: int +TBS_LEFT: int +TBS_RIGHT: int +TBS_BOTH: int +TBS_NOTICKS: int +TBS_ENABLESELRANGE: int +TBS_FIXEDLENGTH: int +TBS_NOTHUMB: int +TBS_TOOLTIPS: int +TBM_GETPOS: int +TBM_GETRANGEMIN: Incomplete +TBM_GETRANGEMAX: Incomplete +TBM_GETTIC: Incomplete +TBM_SETTIC: Incomplete +TBM_SETPOS: Incomplete +TBM_SETRANGE: Incomplete +TBM_SETRANGEMIN: Incomplete +TBM_SETRANGEMAX: Incomplete +TBM_CLEARTICS: Incomplete +TBM_SETSEL: Incomplete +TBM_SETSELSTART: Incomplete +TBM_SETSELEND: Incomplete +TBM_GETPTICS: Incomplete +TBM_GETTICPOS: Incomplete +TBM_GETNUMTICS: Incomplete +TBM_GETSELSTART: Incomplete +TBM_GETSELEND: Incomplete +TBM_CLEARSEL: Incomplete +TBM_SETTICFREQ: Incomplete +TBM_SETPAGESIZE: Incomplete +TBM_GETPAGESIZE: Incomplete +TBM_SETLINESIZE: Incomplete +TBM_GETLINESIZE: Incomplete +TBM_GETTHUMBRECT: Incomplete +TBM_GETCHANNELRECT: Incomplete +TBM_SETTHUMBLENGTH: Incomplete +TBM_GETTHUMBLENGTH: Incomplete +TBM_SETTOOLTIPS: Incomplete +TBM_GETTOOLTIPS: Incomplete +TBM_SETTIPSIDE: Incomplete +TBTS_TOP: int +TBTS_LEFT: int +TBTS_BOTTOM: int +TBTS_RIGHT: int +TBM_SETBUDDY: Incomplete +TBM_GETBUDDY: Incomplete +TBM_SETUNICODEFORMAT: Incomplete +TBM_GETUNICODEFORMAT: Incomplete +TB_LINEUP: int +TB_LINEDOWN: int +TB_PAGEUP: int +TB_PAGEDOWN: int +TB_THUMBPOSITION: int +TB_THUMBTRACK: int +TB_TOP: int +TB_BOTTOM: int +TB_ENDTRACK: int +TBCD_TICS: int +TBCD_THUMB: int +TBCD_CHANNEL: int +DL_BEGINDRAG: Incomplete +DL_DRAGGING: Incomplete +DL_DROPPED: Incomplete +DL_CANCELDRAG: Incomplete +DL_CURSORSET: int +DL_STOPCURSOR: int +DL_COPYCURSOR: int +DL_MOVECURSOR: int +DRAGLISTMSGSTRING: str +UPDOWN_CLASSA: str +UPDOWN_CLASS: str +UD_MAXVAL: int +UD_MINVAL: Incomplete +UDS_WRAP: int +UDS_SETBUDDYINT: int +UDS_ALIGNRIGHT: int +UDS_ALIGNLEFT: int +UDS_AUTOBUDDY: int +UDS_ARROWKEYS: int +UDS_HORZ: int +UDS_NOTHOUSANDS: int +UDS_HOTTRACK: int +UDM_SETRANGE: Incomplete +UDM_GETRANGE: Incomplete +UDM_SETPOS: Incomplete +UDM_GETPOS: Incomplete +UDM_SETBUDDY: Incomplete +UDM_GETBUDDY: Incomplete +UDM_SETACCEL: Incomplete +UDM_GETACCEL: Incomplete +UDM_SETBASE: Incomplete +UDM_GETBASE: Incomplete +UDM_SETRANGE32: Incomplete +UDM_GETRANGE32: Incomplete +UDM_SETUNICODEFORMAT: Incomplete +UDM_GETUNICODEFORMAT: Incomplete +UDN_DELTAPOS: Incomplete +PROGRESS_CLASSA: str +PROGRESS_CLASS: str +PBS_SMOOTH: int +PBS_VERTICAL: int +PBM_SETRANGE: Incomplete +PBM_SETPOS: Incomplete +PBM_DELTAPOS: Incomplete +PBM_SETSTEP: Incomplete +PBM_STEPIT: Incomplete +PBM_SETRANGE32: Incomplete +PBM_GETRANGE: Incomplete +PBM_GETPOS: Incomplete +PBM_SETBARCOLOR: Incomplete +PBM_SETBKCOLOR: Incomplete +HOTKEYF_SHIFT: int +HOTKEYF_CONTROL: int +HOTKEYF_ALT: int +HOTKEYF_EXT: int +HKCOMB_NONE: int +HKCOMB_S: int +HKCOMB_C: int +HKCOMB_A: int +HKCOMB_SC: int +HKCOMB_SA: int +HKCOMB_CA: int +HKCOMB_SCA: int +HKM_SETHOTKEY: Incomplete +HKM_GETHOTKEY: Incomplete +HKM_SETRULES: Incomplete +HOTKEY_CLASSA: str +HOTKEY_CLASS: str +CCS_TOP: int +CCS_NOMOVEY: int +CCS_BOTTOM: int +CCS_NORESIZE: int +CCS_NOPARENTALIGN: int +CCS_ADJUSTABLE: int +CCS_NODIVIDER: int +CCS_VERT: int +CCS_LEFT: Incomplete +CCS_RIGHT: Incomplete +CCS_NOMOVEX: Incomplete +WC_LISTVIEWA: str +WC_LISTVIEW: str +LVS_ICON: int +LVS_REPORT: int +LVS_SMALLICON: int +LVS_LIST: int +LVS_TYPEMASK: int +LVS_SINGLESEL: int +LVS_SHOWSELALWAYS: int +LVS_SORTASCENDING: int +LVS_SORTDESCENDING: int +LVS_SHAREIMAGELISTS: int +LVS_NOLABELWRAP: int +LVS_AUTOARRANGE: int +LVS_EDITLABELS: int +LVS_OWNERDATA: int +LVS_NOSCROLL: int +LVS_TYPESTYLEMASK: int +LVS_ALIGNTOP: int +LVS_ALIGNLEFT: int +LVS_ALIGNMASK: int +LVS_OWNERDRAWFIXED: int +LVS_NOCOLUMNHEADER: int +LVS_NOSORTHEADER: int +LVM_SETUNICODEFORMAT: Incomplete +LVM_GETUNICODEFORMAT: Incomplete +LVM_GETBKCOLOR: Incomplete +LVM_SETBKCOLOR: Incomplete +LVM_GETIMAGELIST: Incomplete +LVSIL_NORMAL: int +LVSIL_SMALL: int +LVSIL_STATE: int +LVM_SETIMAGELIST: Incomplete +LVM_GETITEMCOUNT: Incomplete +LVIF_TEXT: int +LVIF_IMAGE: int +LVIF_PARAM: int +LVIF_STATE: int +LVIF_INDENT: int +LVIF_NORECOMPUTE: int +LVIS_FOCUSED: int +LVIS_SELECTED: int +LVIS_CUT: int +LVIS_DROPHILITED: int +LVIS_ACTIVATING: int +LVIS_OVERLAYMASK: int +LVIS_STATEIMAGEMASK: int +I_INDENTCALLBACK: int +LPSTR_TEXTCALLBACKA: int +LPSTR_TEXTCALLBACK: int +I_IMAGECALLBACK: int +LVM_GETITEMA: Incomplete +LVM_GETITEMW: Incomplete +LVM_GETITEM: Incomplete +LVM_SETITEMA: Incomplete +LVM_SETITEMW: Incomplete +LVM_SETITEM: Incomplete +LVM_INSERTITEMA: Incomplete +LVM_INSERTITEMW: Incomplete +LVM_INSERTITEM: Incomplete +LVM_DELETEITEM: Incomplete +LVM_DELETEALLITEMS: Incomplete +LVM_GETCALLBACKMASK: Incomplete +LVM_SETCALLBACKMASK: Incomplete +LVNI_ALL: int +LVNI_FOCUSED: int +LVNI_SELECTED: int +LVNI_CUT: int +LVNI_DROPHILITED: int +LVNI_ABOVE: int +LVNI_BELOW: int +LVNI_TOLEFT: int +LVNI_TORIGHT: int +LVM_GETNEXTITEM: Incomplete +LVFI_PARAM: int +LVFI_STRING: int +LVFI_PARTIAL: int +LVFI_WRAP: int +LVFI_NEARESTXY: int +LVM_FINDITEMA: Incomplete +LVM_FINDITEMW: Incomplete +LVM_FINDITEM: Incomplete +LVIR_BOUNDS: int +LVIR_ICON: int +LVIR_LABEL: int +LVIR_SELECTBOUNDS: int +LVM_GETITEMRECT: Incomplete +LVM_SETITEMPOSITION: Incomplete +LVM_GETITEMPOSITION: Incomplete +LVM_GETSTRINGWIDTHA: Incomplete +LVM_GETSTRINGWIDTHW: Incomplete +LVM_GETSTRINGWIDTH: Incomplete +LVHT_NOWHERE: int +LVHT_ONITEMICON: int +LVHT_ONITEMLABEL: int +LVHT_ONITEMSTATEICON: int +LVHT_ONITEM: Incomplete +LVHT_ABOVE: int +LVHT_BELOW: int +LVHT_TORIGHT: int +LVHT_TOLEFT: int +LVM_HITTEST: Incomplete +LVM_ENSUREVISIBLE: Incomplete +LVM_SCROLL: Incomplete +LVM_REDRAWITEMS: Incomplete +LVA_DEFAULT: int +LVA_ALIGNLEFT: int +LVA_ALIGNTOP: int +LVA_SNAPTOGRID: int +LVM_ARRANGE: Incomplete +LVM_EDITLABELA: Incomplete +LVM_EDITLABELW: Incomplete +LVM_EDITLABEL: Incomplete +LVM_GETEDITCONTROL: Incomplete +LVCF_FMT: int +LVCF_WIDTH: int +LVCF_TEXT: int +LVCF_SUBITEM: int +LVCF_IMAGE: int +LVCF_ORDER: int +LVCFMT_LEFT: int +LVCFMT_RIGHT: int +LVCFMT_CENTER: int +LVCFMT_JUSTIFYMASK: int +LVCFMT_IMAGE: int +LVCFMT_BITMAP_ON_RIGHT: int +LVCFMT_COL_HAS_IMAGES: int +LVM_GETCOLUMNA: Incomplete +LVM_GETCOLUMNW: Incomplete +LVM_GETCOLUMN: Incomplete +LVM_SETCOLUMNA: Incomplete +LVM_SETCOLUMNW: Incomplete +LVM_SETCOLUMN: Incomplete +LVM_INSERTCOLUMNA: Incomplete +LVM_INSERTCOLUMNW: Incomplete +LVM_INSERTCOLUMN: Incomplete +LVM_DELETECOLUMN: Incomplete +LVM_GETCOLUMNWIDTH: Incomplete +LVSCW_AUTOSIZE: int +LVSCW_AUTOSIZE_USEHEADER: int +LVM_SETCOLUMNWIDTH: Incomplete +LVM_GETHEADER: Incomplete +LVM_CREATEDRAGIMAGE: Incomplete +LVM_GETVIEWRECT: Incomplete +LVM_GETTEXTCOLOR: Incomplete +LVM_SETTEXTCOLOR: Incomplete +LVM_GETTEXTBKCOLOR: Incomplete +LVM_SETTEXTBKCOLOR: Incomplete +LVM_GETTOPINDEX: Incomplete +LVM_GETCOUNTPERPAGE: Incomplete +LVM_GETORIGIN: Incomplete +LVM_UPDATE: Incomplete +LVM_SETITEMSTATE: Incomplete +LVM_GETITEMSTATE: Incomplete +LVM_GETITEMTEXTA: Incomplete +LVM_GETITEMTEXTW: Incomplete +LVM_GETITEMTEXT: Incomplete +LVM_SETITEMTEXTA: Incomplete +LVM_SETITEMTEXTW: Incomplete +LVM_SETITEMTEXT: Incomplete +LVSICF_NOINVALIDATEALL: int +LVSICF_NOSCROLL: int +LVM_SETITEMCOUNT: Incomplete +LVM_SORTITEMS: Incomplete +LVM_SETITEMPOSITION32: Incomplete +LVM_GETSELECTEDCOUNT: Incomplete +LVM_GETITEMSPACING: Incomplete +LVM_GETISEARCHSTRINGA: Incomplete +LVM_GETISEARCHSTRINGW: Incomplete +LVM_GETISEARCHSTRING: Incomplete +LVM_SETICONSPACING: Incomplete +LVM_SETEXTENDEDLISTVIEWSTYLE: Incomplete +LVM_GETEXTENDEDLISTVIEWSTYLE: Incomplete +LVS_EX_GRIDLINES: int +LVS_EX_SUBITEMIMAGES: int +LVS_EX_CHECKBOXES: int +LVS_EX_TRACKSELECT: int +LVS_EX_HEADERDRAGDROP: int +LVS_EX_FULLROWSELECT: int +LVS_EX_ONECLICKACTIVATE: int +LVS_EX_TWOCLICKACTIVATE: int +LVS_EX_FLATSB: int +LVS_EX_REGIONAL: int +LVS_EX_INFOTIP: int +LVS_EX_UNDERLINEHOT: int +LVS_EX_UNDERLINECOLD: int +LVS_EX_MULTIWORKAREAS: int +LVM_GETSUBITEMRECT: Incomplete +LVM_SUBITEMHITTEST: Incomplete +LVM_SETCOLUMNORDERARRAY: Incomplete +LVM_GETCOLUMNORDERARRAY: Incomplete +LVM_SETHOTITEM: Incomplete +LVM_GETHOTITEM: Incomplete +LVM_SETHOTCURSOR: Incomplete +LVM_GETHOTCURSOR: Incomplete +LVM_APPROXIMATEVIEWRECT: Incomplete +LV_MAX_WORKAREAS: int +LVM_SETWORKAREAS: Incomplete +LVM_GETWORKAREAS: Incomplete +LVM_GETNUMBEROFWORKAREAS: Incomplete +LVM_GETSELECTIONMARK: Incomplete +LVM_SETSELECTIONMARK: Incomplete +LVM_SETHOVERTIME: Incomplete +LVM_GETHOVERTIME: Incomplete +LVM_SETTOOLTIPS: Incomplete +LVM_GETTOOLTIPS: Incomplete +LVBKIF_SOURCE_NONE: int +LVBKIF_SOURCE_HBITMAP: int +LVBKIF_SOURCE_URL: int +LVBKIF_SOURCE_MASK: int +LVBKIF_STYLE_NORMAL: int +LVBKIF_STYLE_TILE: int +LVBKIF_STYLE_MASK: int +LVM_SETBKIMAGEA: Incomplete +LVM_SETBKIMAGEW: Incomplete +LVM_GETBKIMAGEA: Incomplete +LVM_GETBKIMAGEW: Incomplete +LVKF_ALT: int +LVKF_CONTROL: int +LVKF_SHIFT: int +LVN_ITEMCHANGING: Incomplete +LVN_ITEMCHANGED: Incomplete +LVN_INSERTITEM: Incomplete +LVN_DELETEITEM: Incomplete +LVN_DELETEALLITEMS: Incomplete +LVN_BEGINLABELEDITA: Incomplete +LVN_BEGINLABELEDITW: Incomplete +LVN_ENDLABELEDITA: Incomplete +LVN_ENDLABELEDITW: Incomplete +LVN_COLUMNCLICK: Incomplete +LVN_BEGINDRAG: Incomplete +LVN_BEGINRDRAG: Incomplete +LVN_ODCACHEHINT: Incomplete +LVN_ODFINDITEMA: Incomplete +LVN_ODFINDITEMW: Incomplete +LVN_ITEMACTIVATE: Incomplete +LVN_ODSTATECHANGED: Incomplete +LVN_ODFINDITEM: Incomplete +LVN_HOTTRACK: Incomplete +LVN_GETDISPINFOA: Incomplete +LVN_GETDISPINFOW: Incomplete +LVN_SETDISPINFOA: Incomplete +LVN_SETDISPINFOW: Incomplete +LVN_BEGINLABELEDIT: Incomplete +LVN_ENDLABELEDIT: Incomplete +LVN_GETDISPINFO: Incomplete +LVN_SETDISPINFO: Incomplete +LVIF_DI_SETITEM: int +LVN_KEYDOWN: Incomplete +LVN_MARQUEEBEGIN: Incomplete +LVGIT_UNFOLDED: int +LVN_GETINFOTIPA: Incomplete +LVN_GETINFOTIPW: Incomplete +LVN_GETINFOTIP: Incomplete +WC_TREEVIEWA: str +WC_TREEVIEW: str +TVS_HASBUTTONS: int +TVS_HASLINES: int +TVS_LINESATROOT: int +TVS_EDITLABELS: int +TVS_DISABLEDRAGDROP: int +TVS_SHOWSELALWAYS: int +TVS_RTLREADING: int +TVS_NOTOOLTIPS: int +TVS_CHECKBOXES: int +TVS_TRACKSELECT: int +TVS_SINGLEEXPAND: int +TVS_INFOTIP: int +TVS_FULLROWSELECT: int +TVS_NOSCROLL: int +TVS_NONEVENHEIGHT: int +TVIF_TEXT: int +TVIF_IMAGE: int +TVIF_PARAM: int +TVIF_STATE: int +TVIF_HANDLE: int +TVIF_SELECTEDIMAGE: int +TVIF_CHILDREN: int +TVIF_INTEGRAL: int +TVIS_SELECTED: int +TVIS_CUT: int +TVIS_DROPHILITED: int +TVIS_BOLD: int +TVIS_EXPANDED: int +TVIS_EXPANDEDONCE: int +TVIS_EXPANDPARTIAL: int +TVIS_OVERLAYMASK: int +TVIS_STATEIMAGEMASK: int +TVIS_USERMASK: int +I_CHILDRENCALLBACK: int +TVI_ROOT: int +TVI_FIRST: int +TVI_LAST: int +TVI_SORT: int +TVM_INSERTITEMA: Incomplete +TVM_INSERTITEMW: Incomplete +TVM_INSERTITEM: Incomplete +TVM_DELETEITEM: Incomplete +TVM_EXPAND: Incomplete +TVE_COLLAPSE: int +TVE_EXPAND: int +TVE_TOGGLE: int +TVE_EXPANDPARTIAL: int +TVE_COLLAPSERESET: int +TVM_GETITEMRECT: Incomplete +TVM_GETCOUNT: Incomplete +TVM_GETINDENT: Incomplete +TVM_SETINDENT: Incomplete +TVM_GETIMAGELIST: Incomplete +TVSIL_NORMAL: int +TVSIL_STATE: int +TVM_SETIMAGELIST: Incomplete +TVM_GETNEXTITEM: Incomplete +TVGN_ROOT: int +TVGN_NEXT: int +TVGN_PREVIOUS: int +TVGN_PARENT: int +TVGN_CHILD: int +TVGN_FIRSTVISIBLE: int +TVGN_NEXTVISIBLE: int +TVGN_PREVIOUSVISIBLE: int +TVGN_DROPHILITE: int +TVGN_CARET: int +TVGN_LASTVISIBLE: int +TVM_SELECTITEM: Incomplete +TVM_GETITEMA: Incomplete +TVM_GETITEMW: Incomplete +TVM_GETITEM: Incomplete +TVM_SETITEMA: Incomplete +TVM_SETITEMW: Incomplete +TVM_SETITEM: Incomplete +TVM_EDITLABELA: Incomplete +TVM_EDITLABELW: Incomplete +TVM_EDITLABEL: Incomplete +TVM_GETEDITCONTROL: Incomplete +TVM_GETVISIBLECOUNT: Incomplete +TVM_HITTEST: Incomplete +TVHT_NOWHERE: int +TVHT_ONITEMICON: int +TVHT_ONITEMLABEL: int +TVHT_ONITEMINDENT: int +TVHT_ONITEMBUTTON: int +TVHT_ONITEMRIGHT: int +TVHT_ONITEMSTATEICON: int +TVHT_ABOVE: int +TVHT_BELOW: int +TVHT_TORIGHT: int +TVHT_TOLEFT: int +TVHT_ONITEM: Incomplete +TVM_CREATEDRAGIMAGE: Incomplete +TVM_SORTCHILDREN: Incomplete +TVM_ENSUREVISIBLE: Incomplete +TVM_SORTCHILDRENCB: Incomplete +TVM_ENDEDITLABELNOW: Incomplete +TVM_GETISEARCHSTRINGA: Incomplete +TVM_GETISEARCHSTRINGW: Incomplete +TVM_GETISEARCHSTRING: Incomplete +TVM_SETTOOLTIPS: Incomplete +TVM_GETTOOLTIPS: Incomplete +TVM_SETINSERTMARK: Incomplete +TVM_SETUNICODEFORMAT: Incomplete +TVM_GETUNICODEFORMAT: Incomplete +TVM_SETITEMHEIGHT: Incomplete +TVM_GETITEMHEIGHT: Incomplete +TVM_SETBKCOLOR: Incomplete +TVM_SETTEXTCOLOR: Incomplete +TVM_GETBKCOLOR: Incomplete +TVM_GETTEXTCOLOR: Incomplete +TVM_SETSCROLLTIME: Incomplete +TVM_GETSCROLLTIME: Incomplete +TVM_SETINSERTMARKCOLOR: Incomplete +TVM_GETINSERTMARKCOLOR: Incomplete +TVN_SELCHANGINGA: Incomplete +TVN_SELCHANGINGW: Incomplete +TVN_SELCHANGEDA: Incomplete +TVN_SELCHANGEDW: Incomplete +TVC_UNKNOWN: int +TVC_BYMOUSE: int +TVC_BYKEYBOARD: int +TVN_GETDISPINFOA: Incomplete +TVN_GETDISPINFOW: Incomplete +TVN_SETDISPINFOA: Incomplete +TVN_SETDISPINFOW: Incomplete +TVIF_DI_SETITEM: int +TVN_ITEMEXPANDINGA: Incomplete +TVN_ITEMEXPANDINGW: Incomplete +TVN_ITEMEXPANDEDA: Incomplete +TVN_ITEMEXPANDEDW: Incomplete +TVN_BEGINDRAGA: Incomplete +TVN_BEGINDRAGW: Incomplete +TVN_BEGINRDRAGA: Incomplete +TVN_BEGINRDRAGW: Incomplete +TVN_DELETEITEMA: Incomplete +TVN_DELETEITEMW: Incomplete +TVN_BEGINLABELEDITA: Incomplete +TVN_BEGINLABELEDITW: Incomplete +TVN_ENDLABELEDITA: Incomplete +TVN_ENDLABELEDITW: Incomplete +TVN_KEYDOWN: Incomplete +TVN_GETINFOTIPA: Incomplete +TVN_GETINFOTIPW: Incomplete +TVN_SINGLEEXPAND: Incomplete +TVN_SELCHANGING: Incomplete +TVN_SELCHANGED: Incomplete +TVN_GETDISPINFO: Incomplete +TVN_SETDISPINFO: Incomplete +TVN_ITEMEXPANDING: Incomplete +TVN_ITEMEXPANDED: Incomplete +TVN_BEGINDRAG: Incomplete +TVN_BEGINRDRAG: Incomplete +TVN_DELETEITEM: Incomplete +TVN_BEGINLABELEDIT: Incomplete +TVN_ENDLABELEDIT: Incomplete +TVN_GETINFOTIP: Incomplete +TVCDRF_NOIMAGES: int +WC_COMBOBOXEXA: str +WC_COMBOBOXEX: str +CBEIF_TEXT: int +CBEIF_IMAGE: int +CBEIF_SELECTEDIMAGE: int +CBEIF_OVERLAY: int +CBEIF_INDENT: int +CBEIF_LPARAM: int +CBEIF_DI_SETITEM: int +CBEM_INSERTITEMA: Incomplete +CBEM_SETIMAGELIST: Incomplete +CBEM_GETIMAGELIST: Incomplete +CBEM_GETITEMA: Incomplete +CBEM_SETITEMA: Incomplete +CBEM_GETCOMBOCONTROL: Incomplete +CBEM_GETEDITCONTROL: Incomplete +CBEM_SETEXSTYLE: Incomplete +CBEM_SETEXTENDEDSTYLE: Incomplete +CBEM_GETEXSTYLE: Incomplete +CBEM_GETEXTENDEDSTYLE: Incomplete +CBEM_SETUNICODEFORMAT: Incomplete +CBEM_GETUNICODEFORMAT: Incomplete +CBEM_HASEDITCHANGED: Incomplete +CBEM_INSERTITEMW: Incomplete +CBEM_SETITEMW: Incomplete +CBEM_GETITEMW: Incomplete +CBEM_INSERTITEM: Incomplete +CBEM_SETITEM: Incomplete +CBEM_GETITEM: Incomplete +CBES_EX_NOEDITIMAGE: int +CBES_EX_NOEDITIMAGEINDENT: int +CBES_EX_PATHWORDBREAKPROC: int +CBES_EX_NOSIZELIMIT: int +CBES_EX_CASESENSITIVE: int +CBEN_GETDISPINFO: Incomplete +CBEN_GETDISPINFOA: Incomplete +CBEN_INSERTITEM: Incomplete +CBEN_DELETEITEM: Incomplete +CBEN_BEGINEDIT: Incomplete +CBEN_ENDEDITA: Incomplete +CBEN_ENDEDITW: Incomplete +CBEN_GETDISPINFOW: Incomplete +CBEN_DRAGBEGINA: Incomplete +CBEN_DRAGBEGINW: Incomplete +CBEN_DRAGBEGIN: Incomplete +CBEN_ENDEDIT: Incomplete +CBENF_KILLFOCUS: int +CBENF_RETURN: int +CBENF_ESCAPE: int +CBENF_DROPDOWN: int +CBEMAXSTRLEN: int +WC_TABCONTROLA: str +WC_TABCONTROL: str +TCS_SCROLLOPPOSITE: int +TCS_BOTTOM: int +TCS_RIGHT: int +TCS_MULTISELECT: int +TCS_FLATBUTTONS: int +TCS_FORCEICONLEFT: int +TCS_FORCELABELLEFT: int +TCS_HOTTRACK: int +TCS_VERTICAL: int +TCS_TABS: int +TCS_BUTTONS: int +TCS_SINGLELINE: int +TCS_MULTILINE: int +TCS_RIGHTJUSTIFY: int +TCS_FIXEDWIDTH: int +TCS_RAGGEDRIGHT: int +TCS_FOCUSONBUTTONDOWN: int +TCS_OWNERDRAWFIXED: int +TCS_TOOLTIPS: int +TCS_FOCUSNEVER: int +TCS_EX_FLATSEPARATORS: int +TCS_EX_REGISTERDROP: int +TCM_GETIMAGELIST: Incomplete +TCM_SETIMAGELIST: Incomplete +TCM_GETITEMCOUNT: Incomplete +TCIF_TEXT: int +TCIF_IMAGE: int +TCIF_RTLREADING: int +TCIF_PARAM: int +TCIF_STATE: int +TCIS_BUTTONPRESSED: int +TCIS_HIGHLIGHTED: int +TCM_GETITEMA: Incomplete +TCM_GETITEMW: Incomplete +TCM_GETITEM: Incomplete +TCM_SETITEMA: Incomplete +TCM_SETITEMW: Incomplete +TCM_SETITEM: Incomplete +TCM_INSERTITEMA: Incomplete +TCM_INSERTITEMW: Incomplete +TCM_INSERTITEM: Incomplete +TCM_DELETEITEM: Incomplete +TCM_DELETEALLITEMS: Incomplete +TCM_GETITEMRECT: Incomplete +TCM_GETCURSEL: Incomplete +TCM_SETCURSEL: Incomplete +TCHT_NOWHERE: int +TCHT_ONITEMICON: int +TCHT_ONITEMLABEL: int +TCHT_ONITEM: Incomplete +TCM_HITTEST: Incomplete +TCM_SETITEMEXTRA: Incomplete +TCM_ADJUSTRECT: Incomplete +TCM_SETITEMSIZE: Incomplete +TCM_REMOVEIMAGE: Incomplete +TCM_SETPADDING: Incomplete +TCM_GETROWCOUNT: Incomplete +TCM_GETTOOLTIPS: Incomplete +TCM_SETTOOLTIPS: Incomplete +TCM_GETCURFOCUS: Incomplete +TCM_SETCURFOCUS: Incomplete +TCM_SETMINTABWIDTH: Incomplete +TCM_DESELECTALL: Incomplete +TCM_HIGHLIGHTITEM: Incomplete +TCM_SETEXTENDEDSTYLE: Incomplete +TCM_GETEXTENDEDSTYLE: Incomplete +TCM_SETUNICODEFORMAT: Incomplete +TCM_GETUNICODEFORMAT: Incomplete +TCN_KEYDOWN: Incomplete +ANIMATE_CLASSA: str +ANIMATE_CLASS: str +ACS_CENTER: int +ACS_TRANSPARENT: int +ACS_AUTOPLAY: int +ACS_TIMER: int +ACM_OPENA: Incomplete +ACM_OPENW: Incomplete +ACM_OPEN: Incomplete +ACM_PLAY: Incomplete +ACM_STOP: Incomplete +ACN_START: int +ACN_STOP: int +MONTHCAL_CLASSA: str +MONTHCAL_CLASS: str +MCM_FIRST: int +MCM_GETCURSEL: Incomplete +MCM_SETCURSEL: Incomplete +MCM_GETMAXSELCOUNT: Incomplete +MCM_SETMAXSELCOUNT: Incomplete +MCM_GETSELRANGE: Incomplete +MCM_SETSELRANGE: Incomplete +MCM_GETMONTHRANGE: Incomplete +MCM_SETDAYSTATE: Incomplete +MCM_GETMINREQRECT: Incomplete +MCM_SETCOLOR: Incomplete +MCM_GETCOLOR: Incomplete +MCSC_BACKGROUND: int +MCSC_TEXT: int +MCSC_TITLEBK: int +MCSC_TITLETEXT: int +MCSC_MONTHBK: int +MCSC_TRAILINGTEXT: int +MCM_SETTODAY: Incomplete +MCM_GETTODAY: Incomplete +MCM_HITTEST: Incomplete +MCHT_TITLE: int +MCHT_CALENDAR: int +MCHT_TODAYLINK: int +MCHT_NEXT: int +MCHT_PREV: int +MCHT_NOWHERE: int +MCHT_TITLEBK: int +MCHT_TITLEMONTH: Incomplete +MCHT_TITLEYEAR: Incomplete +MCHT_TITLEBTNNEXT: Incomplete +MCHT_TITLEBTNPREV: Incomplete +MCHT_CALENDARBK: int +MCHT_CALENDARDATE: Incomplete +MCHT_CALENDARDATENEXT: Incomplete +MCHT_CALENDARDATEPREV: Incomplete +MCHT_CALENDARDAY: Incomplete +MCHT_CALENDARWEEKNUM: Incomplete +MCM_SETFIRSTDAYOFWEEK: Incomplete +MCM_GETFIRSTDAYOFWEEK: Incomplete +MCM_GETRANGE: Incomplete +MCM_SETRANGE: Incomplete +MCM_GETMONTHDELTA: Incomplete +MCM_SETMONTHDELTA: Incomplete +MCM_GETMAXTODAYWIDTH: Incomplete +MCM_SETUNICODEFORMAT: Incomplete +MCM_GETUNICODEFORMAT: Incomplete +MCN_SELCHANGE: Incomplete +MCN_GETDAYSTATE: Incomplete +MCN_SELECT: Incomplete +MCS_DAYSTATE: int +MCS_MULTISELECT: int +MCS_WEEKNUMBERS: int +MCS_NOTODAYCIRCLE: int +MCS_NOTODAY: int +GMR_VISIBLE: int +GMR_DAYSTATE: int +DATETIMEPICK_CLASSA: str +DATETIMEPICK_CLASS: str +DTM_FIRST: int +DTM_GETSYSTEMTIME: Incomplete +DTM_SETSYSTEMTIME: Incomplete +DTM_GETRANGE: Incomplete +DTM_SETRANGE: Incomplete +DTM_SETFORMATA: Incomplete +DTM_SETFORMATW: Incomplete +DTM_SETFORMAT: Incomplete +DTM_SETMCCOLOR: Incomplete +DTM_GETMCCOLOR: Incomplete +DTM_GETMONTHCAL: Incomplete +DTM_SETMCFONT: Incomplete +DTM_GETMCFONT: Incomplete +DTS_UPDOWN: int +DTS_SHOWNONE: int +DTS_SHORTDATEFORMAT: int +DTS_LONGDATEFORMAT: int +DTS_TIMEFORMAT: int +DTS_APPCANPARSE: int +DTS_RIGHTALIGN: int +DTN_DATETIMECHANGE: Incomplete +DTN_USERSTRINGA: Incomplete +DTN_USERSTRINGW: Incomplete +DTN_USERSTRING: Incomplete +DTN_WMKEYDOWNA: Incomplete +DTN_WMKEYDOWNW: Incomplete +DTN_WMKEYDOWN: Incomplete +DTN_FORMATA: Incomplete +DTN_FORMATW: Incomplete +DTN_FORMAT: Incomplete +DTN_FORMATQUERYA: Incomplete +DTN_FORMATQUERYW: Incomplete +DTN_FORMATQUERY: Incomplete +DTN_DROPDOWN: Incomplete +DTN_CLOSEUP: Incomplete +GDTR_MIN: int +GDTR_MAX: int +GDT_ERROR: int +GDT_VALID: int +GDT_NONE: int +IPM_CLEARADDRESS: Incomplete +IPM_SETADDRESS: Incomplete +IPM_GETADDRESS: Incomplete +IPM_SETRANGE: Incomplete +IPM_SETFOCUS: Incomplete +IPM_ISBLANK: Incomplete +WC_IPADDRESSA: str +WC_IPADDRESS: str +IPN_FIELDCHANGED: Incomplete +WC_PAGESCROLLERA: str +WC_PAGESCROLLER: str +PGS_VERT: int +PGS_HORZ: int +PGS_AUTOSCROLL: int +PGS_DRAGNDROP: int +PGF_INVISIBLE: int +PGF_NORMAL: int +PGF_GRAYED: int +PGF_DEPRESSED: int +PGF_HOT: int +PGB_TOPORLEFT: int +PGB_BOTTOMORRIGHT: int +PGM_SETCHILD: Incomplete +PGM_RECALCSIZE: Incomplete +PGM_FORWARDMOUSE: Incomplete +PGM_SETBKCOLOR: Incomplete +PGM_GETBKCOLOR: Incomplete +PGM_SETBORDER: Incomplete +PGM_GETBORDER: Incomplete +PGM_SETPOS: Incomplete +PGM_GETPOS: Incomplete +PGM_SETBUTTONSIZE: Incomplete +PGM_GETBUTTONSIZE: Incomplete +PGM_GETBUTTONSTATE: Incomplete +PGM_GETDROPTARGET: Incomplete +PGN_SCROLL: Incomplete +PGF_SCROLLUP: int +PGF_SCROLLDOWN: int +PGF_SCROLLLEFT: int +PGF_SCROLLRIGHT: int +PGK_SHIFT: int +PGK_CONTROL: int +PGK_MENU: int +PGN_CALCSIZE: Incomplete +PGF_CALCWIDTH: int +PGF_CALCHEIGHT: int +WC_NATIVEFONTCTLA: str +WC_NATIVEFONTCTL: str +NFS_EDIT: int +NFS_STATIC: int +NFS_LISTCOMBO: int +NFS_BUTTON: int +NFS_ALL: int +WM_MOUSEHOVER: int +WM_MOUSELEAVE: int +TME_HOVER: int +TME_LEAVE: int +TME_QUERY: int +TME_CANCEL: int +HOVER_DEFAULT: int +WSB_PROP_CYVSCROLL: int +WSB_PROP_CXHSCROLL: int +WSB_PROP_CYHSCROLL: int +WSB_PROP_CXVSCROLL: int +WSB_PROP_CXHTHUMB: int +WSB_PROP_CYVTHUMB: int +WSB_PROP_VBKGCOLOR: int +WSB_PROP_HBKGCOLOR: int +WSB_PROP_VSTYLE: int +WSB_PROP_HSTYLE: int +WSB_PROP_WINSTYLE: int +WSB_PROP_PALETTE: int +WSB_PROP_MASK: int +FSB_FLAT_MODE: int +FSB_ENCARTA_MODE: int +FSB_REGULAR_MODE: int + +def INDEXTOOVERLAYMASK(i): ... +def INDEXTOSTATEIMAGEMASK(i): ... diff --git a/stubs/pywin32/win32/lib/mmsystem.pyi b/stubs/pywin32/win32/lib/mmsystem.pyi new file mode 100644 index 000000000000..667047551b2c --- /dev/null +++ b/stubs/pywin32/win32/lib/mmsystem.pyi @@ -0,0 +1,858 @@ +from _typeshed import Incomplete + +MAXPNAMELEN: int +MAXERRORLENGTH: int +MAX_JOYSTICKOEMVXDNAME: int +MM_MICROSOFT: int +MM_MIDI_MAPPER: int +MM_WAVE_MAPPER: int +MM_SNDBLST_MIDIOUT: int +MM_SNDBLST_MIDIIN: int +MM_SNDBLST_SYNTH: int +MM_SNDBLST_WAVEOUT: int +MM_SNDBLST_WAVEIN: int +MM_ADLIB: int +MM_MPU401_MIDIOUT: int +MM_MPU401_MIDIIN: int +MM_PC_JOYSTICK: int +TIME_MS: int +TIME_SAMPLES: int +TIME_BYTES: int +TIME_SMPTE: int +TIME_MIDI: int +TIME_TICKS: int +MM_JOY1MOVE: int +MM_JOY2MOVE: int +MM_JOY1ZMOVE: int +MM_JOY2ZMOVE: int +MM_JOY1BUTTONDOWN: int +MM_JOY2BUTTONDOWN: int +MM_JOY1BUTTONUP: int +MM_JOY2BUTTONUP: int +MM_MCINOTIFY: int +MM_WOM_OPEN: int +MM_WOM_CLOSE: int +MM_WOM_DONE: int +MM_WIM_OPEN: int +MM_WIM_CLOSE: int +MM_WIM_DATA: int +MM_MIM_OPEN: int +MM_MIM_CLOSE: int +MM_MIM_DATA: int +MM_MIM_LONGDATA: int +MM_MIM_ERROR: int +MM_MIM_LONGERROR: int +MM_MOM_OPEN: int +MM_MOM_CLOSE: int +MM_MOM_DONE: int +MM_STREAM_OPEN: int +MM_STREAM_CLOSE: int +MM_STREAM_DONE: int +MM_STREAM_ERROR: int +MM_MOM_POSITIONCB: int +MM_MIM_MOREDATA: int +MM_MIXM_LINE_CHANGE: int +MM_MIXM_CONTROL_CHANGE: int +MMSYSERR_BASE: int +WAVERR_BASE: int +MIDIERR_BASE: int +TIMERR_BASE: int +JOYERR_BASE: int +MCIERR_BASE: int +MIXERR_BASE: int +MCI_STRING_OFFSET: int +MCI_VD_OFFSET: int +MCI_CD_OFFSET: int +MCI_WAVE_OFFSET: int +MCI_SEQ_OFFSET: int +MMSYSERR_NOERROR: int +MMSYSERR_ERROR: Incomplete +MMSYSERR_BADDEVICEID: Incomplete +MMSYSERR_NOTENABLED: Incomplete +MMSYSERR_ALLOCATED: Incomplete +MMSYSERR_INVALHANDLE: Incomplete +MMSYSERR_NODRIVER: Incomplete +MMSYSERR_NOMEM: Incomplete +MMSYSERR_NOTSUPPORTED: Incomplete +MMSYSERR_BADERRNUM: Incomplete +MMSYSERR_INVALFLAG: Incomplete +MMSYSERR_INVALPARAM: Incomplete +MMSYSERR_HANDLEBUSY: Incomplete +MMSYSERR_INVALIDALIAS: Incomplete +MMSYSERR_BADDB: Incomplete +MMSYSERR_KEYNOTFOUND: Incomplete +MMSYSERR_READERROR: Incomplete +MMSYSERR_WRITEERROR: Incomplete +MMSYSERR_DELETEERROR: Incomplete +MMSYSERR_VALNOTFOUND: Incomplete +MMSYSERR_NODRIVERCB: Incomplete +MMSYSERR_LASTERROR: Incomplete +DRV_LOAD: int +DRV_ENABLE: int +DRV_OPEN: int +DRV_CLOSE: int +DRV_DISABLE: int +DRV_FREE: int +DRV_CONFIGURE: int +DRV_QUERYCONFIGURE: int +DRV_INSTALL: int +DRV_REMOVE: int +DRV_EXITSESSION: int +DRV_POWER: int +DRV_RESERVED: int +DRV_USER: int +DRVCNF_CANCEL: int +DRVCNF_OK: int +DRVCNF_RESTART: int +DRV_CANCEL: int +DRV_OK: int +DRV_RESTART: int +DRV_MCI_FIRST: int +DRV_MCI_LAST: Incomplete +CALLBACK_TYPEMASK: int +CALLBACK_NULL: int +CALLBACK_WINDOW: int +CALLBACK_TASK: int +CALLBACK_FUNCTION: int +CALLBACK_THREAD: int +CALLBACK_EVENT: int +SND_SYNC: int +SND_ASYNC: int +SND_NODEFAULT: int +SND_MEMORY: int +SND_LOOP: int +SND_NOSTOP: int +SND_NOWAIT: int +SND_ALIAS: int +SND_ALIAS_ID: int +SND_FILENAME: int +SND_RESOURCE: int +SND_PURGE: int +SND_APPLICATION: int +SND_ALIAS_START: int +WAVERR_BADFORMAT: Incomplete +WAVERR_STILLPLAYING: Incomplete +WAVERR_UNPREPARED: Incomplete +WAVERR_SYNC: Incomplete +WAVERR_LASTERROR: Incomplete +WOM_OPEN: int +WOM_CLOSE: int +WOM_DONE: int +WIM_OPEN: int +WIM_CLOSE: int +WIM_DATA: int +WAVE_MAPPER: int +WAVE_FORMAT_QUERY: int +WAVE_ALLOWSYNC: int +WAVE_MAPPED: int +WAVE_FORMAT_DIRECT: int +WAVE_FORMAT_DIRECT_QUERY: Incomplete +WHDR_DONE: int +WHDR_PREPARED: int +WHDR_BEGINLOOP: int +WHDR_ENDLOOP: int +WHDR_INQUEUE: int +WAVECAPS_PITCH: int +WAVECAPS_PLAYBACKRATE: int +WAVECAPS_VOLUME: int +WAVECAPS_LRVOLUME: int +WAVECAPS_SYNC: int +WAVECAPS_SAMPLEACCURATE: int +WAVECAPS_DIRECTSOUND: int +WAVE_INVALIDFORMAT: int +WAVE_FORMAT_1M08: int +WAVE_FORMAT_1S08: int +WAVE_FORMAT_1M16: int +WAVE_FORMAT_1S16: int +WAVE_FORMAT_2M08: int +WAVE_FORMAT_2S08: int +WAVE_FORMAT_2M16: int +WAVE_FORMAT_2S16: int +WAVE_FORMAT_4M08: int +WAVE_FORMAT_4S08: int +WAVE_FORMAT_4M16: int +WAVE_FORMAT_4S16: int +WAVE_FORMAT_PCM: int +WAVE_FORMAT_IEEE_FLOAT: int +MIDIERR_UNPREPARED: Incomplete +MIDIERR_STILLPLAYING: Incomplete +MIDIERR_NOMAP: Incomplete +MIDIERR_NOTREADY: Incomplete +MIDIERR_NODEVICE: Incomplete +MIDIERR_INVALIDSETUP: Incomplete +MIDIERR_BADOPENMODE: Incomplete +MIDIERR_DONT_CONTINUE: Incomplete +MIDIERR_LASTERROR: Incomplete +MIDIPATCHSIZE: int +MIM_OPEN: int +MIM_CLOSE: int +MIM_DATA: int +MIM_LONGDATA: int +MIM_ERROR: int +MIM_LONGERROR: int +MOM_OPEN: int +MOM_CLOSE: int +MOM_DONE: int +MIM_MOREDATA: int +MOM_POSITIONCB: int +MIDI_IO_STATUS: int +MIDI_CACHE_ALL: int +MIDI_CACHE_BESTFIT: int +MIDI_CACHE_QUERY: int +MIDI_UNCACHE: int +MOD_MIDIPORT: int +MOD_SYNTH: int +MOD_SQSYNTH: int +MOD_FMSYNTH: int +MOD_MAPPER: int +MIDICAPS_VOLUME: int +MIDICAPS_LRVOLUME: int +MIDICAPS_CACHE: int +MIDICAPS_STREAM: int +MHDR_DONE: int +MHDR_PREPARED: int +MHDR_INQUEUE: int +MHDR_ISSTRM: int +MEVT_F_SHORT: int +MEVT_F_LONG: int +MEVT_F_CALLBACK: int + +def MEVT_EVENTTYPE(x): ... +def MEVT_EVENTPARM(x): ... + +MIDISTRM_ERROR: int +MIDIPROP_SET: int +MIDIPROP_GET: int +MIDIPROP_TIMEDIV: int +MIDIPROP_TEMPO: int +AUXCAPS_CDAUDIO: int +AUXCAPS_AUXIN: int +AUXCAPS_VOLUME: int +AUXCAPS_LRVOLUME: int +MIXER_SHORT_NAME_CHARS: int +MIXER_LONG_NAME_CHARS: int +MIXERR_INVALLINE: Incomplete +MIXERR_INVALCONTROL: Incomplete +MIXERR_INVALVALUE: Incomplete +MIXERR_LASTERROR: Incomplete +MIXER_OBJECTF_HANDLE: int +MIXER_OBJECTF_MIXER: int +MIXER_OBJECTF_HMIXER: Incomplete +MIXER_OBJECTF_WAVEOUT: int +MIXER_OBJECTF_HWAVEOUT: Incomplete +MIXER_OBJECTF_WAVEIN: int +MIXER_OBJECTF_HWAVEIN: Incomplete +MIXER_OBJECTF_MIDIOUT: int +MIXER_OBJECTF_HMIDIOUT: Incomplete +MIXER_OBJECTF_MIDIIN: int +MIXER_OBJECTF_HMIDIIN: Incomplete +MIXER_OBJECTF_AUX: int +MIXERLINE_LINEF_ACTIVE: int +MIXERLINE_LINEF_DISCONNECTED: int +MIXERLINE_LINEF_SOURCE: int +MIXERLINE_COMPONENTTYPE_DST_FIRST: int +MIXERLINE_COMPONENTTYPE_DST_UNDEFINED: Incomplete +MIXERLINE_COMPONENTTYPE_DST_DIGITAL: Incomplete +MIXERLINE_COMPONENTTYPE_DST_LINE: Incomplete +MIXERLINE_COMPONENTTYPE_DST_MONITOR: Incomplete +MIXERLINE_COMPONENTTYPE_DST_SPEAKERS: Incomplete +MIXERLINE_COMPONENTTYPE_DST_HEADPHONES: Incomplete +MIXERLINE_COMPONENTTYPE_DST_TELEPHONE: Incomplete +MIXERLINE_COMPONENTTYPE_DST_WAVEIN: Incomplete +MIXERLINE_COMPONENTTYPE_DST_VOICEIN: Incomplete +MIXERLINE_COMPONENTTYPE_DST_LAST: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_FIRST: int +MIXERLINE_COMPONENTTYPE_SRC_UNDEFINED: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_DIGITAL: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_LINE: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_ANALOG: Incomplete +MIXERLINE_COMPONENTTYPE_SRC_LAST: Incomplete +MIXERLINE_TARGETTYPE_UNDEFINED: int +MIXERLINE_TARGETTYPE_WAVEOUT: int +MIXERLINE_TARGETTYPE_WAVEIN: int +MIXERLINE_TARGETTYPE_MIDIOUT: int +MIXERLINE_TARGETTYPE_MIDIIN: int +MIXERLINE_TARGETTYPE_AUX: int +MIXER_GETLINEINFOF_DESTINATION: int +MIXER_GETLINEINFOF_SOURCE: int +MIXER_GETLINEINFOF_LINEID: int +MIXER_GETLINEINFOF_COMPONENTTYPE: int +MIXER_GETLINEINFOF_TARGETTYPE: int +MIXER_GETLINEINFOF_QUERYMASK: int +MIXERCONTROL_CONTROLF_UNIFORM: int +MIXERCONTROL_CONTROLF_MULTIPLE: int +MIXERCONTROL_CONTROLF_DISABLED: int +MIXERCONTROL_CT_CLASS_MASK: int +MIXERCONTROL_CT_CLASS_CUSTOM: int +MIXERCONTROL_CT_CLASS_METER: int +MIXERCONTROL_CT_CLASS_SWITCH: int +MIXERCONTROL_CT_CLASS_NUMBER: int +MIXERCONTROL_CT_CLASS_SLIDER: int +MIXERCONTROL_CT_CLASS_FADER: int +MIXERCONTROL_CT_CLASS_TIME: int +MIXERCONTROL_CT_CLASS_LIST: int +MIXERCONTROL_CT_SUBCLASS_MASK: int +MIXERCONTROL_CT_SC_SWITCH_BOOLEAN: int +MIXERCONTROL_CT_SC_SWITCH_BUTTON: int +MIXERCONTROL_CT_SC_METER_POLLED: int +MIXERCONTROL_CT_SC_TIME_MICROSECS: int +MIXERCONTROL_CT_SC_TIME_MILLISECS: int +MIXERCONTROL_CT_SC_LIST_SINGLE: int +MIXERCONTROL_CT_SC_LIST_MULTIPLE: int +MIXERCONTROL_CT_UNITS_MASK: int +MIXERCONTROL_CT_UNITS_CUSTOM: int +MIXERCONTROL_CT_UNITS_BOOLEAN: int +MIXERCONTROL_CT_UNITS_SIGNED: int +MIXERCONTROL_CT_UNITS_UNSIGNED: int +MIXERCONTROL_CT_UNITS_DECIBELS: int +MIXERCONTROL_CT_UNITS_PERCENT: int +MIXERCONTROL_CONTROLTYPE_CUSTOM: Incomplete +MIXERCONTROL_CONTROLTYPE_BOOLEANMETER: Incomplete +MIXERCONTROL_CONTROLTYPE_SIGNEDMETER: Incomplete +MIXERCONTROL_CONTROLTYPE_PEAKMETER: Incomplete +MIXERCONTROL_CONTROLTYPE_UNSIGNEDMETER: Incomplete +MIXERCONTROL_CONTROLTYPE_BOOLEAN: Incomplete +MIXERCONTROL_CONTROLTYPE_ONOFF: Incomplete +MIXERCONTROL_CONTROLTYPE_MUTE: Incomplete +MIXERCONTROL_CONTROLTYPE_MONO: Incomplete +MIXERCONTROL_CONTROLTYPE_LOUDNESS: Incomplete +MIXERCONTROL_CONTROLTYPE_STEREOENH: Incomplete +MIXERCONTROL_CONTROLTYPE_BUTTON: Incomplete +MIXERCONTROL_CONTROLTYPE_DECIBELS: Incomplete +MIXERCONTROL_CONTROLTYPE_SIGNED: Incomplete +MIXERCONTROL_CONTROLTYPE_UNSIGNED: Incomplete +MIXERCONTROL_CONTROLTYPE_PERCENT: Incomplete +MIXERCONTROL_CONTROLTYPE_SLIDER: Incomplete +MIXERCONTROL_CONTROLTYPE_PAN: Incomplete +MIXERCONTROL_CONTROLTYPE_QSOUNDPAN: Incomplete +MIXERCONTROL_CONTROLTYPE_FADER: Incomplete +MIXERCONTROL_CONTROLTYPE_VOLUME: Incomplete +MIXERCONTROL_CONTROLTYPE_BASS: Incomplete +MIXERCONTROL_CONTROLTYPE_TREBLE: Incomplete +MIXERCONTROL_CONTROLTYPE_EQUALIZER: Incomplete +MIXERCONTROL_CONTROLTYPE_SINGLESELECT: Incomplete +MIXERCONTROL_CONTROLTYPE_MUX: Incomplete +MIXERCONTROL_CONTROLTYPE_MULTIPLESELECT: Incomplete +MIXERCONTROL_CONTROLTYPE_MIXER: Incomplete +MIXERCONTROL_CONTROLTYPE_MICROTIME: Incomplete +MIXERCONTROL_CONTROLTYPE_MILLITIME: Incomplete +MIXER_GETLINECONTROLSF_ALL: int +MIXER_GETLINECONTROLSF_ONEBYID: int +MIXER_GETLINECONTROLSF_ONEBYTYPE: int +MIXER_GETLINECONTROLSF_QUERYMASK: int +MIXER_GETCONTROLDETAILSF_VALUE: int +MIXER_GETCONTROLDETAILSF_LISTTEXT: int +MIXER_GETCONTROLDETAILSF_QUERYMASK: int +MIXER_SETCONTROLDETAILSF_VALUE: int +MIXER_SETCONTROLDETAILSF_CUSTOM: int +MIXER_SETCONTROLDETAILSF_QUERYMASK: int +TIMERR_NOERROR: int +TIMERR_NOCANDO: Incomplete +TIMERR_STRUCT: Incomplete +TIME_ONESHOT: int +TIME_PERIODIC: int +TIME_CALLBACK_FUNCTION: int +TIME_CALLBACK_EVENT_SET: int +TIME_CALLBACK_EVENT_PULSE: int +JOYERR_NOERROR: int +JOYERR_PARMS: Incomplete +JOYERR_NOCANDO: Incomplete +JOYERR_UNPLUGGED: Incomplete +JOY_BUTTON1: int +JOY_BUTTON2: int +JOY_BUTTON3: int +JOY_BUTTON4: int +JOY_BUTTON1CHG: int +JOY_BUTTON2CHG: int +JOY_BUTTON3CHG: int +JOY_BUTTON4CHG: int +JOY_BUTTON5: int +JOY_BUTTON6: int +JOY_BUTTON7: int +JOY_BUTTON8: int +JOY_BUTTON9: int +JOY_BUTTON10: int +JOY_BUTTON11: int +JOY_BUTTON12: int +JOY_BUTTON13: int +JOY_BUTTON14: int +JOY_BUTTON15: int +JOY_BUTTON16: int +JOY_BUTTON17: int +JOY_BUTTON18: int +JOY_BUTTON19: int +JOY_BUTTON20: int +JOY_BUTTON21: int +JOY_BUTTON22: int +JOY_BUTTON23: int +JOY_BUTTON24: int +JOY_BUTTON25: int +JOY_BUTTON26: int +JOY_BUTTON27: int +JOY_BUTTON28: int +JOY_BUTTON29: int +JOY_BUTTON30: int +JOY_BUTTON31: int +JOY_BUTTON32: int +JOY_POVFORWARD: int +JOY_POVRIGHT: int +JOY_POVBACKWARD: int +JOY_POVLEFT: int +JOY_RETURNX: int +JOY_RETURNY: int +JOY_RETURNZ: int +JOY_RETURNR: int +JOY_RETURNU: int +JOY_RETURNV: int +JOY_RETURNPOV: int +JOY_RETURNBUTTONS: int +JOY_RETURNRAWDATA: int +JOY_RETURNPOVCTS: int +JOY_RETURNCENTERED: int +JOY_USEDEADZONE: int +JOY_RETURNALL: Incomplete +JOY_CAL_READALWAYS: int +JOY_CAL_READXYONLY: int +JOY_CAL_READ3: int +JOY_CAL_READ4: int +JOY_CAL_READXONLY: int +JOY_CAL_READYONLY: int +JOY_CAL_READ5: int +JOY_CAL_READ6: int +JOY_CAL_READZONLY: int +JOY_CAL_READRONLY: int +JOY_CAL_READUONLY: int +JOY_CAL_READVONLY: int +JOYSTICKID1: int +JOYSTICKID2: int +JOYCAPS_HASZ: int +JOYCAPS_HASR: int +JOYCAPS_HASU: int +JOYCAPS_HASV: int +JOYCAPS_HASPOV: int +JOYCAPS_POV4DIR: int +JOYCAPS_POVCTS: int +MMIOERR_BASE: int +MMIOERR_FILENOTFOUND: Incomplete +MMIOERR_OUTOFMEMORY: Incomplete +MMIOERR_CANNOTOPEN: Incomplete +MMIOERR_CANNOTCLOSE: Incomplete +MMIOERR_CANNOTREAD: Incomplete +MMIOERR_CANNOTWRITE: Incomplete +MMIOERR_CANNOTSEEK: Incomplete +MMIOERR_CANNOTEXPAND: Incomplete +MMIOERR_CHUNKNOTFOUND: Incomplete +MMIOERR_UNBUFFERED: Incomplete +MMIOERR_PATHNOTFOUND: Incomplete +MMIOERR_ACCESSDENIED: Incomplete +MMIOERR_SHARINGVIOLATION: Incomplete +MMIOERR_NETWORKERROR: Incomplete +MMIOERR_TOOMANYOPENFILES: Incomplete +MMIOERR_INVALIDFILE: Incomplete +CFSEPCHAR: Incomplete +MMIO_RWMODE: int +MMIO_SHAREMODE: int +MMIO_CREATE: int +MMIO_PARSE: int +MMIO_DELETE: int +MMIO_EXIST: int +MMIO_ALLOCBUF: int +MMIO_GETTEMP: int +MMIO_DIRTY: int +MMIO_READ: int +MMIO_WRITE: int +MMIO_READWRITE: int +MMIO_COMPAT: int +MMIO_EXCLUSIVE: int +MMIO_DENYWRITE: int +MMIO_DENYREAD: int +MMIO_DENYNONE: int +MMIO_FHOPEN: int +MMIO_EMPTYBUF: int +MMIO_TOUPPER: int +MMIO_INSTALLPROC: int +MMIO_GLOBALPROC: int +MMIO_REMOVEPROC: int +MMIO_UNICODEPROC: int +MMIO_FINDPROC: int +MMIO_FINDCHUNK: int +MMIO_FINDRIFF: int +MMIO_FINDLIST: int +MMIO_CREATERIFF: int +MMIO_CREATELIST: int +MMIOM_READ: int +MMIOM_WRITE: int +MMIOM_SEEK: int +MMIOM_OPEN: int +MMIOM_CLOSE: int +MMIOM_WRITEFLUSH: int +MMIOM_RENAME: int +MMIOM_USER: int +SEEK_SET: int +SEEK_CUR: int +SEEK_END: int +MMIO_DEFAULTBUFFER: int +MCIERR_INVALID_DEVICE_ID: Incomplete +MCIERR_UNRECOGNIZED_KEYWORD: Incomplete +MCIERR_UNRECOGNIZED_COMMAND: Incomplete +MCIERR_HARDWARE: Incomplete +MCIERR_INVALID_DEVICE_NAME: Incomplete +MCIERR_OUT_OF_MEMORY: Incomplete +MCIERR_DEVICE_OPEN: Incomplete +MCIERR_CANNOT_LOAD_DRIVER: Incomplete +MCIERR_MISSING_COMMAND_STRING: Incomplete +MCIERR_PARAM_OVERFLOW: Incomplete +MCIERR_MISSING_STRING_ARGUMENT: Incomplete +MCIERR_BAD_INTEGER: Incomplete +MCIERR_PARSER_INTERNAL: Incomplete +MCIERR_DRIVER_INTERNAL: Incomplete +MCIERR_MISSING_PARAMETER: Incomplete +MCIERR_UNSUPPORTED_FUNCTION: Incomplete +MCIERR_FILE_NOT_FOUND: Incomplete +MCIERR_DEVICE_NOT_READY: Incomplete +MCIERR_INTERNAL: Incomplete +MCIERR_DRIVER: Incomplete +MCIERR_CANNOT_USE_ALL: Incomplete +MCIERR_MULTIPLE: Incomplete +MCIERR_EXTENSION_NOT_FOUND: Incomplete +MCIERR_OUTOFRANGE: Incomplete +MCIERR_FLAGS_NOT_COMPATIBLE: Incomplete +MCIERR_FILE_NOT_SAVED: Incomplete +MCIERR_DEVICE_TYPE_REQUIRED: Incomplete +MCIERR_DEVICE_LOCKED: Incomplete +MCIERR_DUPLICATE_ALIAS: Incomplete +MCIERR_BAD_CONSTANT: Incomplete +MCIERR_MUST_USE_SHAREABLE: Incomplete +MCIERR_MISSING_DEVICE_NAME: Incomplete +MCIERR_BAD_TIME_FORMAT: Incomplete +MCIERR_NO_CLOSING_QUOTE: Incomplete +MCIERR_DUPLICATE_FLAGS: Incomplete +MCIERR_INVALID_FILE: Incomplete +MCIERR_NULL_PARAMETER_BLOCK: Incomplete +MCIERR_UNNAMED_RESOURCE: Incomplete +MCIERR_NEW_REQUIRES_ALIAS: Incomplete +MCIERR_NOTIFY_ON_AUTO_OPEN: Incomplete +MCIERR_NO_ELEMENT_ALLOWED: Incomplete +MCIERR_NONAPPLICABLE_FUNCTION: Incomplete +MCIERR_ILLEGAL_FOR_AUTO_OPEN: Incomplete +MCIERR_FILENAME_REQUIRED: Incomplete +MCIERR_EXTRA_CHARACTERS: Incomplete +MCIERR_DEVICE_NOT_INSTALLED: Incomplete +MCIERR_GET_CD: Incomplete +MCIERR_SET_CD: Incomplete +MCIERR_SET_DRIVE: Incomplete +MCIERR_DEVICE_LENGTH: Incomplete +MCIERR_DEVICE_ORD_LENGTH: Incomplete +MCIERR_NO_INTEGER: Incomplete +MCIERR_WAVE_OUTPUTSINUSE: Incomplete +MCIERR_WAVE_SETOUTPUTINUSE: Incomplete +MCIERR_WAVE_INPUTSINUSE: Incomplete +MCIERR_WAVE_SETINPUTINUSE: Incomplete +MCIERR_WAVE_OUTPUTUNSPECIFIED: Incomplete +MCIERR_WAVE_INPUTUNSPECIFIED: Incomplete +MCIERR_WAVE_OUTPUTSUNSUITABLE: Incomplete +MCIERR_WAVE_SETOUTPUTUNSUITABLE: Incomplete +MCIERR_WAVE_INPUTSUNSUITABLE: Incomplete +MCIERR_WAVE_SETINPUTUNSUITABLE: Incomplete +MCIERR_SEQ_DIV_INCOMPATIBLE: Incomplete +MCIERR_SEQ_PORT_INUSE: Incomplete +MCIERR_SEQ_PORT_NONEXISTENT: Incomplete +MCIERR_SEQ_PORT_MAPNODEVICE: Incomplete +MCIERR_SEQ_PORT_MISCERROR: Incomplete +MCIERR_SEQ_TIMER: Incomplete +MCIERR_SEQ_PORTUNSPECIFIED: Incomplete +MCIERR_SEQ_NOMIDIPRESENT: Incomplete +MCIERR_NO_WINDOW: Incomplete +MCIERR_CREATEWINDOW: Incomplete +MCIERR_FILE_READ: Incomplete +MCIERR_FILE_WRITE: Incomplete +MCIERR_NO_IDENTITY: Incomplete +MCIERR_CUSTOM_DRIVER_BASE: Incomplete +MCI_FIRST: int +MCI_OPEN: int +MCI_CLOSE: int +MCI_ESCAPE: int +MCI_PLAY: int +MCI_SEEK: int +MCI_STOP: int +MCI_PAUSE: int +MCI_INFO: int +MCI_GETDEVCAPS: int +MCI_SPIN: int +MCI_SET: int +MCI_STEP: int +MCI_RECORD: int +MCI_SYSINFO: int +MCI_BREAK: int +MCI_SAVE: int +MCI_STATUS: int +MCI_CUE: int +MCI_REALIZE: int +MCI_WINDOW: int +MCI_PUT: int +MCI_WHERE: int +MCI_FREEZE: int +MCI_UNFREEZE: int +MCI_LOAD: int +MCI_CUT: int +MCI_COPY: int +MCI_PASTE: int +MCI_UPDATE: int +MCI_RESUME: int +MCI_DELETE: int +MCI_USER_MESSAGES: Incomplete +MCI_LAST: int +MCI_DEVTYPE_VCR: int +MCI_DEVTYPE_VIDEODISC: int +MCI_DEVTYPE_OVERLAY: int +MCI_DEVTYPE_CD_AUDIO: int +MCI_DEVTYPE_DAT: int +MCI_DEVTYPE_SCANNER: int +MCI_DEVTYPE_ANIMATION: int +MCI_DEVTYPE_DIGITAL_VIDEO: int +MCI_DEVTYPE_OTHER: int +MCI_DEVTYPE_WAVEFORM_AUDIO: int +MCI_DEVTYPE_SEQUENCER: int +MCI_DEVTYPE_FIRST: int +MCI_DEVTYPE_LAST: int +MCI_DEVTYPE_FIRST_USER: int +MCI_MODE_NOT_READY: Incomplete +MCI_MODE_STOP: Incomplete +MCI_MODE_PLAY: Incomplete +MCI_MODE_RECORD: Incomplete +MCI_MODE_SEEK: Incomplete +MCI_MODE_PAUSE: Incomplete +MCI_MODE_OPEN: Incomplete +MCI_FORMAT_MILLISECONDS: int +MCI_FORMAT_HMS: int +MCI_FORMAT_MSF: int +MCI_FORMAT_FRAMES: int +MCI_FORMAT_SMPTE_24: int +MCI_FORMAT_SMPTE_25: int +MCI_FORMAT_SMPTE_30: int +MCI_FORMAT_SMPTE_30DROP: int +MCI_FORMAT_BYTES: int +MCI_FORMAT_SAMPLES: int +MCI_FORMAT_TMSF: int + +def MCI_MSF_MINUTE(msf): ... +def MCI_MSF_SECOND(msf): ... +def MCI_MSF_FRAME(msf): ... +def MCI_TMSF_TRACK(tmsf): ... +def MCI_TMSF_MINUTE(tmsf): ... +def MCI_TMSF_SECOND(tmsf): ... +def MCI_TMSF_FRAME(tmsf): ... +def MCI_HMS_HOUR(hms): ... +def MCI_HMS_MINUTE(hms): ... +def MCI_HMS_SECOND(hms): ... + +MCI_NOTIFY_SUCCESSFUL: int +MCI_NOTIFY_SUPERSEDED: int +MCI_NOTIFY_ABORTED: int +MCI_NOTIFY_FAILURE: int +MCI_NOTIFY: int +MCI_WAIT: int +MCI_FROM: int +MCI_TO: int +MCI_TRACK: int +MCI_OPEN_SHAREABLE: int +MCI_OPEN_ELEMENT: int +MCI_OPEN_ALIAS: int +MCI_OPEN_ELEMENT_ID: int +MCI_OPEN_TYPE_ID: int +MCI_OPEN_TYPE: int +MCI_SEEK_TO_START: int +MCI_SEEK_TO_END: int +MCI_STATUS_ITEM: int +MCI_STATUS_START: int +MCI_STATUS_LENGTH: int +MCI_STATUS_POSITION: int +MCI_STATUS_NUMBER_OF_TRACKS: int +MCI_STATUS_MODE: int +MCI_STATUS_MEDIA_PRESENT: int +MCI_STATUS_TIME_FORMAT: int +MCI_STATUS_READY: int +MCI_STATUS_CURRENT_TRACK: int +MCI_INFO_PRODUCT: int +MCI_INFO_FILE: int +MCI_INFO_MEDIA_UPC: int +MCI_INFO_MEDIA_IDENTITY: int +MCI_INFO_NAME: int +MCI_INFO_COPYRIGHT: int +MCI_GETDEVCAPS_ITEM: int +MCI_GETDEVCAPS_CAN_RECORD: int +MCI_GETDEVCAPS_HAS_AUDIO: int +MCI_GETDEVCAPS_HAS_VIDEO: int +MCI_GETDEVCAPS_DEVICE_TYPE: int +MCI_GETDEVCAPS_USES_FILES: int +MCI_GETDEVCAPS_COMPOUND_DEVICE: int +MCI_GETDEVCAPS_CAN_EJECT: int +MCI_GETDEVCAPS_CAN_PLAY: int +MCI_GETDEVCAPS_CAN_SAVE: int +MCI_SYSINFO_QUANTITY: int +MCI_SYSINFO_OPEN: int +MCI_SYSINFO_NAME: int +MCI_SYSINFO_INSTALLNAME: int +MCI_SET_DOOR_OPEN: int +MCI_SET_DOOR_CLOSED: int +MCI_SET_TIME_FORMAT: int +MCI_SET_AUDIO: int +MCI_SET_VIDEO: int +MCI_SET_ON: int +MCI_SET_OFF: int +MCI_SET_AUDIO_ALL: int +MCI_SET_AUDIO_LEFT: int +MCI_SET_AUDIO_RIGHT: int +MCI_BREAK_KEY: int +MCI_BREAK_HWND: int +MCI_BREAK_OFF: int +MCI_RECORD_INSERT: int +MCI_RECORD_OVERWRITE: int +MCI_SAVE_FILE: int +MCI_LOAD_FILE: int +MCI_VD_MODE_PARK: Incomplete +MCI_VD_MEDIA_CLV: Incomplete +MCI_VD_MEDIA_CAV: Incomplete +MCI_VD_MEDIA_OTHER: Incomplete +MCI_VD_FORMAT_TRACK: int +MCI_VD_PLAY_REVERSE: int +MCI_VD_PLAY_FAST: int +MCI_VD_PLAY_SPEED: int +MCI_VD_PLAY_SCAN: int +MCI_VD_PLAY_SLOW: int +MCI_VD_SEEK_REVERSE: int +MCI_VD_STATUS_SPEED: int +MCI_VD_STATUS_FORWARD: int +MCI_VD_STATUS_MEDIA_TYPE: int +MCI_VD_STATUS_SIDE: int +MCI_VD_STATUS_DISC_SIZE: int +MCI_VD_GETDEVCAPS_CLV: int +MCI_VD_GETDEVCAPS_CAV: int +MCI_VD_SPIN_UP: int +MCI_VD_SPIN_DOWN: int +MCI_VD_GETDEVCAPS_CAN_REVERSE: int +MCI_VD_GETDEVCAPS_FAST_RATE: int +MCI_VD_GETDEVCAPS_SLOW_RATE: int +MCI_VD_GETDEVCAPS_NORMAL_RATE: int +MCI_VD_STEP_FRAMES: int +MCI_VD_STEP_REVERSE: int +MCI_VD_ESCAPE_STRING: int +MCI_CDA_STATUS_TYPE_TRACK: int +MCI_CDA_TRACK_AUDIO: Incomplete +MCI_CDA_TRACK_OTHER: Incomplete +MCI_WAVE_PCM: Incomplete +MCI_WAVE_MAPPER: Incomplete +MCI_WAVE_OPEN_BUFFER: int +MCI_WAVE_SET_FORMATTAG: int +MCI_WAVE_SET_CHANNELS: int +MCI_WAVE_SET_SAMPLESPERSEC: int +MCI_WAVE_SET_AVGBYTESPERSEC: int +MCI_WAVE_SET_BLOCKALIGN: int +MCI_WAVE_SET_BITSPERSAMPLE: int +MCI_WAVE_INPUT: int +MCI_WAVE_OUTPUT: int +MCI_WAVE_STATUS_FORMATTAG: int +MCI_WAVE_STATUS_CHANNELS: int +MCI_WAVE_STATUS_SAMPLESPERSEC: int +MCI_WAVE_STATUS_AVGBYTESPERSEC: int +MCI_WAVE_STATUS_BLOCKALIGN: int +MCI_WAVE_STATUS_BITSPERSAMPLE: int +MCI_WAVE_STATUS_LEVEL: int +MCI_WAVE_SET_ANYINPUT: int +MCI_WAVE_SET_ANYOUTPUT: int +MCI_WAVE_GETDEVCAPS_INPUTS: int +MCI_WAVE_GETDEVCAPS_OUTPUTS: int +MCI_SEQ_DIV_PPQN: Incomplete +MCI_SEQ_DIV_SMPTE_24: Incomplete +MCI_SEQ_DIV_SMPTE_25: Incomplete +MCI_SEQ_DIV_SMPTE_30DROP: Incomplete +MCI_SEQ_DIV_SMPTE_30: Incomplete +MCI_SEQ_FORMAT_SONGPTR: int +MCI_SEQ_FILE: int +MCI_SEQ_MIDI: int +MCI_SEQ_SMPTE: int +MCI_SEQ_NONE: int +MCI_SEQ_MAPPER: int +MCI_SEQ_STATUS_TEMPO: int +MCI_SEQ_STATUS_PORT: int +MCI_SEQ_STATUS_SLAVE: int +MCI_SEQ_STATUS_MASTER: int +MCI_SEQ_STATUS_OFFSET: int +MCI_SEQ_STATUS_DIVTYPE: int +MCI_SEQ_STATUS_NAME: int +MCI_SEQ_STATUS_COPYRIGHT: int +MCI_SEQ_SET_TEMPO: int +MCI_SEQ_SET_PORT: int +MCI_SEQ_SET_SLAVE: int +MCI_SEQ_SET_MASTER: int +MCI_SEQ_SET_OFFSET: int +MCI_ANIM_OPEN_WS: int +MCI_ANIM_OPEN_PARENT: int +MCI_ANIM_OPEN_NOSTATIC: int +MCI_ANIM_PLAY_SPEED: int +MCI_ANIM_PLAY_REVERSE: int +MCI_ANIM_PLAY_FAST: int +MCI_ANIM_PLAY_SLOW: int +MCI_ANIM_PLAY_SCAN: int +MCI_ANIM_STEP_REVERSE: int +MCI_ANIM_STEP_FRAMES: int +MCI_ANIM_STATUS_SPEED: int +MCI_ANIM_STATUS_FORWARD: int +MCI_ANIM_STATUS_HWND: int +MCI_ANIM_STATUS_HPAL: int +MCI_ANIM_STATUS_STRETCH: int +MCI_ANIM_INFO_TEXT: int +MCI_ANIM_GETDEVCAPS_CAN_REVERSE: int +MCI_ANIM_GETDEVCAPS_FAST_RATE: int +MCI_ANIM_GETDEVCAPS_SLOW_RATE: int +MCI_ANIM_GETDEVCAPS_NORMAL_RATE: int +MCI_ANIM_GETDEVCAPS_PALETTES: int +MCI_ANIM_GETDEVCAPS_CAN_STRETCH: int +MCI_ANIM_GETDEVCAPS_MAX_WINDOWS: int +MCI_ANIM_REALIZE_NORM: int +MCI_ANIM_REALIZE_BKGD: int +MCI_ANIM_WINDOW_HWND: int +MCI_ANIM_WINDOW_STATE: int +MCI_ANIM_WINDOW_TEXT: int +MCI_ANIM_WINDOW_ENABLE_STRETCH: int +MCI_ANIM_WINDOW_DISABLE_STRETCH: int +MCI_ANIM_WINDOW_DEFAULT: int +MCI_ANIM_RECT: int +MCI_ANIM_PUT_SOURCE: int +MCI_ANIM_PUT_DESTINATION: int +MCI_ANIM_WHERE_SOURCE: int +MCI_ANIM_WHERE_DESTINATION: int +MCI_ANIM_UPDATE_HDC: int +MCI_OVLY_OPEN_WS: int +MCI_OVLY_OPEN_PARENT: int +MCI_OVLY_STATUS_HWND: int +MCI_OVLY_STATUS_STRETCH: int +MCI_OVLY_INFO_TEXT: int +MCI_OVLY_GETDEVCAPS_CAN_STRETCH: int +MCI_OVLY_GETDEVCAPS_CAN_FREEZE: int +MCI_OVLY_GETDEVCAPS_MAX_WINDOWS: int +MCI_OVLY_WINDOW_HWND: int +MCI_OVLY_WINDOW_STATE: int +MCI_OVLY_WINDOW_TEXT: int +MCI_OVLY_WINDOW_ENABLE_STRETCH: int +MCI_OVLY_WINDOW_DISABLE_STRETCH: int +MCI_OVLY_WINDOW_DEFAULT: int +MCI_OVLY_RECT: int +MCI_OVLY_PUT_SOURCE: int +MCI_OVLY_PUT_DESTINATION: int +MCI_OVLY_PUT_FRAME: int +MCI_OVLY_PUT_VIDEO: int +MCI_OVLY_WHERE_SOURCE: int +MCI_OVLY_WHERE_DESTINATION: int +MCI_OVLY_WHERE_FRAME: int +MCI_OVLY_WHERE_VIDEO: int +SELECTDIB: int + +def DIBINDEX(n): ... diff --git a/stubs/pywin32/win32/lib/ntsecuritycon.pyi b/stubs/pywin32/win32/lib/ntsecuritycon.pyi new file mode 100644 index 000000000000..7d4d6e8cc02c --- /dev/null +++ b/stubs/pywin32/win32/lib/ntsecuritycon.pyi @@ -0,0 +1,554 @@ +from typing import TypeAlias + +_SixIntTuple: TypeAlias = tuple[int, int, int, int, int, int] + +DELETE: int +READ_CONTROL: int +WRITE_DAC: int +WRITE_OWNER: int +SYNCHRONIZE: int +STANDARD_RIGHTS_REQUIRED: int +STANDARD_RIGHTS_READ: int +STANDARD_RIGHTS_WRITE: int +STANDARD_RIGHTS_EXECUTE: int +STANDARD_RIGHTS_ALL: int +SPECIFIC_RIGHTS_ALL: int +ACCESS_SYSTEM_SECURITY: int +MAXIMUM_ALLOWED: int +GENERIC_READ: int +GENERIC_WRITE: int +GENERIC_EXECUTE: int +GENERIC_ALL: int +FILE_READ_DATA: int +FILE_WRITE_DATA: int +FILE_ADD_FILE: int +FILE_APPEND_DATA: int +FILE_ADD_SUBDIRECTORY: int +FILE_CREATE_PIPE_INSTANCE: int +FILE_READ_EA: int +FILE_WRITE_EA: int +FILE_EXECUTE: int +FILE_TRAVERSE: int +FILE_DELETE_CHILD: int +FILE_READ_ATTRIBUTES: int +FILE_WRITE_ATTRIBUTES: int +FILE_ALL_ACCESS: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +FILE_GENERIC_EXECUTE: int +SECURITY_NULL_SID_AUTHORITY: _SixIntTuple +SECURITY_WORLD_SID_AUTHORITY: _SixIntTuple +SECURITY_LOCAL_SID_AUTHORITY: _SixIntTuple +SECURITY_CREATOR_SID_AUTHORITY: _SixIntTuple +SECURITY_NON_UNIQUE_AUTHORITY: _SixIntTuple +SECURITY_RESOURCE_MANAGER_AUTHORITY: _SixIntTuple +SECURITY_NULL_RID: int +SECURITY_WORLD_RID: int +SECURITY_LOCAL_RID: int +SECURITY_CREATOR_OWNER_RID: int +SECURITY_CREATOR_GROUP_RID: int +SECURITY_CREATOR_OWNER_SERVER_RID: int +SECURITY_CREATOR_GROUP_SERVER_RID: int +SECURITY_CREATOR_OWNER_RIGHTS_RID: int +SECURITY_NT_AUTHORITY: _SixIntTuple +SECURITY_DIALUP_RID: int +SECURITY_NETWORK_RID: int +SECURITY_BATCH_RID: int +SECURITY_INTERACTIVE_RID: int +SECURITY_SERVICE_RID: int +SECURITY_ANONYMOUS_LOGON_RID: int +SECURITY_PROXY_RID: int +SECURITY_SERVER_LOGON_RID: int +SECURITY_LOGON_IDS_RID: int +SECURITY_LOGON_IDS_RID_COUNT: int +SECURITY_LOCAL_SYSTEM_RID: int +SECURITY_NT_NON_UNIQUE: int +SECURITY_BUILTIN_DOMAIN_RID: int +DOMAIN_USER_RID_ADMIN: int +DOMAIN_USER_RID_GUEST: int +DOMAIN_USER_RID_KRBTGT: int +DOMAIN_USER_RID_MAX: int +DOMAIN_GROUP_RID_ADMINS: int +DOMAIN_GROUP_RID_USERS: int +DOMAIN_GROUP_RID_GUESTS: int +DOMAIN_GROUP_RID_COMPUTERS: int +DOMAIN_GROUP_RID_CONTROLLERS: int +DOMAIN_GROUP_RID_CERT_ADMINS: int +DOMAIN_GROUP_RID_SCHEMA_ADMINS: int +DOMAIN_GROUP_RID_ENTERPRISE_ADMINS: int +DOMAIN_GROUP_RID_POLICY_ADMINS: int +DOMAIN_GROUP_RID_READONLY_CONTROLLERS: int +DOMAIN_ALIAS_RID_ADMINS: int +DOMAIN_ALIAS_RID_USERS: int +DOMAIN_ALIAS_RID_GUESTS: int +DOMAIN_ALIAS_RID_POWER_USERS: int +DOMAIN_ALIAS_RID_ACCOUNT_OPS: int +DOMAIN_ALIAS_RID_SYSTEM_OPS: int +DOMAIN_ALIAS_RID_PRINT_OPS: int +DOMAIN_ALIAS_RID_BACKUP_OPS: int +DOMAIN_ALIAS_RID_REPLICATOR: int +DOMAIN_ALIAS_RID_RAS_SERVERS: int +DOMAIN_ALIAS_RID_PREW2KCOMPACCESS: int +DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS: int +DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS: int +DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS: int +DOMAIN_ALIAS_RID_MONITORING_USERS: int +DOMAIN_ALIAS_RID_LOGGING_USERS: int +DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS: int +DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS: int +DOMAIN_ALIAS_RID_DCOM_USERS: int +DOMAIN_ALIAS_RID_IUSERS: int +DOMAIN_ALIAS_RID_CRYPTO_OPERATORS: int +DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP: int +DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP: int +DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP: int +SECURITY_MANDATORY_LABEL_AUTHORITY: _SixIntTuple +SECURITY_MANDATORY_UNTRUSTED_RID: int +SECURITY_MANDATORY_LOW_RID: int +SECURITY_MANDATORY_MEDIUM_RID: int +SECURITY_MANDATORY_HIGH_RID: int +SECURITY_MANDATORY_SYSTEM_RID: int +SECURITY_MANDATORY_PROTECTED_PROCESS_RID: int +SECURITY_MANDATORY_MAXIMUM_USER_RID: int +SYSTEM_LUID: tuple[int, int] +ANONYMOUS_LOGON_LUID: tuple[int, int] +LOCALSERVICE_LUID: tuple[int, int] +NETWORKSERVICE_LUID: tuple[int, int] +IUSER_LUID: tuple[int, int] +SE_GROUP_MANDATORY: int +SE_GROUP_ENABLED_BY_DEFAULT: int +SE_GROUP_ENABLED: int +SE_GROUP_OWNER: int +SE_GROUP_USE_FOR_DENY_ONLY: int +SE_GROUP_INTEGRITY: int +SE_GROUP_INTEGRITY_ENABLED: int +SE_GROUP_RESOURCE: int +SE_GROUP_LOGON_ID: int +ACCESS_MIN_MS_ACE_TYPE: int +ACCESS_ALLOWED_ACE_TYPE: int +ACCESS_DENIED_ACE_TYPE: int +SYSTEM_AUDIT_ACE_TYPE: int +SYSTEM_ALARM_ACE_TYPE: int +ACCESS_MAX_MS_V2_ACE_TYPE: int +ACCESS_ALLOWED_COMPOUND_ACE_TYPE: int +ACCESS_MAX_MS_V3_ACE_TYPE: int +ACCESS_MIN_MS_OBJECT_ACE_TYPE: int +ACCESS_ALLOWED_OBJECT_ACE_TYPE: int +ACCESS_DENIED_OBJECT_ACE_TYPE: int +SYSTEM_AUDIT_OBJECT_ACE_TYPE: int +SYSTEM_ALARM_OBJECT_ACE_TYPE: int +ACCESS_MAX_MS_OBJECT_ACE_TYPE: int +ACCESS_MAX_MS_V4_ACE_TYPE: int +ACCESS_MAX_MS_ACE_TYPE: int +ACCESS_ALLOWED_CALLBACK_ACE_TYPE: int +ACCESS_DENIED_CALLBACK_ACE_TYPE: int +ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: int +ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_AUDIT_CALLBACK_ACE_TYPE: int +SYSTEM_ALARM_CALLBACK_ACE_TYPE: int +SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_MANDATORY_LABEL_ACE_TYPE: int +ACCESS_MAX_MS_V5_ACE_TYPE: int +OBJECT_INHERIT_ACE: int +CONTAINER_INHERIT_ACE: int +NO_PROPAGATE_INHERIT_ACE: int +INHERIT_ONLY_ACE: int +VALID_INHERIT_FLAGS: int +SUCCESSFUL_ACCESS_ACE_FLAG: int +FAILED_ACCESS_ACE_FLAG: int +SE_OWNER_DEFAULTED: int +SE_GROUP_DEFAULTED: int +SE_DACL_PRESENT: int +SE_DACL_DEFAULTED: int +SE_SACL_PRESENT: int +SE_SACL_DEFAULTED: int +SE_SELF_RELATIVE: int +SE_PRIVILEGE_ENABLED_BY_DEFAULT: int +SE_PRIVILEGE_ENABLED: int +SE_PRIVILEGE_USED_FOR_ACCESS: int +PRIVILEGE_SET_ALL_NECESSARY: int +SE_CREATE_TOKEN_NAME: str +SE_ASSIGNPRIMARYTOKEN_NAME: str +SE_LOCK_MEMORY_NAME: str +SE_INCREASE_QUOTA_NAME: str +SE_UNSOLICITED_INPUT_NAME: str +SE_MACHINE_ACCOUNT_NAME: str +SE_TCB_NAME: str +SE_SECURITY_NAME: str +SE_TAKE_OWNERSHIP_NAME: str +SE_LOAD_DRIVER_NAME: str +SE_SYSTEM_PROFILE_NAME: str +SE_SYSTEMTIME_NAME: str +SE_PROF_SINGLE_PROCESS_NAME: str +SE_INC_BASE_PRIORITY_NAME: str +SE_CREATE_PAGEFILE_NAME: str +SE_CREATE_PERMANENT_NAME: str +SE_BACKUP_NAME: str +SE_RESTORE_NAME: str +SE_SHUTDOWN_NAME: str +SE_DEBUG_NAME: str +SE_AUDIT_NAME: str +SE_SYSTEM_ENVIRONMENT_NAME: str +SE_CHANGE_NOTIFY_NAME: str +SE_REMOTE_SHUTDOWN_NAME: str +SecurityAnonymous: int +SecurityIdentification: int +SecurityImpersonation: int +SecurityDelegation: int +SECURITY_MAX_IMPERSONATION_LEVEL: int +DEFAULT_IMPERSONATION_LEVEL: int +TOKEN_ASSIGN_PRIMARY: int +TOKEN_DUPLICATE: int +TOKEN_IMPERSONATE: int +TOKEN_QUERY: int +TOKEN_QUERY_SOURCE: int +TOKEN_ADJUST_PRIVILEGES: int +TOKEN_ADJUST_GROUPS: int +TOKEN_ADJUST_DEFAULT: int +TOKEN_ALL_ACCESS: int +TOKEN_READ: int +TOKEN_WRITE: int +TOKEN_EXECUTE: int +SidTypeUser: int +SidTypeGroup: int +SidTypeDomain: int +SidTypeAlias: int +SidTypeWellKnownGroup: int +SidTypeDeletedAccount: int +SidTypeInvalid: int +SidTypeUnknown: int +SidTypeComputer: int +SidTypeLabel: int +TokenPrimary: int +TokenImpersonation: int +TokenUser: int +TokenGroups: int +TokenPrivileges: int +TokenOwner: int +TokenPrimaryGroup: int +TokenDefaultDacl: int +TokenSource: int +TokenType: int +TokenImpersonationLevel: int +TokenStatistics: int +TokenRestrictedSids: int +TokenSessionId: int +TokenGroupsAndPrivileges: int +TokenSessionReference: int +TokenSandBoxInert: int +TokenAuditPolicy: int +TokenOrigin: int +TokenElevationType: int +TokenLinkedToken: int +TokenElevation: int +TokenHasRestrictions: int +TokenAccessInformation: int +TokenVirtualizationAllowed: int +TokenVirtualizationEnabled: int +TokenIntegrityLevel: int +TokenUIAccess: int +TokenMandatoryPolicy: int +TokenLogonSid: int +DS_BEHAVIOR_WIN2000: int +DS_BEHAVIOR_WIN2003_WITH_MIXED_DOMAINS: int +DS_BEHAVIOR_WIN2003: int +DS_SYNCED_EVENT_NAME: str +ACTRL_DS_OPEN: int +ACTRL_DS_CREATE_CHILD: int +ACTRL_DS_DELETE_CHILD: int +ACTRL_DS_SELF: int +ACTRL_DS_READ_PROP: int +ACTRL_DS_WRITE_PROP: int +ACTRL_DS_DELETE_TREE: int +ACTRL_DS_CONTROL_ACCESS: int +NTDSAPI_BIND_ALLOW_DELEGATION: int +DS_REPSYNC_ASYNCHRONOUS_OPERATION: int +DS_REPSYNC_WRITEABLE: int +DS_REPSYNC_PERIODIC: int +DS_REPSYNC_INTERSITE_MESSAGING: int +DS_REPSYNC_ALL_SOURCES: int +DS_REPSYNC_FULL: int +DS_REPSYNC_URGENT: int +DS_REPSYNC_NO_DISCARD: int +DS_REPSYNC_FORCE: int +DS_REPSYNC_ADD_REFERENCE: int +DS_REPSYNC_NEVER_COMPLETED: int +DS_REPSYNC_TWO_WAY: int +DS_REPSYNC_NEVER_NOTIFY: int +DS_REPSYNC_INITIAL: int +DS_REPSYNC_USE_COMPRESSION: int +DS_REPSYNC_ABANDONED: int +DS_REPSYNC_INITIAL_IN_PROGRESS: int +DS_REPSYNC_PARTIAL_ATTRIBUTE_SET: int +DS_REPSYNC_REQUEUE: int +DS_REPSYNC_NOTIFICATION: int +DS_REPSYNC_ASYNCHRONOUS_REPLICA: int +DS_REPSYNC_CRITICAL: int +DS_REPSYNC_FULL_IN_PROGRESS: int +DS_REPSYNC_PREEMPTED: int +DS_REPADD_ASYNCHRONOUS_OPERATION: int +DS_REPADD_WRITEABLE: int +DS_REPADD_INITIAL: int +DS_REPADD_PERIODIC: int +DS_REPADD_INTERSITE_MESSAGING: int +DS_REPADD_ASYNCHRONOUS_REPLICA: int +DS_REPADD_DISABLE_NOTIFICATION: int +DS_REPADD_DISABLE_PERIODIC: int +DS_REPADD_USE_COMPRESSION: int +DS_REPADD_NEVER_NOTIFY: int +DS_REPADD_TWO_WAY: int +DS_REPADD_CRITICAL: int +DS_REPDEL_ASYNCHRONOUS_OPERATION: int +DS_REPDEL_WRITEABLE: int +DS_REPDEL_INTERSITE_MESSAGING: int +DS_REPDEL_IGNORE_ERRORS: int +DS_REPDEL_LOCAL_ONLY: int +DS_REPDEL_NO_SOURCE: int +DS_REPDEL_REF_OK: int +DS_REPMOD_ASYNCHRONOUS_OPERATION: int +DS_REPMOD_WRITEABLE: int +DS_REPMOD_UPDATE_FLAGS: int +DS_REPMOD_UPDATE_ADDRESS: int +DS_REPMOD_UPDATE_SCHEDULE: int +DS_REPMOD_UPDATE_RESULT: int +DS_REPMOD_UPDATE_TRANSPORT: int +DS_REPUPD_ASYNCHRONOUS_OPERATION: int +DS_REPUPD_WRITEABLE: int +DS_REPUPD_ADD_REFERENCE: int +DS_REPUPD_DELETE_REFERENCE: int +DS_INSTANCETYPE_IS_NC_HEAD: int +DS_INSTANCETYPE_NC_IS_WRITEABLE: int +DS_INSTANCETYPE_NC_COMING: int +DS_INSTANCETYPE_NC_GOING: int +NTDSDSA_OPT_IS_GC: int +NTDSDSA_OPT_DISABLE_INBOUND_REPL: int +NTDSDSA_OPT_DISABLE_OUTBOUND_REPL: int +NTDSDSA_OPT_DISABLE_NTDSCONN_XLATE: int +NTDSCONN_OPT_IS_GENERATED: int +NTDSCONN_OPT_TWOWAY_SYNC: int +NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT: int +NTDSCONN_OPT_USE_NOTIFY: int +NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION: int +NTDSCONN_OPT_USER_OWNED_SCHEDULE: int +NTDSCONN_KCC_NO_REASON: int +NTDSCONN_KCC_GC_TOPOLOGY: int +NTDSCONN_KCC_RING_TOPOLOGY: int +NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY: int +NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY: int +NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY: int +NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY: int +NTDSCONN_KCC_INTERSITE_TOPOLOGY: int +NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY: int +NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY: int +NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY: int +FRSCONN_PRIORITY_MASK: int +FRSCONN_MAX_PRIORITY: int +NTDSCONN_OPT_IGNORE_SCHEDULE_MASK: int +NTDSSETTINGS_OPT_IS_AUTO_TOPOLOGY_DISABLED: int +NTDSSETTINGS_OPT_IS_TOPL_CLEANUP_DISABLED: int +NTDSSETTINGS_OPT_IS_TOPL_MIN_HOPS_DISABLED: int +NTDSSETTINGS_OPT_IS_TOPL_DETECT_STALE_DISABLED: int +NTDSSETTINGS_OPT_IS_INTER_SITE_AUTO_TOPOLOGY_DISABLED: int +NTDSSETTINGS_OPT_IS_GROUP_CACHING_ENABLED: int +NTDSSETTINGS_OPT_FORCE_KCC_WHISTLER_BEHAVIOR: int +NTDSSETTINGS_OPT_FORCE_KCC_W2K_ELECTION: int +NTDSSETTINGS_OPT_IS_RAND_BH_SELECTION_DISABLED: int +NTDSSETTINGS_OPT_IS_SCHEDULE_HASHING_ENABLED: int +NTDSSETTINGS_OPT_IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED: int +NTDSSETTINGS_DEFAULT_SERVER_REDUNDANCY: int +NTDSTRANSPORT_OPT_IGNORE_SCHEDULES: int +NTDSTRANSPORT_OPT_BRIDGES_REQUIRED: int +NTDSSITECONN_OPT_USE_NOTIFY: int +NTDSSITECONN_OPT_TWOWAY_SYNC: int +NTDSSITECONN_OPT_DISABLE_COMPRESSION: int +NTDSSITELINK_OPT_USE_NOTIFY: int +NTDSSITELINK_OPT_TWOWAY_SYNC: int +NTDSSITELINK_OPT_DISABLE_COMPRESSION: int +GUID_USERS_CONTAINER_A: str +GUID_COMPUTRS_CONTAINER_A: str +GUID_SYSTEMS_CONTAINER_A: str +GUID_DOMAIN_CONTROLLERS_CONTAINER_A: str +GUID_INFRASTRUCTURE_CONTAINER_A: str +GUID_DELETED_OBJECTS_CONTAINER_A: str +GUID_LOSTANDFOUND_CONTAINER_A: str +GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_A: str +GUID_PROGRAM_DATA_CONTAINER_A: str +GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_A: str +GUID_NTDS_QUOTAS_CONTAINER_A: str +GUID_USERS_CONTAINER_BYTE: str +GUID_COMPUTRS_CONTAINER_BYTE: str +GUID_SYSTEMS_CONTAINER_BYTE: str +GUID_DOMAIN_CONTROLLERS_CONTAINER_BYTE: str +GUID_INFRASTRUCTURE_CONTAINER_BYTE: str +GUID_DELETED_OBJECTS_CONTAINER_BYTE: str +GUID_LOSTANDFOUND_CONTAINER_BYTE: str +GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE: str +GUID_PROGRAM_DATA_CONTAINER_BYTE: str +GUID_MICROSOFT_PROGRAM_DATA_CONTAINER_BYTE: str +GUID_NTDS_QUOTAS_CONTAINER_BYTE: str +DS_REPSYNCALL_NO_OPTIONS: int +DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE: int +DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY: int +DS_REPSYNCALL_ID_SERVERS_BY_DN: int +DS_REPSYNCALL_DO_NOT_SYNC: int +DS_REPSYNCALL_SKIP_INITIAL_CHECK: int +DS_REPSYNCALL_PUSH_CHANGES_OUTWARD: int +DS_REPSYNCALL_CROSS_SITE_BOUNDARIES: int +DS_ROLE_SCHEMA_OWNER: int +DS_ROLE_DOMAIN_OWNER: int +DS_ROLE_PDC_OWNER: int +DS_ROLE_RID_OWNER: int +DS_ROLE_INFRASTRUCTURE_OWNER: int +DS_SCHEMA_GUID_NOT_FOUND: int +DS_SCHEMA_GUID_ATTR: int +DS_SCHEMA_GUID_ATTR_SET: int +DS_SCHEMA_GUID_CLASS: int +DS_SCHEMA_GUID_CONTROL_RIGHT: int +DS_KCC_FLAG_ASYNC_OP: int +DS_KCC_FLAG_DAMPED: int +DS_EXIST_ADVISORY_MODE: int +DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS: int +DS_REPL_NBR_WRITEABLE: int +DS_REPL_NBR_SYNC_ON_STARTUP: int +DS_REPL_NBR_DO_SCHEDULED_SYNCS: int +DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT: int +DS_REPL_NBR_TWO_WAY_SYNC: int +DS_REPL_NBR_RETURN_OBJECT_PARENTS: int +DS_REPL_NBR_FULL_SYNC_IN_PROGRESS: int +DS_REPL_NBR_FULL_SYNC_NEXT_PACKET: int +DS_REPL_NBR_NEVER_SYNCED: int +DS_REPL_NBR_PREEMPTED: int +DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS: int +DS_REPL_NBR_DISABLE_SCHEDULED_SYNC: int +DS_REPL_NBR_COMPRESS_CHANGES: int +DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS: int +DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET: int +DS_REPL_NBR_MODIFIABLE_MASK: int +DS_UNKNOWN_NAME: int +DS_FQDN_1779_NAME: int +DS_NT4_ACCOUNT_NAME: int +DS_DISPLAY_NAME: int +DS_UNIQUE_ID_NAME: int +DS_CANONICAL_NAME: int +DS_USER_PRINCIPAL_NAME: int +DS_CANONICAL_NAME_EX: int +DS_SERVICE_PRINCIPAL_NAME: int +DS_SID_OR_SID_HISTORY_NAME: int +DS_DNS_DOMAIN_NAME: int +DS_DOMAIN_SIMPLE_NAME: int +DS_ENTERPRISE_SIMPLE_NAME: int +DS_NAME_NO_FLAGS: int +DS_NAME_FLAG_SYNTACTICAL_ONLY: int +DS_NAME_FLAG_EVAL_AT_DC: int +DS_NAME_FLAG_GCVERIFY: int +DS_NAME_FLAG_TRUST_REFERRAL: int +DS_NAME_NO_ERROR: int +DS_NAME_ERROR_RESOLVING: int +DS_NAME_ERROR_NOT_FOUND: int +DS_NAME_ERROR_NOT_UNIQUE: int +DS_NAME_ERROR_NO_MAPPING: int +DS_NAME_ERROR_DOMAIN_ONLY: int +DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: int +DS_NAME_ERROR_TRUST_REFERRAL: int +DS_SPN_DNS_HOST: int +DS_SPN_DN_HOST: int +DS_SPN_NB_HOST: int +DS_SPN_DOMAIN: int +DS_SPN_NB_DOMAIN: int +DS_SPN_SERVICE: int +DS_SPN_ADD_SPN_OP: int +DS_SPN_REPLACE_SPN_OP: int +DS_SPN_DELETE_SPN_OP: int +DS_FORCE_REDISCOVERY: int +DS_DIRECTORY_SERVICE_REQUIRED: int +DS_DIRECTORY_SERVICE_PREFERRED: int +DS_GC_SERVER_REQUIRED: int +DS_PDC_REQUIRED: int +DS_BACKGROUND_ONLY: int +DS_IP_REQUIRED: int +DS_KDC_REQUIRED: int +DS_TIMESERV_REQUIRED: int +DS_WRITABLE_REQUIRED: int +DS_GOOD_TIMESERV_PREFERRED: int +DS_AVOID_SELF: int +DS_ONLY_LDAP_NEEDED: int +DS_IS_FLAT_NAME: int +DS_IS_DNS_NAME: int +DS_RETURN_DNS_NAME: int +DS_RETURN_FLAT_NAME: int +DSGETDC_VALID_FLAGS: int +DS_INET_ADDRESS: int +DS_NETBIOS_ADDRESS: int +DS_PDC_FLAG: int +DS_GC_FLAG: int +DS_LDAP_FLAG: int +DS_DS_FLAG: int +DS_KDC_FLAG: int +DS_TIMESERV_FLAG: int +DS_CLOSEST_FLAG: int +DS_WRITABLE_FLAG: int +DS_GOOD_TIMESERV_FLAG: int +DS_NDNC_FLAG: int +DS_PING_FLAGS: int +DS_DNS_CONTROLLER_FLAG: int +DS_DNS_DOMAIN_FLAG: int +DS_DNS_FOREST_FLAG: int +DS_DOMAIN_IN_FOREST: int +DS_DOMAIN_DIRECT_OUTBOUND: int +DS_DOMAIN_TREE_ROOT: int +DS_DOMAIN_PRIMARY: int +DS_DOMAIN_NATIVE_MODE: int +DS_DOMAIN_DIRECT_INBOUND: int +DS_DOMAIN_VALID_FLAGS: int +DS_GFTI_UPDATE_TDO: int +DS_GFTI_VALID_FLAGS: int +DS_ONLY_DO_SITE_NAME: int +DS_NOTIFY_AFTER_SITE_RECORDS: int +DS_OPEN_VALID_OPTION_FLAGS: int +DS_OPEN_VALID_FLAGS: int +SI_EDIT_PERMS: int +SI_EDIT_OWNER: int +SI_EDIT_AUDITS: int +SI_CONTAINER: int +SI_READONLY: int +SI_ADVANCED: int +SI_RESET: int +SI_OWNER_READONLY: int +SI_EDIT_PROPERTIES: int +SI_OWNER_RECURSE: int +SI_NO_ACL_PROTECT: int +SI_NO_TREE_APPLY: int +SI_PAGE_TITLE: int +SI_SERVER_IS_DC: int +SI_RESET_DACL_TREE: int +SI_RESET_SACL_TREE: int +SI_OBJECT_GUID: int +SI_EDIT_EFFECTIVE: int +SI_RESET_DACL: int +SI_RESET_SACL: int +SI_RESET_OWNER: int +SI_NO_ADDITIONAL_PERMISSION: int +SI_MAY_WRITE: int +SI_EDIT_ALL: int +SI_AUDITS_ELEVATION_REQUIRED: int +SI_VIEW_ONLY: int +SI_OWNER_ELEVATION_REQUIRED: int +SI_PERMS_ELEVATION_REQUIRED: int +SI_ACCESS_SPECIFIC: int +SI_ACCESS_GENERAL: int +SI_ACCESS_CONTAINER: int +SI_ACCESS_PROPERTY: int +SI_PAGE_PERM: int +SI_PAGE_ADVPERM: int +SI_PAGE_AUDIT: int +SI_PAGE_OWNER: int +SI_PAGE_EFFECTIVE: int +PSPCB_SI_INITDIALOG: int +ACTRL_DS_LIST: int +ACTRL_DS_LIST_OBJECT: int +CFSTR_ACLUI_SID_INFO_LIST: str +DS_LIST_ACCOUNT_OBJECT_FOR_SERVER: int +DS_LIST_DNS_HOST_NAME_FOR_SERVER: int +DS_LIST_DSA_OBJECT_FOR_SERVER: int +FILE_LIST_DIRECTORY: int diff --git a/stubs/pywin32/win32/lib/pywintypes.pyi b/stubs/pywin32/win32/lib/pywintypes.pyi new file mode 100644 index 000000000000..e4965177a0c0 --- /dev/null +++ b/stubs/pywin32/win32/lib/pywintypes.pyi @@ -0,0 +1,51 @@ +# Can't generate with stubgen because `import pywintypes` must be called first. +# Otherwise you get the error: "KeyError: 'pywintypes'" +from _typeshed import Incomplete +from collections.abc import Sequence +from datetime import datetime +from typing import ClassVar, Final, SupportsInt, overload +from typing_extensions import deprecated + +import _win32typing + +class error(Exception): + winerror: int + funcname: str + strerror: str + def __init__(self, winerror: int, funcname: str, strerror: str, /): ... + +class com_error(Exception): ... + +class TimeType(datetime): # aka: PyTime, PyDateTime + __name__: ClassVar[str] = "datetime" + def Format(self, format: str = "%c") -> str: ... + +HANDLEType = _win32typing.PyHANDLE +DEVMODEType = _win32typing.PyDEVMODEW +DEVMODEWType = _win32typing.PyDEVMODEW +IIDType = _win32typing.PyIID + +def DosDateTimeToTime(FatDate: int, FatTime: int, /) -> TimeType: ... +def UnicodeFromRaw(_str: str, /) -> str: ... +def IsTextUnicode(_str: str, flags, /) -> tuple[Incomplete, Incomplete]: ... +def OVERLAPPED() -> _win32typing.PyOVERLAPPED: ... +def IID(iidString: str, is_bytes: bool = ..., /) -> _win32typing.PyIID: ... +def Time(timeRepr: SupportsInt | Sequence[SupportsInt] | TimeType, /) -> TimeType: ... +def CreateGuid() -> _win32typing.PyIID: ... +def ACL(bufSize: int = ..., /) -> _win32typing.PyACL: ... +def SID(buffer, idAuthority, subAuthorities, bufSize=..., /) -> _win32typing.PySID: ... +def SECURITY_ATTRIBUTES() -> _win32typing.PySECURITY_ATTRIBUTES: ... +def SECURITY_DESCRIPTOR() -> _win32typing.PySECURITY_DESCRIPTOR: ... +def HANDLE() -> _win32typing.PyHANDLE: ... +def HKEY() -> _win32typing.PyHKEY: ... +def WAVEFORMATEX() -> _win32typing.PyWAVEFORMATEX: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def TimeStamp(timestamp: tuple[int, int], /) -> TimeType: ... +@overload +def TimeStamp(timestamp: int, /) -> TimeType: ... + +FALSE: Final = False +TRUE: Final = True +WAVE_FORMAT_PCM: int diff --git a/stubs/pywin32/win32/lib/regutil.pyi b/stubs/pywin32/win32/lib/regutil.pyi new file mode 100644 index 000000000000..60a3e80cc6bc --- /dev/null +++ b/stubs/pywin32/win32/lib/regutil.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +CLSIDPyFile: str +RegistryIDPyFile: str +RegistryIDPycFile: str + +def BuildDefaultPythonKey(): ... +def GetRootKey(): ... +def GetRegistryDefaultValue(subkey, rootkey: Incomplete | None = ...): ... +def SetRegistryDefaultValue(subKey, value, rootkey: Incomplete | None = ...) -> None: ... +def GetAppPathsKey(): ... +def RegisterPythonExe(exeFullPath, exeAlias: Incomplete | None = ..., exeAppPath: Incomplete | None = ...) -> None: ... +def GetRegisteredExe(exeAlias): ... +def UnregisterPythonExe(exeAlias) -> None: ... +def RegisterNamedPath(name, path) -> None: ... +def UnregisterNamedPath(name) -> None: ... +def GetRegisteredNamedPath(name): ... +def RegisterModule(modName, modPath) -> None: ... +def UnregisterModule(modName) -> None: ... +def GetRegisteredHelpFile(helpDesc): ... +def RegisterHelpFile(helpFile, helpPath, helpDesc: Incomplete | None = ..., bCheckFile: int = ...) -> None: ... +def UnregisterHelpFile(helpFile, helpDesc: Incomplete | None = ...) -> None: ... +def RegisterCoreDLL(coredllName: Incomplete | None = ...) -> None: ... +def RegisterFileExtensions(defPyIcon, defPycIcon, runCommand) -> None: ... +def RegisterShellCommand(shellCommand, exeCommand, shellUserCommand: Incomplete | None = ...) -> None: ... +def RegisterDDECommand(shellCommand, ddeApp, ddeTopic, ddeCommand) -> None: ... diff --git a/stubs/pywin32/win32/lib/sspicon.pyi b/stubs/pywin32/win32/lib/sspicon.pyi new file mode 100644 index 000000000000..978a4370bd58 --- /dev/null +++ b/stubs/pywin32/win32/lib/sspicon.pyi @@ -0,0 +1,457 @@ +ISSP_LEVEL: int +ISSP_MODE: int + +def SEC_SUCCESS(Status: int) -> bool: ... + +SECPKG_FLAG_INTEGRITY: int +SECPKG_FLAG_PRIVACY: int +SECPKG_FLAG_TOKEN_ONLY: int +SECPKG_FLAG_DATAGRAM: int +SECPKG_FLAG_CONNECTION: int +SECPKG_FLAG_MULTI_REQUIRED: int +SECPKG_FLAG_CLIENT_ONLY: int +SECPKG_FLAG_EXTENDED_ERROR: int +SECPKG_FLAG_IMPERSONATION: int +SECPKG_FLAG_ACCEPT_WIN32_NAME: int +SECPKG_FLAG_STREAM: int +SECPKG_FLAG_NEGOTIABLE: int +SECPKG_FLAG_GSS_COMPATIBLE: int +SECPKG_FLAG_LOGON: int +SECPKG_FLAG_ASCII_BUFFERS: int +SECPKG_FLAG_FRAGMENT: int +SECPKG_FLAG_MUTUAL_AUTH: int +SECPKG_FLAG_DELEGATION: int +SECPKG_FLAG_READONLY_WITH_CHECKSUM: int +SECPKG_ID_NONE: int +SECBUFFER_VERSION: int +SECBUFFER_EMPTY: int +SECBUFFER_DATA: int +SECBUFFER_TOKEN: int +SECBUFFER_PKG_PARAMS: int +SECBUFFER_MISSING: int +SECBUFFER_EXTRA: int +SECBUFFER_STREAM_TRAILER: int +SECBUFFER_STREAM_HEADER: int +SECBUFFER_NEGOTIATION_INFO: int +SECBUFFER_PADDING: int +SECBUFFER_STREAM: int +SECBUFFER_TARGET: int +SECBUFFER_CHANNEL_BINDINGS: int +SECBUFFER_ATTRMASK: int +SECBUFFER_READONLY: int +SECBUFFER_READONLY_WITH_CHECKSUM: int +SECBUFFER_RESERVED: int +SECURITY_NATIVE_DREP: int +SECURITY_NETWORK_DREP: int +SECPKG_CRED_INBOUND: int +SECPKG_CRED_OUTBOUND: int +SECPKG_CRED_BOTH: int +SECPKG_CRED_DEFAULT: int +SECPKG_CRED_RESERVED: int +ISC_REQ_DELEGATE: int +ISC_REQ_MUTUAL_AUTH: int +ISC_REQ_REPLAY_DETECT: int +ISC_REQ_SEQUENCE_DETECT: int +ISC_REQ_CONFIDENTIALITY: int +ISC_REQ_USE_SESSION_KEY: int +ISC_REQ_PROMPT_FOR_CREDS: int +ISC_REQ_USE_SUPPLIED_CREDS: int +ISC_REQ_ALLOCATE_MEMORY: int +ISC_REQ_USE_DCE_STYLE: int +ISC_REQ_DATAGRAM: int +ISC_REQ_CONNECTION: int +ISC_REQ_CALL_LEVEL: int +ISC_REQ_FRAGMENT_SUPPLIED: int +ISC_REQ_EXTENDED_ERROR: int +ISC_REQ_STREAM: int +ISC_REQ_INTEGRITY: int +ISC_REQ_IDENTIFY: int +ISC_REQ_NULL_SESSION: int +ISC_REQ_MANUAL_CRED_VALIDATION: int +ISC_REQ_RESERVED1: int +ISC_REQ_FRAGMENT_TO_FIT: int +ISC_REQ_HTTP: int +ISC_RET_DELEGATE: int +ISC_RET_MUTUAL_AUTH: int +ISC_RET_REPLAY_DETECT: int +ISC_RET_SEQUENCE_DETECT: int +ISC_RET_CONFIDENTIALITY: int +ISC_RET_USE_SESSION_KEY: int +ISC_RET_USED_COLLECTED_CREDS: int +ISC_RET_USED_SUPPLIED_CREDS: int +ISC_RET_ALLOCATED_MEMORY: int +ISC_RET_USED_DCE_STYLE: int +ISC_RET_DATAGRAM: int +ISC_RET_CONNECTION: int +ISC_RET_INTERMEDIATE_RETURN: int +ISC_RET_CALL_LEVEL: int +ISC_RET_EXTENDED_ERROR: int +ISC_RET_STREAM: int +ISC_RET_INTEGRITY: int +ISC_RET_IDENTIFY: int +ISC_RET_NULL_SESSION: int +ISC_RET_MANUAL_CRED_VALIDATION: int +ISC_RET_RESERVED1: int +ISC_RET_FRAGMENT_ONLY: int +ASC_REQ_DELEGATE: int +ASC_REQ_MUTUAL_AUTH: int +ASC_REQ_REPLAY_DETECT: int +ASC_REQ_SEQUENCE_DETECT: int +ASC_REQ_CONFIDENTIALITY: int +ASC_REQ_USE_SESSION_KEY: int +ASC_REQ_ALLOCATE_MEMORY: int +ASC_REQ_USE_DCE_STYLE: int +ASC_REQ_DATAGRAM: int +ASC_REQ_CONNECTION: int +ASC_REQ_CALL_LEVEL: int +ASC_REQ_EXTENDED_ERROR: int +ASC_REQ_STREAM: int +ASC_REQ_INTEGRITY: int +ASC_REQ_LICENSING: int +ASC_REQ_IDENTIFY: int +ASC_REQ_ALLOW_NULL_SESSION: int +ASC_REQ_ALLOW_NON_USER_LOGONS: int +ASC_REQ_ALLOW_CONTEXT_REPLAY: int +ASC_REQ_FRAGMENT_TO_FIT: int +ASC_REQ_FRAGMENT_SUPPLIED: int +ASC_REQ_NO_TOKEN: int +ASC_RET_DELEGATE: int +ASC_RET_MUTUAL_AUTH: int +ASC_RET_REPLAY_DETECT: int +ASC_RET_SEQUENCE_DETECT: int +ASC_RET_CONFIDENTIALITY: int +ASC_RET_USE_SESSION_KEY: int +ASC_RET_ALLOCATED_MEMORY: int +ASC_RET_USED_DCE_STYLE: int +ASC_RET_DATAGRAM: int +ASC_RET_CONNECTION: int +ASC_RET_CALL_LEVEL: int +ASC_RET_THIRD_LEG_FAILED: int +ASC_RET_EXTENDED_ERROR: int +ASC_RET_STREAM: int +ASC_RET_INTEGRITY: int +ASC_RET_LICENSING: int +ASC_RET_IDENTIFY: int +ASC_RET_NULL_SESSION: int +ASC_RET_ALLOW_NON_USER_LOGONS: int +ASC_RET_ALLOW_CONTEXT_REPLAY: int +ASC_RET_FRAGMENT_ONLY: int +SECPKG_CRED_ATTR_NAMES: int +SECPKG_ATTR_SIZES: int +SECPKG_ATTR_NAMES: int +SECPKG_ATTR_LIFESPAN: int +SECPKG_ATTR_DCE_INFO: int +SECPKG_ATTR_STREAM_SIZES: int +SECPKG_ATTR_KEY_INFO: int +SECPKG_ATTR_AUTHORITY: int +SECPKG_ATTR_PROTO_INFO: int +SECPKG_ATTR_PASSWORD_EXPIRY: int +SECPKG_ATTR_SESSION_KEY: int +SECPKG_ATTR_PACKAGE_INFO: int +SECPKG_ATTR_USER_FLAGS: int +SECPKG_ATTR_NEGOTIATION_INFO: int +SECPKG_ATTR_NATIVE_NAMES: int +SECPKG_ATTR_FLAGS: int +SECPKG_ATTR_USE_VALIDATED: int +SECPKG_ATTR_CREDENTIAL_NAME: int +SECPKG_ATTR_TARGET_INFORMATION: int +SECPKG_ATTR_ACCESS_TOKEN: int +SECPKG_ATTR_TARGET: int +SECPKG_ATTR_AUTHENTICATION_ID: int +SECPKG_ATTR_REMOTE_CERT_CONTEXT: int +SECPKG_ATTR_LOCAL_CERT_CONTEXT: int +SECPKG_ATTR_ROOT_STORE: int +SECPKG_ATTR_SUPPORTED_ALGS: int +SECPKG_ATTR_CIPHER_STRENGTHS: int +SECPKG_ATTR_SUPPORTED_PROTOCOLS: int +SECPKG_ATTR_CONNECTION_INFO: int +SECPKG_ATTR_EAP_KEY_BLOCK: int +SECPKG_ATTR_MAPPED_CRED_ATTR: int +SECPKG_ATTR_SESSION_INFO: int +SECPKG_ATTR_APP_DATA: int +SECPKG_NEGOTIATION_COMPLETE: int +SECPKG_NEGOTIATION_OPTIMISTIC: int +SECPKG_NEGOTIATION_IN_PROGRESS: int +SECPKG_NEGOTIATION_DIRECT: int +SECPKG_NEGOTIATION_TRY_MULTICRED: int +SECPKG_CONTEXT_EXPORT_RESET_NEW: int +SECPKG_CONTEXT_EXPORT_DELETE_OLD: int +SECQOP_WRAP_NO_ENCRYPT: int +SECURITY_ENTRYPOINT_ANSIW: str +SECURITY_ENTRYPOINT_ANSIA: str +SECURITY_ENTRYPOINT16: str +SECURITY_ENTRYPOINT: str +SECURITY_ENTRYPOINT_ANSI: str +SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION: int +SECURITY_SUPPORT_PROVIDER_INTERFACE_VERSION_2: int +SASL_OPTION_SEND_SIZE: int +SASL_OPTION_RECV_SIZE: int +SASL_OPTION_AUTHZ_STRING: int +SASL_OPTION_AUTHZ_PROCESSING: int +SEC_WINNT_AUTH_IDENTITY_ANSI: int +SEC_WINNT_AUTH_IDENTITY_UNICODE: int +SEC_WINNT_AUTH_IDENTITY_VERSION: int +SEC_WINNT_AUTH_IDENTITY_MARSHALLED: int +SEC_WINNT_AUTH_IDENTITY_ONLY: int +SECPKG_OPTIONS_TYPE_UNKNOWN: int +SECPKG_OPTIONS_TYPE_LSA: int +SECPKG_OPTIONS_TYPE_SSPI: int +SECPKG_OPTIONS_PERMANENT: int +SEC_E_INSUFFICIENT_MEMORY: int +SEC_E_INVALID_HANDLE: int +SEC_E_UNSUPPORTED_FUNCTION: int +SEC_E_TARGET_UNKNOWN: int +SEC_E_INTERNAL_ERROR: int +SEC_E_SECPKG_NOT_FOUND: int +SEC_E_NOT_OWNER: int +SEC_E_CANNOT_INSTALL: int +SEC_E_INVALID_TOKEN: int +SEC_E_CANNOT_PACK: int +SEC_E_QOP_NOT_SUPPORTED: int +SEC_E_NO_IMPERSONATION: int +SEC_E_LOGON_DENIED: int +SEC_E_UNKNOWN_CREDENTIALS: int +SEC_E_NO_CREDENTIALS: int +SEC_E_MESSAGE_ALTERED: int +SEC_E_OUT_OF_SEQUENCE: int +SEC_E_NO_AUTHENTICATING_AUTHORITY: int +SEC_I_CONTINUE_NEEDED: int +SEC_I_COMPLETE_NEEDED: int +SEC_I_COMPLETE_AND_CONTINUE: int +SEC_I_LOCAL_LOGON: int +SEC_E_BAD_PKGID: int +SEC_E_CONTEXT_EXPIRED: int +SEC_I_CONTEXT_EXPIRED: int +SEC_E_BUFFER_TOO_SMALL: int +SEC_I_RENEGOTIATE: int +SEC_E_WRONG_PRINCIPAL: int +SEC_I_NO_LSA_CONTEXT: int +SEC_E_TIME_SKEW: int +SEC_E_UNTRUSTED_ROOT: int +SEC_E_ILLEGAL_MESSAGE: int +SEC_E_CERT_UNKNOWN: int +SEC_E_CERT_EXPIRED: int +SEC_E_ENCRYPT_FAILURE: int +SEC_E_DECRYPT_FAILURE: int +SEC_E_ALGORITHM_MISMATCH: int +SEC_E_SECURITY_QOS_FAILED: int +SEC_E_UNFINISHED_CONTEXT_DELETED: int +SEC_E_NO_TGT_REPLY: int +SEC_E_NO_IP_ADDRESSES: int +SEC_E_WRONG_CREDENTIAL_HANDLE: int +SEC_E_CRYPTO_SYSTEM_INVALID: int +SEC_E_MAX_REFERRALS_EXCEEDED: int +SEC_E_MUST_BE_KDC: int +SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: int +SEC_E_TOO_MANY_PRINCIPALS: int +SEC_E_NO_PA_DATA: int +SEC_E_PKINIT_NAME_MISMATCH: int +SEC_E_SMARTCARD_LOGON_REQUIRED: int +SEC_E_SHUTDOWN_IN_PROGRESS: int +SEC_E_KDC_INVALID_REQUEST: int +SEC_E_KDC_UNABLE_TO_REFER: int +SEC_E_KDC_UNKNOWN_ETYPE: int +SEC_E_UNSUPPORTED_PREAUTH: int +SEC_E_DELEGATION_REQUIRED: int +SEC_E_BAD_BINDINGS: int +SEC_E_MULTIPLE_ACCOUNTS: int +SEC_E_NO_KERB_KEY: int +ERROR_IPSEC_QM_POLICY_EXISTS: int +ERROR_IPSEC_QM_POLICY_NOT_FOUND: int +ERROR_IPSEC_QM_POLICY_IN_USE: int +ERROR_IPSEC_MM_POLICY_EXISTS: int +ERROR_IPSEC_MM_POLICY_NOT_FOUND: int +ERROR_IPSEC_MM_POLICY_IN_USE: int +ERROR_IPSEC_MM_FILTER_EXISTS: int +ERROR_IPSEC_MM_FILTER_NOT_FOUND: int +ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: int +ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: int +ERROR_IPSEC_MM_AUTH_EXISTS: int +ERROR_IPSEC_MM_AUTH_NOT_FOUND: int +ERROR_IPSEC_MM_AUTH_IN_USE: int +ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: int +ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: int +ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: int +ERROR_IPSEC_TUNNEL_FILTER_EXISTS: int +ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: int +ERROR_IPSEC_MM_FILTER_PENDING_DELETION: int +ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: int +ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: int +ERROR_IPSEC_MM_POLICY_PENDING_DELETION: int +ERROR_IPSEC_MM_AUTH_PENDING_DELETION: int +ERROR_IPSEC_QM_POLICY_PENDING_DELETION: int +WARNING_IPSEC_MM_POLICY_PRUNED: int +WARNING_IPSEC_QM_POLICY_PRUNED: int +ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: int +ERROR_IPSEC_IKE_AUTH_FAIL: int +ERROR_IPSEC_IKE_ATTRIB_FAIL: int +ERROR_IPSEC_IKE_NEGOTIATION_PENDING: int +ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: int +ERROR_IPSEC_IKE_TIMED_OUT: int +ERROR_IPSEC_IKE_NO_CERT: int +ERROR_IPSEC_IKE_SA_DELETED: int +ERROR_IPSEC_IKE_SA_REAPED: int +ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: int +ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: int +ERROR_IPSEC_IKE_QUEUE_DROP_MM: int +ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: int +ERROR_IPSEC_IKE_DROP_NO_RESPONSE: int +ERROR_IPSEC_IKE_MM_DELAY_DROP: int +ERROR_IPSEC_IKE_QM_DELAY_DROP: int +ERROR_IPSEC_IKE_ERROR: int +ERROR_IPSEC_IKE_CRL_FAILED: int +ERROR_IPSEC_IKE_INVALID_KEY_USAGE: int +ERROR_IPSEC_IKE_INVALID_CERT_TYPE: int +ERROR_IPSEC_IKE_NO_PRIVATE_KEY: int +ERROR_IPSEC_IKE_DH_FAIL: int +ERROR_IPSEC_IKE_INVALID_HEADER: int +ERROR_IPSEC_IKE_NO_POLICY: int +ERROR_IPSEC_IKE_INVALID_SIGNATURE: int +ERROR_IPSEC_IKE_KERBEROS_ERROR: int +ERROR_IPSEC_IKE_NO_PUBLIC_KEY: int +ERROR_IPSEC_IKE_PROCESS_ERR: int +ERROR_IPSEC_IKE_PROCESS_ERR_SA: int +ERROR_IPSEC_IKE_PROCESS_ERR_PROP: int +ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: int +ERROR_IPSEC_IKE_PROCESS_ERR_KE: int +ERROR_IPSEC_IKE_PROCESS_ERR_ID: int +ERROR_IPSEC_IKE_PROCESS_ERR_CERT: int +ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: int +ERROR_IPSEC_IKE_PROCESS_ERR_HASH: int +ERROR_IPSEC_IKE_PROCESS_ERR_SIG: int +ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: int +ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: int +ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: int +ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: int +ERROR_IPSEC_IKE_INVALID_PAYLOAD: int +ERROR_IPSEC_IKE_LOAD_SOFT_SA: int +ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: int +ERROR_IPSEC_IKE_INVALID_COOKIE: int +ERROR_IPSEC_IKE_NO_PEER_CERT: int +ERROR_IPSEC_IKE_PEER_CRL_FAILED: int +ERROR_IPSEC_IKE_POLICY_CHANGE: int +ERROR_IPSEC_IKE_NO_MM_POLICY: int +ERROR_IPSEC_IKE_NOTCBPRIV: int +ERROR_IPSEC_IKE_SECLOADFAIL: int +ERROR_IPSEC_IKE_FAILSSPINIT: int +ERROR_IPSEC_IKE_FAILQUERYSSP: int +ERROR_IPSEC_IKE_SRVACQFAIL: int +ERROR_IPSEC_IKE_SRVQUERYCRED: int +ERROR_IPSEC_IKE_GETSPIFAIL: int +ERROR_IPSEC_IKE_INVALID_FILTER: int +ERROR_IPSEC_IKE_OUT_OF_MEMORY: int +ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: int +ERROR_IPSEC_IKE_INVALID_POLICY: int +ERROR_IPSEC_IKE_UNKNOWN_DOI: int +ERROR_IPSEC_IKE_INVALID_SITUATION: int +ERROR_IPSEC_IKE_DH_FAILURE: int +ERROR_IPSEC_IKE_INVALID_GROUP: int +ERROR_IPSEC_IKE_ENCRYPT: int +ERROR_IPSEC_IKE_DECRYPT: int +ERROR_IPSEC_IKE_POLICY_MATCH: int +ERROR_IPSEC_IKE_UNSUPPORTED_ID: int +ERROR_IPSEC_IKE_INVALID_HASH: int +ERROR_IPSEC_IKE_INVALID_HASH_ALG: int +ERROR_IPSEC_IKE_INVALID_HASH_SIZE: int +ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: int +ERROR_IPSEC_IKE_INVALID_AUTH_ALG: int +ERROR_IPSEC_IKE_INVALID_SIG: int +ERROR_IPSEC_IKE_LOAD_FAILED: int +ERROR_IPSEC_IKE_RPC_DELETE: int +ERROR_IPSEC_IKE_BENIGN_REINIT: int +ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: int +ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: int +ERROR_IPSEC_IKE_MM_LIMIT: int +ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: int +ERROR_IPSEC_IKE_NEG_STATUS_END: int +CRYPT_E_MSG_ERROR: int +CRYPT_E_UNKNOWN_ALGO: int +CRYPT_E_OID_FORMAT: int +CRYPT_E_INVALID_MSG_TYPE: int +CRYPT_E_UNEXPECTED_ENCODING: int +CRYPT_E_AUTH_ATTR_MISSING: int +CRYPT_E_HASH_VALUE: int +CRYPT_E_INVALID_INDEX: int +CRYPT_E_ALREADY_DECRYPTED: int +CRYPT_E_NOT_DECRYPTED: int +CRYPT_E_RECIPIENT_NOT_FOUND: int +CRYPT_E_CONTROL_TYPE: int +CRYPT_E_ISSUER_SERIALNUMBER: int +CRYPT_E_SIGNER_NOT_FOUND: int +CRYPT_E_ATTRIBUTES_MISSING: int +CRYPT_E_STREAM_MSG_NOT_READY: int +CRYPT_E_STREAM_INSUFFICIENT_DATA: int +CRYPT_I_NEW_PROTECTION_REQUIRED: int +CRYPT_E_BAD_LEN: int +CRYPT_E_BAD_ENCODE: int +CRYPT_E_FILE_ERROR: int +CRYPT_E_NOT_FOUND: int +CRYPT_E_EXISTS: int +CRYPT_E_NO_PROVIDER: int +CRYPT_E_SELF_SIGNED: int +CRYPT_E_DELETED_PREV: int +CRYPT_E_NO_MATCH: int +CRYPT_E_UNEXPECTED_MSG_TYPE: int +CRYPT_E_NO_KEY_PROPERTY: int +CRYPT_E_NO_DECRYPT_CERT: int +CRYPT_E_BAD_MSG: int +CRYPT_E_NO_SIGNER: int +CRYPT_E_PENDING_CLOSE: int +CRYPT_E_REVOKED: int +CRYPT_E_NO_REVOCATION_DLL: int +CRYPT_E_NO_REVOCATION_CHECK: int +CRYPT_E_REVOCATION_OFFLINE: int +CRYPT_E_NOT_IN_REVOCATION_DATABASE: int +CRYPT_E_INVALID_NUMERIC_STRING: int +CRYPT_E_INVALID_PRINTABLE_STRING: int +CRYPT_E_INVALID_IA5_STRING: int +CRYPT_E_INVALID_X500_STRING: int +CRYPT_E_NOT_CHAR_STRING: int +CRYPT_E_FILERESIZED: int +CRYPT_E_SECURITY_SETTINGS: int +CRYPT_E_NO_VERIFY_USAGE_DLL: int +CRYPT_E_NO_VERIFY_USAGE_CHECK: int +CRYPT_E_VERIFY_USAGE_OFFLINE: int +CRYPT_E_NOT_IN_CTL: int +CRYPT_E_NO_TRUSTED_SIGNER: int +CRYPT_E_MISSING_PUBKEY_PARA: int +CRYPT_E_OSS_ERROR: int +KerbDebugRequestMessage: int +KerbQueryTicketCacheMessage: int +KerbChangeMachinePasswordMessage: int +KerbVerifyPacMessage: int +KerbRetrieveTicketMessage: int +KerbUpdateAddressesMessage: int +KerbPurgeTicketCacheMessage: int +KerbChangePasswordMessage: int +KerbRetrieveEncodedTicketMessage: int +KerbDecryptDataMessage: int +KerbAddBindingCacheEntryMessage: int +KerbSetPasswordMessage: int +KerbSetPasswordExMessage: int +KerbVerifyCredentialsMessage: int +KerbQueryTicketCacheExMessage: int +KerbPurgeTicketCacheExMessage: int +KerbRefreshSmartcardCredentialsMessage: int +KerbAddExtraCredentialsMessage: int +KerbQuerySupplementalCredentialsMessage: int +MsV1_0Lm20ChallengeRequest: int +MsV1_0Lm20GetChallengeResponse: int +MsV1_0EnumerateUsers: int +MsV1_0GetUserInfo: int +MsV1_0ReLogonUsers: int +MsV1_0ChangePassword: int +MsV1_0ChangeCachedPassword: int +MsV1_0GenericPassthrough: int +MsV1_0CacheLogon: int +MsV1_0SubAuth: int +MsV1_0DeriveCredential: int +MsV1_0CacheLookup: int +MsV1_0SetProcessOption: int +SEC_E_OK: int +SECBUFFER_MECHLIST: int +SECBUFFER_MECHLIST_SIGNATURE: int +SECPKG_ATTR_ISSUER_LIST_EX: int +SEC_E_INCOMPLETE_CREDENTIALS: int +SEC_E_INCOMPLETE_MESSAGE: int +SEC_I_INCOMPLETE_CREDENTIALS: int diff --git a/stubs/pywin32/win32/lib/win2kras.pyi b/stubs/pywin32/win32/lib/win2kras.pyi new file mode 100644 index 000000000000..ecb1da748f7e --- /dev/null +++ b/stubs/pywin32/win32/lib/win2kras.pyi @@ -0,0 +1,34 @@ +RASEAPF_Logon: int +RASEAPF_NonInteractive: int +RASEAPF_Preview: int + +def GetEapUserIdentity(phoneBook: str | None, entry: str, flags: int, hwnd=None, /): ... + +RASCS_AllDevicesConnected: int +RASCS_AuthAck: int +RASCS_AuthCallback: int +RASCS_AuthChangePassword: int +RASCS_AuthLinkSpeed: int +RASCS_AuthNotify: int +RASCS_AuthProject: int +RASCS_AuthRetry: int +RASCS_Authenticate: int +RASCS_Authenticated: int +RASCS_CallbackComplete: int +RASCS_CallbackSetByCaller: int +RASCS_ConnectDevice: int +RASCS_Connected: int +RASCS_DeviceConnected: int +RASCS_Disconnected: int +RASCS_Interactive: int +RASCS_LogonNetwork: int +RASCS_OpenPort: int +RASCS_PasswordExpired: int +RASCS_PortOpened: int +RASCS_PrepareForCallback: int +RASCS_Projected: int +RASCS_ReAuthenticate: int +RASCS_RetryAuthentication: int +RASCS_StartAuthentication: int +RASCS_WaitForCallback: int +RASCS_WaitForModemReset: int diff --git a/stubs/pywin32/win32/lib/win32con.pyi b/stubs/pywin32/win32/lib/win32con.pyi new file mode 100644 index 000000000000..1322355791df --- /dev/null +++ b/stubs/pywin32/win32/lib/win32con.pyi @@ -0,0 +1,4910 @@ +from typing import Final + +WINVER: Final = 1280 +WM_USER: Final = 1024 +PY_0U: Final = 0 +OFN_READONLY: Final = 1 +OFN_OVERWRITEPROMPT: Final = 2 +OFN_HIDEREADONLY: Final = 4 +OFN_NOCHANGEDIR: Final = 8 +OFN_SHOWHELP: Final = 16 +OFN_ENABLEHOOK: Final = 32 +OFN_ENABLETEMPLATE: Final = 64 +OFN_ENABLETEMPLATEHANDLE: Final = 128 +OFN_NOVALIDATE: Final = 256 +OFN_ALLOWMULTISELECT: Final = 512 +OFN_EXTENSIONDIFFERENT: Final = 1024 +OFN_PATHMUSTEXIST: Final = 2048 +OFN_FILEMUSTEXIST: Final = 4096 +OFN_CREATEPROMPT: Final = 8192 +OFN_SHAREAWARE: Final = 16384 +OFN_NOREADONLYRETURN: Final = 32768 +OFN_NOTESTFILECREATE: Final = 65536 +OFN_NONETWORKBUTTON: Final = 131072 +OFN_NOLONGNAMES: Final = 262144 +OFN_EXPLORER: Final = 524288 +OFN_NODEREFERENCELINKS: Final = 1048576 +OFN_LONGNAMES: Final = 2097152 +OFN_ENABLEINCLUDENOTIFY: Final = 4194304 +OFN_ENABLESIZING: Final = 8388608 +OFN_DONTADDTORECENT: Final = 33554432 +OFN_FORCESHOWHIDDEN: Final = 268435456 +OFN_EX_NOPLACESBAR: Final = 1 +OFN_SHAREFALLTHROUGH: Final = 2 +OFN_SHARENOWARN: Final = 1 +OFN_SHAREWARN: Final = 0 +CDN_FIRST: Final[int] +CDN_LAST: Final[int] +CDN_INITDONE: Final[int] +CDN_SELCHANGE: Final[int] +CDN_FOLDERCHANGE: Final[int] +CDN_SHAREVIOLATION: Final[int] +CDN_HELP: Final[int] +CDN_FILEOK: Final[int] +CDN_TYPECHANGE: Final[int] +CDN_INCLUDEITEM: Final[int] +CDM_FIRST: Final[int] +CDM_LAST: Final[int] +CDM_GETSPEC: Final[int] +CDM_GETFILEPATH: Final[int] +CDM_GETFOLDERPATH: Final[int] +CDM_GETFOLDERIDLIST: Final[int] +CDM_SETCONTROLTEXT: Final[int] +CDM_HIDECONTROL: Final[int] +CDM_SETDEFEXT: Final[int] +CC_RGBINIT: Final = 1 +CC_FULLOPEN: Final = 2 +CC_PREVENTFULLOPEN: Final = 4 +CC_SHOWHELP: Final = 8 +CC_ENABLEHOOK: Final = 16 +CC_ENABLETEMPLATE: Final = 32 +CC_ENABLETEMPLATEHANDLE: Final = 64 +CC_SOLIDCOLOR: Final = 128 +CC_ANYCOLOR: Final = 256 +FR_DOWN: Final = 1 +FR_WHOLEWORD: Final = 2 +FR_MATCHCASE: Final = 4 +FR_FINDNEXT: Final = 8 +FR_REPLACE: Final = 16 +FR_REPLACEALL: Final = 32 +FR_DIALOGTERM: Final = 64 +FR_SHOWHELP: Final = 128 +FR_ENABLEHOOK: Final = 256 +FR_ENABLETEMPLATE: Final = 512 +FR_NOUPDOWN: Final = 1024 +FR_NOMATCHCASE: Final = 2048 +FR_NOWHOLEWORD: Final = 4096 +FR_ENABLETEMPLATEHANDLE: Final = 8192 +FR_HIDEUPDOWN: Final = 16384 +FR_HIDEMATCHCASE: Final = 32768 +FR_HIDEWHOLEWORD: Final = 65536 +CF_SCREENFONTS: Final = 1 +CF_PRINTERFONTS: Final = 2 +CF_BOTH: Final[int] +CF_SHOWHELP: Final = 4 +CF_ENABLEHOOK: Final = 8 +CF_ENABLETEMPLATE: Final = 16 +CF_ENABLETEMPLATEHANDLE: Final = 32 +CF_INITTOLOGFONTSTRUCT: Final = 64 +CF_USESTYLE: Final = 128 +CF_EFFECTS: Final = 256 +CF_APPLY: Final = 512 +CF_ANSIONLY: Final = 1024 +CF_SCRIPTSONLY: Final = CF_ANSIONLY +CF_NOVECTORFONTS: Final = 2048 +CF_NOOEMFONTS: Final = CF_NOVECTORFONTS +CF_NOSIMULATIONS: Final = 4096 +CF_LIMITSIZE: Final = 8192 +CF_FIXEDPITCHONLY: Final = 16384 +CF_WYSIWYG: Final = 32768 +CF_FORCEFONTEXIST: Final = 65536 +CF_SCALABLEONLY: Final = 131072 +CF_TTONLY: Final = 262144 +CF_NOFACESEL: Final = 524288 +CF_NOSTYLESEL: Final = 1048576 +CF_NOSIZESEL: Final = 2097152 +CF_SELECTSCRIPT: Final = 4194304 +CF_NOSCRIPTSEL: Final = 8388608 +CF_NOVERTFONTS: Final = 16777216 +SIMULATED_FONTTYPE: Final = 32768 +PRINTER_FONTTYPE: Final = 16384 +SCREEN_FONTTYPE: Final = 8192 +BOLD_FONTTYPE: Final = 256 +ITALIC_FONTTYPE: Final = 512 +REGULAR_FONTTYPE: Final = 1024 +OPENTYPE_FONTTYPE: Final = 65536 +TYPE1_FONTTYPE: Final = 131072 +DSIG_FONTTYPE: Final = 262144 +WM_CHOOSEFONT_GETLOGFONT: Final[int] +WM_CHOOSEFONT_SETLOGFONT: Final[int] +WM_CHOOSEFONT_SETFLAGS: Final[int] +LBSELCHSTRINGA: Final = "commdlg_LBSelChangedNotify" +SHAREVISTRINGA: Final = "commdlg_ShareViolation" +FILEOKSTRINGA: Final = "commdlg_FileNameOK" +COLOROKSTRINGA: Final = "commdlg_ColorOK" +SETRGBSTRINGA: Final = "commdlg_SetRGBColor" +HELPMSGSTRINGA: Final = "commdlg_help" +FINDMSGSTRINGA: Final = "commdlg_FindReplace" +LBSELCHSTRING: Final = LBSELCHSTRINGA +SHAREVISTRING: Final = SHAREVISTRINGA +FILEOKSTRING: Final = FILEOKSTRINGA +COLOROKSTRING: Final = COLOROKSTRINGA +SETRGBSTRING: Final = SETRGBSTRINGA +HELPMSGSTRING: Final = HELPMSGSTRINGA +FINDMSGSTRING: Final = FINDMSGSTRINGA +CD_LBSELNOITEMS: Final = -1 +CD_LBSELCHANGE: Final = 0 +CD_LBSELSUB: Final = 1 +CD_LBSELADD: Final = 2 +PD_ALLPAGES: Final = 0 +PD_SELECTION: Final = 1 +PD_PAGENUMS: Final = 2 +PD_NOSELECTION: Final = 4 +PD_NOPAGENUMS: Final = 8 +PD_COLLATE: Final = 16 +PD_PRINTTOFILE: Final = 32 +PD_PRINTSETUP: Final = 64 +PD_NOWARNING: Final = 128 +PD_RETURNDC: Final = 256 +PD_RETURNIC: Final = 512 +PD_RETURNDEFAULT: Final = 1024 +PD_SHOWHELP: Final = 2048 +PD_ENABLEPRINTHOOK: Final = 4096 +PD_ENABLESETUPHOOK: Final = 8192 +PD_ENABLEPRINTTEMPLATE: Final = 16384 +PD_ENABLESETUPTEMPLATE: Final = 32768 +PD_ENABLEPRINTTEMPLATEHANDLE: Final = 65536 +PD_ENABLESETUPTEMPLATEHANDLE: Final = 131072 +PD_USEDEVMODECOPIES: Final = 262144 +PD_DISABLEPRINTTOFILE: Final = 524288 +PD_HIDEPRINTTOFILE: Final = 1048576 +PD_NONETWORKBUTTON: Final = 2097152 +DN_DEFAULTPRN: Final = 1 +WM_PSD_PAGESETUPDLG: Final = WM_USER +WM_PSD_FULLPAGERECT: Final[int] +WM_PSD_MINMARGINRECT: Final[int] +WM_PSD_MARGINRECT: Final[int] +WM_PSD_GREEKTEXTRECT: Final[int] +WM_PSD_ENVSTAMPRECT: Final[int] +WM_PSD_YAFULLPAGERECT: Final[int] +PSD_DEFAULTMINMARGINS: Final = 0 +PSD_INWININIINTLMEASURE: Final = 0 +PSD_MINMARGINS: Final = 1 +PSD_MARGINS: Final = 2 +PSD_INTHOUSANDTHSOFINCHES: Final = 4 +PSD_INHUNDREDTHSOFMILLIMETERS: Final = 8 +PSD_DISABLEMARGINS: Final = 16 +PSD_DISABLEPRINTER: Final = 32 +PSD_NOWARNING: Final = 128 +PSD_DISABLEORIENTATION: Final = 256 +PSD_RETURNDEFAULT: Final = 1024 +PSD_DISABLEPAPER: Final = 512 +PSD_SHOWHELP: Final = 2048 +PSD_ENABLEPAGESETUPHOOK: Final = 8192 +PSD_ENABLEPAGESETUPTEMPLATE: Final = 32768 +PSD_ENABLEPAGESETUPTEMPLATEHANDLE: Final = 131072 +PSD_ENABLEPAGEPAINTHOOK: Final = 262144 +PSD_DISABLEPAGEPAINTING: Final = 524288 +PSD_NONETWORKBUTTON: Final = 2097152 + +HKEY_CLASSES_ROOT: Final = -2147483648 +HKEY_CURRENT_USER: Final = -2147483647 +HKEY_LOCAL_MACHINE: Final = -2147483646 +HKEY_USERS: Final = -2147483645 +HKEY_PERFORMANCE_DATA: Final = -2147483644 +HKEY_CURRENT_CONFIG: Final = -2147483643 +HKEY_DYN_DATA: Final = -2147483642 +HKEY_PERFORMANCE_TEXT: Final = -2147483568 +HKEY_PERFORMANCE_NLSTEXT: Final = -2147483552 + +HWND_BROADCAST: Final = 65535 +HWND_DESKTOP: Final = 0 +HWND_TOP: Final = 0 +HWND_BOTTOM: Final = 1 +HWND_TOPMOST: Final = -1 +HWND_NOTOPMOST: Final = -2 +HWND_MESSAGE: Final = -3 + +SM_CXSCREEN: Final = 0 +SM_CYSCREEN: Final = 1 +SM_CXVSCROLL: Final = 2 +SM_CYHSCROLL: Final = 3 +SM_CYCAPTION: Final = 4 +SM_CXBORDER: Final = 5 +SM_CYBORDER: Final = 6 +SM_CXDLGFRAME: Final = 7 +SM_CYDLGFRAME: Final = 8 +SM_CYVTHUMB: Final = 9 +SM_CXHTHUMB: Final = 10 +SM_CXICON: Final = 11 +SM_CYICON: Final = 12 +SM_CXCURSOR: Final = 13 +SM_CYCURSOR: Final = 14 +SM_CYMENU: Final = 15 +SM_CXFULLSCREEN: Final = 16 +SM_CYFULLSCREEN: Final = 17 +SM_CYKANJIWINDOW: Final = 18 +SM_MOUSEPRESENT: Final = 19 +SM_CYVSCROLL: Final = 20 +SM_CXHSCROLL: Final = 21 +SM_DEBUG: Final = 22 +SM_SWAPBUTTON: Final = 23 +SM_RESERVED1: Final = 24 +SM_RESERVED2: Final = 25 +SM_RESERVED3: Final = 26 +SM_RESERVED4: Final = 27 +SM_CXMIN: Final = 28 +SM_CYMIN: Final = 29 +SM_CXSIZE: Final = 30 +SM_CYSIZE: Final = 31 +SM_CXFRAME: Final = 32 +SM_CYFRAME: Final = 33 +SM_CXMINTRACK: Final = 34 +SM_CYMINTRACK: Final = 35 +SM_CXDOUBLECLK: Final = 36 +SM_CYDOUBLECLK: Final = 37 +SM_CXICONSPACING: Final = 38 +SM_CYICONSPACING: Final = 39 +SM_MENUDROPALIGNMENT: Final = 40 +SM_PENWINDOWS: Final = 41 +SM_DBCSENABLED: Final = 42 +SM_CMOUSEBUTTONS: Final = 43 +SM_CXFIXEDFRAME: Final = SM_CXDLGFRAME +SM_CYFIXEDFRAME: Final = SM_CYDLGFRAME +SM_CXSIZEFRAME: Final = SM_CXFRAME +SM_CYSIZEFRAME: Final = SM_CYFRAME +SM_SECURE: Final = 44 +SM_CXEDGE: Final = 45 +SM_CYEDGE: Final = 46 +SM_CXMINSPACING: Final = 47 +SM_CYMINSPACING: Final = 48 +SM_CXSMICON: Final = 49 +SM_CYSMICON: Final = 50 +SM_CYSMCAPTION: Final = 51 +SM_CXSMSIZE: Final = 52 +SM_CYSMSIZE: Final = 53 +SM_CXMENUSIZE: Final = 54 +SM_CYMENUSIZE: Final = 55 +SM_ARRANGE: Final = 56 +SM_CXMINIMIZED: Final = 57 +SM_CYMINIMIZED: Final = 58 +SM_CXMAXTRACK: Final = 59 +SM_CYMAXTRACK: Final = 60 +SM_CXMAXIMIZED: Final = 61 +SM_CYMAXIMIZED: Final = 62 +SM_NETWORK: Final = 63 +SM_CLEANBOOT: Final = 67 +SM_CXDRAG: Final = 68 +SM_CYDRAG: Final = 69 +SM_SHOWSOUNDS: Final = 70 +SM_CXMENUCHECK: Final = 71 +SM_CYMENUCHECK: Final = 72 +SM_SLOWMACHINE: Final = 73 +SM_MIDEASTENABLED: Final = 74 +SM_MOUSEWHEELPRESENT: Final = 75 +SM_XVIRTUALSCREEN: Final = 76 +SM_YVIRTUALSCREEN: Final = 77 +SM_CXVIRTUALSCREEN: Final = 78 +SM_CYVIRTUALSCREEN: Final = 79 +SM_CMONITORS: Final = 80 +SM_SAMEDISPLAYFORMAT: Final = 81 +SM_CMETRICS: Final = 83 +MNC_IGNORE: Final = 0 +MNC_CLOSE: Final = 1 +MNC_EXECUTE: Final = 2 +MNC_SELECT: Final = 3 +MNS_NOCHECK: Final = -2147483648 +MNS_MODELESS: Final = 1073741824 +MNS_DRAGDROP: Final = 536870912 +MNS_AUTODISMISS: Final = 268435456 +MNS_NOTIFYBYPOS: Final = 134217728 +MNS_CHECKORBMP: Final = 67108864 +MIM_MAXHEIGHT: Final = 1 +MIM_BACKGROUND: Final = 2 +MIM_HELPID: Final = 4 +MIM_MENUDATA: Final = 8 +MIM_STYLE: Final = 16 +MIM_APPLYTOSUBMENUS: Final = -2147483648 +MND_CONTINUE: Final = 0 +MND_ENDMENU: Final = 1 +MNGOF_GAP: Final = 3 +MNGO_NOINTERFACE: Final = 0 +MNGO_NOERROR: Final = 1 +MIIM_STATE: Final = 1 +MIIM_ID: Final = 2 +MIIM_SUBMENU: Final = 4 +MIIM_CHECKMARKS: Final = 8 +MIIM_TYPE: Final = 16 +MIIM_DATA: Final = 32 +MIIM_STRING: Final = 64 +MIIM_BITMAP: Final = 128 +MIIM_FTYPE: Final = 256 +HBMMENU_CALLBACK: Final = -1 +HBMMENU_SYSTEM: Final = 1 +HBMMENU_MBAR_RESTORE: Final = 2 +HBMMENU_MBAR_MINIMIZE: Final = 3 +HBMMENU_MBAR_CLOSE: Final = 5 +HBMMENU_MBAR_CLOSE_D: Final = 6 +HBMMENU_MBAR_MINIMIZE_D: Final = 7 +HBMMENU_POPUP_CLOSE: Final = 8 +HBMMENU_POPUP_RESTORE: Final = 9 +HBMMENU_POPUP_MAXIMIZE: Final = 10 +HBMMENU_POPUP_MINIMIZE: Final = 11 +GMDI_USEDISABLED: Final = 1 +GMDI_GOINTOPOPUPS: Final = 2 +TPM_LEFTBUTTON: Final = 0 +TPM_RIGHTBUTTON: Final = 2 +TPM_LEFTALIGN: Final = 0 +TPM_CENTERALIGN: Final = 4 +TPM_RIGHTALIGN: Final = 8 +TPM_TOPALIGN: Final = 0 +TPM_VCENTERALIGN: Final = 16 +TPM_BOTTOMALIGN: Final = 32 +TPM_HORIZONTAL: Final = 0 +TPM_VERTICAL: Final = 64 +TPM_NONOTIFY: Final = 128 +TPM_RETURNCMD: Final = 256 +TPM_RECURSE: Final = 1 +DOF_EXECUTABLE: Final = 32769 +DOF_DOCUMENT: Final = 32770 +DOF_DIRECTORY: Final = 32771 +DOF_MULTIPLE: Final = 32772 +DOF_PROGMAN: Final = 1 +DOF_SHELLDATA: Final = 2 +DO_DROPFILE: Final = 1162627398 +DO_PRINTFILE: Final = 1414419024 +DT_TOP: Final = 0 +DT_LEFT: Final = 0 +DT_CENTER: Final = 1 +DT_RIGHT: Final = 2 +DT_VCENTER: Final = 4 +DT_BOTTOM: Final = 8 +DT_WORDBREAK: Final = 16 +DT_SINGLELINE: Final = 32 +DT_EXPANDTABS: Final = 64 +DT_TABSTOP: Final = 128 +DT_NOCLIP: Final = 256 +DT_EXTERNALLEADING: Final = 512 +DT_CALCRECT: Final = 1024 +DT_NOPREFIX: Final = 2048 +DT_INTERNAL: Final = 4096 +DT_EDITCONTROL: Final = 8192 +DT_PATH_ELLIPSIS: Final = 16384 +DT_END_ELLIPSIS: Final = 32768 +DT_MODIFYSTRING: Final = 65536 +DT_RTLREADING: Final = 131072 +DT_WORD_ELLIPSIS: Final = 262144 +DST_COMPLEX: Final = 0 +DST_TEXT: Final = 1 +DST_PREFIXTEXT: Final = 2 +DST_ICON: Final = 3 +DST_BITMAP: Final = 4 +DSS_NORMAL: Final = 0 +DSS_UNION: Final = 16 +DSS_DISABLED: Final = 32 +DSS_MONO: Final = 128 +DSS_RIGHT: Final = 32768 +DCX_WINDOW: Final = 1 +DCX_CACHE: Final = 2 +DCX_NORESETATTRS: Final = 4 +DCX_CLIPCHILDREN: Final = 8 +DCX_CLIPSIBLINGS: Final = 16 +DCX_PARENTCLIP: Final = 32 +DCX_EXCLUDERGN: Final = 64 +DCX_INTERSECTRGN: Final = 128 +DCX_EXCLUDEUPDATE: Final = 256 +DCX_INTERSECTUPDATE: Final = 512 +DCX_LOCKWINDOWUPDATE: Final = 1024 +DCX_VALIDATE: Final = 2097152 +CUDR_NORMAL: Final = 0 +CUDR_NOSNAPTOGRID: Final = 1 +CUDR_NORESOLVEPOSITIONS: Final = 2 +CUDR_NOCLOSEGAPS: Final = 4 +CUDR_NEGATIVECOORDS: Final = 8 +CUDR_NOPRIMARY: Final = 16 +RDW_INVALIDATE: Final = 1 +RDW_INTERNALPAINT: Final = 2 +RDW_ERASE: Final = 4 +RDW_VALIDATE: Final = 8 +RDW_NOINTERNALPAINT: Final = 16 +RDW_NOERASE: Final = 32 +RDW_NOCHILDREN: Final = 64 +RDW_ALLCHILDREN: Final = 128 +RDW_UPDATENOW: Final = 256 +RDW_ERASENOW: Final = 512 +RDW_FRAME: Final = 1024 +RDW_NOFRAME: Final = 2048 +SW_SCROLLCHILDREN: Final = 1 +SW_INVALIDATE: Final = 2 +SW_ERASE: Final = 4 +SW_SMOOTHSCROLL: Final = 16 +ESB_ENABLE_BOTH: Final = 0 +ESB_DISABLE_BOTH: Final = 3 +ESB_DISABLE_LEFT: Final = 1 +ESB_DISABLE_RIGHT: Final = 2 +ESB_DISABLE_UP: Final = 1 +ESB_DISABLE_DOWN: Final = 2 +ESB_DISABLE_LTUP: Final = ESB_DISABLE_LEFT +ESB_DISABLE_RTDN: Final = ESB_DISABLE_RIGHT +HELPINFO_WINDOW: Final = 1 +HELPINFO_MENUITEM: Final = 2 +MB_OK: Final = 0 +MB_OKCANCEL: Final = 1 +MB_ABORTRETRYIGNORE: Final = 2 +MB_YESNOCANCEL: Final = 3 +MB_YESNO: Final = 4 +MB_RETRYCANCEL: Final = 5 +MB_ICONHAND: Final = 16 +MB_ICONQUESTION: Final = 32 +MB_ICONEXCLAMATION: Final = 48 +MB_ICONASTERISK: Final = 64 +MB_ICONWARNING: Final = MB_ICONEXCLAMATION +MB_ICONERROR: Final = MB_ICONHAND +MB_ICONINFORMATION: Final = MB_ICONASTERISK +MB_ICONSTOP: Final = MB_ICONHAND +MB_DEFBUTTON1: Final = 0 +MB_DEFBUTTON2: Final = 256 +MB_DEFBUTTON3: Final = 512 +MB_DEFBUTTON4: Final = 768 +MB_APPLMODAL: Final = 0 +MB_SYSTEMMODAL: Final = 4096 +MB_TASKMODAL: Final = 8192 +MB_HELP: Final = 16384 +MB_NOFOCUS: Final = 32768 +MB_SETFOREGROUND: Final = 65536 +MB_DEFAULT_DESKTOP_ONLY: Final = 131072 +MB_TOPMOST: Final = 262144 +MB_RIGHT: Final = 524288 +MB_RTLREADING: Final = 1048576 +MB_SERVICE_NOTIFICATION: Final = 2097152 +MB_TYPEMASK: Final = 15 +MB_USERICON: Final = 128 +MB_ICONMASK: Final = 240 +MB_DEFMASK: Final = 3840 +MB_MODEMASK: Final = 12288 +MB_MISCMASK: Final = 49152 + +CWP_ALL: Final = 0 +CWP_SKIPINVISIBLE: Final = 1 +CWP_SKIPDISABLED: Final = 2 +CWP_SKIPTRANSPARENT: Final = 4 +CTLCOLOR_MSGBOX: Final = 0 +CTLCOLOR_EDIT: Final = 1 +CTLCOLOR_LISTBOX: Final = 2 +CTLCOLOR_BTN: Final = 3 +CTLCOLOR_DLG: Final = 4 +CTLCOLOR_SCROLLBAR: Final = 5 +CTLCOLOR_STATIC: Final = 6 +CTLCOLOR_MAX: Final = 7 +COLOR_SCROLLBAR: Final = 0 +COLOR_BACKGROUND: Final = 1 +COLOR_ACTIVECAPTION: Final = 2 +COLOR_INACTIVECAPTION: Final = 3 +COLOR_MENU: Final = 4 +COLOR_WINDOW: Final = 5 +COLOR_WINDOWFRAME: Final = 6 +COLOR_MENUTEXT: Final = 7 +COLOR_WINDOWTEXT: Final = 8 +COLOR_CAPTIONTEXT: Final = 9 +COLOR_ACTIVEBORDER: Final = 10 +COLOR_INACTIVEBORDER: Final = 11 +COLOR_APPWORKSPACE: Final = 12 +COLOR_HIGHLIGHT: Final = 13 +COLOR_HIGHLIGHTTEXT: Final = 14 +COLOR_BTNFACE: Final = 15 +COLOR_BTNSHADOW: Final = 16 +COLOR_GRAYTEXT: Final = 17 +COLOR_BTNTEXT: Final = 18 +COLOR_INACTIVECAPTIONTEXT: Final = 19 +COLOR_BTNHIGHLIGHT: Final = 20 +COLOR_3DDKSHADOW: Final = 21 +COLOR_3DLIGHT: Final = 22 +COLOR_INFOTEXT: Final = 23 +COLOR_INFOBK: Final = 24 +COLOR_HOTLIGHT: Final = 26 +COLOR_GRADIENTACTIVECAPTION: Final = 27 +COLOR_GRADIENTINACTIVECAPTION: Final = 28 +COLOR_DESKTOP: Final = COLOR_BACKGROUND +COLOR_3DFACE: Final = COLOR_BTNFACE +COLOR_3DSHADOW: Final = COLOR_BTNSHADOW +COLOR_3DHIGHLIGHT: Final = COLOR_BTNHIGHLIGHT +COLOR_3DHILIGHT: Final = COLOR_BTNHIGHLIGHT +COLOR_BTNHILIGHT: Final = COLOR_BTNHIGHLIGHT +GW_HWNDFIRST: Final = 0 +GW_HWNDLAST: Final = 1 +GW_HWNDNEXT: Final = 2 +GW_HWNDPREV: Final = 3 +GW_OWNER: Final = 4 +GW_CHILD: Final = 5 +GW_ENABLEDPOPUP: Final = 6 +GW_MAX: Final = 6 +MF_INSERT: Final = 0 +MF_CHANGE: Final = 128 +MF_APPEND: Final = 256 +MF_DELETE: Final = 512 +MF_REMOVE: Final = 4096 +MF_BYCOMMAND: Final = 0 +MF_BYPOSITION: Final = 1024 +MF_SEPARATOR: Final = 2048 +MF_ENABLED: Final = 0 +MF_GRAYED: Final = 1 +MF_DISABLED: Final = 2 +MF_UNCHECKED: Final = 0 +MF_CHECKED: Final = 8 +MF_USECHECKBITMAPS: Final = 512 +MF_STRING: Final = 0 +MF_BITMAP: Final = 4 +MF_OWNERDRAW: Final = 256 +MF_POPUP: Final = 16 +MF_MENUBARBREAK: Final = 32 +MF_MENUBREAK: Final = 64 +MF_UNHILITE: Final = 0 +MF_HILITE: Final = 128 +MF_DEFAULT: Final = 4096 +MF_SYSMENU: Final = 8192 +MF_HELP: Final = 16384 +MF_RIGHTJUSTIFY: Final = 16384 +MF_MOUSESELECT: Final = 32768 +MF_END: Final = 128 +MFT_STRING: Final = MF_STRING +MFT_BITMAP: Final = MF_BITMAP +MFT_MENUBARBREAK: Final = MF_MENUBARBREAK +MFT_MENUBREAK: Final = MF_MENUBREAK +MFT_OWNERDRAW: Final = MF_OWNERDRAW +MFT_RADIOCHECK: Final = 512 +MFT_SEPARATOR: Final = MF_SEPARATOR +MFT_RIGHTORDER: Final = 8192 +MFT_RIGHTJUSTIFY: Final = MF_RIGHTJUSTIFY +MFS_GRAYED: Final = 3 +MFS_DISABLED: Final = MFS_GRAYED +MFS_CHECKED: Final = MF_CHECKED +MFS_HILITE: Final = MF_HILITE +MFS_ENABLED: Final = MF_ENABLED +MFS_UNCHECKED: Final = MF_UNCHECKED +MFS_UNHILITE: Final = MF_UNHILITE +MFS_DEFAULT: Final = MF_DEFAULT +MFS_MASK: Final = 4235 +MFS_HOTTRACKDRAWN: Final = 268435456 +MFS_CACHEDBMP: Final = 536870912 +MFS_BOTTOMGAPDROP: Final = 1073741824 +MFS_TOPGAPDROP: Final = -2147483648 +MFS_GAPDROP: Final = -1073741824 +SC_SIZE: Final = 61440 +SC_MOVE: Final = 61456 +SC_MINIMIZE: Final = 61472 +SC_MAXIMIZE: Final = 61488 +SC_NEXTWINDOW: Final = 61504 +SC_PREVWINDOW: Final = 61520 +SC_CLOSE: Final = 61536 +SC_VSCROLL: Final = 61552 +SC_HSCROLL: Final = 61568 +SC_MOUSEMENU: Final = 61584 +SC_KEYMENU: Final = 61696 +SC_ARRANGE: Final = 61712 +SC_RESTORE: Final = 61728 +SC_TASKLIST: Final = 61744 +SC_SCREENSAVE: Final = 61760 +SC_HOTKEY: Final = 61776 +SC_DEFAULT: Final = 61792 +SC_MONITORPOWER: Final = 61808 +SC_CONTEXTHELP: Final = 61824 +SC_SEPARATOR: Final = 61455 +SC_ICON: Final = SC_MINIMIZE +SC_ZOOM: Final = SC_MAXIMIZE +IDC_ARROW: Final = 32512 +IDC_IBEAM: Final = 32513 +IDC_WAIT: Final = 32514 +IDC_CROSS: Final = 32515 +IDC_UPARROW: Final = 32516 +IDC_SIZE: Final = 32640 +IDC_ICON: Final = 32641 +IDC_SIZENWSE: Final = 32642 +IDC_SIZENESW: Final = 32643 +IDC_SIZEWE: Final = 32644 +IDC_SIZENS: Final = 32645 +IDC_SIZEALL: Final = 32646 +IDC_NO: Final = 32648 +IDC_HAND: Final = 32649 +IDC_APPSTARTING: Final = 32650 +IDC_HELP: Final = 32651 +IDC_PIN: Final = 32671 +IDC_PERSON: Final = 32672 +IMAGE_BITMAP: Final = 0 +IMAGE_ICON: Final = 1 +IMAGE_CURSOR: Final = 2 +IMAGE_ENHMETAFILE: Final = 3 +LR_DEFAULTCOLOR: Final = 0 +LR_MONOCHROME: Final = 1 +LR_COLOR: Final = 2 +LR_COPYRETURNORG: Final = 4 +LR_COPYDELETEORG: Final = 8 +LR_LOADFROMFILE: Final = 16 +LR_LOADTRANSPARENT: Final = 32 +LR_DEFAULTSIZE: Final = 64 +LR_LOADREALSIZE: Final = 128 +LR_LOADMAP3DCOLORS: Final = 4096 +LR_CREATEDIBSECTION: Final = 8192 +LR_COPYFROMRESOURCE: Final = 16384 +LR_SHARED: Final = 32768 +DI_MASK: Final = 1 +DI_IMAGE: Final = 2 +DI_NORMAL: Final = 3 +DI_COMPAT: Final = 4 +DI_DEFAULTSIZE: Final = 8 +RES_ICON: Final = 1 +RES_CURSOR: Final = 2 +OBM_CLOSE: Final = 32754 +OBM_UPARROW: Final = 32753 +OBM_DNARROW: Final = 32752 +OBM_RGARROW: Final = 32751 +OBM_LFARROW: Final = 32750 +OBM_REDUCE: Final = 32749 +OBM_ZOOM: Final = 32748 +OBM_RESTORE: Final = 32747 +OBM_REDUCED: Final = 32746 +OBM_ZOOMD: Final = 32745 +OBM_RESTORED: Final = 32744 +OBM_UPARROWD: Final = 32743 +OBM_DNARROWD: Final = 32742 +OBM_RGARROWD: Final = 32741 +OBM_LFARROWD: Final = 32740 +OBM_MNARROW: Final = 32739 +OBM_COMBO: Final = 32738 +OBM_UPARROWI: Final = 32737 +OBM_DNARROWI: Final = 32736 +OBM_RGARROWI: Final = 32735 +OBM_LFARROWI: Final = 32734 +OBM_OLD_CLOSE: Final = 32767 +OBM_SIZE: Final = 32766 +OBM_OLD_UPARROW: Final = 32765 +OBM_OLD_DNARROW: Final = 32764 +OBM_OLD_RGARROW: Final = 32763 +OBM_OLD_LFARROW: Final = 32762 +OBM_BTSIZE: Final = 32761 +OBM_CHECK: Final = 32760 +OBM_CHECKBOXES: Final = 32759 +OBM_BTNCORNERS: Final = 32758 +OBM_OLD_REDUCE: Final = 32757 +OBM_OLD_ZOOM: Final = 32756 +OBM_OLD_RESTORE: Final = 32755 +OCR_NORMAL: Final = 32512 +OCR_IBEAM: Final = 32513 +OCR_WAIT: Final = 32514 +OCR_CROSS: Final = 32515 +OCR_UP: Final = 32516 +OCR_SIZE: Final = 32640 +OCR_ICON: Final = 32641 +OCR_SIZENWSE: Final = 32642 +OCR_SIZENESW: Final = 32643 +OCR_SIZEWE: Final = 32644 +OCR_SIZENS: Final = 32645 +OCR_SIZEALL: Final = 32646 +OCR_ICOCUR: Final = 32647 +OCR_NO: Final = 32648 +OCR_HAND: Final = 32649 +OCR_APPSTARTING: Final = 32650 + +OIC_SAMPLE: Final = 32512 +OIC_HAND: Final = 32513 +OIC_QUES: Final = 32514 +OIC_BANG: Final = 32515 +OIC_NOTE: Final = 32516 +OIC_WINLOGO: Final = 32517 +OIC_WARNING: Final = OIC_BANG +OIC_ERROR: Final = OIC_HAND +OIC_INFORMATION: Final = OIC_NOTE +ORD_LANGDRIVER: Final = 1 +IDI_APPLICATION: Final = 32512 +IDI_HAND: Final = 32513 +IDI_QUESTION: Final = 32514 +IDI_EXCLAMATION: Final = 32515 +IDI_ASTERISK: Final = 32516 +IDI_WINLOGO: Final = 32517 +IDI_WARNING: Final = IDI_EXCLAMATION +IDI_ERROR: Final = IDI_HAND +IDI_INFORMATION: Final = IDI_ASTERISK +IDOK: Final = 1 +IDCANCEL: Final = 2 +IDABORT: Final = 3 +IDRETRY: Final = 4 +IDIGNORE: Final = 5 +IDYES: Final = 6 +IDNO: Final = 7 +IDCLOSE: Final = 8 +IDHELP: Final = 9 +ES_LEFT: Final = 0 +ES_CENTER: Final = 1 +ES_RIGHT: Final = 2 +ES_MULTILINE: Final = 4 +ES_UPPERCASE: Final = 8 +ES_LOWERCASE: Final = 16 +ES_PASSWORD: Final = 32 +ES_AUTOVSCROLL: Final = 64 +ES_AUTOHSCROLL: Final = 128 +ES_NOHIDESEL: Final = 256 +ES_OEMCONVERT: Final = 1024 +ES_READONLY: Final = 2048 +ES_WANTRETURN: Final = 4096 +ES_NUMBER: Final = 8192 +EN_SETFOCUS: Final = 256 +EN_KILLFOCUS: Final = 512 +EN_CHANGE: Final = 768 +EN_UPDATE: Final = 1024 +EN_ERRSPACE: Final = 1280 +EN_MAXTEXT: Final = 1281 +EN_HSCROLL: Final = 1537 +EN_VSCROLL: Final = 1538 +EC_LEFTMARGIN: Final = 1 +EC_RIGHTMARGIN: Final = 2 +EC_USEFONTINFO: Final = 65535 +EMSIS_COMPOSITIONSTRING: Final = 1 +EIMES_GETCOMPSTRATONCE: Final = 1 +EIMES_CANCELCOMPSTRINFOCUS: Final = 2 +EIMES_COMPLETECOMPSTRKILLFOCUS: Final = 4 +EM_GETSEL: Final = 176 +EM_SETSEL: Final = 177 +EM_GETRECT: Final = 178 +EM_SETRECT: Final = 179 +EM_SETRECTNP: Final = 180 +EM_SCROLL: Final = 181 +EM_LINESCROLL: Final = 182 +EM_SCROLLCARET: Final = 183 +EM_GETMODIFY: Final = 184 +EM_SETMODIFY: Final = 185 +EM_GETLINECOUNT: Final = 186 +EM_LINEINDEX: Final = 187 +EM_SETHANDLE: Final = 188 +EM_GETHANDLE: Final = 189 +EM_GETTHUMB: Final = 190 +EM_LINELENGTH: Final = 193 +EM_REPLACESEL: Final = 194 +EM_GETLINE: Final = 196 +EM_LIMITTEXT: Final = 197 +EM_CANUNDO: Final = 198 +EM_UNDO: Final = 199 +EM_FMTLINES: Final = 200 +EM_LINEFROMCHAR: Final = 201 +EM_SETTABSTOPS: Final = 203 +EM_SETPASSWORDCHAR: Final = 204 +EM_EMPTYUNDOBUFFER: Final = 205 +EM_GETFIRSTVISIBLELINE: Final = 206 +EM_SETREADONLY: Final = 207 +EM_SETWORDBREAKPROC: Final = 208 +EM_GETWORDBREAKPROC: Final = 209 +EM_GETPASSWORDCHAR: Final = 210 +EM_SETMARGINS: Final = 211 +EM_GETMARGINS: Final = 212 +EM_SETLIMITTEXT: Final = EM_LIMITTEXT +EM_GETLIMITTEXT: Final = 213 +EM_POSFROMCHAR: Final = 214 +EM_CHARFROMPOS: Final = 215 +EM_SETIMESTATUS: Final = 216 +EM_GETIMESTATUS: Final = 217 +WB_LEFT: Final = 0 +WB_RIGHT: Final = 1 +WB_ISDELIMITER: Final = 2 +BS_PUSHBUTTON: Final = 0 +BS_DEFPUSHBUTTON: Final = 1 +BS_CHECKBOX: Final = 2 +BS_AUTOCHECKBOX: Final = 3 +BS_RADIOBUTTON: Final = 4 +BS_3STATE: Final = 5 +BS_AUTO3STATE: Final = 6 +BS_GROUPBOX: Final = 7 +BS_USERBUTTON: Final = 8 +BS_AUTORADIOBUTTON: Final = 9 +BS_OWNERDRAW: Final = 11 +BS_LEFTTEXT: Final = 32 +BS_TEXT: Final = 0 +BS_ICON: Final = 64 +BS_BITMAP: Final = 128 +BS_LEFT: Final = 256 +BS_RIGHT: Final = 512 +BS_CENTER: Final = 768 +BS_TOP: Final = 1024 +BS_BOTTOM: Final = 2048 +BS_VCENTER: Final = 3072 +BS_PUSHLIKE: Final = 4096 +BS_MULTILINE: Final = 8192 +BS_NOTIFY: Final = 16384 +BS_FLAT: Final = 32768 +BS_RIGHTBUTTON: Final = BS_LEFTTEXT +BN_CLICKED: Final = 0 +BN_PAINT: Final = 1 +BN_HILITE: Final = 2 +BN_UNHILITE: Final = 3 +BN_DISABLE: Final = 4 +BN_DOUBLECLICKED: Final = 5 +BN_PUSHED: Final = BN_HILITE +BN_UNPUSHED: Final = BN_UNHILITE +BN_DBLCLK: Final = BN_DOUBLECLICKED +BN_SETFOCUS: Final = 6 +BN_KILLFOCUS: Final = 7 +BM_GETCHECK: Final = 240 +BM_SETCHECK: Final = 241 +BM_GETSTATE: Final = 242 +BM_SETSTATE: Final = 243 +BM_SETSTYLE: Final = 244 +BM_CLICK: Final = 245 +BM_GETIMAGE: Final = 246 +BM_SETIMAGE: Final = 247 +BST_UNCHECKED: Final = 0 +BST_CHECKED: Final = 1 +BST_INDETERMINATE: Final = 2 +BST_PUSHED: Final = 4 +BST_FOCUS: Final = 8 +SS_LEFT: Final = 0 +SS_CENTER: Final = 1 +SS_RIGHT: Final = 2 +SS_ICON: Final = 3 +SS_BLACKRECT: Final = 4 +SS_GRAYRECT: Final = 5 +SS_WHITERECT: Final = 6 +SS_BLACKFRAME: Final = 7 +SS_GRAYFRAME: Final = 8 +SS_WHITEFRAME: Final = 9 +SS_USERITEM: Final = 10 +SS_SIMPLE: Final = 11 +SS_LEFTNOWORDWRAP: Final = 12 +SS_BITMAP: Final = 14 +SS_OWNERDRAW: Final = 13 +SS_ENHMETAFILE: Final = 15 +SS_ETCHEDHORZ: Final = 16 +SS_ETCHEDVERT: Final = 17 +SS_ETCHEDFRAME: Final = 18 +SS_TYPEMASK: Final = 31 +SS_NOPREFIX: Final = 128 +SS_NOTIFY: Final = 256 +SS_CENTERIMAGE: Final = 512 +SS_RIGHTJUST: Final = 1024 +SS_REALSIZEIMAGE: Final = 2048 +SS_SUNKEN: Final = 4096 +SS_ENDELLIPSIS: Final = 16384 +SS_PATHELLIPSIS: Final = 32768 +SS_WORDELLIPSIS: Final = 49152 +SS_ELLIPSISMASK: Final = 49152 +STM_SETICON: Final = 368 +STM_GETICON: Final = 369 +STM_SETIMAGE: Final = 370 +STM_GETIMAGE: Final = 371 +STN_CLICKED: Final = 0 +STN_DBLCLK: Final = 1 +STN_ENABLE: Final = 2 +STN_DISABLE: Final = 3 +STM_MSGMAX: Final = 372 +DWL_MSGRESULT: Final = 0 +DWL_DLGPROC: Final = 4 +DWL_USER: Final = 8 +DDL_READWRITE: Final = 0 +DDL_READONLY: Final = 1 +DDL_HIDDEN: Final = 2 +DDL_SYSTEM: Final = 4 +DDL_DIRECTORY: Final = 16 +DDL_ARCHIVE: Final = 32 +DDL_POSTMSGS: Final = 8192 +DDL_DRIVES: Final = 16384 +DDL_EXCLUSIVE: Final = 32768 + +RT_CURSOR: Final = 1 +RT_BITMAP: Final = 2 +RT_ICON: Final = 3 +RT_MENU: Final = 4 +RT_DIALOG: Final = 5 +RT_STRING: Final = 6 +RT_FONTDIR: Final = 7 +RT_FONT: Final = 8 +RT_ACCELERATOR: Final = 9 +RT_RCDATA: Final = 10 +RT_MESSAGETABLE: Final = 11 +DIFFERENCE: Final = 11 +RT_GROUP_CURSOR: Final[int] +RT_GROUP_ICON: Final[int] +RT_VERSION: Final = 16 +RT_DLGINCLUDE: Final = 17 +RT_PLUGPLAY: Final = 19 +RT_VXD: Final = 20 +RT_ANICURSOR: Final = 21 +RT_ANIICON: Final = 22 +RT_HTML: Final = 23 + +SB_HORZ: Final = 0 +SB_VERT: Final = 1 +SB_CTL: Final = 2 +SB_BOTH: Final = 3 +SB_LINEUP: Final = 0 +SB_LINELEFT: Final = 0 +SB_LINEDOWN: Final = 1 +SB_LINERIGHT: Final = 1 +SB_PAGEUP: Final = 2 +SB_PAGELEFT: Final = 2 +SB_PAGEDOWN: Final = 3 +SB_PAGERIGHT: Final = 3 +SB_THUMBPOSITION: Final = 4 +SB_THUMBTRACK: Final = 5 +SB_TOP: Final = 6 +SB_LEFT: Final = 6 +SB_BOTTOM: Final = 7 +SB_RIGHT: Final = 7 +SB_ENDSCROLL: Final = 8 +SW_HIDE: Final = 0 +SW_SHOWNORMAL: Final = 1 +SW_NORMAL: Final = 1 +SW_SHOWMINIMIZED: Final = 2 +SW_SHOWMAXIMIZED: Final = 3 +SW_MAXIMIZE: Final = 3 +SW_SHOWNOACTIVATE: Final = 4 +SW_SHOW: Final = 5 +SW_MINIMIZE: Final = 6 +SW_SHOWMINNOACTIVE: Final = 7 +SW_SHOWNA: Final = 8 +SW_RESTORE: Final = 9 +SW_SHOWDEFAULT: Final = 10 +SW_FORCEMINIMIZE: Final = 11 +SW_MAX: Final = 11 +HIDE_WINDOW: Final = 0 +SHOW_OPENWINDOW: Final = 1 +SHOW_ICONWINDOW: Final = 2 +SHOW_FULLSCREEN: Final = 3 +SHOW_OPENNOACTIVATE: Final = 4 +SW_PARENTCLOSING: Final = 1 +SW_OTHERZOOM: Final = 2 +SW_PARENTOPENING: Final = 3 +SW_OTHERUNZOOM: Final = 4 +AW_HOR_POSITIVE: Final = 1 +AW_HOR_NEGATIVE: Final = 2 +AW_VER_POSITIVE: Final = 4 +AW_VER_NEGATIVE: Final = 8 +AW_CENTER: Final = 16 +AW_HIDE: Final = 65536 +AW_ACTIVATE: Final = 131072 +AW_SLIDE: Final = 262144 +AW_BLEND: Final = 524288 +KF_EXTENDED: Final = 256 +KF_DLGMODE: Final = 2048 +KF_MENUMODE: Final = 4096 +KF_ALTDOWN: Final = 8192 +KF_REPEAT: Final = 16384 +KF_UP: Final = 32768 +VK_LBUTTON: Final = 1 +VK_RBUTTON: Final = 2 +VK_CANCEL: Final = 3 +VK_MBUTTON: Final = 4 +VK_BACK: Final = 8 +VK_TAB: Final = 9 +VK_CLEAR: Final = 12 +VK_RETURN: Final = 13 +VK_SHIFT: Final = 16 +VK_CONTROL: Final = 17 +VK_MENU: Final = 18 +VK_PAUSE: Final = 19 +VK_CAPITAL: Final = 20 +VK_KANA: Final = 21 +VK_HANGEUL: Final = 21 +VK_HANGUL: Final = 21 +VK_JUNJA: Final = 23 +VK_FINAL: Final = 24 +VK_HANJA: Final = 25 +VK_KANJI: Final = 25 +VK_ESCAPE: Final = 27 +VK_CONVERT: Final = 28 +VK_NONCONVERT: Final = 29 +VK_ACCEPT: Final = 30 +VK_MODECHANGE: Final = 31 +VK_SPACE: Final = 32 +VK_PRIOR: Final = 33 +VK_NEXT: Final = 34 +VK_END: Final = 35 +VK_HOME: Final = 36 +VK_LEFT: Final = 37 +VK_UP: Final = 38 +VK_RIGHT: Final = 39 +VK_DOWN: Final = 40 +VK_SELECT: Final = 41 +VK_PRINT: Final = 42 +VK_EXECUTE: Final = 43 +VK_SNAPSHOT: Final = 44 +VK_INSERT: Final = 45 +VK_DELETE: Final = 46 +VK_HELP: Final = 47 +VK_LWIN: Final = 91 +VK_RWIN: Final = 92 +VK_APPS: Final = 93 +VK_NUMPAD0: Final = 96 +VK_NUMPAD1: Final = 97 +VK_NUMPAD2: Final = 98 +VK_NUMPAD3: Final = 99 +VK_NUMPAD4: Final = 100 +VK_NUMPAD5: Final = 101 +VK_NUMPAD6: Final = 102 +VK_NUMPAD7: Final = 103 +VK_NUMPAD8: Final = 104 +VK_NUMPAD9: Final = 105 +VK_MULTIPLY: Final = 106 +VK_ADD: Final = 107 +VK_SEPARATOR: Final = 108 +VK_SUBTRACT: Final = 109 +VK_DECIMAL: Final = 110 +VK_DIVIDE: Final = 111 +VK_F1: Final = 112 +VK_F2: Final = 113 +VK_F3: Final = 114 +VK_F4: Final = 115 +VK_F5: Final = 116 +VK_F6: Final = 117 +VK_F7: Final = 118 +VK_F8: Final = 119 +VK_F9: Final = 120 +VK_F10: Final = 121 +VK_F11: Final = 122 +VK_F12: Final = 123 +VK_F13: Final = 124 +VK_F14: Final = 125 +VK_F15: Final = 126 +VK_F16: Final = 127 +VK_F17: Final = 128 +VK_F18: Final = 129 +VK_F19: Final = 130 +VK_F20: Final = 131 +VK_F21: Final = 132 +VK_F22: Final = 133 +VK_F23: Final = 134 +VK_F24: Final = 135 +VK_NUMLOCK: Final = 144 +VK_SCROLL: Final = 145 +VK_LSHIFT: Final = 160 +VK_RSHIFT: Final = 161 +VK_LCONTROL: Final = 162 +VK_RCONTROL: Final = 163 +VK_LMENU: Final = 164 +VK_RMENU: Final = 165 +VK_PROCESSKEY: Final = 229 +VK_ATTN: Final = 246 +VK_CRSEL: Final = 247 +VK_EXSEL: Final = 248 +VK_EREOF: Final = 249 +VK_PLAY: Final = 250 +VK_ZOOM: Final = 251 +VK_NONAME: Final = 252 +VK_PA1: Final = 253 +VK_OEM_CLEAR: Final = 254 + +VK_XBUTTON1: Final = 0x05 +VK_XBUTTON2: Final = 0x06 +VK_VOLUME_MUTE: Final = 0xAD +VK_VOLUME_DOWN: Final = 0xAE +VK_VOLUME_UP: Final = 0xAF +VK_MEDIA_NEXT_TRACK: Final = 0xB0 +VK_MEDIA_PREV_TRACK: Final = 0xB1 +VK_MEDIA_PLAY_PAUSE: Final = 0xB3 +VK_BROWSER_BACK: Final = 0xA6 +VK_BROWSER_FORWARD: Final = 0xA7 +WH_MIN: Final = -1 +WH_MSGFILTER: Final = -1 +WH_JOURNALRECORD: Final = 0 +WH_JOURNALPLAYBACK: Final = 1 +WH_KEYBOARD: Final = 2 +WH_GETMESSAGE: Final = 3 +WH_CALLWNDPROC: Final = 4 +WH_CBT: Final = 5 +WH_SYSMSGFILTER: Final = 6 +WH_MOUSE: Final = 7 +WH_HARDWARE: Final = 8 +WH_DEBUG: Final = 9 +WH_SHELL: Final = 10 +WH_FOREGROUNDIDLE: Final = 11 +WH_CALLWNDPROCRET: Final = 12 +WH_KEYBOARD_LL: Final = 13 +WH_MOUSE_LL: Final = 14 +WH_MAX: Final = 14 +WH_MINHOOK: Final = WH_MIN +WH_MAXHOOK: Final = WH_MAX +HC_ACTION: Final = 0 +HC_GETNEXT: Final = 1 +HC_SKIP: Final = 2 +HC_NOREMOVE: Final = 3 +HC_NOREM: Final = HC_NOREMOVE +HC_SYSMODALON: Final = 4 +HC_SYSMODALOFF: Final = 5 +HCBT_MOVESIZE: Final = 0 +HCBT_MINMAX: Final = 1 +HCBT_QS: Final = 2 +HCBT_CREATEWND: Final = 3 +HCBT_DESTROYWND: Final = 4 +HCBT_ACTIVATE: Final = 5 +HCBT_CLICKSKIPPED: Final = 6 +HCBT_KEYSKIPPED: Final = 7 +HCBT_SYSCOMMAND: Final = 8 +HCBT_SETFOCUS: Final = 9 +MSGF_DIALOGBOX: Final = 0 +MSGF_MESSAGEBOX: Final = 1 +MSGF_MENU: Final = 2 + +MSGF_SCROLLBAR: Final = 5 +MSGF_NEXTWINDOW: Final = 6 + +MSGF_MAX: Final = 8 +MSGF_USER: Final = 4096 +HSHELL_WINDOWCREATED: Final = 1 +HSHELL_WINDOWDESTROYED: Final = 2 +HSHELL_ACTIVATESHELLWINDOW: Final = 3 +HSHELL_WINDOWACTIVATED: Final = 4 +HSHELL_GETMINRECT: Final = 5 +HSHELL_REDRAW: Final = 6 +HSHELL_TASKMAN: Final = 7 +HSHELL_LANGUAGE: Final = 8 +HSHELL_ACCESSIBILITYSTATE: Final = 11 +ACCESS_STICKYKEYS: Final = 1 +ACCESS_FILTERKEYS: Final = 2 +ACCESS_MOUSEKEYS: Final = 3 + +LLKHF_EXTENDED: Final = 1 +LLKHF_INJECTED: Final = 16 +LLKHF_ALTDOWN: Final = 32 +LLKHF_UP: Final = 128 +LLKHF_LOWER_IL_INJECTED: Final = 2 +LLMHF_INJECTED: Final = 1 +LLMHF_LOWER_IL_INJECTED: Final = 2 + +HKL_PREV: Final = 0 +HKL_NEXT: Final = 1 +KLF_ACTIVATE: Final = 1 +KLF_SUBSTITUTE_OK: Final = 2 +KLF_UNLOADPREVIOUS: Final = 4 +KLF_REORDER: Final = 8 +KLF_REPLACELANG: Final = 16 +KLF_NOTELLSHELL: Final = 128 +KLF_SETFORPROCESS: Final = 256 +KL_NAMELENGTH: Final = 9 +DESKTOP_READOBJECTS: Final = 1 +DESKTOP_CREATEWINDOW: Final = 2 +DESKTOP_CREATEMENU: Final = 4 +DESKTOP_HOOKCONTROL: Final = 8 +DESKTOP_JOURNALRECORD: Final = 16 +DESKTOP_JOURNALPLAYBACK: Final = 32 +DESKTOP_ENUMERATE: Final = 64 +DESKTOP_WRITEOBJECTS: Final = 128 +DESKTOP_SWITCHDESKTOP: Final = 256 +DF_ALLOWOTHERACCOUNTHOOK: Final = 1 +WINSTA_ENUMDESKTOPS: Final = 1 +WINSTA_READATTRIBUTES: Final = 2 +WINSTA_ACCESSCLIPBOARD: Final = 4 +WINSTA_CREATEDESKTOP: Final = 8 +WINSTA_WRITEATTRIBUTES: Final = 16 +WINSTA_ACCESSGLOBALATOMS: Final = 32 +WINSTA_EXITWINDOWS: Final = 64 +WINSTA_ENUMERATE: Final = 256 +WINSTA_READSCREEN: Final = 512 +WSF_VISIBLE: Final = 1 +UOI_FLAGS: Final = 1 +UOI_NAME: Final = 2 +UOI_TYPE: Final = 3 +UOI_USER_SID: Final = 4 +GWL_WNDPROC: Final = -4 +GWL_HINSTANCE: Final = -6 +GWL_HWNDPARENT: Final = -8 +GWL_STYLE: Final = -16 +GWL_EXSTYLE: Final = -20 +GWL_USERDATA: Final = -21 +GWL_ID: Final = -12 +GCL_MENUNAME: Final = -8 +GCL_HBRBACKGROUND: Final = -10 +GCL_HCURSOR: Final = -12 +GCL_HICON: Final = -14 +GCL_HMODULE: Final = -16 +GCL_CBWNDEXTRA: Final = -18 +GCL_CBCLSEXTRA: Final = -20 +GCL_WNDPROC: Final = -24 +GCL_STYLE: Final = -26 +GCW_ATOM: Final = -32 +GCL_HICONSM: Final = -34 + +WM_NULL: Final = 0 +WM_CREATE: Final = 1 +WM_DESTROY: Final = 2 +WM_MOVE: Final = 3 +WM_SIZE: Final = 5 +WM_ACTIVATE: Final = 6 +WA_INACTIVE: Final = 0 +WA_ACTIVE: Final = 1 +WA_CLICKACTIVE: Final = 2 +WM_SETFOCUS: Final = 7 +WM_KILLFOCUS: Final = 8 +WM_ENABLE: Final = 10 +WM_SETREDRAW: Final = 11 +WM_SETTEXT: Final = 12 +WM_GETTEXT: Final = 13 +WM_GETTEXTLENGTH: Final = 14 +WM_PAINT: Final = 15 +WM_CLOSE: Final = 16 +WM_QUERYENDSESSION: Final = 17 +WM_QUIT: Final = 18 +WM_QUERYOPEN: Final = 19 +WM_ERASEBKGND: Final = 20 +WM_SYSCOLORCHANGE: Final = 21 +WM_ENDSESSION: Final = 22 +WM_SHOWWINDOW: Final = 24 +WM_WININICHANGE: Final = 26 +WM_SETTINGCHANGE: Final = WM_WININICHANGE +WM_DEVMODECHANGE: Final = 27 +WM_ACTIVATEAPP: Final = 28 +WM_FONTCHANGE: Final = 29 +WM_TIMECHANGE: Final = 30 +WM_CANCELMODE: Final = 31 +WM_SETCURSOR: Final = 32 +WM_MOUSEACTIVATE: Final = 33 +WM_CHILDACTIVATE: Final = 34 +WM_QUEUESYNC: Final = 35 +WM_GETMINMAXINFO: Final = 36 +WM_PAINTICON: Final = 38 +WM_ICONERASEBKGND: Final = 39 +WM_NEXTDLGCTL: Final = 40 +WM_SPOOLERSTATUS: Final = 42 +WM_DRAWITEM: Final = 43 +WM_MEASUREITEM: Final = 44 +WM_DELETEITEM: Final = 45 +WM_VKEYTOITEM: Final = 46 +WM_CHARTOITEM: Final = 47 +WM_SETFONT: Final = 48 +WM_GETFONT: Final = 49 +WM_SETHOTKEY: Final = 50 +WM_GETHOTKEY: Final = 51 +WM_QUERYDRAGICON: Final = 55 +WM_COMPAREITEM: Final = 57 +WM_GETOBJECT: Final = 61 +WM_COMPACTING: Final = 65 +WM_COMMNOTIFY: Final = 68 +WM_WINDOWPOSCHANGING: Final = 70 +WM_WINDOWPOSCHANGED: Final = 71 +WM_POWER: Final = 72 +PWR_OK: Final = 1 +PWR_FAIL: Final = -1 +PWR_SUSPENDREQUEST: Final = 1 +PWR_SUSPENDRESUME: Final = 2 +PWR_CRITICALRESUME: Final = 3 +WM_COPYDATA: Final = 74 +WM_CANCELJOURNAL: Final = 75 +WM_INPUTLANGCHANGEREQUEST: Final = 80 +WM_INPUTLANGCHANGE: Final = 81 +WM_TCARD: Final = 82 +WM_HELP: Final = 83 +WM_USERCHANGED: Final = 84 +WM_NOTIFYFORMAT: Final = 85 +NFR_ANSI: Final = 1 +NFR_UNICODE: Final = 2 +NF_QUERY: Final = 3 +NF_REQUERY: Final = 4 +WM_STYLECHANGING: Final = 124 +WM_STYLECHANGED: Final = 125 +WM_DISPLAYCHANGE: Final = 126 +WM_GETICON: Final = 127 +WM_SETICON: Final = 128 +WM_NCCREATE: Final = 129 +WM_NCDESTROY: Final = 130 +WM_NCCALCSIZE: Final = 131 +WM_NCHITTEST: Final = 132 +WM_NCPAINT: Final = 133 +WM_NCACTIVATE: Final = 134 +WM_GETDLGCODE: Final = 135 +WM_SYNCPAINT: Final = 136 +WM_NCMOUSEMOVE: Final = 160 +WM_NCLBUTTONDOWN: Final = 161 +WM_NCLBUTTONUP: Final = 162 +WM_NCLBUTTONDBLCLK: Final = 163 +WM_NCRBUTTONDOWN: Final = 164 +WM_NCRBUTTONUP: Final = 165 +WM_NCRBUTTONDBLCLK: Final = 166 +WM_NCMBUTTONDOWN: Final = 167 +WM_NCMBUTTONUP: Final = 168 +WM_NCMBUTTONDBLCLK: Final = 169 +WM_KEYFIRST: Final = 256 +WM_KEYDOWN: Final = 256 +WM_KEYUP: Final = 257 +WM_CHAR: Final = 258 +WM_DEADCHAR: Final = 259 +WM_SYSKEYDOWN: Final = 260 +WM_SYSKEYUP: Final = 261 +WM_SYSCHAR: Final = 262 +WM_SYSDEADCHAR: Final = 263 +WM_KEYLAST: Final = 264 +WM_IME_STARTCOMPOSITION: Final = 269 +WM_IME_ENDCOMPOSITION: Final = 270 +WM_IME_COMPOSITION: Final = 271 +WM_IME_KEYLAST: Final = 271 +WM_INITDIALOG: Final = 272 +WM_COMMAND: Final = 273 +WM_SYSCOMMAND: Final = 274 +WM_TIMER: Final = 275 +WM_HSCROLL: Final = 276 +WM_VSCROLL: Final = 277 +WM_INITMENU: Final = 278 +WM_INITMENUPOPUP: Final = 279 +WM_MENUSELECT: Final = 287 +WM_MENUCHAR: Final = 288 +WM_ENTERIDLE: Final = 289 +WM_MENURBUTTONUP: Final = 290 +WM_MENUDRAG: Final = 291 +WM_MENUGETOBJECT: Final = 292 +WM_UNINITMENUPOPUP: Final = 293 +WM_MENUCOMMAND: Final = 294 +WM_CTLCOLORMSGBOX: Final = 306 +WM_CTLCOLOREDIT: Final = 307 +WM_CTLCOLORLISTBOX: Final = 308 +WM_CTLCOLORBTN: Final = 309 +WM_CTLCOLORDLG: Final = 310 +WM_CTLCOLORSCROLLBAR: Final = 311 +WM_CTLCOLORSTATIC: Final = 312 +WM_MOUSEFIRST: Final = 512 +WM_MOUSEMOVE: Final = 512 +WM_LBUTTONDOWN: Final = 513 +WM_LBUTTONUP: Final = 514 +WM_LBUTTONDBLCLK: Final = 515 +WM_RBUTTONDOWN: Final = 516 +WM_RBUTTONUP: Final = 517 +WM_RBUTTONDBLCLK: Final = 518 +WM_MBUTTONDOWN: Final = 519 +WM_MBUTTONUP: Final = 520 +WM_MBUTTONDBLCLK: Final = 521 +WM_MOUSEWHEEL: Final = 522 +WM_MOUSELAST: Final = 522 +WHEEL_DELTA: Final = 120 +WHEEL_PAGESCROLL: Final = -1 +WM_PARENTNOTIFY: Final = 528 +MENULOOP_WINDOW: Final = 0 +MENULOOP_POPUP: Final = 1 +WM_ENTERMENULOOP: Final = 529 +WM_EXITMENULOOP: Final = 530 +WM_NEXTMENU: Final = 531 +WM_SIZING: Final = 532 +WM_CAPTURECHANGED: Final = 533 +WM_MOVING: Final = 534 +WM_POWERBROADCAST: Final = 536 +PBT_APMQUERYSUSPEND: Final = 0 +PBT_APMQUERYSTANDBY: Final = 1 +PBT_APMQUERYSUSPENDFAILED: Final = 2 +PBT_APMQUERYSTANDBYFAILED: Final = 3 +PBT_APMSUSPEND: Final = 4 +PBT_APMSTANDBY: Final = 5 +PBT_APMRESUMECRITICAL: Final = 6 +PBT_APMRESUMESUSPEND: Final = 7 +PBT_APMRESUMESTANDBY: Final = 8 +PBTF_APMRESUMEFROMFAILURE: Final = 1 +PBT_APMBATTERYLOW: Final = 9 +PBT_APMPOWERSTATUSCHANGE: Final = 10 +PBT_APMOEMEVENT: Final = 11 +PBT_APMRESUMEAUTOMATIC: Final = 18 +WM_MDICREATE: Final = 544 +WM_MDIDESTROY: Final = 545 +WM_MDIACTIVATE: Final = 546 +WM_MDIRESTORE: Final = 547 +WM_MDINEXT: Final = 548 +WM_MDIMAXIMIZE: Final = 549 +WM_MDITILE: Final = 550 +WM_MDICASCADE: Final = 551 +WM_MDIICONARRANGE: Final = 552 +WM_MDIGETACTIVE: Final = 553 +WM_MDISETMENU: Final = 560 +WM_ENTERSIZEMOVE: Final = 561 +WM_EXITSIZEMOVE: Final = 562 +WM_DROPFILES: Final = 563 +WM_MDIREFRESHMENU: Final = 564 +WM_IME_SETCONTEXT: Final = 641 +WM_IME_NOTIFY: Final = 642 +WM_IME_CONTROL: Final = 643 +WM_IME_COMPOSITIONFULL: Final = 644 +WM_IME_SELECT: Final = 645 +WM_IME_CHAR: Final = 646 +WM_IME_REQUEST: Final = 648 +WM_IME_KEYDOWN: Final = 656 +WM_IME_KEYUP: Final = 657 +WM_MOUSEHOVER: Final = 673 +WM_MOUSELEAVE: Final = 675 +WM_CUT: Final = 768 +WM_COPY: Final = 769 +WM_PASTE: Final = 770 +WM_CLEAR: Final = 771 +WM_UNDO: Final = 772 +WM_RENDERFORMAT: Final = 773 +WM_RENDERALLFORMATS: Final = 774 +WM_DESTROYCLIPBOARD: Final = 775 +WM_DRAWCLIPBOARD: Final = 776 +WM_PAINTCLIPBOARD: Final = 777 +WM_VSCROLLCLIPBOARD: Final = 778 +WM_SIZECLIPBOARD: Final = 779 +WM_ASKCBFORMATNAME: Final = 780 +WM_CHANGECBCHAIN: Final = 781 +WM_HSCROLLCLIPBOARD: Final = 782 +WM_QUERYNEWPALETTE: Final = 783 +WM_PALETTEISCHANGING: Final = 784 +WM_PALETTECHANGED: Final = 785 +WM_HOTKEY: Final = 786 +WM_PRINT: Final = 791 +WM_HANDHELDFIRST: Final = 856 +WM_HANDHELDLAST: Final = 863 +WM_AFXFIRST: Final = 864 +WM_AFXLAST: Final = 895 +WM_PENWINFIRST: Final = 896 +WM_PENWINLAST: Final = 911 +WM_APP: Final = 32768 +WMSZ_LEFT: Final = 1 +WMSZ_RIGHT: Final = 2 +WMSZ_TOP: Final = 3 +WMSZ_TOPLEFT: Final = 4 +WMSZ_TOPRIGHT: Final = 5 +WMSZ_BOTTOM: Final = 6 +WMSZ_BOTTOMLEFT: Final = 7 +WMSZ_BOTTOMRIGHT: Final = 8 + +HTERROR: Final = -2 +HTTRANSPARENT: Final = -1 +HTNOWHERE: Final = 0 +HTCLIENT: Final = 1 +HTCAPTION: Final = 2 +HTSYSMENU: Final = 3 +HTGROWBOX: Final = 4 +HTSIZE: Final = HTGROWBOX +HTMENU: Final = 5 +HTHSCROLL: Final = 6 +HTVSCROLL: Final = 7 +HTMINBUTTON: Final = 8 +HTMAXBUTTON: Final = 9 +HTLEFT: Final = 10 +HTRIGHT: Final = 11 +HTTOP: Final = 12 +HTTOPLEFT: Final = 13 +HTTOPRIGHT: Final = 14 +HTBOTTOM: Final = 15 +HTBOTTOMLEFT: Final = 16 +HTBOTTOMRIGHT: Final = 17 +HTBORDER: Final = 18 +HTREDUCE: Final = HTMINBUTTON +HTZOOM: Final = HTMAXBUTTON +HTSIZEFIRST: Final = HTLEFT +HTSIZELAST: Final = HTBOTTOMRIGHT +HTOBJECT: Final = 19 +HTCLOSE: Final = 20 +HTHELP: Final = 21 +SMTO_NORMAL: Final = 0 +SMTO_BLOCK: Final = 1 +SMTO_ABORTIFHUNG: Final = 2 +SMTO_NOTIMEOUTIFNOTHUNG: Final = 8 +MA_ACTIVATE: Final = 1 +MA_ACTIVATEANDEAT: Final = 2 +MA_NOACTIVATE: Final = 3 +MA_NOACTIVATEANDEAT: Final = 4 +ICON_SMALL: Final = 0 +ICON_BIG: Final = 1 +SIZE_RESTORED: Final = 0 +SIZE_MINIMIZED: Final = 1 +SIZE_MAXIMIZED: Final = 2 +SIZE_MAXSHOW: Final = 3 +SIZE_MAXHIDE: Final = 4 +SIZENORMAL: Final = SIZE_RESTORED +SIZEICONIC: Final = SIZE_MINIMIZED +SIZEFULLSCREEN: Final = SIZE_MAXIMIZED +SIZEZOOMSHOW: Final = SIZE_MAXSHOW +SIZEZOOMHIDE: Final = SIZE_MAXHIDE +WVR_ALIGNTOP: Final = 16 +WVR_ALIGNLEFT: Final = 32 +WVR_ALIGNBOTTOM: Final = 64 +WVR_ALIGNRIGHT: Final = 128 +WVR_HREDRAW: Final = 256 +WVR_VREDRAW: Final = 512 +WVR_REDRAW: Final[int] +WVR_VALIDRECTS: Final = 1024 +MK_LBUTTON: Final = 1 +MK_RBUTTON: Final = 2 +MK_SHIFT: Final = 4 +MK_CONTROL: Final = 8 +MK_MBUTTON: Final = 16 +TME_HOVER: Final = 1 +TME_LEAVE: Final = 2 +TME_QUERY: Final = 1073741824 +TME_CANCEL: Final = -2147483648 +HOVER_DEFAULT: Final = -1 +WS_OVERLAPPED: Final = 0 +WS_POPUP: Final = -2147483648 +WS_CHILD: Final = 1073741824 +WS_MINIMIZE: Final = 536870912 +WS_VISIBLE: Final = 268435456 +WS_DISABLED: Final = 134217728 +WS_CLIPSIBLINGS: Final = 67108864 +WS_CLIPCHILDREN: Final = 33554432 +WS_MAXIMIZE: Final = 16777216 +WS_CAPTION: Final = 12582912 +WS_BORDER: Final = 8388608 +WS_DLGFRAME: Final = 4194304 +WS_VSCROLL: Final = 2097152 +WS_HSCROLL: Final = 1048576 +WS_SYSMENU: Final = 524288 +WS_THICKFRAME: Final = 262144 +WS_GROUP: Final = 131072 +WS_TABSTOP: Final = 65536 +WS_MINIMIZEBOX: Final = 131072 +WS_MAXIMIZEBOX: Final = 65536 +WS_TILED: Final = WS_OVERLAPPED +WS_ICONIC: Final = WS_MINIMIZE +WS_SIZEBOX: Final = WS_THICKFRAME +WS_OVERLAPPEDWINDOW: Final[int] +WS_POPUPWINDOW: Final[int] +WS_CHILDWINDOW: Final = WS_CHILD +WS_TILEDWINDOW: Final = WS_OVERLAPPEDWINDOW +WS_EX_DLGMODALFRAME: Final = 1 +WS_EX_NOPARENTNOTIFY: Final = 4 +WS_EX_TOPMOST: Final = 8 +WS_EX_ACCEPTFILES: Final = 16 +WS_EX_TRANSPARENT: Final = 32 +WS_EX_MDICHILD: Final = 64 +WS_EX_TOOLWINDOW: Final = 128 +WS_EX_WINDOWEDGE: Final = 256 +WS_EX_CLIENTEDGE: Final = 512 +WS_EX_CONTEXTHELP: Final = 1024 +WS_EX_RIGHT: Final = 4096 +WS_EX_LEFT: Final = 0 +WS_EX_RTLREADING: Final = 8192 +WS_EX_LTRREADING: Final = 0 +WS_EX_LEFTSCROLLBAR: Final = 16384 +WS_EX_RIGHTSCROLLBAR: Final = 0 +WS_EX_CONTROLPARENT: Final = 65536 +WS_EX_STATICEDGE: Final = 131072 +WS_EX_APPWINDOW: Final = 262144 +WS_EX_OVERLAPPEDWINDOW: Final[int] +WS_EX_PALETTEWINDOW: Final[int] +WS_EX_LAYERED: Final = 0x00080000 +WS_EX_NOINHERITLAYOUT: Final = 0x00100000 +WS_EX_LAYOUTRTL: Final = 0x00400000 +WS_EX_COMPOSITED: Final = 0x02000000 +WS_EX_NOACTIVATE: Final = 0x08000000 + +CS_VREDRAW: Final = 1 +CS_HREDRAW: Final = 2 + +CS_DBLCLKS: Final = 8 +CS_OWNDC: Final = 32 +CS_CLASSDC: Final = 64 +CS_PARENTDC: Final = 128 + +CS_NOCLOSE: Final = 512 +CS_SAVEBITS: Final = 2048 +CS_BYTEALIGNCLIENT: Final = 4096 +CS_BYTEALIGNWINDOW: Final = 8192 +CS_GLOBALCLASS: Final = 16384 +CS_IME: Final = 65536 +PRF_CHECKVISIBLE: Final = 1 +PRF_NONCLIENT: Final = 2 +PRF_CLIENT: Final = 4 +PRF_ERASEBKGND: Final = 8 +PRF_CHILDREN: Final = 16 +PRF_OWNED: Final = 32 +BDR_RAISEDOUTER: Final = 1 +BDR_SUNKENOUTER: Final = 2 +BDR_RAISEDINNER: Final = 4 +BDR_SUNKENINNER: Final = 8 +BDR_OUTER: Final = 3 +BDR_INNER: Final = 12 + +EDGE_RAISED: Final[int] +EDGE_SUNKEN: Final[int] +EDGE_ETCHED: Final[int] +EDGE_BUMP: Final[int] + +ISMEX_NOSEND: Final = 0 +ISMEX_SEND: Final = 1 +ISMEX_NOTIFY: Final = 2 +ISMEX_CALLBACK: Final = 4 +ISMEX_REPLIED: Final = 8 +CW_USEDEFAULT: Final = -2147483648 +FLASHW_STOP: Final = 0 +FLASHW_CAPTION: Final = 1 +FLASHW_TRAY: Final = 2 +FLASHW_ALL: Final[int] +FLASHW_TIMER: Final = 4 +FLASHW_TIMERNOFG: Final = 12 + +DS_ABSALIGN: Final = 1 +DS_SYSMODAL: Final = 2 +DS_LOCALEDIT: Final = 32 +DS_SETFONT: Final = 64 +DS_MODALFRAME: Final = 128 +DS_NOIDLEMSG: Final = 256 +DS_SETFOREGROUND: Final = 512 +DS_3DLOOK: Final = 4 +DS_FIXEDSYS: Final = 8 +DS_NOFAILCREATE: Final = 16 +DS_CONTROL: Final = 1024 +DS_CENTER: Final = 2048 +DS_CENTERMOUSE: Final = 4096 +DS_CONTEXTHELP: Final = 8192 +DM_GETDEFID: Final[int] +DM_SETDEFID: Final[int] +DM_REPOSITION: Final[int] + +DC_HASDEFID: Final = 21323 +DLGC_WANTARROWS: Final = 1 +DLGC_WANTTAB: Final = 2 +DLGC_WANTALLKEYS: Final = 4 +DLGC_WANTMESSAGE: Final = 4 +DLGC_HASSETSEL: Final = 8 +DLGC_DEFPUSHBUTTON: Final = 16 +DLGC_UNDEFPUSHBUTTON: Final = 32 +DLGC_RADIOBUTTON: Final = 64 +DLGC_WANTCHARS: Final = 128 +DLGC_STATIC: Final = 256 +DLGC_BUTTON: Final = 8192 +LB_CTLCODE: Final = 0 +LB_OKAY: Final = 0 +LB_ERR: Final = -1 +LB_ERRSPACE: Final = -2 +LBN_ERRSPACE: Final = -2 +LBN_SELCHANGE: Final = 1 +LBN_DBLCLK: Final = 2 +LBN_SELCANCEL: Final = 3 +LBN_SETFOCUS: Final = 4 +LBN_KILLFOCUS: Final = 5 +LB_ADDSTRING: Final = 384 +LB_INSERTSTRING: Final = 385 +LB_DELETESTRING: Final = 386 +LB_SELITEMRANGEEX: Final = 387 +LB_RESETCONTENT: Final = 388 +LB_SETSEL: Final = 389 +LB_SETCURSEL: Final = 390 +LB_GETSEL: Final = 391 +LB_GETCURSEL: Final = 392 +LB_GETTEXT: Final = 393 +LB_GETTEXTLEN: Final = 394 +LB_GETCOUNT: Final = 395 +LB_SELECTSTRING: Final = 396 +LB_DIR: Final = 397 +LB_GETTOPINDEX: Final = 398 +LB_FINDSTRING: Final = 399 +LB_GETSELCOUNT: Final = 400 +LB_GETSELITEMS: Final = 401 +LB_SETTABSTOPS: Final = 402 +LB_GETHORIZONTALEXTENT: Final = 403 +LB_SETHORIZONTALEXTENT: Final = 404 +LB_SETCOLUMNWIDTH: Final = 405 +LB_ADDFILE: Final = 406 +LB_SETTOPINDEX: Final = 407 +LB_GETITEMRECT: Final = 408 +LB_GETITEMDATA: Final = 409 +LB_SETITEMDATA: Final = 410 +LB_SELITEMRANGE: Final = 411 +LB_SETANCHORINDEX: Final = 412 +LB_GETANCHORINDEX: Final = 413 +LB_SETCARETINDEX: Final = 414 +LB_GETCARETINDEX: Final = 415 +LB_SETITEMHEIGHT: Final = 416 +LB_GETITEMHEIGHT: Final = 417 +LB_FINDSTRINGEXACT: Final = 418 +LB_SETLOCALE: Final = 421 +LB_GETLOCALE: Final = 422 +LB_SETCOUNT: Final = 423 +LB_INITSTORAGE: Final = 424 +LB_ITEMFROMPOINT: Final = 425 +LB_MSGMAX: Final = 432 +LBS_NOTIFY: Final = 1 +LBS_SORT: Final = 2 +LBS_NOREDRAW: Final = 4 +LBS_MULTIPLESEL: Final = 8 +LBS_OWNERDRAWFIXED: Final = 16 +LBS_OWNERDRAWVARIABLE: Final = 32 +LBS_HASSTRINGS: Final = 64 +LBS_USETABSTOPS: Final = 128 +LBS_NOINTEGRALHEIGHT: Final = 256 +LBS_MULTICOLUMN: Final = 512 +LBS_WANTKEYBOARDINPUT: Final = 1024 +LBS_EXTENDEDSEL: Final = 2048 +LBS_DISABLENOSCROLL: Final = 4096 +LBS_NODATA: Final = 8192 +LBS_NOSEL: Final = 16384 +LBS_STANDARD: Final[int] +CB_OKAY: Final = 0 +CB_ERR: Final = -1 +CB_ERRSPACE: Final = -2 +CBN_ERRSPACE: Final = -1 +CBN_SELCHANGE: Final = 1 +CBN_DBLCLK: Final = 2 +CBN_SETFOCUS: Final = 3 +CBN_KILLFOCUS: Final = 4 +CBN_EDITCHANGE: Final = 5 +CBN_EDITUPDATE: Final = 6 +CBN_DROPDOWN: Final = 7 +CBN_CLOSEUP: Final = 8 +CBN_SELENDOK: Final = 9 +CBN_SELENDCANCEL: Final = 10 +CBS_SIMPLE: Final = 1 +CBS_DROPDOWN: Final = 2 +CBS_DROPDOWNLIST: Final = 3 +CBS_OWNERDRAWFIXED: Final = 16 +CBS_OWNERDRAWVARIABLE: Final = 32 +CBS_AUTOHSCROLL: Final = 64 +CBS_OEMCONVERT: Final = 128 +CBS_SORT: Final = 256 +CBS_HASSTRINGS: Final = 512 +CBS_NOINTEGRALHEIGHT: Final = 1024 +CBS_DISABLENOSCROLL: Final = 2048 +CBS_UPPERCASE: Final = 8192 +CBS_LOWERCASE: Final = 16384 +CB_GETEDITSEL: Final = 320 +CB_LIMITTEXT: Final = 321 +CB_SETEDITSEL: Final = 322 +CB_ADDSTRING: Final = 323 +CB_DELETESTRING: Final = 324 +CB_DIR: Final = 325 +CB_GETCOUNT: Final = 326 +CB_GETCURSEL: Final = 327 +CB_GETLBTEXT: Final = 328 +CB_GETLBTEXTLEN: Final = 329 +CB_INSERTSTRING: Final = 330 +CB_RESETCONTENT: Final = 331 +CB_FINDSTRING: Final = 332 +CB_SELECTSTRING: Final = 333 +CB_SETCURSEL: Final = 334 +CB_SHOWDROPDOWN: Final = 335 +CB_GETITEMDATA: Final = 336 +CB_SETITEMDATA: Final = 337 +CB_GETDROPPEDCONTROLRECT: Final = 338 +CB_SETITEMHEIGHT: Final = 339 +CB_GETITEMHEIGHT: Final = 340 +CB_SETEXTENDEDUI: Final = 341 +CB_GETEXTENDEDUI: Final = 342 +CB_GETDROPPEDSTATE: Final = 343 +CB_FINDSTRINGEXACT: Final = 344 +CB_SETLOCALE: Final = 345 +CB_GETLOCALE: Final = 346 +CB_GETTOPINDEX: Final = 347 +CB_SETTOPINDEX: Final = 348 +CB_GETHORIZONTALEXTENT: Final = 349 +CB_SETHORIZONTALEXTENT: Final = 350 +CB_GETDROPPEDWIDTH: Final = 351 +CB_SETDROPPEDWIDTH: Final = 352 +CB_INITSTORAGE: Final = 353 +CB_MSGMAX: Final = 354 +SBS_HORZ: Final = 0 +SBS_VERT: Final = 1 +SBS_TOPALIGN: Final = 2 +SBS_LEFTALIGN: Final = 2 +SBS_BOTTOMALIGN: Final = 4 +SBS_RIGHTALIGN: Final = 4 +SBS_SIZEBOXTOPLEFTALIGN: Final = 2 +SBS_SIZEBOXBOTTOMRIGHTALIGN: Final = 4 +SBS_SIZEBOX: Final = 8 +SBS_SIZEGRIP: Final = 16 +SBM_SETPOS: Final = 224 +SBM_GETPOS: Final = 225 +SBM_SETRANGE: Final = 226 +SBM_SETRANGEREDRAW: Final = 230 +SBM_GETRANGE: Final = 227 +SBM_ENABLE_ARROWS: Final = 228 +SBM_SETSCROLLINFO: Final = 233 +SBM_GETSCROLLINFO: Final = 234 +SIF_RANGE: Final = 1 +SIF_PAGE: Final = 2 +SIF_POS: Final = 4 +SIF_DISABLENOSCROLL: Final = 8 +SIF_TRACKPOS: Final = 16 +SIF_ALL: Final[int] +MDIS_ALLCHILDSTYLES: Final = 1 +MDITILE_VERTICAL: Final = 0 +MDITILE_HORIZONTAL: Final = 1 +MDITILE_SKIPDISABLED: Final = 2 +MDITILE_ZORDER: Final = 4 + +IMC_GETCANDIDATEPOS: Final = 7 +IMC_SETCANDIDATEPOS: Final = 8 +IMC_GETCOMPOSITIONFONT: Final = 9 +IMC_SETCOMPOSITIONFONT: Final = 10 +IMC_GETCOMPOSITIONWINDOW: Final = 11 +IMC_SETCOMPOSITIONWINDOW: Final = 12 +IMC_GETSTATUSWINDOWPOS: Final = 15 +IMC_SETSTATUSWINDOWPOS: Final = 16 +IMC_CLOSESTATUSWINDOW: Final = 33 +IMC_OPENSTATUSWINDOW: Final = 34 + +DELETE: Final = 65536 +READ_CONTROL: Final = 131072 +WRITE_DAC: Final = 262144 +WRITE_OWNER: Final = 524288 +SYNCHRONIZE: Final = 1048576 +STANDARD_RIGHTS_REQUIRED: Final = 983040 +STANDARD_RIGHTS_READ: Final = READ_CONTROL +STANDARD_RIGHTS_WRITE: Final = READ_CONTROL +STANDARD_RIGHTS_EXECUTE: Final = READ_CONTROL +STANDARD_RIGHTS_ALL: Final = 2031616 +SPECIFIC_RIGHTS_ALL: Final = 65535 +ACCESS_SYSTEM_SECURITY: Final = 16777216 +MAXIMUM_ALLOWED: Final = 33554432 +GENERIC_READ: Final = -2147483648 +GENERIC_WRITE: Final = 1073741824 +GENERIC_EXECUTE: Final = 536870912 +GENERIC_ALL: Final = 268435456 + +SERVICE_KERNEL_DRIVER: Final = 1 +SERVICE_FILE_SYSTEM_DRIVER: Final = 2 +SERVICE_ADAPTER: Final = 4 +SERVICE_RECOGNIZER_DRIVER: Final = 8 +SERVICE_DRIVER: Final[int] +SERVICE_WIN32_OWN_PROCESS: Final = 16 +SERVICE_WIN32_SHARE_PROCESS: Final = 32 +SERVICE_WIN32: Final[int] +SERVICE_INTERACTIVE_PROCESS: Final = 256 +SERVICE_TYPE_ALL: Final[int] +SERVICE_BOOT_START: Final = 0 +SERVICE_SYSTEM_START: Final = 1 +SERVICE_AUTO_START: Final = 2 +SERVICE_DEMAND_START: Final = 3 +SERVICE_DISABLED: Final = 4 +SERVICE_ERROR_IGNORE: Final = 0 +SERVICE_ERROR_NORMAL: Final = 1 +SERVICE_ERROR_SEVERE: Final = 2 +SERVICE_ERROR_CRITICAL: Final = 3 +TAPE_ERASE_SHORT: Final = 0 +TAPE_ERASE_LONG: Final = 1 +TAPE_LOAD: Final = 0 +TAPE_UNLOAD: Final = 1 +TAPE_TENSION: Final = 2 +TAPE_LOCK: Final = 3 +TAPE_UNLOCK: Final = 4 +TAPE_FORMAT: Final = 5 +TAPE_SETMARKS: Final = 0 +TAPE_FILEMARKS: Final = 1 +TAPE_SHORT_FILEMARKS: Final = 2 +TAPE_LONG_FILEMARKS: Final = 3 +TAPE_ABSOLUTE_POSITION: Final = 0 +TAPE_LOGICAL_POSITION: Final = 1 +TAPE_PSEUDO_LOGICAL_POSITION: Final = 2 +TAPE_REWIND: Final = 0 +TAPE_ABSOLUTE_BLOCK: Final = 1 +TAPE_LOGICAL_BLOCK: Final = 2 +TAPE_PSEUDO_LOGICAL_BLOCK: Final = 3 +TAPE_SPACE_END_OF_DATA: Final = 4 +TAPE_SPACE_RELATIVE_BLOCKS: Final = 5 +TAPE_SPACE_FILEMARKS: Final = 6 +TAPE_SPACE_SEQUENTIAL_FMKS: Final = 7 +TAPE_SPACE_SETMARKS: Final = 8 +TAPE_SPACE_SEQUENTIAL_SMKS: Final = 9 +TAPE_DRIVE_FIXED: Final = 1 +TAPE_DRIVE_SELECT: Final = 2 +TAPE_DRIVE_INITIATOR: Final = 4 +TAPE_DRIVE_ERASE_SHORT: Final = 16 +TAPE_DRIVE_ERASE_LONG: Final = 32 +TAPE_DRIVE_ERASE_BOP_ONLY: Final = 64 +TAPE_DRIVE_ERASE_IMMEDIATE: Final = 128 +TAPE_DRIVE_TAPE_CAPACITY: Final = 256 +TAPE_DRIVE_TAPE_REMAINING: Final = 512 +TAPE_DRIVE_FIXED_BLOCK: Final = 1024 +TAPE_DRIVE_VARIABLE_BLOCK: Final = 2048 +TAPE_DRIVE_WRITE_PROTECT: Final = 4096 +TAPE_DRIVE_EOT_WZ_SIZE: Final = 8192 +TAPE_DRIVE_ECC: Final = 65536 +TAPE_DRIVE_COMPRESSION: Final = 131072 +TAPE_DRIVE_PADDING: Final = 262144 +TAPE_DRIVE_REPORT_SMKS: Final = 524288 +TAPE_DRIVE_GET_ABSOLUTE_BLK: Final = 1048576 +TAPE_DRIVE_GET_LOGICAL_BLK: Final = 2097152 +TAPE_DRIVE_SET_EOT_WZ_SIZE: Final = 4194304 +TAPE_DRIVE_LOAD_UNLOAD: Final = -2147483647 +TAPE_DRIVE_TENSION: Final = -2147483646 +TAPE_DRIVE_LOCK_UNLOCK: Final = -2147483644 +TAPE_DRIVE_REWIND_IMMEDIATE: Final = -2147483640 +TAPE_DRIVE_SET_BLOCK_SIZE: Final = -2147483632 +TAPE_DRIVE_LOAD_UNLD_IMMED: Final = -2147483616 +TAPE_DRIVE_TENSION_IMMED: Final = -2147483584 +TAPE_DRIVE_LOCK_UNLK_IMMED: Final = -2147483520 +TAPE_DRIVE_SET_ECC: Final = -2147483392 +TAPE_DRIVE_SET_COMPRESSION: Final = -2147483136 +TAPE_DRIVE_SET_PADDING: Final = -2147482624 +TAPE_DRIVE_SET_REPORT_SMKS: Final = -2147481600 +TAPE_DRIVE_ABSOLUTE_BLK: Final = -2147479552 +TAPE_DRIVE_ABS_BLK_IMMED: Final = -2147475456 +TAPE_DRIVE_LOGICAL_BLK: Final = -2147467264 +TAPE_DRIVE_LOG_BLK_IMMED: Final = -2147450880 +TAPE_DRIVE_END_OF_DATA: Final = -2147418112 +TAPE_DRIVE_RELATIVE_BLKS: Final = -2147352576 +TAPE_DRIVE_FILEMARKS: Final = -2147221504 +TAPE_DRIVE_SEQUENTIAL_FMKS: Final = -2146959360 +TAPE_DRIVE_SETMARKS: Final = -2146435072 +TAPE_DRIVE_SEQUENTIAL_SMKS: Final = -2145386496 +TAPE_DRIVE_REVERSE_POSITION: Final = -2143289344 +TAPE_DRIVE_SPACE_IMMEDIATE: Final = -2139095040 +TAPE_DRIVE_WRITE_SETMARKS: Final = -2130706432 +TAPE_DRIVE_WRITE_FILEMARKS: Final = -2113929216 +TAPE_DRIVE_WRITE_SHORT_FMKS: Final = -2080374784 +TAPE_DRIVE_WRITE_LONG_FMKS: Final = -2013265920 +TAPE_DRIVE_WRITE_MARK_IMMED: Final = -1879048192 +TAPE_DRIVE_FORMAT: Final = -1610612736 +TAPE_DRIVE_FORMAT_IMMEDIATE: Final = -1073741824 +TAPE_FIXED_PARTITIONS: Final = 0 +TAPE_SELECT_PARTITIONS: Final = 1 +TAPE_INITIATOR_PARTITIONS: Final = 2 + +APPLICATION_ERROR_MASK: Final = 536870912 +ERROR_SEVERITY_SUCCESS: Final = 0 +ERROR_SEVERITY_INFORMATIONAL: Final = 1073741824 +ERROR_SEVERITY_WARNING: Final = -2147483648 +ERROR_SEVERITY_ERROR: Final = -1073741824 +MINCHAR: Final = 128 +MAXCHAR: Final = 127 +MINSHORT: Final = 32768 +MAXSHORT: Final = 32767 +MINLONG: Final = -2147483648 +MAXLONG: Final = 2147483647 +MAXBYTE: Final = 255 +MAXWORD: Final = 65535 +MAXDWORD: Final = -1 +LANG_NEUTRAL: Final = 0 +LANG_BULGARIAN: Final = 2 +LANG_CHINESE: Final = 4 +LANG_CROATIAN: Final = 26 +LANG_CZECH: Final = 5 +LANG_DANISH: Final = 6 +LANG_DUTCH: Final = 19 +LANG_ENGLISH: Final = 9 +LANG_FINNISH: Final = 11 +LANG_FRENCH: Final = 12 +LANG_GERMAN: Final = 7 +LANG_GREEK: Final = 8 +LANG_HUNGARIAN: Final = 14 +LANG_ICELANDIC: Final = 15 +LANG_ITALIAN: Final = 16 +LANG_JAPANESE: Final = 17 +LANG_KOREAN: Final = 18 +LANG_NORWEGIAN: Final = 20 +LANG_POLISH: Final = 21 +LANG_PORTUGUESE: Final = 22 +LANG_ROMANIAN: Final = 24 +LANG_RUSSIAN: Final = 25 +LANG_SLOVAK: Final = 27 +LANG_SLOVENIAN: Final = 36 +LANG_SPANISH: Final = 10 +LANG_SWEDISH: Final = 29 +LANG_TURKISH: Final = 31 +SUBLANG_NEUTRAL: Final = 0 +SUBLANG_DEFAULT: Final = 1 +SUBLANG_SYS_DEFAULT: Final = 2 +SUBLANG_CHINESE_TRADITIONAL: Final = 1 +SUBLANG_CHINESE_SIMPLIFIED: Final = 2 +SUBLANG_CHINESE_HONGKONG: Final = 3 +SUBLANG_CHINESE_SINGAPORE: Final = 4 +SUBLANG_DUTCH: Final = 1 +SUBLANG_DUTCH_BELGIAN: Final = 2 +SUBLANG_ENGLISH_US: Final = 1 +SUBLANG_ENGLISH_UK: Final = 2 +SUBLANG_ENGLISH_AUS: Final = 3 +SUBLANG_ENGLISH_CAN: Final = 4 +SUBLANG_ENGLISH_NZ: Final = 5 +SUBLANG_ENGLISH_EIRE: Final = 6 +SUBLANG_FRENCH: Final = 1 +SUBLANG_FRENCH_BELGIAN: Final = 2 +SUBLANG_FRENCH_CANADIAN: Final = 3 +SUBLANG_FRENCH_SWISS: Final = 4 +SUBLANG_GERMAN: Final = 1 +SUBLANG_GERMAN_SWISS: Final = 2 +SUBLANG_GERMAN_AUSTRIAN: Final = 3 +SUBLANG_ITALIAN: Final = 1 +SUBLANG_ITALIAN_SWISS: Final = 2 +SUBLANG_NORWEGIAN_BOKMAL: Final = 1 +SUBLANG_NORWEGIAN_NYNORSK: Final = 2 +SUBLANG_PORTUGUESE: Final = 2 +SUBLANG_PORTUGUESE_BRAZILIAN: Final = 1 +SUBLANG_SPANISH: Final = 1 +SUBLANG_SPANISH_MEXICAN: Final = 2 +SUBLANG_SPANISH_MODERN: Final = 3 +SORT_DEFAULT: Final = 0 +SORT_JAPANESE_XJIS: Final = 0 +SORT_JAPANESE_UNICODE: Final = 1 +SORT_CHINESE_BIG5: Final = 0 +SORT_CHINESE_UNICODE: Final = 1 +SORT_KOREAN_KSC: Final = 0 +SORT_KOREAN_UNICODE: Final = 1 + +def PRIMARYLANGID(lgid: int) -> int: ... +def SUBLANGID(lgid: int) -> int: ... + +NLS_VALID_LOCALE_MASK: Final = 1048575 +CONTEXT_PORTABLE_32BIT: Final = 1048576 +CONTEXT_ALPHA: Final = 131072 +SIZE_OF_80387_REGISTERS: Final = 80 +CONTEXT_CONTROL: Final = 1 +CONTEXT_FLOATING_POINT: Final = 2 +CONTEXT_INTEGER: Final = 4 +CONTEXT_FULL: Final[int] +PROCESS_TERMINATE: Final = 1 +PROCESS_CREATE_THREAD: Final = 2 +PROCESS_VM_OPERATION: Final = 8 +PROCESS_VM_READ: Final = 16 +PROCESS_VM_WRITE: Final = 32 +PROCESS_DUP_HANDLE: Final = 64 +PROCESS_CREATE_PROCESS: Final = 128 +PROCESS_SET_QUOTA: Final = 256 +PROCESS_SET_INFORMATION: Final = 512 +PROCESS_QUERY_INFORMATION: Final = 1024 +PROCESS_SUSPEND_RESUME: Final = 2048 +PROCESS_QUERY_LIMITED_INFORMATION: Final = 4096 +PROCESS_SET_LIMITED_INFORMATION: Final = 8192 +PROCESS_ALL_ACCESS: Final[int] +THREAD_TERMINATE: Final = 1 +THREAD_SUSPEND_RESUME: Final = 2 +THREAD_GET_CONTEXT: Final = 8 +THREAD_SET_CONTEXT: Final = 16 +THREAD_SET_INFORMATION: Final = 32 +THREAD_QUERY_INFORMATION: Final = 64 +THREAD_SET_THREAD_TOKEN: Final = 128 +THREAD_IMPERSONATE: Final = 256 +THREAD_DIRECT_IMPERSONATION: Final = 512 +THREAD_SET_LIMITED_INFORMATION: Final = 1024 +THREAD_QUERY_LIMITED_INFORMATION: Final = 2048 +THREAD_RESUME: Final = 4096 +TLS_MINIMUM_AVAILABLE: Final = 64 +EVENT_MODIFY_STATE: Final = 2 +MUTANT_QUERY_STATE: Final = 1 +SEMAPHORE_MODIFY_STATE: Final = 2 +TIME_ZONE_ID_UNKNOWN: Final = 0 +TIME_ZONE_ID_STANDARD: Final = 1 +TIME_ZONE_ID_DAYLIGHT: Final = 2 +PROCESSOR_INTEL_386: Final = 386 +PROCESSOR_INTEL_486: Final = 486 +PROCESSOR_INTEL_PENTIUM: Final = 586 +PROCESSOR_INTEL_860: Final = 860 +PROCESSOR_MIPS_R2000: Final = 2000 +PROCESSOR_MIPS_R3000: Final = 3000 +PROCESSOR_MIPS_R4000: Final = 4000 +PROCESSOR_ALPHA_21064: Final = 21064 +PROCESSOR_PPC_601: Final = 601 +PROCESSOR_PPC_603: Final = 603 +PROCESSOR_PPC_604: Final = 604 +PROCESSOR_PPC_620: Final = 620 +SECTION_QUERY: Final = 1 +SECTION_MAP_WRITE: Final = 2 +SECTION_MAP_READ: Final = 4 +SECTION_MAP_EXECUTE: Final = 8 +SECTION_EXTEND_SIZE: Final = 16 +PAGE_NOACCESS: Final = 1 +PAGE_READONLY: Final = 2 +PAGE_READWRITE: Final = 4 +PAGE_WRITECOPY: Final = 8 +PAGE_EXECUTE: Final = 16 +PAGE_EXECUTE_READ: Final = 32 +PAGE_EXECUTE_READWRITE: Final = 64 +PAGE_EXECUTE_WRITECOPY: Final = 128 +PAGE_GUARD: Final = 256 +PAGE_NOCACHE: Final = 512 +MEM_COMMIT: Final = 4096 +MEM_RESERVE: Final = 8192 +MEM_DECOMMIT: Final = 16384 +MEM_RELEASE: Final = 32768 +MEM_FREE: Final = 65536 +MEM_PRIVATE: Final = 131072 +MEM_MAPPED: Final = 262144 +MEM_TOP_DOWN: Final = 1048576 + +SEC_FILE: Final = 8388608 +SEC_IMAGE: Final = 16777216 +SEC_RESERVE: Final = 67108864 +SEC_COMMIT: Final = 134217728 +SEC_NOCACHE: Final = 268435456 +MEM_IMAGE: Final = SEC_IMAGE +FILE_SHARE_READ: Final = 1 +FILE_SHARE_WRITE: Final = 2 +FILE_SHARE_DELETE: Final = 4 +FILE_ATTRIBUTE_READONLY: Final = 1 +FILE_ATTRIBUTE_HIDDEN: Final = 2 +FILE_ATTRIBUTE_SYSTEM: Final = 4 +FILE_ATTRIBUTE_DIRECTORY: Final = 16 +FILE_ATTRIBUTE_ARCHIVE: Final = 32 +FILE_ATTRIBUTE_DEVICE: Final = 64 +FILE_ATTRIBUTE_NORMAL: Final = 128 +FILE_ATTRIBUTE_TEMPORARY: Final = 256 +FILE_ATTRIBUTE_SPARSE_FILE: Final = 512 +FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024 +FILE_ATTRIBUTE_COMPRESSED: Final = 2048 +FILE_ATTRIBUTE_OFFLINE: Final = 4096 +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192 +FILE_ATTRIBUTE_ENCRYPTED: Final = 16384 +FILE_ATTRIBUTE_VIRTUAL: Final = 65536 + +FILE_NOTIFY_CHANGE_FILE_NAME: Final = 1 +FILE_NOTIFY_CHANGE_DIR_NAME: Final = 2 +FILE_NOTIFY_CHANGE_ATTRIBUTES: Final = 4 +FILE_NOTIFY_CHANGE_SIZE: Final = 8 +FILE_NOTIFY_CHANGE_LAST_WRITE: Final = 16 +FILE_NOTIFY_CHANGE_SECURITY: Final = 256 +FILE_CASE_SENSITIVE_SEARCH: Final = 1 +FILE_CASE_PRESERVED_NAMES: Final = 2 +FILE_FILE_COMPRESSION: Final = 16 +FILE_NAMED_STREAMS: Final = 262144 +FILE_PERSISTENT_ACLS: Final = 0x00000008 +FILE_READ_ONLY_VOLUME: Final = 0x00080000 +FILE_SEQUENTIAL_WRITE_ONCE: Final = 0x00100000 +FILE_SUPPORTS_ENCRYPTION: Final = 0x00020000 +FILE_SUPPORTS_EXTENDED_ATTRIBUTES: Final = 0x00800000 +FILE_SUPPORTS_HARD_LINKS: Final = 0x00400000 +FILE_SUPPORTS_OBJECT_IDS: Final = 0x00010000 +FILE_SUPPORTS_OPEN_BY_FILE_ID: Final = 0x01000000 +FILE_SUPPORTS_REPARSE_POINTS: Final = 0x00000080 +FILE_SUPPORTS_SPARSE_FILES: Final = 0x00000040 +FILE_SUPPORTS_TRANSACTIONS: Final = 0x00200000 +FILE_SUPPORTS_USN_JOURNAL: Final = 0x02000000 +FILE_UNICODE_ON_DISK: Final = 0x00000004 +FILE_VOLUME_QUOTAS: Final = 0x00000020 +FILE_VOLUME_IS_COMPRESSED: Final = 32768 +IO_COMPLETION_MODIFY_STATE: Final = 2 +DUPLICATE_CLOSE_SOURCE: Final = 1 +DUPLICATE_SAME_ACCESS: Final = 2 +SID_MAX_SUB_AUTHORITIES: Final = 15 +SECURITY_NULL_RID: Final = 0 +SECURITY_WORLD_RID: Final = 0 +SECURITY_LOCAL_RID: Final = 0x00000000 +SECURITY_CREATOR_OWNER_RID: Final = 0 +SECURITY_CREATOR_GROUP_RID: Final = 1 +SECURITY_DIALUP_RID: Final = 1 +SECURITY_NETWORK_RID: Final = 2 +SECURITY_BATCH_RID: Final = 3 +SECURITY_INTERACTIVE_RID: Final = 4 +SECURITY_SERVICE_RID: Final = 6 +SECURITY_ANONYMOUS_LOGON_RID: Final = 7 +SECURITY_LOGON_IDS_RID: Final = 5 +SECURITY_LOGON_IDS_RID_COUNT: Final = 3 +SECURITY_LOCAL_SYSTEM_RID: Final = 18 +SECURITY_NT_NON_UNIQUE: Final = 21 +SECURITY_BUILTIN_DOMAIN_RID: Final = 32 +DOMAIN_USER_RID_ADMIN: Final = 500 +DOMAIN_USER_RID_GUEST: Final = 501 +DOMAIN_GROUP_RID_ADMINS: Final = 512 +DOMAIN_GROUP_RID_USERS: Final = 513 +DOMAIN_GROUP_RID_GUESTS: Final = 514 +DOMAIN_ALIAS_RID_ADMINS: Final = 544 +DOMAIN_ALIAS_RID_USERS: Final = 545 +DOMAIN_ALIAS_RID_GUESTS: Final = 546 +DOMAIN_ALIAS_RID_POWER_USERS: Final = 547 +DOMAIN_ALIAS_RID_ACCOUNT_OPS: Final = 548 +DOMAIN_ALIAS_RID_SYSTEM_OPS: Final = 549 +DOMAIN_ALIAS_RID_PRINT_OPS: Final = 550 +DOMAIN_ALIAS_RID_BACKUP_OPS: Final = 551 +DOMAIN_ALIAS_RID_REPLICATOR: Final = 552 +SE_GROUP_MANDATORY: Final = 1 +SE_GROUP_ENABLED_BY_DEFAULT: Final = 2 +SE_GROUP_ENABLED: Final = 4 +SE_GROUP_OWNER: Final = 8 +SE_GROUP_LOGON_ID: Final = -1073741824 +ACL_REVISION: Final = 2 +ACL_REVISION1: Final = 1 +ACL_REVISION2: Final = 2 +ACCESS_ALLOWED_ACE_TYPE: Final = 0 +ACCESS_DENIED_ACE_TYPE: Final = 1 +SYSTEM_AUDIT_ACE_TYPE: Final = 2 +SYSTEM_ALARM_ACE_TYPE: Final = 3 +OBJECT_INHERIT_ACE: Final = 1 +CONTAINER_INHERIT_ACE: Final = 2 +NO_PROPAGATE_INHERIT_ACE: Final = 4 +INHERIT_ONLY_ACE: Final = 8 +VALID_INHERIT_FLAGS: Final = 15 +SUCCESSFUL_ACCESS_ACE_FLAG: Final = 64 +FAILED_ACCESS_ACE_FLAG: Final = 128 +SECURITY_DESCRIPTOR_REVISION: Final = 1 +SECURITY_DESCRIPTOR_REVISION1: Final = 1 +SECURITY_DESCRIPTOR_MIN_LENGTH: Final = 20 +SE_OWNER_DEFAULTED: Final = 1 +SE_GROUP_DEFAULTED: Final = 2 +SE_DACL_PRESENT: Final = 4 +SE_DACL_DEFAULTED: Final = 8 +SE_SACL_PRESENT: Final = 16 +SE_SACL_DEFAULTED: Final = 32 +SE_SELF_RELATIVE: Final = 32768 +SE_PRIVILEGE_ENABLED_BY_DEFAULT: Final = 1 +SE_PRIVILEGE_ENABLED: Final = 2 +SE_PRIVILEGE_USED_FOR_ACCESS: Final = -2147483648 +PRIVILEGE_SET_ALL_NECESSARY: Final = 1 +SE_CREATE_TOKEN_NAME: Final = "SeCreateTokenPrivilege" +SE_ASSIGNPRIMARYTOKEN_NAME: Final = "SeAssignPrimaryTokenPrivilege" +SE_LOCK_MEMORY_NAME: Final = "SeLockMemoryPrivilege" +SE_INCREASE_QUOTA_NAME: Final = "SeIncreaseQuotaPrivilege" +SE_UNSOLICITED_INPUT_NAME: Final = "SeUnsolicitedInputPrivilege" +SE_MACHINE_ACCOUNT_NAME: Final = "SeMachineAccountPrivilege" +SE_TCB_NAME: Final = "SeTcbPrivilege" +SE_SECURITY_NAME: Final = "SeSecurityPrivilege" +SE_TAKE_OWNERSHIP_NAME: Final = "SeTakeOwnershipPrivilege" +SE_LOAD_DRIVER_NAME: Final = "SeLoadDriverPrivilege" +SE_SYSTEM_PROFILE_NAME: Final = "SeSystemProfilePrivilege" +SE_SYSTEMTIME_NAME: Final = "SeSystemtimePrivilege" +SE_PROF_SINGLE_PROCESS_NAME: Final = "SeProfileSingleProcessPrivilege" +SE_INC_BASE_PRIORITY_NAME: Final = "SeIncreaseBasePriorityPrivilege" +SE_CREATE_PAGEFILE_NAME: Final = "SeCreatePagefilePrivilege" +SE_CREATE_PERMANENT_NAME: Final = "SeCreatePermanentPrivilege" +SE_BACKUP_NAME: Final = "SeBackupPrivilege" +SE_RESTORE_NAME: Final = "SeRestorePrivilege" +SE_SHUTDOWN_NAME: Final = "SeShutdownPrivilege" +SE_DEBUG_NAME: Final = "SeDebugPrivilege" +SE_AUDIT_NAME: Final = "SeAuditPrivilege" +SE_SYSTEM_ENVIRONMENT_NAME: Final = "SeSystemEnvironmentPrivilege" +SE_CHANGE_NOTIFY_NAME: Final = "SeChangeNotifyPrivilege" +SE_REMOTE_SHUTDOWN_NAME: Final = "SeRemoteShutdownPrivilege" + +TOKEN_ASSIGN_PRIMARY: Final = 1 +TOKEN_DUPLICATE: Final = 2 +TOKEN_IMPERSONATE: Final = 4 +TOKEN_QUERY: Final = 8 +TOKEN_QUERY_SOURCE: Final = 16 +TOKEN_ADJUST_PRIVILEGES: Final = 32 +TOKEN_ADJUST_GROUPS: Final = 64 +TOKEN_ADJUST_DEFAULT: Final = 128 +TOKEN_ADJUST_SESSIONID: Final = 256 +TOKEN_ALL_ACCESS: Final[int] +TOKEN_READ: Final[int] +TOKEN_WRITE: Final[int] +TOKEN_EXECUTE: Final = STANDARD_RIGHTS_EXECUTE +TOKEN_SOURCE_LENGTH: Final = 8 + +KEY_QUERY_VALUE: Final = 1 +KEY_SET_VALUE: Final = 2 +KEY_CREATE_SUB_KEY: Final = 4 +KEY_ENUMERATE_SUB_KEYS: Final = 8 +KEY_NOTIFY: Final = 16 +KEY_CREATE_LINK: Final = 32 +KEY_WOW64_32KEY: Final = 512 +KEY_WOW64_64KEY: Final = 256 +KEY_WOW64_RES: Final = 768 +KEY_READ: Final[int] +KEY_WRITE: Final[int] +KEY_EXECUTE: Final[int] +KEY_ALL_ACCESS: Final[int] +REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2 +REG_NOTIFY_CHANGE_SECURITY: Final = 8 +REG_NONE: Final = 0 +REG_SZ: Final = 1 +REG_EXPAND_SZ: Final = 2 + +REG_BINARY: Final = 3 +REG_DWORD: Final = 4 +REG_DWORD_LITTLE_ENDIAN: Final = 4 +REG_DWORD_BIG_ENDIAN: Final = 5 +REG_LINK: Final = 6 +REG_MULTI_SZ: Final = 7 +REG_RESOURCE_LIST: Final = 8 +REG_FULL_RESOURCE_DESCRIPTOR: Final = 9 +REG_RESOURCE_REQUIREMENTS_LIST: Final = 10 +REG_QWORD: Final = 11 +REG_QWORD_LITTLE_ENDIAN: Final = 11 + +_NLSCMPERROR: Final = 2147483647 +NULL: Final = 0 +HEAP_NO_SERIALIZE: Final = 1 +HEAP_GROWABLE: Final = 2 +HEAP_GENERATE_EXCEPTIONS: Final = 4 +HEAP_ZERO_MEMORY: Final = 8 +HEAP_REALLOC_IN_PLACE_ONLY: Final = 16 +HEAP_TAIL_CHECKING_ENABLED: Final = 32 +HEAP_FREE_CHECKING_ENABLED: Final = 64 +HEAP_DISABLE_COALESCE_ON_FREE: Final = 128 +IS_TEXT_UNICODE_ASCII16: Final = 1 +IS_TEXT_UNICODE_REVERSE_ASCII16: Final = 16 +IS_TEXT_UNICODE_STATISTICS: Final = 2 +IS_TEXT_UNICODE_REVERSE_STATISTICS: Final = 32 +IS_TEXT_UNICODE_CONTROLS: Final = 4 +IS_TEXT_UNICODE_REVERSE_CONTROLS: Final = 64 +IS_TEXT_UNICODE_SIGNATURE: Final = 8 +IS_TEXT_UNICODE_REVERSE_SIGNATURE: Final = 128 +IS_TEXT_UNICODE_ILLEGAL_CHARS: Final = 256 +IS_TEXT_UNICODE_ODD_LENGTH: Final = 512 +IS_TEXT_UNICODE_DBCS_LEADBYTE: Final = 1024 +IS_TEXT_UNICODE_NULL_BYTES: Final = 4096 +IS_TEXT_UNICODE_UNICODE_MASK: Final = 15 +IS_TEXT_UNICODE_REVERSE_MASK: Final = 240 +IS_TEXT_UNICODE_NOT_UNICODE_MASK: Final = 3840 +IS_TEXT_UNICODE_NOT_ASCII_MASK: Final = 61440 +COMPRESSION_FORMAT_NONE: Final = 0 +COMPRESSION_FORMAT_DEFAULT: Final = 1 +COMPRESSION_FORMAT_LZNT1: Final = 2 +COMPRESSION_ENGINE_STANDARD: Final = 0 +COMPRESSION_ENGINE_MAXIMUM: Final = 256 +MESSAGE_RESOURCE_UNICODE: Final = 1 +RTL_CRITSECT_TYPE: Final = 0 +RTL_RESOURCE_TYPE: Final = 1 +DLL_PROCESS_ATTACH: Final = 1 +DLL_THREAD_ATTACH: Final = 2 +DLL_THREAD_DETACH: Final = 3 +DLL_PROCESS_DETACH: Final = 0 +EVENTLOG_SEQUENTIAL_READ: Final = 0x0001 +EVENTLOG_SEEK_READ: Final = 0x0002 +EVENTLOG_FORWARDS_READ: Final = 0x0004 +EVENTLOG_BACKWARDS_READ: Final = 0x0008 +EVENTLOG_SUCCESS: Final = 0x0000 +EVENTLOG_ERROR_TYPE: Final = 1 +EVENTLOG_WARNING_TYPE: Final = 2 +EVENTLOG_INFORMATION_TYPE: Final = 4 +EVENTLOG_AUDIT_SUCCESS: Final = 8 +EVENTLOG_AUDIT_FAILURE: Final = 16 +EVENTLOG_START_PAIRED_EVENT: Final = 1 +EVENTLOG_END_PAIRED_EVENT: Final = 2 +EVENTLOG_END_ALL_PAIRED_EVENTS: Final = 4 +EVENTLOG_PAIRED_EVENT_ACTIVE: Final = 8 +EVENTLOG_PAIRED_EVENT_INACTIVE: Final = 16 + +OWNER_SECURITY_INFORMATION: Final = 0x00000001 +GROUP_SECURITY_INFORMATION: Final = 0x00000002 +DACL_SECURITY_INFORMATION: Final = 0x00000004 +SACL_SECURITY_INFORMATION: Final = 0x00000008 +IMAGE_SIZEOF_FILE_HEADER: Final = 20 +IMAGE_FILE_MACHINE_UNKNOWN: Final = 0 +IMAGE_NUMBEROF_DIRECTORY_ENTRIES: Final = 16 +IMAGE_SIZEOF_ROM_OPTIONAL_HEADER: Final = 56 +IMAGE_SIZEOF_STD_OPTIONAL_HEADER: Final = 28 +IMAGE_SIZEOF_NT_OPTIONAL_HEADER: Final = 224 +IMAGE_NT_OPTIONAL_HDR_MAGIC: Final = 267 +IMAGE_ROM_OPTIONAL_HDR_MAGIC: Final = 263 +IMAGE_SIZEOF_SHORT_NAME: Final = 8 +IMAGE_SIZEOF_SECTION_HEADER: Final = 40 +IMAGE_SIZEOF_SYMBOL: Final = 18 +IMAGE_SYM_CLASS_NULL: Final = 0 +IMAGE_SYM_CLASS_AUTOMATIC: Final = 1 +IMAGE_SYM_CLASS_EXTERNAL: Final = 2 +IMAGE_SYM_CLASS_STATIC: Final = 3 +IMAGE_SYM_CLASS_REGISTER: Final = 4 +IMAGE_SYM_CLASS_EXTERNAL_DEF: Final = 5 +IMAGE_SYM_CLASS_LABEL: Final = 6 +IMAGE_SYM_CLASS_UNDEFINED_LABEL: Final = 7 +IMAGE_SYM_CLASS_MEMBER_OF_STRUCT: Final = 8 +IMAGE_SYM_CLASS_ARGUMENT: Final = 9 +IMAGE_SYM_CLASS_STRUCT_TAG: Final = 10 +IMAGE_SYM_CLASS_MEMBER_OF_UNION: Final = 11 +IMAGE_SYM_CLASS_UNION_TAG: Final = 12 +IMAGE_SYM_CLASS_TYPE_DEFINITION: Final = 13 +IMAGE_SYM_CLASS_UNDEFINED_STATIC: Final = 14 +IMAGE_SYM_CLASS_ENUM_TAG: Final = 15 +IMAGE_SYM_CLASS_MEMBER_OF_ENUM: Final = 16 +IMAGE_SYM_CLASS_REGISTER_PARAM: Final = 17 +IMAGE_SYM_CLASS_BIT_FIELD: Final = 18 +IMAGE_SYM_CLASS_BLOCK: Final = 100 +IMAGE_SYM_CLASS_FUNCTION: Final = 101 +IMAGE_SYM_CLASS_END_OF_STRUCT: Final = 102 +IMAGE_SYM_CLASS_FILE: Final = 103 +IMAGE_SYM_CLASS_SECTION: Final = 104 +IMAGE_SYM_CLASS_WEAK_EXTERNAL: Final = 105 +N_BTMASK: Final = 15 +N_TMASK: Final = 48 +N_TMASK1: Final = 192 +N_TMASK2: Final = 240 +N_BTSHFT: Final = 4 +N_TSHIFT: Final = 2 +IMAGE_SIZEOF_AUX_SYMBOL: Final = 18 +IMAGE_COMDAT_SELECT_NODUPLICATES: Final = 1 +IMAGE_COMDAT_SELECT_ANY: Final = 2 +IMAGE_COMDAT_SELECT_SAME_SIZE: Final = 3 +IMAGE_COMDAT_SELECT_EXACT_MATCH: Final = 4 +IMAGE_COMDAT_SELECT_ASSOCIATIVE: Final = 5 +IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY: Final = 1 +IMAGE_WEAK_EXTERN_SEARCH_LIBRARY: Final = 2 +IMAGE_WEAK_EXTERN_SEARCH_ALIAS: Final = 3 +IMAGE_SIZEOF_RELOCATION: Final = 10 +IMAGE_REL_I386_SECTION: Final = 10 +IMAGE_REL_I386_SECREL: Final = 11 +IMAGE_REL_MIPS_REFHALF: Final = 1 +IMAGE_REL_MIPS_REFWORD: Final = 2 +IMAGE_REL_MIPS_JMPADDR: Final = 3 +IMAGE_REL_MIPS_REFHI: Final = 4 +IMAGE_REL_MIPS_REFLO: Final = 5 +IMAGE_REL_MIPS_GPREL: Final = 6 +IMAGE_REL_MIPS_LITERAL: Final = 7 +IMAGE_REL_MIPS_SECTION: Final = 10 +IMAGE_REL_MIPS_SECREL: Final = 11 +IMAGE_REL_MIPS_REFWORDNB: Final = 34 +IMAGE_REL_MIPS_PAIR: Final = 37 +IMAGE_REL_ALPHA_ABSOLUTE: Final = 0 +IMAGE_REL_ALPHA_REFLONG: Final = 1 +IMAGE_REL_ALPHA_REFQUAD: Final = 2 +IMAGE_REL_ALPHA_GPREL32: Final = 3 +IMAGE_REL_ALPHA_LITERAL: Final = 4 +IMAGE_REL_ALPHA_LITUSE: Final = 5 +IMAGE_REL_ALPHA_GPDISP: Final = 6 +IMAGE_REL_ALPHA_BRADDR: Final = 7 +IMAGE_REL_ALPHA_HINT: Final = 8 +IMAGE_REL_ALPHA_INLINE_REFLONG: Final = 9 +IMAGE_REL_ALPHA_REFHI: Final = 10 +IMAGE_REL_ALPHA_REFLO: Final = 11 +IMAGE_REL_ALPHA_PAIR: Final = 12 +IMAGE_REL_ALPHA_MATCH: Final = 13 +IMAGE_REL_ALPHA_SECTION: Final = 14 +IMAGE_REL_ALPHA_SECREL: Final = 15 +IMAGE_REL_ALPHA_REFLONGNB: Final = 16 +IMAGE_SIZEOF_BASE_RELOCATION: Final = 8 +IMAGE_REL_BASED_ABSOLUTE: Final = 0 +IMAGE_REL_BASED_HIGH: Final = 1 +IMAGE_REL_BASED_LOW: Final = 2 +IMAGE_REL_BASED_HIGHLOW: Final = 3 +IMAGE_REL_BASED_HIGHADJ: Final = 4 +IMAGE_REL_BASED_MIPS_JMPADDR: Final = 5 +IMAGE_SIZEOF_LINENUMBER: Final = 6 +IMAGE_ARCHIVE_START_SIZE: Final = 8 +IMAGE_ARCHIVE_START: Final = "!\n" +IMAGE_ARCHIVE_END: Final = "`\n" +IMAGE_ARCHIVE_PAD: Final = "\n" +IMAGE_ARCHIVE_LINKER_MEMBER: Final = "/ " +IMAGE_ARCHIVE_LONGNAMES_MEMBER: Final = "// " +IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR: Final = 60 +IMAGE_ORDINAL_FLAG: Final = -2147483648 + +def IMAGE_SNAP_BY_ORDINAL(Ordinal: int) -> bool: ... +def IMAGE_ORDINAL(Ordinal: int) -> int: ... + +IMAGE_RESOURCE_NAME_IS_STRING: Final = -2147483648 +IMAGE_RESOURCE_DATA_IS_DIRECTORY: Final = -2147483648 +IMAGE_DEBUG_TYPE_UNKNOWN: Final = 0 +IMAGE_DEBUG_TYPE_COFF: Final = 1 +IMAGE_DEBUG_TYPE_CODEVIEW: Final = 2 +IMAGE_DEBUG_TYPE_FPO: Final = 3 +IMAGE_DEBUG_TYPE_MISC: Final = 4 +IMAGE_DEBUG_TYPE_EXCEPTION: Final = 5 +IMAGE_DEBUG_TYPE_FIXUP: Final = 6 +IMAGE_DEBUG_TYPE_OMAP_TO_SRC: Final = 7 +IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: Final = 8 +FRAME_FPO: Final = 0 +FRAME_TRAP: Final = 1 +FRAME_TSS: Final = 2 +SIZEOF_RFPO_DATA: Final = 16 +IMAGE_DEBUG_MISC_EXENAME: Final = 1 +IMAGE_SEPARATE_DEBUG_SIGNATURE: Final = 18756 + +NEWFRAME: Final = 1 +ABORTDOC: Final = 2 +NEXTBAND: Final = 3 +SETCOLORTABLE: Final = 4 +GETCOLORTABLE: Final = 5 +FLUSHOUTPUT: Final = 6 +DRAFTMODE: Final = 7 +QUERYESCSUPPORT: Final = 8 +SETABORTPROC: Final = 9 +STARTDOC: Final = 10 +ENDDOC: Final = 11 +GETPHYSPAGESIZE: Final = 12 +GETPRINTINGOFFSET: Final = 13 +GETSCALINGFACTOR: Final = 14 +MFCOMMENT: Final = 15 +GETPENWIDTH: Final = 16 +SETCOPYCOUNT: Final = 17 +SELECTPAPERSOURCE: Final = 18 +DEVICEDATA: Final = 19 +PASSTHROUGH: Final = 19 +GETTECHNOLGY: Final = 20 +GETTECHNOLOGY: Final = 20 +SETLINECAP: Final = 21 +SETLINEJOIN: Final = 22 +SETMITERLIMIT: Final = 23 +BANDINFO: Final = 24 +DRAWPATTERNRECT: Final = 25 +GETVECTORPENSIZE: Final = 26 +GETVECTORBRUSHSIZE: Final = 27 +ENABLEDUPLEX: Final = 28 +GETSETPAPERBINS: Final = 29 +GETSETPRINTORIENT: Final = 30 +ENUMPAPERBINS: Final = 31 +SETDIBSCALING: Final = 32 +EPSPRINTING: Final = 33 +ENUMPAPERMETRICS: Final = 34 +GETSETPAPERMETRICS: Final = 35 +POSTSCRIPT_DATA: Final = 37 +POSTSCRIPT_IGNORE: Final = 38 +MOUSETRAILS: Final = 39 +GETDEVICEUNITS: Final = 42 +GETEXTENDEDTEXTMETRICS: Final = 256 +GETEXTENTTABLE: Final = 257 +GETPAIRKERNTABLE: Final = 258 +GETTRACKKERNTABLE: Final = 259 +EXTTEXTOUT: Final = 512 +GETFACENAME: Final = 513 +DOWNLOADFACE: Final = 514 +ENABLERELATIVEWIDTHS: Final = 768 +ENABLEPAIRKERNING: Final = 769 +SETKERNTRACK: Final = 770 +SETALLJUSTVALUES: Final = 771 +SETCHARSET: Final = 772 +STRETCHBLT: Final = 2048 +GETSETSCREENPARAMS: Final = 3072 +BEGIN_PATH: Final = 4096 +CLIP_TO_PATH: Final = 4097 +END_PATH: Final = 4098 +EXT_DEVICE_CAPS: Final = 4099 +RESTORE_CTM: Final = 4100 +SAVE_CTM: Final = 4101 +SET_ARC_DIRECTION: Final = 4102 +SET_BACKGROUND_COLOR: Final = 4103 +SET_POLY_MODE: Final = 4104 +SET_SCREEN_ANGLE: Final = 4105 +SET_SPREAD: Final = 4106 +TRANSFORM_CTM: Final = 4107 +SET_CLIP_BOX: Final = 4108 +SET_BOUNDS: Final = 4109 +SET_MIRROR_MODE: Final = 4110 +OPENCHANNEL: Final = 4110 +DOWNLOADHEADER: Final = 4111 +CLOSECHANNEL: Final = 4112 +POSTSCRIPT_PASSTHROUGH: Final = 4115 +ENCAPSULATED_POSTSCRIPT: Final = 4116 +SP_NOTREPORTED: Final = 16384 +SP_ERROR: Final = -1 +SP_APPABORT: Final = -2 +SP_USERABORT: Final = -3 +SP_OUTOFDISK: Final = -4 +SP_OUTOFMEMORY: Final = -5 +PR_JOBSTATUS: Final = 0 + +OBJ_PEN: Final = 1 +OBJ_BRUSH: Final = 2 +OBJ_DC: Final = 3 +OBJ_METADC: Final = 4 +OBJ_PAL: Final = 5 +OBJ_FONT: Final = 6 +OBJ_BITMAP: Final = 7 +OBJ_REGION: Final = 8 +OBJ_METAFILE: Final = 9 +OBJ_MEMDC: Final = 10 +OBJ_EXTPEN: Final = 11 +OBJ_ENHMETADC: Final = 12 +OBJ_ENHMETAFILE: Final = 13 +OBJ_COLORSPACE: Final = 14 + +MWT_IDENTITY: Final = 1 +MWT_LEFTMULTIPLY: Final = 2 +MWT_RIGHTMULTIPLY: Final = 3 +MWT_MIN: Final = MWT_IDENTITY +MWT_MAX: Final = MWT_RIGHTMULTIPLY +BI_RGB: Final = 0 +BI_RLE8: Final = 1 +BI_RLE4: Final = 2 +BI_BITFIELDS: Final = 3 +TMPF_FIXED_PITCH: Final = 1 +TMPF_VECTOR: Final = 2 +TMPF_DEVICE: Final = 8 +TMPF_TRUETYPE: Final = 4 +NTM_REGULAR: Final = 64 +NTM_BOLD: Final = 32 +NTM_ITALIC: Final = 1 +LF_FACESIZE: Final = 32 +LF_FULLFACESIZE: Final = 64 +OUT_DEFAULT_PRECIS: Final = 0 +OUT_STRING_PRECIS: Final = 1 +OUT_CHARACTER_PRECIS: Final = 2 +OUT_STROKE_PRECIS: Final = 3 +OUT_TT_PRECIS: Final = 4 +OUT_DEVICE_PRECIS: Final = 5 +OUT_RASTER_PRECIS: Final = 6 +OUT_TT_ONLY_PRECIS: Final = 7 +OUT_OUTLINE_PRECIS: Final = 8 +CLIP_DEFAULT_PRECIS: Final = 0 +CLIP_CHARACTER_PRECIS: Final = 1 +CLIP_STROKE_PRECIS: Final = 2 +CLIP_MASK: Final = 15 +CLIP_LH_ANGLES: Final[int] +CLIP_TT_ALWAYS: Final[int] +CLIP_EMBEDDED: Final[int] +DEFAULT_QUALITY: Final = 0 +DRAFT_QUALITY: Final = 1 +PROOF_QUALITY: Final = 2 +NONANTIALIASED_QUALITY: Final = 3 +ANTIALIASED_QUALITY: Final = 4 +CLEARTYPE_QUALITY: Final = 5 +CLEARTYPE_NATURAL_QUALITY: Final = 6 +DEFAULT_PITCH: Final = 0 +FIXED_PITCH: Final = 1 +VARIABLE_PITCH: Final = 2 +ANSI_CHARSET: Final = 0 +DEFAULT_CHARSET: Final = 1 +SYMBOL_CHARSET: Final = 2 +SHIFTJIS_CHARSET: Final = 128 +HANGEUL_CHARSET: Final = 129 +CHINESEBIG5_CHARSET: Final = 136 +OEM_CHARSET: Final = 255 +JOHAB_CHARSET: Final = 130 +HEBREW_CHARSET: Final = 177 +ARABIC_CHARSET: Final = 178 +GREEK_CHARSET: Final = 161 +TURKISH_CHARSET: Final = 162 +VIETNAMESE_CHARSET: Final = 163 +THAI_CHARSET: Final = 222 +EASTEUROPE_CHARSET: Final = 238 +RUSSIAN_CHARSET: Final = 204 +MAC_CHARSET: Final = 77 +BALTIC_CHARSET: Final = 186 +FF_DONTCARE: Final[int] +FF_ROMAN: Final[int] +FF_SWISS: Final[int] +FF_MODERN: Final[int] +FF_SCRIPT: Final[int] +FF_DECORATIVE: Final[int] +FW_DONTCARE: Final = 0 +FW_THIN: Final = 100 +FW_EXTRALIGHT: Final = 200 +FW_LIGHT: Final = 300 +FW_NORMAL: Final = 400 +FW_MEDIUM: Final = 500 +FW_SEMIBOLD: Final = 600 +FW_BOLD: Final = 700 +FW_EXTRABOLD: Final = 800 +FW_HEAVY: Final = 900 +FW_ULTRALIGHT: Final = FW_EXTRALIGHT +FW_REGULAR: Final = FW_NORMAL +FW_DEMIBOLD: Final = FW_SEMIBOLD +FW_ULTRABOLD: Final = FW_EXTRABOLD +FW_BLACK: Final = FW_HEAVY + +BS_SOLID: Final = 0 +BS_NULL: Final = 1 +BS_HOLLOW: Final = BS_NULL +BS_HATCHED: Final = 2 +BS_PATTERN: Final = 3 +BS_INDEXED: Final = 4 +BS_DIBPATTERN: Final = 5 +BS_DIBPATTERNPT: Final = 6 +BS_PATTERN8X8: Final = 7 +BS_DIBPATTERN8X8: Final = 8 +HS_HORIZONTAL: Final = 0 +HS_VERTICAL: Final = 1 +HS_FDIAGONAL: Final = 2 +HS_BDIAGONAL: Final = 3 +HS_CROSS: Final = 4 +HS_DIAGCROSS: Final = 5 +HS_FDIAGONAL1: Final = 6 +HS_BDIAGONAL1: Final = 7 +HS_SOLID: Final = 8 +HS_DENSE1: Final = 9 +HS_DENSE2: Final = 10 +HS_DENSE3: Final = 11 +HS_DENSE4: Final = 12 +HS_DENSE5: Final = 13 +HS_DENSE6: Final = 14 +HS_DENSE7: Final = 15 +HS_DENSE8: Final = 16 +HS_NOSHADE: Final = 17 +HS_HALFTONE: Final = 18 +HS_SOLIDCLR: Final = 19 +HS_DITHEREDCLR: Final = 20 +HS_SOLIDTEXTCLR: Final = 21 +HS_DITHEREDTEXTCLR: Final = 22 +HS_SOLIDBKCLR: Final = 23 +HS_DITHEREDBKCLR: Final = 24 +HS_API_MAX: Final = 25 +PS_SOLID: Final = 0 +PS_DASH: Final = 1 +PS_DOT: Final = 2 +PS_DASHDOT: Final = 3 +PS_DASHDOTDOT: Final = 4 +PS_NULL: Final = 5 +PS_INSIDEFRAME: Final = 6 +PS_USERSTYLE: Final = 7 +PS_ALTERNATE: Final = 8 +PS_STYLE_MASK: Final = 15 +PS_ENDCAP_ROUND: Final = 0 +PS_ENDCAP_SQUARE: Final = 256 +PS_ENDCAP_FLAT: Final = 512 +PS_ENDCAP_MASK: Final = 3840 +PS_JOIN_ROUND: Final = 0 +PS_JOIN_BEVEL: Final = 4096 +PS_JOIN_MITER: Final = 8192 +PS_JOIN_MASK: Final = 61440 +PS_COSMETIC: Final = 0 +PS_GEOMETRIC: Final = 65536 +PS_TYPE_MASK: Final = 983040 +AD_COUNTERCLOCKWISE: Final = 1 +AD_CLOCKWISE: Final = 2 +DRIVERVERSION: Final = 0 +TECHNOLOGY: Final = 2 +HORZSIZE: Final = 4 +VERTSIZE: Final = 6 +HORZRES: Final = 8 +VERTRES: Final = 10 +BITSPIXEL: Final = 12 +PLANES: Final = 14 +NUMBRUSHES: Final = 16 +NUMPENS: Final = 18 +NUMMARKERS: Final = 20 +NUMFONTS: Final = 22 +NUMCOLORS: Final = 24 +PDEVICESIZE: Final = 26 +CURVECAPS: Final = 28 +LINECAPS: Final = 30 +POLYGONALCAPS: Final = 32 +TEXTCAPS: Final = 34 +CLIPCAPS: Final = 36 +RASTERCAPS: Final = 38 +ASPECTX: Final = 40 +ASPECTY: Final = 42 +ASPECTXY: Final = 44 +LOGPIXELSX: Final = 88 +LOGPIXELSY: Final = 90 +SIZEPALETTE: Final = 104 +NUMRESERVED: Final = 106 +COLORRES: Final = 108 + +PHYSICALWIDTH: Final = 110 +PHYSICALHEIGHT: Final = 111 +PHYSICALOFFSETX: Final = 112 +PHYSICALOFFSETY: Final = 113 +SCALINGFACTORX: Final = 114 +SCALINGFACTORY: Final = 115 +VREFRESH: Final = 116 +DESKTOPVERTRES: Final = 117 +DESKTOPHORZRES: Final = 118 +BLTALIGNMENT: Final = 119 +SHADEBLENDCAPS: Final = 120 +COLORMGMTCAPS: Final = 121 + +DT_PLOTTER: Final = 0 +DT_RASDISPLAY: Final = 1 +DT_RASPRINTER: Final = 2 +DT_RASCAMERA: Final = 3 +DT_CHARSTREAM: Final = 4 +DT_METAFILE: Final = 5 +DT_DISPFILE: Final = 6 +CC_NONE: Final = 0 +CC_CIRCLES: Final = 1 +CC_PIE: Final = 2 +CC_CHORD: Final = 4 +CC_ELLIPSES: Final = 8 +CC_WIDE: Final = 16 +CC_STYLED: Final = 32 +CC_WIDESTYLED: Final = 64 +CC_INTERIORS: Final = 128 +CC_ROUNDRECT: Final = 256 +LC_NONE: Final = 0 +LC_POLYLINE: Final = 2 +LC_MARKER: Final = 4 +LC_POLYMARKER: Final = 8 +LC_WIDE: Final = 16 +LC_STYLED: Final = 32 +LC_WIDESTYLED: Final = 64 +LC_INTERIORS: Final = 128 +PC_NONE: Final = 0 +PC_POLYGON: Final = 1 +PC_RECTANGLE: Final = 2 +PC_WINDPOLYGON: Final = 4 +PC_TRAPEZOID: Final = 4 +PC_SCANLINE: Final = 8 +PC_WIDE: Final = 16 +PC_STYLED: Final = 32 +PC_WIDESTYLED: Final = 64 +PC_INTERIORS: Final = 128 +CP_NONE: Final = 0 +CP_RECTANGLE: Final = 1 +CP_REGION: Final = 2 +TC_OP_CHARACTER: Final = 1 +TC_OP_STROKE: Final = 2 +TC_CP_STROKE: Final = 4 +TC_CR_90: Final = 8 +TC_CR_ANY: Final = 16 +TC_SF_X_YINDEP: Final = 32 +TC_SA_DOUBLE: Final = 64 +TC_SA_INTEGER: Final = 128 +TC_SA_CONTIN: Final = 256 +TC_EA_DOUBLE: Final = 512 +TC_IA_ABLE: Final = 1024 +TC_UA_ABLE: Final = 2048 +TC_SO_ABLE: Final = 4096 +TC_RA_ABLE: Final = 8192 +TC_VA_ABLE: Final = 16384 +TC_RESERVED: Final = 32768 +TC_SCROLLBLT: Final = 65536 +RC_BITBLT: Final = 1 +RC_BANDING: Final = 2 +RC_SCALING: Final = 4 +RC_BITMAP64: Final = 8 +RC_GDI20_OUTPUT: Final = 16 +RC_GDI20_STATE: Final = 32 +RC_SAVEBITMAP: Final = 64 +RC_DI_BITMAP: Final = 128 +RC_PALETTE: Final = 256 +RC_DIBTODEV: Final = 512 +RC_BIGFONT: Final = 1024 +RC_STRETCHBLT: Final = 2048 +RC_FLOODFILL: Final = 4096 +RC_STRETCHDIB: Final = 8192 +RC_OP_DX_OUTPUT: Final = 16384 +RC_DEVBITS: Final = 32768 +DIB_RGB_COLORS: Final = 0 +DIB_PAL_COLORS: Final = 1 +DIB_PAL_INDICES: Final = 2 +DIB_PAL_PHYSINDICES: Final = 2 +DIB_PAL_LOGINDICES: Final = 4 +SYSPAL_ERROR: Final = 0 +SYSPAL_STATIC: Final = 1 +SYSPAL_NOSTATIC: Final = 2 +CBM_CREATEDIB: Final = 2 +CBM_INIT: Final = 4 +FLOODFILLBORDER: Final = 0 +FLOODFILLSURFACE: Final = 1 +CCHFORMNAME: Final = 32 + +DM_SPECVERSION: Final = 800 +DM_ORIENTATION: Final = 1 +DM_PAPERSIZE: Final = 2 +DM_PAPERLENGTH: Final = 4 +DM_PAPERWIDTH: Final = 8 +DM_SCALE: Final = 16 +DM_POSITION: Final = 32 +DM_NUP: Final = 64 +DM_DISPLAYORIENTATION: Final = 128 +DM_COPIES: Final = 256 +DM_DEFAULTSOURCE: Final = 512 +DM_PRINTQUALITY: Final = 1024 +DM_COLOR: Final = 2048 +DM_DUPLEX: Final = 4096 +DM_YRESOLUTION: Final = 8192 +DM_TTOPTION: Final = 16384 +DM_COLLATE: Final = 32768 +DM_FORMNAME: Final = 65536 +DM_LOGPIXELS: Final = 131072 +DM_BITSPERPEL: Final = 262144 +DM_PELSWIDTH: Final = 524288 +DM_PELSHEIGHT: Final = 1048576 +DM_DISPLAYFLAGS: Final = 2097152 +DM_DISPLAYFREQUENCY: Final = 4194304 +DM_ICMMETHOD: Final = 8388608 +DM_ICMINTENT: Final = 16777216 +DM_MEDIATYPE: Final = 33554432 +DM_DITHERTYPE: Final = 67108864 +DM_PANNINGWIDTH: Final = 134217728 +DM_PANNINGHEIGHT: Final = 268435456 +DM_DISPLAYFIXEDOUTPUT: Final = 536870912 + +DMORIENT_PORTRAIT: Final = 1 +DMORIENT_LANDSCAPE: Final = 2 + +DMDO_DEFAULT: Final = 0 +DMDO_90: Final = 1 +DMDO_180: Final = 2 +DMDO_270: Final = 3 + +DMDFO_DEFAULT: Final = 0 +DMDFO_STRETCH: Final = 1 +DMDFO_CENTER: Final = 2 + +DMPAPER_LETTER: Final = 1 +DMPAPER_LETTERSMALL: Final = 2 +DMPAPER_TABLOID: Final = 3 +DMPAPER_LEDGER: Final = 4 +DMPAPER_LEGAL: Final = 5 +DMPAPER_STATEMENT: Final = 6 +DMPAPER_EXECUTIVE: Final = 7 +DMPAPER_A3: Final = 8 +DMPAPER_A4: Final = 9 +DMPAPER_A4SMALL: Final = 10 +DMPAPER_A5: Final = 11 +DMPAPER_B4: Final = 12 +DMPAPER_B5: Final = 13 +DMPAPER_FOLIO: Final = 14 +DMPAPER_QUARTO: Final = 15 +DMPAPER_10X14: Final = 16 +DMPAPER_11X17: Final = 17 +DMPAPER_NOTE: Final = 18 +DMPAPER_ENV_9: Final = 19 +DMPAPER_ENV_10: Final = 20 +DMPAPER_ENV_11: Final = 21 +DMPAPER_ENV_12: Final = 22 +DMPAPER_ENV_14: Final = 23 +DMPAPER_CSHEET: Final = 24 +DMPAPER_DSHEET: Final = 25 +DMPAPER_ESHEET: Final = 26 +DMPAPER_ENV_DL: Final = 27 +DMPAPER_ENV_C5: Final = 28 +DMPAPER_ENV_C3: Final = 29 +DMPAPER_ENV_C4: Final = 30 +DMPAPER_ENV_C6: Final = 31 +DMPAPER_ENV_C65: Final = 32 +DMPAPER_ENV_B4: Final = 33 +DMPAPER_ENV_B5: Final = 34 +DMPAPER_ENV_B6: Final = 35 +DMPAPER_ENV_ITALY: Final = 36 +DMPAPER_ENV_MONARCH: Final = 37 +DMPAPER_ENV_PERSONAL: Final = 38 +DMPAPER_FANFOLD_US: Final = 39 +DMPAPER_FANFOLD_STD_GERMAN: Final = 40 +DMPAPER_FANFOLD_LGL_GERMAN: Final = 41 +DMPAPER_ISO_B4: Final = 42 +DMPAPER_JAPANESE_POSTCARD: Final = 43 +DMPAPER_9X11: Final = 44 +DMPAPER_10X11: Final = 45 +DMPAPER_15X11: Final = 46 +DMPAPER_ENV_INVITE: Final = 47 +DMPAPER_RESERVED_48: Final = 48 +DMPAPER_RESERVED_49: Final = 49 +DMPAPER_LETTER_EXTRA: Final = 50 +DMPAPER_LEGAL_EXTRA: Final = 51 +DMPAPER_TABLOID_EXTRA: Final = 52 +DMPAPER_A4_EXTRA: Final = 53 +DMPAPER_LETTER_TRANSVERSE: Final = 54 +DMPAPER_A4_TRANSVERSE: Final = 55 +DMPAPER_LETTER_EXTRA_TRANSVERSE: Final = 56 +DMPAPER_A_PLUS: Final = 57 +DMPAPER_B_PLUS: Final = 58 +DMPAPER_LETTER_PLUS: Final = 59 +DMPAPER_A4_PLUS: Final = 60 +DMPAPER_A5_TRANSVERSE: Final = 61 +DMPAPER_B5_TRANSVERSE: Final = 62 +DMPAPER_A3_EXTRA: Final = 63 +DMPAPER_A5_EXTRA: Final = 64 +DMPAPER_B5_EXTRA: Final = 65 +DMPAPER_A2: Final = 66 +DMPAPER_A3_TRANSVERSE: Final = 67 +DMPAPER_A3_EXTRA_TRANSVERSE: Final = 68 +DMPAPER_DBL_JAPANESE_POSTCARD: Final = 69 +DMPAPER_A6: Final = 70 +DMPAPER_JENV_KAKU2: Final = 71 +DMPAPER_JENV_KAKU3: Final = 72 +DMPAPER_JENV_CHOU3: Final = 73 +DMPAPER_JENV_CHOU4: Final = 74 +DMPAPER_LETTER_ROTATED: Final = 75 +DMPAPER_A3_ROTATED: Final = 76 +DMPAPER_A4_ROTATED: Final = 77 +DMPAPER_A5_ROTATED: Final = 78 +DMPAPER_B4_JIS_ROTATED: Final = 79 +DMPAPER_B5_JIS_ROTATED: Final = 80 +DMPAPER_JAPANESE_POSTCARD_ROTATED: Final = 81 +DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED: Final = 82 +DMPAPER_A6_ROTATED: Final = 83 +DMPAPER_JENV_KAKU2_ROTATED: Final = 84 +DMPAPER_JENV_KAKU3_ROTATED: Final = 85 +DMPAPER_JENV_CHOU3_ROTATED: Final = 86 +DMPAPER_JENV_CHOU4_ROTATED: Final = 87 +DMPAPER_B6_JIS: Final = 88 +DMPAPER_B6_JIS_ROTATED: Final = 89 +DMPAPER_12X11: Final = 90 +DMPAPER_JENV_YOU4: Final = 91 +DMPAPER_JENV_YOU4_ROTATED: Final = 92 +DMPAPER_P16K: Final = 93 +DMPAPER_P32K: Final = 94 +DMPAPER_P32KBIG: Final = 95 +DMPAPER_PENV_1: Final = 96 +DMPAPER_PENV_2: Final = 97 +DMPAPER_PENV_3: Final = 98 +DMPAPER_PENV_4: Final = 99 +DMPAPER_PENV_5: Final = 100 +DMPAPER_PENV_6: Final = 101 +DMPAPER_PENV_7: Final = 102 +DMPAPER_PENV_8: Final = 103 +DMPAPER_PENV_9: Final = 104 +DMPAPER_PENV_10: Final = 105 +DMPAPER_P16K_ROTATED: Final = 106 +DMPAPER_P32K_ROTATED: Final = 107 +DMPAPER_P32KBIG_ROTATED: Final = 108 +DMPAPER_PENV_1_ROTATED: Final = 109 +DMPAPER_PENV_2_ROTATED: Final = 110 +DMPAPER_PENV_3_ROTATED: Final = 111 +DMPAPER_PENV_4_ROTATED: Final = 112 +DMPAPER_PENV_5_ROTATED: Final = 113 +DMPAPER_PENV_6_ROTATED: Final = 114 +DMPAPER_PENV_7_ROTATED: Final = 115 +DMPAPER_PENV_8_ROTATED: Final = 116 +DMPAPER_PENV_9_ROTATED: Final = 117 +DMPAPER_PENV_10_ROTATED: Final = 118 +DMPAPER_LAST: Final = DMPAPER_PENV_10_ROTATED +DMPAPER_USER: Final = 256 + +DMBIN_UPPER: Final = 1 +DMBIN_ONLYONE: Final = 1 +DMBIN_LOWER: Final = 2 +DMBIN_MIDDLE: Final = 3 +DMBIN_MANUAL: Final = 4 +DMBIN_ENVELOPE: Final = 5 +DMBIN_ENVMANUAL: Final = 6 +DMBIN_AUTO: Final = 7 +DMBIN_TRACTOR: Final = 8 +DMBIN_SMALLFMT: Final = 9 +DMBIN_LARGEFMT: Final = 10 +DMBIN_LARGECAPACITY: Final = 11 +DMBIN_CASSETTE: Final = 14 +DMBIN_FORMSOURCE: Final = 15 +DMBIN_LAST: Final = DMBIN_FORMSOURCE +DMBIN_USER: Final = 256 + +DMRES_DRAFT: Final = -1 +DMRES_LOW: Final = -2 +DMRES_MEDIUM: Final = -3 +DMRES_HIGH: Final = -4 + +DMCOLOR_MONOCHROME: Final = 1 +DMCOLOR_COLOR: Final = 2 + +DMDUP_SIMPLEX: Final = 1 +DMDUP_VERTICAL: Final = 2 +DMDUP_HORIZONTAL: Final = 3 + +DMTT_BITMAP: Final = 1 +DMTT_DOWNLOAD: Final = 2 +DMTT_SUBDEV: Final = 3 +DMTT_DOWNLOAD_OUTLINE: Final = 4 + +DMCOLLATE_FALSE: Final = 0 +DMCOLLATE_TRUE: Final = 1 + +DM_GRAYSCALE: Final = 1 +DM_INTERLACED: Final = 2 + +DMICMMETHOD_NONE: Final = 1 +DMICMMETHOD_SYSTEM: Final = 2 +DMICMMETHOD_DRIVER: Final = 3 +DMICMMETHOD_DEVICE: Final = 4 +DMICMMETHOD_USER: Final = 256 + +DMICM_SATURATE: Final = 1 +DMICM_CONTRAST: Final = 2 +DMICM_COLORIMETRIC: Final = 3 +DMICM_ABS_COLORIMETRIC: Final = 4 +DMICM_USER: Final = 256 + +DMMEDIA_STANDARD: Final = 1 +DMMEDIA_TRANSPARENCY: Final = 2 +DMMEDIA_GLOSSY: Final = 3 +DMMEDIA_USER: Final = 256 + +DMDITHER_NONE: Final = 1 +DMDITHER_COARSE: Final = 2 +DMDITHER_FINE: Final = 3 +DMDITHER_LINEART: Final = 4 +DMDITHER_ERRORDIFFUSION: Final = 5 +DMDITHER_RESERVED6: Final = 6 +DMDITHER_RESERVED7: Final = 7 +DMDITHER_RESERVED8: Final = 8 +DMDITHER_RESERVED9: Final = 9 +DMDITHER_GRAYSCALE: Final = 10 +DMDITHER_USER: Final = 256 + +DMNUP_SYSTEM: Final = 1 +DMNUP_ONEUP: Final = 2 + +FEATURESETTING_NUP: Final = 0 +FEATURESETTING_OUTPUT: Final = 1 +FEATURESETTING_PSLEVEL: Final = 2 +FEATURESETTING_CUSTPAPER: Final = 3 +FEATURESETTING_MIRROR: Final = 4 +FEATURESETTING_NEGATIVE: Final = 5 +FEATURESETTING_PROTOCOL: Final = 6 +FEATURESETTING_PRIVATE_BEGIN: Final = 0x1000 +FEATURESETTING_PRIVATE_END: Final = 0x1FFF + +RDH_RECTANGLES: Final = 1 +GGO_METRICS: Final = 0 +GGO_BITMAP: Final = 1 +GGO_NATIVE: Final = 2 +TT_POLYGON_TYPE: Final = 24 +TT_PRIM_LINE: Final = 1 +TT_PRIM_QSPLINE: Final = 2 +TT_AVAILABLE: Final = 1 +TT_ENABLED: Final = 2 +DM_UPDATE: Final = 1 +DM_COPY: Final = 2 +DM_PROMPT: Final = 4 +DM_MODIFY: Final = 8 +DM_IN_BUFFER: Final = DM_MODIFY +DM_IN_PROMPT: Final = DM_PROMPT +DM_OUT_BUFFER: Final = DM_COPY +DM_OUT_DEFAULT: Final = DM_UPDATE + +DISPLAY_DEVICE_ATTACHED_TO_DESKTOP: Final = 1 +DISPLAY_DEVICE_MULTI_DRIVER: Final = 2 +DISPLAY_DEVICE_PRIMARY_DEVICE: Final = 4 +DISPLAY_DEVICE_MIRRORING_DRIVER: Final = 8 +DISPLAY_DEVICE_VGA_COMPATIBLE: Final = 16 +DISPLAY_DEVICE_REMOVABLE: Final = 32 +DISPLAY_DEVICE_MODESPRUNED: Final = 134217728 +DISPLAY_DEVICE_REMOTE: Final = 67108864 +DISPLAY_DEVICE_DISCONNECT: Final = 33554432 + +DC_FIELDS: Final = 1 +DC_PAPERS: Final = 2 +DC_PAPERSIZE: Final = 3 +DC_MINEXTENT: Final = 4 +DC_MAXEXTENT: Final = 5 +DC_BINS: Final = 6 +DC_DUPLEX: Final = 7 +DC_SIZE: Final = 8 +DC_EXTRA: Final = 9 +DC_VERSION: Final = 10 +DC_DRIVER: Final = 11 +DC_BINNAMES: Final = 12 +DC_ENUMRESOLUTIONS: Final = 13 +DC_FILEDEPENDENCIES: Final = 14 +DC_TRUETYPE: Final = 15 +DC_PAPERNAMES: Final = 16 +DC_ORIENTATION: Final = 17 +DC_COPIES: Final = 18 +DC_BINADJUST: Final = 19 +DC_EMF_COMPLIANT: Final = 20 +DC_DATATYPE_PRODUCED: Final = 21 +DC_COLLATE: Final = 22 +DC_MANUFACTURER: Final = 23 +DC_MODEL: Final = 24 +DC_PERSONALITY: Final = 25 +DC_PRINTRATE: Final = 26 +DC_PRINTRATEUNIT: Final = 27 +DC_PRINTERMEM: Final = 28 +DC_MEDIAREADY: Final = 29 +DC_STAPLE: Final = 30 +DC_PRINTRATEPPM: Final = 31 +DC_COLORDEVICE: Final = 32 +DC_NUP: Final = 33 +DC_MEDIATYPENAMES: Final = 34 +DC_MEDIATYPES: Final = 35 + +PRINTRATEUNIT_PPM: Final = 1 +PRINTRATEUNIT_CPS: Final = 2 +PRINTRATEUNIT_LPM: Final = 3 +PRINTRATEUNIT_IPM: Final = 4 + +DCTT_BITMAP: Final = 1 +DCTT_DOWNLOAD: Final = 2 +DCTT_SUBDEV: Final = 4 +DCTT_DOWNLOAD_OUTLINE: Final = 8 + +DCBA_FACEUPNONE: Final = 0 +DCBA_FACEUPCENTER: Final = 1 +DCBA_FACEUPLEFT: Final = 2 +DCBA_FACEUPRIGHT: Final = 3 +DCBA_FACEDOWNNONE: Final = 256 +DCBA_FACEDOWNCENTER: Final = 257 +DCBA_FACEDOWNLEFT: Final = 258 +DCBA_FACEDOWNRIGHT: Final = 259 + +CA_NEGATIVE: Final = 1 +CA_LOG_FILTER: Final = 2 +ILLUMINANT_DEVICE_DEFAULT: Final = 0 +ILLUMINANT_A: Final = 1 +ILLUMINANT_B: Final = 2 +ILLUMINANT_C: Final = 3 +ILLUMINANT_D50: Final = 4 +ILLUMINANT_D55: Final = 5 +ILLUMINANT_D65: Final = 6 +ILLUMINANT_D75: Final = 7 +ILLUMINANT_F2: Final = 8 +ILLUMINANT_MAX_INDEX: Final = ILLUMINANT_F2 +ILLUMINANT_TUNGSTEN: Final = ILLUMINANT_A +ILLUMINANT_DAYLIGHT: Final = ILLUMINANT_C +ILLUMINANT_FLUORESCENT: Final = ILLUMINANT_F2 +ILLUMINANT_NTSC: Final = ILLUMINANT_C + +FONTMAPPER_MAX: Final = 10 +ENHMETA_SIGNATURE: Final = 1179469088 +ENHMETA_STOCK_OBJECT: Final = -2147483648 +EMR_HEADER: Final = 1 +EMR_POLYBEZIER: Final = 2 +EMR_POLYGON: Final = 3 +EMR_POLYLINE: Final = 4 +EMR_POLYBEZIERTO: Final = 5 +EMR_POLYLINETO: Final = 6 +EMR_POLYPOLYLINE: Final = 7 +EMR_POLYPOLYGON: Final = 8 +EMR_SETWINDOWEXTEX: Final = 9 +EMR_SETWINDOWORGEX: Final = 10 +EMR_SETVIEWPORTEXTEX: Final = 11 +EMR_SETVIEWPORTORGEX: Final = 12 +EMR_SETBRUSHORGEX: Final = 13 +EMR_EOF: Final = 14 +EMR_SETPIXELV: Final = 15 +EMR_SETMAPPERFLAGS: Final = 16 +EMR_SETMAPMODE: Final = 17 +EMR_SETBKMODE: Final = 18 +EMR_SETPOLYFILLMODE: Final = 19 +EMR_SETROP2: Final = 20 +EMR_SETSTRETCHBLTMODE: Final = 21 +EMR_SETTEXTALIGN: Final = 22 +EMR_SETCOLORADJUSTMENT: Final = 23 +EMR_SETTEXTCOLOR: Final = 24 +EMR_SETBKCOLOR: Final = 25 +EMR_OFFSETCLIPRGN: Final = 26 +EMR_MOVETOEX: Final = 27 +EMR_SETMETARGN: Final = 28 +EMR_EXCLUDECLIPRECT: Final = 29 +EMR_INTERSECTCLIPRECT: Final = 30 +EMR_SCALEVIEWPORTEXTEX: Final = 31 +EMR_SCALEWINDOWEXTEX: Final = 32 +EMR_SAVEDC: Final = 33 +EMR_RESTOREDC: Final = 34 +EMR_SETWORLDTRANSFORM: Final = 35 +EMR_MODIFYWORLDTRANSFORM: Final = 36 +EMR_SELECTOBJECT: Final = 37 +EMR_CREATEPEN: Final = 38 +EMR_CREATEBRUSHINDIRECT: Final = 39 +EMR_DELETEOBJECT: Final = 40 +EMR_ANGLEARC: Final = 41 +EMR_ELLIPSE: Final = 42 +EMR_RECTANGLE: Final = 43 +EMR_ROUNDRECT: Final = 44 +EMR_ARC: Final = 45 +EMR_CHORD: Final = 46 +EMR_PIE: Final = 47 +EMR_SELECTPALETTE: Final = 48 +EMR_CREATEPALETTE: Final = 49 +EMR_SETPALETTEENTRIES: Final = 50 +EMR_RESIZEPALETTE: Final = 51 +EMR_REALIZEPALETTE: Final = 52 +EMR_EXTFLOODFILL: Final = 53 +EMR_LINETO: Final = 54 +EMR_ARCTO: Final = 55 +EMR_POLYDRAW: Final = 56 +EMR_SETARCDIRECTION: Final = 57 +EMR_SETMITERLIMIT: Final = 58 +EMR_BEGINPATH: Final = 59 +EMR_ENDPATH: Final = 60 +EMR_CLOSEFIGURE: Final = 61 +EMR_FILLPATH: Final = 62 +EMR_STROKEANDFILLPATH: Final = 63 +EMR_STROKEPATH: Final = 64 +EMR_FLATTENPATH: Final = 65 +EMR_WIDENPATH: Final = 66 +EMR_SELECTCLIPPATH: Final = 67 +EMR_ABORTPATH: Final = 68 +EMR_GDICOMMENT: Final = 70 +EMR_FILLRGN: Final = 71 +EMR_FRAMERGN: Final = 72 +EMR_INVERTRGN: Final = 73 +EMR_PAINTRGN: Final = 74 +EMR_EXTSELECTCLIPRGN: Final = 75 +EMR_BITBLT: Final = 76 +EMR_STRETCHBLT: Final = 77 +EMR_MASKBLT: Final = 78 +EMR_PLGBLT: Final = 79 +EMR_SETDIBITSTODEVICE: Final = 80 +EMR_STRETCHDIBITS: Final = 81 +EMR_EXTCREATEFONTINDIRECTW: Final = 82 +EMR_EXTTEXTOUTA: Final = 83 +EMR_EXTTEXTOUTW: Final = 84 +EMR_POLYBEZIER16: Final = 85 +EMR_POLYGON16: Final = 86 +EMR_POLYLINE16: Final = 87 +EMR_POLYBEZIERTO16: Final = 88 +EMR_POLYLINETO16: Final = 89 +EMR_POLYPOLYLINE16: Final = 90 +EMR_POLYPOLYGON16: Final = 91 +EMR_POLYDRAW16: Final = 92 +EMR_CREATEMONOBRUSH: Final = 93 +EMR_CREATEDIBPATTERNBRUSHPT: Final = 94 +EMR_EXTCREATEPEN: Final = 95 +EMR_POLYTEXTOUTA: Final = 96 +EMR_POLYTEXTOUTW: Final = 97 +EMR_MIN: Final = 1 +EMR_MAX: Final = 97 + +PANOSE_COUNT: Final = 10 +PAN_FAMILYTYPE_INDEX: Final = 0 +PAN_SERIFSTYLE_INDEX: Final = 1 +PAN_WEIGHT_INDEX: Final = 2 +PAN_PROPORTION_INDEX: Final = 3 +PAN_CONTRAST_INDEX: Final = 4 +PAN_STROKEVARIATION_INDEX: Final = 5 +PAN_ARMSTYLE_INDEX: Final = 6 +PAN_LETTERFORM_INDEX: Final = 7 +PAN_MIDLINE_INDEX: Final = 8 +PAN_XHEIGHT_INDEX: Final = 9 +PAN_CULTURE_LATIN: Final = 0 +PAN_ANY: Final = 0 +PAN_NO_FIT: Final = 1 +PAN_FAMILY_TEXT_DISPLAY: Final = 2 +PAN_FAMILY_SCRIPT: Final = 3 +PAN_FAMILY_DECORATIVE: Final = 4 +PAN_FAMILY_PICTORIAL: Final = 5 +PAN_SERIF_COVE: Final = 2 +PAN_SERIF_OBTUSE_COVE: Final = 3 +PAN_SERIF_SQUARE_COVE: Final = 4 +PAN_SERIF_OBTUSE_SQUARE_COVE: Final = 5 +PAN_SERIF_SQUARE: Final = 6 +PAN_SERIF_THIN: Final = 7 +PAN_SERIF_BONE: Final = 8 +PAN_SERIF_EXAGGERATED: Final = 9 +PAN_SERIF_TRIANGLE: Final = 10 +PAN_SERIF_NORMAL_SANS: Final = 11 +PAN_SERIF_OBTUSE_SANS: Final = 12 +PAN_SERIF_PERP_SANS: Final = 13 +PAN_SERIF_FLARED: Final = 14 +PAN_SERIF_ROUNDED: Final = 15 +PAN_WEIGHT_VERY_LIGHT: Final = 2 +PAN_WEIGHT_LIGHT: Final = 3 +PAN_WEIGHT_THIN: Final = 4 +PAN_WEIGHT_BOOK: Final = 5 +PAN_WEIGHT_MEDIUM: Final = 6 +PAN_WEIGHT_DEMI: Final = 7 +PAN_WEIGHT_BOLD: Final = 8 +PAN_WEIGHT_HEAVY: Final = 9 +PAN_WEIGHT_BLACK: Final = 10 +PAN_WEIGHT_NORD: Final = 11 +PAN_PROP_OLD_STYLE: Final = 2 +PAN_PROP_MODERN: Final = 3 +PAN_PROP_EVEN_WIDTH: Final = 4 +PAN_PROP_EXPANDED: Final = 5 +PAN_PROP_CONDENSED: Final = 6 +PAN_PROP_VERY_EXPANDED: Final = 7 +PAN_PROP_VERY_CONDENSED: Final = 8 +PAN_PROP_MONOSPACED: Final = 9 +PAN_CONTRAST_NONE: Final = 2 +PAN_CONTRAST_VERY_LOW: Final = 3 +PAN_CONTRAST_LOW: Final = 4 +PAN_CONTRAST_MEDIUM_LOW: Final = 5 +PAN_CONTRAST_MEDIUM: Final = 6 +PAN_CONTRAST_MEDIUM_HIGH: Final = 7 +PAN_CONTRAST_HIGH: Final = 8 +PAN_CONTRAST_VERY_HIGH: Final = 9 +PAN_STROKE_GRADUAL_DIAG: Final = 2 +PAN_STROKE_GRADUAL_TRAN: Final = 3 +PAN_STROKE_GRADUAL_VERT: Final = 4 +PAN_STROKE_GRADUAL_HORZ: Final = 5 +PAN_STROKE_RAPID_VERT: Final = 6 +PAN_STROKE_RAPID_HORZ: Final = 7 +PAN_STROKE_INSTANT_VERT: Final = 8 +PAN_STRAIGHT_ARMS_HORZ: Final = 2 +PAN_STRAIGHT_ARMS_WEDGE: Final = 3 +PAN_STRAIGHT_ARMS_VERT: Final = 4 +PAN_STRAIGHT_ARMS_SINGLE_SERIF: Final = 5 +PAN_STRAIGHT_ARMS_DOUBLE_SERIF: Final = 6 +PAN_BENT_ARMS_HORZ: Final = 7 +PAN_BENT_ARMS_WEDGE: Final = 8 +PAN_BENT_ARMS_VERT: Final = 9 +PAN_BENT_ARMS_SINGLE_SERIF: Final = 10 +PAN_BENT_ARMS_DOUBLE_SERIF: Final = 11 +PAN_LETT_NORMAL_CONTACT: Final = 2 +PAN_LETT_NORMAL_WEIGHTED: Final = 3 +PAN_LETT_NORMAL_BOXED: Final = 4 +PAN_LETT_NORMAL_FLATTENED: Final = 5 +PAN_LETT_NORMAL_ROUNDED: Final = 6 +PAN_LETT_NORMAL_OFF_CENTER: Final = 7 +PAN_LETT_NORMAL_SQUARE: Final = 8 +PAN_LETT_OBLIQUE_CONTACT: Final = 9 +PAN_LETT_OBLIQUE_WEIGHTED: Final = 10 +PAN_LETT_OBLIQUE_BOXED: Final = 11 +PAN_LETT_OBLIQUE_FLATTENED: Final = 12 +PAN_LETT_OBLIQUE_ROUNDED: Final = 13 +PAN_LETT_OBLIQUE_OFF_CENTER: Final = 14 +PAN_LETT_OBLIQUE_SQUARE: Final = 15 +PAN_MIDLINE_STANDARD_TRIMMED: Final = 2 +PAN_MIDLINE_STANDARD_POINTED: Final = 3 +PAN_MIDLINE_STANDARD_SERIFED: Final = 4 +PAN_MIDLINE_HIGH_TRIMMED: Final = 5 +PAN_MIDLINE_HIGH_POINTED: Final = 6 +PAN_MIDLINE_HIGH_SERIFED: Final = 7 +PAN_MIDLINE_CONSTANT_TRIMMED: Final = 8 +PAN_MIDLINE_CONSTANT_POINTED: Final = 9 +PAN_MIDLINE_CONSTANT_SERIFED: Final = 10 +PAN_MIDLINE_LOW_TRIMMED: Final = 11 +PAN_MIDLINE_LOW_POINTED: Final = 12 +PAN_MIDLINE_LOW_SERIFED: Final = 13 +PAN_XHEIGHT_CONSTANT_SMALL: Final = 2 +PAN_XHEIGHT_CONSTANT_STD: Final = 3 +PAN_XHEIGHT_CONSTANT_LARGE: Final = 4 +PAN_XHEIGHT_DUCKING_SMALL: Final = 5 +PAN_XHEIGHT_DUCKING_STD: Final = 6 +PAN_XHEIGHT_DUCKING_LARGE: Final = 7 +ELF_VENDOR_SIZE: Final = 4 +ELF_VERSION: Final = 0 +ELF_CULTURE_LATIN: Final = 0 +RASTER_FONTTYPE: Final = 1 +DEVICE_FONTTYPE: Final = 2 +TRUETYPE_FONTTYPE: Final = 4 + +def PALETTEINDEX(i: int) -> int: ... + +PC_RESERVED: Final = 1 +PC_EXPLICIT: Final = 2 +PC_NOCOLLAPSE: Final = 4 + +def GetRValue(rgb: int) -> int: ... +def GetGValue(rgb: int) -> int: ... +def GetBValue(rgb: int) -> int: ... + +TRANSPARENT: Final = 1 +OPAQUE: Final = 2 +BKMODE_LAST: Final = 2 +GM_COMPATIBLE: Final = 1 +GM_ADVANCED: Final = 2 +GM_LAST: Final = 2 +PT_CLOSEFIGURE: Final = 1 +PT_LINETO: Final = 2 +PT_BEZIERTO: Final = 4 +PT_MOVETO: Final = 6 +MM_TEXT: Final = 1 +MM_LOMETRIC: Final = 2 +MM_HIMETRIC: Final = 3 +MM_LOENGLISH: Final = 4 +MM_HIENGLISH: Final = 5 +MM_TWIPS: Final = 6 +MM_ISOTROPIC: Final = 7 +MM_ANISOTROPIC: Final = 8 +MM_MIN: Final = MM_TEXT +MM_MAX: Final = MM_ANISOTROPIC +MM_MAX_FIXEDSCALE: Final = MM_TWIPS +ABSOLUTE: Final = 1 +RELATIVE: Final = 2 +WHITE_BRUSH: Final = 0 +LTGRAY_BRUSH: Final = 1 +GRAY_BRUSH: Final = 2 +DKGRAY_BRUSH: Final = 3 +BLACK_BRUSH: Final = 4 +NULL_BRUSH: Final = 5 +HOLLOW_BRUSH: Final = NULL_BRUSH +WHITE_PEN: Final = 6 +BLACK_PEN: Final = 7 +NULL_PEN: Final = 8 +OEM_FIXED_FONT: Final = 10 +ANSI_FIXED_FONT: Final = 11 +ANSI_VAR_FONT: Final = 12 +SYSTEM_FONT: Final = 13 +DEVICE_DEFAULT_FONT: Final = 14 +DEFAULT_PALETTE: Final = 15 +SYSTEM_FIXED_FONT: Final = 16 +STOCK_LAST: Final = 16 +CLR_INVALID: Final = -1 + +DC_BRUSH: Final = 18 +DC_PEN: Final = 19 + +STATUS_WAIT_0: Final = 0 +STATUS_ABANDONED_WAIT_0: Final = 128 +STATUS_USER_APC: Final = 192 +STATUS_TIMEOUT: Final = 258 +STATUS_PENDING: Final = 259 +STATUS_SEGMENT_NOTIFICATION: Final = 1073741829 +STATUS_GUARD_PAGE_VIOLATION: Final = -2147483647 +STATUS_DATATYPE_MISALIGNMENT: Final = -2147483646 +STATUS_BREAKPOINT: Final = -2147483645 +STATUS_SINGLE_STEP: Final = -2147483644 +STATUS_ACCESS_VIOLATION: Final = -1073741819 +STATUS_IN_PAGE_ERROR: Final = -1073741818 +STATUS_INVALID_HANDLE: Final = -1073741816 +STATUS_NO_MEMORY: Final = -1073741801 +STATUS_ILLEGAL_INSTRUCTION: Final = -1073741795 +STATUS_NONCONTINUABLE_EXCEPTION: Final = -1073741787 +STATUS_INVALID_DISPOSITION: Final = -1073741786 +STATUS_ARRAY_BOUNDS_EXCEEDED: Final = -1073741684 +STATUS_FLOAT_DENORMAL_OPERAND: Final = -1073741683 +STATUS_FLOAT_DIVIDE_BY_ZERO: Final = -1073741682 +STATUS_FLOAT_INEXACT_RESULT: Final = -1073741681 +STATUS_FLOAT_INVALID_OPERATION: Final = -1073741680 +STATUS_FLOAT_OVERFLOW: Final = -1073741679 +STATUS_FLOAT_STACK_CHECK: Final = -1073741678 +STATUS_FLOAT_UNDERFLOW: Final = -1073741677 +STATUS_INTEGER_DIVIDE_BY_ZERO: Final = -1073741676 +STATUS_INTEGER_OVERFLOW: Final = -1073741675 +STATUS_PRIVILEGED_INSTRUCTION: Final = -1073741674 +STATUS_STACK_OVERFLOW: Final = -1073741571 +STATUS_CONTROL_C_EXIT: Final = -1073741510 + +WAIT_FAILED: Final = -1 +WAIT_OBJECT_0: Final[int] + +WAIT_ABANDONED: Final[int] +WAIT_ABANDONED_0: Final[int] + +WAIT_TIMEOUT: Final = STATUS_TIMEOUT +WAIT_IO_COMPLETION: Final = STATUS_USER_APC +STILL_ACTIVE: Final = STATUS_PENDING +EXCEPTION_ACCESS_VIOLATION: Final = STATUS_ACCESS_VIOLATION +EXCEPTION_DATATYPE_MISALIGNMENT: Final = STATUS_DATATYPE_MISALIGNMENT +EXCEPTION_BREAKPOINT: Final = STATUS_BREAKPOINT +EXCEPTION_SINGLE_STEP: Final = STATUS_SINGLE_STEP +EXCEPTION_ARRAY_BOUNDS_EXCEEDED: Final = STATUS_ARRAY_BOUNDS_EXCEEDED +EXCEPTION_FLT_DENORMAL_OPERAND: Final = STATUS_FLOAT_DENORMAL_OPERAND +EXCEPTION_FLT_DIVIDE_BY_ZERO: Final = STATUS_FLOAT_DIVIDE_BY_ZERO +EXCEPTION_FLT_INEXACT_RESULT: Final = STATUS_FLOAT_INEXACT_RESULT +EXCEPTION_FLT_INVALID_OPERATION: Final = STATUS_FLOAT_INVALID_OPERATION +EXCEPTION_FLT_OVERFLOW: Final = STATUS_FLOAT_OVERFLOW +EXCEPTION_FLT_STACK_CHECK: Final = STATUS_FLOAT_STACK_CHECK +EXCEPTION_FLT_UNDERFLOW: Final = STATUS_FLOAT_UNDERFLOW +EXCEPTION_INT_DIVIDE_BY_ZERO: Final = STATUS_INTEGER_DIVIDE_BY_ZERO +EXCEPTION_INT_OVERFLOW: Final = STATUS_INTEGER_OVERFLOW +EXCEPTION_PRIV_INSTRUCTION: Final = STATUS_PRIVILEGED_INSTRUCTION +EXCEPTION_IN_PAGE_ERROR: Final = STATUS_IN_PAGE_ERROR +EXCEPTION_ILLEGAL_INSTRUCTION: Final = STATUS_ILLEGAL_INSTRUCTION +EXCEPTION_NONCONTINUABLE_EXCEPTION: Final = STATUS_NONCONTINUABLE_EXCEPTION +EXCEPTION_STACK_OVERFLOW: Final = STATUS_STACK_OVERFLOW +EXCEPTION_INVALID_DISPOSITION: Final = STATUS_INVALID_DISPOSITION +EXCEPTION_GUARD_PAGE: Final = STATUS_GUARD_PAGE_VIOLATION +EXCEPTION_INVALID_HANDLE: Final = STATUS_INVALID_HANDLE +CONTROL_C_EXIT: Final = STATUS_CONTROL_C_EXIT + +SPI_GETBEEP: Final = 1 +SPI_SETBEEP: Final = 2 +SPI_GETMOUSE: Final = 3 +SPI_SETMOUSE: Final = 4 +SPI_GETBORDER: Final = 5 +SPI_SETBORDER: Final = 6 +SPI_GETKEYBOARDSPEED: Final = 10 +SPI_SETKEYBOARDSPEED: Final = 11 +SPI_LANGDRIVER: Final = 12 +SPI_ICONHORIZONTALSPACING: Final = 13 +SPI_GETSCREENSAVETIMEOUT: Final = 14 +SPI_SETSCREENSAVETIMEOUT: Final = 15 +SPI_GETSCREENSAVEACTIVE: Final = 16 +SPI_SETSCREENSAVEACTIVE: Final = 17 +SPI_GETGRIDGRANULARITY: Final = 18 +SPI_SETGRIDGRANULARITY: Final = 19 +SPI_SETDESKWALLPAPER: Final = 20 +SPI_SETDESKPATTERN: Final = 21 +SPI_GETKEYBOARDDELAY: Final = 22 +SPI_SETKEYBOARDDELAY: Final = 23 +SPI_ICONVERTICALSPACING: Final = 24 +SPI_GETICONTITLEWRAP: Final = 25 +SPI_SETICONTITLEWRAP: Final = 26 +SPI_GETMENUDROPALIGNMENT: Final = 27 +SPI_SETMENUDROPALIGNMENT: Final = 28 +SPI_SETDOUBLECLKWIDTH: Final = 29 +SPI_SETDOUBLECLKHEIGHT: Final = 30 +SPI_GETICONTITLELOGFONT: Final = 31 +SPI_SETDOUBLECLICKTIME: Final = 32 +SPI_SETMOUSEBUTTONSWAP: Final = 33 +SPI_SETICONTITLELOGFONT: Final = 34 +SPI_GETFASTTASKSWITCH: Final = 35 +SPI_SETFASTTASKSWITCH: Final = 36 +SPI_SETDRAGFULLWINDOWS: Final = 37 +SPI_GETDRAGFULLWINDOWS: Final = 38 +SPI_GETNONCLIENTMETRICS: Final = 41 +SPI_SETNONCLIENTMETRICS: Final = 42 +SPI_GETMINIMIZEDMETRICS: Final = 43 +SPI_SETMINIMIZEDMETRICS: Final = 44 +SPI_GETICONMETRICS: Final = 45 +SPI_SETICONMETRICS: Final = 46 +SPI_SETWORKAREA: Final = 47 +SPI_GETWORKAREA: Final = 48 +SPI_SETPENWINDOWS: Final = 49 +SPI_GETFILTERKEYS: Final = 50 +SPI_SETFILTERKEYS: Final = 51 +SPI_GETTOGGLEKEYS: Final = 52 +SPI_SETTOGGLEKEYS: Final = 53 +SPI_GETMOUSEKEYS: Final = 54 +SPI_SETMOUSEKEYS: Final = 55 +SPI_GETSHOWSOUNDS: Final = 56 +SPI_SETSHOWSOUNDS: Final = 57 +SPI_GETSTICKYKEYS: Final = 58 +SPI_SETSTICKYKEYS: Final = 59 +SPI_GETACCESSTIMEOUT: Final = 60 +SPI_SETACCESSTIMEOUT: Final = 61 +SPI_GETSERIALKEYS: Final = 62 +SPI_SETSERIALKEYS: Final = 63 +SPI_GETSOUNDSENTRY: Final = 64 +SPI_SETSOUNDSENTRY: Final = 65 +SPI_GETHIGHCONTRAST: Final = 66 +SPI_SETHIGHCONTRAST: Final = 67 +SPI_GETKEYBOARDPREF: Final = 68 +SPI_SETKEYBOARDPREF: Final = 69 +SPI_GETSCREENREADER: Final = 70 +SPI_SETSCREENREADER: Final = 71 +SPI_GETANIMATION: Final = 72 +SPI_SETANIMATION: Final = 73 +SPI_GETFONTSMOOTHING: Final = 74 +SPI_SETFONTSMOOTHING: Final = 75 +SPI_SETDRAGWIDTH: Final = 76 +SPI_SETDRAGHEIGHT: Final = 77 +SPI_SETHANDHELD: Final = 78 +SPI_GETLOWPOWERTIMEOUT: Final = 79 +SPI_GETPOWEROFFTIMEOUT: Final = 80 +SPI_SETLOWPOWERTIMEOUT: Final = 81 +SPI_SETPOWEROFFTIMEOUT: Final = 82 +SPI_GETLOWPOWERACTIVE: Final = 83 +SPI_GETPOWEROFFACTIVE: Final = 84 +SPI_SETLOWPOWERACTIVE: Final = 85 +SPI_SETPOWEROFFACTIVE: Final = 86 +SPI_SETCURSORS: Final = 87 +SPI_SETICONS: Final = 88 +SPI_GETDEFAULTINPUTLANG: Final = 89 +SPI_SETDEFAULTINPUTLANG: Final = 90 +SPI_SETLANGTOGGLE: Final = 91 +SPI_GETWINDOWSEXTENSION: Final = 92 +SPI_SETMOUSETRAILS: Final = 93 +SPI_GETMOUSETRAILS: Final = 94 +SPI_GETSNAPTODEFBUTTON: Final = 95 +SPI_SETSNAPTODEFBUTTON: Final = 96 +SPI_SETSCREENSAVERRUNNING: Final = 97 +SPI_SCREENSAVERRUNNING: Final = SPI_SETSCREENSAVERRUNNING +SPI_GETMOUSEHOVERWIDTH: Final = 98 +SPI_SETMOUSEHOVERWIDTH: Final = 99 +SPI_GETMOUSEHOVERHEIGHT: Final = 100 +SPI_SETMOUSEHOVERHEIGHT: Final = 101 +SPI_GETMOUSEHOVERTIME: Final = 102 +SPI_SETMOUSEHOVERTIME: Final = 103 +SPI_GETWHEELSCROLLLINES: Final = 104 +SPI_SETWHEELSCROLLLINES: Final = 105 +SPI_GETMENUSHOWDELAY: Final = 106 +SPI_SETMENUSHOWDELAY: Final = 107 + +SPI_GETSHOWIMEUI: Final = 110 +SPI_SETSHOWIMEUI: Final = 111 +SPI_GETMOUSESPEED: Final = 112 +SPI_SETMOUSESPEED: Final = 113 +SPI_GETSCREENSAVERRUNNING: Final = 114 +SPI_GETDESKWALLPAPER: Final = 115 + +SPI_GETACTIVEWINDOWTRACKING: Final = 4096 +SPI_SETACTIVEWINDOWTRACKING: Final = 4097 +SPI_GETMENUANIMATION: Final = 4098 +SPI_SETMENUANIMATION: Final = 4099 +SPI_GETCOMBOBOXANIMATION: Final = 4100 +SPI_SETCOMBOBOXANIMATION: Final = 4101 +SPI_GETLISTBOXSMOOTHSCROLLING: Final = 4102 +SPI_SETLISTBOXSMOOTHSCROLLING: Final = 4103 +SPI_GETGRADIENTCAPTIONS: Final = 4104 +SPI_SETGRADIENTCAPTIONS: Final = 4105 +SPI_GETKEYBOARDCUES: Final = 4106 +SPI_SETKEYBOARDCUES: Final = 4107 +SPI_GETMENUUNDERLINES: Final = 4106 +SPI_SETMENUUNDERLINES: Final = 4107 +SPI_GETACTIVEWNDTRKZORDER: Final = 4108 +SPI_SETACTIVEWNDTRKZORDER: Final = 4109 +SPI_GETHOTTRACKING: Final = 4110 +SPI_SETHOTTRACKING: Final = 4111 + +SPI_GETMENUFADE: Final = 4114 +SPI_SETMENUFADE: Final = 4115 +SPI_GETSELECTIONFADE: Final = 4116 +SPI_SETSELECTIONFADE: Final = 4117 +SPI_GETTOOLTIPANIMATION: Final = 4118 +SPI_SETTOOLTIPANIMATION: Final = 4119 +SPI_GETTOOLTIPFADE: Final = 4120 +SPI_SETTOOLTIPFADE: Final = 4121 +SPI_GETCURSORSHADOW: Final = 4122 +SPI_SETCURSORSHADOW: Final = 4123 +SPI_GETMOUSESONAR: Final = 4124 +SPI_SETMOUSESONAR: Final = 4125 +SPI_GETMOUSECLICKLOCK: Final = 4126 +SPI_SETMOUSECLICKLOCK: Final = 4127 +SPI_GETMOUSEVANISH: Final = 4128 +SPI_SETMOUSEVANISH: Final = 4129 +SPI_GETFLATMENU: Final = 4130 +SPI_SETFLATMENU: Final = 4131 +SPI_GETDROPSHADOW: Final = 4132 +SPI_SETDROPSHADOW: Final = 4133 +SPI_GETBLOCKSENDINPUTRESETS: Final = 4134 +SPI_SETBLOCKSENDINPUTRESETS: Final = 4135 +SPI_GETUIEFFECTS: Final = 4158 +SPI_SETUIEFFECTS: Final = 4159 + +SPI_GETFOREGROUNDLOCKTIMEOUT: Final = 8192 +SPI_SETFOREGROUNDLOCKTIMEOUT: Final = 8193 +SPI_GETACTIVEWNDTRKTIMEOUT: Final = 8194 +SPI_SETACTIVEWNDTRKTIMEOUT: Final = 8195 +SPI_GETFOREGROUNDFLASHCOUNT: Final = 8196 +SPI_SETFOREGROUNDFLASHCOUNT: Final = 8197 +SPI_GETCARETWIDTH: Final = 8198 +SPI_SETCARETWIDTH: Final = 8199 +SPI_GETMOUSECLICKLOCKTIME: Final = 8200 +SPI_SETMOUSECLICKLOCKTIME: Final = 8201 +SPI_GETFONTSMOOTHINGTYPE: Final = 8202 +SPI_SETFONTSMOOTHINGTYPE: Final = 8203 +SPI_GETFONTSMOOTHINGCONTRAST: Final = 8204 +SPI_SETFONTSMOOTHINGCONTRAST: Final = 8205 +SPI_GETFOCUSBORDERWIDTH: Final = 8206 +SPI_SETFOCUSBORDERWIDTH: Final = 8207 +SPI_GETFOCUSBORDERHEIGHT: Final = 8208 +SPI_SETFOCUSBORDERHEIGHT: Final = 8209 +SPI_GETFONTSMOOTHINGORIENTATION: Final = 8210 +SPI_SETFONTSMOOTHINGORIENTATION: Final = 8211 + +SPIF_UPDATEINIFILE: Final = 1 +SPIF_SENDWININICHANGE: Final = 2 +SPIF_SENDCHANGE: Final = SPIF_SENDWININICHANGE + +FE_FONTSMOOTHINGSTANDARD: Final = 1 +FE_FONTSMOOTHINGCLEARTYPE: Final = 2 +FE_FONTSMOOTHINGDOCKING: Final = 32768 + +METRICS_USEDEFAULT: Final = -1 +ARW_BOTTOMLEFT: Final = 0 +ARW_BOTTOMRIGHT: Final = 1 +ARW_TOPLEFT: Final = 2 +ARW_TOPRIGHT: Final = 3 +ARW_STARTMASK: Final = 3 +ARW_STARTRIGHT: Final = 1 +ARW_STARTTOP: Final = 2 +ARW_LEFT: Final = 0 +ARW_RIGHT: Final = 0 +ARW_UP: Final = 4 +ARW_DOWN: Final = 4 +ARW_HIDE: Final = 8 + +SERKF_SERIALKEYSON: Final = 1 +SERKF_AVAILABLE: Final = 2 +SERKF_INDICATOR: Final = 4 +HCF_HIGHCONTRASTON: Final = 1 +HCF_AVAILABLE: Final = 2 +HCF_HOTKEYACTIVE: Final = 4 +HCF_CONFIRMHOTKEY: Final = 8 +HCF_HOTKEYSOUND: Final = 16 +HCF_INDICATOR: Final = 32 +HCF_HOTKEYAVAILABLE: Final = 64 +CDS_UPDATEREGISTRY: Final = 1 +CDS_TEST: Final = 2 +CDS_FULLSCREEN: Final = 4 +CDS_GLOBAL: Final = 8 +CDS_SET_PRIMARY: Final = 16 +CDS_RESET: Final = 1073741824 +CDS_SETRECT: Final = 536870912 +CDS_NORESET: Final = 268435456 + +DISP_CHANGE_SUCCESSFUL: Final = 0 +DISP_CHANGE_RESTART: Final = 1 +DISP_CHANGE_FAILED: Final = -1 +DISP_CHANGE_BADMODE: Final = -2 +DISP_CHANGE_NOTUPDATED: Final = -3 +DISP_CHANGE_BADFLAGS: Final = -4 +DISP_CHANGE_BADPARAM: Final = -5 +DISP_CHANGE_BADDUALVIEW: Final = -6 + +ENUM_CURRENT_SETTINGS: Final = -1 +ENUM_REGISTRY_SETTINGS: Final = -2 +FKF_FILTERKEYSON: Final = 1 +FKF_AVAILABLE: Final = 2 +FKF_HOTKEYACTIVE: Final = 4 +FKF_CONFIRMHOTKEY: Final = 8 +FKF_HOTKEYSOUND: Final = 16 +FKF_INDICATOR: Final = 32 +FKF_CLICKON: Final = 64 +SKF_STICKYKEYSON: Final = 1 +SKF_AVAILABLE: Final = 2 +SKF_HOTKEYACTIVE: Final = 4 +SKF_CONFIRMHOTKEY: Final = 8 +SKF_HOTKEYSOUND: Final = 16 +SKF_INDICATOR: Final = 32 +SKF_AUDIBLEFEEDBACK: Final = 64 +SKF_TRISTATE: Final = 128 +SKF_TWOKEYSOFF: Final = 256 +SKF_LALTLATCHED: Final = 268435456 +SKF_LCTLLATCHED: Final = 67108864 +SKF_LSHIFTLATCHED: Final = 16777216 +SKF_RALTLATCHED: Final = 536870912 +SKF_RCTLLATCHED: Final = 134217728 +SKF_RSHIFTLATCHED: Final = 33554432 +SKF_LWINLATCHED: Final = 1073741824 +SKF_RWINLATCHED: Final = -2147483648 +SKF_LALTLOCKED: Final = 1048576 +SKF_LCTLLOCKED: Final = 262144 +SKF_LSHIFTLOCKED: Final = 65536 +SKF_RALTLOCKED: Final = 2097152 +SKF_RCTLLOCKED: Final = 524288 +SKF_RSHIFTLOCKED: Final = 131072 +SKF_LWINLOCKED: Final = 4194304 +SKF_RWINLOCKED: Final = 8388608 +MKF_MOUSEKEYSON: Final = 1 +MKF_AVAILABLE: Final = 2 +MKF_HOTKEYACTIVE: Final = 4 +MKF_CONFIRMHOTKEY: Final = 8 +MKF_HOTKEYSOUND: Final = 16 +MKF_INDICATOR: Final = 32 +MKF_MODIFIERS: Final = 64 +MKF_REPLACENUMBERS: Final = 128 +MKF_LEFTBUTTONSEL: Final = 268435456 +MKF_RIGHTBUTTONSEL: Final = 536870912 +MKF_LEFTBUTTONDOWN: Final = 16777216 +MKF_RIGHTBUTTONDOWN: Final = 33554432 +MKF_MOUSEMODE: Final = -2147483648 +ATF_TIMEOUTON: Final = 1 +ATF_ONOFFFEEDBACK: Final = 2 +SSGF_NONE: Final = 0 +SSGF_DISPLAY: Final = 3 +SSTF_NONE: Final = 0 +SSTF_CHARS: Final = 1 +SSTF_BORDER: Final = 2 +SSTF_DISPLAY: Final = 3 +SSWF_NONE: Final = 0 +SSWF_TITLE: Final = 1 +SSWF_WINDOW: Final = 2 +SSWF_DISPLAY: Final = 3 +SSWF_CUSTOM: Final = 4 +SSF_SOUNDSENTRYON: Final = 1 +SSF_AVAILABLE: Final = 2 +SSF_INDICATOR: Final = 4 +TKF_TOGGLEKEYSON: Final = 1 +TKF_AVAILABLE: Final = 2 +TKF_HOTKEYACTIVE: Final = 4 +TKF_CONFIRMHOTKEY: Final = 8 +TKF_HOTKEYSOUND: Final = 16 +TKF_INDICATOR: Final = 32 +SLE_ERROR: Final = 1 +SLE_MINORERROR: Final = 2 +SLE_WARNING: Final = 3 +MONITOR_DEFAULTTONULL: Final = 0 +MONITOR_DEFAULTTOPRIMARY: Final = 1 +MONITOR_DEFAULTTONEAREST: Final = 2 +MONITORINFOF_PRIMARY: Final = 1 +CCHDEVICENAME: Final = 32 +CHILDID_SELF: Final = 0 +INDEXID_OBJECT: Final = 0 +INDEXID_CONTAINER: Final = 0 +OBJID_WINDOW: Final = 0 +OBJID_SYSMENU: Final = -1 +OBJID_TITLEBAR: Final = -2 +OBJID_MENU: Final = -3 +OBJID_CLIENT: Final = -4 +OBJID_VSCROLL: Final = -5 +OBJID_HSCROLL: Final = -6 +OBJID_SIZEGRIP: Final = -7 +OBJID_CARET: Final = -8 +OBJID_CURSOR: Final = -9 +OBJID_ALERT: Final = -10 +OBJID_SOUND: Final = -11 +EVENT_MIN: Final = 1 +EVENT_MAX: Final = 2147483647 +EVENT_SYSTEM_SOUND: Final = 1 +EVENT_SYSTEM_ALERT: Final = 2 +EVENT_SYSTEM_FOREGROUND: Final = 3 +EVENT_SYSTEM_MENUSTART: Final = 4 +EVENT_SYSTEM_MENUEND: Final = 5 +EVENT_SYSTEM_MENUPOPUPSTART: Final = 6 +EVENT_SYSTEM_MENUPOPUPEND: Final = 7 +EVENT_SYSTEM_CAPTURESTART: Final = 8 +EVENT_SYSTEM_CAPTUREEND: Final = 9 +EVENT_SYSTEM_MOVESIZESTART: Final = 10 +EVENT_SYSTEM_MOVESIZEEND: Final = 11 +EVENT_SYSTEM_CONTEXTHELPSTART: Final = 12 +EVENT_SYSTEM_CONTEXTHELPEND: Final = 13 +EVENT_SYSTEM_DRAGDROPSTART: Final = 14 +EVENT_SYSTEM_DRAGDROPEND: Final = 15 +EVENT_SYSTEM_DIALOGSTART: Final = 16 +EVENT_SYSTEM_DIALOGEND: Final = 17 +EVENT_SYSTEM_SCROLLINGSTART: Final = 18 +EVENT_SYSTEM_SCROLLINGEND: Final = 19 +EVENT_SYSTEM_SWITCHSTART: Final = 20 +EVENT_SYSTEM_SWITCHEND: Final = 21 +EVENT_SYSTEM_MINIMIZESTART: Final = 22 +EVENT_SYSTEM_MINIMIZEEND: Final = 23 +EVENT_OBJECT_CREATE: Final = 32768 +EVENT_OBJECT_DESTROY: Final = 32769 +EVENT_OBJECT_SHOW: Final = 32770 +EVENT_OBJECT_HIDE: Final = 32771 +EVENT_OBJECT_REORDER: Final = 32772 +EVENT_OBJECT_FOCUS: Final = 32773 +EVENT_OBJECT_SELECTION: Final = 32774 +EVENT_OBJECT_SELECTIONADD: Final = 32775 +EVENT_OBJECT_SELECTIONREMOVE: Final = 32776 +EVENT_OBJECT_SELECTIONWITHIN: Final = 32777 +EVENT_OBJECT_STATECHANGE: Final = 32778 +EVENT_OBJECT_LOCATIONCHANGE: Final = 32779 +EVENT_OBJECT_NAMECHANGE: Final = 32780 +EVENT_OBJECT_DESCRIPTIONCHANGE: Final = 32781 +EVENT_OBJECT_VALUECHANGE: Final = 32782 +EVENT_OBJECT_PARENTCHANGE: Final = 32783 +EVENT_OBJECT_HELPCHANGE: Final = 32784 +EVENT_OBJECT_DEFACTIONCHANGE: Final = 32785 +EVENT_OBJECT_ACCELERATORCHANGE: Final = 32786 +SOUND_SYSTEM_STARTUP: Final = 1 +SOUND_SYSTEM_SHUTDOWN: Final = 2 +SOUND_SYSTEM_BEEP: Final = 3 +SOUND_SYSTEM_ERROR: Final = 4 +SOUND_SYSTEM_QUESTION: Final = 5 +SOUND_SYSTEM_WARNING: Final = 6 +SOUND_SYSTEM_INFORMATION: Final = 7 +SOUND_SYSTEM_MAXIMIZE: Final = 8 +SOUND_SYSTEM_MINIMIZE: Final = 9 +SOUND_SYSTEM_RESTOREUP: Final = 10 +SOUND_SYSTEM_RESTOREDOWN: Final = 11 +SOUND_SYSTEM_APPSTART: Final = 12 +SOUND_SYSTEM_FAULT: Final = 13 +SOUND_SYSTEM_APPEND: Final = 14 +SOUND_SYSTEM_MENUCOMMAND: Final = 15 +SOUND_SYSTEM_MENUPOPUP: Final = 16 +CSOUND_SYSTEM: Final = 16 +ALERT_SYSTEM_INFORMATIONAL: Final = 1 +ALERT_SYSTEM_WARNING: Final = 2 +ALERT_SYSTEM_ERROR: Final = 3 +ALERT_SYSTEM_QUERY: Final = 4 +ALERT_SYSTEM_CRITICAL: Final = 5 +CALERT_SYSTEM: Final = 6 +WINEVENT_OUTOFCONTEXT: Final = 0 +WINEVENT_SKIPOWNTHREAD: Final = 1 +WINEVENT_SKIPOWNPROCESS: Final = 2 +WINEVENT_INCONTEXT: Final = 4 +GUI_CARETBLINKING: Final = 1 +GUI_INMOVESIZE: Final = 2 +GUI_INMENUMODE: Final = 4 +GUI_SYSTEMMENUMODE: Final = 8 +GUI_POPUPMENUMODE: Final = 16 +STATE_SYSTEM_UNAVAILABLE: Final = 1 +STATE_SYSTEM_SELECTED: Final = 2 +STATE_SYSTEM_FOCUSED: Final = 4 +STATE_SYSTEM_PRESSED: Final = 8 +STATE_SYSTEM_CHECKED: Final = 16 +STATE_SYSTEM_MIXED: Final = 32 +STATE_SYSTEM_READONLY: Final = 64 +STATE_SYSTEM_HOTTRACKED: Final = 128 +STATE_SYSTEM_DEFAULT: Final = 256 +STATE_SYSTEM_EXPANDED: Final = 512 +STATE_SYSTEM_COLLAPSED: Final = 1024 +STATE_SYSTEM_BUSY: Final = 2048 +STATE_SYSTEM_FLOATING: Final = 4096 +STATE_SYSTEM_MARQUEED: Final = 8192 +STATE_SYSTEM_ANIMATED: Final = 16384 +STATE_SYSTEM_INVISIBLE: Final = 32768 +STATE_SYSTEM_OFFSCREEN: Final = 65536 +STATE_SYSTEM_SIZEABLE: Final = 131072 +STATE_SYSTEM_MOVEABLE: Final = 262144 +STATE_SYSTEM_SELFVOICING: Final = 524288 +STATE_SYSTEM_FOCUSABLE: Final = 1048576 +STATE_SYSTEM_SELECTABLE: Final = 2097152 +STATE_SYSTEM_LINKED: Final = 4194304 +STATE_SYSTEM_TRAVERSED: Final = 8388608 +STATE_SYSTEM_MULTISELECTABLE: Final = 16777216 +STATE_SYSTEM_EXTSELECTABLE: Final = 33554432 +STATE_SYSTEM_ALERT_LOW: Final = 67108864 +STATE_SYSTEM_ALERT_MEDIUM: Final = 134217728 +STATE_SYSTEM_ALERT_HIGH: Final = 268435456 +STATE_SYSTEM_VALID: Final = 536870911 +CCHILDREN_TITLEBAR: Final = 5 +CCHILDREN_SCROLLBAR: Final = 5 +CURSOR_SHOWING: Final = 1 +WS_ACTIVECAPTION: Final = 1 +GA_MIC: Final = 1 +GA_PARENT: Final = 1 +GA_ROOT: Final = 2 +GA_ROOTOWNER: Final = 3 +GA_MAC: Final = 4 + +BF_LEFT: Final = 1 +BF_TOP: Final = 2 +BF_RIGHT: Final = 4 +BF_BOTTOM: Final = 8 +BF_TOPLEFT: Final[int] +BF_TOPRIGHT: Final[int] +BF_BOTTOMLEFT: Final[int] +BF_BOTTOMRIGHT: Final[int] +BF_RECT: Final[int] +BF_DIAGONAL: Final = 16 +BF_DIAGONAL_ENDTOPRIGHT: Final[int] +BF_DIAGONAL_ENDTOPLEFT: Final[int] +BF_DIAGONAL_ENDBOTTOMLEFT: Final[int] +BF_DIAGONAL_ENDBOTTOMRIGHT: Final[int] +BF_MIDDLE: Final = 2048 +BF_SOFT: Final = 4096 +BF_ADJUST: Final = 8192 +BF_FLAT: Final = 16384 +BF_MONO: Final = 32768 +DFC_CAPTION: Final = 1 +DFC_MENU: Final = 2 +DFC_SCROLL: Final = 3 +DFC_BUTTON: Final = 4 +DFC_POPUPMENU: Final = 5 +DFCS_CAPTIONCLOSE: Final = 0 +DFCS_CAPTIONMIN: Final = 1 +DFCS_CAPTIONMAX: Final = 2 +DFCS_CAPTIONRESTORE: Final = 3 +DFCS_CAPTIONHELP: Final = 4 +DFCS_MENUARROW: Final = 0 +DFCS_MENUCHECK: Final = 1 +DFCS_MENUBULLET: Final = 2 +DFCS_MENUARROWRIGHT: Final = 4 +DFCS_SCROLLUP: Final = 0 +DFCS_SCROLLDOWN: Final = 1 +DFCS_SCROLLLEFT: Final = 2 +DFCS_SCROLLRIGHT: Final = 3 +DFCS_SCROLLCOMBOBOX: Final = 5 +DFCS_SCROLLSIZEGRIP: Final = 8 +DFCS_SCROLLSIZEGRIPRIGHT: Final = 16 +DFCS_BUTTONCHECK: Final = 0 +DFCS_BUTTONRADIOIMAGE: Final = 1 +DFCS_BUTTONRADIOMASK: Final = 2 +DFCS_BUTTONRADIO: Final = 4 +DFCS_BUTTON3STATE: Final = 8 +DFCS_BUTTONPUSH: Final = 16 +DFCS_INACTIVE: Final = 256 +DFCS_PUSHED: Final = 512 +DFCS_CHECKED: Final = 1024 +DFCS_TRANSPARENT: Final = 2048 +DFCS_HOT: Final = 4096 +DFCS_ADJUSTRECT: Final = 8192 +DFCS_FLAT: Final = 16384 +DFCS_MONO: Final = 32768 +DC_ACTIVE: Final = 1 +DC_SMALLCAP: Final = 2 +DC_ICON: Final = 4 +DC_TEXT: Final = 8 +DC_INBUTTON: Final = 16 +DC_GRADIENT: Final = 32 +IDANI_OPEN: Final = 1 +IDANI_CLOSE: Final = 2 +IDANI_CAPTION: Final = 3 +CF_TEXT: Final = 1 +CF_BITMAP: Final = 2 +CF_METAFILEPICT: Final = 3 +CF_SYLK: Final = 4 +CF_DIF: Final = 5 +CF_TIFF: Final = 6 +CF_OEMTEXT: Final = 7 +CF_DIB: Final = 8 +CF_PALETTE: Final = 9 +CF_PENDATA: Final = 10 +CF_RIFF: Final = 11 +CF_WAVE: Final = 12 +CF_UNICODETEXT: Final = 13 +CF_ENHMETAFILE: Final = 14 +CF_HDROP: Final = 15 +CF_LOCALE: Final = 16 +CF_DIBV5: Final = 17 +CF_MAX: Final = 18 +CF_OWNERDISPLAY: Final = 128 +CF_DSPTEXT: Final = 129 +CF_DSPBITMAP: Final = 130 +CF_DSPMETAFILEPICT: Final = 131 +CF_DSPENHMETAFILE: Final = 142 +CF_PRIVATEFIRST: Final = 512 +CF_PRIVATELAST: Final = 767 +CF_GDIOBJFIRST: Final = 768 +CF_GDIOBJLAST: Final = 1023 +FVIRTKEY: Final = 1 +FNOINVERT: Final = 2 +FSHIFT: Final = 4 +FCONTROL: Final = 8 +FALT: Final = 16 +WPF_SETMINPOSITION: Final = 1 +WPF_RESTORETOMAXIMIZED: Final = 2 +ODT_MENU: Final = 1 +ODT_LISTBOX: Final = 2 +ODT_COMBOBOX: Final = 3 +ODT_BUTTON: Final = 4 +ODT_STATIC: Final = 5 +ODA_DRAWENTIRE: Final = 1 +ODA_SELECT: Final = 2 +ODA_FOCUS: Final = 4 +ODS_SELECTED: Final = 1 +ODS_GRAYED: Final = 2 +ODS_DISABLED: Final = 4 +ODS_CHECKED: Final = 8 +ODS_FOCUS: Final = 16 +ODS_DEFAULT: Final = 32 +ODS_COMBOBOXEDIT: Final = 4096 +ODS_HOTLIGHT: Final = 64 +ODS_INACTIVE: Final = 128 +PM_NOREMOVE: Final = 0 +PM_REMOVE: Final = 1 +PM_NOYIELD: Final = 2 +MOD_ALT: Final = 1 +MOD_CONTROL: Final = 2 +MOD_SHIFT: Final = 4 +MOD_WIN: Final = 8 +MOD_NOREPEAT: Final = 16384 +IDHOT_SNAPWINDOW: Final = -1 +IDHOT_SNAPDESKTOP: Final = -2 + +ENDSESSION_LOGOFF: Final = -2147483648 +EWX_LOGOFF: Final = 0 +EWX_SHUTDOWN: Final = 1 +EWX_REBOOT: Final = 2 +EWX_FORCE: Final = 4 +EWX_POWEROFF: Final = 8 +EWX_FORCEIFHUNG: Final = 16 +BSM_ALLDESKTOPS: Final = 16 +BROADCAST_QUERY_DENY: Final = 1112363332 + +DBWF_LPARAMPOINTER: Final = 32768 + +SWP_NOSIZE: Final = 1 +SWP_NOMOVE: Final = 2 +SWP_NOZORDER: Final = 4 +SWP_NOREDRAW: Final = 8 +SWP_NOACTIVATE: Final = 16 +SWP_FRAMECHANGED: Final = 32 +SWP_SHOWWINDOW: Final = 64 +SWP_HIDEWINDOW: Final = 128 +SWP_NOCOPYBITS: Final = 256 +SWP_NOOWNERZORDER: Final = 512 +SWP_NOSENDCHANGING: Final = 1024 +SWP_DRAWFRAME: Final = SWP_FRAMECHANGED +SWP_NOREPOSITION: Final = SWP_NOOWNERZORDER +SWP_DEFERERASE: Final = 8192 +SWP_ASYNCWINDOWPOS: Final = 16384 + +DLGWINDOWEXTRA: Final = 30 + +KEYEVENTF_EXTENDEDKEY: Final = 1 +KEYEVENTF_KEYUP: Final = 2 +KEYEVENTF_UNICODE: Final = 4 +KEYEVENTF_SCANCODE: Final = 8 +MOUSEEVENTF_MOVE: Final = 1 +MOUSEEVENTF_LEFTDOWN: Final = 2 +MOUSEEVENTF_LEFTUP: Final = 4 +MOUSEEVENTF_RIGHTDOWN: Final = 8 +MOUSEEVENTF_RIGHTUP: Final = 16 +MOUSEEVENTF_MIDDLEDOWN: Final = 32 +MOUSEEVENTF_MIDDLEUP: Final = 64 +MOUSEEVENTF_XDOWN: Final = 128 +MOUSEEVENTF_XUP: Final = 256 +MOUSEEVENTF_WHEEL: Final = 2048 +MOUSEEVENTF_HWHEEL: Final = 4096 +MOUSEEVENTF_MOVE_NOCOALESCE: Final = 8192 +MOUSEEVENTF_VIRTUALDESK: Final = 16384 +MOUSEEVENTF_ABSOLUTE: Final = 32768 +INPUT_MOUSE: Final = 0 +INPUT_KEYBOARD: Final = 1 +INPUT_HARDWARE: Final = 2 +MWMO_WAITALL: Final = 1 +MWMO_ALERTABLE: Final = 2 +MWMO_INPUTAVAILABLE: Final = 4 +QS_KEY: Final = 1 +QS_MOUSEMOVE: Final = 2 +QS_MOUSEBUTTON: Final = 4 +QS_POSTMESSAGE: Final = 8 +QS_TIMER: Final = 16 +QS_PAINT: Final = 32 +QS_SENDMESSAGE: Final = 64 +QS_HOTKEY: Final = 128 +QS_MOUSE: Final[int] +QS_INPUT: Final[int] +QS_ALLEVENTS: Final[int] +QS_ALLINPUT: Final[int] + +IMN_CLOSESTATUSWINDOW: Final = 1 +IMN_OPENSTATUSWINDOW: Final = 2 +IMN_CHANGECANDIDATE: Final = 3 +IMN_CLOSECANDIDATE: Final = 4 +IMN_OPENCANDIDATE: Final = 5 +IMN_SETCONVERSIONMODE: Final = 6 +IMN_SETSENTENCEMODE: Final = 7 +IMN_SETOPENSTATUS: Final = 8 +IMN_SETCANDIDATEPOS: Final = 9 +IMN_SETCOMPOSITIONFONT: Final = 10 +IMN_SETCOMPOSITIONWINDOW: Final = 11 +IMN_SETSTATUSWINDOWPOS: Final = 12 +IMN_GUIDELINE: Final = 13 +IMN_PRIVATE: Final = 14 + +HELP_CONTEXT: Final = 1 +HELP_QUIT: Final = 2 +HELP_INDEX: Final = 3 +HELP_CONTENTS: Final = 3 +HELP_HELPONHELP: Final = 4 +HELP_SETINDEX: Final = 5 +HELP_SETCONTENTS: Final = 5 +HELP_CONTEXTPOPUP: Final = 8 +HELP_FORCEFILE: Final = 9 +HELP_KEY: Final = 257 +HELP_COMMAND: Final = 258 +HELP_PARTIALKEY: Final = 261 +HELP_MULTIKEY: Final = 513 +HELP_SETWINPOS: Final = 515 +HELP_CONTEXTMENU: Final = 10 +HELP_FINDER: Final = 11 +HELP_WM_HELP: Final = 12 +HELP_SETPOPUP_POS: Final = 13 +HELP_TCARD: Final = 32768 +HELP_TCARD_DATA: Final = 16 +HELP_TCARD_OTHER_CALLER: Final = 17 +IDH_NO_HELP: Final = 28440 +IDH_MISSING_CONTEXT: Final = 28441 +IDH_GENERIC_HELP_BUTTON: Final = 28442 +IDH_OK: Final = 28443 +IDH_CANCEL: Final = 28444 +IDH_HELP: Final = 28445 +GR_GDIOBJECTS: Final = 0 +GR_USEROBJECTS: Final = 1 + +SRCCOPY: Final = 13369376 +SRCPAINT: Final = 15597702 +SRCAND: Final = 8913094 +SRCINVERT: Final = 6684742 +SRCERASE: Final = 4457256 +NOTSRCCOPY: Final = 3342344 +NOTSRCERASE: Final = 1114278 +MERGECOPY: Final = 12583114 +MERGEPAINT: Final = 12255782 +PATCOPY: Final = 15728673 +PATPAINT: Final = 16452105 +PATINVERT: Final = 5898313 +DSTINVERT: Final = 5570569 +BLACKNESS: Final = 66 +WHITENESS: Final = 16711778 + +R2_BLACK: Final = 1 +R2_NOTMERGEPEN: Final = 2 +R2_MASKNOTPEN: Final = 3 +R2_NOTCOPYPEN: Final = 4 +R2_MASKPENNOT: Final = 5 +R2_NOT: Final = 6 +R2_XORPEN: Final = 7 +R2_NOTMASKPEN: Final = 8 +R2_MASKPEN: Final = 9 +R2_NOTXORPEN: Final = 10 +R2_NOP: Final = 11 +R2_MERGENOTPEN: Final = 12 +R2_COPYPEN: Final = 13 +R2_MERGEPENNOT: Final = 14 +R2_MERGEPEN: Final = 15 +R2_WHITE: Final = 16 +R2_LAST: Final = 16 +GDI_ERROR: Final = -1 +ERROR: Final = 0 +NULLREGION: Final = 1 +SIMPLEREGION: Final = 2 +COMPLEXREGION: Final = 3 +RGN_ERROR: Final = ERROR +RGN_AND: Final = 1 +RGN_OR: Final = 2 +RGN_XOR: Final = 3 +RGN_DIFF: Final = 4 +RGN_COPY: Final = 5 +RGN_MIN: Final = RGN_AND +RGN_MAX: Final = RGN_COPY + +BLACKONWHITE: Final = 1 +WHITEONBLACK: Final = 2 +COLORONCOLOR: Final = 3 +HALFTONE: Final = 4 +MAXSTRETCHBLTMODE: Final = 4 +STRETCH_ANDSCANS: Final = BLACKONWHITE +STRETCH_ORSCANS: Final = WHITEONBLACK +STRETCH_DELETESCANS: Final = COLORONCOLOR +STRETCH_HALFTONE: Final = HALFTONE + +ALTERNATE: Final = 1 +WINDING: Final = 2 +POLYFILL_LAST: Final = 2 + +LAYOUT_RTL: Final = 1 +LAYOUT_BTT: Final = 2 +LAYOUT_VBH: Final = 4 +LAYOUT_ORIENTATIONMASK: Final[int] +LAYOUT_BITMAPORIENTATIONPRESERVED: Final = 8 + +TA_NOUPDATECP: Final = 0 +TA_UPDATECP: Final = 1 +TA_LEFT: Final = 0 +TA_RIGHT: Final = 2 +TA_CENTER: Final = 6 +TA_TOP: Final = 0 +TA_BOTTOM: Final = 8 +TA_BASELINE: Final = 24 +TA_MASK: Final[int] +VTA_BASELINE: Final = TA_BASELINE +VTA_LEFT: Final = TA_BOTTOM +VTA_RIGHT: Final = TA_TOP +VTA_CENTER: Final = TA_CENTER +VTA_BOTTOM: Final = TA_RIGHT +VTA_TOP: Final = TA_LEFT +ETO_GRAYED: Final = 1 +ETO_OPAQUE: Final = 2 +ETO_CLIPPED: Final = 4 +ASPECT_FILTERING: Final = 1 +DCB_RESET: Final = 1 +DCB_ACCUMULATE: Final = 2 +DCB_DIRTY: Final = DCB_ACCUMULATE +DCB_SET: Final[int] +DCB_ENABLE: Final = 4 +DCB_DISABLE: Final = 8 +META_SETBKCOLOR: Final = 513 +META_SETBKMODE: Final = 258 +META_SETMAPMODE: Final = 259 +META_SETROP2: Final = 260 +META_SETRELABS: Final = 261 +META_SETPOLYFILLMODE: Final = 262 +META_SETSTRETCHBLTMODE: Final = 263 +META_SETTEXTCHAREXTRA: Final = 264 +META_SETTEXTCOLOR: Final = 521 +META_SETTEXTJUSTIFICATION: Final = 522 +META_SETWINDOWORG: Final = 523 +META_SETWINDOWEXT: Final = 524 +META_SETVIEWPORTORG: Final = 525 +META_SETVIEWPORTEXT: Final = 526 +META_OFFSETWINDOWORG: Final = 527 +META_SCALEWINDOWEXT: Final = 1040 +META_OFFSETVIEWPORTORG: Final = 529 +META_SCALEVIEWPORTEXT: Final = 1042 +META_LINETO: Final = 531 +META_MOVETO: Final = 532 +META_EXCLUDECLIPRECT: Final = 1045 +META_INTERSECTCLIPRECT: Final = 1046 +META_ARC: Final = 2071 +META_ELLIPSE: Final = 1048 +META_FLOODFILL: Final = 1049 +META_PIE: Final = 2074 +META_RECTANGLE: Final = 1051 +META_ROUNDRECT: Final = 1564 +META_PATBLT: Final = 1565 +META_SAVEDC: Final = 30 +META_SETPIXEL: Final = 1055 +META_OFFSETCLIPRGN: Final = 544 +META_TEXTOUT: Final = 1313 +META_BITBLT: Final = 2338 +META_STRETCHBLT: Final = 2851 +META_POLYGON: Final = 804 +META_POLYLINE: Final = 805 +META_ESCAPE: Final = 1574 +META_RESTOREDC: Final = 295 +META_FILLREGION: Final = 552 +META_FRAMEREGION: Final = 1065 +META_INVERTREGION: Final = 298 +META_PAINTREGION: Final = 299 +META_SELECTCLIPREGION: Final = 300 +META_SELECTOBJECT: Final = 301 +META_SETTEXTALIGN: Final = 302 +META_CHORD: Final = 2096 +META_SETMAPPERFLAGS: Final = 561 +META_EXTTEXTOUT: Final = 2610 +META_SETDIBTODEV: Final = 3379 +META_SELECTPALETTE: Final = 564 +META_REALIZEPALETTE: Final = 53 +META_ANIMATEPALETTE: Final = 1078 +META_SETPALENTRIES: Final = 55 +META_POLYPOLYGON: Final = 1336 +META_RESIZEPALETTE: Final = 313 +META_DIBBITBLT: Final = 2368 +META_DIBSTRETCHBLT: Final = 2881 +META_DIBCREATEPATTERNBRUSH: Final = 322 +META_STRETCHDIB: Final = 3907 +META_EXTFLOODFILL: Final = 1352 +META_DELETEOBJECT: Final = 496 +META_CREATEPALETTE: Final = 247 +META_CREATEPATTERNBRUSH: Final = 505 +META_CREATEPENINDIRECT: Final = 762 +META_CREATEFONTINDIRECT: Final = 763 +META_CREATEBRUSHINDIRECT: Final = 764 +META_CREATEREGION: Final = 1791 +FILE_BEGIN: Final = 0 +FILE_CURRENT: Final = 1 +FILE_END: Final = 2 +FILE_FLAG_WRITE_THROUGH: Final = -2147483648 +FILE_FLAG_OVERLAPPED: Final = 1073741824 +FILE_FLAG_NO_BUFFERING: Final = 536870912 +FILE_FLAG_RANDOM_ACCESS: Final = 268435456 +FILE_FLAG_SEQUENTIAL_SCAN: Final = 134217728 +FILE_FLAG_DELETE_ON_CLOSE: Final = 67108864 +FILE_FLAG_BACKUP_SEMANTICS: Final = 33554432 +FILE_FLAG_POSIX_SEMANTICS: Final = 16777216 +CREATE_NEW: Final = 1 +CREATE_ALWAYS: Final = 2 +OPEN_EXISTING: Final = 3 +OPEN_ALWAYS: Final = 4 +TRUNCATE_EXISTING: Final = 5 +PIPE_ACCESS_INBOUND: Final = 1 +PIPE_ACCESS_OUTBOUND: Final = 2 +PIPE_ACCESS_DUPLEX: Final = 3 +PIPE_CLIENT_END: Final = 0 +PIPE_SERVER_END: Final = 1 +PIPE_WAIT: Final = 0 +PIPE_NOWAIT: Final = 1 +PIPE_READMODE_BYTE: Final = 0 +PIPE_READMODE_MESSAGE: Final = 2 +PIPE_TYPE_BYTE: Final = 0 +PIPE_TYPE_MESSAGE: Final = 4 +PIPE_UNLIMITED_INSTANCES: Final = 255 +SECURITY_CONTEXT_TRACKING: Final = 262144 +SECURITY_EFFECTIVE_ONLY: Final = 524288 +SECURITY_SQOS_PRESENT: Final = 1048576 +SECURITY_VALID_SQOS_FLAGS: Final = 2031616 +DTR_CONTROL_DISABLE: Final = 0 +DTR_CONTROL_ENABLE: Final = 1 +DTR_CONTROL_HANDSHAKE: Final = 2 +RTS_CONTROL_DISABLE: Final = 0 +RTS_CONTROL_ENABLE: Final = 1 +RTS_CONTROL_HANDSHAKE: Final = 2 +RTS_CONTROL_TOGGLE: Final = 3 +GMEM_FIXED: Final = 0 +GMEM_MOVEABLE: Final = 2 +GMEM_NOCOMPACT: Final = 16 +GMEM_NODISCARD: Final = 32 +GMEM_ZEROINIT: Final = 64 +GMEM_MODIFY: Final = 128 +GMEM_DISCARDABLE: Final = 256 +GMEM_NOT_BANKED: Final = 4096 +GMEM_SHARE: Final = 8192 +GMEM_DDESHARE: Final = 8192 +GMEM_NOTIFY: Final = 16384 +GMEM_LOWER: Final = GMEM_NOT_BANKED +GMEM_VALID_FLAGS: Final = 32626 +GMEM_INVALID_HANDLE: Final = 32768 +GHND: Final[int] +GPTR: Final[int] +GMEM_DISCARDED: Final = 16384 +GMEM_LOCKCOUNT: Final = 255 +LMEM_FIXED: Final = 0 +LMEM_MOVEABLE: Final = 2 +LMEM_NOCOMPACT: Final = 16 +LMEM_NODISCARD: Final = 32 +LMEM_ZEROINIT: Final = 64 +LMEM_MODIFY: Final = 128 +LMEM_DISCARDABLE: Final = 3840 +LMEM_VALID_FLAGS: Final = 3954 +LMEM_INVALID_HANDLE: Final = 32768 +LHND: Final[int] +LPTR: Final[int] +NONZEROLHND: Final = LMEM_MOVEABLE +NONZEROLPTR: Final = LMEM_FIXED +LMEM_DISCARDED: Final = 16384 +LMEM_LOCKCOUNT: Final = 255 +DEBUG_PROCESS: Final = 1 +DEBUG_ONLY_THIS_PROCESS: Final = 2 +CREATE_SUSPENDED: Final = 4 +DETACHED_PROCESS: Final = 8 +CREATE_NEW_CONSOLE: Final = 16 +NORMAL_PRIORITY_CLASS: Final = 32 +IDLE_PRIORITY_CLASS: Final = 64 +HIGH_PRIORITY_CLASS: Final = 128 +REALTIME_PRIORITY_CLASS: Final = 256 +CREATE_NEW_PROCESS_GROUP: Final = 512 +CREATE_UNICODE_ENVIRONMENT: Final = 1024 +CREATE_SEPARATE_WOW_VDM: Final = 2048 +CREATE_SHARED_WOW_VDM: Final = 4096 +CREATE_DEFAULT_ERROR_MODE: Final = 67108864 +CREATE_NO_WINDOW: Final = 134217728 +PROFILE_USER: Final = 268435456 +PROFILE_KERNEL: Final = 536870912 +PROFILE_SERVER: Final = 1073741824 +THREAD_BASE_PRIORITY_LOWRT: Final = 15 +THREAD_BASE_PRIORITY_MAX: Final = 2 +THREAD_BASE_PRIORITY_MIN: Final = -2 +THREAD_BASE_PRIORITY_IDLE: Final = -15 +THREAD_PRIORITY_LOWEST: Final = THREAD_BASE_PRIORITY_MIN +THREAD_PRIORITY_BELOW_NORMAL: Final[int] +THREAD_PRIORITY_HIGHEST: Final = THREAD_BASE_PRIORITY_MAX +THREAD_PRIORITY_ABOVE_NORMAL: Final[int] +THREAD_PRIORITY_ERROR_RETURN: Final = MAXLONG +THREAD_PRIORITY_TIME_CRITICAL: Final = THREAD_BASE_PRIORITY_LOWRT +THREAD_PRIORITY_IDLE: Final = THREAD_BASE_PRIORITY_IDLE +THREAD_PRIORITY_NORMAL: Final = 0 +THREAD_MODE_BACKGROUND_BEGIN: Final = 0x00010000 +THREAD_MODE_BACKGROUND_END: Final = 0x00020000 + +EXCEPTION_DEBUG_EVENT: Final = 1 +CREATE_THREAD_DEBUG_EVENT: Final = 2 +CREATE_PROCESS_DEBUG_EVENT: Final = 3 +EXIT_THREAD_DEBUG_EVENT: Final = 4 +EXIT_PROCESS_DEBUG_EVENT: Final = 5 +LOAD_DLL_DEBUG_EVENT: Final = 6 +UNLOAD_DLL_DEBUG_EVENT: Final = 7 +OUTPUT_DEBUG_STRING_EVENT: Final = 8 +RIP_EVENT: Final = 9 +DRIVE_UNKNOWN: Final = 0 +DRIVE_NO_ROOT_DIR: Final = 1 +DRIVE_REMOVABLE: Final = 2 +DRIVE_FIXED: Final = 3 +DRIVE_REMOTE: Final = 4 +DRIVE_CDROM: Final = 5 +DRIVE_RAMDISK: Final = 6 +FILE_TYPE_UNKNOWN: Final = 0 +FILE_TYPE_DISK: Final = 1 +FILE_TYPE_CHAR: Final = 2 +FILE_TYPE_PIPE: Final = 3 +FILE_TYPE_REMOTE: Final = 32768 +NOPARITY: Final = 0 +ODDPARITY: Final = 1 +EVENPARITY: Final = 2 +MARKPARITY: Final = 3 +SPACEPARITY: Final = 4 +ONESTOPBIT: Final = 0 +ONE5STOPBITS: Final = 1 +TWOSTOPBITS: Final = 2 +CBR_110: Final = 110 +CBR_300: Final = 300 +CBR_600: Final = 600 +CBR_1200: Final = 1200 +CBR_2400: Final = 2400 +CBR_4800: Final = 4800 +CBR_9600: Final = 9600 +CBR_14400: Final = 14400 +CBR_19200: Final = 19200 +CBR_38400: Final = 38400 +CBR_56000: Final = 56000 +CBR_57600: Final = 57600 +CBR_115200: Final = 115200 +CBR_128000: Final = 128000 +CBR_256000: Final = 256000 +S_QUEUEEMPTY: Final = 0 +S_THRESHOLD: Final = 1 +S_ALLTHRESHOLD: Final = 2 +S_NORMAL: Final = 0 +S_LEGATO: Final = 1 +S_STACCATO: Final = 2 +NMPWAIT_WAIT_FOREVER: Final = -1 +NMPWAIT_NOWAIT: Final = 1 +NMPWAIT_USE_DEFAULT_WAIT: Final = 0 +OF_READ: Final = 0 +OF_WRITE: Final = 1 +OF_READWRITE: Final = 2 +OF_SHARE_COMPAT: Final = 0 +OF_SHARE_EXCLUSIVE: Final = 16 +OF_SHARE_DENY_WRITE: Final = 32 +OF_SHARE_DENY_READ: Final = 48 +OF_SHARE_DENY_NONE: Final = 64 +OF_PARSE: Final = 256 +OF_DELETE: Final = 512 +OF_VERIFY: Final = 1024 +OF_CANCEL: Final = 2048 +OF_CREATE: Final = 4096 +OF_PROMPT: Final = 8192 +OF_EXIST: Final = 16384 +OF_REOPEN: Final = 32768 +OFS_MAXPATHNAME: Final = 128 +MAXINTATOM: Final = 49152 + +PROCESS_HEAP_REGION: Final = 1 +PROCESS_HEAP_UNCOMMITTED_RANGE: Final = 2 +PROCESS_HEAP_ENTRY_BUSY: Final = 4 +PROCESS_HEAP_ENTRY_MOVEABLE: Final = 16 +PROCESS_HEAP_ENTRY_DDESHARE: Final = 32 +SCS_32BIT_BINARY: Final = 0 +SCS_DOS_BINARY: Final = 1 +SCS_WOW_BINARY: Final = 2 +SCS_PIF_BINARY: Final = 3 +SCS_POSIX_BINARY: Final = 4 +SCS_OS216_BINARY: Final = 5 +SEM_FAILCRITICALERRORS: Final = 1 +SEM_NOGPFAULTERRORBOX: Final = 2 +SEM_NOALIGNMENTFAULTEXCEPT: Final = 4 +SEM_NOOPENFILEERRORBOX: Final = 32768 +LOCKFILE_FAIL_IMMEDIATELY: Final = 1 +LOCKFILE_EXCLUSIVE_LOCK: Final = 2 +HANDLE_FLAG_INHERIT: Final = 1 +HANDLE_FLAG_PROTECT_FROM_CLOSE: Final = 2 +HINSTANCE_ERROR: Final = 32 +GET_TAPE_MEDIA_INFORMATION: Final = 0 +GET_TAPE_DRIVE_INFORMATION: Final = 1 +SET_TAPE_MEDIA_INFORMATION: Final = 0 +SET_TAPE_DRIVE_INFORMATION: Final = 1 +FORMAT_MESSAGE_ALLOCATE_BUFFER: Final = 256 +FORMAT_MESSAGE_IGNORE_INSERTS: Final = 512 +FORMAT_MESSAGE_FROM_STRING: Final = 1024 +FORMAT_MESSAGE_FROM_HMODULE: Final = 2048 +FORMAT_MESSAGE_FROM_SYSTEM: Final = 4096 +FORMAT_MESSAGE_ARGUMENT_ARRAY: Final = 8192 +FORMAT_MESSAGE_MAX_WIDTH_MASK: Final = 255 +BACKUP_INVALID: Final = 0 +BACKUP_DATA: Final = 1 +BACKUP_EA_DATA: Final = 2 +BACKUP_SECURITY_DATA: Final = 3 +BACKUP_ALTERNATE_DATA: Final = 4 +BACKUP_LINK: Final = 5 +BACKUP_PROPERTY_DATA: Final = 6 +BACKUP_OBJECT_ID: Final = 7 +BACKUP_REPARSE_DATA: Final = 8 +BACKUP_SPARSE_BLOCK: Final = 9 + +STREAM_NORMAL_ATTRIBUTE: Final = 0 +STREAM_MODIFIED_WHEN_READ: Final = 1 +STREAM_CONTAINS_SECURITY: Final = 2 +STREAM_CONTAINS_PROPERTIES: Final = 4 +STARTF_USESHOWWINDOW: Final = 1 +STARTF_USESIZE: Final = 2 +STARTF_USEPOSITION: Final = 4 +STARTF_USECOUNTCHARS: Final = 8 +STARTF_USEFILLATTRIBUTE: Final = 16 +STARTF_FORCEONFEEDBACK: Final = 64 +STARTF_FORCEOFFFEEDBACK: Final = 128 +STARTF_USESTDHANDLES: Final = 256 +STARTF_USEHOTKEY: Final = 512 +SHUTDOWN_NORETRY: Final = 1 +DONT_RESOLVE_DLL_REFERENCES: Final = 1 +LOAD_LIBRARY_AS_DATAFILE: Final = 2 +LOAD_WITH_ALTERED_SEARCH_PATH: Final = 8 +DDD_RAW_TARGET_PATH: Final = 1 +DDD_REMOVE_DEFINITION: Final = 2 +DDD_EXACT_MATCH_ON_REMOVE: Final = 4 +MOVEFILE_REPLACE_EXISTING: Final = 1 +MOVEFILE_COPY_ALLOWED: Final = 2 +MOVEFILE_DELAY_UNTIL_REBOOT: Final = 4 +MAX_COMPUTERNAME_LENGTH: Final = 15 +LOGON32_LOGON_INTERACTIVE: Final = 2 +LOGON32_LOGON_NETWORK: Final = 3 +LOGON32_LOGON_BATCH: Final = 4 +LOGON32_LOGON_SERVICE: Final = 5 +LOGON32_LOGON_UNLOCK: Final = 7 +LOGON32_LOGON_NETWORK_CLEARTEXT: Final = 8 +LOGON32_LOGON_NEW_CREDENTIALS: Final = 9 +LOGON32_PROVIDER_DEFAULT: Final = 0 +LOGON32_PROVIDER_WINNT35: Final = 1 +LOGON32_PROVIDER_WINNT40: Final = 2 +LOGON32_PROVIDER_WINNT50: Final = 3 +VER_PLATFORM_WIN32s: Final = 0 +VER_PLATFORM_WIN32_WINDOWS: Final = 1 +VER_PLATFORM_WIN32_NT: Final = 2 +TC_NORMAL: Final = 0 +TC_HARDERR: Final = 1 +TC_GP_TRAP: Final = 2 +TC_SIGNAL: Final = 3 +AC_LINE_OFFLINE: Final = 0 +AC_LINE_ONLINE: Final = 1 +AC_LINE_BACKUP_POWER: Final = 2 +AC_LINE_UNKNOWN: Final = 255 +BATTERY_FLAG_HIGH: Final = 1 +BATTERY_FLAG_LOW: Final = 2 +BATTERY_FLAG_CRITICAL: Final = 4 +BATTERY_FLAG_CHARGING: Final = 8 +BATTERY_FLAG_NO_BATTERY: Final = 128 +BATTERY_FLAG_UNKNOWN: Final = 255 +BATTERY_PERCENTAGE_UNKNOWN: Final = 255 +BATTERY_LIFE_UNKNOWN: Final = -1 + +cchTextLimitDefault: Final = 32767 +WM_CONTEXTMENU: Final = 123 +WM_PRINTCLIENT: Final = 792 +EN_MSGFILTER: Final = 1792 +EN_REQUESTRESIZE: Final = 1793 +EN_SELCHANGE: Final = 1794 +EN_DROPFILES: Final = 1795 +EN_PROTECTED: Final = 1796 +EN_CORRECTTEXT: Final = 1797 +EN_STOPNOUNDO: Final = 1798 +EN_IMECHANGE: Final = 1799 +EN_SAVECLIPBOARD: Final = 1800 +EN_OLEOPFAILED: Final = 1801 +ENM_NONE: Final = 0 +ENM_CHANGE: Final = 1 +ENM_UPDATE: Final = 2 +ENM_SCROLL: Final = 4 +ENM_KEYEVENTS: Final = 65536 +ENM_MOUSEEVENTS: Final = 131072 +ENM_REQUESTRESIZE: Final = 262144 +ENM_SELCHANGE: Final = 524288 +ENM_DROPFILES: Final = 1048576 +ENM_PROTECTED: Final = 2097152 +ENM_CORRECTTEXT: Final = 4194304 +ENM_IMECHANGE: Final = 8388608 +ES_SAVESEL: Final = 32768 +ES_SUNKEN: Final = 16384 +ES_DISABLENOSCROLL: Final = 8192 +ES_SELECTIONBAR: Final = 16777216 +ES_EX_NOCALLOLEINIT: Final = 16777216 +ES_VERTICAL: Final = 4194304 +ES_NOIME: Final = 524288 +ES_SELFIME: Final = 262144 +ECO_AUTOWORDSELECTION: Final = 1 +ECO_AUTOVSCROLL: Final = 64 +ECO_AUTOHSCROLL: Final = 128 +ECO_NOHIDESEL: Final = 256 +ECO_READONLY: Final = 2048 +ECO_WANTRETURN: Final = 4096 +ECO_SAVESEL: Final = 32768 +ECO_SELECTIONBAR: Final = 16777216 +ECO_VERTICAL: Final = 4194304 +ECOOP_SET: Final = 1 +ECOOP_OR: Final = 2 +ECOOP_AND: Final = 3 +ECOOP_XOR: Final = 4 +WB_CLASSIFY: Final = 3 +WB_MOVEWORDLEFT: Final = 4 +WB_MOVEWORDRIGHT: Final = 5 +WB_LEFTBREAK: Final = 6 +WB_RIGHTBREAK: Final = 7 +WB_MOVEWORDPREV: Final = 4 +WB_MOVEWORDNEXT: Final = 5 +WB_PREVBREAK: Final = 6 +WB_NEXTBREAK: Final = 7 +PC_FOLLOWING: Final = 1 +PC_LEADING: Final = 2 +PC_OVERFLOW: Final = 3 +PC_DELIMITER: Final = 4 +WBF_WORDWRAP: Final = 16 +WBF_WORDBREAK: Final = 32 +WBF_OVERFLOW: Final = 64 +WBF_LEVEL1: Final = 128 +WBF_LEVEL2: Final = 256 +WBF_CUSTOM: Final = 512 +CFM_BOLD: Final = 1 +CFM_ITALIC: Final = 2 +CFM_UNDERLINE: Final = 4 +CFM_STRIKEOUT: Final = 8 +CFM_PROTECTED: Final = 16 +CFM_SIZE: Final = -2147483648 +CFM_COLOR: Final = 1073741824 +CFM_FACE: Final = 536870912 +CFM_OFFSET: Final = 268435456 +CFM_CHARSET: Final = 134217728 +CFE_BOLD: Final = 1 +CFE_ITALIC: Final = 2 +CFE_UNDERLINE: Final = 4 +CFE_STRIKEOUT: Final = 8 +CFE_PROTECTED: Final = 16 +CFE_AUTOCOLOR: Final = 1073741824 +yHeightCharPtsMost: Final = 1638 +SCF_SELECTION: Final = 1 +SCF_WORD: Final = 2 +SF_TEXT: Final = 1 +SF_RTF: Final = 2 +SF_RTFNOOBJS: Final = 3 +SF_TEXTIZED: Final = 4 +SFF_SELECTION: Final = 32768 +SFF_PLAINRTF: Final = 16384 +MAX_TAB_STOPS: Final = 32 +lDefaultTab: Final = 720 +PFM_STARTINDENT: Final = 1 +PFM_RIGHTINDENT: Final = 2 +PFM_OFFSET: Final = 4 +PFM_ALIGNMENT: Final = 8 +PFM_TABSTOPS: Final = 16 +PFM_NUMBERING: Final = 32 +PFM_OFFSETINDENT: Final = -2147483648 +PFN_BULLET: Final = 1 +PFA_LEFT: Final = 1 +PFA_RIGHT: Final = 2 +PFA_CENTER: Final = 3 +WM_NOTIFY: Final = 78 +SEL_EMPTY: Final = 0 +SEL_TEXT: Final = 1 +SEL_OBJECT: Final = 2 +SEL_MULTICHAR: Final = 4 +SEL_MULTIOBJECT: Final = 8 +OLEOP_DOVERB: Final = 1 +CF_RTF: Final = "Rich Text Format" +CF_RTFNOOBJS: Final = "Rich Text Format Without Objects" +CF_RETEXTOBJ: Final = "RichEdit Text and Objects" + +RIGHT_ALT_PRESSED: Final = 1 +LEFT_ALT_PRESSED: Final = 2 +RIGHT_CTRL_PRESSED: Final = 4 +LEFT_CTRL_PRESSED: Final = 8 +SHIFT_PRESSED: Final = 16 +NUMLOCK_ON: Final = 32 +SCROLLLOCK_ON: Final = 64 +CAPSLOCK_ON: Final = 128 +ENHANCED_KEY: Final = 256 +NLS_DBCSCHAR: Final = 65536 +NLS_ALPHANUMERIC: Final = 0 +NLS_KATAKANA: Final = 131072 +NLS_HIRAGANA: Final = 262144 +NLS_ROMAN: Final = 4194304 +NLS_IME_CONVERSION: Final = 8388608 +NLS_IME_DISABLE: Final = 536870912 + +FROM_LEFT_1ST_BUTTON_PRESSED: Final = 1 +RIGHTMOST_BUTTON_PRESSED: Final = 2 +FROM_LEFT_2ND_BUTTON_PRESSED: Final = 4 +FROM_LEFT_3RD_BUTTON_PRESSED: Final = 8 +FROM_LEFT_4TH_BUTTON_PRESSED: Final = 16 + +CTRL_C_EVENT: Final = 0 +CTRL_BREAK_EVENT: Final = 1 +CTRL_CLOSE_EVENT: Final = 2 +CTRL_LOGOFF_EVENT: Final = 5 +CTRL_SHUTDOWN_EVENT: Final = 6 + +MOUSE_MOVED: Final = 1 +DOUBLE_CLICK: Final = 2 +MOUSE_WHEELED: Final = 4 + +PSM_SETCURSEL: Final[int] +PSM_REMOVEPAGE: Final[int] +PSM_ADDPAGE: Final[int] +PSM_CHANGED: Final[int] +PSM_RESTARTWINDOWS: Final[int] +PSM_REBOOTSYSTEM: Final[int] +PSM_CANCELTOCLOSE: Final[int] +PSM_QUERYSIBLINGS: Final[int] +PSM_UNCHANGED: Final[int] +PSM_APPLY: Final[int] +PSM_SETTITLEA: Final[int] +PSM_SETTITLEW: Final[int] +PSM_SETWIZBUTTONS: Final[int] +PSM_PRESSBUTTON: Final[int] +PSM_SETCURSELID: Final[int] +PSM_SETFINISHTEXTA: Final[int] +PSM_SETFINISHTEXTW: Final[int] +PSM_GETTABCONTROL: Final[int] +PSM_ISDIALOGMESSAGE: Final[int] +PSM_GETCURRENTPAGEHWND: Final[int] +PSM_INSERTPAGE: Final[int] +PSM_SETHEADERTITLEA: Final[int] +PSM_SETHEADERTITLEW: Final[int] +PSM_SETHEADERSUBTITLEA: Final[int] +PSM_SETHEADERSUBTITLEW: Final[int] +PSM_HWNDTOINDEX: Final[int] +PSM_INDEXTOHWND: Final[int] +PSM_PAGETOINDEX: Final[int] +PSM_INDEXTOPAGE: Final[int] +PSM_IDTOINDEX: Final[int] +PSM_INDEXTOID: Final[int] +PSM_GETRESULT: Final[int] +PSM_RECALCPAGESIZES: Final[int] + +NameUnknown: Final = 0 +NameFullyQualifiedDN: Final = 1 +NameSamCompatible: Final = 2 +NameDisplay: Final = 3 +NameUniqueId: Final = 6 +NameCanonical: Final = 7 +NameUserPrincipal: Final = 8 +NameCanonicalEx: Final = 9 +NameServicePrincipal: Final = 10 +NameDnsDomain: Final = 12 + +ComputerNameNetBIOS: Final = 0 +ComputerNameDnsHostname: Final = 1 +ComputerNameDnsDomain: Final = 2 +ComputerNameDnsFullyQualified: Final = 3 +ComputerNamePhysicalNetBIOS: Final = 4 +ComputerNamePhysicalDnsHostname: Final = 5 +ComputerNamePhysicalDnsDomain: Final = 6 +ComputerNamePhysicalDnsFullyQualified: Final = 7 + +LWA_COLORKEY: Final = 0x00000001 +LWA_ALPHA: Final = 0x00000002 +ULW_COLORKEY: Final = 0x00000001 +ULW_ALPHA: Final = 0x00000002 +ULW_OPAQUE: Final = 0x00000004 + +TRUE: Final = 1 +FALSE: Final = 0 +MAX_PATH: Final = 260 + +AC_SRC_OVER: Final = 0 +AC_SRC_ALPHA: Final = 1 +GRADIENT_FILL_RECT_H: Final = 0 +GRADIENT_FILL_RECT_V: Final = 1 +GRADIENT_FILL_TRIANGLE: Final = 2 +GRADIENT_FILL_OP_FLAG: Final = 255 + +MM_WORKING_SET_MAX_HARD_ENABLE: Final = 1 +MM_WORKING_SET_MAX_HARD_DISABLE: Final = 2 +MM_WORKING_SET_MIN_HARD_ENABLE: Final = 4 +MM_WORKING_SET_MIN_HARD_DISABLE: Final = 8 + +VOLUME_NAME_DOS: Final = 0 +VOLUME_NAME_GUID: Final = 1 +VOLUME_NAME_NT: Final = 2 +VOLUME_NAME_NONE: Final = 4 +FILE_NAME_NORMALIZED: Final = 0 +FILE_NAME_OPENED: Final = 8 + +DEVICE_NOTIFY_WINDOW_HANDLE: Final = 0x00000000 +DEVICE_NOTIFY_SERVICE_HANDLE: Final = 0x00000001 + +WM_DEVICECHANGE: Final = 0x0219 +BSF_QUERY: Final = 0x00000001 +BSF_IGNORECURRENTTASK: Final = 0x00000002 +BSF_FLUSHDISK: Final = 0x00000004 +BSF_NOHANG: Final = 0x00000008 +BSF_POSTMESSAGE: Final = 0x00000010 +BSF_FORCEIFHUNG: Final = 0x00000020 +BSF_NOTIMEOUTIFNOTHUNG: Final = 0x00000040 +BSF_MSGSRV32ISOK: Final = -2147483648 +BSF_MSGSRV32ISOK_BIT: Final = 31 +BSM_ALLCOMPONENTS: Final = 0x00000000 +BSM_VXDS: Final = 0x00000001 +BSM_NETDRIVER: Final = 0x00000002 +BSM_INSTALLABLEDRIVERS: Final = 0x00000004 +BSM_APPLICATIONS: Final = 0x00000008 +DBT_APPYBEGIN: Final = 0x0000 +DBT_APPYEND: Final = 0x0001 +DBT_DEVNODES_CHANGED: Final = 0x0007 +DBT_QUERYCHANGECONFIG: Final = 0x0017 +DBT_CONFIGCHANGED: Final = 0x0018 +DBT_CONFIGCHANGECANCELED: Final = 0x0019 +DBT_MONITORCHANGE: Final = 0x001B +DBT_SHELLLOGGEDON: Final = 0x0020 +DBT_CONFIGMGAPI32: Final = 0x0022 +DBT_VXDINITCOMPLETE: Final = 0x0023 +DBT_VOLLOCKQUERYLOCK: Final = 0x8041 +DBT_VOLLOCKLOCKTAKEN: Final = 0x8042 +DBT_VOLLOCKLOCKFAILED: Final = 0x8043 +DBT_VOLLOCKQUERYUNLOCK: Final = 0x8044 +DBT_VOLLOCKLOCKRELEASED: Final = 0x8045 +DBT_VOLLOCKUNLOCKFAILED: Final = 0x8046 +LOCKP_ALLOW_WRITES: Final = 0x01 +LOCKP_FAIL_WRITES: Final = 0x00 +LOCKP_FAIL_MEM_MAPPING: Final = 0x02 +LOCKP_ALLOW_MEM_MAPPING: Final = 0x00 +LOCKP_USER_MASK: Final = 0x03 +LOCKP_LOCK_FOR_FORMAT: Final = 0x04 +LOCKF_LOGICAL_LOCK: Final = 0x00 +LOCKF_PHYSICAL_LOCK: Final = 0x01 +DBT_NO_DISK_SPACE: Final = 0x0047 +DBT_LOW_DISK_SPACE: Final = 0x0048 +DBT_CONFIGMGPRIVATE: Final = 0x7FFF +DBT_DEVICEARRIVAL: Final = 0x8000 +DBT_DEVICEQUERYREMOVE: Final = 0x8001 +DBT_DEVICEQUERYREMOVEFAILED: Final = 0x8002 +DBT_DEVICEREMOVEPENDING: Final = 0x8003 +DBT_DEVICEREMOVECOMPLETE: Final = 0x8004 +DBT_DEVICETYPESPECIFIC: Final = 0x8005 +DBT_CUSTOMEVENT: Final = 0x8006 +DBT_DEVTYP_OEM: Final = 0x00000000 +DBT_DEVTYP_DEVNODE: Final = 0x00000001 +DBT_DEVTYP_VOLUME: Final = 0x00000002 +DBT_DEVTYP_PORT: Final = 0x00000003 +DBT_DEVTYP_NET: Final = 0x00000004 +DBT_DEVTYP_DEVICEINTERFACE: Final = 0x00000005 +DBT_DEVTYP_HANDLE: Final = 0x00000006 +DBTF_MEDIA: Final = 0x0001 +DBTF_NET: Final = 0x0002 +DBTF_RESOURCE: Final = 0x00000001 +DBTF_XPORT: Final = 0x00000002 +DBTF_SLOWNET: Final = 0x00000004 +DBT_VPOWERDAPI: Final = 0x8100 +DBT_USERDEFINED: Final = 0xFFFF + +IME_CMODE_ALPHANUMERIC: Final = 0x0000 +IME_CMODE_NATIVE: Final = 0x0001 +IME_CMODE_CHINESE: Final = IME_CMODE_NATIVE +IME_CMODE_HANGUL: Final = IME_CMODE_NATIVE +IME_CMODE_JAPANESE: Final = IME_CMODE_NATIVE +IME_CMODE_KATAKANA: Final = 0x0002 +IME_CMODE_LANGUAGE: Final = 0x0003 +IME_CMODE_FULLSHAPE: Final = 0x0008 +IME_CMODE_ROMAN: Final = 0x0010 +IME_CMODE_CHARCODE: Final = 0x0020 +IME_CMODE_HANJACONVERT: Final = 0x0040 +IME_CMODE_NATIVESYMBOL: Final = 0x0080 diff --git a/stubs/pywin32/win32/lib/win32cryptcon.pyi b/stubs/pywin32/win32/lib/win32cryptcon.pyi new file mode 100644 index 000000000000..c3865abff621 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32cryptcon.pyi @@ -0,0 +1,1790 @@ +def GET_ALG_CLASS(x: int) -> int: ... +def GET_ALG_TYPE(x: int) -> int: ... +def GET_ALG_SID(x: int) -> int: ... + +ALG_CLASS_ANY: int +ALG_CLASS_SIGNATURE: int +ALG_CLASS_MSG_ENCRYPT: int +ALG_CLASS_DATA_ENCRYPT: int +ALG_CLASS_HASH: int +ALG_CLASS_KEY_EXCHANGE: int +ALG_CLASS_ALL: int +ALG_TYPE_ANY: int +ALG_TYPE_DSS: int +ALG_TYPE_RSA: int +ALG_TYPE_BLOCK: int +ALG_TYPE_STREAM: int +ALG_TYPE_DH: int +ALG_TYPE_SECURECHANNEL: int +ALG_SID_ANY: int +ALG_SID_RSA_ANY: int +ALG_SID_RSA_PKCS: int +ALG_SID_RSA_MSATWORK: int +ALG_SID_RSA_ENTRUST: int +ALG_SID_RSA_PGP: int +ALG_SID_DSS_ANY: int +ALG_SID_DSS_PKCS: int +ALG_SID_DSS_DMS: int +ALG_SID_DES: int +ALG_SID_3DES: int +ALG_SID_DESX: int +ALG_SID_IDEA: int +ALG_SID_CAST: int +ALG_SID_SAFERSK64: int +ALG_SID_SAFERSK128: int +ALG_SID_3DES_112: int +ALG_SID_CYLINK_MEK: int +ALG_SID_RC5: int +ALG_SID_AES_128: int +ALG_SID_AES_192: int +ALG_SID_AES_256: int +ALG_SID_AES: int +ALG_SID_SKIPJACK: int +ALG_SID_TEK: int +CRYPT_MODE_CBCI: int +CRYPT_MODE_CFBP: int +CRYPT_MODE_OFBP: int +CRYPT_MODE_CBCOFM: int +CRYPT_MODE_CBCOFMI: int +ALG_SID_RC2: int +ALG_SID_RC4: int +ALG_SID_SEAL: int +ALG_SID_DH_SANDF: int +ALG_SID_DH_EPHEM: int +ALG_SID_AGREED_KEY_ANY: int +ALG_SID_KEA: int +ALG_SID_MD2: int +ALG_SID_MD4: int +ALG_SID_MD5: int +ALG_SID_SHA: int +ALG_SID_SHA1: int +ALG_SID_MAC: int +ALG_SID_RIPEMD: int +ALG_SID_RIPEMD160: int +ALG_SID_SSL3SHAMD5: int +ALG_SID_HMAC: int +ALG_SID_TLS1PRF: int +ALG_SID_HASH_REPLACE_OWF: int +ALG_SID_SHA_256: int +ALG_SID_SHA_384: int +ALG_SID_SHA_512: int +ALG_SID_SSL3_MASTER: int +ALG_SID_SCHANNEL_MASTER_HASH: int +ALG_SID_SCHANNEL_MAC_KEY: int +ALG_SID_PCT1_MASTER: int +ALG_SID_SSL2_MASTER: int +ALG_SID_TLS1_MASTER: int +ALG_SID_SCHANNEL_ENC_KEY: int +ALG_SID_EXAMPLE: int +CALG_MD2: int +CALG_MD4: int +CALG_MD5: int +CALG_SHA: int +CALG_SHA1: int +CALG_MAC: int +CALG_RSA_SIGN: int +CALG_DSS_SIGN: int +CALG_NO_SIGN: int +CALG_RSA_KEYX: int +CALG_DES: int +CALG_3DES_112: int +CALG_3DES: int +CALG_DESX: int +CALG_RC2: int +CALG_RC4: int +CALG_SEAL: int +CALG_DH_SF: int +CALG_DH_EPHEM: int +CALG_AGREEDKEY_ANY: int +CALG_KEA_KEYX: int +CALG_HUGHES_MD5: int +CALG_SKIPJACK: int +CALG_TEK: int +CALG_CYLINK_MEK: int +CALG_SSL3_SHAMD5: int +CALG_SSL3_MASTER: int +CALG_SCHANNEL_MASTER_HASH: int +CALG_SCHANNEL_MAC_KEY: int +CALG_SCHANNEL_ENC_KEY: int +CALG_PCT1_MASTER: int +CALG_SSL2_MASTER: int +CALG_TLS1_MASTER: int +CALG_RC5: int +CALG_HMAC: int +CALG_TLS1PRF: int +CALG_HASH_REPLACE_OWF: int +CALG_AES_128: int +CALG_AES_192: int +CALG_AES_256: int +CALG_AES: int +CALG_SHA_256: int +CALG_SHA_384: int +CALG_SHA_512: int +CRYPT_VERIFYCONTEXT: int +CRYPT_NEWKEYSET: int +CRYPT_DELETEKEYSET: int +CRYPT_MACHINE_KEYSET: int +CRYPT_SILENT: int +CRYPT_EXPORTABLE: int +CRYPT_USER_PROTECTED: int +CRYPT_CREATE_SALT: int +CRYPT_UPDATE_KEY: int +CRYPT_NO_SALT: int +CRYPT_PREGEN: int +CRYPT_RECIPIENT: int +CRYPT_INITIATOR: int +CRYPT_ONLINE: int +CRYPT_SF: int +CRYPT_CREATE_IV: int +CRYPT_KEK: int +CRYPT_DATA_KEY: int +CRYPT_VOLATILE: int +CRYPT_SGCKEY: int +CRYPT_ARCHIVABLE: int +RSA1024BIT_KEY: int +CRYPT_SERVER: int +KEY_LENGTH_MASK: int +CRYPT_Y_ONLY: int +CRYPT_SSL2_FALLBACK: int +CRYPT_DESTROYKEY: int +CRYPT_OAEP: int +CRYPT_BLOB_VER3: int +CRYPT_IPSEC_HMAC_KEY: int +CRYPT_DECRYPT_RSA_NO_PADDING_CHECK: int +CRYPT_SECRETDIGEST: int +CRYPT_OWF_REPL_LM_HASH: int +CRYPT_LITTLE_ENDIAN: int +CRYPT_NOHASHOID: int +CRYPT_TYPE2_FORMAT: int +CRYPT_X931_FORMAT: int +CRYPT_MACHINE_DEFAULT: int +CRYPT_USER_DEFAULT: int +CRYPT_DELETE_DEFAULT: int +SIMPLEBLOB: int +PUBLICKEYBLOB: int +PRIVATEKEYBLOB: int +PLAINTEXTKEYBLOB: int +OPAQUEKEYBLOB: int +PUBLICKEYBLOBEX: int +SYMMETRICWRAPKEYBLOB: int +AT_KEYEXCHANGE: int +AT_SIGNATURE: int +CRYPT_USERDATA: int +KP_IV: int +KP_SALT: int +KP_PADDING: int +KP_MODE: int +KP_MODE_BITS: int +KP_PERMISSIONS: int +KP_ALGID: int +KP_BLOCKLEN: int +KP_KEYLEN: int +KP_SALT_EX: int +KP_P: int +KP_G: int +KP_Q: int +KP_X: int +KP_Y: int +KP_RA: int +KP_RB: int +KP_INFO: int +KP_EFFECTIVE_KEYLEN: int +KP_SCHANNEL_ALG: int +KP_CLIENT_RANDOM: int +KP_SERVER_RANDOM: int +KP_RP: int +KP_PRECOMP_MD5: int +KP_PRECOMP_SHA: int +KP_CERTIFICATE: int +KP_CLEAR_KEY: int +KP_PUB_EX_LEN: int +KP_PUB_EX_VAL: int +KP_KEYVAL: int +KP_ADMIN_PIN: int +KP_KEYEXCHANGE_PIN: int +KP_SIGNATURE_PIN: int +KP_PREHASH: int +KP_ROUNDS: int +KP_OAEP_PARAMS: int +KP_CMS_KEY_INFO: int +KP_CMS_DH_KEY_INFO: int +KP_PUB_PARAMS: int +KP_VERIFY_PARAMS: int +KP_HIGHEST_VERSION: int +KP_GET_USE_COUNT: int +PKCS5_PADDING: int +RANDOM_PADDING: int +ZERO_PADDING: int +CRYPT_MODE_CBC: int +CRYPT_MODE_ECB: int +CRYPT_MODE_OFB: int +CRYPT_MODE_CFB: int +CRYPT_MODE_CTS: int +CRYPT_ENCRYPT: int +CRYPT_DECRYPT: int +CRYPT_EXPORT: int +CRYPT_READ: int +CRYPT_WRITE: int +CRYPT_MAC: int +CRYPT_EXPORT_KEY: int +CRYPT_IMPORT_KEY: int +CRYPT_ARCHIVE: int +HP_ALGID: int +HP_HASHVAL: int +HP_HASHSIZE: int +HP_HMAC_INFO: int +HP_TLS1PRF_LABEL: int +HP_TLS1PRF_SEED: int +CRYPT_FAILED: int +CRYPT_SUCCEED: int + +def RCRYPT_SUCCEEDED(rt: int) -> bool: ... +def RCRYPT_FAILED(rt: int) -> bool: ... + +PP_ENUMALGS: int +PP_ENUMCONTAINERS: int +PP_IMPTYPE: int +PP_NAME: int +PP_VERSION: int +PP_CONTAINER: int +PP_CHANGE_PASSWORD: int +PP_KEYSET_SEC_DESCR: int +PP_CERTCHAIN: int +PP_KEY_TYPE_SUBTYPE: int +PP_PROVTYPE: int +PP_KEYSTORAGE: int +PP_APPLI_CERT: int +PP_SYM_KEYSIZE: int +PP_SESSION_KEYSIZE: int +PP_UI_PROMPT: int +PP_ENUMALGS_EX: int +PP_ENUMMANDROOTS: int +PP_ENUMELECTROOTS: int +PP_KEYSET_TYPE: int +PP_ADMIN_PIN: int +PP_KEYEXCHANGE_PIN: int +PP_SIGNATURE_PIN: int +PP_SIG_KEYSIZE_INC: int +PP_KEYX_KEYSIZE_INC: int +PP_UNIQUE_CONTAINER: int +PP_SGC_INFO: int +PP_USE_HARDWARE_RNG: int +PP_KEYSPEC: int +PP_ENUMEX_SIGNING_PROT: int +PP_CRYPT_COUNT_KEY_USE: int +CRYPT_FIRST: int +CRYPT_NEXT: int +CRYPT_SGC_ENUM: int +CRYPT_IMPL_HARDWARE: int +CRYPT_IMPL_SOFTWARE: int +CRYPT_IMPL_MIXED: int +CRYPT_IMPL_UNKNOWN: int +CRYPT_IMPL_REMOVABLE: int +CRYPT_SEC_DESCR: int +CRYPT_PSTORE: int +CRYPT_UI_PROMPT: int +CRYPT_FLAG_PCT1: int +CRYPT_FLAG_SSL2: int +CRYPT_FLAG_SSL3: int +CRYPT_FLAG_TLS1: int +CRYPT_FLAG_IPSEC: int +CRYPT_FLAG_SIGNING: int +CRYPT_SGC: int +CRYPT_FASTSGC: int +PP_CLIENT_HWND: int +PP_CONTEXT_INFO: int +PP_KEYEXCHANGE_KEYSIZE: int +PP_SIGNATURE_KEYSIZE: int +PP_KEYEXCHANGE_ALG: int +PP_SIGNATURE_ALG: int +PP_DELETEKEY: int +PROV_RSA_FULL: int +PROV_RSA_SIG: int +PROV_DSS: int +PROV_FORTEZZA: int +PROV_MS_EXCHANGE: int +PROV_SSL: int +PROV_RSA_SCHANNEL: int +PROV_DSS_DH: int +PROV_EC_ECDSA_SIG: int +PROV_EC_ECNRA_SIG: int +PROV_EC_ECDSA_FULL: int +PROV_EC_ECNRA_FULL: int +PROV_DH_SCHANNEL: int +PROV_SPYRUS_LYNKS: int +PROV_RNG: int +PROV_INTEL_SEC: int +PROV_REPLACE_OWF: int +PROV_RSA_AES: int +MS_DEF_PROV_A: str +MS_DEF_PROV: str +MS_ENHANCED_PROV_A: str +MS_ENHANCED_PROV: str +MS_STRONG_PROV_A: str +MS_STRONG_PROV: str +MS_DEF_RSA_SIG_PROV_A: str +MS_DEF_RSA_SIG_PROV: str +MS_DEF_RSA_SCHANNEL_PROV_A: str +MS_DEF_RSA_SCHANNEL_PROV: str +MS_DEF_DSS_PROV_A: str +MS_DEF_DSS_PROV: str +MS_DEF_DSS_DH_PROV_A: str +MS_DEF_DSS_DH_PROV: str +MS_ENH_DSS_DH_PROV_A: str +MS_ENH_DSS_DH_PROV: str +MS_DEF_DH_SCHANNEL_PROV_A: str +MS_DEF_DH_SCHANNEL_PROV: str +MS_SCARD_PROV_A: str +MS_SCARD_PROV: str +MS_ENH_RSA_AES_PROV_A: str +MS_ENH_RSA_AES_PROV: str +MAXUIDLEN: int +EXPO_OFFLOAD_REG_VALUE: str +EXPO_OFFLOAD_FUNC_NAME: str +szKEY_CRYPTOAPI_PRIVATE_KEY_OPTIONS: str +szFORCE_KEY_PROTECTION: str +dwFORCE_KEY_PROTECTION_DISABLED: int +dwFORCE_KEY_PROTECTION_USER_SELECT: int +dwFORCE_KEY_PROTECTION_HIGH: int +szKEY_CACHE_ENABLED: str +szKEY_CACHE_SECONDS: str +CUR_BLOB_VERSION: int +SCHANNEL_MAC_KEY: int +SCHANNEL_ENC_KEY: int +INTERNATIONAL_USAGE: int +szOID_RSA: str +szOID_PKCS: str +szOID_RSA_HASH: str +szOID_RSA_ENCRYPT: str +szOID_PKCS_1: str +szOID_PKCS_2: str +szOID_PKCS_3: str +szOID_PKCS_4: str +szOID_PKCS_5: str +szOID_PKCS_6: str +szOID_PKCS_7: str +szOID_PKCS_8: str +szOID_PKCS_9: str +szOID_PKCS_10: str +szOID_PKCS_12: str +szOID_RSA_RSA: str +szOID_RSA_MD2RSA: str +szOID_RSA_MD4RSA: str +szOID_RSA_MD5RSA: str +szOID_RSA_SHA1RSA: str +szOID_RSA_SETOAEP_RSA: str +szOID_RSA_DH: str +szOID_RSA_data: str +szOID_RSA_signedData: str +szOID_RSA_envelopedData: str +szOID_RSA_signEnvData: str +szOID_RSA_digestedData: str +szOID_RSA_hashedData: str +szOID_RSA_encryptedData: str +szOID_RSA_emailAddr: str +szOID_RSA_unstructName: str +szOID_RSA_contentType: str +szOID_RSA_messageDigest: str +szOID_RSA_signingTime: str +szOID_RSA_counterSign: str +szOID_RSA_challengePwd: str +szOID_RSA_unstructAddr: str +szOID_RSA_extCertAttrs: str +szOID_RSA_certExtensions: str +szOID_RSA_SMIMECapabilities: str +szOID_RSA_preferSignedData: str +szOID_RSA_SMIMEalg: str +szOID_RSA_SMIMEalgESDH: str +szOID_RSA_SMIMEalgCMS3DESwrap: str +szOID_RSA_SMIMEalgCMSRC2wrap: str +szOID_RSA_MD2: str +szOID_RSA_MD4: str +szOID_RSA_MD5: str +szOID_RSA_RC2CBC: str +szOID_RSA_RC4: str +szOID_RSA_DES_EDE3_CBC: str +szOID_RSA_RC5_CBCPad: str +szOID_ANSI_X942: str +szOID_ANSI_X942_DH: str +szOID_X957: str +szOID_X957_DSA: str +szOID_X957_SHA1DSA: str +szOID_DS: str +szOID_DSALG: str +szOID_DSALG_CRPT: str +szOID_DSALG_HASH: str +szOID_DSALG_SIGN: str +szOID_DSALG_RSA: str +szOID_OIW: str +szOID_OIWSEC: str +szOID_OIWSEC_md4RSA: str +szOID_OIWSEC_md5RSA: str +szOID_OIWSEC_md4RSA2: str +szOID_OIWSEC_desECB: str +szOID_OIWSEC_desCBC: str +szOID_OIWSEC_desOFB: str +szOID_OIWSEC_desCFB: str +szOID_OIWSEC_desMAC: str +szOID_OIWSEC_rsaSign: str +szOID_OIWSEC_dsa: str +szOID_OIWSEC_shaDSA: str +szOID_OIWSEC_mdc2RSA: str +szOID_OIWSEC_shaRSA: str +szOID_OIWSEC_dhCommMod: str +szOID_OIWSEC_desEDE: str +szOID_OIWSEC_sha: str +szOID_OIWSEC_mdc2: str +szOID_OIWSEC_dsaComm: str +szOID_OIWSEC_dsaCommSHA: str +szOID_OIWSEC_rsaXchg: str +szOID_OIWSEC_keyHashSeal: str +szOID_OIWSEC_md2RSASign: str +szOID_OIWSEC_md5RSASign: str +szOID_OIWSEC_sha1: str +szOID_OIWSEC_dsaSHA1: str +szOID_OIWSEC_dsaCommSHA1: str +szOID_OIWSEC_sha1RSASign: str +szOID_OIWDIR: str +szOID_OIWDIR_CRPT: str +szOID_OIWDIR_HASH: str +szOID_OIWDIR_SIGN: str +szOID_OIWDIR_md2: str +szOID_OIWDIR_md2RSA: str +szOID_INFOSEC: str +szOID_INFOSEC_sdnsSignature: str +szOID_INFOSEC_mosaicSignature: str +szOID_INFOSEC_sdnsConfidentiality: str +szOID_INFOSEC_mosaicConfidentiality: str +szOID_INFOSEC_sdnsIntegrity: str +szOID_INFOSEC_mosaicIntegrity: str +szOID_INFOSEC_sdnsTokenProtection: str +szOID_INFOSEC_mosaicTokenProtection: str +szOID_INFOSEC_sdnsKeyManagement: str +szOID_INFOSEC_mosaicKeyManagement: str +szOID_INFOSEC_sdnsKMandSig: str +szOID_INFOSEC_mosaicKMandSig: str +szOID_INFOSEC_SuiteASignature: str +szOID_INFOSEC_SuiteAConfidentiality: str +szOID_INFOSEC_SuiteAIntegrity: str +szOID_INFOSEC_SuiteATokenProtection: str +szOID_INFOSEC_SuiteAKeyManagement: str +szOID_INFOSEC_SuiteAKMandSig: str +szOID_INFOSEC_mosaicUpdatedSig: str +szOID_INFOSEC_mosaicKMandUpdSig: str +szOID_INFOSEC_mosaicUpdatedInteg: str +szOID_COMMON_NAME: str +szOID_SUR_NAME: str +szOID_DEVICE_SERIAL_NUMBER: str +szOID_COUNTRY_NAME: str +szOID_LOCALITY_NAME: str +szOID_STATE_OR_PROVINCE_NAME: str +szOID_STREET_ADDRESS: str +szOID_ORGANIZATION_NAME: str +szOID_ORGANIZATIONAL_UNIT_NAME: str +szOID_TITLE: str +szOID_DESCRIPTION: str +szOID_SEARCH_GUIDE: str +szOID_BUSINESS_CATEGORY: str +szOID_POSTAL_ADDRESS: str +szOID_POSTAL_CODE: str +szOID_POST_OFFICE_BOX: str +szOID_PHYSICAL_DELIVERY_OFFICE_NAME: str +szOID_TELEPHONE_NUMBER: str +szOID_TELEX_NUMBER: str +szOID_TELETEXT_TERMINAL_IDENTIFIER: str +szOID_FACSIMILE_TELEPHONE_NUMBER: str +szOID_X21_ADDRESS: str +szOID_INTERNATIONAL_ISDN_NUMBER: str +szOID_REGISTERED_ADDRESS: str +szOID_DESTINATION_INDICATOR: str +szOID_PREFERRED_DELIVERY_METHOD: str +szOID_PRESENTATION_ADDRESS: str +szOID_SUPPORTED_APPLICATION_CONTEXT: str +szOID_MEMBER: str +szOID_OWNER: str +szOID_ROLE_OCCUPANT: str +szOID_SEE_ALSO: str +szOID_USER_PASSWORD: str +szOID_USER_CERTIFICATE: str +szOID_CA_CERTIFICATE: str +szOID_CROSS_CERTIFICATE_PAIR: str +szOID_GIVEN_NAME: str +szOID_INITIALS: str +szOID_DN_QUALIFIER: str +szOID_DOMAIN_COMPONENT: str +szOID_PKCS_12_FRIENDLY_NAME_ATTR: str +szOID_PKCS_12_LOCAL_KEY_ID: str +szOID_PKCS_12_KEY_PROVIDER_NAME_ATTR: str +szOID_LOCAL_MACHINE_KEYSET: str +szOID_KEYID_RDN: str +CERT_RDN_ANY_TYPE: int +CERT_RDN_ENCODED_BLOB: int +CERT_RDN_OCTET_STRING: int +CERT_RDN_NUMERIC_STRING: int +CERT_RDN_PRINTABLE_STRING: int +CERT_RDN_TELETEX_STRING: int +CERT_RDN_T61_STRING: int +CERT_RDN_VIDEOTEX_STRING: int +CERT_RDN_IA5_STRING: int +CERT_RDN_GRAPHIC_STRING: int +CERT_RDN_VISIBLE_STRING: int +CERT_RDN_ISO646_STRING: int +CERT_RDN_GENERAL_STRING: int +CERT_RDN_UNIVERSAL_STRING: int +CERT_RDN_INT4_STRING: int +CERT_RDN_BMP_STRING: int +CERT_RDN_UNICODE_STRING: int +CERT_RDN_UTF8_STRING: int +CERT_RDN_TYPE_MASK: int +CERT_RDN_FLAGS_MASK: int +CERT_RDN_ENABLE_T61_UNICODE_FLAG: int +CERT_RDN_ENABLE_UTF8_UNICODE_FLAG: int +CERT_RDN_DISABLE_CHECK_TYPE_FLAG: int +CERT_RDN_DISABLE_IE4_UTF8_FLAG: int +CERT_RSA_PUBLIC_KEY_OBJID: str +CERT_DEFAULT_OID_PUBLIC_KEY_SIGN: str +CERT_DEFAULT_OID_PUBLIC_KEY_XCHG: str +CERT_V1: int +CERT_V2: int +CERT_V3: int +CERT_INFO_VERSION_FLAG: int +CERT_INFO_SERIAL_NUMBER_FLAG: int +CERT_INFO_SIGNATURE_ALGORITHM_FLAG: int +CERT_INFO_ISSUER_FLAG: int +CERT_INFO_NOT_BEFORE_FLAG: int +CERT_INFO_NOT_AFTER_FLAG: int +CERT_INFO_SUBJECT_FLAG: int +CERT_INFO_SUBJECT_PUBLIC_KEY_INFO_FLAG: int +CERT_INFO_ISSUER_UNIQUE_ID_FLAG: int +CERT_INFO_SUBJECT_UNIQUE_ID_FLAG: int +CERT_INFO_EXTENSION_FLAG: int +CRL_V1: int +CRL_V2: int +CERT_REQUEST_V1: int +CERT_KEYGEN_REQUEST_V1: int +CTL_V1: int +CERT_ENCODING_TYPE_MASK: int +CMSG_ENCODING_TYPE_MASK: int + +def GET_CERT_ENCODING_TYPE(X: int) -> int: ... +def GET_CMSG_ENCODING_TYPE(X: int) -> int: ... + +CRYPT_ASN_ENCODING: int +CRYPT_NDR_ENCODING: int +X509_ASN_ENCODING: int +X509_NDR_ENCODING: int +PKCS_7_ASN_ENCODING: int +PKCS_7_NDR_ENCODING: int +CRYPT_FORMAT_STR_MULTI_LINE: int +CRYPT_FORMAT_STR_NO_HEX: int +CRYPT_FORMAT_SIMPLE: int +CRYPT_FORMAT_X509: int +CRYPT_FORMAT_OID: int +CRYPT_FORMAT_RDN_SEMICOLON: int +CRYPT_FORMAT_RDN_CRLF: int +CRYPT_FORMAT_RDN_UNQUOTE: int +CRYPT_FORMAT_RDN_REVERSE: int +CRYPT_FORMAT_COMMA: int +CRYPT_FORMAT_SEMICOLON: int +CRYPT_FORMAT_CRLF: int +CRYPT_ENCODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: int +CRYPT_ENCODE_ALLOC_FLAG: int +CRYPT_UNICODE_NAME_ENCODE_ENABLE_T61_UNICODE_FLAG: int +CRYPT_UNICODE_NAME_ENCODE_ENABLE_UTF8_UNICODE_FLAG: int +CRYPT_UNICODE_NAME_ENCODE_DISABLE_CHECK_TYPE_FLAG: int +CRYPT_SORTED_CTL_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: int +CRYPT_DECODE_NOCOPY_FLAG: int +CRYPT_DECODE_TO_BE_SIGNED_FLAG: int +CRYPT_DECODE_SHARE_OID_STRING_FLAG: int +CRYPT_DECODE_NO_SIGNATURE_BYTE_REVERSAL_FLAG: int +CRYPT_DECODE_ALLOC_FLAG: int +CRYPT_UNICODE_NAME_DECODE_DISABLE_IE4_UTF8_FLAG: int +CRYPT_ENCODE_DECODE_NONE: int +X509_CERT: int +X509_CERT_TO_BE_SIGNED: int +X509_CERT_CRL_TO_BE_SIGNED: int +X509_CERT_REQUEST_TO_BE_SIGNED: int +X509_EXTENSIONS: int +X509_NAME_VALUE: int +X509_NAME: int +X509_PUBLIC_KEY_INFO: int +X509_AUTHORITY_KEY_ID: int +X509_KEY_ATTRIBUTES: int +X509_KEY_USAGE_RESTRICTION: int +X509_ALTERNATE_NAME: int +X509_BASIC_CONSTRAINTS: int +X509_KEY_USAGE: int +X509_BASIC_CONSTRAINTS2: int +X509_CERT_POLICIES: int +PKCS_UTC_TIME: int +PKCS_TIME_REQUEST: int +RSA_CSP_PUBLICKEYBLOB: int +X509_UNICODE_NAME: int +X509_KEYGEN_REQUEST_TO_BE_SIGNED: int +PKCS_ATTRIBUTE: int +PKCS_CONTENT_INFO_SEQUENCE_OF_ANY: int +X509_UNICODE_NAME_VALUE: int +X509_ANY_STRING: int +X509_UNICODE_ANY_STRING: int +X509_OCTET_STRING: int +X509_BITS: int +X509_INTEGER: int +X509_MULTI_BYTE_INTEGER: int +X509_ENUMERATED: int +X509_CHOICE_OF_TIME: int +X509_AUTHORITY_KEY_ID2: int +X509_AUTHORITY_INFO_ACCESS: int +X509_SUBJECT_INFO_ACCESS: int +X509_CRL_REASON_CODE: int +PKCS_CONTENT_INFO: int +X509_SEQUENCE_OF_ANY: int +X509_CRL_DIST_POINTS: int +X509_ENHANCED_KEY_USAGE: int +PKCS_CTL: int +X509_MULTI_BYTE_UINT: int +X509_DSS_PUBLICKEY: int +X509_DSS_PARAMETERS: int +X509_DSS_SIGNATURE: int +PKCS_RC2_CBC_PARAMETERS: int +PKCS_SMIME_CAPABILITIES: int +X509_QC_STATEMENTS_EXT: int +PKCS_RSA_PRIVATE_KEY: int +PKCS_PRIVATE_KEY_INFO: int +PKCS_ENCRYPTED_PRIVATE_KEY_INFO: int +X509_PKIX_POLICY_QUALIFIER_USERNOTICE: int +X509_DH_PUBLICKEY: int +X509_DH_PARAMETERS: int +PKCS_ATTRIBUTES: int +PKCS_SORTED_CTL: int +X509_ECC_SIGNATURE: int +X942_DH_PARAMETERS: int +X509_BITS_WITHOUT_TRAILING_ZEROES: int +X942_OTHER_INFO: int +X509_CERT_PAIR: int +X509_ISSUING_DIST_POINT: int +X509_NAME_CONSTRAINTS: int +X509_POLICY_MAPPINGS: int +X509_POLICY_CONSTRAINTS: int +X509_CROSS_CERT_DIST_POINTS: int +CMC_DATA: int +CMC_RESPONSE: int +CMC_STATUS: int +CMC_ADD_EXTENSIONS: int +CMC_ADD_ATTRIBUTES: int +X509_CERTIFICATE_TEMPLATE: int +OCSP_SIGNED_REQUEST: int +OCSP_REQUEST: int +OCSP_RESPONSE: int +OCSP_BASIC_SIGNED_RESPONSE: int +OCSP_BASIC_RESPONSE: int +X509_LOGOTYPE_EXT: int +X509_BIOMETRIC_EXT: int +CNG_RSA_PUBLIC_KEY_BLOB: int +X509_OBJECT_IDENTIFIER: int +X509_ALGORITHM_IDENTIFIER: int +PKCS_RSA_SSA_PSS_PARAMETERS: int +PKCS_RSAES_OAEP_PARAMETERS: int +ECC_CMS_SHARED_INFO: int +TIMESTAMP_REQUEST: int +TIMESTAMP_RESPONSE: int +TIMESTAMP_INFO: int +X509_CERT_BUNDLE: int +PKCS7_SIGNER_INFO: int +CMS_SIGNER_INFO: int +szOID_AUTHORITY_KEY_IDENTIFIER: str +szOID_KEY_ATTRIBUTES: str +szOID_CERT_POLICIES_95: str +szOID_KEY_USAGE_RESTRICTION: str +szOID_SUBJECT_ALT_NAME: str +szOID_ISSUER_ALT_NAME: str +szOID_BASIC_CONSTRAINTS: str +szOID_KEY_USAGE: str +szOID_PRIVATEKEY_USAGE_PERIOD: str +szOID_BASIC_CONSTRAINTS2: str +szOID_CERT_POLICIES: str +szOID_ANY_CERT_POLICY: str +szOID_AUTHORITY_KEY_IDENTIFIER2: str +szOID_SUBJECT_KEY_IDENTIFIER: str +szOID_SUBJECT_ALT_NAME2: str +szOID_ISSUER_ALT_NAME2: str +szOID_CRL_REASON_CODE: str +szOID_REASON_CODE_HOLD: str +szOID_CRL_DIST_POINTS: str +szOID_ENHANCED_KEY_USAGE: str +szOID_CRL_NUMBER: str +szOID_DELTA_CRL_INDICATOR: str +szOID_ISSUING_DIST_POINT: str +szOID_FRESHEST_CRL: str +szOID_NAME_CONSTRAINTS: str +szOID_POLICY_MAPPINGS: str +szOID_LEGACY_POLICY_MAPPINGS: str +szOID_POLICY_CONSTRAINTS: str +szOID_RENEWAL_CERTIFICATE: str +szOID_ENROLLMENT_NAME_VALUE_PAIR: str +szOID_ENROLLMENT_CSP_PROVIDER: str +szOID_OS_VERSION: str +szOID_ENROLLMENT_AGENT: str +szOID_PKIX: str +szOID_PKIX_PE: str +szOID_AUTHORITY_INFO_ACCESS: str +szOID_CERT_EXTENSIONS: str +szOID_NEXT_UPDATE_LOCATION: str +szOID_REMOVE_CERTIFICATE: str +szOID_CROSS_CERT_DIST_POINTS: str +szOID_CTL: str +szOID_SORTED_CTL: str +szOID_SERIALIZED: str +szOID_NT_PRINCIPAL_NAME: str +szOID_PRODUCT_UPDATE: str +szOID_ANY_APPLICATION_POLICY: str +szOID_AUTO_ENROLL_CTL_USAGE: str +szOID_ENROLL_CERTTYPE_EXTENSION: str +szOID_CERT_MANIFOLD: str +szOID_CERTSRV_CA_VERSION: str +szOID_CERTSRV_PREVIOUS_CERT_HASH: str +szOID_CRL_VIRTUAL_BASE: str +szOID_CRL_NEXT_PUBLISH: str +szOID_KP_CA_EXCHANGE: str +szOID_KP_KEY_RECOVERY_AGENT: str +szOID_CERTIFICATE_TEMPLATE: str +szOID_ENTERPRISE_OID_ROOT: str +szOID_RDN_DUMMY_SIGNER: str +szOID_APPLICATION_CERT_POLICIES: str +szOID_APPLICATION_POLICY_MAPPINGS: str +szOID_APPLICATION_POLICY_CONSTRAINTS: str +szOID_ARCHIVED_KEY_ATTR: str +szOID_CRL_SELF_CDP: str +szOID_REQUIRE_CERT_CHAIN_POLICY: str +szOID_ARCHIVED_KEY_CERT_HASH: str +szOID_ISSUED_CERT_HASH: str +szOID_DS_EMAIL_REPLICATION: str +szOID_REQUEST_CLIENT_INFO: str +szOID_ENCRYPTED_KEY_HASH: str +szOID_CERTSRV_CROSSCA_VERSION: str +szOID_NTDS_REPLICATION: str +szOID_SUBJECT_DIR_ATTRS: str +szOID_PKIX_KP: str +szOID_PKIX_KP_SERVER_AUTH: str +szOID_PKIX_KP_CLIENT_AUTH: str +szOID_PKIX_KP_CODE_SIGNING: str +szOID_PKIX_KP_EMAIL_PROTECTION: str +szOID_PKIX_KP_IPSEC_END_SYSTEM: str +szOID_PKIX_KP_IPSEC_TUNNEL: str +szOID_PKIX_KP_IPSEC_USER: str +szOID_PKIX_KP_TIMESTAMP_SIGNING: str +szOID_IPSEC_KP_IKE_INTERMEDIATE: str +szOID_KP_CTL_USAGE_SIGNING: str +szOID_KP_TIME_STAMP_SIGNING: str +szOID_SERVER_GATED_CRYPTO: str +szOID_SGC_NETSCAPE: str +szOID_KP_EFS: str +szOID_EFS_RECOVERY: str +szOID_WHQL_CRYPTO: str +szOID_NT5_CRYPTO: str +szOID_OEM_WHQL_CRYPTO: str +szOID_EMBEDDED_NT_CRYPTO: str +szOID_KP_QUALIFIED_SUBORDINATION: str +szOID_KP_KEY_RECOVERY: str +szOID_KP_DOCUMENT_SIGNING: str +szOID_KP_LIFETIME_SIGNING: str +szOID_KP_MOBILE_DEVICE_SOFTWARE: str +szOID_DRM: str +szOID_DRM_INDIVIDUALIZATION: str +szOID_LICENSES: str +szOID_LICENSE_SERVER: str +szOID_KP_SMARTCARD_LOGON: str +szOID_YESNO_TRUST_ATTR: str +szOID_PKIX_POLICY_QUALIFIER_CPS: str +szOID_PKIX_POLICY_QUALIFIER_USERNOTICE: str +szOID_CERT_POLICIES_95_QUALIFIER1: str +CERT_UNICODE_RDN_ERR_INDEX_MASK: int +CERT_UNICODE_RDN_ERR_INDEX_SHIFT: int +CERT_UNICODE_ATTR_ERR_INDEX_MASK: int +CERT_UNICODE_ATTR_ERR_INDEX_SHIFT: int +CERT_UNICODE_VALUE_ERR_INDEX_MASK: int +CERT_UNICODE_VALUE_ERR_INDEX_SHIFT: int +CERT_DIGITAL_SIGNATURE_KEY_USAGE: int +CERT_NON_REPUDIATION_KEY_USAGE: int +CERT_KEY_ENCIPHERMENT_KEY_USAGE: int +CERT_DATA_ENCIPHERMENT_KEY_USAGE: int +CERT_KEY_AGREEMENT_KEY_USAGE: int +CERT_KEY_CERT_SIGN_KEY_USAGE: int +CERT_OFFLINE_CRL_SIGN_KEY_USAGE: int +CERT_CRL_SIGN_KEY_USAGE: int +CERT_ENCIPHER_ONLY_KEY_USAGE: int +CERT_DECIPHER_ONLY_KEY_USAGE: int +CERT_ALT_NAME_OTHER_NAME: int +CERT_ALT_NAME_RFC822_NAME: int +CERT_ALT_NAME_DNS_NAME: int +CERT_ALT_NAME_X400_ADDRESS: int +CERT_ALT_NAME_DIRECTORY_NAME: int +CERT_ALT_NAME_EDI_PARTY_NAME: int +CERT_ALT_NAME_URL: int +CERT_ALT_NAME_IP_ADDRESS: int +CERT_ALT_NAME_REGISTERED_ID: int +CERT_ALT_NAME_ENTRY_ERR_INDEX_MASK: int +CERT_ALT_NAME_ENTRY_ERR_INDEX_SHIFT: int +CERT_ALT_NAME_VALUE_ERR_INDEX_MASK: int +CERT_ALT_NAME_VALUE_ERR_INDEX_SHIFT: int +CERT_CA_SUBJECT_FLAG: int +CERT_END_ENTITY_SUBJECT_FLAG: int +szOID_PKIX_ACC_DESCR: str +szOID_PKIX_OCSP: str +szOID_PKIX_CA_ISSUERS: str +CRL_REASON_UNSPECIFIED: int +CRL_REASON_KEY_COMPROMISE: int +CRL_REASON_CA_COMPROMISE: int +CRL_REASON_AFFILIATION_CHANGED: int +CRL_REASON_SUPERSEDED: int +CRL_REASON_CESSATION_OF_OPERATION: int +CRL_REASON_CERTIFICATE_HOLD: int +CRL_REASON_REMOVE_FROM_CRL: int +CRL_DIST_POINT_NO_NAME: int +CRL_DIST_POINT_FULL_NAME: int +CRL_DIST_POINT_ISSUER_RDN_NAME: int +CRL_REASON_UNUSED_FLAG: int +CRL_REASON_KEY_COMPROMISE_FLAG: int +CRL_REASON_CA_COMPROMISE_FLAG: int +CRL_REASON_AFFILIATION_CHANGED_FLAG: int +CRL_REASON_SUPERSEDED_FLAG: int +CRL_REASON_CESSATION_OF_OPERATION_FLAG: int +CRL_REASON_CERTIFICATE_HOLD_FLAG: int +CRL_DIST_POINT_ERR_INDEX_MASK: int +CRL_DIST_POINT_ERR_INDEX_SHIFT: int +CRL_DIST_POINT_ERR_CRL_ISSUER_BIT: int +CROSS_CERT_DIST_POINT_ERR_INDEX_MASK: int +CROSS_CERT_DIST_POINT_ERR_INDEX_SHIFT: int +CERT_EXCLUDED_SUBTREE_BIT: int +SORTED_CTL_EXT_FLAGS_OFFSET: int +SORTED_CTL_EXT_COUNT_OFFSET: int +SORTED_CTL_EXT_MAX_COLLISION_OFFSET: int +SORTED_CTL_EXT_HASH_BUCKET_OFFSET: int +SORTED_CTL_EXT_HASHED_SUBJECT_IDENTIFIER_FLAG: int +CERT_DSS_R_LEN: int +CERT_DSS_S_LEN: int +CERT_DSS_SIGNATURE_LEN: int +CERT_MAX_ASN_ENCODED_DSS_SIGNATURE_LEN: int +CRYPT_X942_COUNTER_BYTE_LENGTH: int +CRYPT_X942_KEY_LENGTH_BYTE_LENGTH: int +CRYPT_X942_PUB_INFO_BYTE_LENGTH: float +CRYPT_RC2_40BIT_VERSION: int +CRYPT_RC2_56BIT_VERSION: int +CRYPT_RC2_64BIT_VERSION: int +CRYPT_RC2_128BIT_VERSION: int +szOID_VERISIGN_PRIVATE_6_9: str +szOID_VERISIGN_ONSITE_JURISDICTION_HASH: str +szOID_VERISIGN_BITSTRING_6_13: str +szOID_VERISIGN_ISS_STRONG_CRYPTO: str +szOID_NETSCAPE: str +szOID_NETSCAPE_CERT_EXTENSION: str +szOID_NETSCAPE_CERT_TYPE: str +szOID_NETSCAPE_BASE_URL: str +szOID_NETSCAPE_REVOCATION_URL: str +szOID_NETSCAPE_CA_REVOCATION_URL: str +szOID_NETSCAPE_CERT_RENEWAL_URL: str +szOID_NETSCAPE_CA_POLICY_URL: str +szOID_NETSCAPE_SSL_SERVER_NAME: str +szOID_NETSCAPE_COMMENT: str +szOID_NETSCAPE_DATA_TYPE: str +szOID_NETSCAPE_CERT_SEQUENCE: str +NETSCAPE_SSL_CLIENT_AUTH_CERT_TYPE: int +NETSCAPE_SSL_SERVER_AUTH_CERT_TYPE: int +NETSCAPE_SMIME_CERT_TYPE: int +NETSCAPE_SIGN_CERT_TYPE: int +NETSCAPE_SSL_CA_CERT_TYPE: int +NETSCAPE_SMIME_CA_CERT_TYPE: int +NETSCAPE_SIGN_CA_CERT_TYPE: int +szOID_CT_PKI_DATA: str +szOID_CT_PKI_RESPONSE: str +szOID_PKIX_NO_SIGNATURE: str +szOID_CMC: str +szOID_CMC_STATUS_INFO: str +szOID_CMC_IDENTIFICATION: str +szOID_CMC_IDENTITY_PROOF: str +szOID_CMC_DATA_RETURN: str +szOID_CMC_TRANSACTION_ID: str +szOID_CMC_SENDER_NONCE: str +szOID_CMC_RECIPIENT_NONCE: str +szOID_CMC_ADD_EXTENSIONS: str +szOID_CMC_ENCRYPTED_POP: str +szOID_CMC_DECRYPTED_POP: str +szOID_CMC_LRA_POP_WITNESS: str +szOID_CMC_GET_CERT: str +szOID_CMC_GET_CRL: str +szOID_CMC_REVOKE_REQUEST: str +szOID_CMC_REG_INFO: str +szOID_CMC_RESPONSE_INFO: str +szOID_CMC_QUERY_PENDING: str +szOID_CMC_ID_POP_LINK_RANDOM: str +szOID_CMC_ID_POP_LINK_WITNESS: str +szOID_CMC_ID_CONFIRM_CERT_ACCEPTANCE: str +szOID_CMC_ADD_ATTRIBUTES: str +CMC_TAGGED_CERT_REQUEST_CHOICE: int +CMC_OTHER_INFO_NO_CHOICE: int +CMC_OTHER_INFO_FAIL_CHOICE: int +CMC_OTHER_INFO_PEND_CHOICE: int +CMC_STATUS_SUCCESS: int +CMC_STATUS_FAILED: int +CMC_STATUS_PENDING: int +CMC_STATUS_NO_SUPPORT: int +CMC_STATUS_CONFIRM_REQUIRED: int +CMC_FAIL_BAD_ALG: int +CMC_FAIL_BAD_MESSAGE_CHECK: int +CMC_FAIL_BAD_REQUEST: int +CMC_FAIL_BAD_TIME: int +CMC_FAIL_BAD_CERT_ID: int +CMC_FAIL_UNSUPORTED_EXT: int +CMC_FAIL_MUST_ARCHIVE_KEYS: int +CMC_FAIL_BAD_IDENTITY: int +CMC_FAIL_POP_REQUIRED: int +CMC_FAIL_POP_FAILED: int +CMC_FAIL_NO_KEY_REUSE: int +CMC_FAIL_INTERNAL_CA_ERROR: int +CMC_FAIL_TRY_LATER: int +CRYPT_OID_ENCODE_OBJECT_FUNC: str +CRYPT_OID_DECODE_OBJECT_FUNC: str +CRYPT_OID_ENCODE_OBJECT_EX_FUNC: str +CRYPT_OID_DECODE_OBJECT_EX_FUNC: str +CRYPT_OID_CREATE_COM_OBJECT_FUNC: str +CRYPT_OID_VERIFY_REVOCATION_FUNC: str +CRYPT_OID_VERIFY_CTL_USAGE_FUNC: str +CRYPT_OID_FORMAT_OBJECT_FUNC: str +CRYPT_OID_FIND_OID_INFO_FUNC: str +CRYPT_OID_FIND_LOCALIZED_NAME_FUNC: str +CRYPT_OID_REGPATH: str +CRYPT_OID_REG_ENCODING_TYPE_PREFIX: str +CRYPT_OID_REG_DLL_VALUE_NAME: str +CRYPT_OID_REG_FUNC_NAME_VALUE_NAME: str +CRYPT_OID_REG_FUNC_NAME_VALUE_NAME_A: str +CRYPT_OID_REG_FLAGS_VALUE_NAME: str +CRYPT_DEFAULT_OID: str +CRYPT_INSTALL_OID_FUNC_BEFORE_FLAG: int +CRYPT_GET_INSTALLED_OID_FUNC_FLAG: int +CRYPT_REGISTER_FIRST_INDEX: int +CRYPT_REGISTER_LAST_INDEX: int +CRYPT_MATCH_ANY_ENCODING_TYPE: int +CRYPT_HASH_ALG_OID_GROUP_ID: int +CRYPT_ENCRYPT_ALG_OID_GROUP_ID: int +CRYPT_PUBKEY_ALG_OID_GROUP_ID: int +CRYPT_SIGN_ALG_OID_GROUP_ID: int +CRYPT_RDN_ATTR_OID_GROUP_ID: int +CRYPT_EXT_OR_ATTR_OID_GROUP_ID: int +CRYPT_ENHKEY_USAGE_OID_GROUP_ID: int +CRYPT_POLICY_OID_GROUP_ID: int +CRYPT_TEMPLATE_OID_GROUP_ID: int +CRYPT_LAST_OID_GROUP_ID: int +CRYPT_FIRST_ALG_OID_GROUP_ID: int +CRYPT_LAST_ALG_OID_GROUP_ID: int +CRYPT_OID_INHIBIT_SIGNATURE_FORMAT_FLAG: int +CRYPT_OID_USE_PUBKEY_PARA_FOR_PKCS7_FLAG: int +CRYPT_OID_NO_NULL_ALGORITHM_PARA_FLAG: int +CRYPT_OID_INFO_OID_KEY: int +CRYPT_OID_INFO_NAME_KEY: int +CRYPT_OID_INFO_ALGID_KEY: int +CRYPT_OID_INFO_SIGN_KEY: int +CRYPT_INSTALL_OID_INFO_BEFORE_FLAG: int +CRYPT_LOCALIZED_NAME_ENCODING_TYPE: int +CRYPT_LOCALIZED_NAME_OID: str +szOID_PKCS_7_DATA: str +szOID_PKCS_7_SIGNED: str +szOID_PKCS_7_ENVELOPED: str +szOID_PKCS_7_SIGNEDANDENVELOPED: str +szOID_PKCS_7_DIGESTED: str +szOID_PKCS_7_ENCRYPTED: str +szOID_PKCS_9_CONTENT_TYPE: str +szOID_PKCS_9_MESSAGE_DIGEST: str +CMSG_DATA: int +CMSG_SIGNED: int +CMSG_ENVELOPED: int +CMSG_SIGNED_AND_ENVELOPED: int +CMSG_HASHED: int +CMSG_ENCRYPTED: int +CMSG_ALL_FLAGS: int +CMSG_DATA_FLAG: int +CMSG_SIGNED_FLAG: int +CMSG_ENVELOPED_FLAG: int +CMSG_SIGNED_AND_ENVELOPED_FLAG: int +CMSG_HASHED_FLAG: int +CMSG_ENCRYPTED_FLAG: int +CERT_ID_ISSUER_SERIAL_NUMBER: int +CERT_ID_KEY_IDENTIFIER: int +CERT_ID_SHA1_HASH: int +CMSG_KEY_AGREE_EPHEMERAL_KEY_CHOICE: int +CMSG_KEY_AGREE_STATIC_KEY_CHOICE: int +CMSG_KEY_TRANS_RECIPIENT: int +CMSG_KEY_AGREE_RECIPIENT: int +CMSG_SP3_COMPATIBLE_ENCRYPT_FLAG: int +CMSG_RC4_NO_SALT_FLAG: int +CMSG_INDEFINITE_LENGTH: int +CMSG_BARE_CONTENT_FLAG: int +CMSG_LENGTH_ONLY_FLAG: int +CMSG_DETACHED_FLAG: int +CMSG_AUTHENTICATED_ATTRIBUTES_FLAG: int +CMSG_CONTENTS_OCTETS_FLAG: int +CMSG_MAX_LENGTH_FLAG: int +CMSG_CMS_ENCAPSULATED_CONTENT_FLAG: int +CMSG_CRYPT_RELEASE_CONTEXT_FLAG: int +CMSG_TYPE_PARAM: int +CMSG_CONTENT_PARAM: int +CMSG_BARE_CONTENT_PARAM: int +CMSG_INNER_CONTENT_TYPE_PARAM: int +CMSG_SIGNER_COUNT_PARAM: int +CMSG_SIGNER_INFO_PARAM: int +CMSG_SIGNER_CERT_INFO_PARAM: int +CMSG_SIGNER_HASH_ALGORITHM_PARAM: int +CMSG_SIGNER_AUTH_ATTR_PARAM: int +CMSG_SIGNER_UNAUTH_ATTR_PARAM: int +CMSG_CERT_COUNT_PARAM: int +CMSG_CERT_PARAM: int +CMSG_CRL_COUNT_PARAM: int +CMSG_CRL_PARAM: int +CMSG_ENVELOPE_ALGORITHM_PARAM: int +CMSG_RECIPIENT_COUNT_PARAM: int +CMSG_RECIPIENT_INDEX_PARAM: int +CMSG_RECIPIENT_INFO_PARAM: int +CMSG_HASH_ALGORITHM_PARAM: int +CMSG_HASH_DATA_PARAM: int +CMSG_COMPUTED_HASH_PARAM: int +CMSG_ENCRYPT_PARAM: int +CMSG_ENCRYPTED_DIGEST: int +CMSG_ENCODED_SIGNER: int +CMSG_ENCODED_MESSAGE: int +CMSG_VERSION_PARAM: int +CMSG_ATTR_CERT_COUNT_PARAM: int +CMSG_ATTR_CERT_PARAM: int +CMSG_CMS_RECIPIENT_COUNT_PARAM: int +CMSG_CMS_RECIPIENT_INDEX_PARAM: int +CMSG_CMS_RECIPIENT_ENCRYPTED_KEY_INDEX_PARAM: int +CMSG_CMS_RECIPIENT_INFO_PARAM: int +CMSG_UNPROTECTED_ATTR_PARAM: int +CMSG_SIGNER_CERT_ID_PARAM: int +CMSG_CMS_SIGNER_INFO_PARAM: int +CMSG_SIGNED_DATA_V1: int +CMSG_SIGNED_DATA_V3: int +CMSG_SIGNED_DATA_PKCS_1_5_VERSION: int +CMSG_SIGNED_DATA_CMS_VERSION: int +CMSG_SIGNER_INFO_V1: int +CMSG_SIGNER_INFO_V3: int +CMSG_SIGNER_INFO_PKCS_1_5_VERSION: int +CMSG_SIGNER_INFO_CMS_VERSION: int +CMSG_HASHED_DATA_V0: int +CMSG_HASHED_DATA_V2: int +CMSG_HASHED_DATA_PKCS_1_5_VERSION: int +CMSG_HASHED_DATA_CMS_VERSION: int +CMSG_ENVELOPED_DATA_V0: int +CMSG_ENVELOPED_DATA_V2: int +CMSG_ENVELOPED_DATA_PKCS_1_5_VERSION: int +CMSG_ENVELOPED_DATA_CMS_VERSION: int +CMSG_KEY_AGREE_ORIGINATOR_CERT: int +CMSG_KEY_AGREE_ORIGINATOR_PUBLIC_KEY: int +CMSG_ENVELOPED_RECIPIENT_V0: int +CMSG_ENVELOPED_RECIPIENT_V2: int +CMSG_ENVELOPED_RECIPIENT_V3: int +CMSG_ENVELOPED_RECIPIENT_V4: int +CMSG_KEY_TRANS_PKCS_1_5_VERSION: int +CMSG_KEY_TRANS_CMS_VERSION: int +CMSG_KEY_AGREE_VERSION: int +CMSG_CTRL_VERIFY_SIGNATURE: int +CMSG_CTRL_DECRYPT: int +CMSG_CTRL_VERIFY_HASH: int +CMSG_CTRL_ADD_SIGNER: int +CMSG_CTRL_DEL_SIGNER: int +CMSG_CTRL_ADD_SIGNER_UNAUTH_ATTR: int +CMSG_CTRL_DEL_SIGNER_UNAUTH_ATTR: int +CMSG_CTRL_ADD_CERT: int +CMSG_CTRL_DEL_CERT: int +CMSG_CTRL_ADD_CRL: int +CMSG_CTRL_DEL_CRL: int +CMSG_CTRL_ADD_ATTR_CERT: int +CMSG_CTRL_DEL_ATTR_CERT: int +CMSG_CTRL_KEY_TRANS_DECRYPT: int +CMSG_CTRL_KEY_AGREE_DECRYPT: int +CMSG_CTRL_VERIFY_SIGNATURE_EX: int +CMSG_CTRL_ADD_CMS_SIGNER_INFO: int +CMSG_VERIFY_SIGNER_PUBKEY: int +CMSG_VERIFY_SIGNER_CERT: int +CMSG_VERIFY_SIGNER_CHAIN: int +CMSG_VERIFY_SIGNER_NULL: int +CMSG_OID_GEN_ENCRYPT_KEY_FUNC: str +CMSG_OID_EXPORT_ENCRYPT_KEY_FUNC: str +CMSG_OID_IMPORT_ENCRYPT_KEY_FUNC: str +CMSG_CONTENT_ENCRYPT_PAD_ENCODED_LEN_FLAG: int +CMSG_DEFAULT_INSTALLABLE_FUNC_OID: int +CMSG_CONTENT_ENCRYPT_FREE_PARA_FLAG: int +CMSG_CONTENT_ENCRYPT_RELEASE_CONTEXT_FLAG: int +CMSG_OID_GEN_CONTENT_ENCRYPT_KEY_FUNC: str +CMSG_KEY_TRANS_ENCRYPT_FREE_PARA_FLAG: int +CMSG_OID_EXPORT_KEY_TRANS_FUNC: str +CMSG_KEY_AGREE_ENCRYPT_FREE_PARA_FLAG: int +CMSG_KEY_AGREE_ENCRYPT_FREE_MATERIAL_FLAG: int +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_ALG_FLAG: int +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_PARA_FLAG: int +CMSG_KEY_AGREE_ENCRYPT_FREE_PUBKEY_BITS_FLAG: int +CMSG_OID_EXPORT_KEY_AGREE_FUNC: str +CMSG_OID_IMPORT_KEY_TRANS_FUNC: str +CMSG_OID_IMPORT_KEY_AGREE_FUNC: str +CERT_KEY_PROV_HANDLE_PROP_ID: int +CERT_KEY_PROV_INFO_PROP_ID: int +CERT_SHA1_HASH_PROP_ID: int +CERT_MD5_HASH_PROP_ID: int +CERT_HASH_PROP_ID: int +CERT_KEY_CONTEXT_PROP_ID: int +CERT_KEY_SPEC_PROP_ID: int +CERT_IE30_RESERVED_PROP_ID: int +CERT_PUBKEY_HASH_RESERVED_PROP_ID: int +CERT_ENHKEY_USAGE_PROP_ID: int +CERT_CTL_USAGE_PROP_ID: int +CERT_NEXT_UPDATE_LOCATION_PROP_ID: int +CERT_FRIENDLY_NAME_PROP_ID: int +CERT_PVK_FILE_PROP_ID: int +CERT_DESCRIPTION_PROP_ID: int +CERT_ACCESS_STATE_PROP_ID: int +CERT_SIGNATURE_HASH_PROP_ID: int +CERT_SMART_CARD_DATA_PROP_ID: int +CERT_EFS_PROP_ID: int +CERT_FORTEZZA_DATA_PROP_ID: int +CERT_ARCHIVED_PROP_ID: int +CERT_KEY_IDENTIFIER_PROP_ID: int +CERT_AUTO_ENROLL_PROP_ID: int +CERT_PUBKEY_ALG_PARA_PROP_ID: int +CERT_CROSS_CERT_DIST_POINTS_PROP_ID: int +CERT_ISSUER_PUBLIC_KEY_MD5_HASH_PROP_ID: int +CERT_SUBJECT_PUBLIC_KEY_MD5_HASH_PROP_ID: int +CERT_ENROLLMENT_PROP_ID: int +CERT_DATE_STAMP_PROP_ID: int +CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: int +CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: int +CERT_EXTENDED_ERROR_INFO_PROP_ID: int +CERT_RENEWAL_PROP_ID: int +CERT_ARCHIVED_KEY_HASH_PROP_ID: int +CERT_AUTO_ENROLL_RETRY_PROP_ID: int +CERT_AIA_URL_RETRIEVED_PROP_ID: int +CERT_AUTHORITY_INFO_ACCESS_PROP_ID: int +CERT_BACKED_UP_PROP_ID: int +CERT_OCSP_RESPONSE_PROP_ID: int +CERT_REQUEST_ORIGINATOR_PROP_ID: int +CERT_SOURCE_LOCATION_PROP_ID: int +CERT_SOURCE_URL_PROP_ID: int +CERT_NEW_KEY_PROP_ID: int +CERT_OCSP_CACHE_PREFIX_PROP_ID: int +CERT_SMART_CARD_ROOT_INFO_PROP_ID: int +CERT_NO_AUTO_EXPIRE_CHECK_PROP_ID: int +CERT_NCRYPT_KEY_HANDLE_PROP_ID: int +CERT_HCRYPTPROV_OR_NCRYPT_KEY_HANDLE_PROP_ID: int +CERT_SUBJECT_INFO_ACCESS_PROP_ID: int +CERT_CA_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: int +CERT_CA_DISABLE_CRL_PROP_ID: int +CERT_ROOT_PROGRAM_CERT_POLICIES_PROP_ID: int +CERT_ROOT_PROGRAM_NAME_CONSTRAINTS_PROP_ID: int +CERT_SUBJECT_OCSP_AUTHORITY_INFO_ACCESS_PROP_ID: int +CERT_SUBJECT_DISABLE_CRL_PROP_ID: int +CERT_CEP_PROP_ID: int +CERT_SIGN_HASH_CNG_ALG_PROP_ID: int +CERT_SCARD_PIN_ID_PROP_ID: int +CERT_SCARD_PIN_INFO_PROP_ID: int +CERT_FIRST_RESERVED_PROP_ID: int +CERT_LAST_RESERVED_PROP_ID: int +CERT_FIRST_USER_PROP_ID: int +CERT_LAST_USER_PROP_ID: int +szOID_CERT_PROP_ID_PREFIX: str +szOID_CERT_KEY_IDENTIFIER_PROP_ID: str +szOID_CERT_ISSUER_SERIAL_NUMBER_MD5_HASH_PROP_ID: str +szOID_CERT_SUBJECT_NAME_MD5_HASH_PROP_ID: str +CERT_ACCESS_STATE_WRITE_PERSIST_FLAG: int +CERT_ACCESS_STATE_SYSTEM_STORE_FLAG: int +CERT_ACCESS_STATE_LM_SYSTEM_STORE_FLAG: int +CERT_SET_KEY_PROV_HANDLE_PROP_ID: int +CERT_SET_KEY_CONTEXT_PROP_ID: int +sz_CERT_STORE_PROV_MEMORY: str +sz_CERT_STORE_PROV_FILENAME_W: str +sz_CERT_STORE_PROV_FILENAME: str +sz_CERT_STORE_PROV_SYSTEM_W: str +sz_CERT_STORE_PROV_SYSTEM: str +sz_CERT_STORE_PROV_PKCS7: str +sz_CERT_STORE_PROV_SERIALIZED: str +sz_CERT_STORE_PROV_COLLECTION: str +sz_CERT_STORE_PROV_SYSTEM_REGISTRY_W: str +sz_CERT_STORE_PROV_SYSTEM_REGISTRY: str +sz_CERT_STORE_PROV_PHYSICAL_W: str +sz_CERT_STORE_PROV_PHYSICAL: str +sz_CERT_STORE_PROV_SMART_CARD_W: str +sz_CERT_STORE_PROV_SMART_CARD: str +sz_CERT_STORE_PROV_LDAP_W: str +sz_CERT_STORE_PROV_LDAP: str +CERT_STORE_SIGNATURE_FLAG: int +CERT_STORE_TIME_VALIDITY_FLAG: int +CERT_STORE_REVOCATION_FLAG: int +CERT_STORE_NO_CRL_FLAG: int +CERT_STORE_NO_ISSUER_FLAG: int +CERT_STORE_BASE_CRL_FLAG: int +CERT_STORE_DELTA_CRL_FLAG: int +CERT_STORE_NO_CRYPT_RELEASE_FLAG: int +CERT_STORE_SET_LOCALIZED_NAME_FLAG: int +CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG: int +CERT_STORE_DELETE_FLAG: int +CERT_STORE_UNSAFE_PHYSICAL_FLAG: int +CERT_STORE_SHARE_STORE_FLAG: int +CERT_STORE_SHARE_CONTEXT_FLAG: int +CERT_STORE_MANIFOLD_FLAG: int +CERT_STORE_ENUM_ARCHIVED_FLAG: int +CERT_STORE_UPDATE_KEYID_FLAG: int +CERT_STORE_BACKUP_RESTORE_FLAG: int +CERT_STORE_READONLY_FLAG: int +CERT_STORE_OPEN_EXISTING_FLAG: int +CERT_STORE_CREATE_NEW_FLAG: int +CERT_STORE_MAXIMUM_ALLOWED_FLAG: int +CERT_SYSTEM_STORE_MASK: int +CERT_SYSTEM_STORE_RELOCATE_FLAG: int +CERT_SYSTEM_STORE_UNPROTECTED_FLAG: int +CERT_SYSTEM_STORE_LOCATION_MASK: int +CERT_SYSTEM_STORE_LOCATION_SHIFT: int +CERT_SYSTEM_STORE_CURRENT_USER_ID: int +CERT_SYSTEM_STORE_LOCAL_MACHINE_ID: int +CERT_SYSTEM_STORE_CURRENT_SERVICE_ID: int +CERT_SYSTEM_STORE_SERVICES_ID: int +CERT_SYSTEM_STORE_USERS_ID: int +CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY_ID: int +CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY_ID: int +CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE_ID: int +CERT_SYSTEM_STORE_CURRENT_USER: int +CERT_SYSTEM_STORE_LOCAL_MACHINE: int +CERT_SYSTEM_STORE_CURRENT_SERVICE: int +CERT_SYSTEM_STORE_SERVICES: int +CERT_SYSTEM_STORE_USERS: int +CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY: int +CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY: int +CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE: int +CERT_PROT_ROOT_DISABLE_CURRENT_USER_FLAG: int +CERT_PROT_ROOT_INHIBIT_ADD_AT_INIT_FLAG: int +CERT_PROT_ROOT_INHIBIT_PURGE_LM_FLAG: int +CERT_PROT_ROOT_DISABLE_LM_AUTH_FLAG: int +CERT_PROT_ROOT_ONLY_LM_GPT_FLAG: int +CERT_PROT_ROOT_DISABLE_NT_AUTH_REQUIRED_FLAG: int +CERT_PROT_ROOT_DISABLE_NOT_DEFINED_NAME_CONSTRAINT_FLAG: int +CERT_TRUST_PUB_ALLOW_TRUST_MASK: int +CERT_TRUST_PUB_ALLOW_END_USER_TRUST: int +CERT_TRUST_PUB_ALLOW_MACHINE_ADMIN_TRUST: int +CERT_TRUST_PUB_ALLOW_ENTERPRISE_ADMIN_TRUST: int +CERT_TRUST_PUB_CHECK_PUBLISHER_REV_FLAG: int +CERT_TRUST_PUB_CHECK_TIMESTAMP_REV_FLAG: int +CERT_AUTH_ROOT_AUTO_UPDATE_LOCAL_MACHINE_REGPATH: str +CERT_AUTH_ROOT_AUTO_UPDATE_DISABLE_UNTRUSTED_ROOT_LOGGING_FLAG: int +CERT_AUTH_ROOT_AUTO_UPDATE_DISABLE_PARTIAL_CHAIN_LOGGING_FLAG: int +CERT_AUTH_ROOT_AUTO_UPDATE_ROOT_DIR_URL_VALUE_NAME: str +CERT_AUTH_ROOT_AUTO_UPDATE_SYNC_DELTA_TIME_VALUE_NAME: str +CERT_AUTH_ROOT_AUTO_UPDATE_FLAGS_VALUE_NAME: str +CERT_AUTH_ROOT_CTL_FILENAME: str +CERT_AUTH_ROOT_CTL_FILENAME_A: str +CERT_AUTH_ROOT_CAB_FILENAME: str +CERT_AUTH_ROOT_SEQ_FILENAME: str +CERT_AUTH_ROOT_CERT_EXT: str +CERT_GROUP_POLICY_SYSTEM_STORE_REGPATH: str +CERT_EFSBLOB_REGPATH: str +CERT_EFSBLOB_VALUE_NAME: str +CERT_PROT_ROOT_FLAGS_REGPATH: str +CERT_PROT_ROOT_FLAGS_VALUE_NAME: str +CERT_TRUST_PUB_SAFER_GROUP_POLICY_REGPATH: str +CERT_LOCAL_MACHINE_SYSTEM_STORE_REGPATH: str +CERT_TRUST_PUB_SAFER_LOCAL_MACHINE_REGPATH: str +CERT_TRUST_PUB_AUTHENTICODE_FLAGS_VALUE_NAME: str +CERT_OCM_SUBCOMPONENTS_LOCAL_MACHINE_REGPATH: str +CERT_OCM_SUBCOMPONENTS_ROOT_AUTO_UPDATE_VALUE_NAME: str +CERT_DISABLE_ROOT_AUTO_UPDATE_REGPATH: str +CERT_DISABLE_ROOT_AUTO_UPDATE_VALUE_NAME: str +CERT_REGISTRY_STORE_REMOTE_FLAG: int +CERT_REGISTRY_STORE_SERIALIZED_FLAG: int +CERT_REGISTRY_STORE_CLIENT_GPT_FLAG: int +CERT_REGISTRY_STORE_LM_GPT_FLAG: int +CERT_REGISTRY_STORE_ROAMING_FLAG: int +CERT_REGISTRY_STORE_MY_IE_DIRTY_FLAG: int +CERT_IE_DIRTY_FLAGS_REGPATH: str +CERT_FILE_STORE_COMMIT_ENABLE_FLAG: int +CERT_LDAP_STORE_SIGN_FLAG: int +CERT_LDAP_STORE_AREC_EXCLUSIVE_FLAG: int +CERT_LDAP_STORE_OPENED_FLAG: int +CERT_LDAP_STORE_UNBIND_FLAG: int +CRYPT_OID_OPEN_STORE_PROV_FUNC: str +CERT_STORE_PROV_EXTERNAL_FLAG: int +CERT_STORE_PROV_DELETED_FLAG: int +CERT_STORE_PROV_NO_PERSIST_FLAG: int +CERT_STORE_PROV_SYSTEM_STORE_FLAG: int +CERT_STORE_PROV_LM_SYSTEM_STORE_FLAG: int +CERT_STORE_PROV_CLOSE_FUNC: int +CERT_STORE_PROV_READ_CERT_FUNC: int +CERT_STORE_PROV_WRITE_CERT_FUNC: int +CERT_STORE_PROV_DELETE_CERT_FUNC: int +CERT_STORE_PROV_SET_CERT_PROPERTY_FUNC: int +CERT_STORE_PROV_READ_CRL_FUNC: int +CERT_STORE_PROV_WRITE_CRL_FUNC: int +CERT_STORE_PROV_DELETE_CRL_FUNC: int +CERT_STORE_PROV_SET_CRL_PROPERTY_FUNC: int +CERT_STORE_PROV_READ_CTL_FUNC: int +CERT_STORE_PROV_WRITE_CTL_FUNC: int +CERT_STORE_PROV_DELETE_CTL_FUNC: int +CERT_STORE_PROV_SET_CTL_PROPERTY_FUNC: int +CERT_STORE_PROV_CONTROL_FUNC: int +CERT_STORE_PROV_FIND_CERT_FUNC: int +CERT_STORE_PROV_FREE_FIND_CERT_FUNC: int +CERT_STORE_PROV_GET_CERT_PROPERTY_FUNC: int +CERT_STORE_PROV_FIND_CRL_FUNC: int +CERT_STORE_PROV_FREE_FIND_CRL_FUNC: int +CERT_STORE_PROV_GET_CRL_PROPERTY_FUNC: int +CERT_STORE_PROV_FIND_CTL_FUNC: int +CERT_STORE_PROV_FREE_FIND_CTL_FUNC: int +CERT_STORE_PROV_GET_CTL_PROPERTY_FUNC: int +CERT_STORE_PROV_WRITE_ADD_FLAG: int +CERT_STORE_SAVE_AS_STORE: int +CERT_STORE_SAVE_AS_PKCS7: int +CERT_STORE_SAVE_TO_FILE: int +CERT_STORE_SAVE_TO_MEMORY: int +CERT_STORE_SAVE_TO_FILENAME_A: int +CERT_STORE_SAVE_TO_FILENAME_W: int +CERT_STORE_SAVE_TO_FILENAME: int +CERT_CLOSE_STORE_FORCE_FLAG: int +CERT_CLOSE_STORE_CHECK_FLAG: int +CERT_COMPARE_MASK: int +CERT_COMPARE_SHIFT: int +CERT_COMPARE_ANY: int +CERT_COMPARE_SHA1_HASH: int +CERT_COMPARE_NAME: int +CERT_COMPARE_ATTR: int +CERT_COMPARE_MD5_HASH: int +CERT_COMPARE_PROPERTY: int +CERT_COMPARE_PUBLIC_KEY: int +CERT_COMPARE_HASH: int +CERT_COMPARE_NAME_STR_A: int +CERT_COMPARE_NAME_STR_W: int +CERT_COMPARE_KEY_SPEC: int +CERT_COMPARE_ENHKEY_USAGE: int +CERT_COMPARE_CTL_USAGE: int +CERT_COMPARE_SUBJECT_CERT: int +CERT_COMPARE_ISSUER_OF: int +CERT_COMPARE_EXISTING: int +CERT_COMPARE_SIGNATURE_HASH: int +CERT_COMPARE_KEY_IDENTIFIER: int +CERT_COMPARE_CERT_ID: int +CERT_COMPARE_CROSS_CERT_DIST_POINTS: int +CERT_COMPARE_PUBKEY_MD5_HASH: int +CERT_FIND_ANY: int +CERT_FIND_SHA1_HASH: int +CERT_FIND_MD5_HASH: int +CERT_FIND_SIGNATURE_HASH: int +CERT_FIND_KEY_IDENTIFIER: int +CERT_FIND_HASH: int +CERT_FIND_PROPERTY: int +CERT_FIND_PUBLIC_KEY: int +CERT_FIND_SUBJECT_NAME: int +CERT_FIND_SUBJECT_ATTR: int +CERT_FIND_ISSUER_NAME: int +CERT_FIND_ISSUER_ATTR: int +CERT_FIND_SUBJECT_STR_A: int +CERT_FIND_SUBJECT_STR_W: int +CERT_FIND_SUBJECT_STR: int +CERT_FIND_ISSUER_STR_A: int +CERT_FIND_ISSUER_STR_W: int +CERT_FIND_ISSUER_STR: int +CERT_FIND_KEY_SPEC: int +CERT_FIND_ENHKEY_USAGE: int +CERT_FIND_CTL_USAGE: int +CERT_FIND_SUBJECT_CERT: int +CERT_FIND_ISSUER_OF: int +CERT_FIND_EXISTING: int +CERT_FIND_CERT_ID: int +CERT_FIND_CROSS_CERT_DIST_POINTS: int +CERT_FIND_PUBKEY_MD5_HASH: int +CERT_FIND_OPTIONAL_ENHKEY_USAGE_FLAG: int +CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG: int +CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG: int +CERT_FIND_NO_ENHKEY_USAGE_FLAG: int +CERT_FIND_OR_ENHKEY_USAGE_FLAG: int +CERT_FIND_VALID_ENHKEY_USAGE_FLAG: int +CERT_FIND_OPTIONAL_CTL_USAGE_FLAG: int +CERT_FIND_EXT_ONLY_CTL_USAGE_FLAG: int +CERT_FIND_PROP_ONLY_CTL_USAGE_FLAG: int +CERT_FIND_NO_CTL_USAGE_FLAG: int +CERT_FIND_OR_CTL_USAGE_FLAG: int +CERT_FIND_VALID_CTL_USAGE_FLAG: int +CERT_SET_PROPERTY_IGNORE_PERSIST_ERROR_FLAG: int +CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG: int +CTL_ENTRY_FROM_PROP_CHAIN_FLAG: int +CRL_FIND_ANY: int +CRL_FIND_ISSUED_BY: int +CRL_FIND_EXISTING: int +CRL_FIND_ISSUED_FOR: int +CRL_FIND_ISSUED_BY_AKI_FLAG: int +CRL_FIND_ISSUED_BY_SIGNATURE_FLAG: int +CRL_FIND_ISSUED_BY_DELTA_FLAG: int +CRL_FIND_ISSUED_BY_BASE_FLAG: int +CERT_STORE_ADD_NEW: int +CERT_STORE_ADD_USE_EXISTING: int +CERT_STORE_ADD_REPLACE_EXISTING: int +CERT_STORE_ADD_ALWAYS: int +CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES: int +CERT_STORE_ADD_NEWER: int +CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES: int +CERT_STORE_CERTIFICATE_CONTEXT: int +CERT_STORE_CRL_CONTEXT: int +CERT_STORE_CTL_CONTEXT: int +CERT_STORE_ALL_CONTEXT_FLAG: int +CERT_STORE_CERTIFICATE_CONTEXT_FLAG: int +CERT_STORE_CRL_CONTEXT_FLAG: int +CERT_STORE_CTL_CONTEXT_FLAG: int +CTL_ANY_SUBJECT_TYPE: int +CTL_CERT_SUBJECT_TYPE: int +CTL_FIND_ANY: int +CTL_FIND_SHA1_HASH: int +CTL_FIND_MD5_HASH: int +CTL_FIND_USAGE: int +CTL_FIND_SUBJECT: int +CTL_FIND_EXISTING: int +CTL_FIND_SAME_USAGE_FLAG: int +CERT_STORE_CTRL_RESYNC: int +CERT_STORE_CTRL_NOTIFY_CHANGE: int +CERT_STORE_CTRL_COMMIT: int +CERT_STORE_CTRL_AUTO_RESYNC: int +CERT_STORE_CTRL_CANCEL_NOTIFY: int +CERT_STORE_CTRL_INHIBIT_DUPLICATE_HANDLE_FLAG: int +CERT_STORE_CTRL_COMMIT_FORCE_FLAG: int +CERT_STORE_CTRL_COMMIT_CLEAR_FLAG: int +CERT_STORE_LOCALIZED_NAME_PROP_ID: int +CERT_CREATE_CONTEXT_NOCOPY_FLAG: int +CERT_CREATE_CONTEXT_SORTED_FLAG: int +CERT_CREATE_CONTEXT_NO_HCRYPTMSG_FLAG: int +CERT_CREATE_CONTEXT_NO_ENTRY_FLAG: int +CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG: int +CERT_PHYSICAL_STORE_OPEN_DISABLE_FLAG: int +CERT_PHYSICAL_STORE_REMOTE_OPEN_DISABLE_FLAG: int +CERT_PHYSICAL_STORE_INSERT_COMPUTER_NAME_ENABLE_FLAG: int +CERT_PHYSICAL_STORE_PREDEFINED_ENUM_FLAG: int +CERT_PHYSICAL_STORE_DEFAULT_NAME: str +CERT_PHYSICAL_STORE_GROUP_POLICY_NAME: str +CERT_PHYSICAL_STORE_LOCAL_MACHINE_NAME: str +CERT_PHYSICAL_STORE_DS_USER_CERTIFICATE_NAME: str +CERT_PHYSICAL_STORE_LOCAL_MACHINE_GROUP_POLICY_NAME: str +CERT_PHYSICAL_STORE_ENTERPRISE_NAME: str +CERT_PHYSICAL_STORE_AUTH_ROOT_NAME: str +CERT_PHYSICAL_STORE_SMART_CARD_NAME: str +CRYPT_OID_OPEN_SYSTEM_STORE_PROV_FUNC: str +CRYPT_OID_REGISTER_SYSTEM_STORE_FUNC: str +CRYPT_OID_UNREGISTER_SYSTEM_STORE_FUNC: str +CRYPT_OID_ENUM_SYSTEM_STORE_FUNC: str +CRYPT_OID_REGISTER_PHYSICAL_STORE_FUNC: str +CRYPT_OID_UNREGISTER_PHYSICAL_STORE_FUNC: str +CRYPT_OID_ENUM_PHYSICAL_STORE_FUNC: str +CRYPT_OID_SYSTEM_STORE_LOCATION_VALUE_NAME: str +CMSG_TRUSTED_SIGNER_FLAG: int +CMSG_SIGNER_ONLY_FLAG: int +CMSG_USE_SIGNER_INDEX_FLAG: int +CMSG_CMS_ENCAPSULATED_CTL_FLAG: int +CMSG_ENCODE_SORTED_CTL_FLAG: int +CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG: int +CERT_VERIFY_INHIBIT_CTL_UPDATE_FLAG: int +CERT_VERIFY_TRUSTED_SIGNERS_FLAG: int +CERT_VERIFY_NO_TIME_CHECK_FLAG: int +CERT_VERIFY_ALLOW_MORE_USAGE_FLAG: int +CERT_VERIFY_UPDATED_CTL_FLAG: int +CERT_CONTEXT_REVOCATION_TYPE: int +CERT_VERIFY_REV_CHAIN_FLAG: int +CERT_VERIFY_CACHE_ONLY_BASED_REVOCATION: int +CERT_VERIFY_REV_ACCUMULATIVE_TIMEOUT_FLAG: int +CERT_UNICODE_IS_RDN_ATTRS_FLAG: int +CERT_CASE_INSENSITIVE_IS_RDN_ATTRS_FLAG: int +CRYPT_VERIFY_CERT_SIGN_SUBJECT_BLOB: int +CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT: int +CRYPT_VERIFY_CERT_SIGN_SUBJECT_CRL: int +CRYPT_VERIFY_CERT_SIGN_ISSUER_PUBKEY: int +CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT: int +CRYPT_VERIFY_CERT_SIGN_ISSUER_CHAIN: int +CRYPT_VERIFY_CERT_SIGN_ISSUER_NULL: int +CRYPT_DEFAULT_CONTEXT_AUTO_RELEASE_FLAG: int +CRYPT_DEFAULT_CONTEXT_PROCESS_FLAG: int +CRYPT_DEFAULT_CONTEXT_CERT_SIGN_OID: int +CRYPT_DEFAULT_CONTEXT_MULTI_CERT_SIGN_OID: int +CRYPT_OID_EXPORT_PUBLIC_KEY_INFO_FUNC: str +CRYPT_OID_IMPORT_PUBLIC_KEY_INFO_FUNC: str +CRYPT_ACQUIRE_CACHE_FLAG: int +CRYPT_ACQUIRE_USE_PROV_INFO_FLAG: int +CRYPT_ACQUIRE_COMPARE_KEY_FLAG: int +CRYPT_ACQUIRE_SILENT_FLAG: int +CRYPT_FIND_USER_KEYSET_FLAG: int +CRYPT_FIND_MACHINE_KEYSET_FLAG: int +CRYPT_FIND_SILENT_KEYSET_FLAG: int +CRYPT_OID_IMPORT_PRIVATE_KEY_INFO_FUNC: str +CRYPT_OID_EXPORT_PRIVATE_KEY_INFO_FUNC: str +CRYPT_DELETE_KEYSET: int +CERT_SIMPLE_NAME_STR: int +CERT_OID_NAME_STR: int +CERT_X500_NAME_STR: int +CERT_NAME_STR_SEMICOLON_FLAG: int +CERT_NAME_STR_NO_PLUS_FLAG: int +CERT_NAME_STR_NO_QUOTING_FLAG: int +CERT_NAME_STR_CRLF_FLAG: int +CERT_NAME_STR_COMMA_FLAG: int +CERT_NAME_STR_REVERSE_FLAG: int +CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG: int +CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG: int +CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG: int +CERT_NAME_EMAIL_TYPE: int +CERT_NAME_RDN_TYPE: int +CERT_NAME_ATTR_TYPE: int +CERT_NAME_SIMPLE_DISPLAY_TYPE: int +CERT_NAME_FRIENDLY_DISPLAY_TYPE: int +CERT_NAME_DNS_TYPE: int +CERT_NAME_URL_TYPE: int +CERT_NAME_UPN_TYPE: int +CERT_NAME_ISSUER_FLAG: int +CERT_NAME_DISABLE_IE4_UTF8_FLAG: int +CRYPT_MESSAGE_BARE_CONTENT_OUT_FLAG: int +CRYPT_MESSAGE_ENCAPSULATED_CONTENT_OUT_FLAG: int +CRYPT_MESSAGE_KEYID_SIGNER_FLAG: int +CRYPT_MESSAGE_SILENT_KEYSET_FLAG: int +CRYPT_MESSAGE_KEYID_RECIPIENT_FLAG: int +CERT_QUERY_OBJECT_FILE: int +CERT_QUERY_OBJECT_BLOB: int +CERT_QUERY_CONTENT_CERT: int +CERT_QUERY_CONTENT_CTL: int +CERT_QUERY_CONTENT_CRL: int +CERT_QUERY_CONTENT_SERIALIZED_STORE: int +CERT_QUERY_CONTENT_SERIALIZED_CERT: int +CERT_QUERY_CONTENT_SERIALIZED_CTL: int +CERT_QUERY_CONTENT_SERIALIZED_CRL: int +CERT_QUERY_CONTENT_PKCS7_SIGNED: int +CERT_QUERY_CONTENT_PKCS7_UNSIGNED: int +CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED: int +CERT_QUERY_CONTENT_PKCS10: int +CERT_QUERY_CONTENT_PFX: int +CERT_QUERY_CONTENT_CERT_PAIR: int +CERT_QUERY_CONTENT_FLAG_CERT: int +CERT_QUERY_CONTENT_FLAG_CTL: int +CERT_QUERY_CONTENT_FLAG_CRL: int +CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE: int +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT: int +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL: int +CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL: int +CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED: int +CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED: int +CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED: int +CERT_QUERY_CONTENT_FLAG_PKCS10: int +CERT_QUERY_CONTENT_FLAG_PFX: int +CERT_QUERY_CONTENT_FLAG_CERT_PAIR: int +CERT_QUERY_CONTENT_FLAG_ALL: int +CERT_QUERY_FORMAT_BINARY: int +CERT_QUERY_FORMAT_BASE64_ENCODED: int +CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED: int +CERT_QUERY_FORMAT_FLAG_BINARY: int +CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED: int +CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED: int +CERT_QUERY_FORMAT_FLAG_ALL: int +CREDENTIAL_OID_PASSWORD_CREDENTIALS_A: int +CREDENTIAL_OID_PASSWORD_CREDENTIALS_W: int +CREDENTIAL_OID_PASSWORD_CREDENTIALS: int +SCHEME_OID_RETRIEVE_ENCODED_OBJECT_FUNC: str +SCHEME_OID_RETRIEVE_ENCODED_OBJECTW_FUNC: str +CONTEXT_OID_CREATE_OBJECT_CONTEXT_FUNC: str +CONTEXT_OID_CERTIFICATE: int +CONTEXT_OID_CRL: int +CONTEXT_OID_CTL: int +CONTEXT_OID_PKCS7: int +CONTEXT_OID_CAPI2_ANY: int +CONTEXT_OID_OCSP_RESP: int +CRYPT_RETRIEVE_MULTIPLE_OBJECTS: int +CRYPT_CACHE_ONLY_RETRIEVAL: int +CRYPT_WIRE_ONLY_RETRIEVAL: int +CRYPT_DONT_CACHE_RESULT: int +CRYPT_ASYNC_RETRIEVAL: int +CRYPT_STICKY_CACHE_RETRIEVAL: int +CRYPT_LDAP_SCOPE_BASE_ONLY_RETRIEVAL: int +CRYPT_OFFLINE_CHECK_RETRIEVAL: int +CRYPT_LDAP_INSERT_ENTRY_ATTRIBUTE: int +CRYPT_LDAP_SIGN_RETRIEVAL: int +CRYPT_NO_AUTH_RETRIEVAL: int +CRYPT_LDAP_AREC_EXCLUSIVE_RETRIEVAL: int +CRYPT_AIA_RETRIEVAL: int +CRYPT_VERIFY_CONTEXT_SIGNATURE: int +CRYPT_VERIFY_DATA_HASH: int +CRYPT_KEEP_TIME_VALID: int +CRYPT_DONT_VERIFY_SIGNATURE: int +CRYPT_DONT_CHECK_TIME_VALIDITY: int +CRYPT_CHECK_FRESHNESS_TIME_VALIDITY: int +CRYPT_ACCUMULATIVE_TIMEOUT: int +CRYPT_PARAM_ASYNC_RETRIEVAL_COMPLETION: int +CRYPT_PARAM_CANCEL_ASYNC_RETRIEVAL: int +CRYPT_GET_URL_FROM_PROPERTY: int +CRYPT_GET_URL_FROM_EXTENSION: int +CRYPT_GET_URL_FROM_UNAUTH_ATTRIBUTE: int +CRYPT_GET_URL_FROM_AUTH_ATTRIBUTE: int +URL_OID_GET_OBJECT_URL_FUNC: str +TIME_VALID_OID_GET_OBJECT_FUNC: str +TIME_VALID_OID_FLUSH_OBJECT_FUNC: str +TIME_VALID_OID_GET_CTL: int +TIME_VALID_OID_GET_CRL: int +TIME_VALID_OID_GET_CRL_FROM_CERT: int +TIME_VALID_OID_GET_FRESHEST_CRL_FROM_CERT: int +TIME_VALID_OID_GET_FRESHEST_CRL_FROM_CRL: int +TIME_VALID_OID_FLUSH_CTL: int +TIME_VALID_OID_FLUSH_CRL: int +TIME_VALID_OID_FLUSH_CRL_FROM_CERT: int +TIME_VALID_OID_FLUSH_FRESHEST_CRL_FROM_CERT: int +TIME_VALID_OID_FLUSH_FRESHEST_CRL_FROM_CRL: int +CRYPTPROTECT_PROMPT_ON_UNPROTECT: int +CRYPTPROTECT_PROMPT_ON_PROTECT: int +CRYPTPROTECT_PROMPT_RESERVED: int +CRYPTPROTECT_PROMPT_STRONG: int +CRYPTPROTECT_PROMPT_REQUIRE_STRONG: int +CRYPTPROTECT_UI_FORBIDDEN: int +CRYPTPROTECT_LOCAL_MACHINE: int +CRYPTPROTECT_CRED_SYNC: int +CRYPTPROTECT_AUDIT: int +CRYPTPROTECT_NO_RECOVERY: int +CRYPTPROTECT_VERIFY_PROTECTION: int +CRYPTPROTECT_CRED_REGENERATE: int +CRYPTPROTECT_FIRST_RESERVED_FLAGVAL: int +CRYPTPROTECT_LAST_RESERVED_FLAGVAL: int +CRYPTPROTECTMEMORY_BLOCK_SIZE: int +CRYPTPROTECTMEMORY_SAME_PROCESS: int +CRYPTPROTECTMEMORY_CROSS_PROCESS: int +CRYPTPROTECTMEMORY_SAME_LOGON: int +CERT_CREATE_SELFSIGN_NO_SIGN: int +CERT_CREATE_SELFSIGN_NO_KEY_INFO: int +CRYPT_KEYID_MACHINE_FLAG: int +CRYPT_KEYID_ALLOC_FLAG: int +CRYPT_KEYID_DELETE_FLAG: int +CRYPT_KEYID_SET_NEW_FLAG: int +CERT_CHAIN_MAX_AIA_URL_COUNT_IN_CERT_DEFAULT: int +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_COUNT_PER_CHAIN_DEFAULT: int +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_BYTE_COUNT_DEFAULT: int +CERT_CHAIN_MAX_AIA_URL_RETRIEVAL_CERT_COUNT_DEFAULT: int +CERT_CHAIN_CACHE_END_CERT: int +CERT_CHAIN_THREAD_STORE_SYNC: int +CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL: int +CERT_CHAIN_USE_LOCAL_MACHINE_STORE: int +CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE: int +CERT_CHAIN_ENABLE_SHARE_STORE: int +CERT_TRUST_NO_ERROR: int +CERT_TRUST_IS_NOT_TIME_VALID: int +CERT_TRUST_IS_NOT_TIME_NESTED: int +CERT_TRUST_IS_REVOKED: int +CERT_TRUST_IS_NOT_SIGNATURE_VALID: int +CERT_TRUST_IS_NOT_VALID_FOR_USAGE: int +CERT_TRUST_IS_UNTRUSTED_ROOT: int +CERT_TRUST_REVOCATION_STATUS_UNKNOWN: int +CERT_TRUST_IS_CYCLIC: int +CERT_TRUST_INVALID_EXTENSION: int +CERT_TRUST_INVALID_POLICY_CONSTRAINTS: int +CERT_TRUST_INVALID_BASIC_CONSTRAINTS: int +CERT_TRUST_INVALID_NAME_CONSTRAINTS: int +CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT: int +CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT: int +CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT: int +CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT: int +CERT_TRUST_IS_OFFLINE_REVOCATION: int +CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY: int +CERT_TRUST_IS_PARTIAL_CHAIN: int +CERT_TRUST_CTL_IS_NOT_TIME_VALID: int +CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID: int +CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE: int +CERT_TRUST_HAS_EXACT_MATCH_ISSUER: int +CERT_TRUST_HAS_KEY_MATCH_ISSUER: int +CERT_TRUST_HAS_NAME_MATCH_ISSUER: int +CERT_TRUST_IS_SELF_SIGNED: int +CERT_TRUST_HAS_PREFERRED_ISSUER: int +CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY: int +CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS: int +CERT_TRUST_IS_COMPLEX_CHAIN: int +USAGE_MATCH_TYPE_AND: int +USAGE_MATCH_TYPE_OR: int +CERT_CHAIN_REVOCATION_CHECK_END_CERT: int +CERT_CHAIN_REVOCATION_CHECK_CHAIN: int +CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT: int +CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY: int +CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT: int +CERT_CHAIN_DISABLE_PASS1_QUALITY_FILTERING: int +CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS: int +CERT_CHAIN_DISABLE_AUTH_ROOT_AUTO_UPDATE: int +CERT_CHAIN_TIMESTAMP_TIME: int +REVOCATION_OID_CRL_REVOCATION: int +CERT_CHAIN_FIND_BY_ISSUER: int +CERT_CHAIN_FIND_BY_ISSUER_COMPARE_KEY_FLAG: int +CERT_CHAIN_FIND_BY_ISSUER_COMPLEX_CHAIN_FLAG: int +CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_URL_FLAG: int +CERT_CHAIN_FIND_BY_ISSUER_LOCAL_MACHINE_FLAG: int +CERT_CHAIN_FIND_BY_ISSUER_NO_KEY_FLAG: int +CERT_CHAIN_FIND_BY_ISSUER_CACHE_ONLY_FLAG: int +CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG: int +CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG: int +CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG: int +CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG: int +CERT_CHAIN_POLICY_IGNORE_ALL_NOT_TIME_VALID_FLAGS: int +CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG: int +CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG: int +CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG: int +CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG: int +CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG: int +CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG: int +CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG: int +CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG: int +CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS: int +CERT_CHAIN_POLICY_ALLOW_TESTROOT_FLAG: int +CERT_CHAIN_POLICY_TRUST_TESTROOT_FLAG: int +CRYPT_OID_VERIFY_CERTIFICATE_CHAIN_POLICY_FUNC: str +AUTHTYPE_CLIENT: int +AUTHTYPE_SERVER: int +BASIC_CONSTRAINTS_CERT_CHAIN_POLICY_CA_FLAG: int +BASIC_CONSTRAINTS_CERT_CHAIN_POLICY_END_ENTITY_FLAG: int +MICROSOFT_ROOT_CERT_CHAIN_POLICY_ENABLE_TEST_ROOT_FLAG: int +CRYPT_STRING_BASE64HEADER: int +CRYPT_STRING_BASE64: int +CRYPT_STRING_BINARY: int +CRYPT_STRING_BASE64REQUESTHEADER: int +CRYPT_STRING_HEX: int +CRYPT_STRING_HEXASCII: int +CRYPT_STRING_BASE64_ANY: int +CRYPT_STRING_ANY: int +CRYPT_STRING_HEX_ANY: int +CRYPT_STRING_BASE64X509CRLHEADER: int +CRYPT_STRING_HEXADDR: int +CRYPT_STRING_HEXASCIIADDR: int +CRYPT_STRING_NOCR: int +CRYPT_USER_KEYSET: int +PKCS12_IMPORT_RESERVED_MASK: int +REPORT_NO_PRIVATE_KEY: int +REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY: int +EXPORT_PRIVATE_KEYS: int +PKCS12_EXPORT_RESERVED_MASK: int +CERT_STORE_PROV_MSG: int +CERT_STORE_PROV_MEMORY: int +CERT_STORE_PROV_FILE: int +CERT_STORE_PROV_REG: int +CERT_STORE_PROV_PKCS7: int +CERT_STORE_PROV_SERIALIZED: int +CERT_STORE_PROV_FILENAME: int +CERT_STORE_PROV_SYSTEM: int +CERT_STORE_PROV_COLLECTION: int +CERT_STORE_PROV_SYSTEM_REGISTRY: int +CERT_STORE_PROV_PHYSICAL: int +CERT_STORE_PROV_SMART_CARD: int +CERT_STORE_PROV_LDAP: int +URL_OID_CERTIFICATE_ISSUER: int +URL_OID_CERTIFICATE_CRL_DIST_POINT: int +URL_OID_CTL_ISSUER: int +URL_OID_CTL_NEXT_UPDATE: int +URL_OID_CRL_ISSUER: int +URL_OID_CERTIFICATE_FRESHEST_CRL: int +URL_OID_CRL_FRESHEST_CRL: int +URL_OID_CROSS_CERT_DIST_POINT: int +URL_OID_CERTIFICATE_OCSP: int +URL_OID_CERTIFICATE_OCSP_AND_CRL_DIST_POINT: int +URL_OID_CERTIFICATE_CRL_DIST_POINT_AND_OCSP: int +URL_OID_CROSS_CERT_SUBJECT_INFO_ACCESS: int +URL_OID_CERTIFICATE_ONLY_OCSP: int +CMSG_CTRL_MAIL_LIST_DECRYPT: int +CMSG_MAIL_LIST_ENCRYPT_FREE_PARA_FLAG: int +CMSG_MAIL_LIST_HANDLE_KEY_CHOICE: int +CMSG_MAIL_LIST_RECIPIENT: int +CMSG_MAIL_LIST_VERSION: int +CMSG_OID_EXPORT_MAIL_LIST_FUNC: str +CMSG_OID_IMPORT_MAIL_LIST_FUNC: str +CTL_FIND_NO_LIST_ID_CBDATA: int +szOID_AUTHORITY_REVOCATION_LIST: str +szOID_CERTIFICATE_REVOCATION_LIST: str +szOID_ROOT_LIST_SIGNER: str diff --git a/stubs/pywin32/win32/lib/win32evtlogutil.pyi b/stubs/pywin32/win32/lib/win32evtlogutil.pyi new file mode 100644 index 000000000000..7ab2cff5e46b --- /dev/null +++ b/stubs/pywin32/win32/lib/win32evtlogutil.pyi @@ -0,0 +1,25 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +import win32api + +error = win32api.error +langid: Incomplete + +def AddSourceToRegistry( + appName, msgDLL=None, eventLogType: str = "Application", eventLogFlags=None, categoryDLL=None, categoryCount: int = 0 +) -> None: ... +def RemoveSourceFromRegistry(appName, eventLogType: str = ...) -> None: ... +def ReportEvent( + appName: str, + eventID: int, + eventCategory: int = ..., + eventType: int = ..., + strings: Iterable[str] | None = ..., + data: bytes | None = ..., + sid: _win32typing.PySID | None = ..., +) -> None: ... +def FormatMessage(eventLogRecord: _win32typing.PyEventLogRecord, logType: str = ...): ... +def SafeFormatMessage(eventLogRecord, logType: Incomplete | None = ...): ... +def FeedEventLogRecords(feeder, machineName: Incomplete | None = ..., logName: str = ..., readFlags: Incomplete | None = ...): ... diff --git a/stubs/pywin32/win32/lib/win32gui_struct.pyi b/stubs/pywin32/win32/lib/win32gui_struct.pyi new file mode 100644 index 000000000000..fd8708e0f738 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32gui_struct.pyi @@ -0,0 +1,210 @@ +from _typeshed import Incomplete, ReadableBuffer +from array import array +from typing import NamedTuple, type_check_only + +is64bit: bool + +@type_check_only +class _WMNOTIFY(NamedTuple): + hwndFrom: Incomplete + idFrom: Incomplete + code: Incomplete + +def UnpackWMNOTIFY(lparam: int) -> _WMNOTIFY: ... + +@type_check_only +class _NMITEMACTIVATE(NamedTuple): + hwndFrom: Incomplete + idFrom: Incomplete + code: Incomplete + iItem: Incomplete + iSubItem: Incomplete + uNewState: Incomplete + uOldState: Incomplete + uChanged: Incomplete + actionx: Incomplete + actiony: Incomplete + lParam: Incomplete + +def UnpackNMITEMACTIVATE(lparam) -> _NMITEMACTIVATE: ... +def PackMENUITEMINFO( + fType: Incomplete | None = ..., + fState: Incomplete | None = ..., + wID: Incomplete | None = ..., + hSubMenu: Incomplete | None = ..., + hbmpChecked: Incomplete | None = ..., + hbmpUnchecked: Incomplete | None = ..., + dwItemData: Incomplete | None = ..., + text: Incomplete | None = ..., + hbmpItem: Incomplete | None = ..., + dwTypeData: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _MENUITEMINFO(NamedTuple): + fType: int | None + fState: int | None + wID: int | None + hSubMenu: int | None + hbmpChecked: int | None + hbmpUnchecked: int | None + dwItemData: int | None + text: str | None + hbmpItem: int | None + +def UnpackMENUITEMINFO(s: ReadableBuffer) -> _MENUITEMINFO: ... +def EmptyMENUITEMINFO(mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[array[int]]]: ... +def PackMENUINFO( + dwStyle: Incomplete | None = ..., + cyMax: Incomplete | None = ..., + hbrBack: Incomplete | None = ..., + dwContextHelpID: Incomplete | None = ..., + dwMenuData: Incomplete | None = ..., + fMask: int = ..., +) -> array[int]: ... + +@type_check_only +class _MENUINFO(NamedTuple): + dwStyle: Incomplete | None + cyMax: Incomplete | None + hbrBack: Incomplete | None + dwContextHelpID: Incomplete | None + dwMenuData: Incomplete | None + +def UnpackMENUINFO(s: ReadableBuffer) -> _MENUINFO: ... +def EmptyMENUINFO(mask: Incomplete | None = ...) -> array[int]: ... +def PackTVINSERTSTRUCT(parent, insertAfter, tvitem) -> tuple[bytes, list[Incomplete]]: ... +def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param) -> tuple[array[int], list[Incomplete]]: ... +def EmptyTVITEM(hitem, mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _TVITEM(NamedTuple): + item_hItem: Incomplete + item_state: Incomplete | None + item_stateMask: Incomplete | None + text: Incomplete | None + item_image: Incomplete | None + item_selimage: Incomplete | None + item_cChildren: Incomplete | None + item_param: Incomplete | None + +def UnpackTVITEM(buffer: ReadableBuffer) -> _TVITEM: ... + +@type_check_only +class _TVNOTIFY(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + action: Incomplete + item_old: _TVITEM + item_new: _TVITEM + +def UnpackTVNOTIFY(lparam: int) -> _TVNOTIFY: ... + +@type_check_only +class _TVDISPINFO(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: _TVITEM + +def UnpackTVDISPINFO(lparam: int) -> _TVDISPINFO: ... +def PackLVITEM( + item: Incomplete | None = ..., + subItem: Incomplete | None = ..., + state: Incomplete | None = ..., + stateMask: Incomplete | None = ..., + text: Incomplete | None = ..., + image: Incomplete | None = ..., + param: Incomplete | None = ..., + indent: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _LVITEM(NamedTuple): + item_item: Incomplete + item_subItem: Incomplete + item_state: Incomplete | None + item_stateMask: Incomplete | None + text: Incomplete | None + item_image: Incomplete | None + item_param: Incomplete | None + item_indent: Incomplete | None + +def UnpackLVITEM(buffer: ReadableBuffer) -> _LVITEM: ... + +@type_check_only +class _LVDISPINFO(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: _LVITEM + +def UnpackLVDISPINFO(lparam: int) -> _LVDISPINFO: ... + +@type_check_only +class _UnpackLVNOTIFY(NamedTuple): + hwndFrom: Incomplete + id: Incomplete + code: Incomplete + item: Incomplete + subitem: Incomplete + newstate: Incomplete + oldstate: Incomplete + changed: Incomplete + pt: tuple[Incomplete, Incomplete] + lparam: Incomplete + +def UnpackLVNOTIFY(lparam: int) -> _UnpackLVNOTIFY: ... +def EmptyLVITEM( + item, subitem, mask: Incomplete | None = ..., text_buf_size: int = ... +) -> tuple[array[int], list[Incomplete]]: ... +def PackLVCOLUMN( + fmt: Incomplete | None = ..., + cx: Incomplete | None = ..., + text: Incomplete | None = ..., + subItem: Incomplete | None = ..., + image: Incomplete | None = ..., + order: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... + +@type_check_only +class _LVCOLUMN(NamedTuple): + fmt: Incomplete | None + cx: Incomplete | None + text: Incomplete | None + subItem: Incomplete | None + image: Incomplete | None + order: Incomplete | None + +def UnpackLVCOLUMN(lparam: ReadableBuffer) -> _LVCOLUMN: ... +def EmptyLVCOLUMN(mask: Incomplete | None = ..., text_buf_size: int = ...) -> tuple[array[int], list[Incomplete]]: ... +def PackLVHITTEST(pt) -> tuple[array[int], None]: ... + +@type_check_only +class _LVHITTEST(NamedTuple): + pt: tuple[Incomplete, Incomplete] + flags: Incomplete + item: Incomplete + subitem: Incomplete + +def UnpackLVHITTEST(buf: ReadableBuffer) -> tuple[tuple[Incomplete, Incomplete], Incomplete, Incomplete, Incomplete]: ... +def PackHDITEM( + cxy: Incomplete | None = ..., + text: Incomplete | None = ..., + hbm: Incomplete | None = ..., + fmt: Incomplete | None = ..., + param: Incomplete | None = ..., + image: Incomplete | None = ..., + order: Incomplete | None = ..., +) -> tuple[array[int], list[Incomplete]]: ... +def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=...) -> bytes: ... +def PackDEV_BROADCAST_HANDLE(handle, hdevnotify: int = ..., guid=..., name_offset: int = ..., data=...) -> bytes: ... +def PackDEV_BROADCAST_VOLUME(unitmask, flags) -> bytes: ... +def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name: str = ...) -> bytes: ... + +class DEV_BROADCAST_INFO: + devicetype: Incomplete + def __init__(self, devicetype, **kw) -> None: ... + +def UnpackDEV_BROADCAST(lparam: int) -> DEV_BROADCAST_INFO | None: ... diff --git a/stubs/pywin32/win32/lib/win32inetcon.pyi b/stubs/pywin32/win32/lib/win32inetcon.pyi new file mode 100644 index 000000000000..10e562a2c50d --- /dev/null +++ b/stubs/pywin32/win32/lib/win32inetcon.pyi @@ -0,0 +1,989 @@ +INTERNET_INVALID_PORT_NUMBER: int +INTERNET_DEFAULT_FTP_PORT: int +INTERNET_DEFAULT_GOPHER_PORT: int +INTERNET_DEFAULT_HTTP_PORT: int +INTERNET_DEFAULT_HTTPS_PORT: int +INTERNET_DEFAULT_SOCKS_PORT: int +INTERNET_MAX_HOST_NAME_LENGTH: int +INTERNET_MAX_USER_NAME_LENGTH: int +INTERNET_MAX_PASSWORD_LENGTH: int +INTERNET_MAX_PORT_NUMBER_LENGTH: int +INTERNET_MAX_PORT_NUMBER_VALUE: int +INTERNET_MAX_PATH_LENGTH: int +INTERNET_MAX_SCHEME_LENGTH: int +INTERNET_KEEP_ALIVE_ENABLED: int +INTERNET_KEEP_ALIVE_DISABLED: int +INTERNET_REQFLAG_FROM_CACHE: int +INTERNET_REQFLAG_ASYNC: int +INTERNET_REQFLAG_VIA_PROXY: int +INTERNET_REQFLAG_NO_HEADERS: int +INTERNET_REQFLAG_PASSIVE: int +INTERNET_REQFLAG_CACHE_WRITE_DISABLED: int +INTERNET_REQFLAG_NET_TIMEOUT: int +INTERNET_FLAG_RELOAD: int +INTERNET_FLAG_RAW_DATA: int +INTERNET_FLAG_EXISTING_CONNECT: int +INTERNET_FLAG_ASYNC: int +INTERNET_FLAG_PASSIVE: int +INTERNET_FLAG_NO_CACHE_WRITE: int +INTERNET_FLAG_DONT_CACHE: int +INTERNET_FLAG_MAKE_PERSISTENT: int +INTERNET_FLAG_FROM_CACHE: int +INTERNET_FLAG_OFFLINE: int +INTERNET_FLAG_SECURE: int +INTERNET_FLAG_KEEP_CONNECTION: int +INTERNET_FLAG_NO_AUTO_REDIRECT: int +INTERNET_FLAG_READ_PREFETCH: int +INTERNET_FLAG_NO_COOKIES: int +INTERNET_FLAG_NO_AUTH: int +INTERNET_FLAG_RESTRICTED_ZONE: int +INTERNET_FLAG_CACHE_IF_NET_FAIL: int +INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP: int +INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS: int +INTERNET_FLAG_IGNORE_CERT_DATE_INVALID: int +INTERNET_FLAG_IGNORE_CERT_CN_INVALID: int +INTERNET_FLAG_RESYNCHRONIZE: int +INTERNET_FLAG_HYPERLINK: int +INTERNET_FLAG_NO_UI: int +INTERNET_FLAG_PRAGMA_NOCACHE: int +INTERNET_FLAG_CACHE_ASYNC: int +INTERNET_FLAG_FORMS_SUBMIT: int +INTERNET_FLAG_FWD_BACK: int +INTERNET_FLAG_NEED_FILE: int +INTERNET_FLAG_MUST_CACHE_REQUEST: int +SECURITY_INTERNET_MASK: int +INTERNET_ERROR_MASK_INSERT_CDROM: int +INTERNET_ERROR_MASK_COMBINED_SEC_CERT: int +INTERNET_ERROR_MASK_NEED_MSN_SSPI_PKG: int +INTERNET_ERROR_MASK_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: int +WININET_API_FLAG_ASYNC: int +WININET_API_FLAG_SYNC: int +WININET_API_FLAG_USE_CONTEXT: int +INTERNET_NO_CALLBACK: int +IDSI_FLAG_KEEP_ALIVE: int +IDSI_FLAG_SECURE: int +IDSI_FLAG_PROXY: int +IDSI_FLAG_TUNNEL: int +INTERNET_PER_CONN_FLAGS: int +INTERNET_PER_CONN_PROXY_SERVER: int +INTERNET_PER_CONN_PROXY_BYPASS: int +INTERNET_PER_CONN_AUTOCONFIG_URL: int +INTERNET_PER_CONN_AUTODISCOVERY_FLAGS: int +INTERNET_PER_CONN_AUTOCONFIG_SECONDARY_URL: int +INTERNET_PER_CONN_AUTOCONFIG_RELOAD_DELAY_MINS: int +INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_TIME: int +INTERNET_PER_CONN_AUTOCONFIG_LAST_DETECT_URL: int +PROXY_TYPE_DIRECT: int +PROXY_TYPE_PROXY: int +PROXY_TYPE_AUTO_PROXY_URL: int +PROXY_TYPE_AUTO_DETECT: int +AUTO_PROXY_FLAG_USER_SET: int +AUTO_PROXY_FLAG_ALWAYS_DETECT: int +AUTO_PROXY_FLAG_DETECTION_RUN: int +AUTO_PROXY_FLAG_MIGRATED: int +AUTO_PROXY_FLAG_DONT_CACHE_PROXY_RESULT: int +AUTO_PROXY_FLAG_CACHE_INIT_RUN: int +AUTO_PROXY_FLAG_DETECTION_SUSPECT: int +ISO_FORCE_DISCONNECTED: int +INTERNET_RFC1123_FORMAT: int +INTERNET_RFC1123_BUFSIZE: int +ICU_ESCAPE: int +ICU_USERNAME: int +ICU_NO_ENCODE: int +ICU_DECODE: int +ICU_NO_META: int +ICU_ENCODE_SPACES_ONLY: int +ICU_BROWSER_MODE: int +ICU_ENCODE_PERCENT: int +INTERNET_OPEN_TYPE_PRECONFIG: int +INTERNET_OPEN_TYPE_DIRECT: int +INTERNET_OPEN_TYPE_PROXY: int +INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY: int +PRE_CONFIG_INTERNET_ACCESS: int +LOCAL_INTERNET_ACCESS: int +CERN_PROXY_INTERNET_ACCESS: int +INTERNET_SERVICE_FTP: int +INTERNET_SERVICE_GOPHER: int +INTERNET_SERVICE_HTTP: int +IRF_ASYNC: int +IRF_SYNC: int +IRF_USE_CONTEXT: int +IRF_NO_WAIT: int +ISO_GLOBAL: int +ISO_REGISTRY: int +ISO_VALID_FLAGS: int +INTERNET_OPTION_CALLBACK: int +INTERNET_OPTION_CONNECT_TIMEOUT: int +INTERNET_OPTION_CONNECT_RETRIES: int +INTERNET_OPTION_CONNECT_BACKOFF: int +INTERNET_OPTION_SEND_TIMEOUT: int +INTERNET_OPTION_CONTROL_SEND_TIMEOUT: int +INTERNET_OPTION_RECEIVE_TIMEOUT: int +INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT: int +INTERNET_OPTION_DATA_SEND_TIMEOUT: int +INTERNET_OPTION_DATA_RECEIVE_TIMEOUT: int +INTERNET_OPTION_HANDLE_TYPE: int +INTERNET_OPTION_READ_BUFFER_SIZE: int +INTERNET_OPTION_WRITE_BUFFER_SIZE: int +INTERNET_OPTION_ASYNC_ID: int +INTERNET_OPTION_ASYNC_PRIORITY: int +INTERNET_OPTION_PARENT_HANDLE: int +INTERNET_OPTION_KEEP_CONNECTION: int +INTERNET_OPTION_REQUEST_FLAGS: int +INTERNET_OPTION_EXTENDED_ERROR: int +INTERNET_OPTION_OFFLINE_MODE: int +INTERNET_OPTION_CACHE_STREAM_HANDLE: int +INTERNET_OPTION_USERNAME: int +INTERNET_OPTION_PASSWORD: int +INTERNET_OPTION_ASYNC: int +INTERNET_OPTION_SECURITY_FLAGS: int +INTERNET_OPTION_SECURITY_CERTIFICATE_STRUCT: int +INTERNET_OPTION_DATAFILE_NAME: int +INTERNET_OPTION_URL: int +INTERNET_OPTION_SECURITY_CERTIFICATE: int +INTERNET_OPTION_SECURITY_KEY_BITNESS: int +INTERNET_OPTION_REFRESH: int +INTERNET_OPTION_PROXY: int +INTERNET_OPTION_SETTINGS_CHANGED: int +INTERNET_OPTION_VERSION: int +INTERNET_OPTION_USER_AGENT: int +INTERNET_OPTION_END_BROWSER_SESSION: int +INTERNET_OPTION_PROXY_USERNAME: int +INTERNET_OPTION_PROXY_PASSWORD: int +INTERNET_OPTION_CONTEXT_VALUE: int +INTERNET_OPTION_CONNECT_LIMIT: int +INTERNET_OPTION_SECURITY_SELECT_CLIENT_CERT: int +INTERNET_OPTION_POLICY: int +INTERNET_OPTION_DISCONNECTED_TIMEOUT: int +INTERNET_OPTION_CONNECTED_STATE: int +INTERNET_OPTION_IDLE_STATE: int +INTERNET_OPTION_OFFLINE_SEMANTICS: int +INTERNET_OPTION_SECONDARY_CACHE_KEY: int +INTERNET_OPTION_CALLBACK_FILTER: int +INTERNET_OPTION_CONNECT_TIME: int +INTERNET_OPTION_SEND_THROUGHPUT: int +INTERNET_OPTION_RECEIVE_THROUGHPUT: int +INTERNET_OPTION_REQUEST_PRIORITY: int +INTERNET_OPTION_HTTP_VERSION: int +INTERNET_OPTION_RESET_URLCACHE_SESSION: int +INTERNET_OPTION_ERROR_MASK: int +INTERNET_OPTION_FROM_CACHE_TIMEOUT: int +INTERNET_OPTION_BYPASS_EDITED_ENTRY: int +INTERNET_OPTION_DIAGNOSTIC_SOCKET_INFO: int +INTERNET_OPTION_CODEPAGE: int +INTERNET_OPTION_CACHE_TIMESTAMPS: int +INTERNET_OPTION_DISABLE_AUTODIAL: int +INTERNET_OPTION_MAX_CONNS_PER_SERVER: int +INTERNET_OPTION_MAX_CONNS_PER_1_0_SERVER: int +INTERNET_OPTION_PER_CONNECTION_OPTION: int +INTERNET_OPTION_DIGEST_AUTH_UNLOAD: int +INTERNET_OPTION_IGNORE_OFFLINE: int +INTERNET_OPTION_IDENTITY: int +INTERNET_OPTION_REMOVE_IDENTITY: int +INTERNET_OPTION_ALTER_IDENTITY: int +INTERNET_OPTION_SUPPRESS_BEHAVIOR: int +INTERNET_OPTION_AUTODIAL_MODE: int +INTERNET_OPTION_AUTODIAL_CONNECTION: int +INTERNET_OPTION_CLIENT_CERT_CONTEXT: int +INTERNET_OPTION_AUTH_FLAGS: int +INTERNET_OPTION_COOKIES_3RD_PARTY: int +INTERNET_OPTION_DISABLE_PASSPORT_AUTH: int +INTERNET_OPTION_SEND_UTF8_SERVERNAME_TO_PROXY: int +INTERNET_OPTION_EXEMPT_CONNECTION_LIMIT: int +INTERNET_OPTION_ENABLE_PASSPORT_AUTH: int +INTERNET_OPTION_HIBERNATE_INACTIVE_WORKER_THREADS: int +INTERNET_OPTION_ACTIVATE_WORKER_THREADS: int +INTERNET_OPTION_RESTORE_WORKER_THREAD_DEFAULTS: int +INTERNET_OPTION_SOCKET_SEND_BUFFER_LENGTH: int +INTERNET_OPTION_PROXY_SETTINGS_CHANGED: int +INTERNET_FIRST_OPTION: int +INTERNET_LAST_OPTION: int +INTERNET_PRIORITY_FOREGROUND: int +INTERNET_HANDLE_TYPE_INTERNET: int +INTERNET_HANDLE_TYPE_CONNECT_FTP: int +INTERNET_HANDLE_TYPE_CONNECT_GOPHER: int +INTERNET_HANDLE_TYPE_CONNECT_HTTP: int +INTERNET_HANDLE_TYPE_FTP_FIND: int +INTERNET_HANDLE_TYPE_FTP_FIND_HTML: int +INTERNET_HANDLE_TYPE_FTP_FILE: int +INTERNET_HANDLE_TYPE_FTP_FILE_HTML: int +INTERNET_HANDLE_TYPE_GOPHER_FIND: int +INTERNET_HANDLE_TYPE_GOPHER_FIND_HTML: int +INTERNET_HANDLE_TYPE_GOPHER_FILE: int +INTERNET_HANDLE_TYPE_GOPHER_FILE_HTML: int +INTERNET_HANDLE_TYPE_HTTP_REQUEST: int +INTERNET_HANDLE_TYPE_FILE_REQUEST: int +AUTH_FLAG_DISABLE_NEGOTIATE: int +AUTH_FLAG_ENABLE_NEGOTIATE: int +SECURITY_FLAG_SECURE: int +SECURITY_FLAG_STRENGTH_WEAK: int +SECURITY_FLAG_STRENGTH_MEDIUM: int +SECURITY_FLAG_STRENGTH_STRONG: int +SECURITY_FLAG_UNKNOWNBIT: int +SECURITY_FLAG_FORTEZZA: int +SECURITY_FLAG_NORMALBITNESS: int +SECURITY_FLAG_SSL: int +SECURITY_FLAG_SSL3: int +SECURITY_FLAG_PCT: int +SECURITY_FLAG_PCT4: int +SECURITY_FLAG_IETFSSL4: int +SECURITY_FLAG_40BIT: int +SECURITY_FLAG_128BIT: int +SECURITY_FLAG_56BIT: int +SECURITY_FLAG_IGNORE_REVOCATION: int +SECURITY_FLAG_IGNORE_UNKNOWN_CA: int +SECURITY_FLAG_IGNORE_WRONG_USAGE: int +SECURITY_FLAG_IGNORE_CERT_CN_INVALID: int +SECURITY_FLAG_IGNORE_CERT_DATE_INVALID: int +SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS: int +SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP: int +SECURITY_SET_MASK: int +AUTODIAL_MODE_NEVER: int +AUTODIAL_MODE_ALWAYS: int +AUTODIAL_MODE_NO_NETWORK_PRESENT: int +INTERNET_STATUS_RESOLVING_NAME: int +INTERNET_STATUS_NAME_RESOLVED: int +INTERNET_STATUS_CONNECTING_TO_SERVER: int +INTERNET_STATUS_CONNECTED_TO_SERVER: int +INTERNET_STATUS_SENDING_REQUEST: int +INTERNET_STATUS_REQUEST_SENT: int +INTERNET_STATUS_RECEIVING_RESPONSE: int +INTERNET_STATUS_RESPONSE_RECEIVED: int +INTERNET_STATUS_CTL_RESPONSE_RECEIVED: int +INTERNET_STATUS_PREFETCH: int +INTERNET_STATUS_CLOSING_CONNECTION: int +INTERNET_STATUS_CONNECTION_CLOSED: int +INTERNET_STATUS_HANDLE_CREATED: int +INTERNET_STATUS_HANDLE_CLOSING: int +INTERNET_STATUS_DETECTING_PROXY: int +INTERNET_STATUS_REQUEST_COMPLETE: int +INTERNET_STATUS_REDIRECT: int +INTERNET_STATUS_INTERMEDIATE_RESPONSE: int +INTERNET_STATUS_USER_INPUT_REQUIRED: int +INTERNET_STATUS_STATE_CHANGE: int +INTERNET_STATUS_COOKIE_SENT: int +INTERNET_STATUS_COOKIE_RECEIVED: int +INTERNET_STATUS_PRIVACY_IMPACTED: int +INTERNET_STATUS_P3P_HEADER: int +INTERNET_STATUS_P3P_POLICYREF: int +INTERNET_STATUS_COOKIE_HISTORY: int +INTERNET_STATE_CONNECTED: int +INTERNET_STATE_DISCONNECTED: int +INTERNET_STATE_DISCONNECTED_BY_USER: int +INTERNET_STATE_IDLE: int +INTERNET_STATE_BUSY: int +FTP_TRANSFER_TYPE_UNKNOWN: int +FTP_TRANSFER_TYPE_ASCII: int +FTP_TRANSFER_TYPE_BINARY: int +FTP_TRANSFER_TYPE_MASK: int +MAX_GOPHER_DISPLAY_TEXT: int +MAX_GOPHER_SELECTOR_TEXT: int +MAX_GOPHER_HOST_NAME: int +MAX_GOPHER_LOCATOR_LENGTH: int +GOPHER_TYPE_TEXT_FILE: int +GOPHER_TYPE_DIRECTORY: int +GOPHER_TYPE_CSO: int +GOPHER_TYPE_ERROR: int +GOPHER_TYPE_MAC_BINHEX: int +GOPHER_TYPE_DOS_ARCHIVE: int +GOPHER_TYPE_UNIX_UUENCODED: int +GOPHER_TYPE_INDEX_SERVER: int +GOPHER_TYPE_TELNET: int +GOPHER_TYPE_BINARY: int +GOPHER_TYPE_REDUNDANT: int +GOPHER_TYPE_TN3270: int +GOPHER_TYPE_GIF: int +GOPHER_TYPE_IMAGE: int +GOPHER_TYPE_BITMAP: int +GOPHER_TYPE_MOVIE: int +GOPHER_TYPE_SOUND: int +GOPHER_TYPE_HTML: int +GOPHER_TYPE_PDF: int +GOPHER_TYPE_CALENDAR: int +GOPHER_TYPE_INLINE: int +GOPHER_TYPE_UNKNOWN: int +GOPHER_TYPE_ASK: int +GOPHER_TYPE_GOPHER_PLUS: int +GOPHER_TYPE_FILE_MASK: int +MAX_GOPHER_CATEGORY_NAME: int +MAX_GOPHER_ATTRIBUTE_NAME: int +MIN_GOPHER_ATTRIBUTE_LENGTH: int +GOPHER_ATTRIBUTE_ID_BASE: int +GOPHER_CATEGORY_ID_ALL: int +GOPHER_CATEGORY_ID_INFO: int +GOPHER_CATEGORY_ID_ADMIN: int +GOPHER_CATEGORY_ID_VIEWS: int +GOPHER_CATEGORY_ID_ABSTRACT: int +GOPHER_CATEGORY_ID_VERONICA: int +GOPHER_CATEGORY_ID_ASK: int +GOPHER_CATEGORY_ID_UNKNOWN: int +GOPHER_ATTRIBUTE_ID_ALL: int +GOPHER_ATTRIBUTE_ID_ADMIN: int +GOPHER_ATTRIBUTE_ID_MOD_DATE: int +GOPHER_ATTRIBUTE_ID_TTL: int +GOPHER_ATTRIBUTE_ID_SCORE: int +GOPHER_ATTRIBUTE_ID_RANGE: int +GOPHER_ATTRIBUTE_ID_SITE: int +GOPHER_ATTRIBUTE_ID_ORG: int +GOPHER_ATTRIBUTE_ID_LOCATION: int +GOPHER_ATTRIBUTE_ID_GEOG: int +GOPHER_ATTRIBUTE_ID_TIMEZONE: int +GOPHER_ATTRIBUTE_ID_PROVIDER: int +GOPHER_ATTRIBUTE_ID_VERSION: int +GOPHER_ATTRIBUTE_ID_ABSTRACT: int +GOPHER_ATTRIBUTE_ID_VIEW: int +GOPHER_ATTRIBUTE_ID_TREEWALK: int +GOPHER_ATTRIBUTE_ID_UNKNOWN: int +HTTP_MAJOR_VERSION: int +HTTP_MINOR_VERSION: int +HTTP_VERSIONA: str +HTTP_VERSION: str +HTTP_QUERY_MIME_VERSION: int +HTTP_QUERY_CONTENT_TYPE: int +HTTP_QUERY_CONTENT_TRANSFER_ENCODING: int +HTTP_QUERY_CONTENT_ID: int +HTTP_QUERY_CONTENT_DESCRIPTION: int +HTTP_QUERY_CONTENT_LENGTH: int +HTTP_QUERY_CONTENT_LANGUAGE: int +HTTP_QUERY_ALLOW: int +HTTP_QUERY_PUBLIC: int +HTTP_QUERY_DATE: int +HTTP_QUERY_EXPIRES: int +HTTP_QUERY_LAST_MODIFIED: int +HTTP_QUERY_MESSAGE_ID: int +HTTP_QUERY_URI: int +HTTP_QUERY_DERIVED_FROM: int +HTTP_QUERY_COST: int +HTTP_QUERY_LINK: int +HTTP_QUERY_PRAGMA: int +HTTP_QUERY_VERSION: int +HTTP_QUERY_STATUS_CODE: int +HTTP_QUERY_STATUS_TEXT: int +HTTP_QUERY_RAW_HEADERS: int +HTTP_QUERY_RAW_HEADERS_CRLF: int +HTTP_QUERY_CONNECTION: int +HTTP_QUERY_ACCEPT: int +HTTP_QUERY_ACCEPT_CHARSET: int +HTTP_QUERY_ACCEPT_ENCODING: int +HTTP_QUERY_ACCEPT_LANGUAGE: int +HTTP_QUERY_AUTHORIZATION: int +HTTP_QUERY_CONTENT_ENCODING: int +HTTP_QUERY_FORWARDED: int +HTTP_QUERY_FROM: int +HTTP_QUERY_IF_MODIFIED_SINCE: int +HTTP_QUERY_LOCATION: int +HTTP_QUERY_ORIG_URI: int +HTTP_QUERY_REFERER: int +HTTP_QUERY_RETRY_AFTER: int +HTTP_QUERY_SERVER: int +HTTP_QUERY_TITLE: int +HTTP_QUERY_USER_AGENT: int +HTTP_QUERY_WWW_AUTHENTICATE: int +HTTP_QUERY_PROXY_AUTHENTICATE: int +HTTP_QUERY_ACCEPT_RANGES: int +HTTP_QUERY_SET_COOKIE: int +HTTP_QUERY_COOKIE: int +HTTP_QUERY_REQUEST_METHOD: int +HTTP_QUERY_REFRESH: int +HTTP_QUERY_CONTENT_DISPOSITION: int +HTTP_QUERY_AGE: int +HTTP_QUERY_CACHE_CONTROL: int +HTTP_QUERY_CONTENT_BASE: int +HTTP_QUERY_CONTENT_LOCATION: int +HTTP_QUERY_CONTENT_MD5: int +HTTP_QUERY_CONTENT_RANGE: int +HTTP_QUERY_ETAG: int +HTTP_QUERY_HOST: int +HTTP_QUERY_IF_MATCH: int +HTTP_QUERY_IF_NONE_MATCH: int +HTTP_QUERY_IF_RANGE: int +HTTP_QUERY_IF_UNMODIFIED_SINCE: int +HTTP_QUERY_MAX_FORWARDS: int +HTTP_QUERY_PROXY_AUTHORIZATION: int +HTTP_QUERY_RANGE: int +HTTP_QUERY_TRANSFER_ENCODING: int +HTTP_QUERY_UPGRADE: int +HTTP_QUERY_VARY: int +HTTP_QUERY_VIA: int +HTTP_QUERY_WARNING: int +HTTP_QUERY_EXPECT: int +HTTP_QUERY_PROXY_CONNECTION: int +HTTP_QUERY_UNLESS_MODIFIED_SINCE: int +HTTP_QUERY_ECHO_REQUEST: int +HTTP_QUERY_ECHO_REPLY: int +HTTP_QUERY_ECHO_HEADERS: int +HTTP_QUERY_ECHO_HEADERS_CRLF: int +HTTP_QUERY_PROXY_SUPPORT: int +HTTP_QUERY_AUTHENTICATION_INFO: int +HTTP_QUERY_PASSPORT_URLS: int +HTTP_QUERY_PASSPORT_CONFIG: int +HTTP_QUERY_MAX: int +HTTP_QUERY_CUSTOM: int +HTTP_QUERY_FLAG_REQUEST_HEADERS: int +HTTP_QUERY_FLAG_SYSTEMTIME: int +HTTP_QUERY_FLAG_NUMBER: int +HTTP_QUERY_FLAG_COALESCE: int +HTTP_QUERY_MODIFIER_FLAGS_MASK: int +HTTP_QUERY_HEADER_MASK: int +HTTP_STATUS_CONTINUE: int +HTTP_STATUS_SWITCH_PROTOCOLS: int +HTTP_STATUS_OK: int +HTTP_STATUS_CREATED: int +HTTP_STATUS_ACCEPTED: int +HTTP_STATUS_PARTIAL: int +HTTP_STATUS_NO_CONTENT: int +HTTP_STATUS_RESET_CONTENT: int +HTTP_STATUS_PARTIAL_CONTENT: int +HTTP_STATUS_AMBIGUOUS: int +HTTP_STATUS_MOVED: int +HTTP_STATUS_REDIRECT: int +HTTP_STATUS_REDIRECT_METHOD: int +HTTP_STATUS_NOT_MODIFIED: int +HTTP_STATUS_USE_PROXY: int +HTTP_STATUS_REDIRECT_KEEP_VERB: int +HTTP_STATUS_BAD_REQUEST: int +HTTP_STATUS_DENIED: int +HTTP_STATUS_PAYMENT_REQ: int +HTTP_STATUS_FORBIDDEN: int +HTTP_STATUS_NOT_FOUND: int +HTTP_STATUS_BAD_METHOD: int +HTTP_STATUS_NONE_ACCEPTABLE: int +HTTP_STATUS_PROXY_AUTH_REQ: int +HTTP_STATUS_REQUEST_TIMEOUT: int +HTTP_STATUS_CONFLICT: int +HTTP_STATUS_GONE: int +HTTP_STATUS_LENGTH_REQUIRED: int +HTTP_STATUS_PRECOND_FAILED: int +HTTP_STATUS_REQUEST_TOO_LARGE: int +HTTP_STATUS_URI_TOO_LONG: int +HTTP_STATUS_UNSUPPORTED_MEDIA: int +HTTP_STATUS_RETRY_WITH: int +HTTP_STATUS_SERVER_ERROR: int +HTTP_STATUS_NOT_SUPPORTED: int +HTTP_STATUS_BAD_GATEWAY: int +HTTP_STATUS_SERVICE_UNAVAIL: int +HTTP_STATUS_GATEWAY_TIMEOUT: int +HTTP_STATUS_VERSION_NOT_SUP: int +HTTP_STATUS_FIRST: int +HTTP_STATUS_LAST: int +HTTP_ADDREQ_INDEX_MASK: int +HTTP_ADDREQ_FLAGS_MASK: int +HTTP_ADDREQ_FLAG_ADD_IF_NEW: int +HTTP_ADDREQ_FLAG_ADD: int +HTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA: int +HTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON: int +HTTP_ADDREQ_FLAG_COALESCE: int +HTTP_ADDREQ_FLAG_REPLACE: int +HSR_ASYNC: int +HSR_SYNC: int +HSR_USE_CONTEXT: int +HSR_INITIATE: int +HSR_DOWNLOAD: int +HSR_CHUNKED: int +INTERNET_COOKIE_IS_SECURE: int +INTERNET_COOKIE_IS_SESSION: int +INTERNET_COOKIE_THIRD_PARTY: int +INTERNET_COOKIE_PROMPT_REQUIRED: int +INTERNET_COOKIE_EVALUATE_P3P: int +INTERNET_COOKIE_APPLY_P3P: int +INTERNET_COOKIE_P3P_ENABLED: int +INTERNET_COOKIE_IS_RESTRICTED: int +INTERNET_COOKIE_IE6: int +INTERNET_COOKIE_IS_LEGACY: int +FLAG_ICC_FORCE_CONNECTION: int +FLAGS_ERROR_UI_FILTER_FOR_ERRORS: int +FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS: int +FLAGS_ERROR_UI_FLAGS_GENERATE_DATA: int +FLAGS_ERROR_UI_FLAGS_NO_UI: int +FLAGS_ERROR_UI_SERIALIZE_DIALOGS: int +INTERNET_ERROR_BASE: int +ERROR_INTERNET_OUT_OF_HANDLES: int +ERROR_INTERNET_TIMEOUT: int +ERROR_INTERNET_EXTENDED_ERROR: int +ERROR_INTERNET_INTERNAL_ERROR: int +ERROR_INTERNET_INVALID_URL: int +ERROR_INTERNET_UNRECOGNIZED_SCHEME: int +ERROR_INTERNET_NAME_NOT_RESOLVED: int +ERROR_INTERNET_PROTOCOL_NOT_FOUND: int +ERROR_INTERNET_INVALID_OPTION: int +ERROR_INTERNET_BAD_OPTION_LENGTH: int +ERROR_INTERNET_OPTION_NOT_SETTABLE: int +ERROR_INTERNET_SHUTDOWN: int +ERROR_INTERNET_INCORRECT_USER_NAME: int +ERROR_INTERNET_INCORRECT_PASSWORD: int +ERROR_INTERNET_LOGIN_FAILURE: int +ERROR_INTERNET_INVALID_OPERATION: int +ERROR_INTERNET_OPERATION_CANCELLED: int +ERROR_INTERNET_INCORRECT_HANDLE_TYPE: int +ERROR_INTERNET_INCORRECT_HANDLE_STATE: int +ERROR_INTERNET_NOT_PROXY_REQUEST: int +ERROR_INTERNET_REGISTRY_VALUE_NOT_FOUND: int +ERROR_INTERNET_BAD_REGISTRY_PARAMETER: int +ERROR_INTERNET_NO_DIRECT_ACCESS: int +ERROR_INTERNET_NO_CONTEXT: int +ERROR_INTERNET_NO_CALLBACK: int +ERROR_INTERNET_REQUEST_PENDING: int +ERROR_INTERNET_INCORRECT_FORMAT: int +ERROR_INTERNET_ITEM_NOT_FOUND: int +ERROR_INTERNET_CANNOT_CONNECT: int +ERROR_INTERNET_CONNECTION_ABORTED: int +ERROR_INTERNET_CONNECTION_RESET: int +ERROR_INTERNET_FORCE_RETRY: int +ERROR_INTERNET_INVALID_PROXY_REQUEST: int +ERROR_INTERNET_NEED_UI: int +ERROR_INTERNET_HANDLE_EXISTS: int +ERROR_INTERNET_SEC_CERT_DATE_INVALID: int +ERROR_INTERNET_SEC_CERT_CN_INVALID: int +ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR: int +ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR: int +ERROR_INTERNET_MIXED_SECURITY: int +ERROR_INTERNET_CHG_POST_IS_NON_SECURE: int +ERROR_INTERNET_POST_IS_NON_SECURE: int +ERROR_INTERNET_CLIENT_AUTH_CERT_NEEDED: int +ERROR_INTERNET_INVALID_CA: int +ERROR_INTERNET_CLIENT_AUTH_NOT_SETUP: int +ERROR_INTERNET_ASYNC_THREAD_FAILED: int +ERROR_INTERNET_REDIRECT_SCHEME_CHANGE: int +ERROR_INTERNET_DIALOG_PENDING: int +ERROR_INTERNET_RETRY_DIALOG: int +ERROR_INTERNET_HTTPS_HTTP_SUBMIT_REDIR: int +ERROR_INTERNET_INSERT_CDROM: int +ERROR_INTERNET_FORTEZZA_LOGIN_NEEDED: int +ERROR_INTERNET_SEC_CERT_ERRORS: int +ERROR_INTERNET_SEC_CERT_NO_REV: int +ERROR_INTERNET_SEC_CERT_REV_FAILED: int +ERROR_FTP_TRANSFER_IN_PROGRESS: int +ERROR_FTP_DROPPED: int +ERROR_FTP_NO_PASSIVE_MODE: int +ERROR_GOPHER_PROTOCOL_ERROR: int +ERROR_GOPHER_NOT_FILE: int +ERROR_GOPHER_DATA_ERROR: int +ERROR_GOPHER_END_OF_DATA: int +ERROR_GOPHER_INVALID_LOCATOR: int +ERROR_GOPHER_INCORRECT_LOCATOR_TYPE: int +ERROR_GOPHER_NOT_GOPHER_PLUS: int +ERROR_GOPHER_ATTRIBUTE_NOT_FOUND: int +ERROR_GOPHER_UNKNOWN_LOCATOR: int +ERROR_HTTP_HEADER_NOT_FOUND: int +ERROR_HTTP_DOWNLEVEL_SERVER: int +ERROR_HTTP_INVALID_SERVER_RESPONSE: int +ERROR_HTTP_INVALID_HEADER: int +ERROR_HTTP_INVALID_QUERY_REQUEST: int +ERROR_HTTP_HEADER_ALREADY_EXISTS: int +ERROR_HTTP_REDIRECT_FAILED: int +ERROR_HTTP_NOT_REDIRECTED: int +ERROR_HTTP_COOKIE_NEEDS_CONFIRMATION: int +ERROR_HTTP_COOKIE_DECLINED: int +ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION: int +ERROR_INTERNET_SECURITY_CHANNEL_ERROR: int +ERROR_INTERNET_UNABLE_TO_CACHE_FILE: int +ERROR_INTERNET_TCPIP_NOT_INSTALLED: int +ERROR_INTERNET_DISCONNECTED: int +ERROR_INTERNET_SERVER_UNREACHABLE: int +ERROR_INTERNET_PROXY_SERVER_UNREACHABLE: int +ERROR_INTERNET_BAD_AUTO_PROXY_SCRIPT: int +ERROR_INTERNET_UNABLE_TO_DOWNLOAD_SCRIPT: int +ERROR_INTERNET_SEC_INVALID_CERT: int +ERROR_INTERNET_SEC_CERT_REVOKED: int +ERROR_INTERNET_FAILED_DUETOSECURITYCHECK: int +ERROR_INTERNET_NOT_INITIALIZED: int +ERROR_INTERNET_NEED_MSN_SSPI_PKG: int +ERROR_INTERNET_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: int +INTERNET_ERROR_LAST: int +NORMAL_CACHE_ENTRY: int +STICKY_CACHE_ENTRY: int +EDITED_CACHE_ENTRY: int +TRACK_OFFLINE_CACHE_ENTRY: int +TRACK_ONLINE_CACHE_ENTRY: int +SPARSE_CACHE_ENTRY: int +COOKIE_CACHE_ENTRY: int +URLHISTORY_CACHE_ENTRY: int +URLCACHE_FIND_DEFAULT_FILTER: int +CACHEGROUP_ATTRIBUTE_GET_ALL: int +CACHEGROUP_ATTRIBUTE_BASIC: int +CACHEGROUP_ATTRIBUTE_FLAG: int +CACHEGROUP_ATTRIBUTE_TYPE: int +CACHEGROUP_ATTRIBUTE_QUOTA: int +CACHEGROUP_ATTRIBUTE_GROUPNAME: int +CACHEGROUP_ATTRIBUTE_STORAGE: int +CACHEGROUP_FLAG_NONPURGEABLE: int +CACHEGROUP_FLAG_GIDONLY: int +CACHEGROUP_FLAG_FLUSHURL_ONDELETE: int +CACHEGROUP_SEARCH_ALL: int +CACHEGROUP_SEARCH_BYURL: int +CACHEGROUP_TYPE_INVALID: int +CACHEGROUP_READWRITE_MASK: int +GROUPNAME_MAX_LENGTH: int +GROUP_OWNER_STORAGE_SIZE: int +CACHE_ENTRY_ATTRIBUTE_FC: int +CACHE_ENTRY_HITRATE_FC: int +CACHE_ENTRY_MODTIME_FC: int +CACHE_ENTRY_EXPTIME_FC: int +CACHE_ENTRY_ACCTIME_FC: int +CACHE_ENTRY_SYNCTIME_FC: int +CACHE_ENTRY_HEADERINFO_FC: int +CACHE_ENTRY_EXEMPT_DELTA_FC: int +INTERNET_CACHE_GROUP_ADD: int +INTERNET_CACHE_GROUP_REMOVE: int +INTERNET_DIAL_FORCE_PROMPT: int +INTERNET_DIAL_SHOW_OFFLINE: int +INTERNET_DIAL_UNATTENDED: int +INTERENT_GOONLINE_REFRESH: int +INTERENT_GOONLINE_MASK: int +INTERNET_AUTODIAL_FORCE_ONLINE: int +INTERNET_AUTODIAL_FORCE_UNATTENDED: int +INTERNET_AUTODIAL_FAILIFSECURITYCHECK: int +INTERNET_AUTODIAL_OVERRIDE_NET_PRESENT: int +INTERNET_AUTODIAL_FLAGS_MASK: int +PROXY_AUTO_DETECT_TYPE_DHCP: int +PROXY_AUTO_DETECT_TYPE_DNS_A: int +INTERNET_CONNECTION_MODEM: int +INTERNET_CONNECTION_LAN: int +INTERNET_CONNECTION_PROXY: int +INTERNET_CONNECTION_MODEM_BUSY: int +INTERNET_RAS_INSTALLED: int +INTERNET_CONNECTION_OFFLINE: int +INTERNET_CONNECTION_CONFIGURED: int +INTERNET_CUSTOMDIAL_CONNECT: int +INTERNET_CUSTOMDIAL_UNATTENDED: int +INTERNET_CUSTOMDIAL_DISCONNECT: int +INTERNET_CUSTOMDIAL_SHOWOFFLINE: int +INTERNET_CUSTOMDIAL_SAFE_FOR_UNATTENDED: int +INTERNET_CUSTOMDIAL_WILL_SUPPLY_STATE: int +INTERNET_CUSTOMDIAL_CAN_HANGUP: int +INTERNET_DIALSTATE_DISCONNECTED: int +INTERNET_IDENTITY_FLAG_PRIVATE_CACHE: int +INTERNET_IDENTITY_FLAG_SHARED_CACHE: int +INTERNET_IDENTITY_FLAG_CLEAR_DATA: int +INTERNET_IDENTITY_FLAG_CLEAR_COOKIES: int +INTERNET_IDENTITY_FLAG_CLEAR_HISTORY: int +INTERNET_IDENTITY_FLAG_CLEAR_CONTENT: int +INTERNET_SUPPRESS_RESET_ALL: int +INTERNET_SUPPRESS_COOKIE_POLICY: int +INTERNET_SUPPRESS_COOKIE_POLICY_RESET: int +PRIVACY_TEMPLATE_NO_COOKIES: int +PRIVACY_TEMPLATE_HIGH: int +PRIVACY_TEMPLATE_MEDIUM_HIGH: int +PRIVACY_TEMPLATE_MEDIUM: int +PRIVACY_TEMPLATE_MEDIUM_LOW: int +PRIVACY_TEMPLATE_LOW: int +PRIVACY_TEMPLATE_CUSTOM: int +PRIVACY_TEMPLATE_ADVANCED: int +PRIVACY_TEMPLATE_MAX: int +PRIVACY_TYPE_FIRST_PARTY: int +PRIVACY_TYPE_THIRD_PARTY: int +INTERNET_DEFAULT_PORT: int +WINHTTP_FLAG_ASYNC: int +WINHTTP_FLAG_SECURE: int +WINHTTP_FLAG_ESCAPE_PERCENT: int +WINHTTP_FLAG_NULL_CODEPAGE: int +WINHTTP_FLAG_BYPASS_PROXY_CACHE: int +WINHTTP_FLAG_REFRESH: int +WINHTTP_FLAG_ESCAPE_DISABLE: int +WINHTTP_FLAG_ESCAPE_DISABLE_QUERY: int +SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE: int +INTERNET_SCHEME_HTTP: int +INTERNET_SCHEME_HTTPS: int +WINHTTP_AUTOPROXY_AUTO_DETECT: int +WINHTTP_AUTOPROXY_CONFIG_URL: int +WINHTTP_AUTOPROXY_RUN_INPROCESS: int +WINHTTP_AUTOPROXY_RUN_OUTPROCESS_ONLY: int +WINHTTP_AUTO_DETECT_TYPE_DHCP: int +WINHTTP_AUTO_DETECT_TYPE_DNS_A: int +WINHTTP_TIME_FORMAT_BUFSIZE: int +ICU_ESCAPE_AUTHORITY: int +ICU_REJECT_USERPWD: int +WINHTTP_ACCESS_TYPE_DEFAULT_PROXY: int +WINHTTP_ACCESS_TYPE_NO_PROXY: int +WINHTTP_ACCESS_TYPE_NAMED_PROXY: int +WINHTTP_OPTION_CALLBACK: int +WINHTTP_OPTION_RESOLVE_TIMEOUT: int +WINHTTP_OPTION_CONNECT_TIMEOUT: int +WINHTTP_OPTION_CONNECT_RETRIES: int +WINHTTP_OPTION_SEND_TIMEOUT: int +WINHTTP_OPTION_RECEIVE_TIMEOUT: int +WINHTTP_OPTION_RECEIVE_RESPONSE_TIMEOUT: int +WINHTTP_OPTION_HANDLE_TYPE: int +WINHTTP_OPTION_READ_BUFFER_SIZE: int +WINHTTP_OPTION_WRITE_BUFFER_SIZE: int +WINHTTP_OPTION_PARENT_HANDLE: int +WINHTTP_OPTION_EXTENDED_ERROR: int +WINHTTP_OPTION_SECURITY_FLAGS: int +WINHTTP_OPTION_SECURITY_CERTIFICATE_STRUCT: int +WINHTTP_OPTION_URL: int +WINHTTP_OPTION_SECURITY_KEY_BITNESS: int +WINHTTP_OPTION_PROXY: int +WINHTTP_OPTION_USER_AGENT: int +WINHTTP_OPTION_CONTEXT_VALUE: int +WINHTTP_OPTION_CLIENT_CERT_CONTEXT: int +WINHTTP_OPTION_REQUEST_PRIORITY: int +WINHTTP_OPTION_HTTP_VERSION: int +WINHTTP_OPTION_DISABLE_FEATURE: int +WINHTTP_OPTION_CODEPAGE: int +WINHTTP_OPTION_MAX_CONNS_PER_SERVER: int +WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER: int +WINHTTP_OPTION_AUTOLOGON_POLICY: int +WINHTTP_OPTION_SERVER_CERT_CONTEXT: int +WINHTTP_OPTION_ENABLE_FEATURE: int +WINHTTP_OPTION_WORKER_THREAD_COUNT: int +WINHTTP_OPTION_PASSPORT_COBRANDING_TEXT: int +WINHTTP_OPTION_PASSPORT_COBRANDING_URL: int +WINHTTP_OPTION_CONFIGURE_PASSPORT_AUTH: int +WINHTTP_OPTION_SECURE_PROTOCOLS: int +WINHTTP_OPTION_ENABLETRACING: int +WINHTTP_OPTION_PASSPORT_SIGN_OUT: int +WINHTTP_OPTION_PASSPORT_RETURN_URL: int +WINHTTP_OPTION_REDIRECT_POLICY: int +WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS: int +WINHTTP_OPTION_MAX_HTTP_STATUS_CONTINUE: int +WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE: int +WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE: int +WINHTTP_OPTION_CONNECTION_INFO: int +WINHTTP_OPTION_SPN: int +WINHTTP_OPTION_GLOBAL_PROXY_CREDS: int +WINHTTP_OPTION_GLOBAL_SERVER_CREDS: int +WINHTTP_OPTION_UNLOAD_NOTIFY_EVENT: int +WINHTTP_OPTION_REJECT_USERPWD_IN_URL: int +WINHTTP_OPTION_USE_GLOBAL_SERVER_CREDENTIALS: int +WINHTTP_LAST_OPTION: int +WINHTTP_OPTION_USERNAME: int +WINHTTP_OPTION_PASSWORD: int +WINHTTP_OPTION_PROXY_USERNAME: int +WINHTTP_OPTION_PROXY_PASSWORD: int +WINHTTP_CONNS_PER_SERVER_UNLIMITED: int +WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM: int +WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW: int +WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH: int +WINHTTP_AUTOLOGON_SECURITY_LEVEL_DEFAULT: int +WINHTTP_OPTION_REDIRECT_POLICY_NEVER: int +WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP: int +WINHTTP_OPTION_REDIRECT_POLICY_ALWAYS: int +WINHTTP_OPTION_REDIRECT_POLICY_LAST: int +WINHTTP_OPTION_REDIRECT_POLICY_DEFAULT: int +WINHTTP_DISABLE_PASSPORT_AUTH: int +WINHTTP_ENABLE_PASSPORT_AUTH: int +WINHTTP_DISABLE_PASSPORT_KEYRING: int +WINHTTP_ENABLE_PASSPORT_KEYRING: int +WINHTTP_DISABLE_COOKIES: int +WINHTTP_DISABLE_REDIRECTS: int +WINHTTP_DISABLE_AUTHENTICATION: int +WINHTTP_DISABLE_KEEP_ALIVE: int +WINHTTP_ENABLE_SSL_REVOCATION: int +WINHTTP_ENABLE_SSL_REVERT_IMPERSONATION: int +WINHTTP_DISABLE_SPN_SERVER_PORT: int +WINHTTP_ENABLE_SPN_SERVER_PORT: int +WINHTTP_OPTION_SPN_MASK: int +WINHTTP_HANDLE_TYPE_SESSION: int +WINHTTP_HANDLE_TYPE_CONNECT: int +WINHTTP_HANDLE_TYPE_REQUEST: int +WINHTTP_AUTH_SCHEME_BASIC: int +WINHTTP_AUTH_SCHEME_NTLM: int +WINHTTP_AUTH_SCHEME_PASSPORT: int +WINHTTP_AUTH_SCHEME_DIGEST: int +WINHTTP_AUTH_SCHEME_NEGOTIATE: int +WINHTTP_AUTH_TARGET_SERVER: int +WINHTTP_AUTH_TARGET_PROXY: int +WINHTTP_CALLBACK_STATUS_FLAG_CERT_REV_FAILED: int +WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CERT: int +WINHTTP_CALLBACK_STATUS_FLAG_CERT_REVOKED: int +WINHTTP_CALLBACK_STATUS_FLAG_INVALID_CA: int +WINHTTP_CALLBACK_STATUS_FLAG_CERT_CN_INVALID: int +WINHTTP_CALLBACK_STATUS_FLAG_CERT_DATE_INVALID: int +WINHTTP_CALLBACK_STATUS_FLAG_CERT_WRONG_USAGE: int +WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR: int +WINHTTP_FLAG_SECURE_PROTOCOL_SSL2: int +WINHTTP_FLAG_SECURE_PROTOCOL_SSL3: int +WINHTTP_FLAG_SECURE_PROTOCOL_TLS1: int +WINHTTP_FLAG_SECURE_PROTOCOL_ALL: int +WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: int +WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: int +WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: int +WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: int +WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: int +WINHTTP_CALLBACK_STATUS_REQUEST_SENT: int +WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: int +WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: int +WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: int +WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: int +WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: int +WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: int +WINHTTP_CALLBACK_STATUS_DETECTING_PROXY: int +WINHTTP_CALLBACK_STATUS_REDIRECT: int +WINHTTP_CALLBACK_STATUS_INTERMEDIATE_RESPONSE: int +WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: int +WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: int +WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: int +WINHTTP_CALLBACK_STATUS_READ_COMPLETE: int +WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: int +WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: int +WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: int +API_RECEIVE_RESPONSE: int +API_QUERY_DATA_AVAILABLE: int +API_READ_DATA: int +API_WRITE_DATA: int +API_SEND_REQUEST: int +WINHTTP_CALLBACK_FLAG_RESOLVE_NAME: int +WINHTTP_CALLBACK_FLAG_CONNECT_TO_SERVER: int +WINHTTP_CALLBACK_FLAG_SEND_REQUEST: int +WINHTTP_CALLBACK_FLAG_RECEIVE_RESPONSE: int +WINHTTP_CALLBACK_FLAG_CLOSE_CONNECTION: int +WINHTTP_CALLBACK_FLAG_HANDLES: int +WINHTTP_CALLBACK_FLAG_DETECTING_PROXY: int +WINHTTP_CALLBACK_FLAG_REDIRECT: int +WINHTTP_CALLBACK_FLAG_INTERMEDIATE_RESPONSE: int +WINHTTP_CALLBACK_FLAG_SECURE_FAILURE: int +WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE: int +WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE: int +WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE: int +WINHTTP_CALLBACK_FLAG_READ_COMPLETE: int +WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE: int +WINHTTP_CALLBACK_FLAG_REQUEST_ERROR: int +WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS: int +WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS: int +WINHTTP_QUERY_MIME_VERSION: int +WINHTTP_QUERY_CONTENT_TYPE: int +WINHTTP_QUERY_CONTENT_TRANSFER_ENCODING: int +WINHTTP_QUERY_CONTENT_ID: int +WINHTTP_QUERY_CONTENT_DESCRIPTION: int +WINHTTP_QUERY_CONTENT_LENGTH: int +WINHTTP_QUERY_CONTENT_LANGUAGE: int +WINHTTP_QUERY_ALLOW: int +WINHTTP_QUERY_PUBLIC: int +WINHTTP_QUERY_DATE: int +WINHTTP_QUERY_EXPIRES: int +WINHTTP_QUERY_LAST_MODIFIED: int +WINHTTP_QUERY_MESSAGE_ID: int +WINHTTP_QUERY_URI: int +WINHTTP_QUERY_DERIVED_FROM: int +WINHTTP_QUERY_COST: int +WINHTTP_QUERY_LINK: int +WINHTTP_QUERY_PRAGMA: int +WINHTTP_QUERY_VERSION: int +WINHTTP_QUERY_STATUS_CODE: int +WINHTTP_QUERY_STATUS_TEXT: int +WINHTTP_QUERY_RAW_HEADERS: int +WINHTTP_QUERY_RAW_HEADERS_CRLF: int +WINHTTP_QUERY_CONNECTION: int +WINHTTP_QUERY_ACCEPT: int +WINHTTP_QUERY_ACCEPT_CHARSET: int +WINHTTP_QUERY_ACCEPT_ENCODING: int +WINHTTP_QUERY_ACCEPT_LANGUAGE: int +WINHTTP_QUERY_AUTHORIZATION: int +WINHTTP_QUERY_CONTENT_ENCODING: int +WINHTTP_QUERY_FORWARDED: int +WINHTTP_QUERY_FROM: int +WINHTTP_QUERY_IF_MODIFIED_SINCE: int +WINHTTP_QUERY_LOCATION: int +WINHTTP_QUERY_ORIG_URI: int +WINHTTP_QUERY_REFERER: int +WINHTTP_QUERY_RETRY_AFTER: int +WINHTTP_QUERY_SERVER: int +WINHTTP_QUERY_TITLE: int +WINHTTP_QUERY_USER_AGENT: int +WINHTTP_QUERY_WWW_AUTHENTICATE: int +WINHTTP_QUERY_PROXY_AUTHENTICATE: int +WINHTTP_QUERY_ACCEPT_RANGES: int +WINHTTP_QUERY_SET_COOKIE: int +WINHTTP_QUERY_COOKIE: int +WINHTTP_QUERY_REQUEST_METHOD: int +WINHTTP_QUERY_REFRESH: int +WINHTTP_QUERY_CONTENT_DISPOSITION: int +WINHTTP_QUERY_AGE: int +WINHTTP_QUERY_CACHE_CONTROL: int +WINHTTP_QUERY_CONTENT_BASE: int +WINHTTP_QUERY_CONTENT_LOCATION: int +WINHTTP_QUERY_CONTENT_MD5: int +WINHTTP_QUERY_CONTENT_RANGE: int +WINHTTP_QUERY_ETAG: int +WINHTTP_QUERY_HOST: int +WINHTTP_QUERY_IF_MATCH: int +WINHTTP_QUERY_IF_NONE_MATCH: int +WINHTTP_QUERY_IF_RANGE: int +WINHTTP_QUERY_IF_UNMODIFIED_SINCE: int +WINHTTP_QUERY_MAX_FORWARDS: int +WINHTTP_QUERY_PROXY_AUTHORIZATION: int +WINHTTP_QUERY_RANGE: int +WINHTTP_QUERY_TRANSFER_ENCODING: int +WINHTTP_QUERY_UPGRADE: int +WINHTTP_QUERY_VARY: int +WINHTTP_QUERY_VIA: int +WINHTTP_QUERY_WARNING: int +WINHTTP_QUERY_EXPECT: int +WINHTTP_QUERY_PROXY_CONNECTION: int +WINHTTP_QUERY_UNLESS_MODIFIED_SINCE: int +WINHTTP_QUERY_PROXY_SUPPORT: int +WINHTTP_QUERY_AUTHENTICATION_INFO: int +WINHTTP_QUERY_PASSPORT_URLS: int +WINHTTP_QUERY_PASSPORT_CONFIG: int +WINHTTP_QUERY_MAX: int +WINHTTP_QUERY_CUSTOM: int +WINHTTP_QUERY_FLAG_REQUEST_HEADERS: int +WINHTTP_QUERY_FLAG_SYSTEMTIME: int +WINHTTP_QUERY_FLAG_NUMBER: int +HTTP_STATUS_WEBDAV_MULTI_STATUS: int +WINHTTP_ADDREQ_INDEX_MASK: int +WINHTTP_ADDREQ_FLAGS_MASK: int +WINHTTP_ADDREQ_FLAG_ADD_IF_NEW: int +WINHTTP_ADDREQ_FLAG_ADD: int +WINHTTP_ADDREQ_FLAG_COALESCE_WITH_COMMA: int +WINHTTP_ADDREQ_FLAG_COALESCE_WITH_SEMICOLON: int +WINHTTP_ADDREQ_FLAG_COALESCE: int +WINHTTP_ADDREQ_FLAG_REPLACE: int +WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH: int +WINHTTP_ERROR_BASE: int +ERROR_WINHTTP_OUT_OF_HANDLES: int +ERROR_WINHTTP_TIMEOUT: int +ERROR_WINHTTP_INTERNAL_ERROR: int +ERROR_WINHTTP_INVALID_URL: int +ERROR_WINHTTP_UNRECOGNIZED_SCHEME: int +ERROR_WINHTTP_NAME_NOT_RESOLVED: int +ERROR_WINHTTP_INVALID_OPTION: int +ERROR_WINHTTP_OPTION_NOT_SETTABLE: int +ERROR_WINHTTP_SHUTDOWN: int +ERROR_WINHTTP_LOGIN_FAILURE: int +ERROR_WINHTTP_OPERATION_CANCELLED: int +ERROR_WINHTTP_INCORRECT_HANDLE_TYPE: int +ERROR_WINHTTP_INCORRECT_HANDLE_STATE: int +ERROR_WINHTTP_CANNOT_CONNECT: int +ERROR_WINHTTP_CONNECTION_ERROR: int +ERROR_WINHTTP_RESEND_REQUEST: int +ERROR_WINHTTP_CLIENT_AUTH_CERT_NEEDED: int +ERROR_WINHTTP_CANNOT_CALL_BEFORE_OPEN: int +ERROR_WINHTTP_CANNOT_CALL_BEFORE_SEND: int +ERROR_WINHTTP_CANNOT_CALL_AFTER_SEND: int +ERROR_WINHTTP_CANNOT_CALL_AFTER_OPEN: int +ERROR_WINHTTP_HEADER_NOT_FOUND: int +ERROR_WINHTTP_INVALID_SERVER_RESPONSE: int +ERROR_WINHTTP_INVALID_HEADER: int +ERROR_WINHTTP_INVALID_QUERY_REQUEST: int +ERROR_WINHTTP_HEADER_ALREADY_EXISTS: int +ERROR_WINHTTP_REDIRECT_FAILED: int +ERROR_WINHTTP_AUTO_PROXY_SERVICE_ERROR: int +ERROR_WINHTTP_BAD_AUTO_PROXY_SCRIPT: int +ERROR_WINHTTP_UNABLE_TO_DOWNLOAD_SCRIPT: int +ERROR_WINHTTP_NOT_INITIALIZED: int +ERROR_WINHTTP_SECURE_FAILURE: int +ERROR_WINHTTP_SECURE_CERT_DATE_INVALID: int +ERROR_WINHTTP_SECURE_CERT_CN_INVALID: int +ERROR_WINHTTP_SECURE_INVALID_CA: int +ERROR_WINHTTP_SECURE_CERT_REV_FAILED: int +ERROR_WINHTTP_SECURE_CHANNEL_ERROR: int +ERROR_WINHTTP_SECURE_INVALID_CERT: int +ERROR_WINHTTP_SECURE_CERT_REVOKED: int +ERROR_WINHTTP_SECURE_CERT_WRONG_USAGE: int +ERROR_WINHTTP_AUTODETECTION_FAILED: int +ERROR_WINHTTP_HEADER_COUNT_EXCEEDED: int +ERROR_WINHTTP_HEADER_SIZE_OVERFLOW: int +ERROR_WINHTTP_CHUNKED_ENCODING_HEADER_SIZE_OVERFLOW: int +ERROR_WINHTTP_RESPONSE_DRAIN_OVERFLOW: int +ERROR_WINHTTP_CLIENT_CERT_NO_PRIVATE_KEY: int +ERROR_WINHTTP_CLIENT_CERT_NO_ACCESS_PRIVATE_KEY: int +WINHTTP_ERROR_LAST: int +WINHTTP_NO_PROXY_NAME: None +WINHTTP_NO_PROXY_BYPASS: None +WINHTTP_NO_REFERER: None +WINHTTP_DEFAULT_ACCEPT_TYPES: None +WINHTTP_NO_ADDITIONAL_HEADERS: None +WINHTTP_NO_REQUEST_DATA: None +INTERNET_OPTION_LISTEN_TIMEOUT: int +WINHTTP_OPTION_CLIENT_CERT_ISSUER_LIST: int diff --git a/stubs/pywin32/win32/lib/win32netcon.pyi b/stubs/pywin32/win32/lib/win32netcon.pyi new file mode 100644 index 000000000000..0538f443f18d --- /dev/null +++ b/stubs/pywin32/win32/lib/win32netcon.pyi @@ -0,0 +1,571 @@ +CNLEN: int +LM20_CNLEN: int +DNLEN: int +LM20_DNLEN: int +UNCLEN: int +LM20_UNCLEN: int +NNLEN: int +LM20_NNLEN: int +RMLEN: int +LM20_RMLEN: int +SNLEN: int +LM20_SNLEN: int +STXTLEN: int +LM20_STXTLEN: int +PATHLEN: int +LM20_PATHLEN: int +DEVLEN: int +LM20_DEVLEN: int +EVLEN: int +UNLEN: int +LM20_UNLEN: int +GNLEN: int +LM20_GNLEN: int +PWLEN: int +LM20_PWLEN: int +SHPWLEN: int +CLTYPE_LEN: int +MAXCOMMENTSZ: int +LM20_MAXCOMMENTSZ: int +QNLEN: int +LM20_QNLEN: int +ALERTSZ: int +NETBIOS_NAME_LEN: int +CRYPT_KEY_LEN: int +CRYPT_TXT_LEN: int +ENCRYPTED_PWLEN: int +SESSION_PWLEN: int +SESSION_CRYPT_KLEN: int +PARMNUM_ALL: int +PARM_ERROR_NONE: int +PARMNUM_BASE_INFOLEVEL: int +NULL: int +PLATFORM_ID_DOS: int +PLATFORM_ID_OS2: int +PLATFORM_ID_NT: int +PLATFORM_ID_OSF: int +PLATFORM_ID_VMS: int +MAX_LANMAN_MESSAGE_ID: int +UF_SCRIPT: int +UF_ACCOUNTDISABLE: int +UF_HOMEDIR_REQUIRED: int +UF_LOCKOUT: int +UF_PASSWD_NOTREQD: int +UF_PASSWD_CANT_CHANGE: int +UF_TEMP_DUPLICATE_ACCOUNT: int +UF_NORMAL_ACCOUNT: int +UF_INTERDOMAIN_TRUST_ACCOUNT: int +UF_WORKSTATION_TRUST_ACCOUNT: int +UF_SERVER_TRUST_ACCOUNT: int +UF_MACHINE_ACCOUNT_MASK: int +UF_ACCOUNT_TYPE_MASK: int +UF_DONT_EXPIRE_PASSWD: int +UF_MNS_LOGON_ACCOUNT: int +UF_SETTABLE_BITS: int +FILTER_TEMP_DUPLICATE_ACCOUNT: int +FILTER_NORMAL_ACCOUNT: int +FILTER_INTERDOMAIN_TRUST_ACCOUNT: int +FILTER_WORKSTATION_TRUST_ACCOUNT: int +FILTER_SERVER_TRUST_ACCOUNT: int +LG_INCLUDE_INDIRECT: int +AF_OP_PRINT: int +AF_OP_COMM: int +AF_OP_SERVER: int +AF_OP_ACCOUNTS: int +AF_SETTABLE_BITS: int +UAS_ROLE_STANDALONE: int +UAS_ROLE_MEMBER: int +UAS_ROLE_BACKUP: int +UAS_ROLE_PRIMARY: int +USER_NAME_PARMNUM: int +USER_PASSWORD_PARMNUM: int +USER_PASSWORD_AGE_PARMNUM: int +USER_PRIV_PARMNUM: int +USER_HOME_DIR_PARMNUM: int +USER_COMMENT_PARMNUM: int +USER_FLAGS_PARMNUM: int +USER_SCRIPT_PATH_PARMNUM: int +USER_AUTH_FLAGS_PARMNUM: int +USER_FULL_NAME_PARMNUM: int +USER_USR_COMMENT_PARMNUM: int +USER_PARMS_PARMNUM: int +USER_WORKSTATIONS_PARMNUM: int +USER_LAST_LOGON_PARMNUM: int +USER_LAST_LOGOFF_PARMNUM: int +USER_ACCT_EXPIRES_PARMNUM: int +USER_MAX_STORAGE_PARMNUM: int +USER_UNITS_PER_WEEK_PARMNUM: int +USER_LOGON_HOURS_PARMNUM: int +USER_PAD_PW_COUNT_PARMNUM: int +USER_NUM_LOGONS_PARMNUM: int +USER_LOGON_SERVER_PARMNUM: int +USER_COUNTRY_CODE_PARMNUM: int +USER_CODE_PAGE_PARMNUM: int +USER_PRIMARY_GROUP_PARMNUM: int +USER_PROFILE: int +USER_PROFILE_PARMNUM: int +USER_HOME_DIR_DRIVE_PARMNUM: int +USER_NAME_INFOLEVEL: int +USER_PASSWORD_INFOLEVEL: int +USER_PASSWORD_AGE_INFOLEVEL: int +USER_PRIV_INFOLEVEL: int +USER_HOME_DIR_INFOLEVEL: int +USER_COMMENT_INFOLEVEL: int +USER_FLAGS_INFOLEVEL: int +USER_SCRIPT_PATH_INFOLEVEL: int +USER_AUTH_FLAGS_INFOLEVEL: int +USER_FULL_NAME_INFOLEVEL: int +USER_USR_COMMENT_INFOLEVEL: int +USER_PARMS_INFOLEVEL: int +USER_WORKSTATIONS_INFOLEVEL: int +USER_LAST_LOGON_INFOLEVEL: int +USER_LAST_LOGOFF_INFOLEVEL: int +USER_ACCT_EXPIRES_INFOLEVEL: int +USER_MAX_STORAGE_INFOLEVEL: int +USER_UNITS_PER_WEEK_INFOLEVEL: int +USER_LOGON_HOURS_INFOLEVEL: int +USER_PAD_PW_COUNT_INFOLEVEL: int +USER_NUM_LOGONS_INFOLEVEL: int +USER_LOGON_SERVER_INFOLEVEL: int +USER_COUNTRY_CODE_INFOLEVEL: int +USER_CODE_PAGE_INFOLEVEL: int +USER_PRIMARY_GROUP_INFOLEVEL: int +USER_HOME_DIR_DRIVE_INFOLEVEL: int +NULL_USERSETINFO_PASSWD: str +UNITS_PER_DAY: int +UNITS_PER_WEEK: int +USER_PRIV_MASK: int +USER_PRIV_GUEST: int +USER_PRIV_USER: int +USER_PRIV_ADMIN: int +MAX_PASSWD_LEN: int +DEF_MIN_PWLEN: int +DEF_PWUNIQUENESS: int +DEF_MAX_PWHIST: int +DEF_MAX_BADPW: int +VALIDATED_LOGON: int +PASSWORD_EXPIRED: int +NON_VALIDATED_LOGON: int +VALID_LOGOFF: int +MODALS_MIN_PASSWD_LEN_PARMNUM: int +MODALS_MAX_PASSWD_AGE_PARMNUM: int +MODALS_MIN_PASSWD_AGE_PARMNUM: int +MODALS_FORCE_LOGOFF_PARMNUM: int +MODALS_PASSWD_HIST_LEN_PARMNUM: int +MODALS_ROLE_PARMNUM: int +MODALS_PRIMARY_PARMNUM: int +MODALS_DOMAIN_NAME_PARMNUM: int +MODALS_DOMAIN_ID_PARMNUM: int +MODALS_LOCKOUT_DURATION_PARMNUM: int +MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM: int +MODALS_LOCKOUT_THRESHOLD_PARMNUM: int +MODALS_MIN_PASSWD_LEN_INFOLEVEL: int +MODALS_MAX_PASSWD_AGE_INFOLEVEL: int +MODALS_MIN_PASSWD_AGE_INFOLEVEL: int +MODALS_FORCE_LOGOFF_INFOLEVEL: int +MODALS_PASSWD_HIST_LEN_INFOLEVEL: int +MODALS_ROLE_INFOLEVEL: int +MODALS_PRIMARY_INFOLEVEL: int +MODALS_DOMAIN_NAME_INFOLEVEL: int +MODALS_DOMAIN_ID_INFOLEVEL: int +GROUPIDMASK: int +GROUP_ALL_PARMNUM: int +GROUP_NAME_PARMNUM: int +GROUP_COMMENT_PARMNUM: int +GROUP_ATTRIBUTES_PARMNUM: int +GROUP_ALL_INFOLEVEL: int +GROUP_NAME_INFOLEVEL: int +GROUP_COMMENT_INFOLEVEL: int +GROUP_ATTRIBUTES_INFOLEVEL: int +LOCALGROUP_NAME_PARMNUM: int +LOCALGROUP_COMMENT_PARMNUM: int +MAXPERMENTRIES: int +ACCESS_NONE: int +ACCESS_READ: int +ACCESS_WRITE: int +ACCESS_CREATE: int +ACCESS_EXEC: int +ACCESS_DELETE: int +ACCESS_ATRIB: int +ACCESS_PERM: int +ACCESS_GROUP: int +ACCESS_AUDIT: int +ACCESS_SUCCESS_OPEN: int +ACCESS_SUCCESS_WRITE: int +ACCESS_SUCCESS_DELETE: int +ACCESS_SUCCESS_ACL: int +ACCESS_SUCCESS_MASK: int +ACCESS_FAIL_OPEN: int +ACCESS_FAIL_WRITE: int +ACCESS_FAIL_DELETE: int +ACCESS_FAIL_ACL: int +ACCESS_FAIL_MASK: int +ACCESS_FAIL_SHIFT: int +ACCESS_RESOURCE_NAME_PARMNUM: int +ACCESS_ATTR_PARMNUM: int +ACCESS_COUNT_PARMNUM: int +ACCESS_RESOURCE_NAME_INFOLEVEL: int +ACCESS_ATTR_INFOLEVEL: int +ACCESS_COUNT_INFOLEVEL: int +ACCESS_LETTERS: str +NETLOGON_CONTROL_QUERY: int +NETLOGON_CONTROL_REPLICATE: int +NETLOGON_CONTROL_SYNCHRONIZE: int +NETLOGON_CONTROL_PDC_REPLICATE: int +NETLOGON_CONTROL_REDISCOVER: int +NETLOGON_CONTROL_TC_QUERY: int +NETLOGON_CONTROL_TRANSPORT_NOTIFY: int +NETLOGON_CONTROL_FIND_USER: int +NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL: int +NETLOGON_CONTROL_BACKUP_CHANGE_LOG: int +NETLOGON_CONTROL_TRUNCATE_LOG: int +NETLOGON_CONTROL_SET_DBFLAG: int +NETLOGON_CONTROL_BREAKPOINT: int +NETLOGON_REPLICATION_NEEDED: int +NETLOGON_REPLICATION_IN_PROGRESS: int +NETLOGON_FULL_SYNC_REPLICATION: int +NETLOGON_REDO_NEEDED: int + +def TEXT(x: str) -> str: ... + +MAX_PREFERRED_LENGTH: int +PARM_ERROR_UNKNOWN: int +MESSAGE_FILENAME: str +OS2MSG_FILENAME: str +HELP_MSG_FILENAME: str +BACKUP_MSG_FILENAME: str +TIMEQ_FOREVER: int +USER_MAXSTORAGE_UNLIMITED: int +USER_NO_LOGOFF: int +DEF_MAX_PWAGE: int +DEF_MIN_PWAGE: int +DEF_FORCE_LOGOFF: int +ONE_DAY: int +GROUP_SPECIALGRP_USERS: str +GROUP_SPECIALGRP_ADMINS: str +GROUP_SPECIALGRP_GUESTS: str +GROUP_SPECIALGRP_LOCAL: str +ACCESS_ALL: int +SV_PLATFORM_ID_OS2: int +SV_PLATFORM_ID_NT: int +MAJOR_VERSION_MASK: int +SV_TYPE_WORKSTATION: int +SV_TYPE_SERVER: int +SV_TYPE_SQLSERVER: int +SV_TYPE_DOMAIN_CTRL: int +SV_TYPE_DOMAIN_BAKCTRL: int +SV_TYPE_TIME_SOURCE: int +SV_TYPE_AFP: int +SV_TYPE_NOVELL: int +SV_TYPE_DOMAIN_MEMBER: int +SV_TYPE_PRINTQ_SERVER: int +SV_TYPE_DIALIN_SERVER: int +SV_TYPE_XENIX_SERVER: int +SV_TYPE_SERVER_UNIX: int +SV_TYPE_NT: int +SV_TYPE_WFW: int +SV_TYPE_SERVER_MFPN: int +SV_TYPE_SERVER_NT: int +SV_TYPE_POTENTIAL_BROWSER: int +SV_TYPE_BACKUP_BROWSER: int +SV_TYPE_MASTER_BROWSER: int +SV_TYPE_DOMAIN_MASTER: int +SV_TYPE_SERVER_OSF: int +SV_TYPE_SERVER_VMS: int +SV_TYPE_WINDOWS: int +SV_TYPE_DFS: int +SV_TYPE_CLUSTER_NT: int +SV_TYPE_DCE: int +SV_TYPE_ALTERNATE_XPORT: int +SV_TYPE_DOMAIN_ENUM: int +SV_TYPE_ALL: int +SV_NODISC: int +SV_USERSECURITY: int +SV_SHARESECURITY: int +SV_HIDDEN: int +SV_VISIBLE: int +SV_PLATFORM_ID_PARMNUM: int +SV_NAME_PARMNUM: int +SV_VERSION_MAJOR_PARMNUM: int +SV_VERSION_MINOR_PARMNUM: int +SV_TYPE_PARMNUM: int +SV_COMMENT_PARMNUM: int +SV_USERS_PARMNUM: int +SV_DISC_PARMNUM: int +SV_HIDDEN_PARMNUM: int +SV_ANNOUNCE_PARMNUM: int +SV_ANNDELTA_PARMNUM: int +SV_USERPATH_PARMNUM: int +SV_ALERTS_PARMNUM: int +SV_SECURITY_PARMNUM: int +SV_NUMADMIN_PARMNUM: int +SV_LANMASK_PARMNUM: int +SV_GUESTACC_PARMNUM: int +SV_CHDEVQ_PARMNUM: int +SV_CHDEVJOBS_PARMNUM: int +SV_CONNECTIONS_PARMNUM: int +SV_SHARES_PARMNUM: int +SV_OPENFILES_PARMNUM: int +SV_SESSREQS_PARMNUM: int +SV_ACTIVELOCKS_PARMNUM: int +SV_NUMREQBUF_PARMNUM: int +SV_NUMBIGBUF_PARMNUM: int +SV_NUMFILETASKS_PARMNUM: int +SV_ALERTSCHED_PARMNUM: int +SV_ERRORALERT_PARMNUM: int +SV_LOGONALERT_PARMNUM: int +SV_ACCESSALERT_PARMNUM: int +SV_DISKALERT_PARMNUM: int +SV_NETIOALERT_PARMNUM: int +SV_MAXAUDITSZ_PARMNUM: int +SV_SRVHEURISTICS_PARMNUM: int +SV_SESSOPENS_PARMNUM: int +SV_SESSVCS_PARMNUM: int +SV_OPENSEARCH_PARMNUM: int +SV_SIZREQBUF_PARMNUM: int +SV_INITWORKITEMS_PARMNUM: int +SV_MAXWORKITEMS_PARMNUM: int +SV_RAWWORKITEMS_PARMNUM: int +SV_IRPSTACKSIZE_PARMNUM: int +SV_MAXRAWBUFLEN_PARMNUM: int +SV_SESSUSERS_PARMNUM: int +SV_SESSCONNS_PARMNUM: int +SV_MAXNONPAGEDMEMORYUSAGE_PARMNUM: int +SV_MAXPAGEDMEMORYUSAGE_PARMNUM: int +SV_ENABLESOFTCOMPAT_PARMNUM: int +SV_ENABLEFORCEDLOGOFF_PARMNUM: int +SV_TIMESOURCE_PARMNUM: int +SV_ACCEPTDOWNLEVELAPIS_PARMNUM: int +SV_LMANNOUNCE_PARMNUM: int +SV_DOMAIN_PARMNUM: int +SV_MAXCOPYREADLEN_PARMNUM: int +SV_MAXCOPYWRITELEN_PARMNUM: int +SV_MINKEEPSEARCH_PARMNUM: int +SV_MAXKEEPSEARCH_PARMNUM: int +SV_MINKEEPCOMPLSEARCH_PARMNUM: int +SV_MAXKEEPCOMPLSEARCH_PARMNUM: int +SV_THREADCOUNTADD_PARMNUM: int +SV_NUMBLOCKTHREADS_PARMNUM: int +SV_SCAVTIMEOUT_PARMNUM: int +SV_MINRCVQUEUE_PARMNUM: int +SV_MINFREEWORKITEMS_PARMNUM: int +SV_XACTMEMSIZE_PARMNUM: int +SV_THREADPRIORITY_PARMNUM: int +SV_MAXMPXCT_PARMNUM: int +SV_OPLOCKBREAKWAIT_PARMNUM: int +SV_OPLOCKBREAKRESPONSEWAIT_PARMNUM: int +SV_ENABLEOPLOCKS_PARMNUM: int +SV_ENABLEOPLOCKFORCECLOSE_PARMNUM: int +SV_ENABLEFCBOPENS_PARMNUM: int +SV_ENABLERAW_PARMNUM: int +SV_ENABLESHAREDNETDRIVES_PARMNUM: int +SV_MINFREECONNECTIONS_PARMNUM: int +SV_MAXFREECONNECTIONS_PARMNUM: int +SV_INITSESSTABLE_PARMNUM: int +SV_INITCONNTABLE_PARMNUM: int +SV_INITFILETABLE_PARMNUM: int +SV_INITSEARCHTABLE_PARMNUM: int +SV_ALERTSCHEDULE_PARMNUM: int +SV_ERRORTHRESHOLD_PARMNUM: int +SV_NETWORKERRORTHRESHOLD_PARMNUM: int +SV_DISKSPACETHRESHOLD_PARMNUM: int +SV_MAXLINKDELAY_PARMNUM: int +SV_MINLINKTHROUGHPUT_PARMNUM: int +SV_LINKINFOVALIDTIME_PARMNUM: int +SV_SCAVQOSINFOUPDATETIME_PARMNUM: int +SV_MAXWORKITEMIDLETIME_PARMNUM: int +SV_MAXRAWWORKITEMS_PARMNUM: int +SV_PRODUCTTYPE_PARMNUM: int +SV_SERVERSIZE_PARMNUM: int +SV_CONNECTIONLESSAUTODISC_PARMNUM: int +SV_SHARINGVIOLATIONRETRIES_PARMNUM: int +SV_SHARINGVIOLATIONDELAY_PARMNUM: int +SV_MAXGLOBALOPENSEARCH_PARMNUM: int +SV_REMOVEDUPLICATESEARCHES_PARMNUM: int +SV_LOCKVIOLATIONRETRIES_PARMNUM: int +SV_LOCKVIOLATIONOFFSET_PARMNUM: int +SV_LOCKVIOLATIONDELAY_PARMNUM: int +SV_MDLREADSWITCHOVER_PARMNUM: int +SV_CACHEDOPENLIMIT_PARMNUM: int +SV_CRITICALTHREADS_PARMNUM: int +SV_RESTRICTNULLSESSACCESS_PARMNUM: int +SV_ENABLEWFW311DIRECTIPX_PARMNUM: int +SV_OTHERQUEUEAFFINITY_PARMNUM: int +SV_QUEUESAMPLESECS_PARMNUM: int +SV_BALANCECOUNT_PARMNUM: int +SV_PREFERREDAFFINITY_PARMNUM: int +SV_MAXFREERFCBS_PARMNUM: int +SV_MAXFREEMFCBS_PARMNUM: int +SV_MAXFREELFCBS_PARMNUM: int +SV_MAXFREEPAGEDPOOLCHUNKS_PARMNUM: int +SV_MINPAGEDPOOLCHUNKSIZE_PARMNUM: int +SV_MAXPAGEDPOOLCHUNKSIZE_PARMNUM: int +SV_SENDSFROMPREFERREDPROCESSOR_PARMNUM: int +SV_MAXTHREADSPERQUEUE_PARMNUM: int +SV_CACHEDDIRECTORYLIMIT_PARMNUM: int +SV_MAXCOPYLENGTH_PARMNUM: int +SV_ENABLEBULKTRANSFER_PARMNUM: int +SV_ENABLECOMPRESSION_PARMNUM: int +SV_AUTOSHAREWKS_PARMNUM: int +SV_AUTOSHARESERVER_PARMNUM: int +SV_ENABLESECURITYSIGNATURE_PARMNUM: int +SV_REQUIRESECURITYSIGNATURE_PARMNUM: int +SV_MINCLIENTBUFFERSIZE_PARMNUM: int +SV_CONNECTIONNOSESSIONSTIMEOUT_PARMNUM: int +SVI1_NUM_ELEMENTS: int +SVI2_NUM_ELEMENTS: int +SVI3_NUM_ELEMENTS: int +SW_AUTOPROF_LOAD_MASK: int +SW_AUTOPROF_SAVE_MASK: int +SV_MAX_SRV_HEUR_LEN: int +SV_USERS_PER_LICENSE: int +SVTI2_REMAP_PIPE_NAMES: int +SHARE_NETNAME_PARMNUM: int +SHARE_TYPE_PARMNUM: int +SHARE_REMARK_PARMNUM: int +SHARE_PERMISSIONS_PARMNUM: int +SHARE_MAX_USES_PARMNUM: int +SHARE_CURRENT_USES_PARMNUM: int +SHARE_PATH_PARMNUM: int +SHARE_PASSWD_PARMNUM: int +SHARE_FILE_SD_PARMNUM: int +SHI1_NUM_ELEMENTS: int +SHI2_NUM_ELEMENTS: int +STYPE_DISKTREE: int +STYPE_PRINTQ: int +STYPE_DEVICE: int +STYPE_IPC: int +STYPE_SPECIAL: int +SHI1005_FLAGS_DFS: int +SHI1005_FLAGS_DFS_ROOT: int +COW_PERMACHINE: int +COW_PERUSER: int +CSC_CACHEABLE: int +CSC_NOFLOWOPS: int +CSC_AUTO_INWARD: int +CSC_AUTO_OUTWARD: int +SHI1005_VALID_FLAGS_SET: int +SHI1007_VALID_FLAGS_SET: int +SESS_GUEST: int +SESS_NOENCRYPTION: int +SESI1_NUM_ELEMENTS: int +SESI2_NUM_ELEMENTS: int +PERM_FILE_READ: int +PERM_FILE_WRITE: int +PERM_FILE_CREATE: int +WNNC_NET_MSNET: int +WNNC_NET_LANMAN: int +WNNC_NET_NETWARE: int +WNNC_NET_VINES: int +WNNC_NET_10NET: int +WNNC_NET_LOCUS: int +WNNC_NET_SUN_PC_NFS: int +WNNC_NET_LANSTEP: int +WNNC_NET_9TILES: int +WNNC_NET_LANTASTIC: int +WNNC_NET_AS400: int +WNNC_NET_FTP_NFS: int +WNNC_NET_PATHWORKS: int +WNNC_NET_LIFENET: int +WNNC_NET_POWERLAN: int +WNNC_NET_BWNFS: int +WNNC_NET_COGENT: int +WNNC_NET_FARALLON: int +WNNC_NET_APPLETALK: int +WNNC_NET_INTERGRAPH: int +WNNC_NET_SYMFONET: int +WNNC_NET_CLEARCASE: int +WNNC_NET_FRONTIER: int +WNNC_NET_BMC: int +WNNC_NET_DCE: int +WNNC_NET_DECORB: int +WNNC_NET_PROTSTOR: int +WNNC_NET_FJ_REDIR: int +WNNC_NET_DISTINCT: int +WNNC_NET_TWINS: int +WNNC_NET_RDR2SAMPLE: int +RESOURCE_CONNECTED: int +RESOURCE_GLOBALNET: int +RESOURCE_REMEMBERED: int +RESOURCE_RECENT: int +RESOURCE_CONTEXT: int +RESOURCETYPE_ANY: int +RESOURCETYPE_DISK: int +RESOURCETYPE_PRINT: int +RESOURCETYPE_RESERVED: int +RESOURCETYPE_UNKNOWN: int +RESOURCEUSAGE_CONNECTABLE: int +RESOURCEUSAGE_CONTAINER: int +RESOURCEUSAGE_NOLOCALDEVICE: int +RESOURCEUSAGE_SIBLING: int +RESOURCEUSAGE_ATTACHED: int +RESOURCEUSAGE_ALL: int +RESOURCEUSAGE_RESERVED: int +RESOURCEDISPLAYTYPE_GENERIC: int +RESOURCEDISPLAYTYPE_DOMAIN: int +RESOURCEDISPLAYTYPE_SERVER: int +RESOURCEDISPLAYTYPE_SHARE: int +RESOURCEDISPLAYTYPE_FILE: int +RESOURCEDISPLAYTYPE_GROUP: int +RESOURCEDISPLAYTYPE_NETWORK: int +RESOURCEDISPLAYTYPE_ROOT: int +RESOURCEDISPLAYTYPE_SHAREADMIN: int +RESOURCEDISPLAYTYPE_DIRECTORY: int +RESOURCEDISPLAYTYPE_TREE: int +RESOURCEDISPLAYTYPE_NDSCONTAINER: int +NETPROPERTY_PERSISTENT: int +CONNECT_UPDATE_PROFILE: int +CONNECT_UPDATE_RECENT: int +CONNECT_TEMPORARY: int +CONNECT_INTERACTIVE: int +CONNECT_PROMPT: int +CONNECT_NEED_DRIVE: int +CONNECT_REFCOUNT: int +CONNECT_REDIRECT: int +CONNECT_LOCALDRIVE: int +CONNECT_CURRENT_MEDIA: int +CONNECT_DEFERRED: int +CONNECT_RESERVED: int +CONNDLG_RO_PATH: int +CONNDLG_CONN_POINT: int +CONNDLG_USE_MRU: int +CONNDLG_HIDE_BOX: int +CONNDLG_PERSIST: int +CONNDLG_NOT_PERSIST: int +DISC_UPDATE_PROFILE: int +DISC_NO_FORCE: int +UNIVERSAL_NAME_INFO_LEVEL: int +REMOTE_NAME_INFO_LEVEL: int +WNFMT_MULTILINE: int +WNFMT_ABBREVIATED: int +WNFMT_INENUM: int +WNFMT_CONNECTION: int +NETINFO_DLL16: int +NETINFO_DISKRED: int +NETINFO_PRINTERRED: int +RP_LOGON: int +RP_INIFILE: int +PP_DISPLAYERRORS: int +WNCON_FORNETCARD: int +WNCON_NOTROUTED: int +WNCON_SLOWLINK: int +WNCON_DYNAMIC: int +NetSetupUnknown: int +NetSetupMachine: int +NetSetupWorkgroup: int +NetSetupDomain: int +NetSetupNonExistentDomain: int +NetSetupDnsMachine: int +NetSetupUnknownStatus: int +NetSetupUnjoined: int +NetSetupWorkgroupName: int +NetSetupDomainName: int +NetValidateAuthentication: int +NetValidatePasswordChange: int +NetValidatePasswordReset: int +ACCESS_ACCESS_LIST_INFOLEVEL: int +ACCESS_ACCESS_LIST_PARMNUM: int +SV_ALIST_MTIME_PARMNUM: int +SV_GLIST_MTIME_PARMNUM: int +SV_TYPE_LOCAL_LIST_ONLY: int +SV_ULIST_MTIME_PARMNUM: int diff --git a/stubs/pywin32/win32/lib/win32pdhquery.pyi b/stubs/pywin32/win32/lib/win32pdhquery.pyi new file mode 100644 index 000000000000..62753b214e80 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32pdhquery.pyi @@ -0,0 +1,45 @@ +from _typeshed import Incomplete +from typing_extensions import deprecated + +class BaseQuery: + counters: Incomplete + paths: Incomplete + active: int + curpaths: Incomplete + def __init__(self, paths: Incomplete | None = ...) -> None: ... + def addcounterbybrowsing(self, flags=..., windowtitle: str = ...) -> None: ... + def rawaddcounter( + self, object, counter, instance: Incomplete | None = ..., inum: int = ..., machine: Incomplete | None = ... + ) -> None: ... + def addcounter( + self, object, counter, instance: Incomplete | None = ..., inum: int = ..., machine: Incomplete | None = ... + ): ... + def open(self): ... + def killbase(self, base: Incomplete | None = ...) -> None: ... + def close(self) -> None: ... + __del__: Incomplete + def collectdata(self, format=...): ... + def collectdataslave(self, format=...): ... + def __getinitargs__(self): ... + +class Query(BaseQuery): + volatilecounters: Incomplete + def __init__(self, *args, **namedargs) -> None: ... + @deprecated("Use `addcounterbybrowsing` instead.") + def addperfcounter(self, object, counter, machine=None): ... + def addinstcounter( + self, object, counter, machine: Incomplete | None = ..., objtype: str = ..., volatile: int = ..., format=... + ) -> None: ... + def getinstpaths(self, object, counter, machine: Incomplete | None = ..., objtype: str = ..., format=...): ... + def open(self, *args, **namedargs) -> None: ... + curresults: Incomplete + def collectdatafor(self, totalperiod, period: int = ...) -> None: ... + collectdatawhile_active: int + def collectdatawhile(self, period: int = ...) -> None: ... + def collectdatawhile_stop(self) -> None: ... + def collectdatawhile_slave(self, period) -> None: ... + def __getinitargs__(self): ... + +class QueryError: + query: Incomplete + def __init__(self, query) -> None: ... diff --git a/stubs/pywin32/win32/lib/win32serviceutil.pyi b/stubs/pywin32/win32/lib/win32serviceutil.pyi new file mode 100644 index 000000000000..d31471255b4a --- /dev/null +++ b/stubs/pywin32/win32/lib/win32serviceutil.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Sequence + +error = RuntimeError + +def LocatePythonServiceExe(exe: Incomplete | None = ...): ... +def SmartOpenService(hscm, name, access): ... +def LocateSpecificServiceExe(serviceName): ... +def InstallPerfmonForService(serviceName, iniName, dllName: Incomplete | None = ...) -> None: ... +def InstallService( + pythonClassString, + serviceName, + displayName, + startType: Incomplete | None = ..., + errorControl: Incomplete | None = ..., + bRunInteractive: int = ..., + serviceDeps: Incomplete | None = ..., + userName: Incomplete | None = ..., + password: Incomplete | None = ..., + exeName: Incomplete | None = ..., + perfMonIni: Incomplete | None = ..., + perfMonDll: Incomplete | None = ..., + exeArgs: Incomplete | None = ..., + description: Incomplete | None = ..., + delayedstart: Incomplete | None = ..., +) -> None: ... +def ChangeServiceConfig( + pythonClassString, + serviceName, + startType: Incomplete | None = ..., + errorControl: Incomplete | None = ..., + bRunInteractive: int = ..., + serviceDeps: Incomplete | None = ..., + userName: Incomplete | None = ..., + password: Incomplete | None = ..., + exeName: Incomplete | None = ..., + displayName: Incomplete | None = ..., + perfMonIni: Incomplete | None = ..., + perfMonDll: Incomplete | None = ..., + exeArgs: Incomplete | None = ..., + description: Incomplete | None = ..., + delayedstart: Incomplete | None = ..., +) -> None: ... +def InstallPythonClassString(pythonClassString, serviceName) -> None: ... +def SetServiceCustomOption(serviceName, option, value) -> None: ... +def GetServiceCustomOption(serviceName, option, defaultValue: Incomplete | None = ...): ... +def RemoveService(serviceName) -> None: ... +def ControlService(serviceName, code, machine: Incomplete | None = ...): ... +def WaitForServiceStatus(serviceName, status, waitSecs, machine: Incomplete | None = ...) -> None: ... +def StopServiceWithDeps(serviceName, machine: Incomplete | None = ..., waitSecs: int = ...) -> None: ... +def StopService(serviceName, machine: Incomplete | None = ...): ... +def StartService(serviceName, args: Incomplete | None = ..., machine: Incomplete | None = ...) -> None: ... +def RestartService( + serviceName, args: Incomplete | None = ..., waitSeconds: int = ..., machine: Incomplete | None = ... +) -> None: ... +def DebugService(cls, argv=...) -> None: ... +def GetServiceClassString(cls, argv: Incomplete | None = ...): ... +def QueryServiceStatus(serviceName, machine: Incomplete | None = ...): ... +def usage() -> None: ... +def HandleCommandLine( + cls: type[ServiceFramework], + serviceClassString: Incomplete | None = ..., + argv: Sequence[str] | None = ..., + customInstallOptions: str = ..., + customOptionHandler: Incomplete | None = ..., +): ... + +class ServiceFramework: + ssh: Incomplete + checkPoint: int + def __init__(self, args: Iterable[str]) -> None: ... + def GetAcceptedControls(self): ... + def ReportServiceStatus( + self, serviceStatus, waitHint: int = ..., win32ExitCode: int = ..., svcExitCode: int = ... + ) -> None: ... + def SvcInterrogate(self) -> None: ... + def SvcOther(self, control) -> None: ... + def ServiceCtrlHandler(self, control): ... + def SvcOtherEx(self, control, event_type, data): ... + def ServiceCtrlHandlerEx(self, control, event_type, data): ... + def SvcRun(self) -> None: ... diff --git a/stubs/pywin32/win32/lib/win32timezone.pyi b/stubs/pywin32/win32/lib/win32timezone.pyi new file mode 100644 index 000000000000..15508cc26158 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32timezone.pyi @@ -0,0 +1,120 @@ +import datetime +from _operator import _SupportsComparison +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Iterable, Mapping +from logging import Logger +from typing import ClassVar, TypeVar, overload, type_check_only +from typing_extensions import Self + +_RangeMapKT = TypeVar("_RangeMapKT", bound=_SupportsComparison) + +_T = TypeVar("_T") +_VT = TypeVar("_VT") + +log: Logger + +class _SimpleStruct: + def __init__(self, *args, **kw) -> None: ... + def field_names(self) -> list[str]: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +class SYSTEMTIME(_SimpleStruct): ... +class TIME_ZONE_INFORMATION(_SimpleStruct): ... +class DYNAMIC_TIME_ZONE_INFORMATION(_SimpleStruct): ... + +class TimeZoneDefinition(DYNAMIC_TIME_ZONE_INFORMATION): + def __init__(self, *args, **kwargs) -> None: ... + # TIME_ZONE_INFORMATION fields as obtained by __getattribute__ + bias: datetime.timedelta + standard_name: str + standard_start: SYSTEMTIME + standard_bias: datetime.timedelta + daylight_name: str + daylight_start: SYSTEMTIME + daylight_bias: datetime.timedelta + def __getattribute__(self, attr: str): ... + @classmethod + def current(cls) -> tuple[int, Self]: ... + def set(self) -> None: ... + def copy(self) -> Self: ... + def locate_daylight_start(self, year) -> datetime.datetime: ... + def locate_standard_start(self, year) -> datetime.datetime: ... + +class TimeZoneInfo(datetime.tzinfo): + tzRegKey: ClassVar[str] + timeZoneName: str + fixedStandardTime: bool + def __init__(self, param: str | TimeZoneDefinition, fix_standard_time: bool = False) -> None: ... + + @overload # type: ignore[override] # Split definition into overrides + def tzname(self, dt: datetime.datetime) -> str: ... + @overload + def tzname(self, dt: None) -> None: ... + + def getWinInfo(self, targetYear: int) -> TimeZoneDefinition: ... + + @overload # type: ignore[override] # False-positive, our overload covers all base types + def utcoffset(self, dt: None) -> None: ... + @overload + def utcoffset(self, dt: datetime.datetime) -> datetime.timedelta: ... + + @overload # type: ignore[override] # False-positive, our overload covers all base types + def dst(self, dt: None) -> None: ... + @overload + def dst(self, dt: datetime.datetime) -> datetime.timedelta: ... + + def GetDSTStartTime(self, year: int) -> datetime.datetime: ... + def GetDSTEndTime(self, year: int) -> datetime.datetime: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + @classmethod + def local(cls) -> Self: ... + @classmethod + def utc(cls) -> Self: ... + @staticmethod + def get_sorted_time_zone_names() -> list[str]: ... + @staticmethod + def get_all_time_zones() -> list[TimeZoneInfo]: ... + @staticmethod + def get_sorted_time_zones(key: Incomplete | None = ...): ... + +def utcnow() -> datetime.datetime: ... +def now() -> datetime.datetime: ... +def GetTZCapabilities() -> dict[str, bool]: ... + +class DLLHandleCache: + def __getitem__(self, filename: str) -> int: ... + +DLLCache: DLLHandleCache + +def resolveMUITimeZone(spec: str) -> str | None: ... + +class RangeMap(dict[_RangeMapKT, _VT]): + sort_params: Mapping[str, Incomplete] + match: Callable[[_RangeMapKT, _RangeMapKT], bool] + def __init__( + self, + source: SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]], + sort_params: Mapping[str, Incomplete] = {}, + key_match_comparator: Callable[[_RangeMapKT, _RangeMapKT], bool] = ..., + ) -> None: ... + @classmethod + def left(cls, source: SupportsKeysAndGetItem[_RangeMapKT, _VT] | Iterable[tuple[_RangeMapKT, _VT]]) -> Self: ... + def __getitem__(self, item: _RangeMapKT) -> _VT: ... + + @overload # type: ignore[override] # Signature simplified over dict and Mapping + def get(self, key: _RangeMapKT, default: _T) -> _VT | _T: ... + @overload + def get(self, key: _RangeMapKT, default: None = None) -> _VT | None: ... + + def bounds(self) -> tuple[_RangeMapKT, _RangeMapKT]: ... + + @type_check_only + class RangeValueUndefined: ... + + undefined_value: RangeValueUndefined + + class Item(int): ... + first_item: Item + last_item: Item diff --git a/stubs/pywin32/win32/lib/win32verstamp.pyi b/stubs/pywin32/win32/lib/win32verstamp.pyi new file mode 100644 index 000000000000..cac01f8475e1 --- /dev/null +++ b/stubs/pywin32/win32/lib/win32verstamp.pyi @@ -0,0 +1,21 @@ +from typing import Final + +VS_FFI_SIGNATURE: Final = -17890115 +VS_FFI_STRUCVERSION: Final = 0x00010000 +VS_FFI_FILEFLAGSMASK: Final = 0x0000003F +VOS_NT_WINDOWS32: Final = 0x00040004 +null_byte: Final = b"\0" + +def file_flags(debug): ... +def file_type(is_dll): ... +def VS_FIXEDFILEINFO(maj, min, sub, build, debug: int = 0, is_dll: int = 1): ... +def nullterm(s): ... +def pad32(s, extra: int = 2): ... +def addlen(s): ... +def String(key, value): ... +def StringTable(key, data): ... +def StringFileInfo(data): ... +def Var(key, value): ... +def VarFileInfo(data): ... +def VS_VERSION_INFO(maj, min, sub, build, sdata, vdata, debug: int = 0, is_dll: int = 1): ... +def stamp(pathname, options) -> None: ... diff --git a/stubs/pywin32/win32/lib/winerror.pyi b/stubs/pywin32/win32/lib/winerror.pyi new file mode 100644 index 000000000000..a40ca554ca0b --- /dev/null +++ b/stubs/pywin32/win32/lib/winerror.pyi @@ -0,0 +1,7270 @@ +from typing import Final + +ERROR_INSTALL_SERVICE: Final = 1601 +ERROR_BAD_DATABASE_VERSION: Final = 1613 +win16_E_NOTIMPL: Final = -2147483647 +win16_E_OUTOFMEMORY: Final = -2147483646 +win16_E_INVALIDARG: Final = -2147483645 +win16_E_NOINTERFACE: Final = -2147483644 +win16_E_POINTER: Final = -2147483643 +win16_E_HANDLE: Final = -2147483642 +win16_E_ABORT: Final = -2147483641 +win16_E_FAIL: Final = -2147483640 +win16_E_ACCESSDENIED: Final = -2147483639 +CERTDB_E_JET_ERROR: Final = -2146873344 + +FACILITY_NULL: Final = 0 +FACILITY_RPC: Final = 1 +FACILITY_DISPATCH: Final = 2 +FACILITY_STORAGE: Final = 3 +FACILITY_ITF: Final = 4 +FACILITY_WIN32: Final = 7 +FACILITY_WINDOWS: Final = 8 +FACILITY_SSPI: Final = 9 +FACILITY_SECURITY: Final = 9 +FACILITY_CONTROL: Final = 10 +FACILITY_CERT: Final = 11 +FACILITY_INTERNET: Final = 12 +FACILITY_MEDIASERVER: Final = 13 +FACILITY_MSMQ: Final = 14 +FACILITY_SETUPAPI: Final = 15 +FACILITY_SCARD: Final = 16 +FACILITY_COMPLUS: Final = 17 +FACILITY_AAF: Final = 18 +FACILITY_URT: Final = 19 +FACILITY_ACS: Final = 20 +FACILITY_DPLAY: Final = 21 +FACILITY_UMI: Final = 22 +FACILITY_SXS: Final = 23 +FACILITY_WINDOWS_CE: Final = 24 +FACILITY_HTTP: Final = 25 +FACILITY_USERMODE_COMMONLOG: Final = 26 +FACILITY_WER: Final = 27 +FACILITY_USERMODE_FILTER_MANAGER: Final = 31 +FACILITY_BACKGROUNDCOPY: Final = 32 +FACILITY_CONFIGURATION: Final = 33 +FACILITY_WIA: Final = 33 +FACILITY_STATE_MANAGEMENT: Final = 34 +FACILITY_METADIRECTORY: Final = 35 +FACILITY_WINDOWSUPDATE: Final = 36 +FACILITY_DIRECTORYSERVICE: Final = 37 +FACILITY_GRAPHICS: Final = 38 +FACILITY_SHELL: Final = 39 +FACILITY_NAP: Final = 39 +FACILITY_TPM_SERVICES: Final = 40 +FACILITY_TPM_SOFTWARE: Final = 41 +FACILITY_UI: Final = 42 +FACILITY_XAML: Final = 43 +FACILITY_ACTION_QUEUE: Final = 44 +FACILITY_PLA: Final = 48 +FACILITY_WINDOWS_SETUP: Final = 48 +FACILITY_FVE: Final = 49 +FACILITY_FWP: Final = 50 +FACILITY_WINRM: Final = 51 +FACILITY_NDIS: Final = 52 +FACILITY_USERMODE_HYPERVISOR: Final = 53 +FACILITY_CMI: Final = 54 +FACILITY_USERMODE_VIRTUALIZATION: Final = 55 +FACILITY_USERMODE_VOLMGR: Final = 56 +FACILITY_BCD: Final = 57 +FACILITY_USERMODE_VHD: Final = 58 +FACILITY_USERMODE_HNS: Final = 59 +FACILITY_SDIAG: Final = 60 +FACILITY_WEBSERVICES: Final = 61 +FACILITY_WINPE: Final = 61 +FACILITY_WPN: Final = 62 +FACILITY_WINDOWS_STORE: Final = 63 +FACILITY_INPUT: Final = 64 +FACILITY_QUIC: Final = 65 +FACILITY_EAP: Final = 66 +FACILITY_IORING: Final = 70 +FACILITY_WINDOWS_DEFENDER: Final = 80 +FACILITY_OPC: Final = 81 +FACILITY_XPS: Final = 82 +FACILITY_MBN: Final = 84 +FACILITY_POWERSHELL: Final = 84 +FACILITY_RAS: Final = 83 +FACILITY_P2P_INT: Final = 98 +FACILITY_P2P: Final = 99 +FACILITY_DAF: Final = 100 +FACILITY_BLUETOOTH_ATT: Final = 101 +FACILITY_AUDIO: Final = 102 +FACILITY_STATEREPOSITORY: Final = 103 +FACILITY_VISUALCPP: Final = 109 +FACILITY_SCRIPT: Final = 112 +FACILITY_PARSE: Final = 113 +FACILITY_BLB: Final = 120 +FACILITY_BLB_CLI: Final = 121 +FACILITY_WSBAPP: Final = 122 +FACILITY_BLBUI: Final = 128 +FACILITY_USN: Final = 129 +FACILITY_USERMODE_VOLSNAP: Final = 130 +FACILITY_TIERING: Final = 131 +FACILITY_WSB_ONLINE: Final = 133 +FACILITY_ONLINE_ID: Final = 134 +FACILITY_DEVICE_UPDATE_AGENT: Final = 135 +FACILITY_DRVSERVICING: Final = 136 +FACILITY_DLS: Final = 153 +FACILITY_DELIVERY_OPTIMIZATION: Final = 208 +FACILITY_USERMODE_SPACES: Final = 231 +FACILITY_USER_MODE_SECURITY_CORE: Final = 232 +FACILITY_USERMODE_LICENSING: Final = 234 +FACILITY_SOS: Final = 160 +FACILITY_OCP_UPDATE_AGENT: Final = 173 +FACILITY_DEBUGGERS: Final = 176 +FACILITY_SPP: Final = 256 +FACILITY_RESTORE: Final = 256 +FACILITY_DMSERVER: Final = 256 +FACILITY_DEPLOYMENT_SERVICES_SERVER: Final = 257 +FACILITY_DEPLOYMENT_SERVICES_IMAGING: Final = 258 +FACILITY_DEPLOYMENT_SERVICES_MANAGEMENT: Final = 259 +FACILITY_DEPLOYMENT_SERVICES_UTIL: Final = 260 +FACILITY_DEPLOYMENT_SERVICES_BINLSVC: Final = 261 +FACILITY_DEPLOYMENT_SERVICES_PXE: Final = 263 +FACILITY_DEPLOYMENT_SERVICES_TFTP: Final = 264 +FACILITY_DEPLOYMENT_SERVICES_TRANSPORT_MANAGEMENT: Final = 272 +FACILITY_DEPLOYMENT_SERVICES_DRIVER_PROVISIONING: Final = 278 +FACILITY_DEPLOYMENT_SERVICES_MULTICAST_SERVER: Final = 289 +FACILITY_DEPLOYMENT_SERVICES_MULTICAST_CLIENT: Final = 290 +FACILITY_DEPLOYMENT_SERVICES_CONTENT_PROVIDER: Final = 293 +FACILITY_HSP_SERVICES: Final = 296 +FACILITY_HSP_SOFTWARE: Final = 297 +FACILITY_LINGUISTIC_SERVICES: Final = 305 +FACILITY_AUDIOSTREAMING: Final = 1094 +FACILITY_TTD: Final = 1490 +FACILITY_ACCELERATOR: Final = 1536 +FACILITY_WMAAECMA: Final = 1996 +FACILITY_DIRECTMUSIC: Final = 2168 +FACILITY_DIRECT3D10: Final = 2169 +FACILITY_DXGI: Final = 2170 +FACILITY_DXGI_DDI: Final = 2171 +FACILITY_DIRECT3D11: Final = 2172 +FACILITY_DIRECT3D11_DEBUG: Final = 2173 +FACILITY_DIRECT3D12: Final = 2174 +FACILITY_DIRECT3D12_DEBUG: Final = 2175 +FACILITY_DXCORE: Final = 2176 +FACILITY_PRESENTATION: Final = 2177 +FACILITY_LEAP: Final = 2184 +FACILITY_AUDCLNT: Final = 2185 +FACILITY_WINCODEC_DWRITE_DWM: Final = 2200 +FACILITY_WINML: Final = 2192 +FACILITY_DIRECT2D: Final = 2201 +FACILITY_DEFRAG: Final = 2304 +FACILITY_USERMODE_SDBUS: Final = 2305 +FACILITY_JSCRIPT: Final = 2306 +FACILITY_PIDGENX: Final = 2561 +FACILITY_EAS: Final = 85 +FACILITY_WEB: Final = 885 +FACILITY_WEB_SOCKET: Final = 886 +FACILITY_MOBILE: Final = 1793 +FACILITY_SQLITE: Final = 1967 +FACILITY_SERVICE_FABRIC: Final = 1968 +FACILITY_UTC: Final = 1989 +FACILITY_WEP: Final = 2049 +FACILITY_SYNCENGINE: Final = 2050 +FACILITY_XBOX: Final = 2339 +FACILITY_GAME: Final = 2340 +FACILITY_PIX: Final = 2748 +ERROR_SUCCESS: Final = 0 +NO_ERROR: Final = 0 +SEC_E_OK: Final = 0x00000000 +ERROR_INVALID_FUNCTION: Final = 1 +ERROR_FILE_NOT_FOUND: Final = 2 +ERROR_PATH_NOT_FOUND: Final = 3 +ERROR_TOO_MANY_OPEN_FILES: Final = 4 +ERROR_ACCESS_DENIED: Final = 5 +ERROR_INVALID_HANDLE: Final = 6 +ERROR_ARENA_TRASHED: Final = 7 +ERROR_NOT_ENOUGH_MEMORY: Final = 8 +ERROR_INVALID_BLOCK: Final = 9 +ERROR_BAD_ENVIRONMENT: Final = 10 +ERROR_BAD_FORMAT: Final = 11 +ERROR_INVALID_ACCESS: Final = 12 +ERROR_INVALID_DATA: Final = 13 +ERROR_OUTOFMEMORY: Final = 14 +ERROR_INVALID_DRIVE: Final = 15 +ERROR_CURRENT_DIRECTORY: Final = 16 +ERROR_NOT_SAME_DEVICE: Final = 17 +ERROR_NO_MORE_FILES: Final = 18 +ERROR_WRITE_PROTECT: Final = 19 +ERROR_BAD_UNIT: Final = 20 +ERROR_NOT_READY: Final = 21 +ERROR_BAD_COMMAND: Final = 22 +ERROR_CRC: Final = 23 +ERROR_BAD_LENGTH: Final = 24 +ERROR_SEEK: Final = 25 +ERROR_NOT_DOS_DISK: Final = 26 +ERROR_SECTOR_NOT_FOUND: Final = 27 +ERROR_OUT_OF_PAPER: Final = 28 +ERROR_WRITE_FAULT: Final = 29 +ERROR_READ_FAULT: Final = 30 +ERROR_GEN_FAILURE: Final = 31 +ERROR_SHARING_VIOLATION: Final = 32 +ERROR_LOCK_VIOLATION: Final = 33 +ERROR_WRONG_DISK: Final = 34 +ERROR_SHARING_BUFFER_EXCEEDED: Final = 36 +ERROR_HANDLE_EOF: Final = 38 +ERROR_HANDLE_DISK_FULL: Final = 39 +ERROR_NOT_SUPPORTED: Final = 50 +ERROR_REM_NOT_LIST: Final = 51 +ERROR_DUP_NAME: Final = 52 +ERROR_BAD_NETPATH: Final = 53 +ERROR_NETWORK_BUSY: Final = 54 +ERROR_DEV_NOT_EXIST: Final = 55 +ERROR_TOO_MANY_CMDS: Final = 56 +ERROR_ADAP_HDW_ERR: Final = 57 +ERROR_BAD_NET_RESP: Final = 58 +ERROR_UNEXP_NET_ERR: Final = 59 +ERROR_BAD_REM_ADAP: Final = 60 +ERROR_PRINTQ_FULL: Final = 61 +ERROR_NO_SPOOL_SPACE: Final = 62 +ERROR_PRINT_CANCELLED: Final = 63 +ERROR_NETNAME_DELETED: Final = 64 +ERROR_NETWORK_ACCESS_DENIED: Final = 65 +ERROR_BAD_DEV_TYPE: Final = 66 +ERROR_BAD_NET_NAME: Final = 67 +ERROR_TOO_MANY_NAMES: Final = 68 +ERROR_TOO_MANY_SESS: Final = 69 +ERROR_SHARING_PAUSED: Final = 70 +ERROR_REQ_NOT_ACCEP: Final = 71 +ERROR_REDIR_PAUSED: Final = 72 +ERROR_FILE_EXISTS: Final = 80 +ERROR_CANNOT_MAKE: Final = 82 +ERROR_FAIL_I24: Final = 83 +ERROR_OUT_OF_STRUCTURES: Final = 84 +ERROR_ALREADY_ASSIGNED: Final = 85 +ERROR_INVALID_PASSWORD: Final = 86 +ERROR_INVALID_PARAMETER: Final = 87 +ERROR_NET_WRITE_FAULT: Final = 88 +ERROR_NO_PROC_SLOTS: Final = 89 +ERROR_TOO_MANY_SEMAPHORES: Final = 100 +ERROR_EXCL_SEM_ALREADY_OWNED: Final = 101 +ERROR_SEM_IS_SET: Final = 102 +ERROR_TOO_MANY_SEM_REQUESTS: Final = 103 +ERROR_INVALID_AT_INTERRUPT_TIME: Final = 104 +ERROR_SEM_OWNER_DIED: Final = 105 +ERROR_SEM_USER_LIMIT: Final = 106 +ERROR_DISK_CHANGE: Final = 107 +ERROR_DRIVE_LOCKED: Final = 108 +ERROR_BROKEN_PIPE: Final = 109 +ERROR_OPEN_FAILED: Final = 110 +ERROR_BUFFER_OVERFLOW: Final = 111 +ERROR_DISK_FULL: Final = 112 +ERROR_NO_MORE_SEARCH_HANDLES: Final = 113 +ERROR_INVALID_TARGET_HANDLE: Final = 114 +ERROR_INVALID_CATEGORY: Final = 117 +ERROR_INVALID_VERIFY_SWITCH: Final = 118 +ERROR_BAD_DRIVER_LEVEL: Final = 119 +ERROR_CALL_NOT_IMPLEMENTED: Final = 120 +ERROR_SEM_TIMEOUT: Final = 121 +ERROR_INSUFFICIENT_BUFFER: Final = 122 +ERROR_INVALID_NAME: Final = 123 +ERROR_INVALID_LEVEL: Final = 124 +ERROR_NO_VOLUME_LABEL: Final = 125 +ERROR_MOD_NOT_FOUND: Final = 126 +ERROR_PROC_NOT_FOUND: Final = 127 +ERROR_WAIT_NO_CHILDREN: Final = 128 +ERROR_CHILD_NOT_COMPLETE: Final = 129 +ERROR_DIRECT_ACCESS_HANDLE: Final = 130 +ERROR_NEGATIVE_SEEK: Final = 131 +ERROR_SEEK_ON_DEVICE: Final = 132 +ERROR_IS_JOIN_TARGET: Final = 133 +ERROR_IS_JOINED: Final = 134 +ERROR_IS_SUBSTED: Final = 135 +ERROR_NOT_JOINED: Final = 136 +ERROR_NOT_SUBSTED: Final = 137 +ERROR_JOIN_TO_JOIN: Final = 138 +ERROR_SUBST_TO_SUBST: Final = 139 +ERROR_JOIN_TO_SUBST: Final = 140 +ERROR_SUBST_TO_JOIN: Final = 141 +ERROR_BUSY_DRIVE: Final = 142 +ERROR_SAME_DRIVE: Final = 143 +ERROR_DIR_NOT_ROOT: Final = 144 +ERROR_DIR_NOT_EMPTY: Final = 145 +ERROR_IS_SUBST_PATH: Final = 146 +ERROR_IS_JOIN_PATH: Final = 147 +ERROR_PATH_BUSY: Final = 148 +ERROR_IS_SUBST_TARGET: Final = 149 +ERROR_SYSTEM_TRACE: Final = 150 +ERROR_INVALID_EVENT_COUNT: Final = 151 +ERROR_TOO_MANY_MUXWAITERS: Final = 152 +ERROR_INVALID_LIST_FORMAT: Final = 153 +ERROR_LABEL_TOO_LONG: Final = 154 +ERROR_TOO_MANY_TCBS: Final = 155 +ERROR_SIGNAL_REFUSED: Final = 156 +ERROR_DISCARDED: Final = 157 +ERROR_NOT_LOCKED: Final = 158 +ERROR_BAD_THREADID_ADDR: Final = 159 +ERROR_BAD_ARGUMENTS: Final = 160 +ERROR_BAD_PATHNAME: Final = 161 +ERROR_SIGNAL_PENDING: Final = 162 +ERROR_MAX_THRDS_REACHED: Final = 164 +ERROR_LOCK_FAILED: Final = 167 +ERROR_BUSY: Final = 170 +ERROR_DEVICE_SUPPORT_IN_PROGRESS: Final = 171 +ERROR_CANCEL_VIOLATION: Final = 173 +ERROR_ATOMIC_LOCKS_NOT_SUPPORTED: Final = 174 +ERROR_INVALID_SEGMENT_NUMBER: Final = 180 +ERROR_INVALID_ORDINAL: Final = 182 +ERROR_ALREADY_EXISTS: Final = 183 +ERROR_INVALID_FLAG_NUMBER: Final = 186 +ERROR_SEM_NOT_FOUND: Final = 187 +ERROR_INVALID_STARTING_CODESEG: Final = 188 +ERROR_INVALID_STACKSEG: Final = 189 +ERROR_INVALID_MODULETYPE: Final = 190 +ERROR_INVALID_EXE_SIGNATURE: Final = 191 +ERROR_EXE_MARKED_INVALID: Final = 192 +ERROR_BAD_EXE_FORMAT: Final = 193 +ERROR_ITERATED_DATA_EXCEEDS_64k: Final = 194 +ERROR_INVALID_MINALLOCSIZE: Final = 195 +ERROR_DYNLINK_FROM_INVALID_RING: Final = 196 +ERROR_IOPL_NOT_ENABLED: Final = 197 +ERROR_INVALID_SEGDPL: Final = 198 +ERROR_AUTODATASEG_EXCEEDS_64k: Final = 199 +ERROR_RING2SEG_MUST_BE_MOVABLE: Final = 200 +ERROR_RELOC_CHAIN_XEEDS_SEGLIM: Final = 201 +ERROR_INFLOOP_IN_RELOC_CHAIN: Final = 202 +ERROR_ENVVAR_NOT_FOUND: Final = 203 +ERROR_NO_SIGNAL_SENT: Final = 205 +ERROR_FILENAME_EXCED_RANGE: Final = 206 +ERROR_RING2_STACK_IN_USE: Final = 207 +ERROR_META_EXPANSION_TOO_LONG: Final = 208 +ERROR_INVALID_SIGNAL_NUMBER: Final = 209 +ERROR_THREAD_1_INACTIVE: Final = 210 +ERROR_LOCKED: Final = 212 +ERROR_TOO_MANY_MODULES: Final = 214 +ERROR_NESTING_NOT_ALLOWED: Final = 215 +ERROR_EXE_MACHINE_TYPE_MISMATCH: Final = 216 +ERROR_EXE_CANNOT_MODIFY_SIGNED_BINARY: Final = 217 +ERROR_EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY: Final = 218 +ERROR_FILE_CHECKED_OUT: Final = 220 +ERROR_CHECKOUT_REQUIRED: Final = 221 +ERROR_BAD_FILE_TYPE: Final = 222 +ERROR_FILE_TOO_LARGE: Final = 223 +ERROR_FORMS_AUTH_REQUIRED: Final = 224 +ERROR_VIRUS_INFECTED: Final = 225 +ERROR_VIRUS_DELETED: Final = 226 +ERROR_PIPE_LOCAL: Final = 229 +ERROR_BAD_PIPE: Final = 230 +ERROR_PIPE_BUSY: Final = 231 +ERROR_NO_DATA: Final = 232 +ERROR_PIPE_NOT_CONNECTED: Final = 233 +ERROR_MORE_DATA: Final = 234 +ERROR_NO_WORK_DONE: Final = 235 +ERROR_VC_DISCONNECTED: Final = 240 +ERROR_INVALID_EA_NAME: Final = 254 +ERROR_EA_LIST_INCONSISTENT: Final = 255 +WAIT_TIMEOUT: Final = 258 +ERROR_NO_MORE_ITEMS: Final = 259 +ERROR_CANNOT_COPY: Final = 266 +ERROR_DIRECTORY: Final = 267 +ERROR_EAS_DIDNT_FIT: Final = 275 +ERROR_EA_FILE_CORRUPT: Final = 276 +ERROR_EA_TABLE_FULL: Final = 277 +ERROR_INVALID_EA_HANDLE: Final = 278 +ERROR_EAS_NOT_SUPPORTED: Final = 282 +ERROR_NOT_OWNER: Final = 288 +ERROR_TOO_MANY_POSTS: Final = 298 +ERROR_PARTIAL_COPY: Final = 299 +ERROR_OPLOCK_NOT_GRANTED: Final = 300 +ERROR_INVALID_OPLOCK_PROTOCOL: Final = 301 +ERROR_DISK_TOO_FRAGMENTED: Final = 302 +ERROR_DELETE_PENDING: Final = 303 +ERROR_INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING: Final = 304 +ERROR_SHORT_NAMES_NOT_ENABLED_ON_VOLUME: Final = 305 +ERROR_SECURITY_STREAM_IS_INCONSISTENT: Final = 306 +ERROR_INVALID_LOCK_RANGE: Final = 307 +ERROR_IMAGE_SUBSYSTEM_NOT_PRESENT: Final = 308 +ERROR_NOTIFICATION_GUID_ALREADY_DEFINED: Final = 309 +ERROR_INVALID_EXCEPTION_HANDLER: Final = 310 +ERROR_DUPLICATE_PRIVILEGES: Final = 311 +ERROR_NO_RANGES_PROCESSED: Final = 312 +ERROR_NOT_ALLOWED_ON_SYSTEM_FILE: Final = 313 +ERROR_DISK_RESOURCES_EXHAUSTED: Final = 314 +ERROR_INVALID_TOKEN: Final = 315 +ERROR_DEVICE_FEATURE_NOT_SUPPORTED: Final = 316 +ERROR_MR_MID_NOT_FOUND: Final = 317 +ERROR_SCOPE_NOT_FOUND: Final = 318 +ERROR_UNDEFINED_SCOPE: Final = 319 +ERROR_INVALID_CAP: Final = 320 +ERROR_DEVICE_UNREACHABLE: Final = 321 +ERROR_DEVICE_NO_RESOURCES: Final = 322 +ERROR_DATA_CHECKSUM_ERROR: Final = 323 +ERROR_INTERMIXED_KERNEL_EA_OPERATION: Final = 324 +ERROR_FILE_LEVEL_TRIM_NOT_SUPPORTED: Final = 326 +ERROR_OFFSET_ALIGNMENT_VIOLATION: Final = 327 +ERROR_INVALID_FIELD_IN_PARAMETER_LIST: Final = 328 +ERROR_OPERATION_IN_PROGRESS: Final = 329 +ERROR_BAD_DEVICE_PATH: Final = 330 +ERROR_TOO_MANY_DESCRIPTORS: Final = 331 +ERROR_SCRUB_DATA_DISABLED: Final = 332 +ERROR_NOT_REDUNDANT_STORAGE: Final = 333 +ERROR_RESIDENT_FILE_NOT_SUPPORTED: Final = 334 +ERROR_COMPRESSED_FILE_NOT_SUPPORTED: Final = 335 +ERROR_DIRECTORY_NOT_SUPPORTED: Final = 336 +ERROR_NOT_READ_FROM_COPY: Final = 337 +ERROR_FT_WRITE_FAILURE: Final = 338 +ERROR_FT_DI_SCAN_REQUIRED: Final = 339 +ERROR_INVALID_KERNEL_INFO_VERSION: Final = 340 +ERROR_INVALID_PEP_INFO_VERSION: Final = 341 +ERROR_OBJECT_NOT_EXTERNALLY_BACKED: Final = 342 +ERROR_EXTERNAL_BACKING_PROVIDER_UNKNOWN: Final = 343 +ERROR_COMPRESSION_NOT_BENEFICIAL: Final = 344 +ERROR_STORAGE_TOPOLOGY_ID_MISMATCH: Final = 345 +ERROR_BLOCKED_BY_PARENTAL_CONTROLS: Final = 346 +ERROR_BLOCK_TOO_MANY_REFERENCES: Final = 347 +ERROR_MARKED_TO_DISALLOW_WRITES: Final = 348 +ERROR_ENCLAVE_FAILURE: Final = 349 +ERROR_FAIL_NOACTION_REBOOT: Final = 350 +ERROR_FAIL_SHUTDOWN: Final = 351 +ERROR_FAIL_RESTART: Final = 352 +ERROR_MAX_SESSIONS_REACHED: Final = 353 +ERROR_NETWORK_ACCESS_DENIED_EDP: Final = 354 +ERROR_DEVICE_HINT_NAME_BUFFER_TOO_SMALL: Final = 355 +ERROR_EDP_POLICY_DENIES_OPERATION: Final = 356 +ERROR_EDP_DPL_POLICY_CANT_BE_SATISFIED: Final = 357 +ERROR_CLOUD_FILE_SYNC_ROOT_METADATA_CORRUPT: Final = 358 +ERROR_DEVICE_IN_MAINTENANCE: Final = 359 +ERROR_NOT_SUPPORTED_ON_DAX: Final = 360 +ERROR_DAX_MAPPING_EXISTS: Final = 361 +ERROR_CLOUD_FILE_PROVIDER_NOT_RUNNING: Final = 362 +ERROR_CLOUD_FILE_METADATA_CORRUPT: Final = 363 +ERROR_CLOUD_FILE_METADATA_TOO_LARGE: Final = 364 +ERROR_CLOUD_FILE_PROPERTY_BLOB_TOO_LARGE: Final = 365 +ERROR_CLOUD_FILE_PROPERTY_BLOB_CHECKSUM_MISMATCH: Final = 366 +ERROR_CHILD_PROCESS_BLOCKED: Final = 367 +ERROR_STORAGE_LOST_DATA_PERSISTENCE: Final = 368 +ERROR_FILE_SYSTEM_VIRTUALIZATION_UNAVAILABLE: Final = 369 +ERROR_FILE_SYSTEM_VIRTUALIZATION_METADATA_CORRUPT: Final = 370 +ERROR_FILE_SYSTEM_VIRTUALIZATION_BUSY: Final = 371 +ERROR_FILE_SYSTEM_VIRTUALIZATION_PROVIDER_UNKNOWN: Final = 372 +ERROR_GDI_HANDLE_LEAK: Final = 373 +ERROR_CLOUD_FILE_TOO_MANY_PROPERTY_BLOBS: Final = 374 +ERROR_CLOUD_FILE_PROPERTY_VERSION_NOT_SUPPORTED: Final = 375 +ERROR_NOT_A_CLOUD_FILE: Final = 376 +ERROR_CLOUD_FILE_NOT_IN_SYNC: Final = 377 +ERROR_CLOUD_FILE_ALREADY_CONNECTED: Final = 378 +ERROR_CLOUD_FILE_NOT_SUPPORTED: Final = 379 +ERROR_CLOUD_FILE_INVALID_REQUEST: Final = 380 +ERROR_CLOUD_FILE_READ_ONLY_VOLUME: Final = 381 +ERROR_CLOUD_FILE_CONNECTED_PROVIDER_ONLY: Final = 382 +ERROR_CLOUD_FILE_VALIDATION_FAILED: Final = 383 +ERROR_SMB1_NOT_AVAILABLE: Final = 384 +ERROR_FILE_SYSTEM_VIRTUALIZATION_INVALID_OPERATION: Final = 385 +ERROR_CLOUD_FILE_AUTHENTICATION_FAILED: Final = 386 +ERROR_CLOUD_FILE_INSUFFICIENT_RESOURCES: Final = 387 +ERROR_CLOUD_FILE_NETWORK_UNAVAILABLE: Final = 388 +ERROR_CLOUD_FILE_UNSUCCESSFUL: Final = 389 +ERROR_CLOUD_FILE_NOT_UNDER_SYNC_ROOT: Final = 390 +ERROR_CLOUD_FILE_IN_USE: Final = 391 +ERROR_CLOUD_FILE_PINNED: Final = 392 +ERROR_CLOUD_FILE_REQUEST_ABORTED: Final = 393 +ERROR_CLOUD_FILE_PROPERTY_CORRUPT: Final = 394 +ERROR_CLOUD_FILE_ACCESS_DENIED: Final = 395 +ERROR_CLOUD_FILE_INCOMPATIBLE_HARDLINKS: Final = 396 +ERROR_CLOUD_FILE_PROPERTY_LOCK_CONFLICT: Final = 397 +ERROR_CLOUD_FILE_REQUEST_CANCELED: Final = 398 +ERROR_EXTERNAL_SYSKEY_NOT_SUPPORTED: Final = 399 +ERROR_THREAD_MODE_ALREADY_BACKGROUND: Final = 400 +ERROR_THREAD_MODE_NOT_BACKGROUND: Final = 401 +ERROR_PROCESS_MODE_ALREADY_BACKGROUND: Final = 402 +ERROR_PROCESS_MODE_NOT_BACKGROUND: Final = 403 +ERROR_CLOUD_FILE_PROVIDER_TERMINATED: Final = 404 +ERROR_NOT_A_CLOUD_SYNC_ROOT: Final = 405 +ERROR_FILE_PROTECTED_UNDER_DPL: Final = 406 +ERROR_VOLUME_NOT_CLUSTER_ALIGNED: Final = 407 +ERROR_NO_PHYSICALLY_ALIGNED_FREE_SPACE_FOUND: Final = 408 +ERROR_APPX_FILE_NOT_ENCRYPTED: Final = 409 +ERROR_RWRAW_ENCRYPTED_FILE_NOT_ENCRYPTED: Final = 410 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_FILEOFFSET: Final = 411 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_FILERANGE: Final = 412 +ERROR_RWRAW_ENCRYPTED_INVALID_EDATAINFO_PARAMETER: Final = 413 +ERROR_LINUX_SUBSYSTEM_NOT_PRESENT: Final = 414 +ERROR_FT_READ_FAILURE: Final = 415 +ERROR_STORAGE_RESERVE_ID_INVALID: Final = 416 +ERROR_STORAGE_RESERVE_DOES_NOT_EXIST: Final = 417 +ERROR_STORAGE_RESERVE_ALREADY_EXISTS: Final = 418 +ERROR_STORAGE_RESERVE_NOT_EMPTY: Final = 419 +ERROR_NOT_A_DAX_VOLUME: Final = 420 +ERROR_NOT_DAX_MAPPABLE: Final = 421 +ERROR_TIME_SENSITIVE_THREAD: Final = 422 +ERROR_DPL_NOT_SUPPORTED_FOR_USER: Final = 423 +ERROR_CASE_DIFFERING_NAMES_IN_DIR: Final = 424 +ERROR_FILE_NOT_SUPPORTED: Final = 425 +ERROR_CLOUD_FILE_REQUEST_TIMEOUT: Final = 426 +ERROR_NO_TASK_QUEUE: Final = 427 +ERROR_SRC_SRV_DLL_LOAD_FAILED: Final = 428 +ERROR_NOT_SUPPORTED_WITH_BTT: Final = 429 +ERROR_ENCRYPTION_DISABLED: Final = 430 +ERROR_ENCRYPTING_METADATA_DISALLOWED: Final = 431 +ERROR_CANT_CLEAR_ENCRYPTION_FLAG: Final = 432 +ERROR_NO_SUCH_DEVICE: Final = 433 +ERROR_CLOUD_FILE_DEHYDRATION_DISALLOWED: Final = 434 +ERROR_FILE_SNAP_IN_PROGRESS: Final = 435 +ERROR_FILE_SNAP_USER_SECTION_NOT_SUPPORTED: Final = 436 +ERROR_FILE_SNAP_MODIFY_NOT_SUPPORTED: Final = 437 +ERROR_FILE_SNAP_IO_NOT_COORDINATED: Final = 438 +ERROR_FILE_SNAP_UNEXPECTED_ERROR: Final = 439 +ERROR_FILE_SNAP_INVALID_PARAMETER: Final = 440 +ERROR_UNSATISFIED_DEPENDENCIES: Final = 441 +ERROR_CASE_SENSITIVE_PATH: Final = 442 +ERROR_UNEXPECTED_NTCACHEMANAGER_ERROR: Final = 443 +ERROR_LINUX_SUBSYSTEM_UPDATE_REQUIRED: Final = 444 +ERROR_DLP_POLICY_WARNS_AGAINST_OPERATION: Final = 445 +ERROR_DLP_POLICY_DENIES_OPERATION: Final = 446 +ERROR_SECURITY_DENIES_OPERATION: Final = 447 +ERROR_UNTRUSTED_MOUNT_POINT: Final = 448 +ERROR_DLP_POLICY_SILENTLY_FAIL: Final = 449 +ERROR_CAPAUTHZ_NOT_DEVUNLOCKED: Final = 450 +ERROR_CAPAUTHZ_CHANGE_TYPE: Final = 451 +ERROR_CAPAUTHZ_NOT_PROVISIONED: Final = 452 +ERROR_CAPAUTHZ_NOT_AUTHORIZED: Final = 453 +ERROR_CAPAUTHZ_NO_POLICY: Final = 454 +ERROR_CAPAUTHZ_DB_CORRUPTED: Final = 455 +ERROR_CAPAUTHZ_SCCD_INVALID_CATALOG: Final = 456 +ERROR_CAPAUTHZ_SCCD_NO_AUTH_ENTITY: Final = 457 +ERROR_CAPAUTHZ_SCCD_PARSE_ERROR: Final = 458 +ERROR_CAPAUTHZ_SCCD_DEV_MODE_REQUIRED: Final = 459 +ERROR_CAPAUTHZ_SCCD_NO_CAPABILITY_MATCH: Final = 460 +ERROR_CIMFS_IMAGE_CORRUPT: Final = 470 +ERROR_CIMFS_IMAGE_VERSION_NOT_SUPPORTED: Final = 471 +ERROR_STORAGE_STACK_ACCESS_DENIED: Final = 472 +ERROR_INSUFFICIENT_VIRTUAL_ADDR_RESOURCES: Final = 473 +ERROR_INDEX_OUT_OF_BOUNDS: Final = 474 +ERROR_CLOUD_FILE_US_MESSAGE_TIMEOUT: Final = 475 +ERROR_NOT_A_DEV_VOLUME: Final = 476 +ERROR_FS_GUID_MISMATCH: Final = 477 +ERROR_CANT_ATTACH_TO_DEV_VOLUME: Final = 478 +ERROR_INVALID_CONFIG_VALUE: Final = 479 +ERROR_PNP_QUERY_REMOVE_DEVICE_TIMEOUT: Final = 480 +ERROR_PNP_QUERY_REMOVE_RELATED_DEVICE_TIMEOUT: Final = 481 +ERROR_PNP_QUERY_REMOVE_UNRELATED_DEVICE_TIMEOUT: Final = 482 +ERROR_DEVICE_HARDWARE_ERROR: Final = 483 +ERROR_INVALID_ADDRESS: Final = 487 +ERROR_HAS_SYSTEM_CRITICAL_FILES: Final = 488 +ERROR_ENCRYPTED_FILE_NOT_SUPPORTED: Final = 489 +ERROR_SPARSE_FILE_NOT_SUPPORTED: Final = 490 +ERROR_PAGEFILE_NOT_SUPPORTED: Final = 491 +ERROR_VOLUME_NOT_SUPPORTED: Final = 492 +ERROR_NOT_SUPPORTED_WITH_BYPASSIO: Final = 493 +ERROR_NO_BYPASSIO_DRIVER_SUPPORT: Final = 494 +ERROR_NOT_SUPPORTED_WITH_ENCRYPTION: Final = 495 +ERROR_NOT_SUPPORTED_WITH_COMPRESSION: Final = 496 +ERROR_NOT_SUPPORTED_WITH_REPLICATION: Final = 497 +ERROR_NOT_SUPPORTED_WITH_DEDUPLICATION: Final = 498 +ERROR_NOT_SUPPORTED_WITH_AUDITING: Final = 499 +ERROR_USER_PROFILE_LOAD: Final = 500 +ERROR_SESSION_KEY_TOO_SHORT: Final = 501 +ERROR_ACCESS_DENIED_APPDATA: Final = 502 +ERROR_NOT_SUPPORTED_WITH_MONITORING: Final = 503 +ERROR_NOT_SUPPORTED_WITH_SNAPSHOT: Final = 504 +ERROR_NOT_SUPPORTED_WITH_VIRTUALIZATION: Final = 505 +ERROR_BYPASSIO_FLT_NOT_SUPPORTED: Final = 506 +ERROR_DEVICE_RESET_REQUIRED: Final = 507 +ERROR_VOLUME_WRITE_ACCESS_DENIED: Final = 508 +ERROR_NOT_SUPPORTED_WITH_CACHED_HANDLE: Final = 509 +ERROR_FS_METADATA_INCONSISTENT: Final = 510 +ERROR_BLOCK_WEAK_REFERENCE_INVALID: Final = 511 +ERROR_BLOCK_SOURCE_WEAK_REFERENCE_INVALID: Final = 512 +ERROR_BLOCK_TARGET_WEAK_REFERENCE_INVALID: Final = 513 +ERROR_BLOCK_SHARED: Final = 514 +ERROR_VOLUME_UPGRADE_NOT_NEEDED: Final = 515 +ERROR_VOLUME_UPGRADE_PENDING: Final = 516 +ERROR_VOLUME_UPGRADE_DISABLED: Final = 517 +ERROR_VOLUME_UPGRADE_DISABLED_TILL_OS_DOWNGRADE_EXPIRED: Final = 518 +ERROR_ARITHMETIC_OVERFLOW: Final = 534 +ERROR_PIPE_CONNECTED: Final = 535 +ERROR_PIPE_LISTENING: Final = 536 +ERROR_VERIFIER_STOP: Final = 537 +ERROR_ABIOS_ERROR: Final = 538 +ERROR_WX86_WARNING: Final = 539 +ERROR_WX86_ERROR: Final = 540 +ERROR_TIMER_NOT_CANCELED: Final = 541 +ERROR_UNWIND: Final = 542 +ERROR_BAD_STACK: Final = 543 +ERROR_INVALID_UNWIND_TARGET: Final = 544 +ERROR_INVALID_PORT_ATTRIBUTES: Final = 545 +ERROR_PORT_MESSAGE_TOO_LONG: Final = 546 +ERROR_INVALID_QUOTA_LOWER: Final = 547 +ERROR_DEVICE_ALREADY_ATTACHED: Final = 548 +ERROR_INSTRUCTION_MISALIGNMENT: Final = 549 +ERROR_PROFILING_NOT_STARTED: Final = 550 +ERROR_PROFILING_NOT_STOPPED: Final = 551 +ERROR_COULD_NOT_INTERPRET: Final = 552 +ERROR_PROFILING_AT_LIMIT: Final = 553 +ERROR_CANT_WAIT: Final = 554 +ERROR_CANT_TERMINATE_SELF: Final = 555 +ERROR_UNEXPECTED_MM_CREATE_ERR: Final = 556 +ERROR_UNEXPECTED_MM_MAP_ERROR: Final = 557 +ERROR_UNEXPECTED_MM_EXTEND_ERR: Final = 558 +ERROR_BAD_FUNCTION_TABLE: Final = 559 +ERROR_NO_GUID_TRANSLATION: Final = 560 +ERROR_INVALID_LDT_SIZE: Final = 561 +ERROR_INVALID_LDT_OFFSET: Final = 563 +ERROR_INVALID_LDT_DESCRIPTOR: Final = 564 +ERROR_TOO_MANY_THREADS: Final = 565 +ERROR_THREAD_NOT_IN_PROCESS: Final = 566 +ERROR_PAGEFILE_QUOTA_EXCEEDED: Final = 567 +ERROR_LOGON_SERVER_CONFLICT: Final = 568 +ERROR_SYNCHRONIZATION_REQUIRED: Final = 569 +ERROR_NET_OPEN_FAILED: Final = 570 +ERROR_IO_PRIVILEGE_FAILED: Final = 571 +ERROR_CONTROL_C_EXIT: Final = 572 +ERROR_MISSING_SYSTEMFILE: Final = 573 +ERROR_UNHANDLED_EXCEPTION: Final = 574 +ERROR_APP_INIT_FAILURE: Final = 575 +ERROR_PAGEFILE_CREATE_FAILED: Final = 576 +ERROR_INVALID_IMAGE_HASH: Final = 577 +ERROR_NO_PAGEFILE: Final = 578 +ERROR_ILLEGAL_FLOAT_CONTEXT: Final = 579 +ERROR_NO_EVENT_PAIR: Final = 580 +ERROR_DOMAIN_CTRLR_CONFIG_ERROR: Final = 581 +ERROR_ILLEGAL_CHARACTER: Final = 582 +ERROR_UNDEFINED_CHARACTER: Final = 583 +ERROR_FLOPPY_VOLUME: Final = 584 +ERROR_BIOS_FAILED_TO_CONNECT_INTERRUPT: Final = 585 +ERROR_BACKUP_CONTROLLER: Final = 586 +ERROR_MUTANT_LIMIT_EXCEEDED: Final = 587 +ERROR_FS_DRIVER_REQUIRED: Final = 588 +ERROR_CANNOT_LOAD_REGISTRY_FILE: Final = 589 +ERROR_DEBUG_ATTACH_FAILED: Final = 590 +ERROR_SYSTEM_PROCESS_TERMINATED: Final = 591 +ERROR_DATA_NOT_ACCEPTED: Final = 592 +ERROR_VDM_HARD_ERROR: Final = 593 +ERROR_DRIVER_CANCEL_TIMEOUT: Final = 594 +ERROR_REPLY_MESSAGE_MISMATCH: Final = 595 +ERROR_LOST_WRITEBEHIND_DATA: Final = 596 +ERROR_CLIENT_SERVER_PARAMETERS_INVALID: Final = 597 +ERROR_NOT_TINY_STREAM: Final = 598 +ERROR_STACK_OVERFLOW_READ: Final = 599 +ERROR_CONVERT_TO_LARGE: Final = 600 +ERROR_FOUND_OUT_OF_SCOPE: Final = 601 +ERROR_ALLOCATE_BUCKET: Final = 602 +ERROR_MARSHALL_OVERFLOW: Final = 603 +ERROR_INVALID_VARIANT: Final = 604 +ERROR_BAD_COMPRESSION_BUFFER: Final = 605 +ERROR_AUDIT_FAILED: Final = 606 +ERROR_TIMER_RESOLUTION_NOT_SET: Final = 607 +ERROR_INSUFFICIENT_LOGON_INFO: Final = 608 +ERROR_BAD_DLL_ENTRYPOINT: Final = 609 +ERROR_BAD_SERVICE_ENTRYPOINT: Final = 610 +ERROR_IP_ADDRESS_CONFLICT1: Final = 611 +ERROR_IP_ADDRESS_CONFLICT2: Final = 612 +ERROR_REGISTRY_QUOTA_LIMIT: Final = 613 +ERROR_NO_CALLBACK_ACTIVE: Final = 614 +ERROR_PWD_TOO_SHORT: Final = 615 +ERROR_PWD_TOO_RECENT: Final = 616 +ERROR_PWD_HISTORY_CONFLICT: Final = 617 +ERROR_UNSUPPORTED_COMPRESSION: Final = 618 +ERROR_INVALID_HW_PROFILE: Final = 619 +ERROR_INVALID_PLUGPLAY_DEVICE_PATH: Final = 620 +ERROR_QUOTA_LIST_INCONSISTENT: Final = 621 +ERROR_EVALUATION_EXPIRATION: Final = 622 +ERROR_ILLEGAL_DLL_RELOCATION: Final = 623 +ERROR_DLL_INIT_FAILED_LOGOFF: Final = 624 +ERROR_VALIDATE_CONTINUE: Final = 625 +ERROR_NO_MORE_MATCHES: Final = 626 +ERROR_RANGE_LIST_CONFLICT: Final = 627 +ERROR_SERVER_SID_MISMATCH: Final = 628 +ERROR_CANT_ENABLE_DENY_ONLY: Final = 629 +ERROR_FLOAT_MULTIPLE_FAULTS: Final = 630 +ERROR_FLOAT_MULTIPLE_TRAPS: Final = 631 +ERROR_NOINTERFACE: Final = 632 +ERROR_DRIVER_FAILED_SLEEP: Final = 633 +ERROR_CORRUPT_SYSTEM_FILE: Final = 634 +ERROR_COMMITMENT_MINIMUM: Final = 635 +ERROR_PNP_RESTART_ENUMERATION: Final = 636 +ERROR_SYSTEM_IMAGE_BAD_SIGNATURE: Final = 637 +ERROR_PNP_REBOOT_REQUIRED: Final = 638 +ERROR_INSUFFICIENT_POWER: Final = 639 +ERROR_MULTIPLE_FAULT_VIOLATION: Final = 640 +ERROR_SYSTEM_SHUTDOWN: Final = 641 +ERROR_PORT_NOT_SET: Final = 642 +ERROR_DS_VERSION_CHECK_FAILURE: Final = 643 +ERROR_RANGE_NOT_FOUND: Final = 644 +ERROR_NOT_SAFE_MODE_DRIVER: Final = 646 +ERROR_FAILED_DRIVER_ENTRY: Final = 647 +ERROR_DEVICE_ENUMERATION_ERROR: Final = 648 +ERROR_MOUNT_POINT_NOT_RESOLVED: Final = 649 +ERROR_INVALID_DEVICE_OBJECT_PARAMETER: Final = 650 +ERROR_MCA_OCCURED: Final = 651 +ERROR_DRIVER_DATABASE_ERROR: Final = 652 +ERROR_SYSTEM_HIVE_TOO_LARGE: Final = 653 +ERROR_DRIVER_FAILED_PRIOR_UNLOAD: Final = 654 +ERROR_VOLSNAP_PREPARE_HIBERNATE: Final = 655 +ERROR_HIBERNATION_FAILURE: Final = 656 +ERROR_PWD_TOO_LONG: Final = 657 +ERROR_FILE_SYSTEM_LIMITATION: Final = 665 +ERROR_ASSERTION_FAILURE: Final = 668 +ERROR_ACPI_ERROR: Final = 669 +ERROR_WOW_ASSERTION: Final = 670 +ERROR_PNP_BAD_MPS_TABLE: Final = 671 +ERROR_PNP_TRANSLATION_FAILED: Final = 672 +ERROR_PNP_IRQ_TRANSLATION_FAILED: Final = 673 +ERROR_PNP_INVALID_ID: Final = 674 +ERROR_WAKE_SYSTEM_DEBUGGER: Final = 675 +ERROR_HANDLES_CLOSED: Final = 676 +ERROR_EXTRANEOUS_INFORMATION: Final = 677 +ERROR_RXACT_COMMIT_NECESSARY: Final = 678 +ERROR_MEDIA_CHECK: Final = 679 +ERROR_GUID_SUBSTITUTION_MADE: Final = 680 +ERROR_STOPPED_ON_SYMLINK: Final = 681 +ERROR_LONGJUMP: Final = 682 +ERROR_PLUGPLAY_QUERY_VETOED: Final = 683 +ERROR_UNWIND_CONSOLIDATE: Final = 684 +ERROR_REGISTRY_HIVE_RECOVERED: Final = 685 +ERROR_DLL_MIGHT_BE_INSECURE: Final = 686 +ERROR_DLL_MIGHT_BE_INCOMPATIBLE: Final = 687 +ERROR_DBG_EXCEPTION_NOT_HANDLED: Final = 688 +ERROR_DBG_REPLY_LATER: Final = 689 +ERROR_DBG_UNABLE_TO_PROVIDE_HANDLE: Final = 690 +ERROR_DBG_TERMINATE_THREAD: Final = 691 +ERROR_DBG_TERMINATE_PROCESS: Final = 692 +ERROR_DBG_CONTROL_C: Final = 693 +ERROR_DBG_PRINTEXCEPTION_C: Final = 694 +ERROR_DBG_RIPEXCEPTION: Final = 695 +ERROR_DBG_CONTROL_BREAK: Final = 696 +ERROR_DBG_COMMAND_EXCEPTION: Final = 697 +ERROR_OBJECT_NAME_EXISTS: Final = 698 +ERROR_THREAD_WAS_SUSPENDED: Final = 699 +ERROR_IMAGE_NOT_AT_BASE: Final = 700 +ERROR_RXACT_STATE_CREATED: Final = 701 +ERROR_SEGMENT_NOTIFICATION: Final = 702 +ERROR_BAD_CURRENT_DIRECTORY: Final = 703 +ERROR_FT_READ_RECOVERY_FROM_BACKUP: Final = 704 +ERROR_FT_WRITE_RECOVERY: Final = 705 +ERROR_IMAGE_MACHINE_TYPE_MISMATCH: Final = 706 +ERROR_RECEIVE_PARTIAL: Final = 707 +ERROR_RECEIVE_EXPEDITED: Final = 708 +ERROR_RECEIVE_PARTIAL_EXPEDITED: Final = 709 +ERROR_EVENT_DONE: Final = 710 +ERROR_EVENT_PENDING: Final = 711 +ERROR_CHECKING_FILE_SYSTEM: Final = 712 +ERROR_FATAL_APP_EXIT: Final = 713 +ERROR_PREDEFINED_HANDLE: Final = 714 +ERROR_WAS_UNLOCKED: Final = 715 +ERROR_SERVICE_NOTIFICATION: Final = 716 +ERROR_WAS_LOCKED: Final = 717 +ERROR_LOG_HARD_ERROR: Final = 718 +ERROR_ALREADY_WIN32: Final = 719 +ERROR_IMAGE_MACHINE_TYPE_MISMATCH_EXE: Final = 720 +ERROR_NO_YIELD_PERFORMED: Final = 721 +ERROR_TIMER_RESUME_IGNORED: Final = 722 +ERROR_ARBITRATION_UNHANDLED: Final = 723 +ERROR_CARDBUS_NOT_SUPPORTED: Final = 724 +ERROR_MP_PROCESSOR_MISMATCH: Final = 725 +ERROR_HIBERNATED: Final = 726 +ERROR_RESUME_HIBERNATION: Final = 727 +ERROR_FIRMWARE_UPDATED: Final = 728 +ERROR_DRIVERS_LEAKING_LOCKED_PAGES: Final = 729 +ERROR_WAKE_SYSTEM: Final = 730 +ERROR_WAIT_1: Final = 731 +ERROR_WAIT_2: Final = 732 +ERROR_WAIT_3: Final = 733 +ERROR_WAIT_63: Final = 734 +ERROR_ABANDONED_WAIT_0: Final = 735 +ERROR_ABANDONED_WAIT_63: Final = 736 +ERROR_USER_APC: Final = 737 +ERROR_KERNEL_APC: Final = 738 +ERROR_ALERTED: Final = 739 +ERROR_ELEVATION_REQUIRED: Final = 740 +ERROR_REPARSE: Final = 741 +ERROR_OPLOCK_BREAK_IN_PROGRESS: Final = 742 +ERROR_VOLUME_MOUNTED: Final = 743 +ERROR_RXACT_COMMITTED: Final = 744 +ERROR_NOTIFY_CLEANUP: Final = 745 +ERROR_PRIMARY_TRANSPORT_CONNECT_FAILED: Final = 746 +ERROR_PAGE_FAULT_TRANSITION: Final = 747 +ERROR_PAGE_FAULT_DEMAND_ZERO: Final = 748 +ERROR_PAGE_FAULT_COPY_ON_WRITE: Final = 749 +ERROR_PAGE_FAULT_GUARD_PAGE: Final = 750 +ERROR_PAGE_FAULT_PAGING_FILE: Final = 751 +ERROR_CACHE_PAGE_LOCKED: Final = 752 +ERROR_CRASH_DUMP: Final = 753 +ERROR_BUFFER_ALL_ZEROS: Final = 754 +ERROR_REPARSE_OBJECT: Final = 755 +ERROR_RESOURCE_REQUIREMENTS_CHANGED: Final = 756 +ERROR_TRANSLATION_COMPLETE: Final = 757 +ERROR_NOTHING_TO_TERMINATE: Final = 758 +ERROR_PROCESS_NOT_IN_JOB: Final = 759 +ERROR_PROCESS_IN_JOB: Final = 760 +ERROR_VOLSNAP_HIBERNATE_READY: Final = 761 +ERROR_FSFILTER_OP_COMPLETED_SUCCESSFULLY: Final = 762 +ERROR_INTERRUPT_VECTOR_ALREADY_CONNECTED: Final = 763 +ERROR_INTERRUPT_STILL_CONNECTED: Final = 764 +ERROR_WAIT_FOR_OPLOCK: Final = 765 +ERROR_DBG_EXCEPTION_HANDLED: Final = 766 +ERROR_DBG_CONTINUE: Final = 767 +ERROR_CALLBACK_POP_STACK: Final = 768 +ERROR_COMPRESSION_DISABLED: Final = 769 +ERROR_CANTFETCHBACKWARDS: Final = 770 +ERROR_CANTSCROLLBACKWARDS: Final = 771 +ERROR_ROWSNOTRELEASED: Final = 772 +ERROR_BAD_ACCESSOR_FLAGS: Final = 773 +ERROR_ERRORS_ENCOUNTERED: Final = 774 +ERROR_NOT_CAPABLE: Final = 775 +ERROR_REQUEST_OUT_OF_SEQUENCE: Final = 776 +ERROR_VERSION_PARSE_ERROR: Final = 777 +ERROR_BADSTARTPOSITION: Final = 778 +ERROR_MEMORY_HARDWARE: Final = 779 +ERROR_DISK_REPAIR_DISABLED: Final = 780 +ERROR_INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE: Final = 781 +ERROR_SYSTEM_POWERSTATE_TRANSITION: Final = 782 +ERROR_SYSTEM_POWERSTATE_COMPLEX_TRANSITION: Final = 783 +ERROR_MCA_EXCEPTION: Final = 784 +ERROR_ACCESS_AUDIT_BY_POLICY: Final = 785 +ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY: Final = 786 +ERROR_ABANDON_HIBERFILE: Final = 787 +ERROR_LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED: Final = 788 +ERROR_LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR: Final = 789 +ERROR_LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR: Final = 790 +ERROR_BAD_MCFG_TABLE: Final = 791 +ERROR_DISK_REPAIR_REDIRECTED: Final = 792 +ERROR_DISK_REPAIR_UNSUCCESSFUL: Final = 793 +ERROR_CORRUPT_LOG_OVERFULL: Final = 794 +ERROR_CORRUPT_LOG_CORRUPTED: Final = 795 +ERROR_CORRUPT_LOG_UNAVAILABLE: Final = 796 +ERROR_CORRUPT_LOG_DELETED_FULL: Final = 797 +ERROR_CORRUPT_LOG_CLEARED: Final = 798 +ERROR_ORPHAN_NAME_EXHAUSTED: Final = 799 +ERROR_OPLOCK_SWITCHED_TO_NEW_HANDLE: Final = 800 +ERROR_CANNOT_GRANT_REQUESTED_OPLOCK: Final = 801 +ERROR_CANNOT_BREAK_OPLOCK: Final = 802 +ERROR_OPLOCK_HANDLE_CLOSED: Final = 803 +ERROR_NO_ACE_CONDITION: Final = 804 +ERROR_INVALID_ACE_CONDITION: Final = 805 +ERROR_FILE_HANDLE_REVOKED: Final = 806 +ERROR_IMAGE_AT_DIFFERENT_BASE: Final = 807 +ERROR_ENCRYPTED_IO_NOT_POSSIBLE: Final = 808 +ERROR_FILE_METADATA_OPTIMIZATION_IN_PROGRESS: Final = 809 +ERROR_QUOTA_ACTIVITY: Final = 810 +ERROR_HANDLE_REVOKED: Final = 811 +ERROR_CALLBACK_INVOKE_INLINE: Final = 812 +ERROR_CPU_SET_INVALID: Final = 813 +ERROR_ENCLAVE_NOT_TERMINATED: Final = 814 +ERROR_ENCLAVE_VIOLATION: Final = 815 +ERROR_SERVER_TRANSPORT_CONFLICT: Final = 816 +ERROR_CERTIFICATE_VALIDATION_PREFERENCE_CONFLICT: Final = 817 +ERROR_FT_READ_FROM_COPY_FAILURE: Final = 818 +ERROR_SECTION_DIRECT_MAP_ONLY: Final = 819 +ERROR_EA_ACCESS_DENIED: Final = 994 +ERROR_OPERATION_ABORTED: Final = 995 +ERROR_IO_INCOMPLETE: Final = 996 +ERROR_IO_PENDING: Final = 997 +ERROR_NOACCESS: Final = 998 +ERROR_SWAPERROR: Final = 999 +ERROR_STACK_OVERFLOW: Final = 1001 +ERROR_INVALID_MESSAGE: Final = 1002 +ERROR_CAN_NOT_COMPLETE: Final = 1003 +ERROR_INVALID_FLAGS: Final = 1004 +ERROR_UNRECOGNIZED_VOLUME: Final = 1005 +ERROR_FILE_INVALID: Final = 1006 +ERROR_FULLSCREEN_MODE: Final = 1007 +ERROR_NO_TOKEN: Final = 1008 +ERROR_BADDB: Final = 1009 +ERROR_BADKEY: Final = 1010 +ERROR_CANTOPEN: Final = 1011 +ERROR_CANTREAD: Final = 1012 +ERROR_CANTWRITE: Final = 1013 +ERROR_REGISTRY_RECOVERED: Final = 1014 +ERROR_REGISTRY_CORRUPT: Final = 1015 +ERROR_REGISTRY_IO_FAILED: Final = 1016 +ERROR_NOT_REGISTRY_FILE: Final = 1017 +ERROR_KEY_DELETED: Final = 1018 +ERROR_NO_LOG_SPACE: Final = 1019 +ERROR_KEY_HAS_CHILDREN: Final = 1020 +ERROR_CHILD_MUST_BE_VOLATILE: Final = 1021 +ERROR_NOTIFY_ENUM_DIR: Final = 1022 +ERROR_DEPENDENT_SERVICES_RUNNING: Final = 1051 +ERROR_INVALID_SERVICE_CONTROL: Final = 1052 +ERROR_SERVICE_REQUEST_TIMEOUT: Final = 1053 +ERROR_SERVICE_NO_THREAD: Final = 1054 +ERROR_SERVICE_DATABASE_LOCKED: Final = 1055 +ERROR_SERVICE_ALREADY_RUNNING: Final = 1056 +ERROR_INVALID_SERVICE_ACCOUNT: Final = 1057 +ERROR_SERVICE_DISABLED: Final = 1058 +ERROR_CIRCULAR_DEPENDENCY: Final = 1059 +ERROR_SERVICE_DOES_NOT_EXIST: Final = 1060 +ERROR_SERVICE_CANNOT_ACCEPT_CTRL: Final = 1061 +ERROR_SERVICE_NOT_ACTIVE: Final = 1062 +ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: Final = 1063 +ERROR_EXCEPTION_IN_SERVICE: Final = 1064 +ERROR_DATABASE_DOES_NOT_EXIST: Final = 1065 +ERROR_SERVICE_SPECIFIC_ERROR: Final = 1066 +ERROR_PROCESS_ABORTED: Final = 1067 +ERROR_SERVICE_DEPENDENCY_FAIL: Final = 1068 +ERROR_SERVICE_LOGON_FAILED: Final = 1069 +ERROR_SERVICE_START_HANG: Final = 1070 +ERROR_INVALID_SERVICE_LOCK: Final = 1071 +ERROR_SERVICE_MARKED_FOR_DELETE: Final = 1072 +ERROR_SERVICE_EXISTS: Final = 1073 +ERROR_ALREADY_RUNNING_LKG: Final = 1074 +ERROR_SERVICE_DEPENDENCY_DELETED: Final = 1075 +ERROR_BOOT_ALREADY_ACCEPTED: Final = 1076 +ERROR_SERVICE_NEVER_STARTED: Final = 1077 +ERROR_DUPLICATE_SERVICE_NAME: Final = 1078 +ERROR_DIFFERENT_SERVICE_ACCOUNT: Final = 1079 +ERROR_CANNOT_DETECT_DRIVER_FAILURE: Final = 1080 +ERROR_CANNOT_DETECT_PROCESS_ABORT: Final = 1081 +ERROR_NO_RECOVERY_PROGRAM: Final = 1082 +ERROR_SERVICE_NOT_IN_EXE: Final = 1083 +ERROR_NOT_SAFEBOOT_SERVICE: Final = 1084 +ERROR_END_OF_MEDIA: Final = 1100 +ERROR_FILEMARK_DETECTED: Final = 1101 +ERROR_BEGINNING_OF_MEDIA: Final = 1102 +ERROR_SETMARK_DETECTED: Final = 1103 +ERROR_NO_DATA_DETECTED: Final = 1104 +ERROR_PARTITION_FAILURE: Final = 1105 +ERROR_INVALID_BLOCK_LENGTH: Final = 1106 +ERROR_DEVICE_NOT_PARTITIONED: Final = 1107 +ERROR_UNABLE_TO_LOCK_MEDIA: Final = 1108 +ERROR_UNABLE_TO_UNLOAD_MEDIA: Final = 1109 +ERROR_MEDIA_CHANGED: Final = 1110 +ERROR_BUS_RESET: Final = 1111 +ERROR_NO_MEDIA_IN_DRIVE: Final = 1112 +ERROR_NO_UNICODE_TRANSLATION: Final = 1113 +ERROR_DLL_INIT_FAILED: Final = 1114 +ERROR_SHUTDOWN_IN_PROGRESS: Final = 1115 +ERROR_NO_SHUTDOWN_IN_PROGRESS: Final = 1116 +ERROR_IO_DEVICE: Final = 1117 +ERROR_SERIAL_NO_DEVICE: Final = 1118 +ERROR_IRQ_BUSY: Final = 1119 +ERROR_MORE_WRITES: Final = 1120 +ERROR_COUNTER_TIMEOUT: Final = 1121 +ERROR_FLOPPY_ID_MARK_NOT_FOUND: Final = 1122 +ERROR_FLOPPY_WRONG_CYLINDER: Final = 1123 +ERROR_FLOPPY_UNKNOWN_ERROR: Final = 1124 +ERROR_FLOPPY_BAD_REGISTERS: Final = 1125 +ERROR_DISK_RECALIBRATE_FAILED: Final = 1126 +ERROR_DISK_OPERATION_FAILED: Final = 1127 +ERROR_DISK_RESET_FAILED: Final = 1128 +ERROR_EOM_OVERFLOW: Final = 1129 +ERROR_NOT_ENOUGH_SERVER_MEMORY: Final = 1130 +ERROR_POSSIBLE_DEADLOCK: Final = 1131 +ERROR_MAPPED_ALIGNMENT: Final = 1132 +ERROR_SET_POWER_STATE_VETOED: Final = 1140 +ERROR_SET_POWER_STATE_FAILED: Final = 1141 +ERROR_TOO_MANY_LINKS: Final = 1142 +ERROR_OLD_WIN_VERSION: Final = 1150 +ERROR_APP_WRONG_OS: Final = 1151 +ERROR_SINGLE_INSTANCE_APP: Final = 1152 +ERROR_RMODE_APP: Final = 1153 +ERROR_INVALID_DLL: Final = 1154 +ERROR_NO_ASSOCIATION: Final = 1155 +ERROR_DDE_FAIL: Final = 1156 +ERROR_DLL_NOT_FOUND: Final = 1157 +ERROR_NO_MORE_USER_HANDLES: Final = 1158 +ERROR_MESSAGE_SYNC_ONLY: Final = 1159 +ERROR_SOURCE_ELEMENT_EMPTY: Final = 1160 +ERROR_DESTINATION_ELEMENT_FULL: Final = 1161 +ERROR_ILLEGAL_ELEMENT_ADDRESS: Final = 1162 +ERROR_MAGAZINE_NOT_PRESENT: Final = 1163 +ERROR_DEVICE_REINITIALIZATION_NEEDED: Final = 1164 +ERROR_DEVICE_REQUIRES_CLEANING: Final = 1165 +ERROR_DEVICE_DOOR_OPEN: Final = 1166 +ERROR_DEVICE_NOT_CONNECTED: Final = 1167 +ERROR_NOT_FOUND: Final = 1168 +ERROR_NO_MATCH: Final = 1169 +ERROR_SET_NOT_FOUND: Final = 1170 +ERROR_POINT_NOT_FOUND: Final = 1171 +ERROR_NO_TRACKING_SERVICE: Final = 1172 +ERROR_NO_VOLUME_ID: Final = 1173 +ERROR_UNABLE_TO_REMOVE_REPLACED: Final = 1175 +ERROR_UNABLE_TO_MOVE_REPLACEMENT: Final = 1176 +ERROR_UNABLE_TO_MOVE_REPLACEMENT_2: Final = 1177 +ERROR_JOURNAL_DELETE_IN_PROGRESS: Final = 1178 +ERROR_JOURNAL_NOT_ACTIVE: Final = 1179 +ERROR_POTENTIAL_FILE_FOUND: Final = 1180 +ERROR_JOURNAL_ENTRY_DELETED: Final = 1181 +ERROR_PARTITION_TERMINATING: Final = 1184 +ERROR_SHUTDOWN_IS_SCHEDULED: Final = 1190 +ERROR_SHUTDOWN_USERS_LOGGED_ON: Final = 1191 +ERROR_SHUTDOWN_DISKS_NOT_IN_MAINTENANCE_MODE: Final = 1192 +ERROR_BAD_DEVICE: Final = 1200 +ERROR_CONNECTION_UNAVAIL: Final = 1201 +ERROR_DEVICE_ALREADY_REMEMBERED: Final = 1202 +ERROR_NO_NET_OR_BAD_PATH: Final = 1203 +ERROR_BAD_PROVIDER: Final = 1204 +ERROR_CANNOT_OPEN_PROFILE: Final = 1205 +ERROR_BAD_PROFILE: Final = 1206 +ERROR_NOT_CONTAINER: Final = 1207 +ERROR_EXTENDED_ERROR: Final = 1208 +ERROR_INVALID_GROUPNAME: Final = 1209 +ERROR_INVALID_COMPUTERNAME: Final = 1210 +ERROR_INVALID_EVENTNAME: Final = 1211 +ERROR_INVALID_DOMAINNAME: Final = 1212 +ERROR_INVALID_SERVICENAME: Final = 1213 +ERROR_INVALID_NETNAME: Final = 1214 +ERROR_INVALID_SHARENAME: Final = 1215 +ERROR_INVALID_PASSWORDNAME: Final = 1216 +ERROR_INVALID_MESSAGENAME: Final = 1217 +ERROR_INVALID_MESSAGEDEST: Final = 1218 +ERROR_SESSION_CREDENTIAL_CONFLICT: Final = 1219 +ERROR_REMOTE_SESSION_LIMIT_EXCEEDED: Final = 1220 +ERROR_DUP_DOMAINNAME: Final = 1221 +ERROR_NO_NETWORK: Final = 1222 +ERROR_CANCELLED: Final = 1223 +ERROR_USER_MAPPED_FILE: Final = 1224 +ERROR_CONNECTION_REFUSED: Final = 1225 +ERROR_GRACEFUL_DISCONNECT: Final = 1226 +ERROR_ADDRESS_ALREADY_ASSOCIATED: Final = 1227 +ERROR_ADDRESS_NOT_ASSOCIATED: Final = 1228 +ERROR_CONNECTION_INVALID: Final = 1229 +ERROR_CONNECTION_ACTIVE: Final = 1230 +ERROR_NETWORK_UNREACHABLE: Final = 1231 +ERROR_HOST_UNREACHABLE: Final = 1232 +ERROR_PROTOCOL_UNREACHABLE: Final = 1233 +ERROR_PORT_UNREACHABLE: Final = 1234 +ERROR_REQUEST_ABORTED: Final = 1235 +ERROR_CONNECTION_ABORTED: Final = 1236 +ERROR_RETRY: Final = 1237 +ERROR_CONNECTION_COUNT_LIMIT: Final = 1238 +ERROR_LOGIN_TIME_RESTRICTION: Final = 1239 +ERROR_LOGIN_WKSTA_RESTRICTION: Final = 1240 +ERROR_INCORRECT_ADDRESS: Final = 1241 +ERROR_ALREADY_REGISTERED: Final = 1242 +ERROR_SERVICE_NOT_FOUND: Final = 1243 +ERROR_NOT_AUTHENTICATED: Final = 1244 +ERROR_NOT_LOGGED_ON: Final = 1245 +ERROR_CONTINUE: Final = 1246 +ERROR_ALREADY_INITIALIZED: Final = 1247 +ERROR_NO_MORE_DEVICES: Final = 1248 +ERROR_NO_SUCH_SITE: Final = 1249 +ERROR_DOMAIN_CONTROLLER_EXISTS: Final = 1250 +ERROR_ONLY_IF_CONNECTED: Final = 1251 +ERROR_OVERRIDE_NOCHANGES: Final = 1252 +ERROR_BAD_USER_PROFILE: Final = 1253 +ERROR_NOT_SUPPORTED_ON_SBS: Final = 1254 +ERROR_SERVER_SHUTDOWN_IN_PROGRESS: Final = 1255 +ERROR_HOST_DOWN: Final = 1256 +ERROR_NON_ACCOUNT_SID: Final = 1257 +ERROR_NON_DOMAIN_SID: Final = 1258 +ERROR_APPHELP_BLOCK: Final = 1259 +ERROR_ACCESS_DISABLED_BY_POLICY: Final = 1260 +ERROR_REG_NAT_CONSUMPTION: Final = 1261 +ERROR_CSCSHARE_OFFLINE: Final = 1262 +ERROR_PKINIT_FAILURE: Final = 1263 +ERROR_SMARTCARD_SUBSYSTEM_FAILURE: Final = 1264 +ERROR_DOWNGRADE_DETECTED: Final = 1265 +ERROR_MACHINE_LOCKED: Final = 1271 +ERROR_SMB_GUEST_LOGON_BLOCKED: Final = 1272 +ERROR_CALLBACK_SUPPLIED_INVALID_DATA: Final = 1273 +ERROR_SYNC_FOREGROUND_REFRESH_REQUIRED: Final = 1274 +ERROR_DRIVER_BLOCKED: Final = 1275 +ERROR_INVALID_IMPORT_OF_NON_DLL: Final = 1276 +ERROR_ACCESS_DISABLED_WEBBLADE: Final = 1277 +ERROR_ACCESS_DISABLED_WEBBLADE_TAMPER: Final = 1278 +ERROR_RECOVERY_FAILURE: Final = 1279 +ERROR_ALREADY_FIBER: Final = 1280 +ERROR_ALREADY_THREAD: Final = 1281 +ERROR_STACK_BUFFER_OVERRUN: Final = 1282 +ERROR_PARAMETER_QUOTA_EXCEEDED: Final = 1283 +ERROR_DEBUGGER_INACTIVE: Final = 1284 +ERROR_DELAY_LOAD_FAILED: Final = 1285 +ERROR_VDM_DISALLOWED: Final = 1286 +ERROR_UNIDENTIFIED_ERROR: Final = 1287 +ERROR_INVALID_CRUNTIME_PARAMETER: Final = 1288 +ERROR_BEYOND_VDL: Final = 1289 +ERROR_INCOMPATIBLE_SERVICE_SID_TYPE: Final = 1290 +ERROR_DRIVER_PROCESS_TERMINATED: Final = 1291 +ERROR_IMPLEMENTATION_LIMIT: Final = 1292 +ERROR_PROCESS_IS_PROTECTED: Final = 1293 +ERROR_SERVICE_NOTIFY_CLIENT_LAGGING: Final = 1294 +ERROR_DISK_QUOTA_EXCEEDED: Final = 1295 +ERROR_CONTENT_BLOCKED: Final = 1296 +ERROR_INCOMPATIBLE_SERVICE_PRIVILEGE: Final = 1297 +ERROR_APP_HANG: Final = 1298 +ERROR_INVALID_LABEL: Final = 1299 +ERROR_NOT_ALL_ASSIGNED: Final = 1300 +ERROR_SOME_NOT_MAPPED: Final = 1301 +ERROR_NO_QUOTAS_FOR_ACCOUNT: Final = 1302 +ERROR_LOCAL_USER_SESSION_KEY: Final = 1303 +ERROR_NULL_LM_PASSWORD: Final = 1304 +ERROR_UNKNOWN_REVISION: Final = 1305 +ERROR_REVISION_MISMATCH: Final = 1306 +ERROR_INVALID_OWNER: Final = 1307 +ERROR_INVALID_PRIMARY_GROUP: Final = 1308 +ERROR_NO_IMPERSONATION_TOKEN: Final = 1309 +ERROR_CANT_DISABLE_MANDATORY: Final = 1310 +ERROR_NO_LOGON_SERVERS: Final = 1311 +ERROR_NO_SUCH_LOGON_SESSION: Final = 1312 +ERROR_NO_SUCH_PRIVILEGE: Final = 1313 +ERROR_PRIVILEGE_NOT_HELD: Final = 1314 +ERROR_INVALID_ACCOUNT_NAME: Final = 1315 +ERROR_USER_EXISTS: Final = 1316 +ERROR_NO_SUCH_USER: Final = 1317 +ERROR_GROUP_EXISTS: Final = 1318 +ERROR_NO_SUCH_GROUP: Final = 1319 +ERROR_MEMBER_IN_GROUP: Final = 1320 +ERROR_MEMBER_NOT_IN_GROUP: Final = 1321 +ERROR_LAST_ADMIN: Final = 1322 +ERROR_WRONG_PASSWORD: Final = 1323 +ERROR_ILL_FORMED_PASSWORD: Final = 1324 +ERROR_PASSWORD_RESTRICTION: Final = 1325 +ERROR_LOGON_FAILURE: Final = 1326 +ERROR_ACCOUNT_RESTRICTION: Final = 1327 +ERROR_INVALID_LOGON_HOURS: Final = 1328 +ERROR_INVALID_WORKSTATION: Final = 1329 +ERROR_PASSWORD_EXPIRED: Final = 1330 +ERROR_ACCOUNT_DISABLED: Final = 1331 +ERROR_NONE_MAPPED: Final = 1332 +ERROR_TOO_MANY_LUIDS_REQUESTED: Final = 1333 +ERROR_LUIDS_EXHAUSTED: Final = 1334 +ERROR_INVALID_SUB_AUTHORITY: Final = 1335 +ERROR_INVALID_ACL: Final = 1336 +ERROR_INVALID_SID: Final = 1337 +ERROR_INVALID_SECURITY_DESCR: Final = 1338 +ERROR_BAD_INHERITANCE_ACL: Final = 1340 +ERROR_SERVER_DISABLED: Final = 1341 +ERROR_SERVER_NOT_DISABLED: Final = 1342 +ERROR_INVALID_ID_AUTHORITY: Final = 1343 +ERROR_ALLOTTED_SPACE_EXCEEDED: Final = 1344 +ERROR_INVALID_GROUP_ATTRIBUTES: Final = 1345 +ERROR_BAD_IMPERSONATION_LEVEL: Final = 1346 +ERROR_CANT_OPEN_ANONYMOUS: Final = 1347 +ERROR_BAD_VALIDATION_CLASS: Final = 1348 +ERROR_BAD_TOKEN_TYPE: Final = 1349 +ERROR_NO_SECURITY_ON_OBJECT: Final = 1350 +ERROR_CANT_ACCESS_DOMAIN_INFO: Final = 1351 +ERROR_INVALID_SERVER_STATE: Final = 1352 +ERROR_INVALID_DOMAIN_STATE: Final = 1353 +ERROR_INVALID_DOMAIN_ROLE: Final = 1354 +ERROR_NO_SUCH_DOMAIN: Final = 1355 +ERROR_DOMAIN_EXISTS: Final = 1356 +ERROR_DOMAIN_LIMIT_EXCEEDED: Final = 1357 +ERROR_INTERNAL_DB_CORRUPTION: Final = 1358 +ERROR_INTERNAL_ERROR: Final = 1359 +ERROR_GENERIC_NOT_MAPPED: Final = 1360 +ERROR_BAD_DESCRIPTOR_FORMAT: Final = 1361 +ERROR_NOT_LOGON_PROCESS: Final = 1362 +ERROR_LOGON_SESSION_EXISTS: Final = 1363 +ERROR_NO_SUCH_PACKAGE: Final = 1364 +ERROR_BAD_LOGON_SESSION_STATE: Final = 1365 +ERROR_LOGON_SESSION_COLLISION: Final = 1366 +ERROR_INVALID_LOGON_TYPE: Final = 1367 +ERROR_CANNOT_IMPERSONATE: Final = 1368 +ERROR_RXACT_INVALID_STATE: Final = 1369 +ERROR_RXACT_COMMIT_FAILURE: Final = 1370 +ERROR_SPECIAL_ACCOUNT: Final = 1371 +ERROR_SPECIAL_GROUP: Final = 1372 +ERROR_SPECIAL_USER: Final = 1373 +ERROR_MEMBERS_PRIMARY_GROUP: Final = 1374 +ERROR_TOKEN_ALREADY_IN_USE: Final = 1375 +ERROR_NO_SUCH_ALIAS: Final = 1376 +ERROR_MEMBER_NOT_IN_ALIAS: Final = 1377 +ERROR_MEMBER_IN_ALIAS: Final = 1378 +ERROR_ALIAS_EXISTS: Final = 1379 +ERROR_LOGON_NOT_GRANTED: Final = 1380 +ERROR_TOO_MANY_SECRETS: Final = 1381 +ERROR_SECRET_TOO_LONG: Final = 1382 +ERROR_INTERNAL_DB_ERROR: Final = 1383 +ERROR_TOO_MANY_CONTEXT_IDS: Final = 1384 +ERROR_LOGON_TYPE_NOT_GRANTED: Final = 1385 +ERROR_NT_CROSS_ENCRYPTION_REQUIRED: Final = 1386 +ERROR_NO_SUCH_MEMBER: Final = 1387 +ERROR_INVALID_MEMBER: Final = 1388 +ERROR_TOO_MANY_SIDS: Final = 1389 +ERROR_LM_CROSS_ENCRYPTION_REQUIRED: Final = 1390 +ERROR_NO_INHERITANCE: Final = 1391 +ERROR_FILE_CORRUPT: Final = 1392 +ERROR_DISK_CORRUPT: Final = 1393 +ERROR_NO_USER_SESSION_KEY: Final = 1394 +ERROR_LICENSE_QUOTA_EXCEEDED: Final = 1395 +ERROR_WRONG_TARGET_NAME: Final = 1396 +ERROR_MUTUAL_AUTH_FAILED: Final = 1397 +ERROR_TIME_SKEW: Final = 1398 +ERROR_CURRENT_DOMAIN_NOT_ALLOWED: Final = 1399 +ERROR_INVALID_WINDOW_HANDLE: Final = 1400 +ERROR_INVALID_MENU_HANDLE: Final = 1401 +ERROR_INVALID_CURSOR_HANDLE: Final = 1402 +ERROR_INVALID_ACCEL_HANDLE: Final = 1403 +ERROR_INVALID_HOOK_HANDLE: Final = 1404 +ERROR_INVALID_DWP_HANDLE: Final = 1405 +ERROR_TLW_WITH_WSCHILD: Final = 1406 +ERROR_CANNOT_FIND_WND_CLASS: Final = 1407 +ERROR_WINDOW_OF_OTHER_THREAD: Final = 1408 +ERROR_HOTKEY_ALREADY_REGISTERED: Final = 1409 +ERROR_CLASS_ALREADY_EXISTS: Final = 1410 +ERROR_CLASS_DOES_NOT_EXIST: Final = 1411 +ERROR_CLASS_HAS_WINDOWS: Final = 1412 +ERROR_INVALID_INDEX: Final = 1413 +ERROR_INVALID_ICON_HANDLE: Final = 1414 +ERROR_PRIVATE_DIALOG_INDEX: Final = 1415 +ERROR_LISTBOX_ID_NOT_FOUND: Final = 1416 +ERROR_NO_WILDCARD_CHARACTERS: Final = 1417 +ERROR_CLIPBOARD_NOT_OPEN: Final = 1418 +ERROR_HOTKEY_NOT_REGISTERED: Final = 1419 +ERROR_WINDOW_NOT_DIALOG: Final = 1420 +ERROR_CONTROL_ID_NOT_FOUND: Final = 1421 +ERROR_INVALID_COMBOBOX_MESSAGE: Final = 1422 +ERROR_WINDOW_NOT_COMBOBOX: Final = 1423 +ERROR_INVALID_EDIT_HEIGHT: Final = 1424 +ERROR_DC_NOT_FOUND: Final = 1425 +ERROR_INVALID_HOOK_FILTER: Final = 1426 +ERROR_INVALID_FILTER_PROC: Final = 1427 +ERROR_HOOK_NEEDS_HMOD: Final = 1428 +ERROR_GLOBAL_ONLY_HOOK: Final = 1429 +ERROR_JOURNAL_HOOK_SET: Final = 1430 +ERROR_HOOK_NOT_INSTALLED: Final = 1431 +ERROR_INVALID_LB_MESSAGE: Final = 1432 +ERROR_SETCOUNT_ON_BAD_LB: Final = 1433 +ERROR_LB_WITHOUT_TABSTOPS: Final = 1434 +ERROR_DESTROY_OBJECT_OF_OTHER_THREAD: Final = 1435 +ERROR_CHILD_WINDOW_MENU: Final = 1436 +ERROR_NO_SYSTEM_MENU: Final = 1437 +ERROR_INVALID_MSGBOX_STYLE: Final = 1438 +ERROR_INVALID_SPI_VALUE: Final = 1439 +ERROR_SCREEN_ALREADY_LOCKED: Final = 1440 +ERROR_HWNDS_HAVE_DIFF_PARENT: Final = 1441 +ERROR_NOT_CHILD_WINDOW: Final = 1442 +ERROR_INVALID_GW_COMMAND: Final = 1443 +ERROR_INVALID_THREAD_ID: Final = 1444 +ERROR_NON_MDICHILD_WINDOW: Final = 1445 +ERROR_POPUP_ALREADY_ACTIVE: Final = 1446 +ERROR_NO_SCROLLBARS: Final = 1447 +ERROR_INVALID_SCROLLBAR_RANGE: Final = 1448 +ERROR_INVALID_SHOWWIN_COMMAND: Final = 1449 +ERROR_NO_SYSTEM_RESOURCES: Final = 1450 +ERROR_NONPAGED_SYSTEM_RESOURCES: Final = 1451 +ERROR_PAGED_SYSTEM_RESOURCES: Final = 1452 +ERROR_WORKING_SET_QUOTA: Final = 1453 +ERROR_PAGEFILE_QUOTA: Final = 1454 +ERROR_COMMITMENT_LIMIT: Final = 1455 +ERROR_MENU_ITEM_NOT_FOUND: Final = 1456 +ERROR_INVALID_KEYBOARD_HANDLE: Final = 1457 +ERROR_HOOK_TYPE_NOT_ALLOWED: Final = 1458 +ERROR_REQUIRES_INTERACTIVE_WINDOWSTATION: Final = 1459 +ERROR_TIMEOUT: Final = 1460 +ERROR_INVALID_MONITOR_HANDLE: Final = 1461 +ERROR_INCORRECT_SIZE: Final = 1462 +ERROR_SYMLINK_CLASS_DISABLED: Final = 1463 +ERROR_SYMLINK_NOT_SUPPORTED: Final = 1464 +ERROR_XML_PARSE_ERROR: Final = 1465 +ERROR_XMLDSIG_ERROR: Final = 1466 +ERROR_RESTART_APPLICATION: Final = 1467 +ERROR_WRONG_COMPARTMENT: Final = 1468 +ERROR_AUTHIP_FAILURE: Final = 1469 +ERROR_NO_NVRAM_RESOURCES: Final = 1470 +ERROR_NOT_GUI_PROCESS: Final = 1471 +ERROR_EVENTLOG_FILE_CORRUPT: Final = 1500 +ERROR_EVENTLOG_CANT_START: Final = 1501 +ERROR_LOG_FILE_FULL: Final = 1502 +ERROR_EVENTLOG_FILE_CHANGED: Final = 1503 +ERROR_CONTAINER_ASSIGNED: Final = 1504 +ERROR_JOB_NO_CONTAINER: Final = 1505 +ERROR_INVALID_TASK_NAME: Final = 1550 +ERROR_INVALID_TASK_INDEX: Final = 1551 +ERROR_THREAD_ALREADY_IN_TASK: Final = 1552 +ERROR_INSTALL_SERVICE_FAILURE: Final = 1601 +ERROR_INSTALL_USEREXIT: Final = 1602 +ERROR_INSTALL_FAILURE: Final = 1603 +ERROR_INSTALL_SUSPEND: Final = 1604 +ERROR_UNKNOWN_PRODUCT: Final = 1605 +ERROR_UNKNOWN_FEATURE: Final = 1606 +ERROR_UNKNOWN_COMPONENT: Final = 1607 +ERROR_UNKNOWN_PROPERTY: Final = 1608 +ERROR_INVALID_HANDLE_STATE: Final = 1609 +ERROR_BAD_CONFIGURATION: Final = 1610 +ERROR_INDEX_ABSENT: Final = 1611 +ERROR_INSTALL_SOURCE_ABSENT: Final = 1612 +ERROR_INSTALL_PACKAGE_VERSION: Final = 1613 +ERROR_PRODUCT_UNINSTALLED: Final = 1614 +ERROR_BAD_QUERY_SYNTAX: Final = 1615 +ERROR_INVALID_FIELD: Final = 1616 +ERROR_DEVICE_REMOVED: Final = 1617 +ERROR_INSTALL_ALREADY_RUNNING: Final = 1618 +ERROR_INSTALL_PACKAGE_OPEN_FAILED: Final = 1619 +ERROR_INSTALL_PACKAGE_INVALID: Final = 1620 +ERROR_INSTALL_UI_FAILURE: Final = 1621 +ERROR_INSTALL_LOG_FAILURE: Final = 1622 +ERROR_INSTALL_LANGUAGE_UNSUPPORTED: Final = 1623 +ERROR_INSTALL_TRANSFORM_FAILURE: Final = 1624 +ERROR_INSTALL_PACKAGE_REJECTED: Final = 1625 +ERROR_FUNCTION_NOT_CALLED: Final = 1626 +ERROR_FUNCTION_FAILED: Final = 1627 +ERROR_INVALID_TABLE: Final = 1628 +ERROR_DATATYPE_MISMATCH: Final = 1629 +ERROR_UNSUPPORTED_TYPE: Final = 1630 +ERROR_CREATE_FAILED: Final = 1631 +ERROR_INSTALL_TEMP_UNWRITABLE: Final = 1632 +ERROR_INSTALL_PLATFORM_UNSUPPORTED: Final = 1633 +ERROR_INSTALL_NOTUSED: Final = 1634 +ERROR_PATCH_PACKAGE_OPEN_FAILED: Final = 1635 +ERROR_PATCH_PACKAGE_INVALID: Final = 1636 +ERROR_PATCH_PACKAGE_UNSUPPORTED: Final = 1637 +ERROR_PRODUCT_VERSION: Final = 1638 +ERROR_INVALID_COMMAND_LINE: Final = 1639 +ERROR_INSTALL_REMOTE_DISALLOWED: Final = 1640 +ERROR_SUCCESS_REBOOT_INITIATED: Final = 1641 +ERROR_PATCH_TARGET_NOT_FOUND: Final = 1642 +ERROR_PATCH_PACKAGE_REJECTED: Final = 1643 +ERROR_INSTALL_TRANSFORM_REJECTED: Final = 1644 +ERROR_INSTALL_REMOTE_PROHIBITED: Final = 1645 +ERROR_PATCH_REMOVAL_UNSUPPORTED: Final = 1646 +ERROR_UNKNOWN_PATCH: Final = 1647 +ERROR_PATCH_NO_SEQUENCE: Final = 1648 +ERROR_PATCH_REMOVAL_DISALLOWED: Final = 1649 +ERROR_INVALID_PATCH_XML: Final = 1650 +ERROR_PATCH_MANAGED_ADVERTISED_PRODUCT: Final = 1651 +ERROR_INSTALL_SERVICE_SAFEBOOT: Final = 1652 +ERROR_FAIL_FAST_EXCEPTION: Final = 1653 +ERROR_INSTALL_REJECTED: Final = 1654 +ERROR_DYNAMIC_CODE_BLOCKED: Final = 1655 +ERROR_NOT_SAME_OBJECT: Final = 1656 +ERROR_STRICT_CFG_VIOLATION: Final = 1657 +ERROR_SET_CONTEXT_DENIED: Final = 1660 +ERROR_CROSS_PARTITION_VIOLATION: Final = 1661 +ERROR_RETURN_ADDRESS_HIJACK_ATTEMPT: Final = 1662 +RPC_S_INVALID_STRING_BINDING: Final = 1700 +RPC_S_WRONG_KIND_OF_BINDING: Final = 1701 +RPC_S_INVALID_BINDING: Final = 1702 +RPC_S_PROTSEQ_NOT_SUPPORTED: Final = 1703 +RPC_S_INVALID_RPC_PROTSEQ: Final = 1704 +RPC_S_INVALID_STRING_UUID: Final = 1705 +RPC_S_INVALID_ENDPOINT_FORMAT: Final = 1706 +RPC_S_INVALID_NET_ADDR: Final = 1707 +RPC_S_NO_ENDPOINT_FOUND: Final = 1708 +RPC_S_INVALID_TIMEOUT: Final = 1709 +RPC_S_OBJECT_NOT_FOUND: Final = 1710 +RPC_S_ALREADY_REGISTERED: Final = 1711 +RPC_S_TYPE_ALREADY_REGISTERED: Final = 1712 +RPC_S_ALREADY_LISTENING: Final = 1713 +RPC_S_NO_PROTSEQS_REGISTERED: Final = 1714 +RPC_S_NOT_LISTENING: Final = 1715 +RPC_S_UNKNOWN_MGR_TYPE: Final = 1716 +RPC_S_UNKNOWN_IF: Final = 1717 +RPC_S_NO_BINDINGS: Final = 1718 +RPC_S_NO_PROTSEQS: Final = 1719 +RPC_S_CANT_CREATE_ENDPOINT: Final = 1720 +RPC_S_OUT_OF_RESOURCES: Final = 1721 +RPC_S_SERVER_UNAVAILABLE: Final = 1722 +RPC_S_SERVER_TOO_BUSY: Final = 1723 +RPC_S_INVALID_NETWORK_OPTIONS: Final = 1724 +RPC_S_NO_CALL_ACTIVE: Final = 1725 +RPC_S_CALL_FAILED: Final = 1726 +RPC_S_CALL_FAILED_DNE: Final = 1727 +RPC_S_PROTOCOL_ERROR: Final = 1728 +RPC_S_PROXY_ACCESS_DENIED: Final = 1729 +RPC_S_UNSUPPORTED_TRANS_SYN: Final = 1730 +RPC_S_UNSUPPORTED_TYPE: Final = 1732 +RPC_S_INVALID_TAG: Final = 1733 +RPC_S_INVALID_BOUND: Final = 1734 +RPC_S_NO_ENTRY_NAME: Final = 1735 +RPC_S_INVALID_NAME_SYNTAX: Final = 1736 +RPC_S_UNSUPPORTED_NAME_SYNTAX: Final = 1737 +RPC_S_UUID_NO_ADDRESS: Final = 1739 +RPC_S_DUPLICATE_ENDPOINT: Final = 1740 +RPC_S_UNKNOWN_AUTHN_TYPE: Final = 1741 +RPC_S_MAX_CALLS_TOO_SMALL: Final = 1742 +RPC_S_STRING_TOO_LONG: Final = 1743 +RPC_S_PROTSEQ_NOT_FOUND: Final = 1744 +RPC_S_PROCNUM_OUT_OF_RANGE: Final = 1745 +RPC_S_BINDING_HAS_NO_AUTH: Final = 1746 +RPC_S_UNKNOWN_AUTHN_SERVICE: Final = 1747 +RPC_S_UNKNOWN_AUTHN_LEVEL: Final = 1748 +RPC_S_INVALID_AUTH_IDENTITY: Final = 1749 +RPC_S_UNKNOWN_AUTHZ_SERVICE: Final = 1750 +EPT_S_INVALID_ENTRY: Final = 1751 +EPT_S_CANT_PERFORM_OP: Final = 1752 +EPT_S_NOT_REGISTERED: Final = 1753 +RPC_S_NOTHING_TO_EXPORT: Final = 1754 +RPC_S_INCOMPLETE_NAME: Final = 1755 +RPC_S_INVALID_VERS_OPTION: Final = 1756 +RPC_S_NO_MORE_MEMBERS: Final = 1757 +RPC_S_NOT_ALL_OBJS_UNEXPORTED: Final = 1758 +RPC_S_INTERFACE_NOT_FOUND: Final = 1759 +RPC_S_ENTRY_ALREADY_EXISTS: Final = 1760 +RPC_S_ENTRY_NOT_FOUND: Final = 1761 +RPC_S_NAME_SERVICE_UNAVAILABLE: Final = 1762 +RPC_S_INVALID_NAF_ID: Final = 1763 +RPC_S_CANNOT_SUPPORT: Final = 1764 +RPC_S_NO_CONTEXT_AVAILABLE: Final = 1765 +RPC_S_INTERNAL_ERROR: Final = 1766 +RPC_S_ZERO_DIVIDE: Final = 1767 +RPC_S_ADDRESS_ERROR: Final = 1768 +RPC_S_FP_DIV_ZERO: Final = 1769 +RPC_S_FP_UNDERFLOW: Final = 1770 +RPC_S_FP_OVERFLOW: Final = 1771 +RPC_X_NO_MORE_ENTRIES: Final = 1772 +RPC_X_SS_CHAR_TRANS_OPEN_FAIL: Final = 1773 +RPC_X_SS_CHAR_TRANS_SHORT_FILE: Final = 1774 +RPC_X_SS_IN_NULL_CONTEXT: Final = 1775 +RPC_X_SS_CONTEXT_DAMAGED: Final = 1777 +RPC_X_SS_HANDLES_MISMATCH: Final = 1778 +RPC_X_SS_CANNOT_GET_CALL_HANDLE: Final = 1779 +RPC_X_NULL_REF_POINTER: Final = 1780 +RPC_X_ENUM_VALUE_OUT_OF_RANGE: Final = 1781 +RPC_X_BYTE_COUNT_TOO_SMALL: Final = 1782 +RPC_X_BAD_STUB_DATA: Final = 1783 +ERROR_INVALID_USER_BUFFER: Final = 1784 +ERROR_UNRECOGNIZED_MEDIA: Final = 1785 +ERROR_NO_TRUST_LSA_SECRET: Final = 1786 +ERROR_NO_TRUST_SAM_ACCOUNT: Final = 1787 +ERROR_TRUSTED_DOMAIN_FAILURE: Final = 1788 +ERROR_TRUSTED_RELATIONSHIP_FAILURE: Final = 1789 +ERROR_TRUST_FAILURE: Final = 1790 +RPC_S_CALL_IN_PROGRESS: Final = 1791 +ERROR_NETLOGON_NOT_STARTED: Final = 1792 +ERROR_ACCOUNT_EXPIRED: Final = 1793 +ERROR_REDIRECTOR_HAS_OPEN_HANDLES: Final = 1794 +ERROR_PRINTER_DRIVER_ALREADY_INSTALLED: Final = 1795 +ERROR_UNKNOWN_PORT: Final = 1796 +ERROR_UNKNOWN_PRINTER_DRIVER: Final = 1797 +ERROR_UNKNOWN_PRINTPROCESSOR: Final = 1798 +ERROR_INVALID_SEPARATOR_FILE: Final = 1799 +ERROR_INVALID_PRIORITY: Final = 1800 +ERROR_INVALID_PRINTER_NAME: Final = 1801 +ERROR_PRINTER_ALREADY_EXISTS: Final = 1802 +ERROR_INVALID_PRINTER_COMMAND: Final = 1803 +ERROR_INVALID_DATATYPE: Final = 1804 +ERROR_INVALID_ENVIRONMENT: Final = 1805 +RPC_S_NO_MORE_BINDINGS: Final = 1806 +ERROR_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT: Final = 1807 +ERROR_NOLOGON_WORKSTATION_TRUST_ACCOUNT: Final = 1808 +ERROR_NOLOGON_SERVER_TRUST_ACCOUNT: Final = 1809 +ERROR_DOMAIN_TRUST_INCONSISTENT: Final = 1810 +ERROR_SERVER_HAS_OPEN_HANDLES: Final = 1811 +ERROR_RESOURCE_DATA_NOT_FOUND: Final = 1812 +ERROR_RESOURCE_TYPE_NOT_FOUND: Final = 1813 +ERROR_RESOURCE_NAME_NOT_FOUND: Final = 1814 +ERROR_RESOURCE_LANG_NOT_FOUND: Final = 1815 +ERROR_NOT_ENOUGH_QUOTA: Final = 1816 +RPC_S_NO_INTERFACES: Final = 1817 +RPC_S_CALL_CANCELLED: Final = 1818 +RPC_S_BINDING_INCOMPLETE: Final = 1819 +RPC_S_COMM_FAILURE: Final = 1820 +RPC_S_UNSUPPORTED_AUTHN_LEVEL: Final = 1821 +RPC_S_NO_PRINC_NAME: Final = 1822 +RPC_S_NOT_RPC_ERROR: Final = 1823 +RPC_S_UUID_LOCAL_ONLY: Final = 1824 +RPC_S_SEC_PKG_ERROR: Final = 1825 +RPC_S_NOT_CANCELLED: Final = 1826 +RPC_X_INVALID_ES_ACTION: Final = 1827 +RPC_X_WRONG_ES_VERSION: Final = 1828 +RPC_X_WRONG_STUB_VERSION: Final = 1829 +RPC_X_INVALID_PIPE_OBJECT: Final = 1830 +RPC_X_WRONG_PIPE_ORDER: Final = 1831 +RPC_X_WRONG_PIPE_VERSION: Final = 1832 +RPC_S_COOKIE_AUTH_FAILED: Final = 1833 +RPC_S_DO_NOT_DISTURB: Final = 1834 +RPC_S_SYSTEM_HANDLE_COUNT_EXCEEDED: Final = 1835 +RPC_S_SYSTEM_HANDLE_TYPE_MISMATCH: Final = 1836 +RPC_S_GROUP_MEMBER_NOT_FOUND: Final = 1898 +EPT_S_CANT_CREATE: Final = 1899 +RPC_S_INVALID_OBJECT: Final = 1900 +ERROR_INVALID_TIME: Final = 1901 +ERROR_INVALID_FORM_NAME: Final = 1902 +ERROR_INVALID_FORM_SIZE: Final = 1903 +ERROR_ALREADY_WAITING: Final = 1904 +ERROR_PRINTER_DELETED: Final = 1905 +ERROR_INVALID_PRINTER_STATE: Final = 1906 +ERROR_PASSWORD_MUST_CHANGE: Final = 1907 +ERROR_DOMAIN_CONTROLLER_NOT_FOUND: Final = 1908 +ERROR_ACCOUNT_LOCKED_OUT: Final = 1909 +OR_INVALID_OXID: Final = 1910 +OR_INVALID_OID: Final = 1911 +OR_INVALID_SET: Final = 1912 +RPC_S_SEND_INCOMPLETE: Final = 1913 +RPC_S_INVALID_ASYNC_HANDLE: Final = 1914 +RPC_S_INVALID_ASYNC_CALL: Final = 1915 +RPC_X_PIPE_CLOSED: Final = 1916 +RPC_X_PIPE_DISCIPLINE_ERROR: Final = 1917 +RPC_X_PIPE_EMPTY: Final = 1918 +ERROR_NO_SITENAME: Final = 1919 +ERROR_CANT_ACCESS_FILE: Final = 1920 +ERROR_CANT_RESOLVE_FILENAME: Final = 1921 +RPC_S_ENTRY_TYPE_MISMATCH: Final = 1922 +RPC_S_NOT_ALL_OBJS_EXPORTED: Final = 1923 +RPC_S_INTERFACE_NOT_EXPORTED: Final = 1924 +RPC_S_PROFILE_NOT_ADDED: Final = 1925 +RPC_S_PRF_ELT_NOT_ADDED: Final = 1926 +RPC_S_PRF_ELT_NOT_REMOVED: Final = 1927 +RPC_S_GRP_ELT_NOT_ADDED: Final = 1928 +RPC_S_GRP_ELT_NOT_REMOVED: Final = 1929 +ERROR_KM_DRIVER_BLOCKED: Final = 1930 +ERROR_CONTEXT_EXPIRED: Final = 1931 +ERROR_PER_USER_TRUST_QUOTA_EXCEEDED: Final = 1932 +ERROR_ALL_USER_TRUST_QUOTA_EXCEEDED: Final = 1933 +ERROR_USER_DELETE_TRUST_QUOTA_EXCEEDED: Final = 1934 +ERROR_AUTHENTICATION_FIREWALL_FAILED: Final = 1935 +ERROR_REMOTE_PRINT_CONNECTIONS_BLOCKED: Final = 1936 +ERROR_NTLM_BLOCKED: Final = 1937 +ERROR_PASSWORD_CHANGE_REQUIRED: Final = 1938 +ERROR_LOST_MODE_LOGON_RESTRICTION: Final = 1939 +ERROR_INVALID_PIXEL_FORMAT: Final = 2000 +ERROR_BAD_DRIVER: Final = 2001 +ERROR_INVALID_WINDOW_STYLE: Final = 2002 +ERROR_METAFILE_NOT_SUPPORTED: Final = 2003 +ERROR_TRANSFORM_NOT_SUPPORTED: Final = 2004 +ERROR_CLIPPING_NOT_SUPPORTED: Final = 2005 +ERROR_INVALID_CMM: Final = 2010 +ERROR_INVALID_PROFILE: Final = 2011 +ERROR_TAG_NOT_FOUND: Final = 2012 +ERROR_TAG_NOT_PRESENT: Final = 2013 +ERROR_DUPLICATE_TAG: Final = 2014 +ERROR_PROFILE_NOT_ASSOCIATED_WITH_DEVICE: Final = 2015 +ERROR_PROFILE_NOT_FOUND: Final = 2016 +ERROR_INVALID_COLORSPACE: Final = 2017 +ERROR_ICM_NOT_ENABLED: Final = 2018 +ERROR_DELETING_ICM_XFORM: Final = 2019 +ERROR_INVALID_TRANSFORM: Final = 2020 +ERROR_COLORSPACE_MISMATCH: Final = 2021 +ERROR_INVALID_COLORINDEX: Final = 2022 +ERROR_PROFILE_DOES_NOT_MATCH_DEVICE: Final = 2023 +ERROR_CONNECTED_OTHER_PASSWORD: Final = 2108 +ERROR_CONNECTED_OTHER_PASSWORD_DEFAULT: Final = 2109 +ERROR_BAD_USERNAME: Final = 2202 +ERROR_NOT_CONNECTED: Final = 2250 +ERROR_OPEN_FILES: Final = 2401 +ERROR_ACTIVE_CONNECTIONS: Final = 2402 +ERROR_DEVICE_IN_USE: Final = 2404 +ERROR_UNKNOWN_PRINT_MONITOR: Final = 3000 +ERROR_PRINTER_DRIVER_IN_USE: Final = 3001 +ERROR_SPOOL_FILE_NOT_FOUND: Final = 3002 +ERROR_SPL_NO_STARTDOC: Final = 3003 +ERROR_SPL_NO_ADDJOB: Final = 3004 +ERROR_PRINT_PROCESSOR_ALREADY_INSTALLED: Final = 3005 +ERROR_PRINT_MONITOR_ALREADY_INSTALLED: Final = 3006 +ERROR_INVALID_PRINT_MONITOR: Final = 3007 +ERROR_PRINT_MONITOR_IN_USE: Final = 3008 +ERROR_PRINTER_HAS_JOBS_QUEUED: Final = 3009 +ERROR_SUCCESS_REBOOT_REQUIRED: Final = 3010 +ERROR_SUCCESS_RESTART_REQUIRED: Final = 3011 +ERROR_PRINTER_NOT_FOUND: Final = 3012 +ERROR_PRINTER_DRIVER_WARNED: Final = 3013 +ERROR_PRINTER_DRIVER_BLOCKED: Final = 3014 +ERROR_PRINTER_DRIVER_PACKAGE_IN_USE: Final = 3015 +ERROR_CORE_DRIVER_PACKAGE_NOT_FOUND: Final = 3016 +ERROR_FAIL_REBOOT_REQUIRED: Final = 3017 +ERROR_FAIL_REBOOT_INITIATED: Final = 3018 +ERROR_PRINTER_DRIVER_DOWNLOAD_NEEDED: Final = 3019 +ERROR_PRINT_JOB_RESTART_REQUIRED: Final = 3020 +ERROR_INVALID_PRINTER_DRIVER_MANIFEST: Final = 3021 +ERROR_PRINTER_NOT_SHAREABLE: Final = 3022 +ERROR_SERVER_SERVICE_CALL_REQUIRES_SMB1: Final = 3023 +ERROR_NETWORK_AUTHENTICATION_PROMPT_CANCELED: Final = 3024 +ERROR_REQUEST_PAUSED: Final = 3050 +ERROR_APPEXEC_CONDITION_NOT_SATISFIED: Final = 3060 +ERROR_APPEXEC_HANDLE_INVALIDATED: Final = 3061 +ERROR_APPEXEC_INVALID_HOST_GENERATION: Final = 3062 +ERROR_APPEXEC_UNEXPECTED_PROCESS_REGISTRATION: Final = 3063 +ERROR_APPEXEC_INVALID_HOST_STATE: Final = 3064 +ERROR_APPEXEC_NO_DONOR: Final = 3065 +ERROR_APPEXEC_HOST_ID_MISMATCH: Final = 3066 +ERROR_APPEXEC_UNKNOWN_USER: Final = 3067 +ERROR_APPEXEC_APP_COMPAT_BLOCK: Final = 3068 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT: Final = 3069 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_TERMINATION: Final = 3070 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_LICENSING: Final = 3071 +ERROR_APPEXEC_CALLER_WAIT_TIMEOUT_RESOURCES: Final = 3072 +ERROR_VRF_VOLATILE_CFG_AND_IO_ENABLED: Final = 3080 +ERROR_VRF_VOLATILE_NOT_STOPPABLE: Final = 3081 +ERROR_VRF_VOLATILE_SAFE_MODE: Final = 3082 +ERROR_VRF_VOLATILE_NOT_RUNNABLE_SYSTEM: Final = 3083 +ERROR_VRF_VOLATILE_NOT_SUPPORTED_RULECLASS: Final = 3084 +ERROR_VRF_VOLATILE_PROTECTED_DRIVER: Final = 3085 +ERROR_VRF_VOLATILE_NMI_REGISTERED: Final = 3086 +ERROR_VRF_VOLATILE_SETTINGS_CONFLICT: Final = 3087 +ERROR_DIF_IOCALLBACK_NOT_REPLACED: Final = 3190 +ERROR_DIF_LIVEDUMP_LIMIT_EXCEEDED: Final = 3191 +ERROR_DIF_VOLATILE_SECTION_NOT_LOCKED: Final = 3192 +ERROR_DIF_VOLATILE_DRIVER_HOTPATCHED: Final = 3193 +ERROR_DIF_VOLATILE_INVALID_INFO: Final = 3194 +ERROR_DIF_VOLATILE_DRIVER_IS_NOT_RUNNING: Final = 3195 +ERROR_DIF_VOLATILE_PLUGIN_IS_NOT_RUNNING: Final = 3196 +ERROR_DIF_VOLATILE_PLUGIN_CHANGE_NOT_ALLOWED: Final = 3197 +ERROR_DIF_VOLATILE_NOT_ALLOWED: Final = 3198 +ERROR_DIF_BINDING_API_NOT_FOUND: Final = 3199 +ERROR_IO_REISSUE_AS_CACHED: Final = 3950 +ERROR_WINS_INTERNAL: Final = 4000 +ERROR_CAN_NOT_DEL_LOCAL_WINS: Final = 4001 +ERROR_STATIC_INIT: Final = 4002 +ERROR_INC_BACKUP: Final = 4003 +ERROR_FULL_BACKUP: Final = 4004 +ERROR_REC_NON_EXISTENT: Final = 4005 +ERROR_RPL_NOT_ALLOWED: Final = 4006 +PEERDIST_ERROR_CONTENTINFO_VERSION_UNSUPPORTED: Final = 4050 +PEERDIST_ERROR_CANNOT_PARSE_CONTENTINFO: Final = 4051 +PEERDIST_ERROR_MISSING_DATA: Final = 4052 +PEERDIST_ERROR_NO_MORE: Final = 4053 +PEERDIST_ERROR_NOT_INITIALIZED: Final = 4054 +PEERDIST_ERROR_ALREADY_INITIALIZED: Final = 4055 +PEERDIST_ERROR_SHUTDOWN_IN_PROGRESS: Final = 4056 +PEERDIST_ERROR_INVALIDATED: Final = 4057 +PEERDIST_ERROR_ALREADY_EXISTS: Final = 4058 +PEERDIST_ERROR_OPERATION_NOTFOUND: Final = 4059 +PEERDIST_ERROR_ALREADY_COMPLETED: Final = 4060 +PEERDIST_ERROR_OUT_OF_BOUNDS: Final = 4061 +PEERDIST_ERROR_VERSION_UNSUPPORTED: Final = 4062 +PEERDIST_ERROR_INVALID_CONFIGURATION: Final = 4063 +PEERDIST_ERROR_NOT_LICENSED: Final = 4064 +PEERDIST_ERROR_SERVICE_UNAVAILABLE: Final = 4065 +PEERDIST_ERROR_TRUST_FAILURE: Final = 4066 +ERROR_DHCP_ADDRESS_CONFLICT: Final = 4100 +ERROR_WMI_GUID_NOT_FOUND: Final = 4200 +ERROR_WMI_INSTANCE_NOT_FOUND: Final = 4201 +ERROR_WMI_ITEMID_NOT_FOUND: Final = 4202 +ERROR_WMI_TRY_AGAIN: Final = 4203 +ERROR_WMI_DP_NOT_FOUND: Final = 4204 +ERROR_WMI_UNRESOLVED_INSTANCE_REF: Final = 4205 +ERROR_WMI_ALREADY_ENABLED: Final = 4206 +ERROR_WMI_GUID_DISCONNECTED: Final = 4207 +ERROR_WMI_SERVER_UNAVAILABLE: Final = 4208 +ERROR_WMI_DP_FAILED: Final = 4209 +ERROR_WMI_INVALID_MOF: Final = 4210 +ERROR_WMI_INVALID_REGINFO: Final = 4211 +ERROR_WMI_ALREADY_DISABLED: Final = 4212 +ERROR_WMI_READ_ONLY: Final = 4213 +ERROR_WMI_SET_FAILURE: Final = 4214 +ERROR_NOT_APPCONTAINER: Final = 4250 +ERROR_APPCONTAINER_REQUIRED: Final = 4251 +ERROR_NOT_SUPPORTED_IN_APPCONTAINER: Final = 4252 +ERROR_INVALID_PACKAGE_SID_LENGTH: Final = 4253 +ERROR_INVALID_MEDIA: Final = 4300 +ERROR_INVALID_LIBRARY: Final = 4301 +ERROR_INVALID_MEDIA_POOL: Final = 4302 +ERROR_DRIVE_MEDIA_MISMATCH: Final = 4303 +ERROR_MEDIA_OFFLINE: Final = 4304 +ERROR_LIBRARY_OFFLINE: Final = 4305 +ERROR_EMPTY: Final = 4306 +ERROR_NOT_EMPTY: Final = 4307 +ERROR_MEDIA_UNAVAILABLE: Final = 4308 +ERROR_RESOURCE_DISABLED: Final = 4309 +ERROR_INVALID_CLEANER: Final = 4310 +ERROR_UNABLE_TO_CLEAN: Final = 4311 +ERROR_OBJECT_NOT_FOUND: Final = 4312 +ERROR_DATABASE_FAILURE: Final = 4313 +ERROR_DATABASE_FULL: Final = 4314 +ERROR_MEDIA_INCOMPATIBLE: Final = 4315 +ERROR_RESOURCE_NOT_PRESENT: Final = 4316 +ERROR_INVALID_OPERATION: Final = 4317 +ERROR_MEDIA_NOT_AVAILABLE: Final = 4318 +ERROR_DEVICE_NOT_AVAILABLE: Final = 4319 +ERROR_REQUEST_REFUSED: Final = 4320 +ERROR_INVALID_DRIVE_OBJECT: Final = 4321 +ERROR_LIBRARY_FULL: Final = 4322 +ERROR_MEDIUM_NOT_ACCESSIBLE: Final = 4323 +ERROR_UNABLE_TO_LOAD_MEDIUM: Final = 4324 +ERROR_UNABLE_TO_INVENTORY_DRIVE: Final = 4325 +ERROR_UNABLE_TO_INVENTORY_SLOT: Final = 4326 +ERROR_UNABLE_TO_INVENTORY_TRANSPORT: Final = 4327 +ERROR_TRANSPORT_FULL: Final = 4328 +ERROR_CONTROLLING_IEPORT: Final = 4329 +ERROR_UNABLE_TO_EJECT_MOUNTED_MEDIA: Final = 4330 +ERROR_CLEANER_SLOT_SET: Final = 4331 +ERROR_CLEANER_SLOT_NOT_SET: Final = 4332 +ERROR_CLEANER_CARTRIDGE_SPENT: Final = 4333 +ERROR_UNEXPECTED_OMID: Final = 4334 +ERROR_CANT_DELETE_LAST_ITEM: Final = 4335 +ERROR_MESSAGE_EXCEEDS_MAX_SIZE: Final = 4336 +ERROR_VOLUME_CONTAINS_SYS_FILES: Final = 4337 +ERROR_INDIGENOUS_TYPE: Final = 4338 +ERROR_NO_SUPPORTING_DRIVES: Final = 4339 +ERROR_CLEANER_CARTRIDGE_INSTALLED: Final = 4340 +ERROR_IEPORT_FULL: Final = 4341 +ERROR_FILE_OFFLINE: Final = 4350 +ERROR_REMOTE_STORAGE_NOT_ACTIVE: Final = 4351 +ERROR_REMOTE_STORAGE_MEDIA_ERROR: Final = 4352 +ERROR_NOT_A_REPARSE_POINT: Final = 4390 +ERROR_REPARSE_ATTRIBUTE_CONFLICT: Final = 4391 +ERROR_INVALID_REPARSE_DATA: Final = 4392 +ERROR_REPARSE_TAG_INVALID: Final = 4393 +ERROR_REPARSE_TAG_MISMATCH: Final = 4394 +ERROR_REPARSE_POINT_ENCOUNTERED: Final = 4395 +ERROR_APP_DATA_NOT_FOUND: Final = 4400 +ERROR_APP_DATA_EXPIRED: Final = 4401 +ERROR_APP_DATA_CORRUPT: Final = 4402 +ERROR_APP_DATA_LIMIT_EXCEEDED: Final = 4403 +ERROR_APP_DATA_REBOOT_REQUIRED: Final = 4404 +ERROR_SECUREBOOT_ROLLBACK_DETECTED: Final = 4420 +ERROR_SECUREBOOT_POLICY_VIOLATION: Final = 4421 +ERROR_SECUREBOOT_INVALID_POLICY: Final = 4422 +ERROR_SECUREBOOT_POLICY_PUBLISHER_NOT_FOUND: Final = 4423 +ERROR_SECUREBOOT_POLICY_NOT_SIGNED: Final = 4424 +ERROR_SECUREBOOT_NOT_ENABLED: Final = 4425 +ERROR_SECUREBOOT_FILE_REPLACED: Final = 4426 +ERROR_SECUREBOOT_POLICY_NOT_AUTHORIZED: Final = 4427 +ERROR_SECUREBOOT_POLICY_UNKNOWN: Final = 4428 +ERROR_SECUREBOOT_POLICY_MISSING_ANTIROLLBACKVERSION: Final = 4429 +ERROR_SECUREBOOT_PLATFORM_ID_MISMATCH: Final = 4430 +ERROR_SECUREBOOT_POLICY_ROLLBACK_DETECTED: Final = 4431 +ERROR_SECUREBOOT_POLICY_UPGRADE_MISMATCH: Final = 4432 +ERROR_SECUREBOOT_REQUIRED_POLICY_FILE_MISSING: Final = 4433 +ERROR_SECUREBOOT_NOT_BASE_POLICY: Final = 4434 +ERROR_SECUREBOOT_NOT_SUPPLEMENTAL_POLICY: Final = 4435 +ERROR_OFFLOAD_READ_FLT_NOT_SUPPORTED: Final = 4440 +ERROR_OFFLOAD_WRITE_FLT_NOT_SUPPORTED: Final = 4441 +ERROR_OFFLOAD_READ_FILE_NOT_SUPPORTED: Final = 4442 +ERROR_OFFLOAD_WRITE_FILE_NOT_SUPPORTED: Final = 4443 +ERROR_ALREADY_HAS_STREAM_ID: Final = 4444 +ERROR_SMR_GARBAGE_COLLECTION_REQUIRED: Final = 4445 +ERROR_WOF_WIM_HEADER_CORRUPT: Final = 4446 +ERROR_WOF_WIM_RESOURCE_TABLE_CORRUPT: Final = 4447 +ERROR_WOF_FILE_RESOURCE_TABLE_CORRUPT: Final = 4448 +ERROR_OBJECT_IS_IMMUTABLE: Final = 4449 +ERROR_VOLUME_NOT_SIS_ENABLED: Final = 4500 +ERROR_SYSTEM_INTEGRITY_ROLLBACK_DETECTED: Final = 4550 +ERROR_SYSTEM_INTEGRITY_POLICY_VIOLATION: Final = 4551 +ERROR_SYSTEM_INTEGRITY_INVALID_POLICY: Final = 4552 +ERROR_SYSTEM_INTEGRITY_POLICY_NOT_SIGNED: Final = 4553 +ERROR_SYSTEM_INTEGRITY_TOO_MANY_POLICIES: Final = 4554 +ERROR_SYSTEM_INTEGRITY_SUPPLEMENTAL_POLICY_NOT_AUTHORIZED: Final = 4555 +ERROR_SYSTEM_INTEGRITY_REPUTATION_MALICIOUS: Final = 4556 +ERROR_SYSTEM_INTEGRITY_REPUTATION_PUA: Final = 4557 +ERROR_SYSTEM_INTEGRITY_REPUTATION_DANGEROUS_EXT: Final = 4558 +ERROR_SYSTEM_INTEGRITY_REPUTATION_OFFLINE: Final = 4559 +ERROR_VSM_NOT_INITIALIZED: Final = 4560 +ERROR_VSM_DMA_PROTECTION_NOT_IN_USE: Final = 4561 +ERROR_PLATFORM_MANIFEST_NOT_AUTHORIZED: Final = 4570 +ERROR_PLATFORM_MANIFEST_INVALID: Final = 4571 +ERROR_PLATFORM_MANIFEST_FILE_NOT_AUTHORIZED: Final = 4572 +ERROR_PLATFORM_MANIFEST_CATALOG_NOT_AUTHORIZED: Final = 4573 +ERROR_PLATFORM_MANIFEST_BINARY_ID_NOT_FOUND: Final = 4574 +ERROR_PLATFORM_MANIFEST_NOT_ACTIVE: Final = 4575 +ERROR_PLATFORM_MANIFEST_NOT_SIGNED: Final = 4576 +ERROR_SYSTEM_INTEGRITY_REPUTATION_UNFRIENDLY_FILE: Final = 4580 +ERROR_SYSTEM_INTEGRITY_REPUTATION_UNATTAINABLE: Final = 4581 +ERROR_SYSTEM_INTEGRITY_REPUTATION_EXPLICIT_DENY_FILE: Final = 4582 +ERROR_DEPENDENT_RESOURCE_EXISTS: Final = 5001 +ERROR_DEPENDENCY_NOT_FOUND: Final = 5002 +ERROR_DEPENDENCY_ALREADY_EXISTS: Final = 5003 +ERROR_RESOURCE_NOT_ONLINE: Final = 5004 +ERROR_HOST_NODE_NOT_AVAILABLE: Final = 5005 +ERROR_RESOURCE_NOT_AVAILABLE: Final = 5006 +ERROR_RESOURCE_NOT_FOUND: Final = 5007 +ERROR_SHUTDOWN_CLUSTER: Final = 5008 +ERROR_CANT_EVICT_ACTIVE_NODE: Final = 5009 +ERROR_OBJECT_ALREADY_EXISTS: Final = 5010 +ERROR_OBJECT_IN_LIST: Final = 5011 +ERROR_GROUP_NOT_AVAILABLE: Final = 5012 +ERROR_GROUP_NOT_FOUND: Final = 5013 +ERROR_GROUP_NOT_ONLINE: Final = 5014 +ERROR_HOST_NODE_NOT_RESOURCE_OWNER: Final = 5015 +ERROR_HOST_NODE_NOT_GROUP_OWNER: Final = 5016 +ERROR_RESMON_CREATE_FAILED: Final = 5017 +ERROR_RESMON_ONLINE_FAILED: Final = 5018 +ERROR_RESOURCE_ONLINE: Final = 5019 +ERROR_QUORUM_RESOURCE: Final = 5020 +ERROR_NOT_QUORUM_CAPABLE: Final = 5021 +ERROR_CLUSTER_SHUTTING_DOWN: Final = 5022 +ERROR_INVALID_STATE: Final = 5023 +ERROR_RESOURCE_PROPERTIES_STORED: Final = 5024 +ERROR_NOT_QUORUM_CLASS: Final = 5025 +ERROR_CORE_RESOURCE: Final = 5026 +ERROR_QUORUM_RESOURCE_ONLINE_FAILED: Final = 5027 +ERROR_QUORUMLOG_OPEN_FAILED: Final = 5028 +ERROR_CLUSTERLOG_CORRUPT: Final = 5029 +ERROR_CLUSTERLOG_RECORD_EXCEEDS_MAXSIZE: Final = 5030 +ERROR_CLUSTERLOG_EXCEEDS_MAXSIZE: Final = 5031 +ERROR_CLUSTERLOG_CHKPOINT_NOT_FOUND: Final = 5032 +ERROR_CLUSTERLOG_NOT_ENOUGH_SPACE: Final = 5033 +ERROR_QUORUM_OWNER_ALIVE: Final = 5034 +ERROR_NETWORK_NOT_AVAILABLE: Final = 5035 +ERROR_NODE_NOT_AVAILABLE: Final = 5036 +ERROR_ALL_NODES_NOT_AVAILABLE: Final = 5037 +ERROR_RESOURCE_FAILED: Final = 5038 +ERROR_CLUSTER_INVALID_NODE: Final = 5039 +ERROR_CLUSTER_NODE_EXISTS: Final = 5040 +ERROR_CLUSTER_JOIN_IN_PROGRESS: Final = 5041 +ERROR_CLUSTER_NODE_NOT_FOUND: Final = 5042 +ERROR_CLUSTER_LOCAL_NODE_NOT_FOUND: Final = 5043 +ERROR_CLUSTER_NETWORK_EXISTS: Final = 5044 +ERROR_CLUSTER_NETWORK_NOT_FOUND: Final = 5045 +ERROR_CLUSTER_NETINTERFACE_EXISTS: Final = 5046 +ERROR_CLUSTER_NETINTERFACE_NOT_FOUND: Final = 5047 +ERROR_CLUSTER_INVALID_REQUEST: Final = 5048 +ERROR_CLUSTER_INVALID_NETWORK_PROVIDER: Final = 5049 +ERROR_CLUSTER_NODE_DOWN: Final = 5050 +ERROR_CLUSTER_NODE_UNREACHABLE: Final = 5051 +ERROR_CLUSTER_NODE_NOT_MEMBER: Final = 5052 +ERROR_CLUSTER_JOIN_NOT_IN_PROGRESS: Final = 5053 +ERROR_CLUSTER_INVALID_NETWORK: Final = 5054 +ERROR_CLUSTER_NODE_UP: Final = 5056 +ERROR_CLUSTER_IPADDR_IN_USE: Final = 5057 +ERROR_CLUSTER_NODE_NOT_PAUSED: Final = 5058 +ERROR_CLUSTER_NO_SECURITY_CONTEXT: Final = 5059 +ERROR_CLUSTER_NETWORK_NOT_INTERNAL: Final = 5060 +ERROR_CLUSTER_NODE_ALREADY_UP: Final = 5061 +ERROR_CLUSTER_NODE_ALREADY_DOWN: Final = 5062 +ERROR_CLUSTER_NETWORK_ALREADY_ONLINE: Final = 5063 +ERROR_CLUSTER_NETWORK_ALREADY_OFFLINE: Final = 5064 +ERROR_CLUSTER_NODE_ALREADY_MEMBER: Final = 5065 +ERROR_CLUSTER_LAST_INTERNAL_NETWORK: Final = 5066 +ERROR_CLUSTER_NETWORK_HAS_DEPENDENTS: Final = 5067 +ERROR_INVALID_OPERATION_ON_QUORUM: Final = 5068 +ERROR_DEPENDENCY_NOT_ALLOWED: Final = 5069 +ERROR_CLUSTER_NODE_PAUSED: Final = 5070 +ERROR_NODE_CANT_HOST_RESOURCE: Final = 5071 +ERROR_CLUSTER_NODE_NOT_READY: Final = 5072 +ERROR_CLUSTER_NODE_SHUTTING_DOWN: Final = 5073 +ERROR_CLUSTER_JOIN_ABORTED: Final = 5074 +ERROR_CLUSTER_INCOMPATIBLE_VERSIONS: Final = 5075 +ERROR_CLUSTER_MAXNUM_OF_RESOURCES_EXCEEDED: Final = 5076 +ERROR_CLUSTER_SYSTEM_CONFIG_CHANGED: Final = 5077 +ERROR_CLUSTER_RESOURCE_TYPE_NOT_FOUND: Final = 5078 +ERROR_CLUSTER_RESTYPE_NOT_SUPPORTED: Final = 5079 +ERROR_CLUSTER_RESNAME_NOT_FOUND: Final = 5080 +ERROR_CLUSTER_NO_RPC_PACKAGES_REGISTERED: Final = 5081 +ERROR_CLUSTER_OWNER_NOT_IN_PREFLIST: Final = 5082 +ERROR_CLUSTER_DATABASE_SEQMISMATCH: Final = 5083 +ERROR_RESMON_INVALID_STATE: Final = 5084 +ERROR_CLUSTER_GUM_NOT_LOCKER: Final = 5085 +ERROR_QUORUM_DISK_NOT_FOUND: Final = 5086 +ERROR_DATABASE_BACKUP_CORRUPT: Final = 5087 +ERROR_CLUSTER_NODE_ALREADY_HAS_DFS_ROOT: Final = 5088 +ERROR_RESOURCE_PROPERTY_UNCHANGEABLE: Final = 5089 +ERROR_NO_ADMIN_ACCESS_POINT: Final = 5090 +ERROR_CLUSTER_MEMBERSHIP_INVALID_STATE: Final = 5890 +ERROR_CLUSTER_QUORUMLOG_NOT_FOUND: Final = 5891 +ERROR_CLUSTER_MEMBERSHIP_HALT: Final = 5892 +ERROR_CLUSTER_INSTANCE_ID_MISMATCH: Final = 5893 +ERROR_CLUSTER_NETWORK_NOT_FOUND_FOR_IP: Final = 5894 +ERROR_CLUSTER_PROPERTY_DATA_TYPE_MISMATCH: Final = 5895 +ERROR_CLUSTER_EVICT_WITHOUT_CLEANUP: Final = 5896 +ERROR_CLUSTER_PARAMETER_MISMATCH: Final = 5897 +ERROR_NODE_CANNOT_BE_CLUSTERED: Final = 5898 +ERROR_CLUSTER_WRONG_OS_VERSION: Final = 5899 +ERROR_CLUSTER_CANT_CREATE_DUP_CLUSTER_NAME: Final = 5900 +ERROR_CLUSCFG_ALREADY_COMMITTED: Final = 5901 +ERROR_CLUSCFG_ROLLBACK_FAILED: Final = 5902 +ERROR_CLUSCFG_SYSTEM_DISK_DRIVE_LETTER_CONFLICT: Final = 5903 +ERROR_CLUSTER_OLD_VERSION: Final = 5904 +ERROR_CLUSTER_MISMATCHED_COMPUTER_ACCT_NAME: Final = 5905 +ERROR_CLUSTER_NO_NET_ADAPTERS: Final = 5906 +ERROR_CLUSTER_POISONED: Final = 5907 +ERROR_CLUSTER_GROUP_MOVING: Final = 5908 +ERROR_CLUSTER_RESOURCE_TYPE_BUSY: Final = 5909 +ERROR_RESOURCE_CALL_TIMED_OUT: Final = 5910 +ERROR_INVALID_CLUSTER_IPV6_ADDRESS: Final = 5911 +ERROR_CLUSTER_INTERNAL_INVALID_FUNCTION: Final = 5912 +ERROR_CLUSTER_PARAMETER_OUT_OF_BOUNDS: Final = 5913 +ERROR_CLUSTER_PARTIAL_SEND: Final = 5914 +ERROR_CLUSTER_REGISTRY_INVALID_FUNCTION: Final = 5915 +ERROR_CLUSTER_INVALID_STRING_TERMINATION: Final = 5916 +ERROR_CLUSTER_INVALID_STRING_FORMAT: Final = 5917 +ERROR_CLUSTER_DATABASE_TRANSACTION_IN_PROGRESS: Final = 5918 +ERROR_CLUSTER_DATABASE_TRANSACTION_NOT_IN_PROGRESS: Final = 5919 +ERROR_CLUSTER_NULL_DATA: Final = 5920 +ERROR_CLUSTER_PARTIAL_READ: Final = 5921 +ERROR_CLUSTER_PARTIAL_WRITE: Final = 5922 +ERROR_CLUSTER_CANT_DESERIALIZE_DATA: Final = 5923 +ERROR_DEPENDENT_RESOURCE_PROPERTY_CONFLICT: Final = 5924 +ERROR_CLUSTER_NO_QUORUM: Final = 5925 +ERROR_CLUSTER_INVALID_IPV6_NETWORK: Final = 5926 +ERROR_CLUSTER_INVALID_IPV6_TUNNEL_NETWORK: Final = 5927 +ERROR_QUORUM_NOT_ALLOWED_IN_THIS_GROUP: Final = 5928 +ERROR_DEPENDENCY_TREE_TOO_COMPLEX: Final = 5929 +ERROR_EXCEPTION_IN_RESOURCE_CALL: Final = 5930 +ERROR_CLUSTER_RHS_FAILED_INITIALIZATION: Final = 5931 +ERROR_CLUSTER_NOT_INSTALLED: Final = 5932 +ERROR_CLUSTER_RESOURCES_MUST_BE_ONLINE_ON_THE_SAME_NODE: Final = 5933 +ERROR_CLUSTER_MAX_NODES_IN_CLUSTER: Final = 5934 +ERROR_CLUSTER_TOO_MANY_NODES: Final = 5935 +ERROR_CLUSTER_OBJECT_ALREADY_USED: Final = 5936 +ERROR_NONCORE_GROUPS_FOUND: Final = 5937 +ERROR_FILE_SHARE_RESOURCE_CONFLICT: Final = 5938 +ERROR_CLUSTER_EVICT_INVALID_REQUEST: Final = 5939 +ERROR_CLUSTER_SINGLETON_RESOURCE: Final = 5940 +ERROR_CLUSTER_GROUP_SINGLETON_RESOURCE: Final = 5941 +ERROR_CLUSTER_RESOURCE_PROVIDER_FAILED: Final = 5942 +ERROR_CLUSTER_RESOURCE_CONFIGURATION_ERROR: Final = 5943 +ERROR_CLUSTER_GROUP_BUSY: Final = 5944 +ERROR_CLUSTER_NOT_SHARED_VOLUME: Final = 5945 +ERROR_CLUSTER_INVALID_SECURITY_DESCRIPTOR: Final = 5946 +ERROR_CLUSTER_SHARED_VOLUMES_IN_USE: Final = 5947 +ERROR_CLUSTER_USE_SHARED_VOLUMES_API: Final = 5948 +ERROR_CLUSTER_BACKUP_IN_PROGRESS: Final = 5949 +ERROR_NON_CSV_PATH: Final = 5950 +ERROR_CSV_VOLUME_NOT_LOCAL: Final = 5951 +ERROR_CLUSTER_WATCHDOG_TERMINATING: Final = 5952 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_INCOMPATIBLE_NODES: Final = 5953 +ERROR_CLUSTER_INVALID_NODE_WEIGHT: Final = 5954 +ERROR_CLUSTER_RESOURCE_VETOED_CALL: Final = 5955 +ERROR_RESMON_SYSTEM_RESOURCES_LACKING: Final = 5956 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_DESTINATION: Final = 5957 +ERROR_CLUSTER_RESOURCE_VETOED_MOVE_NOT_ENOUGH_RESOURCES_ON_SOURCE: Final = 5958 +ERROR_CLUSTER_GROUP_QUEUED: Final = 5959 +ERROR_CLUSTER_RESOURCE_LOCKED_STATUS: Final = 5960 +ERROR_CLUSTER_SHARED_VOLUME_FAILOVER_NOT_ALLOWED: Final = 5961 +ERROR_CLUSTER_NODE_DRAIN_IN_PROGRESS: Final = 5962 +ERROR_CLUSTER_DISK_NOT_CONNECTED: Final = 5963 +ERROR_DISK_NOT_CSV_CAPABLE: Final = 5964 +ERROR_RESOURCE_NOT_IN_AVAILABLE_STORAGE: Final = 5965 +ERROR_CLUSTER_SHARED_VOLUME_REDIRECTED: Final = 5966 +ERROR_CLUSTER_SHARED_VOLUME_NOT_REDIRECTED: Final = 5967 +ERROR_CLUSTER_CANNOT_RETURN_PROPERTIES: Final = 5968 +ERROR_CLUSTER_RESOURCE_CONTAINS_UNSUPPORTED_DIFF_AREA_FOR_SHARED_VOLUMES: Final = 5969 +ERROR_CLUSTER_RESOURCE_IS_IN_MAINTENANCE_MODE: Final = 5970 +ERROR_CLUSTER_AFFINITY_CONFLICT: Final = 5971 +ERROR_CLUSTER_RESOURCE_IS_REPLICA_VIRTUAL_MACHINE: Final = 5972 +ERROR_CLUSTER_UPGRADE_INCOMPATIBLE_VERSIONS: Final = 5973 +ERROR_CLUSTER_UPGRADE_FIX_QUORUM_NOT_SUPPORTED: Final = 5974 +ERROR_CLUSTER_UPGRADE_RESTART_REQUIRED: Final = 5975 +ERROR_CLUSTER_UPGRADE_IN_PROGRESS: Final = 5976 +ERROR_CLUSTER_UPGRADE_INCOMPLETE: Final = 5977 +ERROR_CLUSTER_NODE_IN_GRACE_PERIOD: Final = 5978 +ERROR_CLUSTER_CSV_IO_PAUSE_TIMEOUT: Final = 5979 +ERROR_NODE_NOT_ACTIVE_CLUSTER_MEMBER: Final = 5980 +ERROR_CLUSTER_RESOURCE_NOT_MONITORED: Final = 5981 +ERROR_CLUSTER_RESOURCE_DOES_NOT_SUPPORT_UNMONITORED: Final = 5982 +ERROR_CLUSTER_RESOURCE_IS_REPLICATED: Final = 5983 +ERROR_CLUSTER_NODE_ISOLATED: Final = 5984 +ERROR_CLUSTER_NODE_QUARANTINED: Final = 5985 +ERROR_CLUSTER_DATABASE_UPDATE_CONDITION_FAILED: Final = 5986 +ERROR_CLUSTER_SPACE_DEGRADED: Final = 5987 +ERROR_CLUSTER_TOKEN_DELEGATION_NOT_SUPPORTED: Final = 5988 +ERROR_CLUSTER_CSV_INVALID_HANDLE: Final = 5989 +ERROR_CLUSTER_CSV_SUPPORTED_ONLY_ON_COORDINATOR: Final = 5990 +ERROR_GROUPSET_NOT_AVAILABLE: Final = 5991 +ERROR_GROUPSET_NOT_FOUND: Final = 5992 +ERROR_GROUPSET_CANT_PROVIDE: Final = 5993 +ERROR_CLUSTER_FAULT_DOMAIN_PARENT_NOT_FOUND: Final = 5994 +ERROR_CLUSTER_FAULT_DOMAIN_INVALID_HIERARCHY: Final = 5995 +ERROR_CLUSTER_FAULT_DOMAIN_FAILED_S2D_VALIDATION: Final = 5996 +ERROR_CLUSTER_FAULT_DOMAIN_S2D_CONNECTIVITY_LOSS: Final = 5997 +ERROR_CLUSTER_INVALID_INFRASTRUCTURE_FILESERVER_NAME: Final = 5998 +ERROR_CLUSTERSET_MANAGEMENT_CLUSTER_UNREACHABLE: Final = 5999 +ERROR_ENCRYPTION_FAILED: Final = 6000 +ERROR_DECRYPTION_FAILED: Final = 6001 +ERROR_FILE_ENCRYPTED: Final = 6002 +ERROR_NO_RECOVERY_POLICY: Final = 6003 +ERROR_NO_EFS: Final = 6004 +ERROR_WRONG_EFS: Final = 6005 +ERROR_NO_USER_KEYS: Final = 6006 +ERROR_FILE_NOT_ENCRYPTED: Final = 6007 +ERROR_NOT_EXPORT_FORMAT: Final = 6008 +ERROR_FILE_READ_ONLY: Final = 6009 +ERROR_DIR_EFS_DISALLOWED: Final = 6010 +ERROR_EFS_SERVER_NOT_TRUSTED: Final = 6011 +ERROR_BAD_RECOVERY_POLICY: Final = 6012 +ERROR_EFS_ALG_BLOB_TOO_BIG: Final = 6013 +ERROR_VOLUME_NOT_SUPPORT_EFS: Final = 6014 +ERROR_EFS_DISABLED: Final = 6015 +ERROR_EFS_VERSION_NOT_SUPPORT: Final = 6016 +ERROR_CS_ENCRYPTION_INVALID_SERVER_RESPONSE: Final = 6017 +ERROR_CS_ENCRYPTION_UNSUPPORTED_SERVER: Final = 6018 +ERROR_CS_ENCRYPTION_EXISTING_ENCRYPTED_FILE: Final = 6019 +ERROR_CS_ENCRYPTION_NEW_ENCRYPTED_FILE: Final = 6020 +ERROR_CS_ENCRYPTION_FILE_NOT_CSE: Final = 6021 +ERROR_ENCRYPTION_POLICY_DENIES_OPERATION: Final = 6022 +ERROR_WIP_ENCRYPTION_FAILED: Final = 6023 +ERROR_NO_BROWSER_SERVERS_FOUND: Final = 6118 +SCHED_E_SERVICE_NOT_LOCALSYSTEM: Final = 6200 +ERROR_CLUSTER_OBJECT_IS_CLUSTER_SET_VM: Final = 6250 +ERROR_LOG_SECTOR_INVALID: Final = 6600 +ERROR_LOG_SECTOR_PARITY_INVALID: Final = 6601 +ERROR_LOG_SECTOR_REMAPPED: Final = 6602 +ERROR_LOG_BLOCK_INCOMPLETE: Final = 6603 +ERROR_LOG_INVALID_RANGE: Final = 6604 +ERROR_LOG_BLOCKS_EXHAUSTED: Final = 6605 +ERROR_LOG_READ_CONTEXT_INVALID: Final = 6606 +ERROR_LOG_RESTART_INVALID: Final = 6607 +ERROR_LOG_BLOCK_VERSION: Final = 6608 +ERROR_LOG_BLOCK_INVALID: Final = 6609 +ERROR_LOG_READ_MODE_INVALID: Final = 6610 +ERROR_LOG_NO_RESTART: Final = 6611 +ERROR_LOG_METADATA_CORRUPT: Final = 6612 +ERROR_LOG_METADATA_INVALID: Final = 6613 +ERROR_LOG_METADATA_INCONSISTENT: Final = 6614 +ERROR_LOG_RESERVATION_INVALID: Final = 6615 +ERROR_LOG_CANT_DELETE: Final = 6616 +ERROR_LOG_CONTAINER_LIMIT_EXCEEDED: Final = 6617 +ERROR_LOG_START_OF_LOG: Final = 6618 +ERROR_LOG_POLICY_ALREADY_INSTALLED: Final = 6619 +ERROR_LOG_POLICY_NOT_INSTALLED: Final = 6620 +ERROR_LOG_POLICY_INVALID: Final = 6621 +ERROR_LOG_POLICY_CONFLICT: Final = 6622 +ERROR_LOG_PINNED_ARCHIVE_TAIL: Final = 6623 +ERROR_LOG_RECORD_NONEXISTENT: Final = 6624 +ERROR_LOG_RECORDS_RESERVED_INVALID: Final = 6625 +ERROR_LOG_SPACE_RESERVED_INVALID: Final = 6626 +ERROR_LOG_TAIL_INVALID: Final = 6627 +ERROR_LOG_FULL: Final = 6628 +ERROR_COULD_NOT_RESIZE_LOG: Final = 6629 +ERROR_LOG_MULTIPLEXED: Final = 6630 +ERROR_LOG_DEDICATED: Final = 6631 +ERROR_LOG_ARCHIVE_NOT_IN_PROGRESS: Final = 6632 +ERROR_LOG_ARCHIVE_IN_PROGRESS: Final = 6633 +ERROR_LOG_EPHEMERAL: Final = 6634 +ERROR_LOG_NOT_ENOUGH_CONTAINERS: Final = 6635 +ERROR_LOG_CLIENT_ALREADY_REGISTERED: Final = 6636 +ERROR_LOG_CLIENT_NOT_REGISTERED: Final = 6637 +ERROR_LOG_FULL_HANDLER_IN_PROGRESS: Final = 6638 +ERROR_LOG_CONTAINER_READ_FAILED: Final = 6639 +ERROR_LOG_CONTAINER_WRITE_FAILED: Final = 6640 +ERROR_LOG_CONTAINER_OPEN_FAILED: Final = 6641 +ERROR_LOG_CONTAINER_STATE_INVALID: Final = 6642 +ERROR_LOG_STATE_INVALID: Final = 6643 +ERROR_LOG_PINNED: Final = 6644 +ERROR_LOG_METADATA_FLUSH_FAILED: Final = 6645 +ERROR_LOG_INCONSISTENT_SECURITY: Final = 6646 +ERROR_LOG_APPENDED_FLUSH_FAILED: Final = 6647 +ERROR_LOG_PINNED_RESERVATION: Final = 6648 +ERROR_INVALID_TRANSACTION: Final = 6700 +ERROR_TRANSACTION_NOT_ACTIVE: Final = 6701 +ERROR_TRANSACTION_REQUEST_NOT_VALID: Final = 6702 +ERROR_TRANSACTION_NOT_REQUESTED: Final = 6703 +ERROR_TRANSACTION_ALREADY_ABORTED: Final = 6704 +ERROR_TRANSACTION_ALREADY_COMMITTED: Final = 6705 +ERROR_TM_INITIALIZATION_FAILED: Final = 6706 +ERROR_RESOURCEMANAGER_READ_ONLY: Final = 6707 +ERROR_TRANSACTION_NOT_JOINED: Final = 6708 +ERROR_TRANSACTION_SUPERIOR_EXISTS: Final = 6709 +ERROR_CRM_PROTOCOL_ALREADY_EXISTS: Final = 6710 +ERROR_TRANSACTION_PROPAGATION_FAILED: Final = 6711 +ERROR_CRM_PROTOCOL_NOT_FOUND: Final = 6712 +ERROR_TRANSACTION_INVALID_MARSHALL_BUFFER: Final = 6713 +ERROR_CURRENT_TRANSACTION_NOT_VALID: Final = 6714 +ERROR_TRANSACTION_NOT_FOUND: Final = 6715 +ERROR_RESOURCEMANAGER_NOT_FOUND: Final = 6716 +ERROR_ENLISTMENT_NOT_FOUND: Final = 6717 +ERROR_TRANSACTIONMANAGER_NOT_FOUND: Final = 6718 +ERROR_TRANSACTIONMANAGER_NOT_ONLINE: Final = 6719 +ERROR_TRANSACTIONMANAGER_RECOVERY_NAME_COLLISION: Final = 6720 +ERROR_TRANSACTION_NOT_ROOT: Final = 6721 +ERROR_TRANSACTION_OBJECT_EXPIRED: Final = 6722 +ERROR_TRANSACTION_RESPONSE_NOT_ENLISTED: Final = 6723 +ERROR_TRANSACTION_RECORD_TOO_LONG: Final = 6724 +ERROR_IMPLICIT_TRANSACTION_NOT_SUPPORTED: Final = 6725 +ERROR_TRANSACTION_INTEGRITY_VIOLATED: Final = 6726 +ERROR_TRANSACTIONMANAGER_IDENTITY_MISMATCH: Final = 6727 +ERROR_RM_CANNOT_BE_FROZEN_FOR_SNAPSHOT: Final = 6728 +ERROR_TRANSACTION_MUST_WRITETHROUGH: Final = 6729 +ERROR_TRANSACTION_NO_SUPERIOR: Final = 6730 +ERROR_HEURISTIC_DAMAGE_POSSIBLE: Final = 6731 +ERROR_TRANSACTIONAL_CONFLICT: Final = 6800 +ERROR_RM_NOT_ACTIVE: Final = 6801 +ERROR_RM_METADATA_CORRUPT: Final = 6802 +ERROR_DIRECTORY_NOT_RM: Final = 6803 +ERROR_TRANSACTIONS_UNSUPPORTED_REMOTE: Final = 6805 +ERROR_LOG_RESIZE_INVALID_SIZE: Final = 6806 +ERROR_OBJECT_NO_LONGER_EXISTS: Final = 6807 +ERROR_STREAM_MINIVERSION_NOT_FOUND: Final = 6808 +ERROR_STREAM_MINIVERSION_NOT_VALID: Final = 6809 +ERROR_MINIVERSION_INACCESSIBLE_FROM_SPECIFIED_TRANSACTION: Final = 6810 +ERROR_CANT_OPEN_MINIVERSION_WITH_MODIFY_INTENT: Final = 6811 +ERROR_CANT_CREATE_MORE_STREAM_MINIVERSIONS: Final = 6812 +ERROR_REMOTE_FILE_VERSION_MISMATCH: Final = 6814 +ERROR_HANDLE_NO_LONGER_VALID: Final = 6815 +ERROR_NO_TXF_METADATA: Final = 6816 +ERROR_LOG_CORRUPTION_DETECTED: Final = 6817 +ERROR_CANT_RECOVER_WITH_HANDLE_OPEN: Final = 6818 +ERROR_RM_DISCONNECTED: Final = 6819 +ERROR_ENLISTMENT_NOT_SUPERIOR: Final = 6820 +ERROR_RECOVERY_NOT_NEEDED: Final = 6821 +ERROR_RM_ALREADY_STARTED: Final = 6822 +ERROR_FILE_IDENTITY_NOT_PERSISTENT: Final = 6823 +ERROR_CANT_BREAK_TRANSACTIONAL_DEPENDENCY: Final = 6824 +ERROR_CANT_CROSS_RM_BOUNDARY: Final = 6825 +ERROR_TXF_DIR_NOT_EMPTY: Final = 6826 +ERROR_INDOUBT_TRANSACTIONS_EXIST: Final = 6827 +ERROR_TM_VOLATILE: Final = 6828 +ERROR_ROLLBACK_TIMER_EXPIRED: Final = 6829 +ERROR_TXF_ATTRIBUTE_CORRUPT: Final = 6830 +ERROR_EFS_NOT_ALLOWED_IN_TRANSACTION: Final = 6831 +ERROR_TRANSACTIONAL_OPEN_NOT_ALLOWED: Final = 6832 +ERROR_LOG_GROWTH_FAILED: Final = 6833 +ERROR_TRANSACTED_MAPPING_UNSUPPORTED_REMOTE: Final = 6834 +ERROR_TXF_METADATA_ALREADY_PRESENT: Final = 6835 +ERROR_TRANSACTION_SCOPE_CALLBACKS_NOT_SET: Final = 6836 +ERROR_TRANSACTION_REQUIRED_PROMOTION: Final = 6837 +ERROR_CANNOT_EXECUTE_FILE_IN_TRANSACTION: Final = 6838 +ERROR_TRANSACTIONS_NOT_FROZEN: Final = 6839 +ERROR_TRANSACTION_FREEZE_IN_PROGRESS: Final = 6840 +ERROR_NOT_SNAPSHOT_VOLUME: Final = 6841 +ERROR_NO_SAVEPOINT_WITH_OPEN_FILES: Final = 6842 +ERROR_DATA_LOST_REPAIR: Final = 6843 +ERROR_SPARSE_NOT_ALLOWED_IN_TRANSACTION: Final = 6844 +ERROR_TM_IDENTITY_MISMATCH: Final = 6845 +ERROR_FLOATED_SECTION: Final = 6846 +ERROR_CANNOT_ACCEPT_TRANSACTED_WORK: Final = 6847 +ERROR_CANNOT_ABORT_TRANSACTIONS: Final = 6848 +ERROR_BAD_CLUSTERS: Final = 6849 +ERROR_COMPRESSION_NOT_ALLOWED_IN_TRANSACTION: Final = 6850 +ERROR_VOLUME_DIRTY: Final = 6851 +ERROR_NO_LINK_TRACKING_IN_TRANSACTION: Final = 6852 +ERROR_OPERATION_NOT_SUPPORTED_IN_TRANSACTION: Final = 6853 +ERROR_EXPIRED_HANDLE: Final = 6854 +ERROR_TRANSACTION_NOT_ENLISTED: Final = 6855 +ERROR_CTX_WINSTATION_NAME_INVALID: Final = 7001 +ERROR_CTX_INVALID_PD: Final = 7002 +ERROR_CTX_PD_NOT_FOUND: Final = 7003 +ERROR_CTX_WD_NOT_FOUND: Final = 7004 +ERROR_CTX_CANNOT_MAKE_EVENTLOG_ENTRY: Final = 7005 +ERROR_CTX_SERVICE_NAME_COLLISION: Final = 7006 +ERROR_CTX_CLOSE_PENDING: Final = 7007 +ERROR_CTX_NO_OUTBUF: Final = 7008 +ERROR_CTX_MODEM_INF_NOT_FOUND: Final = 7009 +ERROR_CTX_INVALID_MODEMNAME: Final = 7010 +ERROR_CTX_MODEM_RESPONSE_ERROR: Final = 7011 +ERROR_CTX_MODEM_RESPONSE_TIMEOUT: Final = 7012 +ERROR_CTX_MODEM_RESPONSE_NO_CARRIER: Final = 7013 +ERROR_CTX_MODEM_RESPONSE_NO_DIALTONE: Final = 7014 +ERROR_CTX_MODEM_RESPONSE_BUSY: Final = 7015 +ERROR_CTX_MODEM_RESPONSE_VOICE: Final = 7016 +ERROR_CTX_TD_ERROR: Final = 7017 +ERROR_CTX_WINSTATION_NOT_FOUND: Final = 7022 +ERROR_CTX_WINSTATION_ALREADY_EXISTS: Final = 7023 +ERROR_CTX_WINSTATION_BUSY: Final = 7024 +ERROR_CTX_BAD_VIDEO_MODE: Final = 7025 +ERROR_CTX_GRAPHICS_INVALID: Final = 7035 +ERROR_CTX_LOGON_DISABLED: Final = 7037 +ERROR_CTX_NOT_CONSOLE: Final = 7038 +ERROR_CTX_CLIENT_QUERY_TIMEOUT: Final = 7040 +ERROR_CTX_CONSOLE_DISCONNECT: Final = 7041 +ERROR_CTX_CONSOLE_CONNECT: Final = 7042 +ERROR_CTX_SHADOW_DENIED: Final = 7044 +ERROR_CTX_WINSTATION_ACCESS_DENIED: Final = 7045 +ERROR_CTX_INVALID_WD: Final = 7049 +ERROR_CTX_SHADOW_INVALID: Final = 7050 +ERROR_CTX_SHADOW_DISABLED: Final = 7051 +ERROR_CTX_CLIENT_LICENSE_IN_USE: Final = 7052 +ERROR_CTX_CLIENT_LICENSE_NOT_SET: Final = 7053 +ERROR_CTX_LICENSE_NOT_AVAILABLE: Final = 7054 +ERROR_CTX_LICENSE_CLIENT_INVALID: Final = 7055 +ERROR_CTX_LICENSE_EXPIRED: Final = 7056 +ERROR_CTX_SHADOW_NOT_RUNNING: Final = 7057 +ERROR_CTX_SHADOW_ENDED_BY_MODE_CHANGE: Final = 7058 +ERROR_ACTIVATION_COUNT_EXCEEDED: Final = 7059 +ERROR_CTX_WINSTATIONS_DISABLED: Final = 7060 +ERROR_CTX_ENCRYPTION_LEVEL_REQUIRED: Final = 7061 +ERROR_CTX_SESSION_IN_USE: Final = 7062 +ERROR_CTX_NO_FORCE_LOGOFF: Final = 7063 +ERROR_CTX_ACCOUNT_RESTRICTION: Final = 7064 +ERROR_RDP_PROTOCOL_ERROR: Final = 7065 +ERROR_CTX_CDM_CONNECT: Final = 7066 +ERROR_CTX_CDM_DISCONNECT: Final = 7067 +ERROR_CTX_SECURITY_LAYER_ERROR: Final = 7068 +ERROR_TS_INCOMPATIBLE_SESSIONS: Final = 7069 +ERROR_TS_VIDEO_SUBSYSTEM_ERROR: Final = 7070 +FRS_ERR_INVALID_API_SEQUENCE: Final = 8001 +FRS_ERR_STARTING_SERVICE: Final = 8002 +FRS_ERR_STOPPING_SERVICE: Final = 8003 +FRS_ERR_INTERNAL_API: Final = 8004 +FRS_ERR_INTERNAL: Final = 8005 +FRS_ERR_SERVICE_COMM: Final = 8006 +FRS_ERR_INSUFFICIENT_PRIV: Final = 8007 +FRS_ERR_AUTHENTICATION: Final = 8008 +FRS_ERR_PARENT_INSUFFICIENT_PRIV: Final = 8009 +FRS_ERR_PARENT_AUTHENTICATION: Final = 8010 +FRS_ERR_CHILD_TO_PARENT_COMM: Final = 8011 +FRS_ERR_PARENT_TO_CHILD_COMM: Final = 8012 +FRS_ERR_SYSVOL_POPULATE: Final = 8013 +FRS_ERR_SYSVOL_POPULATE_TIMEOUT: Final = 8014 +FRS_ERR_SYSVOL_IS_BUSY: Final = 8015 +FRS_ERR_SYSVOL_DEMOTE: Final = 8016 +FRS_ERR_INVALID_SERVICE_PARAMETER: Final = 8017 +DS_S_SUCCESS: Final = NO_ERROR +ERROR_DS_NOT_INSTALLED: Final = 8200 +ERROR_DS_MEMBERSHIP_EVALUATED_LOCALLY: Final = 8201 +ERROR_DS_NO_ATTRIBUTE_OR_VALUE: Final = 8202 +ERROR_DS_INVALID_ATTRIBUTE_SYNTAX: Final = 8203 +ERROR_DS_ATTRIBUTE_TYPE_UNDEFINED: Final = 8204 +ERROR_DS_ATTRIBUTE_OR_VALUE_EXISTS: Final = 8205 +ERROR_DS_BUSY: Final = 8206 +ERROR_DS_UNAVAILABLE: Final = 8207 +ERROR_DS_NO_RIDS_ALLOCATED: Final = 8208 +ERROR_DS_NO_MORE_RIDS: Final = 8209 +ERROR_DS_INCORRECT_ROLE_OWNER: Final = 8210 +ERROR_DS_RIDMGR_INIT_ERROR: Final = 8211 +ERROR_DS_OBJ_CLASS_VIOLATION: Final = 8212 +ERROR_DS_CANT_ON_NON_LEAF: Final = 8213 +ERROR_DS_CANT_ON_RDN: Final = 8214 +ERROR_DS_CANT_MOD_OBJ_CLASS: Final = 8215 +ERROR_DS_CROSS_DOM_MOVE_ERROR: Final = 8216 +ERROR_DS_GC_NOT_AVAILABLE: Final = 8217 +ERROR_SHARED_POLICY: Final = 8218 +ERROR_POLICY_OBJECT_NOT_FOUND: Final = 8219 +ERROR_POLICY_ONLY_IN_DS: Final = 8220 +ERROR_PROMOTION_ACTIVE: Final = 8221 +ERROR_NO_PROMOTION_ACTIVE: Final = 8222 +ERROR_DS_OPERATIONS_ERROR: Final = 8224 +ERROR_DS_PROTOCOL_ERROR: Final = 8225 +ERROR_DS_TIMELIMIT_EXCEEDED: Final = 8226 +ERROR_DS_SIZELIMIT_EXCEEDED: Final = 8227 +ERROR_DS_ADMIN_LIMIT_EXCEEDED: Final = 8228 +ERROR_DS_COMPARE_FALSE: Final = 8229 +ERROR_DS_COMPARE_TRUE: Final = 8230 +ERROR_DS_AUTH_METHOD_NOT_SUPPORTED: Final = 8231 +ERROR_DS_STRONG_AUTH_REQUIRED: Final = 8232 +ERROR_DS_INAPPROPRIATE_AUTH: Final = 8233 +ERROR_DS_AUTH_UNKNOWN: Final = 8234 +ERROR_DS_REFERRAL: Final = 8235 +ERROR_DS_UNAVAILABLE_CRIT_EXTENSION: Final = 8236 +ERROR_DS_CONFIDENTIALITY_REQUIRED: Final = 8237 +ERROR_DS_INAPPROPRIATE_MATCHING: Final = 8238 +ERROR_DS_CONSTRAINT_VIOLATION: Final = 8239 +ERROR_DS_NO_SUCH_OBJECT: Final = 8240 +ERROR_DS_ALIAS_PROBLEM: Final = 8241 +ERROR_DS_INVALID_DN_SYNTAX: Final = 8242 +ERROR_DS_IS_LEAF: Final = 8243 +ERROR_DS_ALIAS_DEREF_PROBLEM: Final = 8244 +ERROR_DS_UNWILLING_TO_PERFORM: Final = 8245 +ERROR_DS_LOOP_DETECT: Final = 8246 +ERROR_DS_NAMING_VIOLATION: Final = 8247 +ERROR_DS_OBJECT_RESULTS_TOO_LARGE: Final = 8248 +ERROR_DS_AFFECTS_MULTIPLE_DSAS: Final = 8249 +ERROR_DS_SERVER_DOWN: Final = 8250 +ERROR_DS_LOCAL_ERROR: Final = 8251 +ERROR_DS_ENCODING_ERROR: Final = 8252 +ERROR_DS_DECODING_ERROR: Final = 8253 +ERROR_DS_FILTER_UNKNOWN: Final = 8254 +ERROR_DS_PARAM_ERROR: Final = 8255 +ERROR_DS_NOT_SUPPORTED: Final = 8256 +ERROR_DS_NO_RESULTS_RETURNED: Final = 8257 +ERROR_DS_CONTROL_NOT_FOUND: Final = 8258 +ERROR_DS_CLIENT_LOOP: Final = 8259 +ERROR_DS_REFERRAL_LIMIT_EXCEEDED: Final = 8260 +ERROR_DS_SORT_CONTROL_MISSING: Final = 8261 +ERROR_DS_OFFSET_RANGE_ERROR: Final = 8262 +ERROR_DS_RIDMGR_DISABLED: Final = 8263 +ERROR_DS_ROOT_MUST_BE_NC: Final = 8301 +ERROR_DS_ADD_REPLICA_INHIBITED: Final = 8302 +ERROR_DS_ATT_NOT_DEF_IN_SCHEMA: Final = 8303 +ERROR_DS_MAX_OBJ_SIZE_EXCEEDED: Final = 8304 +ERROR_DS_OBJ_STRING_NAME_EXISTS: Final = 8305 +ERROR_DS_NO_RDN_DEFINED_IN_SCHEMA: Final = 8306 +ERROR_DS_RDN_DOESNT_MATCH_SCHEMA: Final = 8307 +ERROR_DS_NO_REQUESTED_ATTS_FOUND: Final = 8308 +ERROR_DS_USER_BUFFER_TO_SMALL: Final = 8309 +ERROR_DS_ATT_IS_NOT_ON_OBJ: Final = 8310 +ERROR_DS_ILLEGAL_MOD_OPERATION: Final = 8311 +ERROR_DS_OBJ_TOO_LARGE: Final = 8312 +ERROR_DS_BAD_INSTANCE_TYPE: Final = 8313 +ERROR_DS_MASTERDSA_REQUIRED: Final = 8314 +ERROR_DS_OBJECT_CLASS_REQUIRED: Final = 8315 +ERROR_DS_MISSING_REQUIRED_ATT: Final = 8316 +ERROR_DS_ATT_NOT_DEF_FOR_CLASS: Final = 8317 +ERROR_DS_ATT_ALREADY_EXISTS: Final = 8318 +ERROR_DS_CANT_ADD_ATT_VALUES: Final = 8320 +ERROR_DS_SINGLE_VALUE_CONSTRAINT: Final = 8321 +ERROR_DS_RANGE_CONSTRAINT: Final = 8322 +ERROR_DS_ATT_VAL_ALREADY_EXISTS: Final = 8323 +ERROR_DS_CANT_REM_MISSING_ATT: Final = 8324 +ERROR_DS_CANT_REM_MISSING_ATT_VAL: Final = 8325 +ERROR_DS_ROOT_CANT_BE_SUBREF: Final = 8326 +ERROR_DS_NO_CHAINING: Final = 8327 +ERROR_DS_NO_CHAINED_EVAL: Final = 8328 +ERROR_DS_NO_PARENT_OBJECT: Final = 8329 +ERROR_DS_PARENT_IS_AN_ALIAS: Final = 8330 +ERROR_DS_CANT_MIX_MASTER_AND_REPS: Final = 8331 +ERROR_DS_CHILDREN_EXIST: Final = 8332 +ERROR_DS_OBJ_NOT_FOUND: Final = 8333 +ERROR_DS_ALIASED_OBJ_MISSING: Final = 8334 +ERROR_DS_BAD_NAME_SYNTAX: Final = 8335 +ERROR_DS_ALIAS_POINTS_TO_ALIAS: Final = 8336 +ERROR_DS_CANT_DEREF_ALIAS: Final = 8337 +ERROR_DS_OUT_OF_SCOPE: Final = 8338 +ERROR_DS_OBJECT_BEING_REMOVED: Final = 8339 +ERROR_DS_CANT_DELETE_DSA_OBJ: Final = 8340 +ERROR_DS_GENERIC_ERROR: Final = 8341 +ERROR_DS_DSA_MUST_BE_INT_MASTER: Final = 8342 +ERROR_DS_CLASS_NOT_DSA: Final = 8343 +ERROR_DS_INSUFF_ACCESS_RIGHTS: Final = 8344 +ERROR_DS_ILLEGAL_SUPERIOR: Final = 8345 +ERROR_DS_ATTRIBUTE_OWNED_BY_SAM: Final = 8346 +ERROR_DS_NAME_TOO_MANY_PARTS: Final = 8347 +ERROR_DS_NAME_TOO_LONG: Final = 8348 +ERROR_DS_NAME_VALUE_TOO_LONG: Final = 8349 +ERROR_DS_NAME_UNPARSEABLE: Final = 8350 +ERROR_DS_NAME_TYPE_UNKNOWN: Final = 8351 +ERROR_DS_NOT_AN_OBJECT: Final = 8352 +ERROR_DS_SEC_DESC_TOO_SHORT: Final = 8353 +ERROR_DS_SEC_DESC_INVALID: Final = 8354 +ERROR_DS_NO_DELETED_NAME: Final = 8355 +ERROR_DS_SUBREF_MUST_HAVE_PARENT: Final = 8356 +ERROR_DS_NCNAME_MUST_BE_NC: Final = 8357 +ERROR_DS_CANT_ADD_SYSTEM_ONLY: Final = 8358 +ERROR_DS_CLASS_MUST_BE_CONCRETE: Final = 8359 +ERROR_DS_INVALID_DMD: Final = 8360 +ERROR_DS_OBJ_GUID_EXISTS: Final = 8361 +ERROR_DS_NOT_ON_BACKLINK: Final = 8362 +ERROR_DS_NO_CROSSREF_FOR_NC: Final = 8363 +ERROR_DS_SHUTTING_DOWN: Final = 8364 +ERROR_DS_UNKNOWN_OPERATION: Final = 8365 +ERROR_DS_INVALID_ROLE_OWNER: Final = 8366 +ERROR_DS_COULDNT_CONTACT_FSMO: Final = 8367 +ERROR_DS_CROSS_NC_DN_RENAME: Final = 8368 +ERROR_DS_CANT_MOD_SYSTEM_ONLY: Final = 8369 +ERROR_DS_REPLICATOR_ONLY: Final = 8370 +ERROR_DS_OBJ_CLASS_NOT_DEFINED: Final = 8371 +ERROR_DS_OBJ_CLASS_NOT_SUBCLASS: Final = 8372 +ERROR_DS_NAME_REFERENCE_INVALID: Final = 8373 +ERROR_DS_CROSS_REF_EXISTS: Final = 8374 +ERROR_DS_CANT_DEL_MASTER_CROSSREF: Final = 8375 +ERROR_DS_SUBTREE_NOTIFY_NOT_NC_HEAD: Final = 8376 +ERROR_DS_NOTIFY_FILTER_TOO_COMPLEX: Final = 8377 +ERROR_DS_DUP_RDN: Final = 8378 +ERROR_DS_DUP_OID: Final = 8379 +ERROR_DS_DUP_MAPI_ID: Final = 8380 +ERROR_DS_DUP_SCHEMA_ID_GUID: Final = 8381 +ERROR_DS_DUP_LDAP_DISPLAY_NAME: Final = 8382 +ERROR_DS_SEMANTIC_ATT_TEST: Final = 8383 +ERROR_DS_SYNTAX_MISMATCH: Final = 8384 +ERROR_DS_EXISTS_IN_MUST_HAVE: Final = 8385 +ERROR_DS_EXISTS_IN_MAY_HAVE: Final = 8386 +ERROR_DS_NONEXISTENT_MAY_HAVE: Final = 8387 +ERROR_DS_NONEXISTENT_MUST_HAVE: Final = 8388 +ERROR_DS_AUX_CLS_TEST_FAIL: Final = 8389 +ERROR_DS_NONEXISTENT_POSS_SUP: Final = 8390 +ERROR_DS_SUB_CLS_TEST_FAIL: Final = 8391 +ERROR_DS_BAD_RDN_ATT_ID_SYNTAX: Final = 8392 +ERROR_DS_EXISTS_IN_AUX_CLS: Final = 8393 +ERROR_DS_EXISTS_IN_SUB_CLS: Final = 8394 +ERROR_DS_EXISTS_IN_POSS_SUP: Final = 8395 +ERROR_DS_RECALCSCHEMA_FAILED: Final = 8396 +ERROR_DS_TREE_DELETE_NOT_FINISHED: Final = 8397 +ERROR_DS_CANT_DELETE: Final = 8398 +ERROR_DS_ATT_SCHEMA_REQ_ID: Final = 8399 +ERROR_DS_BAD_ATT_SCHEMA_SYNTAX: Final = 8400 +ERROR_DS_CANT_CACHE_ATT: Final = 8401 +ERROR_DS_CANT_CACHE_CLASS: Final = 8402 +ERROR_DS_CANT_REMOVE_ATT_CACHE: Final = 8403 +ERROR_DS_CANT_REMOVE_CLASS_CACHE: Final = 8404 +ERROR_DS_CANT_RETRIEVE_DN: Final = 8405 +ERROR_DS_MISSING_SUPREF: Final = 8406 +ERROR_DS_CANT_RETRIEVE_INSTANCE: Final = 8407 +ERROR_DS_CODE_INCONSISTENCY: Final = 8408 +ERROR_DS_DATABASE_ERROR: Final = 8409 +ERROR_DS_GOVERNSID_MISSING: Final = 8410 +ERROR_DS_MISSING_EXPECTED_ATT: Final = 8411 +ERROR_DS_NCNAME_MISSING_CR_REF: Final = 8412 +ERROR_DS_SECURITY_CHECKING_ERROR: Final = 8413 +ERROR_DS_SCHEMA_NOT_LOADED: Final = 8414 +ERROR_DS_SCHEMA_ALLOC_FAILED: Final = 8415 +ERROR_DS_ATT_SCHEMA_REQ_SYNTAX: Final = 8416 +ERROR_DS_GCVERIFY_ERROR: Final = 8417 +ERROR_DS_DRA_SCHEMA_MISMATCH: Final = 8418 +ERROR_DS_CANT_FIND_DSA_OBJ: Final = 8419 +ERROR_DS_CANT_FIND_EXPECTED_NC: Final = 8420 +ERROR_DS_CANT_FIND_NC_IN_CACHE: Final = 8421 +ERROR_DS_CANT_RETRIEVE_CHILD: Final = 8422 +ERROR_DS_SECURITY_ILLEGAL_MODIFY: Final = 8423 +ERROR_DS_CANT_REPLACE_HIDDEN_REC: Final = 8424 +ERROR_DS_BAD_HIERARCHY_FILE: Final = 8425 +ERROR_DS_BUILD_HIERARCHY_TABLE_FAILED: Final = 8426 +ERROR_DS_CONFIG_PARAM_MISSING: Final = 8427 +ERROR_DS_COUNTING_AB_INDICES_FAILED: Final = 8428 +ERROR_DS_HIERARCHY_TABLE_MALLOC_FAILED: Final = 8429 +ERROR_DS_INTERNAL_FAILURE: Final = 8430 +ERROR_DS_UNKNOWN_ERROR: Final = 8431 +ERROR_DS_ROOT_REQUIRES_CLASS_TOP: Final = 8432 +ERROR_DS_REFUSING_FSMO_ROLES: Final = 8433 +ERROR_DS_MISSING_FSMO_SETTINGS: Final = 8434 +ERROR_DS_UNABLE_TO_SURRENDER_ROLES: Final = 8435 +ERROR_DS_DRA_GENERIC: Final = 8436 +ERROR_DS_DRA_INVALID_PARAMETER: Final = 8437 +ERROR_DS_DRA_BUSY: Final = 8438 +ERROR_DS_DRA_BAD_DN: Final = 8439 +ERROR_DS_DRA_BAD_NC: Final = 8440 +ERROR_DS_DRA_DN_EXISTS: Final = 8441 +ERROR_DS_DRA_INTERNAL_ERROR: Final = 8442 +ERROR_DS_DRA_INCONSISTENT_DIT: Final = 8443 +ERROR_DS_DRA_CONNECTION_FAILED: Final = 8444 +ERROR_DS_DRA_BAD_INSTANCE_TYPE: Final = 8445 +ERROR_DS_DRA_OUT_OF_MEM: Final = 8446 +ERROR_DS_DRA_MAIL_PROBLEM: Final = 8447 +ERROR_DS_DRA_REF_ALREADY_EXISTS: Final = 8448 +ERROR_DS_DRA_REF_NOT_FOUND: Final = 8449 +ERROR_DS_DRA_OBJ_IS_REP_SOURCE: Final = 8450 +ERROR_DS_DRA_DB_ERROR: Final = 8451 +ERROR_DS_DRA_NO_REPLICA: Final = 8452 +ERROR_DS_DRA_ACCESS_DENIED: Final = 8453 +ERROR_DS_DRA_NOT_SUPPORTED: Final = 8454 +ERROR_DS_DRA_RPC_CANCELLED: Final = 8455 +ERROR_DS_DRA_SOURCE_DISABLED: Final = 8456 +ERROR_DS_DRA_SINK_DISABLED: Final = 8457 +ERROR_DS_DRA_NAME_COLLISION: Final = 8458 +ERROR_DS_DRA_SOURCE_REINSTALLED: Final = 8459 +ERROR_DS_DRA_MISSING_PARENT: Final = 8460 +ERROR_DS_DRA_PREEMPTED: Final = 8461 +ERROR_DS_DRA_ABANDON_SYNC: Final = 8462 +ERROR_DS_DRA_SHUTDOWN: Final = 8463 +ERROR_DS_DRA_INCOMPATIBLE_PARTIAL_SET: Final = 8464 +ERROR_DS_DRA_SOURCE_IS_PARTIAL_REPLICA: Final = 8465 +ERROR_DS_DRA_EXTN_CONNECTION_FAILED: Final = 8466 +ERROR_DS_INSTALL_SCHEMA_MISMATCH: Final = 8467 +ERROR_DS_DUP_LINK_ID: Final = 8468 +ERROR_DS_NAME_ERROR_RESOLVING: Final = 8469 +ERROR_DS_NAME_ERROR_NOT_FOUND: Final = 8470 +ERROR_DS_NAME_ERROR_NOT_UNIQUE: Final = 8471 +ERROR_DS_NAME_ERROR_NO_MAPPING: Final = 8472 +ERROR_DS_NAME_ERROR_DOMAIN_ONLY: Final = 8473 +ERROR_DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING: Final = 8474 +ERROR_DS_CONSTRUCTED_ATT_MOD: Final = 8475 +ERROR_DS_WRONG_OM_OBJ_CLASS: Final = 8476 +ERROR_DS_DRA_REPL_PENDING: Final = 8477 +ERROR_DS_DS_REQUIRED: Final = 8478 +ERROR_DS_INVALID_LDAP_DISPLAY_NAME: Final = 8479 +ERROR_DS_NON_BASE_SEARCH: Final = 8480 +ERROR_DS_CANT_RETRIEVE_ATTS: Final = 8481 +ERROR_DS_BACKLINK_WITHOUT_LINK: Final = 8482 +ERROR_DS_EPOCH_MISMATCH: Final = 8483 +ERROR_DS_SRC_NAME_MISMATCH: Final = 8484 +ERROR_DS_SRC_AND_DST_NC_IDENTICAL: Final = 8485 +ERROR_DS_DST_NC_MISMATCH: Final = 8486 +ERROR_DS_NOT_AUTHORITIVE_FOR_DST_NC: Final = 8487 +ERROR_DS_SRC_GUID_MISMATCH: Final = 8488 +ERROR_DS_CANT_MOVE_DELETED_OBJECT: Final = 8489 +ERROR_DS_PDC_OPERATION_IN_PROGRESS: Final = 8490 +ERROR_DS_CROSS_DOMAIN_CLEANUP_REQD: Final = 8491 +ERROR_DS_ILLEGAL_XDOM_MOVE_OPERATION: Final = 8492 +ERROR_DS_CANT_WITH_ACCT_GROUP_MEMBERSHPS: Final = 8493 +ERROR_DS_NC_MUST_HAVE_NC_PARENT: Final = 8494 +ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE: Final = 8495 +ERROR_DS_DST_DOMAIN_NOT_NATIVE: Final = 8496 +ERROR_DS_MISSING_INFRASTRUCTURE_CONTAINER: Final = 8497 +ERROR_DS_CANT_MOVE_ACCOUNT_GROUP: Final = 8498 +ERROR_DS_CANT_MOVE_RESOURCE_GROUP: Final = 8499 +ERROR_DS_INVALID_SEARCH_FLAG: Final = 8500 +ERROR_DS_NO_TREE_DELETE_ABOVE_NC: Final = 8501 +ERROR_DS_COULDNT_LOCK_TREE_FOR_DELETE: Final = 8502 +ERROR_DS_COULDNT_IDENTIFY_OBJECTS_FOR_TREE_DELETE: Final = 8503 +ERROR_DS_SAM_INIT_FAILURE: Final = 8504 +ERROR_DS_SENSITIVE_GROUP_VIOLATION: Final = 8505 +ERROR_DS_CANT_MOD_PRIMARYGROUPID: Final = 8506 +ERROR_DS_ILLEGAL_BASE_SCHEMA_MOD: Final = 8507 +ERROR_DS_NONSAFE_SCHEMA_CHANGE: Final = 8508 +ERROR_DS_SCHEMA_UPDATE_DISALLOWED: Final = 8509 +ERROR_DS_CANT_CREATE_UNDER_SCHEMA: Final = 8510 +ERROR_DS_INSTALL_NO_SRC_SCH_VERSION: Final = 8511 +ERROR_DS_INSTALL_NO_SCH_VERSION_IN_INIFILE: Final = 8512 +ERROR_DS_INVALID_GROUP_TYPE: Final = 8513 +ERROR_DS_NO_NEST_GLOBALGROUP_IN_MIXEDDOMAIN: Final = 8514 +ERROR_DS_NO_NEST_LOCALGROUP_IN_MIXEDDOMAIN: Final = 8515 +ERROR_DS_GLOBAL_CANT_HAVE_LOCAL_MEMBER: Final = 8516 +ERROR_DS_GLOBAL_CANT_HAVE_UNIVERSAL_MEMBER: Final = 8517 +ERROR_DS_UNIVERSAL_CANT_HAVE_LOCAL_MEMBER: Final = 8518 +ERROR_DS_GLOBAL_CANT_HAVE_CROSSDOMAIN_MEMBER: Final = 8519 +ERROR_DS_LOCAL_CANT_HAVE_CROSSDOMAIN_LOCAL_MEMBER: Final = 8520 +ERROR_DS_HAVE_PRIMARY_MEMBERS: Final = 8521 +ERROR_DS_STRING_SD_CONVERSION_FAILED: Final = 8522 +ERROR_DS_NAMING_MASTER_GC: Final = 8523 +ERROR_DS_DNS_LOOKUP_FAILURE: Final = 8524 +ERROR_DS_COULDNT_UPDATE_SPNS: Final = 8525 +ERROR_DS_CANT_RETRIEVE_SD: Final = 8526 +ERROR_DS_KEY_NOT_UNIQUE: Final = 8527 +ERROR_DS_WRONG_LINKED_ATT_SYNTAX: Final = 8528 +ERROR_DS_SAM_NEED_BOOTKEY_PASSWORD: Final = 8529 +ERROR_DS_SAM_NEED_BOOTKEY_FLOPPY: Final = 8530 +ERROR_DS_CANT_START: Final = 8531 +ERROR_DS_INIT_FAILURE: Final = 8532 +ERROR_DS_NO_PKT_PRIVACY_ON_CONNECTION: Final = 8533 +ERROR_DS_SOURCE_DOMAIN_IN_FOREST: Final = 8534 +ERROR_DS_DESTINATION_DOMAIN_NOT_IN_FOREST: Final = 8535 +ERROR_DS_DESTINATION_AUDITING_NOT_ENABLED: Final = 8536 +ERROR_DS_CANT_FIND_DC_FOR_SRC_DOMAIN: Final = 8537 +ERROR_DS_SRC_OBJ_NOT_GROUP_OR_USER: Final = 8538 +ERROR_DS_SRC_SID_EXISTS_IN_FOREST: Final = 8539 +ERROR_DS_SRC_AND_DST_OBJECT_CLASS_MISMATCH: Final = 8540 +ERROR_SAM_INIT_FAILURE: Final = 8541 +ERROR_DS_DRA_SCHEMA_INFO_SHIP: Final = 8542 +ERROR_DS_DRA_SCHEMA_CONFLICT: Final = 8543 +ERROR_DS_DRA_EARLIER_SCHEMA_CONFLICT: Final = 8544 +ERROR_DS_DRA_OBJ_NC_MISMATCH: Final = 8545 +ERROR_DS_NC_STILL_HAS_DSAS: Final = 8546 +ERROR_DS_GC_REQUIRED: Final = 8547 +ERROR_DS_LOCAL_MEMBER_OF_LOCAL_ONLY: Final = 8548 +ERROR_DS_NO_FPO_IN_UNIVERSAL_GROUPS: Final = 8549 +ERROR_DS_CANT_ADD_TO_GC: Final = 8550 +ERROR_DS_NO_CHECKPOINT_WITH_PDC: Final = 8551 +ERROR_DS_SOURCE_AUDITING_NOT_ENABLED: Final = 8552 +ERROR_DS_CANT_CREATE_IN_NONDOMAIN_NC: Final = 8553 +ERROR_DS_INVALID_NAME_FOR_SPN: Final = 8554 +ERROR_DS_FILTER_USES_CONTRUCTED_ATTRS: Final = 8555 +ERROR_DS_UNICODEPWD_NOT_IN_QUOTES: Final = 8556 +ERROR_DS_MACHINE_ACCOUNT_QUOTA_EXCEEDED: Final = 8557 +ERROR_DS_MUST_BE_RUN_ON_DST_DC: Final = 8558 +ERROR_DS_SRC_DC_MUST_BE_SP4_OR_GREATER: Final = 8559 +ERROR_DS_CANT_TREE_DELETE_CRITICAL_OBJ: Final = 8560 +ERROR_DS_INIT_FAILURE_CONSOLE: Final = 8561 +ERROR_DS_SAM_INIT_FAILURE_CONSOLE: Final = 8562 +ERROR_DS_FOREST_VERSION_TOO_HIGH: Final = 8563 +ERROR_DS_DOMAIN_VERSION_TOO_HIGH: Final = 8564 +ERROR_DS_FOREST_VERSION_TOO_LOW: Final = 8565 +ERROR_DS_DOMAIN_VERSION_TOO_LOW: Final = 8566 +ERROR_DS_INCOMPATIBLE_VERSION: Final = 8567 +ERROR_DS_LOW_DSA_VERSION: Final = 8568 +ERROR_DS_NO_BEHAVIOR_VERSION_IN_MIXEDDOMAIN: Final = 8569 +ERROR_DS_NOT_SUPPORTED_SORT_ORDER: Final = 8570 +ERROR_DS_NAME_NOT_UNIQUE: Final = 8571 +ERROR_DS_MACHINE_ACCOUNT_CREATED_PRENT4: Final = 8572 +ERROR_DS_OUT_OF_VERSION_STORE: Final = 8573 +ERROR_DS_INCOMPATIBLE_CONTROLS_USED: Final = 8574 +ERROR_DS_NO_REF_DOMAIN: Final = 8575 +ERROR_DS_RESERVED_LINK_ID: Final = 8576 +ERROR_DS_LINK_ID_NOT_AVAILABLE: Final = 8577 +ERROR_DS_AG_CANT_HAVE_UNIVERSAL_MEMBER: Final = 8578 +ERROR_DS_MODIFYDN_DISALLOWED_BY_INSTANCE_TYPE: Final = 8579 +ERROR_DS_NO_OBJECT_MOVE_IN_SCHEMA_NC: Final = 8580 +ERROR_DS_MODIFYDN_DISALLOWED_BY_FLAG: Final = 8581 +ERROR_DS_MODIFYDN_WRONG_GRANDPARENT: Final = 8582 +ERROR_DS_NAME_ERROR_TRUST_REFERRAL: Final = 8583 +ERROR_NOT_SUPPORTED_ON_STANDARD_SERVER: Final = 8584 +ERROR_DS_CANT_ACCESS_REMOTE_PART_OF_AD: Final = 8585 +ERROR_DS_CR_IMPOSSIBLE_TO_VALIDATE_V2: Final = 8586 +ERROR_DS_THREAD_LIMIT_EXCEEDED: Final = 8587 +ERROR_DS_NOT_CLOSEST: Final = 8588 +ERROR_DS_CANT_DERIVE_SPN_WITHOUT_SERVER_REF: Final = 8589 +ERROR_DS_SINGLE_USER_MODE_FAILED: Final = 8590 +ERROR_DS_NTDSCRIPT_SYNTAX_ERROR: Final = 8591 +ERROR_DS_NTDSCRIPT_PROCESS_ERROR: Final = 8592 +ERROR_DS_DIFFERENT_REPL_EPOCHS: Final = 8593 +ERROR_DS_DRS_EXTENSIONS_CHANGED: Final = 8594 +ERROR_DS_REPLICA_SET_CHANGE_NOT_ALLOWED_ON_DISABLED_CR: Final = 8595 +ERROR_DS_NO_MSDS_INTID: Final = 8596 +ERROR_DS_DUP_MSDS_INTID: Final = 8597 +ERROR_DS_EXISTS_IN_RDNATTID: Final = 8598 +ERROR_DS_AUTHORIZATION_FAILED: Final = 8599 +ERROR_DS_INVALID_SCRIPT: Final = 8600 +ERROR_DS_REMOTE_CROSSREF_OP_FAILED: Final = 8601 +ERROR_DS_CROSS_REF_BUSY: Final = 8602 +ERROR_DS_CANT_DERIVE_SPN_FOR_DELETED_DOMAIN: Final = 8603 +ERROR_DS_CANT_DEMOTE_WITH_WRITEABLE_NC: Final = 8604 +ERROR_DS_DUPLICATE_ID_FOUND: Final = 8605 +ERROR_DS_INSUFFICIENT_ATTR_TO_CREATE_OBJECT: Final = 8606 +ERROR_DS_GROUP_CONVERSION_ERROR: Final = 8607 +ERROR_DS_CANT_MOVE_APP_BASIC_GROUP: Final = 8608 +ERROR_DS_CANT_MOVE_APP_QUERY_GROUP: Final = 8609 +ERROR_DS_ROLE_NOT_VERIFIED: Final = 8610 +ERROR_DS_WKO_CONTAINER_CANNOT_BE_SPECIAL: Final = 8611 +ERROR_DS_DOMAIN_RENAME_IN_PROGRESS: Final = 8612 +ERROR_DS_EXISTING_AD_CHILD_NC: Final = 8613 +ERROR_DS_REPL_LIFETIME_EXCEEDED: Final = 8614 +ERROR_DS_DISALLOWED_IN_SYSTEM_CONTAINER: Final = 8615 +ERROR_DS_LDAP_SEND_QUEUE_FULL: Final = 8616 +ERROR_DS_DRA_OUT_SCHEDULE_WINDOW: Final = 8617 +ERROR_DS_POLICY_NOT_KNOWN: Final = 8618 +ERROR_NO_SITE_SETTINGS_OBJECT: Final = 8619 +ERROR_NO_SECRETS: Final = 8620 +ERROR_NO_WRITABLE_DC_FOUND: Final = 8621 +ERROR_DS_NO_SERVER_OBJECT: Final = 8622 +ERROR_DS_NO_NTDSA_OBJECT: Final = 8623 +ERROR_DS_NON_ASQ_SEARCH: Final = 8624 +ERROR_DS_AUDIT_FAILURE: Final = 8625 +ERROR_DS_INVALID_SEARCH_FLAG_SUBTREE: Final = 8626 +ERROR_DS_INVALID_SEARCH_FLAG_TUPLE: Final = 8627 +ERROR_DS_HIERARCHY_TABLE_TOO_DEEP: Final = 8628 +ERROR_DS_DRA_CORRUPT_UTD_VECTOR: Final = 8629 +ERROR_DS_DRA_SECRETS_DENIED: Final = 8630 +ERROR_DS_RESERVED_MAPI_ID: Final = 8631 +ERROR_DS_MAPI_ID_NOT_AVAILABLE: Final = 8632 +ERROR_DS_DRA_MISSING_KRBTGT_SECRET: Final = 8633 +ERROR_DS_DOMAIN_NAME_EXISTS_IN_FOREST: Final = 8634 +ERROR_DS_FLAT_NAME_EXISTS_IN_FOREST: Final = 8635 +ERROR_INVALID_USER_PRINCIPAL_NAME: Final = 8636 +ERROR_DS_OID_MAPPED_GROUP_CANT_HAVE_MEMBERS: Final = 8637 +ERROR_DS_OID_NOT_FOUND: Final = 8638 +ERROR_DS_DRA_RECYCLED_TARGET: Final = 8639 +ERROR_DS_DISALLOWED_NC_REDIRECT: Final = 8640 +ERROR_DS_HIGH_ADLDS_FFL: Final = 8641 +ERROR_DS_HIGH_DSA_VERSION: Final = 8642 +ERROR_DS_LOW_ADLDS_FFL: Final = 8643 +ERROR_DOMAIN_SID_SAME_AS_LOCAL_WORKSTATION: Final = 8644 +ERROR_DS_UNDELETE_SAM_VALIDATION_FAILED: Final = 8645 +ERROR_INCORRECT_ACCOUNT_TYPE: Final = 8646 +ERROR_DS_SPN_VALUE_NOT_UNIQUE_IN_FOREST: Final = 8647 +ERROR_DS_UPN_VALUE_NOT_UNIQUE_IN_FOREST: Final = 8648 +ERROR_DS_MISSING_FOREST_TRUST: Final = 8649 +ERROR_DS_VALUE_KEY_NOT_UNIQUE: Final = 8650 +ERROR_WEAK_WHFBKEY_BLOCKED: Final = 8651 +ERROR_DS_PER_ATTRIBUTE_AUTHZ_FAILED_DURING_ADD: Final = 8652 +ERROR_LOCAL_POLICY_MODIFICATION_NOT_SUPPORTED: Final = 8653 +ERROR_POLICY_CONTROLLED_ACCOUNT: Final = 8654 +ERROR_LAPS_LEGACY_SCHEMA_MISSING: Final = 8655 +ERROR_LAPS_SCHEMA_MISSING: Final = 8656 +ERROR_LAPS_ENCRYPTION_REQUIRES_2016_DFL: Final = 8657 +DNS_ERROR_RESPONSE_CODES_BASE: Final = 9000 +DNS_ERROR_RCODE_NO_ERROR: Final = NO_ERROR +DNS_ERROR_MASK: Final = 0x00002328 +DNS_ERROR_RCODE_FORMAT_ERROR: Final = 9001 +DNS_ERROR_RCODE_SERVER_FAILURE: Final = 9002 +DNS_ERROR_RCODE_NAME_ERROR: Final = 9003 +DNS_ERROR_RCODE_NOT_IMPLEMENTED: Final = 9004 +DNS_ERROR_RCODE_REFUSED: Final = 9005 +DNS_ERROR_RCODE_YXDOMAIN: Final = 9006 +DNS_ERROR_RCODE_YXRRSET: Final = 9007 +DNS_ERROR_RCODE_NXRRSET: Final = 9008 +DNS_ERROR_RCODE_NOTAUTH: Final = 9009 +DNS_ERROR_RCODE_NOTZONE: Final = 9010 +DNS_ERROR_RCODE_BADSIG: Final = 9016 +DNS_ERROR_RCODE_BADKEY: Final = 9017 +DNS_ERROR_RCODE_BADTIME: Final = 9018 +DNS_ERROR_RCODE_LAST: Final = DNS_ERROR_RCODE_BADTIME +DNS_ERROR_DNSSEC_BASE: Final = 9100 +DNS_ERROR_KEYMASTER_REQUIRED: Final = 9101 +DNS_ERROR_NOT_ALLOWED_ON_SIGNED_ZONE: Final = 9102 +DNS_ERROR_NSEC3_INCOMPATIBLE_WITH_RSA_SHA1: Final = 9103 +DNS_ERROR_NOT_ENOUGH_SIGNING_KEY_DESCRIPTORS: Final = 9104 +DNS_ERROR_UNSUPPORTED_ALGORITHM: Final = 9105 +DNS_ERROR_INVALID_KEY_SIZE: Final = 9106 +DNS_ERROR_SIGNING_KEY_NOT_ACCESSIBLE: Final = 9107 +DNS_ERROR_KSP_DOES_NOT_SUPPORT_PROTECTION: Final = 9108 +DNS_ERROR_UNEXPECTED_DATA_PROTECTION_ERROR: Final = 9109 +DNS_ERROR_UNEXPECTED_CNG_ERROR: Final = 9110 +DNS_ERROR_UNKNOWN_SIGNING_PARAMETER_VERSION: Final = 9111 +DNS_ERROR_KSP_NOT_ACCESSIBLE: Final = 9112 +DNS_ERROR_TOO_MANY_SKDS: Final = 9113 +DNS_ERROR_INVALID_ROLLOVER_PERIOD: Final = 9114 +DNS_ERROR_INVALID_INITIAL_ROLLOVER_OFFSET: Final = 9115 +DNS_ERROR_ROLLOVER_IN_PROGRESS: Final = 9116 +DNS_ERROR_STANDBY_KEY_NOT_PRESENT: Final = 9117 +DNS_ERROR_NOT_ALLOWED_ON_ZSK: Final = 9118 +DNS_ERROR_NOT_ALLOWED_ON_ACTIVE_SKD: Final = 9119 +DNS_ERROR_ROLLOVER_ALREADY_QUEUED: Final = 9120 +DNS_ERROR_NOT_ALLOWED_ON_UNSIGNED_ZONE: Final = 9121 +DNS_ERROR_BAD_KEYMASTER: Final = 9122 +DNS_ERROR_INVALID_SIGNATURE_VALIDITY_PERIOD: Final = 9123 +DNS_ERROR_INVALID_NSEC3_ITERATION_COUNT: Final = 9124 +DNS_ERROR_DNSSEC_IS_DISABLED: Final = 9125 +DNS_ERROR_INVALID_XML: Final = 9126 +DNS_ERROR_NO_VALID_TRUST_ANCHORS: Final = 9127 +DNS_ERROR_ROLLOVER_NOT_POKEABLE: Final = 9128 +DNS_ERROR_NSEC3_NAME_COLLISION: Final = 9129 +DNS_ERROR_NSEC_INCOMPATIBLE_WITH_NSEC3_RSA_SHA1: Final = 9130 +DNS_ERROR_PACKET_FMT_BASE: Final = 9500 +DNS_INFO_NO_RECORDS: Final = 9501 +DNS_ERROR_BAD_PACKET: Final = 9502 +DNS_ERROR_NO_PACKET: Final = 9503 +DNS_ERROR_RCODE: Final = 9504 +DNS_ERROR_UNSECURE_PACKET: Final = 9505 +DNS_STATUS_PACKET_UNSECURE: Final = DNS_ERROR_UNSECURE_PACKET +DNS_REQUEST_PENDING: Final = 9506 +DNS_ERROR_NO_MEMORY: Final = ERROR_OUTOFMEMORY +DNS_ERROR_INVALID_NAME: Final = ERROR_INVALID_NAME +DNS_ERROR_INVALID_DATA: Final = ERROR_INVALID_DATA +DNS_ERROR_GENERAL_API_BASE: Final = 9550 +DNS_ERROR_INVALID_TYPE: Final = 9551 +DNS_ERROR_INVALID_IP_ADDRESS: Final = 9552 +DNS_ERROR_INVALID_PROPERTY: Final = 9553 +DNS_ERROR_TRY_AGAIN_LATER: Final = 9554 +DNS_ERROR_NOT_UNIQUE: Final = 9555 +DNS_ERROR_NON_RFC_NAME: Final = 9556 +DNS_STATUS_FQDN: Final = 9557 +DNS_STATUS_DOTTED_NAME: Final = 9558 +DNS_STATUS_SINGLE_PART_NAME: Final = 9559 +DNS_ERROR_INVALID_NAME_CHAR: Final = 9560 +DNS_ERROR_NUMERIC_NAME: Final = 9561 +DNS_ERROR_NOT_ALLOWED_ON_ROOT_SERVER: Final = 9562 +DNS_ERROR_NOT_ALLOWED_UNDER_DELEGATION: Final = 9563 +DNS_ERROR_CANNOT_FIND_ROOT_HINTS: Final = 9564 +DNS_ERROR_INCONSISTENT_ROOT_HINTS: Final = 9565 +DNS_ERROR_DWORD_VALUE_TOO_SMALL: Final = 9566 +DNS_ERROR_DWORD_VALUE_TOO_LARGE: Final = 9567 +DNS_ERROR_BACKGROUND_LOADING: Final = 9568 +DNS_ERROR_NOT_ALLOWED_ON_RODC: Final = 9569 +DNS_ERROR_NOT_ALLOWED_UNDER_DNAME: Final = 9570 +DNS_ERROR_DELEGATION_REQUIRED: Final = 9571 +DNS_ERROR_INVALID_POLICY_TABLE: Final = 9572 +DNS_ERROR_ADDRESS_REQUIRED: Final = 9573 +DNS_ERROR_ZONE_BASE: Final = 9600 +DNS_ERROR_ZONE_DOES_NOT_EXIST: Final = 9601 +DNS_ERROR_NO_ZONE_INFO: Final = 9602 +DNS_ERROR_INVALID_ZONE_OPERATION: Final = 9603 +DNS_ERROR_ZONE_CONFIGURATION_ERROR: Final = 9604 +DNS_ERROR_ZONE_HAS_NO_SOA_RECORD: Final = 9605 +DNS_ERROR_ZONE_HAS_NO_NS_RECORDS: Final = 9606 +DNS_ERROR_ZONE_LOCKED: Final = 9607 +DNS_ERROR_ZONE_CREATION_FAILED: Final = 9608 +DNS_ERROR_ZONE_ALREADY_EXISTS: Final = 9609 +DNS_ERROR_AUTOZONE_ALREADY_EXISTS: Final = 9610 +DNS_ERROR_INVALID_ZONE_TYPE: Final = 9611 +DNS_ERROR_SECONDARY_REQUIRES_MASTER_IP: Final = 9612 +DNS_ERROR_ZONE_NOT_SECONDARY: Final = 9613 +DNS_ERROR_NEED_SECONDARY_ADDRESSES: Final = 9614 +DNS_ERROR_WINS_INIT_FAILED: Final = 9615 +DNS_ERROR_NEED_WINS_SERVERS: Final = 9616 +DNS_ERROR_NBSTAT_INIT_FAILED: Final = 9617 +DNS_ERROR_SOA_DELETE_INVALID: Final = 9618 +DNS_ERROR_FORWARDER_ALREADY_EXISTS: Final = 9619 +DNS_ERROR_ZONE_REQUIRES_MASTER_IP: Final = 9620 +DNS_ERROR_ZONE_IS_SHUTDOWN: Final = 9621 +DNS_ERROR_ZONE_LOCKED_FOR_SIGNING: Final = 9622 +DNS_ERROR_DATAFILE_BASE: Final = 9650 +DNS_ERROR_PRIMARY_REQUIRES_DATAFILE: Final = 9651 +DNS_ERROR_INVALID_DATAFILE_NAME: Final = 9652 +DNS_ERROR_DATAFILE_OPEN_FAILURE: Final = 9653 +DNS_ERROR_FILE_WRITEBACK_FAILED: Final = 9654 +DNS_ERROR_DATAFILE_PARSING: Final = 9655 +DNS_ERROR_DATABASE_BASE: Final = 9700 +DNS_ERROR_RECORD_DOES_NOT_EXIST: Final = 9701 +DNS_ERROR_RECORD_FORMAT: Final = 9702 +DNS_ERROR_NODE_CREATION_FAILED: Final = 9703 +DNS_ERROR_UNKNOWN_RECORD_TYPE: Final = 9704 +DNS_ERROR_RECORD_TIMED_OUT: Final = 9705 +DNS_ERROR_NAME_NOT_IN_ZONE: Final = 9706 +DNS_ERROR_CNAME_LOOP: Final = 9707 +DNS_ERROR_NODE_IS_CNAME: Final = 9708 +DNS_ERROR_CNAME_COLLISION: Final = 9709 +DNS_ERROR_RECORD_ONLY_AT_ZONE_ROOT: Final = 9710 +DNS_ERROR_RECORD_ALREADY_EXISTS: Final = 9711 +DNS_ERROR_SECONDARY_DATA: Final = 9712 +DNS_ERROR_NO_CREATE_CACHE_DATA: Final = 9713 +DNS_ERROR_NAME_DOES_NOT_EXIST: Final = 9714 +DNS_WARNING_PTR_CREATE_FAILED: Final = 9715 +DNS_WARNING_DOMAIN_UNDELETED: Final = 9716 +DNS_ERROR_DS_UNAVAILABLE: Final = 9717 +DNS_ERROR_DS_ZONE_ALREADY_EXISTS: Final = 9718 +DNS_ERROR_NO_BOOTFILE_IF_DS_ZONE: Final = 9719 +DNS_ERROR_NODE_IS_DNAME: Final = 9720 +DNS_ERROR_DNAME_COLLISION: Final = 9721 +DNS_ERROR_ALIAS_LOOP: Final = 9722 +DNS_ERROR_OPERATION_BASE: Final = 9750 +DNS_INFO_AXFR_COMPLETE: Final = 9751 +DNS_ERROR_AXFR: Final = 9752 +DNS_INFO_ADDED_LOCAL_WINS: Final = 9753 +DNS_ERROR_SECURE_BASE: Final = 9800 +DNS_STATUS_CONTINUE_NEEDED: Final = 9801 +DNS_ERROR_SETUP_BASE: Final = 9850 +DNS_ERROR_NO_TCPIP: Final = 9851 +DNS_ERROR_NO_DNS_SERVERS: Final = 9852 +DNS_ERROR_DP_BASE: Final = 9900 +DNS_ERROR_DP_DOES_NOT_EXIST: Final = 9901 +DNS_ERROR_DP_ALREADY_EXISTS: Final = 9902 +DNS_ERROR_DP_NOT_ENLISTED: Final = 9903 +DNS_ERROR_DP_ALREADY_ENLISTED: Final = 9904 +DNS_ERROR_DP_NOT_AVAILABLE: Final = 9905 +DNS_ERROR_DP_FSMO_ERROR: Final = 9906 +DNS_ERROR_RRL_NOT_ENABLED: Final = 9911 +DNS_ERROR_RRL_INVALID_WINDOW_SIZE: Final = 9912 +DNS_ERROR_RRL_INVALID_IPV4_PREFIX: Final = 9913 +DNS_ERROR_RRL_INVALID_IPV6_PREFIX: Final = 9914 +DNS_ERROR_RRL_INVALID_TC_RATE: Final = 9915 +DNS_ERROR_RRL_INVALID_LEAK_RATE: Final = 9916 +DNS_ERROR_RRL_LEAK_RATE_LESSTHAN_TC_RATE: Final = 9917 +DNS_ERROR_VIRTUALIZATION_INSTANCE_ALREADY_EXISTS: Final = 9921 +DNS_ERROR_VIRTUALIZATION_INSTANCE_DOES_NOT_EXIST: Final = 9922 +DNS_ERROR_VIRTUALIZATION_TREE_LOCKED: Final = 9923 +DNS_ERROR_INVAILD_VIRTUALIZATION_INSTANCE_NAME: Final = 9924 +DNS_ERROR_DEFAULT_VIRTUALIZATION_INSTANCE: Final = 9925 +DNS_ERROR_ZONESCOPE_ALREADY_EXISTS: Final = 9951 +DNS_ERROR_ZONESCOPE_DOES_NOT_EXIST: Final = 9952 +DNS_ERROR_DEFAULT_ZONESCOPE: Final = 9953 +DNS_ERROR_INVALID_ZONESCOPE_NAME: Final = 9954 +DNS_ERROR_NOT_ALLOWED_WITH_ZONESCOPES: Final = 9955 +DNS_ERROR_LOAD_ZONESCOPE_FAILED: Final = 9956 +DNS_ERROR_ZONESCOPE_FILE_WRITEBACK_FAILED: Final = 9957 +DNS_ERROR_INVALID_SCOPE_NAME: Final = 9958 +DNS_ERROR_SCOPE_DOES_NOT_EXIST: Final = 9959 +DNS_ERROR_DEFAULT_SCOPE: Final = 9960 +DNS_ERROR_INVALID_SCOPE_OPERATION: Final = 9961 +DNS_ERROR_SCOPE_LOCKED: Final = 9962 +DNS_ERROR_SCOPE_ALREADY_EXISTS: Final = 9963 +DNS_ERROR_POLICY_ALREADY_EXISTS: Final = 9971 +DNS_ERROR_POLICY_DOES_NOT_EXIST: Final = 9972 +DNS_ERROR_POLICY_INVALID_CRITERIA: Final = 9973 +DNS_ERROR_POLICY_INVALID_SETTINGS: Final = 9974 +DNS_ERROR_CLIENT_SUBNET_IS_ACCESSED: Final = 9975 +DNS_ERROR_CLIENT_SUBNET_DOES_NOT_EXIST: Final = 9976 +DNS_ERROR_CLIENT_SUBNET_ALREADY_EXISTS: Final = 9977 +DNS_ERROR_SUBNET_DOES_NOT_EXIST: Final = 9978 +DNS_ERROR_SUBNET_ALREADY_EXISTS: Final = 9979 +DNS_ERROR_POLICY_LOCKED: Final = 9980 +DNS_ERROR_POLICY_INVALID_WEIGHT: Final = 9981 +DNS_ERROR_POLICY_INVALID_NAME: Final = 9982 +DNS_ERROR_POLICY_MISSING_CRITERIA: Final = 9983 +DNS_ERROR_INVALID_CLIENT_SUBNET_NAME: Final = 9984 +DNS_ERROR_POLICY_PROCESSING_ORDER_INVALID: Final = 9985 +DNS_ERROR_POLICY_SCOPE_MISSING: Final = 9986 +DNS_ERROR_POLICY_SCOPE_NOT_ALLOWED: Final = 9987 +DNS_ERROR_SERVERSCOPE_IS_REFERENCED: Final = 9988 +DNS_ERROR_ZONESCOPE_IS_REFERENCED: Final = 9989 +DNS_ERROR_POLICY_INVALID_CRITERIA_CLIENT_SUBNET: Final = 9990 +DNS_ERROR_POLICY_INVALID_CRITERIA_TRANSPORT_PROTOCOL: Final = 9991 +DNS_ERROR_POLICY_INVALID_CRITERIA_NETWORK_PROTOCOL: Final = 9992 +DNS_ERROR_POLICY_INVALID_CRITERIA_INTERFACE: Final = 9993 +DNS_ERROR_POLICY_INVALID_CRITERIA_FQDN: Final = 9994 +DNS_ERROR_POLICY_INVALID_CRITERIA_QUERY_TYPE: Final = 9995 +DNS_ERROR_POLICY_INVALID_CRITERIA_TIME_OF_DAY: Final = 9996 +WSABASEERR: Final = 10000 +WSAEINTR: Final = 10004 +WSAEBADF: Final = 10009 +WSAEACCES: Final = 10013 +WSAEFAULT: Final = 10014 +WSAEINVAL: Final = 10022 +WSAEMFILE: Final = 10024 +WSAEWOULDBLOCK: Final = 10035 +WSAEINPROGRESS: Final = 10036 +WSAEALREADY: Final = 10037 +WSAENOTSOCK: Final = 10038 +WSAEDESTADDRREQ: Final = 10039 +WSAEMSGSIZE: Final = 10040 +WSAEPROTOTYPE: Final = 10041 +WSAENOPROTOOPT: Final = 10042 +WSAEPROTONOSUPPORT: Final = 10043 +WSAESOCKTNOSUPPORT: Final = 10044 +WSAEOPNOTSUPP: Final = 10045 +WSAEPFNOSUPPORT: Final = 10046 +WSAEAFNOSUPPORT: Final = 10047 +WSAEADDRINUSE: Final = 10048 +WSAEADDRNOTAVAIL: Final = 10049 +WSAENETDOWN: Final = 10050 +WSAENETUNREACH: Final = 10051 +WSAENETRESET: Final = 10052 +WSAECONNABORTED: Final = 10053 +WSAECONNRESET: Final = 10054 +WSAENOBUFS: Final = 10055 +WSAEISCONN: Final = 10056 +WSAENOTCONN: Final = 10057 +WSAESHUTDOWN: Final = 10058 +WSAETOOMANYREFS: Final = 10059 +WSAETIMEDOUT: Final = 10060 +WSAECONNREFUSED: Final = 10061 +WSAELOOP: Final = 10062 +WSAENAMETOOLONG: Final = 10063 +WSAEHOSTDOWN: Final = 10064 +WSAEHOSTUNREACH: Final = 10065 +WSAENOTEMPTY: Final = 10066 +WSAEPROCLIM: Final = 10067 +WSAEUSERS: Final = 10068 +WSAEDQUOT: Final = 10069 +WSAESTALE: Final = 10070 +WSAEREMOTE: Final = 10071 +WSASYSNOTREADY: Final = 10091 +WSAVERNOTSUPPORTED: Final = 10092 +WSANOTINITIALISED: Final = 10093 +WSAEDISCON: Final = 10101 +WSAENOMORE: Final = 10102 +WSAECANCELLED: Final = 10103 +WSAEINVALIDPROCTABLE: Final = 10104 +WSAEINVALIDPROVIDER: Final = 10105 +WSAEPROVIDERFAILEDINIT: Final = 10106 +WSASYSCALLFAILURE: Final = 10107 +WSASERVICE_NOT_FOUND: Final = 10108 +WSATYPE_NOT_FOUND: Final = 10109 +WSA_E_NO_MORE: Final = 10110 +WSA_E_CANCELLED: Final = 10111 +WSAEREFUSED: Final = 10112 +WSAHOST_NOT_FOUND: Final = 11001 +WSATRY_AGAIN: Final = 11002 +WSANO_RECOVERY: Final = 11003 +WSANO_DATA: Final = 11004 +WSA_QOS_RECEIVERS: Final = 11005 +WSA_QOS_SENDERS: Final = 11006 +WSA_QOS_NO_SENDERS: Final = 11007 +WSA_QOS_NO_RECEIVERS: Final = 11008 +WSA_QOS_REQUEST_CONFIRMED: Final = 11009 +WSA_QOS_ADMISSION_FAILURE: Final = 11010 +WSA_QOS_POLICY_FAILURE: Final = 11011 +WSA_QOS_BAD_STYLE: Final = 11012 +WSA_QOS_BAD_OBJECT: Final = 11013 +WSA_QOS_TRAFFIC_CTRL_ERROR: Final = 11014 +WSA_QOS_GENERIC_ERROR: Final = 11015 +WSA_QOS_ESERVICETYPE: Final = 11016 +WSA_QOS_EFLOWSPEC: Final = 11017 +WSA_QOS_EPROVSPECBUF: Final = 11018 +WSA_QOS_EFILTERSTYLE: Final = 11019 +WSA_QOS_EFILTERTYPE: Final = 11020 +WSA_QOS_EFILTERCOUNT: Final = 11021 +WSA_QOS_EOBJLENGTH: Final = 11022 +WSA_QOS_EFLOWCOUNT: Final = 11023 +WSA_QOS_EUNKOWNPSOBJ: Final = 11024 +WSA_QOS_EPOLICYOBJ: Final = 11025 +WSA_QOS_EFLOWDESC: Final = 11026 +WSA_QOS_EPSFLOWSPEC: Final = 11027 +WSA_QOS_EPSFILTERSPEC: Final = 11028 +WSA_QOS_ESDMODEOBJ: Final = 11029 +WSA_QOS_ESHAPERATEOBJ: Final = 11030 +WSA_QOS_RESERVED_PETYPE: Final = 11031 +WSA_SECURE_HOST_NOT_FOUND: Final = 11032 +WSA_IPSEC_NAME_POLICY_ERROR: Final = 11033 +ERROR_IPSEC_QM_POLICY_EXISTS: Final = 13000 +ERROR_IPSEC_QM_POLICY_NOT_FOUND: Final = 13001 +ERROR_IPSEC_QM_POLICY_IN_USE: Final = 13002 +ERROR_IPSEC_MM_POLICY_EXISTS: Final = 13003 +ERROR_IPSEC_MM_POLICY_NOT_FOUND: Final = 13004 +ERROR_IPSEC_MM_POLICY_IN_USE: Final = 13005 +ERROR_IPSEC_MM_FILTER_EXISTS: Final = 13006 +ERROR_IPSEC_MM_FILTER_NOT_FOUND: Final = 13007 +ERROR_IPSEC_TRANSPORT_FILTER_EXISTS: Final = 13008 +ERROR_IPSEC_TRANSPORT_FILTER_NOT_FOUND: Final = 13009 +ERROR_IPSEC_MM_AUTH_EXISTS: Final = 13010 +ERROR_IPSEC_MM_AUTH_NOT_FOUND: Final = 13011 +ERROR_IPSEC_MM_AUTH_IN_USE: Final = 13012 +ERROR_IPSEC_DEFAULT_MM_POLICY_NOT_FOUND: Final = 13013 +ERROR_IPSEC_DEFAULT_MM_AUTH_NOT_FOUND: Final = 13014 +ERROR_IPSEC_DEFAULT_QM_POLICY_NOT_FOUND: Final = 13015 +ERROR_IPSEC_TUNNEL_FILTER_EXISTS: Final = 13016 +ERROR_IPSEC_TUNNEL_FILTER_NOT_FOUND: Final = 13017 +ERROR_IPSEC_MM_FILTER_PENDING_DELETION: Final = 13018 +ERROR_IPSEC_TRANSPORT_FILTER_PENDING_DELETION: Final = 13019 +ERROR_IPSEC_TUNNEL_FILTER_PENDING_DELETION: Final = 13020 +ERROR_IPSEC_MM_POLICY_PENDING_DELETION: Final = 13021 +ERROR_IPSEC_MM_AUTH_PENDING_DELETION: Final = 13022 +ERROR_IPSEC_QM_POLICY_PENDING_DELETION: Final = 13023 +WARNING_IPSEC_MM_POLICY_PRUNED: Final = 13024 +WARNING_IPSEC_QM_POLICY_PRUNED: Final = 13025 +ERROR_IPSEC_IKE_NEG_STATUS_BEGIN: Final = 13800 +ERROR_IPSEC_IKE_AUTH_FAIL: Final = 13801 +ERROR_IPSEC_IKE_ATTRIB_FAIL: Final = 13802 +ERROR_IPSEC_IKE_NEGOTIATION_PENDING: Final = 13803 +ERROR_IPSEC_IKE_GENERAL_PROCESSING_ERROR: Final = 13804 +ERROR_IPSEC_IKE_TIMED_OUT: Final = 13805 +ERROR_IPSEC_IKE_NO_CERT: Final = 13806 +ERROR_IPSEC_IKE_SA_DELETED: Final = 13807 +ERROR_IPSEC_IKE_SA_REAPED: Final = 13808 +ERROR_IPSEC_IKE_MM_ACQUIRE_DROP: Final = 13809 +ERROR_IPSEC_IKE_QM_ACQUIRE_DROP: Final = 13810 +ERROR_IPSEC_IKE_QUEUE_DROP_MM: Final = 13811 +ERROR_IPSEC_IKE_QUEUE_DROP_NO_MM: Final = 13812 +ERROR_IPSEC_IKE_DROP_NO_RESPONSE: Final = 13813 +ERROR_IPSEC_IKE_MM_DELAY_DROP: Final = 13814 +ERROR_IPSEC_IKE_QM_DELAY_DROP: Final = 13815 +ERROR_IPSEC_IKE_ERROR: Final = 13816 +ERROR_IPSEC_IKE_CRL_FAILED: Final = 13817 +ERROR_IPSEC_IKE_INVALID_KEY_USAGE: Final = 13818 +ERROR_IPSEC_IKE_INVALID_CERT_TYPE: Final = 13819 +ERROR_IPSEC_IKE_NO_PRIVATE_KEY: Final = 13820 +ERROR_IPSEC_IKE_SIMULTANEOUS_REKEY: Final = 13821 +ERROR_IPSEC_IKE_DH_FAIL: Final = 13822 +ERROR_IPSEC_IKE_CRITICAL_PAYLOAD_NOT_RECOGNIZED: Final = 13823 +ERROR_IPSEC_IKE_INVALID_HEADER: Final = 13824 +ERROR_IPSEC_IKE_NO_POLICY: Final = 13825 +ERROR_IPSEC_IKE_INVALID_SIGNATURE: Final = 13826 +ERROR_IPSEC_IKE_KERBEROS_ERROR: Final = 13827 +ERROR_IPSEC_IKE_NO_PUBLIC_KEY: Final = 13828 +ERROR_IPSEC_IKE_PROCESS_ERR: Final = 13829 +ERROR_IPSEC_IKE_PROCESS_ERR_SA: Final = 13830 +ERROR_IPSEC_IKE_PROCESS_ERR_PROP: Final = 13831 +ERROR_IPSEC_IKE_PROCESS_ERR_TRANS: Final = 13832 +ERROR_IPSEC_IKE_PROCESS_ERR_KE: Final = 13833 +ERROR_IPSEC_IKE_PROCESS_ERR_ID: Final = 13834 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT: Final = 13835 +ERROR_IPSEC_IKE_PROCESS_ERR_CERT_REQ: Final = 13836 +ERROR_IPSEC_IKE_PROCESS_ERR_HASH: Final = 13837 +ERROR_IPSEC_IKE_PROCESS_ERR_SIG: Final = 13838 +ERROR_IPSEC_IKE_PROCESS_ERR_NONCE: Final = 13839 +ERROR_IPSEC_IKE_PROCESS_ERR_NOTIFY: Final = 13840 +ERROR_IPSEC_IKE_PROCESS_ERR_DELETE: Final = 13841 +ERROR_IPSEC_IKE_PROCESS_ERR_VENDOR: Final = 13842 +ERROR_IPSEC_IKE_INVALID_PAYLOAD: Final = 13843 +ERROR_IPSEC_IKE_LOAD_SOFT_SA: Final = 13844 +ERROR_IPSEC_IKE_SOFT_SA_TORN_DOWN: Final = 13845 +ERROR_IPSEC_IKE_INVALID_COOKIE: Final = 13846 +ERROR_IPSEC_IKE_NO_PEER_CERT: Final = 13847 +ERROR_IPSEC_IKE_PEER_CRL_FAILED: Final = 13848 +ERROR_IPSEC_IKE_POLICY_CHANGE: Final = 13849 +ERROR_IPSEC_IKE_NO_MM_POLICY: Final = 13850 +ERROR_IPSEC_IKE_NOTCBPRIV: Final = 13851 +ERROR_IPSEC_IKE_SECLOADFAIL: Final = 13852 +ERROR_IPSEC_IKE_FAILSSPINIT: Final = 13853 +ERROR_IPSEC_IKE_FAILQUERYSSP: Final = 13854 +ERROR_IPSEC_IKE_SRVACQFAIL: Final = 13855 +ERROR_IPSEC_IKE_SRVQUERYCRED: Final = 13856 +ERROR_IPSEC_IKE_GETSPIFAIL: Final = 13857 +ERROR_IPSEC_IKE_INVALID_FILTER: Final = 13858 +ERROR_IPSEC_IKE_OUT_OF_MEMORY: Final = 13859 +ERROR_IPSEC_IKE_ADD_UPDATE_KEY_FAILED: Final = 13860 +ERROR_IPSEC_IKE_INVALID_POLICY: Final = 13861 +ERROR_IPSEC_IKE_UNKNOWN_DOI: Final = 13862 +ERROR_IPSEC_IKE_INVALID_SITUATION: Final = 13863 +ERROR_IPSEC_IKE_DH_FAILURE: Final = 13864 +ERROR_IPSEC_IKE_INVALID_GROUP: Final = 13865 +ERROR_IPSEC_IKE_ENCRYPT: Final = 13866 +ERROR_IPSEC_IKE_DECRYPT: Final = 13867 +ERROR_IPSEC_IKE_POLICY_MATCH: Final = 13868 +ERROR_IPSEC_IKE_UNSUPPORTED_ID: Final = 13869 +ERROR_IPSEC_IKE_INVALID_HASH: Final = 13870 +ERROR_IPSEC_IKE_INVALID_HASH_ALG: Final = 13871 +ERROR_IPSEC_IKE_INVALID_HASH_SIZE: Final = 13872 +ERROR_IPSEC_IKE_INVALID_ENCRYPT_ALG: Final = 13873 +ERROR_IPSEC_IKE_INVALID_AUTH_ALG: Final = 13874 +ERROR_IPSEC_IKE_INVALID_SIG: Final = 13875 +ERROR_IPSEC_IKE_LOAD_FAILED: Final = 13876 +ERROR_IPSEC_IKE_RPC_DELETE: Final = 13877 +ERROR_IPSEC_IKE_BENIGN_REINIT: Final = 13878 +ERROR_IPSEC_IKE_INVALID_RESPONDER_LIFETIME_NOTIFY: Final = 13879 +ERROR_IPSEC_IKE_INVALID_MAJOR_VERSION: Final = 13880 +ERROR_IPSEC_IKE_INVALID_CERT_KEYLEN: Final = 13881 +ERROR_IPSEC_IKE_MM_LIMIT: Final = 13882 +ERROR_IPSEC_IKE_NEGOTIATION_DISABLED: Final = 13883 +ERROR_IPSEC_IKE_QM_LIMIT: Final = 13884 +ERROR_IPSEC_IKE_MM_EXPIRED: Final = 13885 +ERROR_IPSEC_IKE_PEER_MM_ASSUMED_INVALID: Final = 13886 +ERROR_IPSEC_IKE_CERT_CHAIN_POLICY_MISMATCH: Final = 13887 +ERROR_IPSEC_IKE_UNEXPECTED_MESSAGE_ID: Final = 13888 +ERROR_IPSEC_IKE_INVALID_AUTH_PAYLOAD: Final = 13889 +ERROR_IPSEC_IKE_DOS_COOKIE_SENT: Final = 13890 +ERROR_IPSEC_IKE_SHUTTING_DOWN: Final = 13891 +ERROR_IPSEC_IKE_CGA_AUTH_FAILED: Final = 13892 +ERROR_IPSEC_IKE_PROCESS_ERR_NATOA: Final = 13893 +ERROR_IPSEC_IKE_INVALID_MM_FOR_QM: Final = 13894 +ERROR_IPSEC_IKE_QM_EXPIRED: Final = 13895 +ERROR_IPSEC_IKE_TOO_MANY_FILTERS: Final = 13896 +ERROR_IPSEC_IKE_NEG_STATUS_END: Final = 13897 +ERROR_IPSEC_IKE_KILL_DUMMY_NAP_TUNNEL: Final = 13898 +ERROR_IPSEC_IKE_INNER_IP_ASSIGNMENT_FAILURE: Final = 13899 +ERROR_IPSEC_IKE_REQUIRE_CP_PAYLOAD_MISSING: Final = 13900 +ERROR_IPSEC_KEY_MODULE_IMPERSONATION_NEGOTIATION_PENDING: Final = 13901 +ERROR_IPSEC_IKE_COEXISTENCE_SUPPRESS: Final = 13902 +ERROR_IPSEC_IKE_RATELIMIT_DROP: Final = 13903 +ERROR_IPSEC_IKE_PEER_DOESNT_SUPPORT_MOBIKE: Final = 13904 +ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE: Final = 13905 +ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_FAILURE: Final = 13906 +ERROR_IPSEC_IKE_AUTHORIZATION_FAILURE_WITH_OPTIONAL_RETRY: Final = 13907 +ERROR_IPSEC_IKE_STRONG_CRED_AUTHORIZATION_AND_CERTMAP_FAILURE: Final = 13908 +ERROR_IPSEC_IKE_NEG_STATUS_EXTENDED_END: Final = 13909 +ERROR_IPSEC_BAD_SPI: Final = 13910 +ERROR_IPSEC_SA_LIFETIME_EXPIRED: Final = 13911 +ERROR_IPSEC_WRONG_SA: Final = 13912 +ERROR_IPSEC_REPLAY_CHECK_FAILED: Final = 13913 +ERROR_IPSEC_INVALID_PACKET: Final = 13914 +ERROR_IPSEC_INTEGRITY_CHECK_FAILED: Final = 13915 +ERROR_IPSEC_CLEAR_TEXT_DROP: Final = 13916 +ERROR_IPSEC_AUTH_FIREWALL_DROP: Final = 13917 +ERROR_IPSEC_THROTTLE_DROP: Final = 13918 +ERROR_IPSEC_DOSP_BLOCK: Final = 13925 +ERROR_IPSEC_DOSP_RECEIVED_MULTICAST: Final = 13926 +ERROR_IPSEC_DOSP_INVALID_PACKET: Final = 13927 +ERROR_IPSEC_DOSP_STATE_LOOKUP_FAILED: Final = 13928 +ERROR_IPSEC_DOSP_MAX_ENTRIES: Final = 13929 +ERROR_IPSEC_DOSP_KEYMOD_NOT_ALLOWED: Final = 13930 +ERROR_IPSEC_DOSP_NOT_INSTALLED: Final = 13931 +ERROR_IPSEC_DOSP_MAX_PER_IP_RATELIMIT_QUEUES: Final = 13932 +ERROR_SXS_SECTION_NOT_FOUND: Final = 14000 +ERROR_SXS_CANT_GEN_ACTCTX: Final = 14001 +ERROR_SXS_INVALID_ACTCTXDATA_FORMAT: Final = 14002 +ERROR_SXS_ASSEMBLY_NOT_FOUND: Final = 14003 +ERROR_SXS_MANIFEST_FORMAT_ERROR: Final = 14004 +ERROR_SXS_MANIFEST_PARSE_ERROR: Final = 14005 +ERROR_SXS_ACTIVATION_CONTEXT_DISABLED: Final = 14006 +ERROR_SXS_KEY_NOT_FOUND: Final = 14007 +ERROR_SXS_VERSION_CONFLICT: Final = 14008 +ERROR_SXS_WRONG_SECTION_TYPE: Final = 14009 +ERROR_SXS_THREAD_QUERIES_DISABLED: Final = 14010 +ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET: Final = 14011 +ERROR_SXS_UNKNOWN_ENCODING_GROUP: Final = 14012 +ERROR_SXS_UNKNOWN_ENCODING: Final = 14013 +ERROR_SXS_INVALID_XML_NAMESPACE_URI: Final = 14014 +ERROR_SXS_ROOT_MANIFEST_DEPENDENCY_NOT_INSTALLED: Final = 14015 +ERROR_SXS_LEAF_MANIFEST_DEPENDENCY_NOT_INSTALLED: Final = 14016 +ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE: Final = 14017 +ERROR_SXS_MANIFEST_MISSING_REQUIRED_DEFAULT_NAMESPACE: Final = 14018 +ERROR_SXS_MANIFEST_INVALID_REQUIRED_DEFAULT_NAMESPACE: Final = 14019 +ERROR_SXS_PRIVATE_MANIFEST_CROSS_PATH_WITH_REPARSE_POINT: Final = 14020 +ERROR_SXS_DUPLICATE_DLL_NAME: Final = 14021 +ERROR_SXS_DUPLICATE_WINDOWCLASS_NAME: Final = 14022 +ERROR_SXS_DUPLICATE_CLSID: Final = 14023 +ERROR_SXS_DUPLICATE_IID: Final = 14024 +ERROR_SXS_DUPLICATE_TLBID: Final = 14025 +ERROR_SXS_DUPLICATE_PROGID: Final = 14026 +ERROR_SXS_DUPLICATE_ASSEMBLY_NAME: Final = 14027 +ERROR_SXS_FILE_HASH_MISMATCH: Final = 14028 +ERROR_SXS_POLICY_PARSE_ERROR: Final = 14029 +ERROR_SXS_XML_E_MISSINGQUOTE: Final = 14030 +ERROR_SXS_XML_E_COMMENTSYNTAX: Final = 14031 +ERROR_SXS_XML_E_BADSTARTNAMECHAR: Final = 14032 +ERROR_SXS_XML_E_BADNAMECHAR: Final = 14033 +ERROR_SXS_XML_E_BADCHARINSTRING: Final = 14034 +ERROR_SXS_XML_E_XMLDECLSYNTAX: Final = 14035 +ERROR_SXS_XML_E_BADCHARDATA: Final = 14036 +ERROR_SXS_XML_E_MISSINGWHITESPACE: Final = 14037 +ERROR_SXS_XML_E_EXPECTINGTAGEND: Final = 14038 +ERROR_SXS_XML_E_MISSINGSEMICOLON: Final = 14039 +ERROR_SXS_XML_E_UNBALANCEDPAREN: Final = 14040 +ERROR_SXS_XML_E_INTERNALERROR: Final = 14041 +ERROR_SXS_XML_E_UNEXPECTED_WHITESPACE: Final = 14042 +ERROR_SXS_XML_E_INCOMPLETE_ENCODING: Final = 14043 +ERROR_SXS_XML_E_MISSING_PAREN: Final = 14044 +ERROR_SXS_XML_E_EXPECTINGCLOSEQUOTE: Final = 14045 +ERROR_SXS_XML_E_MULTIPLE_COLONS: Final = 14046 +ERROR_SXS_XML_E_INVALID_DECIMAL: Final = 14047 +ERROR_SXS_XML_E_INVALID_HEXIDECIMAL: Final = 14048 +ERROR_SXS_XML_E_INVALID_UNICODE: Final = 14049 +ERROR_SXS_XML_E_WHITESPACEORQUESTIONMARK: Final = 14050 +ERROR_SXS_XML_E_UNEXPECTEDENDTAG: Final = 14051 +ERROR_SXS_XML_E_UNCLOSEDTAG: Final = 14052 +ERROR_SXS_XML_E_DUPLICATEATTRIBUTE: Final = 14053 +ERROR_SXS_XML_E_MULTIPLEROOTS: Final = 14054 +ERROR_SXS_XML_E_INVALIDATROOTLEVEL: Final = 14055 +ERROR_SXS_XML_E_BADXMLDECL: Final = 14056 +ERROR_SXS_XML_E_MISSINGROOT: Final = 14057 +ERROR_SXS_XML_E_UNEXPECTEDEOF: Final = 14058 +ERROR_SXS_XML_E_BADPEREFINSUBSET: Final = 14059 +ERROR_SXS_XML_E_UNCLOSEDSTARTTAG: Final = 14060 +ERROR_SXS_XML_E_UNCLOSEDENDTAG: Final = 14061 +ERROR_SXS_XML_E_UNCLOSEDSTRING: Final = 14062 +ERROR_SXS_XML_E_UNCLOSEDCOMMENT: Final = 14063 +ERROR_SXS_XML_E_UNCLOSEDDECL: Final = 14064 +ERROR_SXS_XML_E_UNCLOSEDCDATA: Final = 14065 +ERROR_SXS_XML_E_RESERVEDNAMESPACE: Final = 14066 +ERROR_SXS_XML_E_INVALIDENCODING: Final = 14067 +ERROR_SXS_XML_E_INVALIDSWITCH: Final = 14068 +ERROR_SXS_XML_E_BADXMLCASE: Final = 14069 +ERROR_SXS_XML_E_INVALID_STANDALONE: Final = 14070 +ERROR_SXS_XML_E_UNEXPECTED_STANDALONE: Final = 14071 +ERROR_SXS_XML_E_INVALID_VERSION: Final = 14072 +ERROR_SXS_XML_E_MISSINGEQUALS: Final = 14073 +ERROR_SXS_PROTECTION_RECOVERY_FAILED: Final = 14074 +ERROR_SXS_PROTECTION_PUBLIC_KEY_TOO_SHORT: Final = 14075 +ERROR_SXS_PROTECTION_CATALOG_NOT_VALID: Final = 14076 +ERROR_SXS_UNTRANSLATABLE_HRESULT: Final = 14077 +ERROR_SXS_PROTECTION_CATALOG_FILE_MISSING: Final = 14078 +ERROR_SXS_MISSING_ASSEMBLY_IDENTITY_ATTRIBUTE: Final = 14079 +ERROR_SXS_INVALID_ASSEMBLY_IDENTITY_ATTRIBUTE_NAME: Final = 14080 +ERROR_SXS_ASSEMBLY_MISSING: Final = 14081 +ERROR_SXS_CORRUPT_ACTIVATION_STACK: Final = 14082 +ERROR_SXS_CORRUPTION: Final = 14083 +ERROR_SXS_EARLY_DEACTIVATION: Final = 14084 +ERROR_SXS_INVALID_DEACTIVATION: Final = 14085 +ERROR_SXS_MULTIPLE_DEACTIVATION: Final = 14086 +ERROR_SXS_PROCESS_TERMINATION_REQUESTED: Final = 14087 +ERROR_SXS_RELEASE_ACTIVATION_CONTEXT: Final = 14088 +ERROR_SXS_SYSTEM_DEFAULT_ACTIVATION_CONTEXT_EMPTY: Final = 14089 +ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_VALUE: Final = 14090 +ERROR_SXS_INVALID_IDENTITY_ATTRIBUTE_NAME: Final = 14091 +ERROR_SXS_IDENTITY_DUPLICATE_ATTRIBUTE: Final = 14092 +ERROR_SXS_IDENTITY_PARSE_ERROR: Final = 14093 +ERROR_MALFORMED_SUBSTITUTION_STRING: Final = 14094 +ERROR_SXS_INCORRECT_PUBLIC_KEY_TOKEN: Final = 14095 +ERROR_UNMAPPED_SUBSTITUTION_STRING: Final = 14096 +ERROR_SXS_ASSEMBLY_NOT_LOCKED: Final = 14097 +ERROR_SXS_COMPONENT_STORE_CORRUPT: Final = 14098 +ERROR_ADVANCED_INSTALLER_FAILED: Final = 14099 +ERROR_XML_ENCODING_MISMATCH: Final = 14100 +ERROR_SXS_MANIFEST_IDENTITY_SAME_BUT_CONTENTS_DIFFERENT: Final = 14101 +ERROR_SXS_IDENTITIES_DIFFERENT: Final = 14102 +ERROR_SXS_ASSEMBLY_IS_NOT_A_DEPLOYMENT: Final = 14103 +ERROR_SXS_FILE_NOT_PART_OF_ASSEMBLY: Final = 14104 +ERROR_SXS_MANIFEST_TOO_BIG: Final = 14105 +ERROR_SXS_SETTING_NOT_REGISTERED: Final = 14106 +ERROR_SXS_TRANSACTION_CLOSURE_INCOMPLETE: Final = 14107 +ERROR_SMI_PRIMITIVE_INSTALLER_FAILED: Final = 14108 +ERROR_GENERIC_COMMAND_FAILED: Final = 14109 +ERROR_SXS_FILE_HASH_MISSING: Final = 14110 +ERROR_SXS_DUPLICATE_ACTIVATABLE_CLASS: Final = 14111 +ERROR_EVT_INVALID_CHANNEL_PATH: Final = 15000 +ERROR_EVT_INVALID_QUERY: Final = 15001 +ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND: Final = 15002 +ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND: Final = 15003 +ERROR_EVT_INVALID_PUBLISHER_NAME: Final = 15004 +ERROR_EVT_INVALID_EVENT_DATA: Final = 15005 +ERROR_EVT_CHANNEL_NOT_FOUND: Final = 15007 +ERROR_EVT_MALFORMED_XML_TEXT: Final = 15008 +ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL: Final = 15009 +ERROR_EVT_CONFIGURATION_ERROR: Final = 15010 +ERROR_EVT_QUERY_RESULT_STALE: Final = 15011 +ERROR_EVT_QUERY_RESULT_INVALID_POSITION: Final = 15012 +ERROR_EVT_NON_VALIDATING_MSXML: Final = 15013 +ERROR_EVT_FILTER_ALREADYSCOPED: Final = 15014 +ERROR_EVT_FILTER_NOTELTSET: Final = 15015 +ERROR_EVT_FILTER_INVARG: Final = 15016 +ERROR_EVT_FILTER_INVTEST: Final = 15017 +ERROR_EVT_FILTER_INVTYPE: Final = 15018 +ERROR_EVT_FILTER_PARSEERR: Final = 15019 +ERROR_EVT_FILTER_UNSUPPORTEDOP: Final = 15020 +ERROR_EVT_FILTER_UNEXPECTEDTOKEN: Final = 15021 +ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL: Final = 15022 +ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE: Final = 15023 +ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE: Final = 15024 +ERROR_EVT_CHANNEL_CANNOT_ACTIVATE: Final = 15025 +ERROR_EVT_FILTER_TOO_COMPLEX: Final = 15026 +ERROR_EVT_MESSAGE_NOT_FOUND: Final = 15027 +ERROR_EVT_MESSAGE_ID_NOT_FOUND: Final = 15028 +ERROR_EVT_UNRESOLVED_VALUE_INSERT: Final = 15029 +ERROR_EVT_UNRESOLVED_PARAMETER_INSERT: Final = 15030 +ERROR_EVT_MAX_INSERTS_REACHED: Final = 15031 +ERROR_EVT_EVENT_DEFINITION_NOT_FOUND: Final = 15032 +ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND: Final = 15033 +ERROR_EVT_VERSION_TOO_OLD: Final = 15034 +ERROR_EVT_VERSION_TOO_NEW: Final = 15035 +ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY: Final = 15036 +ERROR_EVT_PUBLISHER_DISABLED: Final = 15037 +ERROR_EVT_FILTER_OUT_OF_RANGE: Final = 15038 +ERROR_EC_SUBSCRIPTION_CANNOT_ACTIVATE: Final = 15080 +ERROR_EC_LOG_DISABLED: Final = 15081 +ERROR_EC_CIRCULAR_FORWARDING: Final = 15082 +ERROR_EC_CREDSTORE_FULL: Final = 15083 +ERROR_EC_CRED_NOT_FOUND: Final = 15084 +ERROR_EC_NO_ACTIVE_CHANNEL: Final = 15085 +ERROR_MUI_FILE_NOT_FOUND: Final = 15100 +ERROR_MUI_INVALID_FILE: Final = 15101 +ERROR_MUI_INVALID_RC_CONFIG: Final = 15102 +ERROR_MUI_INVALID_LOCALE_NAME: Final = 15103 +ERROR_MUI_INVALID_ULTIMATEFALLBACK_NAME: Final = 15104 +ERROR_MUI_FILE_NOT_LOADED: Final = 15105 +ERROR_RESOURCE_ENUM_USER_STOP: Final = 15106 +ERROR_MUI_INTLSETTINGS_UILANG_NOT_INSTALLED: Final = 15107 +ERROR_MUI_INTLSETTINGS_INVALID_LOCALE_NAME: Final = 15108 +ERROR_MRM_RUNTIME_NO_DEFAULT_OR_NEUTRAL_RESOURCE: Final = 15110 +ERROR_MRM_INVALID_PRICONFIG: Final = 15111 +ERROR_MRM_INVALID_FILE_TYPE: Final = 15112 +ERROR_MRM_UNKNOWN_QUALIFIER: Final = 15113 +ERROR_MRM_INVALID_QUALIFIER_VALUE: Final = 15114 +ERROR_MRM_NO_CANDIDATE: Final = 15115 +ERROR_MRM_NO_MATCH_OR_DEFAULT_CANDIDATE: Final = 15116 +ERROR_MRM_RESOURCE_TYPE_MISMATCH: Final = 15117 +ERROR_MRM_DUPLICATE_MAP_NAME: Final = 15118 +ERROR_MRM_DUPLICATE_ENTRY: Final = 15119 +ERROR_MRM_INVALID_RESOURCE_IDENTIFIER: Final = 15120 +ERROR_MRM_FILEPATH_TOO_LONG: Final = 15121 +ERROR_MRM_UNSUPPORTED_DIRECTORY_TYPE: Final = 15122 +ERROR_MRM_INVALID_PRI_FILE: Final = 15126 +ERROR_MRM_NAMED_RESOURCE_NOT_FOUND: Final = 15127 +ERROR_MRM_MAP_NOT_FOUND: Final = 15135 +ERROR_MRM_UNSUPPORTED_PROFILE_TYPE: Final = 15136 +ERROR_MRM_INVALID_QUALIFIER_OPERATOR: Final = 15137 +ERROR_MRM_INDETERMINATE_QUALIFIER_VALUE: Final = 15138 +ERROR_MRM_AUTOMERGE_ENABLED: Final = 15139 +ERROR_MRM_TOO_MANY_RESOURCES: Final = 15140 +ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_MERGE: Final = 15141 +ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_LOAD_UNLOAD_PRI_FILE: Final = 15142 +ERROR_MRM_NO_CURRENT_VIEW_ON_THREAD: Final = 15143 +ERROR_DIFFERENT_PROFILE_RESOURCE_MANAGER_EXIST: Final = 15144 +ERROR_OPERATION_NOT_ALLOWED_FROM_SYSTEM_COMPONENT: Final = 15145 +ERROR_MRM_DIRECT_REF_TO_NON_DEFAULT_RESOURCE: Final = 15146 +ERROR_MRM_GENERATION_COUNT_MISMATCH: Final = 15147 +ERROR_PRI_MERGE_VERSION_MISMATCH: Final = 15148 +ERROR_PRI_MERGE_MISSING_SCHEMA: Final = 15149 +ERROR_PRI_MERGE_LOAD_FILE_FAILED: Final = 15150 +ERROR_PRI_MERGE_ADD_FILE_FAILED: Final = 15151 +ERROR_PRI_MERGE_WRITE_FILE_FAILED: Final = 15152 +ERROR_PRI_MERGE_MULTIPLE_PACKAGE_FAMILIES_NOT_ALLOWED: Final = 15153 +ERROR_PRI_MERGE_MULTIPLE_MAIN_PACKAGES_NOT_ALLOWED: Final = 15154 +ERROR_PRI_MERGE_BUNDLE_PACKAGES_NOT_ALLOWED: Final = 15155 +ERROR_PRI_MERGE_MAIN_PACKAGE_REQUIRED: Final = 15156 +ERROR_PRI_MERGE_RESOURCE_PACKAGE_REQUIRED: Final = 15157 +ERROR_PRI_MERGE_INVALID_FILE_NAME: Final = 15158 +ERROR_MRM_PACKAGE_NOT_FOUND: Final = 15159 +ERROR_MRM_MISSING_DEFAULT_LANGUAGE: Final = 15160 +ERROR_MRM_SCOPE_ITEM_CONFLICT: Final = 15161 +ERROR_MCA_INVALID_CAPABILITIES_STRING: Final = 15200 +ERROR_MCA_INVALID_VCP_VERSION: Final = 15201 +ERROR_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: Final = 15202 +ERROR_MCA_MCCS_VERSION_MISMATCH: Final = 15203 +ERROR_MCA_UNSUPPORTED_MCCS_VERSION: Final = 15204 +ERROR_MCA_INTERNAL_ERROR: Final = 15205 +ERROR_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: Final = 15206 +ERROR_MCA_UNSUPPORTED_COLOR_TEMPERATURE: Final = 15207 +ERROR_AMBIGUOUS_SYSTEM_DEVICE: Final = 15250 +ERROR_SYSTEM_DEVICE_NOT_FOUND: Final = 15299 +ERROR_HASH_NOT_SUPPORTED: Final = 15300 +ERROR_HASH_NOT_PRESENT: Final = 15301 +ERROR_SECONDARY_IC_PROVIDER_NOT_REGISTERED: Final = 15321 +ERROR_GPIO_CLIENT_INFORMATION_INVALID: Final = 15322 +ERROR_GPIO_VERSION_NOT_SUPPORTED: Final = 15323 +ERROR_GPIO_INVALID_REGISTRATION_PACKET: Final = 15324 +ERROR_GPIO_OPERATION_DENIED: Final = 15325 +ERROR_GPIO_INCOMPATIBLE_CONNECT_MODE: Final = 15326 +ERROR_GPIO_INTERRUPT_ALREADY_UNMASKED: Final = 15327 +ERROR_CANNOT_SWITCH_RUNLEVEL: Final = 15400 +ERROR_INVALID_RUNLEVEL_SETTING: Final = 15401 +ERROR_RUNLEVEL_SWITCH_TIMEOUT: Final = 15402 +ERROR_RUNLEVEL_SWITCH_AGENT_TIMEOUT: Final = 15403 +ERROR_RUNLEVEL_SWITCH_IN_PROGRESS: Final = 15404 +ERROR_SERVICES_FAILED_AUTOSTART: Final = 15405 +ERROR_COM_TASK_STOP_PENDING: Final = 15501 +ERROR_INSTALL_OPEN_PACKAGE_FAILED: Final = 15600 +ERROR_INSTALL_PACKAGE_NOT_FOUND: Final = 15601 +ERROR_INSTALL_INVALID_PACKAGE: Final = 15602 +ERROR_INSTALL_RESOLVE_DEPENDENCY_FAILED: Final = 15603 +ERROR_INSTALL_OUT_OF_DISK_SPACE: Final = 15604 +ERROR_INSTALL_NETWORK_FAILURE: Final = 15605 +ERROR_INSTALL_REGISTRATION_FAILURE: Final = 15606 +ERROR_INSTALL_DEREGISTRATION_FAILURE: Final = 15607 +ERROR_INSTALL_CANCEL: Final = 15608 +ERROR_INSTALL_FAILED: Final = 15609 +ERROR_REMOVE_FAILED: Final = 15610 +ERROR_PACKAGE_ALREADY_EXISTS: Final = 15611 +ERROR_NEEDS_REMEDIATION: Final = 15612 +ERROR_INSTALL_PREREQUISITE_FAILED: Final = 15613 +ERROR_PACKAGE_REPOSITORY_CORRUPTED: Final = 15614 +ERROR_INSTALL_POLICY_FAILURE: Final = 15615 +ERROR_PACKAGE_UPDATING: Final = 15616 +ERROR_DEPLOYMENT_BLOCKED_BY_POLICY: Final = 15617 +ERROR_PACKAGES_IN_USE: Final = 15618 +ERROR_RECOVERY_FILE_CORRUPT: Final = 15619 +ERROR_INVALID_STAGED_SIGNATURE: Final = 15620 +ERROR_DELETING_EXISTING_APPLICATIONDATA_STORE_FAILED: Final = 15621 +ERROR_INSTALL_PACKAGE_DOWNGRADE: Final = 15622 +ERROR_SYSTEM_NEEDS_REMEDIATION: Final = 15623 +ERROR_APPX_INTEGRITY_FAILURE_CLR_NGEN: Final = 15624 +ERROR_RESILIENCY_FILE_CORRUPT: Final = 15625 +ERROR_INSTALL_FIREWALL_SERVICE_NOT_RUNNING: Final = 15626 +ERROR_PACKAGE_MOVE_FAILED: Final = 15627 +ERROR_INSTALL_VOLUME_NOT_EMPTY: Final = 15628 +ERROR_INSTALL_VOLUME_OFFLINE: Final = 15629 +ERROR_INSTALL_VOLUME_CORRUPT: Final = 15630 +ERROR_NEEDS_REGISTRATION: Final = 15631 +ERROR_INSTALL_WRONG_PROCESSOR_ARCHITECTURE: Final = 15632 +ERROR_DEV_SIDELOAD_LIMIT_EXCEEDED: Final = 15633 +ERROR_INSTALL_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE: Final = 15634 +ERROR_PACKAGE_NOT_SUPPORTED_ON_FILESYSTEM: Final = 15635 +ERROR_PACKAGE_MOVE_BLOCKED_BY_STREAMING: Final = 15636 +ERROR_INSTALL_OPTIONAL_PACKAGE_APPLICATIONID_NOT_UNIQUE: Final = 15637 +ERROR_PACKAGE_STAGING_ONHOLD: Final = 15638 +ERROR_INSTALL_INVALID_RELATED_SET_UPDATE: Final = 15639 +ERROR_INSTALL_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE_FULLTRUST_CAPABILITY: Final = 15640 +ERROR_DEPLOYMENT_BLOCKED_BY_USER_LOG_OFF: Final = 15641 +ERROR_PROVISION_OPTIONAL_PACKAGE_REQUIRES_MAIN_PACKAGE_PROVISIONED: Final = 15642 +ERROR_PACKAGES_REPUTATION_CHECK_FAILED: Final = 15643 +ERROR_PACKAGES_REPUTATION_CHECK_TIMEDOUT: Final = 15644 +ERROR_DEPLOYMENT_OPTION_NOT_SUPPORTED: Final = 15645 +ERROR_APPINSTALLER_ACTIVATION_BLOCKED: Final = 15646 +ERROR_REGISTRATION_FROM_REMOTE_DRIVE_NOT_SUPPORTED: Final = 15647 +ERROR_APPX_RAW_DATA_WRITE_FAILED: Final = 15648 +ERROR_DEPLOYMENT_BLOCKED_BY_VOLUME_POLICY_PACKAGE: Final = 15649 +ERROR_DEPLOYMENT_BLOCKED_BY_VOLUME_POLICY_MACHINE: Final = 15650 +ERROR_DEPLOYMENT_BLOCKED_BY_PROFILE_POLICY: Final = 15651 +ERROR_DEPLOYMENT_FAILED_CONFLICTING_MUTABLE_PACKAGE_DIRECTORY: Final = 15652 +ERROR_SINGLETON_RESOURCE_INSTALLED_IN_ACTIVE_USER: Final = 15653 +ERROR_DIFFERENT_VERSION_OF_PACKAGED_SERVICE_INSTALLED: Final = 15654 +ERROR_SERVICE_EXISTS_AS_NON_PACKAGED_SERVICE: Final = 15655 +ERROR_PACKAGED_SERVICE_REQUIRES_ADMIN_PRIVILEGES: Final = 15656 +ERROR_REDIRECTION_TO_DEFAULT_ACCOUNT_NOT_ALLOWED: Final = 15657 +ERROR_PACKAGE_LACKS_CAPABILITY_TO_DEPLOY_ON_HOST: Final = 15658 +ERROR_UNSIGNED_PACKAGE_INVALID_CONTENT: Final = 15659 +ERROR_UNSIGNED_PACKAGE_INVALID_PUBLISHER_NAMESPACE: Final = 15660 +ERROR_SIGNED_PACKAGE_INVALID_PUBLISHER_NAMESPACE: Final = 15661 +ERROR_PACKAGE_EXTERNAL_LOCATION_NOT_ALLOWED: Final = 15662 +ERROR_INSTALL_FULLTRUST_HOSTRUNTIME_REQUIRES_MAIN_PACKAGE_FULLTRUST_CAPABILITY: Final = 15663 +ERROR_PACKAGE_LACKS_CAPABILITY_FOR_MANDATORY_STARTUPTASKS: Final = 15664 +ERROR_INSTALL_RESOLVE_HOSTRUNTIME_DEPENDENCY_FAILED: Final = 15665 +ERROR_MACHINE_SCOPE_NOT_ALLOWED: Final = 15666 +ERROR_CLASSIC_COMPAT_MODE_NOT_ALLOWED: Final = 15667 +ERROR_STAGEFROMUPDATEAGENT_PACKAGE_NOT_APPLICABLE: Final = 15668 +ERROR_PACKAGE_NOT_REGISTERED_FOR_USER: Final = 15669 +ERROR_PACKAGE_NAME_MISMATCH: Final = 15670 +ERROR_APPINSTALLER_URI_IN_USE: Final = 15671 +ERROR_APPINSTALLER_IS_MANAGED_BY_SYSTEM: Final = 15672 +APPMODEL_ERROR_NO_PACKAGE: Final = 15700 +APPMODEL_ERROR_PACKAGE_RUNTIME_CORRUPT: Final = 15701 +APPMODEL_ERROR_PACKAGE_IDENTITY_CORRUPT: Final = 15702 +APPMODEL_ERROR_NO_APPLICATION: Final = 15703 +APPMODEL_ERROR_DYNAMIC_PROPERTY_READ_FAILED: Final = 15704 +APPMODEL_ERROR_DYNAMIC_PROPERTY_INVALID: Final = 15705 +APPMODEL_ERROR_PACKAGE_NOT_AVAILABLE: Final = 15706 +APPMODEL_ERROR_NO_MUTABLE_DIRECTORY: Final = 15707 +ERROR_STATE_LOAD_STORE_FAILED: Final = 15800 +ERROR_STATE_GET_VERSION_FAILED: Final = 15801 +ERROR_STATE_SET_VERSION_FAILED: Final = 15802 +ERROR_STATE_STRUCTURED_RESET_FAILED: Final = 15803 +ERROR_STATE_OPEN_CONTAINER_FAILED: Final = 15804 +ERROR_STATE_CREATE_CONTAINER_FAILED: Final = 15805 +ERROR_STATE_DELETE_CONTAINER_FAILED: Final = 15806 +ERROR_STATE_READ_SETTING_FAILED: Final = 15807 +ERROR_STATE_WRITE_SETTING_FAILED: Final = 15808 +ERROR_STATE_DELETE_SETTING_FAILED: Final = 15809 +ERROR_STATE_QUERY_SETTING_FAILED: Final = 15810 +ERROR_STATE_READ_COMPOSITE_SETTING_FAILED: Final = 15811 +ERROR_STATE_WRITE_COMPOSITE_SETTING_FAILED: Final = 15812 +ERROR_STATE_ENUMERATE_CONTAINER_FAILED: Final = 15813 +ERROR_STATE_ENUMERATE_SETTINGS_FAILED: Final = 15814 +ERROR_STATE_COMPOSITE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: Final = 15815 +ERROR_STATE_SETTING_VALUE_SIZE_LIMIT_EXCEEDED: Final = 15816 +ERROR_STATE_SETTING_NAME_SIZE_LIMIT_EXCEEDED: Final = 15817 +ERROR_STATE_CONTAINER_NAME_SIZE_LIMIT_EXCEEDED: Final = 15818 +ERROR_API_UNAVAILABLE: Final = 15841 +STORE_ERROR_UNLICENSED: Final = 15861 +STORE_ERROR_UNLICENSED_USER: Final = 15862 +STORE_ERROR_PENDING_COM_TRANSACTION: Final = 15863 +STORE_ERROR_LICENSE_REVOKED: Final = 15864 +SEVERITY_SUCCESS: Final = 0 +SEVERITY_ERROR: Final = 1 + +def SUCCEEDED(hr): ... +def FAILED(hr): ... +def HRESULT_CODE(hr): ... +def SCODE_CODE(sc): ... +def HRESULT_FACILITY(hr): ... +def SCODE_FACILITY(sc): ... +def HRESULT_SEVERITY(hr): ... +def SCODE_SEVERITY(sc): ... + +FACILITY_NT_BIT: Final = 0x10000000 + +def HRESULT_FROM_WIN32(x): ... +def HRESULT_FROM_NT(x): ... +def GetScode(hr): ... +def ResultFromScode(sc): ... + +NOERROR: Final = 0 +E_UNEXPECTED: Final = -2147418113 +E_NOTIMPL: Final = -2147467263 +E_OUTOFMEMORY: Final = -2147024882 +E_INVALIDARG: Final = -2147024809 +E_NOINTERFACE: Final = -2147467262 +E_POINTER: Final = -2147467261 +E_HANDLE: Final = -2147024890 +E_ABORT: Final = -2147467260 +E_FAIL: Final = -2147467259 +E_ACCESSDENIED: Final = -2147024891 +E_PENDING: Final = -2147483638 +E_BOUNDS: Final = -2147483637 +E_CHANGED_STATE: Final = -2147483636 +E_ILLEGAL_STATE_CHANGE: Final = -2147483635 +E_ILLEGAL_METHOD_CALL: Final = -2147483634 +RO_E_METADATA_NAME_NOT_FOUND: Final = -2147483633 +RO_E_METADATA_NAME_IS_NAMESPACE: Final = -2147483632 +RO_E_METADATA_INVALID_TYPE_FORMAT: Final = -2147483631 +RO_E_INVALID_METADATA_FILE: Final = -2147483630 +RO_E_CLOSED: Final = -2147483629 +RO_E_EXCLUSIVE_WRITE: Final = -2147483628 +RO_E_CHANGE_NOTIFICATION_IN_PROGRESS: Final = -2147483627 +RO_E_ERROR_STRING_NOT_FOUND: Final = -2147483626 +E_STRING_NOT_NULL_TERMINATED: Final = -2147483625 +E_ILLEGAL_DELEGATE_ASSIGNMENT: Final = -2147483624 +E_ASYNC_OPERATION_NOT_STARTED: Final = -2147483623 +E_APPLICATION_EXITING: Final = -2147483622 +E_APPLICATION_VIEW_EXITING: Final = -2147483621 +RO_E_MUST_BE_AGILE: Final = -2147483620 +RO_E_UNSUPPORTED_FROM_MTA: Final = -2147483619 +RO_E_COMMITTED: Final = -2147483618 +RO_E_BLOCKED_CROSS_ASTA_CALL: Final = -2147483617 +RO_E_CANNOT_ACTIVATE_FULL_TRUST_SERVER: Final = -2147483616 +RO_E_CANNOT_ACTIVATE_UNIVERSAL_APPLICATION_SERVER: Final = -2147483615 +CO_E_INIT_TLS: Final = -2147467258 +CO_E_INIT_SHARED_ALLOCATOR: Final = -2147467257 +CO_E_INIT_MEMORY_ALLOCATOR: Final = -2147467256 +CO_E_INIT_CLASS_CACHE: Final = -2147467255 +CO_E_INIT_RPC_CHANNEL: Final = -2147467254 +CO_E_INIT_TLS_SET_CHANNEL_CONTROL: Final = -2147467253 +CO_E_INIT_TLS_CHANNEL_CONTROL: Final = -2147467252 +CO_E_INIT_UNACCEPTED_USER_ALLOCATOR: Final = -2147467251 +CO_E_INIT_SCM_MUTEX_EXISTS: Final = -2147467250 +CO_E_INIT_SCM_FILE_MAPPING_EXISTS: Final = -2147467249 +CO_E_INIT_SCM_MAP_VIEW_OF_FILE: Final = -2147467248 +CO_E_INIT_SCM_EXEC_FAILURE: Final = -2147467247 +CO_E_INIT_ONLY_SINGLE_THREADED: Final = -2147467246 +CO_E_CANT_REMOTE: Final = -2147467245 +CO_E_BAD_SERVER_NAME: Final = -2147467244 +CO_E_WRONG_SERVER_IDENTITY: Final = -2147467243 +CO_E_OLE1DDE_DISABLED: Final = -2147467242 +CO_E_RUNAS_SYNTAX: Final = -2147467241 +CO_E_CREATEPROCESS_FAILURE: Final = -2147467240 +CO_E_RUNAS_CREATEPROCESS_FAILURE: Final = -2147467239 +CO_E_RUNAS_LOGON_FAILURE: Final = -2147467238 +CO_E_LAUNCH_PERMSSION_DENIED: Final = -2147467237 +CO_E_START_SERVICE_FAILURE: Final = -2147467236 +CO_E_REMOTE_COMMUNICATION_FAILURE: Final = -2147467235 +CO_E_SERVER_START_TIMEOUT: Final = -2147467234 +CO_E_CLSREG_INCONSISTENT: Final = -2147467233 +CO_E_IIDREG_INCONSISTENT: Final = -2147467232 +CO_E_NOT_SUPPORTED: Final = -2147467231 +CO_E_RELOAD_DLL: Final = -2147467230 +CO_E_MSI_ERROR: Final = -2147467229 +CO_E_ATTEMPT_TO_CREATE_OUTSIDE_CLIENT_CONTEXT: Final = -2147467228 +CO_E_SERVER_PAUSED: Final = -2147467227 +CO_E_SERVER_NOT_PAUSED: Final = -2147467226 +CO_E_CLASS_DISABLED: Final = -2147467225 +CO_E_CLRNOTAVAILABLE: Final = -2147467224 +CO_E_ASYNC_WORK_REJECTED: Final = -2147467223 +CO_E_SERVER_INIT_TIMEOUT: Final = -2147467222 +CO_E_NO_SECCTX_IN_ACTIVATE: Final = -2147467221 +CO_E_TRACKER_CONFIG: Final = -2147467216 +CO_E_THREADPOOL_CONFIG: Final = -2147467215 +CO_E_SXS_CONFIG: Final = -2147467214 +CO_E_MALFORMED_SPN: Final = -2147467213 +CO_E_UNREVOKED_REGISTRATION_ON_APARTMENT_SHUTDOWN: Final = -2147467212 +CO_E_PREMATURE_STUB_RUNDOWN: Final = -2147467211 +S_OK: Final = 0 +S_FALSE: Final = 1 +OLE_E_FIRST: Final = -2147221504 +OLE_E_LAST: Final = -2147221249 +OLE_S_FIRST: Final = 0x00040000 +OLE_S_LAST: Final = 0x000400FF +OLE_E_OLEVERB: Final = -2147221504 +OLE_E_ADVF: Final = -2147221503 +OLE_E_ENUM_NOMORE: Final = -2147221502 +OLE_E_ADVISENOTSUPPORTED: Final = -2147221501 +OLE_E_NOCONNECTION: Final = -2147221500 +OLE_E_NOTRUNNING: Final = -2147221499 +OLE_E_NOCACHE: Final = -2147221498 +OLE_E_BLANK: Final = -2147221497 +OLE_E_CLASSDIFF: Final = -2147221496 +OLE_E_CANT_GETMONIKER: Final = -2147221495 +OLE_E_CANT_BINDTOSOURCE: Final = -2147221494 +OLE_E_STATIC: Final = -2147221493 +OLE_E_PROMPTSAVECANCELLED: Final = -2147221492 +OLE_E_INVALIDRECT: Final = -2147221491 +OLE_E_WRONGCOMPOBJ: Final = -2147221490 +OLE_E_INVALIDHWND: Final = -2147221489 +OLE_E_NOT_INPLACEACTIVE: Final = -2147221488 +OLE_E_CANTCONVERT: Final = -2147221487 +OLE_E_NOSTORAGE: Final = -2147221486 +DV_E_FORMATETC: Final = -2147221404 +DV_E_DVTARGETDEVICE: Final = -2147221403 +DV_E_STGMEDIUM: Final = -2147221402 +DV_E_STATDATA: Final = -2147221401 +DV_E_LINDEX: Final = -2147221400 +DV_E_TYMED: Final = -2147221399 +DV_E_CLIPFORMAT: Final = -2147221398 +DV_E_DVASPECT: Final = -2147221397 +DV_E_DVTARGETDEVICE_SIZE: Final = -2147221396 +DV_E_NOIVIEWOBJECT: Final = -2147221395 +DRAGDROP_E_FIRST: Final = -2147221248 +DRAGDROP_E_LAST: Final = -2147221233 +DRAGDROP_S_FIRST: Final = 0x00040100 +DRAGDROP_S_LAST: Final = 0x0004010F +DRAGDROP_E_NOTREGISTERED: Final = -2147221248 +DRAGDROP_E_ALREADYREGISTERED: Final = -2147221247 +DRAGDROP_E_INVALIDHWND: Final = -2147221246 +DRAGDROP_E_CONCURRENT_DRAG_ATTEMPTED: Final = -2147221245 +CLASSFACTORY_E_FIRST: Final = -2147221232 +CLASSFACTORY_E_LAST: Final = -2147221217 +CLASSFACTORY_S_FIRST: Final = 0x00040110 +CLASSFACTORY_S_LAST: Final = 0x0004011F +CLASS_E_NOAGGREGATION: Final = -2147221232 +CLASS_E_CLASSNOTAVAILABLE: Final = -2147221231 +CLASS_E_NOTLICENSED: Final = -2147221230 +MARSHAL_E_FIRST: Final = -2147221216 +MARSHAL_E_LAST: Final = -2147221201 +MARSHAL_S_FIRST: Final = 0x00040120 +MARSHAL_S_LAST: Final = 0x0004012F +DATA_E_FIRST: Final = -2147221200 +DATA_E_LAST: Final = -2147221185 +DATA_S_FIRST: Final = 0x00040130 +DATA_S_LAST: Final = 0x0004013F +VIEW_E_FIRST: Final = -2147221184 +VIEW_E_LAST: Final = -2147221169 +VIEW_S_FIRST: Final = 0x00040140 +VIEW_S_LAST: Final = 0x0004014F +VIEW_E_DRAW: Final = -2147221184 +REGDB_E_FIRST: Final = -2147221168 +REGDB_E_LAST: Final = -2147221153 +REGDB_S_FIRST: Final = 0x00040150 +REGDB_S_LAST: Final = 0x0004015F +REGDB_E_READREGDB: Final = -2147221168 +REGDB_E_WRITEREGDB: Final = -2147221167 +REGDB_E_KEYMISSING: Final = -2147221166 +REGDB_E_INVALIDVALUE: Final = -2147221165 +REGDB_E_CLASSNOTREG: Final = -2147221164 +REGDB_E_IIDNOTREG: Final = -2147221163 +REGDB_E_BADTHREADINGMODEL: Final = -2147221162 +REGDB_E_PACKAGEPOLICYVIOLATION: Final = -2147221161 +CAT_E_FIRST: Final = -2147221152 +CAT_E_LAST: Final = -2147221151 +CAT_E_CATIDNOEXIST: Final = -2147221152 +CAT_E_NODESCRIPTION: Final = -2147221151 +CS_E_FIRST: Final = -2147221148 +CS_E_LAST: Final = -2147221137 +CS_E_PACKAGE_NOTFOUND: Final = -2147221148 +CS_E_NOT_DELETABLE: Final = -2147221147 +CS_E_CLASS_NOTFOUND: Final = -2147221146 +CS_E_INVALID_VERSION: Final = -2147221145 +CS_E_NO_CLASSSTORE: Final = -2147221144 +CS_E_OBJECT_NOTFOUND: Final = -2147221143 +CS_E_OBJECT_ALREADY_EXISTS: Final = -2147221142 +CS_E_INVALID_PATH: Final = -2147221141 +CS_E_NETWORK_ERROR: Final = -2147221140 +CS_E_ADMIN_LIMIT_EXCEEDED: Final = -2147221139 +CS_E_SCHEMA_MISMATCH: Final = -2147221138 +CS_E_INTERNAL_ERROR: Final = -2147221137 +CACHE_E_FIRST: Final = -2147221136 +CACHE_E_LAST: Final = -2147221121 +CACHE_S_FIRST: Final = 0x00040170 +CACHE_S_LAST: Final = 0x0004017F +CACHE_E_NOCACHE_UPDATED: Final = -2147221136 +OLEOBJ_E_FIRST: Final = -2147221120 +OLEOBJ_E_LAST: Final = -2147221105 +OLEOBJ_S_FIRST: Final = 0x00040180 +OLEOBJ_S_LAST: Final = 0x0004018F +OLEOBJ_E_NOVERBS: Final = -2147221120 +OLEOBJ_E_INVALIDVERB: Final = -2147221119 +CLIENTSITE_E_FIRST: Final = -2147221104 +CLIENTSITE_E_LAST: Final = -2147221089 +CLIENTSITE_S_FIRST: Final = 0x00040190 +CLIENTSITE_S_LAST: Final = 0x0004019F +INPLACE_E_NOTUNDOABLE: Final = -2147221088 +INPLACE_E_NOTOOLSPACE: Final = -2147221087 +INPLACE_E_FIRST: Final = -2147221088 +INPLACE_E_LAST: Final = -2147221073 +INPLACE_S_FIRST: Final = 0x000401A0 +INPLACE_S_LAST: Final = 0x000401AF +ENUM_E_FIRST: Final = -2147221072 +ENUM_E_LAST: Final = -2147221057 +ENUM_S_FIRST: Final = 0x000401B0 +ENUM_S_LAST: Final = 0x000401BF +CONVERT10_E_FIRST: Final = -2147221056 +CONVERT10_E_LAST: Final = -2147221041 +CONVERT10_S_FIRST: Final = 0x000401C0 +CONVERT10_S_LAST: Final = 0x000401CF +CONVERT10_E_OLESTREAM_GET: Final = -2147221056 +CONVERT10_E_OLESTREAM_PUT: Final = -2147221055 +CONVERT10_E_OLESTREAM_FMT: Final = -2147221054 +CONVERT10_E_OLESTREAM_BITMAP_TO_DIB: Final = -2147221053 +CONVERT10_E_STG_FMT: Final = -2147221052 +CONVERT10_E_STG_NO_STD_STREAM: Final = -2147221051 +CONVERT10_E_STG_DIB_TO_BITMAP: Final = -2147221050 +CONVERT10_E_OLELINK_DISABLED: Final = -2147221049 +CLIPBRD_E_FIRST: Final = -2147221040 +CLIPBRD_E_LAST: Final = -2147221025 +CLIPBRD_S_FIRST: Final = 0x000401D0 +CLIPBRD_S_LAST: Final = 0x000401DF +CLIPBRD_E_CANT_OPEN: Final = -2147221040 +CLIPBRD_E_CANT_EMPTY: Final = -2147221039 +CLIPBRD_E_CANT_SET: Final = -2147221038 +CLIPBRD_E_BAD_DATA: Final = -2147221037 +CLIPBRD_E_CANT_CLOSE: Final = -2147221036 +MK_E_FIRST: Final = -2147221024 +MK_E_LAST: Final = -2147221009 +MK_S_FIRST: Final = 0x000401E0 +MK_S_LAST: Final = 0x000401EF +MK_E_CONNECTMANUALLY: Final = -2147221024 +MK_E_EXCEEDEDDEADLINE: Final = -2147221023 +MK_E_NEEDGENERIC: Final = -2147221022 +MK_E_UNAVAILABLE: Final = -2147221021 +MK_E_SYNTAX: Final = -2147221020 +MK_E_NOOBJECT: Final = -2147221019 +MK_E_INVALIDEXTENSION: Final = -2147221018 +MK_E_INTERMEDIATEINTERFACENOTSUPPORTED: Final = -2147221017 +MK_E_NOTBINDABLE: Final = -2147221016 +MK_E_NOTBOUND: Final = -2147221015 +MK_E_CANTOPENFILE: Final = -2147221014 +MK_E_MUSTBOTHERUSER: Final = -2147221013 +MK_E_NOINVERSE: Final = -2147221012 +MK_E_NOSTORAGE: Final = -2147221011 +MK_E_NOPREFIX: Final = -2147221010 +MK_E_ENUMERATION_FAILED: Final = -2147221009 +CO_E_FIRST: Final = -2147221008 +CO_E_LAST: Final = -2147220993 +CO_S_FIRST: Final = 0x000401F0 +CO_S_LAST: Final = 0x000401FF +CO_E_NOTINITIALIZED: Final = -2147221008 +CO_E_ALREADYINITIALIZED: Final = -2147221007 +CO_E_CANTDETERMINECLASS: Final = -2147221006 +CO_E_CLASSSTRING: Final = -2147221005 +CO_E_IIDSTRING: Final = -2147221004 +CO_E_APPNOTFOUND: Final = -2147221003 +CO_E_APPSINGLEUSE: Final = -2147221002 +CO_E_ERRORINAPP: Final = -2147221001 +CO_E_DLLNOTFOUND: Final = -2147221000 +CO_E_ERRORINDLL: Final = -2147220999 +CO_E_WRONGOSFORAPP: Final = -2147220998 +CO_E_OBJNOTREG: Final = -2147220997 +CO_E_OBJISREG: Final = -2147220996 +CO_E_OBJNOTCONNECTED: Final = -2147220995 +CO_E_APPDIDNTREG: Final = -2147220994 +CO_E_RELEASED: Final = -2147220993 +EVENT_E_FIRST: Final = -2147220992 +EVENT_E_LAST: Final = -2147220961 +EVENT_S_FIRST: Final = 0x00040200 +EVENT_S_LAST: Final = 0x0004021F +EVENT_S_SOME_SUBSCRIBERS_FAILED: Final = 0x00040200 +EVENT_E_ALL_SUBSCRIBERS_FAILED: Final = -2147220991 +EVENT_S_NOSUBSCRIBERS: Final = 0x00040202 +EVENT_E_QUERYSYNTAX: Final = -2147220989 +EVENT_E_QUERYFIELD: Final = -2147220988 +EVENT_E_INTERNALEXCEPTION: Final = -2147220987 +EVENT_E_INTERNALERROR: Final = -2147220986 +EVENT_E_INVALID_PER_USER_SID: Final = -2147220985 +EVENT_E_USER_EXCEPTION: Final = -2147220984 +EVENT_E_TOO_MANY_METHODS: Final = -2147220983 +EVENT_E_MISSING_EVENTCLASS: Final = -2147220982 +EVENT_E_NOT_ALL_REMOVED: Final = -2147220981 +EVENT_E_COMPLUS_NOT_INSTALLED: Final = -2147220980 +EVENT_E_CANT_MODIFY_OR_DELETE_UNCONFIGURED_OBJECT: Final = -2147220979 +EVENT_E_CANT_MODIFY_OR_DELETE_CONFIGURED_OBJECT: Final = -2147220978 +EVENT_E_INVALID_EVENT_CLASS_PARTITION: Final = -2147220977 +EVENT_E_PER_USER_SID_NOT_LOGGED_ON: Final = -2147220976 +TPC_E_INVALID_PROPERTY: Final = -2147220927 +TPC_E_NO_DEFAULT_TABLET: Final = -2147220974 +TPC_E_UNKNOWN_PROPERTY: Final = -2147220965 +TPC_E_INVALID_INPUT_RECT: Final = -2147220967 +TPC_E_INVALID_STROKE: Final = -2147220958 +TPC_E_INITIALIZE_FAIL: Final = -2147220957 +TPC_E_NOT_RELEVANT: Final = -2147220942 +TPC_E_INVALID_PACKET_DESCRIPTION: Final = -2147220941 +TPC_E_RECOGNIZER_NOT_REGISTERED: Final = -2147220939 +TPC_E_INVALID_RIGHTS: Final = -2147220938 +TPC_E_OUT_OF_ORDER_CALL: Final = -2147220937 +TPC_E_QUEUE_FULL: Final = -2147220936 +TPC_E_INVALID_CONFIGURATION: Final = -2147220935 +TPC_E_INVALID_DATA_FROM_RECOGNIZER: Final = -2147220934 +TPC_S_TRUNCATED: Final = 0x00040252 +TPC_S_INTERRUPTED: Final = 0x00040253 +TPC_S_NO_DATA_TO_PROCESS: Final = 0x00040254 +XACT_E_FIRST: Final = -2147168256 +XACT_E_LAST: Final = -2147168213 +XACT_S_FIRST: Final = 0x0004D000 +XACT_S_LAST: Final = 0x0004D010 +XACT_E_ALREADYOTHERSINGLEPHASE: Final = -2147168256 +XACT_E_CANTRETAIN: Final = -2147168255 +XACT_E_COMMITFAILED: Final = -2147168254 +XACT_E_COMMITPREVENTED: Final = -2147168253 +XACT_E_HEURISTICABORT: Final = -2147168252 +XACT_E_HEURISTICCOMMIT: Final = -2147168251 +XACT_E_HEURISTICDAMAGE: Final = -2147168250 +XACT_E_HEURISTICDANGER: Final = -2147168249 +XACT_E_ISOLATIONLEVEL: Final = -2147168248 +XACT_E_NOASYNC: Final = -2147168247 +XACT_E_NOENLIST: Final = -2147168246 +XACT_E_NOISORETAIN: Final = -2147168245 +XACT_E_NORESOURCE: Final = -2147168244 +XACT_E_NOTCURRENT: Final = -2147168243 +XACT_E_NOTRANSACTION: Final = -2147168242 +XACT_E_NOTSUPPORTED: Final = -2147168241 +XACT_E_UNKNOWNRMGRID: Final = -2147168240 +XACT_E_WRONGSTATE: Final = -2147168239 +XACT_E_WRONGUOW: Final = -2147168238 +XACT_E_XTIONEXISTS: Final = -2147168237 +XACT_E_NOIMPORTOBJECT: Final = -2147168236 +XACT_E_INVALIDCOOKIE: Final = -2147168235 +XACT_E_INDOUBT: Final = -2147168234 +XACT_E_NOTIMEOUT: Final = -2147168233 +XACT_E_ALREADYINPROGRESS: Final = -2147168232 +XACT_E_ABORTED: Final = -2147168231 +XACT_E_LOGFULL: Final = -2147168230 +XACT_E_TMNOTAVAILABLE: Final = -2147168229 +XACT_E_CONNECTION_DOWN: Final = -2147168228 +XACT_E_CONNECTION_DENIED: Final = -2147168227 +XACT_E_REENLISTTIMEOUT: Final = -2147168226 +XACT_E_TIP_CONNECT_FAILED: Final = -2147168225 +XACT_E_TIP_PROTOCOL_ERROR: Final = -2147168224 +XACT_E_TIP_PULL_FAILED: Final = -2147168223 +XACT_E_DEST_TMNOTAVAILABLE: Final = -2147168222 +XACT_E_TIP_DISABLED: Final = -2147168221 +XACT_E_NETWORK_TX_DISABLED: Final = -2147168220 +XACT_E_PARTNER_NETWORK_TX_DISABLED: Final = -2147168219 +XACT_E_XA_TX_DISABLED: Final = -2147168218 +XACT_E_UNABLE_TO_READ_DTC_CONFIG: Final = -2147168217 +XACT_E_UNABLE_TO_LOAD_DTC_PROXY: Final = -2147168216 +XACT_E_ABORTING: Final = -2147168215 +XACT_E_PUSH_COMM_FAILURE: Final = -2147168214 +XACT_E_PULL_COMM_FAILURE: Final = -2147168213 +XACT_E_LU_TX_DISABLED: Final = -2147168212 +XACT_E_CLERKNOTFOUND: Final = -2147168128 +XACT_E_CLERKEXISTS: Final = -2147168127 +XACT_E_RECOVERYINPROGRESS: Final = -2147168126 +XACT_E_TRANSACTIONCLOSED: Final = -2147168125 +XACT_E_INVALIDLSN: Final = -2147168124 +XACT_E_REPLAYREQUEST: Final = -2147168123 +XACT_S_ASYNC: Final = 0x0004D000 +XACT_S_DEFECT: Final = 0x0004D001 +XACT_S_READONLY: Final = 0x0004D002 +XACT_S_SOMENORETAIN: Final = 0x0004D003 +XACT_S_OKINFORM: Final = 0x0004D004 +XACT_S_MADECHANGESCONTENT: Final = 0x0004D005 +XACT_S_MADECHANGESINFORM: Final = 0x0004D006 +XACT_S_ALLNORETAIN: Final = 0x0004D007 +XACT_S_ABORTING: Final = 0x0004D008 +XACT_S_SINGLEPHASE: Final = 0x0004D009 +XACT_S_LOCALLY_OK: Final = 0x0004D00A +XACT_S_LASTRESOURCEMANAGER: Final = 0x0004D010 +CONTEXT_E_FIRST: Final = -2147164160 +CONTEXT_E_LAST: Final = -2147164113 +CONTEXT_S_FIRST: Final = 0x0004E000 +CONTEXT_S_LAST: Final = 0x0004E02F +CONTEXT_E_ABORTED: Final = -2147164158 +CONTEXT_E_ABORTING: Final = -2147164157 +CONTEXT_E_NOCONTEXT: Final = -2147164156 +CONTEXT_E_WOULD_DEADLOCK: Final = -2147164155 +CONTEXT_E_SYNCH_TIMEOUT: Final = -2147164154 +CONTEXT_E_OLDREF: Final = -2147164153 +CONTEXT_E_ROLENOTFOUND: Final = -2147164148 +CONTEXT_E_TMNOTAVAILABLE: Final = -2147164145 +CO_E_ACTIVATIONFAILED: Final = -2147164127 +CO_E_ACTIVATIONFAILED_EVENTLOGGED: Final = -2147164126 +CO_E_ACTIVATIONFAILED_CATALOGERROR: Final = -2147164125 +CO_E_ACTIVATIONFAILED_TIMEOUT: Final = -2147164124 +CO_E_INITIALIZATIONFAILED: Final = -2147164123 +CONTEXT_E_NOJIT: Final = -2147164122 +CONTEXT_E_NOTRANSACTION: Final = -2147164121 +CO_E_THREADINGMODEL_CHANGED: Final = -2147164120 +CO_E_NOIISINTRINSICS: Final = -2147164119 +CO_E_NOCOOKIES: Final = -2147164118 +CO_E_DBERROR: Final = -2147164117 +CO_E_NOTPOOLED: Final = -2147164116 +CO_E_NOTCONSTRUCTED: Final = -2147164115 +CO_E_NOSYNCHRONIZATION: Final = -2147164114 +CO_E_ISOLEVELMISMATCH: Final = -2147164113 +CO_E_CALL_OUT_OF_TX_SCOPE_NOT_ALLOWED: Final = -2147164112 +CO_E_EXIT_TRANSACTION_SCOPE_NOT_CALLED: Final = -2147164111 +OLE_S_USEREG: Final = 0x00040000 +OLE_S_STATIC: Final = 0x00040001 +OLE_S_MAC_CLIPFORMAT: Final = 0x00040002 +DRAGDROP_S_DROP: Final = 0x00040100 +DRAGDROP_S_CANCEL: Final = 0x00040101 +DRAGDROP_S_USEDEFAULTCURSORS: Final = 0x00040102 +DATA_S_SAMEFORMATETC: Final = 0x00040130 +VIEW_S_ALREADY_FROZEN: Final = 0x00040140 +CACHE_S_FORMATETC_NOTSUPPORTED: Final = 0x00040170 +CACHE_S_SAMECACHE: Final = 0x00040171 +CACHE_S_SOMECACHES_NOTUPDATED: Final = 0x00040172 +OLEOBJ_S_INVALIDVERB: Final = 0x00040180 +OLEOBJ_S_CANNOT_DOVERB_NOW: Final = 0x00040181 +OLEOBJ_S_INVALIDHWND: Final = 0x00040182 +INPLACE_S_TRUNCATED: Final = 0x000401A0 +CONVERT10_S_NO_PRESENTATION: Final = 0x000401C0 +MK_S_REDUCED_TO_SELF: Final = 0x000401E2 +MK_S_ME: Final = 0x000401E4 +MK_S_HIM: Final = 0x000401E5 +MK_S_US: Final = 0x000401E6 +MK_S_MONIKERALREADYREGISTERED: Final = 0x000401E7 +SCHED_S_TASK_READY: Final = 0x00041300 +SCHED_S_TASK_RUNNING: Final = 0x00041301 +SCHED_S_TASK_DISABLED: Final = 0x00041302 +SCHED_S_TASK_HAS_NOT_RUN: Final = 0x00041303 +SCHED_S_TASK_NO_MORE_RUNS: Final = 0x00041304 +SCHED_S_TASK_NOT_SCHEDULED: Final = 0x00041305 +SCHED_S_TASK_TERMINATED: Final = 0x00041306 +SCHED_S_TASK_NO_VALID_TRIGGERS: Final = 0x00041307 +SCHED_S_EVENT_TRIGGER: Final = 0x00041308 +SCHED_E_TRIGGER_NOT_FOUND: Final = -2147216631 +SCHED_E_TASK_NOT_READY: Final = -2147216630 +SCHED_E_TASK_NOT_RUNNING: Final = -2147216629 +SCHED_E_SERVICE_NOT_INSTALLED: Final = -2147216628 +SCHED_E_CANNOT_OPEN_TASK: Final = -2147216627 +SCHED_E_INVALID_TASK: Final = -2147216626 +SCHED_E_ACCOUNT_INFORMATION_NOT_SET: Final = -2147216625 +SCHED_E_ACCOUNT_NAME_NOT_FOUND: Final = -2147216624 +SCHED_E_ACCOUNT_DBASE_CORRUPT: Final = -2147216623 +SCHED_E_NO_SECURITY_SERVICES: Final = -2147216622 +SCHED_E_UNKNOWN_OBJECT_VERSION: Final = -2147216621 +SCHED_E_UNSUPPORTED_ACCOUNT_OPTION: Final = -2147216620 +SCHED_E_SERVICE_NOT_RUNNING: Final = -2147216619 +SCHED_E_UNEXPECTEDNODE: Final = -2147216618 +SCHED_E_NAMESPACE: Final = -2147216617 +SCHED_E_INVALIDVALUE: Final = -2147216616 +SCHED_E_MISSINGNODE: Final = -2147216615 +SCHED_E_MALFORMEDXML: Final = -2147216614 +SCHED_S_SOME_TRIGGERS_FAILED: Final = 0x0004131B +SCHED_S_BATCH_LOGON_PROBLEM: Final = 0x0004131C +SCHED_E_TOO_MANY_NODES: Final = -2147216611 +SCHED_E_PAST_END_BOUNDARY: Final = -2147216610 +SCHED_E_ALREADY_RUNNING: Final = -2147216609 +SCHED_E_USER_NOT_LOGGED_ON: Final = -2147216608 +SCHED_E_INVALID_TASK_HASH: Final = -2147216607 +SCHED_E_SERVICE_NOT_AVAILABLE: Final = -2147216606 +SCHED_E_SERVICE_TOO_BUSY: Final = -2147216605 +SCHED_E_TASK_ATTEMPTED: Final = -2147216604 +SCHED_S_TASK_QUEUED: Final = 0x00041325 +SCHED_E_TASK_DISABLED: Final = -2147216602 +SCHED_E_TASK_NOT_V1_COMPAT: Final = -2147216601 +SCHED_E_START_ON_DEMAND: Final = -2147216600 +SCHED_E_TASK_NOT_UBPM_COMPAT: Final = -2147216599 +SCHED_E_DEPRECATED_FEATURE_USED: Final = -2147216592 +CO_E_CLASS_CREATE_FAILED: Final = -2146959359 +CO_E_SCM_ERROR: Final = -2146959358 +CO_E_SCM_RPC_FAILURE: Final = -2146959357 +CO_E_BAD_PATH: Final = -2146959356 +CO_E_SERVER_EXEC_FAILURE: Final = -2146959355 +CO_E_OBJSRV_RPC_FAILURE: Final = -2146959354 +MK_E_NO_NORMALIZED: Final = -2146959353 +CO_E_SERVER_STOPPING: Final = -2146959352 +MEM_E_INVALID_ROOT: Final = -2146959351 +MEM_E_INVALID_LINK: Final = -2146959344 +MEM_E_INVALID_SIZE: Final = -2146959343 +CO_S_NOTALLINTERFACES: Final = 0x00080012 +CO_S_MACHINENAMENOTFOUND: Final = 0x00080013 +CO_E_MISSING_DISPLAYNAME: Final = -2146959339 +CO_E_RUNAS_VALUE_MUST_BE_AAA: Final = -2146959338 +CO_E_ELEVATION_DISABLED: Final = -2146959337 +APPX_E_PACKAGING_INTERNAL: Final = -2146958848 +APPX_E_INTERLEAVING_NOT_ALLOWED: Final = -2146958847 +APPX_E_RELATIONSHIPS_NOT_ALLOWED: Final = -2146958846 +APPX_E_MISSING_REQUIRED_FILE: Final = -2146958845 +APPX_E_INVALID_MANIFEST: Final = -2146958844 +APPX_E_INVALID_BLOCKMAP: Final = -2146958843 +APPX_E_CORRUPT_CONTENT: Final = -2146958842 +APPX_E_BLOCK_HASH_INVALID: Final = -2146958841 +APPX_E_REQUESTED_RANGE_TOO_LARGE: Final = -2146958840 +APPX_E_INVALID_SIP_CLIENT_DATA: Final = -2146958839 +APPX_E_INVALID_KEY_INFO: Final = -2146958838 +APPX_E_INVALID_CONTENTGROUPMAP: Final = -2146958837 +APPX_E_INVALID_APPINSTALLER: Final = -2146958836 +APPX_E_DELTA_BASELINE_VERSION_MISMATCH: Final = -2146958835 +APPX_E_DELTA_PACKAGE_MISSING_FILE: Final = -2146958834 +APPX_E_INVALID_DELTA_PACKAGE: Final = -2146958833 +APPX_E_DELTA_APPENDED_PACKAGE_NOT_ALLOWED: Final = -2146958832 +APPX_E_INVALID_PACKAGING_LAYOUT: Final = -2146958831 +APPX_E_INVALID_PACKAGESIGNCONFIG: Final = -2146958830 +APPX_E_RESOURCESPRI_NOT_ALLOWED: Final = -2146958829 +APPX_E_FILE_COMPRESSION_MISMATCH: Final = -2146958828 +APPX_E_INVALID_PAYLOAD_PACKAGE_EXTENSION: Final = -2146958827 +APPX_E_INVALID_ENCRYPTION_EXCLUSION_FILE_LIST: Final = -2146958826 +APPX_E_INVALID_PACKAGE_FOLDER_ACLS: Final = -2146958825 +APPX_E_INVALID_PUBLISHER_BRIDGING: Final = -2146958824 +APPX_E_DIGEST_MISMATCH: Final = -2146958823 +BT_E_SPURIOUS_ACTIVATION: Final = -2146958592 +DISP_E_UNKNOWNINTERFACE: Final = -2147352575 +DISP_E_MEMBERNOTFOUND: Final = -2147352573 +DISP_E_PARAMNOTFOUND: Final = -2147352572 +DISP_E_TYPEMISMATCH: Final = -2147352571 +DISP_E_UNKNOWNNAME: Final = -2147352570 +DISP_E_NONAMEDARGS: Final = -2147352569 +DISP_E_BADVARTYPE: Final = -2147352568 +DISP_E_EXCEPTION: Final = -2147352567 +DISP_E_OVERFLOW: Final = -2147352566 +DISP_E_BADINDEX: Final = -2147352565 +DISP_E_UNKNOWNLCID: Final = -2147352564 +DISP_E_ARRAYISLOCKED: Final = -2147352563 +DISP_E_BADPARAMCOUNT: Final = -2147352562 +DISP_E_PARAMNOTOPTIONAL: Final = -2147352561 +DISP_E_BADCALLEE: Final = -2147352560 +DISP_E_NOTACOLLECTION: Final = -2147352559 +DISP_E_DIVBYZERO: Final = -2147352558 +DISP_E_BUFFERTOOSMALL: Final = -2147352557 +TYPE_E_BUFFERTOOSMALL: Final = -2147319786 +TYPE_E_FIELDNOTFOUND: Final = -2147319785 +TYPE_E_INVDATAREAD: Final = -2147319784 +TYPE_E_UNSUPFORMAT: Final = -2147319783 +TYPE_E_REGISTRYACCESS: Final = -2147319780 +TYPE_E_LIBNOTREGISTERED: Final = -2147319779 +TYPE_E_UNDEFINEDTYPE: Final = -2147319769 +TYPE_E_QUALIFIEDNAMEDISALLOWED: Final = -2147319768 +TYPE_E_INVALIDSTATE: Final = -2147319767 +TYPE_E_WRONGTYPEKIND: Final = -2147319766 +TYPE_E_ELEMENTNOTFOUND: Final = -2147319765 +TYPE_E_AMBIGUOUSNAME: Final = -2147319764 +TYPE_E_NAMECONFLICT: Final = -2147319763 +TYPE_E_UNKNOWNLCID: Final = -2147319762 +TYPE_E_DLLFUNCTIONNOTFOUND: Final = -2147319761 +TYPE_E_BADMODULEKIND: Final = -2147317571 +TYPE_E_SIZETOOBIG: Final = -2147317563 +TYPE_E_DUPLICATEID: Final = -2147317562 +TYPE_E_INVALIDID: Final = -2147317553 +TYPE_E_TYPEMISMATCH: Final = -2147316576 +TYPE_E_OUTOFBOUNDS: Final = -2147316575 +TYPE_E_IOERROR: Final = -2147316574 +TYPE_E_CANTCREATETMPFILE: Final = -2147316573 +TYPE_E_CANTLOADLIBRARY: Final = -2147312566 +TYPE_E_INCONSISTENTPROPFUNCS: Final = -2147312509 +TYPE_E_CIRCULARTYPE: Final = -2147312508 +STG_E_INVALIDFUNCTION: Final = -2147287039 +STG_E_FILENOTFOUND: Final = -2147287038 +STG_E_PATHNOTFOUND: Final = -2147287037 +STG_E_TOOMANYOPENFILES: Final = -2147287036 +STG_E_ACCESSDENIED: Final = -2147287035 +STG_E_INVALIDHANDLE: Final = -2147287034 +STG_E_INSUFFICIENTMEMORY: Final = -2147287032 +STG_E_INVALIDPOINTER: Final = -2147287031 +STG_E_NOMOREFILES: Final = -2147287022 +STG_E_DISKISWRITEPROTECTED: Final = -2147287021 +STG_E_SEEKERROR: Final = -2147287015 +STG_E_WRITEFAULT: Final = -2147287011 +STG_E_READFAULT: Final = -2147287010 +STG_E_SHAREVIOLATION: Final = -2147287008 +STG_E_LOCKVIOLATION: Final = -2147287007 +STG_E_FILEALREADYEXISTS: Final = -2147286960 +STG_E_INVALIDPARAMETER: Final = -2147286953 +STG_E_MEDIUMFULL: Final = -2147286928 +STG_E_PROPSETMISMATCHED: Final = -2147286800 +STG_E_ABNORMALAPIEXIT: Final = -2147286790 +STG_E_INVALIDHEADER: Final = -2147286789 +STG_E_INVALIDNAME: Final = -2147286788 +STG_E_UNKNOWN: Final = -2147286787 +STG_E_UNIMPLEMENTEDFUNCTION: Final = -2147286786 +STG_E_INVALIDFLAG: Final = -2147286785 +STG_E_INUSE: Final = -2147286784 +STG_E_NOTCURRENT: Final = -2147286783 +STG_E_REVERTED: Final = -2147286782 +STG_E_CANTSAVE: Final = -2147286781 +STG_E_OLDFORMAT: Final = -2147286780 +STG_E_OLDDLL: Final = -2147286779 +STG_E_SHAREREQUIRED: Final = -2147286778 +STG_E_NOTFILEBASEDSTORAGE: Final = -2147286777 +STG_E_EXTANTMARSHALLINGS: Final = -2147286776 +STG_E_DOCFILECORRUPT: Final = -2147286775 +STG_E_BADBASEADDRESS: Final = -2147286768 +STG_E_DOCFILETOOLARGE: Final = -2147286767 +STG_E_NOTSIMPLEFORMAT: Final = -2147286766 +STG_E_INCOMPLETE: Final = -2147286527 +STG_E_TERMINATED: Final = -2147286526 +STG_S_CONVERTED: Final = 0x00030200 +STG_S_BLOCK: Final = 0x00030201 +STG_S_RETRYNOW: Final = 0x00030202 +STG_S_MONITORING: Final = 0x00030203 +STG_S_MULTIPLEOPENS: Final = 0x00030204 +STG_S_CONSOLIDATIONFAILED: Final = 0x00030205 +STG_S_CANNOTCONSOLIDATE: Final = 0x00030206 +STG_S_POWER_CYCLE_REQUIRED: Final = 0x00030207 +STG_E_FIRMWARE_SLOT_INVALID: Final = -2147286520 +STG_E_FIRMWARE_IMAGE_INVALID: Final = -2147286519 +STG_E_DEVICE_UNRESPONSIVE: Final = -2147286518 +STG_E_STATUS_COPY_PROTECTION_FAILURE: Final = -2147286267 +STG_E_CSS_AUTHENTICATION_FAILURE: Final = -2147286266 +STG_E_CSS_KEY_NOT_PRESENT: Final = -2147286265 +STG_E_CSS_KEY_NOT_ESTABLISHED: Final = -2147286264 +STG_E_CSS_SCRAMBLED_SECTOR: Final = -2147286263 +STG_E_CSS_REGION_MISMATCH: Final = -2147286262 +STG_E_RESETS_EXHAUSTED: Final = -2147286261 +RPC_E_CALL_REJECTED: Final = -2147418111 +RPC_E_CALL_CANCELED: Final = -2147418110 +RPC_E_CANTPOST_INSENDCALL: Final = -2147418109 +RPC_E_CANTCALLOUT_INASYNCCALL: Final = -2147418108 +RPC_E_CANTCALLOUT_INEXTERNALCALL: Final = -2147418107 +RPC_E_CONNECTION_TERMINATED: Final = -2147418106 +RPC_E_SERVER_DIED: Final = -2147418105 +RPC_E_CLIENT_DIED: Final = -2147418104 +RPC_E_INVALID_DATAPACKET: Final = -2147418103 +RPC_E_CANTTRANSMIT_CALL: Final = -2147418102 +RPC_E_CLIENT_CANTMARSHAL_DATA: Final = -2147418101 +RPC_E_CLIENT_CANTUNMARSHAL_DATA: Final = -2147418100 +RPC_E_SERVER_CANTMARSHAL_DATA: Final = -2147418099 +RPC_E_SERVER_CANTUNMARSHAL_DATA: Final = -2147418098 +RPC_E_INVALID_DATA: Final = -2147418097 +RPC_E_INVALID_PARAMETER: Final = -2147418096 +RPC_E_CANTCALLOUT_AGAIN: Final = -2147418095 +RPC_E_SERVER_DIED_DNE: Final = -2147418094 +RPC_E_SYS_CALL_FAILED: Final = -2147417856 +RPC_E_OUT_OF_RESOURCES: Final = -2147417855 +RPC_E_ATTEMPTED_MULTITHREAD: Final = -2147417854 +RPC_E_NOT_REGISTERED: Final = -2147417853 +RPC_E_FAULT: Final = -2147417852 +RPC_E_SERVERFAULT: Final = -2147417851 +RPC_E_CHANGED_MODE: Final = -2147417850 +RPC_E_INVALIDMETHOD: Final = -2147417849 +RPC_E_DISCONNECTED: Final = -2147417848 +RPC_E_RETRY: Final = -2147417847 +RPC_E_SERVERCALL_RETRYLATER: Final = -2147417846 +RPC_E_SERVERCALL_REJECTED: Final = -2147417845 +RPC_E_INVALID_CALLDATA: Final = -2147417844 +RPC_E_CANTCALLOUT_ININPUTSYNCCALL: Final = -2147417843 +RPC_E_WRONG_THREAD: Final = -2147417842 +RPC_E_THREAD_NOT_INIT: Final = -2147417841 +RPC_E_VERSION_MISMATCH: Final = -2147417840 +RPC_E_INVALID_HEADER: Final = -2147417839 +RPC_E_INVALID_EXTENSION: Final = -2147417838 +RPC_E_INVALID_IPID: Final = -2147417837 +RPC_E_INVALID_OBJECT: Final = -2147417836 +RPC_S_CALLPENDING: Final = -2147417835 +RPC_S_WAITONTIMER: Final = -2147417834 +RPC_E_CALL_COMPLETE: Final = -2147417833 +RPC_E_UNSECURE_CALL: Final = -2147417832 +RPC_E_TOO_LATE: Final = -2147417831 +RPC_E_NO_GOOD_SECURITY_PACKAGES: Final = -2147417830 +RPC_E_ACCESS_DENIED: Final = -2147417829 +RPC_E_REMOTE_DISABLED: Final = -2147417828 +RPC_E_INVALID_OBJREF: Final = -2147417827 +RPC_E_NO_CONTEXT: Final = -2147417826 +RPC_E_TIMEOUT: Final = -2147417825 +RPC_E_NO_SYNC: Final = -2147417824 +RPC_E_FULLSIC_REQUIRED: Final = -2147417823 +RPC_E_INVALID_STD_NAME: Final = -2147417822 +CO_E_FAILEDTOIMPERSONATE: Final = -2147417821 +CO_E_FAILEDTOGETSECCTX: Final = -2147417820 +CO_E_FAILEDTOOPENTHREADTOKEN: Final = -2147417819 +CO_E_FAILEDTOGETTOKENINFO: Final = -2147417818 +CO_E_TRUSTEEDOESNTMATCHCLIENT: Final = -2147417817 +CO_E_FAILEDTOQUERYCLIENTBLANKET: Final = -2147417816 +CO_E_FAILEDTOSETDACL: Final = -2147417815 +CO_E_ACCESSCHECKFAILED: Final = -2147417814 +CO_E_NETACCESSAPIFAILED: Final = -2147417813 +CO_E_WRONGTRUSTEENAMESYNTAX: Final = -2147417812 +CO_E_INVALIDSID: Final = -2147417811 +CO_E_CONVERSIONFAILED: Final = -2147417810 +CO_E_NOMATCHINGSIDFOUND: Final = -2147417809 +CO_E_LOOKUPACCSIDFAILED: Final = -2147417808 +CO_E_NOMATCHINGNAMEFOUND: Final = -2147417807 +CO_E_LOOKUPACCNAMEFAILED: Final = -2147417806 +CO_E_SETSERLHNDLFAILED: Final = -2147417805 +CO_E_FAILEDTOGETWINDIR: Final = -2147417804 +CO_E_PATHTOOLONG: Final = -2147417803 +CO_E_FAILEDTOGENUUID: Final = -2147417802 +CO_E_FAILEDTOCREATEFILE: Final = -2147417801 +CO_E_FAILEDTOCLOSEHANDLE: Final = -2147417800 +CO_E_EXCEEDSYSACLLIMIT: Final = -2147417799 +CO_E_ACESINWRONGORDER: Final = -2147417798 +CO_E_INCOMPATIBLESTREAMVERSION: Final = -2147417797 +CO_E_FAILEDTOOPENPROCESSTOKEN: Final = -2147417796 +CO_E_DECODEFAILED: Final = -2147417795 +CO_E_ACNOTINITIALIZED: Final = -2147417793 +CO_E_CANCEL_DISABLED: Final = -2147417792 +RPC_E_UNEXPECTED: Final = -2147352577 +ERROR_AUDITING_DISABLED: Final = -1073151999 +ERROR_ALL_SIDS_FILTERED: Final = -1073151998 +ERROR_BIZRULES_NOT_ENABLED: Final = -1073151997 +NTE_BAD_UID: Final = -2146893823 +NTE_BAD_HASH: Final = -2146893822 +NTE_BAD_KEY: Final = -2146893821 +NTE_BAD_LEN: Final = -2146893820 +NTE_BAD_DATA: Final = -2146893819 +NTE_BAD_SIGNATURE: Final = -2146893818 +NTE_BAD_VER: Final = -2146893817 +NTE_BAD_ALGID: Final = -2146893816 +NTE_BAD_FLAGS: Final = -2146893815 +NTE_BAD_TYPE: Final = -2146893814 +NTE_BAD_KEY_STATE: Final = -2146893813 +NTE_BAD_HASH_STATE: Final = -2146893812 +NTE_NO_KEY: Final = -2146893811 +NTE_NO_MEMORY: Final = -2146893810 +NTE_EXISTS: Final = -2146893809 +NTE_PERM: Final = -2146893808 +NTE_NOT_FOUND: Final = -2146893807 +NTE_DOUBLE_ENCRYPT: Final = -2146893806 +NTE_BAD_PROVIDER: Final = -2146893805 +NTE_BAD_PROV_TYPE: Final = -2146893804 +NTE_BAD_PUBLIC_KEY: Final = -2146893803 +NTE_BAD_KEYSET: Final = -2146893802 +NTE_PROV_TYPE_NOT_DEF: Final = -2146893801 +NTE_PROV_TYPE_ENTRY_BAD: Final = -2146893800 +NTE_KEYSET_NOT_DEF: Final = -2146893799 +NTE_KEYSET_ENTRY_BAD: Final = -2146893798 +NTE_PROV_TYPE_NO_MATCH: Final = -2146893797 +NTE_SIGNATURE_FILE_BAD: Final = -2146893796 +NTE_PROVIDER_DLL_FAIL: Final = -2146893795 +NTE_PROV_DLL_NOT_FOUND: Final = -2146893794 +NTE_BAD_KEYSET_PARAM: Final = -2146893793 +NTE_FAIL: Final = -2146893792 +NTE_SYS_ERR: Final = -2146893791 +NTE_SILENT_CONTEXT: Final = -2146893790 +NTE_TOKEN_KEYSET_STORAGE_FULL: Final = -2146893789 +NTE_TEMPORARY_PROFILE: Final = -2146893788 +NTE_FIXEDPARAMETER: Final = -2146893787 +NTE_INVALID_HANDLE: Final = -2146893786 +NTE_INVALID_PARAMETER: Final = -2146893785 +NTE_BUFFER_TOO_SMALL: Final = -2146893784 +NTE_NOT_SUPPORTED: Final = -2146893783 +NTE_NO_MORE_ITEMS: Final = -2146893782 +NTE_BUFFERS_OVERLAP: Final = -2146893781 +NTE_DECRYPTION_FAILURE: Final = -2146893780 +NTE_INTERNAL_ERROR: Final = -2146893779 +NTE_UI_REQUIRED: Final = -2146893778 +NTE_HMAC_NOT_SUPPORTED: Final = -2146893777 +NTE_DEVICE_NOT_READY: Final = -2146893776 +NTE_AUTHENTICATION_IGNORED: Final = -2146893775 +NTE_VALIDATION_FAILED: Final = -2146893774 +NTE_INCORRECT_PASSWORD: Final = -2146893773 +NTE_ENCRYPTION_FAILURE: Final = -2146893772 +NTE_DEVICE_NOT_FOUND: Final = -2146893771 +NTE_USER_CANCELLED: Final = -2146893770 +NTE_PASSWORD_CHANGE_REQUIRED: Final = -2146893769 +NTE_NOT_ACTIVE_CONSOLE: Final = -2146893768 +SEC_E_INSUFFICIENT_MEMORY: Final = -2146893056 +SEC_E_INVALID_HANDLE: Final = -2146893055 +SEC_E_UNSUPPORTED_FUNCTION: Final = -2146893054 +SEC_E_TARGET_UNKNOWN: Final = -2146893053 +SEC_E_INTERNAL_ERROR: Final = -2146893052 +SEC_E_SECPKG_NOT_FOUND: Final = -2146893051 +SEC_E_NOT_OWNER: Final = -2146893050 +SEC_E_CANNOT_INSTALL: Final = -2146893049 +SEC_E_INVALID_TOKEN: Final = -2146893048 +SEC_E_CANNOT_PACK: Final = -2146893047 +SEC_E_QOP_NOT_SUPPORTED: Final = -2146893046 +SEC_E_NO_IMPERSONATION: Final = -2146893045 +SEC_E_LOGON_DENIED: Final = -2146893044 +SEC_E_UNKNOWN_CREDENTIALS: Final = -2146893043 +SEC_E_NO_CREDENTIALS: Final = -2146893042 +SEC_E_MESSAGE_ALTERED: Final = -2146893041 +SEC_E_OUT_OF_SEQUENCE: Final = -2146893040 +SEC_E_NO_AUTHENTICATING_AUTHORITY: Final = -2146893039 +SEC_I_CONTINUE_NEEDED: Final = 0x00090312 +SEC_I_COMPLETE_NEEDED: Final = 0x00090313 +SEC_I_COMPLETE_AND_CONTINUE: Final = 0x00090314 +SEC_I_LOCAL_LOGON: Final = 0x00090315 +SEC_I_GENERIC_EXTENSION_RECEIVED: Final = 0x00090316 +SEC_E_BAD_PKGID: Final = -2146893034 +SEC_E_CONTEXT_EXPIRED: Final = -2146893033 +SEC_I_CONTEXT_EXPIRED: Final = 0x00090317 +SEC_E_INCOMPLETE_MESSAGE: Final = -2146893032 +SEC_E_INCOMPLETE_CREDENTIALS: Final = -2146893024 +SEC_E_BUFFER_TOO_SMALL: Final = -2146893023 +SEC_I_INCOMPLETE_CREDENTIALS: Final = 0x00090320 +SEC_I_RENEGOTIATE: Final = 0x00090321 +SEC_E_WRONG_PRINCIPAL: Final = -2146893022 +SEC_I_NO_LSA_CONTEXT: Final = 0x00090323 +SEC_E_TIME_SKEW: Final = -2146893020 +SEC_E_UNTRUSTED_ROOT: Final = -2146893019 +SEC_E_ILLEGAL_MESSAGE: Final = -2146893018 +SEC_E_CERT_UNKNOWN: Final = -2146893017 +SEC_E_CERT_EXPIRED: Final = -2146893016 +SEC_E_ENCRYPT_FAILURE: Final = -2146893015 +SEC_E_DECRYPT_FAILURE: Final = -2146893008 +SEC_E_ALGORITHM_MISMATCH: Final = -2146893007 +SEC_E_SECURITY_QOS_FAILED: Final = -2146893006 +SEC_E_UNFINISHED_CONTEXT_DELETED: Final = -2146893005 +SEC_E_NO_TGT_REPLY: Final = -2146893004 +SEC_E_NO_IP_ADDRESSES: Final = -2146893003 +SEC_E_WRONG_CREDENTIAL_HANDLE: Final = -2146893002 +SEC_E_CRYPTO_SYSTEM_INVALID: Final = -2146893001 +SEC_E_MAX_REFERRALS_EXCEEDED: Final = -2146893000 +SEC_E_MUST_BE_KDC: Final = -2146892999 +SEC_E_STRONG_CRYPTO_NOT_SUPPORTED: Final = -2146892998 +SEC_E_TOO_MANY_PRINCIPALS: Final = -2146892997 +SEC_E_NO_PA_DATA: Final = -2146892996 +SEC_E_PKINIT_NAME_MISMATCH: Final = -2146892995 +SEC_E_SMARTCARD_LOGON_REQUIRED: Final = -2146892994 +SEC_E_SHUTDOWN_IN_PROGRESS: Final = -2146892993 +SEC_E_KDC_INVALID_REQUEST: Final = -2146892992 +SEC_E_KDC_UNABLE_TO_REFER: Final = -2146892991 +SEC_E_KDC_UNKNOWN_ETYPE: Final = -2146892990 +SEC_E_UNSUPPORTED_PREAUTH: Final = -2146892989 +SEC_E_DELEGATION_REQUIRED: Final = -2146892987 +SEC_E_BAD_BINDINGS: Final = -2146892986 +SEC_E_MULTIPLE_ACCOUNTS: Final = -2146892985 +SEC_E_NO_KERB_KEY: Final = -2146892984 +SEC_E_CERT_WRONG_USAGE: Final = -2146892983 +SEC_E_DOWNGRADE_DETECTED: Final = -2146892976 +SEC_E_SMARTCARD_CERT_REVOKED: Final = -2146892975 +SEC_E_ISSUING_CA_UNTRUSTED: Final = -2146892974 +SEC_E_REVOCATION_OFFLINE_C: Final = -2146892973 +SEC_E_PKINIT_CLIENT_FAILURE: Final = -2146892972 +SEC_E_SMARTCARD_CERT_EXPIRED: Final = -2146892971 +SEC_E_NO_S4U_PROT_SUPPORT: Final = -2146892970 +SEC_E_CROSSREALM_DELEGATION_FAILURE: Final = -2146892969 +SEC_E_REVOCATION_OFFLINE_KDC: Final = -2146892968 +SEC_E_ISSUING_CA_UNTRUSTED_KDC: Final = -2146892967 +SEC_E_KDC_CERT_EXPIRED: Final = -2146892966 +SEC_E_KDC_CERT_REVOKED: Final = -2146892965 +SEC_I_SIGNATURE_NEEDED: Final = 0x0009035C +SEC_E_INVALID_PARAMETER: Final = -2146892963 +SEC_E_DELEGATION_POLICY: Final = -2146892962 +SEC_E_POLICY_NLTM_ONLY: Final = -2146892961 +SEC_I_NO_RENEGOTIATION: Final = 0x00090360 +SEC_E_NO_CONTEXT: Final = -2146892959 +SEC_E_PKU2U_CERT_FAILURE: Final = -2146892958 +SEC_E_MUTUAL_AUTH_FAILED: Final = -2146892957 +SEC_I_MESSAGE_FRAGMENT: Final = 0x00090364 +SEC_E_ONLY_HTTPS_ALLOWED: Final = -2146892955 +SEC_I_CONTINUE_NEEDED_MESSAGE_OK: Final = 0x00090366 +SEC_E_APPLICATION_PROTOCOL_MISMATCH: Final = -2146892953 +SEC_I_ASYNC_CALL_PENDING: Final = 0x00090368 +SEC_E_INVALID_UPN_NAME: Final = -2146892951 +SEC_E_EXT_BUFFER_TOO_SMALL: Final = -2146892950 +SEC_E_INSUFFICIENT_BUFFERS: Final = -2146892949 +SEC_E_NO_SPM: Final = SEC_E_INTERNAL_ERROR +SEC_E_NOT_SUPPORTED: Final = SEC_E_UNSUPPORTED_FUNCTION +CRYPT_E_MSG_ERROR: Final = -2146889727 +CRYPT_E_UNKNOWN_ALGO: Final = -2146889726 +CRYPT_E_OID_FORMAT: Final = -2146889725 +CRYPT_E_INVALID_MSG_TYPE: Final = -2146889724 +CRYPT_E_UNEXPECTED_ENCODING: Final = -2146889723 +CRYPT_E_AUTH_ATTR_MISSING: Final = -2146889722 +CRYPT_E_HASH_VALUE: Final = -2146889721 +CRYPT_E_INVALID_INDEX: Final = -2146889720 +CRYPT_E_ALREADY_DECRYPTED: Final = -2146889719 +CRYPT_E_NOT_DECRYPTED: Final = -2146889718 +CRYPT_E_RECIPIENT_NOT_FOUND: Final = -2146889717 +CRYPT_E_CONTROL_TYPE: Final = -2146889716 +CRYPT_E_ISSUER_SERIALNUMBER: Final = -2146889715 +CRYPT_E_SIGNER_NOT_FOUND: Final = -2146889714 +CRYPT_E_ATTRIBUTES_MISSING: Final = -2146889713 +CRYPT_E_STREAM_MSG_NOT_READY: Final = -2146889712 +CRYPT_E_STREAM_INSUFFICIENT_DATA: Final = -2146889711 +CRYPT_I_NEW_PROTECTION_REQUIRED: Final = 0x00091012 +CRYPT_E_BAD_LEN: Final = -2146885631 +CRYPT_E_BAD_ENCODE: Final = -2146885630 +CRYPT_E_FILE_ERROR: Final = -2146885629 +CRYPT_E_NOT_FOUND: Final = -2146885628 +CRYPT_E_EXISTS: Final = -2146885627 +CRYPT_E_NO_PROVIDER: Final = -2146885626 +CRYPT_E_SELF_SIGNED: Final = -2146885625 +CRYPT_E_DELETED_PREV: Final = -2146885624 +CRYPT_E_NO_MATCH: Final = -2146885623 +CRYPT_E_UNEXPECTED_MSG_TYPE: Final = -2146885622 +CRYPT_E_NO_KEY_PROPERTY: Final = -2146885621 +CRYPT_E_NO_DECRYPT_CERT: Final = -2146885620 +CRYPT_E_BAD_MSG: Final = -2146885619 +CRYPT_E_NO_SIGNER: Final = -2146885618 +CRYPT_E_PENDING_CLOSE: Final = -2146885617 +CRYPT_E_REVOKED: Final = -2146885616 +CRYPT_E_NO_REVOCATION_DLL: Final = -2146885615 +CRYPT_E_NO_REVOCATION_CHECK: Final = -2146885614 +CRYPT_E_REVOCATION_OFFLINE: Final = -2146885613 +CRYPT_E_NOT_IN_REVOCATION_DATABASE: Final = -2146885612 +CRYPT_E_INVALID_NUMERIC_STRING: Final = -2146885600 +CRYPT_E_INVALID_PRINTABLE_STRING: Final = -2146885599 +CRYPT_E_INVALID_IA5_STRING: Final = -2146885598 +CRYPT_E_INVALID_X500_STRING: Final = -2146885597 +CRYPT_E_NOT_CHAR_STRING: Final = -2146885596 +CRYPT_E_FILERESIZED: Final = -2146885595 +CRYPT_E_SECURITY_SETTINGS: Final = -2146885594 +CRYPT_E_NO_VERIFY_USAGE_DLL: Final = -2146885593 +CRYPT_E_NO_VERIFY_USAGE_CHECK: Final = -2146885592 +CRYPT_E_VERIFY_USAGE_OFFLINE: Final = -2146885591 +CRYPT_E_NOT_IN_CTL: Final = -2146885590 +CRYPT_E_NO_TRUSTED_SIGNER: Final = -2146885589 +CRYPT_E_MISSING_PUBKEY_PARA: Final = -2146885588 +CRYPT_E_OBJECT_LOCATOR_OBJECT_NOT_FOUND: Final = -2146885587 +CRYPT_E_OSS_ERROR: Final = -2146881536 +OSS_MORE_BUF: Final = -2146881535 +OSS_NEGATIVE_UINTEGER: Final = -2146881534 +OSS_PDU_RANGE: Final = -2146881533 +OSS_MORE_INPUT: Final = -2146881532 +OSS_DATA_ERROR: Final = -2146881531 +OSS_BAD_ARG: Final = -2146881530 +OSS_BAD_VERSION: Final = -2146881529 +OSS_OUT_MEMORY: Final = -2146881528 +OSS_PDU_MISMATCH: Final = -2146881527 +OSS_LIMITED: Final = -2146881526 +OSS_BAD_PTR: Final = -2146881525 +OSS_BAD_TIME: Final = -2146881524 +OSS_INDEFINITE_NOT_SUPPORTED: Final = -2146881523 +OSS_MEM_ERROR: Final = -2146881522 +OSS_BAD_TABLE: Final = -2146881521 +OSS_TOO_LONG: Final = -2146881520 +OSS_CONSTRAINT_VIOLATED: Final = -2146881519 +OSS_FATAL_ERROR: Final = -2146881518 +OSS_ACCESS_SERIALIZATION_ERROR: Final = -2146881517 +OSS_NULL_TBL: Final = -2146881516 +OSS_NULL_FCN: Final = -2146881515 +OSS_BAD_ENCRULES: Final = -2146881514 +OSS_UNAVAIL_ENCRULES: Final = -2146881513 +OSS_CANT_OPEN_TRACE_WINDOW: Final = -2146881512 +OSS_UNIMPLEMENTED: Final = -2146881511 +OSS_OID_DLL_NOT_LINKED: Final = -2146881510 +OSS_CANT_OPEN_TRACE_FILE: Final = -2146881509 +OSS_TRACE_FILE_ALREADY_OPEN: Final = -2146881508 +OSS_TABLE_MISMATCH: Final = -2146881507 +OSS_TYPE_NOT_SUPPORTED: Final = -2146881506 +OSS_REAL_DLL_NOT_LINKED: Final = -2146881505 +OSS_REAL_CODE_NOT_LINKED: Final = -2146881504 +OSS_OUT_OF_RANGE: Final = -2146881503 +OSS_COPIER_DLL_NOT_LINKED: Final = -2146881502 +OSS_CONSTRAINT_DLL_NOT_LINKED: Final = -2146881501 +OSS_COMPARATOR_DLL_NOT_LINKED: Final = -2146881500 +OSS_COMPARATOR_CODE_NOT_LINKED: Final = -2146881499 +OSS_MEM_MGR_DLL_NOT_LINKED: Final = -2146881498 +OSS_PDV_DLL_NOT_LINKED: Final = -2146881497 +OSS_PDV_CODE_NOT_LINKED: Final = -2146881496 +OSS_API_DLL_NOT_LINKED: Final = -2146881495 +OSS_BERDER_DLL_NOT_LINKED: Final = -2146881494 +OSS_PER_DLL_NOT_LINKED: Final = -2146881493 +OSS_OPEN_TYPE_ERROR: Final = -2146881492 +OSS_MUTEX_NOT_CREATED: Final = -2146881491 +OSS_CANT_CLOSE_TRACE_FILE: Final = -2146881490 +CRYPT_E_ASN1_ERROR: Final = -2146881280 +CRYPT_E_ASN1_INTERNAL: Final = -2146881279 +CRYPT_E_ASN1_EOD: Final = -2146881278 +CRYPT_E_ASN1_CORRUPT: Final = -2146881277 +CRYPT_E_ASN1_LARGE: Final = -2146881276 +CRYPT_E_ASN1_CONSTRAINT: Final = -2146881275 +CRYPT_E_ASN1_MEMORY: Final = -2146881274 +CRYPT_E_ASN1_OVERFLOW: Final = -2146881273 +CRYPT_E_ASN1_BADPDU: Final = -2146881272 +CRYPT_E_ASN1_BADARGS: Final = -2146881271 +CRYPT_E_ASN1_BADREAL: Final = -2146881270 +CRYPT_E_ASN1_BADTAG: Final = -2146881269 +CRYPT_E_ASN1_CHOICE: Final = -2146881268 +CRYPT_E_ASN1_RULE: Final = -2146881267 +CRYPT_E_ASN1_UTF8: Final = -2146881266 +CRYPT_E_ASN1_PDU_TYPE: Final = -2146881229 +CRYPT_E_ASN1_NYI: Final = -2146881228 +CRYPT_E_ASN1_EXTENDED: Final = -2146881023 +CRYPT_E_ASN1_NOEOD: Final = -2146881022 +CERTSRV_E_BAD_REQUESTSUBJECT: Final = -2146877439 +CERTSRV_E_NO_REQUEST: Final = -2146877438 +CERTSRV_E_BAD_REQUESTSTATUS: Final = -2146877437 +CERTSRV_E_PROPERTY_EMPTY: Final = -2146877436 +CERTSRV_E_INVALID_CA_CERTIFICATE: Final = -2146877435 +CERTSRV_E_SERVER_SUSPENDED: Final = -2146877434 +CERTSRV_E_ENCODING_LENGTH: Final = -2146877433 +CERTSRV_E_ROLECONFLICT: Final = -2146877432 +CERTSRV_E_RESTRICTEDOFFICER: Final = -2146877431 +CERTSRV_E_KEY_ARCHIVAL_NOT_CONFIGURED: Final = -2146877430 +CERTSRV_E_NO_VALID_KRA: Final = -2146877429 +CERTSRV_E_BAD_REQUEST_KEY_ARCHIVAL: Final = -2146877428 +CERTSRV_E_NO_CAADMIN_DEFINED: Final = -2146877427 +CERTSRV_E_BAD_RENEWAL_CERT_ATTRIBUTE: Final = -2146877426 +CERTSRV_E_NO_DB_SESSIONS: Final = -2146877425 +CERTSRV_E_ALIGNMENT_FAULT: Final = -2146877424 +CERTSRV_E_ENROLL_DENIED: Final = -2146877423 +CERTSRV_E_TEMPLATE_DENIED: Final = -2146877422 +CERTSRV_E_DOWNLEVEL_DC_SSL_OR_UPGRADE: Final = -2146877421 +CERTSRV_E_ADMIN_DENIED_REQUEST: Final = -2146877420 +CERTSRV_E_NO_POLICY_SERVER: Final = -2146877419 +CERTSRV_E_WEAK_SIGNATURE_OR_KEY: Final = -2146877418 +CERTSRV_E_KEY_ATTESTATION_NOT_SUPPORTED: Final = -2146877417 +CERTSRV_E_ENCRYPTION_CERT_REQUIRED: Final = -2146877416 +CERTSRV_E_UNSUPPORTED_CERT_TYPE: Final = -2146875392 +CERTSRV_E_NO_CERT_TYPE: Final = -2146875391 +CERTSRV_E_TEMPLATE_CONFLICT: Final = -2146875390 +CERTSRV_E_SUBJECT_ALT_NAME_REQUIRED: Final = -2146875389 +CERTSRV_E_ARCHIVED_KEY_REQUIRED: Final = -2146875388 +CERTSRV_E_SMIME_REQUIRED: Final = -2146875387 +CERTSRV_E_BAD_RENEWAL_SUBJECT: Final = -2146875386 +CERTSRV_E_BAD_TEMPLATE_VERSION: Final = -2146875385 +CERTSRV_E_TEMPLATE_POLICY_REQUIRED: Final = -2146875384 +CERTSRV_E_SIGNATURE_POLICY_REQUIRED: Final = -2146875383 +CERTSRV_E_SIGNATURE_COUNT: Final = -2146875382 +CERTSRV_E_SIGNATURE_REJECTED: Final = -2146875381 +CERTSRV_E_ISSUANCE_POLICY_REQUIRED: Final = -2146875380 +CERTSRV_E_SUBJECT_UPN_REQUIRED: Final = -2146875379 +CERTSRV_E_SUBJECT_DIRECTORY_GUID_REQUIRED: Final = -2146875378 +CERTSRV_E_SUBJECT_DNS_REQUIRED: Final = -2146875377 +CERTSRV_E_ARCHIVED_KEY_UNEXPECTED: Final = -2146875376 +CERTSRV_E_KEY_LENGTH: Final = -2146875375 +CERTSRV_E_SUBJECT_EMAIL_REQUIRED: Final = -2146875374 +CERTSRV_E_UNKNOWN_CERT_TYPE: Final = -2146875373 +CERTSRV_E_CERT_TYPE_OVERLAP: Final = -2146875372 +CERTSRV_E_TOO_MANY_SIGNATURES: Final = -2146875371 +CERTSRV_E_RENEWAL_BAD_PUBLIC_KEY: Final = -2146875370 +CERTSRV_E_INVALID_EK: Final = -2146875369 +CERTSRV_E_INVALID_IDBINDING: Final = -2146875368 +CERTSRV_E_INVALID_ATTESTATION: Final = -2146875367 +CERTSRV_E_KEY_ATTESTATION: Final = -2146875366 +CERTSRV_E_CORRUPT_KEY_ATTESTATION: Final = -2146875365 +CERTSRV_E_EXPIRED_CHALLENGE: Final = -2146875364 +CERTSRV_E_INVALID_RESPONSE: Final = -2146875363 +CERTSRV_E_INVALID_REQUESTID: Final = -2146875362 +CERTSRV_E_REQUEST_PRECERTIFICATE_MISMATCH: Final = -2146875361 +CERTSRV_E_PENDING_CLIENT_RESPONSE: Final = -2146875360 +CERTSRV_E_SEC_EXT_DIRECTORY_SID_REQUIRED: Final = -2146875359 +XENROLL_E_KEY_NOT_EXPORTABLE: Final = -2146873344 +XENROLL_E_CANNOT_ADD_ROOT_CERT: Final = -2146873343 +XENROLL_E_RESPONSE_KA_HASH_NOT_FOUND: Final = -2146873342 +XENROLL_E_RESPONSE_UNEXPECTED_KA_HASH: Final = -2146873341 +XENROLL_E_RESPONSE_KA_HASH_MISMATCH: Final = -2146873340 +XENROLL_E_KEYSPEC_SMIME_MISMATCH: Final = -2146873339 +TRUST_E_SYSTEM_ERROR: Final = -2146869247 +TRUST_E_NO_SIGNER_CERT: Final = -2146869246 +TRUST_E_COUNTER_SIGNER: Final = -2146869245 +TRUST_E_CERT_SIGNATURE: Final = -2146869244 +TRUST_E_TIME_STAMP: Final = -2146869243 +TRUST_E_BAD_DIGEST: Final = -2146869232 +TRUST_E_MALFORMED_SIGNATURE: Final = -2146869231 +TRUST_E_BASIC_CONSTRAINTS: Final = -2146869223 +TRUST_E_FINANCIAL_CRITERIA: Final = -2146869218 +MSSIPOTF_E_OUTOFMEMRANGE: Final = -2146865151 +MSSIPOTF_E_CANTGETOBJECT: Final = -2146865150 +MSSIPOTF_E_NOHEADTABLE: Final = -2146865149 +MSSIPOTF_E_BAD_MAGICNUMBER: Final = -2146865148 +MSSIPOTF_E_BAD_OFFSET_TABLE: Final = -2146865147 +MSSIPOTF_E_TABLE_TAGORDER: Final = -2146865146 +MSSIPOTF_E_TABLE_LONGWORD: Final = -2146865145 +MSSIPOTF_E_BAD_FIRST_TABLE_PLACEMENT: Final = -2146865144 +MSSIPOTF_E_TABLES_OVERLAP: Final = -2146865143 +MSSIPOTF_E_TABLE_PADBYTES: Final = -2146865142 +MSSIPOTF_E_FILETOOSMALL: Final = -2146865141 +MSSIPOTF_E_TABLE_CHECKSUM: Final = -2146865140 +MSSIPOTF_E_FILE_CHECKSUM: Final = -2146865139 +MSSIPOTF_E_FAILED_POLICY: Final = -2146865136 +MSSIPOTF_E_FAILED_HINTS_CHECK: Final = -2146865135 +MSSIPOTF_E_NOT_OPENTYPE: Final = -2146865134 +MSSIPOTF_E_FILE: Final = -2146865133 +MSSIPOTF_E_CRYPT: Final = -2146865132 +MSSIPOTF_E_BADVERSION: Final = -2146865131 +MSSIPOTF_E_DSIG_STRUCTURE: Final = -2146865130 +MSSIPOTF_E_PCONST_CHECK: Final = -2146865129 +MSSIPOTF_E_STRUCTURE: Final = -2146865128 +ERROR_CRED_REQUIRES_CONFIRMATION: Final = -2146865127 +NTE_OP_OK: Final = 0 +TRUST_E_PROVIDER_UNKNOWN: Final = -2146762751 +TRUST_E_ACTION_UNKNOWN: Final = -2146762750 +TRUST_E_SUBJECT_FORM_UNKNOWN: Final = -2146762749 +TRUST_E_SUBJECT_NOT_TRUSTED: Final = -2146762748 +DIGSIG_E_ENCODE: Final = -2146762747 +DIGSIG_E_DECODE: Final = -2146762746 +DIGSIG_E_EXTENSIBILITY: Final = -2146762745 +DIGSIG_E_CRYPTO: Final = -2146762744 +PERSIST_E_SIZEDEFINITE: Final = -2146762743 +PERSIST_E_SIZEINDEFINITE: Final = -2146762742 +PERSIST_E_NOTSELFSIZING: Final = -2146762741 +TRUST_E_NOSIGNATURE: Final = -2146762496 +CERT_E_EXPIRED: Final = -2146762495 +CERT_E_VALIDITYPERIODNESTING: Final = -2146762494 +CERT_E_ROLE: Final = -2146762493 +CERT_E_PATHLENCONST: Final = -2146762492 +CERT_E_CRITICAL: Final = -2146762491 +CERT_E_PURPOSE: Final = -2146762490 +CERT_E_ISSUERCHAINING: Final = -2146762489 +CERT_E_MALFORMED: Final = -2146762488 +CERT_E_UNTRUSTEDROOT: Final = -2146762487 +CERT_E_CHAINING: Final = -2146762486 +TRUST_E_FAIL: Final = -2146762485 +CERT_E_REVOKED: Final = -2146762484 +CERT_E_UNTRUSTEDTESTROOT: Final = -2146762483 +CERT_E_REVOCATION_FAILURE: Final = -2146762482 +CERT_E_CN_NO_MATCH: Final = -2146762481 +CERT_E_WRONG_USAGE: Final = -2146762480 +TRUST_E_EXPLICIT_DISTRUST: Final = -2146762479 +CERT_E_UNTRUSTEDCA: Final = -2146762478 +CERT_E_INVALID_POLICY: Final = -2146762477 +CERT_E_INVALID_NAME: Final = -2146762476 + +def HRESULT_FROM_SETUPAPI(x): ... + +SPAPI_E_EXPECTED_SECTION_NAME: Final = -2146500608 +SPAPI_E_BAD_SECTION_NAME_LINE: Final = -2146500607 +SPAPI_E_SECTION_NAME_TOO_LONG: Final = -2146500606 +SPAPI_E_GENERAL_SYNTAX: Final = -2146500605 +SPAPI_E_WRONG_INF_STYLE: Final = -2146500352 +SPAPI_E_SECTION_NOT_FOUND: Final = -2146500351 +SPAPI_E_LINE_NOT_FOUND: Final = -2146500350 +SPAPI_E_NO_BACKUP: Final = -2146500349 +SPAPI_E_NO_ASSOCIATED_CLASS: Final = -2146500096 +SPAPI_E_CLASS_MISMATCH: Final = -2146500095 +SPAPI_E_DUPLICATE_FOUND: Final = -2146500094 +SPAPI_E_NO_DRIVER_SELECTED: Final = -2146500093 +SPAPI_E_KEY_DOES_NOT_EXIST: Final = -2146500092 +SPAPI_E_INVALID_DEVINST_NAME: Final = -2146500091 +SPAPI_E_INVALID_CLASS: Final = -2146500090 +SPAPI_E_DEVINST_ALREADY_EXISTS: Final = -2146500089 +SPAPI_E_DEVINFO_NOT_REGISTERED: Final = -2146500088 +SPAPI_E_INVALID_REG_PROPERTY: Final = -2146500087 +SPAPI_E_NO_INF: Final = -2146500086 +SPAPI_E_NO_SUCH_DEVINST: Final = -2146500085 +SPAPI_E_CANT_LOAD_CLASS_ICON: Final = -2146500084 +SPAPI_E_INVALID_CLASS_INSTALLER: Final = -2146500083 +SPAPI_E_DI_DO_DEFAULT: Final = -2146500082 +SPAPI_E_DI_NOFILECOPY: Final = -2146500081 +SPAPI_E_INVALID_HWPROFILE: Final = -2146500080 +SPAPI_E_NO_DEVICE_SELECTED: Final = -2146500079 +SPAPI_E_DEVINFO_LIST_LOCKED: Final = -2146500078 +SPAPI_E_DEVINFO_DATA_LOCKED: Final = -2146500077 +SPAPI_E_DI_BAD_PATH: Final = -2146500076 +SPAPI_E_NO_CLASSINSTALL_PARAMS: Final = -2146500075 +SPAPI_E_FILEQUEUE_LOCKED: Final = -2146500074 +SPAPI_E_BAD_SERVICE_INSTALLSECT: Final = -2146500073 +SPAPI_E_NO_CLASS_DRIVER_LIST: Final = -2146500072 +SPAPI_E_NO_ASSOCIATED_SERVICE: Final = -2146500071 +SPAPI_E_NO_DEFAULT_DEVICE_INTERFACE: Final = -2146500070 +SPAPI_E_DEVICE_INTERFACE_ACTIVE: Final = -2146500069 +SPAPI_E_DEVICE_INTERFACE_REMOVED: Final = -2146500068 +SPAPI_E_BAD_INTERFACE_INSTALLSECT: Final = -2146500067 +SPAPI_E_NO_SUCH_INTERFACE_CLASS: Final = -2146500066 +SPAPI_E_INVALID_REFERENCE_STRING: Final = -2146500065 +SPAPI_E_INVALID_MACHINENAME: Final = -2146500064 +SPAPI_E_REMOTE_COMM_FAILURE: Final = -2146500063 +SPAPI_E_MACHINE_UNAVAILABLE: Final = -2146500062 +SPAPI_E_NO_CONFIGMGR_SERVICES: Final = -2146500061 +SPAPI_E_INVALID_PROPPAGE_PROVIDER: Final = -2146500060 +SPAPI_E_NO_SUCH_DEVICE_INTERFACE: Final = -2146500059 +SPAPI_E_DI_POSTPROCESSING_REQUIRED: Final = -2146500058 +SPAPI_E_INVALID_COINSTALLER: Final = -2146500057 +SPAPI_E_NO_COMPAT_DRIVERS: Final = -2146500056 +SPAPI_E_NO_DEVICE_ICON: Final = -2146500055 +SPAPI_E_INVALID_INF_LOGCONFIG: Final = -2146500054 +SPAPI_E_DI_DONT_INSTALL: Final = -2146500053 +SPAPI_E_INVALID_FILTER_DRIVER: Final = -2146500052 +SPAPI_E_NON_WINDOWS_NT_DRIVER: Final = -2146500051 +SPAPI_E_NON_WINDOWS_DRIVER: Final = -2146500050 +SPAPI_E_NO_CATALOG_FOR_OEM_INF: Final = -2146500049 +SPAPI_E_DEVINSTALL_QUEUE_NONNATIVE: Final = -2146500048 +SPAPI_E_NOT_DISABLEABLE: Final = -2146500047 +SPAPI_E_CANT_REMOVE_DEVINST: Final = -2146500046 +SPAPI_E_INVALID_TARGET: Final = -2146500045 +SPAPI_E_DRIVER_NONNATIVE: Final = -2146500044 +SPAPI_E_IN_WOW64: Final = -2146500043 +SPAPI_E_SET_SYSTEM_RESTORE_POINT: Final = -2146500042 +SPAPI_E_INCORRECTLY_COPIED_INF: Final = -2146500041 +SPAPI_E_SCE_DISABLED: Final = -2146500040 +SPAPI_E_UNKNOWN_EXCEPTION: Final = -2146500039 +SPAPI_E_PNP_REGISTRY_ERROR: Final = -2146500038 +SPAPI_E_REMOTE_REQUEST_UNSUPPORTED: Final = -2146500037 +SPAPI_E_NOT_AN_INSTALLED_OEM_INF: Final = -2146500036 +SPAPI_E_INF_IN_USE_BY_DEVICES: Final = -2146500035 +SPAPI_E_DI_FUNCTION_OBSOLETE: Final = -2146500034 +SPAPI_E_NO_AUTHENTICODE_CATALOG: Final = -2146500033 +SPAPI_E_AUTHENTICODE_DISALLOWED: Final = -2146500032 +SPAPI_E_AUTHENTICODE_TRUSTED_PUBLISHER: Final = -2146500031 +SPAPI_E_AUTHENTICODE_TRUST_NOT_ESTABLISHED: Final = -2146500030 +SPAPI_E_AUTHENTICODE_PUBLISHER_NOT_TRUSTED: Final = -2146500029 +SPAPI_E_SIGNATURE_OSATTRIBUTE_MISMATCH: Final = -2146500028 +SPAPI_E_ONLY_VALIDATE_VIA_AUTHENTICODE: Final = -2146500027 +SPAPI_E_DEVICE_INSTALLER_NOT_READY: Final = -2146500026 +SPAPI_E_DRIVER_STORE_ADD_FAILED: Final = -2146500025 +SPAPI_E_DEVICE_INSTALL_BLOCKED: Final = -2146500024 +SPAPI_E_DRIVER_INSTALL_BLOCKED: Final = -2146500023 +SPAPI_E_WRONG_INF_TYPE: Final = -2146500022 +SPAPI_E_FILE_HASH_NOT_IN_CATALOG: Final = -2146500021 +SPAPI_E_DRIVER_STORE_DELETE_FAILED: Final = -2146500020 +SPAPI_E_UNRECOVERABLE_STACK_OVERFLOW: Final = -2146499840 +SPAPI_E_ERROR_NOT_INSTALLED: Final = -2146496512 +SCARD_S_SUCCESS: Final = NO_ERROR +SCARD_F_INTERNAL_ERROR: Final = -2146435071 +SCARD_E_CANCELLED: Final = -2146435070 +SCARD_E_INVALID_HANDLE: Final = -2146435069 +SCARD_E_INVALID_PARAMETER: Final = -2146435068 +SCARD_E_INVALID_TARGET: Final = -2146435067 +SCARD_E_NO_MEMORY: Final = -2146435066 +SCARD_F_WAITED_TOO_LONG: Final = -2146435065 +SCARD_E_INSUFFICIENT_BUFFER: Final = -2146435064 +SCARD_E_UNKNOWN_READER: Final = -2146435063 +SCARD_E_TIMEOUT: Final = -2146435062 +SCARD_E_SHARING_VIOLATION: Final = -2146435061 +SCARD_E_NO_SMARTCARD: Final = -2146435060 +SCARD_E_UNKNOWN_CARD: Final = -2146435059 +SCARD_E_CANT_DISPOSE: Final = -2146435058 +SCARD_E_PROTO_MISMATCH: Final = -2146435057 +SCARD_E_NOT_READY: Final = -2146435056 +SCARD_E_INVALID_VALUE: Final = -2146435055 +SCARD_E_SYSTEM_CANCELLED: Final = -2146435054 +SCARD_F_COMM_ERROR: Final = -2146435053 +SCARD_F_UNKNOWN_ERROR: Final = -2146435052 +SCARD_E_INVALID_ATR: Final = -2146435051 +SCARD_E_NOT_TRANSACTED: Final = -2146435050 +SCARD_E_READER_UNAVAILABLE: Final = -2146435049 +SCARD_P_SHUTDOWN: Final = -2146435048 +SCARD_E_PCI_TOO_SMALL: Final = -2146435047 +SCARD_E_READER_UNSUPPORTED: Final = -2146435046 +SCARD_E_DUPLICATE_READER: Final = -2146435045 +SCARD_E_CARD_UNSUPPORTED: Final = -2146435044 +SCARD_E_NO_SERVICE: Final = -2146435043 +SCARD_E_SERVICE_STOPPED: Final = -2146435042 +SCARD_E_UNEXPECTED: Final = -2146435041 +SCARD_E_ICC_INSTALLATION: Final = -2146435040 +SCARD_E_ICC_CREATEORDER: Final = -2146435039 +SCARD_E_UNSUPPORTED_FEATURE: Final = -2146435038 +SCARD_E_DIR_NOT_FOUND: Final = -2146435037 +SCARD_E_FILE_NOT_FOUND: Final = -2146435036 +SCARD_E_NO_DIR: Final = -2146435035 +SCARD_E_NO_FILE: Final = -2146435034 +SCARD_E_NO_ACCESS: Final = -2146435033 +SCARD_E_WRITE_TOO_MANY: Final = -2146435032 +SCARD_E_BAD_SEEK: Final = -2146435031 +SCARD_E_INVALID_CHV: Final = -2146435030 +SCARD_E_UNKNOWN_RES_MNG: Final = -2146435029 +SCARD_E_NO_SUCH_CERTIFICATE: Final = -2146435028 +SCARD_E_CERTIFICATE_UNAVAILABLE: Final = -2146435027 +SCARD_E_NO_READERS_AVAILABLE: Final = -2146435026 +SCARD_E_COMM_DATA_LOST: Final = -2146435025 +SCARD_E_NO_KEY_CONTAINER: Final = -2146435024 +SCARD_E_SERVER_TOO_BUSY: Final = -2146435023 +SCARD_E_PIN_CACHE_EXPIRED: Final = -2146435022 +SCARD_E_NO_PIN_CACHE: Final = -2146435021 +SCARD_E_READ_ONLY_CARD: Final = -2146435020 +SCARD_W_UNSUPPORTED_CARD: Final = -2146434971 +SCARD_W_UNRESPONSIVE_CARD: Final = -2146434970 +SCARD_W_UNPOWERED_CARD: Final = -2146434969 +SCARD_W_RESET_CARD: Final = -2146434968 +SCARD_W_REMOVED_CARD: Final = -2146434967 +SCARD_W_SECURITY_VIOLATION: Final = -2146434966 +SCARD_W_WRONG_CHV: Final = -2146434965 +SCARD_W_CHV_BLOCKED: Final = -2146434964 +SCARD_W_EOF: Final = -2146434963 +SCARD_W_CANCELLED_BY_USER: Final = -2146434962 +SCARD_W_CARD_NOT_AUTHENTICATED: Final = -2146434961 +SCARD_W_CACHE_ITEM_NOT_FOUND: Final = -2146434960 +SCARD_W_CACHE_ITEM_STALE: Final = -2146434959 +SCARD_W_CACHE_ITEM_TOO_BIG: Final = -2146434958 +COMADMIN_E_OBJECTERRORS: Final = -2146368511 +COMADMIN_E_OBJECTINVALID: Final = -2146368510 +COMADMIN_E_KEYMISSING: Final = -2146368509 +COMADMIN_E_ALREADYINSTALLED: Final = -2146368508 +COMADMIN_E_APP_FILE_WRITEFAIL: Final = -2146368505 +COMADMIN_E_APP_FILE_READFAIL: Final = -2146368504 +COMADMIN_E_APP_FILE_VERSION: Final = -2146368503 +COMADMIN_E_BADPATH: Final = -2146368502 +COMADMIN_E_APPLICATIONEXISTS: Final = -2146368501 +COMADMIN_E_ROLEEXISTS: Final = -2146368500 +COMADMIN_E_CANTCOPYFILE: Final = -2146368499 +COMADMIN_E_NOUSER: Final = -2146368497 +COMADMIN_E_INVALIDUSERIDS: Final = -2146368496 +COMADMIN_E_NOREGISTRYCLSID: Final = -2146368495 +COMADMIN_E_BADREGISTRYPROGID: Final = -2146368494 +COMADMIN_E_AUTHENTICATIONLEVEL: Final = -2146368493 +COMADMIN_E_USERPASSWDNOTVALID: Final = -2146368492 +COMADMIN_E_CLSIDORIIDMISMATCH: Final = -2146368488 +COMADMIN_E_REMOTEINTERFACE: Final = -2146368487 +COMADMIN_E_DLLREGISTERSERVER: Final = -2146368486 +COMADMIN_E_NOSERVERSHARE: Final = -2146368485 +COMADMIN_E_DLLLOADFAILED: Final = -2146368483 +COMADMIN_E_BADREGISTRYLIBID: Final = -2146368482 +COMADMIN_E_APPDIRNOTFOUND: Final = -2146368481 +COMADMIN_E_REGISTRARFAILED: Final = -2146368477 +COMADMIN_E_COMPFILE_DOESNOTEXIST: Final = -2146368476 +COMADMIN_E_COMPFILE_LOADDLLFAIL: Final = -2146368475 +COMADMIN_E_COMPFILE_GETCLASSOBJ: Final = -2146368474 +COMADMIN_E_COMPFILE_CLASSNOTAVAIL: Final = -2146368473 +COMADMIN_E_COMPFILE_BADTLB: Final = -2146368472 +COMADMIN_E_COMPFILE_NOTINSTALLABLE: Final = -2146368471 +COMADMIN_E_NOTCHANGEABLE: Final = -2146368470 +COMADMIN_E_NOTDELETEABLE: Final = -2146368469 +COMADMIN_E_SESSION: Final = -2146368468 +COMADMIN_E_COMP_MOVE_LOCKED: Final = -2146368467 +COMADMIN_E_COMP_MOVE_BAD_DEST: Final = -2146368466 +COMADMIN_E_REGISTERTLB: Final = -2146368464 +COMADMIN_E_SYSTEMAPP: Final = -2146368461 +COMADMIN_E_COMPFILE_NOREGISTRAR: Final = -2146368460 +COMADMIN_E_COREQCOMPINSTALLED: Final = -2146368459 +COMADMIN_E_SERVICENOTINSTALLED: Final = -2146368458 +COMADMIN_E_PROPERTYSAVEFAILED: Final = -2146368457 +COMADMIN_E_OBJECTEXISTS: Final = -2146368456 +COMADMIN_E_COMPONENTEXISTS: Final = -2146368455 +COMADMIN_E_REGFILE_CORRUPT: Final = -2146368453 +COMADMIN_E_PROPERTY_OVERFLOW: Final = -2146368452 +COMADMIN_E_NOTINREGISTRY: Final = -2146368450 +COMADMIN_E_OBJECTNOTPOOLABLE: Final = -2146368449 +COMADMIN_E_APPLID_MATCHES_CLSID: Final = -2146368442 +COMADMIN_E_ROLE_DOES_NOT_EXIST: Final = -2146368441 +COMADMIN_E_START_APP_NEEDS_COMPONENTS: Final = -2146368440 +COMADMIN_E_REQUIRES_DIFFERENT_PLATFORM: Final = -2146368439 +COMADMIN_E_CAN_NOT_EXPORT_APP_PROXY: Final = -2146368438 +COMADMIN_E_CAN_NOT_START_APP: Final = -2146368437 +COMADMIN_E_CAN_NOT_EXPORT_SYS_APP: Final = -2146368436 +COMADMIN_E_CANT_SUBSCRIBE_TO_COMPONENT: Final = -2146368435 +COMADMIN_E_EVENTCLASS_CANT_BE_SUBSCRIBER: Final = -2146368434 +COMADMIN_E_LIB_APP_PROXY_INCOMPATIBLE: Final = -2146368433 +COMADMIN_E_BASE_PARTITION_ONLY: Final = -2146368432 +COMADMIN_E_START_APP_DISABLED: Final = -2146368431 +COMADMIN_E_CAT_DUPLICATE_PARTITION_NAME: Final = -2146368425 +COMADMIN_E_CAT_INVALID_PARTITION_NAME: Final = -2146368424 +COMADMIN_E_CAT_PARTITION_IN_USE: Final = -2146368423 +COMADMIN_E_FILE_PARTITION_DUPLICATE_FILES: Final = -2146368422 +COMADMIN_E_CAT_IMPORTED_COMPONENTS_NOT_ALLOWED: Final = -2146368421 +COMADMIN_E_AMBIGUOUS_APPLICATION_NAME: Final = -2146368420 +COMADMIN_E_AMBIGUOUS_PARTITION_NAME: Final = -2146368419 +COMADMIN_E_REGDB_NOTINITIALIZED: Final = -2146368398 +COMADMIN_E_REGDB_NOTOPEN: Final = -2146368397 +COMADMIN_E_REGDB_SYSTEMERR: Final = -2146368396 +COMADMIN_E_REGDB_ALREADYRUNNING: Final = -2146368395 +COMADMIN_E_MIG_VERSIONNOTSUPPORTED: Final = -2146368384 +COMADMIN_E_MIG_SCHEMANOTFOUND: Final = -2146368383 +COMADMIN_E_CAT_BITNESSMISMATCH: Final = -2146368382 +COMADMIN_E_CAT_UNACCEPTABLEBITNESS: Final = -2146368381 +COMADMIN_E_CAT_WRONGAPPBITNESS: Final = -2146368380 +COMADMIN_E_CAT_PAUSE_RESUME_NOT_SUPPORTED: Final = -2146368379 +COMADMIN_E_CAT_SERVERFAULT: Final = -2146368378 +COMQC_E_APPLICATION_NOT_QUEUED: Final = -2146368000 +COMQC_E_NO_QUEUEABLE_INTERFACES: Final = -2146367999 +COMQC_E_QUEUING_SERVICE_NOT_AVAILABLE: Final = -2146367998 +COMQC_E_NO_IPERSISTSTREAM: Final = -2146367997 +COMQC_E_BAD_MESSAGE: Final = -2146367996 +COMQC_E_UNAUTHENTICATED: Final = -2146367995 +COMQC_E_UNTRUSTED_ENQUEUER: Final = -2146367994 +MSDTC_E_DUPLICATE_RESOURCE: Final = -2146367743 +COMADMIN_E_OBJECT_PARENT_MISSING: Final = -2146367480 +COMADMIN_E_OBJECT_DOES_NOT_EXIST: Final = -2146367479 +COMADMIN_E_APP_NOT_RUNNING: Final = -2146367478 +COMADMIN_E_INVALID_PARTITION: Final = -2146367477 +COMADMIN_E_SVCAPP_NOT_POOLABLE_OR_RECYCLABLE: Final = -2146367475 +COMADMIN_E_USER_IN_SET: Final = -2146367474 +COMADMIN_E_CANTRECYCLELIBRARYAPPS: Final = -2146367473 +COMADMIN_E_CANTRECYCLESERVICEAPPS: Final = -2146367471 +COMADMIN_E_PROCESSALREADYRECYCLED: Final = -2146367470 +COMADMIN_E_PAUSEDPROCESSMAYNOTBERECYCLED: Final = -2146367469 +COMADMIN_E_CANTMAKEINPROCSERVICE: Final = -2146367468 +COMADMIN_E_PROGIDINUSEBYCLSID: Final = -2146367467 +COMADMIN_E_DEFAULT_PARTITION_NOT_IN_SET: Final = -2146367466 +COMADMIN_E_RECYCLEDPROCESSMAYNOTBEPAUSED: Final = -2146367465 +COMADMIN_E_PARTITION_ACCESSDENIED: Final = -2146367464 +COMADMIN_E_PARTITION_MSI_ONLY: Final = -2146367463 +COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_1_0_FORMAT: Final = -2146367462 +COMADMIN_E_LEGACYCOMPS_NOT_ALLOWED_IN_NONBASE_PARTITIONS: Final = -2146367461 +COMADMIN_E_COMP_MOVE_SOURCE: Final = -2146367460 +COMADMIN_E_COMP_MOVE_DEST: Final = -2146367459 +COMADMIN_E_COMP_MOVE_PRIVATE: Final = -2146367458 +COMADMIN_E_BASEPARTITION_REQUIRED_IN_SET: Final = -2146367457 +COMADMIN_E_CANNOT_ALIAS_EVENTCLASS: Final = -2146367456 +COMADMIN_E_PRIVATE_ACCESSDENIED: Final = -2146367455 +COMADMIN_E_SAFERINVALID: Final = -2146367454 +COMADMIN_E_REGISTRY_ACCESSDENIED: Final = -2146367453 +COMADMIN_E_PARTITIONS_DISABLED: Final = -2146367452 +MENROLL_E_DEVICE_MESSAGE_FORMAT_ERROR: Final = -2145910783 +MENROLL_E_DEVICE_AUTHENTICATION_ERROR: Final = -2145910782 +MENROLL_E_DEVICE_AUTHORIZATION_ERROR: Final = -2145910781 +MENROLL_E_DEVICE_CERTIFICATEREQUEST_ERROR: Final = -2145910780 +MENROLL_E_DEVICE_CONFIGMGRSERVER_ERROR: Final = -2145910779 +MENROLL_E_DEVICE_INTERNALSERVICE_ERROR: Final = -2145910778 +MENROLL_E_DEVICE_INVALIDSECURITY_ERROR: Final = -2145910777 +MENROLL_E_DEVICE_UNKNOWN_ERROR: Final = -2145910776 +MENROLL_E_ENROLLMENT_IN_PROGRESS: Final = -2145910775 +MENROLL_E_DEVICE_ALREADY_ENROLLED: Final = -2145910774 +MENROLL_E_DISCOVERY_SEC_CERT_DATE_INVALID: Final = -2145910771 +MENROLL_E_PASSWORD_NEEDED: Final = -2145910770 +MENROLL_E_WAB_ERROR: Final = -2145910769 +MENROLL_E_CONNECTIVITY: Final = -2145910768 +MENROLL_S_ENROLLMENT_SUSPENDED: Final = 0x00180011 +MENROLL_E_INVALIDSSLCERT: Final = -2145910766 +MENROLL_E_DEVICECAPREACHED: Final = -2145910765 +MENROLL_E_DEVICENOTSUPPORTED: Final = -2145910764 +MENROLL_E_NOT_SUPPORTED: Final = -2145910763 +MENROLL_E_NOTELIGIBLETORENEW: Final = -2145910762 +MENROLL_E_INMAINTENANCE: Final = -2145910761 +MENROLL_E_USER_LICENSE: Final = -2145910760 +MENROLL_E_ENROLLMENTDATAINVALID: Final = -2145910759 +MENROLL_E_INSECUREREDIRECT: Final = -2145910758 +MENROLL_E_PLATFORM_WRONG_STATE: Final = -2145910757 +MENROLL_E_PLATFORM_LICENSE_ERROR: Final = -2145910756 +MENROLL_E_PLATFORM_UNKNOWN_ERROR: Final = -2145910755 +MENROLL_E_PROV_CSP_CERTSTORE: Final = -2145910754 +MENROLL_E_PROV_CSP_W7: Final = -2145910753 +MENROLL_E_PROV_CSP_DMCLIENT: Final = -2145910752 +MENROLL_E_PROV_CSP_PFW: Final = -2145910751 +MENROLL_E_PROV_CSP_MISC: Final = -2145910750 +MENROLL_E_PROV_UNKNOWN: Final = -2145910749 +MENROLL_E_PROV_SSLCERTNOTFOUND: Final = -2145910748 +MENROLL_E_PROV_CSP_APPMGMT: Final = -2145910747 +MENROLL_E_DEVICE_MANAGEMENT_BLOCKED: Final = -2145910746 +MENROLL_E_CERTPOLICY_PRIVATEKEYCREATION_FAILED: Final = -2145910745 +MENROLL_E_CERTAUTH_FAILED_TO_FIND_CERT: Final = -2145910744 +MENROLL_E_EMPTY_MESSAGE: Final = -2145910743 +MENROLL_E_USER_CANCELLED: Final = -2145910736 +MENROLL_E_MDM_NOT_CONFIGURED: Final = -2145910735 +MENROLL_E_CUSTOMSERVERERROR: Final = -2145910734 +WER_S_REPORT_DEBUG: Final = 0x001B0000 +WER_S_REPORT_UPLOADED: Final = 0x001B0001 +WER_S_REPORT_QUEUED: Final = 0x001B0002 +WER_S_DISABLED: Final = 0x001B0003 +WER_S_SUSPENDED_UPLOAD: Final = 0x001B0004 +WER_S_DISABLED_QUEUE: Final = 0x001B0005 +WER_S_DISABLED_ARCHIVE: Final = 0x001B0006 +WER_S_REPORT_ASYNC: Final = 0x001B0007 +WER_S_IGNORE_ASSERT_INSTANCE: Final = 0x001B0008 +WER_S_IGNORE_ALL_ASSERTS: Final = 0x001B0009 +WER_S_ASSERT_CONTINUE: Final = 0x001B000A +WER_S_THROTTLED: Final = 0x001B000B +WER_S_REPORT_UPLOADED_CAB: Final = 0x001B000C +WER_E_CRASH_FAILURE: Final = -2145681408 +WER_E_CANCELED: Final = -2145681407 +WER_E_NETWORK_FAILURE: Final = -2145681406 +WER_E_NOT_INITIALIZED: Final = -2145681405 +WER_E_ALREADY_REPORTING: Final = -2145681404 +WER_E_DUMP_THROTTLED: Final = -2145681403 +WER_E_INSUFFICIENT_CONSENT: Final = -2145681402 +WER_E_TOO_HEAVY: Final = -2145681401 + +def FILTER_HRESULT_FROM_FLT_NTSTATUS(x: int) -> int: ... + +ERROR_FLT_IO_COMPLETE: Final = 0x001F0001 +ERROR_FLT_NO_HANDLER_DEFINED: Final = -2145452031 +ERROR_FLT_CONTEXT_ALREADY_DEFINED: Final = -2145452030 +ERROR_FLT_INVALID_ASYNCHRONOUS_REQUEST: Final = -2145452029 +ERROR_FLT_DISALLOW_FAST_IO: Final = -2145452028 +ERROR_FLT_INVALID_NAME_REQUEST: Final = -2145452027 +ERROR_FLT_NOT_SAFE_TO_POST_OPERATION: Final = -2145452026 +ERROR_FLT_NOT_INITIALIZED: Final = -2145452025 +ERROR_FLT_FILTER_NOT_READY: Final = -2145452024 +ERROR_FLT_POST_OPERATION_CLEANUP: Final = -2145452023 +ERROR_FLT_INTERNAL_ERROR: Final = -2145452022 +ERROR_FLT_DELETING_OBJECT: Final = -2145452021 +ERROR_FLT_MUST_BE_NONPAGED_POOL: Final = -2145452020 +ERROR_FLT_DUPLICATE_ENTRY: Final = -2145452019 +ERROR_FLT_CBDQ_DISABLED: Final = -2145452018 +ERROR_FLT_DO_NOT_ATTACH: Final = -2145452017 +ERROR_FLT_DO_NOT_DETACH: Final = -2145452016 +ERROR_FLT_INSTANCE_ALTITUDE_COLLISION: Final = -2145452015 +ERROR_FLT_INSTANCE_NAME_COLLISION: Final = -2145452014 +ERROR_FLT_FILTER_NOT_FOUND: Final = -2145452013 +ERROR_FLT_VOLUME_NOT_FOUND: Final = -2145452012 +ERROR_FLT_INSTANCE_NOT_FOUND: Final = -2145452011 +ERROR_FLT_CONTEXT_ALLOCATION_NOT_FOUND: Final = -2145452010 +ERROR_FLT_INVALID_CONTEXT_REGISTRATION: Final = -2145452009 +ERROR_FLT_NAME_CACHE_MISS: Final = -2145452008 +ERROR_FLT_NO_DEVICE_OBJECT: Final = -2145452007 +ERROR_FLT_VOLUME_ALREADY_MOUNTED: Final = -2145452006 +ERROR_FLT_ALREADY_ENLISTED: Final = -2145452005 +ERROR_FLT_CONTEXT_ALREADY_LINKED: Final = -2145452004 +ERROR_FLT_NO_WAITER_FOR_REPLY: Final = -2145452000 +ERROR_FLT_REGISTRATION_BUSY: Final = -2145451997 +ERROR_FLT_WCOS_NOT_SUPPORTED: Final = -2145451996 +ERROR_HUNG_DISPLAY_DRIVER_THREAD: Final = -2144993279 +DWM_E_COMPOSITIONDISABLED: Final = -2144980991 +DWM_E_REMOTING_NOT_SUPPORTED: Final = -2144980990 +DWM_E_NO_REDIRECTION_SURFACE_AVAILABLE: Final = -2144980989 +DWM_E_NOT_QUEUING_PRESENTS: Final = -2144980988 +DWM_E_ADAPTER_NOT_FOUND: Final = -2144980987 +DWM_S_GDI_REDIRECTION_SURFACE: Final = 0x00263005 +DWM_E_TEXTURE_TOO_LARGE: Final = -2144980985 +DWM_S_GDI_REDIRECTION_SURFACE_BLT_VIA_GDI: Final = 0x00263008 +ERROR_MONITOR_NO_DESCRIPTOR: Final = 0x00261001 +ERROR_MONITOR_UNKNOWN_DESCRIPTOR_FORMAT: Final = 0x00261002 +ERROR_MONITOR_INVALID_DESCRIPTOR_CHECKSUM: Final = -1071247357 +ERROR_MONITOR_INVALID_STANDARD_TIMING_BLOCK: Final = -1071247356 +ERROR_MONITOR_WMI_DATABLOCK_REGISTRATION_FAILED: Final = -1071247355 +ERROR_MONITOR_INVALID_SERIAL_NUMBER_MONDSC_BLOCK: Final = -1071247354 +ERROR_MONITOR_INVALID_USER_FRIENDLY_MONDSC_BLOCK: Final = -1071247353 +ERROR_MONITOR_NO_MORE_DESCRIPTOR_DATA: Final = -1071247352 +ERROR_MONITOR_INVALID_DETAILED_TIMING_BLOCK: Final = -1071247351 +ERROR_MONITOR_INVALID_MANUFACTURE_DATE: Final = -1071247350 +ERROR_GRAPHICS_NOT_EXCLUSIVE_MODE_OWNER: Final = -1071243264 +ERROR_GRAPHICS_INSUFFICIENT_DMA_BUFFER: Final = -1071243263 +ERROR_GRAPHICS_INVALID_DISPLAY_ADAPTER: Final = -1071243262 +ERROR_GRAPHICS_ADAPTER_WAS_RESET: Final = -1071243261 +ERROR_GRAPHICS_INVALID_DRIVER_MODEL: Final = -1071243260 +ERROR_GRAPHICS_PRESENT_MODE_CHANGED: Final = -1071243259 +ERROR_GRAPHICS_PRESENT_OCCLUDED: Final = -1071243258 +ERROR_GRAPHICS_PRESENT_DENIED: Final = -1071243257 +ERROR_GRAPHICS_CANNOTCOLORCONVERT: Final = -1071243256 +ERROR_GRAPHICS_DRIVER_MISMATCH: Final = -1071243255 +ERROR_GRAPHICS_PARTIAL_DATA_POPULATED: Final = 0x4026200A +ERROR_GRAPHICS_PRESENT_REDIRECTION_DISABLED: Final = -1071243253 +ERROR_GRAPHICS_PRESENT_UNOCCLUDED: Final = -1071243252 +ERROR_GRAPHICS_WINDOWDC_NOT_AVAILABLE: Final = -1071243251 +ERROR_GRAPHICS_WINDOWLESS_PRESENT_DISABLED: Final = -1071243250 +ERROR_GRAPHICS_PRESENT_INVALID_WINDOW: Final = -1071243249 +ERROR_GRAPHICS_PRESENT_BUFFER_NOT_BOUND: Final = -1071243248 +ERROR_GRAPHICS_VAIL_STATE_CHANGED: Final = -1071243247 +ERROR_GRAPHICS_INDIRECT_DISPLAY_ABANDON_SWAPCHAIN: Final = -1071243246 +ERROR_GRAPHICS_INDIRECT_DISPLAY_DEVICE_STOPPED: Final = -1071243245 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_CREATE_SUPERWETINK_MESSAGE: Final = -1071243244 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_DESTROY_SUPERWETINK_MESSAGE: Final = -1071243243 +ERROR_GRAPHICS_VAIL_FAILED_TO_SEND_COMPOSITION_WINDOW_DPI_MESSAGE: Final = -1071243242 +ERROR_GRAPHICS_LINK_CONFIGURATION_IN_PROGRESS: Final = -1071243241 +ERROR_GRAPHICS_MPO_ALLOCATION_UNPINNED: Final = -1071243240 +ERROR_GRAPHICS_NO_VIDEO_MEMORY: Final = -1071243008 +ERROR_GRAPHICS_CANT_LOCK_MEMORY: Final = -1071243007 +ERROR_GRAPHICS_ALLOCATION_BUSY: Final = -1071243006 +ERROR_GRAPHICS_TOO_MANY_REFERENCES: Final = -1071243005 +ERROR_GRAPHICS_TRY_AGAIN_LATER: Final = -1071243004 +ERROR_GRAPHICS_TRY_AGAIN_NOW: Final = -1071243003 +ERROR_GRAPHICS_ALLOCATION_INVALID: Final = -1071243002 +ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNAVAILABLE: Final = -1071243001 +ERROR_GRAPHICS_UNSWIZZLING_APERTURE_UNSUPPORTED: Final = -1071243000 +ERROR_GRAPHICS_CANT_EVICT_PINNED_ALLOCATION: Final = -1071242999 +ERROR_GRAPHICS_INVALID_ALLOCATION_USAGE: Final = -1071242992 +ERROR_GRAPHICS_CANT_RENDER_LOCKED_ALLOCATION: Final = -1071242991 +ERROR_GRAPHICS_ALLOCATION_CLOSED: Final = -1071242990 +ERROR_GRAPHICS_INVALID_ALLOCATION_INSTANCE: Final = -1071242989 +ERROR_GRAPHICS_INVALID_ALLOCATION_HANDLE: Final = -1071242988 +ERROR_GRAPHICS_WRONG_ALLOCATION_DEVICE: Final = -1071242987 +ERROR_GRAPHICS_ALLOCATION_CONTENT_LOST: Final = -1071242986 +ERROR_GRAPHICS_GPU_EXCEPTION_ON_DEVICE: Final = -1071242752 +ERROR_GRAPHICS_SKIP_ALLOCATION_PREPARATION: Final = 0x40262201 +ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY: Final = -1071242496 +ERROR_GRAPHICS_VIDPN_TOPOLOGY_NOT_SUPPORTED: Final = -1071242495 +ERROR_GRAPHICS_VIDPN_TOPOLOGY_CURRENTLY_NOT_SUPPORTED: Final = -1071242494 +ERROR_GRAPHICS_INVALID_VIDPN: Final = -1071242493 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE: Final = -1071242492 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET: Final = -1071242491 +ERROR_GRAPHICS_VIDPN_MODALITY_NOT_SUPPORTED: Final = -1071242490 +ERROR_GRAPHICS_MODE_NOT_PINNED: Final = 0x00262307 +ERROR_GRAPHICS_INVALID_VIDPN_SOURCEMODESET: Final = -1071242488 +ERROR_GRAPHICS_INVALID_VIDPN_TARGETMODESET: Final = -1071242487 +ERROR_GRAPHICS_INVALID_FREQUENCY: Final = -1071242486 +ERROR_GRAPHICS_INVALID_ACTIVE_REGION: Final = -1071242485 +ERROR_GRAPHICS_INVALID_TOTAL_REGION: Final = -1071242484 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_SOURCE_MODE: Final = -1071242480 +ERROR_GRAPHICS_INVALID_VIDEO_PRESENT_TARGET_MODE: Final = -1071242479 +ERROR_GRAPHICS_PINNED_MODE_MUST_REMAIN_IN_SET: Final = -1071242478 +ERROR_GRAPHICS_PATH_ALREADY_IN_TOPOLOGY: Final = -1071242477 +ERROR_GRAPHICS_MODE_ALREADY_IN_MODESET: Final = -1071242476 +ERROR_GRAPHICS_INVALID_VIDEOPRESENTSOURCESET: Final = -1071242475 +ERROR_GRAPHICS_INVALID_VIDEOPRESENTTARGETSET: Final = -1071242474 +ERROR_GRAPHICS_SOURCE_ALREADY_IN_SET: Final = -1071242473 +ERROR_GRAPHICS_TARGET_ALREADY_IN_SET: Final = -1071242472 +ERROR_GRAPHICS_INVALID_VIDPN_PRESENT_PATH: Final = -1071242471 +ERROR_GRAPHICS_NO_RECOMMENDED_VIDPN_TOPOLOGY: Final = -1071242470 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGESET: Final = -1071242469 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE: Final = -1071242468 +ERROR_GRAPHICS_FREQUENCYRANGE_NOT_IN_SET: Final = -1071242467 +ERROR_GRAPHICS_NO_PREFERRED_MODE: Final = 0x0026231E +ERROR_GRAPHICS_FREQUENCYRANGE_ALREADY_IN_SET: Final = -1071242465 +ERROR_GRAPHICS_STALE_MODESET: Final = -1071242464 +ERROR_GRAPHICS_INVALID_MONITOR_SOURCEMODESET: Final = -1071242463 +ERROR_GRAPHICS_INVALID_MONITOR_SOURCE_MODE: Final = -1071242462 +ERROR_GRAPHICS_NO_RECOMMENDED_FUNCTIONAL_VIDPN: Final = -1071242461 +ERROR_GRAPHICS_MODE_ID_MUST_BE_UNIQUE: Final = -1071242460 +ERROR_GRAPHICS_EMPTY_ADAPTER_MONITOR_MODE_SUPPORT_INTERSECTION: Final = -1071242459 +ERROR_GRAPHICS_VIDEO_PRESENT_TARGETS_LESS_THAN_SOURCES: Final = -1071242458 +ERROR_GRAPHICS_PATH_NOT_IN_TOPOLOGY: Final = -1071242457 +ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_SOURCE: Final = -1071242456 +ERROR_GRAPHICS_ADAPTER_MUST_HAVE_AT_LEAST_ONE_TARGET: Final = -1071242455 +ERROR_GRAPHICS_INVALID_MONITORDESCRIPTORSET: Final = -1071242454 +ERROR_GRAPHICS_INVALID_MONITORDESCRIPTOR: Final = -1071242453 +ERROR_GRAPHICS_MONITORDESCRIPTOR_NOT_IN_SET: Final = -1071242452 +ERROR_GRAPHICS_MONITORDESCRIPTOR_ALREADY_IN_SET: Final = -1071242451 +ERROR_GRAPHICS_MONITORDESCRIPTOR_ID_MUST_BE_UNIQUE: Final = -1071242450 +ERROR_GRAPHICS_INVALID_VIDPN_TARGET_SUBSET_TYPE: Final = -1071242449 +ERROR_GRAPHICS_RESOURCES_NOT_RELATED: Final = -1071242448 +ERROR_GRAPHICS_SOURCE_ID_MUST_BE_UNIQUE: Final = -1071242447 +ERROR_GRAPHICS_TARGET_ID_MUST_BE_UNIQUE: Final = -1071242446 +ERROR_GRAPHICS_NO_AVAILABLE_VIDPN_TARGET: Final = -1071242445 +ERROR_GRAPHICS_MONITOR_COULD_NOT_BE_ASSOCIATED_WITH_ADAPTER: Final = -1071242444 +ERROR_GRAPHICS_NO_VIDPNMGR: Final = -1071242443 +ERROR_GRAPHICS_NO_ACTIVE_VIDPN: Final = -1071242442 +ERROR_GRAPHICS_STALE_VIDPN_TOPOLOGY: Final = -1071242441 +ERROR_GRAPHICS_MONITOR_NOT_CONNECTED: Final = -1071242440 +ERROR_GRAPHICS_SOURCE_NOT_IN_TOPOLOGY: Final = -1071242439 +ERROR_GRAPHICS_INVALID_PRIMARYSURFACE_SIZE: Final = -1071242438 +ERROR_GRAPHICS_INVALID_VISIBLEREGION_SIZE: Final = -1071242437 +ERROR_GRAPHICS_INVALID_STRIDE: Final = -1071242436 +ERROR_GRAPHICS_INVALID_PIXELFORMAT: Final = -1071242435 +ERROR_GRAPHICS_INVALID_COLORBASIS: Final = -1071242434 +ERROR_GRAPHICS_INVALID_PIXELVALUEACCESSMODE: Final = -1071242433 +ERROR_GRAPHICS_TARGET_NOT_IN_TOPOLOGY: Final = -1071242432 +ERROR_GRAPHICS_NO_DISPLAY_MODE_MANAGEMENT_SUPPORT: Final = -1071242431 +ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = -1071242430 +ERROR_GRAPHICS_CANT_ACCESS_ACTIVE_VIDPN: Final = -1071242429 +ERROR_GRAPHICS_INVALID_PATH_IMPORTANCE_ORDINAL: Final = -1071242428 +ERROR_GRAPHICS_INVALID_PATH_CONTENT_GEOMETRY_TRANSFORMATION: Final = -1071242427 +ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_SUPPORTED: Final = -1071242426 +ERROR_GRAPHICS_INVALID_GAMMA_RAMP: Final = -1071242425 +ERROR_GRAPHICS_GAMMA_RAMP_NOT_SUPPORTED: Final = -1071242424 +ERROR_GRAPHICS_MULTISAMPLING_NOT_SUPPORTED: Final = -1071242423 +ERROR_GRAPHICS_MODE_NOT_IN_MODESET: Final = -1071242422 +ERROR_GRAPHICS_DATASET_IS_EMPTY: Final = 0x0026234B +ERROR_GRAPHICS_NO_MORE_ELEMENTS_IN_DATASET: Final = 0x0026234C +ERROR_GRAPHICS_INVALID_VIDPN_TOPOLOGY_RECOMMENDATION_REASON: Final = -1071242419 +ERROR_GRAPHICS_INVALID_PATH_CONTENT_TYPE: Final = -1071242418 +ERROR_GRAPHICS_INVALID_COPYPROTECTION_TYPE: Final = -1071242417 +ERROR_GRAPHICS_UNASSIGNED_MODESET_ALREADY_EXISTS: Final = -1071242416 +ERROR_GRAPHICS_PATH_CONTENT_GEOMETRY_TRANSFORMATION_NOT_PINNED: Final = 0x00262351 +ERROR_GRAPHICS_INVALID_SCANLINE_ORDERING: Final = -1071242414 +ERROR_GRAPHICS_TOPOLOGY_CHANGES_NOT_ALLOWED: Final = -1071242413 +ERROR_GRAPHICS_NO_AVAILABLE_IMPORTANCE_ORDINALS: Final = -1071242412 +ERROR_GRAPHICS_INCOMPATIBLE_PRIVATE_FORMAT: Final = -1071242411 +ERROR_GRAPHICS_INVALID_MODE_PRUNING_ALGORITHM: Final = -1071242410 +ERROR_GRAPHICS_INVALID_MONITOR_CAPABILITY_ORIGIN: Final = -1071242409 +ERROR_GRAPHICS_INVALID_MONITOR_FREQUENCYRANGE_CONSTRAINT: Final = -1071242408 +ERROR_GRAPHICS_MAX_NUM_PATHS_REACHED: Final = -1071242407 +ERROR_GRAPHICS_CANCEL_VIDPN_TOPOLOGY_AUGMENTATION: Final = -1071242406 +ERROR_GRAPHICS_INVALID_CLIENT_TYPE: Final = -1071242405 +ERROR_GRAPHICS_CLIENTVIDPN_NOT_SET: Final = -1071242404 +ERROR_GRAPHICS_SPECIFIED_CHILD_ALREADY_CONNECTED: Final = -1071242240 +ERROR_GRAPHICS_CHILD_DESCRIPTOR_NOT_SUPPORTED: Final = -1071242239 +ERROR_GRAPHICS_UNKNOWN_CHILD_STATUS: Final = 0x4026242F +ERROR_GRAPHICS_NOT_A_LINKED_ADAPTER: Final = -1071242192 +ERROR_GRAPHICS_LEADLINK_NOT_ENUMERATED: Final = -1071242191 +ERROR_GRAPHICS_CHAINLINKS_NOT_ENUMERATED: Final = -1071242190 +ERROR_GRAPHICS_ADAPTER_CHAIN_NOT_READY: Final = -1071242189 +ERROR_GRAPHICS_CHAINLINKS_NOT_STARTED: Final = -1071242188 +ERROR_GRAPHICS_CHAINLINKS_NOT_POWERED_ON: Final = -1071242187 +ERROR_GRAPHICS_INCONSISTENT_DEVICE_LINK_STATE: Final = -1071242186 +ERROR_GRAPHICS_LEADLINK_START_DEFERRED: Final = 0x40262437 +ERROR_GRAPHICS_NOT_POST_DEVICE_DRIVER: Final = -1071242184 +ERROR_GRAPHICS_POLLING_TOO_FREQUENTLY: Final = 0x40262439 +ERROR_GRAPHICS_START_DEFERRED: Final = 0x4026243A +ERROR_GRAPHICS_ADAPTER_ACCESS_NOT_EXCLUDED: Final = -1071242181 +ERROR_GRAPHICS_DEPENDABLE_CHILD_STATUS: Final = 0x4026243C +ERROR_GRAPHICS_OPM_NOT_SUPPORTED: Final = -1071241984 +ERROR_GRAPHICS_COPP_NOT_SUPPORTED: Final = -1071241983 +ERROR_GRAPHICS_UAB_NOT_SUPPORTED: Final = -1071241982 +ERROR_GRAPHICS_OPM_INVALID_ENCRYPTED_PARAMETERS: Final = -1071241981 +ERROR_GRAPHICS_OPM_NO_VIDEO_OUTPUTS_EXIST: Final = -1071241979 +ERROR_GRAPHICS_OPM_INTERNAL_ERROR: Final = -1071241973 +ERROR_GRAPHICS_OPM_INVALID_HANDLE: Final = -1071241972 +ERROR_GRAPHICS_PVP_INVALID_CERTIFICATE_LENGTH: Final = -1071241970 +ERROR_GRAPHICS_OPM_SPANNING_MODE_ENABLED: Final = -1071241969 +ERROR_GRAPHICS_OPM_THEATER_MODE_ENABLED: Final = -1071241968 +ERROR_GRAPHICS_PVP_HFS_FAILED: Final = -1071241967 +ERROR_GRAPHICS_OPM_INVALID_SRM: Final = -1071241966 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_HDCP: Final = -1071241965 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_ACP: Final = -1071241964 +ERROR_GRAPHICS_OPM_OUTPUT_DOES_NOT_SUPPORT_CGMSA: Final = -1071241963 +ERROR_GRAPHICS_OPM_HDCP_SRM_NEVER_SET: Final = -1071241962 +ERROR_GRAPHICS_OPM_RESOLUTION_TOO_HIGH: Final = -1071241961 +ERROR_GRAPHICS_OPM_ALL_HDCP_HARDWARE_ALREADY_IN_USE: Final = -1071241960 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_NO_LONGER_EXISTS: Final = -1071241958 +ERROR_GRAPHICS_OPM_SESSION_TYPE_CHANGE_IN_PROGRESS: Final = -1071241957 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_COPP_SEMANTICS: Final = -1071241956 +ERROR_GRAPHICS_OPM_INVALID_INFORMATION_REQUEST: Final = -1071241955 +ERROR_GRAPHICS_OPM_DRIVER_INTERNAL_ERROR: Final = -1071241954 +ERROR_GRAPHICS_OPM_VIDEO_OUTPUT_DOES_NOT_HAVE_OPM_SEMANTICS: Final = -1071241953 +ERROR_GRAPHICS_OPM_SIGNALING_NOT_SUPPORTED: Final = -1071241952 +ERROR_GRAPHICS_OPM_INVALID_CONFIGURATION_REQUEST: Final = -1071241951 +ERROR_GRAPHICS_I2C_NOT_SUPPORTED: Final = -1071241856 +ERROR_GRAPHICS_I2C_DEVICE_DOES_NOT_EXIST: Final = -1071241855 +ERROR_GRAPHICS_I2C_ERROR_TRANSMITTING_DATA: Final = -1071241854 +ERROR_GRAPHICS_I2C_ERROR_RECEIVING_DATA: Final = -1071241853 +ERROR_GRAPHICS_DDCCI_VCP_NOT_SUPPORTED: Final = -1071241852 +ERROR_GRAPHICS_DDCCI_INVALID_DATA: Final = -1071241851 +ERROR_GRAPHICS_DDCCI_MONITOR_RETURNED_INVALID_TIMING_STATUS_BYTE: Final = -1071241850 +ERROR_GRAPHICS_MCA_INVALID_CAPABILITIES_STRING: Final = -1071241849 +ERROR_GRAPHICS_MCA_INTERNAL_ERROR: Final = -1071241848 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_COMMAND: Final = -1071241847 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_LENGTH: Final = -1071241846 +ERROR_GRAPHICS_DDCCI_INVALID_MESSAGE_CHECKSUM: Final = -1071241845 +ERROR_GRAPHICS_INVALID_PHYSICAL_MONITOR_HANDLE: Final = -1071241844 +ERROR_GRAPHICS_MONITOR_NO_LONGER_EXISTS: Final = -1071241843 +ERROR_GRAPHICS_DDCCI_CURRENT_CURRENT_VALUE_GREATER_THAN_MAXIMUM_VALUE: Final = -1071241768 +ERROR_GRAPHICS_MCA_INVALID_VCP_VERSION: Final = -1071241767 +ERROR_GRAPHICS_MCA_MONITOR_VIOLATES_MCCS_SPECIFICATION: Final = -1071241766 +ERROR_GRAPHICS_MCA_MCCS_VERSION_MISMATCH: Final = -1071241765 +ERROR_GRAPHICS_MCA_UNSUPPORTED_MCCS_VERSION: Final = -1071241764 +ERROR_GRAPHICS_MCA_INVALID_TECHNOLOGY_TYPE_RETURNED: Final = -1071241762 +ERROR_GRAPHICS_MCA_UNSUPPORTED_COLOR_TEMPERATURE: Final = -1071241761 +ERROR_GRAPHICS_ONLY_CONSOLE_SESSION_SUPPORTED: Final = -1071241760 +ERROR_GRAPHICS_NO_DISPLAY_DEVICE_CORRESPONDS_TO_NAME: Final = -1071241759 +ERROR_GRAPHICS_DISPLAY_DEVICE_NOT_ATTACHED_TO_DESKTOP: Final = -1071241758 +ERROR_GRAPHICS_MIRRORING_DEVICES_NOT_SUPPORTED: Final = -1071241757 +ERROR_GRAPHICS_INVALID_POINTER: Final = -1071241756 +ERROR_GRAPHICS_NO_MONITORS_CORRESPOND_TO_DISPLAY_DEVICE: Final = -1071241755 +ERROR_GRAPHICS_PARAMETER_ARRAY_TOO_SMALL: Final = -1071241754 +ERROR_GRAPHICS_INTERNAL_ERROR: Final = -1071241753 +ERROR_GRAPHICS_SESSION_TYPE_CHANGE_IN_PROGRESS: Final = -1071249944 +NAP_E_INVALID_PACKET: Final = -2144927743 +NAP_E_MISSING_SOH: Final = -2144927742 +NAP_E_CONFLICTING_ID: Final = -2144927741 +NAP_E_NO_CACHED_SOH: Final = -2144927740 +NAP_E_STILL_BOUND: Final = -2144927739 +NAP_E_NOT_REGISTERED: Final = -2144927738 +NAP_E_NOT_INITIALIZED: Final = -2144927737 +NAP_E_MISMATCHED_ID: Final = -2144927736 +NAP_E_NOT_PENDING: Final = -2144927735 +NAP_E_ID_NOT_FOUND: Final = -2144927734 +NAP_E_MAXSIZE_TOO_SMALL: Final = -2144927733 +NAP_E_SERVICE_NOT_RUNNING: Final = -2144927732 +NAP_S_CERT_ALREADY_PRESENT: Final = 0x0027000D +NAP_E_ENTITY_DISABLED: Final = -2144927730 +NAP_E_NETSH_GROUPPOLICY_ERROR: Final = -2144927729 +NAP_E_TOO_MANY_CALLS: Final = -2144927728 +NAP_E_SHV_CONFIG_EXISTED: Final = -2144927727 +NAP_E_SHV_CONFIG_NOT_FOUND: Final = -2144927726 +NAP_E_SHV_TIMEOUT: Final = -2144927725 +TPM_E_ERROR_MASK: Final = -2144862208 +TPM_E_AUTHFAIL: Final = -2144862207 +TPM_E_BADINDEX: Final = -2144862206 +TPM_E_BAD_PARAMETER: Final = -2144862205 +TPM_E_AUDITFAILURE: Final = -2144862204 +TPM_E_CLEAR_DISABLED: Final = -2144862203 +TPM_E_DEACTIVATED: Final = -2144862202 +TPM_E_DISABLED: Final = -2144862201 +TPM_E_DISABLED_CMD: Final = -2144862200 +TPM_E_FAIL: Final = -2144862199 +TPM_E_BAD_ORDINAL: Final = -2144862198 +TPM_E_INSTALL_DISABLED: Final = -2144862197 +TPM_E_INVALID_KEYHANDLE: Final = -2144862196 +TPM_E_KEYNOTFOUND: Final = -2144862195 +TPM_E_INAPPROPRIATE_ENC: Final = -2144862194 +TPM_E_MIGRATEFAIL: Final = -2144862193 +TPM_E_INVALID_PCR_INFO: Final = -2144862192 +TPM_E_NOSPACE: Final = -2144862191 +TPM_E_NOSRK: Final = -2144862190 +TPM_E_NOTSEALED_BLOB: Final = -2144862189 +TPM_E_OWNER_SET: Final = -2144862188 +TPM_E_RESOURCES: Final = -2144862187 +TPM_E_SHORTRANDOM: Final = -2144862186 +TPM_E_SIZE: Final = -2144862185 +TPM_E_WRONGPCRVAL: Final = -2144862184 +TPM_E_BAD_PARAM_SIZE: Final = -2144862183 +TPM_E_SHA_THREAD: Final = -2144862182 +TPM_E_SHA_ERROR: Final = -2144862181 +TPM_E_FAILEDSELFTEST: Final = -2144862180 +TPM_E_AUTH2FAIL: Final = -2144862179 +TPM_E_BADTAG: Final = -2144862178 +TPM_E_IOERROR: Final = -2144862177 +TPM_E_ENCRYPT_ERROR: Final = -2144862176 +TPM_E_DECRYPT_ERROR: Final = -2144862175 +TPM_E_INVALID_AUTHHANDLE: Final = -2144862174 +TPM_E_NO_ENDORSEMENT: Final = -2144862173 +TPM_E_INVALID_KEYUSAGE: Final = -2144862172 +TPM_E_WRONG_ENTITYTYPE: Final = -2144862171 +TPM_E_INVALID_POSTINIT: Final = -2144862170 +TPM_E_INAPPROPRIATE_SIG: Final = -2144862169 +TPM_E_BAD_KEY_PROPERTY: Final = -2144862168 +TPM_E_BAD_MIGRATION: Final = -2144862167 +TPM_E_BAD_SCHEME: Final = -2144862166 +TPM_E_BAD_DATASIZE: Final = -2144862165 +TPM_E_BAD_MODE: Final = -2144862164 +TPM_E_BAD_PRESENCE: Final = -2144862163 +TPM_E_BAD_VERSION: Final = -2144862162 +TPM_E_NO_WRAP_TRANSPORT: Final = -2144862161 +TPM_E_AUDITFAIL_UNSUCCESSFUL: Final = -2144862160 +TPM_E_AUDITFAIL_SUCCESSFUL: Final = -2144862159 +TPM_E_NOTRESETABLE: Final = -2144862158 +TPM_E_NOTLOCAL: Final = -2144862157 +TPM_E_BAD_TYPE: Final = -2144862156 +TPM_E_INVALID_RESOURCE: Final = -2144862155 +TPM_E_NOTFIPS: Final = -2144862154 +TPM_E_INVALID_FAMILY: Final = -2144862153 +TPM_E_NO_NV_PERMISSION: Final = -2144862152 +TPM_E_REQUIRES_SIGN: Final = -2144862151 +TPM_E_KEY_NOTSUPPORTED: Final = -2144862150 +TPM_E_AUTH_CONFLICT: Final = -2144862149 +TPM_E_AREA_LOCKED: Final = -2144862148 +TPM_E_BAD_LOCALITY: Final = -2144862147 +TPM_E_READ_ONLY: Final = -2144862146 +TPM_E_PER_NOWRITE: Final = -2144862145 +TPM_E_FAMILYCOUNT: Final = -2144862144 +TPM_E_WRITE_LOCKED: Final = -2144862143 +TPM_E_BAD_ATTRIBUTES: Final = -2144862142 +TPM_E_INVALID_STRUCTURE: Final = -2144862141 +TPM_E_KEY_OWNER_CONTROL: Final = -2144862140 +TPM_E_BAD_COUNTER: Final = -2144862139 +TPM_E_NOT_FULLWRITE: Final = -2144862138 +TPM_E_CONTEXT_GAP: Final = -2144862137 +TPM_E_MAXNVWRITES: Final = -2144862136 +TPM_E_NOOPERATOR: Final = -2144862135 +TPM_E_RESOURCEMISSING: Final = -2144862134 +TPM_E_DELEGATE_LOCK: Final = -2144862133 +TPM_E_DELEGATE_FAMILY: Final = -2144862132 +TPM_E_DELEGATE_ADMIN: Final = -2144862131 +TPM_E_TRANSPORT_NOTEXCLUSIVE: Final = -2144862130 +TPM_E_OWNER_CONTROL: Final = -2144862129 +TPM_E_DAA_RESOURCES: Final = -2144862128 +TPM_E_DAA_INPUT_DATA0: Final = -2144862127 +TPM_E_DAA_INPUT_DATA1: Final = -2144862126 +TPM_E_DAA_ISSUER_SETTINGS: Final = -2144862125 +TPM_E_DAA_TPM_SETTINGS: Final = -2144862124 +TPM_E_DAA_STAGE: Final = -2144862123 +TPM_E_DAA_ISSUER_VALIDITY: Final = -2144862122 +TPM_E_DAA_WRONG_W: Final = -2144862121 +TPM_E_BAD_HANDLE: Final = -2144862120 +TPM_E_BAD_DELEGATE: Final = -2144862119 +TPM_E_BADCONTEXT: Final = -2144862118 +TPM_E_TOOMANYCONTEXTS: Final = -2144862117 +TPM_E_MA_TICKET_SIGNATURE: Final = -2144862116 +TPM_E_MA_DESTINATION: Final = -2144862115 +TPM_E_MA_SOURCE: Final = -2144862114 +TPM_E_MA_AUTHORITY: Final = -2144862113 +TPM_E_PERMANENTEK: Final = -2144862111 +TPM_E_BAD_SIGNATURE: Final = -2144862110 +TPM_E_NOCONTEXTSPACE: Final = -2144862109 +TPM_20_E_ASYMMETRIC: Final = -2144862079 +TPM_20_E_ATTRIBUTES: Final = -2144862078 +TPM_20_E_HASH: Final = -2144862077 +TPM_20_E_VALUE: Final = -2144862076 +TPM_20_E_HIERARCHY: Final = -2144862075 +TPM_20_E_KEY_SIZE: Final = -2144862073 +TPM_20_E_MGF: Final = -2144862072 +TPM_20_E_MODE: Final = -2144862071 +TPM_20_E_TYPE: Final = -2144862070 +TPM_20_E_HANDLE: Final = -2144862069 +TPM_20_E_KDF: Final = -2144862068 +TPM_20_E_RANGE: Final = -2144862067 +TPM_20_E_AUTH_FAIL: Final = -2144862066 +TPM_20_E_NONCE: Final = -2144862065 +TPM_20_E_PP: Final = -2144862064 +TPM_20_E_SCHEME: Final = -2144862062 +TPM_20_E_SIZE: Final = -2144862059 +TPM_20_E_SYMMETRIC: Final = -2144862058 +TPM_20_E_TAG: Final = -2144862057 +TPM_20_E_SELECTOR: Final = -2144862056 +TPM_20_E_INSUFFICIENT: Final = -2144862054 +TPM_20_E_SIGNATURE: Final = -2144862053 +TPM_20_E_KEY: Final = -2144862052 +TPM_20_E_POLICY_FAIL: Final = -2144862051 +TPM_20_E_INTEGRITY: Final = -2144862049 +TPM_20_E_TICKET: Final = -2144862048 +TPM_20_E_RESERVED_BITS: Final = -2144862047 +TPM_20_E_BAD_AUTH: Final = -2144862046 +TPM_20_E_EXPIRED: Final = -2144862045 +TPM_20_E_POLICY_CC: Final = -2144862044 +TPM_20_E_BINDING: Final = -2144862043 +TPM_20_E_CURVE: Final = -2144862042 +TPM_20_E_ECC_POINT: Final = -2144862041 +TPM_20_E_INITIALIZE: Final = -2144861952 +TPM_20_E_FAILURE: Final = -2144861951 +TPM_20_E_SEQUENCE: Final = -2144861949 +TPM_20_E_PRIVATE: Final = -2144861941 +TPM_20_E_HMAC: Final = -2144861927 +TPM_20_E_DISABLED: Final = -2144861920 +TPM_20_E_EXCLUSIVE: Final = -2144861919 +TPM_20_E_ECC_CURVE: Final = -2144861917 +TPM_20_E_AUTH_TYPE: Final = -2144861916 +TPM_20_E_AUTH_MISSING: Final = -2144861915 +TPM_20_E_POLICY: Final = -2144861914 +TPM_20_E_PCR: Final = -2144861913 +TPM_20_E_PCR_CHANGED: Final = -2144861912 +TPM_20_E_UPGRADE: Final = -2144861907 +TPM_20_E_TOO_MANY_CONTEXTS: Final = -2144861906 +TPM_20_E_AUTH_UNAVAILABLE: Final = -2144861905 +TPM_20_E_REBOOT: Final = -2144861904 +TPM_20_E_UNBALANCED: Final = -2144861903 +TPM_20_E_COMMAND_SIZE: Final = -2144861886 +TPM_20_E_COMMAND_CODE: Final = -2144861885 +TPM_20_E_AUTHSIZE: Final = -2144861884 +TPM_20_E_AUTH_CONTEXT: Final = -2144861883 +TPM_20_E_NV_RANGE: Final = -2144861882 +TPM_20_E_NV_SIZE: Final = -2144861881 +TPM_20_E_NV_LOCKED: Final = -2144861880 +TPM_20_E_NV_AUTHORIZATION: Final = -2144861879 +TPM_20_E_NV_UNINITIALIZED: Final = -2144861878 +TPM_20_E_NV_SPACE: Final = -2144861877 +TPM_20_E_NV_DEFINED: Final = -2144861876 +TPM_20_E_BAD_CONTEXT: Final = -2144861872 +TPM_20_E_CPHASH: Final = -2144861871 +TPM_20_E_PARENT: Final = -2144861870 +TPM_20_E_NEEDS_TEST: Final = -2144861869 +TPM_20_E_NO_RESULT: Final = -2144861868 +TPM_20_E_SENSITIVE: Final = -2144861867 +TPM_E_COMMAND_BLOCKED: Final = -2144861184 +TPM_E_INVALID_HANDLE: Final = -2144861183 +TPM_E_DUPLICATE_VHANDLE: Final = -2144861182 +TPM_E_EMBEDDED_COMMAND_BLOCKED: Final = -2144861181 +TPM_E_EMBEDDED_COMMAND_UNSUPPORTED: Final = -2144861180 +TPM_E_RETRY: Final = -2144860160 +TPM_E_NEEDS_SELFTEST: Final = -2144860159 +TPM_E_DOING_SELFTEST: Final = -2144860158 +TPM_E_DEFEND_LOCK_RUNNING: Final = -2144860157 +TPM_20_E_CONTEXT_GAP: Final = -2144859903 +TPM_20_E_OBJECT_MEMORY: Final = -2144859902 +TPM_20_E_SESSION_MEMORY: Final = -2144859901 +TPM_20_E_MEMORY: Final = -2144859900 +TPM_20_E_SESSION_HANDLES: Final = -2144859899 +TPM_20_E_OBJECT_HANDLES: Final = -2144859898 +TPM_20_E_LOCALITY: Final = -2144859897 +TPM_20_E_YIELDED: Final = -2144859896 +TPM_20_E_CANCELED: Final = -2144859895 +TPM_20_E_TESTING: Final = -2144859894 +TPM_20_E_NV_RATE: Final = -2144859872 +TPM_20_E_LOCKOUT: Final = -2144859871 +TPM_20_E_RETRY: Final = -2144859870 +TPM_20_E_NV_UNAVAILABLE: Final = -2144859869 +TBS_E_INTERNAL_ERROR: Final = -2144845823 +TBS_E_BAD_PARAMETER: Final = -2144845822 +TBS_E_INVALID_OUTPUT_POINTER: Final = -2144845821 +TBS_E_INVALID_CONTEXT: Final = -2144845820 +TBS_E_INSUFFICIENT_BUFFER: Final = -2144845819 +TBS_E_IOERROR: Final = -2144845818 +TBS_E_INVALID_CONTEXT_PARAM: Final = -2144845817 +TBS_E_SERVICE_NOT_RUNNING: Final = -2144845816 +TBS_E_TOO_MANY_TBS_CONTEXTS: Final = -2144845815 +TBS_E_TOO_MANY_RESOURCES: Final = -2144845814 +TBS_E_SERVICE_START_PENDING: Final = -2144845813 +TBS_E_PPI_NOT_SUPPORTED: Final = -2144845812 +TBS_E_COMMAND_CANCELED: Final = -2144845811 +TBS_E_BUFFER_TOO_LARGE: Final = -2144845810 +TBS_E_TPM_NOT_FOUND: Final = -2144845809 +TBS_E_SERVICE_DISABLED: Final = -2144845808 +TBS_E_NO_EVENT_LOG: Final = -2144845807 +TBS_E_ACCESS_DENIED: Final = -2144845806 +TBS_E_PROVISIONING_NOT_ALLOWED: Final = -2144845805 +TBS_E_PPI_FUNCTION_UNSUPPORTED: Final = -2144845804 +TBS_E_OWNERAUTH_NOT_FOUND: Final = -2144845803 +TBS_E_PROVISIONING_INCOMPLETE: Final = -2144845802 +TPMAPI_E_INVALID_STATE: Final = -2144796416 +TPMAPI_E_NOT_ENOUGH_DATA: Final = -2144796415 +TPMAPI_E_TOO_MUCH_DATA: Final = -2144796414 +TPMAPI_E_INVALID_OUTPUT_POINTER: Final = -2144796413 +TPMAPI_E_INVALID_PARAMETER: Final = -2144796412 +TPMAPI_E_OUT_OF_MEMORY: Final = -2144796411 +TPMAPI_E_BUFFER_TOO_SMALL: Final = -2144796410 +TPMAPI_E_INTERNAL_ERROR: Final = -2144796409 +TPMAPI_E_ACCESS_DENIED: Final = -2144796408 +TPMAPI_E_AUTHORIZATION_FAILED: Final = -2144796407 +TPMAPI_E_INVALID_CONTEXT_HANDLE: Final = -2144796406 +TPMAPI_E_TBS_COMMUNICATION_ERROR: Final = -2144796405 +TPMAPI_E_TPM_COMMAND_ERROR: Final = -2144796404 +TPMAPI_E_MESSAGE_TOO_LARGE: Final = -2144796403 +TPMAPI_E_INVALID_ENCODING: Final = -2144796402 +TPMAPI_E_INVALID_KEY_SIZE: Final = -2144796401 +TPMAPI_E_ENCRYPTION_FAILED: Final = -2144796400 +TPMAPI_E_INVALID_KEY_PARAMS: Final = -2144796399 +TPMAPI_E_INVALID_MIGRATION_AUTHORIZATION_BLOB: Final = -2144796398 +TPMAPI_E_INVALID_PCR_INDEX: Final = -2144796397 +TPMAPI_E_INVALID_DELEGATE_BLOB: Final = -2144796396 +TPMAPI_E_INVALID_CONTEXT_PARAMS: Final = -2144796395 +TPMAPI_E_INVALID_KEY_BLOB: Final = -2144796394 +TPMAPI_E_INVALID_PCR_DATA: Final = -2144796393 +TPMAPI_E_INVALID_OWNER_AUTH: Final = -2144796392 +TPMAPI_E_FIPS_RNG_CHECK_FAILED: Final = -2144796391 +TPMAPI_E_EMPTY_TCG_LOG: Final = -2144796390 +TPMAPI_E_INVALID_TCG_LOG_ENTRY: Final = -2144796389 +TPMAPI_E_TCG_SEPARATOR_ABSENT: Final = -2144796388 +TPMAPI_E_TCG_INVALID_DIGEST_ENTRY: Final = -2144796387 +TPMAPI_E_POLICY_DENIES_OPERATION: Final = -2144796386 +TPMAPI_E_NV_BITS_NOT_DEFINED: Final = -2144796385 +TPMAPI_E_NV_BITS_NOT_READY: Final = -2144796384 +TPMAPI_E_SEALING_KEY_NOT_AVAILABLE: Final = -2144796383 +TPMAPI_E_NO_AUTHORIZATION_CHAIN_FOUND: Final = -2144796382 +TPMAPI_E_SVN_COUNTER_NOT_AVAILABLE: Final = -2144796381 +TPMAPI_E_OWNER_AUTH_NOT_NULL: Final = -2144796380 +TPMAPI_E_ENDORSEMENT_AUTH_NOT_NULL: Final = -2144796379 +TPMAPI_E_AUTHORIZATION_REVOKED: Final = -2144796378 +TPMAPI_E_MALFORMED_AUTHORIZATION_KEY: Final = -2144796377 +TPMAPI_E_AUTHORIZING_KEY_NOT_SUPPORTED: Final = -2144796376 +TPMAPI_E_INVALID_AUTHORIZATION_SIGNATURE: Final = -2144796375 +TPMAPI_E_MALFORMED_AUTHORIZATION_POLICY: Final = -2144796374 +TPMAPI_E_MALFORMED_AUTHORIZATION_OTHER: Final = -2144796373 +TPMAPI_E_SEALING_KEY_CHANGED: Final = -2144796372 +TPMAPI_E_INVALID_TPM_VERSION: Final = -2144796371 +TPMAPI_E_INVALID_POLICYAUTH_BLOB_TYPE: Final = -2144796370 +TBSIMP_E_BUFFER_TOO_SMALL: Final = -2144796160 +TBSIMP_E_CLEANUP_FAILED: Final = -2144796159 +TBSIMP_E_INVALID_CONTEXT_HANDLE: Final = -2144796158 +TBSIMP_E_INVALID_CONTEXT_PARAM: Final = -2144796157 +TBSIMP_E_TPM_ERROR: Final = -2144796156 +TBSIMP_E_HASH_BAD_KEY: Final = -2144796155 +TBSIMP_E_DUPLICATE_VHANDLE: Final = -2144796154 +TBSIMP_E_INVALID_OUTPUT_POINTER: Final = -2144796153 +TBSIMP_E_INVALID_PARAMETER: Final = -2144796152 +TBSIMP_E_RPC_INIT_FAILED: Final = -2144796151 +TBSIMP_E_SCHEDULER_NOT_RUNNING: Final = -2144796150 +TBSIMP_E_COMMAND_CANCELED: Final = -2144796149 +TBSIMP_E_OUT_OF_MEMORY: Final = -2144796148 +TBSIMP_E_LIST_NO_MORE_ITEMS: Final = -2144796147 +TBSIMP_E_LIST_NOT_FOUND: Final = -2144796146 +TBSIMP_E_NOT_ENOUGH_SPACE: Final = -2144796145 +TBSIMP_E_NOT_ENOUGH_TPM_CONTEXTS: Final = -2144796144 +TBSIMP_E_COMMAND_FAILED: Final = -2144796143 +TBSIMP_E_UNKNOWN_ORDINAL: Final = -2144796142 +TBSIMP_E_RESOURCE_EXPIRED: Final = -2144796141 +TBSIMP_E_INVALID_RESOURCE: Final = -2144796140 +TBSIMP_E_NOTHING_TO_UNLOAD: Final = -2144796139 +TBSIMP_E_HASH_TABLE_FULL: Final = -2144796138 +TBSIMP_E_TOO_MANY_TBS_CONTEXTS: Final = -2144796137 +TBSIMP_E_TOO_MANY_RESOURCES: Final = -2144796136 +TBSIMP_E_PPI_NOT_SUPPORTED: Final = -2144796135 +TBSIMP_E_TPM_INCOMPATIBLE: Final = -2144796134 +TBSIMP_E_NO_EVENT_LOG: Final = -2144796133 +TPM_E_PPI_ACPI_FAILURE: Final = -2144795904 +TPM_E_PPI_USER_ABORT: Final = -2144795903 +TPM_E_PPI_BIOS_FAILURE: Final = -2144795902 +TPM_E_PPI_NOT_SUPPORTED: Final = -2144795901 +TPM_E_PPI_BLOCKED_IN_BIOS: Final = -2144795900 +TPM_E_PCP_ERROR_MASK: Final = -2144795648 +TPM_E_PCP_DEVICE_NOT_READY: Final = -2144795647 +TPM_E_PCP_INVALID_HANDLE: Final = -2144795646 +TPM_E_PCP_INVALID_PARAMETER: Final = -2144795645 +TPM_E_PCP_FLAG_NOT_SUPPORTED: Final = -2144795644 +TPM_E_PCP_NOT_SUPPORTED: Final = -2144795643 +TPM_E_PCP_BUFFER_TOO_SMALL: Final = -2144795642 +TPM_E_PCP_INTERNAL_ERROR: Final = -2144795641 +TPM_E_PCP_AUTHENTICATION_FAILED: Final = -2144795640 +TPM_E_PCP_AUTHENTICATION_IGNORED: Final = -2144795639 +TPM_E_PCP_POLICY_NOT_FOUND: Final = -2144795638 +TPM_E_PCP_PROFILE_NOT_FOUND: Final = -2144795637 +TPM_E_PCP_VALIDATION_FAILED: Final = -2144795636 +TPM_E_PCP_WRONG_PARENT: Final = -2144795634 +TPM_E_KEY_NOT_LOADED: Final = -2144795633 +TPM_E_NO_KEY_CERTIFICATION: Final = -2144795632 +TPM_E_KEY_NOT_FINALIZED: Final = -2144795631 +TPM_E_ATTESTATION_CHALLENGE_NOT_SET: Final = -2144795630 +TPM_E_NOT_PCR_BOUND: Final = -2144795629 +TPM_E_KEY_ALREADY_FINALIZED: Final = -2144795628 +TPM_E_KEY_USAGE_POLICY_NOT_SUPPORTED: Final = -2144795627 +TPM_E_KEY_USAGE_POLICY_INVALID: Final = -2144795626 +TPM_E_SOFT_KEY_ERROR: Final = -2144795625 +TPM_E_KEY_NOT_AUTHENTICATED: Final = -2144795624 +TPM_E_PCP_KEY_NOT_AIK: Final = -2144795623 +TPM_E_KEY_NOT_SIGNING_KEY: Final = -2144795622 +TPM_E_LOCKED_OUT: Final = -2144795621 +TPM_E_CLAIM_TYPE_NOT_SUPPORTED: Final = -2144795620 +TPM_E_VERSION_NOT_SUPPORTED: Final = -2144795619 +TPM_E_BUFFER_LENGTH_MISMATCH: Final = -2144795618 +TPM_E_PCP_IFX_RSA_KEY_CREATION_BLOCKED: Final = -2144795617 +TPM_E_PCP_TICKET_MISSING: Final = -2144795616 +TPM_E_PCP_RAW_POLICY_NOT_SUPPORTED: Final = -2144795615 +TPM_E_PCP_KEY_HANDLE_INVALIDATED: Final = -2144795614 +TPM_E_PCP_UNSUPPORTED_PSS_SALT: Final = 0x40290423 +TPM_E_PCP_PLATFORM_CLAIM_MAY_BE_OUTDATED: Final = 0x40290424 +TPM_E_PCP_PLATFORM_CLAIM_OUTDATED: Final = 0x40290425 +TPM_E_PCP_PLATFORM_CLAIM_REBOOT: Final = 0x40290426 +TPM_E_ZERO_EXHAUST_ENABLED: Final = -2144795392 +TPM_E_PROVISIONING_INCOMPLETE: Final = -2144795136 +TPM_E_INVALID_OWNER_AUTH: Final = -2144795135 +TPM_E_TOO_MUCH_DATA: Final = -2144795134 +TPM_E_TPM_GENERATED_EPS: Final = -2144795133 +PLA_E_DCS_NOT_FOUND: Final = -2144337918 +PLA_E_DCS_IN_USE: Final = -2144337750 +PLA_E_TOO_MANY_FOLDERS: Final = -2144337851 +PLA_E_NO_MIN_DISK: Final = -2144337808 +PLA_E_DCS_ALREADY_EXISTS: Final = -2144337737 +PLA_S_PROPERTY_IGNORED: Final = 0x00300100 +PLA_E_PROPERTY_CONFLICT: Final = -2144337663 +PLA_E_DCS_SINGLETON_REQUIRED: Final = -2144337662 +PLA_E_CREDENTIALS_REQUIRED: Final = -2144337661 +PLA_E_DCS_NOT_RUNNING: Final = -2144337660 +PLA_E_CONFLICT_INCL_EXCL_API: Final = -2144337659 +PLA_E_NETWORK_EXE_NOT_VALID: Final = -2144337658 +PLA_E_EXE_ALREADY_CONFIGURED: Final = -2144337657 +PLA_E_EXE_PATH_NOT_VALID: Final = -2144337656 +PLA_E_DC_ALREADY_EXISTS: Final = -2144337655 +PLA_E_DCS_START_WAIT_TIMEOUT: Final = -2144337654 +PLA_E_DC_START_WAIT_TIMEOUT: Final = -2144337653 +PLA_E_REPORT_WAIT_TIMEOUT: Final = -2144337652 +PLA_E_NO_DUPLICATES: Final = -2144337651 +PLA_E_EXE_FULL_PATH_REQUIRED: Final = -2144337650 +PLA_E_INVALID_SESSION_NAME: Final = -2144337649 +PLA_E_PLA_CHANNEL_NOT_ENABLED: Final = -2144337648 +PLA_E_TASKSCHED_CHANNEL_NOT_ENABLED: Final = -2144337647 +PLA_E_RULES_MANAGER_FAILED: Final = -2144337646 +PLA_E_CABAPI_FAILURE: Final = -2144337645 +FVE_E_LOCKED_VOLUME: Final = -2144272384 +FVE_E_NOT_ENCRYPTED: Final = -2144272383 +FVE_E_NO_TPM_BIOS: Final = -2144272382 +FVE_E_NO_MBR_METRIC: Final = -2144272381 +FVE_E_NO_BOOTSECTOR_METRIC: Final = -2144272380 +FVE_E_NO_BOOTMGR_METRIC: Final = -2144272379 +FVE_E_WRONG_BOOTMGR: Final = -2144272378 +FVE_E_SECURE_KEY_REQUIRED: Final = -2144272377 +FVE_E_NOT_ACTIVATED: Final = -2144272376 +FVE_E_ACTION_NOT_ALLOWED: Final = -2144272375 +FVE_E_AD_SCHEMA_NOT_INSTALLED: Final = -2144272374 +FVE_E_AD_INVALID_DATATYPE: Final = -2144272373 +FVE_E_AD_INVALID_DATASIZE: Final = -2144272372 +FVE_E_AD_NO_VALUES: Final = -2144272371 +FVE_E_AD_ATTR_NOT_SET: Final = -2144272370 +FVE_E_AD_GUID_NOT_FOUND: Final = -2144272369 +FVE_E_BAD_INFORMATION: Final = -2144272368 +FVE_E_TOO_SMALL: Final = -2144272367 +FVE_E_SYSTEM_VOLUME: Final = -2144272366 +FVE_E_FAILED_WRONG_FS: Final = -2144272365 +FVE_E_BAD_PARTITION_SIZE: Final = -2144272364 +FVE_E_NOT_SUPPORTED: Final = -2144272363 +FVE_E_BAD_DATA: Final = -2144272362 +FVE_E_VOLUME_NOT_BOUND: Final = -2144272361 +FVE_E_TPM_NOT_OWNED: Final = -2144272360 +FVE_E_NOT_DATA_VOLUME: Final = -2144272359 +FVE_E_AD_INSUFFICIENT_BUFFER: Final = -2144272358 +FVE_E_CONV_READ: Final = -2144272357 +FVE_E_CONV_WRITE: Final = -2144272356 +FVE_E_KEY_REQUIRED: Final = -2144272355 +FVE_E_CLUSTERING_NOT_SUPPORTED: Final = -2144272354 +FVE_E_VOLUME_BOUND_ALREADY: Final = -2144272353 +FVE_E_OS_NOT_PROTECTED: Final = -2144272352 +FVE_E_PROTECTION_DISABLED: Final = -2144272351 +FVE_E_RECOVERY_KEY_REQUIRED: Final = -2144272350 +FVE_E_FOREIGN_VOLUME: Final = -2144272349 +FVE_E_OVERLAPPED_UPDATE: Final = -2144272348 +FVE_E_TPM_SRK_AUTH_NOT_ZERO: Final = -2144272347 +FVE_E_FAILED_SECTOR_SIZE: Final = -2144272346 +FVE_E_FAILED_AUTHENTICATION: Final = -2144272345 +FVE_E_NOT_OS_VOLUME: Final = -2144272344 +FVE_E_AUTOUNLOCK_ENABLED: Final = -2144272343 +FVE_E_WRONG_BOOTSECTOR: Final = -2144272342 +FVE_E_WRONG_SYSTEM_FS: Final = -2144272341 +FVE_E_POLICY_PASSWORD_REQUIRED: Final = -2144272340 +FVE_E_CANNOT_SET_FVEK_ENCRYPTED: Final = -2144272339 +FVE_E_CANNOT_ENCRYPT_NO_KEY: Final = -2144272338 +FVE_E_BOOTABLE_CDDVD: Final = -2144272336 +FVE_E_PROTECTOR_EXISTS: Final = -2144272335 +FVE_E_RELATIVE_PATH: Final = -2144272334 +FVE_E_PROTECTOR_NOT_FOUND: Final = -2144272333 +FVE_E_INVALID_KEY_FORMAT: Final = -2144272332 +FVE_E_INVALID_PASSWORD_FORMAT: Final = -2144272331 +FVE_E_FIPS_RNG_CHECK_FAILED: Final = -2144272330 +FVE_E_FIPS_PREVENTS_RECOVERY_PASSWORD: Final = -2144272329 +FVE_E_FIPS_PREVENTS_EXTERNAL_KEY_EXPORT: Final = -2144272328 +FVE_E_NOT_DECRYPTED: Final = -2144272327 +FVE_E_INVALID_PROTECTOR_TYPE: Final = -2144272326 +FVE_E_NO_PROTECTORS_TO_TEST: Final = -2144272325 +FVE_E_KEYFILE_NOT_FOUND: Final = -2144272324 +FVE_E_KEYFILE_INVALID: Final = -2144272323 +FVE_E_KEYFILE_NO_VMK: Final = -2144272322 +FVE_E_TPM_DISABLED: Final = -2144272321 +FVE_E_NOT_ALLOWED_IN_SAFE_MODE: Final = -2144272320 +FVE_E_TPM_INVALID_PCR: Final = -2144272319 +FVE_E_TPM_NO_VMK: Final = -2144272318 +FVE_E_PIN_INVALID: Final = -2144272317 +FVE_E_AUTH_INVALID_APPLICATION: Final = -2144272316 +FVE_E_AUTH_INVALID_CONFIG: Final = -2144272315 +FVE_E_FIPS_DISABLE_PROTECTION_NOT_ALLOWED: Final = -2144272314 +FVE_E_FS_NOT_EXTENDED: Final = -2144272313 +FVE_E_FIRMWARE_TYPE_NOT_SUPPORTED: Final = -2144272312 +FVE_E_NO_LICENSE: Final = -2144272311 +FVE_E_NOT_ON_STACK: Final = -2144272310 +FVE_E_FS_MOUNTED: Final = -2144272309 +FVE_E_TOKEN_NOT_IMPERSONATED: Final = -2144272308 +FVE_E_DRY_RUN_FAILED: Final = -2144272307 +FVE_E_REBOOT_REQUIRED: Final = -2144272306 +FVE_E_DEBUGGER_ENABLED: Final = -2144272305 +FVE_E_RAW_ACCESS: Final = -2144272304 +FVE_E_RAW_BLOCKED: Final = -2144272303 +FVE_E_BCD_APPLICATIONS_PATH_INCORRECT: Final = -2144272302 +FVE_E_NOT_ALLOWED_IN_VERSION: Final = -2144272301 +FVE_E_NO_AUTOUNLOCK_MASTER_KEY: Final = -2144272300 +FVE_E_MOR_FAILED: Final = -2144272299 +FVE_E_HIDDEN_VOLUME: Final = -2144272298 +FVE_E_TRANSIENT_STATE: Final = -2144272297 +FVE_E_PUBKEY_NOT_ALLOWED: Final = -2144272296 +FVE_E_VOLUME_HANDLE_OPEN: Final = -2144272295 +FVE_E_NO_FEATURE_LICENSE: Final = -2144272294 +FVE_E_INVALID_STARTUP_OPTIONS: Final = -2144272293 +FVE_E_POLICY_RECOVERY_PASSWORD_NOT_ALLOWED: Final = -2144272292 +FVE_E_POLICY_RECOVERY_PASSWORD_REQUIRED: Final = -2144272291 +FVE_E_POLICY_RECOVERY_KEY_NOT_ALLOWED: Final = -2144272290 +FVE_E_POLICY_RECOVERY_KEY_REQUIRED: Final = -2144272289 +FVE_E_POLICY_STARTUP_PIN_NOT_ALLOWED: Final = -2144272288 +FVE_E_POLICY_STARTUP_PIN_REQUIRED: Final = -2144272287 +FVE_E_POLICY_STARTUP_KEY_NOT_ALLOWED: Final = -2144272286 +FVE_E_POLICY_STARTUP_KEY_REQUIRED: Final = -2144272285 +FVE_E_POLICY_STARTUP_PIN_KEY_NOT_ALLOWED: Final = -2144272284 +FVE_E_POLICY_STARTUP_PIN_KEY_REQUIRED: Final = -2144272283 +FVE_E_POLICY_STARTUP_TPM_NOT_ALLOWED: Final = -2144272282 +FVE_E_POLICY_STARTUP_TPM_REQUIRED: Final = -2144272281 +FVE_E_POLICY_INVALID_PIN_LENGTH: Final = -2144272280 +FVE_E_KEY_PROTECTOR_NOT_SUPPORTED: Final = -2144272279 +FVE_E_POLICY_PASSPHRASE_NOT_ALLOWED: Final = -2144272278 +FVE_E_POLICY_PASSPHRASE_REQUIRED: Final = -2144272277 +FVE_E_FIPS_PREVENTS_PASSPHRASE: Final = -2144272276 +FVE_E_OS_VOLUME_PASSPHRASE_NOT_ALLOWED: Final = -2144272275 +FVE_E_INVALID_BITLOCKER_OID: Final = -2144272274 +FVE_E_VOLUME_TOO_SMALL: Final = -2144272273 +FVE_E_DV_NOT_SUPPORTED_ON_FS: Final = -2144272272 +FVE_E_DV_NOT_ALLOWED_BY_GP: Final = -2144272271 +FVE_E_POLICY_USER_CERTIFICATE_NOT_ALLOWED: Final = -2144272270 +FVE_E_POLICY_USER_CERTIFICATE_REQUIRED: Final = -2144272269 +FVE_E_POLICY_USER_CERT_MUST_BE_HW: Final = -2144272268 +FVE_E_POLICY_USER_CONFIGURE_FDV_AUTOUNLOCK_NOT_ALLOWED: Final = -2144272267 +FVE_E_POLICY_USER_CONFIGURE_RDV_AUTOUNLOCK_NOT_ALLOWED: Final = -2144272266 +FVE_E_POLICY_USER_CONFIGURE_RDV_NOT_ALLOWED: Final = -2144272265 +FVE_E_POLICY_USER_ENABLE_RDV_NOT_ALLOWED: Final = -2144272264 +FVE_E_POLICY_USER_DISABLE_RDV_NOT_ALLOWED: Final = -2144272263 +FVE_E_POLICY_INVALID_PASSPHRASE_LENGTH: Final = -2144272256 +FVE_E_POLICY_PASSPHRASE_TOO_SIMPLE: Final = -2144272255 +FVE_E_RECOVERY_PARTITION: Final = -2144272254 +FVE_E_POLICY_CONFLICT_FDV_RK_OFF_AUK_ON: Final = -2144272253 +FVE_E_POLICY_CONFLICT_RDV_RK_OFF_AUK_ON: Final = -2144272252 +FVE_E_NON_BITLOCKER_OID: Final = -2144272251 +FVE_E_POLICY_PROHIBITS_SELFSIGNED: Final = -2144272250 +FVE_E_POLICY_CONFLICT_RO_AND_STARTUP_KEY_REQUIRED: Final = -2144272249 +FVE_E_CONV_RECOVERY_FAILED: Final = -2144272248 +FVE_E_VIRTUALIZED_SPACE_TOO_BIG: Final = -2144272247 +FVE_E_POLICY_CONFLICT_OSV_RP_OFF_ADB_ON: Final = -2144272240 +FVE_E_POLICY_CONFLICT_FDV_RP_OFF_ADB_ON: Final = -2144272239 +FVE_E_POLICY_CONFLICT_RDV_RP_OFF_ADB_ON: Final = -2144272238 +FVE_E_NON_BITLOCKER_KU: Final = -2144272237 +FVE_E_PRIVATEKEY_AUTH_FAILED: Final = -2144272236 +FVE_E_REMOVAL_OF_DRA_FAILED: Final = -2144272235 +FVE_E_OPERATION_NOT_SUPPORTED_ON_VISTA_VOLUME: Final = -2144272234 +FVE_E_CANT_LOCK_AUTOUNLOCK_ENABLED_VOLUME: Final = -2144272233 +FVE_E_FIPS_HASH_KDF_NOT_ALLOWED: Final = -2144272232 +FVE_E_ENH_PIN_INVALID: Final = -2144272231 +FVE_E_INVALID_PIN_CHARS: Final = -2144272230 +FVE_E_INVALID_DATUM_TYPE: Final = -2144272229 +FVE_E_EFI_ONLY: Final = -2144272228 +FVE_E_MULTIPLE_NKP_CERTS: Final = -2144272227 +FVE_E_REMOVAL_OF_NKP_FAILED: Final = -2144272226 +FVE_E_INVALID_NKP_CERT: Final = -2144272225 +FVE_E_NO_EXISTING_PIN: Final = -2144272224 +FVE_E_PROTECTOR_CHANGE_PIN_MISMATCH: Final = -2144272223 +FVE_E_PIN_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: Final = -2144272222 +FVE_E_PROTECTOR_CHANGE_MAX_PIN_CHANGE_ATTEMPTS_REACHED: Final = -2144272221 +FVE_E_POLICY_PASSPHRASE_REQUIRES_ASCII: Final = -2144272220 +FVE_E_FULL_ENCRYPTION_NOT_ALLOWED_ON_TP_STORAGE: Final = -2144272219 +FVE_E_WIPE_NOT_ALLOWED_ON_TP_STORAGE: Final = -2144272218 +FVE_E_KEY_LENGTH_NOT_SUPPORTED_BY_EDRIVE: Final = -2144272217 +FVE_E_NO_EXISTING_PASSPHRASE: Final = -2144272216 +FVE_E_PROTECTOR_CHANGE_PASSPHRASE_MISMATCH: Final = -2144272215 +FVE_E_PASSPHRASE_TOO_LONG: Final = -2144272214 +FVE_E_NO_PASSPHRASE_WITH_TPM: Final = -2144272213 +FVE_E_NO_TPM_WITH_PASSPHRASE: Final = -2144272212 +FVE_E_NOT_ALLOWED_ON_CSV_STACK: Final = -2144272211 +FVE_E_NOT_ALLOWED_ON_CLUSTER: Final = -2144272210 +FVE_E_EDRIVE_NO_FAILOVER_TO_SW: Final = -2144272209 +FVE_E_EDRIVE_BAND_IN_USE: Final = -2144272208 +FVE_E_EDRIVE_DISALLOWED_BY_GP: Final = -2144272207 +FVE_E_EDRIVE_INCOMPATIBLE_VOLUME: Final = -2144272206 +FVE_E_NOT_ALLOWED_TO_UPGRADE_WHILE_CONVERTING: Final = -2144272205 +FVE_E_EDRIVE_DV_NOT_SUPPORTED: Final = -2144272204 +FVE_E_NO_PREBOOT_KEYBOARD_DETECTED: Final = -2144272203 +FVE_E_NO_PREBOOT_KEYBOARD_OR_WINRE_DETECTED: Final = -2144272202 +FVE_E_POLICY_REQUIRES_STARTUP_PIN_ON_TOUCH_DEVICE: Final = -2144272201 +FVE_E_POLICY_REQUIRES_RECOVERY_PASSWORD_ON_TOUCH_DEVICE: Final = -2144272200 +FVE_E_WIPE_CANCEL_NOT_APPLICABLE: Final = -2144272199 +FVE_E_SECUREBOOT_DISABLED: Final = -2144272198 +FVE_E_SECUREBOOT_CONFIGURATION_INVALID: Final = -2144272197 +FVE_E_EDRIVE_DRY_RUN_FAILED: Final = -2144272196 +FVE_E_SHADOW_COPY_PRESENT: Final = -2144272195 +FVE_E_POLICY_INVALID_ENHANCED_BCD_SETTINGS: Final = -2144272194 +FVE_E_EDRIVE_INCOMPATIBLE_FIRMWARE: Final = -2144272193 +FVE_E_PROTECTOR_CHANGE_MAX_PASSPHRASE_CHANGE_ATTEMPTS_REACHED: Final = -2144272192 +FVE_E_PASSPHRASE_PROTECTOR_CHANGE_BY_STD_USER_DISALLOWED: Final = -2144272191 +FVE_E_LIVEID_ACCOUNT_SUSPENDED: Final = -2144272190 +FVE_E_LIVEID_ACCOUNT_BLOCKED: Final = -2144272189 +FVE_E_NOT_PROVISIONED_ON_ALL_VOLUMES: Final = -2144272188 +FVE_E_DE_FIXED_DATA_NOT_SUPPORTED: Final = -2144272187 +FVE_E_DE_HARDWARE_NOT_COMPLIANT: Final = -2144272186 +FVE_E_DE_WINRE_NOT_CONFIGURED: Final = -2144272185 +FVE_E_DE_PROTECTION_SUSPENDED: Final = -2144272184 +FVE_E_DE_OS_VOLUME_NOT_PROTECTED: Final = -2144272183 +FVE_E_DE_DEVICE_LOCKEDOUT: Final = -2144272182 +FVE_E_DE_PROTECTION_NOT_YET_ENABLED: Final = -2144272181 +FVE_E_INVALID_PIN_CHARS_DETAILED: Final = -2144272180 +FVE_E_DEVICE_LOCKOUT_COUNTER_UNAVAILABLE: Final = -2144272179 +FVE_E_DEVICELOCKOUT_COUNTER_MISMATCH: Final = -2144272178 +FVE_E_BUFFER_TOO_LARGE: Final = -2144272177 +FVE_E_NO_SUCH_CAPABILITY_ON_TARGET: Final = -2144272176 +FVE_E_DE_PREVENTED_FOR_OS: Final = -2144272175 +FVE_E_DE_VOLUME_OPTED_OUT: Final = -2144272174 +FVE_E_DE_VOLUME_NOT_SUPPORTED: Final = -2144272173 +FVE_E_EOW_NOT_SUPPORTED_IN_VERSION: Final = -2144272172 +FVE_E_ADBACKUP_NOT_ENABLED: Final = -2144272171 +FVE_E_VOLUME_EXTEND_PREVENTS_EOW_DECRYPT: Final = -2144272170 +FVE_E_NOT_DE_VOLUME: Final = -2144272169 +FVE_E_PROTECTION_CANNOT_BE_DISABLED: Final = -2144272168 +FVE_E_OSV_KSR_NOT_ALLOWED: Final = -2144272167 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_OS_DRIVE: Final = -2144272166 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_FIXED_DRIVE: Final = -2144272165 +FVE_E_AD_BACKUP_REQUIRED_POLICY_NOT_SET_REMOVABLE_DRIVE: Final = -2144272164 +FVE_E_KEY_ROTATION_NOT_SUPPORTED: Final = -2144272163 +FVE_E_EXECUTE_REQUEST_SENT_TOO_SOON: Final = -2144272162 +FVE_E_KEY_ROTATION_NOT_ENABLED: Final = -2144272161 +FVE_E_DEVICE_NOT_JOINED: Final = -2144272160 +FVE_E_AAD_ENDPOINT_BUSY: Final = -2144272159 +FVE_E_INVALID_NBP_CERT: Final = -2144272158 +FVE_E_EDRIVE_BAND_ENUMERATION_FAILED: Final = -2144272157 +FVE_E_POLICY_ON_RDV_EXCLUSION_LIST: Final = -2144272156 +FVE_E_PREDICTED_TPM_PROTECTOR_NOT_SUPPORTED: Final = -2144272155 +FVE_E_SETUP_TPM_CALLBACK_NOT_SUPPORTED: Final = -2144272154 +FVE_E_TPM_CONTEXT_SETUP_NOT_SUPPORTED: Final = -2144272153 +FVE_E_UPDATE_INVALID_CONFIG: Final = -2144272152 +FVE_E_AAD_SERVER_FAIL_RETRY_AFTER: Final = -2144272151 +FVE_E_AAD_SERVER_FAIL_BACKOFF: Final = -2144272150 +FVE_E_DATASET_FULL: Final = -2144272149 +FVE_E_METADATA_FULL: Final = -2144272148 +FWP_E_CALLOUT_NOT_FOUND: Final = -2144206847 +FWP_E_CONDITION_NOT_FOUND: Final = -2144206846 +FWP_E_FILTER_NOT_FOUND: Final = -2144206845 +FWP_E_LAYER_NOT_FOUND: Final = -2144206844 +FWP_E_PROVIDER_NOT_FOUND: Final = -2144206843 +FWP_E_PROVIDER_CONTEXT_NOT_FOUND: Final = -2144206842 +FWP_E_SUBLAYER_NOT_FOUND: Final = -2144206841 +FWP_E_NOT_FOUND: Final = -2144206840 +FWP_E_ALREADY_EXISTS: Final = -2144206839 +FWP_E_IN_USE: Final = -2144206838 +FWP_E_DYNAMIC_SESSION_IN_PROGRESS: Final = -2144206837 +FWP_E_WRONG_SESSION: Final = -2144206836 +FWP_E_NO_TXN_IN_PROGRESS: Final = -2144206835 +FWP_E_TXN_IN_PROGRESS: Final = -2144206834 +FWP_E_TXN_ABORTED: Final = -2144206833 +FWP_E_SESSION_ABORTED: Final = -2144206832 +FWP_E_INCOMPATIBLE_TXN: Final = -2144206831 +FWP_E_TIMEOUT: Final = -2144206830 +FWP_E_NET_EVENTS_DISABLED: Final = -2144206829 +FWP_E_INCOMPATIBLE_LAYER: Final = -2144206828 +FWP_E_KM_CLIENTS_ONLY: Final = -2144206827 +FWP_E_LIFETIME_MISMATCH: Final = -2144206826 +FWP_E_BUILTIN_OBJECT: Final = -2144206825 +FWP_E_TOO_MANY_CALLOUTS: Final = -2144206824 +FWP_E_NOTIFICATION_DROPPED: Final = -2144206823 +FWP_E_TRAFFIC_MISMATCH: Final = -2144206822 +FWP_E_INCOMPATIBLE_SA_STATE: Final = -2144206821 +FWP_E_NULL_POINTER: Final = -2144206820 +FWP_E_INVALID_ENUMERATOR: Final = -2144206819 +FWP_E_INVALID_FLAGS: Final = -2144206818 +FWP_E_INVALID_NET_MASK: Final = -2144206817 +FWP_E_INVALID_RANGE: Final = -2144206816 +FWP_E_INVALID_INTERVAL: Final = -2144206815 +FWP_E_ZERO_LENGTH_ARRAY: Final = -2144206814 +FWP_E_NULL_DISPLAY_NAME: Final = -2144206813 +FWP_E_INVALID_ACTION_TYPE: Final = -2144206812 +FWP_E_INVALID_WEIGHT: Final = -2144206811 +FWP_E_MATCH_TYPE_MISMATCH: Final = -2144206810 +FWP_E_TYPE_MISMATCH: Final = -2144206809 +FWP_E_OUT_OF_BOUNDS: Final = -2144206808 +FWP_E_RESERVED: Final = -2144206807 +FWP_E_DUPLICATE_CONDITION: Final = -2144206806 +FWP_E_DUPLICATE_KEYMOD: Final = -2144206805 +FWP_E_ACTION_INCOMPATIBLE_WITH_LAYER: Final = -2144206804 +FWP_E_ACTION_INCOMPATIBLE_WITH_SUBLAYER: Final = -2144206803 +FWP_E_CONTEXT_INCOMPATIBLE_WITH_LAYER: Final = -2144206802 +FWP_E_CONTEXT_INCOMPATIBLE_WITH_CALLOUT: Final = -2144206801 +FWP_E_INCOMPATIBLE_AUTH_METHOD: Final = -2144206800 +FWP_E_INCOMPATIBLE_DH_GROUP: Final = -2144206799 +FWP_E_EM_NOT_SUPPORTED: Final = -2144206798 +FWP_E_NEVER_MATCH: Final = -2144206797 +FWP_E_PROVIDER_CONTEXT_MISMATCH: Final = -2144206796 +FWP_E_INVALID_PARAMETER: Final = -2144206795 +FWP_E_TOO_MANY_SUBLAYERS: Final = -2144206794 +FWP_E_CALLOUT_NOTIFICATION_FAILED: Final = -2144206793 +FWP_E_INVALID_AUTH_TRANSFORM: Final = -2144206792 +FWP_E_INVALID_CIPHER_TRANSFORM: Final = -2144206791 +FWP_E_INCOMPATIBLE_CIPHER_TRANSFORM: Final = -2144206790 +FWP_E_INVALID_TRANSFORM_COMBINATION: Final = -2144206789 +FWP_E_DUPLICATE_AUTH_METHOD: Final = -2144206788 +FWP_E_INVALID_TUNNEL_ENDPOINT: Final = -2144206787 +FWP_E_L2_DRIVER_NOT_READY: Final = -2144206786 +FWP_E_KEY_DICTATOR_ALREADY_REGISTERED: Final = -2144206785 +FWP_E_KEY_DICTATION_INVALID_KEYING_MATERIAL: Final = -2144206784 +FWP_E_CONNECTIONS_DISABLED: Final = -2144206783 +FWP_E_INVALID_DNS_NAME: Final = -2144206782 +FWP_E_STILL_ON: Final = -2144206781 +FWP_E_IKEEXT_NOT_RUNNING: Final = -2144206780 +FWP_E_DROP_NOICMP: Final = -2144206588 +WS_S_ASYNC: Final = 0x003D0000 +WS_S_END: Final = 0x003D0001 +WS_E_INVALID_FORMAT: Final = -2143485952 +WS_E_OBJECT_FAULTED: Final = -2143485951 +WS_E_NUMERIC_OVERFLOW: Final = -2143485950 +WS_E_INVALID_OPERATION: Final = -2143485949 +WS_E_OPERATION_ABORTED: Final = -2143485948 +WS_E_ENDPOINT_ACCESS_DENIED: Final = -2143485947 +WS_E_OPERATION_TIMED_OUT: Final = -2143485946 +WS_E_OPERATION_ABANDONED: Final = -2143485945 +WS_E_QUOTA_EXCEEDED: Final = -2143485944 +WS_E_NO_TRANSLATION_AVAILABLE: Final = -2143485943 +WS_E_SECURITY_VERIFICATION_FAILURE: Final = -2143485942 +WS_E_ADDRESS_IN_USE: Final = -2143485941 +WS_E_ADDRESS_NOT_AVAILABLE: Final = -2143485940 +WS_E_ENDPOINT_NOT_FOUND: Final = -2143485939 +WS_E_ENDPOINT_NOT_AVAILABLE: Final = -2143485938 +WS_E_ENDPOINT_FAILURE: Final = -2143485937 +WS_E_ENDPOINT_UNREACHABLE: Final = -2143485936 +WS_E_ENDPOINT_ACTION_NOT_SUPPORTED: Final = -2143485935 +WS_E_ENDPOINT_TOO_BUSY: Final = -2143485934 +WS_E_ENDPOINT_FAULT_RECEIVED: Final = -2143485933 +WS_E_ENDPOINT_DISCONNECTED: Final = -2143485932 +WS_E_PROXY_FAILURE: Final = -2143485931 +WS_E_PROXY_ACCESS_DENIED: Final = -2143485930 +WS_E_NOT_SUPPORTED: Final = -2143485929 +WS_E_PROXY_REQUIRES_BASIC_AUTH: Final = -2143485928 +WS_E_PROXY_REQUIRES_DIGEST_AUTH: Final = -2143485927 +WS_E_PROXY_REQUIRES_NTLM_AUTH: Final = -2143485926 +WS_E_PROXY_REQUIRES_NEGOTIATE_AUTH: Final = -2143485925 +WS_E_SERVER_REQUIRES_BASIC_AUTH: Final = -2143485924 +WS_E_SERVER_REQUIRES_DIGEST_AUTH: Final = -2143485923 +WS_E_SERVER_REQUIRES_NTLM_AUTH: Final = -2143485922 +WS_E_SERVER_REQUIRES_NEGOTIATE_AUTH: Final = -2143485921 +WS_E_INVALID_ENDPOINT_URL: Final = -2143485920 +WS_E_OTHER: Final = -2143485919 +WS_E_SECURITY_TOKEN_EXPIRED: Final = -2143485918 +WS_E_SECURITY_SYSTEM_FAILURE: Final = -2143485917 + +ERROR_NDIS_INTERFACE_CLOSING: Final = -2144075774 +ERROR_NDIS_BAD_VERSION: Final = -2144075772 +ERROR_NDIS_BAD_CHARACTERISTICS: Final = -2144075771 +ERROR_NDIS_ADAPTER_NOT_FOUND: Final = -2144075770 +ERROR_NDIS_OPEN_FAILED: Final = -2144075769 +ERROR_NDIS_DEVICE_FAILED: Final = -2144075768 +ERROR_NDIS_MULTICAST_FULL: Final = -2144075767 +ERROR_NDIS_MULTICAST_EXISTS: Final = -2144075766 +ERROR_NDIS_MULTICAST_NOT_FOUND: Final = -2144075765 +ERROR_NDIS_REQUEST_ABORTED: Final = -2144075764 +ERROR_NDIS_RESET_IN_PROGRESS: Final = -2144075763 +ERROR_NDIS_NOT_SUPPORTED: Final = -2144075589 +ERROR_NDIS_INVALID_PACKET: Final = -2144075761 +ERROR_NDIS_ADAPTER_NOT_READY: Final = -2144075759 +ERROR_NDIS_INVALID_LENGTH: Final = -2144075756 +ERROR_NDIS_INVALID_DATA: Final = -2144075755 +ERROR_NDIS_BUFFER_TOO_SHORT: Final = -2144075754 +ERROR_NDIS_INVALID_OID: Final = -2144075753 +ERROR_NDIS_ADAPTER_REMOVED: Final = -2144075752 +ERROR_NDIS_UNSUPPORTED_MEDIA: Final = -2144075751 +ERROR_NDIS_GROUP_ADDRESS_IN_USE: Final = -2144075750 +ERROR_NDIS_FILE_NOT_FOUND: Final = -2144075749 +ERROR_NDIS_ERROR_READING_FILE: Final = -2144075748 +ERROR_NDIS_ALREADY_MAPPED: Final = -2144075747 +ERROR_NDIS_RESOURCE_CONFLICT: Final = -2144075746 +ERROR_NDIS_MEDIA_DISCONNECTED: Final = -2144075745 +ERROR_NDIS_INVALID_ADDRESS: Final = -2144075742 +ERROR_NDIS_INVALID_DEVICE_REQUEST: Final = -2144075760 +ERROR_NDIS_PAUSED: Final = -2144075734 +ERROR_NDIS_INTERFACE_NOT_FOUND: Final = -2144075733 +ERROR_NDIS_UNSUPPORTED_REVISION: Final = -2144075732 +ERROR_NDIS_INVALID_PORT: Final = -2144075731 +ERROR_NDIS_INVALID_PORT_STATE: Final = -2144075730 +ERROR_NDIS_LOW_POWER_STATE: Final = -2144075729 +ERROR_NDIS_REINIT_REQUIRED: Final = -2144075728 +ERROR_NDIS_NO_QUEUES: Final = -2144075727 +ERROR_NDIS_DOT11_AUTO_CONFIG_ENABLED: Final = -2144067584 +ERROR_NDIS_DOT11_MEDIA_IN_USE: Final = -2144067583 +ERROR_NDIS_DOT11_POWER_STATE_INVALID: Final = -2144067582 +ERROR_NDIS_PM_WOL_PATTERN_LIST_FULL: Final = -2144067581 +ERROR_NDIS_PM_PROTOCOL_OFFLOAD_LIST_FULL: Final = -2144067580 +ERROR_NDIS_DOT11_AP_CHANNEL_CURRENTLY_NOT_AVAILABLE: Final = -2144067579 +ERROR_NDIS_DOT11_AP_BAND_CURRENTLY_NOT_AVAILABLE: Final = -2144067578 +ERROR_NDIS_DOT11_AP_CHANNEL_NOT_ALLOWED: Final = -2144067577 +ERROR_NDIS_DOT11_AP_BAND_NOT_ALLOWED: Final = -2144067576 +ERROR_NDIS_INDICATION_REQUIRED: Final = 0x00340001 +ERROR_NDIS_OFFLOAD_POLICY: Final = -1070329841 +ERROR_NDIS_OFFLOAD_CONNECTION_REJECTED: Final = -1070329838 +ERROR_NDIS_OFFLOAD_PATH_REJECTED: Final = -1070329837 +ERROR_HV_INVALID_HYPERCALL_CODE: Final = -1070268414 +ERROR_HV_INVALID_HYPERCALL_INPUT: Final = -1070268413 +ERROR_HV_INVALID_ALIGNMENT: Final = -1070268412 +ERROR_HV_INVALID_PARAMETER: Final = -1070268411 +ERROR_HV_ACCESS_DENIED: Final = -1070268410 +ERROR_HV_INVALID_PARTITION_STATE: Final = -1070268409 +ERROR_HV_OPERATION_DENIED: Final = -1070268408 +ERROR_HV_UNKNOWN_PROPERTY: Final = -1070268407 +ERROR_HV_PROPERTY_VALUE_OUT_OF_RANGE: Final = -1070268406 +ERROR_HV_INSUFFICIENT_MEMORY: Final = -1070268405 +ERROR_HV_PARTITION_TOO_DEEP: Final = -1070268404 +ERROR_HV_INVALID_PARTITION_ID: Final = -1070268403 +ERROR_HV_INVALID_VP_INDEX: Final = -1070268402 +ERROR_HV_INVALID_PORT_ID: Final = -1070268399 +ERROR_HV_INVALID_CONNECTION_ID: Final = -1070268398 +ERROR_HV_INSUFFICIENT_BUFFERS: Final = -1070268397 +ERROR_HV_NOT_ACKNOWLEDGED: Final = -1070268396 +ERROR_HV_INVALID_VP_STATE: Final = -1070268395 +ERROR_HV_ACKNOWLEDGED: Final = -1070268394 +ERROR_HV_INVALID_SAVE_RESTORE_STATE: Final = -1070268393 +ERROR_HV_INVALID_SYNIC_STATE: Final = -1070268392 +ERROR_HV_OBJECT_IN_USE: Final = -1070268391 +ERROR_HV_INVALID_PROXIMITY_DOMAIN_INFO: Final = -1070268390 +ERROR_HV_NO_DATA: Final = -1070268389 +ERROR_HV_INACTIVE: Final = -1070268388 +ERROR_HV_NO_RESOURCES: Final = -1070268387 +ERROR_HV_FEATURE_UNAVAILABLE: Final = -1070268386 +ERROR_HV_INSUFFICIENT_BUFFER: Final = -1070268365 +ERROR_HV_INSUFFICIENT_DEVICE_DOMAINS: Final = -1070268360 +ERROR_HV_CPUID_FEATURE_VALIDATION: Final = -1070268356 +ERROR_HV_CPUID_XSAVE_FEATURE_VALIDATION: Final = -1070268355 +ERROR_HV_PROCESSOR_STARTUP_TIMEOUT: Final = -1070268354 +ERROR_HV_SMX_ENABLED: Final = -1070268353 +ERROR_HV_INVALID_LP_INDEX: Final = -1070268351 +ERROR_HV_INVALID_REGISTER_VALUE: Final = -1070268336 +ERROR_HV_INVALID_VTL_STATE: Final = -1070268335 +ERROR_HV_NX_NOT_DETECTED: Final = -1070268331 +ERROR_HV_INVALID_DEVICE_ID: Final = -1070268329 +ERROR_HV_INVALID_DEVICE_STATE: Final = -1070268328 +ERROR_HV_PENDING_PAGE_REQUESTS: Final = 0x00350059 +ERROR_HV_PAGE_REQUEST_INVALID: Final = -1070268320 +ERROR_HV_INVALID_CPU_GROUP_ID: Final = -1070268305 +ERROR_HV_INVALID_CPU_GROUP_STATE: Final = -1070268304 +ERROR_HV_OPERATION_FAILED: Final = -1070268303 +ERROR_HV_NOT_ALLOWED_WITH_NESTED_VIRT_ACTIVE: Final = -1070268302 +ERROR_HV_INSUFFICIENT_ROOT_MEMORY: Final = -1070268301 +ERROR_HV_EVENT_BUFFER_ALREADY_FREED: Final = -1070268300 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_MEMORY: Final = -1070268299 +ERROR_HV_DEVICE_NOT_IN_DOMAIN: Final = -1070268298 +ERROR_HV_NESTED_VM_EXIT: Final = -1070268297 +ERROR_HV_MSR_ACCESS_FAILED: Final = -1070268288 +ERROR_HV_INSUFFICIENT_MEMORY_MIRRORING: Final = -1070268287 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_MEMORY_MIRRORING: Final = -1070268286 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY: Final = -1070268285 +ERROR_HV_INSUFFICIENT_ROOT_MEMORY_MIRRORING: Final = -1070268284 +ERROR_HV_INSUFFICIENT_CONTIGUOUS_ROOT_MEMORY_MIRRORING: Final = -1070268283 +ERROR_HV_NOT_PRESENT: Final = -1070264320 +ERROR_VID_DUPLICATE_HANDLER: Final = -1070137343 +ERROR_VID_TOO_MANY_HANDLERS: Final = -1070137342 +ERROR_VID_QUEUE_FULL: Final = -1070137341 +ERROR_VID_HANDLER_NOT_PRESENT: Final = -1070137340 +ERROR_VID_INVALID_OBJECT_NAME: Final = -1070137339 +ERROR_VID_PARTITION_NAME_TOO_LONG: Final = -1070137338 +ERROR_VID_MESSAGE_QUEUE_NAME_TOO_LONG: Final = -1070137337 +ERROR_VID_PARTITION_ALREADY_EXISTS: Final = -1070137336 +ERROR_VID_PARTITION_DOES_NOT_EXIST: Final = -1070137335 +ERROR_VID_PARTITION_NAME_NOT_FOUND: Final = -1070137334 +ERROR_VID_MESSAGE_QUEUE_ALREADY_EXISTS: Final = -1070137333 +ERROR_VID_EXCEEDED_MBP_ENTRY_MAP_LIMIT: Final = -1070137332 +ERROR_VID_MB_STILL_REFERENCED: Final = -1070137331 +ERROR_VID_CHILD_GPA_PAGE_SET_CORRUPTED: Final = -1070137330 +ERROR_VID_INVALID_NUMA_SETTINGS: Final = -1070137329 +ERROR_VID_INVALID_NUMA_NODE_INDEX: Final = -1070137328 +ERROR_VID_NOTIFICATION_QUEUE_ALREADY_ASSOCIATED: Final = -1070137327 +ERROR_VID_INVALID_MEMORY_BLOCK_HANDLE: Final = -1070137326 +ERROR_VID_PAGE_RANGE_OVERFLOW: Final = -1070137325 +ERROR_VID_INVALID_MESSAGE_QUEUE_HANDLE: Final = -1070137324 +ERROR_VID_INVALID_GPA_RANGE_HANDLE: Final = -1070137323 +ERROR_VID_NO_MEMORY_BLOCK_NOTIFICATION_QUEUE: Final = -1070137322 +ERROR_VID_MEMORY_BLOCK_LOCK_COUNT_EXCEEDED: Final = -1070137321 +ERROR_VID_INVALID_PPM_HANDLE: Final = -1070137320 +ERROR_VID_MBPS_ARE_LOCKED: Final = -1070137319 +ERROR_VID_MESSAGE_QUEUE_CLOSED: Final = -1070137318 +ERROR_VID_VIRTUAL_PROCESSOR_LIMIT_EXCEEDED: Final = -1070137317 +ERROR_VID_STOP_PENDING: Final = -1070137316 +ERROR_VID_INVALID_PROCESSOR_STATE: Final = -1070137315 +ERROR_VID_EXCEEDED_KM_CONTEXT_COUNT_LIMIT: Final = -1070137314 +ERROR_VID_KM_INTERFACE_ALREADY_INITIALIZED: Final = -1070137313 +ERROR_VID_MB_PROPERTY_ALREADY_SET_RESET: Final = -1070137312 +ERROR_VID_MMIO_RANGE_DESTROYED: Final = -1070137311 +ERROR_VID_INVALID_CHILD_GPA_PAGE_SET: Final = -1070137310 +ERROR_VID_RESERVE_PAGE_SET_IS_BEING_USED: Final = -1070137309 +ERROR_VID_RESERVE_PAGE_SET_TOO_SMALL: Final = -1070137308 +ERROR_VID_MBP_ALREADY_LOCKED_USING_RESERVED_PAGE: Final = -1070137307 +ERROR_VID_MBP_COUNT_EXCEEDED_LIMIT: Final = -1070137306 +ERROR_VID_SAVED_STATE_CORRUPT: Final = -1070137305 +ERROR_VID_SAVED_STATE_UNRECOGNIZED_ITEM: Final = -1070137304 +ERROR_VID_SAVED_STATE_INCOMPATIBLE: Final = -1070137303 +ERROR_VID_VTL_ACCESS_DENIED: Final = -1070137302 +ERROR_VID_INSUFFICIENT_RESOURCES_RESERVE: Final = -1070137301 +ERROR_VID_INSUFFICIENT_RESOURCES_PHYSICAL_BUFFER: Final = -1070137300 +ERROR_VID_INSUFFICIENT_RESOURCES_HV_DEPOSIT: Final = -1070137299 +ERROR_VID_MEMORY_TYPE_NOT_SUPPORTED: Final = -1070137298 +ERROR_VID_INSUFFICIENT_RESOURCES_WITHDRAW: Final = -1070137297 +ERROR_VID_PROCESS_ALREADY_SET: Final = -1070137296 +ERROR_VMCOMPUTE_TERMINATED_DURING_START: Final = -1070137088 +ERROR_VMCOMPUTE_IMAGE_MISMATCH: Final = -1070137087 +ERROR_VMCOMPUTE_HYPERV_NOT_INSTALLED: Final = -1070137086 +ERROR_VMCOMPUTE_OPERATION_PENDING: Final = -1070137085 +ERROR_VMCOMPUTE_TOO_MANY_NOTIFICATIONS: Final = -1070137084 +ERROR_VMCOMPUTE_INVALID_STATE: Final = -1070137083 +ERROR_VMCOMPUTE_UNEXPECTED_EXIT: Final = -1070137082 +ERROR_VMCOMPUTE_TERMINATED: Final = -1070137081 +ERROR_VMCOMPUTE_CONNECT_FAILED: Final = -1070137080 +ERROR_VMCOMPUTE_TIMEOUT: Final = -1070137079 +ERROR_VMCOMPUTE_CONNECTION_CLOSED: Final = -1070137078 +ERROR_VMCOMPUTE_UNKNOWN_MESSAGE: Final = -1070137077 +ERROR_VMCOMPUTE_UNSUPPORTED_PROTOCOL_VERSION: Final = -1070137076 +ERROR_VMCOMPUTE_INVALID_JSON: Final = -1070137075 +ERROR_VMCOMPUTE_SYSTEM_NOT_FOUND: Final = -1070137074 +ERROR_VMCOMPUTE_SYSTEM_ALREADY_EXISTS: Final = -1070137073 +ERROR_VMCOMPUTE_SYSTEM_ALREADY_STOPPED: Final = -1070137072 +ERROR_VMCOMPUTE_PROTOCOL_ERROR: Final = -1070137071 +ERROR_VMCOMPUTE_INVALID_LAYER: Final = -1070137070 +ERROR_VMCOMPUTE_WINDOWS_INSIDER_REQUIRED: Final = -1070137069 +HCS_E_TERMINATED_DURING_START: Final = -2143878912 +HCS_E_IMAGE_MISMATCH: Final = -2143878911 +HCS_E_HYPERV_NOT_INSTALLED: Final = -2143878910 +HCS_E_INVALID_STATE: Final = -2143878907 +HCS_E_UNEXPECTED_EXIT: Final = -2143878906 +HCS_E_TERMINATED: Final = -2143878905 +HCS_E_CONNECT_FAILED: Final = -2143878904 +HCS_E_CONNECTION_TIMEOUT: Final = -2143878903 +HCS_E_CONNECTION_CLOSED: Final = -2143878902 +HCS_E_UNKNOWN_MESSAGE: Final = -2143878901 +HCS_E_UNSUPPORTED_PROTOCOL_VERSION: Final = -2143878900 +HCS_E_INVALID_JSON: Final = -2143878899 +HCS_E_SYSTEM_NOT_FOUND: Final = -2143878898 +HCS_E_SYSTEM_ALREADY_EXISTS: Final = -2143878897 +HCS_E_SYSTEM_ALREADY_STOPPED: Final = -2143878896 +HCS_E_PROTOCOL_ERROR: Final = -2143878895 +HCS_E_INVALID_LAYER: Final = -2143878894 +HCS_E_WINDOWS_INSIDER_REQUIRED: Final = -2143878893 +HCS_E_SERVICE_NOT_AVAILABLE: Final = -2143878892 +HCS_E_OPERATION_NOT_STARTED: Final = -2143878891 +HCS_E_OPERATION_ALREADY_STARTED: Final = -2143878890 +HCS_E_OPERATION_PENDING: Final = -2143878889 +HCS_E_OPERATION_TIMEOUT: Final = -2143878888 +HCS_E_OPERATION_SYSTEM_CALLBACK_ALREADY_SET: Final = -2143878887 +HCS_E_OPERATION_RESULT_ALLOCATION_FAILED: Final = -2143878886 +HCS_E_ACCESS_DENIED: Final = -2143878885 +HCS_E_GUEST_CRITICAL_ERROR: Final = -2143878884 +HCS_E_PROCESS_INFO_NOT_AVAILABLE: Final = -2143878883 +HCS_E_SERVICE_DISCONNECT: Final = -2143878882 +HCS_E_PROCESS_ALREADY_STOPPED: Final = -2143878881 +HCS_E_SYSTEM_NOT_CONFIGURED_FOR_OPERATION: Final = -2143878880 +HCS_E_OPERATION_ALREADY_CANCELLED: Final = -2143878879 +ERROR_VNET_VIRTUAL_SWITCH_NAME_NOT_FOUND: Final = -1070136832 +ERROR_VID_REMOTE_NODE_PARENT_GPA_PAGES_USED: Final = -2143879167 +WHV_E_UNKNOWN_CAPABILITY: Final = -2143878400 +WHV_E_INSUFFICIENT_BUFFER: Final = -2143878399 +WHV_E_UNKNOWN_PROPERTY: Final = -2143878398 +WHV_E_UNSUPPORTED_HYPERVISOR_CONFIG: Final = -2143878397 +WHV_E_INVALID_PARTITION_CONFIG: Final = -2143878396 +WHV_E_GPA_RANGE_NOT_FOUND: Final = -2143878395 +WHV_E_VP_ALREADY_EXISTS: Final = -2143878394 +WHV_E_VP_DOES_NOT_EXIST: Final = -2143878393 +WHV_E_INVALID_VP_STATE: Final = -2143878392 +WHV_E_INVALID_VP_REGISTER_NAME: Final = -2143878391 +WHV_E_UNSUPPORTED_PROCESSOR_CONFIG: Final = -2143878384 +ERROR_VSMB_SAVED_STATE_FILE_NOT_FOUND: Final = -1070136320 +ERROR_VSMB_SAVED_STATE_CORRUPT: Final = -1070136319 +VM_SAVED_STATE_DUMP_E_PARTITION_STATE_NOT_FOUND: Final = -1070136064 +VM_SAVED_STATE_DUMP_E_GUEST_MEMORY_NOT_FOUND: Final = -1070136063 +VM_SAVED_STATE_DUMP_E_NO_VP_FOUND_IN_PARTITION_STATE: Final = -1070136062 +VM_SAVED_STATE_DUMP_E_NESTED_VIRTUALIZATION_NOT_SUPPORTED: Final = -1070136061 +VM_SAVED_STATE_DUMP_E_WINDOWS_KERNEL_IMAGE_NOT_FOUND: Final = -1070136060 +VM_SAVED_STATE_DUMP_E_VA_NOT_MAPPED: Final = -1070136059 +VM_SAVED_STATE_DUMP_E_INVALID_VP_STATE: Final = -1070136058 +VM_SAVED_STATE_DUMP_E_VP_VTL_NOT_ENABLED: Final = -1070136055 +ERROR_DM_OPERATION_LIMIT_EXCEEDED: Final = -1070135808 +ERROR_VOLMGR_INCOMPLETE_REGENERATION: Final = -2143813631 +ERROR_VOLMGR_INCOMPLETE_DISK_MIGRATION: Final = -2143813630 +ERROR_VOLMGR_DATABASE_FULL: Final = -1070071807 +ERROR_VOLMGR_DISK_CONFIGURATION_CORRUPTED: Final = -1070071806 +ERROR_VOLMGR_DISK_CONFIGURATION_NOT_IN_SYNC: Final = -1070071805 +ERROR_VOLMGR_PACK_CONFIG_UPDATE_FAILED: Final = -1070071804 +ERROR_VOLMGR_DISK_CONTAINS_NON_SIMPLE_VOLUME: Final = -1070071803 +ERROR_VOLMGR_DISK_DUPLICATE: Final = -1070071802 +ERROR_VOLMGR_DISK_DYNAMIC: Final = -1070071801 +ERROR_VOLMGR_DISK_ID_INVALID: Final = -1070071800 +ERROR_VOLMGR_DISK_INVALID: Final = -1070071799 +ERROR_VOLMGR_DISK_LAST_VOTER: Final = -1070071798 +ERROR_VOLMGR_DISK_LAYOUT_INVALID: Final = -1070071797 +ERROR_VOLMGR_DISK_LAYOUT_NON_BASIC_BETWEEN_BASIC_PARTITIONS: Final = -1070071796 +ERROR_VOLMGR_DISK_LAYOUT_NOT_CYLINDER_ALIGNED: Final = -1070071795 +ERROR_VOLMGR_DISK_LAYOUT_PARTITIONS_TOO_SMALL: Final = -1070071794 +ERROR_VOLMGR_DISK_LAYOUT_PRIMARY_BETWEEN_LOGICAL_PARTITIONS: Final = -1070071793 +ERROR_VOLMGR_DISK_LAYOUT_TOO_MANY_PARTITIONS: Final = -1070071792 +ERROR_VOLMGR_DISK_MISSING: Final = -1070071791 +ERROR_VOLMGR_DISK_NOT_EMPTY: Final = -1070071790 +ERROR_VOLMGR_DISK_NOT_ENOUGH_SPACE: Final = -1070071789 +ERROR_VOLMGR_DISK_REVECTORING_FAILED: Final = -1070071788 +ERROR_VOLMGR_DISK_SECTOR_SIZE_INVALID: Final = -1070071787 +ERROR_VOLMGR_DISK_SET_NOT_CONTAINED: Final = -1070071786 +ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_MEMBERS: Final = -1070071785 +ERROR_VOLMGR_DISK_USED_BY_MULTIPLE_PLEXES: Final = -1070071784 +ERROR_VOLMGR_DYNAMIC_DISK_NOT_SUPPORTED: Final = -1070071783 +ERROR_VOLMGR_EXTENT_ALREADY_USED: Final = -1070071782 +ERROR_VOLMGR_EXTENT_NOT_CONTIGUOUS: Final = -1070071781 +ERROR_VOLMGR_EXTENT_NOT_IN_PUBLIC_REGION: Final = -1070071780 +ERROR_VOLMGR_EXTENT_NOT_SECTOR_ALIGNED: Final = -1070071779 +ERROR_VOLMGR_EXTENT_OVERLAPS_EBR_PARTITION: Final = -1070071778 +ERROR_VOLMGR_EXTENT_VOLUME_LENGTHS_DO_NOT_MATCH: Final = -1070071777 +ERROR_VOLMGR_FAULT_TOLERANT_NOT_SUPPORTED: Final = -1070071776 +ERROR_VOLMGR_INTERLEAVE_LENGTH_INVALID: Final = -1070071775 +ERROR_VOLMGR_MAXIMUM_REGISTERED_USERS: Final = -1070071774 +ERROR_VOLMGR_MEMBER_IN_SYNC: Final = -1070071773 +ERROR_VOLMGR_MEMBER_INDEX_DUPLICATE: Final = -1070071772 +ERROR_VOLMGR_MEMBER_INDEX_INVALID: Final = -1070071771 +ERROR_VOLMGR_MEMBER_MISSING: Final = -1070071770 +ERROR_VOLMGR_MEMBER_NOT_DETACHED: Final = -1070071769 +ERROR_VOLMGR_MEMBER_REGENERATING: Final = -1070071768 +ERROR_VOLMGR_ALL_DISKS_FAILED: Final = -1070071767 +ERROR_VOLMGR_NO_REGISTERED_USERS: Final = -1070071766 +ERROR_VOLMGR_NO_SUCH_USER: Final = -1070071765 +ERROR_VOLMGR_NOTIFICATION_RESET: Final = -1070071764 +ERROR_VOLMGR_NUMBER_OF_MEMBERS_INVALID: Final = -1070071763 +ERROR_VOLMGR_NUMBER_OF_PLEXES_INVALID: Final = -1070071762 +ERROR_VOLMGR_PACK_DUPLICATE: Final = -1070071761 +ERROR_VOLMGR_PACK_ID_INVALID: Final = -1070071760 +ERROR_VOLMGR_PACK_INVALID: Final = -1070071759 +ERROR_VOLMGR_PACK_NAME_INVALID: Final = -1070071758 +ERROR_VOLMGR_PACK_OFFLINE: Final = -1070071757 +ERROR_VOLMGR_PACK_HAS_QUORUM: Final = -1070071756 +ERROR_VOLMGR_PACK_WITHOUT_QUORUM: Final = -1070071755 +ERROR_VOLMGR_PARTITION_STYLE_INVALID: Final = -1070071754 +ERROR_VOLMGR_PARTITION_UPDATE_FAILED: Final = -1070071753 +ERROR_VOLMGR_PLEX_IN_SYNC: Final = -1070071752 +ERROR_VOLMGR_PLEX_INDEX_DUPLICATE: Final = -1070071751 +ERROR_VOLMGR_PLEX_INDEX_INVALID: Final = -1070071750 +ERROR_VOLMGR_PLEX_LAST_ACTIVE: Final = -1070071749 +ERROR_VOLMGR_PLEX_MISSING: Final = -1070071748 +ERROR_VOLMGR_PLEX_REGENERATING: Final = -1070071747 +ERROR_VOLMGR_PLEX_TYPE_INVALID: Final = -1070071746 +ERROR_VOLMGR_PLEX_NOT_RAID5: Final = -1070071745 +ERROR_VOLMGR_PLEX_NOT_SIMPLE: Final = -1070071744 +ERROR_VOLMGR_STRUCTURE_SIZE_INVALID: Final = -1070071743 +ERROR_VOLMGR_TOO_MANY_NOTIFICATION_REQUESTS: Final = -1070071742 +ERROR_VOLMGR_TRANSACTION_IN_PROGRESS: Final = -1070071741 +ERROR_VOLMGR_UNEXPECTED_DISK_LAYOUT_CHANGE: Final = -1070071740 +ERROR_VOLMGR_VOLUME_CONTAINS_MISSING_DISK: Final = -1070071739 +ERROR_VOLMGR_VOLUME_ID_INVALID: Final = -1070071738 +ERROR_VOLMGR_VOLUME_LENGTH_INVALID: Final = -1070071737 +ERROR_VOLMGR_VOLUME_LENGTH_NOT_SECTOR_SIZE_MULTIPLE: Final = -1070071736 +ERROR_VOLMGR_VOLUME_NOT_MIRRORED: Final = -1070071735 +ERROR_VOLMGR_VOLUME_NOT_RETAINED: Final = -1070071734 +ERROR_VOLMGR_VOLUME_OFFLINE: Final = -1070071733 +ERROR_VOLMGR_VOLUME_RETAINED: Final = -1070071732 +ERROR_VOLMGR_NUMBER_OF_EXTENTS_INVALID: Final = -1070071731 +ERROR_VOLMGR_DIFFERENT_SECTOR_SIZE: Final = -1070071730 +ERROR_VOLMGR_BAD_BOOT_DISK: Final = -1070071729 +ERROR_VOLMGR_PACK_CONFIG_OFFLINE: Final = -1070071728 +ERROR_VOLMGR_PACK_CONFIG_ONLINE: Final = -1070071727 +ERROR_VOLMGR_NOT_PRIMARY_PACK: Final = -1070071726 +ERROR_VOLMGR_PACK_LOG_UPDATE_FAILED: Final = -1070071725 +ERROR_VOLMGR_NUMBER_OF_DISKS_IN_PLEX_INVALID: Final = -1070071724 +ERROR_VOLMGR_NUMBER_OF_DISKS_IN_MEMBER_INVALID: Final = -1070071723 +ERROR_VOLMGR_VOLUME_MIRRORED: Final = -1070071722 +ERROR_VOLMGR_PLEX_NOT_SIMPLE_SPANNED: Final = -1070071721 +ERROR_VOLMGR_NO_VALID_LOG_COPIES: Final = -1070071720 +ERROR_VOLMGR_PRIMARY_PACK_PRESENT: Final = -1070071719 +ERROR_VOLMGR_NUMBER_OF_DISKS_INVALID: Final = -1070071718 +ERROR_VOLMGR_MIRROR_NOT_SUPPORTED: Final = -1070071717 +ERROR_VOLMGR_RAID5_NOT_SUPPORTED: Final = -1070071716 +ERROR_BCD_NOT_ALL_ENTRIES_IMPORTED: Final = -2143748095 +ERROR_BCD_TOO_MANY_ELEMENTS: Final = -1070006270 +ERROR_BCD_NOT_ALL_ENTRIES_SYNCHRONIZED: Final = -2143748093 +ERROR_VHD_DRIVE_FOOTER_MISSING: Final = -1069940735 +ERROR_VHD_DRIVE_FOOTER_CHECKSUM_MISMATCH: Final = -1069940734 +ERROR_VHD_DRIVE_FOOTER_CORRUPT: Final = -1069940733 +ERROR_VHD_FORMAT_UNKNOWN: Final = -1069940732 +ERROR_VHD_FORMAT_UNSUPPORTED_VERSION: Final = -1069940731 +ERROR_VHD_SPARSE_HEADER_CHECKSUM_MISMATCH: Final = -1069940730 +ERROR_VHD_SPARSE_HEADER_UNSUPPORTED_VERSION: Final = -1069940729 +ERROR_VHD_SPARSE_HEADER_CORRUPT: Final = -1069940728 +ERROR_VHD_BLOCK_ALLOCATION_FAILURE: Final = -1069940727 +ERROR_VHD_BLOCK_ALLOCATION_TABLE_CORRUPT: Final = -1069940726 +ERROR_VHD_INVALID_BLOCK_SIZE: Final = -1069940725 +ERROR_VHD_BITMAP_MISMATCH: Final = -1069940724 +ERROR_VHD_PARENT_VHD_NOT_FOUND: Final = -1069940723 +ERROR_VHD_CHILD_PARENT_ID_MISMATCH: Final = -1069940722 +ERROR_VHD_CHILD_PARENT_TIMESTAMP_MISMATCH: Final = -1069940721 +ERROR_VHD_METADATA_READ_FAILURE: Final = -1069940720 +ERROR_VHD_METADATA_WRITE_FAILURE: Final = -1069940719 +ERROR_VHD_INVALID_SIZE: Final = -1069940718 +ERROR_VHD_INVALID_FILE_SIZE: Final = -1069940717 +ERROR_VIRTDISK_PROVIDER_NOT_FOUND: Final = -1069940716 +ERROR_VIRTDISK_NOT_VIRTUAL_DISK: Final = -1069940715 +ERROR_VHD_PARENT_VHD_ACCESS_DENIED: Final = -1069940714 +ERROR_VHD_CHILD_PARENT_SIZE_MISMATCH: Final = -1069940713 +ERROR_VHD_DIFFERENCING_CHAIN_CYCLE_DETECTED: Final = -1069940712 +ERROR_VHD_DIFFERENCING_CHAIN_ERROR_IN_PARENT: Final = -1069940711 +ERROR_VIRTUAL_DISK_LIMITATION: Final = -1069940710 +ERROR_VHD_INVALID_TYPE: Final = -1069940709 +ERROR_VHD_INVALID_STATE: Final = -1069940708 +ERROR_VIRTDISK_UNSUPPORTED_DISK_SECTOR_SIZE: Final = -1069940707 +ERROR_VIRTDISK_DISK_ALREADY_OWNED: Final = -1069940706 +ERROR_VIRTDISK_DISK_ONLINE_AND_WRITABLE: Final = -1069940705 +ERROR_CTLOG_TRACKING_NOT_INITIALIZED: Final = -1069940704 +ERROR_CTLOG_LOGFILE_SIZE_EXCEEDED_MAXSIZE: Final = -1069940703 +ERROR_CTLOG_VHD_CHANGED_OFFLINE: Final = -1069940702 +ERROR_CTLOG_INVALID_TRACKING_STATE: Final = -1069940701 +ERROR_CTLOG_INCONSISTENT_TRACKING_FILE: Final = -1069940700 +ERROR_VHD_RESIZE_WOULD_TRUNCATE_DATA: Final = -1069940699 +ERROR_VHD_COULD_NOT_COMPUTE_MINIMUM_VIRTUAL_SIZE: Final = -1069940698 +ERROR_VHD_ALREADY_AT_OR_BELOW_MINIMUM_VIRTUAL_SIZE: Final = -1069940697 +ERROR_VHD_METADATA_FULL: Final = -1069940696 +ERROR_VHD_INVALID_CHANGE_TRACKING_ID: Final = -1069940695 +ERROR_VHD_CHANGE_TRACKING_DISABLED: Final = -1069940694 +ERROR_VHD_MISSING_CHANGE_TRACKING_INFORMATION: Final = -1069940688 +ERROR_VHD_UNEXPECTED_ID: Final = -1069940684 +ERROR_QUERY_STORAGE_ERROR: Final = -2143682559 +HCN_E_NETWORK_NOT_FOUND: Final = -2143617023 +HCN_E_ENDPOINT_NOT_FOUND: Final = -2143617022 +HCN_E_LAYER_NOT_FOUND: Final = -2143617021 +HCN_E_SWITCH_NOT_FOUND: Final = -2143617020 +HCN_E_SUBNET_NOT_FOUND: Final = -2143617019 +HCN_E_ADAPTER_NOT_FOUND: Final = -2143617018 +HCN_E_PORT_NOT_FOUND: Final = -2143617017 +HCN_E_POLICY_NOT_FOUND: Final = -2143617016 +HCN_E_VFP_PORTSETTING_NOT_FOUND: Final = -2143617015 +HCN_E_INVALID_NETWORK: Final = -2143617014 +HCN_E_INVALID_NETWORK_TYPE: Final = -2143617013 +HCN_E_INVALID_ENDPOINT: Final = -2143617012 +HCN_E_INVALID_POLICY: Final = -2143617011 +HCN_E_INVALID_POLICY_TYPE: Final = -2143617010 +HCN_E_INVALID_REMOTE_ENDPOINT_OPERATION: Final = -2143617009 +HCN_E_NETWORK_ALREADY_EXISTS: Final = -2143617008 +HCN_E_LAYER_ALREADY_EXISTS: Final = -2143617007 +HCN_E_POLICY_ALREADY_EXISTS: Final = -2143617006 +HCN_E_PORT_ALREADY_EXISTS: Final = -2143617005 +HCN_E_ENDPOINT_ALREADY_ATTACHED: Final = -2143617004 +HCN_E_REQUEST_UNSUPPORTED: Final = -2143617003 +HCN_E_MAPPING_NOT_SUPPORTED: Final = -2143617002 +HCN_E_DEGRADED_OPERATION: Final = -2143617001 +HCN_E_SHARED_SWITCH_MODIFICATION: Final = -2143617000 +HCN_E_GUID_CONVERSION_FAILURE: Final = -2143616999 +HCN_E_REGKEY_FAILURE: Final = -2143616998 +HCN_E_INVALID_JSON: Final = -2143616997 +HCN_E_INVALID_JSON_REFERENCE: Final = -2143616996 +HCN_E_ENDPOINT_SHARING_DISABLED: Final = -2143616995 +HCN_E_INVALID_IP: Final = -2143616994 +HCN_E_SWITCH_EXTENSION_NOT_FOUND: Final = -2143616993 +HCN_E_MANAGER_STOPPED: Final = -2143616992 +GCN_E_MODULE_NOT_FOUND: Final = -2143616991 +GCN_E_NO_REQUEST_HANDLERS: Final = -2143616990 +GCN_E_REQUEST_UNSUPPORTED: Final = -2143616989 +GCN_E_RUNTIMEKEYS_FAILED: Final = -2143616988 +GCN_E_NETADAPTER_TIMEOUT: Final = -2143616987 +GCN_E_NETADAPTER_NOT_FOUND: Final = -2143616986 +GCN_E_NETCOMPARTMENT_NOT_FOUND: Final = -2143616985 +GCN_E_NETINTERFACE_NOT_FOUND: Final = -2143616984 +GCN_E_DEFAULTNAMESPACE_EXISTS: Final = -2143616983 +HCN_E_ICS_DISABLED: Final = -2143616982 +HCN_E_ENDPOINT_NAMESPACE_ALREADY_EXISTS: Final = -2143616981 +HCN_E_ENTITY_HAS_REFERENCES: Final = -2143616980 +HCN_E_INVALID_INTERNAL_PORT: Final = -2143616979 +HCN_E_NAMESPACE_ATTACH_FAILED: Final = -2143616978 +HCN_E_ADDR_INVALID_OR_RESERVED: Final = -2143616977 +HCN_E_INVALID_PREFIX: Final = -2143616976 +HCN_E_OBJECT_USED_AFTER_UNLOAD: Final = -2143616975 +HCN_E_INVALID_SUBNET: Final = -2143616974 +HCN_E_INVALID_IP_SUBNET: Final = -2143616973 +HCN_E_ENDPOINT_NOT_ATTACHED: Final = -2143616972 +HCN_E_ENDPOINT_NOT_LOCAL: Final = -2143616971 +HCN_INTERFACEPARAMETERS_ALREADY_APPLIED: Final = -2143616970 +HCN_E_VFP_NOT_ALLOWED: Final = -2143616969 +SDIAG_E_CANCELLED: Final = -2143551232 +SDIAG_E_SCRIPT: Final = -2143551231 +SDIAG_E_POWERSHELL: Final = -2143551230 +SDIAG_E_MANAGEDHOST: Final = -2143551229 +SDIAG_E_NOVERIFIER: Final = -2143551228 +SDIAG_S_CANNOTRUN: Final = 0x003C0105 +SDIAG_E_DISABLED: Final = -2143551226 +SDIAG_E_TRUST: Final = -2143551225 +SDIAG_E_CANNOTRUN: Final = -2143551224 +SDIAG_E_VERSION: Final = -2143551223 +SDIAG_E_RESOURCE: Final = -2143551222 +SDIAG_E_ROOTCAUSE: Final = -2143551221 +WPN_E_CHANNEL_CLOSED: Final = -2143420160 +WPN_E_CHANNEL_REQUEST_NOT_COMPLETE: Final = -2143420159 +WPN_E_INVALID_APP: Final = -2143420158 +WPN_E_OUTSTANDING_CHANNEL_REQUEST: Final = -2143420157 +WPN_E_DUPLICATE_CHANNEL: Final = -2143420156 +WPN_E_PLATFORM_UNAVAILABLE: Final = -2143420155 +WPN_E_NOTIFICATION_POSTED: Final = -2143420154 +WPN_E_NOTIFICATION_HIDDEN: Final = -2143420153 +WPN_E_NOTIFICATION_NOT_POSTED: Final = -2143420152 +WPN_E_CLOUD_DISABLED: Final = -2143420151 +WPN_E_CLOUD_INCAPABLE: Final = -2143420144 +WPN_E_CLOUD_AUTH_UNAVAILABLE: Final = -2143420134 +WPN_E_CLOUD_SERVICE_UNAVAILABLE: Final = -2143420133 +WPN_E_FAILED_LOCK_SCREEN_UPDATE_INTIALIZATION: Final = -2143420132 +WPN_E_NOTIFICATION_DISABLED: Final = -2143420143 +WPN_E_NOTIFICATION_INCAPABLE: Final = -2143420142 +WPN_E_INTERNET_INCAPABLE: Final = -2143420141 +WPN_E_NOTIFICATION_TYPE_DISABLED: Final = -2143420140 +WPN_E_NOTIFICATION_SIZE: Final = -2143420139 +WPN_E_TAG_SIZE: Final = -2143420138 +WPN_E_ACCESS_DENIED: Final = -2143420137 +WPN_E_DUPLICATE_REGISTRATION: Final = -2143420136 +WPN_E_PUSH_NOTIFICATION_INCAPABLE: Final = -2143420135 +WPN_E_DEV_ID_SIZE: Final = -2143420128 +WPN_E_TAG_ALPHANUMERIC: Final = -2143420118 +WPN_E_INVALID_HTTP_STATUS_CODE: Final = -2143420117 +WPN_E_OUT_OF_SESSION: Final = -2143419904 +WPN_E_POWER_SAVE: Final = -2143419903 +WPN_E_IMAGE_NOT_FOUND_IN_CACHE: Final = -2143419902 +WPN_E_ALL_URL_NOT_COMPLETED: Final = -2143419901 +WPN_E_INVALID_CLOUD_IMAGE: Final = -2143419900 +WPN_E_NOTIFICATION_ID_MATCHED: Final = -2143419899 +WPN_E_CALLBACK_ALREADY_REGISTERED: Final = -2143419898 +WPN_E_TOAST_NOTIFICATION_DROPPED: Final = -2143419897 +WPN_E_STORAGE_LOCKED: Final = -2143419896 +WPN_E_GROUP_SIZE: Final = -2143419895 +WPN_E_GROUP_ALPHANUMERIC: Final = -2143419894 +WPN_E_CLOUD_DISABLED_FOR_APP: Final = -2143419893 +E_MBN_CONTEXT_NOT_ACTIVATED: Final = -2141945343 +E_MBN_BAD_SIM: Final = -2141945342 +E_MBN_DATA_CLASS_NOT_AVAILABLE: Final = -2141945341 +E_MBN_INVALID_ACCESS_STRING: Final = -2141945340 +E_MBN_MAX_ACTIVATED_CONTEXTS: Final = -2141945339 +E_MBN_PACKET_SVC_DETACHED: Final = -2141945338 +E_MBN_PROVIDER_NOT_VISIBLE: Final = -2141945337 +E_MBN_RADIO_POWER_OFF: Final = -2141945336 +E_MBN_SERVICE_NOT_ACTIVATED: Final = -2141945335 +E_MBN_SIM_NOT_INSERTED: Final = -2141945334 +E_MBN_VOICE_CALL_IN_PROGRESS: Final = -2141945333 +E_MBN_INVALID_CACHE: Final = -2141945332 +E_MBN_NOT_REGISTERED: Final = -2141945331 +E_MBN_PROVIDERS_NOT_FOUND: Final = -2141945330 +E_MBN_PIN_NOT_SUPPORTED: Final = -2141945329 +E_MBN_PIN_REQUIRED: Final = -2141945328 +E_MBN_PIN_DISABLED: Final = -2141945327 +E_MBN_FAILURE: Final = -2141945326 +E_MBN_INVALID_PROFILE: Final = -2141945320 +E_MBN_DEFAULT_PROFILE_EXIST: Final = -2141945319 +E_MBN_SMS_ENCODING_NOT_SUPPORTED: Final = -2141945312 +E_MBN_SMS_FILTER_NOT_SUPPORTED: Final = -2141945311 +E_MBN_SMS_INVALID_MEMORY_INDEX: Final = -2141945310 +E_MBN_SMS_LANG_NOT_SUPPORTED: Final = -2141945309 +E_MBN_SMS_MEMORY_FAILURE: Final = -2141945308 +E_MBN_SMS_NETWORK_TIMEOUT: Final = -2141945307 +E_MBN_SMS_UNKNOWN_SMSC_ADDRESS: Final = -2141945306 +E_MBN_SMS_FORMAT_NOT_SUPPORTED: Final = -2141945305 +E_MBN_SMS_OPERATION_NOT_ALLOWED: Final = -2141945304 +E_MBN_SMS_MEMORY_FULL: Final = -2141945303 +PEER_E_IPV6_NOT_INSTALLED: Final = -2140995583 +PEER_E_NOT_INITIALIZED: Final = -2140995582 +PEER_E_CANNOT_START_SERVICE: Final = -2140995581 +PEER_E_NOT_LICENSED: Final = -2140995580 +PEER_E_INVALID_GRAPH: Final = -2140995568 +PEER_E_DBNAME_CHANGED: Final = -2140995567 +PEER_E_DUPLICATE_GRAPH: Final = -2140995566 +PEER_E_GRAPH_NOT_READY: Final = -2140995565 +PEER_E_GRAPH_SHUTTING_DOWN: Final = -2140995564 +PEER_E_GRAPH_IN_USE: Final = -2140995563 +PEER_E_INVALID_DATABASE: Final = -2140995562 +PEER_E_TOO_MANY_ATTRIBUTES: Final = -2140995561 +PEER_E_CONNECTION_NOT_FOUND: Final = -2140995325 +PEER_E_CONNECT_SELF: Final = -2140995322 +PEER_E_ALREADY_LISTENING: Final = -2140995321 +PEER_E_NODE_NOT_FOUND: Final = -2140995320 +PEER_E_CONNECTION_FAILED: Final = -2140995319 +PEER_E_CONNECTION_NOT_AUTHENTICATED: Final = -2140995318 +PEER_E_CONNECTION_REFUSED: Final = -2140995317 +PEER_E_CLASSIFIER_TOO_LONG: Final = -2140995071 +PEER_E_TOO_MANY_IDENTITIES: Final = -2140995070 +PEER_E_NO_KEY_ACCESS: Final = -2140995069 +PEER_E_GROUPS_EXIST: Final = -2140995068 +PEER_E_RECORD_NOT_FOUND: Final = -2140994815 +PEER_E_DATABASE_ACCESSDENIED: Final = -2140994814 +PEER_E_DBINITIALIZATION_FAILED: Final = -2140994813 +PEER_E_MAX_RECORD_SIZE_EXCEEDED: Final = -2140994812 +PEER_E_DATABASE_ALREADY_PRESENT: Final = -2140994811 +PEER_E_DATABASE_NOT_PRESENT: Final = -2140994810 +PEER_E_IDENTITY_NOT_FOUND: Final = -2140994559 +PEER_E_EVENT_HANDLE_NOT_FOUND: Final = -2140994303 +PEER_E_INVALID_SEARCH: Final = -2140994047 +PEER_E_INVALID_ATTRIBUTES: Final = -2140994046 +PEER_E_INVITATION_NOT_TRUSTED: Final = -2140993791 +PEER_E_CHAIN_TOO_LONG: Final = -2140993789 +PEER_E_INVALID_TIME_PERIOD: Final = -2140993787 +PEER_E_CIRCULAR_CHAIN_DETECTED: Final = -2140993786 +PEER_E_CERT_STORE_CORRUPTED: Final = -2140993535 +PEER_E_NO_CLOUD: Final = -2140991487 +PEER_E_CLOUD_NAME_AMBIGUOUS: Final = -2140991483 +PEER_E_INVALID_RECORD: Final = -2140987376 +PEER_E_NOT_AUTHORIZED: Final = -2140987360 +PEER_E_PASSWORD_DOES_NOT_MEET_POLICY: Final = -2140987359 +PEER_E_DEFERRED_VALIDATION: Final = -2140987344 +PEER_E_INVALID_GROUP_PROPERTIES: Final = -2140987328 +PEER_E_INVALID_PEER_NAME: Final = -2140987312 +PEER_E_INVALID_CLASSIFIER: Final = -2140987296 +PEER_E_INVALID_FRIENDLY_NAME: Final = -2140987280 +PEER_E_INVALID_ROLE_PROPERTY: Final = -2140987279 +PEER_E_INVALID_CLASSIFIER_PROPERTY: Final = -2140987278 +PEER_E_INVALID_RECORD_EXPIRATION: Final = -2140987264 +PEER_E_INVALID_CREDENTIAL_INFO: Final = -2140987263 +PEER_E_INVALID_CREDENTIAL: Final = -2140987262 +PEER_E_INVALID_RECORD_SIZE: Final = -2140987261 +PEER_E_UNSUPPORTED_VERSION: Final = -2140987248 +PEER_E_GROUP_NOT_READY: Final = -2140987247 +PEER_E_GROUP_IN_USE: Final = -2140987246 +PEER_E_INVALID_GROUP: Final = -2140987245 +PEER_E_NO_MEMBERS_FOUND: Final = -2140987244 +PEER_E_NO_MEMBER_CONNECTIONS: Final = -2140987243 +PEER_E_UNABLE_TO_LISTEN: Final = -2140987242 +PEER_E_IDENTITY_DELETED: Final = -2140987232 +PEER_E_SERVICE_NOT_AVAILABLE: Final = -2140987231 +PEER_E_CONTACT_NOT_FOUND: Final = -2140971007 +PEER_S_GRAPH_DATA_CREATED: Final = 0x00630001 +PEER_S_NO_EVENT_DATA: Final = 0x00630002 +PEER_S_ALREADY_CONNECTED: Final = 0x00632000 +PEER_S_SUBSCRIPTION_EXISTS: Final = 0x00636000 +PEER_S_NO_CONNECTIVITY: Final = 0x00630005 +PEER_S_ALREADY_A_MEMBER: Final = 0x00630006 +PEER_E_CANNOT_CONVERT_PEER_NAME: Final = -2140979199 +PEER_E_INVALID_PEER_HOST_NAME: Final = -2140979198 +PEER_E_NO_MORE: Final = -2140979197 +PEER_E_PNRP_DUPLICATE_PEER_NAME: Final = -2140979195 +PEER_E_INVITE_CANCELLED: Final = -2140966912 +PEER_E_INVITE_RESPONSE_NOT_AVAILABLE: Final = -2140966911 +PEER_E_NOT_SIGNED_IN: Final = -2140966909 +PEER_E_PRIVACY_DECLINED: Final = -2140966908 +PEER_E_TIMEOUT: Final = -2140966907 +PEER_E_INVALID_ADDRESS: Final = -2140966905 +PEER_E_FW_EXCEPTION_DISABLED: Final = -2140966904 +PEER_E_FW_BLOCKED_BY_POLICY: Final = -2140966903 +PEER_E_FW_BLOCKED_BY_SHIELDS_UP: Final = -2140966902 +PEER_E_FW_DECLINED: Final = -2140966901 +UI_E_CREATE_FAILED: Final = -2144731135 +UI_E_SHUTDOWN_CALLED: Final = -2144731134 +UI_E_ILLEGAL_REENTRANCY: Final = -2144731133 +UI_E_OBJECT_SEALED: Final = -2144731132 +UI_E_VALUE_NOT_SET: Final = -2144731131 +UI_E_VALUE_NOT_DETERMINED: Final = -2144731130 +UI_E_INVALID_OUTPUT: Final = -2144731129 +UI_E_BOOLEAN_EXPECTED: Final = -2144731128 +UI_E_DIFFERENT_OWNER: Final = -2144731127 +UI_E_AMBIGUOUS_MATCH: Final = -2144731126 +UI_E_FP_OVERFLOW: Final = -2144731125 +UI_E_WRONG_THREAD: Final = -2144731124 +UI_E_STORYBOARD_ACTIVE: Final = -2144730879 +UI_E_STORYBOARD_NOT_PLAYING: Final = -2144730878 +UI_E_START_KEYFRAME_AFTER_END: Final = -2144730877 +UI_E_END_KEYFRAME_NOT_DETERMINED: Final = -2144730876 +UI_E_LOOPS_OVERLAP: Final = -2144730875 +UI_E_TRANSITION_ALREADY_USED: Final = -2144730874 +UI_E_TRANSITION_NOT_IN_STORYBOARD: Final = -2144730873 +UI_E_TRANSITION_ECLIPSED: Final = -2144730872 +UI_E_TIME_BEFORE_LAST_UPDATE: Final = -2144730871 +UI_E_TIMER_CLIENT_ALREADY_CONNECTED: Final = -2144730870 +UI_E_INVALID_DIMENSION: Final = -2144730869 +UI_E_PRIMITIVE_OUT_OF_BOUNDS: Final = -2144730868 +UI_E_WINDOW_CLOSED: Final = -2144730623 +E_BLUETOOTH_ATT_INVALID_HANDLE: Final = -2140864511 +E_BLUETOOTH_ATT_READ_NOT_PERMITTED: Final = -2140864510 +E_BLUETOOTH_ATT_WRITE_NOT_PERMITTED: Final = -2140864509 +E_BLUETOOTH_ATT_INVALID_PDU: Final = -2140864508 +E_BLUETOOTH_ATT_INSUFFICIENT_AUTHENTICATION: Final = -2140864507 +E_BLUETOOTH_ATT_REQUEST_NOT_SUPPORTED: Final = -2140864506 +E_BLUETOOTH_ATT_INVALID_OFFSET: Final = -2140864505 +E_BLUETOOTH_ATT_INSUFFICIENT_AUTHORIZATION: Final = -2140864504 +E_BLUETOOTH_ATT_PREPARE_QUEUE_FULL: Final = -2140864503 +E_BLUETOOTH_ATT_ATTRIBUTE_NOT_FOUND: Final = -2140864502 +E_BLUETOOTH_ATT_ATTRIBUTE_NOT_LONG: Final = -2140864501 +E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION_KEY_SIZE: Final = -2140864500 +E_BLUETOOTH_ATT_INVALID_ATTRIBUTE_VALUE_LENGTH: Final = -2140864499 +E_BLUETOOTH_ATT_UNLIKELY: Final = -2140864498 +E_BLUETOOTH_ATT_INSUFFICIENT_ENCRYPTION: Final = -2140864497 +E_BLUETOOTH_ATT_UNSUPPORTED_GROUP_TYPE: Final = -2140864496 +E_BLUETOOTH_ATT_INSUFFICIENT_RESOURCES: Final = -2140864495 +E_BLUETOOTH_ATT_UNKNOWN_ERROR: Final = -2140860416 +E_AUDIO_ENGINE_NODE_NOT_FOUND: Final = -2140798975 +E_HDAUDIO_EMPTY_CONNECTION_LIST: Final = -2140798974 +E_HDAUDIO_CONNECTION_LIST_NOT_SUPPORTED: Final = -2140798973 +E_HDAUDIO_NO_LOGICAL_DEVICES_CREATED: Final = -2140798972 +E_HDAUDIO_NULL_LINKED_LIST_ENTRY: Final = -2140798971 +STATEREPOSITORY_E_CONCURRENCY_LOCKING_FAILURE: Final = -2140733439 +STATEREPOSITORY_E_STATEMENT_INPROGRESS: Final = -2140733438 +STATEREPOSITORY_E_CONFIGURATION_INVALID: Final = -2140733437 +STATEREPOSITORY_E_UNKNOWN_SCHEMA_VERSION: Final = -2140733436 +STATEREPOSITORY_ERROR_DICTIONARY_CORRUPTED: Final = -2140733435 +STATEREPOSITORY_E_BLOCKED: Final = -2140733434 +STATEREPOSITORY_E_BUSY_RETRY: Final = -2140733433 +STATEREPOSITORY_E_BUSY_RECOVERY_RETRY: Final = -2140733432 +STATEREPOSITORY_E_LOCKED_RETRY: Final = -2140733431 +STATEREPOSITORY_E_LOCKED_SHAREDCACHE_RETRY: Final = -2140733430 +STATEREPOSITORY_E_TRANSACTION_REQUIRED: Final = -2140733429 +STATEREPOSITORY_E_BUSY_TIMEOUT_EXCEEDED: Final = -2140733428 +STATEREPOSITORY_E_BUSY_RECOVERY_TIMEOUT_EXCEEDED: Final = -2140733427 +STATEREPOSITORY_E_LOCKED_TIMEOUT_EXCEEDED: Final = -2140733426 +STATEREPOSITORY_E_LOCKED_SHAREDCACHE_TIMEOUT_EXCEEDED: Final = -2140733425 +STATEREPOSITORY_E_SERVICE_STOP_IN_PROGRESS: Final = -2140733424 +STATEREPOSTORY_E_NESTED_TRANSACTION_NOT_SUPPORTED: Final = -2140733423 +STATEREPOSITORY_ERROR_CACHE_CORRUPTED: Final = -2140733422 +STATEREPOSITORY_TRANSACTION_CALLER_ID_CHANGED: Final = 0x00670013 +STATEREPOSITORY_TRANSACTION_IN_PROGRESS: Final = -2140733420 +STATEREPOSITORY_E_CACHE_NOT_INIITALIZED: Final = -2140733419 +STATEREPOSITORY_E_DEPENDENCY_NOT_RESOLVED: Final = -2140733418 +ERROR_SPACES_POOL_WAS_DELETED: Final = 0x00E70001 +ERROR_SPACES_FAULT_DOMAIN_TYPE_INVALID: Final = -2132344831 +ERROR_SPACES_INTERNAL_ERROR: Final = -2132344830 +ERROR_SPACES_RESILIENCY_TYPE_INVALID: Final = -2132344829 +ERROR_SPACES_DRIVE_SECTOR_SIZE_INVALID: Final = -2132344828 +ERROR_SPACES_DRIVE_REDUNDANCY_INVALID: Final = -2132344826 +ERROR_SPACES_NUMBER_OF_DATA_COPIES_INVALID: Final = -2132344825 +ERROR_SPACES_PARITY_LAYOUT_INVALID: Final = -2132344824 +ERROR_SPACES_INTERLEAVE_LENGTH_INVALID: Final = -2132344823 +ERROR_SPACES_NUMBER_OF_COLUMNS_INVALID: Final = -2132344822 +ERROR_SPACES_NOT_ENOUGH_DRIVES: Final = -2132344821 +ERROR_SPACES_EXTENDED_ERROR: Final = -2132344820 +ERROR_SPACES_PROVISIONING_TYPE_INVALID: Final = -2132344819 +ERROR_SPACES_ALLOCATION_SIZE_INVALID: Final = -2132344818 +ERROR_SPACES_ENCLOSURE_AWARE_INVALID: Final = -2132344817 +ERROR_SPACES_WRITE_CACHE_SIZE_INVALID: Final = -2132344816 +ERROR_SPACES_NUMBER_OF_GROUPS_INVALID: Final = -2132344815 +ERROR_SPACES_DRIVE_OPERATIONAL_STATE_INVALID: Final = -2132344814 +ERROR_SPACES_ENTRY_INCOMPLETE: Final = -2132344813 +ERROR_SPACES_ENTRY_INVALID: Final = -2132344812 +ERROR_SPACES_UPDATE_COLUMN_STATE: Final = -2132344811 +ERROR_SPACES_MAP_REQUIRED: Final = -2132344810 +ERROR_SPACES_UNSUPPORTED_VERSION: Final = -2132344809 +ERROR_SPACES_CORRUPT_METADATA: Final = -2132344808 +ERROR_SPACES_DRT_FULL: Final = -2132344807 +ERROR_SPACES_INCONSISTENCY: Final = -2132344806 +ERROR_SPACES_LOG_NOT_READY: Final = -2132344805 +ERROR_SPACES_NO_REDUNDANCY: Final = -2132344804 +ERROR_SPACES_DRIVE_NOT_READY: Final = -2132344803 +ERROR_SPACES_DRIVE_SPLIT: Final = -2132344802 +ERROR_SPACES_DRIVE_LOST_DATA: Final = -2132344801 +ERROR_SPACES_MARK_DIRTY: Final = -2132344800 +ERROR_SPACES_FLUSH_METADATA: Final = -2132344795 +ERROR_SPACES_CACHE_FULL: Final = -2132344794 +ERROR_SPACES_REPAIR_IN_PROGRESS: Final = -2132344793 +ERROR_VOLSNAP_BOOTFILE_NOT_VALID: Final = -2138963967 +ERROR_VOLSNAP_ACTIVATION_TIMEOUT: Final = -2138963966 +ERROR_VOLSNAP_NO_BYPASSIO_WITH_SNAPSHOT: Final = -2138963965 +ERROR_TIERING_NOT_SUPPORTED_ON_VOLUME: Final = -2138898431 +ERROR_TIERING_VOLUME_DISMOUNT_IN_PROGRESS: Final = -2138898430 +ERROR_TIERING_STORAGE_TIER_NOT_FOUND: Final = -2138898429 +ERROR_TIERING_INVALID_FILE_ID: Final = -2138898428 +ERROR_TIERING_WRONG_CLUSTER_NODE: Final = -2138898427 +ERROR_TIERING_ALREADY_PROCESSING: Final = -2138898426 +ERROR_TIERING_CANNOT_PIN_OBJECT: Final = -2138898425 +ERROR_TIERING_FILE_IS_NOT_PINNED: Final = -2138898424 +ERROR_NOT_A_TIERED_VOLUME: Final = -2138898423 +ERROR_ATTRIBUTE_NOT_PRESENT: Final = -2138898422 +ERROR_SECCORE_INVALID_COMMAND: Final = -1058537472 +ERROR_NO_APPLICABLE_APP_LICENSES_FOUND: Final = -1058406399 +ERROR_CLIP_LICENSE_NOT_FOUND: Final = -1058406398 +ERROR_CLIP_DEVICE_LICENSE_MISSING: Final = -1058406397 +ERROR_CLIP_LICENSE_INVALID_SIGNATURE: Final = -1058406396 +ERROR_CLIP_KEYHOLDER_LICENSE_MISSING_OR_INVALID: Final = -1058406395 +ERROR_CLIP_LICENSE_EXPIRED: Final = -1058406394 +ERROR_CLIP_LICENSE_SIGNED_BY_UNKNOWN_SOURCE: Final = -1058406393 +ERROR_CLIP_LICENSE_NOT_SIGNED: Final = -1058406392 +ERROR_CLIP_LICENSE_HARDWARE_ID_OUT_OF_TOLERANCE: Final = -1058406391 +ERROR_CLIP_LICENSE_DEVICE_ID_MISMATCH: Final = -1058406390 +DXGI_STATUS_OCCLUDED: Final = 0x087A0001 +DXGI_STATUS_CLIPPED: Final = 0x087A0002 +DXGI_STATUS_NO_REDIRECTION: Final = 0x087A0004 +DXGI_STATUS_NO_DESKTOP_ACCESS: Final = 0x087A0005 +DXGI_STATUS_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = 0x087A0006 +DXGI_STATUS_MODE_CHANGED: Final = 0x087A0007 +DXGI_STATUS_MODE_CHANGE_IN_PROGRESS: Final = 0x087A0008 +DXGI_ERROR_INVALID_CALL: Final = -2005270527 +DXGI_ERROR_NOT_FOUND: Final = -2005270526 +DXGI_ERROR_MORE_DATA: Final = -2005270525 +DXGI_ERROR_UNSUPPORTED: Final = -2005270524 +DXGI_ERROR_DEVICE_REMOVED: Final = -2005270523 +DXGI_ERROR_DEVICE_HUNG: Final = -2005270522 +DXGI_ERROR_DEVICE_RESET: Final = -2005270521 +DXGI_ERROR_WAS_STILL_DRAWING: Final = -2005270518 +DXGI_ERROR_FRAME_STATISTICS_DISJOINT: Final = -2005270517 +DXGI_ERROR_GRAPHICS_VIDPN_SOURCE_IN_USE: Final = -2005270516 +DXGI_ERROR_DRIVER_INTERNAL_ERROR: Final = -2005270496 +DXGI_ERROR_NONEXCLUSIVE: Final = -2005270495 +DXGI_ERROR_NOT_CURRENTLY_AVAILABLE: Final = -2005270494 +DXGI_ERROR_REMOTE_CLIENT_DISCONNECTED: Final = -2005270493 +DXGI_ERROR_REMOTE_OUTOFMEMORY: Final = -2005270492 +DXGI_ERROR_ACCESS_LOST: Final = -2005270490 +DXGI_ERROR_WAIT_TIMEOUT: Final = -2005270489 +DXGI_ERROR_SESSION_DISCONNECTED: Final = -2005270488 +DXGI_ERROR_RESTRICT_TO_OUTPUT_STALE: Final = -2005270487 +DXGI_ERROR_CANNOT_PROTECT_CONTENT: Final = -2005270486 +DXGI_ERROR_ACCESS_DENIED: Final = -2005270485 +DXGI_ERROR_NAME_ALREADY_EXISTS: Final = -2005270484 +DXGI_ERROR_SDK_COMPONENT_MISSING: Final = -2005270483 +DXGI_ERROR_NOT_CURRENT: Final = -2005270482 +DXGI_ERROR_HW_PROTECTION_OUTOFMEMORY: Final = -2005270480 +DXGI_ERROR_DYNAMIC_CODE_POLICY_VIOLATION: Final = -2005270479 +DXGI_ERROR_NON_COMPOSITED_UI: Final = -2005270478 +DXCORE_ERROR_EVENT_NOT_UNREGISTERED: Final = -2004877311 +PRESENTATION_ERROR_LOST: Final = -2004811775 +DXGI_STATUS_UNOCCLUDED: Final = 0x087A0009 +DXGI_STATUS_DDA_WAS_STILL_DRAWING: Final = 0x087A000A +DXGI_ERROR_MODE_CHANGE_IN_PROGRESS: Final = -2005270491 +DXGI_STATUS_PRESENT_REQUIRED: Final = 0x087A002F +DXGI_ERROR_CACHE_CORRUPT: Final = -2005270477 +DXGI_ERROR_CACHE_FULL: Final = -2005270476 +DXGI_ERROR_CACHE_HASH_COLLISION: Final = -2005270475 +DXGI_ERROR_ALREADY_EXISTS: Final = -2005270474 +DXGI_ERROR_MPO_UNPINNED: Final = -2005270428 +DXGI_DDI_ERR_WASSTILLDRAWING: Final = -2005204991 +DXGI_DDI_ERR_UNSUPPORTED: Final = -2005204990 +DXGI_DDI_ERR_NONEXCLUSIVE: Final = -2005204989 +D3D10_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: Final = -2005336063 +D3D10_ERROR_FILE_NOT_FOUND: Final = -2005336062 +D3D11_ERROR_TOO_MANY_UNIQUE_STATE_OBJECTS: Final = -2005139455 +D3D11_ERROR_FILE_NOT_FOUND: Final = -2005139454 +D3D11_ERROR_TOO_MANY_UNIQUE_VIEW_OBJECTS: Final = -2005139453 +D3D11_ERROR_DEFERRED_CONTEXT_MAP_WITHOUT_INITIAL_DISCARD: Final = -2005139452 +D3D12_ERROR_ADAPTER_NOT_FOUND: Final = -2005008383 +D3D12_ERROR_DRIVER_VERSION_MISMATCH: Final = -2005008382 +D3D12_ERROR_INVALID_REDIST: Final = -2005008381 +D2DERR_WRONG_STATE: Final = -2003238911 +D2DERR_NOT_INITIALIZED: Final = -2003238910 +D2DERR_UNSUPPORTED_OPERATION: Final = -2003238909 +D2DERR_SCANNER_FAILED: Final = -2003238908 +D2DERR_SCREEN_ACCESS_DENIED: Final = -2003238907 +D2DERR_DISPLAY_STATE_INVALID: Final = -2003238906 +D2DERR_ZERO_VECTOR: Final = -2003238905 +D2DERR_INTERNAL_ERROR: Final = -2003238904 +D2DERR_DISPLAY_FORMAT_NOT_SUPPORTED: Final = -2003238903 +D2DERR_INVALID_CALL: Final = -2003238902 +D2DERR_NO_HARDWARE_DEVICE: Final = -2003238901 +D2DERR_RECREATE_TARGET: Final = -2003238900 +D2DERR_TOO_MANY_SHADER_ELEMENTS: Final = -2003238899 +D2DERR_SHADER_COMPILE_FAILED: Final = -2003238898 +D2DERR_MAX_TEXTURE_SIZE_EXCEEDED: Final = -2003238897 +D2DERR_UNSUPPORTED_VERSION: Final = -2003238896 +D2DERR_BAD_NUMBER: Final = -2003238895 +D2DERR_WRONG_FACTORY: Final = -2003238894 +D2DERR_LAYER_ALREADY_IN_USE: Final = -2003238893 +D2DERR_POP_CALL_DID_NOT_MATCH_PUSH: Final = -2003238892 +D2DERR_WRONG_RESOURCE_DOMAIN: Final = -2003238891 +D2DERR_PUSH_POP_UNBALANCED: Final = -2003238890 +D2DERR_RENDER_TARGET_HAS_LAYER_OR_CLIPRECT: Final = -2003238889 +D2DERR_INCOMPATIBLE_BRUSH_TYPES: Final = -2003238888 +D2DERR_WIN32_ERROR: Final = -2003238887 +D2DERR_TARGET_NOT_GDI_COMPATIBLE: Final = -2003238886 +D2DERR_TEXT_EFFECT_IS_WRONG_TYPE: Final = -2003238885 +D2DERR_TEXT_RENDERER_NOT_RELEASED: Final = -2003238884 +D2DERR_EXCEEDS_MAX_BITMAP_SIZE: Final = -2003238883 +D2DERR_INVALID_GRAPH_CONFIGURATION: Final = -2003238882 +D2DERR_INVALID_INTERNAL_GRAPH_CONFIGURATION: Final = -2003238881 +D2DERR_CYCLIC_GRAPH: Final = -2003238880 +D2DERR_BITMAP_CANNOT_DRAW: Final = -2003238879 +D2DERR_OUTSTANDING_BITMAP_REFERENCES: Final = -2003238878 +D2DERR_ORIGINAL_TARGET_NOT_BOUND: Final = -2003238877 +D2DERR_INVALID_TARGET: Final = -2003238876 +D2DERR_BITMAP_BOUND_AS_TARGET: Final = -2003238875 +D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES: Final = -2003238874 +D2DERR_INTERMEDIATE_TOO_LARGE: Final = -2003238873 +D2DERR_EFFECT_IS_NOT_REGISTERED: Final = -2003238872 +D2DERR_INVALID_PROPERTY: Final = -2003238871 +D2DERR_NO_SUBPROPERTIES: Final = -2003238870 +D2DERR_PRINT_JOB_CLOSED: Final = -2003238869 +D2DERR_PRINT_FORMAT_NOT_SUPPORTED: Final = -2003238868 +D2DERR_TOO_MANY_TRANSFORM_INPUTS: Final = -2003238867 +D2DERR_INVALID_GLYPH_IMAGE: Final = -2003238866 +DWRITE_E_FILEFORMAT: Final = -2003283968 +DWRITE_E_UNEXPECTED: Final = -2003283967 +DWRITE_E_NOFONT: Final = -2003283966 +DWRITE_E_FILENOTFOUND: Final = -2003283965 +DWRITE_E_FILEACCESS: Final = -2003283964 +DWRITE_E_FONTCOLLECTIONOBSOLETE: Final = -2003283963 +DWRITE_E_ALREADYREGISTERED: Final = -2003283962 +DWRITE_E_CACHEFORMAT: Final = -2003283961 +DWRITE_E_CACHEVERSION: Final = -2003283960 +DWRITE_E_UNSUPPORTEDOPERATION: Final = -2003283959 +DWRITE_E_TEXTRENDERERINCOMPATIBLE: Final = -2003283958 +DWRITE_E_FLOWDIRECTIONCONFLICTS: Final = -2003283957 +DWRITE_E_NOCOLOR: Final = -2003283956 +DWRITE_E_REMOTEFONT: Final = -2003283955 +DWRITE_E_DOWNLOADCANCELLED: Final = -2003283954 +DWRITE_E_DOWNLOADFAILED: Final = -2003283953 +DWRITE_E_TOOMANYDOWNLOADS: Final = -2003283952 +WINCODEC_ERR_WRONGSTATE: Final = -2003292412 +WINCODEC_ERR_VALUEOUTOFRANGE: Final = -2003292411 +WINCODEC_ERR_UNKNOWNIMAGEFORMAT: Final = -2003292409 +WINCODEC_ERR_UNSUPPORTEDVERSION: Final = -2003292405 +WINCODEC_ERR_NOTINITIALIZED: Final = -2003292404 +WINCODEC_ERR_ALREADYLOCKED: Final = -2003292403 +WINCODEC_ERR_PROPERTYNOTFOUND: Final = -2003292352 +WINCODEC_ERR_PROPERTYNOTSUPPORTED: Final = -2003292351 +WINCODEC_ERR_PROPERTYSIZE: Final = -2003292350 +WINCODEC_ERR_CODECPRESENT: Final = -2003292349 +WINCODEC_ERR_CODECNOTHUMBNAIL: Final = -2003292348 +WINCODEC_ERR_PALETTEUNAVAILABLE: Final = -2003292347 +WINCODEC_ERR_CODECTOOMANYSCANLINES: Final = -2003292346 +WINCODEC_ERR_INTERNALERROR: Final = -2003292344 +WINCODEC_ERR_SOURCERECTDOESNOTMATCHDIMENSIONS: Final = -2003292343 +WINCODEC_ERR_COMPONENTNOTFOUND: Final = -2003292336 +WINCODEC_ERR_IMAGESIZEOUTOFRANGE: Final = -2003292335 +WINCODEC_ERR_TOOMUCHMETADATA: Final = -2003292334 +WINCODEC_ERR_BADIMAGE: Final = -2003292320 +WINCODEC_ERR_BADHEADER: Final = -2003292319 +WINCODEC_ERR_FRAMEMISSING: Final = -2003292318 +WINCODEC_ERR_BADMETADATAHEADER: Final = -2003292317 +WINCODEC_ERR_BADSTREAMDATA: Final = -2003292304 +WINCODEC_ERR_STREAMWRITE: Final = -2003292303 +WINCODEC_ERR_STREAMREAD: Final = -2003292302 +WINCODEC_ERR_STREAMNOTAVAILABLE: Final = -2003292301 +WINCODEC_ERR_UNSUPPORTEDPIXELFORMAT: Final = -2003292288 +WINCODEC_ERR_UNSUPPORTEDOPERATION: Final = -2003292287 +WINCODEC_ERR_INVALIDREGISTRATION: Final = -2003292278 +WINCODEC_ERR_COMPONENTINITIALIZEFAILURE: Final = -2003292277 +WINCODEC_ERR_INSUFFICIENTBUFFER: Final = -2003292276 +WINCODEC_ERR_DUPLICATEMETADATAPRESENT: Final = -2003292275 +WINCODEC_ERR_PROPERTYUNEXPECTEDTYPE: Final = -2003292274 +WINCODEC_ERR_UNEXPECTEDSIZE: Final = -2003292273 +WINCODEC_ERR_INVALIDQUERYREQUEST: Final = -2003292272 +WINCODEC_ERR_UNEXPECTEDMETADATATYPE: Final = -2003292271 +WINCODEC_ERR_REQUESTONLYVALIDATMETADATAROOT: Final = -2003292270 +WINCODEC_ERR_INVALIDQUERYCHARACTER: Final = -2003292269 +WINCODEC_ERR_WIN32ERROR: Final = -2003292268 +WINCODEC_ERR_INVALIDPROGRESSIVELEVEL: Final = -2003292267 +WINCODEC_ERR_INVALIDJPEGSCANINDEX: Final = -2003292266 +MILERR_OBJECTBUSY: Final = -2003304447 +MILERR_INSUFFICIENTBUFFER: Final = -2003304446 +MILERR_WIN32ERROR: Final = -2003304445 +MILERR_SCANNER_FAILED: Final = -2003304444 +MILERR_SCREENACCESSDENIED: Final = -2003304443 +MILERR_DISPLAYSTATEINVALID: Final = -2003304442 +MILERR_NONINVERTIBLEMATRIX: Final = -2003304441 +MILERR_ZEROVECTOR: Final = -2003304440 +MILERR_TERMINATED: Final = -2003304439 +MILERR_BADNUMBER: Final = -2003304438 +MILERR_INTERNALERROR: Final = -2003304320 +MILERR_DISPLAYFORMATNOTSUPPORTED: Final = -2003304316 +MILERR_INVALIDCALL: Final = -2003304315 +MILERR_ALREADYLOCKED: Final = -2003304314 +MILERR_NOTLOCKED: Final = -2003304313 +MILERR_DEVICECANNOTRENDERTEXT: Final = -2003304312 +MILERR_GLYPHBITMAPMISSED: Final = -2003304311 +MILERR_MALFORMEDGLYPHCACHE: Final = -2003304310 +MILERR_GENERIC_IGNORE: Final = -2003304309 +MILERR_MALFORMED_GUIDELINE_DATA: Final = -2003304308 +MILERR_NO_HARDWARE_DEVICE: Final = -2003304307 +MILERR_NEED_RECREATE_AND_PRESENT: Final = -2003304306 +MILERR_ALREADY_INITIALIZED: Final = -2003304305 +MILERR_MISMATCHED_SIZE: Final = -2003304304 +MILERR_NO_REDIRECTION_SURFACE_AVAILABLE: Final = -2003304303 +MILERR_REMOTING_NOT_SUPPORTED: Final = -2003304302 +MILERR_QUEUED_PRESENT_NOT_SUPPORTED: Final = -2003304301 +MILERR_NOT_QUEUING_PRESENTS: Final = -2003304300 +MILERR_NO_REDIRECTION_SURFACE_RETRY_LATER: Final = -2003304299 +MILERR_TOOMANYSHADERELEMNTS: Final = -2003304298 +MILERR_MROW_READLOCK_FAILED: Final = -2003304297 +MILERR_MROW_UPDATE_FAILED: Final = -2003304296 +MILERR_SHADER_COMPILE_FAILED: Final = -2003304295 +MILERR_MAX_TEXTURE_SIZE_EXCEEDED: Final = -2003304294 +MILERR_QPC_TIME_WENT_BACKWARD: Final = -2003304293 +MILERR_DXGI_ENUMERATION_OUT_OF_SYNC: Final = -2003304291 +MILERR_ADAPTER_NOT_FOUND: Final = -2003304290 +MILERR_COLORSPACE_NOT_SUPPORTED: Final = -2003304289 +MILERR_PREFILTER_NOT_SUPPORTED: Final = -2003304288 +MILERR_DISPLAYID_ACCESS_DENIED: Final = -2003304287 +UCEERR_INVALIDPACKETHEADER: Final = -2003303424 +UCEERR_UNKNOWNPACKET: Final = -2003303423 +UCEERR_ILLEGALPACKET: Final = -2003303422 +UCEERR_MALFORMEDPACKET: Final = -2003303421 +UCEERR_ILLEGALHANDLE: Final = -2003303420 +UCEERR_HANDLELOOKUPFAILED: Final = -2003303419 +UCEERR_RENDERTHREADFAILURE: Final = -2003303418 +UCEERR_CTXSTACKFRSTTARGETNULL: Final = -2003303417 +UCEERR_CONNECTIONIDLOOKUPFAILED: Final = -2003303416 +UCEERR_BLOCKSFULL: Final = -2003303415 +UCEERR_MEMORYFAILURE: Final = -2003303414 +UCEERR_PACKETRECORDOUTOFRANGE: Final = -2003303413 +UCEERR_ILLEGALRECORDTYPE: Final = -2003303412 +UCEERR_OUTOFHANDLES: Final = -2003303411 +UCEERR_UNCHANGABLE_UPDATE_ATTEMPTED: Final = -2003303410 +UCEERR_NO_MULTIPLE_WORKER_THREADS: Final = -2003303409 +UCEERR_REMOTINGNOTSUPPORTED: Final = -2003303408 +UCEERR_MISSINGENDCOMMAND: Final = -2003303407 +UCEERR_MISSINGBEGINCOMMAND: Final = -2003303406 +UCEERR_CHANNELSYNCTIMEDOUT: Final = -2003303405 +UCEERR_CHANNELSYNCABANDONED: Final = -2003303404 +UCEERR_UNSUPPORTEDTRANSPORTVERSION: Final = -2003303403 +UCEERR_TRANSPORTUNAVAILABLE: Final = -2003303402 +UCEERR_FEEDBACK_UNSUPPORTED: Final = -2003303401 +UCEERR_COMMANDTRANSPORTDENIED: Final = -2003303400 +UCEERR_GRAPHICSSTREAMUNAVAILABLE: Final = -2003303399 +UCEERR_GRAPHICSSTREAMALREADYOPEN: Final = -2003303392 +UCEERR_TRANSPORTDISCONNECTED: Final = -2003303391 +UCEERR_TRANSPORTOVERLOADED: Final = -2003303390 +UCEERR_PARTITION_ZOMBIED: Final = -2003303389 +MILAVERR_NOCLOCK: Final = -2003303168 +MILAVERR_NOMEDIATYPE: Final = -2003303167 +MILAVERR_NOVIDEOMIXER: Final = -2003303166 +MILAVERR_NOVIDEOPRESENTER: Final = -2003303165 +MILAVERR_NOREADYFRAMES: Final = -2003303164 +MILAVERR_MODULENOTLOADED: Final = -2003303163 +MILAVERR_WMPFACTORYNOTREGISTERED: Final = -2003303162 +MILAVERR_INVALIDWMPVERSION: Final = -2003303161 +MILAVERR_INSUFFICIENTVIDEORESOURCES: Final = -2003303160 +MILAVERR_VIDEOACCELERATIONNOTAVAILABLE: Final = -2003303159 +MILAVERR_REQUESTEDTEXTURETOOBIG: Final = -2003303158 +MILAVERR_SEEKFAILED: Final = -2003303157 +MILAVERR_UNEXPECTEDWMPFAILURE: Final = -2003303156 +MILAVERR_MEDIAPLAYERCLOSED: Final = -2003303155 +MILAVERR_UNKNOWNHARDWAREERROR: Final = -2003303154 +MILEFFECTSERR_UNKNOWNPROPERTY: Final = -2003302898 +MILEFFECTSERR_EFFECTNOTPARTOFGROUP: Final = -2003302897 +MILEFFECTSERR_NOINPUTSOURCEATTACHED: Final = -2003302896 +MILEFFECTSERR_CONNECTORNOTCONNECTED: Final = -2003302895 +MILEFFECTSERR_CONNECTORNOTASSOCIATEDWITHEFFECT: Final = -2003302894 +MILEFFECTSERR_RESERVED: Final = -2003302893 +MILEFFECTSERR_CYCLEDETECTED: Final = -2003302892 +MILEFFECTSERR_EFFECTINMORETHANONEGRAPH: Final = -2003302891 +MILEFFECTSERR_EFFECTALREADYINAGRAPH: Final = -2003302890 +MILEFFECTSERR_EFFECTHASNOCHILDREN: Final = -2003302889 +MILEFFECTSERR_ALREADYATTACHEDTOLISTENER: Final = -2003302888 +MILEFFECTSERR_NOTAFFINETRANSFORM: Final = -2003302887 +MILEFFECTSERR_EMPTYBOUNDS: Final = -2003302886 +MILEFFECTSERR_OUTPUTSIZETOOLARGE: Final = -2003302885 +DWMERR_STATE_TRANSITION_FAILED: Final = -2003302656 +DWMERR_THEME_FAILED: Final = -2003302655 +DWMERR_CATASTROPHIC_FAILURE: Final = -2003302654 +DCOMPOSITION_ERROR_WINDOW_ALREADY_COMPOSED: Final = -2003302400 +DCOMPOSITION_ERROR_SURFACE_BEING_RENDERED: Final = -2003302399 +DCOMPOSITION_ERROR_SURFACE_NOT_BEING_RENDERED: Final = -2003302398 +ONL_E_INVALID_AUTHENTICATION_TARGET: Final = -2138701823 +ONL_E_ACCESS_DENIED_BY_TOU: Final = -2138701822 +ONL_E_INVALID_APPLICATION: Final = -2138701821 +ONL_E_PASSWORD_UPDATE_REQUIRED: Final = -2138701820 +ONL_E_ACCOUNT_UPDATE_REQUIRED: Final = -2138701819 +ONL_E_FORCESIGNIN: Final = -2138701818 +ONL_E_ACCOUNT_LOCKED: Final = -2138701817 +ONL_E_PARENTAL_CONSENT_REQUIRED: Final = -2138701816 +ONL_E_EMAIL_VERIFICATION_REQUIRED: Final = -2138701815 +ONL_E_ACCOUNT_SUSPENDED_COMPROIMISE: Final = -2138701814 +ONL_E_ACCOUNT_SUSPENDED_ABUSE: Final = -2138701813 +ONL_E_ACTION_REQUIRED: Final = -2138701812 +ONL_CONNECTION_COUNT_LIMIT: Final = -2138701811 +ONL_E_CONNECTED_ACCOUNT_CAN_NOT_SIGNOUT: Final = -2138701810 +ONL_E_USER_AUTHENTICATION_REQUIRED: Final = -2138701809 +ONL_E_REQUEST_THROTTLED: Final = -2138701808 +FA_E_MAX_PERSISTED_ITEMS_REACHED: Final = -2144927200 +FA_E_HOMEGROUP_NOT_AVAILABLE: Final = -2144927198 +E_MONITOR_RESOLUTION_TOO_LOW: Final = -2144927152 +E_ELEVATED_ACTIVATION_NOT_SUPPORTED: Final = -2144927151 +E_UAC_DISABLED: Final = -2144927150 +E_FULL_ADMIN_NOT_SUPPORTED: Final = -2144927149 +E_APPLICATION_NOT_REGISTERED: Final = -2144927148 +E_MULTIPLE_EXTENSIONS_FOR_APPLICATION: Final = -2144927147 +E_MULTIPLE_PACKAGES_FOR_FAMILY: Final = -2144927146 +E_APPLICATION_MANAGER_NOT_RUNNING: Final = -2144927145 +S_STORE_LAUNCHED_FOR_REMEDIATION: Final = 0x00270258 +S_APPLICATION_ACTIVATION_ERROR_HANDLED_BY_DIALOG: Final = 0x00270259 +E_APPLICATION_ACTIVATION_TIMED_OUT: Final = -2144927142 +E_APPLICATION_ACTIVATION_EXEC_FAILURE: Final = -2144927141 +E_APPLICATION_TEMPORARY_LICENSE_ERROR: Final = -2144927140 +E_APPLICATION_TRIAL_LICENSE_EXPIRED: Final = -2144927139 +E_SKYDRIVE_ROOT_TARGET_FILE_SYSTEM_NOT_SUPPORTED: Final = -2144927136 +E_SKYDRIVE_ROOT_TARGET_OVERLAP: Final = -2144927135 +E_SKYDRIVE_ROOT_TARGET_CANNOT_INDEX: Final = -2144927134 +E_SKYDRIVE_FILE_NOT_UPLOADED: Final = -2144927133 +E_SKYDRIVE_UPDATE_AVAILABILITY_FAIL: Final = -2144927132 +E_SKYDRIVE_ROOT_TARGET_VOLUME_ROOT_NOT_SUPPORTED: Final = -2144927131 +E_SYNCENGINE_FILE_SIZE_OVER_LIMIT: Final = -2013089791 +E_SYNCENGINE_FILE_SIZE_EXCEEDS_REMAINING_QUOTA: Final = -2013089790 +E_SYNCENGINE_UNSUPPORTED_FILE_NAME: Final = -2013089789 +E_SYNCENGINE_FOLDER_ITEM_COUNT_LIMIT_EXCEEDED: Final = -2013089788 +E_SYNCENGINE_FILE_SYNC_PARTNER_ERROR: Final = -2013089787 +E_SYNCENGINE_SYNC_PAUSED_BY_SERVICE: Final = -2013089786 +E_SYNCENGINE_FILE_IDENTIFIER_UNKNOWN: Final = -2013085694 +E_SYNCENGINE_SERVICE_AUTHENTICATION_FAILED: Final = -2013085693 +E_SYNCENGINE_UNKNOWN_SERVICE_ERROR: Final = -2013085692 +E_SYNCENGINE_SERVICE_RETURNED_UNEXPECTED_SIZE: Final = -2013085691 +E_SYNCENGINE_REQUEST_BLOCKED_BY_SERVICE: Final = -2013085690 +E_SYNCENGINE_REQUEST_BLOCKED_DUE_TO_CLIENT_ERROR: Final = -2013085689 +E_SYNCENGINE_FOLDER_INACCESSIBLE: Final = -2013081599 +E_SYNCENGINE_UNSUPPORTED_FOLDER_NAME: Final = -2013081598 +E_SYNCENGINE_UNSUPPORTED_MARKET: Final = -2013081597 +E_SYNCENGINE_PATH_LENGTH_LIMIT_EXCEEDED: Final = -2013081596 +E_SYNCENGINE_REMOTE_PATH_LENGTH_LIMIT_EXCEEDED: Final = -2013081595 +E_SYNCENGINE_CLIENT_UPDATE_NEEDED: Final = -2013081594 +E_SYNCENGINE_PROXY_AUTHENTICATION_REQUIRED: Final = -2013081593 +E_SYNCENGINE_STORAGE_SERVICE_PROVISIONING_FAILED: Final = -2013081592 +E_SYNCENGINE_UNSUPPORTED_REPARSE_POINT: Final = -2013081591 +E_SYNCENGINE_STORAGE_SERVICE_BLOCKED: Final = -2013081590 +E_SYNCENGINE_FOLDER_IN_REDIRECTION: Final = -2013081589 +EAS_E_POLICY_NOT_MANAGED_BY_OS: Final = -2141913087 +EAS_E_POLICY_COMPLIANT_WITH_ACTIONS: Final = -2141913086 +EAS_E_REQUESTED_POLICY_NOT_ENFORCEABLE: Final = -2141913085 +EAS_E_CURRENT_USER_HAS_BLANK_PASSWORD: Final = -2141913084 +EAS_E_REQUESTED_POLICY_PASSWORD_EXPIRATION_INCOMPATIBLE: Final = -2141913083 +EAS_E_USER_CANNOT_CHANGE_PASSWORD: Final = -2141913082 +EAS_E_ADMINS_HAVE_BLANK_PASSWORD: Final = -2141913081 +EAS_E_ADMINS_CANNOT_CHANGE_PASSWORD: Final = -2141913080 +EAS_E_LOCAL_CONTROLLED_USERS_CANNOT_CHANGE_PASSWORD: Final = -2141913079 +EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CONNECTED_ADMINS: Final = -2141913078 +EAS_E_CONNECTED_ADMINS_NEED_TO_CHANGE_PASSWORD: Final = -2141913077 +EAS_E_PASSWORD_POLICY_NOT_ENFORCEABLE_FOR_CURRENT_CONNECTED_USER: Final = -2141913076 +EAS_E_CURRENT_CONNECTED_USER_NEED_TO_CHANGE_PASSWORD: Final = -2141913075 +WEB_E_UNSUPPORTED_FORMAT: Final = -2089484287 +WEB_E_INVALID_XML: Final = -2089484286 +WEB_E_MISSING_REQUIRED_ELEMENT: Final = -2089484285 +WEB_E_MISSING_REQUIRED_ATTRIBUTE: Final = -2089484284 +WEB_E_UNEXPECTED_CONTENT: Final = -2089484283 +WEB_E_RESOURCE_TOO_LARGE: Final = -2089484282 +WEB_E_INVALID_JSON_STRING: Final = -2089484281 +WEB_E_INVALID_JSON_NUMBER: Final = -2089484280 +WEB_E_JSON_VALUE_NOT_FOUND: Final = -2089484279 +HTTP_E_STATUS_UNEXPECTED: Final = -2145845247 +HTTP_E_STATUS_UNEXPECTED_REDIRECTION: Final = -2145845245 +HTTP_E_STATUS_UNEXPECTED_CLIENT_ERROR: Final = -2145845244 +HTTP_E_STATUS_UNEXPECTED_SERVER_ERROR: Final = -2145845243 +HTTP_E_STATUS_AMBIGUOUS: Final = -2145844948 +HTTP_E_STATUS_MOVED: Final = -2145844947 +HTTP_E_STATUS_REDIRECT: Final = -2145844946 +HTTP_E_STATUS_REDIRECT_METHOD: Final = -2145844945 +HTTP_E_STATUS_NOT_MODIFIED: Final = -2145844944 +HTTP_E_STATUS_USE_PROXY: Final = -2145844943 +HTTP_E_STATUS_REDIRECT_KEEP_VERB: Final = -2145844941 +HTTP_E_STATUS_BAD_REQUEST: Final = -2145844848 +HTTP_E_STATUS_DENIED: Final = -2145844847 +HTTP_E_STATUS_PAYMENT_REQ: Final = -2145844846 +HTTP_E_STATUS_FORBIDDEN: Final = -2145844845 +HTTP_E_STATUS_NOT_FOUND: Final = -2145844844 +HTTP_E_STATUS_BAD_METHOD: Final = -2145844843 +HTTP_E_STATUS_NONE_ACCEPTABLE: Final = -2145844842 +HTTP_E_STATUS_PROXY_AUTH_REQ: Final = -2145844841 +HTTP_E_STATUS_REQUEST_TIMEOUT: Final = -2145844840 +HTTP_E_STATUS_CONFLICT: Final = -2145844839 +HTTP_E_STATUS_GONE: Final = -2145844838 +HTTP_E_STATUS_LENGTH_REQUIRED: Final = -2145844837 +HTTP_E_STATUS_PRECOND_FAILED: Final = -2145844836 +HTTP_E_STATUS_REQUEST_TOO_LARGE: Final = -2145844835 +HTTP_E_STATUS_URI_TOO_LONG: Final = -2145844834 +HTTP_E_STATUS_UNSUPPORTED_MEDIA: Final = -2145844833 +HTTP_E_STATUS_RANGE_NOT_SATISFIABLE: Final = -2145844832 +HTTP_E_STATUS_EXPECTATION_FAILED: Final = -2145844831 +HTTP_E_STATUS_SERVER_ERROR: Final = -2145844748 +HTTP_E_STATUS_NOT_SUPPORTED: Final = -2145844747 +HTTP_E_STATUS_BAD_GATEWAY: Final = -2145844746 +HTTP_E_STATUS_SERVICE_UNAVAIL: Final = -2145844745 +HTTP_E_STATUS_GATEWAY_TIMEOUT: Final = -2145844744 +HTTP_E_STATUS_VERSION_NOT_SUP: Final = -2145844743 +E_INVALID_PROTOCOL_OPERATION: Final = -2089418751 +E_INVALID_PROTOCOL_FORMAT: Final = -2089418750 +E_PROTOCOL_EXTENSIONS_NOT_SUPPORTED: Final = -2089418749 +E_SUBPROTOCOL_NOT_SUPPORTED: Final = -2089418748 +E_PROTOCOL_VERSION_NOT_SUPPORTED: Final = -2089418747 +INPUT_E_OUT_OF_ORDER: Final = -2143289344 +INPUT_E_REENTRANCY: Final = -2143289343 +INPUT_E_MULTIMODAL: Final = -2143289342 +INPUT_E_PACKET: Final = -2143289341 +INPUT_E_FRAME: Final = -2143289340 +INPUT_E_HISTORY: Final = -2143289339 +INPUT_E_DEVICE_INFO: Final = -2143289338 +INPUT_E_TRANSFORM: Final = -2143289337 +INPUT_E_DEVICE_PROPERTY: Final = -2143289336 +INET_E_INVALID_URL: Final = -2146697214 +INET_E_NO_SESSION: Final = -2146697213 +INET_E_CANNOT_CONNECT: Final = -2146697212 +INET_E_RESOURCE_NOT_FOUND: Final = -2146697211 +INET_E_OBJECT_NOT_FOUND: Final = -2146697210 +INET_E_DATA_NOT_AVAILABLE: Final = -2146697209 +INET_E_DOWNLOAD_FAILURE: Final = -2146697208 +INET_E_AUTHENTICATION_REQUIRED: Final = -2146697207 +INET_E_NO_VALID_MEDIA: Final = -2146697206 +INET_E_CONNECTION_TIMEOUT: Final = -2146697205 +INET_E_INVALID_REQUEST: Final = -2146697204 +INET_E_UNKNOWN_PROTOCOL: Final = -2146697203 +INET_E_SECURITY_PROBLEM: Final = -2146697202 +INET_E_CANNOT_LOAD_DATA: Final = -2146697201 +INET_E_CANNOT_INSTANTIATE_OBJECT: Final = -2146697200 +INET_E_INVALID_CERTIFICATE: Final = -2146697191 +INET_E_REDIRECT_FAILED: Final = -2146697196 +INET_E_REDIRECT_TO_DIR: Final = -2146697195 +ERROR_DBG_CREATE_PROCESS_FAILURE_LOCKDOWN: Final = -2135949311 +ERROR_DBG_ATTACH_PROCESS_FAILURE_LOCKDOWN: Final = -2135949310 +ERROR_DBG_CONNECT_SERVER_FAILURE_LOCKDOWN: Final = -2135949309 +ERROR_DBG_START_SERVER_FAILURE_LOCKDOWN: Final = -2135949308 +HSP_E_ERROR_MASK: Final = -2128084992 +HSP_E_INTERNAL_ERROR: Final = -2128080897 +HSP_BS_ERROR_MASK: Final = -2128080896 +HSP_BS_INTERNAL_ERROR: Final = -2128080641 +HSP_DRV_ERROR_MASK: Final = -2128019456 +HSP_DRV_INTERNAL_ERROR: Final = -2128019201 +HSP_BASE_ERROR_MASK: Final = -2128019200 +HSP_BASE_INTERNAL_ERROR: Final = -2128018945 +HSP_KSP_ERROR_MASK: Final = -2128018944 +HSP_KSP_DEVICE_NOT_READY: Final = -2128018943 +HSP_KSP_INVALID_PROVIDER_HANDLE: Final = -2128018942 +HSP_KSP_INVALID_KEY_HANDLE: Final = -2128018941 +HSP_KSP_INVALID_PARAMETER: Final = -2128018940 +HSP_KSP_BUFFER_TOO_SMALL: Final = -2128018939 +HSP_KSP_NOT_SUPPORTED: Final = -2128018938 +HSP_KSP_INVALID_DATA: Final = -2128018937 +HSP_KSP_INVALID_FLAGS: Final = -2128018936 +HSP_KSP_ALGORITHM_NOT_SUPPORTED: Final = -2128018935 +HSP_KSP_KEY_ALREADY_FINALIZED: Final = -2128018934 +HSP_KSP_KEY_NOT_FINALIZED: Final = -2128018933 +HSP_KSP_INVALID_KEY_TYPE: Final = -2128018932 +HSP_KSP_NO_MEMORY: Final = -2128018928 +HSP_KSP_PARAMETER_NOT_SET: Final = -2128018927 +HSP_KSP_KEY_EXISTS: Final = -2128018923 +HSP_KSP_KEY_MISSING: Final = -2128018922 +HSP_KSP_KEY_LOAD_FAIL: Final = -2128018921 +HSP_KSP_NO_MORE_ITEMS: Final = -2128018920 +HSP_KSP_INTERNAL_ERROR: Final = -2128018689 +ERROR_IO_PREEMPTED: Final = -1996423167 +JSCRIPT_E_CANTEXECUTE: Final = -1996357631 +WEP_E_NOT_PROVISIONED_ON_ALL_VOLUMES: Final = -2013200383 +WEP_E_FIXED_DATA_NOT_SUPPORTED: Final = -2013200382 +WEP_E_HARDWARE_NOT_COMPLIANT: Final = -2013200381 +WEP_E_LOCK_NOT_CONFIGURED: Final = -2013200380 +WEP_E_PROTECTION_SUSPENDED: Final = -2013200379 +WEP_E_NO_LICENSE: Final = -2013200378 +WEP_E_OS_NOT_PROTECTED: Final = -2013200377 +WEP_E_UNEXPECTED_FAIL: Final = -2013200376 +WEP_E_BUFFER_TOO_LARGE: Final = -2013200375 +ERROR_SVHDX_ERROR_STORED: Final = -1067712512 +ERROR_SVHDX_ERROR_NOT_AVAILABLE: Final = -1067647232 +ERROR_SVHDX_UNIT_ATTENTION_AVAILABLE: Final = -1067647231 +ERROR_SVHDX_UNIT_ATTENTION_CAPACITY_DATA_CHANGED: Final = -1067647230 +ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_PREEMPTED: Final = -1067647229 +ERROR_SVHDX_UNIT_ATTENTION_RESERVATIONS_RELEASED: Final = -1067647228 +ERROR_SVHDX_UNIT_ATTENTION_REGISTRATIONS_PREEMPTED: Final = -1067647227 +ERROR_SVHDX_UNIT_ATTENTION_OPERATING_DEFINITION_CHANGED: Final = -1067647226 +ERROR_SVHDX_RESERVATION_CONFLICT: Final = -1067647225 +ERROR_SVHDX_WRONG_FILE_TYPE: Final = -1067647224 +ERROR_SVHDX_VERSION_MISMATCH: Final = -1067647223 +ERROR_VHD_SHARED: Final = -1067647222 +ERROR_SVHDX_NO_INITIATOR: Final = -1067647221 +ERROR_VHDSET_BACKING_STORAGE_NOT_FOUND: Final = -1067647220 +ERROR_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP: Final = -1067646976 +ERROR_SMB_BAD_CLUSTER_DIALECT: Final = -1067646975 +ERROR_SMB_NO_SIGNING_ALGORITHM_OVERLAP: Final = -1067646974 +WININET_E_OUT_OF_HANDLES: Final = -2147012895 +WININET_E_TIMEOUT: Final = -2147012894 +WININET_E_EXTENDED_ERROR: Final = -2147012893 +WININET_E_INTERNAL_ERROR: Final = -2147012892 +WININET_E_INVALID_URL: Final = -2147012891 +WININET_E_UNRECOGNIZED_SCHEME: Final = -2147012890 +WININET_E_NAME_NOT_RESOLVED: Final = -2147012889 +WININET_E_PROTOCOL_NOT_FOUND: Final = -2147012888 +WININET_E_INVALID_OPTION: Final = -2147012887 +WININET_E_BAD_OPTION_LENGTH: Final = -2147012886 +WININET_E_OPTION_NOT_SETTABLE: Final = -2147012885 +WININET_E_SHUTDOWN: Final = -2147012884 +WININET_E_INCORRECT_USER_NAME: Final = -2147012883 +WININET_E_INCORRECT_PASSWORD: Final = -2147012882 +WININET_E_LOGIN_FAILURE: Final = -2147012881 +WININET_E_INVALID_OPERATION: Final = -2147012880 +WININET_E_OPERATION_CANCELLED: Final = -2147012879 +WININET_E_INCORRECT_HANDLE_TYPE: Final = -2147012878 +WININET_E_INCORRECT_HANDLE_STATE: Final = -2147012877 +WININET_E_NOT_PROXY_REQUEST: Final = -2147012876 +WININET_E_REGISTRY_VALUE_NOT_FOUND: Final = -2147012875 +WININET_E_BAD_REGISTRY_PARAMETER: Final = -2147012874 +WININET_E_NO_DIRECT_ACCESS: Final = -2147012873 +WININET_E_NO_CONTEXT: Final = -2147012872 +WININET_E_NO_CALLBACK: Final = -2147012871 +WININET_E_REQUEST_PENDING: Final = -2147012870 +WININET_E_INCORRECT_FORMAT: Final = -2147012869 +WININET_E_ITEM_NOT_FOUND: Final = -2147012868 +WININET_E_CANNOT_CONNECT: Final = -2147012867 +WININET_E_CONNECTION_ABORTED: Final = -2147012866 +WININET_E_CONNECTION_RESET: Final = -2147012865 +WININET_E_FORCE_RETRY: Final = -2147012864 +WININET_E_INVALID_PROXY_REQUEST: Final = -2147012863 +WININET_E_NEED_UI: Final = -2147012862 +WININET_E_HANDLE_EXISTS: Final = -2147012860 +WININET_E_SEC_CERT_DATE_INVALID: Final = -2147012859 +WININET_E_SEC_CERT_CN_INVALID: Final = -2147012858 +WININET_E_HTTP_TO_HTTPS_ON_REDIR: Final = -2147012857 +WININET_E_HTTPS_TO_HTTP_ON_REDIR: Final = -2147012856 +WININET_E_MIXED_SECURITY: Final = -2147012855 +WININET_E_CHG_POST_IS_NON_SECURE: Final = -2147012854 +WININET_E_POST_IS_NON_SECURE: Final = -2147012853 +WININET_E_CLIENT_AUTH_CERT_NEEDED: Final = -2147012852 +WININET_E_INVALID_CA: Final = -2147012851 +WININET_E_CLIENT_AUTH_NOT_SETUP: Final = -2147012850 +WININET_E_ASYNC_THREAD_FAILED: Final = -2147012849 +WININET_E_REDIRECT_SCHEME_CHANGE: Final = -2147012848 +WININET_E_DIALOG_PENDING: Final = -2147012847 +WININET_E_RETRY_DIALOG: Final = -2147012846 +WININET_E_NO_NEW_CONTAINERS: Final = -2147012845 +WININET_E_HTTPS_HTTP_SUBMIT_REDIR: Final = -2147012844 +WININET_E_SEC_CERT_ERRORS: Final = -2147012841 +WININET_E_SEC_CERT_REV_FAILED: Final = -2147012839 +WININET_E_HEADER_NOT_FOUND: Final = -2147012746 +WININET_E_DOWNLEVEL_SERVER: Final = -2147012745 +WININET_E_INVALID_SERVER_RESPONSE: Final = -2147012744 +WININET_E_INVALID_HEADER: Final = -2147012743 +WININET_E_INVALID_QUERY_REQUEST: Final = -2147012742 +WININET_E_HEADER_ALREADY_EXISTS: Final = -2147012741 +WININET_E_REDIRECT_FAILED: Final = -2147012740 +WININET_E_SECURITY_CHANNEL_ERROR: Final = -2147012739 +WININET_E_UNABLE_TO_CACHE_FILE: Final = -2147012738 +WININET_E_TCPIP_NOT_INSTALLED: Final = -2147012737 +WININET_E_DISCONNECTED: Final = -2147012733 +WININET_E_SERVER_UNREACHABLE: Final = -2147012732 +WININET_E_PROXY_SERVER_UNREACHABLE: Final = -2147012731 +WININET_E_BAD_AUTO_PROXY_SCRIPT: Final = -2147012730 +WININET_E_UNABLE_TO_DOWNLOAD_SCRIPT: Final = -2147012729 +WININET_E_SEC_INVALID_CERT: Final = -2147012727 +WININET_E_SEC_CERT_REVOKED: Final = -2147012726 +WININET_E_FAILED_DUETOSECURITYCHECK: Final = -2147012725 +WININET_E_NOT_INITIALIZED: Final = -2147012724 +WININET_E_LOGIN_FAILURE_DISPLAY_ENTITY_BODY: Final = -2147012722 +WININET_E_DECODING_FAILED: Final = -2147012721 +WININET_E_NOT_REDIRECTED: Final = -2147012736 +WININET_E_COOKIE_NEEDS_CONFIRMATION: Final = -2147012735 +WININET_E_COOKIE_DECLINED: Final = -2147012734 +WININET_E_REDIRECT_NEEDS_CONFIRMATION: Final = -2147012728 +SQLITE_E_ERROR: Final = -2018574335 +SQLITE_E_INTERNAL: Final = -2018574334 +SQLITE_E_PERM: Final = -2018574333 +SQLITE_E_ABORT: Final = -2018574332 +SQLITE_E_BUSY: Final = -2018574331 +SQLITE_E_LOCKED: Final = -2018574330 +SQLITE_E_NOMEM: Final = -2018574329 +SQLITE_E_READONLY: Final = -2018574328 +SQLITE_E_INTERRUPT: Final = -2018574327 +SQLITE_E_IOERR: Final = -2018574326 +SQLITE_E_CORRUPT: Final = -2018574325 +SQLITE_E_NOTFOUND: Final = -2018574324 +SQLITE_E_FULL: Final = -2018574323 +SQLITE_E_CANTOPEN: Final = -2018574322 +SQLITE_E_PROTOCOL: Final = -2018574321 +SQLITE_E_EMPTY: Final = -2018574320 +SQLITE_E_SCHEMA: Final = -2018574319 +SQLITE_E_TOOBIG: Final = -2018574318 +SQLITE_E_CONSTRAINT: Final = -2018574317 +SQLITE_E_MISMATCH: Final = -2018574316 +SQLITE_E_MISUSE: Final = -2018574315 +SQLITE_E_NOLFS: Final = -2018574314 +SQLITE_E_AUTH: Final = -2018574313 +SQLITE_E_FORMAT: Final = -2018574312 +SQLITE_E_RANGE: Final = -2018574311 +SQLITE_E_NOTADB: Final = -2018574310 +SQLITE_E_NOTICE: Final = -2018574309 +SQLITE_E_WARNING: Final = -2018574308 +SQLITE_E_ROW: Final = -2018574236 +SQLITE_E_DONE: Final = -2018574235 +SQLITE_E_IOERR_READ: Final = -2018574070 +SQLITE_E_IOERR_SHORT_READ: Final = -2018573814 +SQLITE_E_IOERR_WRITE: Final = -2018573558 +SQLITE_E_IOERR_FSYNC: Final = -2018573302 +SQLITE_E_IOERR_DIR_FSYNC: Final = -2018573046 +SQLITE_E_IOERR_TRUNCATE: Final = -2018572790 +SQLITE_E_IOERR_FSTAT: Final = -2018572534 +SQLITE_E_IOERR_UNLOCK: Final = -2018572278 +SQLITE_E_IOERR_RDLOCK: Final = -2018572022 +SQLITE_E_IOERR_DELETE: Final = -2018571766 +SQLITE_E_IOERR_BLOCKED: Final = -2018571510 +SQLITE_E_IOERR_NOMEM: Final = -2018571254 +SQLITE_E_IOERR_ACCESS: Final = -2018570998 +SQLITE_E_IOERR_CHECKRESERVEDLOCK: Final = -2018570742 +SQLITE_E_IOERR_LOCK: Final = -2018570486 +SQLITE_E_IOERR_CLOSE: Final = -2018570230 +SQLITE_E_IOERR_DIR_CLOSE: Final = -2018569974 +SQLITE_E_IOERR_SHMOPEN: Final = -2018569718 +SQLITE_E_IOERR_SHMSIZE: Final = -2018569462 +SQLITE_E_IOERR_SHMLOCK: Final = -2018569206 +SQLITE_E_IOERR_SHMMAP: Final = -2018568950 +SQLITE_E_IOERR_SEEK: Final = -2018568694 +SQLITE_E_IOERR_DELETE_NOENT: Final = -2018568438 +SQLITE_E_IOERR_MMAP: Final = -2018568182 +SQLITE_E_IOERR_GETTEMPPATH: Final = -2018567926 +SQLITE_E_IOERR_CONVPATH: Final = -2018567670 +SQLITE_E_IOERR_VNODE: Final = -2018567678 +SQLITE_E_IOERR_AUTH: Final = -2018567677 +SQLITE_E_LOCKED_SHAREDCACHE: Final = -2018574074 +SQLITE_E_BUSY_RECOVERY: Final = -2018574075 +SQLITE_E_BUSY_SNAPSHOT: Final = -2018573819 +SQLITE_E_CANTOPEN_NOTEMPDIR: Final = -2018574066 +SQLITE_E_CANTOPEN_ISDIR: Final = -2018573810 +SQLITE_E_CANTOPEN_FULLPATH: Final = -2018573554 +SQLITE_E_CANTOPEN_CONVPATH: Final = -2018573298 +SQLITE_E_CORRUPT_VTAB: Final = -2018574069 +SQLITE_E_READONLY_RECOVERY: Final = -2018574072 +SQLITE_E_READONLY_CANTLOCK: Final = -2018573816 +SQLITE_E_READONLY_ROLLBACK: Final = -2018573560 +SQLITE_E_READONLY_DBMOVED: Final = -2018573304 +SQLITE_E_ABORT_ROLLBACK: Final = -2018573820 +SQLITE_E_CONSTRAINT_CHECK: Final = -2018574061 +SQLITE_E_CONSTRAINT_COMMITHOOK: Final = -2018573805 +SQLITE_E_CONSTRAINT_FOREIGNKEY: Final = -2018573549 +SQLITE_E_CONSTRAINT_FUNCTION: Final = -2018573293 +SQLITE_E_CONSTRAINT_NOTNULL: Final = -2018573037 +SQLITE_E_CONSTRAINT_PRIMARYKEY: Final = -2018572781 +SQLITE_E_CONSTRAINT_TRIGGER: Final = -2018572525 +SQLITE_E_CONSTRAINT_UNIQUE: Final = -2018572269 +SQLITE_E_CONSTRAINT_VTAB: Final = -2018572013 +SQLITE_E_CONSTRAINT_ROWID: Final = -2018571757 +SQLITE_E_NOTICE_RECOVER_WAL: Final = -2018574053 +SQLITE_E_NOTICE_RECOVER_ROLLBACK: Final = -2018573797 +SQLITE_E_WARNING_AUTOINDEX: Final = -2018574052 +UTC_E_TOGGLE_TRACE_STARTED: Final = -2017128447 +UTC_E_ALTERNATIVE_TRACE_CANNOT_PREEMPT: Final = -2017128446 +UTC_E_AOT_NOT_RUNNING: Final = -2017128445 +UTC_E_SCRIPT_TYPE_INVALID: Final = -2017128444 +UTC_E_SCENARIODEF_NOT_FOUND: Final = -2017128443 +UTC_E_TRACEPROFILE_NOT_FOUND: Final = -2017128442 +UTC_E_FORWARDER_ALREADY_ENABLED: Final = -2017128441 +UTC_E_FORWARDER_ALREADY_DISABLED: Final = -2017128440 +UTC_E_EVENTLOG_ENTRY_MALFORMED: Final = -2017128439 +UTC_E_DIAGRULES_SCHEMAVERSION_MISMATCH: Final = -2017128438 +UTC_E_SCRIPT_TERMINATED: Final = -2017128437 +UTC_E_INVALID_CUSTOM_FILTER: Final = -2017128436 +UTC_E_TRACE_NOT_RUNNING: Final = -2017128435 +UTC_E_REESCALATED_TOO_QUICKLY: Final = -2017128434 +UTC_E_ESCALATION_ALREADY_RUNNING: Final = -2017128433 +UTC_E_PERFTRACK_ALREADY_TRACING: Final = -2017128432 +UTC_E_REACHED_MAX_ESCALATIONS: Final = -2017128431 +UTC_E_FORWARDER_PRODUCER_MISMATCH: Final = -2017128430 +UTC_E_INTENTIONAL_SCRIPT_FAILURE: Final = -2017128429 +UTC_E_SQM_INIT_FAILED: Final = -2017128428 +UTC_E_NO_WER_LOGGER_SUPPORTED: Final = -2017128427 +UTC_E_TRACERS_DONT_EXIST: Final = -2017128426 +UTC_E_WINRT_INIT_FAILED: Final = -2017128425 +UTC_E_SCENARIODEF_SCHEMAVERSION_MISMATCH: Final = -2017128424 +UTC_E_INVALID_FILTER: Final = -2017128423 +UTC_E_EXE_TERMINATED: Final = -2017128422 +UTC_E_ESCALATION_NOT_AUTHORIZED: Final = -2017128421 +UTC_E_SETUP_NOT_AUTHORIZED: Final = -2017128420 +UTC_E_CHILD_PROCESS_FAILED: Final = -2017128419 +UTC_E_COMMAND_LINE_NOT_AUTHORIZED: Final = -2017128418 +UTC_E_CANNOT_LOAD_SCENARIO_EDITOR_XML: Final = -2017128417 +UTC_E_ESCALATION_TIMED_OUT: Final = -2017128416 +UTC_E_SETUP_TIMED_OUT: Final = -2017128415 +UTC_E_TRIGGER_MISMATCH: Final = -2017128414 +UTC_E_TRIGGER_NOT_FOUND: Final = -2017128413 +UTC_E_SIF_NOT_SUPPORTED: Final = -2017128412 +UTC_E_DELAY_TERMINATED: Final = -2017128411 +UTC_E_DEVICE_TICKET_ERROR: Final = -2017128410 +UTC_E_TRACE_BUFFER_LIMIT_EXCEEDED: Final = -2017128409 +UTC_E_API_RESULT_UNAVAILABLE: Final = -2017128408 +UTC_E_RPC_TIMEOUT: Final = -2017128407 +UTC_E_RPC_WAIT_FAILED: Final = -2017128406 +UTC_E_API_BUSY: Final = -2017128405 +UTC_E_TRACE_MIN_DURATION_REQUIREMENT_NOT_MET: Final = -2017128404 +UTC_E_EXCLUSIVITY_NOT_AVAILABLE: Final = -2017128403 +UTC_E_GETFILE_FILE_PATH_NOT_APPROVED: Final = -2017128402 +UTC_E_ESCALATION_DIRECTORY_ALREADY_EXISTS: Final = -2017128401 +UTC_E_TIME_TRIGGER_ON_START_INVALID: Final = -2017128400 +UTC_E_TIME_TRIGGER_ONLY_VALID_ON_SINGLE_TRANSITION: Final = -2017128399 +UTC_E_TIME_TRIGGER_INVALID_TIME_RANGE: Final = -2017128398 +UTC_E_MULTIPLE_TIME_TRIGGER_ON_SINGLE_STATE: Final = -2017128397 +UTC_E_BINARY_MISSING: Final = -2017128396 +UTC_E_FAILED_TO_RESOLVE_CONTAINER_ID: Final = -2017128394 +UTC_E_UNABLE_TO_RESOLVE_SESSION: Final = -2017128393 +UTC_E_THROTTLED: Final = -2017128392 +UTC_E_UNAPPROVED_SCRIPT: Final = -2017128391 +UTC_E_SCRIPT_MISSING: Final = -2017128390 +UTC_E_SCENARIO_THROTTLED: Final = -2017128389 +UTC_E_API_NOT_SUPPORTED: Final = -2017128388 +UTC_E_GETFILE_EXTERNAL_PATH_NOT_APPROVED: Final = -2017128387 +UTC_E_TRY_GET_SCENARIO_TIMEOUT_EXCEEDED: Final = -2017128386 +UTC_E_CERT_REV_FAILED: Final = -2017128385 +UTC_E_FAILED_TO_START_NDISCAP: Final = -2017128384 +UTC_E_KERNELDUMP_LIMIT_REACHED: Final = -2017128383 +UTC_E_MISSING_AGGREGATE_EVENT_TAG: Final = -2017128382 +UTC_E_INVALID_AGGREGATION_STRUCT: Final = -2017128381 +UTC_E_ACTION_NOT_SUPPORTED_IN_DESTINATION: Final = -2017128380 +UTC_E_FILTER_MISSING_ATTRIBUTE: Final = -2017128379 +UTC_E_FILTER_INVALID_TYPE: Final = -2017128378 +UTC_E_FILTER_VARIABLE_NOT_FOUND: Final = -2017128377 +UTC_E_FILTER_FUNCTION_RESTRICTED: Final = -2017128376 +UTC_E_FILTER_VERSION_MISMATCH: Final = -2017128375 +UTC_E_FILTER_INVALID_FUNCTION: Final = -2017128368 +UTC_E_FILTER_INVALID_FUNCTION_PARAMS: Final = -2017128367 +UTC_E_FILTER_INVALID_COMMAND: Final = -2017128366 +UTC_E_FILTER_ILLEGAL_EVAL: Final = -2017128365 +UTC_E_TTTRACER_RETURNED_ERROR: Final = -2017128364 +UTC_E_AGENT_DIAGNOSTICS_TOO_LARGE: Final = -2017128363 +UTC_E_FAILED_TO_RECEIVE_AGENT_DIAGNOSTICS: Final = -2017128362 +UTC_E_SCENARIO_HAS_NO_ACTIONS: Final = -2017128361 +UTC_E_TTTRACER_STORAGE_FULL: Final = -2017128360 +UTC_E_INSUFFICIENT_SPACE_TO_START_TRACE: Final = -2017128359 +UTC_E_ESCALATION_CANCELLED_AT_SHUTDOWN: Final = -2017128358 +UTC_E_GETFILEINFOACTION_FILE_NOT_APPROVED: Final = -2017128357 +UTC_E_SETREGKEYACTION_TYPE_NOT_APPROVED: Final = -2017128356 +UTC_E_TRACE_THROTTLED: Final = -2017128355 +WINML_ERR_INVALID_DEVICE: Final = -2003828735 +WINML_ERR_INVALID_BINDING: Final = -2003828734 +WINML_ERR_VALUE_NOTFOUND: Final = -2003828733 +WINML_ERR_SIZE_MISMATCH: Final = -2003828732 +ERROR_QUIC_HANDSHAKE_FAILURE: Final = -2143223808 +ERROR_QUIC_VER_NEG_FAILURE: Final = -2143223807 +ERROR_QUIC_USER_CANCELED: Final = -2143223806 +ERROR_QUIC_INTERNAL_ERROR: Final = -2143223805 +ERROR_QUIC_PROTOCOL_VIOLATION: Final = -2143223804 +ERROR_QUIC_CONNECTION_IDLE: Final = -2143223803 +ERROR_QUIC_CONNECTION_TIMEOUT: Final = -2143223802 +ERROR_QUIC_ALPN_NEG_FAILURE: Final = -2143223801 +IORING_E_REQUIRED_FLAG_NOT_SUPPORTED: Final = -2142896127 +IORING_E_SUBMISSION_QUEUE_FULL: Final = -2142896126 +IORING_E_VERSION_NOT_SUPPORTED: Final = -2142896125 +IORING_E_SUBMISSION_QUEUE_TOO_BIG: Final = -2142896124 +IORING_E_COMPLETION_QUEUE_TOO_BIG: Final = -2142896123 +IORING_E_SUBMIT_IN_PROGRESS: Final = -2142896122 +IORING_E_CORRUPT: Final = -2142896121 +IORING_E_COMPLETION_QUEUE_TOO_FULL: Final = -2142896120 + +CDERR_DIALOGFAILURE: Final = 0xFFFF +CDERR_GENERALCODES: Final = 0x0000 +CDERR_STRUCTSIZE: Final = 0x0001 +CDERR_INITIALIZATION: Final = 0x0002 +CDERR_NOTEMPLATE: Final = 0x0003 +CDERR_NOHINSTANCE: Final = 0x0004 +CDERR_LOADSTRFAILURE: Final = 0x0005 +CDERR_FINDRESFAILURE: Final = 0x0006 +CDERR_LOADRESFAILURE: Final = 0x0007 +CDERR_LOCKRESFAILURE: Final = 0x0008 +CDERR_MEMALLOCFAILURE: Final = 0x0009 +CDERR_MEMLOCKFAILURE: Final = 0x000A +CDERR_NOHOOK: Final = 0x000B +CDERR_REGISTERMSGFAIL: Final = 0x000C +PDERR_PRINTERCODES: Final = 0x1000 +PDERR_SETUPFAILURE: Final = 0x1001 +PDERR_PARSEFAILURE: Final = 0x1002 +PDERR_RETDEFFAILURE: Final = 0x1003 +PDERR_LOADDRVFAILURE: Final = 0x1004 +PDERR_GETDEVMODEFAIL: Final = 0x1005 +PDERR_INITFAILURE: Final = 0x1006 +PDERR_NODEVICES: Final = 0x1007 +PDERR_NODEFAULTPRN: Final = 0x1008 +PDERR_DNDMMISMATCH: Final = 0x1009 +PDERR_CREATEICFAILURE: Final = 0x100A +PDERR_PRINTERNOTFOUND: Final = 0x100B +PDERR_DEFAULTDIFFERENT: Final = 0x100C +CFERR_CHOOSEFONTCODES: Final = 0x2000 +CFERR_NOFONTS: Final = 0x2001 +CFERR_MAXLESSTHANMIN: Final = 0x2002 +FNERR_FILENAMECODES: Final = 0x3000 +FNERR_SUBCLASSFAILURE: Final = 0x3001 +FNERR_INVALIDFILENAME: Final = 0x3002 +FNERR_BUFFERTOOSMALL: Final = 0x3003 +FRERR_FINDREPLACECODES: Final = 0x4000 +FRERR_BUFFERLENGTHZERO: Final = 0x4001 +CCERR_CHOOSECOLORCODES: Final = 0x5000 diff --git a/stubs/pywin32/win32/lib/winioctlcon.pyi b/stubs/pywin32/win32/lib/winioctlcon.pyi new file mode 100644 index 000000000000..49028ceb8a9b --- /dev/null +++ b/stubs/pywin32/win32/lib/winioctlcon.pyi @@ -0,0 +1,661 @@ +import _win32typing + +def CTL_CODE(DeviceType: int, Function: int, Method: int, Access: int) -> int: ... +def DEVICE_TYPE_FROM_CTL_CODE(ctrlCode: int) -> int: ... + +FILE_DEVICE_BEEP: int +FILE_DEVICE_CD_ROM: int +FILE_DEVICE_CD_ROM_FILE_SYSTEM: int +FILE_DEVICE_CONTROLLER: int +FILE_DEVICE_DATALINK: int +FILE_DEVICE_DFS: int +FILE_DEVICE_DISK: int +FILE_DEVICE_DISK_FILE_SYSTEM: int +FILE_DEVICE_FILE_SYSTEM: int +FILE_DEVICE_INPORT_PORT: int +FILE_DEVICE_KEYBOARD: int +FILE_DEVICE_MAILSLOT: int +FILE_DEVICE_MIDI_IN: int +FILE_DEVICE_MIDI_OUT: int +FILE_DEVICE_MOUSE: int +FILE_DEVICE_MULTI_UNC_PROVIDER: int +FILE_DEVICE_NAMED_PIPE: int +FILE_DEVICE_NETWORK: int +FILE_DEVICE_NETWORK_BROWSER: int +FILE_DEVICE_NETWORK_FILE_SYSTEM: int +FILE_DEVICE_NULL: int +FILE_DEVICE_PARALLEL_PORT: int +FILE_DEVICE_PHYSICAL_NETCARD: int +FILE_DEVICE_PRINTER: int +FILE_DEVICE_SCANNER: int +FILE_DEVICE_SERIAL_MOUSE_PORT: int +FILE_DEVICE_SERIAL_PORT: int +FILE_DEVICE_SCREEN: int +FILE_DEVICE_SOUND: int +FILE_DEVICE_STREAMS: int +FILE_DEVICE_TAPE: int +FILE_DEVICE_TAPE_FILE_SYSTEM: int +FILE_DEVICE_TRANSPORT: int +FILE_DEVICE_UNKNOWN: int +FILE_DEVICE_VIDEO: int +FILE_DEVICE_VIRTUAL_DISK: int +FILE_DEVICE_WAVE_IN: int +FILE_DEVICE_WAVE_OUT: int +FILE_DEVICE_8042_PORT: int +FILE_DEVICE_NETWORK_REDIRECTOR: int +FILE_DEVICE_BATTERY: int +FILE_DEVICE_BUS_EXTENDER: int +FILE_DEVICE_MODEM: int +FILE_DEVICE_VDM: int +FILE_DEVICE_MASS_STORAGE: int +FILE_DEVICE_SMB: int +FILE_DEVICE_KS: int +FILE_DEVICE_CHANGER: int +FILE_DEVICE_SMARTCARD: int +FILE_DEVICE_ACPI: int +FILE_DEVICE_DVD: int +FILE_DEVICE_FULLSCREEN_VIDEO: int +FILE_DEVICE_DFS_FILE_SYSTEM: int +FILE_DEVICE_DFS_VOLUME: int +FILE_DEVICE_SERENUM: int +FILE_DEVICE_TERMSRV: int +FILE_DEVICE_KSEC: int +FILE_DEVICE_FIPS: int +FILE_DEVICE_INFINIBAND: int +METHOD_BUFFERED: int +METHOD_IN_DIRECT: int +METHOD_OUT_DIRECT: int +METHOD_NEITHER: int +METHOD_DIRECT_TO_HARDWARE: int +METHOD_DIRECT_FROM_HARDWARE: int +FILE_ANY_ACCESS: int +FILE_SPECIAL_ACCESS: int +FILE_READ_ACCESS: int +FILE_WRITE_ACCESS: int +IOCTL_STORAGE_BASE: int +RECOVERED_WRITES_VALID: int +UNRECOVERED_WRITES_VALID: int +RECOVERED_READS_VALID: int +UNRECOVERED_READS_VALID: int +WRITE_COMPRESSION_INFO_VALID: int +READ_COMPRESSION_INFO_VALID: int +TAPE_RETURN_STATISTICS: int +TAPE_RETURN_ENV_INFO: int +TAPE_RESET_STATISTICS: int +MEDIA_ERASEABLE: int +MEDIA_WRITE_ONCE: int +MEDIA_READ_ONLY: int +MEDIA_READ_WRITE: int +MEDIA_WRITE_PROTECTED: int +MEDIA_CURRENTLY_MOUNTED: int +IOCTL_DISK_BASE: int +PARTITION_ENTRY_UNUSED: int +PARTITION_FAT_12: int +PARTITION_XENIX_1: int +PARTITION_XENIX_2: int +PARTITION_FAT_16: int +PARTITION_EXTENDED: int +PARTITION_HUGE: int +PARTITION_IFS: int +PARTITION_OS2BOOTMGR: int +PARTITION_FAT32: int +PARTITION_FAT32_XINT13: int +PARTITION_XINT13: int +PARTITION_XINT13_EXTENDED: int +PARTITION_PREP: int +PARTITION_LDM: int +PARTITION_UNIX: int +VALID_NTFT: int +PARTITION_NTFT: int +GPT_ATTRIBUTE_PLATFORM_REQUIRED: int +GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER: int +GPT_BASIC_DATA_ATTRIBUTE_HIDDEN: int +GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY: int +GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY: int +HIST_NO_OF_BUCKETS: int +DISK_LOGGING_START: int +DISK_LOGGING_STOP: int +DISK_LOGGING_DUMP: int +DISK_BINNING: int +CAP_ATA_ID_CMD: int +CAP_ATAPI_ID_CMD: int +CAP_SMART_CMD: int +ATAPI_ID_CMD: int +ID_CMD: int +SMART_CMD: int +SMART_CYL_LOW: int +SMART_CYL_HI: int +SMART_NO_ERROR: int +SMART_IDE_ERROR: int +SMART_INVALID_FLAG: int +SMART_INVALID_COMMAND: int +SMART_INVALID_BUFFER: int +SMART_INVALID_DRIVE: int +SMART_INVALID_IOCTL: int +SMART_ERROR_NO_MEM: int +SMART_INVALID_REGISTER: int +SMART_NOT_SUPPORTED: int +SMART_NO_IDE_DEVICE: int +SMART_OFFLINE_ROUTINE_OFFLINE: int +SMART_SHORT_SELFTEST_OFFLINE: int +SMART_EXTENDED_SELFTEST_OFFLINE: int +SMART_ABORT_OFFLINE_SELFTEST: int +SMART_SHORT_SELFTEST_CAPTIVE: int +SMART_EXTENDED_SELFTEST_CAPTIVE: int +READ_ATTRIBUTE_BUFFER_SIZE: int +IDENTIFY_BUFFER_SIZE: int +READ_THRESHOLD_BUFFER_SIZE: int +SMART_LOG_SECTOR_SIZE: int +READ_ATTRIBUTES: int +READ_THRESHOLDS: int +ENABLE_DISABLE_AUTOSAVE: int +SAVE_ATTRIBUTE_VALUES: int +EXECUTE_OFFLINE_DIAGS: int +SMART_READ_LOG: int +SMART_WRITE_LOG: int +ENABLE_SMART: int +DISABLE_SMART: int +RETURN_SMART_STATUS: int +ENABLE_DISABLE_AUTO_OFFLINE: int +IOCTL_CHANGER_BASE: int +MAX_VOLUME_ID_SIZE: int +MAX_VOLUME_TEMPLATE_SIZE: int +VENDOR_ID_LENGTH: int +PRODUCT_ID_LENGTH: int +REVISION_LENGTH: int +SERIAL_NUMBER_LENGTH: int +CHANGER_BAR_CODE_SCANNER_INSTALLED: int +CHANGER_INIT_ELEM_STAT_WITH_RANGE: int +CHANGER_CLOSE_IEPORT: int +CHANGER_OPEN_IEPORT: int +CHANGER_STATUS_NON_VOLATILE: int +CHANGER_EXCHANGE_MEDIA: int +CHANGER_CLEANER_SLOT: int +CHANGER_LOCK_UNLOCK: int +CHANGER_CARTRIDGE_MAGAZINE: int +CHANGER_MEDIUM_FLIP: int +CHANGER_POSITION_TO_ELEMENT: int +CHANGER_REPORT_IEPORT_STATE: int +CHANGER_STORAGE_DRIVE: int +CHANGER_STORAGE_IEPORT: int +CHANGER_STORAGE_SLOT: int +CHANGER_STORAGE_TRANSPORT: int +CHANGER_DRIVE_CLEANING_REQUIRED: int +CHANGER_PREDISMOUNT_EJECT_REQUIRED: int +CHANGER_CLEANER_ACCESS_NOT_VALID: int +CHANGER_PREMOUNT_EJECT_REQUIRED: int +CHANGER_VOLUME_IDENTIFICATION: int +CHANGER_VOLUME_SEARCH: int +CHANGER_VOLUME_ASSERT: int +CHANGER_VOLUME_REPLACE: int +CHANGER_VOLUME_UNDEFINE: int +CHANGER_SERIAL_NUMBER_VALID: int +CHANGER_DEVICE_REINITIALIZE_CAPABLE: int +CHANGER_KEYPAD_ENABLE_DISABLE: int +CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS: int +CHANGER_RESERVED_BIT: int +CHANGER_PREDISMOUNT_ALIGN_TO_SLOT: int +CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE: int +CHANGER_CLEANER_AUTODISMOUNT: int +CHANGER_TRUE_EXCHANGE_CAPABLE: int +CHANGER_SLOTS_USE_TRAYS: int +CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR: int +CHANGER_CLEANER_OPS_NOT_SUPPORTED: int +CHANGER_IEPORT_USER_CONTROL_OPEN: int +CHANGER_IEPORT_USER_CONTROL_CLOSE: int +CHANGER_MOVE_EXTENDS_IEPORT: int +CHANGER_MOVE_RETRACTS_IEPORT: int +CHANGER_TO_TRANSPORT: int +CHANGER_TO_SLOT: int +CHANGER_TO_IEPORT: int +CHANGER_TO_DRIVE: int +LOCK_UNLOCK_IEPORT: int +LOCK_UNLOCK_DOOR: int +LOCK_UNLOCK_KEYPAD: int +LOCK_ELEMENT: int +UNLOCK_ELEMENT: int +EXTEND_IEPORT: int +RETRACT_IEPORT: int +ELEMENT_STATUS_FULL: int +ELEMENT_STATUS_IMPEXP: int +ELEMENT_STATUS_EXCEPT: int +ELEMENT_STATUS_ACCESS: int +ELEMENT_STATUS_EXENAB: int +ELEMENT_STATUS_INENAB: int +ELEMENT_STATUS_PRODUCT_DATA: int +ELEMENT_STATUS_LUN_VALID: int +ELEMENT_STATUS_ID_VALID: int +ELEMENT_STATUS_NOT_BUS: int +ELEMENT_STATUS_INVERT: int +ELEMENT_STATUS_SVALID: int +ELEMENT_STATUS_PVOLTAG: int +ELEMENT_STATUS_AVOLTAG: int +ERROR_LABEL_UNREADABLE: int +ERROR_LABEL_QUESTIONABLE: int +ERROR_SLOT_NOT_PRESENT: int +ERROR_DRIVE_NOT_INSTALLED: int +ERROR_TRAY_MALFUNCTION: int +ERROR_INIT_STATUS_NEEDED: int +ERROR_UNHANDLED_ERROR: int +SEARCH_ALL: int +SEARCH_PRIMARY: int +SEARCH_ALTERNATE: int +SEARCH_ALL_NO_SEQ: int +SEARCH_PRI_NO_SEQ: int +SEARCH_ALT_NO_SEQ: int +ASSERT_PRIMARY: int +ASSERT_ALTERNATE: int +REPLACE_PRIMARY: int +REPLACE_ALTERNATE: int +UNDEFINE_PRIMARY: int +UNDEFINE_ALTERNATE: int +USN_PAGE_SIZE: int +USN_REASON_DATA_OVERWRITE: int +USN_REASON_DATA_EXTEND: int +USN_REASON_DATA_TRUNCATION: int +USN_REASON_NAMED_DATA_OVERWRITE: int +USN_REASON_NAMED_DATA_EXTEND: int +USN_REASON_NAMED_DATA_TRUNCATION: int +USN_REASON_FILE_CREATE: int +USN_REASON_FILE_DELETE: int +USN_REASON_EA_CHANGE: int +USN_REASON_SECURITY_CHANGE: int +USN_REASON_RENAME_OLD_NAME: int +USN_REASON_RENAME_NEW_NAME: int +USN_REASON_INDEXABLE_CHANGE: int +USN_REASON_BASIC_INFO_CHANGE: int +USN_REASON_HARD_LINK_CHANGE: int +USN_REASON_COMPRESSION_CHANGE: int +USN_REASON_ENCRYPTION_CHANGE: int +USN_REASON_OBJECT_ID_CHANGE: int +USN_REASON_REPARSE_POINT_CHANGE: int +USN_REASON_STREAM_CHANGE: int +USN_REASON_TRANSACTED_CHANGE: int +USN_REASON_CLOSE: int +USN_DELETE_FLAG_DELETE: int +USN_DELETE_FLAG_NOTIFY: int +USN_DELETE_VALID_FLAGS: int +USN_SOURCE_DATA_MANAGEMENT: int +USN_SOURCE_AUXILIARY_DATA: int +USN_SOURCE_REPLICATION_MANAGEMENT: int +MARK_HANDLE_PROTECT_CLUSTERS: int +MARK_HANDLE_TXF_SYSTEM_LOG: int +MARK_HANDLE_NOT_TXF_SYSTEM_LOG: int +VOLUME_IS_DIRTY: int +VOLUME_UPGRADE_SCHEDULED: int +VOLUME_SESSION_OPEN: int +FILE_PREFETCH_TYPE_FOR_CREATE: int +FILE_PREFETCH_TYPE_FOR_DIRENUM: int +FILE_PREFETCH_TYPE_FOR_CREATE_EX: int +FILE_PREFETCH_TYPE_FOR_DIRENUM_EX: int +FILE_PREFETCH_TYPE_MAX: int +FILESYSTEM_STATISTICS_TYPE_NTFS: int +FILESYSTEM_STATISTICS_TYPE_FAT: int +FILE_SET_ENCRYPTION: int +FILE_CLEAR_ENCRYPTION: int +STREAM_SET_ENCRYPTION: int +STREAM_CLEAR_ENCRYPTION: int +MAXIMUM_ENCRYPTION_VALUE: int +ENCRYPTION_FORMAT_DEFAULT: int +COMPRESSION_FORMAT_SPARSE: int +COPYFILE_SIS_LINK: int +COPYFILE_SIS_REPLACE: int +COPYFILE_SIS_FLAGS: int +WMI_DISK_GEOMETRY_GUID: _win32typing.PyIID +GUID_DEVINTERFACE_CDROM: _win32typing.PyIID +GUID_DEVINTERFACE_FLOPPY: _win32typing.PyIID +GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR: _win32typing.PyIID +GUID_DEVINTERFACE_COMPORT: _win32typing.PyIID +GUID_DEVINTERFACE_DISK: _win32typing.PyIID +GUID_DEVINTERFACE_STORAGEPORT: _win32typing.PyIID +GUID_DEVINTERFACE_CDCHANGER: _win32typing.PyIID +GUID_DEVINTERFACE_PARTITION: _win32typing.PyIID +GUID_DEVINTERFACE_VOLUME: _win32typing.PyIID +GUID_DEVINTERFACE_WRITEONCEDISK: _win32typing.PyIID +GUID_DEVINTERFACE_TAPE: _win32typing.PyIID +GUID_DEVINTERFACE_MEDIUMCHANGER: _win32typing.PyIID +GUID_SERENUM_BUS_ENUMERATOR: int +GUID_CLASS_COMPORT: int +DiskClassGuid: int +CdRomClassGuid: int +PartitionClassGuid: int +TapeClassGuid: int +WriteOnceDiskClassGuid: int +VolumeClassGuid: int +MediumChangerClassGuid: int +FloppyClassGuid: int +CdChangerClassGuid: int +StoragePortClassGuid: int +IOCTL_STORAGE_CHECK_VERIFY: int +IOCTL_STORAGE_CHECK_VERIFY2: int +IOCTL_STORAGE_MEDIA_REMOVAL: int +IOCTL_STORAGE_EJECT_MEDIA: int +IOCTL_STORAGE_LOAD_MEDIA: int +IOCTL_STORAGE_LOAD_MEDIA2: int +IOCTL_STORAGE_RESERVE: int +IOCTL_STORAGE_RELEASE: int +IOCTL_STORAGE_FIND_NEW_DEVICES: int +IOCTL_STORAGE_EJECTION_CONTROL: int +IOCTL_STORAGE_MCN_CONTROL: int +IOCTL_STORAGE_GET_MEDIA_TYPES: int +IOCTL_STORAGE_GET_MEDIA_TYPES_EX: int +IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER: int +IOCTL_STORAGE_GET_HOTPLUG_INFO: int +IOCTL_STORAGE_SET_HOTPLUG_INFO: int +IOCTL_STORAGE_RESET_BUS: int +IOCTL_STORAGE_RESET_DEVICE: int +IOCTL_STORAGE_BREAK_RESERVATION: int +IOCTL_STORAGE_GET_DEVICE_NUMBER: int +IOCTL_STORAGE_PREDICT_FAILURE: int +IOCTL_DISK_GET_DRIVE_GEOMETRY: int +IOCTL_DISK_GET_PARTITION_INFO: int +IOCTL_DISK_SET_PARTITION_INFO: int +IOCTL_DISK_GET_DRIVE_LAYOUT: int +IOCTL_DISK_SET_DRIVE_LAYOUT: int +IOCTL_DISK_VERIFY: int +IOCTL_DISK_FORMAT_TRACKS: int +IOCTL_DISK_REASSIGN_BLOCKS: int +IOCTL_DISK_PERFORMANCE: int +IOCTL_DISK_IS_WRITABLE: int +IOCTL_DISK_LOGGING: int +IOCTL_DISK_FORMAT_TRACKS_EX: int +IOCTL_DISK_HISTOGRAM_STRUCTURE: int +IOCTL_DISK_HISTOGRAM_DATA: int +IOCTL_DISK_HISTOGRAM_RESET: int +IOCTL_DISK_REQUEST_STRUCTURE: int +IOCTL_DISK_REQUEST_DATA: int +IOCTL_DISK_PERFORMANCE_OFF: int +IOCTL_DISK_CONTROLLER_NUMBER: int +SMART_GET_VERSION: int +SMART_SEND_DRIVE_COMMAND: int +SMART_RCV_DRIVE_DATA: int +IOCTL_DISK_GET_PARTITION_INFO_EX: int +IOCTL_DISK_SET_PARTITION_INFO_EX: int +IOCTL_DISK_GET_DRIVE_LAYOUT_EX: int +IOCTL_DISK_SET_DRIVE_LAYOUT_EX: int +IOCTL_DISK_CREATE_DISK: int +IOCTL_DISK_GET_LENGTH_INFO: int +IOCTL_DISK_GET_DRIVE_GEOMETRY_EX: int +IOCTL_DISK_REASSIGN_BLOCKS_EX: int +IOCTL_DISK_UPDATE_DRIVE_SIZE: int +IOCTL_DISK_GROW_PARTITION: int +IOCTL_DISK_GET_CACHE_INFORMATION: int +IOCTL_DISK_SET_CACHE_INFORMATION: int +OBSOLETE_IOCTL_STORAGE_RESET_BUS: int +OBSOLETE_IOCTL_STORAGE_RESET_DEVICE: int +OBSOLETE_DISK_GET_WRITE_CACHE_STATE: int +IOCTL_DISK_GET_WRITE_CACHE_STATE: int +IOCTL_DISK_DELETE_DRIVE_LAYOUT: int +IOCTL_DISK_UPDATE_PROPERTIES: int +IOCTL_DISK_FORMAT_DRIVE: int +IOCTL_DISK_SENSE_DEVICE: int +IOCTL_DISK_CHECK_VERIFY: int +IOCTL_DISK_MEDIA_REMOVAL: int +IOCTL_DISK_EJECT_MEDIA: int +IOCTL_DISK_LOAD_MEDIA: int +IOCTL_DISK_RESERVE: int +IOCTL_DISK_RELEASE: int +IOCTL_DISK_FIND_NEW_DEVICES: int +IOCTL_DISK_GET_MEDIA_TYPES: int +DISK_HISTOGRAM_SIZE: int +HISTOGRAM_BUCKET_SIZE: int +IOCTL_CHANGER_GET_PARAMETERS: int +IOCTL_CHANGER_GET_STATUS: int +IOCTL_CHANGER_GET_PRODUCT_DATA: int +IOCTL_CHANGER_SET_ACCESS: int +IOCTL_CHANGER_GET_ELEMENT_STATUS: int +IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS: int +IOCTL_CHANGER_SET_POSITION: int +IOCTL_CHANGER_EXCHANGE_MEDIUM: int +IOCTL_CHANGER_MOVE_MEDIUM: int +IOCTL_CHANGER_REINITIALIZE_TRANSPORT: int +IOCTL_CHANGER_QUERY_VOLUME_TAGS: int +IOCTL_SERIAL_LSRMST_INSERT: int +IOCTL_SERENUM_EXPOSE_HARDWARE: int +IOCTL_SERENUM_REMOVE_HARDWARE: int +IOCTL_SERENUM_PORT_DESC: int +IOCTL_SERENUM_GET_PORT_NAME: int +SERIAL_LSRMST_ESCAPE: int +SERIAL_LSRMST_LSR_DATA: int +SERIAL_LSRMST_LSR_NODATA: int +SERIAL_LSRMST_MST: int +SERIAL_IOC_FCR_FIFO_ENABLE: int +SERIAL_IOC_FCR_RCVR_RESET: int +SERIAL_IOC_FCR_XMIT_RESET: int +SERIAL_IOC_FCR_DMA_MODE: int +SERIAL_IOC_FCR_RES1: int +SERIAL_IOC_FCR_RES2: int +SERIAL_IOC_FCR_RCVR_TRIGGER_LSB: int +SERIAL_IOC_FCR_RCVR_TRIGGER_MSB: int +SERIAL_IOC_MCR_DTR: int +SERIAL_IOC_MCR_RTS: int +SERIAL_IOC_MCR_OUT1: int +SERIAL_IOC_MCR_OUT2: int +SERIAL_IOC_MCR_LOOP: int +FSCTL_REQUEST_OPLOCK_LEVEL_1: int +FSCTL_REQUEST_OPLOCK_LEVEL_2: int +FSCTL_REQUEST_BATCH_OPLOCK: int +FSCTL_OPLOCK_BREAK_ACKNOWLEDGE: int +FSCTL_OPBATCH_ACK_CLOSE_PENDING: int +FSCTL_OPLOCK_BREAK_NOTIFY: int +FSCTL_LOCK_VOLUME: int +FSCTL_UNLOCK_VOLUME: int +FSCTL_DISMOUNT_VOLUME: int +FSCTL_IS_VOLUME_MOUNTED: int +FSCTL_IS_PATHNAME_VALID: int +FSCTL_MARK_VOLUME_DIRTY: int +FSCTL_QUERY_RETRIEVAL_POINTERS: int +FSCTL_GET_COMPRESSION: int +FSCTL_SET_COMPRESSION: int +FSCTL_MARK_AS_SYSTEM_HIVE: int +FSCTL_OPLOCK_BREAK_ACK_NO_2: int +FSCTL_INVALIDATE_VOLUMES: int +FSCTL_QUERY_FAT_BPB: int +FSCTL_REQUEST_FILTER_OPLOCK: int +FSCTL_FILESYSTEM_GET_STATISTICS: int +FSCTL_GET_NTFS_VOLUME_DATA: int +FSCTL_GET_NTFS_FILE_RECORD: int +FSCTL_GET_VOLUME_BITMAP: int +FSCTL_GET_RETRIEVAL_POINTERS: int +FSCTL_MOVE_FILE: int +FSCTL_IS_VOLUME_DIRTY: int +FSCTL_ALLOW_EXTENDED_DASD_IO: int +FSCTL_FIND_FILES_BY_SID: int +FSCTL_SET_OBJECT_ID: int +FSCTL_GET_OBJECT_ID: int +FSCTL_DELETE_OBJECT_ID: int +FSCTL_SET_REPARSE_POINT: int +FSCTL_GET_REPARSE_POINT: int +FSCTL_DELETE_REPARSE_POINT: int +FSCTL_ENUM_USN_DATA: int +FSCTL_SECURITY_ID_CHECK: int +FSCTL_READ_USN_JOURNAL: int +FSCTL_SET_OBJECT_ID_EXTENDED: int +FSCTL_CREATE_OR_GET_OBJECT_ID: int +FSCTL_SET_SPARSE: int +FSCTL_SET_ZERO_DATA: int +FSCTL_QUERY_ALLOCATED_RANGES: int +FSCTL_SET_ENCRYPTION: int +FSCTL_ENCRYPTION_FSCTL_IO: int +FSCTL_WRITE_RAW_ENCRYPTED: int +FSCTL_READ_RAW_ENCRYPTED: int +FSCTL_CREATE_USN_JOURNAL: int +FSCTL_READ_FILE_USN_DATA: int +FSCTL_WRITE_USN_CLOSE_RECORD: int +FSCTL_EXTEND_VOLUME: int +FSCTL_QUERY_USN_JOURNAL: int +FSCTL_DELETE_USN_JOURNAL: int +FSCTL_MARK_HANDLE: int +FSCTL_SIS_COPYFILE: int +FSCTL_SIS_LINK_FILES: int +FSCTL_HSM_MSG: int +FSCTL_HSM_DATA: int +FSCTL_RECALL_FILE: int +FSCTL_READ_FROM_PLEX: int +FSCTL_FILE_PREFETCH: int +FSCTL_MAKE_MEDIA_COMPATIBLE: int +FSCTL_SET_DEFECT_MANAGEMENT: int +FSCTL_QUERY_SPARING_INFO: int +FSCTL_QUERY_ON_DISK_VOLUME_INFO: int +FSCTL_SET_VOLUME_COMPRESSION_STATE: int +FSCTL_TXFS_MODIFY_RM: int +FSCTL_TXFS_QUERY_RM_INFORMATION: int +FSCTL_TXFS_ROLLFORWARD_REDO: int +FSCTL_TXFS_ROLLFORWARD_UNDO: int +FSCTL_TXFS_START_RM: int +FSCTL_TXFS_SHUTDOWN_RM: int +FSCTL_TXFS_READ_BACKUP_INFORMATION: int +FSCTL_TXFS_WRITE_BACKUP_INFORMATION: int +FSCTL_TXFS_CREATE_SECONDARY_RM: int +FSCTL_TXFS_GET_METADATA_INFO: int +FSCTL_TXFS_GET_TRANSACTED_VERSION: int +FSCTL_TXFS_CREATE_MINIVERSION: int +FSCTL_TXFS_TRANSACTION_ACTIVE: int +FSCTL_SET_ZERO_ON_DEALLOCATION: int +FSCTL_SET_REPAIR: int +FSCTL_GET_REPAIR: int +FSCTL_WAIT_FOR_REPAIR: int +FSCTL_INITIATE_REPAIR: int +FSCTL_CSC_INTERNAL: int +FSCTL_SHRINK_VOLUME: int +FSCTL_SET_SHORT_NAME_BEHAVIOR: int +FSCTL_DFSR_SET_GHOST_HANDLE_STATE: int +FSCTL_QUERY_PAGEFILE_ENCRYPTION: int +IOCTL_VOLUME_BASE: int +IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS: int +IOCTL_VOLUME_ONLINE: int +IOCTL_VOLUME_OFFLINE: int +IOCTL_VOLUME_IS_CLUSTERED: int +IOCTL_VOLUME_GET_GPT_ATTRIBUTES: int +DDS_4mm: int +MiniQic: int +Travan: int +QIC: int +MP_8mm: int +AME_8mm: int +AIT1_8mm: int +DLT: int +NCTP: int +IBM_3480: int +IBM_3490E: int +IBM_Magstar_3590: int +IBM_Magstar_MP: int +STK_DATA_D3: int +SONY_DTF: int +DV_6mm: int +DMI: int +SONY_D2: int +CLEANER_CARTRIDGE: int +CD_ROM: int +CD_R: int +CD_RW: int +DVD_ROM: int +DVD_R: int +DVD_RW: int +MO_3_RW: int +MO_5_WO: int +MO_5_RW: int +MO_5_LIMDOW: int +PC_5_WO: int +PC_5_RW: int +PD_5_RW: int +ABL_5_WO: int +PINNACLE_APEX_5_RW: int +SONY_12_WO: int +PHILIPS_12_WO: int +HITACHI_12_WO: int +CYGNET_12_WO: int +KODAK_14_WO: int +MO_NFR_525: int +NIKON_12_RW: int +IOMEGA_ZIP: int +IOMEGA_JAZ: int +SYQUEST_EZ135: int +SYQUEST_EZFLYER: int +SYQUEST_SYJET: int +AVATAR_F2: int +MP2_8mm: int +DST_S: int +DST_M: int +DST_L: int +VXATape_1: int +VXATape_2: int +STK_9840: int +LTO_Ultrium: int +LTO_Accelis: int +DVD_RAM: int +AIT_8mm: int +ADR_1: int +ADR_2: int +STK_9940: int +BusTypeUnknown: int +BusTypeScsi: int +BusTypeAtapi: int +BusTypeAta: int +BusType1394: int +BusTypeSsa: int +BusTypeFibre: int +BusTypeUsb: int +BusTypeRAID: int +BusTypeiScsi: int +BusTypeSas: int +BusTypeSata: int +BusTypeMaxReserved: int +Unknown: int +F5_1Pt2_512: int +F3_1Pt44_512: int +F3_2Pt88_512: int +F3_20Pt8_512: int +F3_720_512: int +F5_360_512: int +F5_320_512: int +F5_320_1024: int +F5_180_512: int +F5_160_512: int +RemovableMedia: int +FixedMedia: int +F3_120M_512: int +F3_640_512: int +F5_640_512: int +F5_720_512: int +F3_1Pt2_512: int +F3_1Pt23_1024: int +F5_1Pt23_1024: int +F3_128Mb_512: int +F3_230Mb_512: int +F8_256_128: int +F3_200Mb_512: int +F3_240M_512: int +F3_32M_512: int +PARTITION_STYLE_MBR: int +PARTITION_STYLE_GPT: int +PARTITION_STYLE_RAW: int +DetectNone: int +DetectInt13: int +DetectExInt13: int +EqualPriority: int +KeepPrefetchedData: int +KeepReadData: int +DiskWriteCacheNormal: int +DiskWriteCacheForceDisable: int +DiskWriteCacheDisableNotSupported: int +RequestSize: int +RequestLocation: int +DeviceProblemNone: int +DeviceProblemHardware: int +DeviceProblemCHMError: int +DeviceProblemDoorOpen: int +DeviceProblemCalibrationError: int +DeviceProblemTargetFailure: int +DeviceProblemCHMMoveError: int +DeviceProblemCHMZeroError: int +DeviceProblemCartridgeInsertError: int +DeviceProblemPositionError: int +DeviceProblemSensorError: int +DeviceProblemCartridgeEjectError: int +DeviceProblemGripperError: int +DeviceProblemDriveError: int +FILE_READ_DATA: int +FILE_WRITE_DATA: int +FSCTL_TXFS_LIST_TRANSACTIONS: int +FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES: int diff --git a/stubs/pywin32/win32/lib/winnt.pyi b/stubs/pywin32/win32/lib/winnt.pyi new file mode 100644 index 000000000000..f1ec8493ccc6 --- /dev/null +++ b/stubs/pywin32/win32/lib/winnt.pyi @@ -0,0 +1,1134 @@ +from _typeshed import Incomplete + +APPLICATION_ERROR_MASK: int +ERROR_SEVERITY_SUCCESS: int +ERROR_SEVERITY_INFORMATIONAL: int +ERROR_SEVERITY_WARNING: int +ERROR_SEVERITY_ERROR: int +MINCHAR: int +MAXCHAR: int +MINSHORT: int +MAXSHORT: int +MINLONG: int +MAXLONG: int +MAXBYTE: int +MAXWORD: int +MAXDWORD: int +LANG_NEUTRAL: int +LANG_AFRIKAANS: int +LANG_ALBANIAN: int +LANG_ARABIC: int +LANG_BASQUE: int +LANG_BELARUSIAN: int +LANG_BULGARIAN: int +LANG_CATALAN: int +LANG_CHINESE: int +LANG_CROATIAN: int +LANG_CZECH: int +LANG_DANISH: int +LANG_DUTCH: int +LANG_ENGLISH: int +LANG_ESTONIAN: int +LANG_FAEROESE: int +LANG_FARSI: int +LANG_FINNISH: int +LANG_FRENCH: int +LANG_GERMAN: int +LANG_GREEK: int +LANG_HEBREW: int +LANG_HINDI: int +LANG_HUNGARIAN: int +LANG_ICELANDIC: int +LANG_INDONESIAN: int +LANG_ITALIAN: int +LANG_JAPANESE: int +LANG_KOREAN: int +LANG_LATVIAN: int +LANG_LITHUANIAN: int +LANG_MACEDONIAN: int +LANG_MALAY: int +LANG_NORWEGIAN: int +LANG_POLISH: int +LANG_PORTUGUESE: int +LANG_ROMANIAN: int +LANG_RUSSIAN: int +LANG_SERBIAN: int +LANG_SLOVAK: int +LANG_SLOVENIAN: int +LANG_SPANISH: int +LANG_SWAHILI: int +LANG_SWEDISH: int +LANG_THAI: int +LANG_TURKISH: int +LANG_UKRAINIAN: int +LANG_VIETNAMESE: int +SUBLANG_NEUTRAL: int +SUBLANG_DEFAULT: int +SUBLANG_SYS_DEFAULT: int +SUBLANG_ARABIC_SAUDI_ARABIA: int +SUBLANG_ARABIC_IRAQ: int +SUBLANG_ARABIC_EGYPT: int +SUBLANG_ARABIC_LIBYA: int +SUBLANG_ARABIC_ALGERIA: int +SUBLANG_ARABIC_MOROCCO: int +SUBLANG_ARABIC_TUNISIA: int +SUBLANG_ARABIC_OMAN: int +SUBLANG_ARABIC_YEMEN: int +SUBLANG_ARABIC_SYRIA: int +SUBLANG_ARABIC_JORDAN: int +SUBLANG_ARABIC_LEBANON: int +SUBLANG_ARABIC_KUWAIT: int +SUBLANG_ARABIC_UAE: int +SUBLANG_ARABIC_BAHRAIN: int +SUBLANG_ARABIC_QATAR: int +SUBLANG_CHINESE_TRADITIONAL: int +SUBLANG_CHINESE_SIMPLIFIED: int +SUBLANG_CHINESE_HONGKONG: int +SUBLANG_CHINESE_SINGAPORE: int +SUBLANG_CHINESE_MACAU: int +SUBLANG_DUTCH: int +SUBLANG_DUTCH_BELGIAN: int +SUBLANG_ENGLISH_US: int +SUBLANG_ENGLISH_UK: int +SUBLANG_ENGLISH_AUS: int +SUBLANG_ENGLISH_CAN: int +SUBLANG_ENGLISH_NZ: int +SUBLANG_ENGLISH_EIRE: int +SUBLANG_ENGLISH_SOUTH_AFRICA: int +SUBLANG_ENGLISH_JAMAICA: int +SUBLANG_ENGLISH_CARIBBEAN: int +SUBLANG_ENGLISH_BELIZE: int +SUBLANG_ENGLISH_TRINIDAD: int +SUBLANG_ENGLISH_ZIMBABWE: int +SUBLANG_ENGLISH_PHILIPPINES: int +SUBLANG_FRENCH: int +SUBLANG_FRENCH_BELGIAN: int +SUBLANG_FRENCH_CANADIAN: int +SUBLANG_FRENCH_SWISS: int +SUBLANG_FRENCH_LUXEMBOURG: int +SUBLANG_FRENCH_MONACO: int +SUBLANG_GERMAN: int +SUBLANG_GERMAN_SWISS: int +SUBLANG_GERMAN_AUSTRIAN: int +SUBLANG_GERMAN_LUXEMBOURG: int +SUBLANG_GERMAN_LIECHTENSTEIN: int +SUBLANG_ITALIAN: int +SUBLANG_ITALIAN_SWISS: int +SUBLANG_KOREAN: int +SUBLANG_KOREAN_JOHAB: int +SUBLANG_LITHUANIAN: int +SUBLANG_LITHUANIAN_CLASSIC: int +SUBLANG_MALAY_MALAYSIA: int +SUBLANG_MALAY_BRUNEI_DARUSSALAM: int +SUBLANG_NORWEGIAN_BOKMAL: int +SUBLANG_NORWEGIAN_NYNORSK: int +SUBLANG_PORTUGUESE: int +SUBLANG_PORTUGUESE_BRAZILIAN: int +SUBLANG_SERBIAN_LATIN: int +SUBLANG_SERBIAN_CYRILLIC: int +SUBLANG_SPANISH: int +SUBLANG_SPANISH_MEXICAN: int +SUBLANG_SPANISH_MODERN: int +SUBLANG_SPANISH_GUATEMALA: int +SUBLANG_SPANISH_COSTA_RICA: int +SUBLANG_SPANISH_PANAMA: int +SUBLANG_SPANISH_DOMINICAN_REPUBLIC: int +SUBLANG_SPANISH_VENEZUELA: int +SUBLANG_SPANISH_COLOMBIA: int +SUBLANG_SPANISH_PERU: int +SUBLANG_SPANISH_ARGENTINA: int +SUBLANG_SPANISH_ECUADOR: int +SUBLANG_SPANISH_CHILE: int +SUBLANG_SPANISH_URUGUAY: int +SUBLANG_SPANISH_PARAGUAY: int +SUBLANG_SPANISH_BOLIVIA: int +SUBLANG_SPANISH_EL_SALVADOR: int +SUBLANG_SPANISH_HONDURAS: int +SUBLANG_SPANISH_NICARAGUA: int +SUBLANG_SPANISH_PUERTO_RICO: int +SUBLANG_SWEDISH: int +SUBLANG_SWEDISH_FINLAND: int +SORT_DEFAULT: int +SORT_JAPANESE_XJIS: int +SORT_JAPANESE_UNICODE: int +SORT_CHINESE_BIG5: int +SORT_CHINESE_PRCP: int +SORT_CHINESE_UNICODE: int +SORT_CHINESE_PRC: int +SORT_KOREAN_KSC: int +SORT_KOREAN_UNICODE: int +SORT_GERMAN_PHONE_BOOK: int + +def PRIMARYLANGID(lgid): ... +def SUBLANGID(lgid): ... + +NLS_VALID_LOCALE_MASK: int + +def LANGIDFROMLCID(lcid): ... +def SORTIDFROMLCID(lcid): ... + +MAXIMUM_WAIT_OBJECTS: int +MAXIMUM_SUSPEND_COUNT: int +EXCEPTION_NONCONTINUABLE: int +EXCEPTION_MAXIMUM_PARAMETERS: int +PROCESS_TERMINATE: int +PROCESS_CREATE_THREAD: int +PROCESS_VM_OPERATION: int +PROCESS_VM_READ: int +PROCESS_VM_WRITE: int +PROCESS_DUP_HANDLE: int +PROCESS_CREATE_PROCESS: int +PROCESS_SET_QUOTA: int +PROCESS_SET_INFORMATION: int +PROCESS_QUERY_INFORMATION: int +PROCESS_SUSPEND_RESUME: int +PROCESS_QUERY_LIMITED_INFORMATION: int +PROCESS_SET_LIMITED_INFORMATION: int +MAXIMUM_PROCESSORS: int +THREAD_TERMINATE: int +THREAD_SUSPEND_RESUME: int +THREAD_GET_CONTEXT: int +THREAD_SET_CONTEXT: int +THREAD_SET_INFORMATION: int +THREAD_QUERY_INFORMATION: int +THREAD_SET_THREAD_TOKEN: int +THREAD_IMPERSONATE: int +THREAD_DIRECT_IMPERSONATION: int +THREAD_SET_LIMITED_INFORMATION: int +THREAD_QUERY_LIMITED_INFORMATION: int +THREAD_RESUME: int +JOB_OBJECT_ASSIGN_PROCESS: int +JOB_OBJECT_SET_ATTRIBUTES: int +JOB_OBJECT_QUERY: int +JOB_OBJECT_TERMINATE: int +TLS_MINIMUM_AVAILABLE: int +THREAD_BASE_PRIORITY_LOWRT: int +THREAD_BASE_PRIORITY_MAX: int +THREAD_BASE_PRIORITY_MIN: int +THREAD_BASE_PRIORITY_IDLE: int +JOB_OBJECT_LIMIT_WORKINGSET: int +JOB_OBJECT_LIMIT_PROCESS_TIME: int +JOB_OBJECT_LIMIT_JOB_TIME: int +JOB_OBJECT_LIMIT_ACTIVE_PROCESS: int +JOB_OBJECT_LIMIT_AFFINITY: int +JOB_OBJECT_LIMIT_PRIORITY_CLASS: int +JOB_OBJECT_LIMIT_VALID_FLAGS: int +EVENT_MODIFY_STATE: int +MUTANT_QUERY_STATE: int +SEMAPHORE_MODIFY_STATE: int +TIME_ZONE_ID_UNKNOWN: int +TIME_ZONE_ID_STANDARD: int +TIME_ZONE_ID_DAYLIGHT: int +PROCESSOR_INTEL_386: int +PROCESSOR_INTEL_486: int +PROCESSOR_INTEL_PENTIUM: int +PROCESSOR_MIPS_R4000: int +PROCESSOR_ALPHA_21064: int +PROCESSOR_HITACHI_SH3: int +PROCESSOR_HITACHI_SH3E: int +PROCESSOR_HITACHI_SH4: int +PROCESSOR_MOTOROLA_821: int +PROCESSOR_ARM_7TDMI: int +PROCESSOR_ARCHITECTURE_INTEL: int +PROCESSOR_ARCHITECTURE_MIPS: int +PROCESSOR_ARCHITECTURE_ALPHA: int +PROCESSOR_ARCHITECTURE_PPC: int +PROCESSOR_ARCHITECTURE_SH: int +PROCESSOR_ARCHITECTURE_ARM: int +PROCESSOR_ARCHITECTURE_IA64: int +PROCESSOR_ARCHITECTURE_ALPHA64: int +PROCESSOR_ARCHITECTURE_MSIL: int +PROCESSOR_ARCHITECTURE_AMD64: int +PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: int +PROCESSOR_ARCHITECTURE_UNKNOWN: int +PF_FLOATING_POINT_PRECISION_ERRATA: int +PF_FLOATING_POINT_EMULATED: int +PF_COMPARE_EXCHANGE_DOUBLE: int +PF_MMX_INSTRUCTIONS_AVAILABLE: int +PF_PPC_MOVEMEM_64BIT_OK: int +PF_ALPHA_BYTE_INSTRUCTIONS: int +SECTION_QUERY: int +SECTION_MAP_WRITE: int +SECTION_MAP_READ: int +SECTION_MAP_EXECUTE: int +SECTION_EXTEND_SIZE: int +PAGE_NOACCESS: int +PAGE_READONLY: int +PAGE_READWRITE: int +PAGE_WRITECOPY: int +PAGE_EXECUTE: int +PAGE_EXECUTE_READ: int +PAGE_EXECUTE_READWRITE: int +PAGE_EXECUTE_WRITECOPY: int +PAGE_GUARD: int +PAGE_NOCACHE: int +MEM_COMMIT: int +MEM_RESERVE: int +MEM_DECOMMIT: int +MEM_RELEASE: int +MEM_FREE: int +MEM_PRIVATE: int +MEM_MAPPED: int +MEM_RESET: int +MEM_TOP_DOWN: int +MEM_4MB_PAGES: int +SEC_FILE: int +SEC_IMAGE: int +SEC_VLM: int +SEC_RESERVE: int +SEC_COMMIT: int +SEC_NOCACHE: int +MEM_IMAGE: int +FILE_READ_DATA: int +FILE_LIST_DIRECTORY: int +FILE_WRITE_DATA: int +FILE_ADD_FILE: int +FILE_APPEND_DATA: int +FILE_ADD_SUBDIRECTORY: int +FILE_CREATE_PIPE_INSTANCE: int +FILE_READ_EA: int +FILE_WRITE_EA: int +FILE_EXECUTE: int +FILE_TRAVERSE: int +FILE_DELETE_CHILD: int +FILE_READ_ATTRIBUTES: int +FILE_WRITE_ATTRIBUTES: int +FILE_SHARE_READ: int +FILE_SHARE_WRITE: int +FILE_SHARE_DELETE: int +FILE_ATTRIBUTE_READONLY: int +FILE_ATTRIBUTE_HIDDEN: int +FILE_ATTRIBUTE_SYSTEM: int +FILE_ATTRIBUTE_DIRECTORY: int +FILE_ATTRIBUTE_ARCHIVE: int +FILE_ATTRIBUTE_DEVICE: int +FILE_ATTRIBUTE_NORMAL: int +FILE_ATTRIBUTE_TEMPORARY: int +FILE_ATTRIBUTE_SPARSE_FILE: int +FILE_ATTRIBUTE_REPARSE_POINT: int +FILE_ATTRIBUTE_COMPRESSED: int +FILE_ATTRIBUTE_OFFLINE: int +FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: int +FILE_ATTRIBUTE_ENCRYPTED: int +FILE_ATTRIBUTE_VIRTUAL: int +FILE_NOTIFY_CHANGE_FILE_NAME: int +FILE_NOTIFY_CHANGE_DIR_NAME: int +FILE_NOTIFY_CHANGE_ATTRIBUTES: int +FILE_NOTIFY_CHANGE_SIZE: int +FILE_NOTIFY_CHANGE_LAST_WRITE: int +FILE_NOTIFY_CHANGE_LAST_ACCESS: int +FILE_NOTIFY_CHANGE_CREATION: int +FILE_NOTIFY_CHANGE_SECURITY: int +FILE_ACTION_ADDED: int +FILE_ACTION_REMOVED: int +FILE_ACTION_MODIFIED: int +FILE_ACTION_RENAMED_OLD_NAME: int +FILE_ACTION_RENAMED_NEW_NAME: int +FILE_CASE_SENSITIVE_SEARCH: int +FILE_CASE_PRESERVED_NAMES: int +FILE_UNICODE_ON_DISK: int +FILE_PERSISTENT_ACLS: int +FILE_FILE_COMPRESSION: int +FILE_VOLUME_QUOTAS: int +FILE_SUPPORTS_SPARSE_FILES: int +FILE_SUPPORTS_REPARSE_POINTS: int +FILE_SUPPORTS_REMOTE_STORAGE: int +FILE_VOLUME_IS_COMPRESSED: int +FILE_SUPPORTS_OBJECT_IDS: int +FILE_SUPPORTS_ENCRYPTION: int +MAXIMUM_REPARSE_DATA_BUFFER_SIZE: Incomplete +IO_REPARSE_TAG_RESERVED_ZERO: int +IO_REPARSE_TAG_RESERVED_ONE: int +IO_REPARSE_TAG_SYMBOLIC_LINK: int +IO_REPARSE_TAG_NSS: int +IO_REPARSE_TAG_FILTER_MANAGER: int +IO_REPARSE_TAG_DFS: int +IO_REPARSE_TAG_SIS: int +IO_REPARSE_TAG_MOUNT_POINT: int +IO_REPARSE_TAG_HSM: int +IO_REPARSE_TAG_NSSRECOVER: int +IO_REPARSE_TAG_RESERVED_MS_RANGE: int +IO_REPARSE_TAG_RESERVED_RANGE: int +IO_COMPLETION_MODIFY_STATE: int +DUPLICATE_CLOSE_SOURCE: int +DUPLICATE_SAME_ACCESS: int +DELETE: int +READ_CONTROL: int +WRITE_DAC: int +WRITE_OWNER: int +SYNCHRONIZE: int +STANDARD_RIGHTS_REQUIRED: int +STANDARD_RIGHTS_READ: int +STANDARD_RIGHTS_WRITE: int +STANDARD_RIGHTS_EXECUTE: int +STANDARD_RIGHTS_ALL: int +SPECIFIC_RIGHTS_ALL: int +IO_COMPLETION_ALL_ACCESS: Incomplete +ACCESS_SYSTEM_SECURITY: int +MAXIMUM_ALLOWED: int +GENERIC_READ: int +GENERIC_WRITE: int +GENERIC_EXECUTE: int +GENERIC_ALL: int +SID_REVISION: int +SID_MAX_SUB_AUTHORITIES: int +SID_RECOMMENDED_SUB_AUTHORITIES: int +SidTypeUser: int +SidTypeGroup: int +SidTypeDomain: int +SidTypeAlias: int +SidTypeWellKnownGroup: int +SidTypeDeletedAccount: int +SidTypeInvalid: int +SidTypeUnknown: int +SECURITY_NULL_RID: int +SECURITY_WORLD_RID: int +SECURITY_LOCAL_RID: int +SECURITY_CREATOR_OWNER_RID: int +SECURITY_CREATOR_GROUP_RID: int +SECURITY_CREATOR_OWNER_SERVER_RID: int +SECURITY_CREATOR_GROUP_SERVER_RID: int +SECURITY_DIALUP_RID: int +SECURITY_NETWORK_RID: int +SECURITY_BATCH_RID: int +SECURITY_INTERACTIVE_RID: int +SECURITY_SERVICE_RID: int +SECURITY_ANONYMOUS_LOGON_RID: int +SECURITY_PROXY_RID: int +SECURITY_SERVER_LOGON_RID: int +SECURITY_PRINCIPAL_SELF_RID: int +SECURITY_AUTHENTICATED_USER_RID: int +SECURITY_LOGON_IDS_RID: int +SECURITY_LOGON_IDS_RID_COUNT: int +SECURITY_LOCAL_SYSTEM_RID: int +SECURITY_NT_NON_UNIQUE: int +SECURITY_BUILTIN_DOMAIN_RID: int +DOMAIN_USER_RID_ADMIN: int +DOMAIN_USER_RID_GUEST: int +DOMAIN_GROUP_RID_ADMINS: int +DOMAIN_GROUP_RID_USERS: int +DOMAIN_GROUP_RID_GUESTS: int +DOMAIN_ALIAS_RID_ADMINS: int +DOMAIN_ALIAS_RID_USERS: int +DOMAIN_ALIAS_RID_GUESTS: int +DOMAIN_ALIAS_RID_POWER_USERS: int +DOMAIN_ALIAS_RID_ACCOUNT_OPS: int +DOMAIN_ALIAS_RID_SYSTEM_OPS: int +DOMAIN_ALIAS_RID_PRINT_OPS: int +DOMAIN_ALIAS_RID_BACKUP_OPS: int +DOMAIN_ALIAS_RID_REPLICATOR: int +SE_GROUP_MANDATORY: int +SE_GROUP_ENABLED_BY_DEFAULT: int +SE_GROUP_ENABLED: int +SE_GROUP_OWNER: int +SE_GROUP_LOGON_ID: int +ACL_REVISION: int +ACL_REVISION_DS: int +ACL_REVISION1: int +ACL_REVISION2: int +ACL_REVISION3: int +ACL_REVISION4: int +MAX_ACL_REVISION: int +ACCESS_MIN_MS_ACE_TYPE: int +ACCESS_ALLOWED_ACE_TYPE: int +ACCESS_DENIED_ACE_TYPE: int +SYSTEM_AUDIT_ACE_TYPE: int +SYSTEM_ALARM_ACE_TYPE: int +ACCESS_MAX_MS_V2_ACE_TYPE: int +ACCESS_ALLOWED_COMPOUND_ACE_TYPE: int +ACCESS_MAX_MS_V3_ACE_TYPE: int +ACCESS_MIN_MS_OBJECT_ACE_TYPE: int +ACCESS_ALLOWED_OBJECT_ACE_TYPE: int +ACCESS_DENIED_OBJECT_ACE_TYPE: int +SYSTEM_AUDIT_OBJECT_ACE_TYPE: int +SYSTEM_ALARM_OBJECT_ACE_TYPE: int +ACCESS_MAX_MS_OBJECT_ACE_TYPE: int +ACCESS_MAX_MS_V4_ACE_TYPE: int +ACCESS_MAX_MS_ACE_TYPE: int +ACCESS_ALLOWED_CALLBACK_ACE_TYPE: int +ACCESS_DENIED_CALLBACK_ACE_TYPE: int +ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: int +ACCESS_DENIED_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_AUDIT_CALLBACK_ACE_TYPE: int +SYSTEM_ALARM_CALLBACK_ACE_TYPE: int +SYSTEM_AUDIT_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_ALARM_CALLBACK_OBJECT_ACE_TYPE: int +SYSTEM_MANDATORY_LABEL_ACE_TYPE: int +ACCESS_MAX_MS_V5_ACE_TYPE: int +OBJECT_INHERIT_ACE: int +CONTAINER_INHERIT_ACE: int +NO_PROPAGATE_INHERIT_ACE: int +INHERIT_ONLY_ACE: int +INHERITED_ACE: int +VALID_INHERIT_FLAGS: int +SUCCESSFUL_ACCESS_ACE_FLAG: int +FAILED_ACCESS_ACE_FLAG: int +ACE_OBJECT_TYPE_PRESENT: int +ACE_INHERITED_OBJECT_TYPE_PRESENT: int +SECURITY_DESCRIPTOR_REVISION: int +SECURITY_DESCRIPTOR_REVISION1: int +SECURITY_DESCRIPTOR_MIN_LENGTH: int +SE_OWNER_DEFAULTED: int +SE_GROUP_DEFAULTED: int +SE_DACL_PRESENT: int +SE_DACL_DEFAULTED: int +SE_SACL_PRESENT: int +SE_SACL_DEFAULTED: int +SE_DACL_AUTO_INHERIT_REQ: int +SE_SACL_AUTO_INHERIT_REQ: int +SE_DACL_AUTO_INHERITED: int +SE_SACL_AUTO_INHERITED: int +SE_DACL_PROTECTED: int +SE_SACL_PROTECTED: int +SE_SELF_RELATIVE: int +ACCESS_OBJECT_GUID: int +ACCESS_PROPERTY_SET_GUID: int +ACCESS_PROPERTY_GUID: int +ACCESS_MAX_LEVEL: int +AUDIT_ALLOW_NO_PRIVILEGE: int +ACCESS_DS_SOURCE_A: str +ACCESS_DS_OBJECT_TYPE_NAME_A: str +SE_PRIVILEGE_ENABLED_BY_DEFAULT: int +SE_PRIVILEGE_ENABLED: int +SE_PRIVILEGE_USED_FOR_ACCESS: int +PRIVILEGE_SET_ALL_NECESSARY: int +SE_CREATE_TOKEN_NAME: str +SE_ASSIGNPRIMARYTOKEN_NAME: str +SE_LOCK_MEMORY_NAME: str +SE_INCREASE_QUOTA_NAME: str +SE_UNSOLICITED_INPUT_NAME: str +SE_MACHINE_ACCOUNT_NAME: str +SE_TCB_NAME: str +SE_SECURITY_NAME: str +SE_TAKE_OWNERSHIP_NAME: str +SE_LOAD_DRIVER_NAME: str +SE_SYSTEM_PROFILE_NAME: str +SE_SYSTEMTIME_NAME: str +SE_PROF_SINGLE_PROCESS_NAME: str +SE_INC_BASE_PRIORITY_NAME: str +SE_CREATE_PAGEFILE_NAME: str +SE_CREATE_PERMANENT_NAME: str +SE_BACKUP_NAME: str +SE_RESTORE_NAME: str +SE_SHUTDOWN_NAME: str +SE_DEBUG_NAME: str +SE_AUDIT_NAME: str +SE_SYSTEM_ENVIRONMENT_NAME: str +SE_CHANGE_NOTIFY_NAME: str +SE_REMOTE_SHUTDOWN_NAME: str +TOKEN_ASSIGN_PRIMARY: int +TOKEN_DUPLICATE: int +TOKEN_IMPERSONATE: int +TOKEN_QUERY: int +TOKEN_QUERY_SOURCE: int +TOKEN_ADJUST_PRIVILEGES: int +TOKEN_ADJUST_GROUPS: int +TOKEN_ADJUST_DEFAULT: int +TOKEN_ALL_ACCESS: Incomplete +TOKEN_READ: Incomplete +TOKEN_WRITE: Incomplete +TOKEN_EXECUTE: int +TOKEN_SOURCE_LENGTH: int +TokenPrimary: int +TokenImpersonation: int +TokenUser: int +TokenGroups: int +TokenPrivileges: int +TokenOwner: int +TokenPrimaryGroup: int +TokenDefaultDacl: int +TokenSource: int +TokenType: int +TokenImpersonationLevel: int +TokenStatistics: int +TokenRestrictedSids: int +TokenSessionId: int +TokenGroupsAndPrivileges: int +TokenSessionReference: int +TokenSandBoxInert: int +TokenAuditPolicy: int +TokenOrigin: int +TokenElevationType: int +TokenLinkedToken: int +TokenElevation: int +TokenHasRestrictions: int +TokenAccessInformation: int +TokenVirtualizationAllowed: int +TokenVirtualizationEnabled: int +TokenIntegrityLevel: int +TokenUIAccess: int +TokenMandatoryPolicy: int +TokenLogonSid: int +OWNER_SECURITY_INFORMATION: int +GROUP_SECURITY_INFORMATION: int +DACL_SECURITY_INFORMATION: int +SACL_SECURITY_INFORMATION: int +LABEL_SECURITY_INFORMATION: int +IMAGE_DOS_SIGNATURE: int +IMAGE_OS2_SIGNATURE: int +IMAGE_OS2_SIGNATURE_LE: int +IMAGE_VXD_SIGNATURE: int +IMAGE_NT_SIGNATURE: int +IMAGE_SIZEOF_FILE_HEADER: int +IMAGE_FILE_RELOCS_STRIPPED: int +IMAGE_FILE_EXECUTABLE_IMAGE: int +IMAGE_FILE_LINE_NUMS_STRIPPED: int +IMAGE_FILE_LOCAL_SYMS_STRIPPED: int +IMAGE_FILE_AGGRESIVE_WS_TRIM: int +IMAGE_FILE_LARGE_ADDRESS_AWARE: int +IMAGE_FILE_BYTES_REVERSED_LO: int +IMAGE_FILE_32BIT_MACHINE: int +IMAGE_FILE_DEBUG_STRIPPED: int +IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP: int +IMAGE_FILE_NET_RUN_FROM_SWAP: int +IMAGE_FILE_SYSTEM: int +IMAGE_FILE_DLL: int +IMAGE_FILE_UP_SYSTEM_ONLY: int +IMAGE_FILE_BYTES_REVERSED_HI: int +IMAGE_FILE_MACHINE_UNKNOWN: int +IMAGE_FILE_MACHINE_I386: int +IMAGE_FILE_MACHINE_R3000: int +IMAGE_FILE_MACHINE_R4000: int +IMAGE_FILE_MACHINE_R10000: int +IMAGE_FILE_MACHINE_WCEMIPSV2: int +IMAGE_FILE_MACHINE_ALPHA: int +IMAGE_FILE_MACHINE_POWERPC: int +IMAGE_FILE_MACHINE_SH3: int +IMAGE_FILE_MACHINE_SH3E: int +IMAGE_FILE_MACHINE_SH4: int +IMAGE_FILE_MACHINE_ARM: int +IMAGE_NUMBEROF_DIRECTORY_ENTRIES: int +IMAGE_SIZEOF_ROM_OPTIONAL_HEADER: int +IMAGE_SIZEOF_STD_OPTIONAL_HEADER: int +IMAGE_SIZEOF_NT_OPTIONAL_HEADER: int +IMAGE_NT_OPTIONAL_HDR_MAGIC: int +IMAGE_ROM_OPTIONAL_HDR_MAGIC: int +IMAGE_SUBSYSTEM_UNKNOWN: int +IMAGE_SUBSYSTEM_NATIVE: int +IMAGE_SUBSYSTEM_WINDOWS_GUI: int +IMAGE_SUBSYSTEM_WINDOWS_CUI: int +IMAGE_SUBSYSTEM_WINDOWS_CE_GUI: int +IMAGE_SUBSYSTEM_OS2_CUI: int +IMAGE_SUBSYSTEM_POSIX_CUI: int +IMAGE_SUBSYSTEM_RESERVED8: int +IMAGE_DLLCHARACTERISTICS_WDM_DRIVER: int +IMAGE_DIRECTORY_ENTRY_EXPORT: int +IMAGE_DIRECTORY_ENTRY_IMPORT: int +IMAGE_DIRECTORY_ENTRY_RESOURCE: int +IMAGE_DIRECTORY_ENTRY_EXCEPTION: int +IMAGE_DIRECTORY_ENTRY_SECURITY: int +IMAGE_DIRECTORY_ENTRY_BASERELOC: int +IMAGE_DIRECTORY_ENTRY_DEBUG: int +IMAGE_DIRECTORY_ENTRY_COPYRIGHT: int +IMAGE_DIRECTORY_ENTRY_GLOBALPTR: int +IMAGE_DIRECTORY_ENTRY_TLS: int +IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: int +IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: int +IMAGE_DIRECTORY_ENTRY_IAT: int +IMAGE_SIZEOF_SHORT_NAME: int +IMAGE_SIZEOF_SECTION_HEADER: int +IMAGE_SCN_TYPE_NO_PAD: int +IMAGE_SCN_CNT_CODE: int +IMAGE_SCN_CNT_INITIALIZED_DATA: int +IMAGE_SCN_CNT_UNINITIALIZED_DATA: int +IMAGE_SCN_LNK_OTHER: int +IMAGE_SCN_LNK_INFO: int +IMAGE_SCN_LNK_REMOVE: int +IMAGE_SCN_LNK_COMDAT: int +IMAGE_SCN_MEM_FARDATA: int +IMAGE_SCN_MEM_PURGEABLE: int +IMAGE_SCN_MEM_16BIT: int +IMAGE_SCN_MEM_LOCKED: int +IMAGE_SCN_MEM_PRELOAD: int +IMAGE_SCN_ALIGN_1BYTES: int +IMAGE_SCN_ALIGN_2BYTES: int +IMAGE_SCN_ALIGN_4BYTES: int +IMAGE_SCN_ALIGN_8BYTES: int +IMAGE_SCN_ALIGN_16BYTES: int +IMAGE_SCN_ALIGN_32BYTES: int +IMAGE_SCN_ALIGN_64BYTES: int +IMAGE_SCN_LNK_NRELOC_OVFL: int +IMAGE_SCN_MEM_DISCARDABLE: int +IMAGE_SCN_MEM_NOT_CACHED: int +IMAGE_SCN_MEM_NOT_PAGED: int +IMAGE_SCN_MEM_SHARED: int +IMAGE_SCN_MEM_EXECUTE: int +IMAGE_SCN_MEM_READ: int +IMAGE_SCN_MEM_WRITE: int +IMAGE_SCN_SCALE_INDEX: int +IMAGE_SIZEOF_SYMBOL: int +IMAGE_SYM_TYPE_NULL: int +IMAGE_SYM_TYPE_VOID: int +IMAGE_SYM_TYPE_CHAR: int +IMAGE_SYM_TYPE_SHORT: int +IMAGE_SYM_TYPE_INT: int +IMAGE_SYM_TYPE_LONG: int +IMAGE_SYM_TYPE_FLOAT: int +IMAGE_SYM_TYPE_DOUBLE: int +IMAGE_SYM_TYPE_STRUCT: int +IMAGE_SYM_TYPE_UNION: int +IMAGE_SYM_TYPE_ENUM: int +IMAGE_SYM_TYPE_MOE: int +IMAGE_SYM_TYPE_BYTE: int +IMAGE_SYM_TYPE_WORD: int +IMAGE_SYM_TYPE_UINT: int +IMAGE_SYM_TYPE_DWORD: int +IMAGE_SYM_TYPE_PCODE: int +IMAGE_SYM_DTYPE_NULL: int +IMAGE_SYM_DTYPE_POINTER: int +IMAGE_SYM_DTYPE_FUNCTION: int +IMAGE_SYM_DTYPE_ARRAY: int +IMAGE_SYM_CLASS_NULL: int +IMAGE_SYM_CLASS_AUTOMATIC: int +IMAGE_SYM_CLASS_EXTERNAL: int +IMAGE_SYM_CLASS_STATIC: int +IMAGE_SYM_CLASS_REGISTER: int +IMAGE_SYM_CLASS_EXTERNAL_DEF: int +IMAGE_SYM_CLASS_LABEL: int +IMAGE_SYM_CLASS_UNDEFINED_LABEL: int +IMAGE_SYM_CLASS_MEMBER_OF_STRUCT: int +IMAGE_SYM_CLASS_ARGUMENT: int +IMAGE_SYM_CLASS_STRUCT_TAG: int +IMAGE_SYM_CLASS_MEMBER_OF_UNION: int +IMAGE_SYM_CLASS_UNION_TAG: int +IMAGE_SYM_CLASS_TYPE_DEFINITION: int +IMAGE_SYM_CLASS_UNDEFINED_STATIC: int +IMAGE_SYM_CLASS_ENUM_TAG: int +IMAGE_SYM_CLASS_MEMBER_OF_ENUM: int +IMAGE_SYM_CLASS_REGISTER_PARAM: int +IMAGE_SYM_CLASS_BIT_FIELD: int +IMAGE_SYM_CLASS_FAR_EXTERNAL: int +IMAGE_SYM_CLASS_BLOCK: int +IMAGE_SYM_CLASS_FUNCTION: int +IMAGE_SYM_CLASS_END_OF_STRUCT: int +IMAGE_SYM_CLASS_FILE: int +IMAGE_SYM_CLASS_SECTION: int +IMAGE_SYM_CLASS_WEAK_EXTERNAL: int +N_BTMASK: int +N_TMASK: int +N_TMASK1: int +N_TMASK2: int +N_BTSHFT: int +N_TSHIFT: int + +def BTYPE(x): ... +def ISPTR(x): ... +def ISFCN(x): ... +def ISARY(x): ... +def INCREF(x): ... +def DECREF(x): ... + +IMAGE_SIZEOF_AUX_SYMBOL: int +IMAGE_COMDAT_SELECT_NODUPLICATES: int +IMAGE_COMDAT_SELECT_ANY: int +IMAGE_COMDAT_SELECT_SAME_SIZE: int +IMAGE_COMDAT_SELECT_EXACT_MATCH: int +IMAGE_COMDAT_SELECT_ASSOCIATIVE: int +IMAGE_COMDAT_SELECT_LARGEST: int +IMAGE_COMDAT_SELECT_NEWEST: int +IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY: int +IMAGE_WEAK_EXTERN_SEARCH_LIBRARY: int +IMAGE_WEAK_EXTERN_SEARCH_ALIAS: int +IMAGE_SIZEOF_RELOCATION: int +IMAGE_REL_I386_ABSOLUTE: int +IMAGE_REL_I386_DIR16: int +IMAGE_REL_I386_REL16: int +IMAGE_REL_I386_DIR32: int +IMAGE_REL_I386_DIR32NB: int +IMAGE_REL_I386_SEG12: int +IMAGE_REL_I386_SECTION: int +IMAGE_REL_I386_SECREL: int +IMAGE_REL_I386_REL32: int +IMAGE_REL_MIPS_ABSOLUTE: int +IMAGE_REL_MIPS_REFHALF: int +IMAGE_REL_MIPS_REFWORD: int +IMAGE_REL_MIPS_JMPADDR: int +IMAGE_REL_MIPS_REFHI: int +IMAGE_REL_MIPS_REFLO: int +IMAGE_REL_MIPS_GPREL: int +IMAGE_REL_MIPS_LITERAL: int +IMAGE_REL_MIPS_SECTION: int +IMAGE_REL_MIPS_SECREL: int +IMAGE_REL_MIPS_SECRELLO: int +IMAGE_REL_MIPS_SECRELHI: int +IMAGE_REL_MIPS_REFWORDNB: int +IMAGE_REL_MIPS_PAIR: int +IMAGE_REL_ALPHA_ABSOLUTE: int +IMAGE_REL_ALPHA_REFLONG: int +IMAGE_REL_ALPHA_REFQUAD: int +IMAGE_REL_ALPHA_GPREL32: int +IMAGE_REL_ALPHA_LITERAL: int +IMAGE_REL_ALPHA_LITUSE: int +IMAGE_REL_ALPHA_GPDISP: int +IMAGE_REL_ALPHA_BRADDR: int +IMAGE_REL_ALPHA_HINT: int +IMAGE_REL_ALPHA_INLINE_REFLONG: int +IMAGE_REL_ALPHA_REFHI: int +IMAGE_REL_ALPHA_REFLO: int +IMAGE_REL_ALPHA_PAIR: int +IMAGE_REL_ALPHA_MATCH: int +IMAGE_REL_ALPHA_SECTION: int +IMAGE_REL_ALPHA_SECREL: int +IMAGE_REL_ALPHA_REFLONGNB: int +IMAGE_REL_ALPHA_SECRELLO: int +IMAGE_REL_ALPHA_SECRELHI: int +IMAGE_REL_PPC_ABSOLUTE: int +IMAGE_REL_PPC_ADDR64: int +IMAGE_REL_PPC_ADDR32: int +IMAGE_REL_PPC_ADDR24: int +IMAGE_REL_PPC_ADDR16: int +IMAGE_REL_PPC_ADDR14: int +IMAGE_REL_PPC_REL24: int +IMAGE_REL_PPC_REL14: int +IMAGE_REL_PPC_TOCREL16: int +IMAGE_REL_PPC_TOCREL14: int +IMAGE_REL_PPC_ADDR32NB: int +IMAGE_REL_PPC_SECREL: int +IMAGE_REL_PPC_SECTION: int +IMAGE_REL_PPC_IFGLUE: int +IMAGE_REL_PPC_IMGLUE: int +IMAGE_REL_PPC_SECREL16: int +IMAGE_REL_PPC_REFHI: int +IMAGE_REL_PPC_REFLO: int +IMAGE_REL_PPC_PAIR: int +IMAGE_REL_PPC_SECRELLO: int +IMAGE_REL_PPC_SECRELHI: int +IMAGE_REL_PPC_TYPEMASK: int +IMAGE_REL_PPC_NEG: int +IMAGE_REL_PPC_BRTAKEN: int +IMAGE_REL_PPC_BRNTAKEN: int +IMAGE_REL_PPC_TOCDEFN: int +IMAGE_REL_SH3_ABSOLUTE: int +IMAGE_REL_SH3_DIRECT16: int +IMAGE_REL_SH3_DIRECT32: int +IMAGE_REL_SH3_DIRECT8: int +IMAGE_REL_SH3_DIRECT8_WORD: int +IMAGE_REL_SH3_DIRECT8_LONG: int +IMAGE_REL_SH3_DIRECT4: int +IMAGE_REL_SH3_DIRECT4_WORD: int +IMAGE_REL_SH3_DIRECT4_LONG: int +IMAGE_REL_SH3_PCREL8_WORD: int +IMAGE_REL_SH3_PCREL8_LONG: int +IMAGE_REL_SH3_PCREL12_WORD: int +IMAGE_REL_SH3_STARTOF_SECTION: int +IMAGE_REL_SH3_SIZEOF_SECTION: int +IMAGE_REL_SH3_SECTION: int +IMAGE_REL_SH3_SECREL: int +IMAGE_REL_SH3_DIRECT32_NB: int +IMAGE_SIZEOF_LINENUMBER: int +IMAGE_SIZEOF_BASE_RELOCATION: int +IMAGE_REL_BASED_ABSOLUTE: int +IMAGE_REL_BASED_HIGH: int +IMAGE_REL_BASED_LOW: int +IMAGE_REL_BASED_HIGHLOW: int +IMAGE_REL_BASED_HIGHADJ: int +IMAGE_REL_BASED_MIPS_JMPADDR: int +IMAGE_REL_BASED_SECTION: int +IMAGE_REL_BASED_REL32: int +IMAGE_ARCHIVE_START_SIZE: int +IMAGE_ARCHIVE_START: str +IMAGE_ARCHIVE_END: str +IMAGE_ARCHIVE_PAD: str +IMAGE_ARCHIVE_LINKER_MEMBER: str +IMAGE_SIZEOF_ARCHIVE_MEMBER_HDR: int +IMAGE_ORDINAL_FLAG: int + +def IMAGE_SNAP_BY_ORDINAL(Ordinal): ... +def IMAGE_ORDINAL(Ordinal): ... + +IMAGE_RESOURCE_NAME_IS_STRING: int +IMAGE_RESOURCE_DATA_IS_DIRECTORY: int +IMAGE_DEBUG_TYPE_UNKNOWN: int +IMAGE_DEBUG_TYPE_COFF: int +IMAGE_DEBUG_TYPE_CODEVIEW: int +IMAGE_DEBUG_TYPE_FPO: int +IMAGE_DEBUG_TYPE_MISC: int +IMAGE_DEBUG_TYPE_EXCEPTION: int +IMAGE_DEBUG_TYPE_FIXUP: int +IMAGE_DEBUG_TYPE_OMAP_TO_SRC: int +IMAGE_DEBUG_TYPE_OMAP_FROM_SRC: int +IMAGE_DEBUG_TYPE_BORLAND: int +FRAME_FPO: int +FRAME_TRAP: int +FRAME_TSS: int +FRAME_NONFPO: int +SIZEOF_RFPO_DATA: int +IMAGE_DEBUG_MISC_EXENAME: int +IMAGE_SEPARATE_DEBUG_SIGNATURE: int +IMAGE_SEPARATE_DEBUG_FLAGS_MASK: int +IMAGE_SEPARATE_DEBUG_MISMATCH: int +NULL: int +HEAP_NO_SERIALIZE: int +HEAP_GROWABLE: int +HEAP_GENERATE_EXCEPTIONS: int +HEAP_ZERO_MEMORY: int +HEAP_REALLOC_IN_PLACE_ONLY: int +HEAP_TAIL_CHECKING_ENABLED: int +HEAP_FREE_CHECKING_ENABLED: int +HEAP_DISABLE_COALESCE_ON_FREE: int +HEAP_CREATE_ALIGN_16: int +HEAP_CREATE_ENABLE_TRACING: int +HEAP_MAXIMUM_TAG: int +HEAP_PSEUDO_TAG_FLAG: int +HEAP_TAG_SHIFT: int +IS_TEXT_UNICODE_ASCII16: int +IS_TEXT_UNICODE_REVERSE_ASCII16: int +IS_TEXT_UNICODE_STATISTICS: int +IS_TEXT_UNICODE_REVERSE_STATISTICS: int +IS_TEXT_UNICODE_CONTROLS: int +IS_TEXT_UNICODE_REVERSE_CONTROLS: int +IS_TEXT_UNICODE_SIGNATURE: int +IS_TEXT_UNICODE_REVERSE_SIGNATURE: int +IS_TEXT_UNICODE_ILLEGAL_CHARS: int +IS_TEXT_UNICODE_ODD_LENGTH: int +IS_TEXT_UNICODE_DBCS_LEADBYTE: int +IS_TEXT_UNICODE_NULL_BYTES: int +IS_TEXT_UNICODE_UNICODE_MASK: int +IS_TEXT_UNICODE_REVERSE_MASK: int +IS_TEXT_UNICODE_NOT_UNICODE_MASK: int +IS_TEXT_UNICODE_NOT_ASCII_MASK: int +COMPRESSION_FORMAT_NONE: int +COMPRESSION_FORMAT_DEFAULT: int +COMPRESSION_FORMAT_LZNT1: int +COMPRESSION_ENGINE_STANDARD: int +COMPRESSION_ENGINE_MAXIMUM: int +MESSAGE_RESOURCE_UNICODE: int +RTL_CRITSECT_TYPE: int +RTL_RESOURCE_TYPE: int +SEF_DACL_AUTO_INHERIT: int +SEF_SACL_AUTO_INHERIT: int +SEF_DEFAULT_DESCRIPTOR_FOR_OBJECT: int +SEF_AVOID_PRIVILEGE_CHECK: int +DLL_PROCESS_ATTACH: int +DLL_THREAD_ATTACH: int +DLL_THREAD_DETACH: int +DLL_PROCESS_DETACH: int +EVENTLOG_SEQUENTIAL_READ: int +EVENTLOG_SEEK_READ: int +EVENTLOG_FORWARDS_READ: int +EVENTLOG_BACKWARDS_READ: int +EVENTLOG_SUCCESS: int +EVENTLOG_ERROR_TYPE: int +EVENTLOG_WARNING_TYPE: int +EVENTLOG_INFORMATION_TYPE: int +EVENTLOG_AUDIT_SUCCESS: int +EVENTLOG_AUDIT_FAILURE: int +EVENTLOG_START_PAIRED_EVENT: int +EVENTLOG_END_PAIRED_EVENT: int +EVENTLOG_END_ALL_PAIRED_EVENTS: int +EVENTLOG_PAIRED_EVENT_ACTIVE: int +EVENTLOG_PAIRED_EVENT_INACTIVE: int +KEY_QUERY_VALUE: int +KEY_SET_VALUE: int +KEY_CREATE_SUB_KEY: int +KEY_ENUMERATE_SUB_KEYS: int +KEY_NOTIFY: int +KEY_CREATE_LINK: int +KEY_READ: Incomplete +KEY_WRITE: Incomplete +KEY_EXECUTE: Incomplete +KEY_ALL_ACCESS: Incomplete +REG_OPTION_RESERVED: int +REG_OPTION_NON_VOLATILE: int +REG_OPTION_VOLATILE: int +REG_OPTION_CREATE_LINK: int +REG_OPTION_BACKUP_RESTORE: int +REG_OPTION_OPEN_LINK: int +REG_LEGAL_OPTION: Incomplete +REG_CREATED_NEW_KEY: int +REG_OPENED_EXISTING_KEY: int +REG_STANDARD_FORMAT: int +REG_LATEST_FORMAT: int +REG_NO_COMPRESSION: int +REG_WHOLE_HIVE_VOLATILE: int +REG_REFRESH_HIVE: int +REG_NO_LAZY_FLUSH: int +REG_FORCE_RESTORE: int +REG_NOTIFY_CHANGE_NAME: int +REG_NOTIFY_CHANGE_ATTRIBUTES: int +REG_NOTIFY_CHANGE_LAST_SET: int +REG_NOTIFY_CHANGE_SECURITY: int +REG_LEGAL_CHANGE_FILTER: Incomplete +REG_NONE: int +REG_SZ: int +REG_EXPAND_SZ: int +REG_BINARY: int +REG_DWORD: int +REG_DWORD_LITTLE_ENDIAN: int +REG_DWORD_BIG_ENDIAN: int +REG_LINK: int +REG_MULTI_SZ: int +REG_RESOURCE_LIST: int +REG_FULL_RESOURCE_DESCRIPTOR: int +REG_RESOURCE_REQUIREMENTS_LIST: int +SERVICE_KERNEL_DRIVER: int +SERVICE_FILE_SYSTEM_DRIVER: int +SERVICE_ADAPTER: int +SERVICE_RECOGNIZER_DRIVER: int +SERVICE_DRIVER: Incomplete +SERVICE_WIN32_OWN_PROCESS: int +SERVICE_WIN32_SHARE_PROCESS: int +SERVICE_WIN32: Incomplete +SERVICE_INTERACTIVE_PROCESS: int +SERVICE_TYPE_ALL: Incomplete +SERVICE_BOOT_START: int +SERVICE_SYSTEM_START: int +SERVICE_AUTO_START: int +SERVICE_DEMAND_START: int +SERVICE_DISABLED: int +SERVICE_ERROR_IGNORE: int +SERVICE_ERROR_NORMAL: int +SERVICE_ERROR_SEVERE: int +SERVICE_ERROR_CRITICAL: int +TAPE_ERASE_SHORT: int +TAPE_ERASE_LONG: int +TAPE_LOAD: int +TAPE_UNLOAD: int +TAPE_TENSION: int +TAPE_LOCK: int +TAPE_UNLOCK: int +TAPE_FORMAT: int +TAPE_SETMARKS: int +TAPE_FILEMARKS: int +TAPE_SHORT_FILEMARKS: int +TAPE_LONG_FILEMARKS: int +TAPE_ABSOLUTE_POSITION: int +TAPE_LOGICAL_POSITION: int +TAPE_PSEUDO_LOGICAL_POSITION: int +TAPE_REWIND: int +TAPE_ABSOLUTE_BLOCK: int +TAPE_LOGICAL_BLOCK: int +TAPE_PSEUDO_LOGICAL_BLOCK: int +TAPE_SPACE_END_OF_DATA: int +TAPE_SPACE_RELATIVE_BLOCKS: int +TAPE_SPACE_FILEMARKS: int +TAPE_SPACE_SEQUENTIAL_FMKS: int +TAPE_SPACE_SETMARKS: int +TAPE_SPACE_SEQUENTIAL_SMKS: int +TAPE_DRIVE_FIXED: int +TAPE_DRIVE_SELECT: int +TAPE_DRIVE_INITIATOR: int +TAPE_DRIVE_ERASE_SHORT: int +TAPE_DRIVE_ERASE_LONG: int +TAPE_DRIVE_ERASE_BOP_ONLY: int +TAPE_DRIVE_ERASE_IMMEDIATE: int +TAPE_DRIVE_TAPE_CAPACITY: int +TAPE_DRIVE_TAPE_REMAINING: int +TAPE_DRIVE_FIXED_BLOCK: int +TAPE_DRIVE_VARIABLE_BLOCK: int +TAPE_DRIVE_WRITE_PROTECT: int +TAPE_DRIVE_EOT_WZ_SIZE: int +TAPE_DRIVE_ECC: int +TAPE_DRIVE_COMPRESSION: int +TAPE_DRIVE_PADDING: int +TAPE_DRIVE_REPORT_SMKS: int +TAPE_DRIVE_GET_ABSOLUTE_BLK: int +TAPE_DRIVE_GET_LOGICAL_BLK: int +TAPE_DRIVE_SET_EOT_WZ_SIZE: int +TAPE_DRIVE_EJECT_MEDIA: int +TAPE_DRIVE_RESERVED_BIT: int +TAPE_DRIVE_LOAD_UNLOAD: int +TAPE_DRIVE_TENSION: int +TAPE_DRIVE_LOCK_UNLOCK: int +TAPE_DRIVE_REWIND_IMMEDIATE: int +TAPE_DRIVE_SET_BLOCK_SIZE: int +TAPE_DRIVE_LOAD_UNLD_IMMED: int +TAPE_DRIVE_TENSION_IMMED: int +TAPE_DRIVE_LOCK_UNLK_IMMED: int +TAPE_DRIVE_SET_ECC: int +TAPE_DRIVE_SET_COMPRESSION: int +TAPE_DRIVE_SET_PADDING: int +TAPE_DRIVE_SET_REPORT_SMKS: int +TAPE_DRIVE_ABSOLUTE_BLK: int +TAPE_DRIVE_ABS_BLK_IMMED: int +TAPE_DRIVE_LOGICAL_BLK: int +TAPE_DRIVE_LOG_BLK_IMMED: int +TAPE_DRIVE_END_OF_DATA: int +TAPE_DRIVE_RELATIVE_BLKS: int +TAPE_DRIVE_FILEMARKS: int +TAPE_DRIVE_SEQUENTIAL_FMKS: int +TAPE_DRIVE_SETMARKS: int +TAPE_DRIVE_SEQUENTIAL_SMKS: int +TAPE_DRIVE_REVERSE_POSITION: int +TAPE_DRIVE_SPACE_IMMEDIATE: int +TAPE_DRIVE_WRITE_SETMARKS: int +TAPE_DRIVE_WRITE_FILEMARKS: int +TAPE_DRIVE_WRITE_SHORT_FMKS: int +TAPE_DRIVE_WRITE_LONG_FMKS: int +TAPE_DRIVE_WRITE_MARK_IMMED: int +TAPE_DRIVE_FORMAT: int +TAPE_DRIVE_FORMAT_IMMEDIATE: int +TAPE_DRIVE_HIGH_FEATURES: int +TAPE_FIXED_PARTITIONS: int +TAPE_SELECT_PARTITIONS: int +TAPE_INITIATOR_PARTITIONS: int +TRANSACTIONMANAGER_QUERY_INFORMATION: int +TRANSACTIONMANAGER_SET_INFORMATION: int +TRANSACTIONMANAGER_RECOVER: int +TRANSACTIONMANAGER_RENAME: int +TRANSACTIONMANAGER_CREATE_RM: int +TRANSACTIONMANAGER_BIND_TRANSACTION: int +TRANSACTIONMANAGER_GENERIC_READ: Incomplete +TRANSACTIONMANAGER_GENERIC_WRITE: Incomplete +TRANSACTIONMANAGER_GENERIC_EXECUTE: int +TRANSACTIONMANAGER_ALL_ACCESS: Incomplete +TRANSACTION_QUERY_INFORMATION: int +TRANSACTION_SET_INFORMATION: int +TRANSACTION_ENLIST: int +TRANSACTION_COMMIT: int +TRANSACTION_ROLLBACK: int +TRANSACTION_PROPAGATE: int +TRANSACTION_SAVEPOINT: int +TRANSACTION_MARSHALL: int +TRANSACTION_GENERIC_READ: Incomplete +TRANSACTION_GENERIC_WRITE: Incomplete +TRANSACTION_GENERIC_EXECUTE: Incomplete +TRANSACTION_ALL_ACCESS: Incomplete +TRANSACTION_RESOURCE_MANAGER_RIGHTS: Incomplete +RESOURCEMANAGER_QUERY_INFORMATION: int +RESOURCEMANAGER_SET_INFORMATION: int +RESOURCEMANAGER_RECOVER: int +RESOURCEMANAGER_ENLIST: int +RESOURCEMANAGER_GET_NOTIFICATION: int +RESOURCEMANAGER_REGISTER_PROTOCOL: int +RESOURCEMANAGER_COMPLETE_PROPAGATION: int +RESOURCEMANAGER_GENERIC_READ: Incomplete +RESOURCEMANAGER_GENERIC_WRITE: Incomplete +RESOURCEMANAGER_GENERIC_EXECUTE: Incomplete +RESOURCEMANAGER_ALL_ACCESS: Incomplete +ENLISTMENT_QUERY_INFORMATION: int +ENLISTMENT_SET_INFORMATION: int +ENLISTMENT_RECOVER: int +ENLISTMENT_SUBORDINATE_RIGHTS: int +ENLISTMENT_SUPERIOR_RIGHTS: int +ENLISTMENT_GENERIC_READ: Incomplete +ENLISTMENT_GENERIC_WRITE: Incomplete +ENLISTMENT_GENERIC_EXECUTE: Incomplete +ENLISTMENT_ALL_ACCESS: Incomplete +TransactionOutcomeUndetermined: int +TransactionOutcomeCommitted: int +TransactionOutcomeAborted: int +TransactionStateNormal: int +TransactionStateIndoubt: int +TransactionStateCommittedNotify: int +TransactionBasicInformation: int +TransactionPropertiesInformation: int +TransactionEnlistmentInformation: int +TransactionFullInformation: int +TransactionManagerBasicInformation: int +TransactionManagerLogInformation: int +TransactionManagerLogPathInformation: int +TransactionManagerOnlineProbeInformation: int +ResourceManagerBasicInformation: int +ResourceManagerCompletionInformation: int +ResourceManagerFullInformation: int +ResourceManagerNameInformation: int +EnlistmentBasicInformation: int +EnlistmentRecoveryInformation: int +EnlistmentFullInformation: int +EnlistmentNameInformation: int +KTMOBJECT_TRANSACTION: int +KTMOBJECT_TRANSACTION_MANAGER: int +KTMOBJECT_RESOURCE_MANAGER: int +KTMOBJECT_ENLISTMENT: int +KTMOBJECT_INVALID: int diff --git a/stubs/pywin32/win32/lib/winperf.pyi b/stubs/pywin32/win32/lib/winperf.pyi new file mode 100644 index 000000000000..bcda5bf33e26 --- /dev/null +++ b/stubs/pywin32/win32/lib/winperf.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete + +PERF_DATA_VERSION: int +PERF_DATA_REVISION: int +PERF_NO_INSTANCES: int +PERF_SIZE_DWORD: int +PERF_SIZE_LARGE: int +PERF_SIZE_ZERO: int +PERF_SIZE_VARIABLE_LEN: int +PERF_TYPE_NUMBER: int +PERF_TYPE_COUNTER: int +PERF_TYPE_TEXT: int +PERF_TYPE_ZERO: int +PERF_NUMBER_HEX: int +PERF_NUMBER_DECIMAL: int +PERF_NUMBER_DEC_1000: int +PERF_COUNTER_VALUE: int +PERF_COUNTER_RATE: int +PERF_COUNTER_FRACTION: int +PERF_COUNTER_BASE: int +PERF_COUNTER_ELAPSED: int +PERF_COUNTER_QUEUELEN: int +PERF_COUNTER_HISTOGRAM: int +PERF_TEXT_UNICODE: int +PERF_TEXT_ASCII: int +PERF_TIMER_TICK: int +PERF_TIMER_100NS: int +PERF_OBJECT_TIMER: int +PERF_DELTA_COUNTER: int +PERF_DELTA_BASE: int +PERF_INVERSE_COUNTER: int +PERF_MULTI_COUNTER: int +PERF_DISPLAY_NO_SUFFIX: int +PERF_DISPLAY_PER_SEC: int +PERF_DISPLAY_PERCENT: int +PERF_DISPLAY_SECONDS: int +PERF_DISPLAY_NOSHOW: int +PERF_COUNTER_COUNTER: Incomplete +PERF_COUNTER_TIMER: Incomplete +PERF_COUNTER_QUEUELEN_TYPE: Incomplete +PERF_COUNTER_LARGE_QUEUELEN_TYPE: Incomplete +PERF_COUNTER_BULK_COUNT: Incomplete +PERF_COUNTER_TEXT: Incomplete +PERF_COUNTER_RAWCOUNT: Incomplete +PERF_COUNTER_LARGE_RAWCOUNT: Incomplete +PERF_COUNTER_RAWCOUNT_HEX: Incomplete +PERF_COUNTER_LARGE_RAWCOUNT_HEX: Incomplete +PERF_SAMPLE_FRACTION: Incomplete +PERF_SAMPLE_COUNTER: Incomplete +PERF_COUNTER_NODATA: Incomplete +PERF_COUNTER_TIMER_INV: Incomplete +PERF_SAMPLE_BASE: Incomplete +PERF_AVERAGE_TIMER: Incomplete +PERF_AVERAGE_BASE: Incomplete +PERF_AVERAGE_BULK: Incomplete +PERF_100NSEC_TIMER: Incomplete +PERF_100NSEC_TIMER_INV: Incomplete +PERF_COUNTER_MULTI_TIMER: Incomplete +PERF_COUNTER_MULTI_TIMER_INV: Incomplete +PERF_COUNTER_MULTI_BASE: Incomplete +PERF_100NSEC_MULTI_TIMER: Incomplete +PERF_100NSEC_MULTI_TIMER_INV: Incomplete +PERF_RAW_FRACTION: Incomplete +PERF_RAW_BASE: Incomplete +PERF_ELAPSED_TIME: Incomplete +PERF_COUNTER_HISTOGRAM_TYPE: int +PERF_COUNTER_DELTA: Incomplete +PERF_COUNTER_LARGE_DELTA: Incomplete +PERF_DETAIL_NOVICE: int +PERF_DETAIL_ADVANCED: int +PERF_DETAIL_EXPERT: int +PERF_DETAIL_WIZARD: int +PERF_NO_UNIQUE_ID: int diff --git a/stubs/pywin32/win32/lib/winxptheme.pyi b/stubs/pywin32/win32/lib/winxptheme.pyi new file mode 100644 index 000000000000..6f88b731dedd --- /dev/null +++ b/stubs/pywin32/win32/lib/winxptheme.pyi @@ -0,0 +1,25 @@ +import _win32typing + +def OpenThemeData(hwnd: int, pszClasslist: str, /) -> _win32typing.PyHTHEME: ... +def CloseThemeData(hTheme: _win32typing.PyHTHEME, /) -> None: ... +def DrawThemeBackground(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pRect, pClipRect, /) -> None: ... +def DrawThemeText( + hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pszText: str, dwCharCount, dwTextFlags, dwTextFlags2, pRect, / +) -> None: ... +def GetThemeBackgroundContentRect(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pBoundingRect, /): ... +def GetThemeBackgroundExtent(hTheme: _win32typing.PyHTHEME, hdc, iPartId, iStateId, pContentRect, /): ... +def IsThemeActive() -> int: ... +def IsAppThemed() -> int: ... +def GetWindowTheme(hwnd: int, /) -> _win32typing.PyHTHEME: ... +def EnableThemeDialogTexture(hdlg, dwFlags, /) -> None: ... +def IsThemeDialogTextureEnabled(hdlg: int | None, /) -> bool: ... +def GetThemeAppProperties(): ... +def EnableTheming(fEnable, /) -> None: ... +def SetWindowTheme(hwnd: int, pszSubAppName: str, pszSubIdlist: str, /) -> None: ... +def GetCurrentThemeName() -> tuple[str, str, str]: ... + +ETDT_DISABLE: int +ETDT_ENABLE: int +ETDT_ENABLETAB: int +ETDT_USETABTEXTURE: int +UNICODE: int diff --git a/stubs/pywin32/win32/mmapfile.pyi b/stubs/pywin32/win32/mmapfile.pyi new file mode 100644 index 000000000000..8d943c3722e5 --- /dev/null +++ b/stubs/pywin32/win32/mmapfile.pyi @@ -0,0 +1,6 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def mmapfile( + File, Name, MaximumSize: int = ..., FileOffset: int = ..., NumberOfBytesToMap: int = ... +) -> _win32typing.Pymmapfile: ... diff --git a/stubs/pywin32/win32/odbc.pyi b/stubs/pywin32/win32/odbc.pyi new file mode 100644 index 000000000000..0a0b7f54047c --- /dev/null +++ b/stubs/pywin32/win32/odbc.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import ClassVar, Literal + +import _win32typing + +def odbc(connectionString: str, /) -> _win32typing.connection: ... +def SQLDataSources(direction, /) -> tuple[Incomplete, Incomplete]: ... + +DATE: str +NUMBER: str +RAW: str +SQL_FETCH_ABSOLUTE: int +SQL_FETCH_FIRST: int +SQL_FETCH_FIRST_SYSTEM: int +SQL_FETCH_FIRST_USER: int +SQL_FETCH_LAST: int +SQL_FETCH_NEXT: int +SQL_FETCH_PRIOR: int +SQL_FETCH_RELATIVE: int +STRING: str +TYPES: tuple[Literal["STRING"], Literal["RAW"], Literal["NUMBER"], Literal["DATE"]] + +class error(Exception): + __name__: ClassVar[str] = "odbcError" + +# These all pretend to come from a module called "dbi", but that module doesn't exist +class dataError(Exception): ... +class integrityError(Exception): ... +class internalError(Exception): ... +class noError(Exception): ... +class opError(Exception): ... +class progError(Exception): ... diff --git a/stubs/pywin32/win32/perfmon.pyi b/stubs/pywin32/win32/perfmon.pyi new file mode 100644 index 000000000000..a7ea4e3d2081 --- /dev/null +++ b/stubs/pywin32/win32/perfmon.pyi @@ -0,0 +1,13 @@ +import _win32typing + +def LoadPerfCounterTextStrings(commandLine: str, /) -> None: ... +def UnloadPerfCounterTextStrings(commandLine: str, /) -> None: ... +def CounterDefinition() -> _win32typing.PyPERF_COUNTER_DEFINITION: ... +def ObjectType() -> _win32typing.PyPERF_OBJECT_TYPE: ... +def PerfMonManager( + serviceName: str, + seqPerfObTypes: list[_win32typing.PyPERF_OBJECT_TYPE], + mappingName: str | None = ..., + eventSourceName: str | None = ..., + /, +) -> _win32typing.PyPerfMonManager: ... diff --git a/stubs/pywin32/win32/servicemanager.pyi b/stubs/pywin32/win32/servicemanager.pyi new file mode 100644 index 000000000000..6acc15a79403 --- /dev/null +++ b/stubs/pywin32/win32/servicemanager.pyi @@ -0,0 +1,34 @@ +from _typeshed import Incomplete + +def CoInitializeEx() -> None: ... +def CoUninitialize() -> None: ... +def RegisterServiceCtrlHandler(serviceName: str, callback, extra_args: bool = ..., /): ... +def LogMsg(errorType: int, eventId: int, inserts: tuple[str, str] | None = ..., /) -> None: ... +def LogInfoMsg(msg: str, /) -> None: ... +def LogErrorMsg(msg: str, /) -> None: ... +def LogWarningMsg(msg: str, /) -> None: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def Debugging(newVal: int = ..., /): ... +def Initialize(eventSourceName: str | None = ..., eventSourceFile: str | None = ..., /) -> None: ... +def Finalize() -> None: ... +def PrepareToHostSingle(klass: Incomplete | None = ..., /) -> None: ... +def PrepareToHostMultiple(service_name: str, klass, /) -> None: ... +def RunningAsService(): ... +def SetEventSourceName(sourceName: str, registerNow: bool = ..., /) -> None: ... +def StartServiceCtrlDispatcher(): ... + +COINIT_APARTMENTTHREADED: int +COINIT_DISABLE_OLE1DDE: int +COINIT_MULTITHREADED: int +COINIT_SPEED_OVER_MEMORY: int +EVENTLOG_AUDIT_FAILURE: int +EVENTLOG_AUDIT_SUCCESS: int +EVENTLOG_ERROR_TYPE: int +EVENTLOG_INFORMATION_TYPE: int +EVENTLOG_WARNING_TYPE: int +PYS_SERVICE_STARTED: int +PYS_SERVICE_STARTING: int +PYS_SERVICE_STOPPED: int +PYS_SERVICE_STOPPING: int + +class startup_error(Exception): ... diff --git a/stubs/pywin32/win32/timer.pyi b/stubs/pywin32/win32/timer.pyi new file mode 100644 index 000000000000..ad8a7bcbe0b9 --- /dev/null +++ b/stubs/pywin32/win32/timer.pyi @@ -0,0 +1,6 @@ +from win32.lib.pywintypes import error as error + +def set_timer(Elapse, TimerFunc, /): ... +def kill_timer(timer_id, /): ... + +__version__: bytes diff --git a/stubs/pywin32/win32/win32api.pyi b/stubs/pywin32/win32/win32api.pyi new file mode 100644 index 000000000000..2023030f3215 --- /dev/null +++ b/stubs/pywin32/win32/win32api.pyi @@ -0,0 +1,376 @@ +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Callable, Iterable +from typing import Literal, TypedDict, overload, type_check_only +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +@type_check_only +class _MonitorInfo(TypedDict): + Monitor: tuple[int, int, int, int] + Work: tuple[int, int, int, int] + Flags: int + Device: str + +@type_check_only +class _FileVersionInfo(TypedDict): + Signature: int + StrucVersion: int + FileVersionMS: int + FileVersionLS: int + ProductVersionMS: int + ProductVersionLS: int + FileFlagsMask: int + FileFlags: int + FileOS: int + FileType: int + FileSubtype: int + FileDate: None | Incomplete + +@type_check_only +class _PwrCapabilitiesBatteryScale(TypedDict): + Granularity: int + Capacity: int + +@type_check_only +class _PwrCapabilities(TypedDict): + PowerButtonPresent: bool + SleepButtonPresent: bool + LidPresent: bool + SystemS1: bool + SystemS2: bool + SystemS3: bool + SystemS4: bool + SystemS5: bool + HiberFilePresent: bool + FullWake: bool + VideoDimPresent: bool + ApmPresent: bool + UpsPresent: bool + ThermalControl: bool + ProcessorThrottle: bool + ProcessorMinThrottle: int + ProcessorMaxThrottle: int + FastSystemS4: bool + spare2: Incomplete | None + DiskSpinDown: bool + spare3: Incomplete | None + SystemBatteriesPresent: bool + BatteriesAreShortTerm: bool + BatteryScale: tuple[_PwrCapabilitiesBatteryScale, ...] + AcOnLineWake: int + SoftLidWake: int + RtcWake: int + MinDeviceWakeState: int + DefaultLowLatencyWake: int + +def AbortSystemShutdown(computerName: str, /) -> None: ... +def InitiateSystemShutdown(computerName: str, message: str, timeOut, bForceClose, bRebootAfterShutdown, /) -> None: ... +def Apply(exceptionHandler, func, args, /): ... +def Beep(freq, dur, /) -> None: ... +def BeginUpdateResource(filename: str, delete, /) -> int: ... +def ChangeDisplaySettings(DevMode: _win32typing.PyDEVMODEW, Flags, /): ... +def ChangeDisplaySettingsEx(DeviceName: str | None = ..., DevMode: _win32typing.PyDEVMODEW | None = ..., Flags=...) -> int: ... +def ClipCursor(arg: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /) -> None: ... +def CloseHandle(handle: int, /) -> None: ... +def CopyFile(src, dest: str, bFailOnExist: int = ..., /) -> None: ... +def DebugBreak() -> None: ... +def DeleteFile(fileName: str, /) -> None: ... + +@overload +def DragQueryFile(hDrop, fileNum: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFile(hDrop, fileNum: int, /) -> str: ... + +def DragFinish(hDrop, /) -> None: ... +def DuplicateHandle( + hSourceProcess: int, hSource: int, hTargetProcessHandle: int, desiredAccess: int, bInheritHandle: int, options: int, / +) -> int: ... +def EndUpdateResource(handle: int, discard, /) -> None: ... +def EnumDisplayDevices(Device: str | None = ..., DevNum: int = ..., Flags: int = ...) -> _win32typing.PyDISPLAY_DEVICE: ... +def EnumDisplayMonitors( + hdc: int | None = ..., rcClip: _win32typing.PyRECT | None = ... +) -> list[tuple[_win32typing.PyHANDLE, _win32typing.PyHANDLE, tuple[int, int, int, int]]]: ... +def EnumDisplaySettings(DeviceName: str | None = ..., ModeNum: int = ...) -> _win32typing.PyDEVMODEW: ... +def EnumDisplaySettingsEx(DeviceName: str | None = ..., ModeNum=..., Flags=...) -> _win32typing.PyDEVMODEW: ... +def EnumResourceLanguages( + hmodule: int, lpType: _win32typing.PyResourceId, lpName: _win32typing.PyResourceId, / +) -> list[Incomplete]: ... +def EnumResourceNames(hmodule: int, resType: _win32typing.PyResourceId, /) -> list[str]: ... +def EnumResourceTypes(hmodule: int, /) -> list[Incomplete]: ... +def ExpandEnvironmentStrings(_in: str, /) -> str: ... +def ExitWindows(reserved1: int = ..., reserved2: int = ..., /) -> None: ... +def ExitWindowsEx(flags, reserved: int = ..., /) -> None: ... +def FindFiles(fileSpec: str, /): ... +def FindFirstChangeNotification(pathName: str, bSubDirs, _filter, /): ... +def FindNextChangeNotification(handle: int, /) -> None: ... +def FindCloseChangeNotification(handle, /) -> None: ... +def FindExecutable(filename: str, _dir: str, /) -> tuple[Incomplete, str]: ... +def FormatMessage( + flags: int, source: str | None = ..., messageId: int = ..., languageID: int = ..., inserts: Iterable[str] | None = ..., / +) -> str: ... +def FormatMessageW( + flags: int, source: int | None = ..., messageId: int = ..., languageID: int = ..., inserts: Iterable[str] | None = ..., / +) -> str: ... +def FreeLibrary(hModule: int, /) -> None: ... +def GenerateConsoleCtrlEvent(controlEvent: int, processGroupId: int, /) -> None: ... +def GetAsyncKeyState(key: int, /) -> int: ... +def GetCommandLine() -> str: ... +def GetComputerName() -> str: ... +def GetComputerNameEx(NameType: int, /) -> str: ... +def GetComputerObjectName(NameFormat: int, /) -> str: ... +def GetMonitorInfo(hMonitor: int) -> _MonitorInfo: ... +def GetUserName() -> str: ... +def GetUserNameEx(NameFormat: int, /) -> str: ... +def GetCursorPos() -> tuple[int, int]: ... +def GetCurrentThread() -> int: ... +def GetCurrentThreadId() -> int: ... +def GetCurrentProcessId() -> int: ... +def GetCurrentProcess() -> int: ... +def GetConsoleTitle() -> str: ... +def GetDateFormat(locale: int, flags: int, time: TimeType | None, _format: str | None = None, /) -> str: ... +def GetDiskFreeSpace(rootPath: str | None = None, /) -> tuple[int, int, int, int]: ... +def GetDiskFreeSpaceEx(rootPath: str | None = None, /) -> tuple[int, int, int]: ... +def GetDllDirectory() -> str: ... +def GetDomainName() -> str: ... +def GetEnvironmentVariable(variable: str, /) -> str | None: ... +def GetEnvironmentVariableW(Name: str, /) -> str | None: ... +def GetFileAttributes(pathName: str, /) -> int: ... +def GetFileVersionInfo(Filename: str, SubBlock: str, /) -> _FileVersionInfo: ... +def GetFocus(): ... +def GetFullPathName(fileName: str, /) -> str: ... +def GetHandleInformation(Object: int, /): ... +def GetKeyboardLayout(threadId: int = ..., /) -> int: ... +def GetKeyboardLayoutName() -> str: ... +def GetKeyboardState() -> bytes: ... +def GetKeyState(key: int, /) -> int: ... +def GetLastError() -> int: ... +def GetLastInputInfo() -> int: ... +def GetLocalTime() -> tuple[int, int, int, int, int, int, int, int]: ... +def GetLongPathName(fileName: str, /) -> str: ... +def GetLongPathNameW(fileName: str, /) -> str: ... +def GetLogicalDrives() -> int: ... +def GetLogicalDriveStrings() -> str: ... +def GetModuleFileName(hModule: int | None, /) -> str: ... +def GetModuleFileNameW(hModule: int | None, /) -> str: ... +def GetModuleHandle(fileName: str | None = None, /) -> int: ... +def GetPwrCapabilities() -> _PwrCapabilities: ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def GetProfileSection(section: str, iniName: str | None = ..., /) -> list[Incomplete]: ... +def GetProcAddress(hModule: int, functionName: _win32typing.PyResourceId, /): ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def GetProfileVal(section: str, entry: str, defValue: str, iniName: str | None = ..., /) -> str: ... +def GetShortPathName(path: str, /) -> str: ... +def GetStdHandle(handle: int, /) -> int: ... +def GetSysColor(index: int, /) -> int: ... +def GetSystemCpuSetInformation() -> list[_win32typing.PySYSTEM_CPU_SET_INFORMATION]: ... +def GetSystemDefaultLangID() -> int: ... +def GetSystemDefaultLCID() -> int: ... +def GetSystemDirectory() -> str: ... +def GetSystemFileCacheSize() -> tuple[int, int, int]: ... +def SetSystemFileCacheSize(MinimumFileCacheSize: int, MaximumFileCacheSize: int, Flags: int = ...) -> None: ... +def GetSystemInfo() -> tuple[int, int, int, int, int, int, int, int, tuple[int, int]]: ... +def GetNativeSystemInfo() -> tuple[int, int, int, int, int, int, int, int, tuple[int, int]]: ... +def GetSystemMetrics(index: int, /) -> int: ... +def GetSystemPowerStatus() -> dict[str, int]: ... +def GetSystemTime() -> tuple[int, int, int, int, int, int, int, int]: ... +def GetTempFileName(path: str, prefix: str, nUnique: int = ..., /) -> tuple[str, int]: ... +def GetTempPath() -> str: ... +def GetThreadLocale() -> int: ... +def GetTickCount() -> int: ... +def GetTimeFormat(locale: int, flags: int, time: TimeType | None, _format: str, /) -> str: ... + +@overload +def GetTimeZoneInformation( + times_as_tuples: Literal[True] = True, / +) -> tuple[ + int, + tuple[int, str, tuple[int, int, int, int, int, int, int, int], int, str, tuple[int, int, int, int, int, int, int, int], int], +]: ... +@overload +def GetTimeZoneInformation(times_as_tuples: Literal[False], /): ... + +def GetVersion() -> int: ... +def GetVersionEx(_format: int = ..., /) -> tuple[int, int, int, int, str]: ... +def GetVolumeInformation(path: str, /) -> tuple[str, int, int, int, str]: ... +def GetWindowsDirectory() -> str: ... +def GetWindowLong(hwnd: int | None, offset: int, /) -> int: ... +def GetUserDefaultLangID() -> int: ... +def GetUserDefaultLCID() -> int: ... +def GlobalMemoryStatus() -> dict[str, int]: ... +def GlobalMemoryStatusEx() -> dict[str, int]: ... +def keybd_event(bVk, bScan, dwFlags: int = ..., dwExtraInfo: int = ..., /) -> None: ... +def mouse_event(dx, dy, dwData, dwFlags: int = ..., dwExtraInfo=..., /) -> None: ... +def LoadCursor(hInstance: int, cursorid: _win32typing.PyResourceId, /) -> int: ... +def LoadKeyboardLayout(KLID: str, Flags: int = ..., /): ... +def LoadLibrary(fileName: str, /): ... +def LoadLibraryEx(fileName: str, handle: int, handle1, /) -> int: ... +def LoadResource(handle: int, _type: _win32typing.PyResourceId, name: _win32typing.PyResourceId, language, /) -> str: ... +def LoadString(handle: int, stringId, numChars: int = ..., /) -> str: ... +def MessageBeep(type: int = 0, /): ... +def MessageBox(hwnd: int | None, message: str, title: str | None = ..., style=..., language=..., /) -> int: ... +def MonitorFromPoint(pt: tuple[Incomplete, Incomplete], Flags: int = ...) -> int: ... +def MonitorFromRect(rc: _win32typing.PyRECT | tuple[int, int, int, int], Flags: int = ...) -> int: ... +def MonitorFromWindow(hwnd: int, Flags: int = ...) -> int: ... +def MoveFile(srcName: str, destName: str, /) -> None: ... +def MoveFileEx(srcName: str, destName: str, flag, /) -> None: ... +def OpenProcess(reqdAccess: int, bInherit: int | bool, pid: int, /) -> int: ... +def OutputDebugString(msg: str, /) -> None: ... +def PostMessage(hwnd: int, idMessage, wParam: Incomplete | None = ..., lParam: Incomplete | None = ..., /) -> None: ... +def PostQuitMessage(exitCode: int = ..., /) -> None: ... +def PostThreadMessage(tid, idMessage, wParam: Incomplete | None = ..., lParam: Incomplete | None = ..., /) -> None: ... +def RegCloseKey(key: _win32typing.PyHKEY, /) -> None: ... +def RegConnectRegistry(computerName: str, key, /): ... +def RegCopyTree(KeySrc: _win32typing.PyHKEY, SubKey: str, KeyDest: _win32typing.PyHKEY) -> None: ... +def RegCreateKey(key: _win32typing.PyHKEY | int, subKey: str, /) -> _win32typing.PyHKEY: ... +def RegCreateKeyEx( + Key: _win32typing.PyHKEY, + SubKey: str, + samDesired, + Class: str | None = ..., + Options=..., + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> tuple[_win32typing.PyHKEY, Incomplete]: ... +def RegDeleteKey(key: _win32typing.PyHKEY, subKey: str, /) -> None: ... +def RegDeleteKeyEx(Key: _win32typing.PyHKEY, SubKey: str, samDesired: int = ..., Transaction: int | None = ...) -> None: ... +def RegDeleteTree(Key: _win32typing.PyHKEY, SubKey: str) -> None: ... +def RegDeleteValue(key: _win32typing.PyHKEY, value: str, /) -> None: ... +def RegEnumKey(key: _win32typing.PyHKEY, index, /) -> str: ... +def RegEnumKeyEx(Key: _win32typing.PyHKEY, /): ... +def RegEnumKeyExW(Key: _win32typing.PyHKEY, /): ... +def RegEnumValue(key: _win32typing.PyHKEY, index, /) -> tuple[str, Incomplete, Incomplete]: ... +def RegFlushKey(key: _win32typing.PyHKEY, /) -> None: ... +def RegGetKeySecurity(key: _win32typing.PyHKEY, security_info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def RegLoadKey(key: _win32typing.PyHKEY, subKey: str, filename: str, /) -> None: ... +def RegOpenCurrentUser(samDesired=..., /) -> _win32typing.PyHKEY: ... +def RegOpenKey( + key: _win32typing.PyHKEY | int, subkey: str | None, reserved: bool = ..., sam: int = ..., / +) -> _win32typing.PyHKEY: ... +def RegOpenKeyEx(key: _win32typing.PyHKEY, subKey: str, sam: int, reserved: bool = ..., /) -> _win32typing.PyHKEY: ... +def RegOpenKeyTransacted( + Key: _win32typing.PyHKEY, SubKey: str, samDesired, Transaction: int, Options: int = ... +) -> _win32typing.PyHKEY: ... +def RegOverridePredefKey(Key: _win32typing.PyHKEY, NewKey: _win32typing.PyHKEY) -> None: ... +def RegQueryValue(key: _win32typing.PyHKEY | int, subKey: str | None, /) -> str: ... +def RegQueryValueEx(key: _win32typing.PyHKEY | int, valueName: str | None, /) -> tuple[str, int]: ... +def RegQueryInfoKey(key: _win32typing.PyHKEY, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def RegQueryInfoKeyW(Key: _win32typing.PyHKEY, /): ... +def RegRestoreKey(Key: _win32typing.PyHKEY, File: str, Flags: int = ...) -> None: ... +def RegSaveKey(key: _win32typing.PyHKEY, filename: str, sa: _win32typing.PySECURITY_ATTRIBUTES | None = ..., /) -> None: ... +def RegSaveKeyEx( + Key: _win32typing.PyHKEY, File: str, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., Flags=... +) -> None: ... +def RegSetKeySecurity(key: _win32typing.PyHKEY, security_info, sd: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def RegSetValue(key: _win32typing.PyHKEY, subKey: str | None, _type, value: str, /) -> None: ... +def RegSetValueEx(key: _win32typing.PyHKEY, valueName: str, reserved, _type, value, /) -> None: ... +def RegUnLoadKey(key: _win32typing.PyHKEY, subKey: str, /) -> None: ... +def RegisterWindowMessage(msgString: str, /) -> None: ... +def RegNotifyChangeKeyValue(key: _win32typing.PyHKEY, bWatchSubTree, dwNotifyFilter, hKey: int, fAsynchronous, /) -> None: ... +def SearchPath(path: str, fileName: str, fileExt: str | None = ..., /): ... +def SendMessage(hwnd: int, idMessage, wParam: str | None = ..., lParam: str | None = ..., /) -> None: ... +def SetConsoleCtrlHandler(ctrlHandler: Callable[[int], bool], bAdd: bool, /) -> None: ... +def SetConsoleTitle(title: str, /) -> None: ... +def SetCursorPos(arg: tuple[Incomplete, Incomplete], /) -> None: ... +def SetDllDirectory(PathName: str, /) -> None: ... +def SetErrorMode(errorMode, /): ... +def SetFileAttributes(pathName: str, attrs, /): ... +def SetLastError(errVal: int, /): ... +def SetSysColors(Elements, RgbValues, /) -> None: ... +def SetLocalTime(SystemTime: TimeType, /) -> None: ... +def SetSystemTime(year, month, dayOfWeek, day, hour, minute, second, millseconds, /): ... +def SetClassLong(hwnd: int, offset, val, /): ... +@deprecated("This function is obsolete, use `win32api.SetClassLong` instead.") +def SetClassWord(hwnd: int, offset, val, /): ... +def SetCursor(hCursor: int, /) -> int: ... +def SetEnvironmentVariable(Name, Value, /) -> None: ... +def SetEnvironmentVariableW(Name, Value, /) -> None: ... +def SetHandleInformation(Object: int, Mask, Flags, /) -> None: ... +def SetStdHandle(handle, handle1: int, /) -> None: ... +def SetSystemPowerState(Suspend, Force, /) -> None: ... +def SetThreadLocale(lcid, /) -> None: ... +def SetTimeZoneInformation(tzi, /): ... +def SetWindowLong(hwnd: int | None, offset: int, value: float, /) -> int: ... +@deprecated("This function is obsolete, use `win32api.SetWindowLong` instead.") +def SetWindowWord(hwnd, offset: int, val: int) -> int: ... +def ShellExecute(hwnd: int, op: str, file: str, params: str, _dir: str, bShow, /): ... +def ShowCursor(show, /): ... +def Sleep(time, bAlterable: int = ..., /): ... +def TerminateProcess(handle: int, exitCode: int, /) -> None: ... +def ToAsciiEx(vk, scancode, keyboardstate, flags: int = ..., hlayout: Incomplete | None = ..., /): ... +def UpdateResource( + handle: int, + type: _win32typing.PyResourceId | int, + name: _win32typing.PyResourceId | int, + data: ReadableBuffer | None, + language: int = ..., + /, +) -> None: ... +def VkKeyScan(char: str | bytes, /): ... +def WinExec(cmdLine: str, arg, /) -> None: ... +def WinHelp(hwnd: int, hlpFile: str, cmd, data: str | int = ..., /) -> None: ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def WriteProfileSection(section: str, data: str, iniName: str | None = ..., /): ... +@deprecated("This function is obsolete, applications should use the registry instead.") +def WriteProfileVal(section: str, entry: str, value: str, iniName: str | None = ..., /) -> None: ... +def HIBYTE(val: int, /) -> int: ... +def LOBYTE(val: int, /) -> int: ... +def HIWORD(val: int, /) -> int: ... +def LOWORD(val: int, /) -> int: ... +def RGB(red: int, green: int, blue: int, /) -> int: ... +def MAKELANGID(PrimaryLanguage, SubLanguage, /): ... +def MAKEWORD(low, high, /): ... +def MAKELONG(low, high, /): ... +def CommandLineToArgv(cmdLine: str, /) -> list[str]: ... +def GetKeyboardLayoutList() -> tuple[int, int]: ... +def MapVirtualKey(vk: int, type: int, hlayout=None, /) -> int: ... +def MessageBoxEx(hwnd, message: str, title: str | None = ..., style: int = ..., language: int = ..., /) -> int: ... +def OpenThread(reqdAccess: int, bInherit, pid: int, /): ... +def SleepEx(time: int, bAlterable=0, /) -> int: ... +def VkKeyScanEx(char: str | bytes, hkl, /) -> int: ... + +NameCanonical: int +NameCanonicalEx: int +NameDisplay: int +NameFullyQualifiedDN: int +NameSamCompatible: int +NameServicePrincipal: int +NameUniqueId: int +NameUnknown: int +NameUserPrincipal: int +PyDISPLAY_DEVICEType = _win32typing.PyDISPLAY_DEVICE +REG_NOTIFY_CHANGE_ATTRIBUTES: int +REG_NOTIFY_CHANGE_LAST_SET: int +REG_NOTIFY_CHANGE_NAME: int +REG_NOTIFY_CHANGE_SECURITY: int +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +VFT_APP: int +VFT_DLL: int +VFT_DRV: int +VFT_FONT: int +VFT_STATIC_LIB: int +VFT_UNKNOWN: int +VFT_VXD: int +VOS_DOS: int +VOS_DOS_WINDOWS16: int +VOS_DOS_WINDOWS32: int +VOS_NT: int +VOS_NT_WINDOWS32: int +VOS_OS216: int +VOS_OS216_PM16: int +VOS_OS232: int +VOS_OS232_PM32: int +VOS_UNKNOWN: int +VOS__PM16: int +VOS__PM32: int +VOS__WINDOWS16: int +VOS__WINDOWS32: int +VS_FF_DEBUG: int +VS_FF_INFOINFERRED: int +VS_FF_PATCHED: int +VS_FF_PRERELEASE: int +VS_FF_PRIVATEBUILD: int +VS_FF_SPECIALBUILD: int diff --git a/stubs/pywin32/win32/win32clipboard.pyi b/stubs/pywin32/win32/win32clipboard.pyi new file mode 100644 index 000000000000..27ed86573bbe --- /dev/null +++ b/stubs/pywin32/win32/win32clipboard.pyi @@ -0,0 +1,48 @@ +from typing import Any, Final + +from win32.lib.pywintypes import error as error + +def ChangeClipboardChain(hWndRemove: int, hWndNewNext: int, /): ... +def CloseClipboard(): ... +def CountClipboardFormats(): ... +def EmptyClipboard(): ... +def EnumClipboardFormats(_format: int = ..., /): ... +def GetClipboardData(_format, /) -> Any: ... # str or bytes depending on the dib format +def GetClipboardDataHandle(_format, /): ... +def GetClipboardFormatName(_format, /) -> str: ... +def GetClipboardOwner(): ... +def GetClipboardSequenceNumber(): ... +def GetClipboardViewer(): ... +def GetGlobalMemory(hglobal: int, /) -> str: ... +def GetOpenClipboardWindow(): ... +def GetPriorityClipboardFormat(formats, /): ... +def IsClipboardFormatAvailable(format: int, /) -> int: ... +def OpenClipboard(hWnd: int | None = ..., /): ... +def RegisterClipboardFormat(name: str, /): ... +def SetClipboardData(_format, hMem, /): ... +def SetClipboardText(text, _format, /): ... +def SetClipboardViewer(hWndNewViewer: int, /) -> int: ... + +CF_BITMAP: Final[int] +CF_DIB: Final[int] +CF_DIBV5: Final[int] +CF_DIF: Final[int] +CF_DSPBITMAP: Final[int] +CF_DSPENHMETAFILE: Final[int] +CF_DSPMETAFILEPICT: Final[int] +CF_DSPTEXT: Final[int] +CF_ENHMETAFILE: Final[int] +CF_HDROP: Final[int] +CF_LOCALE: Final[int] +CF_MAX: Final[int] +CF_METAFILEPICT: Final[int] +CF_OEMTEXT: Final[int] +CF_OWNERDISPLAY: Final[int] +CF_PALETTE: Final[int] +CF_PENDATA: Final[int] +CF_RIFF: Final[int] +CF_SYLK: Final[int] +CF_TEXT: Final[int] +CF_TIFF: Final[int] +CF_UNICODETEXT: Final[int] +CF_WAVE: Final[int] diff --git a/stubs/pywin32/win32/win32console.pyi b/stubs/pywin32/win32/win32console.pyi new file mode 100644 index 000000000000..e007253a2637 --- /dev/null +++ b/stubs/pywin32/win32/win32console.pyi @@ -0,0 +1,82 @@ +from typing import Literal, overload +from typing_extensions import Never + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetConsoleProcessList() -> tuple[int, ...]: ... +def CreateConsoleScreenBuffer( + DesiredAccess=..., ShareMode=..., SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., Flags=... +) -> _win32typing.PyConsoleScreenBuffer: ... +def GetConsoleDisplayMode(): ... +def AttachConsole(ProcessId) -> None: ... +def AllocConsole() -> None: ... +def FreeConsole() -> None: ... +def GetConsoleCP(): ... +def GetConsoleOutputCP(): ... +def SetConsoleCP(CodePageId) -> None: ... +def SetConsoleOutputCP(CodePageID) -> None: ... +def GetConsoleSelectionInfo(): ... +def AddConsoleAlias(Source, Target, ExeName) -> None: ... +def GetConsoleAliases(ExeName: str) -> str: ... +def GetConsoleAliasExes(): ... +def GetConsoleWindow(): ... +def GetNumberOfConsoleFonts(): ... +def SetConsoleTitle(ConsoleTitle: str) -> None: ... +def GetConsoleTitle(): ... + +@overload +def GenerateConsoleCtrlEvent(CtrlEvent: Literal[1], ProcessGroupId: Literal[0] = 0) -> Never: ... +@overload +def GenerateConsoleCtrlEvent(CtrlEvent: Literal[0, 1], ProcessGroupId: int) -> None: ... + +def GetStdHandle(StdHandle: int) -> _win32typing.PyConsoleScreenBuffer: ... + +ATTACH_PARENT_PROCESS: int +BACKGROUND_BLUE: int +BACKGROUND_GREEN: int +BACKGROUND_INTENSITY: int +BACKGROUND_RED: int +COMMON_LVB_GRID_HORIZONTAL: int +COMMON_LVB_GRID_LVERTICAL: int +COMMON_LVB_GRID_RVERTICAL: int +COMMON_LVB_LEADING_BYTE: int +COMMON_LVB_REVERSE_VIDEO: int +COMMON_LVB_TRAILING_BYTE: int +COMMON_LVB_UNDERSCORE: int +CONSOLE_FULLSCREEN: int +CONSOLE_FULLSCREEN_HARDWARE: int +CONSOLE_FULLSCREEN_MODE: int +CONSOLE_MOUSE_DOWN: int +CONSOLE_MOUSE_SELECTION: int +CONSOLE_NO_SELECTION: int +CONSOLE_SELECTION_IN_PROGRESS: int +CONSOLE_SELECTION_NOT_EMPTY: int +CONSOLE_TEXTMODE_BUFFER: int +CONSOLE_WINDOWED_MODE: int +CTRL_BREAK_EVENT: int +CTRL_C_EVENT: int +ENABLE_ECHO_INPUT: int +ENABLE_LINE_INPUT: int +ENABLE_MOUSE_INPUT: int +ENABLE_PROCESSED_INPUT: int +ENABLE_PROCESSED_OUTPUT: int +ENABLE_WINDOW_INPUT: int +ENABLE_WRAP_AT_EOL_OUTPUT: int +FOCUS_EVENT: int +FOREGROUND_BLUE: int +FOREGROUND_GREEN: int +FOREGROUND_INTENSITY: int +FOREGROUND_RED: int +KEY_EVENT: int +LOCALE_USER_DEFAULT: int +MENU_EVENT: int +MOUSE_EVENT: int +PyCOORDType = _win32typing.PyCOORD +PyConsoleScreenBufferType = _win32typing.PyConsoleScreenBuffer +PyINPUT_RECORDType = _win32typing.PyINPUT_RECORD +PySMALL_RECTType = _win32typing.PySMALL_RECT +STD_ERROR_HANDLE: int +STD_INPUT_HANDLE: int +STD_OUTPUT_HANDLE: int +WINDOW_BUFFER_SIZE_EVENT: int diff --git a/stubs/pywin32/win32/win32cred.pyi b/stubs/pywin32/win32/win32cred.pyi new file mode 100644 index 000000000000..e0b9c52d303d --- /dev/null +++ b/stubs/pywin32/win32/win32cred.pyi @@ -0,0 +1,91 @@ +from _typeshed import Incomplete + +def CredMarshalCredential(CredType, Credential: str) -> str: ... +def CredUnmarshalCredential(MarshaledCredential: str) -> tuple[Incomplete, str]: ... +def CredIsMarshaledCredential(MarshaledCredential: str) -> bool: ... +def CredEnumerate(Filter: str | None = ..., Flags: int = ...) -> tuple[dict[str, Incomplete], ...]: ... +def CredGetTargetInfo(TargetName: str, Flags: int = ...): ... +def CredGetSessionTypes(MaximumPersistCount: int = 7) -> tuple[int, ...]: ... +def CredWriteDomainCredentials(TargetInfo, Credential, Flags: int = ...) -> None: ... +def CredReadDomainCredentials(TargetInfo, Flags: int = ...) -> tuple[Incomplete, ...]: ... +def CredDelete(TargetName: str, Type, Flags: int = ...) -> None: ... +def CredWrite(Credential, Flags: int = ...) -> None: ... +def CredRead(TargetName: str, Type, Flags: int = ...): ... +def CredRename(OldTargetName: str, NewTargetName: str, Type, Flags: int = ...): ... +def CredUICmdLinePromptForCredentials( + TargetName: str, AuthError: int = ..., UserName: str | None = ..., Password: str | None = ..., Save: int = ..., Flags=... +) -> tuple[str, str, Incomplete]: ... +def CredUIPromptForCredentials( + TargetName: str, + AuthError: int = ..., + UserName: str | None = ..., + Password: str | None = ..., + Save: bool = ..., + Flags: int = ..., + UiInfo: Incomplete | None = ..., +) -> tuple[str, str, Incomplete]: ... +def CredUIConfirmCredentials(TargetName: str, Confirm) -> None: ... +def CredUIReadSSOCredW(Realm: str | None = ...) -> str: ... +def CredUIStoreSSOCredW(Realm: str, Username: str, Password: str, Persist) -> None: ... +def CredUIParseUserName(UserName: str) -> tuple[str, str]: ... + +CREDUI_FLAGS_ALWAYS_SHOW_UI: int +CREDUI_FLAGS_COMPLETE_USERNAME: int +CREDUI_FLAGS_DO_NOT_PERSIST: int +CREDUI_FLAGS_EXCLUDE_CERTIFICATES: int +CREDUI_FLAGS_EXPECT_CONFIRMATION: int +CREDUI_FLAGS_GENERIC_CREDENTIALS: int +CREDUI_FLAGS_INCORRECT_PASSWORD: int +CREDUI_FLAGS_KEEP_USERNAME: int +CREDUI_FLAGS_PASSWORD_ONLY_OK: int +CREDUI_FLAGS_PERSIST: int +CREDUI_FLAGS_PROMPT_VALID: int +CREDUI_FLAGS_REQUEST_ADMINISTRATOR: int +CREDUI_FLAGS_REQUIRE_CERTIFICATE: int +CREDUI_FLAGS_REQUIRE_SMARTCARD: int +CREDUI_FLAGS_SERVER_CREDENTIAL: int +CREDUI_FLAGS_SHOW_SAVE_CHECK_BOX: int +CREDUI_FLAGS_USERNAME_TARGET_CREDENTIALS: int +CREDUI_FLAGS_VALIDATE_USERNAME: int +CREDUI_MAX_CAPTION_LENGTH: int +CREDUI_MAX_DOMAIN_TARGET_LENGTH: int +CREDUI_MAX_GENERIC_TARGET_LENGTH: int +CREDUI_MAX_MESSAGE_LENGTH: int +CREDUI_MAX_PASSWORD_LENGTH: int +CREDUI_MAX_USERNAME_LENGTH: int +CRED_ALLOW_NAME_RESOLUTION: int +CRED_CACHE_TARGET_INFORMATION: int +CRED_ENUMERATE_ALL_CREDENTIALS: int +CRED_FLAGS_OWF_CRED_BLOB: int +CRED_FLAGS_PASSWORD_FOR_CERT: int +CRED_FLAGS_PROMPT_NOW: int +CRED_FLAGS_USERNAME_TARGET: int +CRED_FLAGS_VALID_FLAGS: int +CRED_MAX_ATTRIBUTES: int +CRED_MAX_DOMAIN_TARGET_NAME_LENGTH: int +CRED_MAX_GENERIC_TARGET_NAME_LENGTH: int +CRED_MAX_STRING_LENGTH: int +CRED_MAX_USERNAME_LENGTH: int +CRED_MAX_VALUE_SIZE: int +CRED_PERSIST_ENTERPRISE: int +CRED_PERSIST_LOCAL_MACHINE: int +CRED_PERSIST_NONE: int +CRED_PERSIST_SESSION: int +CRED_PRESERVE_CREDENTIAL_BLOB: int +CRED_TI_CREATE_EXPLICIT_CRED: int +CRED_TI_DOMAIN_FORMAT_UNKNOWN: int +CRED_TI_ONLY_PASSWORD_REQUIRED: int +CRED_TI_SERVER_FORMAT_UNKNOWN: int +CRED_TI_USERNAME_TARGET: int +CRED_TI_VALID_FLAGS: int +CRED_TI_WORKGROUP_MEMBER: int +CRED_TYPE_DOMAIN_CERTIFICATE: int +CRED_TYPE_DOMAIN_EXTENDED: int +CRED_TYPE_DOMAIN_PASSWORD: int +CRED_TYPE_DOMAIN_VISIBLE_PASSWORD: int +CRED_TYPE_GENERIC: int +CRED_TYPE_GENERIC_CERTIFICATE: int +CRED_TYPE_MAXIMUM: int +CRED_TYPE_MAXIMUM_EX: int +CertCredential: int +UsernameTargetCredential: int diff --git a/stubs/pywin32/win32/win32crypt.pyi b/stubs/pywin32/win32/win32crypt.pyi new file mode 100644 index 000000000000..3bde0ede1ac6 --- /dev/null +++ b/stubs/pywin32/win32/win32crypt.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete + +import _win32typing + +def CryptProtectData( + DataIn, + DataDescr: str | None = ..., + OptionalEntropy: Incomplete | None = ..., + Reserved: Incomplete | None = ..., + PromptStruct: _win32typing.PyCRYPTPROTECT_PROMPTSTRUCT | None = ..., + Flags: int = ..., +): ... +def CryptUnprotectData( + DataIn, + OptionalEntropy: Incomplete | None = ..., + Reserved: Incomplete | None = ..., + PromptStruct: _win32typing.PyCRYPTPROTECT_PROMPTSTRUCT | None = ..., + Flags: int = ..., +) -> tuple[Incomplete, Incomplete]: ... +def CryptEnumProviders() -> list[tuple[str, Incomplete]]: ... +def CryptEnumProviderTypes() -> list[tuple[str, Incomplete]]: ... +def CryptGetDefaultProvider(ProvType, Flags) -> str: ... +def CryptSetProviderEx(ProvName: str, ProvType, Flags) -> None: ... +def CryptAcquireContext(Container: str, Provider: str, ProvType, Flags) -> _win32typing.PyCRYPTPROV: ... +def CryptFindLocalizedName(CryptName: str) -> str: ... +def CertEnumSystemStore(Flags, SystemStoreLocationPara: Incomplete | None = ...) -> list[Incomplete]: ... +def CertEnumSystemStoreLocation(Flags: int = ...) -> list[Incomplete]: ... +def CertEnumPhysicalStore(SystemStore: str, Flags) -> list[Incomplete]: ... +def CertRegisterSystemStore(SystemStore: str, Flags) -> None: ... +def CertUnregisterSystemStore(SystemStore: str, Flags) -> None: ... +def CertOpenStore( + StoreProvider, MsgAndCertEncodingType, CryptProv: _win32typing.PyCRYPTPROV, Flags, Para: Incomplete | None +) -> _win32typing.PyCERTSTORE: ... +def CertOpenSystemStore(SubsystemProtocol: str, Prov: _win32typing.PyCRYPTPROV | None = ...) -> _win32typing.PyCERTSTORE: ... +def CryptFindOIDInfo(KeyType, Key, GroupId: int = ...): ... +def CertAlgIdToOID(AlgId) -> str: ... +def CertOIDToAlgId(ObjId: str): ... +def CryptGetKeyIdentifierProperty(KeyIdentifier: str, PropId=..., Flags: int = ..., ComputerName: str | None = ...): ... +def CryptEnumKeyIdentifierProperties( + KeyIdentifier: str | None = ..., PropId: int = ..., Flags: int = ..., ComputerName: str | None = ... +): ... +def CryptEnumOIDInfo(GroupId: int = ...): ... +def CertAddSerializedElementToStore( + CertStore: _win32typing.PyCERTSTORE, Element, AddDisposition, ContextTypeFlags=..., Flags: int = ... +) -> _win32typing.PyCERT_CONTEXT: ... +def CryptQueryObject(ObjectType, Object, ExpectedContentTypeFlags=..., ExpectedFormatTypeFlags=..., Flags: int = ...): ... +def CryptDecodeMessage( + EncodedBlob, + DecryptPara, + VerifyPara: Incomplete | None = ..., + MsgTypeFlags=..., + SignerIndex: int = ..., + PrevInnerContentType: int = ..., + ReturnData: bool = ..., +): ... +def CryptEncryptMessage( + EncryptPara: _win32typing.PyCRYPT_ENCRYPT_MESSAGE_PARA, RecipientCert: tuple[_win32typing.PyCERT_CONTEXT, ...], ToBeEncrypted +): ... +def CryptDecryptMessage( + DecryptPara: _win32typing.PyCRYPT_DECRYPT_MESSAGE_PARA, EncryptedBlob +) -> tuple[Incomplete, _win32typing.PyCERT_CONTEXT]: ... +def CryptSignAndEncryptMessage( + SignPara: _win32typing.PyCRYPT_SIGN_MESSAGE_PARA, + EncryptPara: _win32typing.PyCRYPT_ENCRYPT_MESSAGE_PARA, + RecipientCert: tuple[_win32typing.PyCERT_CONTEXT, ...], + ToBeSignedAndEncrypted, +): ... +def CryptVerifyMessageSignature( + SignedBlob, SignerIndex: int = ..., VerifyPara: _win32typing.PyCRYPT_VERIFY_MESSAGE_PARA | None = ..., ReturnData: bool = ... +) -> tuple[_win32typing.PyCERT_CONTEXT, Incomplete]: ... +def CryptGetMessageCertificates( + SignedBlob, MsgAndCertEncodingType=..., CryptProv: _win32typing.PyCRYPTPROV | None = ..., Flags: int = ... +) -> _win32typing.PyCERTSTORE: ... +def CryptGetMessageSignerCount(SignedBlob, MsgEncodingType=...): ... +def CryptSignMessage( + SignPara: _win32typing.PyCRYPT_SIGN_MESSAGE_PARA, ToBeSigned: tuple[Incomplete, ...], DetachedSignature: bool = ... +): ... +def CryptVerifyDetachedMessageSignature( + SignerIndex, + DetachedSignBlob, + ToBeSigned: tuple[Incomplete, ...], + VerifyPara: _win32typing.PyCRYPT_VERIFY_MESSAGE_PARA | None = ..., +) -> _win32typing.PyCERT_CONTEXT: ... +def CryptDecryptAndVerifyMessageSignature( + EncryptedBlob, + DecryptPara: _win32typing.PyCRYPT_DECRYPT_MESSAGE_PARA, + VerifyPara: _win32typing.PyCRYPT_VERIFY_MESSAGE_PARA | None = ..., + SignerIndex: int = ..., +): ... +def CryptEncodeObjectEx( + StructType, StructInfo=..., Flags: int = ..., CertEncodingType=..., EncodePara: Incomplete | None = ... +): ... +def CryptDecodeObjectEx(StructType, Encoded, Flags: int = ..., CertEncodingType=..., DecodePara: Incomplete | None = ...): ... +def CertNameToStr(Name, StrType, CertEncodingType): ... +def CryptFormatObject( + StructType, + Encoded, + FormatStrType: int = ..., + CertEncodingType=..., + FormatType: int = ..., + FormatStruct: Incomplete | None = ..., +): ... +def PFXImportCertStore(PFX, Password, Flags) -> _win32typing.PyCERTSTORE: ... +def PFXVerifyPassword(PFX, Password, Flags): ... +def PFXIsPFXBlob(PFX): ... +def CryptBinaryToString(Binary, Flags): ... +def CryptStringToBinary(String, Flags) -> tuple[Incomplete, Incomplete, Incomplete]: ... diff --git a/stubs/pywin32/win32/win32event.pyi b/stubs/pywin32/win32/win32event.pyi new file mode 100644 index 000000000000..a79bb40f86b4 --- /dev/null +++ b/stubs/pywin32/win32/win32event.pyi @@ -0,0 +1,69 @@ +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def CancelWaitableTimer() -> None: ... +def CreateEvent( + EventAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + bManualReset: int | bool, + bInitialState: int | bool, + Name: str | None, + /, +) -> int: ... +def CreateMutex(MutexAttributes: _win32typing.PySECURITY_ATTRIBUTES, InitialOwner, Name: str, /) -> _win32typing.PyHANDLE: ... +def CreateSemaphore( + SemaphoreAttributes: _win32typing.PySECURITY_ATTRIBUTES, InitialCount, MaximumCount, SemaphoreName, / +) -> int: ... +def CreateWaitableTimer(TimerAttributes: _win32typing.PySECURITY_ATTRIBUTES, ManualReset, TimerName, /) -> int: ... +def CreateWaitableTimerEx( + lpTimerAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, lpTimerName: str | None, dwFlags: int, dwDesiredAccess: int, / +) -> _win32typing.PyHANDLE: ... +def MsgWaitForMultipleObjects(handlelist: Iterable[int], bWaitAll: int, milliseconds: int, wakeMask: int, /) -> int: ... +def MsgWaitForMultipleObjectsEx(handlelist: list[int], milliseconds, wakeMask, waitFlags, /): ... +def OpenEvent(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenMutex(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenSemaphore(desiredAccess, bInheritHandle, name: str, /) -> int: ... +def OpenWaitableTimer(desiredAccess, bInheritHandle, timerName, /) -> int: ... +def PulseEvent(hEvent: int, /) -> None: ... +def ReleaseMutex(hEvent: int, /) -> None: ... +def ReleaseSemaphore(hEvent: int, lReleaseCount, /): ... +def ResetEvent(hEvent: int, /) -> None: ... +def SetEvent(hEvent: int, /) -> None: ... +def SetWaitableTimer(handle: int, dueTime, period, func, param, resume_state, /) -> None: ... +def WaitForMultipleObjects(handlelist: list[int], bWaitAll, milliseconds, /): ... +def WaitForMultipleObjectsEx(handlelist: list[int], bWaitAll, milliseconds, bAlertable, /): ... +def WaitForSingleObject(hHandle: int, milliseconds: int, /) -> int: ... +def WaitForSingleObjectEx(hHandle: int, milliseconds, bAlertable, /): ... +def WaitForInputIdle(hProcess: int, milliseconds, /): ... +def SignalObjectAndWait(hSignal, hWaitOn, milliseconds, bAlertable, /): ... + +CREATE_WAITABLE_TIMER_HIGH_RESOLUTION: int +CREATE_WAITABLE_TIMER_MANUAL_RESET: int +EVENT_ALL_ACCESS: int +EVENT_MODIFY_STATE: int +INFINITE: int +MAXIMUM_WAIT_OBJECTS: int +QS_ALLEVENTS: int +QS_ALLINPUT: int +QS_HOTKEY: int +QS_INPUT: int +QS_KEY: int +QS_MOUSE: int +QS_MOUSEBUTTON: int +QS_MOUSEMOVE: int +QS_PAINT: int +QS_POSTMESSAGE: int +QS_SENDMESSAGE: int +QS_TIMER: int +SYNCHRONIZE: int +TIMER_ALL_ACCESS: int +TIMER_MODIFY_STATE: int +TIMER_QUERY_STATE: int +WAIT_ABANDONED: int +WAIT_ABANDONED_0: int +WAIT_FAILED: int +WAIT_IO_COMPLETION: int +WAIT_OBJECT_0: int +WAIT_TIMEOUT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32evtlog.pyi b/stubs/pywin32/win32/win32evtlog.pyi new file mode 100644 index 000000000000..8b3ce18ddb22 --- /dev/null +++ b/stubs/pywin32/win32/win32evtlog.pyi @@ -0,0 +1,272 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def ReadEventLog( + Handle: _win32typing.PyEVTLOG_HANDLE, Flags: int, Offset: int, Size=..., / +) -> list[_win32typing.PyEventLogRecord]: ... +def ClearEventLog(handle: _win32typing.PyEVTLOG_HANDLE, eventLogName: str, /) -> None: ... +def BackupEventLog(handle, eventLogName: str, /) -> None: ... +def CloseEventLog(handle: _win32typing.PyEVTLOG_HANDLE, /) -> None: ... +def DeregisterEventSource(handle, /) -> None: ... +def NotifyChangeEventLog(handle, handle1, /) -> None: ... +def GetNumberOfEventLogRecords(handle: _win32typing.PyEVTLOG_HANDLE, /) -> int: ... +def GetOldestEventLogRecord(): ... +def OpenEventLog(serverName: str | None, sourceName: str, /) -> _win32typing.PyEVTLOG_HANDLE: ... +def RegisterEventSource(serverName: str | None, sourceName: str, /): ... +def OpenBackupEventLog(serverName: str, fileName: str, /) -> _win32typing.PyEVTLOG_HANDLE: ... +def ReportEvent( + EventLog: int, + Type: int, + Category: int, + EventID: int, + UserSid: _win32typing.PySID | None, + Strings: Iterable[str] | None, + RawData: bytes | None, + /, +) -> None: ... +def EvtOpenChannelEnum(Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtFormatMessage(Metadata, Event, Flags, ResourceId=...): ... +def EvtNextChannelPath(ChannelEnum: _win32typing.PyEVT_HANDLE): ... +def EvtOpenLog(Path, Flags, Session: _win32typing.PyEVT_HANDLE | None = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtClearLog( + ChannelPath, TargetFilePath: Incomplete | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ... +) -> None: ... +def EvtExportLog( + Path, TargetFilePath, Flags, Query: Incomplete | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ... +) -> None: ... +def EvtArchiveExportedLog(LogFilePath, Locale, Session: _win32typing.PyEVT_HANDLE | None = ..., Flags=...) -> None: ... +def EvtGetExtendedStatus(): ... +def EvtQuery( + Path: str, Flags: int, Query: str | None = ..., Session: _win32typing.PyEVT_HANDLE | None = ... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtNext( + ResultSet: _win32typing.PyEVT_HANDLE, Count: int, Timeout: int = ..., Flags: int = ... +) -> tuple[_win32typing.PyEVT_HANDLE, ...]: ... +def EvtSeek( + ResultSet: _win32typing.PyEVT_HANDLE, Position, Flags, Bookmark: _win32typing.PyEVT_HANDLE | None = ..., Timeout: int = ... +) -> None: ... +def EvtCreateRenderContext(Flags): ... +def EvtRender(Event: _win32typing.PyEVT_HANDLE, Flags: int, Context=...): ... +def EvtSubscribe( + ChannelPath, + Flags, + SignalEvent: Incomplete | None = ..., + Callback: Incomplete | None = ..., + Context: Incomplete | None = ..., + Query: Incomplete | None = ..., + Session: _win32typing.PyEVT_HANDLE | None = ..., + Bookmark: _win32typing.PyEVT_HANDLE | None = ..., +) -> _win32typing.PyEVT_HANDLE: ... +def EvtCreateBookmark(BookmarkXML: Incomplete | None = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtUpdateBookmark(Bookmark: _win32typing.PyEVT_HANDLE, Event: _win32typing.PyEVT_HANDLE) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetChannelConfigProperty( + ChannelConfig: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtOpenChannelConfig( + ChannelPath, Session: _win32typing.PyEVT_HANDLE | None = ..., Flags=... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtOpenSession( + Login: _win32typing.PyEVT_RPC_LOGIN, LoginClass, Timeout: int = ..., Flags=... +) -> _win32typing.PyEVT_HANDLE: ... +def EvtOpenPublisherEnum(Session: _win32typing.PyEVT_HANDLE | None = ..., Flags: int = ...) -> _win32typing.PyEVT_HANDLE: ... +def EvtNextPublisherId(PublisherEnum: _win32typing.PyEVT_HANDLE): ... +def EvtOpenPublisherMetadata( + PublisherIdentity: str, + Session: _win32typing.PyEVT_HANDLE | None = ..., + LogFilePath: Incomplete | None = ..., + Locale: int = ..., + Flags: int = ..., +) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetPublisherMetadataProperty( + PublisherMetadata: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtOpenEventMetadataEnum(PublisherMetadata: _win32typing.PyEVT_HANDLE, Flags=...) -> _win32typing.PyEVT_HANDLE: ... +def EvtNextEventMetadata(EventMetadataEnum: _win32typing.PyEVT_HANDLE, Flags=...) -> _win32typing.PyEVT_HANDLE: ... +def EvtGetEventMetadataProperty( + EventMetadata: _win32typing.PyEVT_HANDLE, PropertyId, Flags=... +) -> tuple[Incomplete, Incomplete]: ... +def EvtGetLogInfo(Log: _win32typing.PyEVT_HANDLE, PropertyId) -> tuple[Incomplete, Incomplete]: ... +def EvtGetEventInfo(Event: _win32typing.PyEVT_HANDLE, PropertyId) -> tuple[Incomplete, Incomplete]: ... +def EvtGetObjectArraySize(ObjectArray: _win32typing.PyEVT_HANDLE): ... +def EvtGetObjectArrayProperty( + ObjectArray: _win32typing.PyEVT_HANDLE, PropertyId, ArrayIndex, Flags=... +) -> tuple[Incomplete, Incomplete]: ... + +EVENTLOG_AUDIT_FAILURE: int +EVENTLOG_AUDIT_SUCCESS: int +EVENTLOG_BACKWARDS_READ: int +EVENTLOG_END_ALL_PAIRED_EVENTS: int +EVENTLOG_END_PAIRED_EVENT: int +EVENTLOG_ERROR_TYPE: int +EVENTLOG_FORWARDS_READ: int +EVENTLOG_INFORMATION_TYPE: int +EVENTLOG_PAIRED_EVENT_ACTIVE: int +EVENTLOG_PAIRED_EVENT_INACTIVE: int +EVENTLOG_SEEK_READ: int +EVENTLOG_SEQUENTIAL_READ: int +EVENTLOG_START_PAIRED_EVENT: int +EVENTLOG_SUCCESS: int +EVENTLOG_WARNING_TYPE: int +EventMetadataEventChannel: int +EventMetadataEventID: int +EventMetadataEventKeyword: int +EventMetadataEventLevel: int +EventMetadataEventMessageID: int +EventMetadataEventOpcode: int +EventMetadataEventTask: int +EventMetadataEventTemplate: int +EventMetadataEventVersion: int +EvtChannelConfigAccess: int +EvtChannelConfigClassicEventlog: int +EvtChannelConfigEnabled: int +EvtChannelConfigIsolation: int +EvtChannelConfigOwningPublisher: int +EvtChannelConfigPropertyIdEND: int +EvtChannelConfigType: int +EvtChannelLoggingConfigAutoBackup: int +EvtChannelLoggingConfigLogFilePath: int +EvtChannelLoggingConfigMaxSize: int +EvtChannelLoggingConfigRetention: int +EvtChannelPublishingConfigBufferSize: int +EvtChannelPublishingConfigClockType: int +EvtChannelPublishingConfigControlGuid: int +EvtChannelPublishingConfigKeywords: int +EvtChannelPublishingConfigLatency: int +EvtChannelPublishingConfigLevel: int +EvtChannelPublishingConfigMaxBuffers: int +EvtChannelPublishingConfigMinBuffers: int +EvtChannelPublishingConfigSidType: int +EvtEventMetadataPropertyIdEND: int +EvtEventPath: int +EvtEventPropertyIdEND: int +EvtEventQueryIDs: int +EvtExportLogChannelPath: int +EvtExportLogFilePath: int +EvtExportLogTolerateQueryErrors: int +EvtLogAttributes: int +EvtLogCreationTime: int +EvtLogFileSize: int +EvtLogFull: int +EvtLogLastAccessTime: int +EvtLogLastWriteTime: int +EvtLogNumberOfLogRecords: int +EvtLogOldestRecordNumber: int +EvtOpenChannelPath: int +EvtOpenFilePath: int +EvtPublisherMetadataChannelReferenceFlags: int +EvtPublisherMetadataChannelReferenceID: int +EvtPublisherMetadataChannelReferenceIndex: int +EvtPublisherMetadataChannelReferenceMessageID: int +EvtPublisherMetadataChannelReferencePath: int +EvtPublisherMetadataChannelReferences: int +EvtPublisherMetadataHelpLink: int +EvtPublisherMetadataKeywordMessageID: int +EvtPublisherMetadataKeywordName: int +EvtPublisherMetadataKeywords: int +EvtPublisherMetadataKeywordValue: int +EvtPublisherMetadataLevelMessageID: int +EvtPublisherMetadataLevelName: int +EvtPublisherMetadataLevels: int +EvtPublisherMetadataLevelValue: int +EvtPublisherMetadataMessageFilePath: int +EvtPublisherMetadataOpcodeMessageID: int +EvtPublisherMetadataOpcodeName: int +EvtPublisherMetadataOpcodes: int +EvtPublisherMetadataOpcodeValue: int +EvtPublisherMetadataParameterFilePath: int +EvtPublisherMetadataPropertyIdEND: int +EvtPublisherMetadataPublisherGuid: int +EvtPublisherMetadataPublisherMessageID: int +EvtPublisherMetadataResourceFilePath: int +EvtPublisherMetadataTaskEventGuid: int +EvtPublisherMetadataTaskMessageID: int +EvtPublisherMetadataTaskName: int +EvtPublisherMetadataTasks: int +EvtPublisherMetadataTaskValue: int +EvtQueryChannelPath: int +EvtQueryFilePath: int +EvtQueryForwardDirection: int +EvtQueryReverseDirection: int +EvtQueryTolerateQueryErrors: int +EvtRenderBookmark: int +EvtRenderEventValues: int +EvtRenderEventXml: int +EvtRpcLogin: int +EvtRpcLoginAuthDefault: int +EvtRpcLoginAuthKerberos: int +EvtRpcLoginAuthNegotiate: int +EvtRpcLoginAuthNTLM: int +EvtSeekOriginMask: int +EvtSeekRelativeToBookmark: int +EvtSeekRelativeToCurrent: int +EvtSeekRelativeToFirst: int +EvtSeekRelativeToLast: int +EvtSeekStrict: int +EvtSubscribeActionDeliver: int +EvtSubscribeActionError: int +EvtSubscribeOriginMask: int +EvtSubscribeStartAfterBookmark: int +EvtSubscribeStartAtOldestRecord: int +EvtSubscribeStrict: int +EvtSubscribeToFutureEvents: int +EvtSubscribeTolerateQueryErrors: int +EvtVarTypeAnsiString: int +EvtVarTypeBinary: int +EvtVarTypeBoolean: int +EvtVarTypeByte: int +EvtVarTypeDouble: int +EvtVarTypeEvtHandle: int +EvtVarTypeEvtXml: int +EvtVarTypeFileTime: int +EvtVarTypeGuid: int +EvtVarTypeHexInt32: int +EvtVarTypeHexInt64: int +EvtVarTypeInt16: int +EvtVarTypeInt32: int +EvtVarTypeInt64: int +EvtVarTypeNull: int +EvtVarTypeSByte: int +EvtVarTypeSid: int +EvtVarTypeSingle: int +EvtVarTypeSizeT: int +EvtVarTypeString: int +EvtVarTypeSysTime: int +EvtVarTypeUInt16: int +EvtVarTypeUInt32: int +EvtVarTypeUInt64: int +EvtChannelPublisherList: int +EvtFormatMessageChannel: int +EvtFormatMessageEvent: int +EvtFormatMessageId: int +EvtFormatMessageKeyword: int +EvtFormatMessageLevel: int +EvtFormatMessageOpcode: int +EvtFormatMessageProvider: int +EvtFormatMessageTask: int +EvtFormatMessageXml: int +EvtRenderContextSystem: int +EvtRenderContextUser: int +EvtRenderContextValues: int +EvtSystemActivityID: int +EvtSystemChannel: int +EvtSystemComputer: int +EvtSystemEventID: int +EvtSystemEventRecordId: int +EvtSystemKeywords: int +EvtSystemLevel: int +EvtSystemOpcode: int +EvtSystemProcessID: int +EvtSystemPropertyIdEND: int +EvtSystemProviderGuid: int +EvtSystemProviderName: int +EvtSystemQualifiers: int +EvtSystemRelatedActivityID: int +EvtSystemTask: int +EvtSystemThreadID: int +EvtSystemTimeCreated: int +EvtSystemUserID: int +EvtSystemVersion: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32file.pyi b/stubs/pywin32/win32/win32file.pyi new file mode 100644 index 000000000000..34443c808ade --- /dev/null +++ b/stubs/pywin32/win32/win32file.pyi @@ -0,0 +1,485 @@ +from _typeshed import Incomplete +from socket import socket +from typing import overload +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +def AreFileApisANSI(): ... +def CancelIo(handle: int, /) -> None: ... +def CopyFile(_from: str, to: str, bFailIfExists, /) -> None: ... +def CopyFileW(_from: str, to: str, bFailIfExists, /) -> None: ... +def CreateDirectory(name: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateDirectoryW(name: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateDirectoryEx(templateName: str, newDirectory: str, sa: _win32typing.PySECURITY_ATTRIBUTES, /) -> None: ... +def CreateFile( + fileName: str, + desiredAccess: int, + shareMode: int, + attributes: _win32typing.PySECURITY_ATTRIBUTES | None, + CreationDisposition: int, + flagsAndAttributes: int, + hTemplateFile: int | None, + /, +) -> _win32typing.PyHANDLE: ... +def CreateIoCompletionPort(handle: int, existing: int, completionKey, numThreads, /) -> int: ... +def CreateMailslot(Name, MaxMessageSize, ReadTimeout, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, /) -> int: ... +def GetMailslotInfo(Mailslot: int, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def SetMailslotInfo(Mailslot: int, ReadTimeout, /) -> None: ... +def DefineDosDevice(flags, deviceName: str, targetPath: str, /) -> None: ... +def DefineDosDeviceW(flags, deviceName: str, targetPath: str, /) -> None: ... +def DeleteFile(fileName: str, /) -> None: ... +def DeviceIoControl(Device: int, IoControlCode, InBuffer, OutBuffer, Overlapped: _win32typing.PyOVERLAPPED | None = ...): ... +def FindClose(hFindFile, /) -> None: ... +def FindCloseChangeNotification(hChangeHandle, /) -> None: ... +def FindFirstChangeNotification(pathName: str, bWatchSubtree, notifyFilter, /): ... +def FindNextChangeNotification(hChangeHandle, /): ... +def FlushFileBuffers(hFile: int, /) -> None: ... +def GetBinaryType(appName: str, /) -> int: ... +def GetDiskFreeSpace(rootPathName: str, /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def GetDiskFreeSpaceEx(rootPathName: str, /) -> tuple[int, int, int]: ... +def GetDriveType(rootPathName: str, /): ... +def GetDriveTypeW(rootPathName: str, /): ... +def GetFileAttributes(fileName: str, /): ... +def GetFileAttributesW(fileName: str, /): ... +def GetFileTime( + handle: int, creationTime: TimeType, accessTime: TimeType, writeTime: TimeType, / +) -> tuple[TimeType, TimeType, TimeType]: ... +def SetFileTime( + File: int, + CreationTime: TimeType | None = ..., + LastAccessTime: TimeType | None = ..., + LastWriteTime: TimeType | None = ..., + UTCTimes: bool = ..., +) -> None: ... +def GetFileInformationByHandle(handle: int, /): ... +def GetCompressedFileSize(): ... +def GetFileSize(): ... +def AllocateReadBuffer(bufSize: int, /) -> _win32typing.PyOVERLAPPEDReadBuffer: ... + +@overload +def ReadFile(hFile: int, bufSize: int, /) -> tuple[int, str]: ... +@overload +def ReadFile( + hFile: int, buffer: _win32typing.PyOVERLAPPEDReadBuffer, overlapped: _win32typing.PyOVERLAPPED | None, / +) -> tuple[int, str]: ... + +def WriteFile( + hFile: int, data: str | bytes | _win32typing.PyOVERLAPPEDReadBuffer, ol: _win32typing.PyOVERLAPPED | None = ..., / +) -> tuple[int, int]: ... +def CloseHandle(handle: int, /) -> None: ... +def LockFileEx(hFile: int, _int, _int1, _int2, ol: _win32typing.PyOVERLAPPED | None = ..., /) -> None: ... +def UnlockFileEx(hFile: int, _int, _int1, ol: _win32typing.PyOVERLAPPED | None = ..., /) -> None: ... +def GetQueuedCompletionStatus(hPort: int, timeOut, /) -> tuple[Incomplete, Incomplete, Incomplete, _win32typing.PyOVERLAPPED]: ... +def PostQueuedCompletionStatus( + handle: int, numberOfbytes: int = ..., completionKey: int = ..., overlapped: _win32typing.PyOVERLAPPED | None = ..., / +): ... +def GetFileType(hFile: int, /): ... +def GetLogicalDrives(): ... +def GetOverlappedResult(hFile: int, overlapped: _win32typing.PyOVERLAPPED, bWait: int | bool, /) -> int: ... +def LockFile(hFile: int, offsetLow, offsetHigh, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh, /) -> None: ... +def MoveFile(existingFileName: str, newFileName: str, /) -> None: ... +def MoveFileW(existingFileName: str, newFileName: str, /) -> None: ... +def MoveFileEx(existingFileName: str, newFileName: str, flags, /) -> None: ... +def MoveFileExW(existingFileName: str, newFileName: str, flags, /) -> None: ... +def QueryDosDevice(DeviceName: str, /) -> str: ... +def ReadDirectoryChangesW( + handle: int, size, bWatchSubtree, dwNotifyFilter, overlapped: _win32typing.PyOVERLAPPED | None = ..., / +) -> None: ... +def FILE_NOTIFY_INFORMATION(buffer: str, size, /) -> tuple[tuple[Incomplete, Incomplete], ...]: ... +def SetCurrentDirectory(lpPathName: str, /) -> None: ... +def SetEndOfFile(hFile: int, /) -> None: ... +def SetFileApisToANSI() -> None: ... +def SetFileApisToOEM() -> None: ... +def SetFileAttributes(filename: str, newAttributes: int, /) -> None: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def SetFilePointer(handle: int, offset: tuple[int, int], moveMethod, /) -> None: ... +@overload +def SetFilePointer(handle: int, offset: int, moveMethod, /) -> None: ... + +def SetVolumeLabel(rootPathName: str, volumeName: str, /) -> None: ... +def UnlockFile(hFile: int, offsetLow, offsetHigh, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh, /) -> None: ... +def TransmitFile( + Socket, + File: int, + NumberOfBytesToWrite, + NumberOfBytesPerSend, + Overlapped: _win32typing.PyOVERLAPPED, + Flags, + Head: Incomplete | None = ..., + Tail: Incomplete | None = ..., +) -> None: ... +def ConnectEx( + s, name, Overlapped: _win32typing.PyOVERLAPPED, SendBuffer: Incomplete | None = ... +) -> tuple[Incomplete, Incomplete]: ... +def AcceptEx(slistening, sAccepting, buffer, ol: _win32typing.PyOVERLAPPED, /) -> None: ... +def CalculateSocketEndPointSize(socket, /): ... +def GetAcceptExSockaddrs( + sAccepting, buffer: _win32typing.PyOVERLAPPEDReadBuffer, / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def WSAEventSelect(socket: socket, hEvent: int, networkEvents: int, /) -> None: ... +def WSAEnumNetworkEvents(s: socket, hEvent: int, /) -> dict[int, int]: ... +def WSAAsyncSelect(socket, hwnd: int, _int, networkEvents, /) -> None: ... +def WSASend(s, buffer: str, ol: _win32typing.PyOVERLAPPED, dwFlags, /) -> tuple[Incomplete, Incomplete]: ... +def WSARecv(s, buffer, ol: _win32typing.PyOVERLAPPED, dwFlags, /) -> tuple[Incomplete, Incomplete]: ... +def BuildCommDCB(_def: str, dcb: _win32typing.PyDCB, /) -> _win32typing.PyDCB: ... +def ClearCommError(handle: int, /) -> tuple[Incomplete, _win32typing.PyCOMSTAT]: ... +def EscapeCommFunction(handle: int, /) -> None: ... +def GetCommState(handle: int, /) -> _win32typing.PyDCB: ... +def SetCommState(handle: int, dcb: _win32typing.PyDCB, /) -> None: ... +def ClearCommBreak(handle: int, /) -> None: ... +def GetCommMask(handle: int, /): ... +def SetCommMask(handle: int, val, /): ... +def GetCommModemStatus(handle: int, /): ... +def GetCommTimeouts(handle: int, /): ... +def SetCommTimeouts(handle: int, val, /): ... +def PurgeComm(handle: int, action, /) -> None: ... +def SetCommBreak(handle: int, /) -> None: ... +def SetupComm(handle: int, dwInQueue, dwOutQueue, /) -> None: ... +def TransmitCommChar(handle: int, cChar, /) -> None: ... +def WaitCommEvent(handle: int, overlapped: _win32typing.PyOVERLAPPED, /) -> None: ... +def SetVolumeMountPoint(VolumeMountPoint: str, VolumeName: str) -> str: ... +def DeleteVolumeMountPoint(VolumeMountPoint: str) -> None: ... +def GetVolumeNameForVolumeMountPoint(VolumeMountPoint: str) -> str: ... +def GetVolumePathName(FileName: str, BufferLength: int = ...) -> str: ... +def GetVolumePathNamesForVolumeName(VolumeName: str) -> list[Incomplete]: ... +def CreateHardLink( + FileName: str, + ExistingFileName: str, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> None: ... +def CreateSymbolicLink(SymlinkFileName: str, TargetFileName: str, Flags: int = ..., Transaction: int | None = ...) -> None: ... +def EncryptFile(filename: str, /) -> None: ... +def DecryptFile(filename: str, /) -> None: ... +def EncryptionDisable(DirName: str, Disable, /) -> None: ... +def FileEncryptionStatus(FileName: str, /): ... +def QueryUsersOnEncryptedFile(FileName: str, /) -> tuple[_win32typing.PySID, str, Incomplete]: ... +def QueryRecoveryAgentsOnEncryptedFile(FileName: str, /) -> tuple[_win32typing.PySID, str, Incomplete]: ... +def RemoveUsersFromEncryptedFile(FileName: str, pHashes: tuple[tuple[_win32typing.PySID, str, Incomplete], ...], /) -> None: ... +def AddUsersToEncryptedFile(FileName: str, pUsers: tuple[tuple[_win32typing.PySID, str, Incomplete], ...], /) -> None: ... +def DuplicateEncryptionInfoFile( + SrcFileName: str, + DstFileName: str, + CreationDisposition, + Attributes, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> None: ... +def BackupRead( + hFile: int, NumberOfBytesToRead, Buffer, bAbort, bProcessSecurity, lpContext, / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def BackupSeek(hFile: int, NumberOfBytesToSeek: tuple[int, int], lpContext, /): ... +@overload +def BackupSeek(hFile: int, NumberOfBytesToSeek: int, lpContext, /): ... + +def BackupWrite( + hFile: int, NumberOfBytesToWrite, Buffer: str, bAbort, bProcessSecurity, lpContext, / +) -> tuple[Incomplete, Incomplete]: ... +def SetFileShortName(hFile: int, ShortName, /) -> None: ... +def CopyFileEx( + ExistingFileName, + NewFileName, + ProgressRoutine: _win32typing.CopyProgressRoutine | None = ..., + Data: Incomplete | None = ..., + Cancel: bool = ..., + CopyFlags: int = ..., + Transaction: int | None = ..., +) -> None: ... +def MoveFileWithProgress( + ExistingFileName, + NewFileName, + ProgressRoutine: _win32typing.CopyProgressRoutine | None = ..., + Data: Incomplete | None = ..., + Flags: int = ..., + Transaction: int | None = ..., +) -> None: ... +def ReplaceFile( + ReplacedFileName, + ReplacementFileName, + BackupFileName: Incomplete | None = ..., + ReplaceFlags: int = ..., + Exclude: Incomplete | None = ..., + Reserved: Incomplete | None = ..., + /, +) -> None: ... +def OpenEncryptedFileRaw(FileName, Flags, /): ... +def ReadEncryptedFileRaw(ExportCallback, CallbackContext, Context, /) -> None: ... +def WriteEncryptedFileRaw(ImportCallback, CallbackContext, Context, /) -> None: ... +def CloseEncryptedFileRaw(Context, /) -> None: ... +def CreateFileW( + FileName: str, + DesiredAccess, + ShareMode, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, + CreationDisposition, + FlagsAndAttributes, + TemplateFile: int | None = ..., + Transaction: int | None = ..., + MiniVersion: Incomplete | None = ..., + ExtendedParameter: Incomplete | None = ..., +) -> int: ... +def DeleteFileW(FileName: str, Transaction: int | None = ...) -> None: ... +def GetFileAttributesEx(FileName: str, InfoLevelId=..., Transaction: int | None = ...): ... +def SetFileAttributesW(FileName, FileAttributes, Transaction: int | None = ...) -> None: ... +def CreateDirectoryExW( + TemplateDirectory: str, + NewDirectory: str, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + Transaction: int | None = ..., +) -> None: ... +def RemoveDirectory(PathName: str, Transaction: int | None = ...) -> None: ... +def FindFilesW( + FileName: str, Transaction: int | None = ... +) -> list[tuple[int, Incomplete, Incomplete, Incomplete, int, int, int, int, str, str]]: ... +def FindFilesIterator(FileName: str, Transaction: int | None = ...): ... +def FindStreams(FileName: str, Transaction: int | None = ...) -> list[tuple[Incomplete, str]]: ... +def FindFileNames(FileName: str, Transaction: int | None = ...) -> list[str]: ... +def GetFinalPathNameByHandle(File: int, Flags) -> str: ... +def SfcGetNextProtectedFile() -> list[Incomplete]: ... +def SfcIsFileProtected(ProtFileName: str, /): ... +def GetLongPathName(ShortPath: str, Transaction: int | None = ...) -> str: ... +def GetFullPathName(FileName, Transaction: int | None = ...): ... +def Wow64DisableWow64FsRedirection(): ... +def Wow64RevertWow64FsRedirection(OldValue, /) -> None: ... +def GetFileInformationByHandleEx(File: int, FileInformationClass): ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def SetFileInformationByHandle(File: int, FileInformationClass, Information: tuple[int, int]) -> None: ... +@overload +def SetFileInformationByHandle(File: int, FileInformationClass, Information) -> None: ... + +def ReOpenFile(OriginalFile: int, DesiredAccess, ShareMode, Flags) -> int: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def OpenFileById( + File: int, + FileId: tuple[int, int], + DesiredAccess, + ShareMode, + Flags, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... +@overload +def OpenFileById( + File: int, + FileId: _win32typing.PyIID | int, + DesiredAccess, + ShareMode, + Flags, + SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... + +def DCB() -> _win32typing.PyDCB: ... +def GetFileAttributesExW(FileName: str, InfoLevelId: int = ..., Transaction: int | None = None): ... +def OVERLAPPED() -> _win32typing.PyOVERLAPPED: ... + +CALLBACK_CHUNK_FINISHED: int +CALLBACK_STREAM_SWITCH: int +CBR_110: int +CBR_115200: int +CBR_1200: int +CBR_128000: int +CBR_14400: int +CBR_19200: int +CBR_2400: int +CBR_256000: int +CBR_300: int +CBR_38400: int +CBR_4800: int +CBR_56000: int +CBR_57600: int +CBR_600: int +CBR_9600: int +CLRBREAK: int +CLRDTR: int +CLRRTS: int +COPY_FILE_ALLOW_DECRYPTED_DESTINATION: int +COPY_FILE_FAIL_IF_EXISTS: int +COPY_FILE_OPEN_SOURCE_FOR_WRITE: int +COPY_FILE_RESTARTABLE: int +CREATE_ALWAYS: int +CREATE_FOR_DIR: int +CREATE_FOR_IMPORT: int +CREATE_NEW: int +DRIVE_CDROM: int +DRIVE_FIXED: int +DRIVE_NO_ROOT_DIR: int +DRIVE_RAMDISK: int +DRIVE_REMOTE: int +DRIVE_REMOVABLE: int +DRIVE_UNKNOWN: int +DTR_CONTROL_DISABLE: int +DTR_CONTROL_ENABLE: int +DTR_CONTROL_HANDSHAKE: int +EV_BREAK: int +EV_CTS: int +EV_DSR: int +EV_ERR: int +EV_RING: int +EV_RLSD: int +EV_RXCHAR: int +EV_RXFLAG: int +EV_TXEMPTY: int +EVENPARITY: int +FD_ACCEPT: int +FD_CLOSE: int +FD_CONNECT: int +FD_GROUP_QOS: int +FD_OOB: int +FD_QOS: int +FD_READ: int +FD_ROUTING_INTERFACE_CHANGE: int +FD_WRITE: int +FILE_ALL_ACCESS: int +FILE_ATTRIBUTE_ARCHIVE: int +FILE_ATTRIBUTE_COMPRESSED: int +FILE_ATTRIBUTE_DIRECTORY: int +FILE_ATTRIBUTE_HIDDEN: int +FILE_ATTRIBUTE_NORMAL: int +FILE_ATTRIBUTE_OFFLINE: int +FILE_ATTRIBUTE_READONLY: int +FILE_ATTRIBUTE_SYSTEM: int +FILE_ATTRIBUTE_TEMPORARY: int +FILE_BEGIN: int +FILE_CURRENT: int +FILE_ENCRYPTABLE: int +FILE_END: int +FILE_FLAG_BACKUP_SEMANTICS: int +FILE_FLAG_DELETE_ON_CLOSE: int +FILE_FLAG_NO_BUFFERING: int +FILE_FLAG_OPEN_REPARSE_POINT: int +FILE_FLAG_OVERLAPPED: int +FILE_FLAG_POSIX_SEMANTICS: int +FILE_FLAG_RANDOM_ACCESS: int +FILE_FLAG_SEQUENTIAL_SCAN: int +FILE_FLAG_WRITE_THROUGH: int +FILE_GENERIC_READ: int +FILE_GENERIC_WRITE: int +FILE_IS_ENCRYPTED: int +FILE_READ_ONLY: int +FILE_ROOT_DIR: int +FILE_SHARE_DELETE: int +FILE_SHARE_READ: int +FILE_SHARE_WRITE: int +FILE_SYSTEM_ATTR: int +FILE_SYSTEM_DIR: int +FILE_SYSTEM_NOT_SUPPORT: int +FILE_TYPE_CHAR: int +FILE_TYPE_DISK: int +FILE_TYPE_PIPE: int +FILE_TYPE_UNKNOWN: int +FILE_UNKNOWN: int +FILE_USER_DISALLOWED: int +FileAllocationInfo: int +FileAttributeTagInfo: int +FileBasicInfo: int +FileCompressionInfo: int +FileDispositionInfo: int +FileEndOfFileInfo: int +FileIdBothDirectoryInfo: int +FileIdBothDirectoryRestartInfo: int +FileIdType: int +FileIoPriorityHintInfo: int +FileNameInfo: int +FileRenameInfo: int +FileStandardInfo: int +FileStreamInfo: int +GENERIC_EXECUTE: int +GENERIC_READ: int +GENERIC_WRITE: int +GetFileExInfoStandard: int +IoPriorityHintLow: int +IoPriorityHintNormal: int +IoPriorityHintVeryLow: int +MARKPARITY: int +MOVEFILE_COPY_ALLOWED: int +MOVEFILE_CREATE_HARDLINK: int +MOVEFILE_DELAY_UNTIL_REBOOT: int +MOVEFILE_FAIL_IF_NOT_TRACKABLE: int +MOVEFILE_REPLACE_EXISTING: int +MOVEFILE_WRITE_THROUGH: int +NOPARITY: int +ObjectIdType: int +ODDPARITY: int +ONE5STOPBITS: int +ONESTOPBIT: int +OPEN_ALWAYS: int +OPEN_EXISTING: int +OVERWRITE_HIDDEN: int +PROGRESS_CANCEL: int +PROGRESS_CONTINUE: int +PROGRESS_QUIET: int +PROGRESS_STOP: int +PURGE_RXABORT: int +PURGE_RXCLEAR: int +PURGE_TXABORT: int +PURGE_TXCLEAR: int +REPLACEFILE_IGNORE_MERGE_ERRORS: int +REPLACEFILE_WRITE_THROUGH: int +RTS_CONTROL_DISABLE: int +RTS_CONTROL_ENABLE: int +RTS_CONTROL_HANDSHAKE: int +RTS_CONTROL_TOGGLE: int +SCS_32BIT_BINARY: int +SCS_DOS_BINARY: int +SCS_OS216_BINARY: int +SCS_PIF_BINARY: int +SCS_POSIX_BINARY: int +SCS_WOW_BINARY: int +SECURITY_ANONYMOUS: int +SECURITY_CONTEXT_TRACKING: int +SECURITY_DELEGATION: int +SECURITY_EFFECTIVE_ONLY: int +SECURITY_IDENTIFICATION: int +SECURITY_IMPERSONATION: int +SETBREAK: int +SETDTR: int +SETRTS: int +SETXOFF: int +SETXON: int +SO_CONNECT_TIME: int +SO_UPDATE_ACCEPT_CONTEXT: int +SO_UPDATE_CONNECT_CONTEXT: int +SPACEPARITY: int +SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE: int +SYMBOLIC_LINK_FLAG_DIRECTORY: int +TF_DISCONNECT: int +TF_REUSE_SOCKET: int +TF_USE_DEFAULT_WORKER: int +TF_USE_KERNEL_APC: int +TF_USE_SYSTEM_THREAD: int +TF_WRITE_BEHIND: int +TRUNCATE_EXISTING: int +TWOSTOPBITS: int +WSA_IO_PENDING: int +WSA_OPERATION_ABORTED: int +WSAECONNABORTED: int +WSAECONNRESET: int +WSAEDISCON: int +WSAEFAULT: int +WSAEINPROGRESS: int +WSAEINTR: int +WSAEINVAL: int +WSAEMSGSIZE: int +WSAENETDOWN: int +WSAENETRESET: int +WSAENOBUFS: int +WSAENOTCONN: int +WSAENOTSOCK: int +WSAEOPNOTSUPP: int +WSAESHUTDOWN: int +WSAEWOULDBLOCK: int +FD_ADDRESS_LIST_CHANGE: int +INVALID_HANDLE_VALUE: int +UNICODE: int + +# win32pipe.FDCreatePipe is the only known public method to expose this. But it opens both read and write handles. +def _open_osfhandle(osfhandle: _win32typing.PyHANDLE, flags: int, /) -> int: ... diff --git a/stubs/pywin32/win32/win32gui.pyi b/stubs/pywin32/win32/win32gui.pyi new file mode 100644 index 000000000000..a6e91aa5a14e --- /dev/null +++ b/stubs/pywin32/win32/win32gui.pyi @@ -0,0 +1,565 @@ +from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer +from collections.abc import Callable +from typing import Any, Literal, TypeVar + +import _win32typing +from win32.lib.pywintypes import error as error + +_T = TypeVar("_T") + +def EnumFontFamilies(hdc: int, Family: str, EnumFontFamProc, Param, /): ... +def set_logger(logger, /) -> None: ... +def LOGFONT() -> _win32typing.PyLOGFONT: ... +def CreateFontIndirect(lplf: _win32typing.PyLOGFONT, /): ... +def GetObject(handle: int, /): ... +def GetObjectType(h: int, /): ... +def PyGetMemory(addr: int, len: int, /): ... +def PyGetString(addr, _len=..., /) -> str: ... +def PySetString(addr, String, maxLen, /): ... +def PySetMemory(addr, String, /): ... +def PyGetArraySignedLong(array, index, /): ... +def PyGetBufferAddressAndLen(obj, /): ... +def FlashWindow(hwnd: int, bInvert, /): ... +def FlashWindowEx(hwnd: int, dwFlags, uCount, dwTimeout, /): ... +def GetWindowLong(hwnd: int, index, /): ... +def GetClassLong(hwnd: int, index, /): ... +def SetWindowLong(hwnd: int, index, value, /): ... +def CallWindowProc(wndproc, hwnd: int, msg, wparam, lparam, /): ... +def CascadeWindows( + hwndObject: _win32typing.PyHANDLE | int | None, + how: int, + rectObject: _win32typing.PyRECT | tuple[int, int, int, int] | int | None = None, + childrenObject: tuple[_win32typing.PyHANDLE | int, ...] | None = None, + /, +) -> int: ... +def SendMessage( + hwnd: int | None, message: int, wparam: int | None = ..., lparam: ReadableBuffer | float | None = ..., / +) -> int: ... +def SendMessageTimeout( + hwnd: int, + message: int, + wparam: ReadableBuffer | float | None, + lparam: ReadableBuffer | float | None, + flags: int, + timeout: int, + /, +) -> tuple[int, int]: ... +def PostMessage( + hwnd: int | None, message: int, wparam: int | None = ..., lparam: ReadableBuffer | float | None = ..., / +) -> None: ... +def PostThreadMessage(threadId, message, wparam, lparam, /) -> None: ... +def ReplyMessage(result, /): ... +def ResetDC(hdc: int, devmode: _win32typing.PyDEVMODEW, /) -> int: ... +def RegisterWindowMessage(name: str, /): ... +def DefWindowProc( + hwnd: int | None, message: int, wparam: ReadableBuffer | float | None, lparam: ReadableBuffer | float | None, / +) -> int: ... +def EnumWindows(callback: Callable[[int, _T], int | None], extra: _T, /) -> None: ... +def EnumThreadWindows(dwThreadId, callback: Callable[[int, _T], int | None], extra: _T, /) -> None: ... +def EnumChildWindows( + hwnd: _win32typing.PyHANDLE | int | None, callback: Callable[[int, _T], int | None], extra: _T, / +) -> None: ... +def EnumDesktopWindows( + hDesktop: _win32typing.PyHANDLE | int | None, callback: Callable[[int, _T], int | None], extra: _T, / +) -> None: ... +def GetThreadDesktop(ThreadId: int, /) -> int: ... +def DialogBox(hInstance: int, TemplateName: _win32typing.PyResourceId, hWndParent: int, DialogFunc, InitParam: int = ..., /): ... +def DialogBoxParam(): ... +def DialogBoxIndirect( + hInstance: int, controllist: _win32typing.PyDialogTemplate, hWndParent: int, DialogFunc, InitParam: int = ..., / +): ... +def DialogBoxIndirectParam(): ... +def CreateDialogIndirect( + hInstance: int, controllist: _win32typing.PyDialogTemplate, hWndParent: int, DialogFunc, InitParam: int = ..., / +): ... +def EndDialog(hwnd: int, result, /) -> None: ... +def GetDlgItem(hDlg: int, IDDlgItem, /): ... +def GetDlgItemInt(hDlg: int, IDDlgItem, Signed, /) -> None: ... +def SetDlgItemInt(hDlg: int, IDDlgItem, Value, Signed, /) -> None: ... +def GetDlgCtrlID(hwnd: int, /): ... +def GetDlgItemText(hDlg: int, IDDlgItem, /) -> str: ... +def SetDlgItemText(hDlg: int, IDDlgItem, String, /) -> None: ... +def GetNextDlgTabItem(hDlg, hCtl, bPrevious, /): ... +def GetNextDlgGroupItem(hDlg, hCtl, bPrevious, /): ... +def SetWindowText() -> None: ... +def GetWindowText(hwnd: int, /) -> str: ... +def InitCommonControls() -> None: ... +def InitCommonControlsEx(flag, /) -> None: ... +def LoadCursor(hinstance, resid, /): ... +def SetCursor(hcursor, /): ... +def GetCursor(): ... +def GetCursorInfo() -> tuple[int, int, int, int]: ... +def CreateAcceleratorTable(accels: tuple[tuple[Incomplete, Incomplete, Incomplete], ...], /): ... +def LoadMenu(hinstance, resource_id: str, /): ... +def DestroyMenu() -> None: ... +def SetMenu(hwnd: int, hmenu, /) -> None: ... +def GetMenu(hwnd: int, /) -> int: ... +def LoadIcon(hinstance: int, resource_id_or_name: str | int, /) -> _win32typing.PyWNDCLASS: ... +def CopyIcon(hicon, /): ... +def DrawIcon(hDC, X, Y, hicon, /) -> None: ... +def DrawIconEx( + hDC, xLeft, yTop, hIcon, cxWidth, cyWidth, istepIfAniCur, hbrFlickerFreeDraw: _win32typing.PyGdiHANDLE, diFlags, / +) -> None: ... +def CreateIconIndirect(iconinfo: _win32typing.PyICONINFO, /): ... +def CreateIconFromResource(bits: str, fIcon, ver: int = ..., /) -> int: ... +def LoadImage(hinst: int, name: str, type: int, cxDesired: int, cyDesired: int, fuLoad: int, /) -> _win32typing.PyGdiHANDLE: ... +def DeleteObject(handle: int | _win32typing.PyGdiHANDLE, /) -> None: ... +def BitBlt( + hdcDest: int | _win32typing.PyGdiHANDLE, + x: int, + y: int, + width: int, + height: int, + hdcSrc: int | _win32typing.PyGdiHANDLE | None, + nXSrc: int, + nYSrc: int, + dwRop: int, + /, +) -> None: ... +def StretchBlt(hdcDest, x, y, width, height, hdcSrc, nXSrc, nYSrc, nWidthSrc, nHeightSrc, dwRop, /) -> None: ... +def PatBlt(hdc: int, XLeft, YLeft, Width, Height, Rop, /) -> None: ... +def SetStretchBltMode(hdc: int, StretchMode, /): ... +def GetStretchBltMode(hdc: int, /): ... +def TransparentBlt( + Dest: int, + XOriginDest, + YOriginDest, + WidthDest, + HeightDest, + Src: int, + XOriginSrc, + YOriginSrc, + WidthSrc, + HeightSrc, + Transparent, + /, +) -> None: ... +def MaskBlt( + Dest: int, XDest, YDest, Width, Height, Src: int, XSrc, YSrc, Mask: _win32typing.PyGdiHANDLE, xMask, yMask, Rop, / +) -> None: ... +def AlphaBlend( + Dest: int, + XOriginDest, + YOriginDest, + WidthDest, + HeightDest, + Src: int, + XOriginSrc, + YOriginSrc, + WidthSrc, + HeightSrc, + blendFunction: _win32typing.PyBLENDFUNCTION, + /, +) -> None: ... +def MessageBox(parent: _win32typing.PyHANDLE | int | None, text: str, caption: str, flags, /): ... +def MessageBeep(type, /) -> None: ... +def CreateWindow( + className: str | _win32typing.PyResourceId, + windowTitle: str | None, + style: int, + x: int, + y: int, + width: int, + height: int, + parent: int, + menu: int, + hinstance: int, + reserved: Incomplete | None, + /, +) -> int: ... +def DestroyWindow(_hwnd: int, /) -> None: ... +def EnableWindow(hWnd: int, bEnable, /): ... +def FindWindow(ClassName: _win32typing.PyResourceId | str | None, WindowName: str | None, /) -> int: ... +def FindWindowEx( + Parent: int | None, ChildAfter: int | None, ClassName: _win32typing.PyResourceId | str | None, WindowName: str | None, / +) -> int: ... +def DragAcceptFiles(hwnd: int, fAccept, /) -> None: ... +def DragDetect(hwnd: int, point: tuple[Incomplete, Incomplete], /) -> None: ... +def SetDoubleClickTime(newVal, /) -> None: ... +def GetDoubleClickTime(): ... +def HideCaret(hWnd: int, /) -> None: ... +def SetCaretPos(x, y, /) -> None: ... +def GetCaretPos() -> tuple[Incomplete, Incomplete]: ... +def ShowCaret(hWnd: int, /) -> None: ... +def ShowWindow(hWnd: int | None, cmdShow: int, /) -> int: ... +def IsWindowVisible(hwnd: int | None, /) -> int: ... +def IsWindowEnabled(hwnd: int | None, /) -> int: ... +def SetFocus(hwnd: int, /) -> None: ... +def GetFocus() -> None: ... +def UpdateWindow(hwnd: int, /) -> None: ... +def BringWindowToTop(hwnd: int, /) -> None: ... +def SetActiveWindow(hwnd: int, /): ... +def GetActiveWindow(): ... +def SetForegroundWindow(hwnd: int, /) -> None: ... +def GetForegroundWindow() -> int: ... +def GetClientRect(hwnd: int, /) -> tuple[int, int, int, int]: ... +def GetDC(hwnd: int, /): ... +def SaveDC(hdc: int, /): ... +def RestoreDC(hdc: int, SavedDC, /) -> None: ... +def DeleteDC(hdc: int | _win32typing.PyHANDLE, /) -> None: ... +def CreateCompatibleDC(dc: int | _win32typing.PyHANDLE | None, /) -> int: ... +def CreateCompatibleBitmap(hdc: int | _win32typing.PyHANDLE | None, width: int, height: int, /) -> _win32typing.PyGdiHANDLE: ... +def CreateBitmap(width: int, height: int, cPlanes: int, cBitsPerPixel: int, bitmap_bits: None, /) -> _win32typing.PyGdiHANDLE: ... +def SelectObject(hdc: int | _win32typing.PyHANDLE | None, object: int | _win32typing.PyHANDLE | None, /) -> int: ... +def GetCurrentObject(hdc: int, ObjectType, /) -> int: ... +def GetWindowRect(hwnd: int | _win32typing.PyHANDLE, /) -> tuple[int, int, int, int]: ... +def GetStockObject(Object, /) -> int: ... +def PostQuitMessage(rc: int, /) -> None: ... +def WaitMessage() -> None: ... +def SetWindowPos(hWnd: int, InsertAfter: int | None, X: int, Y: int, cx: int, cy: int, Flags: int, /) -> None: ... +def GetWindowPlacement(hwnd: int, /) -> tuple[int, int, tuple[int, int], tuple[int, int], tuple[int, int, int, int]]: ... +def SetWindowPlacement(hWnd: int, placement, /) -> None: ... +def RegisterClass(wndClass: _win32typing.PyWNDCLASS, /) -> _win32typing.PyResourceId: ... +def UnregisterClass(atom: _win32typing.PyResourceId, hinst: int, /) -> None: ... +def PumpMessages() -> None: ... +def PumpWaitingMessages(firstMessage: int = ..., lastMessage: int = ..., /) -> int: ... +def GetMessage(hwnd: int, _min, _max, /): ... +def TranslateMessage(msg, /): ... +def DispatchMessage(msg, /): ... +def TranslateAccelerator(hwnd: int, haccel, msg, /): ... +def PeekMessage(hwnd: int, filterMin, filterMax, removalOptions, /): ... +def Shell_NotifyIcon(Message: int, nid: _win32typing.PyNOTIFYICONDATA, /) -> None: ... +def GetSystemMenu(hwnd: int, bRevert, /): ... +def DrawMenuBar(hwnd: int, /) -> None: ... +def MoveWindow(hwnd: int, x: int, y: int, width: int, height: int, bRepaint: bool, /) -> None: ... +def CloseWindow() -> None: ... +def DeleteMenu(hmenu, position, flags, /) -> None: ... +def RemoveMenu(hmenu, position, flags, /) -> None: ... +def CreateMenu(): ... +def CreatePopupMenu(): ... +def TrackPopupMenu(hmenu, flags, x, y, reserved, hwnd: int, prcRect: _win32typing.PyRECT, /): ... +def CommDlgExtendedError(): ... +def ExtractIcon(hinstance, moduleName: str, index, /): ... +def ExtractIconEx(moduleName: str, index, numIcons: int = ..., /): ... +def DestroyIcon(hicon, /) -> None: ... +def GetIconInfo(hicon: int, /) -> _win32typing.PyICONINFO: ... +def ScreenToClient( + hWnd: int | _win32typing.PyHANDLE, Point: tuple[Incomplete, Incomplete], / +) -> tuple[Incomplete, Incomplete]: ... +def ClientToScreen(hWnd: int, Point: tuple[Incomplete, Incomplete], /) -> tuple[Incomplete, Incomplete]: ... +def PaintDesktop(hdc: int, /) -> None: ... +def RedrawWindow(hWnd: int, rcUpdate: tuple[int, int, int, int], hrgnUpdate: _win32typing.PyGdiHANDLE, flags, /) -> None: ... +def GetTextExtentPoint32(hdc: int, _str: str, /) -> tuple[Incomplete, Incomplete]: ... +def GetTextMetrics(): ... +def GetTextCharacterExtra(hdc: int, /): ... +def SetTextCharacterExtra(hdc: int, CharExtra, /): ... +def GetTextAlign(hdc: int, /): ... +def SetTextAlign(hdc: int, Mode, /): ... +def GetTextFace(hdc: int, /) -> str: ... +def GetMapMode(hdc: int, /): ... +def SetMapMode(hdc: int, MapMode, /): ... +def GetGraphicsMode(hdc: int, /): ... +def SetGraphicsMode(hdc: int, Mode, /): ... +def GetLayout(hdc: int, /): ... +def SetLayout(hdc: int, Layout, /): ... +def GetPolyFillMode(hdc: int, /): ... +def SetPolyFillMode(hdc: int, PolyFillMode, /): ... +def GetWorldTransform(hdc: int, /) -> _win32typing.PyXFORM: ... +def SetWorldTransform(hdc: int, Xform: _win32typing.PyXFORM, /) -> None: ... +def ModifyWorldTransform(hdc: int, Xform: _win32typing.PyXFORM, Mode, /) -> None: ... +def CombineTransform(xform1: _win32typing.PyXFORM, xform2: _win32typing.PyXFORM, /) -> _win32typing.PyXFORM: ... +def GetWindowOrgEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetWindowOrgEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetViewportOrgEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetViewportOrgEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetWindowExtEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetWindowExtEx(hdc: int, XExtent, YExtent, /) -> tuple[Incomplete, Incomplete]: ... +def GetViewportExtEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetViewportExtEx(hdc: int, XExtent, YExtent, /) -> tuple[Incomplete, Incomplete]: ... +def GradientFill(hdc, Vertex: tuple[_win32typing.PyTRIVERTEX, ...], Mesh, Mode, /) -> None: ... +def GetOpenFileName(OPENFILENAME: str, /): ... +def InsertMenuItem(hMenu, uItem, fByPosition, menuItem, /) -> None: ... +def SetMenuItemInfo(hMenu, uItem, fByPosition, menuItem, /) -> None: ... +def GetMenuItemInfo(hMenu: int, uItem: int, fByPosition: bool, menuItem: ReadableBuffer, /) -> None: ... +def GetMenuItemCount(hMenu: int | None, /) -> int: ... + +# Actually returns a list of int|tuple, but lists don't support positional types +def GetMenuItemRect(hWnd: int | None, hMenu: int | None, uItem: int, /) -> tuple[int, tuple[int, int, int, int]]: ... +def GetMenuState(hMenu, uID, flags, /): ... +def SetMenuDefaultItem(hMenu, uItem, fByPos, /) -> None: ... +def GetMenuDefaultItem(hMenu, fByPos, flags, /): ... +def AppendMenu() -> None: ... +def InsertMenu() -> None: ... +def EnableMenuItem() -> None: ... +def CheckMenuItem(): ... +def GetSubMenu(hMenu, nPos, /): ... +def ModifyMenu(hMnu, uPosition, uFlags, uIDNewItem, newItem: str, /) -> None: ... +def GetMenuItemID(hMenu, nPos, /): ... +def SetMenuItemBitmaps( + hMenu, uPosition, uFlags, hBitmapUnchecked: _win32typing.PyGdiHANDLE, hBitmapChecked: _win32typing.PyGdiHANDLE, / +) -> None: ... +def CheckMenuRadioItem(hMenu, idFirst, idLast, idCheck, uFlags, /) -> None: ... +def SetMenuInfo(hmenu, info, /) -> None: ... +def GetMenuInfo(hmenu: int, info: WriteableBuffer, /) -> None: ... +def DrawFocusRect(hDC: int, rc: tuple[int, int, int, int], /) -> None: ... +def DrawText(hDC: int, String, nCount, Rect: _win32typing.PyRECT, Format, /) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def LineTo(hdc: int, XEnd, YEnd, /) -> None: ... +def Ellipse(hdc: int, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def Pie(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def Arc(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def ArcTo(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def AngleArc(hdc: int, Y, Y1, Radius, StartAngle: float, SweepAngle: float, /) -> None: ... +def Chord(hdc: int, LeftRect, TopRect, RightRect, BottomRect, XRadial1, YRadial1, XRadial2, YRadial2, /) -> None: ... +def ExtFloodFill(arg: int, XStart, YStart, Color, FillType, /) -> None: ... +def SetPixel(hdc: int, X, Y, Color, /): ... +def GetPixel(hdc: int, XPos, YPos, /): ... +def GetROP2(hdc: int, /): ... +def SetROP2(hdc: int, DrawMode, /): ... +def SetPixelV(hdc: int, X, Y, Color, /) -> None: ... +def MoveToEx(hdc: int, X, Y, /) -> tuple[Incomplete, Incomplete]: ... +def GetCurrentPositionEx(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def GetArcDirection(hdc: int, /): ... +def SetArcDirection(hdc: int, ArcDirection, /): ... +def Polygon(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def Polyline(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolylineTo(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolyBezier(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PolyBezierTo(hdc: int, Points: list[tuple[Incomplete, Incomplete]], /) -> None: ... +def PlgBlt( + Dest: int, + Point, + Src: int, + XSrc, + YSrc, + Width, + Height, + Mask: _win32typing.PyGdiHANDLE | None = ..., + xMask: int = ..., + yMask: int = ..., + /, +) -> None: ... +def CreatePolygonRgn(Points: list[tuple[Incomplete, Incomplete]], PolyFillMode, /) -> _win32typing.PyGdiHANDLE: ... +def ExtTextOut( + hdc: int, _int, _int1, _int2, rect: _win32typing.PyRECT, string, _tuple: tuple[tuple[Incomplete, Incomplete], ...], / +): ... +def GetTextColor(hdc, /): ... +def SetTextColor(hdc, color, /): ... +def GetBkMode(hdc: int, /): ... +def SetBkMode(hdc: int, BkMode, /): ... +def GetBkColor(hdc: int, /): ... +def SetBkColor(hdc: int, color, /): ... +def DrawEdge(hdc: int, rc: _win32typing.PyRECT, edge, Flags, /) -> _win32typing.PyRECT: ... +def FillRect(hDC: int, rc: _win32typing.PyRECT, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def FillRgn(hdc: int, hrgn: _win32typing.PyGdiHANDLE, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def PaintRgn(hdc: int, hrgn: _win32typing.PyGdiHANDLE, /) -> None: ... +def FrameRgn(hdc: int, hrgn, hbr, Width, Height, /) -> None: ... +def InvertRgn(hdc: int, hrgn, /) -> None: ... +def EqualRgn(SrcRgn1, SrcRgn2, /): ... +def PtInRegion(hrgn, X, Y, /): ... +def PtInRect(rect: tuple[int, int, int, int], point: tuple[Incomplete, Incomplete], /): ... +def RectInRegion(hrgn, rc: _win32typing.PyRECT, /): ... +def SetRectRgn(hrgn, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def CombineRgn(Dest, Src1, Src2, CombineMode, /): ... +def DrawAnimatedRects(hwnd: int, idAni, minCoords: _win32typing.PyRECT, restCoords: _win32typing.PyRECT, /) -> None: ... +def CreateSolidBrush(Color, /) -> _win32typing.PyGdiHANDLE: ... +def CreatePatternBrush(hbmp: _win32typing.PyGdiHANDLE, /) -> _win32typing.PyGdiHANDLE: ... +def CreateHatchBrush(Style, clrref, /) -> _win32typing.PyGdiHANDLE: ... +def CreatePen(PenStyle, Width, Color, /) -> _win32typing.PyGdiHANDLE: ... +def GetSysColor(Index: int, /) -> int: ... +def GetSysColorBrush(Index, /) -> _win32typing.PyGdiHANDLE: ... +def InvalidateRect(hWnd: int, Rect: _win32typing.PyRECT, Erase, /) -> None: ... +def FrameRect(hDC: int, rc: _win32typing.PyRECT, hbr: _win32typing.PyGdiHANDLE, /) -> None: ... +def InvertRect(hDC: int, rc: _win32typing.PyRECT, /) -> None: ... +def WindowFromDC(hDC: int, /) -> int: ... +def GetUpdateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, Erase, /): ... +def GetWindowRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, /): ... +def SetWindowRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE | None, Redraw: bool, /) -> None: ... + +# Actually returns a list, but the length is always fixed +def GetWindowRgnBox(hWnd: _win32typing.PyHANDLE | int | None) -> tuple[int, tuple[int, int, int, int]]: ... +def ValidateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, /) -> None: ... +def InvalidateRgn(hWnd: int, hRgn: _win32typing.PyGdiHANDLE, Erase, /) -> None: ... +def GetRgnBox(hrgn: _win32typing.PyGdiHANDLE, /) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def OffsetRgn(hrgn: _win32typing.PyGdiHANDLE, XOffset, YOffset, /): ... +def Rectangle(hdc: int, LeftRect, TopRect, RightRect, BottomRect, /) -> None: ... +def RoundRect(hdc: int, LeftRect, TopRect, RightRect, BottomRect, Width, Height, /) -> None: ... +def BeginPaint() -> tuple[Incomplete, Incomplete]: ... +def EndPaint(hwnd: int, ps, /) -> None: ... +def BeginPath(hdc: int, /) -> None: ... +def EndPath(hdc: int, /) -> None: ... +def AbortPath(hdc: int, /) -> None: ... +def CloseFigure(hdc: int, /) -> None: ... +def FlattenPath(hdc: int, /) -> None: ... +def FillPath(hdc: int, /) -> None: ... +def WidenPath(hdc: int, /) -> None: ... +def StrokePath(hdc: int, /) -> None: ... +def StrokeAndFillPath(hdc: int, /) -> None: ... +def GetMiterLimit(hdc: int, /) -> float: ... +def SetMiterLimit(hdc: int, NewLimit: float, /) -> float: ... +def PathToRegion(hdc: int, /) -> _win32typing.PyGdiHANDLE: ... +def GetPath(hdc: int, /) -> tuple[Incomplete, Incomplete]: ... +def CreateRoundRectRgn(LeftRect, TopRect, RightRect, BottomRect, WidthEllipse, HeightEllipse, /): ... +def CreateRectRgnIndirect(rc: _win32typing.PyRECT, /): ... +def CreateEllipticRgnIndirect(rc: _win32typing.PyRECT, /): ... +def CreateWindowEx( + dwExStyle, className: str, windowTitle: str, style, x, y, width, height, parent, menu, hinstance, reserved, / +): ... +def GetParent(child: int, /) -> int: ... +def SetParent(child: int, child1: int | _win32typing.PyHANDLE | None, /) -> int: ... +def GetCursorPos() -> tuple[Incomplete, Incomplete]: ... +def GetDesktopWindow(): ... +def GetWindow(hWnd: int, uCmd: int, /) -> int: ... +def GetWindowDC(hWnd: int | _win32typing.PyHANDLE | None, /) -> int: ... +def IsIconic(hWnd: int, /) -> int: ... +def IsWindow(hWnd: int, /) -> int: ... +def IsChild(hWndParent: int, hWnd: int, /) -> int: ... +def ReleaseCapture() -> None: ... +def GetCapture(): ... +def SetCapture() -> None: ... + +# Exists and is documented as a wrapper around TrackMouseEvent +# See https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-_trackmouseevent +def _TrackMouseEvent(tme: tuple[int, int, int], /) -> _win32typing.TRACKMOUSEEVENT: ... +def ReleaseDC(hWnd: int | _win32typing.PyHANDLE | None, hDC: int | _win32typing.PyHANDLE | None, /) -> Literal[0, 1]: ... +def CreateCaret(hWnd: int, hBitmap: _win32typing.PyGdiHANDLE, nWidth, nHeight, /) -> None: ... +def DestroyCaret() -> None: ... +def ScrollWindowEx( + hWnd: int, dx, dy, rcScroll: _win32typing.PyRECT, rcClip: _win32typing.PyRECT, hrgnUpdate, flags, / +) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def SetScrollInfo(hwnd: int, nBar, scollInfo: _win32typing.PySCROLLINFO, bRedraw=..., /) -> None: ... +def GetScrollInfo(hwnd: int, nBar, mask, /) -> _win32typing.PySCROLLINFO: ... +def GetClassName(hwnd: _win32typing.PyHANDLE | int | None, /) -> str | None: ... +def RealGetWindowClass(hwnd: _win32typing.PyHANDLE | int | None, /) -> str | None: ... +def WindowFromPoint(point: tuple[int, int], /) -> int: ... +def ChildWindowFromPoint(hwndParent: int, point: tuple[Incomplete, Incomplete], /): ... +def CreateDC(Driver: str, Device: str, InitData: _win32typing.PyDEVMODEW, /): ... +def GetSaveFileNameW( + hwndOwner: int | None = ..., + hInstance: int | None = ..., + Filter: Incomplete | None = ..., + CustomFilter: Incomplete | None = ..., + FilterIndex: int = ..., + File: Incomplete | None = ..., + MaxFile: int = ..., + InitialDir: Incomplete | None = ..., + Title: Incomplete | None = ..., + Flags: int = ..., + DefExt: Incomplete | None = ..., + TemplateName: _win32typing.PyResourceId | None = ..., + /, +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def GetOpenFileNameW( + hwndOwner: int | None = ..., + hInstance: int | None = ..., + Filter: Incomplete | None = ..., + CustomFilter: Incomplete | None = ..., + FilterIndex: int = ..., + File: Incomplete | None = ..., + MaxFile: int = ..., + InitialDir: Incomplete | None = ..., + Title: Incomplete | None = ..., + Flags: int = ..., + DefExt: Incomplete | None = ..., + TemplateName: _win32typing.PyResourceId | None = ..., +) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +# Any: Return type is too varied based on Action. This would require an overload for all win32con.SPI_* literals +def SystemParametersInfo(Action: int, Param: Incomplete | None = ..., WinIni: int = ...) -> Any: ... +def SetLayeredWindowAttributes(hwnd: int, Key, Alpha, Flags) -> None: ... +def GetLayeredWindowAttributes(hwnd: int) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def UpdateLayeredWindow( + hwnd: int, + hdcDst: int | None = ..., + ptDst: tuple[Incomplete, Incomplete] | None = ..., + size: tuple[Incomplete, Incomplete] | None = ..., + hdcSrc: Incomplete | None = ..., + ptSrc: tuple[Incomplete, Incomplete] | None = ..., + Key: int = ..., + blend: tuple[int, int, int, int] = ..., + Flags: int = ..., +) -> None: ... +def AnimateWindow(hwnd: int, Time, Flags) -> None: ... +def CreateBrushIndirect(lb: _win32typing.PyLOGBRUSH, /) -> _win32typing.PyGdiHANDLE: ... +def ExtCreatePen(PenStyle, Width, lb: _win32typing.PyLOGBRUSH, Style: tuple[Incomplete, ...] | None = ..., /) -> int: ... +def DrawTextW(hDC: int, String: str, Count, Rect: _win32typing.PyRECT, Format) -> tuple[Incomplete, _win32typing.PyRECT]: ... +def EnumPropsEx(hWnd: int, EnumFunc, Param, /) -> None: ... +def RegisterDeviceNotification(handle: int, _filter, flags, /) -> _win32typing.PyHDEVNOTIFY: ... +def UnregisterDeviceNotification() -> None: ... +def RegisterHotKey(hWnd: _win32typing.PyHANDLE | int | None, _id: int, Modifiers: int, vk: int, /) -> None: ... +def UnregisterHotKey(hWnd: _win32typing.PyHANDLE | int | None, _id: int, /) -> None: ... +def GetAncestor(hwnd: int, gaFlags: int, /) -> int: ... +def GetTopWindow(hWnd: int | None, /) -> int: ... +def ChildWindowFromPointEx(hwndParent: int, point: tuple[Incomplete, Incomplete], flags: int, /): ... +def CreateDialogIndirectParam(hInstance, controlList, hWndParent, DialogFunc, InitParam: int = 0, /) -> int: ... +def DestroyAcceleratorTable(haccel, /): ... +def Edit_GetLine(hwnd, line, size=..., /): ... +def GetModuleHandle(lpModuleName: str | None, /) -> int: ... +def GetWindowTextLength(hwnd, /) -> int: ... +def HIWORD(val: int, /) -> int: ... +def ImageList_Add(hImageList, hbmImage, hbmMask, /) -> int: ... +def ImageList_Create(cx: int, cy: int, flags: int, cInitial: int, cGrow: int, /): ... +def ImageList_Destroy(hImageList, /): ... +def ImageList_Draw(hImageList, i: int, hdcDst, x: int, y: int, fStyle, /): ... +def ImageList_DrawEx(hImageList, i: int, hdcDst, x: int, y: int, dx: int, dy: int, rgbBk, rgbFg, fStyle, /): ... +def ImageList_GetIcon(hImageList, i: int, flag: int, /): ... +def ImageList_GetImageCount(hImageList, /) -> int: ... +def ImageList_LoadBitmap(hInst, name, cx: int, cGrow: int, crMask, /): ... +def ImageList_LoadImage(hInst, name, cx: int, cGrow: int, crMask, uType, uFlags, /): ... +def ImageList_Remove(hImageList, i, /): ... +def ImageList_Replace(hImageList, i, hicon, /): ... +def ImageList_ReplaceIcon(hImageList, i, hicon, /): ... +def ImageList_SetBkColor(hImageList, Color, /): ... +def ImageList_SetOverlayImage(hImageList, iImage, iOverlay, /): ... +def LOWORD(val: int, /) -> int: ... +def ListView_SortItems(hwnd, callback, param=None, /) -> None: ... +def ListView_SortItemsEx(hwnd, callback, param=None, /) -> None: ... +def ValidateRect(hWnd, Rect, /): ... +def WNDCLASS() -> _win32typing.PyWNDCLASS: ... +def lpstr(address, /) -> bytes: ... + +CLR_NONE: int +ILC_COLOR: int +ILC_COLOR16: int +ILC_COLOR24: int +ILC_COLOR32: int +ILC_COLOR4: int +ILC_COLOR8: int +ILC_COLORDDB: int +ILC_MASK: int +ILD_BLEND: int +ILD_BLEND25: int +ILD_BLEND50: int +ILD_FOCUS: int +ILD_MASK: int +ILD_NORMAL: int +ILD_SELECTED: int +ILD_TRANSPARENT: int +IMAGE_BITMAP: int +IMAGE_CURSOR: int +IMAGE_ICON: int +LR_CREATEDIBSECTION: int +LR_DEFAULTCOLOR: int +LR_DEFAULTSIZE: int +LR_LOADFROMFILE: int +LR_LOADMAP3DCOLORS: int +LR_LOADTRANSPARENT: int +LR_MONOCHROME: int +LR_SHARED: int +LR_VGACOLOR: int +NIF_ICON: int +NIF_INFO: int +NIF_MESSAGE: int +NIF_STATE: int +NIF_TIP: int +NIIF_ERROR: int +NIIF_ICON_MASK: int +NIIF_INFO: int +NIIF_NONE: int +NIIF_NOSOUND: int +NIIF_WARNING: int +NIM_ADD: int +NIM_DELETE: int +NIM_MODIFY: int +NIM_SETVERSION: int +TPM_BOTTOMALIGN: int +TPM_CENTERALIGN: int +TPM_LEFTALIGN: int +TPM_LEFTBUTTON: int +TPM_NONOTIFY: int +TPM_RETURNCMD: int +TPM_RIGHTALIGN: int +TPM_RIGHTBUTTON: int +TPM_TOPALIGN: int +TPM_VCENTERALIGN: int +UNICODE: Literal[1] +dllhandle: int diff --git a/stubs/pywin32/win32/win32help.pyi b/stubs/pywin32/win32/win32help.pyi new file mode 100644 index 000000000000..811f588e67c2 --- /dev/null +++ b/stubs/pywin32/win32/win32help.pyi @@ -0,0 +1,180 @@ +import _win32typing + +def WinHelp(hwnd: int, hlpFile: str, cmd, data: str | None = ..., /) -> None: ... +def HH_AKLINK() -> _win32typing.PyHH_AKLINK: ... +def HH_FTS_QUERY() -> _win32typing.PyHH_FTS_QUERY: ... +def HH_POPUP() -> _win32typing.PyHH_POPUP: ... +def HH_WINTYPE() -> _win32typing.PyHH_WINTYPE: ... +def NMHDR() -> _win32typing.PyNMHDR: ... +def HHN_NOTIFY() -> _win32typing.PyHHN_NOTIFY: ... +def HHNTRACK() -> _win32typing.PyHHNTRACK: ... +def HtmlHelp(hwnd: int, file: str, cmd, data: str | tuple[int] | int = ..., /): ... + +debug: int +HH_ALINK_LOOKUP: int +HH_CLOSE_ALL: int +HH_DISPLAY_INDEX: int +HH_DISPLAY_SEARCH: int +HH_DISPLAY_TEXT_POPUP: int +HH_DISPLAY_TOC: int +HH_DISPLAY_TOPIC: int +HH_ENUM_CATEGORY: int +HH_ENUM_CATEGORY_IT: int +HH_ENUM_INFO_TYPE: int +HH_FTS_DEFAULT_PROXIMITY: int +HH_GET_LAST_ERROR: int +HH_GET_WIN_HANDLE: int +HH_GET_WIN_TYPE: int +HH_GPROPID_CONTENT_LANGUAGE: int +HH_GPROPID_CURRENT_SUBSET: int +HH_GPROPID_SINGLETHREAD: int +HH_GPROPID_TOOLBAR_MARGIN: int +HH_GPROPID_UI_LANGUAGE: int +HH_HELP_CONTEXT: int +HH_HELP_FINDER: int +HH_INITIALIZE: int +HH_KEYWORD_LOOKUP: int +HH_MAX_TABS_CUSTOM: int +HH_PRETRANSLATEMESSAGE: int +HH_RESERVED1: int +HH_RESERVED2: int +HH_RESERVED3: int +HH_RESET_IT_FILTER: int +HH_SET_EXCLUSIVE_FILTER: int +HH_SET_GLOBAL_PROPERTY: int +HH_SET_INCLUSIVE_FILTER: int +HH_SET_INFO_TYPE: int +HH_SET_WIN_TYPE: int +HH_SYNC: int +HH_TAB_AUTHOR: int +HH_TAB_CONTENTS: int +HH_TAB_CUSTOM_FIRST: int +HH_TAB_CUSTOM_LAST: int +HH_TAB_FAVORITES: int +HH_TAB_HISTORY: int +HH_TAB_INDEX: int +HH_TAB_SEARCH: int +HH_TP_HELP_CONTEXTMENU: int +HH_TP_HELP_WM_HELP: int +HH_UNINITIALIZE: int +HHACT_BACK: int +HHACT_CONTRACT: int +HHACT_CUSTOMIZE: int +HHACT_EXPAND: int +HHACT_FORWARD: int +HHACT_HIGHLIGHT: int +HHACT_HOME: int +HHACT_JUMP1: int +HHACT_JUMP2: int +HHACT_LAST_ENUM: int +HHACT_NOTES: int +HHACT_OPTIONS: int +HHACT_PRINT: int +HHACT_REFRESH: int +HHACT_STOP: int +HHACT_SYNC: int +HHACT_TAB_CONTENTS: int +HHACT_TAB_FAVORITES: int +HHACT_TAB_HISTORY: int +HHACT_TAB_INDEX: int +HHACT_TAB_SEARCH: int +HHACT_TOC_NEXT: int +HHACT_TOC_PREV: int +HHACT_ZOOM: int +HHN_FIRST: int +HHN_LAST: int +HHN_NAVCOMPLETE: int +HHN_TRACK: int +HHN_WINDOW_CREATE: int +HHWIN_BUTTON_BACK: int +HHWIN_BUTTON_BROWSE_BCK: int +HHWIN_BUTTON_BROWSE_FWD: int +HHWIN_BUTTON_CONTENTS: int +HHWIN_BUTTON_EXPAND: int +HHWIN_BUTTON_FAVORITES: int +HHWIN_BUTTON_FORWARD: int +HHWIN_BUTTON_HISTORY: int +HHWIN_BUTTON_HOME: int +HHWIN_BUTTON_INDEX: int +HHWIN_BUTTON_JUMP1: int +HHWIN_BUTTON_JUMP2: int +HHWIN_BUTTON_NOTES: int +HHWIN_BUTTON_OPTIONS: int +HHWIN_BUTTON_PRINT: int +HHWIN_BUTTON_REFRESH: int +HHWIN_BUTTON_SEARCH: int +HHWIN_BUTTON_STOP: int +HHWIN_BUTTON_SYNC: int +HHWIN_BUTTON_TOC_NEXT: int +HHWIN_BUTTON_TOC_PREV: int +HHWIN_BUTTON_ZOOM: int +HHWIN_DEF_BUTTONS: int +HHWIN_NAVTAB_BOTTOM: int +HHWIN_NAVTAB_LEFT: int +HHWIN_NAVTAB_TOP: int +HHWIN_PARAM_CUR_TAB: int +HHWIN_PARAM_EXPANSION: int +HHWIN_PARAM_EXSTYLES: int +HHWIN_PARAM_HISTORY_COUNT: int +HHWIN_PARAM_INFOTYPES: int +HHWIN_PARAM_NAV_WIDTH: int +HHWIN_PARAM_PROPERTIES: int +HHWIN_PARAM_RECT: int +HHWIN_PARAM_SHOWSTATE: int +HHWIN_PARAM_STYLES: int +HHWIN_PARAM_TABORDER: int +HHWIN_PARAM_TABPOS: int +HHWIN_PARAM_TB_FLAGS: int +HHWIN_PROP_AUTO_SYNC: int +HHWIN_PROP_CHANGE_TITLE: int +HHWIN_PROP_MENU: int +HHWIN_PROP_NAV_ONLY_WIN: int +HHWIN_PROP_NO_TOOLBAR: int +HHWIN_PROP_NODEF_EXSTYLES: int +HHWIN_PROP_NODEF_STYLES: int +HHWIN_PROP_NOTB_TEXT: int +HHWIN_PROP_NOTITLEBAR: int +HHWIN_PROP_ONTOP: int +HHWIN_PROP_POST_QUIT: int +HHWIN_PROP_TAB_ADVSEARCH: int +HHWIN_PROP_TAB_AUTOHIDESHOW: int +HHWIN_PROP_TAB_CUSTOM1: int +HHWIN_PROP_TAB_CUSTOM2: int +HHWIN_PROP_TAB_CUSTOM3: int +HHWIN_PROP_TAB_CUSTOM4: int +HHWIN_PROP_TAB_CUSTOM5: int +HHWIN_PROP_TAB_CUSTOM6: int +HHWIN_PROP_TAB_CUSTOM7: int +HHWIN_PROP_TAB_CUSTOM8: int +HHWIN_PROP_TAB_CUSTOM9: int +HHWIN_PROP_TAB_FAVORITES: int +HHWIN_PROP_TAB_HISTORY: int +HHWIN_PROP_TAB_SEARCH: int +HHWIN_PROP_TRACKING: int +HHWIN_PROP_TRI_PANE: int +HHWIN_PROP_USER_POS: int +HHWIN_TB_MARGIN: int +IDTB_BACK: int +IDTB_BROWSE_BACK: int +IDTB_BROWSE_FWD: int +IDTB_CONTENTS: int +IDTB_CONTRACT: int +IDTB_CUSTOMIZE: int +IDTB_EXPAND: int +IDTB_FAVORITES: int +IDTB_FORWARD: int +IDTB_HISTORY: int +IDTB_HOME: int +IDTB_INDEX: int +IDTB_JUMP1: int +IDTB_JUMP2: int +IDTB_NOTES: int +IDTB_OPTIONS: int +IDTB_PRINT: int +IDTB_REFRESH: int +IDTB_SEARCH: int +IDTB_STOP: int +IDTB_SYNC: int +IDTB_TOC_NEXT: int +IDTB_TOC_PREV: int +IDTB_ZOOM: int diff --git a/stubs/pywin32/win32/win32inet.pyi b/stubs/pywin32/win32/win32inet.pyi new file mode 100644 index 000000000000..77bd3645eed2 --- /dev/null +++ b/stubs/pywin32/win32/win32inet.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +def InternetSetCookie(url: str, lpszCookieName: str, data: str, /) -> None: ... +def InternetGetCookie(Url: str, CookieName: str, /) -> str: ... +def InternetAttemptConnect(Reserved: int = ..., /) -> None: ... +def InternetCheckConnection(Url: str, Flags: int = ..., Reserved: int = ..., /) -> None: ... +def InternetGoOnline(Url: str, Parent: Incomplete | None = ..., Flags: int = ..., /) -> None: ... +def InternetCloseHandle(handle: _win32typing.PyHINTERNET, /) -> None: ... +def InternetConnect( + Internet: _win32typing.PyHINTERNET, + ServerName: str, + ServerPort, + Username: str, + Password: str, + Service, + Flags, + Context: Incomplete | None = ..., +) -> None: ... +def InternetOpen(agent: str, proxyName: str, proxyBypass: str, flags) -> None: ... +def InternetOpenUrl( + Internet: _win32typing.PyHINTERNET, Url: str, Headers: str | None = ..., Flags: int = ..., Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def InternetCanonicalizeUrl(url: str, flags: int = ..., /) -> str: ... +def InternetGetLastResponseInfo() -> tuple[Incomplete, str]: ... +def InternetReadFile(hInternet: _win32typing.PyHINTERNET, size, /) -> str: ... +def InternetWriteFile(File: _win32typing.PyHINTERNET, Buffer: str, /): ... +def FtpOpenFile( + Connect: _win32typing.PyHINTERNET, FileName: str, Access, Flags, Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def FtpCommand( + Connect: _win32typing.PyHINTERNET, ExpectResponse, Flags, Command: str, Context: Incomplete | None = ... +) -> _win32typing.PyHINTERNET: ... +def InternetQueryOption(hInternet: _win32typing.PyHINTERNET, Option, /): ... +def InternetSetOption(hInternet: _win32typing.PyHINTERNET, Option, Buffer, /) -> None: ... +def FindFirstUrlCacheEntry(SearchPattern: Incomplete | None = ...) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheEntry(EnumHandle: _win32typing.PyUrlCacheHANDLE): ... +def FindFirstUrlCacheEntryEx( + SearchPattern: Incomplete | None = ..., Flags: int = ..., Filter: int = ..., GroupId=... +) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheEntryEx(EnumHandle: _win32typing.PyUrlCacheHANDLE): ... +def FindCloseUrlCache(EnumHandle: _win32typing.PyUrlCacheHANDLE) -> None: ... +def FindFirstUrlCacheGroup(Filter=...) -> tuple[_win32typing.PyUrlCacheHANDLE, Incomplete]: ... +def FindNextUrlCacheGroup(Find: int): ... +def GetUrlCacheEntryInfo(UrlName): ... +def DeleteUrlCacheGroup(GroupId, Attributes=...) -> None: ... +def CreateUrlCacheGroup(Flags: int = ...): ... +def CreateUrlCacheEntry(UrlName, ExpectedFileSize, FileExtension): ... +def CommitUrlCacheEntry( + UrlName, + LocalFileName, + CacheEntryType, + ExpireTime: TimeType | None = ..., + LastModifiedTime: TimeType | None = ..., + HeaderInfo: Incomplete | None = ..., + OriginalUrl: Incomplete | None = ..., +): ... +def SetUrlCacheEntryGroup(UrlName, Flags, GroupId) -> None: ... +def GetUrlCacheGroupAttribute(GroupId, Attributes=...): ... +def SetUrlCacheGroupAttribute(GroupId, Attributes, GroupInfo, Flags=...) -> None: ... +def DeleteUrlCacheEntry(UrlName, /) -> None: ... +def WinHttpGetDefaultProxyConfiguration(): ... +def WinHttpGetIEProxyConfigForCurrentUser() -> tuple[int, str, str, str]: ... +def WinHttpGetProxyForUrl(handle: _win32typing.PyHANDLE | int | None, url: str, options: tuple[int | str | None, ...], /): ... +def WinHttpOpen(lpszUserAgent: str, dwAccessType: int, lpszProxyName: str, lpszProxyBypass: str, dwFlags: int, /): ... + +UNICODE: int diff --git a/stubs/pywin32/win32/win32job.pyi b/stubs/pywin32/win32/win32job.pyi new file mode 100644 index 000000000000..7b3ded8d35f4 --- /dev/null +++ b/stubs/pywin32/win32/win32job.pyi @@ -0,0 +1,74 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def AssignProcessToJobObject(hJob: int, hProcess: int, /) -> None: ... +def CreateJobObject(jobAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, name: str, /) -> None: ... +def OpenJobObject(desiredAccess, inheritHandles, name, /) -> None: ... +def TerminateJobObject(hJob: int, exitCode, /) -> None: ... +def UserHandleGrantAccess(hUserHandle: int, hJob: int, grant, /) -> None: ... +def IsProcessInJob(hProcess: int, hJob: int, /): ... +def QueryInformationJobObject(Job: int, JobObjectInfoClass, /): ... +def SetInformationJobObject(Job: int, JobObjectInfoClass, JobObjectInfo, /) -> None: ... + +JOB_OBJECT_ALL_ACCESS: int +JOB_OBJECT_ASSIGN_PROCESS: int +JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS: int +JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS: int +JOB_OBJECT_LIMIT_ACTIVE_PROCESS: int +JOB_OBJECT_LIMIT_AFFINITY: int +JOB_OBJECT_LIMIT_BREAKAWAY_OK: int +JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: int +JOB_OBJECT_LIMIT_JOB_MEMORY: int +JOB_OBJECT_LIMIT_JOB_TIME: int +JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: int +JOB_OBJECT_LIMIT_PRESERVE_JOB_TIME: int +JOB_OBJECT_LIMIT_PRIORITY_CLASS: int +JOB_OBJECT_LIMIT_PROCESS_MEMORY: int +JOB_OBJECT_LIMIT_PROCESS_TIME: int +JOB_OBJECT_LIMIT_SCHEDULING_CLASS: int +JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK: int +JOB_OBJECT_LIMIT_VALID_FLAGS: int +JOB_OBJECT_LIMIT_WORKINGSET: int +JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS: int +JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT: int +JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: int +JOB_OBJECT_MSG_END_OF_JOB_TIME: int +JOB_OBJECT_MSG_END_OF_PROCESS_TIME: int +JOB_OBJECT_MSG_EXIT_PROCESS: int +JOB_OBJECT_MSG_JOB_MEMORY_LIMIT: int +JOB_OBJECT_MSG_NEW_PROCESS: int +JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT: int +JOB_OBJECT_POST_AT_END_OF_JOB: int +JOB_OBJECT_QUERY: int +JOB_OBJECT_SECURITY_FILTER_TOKENS: int +JOB_OBJECT_SECURITY_NO_ADMIN: int +JOB_OBJECT_SECURITY_ONLY_TOKEN: int +JOB_OBJECT_SECURITY_RESTRICTED_TOKEN: int +JOB_OBJECT_SECURITY_VALID_FLAGS: int +JOB_OBJECT_SET_ATTRIBUTES: int +JOB_OBJECT_SET_SECURITY_ATTRIBUTES: int +JOB_OBJECT_TERMINATE: int +JOB_OBJECT_TERMINATE_AT_END_OF_JOB: int +JOB_OBJECT_UI_VALID_FLAGS: int +JOB_OBJECT_UILIMIT_ALL: int +JOB_OBJECT_UILIMIT_DESKTOP: int +JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: int +JOB_OBJECT_UILIMIT_EXITWINDOWS: int +JOB_OBJECT_UILIMIT_GLOBALATOMS: int +JOB_OBJECT_UILIMIT_HANDLES: int +JOB_OBJECT_UILIMIT_NONE: int +JOB_OBJECT_UILIMIT_READCLIPBOARD: int +JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: int +JOB_OBJECT_UILIMIT_WRITECLIPBOARD: int +JobObjectAssociateCompletionPortInformation: int +JobObjectBasicAccountingInformation: int +JobObjectBasicAndIoAccountingInformation: int +JobObjectBasicLimitInformation: int +JobObjectBasicUIRestrictions: int +JobObjectEndOfJobTimeInformation: int +JobObjectExtendedLimitInformation: int +JobObjectJobSetInformation: int +JobObjectSecurityLimitInformation: int +MaxJobObjectInfoClass: int +JobObjectBasicProcessIdList: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32lz.pyi b/stubs/pywin32/win32/win32lz.pyi new file mode 100644 index 000000000000..711744c480b1 --- /dev/null +++ b/stubs/pywin32/win32/win32lz.pyi @@ -0,0 +1,9 @@ +from _typeshed import Incomplete + +from win32.lib.pywintypes import error as error + +def GetExpandedName(Source, /) -> str: ... +def Close(handle, /) -> None: ... +def Copy(hSrc, hDest, /): ... +def Init(handle, /) -> None: ... +def OpenFile(fileName: str, action, /) -> tuple[Incomplete, Incomplete]: ... diff --git a/stubs/pywin32/win32/win32net.pyi b/stubs/pywin32/win32/win32net.pyi new file mode 100644 index 000000000000..2a01d0e39135 --- /dev/null +++ b/stubs/pywin32/win32/win32net.pyi @@ -0,0 +1,94 @@ +from _typeshed import Incomplete + +from win32.lib.pywintypes import error as error + +def NetGetJoinInformation() -> tuple[str, Incomplete]: ... +def NetGroupGetInfo(server: str, groupname: str, level, /): ... +def NetGroupGetUsers( + server: str, groupName: str, level, resumeHandle: int = ..., prefLen: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetGroupSetUsers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetGroupSetInfo(server: str, groupname: str, level, data, /) -> None: ... +def NetGroupAdd(server: str, level, data, /) -> None: ... +def NetGroupAddUser(server: str, group: str, username: str, /) -> None: ... +def NetGroupDel(server: str, groupname: str, /) -> None: ... +def NetGroupDelUser(server: str, group: str, username: str, /) -> None: ... +def NetGroupEnum(server: str, level, prefLen, resumeHandle=..., /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetLocalGroupAddMembers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetLocalGroupDelMembers(server: str, group: str, members: list[str], /) -> None: ... +def NetLocalGroupGetMembers( + server: str, groupName: str, level, resumeHandle: int = ..., prefLen: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetLocalGroupSetMembers(server: str, group: str, level, members: tuple[Incomplete, Incomplete], /) -> None: ... +def NetMessageBufferSend(domain: str, userName: str, fromName: str, message: str, /) -> None: ... +def NetMessageNameAdd(server, msgname, /) -> None: ... +def NetMessageNameDel(server, msgname, /) -> None: ... +def NetMessageNameEnum(Server, /) -> None: ... +def NetServerEnum( + server: str, level, _type, prefLen, domain: str | None = ..., resumeHandle: int = ..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetServerGetInfo(server: str, level, /): ... +def NetServerSetInfo(server: str, level, data, /) -> None: ... +def NetShareAdd(server: str, level, data, /) -> None: ... +def NetShareDel(server: str, shareName: str, reserved: int = ..., /) -> None: ... +def NetShareCheck(server: str, deviceName: str, /) -> tuple[Incomplete, Incomplete]: ... +def NetShareEnum( + server: str, level, prefLen, serverName, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetShareGetInfo(server: str, netname: str, level, /): ... +def NetShareSetInfo(server: str, netname: str, level, data, /) -> None: ... +def NetUserAdd(server: str, level, data, /) -> None: ... +def NetUserChangePassword(server: str, username: str, oldPassword: str, newPassword: str, /) -> None: ... +def NetUserEnum( + server: str, level, arg, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetUserGetGroups(serverName: str, userName: str, /) -> list[tuple[Incomplete, Incomplete]]: ... +def NetUserGetInfo(server: str, username: str, level, /): ... +def NetUserGetLocalGroups(serverName: str, userName: str, flags, /) -> list[Incomplete]: ... +def NetUserSetInfo(server: str, username: str, level, data, /) -> None: ... +def NetUserDel(server: str, username: str, /) -> None: ... +def NetUserModalsGet(server: str, level, /): ... +def NetUserModalsSet(server: str, level, data, /) -> None: ... +def NetWkstaUserEnum( + server: str, level, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetWkstaGetInfo(server: str, level, /): ... +def NetWkstaSetInfo(server: str, level, data, /) -> None: ... +def NetWkstaTransportEnum( + server: str, level, prefLen, resumeHandle=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetWkstaTransportAdd(server: str, level, data, /) -> None: ... +def NetWkstaTransportDel(server: str, TransportName: str, ucond: int = ..., /) -> None: ... +def NetServerDiskEnum(server: str, level, /): ... +def NetUseAdd(server: str, level, data, /) -> None: ... +def NetUseDel(server: str, useName: str, forceCond: int = ..., /) -> None: ... +def NetUseEnum(server: str, level, prefLen, resumeHandle=..., /) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +def NetUseGetInfo(server: str, usename: str, level: int = ..., /): ... +def NetGetAnyDCName(server: str | None = ..., domain: str | None = ..., /) -> str: ... +def NetGetDCName(server: str | None = ..., domain: str | None = ..., /) -> str: ... +def NetSessionEnum( + level, server: str | None = ..., client: str | None = ..., username: str | None = ..., / +) -> tuple[Incomplete, ...]: ... +def NetSessionDel(server: str, client: str | None = ..., username: str | None = ..., /) -> None: ... +def NetSessionGetInfo(level, server: str, client: str, username: str, /): ... +def NetFileEnum( + level, servername: str | None = ..., basepath: str | None = ..., username: str | None = ..., / +) -> tuple[Incomplete, ...]: ... +def NetFileClose(servername: str, fileid, /) -> None: ... +def NetFileGetInfo(level, servername: str, fileid, /): ... +def NetStatisticsGet(server: str, service: str, level, options, /): ... +def NetServerComputerNameAdd(ServerName: str, EmulatedDomainName: str, EmulatedServerName: str, /) -> None: ... +def NetServerComputerNameDel(ServerName: str, EmulatedServerName: str, /) -> None: ... +def NetValidateName(Server: str, Name: str, NameType, Account: str | None = ..., Password: str | None = ..., /) -> None: ... +def NetValidatePasswordPolicy(Server: str, Qualifier, ValidationType, arg, /) -> None: ... +def NetLocalGroupAdd(server: str, level: int, data, /) -> None: ... +def NetLocalGroupDel(server: str, groupname: str, data, /) -> None: ... +def NetLocalGroupEnum(server: str, level: int, resumeHandle=..., prefLen: int = ..., /): ... +def NetLocalGroupGetInfo(server: str, groupname: str, level: int, /): ... +def NetLocalGroupSetInfo(server: str, groupname: str, level: int, data, /) -> None: ... + +SERVICE_SERVER: str +SERVICE_WORKSTATION: str +USE_FORCE: int +USE_LOTS_OF_FORCE: int +USE_NOFORCE: int diff --git a/stubs/pywin32/win32/win32pdh.pyi b/stubs/pywin32/win32/win32pdh.pyi new file mode 100644 index 000000000000..e70db79eb204 --- /dev/null +++ b/stubs/pywin32/win32/win32pdh.pyi @@ -0,0 +1,63 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def AddCounter(hQuery, path: str, userData: int = ..., /): ... +def AddEnglishCounter(hQuery, path: str, userData: int = ..., /): ... +def RemoveCounter(handle, /) -> None: ... +def EnumObjectItems(DataSource: str | None, machine: str | None, _object: str, detailLevel, flags=..., /): ... +def EnumObjects(DataSource: str | None, machine: str | None, detailLevel: int, refresh: bool = ..., /): ... +def OpenQuery(DataSource: Incomplete | None = ..., userData: int = ..., /): ... +def CloseQuery(handle, /) -> None: ... +def MakeCounterPath( + elements: tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete], flags=..., / +) -> str: ... +def GetCounterInfo(handle, bRetrieveExplainText, /) -> None: ... +def GetFormattedCounterValue(handle, _format, /) -> tuple[Incomplete, Incomplete]: ... +def CollectQueryData(hQuery, /) -> None: ... +def ValidatePath(path: str, /): ... +def ExpandCounterPath(wildCardPath: str, /) -> tuple[Incomplete, Incomplete]: ... +def ParseCounterPath( + path: str, flags=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... +def ParseInstanceName(instanceName: str, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def SetCounterScaleFactor(hCounter, factor, /) -> None: ... +def BrowseCounters( + Flags: tuple[Incomplete, ...] | None, + hWndOwner: int, + CallBack, + DefaultDetailLevel, + DialogBoxCaption: str | None = ..., + InitialPath: Incomplete | None = ..., + DataSource: Incomplete | None = ..., + ReturnMultiple: bool = ..., + CallBackArg: Incomplete | None = ..., +) -> str: ... +def ConnectMachine(machineName: str, /) -> str: ... +def LookupPerfIndexByName(machineName: str, instanceName: str, /): ... +def LookupPerfNameByIndex(machineName: str | None, index, /) -> str: ... +def GetFormattedCounterArray(handle: _win32typing.PyHANDLE | int | None, format: int, /) -> dict[Incomplete, Incomplete]: ... + +PDH_FMT_1000: int +PDH_FMT_ANSI: int +PDH_FMT_DOUBLE: int +PDH_FMT_LARGE: int +PDH_FMT_LONG: int +PDH_FMT_NODATA: int +PDH_FMT_NOSCALE: int +PDH_FMT_RAW: int +PDH_FMT_UNICODE: int +PDH_MAX_SCALE: int +PDH_MIN_SCALE: int +PDH_PATH_WBEM_INPUT: int +PDH_PATH_WBEM_RESULT: int +PDH_VERSION: int +PERF_DETAIL_ADVANCED: int +PERF_DETAIL_EXPERT: int +PERF_DETAIL_NOVICE: int +PERF_DETAIL_WIZARD: int + +class counter_status_error(Exception): ... + +PDH_FMT_NOCAP100: int diff --git a/stubs/pywin32/win32/win32pipe.pyi b/stubs/pywin32/win32/win32pipe.pyi new file mode 100644 index 000000000000..14779bdc04ff --- /dev/null +++ b/stubs/pywin32/win32/win32pipe.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetNamedPipeHandleState( + hPipe: int, bGetCollectionData=..., / +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, str]: ... +def SetNamedPipeHandleState( + hPipe: int, Mode: int, MaxCollectionCount: None | Incomplete, CollectDataTimeout: None | Incomplete, / +) -> None: ... +def ConnectNamedPipe(hPipe: int, overlapped: _win32typing.PyOVERLAPPED | None = ..., /): ... +def TransactNamedPipe( + pipeName, + writeData: str, + buffer_bufSize: _win32typing.PyOVERLAPPEDReadBuffer, + overlapped: _win32typing.PyOVERLAPPED | None = ..., + /, +) -> str: ... +def CallNamedPipe(pipeName, data: str, bufSize, timeOut, /) -> str: ... +def CreatePipe(sa: _win32typing.PySECURITY_ATTRIBUTES, nSize: int, /) -> tuple[int, int]: ... +def FdCreatePipe(sa: _win32typing.PySECURITY_ATTRIBUTES, nSize, mode, /) -> tuple[Incomplete, Incomplete]: ... +def CreateNamedPipe( + pipeName: str, + openMode, + pipeMode, + nMaxInstances, + nOutBufferSize, + nInBufferSize, + nDefaultTimeOut, + sa: _win32typing.PySECURITY_ATTRIBUTES, + /, +) -> int: ... +def DisconnectNamedPipe(hFile: int, /) -> None: ... +def GetOverlappedResult(hFile: int, overlapped: _win32typing.PyOVERLAPPED, bWait: int | bool, /) -> int: ... +def WaitNamedPipe(pipeName: str, timeout, /) -> None: ... +def GetNamedPipeInfo(hNamedPipe: int, /) -> tuple[int, int, int, int]: ... +def PeekNamedPipe(hPipe: int, size: int, /) -> tuple[str, int, Incomplete]: ... +def GetNamedPipeClientProcessId(hPipe: int, /): ... +def GetNamedPipeServerProcessId(hPipe: int, /): ... +def GetNamedPipeClientSessionId(hPipe: int, /): ... +def GetNamedPipeServerSessionId(hPipe: int, /): ... +def popen(cmdstring: str, mode: str, /): ... +def popen2(*args): ... # incomplete +def popen3(*args): ... # incomplete +def popen4(*args): ... # incomplete + +FILE_FLAG_FIRST_PIPE_INSTANCE: int +PIPE_ACCEPT_REMOTE_CLIENTS: int +PIPE_REJECT_REMOTE_CLIENTS: int +NMPWAIT_NOWAIT: int +NMPWAIT_USE_DEFAULT_WAIT: int +NMPWAIT_WAIT_FOREVER: int +PIPE_ACCESS_DUPLEX: int +PIPE_ACCESS_INBOUND: int +PIPE_ACCESS_OUTBOUND: int +PIPE_NOWAIT: int +PIPE_READMODE_BYTE: int +PIPE_READMODE_MESSAGE: int +PIPE_TYPE_BYTE: int +PIPE_TYPE_MESSAGE: int +PIPE_UNLIMITED_INSTANCES: int +PIPE_WAIT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32print.pyi b/stubs/pywin32/win32/win32print.pyi new file mode 100644 index 000000000000..224a05a570fb --- /dev/null +++ b/stubs/pywin32/win32/win32print.pyi @@ -0,0 +1,365 @@ +from typing import Final, Literal, overload + +import _win32typing + +def OpenPrinter(printer: str, Defaults: _win32typing.PrinterDefaults | None = None, /) -> _win32typing.PyPrinterHANDLE: ... + +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> _win32typing.PrinterInfo2Tuple: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[1], /) -> _win32typing.PrinterInfo1: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[2], /) -> _win32typing.PrinterInfo2: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[3], /) -> _win32typing.PrinterInfo3: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[4], /) -> _win32typing.PrinterInfo4: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[5], /) -> _win32typing.PrinterInfo5: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[6], /) -> _win32typing.PrinterInfo6: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[7], /) -> _win32typing.PrinterInfo7: ... +@overload +def GetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[8, 9], /) -> _win32typing.PrinterInfo89: ... + +@overload +def SetPrinter(hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[0], pPrinter: int | None, Command: int, /) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[2], pPrinter: _win32typing.PrinterInfo2, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[3], pPrinter: _win32typing.PrinterInfo3, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[4], pPrinter: _win32typing.PrinterInfo4, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[5], pPrinter: _win32typing.PrinterInfo5, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[6], pPrinter: _win32typing.PrinterInfo6, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[7], pPrinter: _win32typing.PrinterInfo7, Command: Literal[0], / +) -> None: ... +@overload +def SetPrinter( + hPrinter: _win32typing.PyPrinterHANDLE, Level: Literal[8, 9], pPrinter: _win32typing.PrinterInfo89, Command: Literal[0], / +) -> None: ... + +def ClosePrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def AddPrinterConnection(printer: str, /) -> None: ... +def DeletePrinterConnection(printer: str, /) -> None: ... + +@overload +def EnumPrinters(flags: int, name: str | None = None, level: Literal[1] = 1, /) -> tuple[_win32typing.PrinterInfo1Tuple, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[2], /) -> tuple[_win32typing.PrinterInfo2, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[4], /) -> tuple[_win32typing.PrinterInfo4, ...]: ... +@overload +def EnumPrinters(flags: int, name: str | None, level: Literal[5], /) -> tuple[_win32typing.PrinterInfo5, ...]: ... + +def GetDefaultPrinter() -> str: ... +def GetDefaultPrinterW() -> str: ... +def SetDefaultPrinter(printer: str, /) -> None: ... +def SetDefaultPrinterW(Printer: str | None, /) -> None: ... +def StartDocPrinter( + hprinter: _win32typing.PyPrinterHANDLE, level: Literal[1], tuple: tuple[str, str | None, str | None], / +) -> int: ... +def EndDocPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def AbortPrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def StartPagePrinter(hprinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def EndPagePrinter(hprinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def StartDoc(hdc: int, docinfo: tuple[str, str | None, str | None, int], /) -> int: ... +def EndDoc(hdc: int, /) -> None: ... +def AbortDoc(hdc: int, /) -> None: ... +def StartPage(hdc: int, /) -> None: ... +def EndPage(hdc: int, /) -> None: ... +def WritePrinter(hprinter: _win32typing.PyPrinterHANDLE, buf: bytes | bytearray | memoryview, /) -> int: ... + +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[1] = 1, / +) -> tuple[_win32typing.JobInfo1, ...]: ... +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[2], / +) -> tuple[_win32typing.JobInfo2, ...]: ... +@overload +def EnumJobs( + hPrinter: _win32typing.PyPrinterHANDLE, FirstJob: int, NoJobs: int, Level: Literal[3], / +) -> tuple[_win32typing.JobInfo3, ...]: ... + +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[1] = 1, /) -> _win32typing.JobInfo1: ... +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[2], /) -> _win32typing.JobInfo2: ... +@overload +def GetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[3], /) -> _win32typing.JobInfo3: ... + +@overload +def SetJob(hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[0], JobInfo: None, Command: int, /) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[1], JobInfo: _win32typing.JobInfo1, Command: int, / +) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[2], JobInfo: _win32typing.JobInfo2, Command: int, / +) -> None: ... +@overload +def SetJob( + hPrinter: _win32typing.PyPrinterHANDLE, JobID: int, Level: Literal[3], JobInfo: _win32typing.JobInfo3, Command: int, / +) -> None: ... + +def DocumentProperties( + HWnd: int, + hPrinter: _win32typing.PyPrinterHANDLE, + DeviceName: str, + DevModeOutput: _win32typing.PyDEVMODEW, + DevModeInput: _win32typing.PyDEVMODEW, + Mode: int, + /, +) -> int: ... +def EnumPrintProcessors(Server: str | None = None, Environment: str | None = None, /) -> tuple[str, ...]: ... +def EnumPrintProcessorDatatypes(ServerName: str | None, PrintProcessorName: str, /) -> tuple[str, ...]: ... + +@overload +def EnumPrinterDrivers( + Server: str | None = None, Environment: str | None = None, Level: Literal[1] = 1, / +) -> tuple[_win32typing.DriverInfo1, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[2], / +) -> tuple[_win32typing.DriverInfo2, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[3], / +) -> tuple[_win32typing.DriverInfo3, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[4], / +) -> tuple[_win32typing.DriverInfo4, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[5], / +) -> tuple[_win32typing.DriverInfo5, ...]: ... +@overload +def EnumPrinterDrivers( + Server: str | None, Environment: str | None, Level: Literal[6], / +) -> tuple[_win32typing.DriverInfo6, ...]: ... + +def EnumForms(hprinter: _win32typing.PyPrinterHANDLE, /) -> tuple[_win32typing.FormInfo1, ...]: ... +def AddForm(hprinter: _win32typing.PyPrinterHANDLE, Form: _win32typing.FormInfo1, /) -> None: ... +def DeleteForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, /) -> None: ... +def GetForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, /) -> _win32typing.FormInfo1: ... +def SetForm(hprinter: _win32typing.PyPrinterHANDLE, FormName: str, Form: _win32typing.FormInfo1, /) -> None: ... +def AddJob(hprinter: _win32typing.PyPrinterHANDLE, /) -> tuple[str, int]: ... +def ScheduleJob(hprinter: _win32typing.PyPrinterHANDLE, JobId: int, /) -> None: ... + +@overload +# DC_MINEXTENT, DC_MAXEXTENT +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[4, 5], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> _win32typing.PrinterExtents: ... +@overload +# DC_ENUMRESOLUTIONS +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[13], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[_win32typing.PrinterDpi, ...]: ... +@overload +# DC_PAPERS, DC_BINS, DC_NUP, DC_MEDIATYPES +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[2, 6, 33, 35], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[int, ...]: ... +@overload +# DC_BINNAMES, DC_FILEDEPENDENCIES, DC_PAPERNAMES, DC_PERSONALITY, DC_MEDIAREADY, DC_MEDIATYPENAMES +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[12, 14, 16, 25, 29, 34], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[str, ...]: ... +@overload +# DC_PAPERSIZE +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, Port: str, Capability: Literal[3], DEVMODE: _win32typing.PyDEVMODEW | None = None, / +) -> tuple[_win32typing.PrinterPaperSize, ...]: ... +@overload +# DC_FIELDS, DC_DUPLEX, DC_SIZE, DC_EXTRA, DC_VERSION, DC_DRIVER, DC_TRUETYPE, DC_ORIENTATION, DC_COPIES +# DC_COLLATE, DC_PRINTRATE, DC_PRINTRATEUNIT, DC_PRINTERMEM, DC_STAPLE, DC_PRINTRATEPPM, DC_COLORDEVICE +def DeviceCapabilities( # type: ignore[overload-overlap] + Device: str, + Port: str, + Capability: Literal[1, 7, 8, 9, 10, 11, 15, 17, 18, 22, 26, 27, 28, 30, 31, 32], + DEVMODE: _win32typing.PyDEVMODEW | None = None, + /, +) -> int: ... +@overload +def DeviceCapabilities(Device: str, Port: str, Capability: int, DEVMODE: _win32typing.PyDEVMODEW | None = None, /) -> int: ... + +def GetDeviceCaps(hdc: int | _win32typing.PyHANDLE, Index: int, /) -> int: ... + +@overload +def EnumMonitors(Name: str | None, Level: Literal[1], /) -> tuple[_win32typing.MonitorInfo1, ...]: ... +@overload +def EnumMonitors(Name: str | None, Level: Literal[2], /) -> tuple[_win32typing.MonitorInfo2, ...]: ... + +@overload +def EnumPorts(Name: str | None, Level: Literal[1], /) -> tuple[_win32typing.PortInfo1, ...]: ... +@overload +def EnumPorts(Name: str | None, Level: Literal[2], /) -> tuple[_win32typing.PortInfo2, ...]: ... + +def GetPrintProcessorDirectory(Name: str | None = None, Environment: str | None = None, /) -> str: ... +def GetPrinterDriverDirectory(Name: str | None = None, Environment: str | None = None, /) -> str: ... +def AddPrinter(Name: str | None, Level: Literal[2], pPrinter: _win32typing.PrinterInfo2, /) -> _win32typing.PyPrinterHANDLE: ... +def DeletePrinter(hPrinter: _win32typing.PyPrinterHANDLE, /) -> None: ... +def DeletePrinterDriver(Server: str | None, Environment: str | None, DriverName: str, /) -> None: ... +def DeletePrinterDriverEx( + Server: str | None, Environment: str | None, DriverName: str, DeleteFlag: int, VersionFlag: Literal[0, 1, 2, 3], / +) -> None: ... +def FlushPrinter(Printer: _win32typing.PyPrinterHANDLE, Buf: bytes, Sleep: int, /) -> int: ... + +DEF_PRIORITY: int +DI_APPBANDING: int +DI_ROPS_READ_DESTINATION: int +DPD_DELETE_ALL_FILES: int +DPD_DELETE_SPECIFIC_VERSION: int +DPD_DELETE_UNUSED_FILES: int +DSPRINT_PENDING: int +DSPRINT_PUBLISH: int +DSPRINT_REPUBLISH: int +DSPRINT_UNPUBLISH: int +DSPRINT_UPDATE: int +FORM_BUILTIN: int +FORM_PRINTER: int +FORM_USER: int +JOB_ACCESS_ADMINISTER: int +JOB_ACCESS_READ: int +JOB_ALL_ACCESS: int +JOB_CONTROL_CANCEL: int +JOB_CONTROL_DELETE: int +JOB_CONTROL_LAST_PAGE_EJECTED: int +JOB_CONTROL_PAUSE: int +JOB_CONTROL_RESTART: int +JOB_CONTROL_RESUME: int +JOB_CONTROL_SENT_TO_PRINTER: int +JOB_EXECUTE: int +JOB_INFO_1: int +JOB_POSITION_UNSPECIFIED: int +JOB_READ: int +JOB_STATUS_BLOCKED_DEVQ: int +JOB_STATUS_COMPLETE: int +JOB_STATUS_DELETED: int +JOB_STATUS_DELETING: int +JOB_STATUS_ERROR: int +JOB_STATUS_OFFLINE: int +JOB_STATUS_PAPEROUT: int +JOB_STATUS_PAUSED: int +JOB_STATUS_PRINTED: int +JOB_STATUS_PRINTING: int +JOB_STATUS_RESTART: int +JOB_STATUS_SPOOLING: int +JOB_STATUS_USER_INTERVENTION: int +JOB_WRITE: int +MAX_PRIORITY: int +MIN_PRIORITY: int +PORT_STATUS_DOOR_OPEN: int +PORT_STATUS_NO_TONER: int +PORT_STATUS_OFFLINE: int +PORT_STATUS_OUTPUT_BIN_FULL: int +PORT_STATUS_OUT_OF_MEMORY: int +PORT_STATUS_PAPER_JAM: int +PORT_STATUS_PAPER_OUT: int +PORT_STATUS_PAPER_PROBLEM: int +PORT_STATUS_POWER_SAVE: int +PORT_STATUS_TONER_LOW: int +PORT_STATUS_TYPE_ERROR: int +PORT_STATUS_TYPE_INFO: int +PORT_STATUS_TYPE_WARNING: int +PORT_STATUS_USER_INTERVENTION: int +PORT_STATUS_WARMING_UP: int +PORT_TYPE_NET_ATTACHED: int +PORT_TYPE_READ: int +PORT_TYPE_REDIRECTED: int +PORT_TYPE_WRITE: int +PRINTER_ACCESS_ADMINISTER: int +PRINTER_ACCESS_USE: int +PRINTER_ALL_ACCESS: int +PRINTER_ATTRIBUTE_DEFAULT: int +PRINTER_ATTRIBUTE_DIRECT: int +PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST: int +PRINTER_ATTRIBUTE_ENABLE_BIDI: int +PRINTER_ATTRIBUTE_ENABLE_DEVQ: int +PRINTER_ATTRIBUTE_FAX: int +PRINTER_ATTRIBUTE_HIDDEN: int +PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS: int +PRINTER_ATTRIBUTE_LOCAL: int +PRINTER_ATTRIBUTE_NETWORK: int +PRINTER_ATTRIBUTE_PUBLISHED: int +PRINTER_ATTRIBUTE_QUEUED: int +PRINTER_ATTRIBUTE_RAW_ONLY: int +PRINTER_ATTRIBUTE_SHARED: int +PRINTER_ATTRIBUTE_TS: int +PRINTER_ATTRIBUTE_WORK_OFFLINE: int +PRINTER_CONTROL_PAUSE: int +PRINTER_CONTROL_PURGE: int +PRINTER_CONTROL_RESUME: int +PRINTER_CONTROL_SET_STATUS: int +PRINTER_ENUM_CONNECTIONS: int +PRINTER_ENUM_CONTAINER: int +PRINTER_ENUM_DEFAULT: int +PRINTER_ENUM_EXPAND: int +PRINTER_ENUM_ICON1: int +PRINTER_ENUM_ICON2: int +PRINTER_ENUM_ICON3: int +PRINTER_ENUM_ICON4: int +PRINTER_ENUM_ICON5: int +PRINTER_ENUM_ICON6: int +PRINTER_ENUM_ICON7: int +PRINTER_ENUM_ICON8: int +PRINTER_ENUM_LOCAL: int +PRINTER_ENUM_NAME: int +PRINTER_ENUM_NETWORK: int +PRINTER_ENUM_REMOTE: int +PRINTER_ENUM_SHARED: int +PRINTER_EXECUTE: int +PRINTER_INFO_1: Final = 1 +PRINTER_READ: int +PRINTER_STATUS_BUSY: int +PRINTER_STATUS_DOOR_OPEN: int +PRINTER_STATUS_ERROR: int +PRINTER_STATUS_INITIALIZING: int +PRINTER_STATUS_IO_ACTIVE: int +PRINTER_STATUS_MANUAL_FEED: int +PRINTER_STATUS_NOT_AVAILABLE: int +PRINTER_STATUS_NO_TONER: int +PRINTER_STATUS_OFFLINE: int +PRINTER_STATUS_OUTPUT_BIN_FULL: int +PRINTER_STATUS_OUT_OF_MEMORY: int +PRINTER_STATUS_PAGE_PUNT: int +PRINTER_STATUS_PAPER_JAM: int +PRINTER_STATUS_PAPER_OUT: int +PRINTER_STATUS_PAPER_PROBLEM: int +PRINTER_STATUS_PAUSED: int +PRINTER_STATUS_PENDING_DELETION: int +PRINTER_STATUS_POWER_SAVE: int +PRINTER_STATUS_PRINTING: int +PRINTER_STATUS_PROCESSING: int +PRINTER_STATUS_SERVER_UNKNOWN: int +PRINTER_STATUS_TONER_LOW: int +PRINTER_STATUS_USER_INTERVENTION: int +PRINTER_STATUS_WAITING: int +PRINTER_STATUS_WARMING_UP: int +PRINTER_WRITE: int +SERVER_ACCESS_ADMINISTER: int +SERVER_ACCESS_ENUMERATE: int +SERVER_ALL_ACCESS: int +SERVER_EXECUTE: int +SERVER_READ: int +SERVER_WRITE: int diff --git a/stubs/pywin32/win32/win32process.pyi b/stubs/pywin32/win32/win32process.pyi new file mode 100644 index 000000000000..4dc05a0d8378 --- /dev/null +++ b/stubs/pywin32/win32/win32process.pyi @@ -0,0 +1,124 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def STARTUPINFO() -> _win32typing.PySTARTUPINFO: ... +def beginthreadex(sa: _win32typing.PySECURITY_ATTRIBUTES, stackSize, entryPoint, args, flags, /) -> tuple[int, Incomplete]: ... +def CreateRemoteThread( + hprocess: int, sa: _win32typing.PySECURITY_ATTRIBUTES, stackSize, entryPoint, Parameter, flags, / +) -> tuple[int, Incomplete]: ... +def CreateProcess( + appName: str | None, + commandLine: str, + processAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + threadAttributes: _win32typing.PySECURITY_ATTRIBUTES | None, + bInheritHandles: int | bool, + dwCreationFlags: int, + newEnvironment: dict[str, str] | None, + currentDirectory: str | None, + startupinfo: _win32typing.PySTARTUPINFO, + /, +) -> tuple[int, int, Incomplete, Incomplete]: ... +def CreateProcessAsUser( + hToken: int, + appName: str, + commandLine: str, + processAttributes: _win32typing.PySECURITY_ATTRIBUTES, + threadAttributes: _win32typing.PySECURITY_ATTRIBUTES, + bInheritHandles, + dwCreationFlags, + newEnvironment, + currentDirectory: str, + startupinfo: _win32typing.PySTARTUPINFO, + /, +) -> tuple[int, int, Incomplete, Incomplete]: ... +def GetCurrentProcess() -> int: ... +def GetProcessVersion(processId, /): ... +def GetCurrentProcessId(): ... +def GetStartupInfo() -> _win32typing.PySTARTUPINFO: ... +def GetPriorityClass(handle: int, /): ... +def GetExitCodeThread(handle: int, /): ... +def GetExitCodeProcess(handle: int, /) -> int: ... +def GetWindowThreadProcessId(hwnd: int | None, /) -> tuple[int, int]: ... +def SetThreadPriority(handle: int, nPriority, /) -> None: ... +def GetThreadPriority(handle: int, /): ... +def GetProcessPriorityBoost(Process: int, /): ... +def SetProcessPriorityBoost(Process: int, DisablePriorityBoost, /) -> None: ... +def GetThreadPriorityBoost(Thread: int, /): ... +def SetThreadPriorityBoost(Thread: int, DisablePriorityBoost, /) -> None: ... +def GetThreadIOPendingFlag(Thread: int, /): ... +def GetThreadTimes(Thread: int, /): ... +def GetProcessId(Process: int, /): ... +def SetPriorityClass(handle: int, dwPriorityClass: int, /) -> None: ... +def AttachThreadInput(idAttach, idAttachTo, Attach, /) -> None: ... +def SetThreadIdealProcessor(handle: int, dwIdealProcessor, /): ... +def GetProcessAffinityMask(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetProcessAffinityMask(hProcess: int, mask, /) -> None: ... +def SetThreadAffinityMask(hThread: int, ThreadAffinityMask, /): ... +def SuspendThread(handle: int, /): ... +def ResumeThread(handle: int, /): ... +def TerminateProcess(handle: int, exitCode: int, /) -> None: ... +def ExitProcess(exitCode, /) -> None: ... +def EnumProcesses() -> tuple[Incomplete, Incomplete]: ... +def EnumProcessModules(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def EnumProcessModulesEx(hProcess: int, FilterFlag, /) -> tuple[Incomplete, Incomplete]: ... +def GetModuleFileNameEx(hProcess: int, hModule: int, /): ... +def GetProcessMemoryInfo(hProcess: int, /): ... +def GetProcessTimes(hProcess: int, /): ... +def GetProcessIoCounters(hProcess: int, /): ... +def GetProcessWindowStation() -> None: ... +def GetProcessWorkingSetSize(hProcess: int, /) -> tuple[Incomplete, Incomplete]: ... +def SetProcessWorkingSetSize(hProcess: int, MinimumWorkingSetSize, MaximumWorkingSetSize, /) -> None: ... +def GetProcessShutdownParameters() -> tuple[Incomplete, Incomplete]: ... +def SetProcessShutdownParameters(Level, Flags, /) -> None: ... +def GetGuiResources(Process: int, Flags, /): ... +def IsWow64Process(Process: int | None = ..., /) -> bool: ... +def ReadProcessMemory(hProcess, address: int, size: int, /) -> bytes: ... +def VirtualAllocEx(hProcess, address: int, size: int, allocationType: int, flProtect: int, /): ... +def VirtualFreeEx(hProcess, address: int, size: int, freeType: int, /): ... +def WriteProcessMemory(hProcess, address, buf, /) -> int: ... + +ABOVE_NORMAL_PRIORITY_CLASS: int +BELOW_NORMAL_PRIORITY_CLASS: int +CREATE_BREAKAWAY_FROM_JOB: int +CREATE_DEFAULT_ERROR_MODE: int +CREATE_NEW_CONSOLE: int +CREATE_NEW_PROCESS_GROUP: int +CREATE_NO_WINDOW: int +CREATE_PRESERVE_CODE_AUTHZ_LEVEL: int +CREATE_SEPARATE_WOW_VDM: int +CREATE_SHARED_WOW_VDM: int +CREATE_SUSPENDED: int +CREATE_UNICODE_ENVIRONMENT: int +DEBUG_ONLY_THIS_PROCESS: int +DEBUG_PROCESS: int +DETACHED_PROCESS: int +HIGH_PRIORITY_CLASS: int +IDLE_PRIORITY_CLASS: int +MAXIMUM_PROCESSORS: int +NORMAL_PRIORITY_CLASS: int +REALTIME_PRIORITY_CLASS: int +STARTF_FORCEOFFFEEDBACK: int +STARTF_FORCEONFEEDBACK: int +STARTF_RUNFULLSCREEN: int +STARTF_USECOUNTCHARS: int +STARTF_USEFILLATTRIBUTE: int +STARTF_USEPOSITION: int +STARTF_USESHOWWINDOW: int +STARTF_USESIZE: int +STARTF_USESTDHANDLES: int +THREAD_MODE_BACKGROUND_BEGIN: int +THREAD_MODE_BACKGROUND_END: int +THREAD_PRIORITY_ABOVE_NORMAL: int +THREAD_PRIORITY_BELOW_NORMAL: int +THREAD_PRIORITY_HIGHEST: int +THREAD_PRIORITY_IDLE: int +THREAD_PRIORITY_LOWEST: int +THREAD_PRIORITY_NORMAL: int +THREAD_PRIORITY_TIME_CRITICAL: int +LIST_MODULES_32BIT: int +LIST_MODULES_64BIT: int +LIST_MODULES_ALL: int +LIST_MODULES_DEFAULT: int +UNICODE: int diff --git a/stubs/pywin32/win32/win32profile.pyi b/stubs/pywin32/win32/win32profile.pyi new file mode 100644 index 000000000000..155a77cbdda2 --- /dev/null +++ b/stubs/pywin32/win32/win32profile.pyi @@ -0,0 +1,19 @@ +import _win32typing + +def CreateEnvironmentBlock(Token: int, Inherit): ... +def DeleteProfile(SidString: str, ProfilePath: str | None = ..., ComputerName: str | None = ...) -> None: ... +def ExpandEnvironmentStringsForUser(Token: int, Src: str) -> str: ... +def GetAllUsersProfileDirectory() -> str: ... +def GetDefaultUserProfileDirectory() -> str: ... +def GetEnvironmentStrings(): ... +def GetProfilesDirectory() -> str: ... +def GetProfileType(): ... +def GetUserProfileDirectory(Token: int) -> str: ... +def LoadUserProfile(hToken: int, ProfileInfo: _win32typing.PyPROFILEINFO) -> _win32typing.PyHKEY: ... +def UnloadUserProfile(Token: int, Profile: _win32typing.PyHKEY) -> None: ... + +PI_APPLYPOLICY: int +PI_NOUI: int +PT_MANDATORY: int +PT_ROAMING: int +PT_TEMPORARY: int diff --git a/stubs/pywin32/win32/win32ras.pyi b/stubs/pywin32/win32/win32ras.pyi new file mode 100644 index 000000000000..f27777dd2493 --- /dev/null +++ b/stubs/pywin32/win32/win32ras.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def CreatePhonebookEntry(hWnd: int, fileName: str | None = ..., /) -> None: ... +def Dial( + dialExtensions, fileName: str, RasDialParams: _win32typing.RASDIALPARAMS, callback, / +) -> tuple[Incomplete, Incomplete]: ... +def EditPhonebookEntry(hWnd: int, fileName: str, entryName: str | None = ..., /) -> None: ... +def EnumConnections(): ... +def EnumEntries(reserved: str | None = ..., fileName: str | None = ..., /) -> None: ... +def GetConnectStatus(hrasconn, /) -> tuple[Incomplete, Incomplete, str, str]: ... +def GetEntryDialParams( + fileName: str, entryName: str, / +) -> tuple[tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete], bool]: ... +def GetErrorString(error, /) -> str: ... +def HangUp(hras, /) -> None: ... +def IsHandleValid(hras: int | None, /) -> bool: ... +def SetEntryDialParams(fileName: str, RasDialParams, bSavePassword, /) -> None: ... +def RASDIALEXTENSIONS() -> _win32typing.RASDIALEXTENSIONS: ... + +RASCS_AllDevicesConnected: int +RASCS_AuthAck: int +RASCS_AuthCallback: int +RASCS_AuthChangePassword: int +RASCS_Authenticate: int +RASCS_Authenticated: int +RASCS_AuthLinkSpeed: int +RASCS_AuthNotify: int +RASCS_AuthProject: int +RASCS_AuthRetry: int +RASCS_CallbackComplete: int +RASCS_CallbackSetByCaller: int +RASCS_ConnectDevice: int +RASCS_Connected: int +RASCS_DeviceConnected: int +RASCS_Disconnected: int +RASCS_Interactive: int +RASCS_LogonNetwork: int +RASCS_OpenPort: int +RASCS_PasswordExpired: int +RASCS_PortOpened: int +RASCS_PrepareForCallback: int +RASCS_Projected: int +RASCS_ReAuthenticate: int +RASCS_RetryAuthentication: int +RASCS_StartAuthentication: int +RASCS_WaitForCallback: int +RASCS_WaitForModemReset: int + +def GetEapUserIdentity(phoneBook: str | None, entry: str, flags: int, hwnd: _win32typing.PyHANDLE | int | None = None, /): ... + +RASEAPF_Logon: int +RASEAPF_NonInteractive: int +RASEAPF_Preview: int diff --git a/stubs/pywin32/win32/win32security.pyi b/stubs/pywin32/win32/win32security.pyi new file mode 100644 index 000000000000..477a5d2f63d1 --- /dev/null +++ b/stubs/pywin32/win32/win32security.pyi @@ -0,0 +1,606 @@ +from _typeshed import Incomplete +from typing import overload +from typing_extensions import deprecated + +import _win32typing +from win32.lib.pywintypes import TimeType, error as error + +def DsGetSpn( + ServiceType, + ServiceClass: str, + ServiceName: str, + InstancePort: int = ..., + InstanceNames: tuple[str, ...] | None = ..., + InstancePorts: tuple[Incomplete, ...] | None = ..., + /, +) -> tuple[str, ...]: ... +def DsWriteAccountSpn(hDS: _win32typing.PyDS_HANDLE, Operation, Account: str, Spns: tuple[str, ...], /) -> None: ... +def DsBind(DomainController: str, DnsDomainName: str, /) -> _win32typing.PyDS_HANDLE: ... +def DsUnBind(hDS: _win32typing.PyDS_HANDLE, /) -> None: ... +def DsGetDcName( + computerName: str | None = ..., + domainName: str | None = ..., + domainGUID: _win32typing.PyIID | None = ..., + siteName: str | None = ..., + flags: int = ..., +): ... +def DsCrackNames( + hds: _win32typing.PyDS_HANDLE, flags, formatOffered, formatDesired, names: list[Incomplete], / +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def ACL(bufSize: int = ..., /) -> _win32typing.PyACL: ... +def SID() -> _win32typing.PySID: ... +def SECURITY_ATTRIBUTES() -> _win32typing.PySECURITY_ATTRIBUTES: ... +def SECURITY_DESCRIPTOR() -> _win32typing.PySECURITY_DESCRIPTOR: ... +def ImpersonateNamedPipeClient(handle, /) -> None: ... +def ImpersonateLoggedOnUser(handle: int, /) -> None: ... +def ImpersonateAnonymousToken(ThreadHandle: int, /) -> None: ... +def IsTokenRestricted(TokenHandle: int | None, /) -> bool: ... +def RevertToSelf() -> None: ... +def LogonUser(Username: str, Domain: str | None, Password: str, LogonType: int, LogonProvider: int) -> _win32typing.PyHANDLE: ... +def LogonUserEx( + Username: str, Domain: str, Password: str, LogonType, LogonProvider +) -> tuple[int, _win32typing.PySID, Incomplete, Incomplete]: ... +def LookupAccountName(systemName: str | None, accountName: str, /) -> tuple[_win32typing.PySID, str, int]: ... +def LookupAccountSid(systemName: str | None, sid: _win32typing.PySID, /) -> tuple[str, str, Incomplete]: ... +def GetBinarySid(SID: str, /) -> _win32typing.PySID: ... +def SetSecurityInfo( + handle: int, + ObjectType, + SecurityInfo, + Owner: _win32typing.PySID, + Group: _win32typing.PySID, + Dacl: _win32typing.PyACL, + Sacl: _win32typing.PyACL, + /, +) -> None: ... +def GetSecurityInfo(handle: int, ObjectType, SecurityInfo, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetNamedSecurityInfo( + ObjectName: str, + ObjectType: int, + SecurityInfo: int, + Owner: _win32typing.PySID | None, + Group: _win32typing.PySID | None, + Dacl: _win32typing.PyACL | None, + Sacl: _win32typing.PyACL | None, + /, +) -> None: ... +def GetNamedSecurityInfo(ObjectName: str, ObjectType: int, SecurityInfo: int, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def OpenProcessToken(processHandle, desiredAccess, /) -> int: ... +def LookupPrivilegeValue(systemName: str, privilegeName: str, /) -> int: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LookupPrivilegeName(SystemName: str, luid: tuple[int, int], /) -> str: ... +@overload +def LookupPrivilegeName(SystemName: str, luid: int, /) -> str: ... + +def LookupPrivilegeDisplayName(SystemName: str, Name: str, /) -> str: ... +def AdjustTokenPrivileges( + TokenHandle: int, bDisableAllPrivileges, NewState: _win32typing.PyTOKEN_PRIVILEGES +) -> _win32typing.PyTOKEN_PRIVILEGES: ... +def AdjustTokenGroups(TokenHandle: int, ResetToDefault, NewState: _win32typing.PyTOKEN_GROUPS) -> _win32typing.PyTOKEN_GROUPS: ... +def GetTokenInformation(TokenHandle: int, TokenInformationClass, /): ... +def OpenThreadToken(handle: int, desiredAccess, openAsSelf, /): ... +def SetThreadToken(Thread: int, Token: int, /) -> None: ... +def GetFileSecurity(filename: str, info: int = ..., /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetFileSecurity(filename: str, info: int, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def GetUserObjectSecurity(handle: int, info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetUserObjectSecurity(handle: int, info, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def GetKernelObjectSecurity(handle: int, info, /) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def SetKernelObjectSecurity(handle: int, info, security: _win32typing.PySECURITY_DESCRIPTOR, /) -> None: ... +def SetTokenInformation(TokenHandle: int, TokenInformationClass, TokenInformation, /) -> None: ... +def LsaOpenPolicy(system_name: str, access_mask, /) -> _win32typing.PyLSA_HANDLE: ... +def LsaClose(PolicyHandle: int, /) -> None: ... +def LsaQueryInformationPolicy(PolicyHandle: _win32typing.PyLSA_HANDLE, InformationClass, /) -> None: ... +def LsaSetInformationPolicy(PolicyHandle: _win32typing.PyLSA_HANDLE, InformationClass, Information, /) -> None: ... +def LsaAddAccountRights( + PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, UserRights: tuple[Incomplete, ...] +) -> None: ... +def LsaRemoveAccountRights( + PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, AllRights, UserRights: tuple[Incomplete, ...] +) -> None: ... +def LsaEnumerateAccountRights(PolicyHandle: _win32typing.PyLSA_HANDLE, AccountSid: _win32typing.PySID, /) -> list[str]: ... +def LsaEnumerateAccountsWithUserRight( + PolicyHandle: _win32typing.PyLSA_HANDLE, UserRight, / +) -> tuple[_win32typing.PySID, ...]: ... +def ConvertSidToStringSid(Sid: _win32typing.PySID, /) -> str: ... +def ConvertStringSidToSid(StringSid: str, /) -> _win32typing.PySID: ... +def ConvertSecurityDescriptorToStringSecurityDescriptor( + SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR, RequestedStringSDRevision, SecurityInformation, / +) -> str: ... +def ConvertStringSecurityDescriptorToSecurityDescriptor( + StringSecurityDescriptor: str, StringSDRevision, / +) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def LsaStorePrivateData(PolicyHandle: _win32typing.PyLSA_HANDLE, KeyName: str, PrivateData, /) -> None: ... +def LsaRetrievePrivateData(PolicyHandle: _win32typing.PyLSA_HANDLE, KeyName: str, /) -> str: ... +def LsaRegisterPolicyChangeNotification(InformationClass, NotificationEventHandle: int, /) -> None: ... +def LsaUnregisterPolicyChangeNotification(InformationClass, NotificationEventHandle: int, /) -> None: ... +def CryptEnumProviders() -> list[tuple[str, Incomplete]]: ... +def EnumerateSecurityPackages() -> tuple[Incomplete, ...]: ... +def AllocateLocallyUniqueId() -> None: ... +def ImpersonateSelf(ImpersonationLevel, /) -> None: ... +def DuplicateToken(ExistingTokenHandle: int, ImpersonationLevel, /) -> int: ... +def DuplicateTokenEx( + ExistingToken: int, + ImpersonationLevel, + DesiredAccess, + TokenType, + TokenAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., +) -> int: ... +def CheckTokenMembership(TokenHandle: int, SidToCheck: _win32typing.PySID, /): ... +def CreateRestrictedToken( + ExistingTokenHandle: int, + Flags, + SidsToDisable: tuple[_win32typing.PySID_AND_ATTRIBUTES, ...], + PrivilegesToDelete: tuple[_win32typing.PyLUID_AND_ATTRIBUTES, ...], + SidsToRestrict: tuple[_win32typing.PySID_AND_ATTRIBUTES, ...], +) -> int: ... +def LsaRegisterLogonProcess(LogonProcessName: str, /) -> _win32typing.PyLsaLogon_HANDLE: ... +def LsaConnectUntrusted() -> _win32typing.PyLsaLogon_HANDLE: ... +def LsaDeregisterLogonProcess(LsaHandle: _win32typing.PyLsaLogon_HANDLE, /) -> None: ... +def LsaLookupAuthenticationPackage(LsaHandle: _win32typing.PyLsaLogon_HANDLE, PackageName: str, /): ... +def LsaEnumerateLogonSessions() -> tuple[Incomplete, ...]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LsaGetLogonSessionData(LogonId: tuple[int, int], /) -> tuple[Incomplete, ...]: ... +@overload +def LsaGetLogonSessionData(LogonId: int, /) -> tuple[Incomplete, ...]: ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def AcquireCredentialsHandle( + Principal, Package, CredentialUse, LogonID: tuple[int, int], AuthData, / +) -> tuple[_win32typing.PyCredHandle, TimeType]: ... +@overload +def AcquireCredentialsHandle( + Principal, Package, CredentialUse, LogonID: int | None, AuthData, / +) -> tuple[_win32typing.PyCredHandle, TimeType]: ... + +def InitializeSecurityContext( + Credential: _win32typing.PyCredHandle, + Context: _win32typing.PyCtxtHandle, + TargetName, + ContextReq, + TargetDataRep, + pInput: _win32typing.PySecBufferDesc, + NewContext: _win32typing.PyCtxtHandle, + pOutput: _win32typing.PySecBufferDesc, + /, +) -> tuple[Incomplete, Incomplete, TimeType]: ... +def AcceptSecurityContext( + Credential: _win32typing.PyCredHandle, + Context: _win32typing.PyCtxtHandle, + pInput: _win32typing.PySecBufferDesc, + ContextReq, + TargetDataRep, + NewContext: _win32typing.PyCtxtHandle, + pOutput: _win32typing.PySecBufferDesc, + /, +) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def QuerySecurityPackageInfo(PackageName, /): ... + +@overload +@deprecated("Support for passing two ints to create a 64-bit value is deprecated; pass a single int instead") +def LsaCallAuthenticationPackage( + LsaHandle: _win32typing.PyLsaLogon_HANDLE, AuthenticationPackage, MessageType, ProtocolSubmitBuffer: tuple[int, int], / +) -> None: ... +@overload +def LsaCallAuthenticationPackage( + LsaHandle: _win32typing.PyLsaLogon_HANDLE, AuthenticationPackage, MessageType, ProtocolSubmitBuffer, / +) -> None: ... + +def TranslateName(accountName: str, accountNameFormat, accountNameFormat1, numChars=..., /) -> str: ... +def CreateWellKnownSid(WellKnownSidType, DomainSid: _win32typing.PySID | None = ..., /) -> _win32typing.PySID: ... +def MapGenericMask(AccessMask, GenericMapping: tuple[Incomplete, Incomplete, Incomplete, Incomplete], /): ... + +ACCESS_ALLOWED_ACE_TYPE: int +ACCESS_ALLOWED_OBJECT_ACE_TYPE: int +ACCESS_DENIED_ACE_TYPE: int +ACCESS_DENIED_OBJECT_ACE_TYPE: int +ACL_REVISION: int +ACL_REVISION_DS: int +AuditCategoryAccountLogon: int +AuditCategoryAccountManagement: int +AuditCategoryDetailedTracking: int +AuditCategoryDirectoryServiceAccess: int +AuditCategoryLogon: int +AuditCategoryObjectAccess: int +AuditCategoryPolicyChange: int +AuditCategoryPrivilegeUse: int +AuditCategorySystem: int +CONTAINER_INHERIT_ACE: int +DACL_SECURITY_INFORMATION: int +DENY_ACCESS: int +DISABLE_MAX_PRIVILEGE: int +DS_SPN_ADD_SPN_OP: int +DS_SPN_DELETE_SPN_OP: int +DS_SPN_DN_HOST: int +DS_SPN_DNS_HOST: int +DS_SPN_DOMAIN: int +DS_SPN_NB_DOMAIN: int +DS_SPN_NB_HOST: int +DS_SPN_REPLACE_SPN_OP: int +DS_SPN_SERVICE: int +FAILED_ACCESS_ACE_FLAG: int +GRANT_ACCESS: int +GROUP_SECURITY_INFORMATION: int +INHERIT_ONLY_ACE: int +INHERITED_ACE: int +LABEL_SECURITY_INFORMATION: int +LOGON32_LOGON_BATCH: int +LOGON32_LOGON_INTERACTIVE: int +LOGON32_LOGON_NETWORK: int +LOGON32_LOGON_NETWORK_CLEARTEXT: int +LOGON32_LOGON_NEW_CREDENTIALS: int +LOGON32_LOGON_SERVICE: int +LOGON32_LOGON_UNLOCK: int +LOGON32_PROVIDER_DEFAULT: int +LOGON32_PROVIDER_WINNT35: int +LOGON32_PROVIDER_WINNT40: int +LOGON32_PROVIDER_WINNT50: int +NO_INHERITANCE: int +NO_PROPAGATE_INHERIT_ACE: int +NOT_USED_ACCESS: int +OBJECT_INHERIT_ACE: int +OWNER_SECURITY_INFORMATION: int +POLICY_ALL_ACCESS: int +POLICY_AUDIT_EVENT_FAILURE: int +POLICY_AUDIT_EVENT_NONE: int +POLICY_AUDIT_EVENT_SUCCESS: int +POLICY_AUDIT_EVENT_UNCHANGED: int +POLICY_AUDIT_LOG_ADMIN: int +POLICY_CREATE_ACCOUNT: int +POLICY_CREATE_PRIVILEGE: int +POLICY_CREATE_SECRET: int +POLICY_EXECUTE: int +POLICY_GET_PRIVATE_INFORMATION: int +POLICY_LOOKUP_NAMES: int +POLICY_NOTIFICATION: int +POLICY_READ: int +POLICY_SERVER_ADMIN: int +POLICY_SET_AUDIT_REQUIREMENTS: int +POLICY_SET_DEFAULT_QUOTA_LIMITS: int +POLICY_TRUST_ADMIN: int +POLICY_VIEW_AUDIT_INFORMATION: int +POLICY_VIEW_LOCAL_INFORMATION: int +POLICY_WRITE: int +PolicyAccountDomainInformation: int +PolicyAuditEventsInformation: int +PolicyAuditFullQueryInformation: int +PolicyAuditFullSetInformation: int +PolicyAuditLogInformation: int +PolicyDefaultQuotaInformation: int +PolicyDnsDomainInformation: int +PolicyLsaServerRoleInformation: int +PolicyModificationInformation: int +PolicyNotifyAccountDomainInformation: int +PolicyNotifyAuditEventsInformation: int +PolicyNotifyDnsDomainInformation: int +PolicyNotifyDomainEfsInformation: int +PolicyNotifyDomainKerberosTicketInformation: int +PolicyNotifyMachineAccountPasswordInformation: int +PolicyNotifyServerRoleInformation: int +PolicyPdAccountInformation: int +PolicyPrimaryDomainInformation: int +PolicyReplicaSourceInformation: int +PolicyServerDisabled: int +PolicyServerEnabled: int +PolicyServerRoleBackup: int +PolicyServerRolePrimary: int +PROTECTED_DACL_SECURITY_INFORMATION: int +PROTECTED_SACL_SECURITY_INFORMATION: int +REVOKE_ACCESS: int +SACL_SECURITY_INFORMATION: int +SANDBOX_INERT: int +SDDL_REVISION_1: int +SE_DACL_AUTO_INHERITED: int +SE_DACL_DEFAULTED: int +SE_DACL_PRESENT: int +SE_DACL_PROTECTED: int +SE_DS_OBJECT: int +SE_DS_OBJECT_ALL: int +SE_FILE_OBJECT: int +SE_GROUP_DEFAULTED: int +SE_GROUP_ENABLED: int +SE_GROUP_ENABLED_BY_DEFAULT: int +SE_GROUP_LOGON_ID: int +SE_GROUP_MANDATORY: int +SE_GROUP_OWNER: int +SE_GROUP_RESOURCE: int +SE_GROUP_USE_FOR_DENY_ONLY: int +SE_KERNEL_OBJECT: int +SE_LMSHARE: int +SE_OWNER_DEFAULTED: int +SE_PRINTER: int +SE_PRIVILEGE_ENABLED: int +SE_PRIVILEGE_ENABLED_BY_DEFAULT: int +SE_PRIVILEGE_REMOVED: int +SE_PRIVILEGE_USED_FOR_ACCESS: int +SE_PROVIDER_DEFINED_OBJECT: int +SE_REGISTRY_KEY: int +SE_REGISTRY_WOW64_32KEY: int +SE_SACL_AUTO_INHERITED: int +SE_SACL_DEFAULTED: int +SE_SACL_PRESENT: int +SE_SACL_PROTECTED: int +SE_SELF_RELATIVE: int +SE_SERVICE: int +SE_UNKNOWN_OBJECT_TYPE: int +SE_WINDOW_OBJECT: int +SE_WMIGUID_OBJECT: int +SECPKG_CRED_BOTH: int +SECPKG_CRED_INBOUND: int +SECPKG_CRED_OUTBOUND: int +SECPKG_FLAG_ACCEPT_WIN32_NAME: int +SECPKG_FLAG_CLIENT_ONLY: int +SECPKG_FLAG_CONNECTION: int +SECPKG_FLAG_DATAGRAM: int +SECPKG_FLAG_EXTENDED_ERROR: int +SECPKG_FLAG_IMPERSONATION: int +SECPKG_FLAG_INTEGRITY: int +SECPKG_FLAG_MULTI_REQUIRED: int +SECPKG_FLAG_PRIVACY: int +SECPKG_FLAG_STREAM: int +SECPKG_FLAG_TOKEN_ONLY: int +SECURITY_CREATOR_SID_AUTHORITY: int +SECURITY_LOCAL_SID_AUTHORITY: int +SECURITY_NON_UNIQUE_AUTHORITY: int +SECURITY_NT_AUTHORITY: int +SECURITY_NULL_SID_AUTHORITY: int +SECURITY_RESOURCE_MANAGER_AUTHORITY: int +SECURITY_WORLD_SID_AUTHORITY: int +SecurityAnonymous: int +SecurityDelegation: int +SecurityIdentification: int +SecurityImpersonation: int +SET_ACCESS: int +SET_AUDIT_FAILURE: int +SET_AUDIT_SUCCESS: int +SidTypeAlias: int +SidTypeComputer: int +SidTypeDeletedAccount: int +SidTypeDomain: int +SidTypeGroup: int +SidTypeInvalid: int +SidTypeUnknown: int +SidTypeUser: int +SidTypeWellKnownGroup: int +STYPE_DEVICE: int +STYPE_DISKTREE: int +STYPE_IPC: int +STYPE_PRINTQ: int +STYPE_SPECIAL: int +STYPE_TEMPORARY: int +SUB_CONTAINERS_AND_OBJECTS_INHERIT: int +SUB_CONTAINERS_ONLY_INHERIT: int +SUB_OBJECTS_ONLY_INHERIT: int +SUCCESSFUL_ACCESS_ACE_FLAG: int +SYSTEM_AUDIT_ACE_TYPE: int +SYSTEM_AUDIT_OBJECT_ACE_TYPE: int +TOKEN_ADJUST_DEFAULT: int +TOKEN_ADJUST_GROUPS: int +TOKEN_ADJUST_PRIVILEGES: int +TOKEN_ALL_ACCESS: int +TOKEN_ASSIGN_PRIMARY: int +TOKEN_DUPLICATE: int +TOKEN_EXECUTE: int +TOKEN_IMPERSONATE: int +TOKEN_QUERY: int +TOKEN_QUERY_SOURCE: int +TOKEN_READ: int +TOKEN_WRITE: int +TokenImpersonation: int +TokenPrimary: int +TrustedControllersInformation: int +TrustedDomainAuthInformation: int +TrustedDomainAuthInformationInternal: int +TrustedDomainFullInformation: int +TrustedDomainFullInformation2Internal: int +TrustedDomainFullInformationInternal: int +TrustedDomainInformationBasic: int +TrustedDomainInformationEx: int +TrustedDomainInformationEx2Internal: int +TrustedDomainNameInformation: int +TrustedPasswordInformation: int +TrustedPosixOffsetInformation: int +TRUSTEE_BAD_FORM: int +TRUSTEE_IS_ALIAS: int +TRUSTEE_IS_COMPUTER: int +TRUSTEE_IS_DELETED: int +TRUSTEE_IS_DOMAIN: int +TRUSTEE_IS_GROUP: int +TRUSTEE_IS_INVALID: int +TRUSTEE_IS_NAME: int +TRUSTEE_IS_OBJECTS_AND_NAME: int +TRUSTEE_IS_OBJECTS_AND_SID: int +TRUSTEE_IS_SID: int +TRUSTEE_IS_UNKNOWN: int +TRUSTEE_IS_USER: int +TRUSTEE_IS_WELL_KNOWN_GROUP: int +UNPROTECTED_DACL_SECURITY_INFORMATION: int +UNPROTECTED_SACL_SECURITY_INFORMATION: int +CredHandleType = _win32typing.PyCredHandle +CtxtHandleType = _win32typing.PyCtxtHandle + +def DsListDomainsInSite(hds, site: str, /): ... +def DsListInfoForServer(hds, server: str, /): ... +def DsListRoles(hds, /): ... +def DsListServersForDomainInSite(hds, domain: str, site: str, /): ... +def DsListServersInSite(hds, site: str, /): ... +def DsListSites(hds, /): ... + +GetPolicyHandle = LsaOpenPolicy + +MICROSOFT_KERBEROS_NAME_A: bytes +MSV1_0_PACKAGE_NAME: bytes +PyCredHandleType = _win32typing.PyCredHandle +PyCtxtHandleType = _win32typing.PyCtxtHandle +PySecBufferDescType = _win32typing.PySecBufferDesc +PySecBufferType = _win32typing.PySecBuffer +SE_ASSIGNPRIMARYTOKEN_NAME: str +SE_AUDIT_NAME: str +SE_BACKUP_NAME: str +SE_BATCH_LOGON_NAME: str +SE_CHANGE_NOTIFY_NAME: str +SE_CREATE_GLOBAL_NAME: str +SE_CREATE_PAGEFILE_NAME: str +SE_CREATE_PERMANENT_NAME: str +SE_CREATE_SYMBOLIC_LINK_NAME: str +SE_CREATE_TOKEN_NAME: str +SE_DEBUG_NAME: str +SE_DENY_BATCH_LOGON_NAME: str +SE_DENY_INTERACTIVE_LOGON_NAME: str +SE_DENY_NETWORK_LOGON_NAME: str +SE_DENY_REMOTE_INTERACTIVE_LOGON_NAME: str +SE_DENY_SERVICE_LOGON_NAME: str +SE_ENABLE_DELEGATION_NAME: str +SE_GROUP_INTEGRITY: int +SE_GROUP_INTEGRITY_ENABLED: int +SE_IMPERSONATE_NAME: str +SE_INCREASE_QUOTA_NAME: str +SE_INC_BASE_PRIORITY_NAME: str +SE_INC_WORKING_SET_NAME: str +SE_INTERACTIVE_LOGON_NAME: str +SE_LOAD_DRIVER_NAME: str +SE_LOCK_MEMORY_NAME: str +SE_MACHINE_ACCOUNT_NAME: str +SE_MANAGE_VOLUME_NAME: str +SE_NETWORK_LOGON_NAME: str +SE_PROF_SINGLE_PROCESS_NAME: str +SE_RELABEL_NAME: str +SE_REMOTE_INTERACTIVE_LOGON_NAME: str +SE_REMOTE_SHUTDOWN_NAME: str +SE_RESTORE_NAME: str +SE_SECURITY_NAME: str +SE_SERVICE_LOGON_NAME: str +SE_SHUTDOWN_NAME: str +SE_SYNC_AGENT_NAME: str +SE_SYSTEMTIME_NAME: str +SE_SYSTEM_ENVIRONMENT_NAME: str +SE_SYSTEM_PROFILE_NAME: str +SE_TAKE_OWNERSHIP_NAME: str +SE_TCB_NAME: str +SE_TIME_ZONE_NAME: str +SE_TRUSTED_CREDMAN_ACCESS_NAME: str +SE_UNDOCK_NAME: str +SE_UNSOLICITED_INPUT_NAME: str +SYSTEM_MANDATORY_LABEL_NO_EXECUTE_UP: int +SYSTEM_MANDATORY_LABEL_NO_READ_UP: int +SYSTEM_MANDATORY_LABEL_NO_WRITE_UP: int +SYSTEM_MANDATORY_LABEL_VALID_MASK: int +SecBufferDescType = _win32typing.PySecBufferDesc +SecBufferType = _win32typing.PySecBuffer +TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN: int +TOKEN_MANDATORY_POLICY_NO_WRITE_UP: int +TOKEN_MANDATORY_POLICY_OFF: int +TOKEN_MANDATORY_POLICY_VALID_MASK: int +TokenAccessInformation: int +TokenAuditPolicy: int +TokenDefaultDacl: int +TokenElevation: int +TokenElevationType: int +TokenElevationTypeDefault: int +TokenElevationTypeFull: int +TokenElevationTypeLimited: int +TokenGroups: int +TokenGroupsAndPrivileges: int +TokenHasRestrictions: int +TokenImpersonationLevel: int +TokenIntegrityLevel: int +TokenLinkedToken: int +TokenLogonSid: int +TokenMandatoryPolicy: int +TokenOrigin: int +TokenOwner: int +TokenPrimaryGroup: int +TokenPrivileges: int +TokenRestrictedSids: int +TokenSandBoxInert: int +TokenSessionId: int +TokenSessionReference: int +TokenSource: int +TokenStatistics: int +TokenType: int +TokenUIAccess: int +TokenUser: int +TokenVirtualizationAllowed: int +TokenVirtualizationEnabled: int +UNICODE: int +WinAccountAdministratorSid: int +WinAccountCertAdminsSid: int +WinAccountComputersSid: int +WinAccountControllersSid: int +WinAccountDomainAdminsSid: int +WinAccountDomainGuestsSid: int +WinAccountDomainUsersSid: int +WinAccountEnterpriseAdminsSid: int +WinAccountGuestSid: int +WinAccountKrbtgtSid: int +WinAccountPolicyAdminsSid: int +WinAccountRasAndIasServersSid: int +WinAccountReadonlyControllersSid: int +WinAccountSchemaAdminsSid: int +WinAnonymousSid: int +WinAuthenticatedUserSid: int +WinBatchSid: int +WinBuiltinAccountOperatorsSid: int +WinBuiltinAdministratorsSid: int +WinBuiltinAuthorizationAccessSid: int +WinBuiltinBackupOperatorsSid: int +WinBuiltinCryptoOperatorsSid: int +WinBuiltinDCOMUsersSid: int +WinBuiltinDomainSid: int +WinBuiltinEventLogReadersGroup: int +WinBuiltinGuestsSid: int +WinBuiltinIUsersSid: int +WinBuiltinIncomingForestTrustBuildersSid: int +WinBuiltinNetworkConfigurationOperatorsSid: int +WinBuiltinPerfLoggingUsersSid: int +WinBuiltinPerfMonitoringUsersSid: int +WinBuiltinPowerUsersSid: int +WinBuiltinPreWindows2000CompatibleAccessSid: int +WinBuiltinPrintOperatorsSid: int +WinBuiltinRemoteDesktopUsersSid: int +WinBuiltinReplicatorSid: int +WinBuiltinSystemOperatorsSid: int +WinBuiltinTerminalServerLicenseServersSid: int +WinBuiltinUsersSid: int +WinCacheablePrincipalsGroupSid: int +WinCreatorGroupServerSid: int +WinCreatorGroupSid: int +WinCreatorOwnerRightsSid: int +WinCreatorOwnerServerSid: int +WinCreatorOwnerSid: int +WinDialupSid: int +WinDigestAuthenticationSid: int +WinEnterpriseControllersSid: int +WinEnterpriseReadonlyControllersSid: int +WinHighLabelSid: int +WinIUserSid: int +WinInteractiveSid: int +WinLocalServiceSid: int +WinLocalSid: int +WinLocalSystemSid: int +WinLogonIdsSid: int +WinLowLabelSid: int +WinMediumLabelSid: int +WinNTLMAuthenticationSid: int +WinNetworkServiceSid: int +WinNetworkSid: int +WinNonCacheablePrincipalsGroupSid: int +WinNtAuthoritySid: int +WinNullSid: int +WinOtherOrganizationSid: int +WinProxySid: int +WinRemoteLogonIdSid: int +WinRestrictedCodeSid: int +WinSChannelAuthenticationSid: int +WinSelfSid: int +WinServiceSid: int +WinSystemLabelSid: int +WinTerminalServerSid: int +WinThisOrganizationSid: int +WinUntrustedLabelSid: int +WinWorldSid: int +WinWriteRestrictedCodeSid: int diff --git a/stubs/pywin32/win32/win32service.pyi b/stubs/pywin32/win32/win32service.pyi new file mode 100644 index 000000000000..30797ebefee5 --- /dev/null +++ b/stubs/pywin32/win32/win32service.pyi @@ -0,0 +1,187 @@ +from _typeshed import Incomplete +from collections.abc import Iterable + +import _win32typing +from win32.lib.pywintypes import error as error + +def GetThreadDesktop(ThreadId: int, /) -> _win32typing.PyHDESK: ... +def EnumWindowStations() -> tuple[tuple[str, Incomplete], ...]: ... +def GetUserObjectInformation(Handle: int, _type, /) -> None: ... +def SetUserObjectInformation(Handle: int, info, _type, /) -> None: ... +def OpenWindowStation(szWinSta, Inherit, DesiredAccess, /) -> _win32typing.PyHWINSTA: ... +def OpenDesktop(szDesktop, Flags, Inherit, DesiredAccess, /) -> _win32typing.PyHDESK: ... +def CreateDesktop( + Desktop, Flags, DesiredAccess, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, / +) -> _win32typing.PyHDESK: ... +def OpenInputDesktop(Flags, Inherit, DesiredAccess, /) -> _win32typing.PyHDESK: ... +def GetProcessWindowStation() -> _win32typing.PyHWINSTA: ... +def CreateWindowStation( + WindowStation, Flags, DesiredAccess, SecurityAttributes: _win32typing.PySECURITY_ATTRIBUTES, / +) -> _win32typing.PyHWINSTA: ... +def EnumServicesStatus( + hSCManager: _win32typing.PySC_HANDLE | int, ServiceType: int = ..., ServiceState: int = ..., / +) -> tuple[Incomplete, ...]: ... +def EnumServicesStatusEx( + SCManager: _win32typing.PySC_HANDLE, ServiceType, ServiceState, InfoLevel, GroupName: Incomplete | None = ..., / +) -> tuple[Incomplete, ...]: ... +def EnumDependentServices(hService: _win32typing.PySC_HANDLE, ServiceState, /) -> tuple[Incomplete, ...]: ... +def QueryServiceConfig(hService: _win32typing.PySC_HANDLE, /): ... +def StartService(hService: _win32typing.PySC_HANDLE, args: Iterable[str] | None, /) -> None: ... +def OpenService(scHandle: _win32typing.PySC_HANDLE, name: str, desiredAccess, /) -> _win32typing.PySC_HANDLE: ... +def OpenSCManager(machineName: str | None, dbName: str | None, desiredAccess: int, /) -> _win32typing.PySC_HANDLE: ... +def CloseServiceHandle(scHandle: _win32typing.PySC_HANDLE, /) -> None: ... +def QueryServiceStatus(hService: _win32typing.PySC_HANDLE, /) -> _win32typing.SERVICE_STATUS: ... +def QueryServiceStatusEx(hService: _win32typing.PySC_HANDLE, /) -> _win32typing.SERVICE_STATUS: ... +def SetServiceObjectSecurity( + Handle: _win32typing.PySC_HANDLE, SecurityInformation, SecurityDescriptor: _win32typing.PySECURITY_DESCRIPTOR, / +) -> None: ... +def QueryServiceObjectSecurity( + Handle: _win32typing.PySC_HANDLE, SecurityInformation, / +) -> _win32typing.PySECURITY_DESCRIPTOR: ... +def GetServiceKeyName(hSCManager: _win32typing.PySC_HANDLE, DisplayName, /): ... +def GetServiceDisplayName(hSCManager: _win32typing.PySC_HANDLE, ServiceName, /): ... +def SetServiceStatus( + scHandle, serviceStatus: _win32typing.SERVICE_STATUS | tuple[int, int, int, int, int, int, int], / +) -> None: ... +def ControlService(scHandle: _win32typing.PySC_HANDLE, code, /) -> _win32typing.SERVICE_STATUS: ... +def DeleteService(scHandle: _win32typing.PySC_HANDLE, /) -> None: ... +def CreateService( + scHandle: _win32typing.PySC_HANDLE, + name: str, + displayName: str, + desiredAccess: int, + serviceType: int, + startType: int, + errorControl: int, + binaryFile: str, + loadOrderGroup: str | None, + bFetchTag: bool, + serviceDeps: Iterable[Incomplete] | None, + acctName: str | None, + password: str | None, + /, +) -> _win32typing.PySC_HANDLE: ... +def ChangeServiceConfig( + hService: _win32typing.PySC_HANDLE, + serviceType: int, + startType: int, + errorControl: int, + binaryFile: str | None, + loadOrderGroup: str | None, + bFetchTag: bool, + serviceDeps: Iterable[Incomplete] | None, + acctName: str | None, + password: str | None, + displayName: str | None, + /, +): ... +def LockServiceDatabase(sc_handle: _win32typing.PySC_HANDLE, /): ... +def UnlockServiceDatabase(lock, /): ... +def QueryServiceLockStatus(hSCManager: _win32typing.PySC_HANDLE, /) -> tuple[Incomplete, str, Incomplete]: ... +def ChangeServiceConfig2(hService: _win32typing.PySC_HANDLE, InfoLevel, info, /) -> None: ... +def QueryServiceConfig2(hService: _win32typing.PySC_HANDLE, InfoLevel, /): ... + +DBT_CONFIGCHANGECANCELED: int +DBT_CONFIGCHANGED: int +DBT_CUSTOMEVENT: int +DBT_DEVICEARRIVAL: int +DBT_DEVICEQUERYREMOVE: int +DBT_DEVICEQUERYREMOVEFAILED: int +DBT_DEVICEREMOVECOMPLETE: int +DBT_DEVICEREMOVEPENDING: int +DBT_DEVICETYPESPECIFIC: int +DBT_QUERYCHANGECONFIG: int +DF_ALLOWOTHERACCOUNTHOOK: int +SC_ACTION_NONE: int +SC_ACTION_REBOOT: int +SC_ACTION_RESTART: int +SC_ACTION_RUN_COMMAND: int +SC_ENUM_PROCESS_INFO: int +SC_GROUP_IDENTIFIER: int +SC_MANAGER_ALL_ACCESS: int +SC_MANAGER_CONNECT: int +SC_MANAGER_CREATE_SERVICE: int +SC_MANAGER_ENUMERATE_SERVICE: int +SC_MANAGER_LOCK: int +SC_MANAGER_MODIFY_BOOT_CONFIG: int +SC_MANAGER_QUERY_LOCK_STATUS: int +SERVICE_ACCEPT_HARDWAREPROFILECHANGE: int +SERVICE_ACCEPT_NETBINDCHANGE: int +SERVICE_ACCEPT_PARAMCHANGE: int +SERVICE_ACCEPT_PAUSE_CONTINUE: int +SERVICE_ACCEPT_POWEREVENT: int +SERVICE_ACCEPT_PRESHUTDOWN: int +SERVICE_ACCEPT_SESSIONCHANGE: int +SERVICE_ACCEPT_SHUTDOWN: int +SERVICE_ACCEPT_STOP: int +SERVICE_ACTIVE: int +SERVICE_ALL_ACCESS: int +SERVICE_AUTO_START: int +SERVICE_BOOT_START: int +SERVICE_CHANGE_CONFIG: int +SERVICE_CONFIG_DELAYED_AUTO_START_INFO: int +SERVICE_CONFIG_DESCRIPTION: int +SERVICE_CONFIG_FAILURE_ACTIONS: int +SERVICE_CONFIG_FAILURE_ACTIONS_FLAG: int +SERVICE_CONFIG_PRESHUTDOWN_INFO: int +SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO: int +SERVICE_CONFIG_SERVICE_SID_INFO: int +SERVICE_CONTINUE_PENDING: int +SERVICE_CONTROL_CONTINUE: int +SERVICE_CONTROL_DEVICEEVENT: int +SERVICE_CONTROL_HARDWAREPROFILECHANGE: int +SERVICE_CONTROL_INTERROGATE: int +SERVICE_CONTROL_NETBINDADD: int +SERVICE_CONTROL_NETBINDDISABLE: int +SERVICE_CONTROL_NETBINDENABLE: int +SERVICE_CONTROL_NETBINDREMOVE: int +SERVICE_CONTROL_PARAMCHANGE: int +SERVICE_CONTROL_PAUSE: int +SERVICE_CONTROL_POWEREVENT: int +SERVICE_CONTROL_PRESHUTDOWN: int +SERVICE_CONTROL_SESSIONCHANGE: int +SERVICE_CONTROL_SHUTDOWN: int +SERVICE_CONTROL_STOP: int +SERVICE_DEMAND_START: int +SERVICE_DISABLED: int +SERVICE_DRIVER: int +SERVICE_ENUMERATE_DEPENDENTS: int +SERVICE_ERROR_CRITICAL: int +SERVICE_ERROR_IGNORE: int +SERVICE_ERROR_NORMAL: int +SERVICE_ERROR_SEVERE: int +SERVICE_FILE_SYSTEM_DRIVER: int +SERVICE_INACTIVE: int +SERVICE_INTERACTIVE_PROCESS: int +SERVICE_INTERROGATE: int +SERVICE_KERNEL_DRIVER: int +SERVICE_NO_CHANGE: int +SERVICE_PAUSE_CONTINUE: int +SERVICE_PAUSE_PENDING: int +SERVICE_PAUSED: int +SERVICE_QUERY_CONFIG: int +SERVICE_QUERY_STATUS: int +SERVICE_RUNNING: int +SERVICE_SID_TYPE_NONE: int +SERVICE_SID_TYPE_RESTRICTED: int +SERVICE_SID_TYPE_UNRESTRICTED: int +SERVICE_SPECIFIC_ERROR: int +SERVICE_START: int +SERVICE_START_PENDING: int +SERVICE_STATE_ALL: int +SERVICE_STOP: int +SERVICE_STOP_PENDING: int +SERVICE_STOPPED: int +SERVICE_SYSTEM_START: int +SERVICE_USER_DEFINED_CONTROL: int +SERVICE_WIN32: int +SERVICE_WIN32_OWN_PROCESS: int +SERVICE_WIN32_SHARE_PROCESS: int +UOI_FLAGS: int +UOI_NAME: int +UOI_TYPE: int +UOI_USER_SID: int +WSF_VISIBLE: int +HDESKType = _win32typing.PyHDESK +HWINSTAType = _win32typing.PyHWINSTA +UNICODE: int diff --git a/stubs/pywin32/win32/win32trace.pyi b/stubs/pywin32/win32/win32trace.pyi new file mode 100644 index 000000000000..0ab7e8c3b837 --- /dev/null +++ b/stubs/pywin32/win32/win32trace.pyi @@ -0,0 +1,13 @@ +from win32.lib.pywintypes import error as error + +def GetHandle() -> int: ... +def GetTracer(): ... +def InitRead() -> None: ... +def InitWrite() -> None: ... +def TermRead() -> None: ... +def TermWrite() -> None: ... +def blockingread(milliSeconds: int = ..., /) -> str: ... +def flush() -> None: ... +def read() -> str: ... +def setprint() -> None: ... +def write(data: str, /) -> None: ... diff --git a/stubs/pywin32/win32/win32transaction.pyi b/stubs/pywin32/win32/win32transaction.pyi new file mode 100644 index 000000000000..26d5077d5a55 --- /dev/null +++ b/stubs/pywin32/win32/win32transaction.pyi @@ -0,0 +1,18 @@ +import _win32typing +from win32.lib.pywintypes import error as error + +def CreateTransaction( + TransactionAttributes: _win32typing.PySECURITY_ATTRIBUTES | None = ..., + UOW: _win32typing.PyIID | None = ..., + CreateOptions: int = ..., + IsolationLevel: int = ..., + IsolationFlags: int = ..., + Timeout: int = ..., + Description: str | None = ..., +) -> int: ... +def RollbackTransaction(TransactionHandle: int) -> None: ... +def RollbackTransactionAsync(TransactionHandle: int) -> None: ... +def CommitTransaction(TransactionHandle: int) -> None: ... +def CommitTransactionAsync(TransactionHandle: int) -> None: ... +def GetTransactionId(TransactionHandle: int) -> _win32typing.PyIID: ... +def OpenTransaction(DesiredAccess, TransactionId: _win32typing.PyIID) -> int: ... diff --git a/stubs/pywin32/win32/win32ts.pyi b/stubs/pywin32/win32/win32ts.pyi new file mode 100644 index 000000000000..f9c2b5db1488 --- /dev/null +++ b/stubs/pywin32/win32/win32ts.pyi @@ -0,0 +1,97 @@ +from _typeshed import Incomplete + +def WTSOpenServer(ServerName: str) -> int: ... +def WTSCloseServer(Server: int) -> None: ... +def WTSQueryUserConfig(ServerName: str, UserName: str, WTSConfigClass): ... +def WTSSetUserConfig(ServerName: str, UserName: str, WTSConfigClass, Buffer) -> None: ... +def WTSEnumerateServers(DomainName: str | None = ..., Version: int = ..., Reserved=...) -> tuple[str, ...]: ... +def WTSEnumerateSessions(Server: int = ..., Version: int = ..., Reserved=...) -> tuple[dict[str, str | int], ...]: ... +def WTSLogoffSession(Server: int, SessionId: int, Wait: bool) -> None: ... +def WTSDisconnectSession(Server: int, SessionId: int, Wait: bool) -> None: ... +def WTSQuerySessionInformation(Server: int, SessionId: int, WTSInfoClass: int) -> str: ... +def WTSEnumerateProcesses(Server: int = ..., Version: int = ..., Reserved: int = ...) -> tuple[str, ...]: ... +def WTSQueryUserToken(SessionId) -> int: ... +def WTSShutdownSystem(Server: int, ShutdownFlag) -> None: ... +def WTSTerminateProcess(Server: int, ProcessId, ExitCode) -> None: ... +def ProcessIdToSessionId(ProcessId): ... +def WTSGetActiveConsoleSessionId(): ... +def WTSRegisterSessionNotification(Wnd: int, Flags) -> None: ... +def WTSUnRegisterSessionNotification(Wnd: int) -> None: ... +def WTSWaitSystemEvent(Server: int = ..., EventMask=...): ... +def WTSSendMessage(Server: int, SessionId, Title: str, Message: str, Style, Timeout, Wait): ... + +NOTIFY_FOR_ALL_SESSIONS: int +NOTIFY_FOR_THIS_SESSION: int +WTSActive: int +WTSApplicationName: int +WTSClientAddress: int +WTSClientBuildNumber: int +WTSClientDirectory: int +WTSClientDisplay: int +WTSClientHardwareId: int +WTSClientName: int +WTSClientProductId: int +WTSClientProtocolType: int +WTSIsRemoteSession: int +WTSConnectQuery: int +WTSConnectState: int +WTSConnected: int +WTSDisconnected: int +WTSDomainName: int +WTSDown: int +WTSIdle: int +WTSInit: int +WTSInitialProgram: int +WTSListen: int +WTSOEMId: int +WTSReset: int +WTSSessionId: int +WTSShadow: int +WTSUserConfigBrokenTimeoutSettings: int +WTSUserConfigInitialProgram: int +WTSUserConfigModemCallbackPhoneNumber: int +WTSUserConfigModemCallbackSettings: int +WTSUserConfigReconnectSettings: int +WTSUserConfigShadowingSettings: int +WTSUserConfigTerminalServerHomeDir: int +WTSUserConfigTerminalServerHomeDirDrive: int +WTSUserConfigTerminalServerProfilePath: int +WTSUserConfigTimeoutSettingsConnections: int +WTSUserConfigTimeoutSettingsDisconnections: int +WTSUserConfigTimeoutSettingsIdle: int +WTSUserConfigWorkingDirectory: int +WTSUserConfigfAllowLogonTerminalServer: int +WTSUserConfigfDeviceClientDefaultPrinter: int +WTSUserConfigfDeviceClientDrives: int +WTSUserConfigfDeviceClientPrinters: int +WTSUserConfigfInheritInitialProgram: int +WTSUserConfigfTerminalServerRemoteHomeDir: int +WTSUserName: int +WTSVirtualClientData: int +WTSVirtualFileHandle: int +WTSWinStationName: int +WTSWorkingDirectory: int +WTS_CURRENT_SERVER: int +WTS_CURRENT_SERVER_HANDLE: int +WTS_CURRENT_SERVER_NAME: Incomplete +WTS_CURRENT_SESSION: int +WTS_EVENT_ALL: int +WTS_EVENT_CONNECT: int +WTS_EVENT_CREATE: int +WTS_EVENT_DELETE: int +WTS_EVENT_DISCONNECT: int +WTS_EVENT_FLUSH: int +WTS_EVENT_LICENSE: int +WTS_EVENT_LOGOFF: int +WTS_EVENT_LOGON: int +WTS_EVENT_NONE: int +WTS_EVENT_RENAME: int +WTS_EVENT_STATECHANGE: int +WTS_PROTOCOL_TYPE_CONSOLE: int +WTS_PROTOCOL_TYPE_ICA: int +WTS_PROTOCOL_TYPE_RDP: int +WTS_WSD_FASTREBOOT: int +WTS_WSD_LOGOFF: int +WTS_WSD_POWEROFF: int +WTS_WSD_REBOOT: int +WTS_WSD_SHUTDOWN: int diff --git a/stubs/pywin32/win32/win32wnet.pyi b/stubs/pywin32/win32/win32wnet.pyi new file mode 100644 index 000000000000..6fd4e9b0e432 --- /dev/null +++ b/stubs/pywin32/win32/win32wnet.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +import _win32typing +from win32.lib.pywintypes import error as error + +def NCBBuffer(size, /): ... +def Netbios(ncb: _win32typing.NCB, /): ... +def WNetAddConnection2( + NetResource: _win32typing.PyNETRESOURCE, + Password: Incomplete | None = ..., + UserName: Incomplete | None = ..., + Flags: int = ..., +) -> None: ... +def WNetAddConnection3( + HwndOwner: int | _win32typing.PyHANDLE, + NetResource: _win32typing.PyNETRESOURCE, + Password: Incomplete | None = ..., + UserName: Incomplete | None = ..., + Flags: int = ..., +) -> None: ... +def WNetCancelConnection2(name: str, flags, force, /) -> None: ... +def WNetOpenEnum(scope, _type, usage, resource: _win32typing.PyNETRESOURCE, /) -> _win32typing.PyHANDLE: ... +def WNetCloseEnum(handle: _win32typing.PyHANDLE, /) -> None: ... +def WNetEnumResource(handle: _win32typing.PyHANDLE, maxExtries: int = ..., /) -> list[_win32typing.PyNETRESOURCE]: ... +def WNetGetUser(connection: str | None = ..., /) -> str: ... +def WNetGetUniversalName(localPath: str, infoLevel, /) -> str: ... +def WNetGetResourceInformation(NetResource: _win32typing.PyNETRESOURCE, /) -> tuple[_win32typing.PyNETRESOURCE, Incomplete]: ... +def WNetGetLastError() -> tuple[Incomplete, Incomplete, Incomplete]: ... +def WNetGetResourceParent(NetResource: _win32typing.PyNETRESOURCE, /) -> _win32typing.PyNETRESOURCE: ... +def WNetGetConnection(connection: str | None = ..., /) -> str: ... + +NETRESOURCE = _win32typing.PyNETRESOURCE +NCB = _win32typing.PyNCB +# old "deprecated" names, before types could create instances. +NETRESOURCEType = _win32typing.PyNETRESOURCE +NCBType = _win32typing.PyNCB diff --git a/stubs/pywin32/win32/winxpgui.pyi b/stubs/pywin32/win32/winxpgui.pyi new file mode 100644 index 000000000000..156611576b85 --- /dev/null +++ b/stubs/pywin32/win32/winxpgui.pyi @@ -0,0 +1,5 @@ +# The `winxpgui` module is obsolete and has been completely replaced +# by `win32gui` and `win32console.GetConsoleWindow`. Use those instead. + +from win32console import GetConsoleWindow as GetConsoleWindow +from win32gui import * diff --git a/stubs/pywin32/win32api.pyi b/stubs/pywin32/win32api.pyi new file mode 100644 index 000000000000..8beb8a8a1219 --- /dev/null +++ b/stubs/pywin32/win32api.pyi @@ -0,0 +1 @@ +from win32.win32api import * diff --git a/stubs/pywin32/win32clipboard.pyi b/stubs/pywin32/win32clipboard.pyi new file mode 100644 index 000000000000..77dbe6673232 --- /dev/null +++ b/stubs/pywin32/win32clipboard.pyi @@ -0,0 +1 @@ +from win32.win32clipboard import * diff --git a/stubs/pywin32/win32com/__init__.pyi b/stubs/pywin32/win32com/__init__.pyi new file mode 100644 index 000000000000..64402b719834 --- /dev/null +++ b/stubs/pywin32/win32com/__init__.pyi @@ -0,0 +1,9 @@ +from collections.abc import MutableSequence + +from . import gen_py as gen_py + +__gen_path__: str +__build_path__: str | None + +def SetupEnvironment() -> None: ... +def __PackageSupportBuildPath__(package_path: MutableSequence[str]) -> None: ... diff --git a/stubs/pywin32/win32com/adsi/__init__.pyi b/stubs/pywin32/win32com/adsi/__init__.pyi new file mode 100644 index 000000000000..548c6c6170dd --- /dev/null +++ b/stubs/pywin32/win32com/adsi/__init__.pyi @@ -0,0 +1 @@ +from win32comext.adsi import * diff --git a/stubs/pywin32/win32com/adsi/adsi.pyi b/stubs/pywin32/win32com/adsi/adsi.pyi new file mode 100644 index 000000000000..a6269d428cfa --- /dev/null +++ b/stubs/pywin32/win32com/adsi/adsi.pyi @@ -0,0 +1 @@ +from win32comext.adsi.adsi import * diff --git a/stubs/pywin32/win32com/adsi/adsicon.pyi b/stubs/pywin32/win32com/adsi/adsicon.pyi new file mode 100644 index 000000000000..1776450e43b8 --- /dev/null +++ b/stubs/pywin32/win32com/adsi/adsicon.pyi @@ -0,0 +1 @@ +from win32comext.adsi.adsicon import * diff --git a/stubs/pywin32/win32com/authorization/__init__.pyi b/stubs/pywin32/win32com/authorization/__init__.pyi new file mode 100644 index 000000000000..975c5a823b08 --- /dev/null +++ b/stubs/pywin32/win32com/authorization/__init__.pyi @@ -0,0 +1 @@ +from win32comext.authorization import * diff --git a/stubs/pywin32/win32com/authorization/authorization.pyi b/stubs/pywin32/win32com/authorization/authorization.pyi new file mode 100644 index 000000000000..0ad104f7ebbc --- /dev/null +++ b/stubs/pywin32/win32com/authorization/authorization.pyi @@ -0,0 +1 @@ +from win32comext.authorization.authorization import * diff --git a/stubs/pywin32/win32com/axcontrol/__init__.pyi b/stubs/pywin32/win32com/axcontrol/__init__.pyi new file mode 100644 index 000000000000..fde8be560785 --- /dev/null +++ b/stubs/pywin32/win32com/axcontrol/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axcontrol import * diff --git a/stubs/pywin32/win32com/axcontrol/axcontrol.pyi b/stubs/pywin32/win32com/axcontrol/axcontrol.pyi new file mode 100644 index 000000000000..d3c73448de56 --- /dev/null +++ b/stubs/pywin32/win32com/axcontrol/axcontrol.pyi @@ -0,0 +1 @@ +from win32comext.axcontrol.axcontrol import * diff --git a/stubs/pywin32/win32com/axdebug/__init__.pyi b/stubs/pywin32/win32com/axdebug/__init__.pyi new file mode 100644 index 000000000000..97d083e95e4c --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axdebug import * diff --git a/stubs/pywin32/win32com/axdebug/adb.pyi b/stubs/pywin32/win32com/axdebug/adb.pyi new file mode 100644 index 000000000000..48966a1195b0 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/adb.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.adb import * diff --git a/stubs/pywin32/win32com/axdebug/axdebug.pyi b/stubs/pywin32/win32com/axdebug/axdebug.pyi new file mode 100644 index 000000000000..45b111326729 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/axdebug.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.axdebug import * diff --git a/stubs/pywin32/win32com/axdebug/codecontainer.pyi b/stubs/pywin32/win32com/axdebug/codecontainer.pyi new file mode 100644 index 000000000000..60d3a50fb97e --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/codecontainer.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.codecontainer import * diff --git a/stubs/pywin32/win32com/axdebug/contexts.pyi b/stubs/pywin32/win32com/axdebug/contexts.pyi new file mode 100644 index 000000000000..c1c9fbfd99d3 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/contexts.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.contexts import * diff --git a/stubs/pywin32/win32com/axdebug/debugger.pyi b/stubs/pywin32/win32com/axdebug/debugger.pyi new file mode 100644 index 000000000000..83a0e9c9498f --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/debugger.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.debugger import * diff --git a/stubs/pywin32/win32com/axdebug/documents.pyi b/stubs/pywin32/win32com/axdebug/documents.pyi new file mode 100644 index 000000000000..e0d1bb7431c6 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/documents.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.documents import * diff --git a/stubs/pywin32/win32com/axdebug/expressions.pyi b/stubs/pywin32/win32com/axdebug/expressions.pyi new file mode 100644 index 000000000000..3816f76473c1 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/expressions.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.expressions import * diff --git a/stubs/pywin32/win32com/axdebug/gateways.pyi b/stubs/pywin32/win32com/axdebug/gateways.pyi new file mode 100644 index 000000000000..517204a57a89 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/gateways.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.gateways import * diff --git a/stubs/pywin32/win32com/axdebug/stackframe.pyi b/stubs/pywin32/win32com/axdebug/stackframe.pyi new file mode 100644 index 000000000000..3184248da855 --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/stackframe.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.stackframe import * diff --git a/stubs/pywin32/win32com/axdebug/util.pyi b/stubs/pywin32/win32com/axdebug/util.pyi new file mode 100644 index 000000000000..1ea282e4c35a --- /dev/null +++ b/stubs/pywin32/win32com/axdebug/util.pyi @@ -0,0 +1 @@ +from win32comext.axdebug.util import * diff --git a/stubs/pywin32/win32com/axscript/__init__.pyi b/stubs/pywin32/win32com/axscript/__init__.pyi new file mode 100644 index 000000000000..afc72ec7e6a9 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript import * diff --git a/stubs/pywin32/win32com/axscript/asputil.pyi b/stubs/pywin32/win32com/axscript/asputil.pyi new file mode 100644 index 000000000000..1e04c857f72b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/asputil.pyi @@ -0,0 +1 @@ +from win32comext.axscript.asputil import * diff --git a/stubs/pywin32/win32com/axscript/axscript.pyi b/stubs/pywin32/win32com/axscript/axscript.pyi new file mode 100644 index 000000000000..7ec0b348419d --- /dev/null +++ b/stubs/pywin32/win32com/axscript/axscript.pyi @@ -0,0 +1 @@ +from win32comext.axscript.axscript import * diff --git a/stubs/pywin32/win32com/axscript/client/__init__.pyi b/stubs/pywin32/win32com/axscript/client/__init__.pyi new file mode 100644 index 000000000000..203d0ab35080 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client import * diff --git a/stubs/pywin32/win32com/axscript/client/debug.pyi b/stubs/pywin32/win32com/axscript/client/debug.pyi new file mode 100644 index 000000000000..a39e0e145b4b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/debug.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.debug import * diff --git a/stubs/pywin32/win32com/axscript/client/error.pyi b/stubs/pywin32/win32com/axscript/client/error.pyi new file mode 100644 index 000000000000..f1a3310b6e6b --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/error.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.error import * diff --git a/stubs/pywin32/win32com/axscript/client/framework.pyi b/stubs/pywin32/win32com/axscript/client/framework.pyi new file mode 100644 index 000000000000..cec9c9a8aaf8 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/client/framework.pyi @@ -0,0 +1 @@ +from win32comext.axscript.client.framework import * diff --git a/stubs/pywin32/win32com/axscript/server/__init__.pyi b/stubs/pywin32/win32com/axscript/server/__init__.pyi new file mode 100644 index 000000000000..6cb0b07bc54c --- /dev/null +++ b/stubs/pywin32/win32com/axscript/server/__init__.pyi @@ -0,0 +1 @@ +from win32comext.axscript.server import * diff --git a/stubs/pywin32/win32com/axscript/server/axsite.pyi b/stubs/pywin32/win32com/axscript/server/axsite.pyi new file mode 100644 index 000000000000..e07103462ce5 --- /dev/null +++ b/stubs/pywin32/win32com/axscript/server/axsite.pyi @@ -0,0 +1 @@ +from win32comext.axscript.server.axsite import * diff --git a/stubs/pywin32/win32com/bits/__init__.pyi b/stubs/pywin32/win32com/bits/__init__.pyi new file mode 100644 index 000000000000..020ede08f21a --- /dev/null +++ b/stubs/pywin32/win32com/bits/__init__.pyi @@ -0,0 +1 @@ +from win32comext.bits import * diff --git a/stubs/pywin32/win32com/bits/bits.pyi b/stubs/pywin32/win32com/bits/bits.pyi new file mode 100644 index 000000000000..fcea1eb79ed5 --- /dev/null +++ b/stubs/pywin32/win32com/bits/bits.pyi @@ -0,0 +1 @@ +from win32comext.bits.bits import * diff --git a/stubs/pywin32/win32com/client/__init__.pyi b/stubs/pywin32/win32com/client/__init__.pyi new file mode 100644 index 000000000000..930c9586f3ab --- /dev/null +++ b/stubs/pywin32/win32com/client/__init__.pyi @@ -0,0 +1,75 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Iterator +from typing import Final, TypeAlias + +import _win32typing +from pythoncom import com_record +from win32.lib.pywintypes import IIDType +from win32com.client import dynamic + +_Stringifiable: TypeAlias = object + +def GetObject(Pathname: str | None = None, Class=None, clsctx=None) -> CDispatch: ... +def GetActiveObject(Class: str, clsctx=...): ... +def Moniker(Pathname: str, clsctx=...): ... +def Dispatch( + dispatch: str | dynamic.PyIDispatchType | IIDType | dynamic.PyIUnknownType, + userName: str | None = None, + resultCLSID: _Stringifiable | None = None, + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> dynamic.CDispatch: ... +def DispatchEx(clsid, machine=None, userName=None, resultCLSID=None, typeinfo=None, clsctx=None): ... + +class CDispatch(dynamic.CDispatch): + def __dir__(self) -> list[str]: ... + +def CastTo(ob, target, typelib=None): ... + +class Constants: + __dicts__: list[Incomplete] + def __getattr__(self, a: str): ... + +constants: Final[Constants] + +class EventsProxy: + def __init__(self, ob) -> None: ... + def __del__(self) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, val) -> None: ... + +def DispatchWithEvents(clsid, user_event_class) -> EventsProxy: ... +def WithEvents(disp, user_event_class): ... +def getevents(clsid): ... +def Record(name, object) -> com_record: ... +def register_record_class(cls) -> None: ... + +class DispatchBaseClass: + def __init__(self, oobj=None) -> None: ... + def __dir__(self) -> list[str]: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + +class CoClassBaseClass: + def __init__(self, oobj=None) -> None: ... + def __getattr__(self, attr: str): ... + def __setattr__(self, attr: str, value) -> None: ... + def __call__(self, *args, **kwargs): ... + def __str__(self, *args: Unused) -> str: ... # noqa: Y029 + def __int__(self, *args: Unused) -> int: ... + def __iter__(self) -> Iterator[Incomplete]: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + +class VARIANT: + varianttype: Incomplete + def __init__(self, vt, value) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, newval) -> None: ... + @value.deleter + def value(self) -> None: ... diff --git a/stubs/pywin32/win32com/client/build.pyi b/stubs/pywin32/win32com/client/build.pyi new file mode 100644 index 000000000000..5eba28add3f4 --- /dev/null +++ b/stubs/pywin32/win32com/client/build.pyi @@ -0,0 +1,70 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, Literal + +class NotSupportedException(Exception): ... + +DropIndirection: Final = "DropIndirection" +NoTranslateTypes: Final[list[int]] +NoTranslateMap: Final[set[int]] + +class MapEntry: + dispid: Incomplete + desc: Incomplete | None + names: Incomplete + doc: Incomplete + resultCLSID: Incomplete + resultDocumentation: Incomplete | None + wasProperty: Incomplete + hidden: bool | Literal[0, 1] + def __init__( + self, desc_or_id, names=None, doc=None, resultCLSID=..., resultDoc=None, hidden: bool | Literal[0, 1] = 0 + ) -> None: ... + def GetResultCLSID(self) -> Incomplete | None: ... + def GetResultCLSIDStr(self) -> str: ... + def GetResultName(self) -> Incomplete | None: ... + +class OleItem: + typename: ClassVar[str] + doc: Incomplete + python_name: Incomplete | None + bWritten: bool | Literal[0, 1] + bIsDispatch: bool | Literal[0, 1] + bIsSink: bool | Literal[0, 1] + clsid: Incomplete | None + co_class: Incomplete | None + def __init__(self, doc=None) -> None: ... + +class DispatchItem(OleItem): + typename: ClassVar[str] + propMap: dict[Incomplete, Incomplete] + propMapGet: dict[Incomplete, Incomplete] + propMapPut: dict[Incomplete, Incomplete] + mapFuncs: dict[Incomplete, Incomplete] + defaultDispatchName: Incomplete | None + hidden: bool | Literal[0, 1] + def __init__(self, typeinfo=None, attr=None, doc=None, bForUser: bool | Literal[0, 1] = 1) -> None: ... + clsid: Incomplete + bIsDispatch: bool | Literal[0, 1] + def Build(self, typeinfo, attr, bForUser: bool | Literal[0, 1] = 1) -> None: ... + def CountInOutOptArgs(self, argTuple: Iterable[Incomplete]) -> tuple[int, int, int]: ... + def MakeFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + def MakeDispatchFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + def MakeVarArgsFuncMethod(self, entry, name: str, bMakeClass: bool | Literal[0, 1] = 1) -> list[str]: ... + +class VTableItem(DispatchItem): + vtableFuncs: list[tuple[Incomplete, Incomplete, Incomplete]] + def Build(self, typeinfo, attr, bForUser: bool | Literal[0, 1] = 1) -> None: ... + +class LazyDispatchItem(DispatchItem): + typename: ClassVar[str] + clsid: Incomplete + def __init__(self, attr, doc) -> None: ... + +typeSubstMap: Final[dict[int, int]] +valid_identifier_chars: Final[str] + +def demunge_leading_underscores(className: str) -> str: ... +def MakePublicAttributeName(className: str, is_global: bool = False) -> str: ... +def MakeDefaultArgRepr(defArgVal) -> str | None: ... +def BuildCallList(fdesc, names, defNamedOptArg, defNamedNotOptArg, defUnnamedArg, defOutArg, is_comment: bool = False) -> str: ... diff --git a/stubs/pywin32/win32com/client/dynamic.pyi b/stubs/pywin32/win32com/client/dynamic.pyi new file mode 100644 index 000000000000..100ca291d7cc --- /dev/null +++ b/stubs/pywin32/win32com/client/dynamic.pyi @@ -0,0 +1,69 @@ +from _typeshed import Incomplete +from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only + +import _win32typing +from win32.lib.pywintypes import IIDType +from win32com.client import build + +_T_co = TypeVar("_T_co", covariant=True) +_T = TypeVar("_T") + +@type_check_only +class _DispatchCreateClass(Protocol[_T_co]): + @staticmethod + def __call__( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + olerepr: build.DispatchItem | build.LazyDispatchItem, + userName: str | None = None, + lazydata=None, + ) -> _T_co: ... + +debugging: int +debugging_attr: int +LCID: Final = 0x0 +ERRORS_BAD_CONTEXT: Final[list[int]] +ALL_INVOKE_TYPES: Final[list[int]] + +def debug_print(*args: object) -> None: ... +def debug_attr_print(*args: object) -> None: ... + +PyIDispatchType = _win32typing.PyIDispatch +PyIUnknownType = _win32typing.PyIUnknown + +@overload +def Dispatch( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + userName: str | None, + createClass: _DispatchCreateClass[_T], + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> _T: ... +@overload +def Dispatch( + IDispatch: str | PyIDispatchType | IIDType | PyIUnknownType, + userName: str | None = None, + createClass: None = None, + typeinfo: _win32typing.PyITypeInfo | None = None, + clsctx: int = ..., +) -> CDispatch: ... + +def MakeOleRepr(IDispatch, typeinfo, typecomp) -> build.DispatchItem | build.LazyDispatchItem: ... +def DumbDispatch(IDispatch, userName=None, createClass=None, clsctx=...): ... + +class CDispatch: + def __init__(self, IDispatch, olerepr, userName=None, lazydata=None) -> None: ... + def __call__(self, *args): ... + def __bool__(self) -> bool: ... + def __dir__(self) -> list[str]: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __int__(self) -> int: ... + def __len__(self) -> int: ... + def __getitem__(self, index): ... + def __setitem__(self, index, *args) -> None: ... + def __LazyMap__(self, attr) -> Literal[0, 1] | None: ... + def __AttrToID__(self, attr): ... + ob: Incomplete + # CDispatch objects are dynamically generated and too complex to type + def __getattr__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, value: Any) -> None: ... diff --git a/stubs/pywin32/win32com/client/gencache.pyi b/stubs/pywin32/win32com/client/gencache.pyi new file mode 100644 index 000000000000..9f72ce3009aa --- /dev/null +++ b/stubs/pywin32/win32com/client/gencache.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Generator +from contextlib import contextmanager +from types import ModuleType +from typing import Literal +from typing_extensions import Never + +from win32.lib.pywintypes import IIDType +from win32com.client import dynamic + +bForDemandDefault: int +clsidToTypelib: dict[str, tuple[str, int, int, int]] +versionRedirectMap: dict[tuple[str, int, int, int], ModuleType | None] +is_readonly: bool +is_zip: bool +demandGeneratedTypeLibraries: dict[tuple[str, int, int, int], Incomplete] + +def __init__() -> None: ... + +pickleVersion: int + +@contextmanager +def ModuleMutex(module_name: str) -> Generator[None]: ... +def GetGeneratedFileName(clsid, lcid, major, minor) -> str: ... +def SplitGeneratedFileName(fname: str) -> tuple[str, ...]: ... +def GetGeneratePath() -> str: ... +def GetClassForProgID(progid: str) -> type | None: ... +def GetClassForCLSID(clsid) -> type | None: ... +def GetModuleForProgID(progid: str) -> ModuleType | None: ... +def GetModuleForCLSID(clsid) -> ModuleType | None: ... +def GetModuleForTypelib(typelibCLSID, lcid, major, minor) -> ModuleType: ... +def MakeModuleForTypelib( + typelibCLSID, + lcid, + major, + minor, + progressInstance=None, + bForDemand: bool | Literal[0, 1] = ..., + bBuildHidden: bool | Literal[0, 1] = 1, +) -> ModuleType: ... +def MakeModuleForTypelibInterface( + typelib_ob, progressInstance=None, bForDemand: bool | Literal[0, 1] = ..., bBuildHidden: bool | Literal[0, 1] = 1 +) -> ModuleType | None: ... +def EnsureModuleForTypelibInterface( + typelib_ob, progressInstance=None, bForDemand: bool | Literal[0, 1] = ..., bBuildHidden: bool | Literal[0, 1] = 1 +) -> ModuleType | None: ... +def ForgetAboutTypelibInterface(typelib_ob) -> None: ... +def EnsureModule( + typelibCLSID, + lcid, + major, + minor, + progressInstance=None, + bValidateFile: bool | Literal[0, 1] = ..., + bForDemand: bool | Literal[0, 1] = ..., + bBuildHidden: bool | Literal[0, 1] = 1, +) -> ModuleType | None: ... +def EnsureDispatch( + prog_id: str | dynamic.PyIDispatchType | IIDType | dynamic.PyIUnknownType, bForDemand: bool | Literal[0, 1] = 1 +) -> dynamic.CDispatch: ... +def AddModuleToCache(typelibclsid, lcid, major, minor, verbose: Unused = 1, bFlushNow: bool | Literal[0, 1] = ...) -> None: ... +def GetGeneratedInfos() -> list[tuple[Incomplete, Incomplete, Incomplete, Incomplete]]: ... +def Rebuild(verbose: bool | Literal[0, 1] = 1) -> None: ... +def usage() -> Never: ... diff --git a/stubs/pywin32/win32com/directsound/__init__.pyi b/stubs/pywin32/win32com/directsound/__init__.pyi new file mode 100644 index 000000000000..6ac36b68e0eb --- /dev/null +++ b/stubs/pywin32/win32com/directsound/__init__.pyi @@ -0,0 +1 @@ +from win32comext.directsound import * diff --git a/stubs/pywin32/win32com/directsound/directsound.pyi b/stubs/pywin32/win32com/directsound/directsound.pyi new file mode 100644 index 000000000000..ec66ab405b9a --- /dev/null +++ b/stubs/pywin32/win32com/directsound/directsound.pyi @@ -0,0 +1 @@ +from win32comext.directsound.directsound import * diff --git a/stubs/pywin32/win32com/gen_py/__init__.pyi b/stubs/pywin32/win32com/gen_py/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32com/ifilter/__init__.pyi b/stubs/pywin32/win32com/ifilter/__init__.pyi new file mode 100644 index 000000000000..258d3a36f592 --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/__init__.pyi @@ -0,0 +1 @@ +from win32comext.ifilter import * diff --git a/stubs/pywin32/win32com/ifilter/ifilter.pyi b/stubs/pywin32/win32com/ifilter/ifilter.pyi new file mode 100644 index 000000000000..01872b20c9a2 --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/ifilter.pyi @@ -0,0 +1 @@ +from win32comext.ifilter.ifilter import * diff --git a/stubs/pywin32/win32com/ifilter/ifiltercon.pyi b/stubs/pywin32/win32com/ifilter/ifiltercon.pyi new file mode 100644 index 000000000000..8f2260e73c0b --- /dev/null +++ b/stubs/pywin32/win32com/ifilter/ifiltercon.pyi @@ -0,0 +1 @@ +from win32comext.ifilter.ifiltercon import * diff --git a/stubs/pywin32/win32com/internet/__init__.pyi b/stubs/pywin32/win32com/internet/__init__.pyi new file mode 100644 index 000000000000..8fb46e57e584 --- /dev/null +++ b/stubs/pywin32/win32com/internet/__init__.pyi @@ -0,0 +1 @@ +from win32comext.internet import * diff --git a/stubs/pywin32/win32com/internet/inetcon.pyi b/stubs/pywin32/win32com/internet/inetcon.pyi new file mode 100644 index 000000000000..58e4a6236df5 --- /dev/null +++ b/stubs/pywin32/win32com/internet/inetcon.pyi @@ -0,0 +1 @@ +from win32comext.internet.inetcon import * diff --git a/stubs/pywin32/win32com/internet/internet.pyi b/stubs/pywin32/win32com/internet/internet.pyi new file mode 100644 index 000000000000..e08fbee40e46 --- /dev/null +++ b/stubs/pywin32/win32com/internet/internet.pyi @@ -0,0 +1 @@ +from win32comext.internet.internet import * diff --git a/stubs/pywin32/win32com/mapi/__init__.pyi b/stubs/pywin32/win32com/mapi/__init__.pyi new file mode 100644 index 000000000000..cc183a9712fe --- /dev/null +++ b/stubs/pywin32/win32com/mapi/__init__.pyi @@ -0,0 +1 @@ +from win32comext.mapi import * diff --git a/stubs/pywin32/win32com/mapi/emsabtags.pyi b/stubs/pywin32/win32com/mapi/emsabtags.pyi new file mode 100644 index 000000000000..d38198bb2755 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/emsabtags.pyi @@ -0,0 +1 @@ +from win32comext.mapi.emsabtags import * diff --git a/stubs/pywin32/win32com/mapi/exchange.pyi b/stubs/pywin32/win32com/mapi/exchange.pyi new file mode 100644 index 000000000000..1d4b98a437f4 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/exchange.pyi @@ -0,0 +1 @@ +from win32comext.mapi.exchange import * diff --git a/stubs/pywin32/win32com/mapi/mapi.pyi b/stubs/pywin32/win32com/mapi/mapi.pyi new file mode 100644 index 000000000000..e7bacd919a3b --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapi.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapi import * diff --git a/stubs/pywin32/win32com/mapi/mapitags.pyi b/stubs/pywin32/win32com/mapi/mapitags.pyi new file mode 100644 index 000000000000..f4ff53e2efed --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapitags.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapitags import * diff --git a/stubs/pywin32/win32com/mapi/mapiutil.pyi b/stubs/pywin32/win32com/mapi/mapiutil.pyi new file mode 100644 index 000000000000..cd19df1c9eb2 --- /dev/null +++ b/stubs/pywin32/win32com/mapi/mapiutil.pyi @@ -0,0 +1 @@ +from win32comext.mapi.mapiutil import * diff --git a/stubs/pywin32/win32com/olectl.pyi b/stubs/pywin32/win32com/olectl.pyi new file mode 100644 index 000000000000..bfd6283a5497 --- /dev/null +++ b/stubs/pywin32/win32com/olectl.pyi @@ -0,0 +1,56 @@ +from typing import Final + +FACILITY_CONTROL: Final = 0xA + +def MAKE_SCODE(sev: int, fac: int, code: int) -> int: ... +def STD_CTL_SCODE(n: int) -> int: ... + +CTL_E_ILLEGALFUNCTIONCALL: Final = -2146828283 +CTL_E_OVERFLOW: Final = -2146828282 +CTL_E_OUTOFMEMORY: Final = -2146828281 +CTL_E_DIVISIONBYZERO: Final = -2146828277 +CTL_E_OUTOFSTRINGSPACE: Final = -2146828274 +CTL_E_OUTOFSTACKSPACE: Final = -2146828260 +CTL_E_BADFILENAMEORNUMBER: Final = -2146828236 +CTL_E_FILENOTFOUND: Final = -2146828235 +CTL_E_BADFILEMODE: Final = -2146828234 +CTL_E_FILEALREADYOPEN: Final = -2146828233 +CTL_E_DEVICEIOERROR: Final = -2146828231 +CTL_E_FILEALREADYEXISTS: Final = -2146828230 +CTL_E_BADRECORDLENGTH: Final = -2146828229 +CTL_E_DISKFULL: Final = -2146828227 +CTL_E_BADRECORDNUMBER: Final = -2146828225 +CTL_E_BADFILENAME: Final = -2146828224 +CTL_E_TOOMANYFILES: Final = -2146828221 +CTL_E_DEVICEUNAVAILABLE: Final = -2146828220 +CTL_E_PERMISSIONDENIED: Final = -2146828218 +CTL_E_DISKNOTREADY: Final = -2146828217 +CTL_E_PATHFILEACCESSERROR: Final = -2146828213 +CTL_E_PATHNOTFOUND: Final = -2146828212 +CTL_E_INVALIDPATTERNSTRING: Final = -2146828195 +CTL_E_INVALIDUSEOFNULL: Final = -2146828194 +CTL_E_INVALIDFILEFORMAT: Final = -2146827967 +CTL_E_INVALIDPROPERTYVALUE: Final = -2146827908 +CTL_E_INVALIDPROPERTYARRAYINDEX: Final = -2146827907 +CTL_E_SETNOTSUPPORTEDATRUNTIME: Final = -2146827906 +CTL_E_SETNOTSUPPORTED: Final = -2146827905 +CTL_E_NEEDPROPERTYARRAYINDEX: Final = -2146827903 +CTL_E_SETNOTPERMITTED: Final = -2146827901 +CTL_E_GETNOTSUPPORTEDATRUNTIME: Final = -2146827895 +CTL_E_GETNOTSUPPORTED: Final = -2146827894 +CTL_E_PROPERTYNOTFOUND: Final = -2146827866 +CTL_E_INVALIDCLIPBOARDFORMAT: Final = -2146827828 +CTL_E_INVALIDPICTURE: Final = -2146827807 +CTL_E_PRINTERERROR: Final = -2146827806 +CTL_E_CANTSAVEFILETOTEMP: Final = -2146827553 +CTL_E_SEARCHTEXTNOTFOUND: Final = -2146827544 +CTL_E_REPLACEMENTSTOOLONG: Final = -2146827542 +CONNECT_E_FIRST: Final = -2147220992 +CONNECT_E_LAST: Final = -2147220977 +CONNECT_S_FIRST: Final = 262656 +CONNECT_S_LAST: Final = 262671 +CONNECT_E_NOCONNECTION: Final = -2147220992 +CONNECT_E_ADVISELIMIT: Final = -2147220991 +CONNECT_E_CANNOTCONNECT: Final = -2147220990 +CONNECT_E_OVERRIDDEN: Final = -2147220989 +CLASS_E_NOTLICENSED: Final = -2147221230 diff --git a/stubs/pywin32/win32com/propsys/__init__.pyi b/stubs/pywin32/win32com/propsys/__init__.pyi new file mode 100644 index 000000000000..34b721052b14 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/__init__.pyi @@ -0,0 +1 @@ +from win32comext.propsys import * diff --git a/stubs/pywin32/win32com/propsys/propsys.pyi b/stubs/pywin32/win32com/propsys/propsys.pyi new file mode 100644 index 000000000000..c5afd3cba640 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/propsys.pyi @@ -0,0 +1 @@ +from win32comext.propsys.propsys import * diff --git a/stubs/pywin32/win32com/propsys/pscon.pyi b/stubs/pywin32/win32com/propsys/pscon.pyi new file mode 100644 index 000000000000..0f35b47343f3 --- /dev/null +++ b/stubs/pywin32/win32com/propsys/pscon.pyi @@ -0,0 +1 @@ +from win32comext.propsys.pscon import * diff --git a/stubs/pywin32/win32com/server/__init__.pyi b/stubs/pywin32/win32com/server/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32com/server/connect.pyi b/stubs/pywin32/win32com/server/connect.pyi new file mode 100644 index 000000000000..d4f5e9994d9f --- /dev/null +++ b/stubs/pywin32/win32com/server/connect.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from typing import Final + +IConnectionPointContainer_methods: Final = ["EnumConnectionPoints", "FindConnectionPoint"] +IConnectionPoint_methods: Final = [ + "EnumConnections", + "Unadvise", + "Advise", + "GetConnectionPointContainer", + "GetConnectionInterface", +] + +class ConnectableServer: + cookieNo: int + connections: dict[int, Incomplete] + def EnumConnections(self) -> None: ... + def GetConnectionInterface(self) -> None: ... + def GetConnectionPointContainer(self): ... + def Advise(self, pUnk) -> int: ... + def Unadvise(self, cookie: int) -> None: ... + def EnumConnectionPoints(self) -> None: ... + def FindConnectionPoint(self, iid) -> Incomplete | None: ... diff --git a/stubs/pywin32/win32com/server/dispatcher.pyi b/stubs/pywin32/win32com/server/dispatcher.pyi new file mode 100644 index 000000000000..6c4c9dd74ace --- /dev/null +++ b/stubs/pywin32/win32com/server/dispatcher.pyi @@ -0,0 +1,18 @@ +from logging import Logger +from typing import TypeAlias + +from win32com.server.policy import BasicWrapPolicy + +class DispatcherBase: + policy: BasicWrapPolicy + logger: Logger + def __init__(self, policyClass, object) -> None: ... + +class DispatcherTrace(DispatcherBase): ... + +class DispatcherWin32trace(DispatcherTrace): + def __init__(self, policyClass, object) -> None: ... + +class DispatcherOutputDebugString(DispatcherTrace): ... + +DefaultDebugDispatcher: TypeAlias = DispatcherTrace diff --git a/stubs/pywin32/win32com/server/exception.pyi b/stubs/pywin32/win32com/server/exception.pyi new file mode 100644 index 000000000000..44427b52a099 --- /dev/null +++ b/stubs/pywin32/win32com/server/exception.pyi @@ -0,0 +1,21 @@ +import pythoncom + +class COMException(pythoncom.com_error): + scode: int + description: str + source: str | None + helpfile: str | None + helpcontext: int | None + def __init__( + self, + description: str | None = None, + scode: int | None = None, + source: str | None = None, + helpfile: str | None = None, + helpContext: int | None = None, + desc: str | None = None, + hresult: int | None = None, + ) -> None: ... + +def IsCOMException(t: type[BaseException] | None = None) -> bool: ... +def IsCOMServerException(t: type[BaseException] | None = None) -> bool: ... diff --git a/stubs/pywin32/win32com/server/factory.pyi b/stubs/pywin32/win32com/server/factory.pyi new file mode 100644 index 000000000000..3de546181158 --- /dev/null +++ b/stubs/pywin32/win32com/server/factory.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused +from collections.abc import Iterable + +from _win32typing import PyIClassFactory, PyIID + +def RegisterClassFactories( + clsids: Iterable[PyIID], flags: int | None = None, clsctx: int | None = None +) -> list[tuple[PyIClassFactory, int]]: ... +def RevokeClassFactories(infos: Iterable[tuple[Unused, int]]) -> None: ... diff --git a/stubs/pywin32/win32com/server/localserver.pyi b/stubs/pywin32/win32com/server/localserver.pyi new file mode 100644 index 000000000000..dd0f6c43efb0 --- /dev/null +++ b/stubs/pywin32/win32com/server/localserver.pyi @@ -0,0 +1,9 @@ +from collections.abc import Iterable +from typing import Final + +from _win32typing import PyIID + +usage: Final[str] + +def serve(clsids: Iterable[PyIID]) -> None: ... +def main() -> None: ... diff --git a/stubs/pywin32/win32com/server/policy.pyi b/stubs/pywin32/win32com/server/policy.pyi new file mode 100644 index 000000000000..a14cfe8d8c03 --- /dev/null +++ b/stubs/pywin32/win32com/server/policy.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete +from abc import ABC, abstractmethod +from typing import Any, Final + +import _win32typing + +__author__: Final[str] +S_OK: Final = 0 +IDispatchType: Incomplete +IUnknownType: Incomplete +regSpec: str +regPolicy: str +regDispatcher: str +regAddnPath: str + +def CreateInstance(clsid, reqIID: _win32typing.PyIID) -> _win32typing.PyIUnknown: ... + +class BasicWrapPolicy(ABC): + def __init__(self, object) -> None: ... + def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + @abstractmethod + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +class MappedWrapPolicy(BasicWrapPolicy): + _dispid_to_func_: dict[int, str] + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +class DesignatedWrapPolicy(MappedWrapPolicy): ... +class EventHandlerPolicy(DesignatedWrapPolicy): ... + +class DynamicPolicy(BasicWrapPolicy): + def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider) -> tuple[Incomplete]: ... + +DefaultPolicy = DesignatedWrapPolicy + +# Imports an arbitrary object by it's fully-qualified name. +def resolve_func(spec: str) -> Any: ... + +# Imports and calls an arbitrary callable by it's fully-qualified name. +def call_func(spec: str, *args: Any) -> Any: ... + +DISPATCH_METHOD: int +DISPATCH_PROPERTYGET: int +DISPATCH_PROPERTYPUT: int +DISPATCH_PROPERTYPUTREF: int +DISPID_EVALUATE: int +DISPID_NEWENUM: int +DISPID_PROPERTYPUT: int +DISPID_STARTENUM: int +DISPID_VALUE: int diff --git a/stubs/pywin32/win32com/server/register.pyi b/stubs/pywin32/win32com/server/register.pyi new file mode 100644 index 000000000000..78fb2c6899fe --- /dev/null +++ b/stubs/pywin32/win32com/server/register.pyi @@ -0,0 +1,68 @@ +from collections.abc import Callable, Iterable, Mapping +from typing import Final, Literal, Protocol, TypedDict, TypeVar, type_check_only +from typing_extensions import Unpack + +from _win32typing import PyHKEY, PyIID + +_T = TypeVar("_T", PyHKEY, int) + +@type_check_only +class _RegisterClass(Protocol): + _reg_clsid_: PyIID + +@type_check_only +class _RegisterFlag(TypedDict, total=False): + quiet: bool + debug: bool + finalize_register: Callable[[], None] + +@type_check_only +class _UnregisterFlag(TypedDict, total=False): + quiet: bool + finalize_unregister: Callable[[], None] + +@type_check_only +class _ElevatedFlag(TypedDict, total=False): + quiet: bool + unattended: bool + hwnd: int + +@type_check_only +class _CommandFlag(_RegisterFlag, _UnregisterFlag, _ElevatedFlag): # type: ignore[misc] + ... + +CATID_PythonCOMServer: Final = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}" + +def recurse_delete_key(path: str | None, base: PyHKEY | int = -2147483648) -> None: ... +def RegisterServer( + clsid: PyIID, + pythonInstString: str | None = None, + desc: str | None = None, + progID: str | None = None, + verProgID: str | None = None, + defIcon: str | None = None, + threadingModel: Literal["apartment", "both", "free", "neutral"] = "both", + policy: str | None = None, + catids: list[PyIID] = [], + other: Mapping[str, str] = {}, + addPyComCat: bool | None = None, + dispatcher: str | None = None, + clsctx: int | None = None, + addnPath: str | None = None, +) -> None: ... +def GetUnregisterServerKeys( + clsid: PyIID, progID: str | None = None, verProgID: str | None = None, customKeys: Iterable[tuple[str, _T]] | None = None +) -> list[tuple[str, _T | int]]: ... +def UnregisterServer( + clsid: PyIID, + progID: str | None = None, + verProgID: str | None = None, + customKeys: Iterable[tuple[str, PyHKEY | int]] | None = None, +) -> None: ... +def GetRegisteredServerOption(clsid: PyIID, optionName: str) -> str | None: ... +def RegisterClasses(*classes: type[_RegisterClass], **flags: Unpack[_RegisterFlag]) -> None: ... +def UnregisterClasses(*classes: type[_RegisterClass], **flags: Unpack[_UnregisterFlag]) -> None: ... +def UnregisterInfoClasses(*classes: type[_RegisterClass]) -> list[tuple[str, PyHKEY | int]]: ... +def ReExecuteElevated(flags: _ElevatedFlag) -> None: ... +def UseCommandLine(*classes: type[_RegisterClass], **flags: Unpack[_CommandFlag]) -> list[tuple[str, PyHKEY | int]] | None: ... +def RegisterPyComCategory() -> None: ... diff --git a/stubs/pywin32/win32com/server/util.pyi b/stubs/pywin32/win32com/server/util.pyi new file mode 100644 index 000000000000..fda3f8187ea8 --- /dev/null +++ b/stubs/pywin32/win32com/server/util.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Literal + +import _win32typing + +def wrap( + ob, iid=None, usePolicy: type[Incomplete] | None = None, useDispatcher: type[Incomplete] | bool | Literal[0, 1] | None = None +): ... +def unwrap(ob): ... + +class ListEnumerator: + index: int + def __init__(self, data, index: int = 0, iid=...) -> None: ... + def Next(self, count: int): ... + def Skip(self, count: int) -> None: ... + def Reset(self) -> None: ... + def Clone(self): ... + +class ListEnumeratorGateway(ListEnumerator): + def Next(self, count: int) -> Iterable[Incomplete]: ... + +def NewEnum( + seq, + cls=..., + iid=..., + usePolicy: type[Incomplete] | None = None, + useDispatcher: type[Incomplete] | bool | Literal[0, 1] | None = None, +): ... + +class Collection: + data: Incomplete + def __init__(self, data=None, readOnly: bool | Literal[0, 1] = 0) -> None: ... + def Item(self, *args): ... + def Count(self): ... + def Add(self, value) -> None: ... + def Remove(self, index) -> None: ... + def Insert(self, index, value) -> None: ... + +def NewCollection(seq, cls=...) -> _win32typing.PyIUnknown: ... + +class FileStream: + file: Incomplete + def __init__(self, file: _win32typing.Pymmapfile) -> None: ... + def Read(self, amount): ... + def Write(self, data) -> int: ... + def Clone(self): ... + def CopyTo(self, dest, cb) -> tuple[int, int]: ... + def Seek(self, offset: int, origin: int) -> int: ... diff --git a/stubs/pywin32/win32com/shell/__init__.pyi b/stubs/pywin32/win32com/shell/__init__.pyi new file mode 100644 index 000000000000..1074dc68af86 --- /dev/null +++ b/stubs/pywin32/win32com/shell/__init__.pyi @@ -0,0 +1 @@ +from win32comext.shell import * diff --git a/stubs/pywin32/win32com/shell/shell.pyi b/stubs/pywin32/win32com/shell/shell.pyi new file mode 100644 index 000000000000..63f0421620f0 --- /dev/null +++ b/stubs/pywin32/win32com/shell/shell.pyi @@ -0,0 +1 @@ +from win32comext.shell.shell import * diff --git a/stubs/pywin32/win32com/shell/shellcon.pyi b/stubs/pywin32/win32com/shell/shellcon.pyi new file mode 100644 index 000000000000..d10057f464e4 --- /dev/null +++ b/stubs/pywin32/win32com/shell/shellcon.pyi @@ -0,0 +1 @@ +from win32comext.shell.shellcon import * diff --git a/stubs/pywin32/win32com/storagecon.pyi b/stubs/pywin32/win32com/storagecon.pyi new file mode 100644 index 000000000000..717bba5ebcba --- /dev/null +++ b/stubs/pywin32/win32com/storagecon.pyi @@ -0,0 +1,115 @@ +from typing import Final + +STGC_DEFAULT: Final = 0 +STGC_OVERWRITE: Final = 1 +STGC_ONLYIFCURRENT: Final = 2 +STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE: Final = 4 +STGC_CONSOLIDATE: Final = 8 +STGTY_STORAGE: Final = 1 +STGTY_STREAM: Final = 2 +STGTY_LOCKBYTES: Final = 3 +STGTY_PROPERTY: Final = 4 +STREAM_SEEK_SET: Final = 0 +STREAM_SEEK_CUR: Final = 1 +STREAM_SEEK_END: Final = 2 +LOCK_WRITE: Final = 1 +LOCK_EXCLUSIVE: Final = 2 +LOCK_ONLYONCE: Final = 4 +CWCSTORAGENAME: Final = 32 +STGM_DIRECT: Final = 0x00000000 +STGM_TRANSACTED: Final = 0x00010000 +STGM_SIMPLE: Final = 0x08000000 +STGM_READ: Final = 0x00000000 +STGM_WRITE: Final = 0x00000001 +STGM_READWRITE: Final = 0x00000002 +STGM_SHARE_DENY_NONE: Final = 0x00000040 +STGM_SHARE_DENY_READ: Final = 0x00000030 +STGM_SHARE_DENY_WRITE: Final = 0x00000020 +STGM_SHARE_EXCLUSIVE: Final = 0x00000010 +STGM_PRIORITY: Final = 0x00040000 +STGM_DELETEONRELEASE: Final = 0x04000000 +STGM_NOSCRATCH: Final = 0x00100000 +STGM_CREATE: Final = 0x00001000 +STGM_CONVERT: Final = 0x00020000 +STGM_FAILIFTHERE: Final = 0x00000000 +STGM_NOSNAPSHOT: Final = 0x00200000 +ASYNC_MODE_COMPATIBILITY: Final = 0x00000001 +ASYNC_MODE_DEFAULT: Final = 0x00000000 +STGTY_REPEAT: Final = 0x00000100 +STG_TOEND: Final = 0xFFFFFFFF +STG_LAYOUT_SEQUENTIAL: Final = 0x00000000 +STG_LAYOUT_INTERLEAVED: Final = 0x00000001 +COM_RIGHTS_EXECUTE: Final = 1 +COM_RIGHTS_EXECUTE_LOCAL: Final = 2 +COM_RIGHTS_EXECUTE_REMOTE: Final = 4 +COM_RIGHTS_ACTIVATE_LOCAL: Final = 8 +COM_RIGHTS_ACTIVATE_REMOTE: Final = 16 +STGFMT_DOCUMENT: Final = 0 +STGFMT_STORAGE: Final = 0 +STGFMT_NATIVE: Final = 1 +STGFMT_FILE: Final = 3 +STGFMT_ANY: Final = 4 +STGFMT_DOCFILE: Final = 5 +PID_DICTIONARY: Final = 0 +PID_CODEPAGE: Final = 1 +PID_FIRST_USABLE: Final = 2 +PID_FIRST_NAME_DEFAULT: Final = 4095 +PID_LOCALE: Final = -2147483648 +PID_MODIFY_TIME: Final = -2147483647 +PID_SECURITY: Final = -2147483646 +PID_BEHAVIOR: Final = -2147483645 +PID_ILLEGAL: Final = -1 +PID_MIN_READONLY: Final = -2147483648 +PID_MAX_READONLY: Final = -1073741825 +PIDDI_THUMBNAIL: Final = 0x00000002 +PIDSI_TITLE: Final = 2 +PIDSI_SUBJECT: Final = 3 +PIDSI_AUTHOR: Final = 4 +PIDSI_KEYWORDS: Final = 5 +PIDSI_COMMENTS: Final = 6 +PIDSI_TEMPLATE: Final = 7 +PIDSI_LASTAUTHOR: Final = 8 +PIDSI_REVNUMBER: Final = 9 +PIDSI_EDITTIME: Final = 10 +PIDSI_LASTPRINTED: Final = 11 +PIDSI_CREATE_DTM: Final = 12 +PIDSI_LASTSAVE_DTM: Final = 13 +PIDSI_PAGECOUNT: Final = 14 +PIDSI_WORDCOUNT: Final = 15 +PIDSI_CHARCOUNT: Final = 16 +PIDSI_THUMBNAIL: Final = 17 +PIDSI_APPNAME: Final = 18 +PIDSI_DOC_SECURITY: Final = 19 +PIDDSI_CATEGORY: Final = 2 +PIDDSI_PRESFORMAT: Final = 3 +PIDDSI_BYTECOUNT: Final = 4 +PIDDSI_LINECOUNT: Final = 5 +PIDDSI_PARCOUNT: Final = 6 +PIDDSI_SLIDECOUNT: Final = 7 +PIDDSI_NOTECOUNT: Final = 8 +PIDDSI_HIDDENCOUNT: Final = 9 +PIDDSI_MMCLIPCOUNT: Final = 10 +PIDDSI_SCALE: Final = 11 +PIDDSI_HEADINGPAIR: Final = 12 +PIDDSI_DOCPARTS: Final = 13 +PIDDSI_MANAGER: Final = 14 +PIDDSI_COMPANY: Final = 15 +PIDDSI_LINKSDIRTY: Final = 16 +PIDMSI_EDITOR: Final = 2 +PIDMSI_SUPPLIER: Final = 3 +PIDMSI_SOURCE: Final = 4 +PIDMSI_SEQUENCE_NO: Final = 5 +PIDMSI_PROJECT: Final = 6 +PIDMSI_STATUS: Final = 7 +PIDMSI_OWNER: Final = 8 +PIDMSI_RATING: Final = 9 +PIDMSI_PRODUCTION: Final = 10 +PIDMSI_COPYRIGHT: Final = 11 +PROPSETFLAG_DEFAULT: Final = 0 +PROPSETFLAG_NONSIMPLE: Final = 1 +PROPSETFLAG_ANSI: Final = 2 +PROPSETFLAG_UNBUFFERED: Final = 4 +PROPSETFLAG_CASE_SENSITIVE: Final = 8 +STGMOVE_MOVE: Final = 0 +STGMOVE_COPY: Final = 1 +STGMOVE_SHALLOWCOPY: Final = 2 diff --git a/stubs/pywin32/win32com/taskscheduler/__init__.pyi b/stubs/pywin32/win32com/taskscheduler/__init__.pyi new file mode 100644 index 000000000000..2d22e3f9c8ab --- /dev/null +++ b/stubs/pywin32/win32com/taskscheduler/__init__.pyi @@ -0,0 +1 @@ +from win32comext.taskscheduler import * diff --git a/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi b/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi new file mode 100644 index 000000000000..7771ba730155 --- /dev/null +++ b/stubs/pywin32/win32com/taskscheduler/taskscheduler.pyi @@ -0,0 +1 @@ +from win32comext.taskscheduler.taskscheduler import * diff --git a/stubs/pywin32/win32com/universal.pyi b/stubs/pywin32/win32com/universal.pyi new file mode 100644 index 000000000000..2a52e6d26289 --- /dev/null +++ b/stubs/pywin32/win32com/universal.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing import Literal, SupportsIndex, TypeAlias + +import pythoncom + +com_error = pythoncom.com_error + +# Type of pythoncom._univgw.WriteFromOutTuple +# The two tuples must be of equal length +_WriteFromOutTupleType: TypeAlias = Callable[ + [tuple[Incomplete, ...] | None, tuple[Incomplete, ...] | None, int], Incomplete | None +] + +def RegisterInterfaces( + typelibGUID, lcid, major, minor, interface_names: Iterable[str] | None = None +) -> list[tuple[Incomplete, Incomplete, Incomplete]]: ... + +class Arg: + name: Incomplete + vt: Incomplete + inOut: Incomplete + default: Incomplete + clsid: Incomplete + size: Incomplete + offset: int + def __init__(self, arg_info, name=None) -> None: ... + +class Method: + dispid: Incomplete + invkind: Incomplete + name: Incomplete + args: list[Arg] + cbArgs: Incomplete + def __init__(self, method_info, isEventSink: bool | Literal[0, 1] = 0) -> None: ... + +class Definition: + def __init__(self, iid, is_dispatch, method_defs) -> None: ... + def iid(self): ... + def vtbl_argsizes(self) -> list[Incomplete]: ... + def vtbl_argcounts(self) -> list[int]: ... + def dispatch( + self, ob, index: SupportsIndex, argPtr, ReadFromInTuple=..., WriteFromOutTuple: _WriteFromOutTupleType = ... + ): ... diff --git a/stubs/pywin32/win32com/util.pyi b/stubs/pywin32/win32com/util.pyi new file mode 100644 index 000000000000..4b23324c4289 --- /dev/null +++ b/stubs/pywin32/win32com/util.pyi @@ -0,0 +1 @@ +def IIDToInterfaceName(iid) -> str: ... diff --git a/stubs/pywin32/win32comext/__init__.pyi b/stubs/pywin32/win32comext/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/adsi/__init__.pyi b/stubs/pywin32/win32comext/adsi/__init__.pyi new file mode 100644 index 000000000000..e409f094ef98 --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/__init__.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +import _win32typing +import win32com.client + +# Re-export everything from win32comext/adsi/adsi.pyd +# Not using a star export because the redefinitions below mess up mypy, pyright and stubtest +from win32comext.adsi.adsi import ( + DBPROPSET_ADSISEARCH as DBPROPSET_ADSISEARCH, + ADsBuildEnumerator as ADsBuildEnumerator, + ADsEnumerateNext as ADsEnumerateNext, + ADsGetLastError as ADsGetLastError, + CLSID_AccessControlEntry as CLSID_AccessControlEntry, + CLSID_AccessControlList as CLSID_AccessControlList, + CLSID_ADsDSOObject as CLSID_ADsDSOObject, + CLSID_DsObjectPicker as CLSID_DsObjectPicker, + CLSID_SecurityDescriptor as CLSID_SecurityDescriptor, + DBGUID_LDAPDialect as DBGUID_LDAPDialect, + DSOP_SCOPE_INIT_INFOs as DSOP_SCOPE_INIT_INFOs, + IID_IADs as IID_IADs, + IID_IADsClass as IID_IADsClass, + IID_IADsCollection as IID_IADsCollection, + IID_IADsComputer as IID_IADsComputer, + IID_IADsComputerOperations as IID_IADsComputerOperations, + IID_IADsContainer as IID_IADsContainer, + IID_IADsDeleteOps as IID_IADsDeleteOps, + IID_IADsDomain as IID_IADsDomain, + IID_IADsFileService as IID_IADsFileService, + IID_IADsFileServiceOperations as IID_IADsFileServiceOperations, + IID_IADsFileShare as IID_IADsFileShare, + IID_IADsGroup as IID_IADsGroup, + IID_IADsLocality as IID_IADsLocality, + IID_IADsMembers as IID_IADsMembers, + IID_IADsNamespaces as IID_IADsNamespaces, + IID_IADsO as IID_IADsO, + IID_IADsOpenDSObject as IID_IADsOpenDSObject, + IID_IADsOU as IID_IADsOU, + IID_IADsPrintJob as IID_IADsPrintJob, + IID_IADsPrintJobOperations as IID_IADsPrintJobOperations, + IID_IADsPrintQueue as IID_IADsPrintQueue, + IID_IADsPrintQueueOperations as IID_IADsPrintQueueOperations, + IID_IADsProperty as IID_IADsProperty, + IID_IADsPropertyList as IID_IADsPropertyList, + IID_IADsResource as IID_IADsResource, + IID_IADsSearch as IID_IADsSearch, + IID_IADsService as IID_IADsService, + IID_IADsServiceOperations as IID_IADsServiceOperations, + IID_IADsSession as IID_IADsSession, + IID_IADsSyntax as IID_IADsSyntax, + IID_IADsUser as IID_IADsUser, + IID_IDirectoryObject as IID_IDirectoryObject, + IID_IDirectorySearch as IID_IDirectorySearch, + IID_IDsObjectPicker as IID_IDsObjectPicker, + LIBID_ADs as LIBID_ADs, + StringAsDS_SELECTION_LIST as StringAsDS_SELECTION_LIST, + error as error, +) + +LCID: int +IDispatchType: Incomplete +IADsContainerType: Incomplete + +class ADSIEnumerator: + index: int + def __init__(self, ob) -> None: ... + def __getitem__(self, index): ... + def __call__(self, index): ... + +class ADSIDispatch(win32com.client.CDispatch): + def __getattr__(self, attr: str): ... + def QueryInterface(self, iid): ... + +# Redefinition making "iid" optional. +def ADsGetObject(path, iid: _win32typing.PyIID = ...): ... + +# Redefinition with flipped "reserved" and "iid" arguments. +def ADsOpenObject(path, username, password, reserved: int = ..., iid: _win32typing.PyIID = ...): ... diff --git a/stubs/pywin32/win32comext/adsi/adsi.pyi b/stubs/pywin32/win32comext/adsi/adsi.pyi new file mode 100644 index 000000000000..350593ee7f16 --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/adsi.pyi @@ -0,0 +1,58 @@ +from _typeshed import Incomplete +from typing import TypeAlias + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def ADsOpenObject(path, username, password, iid: _win32typing.PyIID, reserved: int = ..., /): ... +def ADsGetObject(path, iid: _win32typing.PyIID, /): ... +def ADsBuildEnumerator(container: _win32typing.PyIADsContainer, /): ... +def ADsEnumerateNext(enum, num: int = ..., /): ... +def ADsGetLastError() -> tuple[Incomplete, Incomplete, Incomplete]: ... +def StringAsDS_SELECTION_LIST(buf, /): ... + +DSOP_SCOPE_INIT_INFOs = _win32typing.PyDSOP_SCOPE_INIT_INFOs +CLSID_ADsDSOObject: _win32typing.PyIID +CLSID_AccessControlEntry: _win32typing.PyIID +CLSID_AccessControlList: _win32typing.PyIID +CLSID_DsObjectPicker: _win32typing.PyIID +CLSID_SecurityDescriptor: _win32typing.PyIID +DBGUID_LDAPDialect: _win32typing.PyIID +DBPROPSET_ADSISEARCH: _win32typing.PyIID +IID_IADs: _win32typing.PyIID +IID_IADsClass: _win32typing.PyIID +IID_IADsCollection: _win32typing.PyIID +IID_IADsComputer: _win32typing.PyIID +IID_IADsComputerOperations: _win32typing.PyIID +IID_IADsContainer: _win32typing.PyIID +IID_IADsDeleteOps: _win32typing.PyIID +IID_IADsDomain: _win32typing.PyIID +IID_IADsFileService: _win32typing.PyIID +IID_IADsFileServiceOperations: _win32typing.PyIID +IID_IADsFileShare: _win32typing.PyIID +IID_IADsGroup: _win32typing.PyIID +IID_IADsLocality: _win32typing.PyIID +IID_IADsMembers: _win32typing.PyIID +IID_IADsNamespaces: _win32typing.PyIID +IID_IADsO: _win32typing.PyIID +IID_IADsOU: _win32typing.PyIID +IID_IADsOpenDSObject: _win32typing.PyIID +IID_IADsPrintJob: _win32typing.PyIID +IID_IADsPrintJobOperations: _win32typing.PyIID +IID_IADsPrintQueue: _win32typing.PyIID +IID_IADsPrintQueueOperations: _win32typing.PyIID +IID_IADsProperty: _win32typing.PyIID +IID_IADsPropertyList: _win32typing.PyIID +IID_IADsResource: _win32typing.PyIID +IID_IADsSearch: _win32typing.PyIID +IID_IADsService: _win32typing.PyIID +IID_IADsServiceOperations: _win32typing.PyIID +IID_IADsSession: _win32typing.PyIID +IID_IADsSyntax: _win32typing.PyIID +IID_IADsUser: _win32typing.PyIID +IID_IDirectoryObject: _win32typing.PyIID +IID_IDirectorySearch: _win32typing.PyIID +IID_IDsObjectPicker: _win32typing.PyIID +LIBID_ADs: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/adsi/adsicon.pyi b/stubs/pywin32/win32comext/adsi/adsicon.pyi new file mode 100644 index 000000000000..f31229dd089b --- /dev/null +++ b/stubs/pywin32/win32comext/adsi/adsicon.pyi @@ -0,0 +1,318 @@ +from _typeshed import Incomplete + +ADS_ATTR_CLEAR: int +ADS_ATTR_UPDATE: int +ADS_ATTR_APPEND: int +ADS_ATTR_DELETE: int +ADS_EXT_MINEXTDISPID: int +ADS_EXT_MAXEXTDISPID: int +ADS_EXT_INITCREDENTIALS: int +ADS_EXT_INITIALIZE_COMPLETE: int +ADS_SEARCHPREF_ASYNCHRONOUS: int +ADS_SEARCHPREF_DEREF_ALIASES: int +ADS_SEARCHPREF_SIZE_LIMIT: int +ADS_SEARCHPREF_TIME_LIMIT: int +ADS_SEARCHPREF_ATTRIBTYPES_ONLY: int +ADS_SEARCHPREF_SEARCH_SCOPE: int +ADS_SEARCHPREF_TIMEOUT: int +ADS_SEARCHPREF_PAGESIZE: int +ADS_SEARCHPREF_PAGED_TIME_LIMIT: int +ADS_SEARCHPREF_CHASE_REFERRALS: int +ADS_SEARCHPREF_SORT_ON: int +ADS_SEARCHPREF_CACHE_RESULTS: int +ADS_SEARCHPREF_DIRSYNC: int +ADS_SEARCHPREF_TOMBSTONE: int +ADS_SCOPE_BASE: int +ADS_SCOPE_ONELEVEL: int +ADS_SCOPE_SUBTREE: int +ADS_SECURE_AUTHENTICATION: int +ADS_USE_ENCRYPTION: int +ADS_USE_SSL: int +ADS_READONLY_SERVER: int +ADS_PROMPT_CREDENTIALS: int +ADS_NO_AUTHENTICATION: int +ADS_FAST_BIND: int +ADS_USE_SIGNING: int +ADS_USE_SEALING: int +ADS_USE_DELEGATION: int +ADS_SERVER_BIND: int +ADSTYPE_INVALID: int +ADSTYPE_DN_STRING: Incomplete +ADSTYPE_CASE_EXACT_STRING: Incomplete +ADSTYPE_CASE_IGNORE_STRING: Incomplete +ADSTYPE_PRINTABLE_STRING: Incomplete +ADSTYPE_NUMERIC_STRING: Incomplete +ADSTYPE_BOOLEAN: Incomplete +ADSTYPE_INTEGER: Incomplete +ADSTYPE_OCTET_STRING: Incomplete +ADSTYPE_UTC_TIME: Incomplete +ADSTYPE_LARGE_INTEGER: Incomplete +ADSTYPE_PROV_SPECIFIC: Incomplete +ADSTYPE_OBJECT_CLASS: Incomplete +ADSTYPE_CASEIGNORE_LIST: Incomplete +ADSTYPE_OCTET_LIST: Incomplete +ADSTYPE_PATH: Incomplete +ADSTYPE_POSTALADDRESS: Incomplete +ADSTYPE_TIMESTAMP: Incomplete +ADSTYPE_BACKLINK: Incomplete +ADSTYPE_TYPEDNAME: Incomplete +ADSTYPE_HOLD: Incomplete +ADSTYPE_NETADDRESS: Incomplete +ADSTYPE_REPLICAPOINTER: Incomplete +ADSTYPE_FAXNUMBER: Incomplete +ADSTYPE_EMAIL: Incomplete +ADSTYPE_NT_SECURITY_DESCRIPTOR: Incomplete +ADSTYPE_UNKNOWN: Incomplete +ADSTYPE_DN_WITH_BINARY: Incomplete +ADSTYPE_DN_WITH_STRING: Incomplete +ADS_PROPERTY_CLEAR: int +ADS_PROPERTY_UPDATE: int +ADS_PROPERTY_APPEND: int +ADS_PROPERTY_DELETE: int +ADS_SYSTEMFLAG_DISALLOW_DELETE: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_RENAME: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_MOVE: int +ADS_SYSTEMFLAG_CONFIG_ALLOW_LIMITED_MOVE: int +ADS_SYSTEMFLAG_DOMAIN_DISALLOW_RENAME: int +ADS_SYSTEMFLAG_DOMAIN_DISALLOW_MOVE: int +ADS_SYSTEMFLAG_CR_NTDS_NC: int +ADS_SYSTEMFLAG_CR_NTDS_DOMAIN: int +ADS_SYSTEMFLAG_ATTR_NOT_REPLICATED: int +ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED: int +ADS_GROUP_TYPE_GLOBAL_GROUP: int +ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP: int +ADS_GROUP_TYPE_LOCAL_GROUP: int +ADS_GROUP_TYPE_UNIVERSAL_GROUP: int +ADS_GROUP_TYPE_SECURITY_ENABLED: int +ADS_UF_SCRIPT: int +ADS_UF_ACCOUNTDISABLE: int +ADS_UF_HOMEDIR_REQUIRED: int +ADS_UF_LOCKOUT: int +ADS_UF_PASSWD_NOTREQD: int +ADS_UF_PASSWD_CANT_CHANGE: int +ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED: int +ADS_UF_TEMP_DUPLICATE_ACCOUNT: int +ADS_UF_NORMAL_ACCOUNT: int +ADS_UF_INTERDOMAIN_TRUST_ACCOUNT: int +ADS_UF_WORKSTATION_TRUST_ACCOUNT: int +ADS_UF_SERVER_TRUST_ACCOUNT: int +ADS_UF_DONT_EXPIRE_PASSWD: int +ADS_UF_MNS_LOGON_ACCOUNT: int +ADS_UF_SMARTCARD_REQUIRED: int +ADS_UF_TRUSTED_FOR_DELEGATION: int +ADS_UF_NOT_DELEGATED: int +ADS_UF_USE_DES_KEY_ONLY: int +ADS_UF_DONT_REQUIRE_PREAUTH: int +ADS_UF_PASSWORD_EXPIRED: int +ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: int +ADS_RIGHT_DELETE: int +ADS_RIGHT_READ_CONTROL: int +ADS_RIGHT_WRITE_DAC: int +ADS_RIGHT_WRITE_OWNER: int +ADS_RIGHT_SYNCHRONIZE: int +ADS_RIGHT_ACCESS_SYSTEM_SECURITY: int +ADS_RIGHT_GENERIC_READ: int +ADS_RIGHT_GENERIC_WRITE: int +ADS_RIGHT_GENERIC_EXECUTE: int +ADS_RIGHT_GENERIC_ALL: int +ADS_RIGHT_DS_CREATE_CHILD: int +ADS_RIGHT_DS_DELETE_CHILD: int +ADS_RIGHT_ACTRL_DS_LIST: int +ADS_RIGHT_DS_SELF: int +ADS_RIGHT_DS_READ_PROP: int +ADS_RIGHT_DS_WRITE_PROP: int +ADS_RIGHT_DS_DELETE_TREE: int +ADS_RIGHT_DS_LIST_OBJECT: int +ADS_RIGHT_DS_CONTROL_ACCESS: int +ADS_ACETYPE_ACCESS_ALLOWED: int +ADS_ACETYPE_ACCESS_DENIED: int +ADS_ACETYPE_SYSTEM_AUDIT: int +ADS_ACETYPE_ACCESS_ALLOWED_OBJECT: int +ADS_ACETYPE_ACCESS_DENIED_OBJECT: int +ADS_ACETYPE_SYSTEM_AUDIT_OBJECT: int +ADS_ACETYPE_SYSTEM_ALARM_OBJECT: int +ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK: int +ADS_ACETYPE_ACCESS_DENIED_CALLBACK: int +ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK_OBJECT: int +ADS_ACETYPE_ACCESS_DENIED_CALLBACK_OBJECT: int +ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK: int +ADS_ACETYPE_SYSTEM_ALARM_CALLBACK: int +ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK_OBJECT: int +ADS_ACETYPE_SYSTEM_ALARM_CALLBACK_OBJECT: int +ADS_ACEFLAG_INHERIT_ACE: int +ADS_ACEFLAG_NO_PROPAGATE_INHERIT_ACE: int +ADS_ACEFLAG_INHERIT_ONLY_ACE: int +ADS_ACEFLAG_INHERITED_ACE: int +ADS_ACEFLAG_VALID_INHERIT_FLAGS: int +ADS_ACEFLAG_SUCCESSFUL_ACCESS: int +ADS_ACEFLAG_FAILED_ACCESS: int +ADS_FLAG_OBJECT_TYPE_PRESENT: int +ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT: int +ADS_SD_CONTROL_SE_OWNER_DEFAULTED: int +ADS_SD_CONTROL_SE_GROUP_DEFAULTED: int +ADS_SD_CONTROL_SE_DACL_PRESENT: int +ADS_SD_CONTROL_SE_DACL_DEFAULTED: int +ADS_SD_CONTROL_SE_SACL_PRESENT: int +ADS_SD_CONTROL_SE_SACL_DEFAULTED: int +ADS_SD_CONTROL_SE_DACL_AUTO_INHERIT_REQ: int +ADS_SD_CONTROL_SE_SACL_AUTO_INHERIT_REQ: int +ADS_SD_CONTROL_SE_DACL_AUTO_INHERITED: int +ADS_SD_CONTROL_SE_SACL_AUTO_INHERITED: int +ADS_SD_CONTROL_SE_DACL_PROTECTED: int +ADS_SD_CONTROL_SE_SACL_PROTECTED: int +ADS_SD_CONTROL_SE_SELF_RELATIVE: int +ADS_SD_REVISION_DS: int +ADS_NAME_TYPE_1779: int +ADS_NAME_TYPE_CANONICAL: int +ADS_NAME_TYPE_NT4: int +ADS_NAME_TYPE_DISPLAY: int +ADS_NAME_TYPE_DOMAIN_SIMPLE: int +ADS_NAME_TYPE_ENTERPRISE_SIMPLE: int +ADS_NAME_TYPE_GUID: int +ADS_NAME_TYPE_UNKNOWN: int +ADS_NAME_TYPE_USER_PRINCIPAL_NAME: int +ADS_NAME_TYPE_CANONICAL_EX: int +ADS_NAME_TYPE_SERVICE_PRINCIPAL_NAME: int +ADS_NAME_TYPE_SID_OR_SID_HISTORY_NAME: int +ADS_NAME_INITTYPE_DOMAIN: int +ADS_NAME_INITTYPE_SERVER: int +ADS_NAME_INITTYPE_GC: int +ADS_OPTION_SERVERNAME: int +ADS_OPTION_REFERRALS: Incomplete +ADS_OPTION_PAGE_SIZE: Incomplete +ADS_OPTION_SECURITY_MASK: Incomplete +ADS_OPTION_MUTUAL_AUTH_STATUS: Incomplete +ADS_OPTION_QUOTA: Incomplete +ADS_OPTION_PASSWORD_PORTNUMBER: Incomplete +ADS_OPTION_PASSWORD_METHOD: Incomplete +ADS_SECURITY_INFO_OWNER: int +ADS_SECURITY_INFO_GROUP: int +ADS_SECURITY_INFO_DACL: int +ADS_SECURITY_INFO_SACL: int +ADS_SETTYPE_FULL: int +ADS_SETTYPE_PROVIDER: int +ADS_SETTYPE_SERVER: int +ADS_SETTYPE_DN: int +ADS_FORMAT_WINDOWS: int +ADS_FORMAT_WINDOWS_NO_SERVER: int +ADS_FORMAT_WINDOWS_DN: int +ADS_FORMAT_WINDOWS_PARENT: int +ADS_FORMAT_X500: int +ADS_FORMAT_X500_NO_SERVER: int +ADS_FORMAT_X500_DN: int +ADS_FORMAT_X500_PARENT: int +ADS_FORMAT_SERVER: int +ADS_FORMAT_PROVIDER: int +ADS_FORMAT_LEAF: int +ADS_DISPLAY_FULL: int +ADS_DISPLAY_VALUE_ONLY: int +ADS_ESCAPEDMODE_DEFAULT: int +ADS_ESCAPEDMODE_ON: int +ADS_ESCAPEDMODE_OFF: int +ADS_ESCAPEDMODE_OFF_EX: int +ADS_PATH_FILE: int +ADS_PATH_FILESHARE: int +ADS_PATH_REGISTRY: int +ADS_SD_FORMAT_IID: int +ADS_SD_FORMAT_RAW: int +ADS_SD_FORMAT_HEXSTRING: int +E_ADS_BAD_PATHNAME: Incomplete +E_ADS_INVALID_DOMAIN_OBJECT: Incomplete +E_ADS_INVALID_USER_OBJECT: Incomplete +E_ADS_INVALID_COMPUTER_OBJECT: Incomplete +E_ADS_UNKNOWN_OBJECT: Incomplete +E_ADS_PROPERTY_NOT_SET: Incomplete +E_ADS_PROPERTY_NOT_SUPPORTED: Incomplete +E_ADS_PROPERTY_INVALID: Incomplete +E_ADS_BAD_PARAMETER: Incomplete +E_ADS_OBJECT_UNBOUND: Incomplete +E_ADS_PROPERTY_NOT_MODIFIED: Incomplete +E_ADS_PROPERTY_MODIFIED: Incomplete +E_ADS_CANT_CONVERT_DATATYPE: Incomplete +E_ADS_PROPERTY_NOT_FOUND: Incomplete +E_ADS_OBJECT_EXISTS: Incomplete +E_ADS_SCHEMA_VIOLATION: Incomplete +E_ADS_COLUMN_NOT_SET: Incomplete +S_ADS_ERRORSOCCURRED: Incomplete +S_ADS_NOMORE_ROWS: Incomplete +S_ADS_NOMORE_COLUMNS: Incomplete +E_ADS_INVALID_FILTER: Incomplete +ADS_DEREF_NEVER: int +ADS_DEREF_SEARCHING: int +ADS_DEREF_FINDING: int +ADS_DEREF_ALWAYS: int +ADSIPROP_ASYNCHRONOUS: int +ADSIPROP_DEREF_ALIASES: int +ADSIPROP_SIZE_LIMIT: int +ADSIPROP_TIME_LIMIT: int +ADSIPROP_ATTRIBTYPES_ONLY: int +ADSIPROP_SEARCH_SCOPE: int +ADSIPROP_TIMEOUT: int +ADSIPROP_PAGESIZE: int +ADSIPROP_PAGED_TIME_LIMIT: int +ADSIPROP_CHASE_REFERRALS: int +ADSIPROP_SORT_ON: int +ADSIPROP_CACHE_RESULTS: int +ADSIPROP_ADSIFLAG: int +ADSI_DIALECT_LDAP: int +ADSI_DIALECT_SQL: int +ADS_CHASE_REFERRALS_NEVER: int +ADS_CHASE_REFERRALS_SUBORDINATE: int +ADS_CHASE_REFERRALS_EXTERNAL: int +ADS_CHASE_REFERRALS_ALWAYS: Incomplete +DSOP_SCOPE_TYPE_TARGET_COMPUTER: int +DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN: int +DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN: int +DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN: int +DSOP_SCOPE_TYPE_GLOBAL_CATALOG: int +DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN: int +DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN: int +DSOP_SCOPE_TYPE_WORKGROUP: int +DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE: int +DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE: int +DSOP_SCOPE_FLAG_STARTING_SCOPE: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP: int +DSOP_SCOPE_FLAG_WANT_PROVIDER_GC: int +DSOP_SCOPE_FLAG_WANT_SID_PATH: int +DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS: int +DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS: int +DSOP_FILTER_INCLUDE_ADVANCED_VIEW: int +DSOP_FILTER_USERS: int +DSOP_FILTER_BUILTIN_GROUPS: int +DSOP_FILTER_WELL_KNOWN_PRINCIPALS: int +DSOP_FILTER_UNIVERSAL_GROUPS_DL: int +DSOP_FILTER_UNIVERSAL_GROUPS_SE: int +DSOP_FILTER_GLOBAL_GROUPS_DL: int +DSOP_FILTER_GLOBAL_GROUPS_SE: int +DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL: int +DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE: int +DSOP_FILTER_CONTACTS: int +DSOP_FILTER_COMPUTERS: int +DSOP_DOWNLEVEL_FILTER_USERS: int +DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS: int +DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS: int +DSOP_DOWNLEVEL_FILTER_COMPUTERS: int +DSOP_DOWNLEVEL_FILTER_WORLD: int +DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER: int +DSOP_DOWNLEVEL_FILTER_ANONYMOUS: int +DSOP_DOWNLEVEL_FILTER_BATCH: int +DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER: int +DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP: int +DSOP_DOWNLEVEL_FILTER_DIALUP: int +DSOP_DOWNLEVEL_FILTER_INTERACTIVE: int +DSOP_DOWNLEVEL_FILTER_NETWORK: int +DSOP_DOWNLEVEL_FILTER_SERVICE: int +DSOP_DOWNLEVEL_FILTER_SYSTEM: int +DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS: int +DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER: int +DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS: int +DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE: int +DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE: int +DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON: int +DSOP_FLAG_MULTISELECT: int +DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK: int +CFSTR_DSOP_DS_SELECTION_LIST: str diff --git a/stubs/pywin32/win32comext/authorization/__init__.pyi b/stubs/pywin32/win32comext/authorization/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/authorization/authorization.pyi b/stubs/pywin32/win32comext/authorization/authorization.pyi new file mode 100644 index 000000000000..9c2074bac7d8 --- /dev/null +++ b/stubs/pywin32/win32comext/authorization/authorization.pyi @@ -0,0 +1,5 @@ +import _win32typing + +def EditSecurity(hwndOwner, psi): ... + +IID_ISecurityInformation: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axcontrol/__init__.pyi b/stubs/pywin32/win32comext/axcontrol/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi b/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi new file mode 100644 index 000000000000..53be3619c840 --- /dev/null +++ b/stubs/pywin32/win32comext/axcontrol/axcontrol.pyi @@ -0,0 +1,61 @@ +import _win32typing + +def OleCreate( + clsid, + clsid1, + obCLSID: _win32typing.PyIID, + obIID: _win32typing.PyIID, + renderopt, + obFormatEtc, + obOleClientSite: _win32typing.PyIOleClientSite, + obStorage: _win32typing.PyIStorage, + /, +) -> _win32typing.PyIOleObject: ... +def OleLoadPicture( + stream: _win32typing.PyIStream, size, runMode, arg: _win32typing.PyIID, arg1: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def OleLoadPicturePath( + url_or_path: str, unk, reserved, clr, arg: _win32typing.PyIID, arg1: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def OleSetContainedObject(unk: _win32typing.PyIUnknown, fContained, /) -> None: ... +def OleTranslateAccelerator(frame: _win32typing.PyIOleInPlaceFrame, frame_info, msg: _win32typing.PyMSG, /) -> None: ... + +EMBDHLP_CREATENOW: int +EMBDHLP_DELAYCREATE: int +EMBDHLP_INPROC_HANDLER: int +EMBDHLP_INPROC_SERVER: int +OLECLOSE_NOSAVE: int +OLECLOSE_PROMPTSAVE: int +OLECLOSE_SAVEIFDIRTY: int +OLECMDF_ENABLED: int +OLECMDF_LATCHED: int +OLECMDF_NINCHED: int +OLECMDF_SUPPORTED: int +OLECMDTEXTF_NAME: int +OLECMDTEXTF_NONE: int +OLECMDTEXTF_STATUS: int +OLECREATE_LEAVERUNNING: int +OLEIVERB_DISCARDUNDOSTATE: int +OLEIVERB_HIDE: int +OLEIVERB_INPLACEACTIVATE: int +OLEIVERB_OPEN: int +OLEIVERB_PRIMARY: int +OLEIVERB_SHOW: int +OLEIVERB_UIACTIVATE: int +IID_IObjectWithSite: _win32typing.PyIID +IID_IOleClientSite: _win32typing.PyIID +IID_IOleCommandTarget: _win32typing.PyIID +IID_IOleControl: _win32typing.PyIID +IID_IOleControlSite: _win32typing.PyIID +IID_IOleInPlaceActiveObject: _win32typing.PyIID +IID_IOleInPlaceFrame: _win32typing.PyIID +IID_IOleInPlaceObject: _win32typing.PyIID +IID_IOleInPlaceSite: _win32typing.PyIID +IID_IOleInPlaceSiteEx: _win32typing.PyIID +IID_IOleInPlaceSiteWindowless: _win32typing.PyIID +IID_IOleInPlaceUIWindow: _win32typing.PyIID +IID_IOleLink: _win32typing.PyIID +IID_IOleObject: _win32typing.PyIID +IID_ISpecifyPropertyPages: _win32typing.PyIID +IID_IViewObject: _win32typing.PyIID +IID_IViewObject2: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axdebug/__init__.pyi b/stubs/pywin32/win32comext/axdebug/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axdebug/adb.pyi b/stubs/pywin32/win32comext/axdebug/adb.pyi new file mode 100644 index 000000000000..ec29264a8ed9 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/adb.pyi @@ -0,0 +1,71 @@ +import bdb +from _typeshed import Incomplete + +from win32comext.axdebug import gateways +from win32comext.axdebug.util import trace + +def fnull(*args) -> None: ... + +debugging: int +traceenter = fnull +tracev = fnull +traceenter = trace +tracev = trace + +class OutputReflector: + writefunc: Incomplete + file: Incomplete + def __init__(self, file, writefunc) -> None: ... + def __getattr__(self, name: str): ... + def write(self, message) -> None: ... + +g_adb: Incomplete + +def OnSetBreakPoint(codeContext, breakPointState, lineNo) -> None: ... + +class Adb(bdb.Bdb, gateways.RemoteDebugApplicationEvents): + debugApplication: Incomplete + debuggingThread: Incomplete + debuggingThreadStateHandle: Incomplete + stackSnifferCookie: Incomplete + codeContainerProvider: Incomplete + breakFlags: Incomplete + breakReason: Incomplete + appDebugger: Incomplete + appEventConnection: Incomplete + logicalbotframe: Incomplete + currentframe: Incomplete + recursiveData: Incomplete + def __init__(self) -> None: ... + def canonic(self, fname): ... + def reset(self) -> None: ... + def stop_here(self, frame): ... + def break_here(self, frame): ... + def break_anywhere(self, frame): ... + def dispatch_return(self, frame, arg): ... + def dispatch_line(self, frame): ... + def dispatch_call(self, frame, arg): ... + def trace_dispatch(self, frame, event, arg): ... + def user_line(self, frame) -> None: ... + def user_return(self, frame, return_value) -> None: ... + def user_exception(self, frame, exc_info) -> None: ... + def set_trace(self) -> None: ... # type: ignore[override] + def CloseApp(self) -> None: ... + stackSniffer: Incomplete + def AttachApp(self, debugApplication, codeContainerProvider) -> None: ... + def ResetAXDebugging(self) -> None: ... + botframe: Incomplete + stopframe: Incomplete + def SetupAXDebugging(self, baseFrame: Incomplete | None = ..., userFrame: Incomplete | None = ...) -> None: ... + def OnConnectDebugger(self, appDebugger): ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, name) -> None: ... + def OnDebugOutput(self, string) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, rdat) -> None: ... + def OnLeaveBreakPoint(self, rdat) -> None: ... + def OnCreateThread(self, rdat) -> None: ... + def OnDestroyThread(self, rdat) -> None: ... + def OnBreakFlagChange(self, abf, rdat) -> None: ... + +def Debugger(): ... diff --git a/stubs/pywin32/win32comext/axdebug/axdebug.pyi b/stubs/pywin32/win32comext/axdebug/axdebug.pyi new file mode 100644 index 000000000000..d4862d071ef4 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/axdebug.pyi @@ -0,0 +1,122 @@ +# Can't generate with stubgen because: +# "ImportError: DLL load failed while importing axdebug: The specified module could not be found." +import _win32typing + +def GetStackAddress() -> int: ... +def GetThreadStateHandle() -> int: ... +def SetThreadStateTrace(handle: int, func, /) -> None: ... + +APPBREAKFLAG_DEBUGGER_BLOCK: int +APPBREAKFLAG_DEBUGGER_HALT: int +APPBREAKFLAG_STEP: int +BREAKPOINT_DELETED: int +BREAKPOINT_DISABLED: int +BREAKPOINT_ENABLED: int +BREAKREASON_BREAKPOINT: int +BREAKREASON_DEBUGGER_BLOCK: int +BREAKREASON_DEBUGGER_HALT: int +BREAKREASON_ERROR: int +BREAKREASON_HOST_INITIATED: int +BREAKREASON_LANGUAGE_INITIATED: int +BREAKREASON_STEP: int +BREAKRESUMEACTION_ABORT: int +BREAKRESUMEACTION_CONTINUE: int +BREAKRESUMEACTION_STEP_INTO: int +BREAKRESUMEACTION_STEP_OUT: int +BREAKRESUMEACTION_STEP_OVER: int +CLSID_DefaultDebugSessionProvider: int +CLSID_MachineDebugManager: int +CLSID_ProcessDebugManager: int +DBGPROP_ATTRIB_ACCESS_FINAL: int +DBGPROP_ATTRIB_ACCESS_PRIVATE: int +DBGPROP_ATTRIB_ACCESS_PROTECTED: int +DBGPROP_ATTRIB_ACCESS_PUBLIC: int +DBGPROP_ATTRIB_HAS_EXTENDED_ATTRIBS: int +DBGPROP_ATTRIB_NO_ATTRIB: int +DBGPROP_ATTRIB_STORAGE_FIELD: int +DBGPROP_ATTRIB_STORAGE_GLOBAL: int +DBGPROP_ATTRIB_STORAGE_STATIC: int +DBGPROP_ATTRIB_STORAGE_VIRTUAL: int +DBGPROP_ATTRIB_TYPE_IS_CONSTANT: int +DBGPROP_ATTRIB_TYPE_IS_SYNCHRONIZED: int +DBGPROP_ATTRIB_TYPE_IS_VOLATILE: int +DBGPROP_ATTRIB_VALUE_IS_EXPANDABLE: int +DBGPROP_ATTRIB_VALUE_IS_INVALID: int +DBGPROP_ATTRIB_VALUE_READONLY: int +DBGPROP_INFO_ATTRIBUTES: int +DBGPROP_INFO_AUTOEXPAND: int +DBGPROP_INFO_DEBUGPROP: int +DBGPROP_INFO_FULLNAME: int +DBGPROP_INFO_NAME: int +DBGPROP_INFO_TYPE: int +DBGPROP_INFO_VALUE: int +DEBUG_TEXT_ALLOWBREAKPOINTS: int +DEBUG_TEXT_ISEXPRESSION: int +DOCUMENTNAMETYPE_APPNODE: int +DOCUMENTNAMETYPE_FILE_TAIL: int +DOCUMENTNAMETYPE_TITLE: int +DOCUMENTNAMETYPE_URL: int +ERRORRESUMEACTION_AbortCallAndReturnErrorToCaller: int +ERRORRESUMEACTION_ReexecuteErrorStatement: int +ERRORRESUMEACTION_SkipErrorStatement: int +EX_DBGPROP_INFO_DEBUGEXTPROP: int +EX_DBGPROP_INFO_ID: int +EX_DBGPROP_INFO_LOCKBYTES: int +EX_DBGPROP_INFO_NTYPE: int +EX_DBGPROP_INFO_NVALUE: int +SOURCETEXT_ATTR_COMMENT: int +SOURCETEXT_ATTR_FUNCTION_START: int +SOURCETEXT_ATTR_KEYWORD: int +SOURCETEXT_ATTR_NONSOURCE: int +SOURCETEXT_ATTR_NUMBER: int +SOURCETEXT_ATTR_OPERATOR: int +SOURCETEXT_ATTR_STRING: int +TEXT_DOC_ATTR_READONLY: int +APPBREAKFLAG_IN_BREAKPOINT: int +APPBREAKFLAG_STEPTYPE_BYTECODE: int +APPBREAKFLAG_STEPTYPE_MACHINE: int +APPBREAKFLAG_STEPTYPE_MASK: int +APPBREAKFLAG_STEPTYPE_SOURCE: int + +IID_IActiveScriptDebug: _win32typing.PyIID +IID_IActiveScriptErrorDebug: _win32typing.PyIID +IID_IActiveScriptSiteDebug: _win32typing.PyIID +IID_IApplicationDebugger: _win32typing.PyIID +IID_IDebugApplication: _win32typing.PyIID +IID_IDebugApplicationNode: _win32typing.PyIID +IID_IDebugApplicationNodeEvents: _win32typing.PyIID +IID_IDebugApplicationThread: _win32typing.PyIID +IID_IDebugCodeContext: _win32typing.PyIID +IID_IDebugDocument: _win32typing.PyIID +IID_IDebugDocumentContext: _win32typing.PyIID +IID_IDebugDocumentHelper: _win32typing.PyIID +IID_IDebugDocumentHost: _win32typing.PyIID +IID_IDebugDocumentInfo: _win32typing.PyIID +IID_IDebugDocumentProvider: _win32typing.PyIID +IID_IDebugDocumentText: _win32typing.PyIID +IID_IDebugDocumentTextAuthor: _win32typing.PyIID +IID_IDebugDocumentTextEvents: _win32typing.PyIID +IID_IDebugDocumentTextExternalAuthor: _win32typing.PyIID +IID_IDebugExpression: _win32typing.PyIID +IID_IDebugExpressionCallBack: _win32typing.PyIID +IID_IDebugExpressionContext: _win32typing.PyIID +IID_IDebugProperty: _win32typing.PyIID +IID_IDebugSessionProvider: _win32typing.PyIID +IID_IDebugStackFrame: _win32typing.PyIID +IID_IDebugStackFrameSniffer: _win32typing.PyIID +IID_IDebugStackFrameSnifferEx: _win32typing.PyIID +IID_IDebugSyncOperation: _win32typing.PyIID +IID_IEnumDebugApplicationNodes: _win32typing.PyIID +IID_IEnumDebugCodeContexts: _win32typing.PyIID +IID_IEnumDebugExpressionContexts: _win32typing.PyIID +IID_IEnumDebugPropertyInfo: _win32typing.PyIID +IID_IEnumDebugStackFrames: _win32typing.PyIID +IID_IEnumRemoteDebugApplicationThreads: _win32typing.PyIID +IID_IEnumRemoteDebugApplications: _win32typing.PyIID +IID_IMachineDebugManager: _win32typing.PyIID +IID_IMachineDebugManagerEvents: _win32typing.PyIID +IID_IProcessDebugManager: _win32typing.PyIID +IID_IProvideExpressionContexts: _win32typing.PyIID +IID_IRemoteDebugApplication: _win32typing.PyIID +IID_IRemoteDebugApplicationEvents: _win32typing.PyIID +IID_IRemoteDebugApplicationThread: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/axdebug/codecontainer.pyi b/stubs/pywin32/win32comext/axdebug/codecontainer.pyi new file mode 100644 index 000000000000..29dbc568a34b --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/codecontainer.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete + +class SourceCodeContainer: + sourceContext: Incomplete + text: Incomplete + nextLineNo: int + fileName: Incomplete + codeContexts: Incomplete + site: Incomplete + startLineNumber: Incomplete + debugDocument: Incomplete | None + def __init__( + self, + text, + fileName: str = ..., + sourceContext: int = ..., + startLineNumber: int = ..., + site: Incomplete | None = ..., + debugDocument: Incomplete | None = ..., + ) -> None: ... + def GetText(self): ... + def GetName(self, dnt) -> None: ... + def GetFileName(self): ... + def GetPositionOfLine(self, cLineNumber): ... + def GetLineOfPosition(self, charPos): ... + def GetNextLine(self): ... + def GetLine(self, num): ... + def GetNumChars(self): ... + def GetNumLines(self): ... + lastPos: int + attrs: Incomplete + def GetSyntaxColorAttributes(self): ... + def GetCodeContextAtPosition(self, charPos): ... + +class SourceModuleContainer(SourceCodeContainer): + module: Incomplete + def __init__(self, module) -> None: ... + text: Incomplete + def GetText(self): ... + def GetName(self, dnt): ... diff --git a/stubs/pywin32/win32comext/axdebug/contexts.pyi b/stubs/pywin32/win32comext/axdebug/contexts.pyi new file mode 100644 index 000000000000..f3d9528f774e --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/contexts.pyi @@ -0,0 +1,18 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +class DebugCodeContext(gateways.DebugCodeContext, gateways.DebugDocumentContext): + debugSite: Incomplete + offset: Incomplete + length: Incomplete + breakPointState: int + lineno: Incomplete + codeContainer: Incomplete + def __init__(self, lineNo, charPos, len, codeContainer, debugSite) -> None: ... + def GetDocumentContext(self): ... + def SetBreakPoint(self, bps) -> None: ... + def GetDocument(self): ... + def EnumCodeContexts(self): ... + +class EnumDebugCodeContexts(gateways.EnumDebugCodeContexts): ... diff --git a/stubs/pywin32/win32comext/axdebug/debugger.pyi b/stubs/pywin32/win32comext/axdebug/debugger.pyi new file mode 100644 index 000000000000..851ce60c20b2 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/debugger.pyi @@ -0,0 +1,56 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import documents + +currentDebugger: Incomplete + +class ModuleTreeNode: + moduleName: Incomplete + module: Incomplete + realNode: Incomplete + cont: Incomplete + def __init__(self, module) -> None: ... + def Attach(self, parentRealNode) -> None: ... + def Close(self) -> None: ... + +def BuildModule(module, built_nodes, rootNode, create_node_fn, create_node_args) -> None: ... +def RefreshAllModules(builtItems, rootNode, create_node, create_node_args) -> None: ... + +class CodeContainerProvider(documents.CodeContainerProvider): + axdebugger: Incomplete + currentNumModules: Incomplete + nodes: Incomplete + def __init__(self, axdebugger) -> None: ... + def FromFileName(self, fname): ... + def Close(self) -> None: ... + +class OriginalInterfaceMaker: + cookie: Incomplete + def MakeInterfaces(self, pdm): ... + def CloseInterfaces(self, pdm) -> None: ... + +class SimpleHostStyleInterfaceMaker: + def MakeInterfaces(self, pdm): ... + def CloseInterfaces(self, pdm) -> None: ... + +class AXDebugger: + pydebugger: Incomplete + pdm: Incomplete + interfaceMaker: Incomplete + expressionCookie: Incomplete + def __init__(self, interfaceMaker: Incomplete | None = ..., processName: Incomplete | None = ...) -> None: ... + def Break(self) -> None: ... + app: Incomplete + root: Incomplete + def Close(self) -> None: ... + def RefreshAllModules(self, nodes, containerProvider) -> None: ... + def CreateApplicationNode(self, node, containerProvider): ... + +def Break() -> None: ... + +brk = Break +set_trace = Break + +def dosomethingelse() -> None: ... +def dosomething() -> None: ... +def test() -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/documents.pyi b/stubs/pywin32/win32comext/axdebug/documents.pyi new file mode 100644 index 000000000000..33b767822ea8 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/documents.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +def GetGoodFileName(fname): ... + +class DebugDocumentProvider(gateways.DebugDocumentProvider): + doc: Incomplete + def __init__(self, doc) -> None: ... + def GetName(self, dnt): ... + def GetDocumentClassId(self): ... + def GetDocument(self): ... + +class DebugDocumentText(gateways.DebugDocumentText): + codeContainer: Incomplete + def __init__(self, codeContainer) -> None: ... + def GetName(self, dnt): ... + def GetDocumentClassId(self): ... + def GetSize(self): ... + def GetPositionOfLine(self, cLineNumber): ... + def GetLineOfPosition(self, charPos): ... + def GetText(self, charPos, maxChars, wantAttr): ... + def GetPositionOfContext(self, context): ... + def GetContextOfPosition(self, charPos, maxChars): ... + +class CodeContainerProvider: + ccsAndNodes: Incomplete + def AddCodeContainer(self, cc, node: Incomplete | None = ...) -> None: ... + def FromFileName(self, fname): ... + def Close(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/expressions.pyi b/stubs/pywin32/win32comext/axdebug/expressions.pyi new file mode 100644 index 000000000000..2406702c2fbd --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/expressions.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete + +from win32com.server.util import ListEnumeratorGateway +from win32comext.axdebug import gateways + +def MakeNiceString(ob): ... + +class ProvideExpressionContexts(gateways.ProvideExpressionContexts): ... + +class ExpressionContext(gateways.DebugExpressionContext): + frame: Incomplete + def __init__(self, frame) -> None: ... + def ParseLanguageText(self, code, radix, delim, flags): ... + def GetLanguageInfo(self): ... + +class Expression(gateways.DebugExpression): + callback: Incomplete + frame: Incomplete + code: Incomplete + radix: Incomplete + delim: Incomplete + flags: Incomplete + isComplete: int + result: Incomplete + hresult: Incomplete + def __init__(self, frame, code, radix, delim, flags) -> None: ... + def Start(self, callback): ... + def Abort(self) -> None: ... + def QueryIsComplete(self): ... + def GetResultAsString(self): ... + def GetResultAsDebugProperty(self): ... + +def MakeEnumDebugProperty(object, dwFieldSpec, nRadix, iid, stackFrame: Incomplete | None = ...): ... +def GetPropertyInfo( + obname, + obvalue, + dwFieldSpec, + nRadix, + hresult: int = ..., + dictionary: Incomplete | None = ..., + stackFrame: Incomplete | None = ..., +): ... + +class EnumDebugPropertyInfo(ListEnumeratorGateway): + def GetCount(self): ... + +class DebugProperty: + name: Incomplete + value: Incomplete + parent: Incomplete + hresult: Incomplete + dictionary: Incomplete + stackFrame: Incomplete + def __init__( + self, + name, + value, + parent: Incomplete | None = ..., + hresult: int = ..., + dictionary: Incomplete | None = ..., + stackFrame: Incomplete | None = ..., + ) -> None: ... + def GetPropertyInfo(self, dwFieldSpec, nRadix): ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, value, radix) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, iid): ... + def GetParent(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/gateways.pyi b/stubs/pywin32/win32comext/axdebug/gateways.pyi new file mode 100644 index 000000000000..8ed3bb31692c --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/gateways.pyi @@ -0,0 +1,114 @@ +from _typeshed import Incomplete + +from win32com.server.util import ListEnumeratorGateway + +class EnumDebugCodeContexts(ListEnumeratorGateway): ... +class EnumDebugStackFrames(ListEnumeratorGateway): ... +class EnumDebugApplicationNodes(ListEnumeratorGateway): ... +class EnumRemoteDebugApplications(ListEnumeratorGateway): ... +class EnumRemoteDebugApplicationThreads(ListEnumeratorGateway): ... + +class DebugDocumentInfo: + def GetName(self, dnt) -> None: ... + def GetDocumentClassId(self) -> None: ... + +class DebugDocumentProvider(DebugDocumentInfo): + def GetDocument(self) -> None: ... + +class DebugApplicationNode(DebugDocumentProvider): + def EnumChildren(self) -> None: ... + def GetParent(self) -> None: ... + def SetDocumentProvider(self, pddp) -> None: ... + def Close(self) -> None: ... + def Attach(self, parent) -> None: ... + def Detach(self) -> None: ... + +class DebugApplicationNodeEvents: + def onAddChild(self, child) -> None: ... + def onRemoveChild(self, child) -> None: ... + def onDetach(self) -> None: ... + def onAttach(self, parent) -> None: ... + +class DebugDocument(DebugDocumentInfo): ... + +class DebugDocumentText(DebugDocument): + def GetDocumentAttributes(self) -> None: ... + def GetSize(self) -> None: ... + def GetPositionOfLine(self, cLineNumber) -> None: ... + def GetLineOfPosition(self, charPos) -> None: ... + def GetText(self, charPos, maxChars, wantAttr) -> None: ... + def GetPositionOfContext(self, debugDocumentContext) -> None: ... + def GetContextOfPosition(self, charPos, maxChars) -> None: ... + +class DebugDocumentTextExternalAuthor: + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class DebugDocumentTextEvents: + def onDestroy(self) -> None: ... + def onInsertText(self, cCharacterPosition, cNumToInsert) -> None: ... + def onRemoveText(self, cCharacterPosition, cNumToRemove) -> None: ... + def onReplaceText(self, cCharacterPosition, cNumToReplace) -> None: ... + def onUpdateTextAttributes(self, cCharacterPosition, cNumToUpdate) -> None: ... + def onUpdateDocumentAttributes(self, textdocattr) -> None: ... + +class DebugDocumentContext: + def GetDocument(self) -> None: ... + def EnumCodeContexts(self) -> None: ... + +class DebugCodeContext: + def GetDocumentContext(self) -> None: ... + def SetBreakPoint(self, bps) -> None: ... + +class DebugStackFrame: + def GetCodeContext(self) -> None: ... + def GetDescriptionString(self, fLong) -> None: ... + def GetLanguageString(self) -> None: ... + def GetThread(self) -> None: ... + def GetDebugProperty(self) -> None: ... + +class DebugDocumentHost: + def GetDeferredText(self, dwTextStartCookie, maxChars, bWantAttr) -> None: ... + def GetScriptTextAttributes(self, codeText, delimterText, flags) -> None: ... + def OnCreateDocumentContext(self) -> None: ... + def GetPathName(self) -> None: ... + def GetFileName(self) -> None: ... + def NotifyChanged(self) -> None: ... + +class DebugDocumentTextConnectServer: + cookieNo: int + connections: Incomplete + def EnumConnections(self) -> None: ... + def GetConnectionInterface(self) -> None: ... + def GetConnectionPointContainer(self): ... + def Advise(self, pUnk): ... + def Unadvise(self, cookie): ... + def EnumConnectionPoints(self) -> None: ... + def FindConnectionPoint(self, iid): ... + +class RemoteDebugApplicationEvents: + def OnConnectDebugger(self, appDebugger) -> None: ... + def OnDisconnectDebugger(self) -> None: ... + def OnSetName(self, name) -> None: ... + def OnDebugOutput(self, string) -> None: ... + def OnClose(self) -> None: ... + def OnEnterBreakPoint(self, rdat) -> None: ... + def OnLeaveBreakPoint(self, rdat) -> None: ... + def OnCreateThread(self, rdat) -> None: ... + def OnDestroyThread(self, rdat) -> None: ... + def OnBreakFlagChange(self, abf, rdat) -> None: ... + +class DebugExpressionContext: + def ParseLanguageText(self, code, radix, delim, flags) -> None: ... + def GetLanguageInfo(self) -> None: ... + +class DebugExpression: + def Start(self, callback) -> None: ... + def Abort(self) -> None: ... + def QueryIsComplete(self) -> None: ... + def GetResultAsString(self) -> None: ... + def GetResultAsDebugProperty(self) -> None: ... + +class ProvideExpressionContexts: + def EnumExpressionContexts(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/stackframe.pyi b/stubs/pywin32/win32comext/axdebug/stackframe.pyi new file mode 100644 index 000000000000..6c12e6d28d82 --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/stackframe.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways + +class EnumDebugStackFrames(gateways.EnumDebugStackFrames): + def __init__(self, debugger) -> None: ... + def Next(self, count): ... + +class DebugStackFrame(gateways.DebugStackFrame): + frame: Incomplete + lineno: Incomplete + codeContainer: Incomplete + expressionContext: Incomplete + def __init__(self, frame, lineno, codeContainer) -> None: ... + def GetThread(self) -> None: ... + def GetCodeContext(self): ... + def GetDescriptionString(self, fLong): ... + def GetLanguageString(self, fLong): ... # type: ignore[override] + def GetDebugProperty(self): ... + +class DebugStackFrameSniffer: + debugger: Incomplete + def __init__(self, debugger) -> None: ... + def EnumStackFrames(self): ... + +class StackFrameDebugProperty: + frame: Incomplete + def __init__(self, frame) -> None: ... + def GetPropertyInfo(self, dwFieldSpec, nRadix) -> None: ... + def GetExtendedInfo(self) -> None: ... + def SetValueAsString(self, value, radix) -> None: ... + def EnumMembers(self, dwFieldSpec, nRadix, iid): ... + def GetParent(self) -> None: ... diff --git a/stubs/pywin32/win32comext/axdebug/util.pyi b/stubs/pywin32/win32comext/axdebug/util.pyi new file mode 100644 index 000000000000..82b53ac6c07b --- /dev/null +++ b/stubs/pywin32/win32comext/axdebug/util.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +import win32com.server.dispatcher + +debugging: int + +def trace(*args) -> None: ... +def RaiseNotImpl(who: Incomplete | None = ...) -> None: ... + +class Dispatcher(win32com.server.dispatcher.DispatcherWin32trace): + def __init__(self, policyClass, object) -> None: ... diff --git a/stubs/pywin32/win32comext/axscript/__init__.pyi b/stubs/pywin32/win32comext/axscript/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/asputil.pyi b/stubs/pywin32/win32comext/axscript/asputil.pyi new file mode 100644 index 000000000000..37227df960b9 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/asputil.pyi @@ -0,0 +1 @@ +def iif(cond, t, f): ... diff --git a/stubs/pywin32/win32comext/axscript/axscript.pyi b/stubs/pywin32/win32comext/axscript/axscript.pyi new file mode 100644 index 000000000000..8914786fa932 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/axscript.pyi @@ -0,0 +1,52 @@ +import _win32typing + +CATID_ActiveScript: _win32typing.PyIID +CATID_ActiveScriptParse: _win32typing.PyIID +IID_IActiveScript: _win32typing.PyIID +IID_IActiveScriptError: _win32typing.PyIID +IID_IActiveScriptParse: _win32typing.PyIID +IID_IActiveScriptParseProcedure: _win32typing.PyIID +IID_IActiveScriptSite: _win32typing.PyIID +IID_IObjectSafety: _win32typing.PyIID +IID_IProvideMultipleClassInfo: _win32typing.PyIID +INTERFACESAFE_FOR_UNTRUSTED_CALLER: int +INTERFACESAFE_FOR_UNTRUSTED_DATA: int +INTERFACE_USES_DISPEX: int +INTERFACE_USES_SECURITY_MANAGER: int +MULTICLASSINFO_GETIIDPRIMARY: int +MULTICLASSINFO_GETIIDSOURCE: int +MULTICLASSINFO_GETNUMRESERVEDDISPIDS: int +MULTICLASSINFO_GETTYPEINFO: int +SCRIPTINFO_ALL_FLAGS: int +SCRIPTINFO_ITYPEINFO: int +SCRIPTINFO_IUNKNOWN: int +SCRIPTINTERRUPT_ALL_FLAGS: int +SCRIPTINTERRUPT_DEBUG: int +SCRIPTINTERRUPT_RAISEEXCEPTION: int +SCRIPTITEM_ALL_FLAGS: int +SCRIPTITEM_CODEONLY: int +SCRIPTITEM_GLOBALMEMBERS: int +SCRIPTITEM_ISPERSISTENT: int +SCRIPTITEM_ISSOURCE: int +SCRIPTITEM_ISVISIBLE: int +SCRIPTITEM_NOCODE: int +SCRIPTPROC_ALL_FLAGS: int +SCRIPTPROC_HOSTMANAGESSOURCE: int +SCRIPTPROC_IMPLICIT_PARENTS: int +SCRIPTPROC_IMPLICIT_THIS: int +SCRIPTSTATE_CLOSED: int +SCRIPTSTATE_CONNECTED: int +SCRIPTSTATE_DISCONNECTED: int +SCRIPTSTATE_INITIALIZED: int +SCRIPTSTATE_STARTED: int +SCRIPTSTATE_UNINITIALIZED: int +SCRIPTTEXT_ALL_FLAGS: int +SCRIPTTEXT_ISEXPRESSION: int +SCRIPTTEXT_ISPERSISTENT: int +SCRIPTTEXT_ISVISIBLE: int +SCRIPTTHREADSTATE_NOTINSCRIPT: int +SCRIPTTHREADSTATE_RUNNING: int +SCRIPTTYPELIB_ISCONTROL: int +SCRIPTTYPELIB_ISPERSISTENT: int +SCRIPT_E_REPORTED: int +TIFLAGS_EXTENDDISPATCHONLY: int diff --git a/stubs/pywin32/win32comext/axscript/client/__init__.pyi b/stubs/pywin32/win32comext/axscript/client/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/client/debug.pyi b/stubs/pywin32/win32comext/axscript/client/debug.pyi new file mode 100644 index 000000000000..8c1752564df6 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/debug.pyi @@ -0,0 +1,42 @@ +from _typeshed import Incomplete + +from win32comext.axdebug import gateways +from win32comext.axdebug.codecontainer import SourceCodeContainer + +debuggingTrace: int + +def trace(*args) -> None: ... + +class DebugManager: + scriptEngine: Incomplete + adb: Incomplete + rootNode: Incomplete + debugApplication: Incomplete + ccProvider: Incomplete + scriptSiteDebug: Incomplete + activeScriptDebug: Incomplete + codeContainers: Incomplete + def __init__(self, scriptEngine) -> None: ... + def Close(self) -> None: ... + def IsAnyHost(self): ... + def IsSimpleHost(self): ... + def HandleRuntimeError(self): ... + def OnEnterScript(self) -> None: ... + def OnLeaveScript(self) -> None: ... + def AddScriptBlock(self, codeBlock) -> None: ... + +class DebugCodeBlockContainer(SourceCodeContainer): + codeBlock: Incomplete + def __init__(self, codeBlock, site) -> None: ... + def GetName(self, dnt): ... + +class EnumDebugCodeContexts(gateways.EnumDebugCodeContexts): ... + +class ActiveScriptDebug: + debugMgr: Incomplete + scriptSiteDebug: Incomplete + codeContainers: Incomplete + def __init__(self, debugMgr, codeContainers) -> None: ... + def GetScriptTextAttributes(self, code, delim, flags): ... + def GetScriptletTextAttributes(self, code, delim, flags): ... + def EnumCodeContextsOfPosition(self, context, charOffset, numChars): ... diff --git a/stubs/pywin32/win32comext/axscript/client/error.pyi b/stubs/pywin32/win32comext/axscript/client/error.pyi new file mode 100644 index 000000000000..40d95a89c137 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/error.pyi @@ -0,0 +1,35 @@ +from types import TracebackType + +from win32com.server.exception import COMException +from win32comext.axscript.client.debug import DebugManager +from win32comext.axscript.client.framework import AXScriptCodeBlock, COMScript +from win32comext.axscript.server.axsite import AXSite + +debugging: int + +def FormatForAX(text: str) -> str: ... +def ExpandTabs(text: str) -> str: ... +def AddCR(text: str) -> str: ... + +class IActiveScriptError: + def GetSourceLineText(self) -> str | None: ... + def GetSourcePosition(self) -> tuple[int, int, int]: ... + def GetExceptionInfo(self) -> AXScriptException: ... + +class AXScriptException(COMException): + sourceContext: int + startLineNo: int + linetext: str + def __init__( + self, + site: COMScript, + codeBlock: AXScriptCodeBlock | None, + exc_type: None = None, + exc_value: BaseException | None = None, + exc_traceback: None = None, + ) -> None: ... + def ExtractTracebackInfo(self, tb: TracebackType, site: COMScript) -> tuple[str, int, str, str | None]: ... + +def ProcessAXScriptException( + scriptingSite: AXSite, debugManager: DebugManager, exceptionInstance: AXScriptException +) -> None | COMException | AXScriptException: ... diff --git a/stubs/pywin32/win32comext/axscript/client/framework.pyi b/stubs/pywin32/win32comext/axscript/client/framework.pyi new file mode 100644 index 000000000000..19de3698f06a --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/client/framework.pyi @@ -0,0 +1,154 @@ +from _typeshed import Incomplete +from typing_extensions import Never + +def RemoveCR(text): ... + +SCRIPTTEXT_FORCEEXECUTION: int +SCRIPTTEXT_ISEXPRESSION: int +SCRIPTTEXT_ISPERSISTENT: int +state_map: Incomplete + +def profile(fn, *args): ... + +class SafeOutput: + softspace: int + redir: Incomplete + def __init__(self, redir=None) -> None: ... + def write(self, message) -> None: ... + def flush(self) -> None: ... + def close(self) -> None: ... + +def MakeValidSysOuts() -> None: ... +def trace(*args) -> None: ... +def RaiseAssert(scode, desc) -> Never: ... + +class AXScriptCodeBlock: + name: Incomplete + codeText: Incomplete + codeObject: Incomplete + sourceContextCookie: Incomplete + startLineNumber: Incomplete + flags: Incomplete + beenExecuted: int + def __init__(self, name: str, codeText: str, sourceContextCookie: int, startLineNumber: int, flags) -> None: ... + def GetFileName(self): ... + def GetDisplayName(self): ... + def GetLineNo(self, no: int): ... + +class Event: + name: str + def __init__(self) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + dispid: Incomplete + def Build(self, typeinfo, funcdesc) -> None: ... + +class EventSink: + events: Incomplete + connection: Incomplete + coDispatch: Incomplete + myScriptItem: Incomplete + myInvokeMethod: Incomplete + iid: Incomplete + def __init__(self, myItem, coDispatch) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + def GetSourceTypeInfo(self, typeinfo): ... + def BuildEvents(self) -> None: ... + def Connect(self) -> None: ... + def Disconnect(self) -> None: ... + +class ScriptItem: + parentItem: Incomplete + dispatch: Incomplete + name: Incomplete + flags: Incomplete + eventSink: Incomplete + subItems: Incomplete + createdConnections: int + isRegistered: int + def __init__(self, parentItem, name, dispatch, flags) -> None: ... + def Reset(self) -> None: ... + def Close(self) -> None: ... + def Register(self) -> None: ... + def IsGlobal(self): ... + def IsVisible(self): ... + def GetEngine(self): ... + def GetSubItemClass(self): ... + def GetSubItem(self, name): ... + def GetCreateSubItem(self, parentItem, name, dispatch, flags): ... + def CreateConnections(self) -> None: ... + def Connect(self) -> None: ... + def Disconnect(self) -> None: ... + def BuildEvents(self) -> None: ... + def FindBuildSubItemEvents(self) -> None: ... + def GetDefaultSourceTypeInfo(self, typeinfo): ... + +IActiveScriptMethods: Incomplete +IActiveScriptParseMethods: Incomplete +IObjectSafetyMethods: Incomplete +IActiveScriptParseProcedureMethods: Incomplete + +class COMScript: + baseThreadId: int + debugManager: Incomplete + threadState: Incomplete + scriptState: Incomplete + scriptSite: Incomplete + safetyOptions: int + lcid: int + subItems: Incomplete + scriptCodeBlocks: Incomplete + def __init__(self) -> None: ... + def InitNew(self) -> None: ... + def AddScriptlet( + self, defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber + ) -> None: ... + def ParseScriptText(self, code, itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult): ... + def ParseProcedureText( + self, code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags + ) -> None: ... + def SetScriptSite(self, site) -> None: ... + def GetScriptSite(self, iid): ... + def SetScriptState(self, state) -> None: ... + def GetScriptState(self): ... + persistLoaded: int + def Close(self) -> None: ... + def AddNamedItem(self, name, flags) -> None: ... + def GetScriptDispatch(self, name) -> None: ... + def GetCurrentScriptThreadID(self): ... + def GetScriptThreadID(self, win32ThreadId): ... + def GetScriptThreadState(self, scriptThreadId): ... + def AddTypeLib(self, uuid, major, minor, flags) -> None: ... + def Clone(self) -> None: ... + def SetInterfaceSafetyOptions(self, iid, optionsMask, enabledOptions) -> None: ... + def GetInterfaceSafetyOptions(self, iid): ... + def ExecutePendingScripts(self) -> None: ... + def ProcessScriptItemEvent(self, item, event, lcid, wFlags, args): ... + def ResetNamedItems(self) -> None: ... + def GetCurrentSafetyOptions(self): ... + def ProcessNewNamedItemsConnections(self) -> None: ... + def RegisterNewNamedItems(self) -> None: ... + def RegisterNamedItem(self, item) -> None: ... + def CheckConnectedOrDisconnected(self) -> None: ... + def Connect(self) -> None: ... + def Run(self) -> None: ... + def Stop(self) -> None: ... + def Disconnect(self) -> None: ... + def ConnectEventHandlers(self) -> None: ... + def DisconnectEventHandlers(self) -> None: ... + def Reset(self) -> None: ... + def ChangeScriptState(self, state) -> None: ... + def ApplyInScriptedSection(self, codeBlock: AXScriptCodeBlock | None, fn, args): ... + def CompileInScriptedSection(self, codeBlock: AXScriptCodeBlock, type, realCode=None): ... + def ExecInScriptedSection(self, codeBlock: AXScriptCodeBlock, globals, locals=None): ... + def EvalInScriptedSection(self, codeBlock, globals, locals=None): ... + def HandleException(self, codeBlock: AXScriptCodeBlock | None) -> Never: ... + def BeginScriptedSection(self) -> None: ... + def EndScriptedSection(self) -> None: ... + def DisableInterrupts(self) -> None: ... + def EnableInterrupts(self) -> None: ... + def GetNamedItem(self, name): ... + def GetNamedItemClass(self): ... + +def dumptypeinfo(typeinfo) -> None: ... diff --git a/stubs/pywin32/win32comext/axscript/server/__init__.pyi b/stubs/pywin32/win32comext/axscript/server/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/axscript/server/axsite.pyi b/stubs/pywin32/win32comext/axscript/server/axsite.pyi new file mode 100644 index 000000000000..aa77ad51b740 --- /dev/null +++ b/stubs/pywin32/win32comext/axscript/server/axsite.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +class AXEngine: + eScript: Incomplete + eParse: Incomplete + eSafety: Incomplete + def __init__(self, site, engine) -> None: ... + def __del__(self) -> None: ... + def GetScriptDispatch(self, name: Incomplete | None = ...): ... + def AddNamedItem(self, item, flags): ... + def AddCode(self, code, flags: int = ...) -> None: ... + def EvalCode(self, code): ... + def Start(self) -> None: ... + def Close(self) -> None: ... + def SetScriptState(self, state) -> None: ... + +IActiveScriptSite_methods: Incomplete + +class AXSite: + lcid: Incomplete + objModel: Incomplete + engine: Incomplete + def __init__(self, objModel=..., engine: Incomplete | None = ..., lcid: int = ...) -> None: ... + def AddEngine(self, engine): ... + def GetLCID(self): ... + def GetItemInfo(self, name, returnMask): ... + def GetDocVersionString(self): ... + def OnScriptTerminate(self, result, excepInfo) -> None: ... + def OnStateChange(self, state) -> None: ... + def OnScriptError(self, errorInterface): ... + def OnEnterScript(self) -> None: ... + def OnLeaveScript(self) -> None: ... diff --git a/stubs/pywin32/win32comext/bits/__init__.pyi b/stubs/pywin32/win32comext/bits/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/bits/bits.pyi b/stubs/pywin32/win32comext/bits/bits.pyi new file mode 100644 index 000000000000..8bc0c0563e93 --- /dev/null +++ b/stubs/pywin32/win32comext/bits/bits.pyi @@ -0,0 +1,61 @@ +import _win32typing + +BG_AUTH_SCHEME_BASIC: int +BG_AUTH_SCHEME_DIGEST: int +BG_AUTH_SCHEME_NEGOTIATE: int +BG_AUTH_SCHEME_NTLM: int +BG_AUTH_SCHEME_PASSPORT: int +BG_AUTH_TARGET_PROXY: int +BG_AUTH_TARGET_SERVER: int +BG_CERT_STORE_LOCATION_CURRENT_SERVICE: int +BG_CERT_STORE_LOCATION_CURRENT_USER: int +BG_CERT_STORE_LOCATION_CURRENT_USER_GROUP_POLICY: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE_ENTERPRISE: int +BG_CERT_STORE_LOCATION_LOCAL_MACHINE_GROUP_POLICY: int +BG_CERT_STORE_LOCATION_SERVICES: int +BG_CERT_STORE_LOCATION_USERS: int +BG_ERROR_CONTEXT_GENERAL_QUEUE_MANAGER: int +BG_ERROR_CONTEXT_GENERAL_TRANSPORT: int +BG_ERROR_CONTEXT_LOCAL_FILE: int +BG_ERROR_CONTEXT_NONE: int +BG_ERROR_CONTEXT_QUEUE_MANAGER_NOTIFICATION: int +BG_ERROR_CONTEXT_REMOTE_APPLICATION: int +BG_ERROR_CONTEXT_REMOTE_FILE: int +BG_ERROR_CONTEXT_UNKNOWN: int +BG_JOB_ENUM_ALL_USERS: int +BG_JOB_PRIORITY_FOREGROUND: int +BG_JOB_PRIORITY_HIGH: int +BG_JOB_PRIORITY_LOW: int +BG_JOB_PRIORITY_NORMAL: int +BG_JOB_PROXY_USAGE_AUTODETECT: int +BG_JOB_PROXY_USAGE_NO_PROXY: int +BG_JOB_PROXY_USAGE_OVERRIDE: int +BG_JOB_PROXY_USAGE_PRECONFIG: int +BG_JOB_STATE_ACKNOWLEDGED: int +BG_JOB_STATE_CANCELLED: int +BG_JOB_STATE_CONNECTING: int +BG_JOB_STATE_ERROR: int +BG_JOB_STATE_QUEUED: int +BG_JOB_STATE_SUSPENDED: int +BG_JOB_STATE_TRANSFERRED: int +BG_JOB_STATE_TRANSFERRING: int +BG_JOB_STATE_TRANSIENT_ERROR: int +BG_JOB_TYPE_DOWNLOAD: int +BG_JOB_TYPE_UPLOAD: int +BG_JOB_TYPE_UPLOAD_REPLY: int +BG_NOTIFY_DISABLE: int +BG_NOTIFY_JOB_ERROR: int +BG_NOTIFY_JOB_MODIFICATION: int +BG_NOTIFY_JOB_TRANSFERRED: int +CLSID_BackgroundCopyManager: _win32typing.PyIID +IID_IBackgroundCopyCallback: _win32typing.PyIID +IID_IBackgroundCopyError: _win32typing.PyIID +IID_IBackgroundCopyFile: _win32typing.PyIID +IID_IBackgroundCopyFile2: _win32typing.PyIID +IID_IBackgroundCopyJob: _win32typing.PyIID +IID_IBackgroundCopyJob2: _win32typing.PyIID +IID_IBackgroundCopyJob3: _win32typing.PyIID +IID_IBackgroundCopyManager: _win32typing.PyIID +IID_IEnumBackgroundCopyFiles: _win32typing.PyIID +IID_IEnumBackgroundCopyJobs: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/directsound/__init__.pyi b/stubs/pywin32/win32comext/directsound/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/directsound/directsound.pyi b/stubs/pywin32/win32comext/directsound/directsound.pyi new file mode 100644 index 000000000000..1b53c8f84199 --- /dev/null +++ b/stubs/pywin32/win32comext/directsound/directsound.pyi @@ -0,0 +1,116 @@ +from _typeshed import Incomplete + +import _win32typing + +def DirectSoundCreate(guid: _win32typing.PyIID | None = ..., unk: Incomplete | None = ..., /) -> _win32typing.PyIUnknown: ... +def DirectSoundEnumerate(): ... +def DirectSoundCaptureCreate( + guid: _win32typing.PyIID | None = ..., unk: Incomplete | None = ..., / +) -> _win32typing.PyIUnknown: ... +def DirectSoundCaptureEnumerate(): ... +def DSCAPS() -> _win32typing.PyDSCAPS: ... +def DSBCAPS() -> _win32typing.PyDSBCAPS: ... +def DSCCAPS() -> _win32typing.PyDSCCAPS: ... +def DSCBCAPS() -> _win32typing.PyDSCBCAPS: ... +def DSBUFFERDESC() -> _win32typing.PyDSBUFFERDESC: ... +def DSCBUFFERDESC() -> _win32typing.PyDSCBUFFERDESC: ... + +DS3DMODE_DISABLE: int +DS3DMODE_HEADRELATIVE: int +DS3DMODE_NORMAL: int +DSBCAPS_CTRL3D: int +DSBCAPS_CTRLFREQUENCY: int +DSBCAPS_CTRLPAN: int +DSBCAPS_CTRLPOSITIONNOTIFY: int +DSBCAPS_CTRLVOLUME: int +DSBCAPS_GETCURRENTPOSITION2: int +DSBCAPS_GLOBALFOCUS: int +DSBCAPS_LOCHARDWARE: int +DSBCAPS_LOCSOFTWARE: int +DSBCAPS_MUTE3DATMAXDISTANCE: int +DSBCAPS_PRIMARYBUFFER: int +DSBCAPS_STATIC: int +DSBCAPS_STICKYFOCUS: int +DSBLOCK_ENTIREBUFFER: int +DSBLOCK_FROMWRITECURSOR: int +DSBPLAY_LOOPING: int +DSBSTATUS_BUFFERLOST: int +DSBSTATUS_LOOPING: int +DSBSTATUS_PLAYING: int +DSCAPS_CERTIFIED: int +DSCAPS_CONTINUOUSRATE: int +DSCAPS_EMULDRIVER: int +DSCAPS_PRIMARY16BIT: int +DSCAPS_PRIMARY8BIT: int +DSCAPS_PRIMARYMONO: int +DSCAPS_PRIMARYSTEREO: int +DSCAPS_SECONDARY16BIT: int +DSCAPS_SECONDARY8BIT: int +DSCAPS_SECONDARYMONO: int +DSCAPS_SECONDARYSTEREO: int +DSCBCAPS_WAVEMAPPED: int +DSCCAPS_EMULDRIVER: int +DSSCL_EXCLUSIVE: int +DSSCL_NORMAL: int +DSSCL_PRIORITY: int +DSSCL_WRITEPRIMARY: int +DSSPEAKER_GEOMETRY_MAX: int +DSSPEAKER_GEOMETRY_MIN: int +DSSPEAKER_GEOMETRY_NARROW: int +DSSPEAKER_GEOMETRY_WIDE: int +DSSPEAKER_HEADPHONE: int +DSSPEAKER_MONO: int +DSSPEAKER_QUAD: int +DSSPEAKER_STEREO: int +DSSPEAKER_SURROUND: int +DSBCAPSType = _win32typing.PyDSBCAPS +DSBFREQUENCY_MAX: int +DSBFREQUENCY_MIN: int +DSBFREQUENCY_ORIGINAL: int +DSBPAN_CENTER: int +DSBPAN_LEFT: int +DSBPAN_RIGHT: int +DSBPN_OFFSETSTOP: int +DSBSIZE_MAX: int +DSBSIZE_MIN: int +DSBUFFERDESCType = _win32typing.PyDSBUFFERDESC +DSBVOLUME_MAX: int +DSBVOLUME_MIN: int +DSCAPSType = _win32typing.PyDSCAPSType +DSCBCAPSType = _win32typing.PyDSCBCAPSType +DSCBLOCK_ENTIREBUFFER: int +DSCBSTART_LOOPING: int +DSCBSTATUS_CAPTURING: int +DSCBSTATUS_LOOPING: int +DSCBUFFERDESCType = _win32typing.PyDSCBUFFERDESC +DSCCAPSType = _win32typing.PyDSCCAPSType +DSERR_ACCESSDENIED: int +DSERR_ALLOCATED: int +DSERR_ALREADYINITIALIZED: int +DSERR_BADFORMAT: int +DSERR_BADSENDBUFFERGUID: int +DSERR_BUFFERLOST: int +DSERR_BUFFERTOOSMALL: int +DSERR_CONTROLUNAVAIL: int +DSERR_DS8_REQUIRED: int +DSERR_FXUNAVAILABLE: int +DSERR_GENERIC: int +DSERR_INVALIDCALL: int +DSERR_INVALIDPARAM: int +DSERR_NOAGGREGATION: int +DSERR_NODRIVER: int +DSERR_NOINTERFACE: int +DSERR_OBJECTNOTFOUND: int +DSERR_OTHERAPPHASPRIO: int +DSERR_OUTOFMEMORY: int +DSERR_PRIOLEVELNEEDED: int +DSERR_SENDLOOP: int +DSERR_UNINITIALIZED: int +DSERR_UNSUPPORTED: int +DS_NO_VIRTUALIZATION: int +DS_OK: int +IID_IDirectSound: _win32typing.PyIID +IID_IDirectSoundBuffer: _win32typing.PyIID +IID_IDirectSoundCapture: _win32typing.PyIID +IID_IDirectSoundCaptureBuffer: _win32typing.PyIID +IID_IDirectSoundNotify: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/ifilter/__init__.pyi b/stubs/pywin32/win32comext/ifilter/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/ifilter/ifilter.pyi b/stubs/pywin32/win32comext/ifilter/ifilter.pyi new file mode 100644 index 000000000000..f1c1e76b6bd6 --- /dev/null +++ b/stubs/pywin32/win32comext/ifilter/ifilter.pyi @@ -0,0 +1,33 @@ +import _win32typing + +def BindIFilterFromStorage(stg, /): ... +def BindIFilterFromStream(stg, /): ... +def LoadIFilter(path: str, /): ... + +CHUNK_EOC: int +CHUNK_EOP: int +CHUNK_EOS: int +CHUNK_EOW: int +CHUNK_NO_BREAK: int +CHUNK_TEXT: int +CHUNK_VALUE: int +FILTER_E_ACCESS: int +FILTER_E_EMBEDDING_UNAVAILABLE: int +FILTER_E_END_OF_CHUNKS: int +FILTER_E_LINK_UNAVAILABLE: int +FILTER_E_NO_MORE_TEXT: int +FILTER_E_NO_MORE_VALUES: int +FILTER_E_NO_TEXT: int +FILTER_E_NO_VALUES: int +FILTER_E_PASSWORD: int +FILTER_S_LAST_TEXT: int +IFILTER_FLAGS_OLE_PROPERTIES: int +IFILTER_INIT_APPLY_INDEX_ATTRIBUTES: int +IFILTER_INIT_APPLY_OTHER_ATTRIBUTES: int +IFILTER_INIT_CANON_HYPHENS: int +IFILTER_INIT_CANON_PARAGRAPHS: int +IFILTER_INIT_CANON_SPACES: int +IFILTER_INIT_HARD_LINE_BREAKS: int +IFILTER_INIT_INDEXING_ONLY: int +IFILTER_INIT_SEARCH_LINKS: int +IID_IFilter: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi b/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi new file mode 100644 index 000000000000..2b6623498eb4 --- /dev/null +++ b/stubs/pywin32/win32comext/ifilter/ifiltercon.pyi @@ -0,0 +1,103 @@ +from _typeshed import Incomplete + +PSGUID_STORAGE: Incomplete +PSGUID_SUMMARYINFORMATION: Incomplete +PSGUID_HTMLINFORMATION: Incomplete +PSGUID_HTML2_INFORMATION: Incomplete +IFILTER_INIT_CANON_PARAGRAPHS: int +IFILTER_INIT_HARD_LINE_BREAKS: int +IFILTER_INIT_CANON_HYPHENS: int +IFILTER_INIT_CANON_SPACES: int +IFILTER_INIT_APPLY_INDEX_ATTRIBUTES: int +IFILTER_INIT_APPLY_CRAWL_ATTRIBUTES: int +IFILTER_INIT_APPLY_OTHER_ATTRIBUTES: int +IFILTER_INIT_INDEXING_ONLY: int +IFILTER_INIT_SEARCH_LINKS: int +IFILTER_INIT_FILTER_OWNED_VALUE_OK: int +IFILTER_FLAGS_OLE_PROPERTIES: int +CHUNK_TEXT: int +CHUNK_VALUE: int +CHUNK_NO_BREAK: int +CHUNK_EOW: int +CHUNK_EOS: int +CHUNK_EOP: int +CHUNK_EOC: int +NOT_AN_ERROR: int +FILTER_E_END_OF_CHUNKS: int +FILTER_E_NO_MORE_TEXT: int +FILTER_E_NO_MORE_VALUES: int +FILTER_E_ACCESS: int +FILTER_W_MONIKER_CLIPPED: int +FILTER_E_NO_TEXT: int +FILTER_E_NO_VALUES: int +FILTER_E_EMBEDDING_UNAVAILABLE: int +FILTER_E_LINK_UNAVAILABLE: int +FILTER_S_LAST_TEXT: int +FILTER_S_LAST_VALUES: int +FILTER_E_PASSWORD: int +FILTER_E_UNKNOWNFORMAT: int +PROPSETFLAG_DEFAULT: int +PROPSETFLAG_NONSIMPLE: int +PROPSETFLAG_ANSI: int +PROPSETFLAG_UNBUFFERED: int +PROPSETFLAG_CASE_SENSITIVE: int +PROPSET_BEHAVIOR_CASE_SENSITIVE: int +PID_DICTIONARY: int +PID_CODEPAGE: int +PID_FIRST_USABLE: int +PID_FIRST_NAME_DEFAULT: int +PID_LOCALE: int +PID_MODIFY_TIME: int +PID_SECURITY: int +PID_BEHAVIOR: int +PID_ILLEGAL: int +PID_MIN_READONLY: int +PID_MAX_READONLY: int +PIDDI_THUMBNAIL: int +PIDSI_TITLE: int +PIDSI_SUBJECT: int +PIDSI_AUTHOR: int +PIDSI_KEYWORDS: int +PIDSI_COMMENTS: int +PIDSI_TEMPLATE: int +PIDSI_LASTAUTHOR: int +PIDSI_REVNUMBER: int +PIDSI_EDITTIME: int +PIDSI_LASTPRINTED: int +PIDSI_CREATE_DTM: int +PIDSI_LASTSAVE_DTM: int +PIDSI_PAGECOUNT: int +PIDSI_WORDCOUNT: int +PIDSI_CHARCOUNT: int +PIDSI_THUMBNAIL: int +PIDSI_APPNAME: int +PIDSI_DOC_SECURITY: int +PIDDSI_CATEGORY: int +PIDDSI_PRESFORMAT: int +PIDDSI_BYTECOUNT: int +PIDDSI_LINECOUNT: int +PIDDSI_PARCOUNT: int +PIDDSI_SLIDECOUNT: int +PIDDSI_NOTECOUNT: int +PIDDSI_HIDDENCOUNT: int +PIDDSI_MMCLIPCOUNT: int +PIDDSI_SCALE: int +PIDDSI_HEADINGPAIR: int +PIDDSI_DOCPARTS: int +PIDDSI_MANAGER: int +PIDDSI_COMPANY: int +PIDDSI_LINKSDIRTY: int +PIDMSI_EDITOR: int +PIDMSI_SUPPLIER: int +PIDMSI_SOURCE: int +PIDMSI_SEQUENCE_NO: int +PIDMSI_PROJECT: int +PIDMSI_STATUS: int +PIDMSI_OWNER: int +PIDMSI_RATING: int +PIDMSI_PRODUCTION: int +PIDMSI_COPYRIGHT: int +PRSPEC_INVALID: int +PRSPEC_LPWSTR: int +PRSPEC_PROPID: int +CCH_MAX_PROPSTG_NAME: int diff --git a/stubs/pywin32/win32comext/internet/__init__.pyi b/stubs/pywin32/win32comext/internet/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/internet/inetcon.pyi b/stubs/pywin32/win32comext/internet/inetcon.pyi new file mode 100644 index 000000000000..7a90c63576b4 --- /dev/null +++ b/stubs/pywin32/win32comext/internet/inetcon.pyi @@ -0,0 +1,254 @@ +from _typeshed import Incomplete + +INET_E_USE_DEFAULT_PROTOCOLHANDLER: int +INET_E_USE_DEFAULT_SETTING: int +INET_E_DEFAULT_ACTION: int +INET_E_QUERYOPTION_UNKNOWN: int +INET_E_REDIRECTING: int +INET_E_INVALID_URL: int +INET_E_NO_SESSION: int +INET_E_CANNOT_CONNECT: int +INET_E_RESOURCE_NOT_FOUND: int +INET_E_OBJECT_NOT_FOUND: int +INET_E_DATA_NOT_AVAILABLE: int +INET_E_DOWNLOAD_FAILURE: int +INET_E_AUTHENTICATION_REQUIRED: int +INET_E_NO_VALID_MEDIA: int +INET_E_CONNECTION_TIMEOUT: int +INET_E_INVALID_REQUEST: int +INET_E_UNKNOWN_PROTOCOL: int +INET_E_SECURITY_PROBLEM: int +INET_E_CANNOT_LOAD_DATA: int +INET_E_CANNOT_INSTANTIATE_OBJECT: int +INET_E_INVALID_CERTIFICATE: int +INET_E_REDIRECT_FAILED: int +INET_E_REDIRECT_TO_DIR: int +INET_E_CANNOT_LOCK_REQUEST: int +INET_E_USE_EXTEND_BINDING: int +INET_E_TERMINATED_BIND: int +INET_E_CODE_DOWNLOAD_DECLINED: int +INET_E_RESULT_DISPATCHED: int +INET_E_CANNOT_REPLACE_SFP_FILE: int +INET_E_CODE_INSTALL_SUPPRESSED: int +INET_E_CODE_INSTALL_BLOCKED_BY_HASH_POLICY: int +MKSYS_URLMONIKER: int +URL_MK_LEGACY: int +URL_MK_UNIFORM: int +URL_MK_NO_CANONICALIZE: int +FIEF_FLAG_FORCE_JITUI: int +FIEF_FLAG_PEEK: int +FIEF_FLAG_SKIP_INSTALLED_VERSION_CHECK: int +FMFD_DEFAULT: int +FMFD_URLASFILENAME: int +FMFD_ENABLEMIMESNIFFING: int +FMFD_IGNOREMIMETEXTPLAIN: int +URLMON_OPTION_USERAGENT: int +URLMON_OPTION_USERAGENT_REFRESH: int +URLMON_OPTION_URL_ENCODING: int +URLMON_OPTION_USE_BINDSTRINGCREDS: int +URLMON_OPTION_USE_BROWSERAPPSDOCUMENTS: int +CF_NULL: int +Uri_CREATE_ALLOW_RELATIVE: int +Uri_CREATE_ALLOW_IMPLICIT_WILDCARD_SCHEME: int +Uri_CREATE_ALLOW_IMPLICIT_FILE_SCHEME: int +Uri_CREATE_NOFRAG: int +Uri_CREATE_NO_CANONICALIZE: int +Uri_CREATE_CANONICALIZE: int +Uri_CREATE_FILE_USE_DOS_PATH: int +Uri_CREATE_DECODE_EXTRA_INFO: int +Uri_CREATE_NO_DECODE_EXTRA_INFO: int +Uri_CREATE_CRACK_UNKNOWN_SCHEMES: int +Uri_CREATE_NO_CRACK_UNKNOWN_SCHEMES: int +Uri_CREATE_PRE_PROCESS_HTML_URI: int +Uri_CREATE_NO_PRE_PROCESS_HTML_URI: int +Uri_CREATE_IE_SETTINGS: int +Uri_CREATE_NO_IE_SETTINGS: int +Uri_CREATE_NO_ENCODE_FORBIDDEN_CHARACTERS: int +Uri_DISPLAY_NO_FRAGMENT: int +Uri_PUNYCODE_IDN_HOST: int +Uri_DISPLAY_IDN_HOST: int +Uri_ENCODING_USER_INFO_AND_PATH_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_USER_INFO_AND_PATH_IS_CP: int +Uri_ENCODING_HOST_IS_IDN: int +Uri_ENCODING_HOST_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_HOST_IS_PERCENT_ENCODED_CP: int +Uri_ENCODING_QUERY_AND_FRAGMENT_IS_PERCENT_ENCODED_UTF8: int +Uri_ENCODING_QUERY_AND_FRAGMENT_IS_CP: int +Uri_ENCODING_RFC: Incomplete +UriBuilder_USE_ORIGINAL_FLAGS: int +WININETINFO_OPTION_LOCK_HANDLE: int +URLOSTRM_USECACHEDCOPY_ONLY: int +URLOSTRM_USECACHEDCOPY: int +URLOSTRM_GETNEWESTVERSION: int +SET_FEATURE_ON_THREAD: int +SET_FEATURE_ON_PROCESS: int +SET_FEATURE_IN_REGISTRY: int +SET_FEATURE_ON_THREAD_LOCALMACHINE: int +SET_FEATURE_ON_THREAD_INTRANET: int +SET_FEATURE_ON_THREAD_TRUSTED: int +SET_FEATURE_ON_THREAD_INTERNET: int +SET_FEATURE_ON_THREAD_RESTRICTED: int +GET_FEATURE_FROM_THREAD: int +GET_FEATURE_FROM_PROCESS: int +GET_FEATURE_FROM_REGISTRY: int +GET_FEATURE_FROM_THREAD_LOCALMACHINE: int +GET_FEATURE_FROM_THREAD_INTRANET: int +GET_FEATURE_FROM_THREAD_TRUSTED: int +GET_FEATURE_FROM_THREAD_INTERNET: int +GET_FEATURE_FROM_THREAD_RESTRICTED: int +PROTOCOLFLAG_NO_PICS_CHECK: int +MUTZ_NOSAVEDFILECHECK: int +MUTZ_ISFILE: int +MUTZ_ACCEPT_WILDCARD_SCHEME: int +MUTZ_ENFORCERESTRICTED: int +MUTZ_RESERVED: int +MUTZ_REQUIRESAVEDFILECHECK: int +MUTZ_DONT_UNESCAPE: int +MUTZ_DONT_USE_CACHE: int +MUTZ_FORCE_INTRANET_FLAGS: int +MUTZ_IGNORE_ZONE_MAPPINGS: int +MAX_SIZE_SECURITY_ID: int +URLACTION_MIN: int +URLACTION_DOWNLOAD_MIN: int +URLACTION_DOWNLOAD_SIGNED_ACTIVEX: int +URLACTION_DOWNLOAD_UNSIGNED_ACTIVEX: int +URLACTION_DOWNLOAD_CURR_MAX: int +URLACTION_DOWNLOAD_MAX: int +URLACTION_ACTIVEX_MIN: int +URLACTION_ACTIVEX_RUN: int +URLPOLICY_ACTIVEX_CHECK_LIST: int +URLACTION_ACTIVEX_OVERRIDE_OBJECT_SAFETY: int +URLACTION_ACTIVEX_OVERRIDE_DATA_SAFETY: int +URLACTION_ACTIVEX_OVERRIDE_SCRIPT_SAFETY: int +URLACTION_SCRIPT_OVERRIDE_SAFETY: int +URLACTION_ACTIVEX_CONFIRM_NOOBJECTSAFETY: int +URLACTION_ACTIVEX_TREATASUNTRUSTED: int +URLACTION_ACTIVEX_NO_WEBOC_SCRIPT: int +URLACTION_ACTIVEX_OVERRIDE_REPURPOSEDETECTION: int +URLACTION_ACTIVEX_OVERRIDE_OPTIN: int +URLACTION_ACTIVEX_SCRIPTLET_RUN: int +URLACTION_ACTIVEX_DYNSRC_VIDEO_AND_ANIMATION: int +URLACTION_ACTIVEX_CURR_MAX: int +URLACTION_ACTIVEX_MAX: int +URLACTION_SCRIPT_MIN: int +URLACTION_SCRIPT_RUN: int +URLACTION_SCRIPT_JAVA_USE: int +URLACTION_SCRIPT_SAFE_ACTIVEX: int +URLACTION_CROSS_DOMAIN_DATA: int +URLACTION_SCRIPT_PASTE: int +URLACTION_ALLOW_XDOMAIN_SUBFRAME_RESIZE: int +URLACTION_SCRIPT_CURR_MAX: int +URLACTION_SCRIPT_MAX: int +URLACTION_HTML_MIN: int +URLACTION_HTML_SUBMIT_FORMS: int +URLACTION_HTML_SUBMIT_FORMS_FROM: int +URLACTION_HTML_SUBMIT_FORMS_TO: int +URLACTION_HTML_FONT_DOWNLOAD: int +URLACTION_HTML_JAVA_RUN: int +URLACTION_HTML_USERDATA_SAVE: int +URLACTION_HTML_SUBFRAME_NAVIGATE: int +URLACTION_HTML_META_REFRESH: int +URLACTION_HTML_MIXED_CONTENT: int +URLACTION_HTML_INCLUDE_FILE_PATH: int +URLACTION_HTML_MAX: int +URLACTION_SHELL_MIN: int +URLACTION_SHELL_INSTALL_DTITEMS: int +URLACTION_SHELL_MOVE_OR_COPY: int +URLACTION_SHELL_FILE_DOWNLOAD: int +URLACTION_SHELL_VERB: int +URLACTION_SHELL_WEBVIEW_VERB: int +URLACTION_SHELL_SHELLEXECUTE: int +URLACTION_SHELL_EXECUTE_HIGHRISK: int +URLACTION_SHELL_EXECUTE_MODRISK: int +URLACTION_SHELL_EXECUTE_LOWRISK: int +URLACTION_SHELL_POPUPMGR: int +URLACTION_SHELL_RTF_OBJECTS_LOAD: int +URLACTION_SHELL_ENHANCED_DRAGDROP_SECURITY: int +URLACTION_SHELL_EXTENSIONSECURITY: int +URLACTION_SHELL_SECURE_DRAGSOURCE: int +URLACTION_SHELL_CURR_MAX: int +URLACTION_SHELL_MAX: int +URLACTION_NETWORK_MIN: int +URLACTION_CREDENTIALS_USE: int +URLPOLICY_CREDENTIALS_SILENT_LOGON_OK: int +URLPOLICY_CREDENTIALS_MUST_PROMPT_USER: int +URLPOLICY_CREDENTIALS_CONDITIONAL_PROMPT: int +URLPOLICY_CREDENTIALS_ANONYMOUS_ONLY: int +URLACTION_AUTHENTICATE_CLIENT: int +URLPOLICY_AUTHENTICATE_CLEARTEXT_OK: int +URLPOLICY_AUTHENTICATE_CHALLENGE_RESPONSE: int +URLPOLICY_AUTHENTICATE_MUTUAL_ONLY: int +URLACTION_COOKIES: int +URLACTION_COOKIES_SESSION: int +URLACTION_CLIENT_CERT_PROMPT: int +URLACTION_COOKIES_THIRD_PARTY: int +URLACTION_COOKIES_SESSION_THIRD_PARTY: int +URLACTION_COOKIES_ENABLED: int +URLACTION_NETWORK_CURR_MAX: int +URLACTION_NETWORK_MAX: int +URLACTION_JAVA_MIN: int +URLACTION_JAVA_PERMISSIONS: int +URLPOLICY_JAVA_PROHIBIT: int +URLPOLICY_JAVA_HIGH: int +URLPOLICY_JAVA_MEDIUM: int +URLPOLICY_JAVA_LOW: int +URLPOLICY_JAVA_CUSTOM: int +URLACTION_JAVA_CURR_MAX: int +URLACTION_JAVA_MAX: int +URLACTION_INFODELIVERY_MIN: int +URLACTION_INFODELIVERY_NO_ADDING_CHANNELS: int +URLACTION_INFODELIVERY_NO_EDITING_CHANNELS: int +URLACTION_INFODELIVERY_NO_REMOVING_CHANNELS: int +URLACTION_INFODELIVERY_NO_ADDING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_EDITING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_REMOVING_SUBSCRIPTIONS: int +URLACTION_INFODELIVERY_NO_CHANNEL_LOGGING: int +URLACTION_INFODELIVERY_CURR_MAX: int +URLACTION_INFODELIVERY_MAX: int +URLACTION_CHANNEL_SOFTDIST_MIN: int +URLACTION_CHANNEL_SOFTDIST_PERMISSIONS: int +URLPOLICY_CHANNEL_SOFTDIST_PROHIBIT: int +URLPOLICY_CHANNEL_SOFTDIST_PRECACHE: int +URLPOLICY_CHANNEL_SOFTDIST_AUTOINSTALL: int +URLACTION_CHANNEL_SOFTDIST_MAX: int +URLACTION_BEHAVIOR_MIN: int +URLACTION_BEHAVIOR_RUN: int +URLPOLICY_BEHAVIOR_CHECK_LIST: int +URLACTION_FEATURE_MIN: int +URLACTION_FEATURE_MIME_SNIFFING: int +URLACTION_FEATURE_ZONE_ELEVATION: int +URLACTION_FEATURE_WINDOW_RESTRICTIONS: int +URLACTION_FEATURE_SCRIPT_STATUS_BAR: int +URLACTION_FEATURE_FORCE_ADDR_AND_STATUS: int +URLACTION_FEATURE_BLOCK_INPUT_PROMPTS: int +URLACTION_AUTOMATIC_DOWNLOAD_UI_MIN: int +URLACTION_AUTOMATIC_DOWNLOAD_UI: int +URLACTION_AUTOMATIC_ACTIVEX_UI: int +URLACTION_ALLOW_RESTRICTEDPROTOCOLS: int +URLACTION_ALLOW_APEVALUATION: int +URLACTION_WINDOWS_BROWSER_APPLICATIONS: int +URLACTION_XPS_DOCUMENTS: int +URLACTION_LOOSE_XAML: int +URLACTION_LOWRIGHTS: int +URLACTION_WINFX_SETUP: int +URLPOLICY_ALLOW: int +URLPOLICY_QUERY: int +URLPOLICY_DISALLOW: int +URLPOLICY_NOTIFY_ON_ALLOW: int +URLPOLICY_NOTIFY_ON_DISALLOW: int +URLPOLICY_LOG_ON_ALLOW: int +URLPOLICY_LOG_ON_DISALLOW: int +URLPOLICY_MASK_PERMISSIONS: int +URLPOLICY_DONTCHECKDLGBOX: int +URLZONE_ESC_FLAG: int +SECURITY_IE_STATE_GREEN: int +SECURITY_IE_STATE_RED: int +SOFTDIST_FLAG_USAGE_EMAIL: int +SOFTDIST_FLAG_USAGE_PRECACHE: int +SOFTDIST_FLAG_USAGE_AUTOINSTALL: int +SOFTDIST_FLAG_DELETE_SUBSCRIPTION: int +SOFTDIST_ADSTATE_NONE: int +SOFTDIST_ADSTATE_AVAILABLE: int +SOFTDIST_ADSTATE_DOWNLOADED: int +SOFTDIST_ADSTATE_INSTALLED: int +CONFIRMSAFETYACTION_LOADOBJECT: int diff --git a/stubs/pywin32/win32comext/internet/internet.pyi b/stubs/pywin32/win32comext/internet/internet.pyi new file mode 100644 index 000000000000..60d0fff7aa9f --- /dev/null +++ b/stubs/pywin32/win32comext/internet/internet.pyi @@ -0,0 +1,51 @@ +import _win32typing + +def CoInternetCreateSecurityManager(reserved, /) -> _win32typing.PyIInternetSecurityManager: ... +def CoInternetIsFeatureEnabled(flags, /): ... +def CoInternetSetFeatureEnabled(flags, enable, /): ... + +FEATURE_ADDON_MANAGEMENT: int +FEATURE_BEHAVIORS: int +FEATURE_DISABLE_MK_PROTOCOL: int +FEATURE_ENTRY_COUNT: int +FEATURE_GET_URL_DOM_FILEPATH_UNENCODED: int +FEATURE_HTTP_USERNAME_PASSWORD_DISABLE: int +FEATURE_LOCALMACHINE_LOCKDOWN: int +FEATURE_MIME_HANDLING: int +FEATURE_MIME_SNIFFING: int +FEATURE_OBJECT_CACHING: int +FEATURE_PROTOCOL_LOCKDOWN: int +FEATURE_RESTRICT_ACTIVEXINSTALL: int +FEATURE_RESTRICT_FILEDOWNLOAD: int +FEATURE_SAFE_BINDTOOBJECT: int +FEATURE_SECURITYBAND: int +FEATURE_UNC_SAVEDFILECHECK: int +FEATURE_VALIDATE_NAVIGATE_URL: int +FEATURE_WEBOC_POPUPMANAGEMENT: int +FEATURE_WINDOW_RESTRICTIONS: int +FEATURE_ZONE_ELEVATION: int +GET_FEATURE_FROM_PROCESS: int +GET_FEATURE_FROM_REGISTRY: int +GET_FEATURE_FROM_THREAD: int +GET_FEATURE_FROM_THREAD_INTERNET: int +GET_FEATURE_FROM_THREAD_INTRANET: int +GET_FEATURE_FROM_THREAD_LOCALMACHINE: int +GET_FEATURE_FROM_THREAD_RESTRICTED: int +GET_FEATURE_FROM_THREAD_TRUSTED: int +IID_IDocHostUIHandler: _win32typing.PyIID +IID_IHTMLOMWindowServices: _win32typing.PyIID +IID_IInternetBindInfo: _win32typing.PyIID +IID_IInternetPriority: _win32typing.PyIID +IID_IInternetProtocol: _win32typing.PyIID +IID_IInternetProtocolInfo: _win32typing.PyIID +IID_IInternetProtocolRoot: _win32typing.PyIID +IID_IInternetProtocolSink: _win32typing.PyIID +IID_IInternetSecurityManager: _win32typing.PyIID +SET_FEATURE_IN_REGISTRY: int +SET_FEATURE_ON_PROCESS: int +SET_FEATURE_ON_THREAD: int +SET_FEATURE_ON_THREAD_INTERNET: int +SET_FEATURE_ON_THREAD_INTRANET: int +SET_FEATURE_ON_THREAD_LOCALMACHINE: int +SET_FEATURE_ON_THREAD_RESTRICTED: int +SET_FEATURE_ON_THREAD_TRUSTED: int diff --git a/stubs/pywin32/win32comext/mapi/__init__.pyi b/stubs/pywin32/win32comext/mapi/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/mapi/emsabtags.pyi b/stubs/pywin32/win32comext/mapi/emsabtags.pyi new file mode 100644 index 000000000000..59cfd215c362 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/emsabtags.pyi @@ -0,0 +1,865 @@ +from _typeshed import Incomplete + +from win32comext.mapi.mapitags import ( + PROP_TAG as PROP_TAG, + PT_APPTIME as PT_APPTIME, + PT_BINARY as PT_BINARY, + PT_BOOLEAN as PT_BOOLEAN, + PT_CLSID as PT_CLSID, + PT_CURRENCY as PT_CURRENCY, + PT_DOUBLE as PT_DOUBLE, + PT_ERROR as PT_ERROR, + PT_FLOAT as PT_FLOAT, + PT_I2 as PT_I2, + PT_I4 as PT_I4, + PT_I8 as PT_I8, + PT_LONG as PT_LONG, + PT_LONGLONG as PT_LONGLONG, + PT_MV_APPTIME as PT_MV_APPTIME, + PT_MV_BINARY as PT_MV_BINARY, + PT_MV_CLSID as PT_MV_CLSID, + PT_MV_CURRENCY as PT_MV_CURRENCY, + PT_MV_DOUBLE as PT_MV_DOUBLE, + PT_MV_FLOAT as PT_MV_FLOAT, + PT_MV_I2 as PT_MV_I2, + PT_MV_I4 as PT_MV_I4, + PT_MV_I8 as PT_MV_I8, + PT_MV_LONG as PT_MV_LONG, + PT_MV_LONGLONG as PT_MV_LONGLONG, + PT_MV_R4 as PT_MV_R4, + PT_MV_R8 as PT_MV_R8, + PT_MV_SHORT as PT_MV_SHORT, + PT_MV_STRING8 as PT_MV_STRING8, + PT_MV_SYSTIME as PT_MV_SYSTIME, + PT_MV_TSTRING as PT_MV_TSTRING, + PT_MV_UNICODE as PT_MV_UNICODE, + PT_NULL as PT_NULL, + PT_OBJECT as PT_OBJECT, + PT_R4 as PT_R4, + PT_SHORT as PT_SHORT, + PT_STRING8 as PT_STRING8, + PT_SYSTIME as PT_SYSTIME, + PT_TSTRING as PT_TSTRING, + PT_UNICODE as PT_UNICODE, + PT_UNSPECIFIED as PT_UNSPECIFIED, +) + +AB_SHOW_PHANTOMS: int +AB_SHOW_OTHERS: int +EMS_AB_ADDRESS_LOOKUP: int +PR_EMS_AB_SERVER: Incomplete +PR_EMS_AB_SERVER_A: Incomplete +PR_EMS_AB_SERVER_W: Incomplete +PR_EMS_AB_CONTAINERID: Incomplete +PR_EMS_AB_DOS_ENTRYID: Incomplete +PR_EMS_AB_PARENT_ENTRYID: Incomplete +PR_EMS_AB_IS_MASTER: Incomplete +PR_EMS_AB_OBJECT_OID: Incomplete +PR_EMS_AB_HIERARCHY_PATH: Incomplete +PR_EMS_AB_HIERARCHY_PATH_A: Incomplete +PR_EMS_AB_HIERARCHY_PATH_W: Incomplete +PR_EMS_AB_CHILD_RDNS: Incomplete +MIN_EMS_AB_CONSTRUCTED_PROP_ID: int +PR_EMS_AB_OTHER_RECIPS: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE_A: Incomplete +PR_EMS_AB_DISPLAY_NAME_PRINTABLE_W: Incomplete +PR_EMS_AB_ACCESS_CATEGORY: Incomplete +PR_EMS_AB_ACTIVATION_SCHEDULE: Incomplete +PR_EMS_AB_ACTIVATION_STYLE: Incomplete +PR_EMS_AB_ADDRESS_ENTRY_DISPLAY_TABLE: Incomplete +PR_EMS_AB_ADDRESS_ENTRY_DISPLAY_TABLE_MSDOS: Incomplete +PR_EMS_AB_ADDRESS_SYNTAX: Incomplete +PR_EMS_AB_ADDRESS_TYPE: Incomplete +PR_EMS_AB_ADDRESS_TYPE_A: Incomplete +PR_EMS_AB_ADDRESS_TYPE_W: Incomplete +PR_EMS_AB_ADMD: Incomplete +PR_EMS_AB_ADMD_A: Incomplete +PR_EMS_AB_ADMD_W: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION_A: Incomplete +PR_EMS_AB_ADMIN_DESCRIPTION_W: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME_A: Incomplete +PR_EMS_AB_ADMIN_DISPLAY_NAME_W: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL_A: Incomplete +PR_EMS_AB_ADMIN_EXTENSION_DLL_W: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_A: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_W: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_O: Incomplete +PR_EMS_AB_ALIASED_OBJECT_NAME_T: Incomplete +PR_EMS_AB_ALT_RECIPIENT: Incomplete +PR_EMS_AB_ALT_RECIPIENT_A: Incomplete +PR_EMS_AB_ALT_RECIPIENT_W: Incomplete +PR_EMS_AB_ALT_RECIPIENT_O: Incomplete +PR_EMS_AB_ALT_RECIPIENT_T: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_A: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_W: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_O: Incomplete +PR_EMS_AB_ALT_RECIPIENT_BL_T: Incomplete +PR_EMS_AB_ANCESTOR_ID: Incomplete +PR_EMS_AB_ASSOC_NT_ACCOUNT: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_A: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_W: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_O: Incomplete +PR_EMS_AB_ASSOC_REMOTE_DXA_T: Incomplete +PR_EMS_AB_ASSOCIATION_LIFETIME: Incomplete +PR_EMS_AB_AUTH_ORIG_BL: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_A: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_W: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_O: Incomplete +PR_EMS_AB_AUTH_ORIG_BL_T: Incomplete +PR_EMS_AB_AUTHORITY_REVOCATION_LIST: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN_A: Incomplete +PR_EMS_AB_AUTHORIZED_DOMAIN_W: Incomplete +PR_EMS_AB_AUTHORIZED_PASSWORD: Incomplete +PR_EMS_AB_AUTHORIZED_USER: Incomplete +PR_EMS_AB_AUTHORIZED_USER_A: Incomplete +PR_EMS_AB_AUTHORIZED_USER_W: Incomplete +PR_EMS_AB_AUTOREPLY: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE_A: Incomplete +PR_EMS_AB_AUTOREPLY_MESSAGE_W: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT_A: Incomplete +PR_EMS_AB_AUTOREPLY_SUBJECT_W: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_A: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_W: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_O: Incomplete +PR_EMS_AB_BRIDGEHEAD_SERVERS_T: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY_A: Incomplete +PR_EMS_AB_BUSINESS_CATEGORY_W: Incomplete +PR_EMS_AB_BUSINESS_ROLES: Incomplete +PR_EMS_AB_CA_CERTIFICATE: Incomplete +PR_EMS_AB_CAN_CREATE_PF: Incomplete +PR_EMS_AB_CAN_CREATE_PF_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_BL_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_T: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_A: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_W: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_O: Incomplete +PR_EMS_AB_CAN_CREATE_PF_DL_BL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_BL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_T: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_A: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_W: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_O: Incomplete +PR_EMS_AB_CAN_NOT_CREATE_PF_DL_BL_T: Incomplete +PR_EMS_AB_CAN_PRESERVE_DNS: Incomplete +PR_EMS_AB_CERTIFICATE_REVOCATION_LIST: Incomplete +PR_EMS_AB_CLOCK_ALERT_OFFSET: Incomplete +PR_EMS_AB_CLOCK_ALERT_REPAIR: Incomplete +PR_EMS_AB_CLOCK_WARNING_OFFSET: Incomplete +PR_EMS_AB_CLOCK_WARNING_REPAIR: Incomplete +PR_EMS_AB_COMPUTER_NAME: Incomplete +PR_EMS_AB_COMPUTER_NAME_A: Incomplete +PR_EMS_AB_COMPUTER_NAME_W: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS_A: Incomplete +PR_EMS_AB_CONNECTED_DOMAINS_W: Incomplete +PR_EMS_AB_CONTAINER_INFO: Incomplete +PR_EMS_AB_COST: Incomplete +PR_EMS_AB_COUNTRY_NAME: Incomplete +PR_EMS_AB_COUNTRY_NAME_A: Incomplete +PR_EMS_AB_COUNTRY_NAME_W: Incomplete +PR_EMS_AB_CROSS_CERTIFICATE_PAIR: Incomplete +PR_EMS_AB_DELIV_CONT_LENGTH: Incomplete +PR_EMS_AB_DELIV_EITS: Incomplete +PR_EMS_AB_DELIV_EXT_CONT_TYPES: Incomplete +PR_EMS_AB_DELIVER_AND_REDIRECT: Incomplete +PR_EMS_AB_DELIVERY_MECHANISM: Incomplete +PR_EMS_AB_DESCRIPTION: Incomplete +PR_EMS_AB_DESCRIPTION_A: Incomplete +PR_EMS_AB_DESCRIPTION_W: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR_A: Incomplete +PR_EMS_AB_DESTINATION_INDICATOR_W: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY_A: Incomplete +PR_EMS_AB_DIAGNOSTIC_REG_KEY_W: Incomplete +PR_EMS_AB_DISPLAY_NAME_OVERRIDE: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_A: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_W: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_O: Incomplete +PR_EMS_AB_DL_MEM_REJECT_PERMS_BL_T: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_A: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_W: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_O: Incomplete +PR_EMS_AB_DL_MEM_SUBMIT_PERMS_BL_T: Incomplete +PR_EMS_AB_DL_MEMBER_RULE: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_A: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_W: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_O: Incomplete +PR_EMS_AB_DOMAIN_DEF_ALT_RECIP_T: Incomplete +PR_EMS_AB_DOMAIN_NAME: Incomplete +PR_EMS_AB_DOMAIN_NAME_A: Incomplete +PR_EMS_AB_DOMAIN_NAME_W: Incomplete +PR_EMS_AB_DSA_SIGNATURE: Incomplete +PR_EMS_AB_DXA_ADMIN_COPY: Incomplete +PR_EMS_AB_DXA_ADMIN_FORWARD: Incomplete +PR_EMS_AB_DXA_ADMIN_UPDATE: Incomplete +PR_EMS_AB_DXA_APPEND_REQCN: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_A: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_W: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_O: Incomplete +PR_EMS_AB_DXA_CONF_CONTAINER_LIST_T: Incomplete +PR_EMS_AB_DXA_CONF_REQ_TIME: Incomplete +PR_EMS_AB_DXA_CONF_SEQ: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_A: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_W: Incomplete +PR_EMS_AB_DXA_CONF_SEQ_USN: Incomplete +PR_EMS_AB_DXA_EXCHANGE_OPTIONS: Incomplete +PR_EMS_AB_DXA_EXPORT_NOW: Incomplete +PR_EMS_AB_DXA_FLAGS: Incomplete +PR_EMS_AB_DXA_IMP_SEQ: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_A: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_W: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_IMP_SEQ_USN: Incomplete +PR_EMS_AB_DXA_IMPORT_NOW: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP_A: Incomplete +PR_EMS_AB_DXA_IN_TEMPLATE_MAP_W: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_A: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_W: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_O: Incomplete +PR_EMS_AB_DXA_LOCAL_ADMIN_T: Incomplete +PR_EMS_AB_DXA_LOGGING_LEVEL: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE_A: Incomplete +PR_EMS_AB_DXA_NATIVE_ADDRESS_TYPE_W: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP_A: Incomplete +PR_EMS_AB_DXA_OUT_TEMPLATE_MAP_W: Incomplete +PR_EMS_AB_DXA_PASSWORD: Incomplete +PR_EMS_AB_DXA_PASSWORD_A: Incomplete +PR_EMS_AB_DXA_PASSWORD_W: Incomplete +PR_EMS_AB_DXA_PREV_EXCHANGE_OPTIONS: Incomplete +PR_EMS_AB_DXA_PREV_EXPORT_NATIVE_ONLY: Incomplete +PR_EMS_AB_DXA_PREV_IN_EXCHANGE_SENSITIVITY: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_A: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_W: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_O: Incomplete +PR_EMS_AB_DXA_PREV_REMOTE_ENTRIES_T: Incomplete +PR_EMS_AB_DXA_PREV_REPLICATION_SENSITIVITY: Incomplete +PR_EMS_AB_DXA_PREV_TEMPLATE_OPTIONS: Incomplete +PR_EMS_AB_DXA_PREV_TYPES: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP_A: Incomplete +PR_EMS_AB_DXA_RECIPIENT_CP_W: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_A: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_W: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_O: Incomplete +PR_EMS_AB_DXA_REMOTE_CLIENT_T: Incomplete +PR_EMS_AB_DXA_REQ_SEQ: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_A: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_W: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_REQ_SEQ_USN: Incomplete +PR_EMS_AB_DXA_REQNAME: Incomplete +PR_EMS_AB_DXA_REQNAME_A: Incomplete +PR_EMS_AB_DXA_REQNAME_W: Incomplete +PR_EMS_AB_DXA_SVR_SEQ: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_A: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_W: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_TIME: Incomplete +PR_EMS_AB_DXA_SVR_SEQ_USN: Incomplete +PR_EMS_AB_DXA_TASK: Incomplete +PR_EMS_AB_DXA_TEMPLATE_OPTIONS: Incomplete +PR_EMS_AB_DXA_TEMPLATE_TIMESTAMP: Incomplete +PR_EMS_AB_DXA_TYPES: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_A: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_W: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_O: Incomplete +PR_EMS_AB_DXA_UNCONF_CONTAINER_LIST_T: Incomplete +PR_EMS_AB_ENABLED_PROTOCOLS: Incomplete +PR_EMS_AB_ENCAPSULATION_METHOD: Incomplete +PR_EMS_AB_ENCRYPT: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_NA_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_LIST_OTHER_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_NA_W: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER_A: Incomplete +PR_EMS_AB_ENCRYPT_ALG_SELECTED_OTHER_W: Incomplete +PR_EMS_AB_EXPAND_DLS_LOCALLY: Incomplete +PR_EMS_AB_EXPIRATION_TIME: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_A: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_W: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_O: Incomplete +PR_EMS_AB_EXPORT_CONTAINERS_T: Incomplete +PR_EMS_AB_EXPORT_CUSTOM_RECIPIENTS: Incomplete +PR_EMS_AB_EXTENDED_CHARS_ALLOWED: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_1_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_10_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_2_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_3_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_4_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_5_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_6_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_7_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_8_W: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9_A: Incomplete +PR_EMS_AB_EXTENSION_ATTRIBUTE_9_W: Incomplete +PR_EMS_AB_EXTENSION_DATA: Incomplete +PR_EMS_AB_EXTENSION_NAME: Incomplete +PR_EMS_AB_EXTENSION_NAME_A: Incomplete +PR_EMS_AB_EXTENSION_NAME_W: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED_A: Incomplete +PR_EMS_AB_EXTENSION_NAME_INHERITED_W: Incomplete +PR_EMS_AB_FACSIMILE_TELEPHONE_NUMBER: Incomplete +PR_EMS_AB_FILE_VERSION: Incomplete +PR_EMS_AB_FILTER_LOCAL_ADDRESSES: Incomplete +PR_EMS_AB_FOLDER_PATHNAME: Incomplete +PR_EMS_AB_FOLDER_PATHNAME_A: Incomplete +PR_EMS_AB_FOLDER_PATHNAME_W: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_A: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_W: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_O: Incomplete +PR_EMS_AB_FOLDERS_CONTAINER_T: Incomplete +PR_EMS_AB_GARBAGE_COLL_PERIOD: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED_A: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_CRED_W: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG_A: Incomplete +PR_EMS_AB_GATEWAY_LOCAL_DESIG_W: Incomplete +PR_EMS_AB_GATEWAY_PROXY: Incomplete +PR_EMS_AB_GATEWAY_PROXY_A: Incomplete +PR_EMS_AB_GATEWAY_PROXY_W: Incomplete +PR_EMS_AB_GATEWAY_ROUTING_TREE: Incomplete +PR_EMS_AB_GWART_LAST_MODIFIED: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_A: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_W: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_O: Incomplete +PR_EMS_AB_HAS_FULL_REPLICA_NCS_T: Incomplete +PR_EMS_AB_HAS_MASTER_NCS: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_A: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_W: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_O: Incomplete +PR_EMS_AB_HAS_MASTER_NCS_T: Incomplete +PR_EMS_AB_HELP_DATA16: Incomplete +PR_EMS_AB_HELP_DATA32: Incomplete +PR_EMS_AB_HELP_FILE_NAME: Incomplete +PR_EMS_AB_HELP_FILE_NAME_A: Incomplete +PR_EMS_AB_HELP_FILE_NAME_W: Incomplete +PR_EMS_AB_HEURISTICS: Incomplete +PR_EMS_AB_HIDE_DL_MEMBERSHIP: Incomplete +PR_EMS_AB_HIDE_FROM_ADDRESS_BOOK: Incomplete +PR_EMS_AB_HOME_MDB: Incomplete +PR_EMS_AB_HOME_MDB_A: Incomplete +PR_EMS_AB_HOME_MDB_W: Incomplete +PR_EMS_AB_HOME_MDB_O: Incomplete +PR_EMS_AB_HOME_MDB_T: Incomplete +PR_EMS_AB_HOME_MDB_BL: Incomplete +PR_EMS_AB_HOME_MDB_BL_A: Incomplete +PR_EMS_AB_HOME_MDB_BL_W: Incomplete +PR_EMS_AB_HOME_MDB_BL_O: Incomplete +PR_EMS_AB_HOME_MDB_BL_T: Incomplete +PR_EMS_AB_HOME_MTA: Incomplete +PR_EMS_AB_HOME_MTA_A: Incomplete +PR_EMS_AB_HOME_MTA_W: Incomplete +PR_EMS_AB_HOME_MTA_O: Incomplete +PR_EMS_AB_HOME_MTA_T: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_A: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_W: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_O: Incomplete +PR_EMS_AB_HOME_PUBLIC_SERVER_T: Incomplete +PR_EMS_AB_IMPORT_CONTAINER: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_A: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_W: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_O: Incomplete +PR_EMS_AB_IMPORT_CONTAINER_T: Incomplete +PR_EMS_AB_IMPORT_SENSITIVITY: Incomplete +PR_EMS_AB_IMPORTED_FROM: Incomplete +PR_EMS_AB_IMPORTED_FROM_A: Incomplete +PR_EMS_AB_IMPORTED_FROM_W: Incomplete +PR_EMS_AB_INBOUND_SITES: Incomplete +PR_EMS_AB_INBOUND_SITES_A: Incomplete +PR_EMS_AB_INBOUND_SITES_W: Incomplete +PR_EMS_AB_INBOUND_SITES_O: Incomplete +PR_EMS_AB_INBOUND_SITES_T: Incomplete +PR_EMS_AB_INSTANCE_TYPE: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER_A: Incomplete +PR_EMS_AB_INTERNATIONAL_ISDN_NUMBER_W: Incomplete +PR_EMS_AB_INVOCATION_ID: Incomplete +PR_EMS_AB_IS_DELETED: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_A: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_W: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_O: Incomplete +PR_EMS_AB_IS_MEMBER_OF_DL_T: Incomplete +PR_EMS_AB_IS_SINGLE_VALUED: Incomplete +PR_EMS_AB_KCC_STATUS: Incomplete +PR_EMS_AB_KM_SERVER: Incomplete +PR_EMS_AB_KM_SERVER_A: Incomplete +PR_EMS_AB_KM_SERVER_W: Incomplete +PR_EMS_AB_KM_SERVER_O: Incomplete +PR_EMS_AB_KM_SERVER_T: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION_A: Incomplete +PR_EMS_AB_KNOWLEDGE_INFORMATION_W: Incomplete +PR_EMS_AB_LANGUAGE: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME_A: Incomplete +PR_EMS_AB_LDAP_DISPLAY_NAME_W: Incomplete +PR_EMS_AB_LINE_WRAP: Incomplete +PR_EMS_AB_LINK_ID: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_A: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_W: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS_A: Incomplete +PR_EMS_AB_LOCAL_BRIDGE_HEAD_ADDRESS_W: Incomplete +PR_EMS_AB_LOCAL_INITIAL_TURN: Incomplete +PR_EMS_AB_LOCAL_SCOPE: Incomplete +PR_EMS_AB_LOCAL_SCOPE_A: Incomplete +PR_EMS_AB_LOCAL_SCOPE_W: Incomplete +PR_EMS_AB_LOCAL_SCOPE_O: Incomplete +PR_EMS_AB_LOCAL_SCOPE_T: Incomplete +PR_EMS_AB_LOG_FILENAME: Incomplete +PR_EMS_AB_LOG_FILENAME_A: Incomplete +PR_EMS_AB_LOG_FILENAME_W: Incomplete +PR_EMS_AB_LOG_ROLLOVER_INTERVAL: Incomplete +PR_EMS_AB_MAINTAIN_AUTOREPLY_HISTORY: Incomplete +PR_EMS_AB_MANAGER: Incomplete +PR_EMS_AB_MANAGER_A: Incomplete +PR_EMS_AB_MANAGER_W: Incomplete +PR_EMS_AB_MANAGER_O: Incomplete +PR_EMS_AB_MANAGER_T: Incomplete +PR_EMS_AB_MAPI_DISPLAY_TYPE: Incomplete +PR_EMS_AB_MAPI_ID: Incomplete +PR_EMS_AB_MAXIMUM_OBJECT_ID: Incomplete +PR_EMS_AB_MDB_BACKOFF_INTERVAL: Incomplete +PR_EMS_AB_MDB_MSG_TIME_OUT_PERIOD: Incomplete +PR_EMS_AB_MDB_OVER_QUOTA_LIMIT: Incomplete +PR_EMS_AB_MDB_STORAGE_QUOTA: Incomplete +PR_EMS_AB_MDB_UNREAD_LIMIT: Incomplete +PR_EMS_AB_MDB_USE_DEFAULTS: Incomplete +PR_EMS_AB_MEMBER: Incomplete +PR_EMS_AB_MEMBER_A: Incomplete +PR_EMS_AB_MEMBER_W: Incomplete +PR_EMS_AB_MEMBER_O: Incomplete +PR_EMS_AB_MEMBER_T: Incomplete +PR_EMS_AB_MESSAGE_TRACKING_ENABLED: Incomplete +PR_EMS_AB_MONITOR_CLOCK: Incomplete +PR_EMS_AB_MONITOR_SERVERS: Incomplete +PR_EMS_AB_MONITOR_SERVICES: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_A: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_W: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_O: Incomplete +PR_EMS_AB_MONITORED_CONFIGURATIONS_T: Incomplete +PR_EMS_AB_MONITORED_SERVERS: Incomplete +PR_EMS_AB_MONITORED_SERVERS_A: Incomplete +PR_EMS_AB_MONITORED_SERVERS_W: Incomplete +PR_EMS_AB_MONITORED_SERVERS_O: Incomplete +PR_EMS_AB_MONITORED_SERVERS_T: Incomplete +PR_EMS_AB_MONITORED_SERVICES: Incomplete +PR_EMS_AB_MONITORED_SERVICES_A: Incomplete +PR_EMS_AB_MONITORED_SERVICES_W: Incomplete +PR_EMS_AB_MONITORING_ALERT_DELAY: Incomplete +PR_EMS_AB_MONITORING_ALERT_UNITS: Incomplete +PR_EMS_AB_MONITORING_AVAILABILITY_STYLE: Incomplete +PR_EMS_AB_MONITORING_AVAILABILITY_WINDOW: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_A: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_W: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_O: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_MAIL_T: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_A: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_W: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_O: Incomplete +PR_EMS_AB_MONITORING_CACHED_VIA_RPC_T: Incomplete +PR_EMS_AB_MONITORING_ESCALATION_PROCEDURE: Incomplete +PR_EMS_AB_MONITORING_HOTSITE_POLL_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_HOTSITE_POLL_UNITS: Incomplete +PR_EMS_AB_MONITORING_MAIL_UPDATE_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_MAIL_UPDATE_UNITS: Incomplete +PR_EMS_AB_MONITORING_NORMAL_POLL_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_NORMAL_POLL_UNITS: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_A: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_W: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_O: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_T: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_A: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_W: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_O: Incomplete +PR_EMS_AB_MONITORING_RECIPIENTS_NDR_T: Incomplete +PR_EMS_AB_MONITORING_RPC_UPDATE_INTERVAL: Incomplete +PR_EMS_AB_MONITORING_RPC_UPDATE_UNITS: Incomplete +PR_EMS_AB_MONITORING_WARNING_DELAY: Incomplete +PR_EMS_AB_MONITORING_WARNING_UNITS: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED_A: Incomplete +PR_EMS_AB_MTA_LOCAL_CRED_W: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG_A: Incomplete +PR_EMS_AB_MTA_LOCAL_DESIG_W: Incomplete +PR_EMS_AB_N_ADDRESS: Incomplete +PR_EMS_AB_N_ADDRESS_TYPE: Incomplete +PR_EMS_AB_NETWORK_ADDRESS: Incomplete +PR_EMS_AB_NETWORK_ADDRESS_A: Incomplete +PR_EMS_AB_NETWORK_ADDRESS_W: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET_A: Incomplete +PR_EMS_AB_NNTP_CHARACTER_SET_W: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT_A: Incomplete +PR_EMS_AB_NNTP_CONTENT_FORMAT_W: Incomplete +PR_EMS_AB_NT_MACHINE_NAME: Incomplete +PR_EMS_AB_NT_MACHINE_NAME_A: Incomplete +PR_EMS_AB_NT_MACHINE_NAME_W: Incomplete +PR_EMS_AB_NT_SECURITY_DESCRIPTOR: Incomplete +PR_EMS_AB_NUM_OF_OPEN_RETRIES: Incomplete +PR_EMS_AB_NUM_OF_TRANSFER_RETRIES: Incomplete +PR_EMS_AB_OBJ_DIST_NAME: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_A: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_W: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_O: Incomplete +PR_EMS_AB_OBJ_DIST_NAME_T: Incomplete +PR_EMS_AB_OBJECT_CLASS_CATEGORY: Incomplete +PR_EMS_AB_OBJECT_VERSION: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_A: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_W: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_O: Incomplete +PR_EMS_AB_OFF_LINE_AB_CONTAINERS_T: Incomplete +PR_EMS_AB_OFF_LINE_AB_SCHEDULE: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_A: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_W: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_O: Incomplete +PR_EMS_AB_OFF_LINE_AB_SERVER_T: Incomplete +PR_EMS_AB_OFF_LINE_AB_STYLE: Incomplete +PR_EMS_AB_OID_TYPE: Incomplete +PR_EMS_AB_OM_OBJECT_CLASS: Incomplete +PR_EMS_AB_OM_SYNTAX: Incomplete +PR_EMS_AB_OOF_REPLY_TO_ORIGINATOR: Incomplete +PR_EMS_AB_OPEN_RETRY_INTERVAL: Incomplete +PR_EMS_AB_ORGANIZATION_NAME: Incomplete +PR_EMS_AB_ORGANIZATION_NAME_A: Incomplete +PR_EMS_AB_ORGANIZATION_NAME_W: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME_A: Incomplete +PR_EMS_AB_ORGANIZATIONAL_UNIT_NAME_W: Incomplete +PR_EMS_AB_ORIGINAL_DISPLAY_TABLE: Incomplete +PR_EMS_AB_ORIGINAL_DISPLAY_TABLE_MSDOS: Incomplete +PR_EMS_AB_OUTBOUND_SITES: Incomplete +PR_EMS_AB_OUTBOUND_SITES_A: Incomplete +PR_EMS_AB_OUTBOUND_SITES_W: Incomplete +PR_EMS_AB_OUTBOUND_SITES_O: Incomplete +PR_EMS_AB_OUTBOUND_SITES_T: Incomplete +PR_EMS_AB_OWNER: Incomplete +PR_EMS_AB_OWNER_A: Incomplete +PR_EMS_AB_OWNER_W: Incomplete +PR_EMS_AB_OWNER_O: Incomplete +PR_EMS_AB_OWNER_T: Incomplete +PR_EMS_AB_OWNER_BL: Incomplete +PR_EMS_AB_OWNER_BL_A: Incomplete +PR_EMS_AB_OWNER_BL_W: Incomplete +PR_EMS_AB_OWNER_BL_O: Incomplete +PR_EMS_AB_OWNER_BL_T: Incomplete +PR_EMS_AB_P_SELECTOR: Incomplete +PR_EMS_AB_P_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_PER_MSG_DIALOG_DISPLAY_TABLE: Incomplete +PR_EMS_AB_PER_RECIP_DIALOG_DISPLAY_TABLE: Incomplete +PR_EMS_AB_PERIOD_REP_SYNC_TIMES: Incomplete +PR_EMS_AB_PERIOD_REPL_STAGGER: Incomplete +PR_EMS_AB_PF_CONTACTS: Incomplete +PR_EMS_AB_PF_CONTACTS_A: Incomplete +PR_EMS_AB_PF_CONTACTS_W: Incomplete +PR_EMS_AB_PF_CONTACTS_O: Incomplete +PR_EMS_AB_PF_CONTACTS_T: Incomplete +PR_EMS_AB_POP_CHARACTER_SET: Incomplete +PR_EMS_AB_POP_CHARACTER_SET_A: Incomplete +PR_EMS_AB_POP_CHARACTER_SET_W: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT_A: Incomplete +PR_EMS_AB_POP_CONTENT_FORMAT_W: Incomplete +PR_EMS_AB_POSTAL_ADDRESS: Incomplete +PR_EMS_AB_PREFERRED_DELIVERY_METHOD: Incomplete +PR_EMS_AB_PRMD: Incomplete +PR_EMS_AB_PRMD_A: Incomplete +PR_EMS_AB_PRMD_W: Incomplete +PR_EMS_AB_PROXY_ADDRESSES: Incomplete +PR_EMS_AB_PROXY_ADDRESSES_A: Incomplete +PR_EMS_AB_PROXY_ADDRESSES_W: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL_A: Incomplete +PR_EMS_AB_PROXY_GENERATOR_DLL_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_A: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_O: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_T: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_A: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_W: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_O: Incomplete +PR_EMS_AB_PUBLIC_DELEGATES_BL_T: Incomplete +PR_EMS_AB_QUOTA_NOTIFICATION_SCHEDULE: Incomplete +PR_EMS_AB_QUOTA_NOTIFICATION_STYLE: Incomplete +PR_EMS_AB_RANGE_LOWER: Incomplete +PR_EMS_AB_RANGE_UPPER: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER_A: Incomplete +PR_EMS_AB_RAS_CALLBACK_NUMBER_W: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER_A: Incomplete +PR_EMS_AB_RAS_PHONE_NUMBER_W: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME_A: Incomplete +PR_EMS_AB_RAS_PHONEBOOK_ENTRY_NAME_W: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME_A: Incomplete +PR_EMS_AB_RAS_REMOTE_SRVR_NAME_W: Incomplete +PR_EMS_AB_REGISTERED_ADDRESS: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_A: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_W: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS_A: Incomplete +PR_EMS_AB_REMOTE_BRIDGE_HEAD_ADDRESS_W: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_A: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_W: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_O: Incomplete +PR_EMS_AB_REMOTE_OUT_BH_SERVER_T: Incomplete +PR_EMS_AB_REMOTE_SITE: Incomplete +PR_EMS_AB_REMOTE_SITE_A: Incomplete +PR_EMS_AB_REMOTE_SITE_W: Incomplete +PR_EMS_AB_REMOTE_SITE_O: Incomplete +PR_EMS_AB_REMOTE_SITE_T: Incomplete +PR_EMS_AB_REPLICATION_MAIL_MSG_SIZE: Incomplete +PR_EMS_AB_REPLICATION_SENSITIVITY: Incomplete +PR_EMS_AB_REPLICATION_STAGGER: Incomplete +PR_EMS_AB_REPORT_TO_ORIGINATOR: Incomplete +PR_EMS_AB_REPORT_TO_OWNER: Incomplete +PR_EMS_AB_REPORTS: Incomplete +PR_EMS_AB_REPORTS_A: Incomplete +PR_EMS_AB_REPORTS_W: Incomplete +PR_EMS_AB_REPORTS_O: Incomplete +PR_EMS_AB_REPORTS_T: Incomplete +PR_EMS_AB_REQ_SEQ: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_A: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_W: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_O: Incomplete +PR_EMS_AB_RESPONSIBLE_LOCAL_DXA_T: Incomplete +PR_EMS_AB_RID_SERVER: Incomplete +PR_EMS_AB_RID_SERVER_A: Incomplete +PR_EMS_AB_RID_SERVER_W: Incomplete +PR_EMS_AB_RID_SERVER_O: Incomplete +PR_EMS_AB_RID_SERVER_T: Incomplete +PR_EMS_AB_ROLE_OCCUPANT: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_A: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_W: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_O: Incomplete +PR_EMS_AB_ROLE_OCCUPANT_T: Incomplete +PR_EMS_AB_ROUTING_LIST: Incomplete +PR_EMS_AB_ROUTING_LIST_A: Incomplete +PR_EMS_AB_ROUTING_LIST_W: Incomplete +PR_EMS_AB_RTS_CHECKPOINT_SIZE: Incomplete +PR_EMS_AB_RTS_RECOVERY_TIMEOUT: Incomplete +PR_EMS_AB_RTS_WINDOW_SIZE: Incomplete +PR_EMS_AB_RUNS_ON: Incomplete +PR_EMS_AB_RUNS_ON_A: Incomplete +PR_EMS_AB_RUNS_ON_W: Incomplete +PR_EMS_AB_RUNS_ON_O: Incomplete +PR_EMS_AB_RUNS_ON_T: Incomplete +PR_EMS_AB_S_SELECTOR: Incomplete +PR_EMS_AB_S_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_SCHEMA_FLAGS: Incomplete +PR_EMS_AB_SCHEMA_VERSION: Incomplete +PR_EMS_AB_SEARCH_FLAGS: Incomplete +PR_EMS_AB_SEARCH_GUIDE: Incomplete +PR_EMS_AB_SECURITY_PROTOCOL: Incomplete +PR_EMS_AB_SEE_ALSO: Incomplete +PR_EMS_AB_SEE_ALSO_A: Incomplete +PR_EMS_AB_SEE_ALSO_W: Incomplete +PR_EMS_AB_SEE_ALSO_O: Incomplete +PR_EMS_AB_SEE_ALSO_T: Incomplete +PR_EMS_AB_SERIAL_NUMBER: Incomplete +PR_EMS_AB_SERIAL_NUMBER_A: Incomplete +PR_EMS_AB_SERIAL_NUMBER_W: Incomplete +PR_EMS_AB_SERVICE_ACTION_FIRST: Incomplete +PR_EMS_AB_SERVICE_ACTION_OTHER: Incomplete +PR_EMS_AB_SERVICE_ACTION_SECOND: Incomplete +PR_EMS_AB_SERVICE_RESTART_DELAY: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE_A: Incomplete +PR_EMS_AB_SERVICE_RESTART_MESSAGE_W: Incomplete +PR_EMS_AB_SESSION_DISCONNECT_TIMER: Incomplete +PR_EMS_AB_SITE_AFFINITY: Incomplete +PR_EMS_AB_SITE_AFFINITY_A: Incomplete +PR_EMS_AB_SITE_AFFINITY_W: Incomplete +PR_EMS_AB_SITE_FOLDER_GUID: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_A: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_W: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_O: Incomplete +PR_EMS_AB_SITE_FOLDER_SERVER_T: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE_A: Incomplete +PR_EMS_AB_SITE_PROXY_SPACE_W: Incomplete +PR_EMS_AB_SPACE_LAST_COMPUTED: Incomplete +PR_EMS_AB_STREET_ADDRESS: Incomplete +PR_EMS_AB_STREET_ADDRESS_A: Incomplete +PR_EMS_AB_STREET_ADDRESS_W: Incomplete +PR_EMS_AB_SUB_REFS: Incomplete +PR_EMS_AB_SUB_REFS_A: Incomplete +PR_EMS_AB_SUB_REFS_W: Incomplete +PR_EMS_AB_SUB_REFS_O: Incomplete +PR_EMS_AB_SUB_REFS_T: Incomplete +PR_EMS_AB_SUB_SITE: Incomplete +PR_EMS_AB_SUB_SITE_A: Incomplete +PR_EMS_AB_SUB_SITE_W: Incomplete +PR_EMS_AB_SUBMISSION_CONT_LENGTH: Incomplete +PR_EMS_AB_SUPPORTED_APPLICATION_CONTEXT: Incomplete +PR_EMS_AB_SUPPORTING_STACK: Incomplete +PR_EMS_AB_SUPPORTING_STACK_A: Incomplete +PR_EMS_AB_SUPPORTING_STACK_W: Incomplete +PR_EMS_AB_SUPPORTING_STACK_O: Incomplete +PR_EMS_AB_SUPPORTING_STACK_T: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_A: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_W: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_O: Incomplete +PR_EMS_AB_SUPPORTING_STACK_BL_T: Incomplete +PR_EMS_AB_T_SELECTOR: Incomplete +PR_EMS_AB_T_SELECTOR_INBOUND: Incomplete +PR_EMS_AB_TARGET_ADDRESS: Incomplete +PR_EMS_AB_TARGET_ADDRESS_A: Incomplete +PR_EMS_AB_TARGET_ADDRESS_W: Incomplete +PR_EMS_AB_TARGET_MTAS: Incomplete +PR_EMS_AB_TARGET_MTAS_A: Incomplete +PR_EMS_AB_TARGET_MTAS_W: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER_A: Incomplete +PR_EMS_AB_TELEPHONE_NUMBER_W: Incomplete +PR_EMS_AB_TELETEX_TERMINAL_IDENTIFIER: Incomplete +PR_EMS_AB_TEMP_ASSOC_THRESHOLD: Incomplete +PR_EMS_AB_TOMBSTONE_LIFETIME: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME_A: Incomplete +PR_EMS_AB_TRACKING_LOG_PATH_NAME_W: Incomplete +PR_EMS_AB_TRANS_RETRY_MINS: Incomplete +PR_EMS_AB_TRANS_TIMEOUT_MINS: Incomplete +PR_EMS_AB_TRANSFER_RETRY_INTERVAL: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_NON_URGENT: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_NORMAL: Incomplete +PR_EMS_AB_TRANSFER_TIMEOUT_URGENT: Incomplete +PR_EMS_AB_TRANSLATION_TABLE_USED: Incomplete +PR_EMS_AB_TRANSPORT_EXPEDITED_DATA: Incomplete +PR_EMS_AB_TRUST_LEVEL: Incomplete +PR_EMS_AB_TURN_REQUEST_THRESHOLD: Incomplete +PR_EMS_AB_TWO_WAY_ALTERNATE_FACILITY: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_A: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_W: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_O: Incomplete +PR_EMS_AB_UNAUTH_ORIG_BL_T: Incomplete +PR_EMS_AB_USE_SERVER_VALUES: Incomplete +PR_EMS_AB_USER_PASSWORD: Incomplete +PR_EMS_AB_USN_CHANGED: Incomplete +PR_EMS_AB_USN_CREATED: Incomplete +PR_EMS_AB_USN_DSA_LAST_OBJ_REMOVED: Incomplete +PR_EMS_AB_USN_INTERSITE: Incomplete +PR_EMS_AB_USN_LAST_OBJ_REM: Incomplete +PR_EMS_AB_USN_SOURCE: Incomplete +PR_EMS_AB_WWW_HOME_PAGE: Incomplete +PR_EMS_AB_WWW_HOME_PAGE_A: Incomplete +PR_EMS_AB_WWW_HOME_PAGE_W: Incomplete +PR_EMS_AB_X121_ADDRESS: Incomplete +PR_EMS_AB_X121_ADDRESS_A: Incomplete +PR_EMS_AB_X121_ADDRESS_W: Incomplete +PR_EMS_AB_X25_CALL_USER_DATA_INCOMING: Incomplete +PR_EMS_AB_X25_CALL_USER_DATA_OUTGOING: Incomplete +PR_EMS_AB_X25_FACILITIES_DATA_INCOMING: Incomplete +PR_EMS_AB_X25_FACILITIES_DATA_OUTGOING: Incomplete +PR_EMS_AB_X25_LEASED_LINE_PORT: Incomplete +PR_EMS_AB_X25_LEASED_OR_SWITCHED: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE_A: Incomplete +PR_EMS_AB_X25_REMOTE_MTA_PHONE_W: Incomplete +PR_EMS_AB_X400_ATTACHMENT_TYPE: Incomplete +PR_EMS_AB_X400_SELECTOR_SYNTAX: Incomplete +PR_EMS_AB_X500_ACCESS_CONTROL_LIST: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_NON_URGENT: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_NORMAL: Incomplete +PR_EMS_AB_XMIT_TIMEOUT_URGENT: Incomplete diff --git a/stubs/pywin32/win32comext/mapi/exchange.pyi b/stubs/pywin32/win32comext/mapi/exchange.pyi new file mode 100644 index 000000000000..ac1a9741be47 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/exchange.pyi @@ -0,0 +1,9 @@ +import _win32typing + +OPENSTORE_HOME_LOGON: int +OPENSTORE_OVERRIDE_HOME_MDB: int +OPENSTORE_PUBLIC: int +OPENSTORE_TAKE_OWNERSHIP: int +OPENSTORE_USE_ADMIN_PRIVILEGE: int +IID_IExchangeManageStore: _win32typing.PyIID +IID_IExchangeManageStoreEx: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/mapi/mapi.pyi b/stubs/pywin32/win32comext/mapi/mapi.pyi new file mode 100644 index 000000000000..f6895c629079 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapi.pyi @@ -0,0 +1,342 @@ +from _typeshed import Incomplete + +import _win32typing + +def HexFromBin(val: str, /) -> str: ... +def BinFromHex(val: str, /) -> str: ... +def MAPIUninitialize() -> None: ... +def MAPIInitialize(init: _win32typing.MAPIINIT_0, /) -> None: ... +def MAPILogonEx(uiParam, profileName: str, password: str | None = ..., flags=..., /) -> _win32typing.PyIMAPISession: ... +def MAPIAdminProfiles(fFlags, /) -> _win32typing.PyIProfAdmin: ... +def HrQueryAllRows( + table: _win32typing.PyIMAPITable, + properties: _win32typing.PySPropTagArray, + restrictions: _win32typing.PySRestriction, + sortOrderSet: _win32typing.PySSortOrderSet, + rowsMax, + /, +): ... +def RTFSync(message: _win32typing.PyIMessage, flags, /): ... +def WrapCompressedRTFStream(stream: _win32typing.PyIStream, flags, /) -> _win32typing.PyIStream: ... +def WrapCompressedRTFStreamEx(stream: _win32typing.PyIStream, wcsinfo, /) -> tuple[_win32typing.PyIStream, Incomplete]: ... +def OpenIMsgSession(): ... +def CloseIMsgSession() -> None: ... +def OpenIMsgOnIStg( + session, + support, + storage: _win32typing.PyIStorage, + callback: Incomplete | None = ..., + callbackData: int = ..., + flags: int = ..., + /, +) -> _win32typing.PyIMessage: ... +def RTFStreamToHTML(The_stream_to_read_the_uncompressed_RTF_from: _win32typing.PyIStream, /) -> None: ... +def OpenStreamOnFile(filename: str, flags: int = ..., prefix: str | None = ..., /) -> _win32typing.PyIStream: ... +def OpenStreamOnFileW(filename, flags: int = ..., prefix: Incomplete | None = ..., /) -> _win32typing.PyIStream: ... +def HrGetOneProp(prop: _win32typing.PyIMAPIProp, propTag, /): ... +def HrSetOneProp(prop: _win32typing.PyIMAPIProp, propValue: _win32typing.PySPropValue, /): ... +def HrAllocAdviseSink(callback, context, /): ... +def HrThisThreadAdviseSink(_object, /): ... +def HrDispatchNotifications(*args): ... # incomplete +def MAPIUIDFromBinary(sz: str | None, /): ... + +AB_NO_DIALOG: int +ATTACH_BY_REF_ONLY: int +ATTACH_BY_REF_RESOLVE: int +ATTACH_BY_REFERENCE: int +ATTACH_BY_VALUE: int +ATTACH_EMBEDDED_MSG: int +ATTACH_OLE: int +BMR_EQZ: int +BMR_NEZ: int +BOOKMARK_BEGINNING: int +BOOKMARK_CURRENT: int +BOOKMARK_END: int +CCSF_8BITHEADERS: int +CCSF_EMBEDDED_MESSAGE: int +CCSF_INCLUDE_BCC: int +CCSF_NO_MSGID: int +CCSF_NOHEADERS: int +CCSF_PLAIN_TEXT_ONLY: int +CCSF_PRESERVE_SOURCE: int +CCSF_SMTP: int +CCSF_USE_RTF: int +CCSF_USE_TNEF: int +CLEAR_NRN_PENDING: int +CLEAR_READ_FLAG: int +CLEAR_RN_PENDING: int +CONVENIENT_DEPTH: int +DEL_FOLDERS: int +DEL_MESSAGES: int +DELETE_HARD_DELETE: int +DIR_BACKWARD: int +FL_FULLSTRING: int +FL_IGNORECASE: int +FL_IGNORENONSPACE: int +FL_LOOSE: int +FL_PREFIX: int +FL_SUBSTRING: int +FLUSH_ASYNC_OK: int +FLUSH_DOWNLOAD: int +FLUSH_FORCE: int +FLUSH_NO_UI: int +FLUSH_UPLOAD: int +fnevCriticalError: int +fnevExtended: int +fnevNewMail: int +fnevObjectCopied: int +fnevObjectCreated: int +fnevObjectDeleted: int +fnevObjectModified: int +fnevObjectMoved: int +fnevReservedForMapi: int +fnevSearchComplete: int +fnevStatusObjectModified: int +fnevTableModified: int +FOLDER_DIALOG: int +FOLDER_GENERIC: int +FOLDER_SEARCH: int +FORCE_SAVE: int +GENERATE_RECEIPT_ONLY: int +KEEP_OPEN_READONLY: int +KEEP_OPEN_READWRITE: int +LOGOFF_ABORT: int +LOGOFF_COMPLETE: int +LOGOFF_INBOUND: int +LOGOFF_NO_WAIT: int +LOGOFF_ORDERLY: int +LOGOFF_OUTBOUND: int +LOGOFF_OUTBOUND_QUEUE: int +LOGOFF_PURGE: int +LOGOFF_QUIET: int +MAIL_E_NAMENOTFOUND: int +MAPI_ABCONT: int +MAPI_ADDRBOOK: int +MAPI_ALLOW_OTHERS: int +MAPI_ASSOCIATED: int +MAPI_ATTACH: int +MAPI_BCC: int +MAPI_BEST_ACCESS: int +MAPI_CC: int +MAPI_CREATE: int +MAPI_DEFAULT_SERVICES: int +MAPI_DEFERRED_ERRORS: int +MAPI_DIALOG: int +MAPI_E_ACCOUNT_DISABLED: int +MAPI_E_AMBIGUOUS_RECIP: int +MAPI_E_BAD_CHARWIDTH: int +MAPI_E_BAD_COLUMN: int +MAPI_E_BAD_VALUE: int +MAPI_E_BUSY: int +MAPI_E_CALL_FAILED: int +MAPI_E_CANCEL: int +MAPI_E_COLLISION: int +MAPI_E_COMPUTED: int +MAPI_E_CORRUPT_DATA: int +MAPI_E_CORRUPT_STORE: int +MAPI_E_DECLINE_COPY: int +MAPI_E_DISK_ERROR: int +MAPI_E_END_OF_SESSION: int +MAPI_E_EXTENDED_ERROR: int +MAPI_E_FAILONEPROVIDER: int +MAPI_E_FOLDER_CYCLE: int +MAPI_E_HAS_FOLDERS: int +MAPI_E_HAS_MESSAGES: int +MAPI_E_INTERFACE_NOT_SUPPORTED: int +MAPI_E_INVALID_ACCESS_TIME: int +MAPI_E_INVALID_BOOKMARK: int +MAPI_E_INVALID_ENTRYID: int +MAPI_E_INVALID_OBJECT: int +MAPI_E_INVALID_PARAMETER: int +MAPI_E_INVALID_TYPE: int +MAPI_E_INVALID_WORKSTATION_ACCOUNT: int +MAPI_E_LOCKID_LIMIT: int +MAPI_E_LOGON_FAILED: int +MAPI_E_MISSING_REQUIRED_COLUMN: int +MAPI_E_NAMED_PROP_QUOTA_EXCEEDED: int +MAPI_E_NETWORK_ERROR: int +MAPI_E_NO_ACCESS: int +MAPI_E_NO_RECIPIENTS: int +MAPI_E_NO_SUPPORT: int +MAPI_E_NO_SUPPRESS: int +MAPI_E_NON_STANDARD: int +MAPI_E_NOT_ENOUGH_DISK: int +MAPI_E_NOT_ENOUGH_MEMORY: int +MAPI_E_NOT_ENOUGH_RESOURCES: int +MAPI_E_NOT_FOUND: int +MAPI_E_NOT_IN_QUEUE: int +MAPI_E_NOT_INITIALIZED: int +MAPI_E_NOT_ME: int +MAPI_E_OBJECT_CHANGED: int +MAPI_E_OBJECT_DELETED: int +MAPI_E_OFFLINE: int +MAPI_E_PASSWORD_CHANGE_REQUIRED: int +MAPI_E_PASSWORD_EXPIRED: int +MAPI_E_PROFILE_DELETED: int +MAPI_E_RECONNECTED: int +MAPI_E_SESSION_LIMIT: int +MAPI_E_STORE_FULL: int +MAPI_E_STRING_TOO_LONG: int +MAPI_E_SUBMITTED: int +MAPI_E_TABLE_EMPTY: int +MAPI_E_TABLE_TOO_BIG: int +MAPI_E_TIMEOUT: int +MAPI_E_TOO_BIG: int +MAPI_E_TOO_COMPLEX: int +MAPI_E_TYPE_NO_SUPPORT: int +MAPI_E_UNABLE_TO_ABORT: int +MAPI_E_UNABLE_TO_COMPLETE: int +MAPI_E_UNCONFIGURED: int +MAPI_E_UNEXPECTED_ID: int +MAPI_E_UNEXPECTED_TYPE: int +MAPI_E_UNKNOWN_CPID: int +MAPI_E_UNKNOWN_ENTRYID: int +MAPI_E_UNKNOWN_FLAGS: int +MAPI_E_UNKNOWN_LCID: int +MAPI_E_USER_CANCEL: int +MAPI_E_VERSION: int +MAPI_E_WAIT: int +MAPI_EXPLICIT_PROFILE: int +MAPI_EXTENDED: int +MAPI_FOLDER: int +MAPI_FORCE_ACCESS: int +MAPI_FORCE_DOWNLOAD: int +MAPI_FORMINFO: int +MAPI_INIT_VERSION: int +MAPI_LOGON_UI: int +MAPI_MAILUSER: int +MAPI_MESSAGE: int +MAPI_MODIFY: int +MAPI_MOVE: int +MAPI_MULTITHREAD_NOTIFICATIONS: int +MAPI_NATIVE_BODY: int +MAPI_NATIVE_BODY_TYPE_HTML: int +MAPI_NATIVE_BODY_TYPE_PLAINTEXT: int +MAPI_NATIVE_BODY_TYPE_RTF: int +MAPI_NEW_SESSION: int +MAPI_NO_IDS: int +MAPI_NO_MAIL: int +MAPI_NO_STRINGS: int +MAPI_NOREPLACE: int +MAPI_NT_SERVICE: int +MAPI_P1: int +MAPI_PASSWORD_UI: int +MAPI_PROFSECT: int +MAPI_SERVICE_UI_ALWAYS: int +MAPI_SESSION: int +MAPI_STATUS: int +MAPI_STORE: int +MAPI_SUBMITTED: int +MAPI_TIMEOUT_SHORT: int +MAPI_TO: int +MAPI_UNICODE: int +MAPI_USE_DEFAULT: int +MAPI_W_APPROX_COUNT: int +MAPI_W_CANCEL_MESSAGE: int +MAPI_W_ERRORS_RETURNED: int +MAPI_W_NO_SERVICE: int +MAPI_W_PARTIAL_COMPLETION: int +MAPI_W_POSITION_CHANGED: int +MDB_NO_DIALOG: int +MDB_NO_MAIL: int +MDB_TEMPORARY: int +MDB_WRITE: int +MESSAGE_DIALOG: int +MODRECIP_ADD: int +MODRECIP_MODIFY: int +MODRECIP_REMOVE: int +NO_ATTACHMENT: int +OPEN_IF_EXISTS: int +PSTF_BEST_ENCRYPTION: int +PSTF_COMPRESSABLE_ENCRYPTION: int +PSTF_NO_ENCRYPTION: int +RELOP_EQ: int +RELOP_GE: int +RELOP_GT: int +RELOP_LE: int +RELOP_LT: int +RELOP_NE: int +RELOP_RE: int +RES_AND: int +RES_BITMASK: int +RES_COMMENT: int +RES_COMPAREPROPS: int +RES_CONTENT: int +RES_EXIST: int +RES_NOT: int +RES_OR: int +RES_PROPERTY: int +RES_SIZE: int +RES_SUBRESTRICTION: int +RTF_SYNC_BODY_CHANGED: int +RTF_SYNC_RTF_CHANGED: int +SERVICE_UI_ALLOWED: int +SERVICE_UI_ALWAYS: int +SHOW_SOFT_DELETES: int +SOF_UNIQUEFILENAME: int +STATUS_DEFAULT_STORE: int +STATUS_FLUSH_QUEUES: int +STATUS_INBOUND_FLUSH: int +STATUS_OUTBOUND_FLUSH: int +SUPPRESS_RECEIPT: int +TABLE_CHANGED: int +TABLE_ERROR: int +TABLE_RELOAD: int +TABLE_RESTRICT_DONE: int +TABLE_ROW_ADDED: int +TABLE_ROW_DELETED: int +TABLE_ROW_MODIFIED: int +TABLE_SETCOL_DONE: int +TABLE_SORT_ASCEND: int +TABLE_SORT_COMBINE: int +TABLE_SORT_DESCEND: int +TABLE_SORT_DONE: int +TBL_ALL_COLUMNS: int +TBL_ASYNC: int +TBL_BATCH: int +CLSID_IConverterSession: _win32typing.PyIID +CLSID_MailMessage: _win32typing.PyIID +IID_IABContainer: _win32typing.PyIID +IID_IAddrBook: _win32typing.PyIID +IID_IAttachment: _win32typing.PyIID +IID_IConverterSession: _win32typing.PyIID +IID_IDistList: _win32typing.PyIID +IID_IMAPIAdviseSink: _win32typing.PyIID +IID_IMAPIContainer: _win32typing.PyIID +IID_IMAPIFolder: _win32typing.PyIID +IID_IMAPIProp: _win32typing.PyIID +IID_IMAPISession: _win32typing.PyIID +IID_IMAPIStatus: _win32typing.PyIID +IID_IMAPITable: _win32typing.PyIID +IID_IMailUser: _win32typing.PyIID +IID_IMessage: _win32typing.PyIID +IID_IMsgServiceAdmin: _win32typing.PyIID +IID_IMsgServiceAdmin2: _win32typing.PyIID +IID_IMsgStore: _win32typing.PyIID +IID_IProfAdmin: _win32typing.PyIID +IID_IProfSect: _win32typing.PyIID +IID_IProviderAdmin: _win32typing.PyIID +MAPI_DISTLIST: int +MSPST_UID_PROVIDER: _win32typing.PyIID +PSETID_Address: _win32typing.PyIID +PSETID_AirSync: _win32typing.PyIID +PSETID_Appointment: _win32typing.PyIID +PSETID_Common: _win32typing.PyIID +PSETID_Log: _win32typing.PyIID +PSETID_Meeting: _win32typing.PyIID +PSETID_Messaging: _win32typing.PyIID +PSETID_Note: _win32typing.PyIID +PSETID_PostRss: _win32typing.PyIID +PSETID_Remote: _win32typing.PyIID +PSETID_Report: _win32typing.PyIID +PSETID_Sharing: _win32typing.PyIID +PSETID_Task: _win32typing.PyIID +PSETID_UnifiedMessaging: _win32typing.PyIID +PS_INTERNET_HEADERS: _win32typing.PyIID +PS_MAPI: _win32typing.PyIID +PS_PUBLIC_STRINGS: _win32typing.PyIID +PS_ROUTING_ADDRTYPE: _win32typing.PyIID +PS_ROUTING_DISPLAY_NAME: _win32typing.PyIID +PS_ROUTING_EMAIL_ADDRESSES: _win32typing.PyIID +PS_ROUTING_ENTRYID: _win32typing.PyIID +PS_ROUTING_SEARCH_KEY: _win32typing.PyIID diff --git a/stubs/pywin32/win32comext/mapi/mapitags.pyi b/stubs/pywin32/win32comext/mapi/mapitags.pyi new file mode 100644 index 000000000000..660f492e9e57 --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapitags.pyi @@ -0,0 +1,991 @@ +MV_FLAG: int +PT_UNSPECIFIED: int +PT_NULL: int +PT_I2: int +PT_LONG: int +PT_R4: int +PT_DOUBLE: int +PT_CURRENCY: int +PT_APPTIME: int +PT_ERROR: int +PT_BOOLEAN: int +PT_OBJECT: int +PT_I8: int +PT_STRING8: int +PT_UNICODE: int +PT_SYSTIME: int +PT_CLSID: int +PT_BINARY: int +PT_SHORT: int +PT_I4: int +PT_FLOAT: int +PT_R8: int +PT_LONGLONG: int +PT_MV_I2: int +PT_MV_LONG: int +PT_MV_R4: int +PT_MV_DOUBLE: int +PT_MV_CURRENCY: int +PT_MV_APPTIME: int +PT_MV_SYSTIME: int +PT_MV_STRING8: int +PT_MV_BINARY: int +PT_MV_UNICODE: int +PT_MV_CLSID: int +PT_MV_I8: int +PT_MV_SHORT: int +PT_MV_I4: int +PT_MV_FLOAT: int +PT_MV_R8: int +PT_MV_LONGLONG: int +PT_TSTRING: int +PT_MV_TSTRING: int +PROP_TYPE_MASK: int + +def PROP_TYPE(ulPropTag: int) -> int: ... +def PROP_ID(ulPropTag: int) -> int: ... +def PROP_TAG(ulPropType: int, ulPropID: int) -> int: ... + +PROP_ID_NULL: int +PROP_ID_INVALID: int +PR_NULL: int +PR_ACKNOWLEDGEMENT_MODE: int +PR_ALTERNATE_RECIPIENT_ALLOWED: int +PR_AUTHORIZING_USERS: int +PR_AUTO_FORWARD_COMMENT: int +PR_AUTO_FORWARD_COMMENT_W: int +PR_AUTO_FORWARD_COMMENT_A: int +PR_AUTO_FORWARDED: int +PR_CONTENT_CONFIDENTIALITY_ALGORITHM_ID: int +PR_CONTENT_CORRELATOR: int +PR_CONTENT_IDENTIFIER: int +PR_CONTENT_IDENTIFIER_W: int +PR_CONTENT_IDENTIFIER_A: int +PR_CONTENT_LENGTH: int +PR_CONTENT_RETURN_REQUESTED: int +PR_CONVERSATION_KEY: int +PR_CONVERSION_EITS: int +PR_CONVERSION_WITH_LOSS_PROHIBITED: int +PR_CONVERTED_EITS: int +PR_DEFERRED_DELIVERY_TIME: int +PR_DELIVER_TIME: int +PR_DISCARD_REASON: int +PR_DISCLOSURE_OF_RECIPIENTS: int +PR_DL_EXPANSION_HISTORY: int +PR_DL_EXPANSION_PROHIBITED: int +PR_EXPIRY_TIME: int +PR_IMPLICIT_CONVERSION_PROHIBITED: int +PR_IMPORTANCE: int +PR_IPM_ID: int +PR_LATEST_DELIVERY_TIME: int +PR_MESSAGE_CLASS: int +PR_MESSAGE_CLASS_W: int +PR_MESSAGE_CLASS_A: int +PR_MESSAGE_DELIVERY_ID: int +PR_MESSAGE_SECURITY_LABEL: int +PR_OBSOLETED_IPMS: int +PR_ORIGINALLY_INTENDED_RECIPIENT_NAME: int +PR_ORIGINAL_EITS: int +PR_ORIGINATOR_CERTIFICATE: int +PR_ORIGINATOR_DELIVERY_REPORT_REQUESTED: int +PR_ORIGINATOR_RETURN_ADDRESS: int +PR_PARENT_KEY: int +PR_PRIORITY: int +PR_ORIGIN_CHECK: int +PR_PROOF_OF_SUBMISSION_REQUESTED: int +PR_READ_RECEIPT_REQUESTED: int +PR_RECEIPT_TIME: int +PR_RECIPIENT_REASSIGNMENT_PROHIBITED: int +PR_REDIRECTION_HISTORY: int +PR_RELATED_IPMS: int +PR_ORIGINAL_SENSITIVITY: int +PR_LANGUAGES: int +PR_LANGUAGES_W: int +PR_LANGUAGES_A: int +PR_REPLY_TIME: int +PR_REPORT_TAG: int +PR_REPORT_TIME: int +PR_RETURNED_IPM: int +PR_SECURITY: int +PR_INCOMPLETE_COPY: int +PR_SENSITIVITY: int +PR_SUBJECT: int +PR_SUBJECT_W: int +PR_SUBJECT_A: int +PR_SUBJECT_IPM: int +PR_CLIENT_SUBMIT_TIME: int +PR_REPORT_NAME: int +PR_REPORT_NAME_W: int +PR_REPORT_NAME_A: int +PR_SENT_REPRESENTING_SEARCH_KEY: int +PR_X400_CONTENT_TYPE: int +PR_SUBJECT_PREFIX: int +PR_SUBJECT_PREFIX_W: int +PR_SUBJECT_PREFIX_A: int +PR_NON_RECEIPT_REASON: int +PR_RECEIVED_BY_ENTRYID: int +PR_RECEIVED_BY_NAME: int +PR_RECEIVED_BY_NAME_W: int +PR_RECEIVED_BY_NAME_A: int +PR_SENT_REPRESENTING_ENTRYID: int +PR_SENT_REPRESENTING_NAME: int +PR_SENT_REPRESENTING_NAME_W: int +PR_SENT_REPRESENTING_NAME_A: int +PR_RCVD_REPRESENTING_ENTRYID: int +PR_RCVD_REPRESENTING_NAME: int +PR_RCVD_REPRESENTING_NAME_W: int +PR_RCVD_REPRESENTING_NAME_A: int +PR_REPORT_ENTRYID: int +PR_READ_RECEIPT_ENTRYID: int +PR_MESSAGE_SUBMISSION_ID: int +PR_PROVIDER_SUBMIT_TIME: int +PR_ORIGINAL_SUBJECT: int +PR_ORIGINAL_SUBJECT_W: int +PR_ORIGINAL_SUBJECT_A: int +PR_DISC_VAL: int +PR_ORIG_MESSAGE_CLASS: int +PR_ORIG_MESSAGE_CLASS_W: int +PR_ORIG_MESSAGE_CLASS_A: int +PR_ORIGINAL_AUTHOR_ENTRYID: int +PR_ORIGINAL_AUTHOR_NAME: int +PR_ORIGINAL_AUTHOR_NAME_W: int +PR_ORIGINAL_AUTHOR_NAME_A: int +PR_ORIGINAL_SUBMIT_TIME: int +PR_REPLY_RECIPIENT_ENTRIES: int +PR_REPLY_RECIPIENT_NAMES: int +PR_REPLY_RECIPIENT_NAMES_W: int +PR_REPLY_RECIPIENT_NAMES_A: int +PR_RECEIVED_BY_SEARCH_KEY: int +PR_RCVD_REPRESENTING_SEARCH_KEY: int +PR_READ_RECEIPT_SEARCH_KEY: int +PR_REPORT_SEARCH_KEY: int +PR_ORIGINAL_DELIVERY_TIME: int +PR_ORIGINAL_AUTHOR_SEARCH_KEY: int +PR_MESSAGE_TO_ME: int +PR_MESSAGE_CC_ME: int +PR_MESSAGE_RECIP_ME: int +PR_ORIGINAL_SENDER_NAME: int +PR_ORIGINAL_SENDER_NAME_W: int +PR_ORIGINAL_SENDER_NAME_A: int +PR_ORIGINAL_SENDER_ENTRYID: int +PR_ORIGINAL_SENDER_SEARCH_KEY: int +PR_ORIGINAL_SENT_REPRESENTING_NAME: int +PR_ORIGINAL_SENT_REPRESENTING_NAME_W: int +PR_ORIGINAL_SENT_REPRESENTING_NAME_A: int +PR_ORIGINAL_SENT_REPRESENTING_ENTRYID: int +PR_ORIGINAL_SENT_REPRESENTING_SEARCH_KEY: int +PR_START_DATE: int +PR_END_DATE: int +PR_OWNER_APPT_ID: int +PR_RESPONSE_REQUESTED: int +PR_SENT_REPRESENTING_ADDRTYPE: int +PR_SENT_REPRESENTING_ADDRTYPE_W: int +PR_SENT_REPRESENTING_ADDRTYPE_A: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS_W: int +PR_SENT_REPRESENTING_EMAIL_ADDRESS_A: int +PR_ORIGINAL_SENDER_ADDRTYPE: int +PR_ORIGINAL_SENDER_ADDRTYPE_W: int +PR_ORIGINAL_SENDER_ADDRTYPE_A: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS_W: int +PR_ORIGINAL_SENDER_EMAIL_ADDRESS_A: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE_W: int +PR_ORIGINAL_SENT_REPRESENTING_ADDRTYPE_A: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS_W: int +PR_ORIGINAL_SENT_REPRESENTING_EMAIL_ADDRESS_A: int +PR_CONVERSATION_TOPIC: int +PR_CONVERSATION_TOPIC_W: int +PR_CONVERSATION_TOPIC_A: int +PR_CONVERSATION_INDEX: int +PR_ORIGINAL_DISPLAY_BCC: int +PR_ORIGINAL_DISPLAY_BCC_W: int +PR_ORIGINAL_DISPLAY_BCC_A: int +PR_ORIGINAL_DISPLAY_CC: int +PR_ORIGINAL_DISPLAY_CC_W: int +PR_ORIGINAL_DISPLAY_CC_A: int +PR_ORIGINAL_DISPLAY_TO: int +PR_ORIGINAL_DISPLAY_TO_W: int +PR_ORIGINAL_DISPLAY_TO_A: int +PR_RECEIVED_BY_ADDRTYPE: int +PR_RECEIVED_BY_ADDRTYPE_W: int +PR_RECEIVED_BY_ADDRTYPE_A: int +PR_RECEIVED_BY_EMAIL_ADDRESS: int +PR_RECEIVED_BY_EMAIL_ADDRESS_W: int +PR_RECEIVED_BY_EMAIL_ADDRESS_A: int +PR_RCVD_REPRESENTING_ADDRTYPE: int +PR_RCVD_REPRESENTING_ADDRTYPE_W: int +PR_RCVD_REPRESENTING_ADDRTYPE_A: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS_W: int +PR_RCVD_REPRESENTING_EMAIL_ADDRESS_A: int +PR_ORIGINAL_AUTHOR_ADDRTYPE: int +PR_ORIGINAL_AUTHOR_ADDRTYPE_W: int +PR_ORIGINAL_AUTHOR_ADDRTYPE_A: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS_W: int +PR_ORIGINAL_AUTHOR_EMAIL_ADDRESS_A: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE_W: int +PR_ORIGINALLY_INTENDED_RECIP_ADDRTYPE_A: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS_W: int +PR_ORIGINALLY_INTENDED_RECIP_EMAIL_ADDRESS_A: int +PR_TRANSPORT_MESSAGE_HEADERS: int +PR_TRANSPORT_MESSAGE_HEADERS_W: int +PR_TRANSPORT_MESSAGE_HEADERS_A: int +PR_DELEGATION: int +PR_TNEF_CORRELATION_KEY: int +PR_BODY: int +PR_BODY_W: int +PR_BODY_A: int +PR_BODY_HTML: int +PR_BODY_HTML_W: int +PR_BODY_HTML_A: int +PR_REPORT_TEXT: int +PR_REPORT_TEXT_W: int +PR_REPORT_TEXT_A: int +PR_ORIGINATOR_AND_DL_EXPANSION_HISTORY: int +PR_REPORTING_DL_NAME: int +PR_REPORTING_MTA_CERTIFICATE: int +PR_RTF_SYNC_BODY_CRC: int +PR_RTF_SYNC_BODY_COUNT: int +PR_RTF_SYNC_BODY_TAG: int +PR_RTF_SYNC_BODY_TAG_W: int +PR_RTF_SYNC_BODY_TAG_A: int +PR_RTF_COMPRESSED: int +PR_RTF_SYNC_PREFIX_COUNT: int +PR_RTF_SYNC_TRAILING_COUNT: int +PR_ORIGINALLY_INTENDED_RECIP_ENTRYID: int +PR_CONTENT_INTEGRITY_CHECK: int +PR_EXPLICIT_CONVERSION: int +PR_IPM_RETURN_REQUESTED: int +PR_MESSAGE_TOKEN: int +PR_NDR_REASON_CODE: int +PR_NDR_DIAG_CODE: int +PR_NON_RECEIPT_NOTIFICATION_REQUESTED: int +PR_DELIVERY_POINT: int +PR_ORIGINATOR_NON_DELIVERY_REPORT_REQUESTED: int +PR_ORIGINATOR_REQUESTED_ALTERNATE_RECIPIENT: int +PR_PHYSICAL_DELIVERY_BUREAU_FAX_DELIVERY: int +PR_PHYSICAL_DELIVERY_MODE: int +PR_PHYSICAL_DELIVERY_REPORT_REQUEST: int +PR_PHYSICAL_FORWARDING_ADDRESS: int +PR_PHYSICAL_FORWARDING_ADDRESS_REQUESTED: int +PR_PHYSICAL_FORWARDING_PROHIBITED: int +PR_PHYSICAL_RENDITION_ATTRIBUTES: int +PR_PROOF_OF_DELIVERY: int +PR_PROOF_OF_DELIVERY_REQUESTED: int +PR_RECIPIENT_CERTIFICATE: int +PR_RECIPIENT_NUMBER_FOR_ADVICE: int +PR_RECIPIENT_NUMBER_FOR_ADVICE_W: int +PR_RECIPIENT_NUMBER_FOR_ADVICE_A: int +PR_RECIPIENT_TYPE: int +PR_REGISTERED_MAIL_TYPE: int +PR_REPLY_REQUESTED: int +PR_REQUESTED_DELIVERY_METHOD: int +PR_SENDER_ENTRYID: int +PR_SENDER_NAME: int +PR_SENDER_NAME_W: int +PR_SENDER_NAME_A: int +PR_SUPPLEMENTARY_INFO: int +PR_SUPPLEMENTARY_INFO_W: int +PR_SUPPLEMENTARY_INFO_A: int +PR_TYPE_OF_MTS_USER: int +PR_SENDER_SEARCH_KEY: int +PR_SENDER_ADDRTYPE: int +PR_SENDER_ADDRTYPE_W: int +PR_SENDER_ADDRTYPE_A: int +PR_SENDER_EMAIL_ADDRESS: int +PR_SENDER_EMAIL_ADDRESS_W: int +PR_SENDER_EMAIL_ADDRESS_A: int +PR_CURRENT_VERSION: int +PR_DELETE_AFTER_SUBMIT: int +PR_DISPLAY_BCC: int +PR_DISPLAY_BCC_W: int +PR_DISPLAY_BCC_A: int +PR_DISPLAY_CC: int +PR_DISPLAY_CC_W: int +PR_DISPLAY_CC_A: int +PR_DISPLAY_TO: int +PR_DISPLAY_TO_W: int +PR_DISPLAY_TO_A: int +PR_PARENT_DISPLAY: int +PR_PARENT_DISPLAY_W: int +PR_PARENT_DISPLAY_A: int +PR_MESSAGE_DELIVERY_TIME: int +PR_MESSAGE_FLAGS: int +PR_MESSAGE_SIZE: int +PR_PARENT_ENTRYID: int +PR_SENTMAIL_ENTRYID: int +PR_CORRELATE: int +PR_CORRELATE_MTSID: int +PR_DISCRETE_VALUES: int +PR_RESPONSIBILITY: int +PR_SPOOLER_STATUS: int +PR_TRANSPORT_STATUS: int +PR_MESSAGE_RECIPIENTS: int +PR_MESSAGE_ATTACHMENTS: int +PR_SUBMIT_FLAGS: int +PR_RECIPIENT_STATUS: int +PR_TRANSPORT_KEY: int +PR_MSG_STATUS: int +PR_MESSAGE_DOWNLOAD_TIME: int +PR_CREATION_VERSION: int +PR_MODIFY_VERSION: int +PR_HASATTACH: int +PR_BODY_CRC: int +PR_NORMALIZED_SUBJECT: int +PR_NORMALIZED_SUBJECT_W: int +PR_NORMALIZED_SUBJECT_A: int +PR_RTF_IN_SYNC: int +PR_ATTACH_SIZE: int +PR_ATTACH_NUM: int +PR_PREPROCESS: int +PR_ORIGINATING_MTA_CERTIFICATE: int +PR_PROOF_OF_SUBMISSION: int +PR_ENTRYID: int +PR_OBJECT_TYPE: int +PR_ICON: int +PR_MINI_ICON: int +PR_STORE_ENTRYID: int +PR_STORE_RECORD_KEY: int +PR_RECORD_KEY: int +PR_MAPPING_SIGNATURE: int +PR_ACCESS_LEVEL: int +PR_INSTANCE_KEY: int +PR_ROW_TYPE: int +PR_ACCESS: int +PR_ROWID: int +PR_DISPLAY_NAME: int +PR_DISPLAY_NAME_W: int +PR_DISPLAY_NAME_A: int +PR_ADDRTYPE: int +PR_ADDRTYPE_W: int +PR_ADDRTYPE_A: int +PR_EMAIL_ADDRESS: int +PR_EMAIL_ADDRESS_W: int +PR_EMAIL_ADDRESS_A: int +PR_COMMENT: int +PR_COMMENT_W: int +PR_COMMENT_A: int +PR_DEPTH: int +PR_PROVIDER_DISPLAY: int +PR_PROVIDER_DISPLAY_W: int +PR_PROVIDER_DISPLAY_A: int +PR_CREATION_TIME: int +PR_LAST_MODIFICATION_TIME: int +PR_RESOURCE_FLAGS: int +PR_PROVIDER_DLL_NAME: int +PR_PROVIDER_DLL_NAME_W: int +PR_PROVIDER_DLL_NAME_A: int +PR_SEARCH_KEY: int +PR_PROVIDER_UID: int +PR_PROVIDER_ORDINAL: int +PR_FORM_VERSION: int +PR_FORM_VERSION_W: int +PR_FORM_VERSION_A: int +PR_FORM_CLSID: int +PR_FORM_CONTACT_NAME: int +PR_FORM_CONTACT_NAME_W: int +PR_FORM_CONTACT_NAME_A: int +PR_FORM_CATEGORY: int +PR_FORM_CATEGORY_W: int +PR_FORM_CATEGORY_A: int +PR_FORM_CATEGORY_SUB: int +PR_FORM_CATEGORY_SUB_W: int +PR_FORM_CATEGORY_SUB_A: int +PR_FORM_HOST_MAP: int +PR_FORM_HIDDEN: int +PR_FORM_DESIGNER_NAME: int +PR_FORM_DESIGNER_NAME_W: int +PR_FORM_DESIGNER_NAME_A: int +PR_FORM_DESIGNER_GUID: int +PR_FORM_MESSAGE_BEHAVIOR: int +PR_DEFAULT_STORE: int +PR_STORE_SUPPORT_MASK: int +PR_STORE_STATE: int +PR_IPM_SUBTREE_SEARCH_KEY: int +PR_IPM_OUTBOX_SEARCH_KEY: int +PR_IPM_WASTEBASKET_SEARCH_KEY: int +PR_IPM_SENTMAIL_SEARCH_KEY: int +PR_MDB_PROVIDER: int +PR_RECEIVE_FOLDER_SETTINGS: int +PR_VALID_FOLDER_MASK: int +PR_IPM_SUBTREE_ENTRYID: int +PR_IPM_OUTBOX_ENTRYID: int +PR_IPM_WASTEBASKET_ENTRYID: int +PR_IPM_SENTMAIL_ENTRYID: int +PR_VIEWS_ENTRYID: int +PR_COMMON_VIEWS_ENTRYID: int +PR_FINDER_ENTRYID: int +PR_CONTAINER_FLAGS: int +PR_FOLDER_TYPE: int +PR_CONTENT_COUNT: int +PR_CONTENT_UNREAD: int +PR_CREATE_TEMPLATES: int +PR_DETAILS_TABLE: int +PR_SEARCH: int +PR_SELECTABLE: int +PR_SUBFOLDERS: int +PR_STATUS: int +PR_ANR: int +PR_ANR_W: int +PR_ANR_A: int +PR_CONTENTS_SORT_ORDER: int +PR_CONTAINER_HIERARCHY: int +PR_CONTAINER_CONTENTS: int +PR_FOLDER_ASSOCIATED_CONTENTS: int +PR_DEF_CREATE_DL: int +PR_DEF_CREATE_MAILUSER: int +PR_CONTAINER_CLASS: int +PR_CONTAINER_CLASS_W: int +PR_CONTAINER_CLASS_A: int +PR_CONTAINER_MODIFY_VERSION: int +PR_AB_PROVIDER_ID: int +PR_DEFAULT_VIEW_ENTRYID: int +PR_ASSOC_CONTENT_COUNT: int +PR_ATTACHMENT_X400_PARAMETERS: int +PR_ATTACH_DATA_OBJ: int +PR_ATTACH_DATA_BIN: int +PR_ATTACH_ENCODING: int +PR_ATTACH_EXTENSION: int +PR_ATTACH_EXTENSION_W: int +PR_ATTACH_EXTENSION_A: int +PR_ATTACH_FILENAME: int +PR_ATTACH_FILENAME_W: int +PR_ATTACH_FILENAME_A: int +PR_ATTACH_METHOD: int +PR_ATTACH_LONG_FILENAME: int +PR_ATTACH_LONG_FILENAME_W: int +PR_ATTACH_LONG_FILENAME_A: int +PR_ATTACH_PATHNAME: int +PR_ATTACH_PATHNAME_W: int +PR_ATTACH_PATHNAME_A: int +PR_ATTACH_RENDERING: int +PR_ATTACH_TAG: int +PR_RENDERING_POSITION: int +PR_ATTACH_TRANSPORT_NAME: int +PR_ATTACH_TRANSPORT_NAME_W: int +PR_ATTACH_TRANSPORT_NAME_A: int +PR_ATTACH_LONG_PATHNAME: int +PR_ATTACH_LONG_PATHNAME_W: int +PR_ATTACH_LONG_PATHNAME_A: int +PR_ATTACH_MIME_TAG: int +PR_ATTACH_MIME_TAG_W: int +PR_ATTACH_MIME_TAG_A: int +PR_ATTACH_ADDITIONAL_INFO: int +PR_DISPLAY_TYPE: int +PR_TEMPLATEID: int +PR_PRIMARY_CAPABILITY: int +PR_7BIT_DISPLAY_NAME: int +PR_ACCOUNT: int +PR_ACCOUNT_W: int +PR_ACCOUNT_A: int +PR_ALTERNATE_RECIPIENT: int +PR_CALLBACK_TELEPHONE_NUMBER: int +PR_CALLBACK_TELEPHONE_NUMBER_W: int +PR_CALLBACK_TELEPHONE_NUMBER_A: int +PR_CONVERSION_PROHIBITED: int +PR_DISCLOSE_RECIPIENTS: int +PR_GENERATION: int +PR_GENERATION_W: int +PR_GENERATION_A: int +PR_GIVEN_NAME: int +PR_GIVEN_NAME_W: int +PR_GIVEN_NAME_A: int +PR_GOVERNMENT_ID_NUMBER: int +PR_GOVERNMENT_ID_NUMBER_W: int +PR_GOVERNMENT_ID_NUMBER_A: int +PR_BUSINESS_TELEPHONE_NUMBER: int +PR_BUSINESS_TELEPHONE_NUMBER_W: int +PR_BUSINESS_TELEPHONE_NUMBER_A: int +PR_OFFICE_TELEPHONE_NUMBER: int +PR_OFFICE_TELEPHONE_NUMBER_W: int +PR_OFFICE_TELEPHONE_NUMBER_A: int +PR_HOME_TELEPHONE_NUMBER: int +PR_HOME_TELEPHONE_NUMBER_W: int +PR_HOME_TELEPHONE_NUMBER_A: int +PR_INITIALS: int +PR_INITIALS_W: int +PR_INITIALS_A: int +PR_KEYWORD: int +PR_KEYWORD_W: int +PR_KEYWORD_A: int +PR_LANGUAGE: int +PR_LANGUAGE_W: int +PR_LANGUAGE_A: int +PR_LOCATION: int +PR_LOCATION_W: int +PR_LOCATION_A: int +PR_MAIL_PERMISSION: int +PR_MHS_COMMON_NAME: int +PR_MHS_COMMON_NAME_W: int +PR_MHS_COMMON_NAME_A: int +PR_ORGANIZATIONAL_ID_NUMBER: int +PR_ORGANIZATIONAL_ID_NUMBER_W: int +PR_ORGANIZATIONAL_ID_NUMBER_A: int +PR_SURNAME: int +PR_SURNAME_W: int +PR_SURNAME_A: int +PR_ORIGINAL_ENTRYID: int +PR_ORIGINAL_DISPLAY_NAME: int +PR_ORIGINAL_DISPLAY_NAME_W: int +PR_ORIGINAL_DISPLAY_NAME_A: int +PR_ORIGINAL_SEARCH_KEY: int +PR_POSTAL_ADDRESS: int +PR_POSTAL_ADDRESS_W: int +PR_POSTAL_ADDRESS_A: int +PR_COMPANY_NAME: int +PR_COMPANY_NAME_W: int +PR_COMPANY_NAME_A: int +PR_TITLE: int +PR_TITLE_W: int +PR_TITLE_A: int +PR_DEPARTMENT_NAME: int +PR_DEPARTMENT_NAME_W: int +PR_DEPARTMENT_NAME_A: int +PR_OFFICE_LOCATION: int +PR_OFFICE_LOCATION_W: int +PR_OFFICE_LOCATION_A: int +PR_PRIMARY_TELEPHONE_NUMBER: int +PR_PRIMARY_TELEPHONE_NUMBER_W: int +PR_PRIMARY_TELEPHONE_NUMBER_A: int +PR_BUSINESS2_TELEPHONE_NUMBER: int +PR_BUSINESS2_TELEPHONE_NUMBER_W: int +PR_BUSINESS2_TELEPHONE_NUMBER_A: int +PR_OFFICE2_TELEPHONE_NUMBER: int +PR_OFFICE2_TELEPHONE_NUMBER_W: int +PR_OFFICE2_TELEPHONE_NUMBER_A: int +PR_MOBILE_TELEPHONE_NUMBER: int +PR_MOBILE_TELEPHONE_NUMBER_W: int +PR_MOBILE_TELEPHONE_NUMBER_A: int +PR_CELLULAR_TELEPHONE_NUMBER: int +PR_CELLULAR_TELEPHONE_NUMBER_W: int +PR_CELLULAR_TELEPHONE_NUMBER_A: int +PR_RADIO_TELEPHONE_NUMBER: int +PR_RADIO_TELEPHONE_NUMBER_W: int +PR_RADIO_TELEPHONE_NUMBER_A: int +PR_CAR_TELEPHONE_NUMBER: int +PR_CAR_TELEPHONE_NUMBER_W: int +PR_CAR_TELEPHONE_NUMBER_A: int +PR_OTHER_TELEPHONE_NUMBER: int +PR_OTHER_TELEPHONE_NUMBER_W: int +PR_OTHER_TELEPHONE_NUMBER_A: int +PR_TRANSMITABLE_DISPLAY_NAME: int +PR_TRANSMITABLE_DISPLAY_NAME_W: int +PR_TRANSMITABLE_DISPLAY_NAME_A: int +PR_PAGER_TELEPHONE_NUMBER: int +PR_PAGER_TELEPHONE_NUMBER_W: int +PR_PAGER_TELEPHONE_NUMBER_A: int +PR_BEEPER_TELEPHONE_NUMBER: int +PR_BEEPER_TELEPHONE_NUMBER_W: int +PR_BEEPER_TELEPHONE_NUMBER_A: int +PR_USER_CERTIFICATE: int +PR_PRIMARY_FAX_NUMBER: int +PR_PRIMARY_FAX_NUMBER_W: int +PR_PRIMARY_FAX_NUMBER_A: int +PR_BUSINESS_FAX_NUMBER: int +PR_BUSINESS_FAX_NUMBER_W: int +PR_BUSINESS_FAX_NUMBER_A: int +PR_HOME_FAX_NUMBER: int +PR_HOME_FAX_NUMBER_W: int +PR_HOME_FAX_NUMBER_A: int +PR_COUNTRY: int +PR_COUNTRY_W: int +PR_COUNTRY_A: int +PR_BUSINESS_ADDRESS_COUNTRY: int +PR_BUSINESS_ADDRESS_COUNTRY_W: int +PR_BUSINESS_ADDRESS_COUNTRY_A: int +PR_LOCALITY: int +PR_LOCALITY_W: int +PR_LOCALITY_A: int +PR_BUSINESS_ADDRESS_CITY: int +PR_BUSINESS_ADDRESS_CITY_W: int +PR_BUSINESS_ADDRESS_CITY_A: int +PR_STATE_OR_PROVINCE: int +PR_STATE_OR_PROVINCE_W: int +PR_STATE_OR_PROVINCE_A: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_W: int +PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_A: int +PR_STREET_ADDRESS: int +PR_STREET_ADDRESS_W: int +PR_STREET_ADDRESS_A: int +PR_BUSINESS_ADDRESS_STREET: int +PR_BUSINESS_ADDRESS_STREET_W: int +PR_BUSINESS_ADDRESS_STREET_A: int +PR_POSTAL_CODE: int +PR_POSTAL_CODE_W: int +PR_POSTAL_CODE_A: int +PR_BUSINESS_ADDRESS_POSTAL_CODE: int +PR_BUSINESS_ADDRESS_POSTAL_CODE_W: int +PR_BUSINESS_ADDRESS_POSTAL_CODE_A: int +PR_POST_OFFICE_BOX: int +PR_POST_OFFICE_BOX_W: int +PR_POST_OFFICE_BOX_A: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX_W: int +PR_BUSINESS_ADDRESS_POST_OFFICE_BOX_A: int +PR_TELEX_NUMBER: int +PR_TELEX_NUMBER_W: int +PR_TELEX_NUMBER_A: int +PR_ISDN_NUMBER: int +PR_ISDN_NUMBER_W: int +PR_ISDN_NUMBER_A: int +PR_ASSISTANT_TELEPHONE_NUMBER: int +PR_ASSISTANT_TELEPHONE_NUMBER_W: int +PR_ASSISTANT_TELEPHONE_NUMBER_A: int +PR_HOME2_TELEPHONE_NUMBER: int +PR_HOME2_TELEPHONE_NUMBER_W: int +PR_HOME2_TELEPHONE_NUMBER_A: int +PR_ASSISTANT: int +PR_ASSISTANT_W: int +PR_ASSISTANT_A: int +PR_SEND_RICH_INFO: int +PR_WEDDING_ANNIVERSARY: int +PR_BIRTHDAY: int +PR_HOBBIES: int +PR_HOBBIES_W: int +PR_HOBBIES_A: int +PR_MIDDLE_NAME: int +PR_MIDDLE_NAME_W: int +PR_MIDDLE_NAME_A: int +PR_DISPLAY_NAME_PREFIX: int +PR_DISPLAY_NAME_PREFIX_W: int +PR_DISPLAY_NAME_PREFIX_A: int +PR_PROFESSION: int +PR_PROFESSION_W: int +PR_PROFESSION_A: int +PR_PREFERRED_BY_NAME: int +PR_PREFERRED_BY_NAME_W: int +PR_PREFERRED_BY_NAME_A: int +PR_SPOUSE_NAME: int +PR_SPOUSE_NAME_W: int +PR_SPOUSE_NAME_A: int +PR_COMPUTER_NETWORK_NAME: int +PR_COMPUTER_NETWORK_NAME_W: int +PR_COMPUTER_NETWORK_NAME_A: int +PR_CUSTOMER_ID: int +PR_CUSTOMER_ID_W: int +PR_CUSTOMER_ID_A: int +PR_TTYTDD_PHONE_NUMBER: int +PR_TTYTDD_PHONE_NUMBER_W: int +PR_TTYTDD_PHONE_NUMBER_A: int +PR_FTP_SITE: int +PR_FTP_SITE_W: int +PR_FTP_SITE_A: int +PR_GENDER: int +PR_MANAGER_NAME: int +PR_MANAGER_NAME_W: int +PR_MANAGER_NAME_A: int +PR_NICKNAME: int +PR_NICKNAME_W: int +PR_NICKNAME_A: int +PR_PERSONAL_HOME_PAGE: int +PR_PERSONAL_HOME_PAGE_W: int +PR_PERSONAL_HOME_PAGE_A: int +PR_BUSINESS_HOME_PAGE: int +PR_BUSINESS_HOME_PAGE_W: int +PR_BUSINESS_HOME_PAGE_A: int +PR_CONTACT_VERSION: int +PR_CONTACT_ENTRYIDS: int +PR_CONTACT_ADDRTYPES: int +PR_CONTACT_ADDRTYPES_W: int +PR_CONTACT_ADDRTYPES_A: int +PR_CONTACT_DEFAULT_ADDRESS_INDEX: int +PR_CONTACT_EMAIL_ADDRESSES: int +PR_CONTACT_EMAIL_ADDRESSES_W: int +PR_CONTACT_EMAIL_ADDRESSES_A: int +PR_COMPANY_MAIN_PHONE_NUMBER: int +PR_COMPANY_MAIN_PHONE_NUMBER_W: int +PR_COMPANY_MAIN_PHONE_NUMBER_A: int +PR_CHILDRENS_NAMES: int +PR_CHILDRENS_NAMES_W: int +PR_CHILDRENS_NAMES_A: int +PR_HOME_ADDRESS_CITY: int +PR_HOME_ADDRESS_CITY_W: int +PR_HOME_ADDRESS_CITY_A: int +PR_HOME_ADDRESS_COUNTRY: int +PR_HOME_ADDRESS_COUNTRY_W: int +PR_HOME_ADDRESS_COUNTRY_A: int +PR_HOME_ADDRESS_POSTAL_CODE: int +PR_HOME_ADDRESS_POSTAL_CODE_W: int +PR_HOME_ADDRESS_POSTAL_CODE_A: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE_W: int +PR_HOME_ADDRESS_STATE_OR_PROVINCE_A: int +PR_HOME_ADDRESS_STREET: int +PR_HOME_ADDRESS_STREET_W: int +PR_HOME_ADDRESS_STREET_A: int +PR_HOME_ADDRESS_POST_OFFICE_BOX: int +PR_HOME_ADDRESS_POST_OFFICE_BOX_W: int +PR_HOME_ADDRESS_POST_OFFICE_BOX_A: int +PR_OTHER_ADDRESS_CITY: int +PR_OTHER_ADDRESS_CITY_W: int +PR_OTHER_ADDRESS_CITY_A: int +PR_OTHER_ADDRESS_COUNTRY: int +PR_OTHER_ADDRESS_COUNTRY_W: int +PR_OTHER_ADDRESS_COUNTRY_A: int +PR_OTHER_ADDRESS_POSTAL_CODE: int +PR_OTHER_ADDRESS_POSTAL_CODE_W: int +PR_OTHER_ADDRESS_POSTAL_CODE_A: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE_W: int +PR_OTHER_ADDRESS_STATE_OR_PROVINCE_A: int +PR_OTHER_ADDRESS_STREET: int +PR_OTHER_ADDRESS_STREET_W: int +PR_OTHER_ADDRESS_STREET_A: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX_W: int +PR_OTHER_ADDRESS_POST_OFFICE_BOX_A: int +PR_STORE_PROVIDERS: int +PR_AB_PROVIDERS: int +PR_TRANSPORT_PROVIDERS: int +PR_DEFAULT_PROFILE: int +PR_AB_SEARCH_PATH: int +PR_AB_DEFAULT_DIR: int +PR_AB_DEFAULT_PAB: int +PR_FILTERING_HOOKS: int +PR_SERVICE_NAME: int +PR_SERVICE_NAME_W: int +PR_SERVICE_NAME_A: int +PR_SERVICE_DLL_NAME: int +PR_SERVICE_DLL_NAME_W: int +PR_SERVICE_DLL_NAME_A: int +PR_SERVICE_ENTRY_NAME: int +PR_SERVICE_UID: int +PR_SERVICE_EXTRA_UIDS: int +PR_SERVICES: int +PR_SERVICE_SUPPORT_FILES: int +PR_SERVICE_SUPPORT_FILES_W: int +PR_SERVICE_SUPPORT_FILES_A: int +PR_SERVICE_DELETE_FILES: int +PR_SERVICE_DELETE_FILES_W: int +PR_SERVICE_DELETE_FILES_A: int +PR_AB_SEARCH_PATH_UPDATE: int +PR_PROFILE_NAME: int +PR_PROFILE_NAME_A: int +PR_PROFILE_NAME_W: int +PR_IDENTITY_DISPLAY: int +PR_IDENTITY_DISPLAY_W: int +PR_IDENTITY_DISPLAY_A: int +PR_IDENTITY_ENTRYID: int +PR_RESOURCE_METHODS: int +PR_RESOURCE_TYPE: int +PR_STATUS_CODE: int +PR_IDENTITY_SEARCH_KEY: int +PR_OWN_STORE_ENTRYID: int +PR_RESOURCE_PATH: int +PR_RESOURCE_PATH_W: int +PR_RESOURCE_PATH_A: int +PR_STATUS_STRING: int +PR_STATUS_STRING_W: int +PR_STATUS_STRING_A: int +PR_X400_DEFERRED_DELIVERY_CANCEL: int +PR_HEADER_FOLDER_ENTRYID: int +PR_REMOTE_PROGRESS: int +PR_REMOTE_PROGRESS_TEXT: int +PR_REMOTE_PROGRESS_TEXT_W: int +PR_REMOTE_PROGRESS_TEXT_A: int +PR_REMOTE_VALIDATE_OK: int +PR_CONTROL_FLAGS: int +PR_CONTROL_STRUCTURE: int +PR_CONTROL_TYPE: int +PR_DELTAX: int +PR_DELTAY: int +PR_XPOS: int +PR_YPOS: int +PR_CONTROL_ID: int +PR_INITIAL_DETAILS_PANE: int +PROP_ID_SECURE_MIN: int +PROP_ID_SECURE_MAX: int +pidExchangeXmitReservedMin: int +pidExchangeNonXmitReservedMin: int +pidProfileMin: int +pidStoreMin: int +pidFolderMin: int +pidMessageReadOnlyMin: int +pidMessageWriteableMin: int +pidAttachReadOnlyMin: int +pidSpecialMin: int +pidAdminMin: int +pidSecureProfileMin: int +PR_PROFILE_VERSION: int +PR_PROFILE_CONFIG_FLAGS: int +PR_PROFILE_HOME_SERVER: int +PR_PROFILE_HOME_SERVER_DN: int +PR_PROFILE_HOME_SERVER_ADDRS: int +PR_PROFILE_USER: int +PR_PROFILE_CONNECT_FLAGS: int +PR_PROFILE_TRANSPORT_FLAGS: int +PR_PROFILE_UI_STATE: int +PR_PROFILE_UNRESOLVED_NAME: int +PR_PROFILE_UNRESOLVED_SERVER: int +PR_PROFILE_BINDING_ORDER: int +PR_PROFILE_MAX_RESTRICT: int +PR_PROFILE_AB_FILES_PATH: int +PR_PROFILE_OFFLINE_STORE_PATH: int +PR_PROFILE_OFFLINE_INFO: int +PR_PROFILE_ADDR_INFO: int +PR_PROFILE_OPTIONS_DATA: int +PR_PROFILE_SECURE_MAILBOX: int +PR_DISABLE_WINSOCK: int +PR_OST_ENCRYPTION: int +PR_PROFILE_OPEN_FLAGS: int +PR_PROFILE_TYPE: int +PR_PROFILE_MAILBOX: int +PR_PROFILE_SERVER: int +PR_PROFILE_SERVER_DN: int +PR_PROFILE_FAVFLD_DISPLAY_NAME: int +PR_PROFILE_FAVFLD_COMMENT: int +PR_PROFILE_ALLPUB_DISPLAY_NAME: int +PR_PROFILE_ALLPUB_COMMENT: int +OSTF_NO_ENCRYPTION: int +OSTF_COMPRESSABLE_ENCRYPTION: int +OSTF_BEST_ENCRYPTION: int +PR_NON_IPM_SUBTREE_ENTRYID: int +PR_EFORMS_REGISTRY_ENTRYID: int +PR_SPLUS_FREE_BUSY_ENTRYID: int +PR_OFFLINE_ADDRBOOK_ENTRYID: int +PR_EFORMS_FOR_LOCALE_ENTRYID: int +PR_FREE_BUSY_FOR_LOCAL_SITE_ENTRYID: int +PR_ADDRBOOK_FOR_LOCAL_SITE_ENTRYID: int +PR_OFFLINE_MESSAGE_ENTRYID: int +PR_IPM_FAVORITES_ENTRYID: int +PR_IPM_PUBLIC_FOLDERS_ENTRYID: int +PR_GW_MTSIN_ENTRYID: int +PR_GW_MTSOUT_ENTRYID: int +PR_TRANSFER_ENABLED: int +PR_TEST_LINE_SPEED: int +PR_HIERARCHY_SYNCHRONIZER: int +PR_CONTENTS_SYNCHRONIZER: int +PR_COLLECTOR: int +PR_FAST_TRANSFER: int +PR_STORE_OFFLINE: int +PR_IN_TRANSIT: int +PR_REPLICATION_STYLE: int +PR_REPLICATION_SCHEDULE: int +PR_REPLICATION_MESSAGE_PRIORITY: int +PR_OVERALL_MSG_AGE_LIMIT: int +PR_REPLICATION_ALWAYS_INTERVAL: int +PR_REPLICATION_MSG_SIZE: int +STYLE_ALWAYS_INTERVAL_DEFAULT: int +REPLICATION_MESSAGE_SIZE_LIMIT_DEFAULT: int +STYLE_NEVER: int +STYLE_NORMAL: int +STYLE_ALWAYS: int +STYLE_DEFAULT: int +PR_SOURCE_KEY: int +PR_PARENT_SOURCE_KEY: int +PR_CHANGE_KEY: int +PR_PREDECESSOR_CHANGE_LIST: int +PR_FOLDER_CHILD_COUNT: int +PR_RIGHTS: int +PR_ACL_TABLE: int +PR_RULES_TABLE: int +PR_HAS_RULES: int +PR_ADDRESS_BOOK_ENTRYID: int +PR_ACL_DATA: int +PR_RULES_DATA: int +PR_FOLDER_DESIGN_FLAGS: int +PR_DESIGN_IN_PROGRESS: int +PR_SECURE_ORIGINATION: int +PR_PUBLISH_IN_ADDRESS_BOOK: int +PR_RESOLVE_METHOD: int +PR_ADDRESS_BOOK_DISPLAY_NAME: int +PR_EFORMS_LOCALE_ID: int +PR_REPLICA_LIST: int +PR_OVERALL_AGE_LIMIT: int +RESOLVE_METHOD_DEFAULT: int +RESOLVE_METHOD_LAST_WRITER_WINS: int +RESOLVE_METHOD_NO_CONFLICT_NOTIFICATION: int +PR_PUBLIC_FOLDER_ENTRYID: int +PR_HAS_NAMED_PROPERTIES: int +PR_CREATOR_NAME: int +PR_CREATOR_ENTRYID: int +PR_LAST_MODIFIER_NAME: int +PR_LAST_MODIFIER_ENTRYID: int +PR_HAS_DAMS: int +PR_RULE_TRIGGER_HISTORY: int +PR_MOVE_TO_STORE_ENTRYID: int +PR_MOVE_TO_FOLDER_ENTRYID: int +PR_REPLICA_SERVER: int +PR_DEFERRED_SEND_NUMBER: int +PR_DEFERRED_SEND_UNITS: int +PR_EXPIRY_NUMBER: int +PR_EXPIRY_UNITS: int +PR_DEFERRED_SEND_TIME: int +PR_GW_ADMIN_OPERATIONS: int +PR_P1_CONTENT: int +PR_P1_CONTENT_TYPE: int +PR_CLIENT_ACTIONS: int +PR_DAM_ORIGINAL_ENTRYID: int +PR_DAM_BACK_PATCHED: int +PR_RULE_ERROR: int +PR_RULE_ACTION_TYPE: int +PR_RULE_ACTION_NUMBER: int +PR_RULE_FOLDER_ENTRYID: int +PR_CONFLICT_ENTRYID: int +PR_MESSAGE_LOCALE_ID: int +PR_STORAGE_QUOTA_LIMIT: int +PR_EXCESS_STORAGE_USED: int +PR_SVR_GENERATING_QUOTA_MSG: int +PR_DELEGATED_BY_RULE: int +MSGSTATUS_IN_CONFLICT: int +PR_IN_CONFLICT: int +PR_LONGTERM_ENTRYID_FROM_TABLE: int +PR_ORIGINATOR_NAME: int +PR_ORIGINATOR_ADDR: int +PR_ORIGINATOR_ADDRTYPE: int +PR_ORIGINATOR_ENTRYID: int +PR_ARRIVAL_TIME: int +PR_TRACE_INFO: int +PR_INTERNAL_TRACE_INFO: int +PR_SUBJECT_TRACE_INFO: int +PR_RECIPIENT_NUMBER: int +PR_MTS_SUBJECT_ID: int +PR_REPORT_DESTINATION_NAME: int +PR_REPORT_DESTINATION_ENTRYID: int +PR_CONTENT_SEARCH_KEY: int +PR_FOREIGN_ID: int +PR_FOREIGN_REPORT_ID: int +PR_FOREIGN_SUBJECT_ID: int +PR_MTS_ID: int +PR_MTS_REPORT_ID: int +PR_FOLDER_FLAGS: int +PR_LAST_ACCESS_TIME: int +PR_RESTRICTION_COUNT: int +PR_CATEG_COUNT: int +PR_CACHED_COLUMN_COUNT: int +PR_NORMAL_MSG_W_ATTACH_COUNT: int +PR_ASSOC_MSG_W_ATTACH_COUNT: int +PR_RECIPIENT_ON_NORMAL_MSG_COUNT: int +PR_RECIPIENT_ON_ASSOC_MSG_COUNT: int +PR_ATTACH_ON_NORMAL_MSG_COUNT: int +PR_ATTACH_ON_ASSOC_MSG_COUNT: int +PR_NORMAL_MESSAGE_SIZE: int +PR_NORMAL_MESSAGE_SIZE_EXTENDED: int +PR_ASSOC_MESSAGE_SIZE: int +PR_ASSOC_MESSAGE_SIZE_EXTENDED: int +PR_FOLDER_PATHNAME: int +PR_OWNER_COUNT: int +PR_CONTACT_COUNT: int +PR_MESSAGE_SIZE_EXTENDED: int +PR_USERFIELDS: int +PR_FORCE_USE_ENTRYID_SERVER: int +PR_PROFILE_MDB_DN: int +PST_EXTERN_PROPID_BASE: int +PR_PST_PATH: int +PR_PST_PATH_W: int +PR_PST_PATH_A: int +PR_PST_REMEMBER_PW: int +PR_PST_ENCRYPTION: int +PR_PST_PW_SZ_OLD: int +PR_PST_PW_SZ_OLD_W: int +PR_PST_PW_SZ_OLD_A: int +PR_PST_PW_SZ_NEW: int +PR_PST_PW_SZ_NEW_W: int +PR_PST_PW_SZ_NEW_A: int diff --git a/stubs/pywin32/win32comext/mapi/mapiutil.pyi b/stubs/pywin32/win32comext/mapi/mapiutil.pyi new file mode 100644 index 000000000000..a595c89686cb --- /dev/null +++ b/stubs/pywin32/win32comext/mapi/mapiutil.pyi @@ -0,0 +1,15 @@ +prTable: dict[int, str] + +def GetPropTagName(pt): ... + +mapiErrorTable: dict[int, str] + +def GetScodeString(hr): ... + +ptTable: dict[int, str] + +def GetMapiTypeName(propType, rawType: bool = ...): ... +def GetProperties(obj, propList): ... +def GetAllProperties(obj, make_tag_names: bool = ...): ... +def SetPropertyValue(obj, prop, val) -> None: ... +def SetProperties(msg, propDict) -> None: ... diff --git a/stubs/pywin32/win32comext/propsys/__init__.pyi b/stubs/pywin32/win32comext/propsys/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/propsys/propsys.pyi b/stubs/pywin32/win32comext/propsys/propsys.pyi new file mode 100644 index 000000000000..090ef130f25b --- /dev/null +++ b/stubs/pywin32/win32comext/propsys/propsys.pyi @@ -0,0 +1,61 @@ +from typing import TypeAlias + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def PSGetItemPropertyHandler( + Item: _win32typing.PyIShellItem, riid: _win32typing.PyIID, ReadWrite: int, / +) -> _win32typing.PyIPropertyStore: ... +def PSGetPropertyDescription( + Key: _win32typing.PyPROPERTYKEY, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyDescription: ... +def PSGetPropertySystem(riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertySystem: ... +def PSGetNameFromPropertyKey(Key: _win32typing.PyPROPERTYKEY, /) -> str: ... +def PSGetPropertyKeyFromName(Name, /) -> _win32typing.PyPROPERTYKEY: ... +def PSRegisterPropertySchema(filename, /) -> None: ... +def PSUnregisterPropertySchema(filename, /) -> None: ... +def SHGetPropertyStoreFromParsingName( + Path: str, BindCtx: _win32typing.PyIBindCtx | None = ..., Flags: int = ..., riid: _win32typing.PyIID | str = ..., / +) -> _win32typing.PyIPropertyStore: ... +def StgSerializePropVariant(propvar: _win32typing.PyPROPVARIANT, /): ... +def StgDeserializePropVariant(prop, /) -> _win32typing.PyPROPVARIANT: ... +def PSCreateMemoryPropertyStore(riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertyStore: ... +def PSCreatePropertyStoreFromPropertySetStorage( + pss: _win32typing.PyIPropertySetStorage, Mode, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyStore: ... +def PSLookupPropertyHandlerCLSID(FilePath, /) -> _win32typing.PyIID: ... +def SHGetPropertyStoreForWindow(hwnd: int, riid: _win32typing.PyIID, /) -> _win32typing.PyIPropertyStore: ... +def PSGetPropertyFromPropertyStorage(ps, key: _win32typing.PyPROPERTYKEY, /) -> _win32typing.PyPROPVARIANT: ... +def PSGetNamedPropertyFromPropertyStorage(ps, name, /) -> _win32typing.PyPROPVARIANT: ... +def PSCreateSimplePropertyChange( + flags, key: _win32typing.PyPROPERTYKEY, val: _win32typing.PyPROPVARIANT, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyChange: ... +def PSCreatePropertyChangeArray() -> _win32typing.PyIPropertyChangeArray: ... +def SHSetDefaultProperties( + hwnd: int, + Item: _win32typing.PyIShellItem, + FileOpFlags: int = ..., + Sink: _win32typing.PyGFileOperationProgressSink | None = ..., + /, +) -> None: ... + +IID_IInitializeWithFile: _win32typing.PyIID +IID_IInitializeWithStream: _win32typing.PyIID +IID_INamedPropertyStore: _win32typing.PyIID +IID_IObjectWithPropertyKey: _win32typing.PyIID +IID_IPersistSerializedPropStorage: _win32typing.PyIID +IID_IPropertyChange: _win32typing.PyIID +IID_IPropertyChangeArray: _win32typing.PyIID +IID_IPropertyDescription: _win32typing.PyIID +IID_IPropertyDescriptionAliasInfo: _win32typing.PyIID +IID_IPropertyDescriptionList: _win32typing.PyIID +IID_IPropertyDescriptionSearchInfo: _win32typing.PyIID +IID_IPropertyEnumType: _win32typing.PyIID +IID_IPropertyEnumTypeList: _win32typing.PyIID +IID_IPropertyStore: _win32typing.PyIID +IID_IPropertyStoreCache: _win32typing.PyIID +IID_IPropertyStoreCapabilities: _win32typing.PyIID +IID_IPropertySystem: _win32typing.PyIID +PROPVARIANTType = _win32typing.PyPROPVARIANT diff --git a/stubs/pywin32/win32comext/propsys/pscon.pyi b/stubs/pywin32/win32comext/propsys/pscon.pyi new file mode 100644 index 000000000000..799bc0fa1382 --- /dev/null +++ b/stubs/pywin32/win32comext/propsys/pscon.pyi @@ -0,0 +1,695 @@ +from _typeshed import Incomplete + +PET_DISCRETEVALUE: int +PET_RANGEDVALUE: int +PET_DEFAULTVALUE: int +PET_ENDRANGE: int +PDTF_DEFAULT: int +PDTF_MULTIPLEVALUES: int +PDTF_ISINNATE: int +PDTF_ISGROUP: int +PDTF_CANGROUPBY: int +PDTF_CANSTACKBY: int +PDTF_ISTREEPROPERTY: int +PDTF_INCLUDEINFULLTEXTQUERY: int +PDTF_ISVIEWABLE: int +PDTF_ISQUERYABLE: int +PDTF_ISSYSTEMPROPERTY: int +PDTF_MASK_ALL: int +PDVF_DEFAULT: int +PDVF_CENTERALIGN: int +PDVF_RIGHTALIGN: int +PDVF_BEGINNEWGROUP: int +PDVF_FILLAREA: int +PDVF_SORTDESCENDING: int +PDVF_SHOWONLYIFPRESENT: int +PDVF_SHOWBYDEFAULT: int +PDVF_SHOWINPRIMARYLIST: int +PDVF_SHOWINSECONDARYLIST: int +PDVF_HIDELABEL: int +PDVF_HIDDEN: int +PDVF_CANWRAP: int +PDVF_MASK_ALL: int +PDDT_STRING: int +PDDT_NUMBER: int +PDDT_BOOLEAN: int +PDDT_DATETIME: int +PDDT_ENUMERATED: int +PDGR_DISCRETE: int +PDGR_ALPHANUMERIC: int +PDGR_SIZE: int +PDGR_DYNAMIC: int +PDGR_DATE: int +PDGR_PERCENT: int +PDGR_ENUMERATED: int +PDFF_DEFAULT: int +PDFF_PREFIXNAME: int +PDFF_FILENAME: int +PDFF_ALWAYSKB: int +PDFF_RESERVED_RIGHTTOLEFT: int +PDFF_SHORTTIME: int +PDFF_LONGTIME: int +PDFF_HIDETIME: int +PDFF_SHORTDATE: int +PDFF_LONGDATE: int +PDFF_HIDEDATE: int +PDFF_RELATIVEDATE: int +PDFF_USEEDITINVITATION: int +PDFF_READONLY: int +PDFF_NOAUTOREADINGORDER: int +PDSD_GENERAL: int +PDSD_A_Z: int +PDSD_LOWEST_HIGHEST: int +PDSD_SMALLEST_BIGGEST: int +PDSD_OLDEST_NEWEST: int +PDRDT_GENERAL: int +PDRDT_DATE: int +PDRDT_SIZE: int +PDRDT_COUNT: int +PDRDT_REVISION: int +PDRDT_LENGTH: int +PDRDT_DURATION: int +PDRDT_SPEED: int +PDRDT_RATE: int +PDRDT_RATING: int +PDRDT_PRIORITY: int +PDAT_DEFAULT: int +PDAT_FIRST: int +PDAT_SUM: int +PDAT_AVERAGE: int +PDAT_DATERANGE: int +PDAT_UNION: int +PDAT_MAX: int +PDAT_MIN: int +PDCOT_NONE: int +PDCOT_STRING: int +PDCOT_SIZE: int +PDCOT_DATETIME: int +PDCOT_BOOLEAN: int +PDCOT_NUMBER: int +PDSIF_DEFAULT: int +PDSIF_ININVERTEDINDEX: int +PDSIF_ISCOLUMN: int +PDSIF_ISCOLUMNSPARSE: int +PDCIT_NONE: int +PDCIT_ONDISK: int +PDCIT_INMEMORY: int +PDEF_ALL: int +PDEF_SYSTEM: int +PDEF_NONSYSTEM: int +PDEF_VIEWABLE: int +PDEF_QUERYABLE: int +PDEF_INFULLTEXTQUERY: int +PDEF_COLUMN: int +PSC_NORMAL: int +PSC_NOTINSOURCE: int +PSC_DIRTY: int +COP_IMPLICIT: int +COP_EQUAL: int +COP_NOTEQUAL: int +COP_LESSTHAN: int +COP_GREATERTHAN: int +COP_LESSTHANOREQUAL: int +COP_GREATERTHANOREQUAL: int +COP_VALUE_STARTSWITH: int +COP_VALUE_ENDSWITH: int +COP_VALUE_CONTAINS: int +COP_VALUE_NOTCONTAINS: int +COP_DOSWILDCARDS: int +COP_WORD_EQUAL: int +COP_WORD_STARTSWITH: int +COP_APPLICATION_SPECIFIC: int +FPSPS_READONLY: int +PKEY_PIDSTR_MAX: int +GUIDSTRING_MAX: Incomplete +PKEYSTR_MAX: Incomplete +PKEY_Audio_ChannelCount: Incomplete +PKEY_Audio_Compression: Incomplete +PKEY_Audio_EncodingBitrate: Incomplete +PKEY_Audio_Format: Incomplete +PKEY_Audio_IsVariableBitRate: Incomplete +PKEY_Audio_PeakValue: Incomplete +PKEY_Audio_SampleRate: Incomplete +PKEY_Audio_SampleSize: Incomplete +PKEY_Audio_StreamName: Incomplete +PKEY_Audio_StreamNumber: Incomplete +PKEY_Calendar_Duration: Incomplete +PKEY_Calendar_IsOnline: Incomplete +PKEY_Calendar_IsRecurring: Incomplete +PKEY_Calendar_Location: Incomplete +PKEY_Calendar_OptionalAttendeeAddresses: Incomplete +PKEY_Calendar_OptionalAttendeeNames: Incomplete +PKEY_Calendar_OrganizerAddress: Incomplete +PKEY_Calendar_OrganizerName: Incomplete +PKEY_Calendar_ReminderTime: Incomplete +PKEY_Calendar_RequiredAttendeeAddresses: Incomplete +PKEY_Calendar_RequiredAttendeeNames: Incomplete +PKEY_Calendar_Resources: Incomplete +PKEY_Calendar_ShowTimeAs: Incomplete +PKEY_Calendar_ShowTimeAsText: Incomplete +PKEY_Communication_AccountName: Incomplete +PKEY_Communication_Suffix: Incomplete +PKEY_Communication_TaskStatus: Incomplete +PKEY_Communication_TaskStatusText: Incomplete +PKEY_Computer_DecoratedFreeSpace: Incomplete +PKEY_Contact_Anniversary: Incomplete +PKEY_Contact_AssistantName: Incomplete +PKEY_Contact_AssistantTelephone: Incomplete +PKEY_Contact_Birthday: Incomplete +PKEY_Contact_BusinessAddress: Incomplete +PKEY_Contact_BusinessAddressCity: Incomplete +PKEY_Contact_BusinessAddressCountry: Incomplete +PKEY_Contact_BusinessAddressPostalCode: Incomplete +PKEY_Contact_BusinessAddressPostOfficeBox: Incomplete +PKEY_Contact_BusinessAddressState: Incomplete +PKEY_Contact_BusinessAddressStreet: Incomplete +PKEY_Contact_BusinessFaxNumber: Incomplete +PKEY_Contact_BusinessHomePage: Incomplete +PKEY_Contact_BusinessTelephone: Incomplete +PKEY_Contact_CallbackTelephone: Incomplete +PKEY_Contact_CarTelephone: Incomplete +PKEY_Contact_Children: Incomplete +PKEY_Contact_CompanyMainTelephone: Incomplete +PKEY_Contact_Department: Incomplete +PKEY_Contact_EmailAddress: Incomplete +PKEY_Contact_EmailAddress2: Incomplete +PKEY_Contact_EmailAddress3: Incomplete +PKEY_Contact_EmailAddresses: Incomplete +PKEY_Contact_EmailName: Incomplete +PKEY_Contact_FileAsName: Incomplete +PKEY_Contact_FirstName: Incomplete +PKEY_Contact_FullName: Incomplete +PKEY_Contact_Gender: Incomplete +PKEY_Contact_Hobbies: Incomplete +PKEY_Contact_HomeAddress: Incomplete +PKEY_Contact_HomeAddressCity: Incomplete +PKEY_Contact_HomeAddressCountry: Incomplete +PKEY_Contact_HomeAddressPostalCode: Incomplete +PKEY_Contact_HomeAddressPostOfficeBox: Incomplete +PKEY_Contact_HomeAddressState: Incomplete +PKEY_Contact_HomeAddressStreet: Incomplete +PKEY_Contact_HomeFaxNumber: Incomplete +PKEY_Contact_HomeTelephone: Incomplete +PKEY_Contact_IMAddress: Incomplete +PKEY_Contact_Initials: Incomplete +PKEY_Contact_JA_CompanyNamePhonetic: Incomplete +PKEY_Contact_JA_FirstNamePhonetic: Incomplete +PKEY_Contact_JA_LastNamePhonetic: Incomplete +PKEY_Contact_JobTitle: Incomplete +PKEY_Contact_Label: Incomplete +PKEY_Contact_LastName: Incomplete +PKEY_Contact_MailingAddress: Incomplete +PKEY_Contact_MiddleName: Incomplete +PKEY_Contact_MobileTelephone: Incomplete +PKEY_Contact_NickName: Incomplete +PKEY_Contact_OfficeLocation: Incomplete +PKEY_Contact_OtherAddress: Incomplete +PKEY_Contact_OtherAddressCity: Incomplete +PKEY_Contact_OtherAddressCountry: Incomplete +PKEY_Contact_OtherAddressPostalCode: Incomplete +PKEY_Contact_OtherAddressPostOfficeBox: Incomplete +PKEY_Contact_OtherAddressState: Incomplete +PKEY_Contact_OtherAddressStreet: Incomplete +PKEY_Contact_PagerTelephone: Incomplete +PKEY_Contact_PersonalTitle: Incomplete +PKEY_Contact_PrimaryAddressCity: Incomplete +PKEY_Contact_PrimaryAddressCountry: Incomplete +PKEY_Contact_PrimaryAddressPostalCode: Incomplete +PKEY_Contact_PrimaryAddressPostOfficeBox: Incomplete +PKEY_Contact_PrimaryAddressState: Incomplete +PKEY_Contact_PrimaryAddressStreet: Incomplete +PKEY_Contact_PrimaryEmailAddress: Incomplete +PKEY_Contact_PrimaryTelephone: Incomplete +PKEY_Contact_Profession: Incomplete +PKEY_Contact_SpouseName: Incomplete +PKEY_Contact_Suffix: Incomplete +PKEY_Contact_TelexNumber: Incomplete +PKEY_Contact_TTYTDDTelephone: Incomplete +PKEY_Contact_WebPage: Incomplete +PKEY_AcquisitionID: Incomplete +PKEY_ApplicationName: Incomplete +PKEY_Author: Incomplete +PKEY_Capacity: Incomplete +PKEY_Category: Incomplete +PKEY_Comment: Incomplete +PKEY_Company: Incomplete +PKEY_ComputerName: Incomplete +PKEY_ContainedItems: Incomplete +PKEY_ContentStatus: Incomplete +PKEY_ContentType: Incomplete +PKEY_Copyright: Incomplete +PKEY_DateAccessed: Incomplete +PKEY_DateAcquired: Incomplete +PKEY_DateArchived: Incomplete +PKEY_DateCompleted: Incomplete +PKEY_DateCreated: Incomplete +PKEY_DateImported: Incomplete +PKEY_DateModified: Incomplete +PKEY_DueDate: Incomplete +PKEY_EndDate: Incomplete +PKEY_FileAllocationSize: Incomplete +PKEY_FileAttributes: Incomplete +PKEY_FileCount: Incomplete +PKEY_FileDescription: Incomplete +PKEY_FileExtension: Incomplete +PKEY_FileFRN: Incomplete +PKEY_FileName: Incomplete +PKEY_FileOwner: Incomplete +PKEY_FileVersion: Incomplete +PKEY_FindData: Incomplete +PKEY_FlagColor: Incomplete +PKEY_FlagColorText: Incomplete +PKEY_FlagStatus: Incomplete +PKEY_FlagStatusText: Incomplete +PKEY_FreeSpace: Incomplete +PKEY_Identity: Incomplete +PKEY_Importance: Incomplete +PKEY_ImportanceText: Incomplete +PKEY_IsAttachment: Incomplete +PKEY_IsDeleted: Incomplete +PKEY_IsFlagged: Incomplete +PKEY_IsFlaggedComplete: Incomplete +PKEY_IsIncomplete: Incomplete +PKEY_IsRead: Incomplete +PKEY_IsSendToTarget: Incomplete +PKEY_IsShared: Incomplete +PKEY_ItemAuthors: Incomplete +PKEY_ItemDate: Incomplete +PKEY_ItemFolderNameDisplay: Incomplete +PKEY_ItemFolderPathDisplay: Incomplete +PKEY_ItemFolderPathDisplayNarrow: Incomplete +PKEY_ItemName: Incomplete +PKEY_ItemNameDisplay: Incomplete +PKEY_ItemNamePrefix: Incomplete +PKEY_ItemParticipants: Incomplete +PKEY_ItemPathDisplay: Incomplete +PKEY_ItemPathDisplayNarrow: Incomplete +PKEY_ItemType: Incomplete +PKEY_ItemTypeText: Incomplete +PKEY_ItemUrl: Incomplete +PKEY_Keywords: Incomplete +PKEY_Kind: Incomplete +PKEY_KindText: Incomplete +PKEY_Language: Incomplete +PKEY_MileageInformation: Incomplete +PKEY_MIMEType: Incomplete +PKEY_Null: Incomplete +PKEY_OfflineAvailability: Incomplete +PKEY_OfflineStatus: Incomplete +PKEY_OriginalFileName: Incomplete +PKEY_ParentalRating: Incomplete +PKEY_ParentalRatingReason: Incomplete +PKEY_ParentalRatingsOrganization: Incomplete +PKEY_ParsingBindContext: Incomplete +PKEY_ParsingName: Incomplete +PKEY_ParsingPath: Incomplete +PKEY_PerceivedType: Incomplete +PKEY_PercentFull: Incomplete +PKEY_Priority: Incomplete +PKEY_PriorityText: Incomplete +PKEY_Project: Incomplete +PKEY_ProviderItemID: Incomplete +PKEY_Rating: Incomplete +PKEY_RatingText: Incomplete +PKEY_Sensitivity: Incomplete +PKEY_SensitivityText: Incomplete +PKEY_SFGAOFlags: Incomplete +PKEY_SharedWith: Incomplete +PKEY_ShareUserRating: Incomplete +PKEY_Shell_OmitFromView: Incomplete +PKEY_SimpleRating: Incomplete +PKEY_Size: Incomplete +PKEY_SoftwareUsed: Incomplete +PKEY_SourceItem: Incomplete +PKEY_StartDate: Incomplete +PKEY_Status: Incomplete +PKEY_Subject: Incomplete +PKEY_Thumbnail: Incomplete +PKEY_ThumbnailCacheId: Incomplete +PKEY_ThumbnailStream: Incomplete +PKEY_Title: Incomplete +PKEY_TotalFileSize: Incomplete +PKEY_Trademarks: Incomplete +PKEY_Document_ByteCount: Incomplete +PKEY_Document_CharacterCount: Incomplete +PKEY_Document_ClientID: Incomplete +PKEY_Document_Contributor: Incomplete +PKEY_Document_DateCreated: Incomplete +PKEY_Document_DatePrinted: Incomplete +PKEY_Document_DateSaved: Incomplete +PKEY_Document_Division: Incomplete +PKEY_Document_DocumentID: Incomplete +PKEY_Document_HiddenSlideCount: Incomplete +PKEY_Document_LastAuthor: Incomplete +PKEY_Document_LineCount: Incomplete +PKEY_Document_Manager: Incomplete +PKEY_Document_MultimediaClipCount: Incomplete +PKEY_Document_NoteCount: Incomplete +PKEY_Document_PageCount: Incomplete +PKEY_Document_ParagraphCount: Incomplete +PKEY_Document_PresentationFormat: Incomplete +PKEY_Document_RevisionNumber: Incomplete +PKEY_Document_Security: Incomplete +PKEY_Document_SlideCount: Incomplete +PKEY_Document_Template: Incomplete +PKEY_Document_TotalEditingTime: Incomplete +PKEY_Document_Version: Incomplete +PKEY_Document_WordCount: Incomplete +PKEY_DRM_DatePlayExpires: Incomplete +PKEY_DRM_DatePlayStarts: Incomplete +PKEY_DRM_Description: Incomplete +PKEY_DRM_IsProtected: Incomplete +PKEY_DRM_PlayCount: Incomplete +PKEY_GPS_Altitude: Incomplete +PKEY_GPS_AltitudeDenominator: Incomplete +PKEY_GPS_AltitudeNumerator: Incomplete +PKEY_GPS_AltitudeRef: Incomplete +PKEY_GPS_AreaInformation: Incomplete +PKEY_GPS_Date: Incomplete +PKEY_GPS_DestBearing: Incomplete +PKEY_GPS_DestBearingDenominator: Incomplete +PKEY_GPS_DestBearingNumerator: Incomplete +PKEY_GPS_DestBearingRef: Incomplete +PKEY_GPS_DestDistance: Incomplete +PKEY_GPS_DestDistanceDenominator: Incomplete +PKEY_GPS_DestDistanceNumerator: Incomplete +PKEY_GPS_DestDistanceRef: Incomplete +PKEY_GPS_DestLatitude: Incomplete +PKEY_GPS_DestLatitudeDenominator: Incomplete +PKEY_GPS_DestLatitudeNumerator: Incomplete +PKEY_GPS_DestLatitudeRef: Incomplete +PKEY_GPS_DestLongitude: Incomplete +PKEY_GPS_DestLongitudeDenominator: Incomplete +PKEY_GPS_DestLongitudeNumerator: Incomplete +PKEY_GPS_DestLongitudeRef: Incomplete +PKEY_GPS_Differential: Incomplete +PKEY_GPS_DOP: Incomplete +PKEY_GPS_DOPDenominator: Incomplete +PKEY_GPS_DOPNumerator: Incomplete +PKEY_GPS_ImgDirection: Incomplete +PKEY_GPS_ImgDirectionDenominator: Incomplete +PKEY_GPS_ImgDirectionNumerator: Incomplete +PKEY_GPS_ImgDirectionRef: Incomplete +PKEY_GPS_Latitude: Incomplete +PKEY_GPS_LatitudeDenominator: Incomplete +PKEY_GPS_LatitudeNumerator: Incomplete +PKEY_GPS_LatitudeRef: Incomplete +PKEY_GPS_Longitude: Incomplete +PKEY_GPS_LongitudeDenominator: Incomplete +PKEY_GPS_LongitudeNumerator: Incomplete +PKEY_GPS_LongitudeRef: Incomplete +PKEY_GPS_MapDatum: Incomplete +PKEY_GPS_MeasureMode: Incomplete +PKEY_GPS_ProcessingMethod: Incomplete +PKEY_GPS_Satellites: Incomplete +PKEY_GPS_Speed: Incomplete +PKEY_GPS_SpeedDenominator: Incomplete +PKEY_GPS_SpeedNumerator: Incomplete +PKEY_GPS_SpeedRef: Incomplete +PKEY_GPS_Status: Incomplete +PKEY_GPS_Track: Incomplete +PKEY_GPS_TrackDenominator: Incomplete +PKEY_GPS_TrackNumerator: Incomplete +PKEY_GPS_TrackRef: Incomplete +PKEY_GPS_VersionID: Incomplete +PKEY_Image_BitDepth: Incomplete +PKEY_Image_ColorSpace: Incomplete +PKEY_Image_CompressedBitsPerPixel: Incomplete +PKEY_Image_CompressedBitsPerPixelDenominator: Incomplete +PKEY_Image_CompressedBitsPerPixelNumerator: Incomplete +PKEY_Image_Compression: Incomplete +PKEY_Image_CompressionText: Incomplete +PKEY_Image_Dimensions: Incomplete +PKEY_Image_HorizontalResolution: Incomplete +PKEY_Image_HorizontalSize: Incomplete +PKEY_Image_ImageID: Incomplete +PKEY_Image_ResolutionUnit: Incomplete +PKEY_Image_VerticalResolution: Incomplete +PKEY_Image_VerticalSize: Incomplete +PKEY_Journal_Contacts: Incomplete +PKEY_Journal_EntryType: Incomplete +PKEY_Link_Comment: Incomplete +PKEY_Link_DateVisited: Incomplete +PKEY_Link_Description: Incomplete +PKEY_Link_Status: Incomplete +PKEY_Link_TargetExtension: Incomplete +PKEY_Link_TargetParsingPath: Incomplete +PKEY_Link_TargetSFGAOFlags: Incomplete +PKEY_Media_AuthorUrl: Incomplete +PKEY_Media_AverageLevel: Incomplete +PKEY_Media_ClassPrimaryID: Incomplete +PKEY_Media_ClassSecondaryID: Incomplete +PKEY_Media_CollectionGroupID: Incomplete +PKEY_Media_CollectionID: Incomplete +PKEY_Media_ContentDistributor: Incomplete +PKEY_Media_ContentID: Incomplete +PKEY_Media_CreatorApplication: Incomplete +PKEY_Media_CreatorApplicationVersion: Incomplete +PKEY_Media_DateEncoded: Incomplete +PKEY_Media_DateReleased: Incomplete +PKEY_Media_Duration: Incomplete +PKEY_Media_DVDID: Incomplete +PKEY_Media_EncodedBy: Incomplete +PKEY_Media_EncodingSettings: Incomplete +PKEY_Media_FrameCount: Incomplete +PKEY_Media_MCDI: Incomplete +PKEY_Media_MetadataContentProvider: Incomplete +PKEY_Media_Producer: Incomplete +PKEY_Media_PromotionUrl: Incomplete +PKEY_Media_ProtectionType: Incomplete +PKEY_Media_ProviderRating: Incomplete +PKEY_Media_ProviderStyle: Incomplete +PKEY_Media_Publisher: Incomplete +PKEY_Media_SubscriptionContentId: Incomplete +PKEY_Media_SubTitle: Incomplete +PKEY_Media_UniqueFileIdentifier: Incomplete +PKEY_Media_UserNoAutoInfo: Incomplete +PKEY_Media_UserWebUrl: Incomplete +PKEY_Media_Writer: Incomplete +PKEY_Media_Year: Incomplete +PKEY_Message_AttachmentContents: Incomplete +PKEY_Message_AttachmentNames: Incomplete +PKEY_Message_BccAddress: Incomplete +PKEY_Message_BccName: Incomplete +PKEY_Message_CcAddress: Incomplete +PKEY_Message_CcName: Incomplete +PKEY_Message_ConversationID: Incomplete +PKEY_Message_ConversationIndex: Incomplete +PKEY_Message_DateReceived: Incomplete +PKEY_Message_DateSent: Incomplete +PKEY_Message_FromAddress: Incomplete +PKEY_Message_FromName: Incomplete +PKEY_Message_HasAttachments: Incomplete +PKEY_Message_IsFwdOrReply: Incomplete +PKEY_Message_MessageClass: Incomplete +PKEY_Message_SenderAddress: Incomplete +PKEY_Message_SenderName: Incomplete +PKEY_Message_Store: Incomplete +PKEY_Message_ToAddress: Incomplete +PKEY_Message_ToDoTitle: Incomplete +PKEY_Message_ToName: Incomplete +PKEY_Music_AlbumArtist: Incomplete +PKEY_Music_AlbumTitle: Incomplete +PKEY_Music_Artist: Incomplete +PKEY_Music_BeatsPerMinute: Incomplete +PKEY_Music_Composer: Incomplete +PKEY_Music_Conductor: Incomplete +PKEY_Music_ContentGroupDescription: Incomplete +PKEY_Music_Genre: Incomplete +PKEY_Music_InitialKey: Incomplete +PKEY_Music_Lyrics: Incomplete +PKEY_Music_Mood: Incomplete +PKEY_Music_PartOfSet: Incomplete +PKEY_Music_Period: Incomplete +PKEY_Music_SynchronizedLyrics: Incomplete +PKEY_Music_TrackNumber: Incomplete +PKEY_Note_Color: Incomplete +PKEY_Note_ColorText: Incomplete +PKEY_Photo_Aperture: Incomplete +PKEY_Photo_ApertureDenominator: Incomplete +PKEY_Photo_ApertureNumerator: Incomplete +PKEY_Photo_Brightness: Incomplete +PKEY_Photo_BrightnessDenominator: Incomplete +PKEY_Photo_BrightnessNumerator: Incomplete +PKEY_Photo_CameraManufacturer: Incomplete +PKEY_Photo_CameraModel: Incomplete +PKEY_Photo_CameraSerialNumber: Incomplete +PKEY_Photo_Contrast: Incomplete +PKEY_Photo_ContrastText: Incomplete +PKEY_Photo_DateTaken: Incomplete +PKEY_Photo_DigitalZoom: Incomplete +PKEY_Photo_DigitalZoomDenominator: Incomplete +PKEY_Photo_DigitalZoomNumerator: Incomplete +PKEY_Photo_Event: Incomplete +PKEY_Photo_EXIFVersion: Incomplete +PKEY_Photo_ExposureBias: Incomplete +PKEY_Photo_ExposureBiasDenominator: Incomplete +PKEY_Photo_ExposureBiasNumerator: Incomplete +PKEY_Photo_ExposureIndex: Incomplete +PKEY_Photo_ExposureIndexDenominator: Incomplete +PKEY_Photo_ExposureIndexNumerator: Incomplete +PKEY_Photo_ExposureProgram: Incomplete +PKEY_Photo_ExposureProgramText: Incomplete +PKEY_Photo_ExposureTime: Incomplete +PKEY_Photo_ExposureTimeDenominator: Incomplete +PKEY_Photo_ExposureTimeNumerator: Incomplete +PKEY_Photo_Flash: Incomplete +PKEY_Photo_FlashEnergy: Incomplete +PKEY_Photo_FlashEnergyDenominator: Incomplete +PKEY_Photo_FlashEnergyNumerator: Incomplete +PKEY_Photo_FlashManufacturer: Incomplete +PKEY_Photo_FlashModel: Incomplete +PKEY_Photo_FlashText: Incomplete +PKEY_Photo_FNumber: Incomplete +PKEY_Photo_FNumberDenominator: Incomplete +PKEY_Photo_FNumberNumerator: Incomplete +PKEY_Photo_FocalLength: Incomplete +PKEY_Photo_FocalLengthDenominator: Incomplete +PKEY_Photo_FocalLengthInFilm: Incomplete +PKEY_Photo_FocalLengthNumerator: Incomplete +PKEY_Photo_FocalPlaneXResolution: Incomplete +PKEY_Photo_FocalPlaneXResolutionDenominator: Incomplete +PKEY_Photo_FocalPlaneXResolutionNumerator: Incomplete +PKEY_Photo_FocalPlaneYResolution: Incomplete +PKEY_Photo_FocalPlaneYResolutionDenominator: Incomplete +PKEY_Photo_FocalPlaneYResolutionNumerator: Incomplete +PKEY_Photo_GainControl: Incomplete +PKEY_Photo_GainControlDenominator: Incomplete +PKEY_Photo_GainControlNumerator: Incomplete +PKEY_Photo_GainControlText: Incomplete +PKEY_Photo_ISOSpeed: Incomplete +PKEY_Photo_LensManufacturer: Incomplete +PKEY_Photo_LensModel: Incomplete +PKEY_Photo_LightSource: Incomplete +PKEY_Photo_MakerNote: Incomplete +PKEY_Photo_MakerNoteOffset: Incomplete +PKEY_Photo_MaxAperture: Incomplete +PKEY_Photo_MaxApertureDenominator: Incomplete +PKEY_Photo_MaxApertureNumerator: Incomplete +PKEY_Photo_MeteringMode: Incomplete +PKEY_Photo_MeteringModeText: Incomplete +PKEY_Photo_Orientation: Incomplete +PKEY_Photo_OrientationText: Incomplete +PKEY_Photo_PhotometricInterpretation: Incomplete +PKEY_Photo_PhotometricInterpretationText: Incomplete +PKEY_Photo_ProgramMode: Incomplete +PKEY_Photo_ProgramModeText: Incomplete +PKEY_Photo_RelatedSoundFile: Incomplete +PKEY_Photo_Saturation: Incomplete +PKEY_Photo_SaturationText: Incomplete +PKEY_Photo_Sharpness: Incomplete +PKEY_Photo_SharpnessText: Incomplete +PKEY_Photo_ShutterSpeed: Incomplete +PKEY_Photo_ShutterSpeedDenominator: Incomplete +PKEY_Photo_ShutterSpeedNumerator: Incomplete +PKEY_Photo_SubjectDistance: Incomplete +PKEY_Photo_SubjectDistanceDenominator: Incomplete +PKEY_Photo_SubjectDistanceNumerator: Incomplete +PKEY_Photo_TranscodedForSync: Incomplete +PKEY_Photo_WhiteBalance: Incomplete +PKEY_Photo_WhiteBalanceText: Incomplete +PKEY_PropGroup_Advanced: Incomplete +PKEY_PropGroup_Audio: Incomplete +PKEY_PropGroup_Calendar: Incomplete +PKEY_PropGroup_Camera: Incomplete +PKEY_PropGroup_Contact: Incomplete +PKEY_PropGroup_Content: Incomplete +PKEY_PropGroup_Description: Incomplete +PKEY_PropGroup_FileSystem: Incomplete +PKEY_PropGroup_General: Incomplete +PKEY_PropGroup_GPS: Incomplete +PKEY_PropGroup_Image: Incomplete +PKEY_PropGroup_Media: Incomplete +PKEY_PropGroup_MediaAdvanced: Incomplete +PKEY_PropGroup_Message: Incomplete +PKEY_PropGroup_Music: Incomplete +PKEY_PropGroup_Origin: Incomplete +PKEY_PropGroup_PhotoAdvanced: Incomplete +PKEY_PropGroup_RecordedTV: Incomplete +PKEY_PropGroup_Video: Incomplete +PKEY_PropList_ConflictPrompt: Incomplete +PKEY_PropList_ExtendedTileInfo: Incomplete +PKEY_PropList_FileOperationPrompt: Incomplete +PKEY_PropList_FullDetails: Incomplete +PKEY_PropList_InfoTip: Incomplete +PKEY_PropList_NonPersonal: Incomplete +PKEY_PropList_PreviewDetails: Incomplete +PKEY_PropList_PreviewTitle: Incomplete +PKEY_PropList_QuickTip: Incomplete +PKEY_PropList_TileInfo: Incomplete +PKEY_PropList_XPDetailsPanel: Incomplete +PKEY_RecordedTV_ChannelNumber: Incomplete +PKEY_RecordedTV_Credits: Incomplete +PKEY_RecordedTV_DateContentExpires: Incomplete +PKEY_RecordedTV_EpisodeName: Incomplete +PKEY_RecordedTV_IsATSCContent: Incomplete +PKEY_RecordedTV_IsClosedCaptioningAvailable: Incomplete +PKEY_RecordedTV_IsDTVContent: Incomplete +PKEY_RecordedTV_IsHDContent: Incomplete +PKEY_RecordedTV_IsRepeatBroadcast: Incomplete +PKEY_RecordedTV_IsSAP: Incomplete +PKEY_RecordedTV_NetworkAffiliation: Incomplete +PKEY_RecordedTV_OriginalBroadcastDate: Incomplete +PKEY_RecordedTV_ProgramDescription: Incomplete +PKEY_RecordedTV_RecordingTime: Incomplete +PKEY_RecordedTV_StationCallSign: Incomplete +PKEY_RecordedTV_StationName: Incomplete +PKEY_Search_AutoSummary: Incomplete +PKEY_Search_ContainerHash: Incomplete +PKEY_Search_Contents: Incomplete +PKEY_Search_EntryID: Incomplete +PKEY_Search_GatherTime: Incomplete +PKEY_Search_IsClosedDirectory: Incomplete +PKEY_Search_IsFullyContained: Incomplete +PKEY_Search_QueryFocusedSummary: Incomplete +PKEY_Search_Rank: Incomplete +PKEY_Search_Store: Incomplete +PKEY_Search_UrlToIndex: Incomplete +PKEY_Search_UrlToIndexWithModificationTime: Incomplete +PKEY_DescriptionID: Incomplete +PKEY_Link_TargetSFGAOFlagsStrings: Incomplete +PKEY_Link_TargetUrl: Incomplete +PKEY_Shell_SFGAOFlagsStrings: Incomplete +PKEY_Software_DateLastUsed: Incomplete +PKEY_Software_ProductName: Incomplete +PKEY_Software_ProductVersion: Incomplete +PKEY_Sync_Comments: Incomplete +PKEY_Sync_ConflictDescription: Incomplete +PKEY_Sync_ConflictFirstLocation: Incomplete +PKEY_Sync_ConflictSecondLocation: Incomplete +PKEY_Sync_HandlerCollectionID: Incomplete +PKEY_Sync_HandlerID: Incomplete +PKEY_Sync_HandlerName: Incomplete +PKEY_Sync_HandlerType: Incomplete +PKEY_Sync_HandlerTypeLabel: Incomplete +PKEY_Sync_ItemID: Incomplete +PKEY_Sync_ItemName: Incomplete +PKEY_Task_BillingInformation: Incomplete +PKEY_Task_CompletionStatus: Incomplete +PKEY_Task_Owner: Incomplete +PKEY_Video_Compression: Incomplete +PKEY_Video_Director: Incomplete +PKEY_Video_EncodingBitrate: Incomplete +PKEY_Video_FourCC: Incomplete +PKEY_Video_FrameHeight: Incomplete +PKEY_Video_FrameRate: Incomplete +PKEY_Video_FrameWidth: Incomplete +PKEY_Video_HorizontalAspectRatio: Incomplete +PKEY_Video_SampleSize: Incomplete +PKEY_Video_StreamName: Incomplete +PKEY_Video_StreamNumber: Incomplete +PKEY_Video_TotalBitrate: Incomplete +PKEY_Video_VerticalAspectRatio: Incomplete +PKEY_Volume_FileSystem: Incomplete +PKEY_Volume_IsMappedDrive: Incomplete +PKEY_Volume_IsRoot: Incomplete +PKEY_AppUserModel_RelaunchCommand: Incomplete +PKEY_AppUserModel_RelaunchIconResource: Incomplete +PKEY_AppUserModel_RelaunchDisplayNameResource: Incomplete +PKEY_AppUserModel_ID: Incomplete +PKEY_AppUserModel_IsDestListSeparator: Incomplete +PKEY_AppUserModel_ExcludeFromShowInNewInstall: Incomplete +PKEY_AppUserModel_PreventPinning: Incomplete +PKA_SET: int +PKA_APPEND: int +PKA_DELETE: int diff --git a/stubs/pywin32/win32comext/shell/__init__.pyi b/stubs/pywin32/win32comext/shell/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/shell/shell.pyi b/stubs/pywin32/win32comext/shell/shell.pyi new file mode 100644 index 000000000000..b8da6a3cc76c --- /dev/null +++ b/stubs/pywin32/win32comext/shell/shell.pyi @@ -0,0 +1,447 @@ +from _typeshed import Incomplete +from typing import Literal, TypeAlias, overload + +import _win32typing +from win32.lib.pywintypes import com_error + +error: TypeAlias = com_error # noqa: Y042 + +def AssocCreate() -> _win32typing.PyIQueryAssociations: ... +def AssocCreateForClasses() -> _win32typing.PyIUnknown: ... + +@overload +def DragQueryFile(hglobal: int | _win32typing.PyHANDLE | None, index: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFile(hglobal: int | _win32typing.PyHANDLE | None, index: int, /) -> str: ... + +@overload +def DragQueryFileW(hglobal: int | _win32typing.PyHANDLE | None, index: Literal[-1] = -1, /) -> int: ... # type: ignore[overload-overlap] +@overload +def DragQueryFileW(hglobal: int | _win32typing.PyHANDLE | None, index: int, /) -> str: ... + +def DragQueryPoint(hglobal: int, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... +def IsUserAnAdmin() -> bool: ... +def SHCreateDataObject( + parent, children: list[Incomplete], do_inner: _win32typing.PyIDataObject, iid: _win32typing.PyIID, / +) -> _win32typing.PyIUnknown: ... +def SHCreateDefaultContextMenu(dcm, iid: _win32typing.PyIID, /) -> _win32typing.PyIUnknown: ... +def SHCreateDefaultExtractIcon() -> _win32typing.PyIDefaultExtractIconInit: ... +def SHCreateShellFolderView( + sf: _win32typing.PyIShellFolder, viewOuter: _win32typing.PyIShellView | None = ..., callbacks: Incomplete | None = ..., / +) -> _win32typing.PyIShellView: ... +def SHCreateShellItemArray( + parent: _win32typing.PyIDL, sf: _win32typing.PyIShellFolder, children: list[_win32typing.PyIDL], / +) -> _win32typing.PyIShellItemArray: ... +def SHCreateShellItemArrayFromDataObject( + do: _win32typing.PyIDataObject, iid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItemArray: ... +def SHCreateShellItemArrayFromShellItem( + si: _win32typing.PyIShellItem, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItemArray: ... +def SHBrowseForFolder( + hwndOwner: int | None = ..., + pidlRoot: _win32typing.PyIDL | None = ..., + title: str | None = ..., + flags: int = ..., + callback: Incomplete | None = ..., + callback_data: Incomplete | None = ..., + /, +) -> tuple[_win32typing.PyIDL, Incomplete, Incomplete]: ... +def SHGetFileInfo( + name: _win32typing.PyIDL | str, dwFileAttributes, uFlags, infoAttrs: int = ..., / +) -> tuple[Incomplete, _win32typing.SHFILEINFO]: ... +def SHGetFolderPath(hwndOwner: int, nFolder, handle: int, flags, /) -> str: ... +def SHSetFolderPath(csidl, Path, hToken: int | None = ..., /) -> None: ... +def SHGetFolderLocation(hwndOwner: int, nFolder, hToken: int | None = ..., reserved=..., /) -> _win32typing.PyIDL: ... +def SHGetSpecialFolderPath(hwndOwner: int, nFolder, bCreate: int = ..., /) -> str: ... +def SHGetSpecialFolderLocation(hwndOwner: int, nFolder, /) -> _win32typing.PyIDL: ... +def SHAddToRecentDocs(Flags, data, /) -> None: ... +def SHEmptyRecycleBin(hwnd: int, path: str, flags, /) -> None: ... +def SHQueryRecycleBin(RootPath: str | None = ..., /) -> tuple[Incomplete, Incomplete]: ... +def SHGetDesktopFolder() -> _win32typing.PyIShellFolder: ... +def SHUpdateImage(HashItem: str, Index, Flags, ImageIndex, /) -> None: ... +def SHChangeNotify(EventId, Flags, Item1, Item2, /) -> None: ... +def SHChangeNotifyRegister(hwnd: int, sources, events, msg, /): ... +def SHChangeNotifyDeregister(_id, /) -> None: ... +def SHCreateItemFromParsingName(name, ctx: _win32typing.PyIBindCtx, riid: _win32typing.PyIID, /) -> _win32typing.PyIShellItem: ... +def SHCreateItemFromRelativeName( + Parent: _win32typing.PyIShellItem, Name, ctx: _win32typing.PyIBindCtx, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHCreateItemInKnownFolder( + FolderId: _win32typing.PyIID, Flags, Name, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHCreateItemWithParent( + Parent: _win32typing.PyIDL, sfParent: _win32typing.PyIShellFolder, child: _win32typing.PyIDL, riid: _win32typing.PyIID, / +) -> _win32typing.PyIShellItem: ... +def SHGetInstanceExplorer() -> _win32typing.PyIUnknown: ... +def SHFileOperation(operation: _win32typing.SHFILEOPSTRUCT, /) -> tuple[Incomplete, Incomplete]: ... +def StringAsCIDA(pidl: str, /) -> tuple[_win32typing.PyIDL, Incomplete]: ... +def CIDAAsString(pidl: str, /) -> str: ... +def StringAsPIDL(pidl: str, /) -> _win32typing.PyIDL: ... +def AddressAsPIDL(address, /) -> _win32typing.PyIDL: ... +def PIDLAsString(pidl: _win32typing.PyIDL, /) -> str: ... +def SHGetSettings(mask: int = ..., /): ... +def FILEGROUPDESCRIPTORAsString(descriptors: list[Incomplete], arg, /) -> str: ... +def StringAsFILEGROUPDESCRIPTOR(buf, make_unicode: int = ..., /) -> list[Incomplete]: ... +def ShellExecuteEx( + fMask: int = ..., + hwnd: int = ..., + lpVerb: str = ..., + lpFile: str = ..., + lpParameters: str = ..., + lpDirectory: str = ..., + nShow: int = ..., + lpIDlist: _win32typing.PyIDL = ..., + lpClass: str = ..., + hkeyClass=..., + dwHotKey=..., + hIcon: int = ..., + hMonitor: int = ..., +): ... +def SHGetViewStatePropertyBag( + pidl: _win32typing.PyIDL, BagName: str, Flags, riid: _win32typing.PyIID, / +) -> _win32typing.PyIPropertyBag: ... +def SHILCreateFromPath(Path: str, Flags, /) -> tuple[_win32typing.PyIDL, Incomplete]: ... +def SHCreateShellItem( + pidlParent: _win32typing.PyIDL, sfParent: _win32typing.PyIShellFolder, Child: _win32typing.PyIDL, / +) -> _win32typing.PyIShellItem: ... +def SHOpenFolderAndSelectItems(Folder: _win32typing.PyIDL, Items: tuple[_win32typing.PyIDL, ...], Flags=...) -> None: ... +def SHCreateStreamOnFileEx( + File: str, Mode: int, Attributes: int, Create: bool, Template: None = None +) -> _win32typing.PyIStream: ... +def SetCurrentProcessExplicitAppUserModelID(AppID: str, /) -> None: ... +def GetCurrentProcessExplicitAppUserModelID() -> str: ... +def SHParseDisplayName(Name, Attributes, BindCtx: _win32typing.PyIBindCtx | None = ...) -> tuple[list[bytes], int]: ... +def SHCreateItemFromIDList(pidl, riid=..., /): ... +def SHCreateShellItemArrayFromIDLists(pidls, /): ... +def SHGetIDListFromObject(unk, /): ... +def SHGetNameFromIDList(pidl, flags: int, /): ... +def SHGetPathFromIDList(pidl, /): ... +def SHGetPathFromIDListW(Pidl, /): ... + +BHID_AssociationArray: _win32typing.PyIID +BHID_DataObject: _win32typing.PyIID +BHID_EnumItems: _win32typing.PyIID +BHID_Filter: _win32typing.PyIID +BHID_LinkTargetItem: _win32typing.PyIID +BHID_PropertyStore: _win32typing.PyIID +BHID_SFObject: _win32typing.PyIID +BHID_SFUIObject: _win32typing.PyIID +BHID_SFViewObject: _win32typing.PyIID +BHID_Storage: _win32typing.PyIID +BHID_StorageEnum: _win32typing.PyIID +BHID_Stream: _win32typing.PyIID +BHID_ThumbnailHandler: _win32typing.PyIID +BHID_Transfer: _win32typing.PyIID +CGID_DefView: _win32typing.PyIID +CGID_Explorer: _win32typing.PyIID +CGID_ExplorerBarDoc: _win32typing.PyIID +CGID_ShellDocView: _win32typing.PyIID +CGID_ShellServiceObject: _win32typing.PyIID +CLSID_ActiveDesktop: _win32typing.PyIID +CLSID_ApplicationDestinations: _win32typing.PyIID +CLSID_ApplicationDocumentLists: _win32typing.PyIID +CLSID_ControlPanel: _win32typing.PyIID +CLSID_DestinationList: _win32typing.PyIID +CLSID_DragDropHelper: _win32typing.PyIID +CLSID_EnumerableObjectCollection: _win32typing.PyIID +CLSID_FileOperation: _win32typing.PyIID +CLSID_Internet: _win32typing.PyIID +CLSID_InternetShortcut: _win32typing.PyIID +CLSID_KnownFolderManager: _win32typing.PyIID +CLSID_MyComputer: _win32typing.PyIID +CLSID_MyDocuments: _win32typing.PyIID +CLSID_NetworkDomain: _win32typing.PyIID +CLSID_NetworkPlaces: _win32typing.PyIID +CLSID_NetworkServer: _win32typing.PyIID +CLSID_NetworkShare: _win32typing.PyIID +CLSID_Printers: _win32typing.PyIID +CLSID_RecycleBin: _win32typing.PyIID +CLSID_ShellDesktop: _win32typing.PyIID +CLSID_ShellFSFolder: _win32typing.PyIID +CLSID_ShellItem: _win32typing.PyIID +CLSID_ShellLibrary: _win32typing.PyIID +CLSID_ShellLink: _win32typing.PyIID +CLSID_TaskbarList: _win32typing.PyIID +EP_AdvQueryPane: _win32typing.PyIID +EP_Commands: _win32typing.PyIID +EP_Commands_Organize: _win32typing.PyIID +EP_Commands_View: _win32typing.PyIID +EP_DetailsPane: _win32typing.PyIID +EP_NavPane: _win32typing.PyIID +EP_PreviewPane: _win32typing.PyIID +EP_QueryPane: _win32typing.PyIID +FMTID_AudioSummaryInformation: _win32typing.PyIID +FMTID_Briefcase: _win32typing.PyIID +FMTID_Displaced: _win32typing.PyIID +FMTID_ImageProperties: _win32typing.PyIID +FMTID_ImageSummaryInformation: _win32typing.PyIID +FMTID_InternetSite: _win32typing.PyIID +FMTID_Intshcut: _win32typing.PyIID +FMTID_MediaFileSummaryInformation: _win32typing.PyIID +FMTID_Misc: _win32typing.PyIID +FMTID_Query: _win32typing.PyIID +FMTID_ShellDetails: _win32typing.PyIID +FMTID_Storage: _win32typing.PyIID +FMTID_SummaryInformation: _win32typing.PyIID +FMTID_Volume: _win32typing.PyIID +FMTID_WebView: _win32typing.PyIID +FOLDERID_AddNewPrograms: _win32typing.PyIID +FOLDERID_AdminTools: _win32typing.PyIID +FOLDERID_AppUpdates: _win32typing.PyIID +FOLDERID_CDBurning: _win32typing.PyIID +FOLDERID_ChangeRemovePrograms: _win32typing.PyIID +FOLDERID_CommonAdminTools: _win32typing.PyIID +FOLDERID_CommonOEMLinks: _win32typing.PyIID +FOLDERID_CommonPrograms: _win32typing.PyIID +FOLDERID_CommonStartMenu: _win32typing.PyIID +FOLDERID_CommonStartup: _win32typing.PyIID +FOLDERID_CommonTemplates: _win32typing.PyIID +FOLDERID_ComputerFolder: _win32typing.PyIID +FOLDERID_ConflictFolder: _win32typing.PyIID +FOLDERID_ConnectionsFolder: _win32typing.PyIID +FOLDERID_Contacts: _win32typing.PyIID +FOLDERID_ControlPanelFolder: _win32typing.PyIID +FOLDERID_Cookies: _win32typing.PyIID +FOLDERID_Desktop: _win32typing.PyIID +FOLDERID_DeviceMetadataStore: _win32typing.PyIID +FOLDERID_Documents: _win32typing.PyIID +FOLDERID_DocumentsLibrary: _win32typing.PyIID +FOLDERID_Downloads: _win32typing.PyIID +FOLDERID_Favorites: _win32typing.PyIID +FOLDERID_Fonts: _win32typing.PyIID +FOLDERID_GameTasks: _win32typing.PyIID +FOLDERID_Games: _win32typing.PyIID +FOLDERID_History: _win32typing.PyIID +FOLDERID_HomeGroup: _win32typing.PyIID +FOLDERID_ImplicitAppShortcuts: _win32typing.PyIID +FOLDERID_InternetCache: _win32typing.PyIID +FOLDERID_InternetFolder: _win32typing.PyIID +FOLDERID_Libraries: _win32typing.PyIID +FOLDERID_Links: _win32typing.PyIID +FOLDERID_LocalAppData: _win32typing.PyIID +FOLDERID_LocalAppDataLow: _win32typing.PyIID +FOLDERID_LocalizedResourcesDir: _win32typing.PyIID +FOLDERID_Music: _win32typing.PyIID +FOLDERID_MusicLibrary: _win32typing.PyIID +FOLDERID_NetHood: _win32typing.PyIID +FOLDERID_NetworkFolder: _win32typing.PyIID +FOLDERID_OriginalImages: _win32typing.PyIID +FOLDERID_PhotoAlbums: _win32typing.PyIID +FOLDERID_Pictures: _win32typing.PyIID +FOLDERID_PicturesLibrary: _win32typing.PyIID +FOLDERID_Playlists: _win32typing.PyIID +FOLDERID_PrintHood: _win32typing.PyIID +FOLDERID_PrintersFolder: _win32typing.PyIID +FOLDERID_Profile: _win32typing.PyIID +FOLDERID_ProgramData: _win32typing.PyIID +FOLDERID_ProgramFiles: _win32typing.PyIID +FOLDERID_ProgramFilesCommon: _win32typing.PyIID +FOLDERID_ProgramFilesCommonX64: _win32typing.PyIID +FOLDERID_ProgramFilesCommonX86: _win32typing.PyIID +FOLDERID_ProgramFilesX64: _win32typing.PyIID +FOLDERID_ProgramFilesX86: _win32typing.PyIID +FOLDERID_Programs: _win32typing.PyIID +FOLDERID_Public: _win32typing.PyIID +FOLDERID_PublicDesktop: _win32typing.PyIID +FOLDERID_PublicDocuments: _win32typing.PyIID +FOLDERID_PublicDownloads: _win32typing.PyIID +FOLDERID_PublicGameTasks: _win32typing.PyIID +FOLDERID_PublicLibraries: _win32typing.PyIID +FOLDERID_PublicMusic: _win32typing.PyIID +FOLDERID_PublicPictures: _win32typing.PyIID +FOLDERID_PublicRingtones: _win32typing.PyIID +FOLDERID_PublicVideos: _win32typing.PyIID +FOLDERID_QuickLaunch: _win32typing.PyIID +FOLDERID_Recent: _win32typing.PyIID +FOLDERID_RecordedTVLibrary: _win32typing.PyIID +FOLDERID_RecycleBinFolder: _win32typing.PyIID +FOLDERID_ResourceDir: _win32typing.PyIID +FOLDERID_Ringtones: _win32typing.PyIID +FOLDERID_RoamingAppData: _win32typing.PyIID +FOLDERID_SEARCH_CSC: _win32typing.PyIID +FOLDERID_SEARCH_MAPI: _win32typing.PyIID +FOLDERID_SampleMusic: _win32typing.PyIID +FOLDERID_SamplePictures: _win32typing.PyIID +FOLDERID_SamplePlaylists: _win32typing.PyIID +FOLDERID_SampleVideos: _win32typing.PyIID +FOLDERID_SavedGames: _win32typing.PyIID +FOLDERID_SavedSearches: _win32typing.PyIID +FOLDERID_SearchHome: _win32typing.PyIID +FOLDERID_SendTo: _win32typing.PyIID +FOLDERID_SidebarDefaultParts: _win32typing.PyIID +FOLDERID_SidebarParts: _win32typing.PyIID +FOLDERID_StartMenu: _win32typing.PyIID +FOLDERID_Startup: _win32typing.PyIID +FOLDERID_SyncManagerFolder: _win32typing.PyIID +FOLDERID_SyncResultsFolder: _win32typing.PyIID +FOLDERID_SyncSetupFolder: _win32typing.PyIID +FOLDERID_System: _win32typing.PyIID +FOLDERID_SystemX86: _win32typing.PyIID +FOLDERID_Templates: _win32typing.PyIID +FOLDERID_UserPinned: _win32typing.PyIID +FOLDERID_UserProfiles: _win32typing.PyIID +FOLDERID_UserProgramFiles: _win32typing.PyIID +FOLDERID_UserProgramFilesCommon: _win32typing.PyIID +FOLDERID_UsersFiles: _win32typing.PyIID +FOLDERID_UsersLibraries: _win32typing.PyIID +FOLDERID_Videos: _win32typing.PyIID +FOLDERID_VideosLibrary: _win32typing.PyIID +FOLDERID_Windows: _win32typing.PyIID +FOLDERTYPEID_Communications: _win32typing.PyIID +FOLDERTYPEID_CompressedFolder: _win32typing.PyIID +FOLDERTYPEID_Contacts: _win32typing.PyIID +FOLDERTYPEID_ControlPanelCategory: _win32typing.PyIID +FOLDERTYPEID_ControlPanelClassic: _win32typing.PyIID +FOLDERTYPEID_Documents: _win32typing.PyIID +FOLDERTYPEID_Games: _win32typing.PyIID +FOLDERTYPEID_Generic: _win32typing.PyIID +FOLDERTYPEID_GenericLibrary: _win32typing.PyIID +FOLDERTYPEID_GenericSearchResults: _win32typing.PyIID +FOLDERTYPEID_Invalid: _win32typing.PyIID +FOLDERTYPEID_Music: _win32typing.PyIID +FOLDERTYPEID_NetworkExplorer: _win32typing.PyIID +FOLDERTYPEID_OpenSearch: _win32typing.PyIID +FOLDERTYPEID_OtherUsers: _win32typing.PyIID +FOLDERTYPEID_Pictures: _win32typing.PyIID +FOLDERTYPEID_Printers: _win32typing.PyIID +FOLDERTYPEID_PublishedItems: _win32typing.PyIID +FOLDERTYPEID_RecordedTV: _win32typing.PyIID +FOLDERTYPEID_RecycleBin: _win32typing.PyIID +FOLDERTYPEID_SavedGames: _win32typing.PyIID +FOLDERTYPEID_SearchConnector: _win32typing.PyIID +FOLDERTYPEID_SearchHome: _win32typing.PyIID +FOLDERTYPEID_Searches: _win32typing.PyIID +FOLDERTYPEID_SoftwareExplorer: _win32typing.PyIID +FOLDERTYPEID_StartMenu: _win32typing.PyIID +FOLDERTYPEID_UserFiles: _win32typing.PyIID +FOLDERTYPEID_UsersLibraries: _win32typing.PyIID +FOLDERTYPEID_Videos: _win32typing.PyIID +HOTKEYF_ALT: int +HOTKEYF_CONTROL: int +HOTKEYF_EXT: int +HOTKEYF_SHIFT: int +IID_CDefView: _win32typing.PyIID +IID_IADesktopP2: _win32typing.PyIID +IID_IActiveDesktop: _win32typing.PyIID +IID_IActiveDesktopP: _win32typing.PyIID +IID_IApplicationDestinations: _win32typing.PyIID +IID_IApplicationDocumentLists: _win32typing.PyIID +IID_IAsyncOperation: _win32typing.PyIID +IID_IBrowserFrameOptions: _win32typing.PyIID +IID_ICategorizer: _win32typing.PyIID +IID_ICategoryProvider: _win32typing.PyIID +IID_IColumnProvider: _win32typing.PyIID +IID_IContextMenu: _win32typing.PyIID +IID_IContextMenu2: _win32typing.PyIID +IID_IContextMenu3: _win32typing.PyIID +IID_ICopyHook: _win32typing.PyIID +IID_ICopyHookA: _win32typing.PyIID +IID_ICopyHookW: _win32typing.PyIID +IID_ICurrentItem: _win32typing.PyIID +IID_ICustomDestinationList: _win32typing.PyIID +IID_IDefaultExtractIconInit: _win32typing.PyIID +IID_IDeskBand: _win32typing.PyIID +IID_IDisplayItem: _win32typing.PyIID +IID_IDockingWindow: _win32typing.PyIID +IID_IDropTargetHelper: _win32typing.PyIID +IID_IEmptyVolumeCache: _win32typing.PyIID +IID_IEmptyVolumeCache2: _win32typing.PyIID +IID_IEmptyVolumeCacheCallBack: _win32typing.PyIID +IID_IEnumExplorerCommand: _win32typing.PyIID +IID_IEnumIDList: _win32typing.PyIID +IID_IEnumObjects: _win32typing.PyIID +IID_IEnumResources: _win32typing.PyIID +IID_IEnumShellItems: _win32typing.PyIID +IID_IExplorerBrowser: _win32typing.PyIID +IID_IExplorerBrowserEvents: _win32typing.PyIID +IID_IExplorerCommand: _win32typing.PyIID +IID_IExplorerCommandProvider: _win32typing.PyIID +IID_IExplorerPaneVisibility: _win32typing.PyIID +IID_IExtractIcon: _win32typing.PyIID +IID_IExtractIconW: _win32typing.PyIID +IID_IExtractImage: _win32typing.PyIID +IID_IFileOperation: _win32typing.PyIID +IID_IFileOperationProgressSink: _win32typing.PyIID +IID_IFolderView: _win32typing.PyIID +IID_IIdentityName: _win32typing.PyIID +IID_IKnownFolder: _win32typing.PyIID +IID_IKnownFolderManager: _win32typing.PyIID +IID_INameSpaceTreeControl: _win32typing.PyIID +IID_IObjectArray: _win32typing.PyIID +IID_IObjectCollection: _win32typing.PyIID +IID_IPersistFolder: _win32typing.PyIID +IID_IPersistFolder2: _win32typing.PyIID +IID_IQueryAssociations: _win32typing.PyIID +IID_IRelatedItem: _win32typing.PyIID +IID_IShellBrowser: _win32typing.PyIID +IID_IShellCopyHook: _win32typing.PyIID +IID_IShellCopyHookA: _win32typing.PyIID +IID_IShellCopyHookW: _win32typing.PyIID +IID_IShellExtInit: _win32typing.PyIID +IID_IShellFolder: _win32typing.PyIID +IID_IShellFolder2: _win32typing.PyIID +IID_IShellIcon: _win32typing.PyIID +IID_IShellIconOverlay: _win32typing.PyIID +IID_IShellIconOverlayIdentifier: _win32typing.PyIID +IID_IShellIconOverlayManager: _win32typing.PyIID +IID_IShellItem: _win32typing.PyIID +IID_IShellItem2: _win32typing.PyIID +IID_IShellItemArray: _win32typing.PyIID +IID_IShellItemResources: _win32typing.PyIID +IID_IShellLibrary: _win32typing.PyIID +IID_IShellLink: _win32typing.PyIID +IID_IShellLinkA: _win32typing.PyIID +IID_IShellLinkDataList: _win32typing.PyIID +IID_IShellLinkW: _win32typing.PyIID +IID_IShellView: _win32typing.PyIID +IID_ITaskbarList: _win32typing.PyIID +IID_ITransferAdviseSink: _win32typing.PyIID +IID_ITransferDestination: _win32typing.PyIID +IID_ITransferMediumItem: _win32typing.PyIID +IID_ITransferSource: _win32typing.PyIID +IID_IUniformResourceLocator: _win32typing.PyIID +ResourceTypeStream: _win32typing.PyIID +SID_CtxQueryAssociations: _win32typing.PyIID +SID_DefView: _win32typing.PyIID +SID_LinkSite: _win32typing.PyIID +SID_MenuShellFolder: _win32typing.PyIID +SID_SCommDlgBrowser: _win32typing.PyIID +SID_SGetViewFromViewDual: _win32typing.PyIID +SID_SInternetExplorer: _win32typing.PyIID +SID_SMenuBandBKContextMenu: _win32typing.PyIID +SID_SMenuBandBottom: _win32typing.PyIID +SID_SMenuBandBottomSelected: _win32typing.PyIID +SID_SMenuBandChild: _win32typing.PyIID +SID_SMenuBandContextMenuModifier: _win32typing.PyIID +SID_SMenuBandParent: _win32typing.PyIID +SID_SMenuBandTop: _win32typing.PyIID +SID_SMenuPopup: _win32typing.PyIID +SID_SProgressUI: _win32typing.PyIID +SID_SShellBrowser: _win32typing.PyIID +SID_SShellDesktop: _win32typing.PyIID +SID_STopLevelBrowser: _win32typing.PyIID +SID_STopWindow: _win32typing.PyIID +SID_SUrlHistory: _win32typing.PyIID +SID_SWebBrowserApp: _win32typing.PyIID +SID_ShellFolderViewCB: _win32typing.PyIID +SLGP_RAWPATH: int +SLGP_SHORTPATH: int +SLGP_UNCPRIORITY: int +SLR_ANY_MATCH: int +SLR_INVOKE_MSI: int +SLR_NOLINKINFO: int +SLR_NOSEARCH: int +SLR_NOTRACK: int +SLR_NOUPDATE: int +SLR_NO_UI: int +SLR_UPDATE: int +VID_Details: _win32typing.PyIID +VID_LargeIcons: _win32typing.PyIID +VID_List: _win32typing.PyIID +VID_SmallIcons: _win32typing.PyIID +VID_ThumbStrip: _win32typing.PyIID +VID_Thumbnails: _win32typing.PyIID +VID_Tile: _win32typing.PyIID + +def SHGetKnownFolderPath(fid, flags: int = 0, token=None, /): ... diff --git a/stubs/pywin32/win32comext/shell/shellcon.pyi b/stubs/pywin32/win32comext/shell/shellcon.pyi new file mode 100644 index 000000000000..8e6090af389b --- /dev/null +++ b/stubs/pywin32/win32comext/shell/shellcon.pyi @@ -0,0 +1,1413 @@ +from _typeshed import Incomplete + +WM_USER: int +DROPEFFECT_NONE: int +DROPEFFECT_COPY: int +DROPEFFECT_MOVE: int +DROPEFFECT_LINK: int +DROPEFFECT_SCROLL: int +FO_MOVE: int +FO_COPY: int +FO_DELETE: int +FO_RENAME: int +FOF_MULTIDESTFILES: int +FOF_CONFIRMMOUSE: int +FOF_SILENT: int +FOF_RENAMEONCOLLISION: int +FOF_NOCONFIRMATION: int +FOF_WANTMAPPINGHANDLE: int +FOF_ALLOWUNDO: int +FOF_FILESONLY: int +FOF_SIMPLEPROGRESS: int +FOF_NOCONFIRMMKDIR: int +FOF_NOERRORUI: int +FOF_NOCOPYSECURITYATTRIBS: int +FOF_NORECURSION: int +FOF_NO_CONNECTED_ELEMENTS: int +FOF_WANTNUKEWARNING: int +FOF_NORECURSEREPARSE: int +FOF_NO_UI: Incomplete +FOFX_NOSKIPJUNCTIONS: int +FOFX_PREFERHARDLINK: int +FOFX_SHOWELEVATIONPROMPT: int +FOFX_EARLYFAILURE: int +FOFX_PRESERVEFILEEXTENSIONS: int +FOFX_KEEPNEWERFILE: int +FOFX_NOCOPYHOOKS: int +FOFX_NOMINIMIZEBOX: int +FOFX_MOVEACLSACROSSVOLUMES: int +FOFX_DONTDISPLAYSOURCEPATH: int +FOFX_DONTDISPLAYDESTPATH: int +FOFX_REQUIREELEVATION: int +FOFX_COPYASDOWNLOAD: int +FOFX_DONTDISPLAYLOCATIONS: int +PO_DELETE: int +PO_RENAME: int +PO_PORTCHANGE: int +PO_REN_PORT: int +SE_ERR_FNF: int +SE_ERR_PNF: int +SE_ERR_ACCESSDENIED: int +SE_ERR_OOM: int +SE_ERR_DLLNOTFOUND: int +SE_ERR_SHARE: int +SE_ERR_ASSOCINCOMPLETE: int +SE_ERR_DDETIMEOUT: int +SE_ERR_DDEFAIL: int +SE_ERR_DDEBUSY: int +SE_ERR_NOASSOC: int +SEE_MASK_CLASSNAME: int +SEE_MASK_CLASSKEY: int +SEE_MASK_IDLIST: int +SEE_MASK_INVOKEIDLIST: int +SEE_MASK_ICON: int +SEE_MASK_HOTKEY: int +SEE_MASK_NOCLOSEPROCESS: int +SEE_MASK_CONNECTNETDRV: int +SEE_MASK_FLAG_DDEWAIT: int +SEE_MASK_DOENVSUBST: int +SEE_MASK_FLAG_NO_UI: int +SEE_MASK_UNICODE: int +SEE_MASK_NO_CONSOLE: int +SEE_MASK_ASYNCOK: int +SEE_MASK_HMONITOR: int +SHERB_NOCONFIRMATION: int +SHERB_NOPROGRESSUI: int +SHERB_NOSOUND: int +NIM_ADD: int +NIM_MODIFY: int +NIM_DELETE: int +NIF_MESSAGE: int +NIF_ICON: int +NIF_TIP: int +SHGFI_ICON: int +SHGFI_DISPLAYNAME: int +SHGFI_TYPENAME: int +SHGFI_ATTRIBUTES: int +SHGFI_ICONLOCATION: int +SHGFI_EXETYPE: int +SHGFI_SYSICONINDEX: int +SHGFI_LINKOVERLAY: int +SHGFI_SELECTED: int +SHGFI_ATTR_SPECIFIED: int +SHGFI_LARGEICON: int +SHGFI_SMALLICON: int +SHGFI_OPENICON: int +SHGFI_SHELLICONSIZE: int +SHGFI_PIDL: int +SHGFI_USEFILEATTRIBUTES: int +SHGNLI_PIDL: int +SHGNLI_PREFIXNAME: int +SHGNLI_NOUNIQUE: int +PRINTACTION_OPEN: int +PRINTACTION_PROPERTIES: int +PRINTACTION_NETINSTALL: int +PRINTACTION_NETINSTALLLINK: int +PRINTACTION_TESTPAGE: int +PRINTACTION_OPENNETPRN: int +PRINTACTION_DOCUMENTDEFAULTS: int +PRINTACTION_SERVERPROPERTIES: int +CMF_NORMAL: int +CMF_DEFAULTONLY: int +CMF_VERBSONLY: int +CMF_EXPLORE: int +CMF_NOVERBS: int +CMF_CANRENAME: int +CMF_NODEFAULT: int +CMF_INCLUDESTATIC: int +CMF_ITEMMENU: int +CMF_EXTENDEDVERBS: int +CMF_DISABLEDVERBS: int +CMF_ASYNCVERBSTATE: int +CMF_OPTIMIZEFORINVOKE: int +CMF_SYNCCASCADEMENU: int +CMF_DONOTPICKDEFAULT: int +CMF_RESERVED: int +GCS_VERBA: int +GCS_HELPTEXTA: int +GCS_VALIDATEA: int +GCS_VERBW: int +GCS_HELPTEXTW: int +GCS_VALIDATEW: int +GCS_UNICODE: int +GCS_VERB: int +GCS_HELPTEXT: int +GCS_VALIDATE: int +CMDSTR_NEWFOLDERA: str +CMDSTR_VIEWLISTA: str +CMDSTR_VIEWDETAILSA: str +CMDSTR_NEWFOLDER: str +CMDSTR_VIEWLIST: str +CMDSTR_VIEWDETAILS: str +CMIC_MASK_HOTKEY: int +CMIC_MASK_ICON: int +CMIC_MASK_FLAG_NO_UI: int +CMIC_MASK_UNICODE: int +CMIC_MASK_NO_CONSOLE: int +CMIC_MASK_ASYNCOK: int +CMIC_MASK_PTINVOKE: int +GIL_OPENICON: int +GIL_FORSHELL: int +GIL_ASYNC: int +GIL_DEFAULTICON: int +GIL_FORSHORTCUT: int +GIL_CHECKSHIELD: int +GIL_SIMULATEDOC: int +GIL_PERINSTANCE: int +GIL_PERCLASS: int +GIL_NOTFILENAME: int +GIL_DONTCACHE: int +GIL_SHIELD: int +GIL_FORCENOSHIELD: int +ISIOI_ICONFILE: int +ISIOI_ICONINDEX: int +ISIOI_SYSIMAGELISTINDEX: int +FVSIF_RECT: int +FVSIF_PINNED: int +FVSIF_NEWFAILED: int +FVSIF_NEWFILE: int +FVSIF_CANVIEWIT: int +FCIDM_SHVIEWFIRST: int +FCIDM_SHVIEWLAST: int +FCIDM_BROWSERFIRST: int +FCIDM_BROWSERLAST: int +FCIDM_GLOBALFIRST: int +FCIDM_GLOBALLAST: int +FCIDM_MENU_FILE: Incomplete +FCIDM_MENU_EDIT: Incomplete +FCIDM_MENU_VIEW: Incomplete +FCIDM_MENU_VIEW_SEP_OPTIONS: Incomplete +FCIDM_MENU_TOOLS: Incomplete +FCIDM_MENU_TOOLS_SEP_GOTO: Incomplete +FCIDM_MENU_HELP: Incomplete +FCIDM_MENU_FIND: Incomplete +FCIDM_MENU_EXPLORE: Incomplete +FCIDM_MENU_FAVORITES: Incomplete +FCIDM_TOOLBAR: Incomplete +FCIDM_STATUS: Incomplete +IDC_OFFLINE_HAND: int +SBSP_DEFBROWSER: int +SBSP_SAMEBROWSER: int +SBSP_NEWBROWSER: int +SBSP_DEFMODE: int +SBSP_OPENMODE: int +SBSP_EXPLOREMODE: int +SBSP_ABSOLUTE: int +SBSP_RELATIVE: int +SBSP_PARENT: int +SBSP_NAVIGATEBACK: int +SBSP_NAVIGATEFORWARD: int +SBSP_ALLOW_AUTONAVIGATE: int +SBSP_INITIATEDBYHLINKFRAME: int +SBSP_REDIRECT: int +SBSP_WRITENOHISTORY: int +SBSP_NOAUTOSELECT: int +FCW_STATUS: int +FCW_TOOLBAR: int +FCW_TREE: int +FCW_INTERNETBAR: int +FCW_PROGRESS: int +FCT_MERGE: int +FCT_CONFIGABLE: int +FCT_ADDTOEND: int +CDBOSC_SETFOCUS: int +CDBOSC_KILLFOCUS: int +CDBOSC_SELCHANGE: int +CDBOSC_RENAME: int +SVSI_DESELECT: int +SVSI_SELECT: int +SVSI_EDIT: int +SVSI_DESELECTOTHERS: int +SVSI_ENSUREVISIBLE: int +SVSI_FOCUSED: int +SVSI_TRANSLATEPT: int +SVSI_SELECTIONMARK: int +SVSI_POSITIONITEM: int +SVSI_CHECK: int +SVSI_CHECK2: int +SVSI_KEYBOARDSELECT: int +SVSI_NOTAKEFOCUS: int +SVGIO_BACKGROUND: int +SVGIO_SELECTION: int +SVGIO_ALLVIEW: int +SVGIO_CHECKED: Incomplete +SVGIO_TYPE_MASK: Incomplete +SVGIO_FLAG_VIEWORDER: int +STRRET_WSTR: int +STRRET_OFFSET: int +STRRET_CSTR: int +CSIDL_DESKTOP: int +CSIDL_INTERNET: int +CSIDL_PROGRAMS: int +CSIDL_CONTROLS: int +CSIDL_PRINTERS: int +CSIDL_PERSONAL: int +CSIDL_FAVORITES: int +CSIDL_STARTUP: int +CSIDL_RECENT: int +CSIDL_SENDTO: int +CSIDL_BITBUCKET: int +CSIDL_STARTMENU: int +CSIDL_MYDOCUMENTS: int +CSIDL_MYMUSIC: int +CSIDL_MYVIDEO: int +CSIDL_DESKTOPDIRECTORY: int +CSIDL_DRIVES: int +CSIDL_NETWORK: int +CSIDL_NETHOOD: int +CSIDL_FONTS: int +CSIDL_TEMPLATES: int +CSIDL_COMMON_STARTMENU: int +CSIDL_COMMON_PROGRAMS: int +CSIDL_COMMON_STARTUP: int +CSIDL_COMMON_DESKTOPDIRECTORY: int +CSIDL_APPDATA: int +CSIDL_PRINTHOOD: int +CSIDL_LOCAL_APPDATA: int +CSIDL_ALTSTARTUP: int +CSIDL_COMMON_ALTSTARTUP: int +CSIDL_COMMON_FAVORITES: int +CSIDL_INTERNET_CACHE: int +CSIDL_COOKIES: int +CSIDL_HISTORY: int +CSIDL_COMMON_APPDATA: int +CSIDL_WINDOWS: int +CSIDL_SYSTEM: int +CSIDL_PROGRAM_FILES: int +CSIDL_MYPICTURES: int +CSIDL_PROFILE: int +CSIDL_SYSTEMX86: int +CSIDL_PROGRAM_FILESX86: int +CSIDL_PROGRAM_FILES_COMMON: int +CSIDL_PROGRAM_FILES_COMMONX86: int +CSIDL_COMMON_TEMPLATES: int +CSIDL_COMMON_DOCUMENTS: int +CSIDL_COMMON_ADMINTOOLS: int +CSIDL_ADMINTOOLS: int +CSIDL_CONNECTIONS: int +CSIDL_COMMON_MUSIC: int +CSIDL_COMMON_PICTURES: int +CSIDL_COMMON_VIDEO: int +CSIDL_RESOURCES: int +CSIDL_RESOURCES_LOCALIZED: int +CSIDL_COMMON_OEM_LINKS: int +CSIDL_CDBURN_AREA: int +CSIDL_COMPUTERSNEARME: int +BIF_RETURNONLYFSDIRS: int +BIF_DONTGOBELOWDOMAIN: int +BIF_STATUSTEXT: int +BIF_RETURNFSANCESTORS: int +BIF_EDITBOX: int +BIF_VALIDATE: int +BIF_BROWSEFORCOMPUTER: int +BIF_BROWSEFORPRINTER: int +BIF_BROWSEINCLUDEFILES: int +BFFM_INITIALIZED: int +BFFM_SELCHANGED: int +BFFM_VALIDATEFAILEDA: int +BFFM_VALIDATEFAILEDW: int +BFFM_SETSTATUSTEXTA: Incomplete +BFFM_ENABLEOK: Incomplete +BFFM_SETSELECTIONA: Incomplete +BFFM_SETSELECTIONW: Incomplete +BFFM_SETSTATUSTEXTW: Incomplete +BFFM_SETSTATUSTEXT: Incomplete +BFFM_SETSELECTION: Incomplete +BFFM_VALIDATEFAILED: int +SFGAO_CANCOPY: int +SFGAO_CANMOVE: int +SFGAO_CANLINK: int +SFGAO_CANRENAME: int +SFGAO_CANDELETE: int +SFGAO_HASPROPSHEET: int +SFGAO_DROPTARGET: int +SFGAO_CAPABILITYMASK: int +SFGAO_LINK: int +SFGAO_SHARE: int +SFGAO_READONLY: int +SFGAO_GHOSTED: int +SFGAO_HIDDEN: int +SFGAO_DISPLAYATTRMASK: int +SFGAO_FILESYSANCESTOR: int +SFGAO_FOLDER: int +SFGAO_FILESYSTEM: int +SFGAO_HASSUBFOLDER: int +SFGAO_CONTENTSMASK: int +SFGAO_VALIDATE: int +SFGAO_REMOVABLE: int +SFGAO_COMPRESSED: int +SFGAO_BROWSABLE: int +SFGAO_NONENUMERATED: int +SFGAO_NEWCONTENT: int +SFGAO_STORAGE: int +DWFRF_NORMAL: int +DWFRF_DELETECONFIGDATA: int +DWFAF_HIDDEN: int +DBIM_MINSIZE: int +DBIM_MAXSIZE: int +DBIM_INTEGRAL: int +DBIM_ACTUAL: int +DBIM_TITLE: int +DBIM_MODEFLAGS: int +DBIM_BKCOLOR: int +DBIMF_NORMAL: int +DBIMF_VARIABLEHEIGHT: int +DBIMF_DEBOSSED: int +DBIMF_BKCOLOR: int +DBIF_VIEWMODE_NORMAL: int +DBIF_VIEWMODE_VERTICAL: int +DBIF_VIEWMODE_FLOATING: int +DBIF_VIEWMODE_TRANSPARENT: int +COMPONENT_TOP: int +COMP_TYPE_HTMLDOC: int +COMP_TYPE_PICTURE: int +COMP_TYPE_WEBSITE: int +COMP_TYPE_CONTROL: int +COMP_TYPE_CFHTML: int +COMP_TYPE_MAX: int +AD_APPLY_SAVE: int +AD_APPLY_HTMLGEN: int +AD_APPLY_REFRESH: int +AD_APPLY_ALL: Incomplete +AD_APPLY_FORCE: int +AD_APPLY_BUFFERED_REFRESH: int +WPSTYLE_CENTER: int +WPSTYLE_TILE: int +WPSTYLE_STRETCH: int +WPSTYLE_MAX: int +COMP_ELEM_TYPE: int +COMP_ELEM_CHECKED: int +COMP_ELEM_DIRTY: int +COMP_ELEM_NOSCROLL: int +COMP_ELEM_POS_LEFT: int +COMP_ELEM_POS_TOP: int +COMP_ELEM_SIZE_WIDTH: int +COMP_ELEM_SIZE_HEIGHT: int +COMP_ELEM_POS_ZINDEX: int +COMP_ELEM_SOURCE: int +COMP_ELEM_FRIENDLYNAME: int +COMP_ELEM_SUBSCRIBEDURL: int +ADDURL_SILENT: int +CFSTR_SHELLIDLIST: str +CFSTR_SHELLIDLISTOFFSET: str +CFSTR_NETRESOURCES: str +CFSTR_FILEDESCRIPTORA: str +CFSTR_FILEDESCRIPTORW: str +CFSTR_FILECONTENTS: str +CFSTR_FILENAMEA: str +CFSTR_FILENAMEW: str +CFSTR_PRINTERGROUP: str +CFSTR_FILENAMEMAPA: str +CFSTR_FILENAMEMAPW: str +CFSTR_SHELLURL: str +CFSTR_INETURLA: str +CFSTR_INETURLW: str +CFSTR_PREFERREDDROPEFFECT: str +CFSTR_PERFORMEDDROPEFFECT: str +CFSTR_PASTESUCCEEDED: str +CFSTR_INDRAGLOOP: str +CFSTR_DRAGCONTEXT: str +CFSTR_MOUNTEDVOLUME: str +CFSTR_PERSISTEDDATAOBJECT: str +CFSTR_TARGETCLSID: str +CFSTR_LOGICALPERFORMEDDROPEFFECT: str +CFSTR_AUTOPLAY_SHELLIDLISTS: str +CFSTR_FILEDESCRIPTOR: str +CFSTR_FILENAME: str +CFSTR_FILENAMEMAP: str +DVASPECT_SHORTNAME: int +SHCNE_RENAMEITEM: int +SHCNE_CREATE: int +SHCNE_DELETE: int +SHCNE_MKDIR: int +SHCNE_RMDIR: int +SHCNE_MEDIAINSERTED: int +SHCNE_MEDIAREMOVED: int +SHCNE_DRIVEREMOVED: int +SHCNE_DRIVEADD: int +SHCNE_NETSHARE: int +SHCNE_NETUNSHARE: int +SHCNE_ATTRIBUTES: int +SHCNE_UPDATEDIR: int +SHCNE_UPDATEITEM: int +SHCNE_SERVERDISCONNECT: int +SHCNE_UPDATEIMAGE: int +SHCNE_DRIVEADDGUI: int +SHCNE_RENAMEFOLDER: int +SHCNE_FREESPACE: int +SHCNE_EXTENDED_EVENT: int +SHCNE_ASSOCCHANGED: int +SHCNE_DISKEVENTS: int +SHCNE_GLOBALEVENTS: int +SHCNE_ALLEVENTS: int +SHCNE_INTERRUPT: int +SHCNEE_ORDERCHANGED: int +SHCNF_IDLIST: int +SHCNF_PATHA: int +SHCNF_PRINTERA: int +SHCNF_DWORD: int +SHCNF_PATHW: int +SHCNF_PRINTERW: int +SHCNF_TYPE: int +SHCNF_FLUSH: int +SHCNF_FLUSHNOWAIT: int +SHCNF_PATH: int +SHCNF_PRINTER: int +QIF_CACHED: int +QIF_DONTEXPANDFOLDER: int +SWFO_NEEDDISPATCH: int +SWFO_INCLUDEPENDING: int +SWFO_COOKIEPASSED: int +SWC_EXPLORER: int +SWC_BROWSER: int +SWC_3RDPARTY: int +SWC_CALLBACK: int +SWC_DESKTOP: int +SHARD_PIDL: int +SHARD_PATHA: int +SHARD_PATHW: int +SHARD_APPIDINFO: int +SHARD_APPIDINFOIDLIST: int +SHARD_LINK: int +SHARD_APPIDINFOLINK: int +SHARD_SHELLITEM: int +SHARD_PATH: int +SHGDFIL_FINDDATA: int +SHGDFIL_NETRESOURCE: int +SHGDFIL_DESCRIPTIONID: int +SHDID_ROOT_REGITEM: int +SHDID_FS_FILE: int +SHDID_FS_DIRECTORY: int +SHDID_FS_OTHER: int +SHDID_COMPUTER_DRIVE35: int +SHDID_COMPUTER_DRIVE525: int +SHDID_COMPUTER_REMOVABLE: int +SHDID_COMPUTER_FIXED: int +SHDID_COMPUTER_NETDRIVE: int +SHDID_COMPUTER_CDROM: int +SHDID_COMPUTER_RAMDISK: int +SHDID_COMPUTER_OTHER: int +SHDID_NET_DOMAIN: int +SHDID_NET_SERVER: int +SHDID_NET_SHARE: int +SHDID_NET_RESTOFNET: int +SHDID_NET_OTHER: int +PID_IS_URL: int +PID_IS_NAME: int +PID_IS_WORKINGDIR: int +PID_IS_HOTKEY: int +PID_IS_SHOWCMD: int +PID_IS_ICONINDEX: int +PID_IS_ICONFILE: int +PID_IS_WHATSNEW: int +PID_IS_AUTHOR: int +PID_IS_DESCRIPTION: int +PID_IS_COMMENT: int +PID_INTSITE_WHATSNEW: int +PID_INTSITE_AUTHOR: int +PID_INTSITE_LASTVISIT: int +PID_INTSITE_LASTMOD: int +PID_INTSITE_VISITCOUNT: int +PID_INTSITE_DESCRIPTION: int +PID_INTSITE_COMMENT: int +PID_INTSITE_FLAGS: int +PID_INTSITE_CONTENTLEN: int +PID_INTSITE_CONTENTCODE: int +PID_INTSITE_RECURSE: int +PID_INTSITE_WATCH: int +PID_INTSITE_SUBSCRIPTION: int +PID_INTSITE_URL: int +PID_INTSITE_TITLE: int +PID_INTSITE_CODEPAGE: int +PID_INTSITE_TRACKING: int +PIDISF_RECENTLYCHANGED: int +PIDISF_CACHEDSTICKY: int +PIDISF_CACHEIMAGES: int +PIDISF_FOLLOWALLLINKS: int +PIDISM_GLOBAL: int +PIDISM_WATCH: int +PIDISM_DONTWATCH: int +SSF_SHOWALLOBJECTS: int +SSF_SHOWEXTENSIONS: int +SSF_SHOWCOMPCOLOR: int +SSF_SHOWSYSFILES: int +SSF_DOUBLECLICKINWEBVIEW: int +SSF_SHOWATTRIBCOL: int +SSF_DESKTOPHTML: int +SSF_WIN95CLASSIC: int +SSF_DONTPRETTYPATH: int +SSF_SHOWINFOTIP: int +SSF_MAPNETDRVBUTTON: int +SSF_NOCONFIRMRECYCLE: int +SSF_HIDEICONS: int +ABM_NEW: int +ABM_REMOVE: int +ABM_QUERYPOS: int +ABM_SETPOS: int +ABM_GETSTATE: int +ABM_GETTASKBARPOS: int +ABM_ACTIVATE: int +ABM_GETAUTOHIDEBAR: int +ABM_SETAUTOHIDEBAR: int +ABM_WINDOWPOSCHANGED: int +ABN_STATECHANGE: int +ABN_POSCHANGED: int +ABN_FULLSCREENAPP: int +ABN_WINDOWARRANGE: int +ABS_AUTOHIDE: int +ABS_ALWAYSONTOP: int +ABE_LEFT: int +ABE_TOP: int +ABE_RIGHT: int +ABE_BOTTOM: int + +def EIRESID(x): ... + +SHCONTF_FOLDERS: int +SHCONTF_NONFOLDERS: int +SHCONTF_INCLUDEHIDDEN: int +SHCONTF_INIT_ON_FIRST_NEXT: int +SHCONTF_NETPRINTERSRCH: int +SHCONTF_SHAREABLE: int +SHCONTF_STORAGE: int +SHGDN_NORMAL: int +SHGDN_INFOLDER: int +SHGDN_FOREDITING: int +SHGDN_INCLUDE_NONFILESYS: int +SHGDN_FORADDRESSBAR: int +SHGDN_FORPARSING: int +BFO_NONE: int +BFO_BROWSER_PERSIST_SETTINGS: int +BFO_RENAME_FOLDER_OPTIONS_TOINTERNET: int +BFO_BOTH_OPTIONS: int +BIF_PREFER_INTERNET_SHORTCUT: int +BFO_BROWSE_NO_IN_NEW_PROCESS: int +BFO_ENABLE_HYPERLINK_TRACKING: int +BFO_USE_IE_OFFLINE_SUPPORT: int +BFO_SUBSTITUE_INTERNET_START_PAGE: int +BFO_USE_IE_LOGOBANDING: int +BFO_ADD_IE_TOCAPTIONBAR: int +BFO_USE_DIALUP_REF: int +BFO_USE_IE_TOOLBAR: int +BFO_NO_PARENT_FOLDER_SUPPORT: int +BFO_NO_REOPEN_NEXT_RESTART: int +BFO_GO_HOME_PAGE: int +BFO_PREFER_IEPROCESS: int +BFO_SHOW_NAVIGATION_CANCELLED: int +BFO_QUERY_ALL: int +PID_FINDDATA: int +PID_NETRESOURCE: int +PID_DESCRIPTIONID: int +PID_WHICHFOLDER: int +PID_NETWORKLOCATION: int +PID_COMPUTERNAME: int +PID_DISPLACED_FROM: int +PID_DISPLACED_DATE: int +PID_SYNC_COPY_IN: int +PID_MISC_STATUS: int +PID_MISC_ACCESSCOUNT: int +PID_MISC_OWNER: int +PID_HTMLINFOTIPFILE: int +PID_MISC_PICS: int +PID_DISPLAY_PROPERTIES: int +PID_INTROTEXT: int +PIDSI_ARTIST: int +PIDSI_SONGTITLE: int +PIDSI_ALBUM: int +PIDSI_YEAR: int +PIDSI_COMMENT: int +PIDSI_TRACK: int +PIDSI_GENRE: int +PIDSI_LYRICS: int +PIDDRSI_PROTECTED: int +PIDDRSI_DESCRIPTION: int +PIDDRSI_PLAYCOUNT: int +PIDDRSI_PLAYSTARTS: int +PIDDRSI_PLAYEXPIRES: int +PIDVSI_STREAM_NAME: int +PIDVSI_FRAME_WIDTH: int +PIDVSI_FRAME_HEIGHT: int +PIDVSI_TIMELENGTH: int +PIDVSI_FRAME_COUNT: int +PIDVSI_FRAME_RATE: int +PIDVSI_DATA_RATE: int +PIDVSI_SAMPLE_SIZE: int +PIDVSI_COMPRESSION: int +PIDVSI_STREAM_NUMBER: int +PIDASI_FORMAT: int +PIDASI_TIMELENGTH: int +PIDASI_AVG_DATA_RATE: int +PIDASI_SAMPLE_RATE: int +PIDASI_SAMPLE_SIZE: int +PIDASI_CHANNEL_COUNT: int +PIDASI_STREAM_NUMBER: int +PIDASI_STREAM_NAME: int +PIDASI_COMPRESSION: int +PID_CONTROLPANEL_CATEGORY: int +PID_VOLUME_FREE: int +PID_VOLUME_CAPACITY: int +PID_VOLUME_FILESYSTEM: int +PID_SHARE_CSC_STATUS: int +PID_LINK_TARGET: int +PID_QUERY_RANK: int +PROPSETFLAG_DEFAULT: int +PROPSETFLAG_NONSIMPLE: int +PROPSETFLAG_ANSI: int +PROPSETFLAG_UNBUFFERED: int +PROPSETFLAG_CASE_SENSITIVE: int +PROPSET_BEHAVIOR_CASE_SENSITIVE: int +PID_DICTIONARY: int +PID_CODEPAGE: int +PID_FIRST_USABLE: int +PID_FIRST_NAME_DEFAULT: int +PID_LOCALE: int +PID_MODIFY_TIME: int +PID_SECURITY: int +PID_BEHAVIOR: int +PID_ILLEGAL: int +PID_MIN_READONLY: int +PID_MAX_READONLY: int +PIDDI_THUMBNAIL: int +PIDSI_TITLE: int +PIDSI_SUBJECT: int +PIDSI_AUTHOR: int +PIDSI_KEYWORDS: int +PIDSI_COMMENTS: int +PIDSI_TEMPLATE: int +PIDSI_LASTAUTHOR: int +PIDSI_REVNUMBER: int +PIDSI_EDITTIME: int +PIDSI_LASTPRINTED: int +PIDSI_CREATE_DTM: int +PIDSI_LASTSAVE_DTM: int +PIDSI_PAGECOUNT: int +PIDSI_WORDCOUNT: int +PIDSI_CHARCOUNT: int +PIDSI_THUMBNAIL: int +PIDSI_APPNAME: int +PIDSI_DOC_SECURITY: int +PIDDSI_CATEGORY: int +PIDDSI_PRESFORMAT: int +PIDDSI_BYTECOUNT: int +PIDDSI_LINECOUNT: int +PIDDSI_PARCOUNT: int +PIDDSI_SLIDECOUNT: int +PIDDSI_NOTECOUNT: int +PIDDSI_HIDDENCOUNT: int +PIDDSI_MMCLIPCOUNT: int +PIDDSI_SCALE: int +PIDDSI_HEADINGPAIR: int +PIDDSI_DOCPARTS: int +PIDDSI_MANAGER: int +PIDDSI_COMPANY: int +PIDDSI_LINKSDIRTY: int +PIDMSI_EDITOR: int +PIDMSI_SUPPLIER: int +PIDMSI_SOURCE: int +PIDMSI_SEQUENCE_NO: int +PIDMSI_PROJECT: int +PIDMSI_STATUS: int +PIDMSI_OWNER: int +PIDMSI_RATING: int +PIDMSI_PRODUCTION: int +PIDMSI_COPYRIGHT: int +PRSPEC_INVALID: int +PRSPEC_LPWSTR: int +PRSPEC_PROPID: int +SHCIDS_ALLFIELDS: int +SHCIDS_CANONICALONLY: int +SHCIDS_BITMASK: int +SHCIDS_COLUMNMASK: int +SFGAO_CANMONIKER: int +SFGAO_HASSTORAGE: int +SFGAO_STREAM: int +SFGAO_STORAGEANCESTOR: int +SFGAO_STORAGECAPMASK: int +MAXPROPPAGES: int +PSP_DEFAULT: int +PSP_DLGINDIRECT: int +PSP_USEHICON: int +PSP_USEICONID: int +PSP_USETITLE: int +PSP_RTLREADING: int +PSP_HASHELP: int +PSP_USEREFPARENT: int +PSP_USECALLBACK: int +PSP_PREMATURE: int +PSP_HIDEHEADER: int +PSP_USEHEADERTITLE: int +PSP_USEHEADERSUBTITLE: int +PSP_USEFUSIONCONTEXT: int +PSPCB_ADDREF: int +PSPCB_RELEASE: int +PSPCB_CREATE: int +PSH_DEFAULT: int +PSH_PROPTITLE: int +PSH_USEHICON: int +PSH_USEICONID: int +PSH_PROPSHEETPAGE: int +PSH_WIZARDHASFINISH: int +PSH_WIZARD: int +PSH_USEPSTARTPAGE: int +PSH_NOAPPLYNOW: int +PSH_USECALLBACK: int +PSH_HASHELP: int +PSH_MODELESS: int +PSH_RTLREADING: int +PSH_WIZARDCONTEXTHELP: int +PSH_WIZARD97: int +PSH_WATERMARK: int +PSH_USEHBMWATERMARK: int +PSH_USEHPLWATERMARK: int +PSH_STRETCHWATERMARK: int +PSH_HEADER: int +PSH_USEHBMHEADER: int +PSH_USEPAGELANG: int +PSH_WIZARD_LITE: int +PSH_NOCONTEXTHELP: int +PSCB_INITIALIZED: int +PSCB_PRECREATE: int +PSCB_BUTTONPRESSED: int +PSNRET_NOERROR: int +PSNRET_INVALID: int +PSNRET_INVALID_NOCHANGEPAGE: int +PSNRET_MESSAGEHANDLED: int +PSWIZB_BACK: int +PSWIZB_NEXT: int +PSWIZB_FINISH: int +PSWIZB_DISABLEDFINISH: int +PSBTN_BACK: int +PSBTN_NEXT: int +PSBTN_FINISH: int +PSBTN_OK: int +PSBTN_APPLYNOW: int +PSBTN_CANCEL: int +PSBTN_HELP: int +PSBTN_MAX: int +ID_PSRESTARTWINDOWS: int +ID_PSREBOOTSYSTEM: Incomplete +WIZ_CXDLG: int +WIZ_CYDLG: int +WIZ_CXBMP: int +WIZ_BODYX: int +WIZ_BODYCX: int +PROP_SM_CXDLG: int +PROP_SM_CYDLG: int +PROP_MED_CXDLG: int +PROP_MED_CYDLG: int +PROP_LG_CXDLG: int +PROP_LG_CYDLG: int +ISOLATION_AWARE_USE_STATIC_LIBRARY: int +ISOLATION_AWARE_BUILD_STATIC_LIBRARY: int +SHCOLSTATE_TYPE_STR: int +SHCOLSTATE_TYPE_INT: int +SHCOLSTATE_TYPE_DATE: int +SHCOLSTATE_TYPEMASK: int +SHCOLSTATE_ONBYDEFAULT: int +SHCOLSTATE_SLOW: int +SHCOLSTATE_EXTENDED: int +SHCOLSTATE_SECONDARYUI: int +SHCOLSTATE_HIDDEN: int +SHCOLSTATE_PREFER_VARCMP: int +FWF_AUTOARRANGE: int +FWF_ABBREVIATEDNAMES: int +FWF_SNAPTOGRID: int +FWF_OWNERDATA: int +FWF_BESTFITWINDOW: int +FWF_DESKTOP: int +FWF_SINGLESEL: int +FWF_NOSUBFOLDERS: int +FWF_TRANSPARENT: int +FWF_NOCLIENTEDGE: int +FWF_NOSCROLL: int +FWF_ALIGNLEFT: int +FWF_NOICONS: int +FWF_SHOWSELALWAYS: int +FWF_NOVISIBLE: int +FWF_SINGLECLICKACTIVATE: int +FWF_NOWEBVIEW: int +FWF_HIDEFILENAMES: int +FWF_CHECKSELECT: int +FVM_FIRST: int +FVM_ICON: int +FVM_SMALLICON: int +FVM_LIST: int +FVM_DETAILS: int +FVM_THUMBNAIL: int +FVM_TILE: int +FVM_THUMBSTRIP: int +SVUIA_DEACTIVATE: int +SVUIA_ACTIVATE_NOFOCUS: int +SVUIA_ACTIVATE_FOCUS: int +SVUIA_INPLACEACTIVATE: int +SHCNRF_InterruptLevel: int +SHCNRF_ShellLevel: int +SHCNRF_RecursiveInterrupt: int +SHCNRF_NewDelivery: int +FD_CLSID: int +FD_SIZEPOINT: int +FD_ATTRIBUTES: int +FD_CREATETIME: int +FD_ACCESSTIME: int +FD_WRITESTIME: int +FD_FILESIZE: int +FD_PROGRESSUI: int +FD_LINKUI: int +ASSOCF_INIT_NOREMAPCLSID: int +ASSOCF_INIT_BYEXENAME: int +ASSOCF_OPEN_BYEXENAME: int +ASSOCF_INIT_DEFAULTTOSTAR: int +ASSOCF_INIT_DEFAULTTOFOLDER: int +ASSOCF_NOUSERSETTINGS: int +ASSOCF_NOTRUNCATE: int +ASSOCF_VERIFY: int +ASSOCF_REMAPRUNDLL: int +ASSOCF_NOFIXUPS: int +ASSOCF_IGNOREBASECLASS: int +ASSOCSTR_COMMAND: int +ASSOCSTR_EXECUTABLE: int +ASSOCSTR_FRIENDLYDOCNAME: int +ASSOCSTR_FRIENDLYAPPNAME: int +ASSOCSTR_NOOPEN: int +ASSOCSTR_SHELLNEWVALUE: int +ASSOCSTR_DDECOMMAND: int +ASSOCSTR_DDEIFEXEC: int +ASSOCSTR_DDEAPPLICATION: int +ASSOCSTR_DDETOPIC: int +ASSOCSTR_INFOTIP: int +ASSOCSTR_QUICKTIP: int +ASSOCSTR_TILEINFO: int +ASSOCSTR_CONTENTTYPE: int +ASSOCSTR_DEFAULTICON: int +ASSOCSTR_SHELLEXTENSION: int +ASSOCKEY_SHELLEXECCLASS: int +ASSOCKEY_APP: int +ASSOCKEY_CLASS: int +ASSOCKEY_BASECLASS: int +ASSOCDATA_MSIDESCRIPTOR: int +ASSOCDATA_NOACTIVATEHANDLER: int +ASSOCDATA_QUERYCLASSSTORE: int +ASSOCDATA_HASPERUSERASSOC: int +ASSOCDATA_EDITFLAGS: int +ASSOCDATA_VALUE: int +SHGVSPB_PERUSER: int +SHGVSPB_ALLUSERS: int +SHGVSPB_PERFOLDER: int +SHGVSPB_ALLFOLDERS: int +SHGVSPB_INHERIT: int +SHGVSPB_ROAM: int +SHGVSPB_NOAUTODEFAULTS: int +SHGVSPB_FOLDER: Incomplete +SHGVSPB_FOLDERNODEFAULTS: Incomplete +SHGVSPB_USERDEFAULTS: Incomplete +SHGVSPB_GLOBALDEAFAULTS: Incomplete +SFVM_REARRANGE: int +SFVM_ADDOBJECT: int +SFVM_REMOVEOBJECT: int +SFVM_UPDATEOBJECT: int +SFVM_GETSELECTEDOBJECTS: int +SFVM_SETITEMPOS: int +SFVM_SETCLIPBOARD: int +SFVM_SETPOINTS: int +SLDF_HAS_ID_LIST: int +SLDF_HAS_LINK_INFO: int +SLDF_HAS_NAME: int +SLDF_HAS_RELPATH: int +SLDF_HAS_WORKINGDIR: int +SLDF_HAS_ARGS: int +SLDF_HAS_ICONLOCATION: int +SLDF_UNICODE: int +SLDF_FORCE_NO_LINKINFO: int +SLDF_HAS_EXP_SZ: int +SLDF_RUN_IN_SEPARATE: int +SLDF_HAS_LOGO3ID: int +SLDF_HAS_DARWINID: int +SLDF_RUNAS_USER: int +SLDF_NO_PIDL_ALIAS: int +SLDF_FORCE_UNCNAME: int +SLDF_HAS_EXP_ICON_SZ: int +SLDF_RUN_WITH_SHIMLAYER: int +SLDF_RESERVED: int +EXP_SPECIAL_FOLDER_SIG: int +NT_CONSOLE_PROPS_SIG: int +NT_FE_CONSOLE_PROPS_SIG: int +EXP_DARWIN_ID_SIG: int +EXP_LOGO3_ID_SIG: int +EXP_SZ_ICON_SIG: int +EXP_SZ_LINK_SIG: int +IURL_SETURL_FL_GUESS_PROTOCOL: int +IURL_SETURL_FL_USE_DEFAULT_PROTOCOL: int +IURL_INVOKECOMMAND_FL_ALLOW_UI: int +IURL_INVOKECOMMAND_FL_USE_DEFAULT_VERB: int +IURL_INVOKECOMMAND_FL_DDEWAIT: int +IS_NORMAL: int +IS_FULLSCREEN: int +IS_SPLIT: int +IS_VALIDSIZESTATEBITS: Incomplete +IS_VALIDSTATEBITS: Incomplete +AD_APPLY_DYNAMICREFRESH: int +COMP_ELEM_ORIGINAL_CSI: int +COMP_ELEM_RESTORED_CSI: int +COMP_ELEM_CURITEMSTATE: int +COMP_ELEM_ALL: Incomplete +DTI_ADDUI_DEFAULT: int +DTI_ADDUI_DISPSUBWIZARD: int +DTI_ADDUI_POSITIONITEM: int +COMPONENT_DEFAULT_LEFT: int +COMPONENT_DEFAULT_TOP: int +SSM_CLEAR: int +SSM_SET: int +SSM_REFRESH: int +SSM_UPDATE: int +SCHEME_DISPLAY: int +SCHEME_EDIT: int +SCHEME_LOCAL: int +SCHEME_GLOBAL: int +SCHEME_REFRESH: int +SCHEME_UPDATE: int +SCHEME_DONOTUSE: int +SCHEME_CREATE: int +GADOF_DIRTY: int +EVCF_HASSETTINGS: int +EVCF_ENABLEBYDEFAULT: int +EVCF_REMOVEFROMLIST: int +EVCF_ENABLEBYDEFAULT_AUTO: int +EVCF_DONTSHOWIFZERO: int +EVCF_SETTINGSMODE: int +EVCF_OUTOFDISKSPACE: int +EVCCBF_LASTNOTIFICATION: int +EBO_NONE: int +EBO_NAVIGATEONCE: int +EBO_SHOWFRAMES: int +EBO_ALWAYSNAVIGATE: int +EBO_NOTRAVELLOG: int +EBO_NOWRAPPERWINDOW: int +EBF_NONE: int +EBF_SELECTFROMDATAOBJECT: int +EBF_NODROPTARGET: int +ECS_ENABLED: int +ECS_DISABLED: int +ECS_HIDDEN: int +ECS_CHECKBOX: int +ECS_CHECKED: int +ECF_HASSUBCOMMANDS: int +ECF_HASSPLITBUTTON: int +ECF_HIDELABEL: int +ECF_ISSEPARATOR: int +ECF_HASLUASHIELD: int +SIATTRIBFLAGS_AND: int +SIATTRIBFLAGS_OR: int +SIATTRIBFLAGS_APPCOMPAT: int +SIATTRIBFLAGS_MASK: int +SIGDN_NORMALDISPLAY: int +SIGDN_PARENTRELATIVEPARSING: int +SIGDN_DESKTOPABSOLUTEPARSING: int +SIGDN_PARENTRELATIVEEDITING: int +SIGDN_DESKTOPABSOLUTEEDITING: int +SIGDN_FILESYSPATH: int +SIGDN_URL: int +SIGDN_PARENTRELATIVEFORADDRESSBAR: int +SIGDN_PARENTRELATIVE: int +SICHINT_DISPLAY: Incomplete +SICHINT_ALLFIELDS: int +SICHINT_CANONICAL: int +ASSOCCLASS_SHELL_KEY: int +ASSOCCLASS_PROGID_KEY: int +ASSOCCLASS_PROGID_STR: int +ASSOCCLASS_CLSID_KEY: int +ASSOCCLASS_CLSID_STR: int +ASSOCCLASS_APP_KEY: int +ASSOCCLASS_APP_STR: int +ASSOCCLASS_SYSTEM_STR: int +ASSOCCLASS_FOLDER: int +ASSOCCLASS_STAR: int +NSTCS_HASEXPANDOS: int +NSTCS_HASLINES: int +NSTCS_SINGLECLICKEXPAND: int +NSTCS_FULLROWSELECT: int +NSTCS_SPRINGEXPAND: int +NSTCS_HORIZONTALSCROLL: int +NSTCS_ROOTHASEXPANDO: int +NSTCS_SHOWSELECTIONALWAYS: int +NSTCS_NOINFOTIP: int +NSTCS_EVENHEIGHT: int +NSTCS_NOREPLACEOPEN: int +NSTCS_DISABLEDRAGDROP: int +NSTCS_NOORDERSTREAM: int +NSTCS_RICHTOOLTIP: int +NSTCS_BORDER: int +NSTCS_NOEDITLABELS: int +NSTCS_TABSTOP: int +NSTCS_FAVORITESMODE: int +NSTCS_AUTOHSCROLL: int +NSTCS_FADEINOUTEXPANDOS: int +NSTCS_EMPTYTEXT: int +NSTCS_CHECKBOXES: int +NSTCS_PARTIALCHECKBOXES: int +NSTCS_EXCLUSIONCHECKBOXES: int +NSTCS_DIMMEDCHECKBOXES: int +NSTCS_NOINDENTCHECKS: int +NSTCS_ALLOWJUNCTIONS: int +NSTCS_SHOWTABSBUTTON: int +NSTCS_SHOWDELETEBUTTON: int +NSTCS_SHOWREFRESHBUTTON: int +NSTCRS_VISIBLE: int +NSTCRS_HIDDEN: int +NSTCRS_EXPANDED: int +NSTCIS_NONE: int +NSTCIS_SELECTED: int +NSTCIS_EXPANDED: int +NSTCIS_BOLD: int +NSTCIS_DISABLED: int +NSTCGNI_NEXT: int +NSTCGNI_NEXTVISIBLE: int +NSTCGNI_PREV: int +NSTCGNI_PREVVISIBLE: int +NSTCGNI_PARENT: int +NSTCGNI_CHILD: int +NSTCGNI_FIRSTVISIBLE: int +NSTCGNI_LASTVISIBLE: int +CLSID_ExplorerBrowser: str +IBrowserFrame_Methods: Incomplete +ICategorizer_Methods: Incomplete +ICategoryProvider_Methods: Incomplete +IContextMenu_Methods: Incomplete +IExplorerCommand_Methods: Incomplete +IExplorerCommandProvider_Methods: Incomplete +IOleWindow_Methods: Incomplete +IPersist_Methods: Incomplete +IPersistFolder_Methods: Incomplete +IPersistFolder2_Methods: Incomplete +IShellExtInit_Methods: Incomplete +IShellView_Methods: Incomplete +IShellFolder_Methods: Incomplete +IShellFolder2_Methods: Incomplete +GPS_DEFAULT: int +GPS_HANDLERPROPERTIESONLY: int +GPS_READWRITE: int +GPS_TEMPORARY: int +GPS_FASTPROPERTIESONLY: int +GPS_OPENSLOWITEM: int +GPS_DELAYCREATION: int +GPS_BESTEFFORT: int +GPS_MASK_VALID: int +STR_AVOID_DRIVE_RESTRICTION_POLICY: str +STR_BIND_DELEGATE_CREATE_OBJECT: str +STR_BIND_FOLDERS_READ_ONLY: str +STR_BIND_FOLDER_ENUM_MODE: str +STR_BIND_FORCE_FOLDER_SHORTCUT_RESOLVE: str +STR_DONT_PARSE_RELATIVE: str +STR_DONT_RESOLVE_LINK: str +STR_FILE_SYS_BIND_DATA: str +STR_GET_ASYNC_HANDLER: str +STR_GPS_BESTEFFORT: str +STR_GPS_DELAYCREATION: str +STR_GPS_FASTPROPERTIESONLY: str +STR_GPS_HANDLERPROPERTIESONLY: str +STR_GPS_NO_OPLOCK: str +STR_GPS_OPENSLOWITEM: str +STR_IFILTER_FORCE_TEXT_FILTER_FALLBACK: str +STR_IFILTER_LOAD_DEFINED_FILTER: str +STR_INTERNAL_NAVIGATE: str +STR_INTERNETFOLDER_PARSE_ONLY_URLMON_BINDABLE: str +STR_ITEM_CACHE_CONTEXT: str +STR_NO_VALIDATE_FILENAME_CHARS: str +STR_PARSE_ALLOW_INTERNET_SHELL_FOLDERS: str +STR_PARSE_AND_CREATE_ITEM: str +STR_PARSE_DONT_REQUIRE_VALIDATED_URLS: str +STR_PARSE_EXPLICIT_ASSOCIATION_SUCCESSFUL: str +STR_PARSE_PARTIAL_IDLIST: str +STR_PARSE_PREFER_FOLDER_BROWSING: str +STR_PARSE_PREFER_WEB_BROWSING: str +STR_PARSE_PROPERTYSTORE: str +STR_PARSE_SHELL_PROTOCOL_TO_FILE_OBJECTS: str +STR_PARSE_SHOW_NET_DIAGNOSTICS_UI: str +STR_PARSE_SKIP_NET_CACHE: str +STR_PARSE_TRANSLATE_ALIASES: str +STR_PARSE_WITH_EXPLICIT_ASSOCAPP: str +STR_PARSE_WITH_EXPLICIT_PROGID: str +STR_PARSE_WITH_PROPERTIES: str +STR_SKIP_BINDING_CLSID: str +STR_TRACK_CLSID: str +KF_REDIRECTION_CAPABILITIES_ALLOW_ALL: int +KF_REDIRECTION_CAPABILITIES_REDIRECTABLE: int +KF_REDIRECTION_CAPABILITIES_DENY_ALL: int +KF_REDIRECTION_CAPABILITIES_DENY_POLICY_REDIRECTED: int +KF_REDIRECTION_CAPABILITIES_DENY_POLICY: int +KF_REDIRECTION_CAPABILITIES_DENY_PERMISSIONS: int +KF_REDIRECT_USER_EXCLUSIVE: int +KF_REDIRECT_COPY_SOURCE_DACL: int +KF_REDIRECT_OWNER_USER: int +KF_REDIRECT_SET_OWNER_EXPLICIT: int +KF_REDIRECT_CHECK_ONLY: int +KF_REDIRECT_WITH_UI: int +KF_REDIRECT_UNPIN: int +KF_REDIRECT_PIN: int +KF_REDIRECT_COPY_CONTENTS: int +KF_REDIRECT_DEL_SOURCE_CONTENTS: int +KF_REDIRECT_EXCLUDE_ALL_KNOWN_SUBFOLDERS: int +KF_CATEGORY_VIRTUAL: int +KF_CATEGORY_FIXED: int +KF_CATEGORY_COMMON: int +KF_CATEGORY_PERUSER: int +FFFP_EXACTMATCH: int +FFFP_NEARESTPARENTMATCH: int +KF_FLAG_CREATE: int +KF_FLAG_DONT_VERIFY: int +KF_FLAG_DONT_UNEXPAND: int +KF_FLAG_NO_ALIAS: int +KF_FLAG_INIT: int +KF_FLAG_DEFAULT_PATH: int +KF_FLAG_NOT_PARENT_RELATIVE: int +KF_FLAG_SIMPLE_IDLIST: int +ADLT_RECENT: int +ADLT_FREQUENT: int +KDC_FREQUENT: int +KDC_RECENT: int +LFF_FORCEFILESYSTEM: int +LFF_STORAGEITEMS: int +LFF_ALLITEMS: int +DSFT_DETECT: int +DSFT_PRIVATE: int +DSFT_PUBLIC: int +LOF_DEFAULT: int +LOF_PINNEDTONAVPANE: int +LOF_MASK_ALL: int +LSF_FAILIFTHERE: int +LSF_OVERRIDEEXISTING: int +LSF_MAKEUNIQUENAME: int +TSF_NORMAL: int +TSF_FAIL_EXIST: int +TSF_RENAME_EXIST: int +TSF_OVERWRITE_EXIST: int +TSF_ALLOW_DECRYPTION: int +TSF_NO_SECURITY: int +TSF_COPY_CREATION_TIME: int +TSF_COPY_WRITE_TIME: int +TSF_USE_FULL_ACCESS: int +TSF_DELETE_RECYCLE_IF_POSSIBLE: int +TSF_COPY_HARD_LINK: int +TSF_COPY_LOCALIZED_NAME: int +TSF_MOVE_AS_COPY_DELETE: int +TSF_SUSPEND_SHELLEVENTS: int +TS_NONE: int +TS_PERFORMING: int +TS_PREPARING: int +TS_INDETERMINATE: int +COPYENGINE_S_YES: int +COPYENGINE_S_NOT_HANDLED: int +COPYENGINE_S_USER_RETRY: int +COPYENGINE_S_USER_IGNORED: int +COPYENGINE_S_MERGE: int +COPYENGINE_S_DONT_PROCESS_CHILDREN: int +COPYENGINE_S_ALREADY_DONE: int +COPYENGINE_S_PENDING: int +COPYENGINE_S_KEEP_BOTH: int +COPYENGINE_S_CLOSE_PROGRAM: int +COPYENGINE_S_COLLISIONRESOLVED: int +COPYENGINE_E_USER_CANCELLED: int +COPYENGINE_E_CANCELLED: int +COPYENGINE_E_REQUIRES_ELEVATION: int +COPYENGINE_E_SAME_FILE: int +COPYENGINE_E_DIFF_DIR: int +COPYENGINE_E_MANY_SRC_1_DEST: int +COPYENGINE_E_DEST_SUBTREE: int +COPYENGINE_E_DEST_SAME_TREE: int +COPYENGINE_E_FLD_IS_FILE_DEST: int +COPYENGINE_E_FILE_IS_FLD_DEST: int +COPYENGINE_E_FILE_TOO_LARGE: int +COPYENGINE_E_REMOVABLE_FULL: int +COPYENGINE_E_DEST_IS_RO_CD: int +COPYENGINE_E_DEST_IS_RW_CD: int +COPYENGINE_E_DEST_IS_R_CD: int +COPYENGINE_E_DEST_IS_RO_DVD: int +COPYENGINE_E_DEST_IS_RW_DVD: int +COPYENGINE_E_DEST_IS_R_DVD: int +COPYENGINE_E_SRC_IS_RO_CD: int +COPYENGINE_E_SRC_IS_RW_CD: int +COPYENGINE_E_SRC_IS_R_CD: int +COPYENGINE_E_SRC_IS_RO_DVD: int +COPYENGINE_E_SRC_IS_RW_DVD: int +COPYENGINE_E_SRC_IS_R_DVD: int +COPYENGINE_E_INVALID_FILES_SRC: int +COPYENGINE_E_INVALID_FILES_DEST: int +COPYENGINE_E_PATH_TOO_DEEP_SRC: int +COPYENGINE_E_PATH_TOO_DEEP_DEST: int +COPYENGINE_E_ROOT_DIR_SRC: int +COPYENGINE_E_ROOT_DIR_DEST: int +COPYENGINE_E_ACCESS_DENIED_SRC: int +COPYENGINE_E_ACCESS_DENIED_DEST: int +COPYENGINE_E_PATH_NOT_FOUND_SRC: int +COPYENGINE_E_PATH_NOT_FOUND_DEST: int +COPYENGINE_E_NET_DISCONNECT_SRC: int +COPYENGINE_E_NET_DISCONNECT_DEST: int +COPYENGINE_E_SHARING_VIOLATION_SRC: int +COPYENGINE_E_SHARING_VIOLATION_DEST: int +COPYENGINE_E_ALREADY_EXISTS_NORMAL: int +COPYENGINE_E_ALREADY_EXISTS_READONLY: int +COPYENGINE_E_ALREADY_EXISTS_SYSTEM: int +COPYENGINE_E_ALREADY_EXISTS_FOLDER: int +COPYENGINE_E_STREAM_LOSS: int +COPYENGINE_E_EA_LOSS: int +COPYENGINE_E_PROPERTY_LOSS: int +COPYENGINE_E_PROPERTIES_LOSS: int +COPYENGINE_E_ENCRYPTION_LOSS: int +COPYENGINE_E_DISK_FULL: int +COPYENGINE_E_DISK_FULL_CLEAN: int +COPYENGINE_E_EA_NOT_SUPPORTED: int +COPYENGINE_E_CANT_REACH_SOURCE: int +COPYENGINE_E_RECYCLE_UNKNOWN_ERROR: int +COPYENGINE_E_RECYCLE_FORCE_NUKE: int +COPYENGINE_E_RECYCLE_SIZE_TOO_BIG: int +COPYENGINE_E_RECYCLE_PATH_TOO_LONG: int +COPYENGINE_E_RECYCLE_BIN_NOT_FOUND: int +COPYENGINE_E_NEWFILE_NAME_TOO_LONG: int +COPYENGINE_E_NEWFOLDER_NAME_TOO_LONG: int +COPYENGINE_E_DIR_NOT_EMPTY: int +COPYENGINE_E_FAT_MAX_IN_ROOT: int +COPYENGINE_E_ACCESSDENIED_READONLY: int +COPYENGINE_E_REDIRECTED_TO_WEBPAGE: int +COPYENGINE_E_SERVER_BAD_FILE_TYPE: int +FOLDERID_NetworkFolder: str +FOLDERID_ComputerFolder: str +FOLDERID_InternetFolder: str +FOLDERID_ControlPanelFolder: str +FOLDERID_PrintersFolder: str +FOLDERID_SyncManagerFolder: str +FOLDERID_SyncSetupFolder: str +FOLDERID_ConflictFolder: str +FOLDERID_SyncResultsFolder: str +FOLDERID_RecycleBinFolder: str +FOLDERID_ConnectionsFolder: str +FOLDERID_Fonts: str +FOLDERID_Desktop: str +FOLDERID_Startup: str +FOLDERID_Programs: str +FOLDERID_StartMenu: str +FOLDERID_Recent: str +FOLDERID_SendTo: str +FOLDERID_Documents: str +FOLDERID_Favorites: str +FOLDERID_NetHood: str +FOLDERID_PrintHood: str +FOLDERID_Templates: str +FOLDERID_CommonStartup: str +FOLDERID_CommonPrograms: str +FOLDERID_CommonStartMenu: str +FOLDERID_PublicDesktop: str +FOLDERID_ProgramData: str +FOLDERID_CommonTemplates: str +FOLDERID_PublicDocuments: str +FOLDERID_RoamingAppData: str +FOLDERID_LocalAppData: str +FOLDERID_LocalAppDataLow: str +FOLDERID_InternetCache: str +FOLDERID_Cookies: str +FOLDERID_History: str +FOLDERID_System: str +FOLDERID_SystemX86: str +FOLDERID_Windows: str +FOLDERID_Profile: str +FOLDERID_Pictures: str +FOLDERID_ProgramFilesX86: str +FOLDERID_ProgramFilesCommonX86: str +FOLDERID_ProgramFilesX64: str +FOLDERID_ProgramFilesCommonX64: str +FOLDERID_ProgramFiles: str +FOLDERID_ProgramFilesCommon: str +FOLDERID_UserProgramFiles: str +FOLDERID_UserProgramFilesCommon: str +FOLDERID_AdminTools: str +FOLDERID_CommonAdminTools: str +FOLDERID_Music: str +FOLDERID_Videos: str +FOLDERID_Ringtones: str +FOLDERID_PublicPictures: str +FOLDERID_PublicMusic: str +FOLDERID_PublicVideos: str +FOLDERID_PublicRingtones: str +FOLDERID_ResourceDir: str +FOLDERID_LocalizedResourcesDir: str +FOLDERID_CommonOEMLinks: str +FOLDERID_CDBurning: str +FOLDERID_UserProfiles: str +FOLDERID_Playlists: str +FOLDERID_SamplePlaylists: str +FOLDERID_SampleMusic: str +FOLDERID_SamplePictures: str +FOLDERID_SampleVideos: str +FOLDERID_PhotoAlbums: str +FOLDERID_Public: str +FOLDERID_ChangeRemovePrograms: str +FOLDERID_AppUpdates: str +FOLDERID_AddNewPrograms: str +FOLDERID_Downloads: str +FOLDERID_PublicDownloads: str +FOLDERID_SavedSearches: str +FOLDERID_QuickLaunch: str +FOLDERID_Contacts: str +FOLDERID_SidebarParts: str +FOLDERID_SidebarDefaultParts: str +FOLDERID_PublicGameTasks: str +FOLDERID_GameTasks: str +FOLDERID_SavedGames: str +FOLDERID_Games: str +FOLDERID_SEARCH_MAPI: str +FOLDERID_SEARCH_CSC: str +FOLDERID_Links: str +FOLDERID_UsersFiles: str +FOLDERID_UsersLibraries: str +FOLDERID_SearchHome: str +FOLDERID_OriginalImages: str +FOLDERID_DocumentsLibrary: str +FOLDERID_MusicLibrary: str +FOLDERID_PicturesLibrary: str +FOLDERID_VideosLibrary: str +FOLDERID_RecordedTVLibrary: str +FOLDERID_HomeGroup: str +FOLDERID_HomeGroupCurrentUser: str +FOLDERID_DeviceMetadataStore: str +FOLDERID_Libraries: str +FOLDERID_PublicLibraries: str +FOLDERID_UserPinned: str +FOLDERID_ImplicitAppShortcuts: str +FOLDERID_AccountPictures: str +FOLDERID_PublicUserTiles: str +FOLDERID_AppsFolder: str +FOLDERID_StartMenuAllPrograms: str +FOLDERID_CommonStartMenuPlaces: str +FOLDERID_ApplicationShortcuts: str +FOLDERID_RoamingTiles: str +FOLDERID_RoamedTileImages: str +FOLDERID_Screenshots: str +FOLDERID_CameraRoll: str +FOLDERID_SkyDrive: str +FOLDERID_OneDrive: str +FOLDERID_SkyDriveDocuments: str +FOLDERID_SkyDrivePictures: str +FOLDERID_SkyDriveMusic: str +FOLDERID_SkyDriveCameraRoll: str +FOLDERID_SearchHistory: str +FOLDERID_SearchTemplates: str +FOLDERID_CameraRollLibrary: str +FOLDERID_SavedPictures: str +FOLDERID_SavedPicturesLibrary: str +FOLDERID_RetailDemo: str +FOLDERID_Device: str +FOLDERID_DevelopmentFiles: str +FOLDERID_Objects3D: str +FOLDERID_AppCaptures: str +FOLDERID_LocalDocuments: str +FOLDERID_LocalPictures: str +FOLDERID_LocalVideos: str +FOLDERID_LocalMusic: str +FOLDERID_LocalDownloads: str +FOLDERID_RecordedCalls: str +KF_FLAG_DEFAULT: int +KF_FLAG_FORCE_APP_DATA_REDIRECTION: int +KF_FLAG_RETURN_FILTER_REDIRECTION_TARGET: int +KF_FLAG_FORCE_PACKAGE_REDIRECTION: int +KF_FLAG_NO_PACKAGE_REDIRECTION: int +KF_FLAG_FORCE_APPCONTAINER_REDIRECTION: int +KF_FLAG_NO_APPCONTAINER_REDIRECTION: int +KF_FLAG_ALIAS_ONLY: int diff --git a/stubs/pywin32/win32comext/taskscheduler/__init__.pyi b/stubs/pywin32/win32comext/taskscheduler/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi b/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi new file mode 100644 index 000000000000..b37d72241d5d --- /dev/null +++ b/stubs/pywin32/win32comext/taskscheduler/taskscheduler.pyi @@ -0,0 +1,83 @@ +import _win32typing + +CLSID_CTask: _win32typing.PyIID +CLSID_CTaskScheduler: _win32typing.PyIID +HIGH_PRIORITY_CLASS: int +IDLE_PRIORITY_CLASS: int +IID_IProvideTaskPage: _win32typing.PyIID +IID_IScheduledWorkItem: _win32typing.PyIID +IID_ITask: _win32typing.PyIID +IID_ITaskScheduler: _win32typing.PyIID +IID_ITaskTrigger: _win32typing.PyIID +NORMAL_PRIORITY_CLASS: int +REALTIME_PRIORITY_CLASS: int +SCHED_E_ACCOUNT_DBASE_CORRUPT: int +SCHED_E_ACCOUNT_INFORMATION_NOT_SET: int +SCHED_E_ACCOUNT_NAME_NOT_FOUND: int +SCHED_E_CANNOT_OPEN_TASK: int +SCHED_E_INVALID_TASK: int +SCHED_E_SERVICE_NOT_INSTALLED: int +SCHED_E_TASK_NOT_READY: int +SCHED_E_TASK_NOT_RUNNING: int +SCHED_E_TRIGGER_NOT_FOUND: int +SCHED_E_UNKNOWN_OBJECT_VERSION: int +SCHED_S_EVENT_TRIGGER: int +SCHED_S_TASK_DISABLED: int +SCHED_S_TASK_HAS_NOT_RUN: int +SCHED_S_TASK_NOT_SCHEDULED: int +SCHED_S_TASK_NO_MORE_RUNS: int +SCHED_S_TASK_NO_VALID_TRIGGERS: int +SCHED_S_TASK_READY: int +SCHED_S_TASK_RUNNING: int +SCHED_S_TASK_TERMINATED: int +TASKPAGE_SCHEDULE: int +TASKPAGE_SETTINGS: int +TASKPAGE_TASK: int +TASK_APRIL: int +TASK_AUGUST: int +TASK_DECEMBER: int +TASK_EVENT_TRIGGER_AT_LOGON: int +TASK_EVENT_TRIGGER_AT_SYSTEMSTART: int +TASK_EVENT_TRIGGER_ON_IDLE: int +TASK_FEBRUARY: int +TASK_FIRST_WEEK: int +TASK_FLAG_DELETE_WHEN_DONE: int +TASK_FLAG_DISABLED: int +TASK_FLAG_DONT_START_IF_ON_BATTERIES: int +TASK_FLAG_HIDDEN: int +TASK_FLAG_INTERACTIVE: int +TASK_FLAG_KILL_IF_GOING_ON_BATTERIES: int +TASK_FLAG_KILL_ON_IDLE_END: int +TASK_FLAG_RESTART_ON_IDLE_RESUME: int +TASK_FLAG_RUN_IF_CONNECTED_TO_INTERNET: int +TASK_FLAG_RUN_ONLY_IF_DOCKED: int +TASK_FLAG_RUN_ONLY_IF_LOGGED_ON: int +TASK_FLAG_START_ONLY_IF_IDLE: int +TASK_FLAG_SYSTEM_REQUIRED: int +TASK_FOURTH_WEEK: int +TASK_FRIDAY: int +TASK_JANUARY: int +TASK_JULY: int +TASK_JUNE: int +TASK_LAST_WEEK: int +TASK_MARCH: int +TASK_MAY: int +TASK_MONDAY: int +TASK_NOVEMBER: int +TASK_OCTOBER: int +TASK_SATURDAY: int +TASK_SECOND_WEEK: int +TASK_SEPTEMBER: int +TASK_SUNDAY: int +TASK_THIRD_WEEK: int +TASK_THURSDAY: int +TASK_TIME_TRIGGER_DAILY: int +TASK_TIME_TRIGGER_MONTHLYDATE: int +TASK_TIME_TRIGGER_MONTHLYDOW: int +TASK_TIME_TRIGGER_ONCE: int +TASK_TIME_TRIGGER_WEEKLY: int +TASK_TRIGGER_FLAG_DISABLED: int +TASK_TRIGGER_FLAG_HAS_END_DATE: int +TASK_TRIGGER_FLAG_KILL_AT_DURATION_END: int +TASK_TUESDAY: int +TASK_WEDNESDAY: int diff --git a/stubs/pywin32/win32con.pyi b/stubs/pywin32/win32con.pyi new file mode 100644 index 000000000000..54cfd26a805f --- /dev/null +++ b/stubs/pywin32/win32con.pyi @@ -0,0 +1 @@ +from win32.lib.win32con import * diff --git a/stubs/pywin32/win32console.pyi b/stubs/pywin32/win32console.pyi new file mode 100644 index 000000000000..f8539ed68b25 --- /dev/null +++ b/stubs/pywin32/win32console.pyi @@ -0,0 +1 @@ +from win32.win32console import * diff --git a/stubs/pywin32/win32cred.pyi b/stubs/pywin32/win32cred.pyi new file mode 100644 index 000000000000..6cb3e268e445 --- /dev/null +++ b/stubs/pywin32/win32cred.pyi @@ -0,0 +1 @@ +from win32.win32cred import * diff --git a/stubs/pywin32/win32crypt.pyi b/stubs/pywin32/win32crypt.pyi new file mode 100644 index 000000000000..223df5e3f82c --- /dev/null +++ b/stubs/pywin32/win32crypt.pyi @@ -0,0 +1 @@ +from win32.win32crypt import * diff --git a/stubs/pywin32/win32cryptcon.pyi b/stubs/pywin32/win32cryptcon.pyi new file mode 100644 index 000000000000..6df8b4407775 --- /dev/null +++ b/stubs/pywin32/win32cryptcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32cryptcon import * diff --git a/stubs/pywin32/win32event.pyi b/stubs/pywin32/win32event.pyi new file mode 100644 index 000000000000..53191d417c02 --- /dev/null +++ b/stubs/pywin32/win32event.pyi @@ -0,0 +1 @@ +from win32.win32event import * diff --git a/stubs/pywin32/win32evtlog.pyi b/stubs/pywin32/win32evtlog.pyi new file mode 100644 index 000000000000..7c7ffe5ca0e5 --- /dev/null +++ b/stubs/pywin32/win32evtlog.pyi @@ -0,0 +1 @@ +from win32.win32evtlog import * diff --git a/stubs/pywin32/win32evtlogutil.pyi b/stubs/pywin32/win32evtlogutil.pyi new file mode 100644 index 000000000000..c37e5dd7b8af --- /dev/null +++ b/stubs/pywin32/win32evtlogutil.pyi @@ -0,0 +1 @@ +from win32.lib.win32evtlogutil import * diff --git a/stubs/pywin32/win32file.pyi b/stubs/pywin32/win32file.pyi new file mode 100644 index 000000000000..3a703a9739bc --- /dev/null +++ b/stubs/pywin32/win32file.pyi @@ -0,0 +1 @@ +from win32.win32file import * diff --git a/stubs/pywin32/win32gui.pyi b/stubs/pywin32/win32gui.pyi new file mode 100644 index 000000000000..3b2b41ae5c01 --- /dev/null +++ b/stubs/pywin32/win32gui.pyi @@ -0,0 +1 @@ +from win32.win32gui import * diff --git a/stubs/pywin32/win32gui_struct.pyi b/stubs/pywin32/win32gui_struct.pyi new file mode 100644 index 000000000000..3c7cd0a8a581 --- /dev/null +++ b/stubs/pywin32/win32gui_struct.pyi @@ -0,0 +1 @@ +from win32.lib.win32gui_struct import * diff --git a/stubs/pywin32/win32help.pyi b/stubs/pywin32/win32help.pyi new file mode 100644 index 000000000000..bd6fce5076c5 --- /dev/null +++ b/stubs/pywin32/win32help.pyi @@ -0,0 +1 @@ +from win32.win32help import * diff --git a/stubs/pywin32/win32inet.pyi b/stubs/pywin32/win32inet.pyi new file mode 100644 index 000000000000..98e6e47ff79a --- /dev/null +++ b/stubs/pywin32/win32inet.pyi @@ -0,0 +1 @@ +from win32.win32inet import * diff --git a/stubs/pywin32/win32inetcon.pyi b/stubs/pywin32/win32inetcon.pyi new file mode 100644 index 000000000000..db893b68d327 --- /dev/null +++ b/stubs/pywin32/win32inetcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32inetcon import * diff --git a/stubs/pywin32/win32job.pyi b/stubs/pywin32/win32job.pyi new file mode 100644 index 000000000000..9c8f7891eb3d --- /dev/null +++ b/stubs/pywin32/win32job.pyi @@ -0,0 +1 @@ +from win32.win32job import * diff --git a/stubs/pywin32/win32lz.pyi b/stubs/pywin32/win32lz.pyi new file mode 100644 index 000000000000..64281098af98 --- /dev/null +++ b/stubs/pywin32/win32lz.pyi @@ -0,0 +1 @@ +from win32.win32lz import * diff --git a/stubs/pywin32/win32net.pyi b/stubs/pywin32/win32net.pyi new file mode 100644 index 000000000000..f318e55d74f0 --- /dev/null +++ b/stubs/pywin32/win32net.pyi @@ -0,0 +1 @@ +from win32.win32net import * diff --git a/stubs/pywin32/win32netcon.pyi b/stubs/pywin32/win32netcon.pyi new file mode 100644 index 000000000000..f86b2ef4ba93 --- /dev/null +++ b/stubs/pywin32/win32netcon.pyi @@ -0,0 +1 @@ +from win32.lib.win32netcon import * diff --git a/stubs/pywin32/win32pdh.pyi b/stubs/pywin32/win32pdh.pyi new file mode 100644 index 000000000000..739ad216e73f --- /dev/null +++ b/stubs/pywin32/win32pdh.pyi @@ -0,0 +1 @@ +from win32.win32pdh import * diff --git a/stubs/pywin32/win32pdhquery.pyi b/stubs/pywin32/win32pdhquery.pyi new file mode 100644 index 000000000000..2d0976fbbdac --- /dev/null +++ b/stubs/pywin32/win32pdhquery.pyi @@ -0,0 +1 @@ +from win32.lib.win32pdhquery import * diff --git a/stubs/pywin32/win32pipe.pyi b/stubs/pywin32/win32pipe.pyi new file mode 100644 index 000000000000..bf607d6b0d76 --- /dev/null +++ b/stubs/pywin32/win32pipe.pyi @@ -0,0 +1 @@ +from win32.win32pipe import * diff --git a/stubs/pywin32/win32print.pyi b/stubs/pywin32/win32print.pyi new file mode 100644 index 000000000000..ad2515011cce --- /dev/null +++ b/stubs/pywin32/win32print.pyi @@ -0,0 +1 @@ +from win32.win32print import * diff --git a/stubs/pywin32/win32process.pyi b/stubs/pywin32/win32process.pyi new file mode 100644 index 000000000000..86b050b2b958 --- /dev/null +++ b/stubs/pywin32/win32process.pyi @@ -0,0 +1 @@ +from win32.win32process import * diff --git a/stubs/pywin32/win32profile.pyi b/stubs/pywin32/win32profile.pyi new file mode 100644 index 000000000000..b89eef14bbe1 --- /dev/null +++ b/stubs/pywin32/win32profile.pyi @@ -0,0 +1 @@ +from win32.win32profile import * diff --git a/stubs/pywin32/win32ras.pyi b/stubs/pywin32/win32ras.pyi new file mode 100644 index 000000000000..455d2763b253 --- /dev/null +++ b/stubs/pywin32/win32ras.pyi @@ -0,0 +1 @@ +from win32.win32ras import * diff --git a/stubs/pywin32/win32security.pyi b/stubs/pywin32/win32security.pyi new file mode 100644 index 000000000000..bc0b8d20e5ef --- /dev/null +++ b/stubs/pywin32/win32security.pyi @@ -0,0 +1 @@ +from win32.win32security import * diff --git a/stubs/pywin32/win32service.pyi b/stubs/pywin32/win32service.pyi new file mode 100644 index 000000000000..b98158e9ab96 --- /dev/null +++ b/stubs/pywin32/win32service.pyi @@ -0,0 +1 @@ +from win32.win32service import * diff --git a/stubs/pywin32/win32serviceutil.pyi b/stubs/pywin32/win32serviceutil.pyi new file mode 100644 index 000000000000..1e989b027342 --- /dev/null +++ b/stubs/pywin32/win32serviceutil.pyi @@ -0,0 +1 @@ +from win32.lib.win32serviceutil import * diff --git a/stubs/pywin32/win32timezone.pyi b/stubs/pywin32/win32timezone.pyi new file mode 100644 index 000000000000..bd22d6774596 --- /dev/null +++ b/stubs/pywin32/win32timezone.pyi @@ -0,0 +1 @@ +from win32.lib.win32timezone import * diff --git a/stubs/pywin32/win32trace.pyi b/stubs/pywin32/win32trace.pyi new file mode 100644 index 000000000000..3ece62970b26 --- /dev/null +++ b/stubs/pywin32/win32trace.pyi @@ -0,0 +1 @@ +from win32.win32trace import * diff --git a/stubs/pywin32/win32transaction.pyi b/stubs/pywin32/win32transaction.pyi new file mode 100644 index 000000000000..bd529b0919a1 --- /dev/null +++ b/stubs/pywin32/win32transaction.pyi @@ -0,0 +1 @@ +from win32.win32transaction import * diff --git a/stubs/pywin32/win32ts.pyi b/stubs/pywin32/win32ts.pyi new file mode 100644 index 000000000000..dd0d8a231ffd --- /dev/null +++ b/stubs/pywin32/win32ts.pyi @@ -0,0 +1 @@ +from win32.win32ts import * diff --git a/stubs/pywin32/win32ui.pyi b/stubs/pywin32/win32ui.pyi new file mode 100644 index 000000000000..49ea5db902f4 --- /dev/null +++ b/stubs/pywin32/win32ui.pyi @@ -0,0 +1 @@ +from pythonwin.win32ui import * diff --git a/stubs/pywin32/win32uiole.pyi b/stubs/pywin32/win32uiole.pyi new file mode 100644 index 000000000000..b0ae818da649 --- /dev/null +++ b/stubs/pywin32/win32uiole.pyi @@ -0,0 +1 @@ +from pythonwin.win32uiole import * diff --git a/stubs/pywin32/win32verstamp.pyi b/stubs/pywin32/win32verstamp.pyi new file mode 100644 index 000000000000..a1f2de1e1c08 --- /dev/null +++ b/stubs/pywin32/win32verstamp.pyi @@ -0,0 +1 @@ +from win32.lib.win32verstamp import * diff --git a/stubs/pywin32/win32wnet.pyi b/stubs/pywin32/win32wnet.pyi new file mode 100644 index 000000000000..67facc0ca7b5 --- /dev/null +++ b/stubs/pywin32/win32wnet.pyi @@ -0,0 +1 @@ +from win32.win32wnet import * diff --git a/stubs/pywin32/winerror.pyi b/stubs/pywin32/winerror.pyi new file mode 100644 index 000000000000..d0bdce6c46ed --- /dev/null +++ b/stubs/pywin32/winerror.pyi @@ -0,0 +1 @@ +from win32.lib.winerror import * diff --git a/stubs/pywin32/winioctlcon.pyi b/stubs/pywin32/winioctlcon.pyi new file mode 100644 index 000000000000..6e51730f91b1 --- /dev/null +++ b/stubs/pywin32/winioctlcon.pyi @@ -0,0 +1 @@ +from win32.lib.winioctlcon import * diff --git a/stubs/pywin32/winnt.pyi b/stubs/pywin32/winnt.pyi new file mode 100644 index 000000000000..8bbdea596d2f --- /dev/null +++ b/stubs/pywin32/winnt.pyi @@ -0,0 +1 @@ +from win32.lib.winnt import * diff --git a/stubs/pywin32/winperf.pyi b/stubs/pywin32/winperf.pyi new file mode 100644 index 000000000000..d3138f48c8bd --- /dev/null +++ b/stubs/pywin32/winperf.pyi @@ -0,0 +1 @@ +from win32.lib.winperf import * diff --git a/stubs/pywin32/winxpgui.pyi b/stubs/pywin32/winxpgui.pyi new file mode 100644 index 000000000000..9a8e6233d577 --- /dev/null +++ b/stubs/pywin32/winxpgui.pyi @@ -0,0 +1 @@ +from win32.winxpgui import * diff --git a/stubs/pywin32/winxptheme.pyi b/stubs/pywin32/winxptheme.pyi new file mode 100644 index 000000000000..e4b09f60be7e --- /dev/null +++ b/stubs/pywin32/winxptheme.pyi @@ -0,0 +1 @@ +from win32.lib.winxptheme import * diff --git a/stubs/pyxdg/@tests/stubtest_allowlist.txt b/stubs/pyxdg/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..18311a04da36 --- /dev/null +++ b/stubs/pyxdg/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +xdg.IconTheme.basedir # This is a side-effect of a for loop rather than an intended part of the API. +xdg.DesktopEntry.DesktopEntry.checkCategorie # Exists for backwards compatibility. diff --git a/stubs/pyxdg/@tests/test_cases/check_IniFile.py b/stubs/pyxdg/@tests/test_cases/check_IniFile.py new file mode 100644 index 000000000000..d73d09a04dc1 --- /dev/null +++ b/stubs/pyxdg/@tests/test_cases/check_IniFile.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +import re +from typing import List, Tuple +from typing_extensions import assert_type + +from xdg.IniFile import IniFile + +# The "get" method is quite complex with many overloads. Check that many forms +# are valid. +# The function definition is: +# def get(self, key, group=None, locale=False, type="string", list=False, strict=False): + +# Get str +assert_type(IniFile().get("some_key"), str) +assert_type(IniFile().get("some_key", None), str) +assert_type(IniFile().get("some_key", "group"), str) +assert_type(IniFile().get("some_key", "group", False), str) +assert_type(IniFile().get("some_key", "group", True), str) +assert_type(IniFile().get("some_key", "group", True, "string"), str) +assert_type(IniFile().get("some_key", "group", True, "string", False), str) +assert_type(IniFile().get("some_key", "group", True, "string", False, False), str) +assert_type(IniFile().get("some_key", "group", True, "string", False, True), str) +# Keyword parameters +assert_type(IniFile().get("some_key", group=None), str) +assert_type(IniFile().get("some_key", group="group"), str) +assert_type(IniFile().get("some_key", locale=False), str) +assert_type(IniFile().get("some_key", locale=True), str) +assert_type(IniFile().get("some_key", strict=False), str) +assert_type(IniFile().get("some_key", strict=True), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True), str) +# Explicitly set type as string in keyword parameters. +assert_type(IniFile().get("some_key", type="string"), str) +assert_type(IniFile().get("some_key", group=None, type="string"), str) +assert_type(IniFile().get("some_key", group="group", type="string"), str) +assert_type(IniFile().get("some_key", locale=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=True, type="string"), str) +assert_type(IniFile().get("some_key", strict=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=True, type="string"), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, type="string"), str) +# Explicitly set list. +assert_type(IniFile().get("some_key", list=False), str) +assert_type(IniFile().get("some_key", group=None, list=False), str) +assert_type(IniFile().get("some_key", group="group", list=False), str) +assert_type(IniFile().get("some_key", locale=False, list=False), str) +assert_type(IniFile().get("some_key", locale=True, list=False), str) +assert_type(IniFile().get("some_key", strict=False, list=False), str) +assert_type(IniFile().get("some_key", strict=True, list=False), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=False), str) +# Explicitly set both. +assert_type(IniFile().get("some_key", list=False, type="string"), str) +assert_type(IniFile().get("some_key", group=None, list=False, type="string"), str) +assert_type(IniFile().get("some_key", group="group", list=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=False, list=False, type="string"), str) +assert_type(IniFile().get("some_key", locale=True, list=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=False, list=False, type="string"), str) +assert_type(IniFile().get("some_key", strict=True, list=False, type="string"), str) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=False, type="string"), str) + +# Get List[str] +assert_type(IniFile().get("some_key", "group", True, "string", True), List[str]) +assert_type(IniFile().get("some_key", "group", True, "string", True, False), List[str]) +assert_type(IniFile().get("some_key", "group", True, "string", True, True), List[str]) +# Keyword parameters +assert_type(IniFile().get("some_key", list=True, group=None), List[str]) +assert_type(IniFile().get("some_key", list=True, group="group"), List[str]) +assert_type(IniFile().get("some_key", list=True, locale=False), List[str]) +assert_type(IniFile().get("some_key", list=True, locale=True), List[str]) +assert_type(IniFile().get("some_key", list=True, strict=False), List[str]) +assert_type(IniFile().get("some_key", list=True, strict=True), List[str]) +assert_type(IniFile().get("some_key", list=True, group="group", locale=True, strict=True), List[str]) +# Explicitly set list +assert_type(IniFile().get("some_key", list=True), List[str]) +assert_type(IniFile().get("some_key", group=None, list=True), List[str]) +assert_type(IniFile().get("some_key", group="group", list=True), List[str]) +assert_type(IniFile().get("some_key", locale=False, list=True), List[str]) +assert_type(IniFile().get("some_key", locale=True, list=True), List[str]) +assert_type(IniFile().get("some_key", strict=False, list=True), List[str]) +assert_type(IniFile().get("some_key", strict=True, list=True), List[str]) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=True), List[str]) +# Explicitly set both +assert_type(IniFile().get("some_key", list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", group=None, list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", group="group", list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", locale=False, list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", locale=True, list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", strict=False, list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", strict=True, list=True, type="string"), List[str]) +assert_type(IniFile().get("some_key", group="group", locale=True, strict=True, list=True, type="string"), List[str]) + +# Get bool +assert_type(IniFile().get("some_key", "group", True, "boolean"), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False, False), bool) +assert_type(IniFile().get("some_key", "group", True, "boolean", False, True), bool) +# Keyword parameters +assert_type(IniFile().get("some_key", type="boolean"), bool) +assert_type(IniFile().get("some_key", type="boolean", group=None), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group"), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=True), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=True), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", locale=True, strict=True), bool) +# Explicitly set list +assert_type(IniFile().get("some_key", type="boolean", list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group=None, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=False, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", locale=True, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=False, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", strict=True, list=False), bool) +assert_type(IniFile().get("some_key", type="boolean", group="group", locale=True, strict=True, list=False), bool) + +# Get List[bool] +assert_type(IniFile().get("some_key", "group", True, "boolean", True), List[bool]) +assert_type(IniFile().get("some_key", "group", True, "boolean", True, False), List[bool]) +assert_type(IniFile().get("some_key", "group", True, "boolean", True, True), List[bool]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="boolean", list=True), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group=None), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group="group"), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, locale=False), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, locale=True), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, strict=False), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, strict=True), List[bool]) +assert_type(IniFile().get("some_key", type="boolean", list=True, group="group", locale=True, strict=True), List[bool]) + +# Get int +assert_type(IniFile().get("some_key", "group", True, "integer"), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False, False), int) +assert_type(IniFile().get("some_key", "group", True, "integer", False, True), int) +# Keyword parameters +assert_type(IniFile().get("some_key", type="integer"), int) +assert_type(IniFile().get("some_key", type="integer", group=None), int) +assert_type(IniFile().get("some_key", type="integer", group="group"), int) +assert_type(IniFile().get("some_key", type="integer", locale=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=True), int) +assert_type(IniFile().get("some_key", type="integer", strict=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=True), int) +assert_type(IniFile().get("some_key", type="integer", group="group", locale=True, strict=True), int) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="integer", list=False), int) +assert_type(IniFile().get("some_key", type="integer", group=None, list=False), int) +assert_type(IniFile().get("some_key", type="integer", group="group", list=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=False, list=False), int) +assert_type(IniFile().get("some_key", type="integer", locale=True, list=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=False, list=False), int) +assert_type(IniFile().get("some_key", type="integer", strict=True, list=False), int) +assert_type(IniFile().get("some_key", type="integer", group="group", locale=True, strict=True, list=False), int) + +# Get List[int] +assert_type(IniFile().get("some_key", "group", True, "integer", True), List[int]) +assert_type(IniFile().get("some_key", "group", True, "integer", True, False), List[int]) +assert_type(IniFile().get("some_key", "group", True, "integer", True, True), List[int]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="integer", list=True), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group=None), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group="group"), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, locale=False), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, locale=True), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, strict=False), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, strict=True), List[int]) +assert_type(IniFile().get("some_key", type="integer", list=True, group="group", locale=True, strict=True), List[int]) + +# Get float +assert_type(IniFile().get("some_key", "group", True, "numeric"), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False, False), float) +assert_type(IniFile().get("some_key", "group", True, "numeric", False, True), float) +# Keyword parameters +assert_type(IniFile().get("some_key", type="numeric"), float) +assert_type(IniFile().get("some_key", type="numeric", group=None), float) +assert_type(IniFile().get("some_key", type="numeric", group="group"), float) +assert_type(IniFile().get("some_key", type="numeric", locale=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=True), float) +assert_type(IniFile().get("some_key", type="numeric", strict=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=True), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", locale=True, strict=True), float) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="numeric", list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group=None, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", list=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=False, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", locale=True, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=False, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", strict=True, list=False), float) +assert_type(IniFile().get("some_key", type="numeric", group="group", locale=True, strict=True, list=False), float) + +# Get List[float] +assert_type(IniFile().get("some_key", "group", True, "numeric", True), List[float]) +assert_type(IniFile().get("some_key", "group", True, "numeric", True, False), List[float]) +assert_type(IniFile().get("some_key", "group", True, "numeric", True, True), List[float]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="numeric", list=True), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group=None), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group="group"), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, locale=False), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, locale=True), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, strict=False), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, strict=True), List[float]) +assert_type(IniFile().get("some_key", type="numeric", list=True, group="group", locale=True, strict=True), List[float]) + +# Get regex +assert_type(IniFile().get("some_key", "group", True, "regex"), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False, False), re.Pattern[str]) +assert_type(IniFile().get("some_key", "group", True, "regex", False, True), re.Pattern[str]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="regex"), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group=None), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group"), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=True), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=True), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", locale=True, strict=True), re.Pattern[str]) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="regex", list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group=None, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=False, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", locale=True, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=False, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", strict=True, list=False), re.Pattern[str]) +assert_type(IniFile().get("some_key", type="regex", group="group", locale=True, strict=True, list=False), re.Pattern[str]) + +# Get List[regex] +assert_type(IniFile().get("some_key", "group", True, "regex", True), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", "group", True, "regex", True, False), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", "group", True, "regex", True, True), List[re.Pattern[str]]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="regex", list=True), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group=None), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group="group"), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, locale=False), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, locale=True), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, strict=False), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, strict=True), List[re.Pattern[str]]) +assert_type(IniFile().get("some_key", type="regex", list=True, group="group", locale=True, strict=True), List[re.Pattern[str]]) + +# Get point +assert_type(IniFile().get("some_key", "group", True, "point"), Tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False), Tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False, False), Tuple[int, int]) +assert_type(IniFile().get("some_key", "group", True, "point", False, True), Tuple[int, int]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="point"), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group=None), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group"), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=True), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=True), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", locale=True, strict=True), Tuple[int, int]) +# Explicitly set list. +assert_type(IniFile().get("some_key", type="point", list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group=None, list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=False, list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", locale=True, list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=False, list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", strict=True, list=False), Tuple[int, int]) +assert_type(IniFile().get("some_key", type="point", group="group", locale=True, strict=True, list=False), Tuple[int, int]) + +# Get List[point] +assert_type(IniFile().get("some_key", "group", True, "point", True), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", "group", True, "point", True, False), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", "group", True, "point", True, True), List[Tuple[int, int]]) +# Keyword parameters +assert_type(IniFile().get("some_key", type="point", list=True), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group=None), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group="group"), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, locale=False), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, locale=True), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, strict=False), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, strict=True), List[Tuple[int, int]]) +assert_type(IniFile().get("some_key", type="point", list=True, group="group", locale=True, strict=True), List[Tuple[int, int]]) diff --git a/stubs/pyxdg/METADATA.toml b/stubs/pyxdg/METADATA.toml new file mode 100644 index 000000000000..a0370c6a8b74 --- /dev/null +++ b/stubs/pyxdg/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.28.*" +upstream-repository = "https://github.com/takluyver/pyxdg" diff --git a/stubs/pyxdg/xdg/BaseDirectory.pyi b/stubs/pyxdg/xdg/BaseDirectory.pyi new file mode 100644 index 000000000000..6c39679d8a20 --- /dev/null +++ b/stubs/pyxdg/xdg/BaseDirectory.pyi @@ -0,0 +1,18 @@ +from _typeshed import StrPath +from collections.abc import Iterator + +xdg_data_home: str +xdg_data_dirs: list[str] +xdg_config_home: str +xdg_config_dirs: list[str] +xdg_cache_home: str +xdg_state_home: str + +def save_config_path(*resource: StrPath) -> str: ... +def save_data_path(*resource: StrPath) -> str: ... +def save_cache_path(*resource: StrPath) -> str: ... +def save_state_path(*resource: StrPath) -> str: ... +def load_config_paths(*resource: StrPath) -> Iterator[str]: ... +def load_first_config(*resource: StrPath) -> str: ... +def load_data_paths(*resource: StrPath) -> Iterator[str]: ... +def get_runtime_dir(strict: bool = True) -> str: ... diff --git a/stubs/pyxdg/xdg/Config.pyi b/stubs/pyxdg/xdg/Config.pyi new file mode 100644 index 000000000000..d0866c29d7b5 --- /dev/null +++ b/stubs/pyxdg/xdg/Config.pyi @@ -0,0 +1,13 @@ +language: str +windowmanager: str | None +icon_theme: str +icon_size: int +cache_time: int +root_mode: bool + +def setWindowManager(wm: str) -> None: ... +def setIconTheme(theme: str) -> None: ... +def setIconSize(size: int) -> None: ... +def setCacheTime(time: int) -> None: ... +def setLocale(lang: str) -> None: ... +def setRootMode(boolean: bool) -> None: ... diff --git a/stubs/pyxdg/xdg/DesktopEntry.pyi b/stubs/pyxdg/xdg/DesktopEntry.pyi new file mode 100644 index 000000000000..251066b67c46 --- /dev/null +++ b/stubs/pyxdg/xdg/DesktopEntry.pyi @@ -0,0 +1,65 @@ +import re +from _typeshed import StrPath +from typing import Literal + +from xdg.IniFile import IniFile + +class DesktopEntry(IniFile): + defaultGroup: str + content: dict[str, dict[str, str]] + def __init__(self, filename: StrPath | None = None) -> None: ... + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def findTryExec(self) -> str | None: ... + def getType(self) -> str: ... + def getVersion(self) -> float: ... + def getVersionString(self) -> str: ... + def getName(self) -> str: ... + def getGenericName(self) -> str: ... + def getNoDisplay(self) -> bool: ... + def getComment(self) -> str: ... + def getIcon(self) -> str: ... + def getHidden(self) -> bool: ... + def getOnlyShowIn(self) -> list[str]: ... + def getNotShowIn(self) -> list[str]: ... + def getTryExec(self) -> str: ... + def getExec(self) -> str: ... + def getPath(self) -> str: ... + def getTerminal(self) -> bool: ... + def getMimeType(self) -> list[re.Pattern[str]]: ... + def getMimeTypes(self) -> list[str]: ... + def getCategories(self) -> list[str]: ... + def getStartupNotify(self) -> bool: ... + def getStartupWMClass(self) -> str: ... + def getURL(self) -> str: ... + def getServiceTypes(self) -> list[str]: ... + def getDocPath(self) -> str: ... + def getKeywords(self) -> list[str]: ... + def getInitialPreference(self) -> str: ... + def getDev(self) -> str: ... + def getFSType(self) -> str: ... + def getMountPoint(self) -> str: ... + def getReadonly(self) -> bool: ... + def getUnmountIcon(self) -> str: ... + def getMiniIcon(self) -> str: ... + def getTerminalOptions(self) -> str: ... + def getDefaultApp(self) -> str: ... + def getProtocols(self) -> list[str]: ... + def getExtensions(self) -> list[str]: ... + def getBinaryPattern(self) -> str: ... + def getMapNotify(self) -> str: ... + def getEncoding(self) -> str: ... + def getSwallowTitle(self) -> str: ... + def getSwallowExec(self) -> str: ... + def getSortOrder(self) -> list[str]: ... + def getFilePattern(self) -> re.Pattern[str]: ... + def getActions(self) -> list[str]: ... + filename: str + def new(self, filename: str) -> None: ... + type: Literal["Application", "Directory"] + name: str + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + def checkType(self, key: str, type: str) -> None: ... + def checkOnlyShowIn(self, value: str) -> None: ... + def checkCategories(self, value: str) -> None: ... diff --git a/stubs/pyxdg/xdg/Exceptions.pyi b/stubs/pyxdg/xdg/Exceptions.pyi new file mode 100644 index 000000000000..764a1b11216c --- /dev/null +++ b/stubs/pyxdg/xdg/Exceptions.pyi @@ -0,0 +1,41 @@ +debug: bool + +class Error(Exception): + msg: str + def __init__(self, msg: str) -> None: ... + +class ValidationError(Error): + msg: str + file: str + def __init__(self, msg: str, file: str) -> None: ... + +class ParsingError(Error): + msg: str + file: str + def __init__(self, msg: str, file: str) -> None: ... + +class NoKeyError(Error): + key: str + group: str + file: str + def __init__(self, key: str, group: str, file: str) -> None: ... + +class DuplicateKeyError(Error): + key: str + group: str + file: str + def __init__(self, key: str, group: str, file: str) -> None: ... + +class NoGroupError(Error): + group: str + file: str + def __init__(self, group: str, file: str) -> None: ... + +class DuplicateGroupError(Error): + group: str + file: str + def __init__(self, group: str, file: str) -> None: ... + +class NoThemeError(Error): + theme: str + def __init__(self, theme: str) -> None: ... diff --git a/stubs/pyxdg/xdg/IconTheme.pyi b/stubs/pyxdg/xdg/IconTheme.pyi new file mode 100644 index 000000000000..40ba87afda55 --- /dev/null +++ b/stubs/pyxdg/xdg/IconTheme.pyi @@ -0,0 +1,55 @@ +from _typeshed import StrPath +from collections.abc import Collection + +from xdg.IniFile import IniFile + +class IconTheme(IniFile): + def __init__(self) -> None: ... + dir: str + name: str + comment: str + directories: list[str] + type: str + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def getDir(self) -> str: ... + def getName(self) -> str: ... + def getComment(self) -> str: ... + def getInherits(self) -> list[str]: ... + def getDirectories(self) -> list[str]: ... + def getScaledDirectories(self) -> list[str]: ... + def getHidden(self) -> bool: ... + def getExample(self) -> str: ... + def getSize(self, directory: StrPath) -> int: ... + def getContext(self, directory: StrPath) -> str: ... + def getType(self, directory: StrPath) -> str: ... + def getMaxSize(self, directory: StrPath) -> int: ... + def getMinSize(self, directory: StrPath) -> int: ... + def getThreshold(self, directory: StrPath) -> int: ... + def getScale(self, directory: StrPath) -> int: ... + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + +class IconData(IniFile): + def __init__(self) -> None: ... + def parse(self, file: StrPath) -> None: ... # type: ignore[override] + def getDisplayName(self) -> str: ... + def getEmbeddedTextRectangle(self) -> list[int]: ... + def getAttachPoints(self) -> list[tuple[int, int]]: ... + def checkExtras(self) -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + +icondirs: list[str] +themes: list[IconTheme] +theme_cache: dict[str, IconTheme] +dir_cache: dict[str, tuple[str, float, float]] +icon_cache: dict[tuple[str, int, str, tuple[str, ...]], tuple[float, str]] + +def getIconPath( + iconname: str, size: int | None = None, theme: str | None = None, extensions: Collection[str] = ["png", "svg", "xpm"] +) -> str: ... +def getIconData(path: str) -> IconData: ... +def LookupIcon(iconname: str, size: int, theme: str, extensions: Collection[str]) -> str: ... +def DirectoryMatchesSize(subdir: str, iconsize: int, theme: str) -> bool: ... +def DirectorySizeDistance(subdir: str, iconsize: int, theme: str) -> int: ... diff --git a/stubs/pyxdg/xdg/IniFile.pyi b/stubs/pyxdg/xdg/IniFile.pyi new file mode 100644 index 000000000000..2fa7cb47aebd --- /dev/null +++ b/stubs/pyxdg/xdg/IniFile.pyi @@ -0,0 +1,256 @@ +import re +from collections.abc import Iterable, KeysView +from typing import Literal, overload + +def is_ascii(s: str) -> bool: ... + +class IniFile: + defaultGroup: str + fileExtension: str + filename: str + tainted: bool + content: dict[str, dict[str, str]] + warnings: list[str] + errors: list[str] + def __init__(self, filename: str | None = None) -> None: ... + def __cmp__(self, other: IniFile) -> bool: ... + def parse(self, filename: str, headers: Iterable[str] | None = None) -> None: ... + + @overload + def get( + self, + key: str, + group: str | None = None, + locale: bool = False, + type: Literal["string"] = "string", + list: Literal[False] = False, + strict: bool = False, + ) -> str: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["string"], list: Literal[True], strict: bool = False + ) -> list[str]: ... + @overload + def get( + self, + key: str, + *, + list: Literal[True], + group: str | None = None, + locale: bool = False, + type: Literal["string"] = "string", + strict: bool = False, + ) -> list[str]: ... + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["boolean"], + list: Literal[False] = False, + strict: bool = False, + ) -> bool: ... + @overload + def get( + self, + key: str, + *, + type: Literal["boolean"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> bool: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["boolean"], list: Literal[True], strict: bool = False + ) -> list[bool]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["boolean"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[bool]: ... + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["integer"], + list: Literal[False] = False, + strict: bool = False, + ) -> int: ... + @overload + def get( + self, + key: str, + *, + type: Literal["integer"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> int: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["integer"], list: Literal[True], strict: bool = False + ) -> list[int]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["integer"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[int]: ... + + # Float + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["numeric"], + list: Literal[False] = False, + strict: bool = False, + ) -> float: ... + @overload + def get( + self, + key: str, + *, + type: Literal["numeric"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> float: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["numeric"], list: Literal[True], strict: bool = False + ) -> list[float]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["numeric"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[float]: ... + + # Regex + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["regex"], + list: Literal[False] = False, + strict: bool = False, + ) -> re.Pattern[str]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["regex"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> re.Pattern[str]: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["regex"], list: Literal[True], strict: bool = False + ) -> list[re.Pattern[str]]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["regex"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[re.Pattern[str]]: ... + # point + @overload + def get( + self, + key: str, + group: str | None, + locale: bool, + type: Literal["point"], + list: Literal[False] = False, + strict: bool = False, + ) -> tuple[int, int]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["point"], + group: str | None = None, + locale: bool = False, + list: Literal[False] = False, + strict: bool = False, + ) -> tuple[int, int]: ... + @overload + def get( + self, key: str, group: str | None, locale: bool, type: Literal["point"], list: Literal[True], strict: bool = False + ) -> list[tuple[int, int]]: ... + @overload + def get( + self, + key: str, + *, + type: Literal["point"], + list: Literal[True], + group: str | None = None, + locale: bool = False, + strict: bool = False, + ) -> list[tuple[int, int]]: ... + + def getList(self, string: str) -> list[str]: ... + def validate(self, report: Literal["All", "Warnings", "Errors"] = "All") -> None: ... + def checkGroup(self, group: str) -> None: ... + def checkKey(self, key: str, value: str, group: str) -> None: ... + def checkValue( + self, + key: str, + value: str, + type: Literal["string", "localestring", "boolean", "numeric", "integer", "regex", "point"] = "string", + list: bool = False, + ) -> None: ... + def checkExtras(self) -> None: ... + def checkBoolean(self, value: str) -> Literal[1, 2] | None: ... + def checkNumber(self, value: str) -> Literal[1, 2] | None: ... + def checkInteger(self, value: str) -> Literal[1] | None: ... + def checkPoint(self, value: str) -> Literal[1] | None: ... + def checkString(self, value: str) -> Literal[0, 1]: ... + def checkRegex(self, value: str) -> Literal[1] | None: ... + def write(self, filename: str | None = None, trusted: bool = False) -> None: ... + def set(self, key: str, value: str, group: str | None = None, locale: bool = False) -> None: ... + def addGroup(self, group: str) -> None: ... + def removeGroup(self, group: str) -> bool: ... + def removeKey(self, key: str, group: str | None = None, locales: bool = True) -> str: ... + def groups(self) -> KeysView[str]: ... + def hasGroup(self, group: str) -> bool: ... + def hasKey(self, key: str, group: str | None = None) -> bool: ... + def getFileName(self) -> str: ... diff --git a/stubs/pyxdg/xdg/Locale.pyi b/stubs/pyxdg/xdg/Locale.pyi new file mode 100644 index 000000000000..6aa285ad348a --- /dev/null +++ b/stubs/pyxdg/xdg/Locale.pyi @@ -0,0 +1,8 @@ +from collections.abc import Iterable + +regex: str + +def expand_languages(languages: Iterable[str] | None = None) -> list[str]: ... +def update(language: str | None = None) -> None: ... + +langs: list[str] diff --git a/stubs/pyxdg/xdg/Menu.pyi b/stubs/pyxdg/xdg/Menu.pyi new file mode 100644 index 000000000000..bd0b7af99651 --- /dev/null +++ b/stubs/pyxdg/xdg/Menu.pyi @@ -0,0 +1,168 @@ +import ast +import xml.dom +from _typeshed import Unused +from collections.abc import Collection, Iterable, Iterator +from types import CodeType +from typing import Literal + +from .DesktopEntry import DesktopEntry + +DELETED: Literal["Deleted"] = "Deleted" +NO_DISPLAY: Literal["NoDisplay"] = "NoDisplay" +HIDDEN: Literal["Hidden"] = "Hidden" +EMPTY: Literal["Empty"] = "Empty" +NOT_SHOW_IN: Literal["NotShowIn"] = "NotShowIn" +NO_EXEC: Literal["NoExec"] = "NoExec" + +class Menu: + Name: str + Directory: Menu | None + Entries: list[str] + Doc: str + Filename: str + Depth: int + Parent: Menu | None + NotInXml: bool + Show: bool + Visible: int + AppDirs: list[str] + DefaultLayout: str | None + Deleted: bool | None + Directories: list[str] + DirectoryDirs: list[Menu] + Layout: Layout + MenuEntries: list[MenuEntry | Menu | Separator] + Moves: list[Move] + OnlyUnallocated: bool | None + Rules: list[Rule] + Submenus: list[Menu] + def __init__(self) -> None: ... + def __add__(self, other: Menu) -> Menu: ... + def __cmp__(self, other: Menu) -> int: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def getEntries(self, show_hidden: bool = False) -> Iterator[str]: ... + def getMenuEntry(self, desktopfileid: int, deep: bool = False) -> MenuEntry: ... + def getMenu(self, path: str) -> Menu: ... + def getPath(self, org: bool = False, toplevel: bool = False) -> str: ... + def getName(self) -> str: ... + def getGenericName(self) -> str: ... + def getComment(self) -> str: ... + def getIcon(self) -> str: ... + def sort(self) -> None: ... + def addSubmenu(self, newmenu: Menu) -> None: ... + def merge_inline(self, submenu: Menu) -> None: ... + +class Move: + Old: str + New: str + def __init__(self, old: str = "", new: str = "") -> None: ... + def __cmp__(self, other: Move) -> int: ... + +class Layout: + show_empty: bool + inline: bool + inline_limit: int + inline_header: bool + inline_alias: bool + def __init__( + self, + show_empty: bool = False, + inline: bool = False, + inline_limit: int = 4, + inline_header: bool = True, + inline_alias: bool = False, + ) -> None: ... + + @property + def order(self) -> list[list[str]]: ... + @order.setter + def order(self, order: list[list[str]]) -> None: ... + +class Rule: + TYPE_INCLUDE: Literal[0] + TYPE_EXCLUDE: Literal[1] + @classmethod + def fromFilename(cls, type: Literal[0, 1], filename: str) -> Rule: ... + Type: Literal[0, 1] + expression: ast.Expression + code: CodeType + def __init__(self, type: Literal[0, 1], expression: str) -> None: ... + def apply(self, menuentries: Iterable[MenuEntry], run: int) -> Iterable[MenuEntry]: ... + +class MenuEntry: + TYPE_USER: Literal["User"] + TYPE_SYSTEM: Literal["System"] + TYPE_BOTH: Literal["Both"] + DesktopEntry: DesktopEntry + Show: Literal[True, False, "Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] + Visible: Literal[1, 0, "Deleted", "NoDisplay", "Hidden", "Empty", "NotShowIn", "NoExec"] + Original: MenuEntry | None + Parents: list[Menu] + Allocated: bool + Add: bool + MatchedInclude: bool + Categories: list[str] + def __init__(self, filename: str, dir: str = "", prefix: str = "") -> None: ... + def save(self) -> None: ... + def getDir(self) -> str: ... + def getType(self) -> Literal["User", "System", "Both"]: ... + Filename: str + Prefix: str + DesktopFileID: str + def setAttributes(self, filename: str, dir: str = "", prefix: str = "") -> None: ... + def updateAttributes(self) -> None: ... + def __cmp__(self, other: MenuEntry) -> int: ... + def __lt__(self, other: MenuEntry) -> bool: ... + def __eq__(self, other: object) -> bool: ... + +class Separator: + Parent: Menu + Show: bool + def __init__(self, parent: Menu) -> None: ... + +class Header: + Name: str + GenericName: str + Comment: str + def __init__(self, name: str, generic_name: str, comment: str) -> None: ... + +TYPE_DIR: Literal[0] = 0 +TYPE_FILE: Literal[1] = 1 + +class XMLMenuBuilder: + debug: bool + def __init__(self, debug: bool = False) -> None: ... + cache: MenuEntryCache + def parse(self, filename: str | None = None) -> Menu: ... + def parse_menu(self, node: xml.dom.Node, filename: str) -> Menu: ... + def parse_node(self, node: xml.dom.Node, filename: str, parent: Menu | None = None) -> None: ... + def parse_layout(self, node: xml.dom.Node) -> Layout: ... + def parse_move(self, node: xml.dom.Node) -> Move: ... + def parse_rule(self, node: xml.dom.Node) -> Rule: ... + def parse_bool_op(self, node: xml.dom.Node, operator: ast.And | ast.Or) -> ast.BoolOp | ast.UnaryOp | ast.Compare | None: ... + def parse_rule_node(self, node: xml.dom.Node) -> ast.BoolOp | ast.UnaryOp | ast.Compare | None: ... + def parse_app_dir(self, value: str, filename: str, parent: str) -> None: ... + def parse_default_app_dir(self, filename: str, parent: str) -> None: ... + def parse_directory_dir(self, value: str, filename: str, parent: str) -> None: ... + def parse_default_directory_dir(self, filename: str, parent: str) -> None: ... + def parse_merge_file(self, value: str, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def parse_merge_dir(self, value: str, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def parse_default_merge_dirs(self, child: Menu | MenuEntry, filename: str, parent: str) -> None: ... + def merge_file(self, filename: str, child: Unused, parent: Menu) -> None: ... + def parse_legacy_dir(self, dir_: str, prefix: str, filename: str, parent: str) -> None: ... + def merge_legacy_dir(self, dir_: str, prefix: str, filename: str, parent: str) -> Menu: ... + def parse_kde_legacy_dirs(self, filename: str, parent: str) -> None: ... + def post_parse(self, menu: Menu) -> None: ... + def generate_not_only_allocated(self, menu: Menu) -> None: ... + def generate_only_allocated(self, menu: Menu) -> None: ... + def handle_moves(self, menu: Menu) -> None: ... + +class MenuEntryCache: + cacheEntries: dict[str, list[MenuEntry]] + cache: dict[str, list[MenuEntry]] + def __init__(self) -> None: ... + def add_menu_entries(self, dirs: Iterable[str], prefix: str = "", legacy: bool = False) -> None: ... + def get_menu_entries(self, dirs: Collection[str], legacy: bool = True) -> list[MenuEntry]: ... + +def parse(filename: str | None = None, debug: bool = False) -> XMLMenuBuilder: ... diff --git a/stubs/pyxdg/xdg/MenuEditor.pyi b/stubs/pyxdg/xdg/MenuEditor.pyi new file mode 100644 index 000000000000..a3dad5e2b8d8 --- /dev/null +++ b/stubs/pyxdg/xdg/MenuEditor.pyi @@ -0,0 +1,152 @@ +from _typeshed import StrPath, Unused +from typing import Literal, TypeAlias, overload +from xml.etree.ElementTree import ElementTree + +from .Menu import Menu, MenuEntry, Separator, XMLMenuBuilder + +_MenuItem: TypeAlias = Menu | MenuEntry | Separator + +class MenuEditor: + menu: Menu + filename: str + tree: ElementTree + parser: XMLMenuBuilder + filenames: list[str] + def __init__(self, menu: Menu | None = None, filename: StrPath | None = None, root: bool = False) -> None: ... + def parse(self, menu: Menu | None = None, filename: StrPath | None = None, root: bool = False) -> None: ... + def save(self) -> None: ... + + # All "before" or "after" items can be one, the other, or neither, but not both. + @overload + def createMenuEntry( + self, + parent: Menu | None, + name: str, + command: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + after: _MenuItem | None = None, + before: None = None, + ) -> MenuEntry: ... + @overload + def createMenuEntry( + self, + parent: Menu | None, + name: str, + command: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + after: None = None, + before: _MenuItem | None = None, + ) -> MenuEntry: ... + + @overload + def createMenu( + self, + parent: Menu | None, + name: str, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + after: _MenuItem | None = None, + before: None = None, + ) -> Menu: ... + @overload + def createMenu( + self, + parent: Menu | None, + name: str, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + after: None = None, + before: _MenuItem | None = None, + ) -> Menu: ... + + @overload + def createSeparator(self, parent: Menu, after: _MenuItem | None = None, before: None = None) -> Separator: ... + @overload + def createSeparator(self, parent: Menu, after: None = None, before: _MenuItem | None = None) -> Separator: ... + + @overload + def moveMenuEntry( + self, + menuentry: MenuEntry, + oldparent: Menu | None, + newparent: Menu | None, + after: _MenuItem | None = None, + before: None = None, + ) -> MenuEntry: ... + @overload + def moveMenuEntry( + self, + menuentry: MenuEntry, + oldparent: Menu | None, + newparent: Menu | None, + after: None = None, + before: _MenuItem | None = None, + ) -> MenuEntry: ... + + @overload + def moveMenu( + self, menu: Menu, oldparent: Menu, newparent: Menu, after: _MenuItem | None = None, before: None = None + ) -> Menu: ... + @overload + def moveMenu( + self, menu: Menu, oldparent: Menu, newparent: Menu, after: None = None, before: _MenuItem | None = None + ) -> Menu: ... + + @overload + def moveSeparator( + self, separator: Separator, parent: Menu, after: _MenuItem | None = None, before: None = None + ) -> Separator: ... + @overload + def moveSeparator( + self, separator: Separator, parent: Menu, after: None = None, before: _MenuItem | None = None + ) -> Separator: ... + + @overload + def copyMenuEntry( + self, menuentry: MenuEntry, oldparent: Unused, newparent: Menu, after: _MenuItem | None = None, before: None = None + ) -> MenuEntry: ... + @overload + def copyMenuEntry( + self, menuentry: MenuEntry, oldparent: Unused, newparent: Menu, after: None = None, before: _MenuItem | None = None + ) -> MenuEntry: ... + + def editMenuEntry( + self, + menuentry: MenuEntry, + name: str | None = None, + genericname: str | None = None, + comment: str | None = None, + command: str | None = None, + icon: str | None = None, + terminal: bool | None = None, + nodisplay: bool | None = None, + hidden: bool | None = None, + ) -> MenuEntry: ... + def editMenu( + self, + menu: Menu, + name: str | None = None, + genericname: str | None = None, + comment: str | None = None, + icon: str | None = None, + nodisplay: bool | None = None, + hidden: bool | None = None, + ) -> Menu: ... + def hideMenuEntry(self, menuentry: MenuEntry) -> None: ... + def unhideMenuEntry(self, menuentry: MenuEntry) -> None: ... + def hideMenu(self, menu: Menu) -> None: ... + def unhideMenu(self, menu: Menu) -> None: ... + def deleteMenuEntry(self, menuentry: MenuEntry) -> MenuEntry: ... + def revertMenuEntry(self, menuentry: MenuEntry) -> MenuEntry: ... + def deleteMenu(self, menu: Menu) -> Menu: ... + def revertMenu(self, menu: Menu) -> Menu: ... + def deleteSeparator(self, separator: Separator) -> Separator: ... + def getAction(self, entry: _MenuItem) -> Literal["none", "revert", "delete"]: ... diff --git a/stubs/pyxdg/xdg/Mime.pyi b/stubs/pyxdg/xdg/Mime.pyi new file mode 100644 index 000000000000..38607506caea --- /dev/null +++ b/stubs/pyxdg/xdg/Mime.pyi @@ -0,0 +1,102 @@ +import re +from _typeshed import StrOrBytesPath, SupportsLenAndGetItem, Unused +from collections import defaultdict +from collections.abc import Collection, Iterable +from io import BytesIO +from typing import Literal, TypeAlias +from typing_extensions import Self + +FREE_NS: str +types: dict[str, MIMEtype] +exts: Unused | None # This appears to be unused. +globs: GlobDB | None +literals: Unused | None # This appears to be unused. +magic: MagicDB | None +PY3: Literal[True] + +_MimeTypeWeightPair: TypeAlias = tuple[MIMEtype, int] + +def lookup(media: str, subtype: str | None = None) -> MIMEtype: ... + +class MIMEtype: + def __new__(cls, media: str, subtype: str | None = None) -> Self: ... + def get_comment(self) -> str: ... + def canonical(self) -> Self: ... + def inherits_from(self) -> set[MIMEtype]: ... + def __hash__(self) -> int: ... + +class UnknownMagicRuleFormat(ValueError): ... +class DiscardMagicRules(Exception): ... + +class MagicRule: + also: MagicRule | MagicMatchAny | None + start: int + value: bytes + mask: bytes | None + word: int + range: int + def __init__(self, start: int, value: bytes, mask: bytes, word: int, range: int) -> None: ... + rule_ending_re: re.Pattern[str] + @classmethod + def from_file(cls, f: BytesIO) -> tuple[int, MagicRule]: ... + def maxlen(self) -> int: ... + def match(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + def match0(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + +class MagicMatchAny: + rules: Collection[MagicRule] + def __init__(self, rules: Iterable[MagicRule]) -> None: ... + def match(self, buffer: SupportsLenAndGetItem[bytes]) -> bool: ... + def maxlen(self) -> int: ... + @classmethod + def from_file(cls, f: BytesIO) -> MagicMatchAny | MagicRule | None: ... + @classmethod + def from_rule_tree(cls, tree: list[MagicRule]) -> MagicMatchAny | MagicRule | None: ... + +class MagicDB: + bytype: defaultdict[MIMEtype, list[tuple[int, MagicRule]]] + def __init__(self) -> None: ... + def merge_file(self, fname: StrOrBytesPath) -> None: ... + alltypes: list[tuple[int, MIMEtype, MagicRule]] + maxlen: int + def finalise(self) -> None: ... + def match_data( + self, data: bytes, max_pri: int = 100, min_pri: int = 0, possible: Iterable[MIMEtype] | None = None + ) -> MIMEtype: ... + def match( + self, path: StrOrBytesPath, max_pri: int = 100, min_pri: int = 0, possible: Iterable[MIMEtype] | None = None + ) -> MIMEtype: ... + +class GlobDB: + allglobs: defaultdict[MIMEtype, list[tuple[int, str, str]]] + def __init__(self) -> None: ... + def merge_file(self, path: StrOrBytesPath) -> None: ... + exts: defaultdict[str, list[MIMEtype | int]] # Actually list[MIMEtype, int], but that's not valid. + cased_exts: defaultdict[str, list[MIMEtype | int]] # Actually list[MIMEtype, int], but that's not valid. + globs: list[tuple[re.Pattern[str], MIMEtype, int]] + literals: dict[str, _MimeTypeWeightPair] + cased_literals: dict[str, _MimeTypeWeightPair] + def finalise(self) -> None: ... + def first_match(self, path: StrOrBytesPath) -> _MimeTypeWeightPair | None: ... + def all_matches(self, path: StrOrBytesPath) -> list[_MimeTypeWeightPair]: ... + +text: MIMEtype +octet_stream: MIMEtype +inode_block: MIMEtype +inode_char: MIMEtype +inode_dir: MIMEtype +inode_fifo: MIMEtype +inode_socket: MIMEtype +inode_symlink: MIMEtype +inode_door: MIMEtype +app_exe: MIMEtype + +def update_cache() -> None: ... +def get_type_by_name(path: StrOrBytesPath) -> _MimeTypeWeightPair | None: ... +def get_type_by_contents(path: StrOrBytesPath, max_pri: int = 100, min_pri: int = 0) -> MIMEtype: ... +def get_type_by_data(data: bytes, max_pri: int = 100, min_pri: int = 0) -> MIMEtype: ... +def get_type(path: StrOrBytesPath, follow: bool = True, name_pri: int = 100) -> MIMEtype: ... +def get_type2(path: StrOrBytesPath, follow: bool = True) -> MIMEtype: ... +def is_text_file(path: StrOrBytesPath) -> bool: ... +def get_extensions(mimetype: MIMEtype) -> set[str]: ... +def install_mime_info(application: str, package_file: StrOrBytesPath) -> None: ... diff --git a/stubs/pyxdg/xdg/RecentFiles.pyi b/stubs/pyxdg/xdg/RecentFiles.pyi new file mode 100644 index 000000000000..742c9bdf6800 --- /dev/null +++ b/stubs/pyxdg/xdg/RecentFiles.pyi @@ -0,0 +1,26 @@ +from _typeshed import StrOrBytesPath, StrPath +from collections.abc import Iterable + +class RecentFiles: + RecentFiles: list[RecentFile] + filename: str + def __init__(self) -> None: ... + def parse(self, filename: StrPath | None = None) -> None: ... + def write(self, filename: StrOrBytesPath | None = None) -> None: ... + def getFiles( + self, mimetypes: Iterable[str] | None = None, groups: Iterable[str] | None = None, limit: int = 0 + ) -> list[RecentFile]: ... + def addFile(self, item: StrPath, mimetype: str, groups: Iterable[str] | None = None, private: bool = False) -> None: ... + def deleteFile(self, item: RecentFile | StrPath) -> None: ... + def sort(self) -> None: ... + +class RecentFile: + URI: str + MimeType: str + Timestamp: str + Private: bool + Groups: list[str] + def __init__(self) -> None: ... + def __cmp__(self, other: RecentFile) -> int: ... + def __lt__(self, other: RecentFile) -> bool: ... + def __eq__(self, other: object) -> bool: ... diff --git a/stubs/pyxdg/xdg/__init__.pyi b/stubs/pyxdg/xdg/__init__.pyi new file mode 100644 index 000000000000..5bf6489a50b7 --- /dev/null +++ b/stubs/pyxdg/xdg/__init__.pyi @@ -0,0 +1,15 @@ +from . import BaseDirectory, Config, DesktopEntry, Exceptions, IconTheme, IniFile, Locale, Menu, MenuEditor, Mime, RecentFiles + +__all__ = [ + "BaseDirectory", + "Config", + "DesktopEntry", + "Exceptions", + "IconTheme", + "IniFile", + "Locale", + "Menu", + "MenuEditor", + "Mime", + "RecentFiles", +] diff --git a/stubs/pyxdg/xdg/util.pyi b/stubs/pyxdg/xdg/util.pyi new file mode 100644 index 000000000000..15636e13529a --- /dev/null +++ b/stubs/pyxdg/xdg/util.pyi @@ -0,0 +1,6 @@ +from shutil import which as which +from typing import Literal + +PY3: Literal[True] + +def u(s: str) -> str: ... diff --git a/stubs/qrbill/@tests/stubtest_allowlist.txt b/stubs/qrbill/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..7be909504ec4 --- /dev/null +++ b/stubs/qrbill/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +# Error: is inconsistent +# ====================== +# While the method provides default values for all arguments, the first two +# arguments always need to be provided, so it makes no sense to pretend that +# they are optional +qrbill.bill.QRBill.__init__ diff --git a/stubs/qrbill/METADATA.toml b/stubs/qrbill/METADATA.toml new file mode 100644 index 000000000000..468d224cb47d --- /dev/null +++ b/stubs/qrbill/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.2.*" +upstream-repository = "https://github.com/claudep/swiss-qr-bill" +dependencies = ["types-qrcode"] diff --git a/stubs/qrbill/qrbill/__init__.pyi b/stubs/qrbill/qrbill/__init__.pyi new file mode 100644 index 000000000000..995a9dd82092 --- /dev/null +++ b/stubs/qrbill/qrbill/__init__.pyi @@ -0,0 +1 @@ +from .bill import QRBill as QRBill diff --git a/stubs/qrbill/qrbill/bill.pyi b/stubs/qrbill/qrbill/bill.pyi new file mode 100644 index 000000000000..b89b902c45be --- /dev/null +++ b/stubs/qrbill/qrbill/bill.pyi @@ -0,0 +1,193 @@ +from _typeshed import SupportsWrite +from collections.abc import Iterable, Iterator, Mapping +from decimal import Decimal +from pathlib import Path +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import deprecated + +from qrcode.image.svg import SvgPathImage + +# NOTE: Since svgwrite doesn't have any stubs we provide some type aliases, that +# we can choose to refine in the future, e.g. using a Protocol +_SvgDrawing: TypeAlias = Any # svgwrite.Drawing +_SvgGroup: TypeAlias = Any # svgwrite.container.Group + +# NOTE: Eventually we may want to consider replacing this with typed dicts, even +# if that means disallowing non-dict arguments. It should allow anything +# that is valid to pass into `Address.create`. +_AddressDict: TypeAlias = Mapping[str, str | None] + +IBAN_ALLOWED_COUNTRIES: list[str] +QR_IID: dict[str, int] +AMOUNT_REGEX: str +MM_TO_UU: float +BILL_HEIGHT: int +RECEIPT_WIDTH: str +PAYMENT_WIDTH: str +MAX_CHARS_PAYMENT_LINE: int +MAX_CHARS_RECEIPT_LINE: int +A4: tuple[str, str] +LABELS: dict[str, dict[str, str]] +SCISSORS_SVG_PATH: str + +class Address: + @overload + @classmethod + def create(cls, *, name: str | None = None, line1: str, line2: str | None = None, country: str | None) -> CombinedAddress: ... + @overload + @classmethod + def create(cls, *, name: str | None = None, line1: str | None = None, line2: str, country: str | None) -> CombinedAddress: ... + @overload + @classmethod + def create( + cls, + *, + name: str, + street: str | None = None, + house_num: str | None = None, + pcode: str, + city: str, + country: str | None = None, + ) -> StructuredAddress: ... + + @staticmethod + def parse_country(country: str | None) -> str: ... + +class CombinedAddress(Address): + combined: Final = True + name: str + line1: str + line2: str + country: str + def __init__( + self, *, name: str | None = None, line1: str | None = None, line2: str | None = None, country: str | None = None + ) -> None: ... + def data_list(self) -> list[str]: ... + def as_paragraph(self, max_chars: int = 72) -> Iterator[str]: ... + +class StructuredAddress(Address): + combined: Final = False + name: str + street: str + house_num: str + pcode: str + city: str + country: str + def __init__( + self, + *, + name: str | None = None, + street: str | None = None, + house_num: str | None = None, + pcode: str | None = None, + city: str | None = None, + country: str | None = None, + ) -> None: ... + def data_list(self) -> list[str]: ... + def as_paragraph(self, max_chars: int = 72) -> Iterator[str]: ... + +class QRBill: + qr_type: str + version: str + coding: int + allowed_currencies: tuple[Literal["CHF"], Literal["EUR"]] + font_family: str + creditor: CombinedAddress | StructuredAddress + final_creditor: CombinedAddress | StructuredAddress | None + debtor: CombinedAddress | StructuredAddress | None + ref_type: str + reference_number: str | None + account: str + account_is_qriban: bool + amount: str | None + currency: Literal["CHF", "EUR"] + additional_information: str + billing_information: str + + @overload + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + ref_number: None = None, + reference_number: str | None = None, + extra_infos: Literal[""] = "", + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + @overload + @deprecated("ref_number is deprecated and replaced by reference_number") + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + *, + ref_number: str, + reference_number: None = None, + extra_infos: str = "", + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + @overload + @deprecated("extra_infos is deprecated and replaced by additional_information") + def __init__( + self, + account: str, + creditor: _AddressDict, + final_creditor: None = None, + amount: Decimal | str | None = None, + currency: Literal["CHF", "EUR"] = "CHF", + debtor: _AddressDict | None = None, + ref_number: None = None, + reference_number: str | None = None, + *, + extra_infos: str, + additional_information: str = "", + billing_information: str = "", + alt_procs: list[str] | tuple[()] | tuple[str] | tuple[str, str] = (), + language: Literal["en", "de", "fr", "it"] = "en", + top_line: bool = True, + payment_line: bool = True, + font_factor: int = 1, + ) -> None: ... + + @property + def title_font_info(self) -> dict[str, Any]: ... + @property + def font_info(self) -> dict[str, Any]: ... + def head_font_info(self, part: str | None = None) -> dict[str, Any]: ... + @property + def proc_font_info(self) -> dict[str, Any]: ... + def qr_data(self) -> str: ... + def qr_image(self) -> SvgPathImage: ... + def draw_swiss_cross(self, dwg: _SvgDrawing, grp: _SvgGroup, origin: tuple[float, float], size: float) -> None: ... + def draw_blank_rect(self, dwg: _SvgDrawing, grp: _SvgGroup, x: float, y: float, width: float, height: float) -> None: ... + def label(self, txt: str) -> str: ... + def as_svg(self, file_out: str | Path | SupportsWrite[str], full_page: bool = False) -> None: ... + def transform_to_full_page(self, dwg: _SvgDrawing, bill: _SvgGroup) -> None: ... + def draw_bill(self, dwg: _SvgDrawing, horiz_scissors: bool = True) -> _SvgGroup: ... + +def add_mm(*mms: str | float) -> float: ... +def mm(val: str | float) -> float: ... +def format_ref_number(bill: QRBill) -> str: ... +def format_amount(amount_: str | float) -> str: ... +def wrap_infos(infos: Iterable[str]) -> Iterator[str]: ... +def replace_linebreaks(text: str | None) -> str: ... diff --git a/stubs/qrcode/@tests/stubtest_allowlist.txt b/stubs/qrcode/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..e24fb492beb2 --- /dev/null +++ b/stubs/qrcode/@tests/stubtest_allowlist.txt @@ -0,0 +1,22 @@ +# Internal modules +qrcode\.compat +qrcode\.compat\..* +qrcode\.tests +qrcode\.tests\..* + +# Stub-only module +qrcode._types + +# Parameter "data" has unhelpful default value, which creates a QR code with string "None". +qrcode\.main\.make + +# Implementation has marked these methods as abstract without the class +# or its bases deriving from abc.ABCMeta +qrcode\.image\.base\.BaseImage\.(drawrect|new_image|save) + +# The implementation sets this attribute to None on the class but instances +# always set this to a PIL image instance. +qrcode\.image\.styles\.moduledrawers\.(pil\.)?CircleModuleDrawer.circle + +# Leaked loop counter +qrcode.base.i diff --git a/stubs/qrcode/METADATA.toml b/stubs/qrcode/METADATA.toml new file mode 100644 index 000000000000..f329321ac1f0 --- /dev/null +++ b/stubs/qrcode/METADATA.toml @@ -0,0 +1,7 @@ +version = "8.2.*" +upstream-repository = "https://github.com/lincolnloop/python-qrcode" +# must be a version of Pillow that is py.typed +dependencies = ["Pillow>=10.3.0"] + +[tool.stubtest] +extras = ["pil"] diff --git a/stubs/qrcode/qrcode/LUT.pyi b/stubs/qrcode/qrcode/LUT.pyi new file mode 100644 index 000000000000..2e7f6fa4dd4e --- /dev/null +++ b/stubs/qrcode/qrcode/LUT.pyi @@ -0,0 +1,3 @@ +from typing import Final + +rsPoly_LUT: Final[dict[int, list[int]]] diff --git a/stubs/qrcode/qrcode/__init__.pyi b/stubs/qrcode/qrcode/__init__.pyi new file mode 100644 index 000000000000..2109f5de5a0a --- /dev/null +++ b/stubs/qrcode/qrcode/__init__.pyi @@ -0,0 +1,22 @@ +from _typeshed import ConvertibleToInt + +from qrcode import image as image +from qrcode.constants import ( + ERROR_CORRECT_H as ERROR_CORRECT_H, + ERROR_CORRECT_L as ERROR_CORRECT_L, + ERROR_CORRECT_M as ERROR_CORRECT_M, + ERROR_CORRECT_Q as ERROR_CORRECT_Q, +) +from qrcode.main import GenericImage, QRCode as QRCode, make as make + +from ._types import ErrorCorrect, MaskPattern + +def run_example( + data: str = "http://www.lincolnloop.com", + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: type[GenericImage] | None = None, + mask_pattern: MaskPattern | None = None, +) -> None: ... diff --git a/stubs/qrcode/qrcode/_types.pyi b/stubs/qrcode/qrcode/_types.pyi new file mode 100644 index 000000000000..91676c18a6a5 --- /dev/null +++ b/stubs/qrcode/qrcode/_types.pyi @@ -0,0 +1,15 @@ +# Type aliases used in this stub package +from _typeshed import SupportsWrite +from typing import Any, Protocol, TypeAlias, type_check_only + +Box: TypeAlias = tuple[tuple[int, int], tuple[int, int]] +Ink: TypeAlias = tuple[int, int, int] | tuple[int, int, int, int] + +# Don't try to make these Literal[x, y, z] as this really wreaks +# havoc with overloads in mypy. +ErrorCorrect: TypeAlias = int +MaskPattern: TypeAlias = int + +@type_check_only +class Writeable(SupportsWrite[bytes], Protocol): + def seek(self, offset: int, /) -> Any: ... diff --git a/stubs/qrcode/qrcode/base.pyi b/stubs/qrcode/qrcode/base.pyi new file mode 100644 index 000000000000..0b5cd8aa385f --- /dev/null +++ b/stubs/qrcode/qrcode/base.pyi @@ -0,0 +1,27 @@ +from collections.abc import Iterator +from typing import NamedTuple, SupportsIndex + +from ._types import ErrorCorrect + +EXP_TABLE: list[int] +LOG_TABLE: list[int] +RS_BLOCK_OFFSET: dict[ErrorCorrect, int] +RS_BLOCK_TABLE: tuple[tuple[int, int, int] | tuple[int, int, int, int, int, int], ...] + +def glog(n: int) -> int: ... +def gexp(n: int) -> int: ... + +class Polynomial: + num: list[int] + def __init__(self, num: list[int], shift: int) -> None: ... + def __getitem__(self, index: SupportsIndex) -> int: ... + def __iter__(self) -> Iterator[int]: ... + def __len__(self) -> int: ... + def __mul__(self, other: Polynomial) -> Polynomial: ... + def __mod__(self, other: Polynomial) -> Polynomial: ... + +class RSBlock(NamedTuple): + total_count: int + data_count: int + +def rs_blocks(version: int, error_correction: ErrorCorrect) -> list[RSBlock]: ... diff --git a/stubs/qrcode/qrcode/console_scripts.pyi b/stubs/qrcode/qrcode/console_scripts.pyi new file mode 100644 index 000000000000..44bc8d475a7e --- /dev/null +++ b/stubs/qrcode/qrcode/console_scripts.pyi @@ -0,0 +1,12 @@ +from collections.abc import Iterable, Sequence + +from ._types import ErrorCorrect +from .image.base import BaseImage, DrawerAliases as DrawerAliases + +default_factories: dict[str, str] +error_correction: dict[str, ErrorCorrect] + +def main(args: Sequence[str] | None = None) -> None: ... +def get_factory(module: str) -> type[BaseImage]: ... +def get_drawer_help() -> str: ... +def commas(items: Iterable[str], joiner: str = "or") -> str: ... diff --git a/stubs/qrcode/qrcode/constants.pyi b/stubs/qrcode/qrcode/constants.pyi new file mode 100644 index 000000000000..dc308677fe5c --- /dev/null +++ b/stubs/qrcode/qrcode/constants.pyi @@ -0,0 +1,6 @@ +from typing import Final + +ERROR_CORRECT_L: Final = 1 +ERROR_CORRECT_M: Final = 0 +ERROR_CORRECT_Q: Final = 3 +ERROR_CORRECT_H: Final = 2 diff --git a/stubs/qrcode/qrcode/exceptions.pyi b/stubs/qrcode/qrcode/exceptions.pyi new file mode 100644 index 000000000000..982223889922 --- /dev/null +++ b/stubs/qrcode/qrcode/exceptions.pyi @@ -0,0 +1 @@ +class DataOverflowError(Exception): ... diff --git a/stubs/qrcode/qrcode/image/__init__.pyi b/stubs/qrcode/qrcode/image/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/qrcode/qrcode/image/base.pyi b/stubs/qrcode/qrcode/image/base.pyi new file mode 100644 index 000000000000..03a5133994f4 --- /dev/null +++ b/stubs/qrcode/qrcode/image/base.pyi @@ -0,0 +1,66 @@ +from collections.abc import Callable +from typing import IO, Any, TypeAlias + +from ..main import ModulesType, QRCode +from .styles.moduledrawers.base import QRModuleDrawer + +# The second element of the value tuple are keyword arguments used when +# constructing instances of the QRModuleDrawer type. +DrawerAliases: TypeAlias = dict[str, tuple[type[QRModuleDrawer], dict[str, Any]]] + +class BaseImage: + kind: str | None + allowed_kinds: tuple[str] | None + needs_context: bool + needs_processing: bool + needs_drawrect: bool + border: int + width: int + box_size: int + pixel_size: int + modules: list[list[bool | None]] + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call. + def __init__( + self, border: int, width: int, box_size: int, *args: Any, qrcode_modules: ModulesType | None, **kwargs: Any + ) -> None: ... + def drawrect(self, row: int, col: int) -> None: ... + def drawrect_context(self, row: int, col: int, qr: QRCode[Any]) -> None: ... + def process(self) -> None: ... + def save(self, stream: IO[bytes], kind: str | None = None) -> None: ... + def pixel_box(self, row: int, col: int) -> tuple[tuple[int, int], tuple[int, int]]: ... + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Any: ... + def init_new_image(self) -> None: ... + # the get_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def get_image(self, **kwargs: Any) -> Any: ... + def check_kind(self, kind: str | None, transform: Callable[[str | None], str | None] | None = None) -> str | None: ... + def is_eye(self, row: int, col: int) -> bool: ... + +class BaseImageWithDrawer(BaseImage): + default_drawer_class: type[QRModuleDrawer] + drawer_aliases: DrawerAliases + def get_default_module_drawer(self) -> QRModuleDrawer: ... + def get_default_eye_drawer(self) -> QRModuleDrawer: ... + needs_context: bool + module_drawer: QRModuleDrawer + eye_drawer: QRModuleDrawer + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call + # via the BaseImage.__init__ method. + def __init__( + self, + border: int, + width: int, + box_size: int, + *args: Any, + qrcode_modules: ModulesType | None, + module_drawer: QRModuleDrawer | str | None = None, + eye_drawer: QRModuleDrawer | str | None = None, + **kwargs: Any, + ) -> None: ... + def get_drawer(self, drawer: QRModuleDrawer | str | None) -> QRModuleDrawer | None: ... + def init_new_image(self) -> None: ... + def drawrect_context(self, row: int, col: int, qr: QRCode[Any]) -> None: ... diff --git a/stubs/qrcode/qrcode/image/pil.pyi b/stubs/qrcode/qrcode/image/pil.pyi new file mode 100644 index 000000000000..635b069c6550 --- /dev/null +++ b/stubs/qrcode/qrcode/image/pil.pyi @@ -0,0 +1,30 @@ +from pathlib import Path +from typing import Any, Literal + +from PIL import Image + +from .._types import Writeable +from . import base + +class PilImage(base.BaseImage): + kind: Literal["PNG"] + fill_color: str + # the new_image and get_image methods accept arbitrary keyword arguments to + # accommodate subclasses with additional arguments. + def new_image(self, *, back_color: str = "white", fill_color: str = "black", **kwargs: Any) -> Image.Image: ... + def get_image(self, **kwargs: Any) -> Image.Image: ... + def drawrect(self, row: int, col: int) -> None: ... + # kwargs are passed on to PIL.Image.save, which also accepts arbitrary keyword arguments. + def save( # type: ignore[override] + self, + stream: str | bytes | Path | Writeable, + format: str | None = None, + *, + kind: str | None = None, + save_all: bool = ..., + bitmap_format: Literal["bmp", "png"] = ..., + optimize: bool = ..., + **kwargs: Any, + ) -> None: ... + # attribute access is forwarded to the wrapped PIL.Image.Image instance. + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/qrcode/qrcode/image/pure.pyi b/stubs/qrcode/qrcode/image/pure.pyi new file mode 100644 index 000000000000..5e5ec9c8c47b --- /dev/null +++ b/stubs/qrcode/qrcode/image/pure.pyi @@ -0,0 +1,22 @@ +from _typeshed import SupportsWrite +from collections.abc import Generator +from typing import Any, Literal, TypeAlias + +from . import base + +# png.Writer; no types available +_Writer: TypeAlias = Any + +class PyPNGImage(base.BaseImage): + kind: str + allowed_kinds: tuple[Literal["PNG"]] + # the new_image and get_image methods accept arbitrary keyword arguments to + # accommodate subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> _Writer: ... + def get_image(self, **kwargs: Any) -> _Writer: ... + def drawrect(self, row: int, col: int) -> None: ... + def save(self, stream: SupportsWrite[bytes], kind: str | None = None) -> None: ... + def rows_iter(self) -> Generator[list[int], Any]: ... + def border_rows_iter(self) -> Generator[list[int], Any]: ... + +PymagingImage = PyPNGImage diff --git a/stubs/qrcode/qrcode/image/styledpil.pyi b/stubs/qrcode/qrcode/image/styledpil.pyi new file mode 100644 index 000000000000..c8e28463352e --- /dev/null +++ b/stubs/qrcode/qrcode/image/styledpil.pyi @@ -0,0 +1,56 @@ +from _typeshed import SupportsRead +from pathlib import Path +from typing import Any, Literal + +from PIL import Image + +from .._types import Ink, Writeable +from ..main import ModulesType +from . import base +from .styles.colormasks import QRColorMask +from .styles.moduledrawers import SquareModuleDrawer +from .styles.moduledrawers.base import QRModuleDrawer + +class StyledPilImage(base.BaseImageWithDrawer): + kind: Literal["PNG"] + color_mask: QRColorMask + default_drawer_class: type[SquareModuleDrawer] + embeded_image: Image.Image + embeded_image_resample: Image.Resampling + paint_color: Ink + # the class accepts arbitrary additional positional arguments to accommodate + # subclasses with additional arguments. kwargs are forwarded to the `new_image()` call + # via the BaseImage.__init__ method. + def __init__( + self, + border: int, + width: int, + box_size: int, + *args: Any, + qrcode_modules: ModulesType | None, + module_drawer: QRModuleDrawer | str | None = None, + eye_drawer: QRModuleDrawer | str | None = None, + color_mask: QRColorMask = ..., + embeded_image_path: str | bytes | Path | SupportsRead[bytes] | None = None, + embeded_image: Image.Image | None = None, + embeded_image_resample: Image.Resampling = ..., + **kwargs: Any, + ) -> None: ... + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Image.Image: ... + def draw_embedded_image(self) -> None: ... + # kwargs are passed on to PIL.Image.save, which also accepts arbitrary keyword arguments. + def save( # type: ignore[override] + self, + stream: str | bytes | Path | Writeable, + format: str | None = None, + *, + kind: str | None = None, + save_all: bool = ..., + bitmap_format: Literal["bmp", "png"] = ..., + optimize: bool = ..., + **kwargs: Any, + ) -> None: ... + # attribute access is forwarded to the wrapped PIL.Image.Image instance. + def __getattr__(self, name: str) -> Any: ... diff --git a/stubs/qrcode/qrcode/image/styles/__init__.pyi b/stubs/qrcode/qrcode/image/styles/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/qrcode/qrcode/image/styles/colormasks.pyi b/stubs/qrcode/qrcode/image/styles/colormasks.pyi new file mode 100644 index 000000000000..4c66dd25e97a --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/colormasks.pyi @@ -0,0 +1,64 @@ +from _typeshed import SupportsRead +from pathlib import Path + +from PIL import Image + +from ..._types import Ink +from ..styledpil import StyledPilImage + +class QRColorMask: + back_color: Ink + has_transparency: bool + paint_color: Ink + # image is not actually used by any of the initialize implementations in this project. + def initialize(self, styledPilImage: StyledPilImage, image: Image.Image) -> None: ... + def apply_mask(self, image: Image.Image, use_cache: bool = False) -> None: ... + def get_fg_pixel(self, image: Image.Image, x: int, y: int) -> Ink: ... + def get_bg_pixel(self, image: Image.Image, x: int, y: int) -> Ink: ... + def interp_num(self, n1: int, n2: int, norm: float) -> int: ... + def interp_color(self, col1: Ink, col2: Ink, norm: float) -> Ink: ... + def extrap_num(self, n1: int, n2: int, interped_num: int) -> float | None: ... + def extrap_color(self, col1: Ink, col2: Ink, interped_color: Ink) -> float | None: ... + +class SolidFillColorMask(QRColorMask): + front_color: Ink + def __init__(self, back_color: Ink = (255, 255, 255), front_color: Ink = (0, 0, 0)) -> None: ... + def apply_mask(self, image: Image.Image) -> None: ... # type: ignore[override] + +class RadialGradiantColorMask(QRColorMask): + center_color: Ink + edge_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), center_color: Ink = (0, 0, 0), edge_color: Ink = (0, 0, 255) + ) -> None: ... + +class SquareGradiantColorMask(QRColorMask): + center_color: Ink + edge_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), center_color: Ink = (0, 0, 0), edge_color: Ink = (0, 0, 255) + ) -> None: ... + +class HorizontalGradiantColorMask(QRColorMask): + left_color: Ink + right_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), left_color: Ink = (0, 0, 0), right_color: Ink = (0, 0, 255) + ) -> None: ... + +class VerticalGradiantColorMask(QRColorMask): + top_color: Ink + bottom_color: Ink + def __init__( + self, back_color: Ink = (255, 255, 255), top_color: Ink = (0, 0, 0), bottom_color: Ink = (0, 0, 255) + ) -> None: ... + +class ImageColorMask(QRColorMask): + color_img: Ink + def __init__( + self, + back_color: Ink = (255, 255, 255), + color_mask_path: str | bytes | Path | SupportsRead[bytes] | None = None, + color_mask_image: Image.Image | None = None, + ) -> None: ... + paint_color: Ink diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi new file mode 100644 index 000000000000..f51cacc6181d --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/__init__.pyi @@ -0,0 +1,8 @@ +from .pil import ( + CircleModuleDrawer as CircleModuleDrawer, + GappedSquareModuleDrawer as GappedSquareModuleDrawer, + HorizontalBarsDrawer as HorizontalBarsDrawer, + RoundedModuleDrawer as RoundedModuleDrawer, + SquareModuleDrawer as SquareModuleDrawer, + VerticalBarsDrawer as VerticalBarsDrawer, +) diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi new file mode 100644 index 000000000000..74832b09b966 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/base.pyi @@ -0,0 +1,12 @@ +import abc + +from ...._types import Box +from ....main import ActiveWithNeighbors +from ...base import BaseImage + +class QRModuleDrawer(abc.ABC, metaclass=abc.ABCMeta): + needs_neighbors: bool = False + img: BaseImage + def initialize(self, img: BaseImage) -> None: ... + @abc.abstractmethod + def drawrect(self, box: Box, is_active: bool | ActiveWithNeighbors) -> None: ... diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi new file mode 100644 index 000000000000..637091661493 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/pil.pyi @@ -0,0 +1,66 @@ +import abc +from typing import Literal + +from PIL import Image, ImageDraw + +from ...._types import Box +from ....main import ActiveWithNeighbors +from ...styledpil import StyledPilImage +from .base import QRModuleDrawer + +ANTIALIASING_FACTOR: int + +class StyledPilQRModuleDrawer(QRModuleDrawer, metaclass=abc.ABCMeta): + img: StyledPilImage + +class SquareModuleDrawer(StyledPilQRModuleDrawer): + imgDraw: ImageDraw.ImageDraw + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class GappedSquareModuleDrawer(StyledPilQRModuleDrawer): + size_ratio: float + def __init__(self, size_ratio: float = 0.8) -> None: ... + imgDraw: ImageDraw.ImageDraw + delta: float + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class CircleModuleDrawer(StyledPilQRModuleDrawer): + circle: Image.Image + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + +class RoundedModuleDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + radius_ratio: float + def __init__(self, radius_ratio: float = 1) -> None: ... + corner_width: int + SQUARE: Image.Image + NW_ROUND: Image.Image + SW_ROUND: Image.Image + SE_ROUND: Image.Image + NE_ROUND: Image.Image + def setup_corners(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] + +class VerticalBarsDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + horizontal_shrink: float + def __init__(self, horizontal_shrink: float = 0.8) -> None: ... + half_height: int + delta: int + SQUARE: Image.Image + ROUND_TOP: Image.Image + ROUND_BOTTOM: Image.Image + def setup_edges(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] + +class HorizontalBarsDrawer(StyledPilQRModuleDrawer): + needs_neighbors: Literal[True] + vertical_shrink: float + def __init__(self, vertical_shrink: float = 0.8) -> None: ... + half_width: int + delta: int + SQUARE: Image.Image + ROUND_LEFT: Image.Image + ROUND_RIGHT: Image.Image + def setup_edges(self) -> None: ... + def drawrect(self, box: Box, is_active: ActiveWithNeighbors) -> None: ... # type: ignore[override] diff --git a/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi b/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi new file mode 100644 index 000000000000..dbbaa5653931 --- /dev/null +++ b/stubs/qrcode/qrcode/image/styles/moduledrawers/svg.pyi @@ -0,0 +1,56 @@ +import abc +from decimal import Decimal +from typing import Any, NamedTuple +from xml.etree.ElementTree import Element, QName + +from ...._types import Box +from ...svg import SvgFragmentImage, SvgPathImage +from .base import QRModuleDrawer + +ANTIALIASING_FACTOR: int + +class Coords(NamedTuple): + x0: Decimal + y0: Decimal + x1: Decimal + y1: Decimal + xh: Decimal + yh: Decimal + +class BaseSvgQRModuleDrawer(QRModuleDrawer, metaclass=abc.ABCMeta): + img: SvgFragmentImage + size_ratio: Decimal + # kwargs are used to allow for subclasses with additional keyword arguments + def __init__(self, *, size_ratio: Decimal = ..., **kwargs: Any) -> None: ... + box_delta: float + box_size: Decimal + box_half: Decimal + def coords(self, box: Box) -> Coords: ... + +class SvgQRModuleDrawer(BaseSvgQRModuleDrawer, metaclass=abc.ABCMeta): + tag: str + tag_qname: QName + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + @abc.abstractmethod + def el(self, box: Box) -> Element: ... + +class SvgSquareDrawer(SvgQRModuleDrawer): + unit_size: str + def el(self, box: Box) -> Element: ... + +class SvgCircleDrawer(SvgQRModuleDrawer): + tag: str + radius: str + def el(self, box: Box) -> Element: ... + +class SvgPathQRModuleDrawer(BaseSvgQRModuleDrawer, metaclass=abc.ABCMeta): + img: SvgPathImage + def drawrect(self, box: Box, is_active: bool) -> None: ... # type: ignore[override] + @abc.abstractmethod + def subpath(self, box: Box) -> str: ... + +class SvgPathSquareDrawer(SvgPathQRModuleDrawer): + def subpath(self, box: Box) -> str: ... + +class SvgPathCircleDrawer(SvgPathQRModuleDrawer): + def subpath(self, box: Box) -> str: ... diff --git a/stubs/qrcode/qrcode/image/svg.pyi b/stubs/qrcode/qrcode/image/svg.pyi new file mode 100644 index 000000000000..b5f662dbf869 --- /dev/null +++ b/stubs/qrcode/qrcode/image/svg.pyi @@ -0,0 +1,69 @@ +import abc +from decimal import Decimal +from typing import Any, Literal, overload +from xml.etree.ElementTree import Element + +from . import base +from .styles.moduledrawers.base import QRModuleDrawer + +class SvgFragmentImage(base.BaseImageWithDrawer, metaclass=abc.ABCMeta): + kind: str + allowed_kinds: tuple[Literal["SVG"]] + default_drawer_class: type[QRModuleDrawer] + unit_size: Decimal | str + + @overload + def units(self, pixels: int | Decimal, text: Literal[False]) -> Decimal: ... + @overload + def units(self, pixels: int | Decimal, text: Literal[True] = True) -> str: ... + + # to_string is delegated to ET.Element.tostring, which dictates the overload + # options here. + @overload + def to_string( + self, + *, + encoding: None = None, + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> bytes: ... + @overload + def to_string( + self, + *, + encoding: Literal["unicode"], + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> str: ... + @overload + def to_string( + self, + *, + encoding: str, + method: str | None = None, + xml_declaration: bool | None = None, + default_namespace: str | None = None, + short_empty_elements: bool = True, + ) -> Any: ... + + # the new_image method accepts arbitrary keyword arguments to accommodate + # subclasses with additional arguments. + def new_image(self, **kwargs: Any) -> Element: ... + +class SvgImage(SvgFragmentImage, metaclass=abc.ABCMeta): + background: str | None + drawer_aliases: base.DrawerAliases + +class SvgPathImage(SvgImage, metaclass=abc.ABCMeta): + QR_PATH_STYLE: dict[str, str] + path: Element | None + +class SvgFillImage(SvgImage, metaclass=abc.ABCMeta): + background: str + +class SvgPathFillImage(SvgPathImage, metaclass=abc.ABCMeta): + background: str diff --git a/stubs/qrcode/qrcode/main.pyi b/stubs/qrcode/qrcode/main.pyi new file mode 100644 index 000000000000..2c2fb05b2f72 --- /dev/null +++ b/stubs/qrcode/qrcode/main.pyi @@ -0,0 +1,139 @@ +from _typeshed import ConvertibleToInt +from collections.abc import Sequence +from typing import Any, Generic, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only + +from ._types import ErrorCorrect, MaskPattern +from .image.base import BaseImage +from .image.pil import PilImage +from .image.pure import PyPNGImage +from .util import QRData + +ModulesType: TypeAlias = list[list[bool | None]] +precomputed_qr_blanks: dict[int, ModulesType] + +_DefaultImage: TypeAlias = PilImage | PyPNGImage # PilImage if Pillow is installed, PyPNGImage otherwise +_AnySeq = TypeVar("_AnySeq", bound=Sequence[Any]) + +@overload +def make( + data: QRData | bytes | str, + *, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: None = None, + mask_pattern: MaskPattern | None = None, +) -> _DefaultImage: ... +@overload +def make( + data: QRData | bytes | str, + *, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, +) -> GenericImage: ... + +def copy_2d_array(x: Sequence[_AnySeq]) -> list[_AnySeq]: ... + +class ActiveWithNeighbors(NamedTuple): + NW: bool + N: bool + NE: bool + W: bool + me: bool + E: bool + SW: bool + S: bool + SE: bool + def __bool__(self) -> bool: ... + +GenericImage = TypeVar("GenericImage", bound=BaseImage) # noqa: Y001 +GenericImageLocal = TypeVar("GenericImageLocal", bound=BaseImage) # noqa: Y001 + +@type_check_only +class _TTYWriter(Protocol): + def isatty(self) -> bool: ... + def write(self, s: str, /) -> object: ... + def flush(self) -> object: ... + +class QRCode(Generic[GenericImage]): + modules: ModulesType + error_correction: ErrorCorrect + box_size: int + border: int + image_factory: type[GenericImage] | None + + @overload + def __init__( + self, + version: ConvertibleToInt | None, + error_correction: ErrorCorrect, + box_size: ConvertibleToInt, + border: ConvertibleToInt, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, + ) -> None: ... + @overload + def __init__( + self, + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + *, + image_factory: type[GenericImage], + mask_pattern: MaskPattern | None = None, + ) -> None: ... + @overload + def __init__( + self: QRCode[_DefaultImage], + version: ConvertibleToInt | None = None, + error_correction: ErrorCorrect = 0, + box_size: ConvertibleToInt = 10, + border: ConvertibleToInt = 4, + image_factory: None = None, + mask_pattern: MaskPattern | None = None, + ) -> None: ... + + @property + def version(self) -> int: ... + @version.setter + def version(self, value: ConvertibleToInt | None) -> None: ... + + @property + def mask_pattern(self) -> MaskPattern | None: ... + @mask_pattern.setter + def mask_pattern(self, pattern: MaskPattern | None) -> None: ... + + modules_count: int + data_cache: list[int] + data_list: list[QRData] + def clear(self) -> None: ... + def add_data(self, data: QRData | bytes | str, optimize: int = 20) -> None: ... + def make(self, fit: bool = True) -> None: ... + def makeImpl(self, test: bool, mask_pattern: MaskPattern) -> None: ... + def setup_position_probe_pattern(self, row: int, col: int) -> None: ... + def best_fit(self, start: int | None = None) -> int: ... + def best_mask_pattern(self) -> int: ... + def print_tty(self, out: _TTYWriter | None = None) -> None: ... + def print_ascii(self, out: _TTYWriter | None = None, tty: bool = False, invert: bool = False) -> None: ... + + # kwargs are passed on to the specific image factory used, and in turn passed through to + # their make_image method. + @overload + def make_image(self, image_factory: None = None, **kwargs: Any) -> GenericImage: ... + @overload + def make_image(self, image_factory: type[GenericImageLocal], **kwargs: Any) -> GenericImageLocal: ... + + def is_constrained(self, row: int, col: int) -> bool: ... + def setup_timing_pattern(self) -> None: ... + def setup_position_adjust_pattern(self) -> None: ... + def setup_type_number(self, test: bool) -> None: ... + def setup_type_info(self, test: bool, mask_pattern: MaskPattern) -> None: ... + def map_data(self, data: Sequence[int], mask_pattern: MaskPattern) -> None: ... + def get_matrix(self) -> list[list[bool]]: ... + def active_with_neighbors(self, row: int, col: int) -> ActiveWithNeighbors: ... diff --git a/stubs/qrcode/qrcode/release.pyi b/stubs/qrcode/qrcode/release.pyi new file mode 100644 index 000000000000..823dd58f3e15 --- /dev/null +++ b/stubs/qrcode/qrcode/release.pyi @@ -0,0 +1 @@ +def update_manpage(data: dict[str, str]) -> None: ... diff --git a/stubs/qrcode/qrcode/util.pyi b/stubs/qrcode/qrcode/util.pyi new file mode 100644 index 000000000000..0144c7951ecf --- /dev/null +++ b/stubs/qrcode/qrcode/util.pyi @@ -0,0 +1,70 @@ +from collections.abc import Callable, Generator +from re import Pattern +from typing import Final, Literal, TypeAlias, overload + +from ._types import ErrorCorrect, MaskPattern +from .base import RSBlock as RSBlock + +MODE_NUMBER: Final[int] = 1 +MODE_ALPHA_NUM: Final[int] = 2 +MODE_8BIT_BYTE: Final[int] = 4 +MODE_KANJI: Final[int] = 8 + +_MODE: TypeAlias = Literal[1, 2, 4, 8] + +MODE_SIZE_SMALL: Final[dict[_MODE, int]] +MODE_SIZE_MEDIUM: Final[dict[_MODE, int]] +MODE_SIZE_LARGE: Final[dict[_MODE, int]] + +ALPHA_NUM: Final[bytes] +RE_ALPHA_NUM: Final[Pattern[bytes]] +NUMBER_LENGTH: Final[dict[int, int]] +PATTERN_POSITION_TABLE: Final[list[list[int]]] +G15: Final[int] +G18: Final[int] +G15_MASK: Final[int] +PAD0: Final[int] +PAD1: Final[int] +BIT_LIMIT_TABLE: Final[list[list[int]]] + +# In the implementation, MODE_KANJI is not accepted in all places +_SupportedMode: TypeAlias = Literal[1, 2, 4] + +def BCH_type_info(data: int) -> int: ... +def BCH_type_number(data: int) -> int: ... +def BCH_digit(data: int) -> int: ... +def pattern_position(version: int) -> list[int]: ... +def mask_func(pattern: MaskPattern) -> Callable[[int, int], bool]: ... +def mode_sizes_for_version(version: int) -> dict[_MODE, int]: ... +def length_in_bits(mode: _MODE, version: int) -> int: ... +def check_version(version: int) -> None: ... +def lost_point(modules: list[list[bool | None]]) -> int: ... +def optimal_data_chunks(data: str | bytes, minimum: int = 4) -> Generator[QRData]: ... +def to_bytestring(data: str | bytes) -> bytes: ... +def optimal_mode(data: bytes) -> _SupportedMode: ... + +class QRData: + mode: _SupportedMode + data: bytes + + @overload + def __init__(self, data: bytes | str, mode: _SupportedMode | None = None, check_data: Literal[True] = True) -> None: ... + @overload + def __init__(self, data: bytes, mode: _SupportedMode | None = None, *, check_data: Literal[False]) -> None: ... + @overload + def __init__(self, data: bytes, mode: _SupportedMode | None, check_data: Literal[False]) -> None: ... + + def __len__(self) -> int: ... + def write(self, buffer: BitBuffer) -> None: ... + +class BitBuffer: + buffer: list[int] + length: int + def __init__(self) -> None: ... + def get(self, index: int) -> bool: ... + def put(self, num: int, length: int) -> None: ... + def __len__(self) -> int: ... + def put_bit(self, bit: bool) -> None: ... + +def create_bytes(buffer: BitBuffer, rs_blocks: list[RSBlock]) -> list[int]: ... +def create_data(version: int, error_correction: ErrorCorrect, data_list: list[QRData]) -> list[int]: ... diff --git a/stubs/rasterio/@tests/stubtest_allowlist.txt b/stubs/rasterio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ce1edb64708e --- /dev/null +++ b/stubs/rasterio/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# Stubs-only helper modules with no runtime counterpart. +rasterio\._typing +rasterio\._affine_types + +# Stubs-only type aliases referenced in signatures only. +rasterio\.merge\.MethodFunction + +# Cython implementation-detail attributes auto-generated on every +# Cython-compiled module and extension class. +.*\.__pyx_capi__ +.*\.__test__ +.*\.__reduce_cython__ +.*\.__setstate_cython__ + +# attrs-generated introspection helpers on every @attr.s class. +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_props__ + +# attrs-generated comparators and pattern-matching dunders on the +# specific @attr.s classes in the package (these are auto-generated by +# `order=True` / `eq=True`; not part of the documented API surface). +rasterio\._path\._ParsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\._path\._UnparsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.env\.GDALVersion\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.rpc\.RPC\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.windows\.Window\.__(ge|gt|le|lt|match_args|replace)__ + +# Cython param-name drift and @disjoint_base markers for private +# extension modules. Public API surface is reconciled in the +# corresponding public `rasterio.*` modules. +rasterio\._base.* +rasterio\._io.* +rasterio\._env.* +rasterio\._err.* +rasterio\._features.* +rasterio\._transform.* + +# Vendored third-party packages — not part of rasterio's public API. +rasterio\._vendor\..* + +# Click-based CLI subpackage — not exposed through type-checked imports. +rasterio\.rio.* diff --git a/stubs/rasterio/METADATA.toml b/stubs/rasterio/METADATA.toml new file mode 100644 index 000000000000..9988aeddf71d --- /dev/null +++ b/stubs/rasterio/METADATA.toml @@ -0,0 +1,7 @@ +version = "1.5.*" +upstream-repository = "https://github.com/rasterio/rasterio" +requires-python = ">=3.12" +dependencies = ["numpy>=2", "click>=8"] + +[tool.stubtest] +stubtest-dependencies = ["rasterio==1.5.*"] diff --git a/stubs/rasterio/rasterio/__init__.pyi b/stubs/rasterio/rasterio/__init__.pyi new file mode 100644 index 000000000000..0fe6afa52c86 --- /dev/null +++ b/stubs/rasterio/rasterio/__init__.pyi @@ -0,0 +1,132 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, NamedTuple, TypeAlias, overload + +from numpy.typing import DTypeLike, NDArray +from rasterio._base import DatasetBase as DatasetBase +from rasterio._io import Statistics as Statistics +from rasterio._path import _parse_path as _parse_path, _UnparsedPath as _UnparsedPath +from rasterio._show_versions import show_versions as show_versions +from rasterio._typing import AnyDataset, CRSInput, _Opener, _OpenOption +from rasterio._version import ( + gdal_version as gdal_version, + get_geos_version as get_geos_version, + get_proj_version as get_proj_version, +) +from rasterio._vsiopener import _opener_registration as _opener_registration +from rasterio.crs import CRS as CRS +from rasterio.drivers import driver_from_extension as driver_from_extension, is_blacklisted as is_blacklisted +from rasterio.dtypes import ( + bool_ as bool_, + check_dtype as check_dtype, + complex_ as complex_, + complex_int16 as complex_int16, + float16 as float16, + float32 as float32, + float64 as float64, + int8 as int8, + int16 as int16, + int32 as int32, + int64 as int64, + sbyte as sbyte, + ubyte as ubyte, + uint8 as uint8, + uint16 as uint16, + uint32 as uint32, + uint64 as uint64, +) +from rasterio.env import Env as Env, ensure_env_with_credentials as ensure_env_with_credentials +from rasterio.errors import ( + DriverCapabilityError as DriverCapabilityError, + RasterioDeprecationWarning as RasterioDeprecationWarning, + RasterioIOError as RasterioIOError, +) +from rasterio.io import ( + BufferedDatasetWriter as BufferedDatasetWriter, + DatasetReader as DatasetReader, + DatasetWriter as DatasetWriter, + FilePath as FilePath, + MemoryFile as MemoryFile, + get_writer_for_driver as get_writer_for_driver, + get_writer_for_path as get_writer_for_path, +) +from rasterio.profiles import default_gtiff_profile as default_gtiff_profile +from rasterio.transform import Affine as Affine, guard_transform as guard_transform + +__all__ = ["CRS", "Band", "Env", "band", "open", "pad"] + +__version__: Final[str] +__gdal_version__: Final[str] +__proj_version__: Final[str] +__geos_version__: Final[str] + +have_vsi_plugin: Final[bool] +log: logging.Logger + +_Fp: TypeAlias = str | os.PathLike[str] | MemoryFile | FilePath + +@overload +def open( + fp: _Fp, + mode: Literal["r"] = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader: ... +@overload +def open( + fp: _Fp, + mode: Literal["r+", "w", "w+"], + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetWriter: ... +@overload +def open( + fp: _Fp, + mode: str = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader | DatasetWriter: ... + +class Band(NamedTuple): + ds: AnyDataset + bidx: int | Sequence[int] + dtype: str + shape: tuple[int, ...] + +def band(ds: AnyDataset, bidx: int | Sequence[int]) -> Band: ... + +# `mode` and `**kwargs` mirror `numpy.pad`'s signature; see numpy.pad documentation. +def pad( + array: NDArray[Any], transform: Affine, pad_width: int, mode: str | Callable[..., Any] | None = None, **kwargs: Any +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/_affine_types.pyi b/stubs/rasterio/rasterio/_affine_types.pyi new file mode 100644 index 000000000000..bf462c70813f --- /dev/null +++ b/stubs/rasterio/rasterio/_affine_types.pyi @@ -0,0 +1,4 @@ +# Swap to `from affine import Affine as Affine` once affine ships `py.typed` (v3). +from typing import Any, TypeAlias + +Affine: TypeAlias = Any diff --git a/stubs/rasterio/rasterio/_base.pyi b/stubs/rasterio/rasterio/_base.pyi new file mode 100644 index 000000000000..8a7b76903797 --- /dev/null +++ b/stubs/rasterio/rasterio/_base.pyi @@ -0,0 +1,172 @@ +import logging +import os +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from rasterio._affine_types import Affine +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.coords import BoundingBox +from rasterio.crs import CRS +from rasterio.enums import ColorInterp, Compression, Interleaving, MaskFlags, PhotometricInterp +from rasterio.profiles import Profile +from rasterio.rpc import RPC +from rasterio.windows import Window + +log: Final[logging.Logger] + +def get_dataset_driver(path: str) -> str: ... +def driver_supports_mode(drivername: str, creation_mode: str) -> bool: ... +def driver_can_create(drivername: str) -> bool: ... +def driver_can_create_copy(drivername: str) -> bool: ... +def tastes_like_gdal(seq: Affine | Sequence[float]) -> bool: ... +def _raster_driver_extensions() -> dict[str, str]: ... +def _can_create_osr(crs: CRSInput) -> bool: ... +def _transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: Sequence[float], ys: Sequence[float], zs: Sequence[float] | None +) -> tuple[list[float], list[float], list[float]]: ... + +class DatasetBase: + name: str + mode: str + options: dict[str, Any] + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath | None = None, + driver: str | Sequence[str] | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def read_crs(self) -> CRS | None: ... + def read_transform(self) -> list[float]: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... + @property + def indexes(self) -> tuple[int, ...]: ... + @property + def dtypes(self) -> tuple[str, ...]: ... + @property + def block_shapes(self) -> tuple[tuple[int, int], ...]: ... + def get_nodatavals(self) -> tuple[float | None, ...]: ... + @property + def nodatavals(self) -> tuple[float | None, ...]: ... + + @property + def nodata(self) -> float | None: ... + @nodata.setter + def nodata(self, value: float | None) -> None: ... + + @property + def mask_flag_enums(self) -> tuple[list[MaskFlags], ...]: ... + + @property + def crs(self) -> CRS: ... + @crs.setter + def crs(self, value: CRSInput) -> None: ... + + @property + def descriptions(self) -> tuple[str | None, ...]: ... + @descriptions.setter + def descriptions(self, value: Sequence[str | None]) -> None: ... + + def write_transform(self, transform: Sequence[float]) -> None: ... + + @property + def transform(self) -> Affine: ... + @transform.setter + def transform(self, value: Affine) -> None: ... + + @property + def offsets(self) -> tuple[float, ...]: ... + @offsets.setter + def offsets(self, value: Sequence[float]) -> None: ... + + @property + def scales(self) -> tuple[float, ...]: ... + @scales.setter + def scales(self, value: Sequence[float]) -> None: ... + + @property + def units(self) -> tuple[str | None, ...]: ... + @units.setter + def units(self, value: Sequence[str | None]) -> None: ... + + def block_window(self, bidx: int, i: int, j: int) -> Window: ... + def block_size(self, bidx: int, i: int, j: int) -> int: ... + def block_windows(self, bidx: int = 0) -> Iterable[tuple[tuple[int, int], Window]]: ... + @property + def bounds(self) -> BoundingBox: ... + @property + def res(self) -> tuple[float, float]: ... + @property + def meta(self) -> dict[str, Any]: ... + @property + def compression(self) -> Compression | None: ... + @property + def interleaving(self) -> Interleaving | None: ... + @property + def photometric(self) -> PhotometricInterp | None: ... + @property + @deprecated("DatasetBase.is_tiled will be removed in a future rasterio release; inspect block_shapes / profile directly.") + def is_tiled(self) -> bool: ... + @property + def profile(self) -> Profile: ... + def lnglat(self) -> tuple[float, float]: ... + def get_transform(self) -> list[float]: ... + @property + def subdatasets(self) -> list[str]: ... + def tag_namespaces(self, bidx: int = 0) -> list[str]: ... + def tags(self, bidx: int = 0, ns: str | None = None) -> dict[str, str]: ... + def get_tag_item(self, ns: str, dm: str | None = None, bidx: int = 0, ovr: int | None = None) -> str | None: ... + + @property + def colorinterp(self) -> tuple[ColorInterp, ...]: ... + @colorinterp.setter + def colorinterp(self, value: Sequence[ColorInterp]) -> None: ... + + def colormap(self, bidx: int) -> Colormap: ... + def overviews(self, bidx: int) -> list[int]: ... + def checksum(self, bidx: int, window: Window | None = None) -> int: ... + def get_gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + + @property + def gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + @gcps.setter + def gcps(self, value: tuple[Sequence[GroundControlPoint], CRSInput]) -> None: ... + + @property + def rpcs(self) -> RPC | None: ... + @rpcs.setter + def rpcs(self, value: RPC | None) -> None: ... + + @property + def files(self) -> list[str]: ... + +_GDAL_AT_LEAST_3_10: Final[bool] + +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] +float32: Final[str] +float64: Final[str] +int16: Final[str] + +def _parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... diff --git a/stubs/rasterio/rasterio/_env.pyi b/stubs/rasterio/rasterio/_env.pyi new file mode 100644 index 000000000000..60dadbc6b7b2 --- /dev/null +++ b/stubs/rasterio/rasterio/_env.pyi @@ -0,0 +1,43 @@ +from contextlib import AbstractContextManager +from typing import Final + +from rasterio._typing import _GDALOption as _GDALOption + +ca_bundle: Final[str] +code_map: Final[dict[int, int]] +level_map: Final[dict[int, int]] + +def gdal_version() -> str: ... +def get_gdal_config(key: str, normalize: bool = True) -> _GDALOption: ... +def set_gdal_config(key: str, val: _GDALOption, normalize: bool = True) -> None: ... +def del_gdal_config(key: str) -> None: ... +def get_gdal_data() -> str | None: ... +def get_proj_data_search_paths() -> list[str]: ... +def set_proj_data_search_path(path: str) -> None: ... +def driver_count() -> int: ... +def catch_errors() -> AbstractContextManager[None]: ... + +class ConfigEnv: + options: dict[str, _GDALOption] + def __init__(self, **options: _GDALOption) -> None: ... + def update_config_options(self, **kwargs: _GDALOption) -> None: ... + def clear_config_options(self) -> None: ... + def get_config_options(self) -> dict[str, _GDALOption]: ... + +class GDALEnv(ConfigEnv): + def __init__(self, **options: _GDALOption) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + +class GDALDataFinder: + def find_file(self, basename: str) -> str | None: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... + def search_debian(self, prefix: str) -> str | None: ... + +class PROJDataFinder: + def has_data(self) -> bool: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... diff --git a/stubs/rasterio/rasterio/_err.pyi b/stubs/rasterio/rasterio/_err.pyi new file mode 100644 index 000000000000..84e6be115d76 --- /dev/null +++ b/stubs/rasterio/rasterio/_err.pyi @@ -0,0 +1,41 @@ +from contextlib import AbstractContextManager +from enum import IntEnum +from typing import Final + +class GDALError(IntEnum): + none = 0 + debug = 1 + warning = 2 + failure = 3 + fatal = 4 + +class CPLE_BaseError(Exception): + error: int + errno: int + errmsg: str + def __init__(self, error: int, errno: int, errmsg: str) -> None: ... + +class CPLE_AppDefinedError(CPLE_BaseError): ... +class CPLE_AssertionFailedError(CPLE_BaseError): ... +class CPLE_FileIOError(CPLE_BaseError): ... +class CPLE_HttpResponseError(CPLE_BaseError): ... +class CPLE_IllegalArgError(CPLE_BaseError): ... +class CPLE_NoWriteAccessError(CPLE_BaseError): ... +class CPLE_NotSupportedError(CPLE_BaseError): ... +class CPLE_OpenFailedError(CPLE_BaseError): ... +class CPLE_OutOfMemoryError(CPLE_BaseError): ... +class CPLE_UserInterruptError(CPLE_BaseError): ... +class CPLE_AWSAccessDeniedError(CPLE_BaseError): ... +class CPLE_AWSBucketNotFoundError(CPLE_BaseError): ... +class CPLE_AWSError(CPLE_BaseError): ... +class CPLE_AWSInvalidCredentialsError(CPLE_BaseError): ... +class CPLE_AWSObjectNotFoundError(CPLE_BaseError): ... +class CPLE_AWSSignatureDoesNotMatchError(CPLE_BaseError): ... +class ObjectNullError(CPLE_BaseError): ... + +exception_map: Final[dict[int, type[CPLE_BaseError]]] + +class StackChecker: + def __init__(self) -> None: ... + +def stack_errors() -> AbstractContextManager[StackChecker]: ... diff --git a/stubs/rasterio/rasterio/_features.pyi b/stubs/rasterio/rasterio/_features.pyi new file mode 100644 index 000000000000..2fec9414185a --- /dev/null +++ b/stubs/rasterio/rasterio/_features.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterator +from typing import Any, Final + +from rasterio._typing import _OGRGeometry +from rasterio.enums import MergeAlg as MergeAlg + +GEOMETRY_TYPES: Final[dict[int, str]] +GEOJSON2OGR_GEOMETRY_TYPES: Final[dict[str, int]] + +bool_: Final[str] +int8: Final[str] +int16: Final[str] +int32: Final[str] +int64: Final[str] +uint8: Final[str] +uint16: Final[str] +uint32: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] + +# Cython-side builders. `geom` arguments are opaque C structs / OGR +# geometry handles passed through `__pyx_capi__`; not surfaced via the +# public `rasterio.features` API. +class GeomBuilder: + def build(self, geom: object) -> dict[str, Any]: ... + +class OGRGeomBuilder: + def build(self, geom: dict[str, Any]) -> _OGRGeometry: ... + +class ShapeIterator: + def __iter__(self) -> Iterator[tuple[dict[str, Any], float]]: ... + def __next__(self) -> tuple[dict[str, Any], float]: ... diff --git a/stubs/rasterio/rasterio/_filepath.pyi b/stubs/rasterio/rasterio/_filepath.pyi new file mode 100644 index 000000000000..0cd22e067c4c --- /dev/null +++ b/stubs/rasterio/rasterio/_filepath.pyi @@ -0,0 +1,14 @@ +from typing import TypeVar + +_FileT = TypeVar("_FileT") + +class FilePathBase: + # Cython base for FilePath; constructor and overall surface are + # implementation details — see `rasterio.io.FilePath` for the public API. + def __init__(self, *args: object, **kwargs: object) -> None: ... + def close(self) -> None: ... + def exists(self) -> bool: ... + +# Clones any file-like object (BytesIO, MemoryFile, fsspec file, Python +# file object); the returned object has the same concrete type as `fobj`. +def clone_file_obj(fobj: _FileT) -> _FileT: ... diff --git a/stubs/rasterio/rasterio/_io.pyi b/stubs/rasterio/rasterio/_io.pyi new file mode 100644 index 000000000000..671d0067b07f --- /dev/null +++ b/stubs/rasterio/rasterio/_io.pyi @@ -0,0 +1,177 @@ +import os +from collections.abc import Iterator, Sequence +from typing import Any, BinaryIO, Final +from typing_extensions import Self, deprecated + +import numpy as np +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._base import DatasetBase +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, Indexes, NumType, ShapeND, WindowInput, _GDALOption, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +def validate_resampling(resampling: Resampling) -> None: ... +def virtual_file_to_buffer(filename: str) -> bytes: ... +def _is_complex_int(dtype: DTypeLike) -> bool: ... +def _getnpdtype(dtype: DTypeLike) -> np.dtype[Any]: ... +def _gdal_typename(dt: DTypeLike) -> str: ... +def _get_gdal_dtype(type_name: DTypeLike) -> int: ... +def _boundless_vrt_doc( + src_dataset: DatasetBase, + nodata: float | None = None, + background: float | None = None, + hidenodata: bool = False, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + masked: bool = False, + resampling: Resampling = ..., +) -> str: ... +def sample_gen( + dataset: DatasetBase, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False +) -> Iterator[NDArray[Any]]: ... + +class Statistics: + min: float + max: float + mean: float + std: float + def __init__(self, min: float, max: float, mean: float, std: float) -> None: ... + +class DatasetReaderBase(DatasetBase): + def read( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + boundless: bool = False, + resampling: Resampling = ..., + fill_value: NumType | None = None, + out_dtype: DTypeLike | None = None, + ) -> NDArray[Any]: ... + def read_masks( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def dataset_mask( + self, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def sample( + self, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False + ) -> Iterator[NDArray[Any]]: ... + def stats(self, *, indexes: Indexes | None = None, approx: bool = False) -> list[Statistics]: ... + @deprecated("DatasetReaderBase.statistics() will be removed in 2.0.0; please switch to stats().") + def statistics(self, bidx: int, approx: bool = False, clear_cache: bool = False) -> Statistics: ... + +class MemoryFileBase: + name: str + mode: str + closed: bool + def __init__( + self, + file_or_bytes: bytes | BinaryIO | None = None, + dirname: str | None = None, + filename: str | None = None, + ext: str = "", + ) -> None: ... + def __len__(self) -> int: ... + def exists(self) -> bool: ... + def getbuffer(self) -> memoryview: ... + def close(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def tell(self) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def write(self, data: bytes) -> int: ... + +class DatasetWriterBase(DatasetReaderBase): + name: str + mode: str + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def write( + self, arr: NDArray[Any], indexes: Indexes | None = None, window: WindowInput | None = None, masked: bool = False + ) -> None: ... + def write_band(self, bidx: int, src: NDArray[Any], window: WindowInput | None = None) -> None: ... + def update_tags(self, bidx: int = 0, ns: str | None = None, **kwargs: _GDALOption) -> None: ... + def set_band_description(self, bidx: int, value: str) -> None: ... + def set_band_unit(self, bidx: int, value: str) -> None: ... + def write_colormap(self, bidx: int, colormap: Colormap) -> None: ... + def write_mask(self, mask_array: NDArray[Any], window: WindowInput | None = None) -> None: ... + def build_overviews(self, factors: Sequence[int], resampling: Resampling = ...) -> None: ... + def update_stats( + self, *, stats: Sequence[Statistics] | None = None, indexes: Indexes | None = None, approx: bool = False + ) -> None: ... + def clear_stats(self) -> None: ... + +class MemoryDataset(DatasetWriterBase): + def __init__( + self, + image: NDArray[Any] | None = None, + dtype: DTypeLike | None = None, + count: int = 1, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + crs: CRSInput | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + +class BufferedDatasetWriterBase(DatasetWriterBase): + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str = "w", + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def stop(self) -> None: ... + +int8: Final[str] +uint8: Final[str] diff --git a/stubs/rasterio/rasterio/_path.pyi b/stubs/rasterio/rasterio/_path.pyi new file mode 100644 index 000000000000..cf9b098d569c --- /dev/null +++ b/stubs/rasterio/rasterio/_path.pyi @@ -0,0 +1,34 @@ +import os +from typing import Any, Final +from typing_extensions import Self + +SCHEMES: Final[dict[str, str]] +ARCHIVESCHEMES: Final[type[set[Any]]] +CURLSCHEMES: Final[set[str]] +REMOTESCHEMES: Final[set[str]] + +class _Path: + def as_vsi(self) -> str: ... + +class _ParsedPath(_Path): + path: str + archive: str | None + scheme: str | None + def __init__(self, path: str, archive: str | None, scheme: str | None) -> None: ... + @classmethod + def from_uri(cls, uri: str) -> Self: ... + @property + def name(self) -> str: ... + @property + def is_remote(self) -> bool: ... + @property + def is_local(self) -> bool: ... + +class _UnparsedPath(_Path): + path: str + def __init__(self, path: str) -> None: ... + @property + def name(self) -> str: ... + +def _parse_path(path: str | os.PathLike[str] | _Path) -> _ParsedPath | _UnparsedPath: ... +def _vsi_path(path: _Path) -> str: ... diff --git a/stubs/rasterio/rasterio/_show_versions.pyi b/stubs/rasterio/rasterio/_show_versions.pyi new file mode 100644 index 000000000000..1eeec0747405 --- /dev/null +++ b/stubs/rasterio/rasterio/_show_versions.pyi @@ -0,0 +1 @@ +def show_versions() -> None: ... diff --git a/stubs/rasterio/rasterio/_transform.pyi b/stubs/rasterio/rasterio/_transform.pyi new file mode 100644 index 000000000000..350f8c05cd60 --- /dev/null +++ b/stubs/rasterio/rasterio/_transform.pyi @@ -0,0 +1,16 @@ +from collections.abc import Sequence + +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.errors import TransformWarning as TransformWarning +from rasterio.rpc import RPC + +class GCPTransformerBase: + def __init__(self, gcps: Sequence[GroundControlPoint]) -> None: ... + def close(self) -> None: ... + +class RPCTransformerBase: + def __init__(self, rpcs: RPC, **kwargs: _GDALOption) -> None: ... + def close(self) -> None: ... + +def _transform_from_gcps(gcps: Sequence[GroundControlPoint]) -> tuple[float, ...]: ... diff --git a/stubs/rasterio/rasterio/_typing.pyi b/stubs/rasterio/rasterio/_typing.pyi new file mode 100644 index 000000000000..974afc3a8369 --- /dev/null +++ b/stubs/rasterio/rasterio/_typing.pyi @@ -0,0 +1,58 @@ +from collections.abc import Callable, Mapping, Sequence +from enum import Enum +from typing import Any, BinaryIO, Protocol, TypeAlias, type_check_only + +from rasterio.crs import CRS +from rasterio.io import DatasetReaderBase, MemoryFile +from rasterio.windows import Window + +# `DatasetReaderBase` covers every readable dataset handle: DatasetReader, +# DatasetWriter, BufferedDatasetWriter, MemoryDataset, and WarpedVRT (via +# WarpedVRTReaderBase). `MemoryFile` is a file wrapper, not a dataset. +AnyDataset: TypeAlias = DatasetReaderBase | MemoryFile + +@type_check_only +class _SupportsGeoInterface(Protocol): + @property + def __geo_interface__(self) -> Mapping[str, Any]: ... + +# A GeoJSON-like mapping, or any object exposing one through the +# `__geo_interface__` protocol (e.g. shapely / geopandas geometries). +# The runtime unwraps `__geo_interface__` before use, so both forms are +# accepted anywhere a geometry is expected. +Geometry: TypeAlias = Mapping[str, Any] | _SupportsGeoInterface # noqa: Y047 +Colormap: TypeAlias = dict[int, tuple[int, int, int] | tuple[int, int, int, int]] +CRSInput: TypeAlias = str | dict[str, str] | CRS +FileOrBytes: TypeAlias = BinaryIO | bytes +Indexes: TypeAlias = int | Sequence[int] +NumType: TypeAlias = int | float +ShapeND: TypeAlias = Sequence[int] +WindowInput: TypeAlias = Window | tuple[tuple[int, int], tuple[int, int]] + +# Scalar values accepted by every GDAL CSL-style option list: global +# config (`set_gdal_config` / `Env`), per-call warp options +# (NUM_THREADS, INIT_DEST, …), RPC/transformer options (RPC_HEIGHT, +# RPC_DEM, COORDINATE_OPERATION, …), and metadata tag values. The +# runtime stringifies each value at the C boundary and does not +# special-case Enum or tuple types here (use `_OpenOption` for those). +_GDALOption: TypeAlias = str | int | float | bool | None # noqa: Y047 + +# GDAL driver-specific open/creation option values. The runtime coerces +# every value to a string at the C boundary; documented usage covers +# scalars, Enum members (encoded as `.name.upper()`), and tuples of +# scalars (joined with commas). Lists are not handled specially — pass +# a tuple if you need a multi-value option. +_OpenOption: TypeAlias = str | int | float | bool | Enum | tuple[str | int | float | bool, ...] | None # noqa: Y047 + +# Opaque OGR geometry handle (a Cython-wrapped C object). Callers only +# pass it back to other Cython internals; the public API surfaces +# already-decoded GeoJSON-like dicts. +_OGRGeometry: TypeAlias = Any # noqa: Y047 + +# Scalar or arbitrarily nested list of scalars; used by helpers that +# recurse into sequences while preserving the nesting depth. +_NestedScalar: TypeAlias = float | list[_NestedScalar] # noqa: Y047 + +# fsspec-style opener forwarded to `rasterio.open(opener=...)`: +# `(path: str, mode: str) -> file-like`. +_Opener: TypeAlias = Callable[..., Any] # noqa: Y047 diff --git a/stubs/rasterio/rasterio/_version.pyi b/stubs/rasterio/rasterio/_version.pyi new file mode 100644 index 000000000000..063e03ad00dd --- /dev/null +++ b/stubs/rasterio/rasterio/_version.pyi @@ -0,0 +1,5 @@ +def gdal_version() -> str: ... +def get_gdal_version_info(key: str) -> str: ... +def check_gdal_version(major: int, minor: int) -> bool: ... +def get_geos_version() -> tuple[int, int, int]: ... +def get_proj_version() -> tuple[int, int, int]: ... diff --git a/stubs/rasterio/rasterio/_vsiopener.pyi b/stubs/rasterio/rasterio/_vsiopener.pyi new file mode 100644 index 000000000000..0354d31dc260 --- /dev/null +++ b/stubs/rasterio/rasterio/_vsiopener.pyi @@ -0,0 +1,36 @@ +from abc import ABC, abstractmethod +from contextlib import AbstractContextManager +from typing import Any, BinaryIO + +from rasterio.errors import OpenerRegistrationError as OpenerRegistrationError + +class FileContainer(ABC): + @abstractmethod + def open(self, path: str, mode: str = "r", **kwds: Any) -> BinaryIO: ... + @abstractmethod + def isdir(self, path: str) -> bool: ... + @abstractmethod + def isfile(self, path: str) -> bool: ... + @abstractmethod + def ls(self, path: str) -> list[str]: ... + @abstractmethod + def mtime(self, path: str) -> int: ... + @abstractmethod + def rm(self, path: str) -> None: ... + @abstractmethod + def size(self, path: str) -> int: ... + +class MultiByteRangeResource(ABC): + @abstractmethod + def get_byte_ranges(self, offsets: list[int], sizes: list[int]) -> list[bytes]: ... + +class MultiByteRangeResourceContainer(FileContainer): + @abstractmethod + def open(self, path: str, **kwds: Any) -> MultiByteRangeResource: ... # type: ignore[override] + +# Duck-typed adapter: `obj` may be a `FileContainer` subclass or any +# object exposing the fsspec filesystem protocol (`hasattr(obj, "file_size")`). +def to_pyopener(obj: Any) -> FileContainer: ... + +# `obj` accepts the same types as `to_pyopener` plus raw callables. +def _opener_registration(urlpath: str, obj: Any) -> AbstractContextManager[str]: ... diff --git a/stubs/rasterio/rasterio/_warp.pyi b/stubs/rasterio/rasterio/_warp.pyi new file mode 100644 index 000000000000..b98484b6fd62 --- /dev/null +++ b/stubs/rasterio/rasterio/_warp.pyi @@ -0,0 +1,123 @@ +from collections.abc import Sequence +from typing import Any, Final + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._io import DatasetReaderBase +from rasterio._typing import CRSInput, Geometry, Indexes, ShapeND, WindowInput, _GDALOption, _NestedScalar +from rasterio.control import GroundControlPoint +from rasterio.crs import CRS +from rasterio.enums import Resampling +from rasterio.io import DatasetReader +from rasterio.rpc import RPC + +SUPPORTED_RESAMPLING: Final[list[Resampling]] +DEFAULT_NODATA_FLAG: Final[object] + +def recursive_round(val: _NestedScalar, precision: int) -> _NestedScalar: ... +def _transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], precision: int +) -> dict[str, Any] | list[dict[str, Any]]: ... +def _reproject( + source: NDArray[Any] | Any, + destination: NDArray[Any] | Any, + src_transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_alpha: int = 0, + src_alpha: int = 0, + resampling: Resampling = ..., + init_dest_nodata: bool = True, + tolerance: float = 0.125, + num_threads: int = 1, + warp_mem_limit: int = 0, + working_data_type: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def _calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... +def _transform_bounds( + src_crs: CRS, dst_crs: CRS, left: float, bottom: float, right: float, top: float, densify_pts: int +) -> tuple[float, float, float, float]: ... +def _suggested_proxy_vrt_doc( + width: int, + height: int, + transform: Affine | None = None, + crs: CRSInput | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, +) -> str: ... + +class WarpedVRTReaderBase(DatasetReaderBase): + src_dataset: DatasetReader + src_crs: CRS + src_transform: Affine | None + resampling: Resampling + tolerance: float + src_nodata: float | None + dst_nodata: float | None + working_dtype: DTypeLike | None + warp_extras: dict[str, _GDALOption] + + def __init__( + self, + src_dataset: DatasetReader, + src_crs: CRSInput | None = None, + crs: CRSInput | None = None, + resampling: Resampling = ..., + tolerance: float = 0.125, + src_nodata: float | None = ..., + nodata: float | None = ..., + width: int | None = None, + height: int | None = None, + src_transform: Affine | None = None, + transform: Affine | None = None, + init_dest_nodata: bool = True, + src_alpha: int = 0, + dst_alpha: int = 0, + add_alpha: bool = False, + warp_mem_limit: int = 0, + dtype: DTypeLike | None = None, + **warp_extras: _GDALOption, + ) -> None: ... + def read( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + resampling: Resampling = ..., + fill_value: float | None = None, + out_dtype: DTypeLike | None = None, + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... + def read_masks( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + resampling: Resampling = ..., + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/abc.pyi b/stubs/rasterio/rasterio/abc.pyi new file mode 100644 index 000000000000..d9ebb71719e0 --- /dev/null +++ b/stubs/rasterio/rasterio/abc.pyi @@ -0,0 +1 @@ +from rasterio._vsiopener import FileContainer as FileContainer, MultiByteRangeResourceContainer as MultiByteRangeResourceContainer diff --git a/stubs/rasterio/rasterio/cache.pyi b/stubs/rasterio/rasterio/cache.pyi new file mode 100644 index 000000000000..ab1f8b285843 --- /dev/null +++ b/stubs/rasterio/rasterio/cache.pyi @@ -0,0 +1,2 @@ +def invalidate(pattern: str) -> None: ... +def invalidate_all() -> None: ... diff --git a/stubs/rasterio/rasterio/control.pyi b/stubs/rasterio/rasterio/control.pyi new file mode 100644 index 000000000000..0fbec047e6be --- /dev/null +++ b/stubs/rasterio/rasterio/control.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Literal, TypedDict, type_check_only + +@type_check_only +class GroundControlPointDict(TypedDict): + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + +@type_check_only +class GroundControlPointGeometry(TypedDict): + type: Literal["Point"] + coordinates: Sequence[float] + +@type_check_only +class GroundControlPointFeature(TypedDict): + id: str + type: Literal["Feature"] + geometry: GroundControlPointGeometry + properties: GroundControlPointDict + +class GroundControlPoint: + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + def __init__( + self, + row: float | None = None, + col: float | None = None, + x: float | None = None, + y: float | None = None, + z: float | None = None, + id: str | None = None, + info: str | None = None, + ) -> None: ... + def asdict(self) -> GroundControlPointDict: ... + @property + def __geo_interface__(self) -> GroundControlPointFeature: ... diff --git a/stubs/rasterio/rasterio/coords.pyi b/stubs/rasterio/rasterio/coords.pyi new file mode 100644 index 000000000000..c7b97fc2fe31 --- /dev/null +++ b/stubs/rasterio/rasterio/coords.pyi @@ -0,0 +1,11 @@ +from typing import NamedTuple, TypeAlias + +_Quadruple: TypeAlias = tuple[float, float, float, float] + +class BoundingBox(NamedTuple): + left: float + bottom: float + right: float + top: float + +def disjoint_bounds(bounds1: BoundingBox | _Quadruple, bounds2: BoundingBox | _Quadruple) -> bool: ... diff --git a/stubs/rasterio/rasterio/crs.pyi b/stubs/rasterio/rasterio/crs.pyi new file mode 100644 index 000000000000..400c4c939d68 --- /dev/null +++ b/stubs/rasterio/rasterio/crs.pyi @@ -0,0 +1,69 @@ +from collections.abc import Iterator, Mapping +from typing import Any +from typing_extensions import Self, deprecated, disjoint_base + +from rasterio.enums import WktVersion + +all_proj_keys: set[str] + +@disjoint_base +class CRS(Mapping[str, Any]): + def __init__(self, initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> None: ... + def __getitem__(self, key: str, /) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... + def __copy__(self) -> Self: ... + def __hash__(self) -> int: ... + def __getstate__(self) -> dict[str, Any]: ... + def __setstate__(self, state: Mapping[str, Any]) -> None: ... + def to_proj4(self) -> str: ... + def to_wkt(self, morph_to_esri_dialect: bool = False, version: WktVersion | str | None = None) -> str: ... + @property + def wkt(self) -> str: ... + def to_epsg(self, confidence_threshold: int = 70) -> int | None: ... + def to_authority(self, confidence_threshold: int = 70) -> tuple[str, str] | None: ... + def to_dict(self, projjson: bool = False) -> dict[str, Any]: ... + @property + def data(self) -> dict[str, Any]: ... + @property + def is_geographic(self) -> bool: ... + @property + def is_projected(self) -> bool: ... + @property + @deprecated("CRS.is_valid is deprecated since rasterio 1.4 and will be removed in 2.0.0.") + def is_valid(self) -> bool: ... + @property + def is_epsg_code(self) -> bool: ... + @property + def linear_units_factor(self) -> tuple[str, float]: ... + @property + def linear_units(self) -> str: ... + @property + def units_factor(self) -> tuple[str, float]: ... + @property + def geodetic_crs(self) -> CRS | None: ... + def to_string(self) -> str: ... + def equals(self, other: CRS, ignore_axis_order: bool = False) -> bool: ... + def get(self, item: str) -> Any: ... # type: ignore[override] + @staticmethod + def from_epsg(code: int | str) -> CRS: ... + @staticmethod + def from_authority(auth_name: str, code: int | str) -> CRS: ... + @staticmethod + def from_string(value: str, morph_from_esri_dialect: bool = False) -> CRS: ... + @staticmethod + def from_proj4(proj: str) -> CRS: ... + @staticmethod + def from_dict(initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> CRS: ... + @staticmethod + def from_wkt(wkt: str, morph_from_esri_dialect: bool = False) -> CRS: ... + # `value` is dispatched at runtime: CRS, int (EPSG), str (PROJ/WKT/auth), Mapping[str, Any], or any pyproj-CRS-like object. + @staticmethod + def from_user_input(value: Any, morph_from_esri_dialect: bool = False) -> CRS: ... + +def epsg_treats_as_latlong(input_crs: CRS) -> bool: ... +def epsg_treats_as_northingeasting(input_crs: CRS) -> bool: ... +def auth_preference(item: str) -> None: ... diff --git a/stubs/rasterio/rasterio/drivers.pyi b/stubs/rasterio/rasterio/drivers.pyi new file mode 100644 index 000000000000..96b6d727bd5b --- /dev/null +++ b/stubs/rasterio/rasterio/drivers.pyi @@ -0,0 +1,8 @@ +import os +from typing import Final + +blacklist: Final[dict[str, tuple[str, ...]]] + +def raster_driver_extensions() -> dict[str, str]: ... +def driver_from_extension(path: str | os.PathLike[str]) -> str: ... +def is_blacklisted(name: str, mode: str) -> bool: ... diff --git a/stubs/rasterio/rasterio/dtypes.pyi b/stubs/rasterio/rasterio/dtypes.pyi new file mode 100644 index 000000000000..f76501ed11d1 --- /dev/null +++ b/stubs/rasterio/rasterio/dtypes.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Any, Final + +import numpy as np +from numpy.typing import ArrayLike, DTypeLike + +bool_: Final[str] +ubyte: Final[str] +uint8: Final[str] +sbyte: Final[str] +int8: Final[str] +uint16: Final[str] +int16: Final[str] +uint32: Final[str] +int32: Final[str] +int64: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] +complex_: Final[str] +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] + +dtype_fwd: Final[dict[int, str | None]] +dtype_rev: Final[dict[str | None, int]] +typename_fwd: Final[dict[int, str]] +typename_rev: Final[dict[str, int]] +dtype_ranges: Final[dict[str, tuple[float, float]]] +dtype_info_registry: Final[dict[str, type]] + +# `numpy.finfo` instances cached at module import; used by `in_dtype_range`. +f16i: Final[np.finfo[np.float16]] +f32i: Final[np.finfo[np.float32]] +f64i: Final[np.finfo[np.float64]] + +def in_dtype_range(value: float, dtype: DTypeLike) -> bool: ... +def check_dtype(dt: DTypeLike) -> bool: ... +def get_minimum_dtype(values: ArrayLike) -> str: ... + +# isinstance check; accepts any object and returns True for numpy.ndarray +# and any object exposing `__array__`. +def is_ndarray(array: Any) -> bool: ... +def can_cast_dtype(values: ArrayLike, dtype: DTypeLike) -> bool: ... +def validate_dtype(values: ArrayLike, valid_dtypes: Sequence[DTypeLike]) -> bool: ... diff --git a/stubs/rasterio/rasterio/enums.pyi b/stubs/rasterio/rasterio/enums.pyi new file mode 100644 index 000000000000..6e1a2fc76a6b --- /dev/null +++ b/stubs/rasterio/rasterio/enums.pyi @@ -0,0 +1,126 @@ +from enum import Enum, IntEnum + +class TransformDirection(IntEnum): + forward = 1 + reverse = 0 + +class TransformMethod(Enum): + affine = "transform" + gcps = "gcps" + rpcs = "rpcs" + +class ColorInterp(IntEnum): + undefined = 0 + gray = 1 + grey = 1 + palette = 2 + red = 3 + green = 4 + blue = 5 + alpha = 6 + hue = 7 + saturation = 8 + lightness = 9 + cyan = 10 + magenta = 11 + yellow = 12 + black = 13 + Y = 14 + Cb = 15 + Cr = 16 + pan = 17 + coastal = 18 + rededge = 19 + nir = 20 + swir = 21 + mwir = 22 + lwir = 23 + tir = 24 + other_ir = 25 + sar_ka = 30 + sar_k = 31 + sar_ku = 32 + sar_x = 33 + sar_c = 34 + sar_s = 35 + sar_l = 36 + sar_p = 37 + +class Resampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + max = 8 + min = 9 + med = 10 + q1 = 11 + q3 = 12 + sum = 13 + rms = 14 + +class OverviewResampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + rms = 14 + +class Compression(Enum): + jpeg = "JPEG" + lzw = "LZW" + packbits = "PACKBITS" + deflate = "DEFLATE" + ccittrle = "CCITTRLE" + ccittfax3 = "CCITTFAX3" + ccittfax4 = "CCITTFAX4" + lzma = "LZMA" + none = "NONE" + zstd = "ZSTD" + lerc = "LERC" + lerc_deflate = "LERC_DEFLATE" + lerc_zstd = "LERC_ZSTD" + webp = "WEBP" + jpeg2000 = "JPEG2000" + +class Interleaving(Enum): + pixel = "PIXEL" + line = "LINE" + band = "BAND" + tile = "TILE" + +class MaskFlags(IntEnum): + all_valid = 1 + per_dataset = 2 + alpha = 4 + nodata = 8 + +class PhotometricInterp(Enum): + black = "MINISBLACK" + white = "MINISWHITE" + rgb = "RGB" + cmyk = "CMYK" + ycbcr = "YCbCr" + cielab = "CIELAB" + icclab = "ICCLAB" + itulab = "ITULAB" + +class MergeAlg(Enum): + replace = "REPLACE" + add = "ADD" + +class WktVersion(Enum): + WKT2_2015 = "WKT2_2015" + WKT2 = "WKT2" + WKT2_2019 = "WKT2_2018" + WKT1_GDAL = "WKT1_GDAL" + WKT1 = "WKT1" + WKT1_ESRI = "WKT1_ESRI" diff --git a/stubs/rasterio/rasterio/env.pyi b/stubs/rasterio/rasterio/env.pyi new file mode 100644 index 000000000000..3f5c57bfeb2a --- /dev/null +++ b/stubs/rasterio/rasterio/env.pyi @@ -0,0 +1,102 @@ +import logging +import threading +from collections.abc import Callable, Iterable +from types import TracebackType +from typing import Any, Final, TypeVar +from typing_extensions import Self, deprecated + +from rasterio._env import ( + GDALDataFinder as GDALDataFinder, + GDALEnv as GDALEnv, + PROJDataFinder as PROJDataFinder, + _GDALOption, + get_gdal_config as get_gdal_config, + set_gdal_config as set_gdal_config, + set_proj_data_search_path as set_proj_data_search_path, +) +from rasterio.errors import ( + EnvError as EnvError, + GDALVersionError as GDALVersionError, + RasterioDeprecationWarning as RasterioDeprecationWarning, +) +from rasterio.session import DummySession as DummySession, Session as Session + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class ThreadEnv(threading.local): + def __init__(self) -> None: ... + +local: ThreadEnv +log: logging.Logger + +class Env: + session: Session + options: dict[str, _GDALOption] + context_options: dict[str, _GDALOption] + def __init__( + self, + session: Session | None = None, + aws_unsigned: bool = False, + profile_name: str | None = None, + session_class: Callable[..., Session] = ..., + **options: _GDALOption, + ) -> None: ... + @classmethod + def default_options(cls) -> dict[str, _GDALOption]: ... + # Forwarded to `cls(...)` after merging in default_options(); see __init__. + @classmethod + def from_defaults(cls, *args: Any, **kwargs: _GDALOption) -> Self: ... + def credentialize(self) -> None: ... + def aws_creds_from_context_options(self) -> dict[str, str]: ... + def drivers(self) -> dict[str, str]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: ... + +def defenv(**options: _GDALOption) -> None: ... +def getenv() -> dict[str, _GDALOption]: ... +def hasenv() -> bool: ... +def setenv(**options: _GDALOption) -> None: ... +@deprecated("Please use Env.session.hascreds() instead.") +def hascreds() -> bool: ... +def delenv() -> None: ... + +class NullContextManager: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +def env_ctx_if_needed() -> Env | NullContextManager: ... +def ensure_env(f: _F) -> _F: ... +@deprecated("ensure_env_credentialled is a deprecated alias; use ensure_env_with_credentials instead.") +def ensure_env_credentialled(f: _F) -> _F: ... +def ensure_env_with_credentials(f: _F) -> _F: ... +def gdal_version() -> str: ... + +class GDALVersion: + major: int + minor: int + patch: int + def __init__(self, major: int = 0, minor: int = 0, patch: int = 0) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: GDALVersion) -> bool: ... + @classmethod + def parse(cls, input: str | GDALVersion, include_patch: bool = False) -> Self: ... + @classmethod + def runtime(cls, include_patch: bool = False) -> Self: ... + def at_least(self, other: str | GDALVersion, include_patch: bool = False) -> bool: ... + +def require_gdal_version( + version: str | GDALVersion, + param: str | None = None, + # `values` are matched against the decorated function's `param` argument; types depend on that argument. + values: Iterable[Any] | None = None, + is_max_version: bool = False, + reason: str = "", +) -> Callable[[_F], _F]: ... + +path: Final[str | None] diff --git a/stubs/rasterio/rasterio/errors.pyi b/stubs/rasterio/rasterio/errors.pyi new file mode 100644 index 000000000000..c883864c3f86 --- /dev/null +++ b/stubs/rasterio/rasterio/errors.pyi @@ -0,0 +1,40 @@ +from click import FileError + +class RasterioError(Exception): ... +class InvalidArrayError(RasterioError): ... +class WindowError(RasterioError): ... +class CRSError(ValueError): ... +class EnvError(RasterioError): ... +class DriverCapabilityError(RasterioError, ValueError): ... +class DriverRegistrationError(ValueError): ... + +class FileOverwriteError(FileError): + def __init__(self, message: str) -> None: ... + +class RasterioIOError(RasterioError, OSError): ... +class NodataShadowWarning(UserWarning): ... +class NotGeoreferencedWarning(UserWarning): ... +class TransformWarning(UserWarning): ... +class RPCError(ValueError): ... +class ShapeSkipWarning(UserWarning): ... +class GDALBehaviorChangeException(RuntimeError): ... +class GDALOptionNotImplementedError(RasterioError): ... +class GDALVersionError(RasterioError): ... +class WindowEvaluationError(ValueError): ... +class RasterioDeprecationWarning(FutureWarning): ... +class RasterBlockError(RasterioError): ... +class BandOverviewError(UserWarning): ... +class WarpOptionsError(RasterioError): ... +class UnsupportedOperation(RasterioError): ... +class OverviewCreationError(RasterioError): ... +class DatasetAttributeError(RasterioError, NotImplementedError): ... +class PathError(RasterioError): ... +class ResamplingAlgorithmError(RasterioError): ... +class TransformError(RasterioError): ... +class WarpedVRTError(RasterioError): ... +class DatasetIOShapeError(RasterioError): ... +class WarpOperationError(RasterioError): ... +class StatisticsError(RasterioError): ... +class OpenerRegistrationError(RasterioError): ... +class MergeError(RasterioError): ... +class StackError(RasterioError): ... diff --git a/stubs/rasterio/rasterio/features.pyi b/stubs/rasterio/rasterio/features.pyi new file mode 100644 index 000000000000..d3689801f08e --- /dev/null +++ b/stubs/rasterio/rasterio/features.pyi @@ -0,0 +1,74 @@ +import logging +import os +from collections.abc import Iterable, Iterator +from typing import Any, Final, overload +from typing_extensions import deprecated + +import numpy as np +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._typing import Geometry as Geometry +from rasterio.enums import MergeAlg as MergeAlg +from rasterio.io import DatasetReaderBase +from rasterio.windows import Window as Window + +log: Final[logging.Logger] + +def geometry_mask( + geometries: Iterable[Geometry], out_shape: tuple[int, int], transform: Affine, all_touched: bool = False, invert: bool = False +) -> NDArray[np.bool_]: ... +def shapes( + source: NDArray[Any], mask: NDArray[np.bool_] | None = None, connectivity: int = 4, transform: Affine = ... +) -> Iterator[tuple[dict[str, Any], float | int]]: ... +def sieve( + source: NDArray[Any], size: int, out: NDArray[Any] | None = None, mask: NDArray[np.bool_] | None = None, connectivity: int = 4 +) -> NDArray[Any]: ... +def rasterize( + shapes: Iterable[tuple[Geometry, float] | Geometry], + out_shape: tuple[int, int] | None = None, + fill: float = 0, + nodata: float | None = None, + masked: bool = False, + out: NDArray[Any] | None = None, + transform: Affine = ..., + all_touched: bool = False, + merge_alg: MergeAlg = ..., + default_value: float = 1, + dtype: DTypeLike | None = None, + skip_invalid: bool = True, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> NDArray[Any]: ... +def bounds(geometry: Geometry, north_up: bool = True, transform: Affine | None = None) -> tuple[float, float, float, float]: ... + +@overload +def geometry_window( + dataset: DatasetReaderBase, shapes: Iterable[Geometry], pad_x: float = 0, pad_y: float = 0, *, boundless: bool = False +) -> Window: ... +@overload +@deprecated( + "`north_up`, `rotated`, and `pixel_precision` on features.geometry_window are " + "unused since rasterio 1.2.1 and will be removed in a future release." +) +def geometry_window( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + pad_x: float = 0, + pad_y: float = 0, + north_up: bool | None = None, + rotated: bool | None = None, + pixel_precision: float | None = None, + boundless: bool = False, +) -> Window: ... + +def is_valid_geom(geom: Geometry) -> bool: ... +def dataset_features( + src: DatasetReaderBase, + bidx: int | None = None, + sampling: int = 1, + band: bool = True, + as_mask: bool = False, + with_nodata: bool = False, + geographic: bool = True, + precision: int = -1, +) -> Iterator[dict[str, Any]]: ... diff --git a/stubs/rasterio/rasterio/fill.pyi b/stubs/rasterio/rasterio/fill.pyi new file mode 100644 index 000000000000..8f121f75a3a8 --- /dev/null +++ b/stubs/rasterio/rasterio/fill.pyi @@ -0,0 +1,11 @@ +from typing import Any + +from numpy.ma import MaskedArray +from numpy.typing import NDArray + +def fillnodata( + image: NDArray[Any] | MaskedArray[Any, Any], + mask: NDArray[Any] | None = None, + max_search_distance: float = 100.0, + smoothing_iterations: int = 0, +) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/io.pyi b/stubs/rasterio/rasterio/io.pyi new file mode 100644 index 000000000000..ad52b80ed0a7 --- /dev/null +++ b/stubs/rasterio/rasterio/io.pyi @@ -0,0 +1,67 @@ +import logging +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from numpy.typing import DTypeLike +from rasterio._affine_types import Affine +from rasterio._filepath import FilePathBase as FilePathBase +from rasterio._io import ( + BufferedDatasetWriterBase as BufferedDatasetWriterBase, + DatasetReaderBase as DatasetReaderBase, + DatasetWriterBase as DatasetWriterBase, + MemoryFileBase as MemoryFileBase, +) +from rasterio._typing import CRSInput, FileOrBytes, _OpenOption +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +log: Final[logging.Logger] + +class DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin): ... +class DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... +class BufferedDatasetWriter(BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... + +class MemoryFile(MemoryFileBase): + def __init__( + self, file_or_bytes: FileOrBytes | None = None, dirname: str | None = None, filename: str | None = None, ext: str = ".tif" + ) -> None: ... + def open( + self, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> DatasetReader | DatasetWriter: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +class ZipMemoryFile(MemoryFile): + def __init__(self, file_or_bytes: FileOrBytes | None = None) -> None: ... + def open( # type: ignore[override] + self, path: str, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + +@deprecated("FilePath is supplanted by rasterio.open's `opener` keyword argument and will be removed in 2.0.0.") +class FilePath(FilePathBase): + # `filelike_obj`: any Python file-like object (BytesIO, fsspec file, etc.). + def __init__(self, filelike_obj: Any, dirname: str | None = None, filename: str | None = None) -> None: ... + def open( + self, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +def get_writer_for_driver(driver: str) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... +def get_writer_for_path(path: str, driver: str | None = None) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... diff --git a/stubs/rasterio/rasterio/mask.pyi b/stubs/rasterio/rasterio/mask.pyi new file mode 100644 index 000000000000..016f621c567f --- /dev/null +++ b/stubs/rasterio/rasterio/mask.pyi @@ -0,0 +1,34 @@ +import logging +from collections.abc import Iterable +from typing import Any, Final + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio._typing import Geometry +from rasterio.errors import WindowError as WindowError +from rasterio.features import geometry_mask as geometry_mask, geometry_window as geometry_window +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def raster_geometry_mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, +) -> tuple[NDArray[Any], Affine, tuple[int, int, int, int]]: ... +def mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + nodata: float | None = None, + filled: bool = True, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, + indexes: int | Iterable[int] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/merge.pyi b/stubs/rasterio/rasterio/merge.pyi new file mode 100644 index 000000000000..d9d767d53c2e --- /dev/null +++ b/stubs/rasterio/rasterio/merge.pyi @@ -0,0 +1,65 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import deprecated + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +MethodFunction: TypeAlias = Callable[..., None] +MERGE_METHODS: Final[dict[str, MethodFunction]] + +_Arr: TypeAlias = NDArray[Any] + +# `**kwargs` on each merge method accepts forwarded options from `merge()` (e.g. `index`); ignored otherwise. +def copy_first(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_last(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_min(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_max(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_sum(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_count(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... + +@overload +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + *, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... +@overload +@deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + precision: int | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/path.pyi b/stubs/rasterio/rasterio/path.pyi new file mode 100644 index 000000000000..b5e935ebfd94 --- /dev/null +++ b/stubs/rasterio/rasterio/path.pyi @@ -0,0 +1,13 @@ +from typing import TypeAlias +from typing_extensions import deprecated + +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning + +ParsedPath: TypeAlias = _ParsedPath +UnparsedPath: TypeAlias = _UnparsedPath + +@deprecated("rasterio.path.parse_path is deprecated; use rasterio._path._parse_path or pass paths directly to rasterio.open.") +def parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... +@deprecated("rasterio.path.vsi_path is deprecated; use rasterio._path._vsi_path directly.") +def vsi_path(path: _ParsedPath | _UnparsedPath) -> str: ... diff --git a/stubs/rasterio/rasterio/plot.pyi b/stubs/rasterio/rasterio/plot.pyi new file mode 100644 index 000000000000..80815180dac1 --- /dev/null +++ b/stubs/rasterio/rasterio/plot.pyi @@ -0,0 +1,49 @@ +import logging +from collections.abc import Mapping, Sequence +from typing import Any, Final, Literal + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio.io import DatasetReader as DatasetReader +from rasterio.transform import guard_transform as guard_transform + +logger: Final[logging.Logger] + +# Returns the `matplotlib.pyplot` module (lazy import). +def get_plt() -> Any: ... + +# `ax`: matplotlib.axes.Axes; returns matplotlib.image.AxesImage or +# the input `ax` for contour plots. `**kwargs` are forwarded to +# matplotlib's `imshow`/`contour` call. +def show( + source: NDArray[Any] | DatasetReader | tuple[DatasetReader, int], + with_bounds: bool = True, + contour: bool = False, + contour_label_kws: Mapping[str, Any] | None = None, + indexes: Sequence[int] | None = None, + ax: Any | None = None, + title: str | None = None, + transform: Affine | None = None, + percent_range: tuple[float, float] | None = None, + adjust: bool = True, + **kwargs: Any, +) -> Any: ... +def plotting_extent( + source: NDArray[Any] | DatasetReader, transform: Affine | None = None +) -> tuple[float, float, float, float]: ... +def reshape_as_image(arr: NDArray[Any]) -> NDArray[Any]: ... +def reshape_as_raster(arr: NDArray[Any]) -> NDArray[Any]: ... + +# `ax`: matplotlib.axes.Axes; `**kwargs` are forwarded to matplotlib's `hist` call. +def show_hist( + source: NDArray[Any] | DatasetReader, + bins: int = 10, + masked: bool = True, + title: str = "Histogram", + ax: Any | None = None, + label: str | Sequence[str] | None = None, + range: tuple[float, float] | None = None, + **kwargs: Any, +) -> None: ... +def adjust_band(band: NDArray[Any], kind: Literal["linear", "log"] | None = None) -> NDArray[Any]: ... +def contrast_strech(arr: NDArray[Any], percent_range: tuple[float, float] = (2.0, 98.0)) -> NDArray[Any]: ... diff --git a/stubs/rasterio/rasterio/profiles.pyi b/stubs/rasterio/rasterio/profiles.pyi new file mode 100644 index 000000000000..27bc61f92351 --- /dev/null +++ b/stubs/rasterio/rasterio/profiles.pyi @@ -0,0 +1,15 @@ +from collections import UserDict +from typing import Any, ClassVar, Final + +# A `Profile` is a dict of GDAL driver-specific dataset-creation options +# (e.g. `count`, `dtype`, `compress`); value types depend on the option. +class Profile(UserDict[str, Any]): + defaults: ClassVar[dict[str, Any]] + def __init__(self, data: dict[str, Any] = ..., **kwds: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + +class DefaultGTiffProfile(Profile): + defaults: ClassVar[dict[str, Any]] + +default_gtiff_profile: Final[DefaultGTiffProfile] diff --git a/stubs/rasterio/rasterio/rpc.pyi b/stubs/rasterio/rasterio/rpc.pyi new file mode 100644 index 000000000000..b4e2be46df5c --- /dev/null +++ b/stubs/rasterio/rasterio/rpc.pyi @@ -0,0 +1,44 @@ +from collections.abc import Sequence +from typing import Any +from typing_extensions import Self + +class RPC: + height_off: float + height_scale: float + lat_off: float + lat_scale: float + line_den_coeff: Sequence[float] + line_num_coeff: Sequence[float] + line_off: float + line_scale: float + long_off: float + long_scale: float + samp_den_coeff: Sequence[float] + samp_num_coeff: Sequence[float] + samp_off: float + samp_scale: float + err_bias: float | None + err_rand: float | None + def __init__( + self, + height_off: float, + height_scale: float, + lat_off: float, + lat_scale: float, + line_den_coeff: Sequence[float], + line_num_coeff: Sequence[float], + line_off: float, + line_scale: float, + long_off: float, + long_scale: float, + samp_den_coeff: Sequence[float], + samp_num_coeff: Sequence[float], + samp_off: float, + samp_scale: float, + err_bias: float | None = None, + err_rand: float | None = None, + ) -> None: ... + def to_dict(self) -> dict[str, Any]: ... + def to_gdal(self) -> dict[str, str]: ... + @classmethod + def from_gdal(cls, rpcs: dict[str, str]) -> Self: ... diff --git a/stubs/rasterio/rasterio/sample.pyi b/stubs/rasterio/rasterio/sample.pyi new file mode 100644 index 000000000000..4d7722bae293 --- /dev/null +++ b/stubs/rasterio/rasterio/sample.pyi @@ -0,0 +1,13 @@ +from collections.abc import Iterable, Iterator, Sequence +from typing import Any + +from numpy.typing import NDArray +from rasterio.io import DatasetReaderBase + +def sample_gen( + dataset: DatasetReaderBase, + xy: Iterable[tuple[float, float]], + indexes: int | Sequence[int] | None = None, + masked: bool = False, +) -> Iterator[NDArray[Any]]: ... +def sort_xy(xy: Iterable[tuple[float, float]]) -> list[tuple[float, float]]: ... diff --git a/stubs/rasterio/rasterio/session.pyi b/stubs/rasterio/rasterio/session.pyi new file mode 100644 index 000000000000..4a78d07976a1 --- /dev/null +++ b/stubs/rasterio/rasterio/session.pyi @@ -0,0 +1,112 @@ +import logging +from typing import Any, Final + +log: Final[logging.Logger] + +def parse_bool(v: bool | str | int) -> bool: ... + +class Session: + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + # `session` is a foreign session object (e.g. boto3.session.Session, + # google.auth.credentials.Credentials); the runtime dispatches by isinstance. + @staticmethod + def from_foreign_session(session: Any, cls: type[Session] | None = None) -> Session: ... + @staticmethod + def cls_from_path(path: str) -> type[Session]: ... + # Forwarded to the resolved session class' __init__; see its signature. + @staticmethod + def from_path(path: str, *args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def aws_or_dummy(*args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def from_environ(*args: Any, **kwargs: Any) -> Session: ... + +class DummySession(Session): + credentials: dict[str, str] + # Accepts and ignores any args (no credentials are configured). + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AWSSession(Session): + requester_pays: bool + unsigned: bool + endpoint_url: str | None + def __init__( + self, + # A `boto3.session.Session` instance, or None to construct one from the other kwargs. + session: Any | None = None, + aws_unsigned: bool | None = None, + aws_access_key_id: str | None = None, + aws_secret_access_key: str | None = None, + aws_session_token: str | None = None, + region_name: str | None = None, + profile_name: str | None = None, + endpoint_url: str | None = None, + requester_pays: bool = False, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class OSSSession(Session): + def __init__( + self, oss_access_key_id: str | None = None, oss_secret_access_key: str | None = None, oss_endpoint: str | None = None + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class GSSession(Session): + def __init__(self, google_application_credentials: str | None = None) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class SwiftSession(Session): + def __init__( + self, + # A `swiftclient.Connection` instance, or None to construct one from the other kwargs. + session: Any | None = None, + swift_storage_url: str | None = None, + swift_auth_token: str | None = None, + swift_auth_v1_url: str | None = None, + swift_user: str | None = None, + swift_key: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AzureSession(Session): + unsigned: bool + storage_account: str | None + def __init__( + self, + azure_storage_connection_string: str | None = None, + azure_storage_account: str | None = None, + azure_storage_access_token: str | None = None, + azure_storage_access_key: str | None = None, + azure_storage_sas_token: str | None = None, + azure_unsigned: bool = False, + azure_tenant_id: str | None = None, + azure_client_id: str | None = None, + azure_federated_token_file: str | None = None, + azure_authority_host: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... diff --git a/stubs/rasterio/rasterio/shutil.pyi b/stubs/rasterio/rasterio/shutil.pyi new file mode 100644 index 000000000000..409a657b8b8d --- /dev/null +++ b/stubs/rasterio/rasterio/shutil.pyi @@ -0,0 +1,16 @@ +import os +from typing import Any + +from rasterio._typing import _OpenOption + +def exists(path: str | os.PathLike[str]) -> bool: ... +def copy( + # An open dataset handle (DatasetReader / DatasetWriter / DatasetBase) or a path. + src: str | os.PathLike[str] | Any, + dst: str | os.PathLike[str], + driver: str | None = None, + strict: bool = True, + **creation_options: _OpenOption, +) -> None: ... +def copyfiles(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: ... +def delete(path: str | os.PathLike[str], driver: str | None = None) -> None: ... diff --git a/stubs/rasterio/rasterio/stack.pyi b/stubs/rasterio/rasterio/stack.pyi new file mode 100644 index 000000000000..68680ffe9b1e --- /dev/null +++ b/stubs/rasterio/rasterio/stack.pyi @@ -0,0 +1,28 @@ +import logging +import os +from collections.abc import Sequence +from typing import Any, Final + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def stack( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/stubs/rasterio/rasterio/tools.pyi b/stubs/rasterio/rasterio/tools.pyi new file mode 100644 index 000000000000..0d78bca77964 --- /dev/null +++ b/stubs/rasterio/rasterio/tools.pyi @@ -0,0 +1,19 @@ +import os +from collections.abc import Callable, Iterable +from typing import Any, Final + +class JSONSequenceTool: + func: Callable[..., Iterable[Any]] + def __init__(self, func: Callable[..., Iterable[Any]]) -> None: ... + def __call__( + self, + src_path: str | os.PathLike[str], + dst_path: str | os.PathLike[str], + src_kwargs: dict[str, Any] | None = None, + dst_kwargs: dict[str, Any] | None = None, + func_args: Iterable[Any] | None = None, + func_kwargs: dict[str, Any] | None = None, + config: dict[str, Any] | None = None, + ) -> None: ... + +dataset_features_tool: Final[JSONSequenceTool] diff --git a/stubs/rasterio/rasterio/transform.pyi b/stubs/rasterio/rasterio/transform.pyi new file mode 100644 index 000000000000..f6aae2f7f098 --- /dev/null +++ b/stubs/rasterio/rasterio/transform.pyi @@ -0,0 +1,112 @@ +from collections.abc import Callable, Sequence +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self, deprecated + +from rasterio._affine_types import Affine as Affine +from rasterio._transform import GCPTransformerBase, RPCTransformerBase +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import TransformDirection as TransformDirection, TransformMethod as TransformMethod +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning +from rasterio.rpc import RPC + +_Sextuple: TypeAlias = tuple[float, float, float, float, float, float] +_OffsetOptions: TypeAlias = Literal["center", "ul", "ur", "ll", "lr"] +_RoundOperation: TypeAlias = Callable[[float], int] + +IDENTITY: Final[Affine] +GDAL_IDENTITY: Final[_Sextuple] + +class TransformMethodsMixin: + def xy( + self, + row: int | Sequence[int], + col: int | Sequence[int], + z: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + def index( + self, + x: float | Sequence[float], + y: float | Sequence[float], + z: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +def tastes_like_gdal(seq: Affine | _Sextuple) -> bool: ... +def guard_transform(transform: Affine | _Sextuple) -> Affine: ... +def from_origin(west: float, north: float, xsize: float, ysize: float) -> Affine: ... +def from_bounds(west: float, south: float, east: float, north: float, width: float, height: float) -> Affine: ... +def array_bounds(height: int, width: int, transform: Affine) -> tuple[float, float, float, float]: ... +def from_gcps(gcps: Sequence[GroundControlPoint]) -> Affine: ... +def xy( + transform: Affine | Sequence[GroundControlPoint] | RPC, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + **rpc_options: _GDALOption, +) -> tuple[float, float] | tuple[list[float], list[float]]: ... +def rowcol( + transform: Affine | Sequence[GroundControlPoint] | RPC, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + **rpc_options: _GDALOption, +) -> tuple[int, int] | tuple[list[int], list[int]]: ... +def get_transformer( + transform: Affine | Sequence[GroundControlPoint] | RPC, **rpc_options: _GDALOption +) -> type[TransformerBase]: ... + +class TransformerBase: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def xy( + self, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + + @overload + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +class GDALTransformerBase(TransformerBase): + def __init__(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +class AffineTransformer(TransformerBase): + def __init__(self, affine_transform: Affine | _Sextuple) -> None: ... + +class GCPTransformer(GCPTransformerBase, GDALTransformerBase): + def __init__(self, gcps: Sequence[GroundControlPoint], tps: bool = False) -> None: ... + +class RPCTransformer(RPCTransformerBase, GDALTransformerBase): + def __init__(self, rpcs: RPC, **rpc_options: _GDALOption) -> None: ... diff --git a/stubs/rasterio/rasterio/vrt.pyi b/stubs/rasterio/rasterio/vrt.pyi new file mode 100644 index 000000000000..308e932590a2 --- /dev/null +++ b/stubs/rasterio/rasterio/vrt.pyi @@ -0,0 +1,13 @@ +from types import TracebackType +from typing_extensions import Self + +from rasterio._warp import WarpedVRTReaderBase +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +class WarpedVRT(WarpedVRTReaderBase, WindowMethodsMixin, TransformMethodsMixin): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... diff --git a/stubs/rasterio/rasterio/warp.pyi b/stubs/rasterio/rasterio/warp.pyi new file mode 100644 index 000000000000..09e4a86ca08d --- /dev/null +++ b/stubs/rasterio/rasterio/warp.pyi @@ -0,0 +1,84 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from typing import Any, Final, TypeAlias, overload +from typing_extensions import deprecated + +from numpy.typing import ArrayLike, NDArray +from rasterio._affine_types import Affine +from rasterio._typing import CRSInput, Geometry, _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +_Resolution: TypeAlias = tuple[float, float] | float +_Gcps: TypeAlias = Sequence[GroundControlPoint] +_Rpcs: TypeAlias = RPC | Mapping[str, Any] + +SUPPORTED_RESAMPLING: Final[list[Resampling]] + +def transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: ArrayLike, ys: ArrayLike, zs: ArrayLike | None = None +) -> tuple[list[float], list[float]] | tuple[list[float], list[float], list[float]]: ... + +@overload +def transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], *, precision: float = -1 +) -> dict[str, Any] | list[dict[str, Any]]: ... +@overload +@deprecated( + "`antimeridian_cutting` and `antimeridian_offset` are no-ops since GDAL 2.2 " + "and will be removed in a future rasterio release. Call transform_geom " + "without them." +) +def transform_geom( + src_crs: CRSInput, + dst_crs: CRSInput, + geom: Geometry | Sequence[Geometry], + antimeridian_cutting: bool | None = None, + antimeridian_offset: float | None = None, + precision: float = -1, +) -> dict[str, Any] | list[dict[str, Any]]: ... + +def transform_bounds( + src_crs: CRSInput, dst_crs: CRSInput, left: float, bottom: float, right: float, top: float, densify_pts: int = 21 +) -> tuple[float, float, float, float]: ... +def reproject( + source: ArrayLike | Incomplete, + destination: ArrayLike | Incomplete | None = None, + src_transform: Affine | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_resolution: _Resolution | None = None, + src_alpha: int = 0, + dst_alpha: int = 0, + masked: bool = False, + resampling: Resampling = ..., + num_threads: int = 1, + init_dest_nodata: bool = True, + warp_mem_limit: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def aligned_target(transform: Affine, width: int, height: int, resolution: _Resolution) -> tuple[Affine, int, int]: ... +def calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + resolution: _Resolution | None = None, + dst_width: int | None = None, + dst_height: int | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... diff --git a/stubs/rasterio/rasterio/windows.pyi b/stubs/rasterio/rasterio/windows.pyi new file mode 100644 index 000000000000..bead643d3f08 --- /dev/null +++ b/stubs/rasterio/rasterio/windows.pyi @@ -0,0 +1,80 @@ +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias, overload +from typing_extensions import Self, deprecated + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning, WindowError as WindowError + +_Bounds: TypeAlias = tuple[float, float, float, float] +_Ranges: TypeAlias = tuple[tuple[int, int], tuple[int, int]] +_Slices: TypeAlias = tuple[slice, slice] + +class WindowMethodsMixin: + @overload + def window(self, left: float, bottom: float, right: float, top: float) -> Window: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def window(self, left: float, bottom: float, right: float, top: float, precision: int | None = None) -> Window: ... + + def window_transform(self, window: Window) -> Affine: ... + def window_bounds(self, window: Window) -> _Bounds: ... + +def iter_args(function: Callable[..., Any]) -> Callable[..., Any]: ... +def toranges(window: Window | _Ranges) -> _Ranges: ... +def get_data_window(arr: NDArray[Any], nodata: float | None = None) -> Window: ... +def union(*windows: Window) -> Window: ... +def intersection(*windows: Window) -> Window: ... +def intersect(*windows: Window) -> bool: ... + +@overload +def from_bounds(left: float, bottom: float, right: float, top: float, transform: Affine | None = None) -> Window: ... +@overload +@deprecated( + "`height`, `width`, and `precision` on windows.from_bounds are unused since rasterio 1.3 and will be removed in 2.0.0." +) +def from_bounds( + left: float, + bottom: float, + right: float, + top: float, + transform: Affine | None = None, + height: int | None = None, + width: int | None = None, + precision: int | None = None, +) -> Window: ... + +def transform(window: Window, transform: Affine) -> Affine: ... +def bounds(window: Window, transform: Affine, height: int = 0, width: int = 0) -> _Bounds: ... +def crop(window: Window, height: int, width: int) -> Window: ... +def evaluate(window: Window, height: int, width: int, boundless: bool = False) -> Window: ... +def shape(window: Window, height: int = -1, width: int = -1) -> tuple[int, int]: ... +def window_index(window: Window, height: int = 0, width: int = 0) -> _Slices: ... +def round_window_to_full_blocks( + window: Window, block_shapes: Sequence[tuple[int, int]], height: int = 0, width: int = 0 +) -> Window: ... +def validate_length_value(instance: object, attribute: object, value: float) -> None: ... +def subdivide(window: Window, height: int, width: int) -> list[Window]: ... + +class Window: + col_off: float + row_off: float + width: float + height: float + def __init__(self, col_off: float, row_off: float, width: float, height: float) -> None: ... + def flatten(self) -> tuple[float, float, float, float]: ... + def todict(self) -> dict[str, float]: ... + def toranges(self) -> _Ranges: ... + def toslices(self) -> _Slices: ... + @classmethod + def from_slices( + cls, rows: slice | Sequence[int], cols: slice | Sequence[int], height: int = -1, width: int = -1, boundless: bool = False + ) -> Self: ... + # `**kwds` accepts the deprecated kwargs `op` (callable) and `pixel_precision` (int) emitted by rasterio < 1.3. + def round_lengths(self, **kwds: Any) -> Window: ... + @deprecated("Window.round_shape is deprecated and will be removed in Rasterio 2.0.0; use round_lengths instead.") + def round_shape(self, **kwds: Any) -> Window: ... + def round_offsets(self, **kwds: Any) -> Window: ... + def round(self, ndigits: int | None = None) -> Window: ... + def crop(self, height: int, width: int) -> Window: ... + def intersection(self, other: Window) -> Window: ... diff --git a/stubs/ratelimit/@tests/stubtest_allowlist.txt b/stubs/ratelimit/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5b0935ce9175 --- /dev/null +++ b/stubs/ratelimit/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +# This file lacks __all__ and "now" is only used to set the default value of +# RateLimitDecorator.__init__()'s clock parameter +ratelimit.decorators.now diff --git a/stubs/ratelimit/METADATA.toml b/stubs/ratelimit/METADATA.toml new file mode 100644 index 000000000000..dbdb547943c9 --- /dev/null +++ b/stubs/ratelimit/METADATA.toml @@ -0,0 +1,2 @@ +version = "2.2.*" +upstream-repository = "https://github.com/tomasbasham/ratelimit" diff --git a/stubs/ratelimit/ratelimit/__init__.pyi b/stubs/ratelimit/ratelimit/__init__.pyi new file mode 100644 index 000000000000..374329aaa37e --- /dev/null +++ b/stubs/ratelimit/ratelimit/__init__.pyi @@ -0,0 +1,7 @@ +from ratelimit.decorators import RateLimitDecorator, sleep_and_retry +from ratelimit.exception import RateLimitException + +limits = RateLimitDecorator +rate_limited = RateLimitDecorator + +__all__ = ["RateLimitException", "limits", "rate_limited", "sleep_and_retry"] diff --git a/stubs/ratelimit/ratelimit/decorators.pyi b/stubs/ratelimit/ratelimit/decorators.pyi new file mode 100644 index 000000000000..a31adc2fa819 --- /dev/null +++ b/stubs/ratelimit/ratelimit/decorators.pyi @@ -0,0 +1,13 @@ +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +_P = ParamSpec("_P") +_T = TypeVar("_T") + +class RateLimitDecorator: + def __init__( + self, calls: int = 15, period: float = 900, clock: Callable[[], float] = ..., raise_on_limit: bool = True + ) -> None: ... + def __call__(self, func: Callable[_P, _T]) -> Callable[_P, _T]: ... + +def sleep_and_retry(func: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/stubs/ratelimit/ratelimit/exception.pyi b/stubs/ratelimit/ratelimit/exception.pyi new file mode 100644 index 000000000000..2271781458b0 --- /dev/null +++ b/stubs/ratelimit/ratelimit/exception.pyi @@ -0,0 +1,3 @@ +class RateLimitException(Exception): + period_remaining: float + def __init__(self, message: str, period_remaining: float) -> None: ... diff --git a/stubs/regex/@tests/stubtest_allowlist.txt b/stubs/regex/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..5629e03e968a --- /dev/null +++ b/stubs/regex/@tests/stubtest_allowlist.txt @@ -0,0 +1,15 @@ +# Not exported in C modules: +regex._regex.Splitter +regex._regex.Scanner + +# Implementation details: +regex._regex.compile +regex._regex.copyright +regex._regex.fold_case +regex._regex.get_all_cases +regex._regex.get_code_size +regex._regex.get_expand_on_folding +regex._regex.get_properties +regex._regex.has_property_value +regex._regex.CODE_SIZE +regex._regex.MAGIC diff --git a/stubs/regex/@tests/test_cases/check_finditer.py b/stubs/regex/@tests/test_cases/check_finditer.py new file mode 100644 index 000000000000..0b572973ceaf --- /dev/null +++ b/stubs/regex/@tests/test_cases/check_finditer.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from typing import List +from typing_extensions import assert_type + +import regex + +# Regression tests for #9263 +assert_type(list(regex.finditer(r"foo", "foo")), List[regex.Match[str]]) +pat = regex.compile(rb"foo") +assert_type(list(pat.finditer(b"foo")), List[regex.Match[bytes]]) diff --git a/stubs/regex/METADATA.toml b/stubs/regex/METADATA.toml new file mode 100644 index 000000000000..26ff2e9225a9 --- /dev/null +++ b/stubs/regex/METADATA.toml @@ -0,0 +1,2 @@ +version = "2026.7.19" +upstream-repository = "https://github.com/mrabarnett/mrab-regex" diff --git a/stubs/regex/regex/__init__.pyi b/stubs/regex/regex/__init__.pyi new file mode 100644 index 000000000000..d6f58927e4df --- /dev/null +++ b/stubs/regex/regex/__init__.pyi @@ -0,0 +1,65 @@ +from ._main import * + +# Sync with regex._main.__all__ +__all__ = [ + "cache_all", + "compile", + "DEFAULT_VERSION", + "escape", + "findall", + "finditer", + "fullmatch", + "match", + "prefixmatch", + "purge", + "search", + "split", + "splititer", + "sub", + "subf", + "subfn", + "subn", + "template", + "Scanner", + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "S", + "DOTALL", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "X", + "VERBOSE", + "W", + "WORD", + "error", + "Regex", + "__version__", + "__doc__", + "RegexFlag", + "Pattern", + "Match", +] diff --git a/stubs/regex/regex/_main.pyi b/stubs/regex/regex/_main.pyi new file mode 100644 index 000000000000..2a77bafd9fa0 --- /dev/null +++ b/stubs/regex/regex/_main.pyi @@ -0,0 +1,759 @@ +from _typeshed import ReadableBuffer, Unused +from collections.abc import Callable, Mapping +from types import GenericAlias +from typing import Any, AnyStr, Generic, Literal, TypeVar, final, overload +from typing_extensions import Self + +from . import _regex +from ._regex_core import * + +_T = TypeVar("_T") + +__version__: str + +# Sync with regex.__init__.__all__ +__all__ = [ + "cache_all", + "compile", + "DEFAULT_VERSION", + "escape", + "findall", + "finditer", + "fullmatch", + "match", + "prefixmatch", + "purge", + "search", + "split", + "splititer", + "sub", + "subf", + "subfn", + "subn", + "template", + "Scanner", + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "S", + "DOTALL", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "X", + "VERBOSE", + "W", + "WORD", + "error", + "Regex", + "__version__", + "__doc__", + "RegexFlag", + "Pattern", + "Match", +] + +def compile( + pattern: AnyStr | Pattern[AnyStr], + flags: int = 0, + ignore_unused: bool = False, + cache_pattern: bool | None = None, + **kwargs: Any, +) -> Pattern[AnyStr]: ... + +@overload +def search( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def search( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +@overload +def match( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def match( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +prefixmatch = match + +@overload +def fullmatch( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[str] | None: ... +@overload +def fullmatch( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> Match[bytes] | None: ... + +@overload +def split( + pattern: str | Pattern[str], + string: str, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[str | Any]: ... +@overload +def split( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[bytes | Any]: ... + +@overload +def splititer( + pattern: str | Pattern[str], + string: str, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Splitter[str]: ... +@overload +def splititer( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + flags: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Splitter[bytes]: ... + +@overload +def findall( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[Any]: ... +@overload +def findall( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> list[Any]: ... + +@overload +def finditer( + pattern: str | Pattern[str], + string: str, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Scanner[str]: ... +@overload +def finditer( + pattern: bytes | Pattern[bytes], + string: ReadableBuffer, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + partial: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> _regex.Scanner[bytes]: ... + +@overload +def sub( + pattern: str | Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> str: ... +@overload +def sub( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> bytes: ... + +@overload +def subf( + pattern: str | Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> str: ... +@overload +def subf( + pattern: bytes | Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> bytes: ... + +@overload +def subn( + pattern: str | Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[str, int]: ... +@overload +def subn( + pattern: bytes | Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[bytes, int]: ... + +@overload +def subfn( + pattern: str | Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[str, int]: ... +@overload +def subfn( + pattern: bytes | Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + flags: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ignore_unused: bool = False, + **kwargs: Any, +) -> tuple[bytes, int]: ... + +def purge() -> None: ... + +@overload +def cache_all(value: bool = True) -> None: ... +@overload +def cache_all(value: None) -> bool: ... + +def escape(pattern: AnyStr, special_only: bool = True, literal_spaces: bool = False) -> AnyStr: ... + +DEFAULT_VERSION = RegexFlag.VERSION0 + +def template(pattern: AnyStr | Pattern[AnyStr], flags: int = 0) -> Pattern[AnyStr]: ... + +Regex = compile + +@final +class Pattern(Generic[AnyStr]): + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... + @property + def named_lists(self) -> Mapping[str, frozenset[AnyStr]]: ... + + @overload + def search( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def search( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + @overload + def match( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def match( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + prefixmatch = match + + @overload + def fullmatch( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[str] | None: ... + @overload + def fullmatch( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> Match[bytes] | None: ... + + @overload + def split( + self: Pattern[str], string: str, maxsplit: int = 0, concurrent: bool | None = None, timeout: float | None = None + ) -> list[str | Any]: ... + @overload + def split( + self: Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[bytes | Any]: ... + + @overload + def splititer( + self: Pattern[str], string: str, maxsplit: int = 0, concurrent: bool | None = None, timeout: float | None = None + ) -> _regex.Splitter[str]: ... + @overload + def splititer( + self: Pattern[bytes], + string: ReadableBuffer, + maxsplit: int = 0, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> _regex.Splitter[bytes]: ... + + @overload + def findall( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[Any]: ... + @overload + def findall( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> list[Any]: ... + + @overload + def finditer( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[str]: ... + @overload + def finditer( + self: Pattern[bytes], + string: ReadableBuffer, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[bytes]: ... + + @overload + def sub( + self: Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> str: ... + @overload + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> bytes: ... + + @overload + def subf( + self: Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> str: ... + @overload + def subf( + self: Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> bytes: ... + + @overload + def subn( + self: Pattern[str], + repl: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[str, int]: ... + @overload + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[bytes, int]: ... + + @overload + def subfn( + self: Pattern[str], + format: str | Callable[[Match[str]], str], + string: str, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[str, int]: ... + @overload + def subfn( + self: Pattern[bytes], + format: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = 0, + pos: int | None = None, + endpos: int | None = None, + concurrent: bool | None = None, + timeout: float | None = None, + ) -> tuple[bytes, int]: ... + + @overload + def scanner( + self: Pattern[str], + string: str, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[str]: ... + @overload + def scanner( + self: Pattern[bytes], + string: bytes, + pos: int | None = None, + endpos: int | None = None, + overlapped: bool = False, + concurrent: bool | None = None, + partial: bool = False, + timeout: float | None = None, + ) -> _regex.Scanner[bytes]: ... + + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Unused, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + +@final +class Match(Generic[AnyStr]): + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... + @property + def re(self) -> Pattern[AnyStr]: ... + @property + def partial(self) -> bool: ... + @property + def regs(self) -> tuple[tuple[int, int], ...]: ... + @property + def fuzzy_counts(self) -> tuple[int, int, int]: ... + @property + def fuzzy_changes(self) -> tuple[list[int], list[int], list[int]]: ... + + @overload + def group(self, group: Literal[0] = 0, /) -> AnyStr: ... + @overload + def group(self, group: int | str = ..., /) -> AnyStr | Any: ... + @overload + def group(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[AnyStr | Any, ...]: ... + + @overload + def groups(self, default: None = None) -> tuple[AnyStr | Any, ...]: ... + @overload + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + + @overload + def groupdict(self, default: None = None) -> dict[str, AnyStr | Any]: ... + @overload + def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + + @overload + def span(self, group: int | str = ..., /) -> tuple[int, int]: ... + @overload + def span(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[tuple[int, int], ...]: ... + + @overload + def spans(self, group: int | str = ..., /) -> list[tuple[int, int]]: ... + @overload + def spans(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[tuple[int, int]], ...]: ... + + @overload + def start(self, group: int | str = ..., /) -> int: ... + @overload + def start(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[int, ...]: ... + + @overload + def starts(self, group: int | str = ..., /) -> list[int]: ... + @overload + def starts(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[int], ...]: ... + + @overload + def end(self, group: int | str = ..., /) -> int: ... + @overload + def end(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[int, ...]: ... + + @overload + def ends(self, group: int | str = ..., /) -> list[int]: ... + @overload + def ends(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[int], ...]: ... + + def expand(self, template: AnyStr, /) -> AnyStr: ... + def expandf(self, format: AnyStr, /) -> AnyStr: ... + + @overload + def captures(self, group: int | str = ..., /) -> list[AnyStr]: ... + @overload + def captures(self, group1: int | str, group2: int | str, /, *groups: int | str) -> tuple[list[AnyStr], ...]: ... + + def capturesdict(self) -> dict[str, list[AnyStr]]: ... + def detach_string(self) -> None: ... + def allcaptures(self) -> tuple[list[AnyStr]]: ... + def allspans(self) -> tuple[list[tuple[int, int]]]: ... + + @overload + def __getitem__(self, key: Literal[0], /) -> AnyStr: ... + @overload + def __getitem__(self, key: int | str, /) -> AnyStr | Any: ... + + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Unused, /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/stubs/regex/regex/_regex.pyi b/stubs/regex/regex/_regex.pyi new file mode 100644 index 000000000000..c80e1662c33d --- /dev/null +++ b/stubs/regex/regex/_regex.pyi @@ -0,0 +1,26 @@ +# This is actually a C-extension module. +# Not all types defined in C are exported to Python. +# For example: `Pattern` and `Match` are not exported +# and are redefined in `regex.regex module. + +from typing import Any, AnyStr, Generic, final +from typing_extensions import Self + +from ._main import Match, Pattern + +@final +class Splitter(Generic[AnyStr]): + @property + def pattern(self) -> Pattern[AnyStr]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> AnyStr | Any: ... + def split(self) -> AnyStr | Any: ... + +@final +class Scanner(Generic[AnyStr]): + @property + def pattern(self) -> Pattern[AnyStr]: ... + def __iter__(self) -> Self: ... + def __next__(self) -> Match[AnyStr]: ... + def match(self) -> Match[AnyStr] | None: ... + def search(self) -> Match[AnyStr] | None: ... diff --git a/stubs/regex/regex/_regex_core.pyi b/stubs/regex/regex/_regex_core.pyi new file mode 100644 index 000000000000..d8f3014f9a73 --- /dev/null +++ b/stubs/regex/regex/_regex_core.pyi @@ -0,0 +1,130 @@ +import enum +from collections.abc import Callable +from typing import Any, AnyStr, Generic, TypeAlias + +from ._main import Pattern + +__all__ = [ + "A", + "ASCII", + "B", + "BESTMATCH", + "D", + "DEBUG", + "E", + "ENHANCEMATCH", + "F", + "FULLCASE", + "I", + "IGNORECASE", + "L", + "LOCALE", + "M", + "MULTILINE", + "P", + "POSIX", + "R", + "REVERSE", + "S", + "DOTALL", + "T", + "TEMPLATE", + "U", + "UNICODE", + "V0", + "VERSION0", + "V1", + "VERSION1", + "W", + "WORD", + "X", + "VERBOSE", + "error", + "Scanner", + "RegexFlag", +] + +class error(Exception): + def __init__(self, message: str, pattern: AnyStr | None = None, pos: int | None = None) -> None: ... + +class RegexFlag(enum.IntFlag): + A = 0x80 + ASCII = A + B = 0x1000 + BESTMATCH = B + D = 0x200 + DEBUG = D + E = 0x8000 + ENHANCEMATCH = E + F = 0x4000 + FULLCASE = F + I = 0x2 + IGNORECASE = I + L = 0x4 + LOCALE = L + M = 0x8 + MULTILINE = M + P = 0x10000 + POSIX = P + R = 0x400 + REVERSE = R + T = 0x1 + TEMPLATE = T + S = 0x10 + DOTALL = S + U = 0x20 + UNICODE = U + V0 = 0x2000 + VERSION0 = V0 + V1 = 0x100 + VERSION1 = V1 + W = 0x800 + WORD = W + X = 0x40 + VERBOSE = X + +ASCII = RegexFlag.ASCII +BESTMATCH = RegexFlag.BESTMATCH +DEBUG = RegexFlag.DEBUG +ENHANCEMATCH = RegexFlag.ENHANCEMATCH +FULLCASE = RegexFlag.FULLCASE +IGNORECASE = RegexFlag.IGNORECASE +LOCALE = RegexFlag.LOCALE +MULTILINE = RegexFlag.MULTILINE +POSIX = RegexFlag.POSIX +REVERSE = RegexFlag.REVERSE +TEMPLATE = RegexFlag.TEMPLATE +DOTALL = RegexFlag.DOTALL +UNICODE = RegexFlag.UNICODE +VERBOSE = RegexFlag.VERBOSE +VERSION0 = RegexFlag.VERSION0 +VERSION1 = RegexFlag.VERSION1 +WORD = RegexFlag.WORD +A = RegexFlag.A +B = RegexFlag.B +D = RegexFlag.D +E = RegexFlag.E +F = RegexFlag.F +I = RegexFlag.I +L = RegexFlag.L +M = RegexFlag.M +P = RegexFlag.P +R = RegexFlag.R +S = RegexFlag.S +U = RegexFlag.U +V0 = RegexFlag.V0 +V1 = RegexFlag.V1 +W = RegexFlag.W +X = RegexFlag.X +T = RegexFlag.T + +DEFAULT_VERSION = VERSION1 + +_Lexicon: TypeAlias = list[tuple[AnyStr, Callable[[Scanner[AnyStr], AnyStr], Any]]] + +class Scanner(Generic[AnyStr]): + lexicon: _Lexicon[AnyStr] + scanner: Pattern[AnyStr] + + def __init__(self, lexicon: _Lexicon[AnyStr], flags: int = 0) -> None: ... + def scan(self, string: AnyStr) -> tuple[list[Any], AnyStr]: ... diff --git a/stubs/reportlab/@tests/stubtest_allowlist.txt b/stubs/reportlab/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..037ecc58aece --- /dev/null +++ b/stubs/reportlab/@tests/stubtest_allowlist.txt @@ -0,0 +1,107 @@ +# TODO: missing from stub +reportlab.graphics.barcode.dmtx.__all__ +reportlab.rl_config.__all__ + +# Incorrect __all__ names in runtime +reportlab.graphics.barcode.eanbc.__all__ +reportlab.graphics.barcode.ecc200datamatrix.__all__ + +# shapeFragWord has two incompatible definitions, depending on whether +# uharfbuzz is installed or not. We use the version where uharfbuzz is +# installed. +reportlab.pdfbase.ttfonts.shapeFragWord + +# Error: is inconsistent +# ====================== +# The drawOn method violates LSP all over the place and it's usually +# optional parameters that only exist in a base class and some of them +# are internal only like _sW, so we've decided to omit these, in order +# to get less noise from derived classes that don't have these parameters +reportlab\.platypus\.(doctemplate\.|flowables\.)?[A-Za-z_]+\.drawOn + +# similary the wrap/split methods use inconsistent names for their +# parameters, so we decided to make them positional-only +reportlab.graphics.shapes.Drawing.wrap +reportlab\.platypus\.(doctemplate\.|flowables\.|tableofcontents\.)?[A-Za-z_]+\.split +reportlab\.platypus\.(doctemplate\.|flowables\.|tableofcontents\.)?[A-Za-z_]+\.wrap +reportlab.platypus.multicol.MultiCol.split +reportlab.platypus.para.FastPara.split +reportlab.platypus.para.FastPara.wrap +reportlab.platypus.para.Para.split +reportlab.platypus.para.Para.wrap +reportlab.platypus.paragraph.Paragraph.split +reportlab.platypus.paragraph.Paragraph.wrap +reportlab.platypus.tables.Table.split +reportlab.platypus.tables.Table.wrap + +# these have an optional extra argument which isn't consistently used +# among subclasses, so we pretend it doesn't exist for now +reportlab.platypus.flowables._ContainerSpace.getSpaceAfter +reportlab.platypus.flowables._ContainerSpace.getSpaceBefore + +# this has an internal __boundary__ argument which confuses stubtest +# we've decided to just get rid of the argument in the stub entirely +reportlab.platypus.frames.Frame.drawBoundary + +# this is just a case-insenstive version of dict and changes in parameter +# names and them changing from positional-only to keyword or positional +# is entirely untintentional, for simplicity we assume these methods +# work the same as in the base class, there is only one exception +# where the signature actually is more restrictive in CIDict +reportlab.lib.utils.CIDict.get +reportlab.lib.utils.CIDict.pop +reportlab.lib.utils.CIDict.setdefault + +# __new__ just forwards the arguments to the super class +# it doesn't actually accept arbitrary arguments +reportlab.platypus.doctemplate.PTCycle.__new__ + + +# Error: not present in stub +# ========================== +# loop variables that weren't cleaned up +reportlab.lib.fonts.v +reportlab.graphics.barcode.code93.k +reportlab.graphics.barcode.code93.v +reportlab.graphics.barcode.qrencoder.i +reportlab.lib.fonts.k +reportlab.lib.pdfencrypt.i + +# should allow setting any attribute +reportlab.lib.abag.ABag.__setattr__ +reportlab.lib.styles.PropertySet.__setattr__ + +# *-imports that cause a mess we don't want to propagate +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.EVEN_ODD +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.FILL_EVEN_ODD +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.FILL_NON_ZERO +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.NON_ZERO_WINDING +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.STATE_DEFAULTS +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.decimalSymbol +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.pi +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.shapeChecking +reportlab\.graphics\.render(base|PDF|PM|PS|SVG)\.verbose + +# messed up __all__ which contains just a string +reportlab.graphics.barcode.qr.__all__ + + +# Error: is not present at runtime +# ================================ +# These can have arbitrary attributes, so we add a __getattr__ +reportlab.lib.abag.ABag.__getattr__ +reportlab.lib.styles.PropertySet.__getattr__ + +# Only exists on renderPM backend +reportlab.graphics.utils.processGlyph + + +# Error: failed to find stubs +# =========================== +# Modules that are only used for testing +reportlab.graphics.testdrawings +reportlab.graphics.testshapes +reportlab.graphics.barcode.test + +# named tuple docstring +reportlab.pdfbase.ttfonts.ShapeData.__doc__ diff --git a/stubs/reportlab/@tests/test_cases/check_tables.py b/stubs/reportlab/@tests/test_cases/check_tables.py new file mode 100644 index 000000000000..0d1b93de8170 --- /dev/null +++ b/stubs/reportlab/@tests/test_cases/check_tables.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +from typing import Any + +from reportlab.lib import colors +from reportlab.lib.styles import getSampleStyleSheet +from reportlab.lib.units import inch +from reportlab.platypus.flowables import Image +from reportlab.platypus.paragraph import Paragraph +from reportlab.platypus.tables import Table, TableStyle + +data: list[list[Any]] + +# Verify all the examples from the docs work + +# +# TableStyle User Methods +# +LIST_STYLE = TableStyle( + [ + ("LINEABOVE", (0, 0), (-1, 0), 2, colors.green), + ("LINEABOVE", (0, 1), (-1, -1), 0.25, colors.black), + ("LINEBELOW", (0, -1), (-1, -1), 2, colors.green), + ("ALIGN", (1, 1), (-1, -1), "RIGHT"), + ] +) +LIST_STYLE.add("BACKGROUND", (0, 0), (-1, 0), colors.Color(0, 0.7, 0.7)) + +# +# TableStyle Cell Formatting Commands +# +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +t = Table(data) +t.setStyle(TableStyle([("BACKGROUND", (1, 1), (-2, -2), colors.green), ("TEXTCOLOR", (0, 0), (1, -1), colors.red)])) + +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +t = Table(data, 5 * [0.4 * inch], 4 * [0.4 * inch]) +# NOTE: I've modified this example to drop the optional TableStyle +# wrapper, so we test both variants +t.setStyle( + [ + ("ALIGN", (1, 1), (-2, -2), "RIGHT"), + ("TEXTCOLOR", (1, 1), (-2, -2), colors.red), + ("VALIGN", (0, 0), (0, -1), "TOP"), + ("TEXTCOLOR", (0, 0), (0, -1), colors.blue), + ("ALIGN", (0, -1), (-1, -1), "CENTER"), + ("VALIGN", (0, -1), (-1, -1), "MIDDLE"), + ("TEXTCOLOR", (0, -1), (-1, -1), colors.green), + ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), + ("BOX", (0, 0), (-1, -1), 0.25, colors.black), + ] +) + +# +# Table Style Line Commands +# +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ], +) + +data = [ + ["00", "01", "02", "03", "04"], + ["10", "11", "12", "13", "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("BOX", (0, 0), (-1, -1), 2, colors.black), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("BACKGROUND", (1, 1), (1, 2), colors.lavender), + ("BACKGROUND", (2, 2), (2, 3), colors.orange), + ], +) + +# +# Complex Cell Values +# +styleSheet = getSampleStyleSheet() +I = Image("foo.jpg") +I.drawHeight = 1.25 * inch * I.drawHeight / I.drawWidth +I.drawWidth = 1.25 * inch +P0 = Paragraph( + """A paragraph + 1""", + styleSheet["BodyText"], +) +P = Paragraph( + """The ReportLab Left + Logo + Image""", + styleSheet["BodyText"], +) +data = [ + ["A", "B", "C", P0, "D"], + ["00", "01", "02", [I, P], "04"], + ["10", "11", "12", [P, I], "14"], + ["20", "21", "22", "23", "24"], + ["30", "31", "32", "33", "34"], +] +Table( + data, + style=[ + ("GRID", (1, 1), (-2, -2), 1, colors.green), + ("BOX", (0, 0), (1, -1), 2, colors.red), + ("LINEABOVE", (1, 2), (-2, 2), 1, colors.blue), + ("LINEBEFORE", (2, 1), (2, -2), 1, colors.pink), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("BACKGROUND", (1, 1), (1, 2), colors.lavender), + ("BACKGROUND", (2, 2), (2, 3), colors.orange), + ("BOX", (0, 0), (-1, -1), 2, colors.black), + ("GRID", (0, 0), (-1, -1), 0.5, colors.black), + ("VALIGN", (3, 0), (3, 0), "BOTTOM"), + ("BACKGROUND", (3, 0), (3, 0), colors.limegreen), + ("BACKGROUND", (3, 1), (3, 1), colors.khaki), + ("ALIGN", (3, 1), (3, 1), "CENTER"), + ("BACKGROUND", (3, 2), (3, 2), colors.beige), + ("ALIGN", (3, 2), (3, 2), "LEFT"), + ], +) + +# +# TableStyle Span Commands +# +data = [ + ["Top\\nLeft", "", "02", "03", "04"], + ["", "", "12", "13", "14"], + ["20", "21", "22", "Bottom\\nRight", ""], + ["30", "31", "32", "", ""], +] +Table( + data, + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("BACKGROUND", (0, 0), (1, 1), colors.palegreen), + ("SPAN", (0, 0), (1, 1)), + ("BACKGROUND", (-2, -2), (-1, -1), colors.pink), + ("SPAN", (-2, -2), (-1, -1)), + ], +) + +# +# TableStyle Miscellaneous Commands +# +# NOTE: This one doesn't provide any actual examples, we just +# make sure these pass into TableStyle/Table when mixed +# with other commands +TableStyle([("NOSPLIT", (0, 0), (1, 1))]) +LIST_STYLE.add("NOSPLIT", (0, 0), (1, 1)) + +TableStyle([("ROUNDEDCORNERS", [0, 0, 5, 5])]) +TableStyle([("ROUNDEDCORNERS", (0, 0, 5, 5))]) +LIST_STYLE.add("ROUNDEDCORNERS", [0, 0, 5, 5]) +LIST_STYLE.add("ROUNDEDCORNERS", (0, 0, 5, 5)) + +Table( + [["foo"]], + style=[ + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("BACKGROUND", (0, 0), (0, 1), colors.pink), + ("NOSPLIT", (0, 0), (1, 1)), + ("ROUNDEDCORNERS", [0, 0, 5, 5]), + ], +) + + +# Testing the various possible data layouts +Table([["foo"]]) +Table([("foo",)]) +Table((["foo"],)) +Table((("foo",),)) diff --git a/stubs/reportlab/METADATA.toml b/stubs/reportlab/METADATA.toml new file mode 100644 index 000000000000..a01438bb6bca --- /dev/null +++ b/stubs/reportlab/METADATA.toml @@ -0,0 +1,7 @@ +version = "4.5.1" +# GitHub mirror of https://hg.reportlab.com/hg-public/reportlab/file +upstream-repository = "https://github.com/MrBitBucket/reportlab-mirror" + +[tool.stubtest] +apt-dependencies = ["libcairo2-dev"] +extras = ["pycairo"] diff --git a/stubs/reportlab/reportlab/__init__.pyi b/stubs/reportlab/reportlab/__init__.pyi new file mode 100644 index 000000000000..664f86e2f301 --- /dev/null +++ b/stubs/reportlab/reportlab/__init__.pyi @@ -0,0 +1,11 @@ +from _typeshed import SupportsRichComparison +from typing import Final, Literal, TypeVar + +_SupportsRichComparisonT = TypeVar("_SupportsRichComparisonT", bound=SupportsRichComparison) + +Version: Final[str] +__version__: Final[str] +__date__: Final[str] +__min_python_version__: Final[tuple[int, int]] + +def cmp(a: _SupportsRichComparisonT, b: _SupportsRichComparisonT) -> Literal[-1, 0, 1]: ... diff --git a/stubs/reportlab/reportlab/graphics/__init__.pyi b/stubs/reportlab/reportlab/graphics/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi b/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi new file mode 100644 index 000000000000..62d6c1381612 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/__init__.pyi @@ -0,0 +1,7 @@ +def registerWidget(widget) -> None: ... +def getCodes(): ... +def getCodeNames(): ... +def createBarcodeDrawing(codeName, **options): ... +def createBarcodeImageInMemory(codeName, **options): ... + +__all__ = ("registerWidget", "getCodes", "getCodeNames", "createBarcodeDrawing", "createBarcodeImageInMemory") diff --git a/stubs/reportlab/reportlab/graphics/barcode/code128.pyi b/stubs/reportlab/reportlab/graphics/barcode/code128.pyi new file mode 100644 index 000000000000..024bfcdf439f --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code128.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import MultiWidthBarcode + +starta: Incomplete +startb: Incomplete +startc: Incomplete +stop: Incomplete +seta: Incomplete +setb: Incomplete +setc: Incomplete +setmap: Incomplete +cStarts: Incomplete +tos: Incomplete + +class Code128(MultiWidthBarcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + barHeight: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + decomposed: Incomplete + def decompose(self): ... + +class Code128Auto(Code128): + encoded: Incomplete + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/code39.pyi b/stubs/reportlab/reportlab/graphics/barcode/code39.pyi new file mode 100644 index 000000000000..bea530fb0076 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code39.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class _Code39Base(Barcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + gap: Incomplete + barHeight: Incomplete + ratio: float + checksum: int + bearers: float + stop: int + def __init__(self, value: str = "", **args) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Standard39(_Code39Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + +class Extended39(_Code39Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: str + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/code93.pyi b/stubs/reportlab/reportlab/graphics/barcode/code93.pyi new file mode 100644 index 000000000000..cc436c1470bd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/code93.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import MultiWidthBarcode + +class _Code93Base(MultiWidthBarcode): + barWidth: Incomplete + lquiet: Incomplete + rquiet: Incomplete + quiet: int + barHeight: Incomplete + stop: int + def __init__(self, value: str = "", **args) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Standard93(_Code93Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self): ... + +class Extended93(_Code93Base): + valid: int + validated: Incomplete + def validate(self): ... + encoded: str + def encode(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/common.pyi b/stubs/reportlab/reportlab/graphics/barcode/common.pyi new file mode 100644 index 000000000000..513fb79debf7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/common.pyi @@ -0,0 +1,127 @@ +from _typeshed import Incomplete + +from reportlab.platypus.flowables import Flowable + +class Barcode(Flowable): + fontName: str + fontSize: int + humanReadable: int + value: Incomplete + gap: Incomplete + def __init__(self, value: str = "", **kwd) -> None: ... + valid: int + validated: Incomplete + def validate(self) -> None: ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self) -> None: ... + barHeight: Incomplete + def computeSize(self, *args) -> None: ... + + @property + def width(self): ... + @width.setter + def width(self, v) -> None: ... + + @property + def height(self): ... + @height.setter + def height(self, v) -> None: ... + + def draw(self) -> None: ... + def drawHumanReadable(self) -> None: ... + def rect(self, x, y, w, h) -> None: ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +class MultiWidthBarcode(Barcode): + barHeight: Incomplete + def computeSize(self, *args) -> None: ... + def draw(self) -> None: ... + +class I2of5(Barcode): + patterns: Incomplete + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + bearerBox: bool + quiet: int + lquiet: Incomplete + rquiet: Incomplete + stop: int + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class MSI(Barcode): + patterns: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Codabar(Barcode): + patterns: Incomplete + values: Incomplete + chars: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + Valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... + +class Code11(Barcode): + chars: str + patterns: Incomplete + values: Incomplete + stop: int + barHeight: Incomplete + barWidth: Incomplete + ratio: float + checksum: int + bearers: float + quiet: int + lquiet: Incomplete + rquiet: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + valid: int + Valid: int + validated: Incomplete + def validate(self): ... + encoded: Incomplete + def encode(self) -> None: ... + decomposed: Incomplete + def decompose(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi b/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi new file mode 100644 index 000000000000..480095e85683 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/dmtx.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode +from reportlab.graphics.widgetbase import Widget + +class _DMTXCheck: + @classmethod + def pylibdmtx_check(cls) -> None: ... + +class DataMatrix(Barcode, _DMTXCheck): + color: Incomplete + bgColor: Incomplete + def __init__(self, value: str = "", **kwds) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, v) -> None: ... + + @property + def size(self): ... + @size.setter + def size(self, v) -> None: ... + + @property + def border(self): ... + @border.setter + def border(self, v) -> None: ... + + @property + def x(self): ... + @x.setter + def x(self, v) -> None: ... + + @property + def y(self): ... + @y.setter + def y(self, v) -> None: ... + + @property + def cellSize(self): ... + @cellSize.setter + def cellSize(self, v) -> None: ... + + @property + def encoding(self): ... + @encoding.setter + def encoding(self, v) -> None: ... + + @property + def anchor(self): ... + @anchor.setter + def anchor(self, v) -> None: ... + + def recalc(self) -> None: ... + @property + def matrix(self): ... + @property # type: ignore[misc] # TODO: for mypy < 1.16 + def width(self): ... # type: ignore[override] + @property # type: ignore[misc] # TODO: for mypy < 1.16 + def height(self): ... # type: ignore[override] + @property + def cellWidth(self): ... + @property + def cellHeight(self): ... + def draw(self) -> None: ... + +class DataMatrixWidget(Widget, _DMTXCheck): + codeName: str + value: Incomplete + def __init__(self, value: str = "Hello Cruel World!", **kwds) -> None: ... + def rect(self, x, y, w, h, fill: int = 1, stroke: int = 0) -> None: ... + def saveState(self, *args, **kwds) -> None: ... + restoreState = saveState + setStrokeColor = saveState + def setFillColor(self, c) -> None: ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi b/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi new file mode 100644 index 000000000000..18b4045e005f --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/eanbc.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.lib.attrmap import * + +class Ean13BarcodeWidget(PlotArea): + codeName: str + barHeight: Incomplete + barWidth: Incomplete + humanReadable: int + quiet: int + rquiet: Incomplete + lquiet: Incomplete + fontSize: int + fontName: str + textColor: Incomplete + barFillColor: Incomplete + barStrokeColor: Incomplete + barStrokeWidth: int + x: int + y: int + value: Incomplete + def __init__(self, value: str = "123456789012", **kw) -> None: ... + @property + def width(self): ... # type: ignore[override] + def wrap(self, aW, aH): ... + def draw(self): ... + +class Ean8BarcodeWidget(Ean13BarcodeWidget): + codeName: str + +class UPCA(Ean13BarcodeWidget): + codeName: str + +class Ean5BarcodeWidget(Ean13BarcodeWidget): + codeName: str + def draw(self): ... + +class ISBNBarcodeWidget(Ean13BarcodeWidget): + codeName: str + def draw(self): ... + +__all__ = ("Ean13BarcodeWidget", "Ean8BarcodeWidget", "UPCA", "Ean5BarcodeWidget", "ISBNBarcodeWidget") diff --git a/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi b/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi new file mode 100644 index 000000000000..e017b1bba63b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/ecc200datamatrix.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class ECC200DataMatrix(Barcode): + barWidth: int + row_modules: int + col_modules: int + row_regions: int + col_regions: int + cw_data: int + cw_ecc: int + row_usable_modules: Incomplete + col_usable_modules: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + valid: int + validated: Incomplete + def validate(self) -> None: ... + encoded: Incomplete + def encode(self): ... + def computeSize(self, *args) -> None: ... + def draw(self) -> None: ... + +__all__ = ("ECC200DataMatrix",) diff --git a/stubs/reportlab/reportlab/graphics/barcode/fourstate.pyi b/stubs/reportlab/reportlab/graphics/barcode/fourstate.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/reportlab/reportlab/graphics/barcode/lto.pyi b/stubs/reportlab/reportlab/graphics/barcode/lto.pyi new file mode 100644 index 000000000000..dde1e45e2e4a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/lto.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.code39 import Standard39 + +class BaseLTOLabel(Standard39): + LABELWIDTH: Incomplete + LABELHEIGHT: Incomplete + LABELROUND: Incomplete + CODERATIO: float + CODENOMINALWIDTH: Incomplete + CODEBARHEIGHT: Incomplete + CODEBARWIDTH: Incomplete + CODEGAP = CODEBARWIDTH # pyrefly: ignore [unknown-name] + CODELQUIET: Incomplete + CODERQUIET: Incomplete + height: Incomplete + border: Incomplete + label: Incomplete + def __init__( + self, prefix: str = "", number=None, subtype: str = "1", border=None, checksum: bool = False, availheight=None + ) -> None: ... + def drawOn(self, canvas, x, y) -> None: ... + +class VerticalLTOLabel(BaseLTOLabel): + LABELFONT: Incomplete + BLOCKWIDTH: Incomplete + BLOCKHEIGHT: Incomplete + LINEWIDTH: float + NBBLOCKS: int + COLORSCHEME: Incomplete + colored: Incomplete + def __init__(self, *args, **kwargs) -> None: ... + def drawOn(self, canvas, x, y) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/qr.pyi b/stubs/reportlab/reportlab/graphics/barcode/qr.pyi new file mode 100644 index 000000000000..817ba00d72e0 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/qr.pyi @@ -0,0 +1,55 @@ +from _typeshed import Incomplete +from typing import type_check_only + +from reportlab.graphics.shapes import Rect +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import Validator +from reportlab.platypus.flowables import Flowable + +__all__ = ["QrCodeWidget"] + +@type_check_only +class _isLevel(Validator): + def test(self, x): ... + +isLevel: _isLevel + +@type_check_only +class _isUnicodeOrQRList(Validator): + def test(self, x): ... + def normalize(self, x): ... + +isUnicodeOrQRList: _isUnicodeOrQRList + +class SRect(Rect): + def __init__(self, x, y, width, height, fillColor=...) -> None: ... + +class QrCodeWidget(Widget): + codeName: str + x: int + y: int + barFillColor: Incomplete + barStrokeColor: Incomplete + barStrokeWidth: int + barHeight: Incomplete + barWidth: Incomplete + barBorder: int + barLevel: str + qrVersion: Incomplete + value: Incomplete + def __init__(self, value: str = "Hello World", **kw) -> None: ... + def addData(self, value) -> None: ... + def draw(self): ... + +class QrCode(Flowable): + height: Incomplete + width: Incomplete + qrBorder: int + qrLevel: str + qrVersion: Incomplete + value: Incomplete + qr: Incomplete + def __init__(self, value=None, **kw) -> None: ... + def addData(self, value) -> None: ... + def draw(self) -> None: ... + def rect(self, x, y, w, h) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi b/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi new file mode 100644 index 000000000000..5f4d2bb6f47b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/qrencoder.pyi @@ -0,0 +1,202 @@ +from _typeshed import Incomplete + +unicode = str + +class QR: + valid: Incomplete + bits: Incomplete + group: int + data: Incomplete + def __init__(self, data) -> None: ... + def __len__(self) -> int: ... + @property + def bitlength(self): ... + def getLengthBits(self, ver): ... + def getLength(self): ... + def write_header(self, buffer, version) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRNumber(QR): + valid: Incomplete + chars: str + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + +class QRAlphaNum(QR): + valid: Incomplete + chars: str + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + +class QR8bitByte(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRKanji(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def unicode_to_qrkanji(self, data): ... + def write(self, buffer, version) -> None: ... + +class QRHanzi(QR): + bits: Incomplete + group: int + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def unicode_to_qrhanzi(self, data): ... + def write_header(self, buffer, version) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRECI(QR): + mode: int + lengthbits: Incomplete + data: Incomplete + def __init__(self, data) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRStructAppend(QR): + mode: int + lengthbits: Incomplete + part: Incomplete + total: Incomplete + parity: Incomplete + def __init__(self, part, total, parity) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRFNC1First(QR): + mode: int + lengthbits: Incomplete + def __init__(self) -> None: ... + def write(self, buffer, version) -> None: ... + +class QRFNC1Second(QR): + valid: Incomplete + mode: int + lengthbits: Incomplete + def write(self, buffer, version) -> None: ... + +class QRCode: + version: Incomplete + errorCorrectLevel: Incomplete + modules: Incomplete + moduleCount: int + dataCache: Incomplete + dataList: Incomplete + def __init__(self, version, errorCorrectLevel) -> None: ... + def addData(self, data) -> None: ... + def isDark(self, row, col): ... + def getModuleCount(self): ... + def calculate_version(self): ... + def make(self) -> None: ... + def makeImpl(self, test, maskPattern) -> None: ... + def setupPositionProbePattern(self, row, col) -> None: ... + def getBestMaskPattern(self): ... + def setupTimingPattern(self) -> None: ... + def setupPositionAdjustPattern(self) -> None: ... + def setupTypeNumber(self, test) -> None: ... + def setupTypeInfo(self, test, maskPattern) -> None: ... + def dataPosIterator(self): ... + def dataBitIterator(self, data): ... + def mapData(self, data, maskPattern) -> None: ... + PAD0: int + PAD1: int + @staticmethod + def createData(version, errorCorrectLevel, dataList): ... + @staticmethod + def createBytes(buffer, rsBlocks): ... + +class QRErrorCorrectLevel: + L: int + M: int + Q: int + H: int + +class QRMaskPattern: + PATTERN000: int + PATTERN001: int + PATTERN010: int + PATTERN011: int + PATTERN100: int + PATTERN101: int + PATTERN110: int + PATTERN111: int + +class QRUtil: + PATTERN_POSITION_TABLE: Incomplete + G15: Incomplete + G18: Incomplete + G15_MASK: Incomplete + @staticmethod + def getBCHTypeInfo(data): ... + @staticmethod + def getBCHTypeNumber(data): ... + @staticmethod + def getBCHDigit(data): ... + @staticmethod + def getPatternPosition(version): ... + maskPattern: Incomplete + @classmethod + def getMask(cls, maskPattern): ... + @staticmethod + def getErrorCorrectPolynomial(errorCorrectLength): ... + @classmethod + def maskScoreRule1vert(cls, modules): ... + @classmethod + def maskScoreRule2(cls, modules): ... + @classmethod + def maskScoreRule3hor(cls, modules, pattern=...): ... + @classmethod + def maskScoreRule4(cls, modules): ... + @classmethod + def getLostPoint(cls, qrCode): ... + +class QRMath: + @staticmethod + def glog(n): ... + @staticmethod + def gexp(n): ... + +EXP_TABLE: Incomplete +LOG_TABLE: Incomplete + +class QRPolynomial: + num: Incomplete + def __init__(self, num, shift) -> None: ... + def get(self, index): ... + def getLength(self): ... + def multiply(self, e): ... + def mod(self, e): ... + +class QRRSBlock: + RS_BLOCK_TABLE: Incomplete + totalCount: Incomplete + dataCount: Incomplete + def __init__(self, totalCount, dataCount) -> None: ... + @staticmethod + def getRSBlocks(version, errorCorrectLevel): ... + @staticmethod + def getRsBlockTable(version, errorCorrectLevel): ... + +class QRBitBuffer: + buffer: Incomplete + length: int + def __init__(self) -> None: ... + def get(self, index): ... + def put(self, num, length) -> None: ... + def getLengthInBits(self): ... + def putBit(self, bit) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/usps.pyi b/stubs/reportlab/reportlab/graphics/barcode/usps.pyi new file mode 100644 index 000000000000..455b99df3781 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/usps.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class FIM(Barcode): + barWidth: Incomplete + spaceWidth: Incomplete + barHeight: Incomplete + rquiet: Incomplete + lquiet: Incomplete + quiet: int + def __init__(self, value: str = "", **args) -> None: ... + valid: int + validated: str + def validate(self): ... + decomposed: str + def decompose(self): ... + def computeSize(self) -> None: ... + def draw(self) -> None: ... + +class POSTNET(Barcode): + quiet: int + shortHeight: Incomplete + barHeight: Incomplete + barWidth: Incomplete + spaceWidth: Incomplete + def __init__(self, value: str = "", **args) -> None: ... + validated: str + valid: int + def validate(self): ... + encoded: str + def encode(self): ... + decomposed: str + def decompose(self): ... + def computeSize(self) -> None: ... + def draw(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi b/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi new file mode 100644 index 000000000000..069b94a2f30c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/usps4s.pyi @@ -0,0 +1,103 @@ +from _typeshed import Incomplete + +from reportlab.graphics.barcode.common import Barcode + +class USPS_4State(Barcode): + tops: Incomplete + bottoms: Incomplete + dimensions: Incomplete + def __init__(self, value: str = "01234567094987654321", routing: str = "", **kwd) -> None: ... + @staticmethod + def scale(kind, D, s): ... + + @property + def tracking(self): ... + @tracking.setter + def tracking(self, tracking) -> None: ... + + @property + def routing(self): ... + @routing.setter + def routing(self, routing) -> None: ... + + @property + def widthSize(self): ... + @widthSize.setter + def widthSize(self, value) -> None: ... + + @property + def heightSize(self): ... + @heightSize.setter + def heightSize(self, value) -> None: ... + + @property + def fontSize(self): ... + @fontSize.setter + def fontSize(self, value) -> None: ... + + @property + def humanReadable(self): ... + @humanReadable.setter + def humanReadable(self, value) -> None: ... + + @property + def binary(self): ... + @property + def codewords(self): ... + @property + def table1(self): ... + @property + def table2(self): ... + @property + def characters(self): ... + @property + def barcodes(self): ... + table4: Incomplete + @property + def horizontalClearZone(self): ... + @property + def verticalClearZone(self): ... + + @property + def barWidth(self): ... + @barWidth.setter + def barWidth(self, value) -> None: ... + + @property + def pitch(self): ... + @pitch.setter + def pitch(self, value) -> None: ... + + @property + def barHeight(self): ... + @barHeight.setter + def barHeight(self, value) -> None: ... + + @property + def widthScale(self): ... + @property + def heightScale(self): ... + + @property + def width(self): ... + @width.setter + def width(self, v) -> None: ... + + @property + def height(self): ... + @height.setter + def height(self, v) -> None: ... + + def computeSize(self) -> None: ... + def wrap(self, aW, aH): ... + def draw(self) -> None: ... + + @property + def value(self): ... + @value.setter + def value(self, value) -> None: ... + + def drawHumanReadable(self) -> None: ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +__all__ = ("USPS_4State",) diff --git a/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi b/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi new file mode 100644 index 000000000000..2ea5c9d53937 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/barcode/widgets.pyi @@ -0,0 +1,80 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.lib.colors import black + +class _BarcodeWidget(PlotArea): + textColor = black + barFillColor = black + barStrokeColor: Incomplete + barStrokeWidth: int + x: int + def __init__(self, _value: str = "", **kw) -> None: ... + def rect(self, x, y, w, h, **kw) -> None: ... + canv: Incomplete + def draw(self): ... + def annotate(self, x, y, text, fontName, fontSize, anchor: str = "middle") -> None: ... + +class BarcodeI2of5(_BarcodeWidget): + codeName: Final = "I2of5" + def __init__(self, **kw) -> None: ... + +class BarcodeCode128(_BarcodeWidget): + codeName: Final = "Code128" + def __init__(self, **kw) -> None: ... + +class BarcodeStandard93(_BarcodeWidget): + codeName: Final = "Standard93" + def __init__(self, **kw) -> None: ... + +class BarcodeExtended93(_BarcodeWidget): + codeName: Final = "Extended93" + def __init__(self, **kw) -> None: ... + +class BarcodeStandard39(_BarcodeWidget): + codeName: Final = "Standard39" + def __init__(self, **kw) -> None: ... + +class BarcodeExtended39(_BarcodeWidget): + codeName: Final = "Extended39" + def __init__(self, **kw) -> None: ... + +class BarcodeMSI(_BarcodeWidget): + codeName: Final = "MSI" + def __init__(self, **kw) -> None: ... + +class BarcodeCodabar(_BarcodeWidget): + codeName: Final = "Codabar" + def __init__(self, **kw) -> None: ... + +class BarcodeCode11(_BarcodeWidget): + codeName: Final = "Code11" + def __init__(self, **kw) -> None: ... + +class BarcodeFIM(_BarcodeWidget): + codeName: Final = "FIM" + def __init__(self, **kw) -> None: ... + +class BarcodePOSTNET(_BarcodeWidget): + codeName: Final = "POSTNET" + def __init__(self, **kw) -> None: ... + +class BarcodeUSPS_4State(_BarcodeWidget): + codeName: Final = "USPS_4State" + def __init__(self, **kw) -> None: ... + +__all__ = ( + "BarcodeI2of5", + "BarcodeCode128", + "BarcodeStandard93", + "BarcodeExtended93", + "BarcodeStandard39", + "BarcodeExtended39", + "BarcodeMSI", + "BarcodeCodabar", + "BarcodeCode11", + "BarcodeFIM", + "BarcodePOSTNET", + "BarcodeUSPS_4State", +) diff --git a/stubs/reportlab/reportlab/graphics/charts/__init__.pyi b/stubs/reportlab/reportlab/graphics/charts/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/charts/areas.pyi b/stubs/reportlab/reportlab/graphics/charts/areas.pyi new file mode 100644 index 000000000000..018cf3518116 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/areas.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +class PlotArea(Widget): + x: int + y: int + height: int + width: int + strokeColor: Incomplete + strokeWidth: int + fillColor: Incomplete + background: Incomplete + debug: int + def __init__(self) -> None: ... + def makeBackground(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/axes.pyi b/stubs/reportlab/reportlab/graphics/charts/axes.pyi new file mode 100644 index 000000000000..51274804d9e4 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/axes.pyi @@ -0,0 +1,205 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.textlabels import PMVLabel +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import Validator + +__version__: Final[str] + +class AxisLabelAnnotation: + def __init__(self, v, **kwds) -> None: ... + def __call__(self, axis): ... + +class AxisLineAnnotation: + def __init__(self, v, **kwds) -> None: ... + def __call__(self, axis): ... + +class AxisBackgroundAnnotation: + def __init__(self, colors, **kwds) -> None: ... + def __call__(self, axis): ... + +class TickLU: + accuracy: Incomplete + T: Incomplete + def __init__(self, *T, **kwds) -> None: ... + def __contains__(self, t) -> bool: ... + def __getitem__(self, t): ... + +class _AxisG(Widget): + def makeGrid(self, g, dim=None, parent=None, exclude=[]) -> None: ... + def getGridDims(self, start=None, end=None): ... + @property + def isYAxis(self): ... + @property + def isXAxis(self): ... + def addAnnotations(self, g, A=None) -> None: ... + def draw(self): ... + +class CALabel(PMVLabel): + def __init__(self, **kw) -> None: ... + +class CategoryAxis(_AxisG): + visible: int + visibleAxis: int + visibleTicks: int + visibleLabels: int + visibleGrid: int + drawGridLast: bool + strokeWidth: int + strokeColor: Incomplete + strokeDashArray: Incomplete + gridStrokeLineJoin: Incomplete + gridStrokeLineCap: Incomplete + gridStrokeMiterLimit: Incomplete + gridStrokeWidth: float + gridStrokeColor: Incomplete + gridStrokeDashArray: Incomplete + gridStart: Incomplete + strokeLineJoin: Incomplete + strokeLineCap: Incomplete + strokeMiterLimit: Incomplete + labels: Incomplete + categoryNames: Incomplete + joinAxis: Incomplete + joinAxisPos: Incomplete + joinAxisMode: Incomplete + labelAxisMode: str + reverseDirection: int + style: str + tickShift: int + loPad: int + hiPad: int + loLLen: int + hiLLen: int + def __init__(self) -> None: ... + def setPosition(self, x, y, length) -> None: ... + def configure(self, multiSeries, barWidth=None) -> None: ... + def scale(self, idx): ... + def midScale(self, idx): ... + +class _XTicks: + @property + def actualTickStrokeWidth(self): ... + @property + def actualTickStrokeColor(self): ... + def makeTicks(self): ... + +class _YTicks(_XTicks): + def makeTicks(self): ... + +class XCategoryAxis(_XTicks, CategoryAxis): + tickUp: int + tickDown: int + def __init__(self) -> None: ... + categoryNames: Incomplete + def demo(self): ... + def joinToAxis(self, yAxis, mode: str = "bottom", pos=None) -> None: ... + def loScale(self, idx): ... + def makeAxis(self): ... + def makeTickLabels(self): ... + +class YCategoryAxis(_YTicks, CategoryAxis): + tickLeft: int + tickRight: int + def __init__(self) -> None: ... + categoryNames: Incomplete + def demo(self): ... + def joinToAxis(self, xAxis, mode: str = "left", pos=None) -> None: ... + def loScale(self, idx): ... + def makeAxis(self): ... + def makeTickLabels(self): ... + +class TickLabeller: + def __call__(self, axis, value): ... + +class ValueAxis(_AxisG): + def __init__(self, **kw) -> None: ... + def setPosition(self, x, y, length) -> None: ... + def configure(self, dataSeries) -> None: ... + def makeTickLabels(self): ... + def scale(self, value): ... + +class XValueAxis(_XTicks, ValueAxis): + tickUp: int + tickDown: int + joinAxis: Incomplete + joinAxisMode: Incomplete + joinAxisPos: Incomplete + def __init__(self, **kw) -> None: ... + def demo(self): ... + def joinToAxis(self, yAxis, mode: str = "bottom", pos=None) -> None: ... + def makeAxis(self): ... + +def parseDayAndMonth(dmstr): ... + +class _isListOfDaysAndMonths(Validator): + def test(self, x): ... + def normalize(self, x): ... + +isListOfDaysAndMonths: Incomplete + +class NormalDateXValueAxis(XValueAxis): + bottomAxisLabelSlack: float + niceMonth: int + forceEndDate: int + forceFirstDate: int + forceDatesEachYear: Incomplete + dailyFreq: int + xLabelFormat: str + dayOfWeekName: Incomplete + monthName: Incomplete + specialTickClear: int + valueSteps: Incomplete + def __init__(self, **kw) -> None: ... + def configure(self, data) -> None: ... + +class YValueAxis(_YTicks, ValueAxis): + tickRight: int + tickLeft: int + joinAxis: Incomplete + joinAxisMode: Incomplete + joinAxisPos: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def joinToAxis(self, xAxis, mode: str = "left", pos=None) -> None: ... + def makeAxis(self): ... + +class TimeValueAxis: + labelTextFormat: Incomplete + def __init__(self, *args, **kwds) -> None: ... + def timeLabelTextFormatter(self, val): ... + +class XTimeValueAxis(TimeValueAxis, XValueAxis): + def __init__(self, *args, **kwds) -> None: ... + +class AdjYValueAxis(YValueAxis): + requiredRange: int + leftAxisPercent: int + leftAxisOrigShiftIPC: float + leftAxisOrigShiftMin: int + leftAxisSkipLL0: int + valueSteps: Incomplete + def __init__(self, **kw) -> None: ... + +class LogValueAxis(ValueAxis): ... + +class LogAxisTickLabeller(TickLabeller): + def __call__(self, axis, value): ... + +class LogAxisTickLabellerS(TickLabeller): + def __call__(self, axis, value): ... + +class LogAxisLabellingSetup: + labels: Incomplete + labelTextFormat: Incomplete + def __init__(self) -> None: ... + +class LogXValueAxis(LogValueAxis, LogAxisLabellingSetup, XValueAxis): + def __init__(self) -> None: ... + def scale(self, value): ... + +class LogYValueAxis(LogValueAxis, LogAxisLabellingSetup, YValueAxis): + def __init__(self) -> None: ... + def scale(self, value): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi b/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi new file mode 100644 index 000000000000..303ca4bc20c1 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/barcharts.pyi @@ -0,0 +1,105 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.shapes import Drawing +from reportlab.graphics.widgetbase import PropHolder + +__version__: Final[str] + +class BarChartProperties(PropHolder): + strokeColor: Incomplete + fillColor: Incomplete + strokeWidth: float + symbol: Incomplete + strokeDashArray: Incomplete + def __init__(self) -> None: ... + +class BarChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + categoryAxis: Incomplete + valueAxis: Incomplete + barSpacing: int + reversePlotOrder: int + data: Incomplete + useAbsolute: int + barWidth: int + groupSpacing: int + barLabels: Incomplete + barLabelFormat: Incomplete + barLabelArray: Incomplete + bars: Incomplete + naLabel: Incomplete + zIndexOverrides: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def getSeriesOrder(self) -> None: ... + def calcBarPositions(self) -> None: ... + def makeBars(self): ... + def draw(self): ... + +class VerticalBarChart(BarChart): ... +class HorizontalBarChart(BarChart): ... + +class _FakeGroup: + def __init__(self, cmp=None) -> None: ... + def add(self, what) -> None: ... + def value(self): ... + def sort(self) -> None: ... + +class BarChart3D(BarChart): + theta_x: float + theta_y: float + zDepth: Incomplete + zSpace: Incomplete + def calcBarPositions(self) -> None: ... + def makeBars(self): ... + +class VerticalBarChart3D(BarChart3D, VerticalBarChart): ... +class HorizontalBarChart3D(BarChart3D, HorizontalBarChart): ... + +def sampleV0a(): ... +def sampleV0b(): ... +def sampleV0c(): ... +def sampleV1(): ... +def sampleV2a(): ... +def sampleV2b(): ... +def sampleV2c(): ... +def sampleV3(): ... +def sampleV4a(): ... +def sampleV4b(): ... +def sampleV4c(): ... +def sampleV4d(): ... + +dataSample5: Incomplete + +def sampleV5a(): ... +def sampleV5b(): ... +def sampleV5c1(): ... +def sampleV5c2(): ... +def sampleV5c3(): ... +def sampleV5c4(): ... +def sampleH0a(): ... +def sampleH0b(): ... +def sampleH0c(): ... +def sampleH1(): ... +def sampleH2a(): ... +def sampleH2b(): ... +def sampleH2c(): ... +def sampleH3(): ... +def sampleH4a(): ... +def sampleH4b(): ... +def sampleH4c(): ... +def sampleH4d(): ... +def sampleH5a(): ... +def sampleH5b(): ... +def sampleH5c1(): ... +def sampleH5c2(): ... +def sampleH5c3(): ... +def sampleH5c4(): ... +def sampleSymbol1(): ... +def sampleStacked1(): ... + +class SampleH5c4(Drawing): + def __init__(self, width: int = 400, height: int = 200, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi b/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi new file mode 100644 index 000000000000..d67fdfe982b9 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/dotbox.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class DotBox(Widget): + xlabels: Incomplete + ylabels: Incomplete + labelFontName: str + labelFontSize: int + labelOffset: int + strokeWidth: float + gridDivWidth: Incomplete + gridColor: Incomplete + dotDiameter: Incomplete + dotColor: Incomplete + dotXPosition: int + dotYPosition: int + x: int + y: int + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi b/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi new file mode 100644 index 000000000000..414bb8d5ae39 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/doughnut.pyi @@ -0,0 +1,35 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.piecharts import AbstractPieChart, WedgeProperties +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class SectorProperties(WedgeProperties): ... + +class Doughnut(AbstractPieChart): + x: int + y: int + width: int + height: int + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + simpleLabels: int + checkLabelOverlap: int + sideLabels: int + innerRadiusFraction: Incomplete + slices: Incomplete + angleRange: int + def __init__(self, *, angleRange: int = 360, **kwds) -> None: ... + def demo(self): ... + def normalizeData(self, data=None): ... + def makeSectors(self): ... + def draw(self): ... + +def sample1(): ... +def sample2(): ... +def sample3(): ... +def sample4(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/legends.pyi b/stubs/reportlab/reportlab/graphics/charts/legends.pyi new file mode 100644 index 000000000000..ec3b453fba10 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/legends.pyi @@ -0,0 +1,101 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import PropHolder, Widget +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class SubColProperty(PropHolder): + dividerLines: int + +class LegendCallout: + def __call__(self, legend, g, thisx, y, colName) -> None: ... + +class LegendSwatchCallout(LegendCallout): + def __call__(self, legend, g, thisx, y, i, colName, swatch) -> None: ... # type: ignore[override] + +class LegendColEndCallout(LegendCallout): + def __call__(self, legend, g, x, xt, y, width, lWidth) -> None: ... # type: ignore[override] + +class Legend(Widget): + x: int + y: int + alignment: str + deltax: int + deltay: int + autoXPadding: int + autoYPadding: int + dx: int + dy: int + swdx: int + swdy: int + dxTextSpace: int + columnMaximum: int + colorNamePairs: Incomplete + fontName: Incomplete + fontSize: Incomplete + leading: Incomplete + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: Incomplete + swatchMarker: Incomplete + boxAnchor: str + yGap: int + variColumn: int + dividerLines: int + dividerWidth: float + dividerDashArray: Incomplete + dividerColor: Incomplete + dividerOffsX: Incomplete + dividerOffsY: int + colEndCallout: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + def demo(self): ... + +class TotalAnnotator(LegendColEndCallout): + lText: Incomplete + rText: Incomplete + fontName: Incomplete + fontSize: Incomplete + fillColor: Incomplete + dy: Incomplete + dx: Incomplete + dly: Incomplete + dlx: Incomplete + strokeWidth: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + def __init__( + self, + lText: str = "Total", + rText: str = "0.0", + fontName="Times-Roman", + fontSize: int = 10, + fillColor=..., + strokeWidth: float = 0.5, + strokeColor=..., + strokeDashArray=None, + dx: int = 0, + dy: int = 0, + dly: int = 0, + dlx=(0, 0), + ) -> None: ... + def __call__(self, legend, g, x, xt, y, width, lWidth) -> None: ... # type: ignore[override] + +class LineSwatch(Widget): + x: int + y: int + width: int + height: int + strokeColor: Incomplete + strokeDashArray: Incomplete + strokeWidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class LineLegend(Legend): + dx: int + dy: int + def __init__(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi b/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi new file mode 100644 index 000000000000..16d1c4bf69e7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/linecharts.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class LineChartProperties(PropHolder): ... + +class AbstractLineChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + +class LineChart(AbstractLineChart): ... + +class HorizontalLineChart(LineChart): + strokeColor: Incomplete + fillColor: Incomplete + categoryAxis: Incomplete + valueAxis: Incomplete + data: Incomplete + categoryNames: Incomplete + lines: Incomplete + useAbsolute: int + groupSpacing: int + lineLabels: Incomplete + lineLabelFormat: Incomplete + lineLabelArray: Incomplete + lineLabelNudge: int + joinedLines: int + inFill: int + reversePlotOrder: int + def __init__(self) -> None: ... + def demo(self): ... + def calcPositions(self) -> None: ... + def drawLabel(self, G, rowNo, colNo, x, y) -> None: ... + def makeLines(self): ... + def draw(self): ... + +class _FakeGroup: + def __init__(self) -> None: ... + def add(self, what) -> None: ... + def value(self): ... + def sort(self) -> None: ... + +class HorizontalLineChart3D(HorizontalLineChart): + theta_x: float + theta_y: float + zDepth: int + zSpace: int + def calcPositions(self) -> None: ... + def makeLines(self): ... + +class VerticalLineChart(LineChart): ... + +def sample1(): ... + +class SampleHorizontalLineChart(HorizontalLineChart): + def demo(self): ... + def makeBackground(self): ... + +def sample1a(): ... +def sample2(): ... +def sample3(): ... +def sampleCandleStick(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi b/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi new file mode 100644 index 000000000000..77c6ad29d27d --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/lineplots.pyi @@ -0,0 +1,121 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.linecharts import AbstractLineChart +from reportlab.graphics.charts.utils import * +from reportlab.graphics.shapes import Polygon, _SetKeyWordArgs +from reportlab.graphics.widgetbase import PropHolder +from reportlab.graphics.widgets.grids import ShadedPolygon +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class LinePlotProperties(PropHolder): ... + +class InFillValue(int): + yValue: Incomplete + def __new__(cls, v, yValue=None): ... + +class Shader(_SetKeyWordArgs): + def shade(self, lp, g, rowNo, rowColor, row) -> None: ... + +class NoFiller: + def fill(self, lp, g, rowNo, rowColor, points) -> None: ... + +class Filler: + __dict__: Incomplete + def __init__(self, **kw) -> None: ... + def fill(self, lp, g, rowNo, rowColor, points) -> None: ... + +class ShadedPolyFiller(Filler, ShadedPolygon): ... +class PolyFiller(Filler, Polygon): ... + +class LinePlot(AbstractLineChart): + reversePlotOrder: int + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + lines: Incomplete + lineLabels: Incomplete + lineLabelFormat: Incomplete + lineLabelArray: Incomplete + lineLabelNudge: int + annotations: Incomplete + behindAxes: int + gridFirst: int + def __init__(self) -> None: ... + + @property + def joinedLines(self): ... + @joinedLines.setter + def joinedLines(self, v) -> None: ... + + def demo(self): ... + def calcPositions(self) -> None: ... + def drawLabel(self, G, rowNo, colNo, x, y) -> None: ... + def makeLines(self): ... + def draw(self): ... + def addCrossHair(self, name, xv, yv, strokeColor=..., strokeWidth: int = 1, beforeLines: bool = True): ... + +class LinePlot3D(LinePlot): + theta_x: float + theta_y: float + zDepth: int + zSpace: int + def calcPositions(self) -> None: ... + def makeLines(self): ... + +class SimpleTimeSeriesPlot(LinePlot): + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + def __init__(self) -> None: ... + +class GridLinePlot(SimpleTimeSeriesPlot): + scaleFactor: Incomplete + background: Incomplete + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... + +class AreaLinePlot(LinePlot): + reversePlotOrder: int + data: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class SplitLinePlot(AreaLinePlot): + xValueAxis: Incomplete + yValueAxis: Incomplete + data: Incomplete + def __init__(self) -> None: ... + +class ScatterPlot(LinePlot): + width: int + height: int + outerBorderOn: int + outerBorderColor: Incomplete + background: Incomplete + xLabel: str + yLabel: str + data: Incomplete + joinedLines: int + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + x: Incomplete + y: Incomplete + lineLabelFormat: str + lineLabelNudge: int + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... + +def sample1a(): ... +def sample1b(): ... +def sample1c(): ... +def preprocessData(series): ... +def sample2(): ... +def sampleFillPairedData(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/markers.pyi b/stubs/reportlab/reportlab/graphics/charts/markers.pyi new file mode 100644 index 000000000000..7c7c8a6750cd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/markers.pyi @@ -0,0 +1,10 @@ +from typing import Final + +__version__: Final[str] + +def makeEmptySquare(x, y, size, color): ... +def makeFilledSquare(x, y, size, color): ... +def makeFilledDiamond(x, y, size, color): ... +def makeEmptyCircle(x, y, size, color): ... +def makeFilledCircle(x, y, size, color): ... +def makeSmiley(x, y, size, color): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi b/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi new file mode 100644 index 000000000000..aa15c8d58846 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/piecharts.pyi @@ -0,0 +1,183 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.textlabels import Label +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class WedgeLabel(Label): ... + +class WedgeProperties(PropHolder): + strokeWidth: int + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + strokeLineJoin: int + strokeLineCap: int + strokeMiterLimit: int + popout: int + fontName: Incomplete + fontSize: Incomplete + fontColor: Incomplete + labelRadius: float + label_dx: int + label_text: Incomplete + label_topPadding: int + label_boxAnchor: str + label_boxStrokeColor: Incomplete + label_boxStrokeWidth: float + label_boxFillColor: Incomplete + label_strokeColor: Incomplete + label_strokeWidth: float + label_leading: Incomplete + label_textAnchor: str + label_simple_pointer: int + label_visible: int + label_pointer_strokeColor: Incomplete + label_pointer_strokeWidth: float + label_pointer_elbowLength: int + label_pointer_edgePad: int + label_pointer_piePad: int + visible: int + shadingKind: Incomplete + shadingAmount: float + shadingAngle: float + shadingDirection: str + def __init__(self) -> None: ... + +class AbstractPieChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + +def boundsOverlap(P, Q): ... +def findOverlapRun(B, wrap: int = 1): ... +def fixLabelOverlaps(L, sideLabels: bool = False, mult0: float = 1.0) -> None: ... +def intervalIntersection(A, B): ... +def theta0(data, direction): ... + +class AngleData(float): + def __new__(cls, angle, data): ... + +class Pie(AbstractPieChart): + other_threshold: Incomplete + x: int + y: int + width: int + height: int + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + simpleLabels: int + checkLabelOverlap: int + pointerLabelMode: Incomplete + sameRadii: bool + orderMode: str + xradius: Incomplete + sideLabels: int + sideLabelsOffset: float + slices: Incomplete + angleRange: int + def __init__(self, *, angleRange: int = 360, **kwds) -> None: ... + def demo(self): ... + centerx: Incomplete + centery: Incomplete + yradius: Incomplete + lu: Incomplete + ru: Incomplete + def makePointerLabels(self, angles, plMode): ... + def normalizeData(self, keepData: bool = False): ... + def makeAngles(self): ... + def makeWedges(self): ... + def draw(self): ... + +class LegendedPie(Pie): + x: int + y: int + height: int + width: int + data: Incomplete + labels: Incomplete + direction: str + pieAndLegend_colors: Incomplete + legendNumberOffset: int + legendNumberFormat: str + legend_data: Incomplete + legend1: Incomplete + legend_names: Incomplete + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + drawLegend: int + def __init__(self) -> None: ... + def draw(self): ... + def demo(self, drawing=None): ... + +class Wedge3dProperties(PropHolder): + strokeWidth: int + shading: float + visible: int + strokeColorShaded: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + popout: int + fontName: Incomplete + fontSize: Incomplete + fontColor: Incomplete + labelRadius: float + label_dx: int + label_text: Incomplete + label_topPadding: int + label_boxAnchor: str + label_boxStrokeColor: Incomplete + label_boxStrokeWidth: float + label_boxFillColor: Incomplete + label_strokeColor: Incomplete + label_strokeWidth: float + label_leading: Incomplete + label_textAnchor: str + label_visible: int + label_simple_pointer: int + def __init__(self) -> None: ... + +class _SL3D: + lo: Incomplete + hi: Incomplete + mid: Incomplete + not360: Incomplete + def __init__(self, lo, hi) -> None: ... + +class Pie3d(Pie): + perspective: int + depth_3d: int + angle_3d: int + def CX(self, i, d): ... + def CY(self, i, d): ... + def OX(self, i, o, d): ... + def OY(self, i, o, d): ... + def rad_dist(self, a): ... + slices: Incomplete + xradius: Incomplete + width: int + height: int + data: Incomplete + def __init__(self) -> None: ... + dy: Incomplete + def draw(self): ... + def demo(self): ... + +def sample0a(): ... +def sample0b(): ... +def sample1(): ... +def sample2(): ... +def sample3(): ... +def sample4(): ... +def sample5(): ... +def sample6(): ... +def sample7(): ... +def sample8(): ... +def sample9(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi b/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi new file mode 100644 index 000000000000..5af8e999ae03 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/slidebox.pyi @@ -0,0 +1,38 @@ +from _typeshed import Incomplete + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class SlideBox(Widget): + labelFontName: str + labelFontSize: int + labelStrokeColor: Incomplete + labelFillColor: Incomplete + startColor: Incomplete + endColor: Incomplete + numberOfBoxes: int + trianglePosition: int + triangleHeight: Incomplete + triangleWidth: Incomplete + triangleFillColor: Incomplete + triangleStrokeColor: Incomplete + triangleStrokeWidth: float + boxHeight: Incomplete + boxWidth: Incomplete + boxSpacing: Incomplete + boxOutlineColor: Incomplete + boxOutlineWidth: float + leftPadding: int + rightPadding: int + topPadding: int + bottomPadding: int + background: Incomplete + sourceLabelText: str + sourceLabelOffset: Incomplete + sourceLabelFontName: str + sourceLabelFontSize: int + sourceLabelFillColor: Incomplete + def __init__(self) -> None: ... + def demo(self, drawing=None): ... + def draw(self): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/spider.pyi b/stubs/reportlab/reportlab/graphics/charts/spider.pyi new file mode 100644 index 000000000000..e66e11bb7e8a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/spider.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.areas import PlotArea +from reportlab.graphics.charts.piecharts import WedgeLabel +from reportlab.graphics.widgetbase import PropHolder +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class StrandProperty(PropHolder): + strokeWidth: int + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + symbol: Incomplete + symbolSize: int + name: Incomplete + def __init__(self) -> None: ... + +class SpokeProperty(PropHolder): + strokeWidth: float + fillColor: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + visible: int + labelRadius: float + def __init__(self, **kw) -> None: ... + +class SpokeLabel(WedgeLabel): + def __init__(self, **kw) -> None: ... + +class StrandLabel(SpokeLabel): + format: str + dR: int + def __init__(self, **kw) -> None: ... + +class SpiderChart(PlotArea): + def makeSwatchSample(self, rowNo, x, y, width, height): ... + def getSeriesName(self, i, default=None): ... + data: Incomplete + labels: Incomplete + startAngle: int + direction: str + strands: Incomplete + spokes: Incomplete + spokeLabels: Incomplete + strandLabels: Incomplete + x: int + y: int + width: int + height: int + def __init__(self) -> None: ... + def demo(self): ... + def normalizeData(self, outer: float = 0.0): ... + def labelClass(self, kind): ... + def draw(self): ... + +def sample1(): ... +def sample2(): ... diff --git a/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi b/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi new file mode 100644 index 000000000000..c7b4fa1bc0d5 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/textlabels.pyi @@ -0,0 +1,68 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.charts.utils import CustomDrawChanger +from reportlab.graphics.shapes import Drawing, Group +from reportlab.graphics.widgetbase import PropHolder, Widget +from reportlab.lib.attrmap import * + +__version__: Final[str] + +class Label(Widget): + # TODO: This has more attributes. + x: Incomplete + y: Incomplete + def __init__(self, **kw) -> None: ... + + @property + def padding(self): ... + @padding.setter + def padding(self, p) -> None: ... + + def setText(self, text) -> None: ... + def setOrigin(self, x, y) -> None: ... + def demo(self) -> Drawing: ... + def computeSize(self) -> None: ... + def draw(self) -> Group: ... + +class LabelDecorator: + textAnchor: str + boxAnchor: str + def __init__(self) -> None: ... + def decorate(self, l, L) -> None: ... + def __call__(self, l) -> None: ... + +isOffsetMode: Incomplete + +class LabelOffset(PropHolder): + posMode: str + pos: int + def __init__(self) -> None: ... + +NoneOrInstanceOfLabelOffset: Incomplete + +class PMVLabel(Label): + def __init__(self, **kwds) -> None: ... + +class BarChartLabel(PMVLabel): + lineStrokeWidth: int + lineStrokeColor: Incomplete + fixedStart: Incomplete + nudge: int + def __init__(self, **kwds) -> None: ... + +class NA_Label(BarChartLabel): + text: str + def __init__(self) -> None: ... + +NoneOrInstanceOfNA_Label: Incomplete + +class RedNegativeChanger(CustomDrawChanger): + fillColor: Incomplete + def __init__(self, fillColor=...) -> None: ... + +class XLabel(Label): + ddfKlass: Incomplete + ddf: Incomplete + def __init__(self, *args, **kwds) -> None: ... + def computeSize(self) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/utils.pyi b/stubs/reportlab/reportlab/graphics/charts/utils.pyi new file mode 100644 index 000000000000..5139374047ea --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/utils.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from typing import Final, Literal + +__all__ = ( + "angle2corner", + "angle2dir", + "boxCornerCoords", + "CustomDrawChanger", + "DrawTimeCollector", + "FillPairedData", + "find_good_grid", + "find_interval", + "findNones", + "lineSegmentIntersect", + "makeCircularString", + "maverage", + "mkTimeTuple", + "nextRoundNumber", + "pairFixNones", + "pairMaverage", + "seconds2str", + "str2seconds", + "ticks", + "xyDist", +) +__version__: Final[str] + +def mkTimeTuple(timeString): ... +def str2seconds(timeString): ... +def seconds2str(seconds): ... +def nextRoundNumber(x): ... +def find_interval(lo, hi, I: int = 5): ... +def find_good_grid(lower, upper, n=(4, 5, 6, 7, 8, 9), grid=None): ... +def ticks(lower, upper, n=(4, 5, 6, 7, 8, 9), split: int = 1, percent: int = 0, grid=None, labelVOffset: int = 0): ... +def findNones(data): ... +def pairFixNones(pairs): ... +def maverage(data, n: int = 6): ... +def pairMaverage(data, n: int = 6): ... + +class DrawTimeCollector: + formats: Incomplete + disabled: bool + def __init__(self, formats=["gif"]) -> None: ... + def clear(self) -> None: ... + def record(self, func, node, *args, **kwds) -> None: ... + def __call__(self, node, canvas, renderer) -> None: ... + @staticmethod + def rectDrawTimeCallback(node, canvas, renderer, **kwds): ... + @staticmethod + def transformAndFlatten(A, p): ... + @property + def pmcanv(self): ... + def wedgeDrawTimeCallback(self, node, canvas, renderer, **kwds): ... + def save(self, fnroot) -> None: ... + +def xyDist(xxx_todo_changeme, xxx_todo_changeme1): ... +def lineSegmentIntersect(xxx_todo_changeme2, xxx_todo_changeme3, xxx_todo_changeme4, xxx_todo_changeme5): ... +def makeCircularString(x, y, radius, angle, text, fontName, fontSize, inside: int = 0, G=None, textAnchor: str = "start"): ... + +class CustomDrawChanger: + store: Incomplete + def __init__(self) -> None: ... + def __call__(self, change, obj) -> None: ... + +class FillPairedData(list[Incomplete]): + other: Incomplete + def __init__(self, v, other: int = 0) -> None: ... + +def angle2dir(angle: float) -> Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]: ... +def angle2corner(angle: float) -> Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]: ... +def boxCornerCoords(bb: Sequence[float], cn: Literal["n", "ne", "e", "se", "s", "sw", "w", "nw", "c"]) -> tuple[float, float]: ... diff --git a/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi b/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi new file mode 100644 index 000000000000..c54c9e087c1b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/charts/utils3d.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete + +class _YStrip: + y0: Incomplete + y1: Incomplete + slope: Incomplete + fillColor: Incomplete + fillColorShaded: Incomplete + def __init__(self, y0, y1, slope, fillColor, fillColorShaded, shading: float = 0.1) -> None: ... + +def mod_2pi(radians): ... + +class _Segment: + a: Incomplete + b: Incomplete + x0: Incomplete + x1: Incomplete + y0: Incomplete + y1: Incomplete + series: Incomplete + i: Incomplete + s: Incomplete + def __init__(self, s, i, data) -> None: ... + def intersect(self, o, I): ... + +def find_intersections(data, small: int = 0): ... diff --git a/stubs/reportlab/reportlab/graphics/renderPDF.pyi b/stubs/reportlab/reportlab/graphics/renderPDF.pyi new file mode 100644 index 000000000000..382d054f9f63 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPDF.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus import Flowable + +__version__: Final[str] + +def draw(drawing: Drawing, canvas: Canvas, x: float, y: float, showBoundary=...) -> None: ... + +class _PDFRenderer(Renderer): + def __init__(self) -> None: ... + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawImage(self, image) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, polyline) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, polygon) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path) -> None: ... + def setStrokeColor(self, c) -> None: ... + def setFillColor(self, c) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + +class GraphicsFlowable(Flowable): + drawing: Incomplete + width: Incomplete + height: Incomplete + def __init__(self, drawing) -> None: ... + def draw(self) -> None: ... + +def drawToFile(d: Drawing, fn: str | IO[bytes], msg: str = "", showBoundary=..., autoSize: int = 1, **kwds) -> None: ... +def drawToString(d: Drawing, msg: str = "", showBoundary=..., autoSize: int = 1, **kwds) -> str: ... +def test(outDir: str = "pdfout", shout: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderPM.pyi b/stubs/reportlab/reportlab/graphics/renderPM.pyi new file mode 100644 index 000000000000..68833ea9da95 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPM.pyi @@ -0,0 +1,132 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +__version__: Final[str] + +def Color2Hex(c): ... +def CairoColor(c): ... +def draw(drawing: Drawing, canvas: Canvas, x: float, y: float, showBoundary=...) -> None: ... + +class _PMRenderer(Renderer): + def pop(self) -> None: ... + def push(self, node) -> None: ... + def applyState(self) -> None: ... + def initState(self, x, y) -> None: ... + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawImage(self, image) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, polyline, _doClose: int = 0) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, polygon) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path): ... + +BEZIER_ARC_MAGIC: float + +class PMCanvas: + ctm: Incomplete + def __init__( + self, w, h, dpi: int = 72, bg: int = 16777215, configPIL=None, backend=None, backendFmt: str = "RGB" + ) -> None: ... + def toPIL(self): ... + def saveToFile(self, fn, fmt=None): ... + def saveToString(self, fmt: str = "GIF"): ... + def setFont(self, fontName, fontSize, leading=None) -> None: ... + def __setattr__(self, name, value) -> None: ... + def __getattr__(self, name): ... + def fillstrokepath(self, stroke: int = 1, fill: int = 1) -> None: ... + def bezierArcCCW(self, cx, cy, rx, ry, theta0, theta1): ... + def addEllipsoidalArc(self, cx, cy, rx, ry, ang1, ang2) -> None: ... + def drawCentredString( + self, x: float, y: float, text: str, text_anchor: str = "middle", direction: str | None = None, shaping: bool = False + ) -> None: ... + def drawRightString(self, text: str, x: float, y: float, direction: str | None = None) -> None: ... + def drawString( + self, + x: float, + y: float, + text: str, + _fontInfo=None, + text_anchor: str = "left", + direction: str | None = None, + shaping: bool = False, + ) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def rect(self, x, y, width, height, stroke: int = 1, fill: int = 1) -> None: ... + def roundRect(self, x, y, width, height, rx, ry) -> None: ... + def circle(self, cx, cy, r) -> None: ... + def ellipse(self, cx, cy, rx, ry) -> None: ... + def saveState(self) -> None: ... + fillColor: Incomplete + fillOpacity: Incomplete + def setFillColor(self, aColor) -> None: ... + strokeColor: Incomplete + strokeOpacity: Incomplete + def setStrokeColor(self, aColor) -> None: ... + restoreState = saveState + lineCap: Incomplete + def setLineCap(self, cap) -> None: ... + lineJoin: Incomplete + def setLineJoin(self, join) -> None: ... + strokeWidth: Incomplete + def setLineWidth(self, width) -> None: ... + def stringWidth(self, text, fontName=None, fontSize=None): ... + +def drawToPMCanvas( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToPIL( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToPILP( + d: Drawing, + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +): ... +def drawToFile( + d: Drawing, + fn: str | IO[bytes], + fmt: str = "GIF", + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +) -> None: ... +def drawToString( + d: Drawing, + fmt: str = "GIF", + dpi: float = 72, + bg: int = 0xFFFFFF, + configPIL=None, + showBoundary=..., + backend="rlPyCairo", + backendFmt: str = "RGB", +) -> str: ... + +save = drawToFile + +def test(outDir: str = "pmout", shout: bool = False): ... diff --git a/stubs/reportlab/reportlab/graphics/renderPS.pyi b/stubs/reportlab/reportlab/graphics/renderPS.pyi new file mode 100644 index 000000000000..f7e47c5af40e --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderPS.pyi @@ -0,0 +1,73 @@ +from _typeshed import Incomplete +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +__version__: Final[str] +PS_WinAnsiEncoding: Final[str] + +class PSCanvas: + comments: int + code: Incomplete + code_append: Incomplete + PostScriptLevel: Incomplete + def __init__(self, size=(300, 300), PostScriptLevel: int = 2) -> None: ... + def comment(self, msg) -> None: ... + def drawImage(self, image, x1, y1, width=None, height=None) -> None: ... + def clear(self) -> None: ... + def save(self, f=None) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + def stringWidth(self, s, font=None, fontSize=None): ... + def setLineCap(self, v) -> None: ... + def setLineJoin(self, v) -> None: ... + def setDash(self, array=[], phase: int = 0) -> None: ... + def setStrokeColor(self, color) -> None: ... + def setColor(self, color) -> None: ... + def setFillColor(self, color) -> None: ... + def setFillMode(self, v) -> None: ... + def setLineWidth(self, width) -> None: ... + def setFont(self, font, fontSize, leading=None) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def drawString(self, x, y, s, angle: int = 0, text_anchor: str = "left", textRenderMode: int = 0) -> None: ... + def drawCentredString(self, x, y, text, text_anchor: str = "middle", textRenderMode: int = 0) -> None: ... + def drawRightString(self, text, x, y, text_anchor: str = "end", textRenderMode: int = 0) -> None: ... + def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed: int = 0) -> None: ... + def rect(self, x1, y1, x2, y2, stroke: int = 1, fill: int = 1) -> None: ... + def roundRect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8) -> None: ... + def ellipse(self, x1, y1, x2, y2) -> None: ... + def circle(self, xc, yc, r) -> None: ... + def drawArc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 360, fromcenter: int = 0) -> None: ... + def polygon(self, p, closed: int = 0, stroke: int = 1, fill: int = 1) -> None: ... + def lines(self, lineList, color=None, width=None) -> None: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def closePath(self) -> None: ... + def polyLine(self, p) -> None: ... + def drawFigure(self, partList, closed: int = 0) -> None: ... + def translate(self, x, y) -> None: ... + def scale(self, x, y) -> None: ... + def transform(self, a, b, c, d, e, f) -> None: ... + +def draw(drawing: Drawing, canvas: Canvas, x: float = 0, y: float = 0, showBoundary=0) -> None: ... + +class _PSRenderer(Renderer): + def drawNode(self, node) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawPath(self, path, fillMode=None): ... + def applyStateChanges(self, delta, newState) -> None: ... + def drawImage(self, image) -> None: ... + +def drawToFile(d: Drawing, fn: IO[bytes], showBoundary=0, **kwd) -> None: ... +def drawToString(d: Drawing, showBoundary=0) -> str: ... +def test(outDir: str = "epsout", shout: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderSVG.pyi b/stubs/reportlab/reportlab/graphics/renderSVG.pyi new file mode 100644 index 000000000000..b9611dad4138 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderSVG.pyi @@ -0,0 +1,107 @@ +from _typeshed import Incomplete +from collections.abc import Sequence +from math import cos as cos, pi as pi, sin as sin +from typing import IO, Final + +from reportlab.graphics.renderbase import Renderer +from reportlab.graphics.shapes import Drawing +from reportlab.pdfgen.canvas import Canvas + +AREA_STYLES: Final[Sequence[str]] +LINE_STYLES: Final[Sequence[str]] +TEXT_STYLES: Final[Sequence[str]] +EXTRA_STROKE_STYLES: Final[Sequence[str]] +EXTRA_FILL_STYLES: Final[Sequence[str]] + +def drawToString(d: Drawing, showBoundary=0, **kwds) -> str: ... +def drawToFile(d: Drawing, fn: str | IO[str], showBoundary=0, **kwds) -> None: ... +def draw(drawing: Drawing, canvas: Canvas, x: float = 0, y: float = 0, showBoundary=0) -> None: ... +def transformNode(doc, newTag, node=None, **attrDict): ... + +class EncodedWriter(list[Incomplete]): + BOMS: Incomplete + encoding: Incomplete + def __init__(self, encoding, bom: bool = False) -> None: ... + def write(self, u) -> None: ... + def getvalue(self): ... + +def py_fp_str(*args): ... + +class SVGCanvas: + verbose: Incomplete + encoding: Incomplete + bom: Incomplete + fontHacks: Incomplete + extraXmlDecl: Incomplete + code: Incomplete + style: Incomplete + path: str + fp_str: Incomplete + cfp_str: Incomplete + doc: Incomplete + svg: Incomplete + groupTree: Incomplete + scaleTree: Incomplete + currGroup: Incomplete + def __init__(self, size=(300, 300), encoding: str = "utf-8", verbose: int = 0, bom: bool = False, **kwds) -> None: ... + def save(self, fn=None) -> None: ... + def NOTUSED_stringWidth(self, s, font=None, fontSize=None): ... + def setLineCap(self, v) -> None: ... + def setLineJoin(self, v) -> None: ... + def setDash(self, array=[], phase: int = 0) -> None: ... + def setStrokeColor(self, color) -> None: ... + def setFillColor(self, color) -> None: ... + def setFillMode(self, v) -> None: ... + def setLineWidth(self, width) -> None: ... + def setFont(self, font, fontSize) -> None: ... + def rect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8, link_info=None, **_svgAttrs) -> None: ... + def roundRect(self, x1, y1, x2, y2, rx: int = 8, ry: int = 8, link_info=None, **_svgAttrs) -> None: ... + def drawString( + self, s, x, y, angle: int = 0, link_info=None, text_anchor: str = "left", textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def drawCentredString( + self, s, x, y, angle: int = 0, text_anchor: str = "middle", link_info=None, textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def drawRightString( + self, text, x, y, angle: int = 0, text_anchor: str = "end", link_info=None, textRenderMode: int = 0, **_svgAttrs + ) -> None: ... + def comment(self, data) -> None: ... + def drawImage(self, image, x, y, width, height, embed: bool = True) -> None: ... + def line(self, x1, y1, x2, y2) -> None: ... + def ellipse(self, x1, y1, x2, y2, link_info=None) -> None: ... + def circle(self, xc, yc, r, link_info=None) -> None: ... + def drawCurve(self, x1, y1, x2, y2, x3, y3, x4, y4, closed: int = 0) -> None: ... + def drawArc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 360, fromcenter: int = 0) -> None: ... + def polygon(self, points, closed: int = 0, link_info=None) -> None: ... + def lines(self, lineList, color=None, width=None) -> None: ... + def polyLine(self, points) -> None: ... + def startGroup(self, attrDict={"transform": ""}): ... + def endGroup(self, currGroup) -> None: ... + def transform(self, a, b, c, d, e, f) -> None: ... + def translate(self, x, y) -> None: ... + def scale(self, sx, sy) -> None: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def closePath(self) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + +class _SVGRenderer(Renderer): + verbose: int + def __init__(self) -> None: ... + def drawNode(self, node) -> None: ... + def drawGroup(self, group) -> None: ... + def drawRect(self, rect) -> None: ... + def drawString(self, stringObj) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawPath(self, path, fillMode=0): ... + def drawImage(self, image) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + +def test(outDir: str = "out-svg") -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/renderbase.pyi b/stubs/reportlab/reportlab/graphics/renderbase.pyi new file mode 100644 index 000000000000..e9d04c948872 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/renderbase.pyi @@ -0,0 +1,39 @@ +from typing import Final + +__version__: Final[str] + +def getStateDelta(shape): ... + +class StateTracker: + def __init__(self, defaults=None, defaultObj=None) -> None: ... + def push(self, delta) -> None: ... + def pop(self): ... + def getState(self): ... + def getCTM(self): ... + def __getitem__(self, key): ... + def __setitem__(self, key, value) -> None: ... + +def testStateTracker() -> None: ... +def renderScaledDrawing(d): ... + +class Renderer: + def undefined(self, operation) -> None: ... + def draw(self, drawing, canvas, x: int = 0, y: int = 0, showBoundary=...) -> None: ... + def initState(self, x, y) -> None: ... + def pop(self) -> None: ... + def drawNode(self, node) -> None: ... + def getStateValue(self, key): ... + def fillDerivedValues(self, node) -> None: ... + def drawNodeDispatcher(self, anode) -> None: ... + def drawGroup(self, group) -> None: ... + def drawWedge(self, wedge) -> None: ... + def drawPath(self, path) -> None: ... + def drawRect(self, rect) -> None: ... + def drawLine(self, line) -> None: ... + def drawCircle(self, circle) -> None: ... + def drawPolyLine(self, p) -> None: ... + def drawEllipse(self, ellipse) -> None: ... + def drawPolygon(self, p) -> None: ... + def drawString(self, stringObj) -> None: ... + def applyStateChanges(self, delta, newState) -> None: ... + def drawImage(self, *args, **kwds) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/__init__.pyi b/stubs/reportlab/reportlab/graphics/samples/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/reportlab/reportlab/graphics/samples/bubble.pyi b/stubs/reportlab/reportlab/graphics/samples/bubble.pyi new file mode 100644 index 000000000000..c3498e0da7b7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/bubble.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class Bubble(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi b/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi new file mode 100644 index 000000000000..92c971a781db --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/clustered_bar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ClusteredBar(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi b/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi new file mode 100644 index 000000000000..e63bc6a30e89 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/clustered_column.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ClusteredColumn(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi b/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi new file mode 100644 index 000000000000..daf8c0fb4e90 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/excelcolors.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete + +color01: Incomplete +color02: Incomplete +color03: Incomplete +color04: Incomplete +color05: Incomplete +color06: Incomplete +color07: Incomplete +color08: Incomplete +color09: Incomplete +color10: Incomplete +color01Light: Incomplete +color02Light: Incomplete +color03Light: Incomplete +color04Light: Incomplete +color05Light: Incomplete +color06Light: Incomplete +color07Light: Incomplete +color08Light: Incomplete +color09Light: Incomplete +color10Light: Incomplete +color01Dark: Incomplete +color02Dark: Incomplete +color03Dark: Incomplete +color04Dark: Incomplete +color05Dark: Incomplete +color06Dark: Incomplete +color07Dark: Incomplete +color08Dark: Incomplete +color09Dark: Incomplete +color10Dark: Incomplete +backgroundGrey: Incomplete diff --git a/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi b/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi new file mode 100644 index 000000000000..7421505c19bd --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/exploded_pie.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ExplodedPie(_DrawingEditorMixin, Drawing): + background: Incomplete + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi b/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi new file mode 100644 index 000000000000..f0032bdf91aa --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/filled_radar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class FilledRadarChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi b/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi new file mode 100644 index 000000000000..fa026e6cc4c9 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/line_chart.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class LineChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi b/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi new file mode 100644 index 000000000000..0be656dabf2c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/linechart_with_markers.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class LineChartWithMarkers(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/radar.pyi b/stubs/reportlab/reportlab/graphics/samples/radar.pyi new file mode 100644 index 000000000000..483c55c9ee2a --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/radar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class RadarChart(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/runall.pyi b/stubs/reportlab/reportlab/graphics/samples/runall.pyi new file mode 100644 index 000000000000..983f8c55d094 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/runall.pyi @@ -0,0 +1,3 @@ +def moduleClasses(mod): ... +def getclass(f): ... +def run(format, VERBOSE: int = 0) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter.pyi new file mode 100644 index 000000000000..dd2df0cd8fdc --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class Scatter(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi new file mode 100644 index 000000000000..708223a0dbbc --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter_lines.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ScatterLines(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi b/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi new file mode 100644 index 000000000000..b7c25c476a21 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/scatter_lines_markers.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class ScatterLinesMarkers(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi b/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi new file mode 100644 index 000000000000..9b01626f09e3 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/simple_pie.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete + +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class SimplePie(_DrawingEditorMixin, Drawing): + background: Incomplete + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi b/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi new file mode 100644 index 000000000000..2ee3aed65a88 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/stacked_bar.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class StackedBar(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi b/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi new file mode 100644 index 000000000000..f3b47c2c437c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/samples/stacked_column.pyi @@ -0,0 +1,5 @@ +from reportlab.graphics.samples.excelcolors import * +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin + +class StackedColumn(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 200, height: int = 150, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/shapes.pyi b/stubs/reportlab/reportlab/graphics/shapes.pyi new file mode 100644 index 000000000000..123a551ddc2e --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/shapes.pyi @@ -0,0 +1,381 @@ +from _typeshed import Incomplete, SupportsItems +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import Any, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never, Self, Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.validators import NoneOr, Validator +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus import Flowable +from reportlab.platypus.flowables import _HAlignment, _VAlignment + +_IntBool: TypeAlias = Literal[0, 1] +_BoolLike: TypeAlias = _IntBool | bool +_PathOp: TypeAlias = ( + tuple[Literal["moveTo"], float, float] + | tuple[Literal["lineTo"], float, float] + | tuple[Literal["curveTo"], float, float, float, float, float, float] + # close path may either be a tuple or just the string + | Literal["closePath"] + | tuple[Literal["closePath"]] + # fallback for list that is not type safe + | list[Any] +) + +# NOTE: These are derived from _attrMap and can optionally be +# verified at runtime +@type_check_only +class _GroupKwArgs(TypedDict, total=False): + transform: tuple[float, float, float, float, float, float] | list[float] | list[int] + # NOTE: This should be used with care, since it will replace elements + # it's mostly useful for circumventing validation logic and + # reusing the list, rather than populating a new list + contents: list[Shape] + strokeOverprint: _BoolLike + fillOverprint: _BoolLike + overprintMask: _BoolLike + +@type_check_only +class _DrawingKwArgs(_GroupKwArgs, total=False): + # TODO: Restrict to supported formats? + formats: list[str] | tuple[str, ...] + # NOTE: This looks like an implementation detail, so we may not + # want to include this in KwArgs + canv: Canvas + background: Shape | UserNode | None + # NOTE: The runtime validation for alignments is incorrect, so + # we assume it is turned off and allow all valid values + hAlign: _HAlignment + vAlign: _VAlignment + renderScale: float + initialFontName: str | None + initialFontSize: float | None + +@type_check_only +class _LineShapeKwArgs(TypedDict, total=False): + strokeColor: Color | None + strokeWidth: float + strokeLineCap: Literal[0, 1, 2] + strokeLineJoin: Literal[0, 1, 2] + strokeMiterLimit: float + strokeDashArray: Sequence[float] | tuple[float, Sequence[float]] + strokeOpacity: float | None + strokeOverprint: _BoolLike + overprintMask: _BoolLike + +@type_check_only +class _PathKwArgs(_LineShapeKwArgs, total=False): + fillColor: Color | None + fillOpacity: float + fillOverprint: _BoolLike + +@type_check_only +class _AllPathKwArgs(_PathKwArgs, total=False): + points: list[float] | None + operators: list[float] | None + isClipPath: _BoolLike + autoclose: Literal["svg", "pdf"] | None + fillMode: Literal[0, 1] + +@type_check_only +class _SolidShapeKwArgs(_PathKwArgs, total=False): + fillMode: Literal[0, 1] + +@type_check_only +class _DefinePathKwArgs(_SolidShapeKwArgs, total=False): + autoclose: Literal["svg", "pdf"] | None + bbox: tuple[float, float, float, float] | None + +@type_check_only +class _WedgeKwArgs(_SolidShapeKwArgs, total=False): + radius1: float | None + yradius1: float | None + +@type_check_only +class _StringKwArgs(TypedDict, total=False): + fontName: str + fontSize: float + fillColor: Color | None + textAnchor: Literal["start", "middle", "end", "numeric"] + encoding: str + textRenderMode: Literal[0, 1, 2, 3, 4, 5, 6, 7] + +__version__: Final[str] +isOpacity: NoneOr +NON_ZERO_WINDING: Final[str] +EVEN_ODD: Final[str] +STATE_DEFAULTS: Final[Incomplete] + +class _DrawTimeResizeable: ... + +class _SetKeyWordArgs: + def __init__(self, keywords: SupportsItems[str, Any] = {}) -> None: ... + +def getRectsBounds(rectList): ... +def getPathBounds(points): ... +def getPointsBounds(pointList): ... + +class Shape(_SetKeyWordArgs, _DrawTimeResizeable): + @abstractmethod + def copy(self) -> Self: ... + def getProperties(self, recur: int = 1) -> dict[str, Any]: ... + def setProperties(self, props) -> None: ... + def dumpProperties(self, prefix: str = "") -> None: ... + def verify(self) -> None: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Group(Shape): + contents: list[Shape] + transform: tuple[float, float, float, float, float, float] | list[float] | list[int] + def __init__(self, *elements: Shape | UserNode, **keywords: Unpack[_GroupKwArgs]) -> None: ... + def add(self, node: Shape | UserNode, name: str | None = None) -> None: ... + def insert(self, i: int, n: Shape | UserNode, name: str | None = None) -> None: ... + def expandUserNodes(self) -> Group: ... + def copy(self) -> Self: ... + def rotate(self, theta: float, cx: float = 0, cy: float = 0) -> None: ... + def translate(self, dx: float, dy: float = 0) -> None: ... + def scale(self, sx: float, sy: float = 1) -> None: ... + def skew(self, kx: float, ky: float = 0) -> None: ... + def shift(self, x: float, y: float = 0) -> None: ... + # NOTE: This changes the object to a Drawing, rather than returning + # a new one, which is not ideal... + def asDrawing(self, width: float, height: float) -> None: ... + def getContents(self) -> list[Shape | UserNode]: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Drawing(Group, Flowable): + background: Shape | UserNode | None + renderScale: float + def __init__( + self, width: float = 400, height: float = 200, *nodes: Shape | UserNode, **keywords: Unpack[_DrawingKwArgs] + ) -> None: ... + def draw(self, showBoundary=...) -> None: ... + def expandUserNodes(self) -> Drawing: ... + def asGroup(self, *args: Shape | UserNode, **kw: Unpack[_GroupKwArgs]) -> Group: ... + def save( + self, + formats: Iterable[str] | None = None, + verbose: bool | None = None, + fnRoot: str | None = None, + outDir: str | None = None, + title: str = "", + **kw, + ): ... + def asString(self, format: str, verbose: bool | None = None, preview: int = 0, **kw) -> str: ... + def resized( + self, kind: Literal["fit", "fitx", "fity"] = "fit", lpad: float = 0, rpad: float = 0, bpad: float = 0, tpad: float = 0 + ) -> Drawing: ... + +class _DrawingEditorMixin: ... + +@type_check_only +class _isStrokeDashArray(Validator): + def test(self, x): ... + +isStrokeDashArray: _isStrokeDashArray + +class LineShape(Shape): + strokeColor: Color | None + strokeWidth: float + strokeLineCap: Literal[0, 1, 2] + strokeLineJoin: Literal[0, 1, 2] + strokeMiterLimit: float + strokeDashArray: Sequence[float] | tuple[float, Sequence[float]] + strokeOpacity: float | None + def __init__(self, kw: _LineShapeKwArgs) -> None: ... + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Line(LineShape): + x1: float + y1: float + x2: float + y2: float + def __init__(self, x1: float, y1: float, x2: float, y2: float, **kw: Unpack[_LineShapeKwArgs]) -> None: ... + # NOTE: For some reason Line doesn't implement copy + def copy(self) -> Never: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class SolidShape(LineShape): + fillColor: Color | None + fillOpacity: float | None + def __init__(self, kw: _SolidShapeKwArgs) -> None: ... + @abstractmethod + def copy(self) -> Self: ... + @abstractmethod + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Path(SolidShape): + points: list[float] + operators: list[float] + isClipPath: _BoolLike + autoclose: Literal["svg", "pdf"] | None + fillMode: Literal[0, 1] + def __init__( + self, + points: list[float] | None = None, + operators: list[float] | None = None, + isClipPath: _BoolLike = 0, + autoclose: Literal["svg", "pdf"] | None = None, + fillMode: Literal[0, 1] = 0, + **kw: Unpack[_PathKwArgs], + ) -> None: ... + def copy(self) -> Self: ... + def moveTo(self, x: float, y: float) -> None: ... + def lineTo(self, x: float, y: float) -> None: ... + def curveTo(self, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float) -> None: ... + def closePath(self) -> None: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +EmptyClipPath: Final[Path] + +def getArcPoints( + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + degreedelta: float | None = None, + reverse: _BoolLike | None = None, +) -> list[float]: ... + +class ArcPath(Path): + def addArc( + self, + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + degreedelta: float | None = None, + moveTo: _BoolLike | None = None, + reverse: _BoolLike | None = None, + ) -> None: ... + +def definePath( + pathSegs: Iterable[_PathOp] = [], isClipPath: _BoolLike = 0, dx: float = 0, dy: float = 0, **kw: Unpack[_DefinePathKwArgs] +) -> Path: ... + +class Rect(SolidShape): + x: float + y: float + width: float + height: float + rx: float + ry: float + def __init__( + self, x: float, y: float, width: float, height: float, rx: float = 0, ry: float = 0, **kw: _SolidShapeKwArgs + ) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Image(SolidShape): + x: float + y: float + width: float + height: float + path: Incomplete + def __init__(self, x: float, y: float, width: float, height: float, path, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Circle(SolidShape): + cx: float + cy: float + r: float + def __init__(self, cx: float, cy: float, r: float, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Ellipse(SolidShape): + cx: float + cy: float + rx: float + ry: float + def __init__(self, cx: float, cy: float, rx: float, ry: float, **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Wedge(SolidShape): + centerx: float + centery: float + radius: float + startangledegrees: float + endangledegrees: float + yradius: float | None + annular: bool + # NOTE: This one is not actually settable on the instance if runtime validation + # is turned on, but it seems bad to disallow it anyways + degreedelta: float + def __init__( + self, + centerx: float, + centery: float, + radius: float, + startangledegrees: float, + endangledegrees: float, + yradius: float | None = None, + annular: bool = False, + **kw: Unpack[_WedgeKwArgs], + ) -> None: ... + def asPolygon(self) -> Path | Polygon: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Polygon(SolidShape): + points: list[float] + def __init__(self, points: list[float] = [], **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class PolyLine(LineShape): + points: list[float] + def __init__(self, points: list[float] = [], **kw: Unpack[_SolidShapeKwArgs]) -> None: ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class Hatching(Path): + xyLists: Sequence[tuple[float, float]] + angles: Sequence[float] + spacings: Sequence[float] + def __init__( + self, + spacings: float | Sequence[float] = 2, + angles: float | Sequence[float] = 45, + xyLists: Sequence[tuple[float, float] | list[float]] = [], + **kwds: Unpack[_AllPathKwArgs], + ) -> None: ... + +def numericXShift( + tA, text: str, w: float, fontName: str, fontSize: float, encoding: str | None = None, pivotCharacter: str = "." +) -> float: ... + +class String(Shape): + encoding: str + x: float + y: float + text: str + textAnchor: Literal["start", "middle", "end", "numeric"] + fontName: str + fontSize: float + fillColor: Color | None + def __init__(self, x: float, y: float, text: str, **kw: Unpack[_StringKwArgs]) -> None: ... + def getEast(self): ... + def copy(self) -> Self: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class UserNode(_DrawTimeResizeable): + @abstractmethod + def provideNode(self) -> Shape: ... + +class DirectDraw(Shape): + @abstractmethod + def drawDirectly(self, canvas: Canvas) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/svgpath.pyi b/stubs/reportlab/reportlab/graphics/svgpath.pyi new file mode 100644 index 000000000000..1c8f62625f79 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/svgpath.pyi @@ -0,0 +1,10 @@ +from _typeshed import Incomplete + +from .shapes import Path, UserNode + +class SvgPath(Path, UserNode): + fillColor: Incomplete + def __init__(self, s, isClipPath: int = 0, autoclose=None, fillMode=0, **kw) -> None: ... + def provideNode(self): ... + +__all__ = ("SvgPath",) diff --git a/stubs/reportlab/reportlab/graphics/transform.pyi b/stubs/reportlab/reportlab/graphics/transform.pyi new file mode 100644 index 000000000000..820531addd22 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/transform.pyi @@ -0,0 +1,29 @@ +def nullTransform(): ... +def translate(dx: float, dy: float = 0): ... +def scale(sx: float, sy: float = 1): ... +def rotate(angle: float, cx: float = 0, cy: float = 0): ... +def skewX(angle: float): ... +def skewY(angle: float): ... +def mmult(A, B): ... +def combineTransforms(*T): ... +def inverse(A): ... +def zTransformPoint(A, v): ... +def transformPoint(A, v): ... +def transformPoints(matrix, V): ... +def zTransformPoints(matrix, V): ... + +__all__ = ( + "nullTransform", + "translate", + "scale", + "rotate", + "skewX", + "skewY", + "mmult", + "combineTransforms", + "inverse", + "zTransformPoint", + "transformPoint", + "transformPoints", + "zTransformPoints", +) diff --git a/stubs/reportlab/reportlab/graphics/utils.pyi b/stubs/reportlab/reportlab/graphics/utils.pyi new file mode 100644 index 000000000000..af61914c0058 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/utils.pyi @@ -0,0 +1,22 @@ +class RenderPMError(Exception): ... + +def setFont(gs, fontName, fontSize) -> None: ... +def pathNumTrunc(n): ... +def text2Path( + text, + x: int = 0, + y: int = 0, + fontName="Times-Roman", + fontSize: int = 1000, + anchor: str = "start", + truncate: int = 1, + pathReverse: int = 0, + gs=None, + **kwds, +): ... + +# NOTE: This only exists on some render backends +def processGlyph(G, truncate=1, pathReverse=0): ... +def text2PathDescription(text, x=0, y=0, fontName=..., fontSize=1000, anchor="start", truncate=1, pathReverse=0, gs=None): ... + +__all__ = ("setFont", "pathNumTrunc", "processGlyph", "text2PathDescription", "text2Path", "RenderPMError") diff --git a/stubs/reportlab/reportlab/graphics/widgetbase.pyi b/stubs/reportlab/reportlab/graphics/widgetbase.pyi new file mode 100644 index 000000000000..b937f01cc9e7 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgetbase.pyi @@ -0,0 +1,111 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics import shapes +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class PropHolder: + def verify(self) -> None: ... + def __setattr__(self, name, value) -> None: ... + def getProperties(self, recur: int = 1): ... + def setProperties(self, propDict) -> None: ... + def dumpProperties(self, prefix: str = "") -> None: ... + +class Widget(PropHolder, shapes.UserNode): + def draw(self): ... # abstract, but not marked as @abstractmethod + def demo(self): ... # abstract, but not marked as @abstractmethod + def provideNode(self) -> shapes.Shape: ... + def getBounds(self) -> tuple[float, float, float, float]: ... + +class ScaleWidget(Widget): + x: Incomplete + y: Incomplete + contents: Incomplete + scale: Incomplete + def __init__(self, x: int = 0, y: int = 0, scale: float = 1.0, contents=None) -> None: ... + def draw(self): ... + +class CloneMixin: + def clone(self, **kwds): ... + +class TypedPropertyCollection(PropHolder): + def __init__(self, exampleClass, **kwds) -> None: ... + def wKlassFactory(self, Klass): ... + def __getitem__(self, x): ... + def __contains__(self, key) -> bool: ... + def __setitem__(self, key, value) -> None: ... + def __len__(self) -> int: ... + def getProperties(self, recur: int = 1): ... + def setVector(self, **kw) -> None: ... + def __getattr__(self, name): ... + def __setattr__(self, name, value): ... + def checkAttr(self, key, a, default=None): ... + +def tpcGetItem(obj, x): ... +def isWKlass(obj): ... + +class StyleProperties(PropHolder): + def __init__(self, **kwargs) -> None: ... + def __setattr__(self, name, value) -> None: ... + +class TwoCircles(Widget): + leftCircle: Incomplete + rightCircle: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Face(Widget): + x: int + y: int + size: int + skinColor: Incomplete + eyeColor: Incomplete + mood: str + def __init__(self) -> None: ... + def demo(self) -> None: ... + def draw(self): ... + +class TwoFaces(Widget): + faceOne: Incomplete + faceTwo: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + def demo(self) -> None: ... + +class Sizer(Widget): + contents: Incomplete + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self, *elements) -> None: ... + def add(self, node, name=None) -> None: ... + def getBounds(self): ... + def draw(self): ... + +class CandleStickProperties(PropHolder): + strokeWidth: Incomplete + strokeColor: Incomplete + strokeDashArray: Incomplete + crossWidth: Incomplete + crossLo: Incomplete + crossHi: Incomplete + boxWidth: Incomplete + boxFillColor: Incomplete + boxStrokeColor: Incomplete + boxStrokeWidth: Incomplete + boxStrokeDashArray: Incomplete + boxLo: Incomplete + boxMid: Incomplete + boxHi: Incomplete + boxSides: Incomplete + position: Incomplete + candleKind: Incomplete + axes: Incomplete + chart: Incomplete + def __init__(self, **kwds) -> None: ... + def __call__(self, _x, _y, _size, _color): ... + +def CandleSticks(**kwds): ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi b/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi b/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi new file mode 100644 index 000000000000..18bf1002c449 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/adjustableArrow.pyi @@ -0,0 +1,11 @@ +from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +class AdjustableArrow(Widget): + def __init__(self, **kwds) -> None: ... + def draw(self): ... + +class AdjustableArrowDrawing(_DrawingEditorMixin, Drawing): + def __init__(self, width: int = 100, height: int = 63, *args, **kw) -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi b/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi new file mode 100644 index 000000000000..8e850d0f8d84 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/eventcal.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +class EventCalendar(Widget): + x: int + y: int + width: int + height: int + timeColWidth: Incomplete + trackRowHeight: int + data: Incomplete + trackNames: Incomplete + startTime: Incomplete + endTime: Incomplete + day: int + def __init__(self) -> None: ... + def computeSize(self) -> None: ... + def computeStartAndEndTimes(self) -> None: ... + def getAllTracks(self): ... + def getRelevantTalks(self, talkList): ... + def scaleTime(self, theTime): ... + def getTalkRect(self, startTime, duration, trackId, text): ... + def draw(self): ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/flags.pyi b/stubs/reportlab/reportlab/graphics/widgets/flags.pyi new file mode 100644 index 000000000000..69a282c17c1b --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/flags.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgets.signsandsymbols import _Symbol +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] +validFlag: Incomplete + +class Star(_Symbol): + size: int + fillColor: Incomplete + strokeColor: Incomplete + angle: int + def __init__(self) -> None: ... + def demo(self): ... + def draw(self): ... + +class Flag(_Symbol): + kind: Incomplete + size: int + fillColor: Incomplete + border: int + def __init__(self, **kw) -> None: ... + def availableFlagNames(self): ... + def draw(self): ... + def clone(self): ... + def demo(self): ... + +def makeFlag(name): ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/grids.pyi b/stubs/reportlab/reportlab/graphics/widgets/grids.pyi new file mode 100644 index 000000000000..e098fe78fc84 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/grids.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from typing import Final +from typing_extensions import Never + +from reportlab.graphics.shapes import LineShape +from reportlab.graphics.widgetbase import Widget + +__version__: Final[str] + +def frange(start, end=None, inc=None): ... +def makeDistancesList(list): ... + +class Grid(Widget): + x: int + y: int + width: int + height: int + orientation: str + useLines: int + useRects: int + delta: int + delta0: int + deltaSteps: Incomplete + fillColor: Incomplete + stripeColors: Incomplete + strokeColor: Incomplete + strokeWidth: int + def __init__(self) -> None: ... + def demo(self): ... + def makeOuterRect(self): ... + def makeLinePosList(self, start, isX: int = 0): ... + def makeInnerLines(self): ... + def makeInnerTiles(self): ... + def draw(self): ... + +class DoubleGrid(Widget): + x: int + y: int + width: int + height: int + grid0: Incomplete + grid1: Incomplete + def __init__(self) -> None: ... + def demo(self): ... + def draw(self): ... + +class ShadedRect(Widget): + x: int + y: int + width: int + height: int + orientation: str + numShades: int + fillColorStart: Incomplete + fillColorEnd: Incomplete + strokeColor: Incomplete + strokeWidth: int + cylinderMode: int + def __init__(self, **kw) -> None: ... + def demo(self): ... + def draw(self): ... + +def colorRange(c0, c1, n): ... +def centroid(P): ... +def rotatedEnclosingRect(P, angle, rect): ... + +class ShadedPolygon(Widget, LineShape): + angle: int + fillColorStart: Incomplete + fillColorEnd: Incomplete + cylinderMode: int + numShades: int + points: Incomplete + def __init__(self, **kw) -> None: ... + def draw(self): ... + # NOTE: widgets don't implement this, only actual shapes + def copy(self) -> Never: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/markers.pyi b/stubs/reportlab/reportlab/graphics/widgets/markers.pyi new file mode 100644 index 000000000000..6201181a6f99 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/markers.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.validators import Validator + +__version__: Final[str] + +class Marker(Widget): + def __init__(self, *args, **kw) -> None: ... + def clone(self, **kwds): ... + def draw(self): ... + +def uSymbol2Symbol(uSymbol, x, y, color): ... + +class _isSymbol(Validator): + def test(self, x): ... + +isSymbol: Incomplete + +def makeMarker(name, **kw): ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi b/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi new file mode 100644 index 000000000000..6b520e461fa5 --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/signsandsymbols.pyi @@ -0,0 +1,164 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class _Symbol(Widget): + x: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + def __init__(self) -> None: ... + def demo(self): ... + +class ETriangle(_Symbol): + def __init__(self) -> None: ... + def draw(self): ... + +class RTriangle(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Octagon(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class Crossbox(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + crossColor: Incomplete + strokeColor: Incomplete + crosswidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class Tickbox(_Symbol): + x: int + y: int + size: int + tickColor: Incomplete + strokeColor: Incomplete + fillColor: Incomplete + tickwidth: int + def __init__(self) -> None: ... + def draw(self): ... + +class SmileyFace(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class StopSign(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + stopColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NoEntry(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + innerBarColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NotAllowed(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class NoSmoking(NotAllowed): + def __init__(self) -> None: ... + def draw(self): ... + +class DangerSign(_Symbol): + x: int + y: int + size: int + strokeColor: Incomplete + fillColor: Incomplete + strokeWidth: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class YesNo(_Symbol): + x: int + y: int + size: int + tickcolor: Incomplete + crosscolor: Incomplete + testValue: int + def __init__(self) -> None: ... + def draw(self): ... + def demo(self): ... + +class FloppyDisk(_Symbol): + x: int + y: int + size: int + diskColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class ArrowOne(_Symbol): + x: int + y: int + size: int + fillColor: Incomplete + strokeWidth: int + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class ArrowTwo(ArrowOne): + x: int + y: int + size: int + fillColor: Incomplete + strokeWidth: int + strokeColor: Incomplete + def __init__(self) -> None: ... + def draw(self): ... + +class CrossHair(_Symbol): + x: int + size: int + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + innerGap: str + def __init__(self) -> None: ... + def draw(self): ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/graphics/widgets/table.pyi b/stubs/reportlab/reportlab/graphics/widgets/table.pyi new file mode 100644 index 000000000000..a38683fb2e8c --- /dev/null +++ b/stubs/reportlab/reportlab/graphics/widgets/table.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class TableWidget(Widget): + x: Incomplete + y: Incomplete + width: int + height: int + borderStrokeColor: Incomplete + fillColor: Incomplete + borderStrokeWidth: float + horizontalDividerStrokeColor: Incomplete + verticalDividerStrokeColor: Incomplete + horizontalDividerStrokeWidth: float + verticalDividerStrokeWidth: float + dividerDashArray: Incomplete + data: Incomplete + boxAnchor: str + fontSize: int + fontColor: Incomplete + alignment: str + textAnchor: str + def __init__(self, x: int = 10, y: int = 10, **kw) -> None: ... + def demo(self): ... + def draw(self): ... + def preProcessData(self, data): ... diff --git a/stubs/reportlab/reportlab/lib/PyFontify.pyi b/stubs/reportlab/reportlab/lib/PyFontify.pyi new file mode 100644 index 000000000000..cf5a8f4c7b38 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/PyFontify.pyi @@ -0,0 +1,22 @@ +import re +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +def replace(src, sep, rep): ... + +keywordsList: list[str] +commentPat: str +pat: str +quotePat: str +tripleQuotePat: str +nonKeyPat: str +keyPat: str +matchPat: str +matchRE: re.Pattern[str] +idKeyPat: str +idRE: re.Pattern[str] + +def fontify(pytext, searchfrom: int = 0, searchto=None) -> list[tuple[str, int, int, Incomplete]]: ... +def test(path) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/__init__.pyi b/stubs/reportlab/reportlab/lib/__init__.pyi new file mode 100644 index 000000000000..88939e7e7871 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/__init__.pyi @@ -0,0 +1,4 @@ +from typing import Final + +__version__: Final[str] +RL_DEBUG: Final[bool] # initalized based on env diff --git a/stubs/reportlab/reportlab/lib/abag.pyi b/stubs/reportlab/reportlab/lib/abag.pyi new file mode 100644 index 000000000000..4c7d4d6851a0 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/abag.pyi @@ -0,0 +1,11 @@ +from typing import Any, Final +from typing_extensions import Self + +__version__: Final[str] + +class ABag: + def __init__(self, **attr: Any) -> None: ... + def clone(self, **attr: Any) -> Self: ... + # ABag can have arbitrary attributes + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/arciv.pyi b/stubs/reportlab/reportlab/lib/arciv.pyi new file mode 100644 index 000000000000..501f1df37996 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/arciv.pyi @@ -0,0 +1,9 @@ +class ArcIV: + def __init__(self, key) -> None: ... + def reset(self) -> None: ... + def encode(self, S: str | bytes | list[int]) -> bytes: ... + +def encode(text: str | bytes | list[int], key) -> bytes: ... +def decode(text: str | bytes | list[int], key) -> bytes: ... + +__all__ = ["ArcIV", "encode", "decode"] diff --git a/stubs/reportlab/reportlab/lib/attrmap.pyi b/stubs/reportlab/reportlab/lib/attrmap.pyi new file mode 100644 index 000000000000..a951823e0b91 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/attrmap.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class CallableValue: + func: Incomplete + args: Incomplete + kw: Incomplete + def __init__(self, func, *args, **kw) -> None: ... + def __call__(self): ... + +class AttrMapValue: + validate: Incomplete + desc: Incomplete + def __init__(self, validate=None, desc=None, initial=None, advancedUsage: int = 0, **kw) -> None: ... + def __getattr__(self, name): ... + +class AttrMap(dict[str, AttrMapValue]): + def __init__(self, BASE=None, UNWANTED=[], **kw) -> None: ... + def remove(self, unwanted) -> None: ... + def clone(self, UNWANTED=[], **kw) -> AttrMap: ... + +def validateSetattr(obj, name, value) -> None: ... +def hook__setattr__(obj) -> None: ... +def addProxyAttribute(src, name, validate=None, desc=None, initial=None, dst=None) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/boxstuff.pyi b/stubs/reportlab/reportlab/lib/boxstuff.pyi new file mode 100644 index 000000000000..61578c5e15c1 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/boxstuff.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from typing import Final, Literal, overload + +__version__: Final[str] + +@overload +def rectCorner( + x, y, width, height, anchor: str = "sw", dims: Literal[True] = ... +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... +@overload +def rectCorner(x, y, width, height, anchor: str = "sw", dims: Literal[False] | None = False) -> tuple[Incomplete, Incomplete]: ... + +def aspectRatioFix( + preserve, anchor, x, y, width, height, imWidth, imHeight, anchorAtXY: bool = False +) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]: ... diff --git a/stubs/reportlab/reportlab/lib/codecharts.pyi b/stubs/reportlab/reportlab/lib/codecharts.pyi new file mode 100644 index 000000000000..b91508e6c77a --- /dev/null +++ b/stubs/reportlab/reportlab/lib/codecharts.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.graphics.shapes import Group +from reportlab.graphics.widgetbase import Widget +from reportlab.platypus import Flowable + +__version__: Final[str] +adobe2codec: dict[str, str] + +class CodeChartBase(Flowable): + rows: Incomplete + width: Incomplete + height: Incomplete + ylist: Incomplete + xlist: Incomplete + def calcLayout(self) -> None: ... + def formatByte(self, byt) -> str: ... + def drawChars(self, charList) -> None: ... + def drawLabels(self, topLeft: str = "") -> None: ... + +class SingleByteEncodingChart(CodeChartBase): + codePoints: int + faceName: Incomplete + encodingName: Incomplete + fontName: Incomplete + charsPerRow: Incomplete + boxSize: Incomplete + hex: Incomplete + rowLabels: Incomplete + def __init__( + self, + faceName: str = "Helvetica", + encodingName: str = "WinAnsiEncoding", + charsPerRow: int = 16, + boxSize: int = 14, + hex: int = 1, + ) -> None: ... + def draw(self) -> None: ... + +class KutenRowCodeChart(CodeChartBase): + row: Incomplete + codePoints: int + boxSize: int + charsPerRow: int + rows: int + rowLabels: Incomplete + hex: int + faceName: Incomplete + encodingName: Incomplete + fontName: Incomplete + def __init__(self, row, faceName, encodingName) -> None: ... + def makeRow(self, row) -> list[bytes | list[None]]: ... + def draw(self) -> None: ... + +class Big5CodeChart(CodeChartBase): + row: Incomplete + codePoints: int + boxSize: int + charsPerRow: int + rows: int + hex: int + faceName: Incomplete + encodingName: Incomplete + rowLabels: Incomplete + fontName: Incomplete + def __init__(self, row, faceName, encodingName) -> None: ... + def makeRow(self, row) -> list[bytes | list[None]]: ... + def draw(self) -> None: ... + +def hBoxText(msg, canvas, x, y, fontName) -> None: ... + +class CodeWidget(Widget): + x: int + y: int + width: int + height: int + def __init__(self) -> None: ... + def draw(self) -> Group: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/colors.pyi b/stubs/reportlab/reportlab/lib/colors.pyi new file mode 100644 index 000000000000..de0de9789c00 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/colors.pyi @@ -0,0 +1,325 @@ +from collections.abc import Iterable, Iterator +from typing import Final, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self + +_ColorT = TypeVar("_ColorT", bound=Color) +# NOTE: Reportlab is very inconsistent and sometimes uses the interpretation +# used in reportlab.pdfgen.textobject instead, so we pick a different name +_ConvertibleToColor: TypeAlias = Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float] | str | int + +__version__: Final[str] + +class Color: + red: float + green: float + blue: float + alpha: float + def __init__(self, red: float = 0, green: float = 0, blue: float = 0, alpha: float = 1) -> None: ... + @property + def __key__(self) -> tuple[float, ...]: ... + def __hash__(self) -> int: ... + def __comparable__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... + def rgb(self) -> tuple[float, float, float]: ... + def rgba(self) -> tuple[float, float, float, float]: ... + def bitmap_rgb(self) -> tuple[int, int, int]: ... + def bitmap_rgba(self) -> tuple[int, int, int, int]: ... + def hexval(self) -> str: ... + def hexvala(self) -> str: ... + def int_rgb(self) -> int: ... + def int_rgba(self) -> int: ... + def int_argb(self) -> int: ... + @property + def cKwds(self) -> Iterator[tuple[str, int]]: ... + # NOTE: Possible arguments depend on __init__, so this violates LSP + # For now we just leave it unchecked + def clone(self, **kwds) -> Self: ... + @property + def normalizedAlpha(self) -> float: ... + +def opaqueColor(c: object) -> bool: ... + +class CMYKColor(Color): + cyan: float + magenta: float + yellow: float + black: float + spotName: str | None + density: float + knockout: bool | None + alpha: float + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 1, + knockout: bool | None = None, + alpha: float = 1, + ) -> None: ... + def fader(self, n: int, reverse: bool = False) -> list[Self]: ... + def cmyk(self) -> tuple[float, float, float, float]: ... + def cmyka(self) -> tuple[float, float, float, float, float]: ... + +class PCMYKColor(CMYKColor): + def __init__( + self, + cyan: float, + magenta: float, + yellow: float, + black: float, + density: float = 100, + spotName: str | None = None, + knockout: bool | None = None, + alpha: float = 100, + ) -> None: ... + +class CMYKColorSep(CMYKColor): + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 1, + alpha: float = 1, + ) -> None: ... + +class PCMYKColorSep(PCMYKColor, CMYKColorSep): + def __init__( + self, + cyan: float = 0, + magenta: float = 0, + yellow: float = 0, + black: float = 0, + spotName: str | None = None, + density: float = 100, + alpha: float = 100, + ) -> None: ... + +def cmyk2rgb(cmyk: tuple[float, float, float, float], density: float = 1) -> tuple[float, float, float]: ... +def rgb2cmyk(r: float, g: float, b: float) -> tuple[float, float, float, float]: ... +def color2bw(colorRGB: Color) -> Color: ... +def HexColor(val: str | int, htmlOnly: bool = False, hasAlpha: bool = False) -> Color: ... +def linearlyInterpolatedColor(c0: _ColorT, c1: _ColorT, x0: float, x1: float, x: float) -> _ColorT: ... + +@overload +def obj_R_G_B( + c: Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float], +) -> tuple[float, float, float]: ... +@overload +def obj_R_G_B(c: None) -> None: ... + +transparent: Color +ReportLabBlueOLD: Color +ReportLabBlue: Color +ReportLabBluePCMYK: Color +ReportLabLightBlue: Color +ReportLabFidBlue: Color +ReportLabFidRed: Color +ReportLabGreen: Color +ReportLabLightGreen: Color +aliceblue: Color +antiquewhite: Color +aqua: Color +aquamarine: Color +azure: Color +beige: Color +bisque: Color +black: Color +blanchedalmond: Color +blue: Color +blueviolet: Color +brown: Color +burlywood: Color +cadetblue: Color +chartreuse: Color +chocolate: Color +coral: Color +cornflowerblue: Color +cornflower: Color +cornsilk: Color +crimson: Color +cyan: Color +darkblue: Color +darkcyan: Color +darkgoldenrod: Color +darkgray: Color +darkgrey: Color +darkgreen: Color +darkkhaki: Color +darkmagenta: Color +darkolivegreen: Color +darkorange: Color +darkorchid: Color +darkred: Color +darksalmon: Color +darkseagreen: Color +darkslateblue: Color +darkslategray: Color +darkslategrey: Color +darkturquoise: Color +darkviolet: Color +deeppink: Color +deepskyblue: Color +dimgray: Color +dimgrey: Color +dodgerblue: Color +firebrick: Color +floralwhite: Color +forestgreen: Color +fuchsia: Color +gainsboro: Color +ghostwhite: Color +gold: Color +goldenrod: Color +gray: Color +grey: Color +green: Color +greenyellow: Color +honeydew: Color +hotpink: Color +indianred: Color +indigo: Color +ivory: Color +khaki: Color +lavender: Color +lavenderblush: Color +lawngreen: Color +lemonchiffon: Color +lightblue: Color +lightcoral: Color +lightcyan: Color +lightgoldenrodyellow: Color +lightgreen: Color +lightgrey: Color +lightpink: Color +lightsalmon: Color +lightseagreen: Color +lightskyblue: Color +lightslategray: Color +lightslategrey: Color +lightsteelblue: Color +lightyellow: Color +lime: Color +limegreen: Color +linen: Color +magenta: Color +maroon: Color +mediumaquamarine: Color +mediumblue: Color +mediumorchid: Color +mediumpurple: Color +mediumseagreen: Color +mediumslateblue: Color +mediumspringgreen: Color +mediumturquoise: Color +mediumvioletred: Color +midnightblue: Color +mintcream: Color +mistyrose: Color +moccasin: Color +navajowhite: Color +navy: Color +oldlace: Color +olive: Color +olivedrab: Color +orange: Color +orangered: Color +orchid: Color +palegoldenrod: Color +palegreen: Color +paleturquoise: Color +palevioletred: Color +papayawhip: Color +peachpuff: Color +peru: Color +pink: Color +plum: Color +powderblue: Color +purple: Color +red: Color +rosybrown: Color +royalblue: Color +saddlebrown: Color +salmon: Color +sandybrown: Color +seagreen: Color +seashell: Color +sienna: Color +silver: Color +skyblue: Color +slateblue: Color +slategray: Color +slategrey: Color +snow: Color +springgreen: Color +steelblue: Color +tan: Color +teal: Color +thistle: Color +tomato: Color +turquoise: Color +violet: Color +wheat: Color +white: Color +whitesmoke: Color +yellow: Color +yellowgreen: Color +fidblue: Color +fidred: Color +fidlightblue: Color +ColorType: type[Color] + +def colorDistance(col1: Color, col2: Color) -> float: ... +def cmykDistance(col1: Color, col2: Color) -> float: ... +def getAllNamedColors() -> dict[str, Color]: ... + +@overload +def describe(aColor: Color, mode: Literal[0] = 0) -> None: ... +@overload +def describe(aColor: Color, mode: Literal[1]) -> str: ... +@overload +def describe(aColor: Color, mode: Literal[2]) -> tuple[str, float]: ... + +def hue2rgb(m1: float, m2: float, h: float) -> float: ... +def hsl2rgb(h: float, s: float, l: float) -> tuple[float, float, float]: ... + +@type_check_only +class _cssParse: + def pcVal(self, v: str, n: str = "argument") -> float: ... + def rgbPcVal(self, v: str) -> float: ... + def rgbVal(self, v: str) -> float: ... + def floatVal(self, v: str) -> float: ... + def hueVal(self, v: str) -> float: ... + def alphaVal(self, v: str, c: float = 1, n: str = "alpha") -> float: ... + s: str + def __call__(self, s: str) -> Color: ... + +cssParse: _cssParse + +@type_check_only +class _toColor: + extraColorsNS: dict[str, Color] + def __init__(self) -> None: ... + def setExtraColorsNameSpace(self, NS: dict[str, Color]) -> None: ... + def __call__(self, arg: _ConvertibleToColor, default: Color | None = None) -> Color: ... + +toColor: _toColor + +@overload +def toColorOrNone(arg: None, default: Color | None) -> None: ... +@overload +def toColorOrNone(arg: _ConvertibleToColor, default: Color | None = None) -> Color: ... + +def setColors(**kw: _ConvertibleToColor) -> None: ... +def Whiter(c: _ColorT, f: float) -> _ColorT: ... +def Blacker(c: _ColorT, f: float) -> _ColorT: ... +def fade(aSpotColor: CMYKColor, percentages: Iterable[float]) -> list[CMYKColor]: ... diff --git a/stubs/reportlab/reportlab/lib/corp.pyi b/stubs/reportlab/reportlab/lib/corp.pyi new file mode 100644 index 000000000000..9c71b4a4cc9f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/corp.pyi @@ -0,0 +1,81 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import Final + +from reportlab.graphics.shapes import Drawing, Group +from reportlab.graphics.widgetbase import Widget +from reportlab.lib.attrmap import * +from reportlab.lib.validators import * + +__version__: Final[str] + +class RL_CorpLogo(Widget): + fillColor: Incomplete + strokeColor: Incomplete + strokeWidth: float + background: Incomplete + border: Incomplete + borderWidth: int + shadow: float + height: int + width: int + x: int + skewX: int + showPage: int + oColors: Incomplete + pageColors: Incomplete + prec: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + @staticmethod + def applyPrec(P, prec): ... + def draw(self) -> Group: ... + +class RL_CorpLogoReversed(RL_CorpLogo): + background: Incomplete + fillColor: Incomplete + def __init__(self) -> None: ... + +class RL_CorpLogoThin(Widget): + fillColor: Incomplete + strokeColor: Incomplete + x: int + y: int + height: Incomplete + width: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + def draw(self) -> Group: ... + +class ReportLabLogo: + origin: Incomplete + dimensions: Incomplete + powered_by: Incomplete + def __init__(self, atx: int = 0, aty: int = 0, width=180.0, height=108.0, powered_by: int = 0) -> None: ... + def draw(self, canvas) -> None: ... + +class RL_BusinessCard(Widget): + fillColor: Incomplete + strokeColor: Incomplete + altStrokeColor: Incomplete + x: int + y: int + height: Incomplete + width: Incomplete + borderWidth: Incomplete + bleed: Incomplete + cropMarks: int + border: int + name: str + position: str + telephone: str + mobile: str + fax: str + email: str + web: str + rh_blurb_top: Incomplete + def __init__(self) -> None: ... + def demo(self) -> Drawing: ... + def draw(self) -> Group: ... + +def test(formats: Iterable[str] = ["pdf", "eps", "jpg", "gif", "svg"]) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/enums.pyi b/stubs/reportlab/reportlab/lib/enums.pyi new file mode 100644 index 000000000000..56229718802f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/enums.pyi @@ -0,0 +1,7 @@ +from typing import Final + +__version__: Final[str] +TA_LEFT: Final = 0 +TA_CENTER: Final = 1 +TA_RIGHT: Final = 2 +TA_JUSTIFY: Final = 4 diff --git a/stubs/reportlab/reportlab/lib/extformat.pyi b/stubs/reportlab/reportlab/lib/extformat.pyi new file mode 100644 index 000000000000..4d9f857e35f8 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/extformat.pyi @@ -0,0 +1,9 @@ +from collections.abc import Mapping +from typing import Any, Final + +__version__: Final[str] + +def dictformat( + _format: str, L: Mapping[str, object] | None = {}, G: dict[str, Any] | None = {} # `L` and `G` are passed to `eval` function +) -> str: ... +def magicformat(format: str) -> str: ... diff --git a/stubs/reportlab/reportlab/lib/fontfinder.pyi b/stubs/reportlab/reportlab/lib/fontfinder.pyi new file mode 100644 index 000000000000..1cbcb05c185e --- /dev/null +++ b/stubs/reportlab/reportlab/lib/fontfinder.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from typing import Final +from typing_extensions import LiteralString + +__version__: Final[str] + +def asNative(s) -> str: ... + +EXTENSIONS: Final = [".ttf", ".ttc", ".otf", ".pfb", ".pfa"] +FF_FIXED: Final = 1 +FF_SERIF: Final = 2 +FF_SYMBOLIC: Final = 4 +FF_SCRIPT: Final = 8 +FF_NONSYMBOLIC: Final = 32 +FF_ITALIC: Final = 64 +FF_ALLCAP: Final = 65536 +FF_SMALLCAP: Final = 131072 +FF_FORCEBOLD: Final = 262144 + +class FontDescriptor: + name: Incomplete + fullName: Incomplete + familyName: Incomplete + styleName: Incomplete + isBold: bool + isItalic: bool + isFixedPitch: bool + isSymbolic: bool + typeCode: Incomplete + fileName: Incomplete + metricsFileName: Incomplete + timeModified: int + def __init__(self) -> None: ... + def getTag(self) -> LiteralString: ... + +class FontFinder: + useCache: Incomplete + validate: Incomplete + verbose: Incomplete + def __init__( + self, dirs=[], useCache: bool = True, validate: bool = False, recur: bool = False, fsEncoding=None, verbose: int = 0 + ) -> None: ... + def addDirectory(self, dirName, recur=None) -> None: ... + def addDirectories(self, dirNames, recur=None) -> None: ... + def getFamilyNames(self) -> list[bytes]: ... + def getFontsInFamily(self, familyName): ... + def getFamilyXmlReport(self) -> LiteralString: ... + def getFontsWithAttributes(self, **kwds) -> list[FontDescriptor]: ... + def getFont(self, familyName, bold: bool = False, italic: bool = False) -> FontDescriptor: ... + def save(self, fileName) -> None: ... + def load(self, fileName) -> None: ... + def search(self) -> None: ... + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/fonts.pyi b/stubs/reportlab/reportlab/lib/fonts.pyi new file mode 100644 index 000000000000..665e34909894 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/fonts.pyi @@ -0,0 +1,9 @@ +from typing import Final, Literal, TypeAlias + +_BoolInt: TypeAlias = Literal[0, 1] + +__version__: Final[str] + +def ps2tt(psfn: str) -> tuple[str, _BoolInt, _BoolInt]: ... +def tt2ps(fn: str, b: _BoolInt, i: _BoolInt) -> str: ... +def addMapping(face: str, bold: _BoolInt, italic: _BoolInt, psname: str) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/formatters.pyi b/stubs/reportlab/reportlab/lib/formatters.pyi new file mode 100644 index 000000000000..bb46a3be1d94 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/formatters.pyi @@ -0,0 +1,23 @@ +from _typeshed import Incomplete +from typing import Literal +from typing_extensions import LiteralString + +class Formatter: + pattern: str + def __init__(self, pattern: str) -> None: ... + def format(self, obj: object) -> str: ... + def __call__(self, x: object) -> str: ... + +class DecimalFormatter(Formatter): + calcPlaces: Incomplete + places: int + dot: Incomplete + comma: Incomplete + prefix: Incomplete + suffix: Incomplete + def __init__( + self, places: int | Literal["auto"] = 2, decimalSep: str = ".", thousandSep=None, prefix=None, suffix=None + ) -> None: ... + def format(self, num) -> LiteralString: ... + +__all__ = ("Formatter", "DecimalFormatter") diff --git a/stubs/reportlab/reportlab/lib/geomutils.pyi b/stubs/reportlab/reportlab/lib/geomutils.pyi new file mode 100644 index 000000000000..1fec093fb40c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/geomutils.pyi @@ -0,0 +1,5 @@ +from typing import Final + +__version__: Final[str] + +def normalizeTRBL(p: float | tuple[float, ...] | list[float]) -> tuple[float, ...]: ... diff --git a/stubs/reportlab/reportlab/lib/logger.pyi b/stubs/reportlab/reportlab/lib/logger.pyi new file mode 100644 index 000000000000..ce7635c168ee --- /dev/null +++ b/stubs/reportlab/reportlab/lib/logger.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class Logger: + def __init__(self) -> None: ... + def add(self, fp) -> None: ... + def remove(self, fp) -> None: ... + def write(self, text) -> None: ... + def __call__(self, text) -> None: ... + +logger: Logger + +class WarnOnce: + uttered: dict[Incomplete, Incomplete] + pfx: str + enabled: bool | int + def __init__(self, kind: str = "Warn") -> None: ... + def once(self, warning) -> None: ... + def __call__(self, warning) -> None: ... + +warnOnce: WarnOnce +infoOnce: WarnOnce diff --git a/stubs/reportlab/reportlab/lib/normalDate.pyi b/stubs/reportlab/reportlab/lib/normalDate.pyi new file mode 100644 index 000000000000..98e40086381d --- /dev/null +++ b/stubs/reportlab/reportlab/lib/normalDate.pyi @@ -0,0 +1,83 @@ +from _typeshed import ConvertibleToInt +from typing import Final, Literal +from typing_extensions import Self + +__version__: Final[str] + +def getStdMonthNames() -> list[str]: ... +def getStdShortMonthNames() -> list[str]: ... +def getStdDayNames() -> list[str]: ... +def getStdShortDayNames() -> list[str]: ... +def isLeapYear(year: int) -> Literal[0, 1]: ... + +class NormalDateException(Exception): ... + +class NormalDate: + def __init__(self, normalDate=None) -> None: ... + def add(self, days) -> None: ... + def __add__(self, days: int) -> Self: ... + def __radd__(self, days: int) -> Self: ... + def clone(self) -> Self: ... + def __lt__(self, other) -> bool: ... + def __le__(self, other) -> bool: ... + def __eq__(self, other) -> bool: ... + def __ne__(self, other) -> bool: ... + def __ge__(self, other) -> bool: ... + def __gt__(self, other) -> bool: ... + def day(self) -> int: ... + def dayOfWeek(self) -> int: ... + @property + def __day_of_week_name__(self): ... + def dayOfWeekAbbrev(self): ... + def dayOfWeekName(self): ... + def dayOfYear(self) -> int: ... + def daysBetweenDates(self, normalDate) -> int: ... + def equals(self, target) -> bool | Literal[0]: ... + def endOfMonth(self) -> Self: ... + def firstDayOfMonth(self) -> Self: ... + def formatUS(self) -> str: ... + def formatUSCentury(self) -> str: ... + def formatMS(self, fmt): ... + def __hash__(self) -> int: ... + def __int__(self) -> int: ... + def isLeapYear(self) -> Literal[0, 1]: ... + def lastDayOfMonth(self) -> int: ... + def localeFormat(self) -> str: ... + def month(self) -> int: ... + @property + def __month_name__(self): ... + def monthAbbrev(self): ... + def monthName(self): ... + def normalize(self, scalar) -> None: ... + def range(self, days) -> list[NormalDate]: ... + def scalar(self) -> int: ... + def setDay(self, day) -> None: ... + def setMonth(self, month) -> None: ... + normalDate: int | None + def setNormalDate(self, normalDate) -> None: ... + def setYear(self, year) -> None: ... + def __sub__(self, v): ... + def __rsub__(self, v): ... + def toTuple(self) -> tuple[int, int, int]: ... + def year(self) -> int: ... + +def bigBang() -> NormalDate: ... +def bigCrunch() -> NormalDate: ... +def dayOfWeek(y: int, m: int, d: int) -> int: ... +def firstDayOfYear(year: int) -> int: ... +def FND(d): ... + +Epoch: NormalDate +ND = NormalDate +BDEpoch: ND +BDEpochScalar: int + +class BusinessDate(NormalDate): + def add(self, days: int) -> None: ... + def __add__(self, days: int) -> Self: ... + def __sub__(self, v): ... + def asNormalDate(self) -> ND: ... + def daysBetweenDates(self, normalDate) -> int: ... + def normalize(self, i: ConvertibleToInt) -> None: ... + def scalar(self): ... + def setNormalDate(self, normalDate) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/pagesizes.pyi b/stubs/reportlab/reportlab/lib/pagesizes.pyi new file mode 100644 index 000000000000..617b42c9338c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pagesizes.pyi @@ -0,0 +1,51 @@ +from typing import Final + +__version__: Final[str] +A0: Final[tuple[float, float]] +A1: Final[tuple[float, float]] +A2: Final[tuple[float, float]] +A3: Final[tuple[float, float]] +A4: Final[tuple[float, float]] +A5: Final[tuple[float, float]] +A6: Final[tuple[float, float]] +A7: Final[tuple[float, float]] +A8: Final[tuple[float, float]] +A9: Final[tuple[float, float]] +A10: Final[tuple[float, float]] +B0: Final[tuple[float, float]] +B1: Final[tuple[float, float]] +B2: Final[tuple[float, float]] +B3: Final[tuple[float, float]] +B4: Final[tuple[float, float]] +B5: Final[tuple[float, float]] +B6: Final[tuple[float, float]] +B7: Final[tuple[float, float]] +B8: Final[tuple[float, float]] +B9: Final[tuple[float, float]] +B10: Final[tuple[float, float]] +C0: Final[tuple[float, float]] +C1: Final[tuple[float, float]] +C2: Final[tuple[float, float]] +C3: Final[tuple[float, float]] +C4: Final[tuple[float, float]] +C5: Final[tuple[float, float]] +C6: Final[tuple[float, float]] +C7: Final[tuple[float, float]] +C8: Final[tuple[float, float]] +C9: Final[tuple[float, float]] +C10: Final[tuple[float, float]] +LETTER: Final[tuple[float, float]] +LEGAL: Final[tuple[float, float]] +ELEVENSEVENTEEN: Final[tuple[float, float]] +JUNIOR_LEGAL: Final[tuple[float, float]] +HALF_LETTER: Final[tuple[float, float]] +GOV_LETTER: Final[tuple[float, float]] +GOV_LEGAL: Final[tuple[float, float]] +TABLOID: Final[tuple[float, float]] +LEDGER: Final[tuple[float, float]] +letter: Final[tuple[float, float]] +legal: Final[tuple[float, float]] +elevenSeventeen: Final[tuple[float, float]] + +def landscape(pagesize: tuple[float, float]) -> tuple[float, float]: ... +def portrait(pagesize: tuple[float, float]) -> tuple[float, float]: ... diff --git a/stubs/reportlab/reportlab/lib/pdfencrypt.pyi b/stubs/reportlab/reportlab/lib/pdfencrypt.pyi new file mode 100644 index 000000000000..50e9e4ba13de --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pdfencrypt.pyi @@ -0,0 +1,133 @@ +import os +from _typeshed import Incomplete +from typing import Final + +from reportlab.pdfbase.pdfdoc import PDFObject +from reportlab.platypus.flowables import Flowable + +__version__: Final[str] + +def xorKey(num: int, key: bytes) -> bytes: ... + +CLOBBERID: int +CLOBBERPERMISSIONS: int +DEBUG: int +reserved1: int +reserved2: int +printable: int +modifiable: int +copypastable: int +annotatable: int +higherbits: int + +os_urandom = os.urandom + +class StandardEncryption: + prepared: int + userPassword: Incomplete + ownerPassword: Incomplete + revision: int + canPrint: Incomplete + canModify: Incomplete + canCopy: Incomplete + canAnnotate: Incomplete + O: Incomplete + def __init__( + self, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength=None, + ) -> None: ... + def setAllPermissions(self, value) -> None: ... + def permissionBits(self) -> int: ... + def encode(self, t) -> bytes: ... + P: Incomplete + key: Incomplete + U: Incomplete + UE: Incomplete + OE: Incomplete + Perms: Incomplete + objnum: Incomplete + def prepare(self, document, overrideID=None) -> None: ... + version: Incomplete + def register(self, objnum, version) -> None: ... + def info(self) -> StandardEncryptionDictionary: ... + +class StandardEncryptionDictionary(PDFObject): + __RefOnly__: int + revision: Incomplete + def __init__(self, O, OE, U, UE, P, Perms, revision) -> None: ... + def format(self, document) -> bytes: ... + +padding: str + +def hexText(text: str | bytes | bytearray) -> str: ... +def unHexText(hexText) -> bytes: ... + +PadString: bytes + +def checkRevision(revision): ... +def encryptionkey(password, OwnerKey, Permissions, FileId1, revision=None) -> bytes: ... +def computeO(userPassword, ownerPassword, revision) -> bytes: ... +def computeU( + encryptionkey, + encodestring=b"(\xbfN^Nu\x8aAd\x00NV\xff\xfa\x01\x08..\x00\xb6\xd0h>\x80/\x0c\xa9\xfedSiz", + revision=None, + documentId=None, +) -> bytes: ... +def checkU(encryptionkey, U) -> None: ... +def encodePDF(key, objectNumber, generationNumber, string, revision=None) -> bytes: ... +def equalityCheck(observed, expected, label) -> None: ... +def test() -> None: ... +def encryptCanvas( + canvas, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> None: ... + +class EncryptionFlowable(StandardEncryption, Flowable): + def wrap(self, availWidth, availHeight): ... + def draw(self) -> None: ... + +def encryptDocTemplate( + dt, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> None: ... +def encryptPdfInMemory( + inputPDF, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> bytes: ... +def encryptPdfOnDisk( + inputFileName, + outputFileName, + userPassword, + ownerPassword=None, + canPrint: int = 1, + canModify: int = 1, + canCopy: int = 1, + canAnnotate: int = 1, + strength: int = 40, +) -> int: ... +def scriptInterp() -> None: ... +def main() -> None: ... diff --git a/stubs/reportlab/reportlab/lib/pygments2xpre.pyi b/stubs/reportlab/reportlab/lib/pygments2xpre.pyi new file mode 100644 index 000000000000..b18d5296345f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/pygments2xpre.pyi @@ -0,0 +1,3 @@ +__all__ = ("pygments2xpre",) + +def pygments2xpre(s, language: str = "python"): ... diff --git a/stubs/reportlab/reportlab/lib/randomtext.pyi b/stubs/reportlab/reportlab/lib/randomtext.pyi new file mode 100644 index 000000000000..121b100edcd3 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/randomtext.pyi @@ -0,0 +1,19 @@ +from collections.abc import Sequence +from typing import Final + +__version__: Final[str] +STARTUP: Final[Sequence[str]] +COMPUTERS: Final[Sequence[str]] +BLAH: Final[Sequence[str]] +BUZZWORD: Final[Sequence[str]] +STARTREK: Final[Sequence[str]] +PRINTING: Final[Sequence[str]] +PYTHON: Final[Sequence[str]] +leadins: Final[Sequence[str]] +subjects: Final[Sequence[str]] +verbs: Final[Sequence[str]] +objects: Final[Sequence[str]] + +def format_wisdom(text: str, line_length: int = 72) -> str: ... +def chomsky(times: int = 1) -> str: ... +def randomText(theme: str | Sequence[str] = ..., sentences: int = 5) -> str: ... diff --git a/stubs/reportlab/reportlab/lib/rl_accel.pyi b/stubs/reportlab/reportlab/lib/rl_accel.pyi new file mode 100644 index 000000000000..fb6dcc74b0a4 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rl_accel.pyi @@ -0,0 +1,28 @@ +from _typeshed import Incomplete +from typing import Literal + +def fp_str(*a) -> str: ... +def unicode2T1(utext, fonts) -> list[tuple[Incomplete, Incomplete]]: ... +def instanceStringWidthT1(self, text: str, size: float, encoding: str = "utf8") -> float: ... +def instanceStringWidthTTF(self, text: str, size: float, encoding: str = "utf8") -> float: ... +def hex32(i) -> str: ... +def add32(x: int, y: int) -> int: ... +def calcChecksum(data: str | bytes) -> int: ... +def escapePDF(s) -> str: ... +def asciiBase85Encode(input: str) -> str: ... +def asciiBase85Decode(input) -> bytes: ... +def sameFrag(f, g) -> bool | Literal[0]: ... + +__all__ = [ + "fp_str", + "unicode2T1", + "instanceStringWidthT1", + "instanceStringWidthTTF", + "asciiBase85Encode", + "asciiBase85Decode", + "escapePDF", + "sameFrag", + "calcChecksum", + "add32", + "hex32", +] diff --git a/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi b/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi new file mode 100644 index 000000000000..e70536e3ee0f --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi @@ -0,0 +1,237 @@ +import ast +import math +import re +import time +from _typeshed import Incomplete +from collections.abc import Generator +from typing_extensions import Never, Self + +eval_debug: int +strTypes: tuple[type[bytes], type[str]] +isPy39: bool +isPy313: bool + +class BadCode(ValueError): ... + +augOps: dict[ast.operator, str] +__allowed_magic_methods__: frozenset[str] +__rl_unsafe__: frozenset[str] +__rl_unsafe_re__: re.Pattern[str] + +def copy_locations(new_node, old_node) -> None: ... + +class UntrustedAstTransformer(ast.NodeTransformer): + names_seen: Incomplete + nameIsAllowed: Incomplete + def __init__(self, names_seen=None, nameIsAllowed=None) -> None: ... + @property + def tmpName(self) -> str: ... + def error(self, node, msg) -> Never: ... + def guard_iter(self, node): ... + def is_starred(self, ob): ... + def gen_unpack_spec(self, tpl) -> ast.Dict: ... + def protect_unpack_sequence(self, target, value) -> ast.Call: ... + def gen_unpack_wrapper(self, node, target, ctx: str = "store") -> tuple[ast.Name, ast.Try]: ... + def gen_lambda(self, args, body) -> ast.Lambda: ... + def gen_del_stmt(self, name_to_del) -> ast.Delete: ... + def transform_slice(self, slice_): ... + def isAllowedName(self, node, name) -> None: ... + def check_function_argument_names(self, node) -> None: ... + def check_import_names(self, node) -> ast.AST: ... + def gen_attr_check(self, node, attr_name) -> ast.BoolOp: ... + def visit_Constant(self, node) -> ast.AST: ... + def visit_Name(self, node) -> ast.AST: ... + def visit_Call(self, node) -> ast.AST: ... + def visit_Attribute(self, node) -> ast.AST: ... + def visit_Subscript(self, node) -> ast.AST: ... + def visit_Assign(self, node): ... + def visit_AugAssign(self, node) -> ast.Assign: ... + # Bug in `reportlab`'s source code: + def visit_While(node): ... # type: ignore[override] + def visit_ExceptHandler(self, node) -> ast.AST: ... + def visit_With(self, node) -> ast.AST: ... + def visit_FunctionDef(self, node) -> ast.AST: ... + def visit_Lambda(self, node) -> ast.AST: ... + def visit_ClassDef(self, node) -> ast.stmt: ... + def visit_Import(self, node) -> ast.AST: ... + def visit_BinOp(self, node): ... + visit_ImportFrom = visit_Import # pyright: ignore[reportAssignmentType] + visit_For = guard_iter + visit_comprehension = guard_iter + def generic_visit(self, node: ast.AST) -> None: ... # type: ignore[override] + def not_allowed(self, node: ast.AST) -> Never: ... + def visit_children(self, node) -> ast.AST: ... + def visit(self, node): ... + visit_Ellipsis = not_allowed + visit_MatMult = not_allowed + visit_Exec = not_allowed + visit_Nonlocal = not_allowed + visit_AsyncFunctionDef = not_allowed + visit_Await = not_allowed + visit_AsyncFor = not_allowed + visit_AsyncWith = not_allowed + visit_Print = not_allowed + visit_Num = visit_children + visit_Str = visit_children + visit_Bytes = visit_children + visit_List = visit_children + visit_Tuple = visit_children + visit_Set = visit_children + visit_Dict = visit_children + visit_FormattedValue = visit_children + visit_JoinedStr = visit_children + visit_NameConstant = visit_children + visit_Load = visit_children + visit_Store = visit_children + visit_Del = visit_children + visit_Starred = visit_children + visit_Expression = visit_children + visit_Expr = visit_children + visit_UnaryOp = visit_children + visit_UAdd = visit_children + visit_USub = visit_children + visit_Not = visit_children + visit_Invert = visit_children + visit_Add = visit_children + visit_Sub = visit_children + visit_Mult = visit_children + visit_Div = visit_children + visit_FloorDiv = visit_children + visit_Pow = visit_children + visit_Mod = visit_children + visit_LShift = visit_children + visit_RShift = visit_children + visit_BitOr = visit_children + visit_BitXor = visit_children + visit_BitAnd = visit_children + visit_BoolOp = visit_children + visit_And = visit_children + visit_Or = visit_children + visit_Compare = visit_children + visit_Eq = visit_children + visit_NotEq = visit_children + visit_Lt = visit_children + visit_LtE = visit_children + visit_Gt = visit_children + visit_GtE = visit_children + visit_Is = visit_children + visit_IsNot = visit_children + visit_In = visit_children + visit_NotIn = visit_children + visit_keyword = visit_children + visit_IfExp = visit_children + visit_Index = visit_children + visit_Slice = visit_children + visit_ExtSlice = visit_children + visit_ListComp = visit_children + visit_SetComp = visit_children + visit_GeneratorExp = visit_children + visit_DictComp = visit_children + visit_Raise = visit_children + visit_Assert = visit_children + visit_Delete = visit_children + visit_Pass = visit_children + visit_alias = visit_children + visit_If = visit_children + visit_Break = visit_children + visit_Continue = visit_children + visit_Try = visit_children + visit_TryFinally = visit_children + visit_TryExcept = visit_children + visit_withitem = visit_children + visit_arguments = visit_children + visit_arg = visit_children + visit_Return = visit_children + visit_Yield = visit_children + visit_YieldFrom = visit_children + visit_Global = visit_children + visit_Module = visit_children + visit_Param = visit_children + +def astFormat(node): ... + +class __rl_SafeIter__: + __rl_iter__: Incomplete + __rl_owner__: Incomplete + def __init__(self, it, owner) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self): ... + next = __next__ + +__rl_safe_builtins__: Incomplete + +def safer_globals(g=None): ... + +math_log10 = math.log10 +__rl_undef__: Incomplete + +class __RL_SAFE_ENV__: + __time_time__ = time.time + __weakref_ref__: Incomplete + __slicetype__: Incomplete + timeout: Incomplete + allowed_magic_methods: Incomplete + __rl_gen_range__: Incomplete + __rl_real_iter__: Incomplete + real_bi: Incomplete + bi_replace: Incomplete + __rl_builtins__: Incomplete + def __init__(self, timeout=None, allowed_magic_methods=None, allowed_magic_names=None) -> None: ... + def __rl_type__(self, *args): ... + def __rl_check__(self) -> None: ... + def __rl_sd__(self, obj): ... + def __rl_getiter__(self, it): ... + def __rl_max__(self, arg, *args, **kwds): ... + def __rl_min__(self, arg, *args, **kwds): ... + def __rl_sum__(self, sequence, start: int = 0): ... + def __rl_enumerate__(self, seq): ... + def __rl_zip__(self, *args): ... + def __rl_hasattr__(self, obj, name): ... + def __rl_filter__(self, f, seq): ... + def __rl_map__(self, f, seq): ... + def __rl_any__(self, seq): ... + def __rl_all__(self, seq): ... + def __rl_sorted__(self, seq, **kwds): ... + def __rl_reversed__(self, seq): ... + def __rl_range__(self, start, *args): ... + def __rl_set__(self, it): ... + def __rl_frozenset__(self, it=()): ... + def __rl_iter_unpack_sequence__(self, it, spec, _getiter_) -> Generator[Incomplete]: ... + def __rl_unpack_sequence__(self, it, spec, _getiter_): ... + def __rl_is_allowed_name__(self, name, crash: bool = True) -> bool: ... + def __rl_getattr__(self, obj, a, *args): ... + def __rl_getitem__(self, obj, a): ... + __rl_tmax__: int + __rl_max_len__: int + __rl_max_pow_digits__: int + def __rl_add__(self, a, b): ... + def __rl_mult__(self, a, b): ... + def __rl_pow__(self, a, b): ... + def __rl_augAssign__(self, op, v, i): ... + def __rl_apply__(self, func, args, kwds): ... + def __rl_args_iter__(self, *args): ... + def __rl_list__(self, it): ... + def __rl_compile__( + self, src, fname: str = "", mode: str = "eval", flags: int = 0, inherit: bool = True, visit=None + ): ... + __rl_limit__: Incomplete + def __rl_safe_eval__( + self, expr, g, l, mode, timeout=None, allowed_magic_methods=None, __frame_depth__: int = 3, allowed_magic_names=None + ): ... + +class __rl_safe_eval__: + mode: str + env: Incomplete + def __init__(self) -> None: ... + def __call__(self, expr, g=None, l=None, timeout=None, allowed_magic_methods=None, allowed_magic_names=None): ... + +class __rl_safe_exec__(__rl_safe_eval__): + mode: str + +def rl_extended_literal_eval(expr, safe_callables=None, safe_names=None): ... + +rl_safe_exec: __rl_safe_exec__ +rl_safe_eval: __rl_safe_eval__ + +def __fix_set__(value, default=...): ... +def rl_less_safe_eval(expr, NS): ... diff --git a/stubs/reportlab/reportlab/lib/rltempfile.pyi b/stubs/reportlab/reportlab/lib/rltempfile.pyi new file mode 100644 index 000000000000..24b270ff237c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rltempfile.pyi @@ -0,0 +1,4 @@ +def get_rl_tempdir(*subdirs: str) -> str: ... +def get_rl_tempfile(fn: str | None = None) -> str: ... + +__all__ = ("get_rl_tempdir", "get_rl_tempdir") diff --git a/stubs/reportlab/reportlab/lib/rparsexml.pyi b/stubs/reportlab/reportlab/lib/rparsexml.pyi new file mode 100644 index 000000000000..5feac4c061e5 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/rparsexml.pyi @@ -0,0 +1,35 @@ +from _typeshed import FileDescriptorOrPath, Unused +from collections.abc import Iterable +from typing import Final, type_check_only + +RequirePyRXP: int +simpleparse: int + +@type_check_only +class _smartDecode: + @staticmethod + def __call__(s: str | bytes | bytearray) -> str: ... + +smartDecode: _smartDecode +NONAME: Final = "" +NAMEKEY: Final = 0 +CONTENTSKEY: Final = 1 +CDATAMARKER: Final = "" +replacelist: list[tuple[str, str]] + +def unEscapeContentList(contentList: Iterable[str]) -> list[str]: ... +def parsexmlSimple(xmltext, oneOutermostTag: int = 0, eoCB: Unused = None, entityReplacer=...): ... + +parsexml = parsexmlSimple + +def parseFile(filename: FileDescriptorOrPath): ... + +verbose: int + +def skip_prologue(text, cursor): ... +def parsexml0(xmltext, startingat: int = 0, toplevel: int = 1, entityReplacer=...): ... +def pprettyprint(parsedxml): ... +def testparse(s, dump: int = 0) -> None: ... +def test(dump: int = 0) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/sequencer.pyi b/stubs/reportlab/reportlab/lib/sequencer.pyi new file mode 100644 index 000000000000..f7fd2029ba72 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/sequencer.pyi @@ -0,0 +1,39 @@ +from collections.abc import Callable + +__all__ = ["Sequencer", "getSequencer", "setSequencer"] + +from typing import overload + +class _Counter: + _value: int + def __init__(self) -> None: ... + def setFormatter(self, formatFunc: Callable[[int], str]) -> None: ... + def reset(self, value: int | None = None) -> None: ... + def next(self) -> int: ... + __next__ = next + def _this(self) -> int: ... + def nextf(self) -> str: ... + def thisf(self) -> str: ... + def chain(self, otherCounter: _Counter) -> None: ... + +class Sequencer: + def __init__(self) -> None: ... + def __next__(self) -> int: ... + def next(self, counter=None) -> int: ... + def thisf(self, counter=None) -> str: ... + def nextf(self, counter=None) -> str: ... + def setDefaultCounter(self, default=None) -> None: ... + def registerFormat(self, format: str, func: Callable[[int], str]) -> None: ... + def setFormat(self, counter, format: str) -> None: ... + def reset(self, counter=None, base: int = 0) -> None: ... + def chain(self, parent, child) -> None: ... + def __getitem__(self, key: str) -> str: ... + def format(self, template: str) -> str: ... + def dump(self) -> None: ... + +def getSequencer() -> Sequencer: ... + +@overload +def setSequencer(seq: Sequencer) -> Sequencer: ... +@overload +def setSequencer(seq: None) -> None: ... diff --git a/stubs/reportlab/reportlab/lib/styles.pyi b/stubs/reportlab/reportlab/lib/styles.pyi new file mode 100644 index 000000000000..6e550700e5eb --- /dev/null +++ b/stubs/reportlab/reportlab/lib/styles.pyi @@ -0,0 +1,185 @@ +from _typeshed import Incomplete +from typing import Any, ClassVar, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from reportlab.lib.colors import Color + +_AlignmentEnum: TypeAlias = Literal[0, 1, 2, 4] +# FIXME: There are some places in the code that expect upper-case versions +# so I'm unsure whether those would work in stylesheets as well +_AlignmentStr: TypeAlias = Literal["left", "center", "centre", "right", "justify"] +_Alignment: TypeAlias = _AlignmentEnum | _AlignmentStr +_T = TypeVar("_T") + +class PropertySet: + defaults: ClassVar[dict[str, Any]] + name: str + parent: PropertySet | None + def __init__(self, name: str, parent: PropertySet | None = None, **kw: Any) -> None: ... + def refresh(self) -> None: ... + def listAttrs(self, indent: str = "") -> None: ... + def clone(self, name: str, parent: PropertySet | None = None, **kwds: Any) -> Self: ... + # PropertySet can have arbitrary attributes + def __getattr__(self, name: str) -> Any: ... + def __setattr__(self, name: str, value: Any) -> None: ... + +class ParagraphStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: _Alignment + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: Color + backColor: Color | None + wordWrap: Incomplete | None + borderWidth: float + borderPadding: float + borderColor: Color | None + borderRadius: float | None + allowWidows: Incomplete + allowOrphans: Incomplete + textTransform: Incomplete | None + endDots: Incomplete | None + splitLongWords: Incomplete + underlineWidth: float + bulletAnchor: Literal["start", "middle", "end"] | float + justifyLastLine: Incomplete + justifyBreaks: Incomplete + spaceShrinkage: float + strikeWidth: float + underlineOffset: float + underlineGap: float + strikeOffset: float + strikeGap: float + linkUnderline: Incomplete + underlineColor: Color | None + strikeColor: Color | None + hyphenationLang: str + embeddedHyphenation: Incomplete + uriWasteReduce: float + # NOTE: We redefine __init__ for the same reason + def __init__( + self, + name: str, + parent: PropertySet | None = None, + *, + fontName: str = ..., + fontSize: float = ..., + leading: float = ..., + leftIndent: float = ..., + rightIndent: float = ..., + firstLineIndent: float = ..., + alignment: _Alignment = ..., + spaceBefore: float = ..., + spaceAfter: float = ..., + bulletFontName: str = ..., + bulletFontSize: float = ..., + bulletIndent: float = ..., + textColor: Color = ..., + backColor: Color | None = ..., + wordWrap: Incomplete | None = ..., + borderWidth: float = ..., + borderPadding: float = ..., + borderColor: Color | None = ..., + borderRadius: float | None = ..., + allowWidows=..., + allowOrphans=..., + textTransform: Incomplete | None = ..., + endDots: Incomplete | None = ..., + splitLongWords=..., + underlineWidth: float = ..., + bulletAnchor: Literal["start", "middle", "end"] | float = ..., + justifyLastLine=..., + justifyBreaks=..., + spaceShrinkage: float = ..., + strikeWidth: float = ..., + underlineOffset: float = ..., + underlineGap: float = ..., + strikeOffset: float = ..., + strikeGap: float = ..., + linkUnderline=..., + underlineColor: Color | None = ..., + strikeColor: Color | None = ..., + hyphenationLang: str = ..., + embeddedHyphenation=..., + uriWasteReduce: float = ..., + **kw: Any, + ) -> None: ... + +def str2alignment( + v: _AlignmentStr, + __map__: dict[_AlignmentStr, _AlignmentEnum] = {"centre": 1, "center": 1, "left": 0, "right": 2, "justify": 4}, +) -> _AlignmentEnum: ... + +class LineStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + width: float + color: Color + def prepareCanvas(self, canvas) -> None: ... + # NOTE: We redefine __init__ for the same reason + def __init__( + self, name: str, parent: PropertySet | None = None, *, width: float = ..., color: Color = ..., **kw: Any + ) -> None: ... + +class ListStyle(PropertySet): + # NOTE: We list the attributes this has for sure due to defaults + leftIndent: float + rightIndent: float + bulletAlign: _Alignment + bulletType: str + bulletColor: Color + bulletFontName: str + bulletFontSize: float + bulletOffsetY: float + bulletDedent: Incomplete + bulletDir: Incomplete + bulletFormat: Incomplete | None + start: Incomplete | None + # NOTE: We redefine __init__ for the same reason + def __init__( + self, + name: str, + parent: PropertySet | None = None, + *, + leftIndent: float = ..., + rightIndent: float = ..., + bulletAlign: _Alignment = ..., + bulletType: str = ..., + bulletColor: Color = ..., + bulletFontName: str = ..., + bulletFontSize: float = ..., + bulletOffsetY: float = ..., + bulletDedent=..., + bulletDir=..., + bulletFormat: Incomplete | None = ..., + start: Incomplete | None = ..., + **kw: Any, + ) -> None: ... + +class StyleSheet1: + byName: dict[str, PropertySet] + byAlias: dict[str, PropertySet] + def __init__(self) -> None: ... + def __getitem__(self, key: str) -> PropertySet: ... + + @overload + def get(self, key: str) -> PropertySet: ... + @overload + def get(self, key: str, default: _T) -> PropertySet | _T: ... + + def __contains__(self, key: str) -> bool: ... + def has_key(self, key: str) -> bool: ... + def add(self, style: PropertySet, alias: str | None = None) -> None: ... + def list(self) -> None: ... + +def getSampleStyleSheet() -> StyleSheet1: ... + +__all__ = ("PropertySet", "ParagraphStyle", "str2alignment", "LineStyle", "ListStyle", "StyleSheet1", "getSampleStyleSheet") diff --git a/stubs/reportlab/reportlab/lib/testutils.pyi b/stubs/reportlab/reportlab/lib/testutils.pyi new file mode 100644 index 000000000000..7a55147e3739 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/testutils.pyi @@ -0,0 +1,74 @@ +import re +import unittest +from _typeshed import Incomplete, StrPath, Unused +from configparser import ConfigParser, _SectionName +from types import ModuleType +from typing import Final, Literal + +__version__: Final[str] + +def invariantSeed(n: float | str | bytes | bytearray | None) -> None: ... +def haveRenderPM() -> ModuleType | Literal[False]: ... + +DEJAVUSANS: Final = ("DejaVuSans", "DejaVuSans-Bold", "DejaVuSans-Oblique", "DejaVuSans-BoldOblique") + +def haveDejaVu() -> bool: ... +def isWritable(D: Unused) -> Literal[0, 1]: ... + +RL_HOME: str | None +testsFolder: str | None + +def setOutDir(name: str) -> str: ... +def mockUrlRead(name: str): ... +def outputfile(fn: StrPath | None) -> str: ... +def printLocation(depth: int = 1) -> None: ... +def makeSuiteForClasses(*classes: type[unittest.TestCase], testMethodPrefix: str | None = None) -> unittest.TestSuite: ... +def getCVSEntries(folder: StrPath, files: bool | Literal[1, 0] = 1, folders: bool | Literal[1, 0] = 0) -> list[str]: ... + +class ExtConfigParser(ConfigParser): + pat: re.Pattern[str] + def getstringlist(self, section: _SectionName, option: str): ... + +class GlobDirectoryWalker: + index: int + pattern: str + stack: list[str] + files: list[str] + directory: str + def __init__(self, directory: str, pattern: str = "*") -> None: ... + def __getitem__(self, index) -> str | None: ... + def filterFiles(self, folder, files): ... + +class RestrictedGlobDirectoryWalker(GlobDirectoryWalker): + ignorePatterns: Incomplete + def __init__(self, directory, pattern: str = "*", ignore=None) -> None: ... + def filterFiles(self, folder, files): ... + +class CVSGlobDirectoryWalker(GlobDirectoryWalker): + def filterFiles(self, folder, files): ... + +class SecureTestCase(unittest.TestCase): + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + +class NearTestCase(unittest.TestCase): + @staticmethod + def assertNear(a, b, accuracy: float = 1e-05) -> None: ... + +class ScriptThatMakesFileTest(unittest.TestCase): + scriptDir: Incomplete + scriptName: Incomplete + outFileName: Incomplete + verbose: Incomplete + def __init__(self, scriptDir, scriptName, outFileName, verbose: int = 0) -> None: ... + cwd: Incomplete + def setUp(self) -> None: ... + def tearDown(self) -> None: ... + def runTest(self) -> None: ... + +def equalStrings(a: str | bytes, b: str | bytes, enc: str = "utf8") -> bool: ... +def eqCheck(r, x) -> None: ... +def rlextraNeeded() -> bool: ... +def rlSkipIf(cond, reason, __module__=None): ... +def rlSkipUnless(cond, reason, __module__=None): ... +def rlSkip(reason, __module__=None): ... diff --git a/stubs/reportlab/reportlab/lib/textsplit.pyi b/stubs/reportlab/reportlab/lib/textsplit.pyi new file mode 100644 index 000000000000..8ad3489c99a2 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/textsplit.pyi @@ -0,0 +1,20 @@ +import re +from _typeshed import Incomplete, ReadableBuffer +from collections.abc import Sequence +from typing import Final + +__version__: Final[str] +CANNOT_START_LINE: Final[Sequence[str]] +ALL_CANNOT_START: Final[str] +CANNOT_END_LINE: Final[Sequence[str]] +ALL_CANNOT_END: Final[str] + +def is_multi_byte(ch: str | bytes | bytearray) -> bool: ... +def getCharWidths(word: str, fontName: str, fontSize: float) -> list[float]: ... +def wordSplit(word, maxWidths, fontName, fontSize, encoding: str = "utf8") -> list[list[Incomplete]]: ... +def dumbSplit(word, widths, maxWidths) -> list[list[Incomplete]]: ... +def kinsokuShoriSplit(word, widths, availWidth) -> None: ... + +rx: re.Pattern[str] + +def cjkwrap(text: ReadableBuffer, width: float, encoding: str = "utf8"): ... diff --git a/stubs/reportlab/reportlab/lib/units.pyi b/stubs/reportlab/reportlab/lib/units.pyi new file mode 100644 index 000000000000..c22f629a211c --- /dev/null +++ b/stubs/reportlab/reportlab/lib/units.pyi @@ -0,0 +1,9 @@ +from typing import Final + +__version__: Final[str] +inch: Final[float] +cm: Final[float] +mm: Final[float] +pica: Final[float] + +def toLength(s: str) -> float: ... diff --git a/stubs/reportlab/reportlab/lib/utils.pyi b/stubs/reportlab/reportlab/lib/utils.pyi new file mode 100644 index 000000000000..6ea6a6d1ea32 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/utils.pyi @@ -0,0 +1,221 @@ +import datetime as _datetime +import zipimport +from _typeshed import Incomplete, SupportsItems +from builtins import _ClassInfo +from collections.abc import Generator, Iterable, MutableMapping +from os import PathLike +from time import _TimeTuple, struct_time +from types import TracebackType +from typing import AnyStr, Final, Literal, TypeVar, overload, type_check_only +from typing_extensions import TypeIs +from urllib.request import _UrlopenRet + +from reportlab.lib.rltempfile import get_rl_tempdir as get_rl_tempdir, get_rl_tempfile as get_rl_tempfile + +from .rl_safe_eval import ( + rl_extended_literal_eval as rl_extended_literal_eval, + rl_safe_exec as rl_safe_exec, + safer_globals as safer_globals, +) + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + +__version__: Final[str] + +@type_check_only +class _UNSET_: + @staticmethod + def __bool__() -> Literal[False]: ... + +__UNSET__: Final[_UNSET_] + +isPyPy: bool + +def isFunction(v: object) -> bool: ... +def isMethod(v: object, mt: type = ...) -> bool: ... +def isModule(v: object) -> bool: ... +def isSeq(v: object, _st: _ClassInfo = ...) -> bool: ... +def isNative(v: object) -> TypeIs[str]: ... + +strTypes: tuple[type[str], type[bytes]] + +def asBytes(v: str | bytes, enc: str = "utf8") -> bytes: ... +def asUnicode(v: str | bytes, enc: str = "utf8") -> str: ... +def asUnicodeEx(v: str | bytes, enc: str = "utf8") -> str: ... +def asNative(v: str | bytes, enc: str = "utf8") -> str: ... +def int2Byte(i: int) -> bytes: ... +def isStr(v: object) -> TypeIs[str | bytes]: ... +def isBytes(v: object) -> TypeIs[bytes]: ... +def isUnicode(v: object) -> TypeIs[str]: ... +def isClass(v: object) -> TypeIs[type]: ... +def isNonPrimitiveInstance(x: object) -> bool: ... +def instantiated(v: object) -> bool: ... +def bytestr(x: object, enc: str = "utf8") -> bytes: ... +def encode_label(args) -> str: ... +def decode_label(label: str): ... +def rawUnicode(s: str | bytes) -> str: ... +def rawBytes(s: str | bytes) -> bytes: ... + +rl_exec = exec + +def char2int(s: int | str | bytes) -> int: ... +def rl_reraise(t, v: BaseException, b: TracebackType | None = None) -> None: ... +def rl_add_builtins(**kwd) -> None: ... +def zipImported(ldr: zipimport.zipimporter | None = None) -> zipimport.zipimporter | None: ... + +class CIDict(dict[_KT, _VT]): + def __init__(self, *args, **kwds) -> None: ... + def update(self, D: SupportsItems[_KT, _VT]) -> None: ... # type: ignore[override] + +def markfilename(filename, creatorcode=None, filetype=None): ... + +__rl_loader__: Incomplete + +def rl_glob(pattern: AnyStr, glob=...) -> list[AnyStr]: ... +def isFileSystemDistro() -> bool: ... +def isCompactDistro() -> bool: ... +def isSourceDistro() -> bool: ... +def normalize_path(p: PathLike[AnyStr]) -> PathLike[AnyStr]: ... +def recursiveImport(modulename, baseDir=None, noCWD: int = 0, debug: int = 0): ... + +haveImages: Final[bool] + +class ArgvDictValue: + value: Incomplete + func: Incomplete + def __init__(self, value, func) -> None: ... + +def getArgvDict(**kw): ... +def getHyphenater(hDict=None): ... +def open_for_read_by_name(name, mode: str = "b"): ... +def rlUrlRead(name: str, headers: MutableMapping[str, str] | None = None) -> _UrlopenRet: ... +def open_for_read(name, mode: str = "b"): ... +def open_and_read(name, mode: str = "b"): ... +def open_and_readlines(name, mode: str = "t"): ... +def rl_isfile(fn, os_path_isfile=...): ... +def rl_isdir(pn, os_path_isdir=..., os_path_normpath=...): ... +def rl_listdir(pn, os_path_isdir=..., os_path_normpath=..., os_listdir=...): ... +def rl_getmtime(pn, os_path_isfile=..., os_path_normpath=..., os_path_getmtime=..., time_mktime=...): ... +def __rl_get_module__(name, dir): ... +def rl_get_module(name, dir): ... + +class ImageReader: + fileName: Incomplete + fp: Incomplete + def __init__(self, fileName, ident=None) -> None: ... + def identity(self) -> str: ... + @classmethod + def check_pil_image_size(cls, im) -> None: ... + @classmethod + def set_max_image_size(cls, max_image_size=None) -> None: ... + def jpeg_fh(self) -> None: ... + def getSize(self) -> tuple[int, int]: ... + mode: Incomplete + def getRGBData(self): ... + def getImageData(self): ... + def getTransparent(self): ... + +class LazyImageReader(ImageReader): ... + +def getImageData(imageFileName): ... + +class DebugMemo: + fn: Incomplete + stdout: Incomplete + store: Incomplete + def __init__( + self, + fn: str = "rl_dbgmemo.dbg", + mode: str = "w", + getScript: int = 1, + modules=(), + capture_traceback: int = 1, + stdout=None, + **kw, + ) -> None: ... + def add(self, **kw) -> None: ... + def dump(self) -> None: ... + def dumps(self): ... + def load(self) -> None: ... + def loads(self, s) -> None: ... + specials: Incomplete + def show(self) -> None: ... + def payload(self, name): ... + def __setitem__(self, name, value) -> None: ... + def __getitem__(self, name): ... + +def flatten(L): ... +def find_locals(func, depth: int = 0): ... + +class _FmtSelfDict: + obj: Incomplete + def __init__(self, obj, overrideArgs) -> None: ... + def __getitem__(self, k): ... + +class FmtSelfDict: ... + +def simpleSplit(text: str | bytes, fontName: str | None, fontSize: float, maxWidth: float | None): ... + +@overload +def escapeTextOnce(text: None) -> None: ... +@overload +def escapeTextOnce(text: str | bytes) -> str: ... + +def fileName2FSEnc(fn): ... +def prev_this_next(items): ... +def commasplit(s: str | bytes) -> list[str]: ... +def commajoin(l: Iterable[str | bytes]) -> str: ... +def findInPaths(fn, paths, isfile: bool = True, fail: bool = False): ... +def annotateException(msg: str, enc: str = "utf8", postMsg: str = "", sep: str = " ") -> None: ... +def escapeOnce(data: str) -> str: ... + +class IdentStr(str): + def __new__(cls, value): ... + +class RLString(str): + def __new__(cls, v, **kwds): ... + +def makeFileName(s): ... + +class FixedOffsetTZ(_datetime.tzinfo): + def __init__(self, h: float, m: float, name: str | None) -> None: ... + def utcoffset(self, dt: _datetime.datetime | None) -> _datetime.timedelta: ... + def tzname(self, dt: _datetime.datetime | None) -> str | None: ... + def dst(self, dt: _datetime.datetime | None) -> _datetime.timedelta: ... + +class TimeStamp: + tzname: str + t: float + lt: struct_time | _TimeTuple + YMDhms: tuple[int, ...] + dhh: int + dmm: int + def __init__(self, invariant: int | bool | None = None) -> None: ... + @property + def datetime(self) -> _datetime.datetime: ... + @property + def asctime(self) -> str: ... + +def recursiveGetAttr(obj, name, g=None): ... +def recursiveSetAttr(obj, name, value) -> None: ... +def recursiveDelAttr(obj, name) -> None: ... +def yieldNoneSplits(L) -> Generator[Incomplete]: ... + +class KlassStore: + lim: int + store: dict[str, type] + def __init__(self, lim: int = 127) -> None: ... + def add(self, k: str, v: type) -> None: ... + def __contains__(self, k) -> bool: ... + def __getitem__(self, k: str) -> type: ... + def get(self, k, default=None): ... + +@type_check_only +class _rl_warn: + def __init__(self) -> None: ... + def __call__(self, message: str) -> None: ... + @property + def warnings_seen(self) -> dict[str, set[str]]: ... + +rl_warn: _rl_warn diff --git a/stubs/reportlab/reportlab/lib/validators.pyi b/stubs/reportlab/reportlab/lib/validators.pyi new file mode 100644 index 000000000000..a739cafe87df --- /dev/null +++ b/stubs/reportlab/reportlab/lib/validators.pyi @@ -0,0 +1,169 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +class Percentage(float): ... + +class Validator: + def __call__(self, x): ... + def normalize(self, x): ... + def normalizeTest(self, x): ... + +class _isAnything(Validator): + def test(self, x): ... + +class _isNothing(Validator): + def test(self, x): ... + +class _isBoolean(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isString(Validator): + def test(self, x): ... + +class _isCodec(Validator): + def test(self, x): ... + +class _isNumber(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isInt(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isNumberOrNone(_isNumber): + def test(self, x): ... + def normalize(self, x): ... + +class _isListOfNumbersOrNone(Validator): + def test(self, x): ... + +class isNumberInRange(_isNumber): + min: Incomplete + max: Incomplete + def __init__(self, min, max) -> None: ... + def test(self, x): ... + +class _isListOfShapes(Validator): + def test(self, x): ... + +class _isListOfStringsOrNone(Validator): + def test(self, x): ... + +class _isTransform(Validator): + def test(self, x): ... + +class _isColor(Validator): + def test(self, x): ... + +class _isColorOrNone(Validator): + def test(self, x): ... + +class _isNormalDate(Validator): + def test(self, x): ... + def normalize(self, x): ... + +class _isValidChild(Validator): + def test(self, x): ... + +class _isValidChildOrNone(_isValidChild): + def test(self, x): ... + +class _isCallable(Validator): + def test(self, x): ... + +class OneOf(Validator): + def __init__(self, enum, *args) -> None: ... + def test(self, x): ... + +class SequenceOf(Validator): + def __init__(self, elemTest, name=None, emptyOK: int = 1, NoneOK: int = 0, lo: int = 0, hi: int = 2147483647) -> None: ... + def test(self, x): ... + +class EitherOr(Validator): + def __init__(self, tests, name=None) -> None: ... + def test(self, x): ... + +class NoneOr(EitherOr): + def test(self, x): ... + +class NotSetOr(EitherOr): + def test(self, x): ... + @staticmethod + def conditionalValue(v, a): ... + +class _isNotSet(Validator): + def test(self, x): ... + +class Auto(Validator): + def __init__(self, **kw) -> None: ... + def test(self, x): ... + +class AutoOr(EitherOr): + def test(self, x): ... + +class isInstanceOf(Validator): + def __init__(self, klass=None) -> None: ... + def test(self, x): ... + +class isSubclassOf(Validator): + def __init__(self, klass=None) -> None: ... + def test(self, x): ... + +class matchesPattern(Validator): + def __init__(self, pattern) -> None: ... + def test(self, x): ... + +class DerivedValue: + def getValue(self, renderer, attr) -> None: ... + +class Inherit(DerivedValue): + def getValue(self, renderer, attr): ... + +inherit: Inherit + +class NumericAlign(str): + def __new__(cls, dp: str = ".", dpLen: int = 0): ... + +isAuto: Auto +isBoolean: _isBoolean +isString: _isString +isCodec: _isCodec +isNumber: _isNumber +isInt: _isInt +isNoneOrInt: NoneOr +isNumberOrNone: _isNumberOrNone +isTextAnchor: OneOf +isListOfNumbers: SequenceOf +isListOfNoneOrNumber: SequenceOf +isListOfListOfNoneOrNumber: SequenceOf +isListOfNumbersOrNone: _isListOfNumbersOrNone +isListOfShapes: _isListOfShapes +isListOfStrings: SequenceOf +isListOfStringsOrNone: _isListOfStringsOrNone +isTransform: _isTransform +isColor: _isColor +isListOfColors: SequenceOf +isColorOrNone: _isColorOrNone +isShape: _isValidChild +isValidChild: _isValidChild +isNoneOrShape: _isValidChildOrNone +isValidChildOrNone: _isValidChildOrNone +isAnything: _isAnything +isNothing: _isNothing +isXYCoord: SequenceOf +isBoxAnchor: OneOf +isNoneOrString: NoneOr +isNoneOrListOfNoneOrStrings: SequenceOf +isListOfNoneOrString: SequenceOf +isNoneOrListOfNoneOrNumbers: SequenceOf +isCallable: _isCallable +isNoneOrCallable: NoneOr +isStringOrCallable: EitherOr +isStringOrCallableOrNone: NoneOr +isStringOrNone: NoneOr +isNormalDate: _isNormalDate +isNotSet: _isNotSet diff --git a/stubs/reportlab/reportlab/lib/yaml.pyi b/stubs/reportlab/reportlab/lib/yaml.pyi new file mode 100644 index 000000000000..62cd8164c841 --- /dev/null +++ b/stubs/reportlab/reportlab/lib/yaml.pyi @@ -0,0 +1,27 @@ +from _typeshed import FileDescriptorOrPath +from typing import Final + +__version__: Final[str] +PLAIN: Final = 1 +PREFORMATTED: Final = 2 +BULLETCHAR: Final = "\267" + +class BaseParser: + def __init__(self) -> None: ... + def reset(self) -> None: ... + def parseFile(self, filename: FileDescriptorOrPath) -> list[tuple[str, str] | tuple[str, str, str]]: ... + def parseText(self, textBlock: str) -> list[tuple[str, str] | tuple[str, str, str]]: ... + def readLine(self, line: str) -> None: ... + def endPara(self) -> None: ... + def beginPre(self, stylename: str) -> None: ... + def endPre(self) -> None: ... + def image(self, filename: str) -> None: ... + +class Parser(BaseParser): + def vSpace(self, points) -> None: ... + def pageBreak(self) -> None: ... + def custom(self, moduleName: str, funcName: str) -> None: ... + def nextPageTemplate(self, templateName: str) -> None: ... + +def parseFile(filename: FileDescriptorOrPath) -> list[tuple[str, str] | tuple[str, str, str]]: ... +def parseText(textBlock: str) -> list[tuple[str, str] | tuple[str, str, str]]: ... diff --git a/stubs/reportlab/reportlab/pdfbase/__init__.pyi b/stubs/reportlab/reportlab/pdfbase/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/pdfbase/acroform.pyi b/stubs/reportlab/reportlab/pdfbase/acroform.pyi new file mode 100644 index 000000000000..aa8f2288ac84 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/acroform.pyi @@ -0,0 +1,340 @@ +from _typeshed import Incomplete +from weakref import ReferenceType + +from reportlab.lib.colors import Color +from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFObject, PDFStream + +__all__ = ("AcroForm",) + +visibilities: dict[str, int] +orientations: dict[str, list[Incomplete]] +fieldFlagValues: dict[str, int] +annotationFlagValues: dict[str, int] + +def bsPDF(borderWidth: int, borderStyle: str, dashLen) -> PDFDictionary: ... +def escPDF(s) -> str: ... +def makeFlags(s: int | str, d: dict[str, int] = ...) -> int: ... + +class PDFFromString(PDFObject): + def __init__(self, s: str | bytes) -> None: ... + def format(self, document) -> bytes: ... + +class RadioGroup(PDFObject): + TU: Incomplete + Ff: int + kids: list[Incomplete] + T: Incomplete + V: Incomplete + def __init__(self, name, tooltip: str = "", fieldFlags: str = "noToggleToOff required radio") -> None: ... + def format(self, doc) -> bytes: ... + +class AcroForm(PDFObject): + formFontNames: dict[str, str] + referenceMap: dict[Incomplete, Incomplete] + fonts: dict[str, str] + fields: list[Incomplete] + sigFlags: Incomplete + extras: dict[Incomplete, Incomplete] + def __init__(self, canv, **kwds) -> None: ... + @property + def useDefault(self) -> object: ... + @property + def canv(self) -> ReferenceType[Incomplete]: ... + def fontRef(self, f) -> str: ... + def format(self, doc) -> bytes: ... + def colorTuple(self, c): ... + def streamFillColor(self, c) -> str: ... + def streamStrokeColor(self, c) -> str: ... + def checkboxAP( + self, + key, + value, + buttonStyle: str = "circle", + shape: str = "square", + fillColor=None, + borderColor=None, + textColor=None, + borderWidth: int | None = None, + borderStyle: str = "solid", + size: int = 20, + dashLen: int = 3, + ) -> PDFStream: ... + @staticmethod + def circleArcStream(size, r, arcs=(0, 1, 2, 3), rotated: bool = False) -> str: ... + def zdMark(self, c, size, ds, iFontName) -> str: ... + def getRef(self, obj): ... + def getRefStr(self, obj) -> str: ... + def setDefault(self, name: str, value: Color | float | None) -> None: ... + def getDefaults( + self, textColor, borderColor, fillColor, borderWidth + ) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete]: ... + @staticmethod + def varyColors(key, t, b, f) -> tuple[Incomplete, Incomplete, Incomplete]: ... + def checkForceBorder( + self, x, y, width, height, forceBorder, shape, borderStyle, borderWidth, borderColor, fillColor + ) -> None: ... + def checkbox( + self, + checked: bool = False, + buttonStyle: str = "check", + shape: str = "square", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "required", + forceBorder: bool = False, + relative: bool = False, + dashLen: int = 3, + ) -> None: ... + def radio( + self, + value=None, + selected: bool = False, + buttonStyle: str = "circle", + shape: str = "circle", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "noToggleToOff required radio", + forceBorder: bool = False, + relative: bool = False, + dashLen: int = 3, + ) -> None: ... + def makeStream(self, width, height, stream, **D) -> PDFStream: ... + def txAP( + self, + key, + value, + iFontName, + rFontName, + fontSize, + shape: str = "square", + fillColor=None, + borderColor=None, + textColor=None, + borderWidth: int | None = None, + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + dashLen: int = 3, + wkind: str = "textfield", + labels=[], + I=[], + sel_bg: str = "0.600006 0.756866 0.854904 rg", + sel_fg: str = "0 g", + ) -> PDFStream: ... + def makeFont(self, fontName: str | None) -> tuple[str, str]: ... + def textfield( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + relative: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def listbox( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + relative: bool = False, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + maxlen=None, + options=[], + ) -> None: ... + def choice( + self, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "combo", + forceBorder: bool = False, + relative: bool = False, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + maxlen=None, + options=[], + ) -> None: ... + def checkboxRelative( + self, + *, + checked: bool = False, + buttonStyle: str = "check", + shape: str = "square", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "required", + forceBorder: bool = False, + dashLen: int = 3, + ) -> None: ... + def radioRelative( + self, + *, + value=None, + selected: bool = False, + buttonStyle: str = "circle", + shape: str = "circle", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + size: int = 20, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "noToggleToOff required radio", + forceBorder: bool = False, + dashLen: int = 3, + ) -> None: ... + def textfieldRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def listboxRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + def choiceRelative( + self, + *, + value: str = "", + fillColor=..., + borderColor=..., + textColor=..., + borderWidth: int = ..., + borderStyle: str = "solid", + width: int = 120, + height: int = 36, + x: int = 0, + y: int = 0, + tooltip=None, + name=None, + annotationFlags: str = "print", + fieldFlags: str = "", + forceBorder: bool = False, + maxlen: int = 100, + fontName: str | None = None, + fontSize=None, + dashLen: int = 3, + ) -> None: ... + @property + def encRefStr(self) -> str: ... + +class CBMark: + opNames: list[str] + opCount: tuple[int, ...] + ops: Incomplete + xmin: Incomplete + ymin: Incomplete + xmax: Incomplete + ymax: Incomplete + points: Incomplete + slack: Incomplete + def __init__(self, ops, points, bounds, slack: float = 0.05) -> None: ... + def scaledRender(self, size, ds: int = 0) -> str: ... diff --git a/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi b/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi new file mode 100644 index 000000000000..3d84603c4682 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/cidfonts.pyi @@ -0,0 +1,52 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +from reportlab.pdfbase import pdfmetrics + +__version__: Final[str] +DISABLE_CMAP: bool + +def findCMapFile(name: str) -> str: ... +def structToPDF(structure): ... + +class CIDEncoding(pdfmetrics.Encoding): + name: Incomplete + source: str | None + def __init__(self, name, useCache: bool | Literal[0, 1] = 1) -> None: ... + def parseCMAPFile(self, name) -> None: ... + def translate(self, text) -> list[Incomplete]: ... + def fastSave(self, directory) -> None: ... + def fastLoad(self, directory) -> None: ... + def getData(self) -> dict[str, Incomplete]: ... + +class CIDTypeFace(pdfmetrics.TypeFace): + def __init__(self, name) -> None: ... + def getCharWidth(self, characterId): ... + +class CIDFont(pdfmetrics.Font): + faceName: Incomplete + face: CIDTypeFace + encodingName: Incomplete + encoding: CIDEncoding + fontName: Incomplete + name: Incomplete + isVertical: bool + substitutionFonts: list[Incomplete] + def __init__(self, face, encoding) -> None: ... + def formatForPdf(self, text) -> str: ... + def stringWidth(self, text, size, encoding=None) -> float: ... + def addObjects(self, doc) -> None: ... + +class UnicodeCIDFont(CIDFont): + language: str + name: Incomplete + fontName: Incomplete + vertical: bool + isHalfWidth: bool + unicodeWidths: Incomplete + def __init__(self, face: str, isVertical: bool = False, isHalfWidth: bool = False) -> None: ... + def formatForPdf(self, text) -> str: ... + def stringWidth(self, text, size, encoding=None) -> float: ... + +def precalculate(cmapdir) -> None: ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi b/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi new file mode 100644 index 000000000000..27cc2bc543ea --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfdoc.pyi @@ -0,0 +1,633 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Callable, Iterable, Mapping +from typing import Any, Final, Literal, TypeVar, overload + +_T = TypeVar("_T") + +__version__: Final[str] + +class PDFError(Exception): ... + +__InternalName__: Final[str] +__RefOnly__: Final[str] +__Comment__: Final[str] +BasicFonts: Final[str] +Pages: Final[str] +PDF_VERSION_DEFAULT: Final[tuple[int, int]] +PDF_SUPPORT_VERSION: Final[Mapping[str, tuple[int, int]]] + +def pdfdocEnc(x: str | _T) -> bytes | _T: ... +def format(element, document, toplevel: bool | Literal[0, 1] = 0): ... +def xObjectName(externalname: str) -> str: ... + +formName = xObjectName + +class NoEncryption: + def encode(self, t): ... + def prepare(self, document) -> None: ... + def register(self, objnum, version) -> None: ... + def info(self) -> None: ... + +class PDFObject: ... + +class DummyDoc(PDFObject): + encrypt: NoEncryption + +class PDFDocument(PDFObject): + defaultStreamFilters: Incomplete + encrypt: NoEncryption + objectcounter: int + shadingCounter: int + inObject: str | None + pageCounter: int + invariant: bool | Literal[0, 1] + idToObjectNumberAndVersion: dict[str, tuple[int, int]] + idToObject: dict[str, PDFObject] + idToOffset: dict[Incomplete, Incomplete] + numberToId: dict[int, str] + outline: PDFOutlines0 | PDFOutlines + Outlines: PDFOutlines0 | PDFOutlines + info: PDFInfo + fontMapping: dict[Incomplete, Incomplete] + delayedFonts: list[Incomplete] + def __init__( + self, + dummyoutline: bool | Literal[0, 1] | None = 0, + compression: bool | Literal[0, 1] | None = 1, + invariant: bool | Literal[0, 1] | None = 0, + filename=None, + pdfVersion=(1, 3), + lang=None, + ) -> None: ... + compression: bool | Literal[0, 1] | None + def setCompression(self, onoff: bool | Literal[0, 1] | None) -> None: ... + def ensureMinPdfVersion(self, *keys: str) -> None: ... + def updateSignature(self, thing) -> None: ... + def ID(self) -> bytes: ... + def SaveToFile(self, filename, canvas) -> None: ... + def GetPDFData(self, canvas) -> bytes: ... + def inPage(self) -> None: ... + def inForm(self) -> None: ... + def getInternalFontName(self, psfontname: str): ... + def thisPageName(self) -> str: ... + def thisPageRef(self) -> PDFObjectReference: ... + def addPage(self, page) -> None: ... + def addForm(self, name, form) -> None: ... + def annotationName(self, externalname) -> str: ... + def addAnnotation(self, name, annotation) -> None: ... + def refAnnotation(self, name) -> PDFObjectReference: ... + def addShading(self, shading) -> str: ... + def addColor(self, cmyk) -> tuple[Incomplete, Incomplete]: ... + def setTitle(self, title) -> None: ... + def setAuthor(self, author) -> None: ... + def setSubject(self, subject) -> None: ... + def setCreator(self, creator) -> None: ... + def setProducer(self, producer) -> None: ... + def setKeywords(self, keywords) -> None: ... + def setDateFormatter(self, dateFormatter) -> None: ... + def getAvailableFonts(self) -> list[Incomplete]: ... + __accum__: PDFFile + def format(self) -> bytes: ... + def hasForm(self, name: str) -> bool: ... + def getFormBBox(self, name: str, boxType: str = "MediaBox"): ... + def getXObjectName(self, name: str) -> str: ... + def xobjDict(self, formnames: Iterable[str]) -> PDFDictionary: ... + def Reference(self, obj, name=None): ... + +PDFtrue: Final = "true" +PDFfalse: Final = "false" +PDFnull: Final = "null" + +class PDFText(PDFObject): + t: Incomplete + enc: str + def __init__(self, t, enc: str = "utf-8") -> None: ... + def format(self, document) -> bytes: ... + +def PDFnumber(n: _T) -> _T: ... + +class PDFString(PDFObject): + unicodeEncValid: bool + s: str | bytes + escape: int + enc: str + def __init__(self, s: str | bytes | PDFString, escape: int = 1, enc: str = "auto") -> None: ... + def format(self, document) -> bytes: ... + +def PDFName(data, lo="!", hi="~") -> str: ... + +class PDFDictionary(PDFObject): + multiline: bool + dict: Incomplete + def __init__(self, dict=None) -> None: ... + def __setitem__(self, name, value) -> None: ... + def __getitem__(self, a): ... + def __contains__(self, a) -> bool: ... + def Reference(self, name, document) -> None: ... + def format(self, document, IND: bytes = b"\n ") -> bytes: ... + def copy(self) -> PDFDictionary: ... + def normalize(self) -> None: ... + +class checkPDFNames: + names: list[str] + def __init__(self, *names) -> None: ... + def __call__(self, value: str) -> str | None: ... + +@overload +def checkPDFBoolean(value: Literal["true"]) -> Literal["true"]: ... +@overload +def checkPDFBoolean(value: Literal["false"]) -> Literal["false"]: ... +@overload +def checkPDFBoolean(value: Any) -> None: ... + +class CheckedPDFDictionary(PDFDictionary): + validate: dict[str, Incomplete] + def __init__(self, dict=None, validate: dict[str, Incomplete] | None = None) -> None: ... + def __setitem__(self, name, value) -> None: ... + +class ViewerPreferencesPDFDictionary(CheckedPDFDictionary): + validate: dict[str, Incomplete] + +class PDFStreamFilterZCompress: + pdfname: str + def encode(self, text) -> bytes: ... + def decode(self, encoded) -> bytes: ... + +PDFZCompress: PDFStreamFilterZCompress + +class PDFStreamFilterBase85Encode: + pdfname: str + def encode(self, text) -> str: ... + def decode(self, text) -> bytes: ... + +PDFBase85Encode: PDFStreamFilterBase85Encode + +class PDFStream(PDFObject): + __RefOnly__: int + dictionary: Incomplete + content: Incomplete + filters: Incomplete + def __init__(self, dictionary=None, content=None, filters=None) -> None: ... + def format(self, document) -> bytes: ... + +def teststream(content=None) -> PDFStream: ... + +teststreamcontent: str + +class PDFArray(PDFObject): + multiline: bool + sequence: list[Incomplete] + def __init__(self, sequence) -> None: ... + def References(self, document) -> None: ... + def format(self, document, IND: bytes = b"\n ") -> bytes: ... + +class PDFArrayCompact(PDFArray): + multiline: bool + +class PDFIndirectObject(PDFObject): + __RefOnly__: int + name: str + content: Incomplete + def __init__(self, name: str, content) -> None: ... + def format(self, document) -> bytes: ... + +class PDFObjectReference(PDFObject): + name: str + def __init__(self, name: str) -> None: ... + def format(self, document) -> bytes: ... + +class PDFFile(PDFObject): + strings: list[bytes] + write: Callable[[bytes], None] + offset: int + def __init__(self, pdfVersion: tuple[int, int] = (1, 3)) -> None: ... + def closeOrReset(self) -> None: ... + def add(self, s) -> int: ... + def format(self, document) -> bytes: ... + +class PDFCrossReferenceSubsection(PDFObject): + firstentrynumber: Incomplete + idsequence: Incomplete + def __init__(self, firstentrynumber, idsequence) -> None: ... + def format(self, document) -> bytes: ... + +class PDFCrossReferenceTable(PDFObject): + sections: list[PDFCrossReferenceSubsection] + def __init__(self) -> None: ... + def addsection(self, firstentry, ids) -> None: ... + def format(self, document) -> bytes: ... + +class PDFTrailer(PDFObject): + startxref: Incomplete + def __init__(self, startxref, Size=None, Prev=None, Root=None, Info=None, ID=None, Encrypt=None) -> None: ... + def format(self, document) -> bytes: ... + +class PDFCatalog(PDFObject): + __Comment__: str + __RefOnly__: int + __Defaults__: dict[str, str | None] + __NoDefault__: list[str] + __Refs__ = __NoDefault__ # pyrefly: ignore [unknown-name] + def format(self, document) -> bytes: ... + def showOutline(self) -> None: ... + def showFullScreen(self) -> None: ... + PageLayout: Incomplete + def setPageLayout(self, layout) -> None: ... + PageMode: Incomplete + def setPageMode(self, mode) -> None: ... + def check_format(self, document) -> None: ... + +class PDFPages(PDFCatalog): + __Comment__: str + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + pages: Incomplete + def __init__(self) -> None: ... + def __getitem__(self, item): ... + def addPage(self, page) -> None: ... + Kids: PDFArray + Count: int + def check_format(self, document) -> None: ... + +class PDFPage(PDFCatalog): + __Comment__: str + Override_default_compilation: int + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + pagewidth: int + pageheight: int + stream: Incomplete + hasImages: bool | Literal[0, 1] + compression: bool | Literal[0, 1] + XObjects: Incomplete + Trans: Incomplete + def __init__(self) -> None: ... + def setCompression(self, onoff) -> None: ... + def setStream(self, code) -> None: ... + def setPageTransition(self, tranDict) -> None: ... + MediaBox: Incomplete + Annots: Incomplete + Contents: Incomplete + Resources: Incomplete + Parent: Incomplete + def check_format(self, document) -> None: ... + +class DuplicatePageLabelPage(Exception): ... + +class PDFPageLabels(PDFCatalog): + __comment__: Incomplete + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __Refs__: Incomplete + labels: Incomplete + def __init__(self) -> None: ... + def addPageLabel(self, page, label) -> None: ... + Nums: Incomplete + def format(self, document) -> bytes: ... + +class PDFPageLabel(PDFCatalog): + __Comment__: Incomplete + __RefOnly__: int + __Defaults__: Incomplete + __NoDefault__: list[str] + __convertible__: str + ARABIC: str + ROMAN_UPPER: str + ROMAN_LOWER: str + LETTERS_UPPER: str + LETTERS_LOWER: str + S: Incomplete + St: Incomplete + P: Incomplete + def __init__(self, style=None, start=None, prefix=None) -> None: ... + def __lt__(self, oth): ... + +def testpage(document) -> None: ... + +DUMMYOUTLINE: str + +class PDFOutlines0(PDFObject): + __Comment__: str + text: str + __RefOnly__: int + def format(self, document) -> bytes: ... + +class OutlineEntryObject(PDFObject): + Title: Incomplete + Dest: Incomplete + Parent: Incomplete + Prev: Incomplete + Next: Incomplete + First: Incomplete + Last: Incomplete + Count: Incomplete + def format(self, document) -> bytes: ... + +class PDFOutlines(PDFObject): + mydestinations: Incomplete + ready: int | None + counter: int + currentlevel: int + destinationnamestotitles: Incomplete + destinationstotitles: Incomplete + levelstack: Incomplete + buildtree: Incomplete + closedict: Incomplete + def __init__(self) -> None: ... + def addOutlineEntry(self, destinationname, level: int = 0, title=None, closed=None) -> None: ... + def setDestinations(self, destinationtree) -> None: ... + def format(self, document) -> bytes: ... + def setNames(self, canvas, *nametree) -> None: ... + def setNameList(self, canvas, nametree) -> None: ... + def translateNames(self, canvas, object): ... + first: Incomplete + last: Incomplete + count: int + def prepare(self, document, canvas) -> None: ... + def maketree( + self, document, destinationtree, Parent=None, toplevel: bool | Literal[0, 1] = 0 + ) -> tuple[Incomplete, Incomplete]: ... + +def count(tree, closedict=None) -> int: ... + +class PDFInfo(PDFObject): + producer: Incomplete + creator: str + title: str + author: str + subject: str + keywords: str + trapped: str + def __init__(self) -> None: ... + def digest(self, md5object) -> None: ... + def format(self, document) -> bytes: ... + def copy(self): ... + +class Annotation(PDFObject): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + def cvtdict(self, d: dict[str, Incomplete], escape: int = 1) -> dict[str, Incomplete]: ... + def AnnotationDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class FreeTextAnnotation(Annotation): + permitted: tuple[str, ...] + Rect: Incomplete + Contents: Incomplete + DA: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Rect, Contents, DA, **kw) -> None: ... + def Dict(self) -> PDFDictionary: ... + +class LinkAnnotation(Annotation): + permitted: tuple[str, ...] + Border: Incomplete + Rect: Incomplete + Contents: Incomplete + Destination: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Rect, Contents, Destination, Border: str = "[0 0 1]", **kw) -> None: ... + def dummyDictString(self) -> str: ... + def Dict(self) -> PDFDictionary: ... + +class HighlightAnnotation(Annotation): + permitted: tuple[str, ...] + Rect: Incomplete + Contents: Incomplete + otherkw: dict[str, Incomplete] + QuadPoints: Incomplete + Color: Incomplete + def __init__(self, Rect, Contents, QuadPoints, Color=[0.83, 0.89, 0.95], **kw) -> None: ... + def cvtdict(self, d: dict[str, Incomplete], escape: int = 1) -> dict[str, Incomplete]: ... + def Dict(self) -> PDFDictionary: ... + +class TextAnnotation(HighlightAnnotation): + permitted: tuple[str, ...] + def __init__(self, Rect, Contents, **kw) -> None: ... + def Dict(self) -> PDFDictionary: ... + +def rect_to_quad(Rect) -> list[Incomplete]: ... + +class PDFRectangle(PDFObject): + def __init__(self, llx, lly, urx, ury) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDate(PDFObject): + dateFormatter: Incomplete + def __init__(self, ts=None, dateFormatter=None) -> None: ... + def format(self, doc) -> bytes: ... + +class Destination(PDFObject): + representation: None + page: None + name: Incomplete + fmt: Incomplete + def __init__(self, name) -> None: ... + def format(self, document) -> bytes: ... + def xyz(self, left, top, zoom) -> None: ... + def fit(self) -> None: ... + def fitb(self) -> None: ... + def fith(self, top) -> None: ... + def fitv(self, left) -> None: ... + def fitbh(self, top) -> None: ... + def fitbv(self, left) -> None: ... + def fitr(self, left, bottom, right, top) -> None: ... + def setPage(self, page) -> None: ... + +class PDFDestinationXYZ(PDFObject): + typename: str + page: Incomplete + top: Incomplete + zoom: Incomplete + left: Incomplete + def __init__(self, page, left, top, zoom) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFit(PDFObject): + typename: str + page: Incomplete + def __init__(self, page) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitB(PDFDestinationFit): + typename: str + +class PDFDestinationFitH(PDFObject): + typename: str + page: Incomplete + top: Incomplete + def __init__(self, page, top) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitBH(PDFDestinationFitH): + typename: str + +class PDFDestinationFitV(PDFObject): + typename: str + page: Incomplete + left: Incomplete + def __init__(self, page, left) -> None: ... + def format(self, document) -> bytes: ... + +class PDFDestinationFitBV(PDFDestinationFitV): + typename: str + +class PDFDestinationFitR(PDFObject): + typename: str + page: Incomplete + left: Incomplete + bottom: Incomplete + right: Incomplete + top: Incomplete + def __init__(self, page, left, bottom, right, top) -> None: ... + def format(self, document) -> bytes: ... + +class PDFResourceDictionary(PDFObject): + ProcSet: Incomplete + def __init__(self, **kwds) -> None: ... + stdprocs: Incomplete + dict_attributes: Incomplete + def allProcs(self) -> None: ... + def basicProcs(self) -> None: ... + Font: Incomplete + def basicFonts(self) -> None: ... + def setColorSpace(self, colorsUsed) -> None: ... + def setShading(self, shadingUsed) -> None: ... + def format(self, document) -> bytes: ... + +class PDFType1Font(PDFObject): + __RefOnly__: int + name_attributes: Incomplete + Type: str + Subtype: str + local_attributes: Incomplete + def format(self, document) -> bytes: ... + +class PDFTrueTypeFont(PDFType1Font): + Subtype: str + +class PDFFormXObject(PDFObject): + XObjects: Incomplete + Annots: Incomplete + BBox: Incomplete + Matrix: Incomplete + Contents: Incomplete + stream: Incomplete + Resources: Incomplete + hasImages: bool | Literal[0, 1] + compression: bool | Literal[0, 1] + lowerx: Incomplete + lowery: Incomplete + upperx: Incomplete + uppery: Incomplete + def __init__(self, lowerx, lowery, upperx, uppery) -> None: ... + def setStreamList(self, data) -> None: ... + def BBoxList(self) -> list[Incomplete]: ... + def format(self, document) -> bytes: ... + +class PDFPostScriptXObject(PDFObject): + content: Incomplete + def __init__(self, content=None) -> None: ... + def format(self, document) -> bytes: ... + +class PDFImageXObject(PDFObject): + name: Incomplete + width: int + height: int + bitsPerComponent: int + colorSpace: str + streamContent: str + mask: Incomplete + def __init__(self, name, source=None, mask=None) -> None: ... + def loadImageFromA85(self, source) -> None: ... + def loadImageFromJPEG(self, imageFile) -> bool: ... + def loadImageFromRaw(self, source) -> None: ... + def loadImageFromSRC(self, im) -> None: ... + def format(self, document) -> bytes: ... + +class PDFSeparationCMYKColor: + cmyk: Incomplete + def __init__(self, cmyk) -> None: ... + def value(self) -> PDFArrayCompact: ... + +class PDFFunction(PDFObject): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + def FunctionDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self, document) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class PDFExponentialFunction(PDFFunction): + defaults: Incomplete + required: tuple[str, ...] + permitted: tuple[str, ...] + C0: Incomplete + C1: Incomplete + N: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, C0, C1, N, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFStitchingFunction(PDFFunction): + required: tuple[str, ...] + permitted: tuple[str, ...] + Functions: Incomplete + Bounds: Incomplete + Encode: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Functions, Bounds, Encode, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFShading(PDFObject): + required: tuple[str, ...] + permitted: tuple[str, ...] + def ShadingDict(self, **kw) -> PDFDictionary: ... + @abstractmethod + def Dict(self, document) -> PDFDictionary: ... + def format(self, document) -> bytes: ... + +class PDFFunctionShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFAxialShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Coords: Incomplete + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, x0, y0, x1, y1, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class PDFRadialShading(PDFShading): + required: tuple[str, ...] + permitted: tuple[str, ...] + Coords: Incomplete + Function: Incomplete + ColorSpace: Incomplete + otherkw: dict[str, Incomplete] + def __init__(self, x0, y0, r0, x1, y1, r1, Function, ColorSpace, **kw) -> None: ... + def Dict(self, document) -> PDFDictionary: ... + +class XMP(PDFStream): + def __init__(self, path=None, creator=None) -> None: ... + def makeContent(self, doc): ... + # Param name is changed from the base class: + def format(self, doc) -> bytes: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfform.pyi b/stubs/reportlab/reportlab/pdfbase/pdfform.pyi new file mode 100644 index 000000000000..a747030f3d6a --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfform.pyi @@ -0,0 +1,86 @@ +from typing import Literal + +from reportlab.pdfbase.pdfdoc import PDFDictionary, PDFObject, PDFStream, PDFString +from reportlab.pdfbase.pdfpattern import PDFPattern, PDFPatternIf + +def textFieldAbsolute( + canvas, title, x, y, width, height, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 +) -> None: ... +def textFieldRelative( + canvas, title, xR, yR, width, height, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 +) -> None: ... +def buttonFieldAbsolute(canvas, title, value, x, y, width: float = 16.7704, height: float = 14.907) -> None: ... +def buttonFieldRelative(canvas, title, value, xR, yR, width: float = 16.7704, height: float = 14.907) -> None: ... +def selectFieldAbsolute(canvas, title, value, options, x, y, width, height) -> None: ... +def selectFieldRelative(canvas, title, value, options, xR, yR, width, height) -> None: ... +def getForm(canvas) -> AcroForm: ... + +class AcroForm(PDFObject): + fields: list[PDFPattern] + def __init__(self) -> None: ... + def textField( + self, canvas, title, xmin, ymin, xmax, ymax, value: str = "", maxlen: int = 1000000, multiline: bool | Literal[0, 1] = 0 + ) -> None: ... + def selectField(self, canvas, title, value, options, xmin, ymin, xmax, ymax) -> None: ... + def buttonField(self, canvas, title, value, xmin, ymin, width: float = 16.7704, height: float = 14.907) -> None: ... + def format(self, document) -> bytes: ... + +FormPattern: list[str | list[str] | PDFString | PDFPatternIf] + +def FormFontsDictionary() -> PDFDictionary: ... +def FormResources() -> PDFPattern: ... + +ZaDbPattern: list[str] +FormResourcesDictionaryPattern: list[str | list[str]] +FORMFONTNAMES: dict[str, str] +EncodingPattern: list[str | list[str]] +PDFDocEncodingPattern: list[str] + +def FormFont(BaseFont, Name) -> PDFPattern: ... + +FormFontPattern: list[str | list[str]] + +def resetPdfForm() -> None: ... +def TextField( + title, + value, + xmin, + ymin, + xmax, + ymax, + page, + maxlen: int = 1000000, + font: str = "Helvetica-Bold", + fontsize: int = 9, + R: int = 0, + G: int = 0, + B: float = 0.627, + multiline: bool | Literal[0, 1] = 0, +) -> PDFPattern: ... + +TextFieldPattern: list[str | list[str]] + +def SelectField( + title, + value, + options, + xmin, + ymin, + xmax, + ymax, + page, + font: str = "Helvetica-Bold", + fontsize: int = 9, + R: int = 0, + G: int = 0, + B: float = 0.627, +) -> PDFPattern: ... + +SelectFieldPattern: list[str | list[str]] + +def ButtonField(title, value, xmin, ymin, page, width: float = 16.7704, height: float = 14.907) -> PDFPattern: ... + +ButtonFieldPattern: list[str | list[str] | PDFString] + +def buttonStreamDictionary(width: float = 16.7704, height: float = 14.907) -> PDFDictionary: ... +def ButtonStream(content, width: float = 16.7704, height: float = 14.907) -> PDFStream: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi b/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi new file mode 100644 index 000000000000..f2960d313f17 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfmetrics.pyi @@ -0,0 +1,90 @@ +from _typeshed import Incomplete, StrOrBytesPath +from typing import Final, Literal + +from reportlab.lib.rl_accel import unicode2T1 as unicode2T1 +from reportlab.pdfbase.pdfdoc import PDFDictionary + +__version__: Final[str] +standardFonts: Incomplete +standardEncodings: Incomplete + +class FontError(Exception): ... +class FontNotFoundError(Exception): ... + +def parseAFMFile(afmFileName: StrOrBytesPath) -> tuple[dict[Incomplete, Incomplete], list[Incomplete]]: ... + +class TypeFace: + name: Incomplete + glyphNames: Incomplete + glyphWidths: Incomplete + ascent: int + descent: int + familyName: Incomplete + bold: int + italic: int + requiredEncoding: str + builtIn: int + def __init__(self, name) -> None: ... + def getFontFiles(self) -> list[Incomplete]: ... + def findT1File(self, ext: str = ".pfb") -> str | None: ... + +def bruteForceSearchForFile(fn, searchPath=None): ... +def bruteForceSearchForAFM(faceName) -> str | None: ... + +class Encoding: + name: Incomplete + frozen: Literal[0, 1] + baseEncodingName: Incomplete + vector: tuple[Incomplete, ...] + def __init__(self, name, base=None) -> None: ... + def __getitem__(self, index): ... + def __setitem__(self, index, value) -> None: ... + def freeze(self) -> None: ... + def isEqual(self, other) -> bool: ... + def modifyRange(self, base, newNames) -> None: ... + def getDifferences(self, otherEnc) -> list[Incomplete]: ... + def makePDFObject(self) -> PDFDictionary | str: ... + +standardT1SubstitutionFonts: Incomplete + +class Font: + fontName: Incomplete + encoding: Incomplete + encName: Incomplete + substitutionFonts: Incomplete + shapable: bool + def __init__(self, name, faceName, encName, substitutionFonts=None) -> None: ... + def stringWidth(self, text: str | bytes, size: float, encoding: str = "utf8") -> float: ... + widths: list[int] + def addObjects(self, doc) -> None: ... + +PFB_MARKER: Final[str] +PFB_ASCII: Final[str] +PFB_BINARY: Final[str] +PFB_EOF: Final[str] + +class EmbeddedType1Face(TypeFace): + afmFileName: Incomplete + pfbFileName: Incomplete + requiredEncoding: Incomplete + def __init__(self, afmFileName, pfbFileName) -> None: ... + def getFontFiles(self) -> list[Incomplete]: ... + def addObjects(self, doc): ... + +def registerTypeFace(face) -> None: ... +def registerEncoding(enc) -> None: ... +def registerFontFamily(family, normal=None, bold=None, italic=None, boldItalic=None) -> None: ... +def registerFont(font) -> None: ... +def getTypeFace(faceName) -> TypeFace: ... +def getEncoding(encName) -> Encoding: ... +def findFontAndRegister(fontName: str) -> Font: ... +def getFont(fontName: str) -> Font: ... +def getAscentDescent(fontName: str, fontSize: float | None = None) -> tuple[float, float]: ... +def getAscent(fontName: str, fontSize: float | None = None) -> float: ... +def getDescent(fontName: str, fontSize: float | None = None) -> float: ... +def getRegisteredFontNames() -> list[Incomplete]: ... +def stringWidth(text: str | bytes, fontName: str, fontSize: float, encoding: str = "utf8") -> float: ... +def dumpFontData() -> None: ... +def test3widths(texts) -> None: ... +def testStringWidthAlgorithms() -> None: ... +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi b/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi new file mode 100644 index 000000000000..1f98675e4bc0 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfpattern.pyi @@ -0,0 +1,22 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing_extensions import Self + +from reportlab.pdfbase.pdfdoc import PDFObject + +class PDFPattern(PDFObject): + __RefOnly__: int + pattern: Incomplete + arguments: dict[str, Incomplete] + def __init__(self, pattern_sequence, **keywordargs) -> None: ... + def __setitem__(self, item: str, value) -> None: ... + def __getitem__(self, item: str): ... + def eval(self, L) -> Iterator[bytes]: ... + def format(self, document) -> bytes: ... + def clone(self) -> Self: ... + +class PDFPatternIf: + cond: Incomplete + thenPart: Incomplete + elsePart: Incomplete + def __init__(self, cond, thenPart=[], elsePart=[]) -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi b/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi new file mode 100644 index 000000000000..92406a359049 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/pdfutils.pyi @@ -0,0 +1,16 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +def makeA85Image(filename, IMG=None, detectJpeg: bool = False) -> list[Incomplete] | None: ... +def makeRawImage(filename, IMG=None, detectJpeg: bool = False) -> list[Incomplete] | None: ... +def cacheImageFile(filename, returnInMemory: bool | Literal[0, 1] = 0, IMG=None): ... +def preProcessImages(spec) -> None: ... +def cachedImageExists(filename) -> Literal[0, 1]: ... +def readJPEGInfo(image) -> tuple[Incomplete, Incomplete, Incomplete, Incomplete] | None: ... + +class _fusc: + def __init__(self, k, n) -> None: ... + def encrypt(self, s) -> str: ... + def decrypt(self, s) -> str: ... diff --git a/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi b/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi new file mode 100644 index 000000000000..c87628e05b09 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/rl_codecs.pyi @@ -0,0 +1,23 @@ +from typing import NamedTuple + +__all__ = ["RL_Codecs"] + +class StdCodecData(NamedTuple): + exceptions: dict[int, int | None] | None + rexceptions: dict[int, int | None] | None + +class ExtCodecData(NamedTuple): + baseName: str + exceptions: dict[int, int | None] | None + rexceptions: dict[int, int | None] | None + +class RL_Codecs: + def __init__(self) -> None: ... + @staticmethod + def register() -> None: ... + @staticmethod + def add_dynamic_codec(name: str, exceptions, rexceptions) -> None: ... + @staticmethod + def remove_dynamic_codec(name: str) -> None: ... + @staticmethod + def reset_dynamic_codecs() -> None: ... diff --git a/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi b/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi new file mode 100644 index 000000000000..aab282f6c48b --- /dev/null +++ b/stubs/reportlab/reportlab/pdfbase/ttfonts.pyi @@ -0,0 +1,192 @@ +from _typeshed import Incomplete, ReadableBuffer, StrOrBytesPath +from collections.abc import Sequence +from typing import Final, Literal, NamedTuple +from typing_extensions import Self +from weakref import WeakKeyDictionary + +from reportlab.pdfbase import pdfdoc, pdfmetrics + +__version__: Final[str] + +class TTFError(pdfdoc.PDFError): ... + +def SUBSETN(n, table: ReadableBuffer | None = ...) -> bytes: ... +def makeToUnicodeCMap(fontname: str, subset) -> str: ... +def splice(stream, offset, value): ... + +GF_ARG_1_AND_2_ARE_WORDS: Final = 1 +GF_ARGS_ARE_XY_VALUES: Final = 2 +GF_ROUND_XY_TO_GRID: Final = 4 +GF_WE_HAVE_A_SCALE: Final = 8 +GF_RESERVED: Final = 16 +GF_MORE_COMPONENTS: Final = 32 +GF_WE_HAVE_AN_X_AND_Y_SCALE: Final = 64 +GF_WE_HAVE_A_TWO_BY_TWO: Final = 128 +GF_WE_HAVE_INSTRUCTIONS: Final = 256 +GF_USE_MY_METRICS: Final = 512 +GF_OVERLAP_COMPOUND: Final = 1024 +GF_SCALED_COMPONENT_OFFSET: Final = 2048 +GF_UNSCALED_COMPONENT_OFFSET: Final = 4096 + +def TTFOpenFile(fn: StrOrBytesPath) -> tuple[StrOrBytesPath,]: ... + +class TTFontParser: + ttfVersions: tuple[int, ...] + ttcVersions: tuple[int, ...] + fileKind: str + validate: bool | Literal[0, 1] + subfontNameX: bytes + def __init__(self, file, validate: bool | Literal[0, 1] = 0, subfontIndex: int = 0) -> None: ... + ttcVersion: int + numSubfonts: int + subfontOffsets: list[int] + def readTTCHeader(self) -> None: ... + def getSubfont(self, subfontIndex: int) -> None: ... + numTables: int + searchRange: int + entrySelector: int + rangeShift: int + table: dict[Incomplete, Incomplete] + tables: list[Incomplete] + def readTableDirectory(self) -> None: ... + version: int + def readHeader(self) -> bool: ... + filename: Incomplete + def readFile(self, f) -> None: ... + def checksumTables(self) -> None: ... + def checksumFile(self) -> None: ... + def get_table_pos(self, tag) -> tuple[Incomplete, Incomplete]: ... + def seek(self, pos: int) -> None: ... + def skip(self, delta: int) -> None: ... + def seek_table(self, tag, offset_in_table: int = 0) -> int: ... + def read_tag(self) -> str: ... + def get_chunk(self, pos: int, length: int) -> bytes: ... + def read_uint8(self) -> int: ... + def read_ushort(self) -> int: ... + def read_ulong(self) -> int: ... + def read_short(self) -> int: ... + def get_ushort(self, pos: int) -> int: ... + def get_ulong(self, pos: int) -> int: ... + def get_table(self, tag): ... + +class TTFontMaker: + tables: dict[Incomplete, Incomplete] + def __init__(self) -> None: ... + def add(self, tag, data) -> None: ... + def makeStream(self) -> bytes: ... + +class CMapFmt2SubHeader(NamedTuple): + firstCode: int + entryCount: int + idDelta: int + idRangeOffset: int + +class TTFNameBytes(bytes): + ustr: Incomplete + def __new__(cls, b, enc: str = "utf8") -> Self: ... + +class TTFontFile(TTFontParser): + def __init__( + self, file, charInfo: bool | Literal[0, 1] = 1, validate: bool | Literal[0, 1] = 0, subfontIndex: int | str | bytes = 0 + ) -> None: ... + name: Incomplete + familyName: Incomplete + styleName: Incomplete + fullName: Incomplete + uniqueFontID: Incomplete + fontRevision: Incomplete + unitsPerEm: Incomplete + bbox: Incomplete + ascent: Incomplete + descent: Incomplete + capHeight: Incomplete + stemV: Incomplete + italicAngle: Incomplete + underlinePosition: Incomplete + underlineThickness: Incomplete + flags: Incomplete + numGlyphs: Incomplete + charToGlyph: Incomplete + defaultWidth: Incomplete + charWidths: Incomplete + hmetrics: Incomplete + glyphPos: Incomplete + def extractInfo(self, charInfo: bool | Literal[0, 1] = 1) -> None: ... + def makeSubset(self, subset: Sequence[Incomplete]) -> bytes: ... + +FF_FIXED: Final = 1 +FF_SERIF: Final = 2 +FF_SYMBOLIC: Final = 4 +FF_SCRIPT: Final = 8 +FF_NONSYMBOLIC: Final = 32 +FF_ITALIC: Final = 64 +FF_ALLCAP: Final = 65536 +FF_SMALLCAP: Final = 131072 +FF_FORCEBOLD: Final = 262144 + +class TTFontFace(TTFontFile, pdfmetrics.TypeFace): + def __init__(self, filename, validate: bool | Literal[0, 1] = 0, subfontIndex: int | str | bytes = 0) -> None: ... + def getCharWidth(self, code): ... + def addSubsetObjects(self, doc, fontname, subset): ... + +class TTEncoding: + name: str + def __init__(self) -> None: ... + +class TTFont: + class State: + namePrefix: str + nextCode: int + internalName: Incomplete + frozen: bool | Literal[0, 1] + subsets: Incomplete + def __init__(self, asciiReadable: bool | Literal[0, 1] | None = None, ttf=None) -> None: ... + + fontName: str + face: TTFontFace + encoding: TTEncoding + state: WeakKeyDictionary[Incomplete, State] + def __init__( + self, + name: str, + filename, + validate: bool | Literal[0, 1] = 0, + subfontIndex: int | str | bytes = 0, + asciiReadable: bool | Literal[0, 1] | None = None, + shapable: bool = True, + ) -> None: ... + def stringWidth(self, text, size, encoding: str = "utf8") -> float: ... + def splitString(self, text, doc, encoding: str = "utf-8") -> list[tuple[int, bytes]]: ... + def getSubsetInternalName(self, subset, doc) -> str: ... + def addObjects(self, doc) -> None: ... + @property + def hbFace(self) -> Incomplete | None: ... + def hbFont(self, fontSize: float = 10): ... + + @property + def shapable(self) -> bool: ... + @shapable.setter + def shapable(self, v) -> None: ... + + def pdfScale(self, v): ... + def unregister(self) -> None: ... + +class ShapedFragWord(list[Incomplete]): ... + +class ShapeData(NamedTuple): + cluster: int + x_advance: float + y_advance: float + x_offset: float + y_offset: float + width: float + +class ShapedStr(str): + def __new__(cls, s, shapeData: ShapeData | None = None) -> Self: ... + def __add__(self, other) -> ShapedStr: ... + def __radd__(self, other) -> ShapedStr: ... + +def shapeStr(s: str, fontName: str, fontSize: float, force: bool = False): ... +def freshTTFont(ttfn, ttfpath, **kwds) -> TTFont: ... +def makeShapedFragWord(w, K: list[Incomplete] = [], V: list[Incomplete] = []) -> type[ShapedFragWord]: ... +def shapeFragWord(w, features=None, force: bool = False): ... diff --git a/stubs/reportlab/reportlab/pdfgen/__init__.pyi b/stubs/reportlab/reportlab/pdfgen/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/pdfgen/canvas.pyi b/stubs/reportlab/reportlab/pdfgen/canvas.pyi new file mode 100644 index 000000000000..15b3827a28b7 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/canvas.pyi @@ -0,0 +1,297 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import IO, Literal + +from reportlab.lib.colors import Color, _ConvertibleToColor +from reportlab.pdfbase.acroform import AcroForm +from reportlab.pdfbase.pdfdoc import Destination +from reportlab.pdfgen.pathobject import PDFPathObject +from reportlab.pdfgen.textobject import PDFTextObject, _PDFColorSetter + +class ShowBoundaryValue: + color: _ConvertibleToColor | None + width: float + dashArray: Incomplete + def __init__( + self, + color: _ConvertibleToColor | None = (0, 0, 0), + width: float = 0.1, + dashArray: list[float] | tuple[float, ...] | None = None, + ) -> None: ... + def __bool__(self) -> bool: ... + +class Canvas(_PDFColorSetter): + bottomup: bool | Literal[0, 1] + imageCaching: Incomplete + state_stack: list[Incomplete] + def __init__( + self, + filename: str | IO[bytes], + pagesize: tuple[float, float] | None = None, + bottomup: bool | Literal[0, 1] = 1, + pageCompression=None, + invariant=None, + verbosity: int = 0, + encrypt=None, + cropMarks=None, + pdfVersion=None, + enforceColorSpace=None, + initialFontName: float | None = None, + initialFontSize: float | None = None, + initialLeading: float | None = None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + lang=None, + ) -> None: ... + def setEncrypt(self, encrypt) -> None: ... + def init_graphics_state(self) -> None: ... + def push_state_stack(self) -> None: ... + def pop_state_stack(self) -> None: ... + STATE_ATTRIBUTES: list[str] + STATE_RANGE: list[int] + def setAuthor(self, author: str | None) -> None: ... + def setDateFormatter(self, dateFormatter) -> None: ... + def addOutlineEntry(self, title, key, level: int = 0, closed=None) -> None: ... + def setOutlineNames0(self, *nametree) -> None: ... + def setTitle(self, title: str | None) -> None: ... + def setSubject(self, subject: str | None) -> None: ... + def setCreator(self, creator: str | None) -> None: ... + def setProducer(self, producer: str | None) -> None: ... + def setKeywords(self, keywords: str | None) -> None: ... + def pageHasData(self) -> bool: ... + def showOutline(self) -> None: ... + def showFullScreen0(self) -> None: ... + def setBlendMode(self, v) -> None: ... + def showPage(self) -> None: ... + def setPageCallBack(self, func) -> None: ... + def bookmarkPage(self, key, fit: str = "Fit", left=None, top=None, bottom=None, right=None, zoom=None) -> Destination: ... + def bookmarkHorizontalAbsolute(self, key, top, left: int = 0, fit: str = "XYZ", **kw) -> Destination: ... + def bookmarkHorizontal(self, key, relativeX, relativeY, **kw) -> None: ... + def doForm(self, name) -> None: ... + def hasForm(self, name: str) -> bool: ... + def drawInlineImage( + self, + image, + x: float, + y: float, + width: float | None = None, + height: float | None = None, + preserveAspectRatio: bool = False, + anchor: str = "c", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> tuple[Incomplete, Incomplete]: ... + def drawImage( + self, + image, + x: float, + y: float, + width: float | None = None, + height: float | None = None, + mask=None, + preserveAspectRatio: bool = False, + anchor: str = "c", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> tuple[Incomplete, Incomplete]: ... + def beginForm(self, name, lowerx: int = 0, lowery: int = 0, upperx=None, uppery=None) -> None: ... + def endForm(self, **extra_attributes) -> None: ... + def addPostScriptCommand(self, command, position: int = 1) -> None: ... + def freeTextAnnotation( + self, contents, DA, Rect=None, addtopage: bool | Literal[0, 1] = 1, name=None, relative: bool | Literal[0, 1] = 0, **kw + ) -> None: ... + def textAnnotation( + self, contents, Rect=None, addtopage: bool | Literal[0, 1] = 1, name=None, relative: bool | Literal[0, 1] = 0, **kw + ) -> None: ... + textAnnotation0 = textAnnotation + def highlightAnnotation( + self, + contents, + Rect, + QuadPoints=None, + Color=[0.83, 0.89, 0.95], + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 0, + **kw, + ) -> None: ... + def inkAnnotation( + self, + contents, + InkList=None, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 0, + **kw, + ) -> None: ... + inkAnnotation0 = inkAnnotation + def linkAbsolute( + self, + contents, + destinationname, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + **kw, + ) -> None: ... + def linkRect( + self, + contents, + destinationname, + Rect=None, + addtopage: bool | Literal[0, 1] = 1, + name=None, + relative: bool | Literal[0, 1] = 1, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + **kw, + ) -> None: ... + def linkURL( + self, + url, + rect, + relative: bool | Literal[0, 1] = 0, + thickness: int = 0, + color: Color | None = None, + dashArray=None, + kind: str = "URI", + **kw, + ) -> None: ... + def getPageNumber(self) -> int: ... + def save(self) -> None: ... + def getpdfdata(self): ... + def setPageSize(self, size: tuple[float, float]) -> None: ... + def setCropBox(self, size, name: str = "crop") -> None: ... + def setTrimBox(self, size) -> None: ... + def setArtBox(self, size) -> None: ... + def setBleedBox(self, size) -> None: ... + # NOTE: Only accepts right angles + def setPageRotation(self, rot: float) -> None: ... + def addLiteral(self, s: object, escaped: Literal[0, 1] = 1) -> None: ... + def resetTransforms(self) -> None: ... + def transform(self, a: float, b: float, c: float, d: float, e: float, f: float) -> None: ... + def absolutePosition(self, x: float, y: float) -> tuple[float, float]: ... + def translate(self, dx: float, dy: float) -> None: ... + def scale(self, x: float, y: float) -> None: ... + def rotate(self, theta: float) -> None: ... + def skew(self, alpha: float, beta: float) -> None: ... + def saveState(self) -> None: ... + def restoreState(self) -> None: ... + def line(self, x1: float, y1: float, x2: float, y2: float) -> None: ... + def lines(self, linelist) -> None: ... + def cross( + self, + x: float, + y: float, + size: float = 5, + gap: float = 1, + text=None, + strokeColor=None, + strokeWidth: float | None = None, + fontSize: float = 3, + ) -> None: ... + def grid(self, xlist, ylist) -> None: ... + def bezier(self, x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, x4: float, y4: float) -> None: ... + def arc(self, x1: float, y1: float, x2: float, y2: float, startAng: float = 0, extent: float = 90) -> None: ... + def rect(self, x: float, y: float, width: float, height: float, stroke: float = 1, fill: float = 0) -> None: ... + def ellipse(self, x1: float, y1: float, x2: float, y2: float, stroke: float = 1, fill: float = 0) -> None: ... + def wedge( + self, x1: float, y1: float, x2: float, y2: float, startAng: float, extent: float, stroke: float = 1, fill: float = 0 + ) -> None: ... + def circle(self, x_cen: float, y_cen: float, r: float, stroke: float = 1, fill: float = 0) -> None: ... + def roundRect( + self, x: float, y: float, width: float, height: float, radius: float, stroke: float = 1, fill: float = 0 + ) -> None: ... + def shade(self, shading) -> None: ... + def linearGradient(self, x0: float, y0: float, x1: float, y1: float, colors, positions=None, extend: bool = True) -> None: ... + def radialGradient(self, x: float, y: float, radius: float, colors, positions=None, extend: bool = True) -> None: ... + def drawString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawRightString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawCentredString( + self, + x: float, + y: float, + text: str, + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def drawAlignedString( + self, + x: float, + y: float, + text: str, + pivotChar: str = ".", + mode: Literal[0, 1, 2, 3, 4, 5, 6, 7] | None = None, + charSpace: float = 0, + direction: Literal["LTR", "RTL"] | None = None, + wordSpace: float | None = None, + shaping: bool = False, + ) -> None: ... + def getAvailableFonts(self) -> list[Incomplete]: ... + def listLoadedFonts0(self) -> list[Incomplete]: ... + def setFont(self, psfontname: str, size: float, leading: float | None = None) -> None: ... + def setFontSize(self, size: float | None = None, leading: float | None = None) -> None: ... + def stringWidth(self, text: str, fontName: str | None = None, fontSize: float | None = None) -> float: ... + def setLineWidth(self, width: float) -> None: ... + def setLineCap(self, mode) -> None: ... + def setLineJoin(self, mode) -> None: ... + def setMiterLimit(self, limit) -> None: ... + def setDash(self, array: list[float] | tuple[float, ...] | float = [], phase: float = 0) -> None: ... + def beginPath(self) -> PDFPathObject: ... + def drawPath(self, aPath, stroke: int = 1, fill: int = 0, fillMode=None) -> None: ... + def clipPath(self, aPath, stroke: int = 1, fill: int = 0, fillMode=None) -> None: ... + def beginText(self, x: float = 0, y: float = 0, direction: Literal["LTR", "RTL"] | None = None) -> PDFTextObject: ... + def drawText(self, aTextObject: PDFTextObject) -> None: ... + def setPageCompression(self, pageCompression: bool | Literal[0, 1] | None = 1) -> None: ... + def setPageDuration(self, duration=None) -> None: ... + def setPageTransition( + self, effectname: str | None = None, duration: float = 1, direction: float = 0, dimension: str = "H", motion: str = "I" + ) -> None: ... + def getCurrentPageContent(self) -> str: ... + def setViewerPreference(self, pref, value) -> None: ... + def getViewerPreference(self, pref): ... + def delViewerPreference(self, pref) -> None: ... + def setCatalogEntry(self, key: str, value) -> None: ... + def getCatalogEntry(self, key: str): ... + def delCatalogEntry(self, key: str) -> None: ... + def addPageLabel(self, pageNum, style=None, start=None, prefix=None) -> None: ... + @property + def acroForm(self) -> AcroForm: ... + def drawBoundary(self, sb, x1: float, y1: float, width: float, height: float) -> None: ... + # Following callbacks are accepted: canvas, kind and label + def setNamedCB(self, name: str, cb: Callable[[Canvas, str | None, str], None]) -> None: ... + def getNamedCB(self, name: str) -> Callable[[Canvas, str | None, str], None] | None: ... + +__all__ = ["Canvas", "ShowBoundaryValue"] diff --git a/stubs/reportlab/reportlab/pdfgen/pathobject.pyi b/stubs/reportlab/reportlab/pdfgen/pathobject.pyi new file mode 100644 index 000000000000..9e1c93ce5e38 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pathobject.pyi @@ -0,0 +1,17 @@ +from typing import Final + +__version__: Final[str] + +class PDFPathObject: + def __init__(self, code=None) -> None: ... + def getCode(self) -> str: ... + def moveTo(self, x, y) -> None: ... + def lineTo(self, x, y) -> None: ... + def curveTo(self, x1, y1, x2, y2, x3, y3) -> None: ... + def arc(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 90) -> None: ... + def arcTo(self, x1, y1, x2, y2, startAng: int = 0, extent: int = 90) -> None: ... + def rect(self, x, y, width, height) -> None: ... + def ellipse(self, x, y, width, height) -> None: ... + def circle(self, x_cen, y_cen, r) -> None: ... + def roundRect(self, x, y, width, height, radius) -> None: ... + def close(self) -> None: ... diff --git a/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi b/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi new file mode 100644 index 000000000000..ab3e5ad0523d --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pdfgeom.pyi @@ -0,0 +1,8 @@ +from _typeshed import Incomplete +from typing import Final + +__version__: Final[str] + +def bezierArc( + x1, y1, x2, y2, startAng: int = 0, extent: int = 90 +) -> list[tuple[Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete, Incomplete]]: ... diff --git a/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi b/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi new file mode 100644 index 000000000000..83695d0069c4 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/pdfimages.pyi @@ -0,0 +1,36 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +class PDFImage: + image: Incomplete + x: Incomplete + y: Incomplete + width: Incomplete + height: Incomplete + filename: Incomplete + imageCaching: bool | Literal[0, 1] + colorSpace: str + bitsPerComponent: int + filters: Incomplete + source: Incomplete + def __init__(self, image, x, y, width=None, height=None, caching: bool | Literal[0, 1] = 0) -> None: ... + def jpg_imagedata(self) -> tuple[list[str], Incomplete, Incomplete]: ... + def cache_imagedata(self) -> list[str]: ... + def PIL_imagedata(self) -> tuple[list[str], Incomplete, Incomplete]: ... + def non_jpg_imagedata(self, image) -> tuple[list[str], int, int]: ... + imageData: Incomplete + imgwidth: Incomplete + imgheight: Incomplete + def getImageData(self, preserveAspectRatio: bool = False) -> None: ... + def drawInlineImage( + self, + canvas, + preserveAspectRatio: bool = False, + anchor: str = "sw", + anchorAtXY: bool = False, + showBoundary: bool = False, + extraReturn=None, + ) -> bool: ... + def format(self, document) -> bytes: ... diff --git a/stubs/reportlab/reportlab/pdfgen/textobject.pyi b/stubs/reportlab/reportlab/pdfgen/textobject.pyi new file mode 100644 index 000000000000..31edb40dddb9 --- /dev/null +++ b/stubs/reportlab/reportlab/pdfgen/textobject.pyi @@ -0,0 +1,71 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import Final, Literal, TypeAlias + +from reportlab.lib.colors import Color +from reportlab.pdfbase.ttfonts import ShapedStr +from reportlab.pdfgen.canvas import Canvas + +# NOTE: This is slightly different from what toColor accepts and interprets +_Color: TypeAlias = Color | tuple[float, float, float, float] | tuple[float, float, float] | list[float] | str + +__version__: Final[str] +log2vis: Callable[..., str | None] +BidiStr: type[str] +BidiList: type[list[Incomplete]] +BidiIndex: Incomplete + +def bidiText(text: str, direction: str | None) -> str: ... +def bidiShapedText( + text: str, direction: str = "RTL", clean: bool = True, fontName: str = "Helvetica", fontSize: int = 10, shaping: bool = False +) -> tuple[ShapedStr | str, float]: ... +def isBidiStr(_: Unused) -> bool: ... +def isBidiList(_: Unused) -> bool: ... +def innerBidiStrWrap(s: str, bidiV: int = -1, bidiL: int = -1) -> str: ... +def bidiStrWrap(s: str, orig: str) -> str: ... +def bidiListWrap(L, orig) -> list[Incomplete]: ... +def bidiFragWord(w: str, direction: str | None = None, bidiV: int = -1, bidiL: int = -1, clean: bool = True): ... +def bidiWordList( + words: list[str] | tuple[str], direction: str = "RTL", clean: bool = True, wx: bool = False +) -> list[Incomplete]: ... + +rtlSupport: bool + +class _PDFColorSetter: + def setFillColorCMYK(self, c: float, m: float, y: float, k: float, alpha: float | None = None) -> None: ... + def setStrokeColorCMYK(self, c: float, m: float, y: float, k: float, alpha: float | None = None) -> None: ... + def setFillColorRGB(self, r: float, g: float, b: float, alpha: float | None = None) -> None: ... + def setStrokeColorRGB(self, r: float, g: float, b: float, alpha: float | None = None) -> None: ... + def setFillColor(self, aColor: _Color, alpha: float | None = None) -> None: ... + def setStrokeColor(self, aColor: _Color, alpha: float | None = None) -> None: ... + def setFillGray(self, gray: float, alpha: float | None = None) -> None: ... + def setStrokeGray(self, gray: float, alpha: float | None = None) -> None: ... + def setStrokeAlpha(self, a: float) -> None: ... + def setFillAlpha(self, a: float) -> None: ... + def setStrokeOverprint(self, a) -> None: ... + def setFillOverprint(self, a) -> None: ... + def setOverprintMask(self, a) -> None: ... + +class PDFTextObject(_PDFColorSetter): + direction: Literal["LTR", "RTL"] + def __init__(self, canvas: Canvas, x: float = 0, y: float = 0, direction: Literal["LTR", "RTL"] | None = None) -> None: ... + def getCode(self) -> str: ... + def setTextOrigin(self, x: float, y: float) -> None: ... + def setTextTransform(self, a: float, b: float, c: float, d: float, e: float, f: float) -> None: ... + def moveCursor(self, dx: float, dy: float) -> None: ... + def setXPos(self, dx: float) -> None: ... + def getCursor(self) -> tuple[float, float]: ... + def getStartOfLine(self) -> tuple[float, float]: ... + def getX(self) -> float: ... + def getY(self) -> float: ... + def setFont(self, psfontname: str, size: float, leading: float | None = None) -> None: ... + def setCharSpace(self, charSpace: float) -> None: ... + def setWordSpace(self, wordSpace: float) -> None: ... + def setHorizScale(self, horizScale: float) -> None: ... + def setLeading(self, leading: float) -> None: ... + def setTextRenderMode(self, mode: Literal[0, 1, 2, 3, 4, 5, 6, 7]) -> None: ... + def setRise(self, rise: float) -> None: ... + def textOut(self, text: str) -> None: ... + def textLine(self, text: str = "") -> None: ... + def textLines(self, stuff: list[str] | tuple[str, ...] | str, trim: Literal[0, 1] = 1) -> None: ... + def __nonzero__(self) -> bool: ... diff --git a/stubs/reportlab/reportlab/platypus/__init__.pyi b/stubs/reportlab/reportlab/platypus/__init__.pyi new file mode 100644 index 000000000000..973e8dec08fe --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/__init__.pyi @@ -0,0 +1,12 @@ +from typing import Final + +from .doctemplate import * +from .flowables import * +from .frames import * +from .multicol import * +from .paragraph import * +from .paraparser import * +from .tables import * +from .xpreformatted import * + +__version__: Final[str] diff --git a/stubs/reportlab/reportlab/platypus/doctemplate.pyi b/stubs/reportlab/reportlab/platypus/doctemplate.pyi new file mode 100644 index 000000000000..ca2ec31b2fe3 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/doctemplate.pyi @@ -0,0 +1,325 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Callable +from typing import IO, Any, Literal, Protocol, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self, Unpack + +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.flowables import Flowable +from reportlab.platypus.frames import Frame + +__all__ = ( + "ActionFlowable", + "BaseDocTemplate", + "CurrentFrameFlowable", + "FrameActionFlowable", + "FrameBreak", + "Indenter", + "IndexingFlowable", + "LayoutError", + "LCActionFlowable", + "NextFrameFlowable", + "NextPageTemplate", + "NotAtTopPageBreak", + "NullActionFlowable", + "PageAccumulator", + "PageBegin", + "PageTemplate", + "SimpleDocTemplate", +) + +# NOTE: Since we don't know what kind of DocTemplate we will use in a PageTemplate +# we'll leave the second argument at Any, since the workaround with unbound +# type vars didn't seem to work for this one +_PageCallback: TypeAlias = Callable[[Canvas, Any], object] + +@type_check_only +class _CanvasMaker(Protocol): + # NOTE: This matches a subset of Canvas.__init__ + def __call__( + self, + filename: str | IO[bytes], + /, + *, + pagesize=None, + pageCompression=None, + invariant=None, + enforceColorSpace=None, + initialFontName=None, + initialFontSize=None, + initialLeading=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + lang=None, + ) -> Canvas: ... + +class LayoutError(Exception): ... + +# NOTE: While internal, this is used as sentinel value in PageTemplate +# and SimpleDocTemplate so in subclasses you may need to use this +def _doNothing(canvas: Canvas, doc: BaseDocTemplate) -> None: ... + +class PTCycle(list[PageTemplate]): + @property + def next_value(self) -> PageTemplate: ... + @property + def peek(self) -> PageTemplate: ... + +class IndexingFlowable(Flowable): + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> int: ... + def notify(self, kind: str, stuff: Any) -> None: ... + def beforeBuild(self) -> None: ... + def afterBuild(self) -> None: ... + +class ActionFlowable(Flowable): + # NOTE: Technically action always has to contain a string referencing + # a handle_ method on the DocTemplate, while the rest are the args + # that should be passed to that method, but since the default arg + # on __init__ violates that we might as well keep things simple + action: tuple[Any, ...] + def __init__(self, action: list[Any] | tuple[Any, ...] = ()) -> None: ... + def apply(self, doc: BaseDocTemplate) -> None: ... + def __call__(self) -> Self: ... + +class NullActionFlowable(ActionFlowable): ... + +class LCActionFlowable(ActionFlowable): + locChanger: int + def draw(self) -> None: ... + +class NextFrameFlowable(ActionFlowable): + locChanger: int + def __init__(self, ix: int | str, resume: int = 0) -> None: ... + +class CurrentFrameFlowable(LCActionFlowable): + def __init__(self, ix: int | str, resume: int = 0) -> None: ... + +class _FrameBreak(LCActionFlowable): + def __call__(self, ix: int | str | None = None, resume: int = 0) -> Self: ... + def apply(self, doc: BaseDocTemplate) -> None: ... + +FrameBreak: _FrameBreak +PageBegin: LCActionFlowable + +class FrameActionFlowable(Flowable): + @abstractmethod + def __init__(self, *arg: Any, **kw: Any) -> None: ... + @abstractmethod + def frameAction(self, frame: Frame) -> None: ... + +class Indenter(FrameActionFlowable): + width: float + height: float + left: float + right: float + def __init__(self, left: float | str = 0, right: float | str = 0) -> None: ... + def frameAction(self, frame: Frame) -> None: ... + +class NotAtTopPageBreak(FrameActionFlowable): + locChanger: int + nextTemplate: Incomplete + def __init__(self, nextTemplate=None) -> None: ... + def frameAction(self, frame: Frame) -> None: ... + +class NextPageTemplate(ActionFlowable): + locChanger: int + def __init__(self, pt: str | int | list[str] | tuple[str, ...]) -> None: ... + +class PageTemplate: + id: str | None + frames: list[Frame] + onPage: _PageCallback + onPageEnd: _PageCallback + pagesize: tuple[float, float] + autoNextPageTemplate: Incomplete + cropBox: Incomplete + artBox: Incomplete + trimBox: Incomplete + bleedBox: Incomplete + def __init__( + self, + id: str | None = None, + frames: list[Frame] | Frame = [], + onPage: _PageCallback = ..., + onPageEnd: _PageCallback = ..., + pagesize: tuple[float, float] | None = None, + autoNextPageTemplate=None, + cropBox=None, + artBox=None, + trimBox=None, + bleedBox=None, + ) -> None: ... + def beforeDrawPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def checkPageSize(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def afterDrawPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + +class onDrawStr(str): + onDraw: Callable[[Canvas, str | None, str], object] + kind: str | None + label: str + def __new__( + cls, value: object, onDraw: Callable[[Canvas, str | None, str], object], label: str, kind: str | None = None + ) -> Self: ... + def __getnewargs__(self) -> tuple[str, Callable[[Canvas, str | None, str], object], str, str | None]: ... # type: ignore[override] + +_OnDrawStr: TypeAlias = onDrawStr + +class PageAccumulator: + name: str + data: list[tuple[Any, ...]] + def __init__(self, name: str | None = None) -> None: ... + def reset(self) -> None: ... + def add(self, *args) -> None: ... + def onDrawText(self, *args) -> str: ... + def __call__(self, canv: Canvas, kind: str | None, label: str) -> None: ... + def attachToPageTemplate(self, pt: PageTemplate) -> None: ... + def onPage(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def onPageEnd(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def pageEndAction(self, canv: Canvas, doc: BaseDocTemplate) -> None: ... + def onDrawStr(self, value: object, *args) -> _OnDrawStr: ... + +@type_check_only +class _DocTemplateKwargs(TypedDict, total=False): + pagesize: Incomplete + pageTemplates: list[PageTemplate] + showBoundary: Incomplete + width: float + height: float + leftMargin: float + rightMargin: float + topMargin: float + bottomMargin: float + allowSplitting: Incomplete + title: Incomplete | None + author: Incomplete | None + subject: Incomplete | None + creator: Incomplete | None + producer: Incomplete | None + keywords: list[Incomplete] + invariant: Incomplete | None + pageCompression: Incomplete | None + rotation: Incomplete + encrypt: Incomplete | None + cropMarks: Incomplete | None + enforceColorSpace: Incomplete | None + displayDocTitle: Incomplete | None + lang: Incomplete | None + initialFontName: Incomplete | None + initialFontSize: Incomplete | None + initialLeading: Incomplete | None + cropBox: Incomplete | None + artBox: Incomplete | None + trimBox: Incomplete | None + bleedBox: Incomplete | None + keepTogetherClass: type[Flowable] + hideToolbar: Incomplete | None + hideMenubar: Incomplete | None + hideWindowUI: Incomplete | None + fitWindow: Incomplete | None + centerWindow: Incomplete | None + nonFullScreenPageMode: Incomplete | None + direction: Incomplete | None + viewArea: Incomplete | None + viewClip: Incomplete | None + printArea: Incomplete | None + printClip: Incomplete | None + printScaling: Incomplete | None + duplex: Incomplete | None + +class BaseDocTemplate: + filename: Incomplete + pagesize: Incomplete + pageTemplates: list[PageTemplate] + showBoundary: Incomplete + width: float + height: float + leftMargin: float + rightMargin: float + topMargin: float + bottomMargin: float + allowSplitting: Incomplete + title: Incomplete | None + author: Incomplete | None + subject: Incomplete | None + creator: Incomplete | None + producer: Incomplete | None + keywords: list[Incomplete] + invariant: Incomplete | None + pageCompression: Incomplete | None + rotation: Incomplete + encrypt: Incomplete | None + cropMarks: Incomplete | None + enforceColorSpace: Incomplete | None + displayDocTitle: Incomplete | None + lang: Incomplete | None + initialFontName: Incomplete | None + initialFontSize: Incomplete | None + initialLeading: Incomplete | None + cropBox: Incomplete | None + artBox: Incomplete | None + trimBox: Incomplete | None + bleedBox: Incomplete | None + keepTogetherClass: type[Flowable] + hideToolbar: Incomplete | None + hideMenubar: Incomplete | None + hideWindowUI: Incomplete | None + fitWindow: Incomplete | None + centerWindow: Incomplete | None + nonFullScreenPageMode: Incomplete | None + direction: Incomplete | None + viewArea: Incomplete | None + viewClip: Incomplete | None + printArea: Incomplete | None + printClip: Incomplete | None + printScaling: Incomplete | None + duplex: Incomplete | None + # NOTE: The following attributes only exist while/after pages are rendered + pageTemplate: PageTemplate + page: int + frame: Frame + canv: Canvas + def __init__(self, filename: str | IO[bytes], **kw: Unpack[_DocTemplateKwargs]) -> None: ... + def setPageCallBack(self, func: Callable[[int], object] | None) -> None: ... + def setProgressCallBack(self, func: Callable[[str, int], object] | None) -> None: ... + def clean_hanging(self) -> None: ... + def addPageTemplates(self, pageTemplates: list[PageTemplate] | tuple[PageTemplate, ...] | PageTemplate) -> None: ... + def handle_documentBegin(self) -> None: ... + def handle_pageBegin(self) -> None: ... + def handle_pageEnd(self) -> None: ... + def handle_pageBreak(self, slow: bool | None = None) -> None: ... + def handle_frameBegin(self, resume: int = 0, pageTopFlowables=None) -> None: ... + def handle_frameEnd(self, resume: int = 0) -> None: ... + def handle_nextPageTemplate(self, pt: str | int | list[str] | tuple[str, ...]) -> None: ... + def handle_nextFrame(self, fx: str | int, resume: int = 0) -> None: ... + def handle_currentFrame(self, fx: str | int, resume: int = 0) -> None: ... + def handle_breakBefore(self, flowables: list[Flowable]) -> None: ... + def handle_keepWithNext(self, flowables: list[Flowable]) -> None: ... + def handle_flowable(self, flowables: list[Flowable]) -> None: ... + def build( + self, flowables: list[Flowable], filename: str | IO[bytes] | None = None, canvasmaker: _CanvasMaker = ... + ) -> None: ... + def notify(self, kind: str, stuff: Any) -> None: ... + def pageRef(self, label: str) -> None: ... + def multiBuild(self, story: list[Flowable], maxPasses: int = 10, **buildKwds: Any) -> int: ... + def afterInit(self) -> None: ... + def beforeDocument(self) -> None: ... + def beforePage(self) -> None: ... + def afterPage(self) -> None: ... + def filterFlowables(self, flowables: list[Flowable]) -> None: ... + def afterFlowable(self, flowable: Flowable) -> None: ... + def docAssign(self, var: str, expr: object, lifetime: str) -> None: ... + def docExec(self, stmt: str, lifetime: str) -> None: ... + def docEval(self, expr: str) -> Any: ... + +class SimpleDocTemplate(BaseDocTemplate): + def handle_pageBegin(self) -> None: ... + def build( # type: ignore[override] + self, + flowables: list[Flowable], + onFirstPage: _PageCallback = ..., + onLaterPages: _PageCallback = ..., + canvasmaker: _CanvasMaker = ..., + ) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/figures.pyi b/stubs/reportlab/reportlab/platypus/figures.pyi new file mode 100644 index 000000000000..8433c7e14f04 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/figures.pyi @@ -0,0 +1,108 @@ +from _typeshed import Incomplete +from typing import Final + +from reportlab.platypus import Flowable + +__version__: Final[str] +captionStyle: Incomplete + +class Figure(Flowable): + width: Incomplete + figureHeight: Incomplete + caption: Incomplete + captionFont: Incomplete + captionSize: Incomplete + captionTextColor: Incomplete + captionBackColor: Incomplete + captionGap: Incomplete + captionAlign: Incomplete + captionPosition: Incomplete + captionHeight: int + background: Incomplete + border: Incomplete + spaceBefore: Incomplete + spaceAfter: Incomplete + hAlign: Incomplete + def __init__( + self, + width, + height, + caption: str = "", + captionFont="Helvetica-Oblique", + captionSize: int = 12, + background=None, + captionTextColor=..., + captionBackColor=None, + border=None, + spaceBefore: int = 12, + spaceAfter: int = 12, + captionGap=None, + captionAlign: str = "centre", + captionPosition: str = "bottom", + hAlign: str = "CENTER", + ) -> None: ... + height: Incomplete + dx: Incomplete + def wrap(self, availWidth, availHeight): ... + def draw(self) -> None: ... + def drawBorder(self) -> None: ... + def drawBackground(self) -> None: ... + def drawCaption(self) -> None: ... + def drawFigure(self) -> None: ... + +def drawPage(canvas, x, y, width, height) -> None: ... + +class PageFigure(Figure): + caption: str + captionStyle: Incomplete + background: Incomplete + def __init__(self, background=None) -> None: ... + def drawVirtualPage(self) -> None: ... + def drawFigure(self) -> None: ... + +class PlatPropFigure1(PageFigure): + caption: str + def __init__(self) -> None: ... + def drawVirtualPage(self) -> None: ... + +class FlexFigure(Figure): + shrinkToFit: Incomplete + growToFit: Incomplete + scaleFactor: Incomplete + background: Incomplete + def __init__( + self, + width, + height, + caption, + background=None, + captionFont: str = "Helvetica-Oblique", + captionSize: int = 8, + captionTextColor=..., + shrinkToFit: int = 1, + growToFit: int = 1, + spaceBefore: int = 12, + spaceAfter: int = 12, + captionGap: int = 9, + captionAlign: str = "centre", + captionPosition: str = "top", + scaleFactor=None, + hAlign: str = "CENTER", + border: int = 1, + ) -> None: ... + def wrap(self, availWidth, availHeight): ... + def split(self, availWidth, availHeight): ... + +class ImageFigure(FlexFigure): + filename: Incomplete + def __init__(self, filename, caption, background=None, scaleFactor=None, hAlign: str = "CENTER", border=None) -> None: ... + def drawFigure(self) -> None: ... + +class DrawingFigure(FlexFigure): + drawing: Incomplete + growToFit: int + def __init__(self, modulename, classname, caption, baseDir=None, background=None) -> None: ... + def drawFigure(self) -> None: ... + +def demo1(canvas) -> None: ... +def test1() -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/flowables.pyi b/stubs/reportlab/reportlab/platypus/flowables.pyi new file mode 100644 index 000000000000..893d705c3b0d --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/flowables.pyi @@ -0,0 +1,472 @@ +from _typeshed import Incomplete, SupportsRead, Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Never, Self + +from reportlab.lib.colors import Color +from reportlab.lib.styles import ListStyle, ParagraphStyle, PropertySet +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfgen.textobject import _Color +from reportlab.platypus.paragraph import Paragraph + +__all__ = [ + "AnchorFlowable", + "BalancedColumns", + "BulletDrawer", + "CallerMacro", + "CondPageBreak", + "DDIndenter", + "DocAssert", + "DocAssign", + "DocExec", + "DocIf", + "DocPara", + "DocWhile", + "FailOnDraw", + "FailOnWrap", + "Flowable", + "FrameBG", + "FrameSplitter", + "HRFlowable", + "Image", + "ImageAndFlowables", + "KeepInFrame", + "KeepTogether", + "LIIndenter", + "ListFlowable", + "ListItem", + "Macro", + "NullDraw", + "PTOContainer", + "PageBreak", + "PageBreakIfNotEmpty", + "ParagraphAndImage", + "Preformatted", + "SetPageTopFlowables", + "SetTopFlowables", + "SlowPageBreak", + "Spacer", + "TopPadder", + "TraceInfo", + "UseUpSpace", + "XBox", + "splitLine", + "splitLines", + "PlacedStory", +] + +_HAlignment: TypeAlias = Literal["LEFT", "CENTER", "CENTRE", "RIGHT", 0, 1, 2] +_VAlignment: TypeAlias = Literal["BOTTOM", "MIDDLE", "TOP"] +# FIXME: Consider using Sequence[Flowable] for covariance on list, even though +# that will give false negatives for non list or tuple sequences, it also +# would reduce type safety, since flowables don't copy the list +_FlowableSublist: TypeAlias = Flowable | list[Flowable] | tuple[Flowable, ...] +# NOTE: Technically can only be list or tuple, but would be annoying for variance +_NestedFlowable: TypeAlias = Flowable | Sequence[_NestedFlowable] + +@type_check_only +class _StyledFlowableFactory(Protocol): + # NOTE: We leave style at Any so people can specify a specifc property set + def __call__(self, value: str, /, *, style: Any) -> Flowable: ... + +class TraceInfo: + srcFile: str + startLineNo: int + startLinePos: int + endLineNo: int + endLinePos: int + def __init__(self) -> None: ... + +class Flowable: + width: float + height: float + wrapped: int + hAlign: _HAlignment + vAlign: _VAlignment + encoding: str | None + # NOTE: this only exists during drawing, splitting and wrapping + canv: Canvas + # NOTE: The following attributes will not exist on all flowables, but + # they need to be settable on individual instances + keepWithNext: Incomplete + spaceAfter: float + spaceBefore: float + def __init__(self) -> None: ... + # NOTE: We pretend the optional internal _sW argument does not exist + # since not all flowables support it and we'd have to deal with + # a bunch of LSP errors. Conversely we will get type errors in + # subclasses that rely on the argument existing when called through + # super() inside their own implementation, so we can't really + # make everyone happy here, sigh... + def drawOn(self, canvas: Canvas, x: float, y: float) -> None: ... + def wrapOn(self, canv: Canvas, aW: float, aH: float) -> tuple[float, float]: ... + def wrap(self, aW: float, aH: float) -> tuple[float, float]: ... + def minWidth(self) -> float: ... + def splitOn(self, canv: Canvas, aW: float, aH: float) -> list[Flowable]: ... + def split(self, aW: float, aH: float, /) -> list[Flowable]: ... + def getKeepWithNext(self): ... + def getSpaceAfter(self) -> float: ... + def getSpaceBefore(self) -> float: ... + def isIndexing(self) -> int: ... + def identity(self, maxLen: int | None = None) -> str: ... + +class XBox(Flowable): + text: str + def __init__(self, width: float, height: float, text: str = "A Box") -> None: ... + def draw(self) -> None: ... + +def splitLines(lines, maximum_length, split_characters, new_line_characters): ... +def splitLine(line_to_split, lines_splitted, maximum_length, split_characters, new_line_characters) -> None: ... + +class Preformatted(Flowable): + style: ParagraphStyle + bulletText: str | None + lines: list[str] + def __init__( + self, + text: str, + # NOTE: Technically has to be a ParagraphStyle, but that would + # conflict with stylesheet["Style"] usage + style: PropertySet, + bulletText: str | None = None, + dedent: int = 0, + maxLineLength: int | None = None, + splitChars: str | None = None, + newLineChars: str = "", + ) -> None: ... + def draw(self) -> None: ... + +class Image(Flowable): + filename: str + # these are lazy, but __getattr__ ensures the image gets loaded + # as soon as these attributes are accessed + imageWidth: int + imageHeight: int + drawWidth: float + drawHeight: float + def __init__( + self, + # TODO: I think this might also accept a PIL.Image and other + # kinds of path represenations, should be kept in sync + # with reportlab.lib.utils.ImageReader, except for the + # potential PIL.Image shortcut + filename: str | SupportsRead[bytes] | Incomplete, + width: float | None = None, + height: float | None = None, + kind: str = "direct", + mask: str = "auto", + lazy: int = 1, + hAlign: _HAlignment = "CENTER", + useDPI: bool = False, + ) -> None: ... + def draw(self) -> None: ... + +class NullDraw(Flowable): + def draw(self) -> None: ... + +class Spacer(NullDraw): + # NOTE: This may actually be a bug, it seems likely that Spacer is meant + # to set spaceBefore in the isGlue case. + spacebefore: float + def __init__(self, width: float, height: float, isGlue: bool = False) -> None: ... + +class UseUpSpace(NullDraw): ... + +class PageBreak(UseUpSpace): + locChanger: int + nextTemplate: str | None + def __init__(self, nextTemplate: str | None = None) -> None: ... + +class SlowPageBreak(PageBreak): ... +class PageBreakIfNotEmpty(PageBreak): ... + +class CondPageBreak(Spacer): + locChanger: int + def __init__(self, height: float) -> None: ... + +class _ContainerSpace: + def getSpaceBefore(self) -> float: ... + def getSpaceAfter(self) -> float: ... + +class KeepTogether(_ContainerSpace, Flowable): + splitAtTop: bool + # TODO: Consider using Sequence[Flowable] for covariance, even if reportlab + # only supports list/tuple + def __init__(self, flowables: _FlowableSublist | None, maxHeight=None) -> None: ... + +class KeepTogetherSplitAtTop(KeepTogether): + splitAtTop: bool + +class Macro(Flowable): + command: str + def __init__(self, command: str) -> None: ... + def draw(self) -> None: ... + +class CallerMacro(Flowable): + def __init__( + self, + drawCallable: Callable[[CallerMacro, float, float], object] | None = None, + wrapCallable: Callable[[CallerMacro, float, float], object] | None = None, + ) -> None: ... + def draw(self) -> None: ... + +class ParagraphAndImage(Flowable): + P: Paragraph + I: Image + xpad: float + ypad: float + def __init__(self, P: Paragraph, I: Image, xpad: float = 3, ypad: float = 3, side: str = "right") -> None: ... + def draw(self) -> None: ... + +class FailOnWrap(NullDraw): + def wrap(self, aW: float, aH: float) -> Never: ... + +class FailOnDraw(Flowable): + def draw(self) -> Never: ... + +class HRFlowable(Flowable): + width: float | str # type: ignore[assignment] + lineWidth: float + lineCap: str + color: _Color + dash: Incomplete | None + def __init__( + self, + width: float | str = "80%", + thickness: float = 1, + lineCap: str = "round", + color: _Color = ..., + spaceBefore: float = 1, + spaceAfter: float = 1, + hAlign: _HAlignment = "CENTER", + vAlign: _VAlignment = "BOTTOM", + dash=None, + ) -> None: ... + def draw(self) -> None: ... + +class _Container(_ContainerSpace): + def drawOn(self, canv: Canvas, x: float, y: float) -> None: ... + def copyContent(self, content: _FlowableSublist | None = None) -> None: ... + +class PTOContainer(_Container, Flowable): # pyrefly: ignore [inconsistent-inheritance] + def __init__( + self, content: _FlowableSublist | None, trailer: _FlowableSublist | None = None, header: _FlowableSublist | None = None + ) -> None: ... + +class KeepInFrame(_Container, Flowable): # pyrefly: ignore [inconsistent-inheritance] + name: str + maxWidth: float + maxHeight: float + mode: Literal["error", "continue", "shrink", "truncate"] + mergespace: Incomplete | None + fakeWidth: bool | None + def __init__( + self, + maxWidth: float, + maxHeight: float, + content: list[Flowable] = [], + mergeSpace: Incomplete | None = 1, + mode: Literal["error", "continue", "shrink", "truncate"] = "shrink", + name: str = "", + hAlign: str = "LEFT", + vAlign: str = "BOTTOM", + fakeWidth: bool | None = None, + ) -> None: ... + +class PlacedStory(Flowable): + def __init__( + self, + x, + y, + maxWidth: float, + maxHeight: float, + content: list[Flowable] = [], + mergeSpace: Incomplete | None = 1, + mode: Literal["error", "continue", "shrink", "truncate"] = "shrink", + name: str = "", + anchor: str = "sw", + fakeWidth: bool | None = None, + hAlign: str = "LEFT", + vAlign: str = "BOTTOM", + showBoundary=None, + origin="page", + ) -> None: ... + def wrap(self, _aW: Unused, _aH: Unused) -> tuple[Literal[0], Literal[0]]: ... + def drawOn(self, canv: Canvas, lx: float, ly: float, _sW=0) -> None: ... + +class _FindSplitterMixin: ... + +class ImageAndFlowables(_Container, _FindSplitterMixin, Flowable): # pyrefly: ignore [inconsistent-inheritance] + imageHref: str | None + def __init__( + self, + I: Image, + F: _FlowableSublist | None, + imageLeftPadding: float = 0, + imageRightPadding: float = 3, + imageTopPadding: float = 0, + imageBottomPadding: float = 3, + imageSide: str = "right", + imageHref: str | None = None, + ) -> None: ... + def deepcopy(self) -> Self: ... + +class BalancedColumns(_FindSplitterMixin, NullDraw): + name: str + showBoundary: Incomplete | None + endSlack: float + def __init__( + self, + F: _FlowableSublist | None, + nCols: int = 2, + needed: float = 72, + spaceBefore: float = 0, + spaceAfter: float = 0, + showBoundary=None, + leftPadding: float | None = None, + innerPadding: float | None = None, + rightPadding: float | None = None, + topPadding: float | None = None, + bottomPadding: float | None = None, + name: str = "", + endSlack: float = 0.1, + boxStrokeColor: Color | None = None, + boxStrokeWidth: float = 0, + boxFillColor: Color | None = None, + boxMargin: tuple[int, int, int, int] | tuple[int, int, int] | tuple[int, int] | tuple[int] | None = None, + vLinesStrokeColor: Color | None = None, + vLinesStrokeWidth: float | None = None, + ) -> None: ... + +class AnchorFlowable(Spacer): + def __init__(self, name: str) -> None: ... + +class FrameBG(AnchorFlowable): + start: bool + left: float + right: float + color: Color + strokeWidth: float + strokeColor: Color + strokeDashArray: list[float] | tuple[float, ...] | None + def __init__( + self, + color: Color | None = None, + left: float | str = 0, + right: float | str = 0, + start: bool = True, + strokeWidth: float | None = None, + strokeColor: Color | None = None, + strokeDashArray: list[float] | tuple[float, ...] | None = None, + ) -> None: ... + +class FrameSplitter(NullDraw): + nextTemplate: str + nextFrames: list[str] + gap: float + required: float + adjustHeight: bool + def __init__( + self, + nextTemplate: str, + nextFrames: list[str] | None = [], + gap: float = 10, + required: float = 72, + adjustHeight: bool = True, + ) -> None: ... + +class BulletDrawer: + value: str + def __init__( + self, + value: str = "0", + bulletAlign: str = "left", + bulletType: str = "1", + bulletColor: str = "black", + bulletFontName: str = "Helvetica", + bulletFontSize: int = 12, + bulletOffsetY: int = 0, + bulletDedent: int = 0, + bulletDir: str = "ltr", + bulletFormat=None, + ) -> None: ... + def drawOn(self, indenter: DDIndenter, canv: Canvas, x: float, y: float) -> None: ... + +class DDIndenter(Flowable): + def __init__(self, flowable: Flowable, leftIndent: float = 0, rightIndent: float = 0) -> None: ... + +class LIIndenter(DDIndenter): + def __init__( + self, + flowable: Flowable, + leftIndent: float = 0, + rightIndent: float = 0, + bullet=None, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + ) -> None: ... + +class ListItem: + # NOTE: style has to be a ListStyle, but this will be annoying with sheet["ul"] + # TODO: Use Unpack for kwds with the ListStyle properties + value/spaceBefore/spaceAfter + def __init__(self, flowables: _FlowableSublist, style: PropertySet | None = None, **kwds) -> None: ... + +class ListFlowable(_Container, Flowable, _FindSplitterMixin): # pyrefly: ignore [inconsistent-inheritance] + style: ListStyle + # NOTE: style has to be a ListStyle, but this will be annoying with sheet["ul"] + # TODO: Use Unpack for kwds with the ListStyle properties + spaceBefore/spaceAfter + def __init__(self, flowables: Iterable[_NestedFlowable], start=None, style: PropertySet | None = None, **kwds) -> None: ... + +class TopPadder(Flowable): + # NOTE: TopPadder is mostly a transparent wrapper, we may consider trying + # something using __new__ in the future + def __init__(self, f: Flowable) -> None: ... + def __setattr__(self, a: str, v: Any) -> None: ... + def __getattr__(self, a: str) -> Any: ... + def __delattr__(self, a: str) -> None: ... + +class DocAssign(NullDraw): + args: tuple[Any, ...] + def __init__(self, var: str, expr: object, life: str = "forever") -> None: ... + def funcWrap(self, aW: float, aH: float) -> None: ... + def func(self) -> None: ... + +class DocExec(DocAssign): + def __init__(self, stmt: str, lifetime: str = "forever") -> None: ... + +class DocPara(DocAssign): + expr: object + format: str | None + style: PropertySet | None + klass: Incomplete + escape: bool + def __init__( + self, + expr: object, + format: str | None = None, + style: PropertySet | None = None, + klass: _StyledFlowableFactory | None = None, + escape: bool = True, + ) -> None: ... + def funcWrap(self, aW: float, aH: float) -> Any: ... + def func(self) -> Any: ... + def add_content(self, *args: Flowable) -> None: ... + def get_value(self, aW: float, aH: float) -> str: ... + +class DocAssert(DocPara): + def __init__(self, cond: object, format: str | None = None) -> None: ... + +class DocIf(DocPara): + blocks: tuple[_FlowableSublist, _FlowableSublist] + def __init__(self, cond: object, thenBlock: _FlowableSublist, elseBlock: _FlowableSublist = []) -> None: ... + def checkBlock(self, block: _FlowableSublist) -> list[Flowable] | tuple[Flowable, ...]: ... + +class DocWhile(DocIf): + block: _FlowableSublist + def __init__(self, cond: object, whileBlock: _FlowableSublist) -> None: ... + +class SetTopFlowables(NullDraw): + def __init__(self, F: list[Flowable], show: bool = False) -> None: ... + +class SetPageTopFlowables(NullDraw): + def __init__(self, F: list[Flowable], show: bool = False) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/frames.pyi b/stubs/reportlab/reportlab/platypus/frames.pyi new file mode 100644 index 000000000000..f8e832c1b83a --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/frames.pyi @@ -0,0 +1,38 @@ +from typing import Literal + +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.flowables import Flowable + +class Frame: + id: str | None + x1: float + y1: float + width: float + height: float + leftPadding: float + bottomPadding: float + rightPadding: float + topPadding: float + showBoundary: int + def __init__( + self, + x1: float, + y1: float, + width: float, + height: float, + leftPadding: float = 6, + bottomPadding: float = 6, + rightPadding: float = 6, + topPadding: float = 6, + id: str | None = None, + showBoundary: int = 0, + overlapAttachedSpace=None, + _debug=None, + ) -> None: ... + def add(self, flowable: Flowable, canv: Canvas, trySplit: int = 0) -> Literal[0, 1]: ... + def split(self, flowable: Flowable, canv: Canvas) -> list[Flowable]: ... + def drawBoundary(self, canv: Canvas) -> None: ... + def addFromList(self, drawlist: list[Flowable], canv: Canvas) -> None: ... + def add_generated_content(self, *C: Flowable) -> None: ... + +__all__ = ("Frame",) diff --git a/stubs/reportlab/reportlab/platypus/multicol.pyi b/stubs/reportlab/reportlab/platypus/multicol.pyi new file mode 100644 index 000000000000..09fe9cdb8e31 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/multicol.pyi @@ -0,0 +1,19 @@ +from collections.abc import Sequence + +from .flowables import Flowable, _Container, _FindSplitterMixin + +class MultiCol(_Container, _FindSplitterMixin, Flowable): # pyrefly: ignore [inconsistent-inheritance] + contents: Sequence[Flowable] + widths: Sequence[float | str] + minHeightNeeded: float + def __init__( + self, + contents: Sequence[Flowable], + widths: Sequence[float | str], + minHeightNeeded: float = 36, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + ) -> None: ... + def nWidths(self, aW: float) -> list[float]: ... + +__all__ = ["MultiCol"] diff --git a/stubs/reportlab/reportlab/platypus/para.pyi b/stubs/reportlab/reportlab/platypus/para.pyi new file mode 100644 index 000000000000..f2205c40992b --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/para.pyi @@ -0,0 +1,276 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Mapping +from typing import Any, Final, Literal, Protocol, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.styles import ParagraphStyle, PropertySet, StyleSheet1 +from reportlab.pdfgen.canvas import Canvas +from reportlab.pdfgen.textobject import PDFTextObject, _Color +from reportlab.platypus.flowables import Flowable + +_T = TypeVar("_T") +_BoolInt: TypeAlias = Literal[0, 1] +_Op: TypeAlias = _SupportsWidthAndExecute | str | float | tuple[str, Unpack[tuple[Any, ...]]] +# NOTE: Output from pyRXP xml parser +_ParsedText: TypeAlias = tuple[str, dict[str, Any], list[_ParsedText], Any] | list[_ParsedText] | str + +@type_check_only +class _LineOpHandler(Protocol): + def start_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + def end_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + +@type_check_only +class _SupportsWidthAndExecute(Protocol): + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> object: ... + +@type_check_only +class _SimpleStyleKwargs(TypedDict, total=False): + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: Literal[0, 1, 2, 4] + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: _Color + backColor: _Color | None + +debug: int +DUMPPROGRAM: int +TOOSMALLSPACE: float + +class paragraphEngine: + TEXT_STATE_VARIABLES: Final[tuple[str, ...]] + lineOpHandlers: list[_LineOpHandler] + program: list[_Op] + indent: float + baseindent: float + fontName: str + fontSize: float + leading: float + fontColor: _Color + x: float + y: float + alignment: Literal[0, 1, 2, 4] + # NOTE: The inner list matches TEXT_STATE_VARIABLES + textStateStack: list[list[Any]] + def __init__(self, program: list[_Op] | None = None) -> None: ... + def pushTextState(self) -> list[Any]: ... + def popTextState(self) -> None: ... + def format( + self, maxwidth: float, maxheight: float, program: list[_Op], leading: float = 0 + ) -> tuple[list[_Op], str, dict[str, Any], float]: ... + def getState(self) -> dict[str, Any]: ... + def resetState(self, state: dict[str, Any]) -> None: ... + def fitLine( + self, program: list[_Op], totalLength: float + ) -> tuple[Literal[0, 1], list[_Op], int, float, float, float, Literal[0, 1]]: ... + def centerAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def rightAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def insertShift(self, line: list[_Op], shift: float) -> list[_Op]: ... + def justifyAlign(self, line: list[_Op], lineLength: float, maxLength: float) -> list[_Op]: ... + def shrinkWrap(self, line: list[_Op]) -> list[_Op]: ... + def cleanProgram(self, line: list[_Op]) -> list[_Op]: ... + def runOpCodes(self, program: list[_Op], canvas: Canvas, textobject: PDFTextObject) -> dict[str, Any]: ... + +def stringLine(line: list[_Op], length: float) -> list[_Op]: ... +def simpleJustifyAlign(line: list[_Op], currentLength: float, maxLength: float) -> list[_Op]: ... +def readBool(text: str) -> _BoolInt: ... +def readAlignment(text: str) -> Literal[0, 1, 2, 4] | None: ... +def readLength(text: str) -> float: ... + +@overload +def lengthSequence(s: str, converter: Callable[[str], float] = ...) -> list[float]: ... +@overload +def lengthSequence(s: str, converter: Callable[[str], _T]) -> list[_T]: ... + +def readColor(text: str | None) -> Color | None: ... + +class StyleAttributeConverters: + fontSize: list[Callable[[str], float]] + leading: list[Callable[[str], float]] + leftIndent: list[Callable[[str], float]] + rightIndent: list[Callable[[str], float]] + firstLineIndent: list[Callable[[str], float]] + alignment: list[Callable[[str], Literal[0, 1, 2, 4] | None]] + spaceBefore: list[Callable[[str], float]] + spaceAfter: list[Callable[[str], float]] + bulletFontSize: list[Callable[[str], float]] + bulletIndent: list[Callable[[str], float]] + textColor: list[Callable[[str], Color | None]] + backColor: list[Callable[[str], Color | None]] + +class SimpleStyle: + name: str + fontName: str + fontSize: float + leading: float + leftIndent: float + rightIndent: float + firstLineIndent: float + alignment: Literal[0, 1, 2, 4] + spaceBefore: float + spaceAfter: float + bulletFontName: str + bulletFontSize: float + bulletIndent: float + textColor: _Color + backColor: _Color | None + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + def __init__(self, name: str, parent: SimpleStyle | PropertySet | None = None, **kw: Unpack[_SimpleStyleKwargs]) -> None: ... + def addAttributes(self, dictionary: Mapping[str, str | None]) -> None: ... + +DEFAULT_ALIASES: Final[dict[str, str]] + +class FastPara(Flowable): + style: SimpleStyle | ParagraphStyle + simpletext: str + lines: list[str] | None + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + def __init__(self, style: SimpleStyle | PropertySet, simpletext: str) -> None: ... + def draw(self) -> None: ... + +def defaultContext() -> dict[str, PropertySet]: ... +def buildContext(stylesheet: StyleSheet1 | None = None) -> dict[str, PropertySet]: ... + +class Para(Flowable): + baseindent: float + context: dict[str, PropertySet] + parsedText: _ParsedText + bulletText: str | None + style1: SimpleStyle | PropertySet + program: list[_Op] + formattedProgram: list[_Op] + remainder: _ParsedText + state: dict[str, Any] + bold: _BoolInt + italic: _BoolInt + face: str + size: float + def __init__( + self, + # NOTE: We are being generous by allowing PropertySet i.e. ParagraphStyle here + # technically SimpleStyle is more strict and doesn't allow string alignments + style: SimpleStyle | PropertySet, + parsedText: tuple[Any, ...] | None = None, + bulletText: str | None = None, + state: dict[str, Any] | None = None, + context: dict[str, PropertySet] | None = None, + baseindent: float = 0, + ) -> None: ... + def draw(self) -> None: ... + def compileProgram(self, parsedText: _ParsedText, program: list[_Op] | None = None) -> list[_Op]: ... + def linearize(self, program: list[_Op] | None = None, parsedText: _ParsedText | None = None) -> None: ... + def compileComponent(self, parsedText: _ParsedText, program: list[_Op]) -> None: ... + def shiftfont( + self, program: list[_Op], face: str | None = None, bold: _BoolInt | None = None, italic: _BoolInt | None = None + ): ... + def compile_(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_pageNumber(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_b(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_i(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_u(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_sub(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_ul(self, attdict, content, extra, program: list[_Op], tagname: str = "ul") -> None: ... + def compile_ol(self, attdict, content, extra, program: list[_Op]): ... + def compile_dl(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_super(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_font(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_a(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_link(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_setLink(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_bullet(self, attdict, content, extra, program: list[_Op]) -> None: ... + def do_bullet(self, text: str, program: list[_Op]) -> None: ... + def compile_tt(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_greek(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_evalString(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_name(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_getName(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seq(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seqReset(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_seqDefault(self, attdict, content, extra, program: list[_Op]) -> None: ... + def compile_para(self, attdict, content, extra, program: list[_Op], stylename: str = "para.defaultStyle") -> None: ... + +class bulletMaker: + tagname: Literal["ul", "ol", "dl"] + style: str + typ: str + count: int + def __init__(self, tagname: Literal["ul", "ol", "dl"], atts, context) -> None: ... + def makeBullet(self, atts, bl: str | None = None) -> None: ... + +class EvalStringObject: + tagname: str + attdict: Incomplete + content: str + context: Incomplete + extra: Incomplete + op: Incomplete + def __init__(self, attdict, content: str, extra, context) -> None: ... + def getOp(self, tuple, engine): ... + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> None: ... + +class SeqObject(EvalStringObject): ... +class NameObject(EvalStringObject): ... +class SeqDefaultObject(NameObject): ... +class SeqResetObject(NameObject): ... +class GetNameObject(EvalStringObject): ... + +class PageNumberObject: + example: str + def __init__(self, example: str = "XXX") -> None: ... + def width(self, engine) -> float: ... + def execute(self, engine, textobject: PDFTextObject, canvas: Canvas) -> None: ... + +def EmbedInRml2pdf() -> None: ... +def handleSpecialCharacters(engine, text: str, program: list[_Op] | None = None) -> list[_Op]: ... +def Paragraph( + text: str, + style: SimpleStyle | PropertySet, + bulletText: str | None = None, + frags: Unused | None = None, + context: dict[str, PropertySet] | None = None, +) -> Para | FastPara: ... + +class UnderLineHandler: + color: _Color | None + # NOTE: available after start_at + xStart: float + yStart: float + def __init__(self, color: _Color | None = None) -> None: ... + def start_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + def end_at(self, x: float, y: float, para: paragraphEngine, canvas: Canvas, textobject: PDFTextObject) -> None: ... + +UNDERLINE: Final[UnderLineHandler] + +class HotLink(UnderLineHandler): + url: str + def __init__(self, url: str) -> None: ... + def link(self, rect, canvas: Canvas) -> None: ... + +class InternalLink(HotLink): ... + +class DefDestination(HotLink): + defined: _BoolInt + +def splitspace(text: str) -> list[str]: ... + +testparagraph: str +testparagraph1: str + +def test2(canv, testpara) -> None: ... + +testlink: Incomplete +test_program: Incomplete + +def test() -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/paragraph.pyi b/stubs/reportlab/reportlab/platypus/paragraph.pyi new file mode 100644 index 000000000000..6f38d99f8ec6 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/paragraph.pyi @@ -0,0 +1,40 @@ +from reportlab.lib.abag import ABag +from reportlab.lib.styles import ParagraphStyle, PropertySet +from reportlab.pdfgen.textobject import PDFTextObject +from reportlab.platypus.flowables import Flowable +from reportlab.platypus.paraparser import ParaFrag + +class ParaLines(ABag): ... +class FragLine(ABag): ... + +def cleanBlockQuotedText(text: str, joiner: str = " ") -> str: ... + +class Paragraph(Flowable): + text: str + frags: list[ParaFrag] + style: ParagraphStyle + bulletText: str | None + caseSensitive: int + encoding: str + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet | None = None, + bulletText: str | None = None, + frags: list[ParaFrag] | None = None, + caseSensitive: int = 1, + encoding: str = "utf8", + ) -> None: ... + def minWidth(self) -> float: ... + def draw(self) -> None: ... + def breakLines(self, width: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + def breakLinesCJK(self, maxWidths: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + def beginText(self, x: float, y: float) -> PDFTextObject: ... + def drawPara(self, debug: int = 0) -> None: ... + def getPlainText(self, identify: bool | None = None) -> str: ... + def getActualLineWidths0(self) -> list[float]: ... + @staticmethod + def dumpFrags(frags, indent: int = 4, full: bool = False) -> str: ... + +__all__ = ("Paragraph", "cleanBlockQuotedText", "ParaLines", "FragLine") diff --git a/stubs/reportlab/reportlab/platypus/paraparser.pyi b/stubs/reportlab/reportlab/platypus/paraparser.pyi new file mode 100644 index 000000000000..449946eb0806 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/paraparser.pyi @@ -0,0 +1,117 @@ +from _typeshed import Incomplete +from html.parser import HTMLParser + +from reportlab.lib.abag import ABag + +__all__ = ("ParaFrag", "ParaParser") + +class _PCT(float): + def __new__(cls, v): ... + def normalizedValue(self, normalizer): ... + def __copy__(self): ... + def __deepcopy__(self, mem): ... + +class _ExValidate: + tag: Incomplete + attr: Incomplete + def __init__(self, tag, attr) -> None: ... + def invalid(self, s) -> None: ... + def validate(self, parser, s): ... + def __call__(self, parser, s): ... + +class _CheckSup(_ExValidate): + fontSize: Incomplete + def validate(self, parser, s): ... + def __call__(self, parser, s): ... + +class _CheckUS(_ExValidate): + def validate(self, parser, s): ... + +class ParaFrag(ABag): ... + +class ParaParser(HTMLParser): + def __getattr__(self, attrName): ... + def start_b(self, attributes) -> None: ... + def end_b(self) -> None: ... + def start_strong(self, attributes) -> None: ... + def end_strong(self) -> None: ... + def start_i(self, attributes) -> None: ... + def end_i(self) -> None: ... + def start_em(self, attributes) -> None: ... + def end_em(self) -> None: ... + def start_u(self, attributes) -> None: ... + def end_u(self) -> None: ... + def start_strike(self, attributes) -> None: ... + def end_strike(self) -> None: ... + def start_link(self, attributes) -> None: ... + def end_link(self) -> None: ... + def start_a(self, attributes) -> None: ... + def end_a(self) -> None: ... + def start_img(self, attributes) -> None: ... + def end_img(self) -> None: ... + def start_super(self, attributes) -> None: ... + def end_super(self) -> None: ... + start_sup = start_super + end_sup = end_super + def start_sub(self, attributes) -> None: ... + def end_sub(self) -> None: ... + def start_nobr(self, attrs) -> None: ... + def end_nobr(self) -> None: ... + def handle_charref(self, name) -> None: ... + def syntax_error(self, lineno, message) -> None: ... + def start_greek(self, attr) -> None: ... + def end_greek(self) -> None: ... + def start_unichar(self, attr) -> None: ... + def end_unichar(self) -> None: ... + def start_font(self, attr) -> None: ... + def end_font(self) -> None: ... + def start_span(self, attr) -> None: ... + def end_span(self) -> None: ... + def start_br(self, attr) -> None: ... + def end_br(self) -> None: ... + def start_para(self, attr) -> None: ... + def end_para(self) -> None: ... + bFragList: Incomplete + def start_bullet(self, attr) -> None: ... + def end_bullet(self) -> None: ... + def start_seqdefault(self, attr) -> None: ... + def end_seqdefault(self) -> None: ... + def start_seqreset(self, attr) -> None: ... + def end_seqreset(self) -> None: ... + def start_seqchain(self, attr) -> None: ... + end_seqchain = end_seqreset + def start_seqformat(self, attr) -> None: ... + end_seqformat = end_seqreset + start_seqDefault = start_seqdefault + end_seqDefault = end_seqdefault + start_seqReset = start_seqreset + end_seqReset = end_seqreset + start_seqChain = start_seqchain + end_seqChain = end_seqchain + start_seqFormat = start_seqformat + end_seqFormat = end_seqformat + def start_seq(self, attr) -> None: ... + def end_seq(self) -> None: ... + def start_ondraw(self, attr) -> None: ... + start_onDraw = start_ondraw + end_onDraw = end_seq + end_ondraw = end_seq + def start_index(self, attr) -> None: ... + end_index = end_seq + def start_unknown(self, attr) -> None: ... + end_unknown = end_seq + def getAttributes(self, attr, attrMap): ... + verbose: Incomplete + caseSensitive: Incomplete + ignoreUnknownTags: Incomplete + def __init__( + self, verbose: int = 0, caseSensitive: int = 0, ignoreUnknownTags: int = 1, crashOnError: bool = True + ) -> None: ... + def handle_data(self, data) -> None: ... + def handle_cdata(self, data) -> None: ... + def tt_parse(self, tt, style): ... + def findSpanStyle(self, style) -> None: ... + def parse(self, text, style): ... + def handle_starttag(self, tag, attrs) -> None: ... + def handle_endtag(self, tag) -> None: ... + def handle_entityref(self, name) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/tableofcontents.pyi b/stubs/reportlab/reportlab/platypus/tableofcontents.pyi new file mode 100644 index 000000000000..0ae40aa5b850 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/tableofcontents.pyi @@ -0,0 +1,110 @@ +from _typeshed import Unused +from collections.abc import Callable, Iterable, Sequence +from typing import Any, Final, Literal, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Unpack + +from reportlab.lib.styles import ParagraphStyle, PropertySet +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus.doctemplate import IndexingFlowable, _CanvasMaker +from reportlab.platypus.tables import TableStyle + +_T = TypeVar("_T") +_Entry: TypeAlias = tuple[int, str, int] | tuple[int, str, int, str | None] | Sequence[int | str | None] +_SequencerFormat: TypeAlias = Literal["I", "i", "123", "ABC", "abc"] + +@type_check_only +class _TableOfContentsKwargs(TypedDict, total=False): + rightColumnWidth: float + levelStyles: list[PropertySet] # should be ParagraphStyle + tableStyle: TableStyle + dotsMinLevel: int + formatter: Callable[[int], str] | None + +@type_check_only +class _SimpleIndexKwargs(TypedDict, total=False): + style: Iterable[PropertySet] | PropertySet | None # should be ParagraphStyle + dot: str | None + tableStyle: TableStyle | None + headers: bool + name: str | None + format: _SequencerFormat + offset: int + +__version__: Final[str] + +def unquote(txt: str) -> str: ... +def drawPageNumbers( + canvas: Canvas, + style: PropertySet, # should be ParagraphStyle + pages: Iterable[tuple[int | str, Unused]], + availWidth: float, + availHeight: float, + dot: str = " . ", + formatter: Unused | None = None, +) -> None: ... + +delta: float +epsilon: float +defaultLevelStyles: list[ParagraphStyle] +defaultTableStyle: TableStyle + +class TableOfContents(IndexingFlowable): + rightColumnWidth: float + levelStyles: list[ParagraphStyle] + tableStyle: TableStyle + dotsMinLevel: int + formatter: Callable[[int], str] | None + def __init__(self, **kwds: Unpack[_TableOfContentsKwargs]) -> None: ... + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> bool: ... + def clearEntries(self) -> None: ... + def getLevelStyle(self, n: int) -> ParagraphStyle: ... + def addEntry(self, level: int, text: str, pageNum: int, key: str | None = None) -> None: ... + def addEntries(self, listOfEntries: Iterable[_Entry]) -> None: ... + +@overload +def makeTuple(x: tuple[_T, ...]) -> tuple[_T, ...]: ... +@overload +def makeTuple(x: list[_T]) -> tuple[_T, ...]: ... +@overload +def makeTuple(x: _T) -> tuple[_T, ...]: ... + +class SimpleIndex(IndexingFlowable): + # NOTE: Will be a list after getLevelStyle is called + textStyle: ParagraphStyle | Iterable[ParagraphStyle] | list[ParagraphStyle] + tableStyle: TableStyle + dot: str | None + headers: bool + name: str + formatFunc: Callable[[int], str] + offset: float + def __init__(self, **kwargs: Unpack[_SimpleIndexKwargs]) -> None: ... + def getFormatFunc(self, formatName): ... + def setup( + self, + style: PropertySet | None = None, # should be ParagraphStyle + dot: str | None = None, + tableStyle: TableStyle | None = None, + headers: bool = True, + name: str | None = None, + format: _SequencerFormat = "123", + offset: float = 0, + ) -> None: ... + def __call__(self, canv: Canvas, kind: str | None, label: str) -> None: ... + def getCanvasMaker(self, canvasmaker: _CanvasMaker = ...) -> _CanvasMaker: ... + def isIndexing(self) -> Literal[1]: ... + def isSatisfied(self) -> bool: ... + def clearEntries(self) -> None: ... + def addEntry(self, text: str, pageNum: tuple[int, str], key: str | None = None) -> None: ... + def draw(self) -> None: ... + def getLevelStyle(self, n: int) -> ParagraphStyle: ... + +AlphabeticIndex = SimpleIndex + +def listdiff(l1: list[Any], l2: list[_T]) -> tuple[int, list[_T]]: ... + +class ReferenceText(IndexingFlowable): + textPattern: str + target: str + paraStyle: ParagraphStyle + def __init__(self, textPattern: str, targetKey: str) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/tables.pyi b/stubs/reportlab/reportlab/platypus/tables.pyi new file mode 100644 index 000000000000..2bcee72979e2 --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/tables.pyi @@ -0,0 +1,136 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from collections.abc import Collection, Iterable, Sequence +from typing import Any, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Unpack + +from reportlab.lib.colors import Color +from reportlab.lib.styles import PropertySet +from reportlab.lib.utils import _UNSET_ +from reportlab.platypus.flowables import Flowable, _HAlignment, _VAlignment + +__all__ = ("Table", "TableStyle", "CellStyle", "LongTable") + +_Color: TypeAlias = Color | list[float] | tuple[float, float, float, float] | tuple[float, float, float] | str | int +# TODO: consider creating a tagged union of all the possible commands, although +# this would restrict us to passing cmds to TableStyle.__init__ in a tuple +# since a list would not be able to be inferred correctly +# All commands are a tuple with a str opcode as the first element, followed +# by the arguments for that command. Most commands start with two positions +# indicating the cell-range affected by the command, the only exception is +# the ROUNDEDCORNERS command which applies to the whole table always. +_SpecialRow: TypeAlias = Literal["splitfirst", "splitlast", "inrowsplitstart", "inrowsplitend"] +_TableSectionCommand: TypeAlias = tuple[str, tuple[int | _SpecialRow, int], tuple[int, int], Unpack[tuple[Any, ...]]] +_CornerRadii: TypeAlias = tuple[float, float, float, float] | list[float] +_RoundedCornersTableCommand: TypeAlias = tuple[Literal["ROUNDEDCORNERS"], _CornerRadii | None] +_TableCommand: TypeAlias = _TableSectionCommand | _RoundedCornersTableCommand + +class CellStyle(PropertySet): + name: str + fontname: str + fontsize: float + leading: float + leftPadding: float + rightPadding: float + topPadding: float + bottomPadding: float + firstLineIndent: float + color: _Color + alignment: Literal["LEFT", "CENTER", "CENTRE", "RIGHT", "DECIMAL"] + background: _Color + valign: Literal["TOP", "MIDDLE", "BOTTOM"] + href: str | None + direction: str | None + shaping: Incomplete | None + destination: Incomplete | None + def __init__(self, name: str, parent: CellStyle | None = None) -> None: ... + def copy(self, result: CellStyle | None = None) -> CellStyle: ... + +class TableStyle: + # TODO: Add TypedDict for Table properties that can be set through the style + def __init__(self, cmds: Iterable[_TableCommand] | None = None, parent: TableStyle | None = None, **kw) -> None: ... + + @overload + def add(self, *cmd: Unpack[_TableSectionCommand]) -> None: ... + @overload + def add(self, *cmd: Unpack[_RoundedCornersTableCommand]) -> None: ... + + def getCommands(self) -> list[_TableCommand]: ... + +class ShadowStyle(NamedTuple): + dx: int | Incomplete = 10 # TODO: is either `int` or `float` + dy: int | Incomplete = -10 # TODO: is either `int` or `float` + color0: _Color = "grey" + color1: _Color = "white" + nshades: int = 30 + +class Table(Flowable): + ident: str | None + repeatRows: int + repeatCols: int + splitByRow: int + splitInRow: int + spaceBefore: float + spaceAfter: float + def __init__( + self, + # NOTE: Technically only list or tuple works but lack of covariance + # on list makes this too annoying + data: Sequence[list[Any] | tuple[Any, ...]], + colWidths: Sequence[float | str | None] | float | str | None = None, + rowHeights: Sequence[float | None] | float | None = None, + style: TableStyle | Iterable[_TableCommand] | None = None, + # docs say list/tuple, but the implementation allows any collection + repeatRows: int | Collection[int] = 0, + repeatCols: int | Collection[int] = 0, + splitByRow: int = 1, + splitInRow: int = 0, + emptyTableAction: Literal["error", "indicate", "ignore"] | None = None, + ident: str | None = None, + hAlign: _HAlignment | None = None, + vAlign: _VAlignment | None = None, + normalizedData: int = 0, + cellStyles: Sequence[Sequence[CellStyle]] | None = None, + rowSplitRange: tuple[int, int] | None = None, + spaceBefore: float | None = None, + spaceAfter: float | None = None, + longTableOptimize=None, + minRowHeights: Sequence[float] | None = None, + cornerRadii: _CornerRadii | _UNSET_ | None = ..., + renderCB: TableRenderCB | None = None, + shadow: ShadowStyle | None = None, + ) -> None: ... + def identity(self, maxLen: int | None = 30) -> str: ... + def normalizeData(self, data: Iterable[Iterable[Any]]) -> list[list[Any]]: ... + def minWidth(self) -> float: ... + def setStyle(self, tblstyle: TableStyle | Iterable[_TableCommand]) -> None: ... + def normCellRange(self, sc: int, ec: int, sr: int, er: int) -> tuple[int, int, int, int]: ... + def onSplit(self, T: Table, byRow: int = 1) -> None: ... + def draw(self) -> None: ... + +class LongTable(Table): ... + +class TableRenderCB: + def __call__(self, T: Table, cmd: str, *args: Any) -> None: ... + @abstractmethod + def startTable(self, T: Table) -> None: ... + @abstractmethod + def startBG(self, T: Table) -> None: ... + @abstractmethod + def endBG(self, T: Table) -> None: ... + @abstractmethod + def startRow(self, T: Table, rowNo: int) -> None: ... + @abstractmethod + def startCell( + self, T: Table, rowNo: int, colNo: int, cellval: Any, cellstyle: CellStyle, pos: tuple[int, int], size: tuple[int, int] + ) -> None: ... + @abstractmethod + def endCell(self, T: Table) -> None: ... + @abstractmethod + def endRow(self, T: Table) -> None: ... + @abstractmethod + def startLines(self, T: Table) -> None: ... + @abstractmethod + def endLines(self, T: Table) -> None: ... + @abstractmethod + def endTable(self, T: Table) -> None: ... diff --git a/stubs/reportlab/reportlab/platypus/xpreformatted.pyi b/stubs/reportlab/reportlab/platypus/xpreformatted.pyi new file mode 100644 index 000000000000..c5b5e4c81b4e --- /dev/null +++ b/stubs/reportlab/reportlab/platypus/xpreformatted.pyi @@ -0,0 +1,32 @@ +from reportlab.lib.styles import PropertySet +from reportlab.platypus.paragraph import Paragraph, ParaLines +from reportlab.platypus.paraparser import ParaFrag + +class XPreformatted(Paragraph): + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet, + bulletText: str | None = None, + frags: list[ParaFrag] | None = None, + caseSensitive: int = 1, + dedent: int = 0, + ) -> None: ... + def breakLinesCJK(self, width: float | list[float] | tuple[float, ...]) -> ParaLines | ParaFrag: ... + +class PythonPreformatted(XPreformatted): + formats: dict[str, tuple[str, str]] + def __init__( + self, + text: str, + # NOTE: This should be a ParagraphStyle + style: PropertySet, + bulletText: str | None = None, + dedent: int = 0, + frags: list[ParaFrag] | None = None, + ) -> None: ... + def escapeHtml(self, text: str) -> str: ... + def fontify(self, code: str) -> str: ... + +__all__ = ("XPreformatted", "PythonPreformatted") diff --git a/stubs/reportlab/reportlab/rl_config.pyi b/stubs/reportlab/reportlab/rl_config.pyi new file mode 100644 index 000000000000..5267a7f269a5 --- /dev/null +++ b/stubs/reportlab/reportlab/rl_config.pyi @@ -0,0 +1,77 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, Literal +from weakref import ReferenceType + +__all__ = ("_reset", "register_reset") + +def register_reset( + func: Callable[[], Callable[[], object] | None], callback: Callable[[ReferenceType[Any]], object] | None = None +) -> None: ... +def _reset() -> None: ... + +allowTableBoundsErrors: int +shapeChecking: int +defaultEncoding: str +defaultGraphicsFontName: str +pageCompression: int +useA85: int +defaultPageSize: tuple[float, float] +defaultImageCaching: int +warnOnMissingFontGlyphs: int +verbose: int +showBoundary: int +emptyTableAction: str +invariant: int +eps_preview_transparent: Incomplete +eps_preview: int +eps_ttf_embed: int +eps_ttf_embed_uid: int +overlapAttachedSpace: int +longTableOptimize: int +autoConvertEncoding: int +_FUZZ: float +wrapA85: int +fsEncodings: tuple[Literal["utf8"], Literal["cp1252"], Literal["cp430"]] +odbc_driver: str +platypus_link_underline: int +canvas_basefontname: str +allowShortTableRows: int +imageReaderFlags: int +paraFontSizeHeightOffset: int +canvas_baseColor: Incomplete +ignoreContainerActions: int +ttfAsciiReadable: int +pdfMultiLine: int +pdfComments: int +debug: int +listWrapOnFakeWidth: int +underlineWidth: str +underlineOffset: str +underlineGap: str +strikeWidth: str +strikeOffset: str +strikeGap: str +decimalSymbol: str +errorOnDuplicatePageLabelPage: int +autoGenerateMissingTTFName: int +allowTTFSubsetting: list[str] +spaceShrinkage: float +hyphenationLang: str +uriWasteReduce: int +embeddedHyphenation: int +hyphenationMinWordLength: int +reserveTTFNotdef: int +documentLang: Incomplete +encryptionStrength: int +trustedHosts: list[str] | None +trustedSchemes: list[str] +renderPMBackend: str +xmlParser: str +textPaths: str +toColorCanUse: str +defCWRF: float +unShapedFontGlob: list[str] | None +T1SearchPath: list[str] +TTFSearchPath: list[str] +CMapSearchPath: list[str] diff --git a/stubs/reportlab/reportlab/rl_settings.pyi b/stubs/reportlab/reportlab/rl_settings.pyi new file mode 100644 index 000000000000..8e36a529bb22 --- /dev/null +++ b/stubs/reportlab/reportlab/rl_settings.pyi @@ -0,0 +1,140 @@ +from _typeshed import Incomplete +from typing import Final, Literal + +__version__: Final[str] + +# NOTE: All the attributes in this module are Final +# rl_config is the place to make changes +allowTableBoundsErrors: Final[int] +shapeChecking: Final[int] +defaultEncoding: Final[str] +defaultGraphicsFontName: Final[str] +pageCompression: Final[int] +useA85: Final[int] +defaultPageSize: Final[str] +defaultImageCaching: Final[int] +warnOnMissingFontGlyphs: Final[int] +verbose: Final[int] +showBoundary: Final[int] +emptyTableAction: Final[str] +invariant: Final[int] +eps_preview_transparent: Final[Incomplete] +eps_preview: Final[int] +eps_ttf_embed: Final[int] +eps_ttf_embed_uid: Final[int] +overlapAttachedSpace: Final[int] +longTableOptimize: Final[int] +autoConvertEncoding: Final[int] +_FUZZ: Final[float] +wrapA85: Final[int] +fsEncodings: Final[tuple[Literal["utf8"], Literal["cp1252"], Literal["cp430"]]] +odbc_driver: Final[str] +platypus_link_underline: Final[int] +canvas_basefontname: Final[str] +allowShortTableRows: Final[int] +imageReaderFlags: Final[int] +paraFontSizeHeightOffset: Final[int] +canvas_baseColor: Final[Incomplete] +ignoreContainerActions: Final[int] +ttfAsciiReadable: Final[int] +pdfMultiLine: Final[int] +pdfComments: Final[int] +debug: Final[int] +listWrapOnFakeWidth: Final[int] +underlineWidth: Final[str] +underlineOffset: Final[str] +underlineGap: Final[str] +strikeWidth: Final[str] +strikeOffset: Final[str] +strikeGap: Final[str] +decimalSymbol: Final[str] +errorOnDuplicatePageLabelPage: Final[int] +autoGenerateMissingTTFName: Final[int] +allowTTFSubsetting: Final[list[str]] +spaceShrinkage: Final[float] +hyphenationLang: Final[str] +uriWasteReduce: Final[int] +embeddedHyphenation: Final[int] +hyphenationMinWordLength: Final[int] +reserveTTFNotdef: Final[int] +documentLang: Final[Incomplete] +encryptionStrength: Final[int] +trustedHosts: Final[Incomplete] +trustedSchemes: Final[list[str]] +renderPMBackend: Final[str] +xmlParser: Final[str] +textPaths: Final[str] +toColorCanUse: Final[str] +defCWRF: Final[float] +unShapedFontGlob: list[str] | None +T1SearchPath: Final[tuple[str, ...]] +TTFSearchPath: Final[tuple[str, ...]] +CMapSearchPath: Final[tuple[str, ...]] + +__all__ = ( + "allowTableBoundsErrors", + "shapeChecking", + "defaultEncoding", + "defaultGraphicsFontName", + "pageCompression", + "useA85", + "defaultPageSize", + "defaultImageCaching", + "warnOnMissingFontGlyphs", + "verbose", + "showBoundary", + "emptyTableAction", + "invariant", + "eps_preview_transparent", + "eps_preview", + "eps_ttf_embed", + "eps_ttf_embed_uid", + "overlapAttachedSpace", + "longTableOptimize", + "autoConvertEncoding", + "_FUZZ", + "wrapA85", + "fsEncodings", + "odbc_driver", + "platypus_link_underline", + "canvas_basefontname", + "allowShortTableRows", + "imageReaderFlags", + "paraFontSizeHeightOffset", + "canvas_baseColor", + "ignoreContainerActions", + "ttfAsciiReadable", + "pdfMultiLine", + "pdfComments", + "debug", + "listWrapOnFakeWidth", + "T1SearchPath", + "TTFSearchPath", + "CMapSearchPath", + "decimalSymbol", + "errorOnDuplicatePageLabelPage", + "autoGenerateMissingTTFName", + "allowTTFSubsetting", + "spaceShrinkage", + "underlineWidth", + "underlineOffset", + "underlineGap", + "strikeWidth", + "strikeOffset", + "strikeGap", + "hyphenationLang", + "uriWasteReduce", + "embeddedHyphenation", + "hyphenationMinWordLength", + "reserveTTFNotdef", + "documentLang", + "encryptionStrength", + "trustedHosts", + "trustedSchemes", + "renderPMBackend", + "xmlParser", + "textPaths", + "toColorCanUse", + "defCWRF", + "unShapedFontGlob", +) diff --git a/stubs/requests-oauthlib/METADATA.toml b/stubs/requests-oauthlib/METADATA.toml new file mode 100644 index 000000000000..5ae6f9018d46 --- /dev/null +++ b/stubs/requests-oauthlib/METADATA.toml @@ -0,0 +1,3 @@ +version = "2.0.*" +upstream-repository = "https://github.com/requests/requests-oauthlib" +dependencies = ["requests >= 2.34.0", "types-oauthlib"] diff --git a/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi b/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi new file mode 100644 index 000000000000..0a22c06d9e4f --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/__init__.pyi @@ -0,0 +1,6 @@ +from .oauth1_auth import OAuth1 as OAuth1 +from .oauth1_session import OAuth1Session as OAuth1Session +from .oauth2_auth import OAuth2 as OAuth2 +from .oauth2_session import OAuth2Session as OAuth2Session, TokenUpdated as TokenUpdated + +__version__: str diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi new file mode 100644 index 000000000000..77a5568fad7a --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/__init__.pyi @@ -0,0 +1,8 @@ +from .ebay import ebay_compliance_fix as ebay_compliance_fix +from .facebook import facebook_compliance_fix as facebook_compliance_fix +from .fitbit import fitbit_compliance_fix as fitbit_compliance_fix +from .instagram import instagram_compliance_fix as instagram_compliance_fix +from .mailchimp import mailchimp_compliance_fix as mailchimp_compliance_fix +from .plentymarkets import plentymarkets_compliance_fix as plentymarkets_compliance_fix +from .slack import slack_compliance_fix as slack_compliance_fix +from .weibo import weibo_compliance_fix as weibo_compliance_fix diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi new file mode 100644 index 000000000000..8a1384588d1b --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/douban.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def douban_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi new file mode 100644 index 000000000000..58369d712b85 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/ebay.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def ebay_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi new file mode 100644 index 000000000000..6544ed533c45 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/facebook.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def facebook_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi new file mode 100644 index 000000000000..cd311cdc277a --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/fitbit.pyi @@ -0,0 +1,3 @@ +from requests_oauthlib import OAuth2Session + +def fitbit_compliance_fix(session: OAuth2Session) -> OAuth2Session: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi new file mode 100644 index 000000000000..342505444ff8 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/instagram.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def instagram_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi new file mode 100644 index 000000000000..f27eca44579d --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/mailchimp.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def mailchimp_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi new file mode 100644 index 000000000000..38f27441ebf8 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/plentymarkets.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def plentymarkets_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi new file mode 100644 index 000000000000..f5f67b00e627 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/slack.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def slack_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi new file mode 100644 index 000000000000..dd8c3b23b861 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/compliance_fixes/weibo.pyi @@ -0,0 +1,7 @@ +from typing import TypeVar + +from requests_oauthlib import OAuth2Session + +_OAuth2SessionT = TypeVar("_OAuth2SessionT", bound=OAuth2Session) + +def weibo_compliance_fix(session: _OAuth2SessionT) -> _OAuth2SessionT: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi new file mode 100644 index 000000000000..75a2de35da1d --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth1_auth.pyi @@ -0,0 +1,35 @@ +from logging import Logger +from typing import Any + +from oauthlib.oauth1 import Client +from requests.auth import AuthBase + +CONTENT_TYPE_FORM_URLENCODED: str +CONTENT_TYPE_MULTI_PART: str +log: Logger + +class OAuth1(AuthBase): + client_class: type[Client] + client: Client + force_include_body: bool + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + decoding: str | None = "utf-8", + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + realm=None, + encoding: str = "utf-8", + nonce=None, + timestamp=None, + **kwargs: Any, # passed to client_class's __init__ + ) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi new file mode 100644 index 000000000000..fcbfdb73cfb3 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth1_session.pyi @@ -0,0 +1,67 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import TypeAlias, TypedDict, type_check_only + +import requests +from oauthlib.oauth1 import Client + +from . import OAuth1 + +# should be dict[str, str] but could look different +_ParsedToken: TypeAlias = dict[str, Incomplete] + +@type_check_only +class _TokenDict(TypedDict, total=False): + oauth_token: Incomplete # oauthlib.oauth1.Client.resource_owner_key + oauth_token_secret: Incomplete # oauthlib.oauth1.Client.resource_token_secret + oauth_verifier: Incomplete # oauthlib.oauth1.Client.oauth_verifier + +log: Logger + +def urldecode(body): ... + +class TokenRequestDenied(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + @property + def status_code(self) -> int: ... + +class TokenMissing(ValueError): + response: requests.Response + def __init__(self, message: str, response: requests.Response) -> None: ... + +class VerifierMissing(ValueError): ... + +class OAuth1Session(requests.Session): + auth: OAuth1 + def __init__( + self, + client_key, + client_secret=None, + resource_owner_key=None, + resource_owner_secret=None, + callback_uri=None, + signature_method="HMAC-SHA1", + signature_type="AUTH_HEADER", + rsa_key=None, + verifier=None, + client_class: type[Client] | None = None, + force_include_body: bool = False, + *, + encoding: str = "utf-8", + nonce=None, + timestamp=None, + ) -> None: ... + + @property + def token(self) -> _TokenDict: ... + @token.setter + def token(self, value: _TokenDict) -> None: ... + + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, request_token=None, **kwargs) -> str: ... + def fetch_request_token(self, url: str, realm=None, **request_kwargs) -> _ParsedToken: ... + def fetch_access_token(self, url: str, verifier=None, **request_kwargs) -> _ParsedToken: ... + def parse_authorization_response(self, url: str) -> _ParsedToken: ... + def rebuild_auth(self, prepared_request: requests.PreparedRequest, response: requests.Response) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi new file mode 100644 index 000000000000..9bd5a5258562 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth2_auth.pyi @@ -0,0 +1,5 @@ +from oauthlib.oauth2 import Client +from requests.auth import AuthBase + +class OAuth2(AuthBase): + def __init__(self, client_id=None, client: Client | None = None, token=None) -> None: ... diff --git a/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi b/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi new file mode 100644 index 000000000000..001b57f52b77 --- /dev/null +++ b/stubs/requests-oauthlib/requests_oauthlib/oauth2_session.pyi @@ -0,0 +1,149 @@ +from _typeshed import Incomplete +from logging import Logger +from typing import Any, Literal, Protocol, TypeAlias, TypedDict, overload, type_check_only + +import requests +from oauthlib.oauth2 import Client +from requests import _types +from requests.cookies import RequestsCookieJar + +_Token: TypeAlias = dict[str, Incomplete] # oauthlib.oauth2.Client.token + +@type_check_only +class _AccessTokenResponseHook(Protocol): + def __call__(self, response: requests.Response, /) -> requests.Response: ... + +@type_check_only +class _RefreshTokenResponseHook(Protocol): + def __call__(self, response: requests.Response, /) -> requests.Response: ... + +@type_check_only +class _ProtectedRequestHook(Protocol): + def __call__(self, url, headers, data, /) -> tuple[Incomplete, Incomplete, Incomplete]: ... + +@type_check_only +class _ComplianceHooks(TypedDict): + access_token_response: set[_AccessTokenResponseHook] + refresh_token_response: set[_RefreshTokenResponseHook] + protected_request: set[_ProtectedRequestHook] + +log: Logger + +class TokenUpdated(Warning): + token: Incomplete + def __init__(self, token) -> None: ... + +class OAuth2Session(requests.Session): + redirect_uri: Incomplete + state: Incomplete + auto_refresh_url: str | None + auto_refresh_kwargs: dict[str, Any] + token_updater: Incomplete + compliance_hook: _ComplianceHooks + def __init__( + self, + client_id=None, + client: Client | None = None, + auto_refresh_url: str | None = None, + auto_refresh_kwargs: dict[str, Any] | None = None, + scope=None, + redirect_uri=None, + token=None, + state=None, + token_updater=None, + pkce=None, + **kwargs, + ) -> None: ... + + @property + def scope(self) -> Incomplete | None: ... # oauthlib.oauth2.Client.scope + @scope.setter + def scope(self, value: Incomplete | None) -> None: ... + + def new_state(self): ... + + @property + def client_id(self) -> Incomplete | None: ... # oauthlib.oauth2.Client.client_id + @client_id.setter + def client_id(self, value: Incomplete | None) -> None: ... + @client_id.deleter + def client_id(self) -> None: ... + + @property + def token(self): ... # oauthlib.oauth2.Client.token + @token.setter + def token(self, value) -> None: ... + + @property + def access_token(self): ... # oauthlib.oauth2.Client.access_token + @access_token.setter + def access_token(self, value) -> None: ... + @access_token.deleter + def access_token(self) -> None: ... + + @property + def authorized(self) -> bool: ... + def authorization_url(self, url: str, state=None, **kwargs) -> tuple[str, str]: ... + def fetch_token( + self, + token_url: str, + code=None, + authorization_response=None, + body: str = "", + auth=None, + username=None, + password=None, + method: str = "POST", + force_querystring: bool = False, + timeout=None, + headers=None, + verify: bool | None = None, + proxies=None, + include_client_id=None, + client_secret=None, + cert=None, + **kwargs, + ) -> _Token: ... + def token_from_fragment(self, authorization_response: str) -> _Token: ... + def refresh_token( + self, + token_url: str, + refresh_token=None, + body: str = "", + auth=None, + timeout=None, + headers=None, + verify: bool | None = None, + proxies=None, + **kwargs, + ) -> _Token: ... + def request( # type: ignore[override] + self, + method: str | bytes, + url: str | bytes, + data: _types.DataType = None, + headers: _types.HeadersType = None, + withhold_token: bool = False, + client_id=None, + client_secret=None, + files: _types.FilesType = None, + *, + params: _types.ParamsType = None, + cookies: None | RequestsCookieJar | dict[str, str] = None, + auth: _types.AuthType = None, + timeout: _types.TimeoutType = None, + allow_redirects: bool = True, + proxies: dict[str, str] | None = None, + hooks: _types.HooksInputType | None = None, + stream: bool | None = None, + verify: _types.VerifyType | None = None, + cert: _types.CertType = None, + json=None, + ) -> requests.Response: ... + + @overload + def register_compliance_hook(self, hook_type: Literal["access_token_response"], hook: _AccessTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["refresh_token_response"], hook: _RefreshTokenResponseHook) -> None: ... + @overload + def register_compliance_hook(self, hook_type: Literal["protected_request"], hook: _ProtectedRequestHook) -> None: ... diff --git a/stubs/requests/@tests/stubtest_allowlist.txt b/stubs/requests/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..9f24211ef4d4 --- /dev/null +++ b/stubs/requests/@tests/stubtest_allowlist.txt @@ -0,0 +1,7 @@ +# Loop variables that leak into the global scope +requests.packages.mod +requests.packages.package +requests.packages.target + +# Should allow setting any attribute: +requests.structures.LookupDict.__setattr__ diff --git a/stubs/requests/@tests/test_cases/check_post.py b/stubs/requests/@tests/test_cases/check_post.py new file mode 100644 index 000000000000..d68a484d9c8e --- /dev/null +++ b/stubs/requests/@tests/test_cases/check_post.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from collections.abc import Iterable + +import requests + +# ================================================================================================= +# Regression test for #7988 (multiple files should be allowed for the "files" argument) +# This snippet comes from the requests documentation +# (https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files), +# so should pass a type checker without error +# ================================================================================================= + + +url = "https://httpbin.org/post" +multiple_files = [ + ("images", ("foo.png", open("foo.png", "rb"), "image/png")), + ("images", ("bar.png", open("bar.png", "rb"), "image/png")), +] +r = requests.post(url, files=multiple_files) + + +# ================================================================================= +# Tests for various different types being passed into the "data" parameter +# (These all return "Any", so there's not much value in using assert_type here.) +# (Just test that type checkers don't emit an error if it doesn't fail at runtime.) +# ================================================================================= + + +# Arbitrary iterable +def gen() -> Iterable[bytes]: + yield b"foo" + yield b"bar" + + +requests.post("http://httpbin.org/anything", data=gen()).json()["data"] + +# bytes +requests.post("http://httpbin.org/anything", data=b"foobar").json()["data"] + +# str +requests.post("http://httpbin.org/anything", data="foobar").json()["data"] + +# Files +requests.post("http://httpbin.org/anything", data=open("/tmp/foobar", "rb", encoding="UTF-8")).json()["data"] +requests.post("http://httpbin.org/anything", data=open("/tmp/foobar", "r", encoding="UTF-8")).json()["data"] + +# Mappings +requests.post("http://httpbin.org/anything", data={b"foo": b"bar"}).json()["form"] +requests.post("http://httpbin.org/anything", data={"foo": "bar"}).json()["form"] + +# mappings represented by an list/tuple of key-values pairs +requests.post("http://httpbin.org/anything", data=[(b"foo", b"bar")]).json()["form"] +requests.post("http://httpbin.org/anything", data=[("foo", "bar")]).json()["form"] +requests.post("http://httpbin.org/anything", data=((b"foo", b"bar"),)).json()["form"] +requests.post("http://httpbin.org/anything", data=(("foo", "bar"),)).json()["form"] diff --git a/stubs/requests/METADATA.toml b/stubs/requests/METADATA.toml new file mode 100644 index 000000000000..8f263ce769c9 --- /dev/null +++ b/stubs/requests/METADATA.toml @@ -0,0 +1,14 @@ +# requires a version of urllib3 with a py.typed file +version = "~=2.33.0" +upstream-repository = "https://github.com/psf/requests" +dependencies = ["urllib3>=2"] +extra-description = """\ + Note: `types-requests` has required `urllib3>=2` since v2.31.0.7. \ + If you need to install `types-requests` into an environment \ + that must also have `urllib3<2` installed into it, \ + you will have to use `types-requests<2.31.0.7`.\ + """ +obsolete-since = { version = "2.34.0", date = "2026-05-11" } + +[tool.stubtest] +extras = ["socks"] diff --git a/stubs/requests/requests/__init__.pyi b/stubs/requests/requests/__init__.pyi new file mode 100644 index 000000000000..199c59e9eea6 --- /dev/null +++ b/stubs/requests/requests/__init__.pyi @@ -0,0 +1,39 @@ +from . import __version__ as version_mod, packages as packages, utils as utils +from .api import ( + delete as delete, + get as get, + head as head, + options as options, + patch as patch, + post as post, + put as put, + request as request, +) +from .exceptions import ( + ConnectionError as ConnectionError, + ConnectTimeout as ConnectTimeout, + FileModeWarning as FileModeWarning, + HTTPError as HTTPError, + JSONDecodeError as JSONDecodeError, + ReadTimeout as ReadTimeout, + RequestException as RequestException, + Timeout as Timeout, + TooManyRedirects as TooManyRedirects, + URLRequired as URLRequired, +) +from .models import PreparedRequest as PreparedRequest, Request as Request, Response as Response +from .sessions import Session as Session, session as session +from .status_codes import codes as codes + +__author__ = version_mod.__author__ +__author_email__ = version_mod.__author_email__ +__build__ = version_mod.__build__ +__cake__ = version_mod.__cake__ +__copyright__ = version_mod.__copyright__ +__description__ = version_mod.__description__ +__license__ = version_mod.__license__ +__title__ = version_mod.__title__ +__url__ = version_mod.__url__ +__version__ = version_mod.__version__ + +def check_compatibility(urllib3_version: str, chardet_version: str | None, charset_normalizer_version: str | None) -> None: ... diff --git a/stubs/requests/requests/__version__.pyi b/stubs/requests/requests/__version__.pyi new file mode 100644 index 000000000000..05c93ebcba6e --- /dev/null +++ b/stubs/requests/requests/__version__.pyi @@ -0,0 +1,12 @@ +from typing import Final + +__title__: Final = "requests" +__description__: Final[str] +__url__: Final[str] +__version__: Final[str] +__build__: Final[int] +__author__: Final[str] +__author_email__: Final[str] +__license__: Final[str] +__copyright__: Final[str] +__cake__: Final[str] diff --git a/stubs/requests/requests/adapters.pyi b/stubs/requests/requests/adapters.pyi new file mode 100644 index 000000000000..d34484da6107 --- /dev/null +++ b/stubs/requests/requests/adapters.pyi @@ -0,0 +1,137 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from ssl import SSLContext +from typing import Any, Literal, TypedDict, type_check_only +from typing_extensions import NotRequired, deprecated + +import urllib3 +from urllib3.connectionpool import ConnectionPool +from urllib3.contrib.socks import SOCKSProxyManager as SOCKSProxyManager +from urllib3.exceptions import ( + ConnectTimeoutError as ConnectTimeoutError, + MaxRetryError as MaxRetryError, + ProtocolError as ProtocolError, + ReadTimeoutError as ReadTimeoutError, + ResponseError as ResponseError, +) +from urllib3.poolmanager import PoolManager as PoolManager, proxy_from_url as proxy_from_url +from urllib3.util.retry import Retry as Retry + +from .cookies import extract_cookies_to_jar as extract_cookies_to_jar +from .exceptions import ( + ConnectionError as ConnectionError, + ConnectTimeout as ConnectTimeout, + ProxyError as ProxyError, + ReadTimeout as ReadTimeout, + RetryError as RetryError, + SSLError as SSLError, +) +from .models import PreparedRequest, Response as Response +from .structures import CaseInsensitiveDict as CaseInsensitiveDict +from .utils import ( + DEFAULT_CA_BUNDLE_PATH as DEFAULT_CA_BUNDLE_PATH, + _Uri, + get_auth_from_url as get_auth_from_url, + get_encoding_from_headers as get_encoding_from_headers, + prepend_scheme_if_needed as prepend_scheme_if_needed, + urldefragauth as urldefragauth, +) + +# Arguments to urllib3 connection_from_host() functions (except pool_kwargs). +@type_check_only +class _HostParams(TypedDict): + host: str + scheme: str + port: int + +@type_check_only +class _PoolKwargs(TypedDict): + ssl_context: NotRequired[SSLContext] + ca_certs: NotRequired[str] + ca_cert_dir: NotRequired[str] + cert_reqs: Literal["CERT_REQUIRED", "CERT_NONE"] + cert_file: NotRequired[str] + key_file: NotRequired[str] + +DEFAULT_POOLBLOCK: bool +DEFAULT_POOLSIZE: int +DEFAULT_RETRIES: int +DEFAULT_POOL_TIMEOUT: float | None + +class BaseAdapter: + def __init__(self) -> None: ... + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: None | float | tuple[float, float] | tuple[float, None] = None, + verify: bool | str = True, + cert: None | bytes | str | tuple[bytes | str, bytes | str] = None, + proxies: Mapping[str, str] | None = None, + ) -> Response: ... + def close(self) -> None: ... + +class HTTPAdapter(BaseAdapter): + __attrs__: Incomplete + max_retries: Retry + config: Incomplete + proxy_manager: Incomplete + def __init__( + self, pool_connections: int = 10, pool_maxsize: int = 10, max_retries: Retry | int | None = 0, pool_block: bool = False + ) -> None: ... + poolmanager: Incomplete + def init_poolmanager( + self, + connections: int, + maxsize: int, + block: bool = False, + **pool_kwargs: Any, # Any: Arbitrary keyword arguments passed directly to urllib3's PoolManager constructor. + # Allowed types depend on urllib3 version, but typically include: + # ssl_version (int), cert_reqs (str), ca_certs (str), ca_cert_dir (str), + # ssl_context (ssl.SSLContext), socket_options (list), etc. + # We use Any because the exact set is dynamic and not fully specified in stubs. + ) -> None: ... + def proxy_manager_for( + self, + proxy: str, + **proxy_kwargs: Any, # Any: Same as pool_kwargs above, passed to ProxyManager or SOCKSProxyManager. + # May include: ssl_context, cert_reqs, ca_certs, ca_cert_dir, etc. + ) -> Any: # Any: Returns either urllib3.ProxyManager (for HTTP/HTTPS proxies) or SOCKSProxyManager (for SOCKS). + # The exact return type depends on the proxy scheme and is not needed by callers; using Any avoids + # circular imports or complex union types. In practice, the object adheres to a common interface. + ... + + def cert_verify(self, conn, url, verify, cert): ... + def build_response(self, req: PreparedRequest, resp: urllib3.BaseHTTPResponse) -> Response: ... + def build_connection_pool_key_attributes( + self, request: PreparedRequest, verify: bool | str, cert: str | tuple[str, str] | None = None + ) -> tuple[_HostParams, _PoolKwargs]: ... + def get_connection_with_tls_context( + self, + request: PreparedRequest, + verify: bool | str | None, + proxies: Mapping[str, str] | None = None, + cert: tuple[str, str] | str | None = None, + ) -> ConnectionPool: ... + @deprecated("Use get_connection_with_tls_context() instead.") + def get_connection(self, url: _Uri, proxies: Mapping[str, str] | None = None) -> ConnectionPool: ... + def close(self) -> None: ... + def request_url(self, request: PreparedRequest, proxies: Mapping[str, str] | None) -> str: ... + def add_headers( + self, + request: PreparedRequest, + **kwargs: Any, # Any: Hook method for subclasses to add custom headers. + # The kwargs mirror the send() parameters: stream (bool), timeout (float|tuple), + # verify (bool|str), cert (str|tuple), proxies (dict). Base implementation ignores them. + # Using Any allows subclasses to access these arguments without repeating the full signature. + ) -> None: ... + def proxy_headers(self, proxy: str) -> dict[str, str]: ... + def send( + self, + request: PreparedRequest, + stream: bool = False, + timeout: None | float | tuple[float, float] | tuple[float, None] = None, + verify: bool | str = True, + cert: None | bytes | str | tuple[bytes | str, bytes | str] = None, + proxies: Mapping[str, str] | None = None, + ) -> Response: ... diff --git a/stubs/requests/requests/api.pyi b/stubs/requests/requests/api.pyi new file mode 100644 index 000000000000..c29ff6472fc1 --- /dev/null +++ b/stubs/requests/requests/api.pyi @@ -0,0 +1,154 @@ +from collections.abc import Mapping +from http.cookiejar import CookieJar +from typing import TypeAlias + +from .models import _JSON, Response +from .sessions import _Auth, _Cert, _Data, _Files, _HooksInput, _Params, _TextMapping, _Timeout, _Verify + +_HeadersMapping: TypeAlias = Mapping[str, str | bytes | None] + +def request( + method: str | bytes, + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def get( + url: str | bytes, + params: _Params | None = None, + *, + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def options( + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def head( + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def post( + url: str | bytes, + data: _Data | None = None, + json: _JSON | None = None, + *, + params: _Params | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., +) -> Response: ... +def put( + url: str | bytes, + data: _Data | None = None, + *, + params: _Params | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def patch( + url: str | bytes, + data: _Data | None = None, + *, + params: _Params | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... +def delete( + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersMapping | None = ..., + cookies: CookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, +) -> Response: ... diff --git a/stubs/requests/requests/auth.pyi b/stubs/requests/requests/auth.pyi new file mode 100644 index 000000000000..21ef4abf5faf --- /dev/null +++ b/stubs/requests/requests/auth.pyi @@ -0,0 +1,39 @@ +from typing import Any + +from . import cookies, models, utils + +extract_cookies_to_jar = cookies.extract_cookies_to_jar +parse_dict_header = utils.parse_dict_header +to_native_string = utils.to_native_string + +CONTENT_TYPE_FORM_URLENCODED: Any +CONTENT_TYPE_MULTI_PART: Any + +def _basic_auth_str(username: bytes | str, password: bytes | str) -> str: ... + +class AuthBase: + def __call__(self, r: models.PreparedRequest) -> models.PreparedRequest: ... + +class HTTPBasicAuth(AuthBase): + username: bytes | str + password: bytes | str + def __init__(self, username: bytes | str, password: bytes | str) -> None: ... + def __call__(self, r): ... + +class HTTPProxyAuth(HTTPBasicAuth): + def __call__(self, r): ... + +class HTTPDigestAuth(AuthBase): + username: bytes | str + password: bytes | str + last_nonce: Any + nonce_count: Any + chal: Any + pos: Any + num_401_calls: Any + def __init__(self, username: bytes | str, password: bytes | str) -> None: ... + def build_digest_header(self, method, url): ... + def handle_redirect(self, r, **kwargs): ... + def handle_401(self, r, **kwargs): ... + def __call__(self, r): ... + def init_per_thread_state(self) -> None: ... diff --git a/stubs/requests/requests/certs.pyi b/stubs/requests/requests/certs.pyi new file mode 100644 index 000000000000..7c5857d69ad3 --- /dev/null +++ b/stubs/requests/requests/certs.pyi @@ -0,0 +1 @@ +# no public data diff --git a/stubs/requests/requests/compat.pyi b/stubs/requests/requests/compat.pyi new file mode 100644 index 000000000000..88b4736313fc --- /dev/null +++ b/stubs/requests/requests/compat.pyi @@ -0,0 +1,29 @@ +from builtins import bytes as bytes, str as str +from collections import OrderedDict as OrderedDict + +# If simplejson is installed, JSONDecodeError is actually imported from there. +from json import JSONDecodeError as JSONDecodeError +from typing import Literal, TypeAlias +from urllib.parse import ( + quote as quote, + quote_plus as quote_plus, + unquote as unquote, + unquote_plus as unquote_plus, + urldefrag as urldefrag, + urlencode as urlencode, + urljoin as urljoin, + urlparse as urlparse, + urlsplit as urlsplit, + urlunparse as urlunparse, +) +from urllib.request import getproxies as getproxies, parse_http_list as parse_http_list, proxy_bypass as proxy_bypass + +is_urllib3_1: bool +is_py2: Literal[False] +is_py3: Literal[True] +has_simplejson: bool + +builtin_str: TypeAlias = str # noqa: Y042 +basestring: tuple[type, ...] +numeric_types: tuple[type, ...] +integer_types: tuple[type, ...] diff --git a/stubs/requests/requests/cookies.pyi b/stubs/requests/requests/cookies.pyi new file mode 100644 index 000000000000..dc0138d896fc --- /dev/null +++ b/stubs/requests/requests/cookies.pyi @@ -0,0 +1,62 @@ +from _typeshed import SupportsKeysAndGetItem +from collections.abc import Iterator, MutableMapping +from http.cookiejar import Cookie, CookieJar, CookiePolicy +from http.cookies import Morsel +from typing import Any + +class MockRequest: + type: Any + def __init__(self, request) -> None: ... + def get_type(self): ... + def get_host(self): ... + def get_origin_req_host(self): ... + def get_full_url(self): ... + def is_unverifiable(self): ... + def has_header(self, name): ... + def get_header(self, name, default=None): ... + def add_header(self, key, val): ... + def add_unredirected_header(self, name, value): ... + def get_new_headers(self): ... + @property + def unverifiable(self): ... + @property + def origin_req_host(self): ... + @property + def host(self): ... + +class MockResponse: + def __init__(self, headers) -> None: ... + def info(self): ... + def getheaders(self, name): ... + +def extract_cookies_to_jar(jar, request, response): ... +def get_cookie_header(jar, request): ... +def remove_cookie_by_name(cookiejar, name, domain=None, path=None): ... + +class CookieConflictError(RuntimeError): ... + +class RequestsCookieJar(CookieJar, MutableMapping[str, str]): # type: ignore[misc] # conflicting __iter__ in the base classes + def get(self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None) -> str | None: ... # type: ignore[override] + def set(self, name: str, value: str | Morsel[dict[str, str]], **kwargs) -> Cookie | None: ... + def iterkeys(self) -> Iterator[str]: ... + def keys(self) -> list[str]: ... # type: ignore[override] + def itervalues(self) -> Iterator[str]: ... + def values(self) -> list[str]: ... # type: ignore[override] + def iteritems(self) -> Iterator[tuple[str, str]]: ... + def items(self) -> list[tuple[str, str]]: ... # type: ignore[override] + def list_domains(self) -> list[str]: ... + def list_paths(self) -> list[str]: ... + def multiple_domains(self) -> bool: ... + def get_dict(self, domain: str | None = None, path: str | None = None) -> dict[str, str]: ... + def __getitem__(self, name: str) -> str: ... + def __setitem__(self, name: str, value: str | Morsel[dict[str, str]]) -> None: ... + def __delitem__(self, name: str) -> None: ... + def set_cookie(self, cookie: Cookie, *args, **kwargs): ... + def update(self, other: CookieJar | SupportsKeysAndGetItem[str, str]): ... # type: ignore[override] + def copy(self) -> RequestsCookieJar: ... + def get_policy(self) -> CookiePolicy: ... + +def create_cookie(name, value, **kwargs): ... +def morsel_to_cookie(morsel): ... +def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): ... +def merge_cookies(cookiejar, cookies): ... diff --git a/stubs/requests/requests/exceptions.pyi b/stubs/requests/requests/exceptions.pyi new file mode 100644 index 000000000000..c76e78d4f52c --- /dev/null +++ b/stubs/requests/requests/exceptions.pyi @@ -0,0 +1,43 @@ +from typing import Any + +from urllib3.exceptions import HTTPError as BaseHTTPError + +from .compat import JSONDecodeError as CompatJSONDecodeError +from .models import Request, Response +from .sessions import PreparedRequest + +class RequestException(OSError): + response: Response | None + request: Request | PreparedRequest | None + def __init__( + self, *args: object, request: Request | PreparedRequest | None = ..., response: Response | None = ... + ) -> None: ... + +class InvalidJSONError(RequestException): ... +class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError): ... + +class HTTPError(RequestException): + request: Request | PreparedRequest | Any + response: Response | Any + +class ConnectionError(RequestException): ... +class ProxyError(ConnectionError): ... +class SSLError(ConnectionError): ... +class Timeout(RequestException): ... +class ConnectTimeout(ConnectionError, Timeout): ... +class ReadTimeout(Timeout): ... +class URLRequired(RequestException): ... +class TooManyRedirects(RequestException): ... +class MissingSchema(RequestException, ValueError): ... +class InvalidSchema(RequestException, ValueError): ... +class InvalidURL(RequestException, ValueError): ... +class InvalidHeader(RequestException, ValueError): ... +class InvalidProxyURL(InvalidURL): ... +class ChunkedEncodingError(RequestException): ... +class ContentDecodingError(RequestException, BaseHTTPError): ... +class StreamConsumedError(RequestException, TypeError): ... +class RetryError(RequestException): ... +class UnrewindableBodyError(RequestException): ... +class RequestsWarning(Warning): ... +class FileModeWarning(RequestsWarning, DeprecationWarning): ... +class RequestsDependencyWarning(RequestsWarning): ... diff --git a/stubs/requests/requests/help.pyi b/stubs/requests/requests/help.pyi new file mode 100644 index 000000000000..697afb1be11f --- /dev/null +++ b/stubs/requests/requests/help.pyi @@ -0,0 +1,40 @@ +from typing import TypedDict, type_check_only + +@type_check_only +class _VersionDict(TypedDict): + version: str + +@type_check_only +class _OptionalVersionDict(TypedDict): + version: str | None + +@type_check_only +class _PlatformDict(TypedDict): + system: str + release: str + +@type_check_only +class _ImplementationDict(_VersionDict): + name: str + +@type_check_only +class _PyOpenSSLDict(_OptionalVersionDict): + openssl_version: str + +@type_check_only +class _InfoDict(TypedDict): + platform: _PlatformDict + implementation: _ImplementationDict + system_ssl: _VersionDict + using_pyopenssl: bool + using_charset_normalizer: bool + pyOpenSSL: _PyOpenSSLDict + urllib3: _VersionDict + chardet: _OptionalVersionDict + charset_normalizer: _OptionalVersionDict + cryptography: _VersionDict + idna: _VersionDict + requests: _VersionDict + +def info() -> _InfoDict: ... +def main() -> None: ... diff --git a/stubs/requests/requests/hooks.pyi b/stubs/requests/requests/hooks.pyi new file mode 100644 index 000000000000..f706016ca386 --- /dev/null +++ b/stubs/requests/requests/hooks.pyi @@ -0,0 +1,6 @@ +from typing import Any + +HOOKS: Any + +def default_hooks(): ... +def dispatch_hook(key, hooks, hook_data, **kwargs): ... diff --git a/stubs/requests/requests/models.pyi b/stubs/requests/requests/models.pyi new file mode 100644 index 000000000000..0e85e09a6a8f --- /dev/null +++ b/stubs/requests/requests/models.pyi @@ -0,0 +1,169 @@ +import datetime +from _typeshed import Incomplete, MaybeNone, Unused +from collections.abc import Callable, Iterator +from json import JSONDecoder +from typing import Any, TypeAlias +from typing_extensions import Self + +from urllib3 import exceptions as urllib3_exceptions, fields, filepost, util +from urllib3.response import HTTPResponse + +from . import auth, cookies, exceptions, hooks, status_codes, utils +from .adapters import HTTPAdapter +from .cookies import RequestsCookieJar +from .structures import CaseInsensitiveDict as CaseInsensitiveDict + +_JSON: TypeAlias = Any # any object that can be serialized to JSON + +default_hooks = hooks.default_hooks +HTTPBasicAuth = auth.HTTPBasicAuth +cookiejar_from_dict = cookies.cookiejar_from_dict +get_cookie_header = cookies.get_cookie_header +RequestField = fields.RequestField +encode_multipart_formdata = filepost.encode_multipart_formdata +parse_url = util.parse_url +DecodeError = urllib3_exceptions.DecodeError +ReadTimeoutError = urllib3_exceptions.ReadTimeoutError +ProtocolError = urllib3_exceptions.ProtocolError +LocationParseError = urllib3_exceptions.LocationParseError +HTTPError = exceptions.HTTPError +MissingSchema = exceptions.MissingSchema +InvalidURL = exceptions.InvalidURL +ChunkedEncodingError = exceptions.ChunkedEncodingError +ContentDecodingError = exceptions.ContentDecodingError +ConnectionError = exceptions.ConnectionError +StreamConsumedError = exceptions.StreamConsumedError +guess_filename = utils.guess_filename +get_auth_from_url = utils.get_auth_from_url +requote_uri = utils.requote_uri +stream_decode_response_unicode = utils.stream_decode_response_unicode +to_key_val_list = utils.to_key_val_list +parse_header_links = utils.parse_header_links +iter_slices = utils.iter_slices +guess_json_utf = utils.guess_json_utf +super_len = utils.super_len +to_native_string = utils.to_native_string +codes = status_codes.codes + +REDIRECT_STATI: Incomplete +DEFAULT_REDIRECT_LIMIT: Incomplete +CONTENT_CHUNK_SIZE: Incomplete +ITER_CHUNK_SIZE: Incomplete + +class RequestEncodingMixin: + @property + def path_url(self) -> str: ... + +class RequestHooksMixin: + def register_hook(self, event, hook): ... + def deregister_hook(self, event, hook): ... + +class Request(RequestHooksMixin): + hooks: Incomplete + method: Incomplete + url: Incomplete + headers: Incomplete + files: Incomplete + data: Incomplete + json: _JSON | None + params: Incomplete + auth: Incomplete + cookies: Incomplete + def __init__( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json: _JSON | None = None, + ) -> None: ... + def prepare(self) -> PreparedRequest: ... + +class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): + method: str | None + url: str | None + headers: CaseInsensitiveDict[str] + body: bytes | str | None + hooks: Incomplete + def __init__(self) -> None: ... + def prepare( + self, + method=None, + url=None, + headers=None, + files=None, + data=None, + params=None, + auth=None, + cookies=None, + hooks=None, + json=None, + ) -> None: ... + def copy(self) -> PreparedRequest: ... + def prepare_method(self, method) -> None: ... + def prepare_url(self, url, params) -> None: ... + def prepare_headers(self, headers) -> None: ... + def prepare_body(self, data, files, json=None) -> None: ... + def prepare_content_length(self, body: bytes | str | None) -> None: ... + def prepare_auth(self, auth, url="") -> None: ... + def prepare_cookies(self, cookies) -> None: ... + def prepare_hooks(self, hooks) -> None: ... + +class Response: + __attrs__: Incomplete + _content: bytes | None # undocumented + status_code: int + headers: CaseInsensitiveDict[str] + raw: HTTPResponse | MaybeNone + url: str + encoding: str | None + history: list[Response] + reason: str + cookies: RequestsCookieJar + elapsed: datetime.timedelta + request: PreparedRequest + connection: HTTPAdapter + def __init__(self) -> None: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + @property + def next(self) -> PreparedRequest | None: ... + @property + def ok(self) -> bool: ... + @property + def is_redirect(self) -> bool: ... + @property + def is_permanent_redirect(self) -> bool: ... + @property + def apparent_encoding(self) -> str: ... + def iter_content(self, chunk_size: int | None = 1, decode_unicode: bool = False) -> Iterator[Incomplete]: ... + def iter_lines( + self, chunk_size: int | None = 512, decode_unicode: bool = False, delimiter: str | bytes | None = None + ) -> Iterator[Incomplete]: ... + @property + def content(self) -> bytes | MaybeNone: ... + @property + def text(self) -> str: ... + def json( + self, + *, + cls: type[JSONDecoder] | None = ..., + object_hook: Callable[[dict[Any, Any]], Any] | None = ..., + parse_float: Callable[[str], Any] | None = ..., + parse_int: Callable[[str], Any] | None = ..., + parse_constant: Callable[[str], Any] | None = ..., + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., + **kwds: Any, + ) -> Any: ... + @property + def links(self) -> dict[Incomplete, Incomplete]: ... + def raise_for_status(self) -> None: ... + def close(self) -> None: ... diff --git a/stubs/requests/requests/packages.pyi b/stubs/requests/requests/packages.pyi new file mode 100644 index 000000000000..22281ce4c6e3 --- /dev/null +++ b/stubs/requests/requests/packages.pyi @@ -0,0 +1,3 @@ +# requests also imports urllib3, idna, and chardet below +# requests.packages. The stubs don't reflect that and it's recommended to +# import these packages directly if needed. diff --git a/stubs/requests/requests/sessions.pyi b/stubs/requests/requests/sessions.pyi new file mode 100644 index 000000000000..fc21257ed706 --- /dev/null +++ b/stubs/requests/requests/sessions.pyi @@ -0,0 +1,314 @@ +from _typeshed import SupportsItems, SupportsRead, Unused +from collections.abc import Callable, Iterable, Mapping, MutableMapping +from typing import Any, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self + +from . import adapters, auth as _auth, compat, cookies, exceptions, hooks, models, status_codes, utils +from .models import _JSON, Response +from .structures import CaseInsensitiveDict as CaseInsensitiveDict + +_BaseAdapter: TypeAlias = adapters.BaseAdapter +OrderedDict = compat.OrderedDict +cookiejar_from_dict = cookies.cookiejar_from_dict +extract_cookies_to_jar = cookies.extract_cookies_to_jar +RequestsCookieJar = cookies.RequestsCookieJar +merge_cookies = cookies.merge_cookies +Request = models.Request +PreparedRequest = models.PreparedRequest +DEFAULT_REDIRECT_LIMIT = models.DEFAULT_REDIRECT_LIMIT +default_hooks = hooks.default_hooks +dispatch_hook = hooks.dispatch_hook +to_key_val_list = utils.to_key_val_list +default_headers = utils.default_headers +to_native_string = utils.to_native_string +TooManyRedirects = exceptions.TooManyRedirects +InvalidSchema = exceptions.InvalidSchema +ChunkedEncodingError = exceptions.ChunkedEncodingError +ContentDecodingError = exceptions.ContentDecodingError +HTTPAdapter = adapters.HTTPAdapter +requote_uri = utils.requote_uri +get_environ_proxies = utils.get_environ_proxies +get_netrc_auth = utils.get_netrc_auth +should_bypass_proxies = utils.should_bypass_proxies +get_auth_from_url = utils.get_auth_from_url +codes = status_codes.codes +REDIRECT_STATI = models.REDIRECT_STATI + +def preferred_clock() -> float: ... +def merge_setting(request_setting, session_setting, dict_class=...): ... +def merge_hooks(request_hooks, session_hooks, dict_class=...): ... + +class SessionRedirectMixin: + def resolve_redirects( + self, + resp, + req, + stream: bool = False, + timeout=None, + verify: bool = True, + cert=None, + proxies=None, + yield_requests: bool = False, + **adapter_kwargs, + ): ... + def rebuild_auth(self, prepared_request, response): ... + def rebuild_proxies(self, prepared_request, proxies): ... + def should_strip_auth(self, old_url, new_url): ... + def rebuild_method(self, prepared_request: PreparedRequest, response: Response) -> None: ... + def get_redirect_target(self, resp: Response) -> str | None: ... + +_Data: TypeAlias = ( + # used in requests.models.PreparedRequest.prepare_body + # + # case: is_stream + # see requests.adapters.HTTPAdapter.send + # will be sent directly to http.HTTPConnection.send(...) (through urllib3) + Iterable[bytes] + # case: not is_stream + # will be modified before being sent to urllib3.HTTPConnectionPool.urlopen(body=...) + # see requests.models.RequestEncodingMixin._encode_params + # see requests.models.RequestEncodingMixin._encode_files + # note that keys&values are converted from Any to str by urllib.parse.urlencode + | str + | bytes + | SupportsRead[str | bytes] + | list[tuple[Any, Any]] + | tuple[tuple[Any, Any], ...] + | Mapping[Any, Any] +) +_Auth: TypeAlias = tuple[str, str] | _auth.AuthBase | Callable[[PreparedRequest], PreparedRequest] +_Cert: TypeAlias = str | tuple[str, str] +# Files is passed to requests.utils.to_key_val_list() +_FileName: TypeAlias = str | None +_FileContent: TypeAlias = SupportsRead[str | bytes] | str | bytes +_FileContentType: TypeAlias = str +_FileCustomHeaders: TypeAlias = Mapping[str, str] +_FileSpecTuple2: TypeAlias = tuple[_FileName, _FileContent] +_FileSpecTuple3: TypeAlias = tuple[_FileName, _FileContent, _FileContentType] +_FileSpecTuple4: TypeAlias = tuple[_FileName, _FileContent, _FileContentType, _FileCustomHeaders] +_FileSpec: TypeAlias = _FileContent | _FileSpecTuple2 | _FileSpecTuple3 | _FileSpecTuple4 +_Files: TypeAlias = Mapping[str, _FileSpec] | Iterable[tuple[str, _FileSpec]] +_Hook: TypeAlias = Callable[[Response], Any] +_HooksInput: TypeAlias = Mapping[str, Iterable[_Hook] | _Hook] + +_ParamsMappingKeyType: TypeAlias = str | bytes | int | float +_ParamsMappingValueType: TypeAlias = str | bytes | int | float | Iterable[str | bytes | int | float] | None +_Params: TypeAlias = ( + SupportsItems[_ParamsMappingKeyType, _ParamsMappingValueType] + | tuple[_ParamsMappingKeyType, _ParamsMappingValueType] + | Iterable[tuple[_ParamsMappingKeyType, _ParamsMappingValueType]] + | str + | bytes +) +_TextMapping: TypeAlias = MutableMapping[str, str] +_HeadersUpdateMapping: TypeAlias = Mapping[str, str | bytes | None] +_Timeout: TypeAlias = float | tuple[float | None, float | None] +_Verify: TypeAlias = bool | str + +@type_check_only +class _Settings(TypedDict): + verify: _Verify | None + proxies: _TextMapping + stream: bool + cert: _Cert | None + +class Session(SessionRedirectMixin): + __attrs__: Any + # See https://github.com/psf/requests/issues/5020#issuecomment-989082461: + # requests sets this as a CaseInsensitiveDict, but users may set it to any MutableMapping + headers: MutableMapping[str, str | bytes] + auth: _Auth | None + proxies: _TextMapping + # Don't complain if: + # - value is assumed to be a list (which it is by default) + # - a _Hook is assigned directly, without wrapping it in a list (also works) + hooks: dict[str, list[_Hook] | Any] + params: _Params + stream: bool + verify: _Verify | None + cert: _Cert | None + max_redirects: int + trust_env: bool + cookies: RequestsCookieJar + adapters: MutableMapping[str, _BaseAdapter] + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: Unused) -> None: ... + def prepare_request(self, request: Request) -> PreparedRequest: ... + def request( + self, + method: str | bytes, + url: str | bytes, + params: _Params | None = None, + data: _Data | None = None, + headers: _HeadersUpdateMapping | None = None, + cookies: None | RequestsCookieJar | _TextMapping = None, + files: _Files | None = None, + auth: _Auth | None = None, + timeout: _Timeout | None = None, + allow_redirects: bool = True, + proxies: _TextMapping | None = None, + hooks: _HooksInput | None = None, + stream: bool | None = None, + verify: _Verify | None = None, + cert: _Cert | None = None, + json: _JSON | None = None, + ) -> Response: ... + def get( + self, + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def options( + self, + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def head( + self, + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def post( + self, + url: str | bytes, + data: _Data | None = None, + json: _JSON | None = None, + *, + params: _Params | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + ) -> Response: ... + def put( + self, + url: str | bytes, + data: _Data | None = None, + *, + params: _Params | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def patch( + self, + url: str | bytes, + data: _Data | None = None, + *, + params: _Params | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def delete( + self, + url: str | bytes, + *, + params: _Params | None = ..., + data: _Data | None = ..., + headers: _HeadersUpdateMapping | None = ..., + cookies: RequestsCookieJar | _TextMapping | None = ..., + files: _Files | None = ..., + auth: _Auth | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + proxies: _TextMapping | None = ..., + hooks: _HooksInput | None = ..., + stream: bool | None = ..., + verify: _Verify | None = ..., + cert: _Cert | None = ..., + json: _JSON | None = None, + ) -> Response: ... + def send( + self, + request: PreparedRequest, + *, + stream: bool | None = ..., + verify: _Verify | None = ..., + proxies: _TextMapping | None = ..., + cert: _Cert | None = ..., + timeout: _Timeout | None = ..., + allow_redirects: bool = ..., + **kwargs: Any, + ) -> Response: ... + def merge_environment_settings( + self, + url: str | bytes | None, + proxies: _TextMapping | None, + stream: bool | None, + verify: _Verify | None, + cert: _Cert | None, + ) -> _Settings: ... + def get_adapter(self, url: str) -> _BaseAdapter: ... + def close(self) -> None: ... + def mount(self, prefix: str | bytes, adapter: _BaseAdapter) -> None: ... + +def session() -> Session: ... diff --git a/stubs/requests/requests/status_codes.pyi b/stubs/requests/requests/status_codes.pyi new file mode 100644 index 000000000000..4660b4768dc5 --- /dev/null +++ b/stubs/requests/requests/status_codes.pyi @@ -0,0 +1,3 @@ +from typing import Any + +codes: Any diff --git a/stubs/requests/requests/structures.pyi b/stubs/requests/requests/structures.pyi new file mode 100644 index 000000000000..fbfffefce04b --- /dev/null +++ b/stubs/requests/requests/structures.pyi @@ -0,0 +1,26 @@ +from collections.abc import Iterable, Iterator, Mapping, MutableMapping +from typing import Any, Generic, TypeVar, overload + +_D = TypeVar("_D") +_VT = TypeVar("_VT") + +class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]): + def __init__(self, data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None, **kwargs: _VT) -> None: ... + def lower_items(self) -> Iterator[tuple[str, _VT]]: ... + def __setitem__(self, key: str, value: _VT) -> None: ... + def __getitem__(self, key: str) -> _VT: ... + def __delitem__(self, key: str) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def copy(self) -> CaseInsensitiveDict[_VT]: ... + +class LookupDict(dict[str, _VT]): + name: Any + def __init__(self, name: Any = None) -> None: ... + def __getitem__(self, key: str) -> _VT | None: ... # type: ignore[override] + def __setattr__(self, attr: str, value: _VT, /) -> None: ... + + @overload + def get(self, key: str, default: None = None) -> _VT | None: ... + @overload + def get(self, key: str, default: _D | _VT) -> _D | _VT: ... diff --git a/stubs/requests/requests/utils.pyi b/stubs/requests/requests/utils.pyi new file mode 100644 index 000000000000..ecd3536463cf --- /dev/null +++ b/stubs/requests/requests/utils.pyi @@ -0,0 +1,69 @@ +import sys +from _typeshed import Incomplete, StrOrBytesPath +from collections.abc import Generator, Iterable, Mapping +from contextlib import _GeneratorContextManager +from io import BufferedWriter +from typing import AnyStr, TypeAlias + +from . import compat, cookies, exceptions, structures +from .models import PreparedRequest, Request + +_Uri: TypeAlias = str | bytes +OrderedDict = compat.OrderedDict +cookiejar_from_dict = cookies.cookiejar_from_dict +CaseInsensitiveDict = structures.CaseInsensitiveDict +InvalidURL = exceptions.InvalidURL + +NETRC_FILES: tuple[str, str] +DEFAULT_CA_BUNDLE_PATH: Incomplete +DEFAULT_PORTS: dict[str, int] +DEFAULT_ACCEPT_ENCODING: str + +def dict_to_sequence(d): ... +def super_len(o): ... +def get_netrc_auth(url: _Uri, raise_errors: bool = False) -> tuple[str, str] | None: ... +def guess_filename(obj): ... +def extract_zipped_paths(path): ... +def atomic_open(filename: StrOrBytesPath) -> _GeneratorContextManager[BufferedWriter]: ... +def from_key_val_list(value): ... +def to_key_val_list(value): ... +def parse_list_header(value): ... +def parse_dict_header(value): ... +def unquote_header_value(value, is_filename: bool = False): ... +def dict_from_cookiejar(cj): ... +def add_dict_to_cookiejar(cj, cookie_dict): ... +def get_encodings_from_content(content): ... +def get_encoding_from_headers(headers: Mapping[str, str]) -> str | None: ... +def stream_decode_response_unicode(iterator, r): ... +def iter_slices(string: str, slice_length: int | None) -> Generator[str]: ... +def get_unicode_from_response(r): ... + +UNRESERVED_SET: frozenset[str] + +def unquote_unreserved(uri: str) -> str: ... +def requote_uri(uri: str) -> str: ... +def address_in_network(ip: str, net: str) -> bool: ... +def dotted_netmask(mask: int) -> str: ... +def is_ipv4_address(string_ip: str) -> bool: ... +def is_valid_cidr(string_network: str) -> bool: ... +def set_environ(env_name: str, value: None) -> _GeneratorContextManager[None]: ... +def should_bypass_proxies(url: _Uri, no_proxy: str | None) -> bool: ... +def get_environ_proxies(url: _Uri, no_proxy: Iterable[str] | None = None) -> dict[Incomplete, Incomplete]: ... +def select_proxy(url: _Uri, proxies: Mapping[str, str] | None) -> str | None: ... +def resolve_proxies( + request: Request | PreparedRequest, proxies: dict[str, str] | None, trust_env: bool = True +) -> dict[str, str]: ... +def default_user_agent(name: str = "python-requests") -> str: ... +def default_headers() -> CaseInsensitiveDict[str]: ... +def parse_header_links(value: str) -> list[dict[str, str]]: ... +def guess_json_utf(data): ... +def prepend_scheme_if_needed(url, new_scheme): ... +def get_auth_from_url(url: _Uri) -> tuple[str, str]: ... +def to_native_string(string, encoding="ascii"): ... +def urldefragauth(url: _Uri): ... +def rewind_body(prepared_request: PreparedRequest) -> None: ... +def check_header_validity(header: tuple[AnyStr, AnyStr]) -> None: ... + +if sys.platform == "win32": + def proxy_bypass_registry(host: str) -> bool: ... + def proxy_bypass(host: str) -> bool: ... diff --git a/stubs/resampy/@tests/stubtest_allowlist.txt b/stubs/resampy/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..c6295d94aa58 --- /dev/null +++ b/stubs/resampy/@tests/stubtest_allowlist.txt @@ -0,0 +1,2 @@ +# Part of internal API which is not needed for public type stubs: +resampy.interpn diff --git a/stubs/resampy/METADATA.toml b/stubs/resampy/METADATA.toml new file mode 100644 index 000000000000..ed770025c32d --- /dev/null +++ b/stubs/resampy/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.4.*" +upstream-repository = "https://github.com/bmcfee/resampy" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] diff --git a/stubs/resampy/resampy/__init__.pyi b/stubs/resampy/resampy/__init__.pyi new file mode 100644 index 000000000000..92d287f8a8fb --- /dev/null +++ b/stubs/resampy/resampy/__init__.pyi @@ -0,0 +1,2 @@ +from . import filters as filters +from .core import * diff --git a/stubs/resampy/resampy/core.pyi b/stubs/resampy/resampy/core.pyi new file mode 100644 index 000000000000..f4d29b1b925b --- /dev/null +++ b/stubs/resampy/resampy/core.pyi @@ -0,0 +1,35 @@ +from collections.abc import Callable +from typing import Any, TypeAlias, TypeVar + +import numpy as np + +__all__ = ["resample", "resample_nu"] + +# np.floating[Any] because precision is not important +_FloatArray = TypeVar("_FloatArray", bound=np.ndarray[tuple[int, ...], np.dtype[np.floating[Any]]]) +_FilterType: TypeAlias = str | Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] + +def resample( + x: _FloatArray, + sr_orig: float, + sr_new: float, + axis: int = -1, + filter: _FilterType = "kaiser_best", + parallel: bool = False, + *, + num_zeros: int = 64, + precision: int = 9, + rolloff: float = 0.945, +) -> _FloatArray: ... +def resample_nu( + x: _FloatArray, + sr_orig: float, + t_out: _FloatArray, + axis: int = -1, + filter: _FilterType = "kaiser_best", + parallel: bool = False, + *, + num_zeros: int = 64, + precision: int = 9, + rolloff: float = 0.945, +) -> _FloatArray: ... diff --git a/stubs/resampy/resampy/filters.pyi b/stubs/resampy/resampy/filters.pyi new file mode 100644 index 000000000000..07e85e4e26af --- /dev/null +++ b/stubs/resampy/resampy/filters.pyi @@ -0,0 +1,26 @@ +from collections.abc import Callable +from typing import TypeAlias + +import numpy as np + +__all__ = ["get_filter", "clear_cache", "sinc_window"] + +# Dictionary to cache loaded filters +FILTER_CACHE: dict[str, tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]] + +# List of filter functions available +FILTER_FUNCTIONS: list[str] + +_FilterType: TypeAlias = str | Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] + +def sinc_window( + num_zeros: int = 64, + precision: int = 9, + window: Callable[[int], np.ndarray[tuple[int], np.dtype[np.float64]]] | None = None, + rolloff: float = 0.945, +) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def get_filter( + name_or_function: _FilterType, *, num_zeros: int = 64, precision: int = 9, rolloff: float = 0.945 +) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def load_filter(filter_name: str) -> tuple[np.ndarray[tuple[int], np.dtype[np.float64]], int, float]: ... +def clear_cache() -> None: ... diff --git a/stubs/resampy/resampy/version.pyi b/stubs/resampy/resampy/version.pyi new file mode 100644 index 000000000000..24179934d795 --- /dev/null +++ b/stubs/resampy/resampy/version.pyi @@ -0,0 +1,4 @@ +from typing import Final + +short_version: Final[str] +version: Final[str] diff --git a/stubs/retry/@tests/stubtest_allowlist.txt b/stubs/retry/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..0e4e3d2ea1ed --- /dev/null +++ b/stubs/retry/@tests/stubtest_allowlist.txt @@ -0,0 +1,3 @@ +retry.compat +retry.tests +retry.tests.test_retry diff --git a/stubs/retry/METADATA.toml b/stubs/retry/METADATA.toml new file mode 100644 index 000000000000..40237f386a7f --- /dev/null +++ b/stubs/retry/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.9.*" +upstream-repository = "https://github.com/invl/retry" diff --git a/stubs/retry/retry/__init__.pyi b/stubs/retry/retry/__init__.pyi new file mode 100644 index 000000000000..6818afd2d64a --- /dev/null +++ b/stubs/retry/retry/__init__.pyi @@ -0,0 +1,3 @@ +from .api import retry as retry + +__all__ = ["retry"] diff --git a/stubs/retry/retry/api.pyi b/stubs/retry/retry/api.pyi new file mode 100644 index 000000000000..e550c1ca2c90 --- /dev/null +++ b/stubs/retry/retry/api.pyi @@ -0,0 +1,30 @@ +from _typeshed import IdentityFunction +from collections.abc import Callable, Sequence +from logging import Logger +from typing import Any, TypeVar + +_R = TypeVar("_R") + +logging_logger: Logger + +def retry_call( + f: Callable[..., _R], + fargs: Sequence[Any] | None = None, + fkwargs: dict[str, Any] | None = None, + exceptions: type[Exception] | tuple[type[Exception], ...] = ..., + tries: int = -1, + delay: float = 0, + max_delay: float | None = None, + backoff: float = 1, + jitter: tuple[float, float] | float = 0, + logger: Logger | None = ..., +) -> _R: ... +def retry( + exceptions: type[Exception] | tuple[type[Exception], ...] = ..., + tries: int = -1, + delay: float = 0, + max_delay: float | None = None, + backoff: float = 1, + jitter: tuple[float, float] | float = 0, + logger: Logger | None = ..., +) -> IdentityFunction: ... diff --git a/stubs/rfc3339-validator/METADATA.toml b/stubs/rfc3339-validator/METADATA.toml new file mode 100644 index 000000000000..d2bb8f30a310 --- /dev/null +++ b/stubs/rfc3339-validator/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.1.*" +upstream-repository = "https://github.com/naimetti/rfc3339-validator" diff --git a/stubs/rfc3339-validator/rfc3339_validator.pyi b/stubs/rfc3339-validator/rfc3339_validator.pyi new file mode 100644 index 000000000000..71f545bf2415 --- /dev/null +++ b/stubs/rfc3339-validator/rfc3339_validator.pyi @@ -0,0 +1,10 @@ +import re +from typing import Final + +__version__: Final[str] +__author__: Final[str] +__email__: Final[str] +RFC3339_REGEX_FLAGS: Final[int] +RFC3339_REGEX: Final[re.Pattern[str]] + +def validate_rfc3339(date_string: str) -> bool: ... diff --git a/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt b/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..b2e471a072ca --- /dev/null +++ b/stubs/s2clientprotocol/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +# All modules ending with *_pb2 fail to import +# The error message is "TypeError: Descriptors cannot be created directly. +# If this call came from a _pb2.py file, your generated code is out of date and must be regenerated with protoc >= 3.19.0." +s2clientprotocol\..+_pb2 diff --git a/stubs/s2clientprotocol/METADATA.toml b/stubs/s2clientprotocol/METADATA.toml new file mode 100644 index 000000000000..04ffb1ba31f9 --- /dev/null +++ b/stubs/s2clientprotocol/METADATA.toml @@ -0,0 +1,7 @@ +# Whenever you update version here, PACKAGE_VERSION should be updated +# in scripts/sync_protobuf/s2clientprotocol.py and vice-versa. +# When updating, also re-run the script +version = "5.*" +upstream-repository = "https://github.com/Blizzard/s2client-proto" +dependencies = ["types-protobuf"] +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 27.2 on [s2client-proto 5.0.12.91115.0](https://github.com/Blizzard/s2client-proto/tree/c04df4adbe274858a4eb8417175ee32ad02fd609)." diff --git a/stubs/s2clientprotocol/s2clientprotocol/build.pyi b/stubs/s2clientprotocol/s2clientprotocol/build.pyi new file mode 100644 index 000000000000..53949f46173c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/build.pyi @@ -0,0 +1,5 @@ +from subprocess import _CMD + +def game_version() -> str: ... +def git_commit_hash() -> str: ... +def read_command_output(cmd: _CMD) -> list[str]: ... diff --git a/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi new file mode 100644 index 000000000000..cfa0bec86506 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/common_pb2.pyi @@ -0,0 +1,177 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Race: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RaceEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Race.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NoRace: _Race.ValueType # 0 + Terran: _Race.ValueType # 1 + Zerg: _Race.ValueType # 2 + Protoss: _Race.ValueType # 3 + Random: _Race.ValueType # 4 + +class Race(_Race, metaclass=_RaceEnumTypeWrapper): ... + +NoRace: Race.ValueType # 0 +Terran: Race.ValueType # 1 +Zerg: Race.ValueType # 2 +Protoss: Race.ValueType # 3 +Random: Race.ValueType # 4 +global___Race = Race + +@typing.final +class AvailableAbility(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + REQUIRES_POINT_FIELD_NUMBER: builtins.int + ability_id: builtins.int + requires_point: builtins.bool + def __init__(self, *, ability_id: builtins.int | None = ..., requires_point: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "requires_point", b"requires_point"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "requires_point", b"requires_point"] + ) -> None: ... + +global___AvailableAbility = AvailableAbility + +@typing.final +class ImageData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BITS_PER_PIXEL_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + bits_per_pixel: builtins.int + """Number of bits per pixel; 8 bits for a byte etc.""" + data: builtins.bytes + """Binary data; the size of this buffer in bytes is width * height * bits_per_pixel / 8.""" + @property + def size(self) -> global___Size2DI: + """Dimension in pixels.""" + + def __init__( + self, *, bits_per_pixel: builtins.int | None = ..., size: global___Size2DI | None = ..., data: builtins.bytes | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["bits_per_pixel", b"bits_per_pixel", "data", b"data", "size", b"size"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["bits_per_pixel", b"bits_per_pixel", "data", b"data", "size", b"size"] + ) -> None: ... + +global___ImageData = ImageData + +@typing.final +class PointI(google.protobuf.message.Message): + """Point on the screen/minimap (e.g., 0..64). + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.int + y: builtins.int + def __init__(self, *, x: builtins.int | None = ..., y: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___PointI = PointI + +@typing.final +class RectangleI(google.protobuf.message.Message): + """Screen space rectangular area.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + P0_FIELD_NUMBER: builtins.int + P1_FIELD_NUMBER: builtins.int + @property + def p0(self) -> global___PointI: ... + @property + def p1(self) -> global___PointI: ... + def __init__(self, *, p0: global___PointI | None = ..., p1: global___PointI | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> None: ... + +global___RectangleI = RectangleI + +@typing.final +class Point2D(google.protobuf.message.Message): + """Point on the game board, 0..255. + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.float + y: builtins.float + def __init__(self, *, x: builtins.float | None = ..., y: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___Point2D = Point2D + +@typing.final +class Point(google.protobuf.message.Message): + """Point on the game board, 0..255. + Note: bottom left of the screen is 0, 0. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + Z_FIELD_NUMBER: builtins.int + x: builtins.float + y: builtins.float + z: builtins.float + def __init__( + self, *, x: builtins.float | None = ..., y: builtins.float | None = ..., z: builtins.float | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y", "z", b"z"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y", "z", b"z"]) -> None: ... + +global___Point = Point + +@typing.final +class Size2DI(google.protobuf.message.Message): + """Screen dimensions.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + X_FIELD_NUMBER: builtins.int + Y_FIELD_NUMBER: builtins.int + x: builtins.int + y: builtins.int + def __init__(self, *, x: builtins.int | None = ..., y: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["x", b"x", "y", b"y"]) -> None: ... + +global___Size2DI = Size2DI diff --git a/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi new file mode 100644 index 000000000000..cd68bb65df02 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/data_pb2.pyi @@ -0,0 +1,615 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Attribute: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AttributeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Attribute.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Light: _Attribute.ValueType # 1 + Armored: _Attribute.ValueType # 2 + Biological: _Attribute.ValueType # 3 + Mechanical: _Attribute.ValueType # 4 + Robotic: _Attribute.ValueType # 5 + Psionic: _Attribute.ValueType # 6 + Massive: _Attribute.ValueType # 7 + Structure: _Attribute.ValueType # 8 + Hover: _Attribute.ValueType # 9 + Heroic: _Attribute.ValueType # 10 + Summoned: _Attribute.ValueType # 11 + +class Attribute(_Attribute, metaclass=_AttributeEnumTypeWrapper): ... + +Light: Attribute.ValueType # 1 +Armored: Attribute.ValueType # 2 +Biological: Attribute.ValueType # 3 +Mechanical: Attribute.ValueType # 4 +Robotic: Attribute.ValueType # 5 +Psionic: Attribute.ValueType # 6 +Massive: Attribute.ValueType # 7 +Structure: Attribute.ValueType # 8 +Hover: Attribute.ValueType # 9 +Heroic: Attribute.ValueType # 10 +Summoned: Attribute.ValueType # 11 +global___Attribute = Attribute + +@typing.final +class AbilityData(google.protobuf.message.Message): + """May not relevant: queueable (everything is queueable). + May not be important: AbilSetId - marine stim, marauder stim. + Stuff omitted: transient. + Stuff that may be important: cost, range, Alignment, targetfilters. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Target: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TargetEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[AbilityData._Target.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Point: AbilityData._Target.ValueType # 2 + """Requires a target position.""" + Unit: AbilityData._Target.ValueType # 3 + """Requires a unit to target. Given by position using feature layers.""" + PointOrUnit: AbilityData._Target.ValueType # 4 + """Requires either a target point or target unit.""" + PointOrNone: AbilityData._Target.ValueType # 5 + """Requires either a target point or no target. (eg. building add-ons)""" + + class Target(_Target, metaclass=_TargetEnumTypeWrapper): ... + Point: AbilityData.Target.ValueType # 2 + """Requires a target position.""" + Unit: AbilityData.Target.ValueType # 3 + """Requires a unit to target. Given by position using feature layers.""" + PointOrUnit: AbilityData.Target.ValueType # 4 + """Requires either a target point or target unit.""" + PointOrNone: AbilityData.Target.ValueType # 5 + """Requires either a target point or no target. (eg. building add-ons)""" + + ABILITY_ID_FIELD_NUMBER: builtins.int + LINK_NAME_FIELD_NUMBER: builtins.int + LINK_INDEX_FIELD_NUMBER: builtins.int + BUTTON_NAME_FIELD_NUMBER: builtins.int + FRIENDLY_NAME_FIELD_NUMBER: builtins.int + HOTKEY_FIELD_NUMBER: builtins.int + REMAPS_TO_ABILITY_ID_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + TARGET_FIELD_NUMBER: builtins.int + ALLOW_MINIMAP_FIELD_NUMBER: builtins.int + ALLOW_AUTOCAST_FIELD_NUMBER: builtins.int + IS_BUILDING_FIELD_NUMBER: builtins.int + FOOTPRINT_RADIUS_FIELD_NUMBER: builtins.int + IS_INSTANT_PLACEMENT_FIELD_NUMBER: builtins.int + CAST_RANGE_FIELD_NUMBER: builtins.int + ability_id: builtins.int + """Stable ID.""" + link_name: builtins.str + """Catalog name of the ability.""" + link_index: builtins.int + """Catalog index of the ability.""" + button_name: builtins.str + """Name used for the command card. May not always be set.""" + friendly_name: builtins.str + """A human friendly name when the button name or link name isn't descriptive.""" + hotkey: builtins.str + """Hotkey. May not always be set.""" + remaps_to_ability_id: builtins.int + """This ability id may be represented by the given more generic id.""" + available: builtins.bool + """If true, the ability may be used by this set of mods/map.""" + target: global___AbilityData.Target.ValueType + """Determines if a point is optional or required.""" + allow_minimap: builtins.bool + """Can be cast in the minimap.""" + allow_autocast: builtins.bool + """Autocast can be set.""" + is_building: builtins.bool + """Requires placement to construct a building.""" + footprint_radius: builtins.float + """Estimation of the footprint size. Need a better footprint.""" + is_instant_placement: builtins.bool + """Placement next to an existing structure, e.g., an add-on like a Tech Lab.""" + cast_range: builtins.float + """Range unit can cast ability without needing to approach target.""" + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + link_name: builtins.str | None = ..., + link_index: builtins.int | None = ..., + button_name: builtins.str | None = ..., + friendly_name: builtins.str | None = ..., + hotkey: builtins.str | None = ..., + remaps_to_ability_id: builtins.int | None = ..., + available: builtins.bool | None = ..., + target: global___AbilityData.Target.ValueType | None = ..., + allow_minimap: builtins.bool | None = ..., + allow_autocast: builtins.bool | None = ..., + is_building: builtins.bool | None = ..., + footprint_radius: builtins.float | None = ..., + is_instant_placement: builtins.bool | None = ..., + cast_range: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "allow_autocast", + b"allow_autocast", + "allow_minimap", + b"allow_minimap", + "available", + b"available", + "button_name", + b"button_name", + "cast_range", + b"cast_range", + "footprint_radius", + b"footprint_radius", + "friendly_name", + b"friendly_name", + "hotkey", + b"hotkey", + "is_building", + b"is_building", + "is_instant_placement", + b"is_instant_placement", + "link_index", + b"link_index", + "link_name", + b"link_name", + "remaps_to_ability_id", + b"remaps_to_ability_id", + "target", + b"target", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "allow_autocast", + b"allow_autocast", + "allow_minimap", + b"allow_minimap", + "available", + b"available", + "button_name", + b"button_name", + "cast_range", + b"cast_range", + "footprint_radius", + b"footprint_radius", + "friendly_name", + b"friendly_name", + "hotkey", + b"hotkey", + "is_building", + b"is_building", + "is_instant_placement", + b"is_instant_placement", + "link_index", + b"link_index", + "link_name", + b"link_name", + "remaps_to_ability_id", + b"remaps_to_ability_id", + "target", + b"target", + ], + ) -> None: ... + +global___AbilityData = AbilityData + +@typing.final +class DamageBonus(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ATTRIBUTE_FIELD_NUMBER: builtins.int + BONUS_FIELD_NUMBER: builtins.int + attribute: global___Attribute.ValueType + bonus: builtins.float + def __init__(self, *, attribute: global___Attribute.ValueType | None = ..., bonus: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["attribute", b"attribute", "bonus", b"bonus"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["attribute", b"attribute", "bonus", b"bonus"]) -> None: ... + +global___DamageBonus = DamageBonus + +@typing.final +class Weapon(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _TargetType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TargetTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Weapon._TargetType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Ground: Weapon._TargetType.ValueType # 1 + Air: Weapon._TargetType.ValueType # 2 + Any: Weapon._TargetType.ValueType # 3 + + class TargetType(_TargetType, metaclass=_TargetTypeEnumTypeWrapper): ... + Ground: Weapon.TargetType.ValueType # 1 + Air: Weapon.TargetType.ValueType # 2 + Any: Weapon.TargetType.ValueType # 3 + + TYPE_FIELD_NUMBER: builtins.int + DAMAGE_FIELD_NUMBER: builtins.int + DAMAGE_BONUS_FIELD_NUMBER: builtins.int + ATTACKS_FIELD_NUMBER: builtins.int + RANGE_FIELD_NUMBER: builtins.int + SPEED_FIELD_NUMBER: builtins.int + type: global___Weapon.TargetType.ValueType + damage: builtins.float + attacks: builtins.int + """Number of hits per attack. (eg. Colossus has 2 beams)""" + range: builtins.float + speed: builtins.float + """Time between attacks.""" + @property + def damage_bonus(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DamageBonus]: ... + def __init__( + self, + *, + type: global___Weapon.TargetType.ValueType | None = ..., + damage: builtins.float | None = ..., + damage_bonus: collections.abc.Iterable[global___DamageBonus] | None = ..., + attacks: builtins.int | None = ..., + range: builtins.float | None = ..., + speed: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "attacks", b"attacks", "damage", b"damage", "range", b"range", "speed", b"speed", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "attacks", + b"attacks", + "damage", + b"damage", + "damage_bonus", + b"damage_bonus", + "range", + b"range", + "speed", + b"speed", + "type", + b"type", + ], + ) -> None: ... + +global___Weapon = Weapon + +@typing.final +class UnitTypeData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + CARGO_SIZE_FIELD_NUMBER: builtins.int + MINERAL_COST_FIELD_NUMBER: builtins.int + VESPENE_COST_FIELD_NUMBER: builtins.int + FOOD_REQUIRED_FIELD_NUMBER: builtins.int + FOOD_PROVIDED_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + RACE_FIELD_NUMBER: builtins.int + BUILD_TIME_FIELD_NUMBER: builtins.int + HAS_VESPENE_FIELD_NUMBER: builtins.int + HAS_MINERALS_FIELD_NUMBER: builtins.int + SIGHT_RANGE_FIELD_NUMBER: builtins.int + TECH_ALIAS_FIELD_NUMBER: builtins.int + UNIT_ALIAS_FIELD_NUMBER: builtins.int + TECH_REQUIREMENT_FIELD_NUMBER: builtins.int + REQUIRE_ATTACHED_FIELD_NUMBER: builtins.int + ATTRIBUTES_FIELD_NUMBER: builtins.int + MOVEMENT_SPEED_FIELD_NUMBER: builtins.int + ARMOR_FIELD_NUMBER: builtins.int + WEAPONS_FIELD_NUMBER: builtins.int + unit_id: builtins.int + """Stable ID.""" + name: builtins.str + """Catalog name of the unit.""" + available: builtins.bool + """If true, the ability may be used by this set of mods/map.""" + cargo_size: builtins.int + """Number of cargo slots it occupies in transports.""" + mineral_cost: builtins.int + vespene_cost: builtins.int + food_required: builtins.float + food_provided: builtins.float + ability_id: builtins.int + """The ability that builds this unit.""" + race: s2clientprotocol.common_pb2.Race.ValueType + build_time: builtins.float + has_vespene: builtins.bool + has_minerals: builtins.bool + sight_range: builtins.float + """Range unit reveals vision.""" + unit_alias: builtins.int + """The morphed variant of this unit.""" + tech_requirement: builtins.int + """Structure required to build this unit. (Or any with the same tech_alias)""" + require_attached: builtins.bool + """Whether tech_requirement is an add-on.""" + movement_speed: builtins.float + armor: builtins.float + @property + def tech_alias(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Other units that satisfy the same tech requirement.""" + + @property + def attributes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___Attribute.ValueType]: + """Values include changes from upgrades""" + + @property + def weapons(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Weapon]: ... + def __init__( + self, + *, + unit_id: builtins.int | None = ..., + name: builtins.str | None = ..., + available: builtins.bool | None = ..., + cargo_size: builtins.int | None = ..., + mineral_cost: builtins.int | None = ..., + vespene_cost: builtins.int | None = ..., + food_required: builtins.float | None = ..., + food_provided: builtins.float | None = ..., + ability_id: builtins.int | None = ..., + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + build_time: builtins.float | None = ..., + has_vespene: builtins.bool | None = ..., + has_minerals: builtins.bool | None = ..., + sight_range: builtins.float | None = ..., + tech_alias: collections.abc.Iterable[builtins.int] | None = ..., + unit_alias: builtins.int | None = ..., + tech_requirement: builtins.int | None = ..., + require_attached: builtins.bool | None = ..., + attributes: collections.abc.Iterable[global___Attribute.ValueType] | None = ..., + movement_speed: builtins.float | None = ..., + armor: builtins.float | None = ..., + weapons: collections.abc.Iterable[global___Weapon] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "armor", + b"armor", + "available", + b"available", + "build_time", + b"build_time", + "cargo_size", + b"cargo_size", + "food_provided", + b"food_provided", + "food_required", + b"food_required", + "has_minerals", + b"has_minerals", + "has_vespene", + b"has_vespene", + "mineral_cost", + b"mineral_cost", + "movement_speed", + b"movement_speed", + "name", + b"name", + "race", + b"race", + "require_attached", + b"require_attached", + "sight_range", + b"sight_range", + "tech_requirement", + b"tech_requirement", + "unit_alias", + b"unit_alias", + "unit_id", + b"unit_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "armor", + b"armor", + "attributes", + b"attributes", + "available", + b"available", + "build_time", + b"build_time", + "cargo_size", + b"cargo_size", + "food_provided", + b"food_provided", + "food_required", + b"food_required", + "has_minerals", + b"has_minerals", + "has_vespene", + b"has_vespene", + "mineral_cost", + b"mineral_cost", + "movement_speed", + b"movement_speed", + "name", + b"name", + "race", + b"race", + "require_attached", + b"require_attached", + "sight_range", + b"sight_range", + "tech_alias", + b"tech_alias", + "tech_requirement", + b"tech_requirement", + "unit_alias", + b"unit_alias", + "unit_id", + b"unit_id", + "vespene_cost", + b"vespene_cost", + "weapons", + b"weapons", + ], + ) -> None: ... + +global___UnitTypeData = UnitTypeData + +@typing.final +class UpgradeData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UPGRADE_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + MINERAL_COST_FIELD_NUMBER: builtins.int + VESPENE_COST_FIELD_NUMBER: builtins.int + RESEARCH_TIME_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + upgrade_id: builtins.int + """Stable ID.""" + name: builtins.str + mineral_cost: builtins.int + vespene_cost: builtins.int + research_time: builtins.float + ability_id: builtins.int + def __init__( + self, + *, + upgrade_id: builtins.int | None = ..., + name: builtins.str | None = ..., + mineral_cost: builtins.int | None = ..., + vespene_cost: builtins.int | None = ..., + research_time: builtins.float | None = ..., + ability_id: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "mineral_cost", + b"mineral_cost", + "name", + b"name", + "research_time", + b"research_time", + "upgrade_id", + b"upgrade_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "mineral_cost", + b"mineral_cost", + "name", + b"name", + "research_time", + b"research_time", + "upgrade_id", + b"upgrade_id", + "vespene_cost", + b"vespene_cost", + ], + ) -> None: ... + +global___UpgradeData = UpgradeData + +@typing.final +class BuffData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BUFF_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + buff_id: builtins.int + """Stable ID.""" + name: builtins.str + def __init__(self, *, buff_id: builtins.int | None = ..., name: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["buff_id", b"buff_id", "name", b"name"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["buff_id", b"buff_id", "name", b"name"]) -> None: ... + +global___BuffData = BuffData + +@typing.final +class EffectData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EFFECT_ID_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + FRIENDLY_NAME_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + effect_id: builtins.int + """Stable ID.""" + name: builtins.str + friendly_name: builtins.str + radius: builtins.float + def __init__( + self, + *, + effect_id: builtins.int | None = ..., + name: builtins.str | None = ..., + friendly_name: builtins.str | None = ..., + radius: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "effect_id", b"effect_id", "friendly_name", b"friendly_name", "name", b"name", "radius", b"radius" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "effect_id", b"effect_id", "friendly_name", b"friendly_name", "name", b"name", "radius", b"radius" + ], + ) -> None: ... + +global___EffectData = EffectData diff --git a/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi new file mode 100644 index 000000000000..eba2ae972064 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/debug_pb2.pyi @@ -0,0 +1,501 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _DebugGameState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DebugGameStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DebugGameState.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + show_map: _DebugGameState.ValueType # 1 + control_enemy: _DebugGameState.ValueType # 2 + food: _DebugGameState.ValueType # 3 + free: _DebugGameState.ValueType # 4 + all_resources: _DebugGameState.ValueType # 5 + god: _DebugGameState.ValueType # 6 + minerals: _DebugGameState.ValueType # 7 + gas: _DebugGameState.ValueType # 8 + cooldown: _DebugGameState.ValueType # 9 + tech_tree: _DebugGameState.ValueType # 10 + upgrade: _DebugGameState.ValueType # 11 + fast_build: _DebugGameState.ValueType # 12 + +class DebugGameState(_DebugGameState, metaclass=_DebugGameStateEnumTypeWrapper): ... + +show_map: DebugGameState.ValueType # 1 +control_enemy: DebugGameState.ValueType # 2 +food: DebugGameState.ValueType # 3 +free: DebugGameState.ValueType # 4 +all_resources: DebugGameState.ValueType # 5 +god: DebugGameState.ValueType # 6 +minerals: DebugGameState.ValueType # 7 +gas: DebugGameState.ValueType # 8 +cooldown: DebugGameState.ValueType # 9 +tech_tree: DebugGameState.ValueType # 10 +upgrade: DebugGameState.ValueType # 11 +fast_build: DebugGameState.ValueType # 12 +global___DebugGameState = DebugGameState + +@typing.final +class DebugCommand(google.protobuf.message.Message): + """Issue various useful commands to the game engine.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DRAW_FIELD_NUMBER: builtins.int + GAME_STATE_FIELD_NUMBER: builtins.int + CREATE_UNIT_FIELD_NUMBER: builtins.int + KILL_UNIT_FIELD_NUMBER: builtins.int + TEST_PROCESS_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + END_GAME_FIELD_NUMBER: builtins.int + UNIT_VALUE_FIELD_NUMBER: builtins.int + game_state: global___DebugGameState.ValueType + @property + def draw(self) -> global___DebugDraw: ... + @property + def create_unit(self) -> global___DebugCreateUnit: ... + @property + def kill_unit(self) -> global___DebugKillUnit: ... + @property + def test_process(self) -> global___DebugTestProcess: ... + @property + def score(self) -> global___DebugSetScore: + """Useful only for single-player "curriculum" maps.""" + + @property + def end_game(self) -> global___DebugEndGame: ... + @property + def unit_value(self) -> global___DebugSetUnitValue: ... + def __init__( + self, + *, + draw: global___DebugDraw | None = ..., + game_state: global___DebugGameState.ValueType | None = ..., + create_unit: global___DebugCreateUnit | None = ..., + kill_unit: global___DebugKillUnit | None = ..., + test_process: global___DebugTestProcess | None = ..., + score: global___DebugSetScore | None = ..., + end_game: global___DebugEndGame | None = ..., + unit_value: global___DebugSetUnitValue | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "command", + b"command", + "create_unit", + b"create_unit", + "draw", + b"draw", + "end_game", + b"end_game", + "game_state", + b"game_state", + "kill_unit", + b"kill_unit", + "score", + b"score", + "test_process", + b"test_process", + "unit_value", + b"unit_value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "command", + b"command", + "create_unit", + b"create_unit", + "draw", + b"draw", + "end_game", + b"end_game", + "game_state", + b"game_state", + "kill_unit", + b"kill_unit", + "score", + b"score", + "test_process", + b"test_process", + "unit_value", + b"unit_value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["command", b"command"] + ) -> ( + typing.Literal["draw", "game_state", "create_unit", "kill_unit", "test_process", "score", "end_game", "unit_value"] | None + ): ... + +global___DebugCommand = DebugCommand + +@typing.final +class DebugDraw(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TEXT_FIELD_NUMBER: builtins.int + LINES_FIELD_NUMBER: builtins.int + BOXES_FIELD_NUMBER: builtins.int + SPHERES_FIELD_NUMBER: builtins.int + @property + def text(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugText]: ... + @property + def lines(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugLine]: ... + @property + def boxes(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugBox]: ... + @property + def spheres(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___DebugSphere]: ... + def __init__( + self, + *, + text: collections.abc.Iterable[global___DebugText] | None = ..., + lines: collections.abc.Iterable[global___DebugLine] | None = ..., + boxes: collections.abc.Iterable[global___DebugBox] | None = ..., + spheres: collections.abc.Iterable[global___DebugSphere] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["boxes", b"boxes", "lines", b"lines", "spheres", b"spheres", "text", b"text"] + ) -> None: ... + +global___DebugDraw = DebugDraw + +@typing.final +class Line(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + P0_FIELD_NUMBER: builtins.int + P1_FIELD_NUMBER: builtins.int + @property + def p0(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def p1(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, *, p0: s2clientprotocol.common_pb2.Point | None = ..., p1: s2clientprotocol.common_pb2.Point | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["p0", b"p0", "p1", b"p1"]) -> None: ... + +global___Line = Line + +@typing.final +class Color(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + R_FIELD_NUMBER: builtins.int + G_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + r: builtins.int + g: builtins.int + b: builtins.int + def __init__(self, *, r: builtins.int | None = ..., g: builtins.int | None = ..., b: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["b", b"b", "g", b"g", "r", b"r"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["b", b"b", "g", b"g", "r", b"r"]) -> None: ... + +global___Color = Color + +@typing.final +class DebugText(google.protobuf.message.Message): + """Display debug text on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + TEXT_FIELD_NUMBER: builtins.int + VIRTUAL_POS_FIELD_NUMBER: builtins.int + WORLD_POS_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + text: builtins.str + """Text to display.""" + size: builtins.int + """Pixel height of the text. Defaults to 8px.""" + @property + def color(self) -> global___Color: ... + @property + def virtual_pos(self) -> s2clientprotocol.common_pb2.Point: + """Virtualized position in 2D (the screen is 0..1, 0..1 for any resolution).""" + + @property + def world_pos(self) -> s2clientprotocol.common_pb2.Point: + """Position in the world.""" + + def __init__( + self, + *, + color: global___Color | None = ..., + text: builtins.str | None = ..., + virtual_pos: s2clientprotocol.common_pb2.Point | None = ..., + world_pos: s2clientprotocol.common_pb2.Point | None = ..., + size: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "color", b"color", "size", b"size", "text", b"text", "virtual_pos", b"virtual_pos", "world_pos", b"world_pos" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "color", b"color", "size", b"size", "text", b"text", "virtual_pos", b"virtual_pos", "world_pos", b"world_pos" + ], + ) -> None: ... + +global___DebugText = DebugText + +@typing.final +class DebugLine(google.protobuf.message.Message): + """Display debug lines on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + LINE_FIELD_NUMBER: builtins.int + @property + def color(self) -> global___Color: ... + @property + def line(self) -> global___Line: + """World space line.""" + + def __init__(self, *, color: global___Color | None = ..., line: global___Line | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "line", b"line"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "line", b"line"]) -> None: ... + +global___DebugLine = DebugLine + +@typing.final +class DebugBox(google.protobuf.message.Message): + """Display debug boxes on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + MIN_FIELD_NUMBER: builtins.int + MAX_FIELD_NUMBER: builtins.int + @property + def color(self) -> global___Color: ... + @property + def min(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def max(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + color: global___Color | None = ..., + min: s2clientprotocol.common_pb2.Point | None = ..., + max: s2clientprotocol.common_pb2.Point | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "max", b"max", "min", b"min"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "max", b"max", "min", b"min"]) -> None: ... + +global___DebugBox = DebugBox + +@typing.final +class DebugSphere(google.protobuf.message.Message): + """Display debug spheres on screen.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COLOR_FIELD_NUMBER: builtins.int + P_FIELD_NUMBER: builtins.int + R_FIELD_NUMBER: builtins.int + r: builtins.float + @property + def color(self) -> global___Color: ... + @property + def p(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + color: global___Color | None = ..., + p: s2clientprotocol.common_pb2.Point | None = ..., + r: builtins.float | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["color", b"color", "p", b"p", "r", b"r"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["color", b"color", "p", b"p", "r", b"r"]) -> None: ... + +global___DebugSphere = DebugSphere + +@typing.final +class DebugCreateUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TYPE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + QUANTITY_FIELD_NUMBER: builtins.int + unit_type: builtins.int + owner: builtins.int + quantity: builtins.int + @property + def pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + unit_type: builtins.int | None = ..., + owner: builtins.int | None = ..., + pos: s2clientprotocol.common_pb2.Point2D | None = ..., + quantity: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["owner", b"owner", "pos", b"pos", "quantity", b"quantity", "unit_type", b"unit_type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["owner", b"owner", "pos", b"pos", "quantity", b"quantity", "unit_type", b"unit_type"] + ) -> None: ... + +global___DebugCreateUnit = DebugCreateUnit + +@typing.final +class DebugKillUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TAG_FIELD_NUMBER: builtins.int + @property + def tag(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, tag: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["tag", b"tag"]) -> None: ... + +global___DebugKillUnit = DebugKillUnit + +@typing.final +class DebugTestProcess(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Test: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TestEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugTestProcess._Test.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + hang: DebugTestProcess._Test.ValueType # 1 + crash: DebugTestProcess._Test.ValueType # 2 + exit: DebugTestProcess._Test.ValueType # 3 + + class Test(_Test, metaclass=_TestEnumTypeWrapper): ... + hang: DebugTestProcess.Test.ValueType # 1 + crash: DebugTestProcess.Test.ValueType # 2 + exit: DebugTestProcess.Test.ValueType # 3 + + TEST_FIELD_NUMBER: builtins.int + DELAY_MS_FIELD_NUMBER: builtins.int + test: global___DebugTestProcess.Test.ValueType + delay_ms: builtins.int + def __init__( + self, *, test: global___DebugTestProcess.Test.ValueType | None = ..., delay_ms: builtins.int | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["delay_ms", b"delay_ms", "test", b"test"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["delay_ms", b"delay_ms", "test", b"test"]) -> None: ... + +global___DebugTestProcess = DebugTestProcess + +@typing.final +class DebugSetScore(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SCORE_FIELD_NUMBER: builtins.int + score: builtins.float + def __init__(self, *, score: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["score", b"score"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["score", b"score"]) -> None: ... + +global___DebugSetScore = DebugSetScore + +@typing.final +class DebugEndGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _EndResult: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _EndResultEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugEndGame._EndResult.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Surrender: DebugEndGame._EndResult.ValueType # 1 + """Default if nothing is set. The current player admits defeat.""" + DeclareVictory: DebugEndGame._EndResult.ValueType # 2 + + class EndResult(_EndResult, metaclass=_EndResultEnumTypeWrapper): ... + Surrender: DebugEndGame.EndResult.ValueType # 1 + """Default if nothing is set. The current player admits defeat.""" + DeclareVictory: DebugEndGame.EndResult.ValueType # 2 + + END_RESULT_FIELD_NUMBER: builtins.int + end_result: global___DebugEndGame.EndResult.ValueType + def __init__(self, *, end_result: global___DebugEndGame.EndResult.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["end_result", b"end_result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["end_result", b"end_result"]) -> None: ... + +global___DebugEndGame = DebugEndGame + +@typing.final +class DebugSetUnitValue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _UnitValue: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _UnitValueEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugSetUnitValue._UnitValue.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Energy: DebugSetUnitValue._UnitValue.ValueType # 1 + Life: DebugSetUnitValue._UnitValue.ValueType # 2 + Shields: DebugSetUnitValue._UnitValue.ValueType # 3 + + class UnitValue(_UnitValue, metaclass=_UnitValueEnumTypeWrapper): ... + Energy: DebugSetUnitValue.UnitValue.ValueType # 1 + Life: DebugSetUnitValue.UnitValue.ValueType # 2 + Shields: DebugSetUnitValue.UnitValue.ValueType # 3 + + UNIT_VALUE_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + unit_value: global___DebugSetUnitValue.UnitValue.ValueType + value: builtins.float + unit_tag: builtins.int + def __init__( + self, + *, + unit_value: global___DebugSetUnitValue.UnitValue.ValueType | None = ..., + value: builtins.float | None = ..., + unit_tag: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_value", b"unit_value", "value", b"value"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_value", b"unit_value", "value", b"value"] + ) -> None: ... + +global___DebugSetUnitValue = DebugSetUnitValue diff --git a/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi new file mode 100644 index 000000000000..5c14aaba748c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/error_pb2.pyi @@ -0,0 +1,459 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _ActionResult: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ActionResultEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ActionResult.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Success: _ActionResult.ValueType # 1 + NotSupported: _ActionResult.ValueType # 2 + Error: _ActionResult.ValueType # 3 + CantQueueThatOrder: _ActionResult.ValueType # 4 + Retry: _ActionResult.ValueType # 5 + Cooldown: _ActionResult.ValueType # 6 + QueueIsFull: _ActionResult.ValueType # 7 + RallyQueueIsFull: _ActionResult.ValueType # 8 + NotEnoughMinerals: _ActionResult.ValueType # 9 + NotEnoughVespene: _ActionResult.ValueType # 10 + NotEnoughTerrazine: _ActionResult.ValueType # 11 + NotEnoughCustom: _ActionResult.ValueType # 12 + NotEnoughFood: _ActionResult.ValueType # 13 + FoodUsageImpossible: _ActionResult.ValueType # 14 + NotEnoughLife: _ActionResult.ValueType # 15 + NotEnoughShields: _ActionResult.ValueType # 16 + NotEnoughEnergy: _ActionResult.ValueType # 17 + LifeSuppressed: _ActionResult.ValueType # 18 + ShieldsSuppressed: _ActionResult.ValueType # 19 + EnergySuppressed: _ActionResult.ValueType # 20 + NotEnoughCharges: _ActionResult.ValueType # 21 + CantAddMoreCharges: _ActionResult.ValueType # 22 + TooMuchMinerals: _ActionResult.ValueType # 23 + TooMuchVespene: _ActionResult.ValueType # 24 + TooMuchTerrazine: _ActionResult.ValueType # 25 + TooMuchCustom: _ActionResult.ValueType # 26 + TooMuchFood: _ActionResult.ValueType # 27 + TooMuchLife: _ActionResult.ValueType # 28 + TooMuchShields: _ActionResult.ValueType # 29 + TooMuchEnergy: _ActionResult.ValueType # 30 + MustTargetUnitWithLife: _ActionResult.ValueType # 31 + MustTargetUnitWithShields: _ActionResult.ValueType # 32 + MustTargetUnitWithEnergy: _ActionResult.ValueType # 33 + CantTrade: _ActionResult.ValueType # 34 + CantSpend: _ActionResult.ValueType # 35 + CantTargetThatUnit: _ActionResult.ValueType # 36 + CouldntAllocateUnit: _ActionResult.ValueType # 37 + UnitCantMove: _ActionResult.ValueType # 38 + TransportIsHoldingPosition: _ActionResult.ValueType # 39 + BuildTechRequirementsNotMet: _ActionResult.ValueType # 40 + CantFindPlacementLocation: _ActionResult.ValueType # 41 + CantBuildOnThat: _ActionResult.ValueType # 42 + CantBuildTooCloseToDropOff: _ActionResult.ValueType # 43 + CantBuildLocationInvalid: _ActionResult.ValueType # 44 + CantSeeBuildLocation: _ActionResult.ValueType # 45 + CantBuildTooCloseToCreepSource: _ActionResult.ValueType # 46 + CantBuildTooCloseToResources: _ActionResult.ValueType # 47 + CantBuildTooFarFromWater: _ActionResult.ValueType # 48 + CantBuildTooFarFromCreepSource: _ActionResult.ValueType # 49 + CantBuildTooFarFromBuildPowerSource: _ActionResult.ValueType # 50 + CantBuildOnDenseTerrain: _ActionResult.ValueType # 51 + CantTrainTooFarFromTrainPowerSource: _ActionResult.ValueType # 52 + CantLandLocationInvalid: _ActionResult.ValueType # 53 + CantSeeLandLocation: _ActionResult.ValueType # 54 + CantLandTooCloseToCreepSource: _ActionResult.ValueType # 55 + CantLandTooCloseToResources: _ActionResult.ValueType # 56 + CantLandTooFarFromWater: _ActionResult.ValueType # 57 + CantLandTooFarFromCreepSource: _ActionResult.ValueType # 58 + CantLandTooFarFromBuildPowerSource: _ActionResult.ValueType # 59 + CantLandTooFarFromTrainPowerSource: _ActionResult.ValueType # 60 + CantLandOnDenseTerrain: _ActionResult.ValueType # 61 + AddOnTooFarFromBuilding: _ActionResult.ValueType # 62 + MustBuildRefineryFirst: _ActionResult.ValueType # 63 + BuildingIsUnderConstruction: _ActionResult.ValueType # 64 + CantFindDropOff: _ActionResult.ValueType # 65 + CantLoadOtherPlayersUnits: _ActionResult.ValueType # 66 + NotEnoughRoomToLoadUnit: _ActionResult.ValueType # 67 + CantUnloadUnitsThere: _ActionResult.ValueType # 68 + CantWarpInUnitsThere: _ActionResult.ValueType # 69 + CantLoadImmobileUnits: _ActionResult.ValueType # 70 + CantRechargeImmobileUnits: _ActionResult.ValueType # 71 + CantRechargeUnderConstructionUnits: _ActionResult.ValueType # 72 + CantLoadThatUnit: _ActionResult.ValueType # 73 + NoCargoToUnload: _ActionResult.ValueType # 74 + LoadAllNoTargetsFound: _ActionResult.ValueType # 75 + NotWhileOccupied: _ActionResult.ValueType # 76 + CantAttackWithoutAmmo: _ActionResult.ValueType # 77 + CantHoldAnyMoreAmmo: _ActionResult.ValueType # 78 + TechRequirementsNotMet: _ActionResult.ValueType # 79 + MustLockdownUnitFirst: _ActionResult.ValueType # 80 + MustTargetUnit: _ActionResult.ValueType # 81 + MustTargetInventory: _ActionResult.ValueType # 82 + MustTargetVisibleUnit: _ActionResult.ValueType # 83 + MustTargetVisibleLocation: _ActionResult.ValueType # 84 + MustTargetWalkableLocation: _ActionResult.ValueType # 85 + MustTargetPawnableUnit: _ActionResult.ValueType # 86 + YouCantControlThatUnit: _ActionResult.ValueType # 87 + YouCantIssueCommandsToThatUnit: _ActionResult.ValueType # 88 + MustTargetResources: _ActionResult.ValueType # 89 + RequiresHealTarget: _ActionResult.ValueType # 90 + RequiresRepairTarget: _ActionResult.ValueType # 91 + NoItemsToDrop: _ActionResult.ValueType # 92 + CantHoldAnyMoreItems: _ActionResult.ValueType # 93 + CantHoldThat: _ActionResult.ValueType # 94 + TargetHasNoInventory: _ActionResult.ValueType # 95 + CantDropThisItem: _ActionResult.ValueType # 96 + CantMoveThisItem: _ActionResult.ValueType # 97 + CantPawnThisUnit: _ActionResult.ValueType # 98 + MustTargetCaster: _ActionResult.ValueType # 99 + CantTargetCaster: _ActionResult.ValueType # 100 + MustTargetOuter: _ActionResult.ValueType # 101 + CantTargetOuter: _ActionResult.ValueType # 102 + MustTargetYourOwnUnits: _ActionResult.ValueType # 103 + CantTargetYourOwnUnits: _ActionResult.ValueType # 104 + MustTargetFriendlyUnits: _ActionResult.ValueType # 105 + CantTargetFriendlyUnits: _ActionResult.ValueType # 106 + MustTargetNeutralUnits: _ActionResult.ValueType # 107 + CantTargetNeutralUnits: _ActionResult.ValueType # 108 + MustTargetEnemyUnits: _ActionResult.ValueType # 109 + CantTargetEnemyUnits: _ActionResult.ValueType # 110 + MustTargetAirUnits: _ActionResult.ValueType # 111 + CantTargetAirUnits: _ActionResult.ValueType # 112 + MustTargetGroundUnits: _ActionResult.ValueType # 113 + CantTargetGroundUnits: _ActionResult.ValueType # 114 + MustTargetStructures: _ActionResult.ValueType # 115 + CantTargetStructures: _ActionResult.ValueType # 116 + MustTargetLightUnits: _ActionResult.ValueType # 117 + CantTargetLightUnits: _ActionResult.ValueType # 118 + MustTargetArmoredUnits: _ActionResult.ValueType # 119 + CantTargetArmoredUnits: _ActionResult.ValueType # 120 + MustTargetBiologicalUnits: _ActionResult.ValueType # 121 + CantTargetBiologicalUnits: _ActionResult.ValueType # 122 + MustTargetHeroicUnits: _ActionResult.ValueType # 123 + CantTargetHeroicUnits: _ActionResult.ValueType # 124 + MustTargetRoboticUnits: _ActionResult.ValueType # 125 + CantTargetRoboticUnits: _ActionResult.ValueType # 126 + MustTargetMechanicalUnits: _ActionResult.ValueType # 127 + CantTargetMechanicalUnits: _ActionResult.ValueType # 128 + MustTargetPsionicUnits: _ActionResult.ValueType # 129 + CantTargetPsionicUnits: _ActionResult.ValueType # 130 + MustTargetMassiveUnits: _ActionResult.ValueType # 131 + CantTargetMassiveUnits: _ActionResult.ValueType # 132 + MustTargetMissile: _ActionResult.ValueType # 133 + CantTargetMissile: _ActionResult.ValueType # 134 + MustTargetWorkerUnits: _ActionResult.ValueType # 135 + CantTargetWorkerUnits: _ActionResult.ValueType # 136 + MustTargetEnergyCapableUnits: _ActionResult.ValueType # 137 + CantTargetEnergyCapableUnits: _ActionResult.ValueType # 138 + MustTargetShieldCapableUnits: _ActionResult.ValueType # 139 + CantTargetShieldCapableUnits: _ActionResult.ValueType # 140 + MustTargetFlyers: _ActionResult.ValueType # 141 + CantTargetFlyers: _ActionResult.ValueType # 142 + MustTargetBuriedUnits: _ActionResult.ValueType # 143 + CantTargetBuriedUnits: _ActionResult.ValueType # 144 + MustTargetCloakedUnits: _ActionResult.ValueType # 145 + CantTargetCloakedUnits: _ActionResult.ValueType # 146 + MustTargetUnitsInAStasisField: _ActionResult.ValueType # 147 + CantTargetUnitsInAStasisField: _ActionResult.ValueType # 148 + MustTargetUnderConstructionUnits: _ActionResult.ValueType # 149 + CantTargetUnderConstructionUnits: _ActionResult.ValueType # 150 + MustTargetDeadUnits: _ActionResult.ValueType # 151 + CantTargetDeadUnits: _ActionResult.ValueType # 152 + MustTargetRevivableUnits: _ActionResult.ValueType # 153 + CantTargetRevivableUnits: _ActionResult.ValueType # 154 + MustTargetHiddenUnits: _ActionResult.ValueType # 155 + CantTargetHiddenUnits: _ActionResult.ValueType # 156 + CantRechargeOtherPlayersUnits: _ActionResult.ValueType # 157 + MustTargetHallucinations: _ActionResult.ValueType # 158 + CantTargetHallucinations: _ActionResult.ValueType # 159 + MustTargetInvulnerableUnits: _ActionResult.ValueType # 160 + CantTargetInvulnerableUnits: _ActionResult.ValueType # 161 + MustTargetDetectedUnits: _ActionResult.ValueType # 162 + CantTargetDetectedUnits: _ActionResult.ValueType # 163 + CantTargetUnitWithEnergy: _ActionResult.ValueType # 164 + CantTargetUnitWithShields: _ActionResult.ValueType # 165 + MustTargetUncommandableUnits: _ActionResult.ValueType # 166 + CantTargetUncommandableUnits: _ActionResult.ValueType # 167 + MustTargetPreventDefeatUnits: _ActionResult.ValueType # 168 + CantTargetPreventDefeatUnits: _ActionResult.ValueType # 169 + MustTargetPreventRevealUnits: _ActionResult.ValueType # 170 + CantTargetPreventRevealUnits: _ActionResult.ValueType # 171 + MustTargetPassiveUnits: _ActionResult.ValueType # 172 + CantTargetPassiveUnits: _ActionResult.ValueType # 173 + MustTargetStunnedUnits: _ActionResult.ValueType # 174 + CantTargetStunnedUnits: _ActionResult.ValueType # 175 + MustTargetSummonedUnits: _ActionResult.ValueType # 176 + CantTargetSummonedUnits: _ActionResult.ValueType # 177 + MustTargetUser1: _ActionResult.ValueType # 178 + CantTargetUser1: _ActionResult.ValueType # 179 + MustTargetUnstoppableUnits: _ActionResult.ValueType # 180 + CantTargetUnstoppableUnits: _ActionResult.ValueType # 181 + MustTargetResistantUnits: _ActionResult.ValueType # 182 + CantTargetResistantUnits: _ActionResult.ValueType # 183 + MustTargetDazedUnits: _ActionResult.ValueType # 184 + CantTargetDazedUnits: _ActionResult.ValueType # 185 + CantLockdown: _ActionResult.ValueType # 186 + CantMindControl: _ActionResult.ValueType # 187 + MustTargetDestructibles: _ActionResult.ValueType # 188 + CantTargetDestructibles: _ActionResult.ValueType # 189 + MustTargetItems: _ActionResult.ValueType # 190 + CantTargetItems: _ActionResult.ValueType # 191 + NoCalldownAvailable: _ActionResult.ValueType # 192 + WaypointListFull: _ActionResult.ValueType # 193 + MustTargetRace: _ActionResult.ValueType # 194 + CantTargetRace: _ActionResult.ValueType # 195 + MustTargetSimilarUnits: _ActionResult.ValueType # 196 + CantTargetSimilarUnits: _ActionResult.ValueType # 197 + CantFindEnoughTargets: _ActionResult.ValueType # 198 + AlreadySpawningLarva: _ActionResult.ValueType # 199 + CantTargetExhaustedResources: _ActionResult.ValueType # 200 + CantUseMinimap: _ActionResult.ValueType # 201 + CantUseInfoPanel: _ActionResult.ValueType # 202 + OrderQueueIsFull: _ActionResult.ValueType # 203 + CantHarvestThatResource: _ActionResult.ValueType # 204 + HarvestersNotRequired: _ActionResult.ValueType # 205 + AlreadyTargeted: _ActionResult.ValueType # 206 + CantAttackWeaponsDisabled: _ActionResult.ValueType # 207 + CouldntReachTarget: _ActionResult.ValueType # 208 + TargetIsOutOfRange: _ActionResult.ValueType # 209 + TargetIsTooClose: _ActionResult.ValueType # 210 + TargetIsOutOfArc: _ActionResult.ValueType # 211 + CantFindTeleportLocation: _ActionResult.ValueType # 212 + InvalidItemClass: _ActionResult.ValueType # 213 + CantFindCancelOrder: _ActionResult.ValueType # 214 + +class ActionResult(_ActionResult, metaclass=_ActionResultEnumTypeWrapper): ... + +Success: ActionResult.ValueType # 1 +NotSupported: ActionResult.ValueType # 2 +Error: ActionResult.ValueType # 3 +CantQueueThatOrder: ActionResult.ValueType # 4 +Retry: ActionResult.ValueType # 5 +Cooldown: ActionResult.ValueType # 6 +QueueIsFull: ActionResult.ValueType # 7 +RallyQueueIsFull: ActionResult.ValueType # 8 +NotEnoughMinerals: ActionResult.ValueType # 9 +NotEnoughVespene: ActionResult.ValueType # 10 +NotEnoughTerrazine: ActionResult.ValueType # 11 +NotEnoughCustom: ActionResult.ValueType # 12 +NotEnoughFood: ActionResult.ValueType # 13 +FoodUsageImpossible: ActionResult.ValueType # 14 +NotEnoughLife: ActionResult.ValueType # 15 +NotEnoughShields: ActionResult.ValueType # 16 +NotEnoughEnergy: ActionResult.ValueType # 17 +LifeSuppressed: ActionResult.ValueType # 18 +ShieldsSuppressed: ActionResult.ValueType # 19 +EnergySuppressed: ActionResult.ValueType # 20 +NotEnoughCharges: ActionResult.ValueType # 21 +CantAddMoreCharges: ActionResult.ValueType # 22 +TooMuchMinerals: ActionResult.ValueType # 23 +TooMuchVespene: ActionResult.ValueType # 24 +TooMuchTerrazine: ActionResult.ValueType # 25 +TooMuchCustom: ActionResult.ValueType # 26 +TooMuchFood: ActionResult.ValueType # 27 +TooMuchLife: ActionResult.ValueType # 28 +TooMuchShields: ActionResult.ValueType # 29 +TooMuchEnergy: ActionResult.ValueType # 30 +MustTargetUnitWithLife: ActionResult.ValueType # 31 +MustTargetUnitWithShields: ActionResult.ValueType # 32 +MustTargetUnitWithEnergy: ActionResult.ValueType # 33 +CantTrade: ActionResult.ValueType # 34 +CantSpend: ActionResult.ValueType # 35 +CantTargetThatUnit: ActionResult.ValueType # 36 +CouldntAllocateUnit: ActionResult.ValueType # 37 +UnitCantMove: ActionResult.ValueType # 38 +TransportIsHoldingPosition: ActionResult.ValueType # 39 +BuildTechRequirementsNotMet: ActionResult.ValueType # 40 +CantFindPlacementLocation: ActionResult.ValueType # 41 +CantBuildOnThat: ActionResult.ValueType # 42 +CantBuildTooCloseToDropOff: ActionResult.ValueType # 43 +CantBuildLocationInvalid: ActionResult.ValueType # 44 +CantSeeBuildLocation: ActionResult.ValueType # 45 +CantBuildTooCloseToCreepSource: ActionResult.ValueType # 46 +CantBuildTooCloseToResources: ActionResult.ValueType # 47 +CantBuildTooFarFromWater: ActionResult.ValueType # 48 +CantBuildTooFarFromCreepSource: ActionResult.ValueType # 49 +CantBuildTooFarFromBuildPowerSource: ActionResult.ValueType # 50 +CantBuildOnDenseTerrain: ActionResult.ValueType # 51 +CantTrainTooFarFromTrainPowerSource: ActionResult.ValueType # 52 +CantLandLocationInvalid: ActionResult.ValueType # 53 +CantSeeLandLocation: ActionResult.ValueType # 54 +CantLandTooCloseToCreepSource: ActionResult.ValueType # 55 +CantLandTooCloseToResources: ActionResult.ValueType # 56 +CantLandTooFarFromWater: ActionResult.ValueType # 57 +CantLandTooFarFromCreepSource: ActionResult.ValueType # 58 +CantLandTooFarFromBuildPowerSource: ActionResult.ValueType # 59 +CantLandTooFarFromTrainPowerSource: ActionResult.ValueType # 60 +CantLandOnDenseTerrain: ActionResult.ValueType # 61 +AddOnTooFarFromBuilding: ActionResult.ValueType # 62 +MustBuildRefineryFirst: ActionResult.ValueType # 63 +BuildingIsUnderConstruction: ActionResult.ValueType # 64 +CantFindDropOff: ActionResult.ValueType # 65 +CantLoadOtherPlayersUnits: ActionResult.ValueType # 66 +NotEnoughRoomToLoadUnit: ActionResult.ValueType # 67 +CantUnloadUnitsThere: ActionResult.ValueType # 68 +CantWarpInUnitsThere: ActionResult.ValueType # 69 +CantLoadImmobileUnits: ActionResult.ValueType # 70 +CantRechargeImmobileUnits: ActionResult.ValueType # 71 +CantRechargeUnderConstructionUnits: ActionResult.ValueType # 72 +CantLoadThatUnit: ActionResult.ValueType # 73 +NoCargoToUnload: ActionResult.ValueType # 74 +LoadAllNoTargetsFound: ActionResult.ValueType # 75 +NotWhileOccupied: ActionResult.ValueType # 76 +CantAttackWithoutAmmo: ActionResult.ValueType # 77 +CantHoldAnyMoreAmmo: ActionResult.ValueType # 78 +TechRequirementsNotMet: ActionResult.ValueType # 79 +MustLockdownUnitFirst: ActionResult.ValueType # 80 +MustTargetUnit: ActionResult.ValueType # 81 +MustTargetInventory: ActionResult.ValueType # 82 +MustTargetVisibleUnit: ActionResult.ValueType # 83 +MustTargetVisibleLocation: ActionResult.ValueType # 84 +MustTargetWalkableLocation: ActionResult.ValueType # 85 +MustTargetPawnableUnit: ActionResult.ValueType # 86 +YouCantControlThatUnit: ActionResult.ValueType # 87 +YouCantIssueCommandsToThatUnit: ActionResult.ValueType # 88 +MustTargetResources: ActionResult.ValueType # 89 +RequiresHealTarget: ActionResult.ValueType # 90 +RequiresRepairTarget: ActionResult.ValueType # 91 +NoItemsToDrop: ActionResult.ValueType # 92 +CantHoldAnyMoreItems: ActionResult.ValueType # 93 +CantHoldThat: ActionResult.ValueType # 94 +TargetHasNoInventory: ActionResult.ValueType # 95 +CantDropThisItem: ActionResult.ValueType # 96 +CantMoveThisItem: ActionResult.ValueType # 97 +CantPawnThisUnit: ActionResult.ValueType # 98 +MustTargetCaster: ActionResult.ValueType # 99 +CantTargetCaster: ActionResult.ValueType # 100 +MustTargetOuter: ActionResult.ValueType # 101 +CantTargetOuter: ActionResult.ValueType # 102 +MustTargetYourOwnUnits: ActionResult.ValueType # 103 +CantTargetYourOwnUnits: ActionResult.ValueType # 104 +MustTargetFriendlyUnits: ActionResult.ValueType # 105 +CantTargetFriendlyUnits: ActionResult.ValueType # 106 +MustTargetNeutralUnits: ActionResult.ValueType # 107 +CantTargetNeutralUnits: ActionResult.ValueType # 108 +MustTargetEnemyUnits: ActionResult.ValueType # 109 +CantTargetEnemyUnits: ActionResult.ValueType # 110 +MustTargetAirUnits: ActionResult.ValueType # 111 +CantTargetAirUnits: ActionResult.ValueType # 112 +MustTargetGroundUnits: ActionResult.ValueType # 113 +CantTargetGroundUnits: ActionResult.ValueType # 114 +MustTargetStructures: ActionResult.ValueType # 115 +CantTargetStructures: ActionResult.ValueType # 116 +MustTargetLightUnits: ActionResult.ValueType # 117 +CantTargetLightUnits: ActionResult.ValueType # 118 +MustTargetArmoredUnits: ActionResult.ValueType # 119 +CantTargetArmoredUnits: ActionResult.ValueType # 120 +MustTargetBiologicalUnits: ActionResult.ValueType # 121 +CantTargetBiologicalUnits: ActionResult.ValueType # 122 +MustTargetHeroicUnits: ActionResult.ValueType # 123 +CantTargetHeroicUnits: ActionResult.ValueType # 124 +MustTargetRoboticUnits: ActionResult.ValueType # 125 +CantTargetRoboticUnits: ActionResult.ValueType # 126 +MustTargetMechanicalUnits: ActionResult.ValueType # 127 +CantTargetMechanicalUnits: ActionResult.ValueType # 128 +MustTargetPsionicUnits: ActionResult.ValueType # 129 +CantTargetPsionicUnits: ActionResult.ValueType # 130 +MustTargetMassiveUnits: ActionResult.ValueType # 131 +CantTargetMassiveUnits: ActionResult.ValueType # 132 +MustTargetMissile: ActionResult.ValueType # 133 +CantTargetMissile: ActionResult.ValueType # 134 +MustTargetWorkerUnits: ActionResult.ValueType # 135 +CantTargetWorkerUnits: ActionResult.ValueType # 136 +MustTargetEnergyCapableUnits: ActionResult.ValueType # 137 +CantTargetEnergyCapableUnits: ActionResult.ValueType # 138 +MustTargetShieldCapableUnits: ActionResult.ValueType # 139 +CantTargetShieldCapableUnits: ActionResult.ValueType # 140 +MustTargetFlyers: ActionResult.ValueType # 141 +CantTargetFlyers: ActionResult.ValueType # 142 +MustTargetBuriedUnits: ActionResult.ValueType # 143 +CantTargetBuriedUnits: ActionResult.ValueType # 144 +MustTargetCloakedUnits: ActionResult.ValueType # 145 +CantTargetCloakedUnits: ActionResult.ValueType # 146 +MustTargetUnitsInAStasisField: ActionResult.ValueType # 147 +CantTargetUnitsInAStasisField: ActionResult.ValueType # 148 +MustTargetUnderConstructionUnits: ActionResult.ValueType # 149 +CantTargetUnderConstructionUnits: ActionResult.ValueType # 150 +MustTargetDeadUnits: ActionResult.ValueType # 151 +CantTargetDeadUnits: ActionResult.ValueType # 152 +MustTargetRevivableUnits: ActionResult.ValueType # 153 +CantTargetRevivableUnits: ActionResult.ValueType # 154 +MustTargetHiddenUnits: ActionResult.ValueType # 155 +CantTargetHiddenUnits: ActionResult.ValueType # 156 +CantRechargeOtherPlayersUnits: ActionResult.ValueType # 157 +MustTargetHallucinations: ActionResult.ValueType # 158 +CantTargetHallucinations: ActionResult.ValueType # 159 +MustTargetInvulnerableUnits: ActionResult.ValueType # 160 +CantTargetInvulnerableUnits: ActionResult.ValueType # 161 +MustTargetDetectedUnits: ActionResult.ValueType # 162 +CantTargetDetectedUnits: ActionResult.ValueType # 163 +CantTargetUnitWithEnergy: ActionResult.ValueType # 164 +CantTargetUnitWithShields: ActionResult.ValueType # 165 +MustTargetUncommandableUnits: ActionResult.ValueType # 166 +CantTargetUncommandableUnits: ActionResult.ValueType # 167 +MustTargetPreventDefeatUnits: ActionResult.ValueType # 168 +CantTargetPreventDefeatUnits: ActionResult.ValueType # 169 +MustTargetPreventRevealUnits: ActionResult.ValueType # 170 +CantTargetPreventRevealUnits: ActionResult.ValueType # 171 +MustTargetPassiveUnits: ActionResult.ValueType # 172 +CantTargetPassiveUnits: ActionResult.ValueType # 173 +MustTargetStunnedUnits: ActionResult.ValueType # 174 +CantTargetStunnedUnits: ActionResult.ValueType # 175 +MustTargetSummonedUnits: ActionResult.ValueType # 176 +CantTargetSummonedUnits: ActionResult.ValueType # 177 +MustTargetUser1: ActionResult.ValueType # 178 +CantTargetUser1: ActionResult.ValueType # 179 +MustTargetUnstoppableUnits: ActionResult.ValueType # 180 +CantTargetUnstoppableUnits: ActionResult.ValueType # 181 +MustTargetResistantUnits: ActionResult.ValueType # 182 +CantTargetResistantUnits: ActionResult.ValueType # 183 +MustTargetDazedUnits: ActionResult.ValueType # 184 +CantTargetDazedUnits: ActionResult.ValueType # 185 +CantLockdown: ActionResult.ValueType # 186 +CantMindControl: ActionResult.ValueType # 187 +MustTargetDestructibles: ActionResult.ValueType # 188 +CantTargetDestructibles: ActionResult.ValueType # 189 +MustTargetItems: ActionResult.ValueType # 190 +CantTargetItems: ActionResult.ValueType # 191 +NoCalldownAvailable: ActionResult.ValueType # 192 +WaypointListFull: ActionResult.ValueType # 193 +MustTargetRace: ActionResult.ValueType # 194 +CantTargetRace: ActionResult.ValueType # 195 +MustTargetSimilarUnits: ActionResult.ValueType # 196 +CantTargetSimilarUnits: ActionResult.ValueType # 197 +CantFindEnoughTargets: ActionResult.ValueType # 198 +AlreadySpawningLarva: ActionResult.ValueType # 199 +CantTargetExhaustedResources: ActionResult.ValueType # 200 +CantUseMinimap: ActionResult.ValueType # 201 +CantUseInfoPanel: ActionResult.ValueType # 202 +OrderQueueIsFull: ActionResult.ValueType # 203 +CantHarvestThatResource: ActionResult.ValueType # 204 +HarvestersNotRequired: ActionResult.ValueType # 205 +AlreadyTargeted: ActionResult.ValueType # 206 +CantAttackWeaponsDisabled: ActionResult.ValueType # 207 +CouldntReachTarget: ActionResult.ValueType # 208 +TargetIsOutOfRange: ActionResult.ValueType # 209 +TargetIsTooClose: ActionResult.ValueType # 210 +TargetIsOutOfArc: ActionResult.ValueType # 211 +CantFindTeleportLocation: ActionResult.ValueType # 212 +InvalidItemClass: ActionResult.ValueType # 213 +CantFindCancelOrder: ActionResult.ValueType # 214 +global___ActionResult = ActionResult diff --git a/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi new file mode 100644 index 000000000000..2df098c7eb4a --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/query_pb2.pyi @@ -0,0 +1,228 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import s2clientprotocol.common_pb2 +import s2clientprotocol.error_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class RequestQuery(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATHING_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + PLACEMENTS_FIELD_NUMBER: builtins.int + IGNORE_RESOURCE_REQUIREMENTS_FIELD_NUMBER: builtins.int + ignore_resource_requirements: builtins.bool + """Ignores requirements like food, minerals and so on.""" + @property + def pathing(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryPathing]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryAvailableAbilities]: ... + @property + def placements( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RequestQueryBuildingPlacement]: ... + def __init__( + self, + *, + pathing: collections.abc.Iterable[global___RequestQueryPathing] | None = ..., + abilities: collections.abc.Iterable[global___RequestQueryAvailableAbilities] | None = ..., + placements: collections.abc.Iterable[global___RequestQueryBuildingPlacement] | None = ..., + ignore_resource_requirements: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["ignore_resource_requirements", b"ignore_resource_requirements"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", + b"abilities", + "ignore_resource_requirements", + b"ignore_resource_requirements", + "pathing", + b"pathing", + "placements", + b"placements", + ], + ) -> None: ... + +global___RequestQuery = RequestQuery + +@typing.final +class ResponseQuery(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PATHING_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + PLACEMENTS_FIELD_NUMBER: builtins.int + @property + def pathing(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryPathing]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryAvailableAbilities]: ... + @property + def placements( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ResponseQueryBuildingPlacement]: ... + def __init__( + self, + *, + pathing: collections.abc.Iterable[global___ResponseQueryPathing] | None = ..., + abilities: collections.abc.Iterable[global___ResponseQueryAvailableAbilities] | None = ..., + placements: collections.abc.Iterable[global___ResponseQueryBuildingPlacement] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["abilities", b"abilities", "pathing", b"pathing", "placements", b"placements"] + ) -> None: ... + +global___ResponseQuery = ResponseQuery + +@typing.final +class RequestQueryPathing(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_POS_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + END_POS_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + @property + def start_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + @property + def end_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + start_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + unit_tag: builtins.int | None = ..., + end_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["end_pos", b"end_pos", "start", b"start", "start_pos", b"start_pos", "unit_tag", b"unit_tag"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["end_pos", b"end_pos", "start", b"start", "start_pos", b"start_pos", "unit_tag", b"unit_tag"], + ) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["start", b"start"]) -> typing.Literal["start_pos", "unit_tag"] | None: ... + +global___RequestQueryPathing = RequestQueryPathing + +@typing.final +class ResponseQueryPathing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISTANCE_FIELD_NUMBER: builtins.int + distance: builtins.float + """0 if no path exists""" + def __init__(self, *, distance: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["distance", b"distance"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["distance", b"distance"]) -> None: ... + +global___ResponseQueryPathing = ResponseQueryPathing + +@typing.final +class RequestQueryAvailableAbilities(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAG_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + def __init__(self, *, unit_tag: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_tag", b"unit_tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_tag", b"unit_tag"]) -> None: ... + +global___RequestQueryAvailableAbilities = RequestQueryAvailableAbilities + +@typing.final +class ResponseQueryAvailableAbilities(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITIES_FIELD_NUMBER: builtins.int + UNIT_TAG_FIELD_NUMBER: builtins.int + UNIT_TYPE_ID_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + unit_type_id: builtins.int + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.AvailableAbility]: ... + def __init__( + self, + *, + abilities: collections.abc.Iterable[s2clientprotocol.common_pb2.AvailableAbility] | None = ..., + unit_tag: builtins.int | None = ..., + unit_type_id: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["unit_tag", b"unit_tag", "unit_type_id", b"unit_type_id"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["abilities", b"abilities", "unit_tag", b"unit_tag", "unit_type_id", b"unit_type_id"] + ) -> None: ... + +global___ResponseQueryAvailableAbilities = ResponseQueryAvailableAbilities + +@typing.final +class RequestQueryBuildingPlacement(google.protobuf.message.Message): + """--------------------------------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_POS_FIELD_NUMBER: builtins.int + PLACING_UNIT_TAG_FIELD_NUMBER: builtins.int + ability_id: builtins.int + placing_unit_tag: builtins.int + """Not required""" + @property + def target_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + placing_unit_tag: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", b"ability_id", "placing_unit_tag", b"placing_unit_tag", "target_pos", b"target_pos" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", b"ability_id", "placing_unit_tag", b"placing_unit_tag", "target_pos", b"target_pos" + ], + ) -> None: ... + +global___RequestQueryBuildingPlacement = RequestQueryBuildingPlacement + +@typing.final +class ResponseQueryBuildingPlacement(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESULT_FIELD_NUMBER: builtins.int + result: s2clientprotocol.error_pb2.ActionResult.ValueType + def __init__(self, *, result: s2clientprotocol.error_pb2.ActionResult.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["result", b"result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["result", b"result"]) -> None: ... + +global___ResponseQueryBuildingPlacement = ResponseQueryBuildingPlacement diff --git a/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi new file mode 100644 index 000000000000..a50167f1e087 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/raw_pb2.pyi @@ -0,0 +1,1024 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _DisplayType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DisplayTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DisplayType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Visible: _DisplayType.ValueType # 1 + """Fully visible""" + Snapshot: _DisplayType.ValueType # 2 + """Dimmed version of unit left behind after entering fog of war""" + Hidden: _DisplayType.ValueType # 3 + """Fully hidden""" + Placeholder: _DisplayType.ValueType # 4 + """Building that hasn't started construction.""" + +class DisplayType(_DisplayType, metaclass=_DisplayTypeEnumTypeWrapper): ... + +Visible: DisplayType.ValueType # 1 +"""Fully visible""" +Snapshot: DisplayType.ValueType # 2 +"""Dimmed version of unit left behind after entering fog of war""" +Hidden: DisplayType.ValueType # 3 +"""Fully hidden""" +Placeholder: DisplayType.ValueType # 4 +"""Building that hasn't started construction.""" +global___DisplayType = DisplayType + +class _Alliance: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AllianceEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Alliance.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Self: _Alliance.ValueType # 1 + Ally: _Alliance.ValueType # 2 + Neutral: _Alliance.ValueType # 3 + Enemy: _Alliance.ValueType # 4 + +class Alliance(_Alliance, metaclass=_AllianceEnumTypeWrapper): ... + +Self: Alliance.ValueType # 1 +Ally: Alliance.ValueType # 2 +Neutral: Alliance.ValueType # 3 +Enemy: Alliance.ValueType # 4 +global___Alliance = Alliance + +class _CloakState: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CloakStateEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CloakState.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CloakedUnknown: _CloakState.ValueType # 0 + """Under the fog, so unknown whether it's cloaked or not.""" + Cloaked: _CloakState.ValueType # 1 + CloakedDetected: _CloakState.ValueType # 2 + NotCloaked: _CloakState.ValueType # 3 + CloakedAllied: _CloakState.ValueType # 4 + +class CloakState(_CloakState, metaclass=_CloakStateEnumTypeWrapper): ... + +CloakedUnknown: CloakState.ValueType # 0 +"""Under the fog, so unknown whether it's cloaked or not.""" +Cloaked: CloakState.ValueType # 1 +CloakedDetected: CloakState.ValueType # 2 +NotCloaked: CloakState.ValueType # 3 +CloakedAllied: CloakState.ValueType # 4 +global___CloakState = CloakState + +@typing.final +class StartRaw(google.protobuf.message.Message): + """ + Start + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_SIZE_FIELD_NUMBER: builtins.int + PATHING_GRID_FIELD_NUMBER: builtins.int + TERRAIN_HEIGHT_FIELD_NUMBER: builtins.int + PLACEMENT_GRID_FIELD_NUMBER: builtins.int + PLAYABLE_AREA_FIELD_NUMBER: builtins.int + START_LOCATIONS_FIELD_NUMBER: builtins.int + @property + def map_size(self) -> s2clientprotocol.common_pb2.Size2DI: + """Width and height of the map.""" + + @property + def pathing_grid(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit bitmap of the pathing grid.""" + + @property + def terrain_height(self) -> s2clientprotocol.common_pb2.ImageData: + """1 byte bitmap of the terrain height.""" + + @property + def placement_grid(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit bitmap of the building placement grid.""" + + @property + def playable_area(self) -> s2clientprotocol.common_pb2.RectangleI: + """The playable cells.""" + + @property + def start_locations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.Point2D]: + """Possible start locations for players.""" + + def __init__( + self, + *, + map_size: s2clientprotocol.common_pb2.Size2DI | None = ..., + pathing_grid: s2clientprotocol.common_pb2.ImageData | None = ..., + terrain_height: s2clientprotocol.common_pb2.ImageData | None = ..., + placement_grid: s2clientprotocol.common_pb2.ImageData | None = ..., + playable_area: s2clientprotocol.common_pb2.RectangleI | None = ..., + start_locations: collections.abc.Iterable[s2clientprotocol.common_pb2.Point2D] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "map_size", + b"map_size", + "pathing_grid", + b"pathing_grid", + "placement_grid", + b"placement_grid", + "playable_area", + b"playable_area", + "terrain_height", + b"terrain_height", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "map_size", + b"map_size", + "pathing_grid", + b"pathing_grid", + "placement_grid", + b"placement_grid", + "playable_area", + b"playable_area", + "start_locations", + b"start_locations", + "terrain_height", + b"terrain_height", + ], + ) -> None: ... + +global___StartRaw = StartRaw + +@typing.final +class ObservationRaw(google.protobuf.message.Message): + """ + Observation + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_FIELD_NUMBER: builtins.int + UNITS_FIELD_NUMBER: builtins.int + MAP_STATE_FIELD_NUMBER: builtins.int + EVENT_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + RADAR_FIELD_NUMBER: builtins.int + @property + def player(self) -> global___PlayerRaw: ... + @property + def units(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Unit]: ... + @property + def map_state(self) -> global___MapState: + """Fog of war, creep and so on. Board stuff that changes per frame.""" + + @property + def event(self) -> global___Event: ... + @property + def effects(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Effect]: ... + @property + def radar(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RadarRing]: ... + def __init__( + self, + *, + player: global___PlayerRaw | None = ..., + units: collections.abc.Iterable[global___Unit] | None = ..., + map_state: global___MapState | None = ..., + event: global___Event | None = ..., + effects: collections.abc.Iterable[global___Effect] | None = ..., + radar: collections.abc.Iterable[global___RadarRing] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["event", b"event", "map_state", b"map_state", "player", b"player"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "effects", + b"effects", + "event", + b"event", + "map_state", + b"map_state", + "player", + b"player", + "radar", + b"radar", + "units", + b"units", + ], + ) -> None: ... + +global___ObservationRaw = ObservationRaw + +@typing.final +class RadarRing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POS_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + radius: builtins.float + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__(self, *, pos: s2clientprotocol.common_pb2.Point | None = ..., radius: builtins.float | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius"]) -> None: ... + +global___RadarRing = RadarRing + +@typing.final +class PowerSource(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POS_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + radius: builtins.float + tag: builtins.int + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + pos: s2clientprotocol.common_pb2.Point | None = ..., + radius: builtins.float | None = ..., + tag: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius", "tag", b"tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["pos", b"pos", "radius", b"radius", "tag", b"tag"]) -> None: ... + +global___PowerSource = PowerSource + +@typing.final +class PlayerRaw(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POWER_SOURCES_FIELD_NUMBER: builtins.int + CAMERA_FIELD_NUMBER: builtins.int + UPGRADE_IDS_FIELD_NUMBER: builtins.int + @property + def power_sources(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PowerSource]: ... + @property + def camera(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def upgrade_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """TODO: Add to UI observation?""" + + def __init__( + self, + *, + power_sources: collections.abc.Iterable[global___PowerSource] | None = ..., + camera: s2clientprotocol.common_pb2.Point | None = ..., + upgrade_ids: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["camera", b"camera"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["camera", b"camera", "power_sources", b"power_sources", "upgrade_ids", b"upgrade_ids"] + ) -> None: ... + +global___PlayerRaw = PlayerRaw + +@typing.final +class UnitOrder(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_WORLD_SPACE_POS_FIELD_NUMBER: builtins.int + TARGET_UNIT_TAG_FIELD_NUMBER: builtins.int + PROGRESS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + target_unit_tag: builtins.int + progress: builtins.float + """Progress of train abilities. Range: [0.0, 1.0]""" + @property + def target_world_space_pos(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_world_space_pos: s2clientprotocol.common_pb2.Point | None = ..., + target_unit_tag: builtins.int | None = ..., + progress: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "progress", + b"progress", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "progress", + b"progress", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_world_space_pos", "target_unit_tag"] | None: ... + +global___UnitOrder = UnitOrder + +@typing.final +class PassengerUnit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TAG_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + HEALTH_MAX_FIELD_NUMBER: builtins.int + SHIELD_FIELD_NUMBER: builtins.int + SHIELD_MAX_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + ENERGY_MAX_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + tag: builtins.int + health: builtins.float + health_max: builtins.float + shield: builtins.float + shield_max: builtins.float + energy: builtins.float + energy_max: builtins.float + unit_type: builtins.int + def __init__( + self, + *, + tag: builtins.int | None = ..., + health: builtins.float | None = ..., + health_max: builtins.float | None = ..., + shield: builtins.float | None = ..., + shield_max: builtins.float | None = ..., + energy: builtins.float | None = ..., + energy_max: builtins.float | None = ..., + unit_type: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "energy", + b"energy", + "energy_max", + b"energy_max", + "health", + b"health", + "health_max", + b"health_max", + "shield", + b"shield", + "shield_max", + b"shield_max", + "tag", + b"tag", + "unit_type", + b"unit_type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "energy", + b"energy", + "energy_max", + b"energy_max", + "health", + b"health", + "health_max", + b"health_max", + "shield", + b"shield", + "shield_max", + b"shield_max", + "tag", + b"tag", + "unit_type", + b"unit_type", + ], + ) -> None: ... + +global___PassengerUnit = PassengerUnit + +@typing.final +class RallyTarget(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + POINT_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + tag: builtins.int + """Only if it's targeting a unit.""" + @property + def point(self) -> s2clientprotocol.common_pb2.Point: + """Will always be filled.""" + + def __init__(self, *, point: s2clientprotocol.common_pb2.Point | None = ..., tag: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["point", b"point", "tag", b"tag"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["point", b"point", "tag", b"tag"]) -> None: ... + +global___RallyTarget = RallyTarget + +@typing.final +class Unit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISPLAY_TYPE_FIELD_NUMBER: builtins.int + ALLIANCE_FIELD_NUMBER: builtins.int + TAG_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + FACING_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + CLOAK_FIELD_NUMBER: builtins.int + BUFF_IDS_FIELD_NUMBER: builtins.int + DETECT_RANGE_FIELD_NUMBER: builtins.int + RADAR_RANGE_FIELD_NUMBER: builtins.int + IS_SELECTED_FIELD_NUMBER: builtins.int + IS_ON_SCREEN_FIELD_NUMBER: builtins.int + IS_BLIP_FIELD_NUMBER: builtins.int + IS_POWERED_FIELD_NUMBER: builtins.int + IS_ACTIVE_FIELD_NUMBER: builtins.int + ATTACK_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + ARMOR_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + SHIELD_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + HEALTH_MAX_FIELD_NUMBER: builtins.int + SHIELD_FIELD_NUMBER: builtins.int + SHIELD_MAX_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + ENERGY_MAX_FIELD_NUMBER: builtins.int + MINERAL_CONTENTS_FIELD_NUMBER: builtins.int + VESPENE_CONTENTS_FIELD_NUMBER: builtins.int + IS_FLYING_FIELD_NUMBER: builtins.int + IS_BURROWED_FIELD_NUMBER: builtins.int + IS_HALLUCINATION_FIELD_NUMBER: builtins.int + ORDERS_FIELD_NUMBER: builtins.int + ADD_ON_TAG_FIELD_NUMBER: builtins.int + PASSENGERS_FIELD_NUMBER: builtins.int + CARGO_SPACE_TAKEN_FIELD_NUMBER: builtins.int + CARGO_SPACE_MAX_FIELD_NUMBER: builtins.int + ASSIGNED_HARVESTERS_FIELD_NUMBER: builtins.int + IDEAL_HARVESTERS_FIELD_NUMBER: builtins.int + WEAPON_COOLDOWN_FIELD_NUMBER: builtins.int + ENGAGED_TARGET_TAG_FIELD_NUMBER: builtins.int + BUFF_DURATION_REMAIN_FIELD_NUMBER: builtins.int + BUFF_DURATION_MAX_FIELD_NUMBER: builtins.int + RALLY_TARGETS_FIELD_NUMBER: builtins.int + display_type: global___DisplayType.ValueType + """Fields are populated based on type/alliance""" + alliance: global___Alliance.ValueType + tag: builtins.int + """Unique identifier for a unit""" + unit_type: builtins.int + owner: builtins.int + facing: builtins.float + radius: builtins.float + build_progress: builtins.float + """Range: [0.0, 1.0]""" + cloak: global___CloakState.ValueType + detect_range: builtins.float + radar_range: builtins.float + is_selected: builtins.bool + is_on_screen: builtins.bool + """Visible and within the camera frustrum.""" + is_blip: builtins.bool + """Detected by sensor tower""" + is_powered: builtins.bool + is_active: builtins.bool + """Building is training/researching (ie animated).""" + attack_upgrade_level: builtins.int + armor_upgrade_level: builtins.int + shield_upgrade_level: builtins.int + health: builtins.float + """Not populated for snapshots""" + health_max: builtins.float + shield: builtins.float + shield_max: builtins.float + energy: builtins.float + energy_max: builtins.float + mineral_contents: builtins.int + vespene_contents: builtins.int + is_flying: builtins.bool + is_burrowed: builtins.bool + is_hallucination: builtins.bool + """Unit is your own or detected as a hallucination.""" + add_on_tag: builtins.int + cargo_space_taken: builtins.int + cargo_space_max: builtins.int + assigned_harvesters: builtins.int + ideal_harvesters: builtins.int + weapon_cooldown: builtins.float + engaged_target_tag: builtins.int + buff_duration_remain: builtins.int + """How long a buff or unit is still around (eg mule, broodling, chronoboost).""" + buff_duration_max: builtins.int + """How long the buff or unit is still around (eg mule, broodling, chronoboost).""" + @property + def pos(self) -> s2clientprotocol.common_pb2.Point: ... + @property + def buff_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def orders(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitOrder]: + """Not populated for enemies""" + + @property + def passengers(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PassengerUnit]: ... + @property + def rally_targets(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___RallyTarget]: ... + def __init__( + self, + *, + display_type: global___DisplayType.ValueType | None = ..., + alliance: global___Alliance.ValueType | None = ..., + tag: builtins.int | None = ..., + unit_type: builtins.int | None = ..., + owner: builtins.int | None = ..., + pos: s2clientprotocol.common_pb2.Point | None = ..., + facing: builtins.float | None = ..., + radius: builtins.float | None = ..., + build_progress: builtins.float | None = ..., + cloak: global___CloakState.ValueType | None = ..., + buff_ids: collections.abc.Iterable[builtins.int] | None = ..., + detect_range: builtins.float | None = ..., + radar_range: builtins.float | None = ..., + is_selected: builtins.bool | None = ..., + is_on_screen: builtins.bool | None = ..., + is_blip: builtins.bool | None = ..., + is_powered: builtins.bool | None = ..., + is_active: builtins.bool | None = ..., + attack_upgrade_level: builtins.int | None = ..., + armor_upgrade_level: builtins.int | None = ..., + shield_upgrade_level: builtins.int | None = ..., + health: builtins.float | None = ..., + health_max: builtins.float | None = ..., + shield: builtins.float | None = ..., + shield_max: builtins.float | None = ..., + energy: builtins.float | None = ..., + energy_max: builtins.float | None = ..., + mineral_contents: builtins.int | None = ..., + vespene_contents: builtins.int | None = ..., + is_flying: builtins.bool | None = ..., + is_burrowed: builtins.bool | None = ..., + is_hallucination: builtins.bool | None = ..., + orders: collections.abc.Iterable[global___UnitOrder] | None = ..., + add_on_tag: builtins.int | None = ..., + passengers: collections.abc.Iterable[global___PassengerUnit] | None = ..., + cargo_space_taken: builtins.int | None = ..., + cargo_space_max: builtins.int | None = ..., + assigned_harvesters: builtins.int | None = ..., + ideal_harvesters: builtins.int | None = ..., + weapon_cooldown: builtins.float | None = ..., + engaged_target_tag: builtins.int | None = ..., + buff_duration_remain: builtins.int | None = ..., + buff_duration_max: builtins.int | None = ..., + rally_targets: collections.abc.Iterable[global___RallyTarget] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "add_on_tag", + b"add_on_tag", + "alliance", + b"alliance", + "armor_upgrade_level", + b"armor_upgrade_level", + "assigned_harvesters", + b"assigned_harvesters", + "attack_upgrade_level", + b"attack_upgrade_level", + "buff_duration_max", + b"buff_duration_max", + "buff_duration_remain", + b"buff_duration_remain", + "build_progress", + b"build_progress", + "cargo_space_max", + b"cargo_space_max", + "cargo_space_taken", + b"cargo_space_taken", + "cloak", + b"cloak", + "detect_range", + b"detect_range", + "display_type", + b"display_type", + "energy", + b"energy", + "energy_max", + b"energy_max", + "engaged_target_tag", + b"engaged_target_tag", + "facing", + b"facing", + "health", + b"health", + "health_max", + b"health_max", + "ideal_harvesters", + b"ideal_harvesters", + "is_active", + b"is_active", + "is_blip", + b"is_blip", + "is_burrowed", + b"is_burrowed", + "is_flying", + b"is_flying", + "is_hallucination", + b"is_hallucination", + "is_on_screen", + b"is_on_screen", + "is_powered", + b"is_powered", + "is_selected", + b"is_selected", + "mineral_contents", + b"mineral_contents", + "owner", + b"owner", + "pos", + b"pos", + "radar_range", + b"radar_range", + "radius", + b"radius", + "shield", + b"shield", + "shield_max", + b"shield_max", + "shield_upgrade_level", + b"shield_upgrade_level", + "tag", + b"tag", + "unit_type", + b"unit_type", + "vespene_contents", + b"vespene_contents", + "weapon_cooldown", + b"weapon_cooldown", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "add_on_tag", + b"add_on_tag", + "alliance", + b"alliance", + "armor_upgrade_level", + b"armor_upgrade_level", + "assigned_harvesters", + b"assigned_harvesters", + "attack_upgrade_level", + b"attack_upgrade_level", + "buff_duration_max", + b"buff_duration_max", + "buff_duration_remain", + b"buff_duration_remain", + "buff_ids", + b"buff_ids", + "build_progress", + b"build_progress", + "cargo_space_max", + b"cargo_space_max", + "cargo_space_taken", + b"cargo_space_taken", + "cloak", + b"cloak", + "detect_range", + b"detect_range", + "display_type", + b"display_type", + "energy", + b"energy", + "energy_max", + b"energy_max", + "engaged_target_tag", + b"engaged_target_tag", + "facing", + b"facing", + "health", + b"health", + "health_max", + b"health_max", + "ideal_harvesters", + b"ideal_harvesters", + "is_active", + b"is_active", + "is_blip", + b"is_blip", + "is_burrowed", + b"is_burrowed", + "is_flying", + b"is_flying", + "is_hallucination", + b"is_hallucination", + "is_on_screen", + b"is_on_screen", + "is_powered", + b"is_powered", + "is_selected", + b"is_selected", + "mineral_contents", + b"mineral_contents", + "orders", + b"orders", + "owner", + b"owner", + "passengers", + b"passengers", + "pos", + b"pos", + "radar_range", + b"radar_range", + "radius", + b"radius", + "rally_targets", + b"rally_targets", + "shield", + b"shield", + "shield_max", + b"shield_max", + "shield_upgrade_level", + b"shield_upgrade_level", + "tag", + b"tag", + "unit_type", + b"unit_type", + "vespene_contents", + b"vespene_contents", + "weapon_cooldown", + b"weapon_cooldown", + ], + ) -> None: ... + +global___Unit = Unit + +@typing.final +class MapState(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VISIBILITY_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + @property + def visibility(self) -> s2clientprotocol.common_pb2.ImageData: + """1 byte visibility layer.""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1 bit creep layer.""" + + def __init__( + self, + *, + visibility: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["creep", b"creep", "visibility", b"visibility"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["creep", b"creep", "visibility", b"visibility"]) -> None: ... + +global___MapState = MapState + +@typing.final +class Event(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEAD_UNITS_FIELD_NUMBER: builtins.int + @property + def dead_units(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, dead_units: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dead_units", b"dead_units"]) -> None: ... + +global___Event = Event + +@typing.final +class Effect(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EFFECT_ID_FIELD_NUMBER: builtins.int + POS_FIELD_NUMBER: builtins.int + ALLIANCE_FIELD_NUMBER: builtins.int + OWNER_FIELD_NUMBER: builtins.int + RADIUS_FIELD_NUMBER: builtins.int + effect_id: builtins.int + alliance: global___Alliance.ValueType + owner: builtins.int + radius: builtins.float + @property + def pos(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.Point2D]: + """Effect may impact multiple locations. (eg. Lurker attack)""" + + def __init__( + self, + *, + effect_id: builtins.int | None = ..., + pos: collections.abc.Iterable[s2clientprotocol.common_pb2.Point2D] | None = ..., + alliance: global___Alliance.ValueType | None = ..., + owner: builtins.int | None = ..., + radius: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["alliance", b"alliance", "effect_id", b"effect_id", "owner", b"owner", "radius", b"radius"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alliance", b"alliance", "effect_id", b"effect_id", "owner", b"owner", "pos", b"pos", "radius", b"radius" + ], + ) -> None: ... + +global___Effect = Effect + +@typing.final +class ActionRaw(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_COMMAND_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + TOGGLE_AUTOCAST_FIELD_NUMBER: builtins.int + @property + def unit_command(self) -> global___ActionRawUnitCommand: ... + @property + def camera_move(self) -> global___ActionRawCameraMove: ... + @property + def toggle_autocast(self) -> global___ActionRawToggleAutocast: ... + def __init__( + self, + *, + unit_command: global___ActionRawUnitCommand | None = ..., + camera_move: global___ActionRawCameraMove | None = ..., + toggle_autocast: global___ActionRawToggleAutocast | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "toggle_autocast", + b"toggle_autocast", + "unit_command", + b"unit_command", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "toggle_autocast", + b"toggle_autocast", + "unit_command", + b"unit_command", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["unit_command", "camera_move", "toggle_autocast"] | None: ... + +global___ActionRaw = ActionRaw + +@typing.final +class ActionRawUnitCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_WORLD_SPACE_POS_FIELD_NUMBER: builtins.int + TARGET_UNIT_TAG_FIELD_NUMBER: builtins.int + UNIT_TAGS_FIELD_NUMBER: builtins.int + QUEUE_COMMAND_FIELD_NUMBER: builtins.int + ability_id: builtins.int + target_unit_tag: builtins.int + queue_command: builtins.bool + @property + def target_world_space_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_world_space_pos: s2clientprotocol.common_pb2.Point2D | None = ..., + target_unit_tag: builtins.int | None = ..., + unit_tags: collections.abc.Iterable[builtins.int] | None = ..., + queue_command: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_unit_tag", + b"target_unit_tag", + "target_world_space_pos", + b"target_world_space_pos", + "unit_tags", + b"unit_tags", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_world_space_pos", "target_unit_tag"] | None: ... + +global___ActionRawUnitCommand = ActionRawUnitCommand + +@typing.final +class ActionRawCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CENTER_WORLD_SPACE_FIELD_NUMBER: builtins.int + @property + def center_world_space(self) -> s2clientprotocol.common_pb2.Point: ... + def __init__(self, *, center_world_space: s2clientprotocol.common_pb2.Point | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["center_world_space", b"center_world_space"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["center_world_space", b"center_world_space"]) -> None: ... + +global___ActionRawCameraMove = ActionRawCameraMove + +@typing.final +class ActionRawToggleAutocast(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + UNIT_TAGS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, *, ability_id: builtins.int | None = ..., unit_tags: collections.abc.Iterable[builtins.int] | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ability_id", b"ability_id", "unit_tags", b"unit_tags"]) -> None: ... + +global___ActionRawToggleAutocast = ActionRawToggleAutocast diff --git a/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi new file mode 100644 index 000000000000..fbf53b67a613 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/sc2api_pb2.pyi @@ -0,0 +1,2896 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 +import s2clientprotocol.data_pb2 +import s2clientprotocol.debug_pb2 +import s2clientprotocol.error_pb2 +import s2clientprotocol.query_pb2 +import s2clientprotocol.raw_pb2 +import s2clientprotocol.score_pb2 +import s2clientprotocol.spatial_pb2 +import s2clientprotocol.ui_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _Status: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _StatusEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Status.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + launched: _Status.ValueType # 1 + """Game has been launch and is not yet doing anything.""" + init_game: _Status.ValueType # 2 + """Create game has been called, and the host is awaiting players.""" + in_game: _Status.ValueType # 3 + """In a single or multiplayer game.""" + in_replay: _Status.ValueType # 4 + """In a replay.""" + ended: _Status.ValueType # 5 + """Game has ended, can still request game info, but ready for a new game.""" + quit: _Status.ValueType # 6 + """Application is shutting down.""" + unknown: _Status.ValueType # 99 + """Should not happen, but indicates an error if it occurs.""" + +class Status(_Status, metaclass=_StatusEnumTypeWrapper): ... + +launched: Status.ValueType # 1 +"""Game has been launch and is not yet doing anything.""" +init_game: Status.ValueType # 2 +"""Create game has been called, and the host is awaiting players.""" +in_game: Status.ValueType # 3 +"""In a single or multiplayer game.""" +in_replay: Status.ValueType # 4 +"""In a replay.""" +ended: Status.ValueType # 5 +"""Game has ended, can still request game info, but ready for a new game.""" +quit: Status.ValueType # 6 +"""Application is shutting down.""" +unknown: Status.ValueType # 99 +"""Should not happen, but indicates an error if it occurs.""" +global___Status = Status + +class _Difficulty: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DifficultyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Difficulty.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + VeryEasy: _Difficulty.ValueType # 1 + Easy: _Difficulty.ValueType # 2 + Medium: _Difficulty.ValueType # 3 + MediumHard: _Difficulty.ValueType # 4 + Hard: _Difficulty.ValueType # 5 + Harder: _Difficulty.ValueType # 6 + VeryHard: _Difficulty.ValueType # 7 + CheatVision: _Difficulty.ValueType # 8 + CheatMoney: _Difficulty.ValueType # 9 + CheatInsane: _Difficulty.ValueType # 10 + +class Difficulty(_Difficulty, metaclass=_DifficultyEnumTypeWrapper): + """ + Game Setup + """ + +VeryEasy: Difficulty.ValueType # 1 +Easy: Difficulty.ValueType # 2 +Medium: Difficulty.ValueType # 3 +MediumHard: Difficulty.ValueType # 4 +Hard: Difficulty.ValueType # 5 +Harder: Difficulty.ValueType # 6 +VeryHard: Difficulty.ValueType # 7 +CheatVision: Difficulty.ValueType # 8 +CheatMoney: Difficulty.ValueType # 9 +CheatInsane: Difficulty.ValueType # 10 +global___Difficulty = Difficulty + +class _PlayerType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PlayerTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PlayerType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Participant: _PlayerType.ValueType # 1 + Computer: _PlayerType.ValueType # 2 + Observer: _PlayerType.ValueType # 3 + +class PlayerType(_PlayerType, metaclass=_PlayerTypeEnumTypeWrapper): ... + +Participant: PlayerType.ValueType # 1 +Computer: PlayerType.ValueType # 2 +Observer: PlayerType.ValueType # 3 +global___PlayerType = PlayerType + +class _AIBuild: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AIBuildEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_AIBuild.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RandomBuild: _AIBuild.ValueType # 1 + Rush: _AIBuild.ValueType # 2 + Timing: _AIBuild.ValueType # 3 + Power: _AIBuild.ValueType # 4 + Macro: _AIBuild.ValueType # 5 + Air: _AIBuild.ValueType # 6 + +class AIBuild(_AIBuild, metaclass=_AIBuildEnumTypeWrapper): ... + +RandomBuild: AIBuild.ValueType # 1 +Rush: AIBuild.ValueType # 2 +Timing: AIBuild.ValueType # 3 +Power: AIBuild.ValueType # 4 +Macro: AIBuild.ValueType # 5 +Air: AIBuild.ValueType # 6 +global___AIBuild = AIBuild + +class _Alert: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AlertEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Alert.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AlertError: _Alert.ValueType # 3 + AddOnComplete: _Alert.ValueType # 4 + BuildingComplete: _Alert.ValueType # 5 + BuildingUnderAttack: _Alert.ValueType # 6 + LarvaHatched: _Alert.ValueType # 7 + MergeComplete: _Alert.ValueType # 8 + MineralsExhausted: _Alert.ValueType # 9 + MorphComplete: _Alert.ValueType # 10 + MothershipComplete: _Alert.ValueType # 11 + MULEExpired: _Alert.ValueType # 12 + NuclearLaunchDetected: _Alert.ValueType # 1 + NukeComplete: _Alert.ValueType # 13 + NydusWormDetected: _Alert.ValueType # 2 + ResearchComplete: _Alert.ValueType # 14 + TrainError: _Alert.ValueType # 15 + TrainUnitComplete: _Alert.ValueType # 16 + TrainWorkerComplete: _Alert.ValueType # 17 + TransformationComplete: _Alert.ValueType # 18 + UnitUnderAttack: _Alert.ValueType # 19 + UpgradeComplete: _Alert.ValueType # 20 + VespeneExhausted: _Alert.ValueType # 21 + WarpInComplete: _Alert.ValueType # 22 + +class Alert(_Alert, metaclass=_AlertEnumTypeWrapper): ... + +AlertError: Alert.ValueType # 3 +AddOnComplete: Alert.ValueType # 4 +BuildingComplete: Alert.ValueType # 5 +BuildingUnderAttack: Alert.ValueType # 6 +LarvaHatched: Alert.ValueType # 7 +MergeComplete: Alert.ValueType # 8 +MineralsExhausted: Alert.ValueType # 9 +MorphComplete: Alert.ValueType # 10 +MothershipComplete: Alert.ValueType # 11 +MULEExpired: Alert.ValueType # 12 +NuclearLaunchDetected: Alert.ValueType # 1 +NukeComplete: Alert.ValueType # 13 +NydusWormDetected: Alert.ValueType # 2 +ResearchComplete: Alert.ValueType # 14 +TrainError: Alert.ValueType # 15 +TrainUnitComplete: Alert.ValueType # 16 +TrainWorkerComplete: Alert.ValueType # 17 +TransformationComplete: Alert.ValueType # 18 +UnitUnderAttack: Alert.ValueType # 19 +UpgradeComplete: Alert.ValueType # 20 +VespeneExhausted: Alert.ValueType # 21 +WarpInComplete: Alert.ValueType # 22 +global___Alert = Alert + +class _Result: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ResultEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Result.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Victory: _Result.ValueType # 1 + Defeat: _Result.ValueType # 2 + Tie: _Result.ValueType # 3 + Undecided: _Result.ValueType # 4 + +class Result(_Result, metaclass=_ResultEnumTypeWrapper): ... + +Victory: Result.ValueType # 1 +Defeat: Result.ValueType # 2 +Tie: Result.ValueType # 3 +Undecided: Result.ValueType # 4 +global___Result = Result + +@typing.final +class Request(google.protobuf.message.Message): + """ + Request/Response + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CREATE_GAME_FIELD_NUMBER: builtins.int + JOIN_GAME_FIELD_NUMBER: builtins.int + RESTART_GAME_FIELD_NUMBER: builtins.int + START_REPLAY_FIELD_NUMBER: builtins.int + LEAVE_GAME_FIELD_NUMBER: builtins.int + QUICK_SAVE_FIELD_NUMBER: builtins.int + QUICK_LOAD_FIELD_NUMBER: builtins.int + QUIT_FIELD_NUMBER: builtins.int + GAME_INFO_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + ACTION_FIELD_NUMBER: builtins.int + OBS_ACTION_FIELD_NUMBER: builtins.int + STEP_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + QUERY_FIELD_NUMBER: builtins.int + SAVE_REPLAY_FIELD_NUMBER: builtins.int + MAP_COMMAND_FIELD_NUMBER: builtins.int + REPLAY_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_MAPS_FIELD_NUMBER: builtins.int + SAVE_MAP_FIELD_NUMBER: builtins.int + PING_FIELD_NUMBER: builtins.int + DEBUG_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + id: builtins.int + @property + def create_game(self) -> global___RequestCreateGame: + """Game Setup + Send to host to initialize game. + """ + + @property + def join_game(self) -> global___RequestJoinGame: + """Send to host and all clients for game to begin.""" + + @property + def restart_game(self) -> global___RequestRestartGame: + """Single player only. Reinitializes the game with the same player setup.""" + + @property + def start_replay(self) -> global___RequestStartReplay: + """Start playing a replay.""" + + @property + def leave_game(self) -> global___RequestLeaveGame: + """Multiplayer only. Disconnects from a multiplayer game, equivalent to surrender.""" + + @property + def quick_save(self) -> global___RequestQuickSave: + """Saves game to an in-memory bookmark.""" + + @property + def quick_load(self) -> global___RequestQuickLoad: + """Loads from an in-memory bookmark.""" + + @property + def quit(self) -> global___RequestQuit: + """Terminates the application.""" + + @property + def game_info(self) -> global___RequestGameInfo: + """During Game + Static data about the current game and map. + """ + + @property + def observation(self) -> global___RequestObservation: + """Snapshot of the current game state.""" + + @property + def action(self) -> global___RequestAction: + """Executes an action for a participant.""" + + @property + def obs_action(self) -> global___RequestObserverAction: + """Executes an action for an observer.""" + + @property + def step(self) -> global___RequestStep: + """Advances the game simulation.""" + + @property + def data(self) -> global___RequestData: + """Data about different gameplay elements. May be different for different games.""" + + @property + def query(self) -> s2clientprotocol.query_pb2.RequestQuery: + """Additional methods for inspecting game state.""" + + @property + def save_replay(self) -> global___RequestSaveReplay: + """Generates a replay.""" + + @property + def map_command(self) -> global___RequestMapCommand: + """Execute a particular trigger through a string interface""" + + @property + def replay_info(self) -> global___RequestReplayInfo: + """Other. + Returns metadata about a replay file. Does not load the replay. + """ + + @property + def available_maps(self) -> global___RequestAvailableMaps: + """Returns directory of maps that can be played on.""" + + @property + def save_map(self) -> global___RequestSaveMap: + """Saves binary map data to the local temp directory.""" + + @property + def ping(self) -> global___RequestPing: + """Debugging + Network ping for testing connection. + """ + + @property + def debug(self) -> global___RequestDebug: + """Display debug information and execute debug actions.""" + + def __init__( + self, + *, + create_game: global___RequestCreateGame | None = ..., + join_game: global___RequestJoinGame | None = ..., + restart_game: global___RequestRestartGame | None = ..., + start_replay: global___RequestStartReplay | None = ..., + leave_game: global___RequestLeaveGame | None = ..., + quick_save: global___RequestQuickSave | None = ..., + quick_load: global___RequestQuickLoad | None = ..., + quit: global___RequestQuit | None = ..., + game_info: global___RequestGameInfo | None = ..., + observation: global___RequestObservation | None = ..., + action: global___RequestAction | None = ..., + obs_action: global___RequestObserverAction | None = ..., + step: global___RequestStep | None = ..., + data: global___RequestData | None = ..., + query: s2clientprotocol.query_pb2.RequestQuery | None = ..., + save_replay: global___RequestSaveReplay | None = ..., + map_command: global___RequestMapCommand | None = ..., + replay_info: global___RequestReplayInfo | None = ..., + available_maps: global___RequestAvailableMaps | None = ..., + save_map: global___RequestSaveMap | None = ..., + ping: global___RequestPing | None = ..., + debug: global___RequestDebug | None = ..., + id: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "request", + b"request", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "step", + b"step", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "request", + b"request", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "step", + b"step", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["request", b"request"] + ) -> ( + typing.Literal[ + "create_game", + "join_game", + "restart_game", + "start_replay", + "leave_game", + "quick_save", + "quick_load", + "quit", + "game_info", + "observation", + "action", + "obs_action", + "step", + "data", + "query", + "save_replay", + "map_command", + "replay_info", + "available_maps", + "save_map", + "ping", + "debug", + ] + | None + ): ... + +global___Request = Request + +@typing.final +class Response(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CREATE_GAME_FIELD_NUMBER: builtins.int + JOIN_GAME_FIELD_NUMBER: builtins.int + RESTART_GAME_FIELD_NUMBER: builtins.int + START_REPLAY_FIELD_NUMBER: builtins.int + LEAVE_GAME_FIELD_NUMBER: builtins.int + QUICK_SAVE_FIELD_NUMBER: builtins.int + QUICK_LOAD_FIELD_NUMBER: builtins.int + QUIT_FIELD_NUMBER: builtins.int + GAME_INFO_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + ACTION_FIELD_NUMBER: builtins.int + OBS_ACTION_FIELD_NUMBER: builtins.int + STEP_FIELD_NUMBER: builtins.int + DATA_FIELD_NUMBER: builtins.int + QUERY_FIELD_NUMBER: builtins.int + SAVE_REPLAY_FIELD_NUMBER: builtins.int + REPLAY_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_MAPS_FIELD_NUMBER: builtins.int + SAVE_MAP_FIELD_NUMBER: builtins.int + MAP_COMMAND_FIELD_NUMBER: builtins.int + PING_FIELD_NUMBER: builtins.int + DEBUG_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + STATUS_FIELD_NUMBER: builtins.int + id: builtins.int + status: global___Status.ValueType + """Should be sent back with all responses.""" + @property + def create_game(self) -> global___ResponseCreateGame: ... + @property + def join_game(self) -> global___ResponseJoinGame: ... + @property + def restart_game(self) -> global___ResponseRestartGame: ... + @property + def start_replay(self) -> global___ResponseStartReplay: ... + @property + def leave_game(self) -> global___ResponseLeaveGame: ... + @property + def quick_save(self) -> global___ResponseQuickSave: ... + @property + def quick_load(self) -> global___ResponseQuickLoad: ... + @property + def quit(self) -> global___ResponseQuit: ... + @property + def game_info(self) -> global___ResponseGameInfo: ... + @property + def observation(self) -> global___ResponseObservation: ... + @property + def action(self) -> global___ResponseAction: ... + @property + def obs_action(self) -> global___ResponseObserverAction: ... + @property + def step(self) -> global___ResponseStep: ... + @property + def data(self) -> global___ResponseData: ... + @property + def query(self) -> s2clientprotocol.query_pb2.ResponseQuery: ... + @property + def save_replay(self) -> global___ResponseSaveReplay: ... + @property + def replay_info(self) -> global___ResponseReplayInfo: ... + @property + def available_maps(self) -> global___ResponseAvailableMaps: ... + @property + def save_map(self) -> global___ResponseSaveMap: ... + @property + def map_command(self) -> global___ResponseMapCommand: ... + @property + def ping(self) -> global___ResponsePing: + """Debugging""" + + @property + def debug(self) -> global___ResponseDebug: ... + @property + def error(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """If command is missing, this will contain the error. Otherwise this will contain any warnings.""" + + def __init__( + self, + *, + create_game: global___ResponseCreateGame | None = ..., + join_game: global___ResponseJoinGame | None = ..., + restart_game: global___ResponseRestartGame | None = ..., + start_replay: global___ResponseStartReplay | None = ..., + leave_game: global___ResponseLeaveGame | None = ..., + quick_save: global___ResponseQuickSave | None = ..., + quick_load: global___ResponseQuickLoad | None = ..., + quit: global___ResponseQuit | None = ..., + game_info: global___ResponseGameInfo | None = ..., + observation: global___ResponseObservation | None = ..., + action: global___ResponseAction | None = ..., + obs_action: global___ResponseObserverAction | None = ..., + step: global___ResponseStep | None = ..., + data: global___ResponseData | None = ..., + query: s2clientprotocol.query_pb2.ResponseQuery | None = ..., + save_replay: global___ResponseSaveReplay | None = ..., + replay_info: global___ResponseReplayInfo | None = ..., + available_maps: global___ResponseAvailableMaps | None = ..., + save_map: global___ResponseSaveMap | None = ..., + map_command: global___ResponseMapCommand | None = ..., + ping: global___ResponsePing | None = ..., + debug: global___ResponseDebug | None = ..., + id: builtins.int | None = ..., + error: collections.abc.Iterable[builtins.str] | None = ..., + status: global___Status.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "response", + b"response", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "status", + b"status", + "step", + b"step", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "available_maps", + b"available_maps", + "create_game", + b"create_game", + "data", + b"data", + "debug", + b"debug", + "error", + b"error", + "game_info", + b"game_info", + "id", + b"id", + "join_game", + b"join_game", + "leave_game", + b"leave_game", + "map_command", + b"map_command", + "obs_action", + b"obs_action", + "observation", + b"observation", + "ping", + b"ping", + "query", + b"query", + "quick_load", + b"quick_load", + "quick_save", + b"quick_save", + "quit", + b"quit", + "replay_info", + b"replay_info", + "response", + b"response", + "restart_game", + b"restart_game", + "save_map", + b"save_map", + "save_replay", + b"save_replay", + "start_replay", + b"start_replay", + "status", + b"status", + "step", + b"step", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["response", b"response"] + ) -> ( + typing.Literal[ + "create_game", + "join_game", + "restart_game", + "start_replay", + "leave_game", + "quick_save", + "quick_load", + "quit", + "game_info", + "observation", + "action", + "obs_action", + "step", + "data", + "query", + "save_replay", + "replay_info", + "available_maps", + "save_map", + "map_command", + "ping", + "debug", + ] + | None + ): ... + +global___Response = Response + +@typing.final +class RequestCreateGame(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + If successful, puts the game into the status: init_game. + The next expected request should be RequestJoinGame. Can also quit (exit). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOCAL_MAP_FIELD_NUMBER: builtins.int + BATTLENET_MAP_NAME_FIELD_NUMBER: builtins.int + PLAYER_SETUP_FIELD_NUMBER: builtins.int + DISABLE_FOG_FIELD_NUMBER: builtins.int + RANDOM_SEED_FIELD_NUMBER: builtins.int + REALTIME_FIELD_NUMBER: builtins.int + battlenet_map_name: builtins.str + """Map published to BattleNet""" + disable_fog: builtins.bool + random_seed: builtins.int + """Sets the pseudo-random seed for the game.""" + realtime: builtins.bool + """If set, the game plays in real time.""" + @property + def local_map(self) -> global___LocalMap: + """Local .SC2Map file""" + + @property + def player_setup(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerSetup]: ... + def __init__( + self, + *, + local_map: global___LocalMap | None = ..., + battlenet_map_name: builtins.str | None = ..., + player_setup: collections.abc.Iterable[global___PlayerSetup] | None = ..., + disable_fog: builtins.bool | None = ..., + random_seed: builtins.int | None = ..., + realtime: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "Map", + b"Map", + "battlenet_map_name", + b"battlenet_map_name", + "disable_fog", + b"disable_fog", + "local_map", + b"local_map", + "random_seed", + b"random_seed", + "realtime", + b"realtime", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "Map", + b"Map", + "battlenet_map_name", + b"battlenet_map_name", + "disable_fog", + b"disable_fog", + "local_map", + b"local_map", + "player_setup", + b"player_setup", + "random_seed", + b"random_seed", + "realtime", + b"realtime", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["Map", b"Map"] + ) -> typing.Literal["local_map", "battlenet_map_name"] | None: ... + +global___RequestCreateGame = RequestCreateGame + +@typing.final +class LocalMap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_PATH_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + map_path: builtins.str + """A map can be specified either by a file path or the data of the .SC2Map file. + If you provide both, it will play the game using map_data and store map_path + into the replay. (260 character max) + """ + map_data: builtins.bytes + def __init__(self, *, map_path: builtins.str | None = ..., map_data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> None: ... + +global___LocalMap = LocalMap + +@typing.final +class ResponseCreateGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseCreateGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingMap: ResponseCreateGame._Error.ValueType # 1 + InvalidMapPath: ResponseCreateGame._Error.ValueType # 2 + InvalidMapData: ResponseCreateGame._Error.ValueType # 3 + InvalidMapName: ResponseCreateGame._Error.ValueType # 4 + InvalidMapHandle: ResponseCreateGame._Error.ValueType # 5 + MissingPlayerSetup: ResponseCreateGame._Error.ValueType # 6 + InvalidPlayerSetup: ResponseCreateGame._Error.ValueType # 7 + MultiplayerUnsupported: ResponseCreateGame._Error.ValueType # 8 + """Multiplayer is not supported in the current build.""" + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingMap: ResponseCreateGame.Error.ValueType # 1 + InvalidMapPath: ResponseCreateGame.Error.ValueType # 2 + InvalidMapData: ResponseCreateGame.Error.ValueType # 3 + InvalidMapName: ResponseCreateGame.Error.ValueType # 4 + InvalidMapHandle: ResponseCreateGame.Error.ValueType # 5 + MissingPlayerSetup: ResponseCreateGame.Error.ValueType # 6 + InvalidPlayerSetup: ResponseCreateGame.Error.ValueType # 7 + MultiplayerUnsupported: ResponseCreateGame.Error.ValueType # 8 + """Multiplayer is not supported in the current build.""" + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseCreateGame.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseCreateGame.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseCreateGame = ResponseCreateGame + +@typing.final +class RequestJoinGame(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + If successful, puts the game into the status: in_game. Will be able to + request actions, observations and step the game. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RACE_FIELD_NUMBER: builtins.int + OBSERVED_PLAYER_ID_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + SERVER_PORTS_FIELD_NUMBER: builtins.int + CLIENT_PORTS_FIELD_NUMBER: builtins.int + SHARED_PORT_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + HOST_IP_FIELD_NUMBER: builtins.int + race: s2clientprotocol.common_pb2.Race.ValueType + """Join as participant""" + observed_player_id: builtins.int + """Join as observer""" + shared_port: builtins.int + """Currently only a singe client is supported. + deprecated + """ + player_name: builtins.str + """Use this to set the player's name to something other than autogenerated name.""" + host_ip: builtins.str + """Both game creator and joiner should provide the ip address of the game creator in order to play remotely. Defaults to localhost.""" + @property + def options(self) -> global___InterfaceOptions: + """This is limited to what is specified in RequestCreateGame, but you can request less information if you want.""" + + @property + def server_ports(self) -> global___PortSet: + """Do not set in the single-player case. This is the port a server will use.""" + + @property + def client_ports(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PortSet]: + """Do not set in the single-player case. These are the ports clients will use to initialize communication.""" + + def __init__( + self, + *, + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + observed_player_id: builtins.int | None = ..., + options: global___InterfaceOptions | None = ..., + server_ports: global___PortSet | None = ..., + client_ports: collections.abc.Iterable[global___PortSet] | None = ..., + shared_port: builtins.int | None = ..., + player_name: builtins.str | None = ..., + host_ip: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "host_ip", + b"host_ip", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "participation", + b"participation", + "player_name", + b"player_name", + "race", + b"race", + "server_ports", + b"server_ports", + "shared_port", + b"shared_port", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "client_ports", + b"client_ports", + "host_ip", + b"host_ip", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "participation", + b"participation", + "player_name", + b"player_name", + "race", + b"race", + "server_ports", + b"server_ports", + "shared_port", + b"shared_port", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["participation", b"participation"] + ) -> typing.Literal["race", "observed_player_id"] | None: ... + +global___RequestJoinGame = RequestJoinGame + +@typing.final +class PortSet(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_PORT_FIELD_NUMBER: builtins.int + BASE_PORT_FIELD_NUMBER: builtins.int + game_port: builtins.int + """Game right now needs two internal ports to establish a multiplay game on the local host.""" + base_port: builtins.int + def __init__(self, *, game_port: builtins.int | None = ..., base_port: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["base_port", b"base_port", "game_port", b"game_port"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["base_port", b"base_port", "game_port", b"game_port"]) -> None: ... + +global___PortSet = PortSet + +@typing.final +class ResponseJoinGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseJoinGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingParticipation: ResponseJoinGame._Error.ValueType # 1 + InvalidObservedPlayerId: ResponseJoinGame._Error.ValueType # 2 + MissingOptions: ResponseJoinGame._Error.ValueType # 3 + MissingPorts: ResponseJoinGame._Error.ValueType # 4 + GameFull: ResponseJoinGame._Error.ValueType # 5 + LaunchError: ResponseJoinGame._Error.ValueType # 6 + FeatureUnsupported: ResponseJoinGame._Error.ValueType # 7 + """Multiplayer specific. + Multiplayer is not supported in the current build for the requested features. + """ + NoSpaceForUser: ResponseJoinGame._Error.ValueType # 8 + MapDoesNotExist: ResponseJoinGame._Error.ValueType # 9 + CannotOpenMap: ResponseJoinGame._Error.ValueType # 10 + ChecksumError: ResponseJoinGame._Error.ValueType # 11 + NetworkError: ResponseJoinGame._Error.ValueType # 12 + OtherError: ResponseJoinGame._Error.ValueType # 13 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingParticipation: ResponseJoinGame.Error.ValueType # 1 + InvalidObservedPlayerId: ResponseJoinGame.Error.ValueType # 2 + MissingOptions: ResponseJoinGame.Error.ValueType # 3 + MissingPorts: ResponseJoinGame.Error.ValueType # 4 + GameFull: ResponseJoinGame.Error.ValueType # 5 + LaunchError: ResponseJoinGame.Error.ValueType # 6 + FeatureUnsupported: ResponseJoinGame.Error.ValueType # 7 + """Multiplayer specific. + Multiplayer is not supported in the current build for the requested features. + """ + NoSpaceForUser: ResponseJoinGame.Error.ValueType # 8 + MapDoesNotExist: ResponseJoinGame.Error.ValueType # 9 + CannotOpenMap: ResponseJoinGame.Error.ValueType # 10 + ChecksumError: ResponseJoinGame.Error.ValueType # 11 + NetworkError: ResponseJoinGame.Error.ValueType # 12 + OtherError: ResponseJoinGame.Error.ValueType # 13 + + PLAYER_ID_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + player_id: builtins.int + error: global___ResponseJoinGame.Error.ValueType + error_details: builtins.str + def __init__( + self, + *, + player_id: builtins.int | None = ..., + error: global___ResponseJoinGame.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["error", b"error", "error_details", b"error_details", "player_id", b"player_id"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["error", b"error", "error_details", b"error_details", "player_id", b"player_id"] + ) -> None: ... + +global___ResponseJoinGame = ResponseJoinGame + +@typing.final +class RequestRestartGame(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestRestartGame = RequestRestartGame + +@typing.final +class ResponseRestartGame(google.protobuf.message.Message): + """The defaultRestartGameLoops is specified to be (1<<18) by default""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseRestartGame._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + LaunchError: ResponseRestartGame._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + LaunchError: ResponseRestartGame.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + NEED_HARD_RESET_FIELD_NUMBER: builtins.int + error: global___ResponseRestartGame.Error.ValueType + error_details: builtins.str + need_hard_reset: builtins.bool + """This will occur once the simulation_loop is greater then defaultRestartGameLoops""" + def __init__( + self, + *, + error: global___ResponseRestartGame.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + need_hard_reset: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["error", b"error", "error_details", b"error_details", "need_hard_reset", b"need_hard_reset"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["error", b"error", "error_details", b"error_details", "need_hard_reset", b"need_hard_reset"], + ) -> None: ... + +global___ResponseRestartGame = ResponseRestartGame + +@typing.final +class RequestStartReplay(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLAY_PATH_FIELD_NUMBER: builtins.int + REPLAY_DATA_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + OBSERVED_PLAYER_ID_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + DISABLE_FOG_FIELD_NUMBER: builtins.int + REALTIME_FIELD_NUMBER: builtins.int + RECORD_REPLAY_FIELD_NUMBER: builtins.int + replay_path: builtins.str + replay_data: builtins.bytes + map_data: builtins.bytes + """Overrides the map path stored in the replay.""" + observed_player_id: builtins.int + disable_fog: builtins.bool + realtime: builtins.bool + record_replay: builtins.bool + """Allow RequestSaveReplay from a replay. Useful for truncating a replay, or restoring tracker.events.""" + @property + def options(self) -> global___InterfaceOptions: ... + def __init__( + self, + *, + replay_path: builtins.str | None = ..., + replay_data: builtins.bytes | None = ..., + map_data: builtins.bytes | None = ..., + observed_player_id: builtins.int | None = ..., + options: global___InterfaceOptions | None = ..., + disable_fog: builtins.bool | None = ..., + realtime: builtins.bool | None = ..., + record_replay: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "disable_fog", + b"disable_fog", + "map_data", + b"map_data", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "realtime", + b"realtime", + "record_replay", + b"record_replay", + "replay", + b"replay", + "replay_data", + b"replay_data", + "replay_path", + b"replay_path", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "disable_fog", + b"disable_fog", + "map_data", + b"map_data", + "observed_player_id", + b"observed_player_id", + "options", + b"options", + "realtime", + b"realtime", + "record_replay", + b"record_replay", + "replay", + b"replay", + "replay_data", + b"replay_data", + "replay_path", + b"replay_path", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["replay", b"replay"] + ) -> typing.Literal["replay_path", "replay_data"] | None: ... + +global___RequestStartReplay = RequestStartReplay + +@typing.final +class ResponseStartReplay(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseStartReplay._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingReplay: ResponseStartReplay._Error.ValueType # 1 + InvalidReplayPath: ResponseStartReplay._Error.ValueType # 2 + InvalidReplayData: ResponseStartReplay._Error.ValueType # 3 + InvalidMapData: ResponseStartReplay._Error.ValueType # 4 + InvalidObservedPlayerId: ResponseStartReplay._Error.ValueType # 5 + MissingOptions: ResponseStartReplay._Error.ValueType # 6 + LaunchError: ResponseStartReplay._Error.ValueType # 7 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingReplay: ResponseStartReplay.Error.ValueType # 1 + InvalidReplayPath: ResponseStartReplay.Error.ValueType # 2 + InvalidReplayData: ResponseStartReplay.Error.ValueType # 3 + InvalidMapData: ResponseStartReplay.Error.ValueType # 4 + InvalidObservedPlayerId: ResponseStartReplay.Error.ValueType # 5 + MissingOptions: ResponseStartReplay.Error.ValueType # 6 + LaunchError: ResponseStartReplay.Error.ValueType # 7 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseStartReplay.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseStartReplay.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseStartReplay = ResponseStartReplay + +@typing.final +class RequestMapCommand(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TRIGGER_CMD_FIELD_NUMBER: builtins.int + trigger_cmd: builtins.str + def __init__(self, *, trigger_cmd: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["trigger_cmd", b"trigger_cmd"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["trigger_cmd", b"trigger_cmd"]) -> None: ... + +global___RequestMapCommand = RequestMapCommand + +@typing.final +class ResponseMapCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseMapCommand._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NoTriggerError: ResponseMapCommand._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + NoTriggerError: ResponseMapCommand.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + error: global___ResponseMapCommand.Error.ValueType + error_details: builtins.str + def __init__( + self, *, error: global___ResponseMapCommand.Error.ValueType | None = ..., error_details: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error", "error_details", b"error_details"]) -> None: ... + +global___ResponseMapCommand = ResponseMapCommand + +@typing.final +class RequestLeaveGame(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestLeaveGame = RequestLeaveGame + +@typing.final +class ResponseLeaveGame(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseLeaveGame = ResponseLeaveGame + +@typing.final +class RequestQuickSave(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuickSave = RequestQuickSave + +@typing.final +class ResponseQuickSave(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuickSave = ResponseQuickSave + +@typing.final +class RequestQuickLoad(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuickLoad = RequestQuickLoad + +@typing.final +class ResponseQuickLoad(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuickLoad = ResponseQuickLoad + +@typing.final +class RequestQuit(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestQuit = RequestQuit + +@typing.final +class ResponseQuit(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseQuit = ResponseQuit + +@typing.final +class RequestGameInfo(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestGameInfo = RequestGameInfo + +@typing.final +class ResponseGameInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_NAME_FIELD_NUMBER: builtins.int + MOD_NAMES_FIELD_NUMBER: builtins.int + LOCAL_MAP_PATH_FIELD_NUMBER: builtins.int + PLAYER_INFO_FIELD_NUMBER: builtins.int + START_RAW_FIELD_NUMBER: builtins.int + OPTIONS_FIELD_NUMBER: builtins.int + map_name: builtins.str + local_map_path: builtins.str + @property + def mod_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def player_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerInfo]: ... + @property + def start_raw(self) -> s2clientprotocol.raw_pb2.StartRaw: + """Populated if Raw interface is enabled.""" + + @property + def options(self) -> global___InterfaceOptions: ... + def __init__( + self, + *, + map_name: builtins.str | None = ..., + mod_names: collections.abc.Iterable[builtins.str] | None = ..., + local_map_path: builtins.str | None = ..., + player_info: collections.abc.Iterable[global___PlayerInfo] | None = ..., + start_raw: s2clientprotocol.raw_pb2.StartRaw | None = ..., + options: global___InterfaceOptions | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "local_map_path", b"local_map_path", "map_name", b"map_name", "options", b"options", "start_raw", b"start_raw" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + "mod_names", + b"mod_names", + "options", + b"options", + "player_info", + b"player_info", + "start_raw", + b"start_raw", + ], + ) -> None: ... + +global___ResponseGameInfo = ResponseGameInfo + +@typing.final +class RequestObservation(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DISABLE_FOG_FIELD_NUMBER: builtins.int + GAME_LOOP_FIELD_NUMBER: builtins.int + disable_fog: builtins.bool + game_loop: builtins.int + """In realtime the request will only return once the simulation game loop has reached this value. When not realtime this value is ignored.""" + def __init__(self, *, disable_fog: builtins.bool | None = ..., game_loop: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["disable_fog", b"disable_fog", "game_loop", b"game_loop"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["disable_fog", b"disable_fog", "game_loop", b"game_loop"]) -> None: ... + +global___RequestObservation = RequestObservation + +@typing.final +class ResponseObservation(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + ACTION_ERRORS_FIELD_NUMBER: builtins.int + OBSERVATION_FIELD_NUMBER: builtins.int + PLAYER_RESULT_FIELD_NUMBER: builtins.int + CHAT_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Action]: + """Actions this player did since the last Observation.""" + + @property + def action_errors(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ActionError]: + """Equivalent of UI "red text" errors.""" + + @property + def observation(self) -> global___Observation: ... + @property + def player_result(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerResult]: + """Only populated if the game ended during this step.""" + + @property + def chat(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ChatReceived]: ... + def __init__( + self, + *, + actions: collections.abc.Iterable[global___Action] | None = ..., + action_errors: collections.abc.Iterable[global___ActionError] | None = ..., + observation: global___Observation | None = ..., + player_result: collections.abc.Iterable[global___PlayerResult] | None = ..., + chat: collections.abc.Iterable[global___ChatReceived] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["observation", b"observation"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_errors", + b"action_errors", + "actions", + b"actions", + "chat", + b"chat", + "observation", + b"observation", + "player_result", + b"player_result", + ], + ) -> None: ... + +global___ResponseObservation = ResponseObservation + +@typing.final +class ChatReceived(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + player_id: builtins.int + message: builtins.str + def __init__(self, *, player_id: builtins.int | None = ..., message: builtins.str | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["message", b"message", "player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["message", b"message", "player_id", b"player_id"]) -> None: ... + +global___ChatReceived = ChatReceived + +@typing.final +class RequestAction(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Action]: ... + def __init__(self, *, actions: collections.abc.Iterable[global___Action] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["actions", b"actions"]) -> None: ... + +global___RequestAction = RequestAction + +@typing.final +class ResponseAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESULT_FIELD_NUMBER: builtins.int + @property + def result( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[s2clientprotocol.error_pb2.ActionResult.ValueType]: ... + def __init__( + self, *, result: collections.abc.Iterable[s2clientprotocol.error_pb2.ActionResult.ValueType] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["result", b"result"]) -> None: ... + +global___ResponseAction = ResponseAction + +@typing.final +class RequestObserverAction(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTIONS_FIELD_NUMBER: builtins.int + @property + def actions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ObserverAction]: ... + def __init__(self, *, actions: collections.abc.Iterable[global___ObserverAction] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["actions", b"actions"]) -> None: ... + +global___RequestObserverAction = RequestObserverAction + +@typing.final +class ResponseObserverAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseObserverAction = ResponseObserverAction + +@typing.final +class RequestStep(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COUNT_FIELD_NUMBER: builtins.int + count: builtins.int + """Number of game loops to simulate for the next frame.""" + def __init__(self, *, count: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["count", b"count"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["count", b"count"]) -> None: ... + +global___RequestStep = RequestStep + +@typing.final +class ResponseStep(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIMULATION_LOOP_FIELD_NUMBER: builtins.int + simulation_loop: builtins.int + """ Max simulation_loop is (1<<19) before "end of time" will occur + The "end of time" is classified as the maximum number of game loops or absolute game time + representable as a positive fixed point number. + When we reach the "end of time", permanently pause the game and end the game for all. + """ + def __init__(self, *, simulation_loop: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["simulation_loop", b"simulation_loop"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["simulation_loop", b"simulation_loop"]) -> None: ... + +global___ResponseStep = ResponseStep + +@typing.final +class RequestData(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + UNIT_TYPE_ID_FIELD_NUMBER: builtins.int + UPGRADE_ID_FIELD_NUMBER: builtins.int + BUFF_ID_FIELD_NUMBER: builtins.int + EFFECT_ID_FIELD_NUMBER: builtins.int + ability_id: builtins.bool + unit_type_id: builtins.bool + upgrade_id: builtins.bool + buff_id: builtins.bool + effect_id: builtins.bool + def __init__( + self, + *, + ability_id: builtins.bool | None = ..., + unit_type_id: builtins.bool | None = ..., + upgrade_id: builtins.bool | None = ..., + buff_id: builtins.bool | None = ..., + effect_id: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "buff_id", + b"buff_id", + "effect_id", + b"effect_id", + "unit_type_id", + b"unit_type_id", + "upgrade_id", + b"upgrade_id", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "buff_id", + b"buff_id", + "effect_id", + b"effect_id", + "unit_type_id", + b"unit_type_id", + "upgrade_id", + b"upgrade_id", + ], + ) -> None: ... + +global___RequestData = RequestData + +@typing.final +class ResponseData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITIES_FIELD_NUMBER: builtins.int + UNITS_FIELD_NUMBER: builtins.int + UPGRADES_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.AbilityData]: ... + @property + def units( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.UnitTypeData]: ... + @property + def upgrades( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.UpgradeData]: ... + @property + def buffs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.BuffData]: ... + @property + def effects( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.data_pb2.EffectData]: ... + def __init__( + self, + *, + abilities: collections.abc.Iterable[s2clientprotocol.data_pb2.AbilityData] | None = ..., + units: collections.abc.Iterable[s2clientprotocol.data_pb2.UnitTypeData] | None = ..., + upgrades: collections.abc.Iterable[s2clientprotocol.data_pb2.UpgradeData] | None = ..., + buffs: collections.abc.Iterable[s2clientprotocol.data_pb2.BuffData] | None = ..., + effects: collections.abc.Iterable[s2clientprotocol.data_pb2.EffectData] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", b"abilities", "buffs", b"buffs", "effects", b"effects", "units", b"units", "upgrades", b"upgrades" + ], + ) -> None: ... + +global___ResponseData = ResponseData + +@typing.final +class RequestSaveReplay(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestSaveReplay = RequestSaveReplay + +@typing.final +class ResponseSaveReplay(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATA_FIELD_NUMBER: builtins.int + data: builtins.bytes + def __init__(self, *, data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["data", b"data"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["data", b"data"]) -> None: ... + +global___ResponseSaveReplay = ResponseSaveReplay + +@typing.final +class RequestReplayInfo(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLAY_PATH_FIELD_NUMBER: builtins.int + REPLAY_DATA_FIELD_NUMBER: builtins.int + DOWNLOAD_DATA_FIELD_NUMBER: builtins.int + replay_path: builtins.str + """Limitation: might fail if the replay file is currently loaded.""" + replay_data: builtins.bytes + download_data: builtins.bool + """Ensure the data and binary are downloaded if this is an old version replay.""" + def __init__( + self, + *, + replay_path: builtins.str | None = ..., + replay_data: builtins.bytes | None = ..., + download_data: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "download_data", b"download_data", "replay", b"replay", "replay_data", b"replay_data", "replay_path", b"replay_path" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "download_data", b"download_data", "replay", b"replay", "replay_data", b"replay_data", "replay_path", b"replay_path" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["replay", b"replay"] + ) -> typing.Literal["replay_path", "replay_data"] | None: ... + +global___RequestReplayInfo = RequestReplayInfo + +@typing.final +class PlayerInfoExtra(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_INFO_FIELD_NUMBER: builtins.int + PLAYER_RESULT_FIELD_NUMBER: builtins.int + PLAYER_MMR_FIELD_NUMBER: builtins.int + PLAYER_APM_FIELD_NUMBER: builtins.int + player_mmr: builtins.int + player_apm: builtins.int + @property + def player_info(self) -> global___PlayerInfo: ... + @property + def player_result(self) -> global___PlayerResult: ... + def __init__( + self, + *, + player_info: global___PlayerInfo | None = ..., + player_result: global___PlayerResult | None = ..., + player_mmr: builtins.int | None = ..., + player_apm: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "player_apm", + b"player_apm", + "player_info", + b"player_info", + "player_mmr", + b"player_mmr", + "player_result", + b"player_result", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "player_apm", + b"player_apm", + "player_info", + b"player_info", + "player_mmr", + b"player_mmr", + "player_result", + b"player_result", + ], + ) -> None: ... + +global___PlayerInfoExtra = PlayerInfoExtra + +@typing.final +class ResponseReplayInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseReplayInfo._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + MissingReplay: ResponseReplayInfo._Error.ValueType # 1 + InvalidReplayPath: ResponseReplayInfo._Error.ValueType # 2 + InvalidReplayData: ResponseReplayInfo._Error.ValueType # 3 + ParsingError: ResponseReplayInfo._Error.ValueType # 4 + DownloadError: ResponseReplayInfo._Error.ValueType # 5 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + MissingReplay: ResponseReplayInfo.Error.ValueType # 1 + InvalidReplayPath: ResponseReplayInfo.Error.ValueType # 2 + InvalidReplayData: ResponseReplayInfo.Error.ValueType # 3 + ParsingError: ResponseReplayInfo.Error.ValueType # 4 + DownloadError: ResponseReplayInfo.Error.ValueType # 5 + + MAP_NAME_FIELD_NUMBER: builtins.int + LOCAL_MAP_PATH_FIELD_NUMBER: builtins.int + PLAYER_INFO_FIELD_NUMBER: builtins.int + GAME_DURATION_LOOPS_FIELD_NUMBER: builtins.int + GAME_DURATION_SECONDS_FIELD_NUMBER: builtins.int + GAME_VERSION_FIELD_NUMBER: builtins.int + DATA_VERSION_FIELD_NUMBER: builtins.int + DATA_BUILD_FIELD_NUMBER: builtins.int + BASE_BUILD_FIELD_NUMBER: builtins.int + ERROR_FIELD_NUMBER: builtins.int + ERROR_DETAILS_FIELD_NUMBER: builtins.int + map_name: builtins.str + local_map_path: builtins.str + game_duration_loops: builtins.int + game_duration_seconds: builtins.float + game_version: builtins.str + data_version: builtins.str + data_build: builtins.int + base_build: builtins.int + error: global___ResponseReplayInfo.Error.ValueType + error_details: builtins.str + @property + def player_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PlayerInfoExtra]: ... + def __init__( + self, + *, + map_name: builtins.str | None = ..., + local_map_path: builtins.str | None = ..., + player_info: collections.abc.Iterable[global___PlayerInfoExtra] | None = ..., + game_duration_loops: builtins.int | None = ..., + game_duration_seconds: builtins.float | None = ..., + game_version: builtins.str | None = ..., + data_version: builtins.str | None = ..., + data_build: builtins.int | None = ..., + base_build: builtins.int | None = ..., + error: global___ResponseReplayInfo.Error.ValueType | None = ..., + error_details: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "error", + b"error", + "error_details", + b"error_details", + "game_duration_loops", + b"game_duration_loops", + "game_duration_seconds", + b"game_duration_seconds", + "game_version", + b"game_version", + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "error", + b"error", + "error_details", + b"error_details", + "game_duration_loops", + b"game_duration_loops", + "game_duration_seconds", + b"game_duration_seconds", + "game_version", + b"game_version", + "local_map_path", + b"local_map_path", + "map_name", + b"map_name", + "player_info", + b"player_info", + ], + ) -> None: ... + +global___ResponseReplayInfo = ResponseReplayInfo + +@typing.final +class RequestAvailableMaps(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestAvailableMaps = RequestAvailableMaps + +@typing.final +class ResponseAvailableMaps(google.protobuf.message.Message): + """This will only contain locally cached BattleNet maps. + To download all ladder maps, log in and queue into a ladder match. + To download any other map, play a custom game on that map. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOCAL_MAP_PATHS_FIELD_NUMBER: builtins.int + BATTLENET_MAP_NAMES_FIELD_NUMBER: builtins.int + @property + def local_map_paths(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """All the maps in the "Maps/" directory.""" + + @property + def battlenet_map_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """All the maps in the BattleNet cache.""" + + def __init__( + self, + *, + local_map_paths: collections.abc.Iterable[builtins.str] | None = ..., + battlenet_map_names: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["battlenet_map_names", b"battlenet_map_names", "local_map_paths", b"local_map_paths"] + ) -> None: ... + +global___ResponseAvailableMaps = ResponseAvailableMaps + +@typing.final +class RequestSaveMap(google.protobuf.message.Message): + """----------------------------------------------------------------------------- + Copies map data into the path specified. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_PATH_FIELD_NUMBER: builtins.int + MAP_DATA_FIELD_NUMBER: builtins.int + map_path: builtins.str + """Path the game process will write to, relative to the temp directory. (260 character max)""" + map_data: builtins.bytes + """Binary map data of a .SC2Map.""" + def __init__(self, *, map_path: builtins.str | None = ..., map_data: builtins.bytes | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map_data", b"map_data", "map_path", b"map_path"]) -> None: ... + +global___RequestSaveMap = RequestSaveMap + +@typing.final +class ResponseSaveMap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Error: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ErrorEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ResponseSaveMap._Error.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + InvalidMapData: ResponseSaveMap._Error.ValueType # 1 + + class Error(_Error, metaclass=_ErrorEnumTypeWrapper): ... + InvalidMapData: ResponseSaveMap.Error.ValueType # 1 + + ERROR_FIELD_NUMBER: builtins.int + error: global___ResponseSaveMap.Error.ValueType + def __init__(self, *, error: global___ResponseSaveMap.Error.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["error", b"error"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["error", b"error"]) -> None: ... + +global___ResponseSaveMap = ResponseSaveMap + +@typing.final +class RequestPing(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___RequestPing = RequestPing + +@typing.final +class ResponsePing(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_VERSION_FIELD_NUMBER: builtins.int + DATA_VERSION_FIELD_NUMBER: builtins.int + DATA_BUILD_FIELD_NUMBER: builtins.int + BASE_BUILD_FIELD_NUMBER: builtins.int + game_version: builtins.str + data_version: builtins.str + data_build: builtins.int + base_build: builtins.int + def __init__( + self, + *, + game_version: builtins.str | None = ..., + data_version: builtins.str | None = ..., + data_build: builtins.int | None = ..., + base_build: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "game_version", + b"game_version", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_build", + b"base_build", + "data_build", + b"data_build", + "data_version", + b"data_version", + "game_version", + b"game_version", + ], + ) -> None: ... + +global___ResponsePing = ResponsePing + +@typing.final +class RequestDebug(google.protobuf.message.Message): + """-----------------------------------------------------------------------------""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEBUG_FIELD_NUMBER: builtins.int + @property + def debug( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.debug_pb2.DebugCommand]: ... + def __init__(self, *, debug: collections.abc.Iterable[s2clientprotocol.debug_pb2.DebugCommand] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["debug", b"debug"]) -> None: ... + +global___RequestDebug = RequestDebug + +@typing.final +class ResponseDebug(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ResponseDebug = ResponseDebug + +@typing.final +class PlayerSetup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TYPE_FIELD_NUMBER: builtins.int + RACE_FIELD_NUMBER: builtins.int + DIFFICULTY_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + AI_BUILD_FIELD_NUMBER: builtins.int + type: global___PlayerType.ValueType + race: s2clientprotocol.common_pb2.Race.ValueType + """Only used for a computer player.""" + difficulty: global___Difficulty.ValueType + player_name: builtins.str + ai_build: global___AIBuild.ValueType + def __init__( + self, + *, + type: global___PlayerType.ValueType | None = ..., + race: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + difficulty: global___Difficulty.ValueType | None = ..., + player_name: builtins.str | None = ..., + ai_build: global___AIBuild.ValueType | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ai_build", b"ai_build", "difficulty", b"difficulty", "player_name", b"player_name", "race", b"race", "type", b"type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ai_build", b"ai_build", "difficulty", b"difficulty", "player_name", b"player_name", "race", b"race", "type", b"type" + ], + ) -> None: ... + +global___PlayerSetup = PlayerSetup + +@typing.final +class SpatialCameraSetup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RESOLUTION_FIELD_NUMBER: builtins.int + MINIMAP_RESOLUTION_FIELD_NUMBER: builtins.int + WIDTH_FIELD_NUMBER: builtins.int + CROP_TO_PLAYABLE_AREA_FIELD_NUMBER: builtins.int + ALLOW_CHEATING_LAYERS_FIELD_NUMBER: builtins.int + width: builtins.float + """Below are only relevant for feature layers. + Set the screen camera width in world units. + """ + crop_to_playable_area: builtins.bool + """Crop minimap to the playable area.""" + allow_cheating_layers: builtins.bool + """Return unit_type on the minimap, and potentially other cheating layers.""" + @property + def resolution(self) -> s2clientprotocol.common_pb2.Size2DI: ... + @property + def minimap_resolution(self) -> s2clientprotocol.common_pb2.Size2DI: ... + def __init__( + self, + *, + resolution: s2clientprotocol.common_pb2.Size2DI | None = ..., + minimap_resolution: s2clientprotocol.common_pb2.Size2DI | None = ..., + width: builtins.float | None = ..., + crop_to_playable_area: builtins.bool | None = ..., + allow_cheating_layers: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "allow_cheating_layers", + b"allow_cheating_layers", + "crop_to_playable_area", + b"crop_to_playable_area", + "minimap_resolution", + b"minimap_resolution", + "resolution", + b"resolution", + "width", + b"width", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allow_cheating_layers", + b"allow_cheating_layers", + "crop_to_playable_area", + b"crop_to_playable_area", + "minimap_resolution", + b"minimap_resolution", + "resolution", + b"resolution", + "width", + b"width", + ], + ) -> None: ... + +global___SpatialCameraSetup = SpatialCameraSetup + +@typing.final +class InterfaceOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RAW_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + FEATURE_LAYER_FIELD_NUMBER: builtins.int + RENDER_FIELD_NUMBER: builtins.int + SHOW_CLOAKED_FIELD_NUMBER: builtins.int + SHOW_BURROWED_SHADOWS_FIELD_NUMBER: builtins.int + SHOW_PLACEHOLDERS_FIELD_NUMBER: builtins.int + RAW_AFFECTS_SELECTION_FIELD_NUMBER: builtins.int + RAW_CROP_TO_PLAYABLE_AREA_FIELD_NUMBER: builtins.int + raw: builtins.bool + """Interface options""" + score: builtins.bool + show_cloaked: builtins.bool + """By default cloaked units are completely hidden. This shows some details.""" + show_burrowed_shadows: builtins.bool + """By default burrowed units are completely hidden. This shows some details for those that produce a shadow.""" + show_placeholders: builtins.bool + """Return placeholder units (buildings to be constructed), both for raw and feature layers.""" + raw_affects_selection: builtins.bool + """By default raw actions select, act and revert the selection. This is useful + if you're playing simultaneously with the agent so it doesn't steal your + selection. This inflates APM (due to deselect) and makes the actions hard + to follow in a replay. Setting this to true will cause raw actions to do + select, act, but not revert the selection. + """ + raw_crop_to_playable_area: builtins.bool + """Changes the coordinates in raw.proto to be relative to the playable area. + The map_size and playable_area will be the diagonal of the real playable area. + """ + @property + def feature_layer(self) -> global___SpatialCameraSetup: + """Omit to disable.""" + + @property + def render(self) -> global___SpatialCameraSetup: + """Omit to disable.""" + + def __init__( + self, + *, + raw: builtins.bool | None = ..., + score: builtins.bool | None = ..., + feature_layer: global___SpatialCameraSetup | None = ..., + render: global___SpatialCameraSetup | None = ..., + show_cloaked: builtins.bool | None = ..., + show_burrowed_shadows: builtins.bool | None = ..., + show_placeholders: builtins.bool | None = ..., + raw_affects_selection: builtins.bool | None = ..., + raw_crop_to_playable_area: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "feature_layer", + b"feature_layer", + "raw", + b"raw", + "raw_affects_selection", + b"raw_affects_selection", + "raw_crop_to_playable_area", + b"raw_crop_to_playable_area", + "render", + b"render", + "score", + b"score", + "show_burrowed_shadows", + b"show_burrowed_shadows", + "show_cloaked", + b"show_cloaked", + "show_placeholders", + b"show_placeholders", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "feature_layer", + b"feature_layer", + "raw", + b"raw", + "raw_affects_selection", + b"raw_affects_selection", + "raw_crop_to_playable_area", + b"raw_crop_to_playable_area", + "render", + b"render", + "score", + b"score", + "show_burrowed_shadows", + b"show_burrowed_shadows", + "show_cloaked", + b"show_cloaked", + "show_placeholders", + b"show_placeholders", + ], + ) -> None: ... + +global___InterfaceOptions = InterfaceOptions + +@typing.final +class PlayerInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + RACE_REQUESTED_FIELD_NUMBER: builtins.int + RACE_ACTUAL_FIELD_NUMBER: builtins.int + DIFFICULTY_FIELD_NUMBER: builtins.int + AI_BUILD_FIELD_NUMBER: builtins.int + PLAYER_NAME_FIELD_NUMBER: builtins.int + player_id: builtins.int + """Identifier that will be used to reference this player. + SC2 will always assign playerIds starting from 1 in standard Melee maps. This may not be true in custom maps. + """ + type: global___PlayerType.ValueType + race_requested: s2clientprotocol.common_pb2.Race.ValueType + race_actual: s2clientprotocol.common_pb2.Race.ValueType + """Only populated for your player or when watching replay""" + difficulty: global___Difficulty.ValueType + ai_build: global___AIBuild.ValueType + player_name: builtins.str + def __init__( + self, + *, + player_id: builtins.int | None = ..., + type: global___PlayerType.ValueType | None = ..., + race_requested: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + race_actual: s2clientprotocol.common_pb2.Race.ValueType | None = ..., + difficulty: global___Difficulty.ValueType | None = ..., + ai_build: global___AIBuild.ValueType | None = ..., + player_name: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ai_build", + b"ai_build", + "difficulty", + b"difficulty", + "player_id", + b"player_id", + "player_name", + b"player_name", + "race_actual", + b"race_actual", + "race_requested", + b"race_requested", + "type", + b"type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ai_build", + b"ai_build", + "difficulty", + b"difficulty", + "player_id", + b"player_id", + "player_name", + b"player_name", + "race_actual", + b"race_actual", + "race_requested", + b"race_requested", + "type", + b"type", + ], + ) -> None: ... + +global___PlayerInfo = PlayerInfo + +@typing.final +class PlayerCommon(google.protobuf.message.Message): + """ + During Game + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + MINERALS_FIELD_NUMBER: builtins.int + VESPENE_FIELD_NUMBER: builtins.int + FOOD_CAP_FIELD_NUMBER: builtins.int + FOOD_USED_FIELD_NUMBER: builtins.int + FOOD_ARMY_FIELD_NUMBER: builtins.int + FOOD_WORKERS_FIELD_NUMBER: builtins.int + IDLE_WORKER_COUNT_FIELD_NUMBER: builtins.int + ARMY_COUNT_FIELD_NUMBER: builtins.int + WARP_GATE_COUNT_FIELD_NUMBER: builtins.int + LARVA_COUNT_FIELD_NUMBER: builtins.int + player_id: builtins.int + minerals: builtins.int + vespene: builtins.int + food_cap: builtins.int + food_used: builtins.int + food_army: builtins.int + food_workers: builtins.int + idle_worker_count: builtins.int + army_count: builtins.int + warp_gate_count: builtins.int + larva_count: builtins.int + def __init__( + self, + *, + player_id: builtins.int | None = ..., + minerals: builtins.int | None = ..., + vespene: builtins.int | None = ..., + food_cap: builtins.int | None = ..., + food_used: builtins.int | None = ..., + food_army: builtins.int | None = ..., + food_workers: builtins.int | None = ..., + idle_worker_count: builtins.int | None = ..., + army_count: builtins.int | None = ..., + warp_gate_count: builtins.int | None = ..., + larva_count: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "army_count", + b"army_count", + "food_army", + b"food_army", + "food_cap", + b"food_cap", + "food_used", + b"food_used", + "food_workers", + b"food_workers", + "idle_worker_count", + b"idle_worker_count", + "larva_count", + b"larva_count", + "minerals", + b"minerals", + "player_id", + b"player_id", + "vespene", + b"vespene", + "warp_gate_count", + b"warp_gate_count", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "army_count", + b"army_count", + "food_army", + b"food_army", + "food_cap", + b"food_cap", + "food_used", + b"food_used", + "food_workers", + b"food_workers", + "idle_worker_count", + b"idle_worker_count", + "larva_count", + b"larva_count", + "minerals", + b"minerals", + "player_id", + b"player_id", + "vespene", + b"vespene", + "warp_gate_count", + b"warp_gate_count", + ], + ) -> None: ... + +global___PlayerCommon = PlayerCommon + +@typing.final +class Observation(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GAME_LOOP_FIELD_NUMBER: builtins.int + PLAYER_COMMON_FIELD_NUMBER: builtins.int + ALERTS_FIELD_NUMBER: builtins.int + ABILITIES_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + RAW_DATA_FIELD_NUMBER: builtins.int + FEATURE_LAYER_DATA_FIELD_NUMBER: builtins.int + RENDER_DATA_FIELD_NUMBER: builtins.int + UI_DATA_FIELD_NUMBER: builtins.int + game_loop: builtins.int + @property + def player_common(self) -> global___PlayerCommon: ... + @property + def alerts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___Alert.ValueType]: ... + @property + def abilities( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.AvailableAbility]: + """Abilities available in the selection. Enabled if in this list, disabled otherwise.""" + + @property + def score(self) -> s2clientprotocol.score_pb2.Score: ... + @property + def raw_data(self) -> s2clientprotocol.raw_pb2.ObservationRaw: + """Populated if Raw interface is enabled.""" + + @property + def feature_layer_data(self) -> s2clientprotocol.spatial_pb2.ObservationFeatureLayer: + """Populated if Feature Layer interface is enabled.""" + + @property + def render_data(self) -> s2clientprotocol.spatial_pb2.ObservationRender: + """Populated if Render interface is enabled.""" + + @property + def ui_data(self) -> s2clientprotocol.ui_pb2.ObservationUI: + """Populated if Feature Layer or Render interface is enabled.""" + + def __init__( + self, + *, + game_loop: builtins.int | None = ..., + player_common: global___PlayerCommon | None = ..., + alerts: collections.abc.Iterable[global___Alert.ValueType] | None = ..., + abilities: collections.abc.Iterable[s2clientprotocol.common_pb2.AvailableAbility] | None = ..., + score: s2clientprotocol.score_pb2.Score | None = ..., + raw_data: s2clientprotocol.raw_pb2.ObservationRaw | None = ..., + feature_layer_data: s2clientprotocol.spatial_pb2.ObservationFeatureLayer | None = ..., + render_data: s2clientprotocol.spatial_pb2.ObservationRender | None = ..., + ui_data: s2clientprotocol.ui_pb2.ObservationUI | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "feature_layer_data", + b"feature_layer_data", + "game_loop", + b"game_loop", + "player_common", + b"player_common", + "raw_data", + b"raw_data", + "render_data", + b"render_data", + "score", + b"score", + "ui_data", + b"ui_data", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "abilities", + b"abilities", + "alerts", + b"alerts", + "feature_layer_data", + b"feature_layer_data", + "game_loop", + b"game_loop", + "player_common", + b"player_common", + "raw_data", + b"raw_data", + "render_data", + b"render_data", + "score", + b"score", + "ui_data", + b"ui_data", + ], + ) -> None: ... + +global___Observation = Observation + +@typing.final +class Action(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTION_RAW_FIELD_NUMBER: builtins.int + ACTION_FEATURE_LAYER_FIELD_NUMBER: builtins.int + ACTION_RENDER_FIELD_NUMBER: builtins.int + ACTION_UI_FIELD_NUMBER: builtins.int + ACTION_CHAT_FIELD_NUMBER: builtins.int + GAME_LOOP_FIELD_NUMBER: builtins.int + game_loop: builtins.int + """Populated for actions in ResponseObservation. The game loop on which the action was executed.""" + @property + def action_raw(self) -> s2clientprotocol.raw_pb2.ActionRaw: + """Populated if Raw interface is enabled.""" + + @property + def action_feature_layer(self) -> s2clientprotocol.spatial_pb2.ActionSpatial: + """Populated if Feature Layer interface is enabled.""" + + @property + def action_render(self) -> s2clientprotocol.spatial_pb2.ActionSpatial: + """Not implemented. Populated if Render interface is enabled.""" + + @property + def action_ui(self) -> s2clientprotocol.ui_pb2.ActionUI: + """Populated if Feature Layer or Render interface is enabled.""" + + @property + def action_chat(self) -> global___ActionChat: + """Chat messages as a player typing into the chat channel.""" + + def __init__( + self, + *, + action_raw: s2clientprotocol.raw_pb2.ActionRaw | None = ..., + action_feature_layer: s2clientprotocol.spatial_pb2.ActionSpatial | None = ..., + action_render: s2clientprotocol.spatial_pb2.ActionSpatial | None = ..., + action_ui: s2clientprotocol.ui_pb2.ActionUI | None = ..., + action_chat: global___ActionChat | None = ..., + game_loop: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action_chat", + b"action_chat", + "action_feature_layer", + b"action_feature_layer", + "action_raw", + b"action_raw", + "action_render", + b"action_render", + "action_ui", + b"action_ui", + "game_loop", + b"game_loop", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_chat", + b"action_chat", + "action_feature_layer", + b"action_feature_layer", + "action_raw", + b"action_raw", + "action_render", + b"action_render", + "action_ui", + b"action_ui", + "game_loop", + b"game_loop", + ], + ) -> None: ... + +global___Action = Action + +@typing.final +class ActionChat(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Channel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ChannelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionChat._Channel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Broadcast: ActionChat._Channel.ValueType # 1 + Team: ActionChat._Channel.ValueType # 2 + + class Channel(_Channel, metaclass=_ChannelEnumTypeWrapper): ... + Broadcast: ActionChat.Channel.ValueType # 1 + Team: ActionChat.Channel.ValueType # 2 + + CHANNEL_FIELD_NUMBER: builtins.int + MESSAGE_FIELD_NUMBER: builtins.int + channel: global___ActionChat.Channel.ValueType + message: builtins.str + def __init__( + self, *, channel: global___ActionChat.Channel.ValueType | None = ..., message: builtins.str | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["channel", b"channel", "message", b"message"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["channel", b"channel", "message", b"message"]) -> None: ... + +global___ActionChat = ActionChat + +@typing.final +class ActionError(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAG_FIELD_NUMBER: builtins.int + ABILITY_ID_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + unit_tag: builtins.int + """Only populated when using raw interface.""" + ability_id: builtins.int + result: s2clientprotocol.error_pb2.ActionResult.ValueType + def __init__( + self, + *, + unit_tag: builtins.int | None = ..., + ability_id: builtins.int | None = ..., + result: s2clientprotocol.error_pb2.ActionResult.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "result", b"result", "unit_tag", b"unit_tag"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "result", b"result", "unit_tag", b"unit_tag"] + ) -> None: ... + +global___ActionError = ActionError + +@typing.final +class ObserverAction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_PERSPECTIVE_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + CAMERA_FOLLOW_PLAYER_FIELD_NUMBER: builtins.int + CAMERA_FOLLOW_UNITS_FIELD_NUMBER: builtins.int + @property + def player_perspective(self) -> global___ActionObserverPlayerPerspective: + """Not implemented""" + + @property + def camera_move(self) -> global___ActionObserverCameraMove: ... + @property + def camera_follow_player(self) -> global___ActionObserverCameraFollowPlayer: ... + @property + def camera_follow_units(self) -> global___ActionObserverCameraFollowUnits: + """Not implemented""" + + def __init__( + self, + *, + player_perspective: global___ActionObserverPlayerPerspective | None = ..., + camera_move: global___ActionObserverCameraMove | None = ..., + camera_follow_player: global___ActionObserverCameraFollowPlayer | None = ..., + camera_follow_units: global___ActionObserverCameraFollowUnits | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_follow_player", + b"camera_follow_player", + "camera_follow_units", + b"camera_follow_units", + "camera_move", + b"camera_move", + "player_perspective", + b"player_perspective", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_follow_player", + b"camera_follow_player", + "camera_follow_units", + b"camera_follow_units", + "camera_move", + b"camera_move", + "player_perspective", + b"player_perspective", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["player_perspective", "camera_move", "camera_follow_player", "camera_follow_units"] | None: ... + +global___ObserverAction = ObserverAction + +@typing.final +class ActionObserverPlayerPerspective(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + player_id: builtins.int + """0 to observe "Everyone" """ + def __init__(self, *, player_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id"]) -> None: ... + +global___ActionObserverPlayerPerspective = ActionObserverPlayerPerspective + +@typing.final +class ActionObserverCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + WORLD_POS_FIELD_NUMBER: builtins.int + DISTANCE_FIELD_NUMBER: builtins.int + distance: builtins.float + """Distance between camera and terrain. Larger value zooms out camera. + Defaults to standard camera distance if set to 0. + """ + @property + def world_pos(self) -> s2clientprotocol.common_pb2.Point2D: ... + def __init__( + self, *, world_pos: s2clientprotocol.common_pb2.Point2D | None = ..., distance: builtins.float | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["distance", b"distance", "world_pos", b"world_pos"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["distance", b"distance", "world_pos", b"world_pos"]) -> None: ... + +global___ActionObserverCameraMove = ActionObserverCameraMove + +@typing.final +class ActionObserverCameraFollowPlayer(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + player_id: builtins.int + """Not implemented. Value must be [1, 15]""" + def __init__(self, *, player_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id"]) -> None: ... + +global___ActionObserverCameraFollowPlayer = ActionObserverCameraFollowPlayer + +@typing.final +class ActionObserverCameraFollowUnits(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TAGS_FIELD_NUMBER: builtins.int + @property + def unit_tags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, unit_tags: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["unit_tags", b"unit_tags"]) -> None: ... + +global___ActionObserverCameraFollowUnits = ActionObserverCameraFollowUnits + +@typing.final +class PlayerResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PLAYER_ID_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + player_id: builtins.int + result: global___Result.ValueType + def __init__(self, *, player_id: builtins.int | None = ..., result: global___Result.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["player_id", b"player_id", "result", b"result"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["player_id", b"player_id", "result", b"result"]) -> None: ... + +global___PlayerResult = PlayerResult diff --git a/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi new file mode 100644 index 000000000000..611578a5c889 --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/score_pb2.pyi @@ -0,0 +1,406 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Score(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ScoreType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ScoreTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[Score._ScoreType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Curriculum: Score._ScoreType.ValueType # 1 + """map generated score (from curriculum maps with special scoring)""" + Melee: Score._ScoreType.ValueType # 2 + """summation of in-progress and current units/buildings value + minerals + vespene""" + + class ScoreType(_ScoreType, metaclass=_ScoreTypeEnumTypeWrapper): ... + Curriculum: Score.ScoreType.ValueType # 1 + """map generated score (from curriculum maps with special scoring)""" + Melee: Score.ScoreType.ValueType # 2 + """summation of in-progress and current units/buildings value + minerals + vespene""" + + SCORE_TYPE_FIELD_NUMBER: builtins.int + SCORE_FIELD_NUMBER: builtins.int + SCORE_DETAILS_FIELD_NUMBER: builtins.int + score_type: global___Score.ScoreType.ValueType + score: builtins.int + """Note: check score_type to know whether this is a melee score or curriculum score""" + @property + def score_details(self) -> global___ScoreDetails: ... + def __init__( + self, + *, + score_type: global___Score.ScoreType.ValueType | None = ..., + score: builtins.int | None = ..., + score_details: global___ScoreDetails | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["score", b"score", "score_details", b"score_details", "score_type", b"score_type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["score", b"score", "score_details", b"score_details", "score_type", b"score_type"] + ) -> None: ... + +global___Score = Score + +@typing.final +class CategoryScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NONE_FIELD_NUMBER: builtins.int + ARMY_FIELD_NUMBER: builtins.int + ECONOMY_FIELD_NUMBER: builtins.int + TECHNOLOGY_FIELD_NUMBER: builtins.int + UPGRADE_FIELD_NUMBER: builtins.int + none: builtins.float + """Used when no other category is configured in game data""" + army: builtins.float + economy: builtins.float + technology: builtins.float + upgrade: builtins.float + def __init__( + self, + *, + none: builtins.float | None = ..., + army: builtins.float | None = ..., + economy: builtins.float | None = ..., + technology: builtins.float | None = ..., + upgrade: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "army", b"army", "economy", b"economy", "none", b"none", "technology", b"technology", "upgrade", b"upgrade" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "army", b"army", "economy", b"economy", "none", b"none", "technology", b"technology", "upgrade", b"upgrade" + ], + ) -> None: ... + +global___CategoryScoreDetails = CategoryScoreDetails + +@typing.final +class VitalScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LIFE_FIELD_NUMBER: builtins.int + SHIELDS_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + life: builtins.float + shields: builtins.float + energy: builtins.float + def __init__( + self, *, life: builtins.float | None = ..., shields: builtins.float | None = ..., energy: builtins.float | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["energy", b"energy", "life", b"life", "shields", b"shields"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["energy", b"energy", "life", b"life", "shields", b"shields"]) -> None: ... + +global___VitalScoreDetails = VitalScoreDetails + +@typing.final +class ScoreDetails(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + IDLE_PRODUCTION_TIME_FIELD_NUMBER: builtins.int + IDLE_WORKER_TIME_FIELD_NUMBER: builtins.int + TOTAL_VALUE_UNITS_FIELD_NUMBER: builtins.int + TOTAL_VALUE_STRUCTURES_FIELD_NUMBER: builtins.int + KILLED_VALUE_UNITS_FIELD_NUMBER: builtins.int + KILLED_VALUE_STRUCTURES_FIELD_NUMBER: builtins.int + COLLECTED_MINERALS_FIELD_NUMBER: builtins.int + COLLECTED_VESPENE_FIELD_NUMBER: builtins.int + COLLECTION_RATE_MINERALS_FIELD_NUMBER: builtins.int + COLLECTION_RATE_VESPENE_FIELD_NUMBER: builtins.int + SPENT_MINERALS_FIELD_NUMBER: builtins.int + SPENT_VESPENE_FIELD_NUMBER: builtins.int + FOOD_USED_FIELD_NUMBER: builtins.int + KILLED_MINERALS_FIELD_NUMBER: builtins.int + KILLED_VESPENE_FIELD_NUMBER: builtins.int + LOST_MINERALS_FIELD_NUMBER: builtins.int + LOST_VESPENE_FIELD_NUMBER: builtins.int + FRIENDLY_FIRE_MINERALS_FIELD_NUMBER: builtins.int + FRIENDLY_FIRE_VESPENE_FIELD_NUMBER: builtins.int + USED_MINERALS_FIELD_NUMBER: builtins.int + USED_VESPENE_FIELD_NUMBER: builtins.int + TOTAL_USED_MINERALS_FIELD_NUMBER: builtins.int + TOTAL_USED_VESPENE_FIELD_NUMBER: builtins.int + TOTAL_DAMAGE_DEALT_FIELD_NUMBER: builtins.int + TOTAL_DAMAGE_TAKEN_FIELD_NUMBER: builtins.int + TOTAL_HEALED_FIELD_NUMBER: builtins.int + CURRENT_APM_FIELD_NUMBER: builtins.int + CURRENT_EFFECTIVE_APM_FIELD_NUMBER: builtins.int + idle_production_time: builtins.float + """Sum of time any available structure able to produce a unit is not. The time stacks, as in, three idle barracks will increase idle_production_time three times quicker than just one.""" + idle_worker_time: builtins.float + """Sum of time any worker is not mining. Note a worker building is not idle and three idle workers will increase this value three times quicker than just one.""" + total_value_units: builtins.float + """Sum of minerals and vespene spent on completed units.""" + total_value_structures: builtins.float + """Sum of minerals and vespene spent on completed structures.""" + killed_value_units: builtins.float + """Sum of minerals and vespene of units, belonging to the opponent, that the player has destroyed.""" + killed_value_structures: builtins.float + """Sum of minerals and vespene of structures, belonging to the opponent, that the player has destroyed.""" + collected_minerals: builtins.float + """Sum of minerals collected by the player.""" + collected_vespene: builtins.float + """Sum of vespene collected by the player.""" + collection_rate_minerals: builtins.float + """Estimated income of minerals over the next minute based on the players current income. The unit is minerals per minute.""" + collection_rate_vespene: builtins.float + """Estimated income of vespene over the next minute based on the players current income. The unit is vespene per minute.""" + spent_minerals: builtins.float + """Sum of spent minerals at the moment it is spent. For example, this number is incremented by 50 the moment an scv is queued in a command center. It is decremented by 50 if that unit is canceled.""" + spent_vespene: builtins.float + """Sum of spent vespene at the moment it is spent. For example, this number is incremented by 50 when a reaper is queued but decremented by 50 if it is canceled.""" + current_apm: builtins.float + """Recent raw APM.""" + current_effective_apm: builtins.float + """Recent effective APM.""" + @property + def food_used(self) -> global___CategoryScoreDetails: + """The following entries contains floating point values for the following catgories: + none - There is no category defined in game data. + army - This category includes all military units but not workers. + economy - This category contains town halls, supply structures, vespene buildings and workers. + technology - This category is any structure that produces units or upgrades, Barracks and Engineering Bays both fall in this category, for example. + upgrade - This category is upgrades such as warp gate or weapons upgrades. + + Sum of food, or supply, utilized in the categories above. + """ + + @property + def killed_minerals(self) -> global___CategoryScoreDetails: + """Sum of enemies catagories destroyed in minerals.""" + + @property + def killed_vespene(self) -> global___CategoryScoreDetails: + """Sum of enemies catagories destroyed in vespene.""" + + @property + def lost_minerals(self) -> global___CategoryScoreDetails: + """Sum of lost minerals for the player in each category.""" + + @property + def lost_vespene(self) -> global___CategoryScoreDetails: + """Sum of lost vespene for the player in each category.""" + + @property + def friendly_fire_minerals(self) -> global___CategoryScoreDetails: + """Sum of the lost minerals via destroying the players own units/buildings.""" + + @property + def friendly_fire_vespene(self) -> global___CategoryScoreDetails: + """Sum of the lost vespene via destroying the players own units/buildings.""" + + @property + def used_minerals(self) -> global___CategoryScoreDetails: + """Sum of used minerals for the player in each category for each existing unit or upgrade. Therefore if a unit died worth 50 mierals this number will be decremented by 50.""" + + @property + def used_vespene(self) -> global___CategoryScoreDetails: + """Sum of used vespene for the player in each category. Therefore if a unit died worth 50 vespene this number will be decremented by 50.""" + + @property + def total_used_minerals(self) -> global___CategoryScoreDetails: + """Sum of used minerals throughout the entire game for each category. Unliked used_minerals, this value is never decremented.""" + + @property + def total_used_vespene(self) -> global___CategoryScoreDetails: + """Sum of used vespene throughout the entire game for each category. Unliked used_vespene, this value is never decremented.""" + + @property + def total_damage_dealt(self) -> global___VitalScoreDetails: + """Sum of damage dealt to the player's opponent for each category.""" + + @property + def total_damage_taken(self) -> global___VitalScoreDetails: + """Sum of damage taken by the player for each category.""" + + @property + def total_healed(self) -> global___VitalScoreDetails: + """Sum of health healed by the player. Note that technology can be healed (by queens) or repaired (by scvs).""" + + def __init__( + self, + *, + idle_production_time: builtins.float | None = ..., + idle_worker_time: builtins.float | None = ..., + total_value_units: builtins.float | None = ..., + total_value_structures: builtins.float | None = ..., + killed_value_units: builtins.float | None = ..., + killed_value_structures: builtins.float | None = ..., + collected_minerals: builtins.float | None = ..., + collected_vespene: builtins.float | None = ..., + collection_rate_minerals: builtins.float | None = ..., + collection_rate_vespene: builtins.float | None = ..., + spent_minerals: builtins.float | None = ..., + spent_vespene: builtins.float | None = ..., + food_used: global___CategoryScoreDetails | None = ..., + killed_minerals: global___CategoryScoreDetails | None = ..., + killed_vespene: global___CategoryScoreDetails | None = ..., + lost_minerals: global___CategoryScoreDetails | None = ..., + lost_vespene: global___CategoryScoreDetails | None = ..., + friendly_fire_minerals: global___CategoryScoreDetails | None = ..., + friendly_fire_vespene: global___CategoryScoreDetails | None = ..., + used_minerals: global___CategoryScoreDetails | None = ..., + used_vespene: global___CategoryScoreDetails | None = ..., + total_used_minerals: global___CategoryScoreDetails | None = ..., + total_used_vespene: global___CategoryScoreDetails | None = ..., + total_damage_dealt: global___VitalScoreDetails | None = ..., + total_damage_taken: global___VitalScoreDetails | None = ..., + total_healed: global___VitalScoreDetails | None = ..., + current_apm: builtins.float | None = ..., + current_effective_apm: builtins.float | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "collected_minerals", + b"collected_minerals", + "collected_vespene", + b"collected_vespene", + "collection_rate_minerals", + b"collection_rate_minerals", + "collection_rate_vespene", + b"collection_rate_vespene", + "current_apm", + b"current_apm", + "current_effective_apm", + b"current_effective_apm", + "food_used", + b"food_used", + "friendly_fire_minerals", + b"friendly_fire_minerals", + "friendly_fire_vespene", + b"friendly_fire_vespene", + "idle_production_time", + b"idle_production_time", + "idle_worker_time", + b"idle_worker_time", + "killed_minerals", + b"killed_minerals", + "killed_value_structures", + b"killed_value_structures", + "killed_value_units", + b"killed_value_units", + "killed_vespene", + b"killed_vespene", + "lost_minerals", + b"lost_minerals", + "lost_vespene", + b"lost_vespene", + "spent_minerals", + b"spent_minerals", + "spent_vespene", + b"spent_vespene", + "total_damage_dealt", + b"total_damage_dealt", + "total_damage_taken", + b"total_damage_taken", + "total_healed", + b"total_healed", + "total_used_minerals", + b"total_used_minerals", + "total_used_vespene", + b"total_used_vespene", + "total_value_structures", + b"total_value_structures", + "total_value_units", + b"total_value_units", + "used_minerals", + b"used_minerals", + "used_vespene", + b"used_vespene", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "collected_minerals", + b"collected_minerals", + "collected_vespene", + b"collected_vespene", + "collection_rate_minerals", + b"collection_rate_minerals", + "collection_rate_vespene", + b"collection_rate_vespene", + "current_apm", + b"current_apm", + "current_effective_apm", + b"current_effective_apm", + "food_used", + b"food_used", + "friendly_fire_minerals", + b"friendly_fire_minerals", + "friendly_fire_vespene", + b"friendly_fire_vespene", + "idle_production_time", + b"idle_production_time", + "idle_worker_time", + b"idle_worker_time", + "killed_minerals", + b"killed_minerals", + "killed_value_structures", + b"killed_value_structures", + "killed_value_units", + b"killed_value_units", + "killed_vespene", + b"killed_vespene", + "lost_minerals", + b"lost_minerals", + "lost_vespene", + b"lost_vespene", + "spent_minerals", + b"spent_minerals", + "spent_vespene", + b"spent_vespene", + "total_damage_dealt", + b"total_damage_dealt", + "total_damage_taken", + b"total_damage_taken", + "total_healed", + b"total_healed", + "total_used_minerals", + b"total_used_minerals", + "total_used_vespene", + b"total_used_vespene", + "total_value_structures", + b"total_value_structures", + "total_value_units", + b"total_value_units", + "used_minerals", + b"used_minerals", + "used_vespene", + b"used_vespene", + ], + ) -> None: ... + +global___ScoreDetails = ScoreDetails diff --git a/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi new file mode 100644 index 000000000000..5fd2301ac84b --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/spatial_pb2.pyi @@ -0,0 +1,712 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import s2clientprotocol.common_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ObservationFeatureLayer(google.protobuf.message.Message): + """ + Observation - Feature Layer + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + RENDERS_FIELD_NUMBER: builtins.int + MINIMAP_RENDERS_FIELD_NUMBER: builtins.int + @property + def renders(self) -> global___FeatureLayers: ... + @property + def minimap_renders(self) -> global___FeatureLayersMinimap: ... + def __init__( + self, *, renders: global___FeatureLayers | None = ..., minimap_renders: global___FeatureLayersMinimap | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["minimap_renders", b"minimap_renders", "renders", b"renders"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["minimap_renders", b"minimap_renders", "renders", b"renders"]) -> None: ... + +global___ObservationFeatureLayer = ObservationFeatureLayer + +@typing.final +class FeatureLayers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HEIGHT_MAP_FIELD_NUMBER: builtins.int + VISIBILITY_MAP_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + POWER_FIELD_NUMBER: builtins.int + PLAYER_ID_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + SELECTED_FIELD_NUMBER: builtins.int + UNIT_HIT_POINTS_FIELD_NUMBER: builtins.int + UNIT_HIT_POINTS_RATIO_FIELD_NUMBER: builtins.int + UNIT_ENERGY_FIELD_NUMBER: builtins.int + UNIT_ENERGY_RATIO_FIELD_NUMBER: builtins.int + UNIT_SHIELDS_FIELD_NUMBER: builtins.int + UNIT_SHIELDS_RATIO_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + UNIT_DENSITY_AA_FIELD_NUMBER: builtins.int + UNIT_DENSITY_FIELD_NUMBER: builtins.int + EFFECTS_FIELD_NUMBER: builtins.int + HALLUCINATIONS_FIELD_NUMBER: builtins.int + CLOAKED_FIELD_NUMBER: builtins.int + BLIP_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + BUFF_DURATION_FIELD_NUMBER: builtins.int + ACTIVE_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + BUILDABLE_FIELD_NUMBER: builtins.int + PATHABLE_FIELD_NUMBER: builtins.int + PLACEHOLDER_FIELD_NUMBER: builtins.int + @property + def height_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Terrain height. World space units of [-200, 200] encoded into [0, 255].""" + + @property + def visibility_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. 0=Hidden, 1=Fogged, 2=Visible, 3=FullHidden""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Zerg creep.""" + + @property + def power(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Protoss power.""" + + @property + def player_id(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Participants: [1, 15] Neutral: 16""" + + @property + def unit_type(self) -> s2clientprotocol.common_pb2.ImageData: + """int32. Unique identifier for type of unit.""" + + @property + def selected(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Selected units.""" + + @property + def unit_hit_points(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_hit_points_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current health to max health. [0%, 100%] encoded into [0, 255].""" + + @property + def unit_energy(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_energy_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current energy to max energy. [0%, 100%] encoded into [0, 255].""" + + @property + def unit_shields(self) -> s2clientprotocol.common_pb2.ImageData: + """int32.""" + + @property + def unit_shields_ratio(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of current shields to max shields. [0%, 100%] encoded into [0, 255].""" + + @property + def player_relative(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. See "Alliance" enum in raw.proto. Range: [1, 4]""" + + @property + def unit_density_aa(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Density of units overlapping a pixel, anti-aliased. [0.0, 16.0f] encoded into [0, 255].""" + + @property + def unit_density(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Count of units overlapping a pixel.""" + + @property + def effects(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Visuals of persistent abilities. (eg. Psistorm)""" + + @property + def hallucinations(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a hallucination.""" + + @property + def cloaked(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is cloaked. Hidden units will show up too, but with less details in other layers.""" + + @property + def blip(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a blip.""" + + @property + def buffs(self) -> s2clientprotocol.common_pb2.ImageData: + """int32. One of the buffs applied to this unit. Extras are ignored.""" + + @property + def buff_duration(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Ratio of buff remaining. [0%, 100%] encoded into [0, 255].""" + + @property + def active(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is active.""" + + @property + def build_progress(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. How far along the building is building something. [0%, 100%] encoded into [0, 255].""" + + @property + def buildable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a building can be built here.""" + + @property + def pathable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a unit can walk here.""" + + @property + def placeholder(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether the unit here is a placeholder building to be constructed.""" + + def __init__( + self, + *, + height_map: s2clientprotocol.common_pb2.ImageData | None = ..., + visibility_map: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + power: s2clientprotocol.common_pb2.ImageData | None = ..., + player_id: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_type: s2clientprotocol.common_pb2.ImageData | None = ..., + selected: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_hit_points: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_hit_points_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_energy: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_energy_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_shields: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_shields_ratio: s2clientprotocol.common_pb2.ImageData | None = ..., + player_relative: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_density_aa: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_density: s2clientprotocol.common_pb2.ImageData | None = ..., + effects: s2clientprotocol.common_pb2.ImageData | None = ..., + hallucinations: s2clientprotocol.common_pb2.ImageData | None = ..., + cloaked: s2clientprotocol.common_pb2.ImageData | None = ..., + blip: s2clientprotocol.common_pb2.ImageData | None = ..., + buffs: s2clientprotocol.common_pb2.ImageData | None = ..., + buff_duration: s2clientprotocol.common_pb2.ImageData | None = ..., + active: s2clientprotocol.common_pb2.ImageData | None = ..., + build_progress: s2clientprotocol.common_pb2.ImageData | None = ..., + buildable: s2clientprotocol.common_pb2.ImageData | None = ..., + pathable: s2clientprotocol.common_pb2.ImageData | None = ..., + placeholder: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "active", + b"active", + "blip", + b"blip", + "buff_duration", + b"buff_duration", + "buffs", + b"buffs", + "build_progress", + b"build_progress", + "buildable", + b"buildable", + "cloaked", + b"cloaked", + "creep", + b"creep", + "effects", + b"effects", + "hallucinations", + b"hallucinations", + "height_map", + b"height_map", + "pathable", + b"pathable", + "placeholder", + b"placeholder", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "power", + b"power", + "selected", + b"selected", + "unit_density", + b"unit_density", + "unit_density_aa", + b"unit_density_aa", + "unit_energy", + b"unit_energy", + "unit_energy_ratio", + b"unit_energy_ratio", + "unit_hit_points", + b"unit_hit_points", + "unit_hit_points_ratio", + b"unit_hit_points_ratio", + "unit_shields", + b"unit_shields", + "unit_shields_ratio", + b"unit_shields_ratio", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "active", + b"active", + "blip", + b"blip", + "buff_duration", + b"buff_duration", + "buffs", + b"buffs", + "build_progress", + b"build_progress", + "buildable", + b"buildable", + "cloaked", + b"cloaked", + "creep", + b"creep", + "effects", + b"effects", + "hallucinations", + b"hallucinations", + "height_map", + b"height_map", + "pathable", + b"pathable", + "placeholder", + b"placeholder", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "power", + b"power", + "selected", + b"selected", + "unit_density", + b"unit_density", + "unit_density_aa", + b"unit_density_aa", + "unit_energy", + b"unit_energy", + "unit_energy_ratio", + b"unit_energy_ratio", + "unit_hit_points", + b"unit_hit_points", + "unit_hit_points_ratio", + b"unit_hit_points_ratio", + "unit_shields", + b"unit_shields", + "unit_shields_ratio", + b"unit_shields_ratio", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> None: ... + +global___FeatureLayers = FeatureLayers + +@typing.final +class FeatureLayersMinimap(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HEIGHT_MAP_FIELD_NUMBER: builtins.int + VISIBILITY_MAP_FIELD_NUMBER: builtins.int + CREEP_FIELD_NUMBER: builtins.int + CAMERA_FIELD_NUMBER: builtins.int + PLAYER_ID_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + SELECTED_FIELD_NUMBER: builtins.int + ALERTS_FIELD_NUMBER: builtins.int + BUILDABLE_FIELD_NUMBER: builtins.int + PATHABLE_FIELD_NUMBER: builtins.int + UNIT_TYPE_FIELD_NUMBER: builtins.int + @property + def height_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Terrain height. World space units of [-200, 200] encoded into [0, 255].""" + + @property + def visibility_map(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. 0=Hidden, 1=Fogged, 2=Visible, 3=FullHidden""" + + @property + def creep(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Zerg creep.""" + + @property + def camera(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Area covered by the camera.""" + + @property + def player_id(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. Participants: [1, 15] Neutral: 16""" + + @property + def player_relative(self) -> s2clientprotocol.common_pb2.ImageData: + """uint8. See "Alliance" enum in raw.proto. Range: [1, 4]""" + + @property + def selected(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Selected units.""" + + @property + def alerts(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Shows 'UnitAttacked' alert location.""" + + @property + def buildable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a building can be built here.""" + + @property + def pathable(self) -> s2clientprotocol.common_pb2.ImageData: + """1-bit. Whether a unit can walk here.""" + + @property + def unit_type(self) -> s2clientprotocol.common_pb2.ImageData: + """Cheat layers, enable with SpatialCameraSetup.allow_cheating_layers. + int32. Unique identifier for type of unit. + """ + + def __init__( + self, + *, + height_map: s2clientprotocol.common_pb2.ImageData | None = ..., + visibility_map: s2clientprotocol.common_pb2.ImageData | None = ..., + creep: s2clientprotocol.common_pb2.ImageData | None = ..., + camera: s2clientprotocol.common_pb2.ImageData | None = ..., + player_id: s2clientprotocol.common_pb2.ImageData | None = ..., + player_relative: s2clientprotocol.common_pb2.ImageData | None = ..., + selected: s2clientprotocol.common_pb2.ImageData | None = ..., + alerts: s2clientprotocol.common_pb2.ImageData | None = ..., + buildable: s2clientprotocol.common_pb2.ImageData | None = ..., + pathable: s2clientprotocol.common_pb2.ImageData | None = ..., + unit_type: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "alerts", + b"alerts", + "buildable", + b"buildable", + "camera", + b"camera", + "creep", + b"creep", + "height_map", + b"height_map", + "pathable", + b"pathable", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "selected", + b"selected", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alerts", + b"alerts", + "buildable", + b"buildable", + "camera", + b"camera", + "creep", + b"creep", + "height_map", + b"height_map", + "pathable", + b"pathable", + "player_id", + b"player_id", + "player_relative", + b"player_relative", + "selected", + b"selected", + "unit_type", + b"unit_type", + "visibility_map", + b"visibility_map", + ], + ) -> None: ... + +global___FeatureLayersMinimap = FeatureLayersMinimap + +@typing.final +class ObservationRender(google.protobuf.message.Message): + """ + Observation - Rendered + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAP_FIELD_NUMBER: builtins.int + MINIMAP_FIELD_NUMBER: builtins.int + @property + def map(self) -> s2clientprotocol.common_pb2.ImageData: ... + @property + def minimap(self) -> s2clientprotocol.common_pb2.ImageData: ... + def __init__( + self, + *, + map: s2clientprotocol.common_pb2.ImageData | None = ..., + minimap: s2clientprotocol.common_pb2.ImageData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["map", b"map", "minimap", b"minimap"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["map", b"map", "minimap", b"minimap"]) -> None: ... + +global___ObservationRender = ObservationRender + +@typing.final +class ActionSpatial(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_COMMAND_FIELD_NUMBER: builtins.int + CAMERA_MOVE_FIELD_NUMBER: builtins.int + UNIT_SELECTION_POINT_FIELD_NUMBER: builtins.int + UNIT_SELECTION_RECT_FIELD_NUMBER: builtins.int + @property + def unit_command(self) -> global___ActionSpatialUnitCommand: ... + @property + def camera_move(self) -> global___ActionSpatialCameraMove: ... + @property + def unit_selection_point(self) -> global___ActionSpatialUnitSelectionPoint: ... + @property + def unit_selection_rect(self) -> global___ActionSpatialUnitSelectionRect: ... + def __init__( + self, + *, + unit_command: global___ActionSpatialUnitCommand | None = ..., + camera_move: global___ActionSpatialCameraMove | None = ..., + unit_selection_point: global___ActionSpatialUnitSelectionPoint | None = ..., + unit_selection_rect: global___ActionSpatialUnitSelectionRect | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "unit_command", + b"unit_command", + "unit_selection_point", + b"unit_selection_point", + "unit_selection_rect", + b"unit_selection_rect", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "camera_move", + b"camera_move", + "unit_command", + b"unit_command", + "unit_selection_point", + b"unit_selection_point", + "unit_selection_rect", + b"unit_selection_rect", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> typing.Literal["unit_command", "camera_move", "unit_selection_point", "unit_selection_rect"] | None: ... + +global___ActionSpatial = ActionSpatial + +@typing.final +class ActionSpatialUnitCommand(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + TARGET_SCREEN_COORD_FIELD_NUMBER: builtins.int + TARGET_MINIMAP_COORD_FIELD_NUMBER: builtins.int + QUEUE_COMMAND_FIELD_NUMBER: builtins.int + ability_id: builtins.int + queue_command: builtins.bool + """Equivalent to shift+command.""" + @property + def target_screen_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + @property + def target_minimap_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + def __init__( + self, + *, + ability_id: builtins.int | None = ..., + target_screen_coord: s2clientprotocol.common_pb2.PointI | None = ..., + target_minimap_coord: s2clientprotocol.common_pb2.PointI | None = ..., + queue_command: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_minimap_coord", + b"target_minimap_coord", + "target_screen_coord", + b"target_screen_coord", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "ability_id", + b"ability_id", + "queue_command", + b"queue_command", + "target", + b"target", + "target_minimap_coord", + b"target_minimap_coord", + "target_screen_coord", + b"target_screen_coord", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["target", b"target"] + ) -> typing.Literal["target_screen_coord", "target_minimap_coord"] | None: ... + +global___ActionSpatialUnitCommand = ActionSpatialUnitCommand + +@typing.final +class ActionSpatialCameraMove(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CENTER_MINIMAP_FIELD_NUMBER: builtins.int + @property + def center_minimap(self) -> s2clientprotocol.common_pb2.PointI: + """Simulates a click on the minimap to move the camera.""" + + def __init__(self, *, center_minimap: s2clientprotocol.common_pb2.PointI | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["center_minimap", b"center_minimap"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["center_minimap", b"center_minimap"]) -> None: ... + +global___ActionSpatialCameraMove = ActionSpatialCameraMove + +@typing.final +class ActionSpatialUnitSelectionPoint(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionSpatialUnitSelectionPoint._Type.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Select: ActionSpatialUnitSelectionPoint._Type.ValueType # 1 + """Equivalent to normal click. Changes selection to unit.""" + Toggle: ActionSpatialUnitSelectionPoint._Type.ValueType # 2 + """Equivalent to shift+click. Toggle selection of unit.""" + AllType: ActionSpatialUnitSelectionPoint._Type.ValueType # 3 + """Equivalent to control+click. Selects all units of a given type.""" + AddAllType: ActionSpatialUnitSelectionPoint._Type.ValueType # 4 + """Equivalent to shift+control+click. Selects all units of a given type.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + Select: ActionSpatialUnitSelectionPoint.Type.ValueType # 1 + """Equivalent to normal click. Changes selection to unit.""" + Toggle: ActionSpatialUnitSelectionPoint.Type.ValueType # 2 + """Equivalent to shift+click. Toggle selection of unit.""" + AllType: ActionSpatialUnitSelectionPoint.Type.ValueType # 3 + """Equivalent to control+click. Selects all units of a given type.""" + AddAllType: ActionSpatialUnitSelectionPoint.Type.ValueType # 4 + """Equivalent to shift+control+click. Selects all units of a given type.""" + + SELECTION_SCREEN_COORD_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + type: global___ActionSpatialUnitSelectionPoint.Type.ValueType + @property + def selection_screen_coord(self) -> s2clientprotocol.common_pb2.PointI: ... + def __init__( + self, + *, + selection_screen_coord: s2clientprotocol.common_pb2.PointI | None = ..., + type: global___ActionSpatialUnitSelectionPoint.Type.ValueType | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["selection_screen_coord", b"selection_screen_coord", "type", b"type"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["selection_screen_coord", b"selection_screen_coord", "type", b"type"] + ) -> None: ... + +global___ActionSpatialUnitSelectionPoint = ActionSpatialUnitSelectionPoint + +@typing.final +class ActionSpatialUnitSelectionRect(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_SCREEN_COORD_FIELD_NUMBER: builtins.int + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + """Equivalent to shift+drag. Adds units to selection.""" + @property + def selection_screen_coord( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[s2clientprotocol.common_pb2.RectangleI]: + """Eventually this should not be an array, but a single field (multiple would be cheating).""" + + def __init__( + self, + *, + selection_screen_coord: collections.abc.Iterable[s2clientprotocol.common_pb2.RectangleI] | None = ..., + selection_add: builtins.bool | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["selection_add", b"selection_add", "selection_screen_coord", b"selection_screen_coord"] + ) -> None: ... + +global___ActionSpatialUnitSelectionRect = ActionSpatialUnitSelectionRect diff --git a/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi b/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi new file mode 100644 index 000000000000..2608a8aa142c --- /dev/null +++ b/stubs/s2clientprotocol/s2clientprotocol/ui_pb2.pyi @@ -0,0 +1,681 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ObservationUI(google.protobuf.message.Message): + """ + Observation + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + GROUPS_FIELD_NUMBER: builtins.int + SINGLE_FIELD_NUMBER: builtins.int + MULTI_FIELD_NUMBER: builtins.int + CARGO_FIELD_NUMBER: builtins.int + PRODUCTION_FIELD_NUMBER: builtins.int + @property + def groups(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ControlGroup]: ... + @property + def single(self) -> global___SinglePanel: ... + @property + def multi(self) -> global___MultiPanel: ... + @property + def cargo(self) -> global___CargoPanel: ... + @property + def production(self) -> global___ProductionPanel: ... + def __init__( + self, + *, + groups: collections.abc.Iterable[global___ControlGroup] | None = ..., + single: global___SinglePanel | None = ..., + multi: global___MultiPanel | None = ..., + cargo: global___CargoPanel | None = ..., + production: global___ProductionPanel | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cargo", b"cargo", "multi", b"multi", "panel", b"panel", "production", b"production", "single", b"single" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "cargo", + b"cargo", + "groups", + b"groups", + "multi", + b"multi", + "panel", + b"panel", + "production", + b"production", + "single", + b"single", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["panel", b"panel"] + ) -> typing.Literal["single", "multi", "cargo", "production"] | None: ... + +global___ObservationUI = ObservationUI + +@typing.final +class ControlGroup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTROL_GROUP_INDEX_FIELD_NUMBER: builtins.int + LEADER_UNIT_TYPE_FIELD_NUMBER: builtins.int + COUNT_FIELD_NUMBER: builtins.int + control_group_index: builtins.int + leader_unit_type: builtins.int + count: builtins.int + def __init__( + self, + *, + control_group_index: builtins.int | None = ..., + leader_unit_type: builtins.int | None = ..., + count: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "control_group_index", b"control_group_index", "count", b"count", "leader_unit_type", b"leader_unit_type" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "control_group_index", b"control_group_index", "count", b"count", "leader_unit_type", b"leader_unit_type" + ], + ) -> None: ... + +global___ControlGroup = ControlGroup + +@typing.final +class UnitInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_TYPE_FIELD_NUMBER: builtins.int + PLAYER_RELATIVE_FIELD_NUMBER: builtins.int + HEALTH_FIELD_NUMBER: builtins.int + SHIELDS_FIELD_NUMBER: builtins.int + ENERGY_FIELD_NUMBER: builtins.int + TRANSPORT_SLOTS_TAKEN_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + ADD_ON_FIELD_NUMBER: builtins.int + MAX_HEALTH_FIELD_NUMBER: builtins.int + MAX_SHIELDS_FIELD_NUMBER: builtins.int + MAX_ENERGY_FIELD_NUMBER: builtins.int + unit_type: builtins.int + player_relative: builtins.int + health: builtins.int + shields: builtins.int + energy: builtins.int + transport_slots_taken: builtins.int + build_progress: builtins.float + """Range: [0.0, 1.0]""" + max_health: builtins.int + max_shields: builtins.int + max_energy: builtins.int + @property + def add_on(self) -> global___UnitInfo: ... + def __init__( + self, + *, + unit_type: builtins.int | None = ..., + player_relative: builtins.int | None = ..., + health: builtins.int | None = ..., + shields: builtins.int | None = ..., + energy: builtins.int | None = ..., + transport_slots_taken: builtins.int | None = ..., + build_progress: builtins.float | None = ..., + add_on: global___UnitInfo | None = ..., + max_health: builtins.int | None = ..., + max_shields: builtins.int | None = ..., + max_energy: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "add_on", + b"add_on", + "build_progress", + b"build_progress", + "energy", + b"energy", + "health", + b"health", + "max_energy", + b"max_energy", + "max_health", + b"max_health", + "max_shields", + b"max_shields", + "player_relative", + b"player_relative", + "shields", + b"shields", + "transport_slots_taken", + b"transport_slots_taken", + "unit_type", + b"unit_type", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "add_on", + b"add_on", + "build_progress", + b"build_progress", + "energy", + b"energy", + "health", + b"health", + "max_energy", + b"max_energy", + "max_health", + b"max_health", + "max_shields", + b"max_shields", + "player_relative", + b"player_relative", + "shields", + b"shields", + "transport_slots_taken", + b"transport_slots_taken", + "unit_type", + b"unit_type", + ], + ) -> None: ... + +global___UnitInfo = UnitInfo + +@typing.final +class SinglePanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + ATTACK_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + ARMOR_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + SHIELD_UPGRADE_LEVEL_FIELD_NUMBER: builtins.int + BUFFS_FIELD_NUMBER: builtins.int + attack_upgrade_level: builtins.int + armor_upgrade_level: builtins.int + shield_upgrade_level: builtins.int + @property + def unit(self) -> global___UnitInfo: ... + @property + def buffs(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + attack_upgrade_level: builtins.int | None = ..., + armor_upgrade_level: builtins.int | None = ..., + shield_upgrade_level: builtins.int | None = ..., + buffs: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "armor_upgrade_level", + b"armor_upgrade_level", + "attack_upgrade_level", + b"attack_upgrade_level", + "shield_upgrade_level", + b"shield_upgrade_level", + "unit", + b"unit", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "armor_upgrade_level", + b"armor_upgrade_level", + "attack_upgrade_level", + b"attack_upgrade_level", + "buffs", + b"buffs", + "shield_upgrade_level", + b"shield_upgrade_level", + "unit", + b"unit", + ], + ) -> None: ... + +global___SinglePanel = SinglePanel + +@typing.final +class MultiPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNITS_FIELD_NUMBER: builtins.int + @property + def units(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: ... + def __init__(self, *, units: collections.abc.Iterable[global___UnitInfo] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["units", b"units"]) -> None: ... + +global___MultiPanel = MultiPanel + +@typing.final +class CargoPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + PASSENGERS_FIELD_NUMBER: builtins.int + SLOTS_AVAILABLE_FIELD_NUMBER: builtins.int + slots_available: builtins.int + """TODO: Change to cargo size""" + @property + def unit(self) -> global___UnitInfo: ... + @property + def passengers(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + passengers: collections.abc.Iterable[global___UnitInfo] | None = ..., + slots_available: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["slots_available", b"slots_available", "unit", b"unit"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["passengers", b"passengers", "slots_available", b"slots_available", "unit", b"unit"] + ) -> None: ... + +global___CargoPanel = CargoPanel + +@typing.final +class BuildItem(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + BUILD_PROGRESS_FIELD_NUMBER: builtins.int + ability_id: builtins.int + build_progress: builtins.float + """Range: [0.0, 1.0]""" + def __init__(self, *, ability_id: builtins.int | None = ..., build_progress: builtins.float | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["ability_id", b"ability_id", "build_progress", b"build_progress"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["ability_id", b"ability_id", "build_progress", b"build_progress"] + ) -> None: ... + +global___BuildItem = BuildItem + +@typing.final +class ProductionPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_FIELD_NUMBER: builtins.int + BUILD_QUEUE_FIELD_NUMBER: builtins.int + PRODUCTION_QUEUE_FIELD_NUMBER: builtins.int + @property + def unit(self) -> global___UnitInfo: ... + @property + def build_queue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___UnitInfo]: + """build_queue ONLY gives information about units that are being produced. + Use production_queue instead to see both units being trained as well as research in the queue. + """ + + @property + def production_queue(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BuildItem]: ... + def __init__( + self, + *, + unit: global___UnitInfo | None = ..., + build_queue: collections.abc.Iterable[global___UnitInfo] | None = ..., + production_queue: collections.abc.Iterable[global___BuildItem] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["unit", b"unit"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["build_queue", b"build_queue", "production_queue", b"production_queue", "unit", b"unit"] + ) -> None: ... + +global___ProductionPanel = ProductionPanel + +@typing.final +class ActionUI(google.protobuf.message.Message): + """ + Action + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTROL_GROUP_FIELD_NUMBER: builtins.int + SELECT_ARMY_FIELD_NUMBER: builtins.int + SELECT_WARP_GATES_FIELD_NUMBER: builtins.int + SELECT_LARVA_FIELD_NUMBER: builtins.int + SELECT_IDLE_WORKER_FIELD_NUMBER: builtins.int + MULTI_PANEL_FIELD_NUMBER: builtins.int + CARGO_PANEL_FIELD_NUMBER: builtins.int + PRODUCTION_PANEL_FIELD_NUMBER: builtins.int + TOGGLE_AUTOCAST_FIELD_NUMBER: builtins.int + @property + def control_group(self) -> global___ActionControlGroup: ... + @property + def select_army(self) -> global___ActionSelectArmy: ... + @property + def select_warp_gates(self) -> global___ActionSelectWarpGates: ... + @property + def select_larva(self) -> global___ActionSelectLarva: ... + @property + def select_idle_worker(self) -> global___ActionSelectIdleWorker: ... + @property + def multi_panel(self) -> global___ActionMultiPanel: ... + @property + def cargo_panel(self) -> global___ActionCargoPanelUnload: ... + @property + def production_panel(self) -> global___ActionProductionPanelRemoveFromQueue: ... + @property + def toggle_autocast(self) -> global___ActionToggleAutocast: ... + def __init__( + self, + *, + control_group: global___ActionControlGroup | None = ..., + select_army: global___ActionSelectArmy | None = ..., + select_warp_gates: global___ActionSelectWarpGates | None = ..., + select_larva: global___ActionSelectLarva | None = ..., + select_idle_worker: global___ActionSelectIdleWorker | None = ..., + multi_panel: global___ActionMultiPanel | None = ..., + cargo_panel: global___ActionCargoPanelUnload | None = ..., + production_panel: global___ActionProductionPanelRemoveFromQueue | None = ..., + toggle_autocast: global___ActionToggleAutocast | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "action", + b"action", + "cargo_panel", + b"cargo_panel", + "control_group", + b"control_group", + "multi_panel", + b"multi_panel", + "production_panel", + b"production_panel", + "select_army", + b"select_army", + "select_idle_worker", + b"select_idle_worker", + "select_larva", + b"select_larva", + "select_warp_gates", + b"select_warp_gates", + "toggle_autocast", + b"toggle_autocast", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "action", + b"action", + "cargo_panel", + b"cargo_panel", + "control_group", + b"control_group", + "multi_panel", + b"multi_panel", + "production_panel", + b"production_panel", + "select_army", + b"select_army", + "select_idle_worker", + b"select_idle_worker", + "select_larva", + b"select_larva", + "select_warp_gates", + b"select_warp_gates", + "toggle_autocast", + b"toggle_autocast", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["action", b"action"] + ) -> ( + typing.Literal[ + "control_group", + "select_army", + "select_warp_gates", + "select_larva", + "select_idle_worker", + "multi_panel", + "cargo_panel", + "production_panel", + "toggle_autocast", + ] + | None + ): ... + +global___ActionUI = ActionUI + +@typing.final +class ActionControlGroup(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ControlGroupAction: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ControlGroupActionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionControlGroup._ControlGroupAction.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Recall: ActionControlGroup._ControlGroupAction.ValueType # 1 + """Equivalent to number hotkey. Replaces current selection with control group.""" + Set: ActionControlGroup._ControlGroupAction.ValueType # 2 + """Equivalent to Control + number hotkey. Sets control group to current selection.""" + Append: ActionControlGroup._ControlGroupAction.ValueType # 3 + """Equivalent to Shift + number hotkey. Adds current selection into control group.""" + SetAndSteal: ActionControlGroup._ControlGroupAction.ValueType # 4 + """Equivalent to Control + Alt + number hotkey. Sets control group to current selection. Units are removed from other control groups.""" + AppendAndSteal: ActionControlGroup._ControlGroupAction.ValueType # 5 + """Equivalent to Shift + Alt + number hotkey. Adds current selection into control group. Units are removed from other control groups.""" + + class ControlGroupAction(_ControlGroupAction, metaclass=_ControlGroupActionEnumTypeWrapper): ... + Recall: ActionControlGroup.ControlGroupAction.ValueType # 1 + """Equivalent to number hotkey. Replaces current selection with control group.""" + Set: ActionControlGroup.ControlGroupAction.ValueType # 2 + """Equivalent to Control + number hotkey. Sets control group to current selection.""" + Append: ActionControlGroup.ControlGroupAction.ValueType # 3 + """Equivalent to Shift + number hotkey. Adds current selection into control group.""" + SetAndSteal: ActionControlGroup.ControlGroupAction.ValueType # 4 + """Equivalent to Control + Alt + number hotkey. Sets control group to current selection. Units are removed from other control groups.""" + AppendAndSteal: ActionControlGroup.ControlGroupAction.ValueType # 5 + """Equivalent to Shift + Alt + number hotkey. Adds current selection into control group. Units are removed from other control groups.""" + + ACTION_FIELD_NUMBER: builtins.int + CONTROL_GROUP_INDEX_FIELD_NUMBER: builtins.int + action: global___ActionControlGroup.ControlGroupAction.ValueType + control_group_index: builtins.int + def __init__( + self, + *, + action: global___ActionControlGroup.ControlGroupAction.ValueType | None = ..., + control_group_index: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["action", b"action", "control_group_index", b"control_group_index"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["action", b"action", "control_group_index", b"control_group_index"] + ) -> None: ... + +global___ActionControlGroup = ActionControlGroup + +@typing.final +class ActionSelectArmy(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + def __init__(self, *, selection_add: builtins.bool | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> None: ... + +global___ActionSelectArmy = ActionSelectArmy + +@typing.final +class ActionSelectWarpGates(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SELECTION_ADD_FIELD_NUMBER: builtins.int + selection_add: builtins.bool + def __init__(self, *, selection_add: builtins.bool | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["selection_add", b"selection_add"]) -> None: ... + +global___ActionSelectWarpGates = ActionSelectWarpGates + +@typing.final +class ActionSelectLarva(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + def __init__(self) -> None: ... + +global___ActionSelectLarva = ActionSelectLarva + +@typing.final +class ActionSelectIdleWorker(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionSelectIdleWorker._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + Set: ActionSelectIdleWorker._Type.ValueType # 1 + """Equivalent to click with no modifiers. Replaces selection with single idle worker.""" + Add: ActionSelectIdleWorker._Type.ValueType # 2 + """Equivalent to shift+click. Adds single idle worker to current selection.""" + All: ActionSelectIdleWorker._Type.ValueType # 3 + """Equivalent to control+click. Selects all idle workers.""" + AddAll: ActionSelectIdleWorker._Type.ValueType # 4 + """Equivalent to shift+control+click. Adds all idle workers to current selection.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + Set: ActionSelectIdleWorker.Type.ValueType # 1 + """Equivalent to click with no modifiers. Replaces selection with single idle worker.""" + Add: ActionSelectIdleWorker.Type.ValueType # 2 + """Equivalent to shift+click. Adds single idle worker to current selection.""" + All: ActionSelectIdleWorker.Type.ValueType # 3 + """Equivalent to control+click. Selects all idle workers.""" + AddAll: ActionSelectIdleWorker.Type.ValueType # 4 + """Equivalent to shift+control+click. Adds all idle workers to current selection.""" + + TYPE_FIELD_NUMBER: builtins.int + type: global___ActionSelectIdleWorker.Type.ValueType + def __init__(self, *, type: global___ActionSelectIdleWorker.Type.ValueType | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["type", b"type"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["type", b"type"]) -> None: ... + +global___ActionSelectIdleWorker = ActionSelectIdleWorker + +@typing.final +class ActionMultiPanel(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ActionMultiPanel._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SingleSelect: ActionMultiPanel._Type.ValueType # 1 + """Click on icon""" + DeselectUnit: ActionMultiPanel._Type.ValueType # 2 + """Shift Click on icon""" + SelectAllOfType: ActionMultiPanel._Type.ValueType # 3 + """Control Click on icon.""" + DeselectAllOfType: ActionMultiPanel._Type.ValueType # 4 + """Control+Shift Click on icon.""" + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + SingleSelect: ActionMultiPanel.Type.ValueType # 1 + """Click on icon""" + DeselectUnit: ActionMultiPanel.Type.ValueType # 2 + """Shift Click on icon""" + SelectAllOfType: ActionMultiPanel.Type.ValueType # 3 + """Control Click on icon.""" + DeselectAllOfType: ActionMultiPanel.Type.ValueType # 4 + """Control+Shift Click on icon.""" + + TYPE_FIELD_NUMBER: builtins.int + UNIT_INDEX_FIELD_NUMBER: builtins.int + type: global___ActionMultiPanel.Type.ValueType + unit_index: builtins.int + def __init__( + self, *, type: global___ActionMultiPanel.Type.ValueType | None = ..., unit_index: builtins.int | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["type", b"type", "unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["type", b"type", "unit_index", b"unit_index"]) -> None: ... + +global___ActionMultiPanel = ActionMultiPanel + +@typing.final +class ActionCargoPanelUnload(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_INDEX_FIELD_NUMBER: builtins.int + unit_index: builtins.int + def __init__(self, *, unit_index: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> None: ... + +global___ActionCargoPanelUnload = ActionCargoPanelUnload + +@typing.final +class ActionProductionPanelRemoveFromQueue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UNIT_INDEX_FIELD_NUMBER: builtins.int + unit_index: builtins.int + def __init__(self, *, unit_index: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["unit_index", b"unit_index"]) -> None: ... + +global___ActionProductionPanelRemoveFromQueue = ActionProductionPanelRemoveFromQueue + +@typing.final +class ActionToggleAutocast(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ABILITY_ID_FIELD_NUMBER: builtins.int + ability_id: builtins.int + def __init__(self, *, ability_id: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["ability_id", b"ability_id"]) -> None: ... + +global___ActionToggleAutocast = ActionToggleAutocast diff --git a/stubs/scp/METADATA.toml b/stubs/scp/METADATA.toml new file mode 100644 index 000000000000..4456de13a4d5 --- /dev/null +++ b/stubs/scp/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.16.*" +upstream-repository = "https://github.com/jbardin/scp.py" +dependencies = ["types-paramiko"] diff --git a/stubs/scp/scp.pyi b/stubs/scp/scp.pyi new file mode 100644 index 000000000000..a7b9ae28b963 --- /dev/null +++ b/stubs/scp/scp.pyi @@ -0,0 +1,83 @@ +from collections.abc import Callable, Iterable +from pathlib import PurePath +from types import TracebackType +from typing import Final, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Self + +from paramiko.channel import Channel +from paramiko.transport import Transport + +__version__: Final[str] + +SCP_COMMAND: Final = b"scp" +PATH_TYPES: Final[tuple[type[str], type[bytes], type[PurePath]]] +bytes_sep: Final[bytes] + +PathTypes: TypeAlias = str | bytes | PurePath + +@type_check_only +class _PutFOReader(Protocol): + def read(self, size: int, /) -> str | bytes | bytearray: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: Literal[0, 2], /) -> object: ... + +def asbytes(s: PathTypes) -> bytes: ... +def asunicode(s: bytes | str) -> str: ... +def asunicode_win(s: bytes | str) -> str: ... + +class SCPClient: + transport: Transport + buff_size: int + socket_timeout: float | None + channel: Channel | None + preserve_times: bool + sanitize: Callable[[bytes], bytes] + peername: tuple[str, int] + scp_command: bytes + def __init__( + self, + transport: Transport, + buff_size: int = 16384, + socket_timeout: float | None = 10.0, + progress: Callable[[str | bytes, int, int], None] | None = None, + progress4: Callable[[str | bytes, int, int, tuple[str, int]], None] | None = None, + sanitize: Callable[[bytes], bytes] | Literal[False] = ..., + limit_bw: int | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def put( + self, + files: PathTypes | Iterable[PathTypes], + remote_path: PathTypes = b".", + recursive: bool = False, + preserve_times: bool = False, + ) -> None: ... + def putfo(self, fl: _PutFOReader, remote_path: PathTypes, mode: str | bytes = "0644", size: int | None = None) -> None: ... + def get( + self, + remote_path: PathTypes | Iterable[PathTypes], + local_path: PathTypes = "", + recursive: bool = False, + preserve_times: bool = False, + ) -> None: ... + def close(self) -> None: ... + +class SCPException(Exception): ... + +def put( + transport: Transport, + files: PathTypes | Iterable[PathTypes], + remote_path: PathTypes = b".", + recursive: bool = False, + preserve_times: bool = False, +) -> None: ... +def get( + transport: Transport, + remote_path: PathTypes | Iterable[PathTypes], + local_path: PathTypes = "", + recursive: bool = False, + preserve_times: bool = False, +) -> None: ... diff --git a/stubs/seaborn/@tests/stubtest_allowlist.txt b/stubs/seaborn/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..31b226b5a849 --- /dev/null +++ b/stubs/seaborn/@tests/stubtest_allowlist.txt @@ -0,0 +1,6 @@ +seaborn._core.scales.(Pipeline|TransFuncs) # aliases defined in `if TYPE_CHECKING` block +seaborn.external.docscrape.NumpyDocString.__str__ # weird signature + +seaborn.axisgrid.Grid.tight_layout # the method doesn't really take pos args but runtime has *args + +seaborn.external.appdirs.unicode diff --git a/stubs/seaborn/METADATA.toml b/stubs/seaborn/METADATA.toml new file mode 100644 index 000000000000..960160f52d9c --- /dev/null +++ b/stubs/seaborn/METADATA.toml @@ -0,0 +1,4 @@ +version = "0.13.2" +upstream-repository = "https://github.com/mwaskom/seaborn" +# Requires a version of numpy and matplotlib with a `py.typed` file +dependencies = ["matplotlib>=3.8", "numpy>=1.20", "pandas-stubs"] diff --git a/stubs/seaborn/seaborn/__init__.pyi b/stubs/seaborn/seaborn/__init__.pyi new file mode 100644 index 000000000000..f8a92d1d6515 --- /dev/null +++ b/stubs/seaborn/seaborn/__init__.pyi @@ -0,0 +1,13 @@ +from . import cm as cm +from .axisgrid import * +from .categorical import * +from .colors import crayons as crayons, xkcd_rgb as xkcd_rgb +from .distributions import * +from .matrix import * +from .miscplot import * +from .palettes import * +from .rcmod import * +from .regression import * +from .relational import * +from .utils import * +from .widgets import * diff --git a/stubs/seaborn/seaborn/_core/__init__.pyi b/stubs/seaborn/seaborn/_core/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_core/data.pyi b/stubs/seaborn/seaborn/_core/data.pyi new file mode 100644 index 000000000000..7686ead8de08 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/data.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from collections.abc import Mapping +from typing import TypeVar, overload + +from pandas import DataFrame +from seaborn._core.typing import DataSource, SupportsDataFrame, VariableSpec + +_T = TypeVar("_T", Mapping[Incomplete, Incomplete], None) + +class PlotData: + frame: DataFrame + frames: dict[tuple[str, str], DataFrame] + names: dict[str, str | None] + ids: dict[str, str | int] + source_data: DataSource + source_vars: dict[str, VariableSpec] + def __init__(self, data: DataSource, variables: dict[str, VariableSpec]) -> None: ... + def __contains__(self, key: str) -> bool: ... + def join(self, data: DataSource, variables: dict[str, VariableSpec] | None) -> PlotData: ... + +@overload +def handle_data_source(data: _T) -> _T: ... +@overload +def handle_data_source(data: SupportsDataFrame) -> DataFrame: ... + +def convert_dataframe_to_pandas(data: object) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_core/exceptions.pyi b/stubs/seaborn/seaborn/_core/exceptions.pyi new file mode 100644 index 000000000000..c453083b113f --- /dev/null +++ b/stubs/seaborn/seaborn/_core/exceptions.pyi @@ -0,0 +1 @@ +class PlotSpecError(RuntimeError): ... diff --git a/stubs/seaborn/seaborn/_core/groupby.pyi b/stubs/seaborn/seaborn/_core/groupby.pyi new file mode 100644 index 000000000000..a07f2757c56b --- /dev/null +++ b/stubs/seaborn/seaborn/_core/groupby.pyi @@ -0,0 +1,32 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Hashable, Mapping +from typing import Concatenate, ParamSpec, TypeAlias + +from numpy import ufunc +from pandas import DataFrame + +# pandas._typing.AggFuncTypeFrame is partially Unknown +_AggFuncTypeBase: TypeAlias = Callable[..., Incomplete] | str | ufunc +_AggFuncTypeDictFrame: TypeAlias = Mapping[Hashable, _AggFuncTypeBase | list[_AggFuncTypeBase]] +_AggFuncTypeFrame: TypeAlias = _AggFuncTypeBase | list[_AggFuncTypeBase] | _AggFuncTypeDictFrame + +_P = ParamSpec("_P") + +class GroupBy: + order: dict[str, list[Incomplete] | None] + def __init__(self, order: list[str] | dict[str, list[Incomplete] | None]) -> None: ... + # Signature based on pandas.core.groupby.generic.DataFrameGroupBy.aggregate + # args and kwargs possible values depend on func which itself can be + # an attribute name, a mapping, a callable, or lead to a jitted numba function + def agg( + self, + data: DataFrame, + func: _AggFuncTypeFrame = ..., + *args, + engine: str | None = None, + engine_kwargs: dict[str, bool] | None = None, + **kwargs, + ) -> DataFrame: ... + def apply( + self, data: DataFrame, func: Callable[Concatenate[DataFrame, _P], DataFrame], *args: _P.args, **kwargs: _P.kwargs + ) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_core/moves.pyi b/stubs/seaborn/seaborn/_core/moves.pyi new file mode 100644 index 000000000000..ed3f7f5e439a --- /dev/null +++ b/stubs/seaborn/seaborn/_core/moves.pyi @@ -0,0 +1,44 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from dataclasses import dataclass +from typing import ClassVar + +from pandas import DataFrame +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale +from seaborn._core.typing import Default + +default: Default + +@dataclass +class Move: + group_by_orient: ClassVar[bool] + def __call__(self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale]) -> DataFrame: ... + +@dataclass +class Jitter(Move): + width: float | Default = ... + x: float = 0 + y: float = 0 + seed: int | None = None + +@dataclass +class Dodge(Move): + empty: str = "keep" + gap: float = 0 + by: list[str] | None = None + +@dataclass +class Stack(Move): ... + +@dataclass +class Shift(Move): + x: float = 0 + y: float = 0 + +@dataclass +class Norm(Move): + func: Callable[..., Incomplete] | str = "max" + where: str | None = None + by: list[str] | None = None + percent: bool = False diff --git a/stubs/seaborn/seaborn/_core/plot.pyi b/stubs/seaborn/seaborn/_core/plot.pyi new file mode 100644 index 000000000000..7f8bf81069c6 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/plot.pyi @@ -0,0 +1,153 @@ +import inspect +import os +from _typeshed import Incomplete, SupportsKeysAndGetItem +from collections.abc import Callable, Generator +from contextlib import contextmanager +from typing import IO, Any, Literal, TypedDict, TypeVar +from typing_extensions import Never, Self + +import matplotlib as mpl +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.figure import Figure, SubFigure +from matplotlib.transforms import Bbox +from matplotlib.typing import ColorType +from seaborn._core.data import PlotData +from seaborn._core.moves import Move +from seaborn._core.scales import Scale +from seaborn._core.typing import DataSource, Default, OrderSpec, VariableSpec, VariableSpecList +from seaborn._marks.base import Mark +from seaborn._stats.base import Stat + +_ClsT = TypeVar("_ClsT", bound=type[Any]) + +default: Default + +class Layer(TypedDict, total=False): + mark: Mark + stat: Stat | None + move: Move | list[Move] | None + data: PlotData + source: DataSource + vars: dict[str, VariableSpec] + orient: str + legend: bool + label: str | None + +class FacetSpec(TypedDict, total=False): + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + wrap: int | None + +class PairSpec(TypedDict, total=False): + variables: dict[str, VariableSpec] + structure: dict[str, list[str]] + cross: bool + wrap: int | None + +@contextmanager +def theme_context(params: dict[str, Any]) -> Generator[None]: ... +def build_plot_signature(cls: _ClsT) -> _ClsT: ... # -> _ClsT & "__signature__ protocol" + +class ThemeConfig(mpl.RcParams): + THEME_GROUPS: list[str] + def __init__(self) -> None: ... + def reset(self) -> None: ... + def update(self, other: SupportsKeysAndGetItem[Incomplete, Incomplete] | None = None, /, **kwds) -> None: ... # type: ignore[override] + +class DisplayConfig(TypedDict): + format: Literal["png", "svg"] + scaling: float + hidpi: bool + +class PlotConfig: + def __init__(self) -> None: ... + @property + def theme(self) -> dict[str, Any]: ... + @property + def display(self) -> DisplayConfig: ... + +@build_plot_signature +class Plot: + __signature__: inspect.Signature + config: PlotConfig + def __init__(self, *args: DataSource | VariableSpec, data: DataSource = None, **variables: VariableSpec) -> None: ... + def __add__(self, other: Never) -> Never: ... + def on(self, target: Axes | SubFigure | Figure) -> Plot: ... + def add( + self, + mark: Mark, + *transforms: Stat | Move, + orient: str | None = None, + legend: bool = True, + label: str | None = None, + data: DataSource = None, + **variables: VariableSpec, + ) -> Plot: ... + def pair( + self, x: VariableSpecList = None, y: VariableSpecList = None, wrap: int | None = None, cross: bool = True + ) -> Plot: ... + def facet( + self, + col: VariableSpec = None, + row: VariableSpec = None, + order: OrderSpec | dict[str, OrderSpec] = None, + wrap: int | None = None, + ) -> Plot: ... + def scale(self, **scales: Scale) -> Plot: ... + def share(self, **shares: bool | str) -> Plot: ... + def limit(self, **limits: tuple[Any, Any]) -> Plot: ... + def label(self, *, title: str | None = None, legend: str | None = None, **variables: str | Callable[[str], str]) -> Plot: ... + def layout( + self, + *, + size: tuple[float, float] | Default = ..., + engine: str | None | Default = ..., + extent: tuple[float, float, float, float] | Default = ..., + ) -> Plot: ... + def theme(self, config: dict[str, Any], /) -> Plot: ... + # Same signature as Plotter.save + def save( + self, + loc: str | os.PathLike[Any] | IO[Any], + *, + transparent: bool | None = None, + dpi: float | None = 96, + facecolor: ColorType | Literal["auto"] | None = ..., + edgecolor: ColorType | Literal["auto"] | None = ..., + orientation: str = "protrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = None, + pad_inches: float | None = None, + bbox_extra_artists: list[Artist] | None = None, + backend: str | None = None, + **kwargs: Any, + ) -> Self: ... + # Same signature as Plotter.show + def show(self, *, block: bool | None = None) -> None: ... + def plot(self, pyplot: bool = False) -> Plotter: ... + +class Plotter: + def __init__(self, pyplot: bool, theme: dict[str, Any]) -> None: ... + def save( + self, + loc: str | os.PathLike[Any] | IO[Any], + *, + # From matplotlib.figure.Figure.savefig + transparent: bool | None = None, + # keyword-only arguments below are the same as matplotlib.backend_bases.FigureCanvasBase.print_figure + # but with different defaults + dpi: float | None = 96, + facecolor: ColorType | Literal["auto"] | None = ..., + edgecolor: ColorType | Literal["auto"] | None = ..., + orientation: str = "protrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = None, + pad_inches: float | None = None, + bbox_extra_artists: list[Artist] | None = None, + backend: str | None = None, + # Further **kwargs can truly be anything from an overridden Canvas method that is still passed down + **kwargs: Any, + ) -> Self: ... + # Same as matplotlib.backend_bases._Bases. No other backend override show + def show(self, *, block: bool | None = None) -> None: ... diff --git a/stubs/seaborn/seaborn/_core/properties.pyi b/stubs/seaborn/seaborn/_core/properties.pyi new file mode 100644 index 000000000000..548cc5a9d3ce --- /dev/null +++ b/stubs/seaborn/seaborn/_core/properties.pyi @@ -0,0 +1,97 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, TypeAlias + +from matplotlib.markers import MarkerStyle +from matplotlib.path import Path +from numpy.typing import ArrayLike +from pandas import Series +from seaborn._core.scales import Scale + +RGBTuple: TypeAlias = tuple[float, float, float] +RGBATuple: TypeAlias = tuple[float, float, float, float] +ColorSpec: TypeAlias = RGBTuple | RGBATuple | str +DashPattern: TypeAlias = tuple[float, ...] +DashPatternWithOffset: TypeAlias = tuple[float, DashPattern | None] +MarkerPattern: TypeAlias = float | str | tuple[int, int, float] | list[tuple[float, float]] | Path | MarkerStyle +Mapping: TypeAlias = Callable[[ArrayLike], ArrayLike] + +class Property: + legend: bool + normed: bool + variable: Incomplete + def __init__(self, variable: str | None = None) -> None: ... + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + def standardize(self, val: Any) -> Any: ... + +class Coordinate(Property): + legend: bool + normed: bool + +class IntervalProperty(Property): + legend: bool + normed: bool + @property + def default_range(self) -> tuple[float, float]: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class PointSize(IntervalProperty): ... + +class LineWidth(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class EdgeWidth(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class Stroke(IntervalProperty): ... +class Alpha(IntervalProperty): ... +class Offset(IntervalProperty): ... + +class FontSize(IntervalProperty): + @property + def default_range(self) -> tuple[float, float]: ... + +class ObjectProperty(Property): + legend: bool + normed: bool + null_value: Any + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class Marker(ObjectProperty): + null_value: Incomplete + def standardize(self, val: MarkerPattern) -> MarkerStyle: ... + +class LineStyle(ObjectProperty): + null_value: str + def standardize(self, val: str | DashPattern) -> DashPatternWithOffset: ... + +class TextAlignment(ObjectProperty): + legend: bool + +class HorizontalAlignment(TextAlignment): ... +class VerticalAlignment(TextAlignment): ... + +class Color(Property): + legend: bool + normed: bool + def standardize(self, val: ColorSpec) -> RGBTuple | RGBATuple: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +class Fill(Property): + legend: bool + normed: bool + def default_scale(self, data: Series[Any]) -> Scale: ... + def infer_scale(self, arg: Any, data: Series[Any]) -> Scale: ... + def standardize(self, val: Any) -> bool: ... + def get_mapping(self, scale: Scale, data: Series[Any]) -> Mapping: ... + +PROPERTY_CLASSES: dict[str, type[Property]] +PROPERTIES: dict[str, Property] diff --git a/stubs/seaborn/seaborn/_core/rules.pyi b/stubs/seaborn/seaborn/_core/rules.pyi new file mode 100644 index 000000000000..8f07c919295a --- /dev/null +++ b/stubs/seaborn/seaborn/_core/rules.pyi @@ -0,0 +1,14 @@ +from collections import UserString +from typing import Any, Literal + +from pandas import Series + +class VarType(UserString): + allowed: tuple[str, ...] + def __init__(self, data: str) -> None: ... + def __eq__(self, other: str) -> bool: ... # type: ignore[override] + +def variable_type( + vector: Series[Any], boolean_type: Literal["numeric", "categorical", "boolean"] = "numeric", strict_boolean: bool = False +) -> VarType: ... +def categorical_order(vector: Series[Any], order: list[Any] | None = None) -> list[Any]: ... diff --git a/stubs/seaborn/seaborn/_core/scales.pyi b/stubs/seaborn/seaborn/_core/scales.pyi new file mode 100644 index 000000000000..8e164e265ef0 --- /dev/null +++ b/stubs/seaborn/seaborn/_core/scales.pyi @@ -0,0 +1,100 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, ClassVar, TypeAlias +from typing_extensions import Self + +from matplotlib.axis import Ticker +from matplotlib.scale import ScaleBase +from matplotlib.ticker import Formatter, Locator +from matplotlib.units import ConversionInterface +from numpy.typing import ArrayLike, NDArray +from pandas import Series +from seaborn._core.typing import Default + +TransFuncs: TypeAlias = tuple[Callable[[ArrayLike], ArrayLike], Callable[[ArrayLike], ArrayLike]] +Pipeline: TypeAlias = Sequence[Callable[[Any], Any] | None] + +class Scale: + values: tuple[Incomplete, ...] | str | list[Incomplete] | dict[Incomplete, Incomplete] | None + def __post_init__(self) -> None: ... + def tick(self) -> Self: ... + def label(self) -> Self: ... + def __call__(self, data: Series[Any]) -> ArrayLike: ... + +@dataclass +class Boolean(Scale): + values: tuple[Incomplete, ...] | list[Incomplete] | dict[Incomplete, Incomplete] | None = None + def tick(self, locator: Locator | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None) -> Self: ... + +@dataclass +class Nominal(Scale): + values: tuple[Incomplete, ...] | str | list[Incomplete] | dict[Incomplete, Incomplete] | None = None + order: list[Incomplete] | None = None + def tick(self, locator: Locator | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None) -> Self: ... + +@dataclass +class Ordinal(Scale): ... + +@dataclass +class Discrete(Scale): ... + +@dataclass +class ContinuousBase(Scale): + values: tuple[Incomplete, ...] | str | None = None + norm: tuple[Incomplete, ...] | None = None + +@dataclass +class Continuous(ContinuousBase): + values: tuple[Incomplete, ...] | str | None = None + trans: str | TransFuncs | None = None + def tick( + self, + locator: Locator | None = None, + *, + at: Sequence[float] | None = None, + upto: int | None = None, + count: int | None = None, + every: float | None = None, + between: tuple[float, float] | None = None, + minor: int | None = None, + ) -> Self: ... + def label( + self, + formatter: Formatter | None = None, + *, + like: str | Callable[[float], str] | None = None, + base: int | None | Default = ..., + unit: str | None = None, + ) -> Self: ... + +@dataclass +class Temporal(ContinuousBase): + trans: ClassVar[Incomplete] # not sure it is a classvar but the runtime has no annotation so it is not a dataclass field + def tick(self, locator: Locator | None = None, *, upto: int | None = None) -> Self: ... + def label(self, formatter: Formatter | None = None, *, concise: bool = False) -> Self: ... + +class PseudoAxis: + axis_name: str + converter: ConversionInterface | None + units: Incomplete | None + scale: ScaleBase + major: Ticker + minor: Ticker + def __init__(self, scale: ScaleBase) -> None: ... + def set_view_interval(self, vmin: float, vmax: float) -> None: ... + def get_view_interval(self) -> tuple[float, float]: ... + def set_data_interval(self, vmin: float, vmax: float) -> None: ... + def get_data_interval(self) -> tuple[float, float]: ... + def get_tick_space(self) -> int: ... + def set_major_locator(self, locator: Locator) -> None: ... + def set_major_formatter(self, formatter: Formatter) -> None: ... + def set_minor_locator(self, locator: Locator) -> None: ... + def set_minor_formatter(self, formatter: Formatter) -> None: ... + def set_units(self, units) -> None: ... + def update_units(self, x) -> None: ... + def convert_units(self, x): ... + def get_scale(self) -> ScaleBase: ... + def get_majorticklocs(self) -> NDArray[Incomplete]: ... diff --git a/stubs/seaborn/seaborn/_core/subplots.pyi b/stubs/seaborn/seaborn/_core/subplots.pyi new file mode 100644 index 000000000000..a3713e2f30de --- /dev/null +++ b/stubs/seaborn/seaborn/_core/subplots.pyi @@ -0,0 +1,19 @@ +from collections.abc import Iterator +from typing import Any + +from matplotlib.axes import Axes +from matplotlib.figure import Figure, SubFigure +from seaborn._core.plot import FacetSpec, PairSpec + +class Subplots: + subplot_spec: dict[str, Any] + def __init__(self, subplot_spec: dict[str, Any], facet_spec: FacetSpec, pair_spec: PairSpec) -> None: ... + def init_figure( + self, + pair_spec: PairSpec, + pyplot: bool = False, + figure_kws: dict[str, Any] | None = None, + target: Axes | Figure | SubFigure | None = None, + ) -> Figure: ... + def __iter__(self) -> Iterator[dict[str, Any]]: ... + def __len__(self) -> int: ... diff --git a/stubs/seaborn/seaborn/_core/typing.pyi b/stubs/seaborn/seaborn/_core/typing.pyi new file mode 100644 index 000000000000..c114bdf8f09f --- /dev/null +++ b/stubs/seaborn/seaborn/_core/typing.pyi @@ -0,0 +1,29 @@ +from _typeshed import Incomplete +from collections.abc import Iterable, Mapping +from datetime import date, datetime, timedelta +from typing import Any, Protocol, TypeAlias, type_check_only + +from matplotlib.colors import Colormap, Normalize +from numpy import ndarray +from pandas import DataFrame, Index, Series, Timedelta, Timestamp + +@type_check_only +class SupportsDataFrame(Protocol): + def __dataframe__(self, nan_as_null: bool = ..., allow_copy: bool = ...): ... + +ColumnName: TypeAlias = str | bytes | date | datetime | timedelta | bool | complex | Timestamp | Timedelta +Vector: TypeAlias = Series[Any] | Index[Any] | ndarray[Any, Any] +VariableSpec: TypeAlias = ColumnName | Vector | None +VariableSpecList: TypeAlias = list[VariableSpec] | Index[Any] | None +DataSource: TypeAlias = DataFrame | SupportsDataFrame | Mapping[Any, Incomplete] | None +OrderSpec: TypeAlias = Iterable[str] | None +NormSpec: TypeAlias = tuple[float | None, float | None] | Normalize | None +PaletteSpec: TypeAlias = str | list[Incomplete] | dict[Incomplete, Incomplete] | Colormap | None +DiscreteValueSpec: TypeAlias = dict[Incomplete, Incomplete] | list[Incomplete] | None +ContinuousValueSpec: TypeAlias = tuple[float, float] | list[float] | dict[Any, float] | None + +class Default: ... +class Deprecated: ... + +default: Default +deprecated: Deprecated diff --git a/stubs/seaborn/seaborn/_marks/__init__.pyi b/stubs/seaborn/seaborn/_marks/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_marks/area.pyi b/stubs/seaborn/seaborn/_marks/area.pyi new file mode 100644 index 000000000000..04cca8781ee7 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/area.pyi @@ -0,0 +1,28 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableBool, MappableColor, MappableFloat, MappableStyle, Mark, document_properties + +class AreaBase: ... + +@document_properties +@dataclass +class Area(AreaBase, Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + baseline: MappableFloat = ... + +@document_properties +@dataclass +class Band(AreaBase, Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/bar.pyi b/stubs/seaborn/seaborn/_marks/bar.pyi new file mode 100644 index 000000000000..5cee9ad83af8 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/bar.pyi @@ -0,0 +1,31 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableBool, MappableColor, MappableFloat, MappableStyle, Mark, document_properties + +class BarBase(Mark): ... + +@document_properties +@dataclass +class Bar(BarBase): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + width: MappableFloat = ... + baseline: MappableFloat = ... + +@document_properties +@dataclass +class Bars(BarBase): + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + width: MappableFloat = ... + baseline: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/base.pyi b/stubs/seaborn/seaborn/_marks/base.pyi new file mode 100644 index 000000000000..80989c2f4274 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/base.pyi @@ -0,0 +1,37 @@ +from _typeshed import Incomplete +from dataclasses import dataclass +from typing import Any, TypeAlias, TypeVar + +from numpy.typing import NDArray +from pandas import DataFrame +from seaborn._core.properties import DashPattern, DashPatternWithOffset, RGBATuple +from seaborn._core.scales import Scale + +_MarkT = TypeVar("_MarkT", bound=type[Mark]) + +class Mappable: + def __init__( + self, val: Any = None, depend: str | None = None, rc: str | None = None, auto: bool = False, grouping: bool = True + ) -> None: ... + @property + def depend(self) -> Any: ... # -> str | None + @property + def grouping(self) -> bool: ... + @property + def default(self) -> Any: ... + +MappableBool: TypeAlias = bool | Mappable +MappableString: TypeAlias = str | Mappable +MappableFloat: TypeAlias = float | Mappable +MappableColor: TypeAlias = str | tuple[Incomplete, ...] | Mappable +MappableStyle: TypeAlias = str | DashPattern | DashPatternWithOffset | Mappable + +@dataclass +class Mark: + artist_kws: dict[str, Any] = ... + +def resolve_properties(mark: Mark, data: DataFrame, scales: dict[str, Scale]) -> dict[str, Any]: ... +def resolve_color( + mark: Mark, data: DataFrame | dict[str, Any], prefix: str = "", scales: dict[str, Scale] | None = None +) -> RGBATuple | NDArray[Incomplete]: ... +def document_properties(mark: _MarkT) -> _MarkT: ... diff --git a/stubs/seaborn/seaborn/_marks/dot.pyi b/stubs/seaborn/seaborn/_marks/dot.pyi new file mode 100644 index 000000000000..6b5a0428a3de --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/dot.pyi @@ -0,0 +1,39 @@ +from dataclasses import dataclass + +from seaborn._marks.base import ( + MappableBool, + MappableColor, + MappableFloat, + MappableString, + MappableStyle, + Mark, + document_properties, +) + +class DotBase(Mark): ... + +@document_properties +@dataclass +class Dot(DotBase): + marker: MappableString = ... + pointsize: MappableFloat = ... + stroke: MappableFloat = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + edgecolor: MappableColor = ... + edgealpha: MappableFloat = ... + edgewidth: MappableFloat = ... + edgestyle: MappableStyle = ... + +@document_properties +@dataclass +class Dots(DotBase): + marker: MappableString = ... + pointsize: MappableFloat = ... + stroke: MappableFloat = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fill: MappableBool = ... + fillcolor: MappableColor = ... + fillalpha: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/line.pyi b/stubs/seaborn/seaborn/_marks/line.pyi new file mode 100644 index 000000000000..71594380a7f7 --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/line.pyi @@ -0,0 +1,42 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableColor, MappableFloat, MappableString, Mark, document_properties + +@document_properties +@dataclass +class Path(Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + linewidth: MappableFloat = ... + linestyle: MappableString = ... + marker: MappableString = ... + pointsize: MappableFloat = ... + fillcolor: MappableColor = ... + edgecolor: MappableColor = ... + edgewidth: MappableFloat = ... + +@document_properties +@dataclass +class Line(Path): ... + +@document_properties +@dataclass +class Paths(Mark): + color: MappableColor = ... + alpha: MappableFloat = ... + linewidth: MappableFloat = ... + linestyle: MappableString = ... + def __post_init__(self) -> None: ... + +@document_properties +@dataclass +class Lines(Paths): ... + +@document_properties +@dataclass +class Range(Paths): ... + +@document_properties +@dataclass +class Dash(Paths): + width: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_marks/text.pyi b/stubs/seaborn/seaborn/_marks/text.pyi new file mode 100644 index 000000000000..a8c72fe0cdcc --- /dev/null +++ b/stubs/seaborn/seaborn/_marks/text.pyi @@ -0,0 +1,14 @@ +from dataclasses import dataclass + +from seaborn._marks.base import MappableColor, MappableFloat, MappableString, Mark, document_properties + +@document_properties +@dataclass +class Text(Mark): + text: MappableString = ... + color: MappableColor = ... + alpha: MappableFloat = ... + fontsize: MappableFloat = ... + halign: MappableString = ... + valign: MappableString = ... + offset: MappableFloat = ... diff --git a/stubs/seaborn/seaborn/_stats/__init__.pyi b/stubs/seaborn/seaborn/_stats/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/_stats/aggregation.pyi b/stubs/seaborn/seaborn/_stats/aggregation.pyi new file mode 100644 index 000000000000..cf30b12a2dc4 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/aggregation.pyi @@ -0,0 +1,19 @@ +from collections.abc import Callable +from dataclasses import dataclass + +from seaborn._core.typing import Vector +from seaborn._stats.base import Stat + +@dataclass +class Agg(Stat): + func: str | Callable[[Vector], float] = "mean" + +@dataclass +class Est(Stat): + func: str | Callable[[Vector], float] = "mean" + errorbar: str | tuple[str, float] = ("ci", 95) + n_boot: int = 1000 + seed: int | None = None + +@dataclass +class Rolling(Stat): ... diff --git a/stubs/seaborn/seaborn/_stats/base.pyi b/stubs/seaborn/seaborn/_stats/base.pyi new file mode 100644 index 000000000000..7f3184b4e72b --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/base.pyi @@ -0,0 +1,11 @@ +from dataclasses import dataclass +from typing import ClassVar + +from pandas import DataFrame +from seaborn._core.groupby import GroupBy +from seaborn._core.scales import Scale + +@dataclass +class Stat: + group_by_orient: ClassVar[bool] + def __call__(self, data: DataFrame, groupby: GroupBy, orient: str, scales: dict[str, Scale]) -> DataFrame: ... diff --git a/stubs/seaborn/seaborn/_stats/counting.pyi b/stubs/seaborn/seaborn/_stats/counting.pyi new file mode 100644 index 000000000000..b6283af97cdd --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/counting.pyi @@ -0,0 +1,19 @@ +from dataclasses import dataclass + +from numpy.typing import ArrayLike +from seaborn._stats.base import Stat + +@dataclass +class Count(Stat): ... + +@dataclass +class Hist(Stat): + stat: str = "count" + bins: str | int | ArrayLike = "auto" + binwidth: float | None = None + binrange: tuple[float, float] | None = None + common_norm: bool | list[str] = True + common_bins: bool | list[str] = True + cumulative: bool = False + discrete: bool = False + def __post_init__(self) -> None: ... diff --git a/stubs/seaborn/seaborn/_stats/density.pyi b/stubs/seaborn/seaborn/_stats/density.pyi new file mode 100644 index 000000000000..386424ccbcd3 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/density.pyi @@ -0,0 +1,15 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat +from seaborn.external.kde import _BwMethodType + +@dataclass +class KDE(Stat): + bw_adjust: float = 1 + bw_method: _BwMethodType = "scott" + common_norm: bool | list[str] = True + common_grid: bool | list[str] = True + gridsize: int | None = 200 + cut: float = 3 + cumulative: bool = False + def __post_init__(self) -> None: ... diff --git a/stubs/seaborn/seaborn/_stats/order.pyi b/stubs/seaborn/seaborn/_stats/order.pyi new file mode 100644 index 000000000000..8950dc411d36 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/order.pyi @@ -0,0 +1,8 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat + +@dataclass +class Perc(Stat): + k: int | list[float] = 5 + method: str = "linear" diff --git a/stubs/seaborn/seaborn/_stats/regression.pyi b/stubs/seaborn/seaborn/_stats/regression.pyi new file mode 100644 index 000000000000..c5f9fcf25170 --- /dev/null +++ b/stubs/seaborn/seaborn/_stats/regression.pyi @@ -0,0 +1,11 @@ +from dataclasses import dataclass + +from seaborn._stats.base import Stat + +@dataclass +class PolyFit(Stat): + order: int = 2 + gridsize: int = 100 + +@dataclass +class OLSFit(Stat): ... diff --git a/stubs/seaborn/seaborn/algorithms.pyi b/stubs/seaborn/seaborn/algorithms.pyi new file mode 100644 index 000000000000..d413cdee161c --- /dev/null +++ b/stubs/seaborn/seaborn/algorithms.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable +from typing import Any, overload +from typing_extensions import deprecated + +from numpy.typing import ArrayLike, NDArray + +from .utils import _Seed + +@overload +def bootstrap( + *args: ArrayLike, + n_boot: int = 10000, + func: str | Callable[..., Any] = "mean", + axis: int | None = None, + units: ArrayLike | None = None, + seed: _Seed | None = None, +) -> NDArray[Any]: ... +@overload +@deprecated("Parameter `random_seed` is deprecated in favor of `seed`") +def bootstrap( + *args: ArrayLike, + n_boot: int = 10000, + func: str | Callable[..., Any] = "mean", + axis: int | None = None, + units: ArrayLike | None = None, + seed: _Seed | None = None, + random_seed: _Seed | None = None, +) -> NDArray[Any]: ... diff --git a/stubs/seaborn/seaborn/axisgrid.pyi b/stubs/seaborn/seaborn/axisgrid.pyi new file mode 100644 index 000000000000..3cc0dd8dabdc --- /dev/null +++ b/stubs/seaborn/seaborn/axisgrid.pyi @@ -0,0 +1,402 @@ +import os +from _typeshed import Incomplete +from collections.abc import Callable, Generator, Iterable, Mapping +from typing import IO, Any, Concatenate, Literal, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self, deprecated + +import numpy as np +from matplotlib.artist import Artist +from matplotlib.axes import Axes +from matplotlib.backend_bases import MouseEvent, RendererBase +from matplotlib.colors import Colormap +from matplotlib.figure import Figure +from matplotlib.font_manager import FontProperties +from matplotlib.gridspec import SubplotSpec +from matplotlib.legend import Legend +from matplotlib.patches import Patch +from matplotlib.path import Path as mpl_Path +from matplotlib.patheffects import AbstractPathEffect +from matplotlib.scale import ScaleBase +from matplotlib.text import Text +from matplotlib.transforms import Bbox, BboxBase, Transform, TransformedPath +from matplotlib.typing import ColorType, LineStyleType, MarkerType +from numpy.typing import ArrayLike, NDArray +from pandas import DataFrame, Series + +from ._core.typing import ColumnName, DataSource, NormSpec, SupportsDataFrame +from .palettes import _RGBColorPalette +from .utils import _DataSourceWideForm, _Palette, _Vector + +__all__ = ["FacetGrid", "PairGrid", "JointGrid", "pairplot", "jointplot"] + +_P = ParamSpec("_P") +_R = TypeVar("_R") + +_LiteralFont: TypeAlias = Literal["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"] + +class _BaseGrid: + def set( + self, + *, + # Keywords follow `matplotlib.axes.Axes.set`. Each keyword corresponds to a `set_` method + adjustable: Literal["box", "datalim"] = ..., + agg_filter: Callable[[ArrayLike, float], tuple[NDArray[np.floating[Any]], float, float]] | None = ..., + alpha: float | None = ..., + anchor: str | tuple[float, float] = ..., + animated: bool = ..., + aspect: float | Literal["auto", "equal"] = ..., + autoscale_on: bool = ..., + autoscalex_on: bool = ..., + autoscaley_on: bool = ..., + axes_locator: Callable[[Axes, RendererBase], Bbox] = ..., + axisbelow: bool | Literal["line"] = ..., + box_aspect: float | None = ..., + clip_box: BboxBase | None = ..., + clip_on: bool = ..., + clip_path: Patch | mpl_Path | TransformedPath | None = ..., + facecolor: ColorType | None = ..., + frame_on: bool = ..., + gid: str | None = ..., + in_layout: bool = ..., + label: object = ..., + mouseover: bool = ..., + navigate: bool = ..., + path_effects: list[AbstractPathEffect] = ..., + picker: bool | float | Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]] | None = ..., + position: Bbox | tuple[float, float, float, float] = ..., + prop_cycle=..., # TODO: use cycler.Cycler when cycler gets typed + rasterization_zorder: float | None = ..., + rasterized: bool = ..., + sketch_params: float | None = ..., + snap: bool | None = ..., + subplotspec: SubplotSpec = ..., + title: str = ..., + transform: Transform | None = ..., + url: str | None = ..., + visible: bool = ..., + xbound: float | None | tuple[float | None, float | None] = ..., + xlabel: str = ..., + xlim: float | None | tuple[float | None, float | None] = ..., + xmargin: float = ..., + xscale: str | ScaleBase = ..., + xticklabels: Iterable[str | Text] = ..., + xticks: ArrayLike = ..., + ybound: float | None | tuple[float | None, float | None] = ..., + ylabel: str = ..., + ylim: float | None | tuple[float | None, float | None] = ..., + ymargin: float = ..., + yscale: str | ScaleBase = ..., + yticklabels: Iterable[str | Text] = ..., + yticks: ArrayLike = ..., + zorder: float = ..., + **kwargs: Any, + ) -> Self: ... + @property + @deprecated("Attribute `fig` is deprecated in favor of `figure`") + def fig(self) -> Figure: ... + @property + def figure(self) -> Figure: ... + def apply(self, func: Callable[Concatenate[Self, _P], object], *args: _P.args, **kwargs: _P.kwargs) -> Self: ... + def pipe(self, func: Callable[Concatenate[Self, _P], _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... + def savefig( + self, + # Signature follows `matplotlib.figure.Figure.savefig` + fname: str | os.PathLike[Any] | IO[Any], + *, + transparent: bool | None = None, + dpi: float | Literal["figure"] | None = 96, + facecolor: ColorType | Literal["auto"] | None = "auto", + edgecolor: ColorType | Literal["auto"] | None = "auto", + orientation: Literal["landscape", "portrait"] = "portrait", + format: str | None = None, + bbox_inches: Literal["tight"] | Bbox | None = "tight", + pad_inches: float | Literal["layout"] | None = None, + backend: str | None = None, + **kwargs: Any, + ) -> None: ... + +class Grid(_BaseGrid): + def __init__(self) -> None: ... + def tight_layout( + self, + *, + # Keywords follow `matplotlib.figure.Figure.tight_layout` + pad: float = 1.08, + h_pad: float | None = None, + w_pad: float | None = None, + rect: tuple[float, float, float, float] | None = None, + ) -> Self: ... + def add_legend( + self, + # Cannot use precise key type with union for legend_data because of invariant Mapping keys + legend_data: Mapping[Any, Artist] | None = None, + title: str | None = None, + label_order: list[str] | None = None, + adjust_subtitles: bool = False, + *, + # Keywords follow `matplotlib.legend.Legend` + loc: str | int | tuple[float, float] | None = None, + numpoints: int | None = None, + markerscale: float | None = None, + markerfirst: bool = True, + reverse: bool = False, + scatterpoints: int | None = None, + scatteryoffsets: Iterable[float] | None = None, + prop: FontProperties | dict[str, Any] | None = None, + fontsize: int | _LiteralFont | None = None, + labelcolor: str | Iterable[str] | None = None, + borderpad: float | None = None, + labelspacing: float | None = None, + handlelength: float | None = None, + handleheight: float | None = None, + handletextpad: float | None = None, + borderaxespad: float | None = None, + columnspacing: float | None = None, + ncols: int = 1, + mode: Literal["expand"] | None = None, + fancybox: bool | None = None, + shadow: bool | dict[str, int] | dict[str, float] | None = None, + title_fontsize: int | _LiteralFont | None = None, + framealpha: float | None = None, + edgecolor: ColorType | None = None, + facecolor: ColorType | None = None, + bbox_to_anchor: BboxBase | tuple[float, float] | tuple[float, float, float, float] | None = None, + bbox_transform: Transform | None = None, + frameon: bool | None = None, + handler_map: None = None, + title_fontproperties: FontProperties | None = None, + alignment: Literal["center", "left", "right"] = "center", + ncol: int = 1, + draggable: bool = False, + ) -> Self: ... + @property + def legend(self) -> Legend | None: ... + def tick_params( + self, + axis: Literal["x", "y", "both"] = "both", + *, + # Keywords follow `matplotlib.axes.Axes.tick_params` + which: Literal["major", "minor", "both"] = "major", + reset: bool = False, + direction: Literal["in", "out", "inout"] = ..., + length: float = ..., + width: float = ..., + color: ColorType = ..., + pad: float = ..., + labelsize: float | str = ..., + labelcolor: ColorType = ..., + labelfontfamily: str = ..., + colors: ColorType = ..., + zorder: float = ..., + bottom: bool = ..., + top: bool = ..., + left: bool = ..., + right: bool = ..., + labelbottom: bool = ..., + labeltop: bool = ..., + labelleft: bool = ..., + labelright: bool = ..., + labelrotation: float = ..., + grid_color: ColorType = ..., + grid_alpha: float = ..., + grid_linewidth: float = ..., + grid_linestyle: str = ..., + **kwargs: Any, + ) -> Self: ... + +class FacetGrid(Grid): + data: DataFrame + row_names: list[Any] + col_names: list[Any] + hue_names: list[Any] | None + hue_kws: dict[str, Any] + def __init__( + self, + data: DataFrame | SupportsDataFrame, + *, + row: str | None = None, + col: str | None = None, + hue: str | None = None, + col_wrap: int | None = None, + sharex: bool | Literal["col", "row"] = True, + sharey: bool | Literal["col", "row"] = True, + height: float = 3, + aspect: float = 1, + palette: _Palette | None = None, + row_order: Iterable[Any] | None = None, + col_order: Iterable[Any] | None = None, + hue_order: Iterable[Any] | None = None, + hue_kws: dict[str, Any] | None = None, + dropna: bool = False, + legend_out: bool = True, + despine: bool = True, + margin_titles: bool = False, + xlim: tuple[float, float] | None = None, + ylim: tuple[float, float] | None = None, + subplot_kws: dict[str, Any] | None = None, + gridspec_kws: dict[str, Any] | None = None, + ) -> None: ... + def facet_data(self) -> Generator[tuple[tuple[int, int, int], DataFrame]]: ... + def map(self, func: Callable[..., object], *args: str, **kwargs: Any) -> Self: ... + def map_dataframe(self, func: Callable[..., object], *args: str, **kwargs: Any) -> Self: ... + def facet_axis(self, row_i: int, col_j: int, modify_state: bool = True) -> Axes: ... + # `despine` should be kept roughly in line with `seaborn.utils.despine` + def despine( + self, + *, + ax: Axes | None = None, + top: bool = True, + right: bool = True, + left: bool = False, + bottom: bool = False, + offset: int | Mapping[str, int] | None = None, + trim: bool = False, + ) -> Self: ... + def set_axis_labels( + self, x_var: str | None = None, y_var: str | None = None, clear_inner: bool = True, **kwargs: Any + ) -> Self: ... + def set_xlabels(self, label: str | None = None, clear_inner: bool = True, **kwargs: Any) -> Self: ... + def set_ylabels(self, label: str | None = None, clear_inner: bool = True, **kwargs: Any) -> Self: ... + def set_xticklabels(self, labels: Iterable[str | Text] | None = None, step: int | None = None, **kwargs: Any) -> Self: ... + def set_yticklabels(self, labels: Iterable[str | Text] | None = None, **kwargs: Any) -> Self: ... + def set_titles( + self, template: str | None = None, row_template: str | None = None, col_template: str | None = None, **kwargs: Any + ) -> Self: ... + def refline( + self, + *, + x: float | None = None, + y: float | None = None, + color: ColorType = ".5", + linestyle: LineStyleType = "--", + **line_kws: Any, + ) -> Self: ... + @property + def axes(self) -> NDArray[Incomplete]: ... # array of `Axes` + @property + def ax(self) -> Axes: ... + @property + def axes_dict(self) -> dict[Any, Axes]: ... + +class PairGrid(Grid): + x_vars: list[str] + y_vars: list[str] + square_grid: bool + axes: NDArray[Incomplete] # two-dimensional array of `Axes` + data: DataFrame + diag_sharey: bool + diag_vars: list[str] | None + diag_axes: list[Axes] | None + hue_names: list[str] + hue_vals: Series[Any] + hue_kws: dict[str, Any] + palette: _RGBColorPalette + def __init__( + self, + data: DataFrame | SupportsDataFrame, + *, + hue: str | None = None, + vars: Iterable[str] | None = None, + x_vars: Iterable[str] | str | None = None, + y_vars: Iterable[str] | str | None = None, + hue_order: Iterable[str] | None = None, + palette: _Palette | None = None, + hue_kws: dict[str, Any] | None = None, + corner: bool = False, + diag_sharey: bool = True, + height: float = 2.5, + aspect: float = 1, + layout_pad: float = 0.5, + despine: bool = True, + dropna: bool = False, + ) -> None: ... + def map(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_lower(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_upper(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_offdiag(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def map_diag(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + +class JointGrid(_BaseGrid): + ax_joint: Axes + ax_marg_x: Axes + ax_marg_y: Axes + x: Series[Any] + y: Series[Any] + hue: Series[Any] + def __init__( + self, + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + height: float = 6, + ratio: float = 5, + space: float = 0.2, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + dropna: bool = False, + xlim: float | tuple[float, float] | None = None, + ylim: float | tuple[float, float] | None = None, + marginal_ticks: bool = False, + ) -> None: ... + def plot(self, joint_func: Callable[..., object], marginal_func: Callable[..., object], **kwargs: Any) -> Self: ... + def plot_joint(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def plot_marginals(self, func: Callable[..., object], **kwargs: Any) -> Self: ... + def refline( + self, + *, + x: float | None = None, + y: float | None = None, + joint: bool = True, + marginal: bool = True, + color: ColorType = ".5", + linestyle: LineStyleType = "--", + **line_kws: Any, + ) -> Self: ... + def set_axis_labels(self, xlabel: str = "", ylabel: str = "", **kwargs: Any) -> Self: ... + +def pairplot( + data: DataFrame, + *, + hue: str | None = None, + hue_order: Iterable[str] | None = None, + palette: _Palette | None = None, + vars: Iterable[str] | None = None, + x_vars: Iterable[str] | str | None = None, + y_vars: Iterable[str] | str | None = None, + kind: Literal["scatter", "kde", "hist", "reg"] = "scatter", + diag_kind: Literal["auto", "hist", "kde"] | None = "auto", + markers: MarkerType | list[MarkerType] | None = None, + height: float = 2.5, + aspect: float = 1, + corner: bool = False, + dropna: bool = False, + plot_kws: dict[str, Any] | None = None, + diag_kws: dict[str, Any] | None = None, + grid_kws: dict[str, Any] | None = None, + size: float | None = None, # deprecated +) -> PairGrid: ... +def jointplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + kind: Literal["scatter", "kde", "hist", "hex", "reg", "resid"] = "scatter", + height: float = 6, + ratio: float = 5, + space: float = 0.2, + dropna: bool = False, + xlim: float | tuple[float, float] | None = None, + ylim: float | tuple[float, float] | None = None, + color: ColorType | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + marginal_ticks: bool = False, + joint_kws: dict[str, Any] | None = None, + marginal_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> JointGrid: ... diff --git a/stubs/seaborn/seaborn/categorical.pyi b/stubs/seaborn/seaborn/categorical.pyi new file mode 100644 index 000000000000..eed93a807628 --- /dev/null +++ b/stubs/seaborn/seaborn/categorical.pyi @@ -0,0 +1,294 @@ +from collections.abc import Callable, Iterable +from typing import Any, Literal + +from matplotlib.axes import Axes +from matplotlib.typing import ColorType, LineStyleType, MarkerType + +from ._core.typing import ColumnName, DataSource, Default, NormSpec +from .axisgrid import FacetGrid +from .external.kde import _BwMethodType +from .utils import _DataSourceWideForm, _ErrorBar, _Estimator, _Legend, _LogScale, _Palette, _Seed, _Vector + +__all__ = ["catplot", "stripplot", "swarmplot", "boxplot", "violinplot", "boxenplot", "pointplot", "barplot", "countplot"] + +def boxplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + dodge: bool | Literal["auto"] = "auto", + width: float = 0.8, + gap: float = 0, + whis: float | tuple[float, float] = 1.5, + linecolor: ColorType = "auto", + linewidth: float | None = None, + fliersize: float | None = None, + hue_norm: NormSpec = None, + native_scale: bool = False, + log_scale: _LogScale | None = None, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def violinplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + inner: str | None = "box", + split: bool = False, + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + linewidth: float | None = None, + linecolor: ColorType = "auto", + cut: float = 2, + gridsize: int = 100, + bw_method: _BwMethodType = "scott", + bw_adjust: float = 1, + density_norm: Literal["area", "count", "width"] = "area", + common_norm: bool | None = False, + hue_norm: NormSpec = None, + formatter: Callable[[Any], str] | None = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + legend: _Legend = "auto", + scale=..., # deprecated + scale_hue=..., # deprecated + bw=..., # deprecated + inner_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def boxenplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + dodge: bool | Literal["auto"] = "auto", + width: float = 0.8, + gap: float = 0, + linewidth: float | None = None, + linecolor: ColorType | None = None, + width_method: Literal["exponential", "linear", "area"] = "exponential", + k_depth: Literal["tukey", "proportion", "trustworthy", "full"] | int = "tukey", + outlier_prop: float = 0.007, + trust_alpha: float = 0.05, + showfliers: bool = True, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + scale=..., # deprecated + box_kws: dict[str, Any] | None = None, + flier_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def stripplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + jitter: float | Literal[True] = True, + dodge: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + size: float = 5, + edgecolor: ColorType | Default = ..., + linewidth: float = 0, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def swarmplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + dodge: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + size: float = 5, + edgecolor: ColorType | None = None, + linewidth: float = 0, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + warn_thresh: float = 0.05, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def barplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + hue_norm: NormSpec = None, + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + capsize: float = 0, + err_kws: dict[str, Any] | None = None, + ci=..., # deprecated + errcolor=..., # deprecated + errwidth=..., # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def pointplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + hue_norm: NormSpec = None, + markers: MarkerType | list[MarkerType] | Default = ..., + linestyles: LineStyleType | list[LineStyleType] | Default = ..., + dodge: bool = False, + log_scale: _LogScale | None = None, + native_scale: bool = False, + orient: Literal["v", "h", "x", "y"] | None = None, + capsize: float = 0, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + err_kws: dict[str, Any] | None = None, + ci=..., # deprecated + errwidth=..., # deprecated + join=..., # deprecated + scale=..., # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def countplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + saturation: float = 0.75, + fill: bool = True, + hue_norm: NormSpec = None, + stat: Literal["count", "percent", "proportion", "probability"] = "count", + width: float = 0.8, + dodge: bool | Literal["auto"] = "auto", + gap: float = 0, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def catplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + kind: Literal["strip", "swarm", "box", "violin", "boxen", "point", "bar", "count"] = "strip", + estimator: _Estimator = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + seed: _Seed | None = None, + order: Iterable[ColumnName] | None = None, + hue_order: Iterable[ColumnName] | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + col_wrap: int | None = None, + height: float = 5, + aspect: float = 1, + log_scale: _LogScale | None = None, + native_scale: bool = False, + formatter: Callable[[Any], str] | None = None, + orient: Literal["v", "h", "x", "y"] | None = None, + color: ColorType | None = None, + palette: _Palette | None = None, + hue_norm: NormSpec = None, + legend: _Legend = "auto", + legend_out: bool = True, + sharex: bool = True, + sharey: bool = True, + margin_titles: bool = False, + facet_kws: dict[str, Any] | None = None, + ci=..., # deprecated + **kwargs: Any, +) -> FacetGrid: ... diff --git a/stubs/seaborn/seaborn/cm.pyi b/stubs/seaborn/seaborn/cm.pyi new file mode 100644 index 000000000000..85c912b97d2d --- /dev/null +++ b/stubs/seaborn/seaborn/cm.pyi @@ -0,0 +1,15 @@ +from matplotlib.colors import ListedColormap + +# generated +rocket: ListedColormap +mako: ListedColormap +icefire: ListedColormap +vlag: ListedColormap +flare: ListedColormap +crest: ListedColormap +rocket_r: ListedColormap +mako_r: ListedColormap +icefire_r: ListedColormap +vlag_r: ListedColormap +flare_r: ListedColormap +crest_r: ListedColormap diff --git a/stubs/seaborn/seaborn/colors/__init__.pyi b/stubs/seaborn/seaborn/colors/__init__.pyi new file mode 100644 index 000000000000..f2f1b9731393 --- /dev/null +++ b/stubs/seaborn/seaborn/colors/__init__.pyi @@ -0,0 +1,2 @@ +from .crayons import crayons as crayons +from .xkcd_rgb import xkcd_rgb as xkcd_rgb diff --git a/stubs/seaborn/seaborn/colors/crayons.pyi b/stubs/seaborn/seaborn/colors/crayons.pyi new file mode 100644 index 000000000000..c0479d29f98f --- /dev/null +++ b/stubs/seaborn/seaborn/colors/crayons.pyi @@ -0,0 +1 @@ +crayons: dict[str, str] diff --git a/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi b/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi new file mode 100644 index 000000000000..0ac3abc8087c --- /dev/null +++ b/stubs/seaborn/seaborn/colors/xkcd_rgb.pyi @@ -0,0 +1 @@ +xkcd_rgb: dict[str, str] diff --git a/stubs/seaborn/seaborn/distributions.pyi b/stubs/seaborn/seaborn/distributions.pyi new file mode 100644 index 000000000000..036a0d9d4e43 --- /dev/null +++ b/stubs/seaborn/seaborn/distributions.pyi @@ -0,0 +1,171 @@ +from collections.abc import Iterable +from typing import Any, Literal, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import deprecated + +from matplotlib.axes import Axes +from matplotlib.colors import Colormap +from matplotlib.typing import ColorType +from numpy.typing import ArrayLike + +from ._core.typing import ColumnName, DataSource, NormSpec +from .axisgrid import FacetGrid +from .external.kde import _BwMethodType +from .utils import _DataSourceWideForm, _LogScale, _Palette, _Vector + +__all__ = ["displot", "histplot", "kdeplot", "ecdfplot", "rugplot", "distplot"] + +_T = TypeVar("_T") +_OneOrPair: TypeAlias = _T | tuple[_T, _T] + +@type_check_only +class _Fit(Protocol): + def fit(self, a: ArrayLike) -> tuple[ArrayLike, ...]: ... + def pdf(self, x: ArrayLike, *params: ArrayLike) -> ArrayLike: ... + +def histplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + stat: str = "count", + bins: _OneOrPair[str | int | ArrayLike] = "auto", + binwidth: float | tuple[float, float] | None = None, + binrange: _OneOrPair[tuple[float, float]] | None = None, + discrete: bool | None = None, + cumulative: bool = False, + common_bins: bool = True, + common_norm: bool = True, + multiple: Literal["layer", "dodge", "stack", "fill"] = "layer", + element: Literal["bars", "step", "poly"] = "bars", + fill: bool = True, + shrink: float = 1, + kde: bool = False, + kde_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + thresh: float | None = 0, + pthresh: float | None = None, + pmax: float | None = None, + cbar: bool = False, + cbar_ax: Axes | None = None, + cbar_kws: dict[str, Any] | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + log_scale: _LogScale | None = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def kdeplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + fill: bool | None = None, + multiple: Literal["layer", "stack", "fill"] = "layer", + common_norm: bool = True, + common_grid: bool = False, + cumulative: bool = False, + bw_method: _BwMethodType = "scott", + bw_adjust: float = 1, + warn_singular: bool = True, + log_scale: _LogScale | None = None, + levels: int | Iterable[float] = 10, + thresh: float = 0.05, + gridsize: int = 200, + cut: float = 3, + clip: _OneOrPair[tuple[float | None, float | None]] | None = None, + legend: bool = True, + cbar: bool = False, + cbar_ax: Axes | None = None, + cbar_kws: dict[str, Any] | None = None, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def ecdfplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + stat: Literal["proportion", "percent", "count"] = "proportion", + complementary: bool = False, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + log_scale: _LogScale | None = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def rugplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + height: float = 0.025, + expand_margins: bool = True, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + legend: bool = True, + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def displot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + kind: Literal["hist", "kde", "ecdf"] = "hist", + rug: bool = False, + rug_kws: dict[str, Any] | None = None, + log_scale: _LogScale | None = None, + legend: bool = True, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + color: ColorType | None = None, + col_wrap: int | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + height: float = 5, + aspect: float = 1, + facet_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> FacetGrid: ... +@deprecated("Function `distplot` is deprecated and will be removed in seaborn v0.14.0") +def distplot( + a: ArrayLike | None = None, + bins: ArrayLike | None = None, + hist: bool = True, + kde: bool = True, + rug: bool = False, + fit: _Fit | None = None, + hist_kws: dict[str, Any] | None = None, + kde_kws: dict[str, Any] | None = None, + rug_kws: dict[str, Any] | None = None, + fit_kws: dict[str, Any] | None = None, + color: ColorType | None = None, + vertical: bool = False, + norm_hist: bool = False, + axlabel: str | Literal[False] | None = None, + label: str | None = None, + ax: Axes | None = None, + x: ArrayLike | None = None, +) -> Axes: ... diff --git a/stubs/seaborn/seaborn/external/__init__.pyi b/stubs/seaborn/seaborn/external/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/seaborn/seaborn/external/appdirs.pyi b/stubs/seaborn/seaborn/external/appdirs.pyi new file mode 100644 index 000000000000..d9291bbb8d1e --- /dev/null +++ b/stubs/seaborn/seaborn/external/appdirs.pyi @@ -0,0 +1,9 @@ +from typing import Literal + +__version__: str +__version_info__: tuple[int, int, int] +system: str + +def user_cache_dir( + appname: str | None = None, appauthor: Literal[False] | str | None = None, version: str | None = None, opinion: bool = True +) -> str: ... diff --git a/stubs/seaborn/seaborn/external/docscrape.pyi b/stubs/seaborn/seaborn/external/docscrape.pyi new file mode 100644 index 000000000000..5d3e5e1b5807 --- /dev/null +++ b/stubs/seaborn/seaborn/external/docscrape.pyi @@ -0,0 +1,72 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence +from typing import Any, ClassVar, NamedTuple, SupportsIndex, TypeVar, overload + +_S = TypeVar("_S", bound=MutableSequence[str]) + +def strip_blank_lines(l: _S) -> _S: ... + +class Reader: + def __init__(self, data: str | list[str]) -> None: ... + + @overload + def __getitem__(self, n: slice) -> list[str]: ... + @overload + def __getitem__(self, n: SupportsIndex) -> str: ... + + def reset(self) -> None: ... + def read(self) -> str: ... + def seek_next_non_empty_line(self) -> None: ... + def eof(self) -> bool: ... + def read_to_condition(self, condition_func: Callable[[str], bool]) -> list[str]: ... + def read_to_next_empty_line(self) -> list[str]: ... + def read_to_next_unindented_line(self) -> list[str]: ... + def peek(self, n: int = 0) -> str: ... + def is_empty(self) -> bool: ... + +class ParseError(Exception): ... + +class Parameter(NamedTuple): + name: str + type: str + desc: list[str] + +class NumpyDocString(Mapping[str, Any]): + sections: ClassVar[dict[str, Any]] + def __init__(self, docstring: str, config: Unused = {}) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + empty_description: str + +def indent(str: str | None, indent: int = 4) -> str: ... +def dedent_lines(lines: Iterable[str]) -> list[str]: ... +def header(text: str, style: str = "-") -> str: ... + +class FunctionDoc(NumpyDocString): + def __init__(self, func: object, role: str = "func", doc: str | None = None, config: Unused = {}) -> None: ... + def get_func(self) -> tuple[Incomplete, str]: ... + +class ClassDoc(NumpyDocString): + extra_public_methods: list[str] + show_inherited_members: bool + + @overload + def __init__( + self, cls: None, doc: str, modulename: str = "", func_doc: type[FunctionDoc] = ..., config: Mapping[str, Any] = {} + ) -> None: ... + @overload + def __init__( + self, + cls: type, + doc: str | None = None, + modulename: str = "", + func_doc: type[FunctionDoc] = ..., + config: Mapping[str, Any] = {}, + ) -> None: ... + + @property + def methods(self) -> list[str]: ... + @property + def properties(self) -> list[str]: ... diff --git a/stubs/seaborn/seaborn/external/husl.pyi b/stubs/seaborn/seaborn/external/husl.pyi new file mode 100644 index 000000000000..f76e09c84764 --- /dev/null +++ b/stubs/seaborn/seaborn/external/husl.pyi @@ -0,0 +1,42 @@ +from collections.abc import Iterable + +m: list[list[float]] +m_inv: list[list[float]] +refX: float +refY: float +refZ: float +refU: float +refV: float +lab_e: float +lab_k: float + +def husl_to_rgb(h: float, s: float, l: float) -> list[float]: ... +def husl_to_hex(h: float, s: float, l: float) -> str: ... +def rgb_to_husl(r: float, g: float, b: float) -> list[float]: ... +def hex_to_husl(hex: str) -> list[float]: ... +def huslp_to_rgb(h: float, s: float, l: float) -> list[float]: ... +def huslp_to_hex(h: float, s: float, l: float) -> str: ... +def rgb_to_huslp(r: float, g: float, b: float) -> list[float]: ... +def hex_to_huslp(hex: str) -> list[float]: ... +def lch_to_rgb(l: float, c: float, h: float) -> list[float]: ... +def rgb_to_lch(r: float, g: float, b: float) -> list[float]: ... +def max_chroma(L: float, H: float) -> float: ... +def max_chroma_pastel(L: float) -> float: ... +def dot_product(a: Iterable[float], b: Iterable[float]) -> float: ... +def f(t: float) -> float: ... +def f_inv(t: float) -> float: ... +def from_linear(c: float) -> float: ... +def to_linear(c: float) -> float: ... +def rgb_prepare(triple: Iterable[float]) -> list[int]: ... +def hex_to_rgb(hex: str) -> list[float]: ... +def rgb_to_hex(triple: Iterable[float]) -> str: ... +def xyz_to_rgb(triple: Iterable[float]) -> list[float]: ... +def rgb_to_xyz(triple: Iterable[float]) -> list[float]: ... +def xyz_to_luv(triple: Iterable[float]) -> list[float]: ... +def luv_to_xyz(triple: Iterable[float]) -> list[float]: ... +def luv_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_luv(triple: Iterable[float]) -> list[float]: ... +def husl_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_husl(triple: Iterable[float]) -> list[float]: ... +def huslp_to_lch(triple: Iterable[float]) -> list[float]: ... +def lch_to_huslp(triple: Iterable[float]) -> list[float]: ... diff --git a/stubs/seaborn/seaborn/external/kde.pyi b/stubs/seaborn/seaborn/external/kde.pyi new file mode 100644 index 000000000000..76769a3fd5f8 --- /dev/null +++ b/stubs/seaborn/seaborn/external/kde.pyi @@ -0,0 +1,43 @@ +from collections.abc import Callable +from typing import Any, Literal, Protocol, TypeAlias, type_check_only + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +__all__ = ["gaussian_kde"] + +# define a "Gaussian KDE" protocol so that we can also pass `scipy.stats.gaussian_kde` to +# functions that expect it without adding a dependency on scipy +@type_check_only +class _GaussianKDELike(Protocol): + dataset: NDArray[np.float64] + def __init__(self, dataset: ArrayLike, bw_method: Any | None = ..., weights: ArrayLike | None = ...) -> None: ... + def evaluate(self, points: ArrayLike) -> NDArray[Any]: ... + def __call__(self, points: ArrayLike) -> NDArray[Any]: ... + def scotts_factor(self) -> float: ... + def silverman_factor(self) -> float: ... + def covariance_factor(self) -> float: ... + def pdf(self, x: ArrayLike) -> NDArray[Any]: ... + def set_bandwidth(self, bw_method: Any | None = ...) -> None: ... + @property + def weights(self) -> NDArray[Any]: ... + @property + def neff(self) -> NDArray[Any]: ... + +_Scalar: TypeAlias = float | np.number[Any] +_BwMethodType: TypeAlias = Literal["scott", "silverman"] | Callable[[_GaussianKDELike], _Scalar] | _Scalar | None + +class gaussian_kde: + dataset: NDArray[np.float64] + def __init__(self, dataset: ArrayLike, bw_method: _BwMethodType = None, weights: ArrayLike | None = None) -> None: ... + def evaluate(self, points: ArrayLike) -> NDArray[np.float64]: ... + __call__ = evaluate + def scotts_factor(self) -> float: ... + def silverman_factor(self) -> float: ... + covariance_factor = scotts_factor + def set_bandwidth(self, bw_method: _BwMethodType = None) -> None: ... + def pdf(self, x: ArrayLike) -> NDArray[np.float64]: ... + @property + def weights(self) -> NDArray[np.float64]: ... + @property + def neff(self) -> NDArray[np.float64]: ... diff --git a/stubs/seaborn/seaborn/external/version.pyi b/stubs/seaborn/seaborn/external/version.pyi new file mode 100644 index 000000000000..fb9d9b3b11a3 --- /dev/null +++ b/stubs/seaborn/seaborn/external/version.pyi @@ -0,0 +1,45 @@ +__all__ = ["Version", "InvalidVersion", "VERSION_PATTERN"] + +class InvalidVersion(ValueError): ... + +class _BaseVersion: + def __hash__(self) -> int: ... + def __lt__(self, other: _BaseVersion) -> bool: ... + def __le__(self, other: _BaseVersion) -> bool: ... + def __eq__(self, other: object) -> bool: ... + def __ge__(self, other: _BaseVersion) -> bool: ... + def __gt__(self, other: _BaseVersion) -> bool: ... + def __ne__(self, other: object) -> bool: ... + +VERSION_PATTERN: str + +class Version(_BaseVersion): + def __init__(self, version: str) -> None: ... + @property + def epoch(self) -> int: ... + @property + def release(self) -> tuple[int, ...]: ... + @property + def pre(self) -> tuple[str, int] | None: ... + @property + def post(self) -> int | None: ... + @property + def dev(self) -> int | None: ... + @property + def local(self) -> str | None: ... + @property + def public(self) -> str: ... + @property + def base_version(self) -> str: ... + @property + def is_prerelease(self) -> bool: ... + @property + def is_postrelease(self) -> bool: ... + @property + def is_devrelease(self) -> bool: ... + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... diff --git a/stubs/seaborn/seaborn/matrix.pyi b/stubs/seaborn/seaborn/matrix.pyi new file mode 100644 index 000000000000..50214ffaaae3 --- /dev/null +++ b/stubs/seaborn/seaborn/matrix.pyi @@ -0,0 +1,220 @@ +from _typeshed import Incomplete +from collections.abc import Hashable, Iterable, Mapping, Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Self + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.colors import Colormap, ListedColormap, Normalize +from matplotlib.gridspec import GridSpec +from matplotlib.typing import ColorType +from numpy._typing import _ArrayLikeInt_co +from numpy.typing import ArrayLike, NDArray + +from .axisgrid import Grid + +# pandas._typing.ListLikeU is partially Unknown +_ListLikeU: TypeAlias = Sequence[Incomplete] | NDArray[Incomplete] | pd.Series[Incomplete] | pd.Index[Incomplete] +_ConvertibleToDataFrame: TypeAlias = ( + _ListLikeU + | pd.DataFrame + | dict[Incomplete, Incomplete] + | Iterable[_ListLikeU | tuple[Hashable, _ListLikeU] | dict[Incomplete, Incomplete]] + | None +) +_FlatOrNestedSequenceOfColors: TypeAlias = ( + Sequence[ColorType] + | Sequence[Iterable[ColorType]] + | NDArray[Incomplete] + | pd.Index[Incomplete] + | pd.Series[Incomplete] + | pd.DataFrame +) + +__all__ = ["heatmap", "clustermap"] + +def heatmap( + data: pd.DataFrame | ArrayLike, + *, + vmin: float | None = None, + vmax: float | None = None, + cmap: str | list[ColorType] | Colormap | None = None, + center: float | None = None, + robust: bool = False, + annot: bool | ArrayLike | None = None, + fmt: str = ".2g", + annot_kws: dict[str, Incomplete] | None = None, + linewidths: float = 0, + linecolor: ColorType = "white", + cbar: bool = True, + cbar_kws: dict[str, Incomplete] | None = None, + cbar_ax: Axes | None = None, + square: bool = False, + xticklabels: Literal["auto"] | bool | int | Sequence[str] = "auto", + yticklabels: Literal["auto"] | bool | int | Sequence[str] = "auto", + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + ax: Axes | None = None, + # Kwargs below passed to matplotlib.axes.Axes.pcolormesh + alpha: float | None = None, + norm: str | Normalize | None = None, + shading: Literal["flat", "nearest", "gouraud", "auto"] | None = None, + antialiased: bool = False, + **kwargs, +) -> Axes: ... + +@type_check_only +class _Dendogram(TypedDict): + icoord: list[list[float]] + dcoord: list[list[float]] + ivl: list[str] + leaves: list[int] + color_list: list[str] + leaves_color_list: list[str] + +class _DendrogramPlotter: + axis: int + array: NDArray[np.floating] + data: pd.DataFrame + shape: tuple[int, int] + metric: str + method: str + label: bool + rotate: bool + linkage: NDArray[np.floating] + dendrogram: _Dendogram + xticks: list[float] | NDArray[np.floating] + yticks: list[float] | NDArray[np.floating] + xticklabels: list[str] + yticklabels: list[str] + ylabel: str + xlabel: str + dependent_coord: list[list[float]] + independent_coord: list[list[float]] + def __init__( + self, + data: pd.DataFrame, + linkage: NDArray[np.floating] | None, + metric: str, + method: str, + axis: int, + label: bool, + rotate: bool, + ) -> None: ... + @property + def calculated_linkage(self) -> NDArray[np.float64]: ... + def calculate_dendrogram(self) -> _Dendogram: ... + @property + def reordered_ind(self) -> list[int]: ... + def plot(self, ax: Axes, tree_kws: dict[str, Incomplete]) -> Self: ... + +def dendrogram( + data: pd.DataFrame, + *, + linkage: NDArray[np.floating] | None = None, + axis: int = 1, + label: bool = True, + metric: str = "euclidean", + method: str = "average", + rotate: bool = False, + tree_kws: dict[str, Incomplete] | None = None, + ax: Axes | None = None, +) -> _DendrogramPlotter: ... + +class ClusterGrid(Grid): + data: pd.DataFrame + data2d: pd.DataFrame + mask: pd.DataFrame + row_colors: list[list[tuple[float, float, float]]] | None + row_color_labels: list[str] | None + col_colors: list[list[tuple[float, float, float]]] | None + col_color_labels: list[str] | None + gs: GridSpec + ax_row_dendrogram: Axes + ax_col_dendrogram: Axes + ax_row_colors: Axes | None + ax_col_colors: Axes | None + ax_heatmap: Axes + ax_cbar: Axes | None + cax: Axes | None + cbar_pos: tuple[float, float, float, float] | None + dendrogram_row: _DendrogramPlotter | None + dendrogram_col: _DendrogramPlotter | None + def __init__( + self, + data: _ConvertibleToDataFrame, + pivot_kws: Mapping[str, Incomplete] | None = None, + z_score: int | None = None, + standard_scale: int | None = None, + figsize: tuple[float, float] | None = None, + row_colors: _FlatOrNestedSequenceOfColors | None = None, + col_colors: _FlatOrNestedSequenceOfColors | None = None, + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + dendrogram_ratio: float | tuple[float, float] | None = None, + colors_ratio: float | tuple[float, float] | None = None, + cbar_pos: tuple[float, float, float, float] | None = None, + ) -> None: ... + def format_data( + self, + data: pd.DataFrame, + pivot_kws: Mapping[str, Incomplete] | None, + z_score: int | None = None, + standard_scale: int | None = None, + ) -> pd.DataFrame: ... + @staticmethod + def z_score(data2d: pd.DataFrame, axis: int = 1) -> pd.DataFrame: ... + @staticmethod + def standard_scale(data2d: pd.DataFrame, axis: int = 1) -> pd.DataFrame: ... + def dim_ratios(self, colors: ArrayLike | None, dendrogram_ratio: float, colors_ratio: float) -> list[float]: ... + @staticmethod + def color_list_to_matrix_and_cmap( + colors: _FlatOrNestedSequenceOfColors, ind: _ArrayLikeInt_co, axis: int = 0 + ) -> tuple[NDArray[np.int_], ListedColormap]: ... + def plot_dendrograms( + self, + row_cluster: bool, + col_cluster: bool, + metric: str, + method: str, + row_linkage: NDArray[np.floating] | None, + col_linkage: NDArray[np.floating] | None, + tree_kws: dict[str, Incomplete] | None, + ) -> None: ... + def plot_colors(self, xind: _ArrayLikeInt_co, yind: _ArrayLikeInt_co, **kws) -> None: ... + def plot_matrix(self, colorbar_kws: dict[str, Incomplete], xind: _ArrayLikeInt_co, yind: _ArrayLikeInt_co, **kws) -> None: ... + def plot( + self, + metric: str, + method: str, + colorbar_kws: dict[str, Incomplete] | None, + row_cluster: bool, + col_cluster: bool, + row_linkage: NDArray[np.floating] | None, + col_linkage: NDArray[np.floating] | None, + tree_kws: dict[str, Incomplete] | None, + **kws, + ) -> Self: ... + +def clustermap( + data: _ConvertibleToDataFrame, + *, + pivot_kws: dict[str, Incomplete] | None = None, + method: str = "average", + metric: str = "euclidean", + z_score: int | None = None, + standard_scale: int | None = None, + figsize: tuple[float, float] | None = (10, 10), + cbar_kws: dict[str, Incomplete] | None = None, + row_cluster: bool = True, + col_cluster: bool = True, + row_linkage: NDArray[np.floating] | None = None, + col_linkage: NDArray[np.floating] | None = None, + row_colors: _FlatOrNestedSequenceOfColors | None = None, + col_colors: _FlatOrNestedSequenceOfColors | None = None, + mask: NDArray[np.bool_] | pd.DataFrame | None = None, + dendrogram_ratio: float | tuple[float, float] = 0.2, + colors_ratio: float | tuple[float, float] = 0.03, + cbar_pos: tuple[float, float, float, float] | None = (0.02, 0.8, 0.05, 0.18), + tree_kws: dict[str, Incomplete] | None = None, + **kwargs, +) -> ClusterGrid: ... diff --git a/stubs/seaborn/seaborn/miscplot.pyi b/stubs/seaborn/seaborn/miscplot.pyi new file mode 100644 index 000000000000..82e8dbac5e2c --- /dev/null +++ b/stubs/seaborn/seaborn/miscplot.pyi @@ -0,0 +1,9 @@ +from _typeshed import Unused +from collections.abc import Sequence + +from matplotlib.typing import ColorType + +__all__ = ["palplot", "dogplot"] + +def palplot(pal: Sequence[ColorType], size: int = 1) -> None: ... +def dogplot(*_: Unused, **__: Unused) -> None: ... diff --git a/stubs/seaborn/seaborn/objects.pyi b/stubs/seaborn/seaborn/objects.pyi new file mode 100644 index 000000000000..4f757e0bba32 --- /dev/null +++ b/stubs/seaborn/seaborn/objects.pyi @@ -0,0 +1,21 @@ +from seaborn._core.moves import Dodge as Dodge, Jitter as Jitter, Move as Move, Norm as Norm, Shift as Shift, Stack as Stack +from seaborn._core.plot import Plot as Plot +from seaborn._core.scales import ( + Boolean as Boolean, + Continuous as Continuous, + Nominal as Nominal, + Scale as Scale, + Temporal as Temporal, +) +from seaborn._marks.area import Area as Area, Band as Band +from seaborn._marks.bar import Bar as Bar, Bars as Bars +from seaborn._marks.base import Mark as Mark +from seaborn._marks.dot import Dot as Dot, Dots as Dots +from seaborn._marks.line import Dash as Dash, Line as Line, Lines as Lines, Path as Path, Paths as Paths, Range as Range +from seaborn._marks.text import Text as Text +from seaborn._stats.aggregation import Agg as Agg, Est as Est +from seaborn._stats.base import Stat as Stat +from seaborn._stats.counting import Count as Count, Hist as Hist +from seaborn._stats.density import KDE as KDE +from seaborn._stats.order import Perc as Perc +from seaborn._stats.regression import PolyFit as PolyFit diff --git a/stubs/seaborn/seaborn/palettes.pyi b/stubs/seaborn/seaborn/palettes.pyi new file mode 100644 index 000000000000..c64d4d1234fe --- /dev/null +++ b/stubs/seaborn/seaborn/palettes.pyi @@ -0,0 +1,159 @@ +from collections.abc import Iterable, Sequence +from typing import Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from matplotlib.colors import Colormap, LinearSegmentedColormap, ListedColormap +from matplotlib.typing import ColorType + +__all__ = [ + "color_palette", + "hls_palette", + "husl_palette", + "mpl_palette", + "dark_palette", + "light_palette", + "diverging_palette", + "blend_palette", + "xkcd_palette", + "crayon_palette", + "cubehelix_palette", + "set_color_codes", +] + +_ColorT = TypeVar("_ColorT", bound=ColorType) + +SEABORN_PALETTES: dict[str, list[str]] +MPL_QUAL_PALS: dict[str, int] +QUAL_PALETTE_SIZES: dict[str, int] +QUAL_PALETTES: list[str] + +class _ColorPalette(list[_ColorT]): + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def as_hex(self) -> _ColorPalette[str]: ... + +_RGBColorPalette: TypeAlias = _ColorPalette[tuple[float, float, float]] +_SeabornPaletteName: TypeAlias = Literal[ + "deep", "deep6", "muted", "muted6", "pastel", "pastel6", "bright", "bright6", "dark", "dark6", "colorblind", "colorblind6" +] + +@overload +def color_palette( # type: ignore[overload-overlap] + palette: _SeabornPaletteName | None = None, n_colors: int | None = None, desat: float | None = None, *, as_cmap: Literal[True] +) -> list[str]: ... # this might be a bug in seaborn because we expect the return type to be a Colormap instance +@overload +def color_palette( + palette: str | Sequence[ColorType], n_colors: int | None = None, desat: float | None = None, *, as_cmap: Literal[True] +) -> Colormap: ... +@overload +def color_palette( + palette: str | Sequence[ColorType] | None = None, + n_colors: int | None = None, + desat: float | None = None, + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +@overload +def hls_palette( + n_colors: int = 6, h: float = 0.01, l: float = 0.6, s: float = 0.65, *, as_cmap: Literal[True] +) -> ListedColormap: ... +@overload +def hls_palette( + n_colors: int = 6, h: float = 0.01, l: float = 0.6, s: float = 0.65, as_cmap: Literal[False] = False +) -> _RGBColorPalette: ... + +@overload +def husl_palette( + n_colors: int = 6, h: float = 0.01, s: float = 0.9, l: float = 0.65, *, as_cmap: Literal[True] +) -> ListedColormap: ... +@overload +def husl_palette( + n_colors: int = 6, h: float = 0.01, s: float = 0.9, l: float = 0.65, as_cmap: Literal[False] = False +) -> _RGBColorPalette: ... + +@overload +def mpl_palette(name: str, n_colors: int = 6, *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def mpl_palette(name: str, n_colors: int = 6, as_cmap: Literal[False] = False) -> _RGBColorPalette: ... + +@overload +def dark_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def dark_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +@overload +def light_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def light_palette( + color: ColorType, n_colors: int = 6, reverse: bool = False, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +@overload +def diverging_palette( + h_neg: float, + h_pos: float, + s: float = 75, + l: float = 50, + sep: int = 1, + n: int = 6, + center: Literal["light", "dark"] = "light", + *, + as_cmap: Literal[True], +) -> LinearSegmentedColormap: ... +@overload +def diverging_palette( + h_neg: float, + h_pos: float, + s: float = 75, + l: float = 50, + sep: int = 1, + n: int = 6, + center: Literal["light", "dark"] = "light", + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +@overload +def blend_palette( + colors: Iterable[ColorType], n_colors: int = 6, *, as_cmap: Literal[True], input: str = "rgb" +) -> LinearSegmentedColormap: ... +@overload +def blend_palette( + colors: Iterable[ColorType], n_colors: int = 6, as_cmap: Literal[False] = False, input: str = "rgb" +) -> _RGBColorPalette: ... + +def xkcd_palette(colors: Iterable[str]) -> _RGBColorPalette: ... +def crayon_palette(colors: Iterable[str]) -> _RGBColorPalette: ... + +@overload +def cubehelix_palette( + n_colors: int = 6, + start: float = 0, + rot: float = 0.4, + gamma: float = 1.0, + hue: float = 0.8, + light: float = 0.85, + dark: float = 0.15, + reverse: bool = False, + *, + as_cmap: Literal[True], +) -> ListedColormap: ... +@overload +def cubehelix_palette( + n_colors: int = 6, + start: float = 0, + rot: float = 0.4, + gamma: float = 1.0, + hue: float = 0.8, + light: float = 0.85, + dark: float = 0.15, + reverse: bool = False, + as_cmap: Literal[False] = False, +) -> _RGBColorPalette: ... + +def set_color_codes(palette: str = "deep") -> None: ... diff --git a/stubs/seaborn/seaborn/rcmod.pyi b/stubs/seaborn/seaborn/rcmod.pyi new file mode 100644 index 000000000000..04c669d74f0e --- /dev/null +++ b/stubs/seaborn/seaborn/rcmod.pyi @@ -0,0 +1,74 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from typing import Any, Literal, TypeVar +from typing_extensions import deprecated + +from matplotlib.typing import ColorType + +__all__ = [ + "set_theme", + "set", + "reset_defaults", + "reset_orig", + "axes_style", + "set_style", + "plotting_context", + "set_context", + "set_palette", +] + +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") +_F = TypeVar("_F", bound=Callable[..., Any]) + +def set_theme( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] = "notebook", + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] = "darkgrid", + palette: str | Sequence[ColorType] | None = "deep", + font: str = "sans-serif", + font_scale: float = 1, + color_codes: bool = True, + rc: dict[str, Any] | None = None, +) -> None: ... +@deprecated("Function `set` is deprecated in favor of `set_theme`") +def set( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] = "notebook", + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] = "darkgrid", + palette: str | Sequence[ColorType] | None = "deep", + font: str = "sans-serif", + font_scale: float = 1, + color_codes: bool = True, + rc: dict[str, Any] | None = None, +) -> None: ... +def reset_defaults() -> None: ... +def reset_orig() -> None: ... +def axes_style( + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] | None = None, + rc: dict[str, Any] | None = None, +) -> _AxesStyle[str, Any]: ... +def set_style( + style: Literal["white", "dark", "whitegrid", "darkgrid", "ticks"] | dict[str, Any] | None = None, + rc: dict[str, Any] | None = None, +) -> None: ... +def plotting_context( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] | None = None, + font_scale: float = 1, + rc: dict[str, Any] | None = None, +) -> _PlottingContext[str, Any]: ... +def set_context( + context: Literal["paper", "notebook", "talk", "poster"] | dict[str, Any] | None = None, + font_scale: float = 1, + rc: dict[str, Any] | None = None, +) -> None: ... + +class _RCAesthetics(dict[_KT, _VT]): + def __enter__(self) -> None: ... + def __exit__(self, exc_type: Unused, exc_value: Unused, exc_tb: Unused) -> None: ... + def __call__(self, func: _F) -> _F: ... + +class _AxesStyle(_RCAesthetics[_KT, _VT]): ... +class _PlottingContext(_RCAesthetics[_KT, _VT]): ... + +def set_palette( + palette: str | Sequence[ColorType] | None, n_colors: int | None = None, desat: float | None = None, color_codes: bool = False +) -> None: ... diff --git a/stubs/seaborn/seaborn/regression.pyi b/stubs/seaborn/seaborn/regression.pyi new file mode 100644 index 000000000000..615035fa1206 --- /dev/null +++ b/stubs/seaborn/seaborn/regression.pyi @@ -0,0 +1,163 @@ +from _typeshed import Incomplete +from collections.abc import Callable, Iterable +from typing import Any, Literal, TypeAlias, overload + +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.typing import ColorType +from numpy.typing import NDArray + +from .axisgrid import FacetGrid +from .utils import _Palette, _Seed + +__all__ = ["lmplot", "regplot", "residplot"] + +_Vector: TypeAlias = list[Incomplete] | pd.Series[Incomplete] | pd.Index[Incomplete] | NDArray[Incomplete] + +def lmplot( + data: pd.DataFrame, + *, + x: str | None = None, + y: str | None = None, + hue: str | None = None, + col: str | None = None, + row: str | None = None, + palette: _Palette | None = None, + col_wrap: int | None = None, + height: float = 5, + aspect: float = 1, + markers: str = "o", + sharex: bool | Literal["col", "row"] | None = None, # deprecated + sharey: bool | Literal["col", "row"] | None = None, # deprecated + hue_order: Iterable[str] | None = None, + col_order: Iterable[str] | None = None, + row_order: Iterable[str] | None = None, + legend: bool = True, + legend_out: bool | None = None, # deprecated + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: str | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: str | None = None, + y_partial: str | None = None, + truncate: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + facet_kws: dict[str, Any] | None = None, +) -> FacetGrid: ... + +@overload +def regplot( + data: None = None, + *, + x: _Vector | None = None, + y: _Vector | None = None, + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: _Vector | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: _Vector | None = None, + y_partial: _Vector | None = None, + truncate: bool = True, + dropna: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + label: str | None = None, + color: ColorType | None = None, + marker: str = "o", + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... +@overload +def regplot( + data: pd.DataFrame, + *, + x: str | _Vector | None = None, + y: str | _Vector | None = None, + x_estimator: Callable[[Incomplete], Incomplete] | None = None, + x_bins: int | _Vector | None = None, + x_ci: Literal["ci", "sd"] | int | None = "ci", + scatter: bool = True, + fit_reg: bool = True, + ci: int | None = 95, + n_boot: int = 1000, + units: str | _Vector | None = None, + seed: _Seed | None = None, + order: int = 1, + logistic: bool = False, + lowess: bool = False, + robust: bool = False, + logx: bool = False, + x_partial: str | _Vector | None = None, + y_partial: str | _Vector | None = None, + truncate: bool = True, + dropna: bool = True, + x_jitter: float | None = None, + y_jitter: float | None = None, + label: str | None = None, + color: ColorType | None = None, + marker: str = "o", + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... + +@overload +def residplot( + data: None = None, + *, + x: _Vector | None = None, + y: _Vector | None = None, + x_partial: _Vector | None = None, + y_partial: _Vector | None = None, + lowess: bool = False, + order: int = 1, + robust: bool = False, + dropna: bool = True, + label: str | None = None, + color: ColorType | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... +@overload +def residplot( + data: pd.DataFrame, + *, + x: str | _Vector | None = None, + y: str | _Vector | None = None, + x_partial: str | _Vector | None = None, + y_partial: str | _Vector | None = None, + lowess: bool = False, + order: int = 1, + robust: bool = False, + dropna: bool = True, + label: str | None = None, + color: ColorType | None = None, + scatter_kws: dict[str, Any] | None = None, + line_kws: dict[str, Any] | None = None, + ax: Axes | None = None, +) -> Axes: ... diff --git a/stubs/seaborn/seaborn/relational.pyi b/stubs/seaborn/seaborn/relational.pyi new file mode 100644 index 000000000000..7b4ebc48bf2c --- /dev/null +++ b/stubs/seaborn/seaborn/relational.pyi @@ -0,0 +1,102 @@ +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, Literal, TypeAlias + +from matplotlib.axes import Axes +from matplotlib.colors import Colormap +from matplotlib.typing import MarkerType + +from ._core.typing import ColumnName, DataSource, NormSpec +from .axisgrid import FacetGrid +from .utils import _DataSourceWideForm, _ErrorBar, _Estimator, _Legend, _Palette, _Seed, _Vector + +__all__ = ["relplot", "scatterplot", "lineplot"] + +_Sizes: TypeAlias = list[int] | list[float] | dict[str, int] | dict[str, float] | tuple[float, float] +_DashType: TypeAlias = tuple[None, None] | Sequence[float] # See matplotlib.lines.Line2D.set_dashes +# "dashes" and "markers" require dict but we use mapping to avoid long unions because dict is invariant in its value type +_Dashes: TypeAlias = bool | Sequence[_DashType] | Mapping[Any, _DashType] +_Markers: TypeAlias = bool | Sequence[MarkerType] | Mapping[Any, MarkerType] + +def lineplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + dashes: _Dashes | None = True, + markers: _Markers | None = None, + style_order: Iterable[ColumnName] | None = None, + estimator: _Estimator | None = "mean", + errorbar: _ErrorBar | None = ("ci", 95), + n_boot: int = 1000, + seed: _Seed | None = None, + orient: Literal["x", "y"] = "x", + sort: bool = True, + err_style: Literal["band", "bars"] = "band", + err_kws: dict[str, Any] | None = None, + legend: _Legend = "auto", + ci: str | int | None = "deprecated", # deprecated + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def scatterplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + markers: _Markers | None = True, + style_order: Iterable[ColumnName] | None = None, + legend: _Legend = "auto", + ax: Axes | None = None, + **kwargs: Any, +) -> Axes: ... +def relplot( + data: DataSource | _DataSourceWideForm | None = None, + *, + x: ColumnName | _Vector | None = None, + y: ColumnName | _Vector | None = None, + hue: ColumnName | _Vector | None = None, + size: ColumnName | _Vector | None = None, + style: ColumnName | _Vector | None = None, + units: ColumnName | _Vector | None = None, + weights: ColumnName | _Vector | None = None, + row: ColumnName | _Vector | None = None, + col: ColumnName | _Vector | None = None, + col_wrap: int | None = None, + row_order: Iterable[ColumnName] | None = None, + col_order: Iterable[ColumnName] | None = None, + palette: _Palette | Colormap | None = None, + hue_order: Iterable[ColumnName] | None = None, + hue_norm: NormSpec = None, + sizes: _Sizes | None = None, + size_order: Iterable[ColumnName] | None = None, + size_norm: NormSpec = None, + markers: _Markers | None = None, + dashes: _Dashes | None = None, + style_order: Iterable[ColumnName] | None = None, + legend: _Legend = "auto", + kind: Literal["scatter", "line"] = "scatter", + height: float = 5, + aspect: float = 1, + facet_kws: dict[str, Any] | None = None, + **kwargs: Any, +) -> FacetGrid: ... diff --git a/stubs/seaborn/seaborn/utils.pyi b/stubs/seaborn/seaborn/utils.pyi new file mode 100644 index 000000000000..bd8cdecc9b8c --- /dev/null +++ b/stubs/seaborn/seaborn/utils.pyi @@ -0,0 +1,115 @@ +import datetime as dt +from _typeshed import Incomplete, SupportsGetItem +from collections.abc import Callable, Iterable, Mapping, Sequence +from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import deprecated + +import numpy as np +import pandas as pd +from matplotlib.axes import Axes +from matplotlib.figure import Figure +from matplotlib.legend import Legend +from matplotlib.text import Text +from matplotlib.ticker import Locator +from matplotlib.typing import ColorType +from numpy.typing import ArrayLike, NDArray +from pandas import DataFrame + +from .axisgrid import Grid + +__all__ = [ + "desaturate", + "saturate", + "set_hls_values", + "move_legend", + "despine", + "get_dataset_names", + "get_data_home", + "load_dataset", +] + +_VectorT = TypeVar("_VectorT", bound=SupportsGetItem[Any, Any]) + +# Type aliases used heavily throughout seaborn +_ErrorBar: TypeAlias = str | tuple[str, float] | Callable[[Iterable[float]], tuple[float, float]] # noqa: Y047 +_Estimator: TypeAlias = str | Callable[..., Incomplete] # noqa: Y047 +_Legend: TypeAlias = Literal["auto", "brief", "full"] | bool # noqa: Y047 +_LogScale: TypeAlias = bool | float | tuple[bool | float, bool | float] # noqa: Y047 +# `palette` requires dict but we use mapping to avoid a very long union because dict is invariant in its value type +_Palette: TypeAlias = str | Sequence[ColorType] | Mapping[Any, ColorType] # noqa: Y047 +_Seed: TypeAlias = int | np.random.Generator | np.random.RandomState # noqa: Y047 +_Scalar: TypeAlias = ( + # numeric + float + | complex + | np.number[Any] + # categorical + | bool + | str + | bytes + | None + # dates + | dt.date + | dt.datetime + | dt.timedelta + | pd.Timestamp + | pd.Timedelta +) +_Vector: TypeAlias = Iterable[_Scalar] +_DataSourceWideForm: TypeAlias = ( # noqa: Y047 + # Mapping of keys to "convertible to pd.Series" vectors + Mapping[Any, _Vector] + # Sequence of "convertible to pd.Series" vectors + | Sequence[_Vector] + # A "convertible to pd.DataFrame" table + | Mapping[Any, Mapping[Any, _Scalar]] + | NDArray[Any] + # Flat "convertible to pd.Series" vector of scalars + | Sequence[_Scalar] +) + +DATASET_SOURCE: str +DATASET_NAMES_URL: str + +def ci_to_errsize(cis: ArrayLike, heights: ArrayLike) -> NDArray[np.float64]: ... +def desaturate(color: ColorType, prop: float) -> tuple[float, float, float]: ... +def saturate(color: ColorType) -> tuple[float, float, float]: ... +def set_hls_values( + color: ColorType, h: float | None = None, l: float | None = None, s: float | None = None +) -> tuple[float, float, float]: ... +@deprecated("Function `axlabel` is deprecated and will be removed in a future version") +def axlabel(xlabel: str, ylabel: str, **kwargs: Any) -> None: ... +def remove_na(vector: _VectorT) -> _VectorT: ... +def get_color_cycle() -> list[str]: ... + +# `despine` should be kept roughly in line with `seaborn.axisgrid.FacetGrid.despine` +def despine( + fig: Figure | None = None, + ax: Axes | None = None, + top: bool = True, + right: bool = True, + left: bool = False, + bottom: bool = False, + offset: int | Mapping[str, int] | None = None, + trim: bool = False, +) -> None: ... +def move_legend(obj: Grid | Axes | Figure, loc: str | int, **kwargs: Any) -> None: ... +def ci( + a: float | ArrayLike, which: float | ArrayLike = 95, axis: SupportsIndex | Sequence[SupportsIndex] | None = None +) -> NDArray[np.float64]: ... +def get_dataset_names() -> list[str]: ... +def get_data_home(data_home: str | None = None) -> str: ... +def load_dataset(name: str, cache: bool = True, data_home: str | None = None, **kws: Any) -> DataFrame: ... +def axis_ticklabels_overlap(labels: Iterable[Text]) -> bool: ... +def axes_ticklabels_overlap(ax: Axes) -> tuple[bool, bool]: ... +def locator_to_legend_entries(locator: Locator, limits: Iterable[float], dtype) -> tuple[list[Incomplete], list[str]]: ... + +@overload +def relative_luminance(color: ColorType) -> float: ... # type: ignore[overload-overlap] +@overload +def relative_luminance(color: Sequence[ColorType]) -> NDArray[np.float64]: ... +@overload +def relative_luminance(color: ColorType | Sequence[ColorType] | ArrayLike) -> float | NDArray[np.float64]: ... + +def to_utf8(obj: object) -> str: ... +def adjust_legend_subtitles(legend: Legend) -> None: ... # not public API diff --git a/stubs/seaborn/seaborn/widgets.pyi b/stubs/seaborn/seaborn/widgets.pyi new file mode 100644 index 000000000000..64fd59ff27ab --- /dev/null +++ b/stubs/seaborn/seaborn/widgets.pyi @@ -0,0 +1,40 @@ +from typing import Literal, overload + +from matplotlib.colors import LinearSegmentedColormap + +__all__ = [ + "choose_colorbrewer_palette", + "choose_cubehelix_palette", + "choose_dark_palette", + "choose_light_palette", + "choose_diverging_palette", +] + +@overload +def choose_colorbrewer_palette( + data_type: Literal["sequential", "diverging", "qualitative"], as_cmap: Literal[True] +) -> LinearSegmentedColormap: ... +@overload +def choose_colorbrewer_palette( + data_type: Literal["sequential", "diverging", "qualitative"], as_cmap: Literal[False] = False +) -> list[tuple[float, float, float]]: ... + +@overload +def choose_dark_palette(input: str = "husl", *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_dark_palette(input: str = "husl", as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_light_palette(input: str = "husl", *, as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_light_palette(input: str = "husl", as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_diverging_palette(as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_diverging_palette(as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... + +@overload +def choose_cubehelix_palette(as_cmap: Literal[True]) -> LinearSegmentedColormap: ... +@overload +def choose_cubehelix_palette(as_cmap: Literal[False] = False) -> list[tuple[float, float, float]]: ... diff --git a/stubs/setuptools/@tests/stubtest_allowlist.txt b/stubs/setuptools/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ec19bc003004 --- /dev/null +++ b/stubs/setuptools/@tests/stubtest_allowlist.txt @@ -0,0 +1,88 @@ +# Is a functools.partial, so stubtest says "is not a function" +setuptools._distutils._modified.newer_pairwise_group + +# Runtime initializes to None, but this really should never be None when used +setuptools._distutils.compilers.C.base.Compiler.compiler_type + +# Dynamically created in __init__ +setuptools._distutils.dist.Distribution.get_name +setuptools._distutils.dist.Distribution.get_version +setuptools._distutils.dist.Distribution.get_fullname +setuptools._distutils.dist.Distribution.get_author +setuptools._distutils.dist.Distribution.get_author_email +setuptools._distutils.dist.Distribution.get_maintainer +setuptools._distutils.dist.Distribution.get_maintainer_email +setuptools._distutils.dist.Distribution.get_contact +setuptools._distutils.dist.Distribution.get_contact_email +setuptools._distutils.dist.Distribution.get_url +setuptools._distutils.dist.Distribution.get_license +setuptools._distutils.dist.Distribution.get_licence +setuptools._distutils.dist.Distribution.get_description +setuptools._distutils.dist.Distribution.get_long_description +setuptools._distutils.dist.Distribution.get_keywords +setuptools._distutils.dist.Distribution.get_platforms +setuptools._distutils.dist.Distribution.get_classifiers +setuptools._distutils.dist.Distribution.get_download_url +setuptools._distutils.dist.Distribution.get_requires +setuptools._distutils.dist.Distribution.get_provides +setuptools._distutils.dist.Distribution.get_obsoletes + +# Missing objects from setuptools._distutils +setuptools._distutils.archive_util.ARCHIVE_FORMATS +setuptools._distutils.archive_util.check_archive_formats +setuptools._distutils.cmd.Command.dump_options +setuptools._distutils.command.build_ext.extension_name_re +setuptools._distutils.command.install.HAS_USER_SITE +setuptools._distutils.command.install.INSTALL_SCHEMES +setuptools._distutils.command.install.SCHEME_KEYS +setuptools._distutils.command.install.WINDOWS_SCHEME +setuptools._distutils.command.install_lib.PYTHON_SOURCE_EXTENSION +setuptools._distutils.dir_util.SkipRepeatAbsolutePaths.instance +setuptools._distutils.dist.fix_help_options +setuptools._distutils.extension.read_setup_file +setuptools._distutils.filelist.findall +setuptools._distutils.filelist.glob_to_re +setuptools._distutils.filelist.translate_pattern +setuptools._distutils.sysconfig.BASE_EXEC_PREFIX +setuptools._distutils.sysconfig.BASE_PREFIX +setuptools._distutils.sysconfig.IS_PYPY +setuptools._distutils.sysconfig.build_flags +setuptools._distutils.sysconfig.expand_makefile_vars +setuptools._distutils.sysconfig.get_python_version +setuptools._distutils.sysconfig.parse_config_h +setuptools._distutils.sysconfig.parse_makefile +setuptools._distutils.sysconfig.project_base +setuptools._distutils.sysconfig.python_build +setuptools._distutils.util.MACOSX_VERSION_VAR + +# Missing submodules from setuptools._distutils +# (Many of these may be implementation details, +# but they can be added if people ask for them) +setuptools._distutils.command.__all__ +setuptools._distutils.command.bdist_dumb +setuptools._distutils.command.build_scripts +setuptools._distutils.command.check +setuptools._distutils.command.clean +setuptools._distutils.command.config +setuptools._distutils.command.install_egg_info +setuptools._distutils.command.install_headers +setuptools._distutils.compat.numpy +setuptools._distutils.compat.py39 +setuptools._distutils.core +setuptools._distutils.debug +setuptools._distutils.fancy_getopt +setuptools._distutils.log +setuptools._distutils.text_file +setuptools._distutils.version.Version._cmp # abstract method +setuptools._distutils.version.Version.parse # abstract method +setuptools._distutils.version.suppress_known_deprecation +setuptools._distutils.versionpredicate + +# Reexported from setuptools._distutils; problems should be fixed there +distutils\..+ + +# Private APIs, tests and other vendored code +setuptools.config._validate_pyproject.* +setuptools.compat.* +setuptools.command.build_py.build_py.existing_egg_info_dir +.+?\.tests.* diff --git a/stubs/setuptools/@tests/test_cases/check_distutils.py b/stubs/setuptools/@tests/test_cases/check_distutils.py new file mode 100644 index 000000000000..cbd3e645c545 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_distutils.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +import distutils.command.sdist +from _typeshed import StrPath +from os import PathLike +from pathlib import Path + +from setuptools._distutils.ccompiler import CCompiler + +c = distutils.command.sdist.sdist + +# Test CCompiler().compile with varied sources + +compiler = CCompiler() + +str_list: list[str] = ["file1.c", "file2.c"] +compiler.compile(sources=str_list) + +path_list: list[Path] = [Path("file1.c"), Path("file2.c")] +compiler.compile(sources=path_list) + +pathlike_list: list[PathLike[str]] = [Path("file1.c"), Path("file2.c")] +compiler.compile(sources=pathlike_list) + +strpath_list: list[StrPath] = [Path("file1.c"), "file2.c"] +compiler.compile(sources=strpath_list) + +# Direct literals should also work +compiler.compile(sources=["file1.c", "file2.c"]) +compiler.compile(sources=[Path("file1.c"), Path("file2.c")]) +compiler.compile(sources=[Path("file1.c"), "file2.c"]) diff --git a/stubs/setuptools/@tests/test_cases/check_extension.py b/stubs/setuptools/@tests/test_cases/check_extension.py new file mode 100644 index 000000000000..c798d4eb98ad --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_extension.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from os import PathLike +from pathlib import Path + +from setuptools import Extension + +# Dummy extensions +ext1 = Extension(name="test1", sources=["file1.c", "file2.c"]) # plain list[str] works + +path_sources: list[Path] = [Path("file1.c"), Path("file2.c")] +ext2 = Extension(name="test2", sources=path_sources) # list of Path(s) + +mixed_sources: list[str | PathLike[str]] = [Path("file1.c"), "file2.c"] # or list[StrPath] +ext3 = Extension(name="test3", sources=mixed_sources) # mixed types diff --git a/stubs/setuptools/@tests/test_cases/check_protocols.py b/stubs/setuptools/@tests/test_cases/check_protocols.py new file mode 100644 index 000000000000..20573855ac44 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_protocols.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from typing import Any + +from setuptools.command.editable_wheel import EditableStrategy, _LinkTree, _StaticPth, _TopLevelFinder +from setuptools.config.expand import EnsurePackagesDiscovered +from setuptools.config.pyprojecttoml import _EnsurePackagesDiscovered + +# We don't care about the __init__ methods, only about if an instance respects the Protocol +_: Any = object() + +# Test EditableStrategy Protocol implementers +editable_strategy: EditableStrategy +editable_strategy = _StaticPth(_, _, _) +editable_strategy = _LinkTree(_, _, _, _) +editable_strategy = _TopLevelFinder(_, _) +# Not EditableStrategy due to incompatible __call__ method +editable_strategy = EnsurePackagesDiscovered(_) # type: ignore +editable_strategy = _EnsurePackagesDiscovered(_, _, _) # type: ignore diff --git a/stubs/setuptools/@tests/test_cases/check_setup.py b/stubs/setuptools/@tests/test_cases/check_setup.py new file mode 100644 index 000000000000..b6bac7b01de5 --- /dev/null +++ b/stubs/setuptools/@tests/test_cases/check_setup.py @@ -0,0 +1,23 @@ +from typing_extensions import assert_type + +from setuptools import Command as setuptools_Command, Distribution as setuptools_Distribution, setup +from setuptools._distutils.cmd import Command as distutils_Command +from setuptools._distutils.dist import Distribution as distutils_Distribution + +# Ensure that any distutils-derived classes are usable w/o type variance issues +assert_type( + setup( + cmdclass=dict[str, type[distutils_Command]](), + command_obj=dict[str, distutils_Command](), + distclass=distutils_Distribution, + ), + distutils_Distribution, +) +assert_type( + setup( + cmdclass=dict[str, type[setuptools_Command]](), + command_obj=dict[str, setuptools_Command](), + distclass=setuptools_Distribution, + ), + setuptools_Distribution, +) diff --git a/stubs/setuptools/METADATA.toml b/stubs/setuptools/METADATA.toml new file mode 100644 index 000000000000..2354f4fa48e2 --- /dev/null +++ b/stubs/setuptools/METADATA.toml @@ -0,0 +1,16 @@ +version = "83.0.*" +upstream-repository = "https://github.com/pypa/setuptools" +extra-description = """\ +Given that `pkg_resources` is typed since `setuptools >= 71.1`, \ +it is no longer included with `types-setuptools`. +""" + +[tool.stubtest] +# darwin is equivalent to linux for OS-specific methods +ci-platforms = ["linux", "win32"] +stubtest-dependencies = ["more_itertools", "tomli"] + +# Stubtest fails on trying to run mypy on the source files rather than our stubs +[mypy-tests.distutils] +module-name = "setuptools._distutils.compilers.C.*" +values = { ignore_errors = true } diff --git a/stubs/setuptools/distutils/__init__.pyi b/stubs/setuptools/distutils/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/setuptools/distutils/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/setuptools/distutils/_modified.pyi b/stubs/setuptools/distutils/_modified.pyi new file mode 100644 index 000000000000..e916197a5ae2 --- /dev/null +++ b/stubs/setuptools/distutils/_modified.pyi @@ -0,0 +1 @@ +from setuptools._distutils._modified import * diff --git a/stubs/setuptools/distutils/_msvccompiler.pyi b/stubs/setuptools/distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..f2ead92dea06 --- /dev/null +++ b/stubs/setuptools/distutils/_msvccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils._msvccompiler import * diff --git a/stubs/setuptools/distutils/archive_util.pyi b/stubs/setuptools/distutils/archive_util.pyi new file mode 100644 index 000000000000..115f30506461 --- /dev/null +++ b/stubs/setuptools/distutils/archive_util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.archive_util import * diff --git a/stubs/setuptools/distutils/ccompiler.pyi b/stubs/setuptools/distutils/ccompiler.pyi new file mode 100644 index 000000000000..d8f1af11ef33 --- /dev/null +++ b/stubs/setuptools/distutils/ccompiler.pyi @@ -0,0 +1,12 @@ +from setuptools._distutils.ccompiler import * +from setuptools._distutils.ccompiler import CCompiler as CCompiler + +__all__ = [ + "CompileError", + "LinkError", + "gen_lib_options", + "gen_preprocess_options", + "get_default_compiler", + "new_compiler", + "show_compilers", +] diff --git a/stubs/setuptools/distutils/cmd.pyi b/stubs/setuptools/distutils/cmd.pyi new file mode 100644 index 000000000000..235ca5680913 --- /dev/null +++ b/stubs/setuptools/distutils/cmd.pyi @@ -0,0 +1 @@ +from setuptools._distutils.cmd import * diff --git a/stubs/setuptools/distutils/command/__init__.pyi b/stubs/setuptools/distutils/command/__init__.pyi new file mode 100644 index 000000000000..adeb472a515f --- /dev/null +++ b/stubs/setuptools/distutils/command/__init__.pyi @@ -0,0 +1,39 @@ +from . import ( + bdist as bdist, + bdist_rpm as bdist_rpm, + build as build, + build_clib as build_clib, + build_ext as build_ext, + build_py as build_py, + # build_scripts as build_scripts, + # check as check, + # clean as clean, + install as install, + # install_data as install_data, + # install_headers as install_headers, + install_lib as install_lib, + install_scripts as install_scripts, + sdist as sdist, +) + +# Commented out commands are not stubbed. +# (Many of these may be implementation details, +# but they can be added if people ask for them) +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + # "build_scripts", + # "clean", + "install", + "install_lib", + # "install_headers", + "install_scripts", + # "install_data", + "sdist", + "bdist", + # "bdist_dumb", + "bdist_rpm", + # "check", +] diff --git a/stubs/setuptools/distutils/command/bdist.pyi b/stubs/setuptools/distutils/command/bdist.pyi new file mode 100644 index 000000000000..3445de9fbe0c --- /dev/null +++ b/stubs/setuptools/distutils/command/bdist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.bdist import * diff --git a/stubs/setuptools/distutils/command/bdist_rpm.pyi b/stubs/setuptools/distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..32e88d493a3f --- /dev/null +++ b/stubs/setuptools/distutils/command/bdist_rpm.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.bdist_rpm import * diff --git a/stubs/setuptools/distutils/command/build.pyi b/stubs/setuptools/distutils/command/build.pyi new file mode 100644 index 000000000000..1fe7d1e73415 --- /dev/null +++ b/stubs/setuptools/distutils/command/build.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build import * diff --git a/stubs/setuptools/distutils/command/build_clib.pyi b/stubs/setuptools/distutils/command/build_clib.pyi new file mode 100644 index 000000000000..f60f41aa89f4 --- /dev/null +++ b/stubs/setuptools/distutils/command/build_clib.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_clib import * diff --git a/stubs/setuptools/distutils/command/build_ext.pyi b/stubs/setuptools/distutils/command/build_ext.pyi new file mode 100644 index 000000000000..c1967156809e --- /dev/null +++ b/stubs/setuptools/distutils/command/build_ext.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_ext import * diff --git a/stubs/setuptools/distutils/command/build_py.pyi b/stubs/setuptools/distutils/command/build_py.pyi new file mode 100644 index 000000000000..0d97b743f7de --- /dev/null +++ b/stubs/setuptools/distutils/command/build_py.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.build_py import * diff --git a/stubs/setuptools/distutils/command/install.pyi b/stubs/setuptools/distutils/command/install.pyi new file mode 100644 index 000000000000..6ef0aca09e23 --- /dev/null +++ b/stubs/setuptools/distutils/command/install.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install import * diff --git a/stubs/setuptools/distutils/command/install_data.pyi b/stubs/setuptools/distutils/command/install_data.pyi new file mode 100644 index 000000000000..039f8b41c901 --- /dev/null +++ b/stubs/setuptools/distutils/command/install_data.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_data import * diff --git a/stubs/setuptools/distutils/command/install_lib.pyi b/stubs/setuptools/distutils/command/install_lib.pyi new file mode 100644 index 000000000000..bfcfe358cb1e --- /dev/null +++ b/stubs/setuptools/distutils/command/install_lib.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_lib import * diff --git a/stubs/setuptools/distutils/command/install_scripts.pyi b/stubs/setuptools/distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..3cebd5543427 --- /dev/null +++ b/stubs/setuptools/distutils/command/install_scripts.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.install_scripts import * diff --git a/stubs/setuptools/distutils/command/sdist.pyi b/stubs/setuptools/distutils/command/sdist.pyi new file mode 100644 index 000000000000..50a819163764 --- /dev/null +++ b/stubs/setuptools/distutils/command/sdist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.command.sdist import * diff --git a/stubs/setuptools/distutils/compat/__init__.pyi b/stubs/setuptools/distutils/compat/__init__.pyi new file mode 100644 index 000000000000..bbcbf9cc1f7a --- /dev/null +++ b/stubs/setuptools/distutils/compat/__init__.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compat import * diff --git a/stubs/setuptools/distutils/compilers/C/base.pyi b/stubs/setuptools/distutils/compilers/C/base.pyi new file mode 100644 index 000000000000..5e58ee9cbe68 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/base.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.base import * diff --git a/stubs/setuptools/distutils/compilers/C/cygwin.pyi b/stubs/setuptools/distutils/compilers/C/cygwin.pyi new file mode 100644 index 000000000000..9b7a9d9e0ca0 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/cygwin.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.cygwin import * diff --git a/stubs/setuptools/distutils/compilers/C/errors.pyi b/stubs/setuptools/distutils/compilers/C/errors.pyi new file mode 100644 index 000000000000..6cc2192bd587 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/errors.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.errors import * diff --git a/stubs/setuptools/distutils/compilers/C/msvc.pyi b/stubs/setuptools/distutils/compilers/C/msvc.pyi new file mode 100644 index 000000000000..733c0ce32c3b --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/msvc.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.msvc import * diff --git a/stubs/setuptools/distutils/compilers/C/unix.pyi b/stubs/setuptools/distutils/compilers/C/unix.pyi new file mode 100644 index 000000000000..d4dbeff6b110 --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/unix.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.unix import * diff --git a/stubs/setuptools/distutils/compilers/C/zos.pyi b/stubs/setuptools/distutils/compilers/C/zos.pyi new file mode 100644 index 000000000000..921cd46b47ef --- /dev/null +++ b/stubs/setuptools/distutils/compilers/C/zos.pyi @@ -0,0 +1 @@ +from setuptools._distutils.compilers.C.zos import * diff --git a/stubs/setuptools/distutils/cygwinccompiler.pyi b/stubs/setuptools/distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..1784f31d60fc --- /dev/null +++ b/stubs/setuptools/distutils/cygwinccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.cygwinccompiler import * diff --git a/stubs/setuptools/distutils/dep_util.pyi b/stubs/setuptools/distutils/dep_util.pyi new file mode 100644 index 000000000000..22008d8cf747 --- /dev/null +++ b/stubs/setuptools/distutils/dep_util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.dep_util import * diff --git a/stubs/setuptools/distutils/dist.pyi b/stubs/setuptools/distutils/dist.pyi new file mode 100644 index 000000000000..b6cdf2bd9f2a --- /dev/null +++ b/stubs/setuptools/distutils/dist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.dist import * diff --git a/stubs/setuptools/distutils/errors.pyi b/stubs/setuptools/distutils/errors.pyi new file mode 100644 index 000000000000..28a21bf13e2a --- /dev/null +++ b/stubs/setuptools/distutils/errors.pyi @@ -0,0 +1 @@ +from setuptools._distutils.errors import * diff --git a/stubs/setuptools/distutils/extension.pyi b/stubs/setuptools/distutils/extension.pyi new file mode 100644 index 000000000000..95b5cf764dfd --- /dev/null +++ b/stubs/setuptools/distutils/extension.pyi @@ -0,0 +1 @@ +from setuptools._distutils.extension import * diff --git a/stubs/setuptools/distutils/filelist.pyi b/stubs/setuptools/distutils/filelist.pyi new file mode 100644 index 000000000000..fe746bbdcfe4 --- /dev/null +++ b/stubs/setuptools/distutils/filelist.pyi @@ -0,0 +1 @@ +from setuptools._distutils.filelist import * diff --git a/stubs/setuptools/distutils/spawn.pyi b/stubs/setuptools/distutils/spawn.pyi new file mode 100644 index 000000000000..4432100c0024 --- /dev/null +++ b/stubs/setuptools/distutils/spawn.pyi @@ -0,0 +1 @@ +from setuptools._distutils.spawn import * diff --git a/stubs/setuptools/distutils/sysconfig.pyi b/stubs/setuptools/distutils/sysconfig.pyi new file mode 100644 index 000000000000..9b50b49872bc --- /dev/null +++ b/stubs/setuptools/distutils/sysconfig.pyi @@ -0,0 +1 @@ +from setuptools._distutils.sysconfig import * diff --git a/stubs/setuptools/distutils/unixccompiler.pyi b/stubs/setuptools/distutils/unixccompiler.pyi new file mode 100644 index 000000000000..fcbf9e199041 --- /dev/null +++ b/stubs/setuptools/distutils/unixccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.unixccompiler import * diff --git a/stubs/setuptools/distutils/util.pyi b/stubs/setuptools/distutils/util.pyi new file mode 100644 index 000000000000..b5723b79d9ff --- /dev/null +++ b/stubs/setuptools/distutils/util.pyi @@ -0,0 +1 @@ +from setuptools._distutils.util import * diff --git a/stubs/setuptools/distutils/version.pyi b/stubs/setuptools/distutils/version.pyi new file mode 100644 index 000000000000..1cac35f20653 --- /dev/null +++ b/stubs/setuptools/distutils/version.pyi @@ -0,0 +1 @@ +from setuptools._distutils.version import * diff --git a/stubs/setuptools/distutils/zosccompiler.pyi b/stubs/setuptools/distutils/zosccompiler.pyi new file mode 100644 index 000000000000..b69c6320e43b --- /dev/null +++ b/stubs/setuptools/distutils/zosccompiler.pyi @@ -0,0 +1 @@ +from setuptools._distutils.zosccompiler import * diff --git a/stubs/setuptools/setuptools/__init__.pyi b/stubs/setuptools/setuptools/__init__.pyi new file mode 100644 index 000000000000..e89fce7ebdc6 --- /dev/null +++ b/stubs/setuptools/setuptools/__init__.pyi @@ -0,0 +1,279 @@ +from _typeshed import Incomplete, StrPath +from abc import abstractmethod +from collections.abc import ItemsView, Iterable, Mapping, Sequence +from typing import Any, Literal, Protocol, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, NotRequired + +from ._distutils.cmd import Command as _Command +from ._distutils.dist import Distribution as _Distribution +from ._distutils.extension import Extension as _Extension +from .command.alias import alias +from .command.bdist_egg import bdist_egg +from .command.bdist_rpm import bdist_rpm +from .command.bdist_wheel import bdist_wheel +from .command.build import build +from .command.build_clib import build_clib +from .command.build_ext import build_ext +from .command.build_py import build_py +from .command.develop import develop +from .command.dist_info import dist_info +from .command.easy_install import easy_install +from .command.editable_wheel import editable_wheel +from .command.egg_info import egg_info +from .command.install import install +from .command.install_egg_info import install_egg_info +from .command.install_lib import install_lib +from .command.install_scripts import install_scripts +from .command.rotate import rotate +from .command.saveopts import saveopts +from .command.sdist import sdist +from .command.setopt import setopt +from .depends import Require as Require +from .discovery import _Finder +from .dist import Distribution as Distribution +from .extension import Extension as Extension +from .warnings import SetuptoolsDeprecationWarning as SetuptoolsDeprecationWarning + +_CommandT = TypeVar("_CommandT", bound=_Command) +_DistributionT = TypeVar("_DistributionT", bound=_Distribution, default=Distribution) +_KT = TypeVar("_KT") +_VT_co = TypeVar("_VT_co", covariant=True) + +__all__ = [ + "setup", + "Distribution", + "Command", + "Extension", + "Require", + "SetuptoolsDeprecationWarning", + "find_packages", + "find_namespace_packages", +] + +__version__: str + +# We need any Command subclass to be valid +# Any: pyright would accept using covariance in __setitem__, but mypy won't let a dict be assignable to this protocol +# This is unsound, but it's a quirk of setuptools' internals +@type_check_only +class _DictLike(Protocol[_KT, _VT_co]): + # See note about using _VT_co instead of Any + def get(self, key: _KT, default: Any | None = None, /) -> _VT_co | None: ... + def items(self) -> ItemsView[_KT, _VT_co]: ... + def keys(self) -> Iterable[_KT]: ... + def __getitem__(self, key: _KT, /) -> _VT_co: ... + def __contains__(self, x: object, /) -> bool: ... + +@type_check_only +class _MutableDictLike(_DictLike[_KT, _VT_co], Protocol): + # See note about using _VT_co instead of Any + def __setitem__(self, key: _KT, value: Any, /) -> None: ... + def setdefault(self, key: _KT, default: Any, /) -> _VT_co: ... + +@type_check_only +class _BuildInfo(TypedDict): + sources: list[str] | tuple[str, ...] + obj_deps: NotRequired[dict[str, list[str] | tuple[str, ...]]] + macros: NotRequired[list[tuple[str] | tuple[str, str | None]]] + include_dirs: NotRequired[list[str]] + cflags: NotRequired[list[str]] + +find_packages = _Finder.find +find_namespace_packages = _Finder.find + +def setup( + *, + # Attributes from distutils.dist.DistributionMetadata.set_* + # These take priority over attributes from distutils.dist.DistributionMetadata.__init__ + keywords: str | Iterable[str] = ..., + platforms: str | Iterable[str] = ..., + classifiers: str | Iterable[str] = ..., + requires: Iterable[str] = ..., + provides: Iterable[str] = ..., + obsoletes: Iterable[str] = ..., + # Attributes from distutils.dist.DistributionMetadata.__init__ + # These take priority over attributes from distutils.dist.Distribution.__init__ + name: str | None = None, + version: str | None = None, + author: str | None = None, + author_email: str | None = None, + maintainer: str | None = None, + maintainer_email: str | None = None, + url: str | None = None, + license: str | None = None, + description: str | None = None, + long_description: str | None = None, + download_url: str | None = None, + # Attributes from distutils.dist.Distribution.__init__ (except self.metadata) + # These take priority over attributes from distutils.dist.Distribution.display_option_names + verbose: bool = True, + help: bool = False, + cmdclass: _MutableDictLike[str, type[_Command]] = {}, + command_packages: str | list[str] | None = None, + script_name: StrPath | None = ..., # default is actually set in distutils.core.setup + script_args: list[str] | None = ..., # default is actually set in distutils.core.setup + command_options: _MutableDictLike[str, _DictLike[str, tuple[str, str]]] = {}, + packages: list[str] | None = None, + package_dir: Mapping[str, str] | None = None, + py_modules: list[str] | None = None, + libraries: list[tuple[str, _BuildInfo]] | None = None, + headers: list[str] | None = None, + ext_modules: Sequence[_Extension] | None = None, + ext_package: str | None = None, + include_dirs: list[str] | None = None, + extra_path: Never = ..., # Deprecated + scripts: list[str] | None = None, + data_files: list[tuple[str, Sequence[str]]] | None = None, + password: str = "", + command_obj: _MutableDictLike[str, _Command] = {}, + have_run: _MutableDictLike[str, bool] = {}, + # kwargs used directly in distutils.dist.Distribution.__init__ + options: Mapping[str, Mapping[str, str]] | None = None, + licence: Never = ..., # Deprecated + # Attributes from distutils.dist.Distribution.display_option_names + # (this can more easily be copied from the `if TYPE_CHECKING` block) + help_commands: bool = False, + fullname: str | Literal[False] = False, + contact: str | Literal[False] = False, + contact_email: str | Literal[False] = False, + # kwargs used directly in setuptools.dist.Distribution.__init__ + # and attributes from setuptools.dist.Distribution.__init__ + package_data: _DictLike[str, list[str]] = {}, + dist_files: list[tuple[str, str, str]] = [], + include_package_data: bool | None = None, + exclude_package_data: _DictLike[str, list[str]] | None = None, + src_root: str | None = None, + dependency_links: list[str] = [], + setup_requires: list[str] = [], + # From Distribution._DISTUTILS_UNSUPPORTED_METADATA set in Distribution._set_metadata_defaults + long_description_content_type: str | None = None, + project_urls: _DictLike[Incomplete, Incomplete] = {}, + provides_extras: _MutableDictLike[Incomplete, Incomplete] = {}, + license_expression: str | None = None, + license_file: Never = ..., # Deprecated + license_files: Iterable[str] | None = None, + install_requires: str | Iterable[str] = [], + extras_require: _DictLike[Incomplete, Incomplete] = {}, + # kwargs used directly in distutils.core.setup + distclass: type[_DistributionT] = Distribution, # type: ignore[assignment] # noqa: Y011 # ty:ignore[invalid-parameter-default] + # Custom Distributions could accept more params + **attrs: Any, +) -> _DistributionT: ... + +class Command(_Command): + command_consumes_arguments: bool + distribution: Distribution + dry_run: bool + # Any: Dynamic command subclass attributes + def __init__(self, dist: Distribution, **kw: Any) -> None: ... + + # Note: Commands that setuptools doesn't re-expose are considered deprecated (they must be imported from distutils directly) + # So we're not listing them here. This list comes directly from the setuptools/command folder. Minus the test command. + @overload # type: ignore[override] + def get_finalized_command(self, command: Literal["alias"], create: bool | Literal[0, 1] = 1) -> alias: ... + @overload + def get_finalized_command(self, command: Literal["bdist_egg"], create: bool | Literal[0, 1] = 1) -> bdist_egg: ... + @overload + def get_finalized_command(self, command: Literal["bdist_rpm"], create: bool | Literal[0, 1] = 1) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["bdist_wheel"], create: bool | Literal[0, 1] = 1) -> bdist_wheel: ... + @overload + def get_finalized_command(self, command: Literal["build"], create: bool | Literal[0, 1] = 1) -> build: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_clib"], create: bool | Literal[0, 1] = 1) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_ext"], create: bool | Literal[0, 1] = 1) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["build_py"], create: bool | Literal[0, 1] = 1) -> build_py: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["develop"], create: bool | Literal[0, 1] = 1) -> develop: ... + @overload + def get_finalized_command(self, command: Literal["dist_info"], create: bool | Literal[0, 1] = 1) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["easy_install"], create: bool | Literal[0, 1] = 1) -> easy_install: ... + @overload + def get_finalized_command(self, command: Literal["editable_wheel"], create: bool | Literal[0, 1] = 1) -> editable_wheel: ... + @overload + def get_finalized_command(self, command: Literal["egg_info"], create: bool | Literal[0, 1] = 1) -> egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install"], create: bool | Literal[0, 1] = 1) -> install: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command( + self, command: Literal["install_egg_info"], create: bool | Literal[0, 1] = 1 + ) -> install_egg_info: ... + @overload + def get_finalized_command(self, command: Literal["install_lib"], create: bool | Literal[0, 1] = 1) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["install_scripts"], create: bool | Literal[0, 1] = 1) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["rotate"], create: bool | Literal[0, 1] = 1) -> rotate: ... + @overload + def get_finalized_command(self, command: Literal["saveopts"], create: bool | Literal[0, 1] = 1) -> saveopts: ... + @overload + def get_finalized_command(self, command: Literal["sdist"], create: bool | Literal[0, 1] = 1) -> sdist: ... # type: ignore[overload-overlap] + @overload + def get_finalized_command(self, command: Literal["setopt"], create: bool | Literal[0, 1] = 1) -> setopt: ... + @overload + def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ... + + @overload # type: ignore[override] # Extra **kw param + def reinitialize_command(self, command: Literal["alias"], reinit_subcommands: bool = False, **kw) -> alias: ... + @overload + def reinitialize_command(self, command: Literal["bdist_egg"], reinit_subcommands: bool = False, **kw) -> bdist_egg: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False, **kw) -> bdist_rpm: ... + @overload + def reinitialize_command(self, command: Literal["bdist_wheel"], reinit_subcommands: bool = False, **kw) -> bdist_wheel: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False, **kw) -> build: ... + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False, **kw) -> build_clib: ... + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False, **kw) -> build_ext: ... + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False, **kw) -> build_py: ... + @overload + def reinitialize_command(self, command: Literal["develop"], reinit_subcommands: bool = False, **kw) -> develop: ... + @overload + def reinitialize_command(self, command: Literal["dist_info"], reinit_subcommands: bool = False, **kw) -> dist_info: ... + @overload + def reinitialize_command(self, command: Literal["easy_install"], reinit_subcommands: bool = False, **kw) -> easy_install: ... + @overload + def reinitialize_command( + self, command: Literal["editable_wheel"], reinit_subcommands: bool = False, **kw + ) -> editable_wheel: ... + @overload + def reinitialize_command(self, command: Literal["egg_info"], reinit_subcommands: bool = False, **kw) -> egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False, **kw) -> install: ... + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False, **kw + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False, **kw) -> install_lib: ... + @overload + def reinitialize_command( + self, command: Literal["install_scripts"], reinit_subcommands: bool = False, **kw + ) -> install_scripts: ... + @overload + def reinitialize_command(self, command: Literal["rotate"], reinit_subcommands: bool = False, **kw) -> rotate: ... + @overload + def reinitialize_command(self, command: Literal["saveopts"], reinit_subcommands: bool = False, **kw) -> saveopts: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False, **kw) -> sdist: ... + @overload + def reinitialize_command(self, command: Literal["setopt"], reinit_subcommands: bool = False, **kw) -> setopt: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False, **kw) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False, **kw) -> _CommandT: ... + + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + +class sic(str): ... diff --git a/stubs/setuptools/setuptools/_distutils/__init__.pyi b/stubs/setuptools/setuptools/_distutils/__init__.pyi new file mode 100644 index 000000000000..c5dd95466063 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/stubs/setuptools/setuptools/_distutils/_modified.pyi b/stubs/setuptools/setuptools/_distutils/_modified.pyi new file mode 100644 index 000000000000..b64061d5c4b2 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/_modified.pyi @@ -0,0 +1,17 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Callable, Iterable +from typing import Literal, TypeVar + +_SourcesT = TypeVar("_SourcesT", bound=StrOrBytesPath) +_TargetsT = TypeVar("_TargetsT", bound=StrOrBytesPath) + +def newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool: ... +def newer_pairwise( + sources: Iterable[_SourcesT], targets: Iterable[_TargetsT], newer: Callable[[_SourcesT, _TargetsT], bool] = ... +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... +def newer_group( + sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal["error", "ignore", "newer"] = "error" +) -> bool: ... +def newer_pairwise_group( + sources: Iterable[_SourcesT], targets: Iterable[_TargetsT], *, newer: Callable[[_SourcesT, _TargetsT], bool] = ... +) -> tuple[list[_SourcesT], list[_TargetsT]]: ... diff --git a/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi b/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..8471ccab28fa --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/_msvccompiler.pyi @@ -0,0 +1,5 @@ +from .compilers.C import msvc + +__all__ = ["MSVCCompiler"] + +MSVCCompiler = msvc.Compiler diff --git a/stubs/setuptools/setuptools/_distutils/archive_util.pyi b/stubs/setuptools/setuptools/_distutils/archive_util.pyi new file mode 100644 index 000000000000..2c6dae867a6b --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/archive_util.pyi @@ -0,0 +1,33 @@ +from _typeshed import StrOrBytesPath, StrPath +from typing import Literal, overload + +@overload +def make_archive( + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +@overload +def make_archive( + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... + +def make_tarball( + base_name: str, + base_dir: StrPath, + compress: Literal["gzip", "bzip2", "xz"] | None = "gzip", + verbose: bool = False, + owner: str | None = None, + group: str | None = None, +) -> str: ... +def make_zipfile(base_name: str, base_dir: StrPath, verbose: bool = False) -> str: ... diff --git a/stubs/setuptools/setuptools/_distutils/ccompiler.pyi b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi new file mode 100644 index 000000000000..cbb794e101a0 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/ccompiler.pyi @@ -0,0 +1,15 @@ +from .compilers.C import base +from .compilers.C.base import gen_lib_options, gen_preprocess_options, get_default_compiler, new_compiler, show_compilers +from .compilers.C.errors import CompileError, LinkError + +__all__ = [ + "CompileError", + "LinkError", + "gen_lib_options", + "gen_preprocess_options", + "get_default_compiler", + "new_compiler", + "show_compilers", +] + +CCompiler = base.Compiler diff --git a/stubs/setuptools/setuptools/_distutils/cmd.pyi b/stubs/setuptools/setuptools/_distutils/cmd.pyi new file mode 100644 index 000000000000..879a0858d97d --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/cmd.pyi @@ -0,0 +1,127 @@ +from _typeshed import BytesPath, StrOrBytesPath, StrPath, Unused +from abc import abstractmethod +from collections.abc import Callable, MutableSequence, Sequence +from typing import Any, ClassVar, Literal, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack + +from .dist import Distribution + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) +_CommandT = TypeVar("_CommandT", bound=Command) +_Ts = TypeVarTuple("_Ts") + +class Command: + distribution: Distribution + # Any to work around variance issues + sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]] + user_options: ClassVar[ + # Specifying both because list is invariant. Avoids mypy override assignment issues + list[tuple[str, str, str]] + | list[tuple[str, str | None, str]] + ] + def __init__(self, dist: Distribution) -> None: ... + def ensure_finalized(self) -> None: ... + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + def announce(self, msg: str, level: int = 10) -> None: ... + def debug_print(self, msg: str) -> None: ... + def ensure_string(self, option: str, default: str | None = None) -> None: ... + def ensure_string_list(self, option: str) -> None: ... + def ensure_filename(self, option: str) -> None: ... + def ensure_dirname(self, option: str) -> None: ... + def get_command_name(self) -> str: ... + def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ... + # NOTE: Because this is private setuptools implementation and we don't re-expose all commands here, + # we're not overloading each and every command possibility. + def get_finalized_command(self, command: str, create: bool = True) -> Command: ... + + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def run_command(self, command: str) -> None: ... + def get_sub_commands(self) -> list[str]: ... + def warn(self, msg: str) -> None: ... + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def copy_file( + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... + @overload + def copy_file( + self, + infile: BytesPath, + outfile: _BytesPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_BytesPathT | bytes, bool]: ... + + def copy_tree( + self, + infile: StrPath, + outfile: str, + preserve_mode: bool = True, + preserve_times: bool = True, + preserve_symlinks: bool = False, + level: Unused = 1, + ) -> list[str]: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... + + @overload + def spawn(self, cmd: Sequence[StrOrBytesPath], search_path: Literal[False], level: Unused = 1) -> None: ... + @overload + def spawn(self, cmd: MutableSequence[bytes | StrPath], search_path: Literal[True] = True, level: Unused = 1) -> None: ... + + @overload + def make_archive( + self, + base_name: str, + format: str, + root_dir: StrOrBytesPath | None = None, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + @overload + def make_archive( + self, + base_name: StrPath, + format: str, + root_dir: StrOrBytesPath, + base_dir: str | None = None, + owner: str | None = None, + group: str | None = None, + ) -> str: ... + + def make_file( + self, + infiles: str | list[str] | tuple[str, ...], + outfile: StrOrBytesPath, + func: Callable[[Unpack[_Ts]], Unused], + args: tuple[Unpack[_Ts]], + exec_msg: str | None = None, + skip_msg: str | None = None, + level: Unused = 1, + ) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/__init__.pyi b/stubs/setuptools/setuptools/_distutils/command/__init__.pyi new file mode 100644 index 000000000000..f6b93d32846a --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/__init__.pyi @@ -0,0 +1,39 @@ +from . import ( + bdist as bdist, + bdist_rpm as bdist_rpm, + build as build, + build_clib as build_clib, + build_ext as build_ext, + build_py as build_py, + # build_scripts as build_scripts, + # check as check, + # clean as clean, + install as install, + install_data as install_data, + # install_headers as install_headers, + install_lib as install_lib, + install_scripts as install_scripts, + sdist as sdist, +) + +# Commented out commands are not stubbed. +# (Many of these may be implementation details, +# but they can be added if people ask for them) +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + # "build_scripts", + # "clean", + "install", + "install_lib", + # "install_headers", + "install_scripts", + "install_data", + "sdist", + "bdist", + # "bdist_dumb", + "bdist_rpm", + # "check", +] diff --git a/stubs/setuptools/setuptools/_distutils/command/bdist.pyi b/stubs/setuptools/setuptools/_distutils/command/bdist.pyi new file mode 100644 index 000000000000..4c95b17011b1 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/bdist.pyi @@ -0,0 +1,26 @@ +from _typeshed import Unused +from collections.abc import Callable +from typing import ClassVar +from typing_extensions import deprecated + +from ..cmd import Command + +def show_formats() -> None: ... + +class ListCompat(dict[str, tuple[str, str]]): + @deprecated("format_commands is now a dict. append is deprecated") + def append(self, item: Unused) -> None: ... + +class bdist(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + no_format_option: ClassVar[tuple[str, ...]] + default_format: ClassVar[dict[str, str]] + format_commands: ClassVar[ListCompat] + format_command = format_commands # pyrefly: ignore [unknown-name] + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi b/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi new file mode 100644 index 000000000000..fed7833ed5e9 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/bdist_rpm.pyi @@ -0,0 +1,53 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class bdist_rpm(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + bdist_base: Incomplete + rpm_base: Incomplete + dist_dir: Incomplete + python: Incomplete + fix_python: Incomplete + spec_only: Incomplete + binary_only: Incomplete + source_only: Incomplete + use_bzip2: Incomplete + distribution_name: Incomplete + group: Incomplete + release: Incomplete + serial: Incomplete + vendor: Incomplete + packager: Incomplete + doc_files: Incomplete + changelog: Incomplete + icon: Incomplete + prep_script: Incomplete + build_script: Incomplete + install_script: Incomplete + clean_script: Incomplete + verify_script: Incomplete + pre_install: Incomplete + post_install: Incomplete + pre_uninstall: Incomplete + post_uninstall: Incomplete + prep: Incomplete + provides: Incomplete + requires: Incomplete + conflicts: Incomplete + build_requires: Incomplete + obsoletes: Incomplete + keep_temp: bool + use_rpm_opt_flags: bool + rpm3_mode: bool + no_autoreq: bool + force_arch: Incomplete + quiet: bool + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def finalize_package_data(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build.pyi b/stubs/setuptools/setuptools/_distutils/command/build.pyi new file mode 100644 index 000000000000..619b5e059b45 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build.pyi @@ -0,0 +1,30 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +class build(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_base: str + build_purelib: Incomplete + build_platlib: Incomplete + build_lib: Incomplete + build_temp: Incomplete + build_scripts: Incomplete + compiler: Incomplete + plat_name: Incomplete + debug: Incomplete + force: bool + executable: Incomplete + parallel: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_scripts(self) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi b/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi new file mode 100644 index 000000000000..e416a6dfe44d --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_clib.pyi @@ -0,0 +1,27 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +class build_clib(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + build_clib: Incomplete + build_temp: Incomplete + libraries: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + debug: Incomplete + force: bool + compiler: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_library_list(self, libraries) -> None: ... + def get_library_names(self): ... + def get_source_files(self): ... + def build_libraries(self, libraries) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi b/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi new file mode 100644 index 000000000000..a37eb6d17c55 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_ext.pyi @@ -0,0 +1,49 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command +from ..extension import Extension + +class build_ext(Command): + description: ClassVar[str] + sep_by: Incomplete + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + extensions: Incomplete + build_lib: Incomplete + plat_name: Incomplete + build_temp: Incomplete + inplace: bool + package: Incomplete + include_dirs: Incomplete + define: Incomplete + undef: Incomplete + libraries: Incomplete + library_dirs: Incomplete + rpath: Incomplete + link_objects: Incomplete + debug: Incomplete + force: Incomplete + compiler: Incomplete + swig: Incomplete + swig_cpp: Incomplete + swig_opts: Incomplete + user: Incomplete + parallel: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def check_extensions_list(self, extensions) -> None: ... + def get_source_files(self): ... + def get_outputs(self): ... + def build_extensions(self) -> None: ... + def build_extension(self, ext) -> None: ... + def swig_sources(self, sources, extension): ... + def find_swig(self): ... + def get_ext_fullpath(self, ext_name: str) -> str: ... + def get_ext_fullname(self, ext_name: str) -> str: ... + def get_ext_filename(self, ext_name: str) -> str: ... + def get_export_symbols(self, ext: Extension) -> list[str]: ... + def get_libraries(self, ext: Extension) -> list[str]: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/build_py.pyi b/stubs/setuptools/setuptools/_distutils/command/build_py.pyi new file mode 100644 index 000000000000..967e27a32236 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/build_py.pyi @@ -0,0 +1,39 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class build_py(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + build_lib: Incomplete + py_modules: Incomplete + package: Incomplete + package_data: Incomplete + package_dir: Incomplete + compile: bool + optimize: bool + force: Incomplete + def initialize_options(self) -> None: ... + packages: Incomplete + data_files: Incomplete + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_data_files(self): ... + def find_data_files(self, package, src_dir): ... + def build_package_data(self) -> None: ... + def get_package_dir(self, package): ... + def check_package(self, package, package_dir): ... + def check_module(self, module, module_file): ... + def find_package_modules(self, package, package_dir): ... + def find_modules(self): ... + def find_all_modules(self): ... + def get_source_files(self): ... + def get_module_outfile(self, build_dir, package, module): ... + def get_outputs(self, include_bytecode: bool = True) -> list[str]: ... + def build_module(self, module, module_file, package): ... + def build_modules(self) -> None: ... + def build_packages(self) -> None: ... + def byte_compile(self, files) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install.pyi b/stubs/setuptools/setuptools/_distutils/command/install.pyi new file mode 100644 index 000000000000..77d083545d05 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install.pyi @@ -0,0 +1,60 @@ +from _typeshed import Incomplete +from collections import ChainMap +from typing import Any, ClassVar + +from ..cmd import Command + +class install(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + prefix: str | None + exec_prefix: Incomplete + home: str | None + user: bool + install_base: Incomplete + install_platbase: Incomplete + root: str | None + install_purelib: str | None + install_platlib: str | None + install_headers: str | None + install_lib: str | None + install_scripts: str | None + install_data: str | None + install_userbase: Incomplete + install_usersite: Incomplete + compile: Incomplete + optimize: Incomplete + extra_path: Incomplete + install_path_file: bool + force: bool + skip_build: bool + warn_dir: bool + build_base: Incomplete + build_lib: Incomplete + record: Incomplete + def initialize_options(self) -> None: ... + config_vars: ChainMap[str, Any] # Any: Same as sysconfig.get_config_vars + install_libbase: Incomplete + def finalize_options(self) -> None: ... + def dump_dirs(self, msg) -> None: ... + def finalize_unix(self) -> None: ... + def finalize_other(self) -> None: ... + def select_scheme(self, name) -> None: ... + def expand_basedirs(self) -> None: ... + def expand_dirs(self) -> None: ... + def convert_paths(self, *names) -> None: ... + path_file: Incomplete + extra_dirs: Incomplete + def handle_extra_path(self) -> None: ... + def change_roots(self, *names) -> None: ... + def create_home_path(self) -> None: ... + def run(self) -> None: ... + def create_path_file(self) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... + def has_lib(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data(self) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_data.pyi b/stubs/setuptools/setuptools/_distutils/command/install_data.pyi new file mode 100644 index 000000000000..777e28428fe6 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_data.pyi @@ -0,0 +1,20 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_data(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: Incomplete + install_dir: Incomplete + outfiles: Incomplete + root: Incomplete + force: bool + data_files: Incomplete + warn_dir: bool + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi b/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi new file mode 100644 index 000000000000..2494af393e19 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_lib.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete, MaybeNone +from typing import ClassVar + +from ..cmd import Command + +class install_lib(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + install_dir: Incomplete + build_dir: Incomplete + force: bool + compile: Incomplete + optimize: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def build(self) -> None: ... + def install(self) -> list[str] | MaybeNone: ... + def byte_compile(self, files) -> None: ... + def get_outputs(self): ... + def get_inputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi b/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi new file mode 100644 index 000000000000..356e8621ee10 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/install_scripts.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from ..cmd import Command + +class install_scripts(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + force: bool + build_dir: Incomplete + skip_build: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + outfiles: list[str] + def run(self) -> None: ... + def get_inputs(self): ... + def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/_distutils/command/sdist.pyi b/stubs/setuptools/setuptools/_distutils/command/sdist.pyi new file mode 100644 index 000000000000..4dc38b055cc6 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/command/sdist.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete, Unused +from collections.abc import Callable +from typing import ClassVar + +from ..cmd import Command + +def show_formats() -> None: ... + +class sdist(Command): + description: ClassVar[str] + + def checking_metadata(self): ... + + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]] + negative_opt: ClassVar[dict[str, str]] + READMES: ClassVar[tuple[str, ...]] + template: Incomplete + manifest: Incomplete + use_defaults: bool + prune: bool + manifest_only: bool + force_manifest: bool + formats: Incomplete + keep_temp: bool + dist_dir: Incomplete + archive_files: Incomplete + metadata_check: int # Soon to be updated to boolean upstream + owner: Incomplete + group: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + filelist: Incomplete + def run(self) -> None: ... + def get_file_list(self) -> None: ... + def add_defaults(self) -> None: ... + def read_template(self) -> None: ... + def prune_file_list(self) -> None: ... + def write_manifest(self) -> None: ... + def read_manifest(self) -> None: ... + def make_release_tree(self, base_dir, files) -> None: ... + def make_distribution(self) -> None: ... + def get_archive_files(self): ... + +def is_comment(line: str) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/compat/__init__.pyi b/stubs/setuptools/setuptools/_distutils/compat/__init__.pyi new file mode 100644 index 000000000000..7325c194f699 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compat/__init__.pyi @@ -0,0 +1,6 @@ +from collections.abc import Iterable +from typing import TypeVar + +_IterableT = TypeVar("_IterableT", bound=Iterable[str]) + +def consolidate_linker_args(args: _IterableT) -> _IterableT | str: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi new file mode 100644 index 000000000000..041c2ef772c0 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/base.pyi @@ -0,0 +1,217 @@ +from _typeshed import BytesPath, Incomplete, StrOrBytesPath, StrPath, Unused +from collections.abc import Callable, Iterable, MutableSequence, Sequence +from subprocess import _ENV +from typing import ClassVar, Final, Literal, TypeAlias, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack, deprecated + +_Macro: TypeAlias = tuple[str] | tuple[str, str | None] +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) +_Ts = TypeVarTuple("_Ts") + +class Compiler: + compiler_type: ClassVar[str] + executables: ClassVar[dict[str, Incomplete]] + + # Subclasses that rely on the standard filename generation methods + # implemented below should override these + src_extensions: ClassVar[list[str] | None] + obj_extension: ClassVar[str | None] + static_lib_extension: ClassVar[str | None] + shared_lib_extension: ClassVar[str | None] + static_lib_format: ClassVar[str | None] + shared_lib_format: ClassVar[str | None] + exe_extension: ClassVar[str | None] + + language_map: ClassVar[dict[str, str]] + language_order: ClassVar[list[str]] + force: bool + verbose: bool + output_dir: str | None + macros: list[_Macro] + include_dirs: list[str] + libraries: list[str] + library_dirs: list[str] + runtime_library_dirs: list[str] + objects: list[str] + + SHARED_OBJECT: Final = "shared_object" + SHARED_LIBRARY: Final = "shared_library" + EXECUTABLE: Final = "executable" + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def add_include_dir(self, dir: str) -> None: ... + def set_include_dirs(self, dirs: list[str]) -> None: ... + def add_library(self, libname: str) -> None: ... + def set_libraries(self, libnames: list[str]) -> None: ... + def add_library_dir(self, dir: str) -> None: ... + def set_library_dirs(self, dirs: list[str]) -> None: ... + def add_runtime_library_dir(self, dir: str) -> None: ... + def set_runtime_library_dirs(self, dirs: list[str]) -> None: ... + def define_macro(self, name: str, value: str | None = None) -> None: ... + def undefine_macro(self, name: str) -> None: ... + def add_link_object(self, object: str) -> None: ... + def set_link_objects(self, objects: list[str]) -> None: ... + def detect_language(self, sources: str | list[str]) -> str | None: ... + def find_library_file(self, dirs: Iterable[str], lib: str, debug: bool = False) -> str | None: ... + + @overload + def has_function( + self, funcname: str, libraries: list[str] | None = None, library_dirs: list[str] | tuple[str, ...] | None = None + ) -> bool: ... + @overload + @deprecated("The `includes`, `include_dirs` parameters are deprecated.") + def has_function( + self, + funcname: str, + includes: Iterable[str] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + libraries: list[str] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + ) -> bool: ... + + def library_dir_option(self, dir: str) -> str: ... + def library_option(self, lib: str) -> str: ... + def runtime_library_dir_option(self, dir: str) -> str | list[str]: ... + def set_executables(self, **kwargs: str) -> None: ... + def set_executable(self, key: str, value) -> None: ... + def compile( + self, + sources: Sequence[StrPath], + output_dir: str | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + depends: list[str] | tuple[str, ...] | None = None, + ) -> list[str]: ... + def create_static_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + debug: bool = False, + target_lang: str | None = None, + ) -> None: ... + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_executable( + self, + objects: list[str] | tuple[str, ...], + output_progname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_lib( + self, + objects: list[str] | tuple[str, ...], + output_libname: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def link_shared_object( + self, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + def preprocess( + self, + source: StrPath, + output_file: StrPath | None = None, + macros: list[_Macro] | None = None, + include_dirs: list[str] | tuple[str, ...] | None = None, + extra_preargs: list[str] | None = None, + extra_postargs: Iterable[str] | None = None, + ) -> None: ... + + @overload + def executable_filename(self, basename: str, strip_dir: Literal[False] = False, output_dir: StrPath = "") -> str: ... + @overload + def executable_filename(self, basename: StrPath, strip_dir: Literal[True], output_dir: StrPath = "") -> str: ... + + def library_filename( + self, libname: str, lib_type: str = "static", strip_dir: bool = False, output_dir: StrPath = "" + ) -> str: ... + @property + def out_extensions(self) -> dict[str, str]: ... + def object_filenames( + self, source_filenames: Iterable[StrPath], strip_dir: bool = False, output_dir: StrPath | None = "" + ) -> list[str]: ... + + @overload + def shared_object_filename(self, basename: str, strip_dir: Literal[False] = False, output_dir: StrPath = "") -> str: ... + @overload + def shared_object_filename(self, basename: StrPath, strip_dir: Literal[True], output_dir: StrPath = "") -> str: ... + + def execute( + self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 + ) -> None: ... + + @overload + def spawn(self, cmd: Sequence[StrOrBytesPath], *, search_path: Literal[False], env: _ENV | None = None) -> None: ... + @overload + def spawn( + self, cmd: MutableSequence[bytes | StrPath], *, search_path: Literal[True] = True, env: _ENV | None = None + ) -> None: ... + + def mkpath(self, name: str, mode: int = 0o777) -> None: ... + + @overload + def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ... + @overload + def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ... + + def announce(self, msg: str, level: int = 1) -> None: ... + def warn(self, msg: str) -> None: ... + def debug_print(self, msg: str) -> None: ... + +def get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: ... + +compiler_class: dict[str, tuple[str, str, str]] + +def show_compilers() -> None: ... +def new_compiler( + plat: str | None = None, compiler: str | None = None, verbose: bool = False, force: bool = False +) -> Compiler: ... +def gen_preprocess_options(macros: Iterable[_Macro], include_dirs: Iterable[str]) -> list[str]: ... +def gen_lib_options( + compiler: Compiler, library_dirs: Iterable[str], runtime_library_dirs: Iterable[str], libraries: Iterable[str] +) -> list[str]: ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi new file mode 100644 index 000000000000..14fd3bdc641c --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi @@ -0,0 +1,68 @@ +from _typeshed import StrPath +from collections.abc import Callable, Iterable +from shlex import _ShlexInstream +from typing import ClassVar, Final, Literal +from typing_extensions import Never, deprecated + +from ...version import LooseVersion +from . import unix + +def get_msvcr() -> list[str]: ... + +class Compiler(unix.Compiler): + compiler_type: ClassVar[str] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + dylib_lib_extension: ClassVar[str] + static_lib_format: ClassVar[str] + shared_lib_format: ClassVar[str] + dylib_lib_format: ClassVar[str] + exe_extension: ClassVar[str] + cc: str + cxx: str + linker_dll: str + linker_dll_cxx: str + dll_libraries: list[str] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + @property + @deprecated( + "gcc_version attribute of CygwinCCompiler is deprecated. " + "Instead of returning actual gcc version a fixed value 11.2.0 is returned." + ) + def gcc_version(self) -> LooseVersion: ... + # `objects` and `libraries` uses list methods + def link( + self, + target_desc: str, + objects: list[str], # type: ignore[override] + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | None = None, # type: ignore[override] + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... + # cygwin doesn't support rpath; prints a warning and returns an empty list + def runtime_library_dir_option(self, dir: str) -> list[Never]: ... # type: ignore[override] + @property + def out_extensions(self) -> dict[str, str]: ... + +class MinGW32Compiler(Compiler): + compiler_type: ClassVar[str] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def runtime_library_dir_option(self, dir: str) -> Never: ... + +CONFIG_H_OK: Final = "ok" +CONFIG_H_NOTOK: Final = "not ok" +CONFIG_H_UNCERTAIN: Final = "uncertain" + +def check_config_h() -> tuple[Literal["ok", "not ok", "uncertain"], str]: ... +def is_cygwincc(cc: str | _ShlexInstream) -> bool: ... + +get_versions: Callable[[], tuple[LooseVersion | None, ...]] | None diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi new file mode 100644 index 000000000000..5c3cf1e9f0c6 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/errors.pyi @@ -0,0 +1,6 @@ +class Error(Exception): ... +class PreprocessError(Error): ... +class CompileError(Error): ... +class LibError(Error): ... +class LinkError(Error): ... +class UnknownFileType(Error): ... diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi new file mode 100644 index 000000000000..ef06b85f4d74 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/msvc.pyi @@ -0,0 +1,23 @@ +from _typeshed import StrPath +from collections.abc import Sequence +from typing import ClassVar, Final + +from . import base + +PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] + +class Compiler(base.Compiler): + src_extensions: ClassVar[list[str]] + res_extension: ClassVar[str] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + shared_lib_format: ClassVar[str] + static_lib_format = shared_lib_format # pyrefly: ignore [unknown-name] + exe_extension: ClassVar[str] + initialized: bool + plat_name: str | None + def initialize(self, plat_name: str | None = None) -> None: ... + @property + def out_extensions(self) -> dict[str, str]: ... + def spawn(self, cmd: Sequence[bytes | StrPath]): ... # type: ignore[override] # Less params diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi new file mode 100644 index 000000000000..2e78f191dd55 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/unix.pyi @@ -0,0 +1,16 @@ +from typing import ClassVar + +from . import base + +class Compiler(base.Compiler): + src_extensions: ClassVar[list[str]] + obj_extension: ClassVar[str] + static_lib_extension: ClassVar[str] + shared_lib_extension: ClassVar[str] + dylib_lib_extension: ClassVar[str] + xcode_stub_lib_extension: ClassVar[str] + static_lib_format: ClassVar[str] + shared_lib_format: ClassVar[str] + dylib_lib_format: ClassVar[str] + xcode_stub_lib_format: ClassVar[str] + def runtime_library_dir_option(self, dir: str) -> str | list[str]: ... # type: ignore[override] diff --git a/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi b/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi new file mode 100644 index 000000000000..d948cbbf8056 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/compilers/C/zos.pyi @@ -0,0 +1,27 @@ +from _typeshed import StrPath +from collections.abc import Iterable +from typing import ClassVar, Literal + +from . import unix + +class Compiler(unix.Compiler): + src_extensions: ClassVar[list[str]] + zos_compiler: Literal["ibm-openxl", "ibm-xlclang", "ibm-xlc"] + def __init__(self, verbose: bool = False, force: bool = False) -> None: ... + def runtime_library_dir_option(self, dir: str) -> str: ... + def link( + self, + target_desc: str, + objects: list[str] | tuple[str, ...], + output_filename: str, + output_dir: str | None = None, + libraries: list[str] | tuple[str, ...] | None = None, + library_dirs: list[str] | tuple[str, ...] | None = None, + runtime_library_dirs: list[str] | tuple[str, ...] | None = None, + export_symbols: Iterable[str] | None = None, + debug: bool = False, + extra_preargs: list[str] | None = None, + extra_postargs: list[str] | None = None, + build_temp: StrPath | None = None, + target_lang: str | None = None, + ) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi b/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi new file mode 100644 index 000000000000..db2a886c6882 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/cygwinccompiler.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable + +from .compilers.C import cygwin +from .compilers.C.cygwin import ( + CONFIG_H_NOTOK as CONFIG_H_NOTOK, + CONFIG_H_OK as CONFIG_H_OK, + CONFIG_H_UNCERTAIN as CONFIG_H_UNCERTAIN, + check_config_h as check_config_h, + get_msvcr as get_msvcr, + is_cygwincc as is_cygwincc, +) +from .version import LooseVersion + +__all__ = [ + "CONFIG_H_NOTOK", + "CONFIG_H_OK", + "CONFIG_H_UNCERTAIN", + "CygwinCCompiler", + "Mingw32CCompiler", + "check_config_h", + "get_msvcr", + "is_cygwincc", +] + +CygwinCCompiler = cygwin.Compiler +Mingw32CCompiler = cygwin.MinGW32Compiler + +get_versions: Callable[[], tuple[LooseVersion | None, ...]] | None diff --git a/stubs/setuptools/setuptools/_distutils/dep_util.pyi b/stubs/setuptools/setuptools/_distutils/dep_util.pyi new file mode 100644 index 000000000000..88cd92f00160 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/dep_util.pyi @@ -0,0 +1 @@ +from ._modified import newer as newer, newer_group as newer_group, newer_pairwise as newer_pairwise diff --git a/stubs/setuptools/setuptools/_distutils/dist.pyi b/stubs/setuptools/setuptools/_distutils/dist.pyi new file mode 100644 index 000000000000..664c33f71a46 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/dist.pyi @@ -0,0 +1,179 @@ +from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsWrite +from collections.abc import Iterable, MutableMapping +from re import Pattern +from typing import IO, ClassVar, Literal, TypeAlias, TypeVar, overload + +from .cmd import Command +from .extension import Extension + +command_re: Pattern[str] + +_OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str | None, str]] +_CommandT = TypeVar("_CommandT", bound=Command) + +class DistributionMetadata: + def __init__(self, path: StrOrBytesPath | None = None) -> None: ... + name: str | None + version: str | None + author: str | None + author_email: str | None + maintainer: str | None + maintainer_email: str | None + url: str | None + license: str | None + description: str | None + long_description: str | None + keywords: str | list[str] | None + platforms: str | list[str] | None + classifiers: str | list[str] | None + download_url: str | None + provides: list[str] | None + requires: list[str] | None + obsoletes: list[str] | None + def read_pkg_file(self, file: IO[str]) -> None: ... + def write_pkg_info(self, base_dir: StrPath) -> None: ... + def write_pkg_file(self, file: SupportsWrite[str]) -> None: ... + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str | None: ... + def get_author_email(self) -> str | None: ... + def get_maintainer(self) -> str | None: ... + def get_maintainer_email(self) -> str | None: ... + def get_contact(self) -> str | None: ... + def get_contact_email(self) -> str | None: ... + def get_url(self) -> str | None: ... + def get_license(self) -> str | None: ... + get_licence = get_license + def get_description(self) -> str | None: ... + def get_long_description(self) -> str | None: ... + def get_keywords(self) -> str | list[str]: ... + def set_keywords(self, value: str | Iterable[str]) -> None: ... + def get_platforms(self) -> str | list[str] | None: ... + def set_platforms(self, value: str | Iterable[str]) -> None: ... + def get_classifiers(self) -> str | list[str]: ... + def set_classifiers(self, value): ... + def get_download_url(self) -> str | None: ... + def get_requires(self) -> str | list[str]: ... + def set_requires(self, value: Iterable[str]) -> None: ... + def get_provides(self) -> str | list[str]: ... + def set_provides(self, value: Iterable[str]) -> None: ... + def get_obsoletes(self) -> str | list[str]: ... + def set_obsoletes(self, value: Iterable[str]) -> None: ... + +class Distribution: + cmdclass: dict[str, type[Command]] + metadata: DistributionMetadata + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... + def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... + def parse_config_files(self, filenames: Iterable[str] | None = None) -> None: ... + global_options: ClassVar[_OptionsList] + common_usage: ClassVar[str] + display_options: ClassVar[_OptionsList] + display_option_names: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + verbose: bool + help: bool + command_packages: str | list[str] | None + script_name: StrPath | None + script_args: list[str] | None + command_options: dict[str, dict[str, tuple[str, str]]] + dist_files: list[tuple[str, str, str]] + packages: list[str] | None + package_data: dict[str, list[str]] + package_dir: dict[str, str] | None + py_modules: list[str] | None + libraries: Incomplete + headers: Incomplete + ext_modules: list[Extension] | None + ext_package: Incomplete + include_dirs: Incomplete + extra_path: Incomplete + scripts: Incomplete + data_files: list[str | tuple[Incomplete, ...]] | None + password: str + command_obj: dict[str, Command] + have_run: dict[str, bool] + want_user_cfg: bool + def dump_option_dicts(self, header=None, commands=None, indent: str = "") -> None: ... + def find_config_files(self): ... + commands: Incomplete + def parse_command_line(self): ... + def finalize_options(self) -> None: ... + def handle_display_options(self, option_order): ... + def print_command_list(self, commands, header, max_length) -> None: ... + def print_commands(self) -> None: ... + def get_command_list(self): ... + def get_command_packages(self): ... + + # NOTE: Because this is private setuptools implementation and we don't re-expose all commands here, + # we're not overloading each and every command possibility. + @overload + def get_command_obj(self, command: str, create: Literal[True] = True) -> Command: ... + @overload + def get_command_obj(self, command: str, create: Literal[False]) -> Command | None: ... + + def get_command_class(self, command: str) -> type[Command]: ... + + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def announce(self, msg, level: int = 20) -> None: ... + def run_commands(self) -> None: ... + def run_command(self, command: str) -> None: ... + def has_pure_modules(self) -> bool: ... + def has_ext_modules(self) -> bool: ... + def has_c_libraries(self) -> bool: ... + def has_modules(self) -> bool: ... + def has_headers(self) -> bool: ... + def has_scripts(self) -> bool: ... + def has_data_files(self) -> bool: ... + def is_pure(self) -> bool: ... + + # Default getter methods generated in __init__ from self.metadata._METHOD_BASENAMES + def get_name(self) -> str: ... + def get_version(self) -> str: ... + def get_fullname(self) -> str: ... + def get_author(self) -> str: ... + def get_author_email(self) -> str: ... + def get_maintainer(self) -> str: ... + def get_maintainer_email(self) -> str: ... + def get_contact(self) -> str: ... + def get_contact_email(self) -> str: ... + def get_url(self) -> str: ... + def get_license(self) -> str: ... + def get_licence(self) -> str: ... + def get_description(self) -> str: ... + def get_long_description(self) -> str: ... + def get_keywords(self) -> str | list[str]: ... + def get_platforms(self) -> str | list[str]: ... + def get_classifiers(self) -> str | list[str]: ... + def get_download_url(self) -> str: ... + def get_requires(self) -> list[str]: ... + def get_provides(self) -> list[str]: ... + def get_obsoletes(self) -> list[str]: ... + + # Default attributes generated in __init__ from self.display_option_names + help_commands: bool + name: str | Literal[False] + version: str | Literal[False] + fullname: str | Literal[False] + author: str | Literal[False] + author_email: str | Literal[False] + maintainer: str | Literal[False] + maintainer_email: str | Literal[False] + contact: str | Literal[False] + contact_email: str | Literal[False] + url: str | Literal[False] + license: str | Literal[False] + licence: str | Literal[False] + description: str | Literal[False] + long_description: str | Literal[False] + platforms: str | list[str] | Literal[False] + classifiers: str | list[str] | Literal[False] + keywords: str | list[str] | Literal[False] + provides: list[str] | Literal[False] + requires: list[str] | Literal[False] + obsoletes: list[str] | Literal[False] diff --git a/stubs/setuptools/setuptools/_distutils/errors.pyi b/stubs/setuptools/setuptools/_distutils/errors.pyi new file mode 100644 index 000000000000..79eb7f7baa0f --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/errors.pyi @@ -0,0 +1,25 @@ +from .compilers.C.errors import ( + CompileError as CompileError, + Error as _Error, + LibError as LibError, + LinkError as LinkError, + PreprocessError as PreprocessError, + UnknownFileType as _UnknownFileType, +) + +CCompilerError = _Error +UnknownFileError = _UnknownFileType + +class DistutilsError(Exception): ... +class DistutilsModuleError(DistutilsError): ... +class DistutilsClassError(DistutilsError): ... +class DistutilsGetoptError(DistutilsError): ... +class DistutilsArgError(DistutilsError): ... +class DistutilsFileError(DistutilsError): ... +class DistutilsOptionError(DistutilsError): ... +class DistutilsSetupError(DistutilsError): ... +class DistutilsPlatformError(DistutilsError): ... +class DistutilsExecError(DistutilsError): ... +class DistutilsInternalError(DistutilsError): ... +class DistutilsTemplateError(DistutilsError): ... +class DistutilsByteCompileError(DistutilsError): ... diff --git a/stubs/setuptools/setuptools/_distutils/extension.pyi b/stubs/setuptools/setuptools/_distutils/extension.pyi new file mode 100644 index 000000000000..1aee26696a94 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/extension.pyi @@ -0,0 +1,39 @@ +from _typeshed import StrPath +from collections.abc import Iterable + +class Extension: + name: str + sources: list[str] + include_dirs: list[str] + define_macros: list[tuple[str, str | None]] + undef_macros: list[str] + library_dirs: list[str] + libraries: list[str] + runtime_library_dirs: list[str] + extra_objects: list[str] + extra_compile_args: list[str] + extra_link_args: list[str] + export_symbols: list[str] + swig_opts: list[str] + depends: list[str] + language: str | None + optional: bool | None + def __init__( + self, + name: str, + sources: Iterable[StrPath], + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, + ) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/filelist.pyi b/stubs/setuptools/setuptools/_distutils/filelist.pyi new file mode 100644 index 000000000000..39c3e77d79fc --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/filelist.pyi @@ -0,0 +1,40 @@ +from _typeshed import StrPath, Unused +from collections.abc import Iterable +from re import Pattern +from typing import Literal, overload + +# class is entirely undocumented +class FileList: + allfiles: Iterable[str] | None + files: list[str] + def __init__(self, warn: Unused = None, debug_print: Unused = None) -> None: ... + def set_allfiles(self, allfiles: Iterable[str]) -> None: ... + def findall(self, dir: StrPath = ".") -> None: ... + def debug_print(self, msg: object) -> None: ... + def append(self, item: str) -> None: ... + def extend(self, items: Iterable[str]) -> None: ... + def sort(self) -> None: ... + def remove_duplicates(self) -> None: ... + def process_template_line(self, line: str) -> None: ... + + @overload + def include_pattern( + self, pattern: str, anchor: bool = True, prefix: str | None = None, is_regex: Literal[False] = False + ) -> bool: ... + @overload + def include_pattern( + self, pattern: str | Pattern[str], anchor: bool = True, prefix: str | None = None, *, is_regex: Literal[True] + ) -> bool: ... + @overload + def include_pattern(self, pattern: str | Pattern[str], anchor: bool, prefix: str | None, is_regex: Literal[True]) -> bool: ... + + @overload + def exclude_pattern( + self, pattern: str, anchor: bool = True, prefix: str | None = None, is_regex: Literal[False] = False + ) -> bool: ... + @overload + def exclude_pattern( + self, pattern: str | Pattern[str], anchor: bool = True, prefix: str | None = None, *, is_regex: Literal[True] + ) -> bool: ... + @overload + def exclude_pattern(self, pattern: str | Pattern[str], anchor: bool, prefix: str | None, is_regex: Literal[True]) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/spawn.pyi b/stubs/setuptools/setuptools/_distutils/spawn.pyi new file mode 100644 index 000000000000..c76535e0bf5e --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/spawn.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrOrBytesPath, StrPath, Unused +from collections.abc import MutableSequence, Sequence +from subprocess import _ENV +from typing import Literal, overload + +@overload +def spawn( + cmd: Sequence[StrOrBytesPath], search_path: Literal[False], verbose: Unused = False, env: _ENV | None = None +) -> None: ... +@overload +def spawn( + cmd: MutableSequence[bytes | StrPath], search_path: Literal[True] = True, verbose: Unused = False, env: _ENV | None = None +) -> None: ... + +def find_executable(executable: str, path: str | None = None) -> str | None: ... diff --git a/stubs/setuptools/setuptools/_distutils/sysconfig.pyi b/stubs/setuptools/setuptools/_distutils/sysconfig.pyi new file mode 100644 index 000000000000..e3b0292ef39b --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/sysconfig.pyi @@ -0,0 +1,24 @@ +from typing import Final, Literal, overload +from typing_extensions import deprecated + +from setuptools._distutils.ccompiler import CCompiler + +PREFIX: Final[str] +EXEC_PREFIX: Final[str] + +@overload +@deprecated("SO is deprecated, use EXT_SUFFIX. Support will be removed when this module is synchronized with stdlib Python 3.11") +def get_config_var(name: Literal["SO"]) -> int | str | None: ... +@overload +def get_config_var(name: str) -> int | str | None: ... + +@overload +def get_config_vars() -> dict[str, str | int]: ... +@overload +def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... + +def get_config_h_filename() -> str: ... +def get_makefile_filename() -> str: ... +def get_python_inc(plat_specific: bool = False, prefix: str | None = None) -> str: ... +def get_python_lib(plat_specific: bool = False, standard_lib: bool = False, prefix: str | None = None) -> str: ... +def customize_compiler(compiler: CCompiler) -> None: ... diff --git a/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi b/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi new file mode 100644 index 000000000000..9cd30ad9a64e --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/unixccompiler.pyi @@ -0,0 +1,3 @@ +from .compilers.C import unix + +UnixCCompiler = unix.Compiler diff --git a/stubs/setuptools/setuptools/_distutils/util.pyi b/stubs/setuptools/setuptools/_distutils/util.pyi new file mode 100644 index 000000000000..1f9ef45e5ab8 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/util.pyi @@ -0,0 +1,34 @@ +from _typeshed import GenericPath, StrPath, Unused +from collections.abc import Callable, Iterable, Mapping +from typing import AnyStr, Literal +from typing_extensions import TypeVarTuple, Unpack + +_Ts = TypeVarTuple("_Ts") + +def get_host_platform() -> str: ... +def get_platform() -> str: ... +def get_macosx_target_ver_from_syscfg(): ... +def get_macosx_target_ver(): ... +def split_version(s: str) -> list[int]: ... +def convert_path(pathname: StrPath) -> str: ... +def change_root(new_root: GenericPath[AnyStr], pathname: GenericPath[AnyStr]) -> AnyStr: ... +def check_environ() -> None: ... +def subst_vars(s: str, local_vars: Mapping[str, object]) -> str: ... +def grok_environment_error(exc: object, prefix: str = "error: ") -> str: ... +def split_quoted(s: str) -> list[str]: ... +def execute( + func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, verbose: bool = False +) -> None: ... +def strtobool(val: str) -> Literal[0, 1]: ... +def byte_compile( + py_files: Iterable[str], + optimize: int = 0, + force: bool = False, + prefix: str | None = None, + base_dir: str | None = None, + verbose: bool = True, + direct: bool | None = None, +) -> None: ... +def rfc822_escape(header: str) -> str: ... +def is_mingw() -> bool: ... +def is_freethreaded() -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/version.pyi b/stubs/setuptools/setuptools/_distutils/version.pyi new file mode 100644 index 000000000000..94b0512e37f5 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/version.pyi @@ -0,0 +1,35 @@ +from abc import abstractmethod +from re import Pattern +from typing_extensions import Self, deprecated + +@deprecated("The `Version` class is deprecated. Use `packaging.version` instead.") +class Version: + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: Self | str) -> bool: ... + def __le__(self, other: Self | str) -> bool: ... + def __gt__(self, other: Self | str) -> bool: ... + def __ge__(self, other: Self | str) -> bool: ... + @abstractmethod + def __init__(self, vstring: str | None = None) -> None: ... + @abstractmethod + def parse(self, vstring: str) -> Self: ... + @abstractmethod + def _cmp(self, other: Self | str) -> bool: ... + +@deprecated("The `StrictVersion` class is deprecated. Use `packaging.version` instead.") +class StrictVersion(Version): + version_re: Pattern[str] + version: tuple[int, int, int] + prerelease: tuple[str, int] | None + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def _cmp(self, other: Self | str) -> bool: ... + +@deprecated("The `LooseVersion` class is deprecated. Use `packaging.version` instead.") +class LooseVersion(Version): + component_re: Pattern[str] + vstring: str + version: tuple[str | int, ...] + def __init__(self, vstring: str | None = None) -> None: ... + def parse(self, vstring: str) -> Self: ... + def _cmp(self, other: Self | str) -> bool: ... diff --git a/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi b/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi new file mode 100644 index 000000000000..e49630ac6ed8 --- /dev/null +++ b/stubs/setuptools/setuptools/_distutils/zosccompiler.pyi @@ -0,0 +1,3 @@ +from .compilers.C import zos + +zOSCCompiler = zos.Compiler diff --git a/stubs/setuptools/setuptools/archive_util.pyi b/stubs/setuptools/setuptools/archive_util.pyi new file mode 100644 index 000000000000..acadce09a7ca --- /dev/null +++ b/stubs/setuptools/setuptools/archive_util.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from collections.abc import Callable + +from ._distutils.errors import DistutilsError + +__all__ = [ + "unpack_archive", + "unpack_zipfile", + "unpack_tarfile", + "default_filter", + "UnrecognizedFormat", + "extraction_drivers", + "unpack_directory", +] + +class UnrecognizedFormat(DistutilsError): ... + +def default_filter(src, dst): ... +def unpack_archive(filename, extract_dir, progress_filter=..., drivers=None) -> None: ... +def unpack_directory(filename, extract_dir, progress_filter=...) -> None: ... +def unpack_zipfile(filename, extract_dir, progress_filter=...) -> None: ... +def unpack_tarfile(filename, extract_dir, progress_filter=...): ... + +extraction_drivers: tuple[Callable[..., Incomplete], ...] diff --git a/stubs/setuptools/setuptools/build_meta.pyi b/stubs/setuptools/setuptools/build_meta.pyi new file mode 100644 index 000000000000..08f3128cda37 --- /dev/null +++ b/stubs/setuptools/setuptools/build_meta.pyi @@ -0,0 +1,64 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Mapping +from contextlib import _GeneratorContextManager +from typing import TypeAlias +from typing_extensions import Never + +from . import dist + +__all__ = [ + "get_requires_for_build_sdist", + "get_requires_for_build_wheel", + "prepare_metadata_for_build_wheel", + "build_wheel", + "build_sdist", + "get_requires_for_build_editable", + "prepare_metadata_for_build_editable", + "build_editable", + "__legacy__", + "SetupRequirementsError", +] + +_ConfigSettings: TypeAlias = Mapping[str, str | list[str] | None] | None + +class SetupRequirementsError(BaseException): + specifiers: Incomplete + def __init__(self, specifiers) -> None: ... + +class Distribution(dist.Distribution): + def fetch_build_eggs(self, specifiers) -> Never: ... + @classmethod + def patch(cls) -> _GeneratorContextManager[None]: ... + +class _BuildMetaBackend: + def run_setup(self, setup_script: str = "setup.py") -> None: ... + def get_requires_for_build_wheel(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def get_requires_for_build_sdist(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def prepare_metadata_for_build_wheel(self, metadata_directory: StrPath, config_settings: _ConfigSettings = None) -> str: ... + def build_wheel( + self, wheel_directory: StrPath, config_settings: _ConfigSettings = None, metadata_directory: StrPath | None = None + ) -> str: ... + def build_sdist(self, sdist_directory: StrPath, config_settings: _ConfigSettings = None) -> str: ... + def build_editable( + self, wheel_directory: StrPath, config_settings: _ConfigSettings = None, metadata_directory: StrPath | None = None + ) -> str: ... + def get_requires_for_build_editable(self, config_settings: _ConfigSettings = None) -> list[str]: ... + def prepare_metadata_for_build_editable( + self, metadata_directory: StrPath, config_settings: _ConfigSettings = None + ) -> str: ... + +class _BuildMetaLegacyBackend(_BuildMetaBackend): + def run_setup(self, setup_script: str = "setup.py") -> None: ... + +_BACKEND: _BuildMetaBackend +get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel +get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist +prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel +build_wheel = _BACKEND.build_wheel +build_sdist = _BACKEND.build_sdist + +get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable +prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable +build_editable = _BACKEND.build_editable + +__legacy__: _BuildMetaLegacyBackend diff --git a/stubs/setuptools/setuptools/command/__init__.pyi b/stubs/setuptools/setuptools/command/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/setuptools/setuptools/command/alias.pyi b/stubs/setuptools/setuptools/command/alias.pyi new file mode 100644 index 000000000000..cd3b4d9b5b74 --- /dev/null +++ b/stubs/setuptools/setuptools/command/alias.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from .setopt import option_base + +def shquote(arg): ... + +class alias(option_base): + description: str + command_consumes_arguments: bool + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + args: Incomplete + remove: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + +def format_alias(name, aliases): ... diff --git a/stubs/setuptools/setuptools/command/bdist_egg.pyi b/stubs/setuptools/setuptools/command/bdist_egg.pyi new file mode 100644 index 000000000000..dc921dde8c8a --- /dev/null +++ b/stubs/setuptools/setuptools/command/bdist_egg.pyi @@ -0,0 +1,56 @@ +from _typeshed import GenericPath, Incomplete, StrPath +from collections.abc import Iterator +from types import CodeType +from typing import AnyStr, ClassVar, Final, Literal, TypeVar +from zipfile import _ZipFileMode + +from .. import Command + +_StrPathT = TypeVar("_StrPathT", bound=StrPath) + +def strip_module(filename): ... +def sorted_walk(dir: GenericPath[AnyStr]) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... +def write_stub(resource, pyfile) -> None: ... + +class bdist_egg(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + bdist_dir: Incomplete + plat_name: str + keep_temp: bool + dist_dir: Incomplete + skip_build: bool + egg_output: Incomplete + exclude_source_files: Incomplete + def initialize_options(self) -> None: ... + egg_info: Incomplete + def finalize_options(self) -> None: ... + def do_install_data(self) -> None: ... + def get_outputs(self): ... + def call_command(self, cmdname, **kw): ... + stubs: Incomplete + def run(self) -> None: ... + def zap_pyfiles(self) -> None: ... + def zip_safe(self): ... + def gen_header(self) -> Literal["w"]: ... + def copy_metadata_to(self, target_dir) -> None: ... + def get_ext_outputs(self): ... + +NATIVE_EXTENSIONS: Final[dict[str, None]] + +def walk_egg(egg_dir: StrPath) -> Iterator[tuple[str, list[str], list[str]]]: ... +def analyze_egg(egg_dir, stubs): ... +def write_safety_flag(egg_dir, safe) -> None: ... + +safety_flags: Incomplete + +def scan_module(egg_dir, base, name, stubs): ... +def iter_symbols(code: CodeType) -> Iterator[str]: ... +def can_scan() -> bool: ... + +INSTALL_DIRECTORY_ATTRS: Final[list[str]] + +def make_zipfile( + zip_filename: _StrPathT, base_dir, verbose: bool = False, compress: bool = True, mode: _ZipFileMode = "w" +) -> _StrPathT: ... diff --git a/stubs/setuptools/setuptools/command/bdist_rpm.pyi b/stubs/setuptools/setuptools/command/bdist_rpm.pyi new file mode 100644 index 000000000000..cb79f3dbf156 --- /dev/null +++ b/stubs/setuptools/setuptools/command/bdist_rpm.pyi @@ -0,0 +1,7 @@ +from setuptools.dist import Distribution + +from .._distutils.command import bdist_rpm as orig + +class bdist_rpm(orig.bdist_rpm): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/bdist_wheel.pyi b/stubs/setuptools/setuptools/command/bdist_wheel.pyi new file mode 100644 index 000000000000..d6538ab52d4c --- /dev/null +++ b/stubs/setuptools/setuptools/command/bdist_wheel.pyi @@ -0,0 +1,54 @@ +from _typeshed import Incomplete +from collections.abc import Iterable +from typing import ClassVar, Final, Literal + +from setuptools import Command + +def safe_version(version: str) -> str: ... + +setuptools_major_version: Final[int] + +PY_LIMITED_API_PATTERN: Final[str] + +def python_tag() -> str: ... +def get_platform(archive_root: str | None) -> str: ... +def get_flag(var: str, fallback: bool, expected: bool = True, warn: bool = True) -> bool: ... +def get_abi_tag() -> str | None: ... +def safer_version(version: str) -> str: ... + +class bdist_wheel(Command): + description: ClassVar[str] + supported_compressions: ClassVar[dict[str, int]] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + + bdist_dir: str | None + data_dir: str + plat_name: str | None + plat_tag: str | None + format: str + keep_temp: bool + dist_dir: str | None + egginfo_dir: str | None + root_is_pure: bool | None + skip_build: bool + relative: bool + owner: Incomplete | None + group: Incomplete | None + universal: bool + compression: str | int + python_tag: str + build_number: str | None + py_limited_api: str | Literal[False] + plat_name_supplied: bool + + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @property + def wheel_dist_name(self) -> str: ... + def get_tag(self) -> tuple[str, str, str]: ... + def run(self) -> None: ... + def write_wheelfile(self, wheelfile_base: str, generator: str = ...) -> None: ... + @property + def license_paths(self) -> Iterable[str]: ... + def egg2dist(self, egginfo_path: str, distinfo_path: str) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build.pyi b/stubs/setuptools/setuptools/command/build.pyi new file mode 100644 index 000000000000..5263a05bda51 --- /dev/null +++ b/stubs/setuptools/setuptools/command/build.pyi @@ -0,0 +1,18 @@ +from typing import Protocol + +from setuptools.dist import Distribution + +from .._distutils.command.build import build as _build + +class build(_build): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + +class SubCommand(Protocol): + editable_mode: bool + build_lib: str + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_source_files(self) -> list[str]: ... + def get_outputs(self) -> list[str]: ... + def get_output_mapping(self) -> dict[str, str]: ... diff --git a/stubs/setuptools/setuptools/command/build_clib.pyi b/stubs/setuptools/setuptools/command/build_clib.pyi new file mode 100644 index 000000000000..6f657c2c7c2f --- /dev/null +++ b/stubs/setuptools/setuptools/command/build_clib.pyi @@ -0,0 +1,8 @@ +from setuptools.dist import Distribution + +from .._distutils.command import build_clib as orig + +class build_clib(orig.build_clib): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + + def build_libraries(self, libraries) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build_ext.pyi b/stubs/setuptools/setuptools/command/build_ext.pyi new file mode 100644 index 000000000000..34366afb3ee0 --- /dev/null +++ b/stubs/setuptools/setuptools/command/build_ext.pyi @@ -0,0 +1,51 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from setuptools.dist import Distribution + +from .._distutils.command.build_ext import build_ext as _build_ext + +have_rtld: bool +use_stubs: bool +libtype: str + +def get_abi3_suffix(): ... + +class build_ext(_build_ext): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + editable_mode: ClassVar[bool] + inplace: bool + def run(self) -> None: ... + def copy_extensions_to_source(self) -> None: ... + def get_ext_filename(self, fullname): ... + shlib_compiler: Incomplete + shlibs: list[Incomplete] + ext_map: dict[Incomplete, Incomplete] + def initialize_options(self) -> None: ... + extensions: list[Incomplete] + def finalize_options(self) -> None: ... + def setup_shlib_compiler(self) -> None: ... + def get_export_symbols(self, ext): ... + compiler: Incomplete + def build_extension(self, ext) -> None: ... + def links_to_dynamic(self, ext): ... + def get_source_files(self) -> list[str]: ... + def get_outputs(self) -> list[str]: ... + def get_output_mapping(self) -> dict[str, str]: ... + def write_stub(self, output_dir, ext, compile: bool = False) -> None: ... + +def link_shared_object( + self, + objects, + output_libname, + output_dir=None, + libraries=None, + library_dirs=None, + runtime_library_dirs=None, + export_symbols=None, + debug: bool = False, + extra_preargs=None, + extra_postargs=None, + build_temp=None, + target_lang=None, +) -> None: ... diff --git a/stubs/setuptools/setuptools/command/build_py.pyi b/stubs/setuptools/setuptools/command/build_py.pyi new file mode 100644 index 000000000000..7a2435bed01c --- /dev/null +++ b/stubs/setuptools/setuptools/command/build_py.pyi @@ -0,0 +1,43 @@ +from _typeshed import Incomplete, StrPath, Unused +from typing import ClassVar + +from setuptools.dist import Distribution + +from .._distutils.cmd import _StrPathT +from .._distutils.command import build_py as orig + +def make_writable(target) -> None: ... + +class build_py(orig.build_py): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + editable_mode: ClassVar[bool] + package_data: dict[str, list[str]] + exclude_package_data: dict[Incomplete, Incomplete] + def finalize_options(self) -> None: ... + def copy_file( # type: ignore[override] # No overload, str support only + self, + infile: StrPath, + outfile: _StrPathT, + preserve_mode: bool = True, + preserve_times: bool = True, + link: str | None = None, + level: Unused = 1, + ) -> tuple[_StrPathT | str, bool]: ... + def run(self) -> None: ... + data_files: list[tuple[str, str, str, list[str]]] + def __getattr__(self, attr: str): ... + def get_data_files_without_manifest(self) -> list[tuple[str, str, str, list[str]]]: ... + def find_data_files(self, package, src_dir) -> list[str]: ... + def get_outputs(self, include_bytecode: bool = True) -> list[str]: ... # type: ignore[override] # Using a real boolean instead of 0|1 + def build_package_data(self) -> None: ... + manifest_files: dict[str, list[str]] + def get_output_mapping(self) -> dict[str, str]: ... + def analyze_manifest(self) -> None: ... + def get_data_files(self) -> None: ... + def check_package(self, package, package_dir): ... + def initialize_options(self) -> None: ... + packages_checked: dict[Incomplete, Incomplete] + def get_package_dir(self, package: str) -> str: ... + def exclude_data_files(self, package, src_dir, files): ... + +def assert_relative(path): ... diff --git a/stubs/setuptools/setuptools/command/develop.pyi b/stubs/setuptools/setuptools/command/develop.pyi new file mode 100644 index 000000000000..afad2e9a4568 --- /dev/null +++ b/stubs/setuptools/setuptools/command/develop.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from typing import ClassVar +from typing_extensions import deprecated + +from setuptools import Command +from setuptools.warnings import SetuptoolsDeprecationWarning + +class develop(Command): + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + install_dir: Incomplete + no_deps: bool + user: bool + prefix: Incomplete + index_url: Incomplete + def run(self) -> None: ... + @deprecated( + "develop command is deprecated. Please avoid running `setup.py` and `develop`. " + "Instead, use standards-based tools like pip or uv." + ) + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + +class DevelopDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/command/dist_info.pyi b/stubs/setuptools/setuptools/command/dist_info.pyi new file mode 100644 index 000000000000..1343b926905b --- /dev/null +++ b/stubs/setuptools/setuptools/command/dist_info.pyi @@ -0,0 +1,12 @@ +from typing import ClassVar + +from .._distutils.cmd import Command + +class dist_info(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/easy_install.pyi b/stubs/setuptools/setuptools/command/easy_install.pyi new file mode 100644 index 000000000000..101bc1d69449 --- /dev/null +++ b/stubs/setuptools/setuptools/command/easy_install.pyi @@ -0,0 +1,11 @@ +from abc import abstractmethod + +from setuptools import Command + +class easy_install(Command): + @abstractmethod + def initialize_options(self) -> None: ... + @abstractmethod + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/editable_wheel.pyi b/stubs/setuptools/setuptools/command/editable_wheel.pyi new file mode 100644 index 000000000000..d9aececdac84 --- /dev/null +++ b/stubs/setuptools/setuptools/command/editable_wheel.pyi @@ -0,0 +1,78 @@ +from _typeshed import Incomplete, StrPath, Unused +from collections.abc import Iterator, Mapping +from enum import Enum +from pathlib import Path +from types import TracebackType +from typing import ClassVar, Protocol, TypeAlias +from typing_extensions import Self + +from .. import Command, errors, namespaces +from ..dist import Distribution +from ..warnings import SetuptoolsWarning + +# Actually from wheel.wheelfile import WheelFile +_WheelFile: TypeAlias = Incomplete + +class _EditableMode(Enum): + STRICT = "strict" + LENIENT = "lenient" + COMPAT = "compat" + @classmethod + def convert(cls, mode: str | None) -> _EditableMode: ... + +class editable_wheel(Command): + description: str + user_options: ClassVar[list[tuple[str, str | None, str]]] + dist_dir: Incomplete + dist_info_dir: Incomplete + project_dir: Incomplete + mode: Incomplete + def initialize_options(self) -> None: ... + package_dir: dict[Incomplete, Incomplete] + def finalize_options(self) -> None: ... + def run(self) -> None: ... + +class EditableStrategy(Protocol): + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]) -> Unused: ... + def __enter__(self) -> Self: ... + def __exit__( + self, _exc_type: type[BaseException] | None, _exc_value: BaseException | None, _traceback: TracebackType | None + ) -> Unused: ... + +class _StaticPth: + dist: Distribution + name: str + path_entries: list[Path] + def __init__(self, dist: Distribution, name: str, path_entries: list[Path]) -> None: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _LinkTree(_StaticPth): + auxiliary_dir: Path + build_lib: Path + def __init__(self, dist: Distribution, name: str, auxiliary_dir: StrPath, build_lib: StrPath) -> None: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _TopLevelFinder: + dist: Distribution + name: str + def __init__(self, dist: Distribution, name: str) -> None: ... + def template_vars(self) -> tuple[str, str, dict[str, str], dict[str, list[str]]]: ... + def get_implementation(self) -> Iterator[tuple[str, bytes]]: ... + def __call__(self, wheel: _WheelFile, files: list[str], mapping: Mapping[str, str]): ... + def __enter__(self) -> Self: ... + def __exit__(self, _exc_type: Unused, _exc_value: Unused, _traceback: Unused) -> None: ... + +class _NamespaceInstaller(namespaces.Installer): + distribution: Incomplete + src_root: Incomplete + installation_dir: Incomplete + editable_name: Incomplete + outputs: list[str] + def __init__(self, distribution, installation_dir, editable_name, src_root) -> None: ... + +class InformationOnly(SetuptoolsWarning): ... +class LinksNotSupported(errors.FileError): ... diff --git a/stubs/setuptools/setuptools/command/egg_info.pyi b/stubs/setuptools/setuptools/command/egg_info.pyi new file mode 100644 index 000000000000..10069f414f16 --- /dev/null +++ b/stubs/setuptools/setuptools/command/egg_info.pyi @@ -0,0 +1,86 @@ +from _typeshed import Incomplete +from typing import ClassVar, Final + +from .. import Command, SetuptoolsDeprecationWarning +from .._distutils.filelist import FileList as _FileList +from .sdist import sdist + +PY_MAJOR: Final[str] + +def translate_pattern(glob): ... + +class InfoCommon: + tag_build: Incomplete + tag_date: Incomplete + @property + def name(self): ... + def tagged_version(self): ... + def tags(self): ... + @property + def vtags(self): ... + +class egg_info(InfoCommon, Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + negative_opt: ClassVar[dict[str, str]] + egg_base: Incomplete + egg_name: Incomplete + egg_info: Incomplete + egg_version: Incomplete + def initialize_options(self) -> None: ... + + @property + def tag_svn_revision(self) -> int | None: ... + @tag_svn_revision.setter + def tag_svn_revision(self, value) -> None: ... + + def save_version_info(self, filename) -> None: ... + def finalize_options(self) -> None: ... + def write_or_delete_file(self, what, filename, data, force: bool = False) -> None: ... + def write_file(self, what, filename, data) -> None: ... + def delete_file(self, filename) -> None: ... + def run(self) -> None: ... + filelist: Incomplete + def find_sources(self) -> None: ... + +class FileList(_FileList): + def __init__(self, warn=None, debug_print=None, ignore_egg_info_dir: bool = False) -> None: ... + def process_template_line(self, line) -> None: ... + def include(self, pattern): ... + def exclude(self, pattern): ... + def recursive_include(self, dir, pattern): ... + def recursive_exclude(self, dir, pattern): ... + def graft(self, dir): ... + def prune(self, dir): ... + def global_include(self, pattern): ... + def global_exclude(self, pattern): ... + def append(self, item) -> None: ... + def extend(self, paths) -> None: ... + +class manifest_maker(sdist): + template: str + use_defaults: bool + prune: bool + manifest_only: bool + force_manifest: bool + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + filelist: FileList + def run(self) -> None: ... + def write_manifest(self) -> None: ... + def warn(self, msg) -> None: ... + def add_defaults(self) -> None: ... + def add_license_files(self) -> None: ... + +def write_file(filename, contents) -> None: ... +def write_pkg_info(cmd, basename, filename) -> None: ... +def warn_depends_obsolete(cmd, basename, filename) -> None: ... +def write_requirements(cmd, basename, filename) -> None: ... +def write_setup_requirements(cmd, basename, filename) -> None: ... +def write_toplevel_names(cmd, basename, filename) -> None: ... +def overwrite_arg(cmd, basename, filename) -> None: ... +def write_arg(cmd, basename, filename, force: bool = False) -> None: ... +def write_entries(cmd, basename, filename) -> None: ... + +class EggInfoDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/command/install.pyi b/stubs/setuptools/setuptools/command/install.pyi new file mode 100644 index 000000000000..2c4e07f318e2 --- /dev/null +++ b/stubs/setuptools/setuptools/command/install.pyi @@ -0,0 +1,21 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import Any, ClassVar + +from setuptools.dist import Distribution + +from .._distutils.command import install as orig + +class install(orig.install): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] + # Any to work around variance issues + new_commands: ClassVar[list[tuple[str, Callable[[Any], bool]] | None]] + old_and_unmanageable: Incomplete + single_version_externally_managed: bool | None + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + path_file: Incomplete + extra_dirs: str + def handle_extra_path(self): ... diff --git a/stubs/setuptools/setuptools/command/install_egg_info.pyi b/stubs/setuptools/setuptools/command/install_egg_info.pyi new file mode 100644 index 000000000000..2c32f1a6bac2 --- /dev/null +++ b/stubs/setuptools/setuptools/command/install_egg_info.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from .. import Command, namespaces + +class install_egg_info(namespaces.Installer, Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + install_dir: Incomplete + def initialize_options(self) -> None: ... + source: Incomplete + target: str + outputs: list[str] + def finalize_options(self) -> None: ... + def run(self) -> None: ... + def get_outputs(self): ... + def copytree(self): ... diff --git a/stubs/setuptools/setuptools/command/install_lib.pyi b/stubs/setuptools/setuptools/command/install_lib.pyi new file mode 100644 index 000000000000..a7576d20a35a --- /dev/null +++ b/stubs/setuptools/setuptools/command/install_lib.pyi @@ -0,0 +1,20 @@ +from _typeshed import StrPath, Unused + +from setuptools.dist import Distribution + +from .._distutils.command import install_lib as orig + +class install_lib(orig.install_lib): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + def run(self) -> None: ... + def get_exclusions(self): ... + def copy_tree( + self, + infile: StrPath, + outfile: str, + preserve_mode: bool = True, + preserve_times: bool = True, + preserve_symlinks: bool = False, + level: Unused = 1, + ): ... + def get_outputs(self): ... diff --git a/stubs/setuptools/setuptools/command/install_scripts.pyi b/stubs/setuptools/setuptools/command/install_scripts.pyi new file mode 100644 index 000000000000..f131b0f7c4fa --- /dev/null +++ b/stubs/setuptools/setuptools/command/install_scripts.pyi @@ -0,0 +1,11 @@ +from setuptools.dist import Distribution + +from .._distutils.command import install_scripts as orig + +class install_scripts(orig.install_scripts): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + no_ep: bool + def initialize_options(self) -> None: ... + outfiles: list[str] + def run(self) -> None: ... + def write_script(self, script_name, contents, mode: str = "t", *ignored) -> None: ... diff --git a/stubs/setuptools/setuptools/command/rotate.pyi b/stubs/setuptools/setuptools/command/rotate.pyi new file mode 100644 index 000000000000..653a380bc29a --- /dev/null +++ b/stubs/setuptools/setuptools/command/rotate.pyi @@ -0,0 +1,15 @@ +from _typeshed import Incomplete +from typing import ClassVar + +from .. import Command + +class rotate(Command): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + match: Incomplete + dist_dir: Incomplete + keep: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/saveopts.pyi b/stubs/setuptools/setuptools/command/saveopts.pyi new file mode 100644 index 000000000000..c96862b29284 --- /dev/null +++ b/stubs/setuptools/setuptools/command/saveopts.pyi @@ -0,0 +1,5 @@ +from .setopt import option_base + +class saveopts(option_base): + description: str + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/sdist.pyi b/stubs/setuptools/setuptools/command/sdist.pyi new file mode 100644 index 000000000000..77c87df95d0b --- /dev/null +++ b/stubs/setuptools/setuptools/command/sdist.pyi @@ -0,0 +1,24 @@ +from _typeshed import Incomplete +from collections.abc import Iterator +from typing import ClassVar + +from setuptools.dist import Distribution + +from .._distutils.command import sdist as orig + +def walk_revctrl(dirname: str = "") -> Iterator[Incomplete]: ... + +class sdist(orig.sdist): + distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution + user_options: ClassVar[list[tuple[str, str | None, str]]] + negative_opt: ClassVar[dict[str, str]] + README_EXTENSIONS: ClassVar[list[str]] + READMES: ClassVar[tuple[str, ...]] + filelist: Incomplete + def run(self) -> None: ... + def initialize_options(self) -> None: ... + def make_distribution(self) -> None: ... + def prune_file_list(self) -> None: ... + def check_readme(self) -> None: ... + def make_release_tree(self, base_dir, files) -> None: ... + def read_manifest(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/setopt.pyi b/stubs/setuptools/setuptools/command/setopt.pyi new file mode 100644 index 000000000000..62957a112fa4 --- /dev/null +++ b/stubs/setuptools/setuptools/command/setopt.pyi @@ -0,0 +1,33 @@ +from _typeshed import Incomplete +from abc import abstractmethod +from typing import ClassVar + +from .. import Command + +__all__ = ["config_file", "edit_config", "option_base", "setopt"] + +def config_file(kind: str = "local"): ... +def edit_config(filename, settings) -> None: ... + +class option_base(Command): + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + global_config: Incomplete + user_config: Incomplete + filename: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + @abstractmethod + def run(self) -> None: ... + +class setopt(option_base): + description: str + user_options: ClassVar[list[tuple[str, str, str]]] + boolean_options: ClassVar[list[str]] + command: Incomplete + option: Incomplete + set_value: Incomplete + remove: Incomplete + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/stubs/setuptools/setuptools/command/test.pyi b/stubs/setuptools/setuptools/command/test.pyi new file mode 100644 index 000000000000..536179f18f09 --- /dev/null +++ b/stubs/setuptools/setuptools/command/test.pyi @@ -0,0 +1,15 @@ +from typing import ClassVar +from typing_extensions import Never, deprecated + +from .. import Command + +@deprecated("""\ +The test command is disabled and references to it are deprecated. \ +Please remove any references to `setuptools.command.test` in all supported versions of the affected package.\ +""") +class test(Command): + description: ClassVar[str] + user_options: ClassVar[list[tuple[str, str, str]]] + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> Never: ... diff --git a/stubs/setuptools/setuptools/config/__init__.pyi b/stubs/setuptools/setuptools/config/__init__.pyi new file mode 100644 index 000000000000..61e17fdccf16 --- /dev/null +++ b/stubs/setuptools/setuptools/config/__init__.pyi @@ -0,0 +1,3 @@ +from .setupcfg import parse_configuration as parse_configuration, read_configuration as read_configuration + +__all__ = ("parse_configuration", "read_configuration") diff --git a/stubs/setuptools/setuptools/config/expand.pyi b/stubs/setuptools/setuptools/config/expand.pyi new file mode 100644 index 000000000000..c85a43bfcfea --- /dev/null +++ b/stubs/setuptools/setuptools/config/expand.pyi @@ -0,0 +1,50 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Callable, Iterable, Iterator, Mapping +from importlib.machinery import ModuleSpec +from types import TracebackType +from typing import TypeVar +from typing_extensions import Self + +from ..dist import Distribution + +_K = TypeVar("_K") +_V_co = TypeVar("_V_co", covariant=True) + +class StaticModule: + def __init__(self, name: str, spec: ModuleSpec) -> None: ... + def __getattr__(self, attr: str): ... + +def glob_relative(patterns: Iterable[str], root_dir: StrPath | None = None) -> list[str]: ... +def read_files(filepaths: StrPath | Iterable[StrPath], root_dir: StrPath | None = None) -> str: ... +def read_attr(attr_desc: str, package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None): ... +def resolve_class( + qualified_class_name: str, package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None +) -> Callable[..., Incomplete]: ... +def cmdclass( + values: dict[str, str], package_dir: Mapping[str, str] | None = None, root_dir: StrPath | None = None +) -> dict[str, Callable[..., Incomplete]]: ... +def find_packages( + *, namespaces: bool = True, fill_package_dir: dict[str, str] | None = None, root_dir: StrPath | None = None, **kwargs +) -> list[str]: ... +def version(value: Callable[[], Incomplete] | Iterable[str | int] | str) -> str: ... +def canonic_package_data(package_data: dict[Incomplete, Incomplete]) -> dict[Incomplete, Incomplete]: ... +def canonic_data_files( + data_files: list[Incomplete] | dict[Incomplete, Incomplete], root_dir: StrPath | None = None +) -> list[tuple[str, list[str]]]: ... +def entry_points(text: str, text_source: str = "entry-points") -> dict[str, dict[str, str]]: ... + +class EnsurePackagesDiscovered: + def __init__(self, distribution: Distribution) -> None: ... + def __call__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + @property + def package_dir(self) -> LazyMappingProxy[str, str]: ... + +class LazyMappingProxy(Mapping[_K, _V_co]): + def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V_co]]) -> None: ... + def __getitem__(self, key: _K) -> _V_co: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_K]: ... diff --git a/stubs/setuptools/setuptools/config/pyprojecttoml.pyi b/stubs/setuptools/setuptools/config/pyprojecttoml.pyi new file mode 100644 index 000000000000..45febbdafb2d --- /dev/null +++ b/stubs/setuptools/setuptools/config/pyprojecttoml.pyi @@ -0,0 +1,46 @@ +from _typeshed import Incomplete, StrPath +from types import TracebackType +from typing import Any +from typing_extensions import Self + +from ..dist import Distribution +from . import expand + +def load_file(filepath: StrPath) -> dict[Incomplete, Incomplete]: ... +def validate(config: dict[Incomplete, Incomplete], filepath: StrPath) -> bool: ... +def apply_configuration(dist: Distribution, filepath: StrPath, ignore_option_errors: bool = False) -> Distribution: ... +def read_configuration( + filepath: StrPath, expand: bool = True, ignore_option_errors: bool = False, dist: Distribution | None = None +) -> dict[str, Any]: ... +def expand_configuration( + config: dict[Incomplete, Incomplete], + root_dir: StrPath | None = None, + ignore_option_errors: bool = False, + dist: Distribution | None = None, +) -> dict[Incomplete, Incomplete]: ... + +class _ConfigExpander: + config: dict[Incomplete, Incomplete] + root_dir: StrPath + project_cfg: Incomplete + dynamic: Incomplete + setuptools_cfg: Incomplete + dynamic_cfg: Incomplete + ignore_option_errors: bool + def __init__( + self, + config: dict[Incomplete, Incomplete], + root_dir: StrPath | None = None, + ignore_option_errors: bool = False, + dist: Distribution | None = None, + ) -> None: ... + def expand(self): ... + +class _EnsurePackagesDiscovered(expand.EnsurePackagesDiscovered): + def __init__( + self, distribution: Distribution, project_cfg: dict[Incomplete, Incomplete], setuptools_cfg: dict[Incomplete, Incomplete] + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> None: ... diff --git a/stubs/setuptools/setuptools/config/setupcfg.pyi b/stubs/setuptools/setuptools/config/setupcfg.pyi new file mode 100644 index 000000000000..35eb6821565f --- /dev/null +++ b/stubs/setuptools/setuptools/config/setupcfg.pyi @@ -0,0 +1,83 @@ +from _typeshed import Incomplete, StrPath +from abc import abstractmethod +from collections.abc import Callable, Iterable +from typing import Any, ClassVar, Generic, TypeAlias, TypeVar + +from .._distutils.dist import DistributionMetadata +from ..dist import Distribution +from . import expand + +SingleCommandOptions: TypeAlias = dict[str, tuple[str, Any]] +AllCommandOptions: TypeAlias = dict[str, SingleCommandOptions] +Target = TypeVar("Target", Distribution, DistributionMetadata) # noqa: Y001 # Exists at runtime + +def read_configuration( + filepath: StrPath, find_others: bool = False, ignore_option_errors: bool = False +) -> dict[Incomplete, Incomplete]: ... +def apply_configuration(dist: Distribution, filepath: StrPath) -> Distribution: ... +def configuration_to_dict( + handlers: Iterable[ConfigHandler[Distribution] | ConfigHandler[DistributionMetadata]], +) -> dict[Incomplete, Incomplete]: ... +def parse_configuration( + distribution: Distribution, command_options: AllCommandOptions, ignore_option_errors: bool = False +) -> tuple[ConfigMetadataHandler, ConfigOptionsHandler]: ... + +class ConfigHandler(Generic[Target]): + section_prefix: str + aliases: ClassVar[dict[str, str]] + ignore_option_errors: Incomplete + target_obj: Target + sections: dict[str, SingleCommandOptions] + set_options: list[str] + ensure_discovered: expand.EnsurePackagesDiscovered + def __init__( + self, + target_obj: Target, + options: AllCommandOptions, + ignore_option_errors, + ensure_discovered: expand.EnsurePackagesDiscovered, + ) -> None: ... + @property + @abstractmethod + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + def __setitem__(self, option_name, value): ... + def parse_section(self, section_options) -> None: ... + def parse(self) -> None: ... + +class ConfigMetadataHandler(ConfigHandler[DistributionMetadata]): + section_prefix: str + aliases: ClassVar[dict[str, str]] + strict_mode: bool + package_dir: dict[Incomplete, Incomplete] | None + root_dir: StrPath | None + def __init__( + self, + target_obj: DistributionMetadata, + options: AllCommandOptions, + ignore_option_errors: bool, + ensure_discovered: expand.EnsurePackagesDiscovered, + package_dir: dict[Incomplete, Incomplete] | None = None, + root_dir: StrPath | None = ".", + ) -> None: ... + @property + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + +class ConfigOptionsHandler(ConfigHandler[Distribution]): + section_prefix: str + root_dir: str | None + package_dir: dict[str, str] + def __init__( + self, + target_obj: Distribution, + options: AllCommandOptions, + ignore_option_errors: bool, + ensure_discovered: expand.EnsurePackagesDiscovered, + ) -> None: ... + @property + def parsers(self) -> dict[str, Callable[..., Incomplete]]: ... + def parse_section_packages__find(self, section_options): ... + def parse_section_entry_points(self, section_options) -> None: ... + def parse_section_package_data(self, section_options) -> None: ... + def parse_section_exclude_package_data(self, section_options) -> None: ... + def parse_section_extras_require(self, section_options) -> None: ... + def parse_section_data_files(self, section_options) -> None: ... diff --git a/stubs/setuptools/setuptools/depends.pyi b/stubs/setuptools/setuptools/depends.pyi new file mode 100644 index 000000000000..54ddd352768c --- /dev/null +++ b/stubs/setuptools/setuptools/depends.pyi @@ -0,0 +1,20 @@ +from typing import IO, Any, Literal, TypeVar + +_T = TypeVar("_T") + +__all__ = ["Require", "find_module", "get_module_constant", "extract_constant"] + +def find_module( + module, paths=None +) -> tuple[IO[Any], str | None, tuple[str, Literal["", "r", "rb"], Literal[7, 6, 1, 2, 3, -1]]]: ... + +class Require: + def __init__(self, name, requested_version, module, homepage: str = "", attribute=None, format=None) -> None: ... + def full_name(self): ... + def version_ok(self, version): ... + def get_version(self, paths=None, default: _T | Literal["unknown"] = "unknown") -> _T | Literal["unknown"] | None | Any: ... + def is_present(self, paths=None): ... + def is_current(self, paths=None): ... + +def get_module_constant(module, symbol, default: _T | int = -1, paths=None) -> _T | int | None | Any: ... +def extract_constant(code, symbol, default: _T | int = -1) -> _T | int | None | Any: ... diff --git a/stubs/setuptools/setuptools/discovery.pyi b/stubs/setuptools/setuptools/discovery.pyi new file mode 100644 index 000000000000..9059a381f578 --- /dev/null +++ b/stubs/setuptools/setuptools/discovery.pyi @@ -0,0 +1,43 @@ +import itertools +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Mapping +from typing import ClassVar + +from . import Distribution + +chain_iter = itertools.chain.from_iterable + +class _Filter: + def __init__(self, *patterns: str) -> None: ... + def __call__(self, item: str) -> bool: ... + def __contains__(self, item: str) -> bool: ... + +class _Finder: + ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + @classmethod + def find(cls, where: StrPath = ".", exclude: Iterable[str] = (), include: Iterable[str] = ("*",)) -> list[str]: ... + +class PackageFinder(_Finder): + ALWAYS_EXCLUDE: ClassVar[tuple[str, ...]] + +class PEP420PackageFinder(PackageFinder): ... +class ModuleFinder(_Finder): ... + +class FlatLayoutPackageFinder(PEP420PackageFinder): + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + +class FlatLayoutModuleFinder(ModuleFinder): + DEFAULT_EXCLUDE: ClassVar[tuple[str, ...]] + +class ConfigDiscovery: + dist: Incomplete + def __init__(self, distribution: Distribution) -> None: ... + def __call__(self, force: bool = False, name: bool = True, ignore_ext_modules: bool = False) -> None: ... + def analyse_name(self) -> None: ... + +def remove_nested_packages(packages: list[str]) -> list[str]: ... +def remove_stubs(packages: list[str]) -> list[str]: ... +def find_parent_package(packages: list[str], package_dir: Mapping[str, str], root_dir: StrPath) -> str | None: ... +def find_package_path(name: str, package_dir: Mapping[str, str], root_dir: StrPath) -> str: ... +def construct_package_dir(packages: list[str], package_path: StrPath) -> dict[str, str]: ... diff --git a/stubs/setuptools/setuptools/dist.pyi b/stubs/setuptools/setuptools/dist.pyi new file mode 100644 index 000000000000..a17b46c69fe9 --- /dev/null +++ b/stubs/setuptools/setuptools/dist.pyi @@ -0,0 +1,199 @@ +from _typeshed import Incomplete, StrPath +from collections.abc import Iterable, Iterator, MutableMapping +from importlib import metadata +from typing import Literal, TypeVar, overload + +from . import Command, SetuptoolsDeprecationWarning +from ._distutils.cmd import Command as _Command +from ._distutils.dist import Distribution as _Distribution +from .command.alias import alias +from .command.bdist_egg import bdist_egg +from .command.bdist_rpm import bdist_rpm +from .command.bdist_wheel import bdist_wheel +from .command.build import build +from .command.build_clib import build_clib +from .command.build_ext import build_ext +from .command.build_py import build_py +from .command.develop import develop +from .command.dist_info import dist_info +from .command.easy_install import easy_install +from .command.editable_wheel import editable_wheel +from .command.egg_info import egg_info +from .command.install import install +from .command.install_egg_info import install_egg_info +from .command.install_lib import install_lib +from .command.install_scripts import install_scripts +from .command.rotate import rotate +from .command.saveopts import saveopts +from .command.sdist import sdist +from .command.setopt import setopt + +_CommandT = TypeVar("_CommandT", bound=_Command) + +__all__ = ["Distribution"] + +class Distribution(_Distribution): + include_package_data: bool | None + exclude_package_data: dict[str, list[str]] | None + src_root: str | None + dependency_links: list[str] + setup_requires: list[str] + def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ... + def parse_config_files(self, filenames: Iterable[StrPath] | None = None, ignore_option_errors: bool = False) -> None: ... + def fetch_build_eggs(self, requires: str | Iterable[str]) -> list[metadata.Distribution]: ... + def get_egg_cache_dir(self) -> str: ... + def fetch_build_egg(self, req): ... + + # NOTE: Commands that setuptools doesn't re-expose are considered deprecated (they must be imported from distutils directly) + # So we're not listing them here. This list comes directly from the setuptools/command folder. Minus the test command. + @overload # type: ignore[override] + def get_command_obj(self, command: Literal["alias"], create: Literal[1, True] = 1) -> alias: ... + @overload + def get_command_obj(self, command: Literal["bdist_egg"], create: Literal[1, True] = 1) -> bdist_egg: ... + @overload + def get_command_obj(self, command: Literal["bdist_rpm"], create: Literal[1, True] = 1) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["bdist_wheel"], create: Literal[1, True] = 1) -> bdist_wheel: ... + @overload + def get_command_obj(self, command: Literal["build"], create: Literal[1, True] = 1) -> build: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_clib"], create: Literal[1, True] = 1) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_ext"], create: Literal[1, True] = 1) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["build_py"], create: Literal[1, True] = 1) -> build_py: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["develop"], create: Literal[1, True] = 1) -> develop: ... + @overload + def get_command_obj(self, command: Literal["dist_info"], create: Literal[1, True] = 1) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["easy_install"], create: Literal[1, True] = 1) -> easy_install: ... + @overload + def get_command_obj(self, command: Literal["editable_wheel"], create: Literal[1, True] = 1) -> editable_wheel: ... + @overload + def get_command_obj(self, command: Literal["egg_info"], create: Literal[1, True] = 1) -> egg_info: ... + @overload + def get_command_obj(self, command: Literal["install"], create: Literal[1, True] = 1) -> install: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["install_egg_info"], create: Literal[1, True] = 1) -> install_egg_info: ... + @overload + def get_command_obj(self, command: Literal["install_lib"], create: Literal[1, True] = 1) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["install_scripts"], create: Literal[1, True] = 1) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["rotate"], create: Literal[1, True] = 1) -> rotate: ... + @overload + def get_command_obj(self, command: Literal["saveopts"], create: Literal[1, True] = 1) -> saveopts: ... + @overload + def get_command_obj(self, command: Literal["sdist"], create: Literal[1, True] = 1) -> sdist: ... # type: ignore[overload-overlap] + @overload + def get_command_obj(self, command: Literal["setopt"], create: Literal[1, True] = 1) -> setopt: ... + @overload + def get_command_obj(self, command: str, create: Literal[1, True] = 1) -> Command: ... + # Not replicating the overloads for "Command | None", user may use "isinstance" + @overload + def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... + + @overload + def get_command_class(self, command: Literal["alias"]) -> type[alias]: ... + @overload + def get_command_class(self, command: Literal["bdist_egg"]) -> type[bdist_egg]: ... + @overload + def get_command_class(self, command: Literal["bdist_rpm"]) -> type[bdist_rpm]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["bdist_wheel"]) -> type[bdist_wheel]: ... + @overload + def get_command_class(self, command: Literal["build"]) -> type[build]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_clib"]) -> type[build_clib]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_ext"]) -> type[build_ext]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["build_py"]) -> type[build_py]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["develop"]) -> type[develop]: ... + @overload + def get_command_class(self, command: Literal["dist_info"]) -> type[dist_info]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["easy_install"]) -> type[easy_install]: ... + @overload + def get_command_class(self, command: Literal["editable_wheel"]) -> type[editable_wheel]: ... + @overload + def get_command_class(self, command: Literal["egg_info"]) -> type[egg_info]: ... + @overload + def get_command_class(self, command: Literal["install"]) -> type[install]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["install_egg_info"]) -> type[install_egg_info]: ... + @overload + def get_command_class(self, command: Literal["install_lib"]) -> type[install_lib]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["install_scripts"]) -> type[install_scripts]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["rotate"]) -> type[rotate]: ... + @overload + def get_command_class(self, command: Literal["saveopts"]) -> type[saveopts]: ... + @overload + def get_command_class(self, command: Literal["sdist"]) -> type[sdist]: ... # type: ignore[overload-overlap] + @overload + def get_command_class(self, command: Literal["setopt"]) -> type[setopt]: ... + @overload + def get_command_class(self, command: str) -> type[Command]: ... + + @overload # type: ignore[override] + def reinitialize_command(self, command: Literal["alias"], reinit_subcommands: bool = False) -> alias: ... + @overload + def reinitialize_command(self, command: Literal["bdist_egg"], reinit_subcommands: bool = False) -> bdist_egg: ... + @overload + def reinitialize_command(self, command: Literal["bdist_rpm"], reinit_subcommands: bool = False) -> bdist_rpm: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["bdist_wheel"], reinit_subcommands: bool = False) -> bdist_wheel: ... + @overload + def reinitialize_command(self, command: Literal["build"], reinit_subcommands: bool = False) -> build: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_clib"], reinit_subcommands: bool = False) -> build_clib: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_ext"], reinit_subcommands: bool = False) -> build_ext: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["build_py"], reinit_subcommands: bool = False) -> build_py: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["develop"], reinit_subcommands: bool = False) -> develop: ... + @overload + def reinitialize_command(self, command: Literal["dist_info"], reinit_subcommands: bool = False) -> dist_info: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["easy_install"], reinit_subcommands: bool = False) -> easy_install: ... + @overload + def reinitialize_command(self, command: Literal["editable_wheel"], reinit_subcommands: bool = False) -> editable_wheel: ... + @overload + def reinitialize_command(self, command: Literal["egg_info"], reinit_subcommands: bool = False) -> egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install"], reinit_subcommands: bool = False) -> install: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command( + self, command: Literal["install_egg_info"], reinit_subcommands: bool = False + ) -> install_egg_info: ... + @overload + def reinitialize_command(self, command: Literal["install_lib"], reinit_subcommands: bool = False) -> install_lib: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["install_scripts"], reinit_subcommands: bool = False) -> install_scripts: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["rotate"], reinit_subcommands: bool = False) -> rotate: ... + @overload + def reinitialize_command(self, command: Literal["saveopts"], reinit_subcommands: bool = False) -> saveopts: ... + @overload + def reinitialize_command(self, command: Literal["sdist"], reinit_subcommands: bool = False) -> sdist: ... # type: ignore[overload-overlap] + @overload + def reinitialize_command(self, command: Literal["setopt"], reinit_subcommands: bool = False) -> setopt: ... + @overload + def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... + @overload + def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + + def include(self, **attrs) -> None: ... + def exclude_package(self, package: str) -> None: ... + def has_contents_for(self, package: str) -> bool: ... + def exclude(self, **attrs) -> None: ... + def get_cmdline_options(self) -> dict[str, dict[str, str | None]]: ... + def iter_distribution_names(self) -> Iterator[str]: ... + def handle_display_options(self, option_order): ... + +class DistDeprecationWarning(SetuptoolsDeprecationWarning): ... diff --git a/stubs/setuptools/setuptools/errors.pyi b/stubs/setuptools/setuptools/errors.pyi new file mode 100644 index 000000000000..9723a11d514f --- /dev/null +++ b/stubs/setuptools/setuptools/errors.pyi @@ -0,0 +1,24 @@ +from ._distutils import errors as _distutils_errors + +ByteCompileError = _distutils_errors.DistutilsByteCompileError +CCompilerError = _distutils_errors.CCompilerError +ClassError = _distutils_errors.DistutilsClassError +CompileError = _distutils_errors.CompileError +ExecError = _distutils_errors.DistutilsExecError +FileError = _distutils_errors.DistutilsFileError +InternalError = _distutils_errors.DistutilsInternalError +LibError = _distutils_errors.LibError +LinkError = _distutils_errors.LinkError +ModuleError = _distutils_errors.DistutilsModuleError +OptionError = _distutils_errors.DistutilsOptionError +PlatformError = _distutils_errors.DistutilsPlatformError +PreprocessError = _distutils_errors.PreprocessError +SetupError = _distutils_errors.DistutilsSetupError +TemplateError = _distutils_errors.DistutilsTemplateError +UnknownFileError = _distutils_errors.UnknownFileError +BaseError = _distutils_errors.DistutilsError + +class InvalidConfigError(OptionError): ... +class RemovedConfigError(OptionError): ... +class RemovedCommandError(BaseError, RuntimeError): ... +class PackageDiscoveryError(BaseError, RuntimeError): ... diff --git a/stubs/setuptools/setuptools/extension.pyi b/stubs/setuptools/setuptools/extension.pyi new file mode 100644 index 000000000000..0f9c99214ad2 --- /dev/null +++ b/stubs/setuptools/setuptools/extension.pyi @@ -0,0 +1,32 @@ +from _typeshed import StrPath +from collections.abc import Iterable + +from ._distutils.extension import Extension as _Extension + +def have_pyrex() -> bool: ... + +class Extension(_Extension): + py_limited_api: bool + def __init__( + self, + name: str, + sources: Iterable[StrPath], + include_dirs: list[str] | None = None, + define_macros: list[tuple[str, str | None]] | None = None, + undef_macros: list[str] | None = None, + library_dirs: list[str] | None = None, + libraries: list[str] | None = None, + runtime_library_dirs: list[str] | None = None, + extra_objects: list[str] | None = None, + extra_compile_args: list[str] | None = None, + extra_link_args: list[str] | None = None, + export_symbols: list[str] | None = None, + swig_opts: list[str] | None = None, + depends: list[str] | None = None, + language: str | None = None, + optional: bool | None = None, + *, + py_limited_api: bool = False, + ) -> None: ... + +class Library(Extension): ... diff --git a/stubs/setuptools/setuptools/glob.pyi b/stubs/setuptools/setuptools/glob.pyi new file mode 100644 index 000000000000..e5d6431bbe95 --- /dev/null +++ b/stubs/setuptools/setuptools/glob.pyi @@ -0,0 +1,5 @@ +__all__ = ["glob", "iglob", "escape"] + +def glob(pathname, recursive: bool = False): ... +def iglob(pathname, recursive: bool = False): ... +def escape(pathname): ... diff --git a/stubs/setuptools/setuptools/installer.pyi b/stubs/setuptools/setuptools/installer.pyi new file mode 100644 index 000000000000..8902dd66f711 --- /dev/null +++ b/stubs/setuptools/setuptools/installer.pyi @@ -0,0 +1,14 @@ +from importlib import metadata +from typing import Any +from typing_extensions import deprecated + +@deprecated(""" + `setuptools.installer` and `fetch_build_eggs` are deprecated. + Requirements should be satisfied by a PEP 517 installer. + If you are using pip, you can try `pip install --use-pep517`. + """) +def fetch_build_egg(dist, req) -> metadata.Distribution | metadata.PathDistribution: ... + +# Returns packaging.requirements.Requirement +# But since this module is deprecated, we avoid declaring a dependency on packaging +def strip_marker(req) -> Any: ... diff --git a/stubs/setuptools/setuptools/launch.pyi b/stubs/setuptools/setuptools/launch.pyi new file mode 100644 index 000000000000..b88194ac6bff --- /dev/null +++ b/stubs/setuptools/setuptools/launch.pyi @@ -0,0 +1 @@ +def run() -> None: ... diff --git a/stubs/setuptools/setuptools/logging.pyi b/stubs/setuptools/setuptools/logging.pyi new file mode 100644 index 000000000000..4f87159e22a8 --- /dev/null +++ b/stubs/setuptools/setuptools/logging.pyi @@ -0,0 +1,2 @@ +def configure() -> None: ... +def set_threshold(level: int) -> int: ... diff --git a/stubs/setuptools/setuptools/modified.pyi b/stubs/setuptools/setuptools/modified.pyi new file mode 100644 index 000000000000..0437d4efc3ed --- /dev/null +++ b/stubs/setuptools/setuptools/modified.pyi @@ -0,0 +1,3 @@ +from ._distutils._modified import newer, newer_group, newer_pairwise, newer_pairwise_group + +__all__ = ["newer", "newer_pairwise", "newer_group", "newer_pairwise_group"] diff --git a/stubs/setuptools/setuptools/monkey.pyi b/stubs/setuptools/setuptools/monkey.pyi new file mode 100644 index 000000000000..c69326ab1fd5 --- /dev/null +++ b/stubs/setuptools/setuptools/monkey.pyi @@ -0,0 +1,16 @@ +from types import FunctionType +from typing import TypeVar, overload + +_T = TypeVar("_T") +_UnpatchT = TypeVar("_UnpatchT", type, FunctionType) +__all__: list[str] = [] + +@overload +def get_unpatched(item: _UnpatchT) -> _UnpatchT: ... # type: ignore[overload-overlap] +@overload +def get_unpatched(item: object) -> None: ... + +def get_unpatched_class(cls: type[_T]) -> type[_T]: ... +def patch_all() -> None: ... +def patch_func(replacement, target_mod, func_name) -> None: ... +def get_unpatched_function(candidate): ... diff --git a/stubs/setuptools/setuptools/msvc.pyi b/stubs/setuptools/setuptools/msvc.pyi new file mode 100644 index 000000000000..433b0b161fd2 --- /dev/null +++ b/stubs/setuptools/setuptools/msvc.pyi @@ -0,0 +1,168 @@ +import sys +from typing import Final, TypedDict, overload +from typing_extensions import LiteralString, NotRequired + +if sys.platform == "win32": + import winreg as winreg + from os import environ as environ +else: + class winreg: + HKEY_USERS: Final[None] + HKEY_CURRENT_USER: Final[None] + HKEY_LOCAL_MACHINE: Final[None] + HKEY_CLASSES_ROOT: Final[None] + + environ: dict[str, str] + +class PlatformInfo: + current_cpu: Final[str] + + arch: str + + def __init__(self, arch: str) -> None: ... + @property + def target_cpu(self) -> str: ... + def target_is_x86(self) -> bool: ... + def current_is_x86(self) -> bool: ... + def current_dir(self, hidex86: bool = False, x64: bool = False) -> str: ... + def target_dir(self, hidex86: bool = False, x64: bool = False) -> str: ... + def cross_dir(self, forcex86: bool = False) -> str: ... + +class RegistryInfo: + if sys.platform == "win32": + HKEYS: Final[tuple[int, int, int, int]] + else: + HKEYS: Final[tuple[None, None, None, None]] + + pi: PlatformInfo + + def __init__(self, platform_info: PlatformInfo) -> None: ... + @property + def visualstudio(self) -> LiteralString: ... + @property + def sxs(self) -> LiteralString: ... + @property + def vc(self) -> LiteralString: ... + @property + def vs(self) -> LiteralString: ... + @property + def vc_for_python(self) -> LiteralString: ... + @property + def microsoft_sdk(self) -> LiteralString: ... + @property + def windows_sdk(self) -> LiteralString: ... + @property + def netfx_sdk(self) -> LiteralString: ... + @property + def windows_kits_roots(self) -> LiteralString: ... + + @overload + def microsoft(self, key: LiteralString, x86: bool = False) -> LiteralString: ... + @overload + def microsoft(self, key: str, x86: bool = False) -> str: ... # type: ignore[misc] + + def lookup(self, key: str, name: str) -> str | None: ... + +class SystemInfo: + WinDir: Final[str] + ProgramFiles: Final[str] + ProgramFilesx86: Final[str] + + ri: RegistryInfo + pi: PlatformInfo + known_vs_paths: dict[float, str] + vs_ver: float + vc_ver: float + + def __init__(self, registry_info: RegistryInfo, vc_ver: float | None = None) -> None: ... + def find_reg_vs_vers(self) -> list[float]: ... + def find_programdata_vs_vers(self) -> dict[float, str]: ... + @property + def VSInstallDir(self) -> str: ... + @property + def VCInstallDir(self) -> str: ... + @property + def WindowsSdkVersion(self) -> tuple[LiteralString, ...]: ... + @property + def WindowsSdkLastVersion(self) -> str: ... + @property + def WindowsSdkDir(self) -> str | None: ... + @property + def WindowsSDKExecutablePath(self) -> str | None: ... + @property + def FSharpInstallDir(self) -> str: ... + @property + def UniversalCRTSdkDir(self) -> str | None: ... + @property + def UniversalCRTSdkLastVersion(self) -> str: ... + @property + def NetFxSdkVersion(self) -> tuple[LiteralString, ...]: ... + @property + def NetFxSdkDir(self) -> str: ... + @property + def FrameworkDir32(self) -> str: ... + @property + def FrameworkDir64(self) -> str: ... + @property + def FrameworkVersion32(self) -> tuple[str, ...]: ... + @property + def FrameworkVersion64(self) -> tuple[str, ...]: ... + +class _EnvironmentDict(TypedDict): + include: str + lib: str + libpath: str + path: str + py_vcruntime_redist: NotRequired[str | None] + +class EnvironmentInfo: + pi: PlatformInfo + ri: RegistryInfo + si: SystemInfo + + def __init__(self, arch: str, vc_ver: float | None = None, vc_min_ver: float = 0) -> None: ... + @property + def vs_ver(self) -> float: ... + @property + def vc_ver(self) -> float: ... + @property + def VSTools(self) -> list[str]: ... + @property + def VCIncludes(self) -> list[str]: ... + @property + def VCLibraries(self) -> list[str]: ... + @property + def VCStoreRefs(self) -> list[str]: ... + @property + def VCTools(self) -> list[str]: ... + @property + def OSLibraries(self) -> list[str]: ... + @property + def OSIncludes(self) -> list[str]: ... + @property + def OSLibpath(self) -> list[str]: ... + @property + def SdkTools(self) -> list[str]: ... + @property + def SdkSetup(self) -> list[str]: ... + @property + def FxTools(self) -> list[str]: ... + @property + def NetFxSDKLibraries(self) -> list[str]: ... + @property + def NetFxSDKIncludes(self) -> list[str]: ... + @property + def VsTDb(self) -> list[str]: ... + @property + def MSBuild(self) -> list[str]: ... + @property + def HTMLHelpWorkshop(self) -> list[str]: ... + @property + def UCRTLibraries(self) -> list[str]: ... + @property + def UCRTIncludes(self) -> list[str]: ... + @property + def FSharp(self) -> list[str]: ... + @property + def VCRuntimeRedist(self) -> str | None: ... + def return_env(self, exists: bool = True) -> _EnvironmentDict: ... diff --git a/stubs/setuptools/setuptools/namespaces.pyi b/stubs/setuptools/setuptools/namespaces.pyi new file mode 100644 index 000000000000..9170ecfdd5e6 --- /dev/null +++ b/stubs/setuptools/setuptools/namespaces.pyi @@ -0,0 +1,10 @@ +import itertools + +flatten = itertools.chain.from_iterable + +class Installer: + nspkg_ext: str + def install_namespaces(self) -> None: ... + def uninstall_namespaces(self) -> None: ... + +class DevelopInstaller(Installer): ... diff --git a/stubs/setuptools/setuptools/unicode_utils.pyi b/stubs/setuptools/setuptools/unicode_utils.pyi new file mode 100644 index 000000000000..4ab4afd02181 --- /dev/null +++ b/stubs/setuptools/setuptools/unicode_utils.pyi @@ -0,0 +1,4 @@ +def decompose(path): ... +def normalize(text): ... +def filesys_decode(path): ... +def try_encode(string, enc): ... diff --git a/stubs/setuptools/setuptools/version.pyi b/stubs/setuptools/setuptools/version.pyi new file mode 100644 index 000000000000..bda5b5a7f4cc --- /dev/null +++ b/stubs/setuptools/setuptools/version.pyi @@ -0,0 +1 @@ +__version__: str diff --git a/stubs/setuptools/setuptools/warnings.pyi b/stubs/setuptools/setuptools/warnings.pyi new file mode 100644 index 000000000000..81d3bcfb3922 --- /dev/null +++ b/stubs/setuptools/setuptools/warnings.pyi @@ -0,0 +1,19 @@ +from typing import TypeAlias + +_DueDate: TypeAlias = tuple[int, int, int] # time tuple + +class SetuptoolsWarning(UserWarning): + @classmethod + def emit( + cls, + summary: str | None = None, + details: str | None = None, + due_date: _DueDate | None = None, + see_docs: str | None = None, + see_url: str | None = None, + stacklevel: int = 2, + **kwargs, + ) -> None: ... + +class InformationOnly(SetuptoolsWarning): ... +class SetuptoolsDeprecationWarning(SetuptoolsWarning): ... diff --git a/stubs/setuptools/setuptools/wheel.pyi b/stubs/setuptools/setuptools/wheel.pyi new file mode 100644 index 000000000000..ae56166a8556 --- /dev/null +++ b/stubs/setuptools/setuptools/wheel.pyi @@ -0,0 +1,17 @@ +from _typeshed import Incomplete +from collections.abc import Generator + +WHEEL_NAME: Incomplete +NAMESPACE_PACKAGE_INIT: str + +def unpack(src_dir, dst_dir) -> None: ... +def disable_info_traces() -> Generator[None]: ... + +class Wheel: + filename: Incomplete + def __init__(self, filename) -> None: ... + def tags(self): ... + def is_compatible(self): ... + def egg_name(self): ... + def get_dist_info(self, zf): ... + def install_as_egg(self, destination_eggdir) -> None: ... diff --git a/stubs/setuptools/setuptools/windows_support.pyi b/stubs/setuptools/setuptools/windows_support.pyi new file mode 100644 index 000000000000..7daf9e3a66cc --- /dev/null +++ b/stubs/setuptools/setuptools/windows_support.pyi @@ -0,0 +1,2 @@ +def windows_only(func): ... +def hide_file(path: str) -> None: ... diff --git a/stubs/shapely/@tests/stubtest_allowlist.txt b/stubs/shapely/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..fd759a27a630 --- /dev/null +++ b/stubs/shapely/@tests/stubtest_allowlist.txt @@ -0,0 +1,4 @@ +shapely\.conftest +shapely\.tests.* + +shapely\._typing # stubs only module diff --git a/stubs/shapely/METADATA.toml b/stubs/shapely/METADATA.toml new file mode 100644 index 000000000000..326a70f2733c --- /dev/null +++ b/stubs/shapely/METADATA.toml @@ -0,0 +1,4 @@ +version = "2.1.*" +upstream-repository = "https://github.com/shapely/shapely" +# Requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20"] diff --git a/stubs/shapely/shapely/__init__.pyi b/stubs/shapely/shapely/__init__.pyi new file mode 100644 index 000000000000..22e9b97f7ee6 --- /dev/null +++ b/stubs/shapely/shapely/__init__.pyi @@ -0,0 +1,35 @@ +from typing import Final + +from . import affinity as affinity +from ._coverage import * +from ._geometry import * +from .constructive import * +from .coordinates import * +from .creation import * +from .errors import setup_signal_checks as setup_signal_checks +from .geometry import ( + GeometryCollection as GeometryCollection, + LinearRing as LinearRing, + LineString as LineString, + MultiLineString as MultiLineString, + MultiPoint as MultiPoint, + MultiPolygon as MultiPolygon, + Point as Point, + Polygon as Polygon, +) +from .io import * +from .lib import ( + Geometry as Geometry, + GEOSException as GEOSException, + geos_capi_version as geos_capi_version, + geos_capi_version_string as geos_capi_version_string, + geos_version as geos_version, + geos_version_string as geos_version_string, +) +from .linear import * +from .measurement import * +from .predicates import * +from .set_operations import * +from .strtree import * + +__version__: Final[str] diff --git a/stubs/shapely/shapely/_coverage.pyi b/stubs/shapely/shapely/_coverage.pyi new file mode 100644 index 000000000000..fefc40e02d48 --- /dev/null +++ b/stubs/shapely/shapely/_coverage.pyi @@ -0,0 +1,16 @@ +from typing import overload + +import numpy as np + +from ._typing import ArrayLike, GeoArray, GeoArrayLikeSeq, OptGeoArrayLike +from .geometry import Polygon + +__all__ = ["coverage_invalid_edges", "coverage_is_valid", "coverage_simplify"] + +def coverage_is_valid(geometry: OptGeoArrayLike, gap_width: float = 0.0, **kwargs) -> np.bool_: ... +def coverage_invalid_edges(geometry: OptGeoArrayLike, gap_width: float = 0.0, **kwargs) -> GeoArray: ... + +@overload +def coverage_simplify(geometry: Polygon, tolerance: ArrayLike[float], *, simplify_boundary: bool = True) -> Polygon: ... +@overload +def coverage_simplify(geometry: GeoArrayLikeSeq, tolerance: ArrayLike[float], *, simplify_boundary: bool = True) -> GeoArray: ... diff --git a/stubs/shapely/shapely/_enum.pyi b/stubs/shapely/shapely/_enum.pyi new file mode 100644 index 000000000000..c36e15fed401 --- /dev/null +++ b/stubs/shapely/shapely/_enum.pyi @@ -0,0 +1,5 @@ +from enum import IntEnum + +class ParamEnum(IntEnum): # type: ignore[misc] # Enum with no members + @classmethod + def get_value(cls, item: str) -> int: ... diff --git a/stubs/shapely/shapely/_geometry.pyi b/stubs/shapely/shapely/_geometry.pyi new file mode 100644 index 000000000000..7e9b64f1a71d --- /dev/null +++ b/stubs/shapely/shapely/_geometry.pyi @@ -0,0 +1,209 @@ +from enum import IntEnum +from typing import Any, Literal, SupportsIndex, TypeAlias, overload + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT +from .geometry import LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry +from .lib import Geometry + +__all__ = [ + "GeometryType", + "force_2d", + "force_3d", + "get_coordinate_dimension", + "get_dimensions", + "get_exterior_ring", + "get_geometry", + "get_interior_ring", + "get_m", + "get_num_coordinates", + "get_num_geometries", + "get_num_interior_rings", + "get_num_points", + "get_parts", + "get_point", + "get_precision", + "get_rings", + "get_srid", + "get_type_id", + "get_x", + "get_y", + "get_z", + "set_precision", + "set_srid", +] + +_PrecisionMode: TypeAlias = Literal["valid_output", "pointwise", "keep_collapsed", 0, 1, 2] + +class GeometryType(IntEnum): + MISSING = -1 + POINT = 0 + LINESTRING = 1 + LINEARRING = 2 + POLYGON = 3 + MULTIPOINT = 4 + MULTILINESTRING = 5 + MULTIPOLYGON = 6 + GEOMETRYCOLLECTION = 7 + +@overload +def get_type_id(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_type_id(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_dimensions(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_dimensions(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_coordinate_dimension(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_coordinate_dimension(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_num_coordinates(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_coordinates(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_srid(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_srid(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def set_srid(geometry: OptGeoT, srid: SupportsIndex, **kwargs) -> OptGeoT: ... +@overload +def set_srid(geometry: OptGeoArrayLikeSeq, srid: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def set_srid(geometry: OptGeoArrayLike, srid: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_x(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_x(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_y(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_y(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_z(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_z(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_m(point: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_m(point: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def get_point(geometry: LineString, index: SupportsIndex, **kwargs) -> Point | Any: ... +@overload +def get_point(geometry: Point | Polygon | BaseMultipartGeometry | None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_point(geometry: Geometry, index: SupportsIndex, **kwargs) -> Point | None: ... +@overload +def get_point(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_point(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_num_points(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_points(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_exterior_ring(geometry: Polygon, **kwargs) -> LinearRing: ... +@overload +def get_exterior_ring(geometry: Point | LineString | BaseMultipartGeometry | None, **kwargs) -> None: ... +@overload +def get_exterior_ring(geometry: Geometry, **kwargs) -> LinearRing | None: ... +@overload +def get_exterior_ring(geometry: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... + +@overload +def get_interior_ring(geometry: Polygon, index: SupportsIndex, **kwargs) -> LinearRing | Any: ... +@overload +def get_interior_ring(geometry: Point | LineString | BaseMultipartGeometry | None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_interior_ring(geometry: Geometry, index: SupportsIndex, **kwargs) -> LinearRing | None: ... +@overload +def get_interior_ring(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_interior_ring(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_num_interior_rings(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_interior_rings(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_geometry(geometry: MultiPoint, index: SupportsIndex, **kwargs) -> Point | Any: ... +@overload +def get_geometry(geometry: MultiLineString, index: SupportsIndex, **kwargs) -> LineString | Any: ... +@overload +def get_geometry(geometry: MultiPolygon, index: SupportsIndex, **kwargs) -> Polygon | Any: ... +@overload +def get_geometry(geometry: BaseMultipartGeometry, index: SupportsIndex, **kwargs) -> BaseGeometry | Any: ... +@overload +def get_geometry(geometry: None, index: SupportsIndex, **kwargs) -> None: ... +@overload +def get_geometry(geometry: Geometry | None, index: SupportsIndex, **kwargs) -> BaseGeometry | None: ... +@overload +def get_geometry(geometry: OptGeoArrayLikeSeq, index: ArrayLike[SupportsIndex], **kwargs) -> GeoArray: ... +@overload +def get_geometry(geometry: OptGeoArrayLike, index: ArrayLikeSeq[SupportsIndex], **kwargs) -> GeoArray: ... + +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: Literal[False] = False) -> GeoArray: ... +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: Literal[True]) -> tuple[GeoArray, NDArray[np.int64]]: ... +@overload +def get_parts(geometry: OptGeoArrayLike, return_index: bool) -> GeoArray | tuple[GeoArray, NDArray[np.int64]]: ... + +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: Literal[False] = False) -> GeoArray: ... +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: Literal[True]) -> tuple[GeoArray, NDArray[np.int64]]: ... +@overload +def get_rings(geometry: OptGeoArrayLike, return_index: bool) -> GeoArray | tuple[GeoArray, NDArray[np.int64]]: ... + +@overload +def get_num_geometries(geometry: Geometry | None, **kwargs) -> np.int32: ... +@overload +def get_num_geometries(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.int32]: ... + +@overload +def get_precision(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def get_precision(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +class SetPrecisionMode(ParamEnum): + valid_output = 0 + pointwise = 1 + keep_collapsed = 2 + +@overload +def set_precision(geometry: OptGeoT, grid_size: float, mode: _PrecisionMode = "valid_output", **kwargs) -> OptGeoT: ... +@overload +def set_precision( + geometry: OptGeoArrayLikeSeq, grid_size: float, mode: _PrecisionMode = "valid_output", **kwargs +) -> GeoArray: ... + +@overload +def force_2d(geometry: OptGeoT, **kwargs) -> OptGeoT: ... +@overload +def force_2d(geometry: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... + +@overload +def force_3d(geometry: OptGeoT, z: float = 0.0, **kwargs) -> OptGeoT: ... +@overload +def force_3d(geometry: OptGeoArrayLikeSeq, z: ArrayLike[float] = 0.0, **kwargs) -> GeoArray: ... +@overload +def force_3d(geometry: OptGeoArrayLike, z: ArrayLikeSeq[float], **kwargs) -> GeoArray: ... diff --git a/stubs/shapely/shapely/_ragged_array.pyi b/stubs/shapely/shapely/_ragged_array.pyi new file mode 100644 index 000000000000..a0822d55e5c6 --- /dev/null +++ b/stubs/shapely/shapely/_ragged_array.pyi @@ -0,0 +1,14 @@ +import numpy as np +from numpy.typing import NDArray + +from ._geometry import GeometryType +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLikeSeq + +def to_ragged_array( + geometries: OptGeoArrayLikeSeq, include_z: bool | None = None, include_m: bool | None = None +) -> tuple[GeometryType, NDArray[np.float64], tuple[NDArray[np.int32], ...]]: ... +def from_ragged_array( + geometry_type: GeometryType, coords: ArrayLike[float], offsets: ArrayLikeSeq[int] | None = None +) -> GeoArray: ... + +__all__ = ["to_ragged_array", "from_ragged_array"] diff --git a/stubs/shapely/shapely/_typing.pyi b/stubs/shapely/shapely/_typing.pyi new file mode 100644 index 000000000000..ed62e8b881eb --- /dev/null +++ b/stubs/shapely/shapely/_typing.pyi @@ -0,0 +1,75 @@ +import sys +from _typeshed import SupportsWrite as SupportsWrite +from collections.abc import Sequence +from typing import Any, Literal, Protocol, TypeAlias, TypedDict, TypeVar, type_check_only + +import numpy as np +import numpy.typing as npt + +from .lib import Geometry + +if sys.version_info >= (3, 12): + from collections.abc import Buffer + +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_DType = TypeVar("_DType", bound=np.dtype[Any]) +_DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype[Any]) + +GeoT = TypeVar("GeoT", bound=Geometry) # noqa: Y001 +OptGeoT = TypeVar("OptGeoT", bound=Geometry | None) # noqa: Y001 + +@type_check_only +class SupportsArray(Protocol[_DType_co]): + def __array__(self) -> np.ndarray[Any, _DType_co]: ... + +# TODO: revisit when mypy is happy with generic recursive type alias +# NestedSequence: TypeAlias = Sequence[_T] | Sequence[NestedSequence[_T]] +NestedSequence: TypeAlias = Sequence[_T] | Sequence[Sequence[_T]] | Sequence[Sequence[Sequence[_T]]] +DualArrayLike: TypeAlias = SupportsArray[_DType] | NestedSequence[SupportsArray[_DType]] | NestedSequence[_T] + +# array-like sequences: objects accepted by np.array that produce at least 1-D arrays +if sys.version_info >= (3, 12): + ArrayLikeSeq: TypeAlias = Buffer | DualArrayLike[np.dtype[Any], _T] +else: + ArrayLikeSeq: TypeAlias = DualArrayLike[np.dtype[Any], _T] +GeoArrayLikeSeq: TypeAlias = ArrayLikeSeq[Geometry] +OptGeoArrayLikeSeq: TypeAlias = ArrayLikeSeq[Geometry | None] + +# array-like: objects accepted by np.array that may also produce 0-D array +ArrayLike: TypeAlias = _T | ArrayLikeSeq[_T] +GeoArrayLike: TypeAlias = ArrayLike[Geometry] +OptGeoArrayLike: TypeAlias = ArrayLike[Geometry | None] + +# There is no way to pronounce "array of BaseGeometry" currently because of the restriction on +# NDArray type variable to np.dtype and because np.object_ is not generic. +# Note the use of `BaseGeometry` instead of `Geometry` as the alias is used in return types. +GeoArray: TypeAlias = npt.NDArray[np.object_] + +@type_check_only +class SupportsGeoInterface(Protocol): + @property + def __geo_interface__(self) -> dict[str, Any]: ... + +# Unlike _typeshed.SupportsRead, this protocol does not require a length parameter +@type_check_only +class SupportsRead(Protocol[_T_co]): + def read(self) -> _T_co: ... + +CastingKind: TypeAlias = Literal["no", "equiv", "safe", "same_kind", "unsafe"] +OrderKind: TypeAlias = Literal["K", "A", "C", "F"] + +@type_check_only +class _UFuncKwargsBase(TypedDict, total=False): + where: npt.ArrayLike + casting: CastingKind + order: OrderKind + dtype: np.dtype[Any] | type[Any] + subok: bool + +@type_check_only +class UFuncKwargs(_UFuncKwargsBase, total=False): + out: npt.NDArray[Any] | tuple[npt.NDArray[Any], ...] + +@type_check_only +class UFuncKwargsNoOut(_UFuncKwargsBase, total=False): ... diff --git a/stubs/shapely/shapely/_version.pyi b/stubs/shapely/shapely/_version.pyi new file mode 100644 index 000000000000..249ab567c82e --- /dev/null +++ b/stubs/shapely/shapely/_version.pyi @@ -0,0 +1,6 @@ +from typing import TypedDict + +version_json: str +_Versions = TypedDict("_Versions", {"date": str, "dirty": bool, "error": None, "full-revisionid": str, "version": str}) + +def get_versions() -> _Versions: ... diff --git a/stubs/shapely/shapely/affinity.pyi b/stubs/shapely/shapely/affinity.pyi new file mode 100644 index 000000000000..d5e230db085f --- /dev/null +++ b/stubs/shapely/shapely/affinity.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection +from typing import Literal, TypeAlias, overload + +from ._typing import GeoT +from .geometry import Point +from .lib import Geometry + +__all__ = ["affine_transform", "rotate", "scale", "skew", "translate"] + +_Origin: TypeAlias = Literal["center", "centroid"] | Point | tuple[float, float] | tuple[float, float, float] + +def affine_transform(geom: GeoT, matrix: Collection[float]) -> GeoT: ... + +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: Literal[2]) -> tuple[float, float]: ... +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: Literal[3]) -> tuple[float, float, float]: ... +@overload +def interpret_origin(geom: Geometry, origin: _Origin, ndim: int) -> tuple[float, float] | tuple[float, float, float]: ... + +def rotate(geom: GeoT, angle: float, origin: _Origin = "center", use_radians: bool = False) -> GeoT: ... +def scale(geom: GeoT, xfact: float = 1.0, yfact: float = 1.0, zfact: float = 1.0, origin: _Origin = "center") -> GeoT: ... +def skew(geom: GeoT, xs: float = 0.0, ys: float = 0.0, origin: _Origin = "center", use_radians: bool = False) -> GeoT: ... +def translate(geom: GeoT, xoff: float = 0.0, yoff: float = 0.0, zoff: float = 0.0) -> GeoT: ... diff --git a/stubs/shapely/shapely/algorithms/__init__.pyi b/stubs/shapely/shapely/algorithms/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/stubs/shapely/shapely/algorithms/cga.pyi b/stubs/shapely/shapely/algorithms/cga.pyi new file mode 100644 index 000000000000..de6ecd5ed1cc --- /dev/null +++ b/stubs/shapely/shapely/algorithms/cga.pyi @@ -0,0 +1,5 @@ +import numpy as np + +from ..geometry import LinearRing + +def signed_area(ring: LinearRing) -> np.float64: ... diff --git a/stubs/shapely/shapely/algorithms/polylabel.pyi b/stubs/shapely/shapely/algorithms/polylabel.pyi new file mode 100644 index 000000000000..5d9777c30eab --- /dev/null +++ b/stubs/shapely/shapely/algorithms/polylabel.pyi @@ -0,0 +1,3 @@ +from ..geometry import Point, Polygon + +def polylabel(polygon: Polygon, tolerance: float = 1.0) -> Point: ... diff --git a/stubs/shapely/shapely/constructive.pyi b/stubs/shapely/shapely/constructive.pyi new file mode 100644 index 000000000000..e3d21dedb46d --- /dev/null +++ b/stubs/shapely/shapely/constructive.pyi @@ -0,0 +1,634 @@ +from collections.abc import Sequence +from typing import Any, Literal, SupportsIndex, overload +from typing_extensions import Unpack + +from ._enum import ParamEnum +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT, UFuncKwargs +from .geometry import GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry +from .lib import Geometry + +__all__ = [ + "BufferCapStyle", + "BufferJoinStyle", + "boundary", + "buffer", + "build_area", + "centroid", + "clip_by_rect", + "concave_hull", + "constrained_delaunay_triangles", + "convex_hull", + "delaunay_triangles", + "envelope", + "extract_unique_points", + "make_valid", + "maximum_inscribed_circle", + "minimum_bounding_circle", + "minimum_clearance_line", + "minimum_rotated_rectangle", + "node", + "normalize", + "offset_curve", + "orient_polygons", + "oriented_envelope", + "point_on_surface", + "polygonize", + "polygonize_full", + "remove_repeated_points", + "reverse", + "segmentize", + "simplify", + "snap", + "voronoi_polygons", +] + +class BufferCapStyle(ParamEnum): + round = 1 + flat = 2 + square = 3 + +class BufferJoinStyle(ParamEnum): + round = 1 + mitre = 2 + bevel = 3 + +@overload +def boundary(geometry: Point | MultiPoint, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... +@overload +def boundary(geometry: LineString | MultiLineString, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint: ... +@overload +def boundary(geometry: Polygon | MultiPolygon, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString: ... +@overload +def boundary(geometry: GeometryCollection | None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def boundary(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseMultipartGeometry | Any: ... +@overload +def boundary(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def buffer( + geometry: Geometry, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> Polygon: ... +@overload +def buffer( + geometry: None, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def buffer( + geometry: Geometry | None, + distance: float, + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> Polygon | None: ... +@overload +def buffer( + geometry: OptGeoArrayLike, + distance: ArrayLikeSeq[float], + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def buffer( + geometry: OptGeoArrayLikeSeq, + distance: ArrayLike[float], + quad_segs: int = 8, + cap_style: BufferJoinStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def offset_curve( + geometry: Geometry, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def offset_curve( + geometry: None, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def offset_curve( + geometry: Geometry | None, + distance: float, + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString | None: ... +@overload +def offset_curve( + geometry: OptGeoArrayLike, + distance: ArrayLikeSeq[float], + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def offset_curve( + geometry: OptGeoArrayLikeSeq, + distance: ArrayLike[float], + quad_segs: SupportsIndex = 8, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def centroid(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def centroid(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def centroid(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Point | None: ... +@overload +def centroid(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def clip_by_rect( + geometry: Geometry, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def clip_by_rect(geometry: None, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def clip_by_rect( + geometry: Geometry | None, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def clip_by_rect( + geometry: OptGeoArrayLikeSeq, xmin: float, ymin: float, xmax: float, ymax: float, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def concave_hull( + geometry: Geometry, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def concave_hull(geometry: None, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def concave_hull( + geometry: Geometry | None, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def concave_hull( + geometry: OptGeoArrayLikeSeq, ratio: float = 0.0, allow_holes: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def convex_hull(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def convex_hull(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def convex_hull(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def convex_hull(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, only_edges: Literal[False] = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float, only_edges: Literal[True], **kwargs: Unpack[UFuncKwargs] +) -> MultiLineString: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, *, only_edges: Literal[True], **kwargs: Unpack[UFuncKwargs] +) -> MultiLineString: ... +@overload +def delaunay_triangles( + geometry: Geometry, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection | MultiLineString: ... +@overload +def delaunay_triangles( + geometry: None, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def delaunay_triangles( + geometry: Geometry | None, tolerance: float = 0.0, only_edges: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> GeometryCollection | MultiLineString | None: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLike[float], only_edges: ArrayLikeSeq[bool], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLike[float] = 0.0, *, only_edges: ArrayLikeSeq[bool], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], only_edges: ArrayLike[bool] = False, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def delaunay_triangles( + geometry: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + only_edges: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def constrained_delaunay_triangles(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection | None: ... # type: ignore[overload-overlap] +@overload +def constrained_delaunay_triangles(geometry: OptGeoArrayLikeSeq | OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def envelope(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def envelope(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def envelope(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def envelope(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def envelope(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def extract_unique_points(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint: ... +@overload +def extract_unique_points(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def extract_unique_points(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> MultiPoint | None: ... +@overload +def extract_unique_points(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def build_area(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def build_area(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def build_area(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def build_area(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +# make_valid with `method="linework"` only accepts `keep_collapsed=True` +@overload +def make_valid( + geometry: Geometry, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> BaseGeometry: ... +@overload +def make_valid( + geometry: None, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def make_valid( + geometry: Geometry | None, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> BaseGeometry | None: ... +@overload +def make_valid( + geometry: OptGeoArrayLikeSeq, + *, + method: Literal["linework"] = "linework", + keep_collapsed: Literal[True] = True, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def make_valid( + geometry: Geometry, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def make_valid( + geometry: None, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def make_valid( + geometry: Geometry | None, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | None: ... +@overload +def make_valid( + geometry: OptGeoArrayLikeSeq, *, method: Literal["structure"], keep_collapsed: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def minimum_clearance_line(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def minimum_clearance_line(geometry: LineString | Polygon | BaseMultipartGeometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon: ... +@overload +def minimum_clearance_line(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point: ... +@overload +def minimum_clearance_line(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def minimum_clearance_line(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point | None: ... +@overload +def minimum_clearance_line(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def normalize(geometry: OptGeoT, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def normalize(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def point_on_surface(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def point_on_surface(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def point_on_surface(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Point | None: ... +@overload +def point_on_surface(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def node(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString: ... +@overload +def node(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def node(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> MultiLineString | None: ... +@overload +def node(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def polygonize(geometries: Sequence[Geometry | None], **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection: ... +@overload +def polygonize(geometries: Sequence[Sequence[Geometry | None]], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... +@overload +def polygonize(geometries: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeometryCollection | GeoArray: ... + +@overload +def polygonize_full( + geometries: Sequence[Geometry | None], **kwargs: Unpack[UFuncKwargs] +) -> tuple[GeometryCollection, GeometryCollection, GeometryCollection, GeometryCollection]: ... +@overload +def polygonize_full( + geometries: Sequence[Sequence[Geometry | None]], **kwargs: Unpack[UFuncKwargs] +) -> tuple[GeoArray, GeoArray, GeoArray, GeoArray]: ... +@overload +def polygonize_full( + geometries: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs] +) -> ( + tuple[GeometryCollection, GeometryCollection, GeometryCollection, GeometryCollection] + | tuple[GeoArray, GeoArray, GeoArray, GeoArray] +): ... + +@overload +def remove_repeated_points(geometry: OptGeoT, tolerance: float = 0.0, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def remove_repeated_points(geometry: OptGeoArrayLikeSeq, tolerance: float = 0.0, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def reverse(geometry: OptGeoT, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def reverse(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def segmentize(geometry: OptGeoT, max_segment_length: float, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def segmentize(geometry: OptGeoArrayLike, max_segment_length: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... +@overload +def segmentize(geometry: OptGeoArrayLikeSeq, max_segment_length: ArrayLike[float], **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def simplify(geometry: OptGeoT, tolerance: float, preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def simplify( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def simplify( + geometry: OptGeoArrayLikeSeq, tolerance: ArrayLike[float], preserve_topology: bool = True, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def snap(geometry: OptGeoT, reference: Geometry, tolerance: float, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def snap(geometry: Geometry | None, reference: None, tolerance: float, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def snap( + geometry: OptGeoArrayLikeSeq, reference: OptGeoArrayLike, tolerance: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def snap( + geometry: OptGeoArrayLike, reference: OptGeoArrayLikeSeq, tolerance: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def snap( + geometry: OptGeoArrayLike, reference: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: Literal[False] = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon]: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float, + extend_to: Geometry | None, + only_edges: Literal[True], + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + *, + only_edges: Literal[True], + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: Geometry, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon] | LineString | MultiLineString: ... +@overload +def voronoi_polygons( + geometry: None, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def voronoi_polygons( + geometry: Geometry | None, + tolerance: float = 0.0, + extend_to: Geometry | None = None, + only_edges: bool = False, + ordered: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeometryCollection[Polygon] | LineString | MultiLineString | None: ... +@overload # `geometry` as sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `tolerance` as sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLikeSeq[float], + extend_to: OptGeoArrayLike = None, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `extend_to` as positional sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLikeSeq, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `extend_to` as keyword sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + *, + extend_to: OptGeoArrayLikeSeq, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `only_edges` as positional sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLike, + only_edges: ArrayLikeSeq[bool], + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload +def voronoi_polygons( # `only_edges` as keyword sequence-like + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + *, + only_edges: ArrayLikeSeq[bool], + ordered: ArrayLike[bool] = False, + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `ordered` as positional sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float], + extend_to: OptGeoArrayLike, + only_edges: ArrayLike[bool], + ordered: ArrayLikeSeq[bool], + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... +@overload # `ordered` as keyword sequence-like +def voronoi_polygons( + geometry: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + extend_to: OptGeoArrayLike = None, + *, + only_edges: ArrayLike[bool] = False, + ordered: ArrayLikeSeq[bool], + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def oriented_envelope(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def oriented_envelope(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def oriented_envelope(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def oriented_envelope(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | None: ... +@overload +def oriented_envelope(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +minimum_rotated_rectangle = oriented_envelope + +@overload +def minimum_bounding_circle(geometry: Point, **kwargs: Unpack[UFuncKwargs]) -> Point: ... +@overload +def minimum_bounding_circle(geometry: LineString | Polygon | BaseMultipartGeometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon: ... +@overload +def minimum_bounding_circle(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point: ... +@overload +def minimum_bounding_circle(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def minimum_bounding_circle(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> Polygon | Point | None: ... +@overload +def minimum_bounding_circle(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... + +@overload +def maximum_inscribed_circle( + geometry: Polygon | MultiPolygon, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> LineString: ... +@overload +def maximum_inscribed_circle(geometry: None, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def maximum_inscribed_circle( + geometry: Polygon | MultiPolygon | None, tolerance: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> LineString | None: ... +@overload +def maximum_inscribed_circle( + geometry: OptGeoArrayLikeSeq, tolerance: ArrayLike[float] | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def maximum_inscribed_circle( + geometry: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def orient_polygons(geometry: OptGeoT, *, exterior_cw: bool = False, **kwargs: Unpack[UFuncKwargs]) -> OptGeoT: ... +@overload +def orient_polygons(geometry: OptGeoArrayLikeSeq, *, exterior_cw: bool = False, **kwargs: Unpack[UFuncKwargs]) -> GeoArray: ... diff --git a/stubs/shapely/shapely/coordinates.pyi b/stubs/shapely/shapely/coordinates.pyi new file mode 100644 index 000000000000..fd3d1284c10f --- /dev/null +++ b/stubs/shapely/shapely/coordinates.pyi @@ -0,0 +1,54 @@ +from collections.abc import Callable +from typing import Literal, overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLikeSeq, GeoArray, GeoT, OptGeoArrayLike, OptGeoArrayLikeSeq, OptGeoT + +__all__ = ["transform", "count_coordinates", "get_coordinates", "set_coordinates"] + +@overload +def transform( + geometry: OptGeoT, + transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], + include_z: bool = False, + *, + interleaved: bool = True, +) -> OptGeoT: ... +@overload +def transform( + geometry: OptGeoArrayLikeSeq, + transformation: Callable[[NDArray[np.float64]], NDArray[np.float64]], + include_z: bool = False, + *, + interleaved: bool = True, +) -> GeoArray: ... + +def count_coordinates(geometry: OptGeoArrayLike) -> int: ... + +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, return_index: Literal[False] = False, *, include_m: bool = False +) -> NDArray[np.float64]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, *, return_index: Literal[True], include_m: bool = False +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool, return_index: Literal[True], *, include_m: bool = False +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool = False, *, return_index: bool, include_m: bool = False +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + geometry: OptGeoArrayLike, include_z: bool, return_index: bool, *, include_m: bool = False +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... + +@overload +def set_coordinates(geometry: GeoT, coordinates: ArrayLikeSeq[float]) -> GeoT: ... +@overload +def set_coordinates(geometry: OptGeoArrayLikeSeq, coordinates: ArrayLikeSeq[float]) -> GeoArray: ... diff --git a/stubs/shapely/shapely/coords.pyi b/stubs/shapely/shapely/coords.pyi new file mode 100644 index 000000000000..7ea73aa8404a --- /dev/null +++ b/stubs/shapely/shapely/coords.pyi @@ -0,0 +1,20 @@ +from array import array +from collections.abc import Iterator +from typing import Literal, overload + +import numpy as np +from numpy.typing import DTypeLike, NDArray + +class CoordinateSequence: + def __init__(self, coords: NDArray[np.float64]) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[tuple[float, ...]]: ... + + @overload + def __getitem__(self, key: int) -> tuple[float, ...]: ... + @overload + def __getitem__(self, key: slice) -> list[tuple[float, ...]]: ... + + def __array__(self, dtype: DTypeLike | None = None, copy: Literal[True] | None = None) -> NDArray[np.float64]: ... + @property + def xy(self) -> tuple[array[float], array[float]]: ... diff --git a/stubs/shapely/shapely/creation.pyi b/stubs/shapely/shapely/creation.pyi new file mode 100644 index 000000000000..a51ff551071d --- /dev/null +++ b/stubs/shapely/shapely/creation.pyi @@ -0,0 +1,331 @@ +from collections.abc import Sequence +from typing import Literal, SupportsIndex, TypeAlias, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._geometry import GeometryType +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargsNoOut +from .geometry import GeometryCollection, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +from .lib import Geometry + +__all__ = [ + "box", + "destroy_prepared", + "empty", + "geometrycollections", + "linearrings", + "linestrings", + "multilinestrings", + "multipoints", + "multipolygons", + "points", + "polygons", + "prepare", +] + +class HandleNaN(ParamEnum): + allow = 0 + skip = 1 + error = 2 + +_HandleNaN: TypeAlias = Literal["allow", "skip", "error"] | HandleNaN + +@overload +def points( + coords: float, + y: float, + z: float | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], # acts as x +) -> Point: ... +@overload +def points( + coords: Sequence[float], + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], # acts as x, y[, z] +) -> Point: ... +@overload +def points( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], # must be (y1, y2, ...) + z: Sequence[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def points( + coords: Sequence[Sequence[float]], # acts as (x1, x2, ...), (y1, y2, ...)[, (z1, z2, ...)] + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def points( + coords: ArrayLike[float], + y: ArrayLike[float], + z: ArrayLike[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Point | GeoArray: ... +@overload +def points( + coords: ArrayLikeSeq[float], + y: ArrayLike[float] | None = None, + z: ArrayLike[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Point | GeoArray: ... + +@overload +def linestrings( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], + z: Sequence[float] | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString: ... +@overload +def linestrings( + coords: Sequence[Sequence[float]], # acts as (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString: ... +@overload +def linestrings( + coords: Sequence[Sequence[Sequence[float]]], # acts as seq of (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def linestrings( + coords: ArrayLikeSeq[float], + y: ArrayLikeSeq[float] | None = None, + z: ArrayLikeSeq[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LineString | GeoArray: ... + +@overload +def linearrings( + coords: Sequence[float], # acts as (x1, x2, ...) + y: Sequence[float], + z: Sequence[float] | None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing: ... +@overload +def linearrings( + coords: Sequence[Sequence[float]], # acts as (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: None = None, + *, + handle_nan: _HandleNaN = ..., + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing: ... +@overload +def linearrings( + coords: Sequence[Sequence[Sequence[float]]], # acts as seq of (x1, y1[, z1]), (x2, y2[, z2]), ... + y: None = None, + z: None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def linearrings( + coords: ArrayLikeSeq[float], + y: ArrayLikeSeq[float] | None = None, + z: ArrayLikeSeq[float] | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + handle_nan: _HandleNaN = ..., + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> LinearRing | GeoArray: ... + +@overload +def polygons( + geometries: LinearRing | Sequence[Sequence[float]] | None, + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Polygon: ... +@overload +def polygons( + geometries: Sequence[LinearRing | Sequence[Sequence[float]] | None], + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def polygons( + geometries: ArrayLikeSeq[float] | OptGeoArrayLikeSeq, + holes: ArrayLikeSeq[float] | OptGeoArrayLikeSeq | None = None, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> Polygon | GeoArray: ... + +@overload +def box(xmin: float, ymin: float, xmax: float, ymax: float, ccw: bool = True, **kwargs: Unpack[UFuncKwargsNoOut]) -> Polygon: ... +@overload +def box( + xmin: ArrayLikeSeq[float], + ymin: ArrayLikeSeq[float], + xmax: ArrayLikeSeq[float], + ymax: ArrayLikeSeq[float], + ccw: bool = True, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... + +@overload +def multipoints( + geometries: Sequence[Point | Sequence[float] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPoint: ... +@overload +def multipoints( + geometries: Sequence[Sequence[Point | Sequence[float] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multipoints( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPoint | GeoArray: ... + +@overload +def multilinestrings( + geometries: Sequence[LineString | Sequence[Sequence[float]] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiLineString: ... +@overload +def multilinestrings( + geometries: Sequence[Sequence[LineString | Sequence[Sequence[float]] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multilinestrings( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiLineString | GeoArray: ... + +@overload +def multipolygons( + geometries: Sequence[Polygon | Sequence[Sequence[float]] | None], + indices: None = None, + *, + out: None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPolygon: ... +@overload +def multipolygons( + geometries: Sequence[Sequence[Polygon | Sequence[Sequence[float]] | None]], + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def multipolygons( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + *, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> MultiPolygon | GeoArray: ... + +@overload +def geometrycollections( + geometries: Sequence[Geometry | None], indices: None = None, out: None = None, **kwargs: Unpack[UFuncKwargsNoOut] +) -> GeometryCollection: ... +@overload +def geometrycollections( + geometries: Sequence[Sequence[Geometry | None]], + indices: ArrayLikeSeq[int] | None = None, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeoArray: ... +@overload +def geometrycollections( + geometries: OptGeoArrayLikeSeq, + indices: ArrayLikeSeq[int] | None = None, + out: NDArray[np.object_] | None = None, + **kwargs: Unpack[UFuncKwargsNoOut], +) -> GeometryCollection | GeoArray: ... + +def prepare(geometry: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargsNoOut]) -> None: ... +def destroy_prepared(geometry: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargsNoOut]) -> None: ... +def empty( + shape: SupportsIndex | Sequence[SupportsIndex], geom_type: GeometryType | int | None = None, order: Literal["C", "F"] = "C" +) -> NDArray[np.object_]: ... diff --git a/stubs/shapely/shapely/decorators.pyi b/stubs/shapely/shapely/decorators.pyi new file mode 100644 index 000000000000..fe5131950cec --- /dev/null +++ b/stubs/shapely/shapely/decorators.pyi @@ -0,0 +1,12 @@ +from collections.abc import Callable, Container +from typing import TypeVar + +_F = TypeVar("_F", bound=Callable[..., object]) + +class requires_geos: + version: tuple[int, int, int] + def __init__(self, version: str) -> None: ... + def __call__(self, func: _F) -> _F: ... + +def multithreading_enabled(func: _F) -> _F: ... +def deprecate_positional(should_be_kwargs: Container[str], category: type[Warning] = ...) -> Callable[..., object]: ... diff --git a/stubs/shapely/shapely/errors.pyi b/stubs/shapely/shapely/errors.pyi new file mode 100644 index 000000000000..3cef1a428ab0 --- /dev/null +++ b/stubs/shapely/shapely/errors.pyi @@ -0,0 +1,17 @@ +from .lib import GEOSException as GEOSException, ShapelyError as ShapelyError + +def setup_signal_checks(interval: int = 10000) -> None: ... + +class UnsupportedGEOSVersionError(ShapelyError): ... +class DimensionError(ShapelyError): ... +class TopologicalError(ShapelyError): ... +class ShapelyDeprecationWarning(FutureWarning): ... +class EmptyPartError(ShapelyError): ... +class GeometryTypeError(ShapelyError): ... + +# deprecated aliases +ReadingError = ShapelyError +WKBReadingError = ShapelyError +WKTReadingError = ShapelyError +PredicateError = ShapelyError +InvalidGeometryError = ShapelyError diff --git a/stubs/shapely/shapely/geometry/__init__.pyi b/stubs/shapely/shapely/geometry/__init__.pyi new file mode 100644 index 000000000000..97227a3a41fa --- /dev/null +++ b/stubs/shapely/shapely/geometry/__init__.pyi @@ -0,0 +1,25 @@ +from .base import CAP_STYLE as CAP_STYLE, JOIN_STYLE as JOIN_STYLE +from .collection import GeometryCollection as GeometryCollection +from .geo import box as box, mapping as mapping, shape as shape +from .linestring import LineString as LineString +from .multilinestring import MultiLineString as MultiLineString +from .multipoint import MultiPoint as MultiPoint +from .multipolygon import MultiPolygon as MultiPolygon +from .point import Point as Point +from .polygon import LinearRing as LinearRing, Polygon as Polygon + +__all__ = [ + "box", + "shape", + "mapping", + "Point", + "LineString", + "Polygon", + "MultiPoint", + "MultiLineString", + "MultiPolygon", + "GeometryCollection", + "LinearRing", + "CAP_STYLE", + "JOIN_STYLE", +] diff --git a/stubs/shapely/shapely/geometry/base.pyi b/stubs/shapely/shapely/geometry/base.pyi new file mode 100644 index 000000000000..e4138123166b --- /dev/null +++ b/stubs/shapely/shapely/geometry/base.pyi @@ -0,0 +1,326 @@ +from array import array +from collections.abc import Iterator +from typing import Any, Generic, Literal, overload +from typing_extensions import Never, Self, TypeVar, deprecated + +import numpy as np +from numpy.typing import NDArray + +from .._typing import ArrayLikeSeq, GeoArray, GeoT, OptGeoArrayLike, OptGeoArrayLikeSeq +from ..constructive import BufferCapStyle, BufferJoinStyle +from ..coords import CoordinateSequence +from ..lib import Geometry +from .collection import GeometryCollection +from .point import Point +from .polygon import Polygon + +GEOMETRY_TYPES: list[str] + +@deprecated("Function 'geom_factory' is deprecated.") +def geom_factory(g: int, parent: object | None = None) -> Any: ... +def dump_coords(geom: Geometry) -> list[tuple[float, float] | list[tuple[float, float]]]: ... + +class CAP_STYLE: + round: Literal[BufferCapStyle.round] + flat: Literal[BufferCapStyle.flat] + square: Literal[BufferCapStyle.square] + +class JOIN_STYLE: + round: Literal[BufferJoinStyle.round] + mitre: Literal[BufferJoinStyle.mitre] + bevel: Literal[BufferJoinStyle.bevel] + +class BaseGeometry(Geometry): + __slots__: list[str] = [] + @deprecated( + "Directly calling 'BaseGeometry()' is deprecated. To create an empty geometry, " + "use one of the subclasses instead, for example 'GeometryCollection()'." + ) + def __new__(self) -> GeometryCollection: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __format__(self, format_spec: str) -> str: ... + + @overload + def __and__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __and__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __and__(self, other: None) -> None: ... + + @overload + def __or__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __or__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __or__(self, other: None) -> None: ... + + @overload + def __sub__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __sub__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __sub__(self, other: None) -> None: ... + + @overload + def __xor__(self, other: Geometry) -> BaseGeometry: ... + @overload + def __xor__(self, other: OptGeoArrayLikeSeq) -> GeoArray: ... + @overload + def __xor__(self, other: None) -> None: ... + + def __eq__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __hash__(self) -> int: ... + @property + def coords(self) -> CoordinateSequence: ... + @property + def xy(self) -> tuple[array[float], array[float]]: ... + @property + def __geo_interface__(self) -> dict[str, Any]: ... + @deprecated("Method 'geometryType()' is deprecated. Use attribute 'geom_type' instead.") + def geometryType(self) -> str: ... + @property + @deprecated("Attribute 'type' is deprecated. Use attribute 'geom_type' instead.") + def type(self) -> str: ... + @property + def wkt(self) -> str: ... + @property + def wkb(self) -> bytes: ... + @property + def wkb_hex(self) -> str: ... + def svg(self, scale_factor: float = 1.0, **kwargs) -> str: ... + def _repr_svg_(self) -> str: ... + @property + def geom_type(self) -> str: ... + @property + def area(self) -> float: ... + + @overload + def distance(self, other: Geometry | None) -> float: ... + @overload + def distance(self, other: OptGeoArrayLikeSeq) -> NDArray[np.float64]: ... + + @overload + def hausdorff_distance(self, other: Geometry | None) -> float: ... + @overload + def hausdorff_distance(self, other: OptGeoArrayLikeSeq) -> NDArray[np.float64]: ... + + @property + def length(self) -> float: ... + @property + def minimum_clearance(self) -> float: ... + @property + def boundary(self) -> BaseMultipartGeometry | Any: ... # is None for GeometryCollection + @property + def bounds(self) -> tuple[float, float, float, float]: ... + @property + def centroid(self) -> Point: ... + def point_on_surface(self) -> Point: ... + def representative_point(self) -> Point: ... + @property + def convex_hull(self) -> BaseGeometry: ... + @property + def envelope(self) -> BaseGeometry: ... + @property + def oriented_envelope(self) -> BaseGeometry: ... + @property + def minimum_rotated_rectangle(self) -> BaseGeometry: ... + def buffer( + self, + distance: float, + quad_segs: int = 16, + cap_style: BufferCapStyle | Literal["round", "square", "flat"] = "round", + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = "round", + mitre_limit: float = 5.0, + single_sided: bool = False, + *, + quadsegs: int | None = None, # deprecated + resolution: int | None = None, # deprecated + ) -> Polygon: ... + def simplify(self, tolerance: float, preserve_topology: bool = True) -> BaseGeometry: ... + def normalize(self) -> BaseGeometry: ... + + @overload + def difference(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def difference(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def difference(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def intersection(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def intersection(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def intersection(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def symmetric_difference(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def symmetric_difference(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def symmetric_difference(self, other: None, grid_size: float | None = None) -> None: ... + + @overload + def union(self, other: Geometry, grid_size: float | None = None) -> BaseGeometry: ... + @overload + def union(self, other: OptGeoArrayLikeSeq, grid_size: float | None = None) -> GeoArray: ... + @overload + def union(self, other: None, grid_size: float | None = None) -> None: ... + + @property + def has_z(self) -> bool: ... + @property + def has_m(self) -> bool: ... + @property + def is_empty(self) -> bool: ... + @property + def is_ring(self) -> bool: ... + @property + def is_closed(self) -> bool: ... + @property + def is_simple(self) -> bool: ... + @property + def is_valid(self) -> bool: ... + + @overload + def relate(self, other: Geometry) -> str: ... + @overload + def relate(self, other: OptGeoArrayLikeSeq) -> NDArray[np.str_]: ... + @overload + def relate(self, other: None) -> None: ... + + @overload + def covers(self, other: Geometry | None) -> bool: ... + @overload + def covers(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def covered_by(self, other: Geometry | None) -> bool: ... + @overload + def covered_by(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def contains(self, other: Geometry | None) -> bool: ... + @overload + def contains(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def contains_properly(self, other: Geometry | None) -> bool: ... + @overload + def contains_properly(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def crosses(self, other: Geometry | None) -> bool: ... + @overload + def crosses(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def disjoint(self, other: Geometry | None) -> bool: ... + @overload + def disjoint(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def equals(self, other: Geometry | None) -> bool: ... + @overload + def equals(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def intersects(self, other: Geometry | None) -> bool: ... + @overload + def intersects(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def overlaps(self, other: Geometry | None) -> bool: ... + @overload + def overlaps(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def touches(self, other: Geometry | None) -> bool: ... + @overload + def touches(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def within(self, other: Geometry | None) -> bool: ... + @overload + def within(self, other: OptGeoArrayLikeSeq) -> NDArray[np.bool_]: ... + + @overload + def dwithin(self, other: Geometry | None, distance: float) -> bool: ... + @overload + def dwithin(self, other: OptGeoArrayLikeSeq, distance: float) -> NDArray[np.bool_]: ... + @overload + def dwithin(self, other: OptGeoArrayLike, distance: ArrayLikeSeq[float]) -> NDArray[np.bool_]: ... + + @overload + def equals_exact(self, other: Geometry | None, tolerance: float = 0.0, *, normalize: bool = False) -> bool: ... + @overload + def equals_exact( + self, other: OptGeoArrayLikeSeq, tolerance: float = 0.0, *, normalize: bool = False + ) -> NDArray[np.bool_]: ... + @overload + def equals_exact( + self, other: OptGeoArrayLike, tolerance: ArrayLikeSeq[float], *, normalize: bool = False + ) -> NDArray[np.bool_]: ... + + @overload + def relate_pattern(self, other: Geometry | None, pattern: str) -> bool: ... + @overload + def relate_pattern(self, other: OptGeoArrayLikeSeq, pattern: str) -> NDArray[np.bool_]: ... + + @overload + def line_locate_point(self, other: Point | None, normalized: bool = False) -> float: ... + @overload + def line_locate_point(self, other: OptGeoArrayLikeSeq, normalized: bool = False) -> NDArray[np.float64]: ... + + @overload + def project(self, other: Point | None, normalized: bool = False) -> float: ... + @overload + def project(self, other: OptGeoArrayLikeSeq, normalized: bool = False) -> NDArray[np.float64]: ... + + @overload + def line_interpolate_point(self, distance: float, normalized: bool = False) -> Point: ... + @overload + def line_interpolate_point(self, distance: ArrayLikeSeq[float], normalized: bool = False) -> GeoArray: ... + + @overload + def interpolate(self, distance: float, normalized: bool = False) -> Point: ... + @overload + def interpolate(self, distance: ArrayLikeSeq[float], normalized: bool = False) -> GeoArray: ... + + @overload + def segmentize(self, max_segment_length: float) -> Self: ... + @overload + def segmentize(self, max_segment_length: ArrayLikeSeq[float]) -> GeoArray: ... + + def reverse(self) -> Self: ... + +_GeoT_co = TypeVar("_GeoT_co", bound=Geometry, default=BaseGeometry, covariant=True) + +class BaseMultipartGeometry(BaseGeometry, Generic[_GeoT_co]): + __slots__: list[str] = [] + @property + def coords(self) -> Never: ... + @property + def geoms(self) -> GeometrySequence[Self]: ... + def svg(self, scale_factor: float = 1.0, color: str | None = None) -> str: ... # type: ignore[override] + +_P_co = TypeVar("_P_co", covariant=True, bound=BaseMultipartGeometry[Geometry]) + +class GeometrySequence(Generic[_P_co]): + def __init__(self, parent: _P_co) -> None: ... + def __iter__(self: GeometrySequence[BaseMultipartGeometry[GeoT]]) -> Iterator[GeoT]: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self: GeometrySequence[BaseMultipartGeometry[GeoT]], key: int | np.integer[Any]) -> GeoT: ... + @overload + def __getitem__(self, key: slice) -> _P_co: ... + +class EmptyGeometry(BaseGeometry): + @deprecated( + "The 'EmptyGeometry()' constructor is deprecated. Use one of the " + "geometry subclasses instead, for example 'GeometryCollection()'." + ) + def __new__(self) -> GeometryCollection: ... # type: ignore[misc] diff --git a/stubs/shapely/shapely/geometry/collection.pyi b/stubs/shapely/shapely/geometry/collection.pyi new file mode 100644 index 000000000000..abc1b7e42af1 --- /dev/null +++ b/stubs/shapely/shapely/geometry/collection.pyi @@ -0,0 +1,23 @@ +from collections.abc import Collection +from typing import Literal, overload +from typing_extensions import Self + +from .._typing import OptGeoArrayLike +from .base import BaseMultipartGeometry, GeometrySequence, _GeoT_co + +class GeometryCollection(BaseMultipartGeometry[_GeoT_co]): + # Overloads of __new__ are used because mypy is unable to narrow the typevar otherwise + __slots__: list[str] = [] + + @overload + def __new__( + self, geoms: BaseMultipartGeometry[_GeoT_co] | GeometrySequence[BaseMultipartGeometry[_GeoT_co]] | Collection[_GeoT_co] + ) -> Self: ... + @overload + def __new__(self, geoms: OptGeoArrayLike = None) -> Self: ... + + # more precise base overrides + @property + def geom_type(self) -> Literal["GeometryCollection"]: ... + @property + def boundary(self) -> None: ... diff --git a/stubs/shapely/shapely/geometry/geo.pyi b/stubs/shapely/shapely/geometry/geo.pyi new file mode 100644 index 000000000000..ac1c48664f48 --- /dev/null +++ b/stubs/shapely/shapely/geometry/geo.pyi @@ -0,0 +1,9 @@ +from typing import Any + +from .._typing import SupportsGeoInterface +from .base import BaseGeometry +from .polygon import Polygon + +def box(minx: float, miny: float, maxx: float, maxy: float, ccw: bool = True) -> Polygon: ... +def shape(context: dict[str, Any] | SupportsGeoInterface) -> BaseGeometry: ... +def mapping(ob: SupportsGeoInterface) -> dict[str, Any]: ... diff --git a/stubs/shapely/shapely/geometry/linestring.pyi b/stubs/shapely/shapely/geometry/linestring.pyi new file mode 100644 index 000000000000..54649d1e6963 --- /dev/null +++ b/stubs/shapely/shapely/geometry/linestring.pyi @@ -0,0 +1,48 @@ +from collections.abc import Iterable +from typing import Literal, SupportsFloat, SupportsIndex, TypeAlias +from typing_extensions import Self + +from .._typing import ArrayLikeSeq +from ..constructive import BufferJoinStyle +from .base import BaseGeometry +from .multilinestring import MultiLineString +from .multipoint import MultiPoint +from .point import Point +from .polygon import Polygon + +__all__ = ["LineString"] + +_ConvertibleToLineString: TypeAlias = LineString | ArrayLikeSeq[float] | Iterable[Point | Iterable[SupportsFloat]] + +class LineString(BaseGeometry): + __slots__: list[str] = [] + def __new__(self, coordinates: _ConvertibleToLineString | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, stroke_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + def offset_curve( + self, + distance: float, + quad_segs: SupportsIndex = 16, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = ..., + mitre_limit: float = 5.0, + ) -> LineString | MultiLineString: ... + def parallel_offset( # to be deprecated + self, + distance: float, + side: str = "right", + resolution: SupportsIndex = 16, + join_style: BufferJoinStyle | Literal["round", "mitre", "bevel"] = ..., + mitre_limit: float = 5.0, + ) -> LineString | MultiLineString: ... + # more precise base overrides + @property + def geom_type(self) -> Literal["LineString", "LinearRing"]: ... # LinearRing is a subclass of LineString + @property + def boundary(self) -> MultiPoint: ... + @property + def convex_hull(self) -> LineString: ... + @property + def envelope(self) -> Polygon: ... + @property + def oriented_envelope(self) -> LineString: ... + @property + def minimum_rotated_rectangle(self) -> LineString: ... diff --git a/stubs/shapely/shapely/geometry/multilinestring.pyi b/stubs/shapely/shapely/geometry/multilinestring.pyi new file mode 100644 index 000000000000..ec0f6c53857c --- /dev/null +++ b/stubs/shapely/shapely/geometry/multilinestring.pyi @@ -0,0 +1,19 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .linestring import LineString, _ConvertibleToLineString +from .multipoint import MultiPoint + +__all__ = ["MultiLineString"] + +class MultiLineString(BaseMultipartGeometry[LineString]): + __slots__: list[str] = [] + def __new__(self, lines: BaseMultipartGeometry | Collection[_ConvertibleToLineString] | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, stroke_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiLineString"]: ... + @property + def boundary(self) -> MultiPoint: ... diff --git a/stubs/shapely/shapely/geometry/multipoint.pyi b/stubs/shapely/shapely/geometry/multipoint.pyi new file mode 100644 index 000000000000..c931c474d165 --- /dev/null +++ b/stubs/shapely/shapely/geometry/multipoint.pyi @@ -0,0 +1,24 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .collection import GeometryCollection +from .point import Point, _PointLike + +__all__ = ["MultiPoint"] + +class MultiPoint(BaseMultipartGeometry[Point]): + # Note on "points" type in `__new__`: + # * `Collection` here is loose as the expected type should support "__getitem__". + # * `Sequence` is more correct but it will lead to False positives with common types + # like np.ndarray, pd.Index, pd.Series, ... + # I went with Collection as false negatives seem better to me than false positives in this case + __slots__: list[str] = [] + def __new__(self, points: MultiPoint | Collection[_PointLike] | None = None) -> Self: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiPoint"]: ... + @property + def boundary(self) -> GeometryCollection: ... # empty geometry collection diff --git a/stubs/shapely/shapely/geometry/multipolygon.pyi b/stubs/shapely/shapely/geometry/multipolygon.pyi new file mode 100644 index 000000000000..0c60c5fa7da9 --- /dev/null +++ b/stubs/shapely/shapely/geometry/multipolygon.pyi @@ -0,0 +1,26 @@ +from collections.abc import Collection +from typing import Literal +from typing_extensions import Self + +from .base import BaseMultipartGeometry +from .multilinestring import MultiLineString +from .polygon import Polygon, _PolygonHolesLike, _PolygonShellLike + +__all__ = ["MultiPolygon"] + +class MultiPolygon(BaseMultipartGeometry[Polygon]): + __slots__: list[str] = [] + def __new__( + self, + polygons: ( + BaseMultipartGeometry + | Collection[Polygon | tuple[_PolygonShellLike] | tuple[_PolygonShellLike, _PolygonHolesLike] | None] + | None + ) = None, + ) -> Self: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["MultiPolygon"]: ... + @property + def boundary(self) -> MultiLineString: ... diff --git a/stubs/shapely/shapely/geometry/point.pyi b/stubs/shapely/shapely/geometry/point.pyi new file mode 100644 index 000000000000..5f37e65a7b93 --- /dev/null +++ b/stubs/shapely/shapely/geometry/point.pyi @@ -0,0 +1,46 @@ +from collections.abc import Iterable +from typing import Literal, TypeAlias, overload +from typing_extensions import Self + +from .._typing import ArrayLikeSeq +from .base import BaseGeometry +from .collection import GeometryCollection + +__all__ = ["Point"] + +_PointLike: TypeAlias = Point | Iterable[float] | ArrayLikeSeq[float] + +class Point(BaseGeometry): + __slots__: list[str] = [] + + @overload # no args: empty point + def __new__(self) -> Self: ... + @overload # one arg: (x, y[, z]) tuple or a Point instance + def __new__(self, coords: _PointLike, /) -> Self: ... + @overload # two args: (x, y) tuple + def __new__(self, x: float, y: float, /) -> Self: ... + @overload # three args: (x, y, z) tuple + def __new__(self, x: float, y: float, z: float, /) -> Self: ... + + @property + def x(self) -> float: ... + @property + def y(self) -> float: ... + @property + def z(self) -> float: ... + @property + def m(self) -> float: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + # more precise base overrides + @property + def geom_type(self) -> Literal["Point"]: ... + @property + def boundary(self) -> GeometryCollection: ... # empty geometry collection + @property + def convex_hull(self) -> Point: ... + @property + def envelope(self) -> Point: ... + @property + def oriented_envelope(self) -> Point: ... + @property + def minimum_rotated_rectangle(self) -> Point: ... diff --git a/stubs/shapely/shapely/geometry/polygon.pyi b/stubs/shapely/shapely/geometry/polygon.pyi new file mode 100644 index 000000000000..e52857a88946 --- /dev/null +++ b/stubs/shapely/shapely/geometry/polygon.pyi @@ -0,0 +1,52 @@ +from collections.abc import Collection +from typing import Literal, TypeAlias, overload +from typing_extensions import Never, Self + +from .base import BaseGeometry +from .linestring import LineString, _ConvertibleToLineString +from .multilinestring import MultiLineString + +__all__ = ["orient", "Polygon", "LinearRing"] + +_ConvertibleToLinearRing: TypeAlias = _ConvertibleToLineString # same alias but with better name for doc purposes +_PolygonShellLike: TypeAlias = Polygon | _ConvertibleToLinearRing | None +_PolygonHolesLike: TypeAlias = Collection[_ConvertibleToLinearRing | None] | None + +class LinearRing(LineString): + __slots__: list[str] = [] + def __new__(self, coordinates: _ConvertibleToLinearRing | None = None) -> Self: ... + @property + def is_ccw(self) -> bool: ... + @property + def geom_type(self) -> Literal["LinearRing"]: ... + +class InteriorRingSequence: + def __init__(self, parent: Polygon) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> LinearRing: ... + def __len__(self) -> int: ... + + @overload + def __getitem__(self, key: int) -> LinearRing: ... + @overload + def __getitem__(self, key: slice) -> list[LinearRing]: ... + +class Polygon(BaseGeometry): + __slots__: list[str] = [] + def __new__(self, shell: _PolygonShellLike = None, holes: _PolygonHolesLike = None) -> Self: ... + @property + def exterior(self) -> LinearRing: ... + @property + def interiors(self) -> list[LinearRing] | InteriorRingSequence: ... + @property + def coords(self) -> Never: ... + def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] + @classmethod + def from_bounds(cls, xmin: float, ymin: float, xmax: float, ymax: float) -> Self: ... + # more precise base overrides + @property + def geom_type(self) -> Literal["Polygon"]: ... + @property + def boundary(self) -> MultiLineString: ... + +def orient(polygon: Polygon, sign: float = 1.0) -> Polygon: ... diff --git a/stubs/shapely/shapely/geos.pyi b/stubs/shapely/shapely/geos.pyi new file mode 100644 index 000000000000..669802c38a36 --- /dev/null +++ b/stubs/shapely/shapely/geos.pyi @@ -0,0 +1,3 @@ +geos_version_string: str +geos_version: tuple[int, int, int] +geos_capi_version: tuple[int, int, int] diff --git a/stubs/shapely/shapely/io.pyi b/stubs/shapely/shapely/io.pyi new file mode 100644 index 000000000000..2506df3e6c3b --- /dev/null +++ b/stubs/shapely/shapely/io.pyi @@ -0,0 +1,176 @@ +from _typeshed import Incomplete +from typing import Literal, TypeAlias, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._ragged_array import from_ragged_array as from_ragged_array, to_ragged_array as to_ragged_array +from ._typing import ArrayLikeSeq, GeoArray, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = ["from_geojson", "from_ragged_array", "from_wkb", "from_wkt", "to_geojson", "to_ragged_array", "to_wkb", "to_wkt"] + +_OutputDimension: TypeAlias = Literal[2, 3, 4] + +# Mypy and stubtest aren't happy with the following definition and +# raise is a reserved keyword, so we cannot use the class syntax of enums +# DecodingErrorOptions = ParamEnum("DecodingErrorOptions", {"ignore": 0, "warn": 1, "raise": 2, "fix": 3}) +DecodingErrorOptions: Incomplete + +class WKBFlavorOptions(ParamEnum): + extended = 1 + iso = 2 + +@overload +def to_wkt( + geometry: None, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def to_wkt( + geometry: Geometry, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> str: ... +@overload +def to_wkt( + geometry: OptGeoArrayLikeSeq, + rounding_precision: int = 6, + trim: bool = True, + output_dimension: _OutputDimension | None = None, + old_3d: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.str_]: ... + +@overload +def to_wkb( + geometry: None, + hex: bool = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> None: ... +@overload +def to_wkb( + geometry: Geometry, + hex: Literal[False] = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> bytes: ... +@overload +def to_wkb( + geometry: Geometry, + hex: Literal[True], + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> str: ... +@overload +def to_wkb( + geometry: Geometry, + hex: bool, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> bytes | str: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: Literal[False] = False, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bytes_]: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: Literal[True], + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.str_]: ... +@overload +def to_wkb( + geometry: OptGeoArrayLikeSeq, + hex: bool, + output_dimension: _OutputDimension | None = None, + byte_order: int = -1, + include_srid: bool = False, + flavor: Literal["iso", "extended"] = "extended", + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bytes_] | NDArray[np.str_]: ... + +@overload +def to_geojson(geometry: None, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def to_geojson(geometry: Geometry, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def to_geojson(geometry: OptGeoArrayLikeSeq, indent: int | None = None, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.str_]: ... + +@overload +def from_wkt( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_wkt( # type: ignore[overload-overlap] + geometry: str, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_wkt( + geometry: ArrayLikeSeq[str | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def from_wkb( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_wkb( # type: ignore[overload-overlap] + geometry: str | bytes, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_wkb( + geometry: ArrayLikeSeq[str | bytes | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... + +@overload +def from_geojson( + geometry: None, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> None: ... +@overload +def from_geojson( # type: ignore[overload-overlap] + geometry: str | bytes, on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def from_geojson( + geometry: ArrayLikeSeq[str | bytes | None], + on_invalid: Literal["raise", "warn", "ignore", "fix"] = "raise", + **kwargs: Unpack[UFuncKwargs], +) -> GeoArray: ... diff --git a/stubs/shapely/shapely/lib.pyi b/stubs/shapely/shapely/lib.pyi new file mode 100644 index 000000000000..ea224928eab6 --- /dev/null +++ b/stubs/shapely/shapely/lib.pyi @@ -0,0 +1,182 @@ +from typing import Literal, SupportsIndex, final, overload +from typing_extensions import Never, Self, disjoint_base + +import numpy as np +from numpy.typing import NDArray + +area: np.ufunc +boundary: np.ufunc +bounds: np.ufunc +box: np.ufunc +buffer: np.ufunc +build_area: np.ufunc +centroid: np.ufunc +clip_by_rect: np.ufunc +concave_hull: np.ufunc +constrained_delaunay_triangles: np.ufunc +contains: np.ufunc +contains_properly: np.ufunc +contains_xy: np.ufunc +convex_hull: np.ufunc +coverage_invalid_edges: np.ufunc +coverage_is_valid: np.ufunc +coverage_simplify: np.ufunc +coverage_union: np.ufunc +covered_by: np.ufunc +covers: np.ufunc +create_collection: np.ufunc +crosses: np.ufunc +delaunay_triangles: np.ufunc +destroy_prepared: np.ufunc +difference: np.ufunc +difference_prec: np.ufunc +disjoint: np.ufunc +disjoint_subset_union: np.ufunc +distance: np.ufunc +dwithin: np.ufunc +envelope: np.ufunc +equals: np.ufunc +equals_exact: np.ufunc +equals_identical: np.ufunc +extract_unique_points: np.ufunc +force_2d: np.ufunc +force_3d: np.ufunc +frechet_distance: np.ufunc +frechet_distance_densify: np.ufunc +from_geojson: np.ufunc +from_wkb: np.ufunc +from_wkt: np.ufunc +get_coordinate_dimension: np.ufunc +get_dimensions: np.ufunc +get_exterior_ring: np.ufunc +get_geometry: np.ufunc +get_interior_ring: np.ufunc +get_m: np.ufunc +get_num_coordinates: np.ufunc +get_num_geometries: np.ufunc +get_num_interior_rings: np.ufunc +get_num_points: np.ufunc +get_point: np.ufunc +get_precision: np.ufunc +get_srid: np.ufunc +get_type_id: np.ufunc +has_m: np.ufunc +get_x: np.ufunc +get_y: np.ufunc +get_z: np.ufunc +has_z: np.ufunc +hausdorff_distance: np.ufunc +hausdorff_distance_densify: np.ufunc +intersection: np.ufunc +intersection_all: np.ufunc +intersection_prec: np.ufunc +intersects: np.ufunc +intersects_xy: np.ufunc +is_ccw: np.ufunc +is_closed: np.ufunc +is_empty: np.ufunc +is_geometry: np.ufunc +is_missing: np.ufunc +is_prepared: np.ufunc +is_ring: np.ufunc +is_simple: np.ufunc +is_valid: np.ufunc +is_valid_input: np.ufunc +is_valid_reason: np.ufunc +length: np.ufunc +line_interpolate_point: np.ufunc +line_interpolate_point_normalized: np.ufunc +line_locate_point: np.ufunc +line_locate_point_normalized: np.ufunc +line_merge: np.ufunc +line_merge_directed: np.ufunc +linearrings: np.ufunc +linestrings: np.ufunc +make_valid: np.ufunc +make_valid_with_params: np.ufunc +maximum_inscribed_circle: np.ufunc +minimum_bounding_circle: np.ufunc +minimum_bounding_radius: np.ufunc +minimum_clearance: np.ufunc +minimum_clearance_line: np.ufunc +node: np.ufunc +normalize: np.ufunc +offset_curve: np.ufunc +orient_polygons: np.ufunc +oriented_envelope: np.ufunc +overlaps: np.ufunc +point_on_surface: np.ufunc +points: np.ufunc +polygonize: np.ufunc +polygonize_full: np.ufunc +polygons: np.ufunc +prepare: np.ufunc +relate: np.ufunc +relate_pattern: np.ufunc +remove_repeated_points: np.ufunc +reverse: np.ufunc +segmentize: np.ufunc +set_precision: np.ufunc +set_srid: np.ufunc +shared_paths: np.ufunc +shortest_line: np.ufunc +simplify: np.ufunc +simplify_preserve_topology: np.ufunc +snap: np.ufunc +symmetric_difference: np.ufunc +symmetric_difference_all: np.ufunc +symmetric_difference_prec: np.ufunc +to_geojson: np.ufunc +to_wkb: np.ufunc +to_wkt: np.ufunc +touches: np.ufunc +unary_union: np.ufunc +unary_union_prec: np.ufunc +union: np.ufunc +union_prec: np.ufunc +voronoi_polygons: np.ufunc +within: np.ufunc +geos_capi_version: tuple[int, int, int] +geos_capi_version_string: str +geos_version: tuple[int, int, int] +geos_version_string: str +registry: list[type[Geometry]] + +@disjoint_base +class Geometry: + def __hash__(self) -> int: ... + def __eq__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __ge__(self, other: Never, /) -> bool: ... + def __gt__(self, other: Never, /) -> bool: ... + def __le__(self, other: Never, /) -> bool: ... + def __lt__(self, other: Never, /) -> bool: ... + +@final +class STRtree: + count: int + def __new__(cls, geoms: NDArray[np.object_], node_capacity: SupportsIndex, /, **kwargs: object) -> Self: ... + def dwithin(self, geoms: NDArray[np.object_], distances: NDArray[np.float64], /) -> NDArray[np.int64]: ... + def nearest(self, geoms: NDArray[np.object_], /) -> NDArray[np.int64]: ... + def query(self, geoms: NDArray[np.object_], predicate: SupportsIndex, /) -> NDArray[np.int64]: ... + def query_nearest( + self, geoms: NDArray[np.object_], max_distance: float, exclusive: SupportsIndex, all_matches: SupportsIndex, / + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + +class ShapelyError(Exception): ... +class GEOSException(ShapelyError): ... + +def count_coordinates(geoms: NDArray[np.object_], /) -> int: ... + +@overload +def get_coordinates(arr: NDArray[np.object_], include_z: bool, return_index: Literal[False], /) -> NDArray[np.float64]: ... +@overload +def get_coordinates( + arr: NDArray[np.object_], include_z: bool, return_index: Literal[True], / +) -> tuple[NDArray[np.float64], NDArray[np.int64]]: ... +@overload +def get_coordinates( + arr: NDArray[np.object_], include_z: bool, return_index: bool, / +) -> NDArray[np.float64] | tuple[NDArray[np.float64], NDArray[np.int64]]: ... + +def set_coordinates(geoms: NDArray[np.object_], coords: NDArray[np.float64], /) -> NDArray[np.object_]: ... diff --git a/stubs/shapely/shapely/linear.pyi b/stubs/shapely/shapely/linear.pyi new file mode 100644 index 000000000000..904a00ce1f95 --- /dev/null +++ b/stubs/shapely/shapely/linear.pyi @@ -0,0 +1,73 @@ +from typing import overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq +from .geometry import GeometryCollection, LineString, MultiLineString, Point +from .lib import Geometry + +__all__ = ["line_interpolate_point", "line_locate_point", "line_merge", "shared_paths", "shortest_line"] + +@overload +def line_interpolate_point(line: None, distance: float, normalized: bool = False, **kwargs) -> None: ... +@overload +def line_interpolate_point( + line: None, distance: ArrayLikeSeq[float], normalized: bool = False, **kwargs +) -> NDArray[np.object_]: ... # Array of None +@overload +def line_interpolate_point( + line: LineString | MultiLineString | GeometryCollection, distance: float, normalized: bool = False, **kwargs +) -> Point: ... +@overload +def line_interpolate_point( + line: LineString | MultiLineString | GeometryCollection, distance: ArrayLikeSeq[float], normalized: bool = False, **kwargs +) -> GeoArray: ... +@overload +def line_interpolate_point( + line: OptGeoArrayLikeSeq, distance: ArrayLike[float], normalized: bool = False, **kwargs +) -> GeoArray: ... + +@overload +def line_locate_point( + line: LineString | MultiLineString | GeometryCollection | None, other: Point | None, normalized: bool = False, **kwargs +) -> np.float64: ... +@overload +def line_locate_point( + line: LineString | MultiLineString | GeometryCollection | None, other: OptGeoArrayLikeSeq, normalized: bool = False, **kwargs +) -> NDArray[np.float64]: ... +@overload +def line_locate_point( + line: OptGeoArrayLikeSeq, other: OptGeoArrayLike, normalized: bool = False, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def line_merge(line: None, directed: bool = False, **kwargs) -> None: ... +@overload +def line_merge(line: Geometry, directed: bool = False, **kwargs) -> LineString | MultiLineString | GeometryCollection: ... +@overload +def line_merge(line: OptGeoArrayLikeSeq, directed: bool = False, **kwargs) -> GeoArray: ... + +@overload +def shared_paths(a: LineString | MultiLineString | None, b: None, **kwargs) -> None: ... +@overload +def shared_paths(a: None, b: LineString | MultiLineString | None, **kwargs) -> None: ... +@overload +def shared_paths( + a: LineString | MultiLineString, b: LineString | MultiLineString, **kwargs +) -> GeometryCollection[MultiLineString]: ... +@overload +def shared_paths(a: LineString | MultiLineString | None, b: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... +@overload +def shared_paths(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> GeoArray: ... + +@overload +def shortest_line(a: Geometry | None, b: None, **kwargs) -> None: ... +@overload +def shortest_line(a: None, b: Geometry | None, **kwargs) -> None: ... +@overload +def shortest_line(a: Geometry, b: Geometry, **kwargs) -> LineString: ... +@overload +def shortest_line(a: Geometry | None, b: OptGeoArrayLikeSeq, **kwargs) -> GeoArray: ... +@overload +def shortest_line(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> GeoArray: ... diff --git a/stubs/shapely/shapely/measurement.pyi b/stubs/shapely/shapely/measurement.pyi new file mode 100644 index 000000000000..b0291b92f633 --- /dev/null +++ b/stubs/shapely/shapely/measurement.pyi @@ -0,0 +1,75 @@ +from typing import overload + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, OptGeoArrayLike, OptGeoArrayLikeSeq +from .lib import Geometry + +__all__ = [ + "area", + "bounds", + "distance", + "frechet_distance", + "hausdorff_distance", + "length", + "minimum_bounding_radius", + "minimum_clearance", + "total_bounds", +] + +@overload +def area(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def area(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def distance(a: Geometry | None, b: Geometry | None, **kwargs) -> np.float64: ... +@overload +def distance(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... +@overload +def distance(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +def bounds(geometry: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... +def total_bounds(geometry: OptGeoArrayLike, **kwargs) -> NDArray[np.float64]: ... + +@overload +def length(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def length(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def hausdorff_distance(a: Geometry | None, b: Geometry | None, densify: float | None = None, **kwargs) -> np.float64: ... +@overload +def hausdorff_distance(a: OptGeoArrayLike, b: OptGeoArrayLike, densify: ArrayLikeSeq[float], **kwargs) -> NDArray[np.float64]: ... +@overload +def hausdorff_distance( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... +@overload +def hausdorff_distance( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def frechet_distance(a: Geometry | None, b: Geometry | None, densify: float | None = None, **kwargs) -> np.float64: ... +@overload +def frechet_distance(a: OptGeoArrayLike, b: OptGeoArrayLike, densify: ArrayLikeSeq[float], **kwargs) -> NDArray[np.float64]: ... +@overload +def frechet_distance( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... +@overload +def frechet_distance( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, densify: ArrayLike[float] | None = None, **kwargs +) -> NDArray[np.float64]: ... + +@overload +def minimum_clearance(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def minimum_clearance(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... + +@overload +def minimum_bounding_radius(geometry: Geometry | None, **kwargs) -> np.float64: ... +@overload +def minimum_bounding_radius(geometry: OptGeoArrayLikeSeq, **kwargs) -> NDArray[np.float64]: ... diff --git a/stubs/shapely/shapely/ops.pyi b/stubs/shapely/shapely/ops.pyi new file mode 100644 index 000000000000..206f91861b3e --- /dev/null +++ b/stubs/shapely/shapely/ops.pyi @@ -0,0 +1,104 @@ +from collections.abc import Callable, Iterable +from typing import Any, Literal, overload + +from ._typing import GeoT, OptGeoArrayLike, SupportsGeoInterface +from .algorithms.polylabel import polylabel as polylabel +from .geometry import GeometryCollection, LineString, MultiLineString, Point, Polygon +from .geometry.base import BaseGeometry, BaseMultipartGeometry, GeometrySequence +from .geometry.linestring import _ConvertibleToLineString +from .lib import Geometry + +__all__ = [ + "clip_by_rect", + "linemerge", + "nearest_points", + "operator", + "orient", + "polygonize", + "polygonize_full", + "shared_paths", + "snap", + "split", + "substring", + "transform", + "triangulate", + "unary_union", + "validate", + "voronoi_diagram", +] + +class CollectionOperator: + @overload + def shapeup(self, ob: GeoT) -> GeoT: ... # type: ignore[overload-overlap] + @overload + def shapeup(self, ob: dict[str, Any] | SupportsGeoInterface) -> BaseGeometry: ... # type: ignore[overload-overlap] + @overload + def shapeup(self, ob: _ConvertibleToLineString) -> LineString: ... + + def polygonize( + self, lines: OptGeoArrayLike | Iterable[_ConvertibleToLineString | None] + ) -> GeometrySequence[GeometryCollection[Polygon]]: ... + def polygonize_full( + self, lines: OptGeoArrayLike | Iterable[_ConvertibleToLineString | None] + ) -> tuple[ + GeometryCollection[Polygon], GeometryCollection[LineString], GeometryCollection[LineString], GeometryCollection[Polygon] + ]: ... + def linemerge( + self, lines: MultiLineString | BaseMultipartGeometry | Iterable[_ConvertibleToLineString], directed: bool = False + ) -> LineString | MultiLineString: ... + def unary_union(self, geoms: OptGeoArrayLike) -> BaseGeometry: ... + +operator: CollectionOperator +polygonize = operator.polygonize +polygonize_full = operator.polygonize_full +linemerge = operator.linemerge +unary_union = operator.unary_union + +# This is also an alias to operator method but we want to mark it as deprecated +@overload # edges false +def triangulate(geom: Geometry, tolerance: float = 0.0, edges: Literal[False] = False) -> list[Polygon]: ... +@overload # edges true (keyword) +def triangulate(geom: Geometry, tolerance: float = 0.0, *, edges: Literal[True]) -> list[LineString]: ... +@overload # edges true (positional) +def triangulate(geom: Geometry, tolerance: float, edges: Literal[True]) -> list[LineString]: ... +@overload # fallback +def triangulate(geom: Geometry, tolerance: float = 0.0, edges: bool = False) -> list[Polygon] | list[LineString]: ... + +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, edges: Literal[False] = False +) -> GeometryCollection[Polygon]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None, tolerance: float, edges: Literal[True] +) -> GeometryCollection[LineString | MultiLineString]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, *, edges: Literal[True] +) -> GeometryCollection[LineString | MultiLineString]: ... +@overload +def voronoi_diagram( + geom: Geometry, envelope: Geometry | None = None, tolerance: float = 0.0, edges: bool = False +) -> GeometryCollection[Polygon | LineString | MultiLineString]: ... + +@overload +def validate(geom: None) -> None: ... +@overload +def validate(geom: Geometry) -> str: ... +@overload +def validate(geom: Geometry | None) -> str | None: ... + +def transform(func: Callable[[float, float, float | None], tuple[float, ...]], geom: GeoT) -> GeoT: ... +def nearest_points(g1: Geometry, g2: Geometry) -> tuple[Point, Point]: ... +def snap(g1: GeoT, g2: Geometry, tolerance: float) -> GeoT: ... +def shared_paths(g1: LineString, g2: LineString) -> GeometryCollection[MultiLineString]: ... + +class SplitOp: + @staticmethod + def split(geom: Geometry, splitter: Geometry) -> GeometryCollection: ... + +split = SplitOp.split + +def substring(geom: LineString, start_dist: float, end_dist: float, normalized: bool = False) -> Point | LineString: ... +def clip_by_rect(geom: Geometry, xmin: float, ymin: float, xmax: float, ymax: float) -> BaseGeometry: ... +def orient(geom: GeoT, sign: float = 1.0) -> GeoT: ... diff --git a/stubs/shapely/shapely/plotting.pyi b/stubs/shapely/shapely/plotting.pyi new file mode 100644 index 000000000000..5afa968029c4 --- /dev/null +++ b/stubs/shapely/shapely/plotting.pyi @@ -0,0 +1,79 @@ +from typing import Any, Literal, overload + +from matplotlib.axes import Axes # type: ignore[import-not-found] +from matplotlib.lines import Line2D # type: ignore[import-not-found] +from matplotlib.patches import PathPatch # type: ignore[import-not-found] +from matplotlib.typing import ColorType # type: ignore[import-not-found] + +from .geometry import LinearRing, LineString, MultiLineString, MultiPolygon, Polygon +from .lib import Geometry + +def patch_from_polygon(polygon: Polygon | MultiPolygon, **kwargs: Any) -> PathPatch: ... + +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None = None, + add_points: Literal[True] = True, + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> tuple[PathPatch, Line2D]: ... +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None = None, + *, + add_points: Literal[False], + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> PathPatch: ... +@overload +def plot_polygon( + polygon: Polygon | MultiPolygon, + ax: Axes | None, + add_points: Literal[False], + color: ColorType | None = None, + facecolor: ColorType | None = None, + edgecolor: ColorType | None = None, + linewidth: float | None = None, + **kwargs: Any, +) -> PathPatch: ... + +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None = None, + add_points: Literal[True] = True, + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> tuple[PathPatch, Line2D]: ... +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None = None, + *, + add_points: Literal[False], + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> PathPatch: ... +@overload +def plot_line( + line: LineString | LinearRing | MultiLineString, + ax: Axes | None, + add_points: Literal[False], + color: ColorType | None = None, + linewidth: float = 2, + **kwargs: Any, +) -> PathPatch: ... + +def plot_points( + geom: Geometry, ax: Axes | None = None, color: ColorType | None = None, marker: str = "o", **kwargs: Any +) -> Line2D: ... diff --git a/stubs/shapely/shapely/predicates.pyi b/stubs/shapely/shapely/predicates.pyi new file mode 100644 index 000000000000..03e2a2fd4b50 --- /dev/null +++ b/stubs/shapely/shapely/predicates.pyi @@ -0,0 +1,303 @@ +from typing import Any, Literal, TypeGuard, overload +from typing_extensions import Unpack + +import numpy as np +from numpy.typing import NDArray + +from ._typing import ArrayLike, ArrayLikeSeq, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = [ + "contains", + "contains_properly", + "contains_xy", + "covered_by", + "covers", + "crosses", + "disjoint", + "dwithin", + "equals", + "equals_exact", + "equals_identical", + "has_m", + "has_z", + "intersects", + "intersects_xy", + "is_ccw", + "is_closed", + "is_empty", + "is_geometry", + "is_missing", + "is_prepared", + "is_ring", + "is_simple", + "is_valid", + "is_valid_input", + "is_valid_reason", + "overlaps", + "relate", + "relate_pattern", + "touches", + "within", +] + +@overload +def has_z(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def has_z(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def has_m(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def has_m(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_ccw(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_ccw(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_closed(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_closed(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_empty(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_empty(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_geometry(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... # type: ignore[overload-overlap] +@overload +def is_geometry(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[False]]: ... +@overload +def is_geometry(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_geometry(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[BaseGeometry]: ... + +@overload +def is_missing(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[False]]: ... # type: ignore[overload-overlap] +@overload +def is_missing(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... +@overload +def is_missing(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_missing(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[None]: ... + +@overload +def is_prepared(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_prepared(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid_input(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_[Literal[True]]: ... # type: ignore[overload-overlap] +@overload +def is_valid_input(geometry: ArrayLikeSeq[Any], **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... # type: ignore[overload-overlap] +@overload +def is_valid_input(geometry: object, **kwargs: Unpack[UFuncKwargs]) -> TypeGuard[BaseGeometry | None]: ... + +@overload +def is_ring(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_ring(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_simple(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_simple(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid(geometry: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def is_valid(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def is_valid_reason(geometry: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def is_valid_reason(geometry: Geometry, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def is_valid_reason(geometry: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... + +@overload +def crosses(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def crosses(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def crosses(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def contains(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains_properly(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains_properly(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def contains_properly(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def covered_by(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def covered_by(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def covered_by(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def covers(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def covers(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def covers(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def disjoint(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def disjoint(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def disjoint(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def equals(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def equals(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def equals(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def intersects(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def intersects(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def intersects(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def overlaps(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def overlaps(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def overlaps(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def touches(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def touches(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def touches(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def within(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def within(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def within(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def equals_exact( + a: Geometry | None, b: Geometry | None, tolerance: float = 0.0, *, normalize: bool = False, **kwargs: Unpack[UFuncKwargs] +) -> np.bool_: ... +@overload +def equals_exact( + a: OptGeoArrayLike, + b: OptGeoArrayLike, + tolerance: ArrayLikeSeq[float], + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... +@overload +def equals_exact( + a: OptGeoArrayLikeSeq, + b: OptGeoArrayLike, + tolerance: ArrayLike[float] = 0.0, + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... +@overload +def equals_exact( + a: OptGeoArrayLike, + b: OptGeoArrayLikeSeq, + tolerance: ArrayLike[float] = 0.0, + *, + normalize: bool = False, + **kwargs: Unpack[UFuncKwargs], +) -> NDArray[np.bool_]: ... + +@overload +def equals_identical(a: Geometry | None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def equals_identical(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def equals_identical(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def relate(a: Geometry | None, b: None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def relate(a: None, b: Geometry | None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def relate(a: Geometry, b: Geometry, **kwargs: Unpack[UFuncKwargs]) -> str: ... +@overload +def relate(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... +@overload +def relate(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.object_]: ... + +@overload +def relate_pattern(a: Geometry | None, b: Geometry | None, pattern: str, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def relate_pattern( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, pattern: str, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def relate_pattern( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, pattern: str, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... + +@overload +def dwithin(a: Geometry | None, b: Geometry | None, distance: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def dwithin(a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, distance: float, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... +@overload +def dwithin(a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, distance: float, **kwargs: Unpack[UFuncKwargs]) -> NDArray[np.bool_]: ... + +@overload +def contains_xy(geom: Geometry | None, x: float, y: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def contains_xy( + geom: OptGeoArrayLike, x: ArrayLikeSeq[float], y: None = None, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: Geometry | None, x: ArrayLike[float], y: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: Geometry | None, x: ArrayLikeSeq[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def contains_xy( + geom: OptGeoArrayLikeSeq, x: ArrayLike[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... + +@overload +def intersects_xy(geom: Geometry | None, x: float, y: float, **kwargs: Unpack[UFuncKwargs]) -> np.bool_: ... +@overload +def intersects_xy( + geom: OptGeoArrayLike, x: ArrayLikeSeq[float], y: None = None, **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: Geometry | None, x: ArrayLike[float], y: ArrayLikeSeq[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: Geometry | None, x: ArrayLikeSeq[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... +@overload +def intersects_xy( + geom: OptGeoArrayLikeSeq, x: ArrayLike[float], y: ArrayLike[float], **kwargs: Unpack[UFuncKwargs] +) -> NDArray[np.bool_]: ... diff --git a/stubs/shapely/shapely/prepared.pyi b/stubs/shapely/shapely/prepared.pyi new file mode 100644 index 000000000000..e89026dc3d36 --- /dev/null +++ b/stubs/shapely/shapely/prepared.pyi @@ -0,0 +1,20 @@ +from typing import Generic, Literal + +from ._typing import GeoT +from .lib import Geometry + +class PreparedGeometry(Generic[GeoT]): + context: GeoT + prepared: Literal[True] + def __init__(self, context: GeoT | PreparedGeometry[GeoT]) -> None: ... + def contains(self, other: Geometry | None) -> bool: ... + def contains_properly(self, other: Geometry | None) -> bool: ... + def covers(self, other: Geometry | None) -> bool: ... + def crosses(self, other: Geometry | None) -> bool: ... + def disjoint(self, other: Geometry | None) -> bool: ... + def intersects(self, other: Geometry | None) -> bool: ... + def overlaps(self, other: Geometry | None) -> bool: ... + def touches(self, other: Geometry | None) -> bool: ... + def within(self, other: Geometry | None) -> bool: ... + +def prep(ob: GeoT | PreparedGeometry[GeoT]) -> PreparedGeometry[GeoT]: ... diff --git a/stubs/shapely/shapely/set_operations.pyi b/stubs/shapely/shapely/set_operations.pyi new file mode 100644 index 000000000000..f1972a624d7f --- /dev/null +++ b/stubs/shapely/shapely/set_operations.pyi @@ -0,0 +1,137 @@ +from typing import overload +from typing_extensions import Unpack, deprecated + +from ._typing import GeoArray, OptGeoArrayLike, OptGeoArrayLikeSeq, UFuncKwargs +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = [ + "coverage_union", + "coverage_union_all", + "difference", + "disjoint_subset_union", + "disjoint_subset_union_all", + "intersection", + "intersection_all", + "symmetric_difference", + "symmetric_difference_all", + "unary_union", + "union", + "union_all", +] + +@overload +def difference(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def difference(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def difference(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def difference( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def difference( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def intersection(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def intersection(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def intersection(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def intersection( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def intersection( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def intersection_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def intersection_all(geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +@overload +def symmetric_difference( + a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def symmetric_difference(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def symmetric_difference(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def symmetric_difference( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def symmetric_difference( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +@deprecated("symmetric_difference_all behaves incorrectly and will be removed in a future version.") +def symmetric_difference_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +@deprecated("symmetric_difference_all behaves incorrectly and will be removed in a future version.") +def symmetric_difference_all( + geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +@overload +def union(a: Geometry, b: Geometry, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def union(a: None, b: Geometry | None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def union(a: Geometry | None, b: None, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs]) -> None: ... +@overload +def union( + a: OptGeoArrayLikeSeq, b: OptGeoArrayLike, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... +@overload +def union( + a: OptGeoArrayLike, b: OptGeoArrayLikeSeq, grid_size: float | None = None, **kwargs: Unpack[UFuncKwargs] +) -> GeoArray: ... + +@overload +def union_all( + geometries: OptGeoArrayLike, grid_size: float | None = None, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def union_all( + geometries: OptGeoArrayLikeSeq, grid_size: float | None = None, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... +@overload +def union_all( + geometries: OptGeoArrayLikeSeq, grid_size: float | None, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +unary_union = union_all + +@overload +def coverage_union( + a: OptGeoArrayLike, b: OptGeoArrayLike, *, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def coverage_union( + a: OptGeoArrayLike, b: OptGeoArrayLike, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... + +@overload +def coverage_union_all(geometries: OptGeoArrayLike, axis: None = None, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry: ... +@overload +def coverage_union_all(geometries: OptGeoArrayLikeSeq, axis: int, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +def disjoint_subset_union(a: OptGeoArrayLike, b: OptGeoArrayLike, **kwargs: Unpack[UFuncKwargs]) -> BaseGeometry | GeoArray: ... + +@overload +def disjoint_subset_union_all( + geometries: OptGeoArrayLike, *, axis: None = None, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry: ... +@overload +def disjoint_subset_union_all( + geometries: OptGeoArrayLikeSeq, *, axis: int, **kwargs: Unpack[UFuncKwargs] +) -> BaseGeometry | GeoArray: ... diff --git a/stubs/shapely/shapely/speedups.pyi b/stubs/shapely/shapely/speedups.pyi new file mode 100644 index 000000000000..c2b505f068d9 --- /dev/null +++ b/stubs/shapely/shapely/speedups.pyi @@ -0,0 +1,12 @@ +from typing import Final +from typing_extensions import deprecated + +__all__ = ["available", "enable", "disable", "enabled"] + +available: Final = True +enabled: Final = True + +@deprecated("Function `enable` is deprecated and no longer has any effect. Speedups are always available.") +def enable() -> None: ... +@deprecated("Function `disable` is deprecated and no longer has any effect. Speedups are always available.") +def disable() -> None: ... diff --git a/stubs/shapely/shapely/strtree.pyi b/stubs/shapely/shapely/strtree.pyi new file mode 100644 index 000000000000..c9728d0f687c --- /dev/null +++ b/stubs/shapely/shapely/strtree.pyi @@ -0,0 +1,84 @@ +from typing import Any, Literal, SupportsIndex, TypeAlias, overload + +import numpy as np +from numpy.typing import NDArray + +from ._enum import ParamEnum +from ._typing import ArrayLike, GeoArray, GeoArrayLikeSeq, OptGeoArrayLike +from .lib import Geometry + +__all__ = ["STRtree"] + +_BinaryPredicate: TypeAlias = Literal[ + "intersects", "within", "contains", "overlaps", "crosses", "touches", "covers", "covered_by", "contains_properly" +] + +class BinaryPredicate(ParamEnum): + intersects = 1 + within = 2 + contains = 3 + overlaps = 4 + crosses = 5 + touches = 6 + covers = 7 + covered_by = 8 + contains_properly = 9 + +class STRtree: + def __init__(self, geoms: GeoArrayLikeSeq, node_capacity: SupportsIndex = 10) -> None: ... + def __len__(self) -> int: ... + @property + def geometries(self) -> GeoArray: ... + + @overload + def query( + self, geometry: OptGeoArrayLike, predicate: Literal["dwithin"], distance: ArrayLike[float] + ) -> NDArray[np.int64]: ... + @overload + def query( + self, geometry: OptGeoArrayLike, predicate: _BinaryPredicate | None = None, distance: object = None + ) -> NDArray[np.int64]: ... + + # nearest may return `None` if the tree is empty, use the "Any trick" + @overload + def nearest(self, geometry: Geometry) -> np.int64 | Any: ... + @overload + def nearest(self, geometry: GeoArrayLikeSeq) -> NDArray[np.int64] | Any: ... + + @overload # return_distance=False + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + return_distance: Literal[False] = False, + exclusive: bool = False, + all_matches: bool = True, + ) -> NDArray[np.int64]: ... + @overload # return_distance=True keyword + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + *, + return_distance: Literal[True], + exclusive: bool = False, + all_matches: bool = True, + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + @overload # return_distance=True positional + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None, + return_distance: Literal[True], + exclusive: bool = False, + all_matches: bool = True, + ) -> tuple[NDArray[np.int64], NDArray[np.float64]]: ... + @overload # return_distance=bool fallback + def query_nearest( + self, + geometry: OptGeoArrayLike, + max_distance: float | None = None, + return_distance: bool = False, + exclusive: bool = False, + all_matches: bool = True, + ) -> NDArray[np.int64] | tuple[NDArray[np.int64], NDArray[np.float64]]: ... diff --git a/stubs/shapely/shapely/testing.pyi b/stubs/shapely/shapely/testing.pyi new file mode 100644 index 000000000000..1acff3f0a071 --- /dev/null +++ b/stubs/shapely/shapely/testing.pyi @@ -0,0 +1,14 @@ +from ._typing import ArrayLike, OptGeoArrayLike + +__all__ = ["assert_geometries_equal"] + +def assert_geometries_equal( + x: OptGeoArrayLike, + y: OptGeoArrayLike, + tolerance: ArrayLike[float] = 1e-7, + equal_none: bool = True, + equal_nan: bool = True, + normalize: bool = False, + err_msg: str = "", + verbose: bool = True, +) -> None: ... diff --git a/stubs/shapely/shapely/validation.pyi b/stubs/shapely/shapely/validation.pyi new file mode 100644 index 000000000000..579199d6dd75 --- /dev/null +++ b/stubs/shapely/shapely/validation.pyi @@ -0,0 +1,7 @@ +from .geometry.base import BaseGeometry +from .lib import Geometry + +__all__ = ["explain_validity", "make_valid"] + +def explain_validity(ob: Geometry) -> str: ... +def make_valid(ob: Geometry) -> BaseGeometry: ... diff --git a/stubs/shapely/shapely/vectorized/__init__.pyi b/stubs/shapely/shapely/vectorized/__init__.pyi new file mode 100644 index 000000000000..c7b42e6c5e0a --- /dev/null +++ b/stubs/shapely/shapely/vectorized/__init__.pyi @@ -0,0 +1,47 @@ +from typing import overload +from typing_extensions import deprecated + +import numpy as np +from numpy.typing import NDArray + +from .._typing import ArrayLike, ArrayLikeSeq +from ..lib import Geometry +from ..prepared import PreparedGeometry + +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains(geometry: Geometry | PreparedGeometry[Geometry], x: float, y: float) -> np.bool_: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLikeSeq[float], y: ArrayLike[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLikeSeq[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.contains_xy' instead (available since shapely 2.0.0).") +def contains( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLike[float] +) -> np.bool_ | NDArray[np.bool_]: ... + +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches(geometry: Geometry | PreparedGeometry[Geometry], x: float, y: float) -> np.bool_: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLikeSeq[float], y: ArrayLike[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLikeSeq[float] +) -> NDArray[np.bool_]: ... +@overload +@deprecated("Use 'shapely.intersects_xy' instead (available since shapely 2.0.0).") +def touches( + geometry: Geometry | PreparedGeometry[Geometry], x: ArrayLike[float], y: ArrayLike[float] +) -> np.bool_ | NDArray[np.bool_]: ... diff --git a/stubs/shapely/shapely/wkb.pyi b/stubs/shapely/shapely/wkb.pyi new file mode 100644 index 000000000000..9a9adffe2884 --- /dev/null +++ b/stubs/shapely/shapely/wkb.pyi @@ -0,0 +1,18 @@ +from typing import Literal, overload + +from ._typing import SupportsRead, SupportsWrite +from .geometry.base import BaseGeometry +from .lib import Geometry + +def loads(data: str | bytes, hex: bool = False) -> BaseGeometry: ... +def load(fp: SupportsRead[str] | SupportsRead[bytes], hex: bool = False) -> BaseGeometry: ... + +@overload +def dumps(ob: Geometry, hex: Literal[False] = False, srid: int | None = None, **kw) -> bytes: ... +@overload +def dumps(ob: Geometry, hex: Literal[True], srid: int | None = None, **kw) -> str: ... + +@overload +def dump(ob: Geometry, fp: SupportsWrite[bytes], hex: Literal[False] = False, *, srid: int | None = None, **kw) -> None: ... +@overload +def dump(ob: Geometry, fp: SupportsWrite[str], hex: Literal[True], *, srid: int | None = None, **kw) -> None: ... diff --git a/stubs/shapely/shapely/wkt.pyi b/stubs/shapely/shapely/wkt.pyi new file mode 100644 index 000000000000..cb56d4f386b6 --- /dev/null +++ b/stubs/shapely/shapely/wkt.pyi @@ -0,0 +1,8 @@ +from ._typing import SupportsRead, SupportsWrite +from .geometry.base import BaseGeometry +from .lib import Geometry + +def loads(data: str) -> BaseGeometry: ... +def load(fp: SupportsRead[str]) -> BaseGeometry: ... +def dumps(ob: Geometry, trim: bool = False, rounding_precision: int = -1, **kw) -> str: ... +def dump(ob: Geometry, fp: SupportsWrite[str], *, trim: bool = False, rounding_precision: int = -1, **kw) -> None: ... diff --git a/stubs/simple-websocket/METADATA.toml b/stubs/simple-websocket/METADATA.toml new file mode 100644 index 000000000000..85219da88908 --- /dev/null +++ b/stubs/simple-websocket/METADATA.toml @@ -0,0 +1,3 @@ +version = "1.1.*" +upstream-repository = "https://github.com/miguelgrinberg/simple-websocket" +dependencies = ["wsproto"] diff --git a/stubs/simple-websocket/simple_websocket/__init__.pyi b/stubs/simple-websocket/simple_websocket/__init__.pyi new file mode 100644 index 000000000000..d3da863383ca --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/__init__.pyi @@ -0,0 +1,3 @@ +from .aiows import AioClient as AioClient, AioServer as AioServer +from .errors import ConnectionClosed as ConnectionClosed, ConnectionError as ConnectionError +from .ws import Client as Client, Server as Server diff --git a/stubs/simple-websocket/simple_websocket/aiows.pyi b/stubs/simple-websocket/simple_websocket/aiows.pyi new file mode 100644 index 000000000000..066a243cb78e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/aiows.pyi @@ -0,0 +1,130 @@ +import asyncio +import socket +from _typeshed import Incomplete, Unused +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Awaitable, Callable +from ssl import SSLContext +from typing import Any, Literal, TypedDict, type_check_only + +from wsproto import ConnectionType, WSConnection +from wsproto.events import Request +from wsproto.frame_protocol import CloseReason + +from .asgi import WebSocketASGI, _SocketDataBase, _SocketDataBytes, _SocketDataProtocol, _SocketDataStr + +class AioBase: + subprotocol: str | None + connection_type: ConnectionType + receive_bytes: int + ping_interval: float | None + max_message_size: int | None + pong_received: bool + input_buffer: list[bytes | str] + incoming_message: bytes | str | None + incoming_message_len: int + connected: bool + is_server: bool + close_reason: CloseReason + close_message: str + rsock: asyncio.StreamReader + wsock: asyncio.StreamWriter + event: asyncio.Event + ws: WSConnection | None + task: asyncio.Task[None] + def __init__( + self, + connection_type: ConnectionType | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> None: ... + async def connect(self) -> None: ... + async def handshake(self) -> None: ... + # data can be antyhing. a special case is made for `bytes`, anything else is converted to `str`. + async def send(self, data: bytes | Any) -> None: ... + async def receive(self, timeout: float | None = None) -> bytes | str | None: ... + async def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +@type_check_only +class _AioServerRequest(TypedDict): + # this is `aiohttp.web.Request` + aiohttp: Incomplete + sock: None + headers: None + +class AioServer(AioBase): + request: _AioServerRequest + headers: dict[str, Any] + subprotocols: list[str] + is_server: Literal[True] + mode: str + connected: bool + def __init__( + self, + request: _AioServerRequest, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> None: ... + @classmethod + async def accept( + cls, + # this is `aiohttp.web.Request` + aiohttp=None, + asgi: ( + tuple[ + WSGIEnvironment, + Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + ] + | None + ) = None, + sock: socket.socket | None = None, + headers: dict[str, Any] | None = None, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ) -> WebSocketASGI | AioServer: ... + async def handshake(self) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class AioClient(AioBase): + url: str + ssl_context: SSLContext | None + is_secure: bool + host: str + port: int + path: str + subprotocols: list[str] + extra_headeers: list[tuple[bytes, bytes]] + subprotocol: str | None + connected: bool + def __init__( + self, + url: str, + subprotocols: list[str] | None = None, + headers: dict[str, Any] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + ) -> None: ... + # the source code itself has this override + @classmethod + async def connect( # type: ignore[override] + cls, + url: str, + subprotocols: list[str] | None = None, + headers: dict[str, Any] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: Unused = None, + event_class: Unused = None, + ) -> AioClient: ... + async def handshake(self) -> None: ... + async def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/asgi.pyi b/stubs/simple-websocket/simple_websocket/asgi.pyi new file mode 100644 index 000000000000..92e802188c5e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/asgi.pyi @@ -0,0 +1,44 @@ +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Awaitable, Callable +from typing import TypedDict, type_check_only + +@type_check_only +class _SocketDataBase(TypedDict): + type: str + +@type_check_only +class _SocketDataProtocol(_SocketDataBase): + subprotocol: str | None + +@type_check_only +class _SocketDataStr(_SocketDataBase): + text: str + +@type_check_only +class _SocketDataBytes(_SocketDataBase): + bytes: bytes + +class WebSocketASGI: + subprotocols: list[str] + subprotocol: str + connected: bool + # this is set in `close` to `False` + conncted: bool + def __init__( + self, + scope: WSGIEnvironment, + receive: Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + send: Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + subprotocols: list[str] | None = None, + ) -> None: ... + @classmethod + async def accept( + cls, + scope: WSGIEnvironment, + receive: Callable[[], Awaitable[_SocketDataBytes | _SocketDataStr]], + send: Callable[[_SocketDataBase | _SocketDataProtocol | _SocketDataBytes | _SocketDataStr], Awaitable[None]], + subprotocols: list[str] | None = None, + ) -> WebSocketASGI: ... + async def receive(self) -> bytes | str: ... + async def send(self, data: bytes | str) -> None: ... + async def close(self) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/errors.pyi b/stubs/simple-websocket/simple_websocket/errors.pyi new file mode 100644 index 000000000000..88e25065121e --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/errors.pyi @@ -0,0 +1,12 @@ +from wsproto.frame_protocol import CloseReason + +class SimpleWebsocketError(RuntimeError): ... + +class ConnectionError(SimpleWebsocketError): + status_code: int | None + def __init__(self, status_code: int | None = None) -> None: ... + +class ConnectionClosed(SimpleWebsocketError): + reason: CloseReason + message: str | None + def __init__(self, reason: CloseReason = ..., message: str | None = None) -> None: ... diff --git a/stubs/simple-websocket/simple_websocket/ws.pyi b/stubs/simple-websocket/simple_websocket/ws.pyi new file mode 100644 index 000000000000..0366967d6d5a --- /dev/null +++ b/stubs/simple-websocket/simple_websocket/ws.pyi @@ -0,0 +1,136 @@ +import socket +import threading +from _typeshed import FileDescriptorLike +from _typeshed.wsgi import WSGIEnvironment +from collections.abc import Callable +from selectors import SelectorKey +from ssl import SSLContext +from typing import Any, Protocol, type_check_only + +from wsproto import ConnectionType, WSConnection +from wsproto.events import Request +from wsproto.frame_protocol import CloseReason + +@type_check_only +class _ThreadClassProtocol(Protocol): + name: str + # this accepts any callable as the target, like `threading.Thread` + def __init__(self, target: Callable[..., Any]) -> None: ... + def start(self) -> None: ... + +@type_check_only +class _EventClassProtocol(Protocol): + def clear(self) -> None: ... + def set(self) -> None: ... + def wait(self, timeout: float | None = None) -> bool: ... + +@type_check_only +class _SelectorClassProtocol(Protocol): + # the signature of `register` here is the same as `selectors._BaseSelectorImpl` from the stdlib + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... + # the signature of `select` here is the same as `selectors.DefaultSelector` from the stdlib + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... + def close(self) -> None: ... + +class Base: + subprotocol: str | None + sock: socket.socket | None + receive_bytes: int + ping_interval: float | None + max_message_size: int | None + pong_received: bool + input_buffer: list[bytes | str] + incoming_message: bytes | str | None + incoming_message_len: int + connected: bool + is_server: bool + close_reason: CloseReason + close_message: str | None + selector_class: type[_SelectorClassProtocol] + event: _EventClassProtocol | threading.Event + ws: WSConnection + thread: _ThreadClassProtocol | threading.Thread + def __init__( + self, + sock: socket.socket | None = None, + connection_type: ConnectionType | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> None: ... + def handshake(self) -> None: ... + # data can be antyhing. a special case is made for `bytes`, anything else is converted to `str`. + def send(self, data: bytes | Any) -> None: ... + def receive(self, timeout: float | None = None) -> bytes | str | None: ... + def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class Server(Base): + environ: WSGIEnvironment + subprotocols: list[str] + mode: str + connected: bool + def __init__( + self, + environ: WSGIEnvironment, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> None: ... + @classmethod + def accept( + cls, + environ: WSGIEnvironment, + subprotocols: list[str] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + selector_class: type[_SelectorClassProtocol] | None = None, + ) -> Server: ... + def handshake(self) -> None: ... + def choose_subprotocol(self, request: Request) -> str | None: ... + +class Client(Base): + host: str + port: int + path: str + subprotocols: list[str] + extra_headeers: list[tuple[bytes, bytes]] + subprotocol: str | None + connected: bool + def __init__( + self, + url: str, + subprotocols: list[str] | None = None, + headers: dict[bytes, bytes] | list[tuple[bytes, bytes]] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + ) -> None: ... + @classmethod + def connect( + cls, + url: str, + subprotocols: list[str] | None = None, + headers: dict[bytes, bytes] | list[tuple[bytes, bytes]] | None = None, + receive_bytes: int = 4096, + ping_interval: float | None = None, + max_message_size: int | None = None, + ssl_context: SSLContext | None = None, + thread_class: type[_ThreadClassProtocol] | None = None, + event_class: type[_EventClassProtocol] | None = None, + ) -> Client: ... + def handshake(self) -> None: ... + def close(self, reason: CloseReason | None = None, message: str | None = None) -> None: ... diff --git a/stubs/simplejson/@tests/stubtest_allowlist.txt b/stubs/simplejson/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ebb5d87976c4 --- /dev/null +++ b/stubs/simplejson/@tests/stubtest_allowlist.txt @@ -0,0 +1,16 @@ +# Speedups (C vs Python inconsistency): +simplejson.scanner.make_scanner +simplejson.scanner.JSONDecodeError.__init__ +simplejson.encoder.c_make_encoder +simplejson.encoder.c_encode_basestring +simplejson.encoder.py_encode_basestring +simplejson.encoder.c_encode_basestring_ascii +simplejson.encoder.py_encode_basestring_ascii + +# Tests are not included: +simplejson.tests.* + +# Internal and compat tools: +simplejson.compat +simplejson.ordered_dict +simplejson.tool diff --git a/stubs/simplejson/@tests/test_cases/check_simplejson.py b/stubs/simplejson/@tests/test_cases/check_simplejson.py new file mode 100644 index 000000000000..c62fd73dad6e --- /dev/null +++ b/stubs/simplejson/@tests/test_cases/check_simplejson.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from typing_extensions import assert_type + +from simplejson import JSONEncoder, dumps + + +class CustomEncoder(JSONEncoder): # eventhough it does not have `extra_kw` arg. + ... + + +# We are only testing `dumps` here, because they are all the same: +dumps([], extra_kw=True) # type: ignore + +# Ok: +assert_type(dumps([], cls=CustomEncoder, extra_kw=True), str) diff --git a/stubs/simplejson/METADATA.toml b/stubs/simplejson/METADATA.toml new file mode 100644 index 000000000000..d88621057572 --- /dev/null +++ b/stubs/simplejson/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.1.*" +upstream-repository = "https://github.com/simplejson/simplejson" diff --git a/stubs/simplejson/simplejson/__init__.pyi b/stubs/simplejson/simplejson/__init__.pyi new file mode 100644 index 000000000000..b89f04f64fdf --- /dev/null +++ b/stubs/simplejson/simplejson/__init__.pyi @@ -0,0 +1,189 @@ +from _typeshed import SupportsRichComparison +from collections import OrderedDict +from collections.abc import Callable +from typing import IO, Any, TypeAlias, TypeVar, overload + +from simplejson.decoder import JSONDecoder as JSONDecoder +from simplejson.encoder import JSONEncoder as JSONEncoder, JSONEncoderForHTML as JSONEncoderForHTML +from simplejson.raw_json import RawJSON as RawJSON +from simplejson.scanner import JSONDecodeError as JSONDecodeError + +_LoadsString: TypeAlias = str | bytes | bytearray +_T = TypeVar("_T") + +@overload +def dumps( + obj: Any, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + *, + cls: type[JSONEncoder], + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + **kw: Any, +) -> str: ... +@overload +def dumps( + obj: Any, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + cls: type[JSONEncoder] | None = None, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, +) -> str: ... + +@overload +def dump( + obj: Any, + fp: IO[str], + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + *, + cls: type[JSONEncoder], + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + **kw: Any, +) -> None: ... +@overload +def dump( + obj: Any, + fp: IO[str], + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + cls: type[JSONEncoder] | None = None, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str | None = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + sort_keys: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, +) -> None: ... + +@overload +def loads( + s: _LoadsString, + encoding: str | None = None, + *, + cls: type[JSONDecoder], + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + **kw: Any, +) -> Any: ... +@overload +def loads( + s: _LoadsString, + encoding: str | None = None, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value +) -> Any: ... + +@overload +def load( + fp: IO[str], + encoding: str | None = None, + *, + cls: type[JSONDecoder], + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + **kw: Any, +) -> Any: ... +@overload +def load( + fp: IO[str], + encoding: str | None = None, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + use_decimal: bool = False, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value +) -> Any: ... + +def simple_first(kv: tuple[_T, object]) -> tuple[bool, _T]: ... + +__all__ = [ + "dump", + "dumps", + "load", + "loads", + "JSONDecoder", + "JSONDecodeError", + "JSONEncoder", + "OrderedDict", + "simple_first", + "RawJSON", +] diff --git a/stubs/simplejson/simplejson/decoder.pyi b/stubs/simplejson/simplejson/decoder.pyi new file mode 100644 index 000000000000..3fc18bc176e5 --- /dev/null +++ b/stubs/simplejson/simplejson/decoder.pyi @@ -0,0 +1,40 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from re import Match +from typing import Any, Literal + +class JSONDecoder: + encoding: str + object_hook: Callable[[dict[Any, Any]], Any] | None + # transforms a list of (key, json_value) pairs to an arbitrary value + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None + parse_float: Callable[[str], Any] | None + parse_int: Callable[[str], Any] | None + parse_constant: Callable[[str], Any] | None + strict: bool + array_hook: Callable[[list[Any]], Any] | None # transforms a JSON value to an arbitrary value + # They have many parameters, it might be better to use Protocol: + parse_object: Callable[..., tuple[Incomplete, int]] + parse_array: Callable[..., tuple[Incomplete, int]] + parse_string: Callable[..., tuple[Incomplete, int]] + memo: dict[Any, Any] + scan_once: Callable[[str, int], tuple[bool, int]] + + def __init__( + self, + encoding: str | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value + ) -> None: ... + def decode(self, s: str, _w: Callable[[str, int], Match[str]] = ..., _PY3: Literal[True] = True) -> Any: ... + def raw_decode( + self, s: str, idx: int = 0, _w: Callable[[str, int], Match[str]] = ..., _PY3: Literal[True] = True + ) -> tuple[Any, int]: ... + +__all__ = ["JSONDecoder"] diff --git a/stubs/simplejson/simplejson/encoder.pyi b/stubs/simplejson/simplejson/encoder.pyi new file mode 100644 index 000000000000..9f82016fe917 --- /dev/null +++ b/stubs/simplejson/simplejson/encoder.pyi @@ -0,0 +1,61 @@ +import re +from _typeshed import SupportsRichComparison +from collections.abc import Callable, Iterator +from typing import Any +from typing_extensions import Never + +ESCAPE: re.Pattern[str] +ESCAPE_ASCII: re.Pattern[str] +HAS_UTF8: re.Pattern[str] +ESCAPE_DCT: dict[str, str] +FLOAT_REPR: Callable[[object], str] + +class JSONEncoder: + item_separator: str + key_separator: str + skipkeys: bool + ensure_ascii: bool + check_circular: bool + allow_nan: bool + sort_keys: bool + indent: str + encoding: str + use_decimal: bool + namedtuple_as_object: bool + tuple_as_array: bool + bigint_as_string: bool + item_sort_key: Callable[[Any], SupportsRichComparison] | None + for_json: bool + ignore_nan: bool + int_as_string_bitcount: int | None + iterable_as_array: bool + + def __init__( + self, + skipkeys: bool = False, + ensure_ascii: bool = True, + check_circular: bool = True, + allow_nan: bool = False, + sort_keys: bool = False, + indent: str | int | None = None, + separators: tuple[str, str] | None = None, + encoding: str = "utf-8", + default: Callable[[Any], Any] | None = None, + use_decimal: bool = True, + namedtuple_as_object: bool = True, + tuple_as_array: bool = True, + bigint_as_string: bool = False, + item_sort_key: Callable[[Any], SupportsRichComparison] | None = None, + for_json: bool = False, + ignore_nan: bool = False, + int_as_string_bitcount: int | None = None, + iterable_as_array: bool = False, + ) -> None: ... + def encode(self, o: Any) -> str: ... + def default(self, o: Any) -> Never: ... + def iterencode(self, o: Any) -> Iterator[str]: ... + +class JSONEncoderForHTML(JSONEncoder): ... + +def encode_basestring(s: str | bytes, /) -> str: ... +def encode_basestring_ascii(s: str | bytes, /) -> str: ... diff --git a/stubs/simplejson/simplejson/errors.pyi b/stubs/simplejson/simplejson/errors.pyi new file mode 100644 index 000000000000..b4b6539c652e --- /dev/null +++ b/stubs/simplejson/simplejson/errors.pyi @@ -0,0 +1,16 @@ +__all__ = ["JSONDecodeError"] + +def linecol(doc: str, pos: int) -> tuple[int, int]: ... +def errmsg(msg: str, doc: str, pos: int, end: int | None = None) -> str: ... + +class JSONDecodeError(ValueError): + msg: str + doc: str + pos: int + end: int | None + lineno: int + colno: int + endlineno: int | None + endcolno: int | None + def __init__(self, msg: str, doc: str, pos: int, end: int | None = None) -> None: ... + def __reduce__(self) -> tuple[JSONDecodeError, tuple[str, str, int, int | None]]: ... diff --git a/stubs/simplejson/simplejson/raw_json.pyi b/stubs/simplejson/simplejson/raw_json.pyi new file mode 100644 index 000000000000..bacd7550aa82 --- /dev/null +++ b/stubs/simplejson/simplejson/raw_json.pyi @@ -0,0 +1,3 @@ +class RawJSON: + encoded_json: str + def __init__(self, encoded_json: str) -> None: ... diff --git a/stubs/simplejson/simplejson/scanner.pyi b/stubs/simplejson/simplejson/scanner.pyi new file mode 100644 index 000000000000..2e7f9fe58eda --- /dev/null +++ b/stubs/simplejson/simplejson/scanner.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable + +from simplejson.decoder import JSONDecoder + +class JSONDecodeError(ValueError): + msg: str + doc: str + pos: int + end: int | None + lineno: int + colno: int + endlineno: int | None + endcolno: int | None + +def make_scanner(context: JSONDecoder) -> Callable[[str, int], tuple[bool, int]]: ... + +__all__ = ["make_scanner", "JSONDecodeError"] diff --git a/stubs/singledispatch/METADATA.toml b/stubs/singledispatch/METADATA.toml new file mode 100644 index 000000000000..9bdcc7abbe8d --- /dev/null +++ b/stubs/singledispatch/METADATA.toml @@ -0,0 +1,2 @@ +version = "4.1.*" +upstream-repository = "https://github.com/jaraco/singledispatch" diff --git a/stubs/singledispatch/singledispatch.pyi b/stubs/singledispatch/singledispatch.pyi new file mode 100644 index 000000000000..62e59c9fe30f --- /dev/null +++ b/stubs/singledispatch/singledispatch.pyi @@ -0,0 +1,38 @@ +from collections.abc import Callable, Mapping +from typing import Any, Generic, TypeVar, overload, type_check_only + +_T = TypeVar("_T") +_S = TypeVar("_S") + +@type_check_only +class _SingleDispatchCallable(Generic[_T]): + registry: Mapping[Any, Callable[..., _T]] + def dispatch(self, cls: Any) -> Callable[..., _T]: ... + + @overload + def register(self, cls: Any) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Any, func: Callable[..., _T]) -> Callable[..., _T]: ... + + def _clear_cache(self) -> None: ... + def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + +def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... + +class singledispatchmethod(Generic[_T]): + dispatcher: _SingleDispatchCallable[_T] + func: Callable[..., _T] + def __init__(self, func: Callable[..., _T]) -> None: ... + @property + def __isabstractmethod__(self) -> bool: ... + + @overload + def register(self, cls: type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... + @overload + def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... + + def __get__(self, obj: _S, cls: type[_S] | None = ...) -> Callable[..., _T]: ... + +__all__ = ["singledispatch", "singledispatchmethod"] diff --git a/stubs/six/@tests/stubtest_allowlist.txt b/stubs/six/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..d1870c38df1e --- /dev/null +++ b/stubs/six/@tests/stubtest_allowlist.txt @@ -0,0 +1,29 @@ +# Problems inherited from the standard library +six.create_bound_method.__closure__ +six.create_bound_method.__code__ +six.create_bound_method.__defaults__ +six.moves.* + +# Implemented using "operator" functions in the implementation +six.get_function_closure +six.get_function_code +six.get_function_defaults +six.get_function_globals +six.get_method_function +six.get_method_self +six.viewitems +six.viewkeys +six.viewvalues +# Should be `byte2int: operator.itemgetter[int]`. But `itemgetter.__call__` returns `Any` +six.byte2int + +# Utils +six.Module_six_moves_urllib +six.Module_six_moves_urllib_error +six.Module_six_moves_urllib_parse +six.Module_six_moves_urllib_request +six.Module_six_moves_urllib_response +six.Module_six_moves_urllib_robotparser + +# Belongs to `django.utils.six` +six.iterlists diff --git a/stubs/six/METADATA.toml b/stubs/six/METADATA.toml new file mode 100644 index 000000000000..bf036333b2b7 --- /dev/null +++ b/stubs/six/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.17.*" +upstream-repository = "https://github.com/benjaminp/six" diff --git a/stubs/six/six/__init__.pyi b/stubs/six/six/__init__.pyi new file mode 100644 index 000000000000..b137922b7482 --- /dev/null +++ b/stubs/six/six/__init__.pyi @@ -0,0 +1,112 @@ +import operator +import types +import unittest +from _typeshed import IdentityFunction, SupportsGetItem, Unused +from builtins import callable as callable, next as next +from collections.abc import Callable, ItemsView, Iterable, Iterator as _Iterator, KeysView, Mapping, ValuesView +from functools import wraps as wraps +from importlib.util import spec_from_loader as spec_from_loader +from io import BytesIO as BytesIO, StringIO as StringIO +from re import Pattern +from typing import Any, AnyStr, Literal, TypeVar, overload +from typing_extensions import Never + +from six import moves as moves + +_T = TypeVar("_T") +_K = TypeVar("_K") +_V = TypeVar("_V") + +__author__: str +__version__: str + +PY2: Literal[False] +PY3: Literal[True] +PY34: Literal[True] + +string_types: tuple[type[str]] +integer_types: tuple[type[int]] +class_types: tuple[type[type]] +text_type = str +binary_type = bytes + +MAXSIZE: int + +def get_unbound_function(unbound: types.FunctionType) -> types.FunctionType: ... + +create_bound_method = types.MethodType + +def create_unbound_method(func: types.FunctionType, cls: type) -> types.FunctionType: ... + +Iterator = object + +def get_method_function(meth: types.MethodType) -> types.FunctionType: ... +def get_method_self(meth: types.MethodType) -> object: ... +def get_function_closure(fun: types.FunctionType) -> tuple[types.CellType, ...] | None: ... +def get_function_code(fun: types.FunctionType) -> types.CodeType: ... +def get_function_defaults(fun: types.FunctionType) -> tuple[Any, ...] | None: ... +def get_function_globals(fun: types.FunctionType) -> dict[str, Any]: ... +def iterkeys(d: Mapping[_K, Any]) -> _Iterator[_K]: ... +def itervalues(d: Mapping[Any, _V]) -> _Iterator[_V]: ... +def iteritems(d: Mapping[_K, _V]) -> _Iterator[tuple[_K, _V]]: ... +def viewkeys(d: Mapping[_K, Any]) -> KeysView[_K]: ... +def viewvalues(d: Mapping[Any, _V]) -> ValuesView[_V]: ... +def viewitems(d: Mapping[_K, _V]) -> ItemsView[_K, _V]: ... +def b(s: str) -> bytes: ... +def u(s: str) -> str: ... + +unichr = chr + +def int2byte(i: int) -> bytes: ... + +# Should be `byte2int: operator.itemgetter[int]`. But `itemgetter.__call__` returns `Any` +def byte2int(obj: SupportsGetItem[int, _T]) -> _T: ... + +indexbytes = operator.getitem +iterbytes = iter + +def assertCountEqual(self: unittest.TestCase, first: Iterable[_T], second: Iterable[_T], msg: str | None = ...) -> None: ... + +@overload +def assertRaisesRegex(self: unittest.TestCase, msg: str | None = ...) -> Any: ... +@overload +def assertRaisesRegex(self: unittest.TestCase, callable_obj: Callable[..., object], *args: Any, **kwargs: Any) -> Any: ... + +def assertRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... +def assertNotRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... + +exec_ = exec + +def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... +def raise_from(value: BaseException | type[BaseException], from_value: BaseException | None) -> Never: ... + +print_ = print + +def with_metaclass(meta: type, *bases: type) -> type: ... +def add_metaclass(metaclass: type) -> IdentityFunction: ... +def ensure_binary(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... +def ensure_str(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> str: ... +def ensure_text(s: bytes | str, encoding: str = "utf-8", errors: str = "strict") -> str: ... +def python_2_unicode_compatible(klass: _T) -> _T: ... + +class _LazyDescr: + name: str + def __init__(self, name: str) -> None: ... + def __get__(self, obj: object, tp: Unused) -> Any: ... + +class MovedModule(_LazyDescr): + mod: str + def __init__(self, name: str, old: str, new: str | None = None) -> None: ... + def __getattr__(self, attr: str) -> Any: ... + +class MovedAttribute(_LazyDescr): + mod: str + attr: str + def __init__( + self, name: str, old_mod: str, new_mod: str, old_attr: str | None = None, new_attr: str | None = None + ) -> None: ... + +def add_move(move: MovedModule | MovedAttribute) -> None: ... +def remove_move(name: str) -> None: ... + +advance_iterator = next diff --git a/stubs/six/six/moves/BaseHTTPServer.pyi b/stubs/six/six/moves/BaseHTTPServer.pyi new file mode 100644 index 000000000000..0e1ad7131458 --- /dev/null +++ b/stubs/six/six/moves/BaseHTTPServer.pyi @@ -0,0 +1 @@ +from http.server import * diff --git a/stubs/six/six/moves/CGIHTTPServer.pyi b/stubs/six/six/moves/CGIHTTPServer.pyi new file mode 100644 index 000000000000..0e1ad7131458 --- /dev/null +++ b/stubs/six/six/moves/CGIHTTPServer.pyi @@ -0,0 +1 @@ +from http.server import * diff --git a/stubs/six/six/moves/SimpleHTTPServer.pyi b/stubs/six/six/moves/SimpleHTTPServer.pyi new file mode 100644 index 000000000000..0e1ad7131458 --- /dev/null +++ b/stubs/six/six/moves/SimpleHTTPServer.pyi @@ -0,0 +1 @@ +from http.server import * diff --git a/stubs/six/six/moves/__init__.pyi b/stubs/six/six/moves/__init__.pyi new file mode 100644 index 000000000000..ae64ae674f03 --- /dev/null +++ b/stubs/six/six/moves/__init__.pyi @@ -0,0 +1,65 @@ +# Stubs for six.moves +# +# Note: Commented out items means they weren't implemented at the time. +# Uncomment them when the modules have been added to the typeshed. +import importlib +import shlex +from builtins import filter as filter, input as input, map as map, range as range, zip as zip +from collections import UserDict as UserDict, UserList as UserList, UserString as UserString +from functools import reduce as reduce +from io import StringIO as StringIO +from itertools import filterfalse as filterfalse, zip_longest as zip_longest +from os import getcwd as getcwd, getcwdb as getcwdb +from sys import intern as intern + +# import tkinter.font as tkinter_font +# import tkinter.messagebox as tkinter_messagebox +# import tkinter.simpledialog as tkinter_tksimpledialog +# import tkinter.dnd as tkinter_dnd +# import tkinter.colorchooser as tkinter_colorchooser +# import tkinter.scrolledtext as tkinter_scrolledtext +# import tkinter.simpledialog as tkinter_simpledialog +# import tkinter.tix as tkinter_tix +# import dbm.gnu as dbm_gnu +from . import ( + BaseHTTPServer as BaseHTTPServer, + CGIHTTPServer as CGIHTTPServer, + SimpleHTTPServer as SimpleHTTPServer, + _dummy_thread as _dummy_thread, + _thread as _thread, + builtins as builtins, + configparser as configparser, + copyreg as copyreg, + cPickle as cPickle, + email_mime_base as email_mime_base, + email_mime_multipart as email_mime_multipart, + email_mime_nonmultipart as email_mime_nonmultipart, + email_mime_text as email_mime_text, + html_entities as html_entities, + html_parser as html_parser, + http_client as http_client, + http_cookiejar as http_cookiejar, + http_cookies as http_cookies, + queue as queue, + reprlib as reprlib, + socketserver as socketserver, + tkinter as tkinter, + tkinter_commondialog as tkinter_commondialog, + tkinter_constants as tkinter_constants, + tkinter_dialog as tkinter_dialog, + tkinter_filedialog as tkinter_filedialog, + tkinter_tkfiledialog as tkinter_tkfiledialog, + tkinter_ttk as tkinter_ttk, + urllib as urllib, + urllib_error as urllib_error, + urllib_parse as urllib_parse, + urllib_robotparser as urllib_robotparser, +) + +# import xmlrpc.client as xmlrpc_client +# import xmlrpc.server as xmlrpc_server + +xrange = range +reload_module = importlib.reload +cStringIO = StringIO +shlex_quote = shlex.quote diff --git a/stubs/six/six/moves/_dummy_thread.pyi b/stubs/six/six/moves/_dummy_thread.pyi new file mode 100644 index 000000000000..25952a61494f --- /dev/null +++ b/stubs/six/six/moves/_dummy_thread.pyi @@ -0,0 +1 @@ +from _thread import * diff --git a/stubs/six/six/moves/_thread.pyi b/stubs/six/six/moves/_thread.pyi new file mode 100644 index 000000000000..25952a61494f --- /dev/null +++ b/stubs/six/six/moves/_thread.pyi @@ -0,0 +1 @@ +from _thread import * diff --git a/stubs/six/six/moves/builtins.pyi b/stubs/six/six/moves/builtins.pyi new file mode 100644 index 000000000000..eee6b75c0554 --- /dev/null +++ b/stubs/six/six/moves/builtins.pyi @@ -0,0 +1,3 @@ +# six explicitly re-exports builtins. Normally this is something we'd want to avoid. +# But this is specifically a compatibility package. +from builtins import * # noqa: UP029 diff --git a/stubs/six/six/moves/cPickle.pyi b/stubs/six/six/moves/cPickle.pyi new file mode 100644 index 000000000000..2b944b59d656 --- /dev/null +++ b/stubs/six/six/moves/cPickle.pyi @@ -0,0 +1 @@ +from pickle import * diff --git a/stubs/six/six/moves/collections_abc.pyi b/stubs/six/six/moves/collections_abc.pyi new file mode 100644 index 000000000000..dba0f1535768 --- /dev/null +++ b/stubs/six/six/moves/collections_abc.pyi @@ -0,0 +1 @@ +from collections.abc import * diff --git a/stubs/six/six/moves/configparser.pyi b/stubs/six/six/moves/configparser.pyi new file mode 100644 index 000000000000..3367dbd19622 --- /dev/null +++ b/stubs/six/six/moves/configparser.pyi @@ -0,0 +1,3 @@ +# Error is not included in __all__ so export it explicitly +from configparser import * +from configparser import Error as Error diff --git a/stubs/six/six/moves/copyreg.pyi b/stubs/six/six/moves/copyreg.pyi new file mode 100644 index 000000000000..1848b74c35a3 --- /dev/null +++ b/stubs/six/six/moves/copyreg.pyi @@ -0,0 +1 @@ +from copyreg import * diff --git a/stubs/six/six/moves/email_mime_base.pyi b/stubs/six/six/moves/email_mime_base.pyi new file mode 100644 index 000000000000..4df155c939d5 --- /dev/null +++ b/stubs/six/six/moves/email_mime_base.pyi @@ -0,0 +1 @@ +from email.mime.base import * diff --git a/stubs/six/six/moves/email_mime_multipart.pyi b/stubs/six/six/moves/email_mime_multipart.pyi new file mode 100644 index 000000000000..4f312412bbc0 --- /dev/null +++ b/stubs/six/six/moves/email_mime_multipart.pyi @@ -0,0 +1 @@ +from email.mime.multipart import * diff --git a/stubs/six/six/moves/email_mime_nonmultipart.pyi b/stubs/six/six/moves/email_mime_nonmultipart.pyi new file mode 100644 index 000000000000..c15c8c0440b5 --- /dev/null +++ b/stubs/six/six/moves/email_mime_nonmultipart.pyi @@ -0,0 +1 @@ +from email.mime.nonmultipart import * diff --git a/stubs/six/six/moves/email_mime_text.pyi b/stubs/six/six/moves/email_mime_text.pyi new file mode 100644 index 000000000000..51e147387fa2 --- /dev/null +++ b/stubs/six/six/moves/email_mime_text.pyi @@ -0,0 +1 @@ +from email.mime.text import * diff --git a/stubs/six/six/moves/html_entities.pyi b/stubs/six/six/moves/html_entities.pyi new file mode 100644 index 000000000000..c1244ddbee45 --- /dev/null +++ b/stubs/six/six/moves/html_entities.pyi @@ -0,0 +1 @@ +from html.entities import * diff --git a/stubs/six/six/moves/html_parser.pyi b/stubs/six/six/moves/html_parser.pyi new file mode 100644 index 000000000000..6db6dd83f35e --- /dev/null +++ b/stubs/six/six/moves/html_parser.pyi @@ -0,0 +1 @@ +from html.parser import * diff --git a/stubs/six/six/moves/http_client.pyi b/stubs/six/six/moves/http_client.pyi new file mode 100644 index 000000000000..ecfce42f02c3 --- /dev/null +++ b/stubs/six/six/moves/http_client.pyi @@ -0,0 +1,61 @@ +# Many definitions are not included in http.client.__all__ +from http.client import * +from http.client import ( + ACCEPTED as ACCEPTED, + BAD_GATEWAY as BAD_GATEWAY, + BAD_REQUEST as BAD_REQUEST, + CONFLICT as CONFLICT, + CONTINUE as CONTINUE, + CREATED as CREATED, + EXPECTATION_FAILED as EXPECTATION_FAILED, + FAILED_DEPENDENCY as FAILED_DEPENDENCY, + FORBIDDEN as FORBIDDEN, + FOUND as FOUND, + GATEWAY_TIMEOUT as GATEWAY_TIMEOUT, + GONE as GONE, + HTTP_PORT as HTTP_PORT, + HTTP_VERSION_NOT_SUPPORTED as HTTP_VERSION_NOT_SUPPORTED, + HTTPS_PORT as HTTPS_PORT, + IM_USED as IM_USED, + INSUFFICIENT_STORAGE as INSUFFICIENT_STORAGE, + INTERNAL_SERVER_ERROR as INTERNAL_SERVER_ERROR, + LENGTH_REQUIRED as LENGTH_REQUIRED, + LOCKED as LOCKED, + METHOD_NOT_ALLOWED as METHOD_NOT_ALLOWED, + MOVED_PERMANENTLY as MOVED_PERMANENTLY, + MULTI_STATUS as MULTI_STATUS, + MULTIPLE_CHOICES as MULTIPLE_CHOICES, + NETWORK_AUTHENTICATION_REQUIRED as NETWORK_AUTHENTICATION_REQUIRED, + NO_CONTENT as NO_CONTENT, + NON_AUTHORITATIVE_INFORMATION as NON_AUTHORITATIVE_INFORMATION, + NOT_ACCEPTABLE as NOT_ACCEPTABLE, + NOT_EXTENDED as NOT_EXTENDED, + NOT_FOUND as NOT_FOUND, + NOT_IMPLEMENTED as NOT_IMPLEMENTED, + NOT_MODIFIED as NOT_MODIFIED, + OK as OK, + PARTIAL_CONTENT as PARTIAL_CONTENT, + PAYMENT_REQUIRED as PAYMENT_REQUIRED, + PRECONDITION_FAILED as PRECONDITION_FAILED, + PRECONDITION_REQUIRED as PRECONDITION_REQUIRED, + PROCESSING as PROCESSING, + PROXY_AUTHENTICATION_REQUIRED as PROXY_AUTHENTICATION_REQUIRED, + REQUEST_ENTITY_TOO_LARGE as REQUEST_ENTITY_TOO_LARGE, + REQUEST_HEADER_FIELDS_TOO_LARGE as REQUEST_HEADER_FIELDS_TOO_LARGE, + REQUEST_TIMEOUT as REQUEST_TIMEOUT, + REQUEST_URI_TOO_LONG as REQUEST_URI_TOO_LONG, + REQUESTED_RANGE_NOT_SATISFIABLE as REQUESTED_RANGE_NOT_SATISFIABLE, + RESET_CONTENT as RESET_CONTENT, + SEE_OTHER as SEE_OTHER, + SERVICE_UNAVAILABLE as SERVICE_UNAVAILABLE, + SWITCHING_PROTOCOLS as SWITCHING_PROTOCOLS, + TEMPORARY_REDIRECT as TEMPORARY_REDIRECT, + TOO_MANY_REQUESTS as TOO_MANY_REQUESTS, + UNAUTHORIZED as UNAUTHORIZED, + UNPROCESSABLE_ENTITY as UNPROCESSABLE_ENTITY, + UNSUPPORTED_MEDIA_TYPE as UNSUPPORTED_MEDIA_TYPE, + UPGRADE_REQUIRED as UPGRADE_REQUIRED, + USE_PROXY as USE_PROXY, + HTTPMessage as HTTPMessage, + parse_headers as parse_headers, +) diff --git a/stubs/six/six/moves/http_cookiejar.pyi b/stubs/six/six/moves/http_cookiejar.pyi new file mode 100644 index 000000000000..88a1aed6cc0f --- /dev/null +++ b/stubs/six/six/moves/http_cookiejar.pyi @@ -0,0 +1 @@ +from http.cookiejar import * diff --git a/stubs/six/six/moves/http_cookies.pyi b/stubs/six/six/moves/http_cookies.pyi new file mode 100644 index 000000000000..1e168c8e7138 --- /dev/null +++ b/stubs/six/six/moves/http_cookies.pyi @@ -0,0 +1,3 @@ +# Morsel is not included in __all__ so export it explicitly +from http.cookies import * +from http.cookies import Morsel as Morsel diff --git a/stubs/six/six/moves/queue.pyi b/stubs/six/six/moves/queue.pyi new file mode 100644 index 000000000000..fe7be53a37ad --- /dev/null +++ b/stubs/six/six/moves/queue.pyi @@ -0,0 +1 @@ +from queue import * diff --git a/stubs/six/six/moves/reprlib.pyi b/stubs/six/six/moves/reprlib.pyi new file mode 100644 index 000000000000..c329846fde0b --- /dev/null +++ b/stubs/six/six/moves/reprlib.pyi @@ -0,0 +1 @@ +from reprlib import * diff --git a/stubs/six/six/moves/socketserver.pyi b/stubs/six/six/moves/socketserver.pyi new file mode 100644 index 000000000000..6101c8bb022b --- /dev/null +++ b/stubs/six/six/moves/socketserver.pyi @@ -0,0 +1 @@ +from socketserver import * diff --git a/stubs/six/six/moves/tkinter.pyi b/stubs/six/six/moves/tkinter.pyi new file mode 100644 index 000000000000..fc4d53a5a0b8 --- /dev/null +++ b/stubs/six/six/moves/tkinter.pyi @@ -0,0 +1 @@ +from tkinter import * diff --git a/stubs/six/six/moves/tkinter_commondialog.pyi b/stubs/six/six/moves/tkinter_commondialog.pyi new file mode 100644 index 000000000000..34eb41961996 --- /dev/null +++ b/stubs/six/six/moves/tkinter_commondialog.pyi @@ -0,0 +1 @@ +from tkinter.commondialog import * diff --git a/stubs/six/six/moves/tkinter_constants.pyi b/stubs/six/six/moves/tkinter_constants.pyi new file mode 100644 index 000000000000..3c04f6d84fa3 --- /dev/null +++ b/stubs/six/six/moves/tkinter_constants.pyi @@ -0,0 +1 @@ +from tkinter.constants import * diff --git a/stubs/six/six/moves/tkinter_dialog.pyi b/stubs/six/six/moves/tkinter_dialog.pyi new file mode 100644 index 000000000000..0da73c27acb8 --- /dev/null +++ b/stubs/six/six/moves/tkinter_dialog.pyi @@ -0,0 +1 @@ +from tkinter.dialog import * diff --git a/stubs/six/six/moves/tkinter_filedialog.pyi b/stubs/six/six/moves/tkinter_filedialog.pyi new file mode 100644 index 000000000000..c4cc7c48b51c --- /dev/null +++ b/stubs/six/six/moves/tkinter_filedialog.pyi @@ -0,0 +1 @@ +from tkinter.filedialog import * diff --git a/stubs/six/six/moves/tkinter_tkfiledialog.pyi b/stubs/six/six/moves/tkinter_tkfiledialog.pyi new file mode 100644 index 000000000000..c4cc7c48b51c --- /dev/null +++ b/stubs/six/six/moves/tkinter_tkfiledialog.pyi @@ -0,0 +1 @@ +from tkinter.filedialog import * diff --git a/stubs/six/six/moves/tkinter_ttk.pyi b/stubs/six/six/moves/tkinter_ttk.pyi new file mode 100644 index 000000000000..14576f61c12c --- /dev/null +++ b/stubs/six/six/moves/tkinter_ttk.pyi @@ -0,0 +1 @@ +from tkinter.ttk import * diff --git a/stubs/six/six/moves/urllib/__init__.pyi b/stubs/six/six/moves/urllib/__init__.pyi new file mode 100644 index 000000000000..fa6dc977937d --- /dev/null +++ b/stubs/six/six/moves/urllib/__init__.pyi @@ -0,0 +1 @@ +from six.moves.urllib import error as error, parse as parse, request as request, response as response, robotparser as robotparser diff --git a/stubs/six/six/moves/urllib/error.pyi b/stubs/six/six/moves/urllib/error.pyi new file mode 100644 index 000000000000..4e10fe2fd42f --- /dev/null +++ b/stubs/six/six/moves/urllib/error.pyi @@ -0,0 +1 @@ +from urllib.error import ContentTooShortError as ContentTooShortError, HTTPError as HTTPError, URLError as URLError diff --git a/stubs/six/six/moves/urllib/parse.pyi b/stubs/six/six/moves/urllib/parse.pyi new file mode 100644 index 000000000000..20adc639d55a --- /dev/null +++ b/stubs/six/six/moves/urllib/parse.pyi @@ -0,0 +1,30 @@ +# Stubs for six.moves.urllib.parse +# +# Note: Commented out items means they weren't implemented at the time. +# Uncomment them when the modules have been added to the typeshed. +# from urllib.parse import splitquery as splitquery +# from urllib.parse import splittag as splittag +# from urllib.parse import splituser as splituser +from urllib.parse import ( + ParseResult as ParseResult, + SplitResult as SplitResult, + parse_qs as parse_qs, + parse_qsl as parse_qsl, + quote as quote, + quote_plus as quote_plus, + unquote as unquote, + unquote_plus as unquote_plus, + unquote_to_bytes as unquote_to_bytes, + urldefrag as urldefrag, + urlencode as urlencode, + urljoin as urljoin, + urlparse as urlparse, + urlsplit as urlsplit, + urlunparse as urlunparse, + urlunsplit as urlunsplit, + uses_fragment as uses_fragment, + uses_netloc as uses_netloc, + uses_params as uses_params, + uses_query as uses_query, + uses_relative as uses_relative, +) diff --git a/stubs/six/six/moves/urllib/request.pyi b/stubs/six/six/moves/urllib/request.pyi new file mode 100644 index 000000000000..69d402c61659 --- /dev/null +++ b/stubs/six/six/moves/urllib/request.pyi @@ -0,0 +1,44 @@ +import sys + +# Stubs for six.moves.urllib.request +# +# Note: Commented out items means they weren't implemented at the time. +# Uncomment them when the modules have been added to the typeshed. +# from urllib.request import proxy_bypass as proxy_bypass +from urllib.request import ( + AbstractBasicAuthHandler as AbstractBasicAuthHandler, + AbstractDigestAuthHandler as AbstractDigestAuthHandler, + BaseHandler as BaseHandler, + CacheFTPHandler as CacheFTPHandler, + FileHandler as FileHandler, + FTPHandler as FTPHandler, + HTTPBasicAuthHandler as HTTPBasicAuthHandler, + HTTPCookieProcessor as HTTPCookieProcessor, + HTTPDefaultErrorHandler as HTTPDefaultErrorHandler, + HTTPDigestAuthHandler as HTTPDigestAuthHandler, + HTTPErrorProcessor as HTTPErrorProcessor, + HTTPHandler as HTTPHandler, + HTTPPasswordMgr as HTTPPasswordMgr, + HTTPPasswordMgrWithDefaultRealm as HTTPPasswordMgrWithDefaultRealm, + HTTPRedirectHandler as HTTPRedirectHandler, + HTTPSHandler as HTTPSHandler, + OpenerDirector as OpenerDirector, + ProxyBasicAuthHandler as ProxyBasicAuthHandler, + ProxyDigestAuthHandler as ProxyDigestAuthHandler, + ProxyHandler as ProxyHandler, + Request as Request, + UnknownHandler as UnknownHandler, + build_opener as build_opener, + getproxies as getproxies, + install_opener as install_opener, + parse_http_list as parse_http_list, + parse_keqv_list as parse_keqv_list, + pathname2url as pathname2url, + url2pathname as url2pathname, + urlcleanup as urlcleanup, + urlopen as urlopen, + urlretrieve as urlretrieve, +) + +if sys.version_info < (3, 14): + from urllib.request import FancyURLopener as FancyURLopener, URLopener as URLopener diff --git a/stubs/six/six/moves/urllib/response.pyi b/stubs/six/six/moves/urllib/response.pyi new file mode 100644 index 000000000000..9f681ea33cad --- /dev/null +++ b/stubs/six/six/moves/urllib/response.pyi @@ -0,0 +1,8 @@ +# Stubs for six.moves.urllib.response +# +# Note: Commented out items means they weren't implemented at the time. +# Uncomment them when the modules have been added to the typeshed. +# from urllib.response import addbase as addbase +# from urllib.response import addclosehook as addclosehook +# from urllib.response import addinfo as addinfo +from urllib.response import addinfourl as addinfourl diff --git a/stubs/six/six/moves/urllib/robotparser.pyi b/stubs/six/six/moves/urllib/robotparser.pyi new file mode 100644 index 000000000000..bccda14b4342 --- /dev/null +++ b/stubs/six/six/moves/urllib/robotparser.pyi @@ -0,0 +1 @@ +from urllib.robotparser import RobotFileParser as RobotFileParser diff --git a/stubs/six/six/moves/urllib_error.pyi b/stubs/six/six/moves/urllib_error.pyi new file mode 100644 index 000000000000..272007222364 --- /dev/null +++ b/stubs/six/six/moves/urllib_error.pyi @@ -0,0 +1 @@ +from urllib.error import * diff --git a/stubs/six/six/moves/urllib_parse.pyi b/stubs/six/six/moves/urllib_parse.pyi new file mode 100644 index 000000000000..b557bbbb645f --- /dev/null +++ b/stubs/six/six/moves/urllib_parse.pyi @@ -0,0 +1 @@ +from urllib.parse import * diff --git a/stubs/six/six/moves/urllib_request.pyi b/stubs/six/six/moves/urllib_request.pyi new file mode 100644 index 000000000000..dc03dcecc118 --- /dev/null +++ b/stubs/six/six/moves/urllib_request.pyi @@ -0,0 +1 @@ +from .urllib.request import * diff --git a/stubs/six/six/moves/urllib_response.pyi b/stubs/six/six/moves/urllib_response.pyi new file mode 100644 index 000000000000..bbee52256e31 --- /dev/null +++ b/stubs/six/six/moves/urllib_response.pyi @@ -0,0 +1 @@ +from .urllib.response import * diff --git a/stubs/six/six/moves/urllib_robotparser.pyi b/stubs/six/six/moves/urllib_robotparser.pyi new file mode 100644 index 000000000000..bbf5c3ce4cd1 --- /dev/null +++ b/stubs/six/six/moves/urllib_robotparser.pyi @@ -0,0 +1 @@ +from urllib.robotparser import * diff --git a/stubs/slumber/METADATA.toml b/stubs/slumber/METADATA.toml new file mode 100644 index 000000000000..c26264bafec2 --- /dev/null +++ b/stubs/slumber/METADATA.toml @@ -0,0 +1,3 @@ +version = "0.7.*" +upstream-repository = "https://github.com/samgiles/slumber" +dependencies = ["requests>=2.34.0"] diff --git a/stubs/slumber/slumber/__init__.pyi b/stubs/slumber/slumber/__init__.pyi new file mode 100644 index 000000000000..4169c337c152 --- /dev/null +++ b/stubs/slumber/slumber/__init__.pyi @@ -0,0 +1,43 @@ +from typing import Any +from typing_extensions import Self + +from requests import Response, Session +from requests._types import AuthType, DataType, FilesType, _ParamsMappingValueType + +from .serialize import Serializer + +__all__ = ["Resource", "API"] + +class ResourceAttributesMixin: + # Exists at runtime: + def __getattr__(self, item: str) -> Any: ... + +class Resource(ResourceAttributesMixin): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def __call__(self, id: str | None = None, format: str | None = None, url_override: str | None = None) -> Self: ... + def get(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def options(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def head(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def post( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def patch( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def put( + self, data: DataType | None = None, files: FilesType | None = None, **kwargs: _ParamsMappingValueType + ) -> Response: ... + def delete(self, **kwargs: _ParamsMappingValueType) -> Response: ... + def url(self) -> str: ... + +class API(ResourceAttributesMixin): + resource_class: type[Resource] + def __init__( + self, + base_url: str | None = None, + auth: AuthType | None = None, + format: str | None = None, + append_slash: bool = True, + session: Session | None = None, + serializer: Serializer | None = None, + ) -> None: ... diff --git a/stubs/slumber/slumber/exceptions.pyi b/stubs/slumber/slumber/exceptions.pyi new file mode 100644 index 000000000000..20cac92d7479 --- /dev/null +++ b/stubs/slumber/slumber/exceptions.pyi @@ -0,0 +1,13 @@ +from typing import Any + +class SlumberBaseException(Exception): ... + +class SlumberHttpBaseException(SlumberBaseException): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + +class HttpClientError(SlumberHttpBaseException): ... +class HttpNotFoundError(HttpClientError): ... +class HttpServerError(SlumberHttpBaseException): ... +class SerializerNoAvailable(SlumberBaseException): ... +class SerializerNotAvailable(SlumberBaseException): ... +class ImproperlyConfigured(SlumberBaseException): ... diff --git a/stubs/slumber/slumber/serialize.pyi b/stubs/slumber/slumber/serialize.pyi new file mode 100644 index 000000000000..49a611cc084b --- /dev/null +++ b/stubs/slumber/slumber/serialize.pyi @@ -0,0 +1,27 @@ +from typing import Any, TypeAlias + +_Data: TypeAlias = str | bytes | bytearray + +class BaseSerializer: + content_types: list[str] | None + key: str | None + def get_content_type(self) -> str: ... + def loads(self, data: _Data) -> Any: ... + def dumps(self, data: _Data) -> Any: ... + +class JsonSerializer(BaseSerializer): + content_types: list[str] + key: str + +class YamlSerializer(BaseSerializer): + content_types: list[str] + key: str + +class Serializer: + serializers: list[BaseSerializer] + default: str + def __init__(self, default: str | None = None, serializers: list[BaseSerializer] | None = None) -> None: ... + def get_serializer(self, name: str | None = None, content_type: str | None = None) -> BaseSerializer: ... + def loads(self, data: _Data, format: str | None = None) -> Any: ... + def dumps(self, data: _Data, format: str | None = None) -> Any: ... + def get_content_type(self, format: str | None = None) -> str: ... diff --git a/stubs/slumber/slumber/utils.pyi b/stubs/slumber/slumber/utils.pyi new file mode 100644 index 000000000000..3dc0c9ee6dc8 --- /dev/null +++ b/stubs/slumber/slumber/utils.pyi @@ -0,0 +1,10 @@ +from collections.abc import ItemsView, Mapping, MutableMapping +from typing import Any, TypeVar + +_KT = TypeVar("_KT") +_VT_co = TypeVar("_VT_co", covariant=True) +_MM = TypeVar("_MM", bound=MutableMapping[Any, Any]) + +def url_join(base: str, *args: str) -> str: ... +def copy_kwargs(dictionary: _MM) -> _MM: ... +def iterator(d: Mapping[_KT, _VT_co]) -> ItemsView[_KT, _VT_co]: ... diff --git a/stubs/str2bool/METADATA.toml b/stubs/str2bool/METADATA.toml new file mode 100644 index 000000000000..603a54f0026b --- /dev/null +++ b/stubs/str2bool/METADATA.toml @@ -0,0 +1,2 @@ +version = "1.1" +upstream-repository = "https://github.com/symonsoft/str2bool" diff --git a/stubs/str2bool/str2bool/__init__.pyi b/stubs/str2bool/str2bool/__init__.pyi new file mode 100644 index 000000000000..d7d801d9a239 --- /dev/null +++ b/stubs/str2bool/str2bool/__init__.pyi @@ -0,0 +1,8 @@ +from typing import Literal, overload + +@overload +def str2bool(value: str, raise_exc: Literal[True]) -> bool: ... +@overload +def str2bool(value: str, raise_exc: bool = False) -> bool | None: ... + +def str2bool_exc(value: str) -> bool: ... diff --git a/stubs/tabulate/METADATA.toml b/stubs/tabulate/METADATA.toml new file mode 100644 index 000000000000..7deacccbf1f4 --- /dev/null +++ b/stubs/tabulate/METADATA.toml @@ -0,0 +1,2 @@ +version = "0.10.*" +upstream-repository = "https://github.com/astanin/python-tabulate" diff --git a/stubs/tabulate/tabulate/__init__.pyi b/stubs/tabulate/tabulate/__init__.pyi new file mode 100644 index 000000000000..2debb6fe4a5f --- /dev/null +++ b/stubs/tabulate/tabulate/__init__.pyi @@ -0,0 +1,71 @@ +from collections.abc import Callable, Container, Iterable, Mapping, Sequence +from typing import Any, Final, Literal, NamedTuple, TypeAlias +from typing_extensions import Self + +__all__ = ["tabulate", "tabulate_formats", "simple_separated_format"] + +__version__: Final[str] +# These constants are meant to be configurable +# https://github.com/astanin/python-tabulate#text-formatting +PRESERVE_WHITESPACE: bool +MIN_PADDING: int +# https://github.com/astanin/python-tabulate#wide-fullwidth-cjk-symbols +WIDE_CHARS_MODE: bool +SEPARATING_LINE: str + +class Line(NamedTuple): + begin: str + hline: str + sep: str + end: str + +class DataRow(NamedTuple): + begin: str + sep: str + end: str + +_TableFormatLine: TypeAlias = None | Line | Callable[[list[int], list[str]], str] +_TableFormatRow: TypeAlias = None | DataRow | Callable[[list[Any], list[int], list[str]], str] + +class TableFormat(NamedTuple): + lineabove: _TableFormatLine + linebelowheader: _TableFormatLine + linebetweenrows: _TableFormatLine + linebelow: _TableFormatLine + headerrow: _TableFormatRow + datarow: _TableFormatRow + padding: int + with_header_hide: Container[str] | None + +LATEX_ESCAPE_RULES: Final[dict[str, str]] +tabulate_formats: list[str] +multiline_formats: dict[str, str] + +def simple_separated_format(separator: str) -> TableFormat: ... +def tabulate( + # The key is converted using str(). + tabular_data: Mapping[Any, Iterable[Any]] | Iterable[Iterable[Any]], + headers: str | dict[str, str] | Sequence[str] = (), + tablefmt: str | TableFormat = "simple", + floatfmt: str | Iterable[str] = "g", + intfmt: str | Iterable[str] = "", + numalign: str | None = "default", + stralign: str | None = "default", + missingval: str | Iterable[str] = "", + showindex: str | bool | Iterable[Any] = "default", + disable_numparse: bool | Iterable[int] = False, + colglobalalign: Literal["right", "center", "decimal", "left"] | None = None, + colalign: Iterable[str | None] | None = None, + preserve_whitespace: bool = False, + maxcolwidths: int | Iterable[int | None] | None = None, + headersglobalalign: Literal["right", "center", "left"] | None = None, + headersalign: Iterable[str | None] | None = None, + rowalign: str | Iterable[str] | None = None, + maxheadercolwidths: int | Iterable[int] | None = None, + break_long_words: bool = True, + break_on_hyphens: bool = True, +) -> str: ... + +class JupyterHTMLStr(str): + @property + def str(self) -> Self: ... diff --git a/stubs/tensorflow/@tests/stubtest_allowlist.txt b/stubs/tensorflow/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..92811b4f79b4 --- /dev/null +++ b/stubs/tensorflow/@tests/stubtest_allowlist.txt @@ -0,0 +1,115 @@ +# Some methods are dynamically patched onto to instances as they +# may depend on whether code is executed in graph/eager/v1/v2/etc. +# Tensorflow supports multiple modes of execution which changes some +# of the attributes/methods/even class hierarchies. +tensorflow.Tensor.__int__ +tensorflow.Tensor.numpy +tensorflow.Tensor.__index__ +# Incomplete +tensorflow.sparse.SparseTensor.__getattr__ +tensorflow.SparseTensor.__getattr__ +tensorflow.TensorShape.__getattr__ +tensorflow.dtypes.DType.__getattr__ +tensorflow.RaggedTensor.__getattr__ +tensorflow.DType.__getattr__ +tensorflow.Graph.__getattr__ +tensorflow.Operation.__getattr__ +tensorflow.Variable.__getattr__ +tensorflow.keras.layers.Layer.__getattr__ +tensorflow.python.feature_column.feature_column_v2.SharedEmbeddingColumnCreator.__getattr__ +tensorflow.GradientTape.__getattr__ +tensorflow.data.Dataset.__getattr__ +tensorflow.experimental.Optional.__getattr__ +tensorflow.autodiff.GradientTape.__getattr__ + +# The Tensor methods below were removed in 2.14, however they are still defined for the +# internal subclasses that are used at runtime/in practice. +tensorflow.Tensor.consumers +tensorflow.Tensor.graph +tensorflow.Tensor.op + +# Internal undocumented API +tensorflow.RaggedTensor.__init__ +tensorflow.data.Dataset.__init__ + +# Has an undocumented extra argument that tf.Variable which acts like subclass +# (by dynamically patching tf.Tensor methods) does not preserve. +tensorflow.Tensor.__getitem__ +# stub internal utilities +tensorflow._aliases + +# Tensorflow imports are cursed. +# import tensorflow.initializers +# import tensorflow as tf +# tf.initializers +# Usually these two ways are same module, but for tensorflow the first way +# often does not work and the second way does. The documentation describes +# tf.initializers as module and has that type if accessed the second way, +# but the real module file is completely different name (even package) and dynamically handled. +# tf.initializers at runtime is +tensorflow.initializers +# Other cursed import magic similar to the one above. +tensorflow.distribute.coordinator +tensorflow.distribute.experimental.coordinator + +# __call__ in tensorflow classes often allow keyword usage, but +# when you subclass those classes it is not expected to handle keyword case. As an example, +# class MyLayer(tf.keras.layers.Layer): +# def call(self, x): +# ... +# is common even though Layer.call is defined like def call(self, inputs). Treating inputs as +# a keyword argument would lead to many false positives with typical subclass usage. +# Additional awkwardness for Layer's is call may optionally have training/mask as keyword arguments and some +# layers do while others do not. At runtime call is not intended to be used directly by users, +# but instead through __call__ which extracts out the training/mask arguments. Trying to describe +# this better in stubs would similarly add many false positive Liskov violations. +tensorflow.keras.layers.*.call +tensorflow.keras.regularizers.Regularizer.__call__ +tensorflow.keras.constraints.Constraint.__call__ + +# Layer/Model class does good deal of __new__ magic and actually returns one of two different internal +# types depending on tensorflow execution mode. This feels like implementation internal. +tensorflow.keras.layers.Layer.__new__ + +# build/compute_output_shape are marked positional only in stubs +# as argument name is inconsistent across layer's and looks like +# an implementation detail as documentation never mentions the +# disagreements. +tensorflow.keras.layers.*.build +tensorflow.keras.layers.*.compute_output_shape + +# pb2.pyi generated by mypy-protobuf diverge with runtime in many ways. These stubs +# are mainly tested in mypy-protobuf. +.*_pb2.* + +# Uses namedtuple at runtime, but NamedTuple in stubs and the two disagree about the name of +# __new__ first argument (cls vs cls_). +tensorflow.io.RaggedFeature.__new__ +tensorflow.io.FixedLenSequenceFeature.__new__ +tensorflow.io.FixedLenFeature.__new__ +tensorflow.io.SparseFeature.__new__ + +# Metaclass inconsistency. The runtime metaclass is defined from c++ extension and is undocumented. +tensorflow.io.TFRecordWriter +tensorflow.experimental.dtensor.Mesh + +# stubtest does not pass for protobuf generated stubs. +tensorflow.train.Example.* +tensorflow.train.BytesList.* +tensorflow.train.Feature.* +tensorflow.train.FloatList.* +tensorflow.train.Int64List.* +tensorflow.train.ClusterDef.* +tensorflow.train.ServerDef.* + +# The python module cannot be accessed directly, so to stubtest it appears that it is not present at runtime. +# However it can be accessed by doing: +# from tensorflow import python +# python.X +tensorflow.python.* + +# The modules below are re-exported from tensorflow.python, and they therefore appear missing to stubtest. +tensorflow.distribute.Strategy + +# sigmoid_cross_entropy_with_logits has default values (None), however those values are not valid. +tensorflow.nn.sigmoid_cross_entropy_with_logits diff --git a/stubs/tensorflow/METADATA.toml b/stubs/tensorflow/METADATA.toml new file mode 100644 index 000000000000..7366aee540b5 --- /dev/null +++ b/stubs/tensorflow/METADATA.toml @@ -0,0 +1,16 @@ +# Using an exact number in the specifier for scripts/sync_protobuf/tensorflow.py +# When updating, also re-run the script +version = "~=2.18.0" +upstream-repository = "https://github.com/tensorflow/tensorflow" +# requires a version of numpy with a `py.typed` file +dependencies = ["numpy>=1.20", "types-protobuf", "requests>=2.34.0"] +extra-description = "Partially generated using [mypy-protobuf==3.6.0](https://github.com/nipunn1313/mypy-protobuf/tree/v3.6.0) and libprotoc 27.2 on `tensorflow==2.18.0`." +partial-stub = true + +[tool.stubtest] +ignore-missing-stub = true +# TODO: Support/update to keras 3.7 +stubtest-dependencies = ["keras==3.6.*"] +# tensorflow 2.19 doesn't support Python 3.13: +# https://github.com/tensorflow/tensorflow/issues/78774 +skip = true diff --git a/stubs/tensorflow/tensorflow/__init__.pyi b/stubs/tensorflow/tensorflow/__init__.pyi new file mode 100644 index 000000000000..a8961b022b87 --- /dev/null +++ b/stubs/tensorflow/tensorflow/__init__.pyi @@ -0,0 +1,523 @@ +import abc +from _typeshed import Incomplete, Unused +from abc import ABC, ABCMeta, abstractmethod +from builtins import bool as _bool, slice as _slice +from collections.abc import Callable, Generator, Iterable, Iterator, Sequence +from contextlib import contextmanager +from enum import Enum +from types import TracebackType +from typing import Any, Generic, Literal, ParamSpec, TypeAlias, TypeVar, overload +from typing_extensions import Self + +from google.protobuf.message import Message +from tensorflow import ( + data as data, + debugging as debugging, + experimental as experimental, + feature_column as feature_column, + image as image, + initializers as initializers, + io as io, + keras as keras, + math as math, + nn as nn, + random as random, + types as types, +) +from tensorflow._aliases import ( + AnyArray, + DTypeLike, + IntArray, + IntTensorCompatible, + RaggedTensorLike, + ScalarTensorCompatible, + ShapeLike, + Signature, + Slice, + SparseTensorCompatible, + TensorCompatible, + TensorLike, + UIntTensorCompatible, +) +from tensorflow.autodiff import GradientTape as GradientTape +from tensorflow.core.protobuf import struct_pb2 +from tensorflow.dtypes import * +from tensorflow.experimental.dtensor import Layout +from tensorflow.keras import losses as losses +from tensorflow.linalg import eye as eye, matmul as matmul + +# Most tf.math functions are exported as tf, but sadly not all are. +from tensorflow.math import ( + abs as abs, + add as add, + add_n as add_n, + argmax as argmax, + argmin as argmin, + cos as cos, + cosh as cosh, + divide as divide, + equal as equal, + greater as greater, + greater_equal as greater_equal, + less as less, + less_equal as less_equal, + logical_and as logical_and, + logical_not as logical_not, + logical_or as logical_or, + maximum as maximum, + minimum as minimum, + multiply as multiply, + not_equal as not_equal, + pow as pow, + reduce_max as reduce_max, + reduce_mean as reduce_mean, + reduce_min as reduce_min, + reduce_prod as reduce_prod, + reduce_sum as reduce_sum, + round as round, + sigmoid as sigmoid, + sign as sign, + sin as sin, + sinh as sinh, + sqrt as sqrt, + square as square, + subtract as subtract, + tanh as tanh, +) +from tensorflow.python.trackable.autotrackable import AutoTrackable +from tensorflow.sparse import SparseTensor as SparseTensor + +# Tensors ideally should be a generic type, but properly typing data type/shape +# will be a lot of work. Until we have good non-generic tensorflow stubs, +# we will skip making Tensor generic. Also good type hints for shapes will +# run quickly into many places where type system is not strong enough today. +# So shape typing is probably not worth doing anytime soon. +class Tensor: + def __init__(self, op: Operation, value_index: int, dtype: DType) -> None: ... + def consumers(self) -> list[Incomplete]: ... + @property + def shape(self) -> TensorShape: ... + def get_shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def graph(self) -> Graph: ... + @property + def name(self) -> str: ... + @property + def op(self) -> Operation: ... + def numpy(self) -> AnyArray: ... + def __array__(self, dtype: DTypeLike | None = None) -> AnyArray: ... + def __int__(self) -> int: ... + def __abs__(self, name: str | None = None) -> Tensor: ... + def __add__(self, other: TensorCompatible) -> Tensor: ... + def __radd__(self, other: TensorCompatible) -> Tensor: ... + def __sub__(self, other: TensorCompatible) -> Tensor: ... + def __rsub__(self, other: TensorCompatible) -> Tensor: ... + def __mul__(self, other: TensorCompatible) -> Tensor: ... + def __rmul__(self, other: TensorCompatible) -> Tensor: ... + def __pow__(self, other: TensorCompatible) -> Tensor: ... + def __matmul__(self, other: TensorCompatible) -> Tensor: ... + def __rmatmul__(self, other: TensorCompatible) -> Tensor: ... + def __floordiv__(self, other: TensorCompatible) -> Tensor: ... + def __rfloordiv__(self, other: TensorCompatible) -> Tensor: ... + def __truediv__(self, other: TensorCompatible) -> Tensor: ... + def __rtruediv__(self, other: TensorCompatible) -> Tensor: ... + def __neg__(self, name: str | None = None) -> Tensor: ... + def __and__(self, other: TensorCompatible) -> Tensor: ... + def __rand__(self, other: TensorCompatible) -> Tensor: ... + def __or__(self, other: TensorCompatible) -> Tensor: ... + def __ror__(self, other: TensorCompatible) -> Tensor: ... + def __eq__(self, other: TensorCompatible) -> Tensor: ... # type: ignore[override] + def __ne__(self, other: TensorCompatible) -> Tensor: ... # type: ignore[override] + def __ge__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __gt__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __le__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __lt__(self, other: TensorCompatible, name: str | None = None) -> Tensor: ... + def __bool__(self) -> _bool: ... + def __getitem__(self, slice_spec: Slice | tuple[Slice, ...]) -> Tensor: ... + def __len__(self) -> int: ... + # This only works for rank 0 tensors. + def __index__(self) -> int: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class VariableSynchronization(Enum): + AUTO = 0 + NONE = 1 + ON_WRITE = 2 + ON_READ = 3 + +class VariableAggregation(Enum): + NONE = 0 + SUM = 1 + MEAN = 2 + ONLY_FIRST_REPLICA = 3 + +class _VariableMetaclass(type): ... + +# Variable class in intent/documentation is a Tensor. In implementation there's +# TODO: comment to make it Tensor. It is not actually Tensor type wise, but even +# dynamically patches on most methods of tf.Tensor +# https://github.com/tensorflow/tensorflow/blob/9524a636cae9ae3f0554203c1ba7ee29c85fcf12/tensorflow/python/ops/variables.py#L1086. +class Variable(Tensor, metaclass=_VariableMetaclass): + def __init__( + self, + initial_value: Tensor | Callable[[], Tensor] | None = None, + trainable: _bool | None = None, + validate_shape: _bool = True, + # Valid non-None values are deprecated. + caching_device: None = None, + name: str | None = None, + # Real type is VariableDef protobuf type. Can be added after adding script + # to generate tensorflow protobuf stubs with mypy-protobuf. + variable_def=None, + dtype: DTypeLike | None = None, + import_scope: str | None = None, + constraint: Callable[[Tensor], Tensor] | None = None, + synchronization: VariableSynchronization = ..., + aggregation: VariableAggregation = ..., + shape: ShapeLike | None = None, + experimental_enable_variable_lifting: _bool = True, + ) -> None: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class RaggedTensor(metaclass=ABCMeta): + def bounding_shape( + self, axis: TensorCompatible | None = None, name: str | None = None, out_type: DTypeLike | None = None + ) -> Tensor: ... + @classmethod + def from_sparse(cls, st_input: SparseTensor, name: str | None = None, row_splits_dtype: DTypeLike = ...) -> RaggedTensor: ... + def to_sparse(self, name: str | None = None) -> SparseTensor: ... + def to_tensor( + self, default_value: float | str | None = None, name: str | None = None, shape: ShapeLike | None = None + ) -> Tensor: ... + def __add__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __radd__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __sub__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __mul__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __rmul__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __floordiv__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __truediv__(self, other: RaggedTensor | float, name: str | None = None) -> RaggedTensor: ... + def __getitem__(self, slice_spec: Slice | tuple[Slice, ...]) -> RaggedTensor: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class Operation: + def __init__( + self, + node_def, + g: Graph, + # isinstance is used so can not be Sequence/Iterable. + inputs: list[Tensor] | None = None, + output_types: Unused = None, + control_inputs: Iterable[Tensor | Operation] | None = None, + input_types: Iterable[DType] | None = None, + original_op: Operation | None = None, + op_def=None, + ) -> None: ... + @property + def inputs(self) -> list[Tensor]: ... + @property + def outputs(self) -> list[Tensor]: ... + @property + def device(self) -> str: ... + @property + def name(self) -> str: ... + @property + def type(self) -> str: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class TensorShape(metaclass=ABCMeta): + __slots__ = ["_dims"] + def __init__(self, dims: ShapeLike) -> None: ... + @property + def rank(self) -> int: ... + def as_list(self) -> list[int | None]: ... + def assert_has_rank(self, rank: int) -> None: ... + def assert_is_compatible_with(self, other: Iterable[int | None]) -> None: ... + def __bool__(self) -> _bool: ... + + @overload + def __getitem__(self, key: int) -> int | None: ... + @overload + def __getitem__(self, key: _slice) -> TensorShape: ... + + def __iter__(self) -> Iterator[int | None]: ... + def __len__(self) -> int: ... + def __add__(self, other: Iterable[int | None]) -> TensorShape: ... + def __radd__(self, other: Iterable[int | None]) -> TensorShape: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class Graph: + def add_to_collection(self, name: str, value: object) -> None: ... + def add_to_collections(self, names: Iterable[str] | str, value: object) -> None: ... + @contextmanager + def as_default(self) -> Generator[Self]: ... + def finalize(self) -> None: ... + def get_tensor_by_name(self, name: str) -> Tensor: ... + def get_operation_by_name(self, name: str) -> Operation: ... + def get_operations(self) -> list[Operation]: ... + def get_name_scope(self) -> str: ... + def __getattr__(self, name: str) -> Incomplete: ... + +class IndexedSlices(metaclass=ABCMeta): + def __init__(self, values: Tensor, indices: Tensor, dense_shape: None | Tensor = None) -> None: ... + @property + def values(self) -> Tensor: ... + @property + def indices(self) -> Tensor: ... + @property + def dense_shape(self) -> None | Tensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def name(self) -> str: ... + @property + def op(self) -> Operation: ... + @property + def graph(self) -> Graph: ... + @property + def device(self) -> str: ... + def __neg__(self) -> IndexedSlices: ... + def consumers(self) -> list[Operation]: ... + +class name_scope(metaclass=abc.ABCMeta): + def __init__(self, name: str) -> None: ... + def __enter__(self) -> str: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + +_P = ParamSpec("_P") +_R = TypeVar("_R") +_NameScope: TypeAlias = name_scope + +class Module(AutoTrackable): + def __init__(self, name: str | None = None) -> None: ... + @property + def name(self) -> str: ... + @property + def name_scope(self) -> _NameScope: ... + # Documentation only specifies these as returning Sequence. Actual + # implementation does tuple. + @property + def variables(self) -> Sequence[Variable]: ... + @property + def trainable_variables(self) -> Sequence[Variable]: ... + @property + def non_trainable_variables(self) -> Sequence[Variable]: ... + @property + def submodules(self) -> Sequence[Module]: ... + @classmethod + def with_name_scope(cls, method: Callable[_P, _R]) -> Callable[_P, _R]: ... + +class UnconnectedGradients(Enum): + NONE = "none" + ZERO = "zero" + +_SpecProto = TypeVar("_SpecProto", bound=Message) + +class TypeSpec(ABC, Generic[_SpecProto]): + __slots__ = ["_cached_cmp_key"] + @property + @abstractmethod + def value_type(self) -> Any: ... + def experimental_as_proto(self) -> _SpecProto: ... + @classmethod + def experimental_from_proto(cls, proto: _SpecProto) -> Self: ... + @classmethod + def experimental_type_proto(cls) -> type[_SpecProto]: ... + def is_compatible_with(self, spec_or_value: Self | TensorCompatible | SparseTensor | RaggedTensor) -> _bool: ... + # Incomplete as tf.types is not yet covered. + def is_subtype_of(self, other) -> _bool: ... + def most_specific_common_supertype(self, others: Sequence[Incomplete]) -> Self | None: ... + def most_specific_compatible_type(self, other: Self) -> Self: ... + +class TensorSpec(TypeSpec[struct_pb2.TensorSpecProto]): + __slots__: list[str] = [] + def __init__(self, shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None) -> None: ... + @property + def value_type(self) -> Tensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @property + def name(self) -> str | None: ... + @classmethod + def from_spec(cls, spec: TypeSpec[Any], name: str | None = None) -> Self: ... + @classmethod + def from_tensor(cls, tensor: Tensor, name: str | None = None) -> Self: ... + def is_compatible_with(self, spec_or_tensor: Self | TensorCompatible) -> _bool: ... # type: ignore[override] + +class SparseTensorSpec(TypeSpec[struct_pb2.TypeSpecProto]): + __slots__ = ["_shape", "_dtype"] + def __init__(self, shape: ShapeLike | None = None, dtype: DTypeLike = ...) -> None: ... + @property + def value_type(self) -> SparseTensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @classmethod + def from_value(cls, value: SparseTensor) -> Self: ... + +class RaggedTensorSpec(TypeSpec[struct_pb2.TypeSpecProto]): + __slots__ = ["_shape", "_dtype", "_ragged_rank", "_row_splits_dtype", "_flat_values_spec"] + def __init__( + self, + shape: ShapeLike | None = None, + dtype: DTypeLike = ..., + ragged_rank: int | None = None, + row_splits_dtype: DTypeLike = ..., + flat_values_spec: TypeSpec[Any] | None = None, + ) -> None: ... + @property + def value_type(self) -> RaggedTensor: ... + @property + def shape(self) -> TensorShape: ... + @property + def dtype(self) -> DType: ... + @classmethod + def from_value(cls, value: RaggedTensor) -> Self: ... + +newaxis: None + +def convert_to_tensor( + value: TensorCompatible | IndexedSlices, + dtype: DTypeLike | None = None, + dtype_hint: DTypeLike | None = None, + name: str | None = None, +) -> Tensor: ... + +@overload +def expand_dims(input: TensorCompatible, axis: int, name: str | None = None) -> Tensor: ... +@overload +def expand_dims(input: RaggedTensor, axis: int, name: str | None = None) -> RaggedTensor: ... + +@overload +def concat(values: TensorCompatible, axis: int, name: str | None = "concat") -> Tensor: ... +@overload +def concat(values: Sequence[RaggedTensor], axis: int, name: str | None = "concat") -> RaggedTensor: ... + +@overload +def squeeze( + input: TensorCompatible, axis: int | tuple[int, ...] | list[int] | None = None, name: str | None = None +) -> Tensor: ... +@overload +def squeeze(input: RaggedTensor, axis: int | tuple[int, ...] | list[int], name: str | None = None) -> RaggedTensor: ... + +def slice(input_: TensorCompatible, begin: IntTensorCompatible, size: IntTensorCompatible, name: str | None = None) -> Tensor: ... +def split( + value: TensorCompatible, + num_or_size_splits: int | TensorCompatible, + axis: int | Tensor = 0, + num: int | None = None, + name: str | None = "split", +) -> list[Tensor]: ... +def stack(values: TensorCompatible, axis: int = 0, name: str | None = "stack") -> Tensor: ... +def tensor_scatter_nd_update( + tensor: TensorCompatible, indices: TensorCompatible, updates: TensorCompatible, name: str | None = None +) -> Tensor: ... +def constant( + value: TensorCompatible, dtype: DTypeLike | None = None, shape: ShapeLike | None = None, name: str | None = "Const" +) -> Tensor: ... + +@overload +def cast(x: TensorCompatible, dtype: DTypeLike, name: str | None = None) -> Tensor: ... +@overload +def cast(x: SparseTensor, dtype: DTypeLike, name: str | None = None) -> SparseTensor: ... +@overload +def cast(x: RaggedTensor, dtype: DTypeLike, name: str | None = None) -> RaggedTensor: ... + +def zeros(shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None, layout: Layout | None = None) -> Tensor: ... +def ones(shape: ShapeLike, dtype: DTypeLike = ..., name: str | None = None, layout: Layout | None = None) -> Tensor: ... + +@overload +def zeros_like( + input: TensorCompatible | IndexedSlices, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> Tensor: ... +@overload +def zeros_like( + input: RaggedTensor, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> RaggedTensor: ... + +@overload +def ones_like( + input: TensorCompatible, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> Tensor: ... +@overload +def ones_like( + input: RaggedTensor, dtype: DTypeLike | None = None, name: str | None = None, layout: Layout | None = None +) -> RaggedTensor: ... + +def reshape(tensor: TensorCompatible, shape: ShapeLike | Tensor, name: str | None = None) -> Tensor: ... +def reverse(tensor: TensorCompatible, axis: IntTensorCompatible, name: str | None = None) -> Tensor: ... + +_ElemT = TypeVar("_ElemT", bound=TensorLike) +_RetT = TypeVar("_RetT", bound=TensorLike) + +@overload +def map_fn( + fn: Callable[[_ElemT], _RetT], + elems: _ElemT, + dtype: DTypeLike | None = None, + parallel_iterations: int | None = None, + back_prop: _bool = True, + swap_memory: _bool = False, + infer_shape: _bool = True, + name: str | None = None, + fn_output_signature: Signature | None = None, +) -> _RetT: ... +@overload +def map_fn( + fn: Callable[[Tensor], _RetT], + elems: TensorCompatible, + dtype: DTypeLike | None = None, + parallel_iterations: int | None = None, + back_prop: _bool = True, + swap_memory: _bool = False, + infer_shape: _bool = True, + name: str | None = None, + fn_output_signature: Signature | None = None, +) -> _RetT: ... + +def pad( + tensor: TensorCompatible, + paddings: Tensor | IntArray | Iterable[Iterable[int]], + mode: Literal["CONSTANT", "constant", "REFLECT", "reflect", "SYMMETRIC", "symmetric"] = "CONSTANT", + constant_values: ScalarTensorCompatible = 0, + name: str | None = None, +) -> Tensor: ... +def shape(input: SparseTensorCompatible, out_type: DTypeLike | None = None, name: str | None = None) -> Tensor: ... +def where( + condition: TensorCompatible, x: TensorCompatible | None = None, y: TensorCompatible | None = None, name: str | None = None +) -> Tensor: ... +def gather_nd( + params: TensorCompatible, + indices: UIntTensorCompatible, + batch_dims: UIntTensorCompatible = 0, + name: str | None = None, + bad_indices_policy: Literal["", "DEFAULT", "ERROR", "IGNORE"] = "", +) -> Tensor: ... +def transpose( + a: Tensor, perm: Sequence[int] | IntArray | None = None, conjugate: _bool = False, name: str = "transpose" +) -> Tensor: ... +def clip_by_value( + t: Tensor | IndexedSlices, clip_value_min: TensorCompatible, clip_value_max: TensorCompatible, name: str | None = None +) -> Tensor: ... +def tile(input: RaggedTensorLike, multiples: Tensor | Sequence[int], name: str | None = None) -> Tensor: ... + +@overload +def range( + limit: int | Tensor, /, *, delta: int | Tensor = 1, dtype: DTypeLike | None = None, name: str | None = "range" +) -> Tensor: ... +@overload +def range( + start: int | Tensor = 0, + limit: int | Tensor = 0, + delta: int | Tensor = 1, + dtype: DTypeLike | None = None, + name: str | None = "range", +) -> Tensor: ... + +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/_aliases.pyi b/stubs/tensorflow/tensorflow/_aliases.pyi new file mode 100644 index 000000000000..a3ac8f423437 --- /dev/null +++ b/stubs/tensorflow/tensorflow/_aliases.pyi @@ -0,0 +1,73 @@ +# Commonly used type aliases. +# Everything in this module is private for stubs. There is no runtime equivalent. + +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, Protocol, TypeAlias, TypeVar, type_check_only + +import numpy as np +import numpy.typing as npt +import tensorflow as tf +from tensorflow.dtypes import DType +from tensorflow.keras.layers import InputSpec + +_T = TypeVar("_T") +ContainerGeneric: TypeAlias = Mapping[str, ContainerGeneric[_T]] | Sequence[ContainerGeneric[_T]] | _T + +TensorLike: TypeAlias = tf.Tensor | tf.RaggedTensor | tf.SparseTensor +SparseTensorLike: TypeAlias = tf.Tensor | tf.SparseTensor +RaggedTensorLike: TypeAlias = tf.Tensor | tf.RaggedTensor +# _RaggedTensorLikeT = TypeVar("_RaggedTensorLikeT", tf.Tensor, tf.RaggedTensor) +Gradients: TypeAlias = tf.Tensor | tf.IndexedSlices + +@type_check_only +class KerasSerializable1(Protocol): + def get_config(self) -> dict[str, Any]: ... + +@type_check_only +class KerasSerializable2(Protocol): + __name__: str + +KerasSerializable: TypeAlias = KerasSerializable1 | KerasSerializable2 + +TensorValue: TypeAlias = tf.Tensor # Alias for a 0D Tensor +Integer: TypeAlias = TensorValue | int | IntArray | np.number[Any] # Here IntArray are assumed to be 0D. +Float: TypeAlias = Integer | float | FloatArray +Slice: TypeAlias = tf.Tensor | tf.RaggedTensor | int | slice | None +FloatDataSequence: TypeAlias = Sequence[float] | Sequence[FloatDataSequence] +IntDataSequence: TypeAlias = Sequence[int] | Sequence[IntDataSequence] +StrDataSequence: TypeAlias = Sequence[str] | Sequence[StrDataSequence] +DataSequence: TypeAlias = FloatDataSequence | StrDataSequence | IntDataSequence +ScalarTensorCompatible: TypeAlias = tf.Tensor | str | float | np.ndarray[Any, Any] | np.number[Any] +UIntTensorCompatible: TypeAlias = tf.Tensor | int | UIntArray +IntTensorCompatible: TypeAlias = tf.Tensor | int | IntArray | Sequence[IntTensorCompatible] +FloatTensorCompatible: TypeAlias = tf.Tensor | int | IntArray | float | FloatArray | np.number[Any] +StringTensorCompatible: TypeAlias = tf.Tensor | str | npt.NDArray[np.str_] | Sequence[StringTensorCompatible] + +TensorCompatible: TypeAlias = ScalarTensorCompatible | Sequence[TensorCompatible] +# _TensorCompatibleT = TypeVar("_TensorCompatibleT", bound=TensorCompatible) +# Sparse tensors are very annoying. Some operations work on them, but many do not. +# You will need to manually verify if an operation supports them. SparseTensorCompatible is intended to be a +# broader type than TensorCompatible and not all operations will support broader version. If unsure, +# use TensorCompatible instead. +SparseTensorCompatible: TypeAlias = TensorCompatible | tf.SparseTensor +# TensorFlow tries to convert anything passed as input. Meaning that even if, for example, only a Tensor of int32 +# is allowed, a numpy array of strings that can be converted to int32 will work. Therefore having anything more specific +# then AnyArray might cause false positives, while AnyArray might cause false negatives. +TensorOrArray: TypeAlias = tf.Tensor | AnyArray + +ShapeLike: TypeAlias = tf.TensorShape | Iterable[ScalarTensorCompatible | None] | int | tf.Tensor +DTypeLike: TypeAlias = DType | str | np.dtype[Any] | int +Signature: TypeAlias = DType | tf.RaggedTensorSpec | tf.SparseTensorSpec | Sequence[Signature] + +ContainerTensors: TypeAlias = ContainerGeneric[tf.Tensor] +ContainerTensorsLike: TypeAlias = ContainerGeneric[TensorLike] +ContainerTensorCompatible: TypeAlias = ContainerGeneric[TensorCompatible] +ContainerGradients: TypeAlias = ContainerGeneric[Gradients] +ContainerTensorShape: TypeAlias = ContainerGeneric[tf.TensorShape] +ContainerInputSpec: TypeAlias = ContainerGeneric[InputSpec] + +AnyArray: TypeAlias = npt.NDArray[Any] +FloatArray: TypeAlias = npt.NDArray[np.float16 | np.float32 | np.float64] +UIntArray: TypeAlias = npt.NDArray[np.uint | np.uint8 | np.uint16 | np.uint32 | np.uint64] +SignedIntArray: TypeAlias = npt.NDArray[np.int_ | np.int8 | np.int16 | np.int32 | np.int64] +IntArray: TypeAlias = UIntArray | SignedIntArray diff --git a/stubs/tensorflow/tensorflow/audio.pyi b/stubs/tensorflow/tensorflow/audio.pyi new file mode 100644 index 000000000000..480c72ad2e4c --- /dev/null +++ b/stubs/tensorflow/tensorflow/audio.pyi @@ -0,0 +1,7 @@ +import tensorflow as tf +from tensorflow._aliases import Integer, StringTensorCompatible + +def decode_wav( + contents: StringTensorCompatible, desired_channels: int = -1, desired_samples: int = -1, name: str | None = None +) -> tuple[tf.Tensor, tf.Tensor]: ... +def encode_wav(audio: tf.Tensor, sample_rate: Integer, name: str | None = None) -> tf.Tensor: ... diff --git a/stubs/tensorflow/tensorflow/autodiff.pyi b/stubs/tensorflow/tensorflow/autodiff.pyi new file mode 100644 index 000000000000..23bce8f0254e --- /dev/null +++ b/stubs/tensorflow/tensorflow/autodiff.pyi @@ -0,0 +1,65 @@ +from _typeshed import Incomplete +from builtins import bool as _bool +from collections.abc import Generator, Mapping, Sequence +from contextlib import contextmanager +from types import TracebackType +from typing import overload +from typing_extensions import Self + +import tensorflow as tf +from tensorflow import Tensor, UnconnectedGradients, Variable +from tensorflow._aliases import ContainerGradients, ContainerTensors, ContainerTensorsLike, Gradients, TensorLike + +class ForwardAccumulator: + def __init__(self, primals: Tensor, tangents: Tensor) -> None: ... + def jvp( + self, primals: Tensor, unconnected_gradients: tf.UnconnectedGradients = tf.UnconnectedGradients.NONE # noqa: Y011 + ) -> Tensor | None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + +class GradientTape: + def __init__(self, persistent: _bool = False, watch_accessed_variables: _bool = True) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) -> None: ... + + # Higher kinded types would be nice here and these overloads are a way to simulate some of them. + @overload + def gradient( + self, + target: ContainerTensors, + sources: TensorLike, + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> Gradients: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: Sequence[Tensor], + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> list[Gradients]: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: Mapping[str, Tensor], + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> dict[str, Gradients]: ... + @overload + def gradient( + self, + target: ContainerTensors, + sources: ContainerTensors, + output_gradients: list[Tensor] | None = None, + unconnected_gradients: UnconnectedGradients = ..., + ) -> ContainerGradients: ... + + @contextmanager + def stop_recording(self) -> Generator[None]: ... + def reset(self) -> None: ... + def watch(self, tensor: ContainerTensorsLike) -> None: ... + def watched_variables(self) -> tuple[Variable, ...]: ... + def __getattr__(self, name: str) -> Incomplete: ... diff --git a/stubs/tensorflow/tensorflow/autograph/__init__.pyi b/stubs/tensorflow/tensorflow/autograph/__init__.pyi new file mode 100644 index 000000000000..4058de0c3ec3 --- /dev/null +++ b/stubs/tensorflow/tensorflow/autograph/__init__.pyi @@ -0,0 +1,17 @@ +from collections.abc import Callable +from typing import Any, TypeVar + +from tensorflow.autograph.experimental import Feature + +_Type = TypeVar("_Type") + +def set_verbosity(level: int, alsologtostdout: bool = False) -> None: ... +def to_code( + entity: Callable[..., Any], + recursive: bool = True, + experimental_optional_features: None | Feature | tuple[Feature, ...] = None, +) -> str: ... +def to_graph( + entity: _Type, recursive: bool = True, experimental_optional_features: None | Feature | tuple[Feature, ...] = None +) -> _Type: ... +def trace(*args: Any) -> None: ... diff --git a/stubs/tensorflow/tensorflow/autograph/experimental.pyi b/stubs/tensorflow/tensorflow/autograph/experimental.pyi new file mode 100644 index 000000000000..559c230db66f --- /dev/null +++ b/stubs/tensorflow/tensorflow/autograph/experimental.pyi @@ -0,0 +1,30 @@ +from collections.abc import Callable, Iterable +from enum import Enum +from typing import ParamSpec, TypeVar, overload + +import tensorflow as tf +from tensorflow._aliases import Integer + +_Param = ParamSpec("_Param") +_RetType = TypeVar("_RetType") + +class Feature(Enum): + ALL = "ALL" + ASSERT_STATEMENTS = "ASSERT_STATEMENTS" + AUTO_CONTROL_DEPS = "AUTO_CONTROL_DEPS" + BUILTIN_FUNCTIONS = "BUILTIN_FUNCTIONS" + EQUALITY_OPERATORS = "EQUALITY_OPERATORS" + LISTS = "LISTS" + NAME_SCOPES = "NAME_SCOPES" + +@overload +def do_not_convert(func: Callable[_Param, _RetType]) -> Callable[_Param, _RetType]: ... +@overload +def do_not_convert(func: None = None) -> Callable[[Callable[_Param, _RetType]], Callable[_Param, _RetType]]: ... + +def set_loop_options( + parallel_iterations: Integer = ..., + swap_memory: bool = ..., + maximum_iterations: Integer = ..., + shape_invariants: Iterable[tuple[tf.Tensor, tf.TensorShape]] = ..., +) -> None: ... diff --git a/stubs/tensorflow/tensorflow/bitwise.pyi b/stubs/tensorflow/tensorflow/bitwise.pyi new file mode 100644 index 000000000000..10671acebe88 --- /dev/null +++ b/stubs/tensorflow/tensorflow/bitwise.pyi @@ -0,0 +1,41 @@ +from typing import Any, TypeAlias, overload + +import numpy as np +import tensorflow as tf +from tensorflow._aliases import FloatArray, IntArray + +# The alias below is not fully accurate, since TensorFlow casts the inputs, they have some additional +# requirements. For example y needs to be castable into x's dtype. Moreover, x and y cannot both be booleans. +# Properly typing the bitwise functions would be overly complicated and unlikely to provide much benefits +# since most people use Tensors, it was therefore not done. +_BitwiseCompatible: TypeAlias = tf.Tensor | int | FloatArray | IntArray | np.number[Any] + +@overload +def bitwise_and(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_and(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def bitwise_or(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_or(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def bitwise_xor(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def bitwise_xor(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def invert(x: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def invert(x: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def left_shift(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def left_shift(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... + +@overload +def right_shift(x: _BitwiseCompatible, y: _BitwiseCompatible, name: str | None = None) -> tf.Tensor: ... +@overload +def right_shift(x: tf.RaggedTensor, y: tf.RaggedTensor, name: str | None = None) -> tf.RaggedTensor: ... diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi new file mode 100644 index 000000000000..9057959cc005 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_pb2.pyi @@ -0,0 +1,2113 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +This proto file defines messages which represent the HLO module. This is a +full fidelity serialization of the c++ HLO constructs. + +Many of the protos below are simple 1-to-1 serializations of the +corresponding C++ classes, e.g., HloModule, HloComputation, and +HloInstruction. + +FIELD NAMES ARE IMPORTANT + +Unlike most protos, you can't safely change the names of fields, even if you +keep the numeric ids the same. This is because we sometimes serialize these +protos as JSON, which includes the field names in the serialization. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.compiler.xla.xla_data_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _CustomCallSchedule: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CustomCallScheduleEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CustomCallSchedule.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SCHEDULE_NONE: _CustomCallSchedule.ValueType # 0 + SCHEDULE_LATEST: _CustomCallSchedule.ValueType # 1 + SCHEDULE_EARLIEST: _CustomCallSchedule.ValueType # 2 + +class CustomCallSchedule(_CustomCallSchedule, metaclass=_CustomCallScheduleEnumTypeWrapper): ... + +SCHEDULE_NONE: CustomCallSchedule.ValueType # 0 +SCHEDULE_LATEST: CustomCallSchedule.ValueType # 1 +SCHEDULE_EARLIEST: CustomCallSchedule.ValueType # 2 +global___CustomCallSchedule = CustomCallSchedule + +class _CustomCallApiVersion: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CustomCallApiVersionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CustomCallApiVersion.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + API_VERSION_UNSPECIFIED: _CustomCallApiVersion.ValueType # 0 + API_VERSION_ORIGINAL: _CustomCallApiVersion.ValueType # 1 + """The first version of the API, with the following signatures: + + CPU: + void do_custom_call(void* out, const void** in); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len); + """ + API_VERSION_STATUS_RETURNING: _CustomCallApiVersion.ValueType # 2 + """When the ability to return success/failure status was added: + + CPU: + void do_custom_call(void* out, const void** in, + XlaCustomCallStatus* status); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + """ + API_VERSION_STATUS_RETURNING_UNIFIED: _CustomCallApiVersion.ValueType # 3 + """Fixes the API signatures on the CPU side of the version STATUS_RETURNING by + adding the opaque string so that the custom call API is consistent across + CPUs and GPUs. For GPUs, the behaviors invoked by + API_VERSION_STATUS_RETURNING and API_VERSION_STATUS_RETURNING_UNIFIED are + the same. + + CPU: + void do_custom_call(void* out, const void** in, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + + GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + """ + API_VERSION_TYPED_FFI: _CustomCallApiVersion.ValueType # 4 + """Api version implementing XLA runtime custom call calling convention. These + custom calls can be registered as an XLA runtime custom call (1) or as XLA + runtime FFI binding (2). + + This type of custom call uses custom ABI to pass type information along + with custom call arguments. Also it passes buffer arguments together with + data type, sizes and strides. + + Example: (XLA runtime custom call) + + absl::Status DoCustomCall(StridedMemrefView arg, float attr); + + CustomCall::Bind("custom_call") + .Arg() + .Attr("attr") + .To(DoCustomCall); + + (1) xla/runtime/custom_call.h + (2) xla/runtime/ffi/ffi.h + """ + +class CustomCallApiVersion(_CustomCallApiVersion, metaclass=_CustomCallApiVersionEnumTypeWrapper): + """The version of the API used by the custom call function. The signatures for + each version are given below. + TODO(b/189822916): Remove this enum when all clients are migrated to the + status-returning API. + """ + +API_VERSION_UNSPECIFIED: CustomCallApiVersion.ValueType # 0 +API_VERSION_ORIGINAL: CustomCallApiVersion.ValueType # 1 +"""The first version of the API, with the following signatures: + +CPU: + void do_custom_call(void* out, const void** in); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len); +""" +API_VERSION_STATUS_RETURNING: CustomCallApiVersion.ValueType # 2 +"""When the ability to return success/failure status was added: + +CPU: + void do_custom_call(void* out, const void** in, + XlaCustomCallStatus* status); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); +""" +API_VERSION_STATUS_RETURNING_UNIFIED: CustomCallApiVersion.ValueType # 3 +"""Fixes the API signatures on the CPU side of the version STATUS_RETURNING by +adding the opaque string so that the custom call API is consistent across +CPUs and GPUs. For GPUs, the behaviors invoked by +API_VERSION_STATUS_RETURNING and API_VERSION_STATUS_RETURNING_UNIFIED are +the same. + +CPU: + void do_custom_call(void* out, const void** in, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); + +GPU: + void do_custom_call(CUstream stream, void** buffers, + const char* opaque, size_t opaque_len, + XlaCustomCallStatus* status); +""" +API_VERSION_TYPED_FFI: CustomCallApiVersion.ValueType # 4 +"""Api version implementing XLA runtime custom call calling convention. These +custom calls can be registered as an XLA runtime custom call (1) or as XLA +runtime FFI binding (2). + +This type of custom call uses custom ABI to pass type information along +with custom call arguments. Also it passes buffer arguments together with +data type, sizes and strides. + +Example: (XLA runtime custom call) + + absl::Status DoCustomCall(StridedMemrefView arg, float attr); + + CustomCall::Bind("custom_call") + .Arg() + .Attr("attr") + .To(DoCustomCall); + +(1) xla/runtime/custom_call.h +(2) xla/runtime/ffi/ffi.h +""" +global___CustomCallApiVersion = CustomCallApiVersion + +class _Kind: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _KindEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_Kind.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNDEFINED_ALIAS: _Kind.ValueType # 0 + """Define a UNDEFINED_ALIAS equal to zero to get around the default-0 proto3 + behavior and missing has_*() APIs. + """ + MAY_ALIAS: _Kind.ValueType # 1 + """The buffers may or may not alias at runtime.""" + MUST_ALIAS: _Kind.ValueType # 2 + """The buffers must alias at runtime.""" + +class Kind(_Kind, metaclass=_KindEnumTypeWrapper): ... + +UNDEFINED_ALIAS: Kind.ValueType # 0 +"""Define a UNDEFINED_ALIAS equal to zero to get around the default-0 proto3 +behavior and missing has_*() APIs. +""" +MAY_ALIAS: Kind.ValueType # 1 +"""The buffers may or may not alias at runtime.""" +MUST_ALIAS: Kind.ValueType # 2 +"""The buffers must alias at runtime.""" +global___Kind = Kind + +@typing.final +class HloInstructionProto(google.protobuf.message.Message): + """Serialization of HloInstruction. + Next ID: 90 + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class SliceDimensions(google.protobuf.message.Message): + """Describes the [begin, end) index range and stride for slices.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + START_FIELD_NUMBER: builtins.int + LIMIT_FIELD_NUMBER: builtins.int + STRIDE_FIELD_NUMBER: builtins.int + start: builtins.int + limit: builtins.int + stride: builtins.int + def __init__( + self, *, start: builtins.int | None = ..., limit: builtins.int | None = ..., stride: builtins.int | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["limit", b"limit", "start", b"start", "stride", b"stride"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + OPCODE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + METADATA_FIELD_NUMBER: builtins.int + LITERAL_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + FUSION_KIND_FIELD_NUMBER: builtins.int + TUPLE_INDEX_FIELD_NUMBER: builtins.int + DIMENSIONS_FIELD_NUMBER: builtins.int + WINDOW_FIELD_NUMBER: builtins.int + CONVOLUTION_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + FEATURE_GROUP_COUNT_FIELD_NUMBER: builtins.int + BATCH_GROUP_COUNT_FIELD_NUMBER: builtins.int + SLICE_DIMENSIONS_FIELD_NUMBER: builtins.int + EXPONENT_BITS_FIELD_NUMBER: builtins.int + MANTISSA_BITS_FIELD_NUMBER: builtins.int + DYNAMIC_SLICE_SIZES_FIELD_NUMBER: builtins.int + PADDING_CONFIG_FIELD_NUMBER: builtins.int + OUTFEED_CONFIG_FIELD_NUMBER: builtins.int + DISTRIBUTION_FIELD_NUMBER: builtins.int + EPSILON_FIELD_NUMBER: builtins.int + FEATURE_INDEX_FIELD_NUMBER: builtins.int + CHANNEL_ID_FIELD_NUMBER: builtins.int + INFEED_CONFIG_FIELD_NUMBER: builtins.int + CUSTOM_CALL_TARGET_FIELD_NUMBER: builtins.int + OUTFEED_SHAPE_FIELD_NUMBER: builtins.int + DOT_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + FFT_TYPE_FIELD_NUMBER: builtins.int + FFT_LENGTH_FIELD_NUMBER: builtins.int + COMPARISON_DIRECTION_FIELD_NUMBER: builtins.int + GATHER_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + GATHER_SLICE_SIZES_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + OPERAND_IDS_FIELD_NUMBER: builtins.int + CONTROL_PREDECESSOR_IDS_FIELD_NUMBER: builtins.int + CALLED_COMPUTATION_IDS_FIELD_NUMBER: builtins.int + SHARDING_FIELD_NUMBER: builtins.int + BACKEND_CONFIG_FIELD_NUMBER: builtins.int + REPLICA_GROUPS_FIELD_NUMBER: builtins.int + ALL_REDUCE_ID_FIELD_NUMBER: builtins.int + USE_GLOBAL_DEVICE_IDS_FIELD_NUMBER: builtins.int + IS_HOST_TRANSFER_FIELD_NUMBER: builtins.int + IS_STABLE_FIELD_NUMBER: builtins.int + SCATTER_DIMENSION_NUMBERS_FIELD_NUMBER: builtins.int + PRECISION_CONFIG_FIELD_NUMBER: builtins.int + SOURCE_TARGET_PAIRS_FIELD_NUMBER: builtins.int + DOMAIN_ENTRY_SHARDING_FIELD_NUMBER: builtins.int + DOMAIN_EXIT_SHARDING_FIELD_NUMBER: builtins.int + CONSTRAIN_LAYOUT_FIELD_NUMBER: builtins.int + OPERAND_SHAPES_WITH_LAYOUT_FIELD_NUMBER: builtins.int + TRIANGULAR_SOLVE_OPTIONS_FIELD_NUMBER: builtins.int + CHOLESKY_OPTIONS_FIELD_NUMBER: builtins.int + PARAMETER_REPLICATION_FIELD_NUMBER: builtins.int + CUSTOM_CALL_HAS_SIDE_EFFECT_FIELD_NUMBER: builtins.int + OUTPUT_OPERAND_ALIASING_FIELD_NUMBER: builtins.int + CUSTOM_CALL_SCHEDULE_FIELD_NUMBER: builtins.int + DELTA_FIELD_NUMBER: builtins.int + INDICES_ARE_SORTED_FIELD_NUMBER: builtins.int + FRONTEND_ATTRIBUTES_FIELD_NUMBER: builtins.int + UNIQUE_INDICES_FIELD_NUMBER: builtins.int + RNG_ALGORITHM_FIELD_NUMBER: builtins.int + COMPARISON_TYPE_FIELD_NUMBER: builtins.int + IS_CROSS_PROGRAM_PREFETCH_FIELD_NUMBER: builtins.int + CROSS_PROGRAM_PREFETCH_INDEX_FIELD_NUMBER: builtins.int + PADDING_TYPE_FIELD_NUMBER: builtins.int + CUSTOM_CALL_API_VERSION_FIELD_NUMBER: builtins.int + ASYNC_EXECUTION_THREAD_FIELD_NUMBER: builtins.int + K_FIELD_NUMBER: builtins.int + LARGEST_FIELD_NUMBER: builtins.int + STATISTICS_VIZ_FIELD_NUMBER: builtins.int + DOT_SPARSITY_FIELD_NUMBER: builtins.int + COLLECTIVE_DEVICE_LIST_FIELD_NUMBER: builtins.int + ORIGINAL_VALUE_FIELD_NUMBER: builtins.int + IS_COMPOSITE_FIELD_NUMBER: builtins.int + name: builtins.str + opcode: builtins.str + parameter_number: builtins.int + """Parameter number is only present for kParameter.""" + fusion_kind: builtins.str + """Fusion state, only present for kFusion.""" + tuple_index: builtins.int + """Index for kGetTupleElement.""" + feature_group_count: builtins.int + """The number of feature groups. Used for a convolution. Must be a divisor of + the input feature dimension and output feature dimension. If not specified, + it will use a default value of 1. + """ + batch_group_count: builtins.int + exponent_bits: builtins.int + """The bit sizes for a reduce-precision operation.""" + mantissa_bits: builtins.int + outfeed_config: builtins.bytes + """Outfeed configuration information, only present for kOutfeed.""" + distribution: tensorflow.compiler.xla.xla_data_pb2.RandomDistribution.ValueType + """The distribution requested for random number generation. + Only present for kRng. + """ + epsilon: builtins.float + """A small float number added to the variance to avoid divide-by-zero error. + Only present for kBatchNormTraining, kBatchNormInference, and + kBatchNormGrad. + """ + feature_index: builtins.int + """An integer value representing the index of the feature dimension. + Only present for kBatchNormTraining, kBatchNormInference, and + kBatchNormGrad. + """ + channel_id: builtins.int + """Represents a unique identifier for each Send/Recv instruction pair or + optionally for collective instructions (AllReduce, CollectivePermute, + AllToAll). Non-positive channel_id is equivalent to no channel id. + """ + infeed_config: builtins.bytes + """The string representation of the infeed configuration.""" + custom_call_target: builtins.str + """Name of a external target (eg, global symbol) to call, only present for + kCustomCall. + """ + fft_type: tensorflow.compiler.xla.xla_data_pb2.FftType.ValueType + """FFT type (FFT, IFFT, etc).""" + comparison_direction: builtins.str + """Comparison direction only used for kCompare.""" + id: builtins.int + """The id of this instruction.""" + backend_config: builtins.bytes + """Backend configuration for the instruction. Has backend-specific meaning.""" + all_reduce_id: builtins.int + """Deprecated, but keeping it for backward compatibility. Use channel_id. + Non-positive all_reduce_id is equivalent to no all_reduce_id. + """ + use_global_device_ids: builtins.bool + """If true, interprets ids in ReplicaGroup as global device ids, which is + a linearized id of `replica_id * partition_count + partition_id`. + """ + is_host_transfer: builtins.bool + """Whether this Send/Recv instruction transfers data to/from the host. Only + present for Send and Recv instructions and their SendDone and RecvDone + partners. + """ + is_stable: builtins.bool + """Whether this Sort instruction should be stable.""" + constrain_layout: builtins.bool + """For custom call this indicates that the layouts are constrained. If + constrain_layout is true then the 'shape' field must contain a layout, and + 'operand_shapes_with_layout' must contain a shape with layout for each + operand. + """ + custom_call_has_side_effect: builtins.bool + """Whether the kCustomCall instruction has side-effects, only present for + kCustomCall. + """ + custom_call_schedule: global___CustomCallSchedule.ValueType + """Specifies the desired schedule for the custom-call. The field is only + present for custom-call. + """ + delta: builtins.int + """The delta value for kRngGetAndUpdateState.""" + indices_are_sorted: builtins.bool + """Specifies if the gather/scatter indices are guaranteed to be sorted by the + caller. + """ + unique_indices: builtins.bool + """Specifies if all elements updated are guaranteed to be unique by + the caller. + """ + rng_algorithm: tensorflow.compiler.xla.xla_data_pb2.RandomAlgorithm.ValueType + """RNG algorithm used by kRngBitGenerator.""" + comparison_type: builtins.str + """The comparison type used for kCompare.""" + is_cross_program_prefetch: builtins.bool + """Specifies if this is a cross-program-prefetch, used by kCopyStart. + Deprecated and replaced by optional_cross_program_prefetch_index. + """ + cross_program_prefetch_index: builtins.int + padding_type: tensorflow.compiler.xla.xla_data_pb2.PaddingType.ValueType + """If a convolution is dynamic, a dynamic padding type will be specified.""" + custom_call_api_version: global___CustomCallApiVersion.ValueType + """The API version used by the custom call function. This field is only + present for custom-call. + TODO(b/189822916): Remove this field when all clients are migrated to the + status-returning API. + """ + async_execution_thread: builtins.str + """Represents a unique execution thread name for one or more async groups. + Each HLO module may contain a main thread and one or more parallel threads. + Empty async_execution_thread is equivalent to main thread. + """ + k: builtins.int + """Represents the K value for top-k.""" + largest: builtins.bool + """Represents the largest flag for top-k.""" + is_composite: builtins.bool + """Specifies if a call instruction is a composite.""" + @property + def shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: ... + @property + def metadata(self) -> tensorflow.compiler.xla.xla_data_pb2.OpMetadata: ... + @property + def literal(self) -> tensorflow.compiler.xla.xla_data_pb2.LiteralProto: + """Literal, only present for kConstant.""" + + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimensions present for some operations that require reshaping or + broadcasting, including Reshape, Reduce, ReduceWindow, and Reverse. + """ + + @property + def window(self) -> tensorflow.compiler.xla.xla_data_pb2.Window: + """Describes the window in a windowed operation such as convolution.""" + + @property + def convolution_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.ConvolutionDimensionNumbers: + """Describes the dimension numbers used for a convolution.""" + + @property + def slice_dimensions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloInstructionProto.SliceDimensions]: ... + @property + def dynamic_slice_sizes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Describes the [start, start + size) range size for a dynamic slice + ('start' is specified dynamically in the second operand of the operation). + """ + + @property + def padding_config(self) -> tensorflow.compiler.xla.xla_data_pb2.PaddingConfig: + """The padding configuration that describes the edge padding and interior + padding of this pad instruction. Only set for pad instructions. + """ + + @property + def outfeed_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: + """Shape of outfeed request.""" + + @property + def dot_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.DotDimensionNumbers: + """Describes the dimension numbers used for a dot operation""" + + @property + def fft_length(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """FFT length.""" + + @property + def gather_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.GatherDimensionNumbers: + """Gather dimension numbers.""" + + @property + def gather_slice_sizes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def operand_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def control_predecessor_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def called_computation_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def replica_groups( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.ReplicaGroup]: + """Deprecated, but keeping for backward compatibility. + Use collective_device_list. Cross replica op fields. + """ + + @property + def scatter_dimension_numbers(self) -> tensorflow.compiler.xla.xla_data_pb2.ScatterDimensionNumbers: ... + @property + def precision_config(self) -> tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig: + """Precision configuration for the instruction. Has backend-specific meaning.""" + + @property + def source_target_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.SourceTarget]: + """Collective permute field.""" + + @property + def domain_entry_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: + """Sharding for kDomain instructions.""" + + @property + def domain_exit_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def operand_shapes_with_layout( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.ShapeProto]: ... + @property + def triangular_solve_options(self) -> tensorflow.compiler.xla.xla_data_pb2.TriangularSolveOptions: + """Options for TriangularSolve""" + + @property + def cholesky_options(self) -> tensorflow.compiler.xla.xla_data_pb2.CholeskyOptions: + """Options for Cholesky""" + + @property + def parameter_replication(self) -> tensorflow.compiler.xla.xla_data_pb2.ParameterReplication: + """Describes how parameters behave with regards to replicas.""" + + @property + def output_operand_aliasing( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.compiler.xla.xla_data_pb2.OutputOperandAliasing + ]: + """A list of OutputOperandAliasing pairs that specifies aliasing buffers + between output and operands for kCustomCall and kFusion. + """ + + @property + def frontend_attributes(self) -> tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes: + """Frontend attributes to pass to the XLA backend.""" + + @property + def statistics_viz(self) -> tensorflow.compiler.xla.xla_data_pb2.StatisticsViz: + """Represents the information for tracking propagation of values within HLO + graph. + """ + + @property + def dot_sparsity( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.compiler.xla.xla_data_pb2.SparsityDescriptor + ]: + """Sparsity descriptor for dot operation.""" + + @property + def collective_device_list(self) -> tensorflow.compiler.xla.xla_data_pb2.CollectiveDeviceListProto: + """Represents the list of devices that participate in a collective operation.""" + + @property + def original_value(self) -> tensorflow.compiler.xla.xla_data_pb2.OriginalValueProto: + """For HLO value tracking.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + opcode: builtins.str | None = ..., + shape: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + metadata: tensorflow.compiler.xla.xla_data_pb2.OpMetadata | None = ..., + literal: tensorflow.compiler.xla.xla_data_pb2.LiteralProto | None = ..., + parameter_number: builtins.int | None = ..., + fusion_kind: builtins.str | None = ..., + tuple_index: builtins.int | None = ..., + dimensions: collections.abc.Iterable[builtins.int] | None = ..., + window: tensorflow.compiler.xla.xla_data_pb2.Window | None = ..., + convolution_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.ConvolutionDimensionNumbers | None = ..., + feature_group_count: builtins.int | None = ..., + batch_group_count: builtins.int | None = ..., + slice_dimensions: collections.abc.Iterable[global___HloInstructionProto.SliceDimensions] | None = ..., + exponent_bits: builtins.int | None = ..., + mantissa_bits: builtins.int | None = ..., + dynamic_slice_sizes: collections.abc.Iterable[builtins.int] | None = ..., + padding_config: tensorflow.compiler.xla.xla_data_pb2.PaddingConfig | None = ..., + outfeed_config: builtins.bytes | None = ..., + distribution: tensorflow.compiler.xla.xla_data_pb2.RandomDistribution.ValueType | None = ..., + epsilon: builtins.float | None = ..., + feature_index: builtins.int | None = ..., + channel_id: builtins.int | None = ..., + infeed_config: builtins.bytes | None = ..., + custom_call_target: builtins.str | None = ..., + outfeed_shape: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + dot_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.DotDimensionNumbers | None = ..., + fft_type: tensorflow.compiler.xla.xla_data_pb2.FftType.ValueType | None = ..., + fft_length: collections.abc.Iterable[builtins.int] | None = ..., + comparison_direction: builtins.str | None = ..., + gather_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.GatherDimensionNumbers | None = ..., + gather_slice_sizes: collections.abc.Iterable[builtins.int] | None = ..., + id: builtins.int | None = ..., + operand_ids: collections.abc.Iterable[builtins.int] | None = ..., + control_predecessor_ids: collections.abc.Iterable[builtins.int] | None = ..., + called_computation_ids: collections.abc.Iterable[builtins.int] | None = ..., + sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + backend_config: builtins.bytes | None = ..., + replica_groups: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.ReplicaGroup] | None = ..., + all_reduce_id: builtins.int | None = ..., + use_global_device_ids: builtins.bool | None = ..., + is_host_transfer: builtins.bool | None = ..., + is_stable: builtins.bool | None = ..., + scatter_dimension_numbers: tensorflow.compiler.xla.xla_data_pb2.ScatterDimensionNumbers | None = ..., + precision_config: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig | None = ..., + source_target_pairs: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.SourceTarget] | None = ..., + domain_entry_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + domain_exit_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + constrain_layout: builtins.bool | None = ..., + operand_shapes_with_layout: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.ShapeProto] | None = ..., + triangular_solve_options: tensorflow.compiler.xla.xla_data_pb2.TriangularSolveOptions | None = ..., + cholesky_options: tensorflow.compiler.xla.xla_data_pb2.CholeskyOptions | None = ..., + parameter_replication: tensorflow.compiler.xla.xla_data_pb2.ParameterReplication | None = ..., + custom_call_has_side_effect: builtins.bool | None = ..., + output_operand_aliasing: ( + collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.OutputOperandAliasing] | None + ) = ..., + custom_call_schedule: global___CustomCallSchedule.ValueType | None = ..., + delta: builtins.int | None = ..., + indices_are_sorted: builtins.bool | None = ..., + frontend_attributes: tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes | None = ..., + unique_indices: builtins.bool | None = ..., + rng_algorithm: tensorflow.compiler.xla.xla_data_pb2.RandomAlgorithm.ValueType | None = ..., + comparison_type: builtins.str | None = ..., + is_cross_program_prefetch: builtins.bool | None = ..., + cross_program_prefetch_index: builtins.int | None = ..., + padding_type: tensorflow.compiler.xla.xla_data_pb2.PaddingType.ValueType | None = ..., + custom_call_api_version: global___CustomCallApiVersion.ValueType | None = ..., + async_execution_thread: builtins.str | None = ..., + k: builtins.int | None = ..., + largest: builtins.bool | None = ..., + statistics_viz: tensorflow.compiler.xla.xla_data_pb2.StatisticsViz | None = ..., + dot_sparsity: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.SparsityDescriptor] | None = ..., + collective_device_list: tensorflow.compiler.xla.xla_data_pb2.CollectiveDeviceListProto | None = ..., + original_value: tensorflow.compiler.xla.xla_data_pb2.OriginalValueProto | None = ..., + is_composite: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "cholesky_options", + b"cholesky_options", + "collective_device_list", + b"collective_device_list", + "convolution_dimension_numbers", + b"convolution_dimension_numbers", + "cross_program_prefetch_index", + b"cross_program_prefetch_index", + "domain_entry_sharding", + b"domain_entry_sharding", + "domain_exit_sharding", + b"domain_exit_sharding", + "dot_dimension_numbers", + b"dot_dimension_numbers", + "frontend_attributes", + b"frontend_attributes", + "gather_dimension_numbers", + b"gather_dimension_numbers", + "literal", + b"literal", + "metadata", + b"metadata", + "optional_cross_program_prefetch_index", + b"optional_cross_program_prefetch_index", + "original_value", + b"original_value", + "outfeed_shape", + b"outfeed_shape", + "padding_config", + b"padding_config", + "parameter_replication", + b"parameter_replication", + "precision_config", + b"precision_config", + "scatter_dimension_numbers", + b"scatter_dimension_numbers", + "shape", + b"shape", + "sharding", + b"sharding", + "statistics_viz", + b"statistics_viz", + "triangular_solve_options", + b"triangular_solve_options", + "window", + b"window", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "all_reduce_id", + b"all_reduce_id", + "async_execution_thread", + b"async_execution_thread", + "backend_config", + b"backend_config", + "batch_group_count", + b"batch_group_count", + "called_computation_ids", + b"called_computation_ids", + "channel_id", + b"channel_id", + "cholesky_options", + b"cholesky_options", + "collective_device_list", + b"collective_device_list", + "comparison_direction", + b"comparison_direction", + "comparison_type", + b"comparison_type", + "constrain_layout", + b"constrain_layout", + "control_predecessor_ids", + b"control_predecessor_ids", + "convolution_dimension_numbers", + b"convolution_dimension_numbers", + "cross_program_prefetch_index", + b"cross_program_prefetch_index", + "custom_call_api_version", + b"custom_call_api_version", + "custom_call_has_side_effect", + b"custom_call_has_side_effect", + "custom_call_schedule", + b"custom_call_schedule", + "custom_call_target", + b"custom_call_target", + "delta", + b"delta", + "dimensions", + b"dimensions", + "distribution", + b"distribution", + "domain_entry_sharding", + b"domain_entry_sharding", + "domain_exit_sharding", + b"domain_exit_sharding", + "dot_dimension_numbers", + b"dot_dimension_numbers", + "dot_sparsity", + b"dot_sparsity", + "dynamic_slice_sizes", + b"dynamic_slice_sizes", + "epsilon", + b"epsilon", + "exponent_bits", + b"exponent_bits", + "feature_group_count", + b"feature_group_count", + "feature_index", + b"feature_index", + "fft_length", + b"fft_length", + "fft_type", + b"fft_type", + "frontend_attributes", + b"frontend_attributes", + "fusion_kind", + b"fusion_kind", + "gather_dimension_numbers", + b"gather_dimension_numbers", + "gather_slice_sizes", + b"gather_slice_sizes", + "id", + b"id", + "indices_are_sorted", + b"indices_are_sorted", + "infeed_config", + b"infeed_config", + "is_composite", + b"is_composite", + "is_cross_program_prefetch", + b"is_cross_program_prefetch", + "is_host_transfer", + b"is_host_transfer", + "is_stable", + b"is_stable", + "k", + b"k", + "largest", + b"largest", + "literal", + b"literal", + "mantissa_bits", + b"mantissa_bits", + "metadata", + b"metadata", + "name", + b"name", + "opcode", + b"opcode", + "operand_ids", + b"operand_ids", + "operand_shapes_with_layout", + b"operand_shapes_with_layout", + "optional_cross_program_prefetch_index", + b"optional_cross_program_prefetch_index", + "original_value", + b"original_value", + "outfeed_config", + b"outfeed_config", + "outfeed_shape", + b"outfeed_shape", + "output_operand_aliasing", + b"output_operand_aliasing", + "padding_config", + b"padding_config", + "padding_type", + b"padding_type", + "parameter_number", + b"parameter_number", + "parameter_replication", + b"parameter_replication", + "precision_config", + b"precision_config", + "replica_groups", + b"replica_groups", + "rng_algorithm", + b"rng_algorithm", + "scatter_dimension_numbers", + b"scatter_dimension_numbers", + "shape", + b"shape", + "sharding", + b"sharding", + "slice_dimensions", + b"slice_dimensions", + "source_target_pairs", + b"source_target_pairs", + "statistics_viz", + b"statistics_viz", + "triangular_solve_options", + b"triangular_solve_options", + "tuple_index", + b"tuple_index", + "unique_indices", + b"unique_indices", + "use_global_device_ids", + b"use_global_device_ids", + "window", + b"window", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_cross_program_prefetch_index", b"optional_cross_program_prefetch_index"] + ) -> typing.Literal["cross_program_prefetch_index"] | None: ... + +global___HloInstructionProto = HloInstructionProto + +@typing.final +class HloComputationProto(google.protobuf.message.Message): + """Serialization of HloComputation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + INSTRUCTIONS_FIELD_NUMBER: builtins.int + PROGRAM_SHAPE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + ROOT_ID_FIELD_NUMBER: builtins.int + IS_FUSION_COMPUTATION_FIELD_NUMBER: builtins.int + EXECUTION_THREAD_FIELD_NUMBER: builtins.int + name: builtins.str + id: builtins.int + """The id of this computation.""" + root_id: builtins.int + """The id of the root of the computation.""" + is_fusion_computation: builtins.bool + """Whether this is a fusion computation. Fusion computations should use this + to determine whether they are a fusion in CreateFromProto since the + parent fusion_instruction_ may get removed and be nullptr. + """ + execution_thread: builtins.str + """The name of execution thread this computation belongs to.""" + @property + def instructions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloInstructionProto]: + """The array of instructions is always in a valid dependency order, where + operands appear before their users. + """ + + @property + def program_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: + """The program shape (with layout) of this computation.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + instructions: collections.abc.Iterable[global___HloInstructionProto] | None = ..., + program_shape: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + id: builtins.int | None = ..., + root_id: builtins.int | None = ..., + is_fusion_computation: builtins.bool | None = ..., + execution_thread: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["program_shape", b"program_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "execution_thread", + b"execution_thread", + "id", + b"id", + "instructions", + b"instructions", + "is_fusion_computation", + b"is_fusion_computation", + "name", + b"name", + "program_shape", + b"program_shape", + "root_id", + b"root_id", + ], + ) -> None: ... + +global___HloComputationProto = HloComputationProto + +@typing.final +class HloScheduleProto(google.protobuf.message.Message): + """Serialization of an HLO schedule. An HLO schedule contains a total order of + instructions for each non-fusion computation in the module. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class InstructionSequence(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INSTRUCTION_IDS_FIELD_NUMBER: builtins.int + @property + def instruction_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, instruction_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["instruction_ids", b"instruction_ids"]) -> None: ... + + @typing.final + class SequencesEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.int + @property + def value(self) -> global___HloScheduleProto.InstructionSequence: ... + def __init__( + self, *, key: builtins.int | None = ..., value: global___HloScheduleProto.InstructionSequence | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + SEQUENCES_FIELD_NUMBER: builtins.int + @property + def sequences( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.int, global___HloScheduleProto.InstructionSequence]: + """Map from computation id to sequence.""" + + def __init__( + self, *, sequences: collections.abc.Mapping[builtins.int, global___HloScheduleProto.InstructionSequence] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["sequences", b"sequences"]) -> None: ... + +global___HloScheduleProto = HloScheduleProto + +@typing.final +class HloInputOutputAliasProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class AliasEntryProto(google.protobuf.message.Message): + """The following proto describes a pair of aliased an input + (described by parameter number and a ShapeIndex of the parameter) + and an output (described by a ShapeIndex of the root + instruction). For example: + + entry = { + output_shape_index={1}, + parameter_number=0, + parameter_shape_index={1, 2}, + } + + This entry indicates that the first parameter's {1, 2} element is + aliased with the {1} element of the root instruction. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + KIND_FIELD_NUMBER: builtins.int + parameter_number: builtins.int + """Number of the parameter in entry computation.""" + kind: global___Kind.ValueType + """The kind of alias to be setup.""" + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the root hlo.""" + + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the parameter instruction.""" + + def __init__( + self, + *, + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + kind: global___Kind.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "kind", + b"kind", + "output_shape_index", + b"output_shape_index", + "parameter_number", + b"parameter_number", + "parameter_shape_index", + b"parameter_shape_index", + ], + ) -> None: ... + + ENTRIES_FIELD_NUMBER: builtins.int + @property + def entries( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloInputOutputAliasProto.AliasEntryProto + ]: ... + def __init__( + self, *, entries: collections.abc.Iterable[global___HloInputOutputAliasProto.AliasEntryProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["entries", b"entries"]) -> None: ... + +global___HloInputOutputAliasProto = HloInputOutputAliasProto + +@typing.final +class HloBufferDonorProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class BufferDonorEntryProto(google.protobuf.message.Message): + """The following proto describes an input (described by parameter number and a + ShapeIndex of the parameter) that can donate its butter to any output + tensor. It is similar to HloInputOutputAliasProto, but without a paired + output. For example: + + entry = { + parameter_number=0, + parameter_shape_index={1, 2}, + } + + This entry indicates that the first parameter's {1, 2} element can donate + its buffer. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + parameter_number: builtins.int + """Number of the parameter in entry computation.""" + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ShapeIndex of the parameter instruction.""" + + def __init__( + self, + *, + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "parameter_number", b"parameter_number", "parameter_shape_index", b"parameter_shape_index" + ], + ) -> None: ... + + ENTRIES_FIELD_NUMBER: builtins.int + @property + def entries( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloBufferDonorProto.BufferDonorEntryProto + ]: ... + def __init__( + self, *, entries: collections.abc.Iterable[global___HloBufferDonorProto.BufferDonorEntryProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["entries", b"entries"]) -> None: ... + +global___HloBufferDonorProto = HloBufferDonorProto + +@typing.final +class CrossProgramPrefetch(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETER_FIELD_NUMBER: builtins.int + INDEX_FIELD_NUMBER: builtins.int + OFFSET_FIELD_NUMBER: builtins.int + parameter: builtins.int + offset: builtins.int + @property + def index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + parameter: builtins.int | None = ..., + index: collections.abc.Iterable[builtins.int] | None = ..., + offset: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["index", b"index", "offset", b"offset", "parameter", b"parameter"] + ) -> None: ... + +global___CrossProgramPrefetch = CrossProgramPrefetch + +@typing.final +class StackFrameIndexProto(google.protobuf.message.Message): + """Serialization of stack frames index representations. + Stack frames index presented in four flat arrays: + 1. File names array. + 2. Function names array. + 3. File location array. + 4. Frame array. + All reference ids in sub-protos are 1-based positions of the + entity in the flat array. + Ids are 1-based to keep 0 value as representation of non-set property. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FileLocation(google.protobuf.message.Message): + """Serialization of file position.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_NAME_ID_FIELD_NUMBER: builtins.int + FUNCTION_NAME_ID_FIELD_NUMBER: builtins.int + LINE_FIELD_NUMBER: builtins.int + COLUMN_FIELD_NUMBER: builtins.int + file_name_id: builtins.int + """1-based position of file name.""" + function_name_id: builtins.int + """1-based position of function name.""" + line: builtins.int + """Line number.""" + column: builtins.int + """Column number.""" + def __init__( + self, + *, + file_name_id: builtins.int | None = ..., + function_name_id: builtins.int | None = ..., + line: builtins.int | None = ..., + column: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "column", b"column", "file_name_id", b"file_name_id", "function_name_id", b"function_name_id", "line", b"line" + ], + ) -> None: ... + + @typing.final + class StackFrame(google.protobuf.message.Message): + """Serialization of frame.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FILE_LOCATION_ID_FIELD_NUMBER: builtins.int + PARENT_FRAME_ID_FIELD_NUMBER: builtins.int + file_location_id: builtins.int + """1-based position of file location.""" + parent_frame_id: builtins.int + """1-based position of the parent frame.""" + def __init__( + self, *, file_location_id: builtins.int | None = ..., parent_frame_id: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["file_location_id", b"file_location_id", "parent_frame_id", b"parent_frame_id"] + ) -> None: ... + + FILE_NAMES_FIELD_NUMBER: builtins.int + FUNCTION_NAMES_FIELD_NUMBER: builtins.int + FILE_LOCATIONS_FIELD_NUMBER: builtins.int + STACK_FRAMES_FIELD_NUMBER: builtins.int + @property + def file_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Flat index array of file names.""" + + @property + def function_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Flat index array of function names.""" + + @property + def file_locations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___StackFrameIndexProto.FileLocation]: + """Flat index array of file locations.""" + + @property + def stack_frames( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___StackFrameIndexProto.StackFrame]: + """Flat index array of frames.""" + + def __init__( + self, + *, + file_names: collections.abc.Iterable[builtins.str] | None = ..., + function_names: collections.abc.Iterable[builtins.str] | None = ..., + file_locations: collections.abc.Iterable[global___StackFrameIndexProto.FileLocation] | None = ..., + stack_frames: collections.abc.Iterable[global___StackFrameIndexProto.StackFrame] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "file_locations", + b"file_locations", + "file_names", + b"file_names", + "function_names", + b"function_names", + "stack_frames", + b"stack_frames", + ], + ) -> None: ... + +global___StackFrameIndexProto = StackFrameIndexProto + +@typing.final +class HloModuleProto(google.protobuf.message.Message): + """Serialization of HloModule.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ProfileType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ProfileTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HloModuleProto._ProfileType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: HloModuleProto._ProfileType.ValueType # 0 + FLAG: HloModuleProto._ProfileType.ValueType # 1 + FUSION: HloModuleProto._ProfileType.ValueType # 2 + LAYOUT: HloModuleProto._ProfileType.ValueType # 3 + DOT: HloModuleProto._ProfileType.ValueType # 4 + FLAGNET: HloModuleProto._ProfileType.ValueType # 5 + + class ProfileType(_ProfileType, metaclass=_ProfileTypeEnumTypeWrapper): + """The type of optimization profile in use for module-level optimizations.""" + + INVALID: HloModuleProto.ProfileType.ValueType # 0 + FLAG: HloModuleProto.ProfileType.ValueType # 1 + FUSION: HloModuleProto.ProfileType.ValueType # 2 + LAYOUT: HloModuleProto.ProfileType.ValueType # 3 + DOT: HloModuleProto.ProfileType.ValueType # 4 + FLAGNET: HloModuleProto.ProfileType.ValueType # 5 + + @typing.final + class ProfileInfo(google.protobuf.message.Message): + """Information about the optimization profile that this module contains.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PROFILE_TYPE_FIELD_NUMBER: builtins.int + RELATIVE_SPEEDUP_FIELD_NUMBER: builtins.int + PROFILE_SOURCE_FIELD_NUMBER: builtins.int + COMPILATION_EVENT_FIELD_NUMBER: builtins.int + FINGERPRINT_FIELD_NUMBER: builtins.int + profile_type: global___HloModuleProto.ProfileType.ValueType + """The optimization profiles that this module contains.""" + relative_speedup: builtins.float + """Speedup of tuned config compared to default config.""" + profile_source: tensorflow.compiler.xla.xla_data_pb2.ProfileSource.ValueType + """The source of the optimization profile that this module contains.""" + compilation_event: tensorflow.compiler.xla.xla_data_pb2.CompilationEvent.ValueType + """The compilation event that triggered the use of the profile.""" + fingerprint: builtins.str + """The fingerprint of the unoptimized module this profile was applied to.""" + def __init__( + self, + *, + profile_type: global___HloModuleProto.ProfileType.ValueType | None = ..., + relative_speedup: builtins.float | None = ..., + profile_source: tensorflow.compiler.xla.xla_data_pb2.ProfileSource.ValueType | None = ..., + compilation_event: tensorflow.compiler.xla.xla_data_pb2.CompilationEvent.ValueType | None = ..., + fingerprint: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_event", + b"compilation_event", + "fingerprint", + b"fingerprint", + "profile_source", + b"profile_source", + "profile_type", + b"profile_type", + "relative_speedup", + b"relative_speedup", + ], + ) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_NAME_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_ID_FIELD_NUMBER: builtins.int + COMPUTATIONS_FIELD_NUMBER: builtins.int + HOST_PROGRAM_SHAPE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + SCHEDULE_FIELD_NUMBER: builtins.int + INPUT_OUTPUT_ALIAS_FIELD_NUMBER: builtins.int + BUFFER_DONOR_FIELD_NUMBER: builtins.int + CROSS_PROGRAM_PREFETCHES_FIELD_NUMBER: builtins.int + IS_DYNAMIC_FIELD_NUMBER: builtins.int + SPMD_OUTPUT_SHARDING_FIELD_NUMBER: builtins.int + SPMD_PARAMETERS_SHARDINGS_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + PROFILE_INFO_FIELD_NUMBER: builtins.int + DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + STACK_FRAME_INDEX_FIELD_NUMBER: builtins.int + FRONTEND_ATTRIBUTES_FIELD_NUMBER: builtins.int + name: builtins.str + entry_computation_name: builtins.str + entry_computation_id: builtins.int + id: builtins.int + """The id of this module.""" + is_dynamic: builtins.bool + """True if the module contains dynamic computation.""" + use_auto_spmd_partitioning: builtins.bool + """Uses AutoSharding pass or not.""" + @property + def computations(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloComputationProto]: + """The array of computations is always in a valid dependency order, where + callees appear before their callers. + """ + + @property + def host_program_shape(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: + """The host program shape (with layout) of the entry computation.""" + + @property + def schedule(self) -> global___HloScheduleProto: + """The schedule for this module.""" + + @property + def input_output_alias(self) -> global___HloInputOutputAliasProto: + """Describes alias information between inputs and outputs.""" + + @property + def buffer_donor(self) -> global___HloBufferDonorProto: + """Describes the information of input buffer donors.""" + + @property + def cross_program_prefetches( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CrossProgramPrefetch]: ... + @property + def spmd_output_sharding(self) -> tensorflow.compiler.xla.xla_data_pb2.OpSharding: ... + @property + def spmd_parameters_shardings( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.OpSharding]: ... + @property + def profile_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleProto.ProfileInfo]: + """Profile information for the HLO module.""" + + @property + def device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """DeviceAssignment object information.""" + + @property + def stack_frame_index(self) -> global___StackFrameIndexProto: + """Stack frames index.""" + + @property + def frontend_attributes(self) -> tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes: + """Frontend attributes to pass to the XLA backend.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + entry_computation_name: builtins.str | None = ..., + entry_computation_id: builtins.int | None = ..., + computations: collections.abc.Iterable[global___HloComputationProto] | None = ..., + host_program_shape: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + id: builtins.int | None = ..., + schedule: global___HloScheduleProto | None = ..., + input_output_alias: global___HloInputOutputAliasProto | None = ..., + buffer_donor: global___HloBufferDonorProto | None = ..., + cross_program_prefetches: collections.abc.Iterable[global___CrossProgramPrefetch] | None = ..., + is_dynamic: builtins.bool | None = ..., + spmd_output_sharding: tensorflow.compiler.xla.xla_data_pb2.OpSharding | None = ..., + spmd_parameters_shardings: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.OpSharding] | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + profile_info: collections.abc.Iterable[global___HloModuleProto.ProfileInfo] | None = ..., + device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + stack_frame_index: global___StackFrameIndexProto | None = ..., + frontend_attributes: tensorflow.compiler.xla.xla_data_pb2.FrontendAttributes | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "buffer_donor", + b"buffer_donor", + "device_assignment", + b"device_assignment", + "frontend_attributes", + b"frontend_attributes", + "host_program_shape", + b"host_program_shape", + "input_output_alias", + b"input_output_alias", + "schedule", + b"schedule", + "spmd_output_sharding", + b"spmd_output_sharding", + "stack_frame_index", + b"stack_frame_index", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_donor", + b"buffer_donor", + "computations", + b"computations", + "cross_program_prefetches", + b"cross_program_prefetches", + "device_assignment", + b"device_assignment", + "entry_computation_id", + b"entry_computation_id", + "entry_computation_name", + b"entry_computation_name", + "frontend_attributes", + b"frontend_attributes", + "host_program_shape", + b"host_program_shape", + "id", + b"id", + "input_output_alias", + b"input_output_alias", + "is_dynamic", + b"is_dynamic", + "name", + b"name", + "profile_info", + b"profile_info", + "schedule", + b"schedule", + "spmd_output_sharding", + b"spmd_output_sharding", + "spmd_parameters_shardings", + b"spmd_parameters_shardings", + "stack_frame_index", + b"stack_frame_index", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + ], + ) -> None: ... + +global___HloModuleProto = HloModuleProto + +@typing.final +class LogicalBufferProto(google.protobuf.message.Message): + """Serialization of LogicalBuffer.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Location(google.protobuf.message.Message): + """Location represents an instruction and its shape index, which uniquely + identifies a point where a buffer is needed. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + INSTRUCTION_ID_FIELD_NUMBER: builtins.int + SHAPE_INDEX_FIELD_NUMBER: builtins.int + instruction_name: builtins.str + """TODO(b/239098765): Remove instruction_name and computation_name.""" + instruction_id: builtins.int + @property + def shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + instruction_name: builtins.str | None = ..., + instruction_id: builtins.int | None = ..., + shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_id", b"instruction_id", "instruction_name", b"instruction_name", "shape_index", b"shape_index" + ], + ) -> None: ... + + ID_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + DEFINED_AT_FIELD_NUMBER: builtins.int + COLOR_FIELD_NUMBER: builtins.int + id: builtins.int + size: builtins.int + color: builtins.int + @property + def defined_at(self) -> global___LogicalBufferProto.Location: + """The location where the buffer is defined.""" + + def __init__( + self, + *, + id: builtins.int | None = ..., + size: builtins.int | None = ..., + defined_at: global___LogicalBufferProto.Location | None = ..., + color: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["defined_at", b"defined_at"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["color", b"color", "defined_at", b"defined_at", "id", b"id", "size", b"size"] + ) -> None: ... + +global___LogicalBufferProto = LogicalBufferProto + +@typing.final +class BufferAllocationProto(google.protobuf.message.Message): + """Serialization of BufferAllocation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Assigned(google.protobuf.message.Message): + """Assigned represents a single LogicalBuffer that is assigned to this + BufferAllocation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOGICAL_BUFFER_ID_FIELD_NUMBER: builtins.int + OFFSET_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + logical_buffer_id: builtins.int + offset: builtins.int + size: builtins.int + def __init__( + self, + *, + logical_buffer_id: builtins.int | None = ..., + offset: builtins.int | None = ..., + size: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["logical_buffer_id", b"logical_buffer_id", "offset", b"offset", "size", b"size"] + ) -> None: ... + + INDEX_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + IS_THREAD_LOCAL_FIELD_NUMBER: builtins.int + IS_TUPLE_FIELD_NUMBER: builtins.int + IS_ENTRY_COMPUTATION_PARAMETER_FIELD_NUMBER: builtins.int + IS_CONSTANT_FIELD_NUMBER: builtins.int + PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + MAYBE_LIVE_OUT_FIELD_NUMBER: builtins.int + COLOR_FIELD_NUMBER: builtins.int + ASSIGNED_FIELD_NUMBER: builtins.int + index: builtins.int + size: builtins.int + is_thread_local: builtins.bool + is_tuple: builtins.bool + is_entry_computation_parameter: builtins.bool + is_constant: builtins.bool + parameter_number: builtins.int + maybe_live_out: builtins.bool + color: builtins.int + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def assigned( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAllocationProto.Assigned]: ... + def __init__( + self, + *, + index: builtins.int | None = ..., + size: builtins.int | None = ..., + is_thread_local: builtins.bool | None = ..., + is_tuple: builtins.bool | None = ..., + is_entry_computation_parameter: builtins.bool | None = ..., + is_constant: builtins.bool | None = ..., + parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + maybe_live_out: builtins.bool | None = ..., + color: builtins.int | None = ..., + assigned: collections.abc.Iterable[global___BufferAllocationProto.Assigned] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "assigned", + b"assigned", + "color", + b"color", + "index", + b"index", + "is_constant", + b"is_constant", + "is_entry_computation_parameter", + b"is_entry_computation_parameter", + "is_thread_local", + b"is_thread_local", + "is_tuple", + b"is_tuple", + "maybe_live_out", + b"maybe_live_out", + "parameter_number", + b"parameter_number", + "parameter_shape_index", + b"parameter_shape_index", + "size", + b"size", + ], + ) -> None: ... + +global___BufferAllocationProto = BufferAllocationProto + +@typing.final +class HeapSimulatorTrace(google.protobuf.message.Message): + """A trace of a HeapSimulator run.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Event(google.protobuf.message.Message): + """The trace includes a list of events, where each event describes one action + performed by the heap simulator. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Kind: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _KindEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HeapSimulatorTrace.Event._Kind.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ALLOC: HeapSimulatorTrace.Event._Kind.ValueType # 0 + """A memory region was allocated for the buffer.""" + FREE: HeapSimulatorTrace.Event._Kind.ValueType # 1 + """A memory region was freed for the buffer.""" + SHARE_WITH: HeapSimulatorTrace.Event._Kind.ValueType # 2 + """A buffer was shared with another (canonical) buffer. This is similar to + ALLOC, except that instead of allocating a new region of memory, the + memory region of the canonical buffer is directly re-used. Multiple + buffers may share with the same canonical buffer. The lifetime of the + canonical buffer is extended to the union of all lifetimes. + """ + + class Kind(_Kind, metaclass=_KindEnumTypeWrapper): ... + ALLOC: HeapSimulatorTrace.Event.Kind.ValueType # 0 + """A memory region was allocated for the buffer.""" + FREE: HeapSimulatorTrace.Event.Kind.ValueType # 1 + """A memory region was freed for the buffer.""" + SHARE_WITH: HeapSimulatorTrace.Event.Kind.ValueType # 2 + """A buffer was shared with another (canonical) buffer. This is similar to + ALLOC, except that instead of allocating a new region of memory, the + memory region of the canonical buffer is directly re-used. Multiple + buffers may share with the same canonical buffer. The lifetime of the + canonical buffer is extended to the union of all lifetimes. + """ + + KIND_FIELD_NUMBER: builtins.int + BUFFER_ID_FIELD_NUMBER: builtins.int + COMPUTATION_NAME_FIELD_NUMBER: builtins.int + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + SHARE_WITH_CANONICAL_ID_FIELD_NUMBER: builtins.int + kind: global___HeapSimulatorTrace.Event.Kind.ValueType + buffer_id: builtins.int + """The id of the LogicalBuffer that the event applies to.""" + computation_name: builtins.str + """The HloInstruction that the simulation was processing that caused this + event to occur, identified by its computation and instruction name. E.g. + buffers defined by instruction A are allocated when processing A. + """ + instruction_name: builtins.str + share_with_canonical_id: builtins.int + """The id of the canonical LogicalBuffer that the buffer shares with. Only + set for SHARE_WITH events. + """ + def __init__( + self, + *, + kind: global___HeapSimulatorTrace.Event.Kind.ValueType | None = ..., + buffer_id: builtins.int | None = ..., + computation_name: builtins.str | None = ..., + instruction_name: builtins.str | None = ..., + share_with_canonical_id: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_id", + b"buffer_id", + "computation_name", + b"computation_name", + "instruction_name", + b"instruction_name", + "kind", + b"kind", + "share_with_canonical_id", + b"share_with_canonical_id", + ], + ) -> None: ... + + EVENTS_FIELD_NUMBER: builtins.int + WHOLE_MODULE_SIMULATION_FIELD_NUMBER: builtins.int + BUFFER_ALLOCATION_INDEX_FIELD_NUMBER: builtins.int + whole_module_simulation: builtins.bool + buffer_allocation_index: builtins.int + @property + def events( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HeapSimulatorTrace.Event]: ... + def __init__( + self, + *, + events: collections.abc.Iterable[global___HeapSimulatorTrace.Event] | None = ..., + whole_module_simulation: builtins.bool | None = ..., + buffer_allocation_index: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_allocation_index", + b"buffer_allocation_index", + "events", + b"events", + "whole_module_simulation", + b"whole_module_simulation", + ], + ) -> None: ... + +global___HeapSimulatorTrace = HeapSimulatorTrace + +@typing.final +class HloModuleGroupProto(google.protobuf.message.Message): + """An abstraction representing a set of HLO module built to run concurrently + across different devices. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + HLO_MODULES_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def hlo_modules(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleProto]: ... + def __init__( + self, *, name: builtins.str | None = ..., hlo_modules: collections.abc.Iterable[global___HloModuleProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["hlo_modules", b"hlo_modules", "name", b"name"]) -> None: ... + +global___HloModuleGroupProto = HloModuleGroupProto + +@typing.final +class BufferAssignmentProto(google.protobuf.message.Message): + """Serialization of BufferAssignment.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class BufferAlias(google.protobuf.message.Message): + """Alias represents a source LogicalBuffer, and the buffer location that + aliases it. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOURCE_BUFFER_ID_FIELD_NUMBER: builtins.int + LOCATION_FIELD_NUMBER: builtins.int + source_buffer_id: builtins.int + @property + def location(self) -> global___LogicalBufferProto.Location: ... + def __init__( + self, *, source_buffer_id: builtins.int | None = ..., location: global___LogicalBufferProto.Location | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["location", b"location"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["location", b"location", "source_buffer_id", b"source_buffer_id"] + ) -> None: ... + + LOGICAL_BUFFERS_FIELD_NUMBER: builtins.int + BUFFER_ALIASES_FIELD_NUMBER: builtins.int + BUFFER_ALLOCATIONS_FIELD_NUMBER: builtins.int + HEAP_SIMULATOR_TRACES_FIELD_NUMBER: builtins.int + @property + def logical_buffers( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___LogicalBufferProto]: ... + @property + def buffer_aliases( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAssignmentProto.BufferAlias]: ... + @property + def buffer_allocations( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BufferAllocationProto]: ... + @property + def heap_simulator_traces( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HeapSimulatorTrace]: ... + def __init__( + self, + *, + logical_buffers: collections.abc.Iterable[global___LogicalBufferProto] | None = ..., + buffer_aliases: collections.abc.Iterable[global___BufferAssignmentProto.BufferAlias] | None = ..., + buffer_allocations: collections.abc.Iterable[global___BufferAllocationProto] | None = ..., + heap_simulator_traces: collections.abc.Iterable[global___HeapSimulatorTrace] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "buffer_aliases", + b"buffer_aliases", + "buffer_allocations", + b"buffer_allocations", + "heap_simulator_traces", + b"heap_simulator_traces", + "logical_buffers", + b"logical_buffers", + ], + ) -> None: ... + +global___BufferAssignmentProto = BufferAssignmentProto + +@typing.final +class HloProto(google.protobuf.message.Message): + """Grouping message that contains all of the information above.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_MODULE_FIELD_NUMBER: builtins.int + BUFFER_ASSIGNMENT_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> global___HloModuleProto: ... + @property + def buffer_assignment(self) -> global___BufferAssignmentProto: ... + def __init__( + self, *, hlo_module: global___HloModuleProto | None = ..., buffer_assignment: global___BufferAssignmentProto | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["buffer_assignment", b"buffer_assignment", "hlo_module", b"hlo_module"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["buffer_assignment", b"buffer_assignment", "hlo_module", b"hlo_module"] + ) -> None: ... + +global___HloProto = HloProto + +@typing.final +class HloSnapshot(google.protobuf.message.Message): + """Encapsulates HloProto together with the arguments, result, and + execution_platform. This message is used for purposes such as + analysis/replay/file-storage. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_FIELD_NUMBER: builtins.int + ARGUMENTS_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + EXECUTION_PLATFORM_FIELD_NUMBER: builtins.int + execution_platform: builtins.str + """The name of the platform used to run the graph.""" + @property + def hlo(self) -> global___HloProto: + """The hlo graph.""" + + @property + def arguments( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.LiteralProto]: + """The arguments passed to the graph.""" + + @property + def result(self) -> tensorflow.compiler.xla.xla_data_pb2.LiteralProto: + """The result of the graph.""" + + def __init__( + self, + *, + hlo: global___HloProto | None = ..., + arguments: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.LiteralProto] | None = ..., + result: tensorflow.compiler.xla.xla_data_pb2.LiteralProto | None = ..., + execution_platform: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["hlo", b"hlo", "result", b"result"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "arguments", b"arguments", "execution_platform", b"execution_platform", "hlo", b"hlo", "result", b"result" + ], + ) -> None: ... + +global___HloSnapshot = HloSnapshot + +@typing.final +class HloModuleMetadataProto(google.protobuf.message.Message): + """Metadata for an HLO module. Dumped after HLO passes and before LLO lowering + with filename module_####.metadata.textproto, where #### is + canonical_module_id. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CANONICAL_MODULE_ID_FIELD_NUMBER: builtins.int + MODULE_GROUP_NAME_FIELD_NUMBER: builtins.int + ORIGINAL_MODULE_ID_FIELD_NUMBER: builtins.int + PARTITIONED_MODULE_IDS_FIELD_NUMBER: builtins.int + PASS_METADATA_FIELD_NUMBER: builtins.int + canonical_module_id: builtins.int + """Uniquely identifies an HloModuleMetadata. Equal to the first unique_id + of the module (a module may go through multiple unique_ids). If a module + is partitioned into multiple modules, those modules will each have a new + HloModuleMetadata with a different canonical_module_id. + """ + module_group_name: builtins.str + """Name of the module group that the module is part of.""" + original_module_id: builtins.int + """The canonical module id of the module that this one is partitioned from, + if applicable. + """ + @property + def partitioned_module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The canonical module ids of the modules that this one is partitioned into, + if applicable. + """ + + @property + def pass_metadata(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloPassMetadata]: + """Metadata for the HLO passes that are run on the module.""" + + def __init__( + self, + *, + canonical_module_id: builtins.int | None = ..., + module_group_name: builtins.str | None = ..., + original_module_id: builtins.int | None = ..., + partitioned_module_ids: collections.abc.Iterable[builtins.int] | None = ..., + pass_metadata: collections.abc.Iterable[global___HloPassMetadata] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "canonical_module_id", + b"canonical_module_id", + "module_group_name", + b"module_group_name", + "original_module_id", + b"original_module_id", + "partitioned_module_ids", + b"partitioned_module_ids", + "pass_metadata", + b"pass_metadata", + ], + ) -> None: ... + +global___HloModuleMetadataProto = HloModuleMetadataProto + +@typing.final +class HloPassMetadata(google.protobuf.message.Message): + """Metadata for one run of an HLO pass on a module. Provides more information + when processing debug dumps of HloProtos about the order of HLO passes and + various other stats like duration. `pass_id` may also be used to identify a + particular run of a pass in debug info that propagates through stages of + compilation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PASS_ID_FIELD_NUMBER: builtins.int + PASS_NAME_FIELD_NUMBER: builtins.int + PIPELINE_NAME_FIELD_NUMBER: builtins.int + DUMP_FILENAMES_FIELD_NUMBER: builtins.int + MODULE_CHANGED_FIELD_NUMBER: builtins.int + MODULE_ID_FIELD_NUMBER: builtins.int + MODULE_GROUP_MODULE_IDS_FIELD_NUMBER: builtins.int + START_TIMESTAMP_USEC_FIELD_NUMBER: builtins.int + END_TIMESTAMP_USEC_FIELD_NUMBER: builtins.int + CUSTOM_METADATA_FIELD_NUMBER: builtins.int + pass_id: builtins.int + """For a given module, pass_id uniquely identifies a run of an HLO pass on + that module. Note that a pass_id may not always refer to the same pass + because the order of passes during compilation may change. For finding + metadata for a particular pass, pass_name and pipeline_name would be more + reliable, although note that they may not be unique. + """ + pass_name: builtins.str + pipeline_name: builtins.str + module_changed: builtins.bool + """Return value of pass.Run(). True if this pass changed the module, or, in + the case where the module was run through this pass as part of a module + group, true if this pass changed any module in the same module group. + """ + module_id: builtins.int + """The unique_id of the module that this pass is run on. May be different from + the canonical_module_id of the HloModuleMetadata that this HloPassMetadata + is inside. + """ + start_timestamp_usec: builtins.int + """Timestamp before and after the pass is run. Note they may be equal.""" + end_timestamp_usec: builtins.int + @property + def dump_filenames(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Filenames of the dumps of the module after this pass ran. Module may be + dumped in multiple formats, and the order of formats in this field will + stay consistent across passes. + """ + + @property + def module_group_module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """If the module went through this pass as part of a module group, this is + set as the ids of all the modules in the module group. Empty otherwise. + """ + + @property + def custom_metadata(self) -> google.protobuf.any_pb2.Any: + """Custom metadata for the pass.""" + + def __init__( + self, + *, + pass_id: builtins.int | None = ..., + pass_name: builtins.str | None = ..., + pipeline_name: builtins.str | None = ..., + dump_filenames: collections.abc.Iterable[builtins.str] | None = ..., + module_changed: builtins.bool | None = ..., + module_id: builtins.int | None = ..., + module_group_module_ids: collections.abc.Iterable[builtins.int] | None = ..., + start_timestamp_usec: builtins.int | None = ..., + end_timestamp_usec: builtins.int | None = ..., + custom_metadata: google.protobuf.any_pb2.Any | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["custom_metadata", b"custom_metadata"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "custom_metadata", + b"custom_metadata", + "dump_filenames", + b"dump_filenames", + "end_timestamp_usec", + b"end_timestamp_usec", + "module_changed", + b"module_changed", + "module_group_module_ids", + b"module_group_module_ids", + "module_id", + b"module_id", + "pass_id", + b"pass_id", + "pass_name", + b"pass_name", + "pipeline_name", + b"pipeline_name", + "start_timestamp_usec", + b"start_timestamp_usec", + ], + ) -> None: ... + +global___HloPassMetadata = HloPassMetadata diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi new file mode 100644 index 000000000000..5699e8cc13fc --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/hlo_profile_printer_data_pb2.pyi @@ -0,0 +1,187 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2018 The OpenXLA 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 builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class HloProfilePrinterData(google.protobuf.message.Message): + """Describes how to pretty-print a profile counter array gathered for a specific + HloModule. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class HloInstructionInfo(google.protobuf.message.Message): + """Pretty-printer information about an HloInstruction.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LONG_NAME_FIELD_NUMBER: builtins.int + SHORT_NAME_FIELD_NUMBER: builtins.int + CATEGORY_FIELD_NUMBER: builtins.int + FLOP_COUNT_FIELD_NUMBER: builtins.int + TRANSCENDENTAL_COUNT_FIELD_NUMBER: builtins.int + BYTES_ACCESSED_FIELD_NUMBER: builtins.int + OPTIMAL_SECONDS_FIELD_NUMBER: builtins.int + PROFILE_INDEX_FIELD_NUMBER: builtins.int + long_name: builtins.str + short_name: builtins.str + category: builtins.str + flop_count: builtins.float + """Metrics computed by HloCostAnalysis.""" + transcendental_count: builtins.float + bytes_accessed: builtins.int + optimal_seconds: builtins.float + profile_index: builtins.int + """The index into the profile counters array for the HloInstruction + corresponding to this HloInstructionInfo. + """ + def __init__( + self, + *, + long_name: builtins.str | None = ..., + short_name: builtins.str | None = ..., + category: builtins.str | None = ..., + flop_count: builtins.float | None = ..., + transcendental_count: builtins.float | None = ..., + bytes_accessed: builtins.int | None = ..., + optimal_seconds: builtins.float | None = ..., + profile_index: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_accessed", + b"bytes_accessed", + "category", + b"category", + "flop_count", + b"flop_count", + "long_name", + b"long_name", + "optimal_seconds", + b"optimal_seconds", + "profile_index", + b"profile_index", + "short_name", + b"short_name", + "transcendental_count", + b"transcendental_count", + ], + ) -> None: ... + + @typing.final + class HloComputationInfo(google.protobuf.message.Message): + """Pretty-printer information about an HloComputation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + PROFILE_INDEX_FIELD_NUMBER: builtins.int + INSTRUCTION_INFOS_FIELD_NUMBER: builtins.int + name: builtins.str + profile_index: builtins.int + """The index into the profile counters array for the HloComputation + corresponding to this HloComputationInfo. + """ + @property + def instruction_infos( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___HloProfilePrinterData.HloInstructionInfo + ]: + """HloInstructionInfos for every HloInstruction in the HloComputation for + corresponding to this HloComputattionInfo. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + profile_index: builtins.int | None = ..., + instruction_infos: collections.abc.Iterable[global___HloProfilePrinterData.HloInstructionInfo] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_infos", b"instruction_infos", "name", b"name", "profile_index", b"profile_index" + ], + ) -> None: ... + + @typing.final + class ExtraMetricsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + COMPUTATION_INFOS_FIELD_NUMBER: builtins.int + PROFILE_COUNTERS_SIZE_FIELD_NUMBER: builtins.int + EXTRA_METRICS_FIELD_NUMBER: builtins.int + ENTRY_COMPUTATION_FIELD_NUMBER: builtins.int + profile_counters_size: builtins.int + """The size of the profile counters array we will pretty-print.""" + entry_computation: builtins.str + """Name of the entry computation.""" + @property + def computation_infos( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloProfilePrinterData.HloComputationInfo]: + """HloComputationInfos for every HloComputation in the HloModule.""" + + @property + def extra_metrics(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Maps extra metric name to the index into the profile counters array.""" + + def __init__( + self, + *, + computation_infos: collections.abc.Iterable[global___HloProfilePrinterData.HloComputationInfo] | None = ..., + profile_counters_size: builtins.int | None = ..., + extra_metrics: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + entry_computation: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_infos", + b"computation_infos", + "entry_computation", + b"entry_computation", + "extra_metrics", + b"extra_metrics", + "profile_counters_size", + b"profile_counters_size", + ], + ) -> None: ... + +global___HloProfilePrinterData = HloProfilePrinterData diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi new file mode 100644 index 000000000000..30b4ef4a491a --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/metrics_pb2.pyi @@ -0,0 +1,284 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.duration_pb2 +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import google.protobuf.timestamp_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class PassMetrics(google.protobuf.message.Message): + """Defines pass specific metrics.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODULE_ID_FIELD_NUMBER: builtins.int + PASS_NAME_FIELD_NUMBER: builtins.int + PASS_DURATION_FIELD_NUMBER: builtins.int + CUSTOM_METRICS_FIELD_NUMBER: builtins.int + module_id: builtins.int + """Unique ID of the module on which the pass was run.""" + pass_name: builtins.str + """The name of the pass.""" + @property + def pass_duration(self) -> google.protobuf.duration_pb2.Duration: + """Duration of the pass.""" + + @property + def custom_metrics(self) -> google.protobuf.any_pb2.Any: + """Custom pass metrics. This is kept opaque, via `google.protobuf.Any`, in + order to decouple pass agnostic compilation logs from possibly proprietary + compiler passes. + """ + + def __init__( + self, + *, + module_id: builtins.int | None = ..., + pass_name: builtins.str | None = ..., + pass_duration: google.protobuf.duration_pb2.Duration | None = ..., + custom_metrics: google.protobuf.any_pb2.Any | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["custom_metrics", b"custom_metrics", "pass_duration", b"pass_duration"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "custom_metrics", + b"custom_metrics", + "module_id", + b"module_id", + "pass_duration", + b"pass_duration", + "pass_name", + b"pass_name", + ], + ) -> None: ... + +global___PassMetrics = PassMetrics + +@typing.final +class JobInfo(google.protobuf.message.Message): + """Defines compilation job information.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + CELL_FIELD_NUMBER: builtins.int + USER_FIELD_NUMBER: builtins.int + UID_FIELD_NUMBER: builtins.int + TASK_ID_FIELD_NUMBER: builtins.int + TASK_UID_FIELD_NUMBER: builtins.int + name: builtins.str + """Name of the job running compilation.""" + cell: builtins.str + """Cell in which the job is running.""" + user: builtins.str + """User running the job.""" + uid: builtins.int + """Unique id when combined with user and cell field.""" + task_id: builtins.int + """Task index, which will not change across job restarts.""" + task_uid: builtins.int + """Task unique id, which may change across job restarts.""" + def __init__( + self, + *, + name: builtins.str | None = ..., + cell: builtins.str | None = ..., + user: builtins.str | None = ..., + uid: builtins.int | None = ..., + task_id: builtins.int | None = ..., + task_uid: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "_cell", + b"_cell", + "_name", + b"_name", + "_task_id", + b"_task_id", + "_task_uid", + b"_task_uid", + "_uid", + b"_uid", + "_user", + b"_user", + "cell", + b"cell", + "name", + b"name", + "task_id", + b"task_id", + "task_uid", + b"task_uid", + "uid", + b"uid", + "user", + b"user", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "_cell", + b"_cell", + "_name", + b"_name", + "_task_id", + b"_task_id", + "_task_uid", + b"_task_uid", + "_uid", + b"_uid", + "_user", + b"_user", + "cell", + b"cell", + "name", + b"name", + "task_id", + b"task_id", + "task_uid", + b"task_uid", + "uid", + b"uid", + "user", + b"user", + ], + ) -> None: ... + + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_cell", b"_cell"]) -> typing.Literal["cell"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_name", b"_name"]) -> typing.Literal["name"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_task_id", b"_task_id"]) -> typing.Literal["task_id"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_task_uid", b"_task_uid"]) -> typing.Literal["task_uid"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_uid", b"_uid"]) -> typing.Literal["uid"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["_user", b"_user"]) -> typing.Literal["user"] | None: ... + +global___JobInfo = JobInfo + +@typing.final +class CompilationLogEntry(google.protobuf.message.Message): + """Defines XLA compilation metrics.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _CompilationStage: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CompilationStageEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CompilationLogEntry._CompilationStage.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNSPECIFIED: CompilationLogEntry._CompilationStage.ValueType # 0 + END_TO_END: CompilationLogEntry._CompilationStage.ValueType # 1 + HLO_PASSES: CompilationLogEntry._CompilationStage.ValueType # 2 + CODE_GENERATION: CompilationLogEntry._CompilationStage.ValueType # 3 + BACKEND_PASSES: CompilationLogEntry._CompilationStage.ValueType # 4 + + class CompilationStage(_CompilationStage, metaclass=_CompilationStageEnumTypeWrapper): + """Defines compilation stages for which metrics are collected.""" + + UNSPECIFIED: CompilationLogEntry.CompilationStage.ValueType # 0 + END_TO_END: CompilationLogEntry.CompilationStage.ValueType # 1 + HLO_PASSES: CompilationLogEntry.CompilationStage.ValueType # 2 + CODE_GENERATION: CompilationLogEntry.CompilationStage.ValueType # 3 + BACKEND_PASSES: CompilationLogEntry.CompilationStage.ValueType # 4 + + TIMESTAMP_FIELD_NUMBER: builtins.int + STAGE_FIELD_NUMBER: builtins.int + DURATION_FIELD_NUMBER: builtins.int + TASK_INDEX_FIELD_NUMBER: builtins.int + PASS_METRICS_FIELD_NUMBER: builtins.int + MODULE_IDS_FIELD_NUMBER: builtins.int + JOB_INFO_FIELD_NUMBER: builtins.int + stage: global___CompilationLogEntry.CompilationStage.ValueType + """Compilation stage recorded by this log entry.""" + task_index: builtins.int + """Task index from which this log entry was recorded or + -1 if the task index could not be fetched. In the case task_index is not + equal to -1, it is guaranteed to match the task_id in job_info. + """ + @property + def timestamp(self) -> google.protobuf.timestamp_pb2.Timestamp: + """Time when the event captured by this log entry occurred.""" + + @property + def duration(self) -> google.protobuf.duration_pb2.Duration: + """Duration of the given compilation stage.""" + + @property + def pass_metrics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PassMetrics]: + """Pass specific metrics.""" + + @property + def module_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """IDs of modules on which the compilation stage was run.""" + + @property + def job_info(self) -> global___JobInfo: + """Job information.""" + + def __init__( + self, + *, + timestamp: google.protobuf.timestamp_pb2.Timestamp | None = ..., + stage: global___CompilationLogEntry.CompilationStage.ValueType | None = ..., + duration: google.protobuf.duration_pb2.Duration | None = ..., + task_index: builtins.int | None = ..., + pass_metrics: collections.abc.Iterable[global___PassMetrics] | None = ..., + module_ids: collections.abc.Iterable[builtins.int] | None = ..., + job_info: global___JobInfo | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["duration", b"duration", "job_info", b"job_info", "timestamp", b"timestamp"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "duration", + b"duration", + "job_info", + b"job_info", + "module_ids", + b"module_ids", + "pass_metrics", + b"pass_metrics", + "stage", + b"stage", + "task_index", + b"task_index", + "timestamp", + b"timestamp", + ], + ) -> None: ... + +global___CompilationLogEntry = CompilationLogEntry diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi new file mode 100644 index 000000000000..6b3b31b94f3d --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/test_compilation_environment_pb2.pyi @@ -0,0 +1,59 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2022 The OpenXLA 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 builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class TestCompilationEnvironment1(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOME_FLAG_FIELD_NUMBER: builtins.int + some_flag: builtins.int + def __init__(self, *, some_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["some_flag", b"some_flag"]) -> None: ... + +global___TestCompilationEnvironment1 = TestCompilationEnvironment1 + +@typing.final +class TestCompilationEnvironment2(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOME_OTHER_FLAG_FIELD_NUMBER: builtins.int + some_other_flag: builtins.int + def __init__(self, *, some_other_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["some_other_flag", b"some_other_flag"]) -> None: ... + +global___TestCompilationEnvironment2 = TestCompilationEnvironment2 + +@typing.final +class TestCompilationEnvironment3(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + A_THIRD_FLAG_FIELD_NUMBER: builtins.int + a_third_flag: builtins.int + def __init__(self, *, a_third_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["a_third_flag", b"a_third_flag"]) -> None: ... + +global___TestCompilationEnvironment3 = TestCompilationEnvironment3 diff --git a/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi new file mode 100644 index 000000000000..e17f9559b648 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/service/xla_compile_result_pb2.pyi @@ -0,0 +1,167 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2023 The OpenXLA 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 builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.duration_pb2 +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.compiler.xla.service.hlo_pb2 +import tensorflow.tsl.protobuf.status_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompilerPerfStats(google.protobuf.message.Message): + """Statistics on how long various parts of compilation took. + Not all durations may be relevant for all producers of this message, in + which irrelevant fields should simply be skipped. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INIT_DURATION_FIELD_NUMBER: builtins.int + HLO_VERIFICATION_DURATION_FIELD_NUMBER: builtins.int + COMPILATION_PROLOGUE_DURATION_FIELD_NUMBER: builtins.int + COMPILATION_DURATION_FIELD_NUMBER: builtins.int + TOTAL_DURATION_FIELD_NUMBER: builtins.int + @property + def init_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to initialize the compiler?""" + + @property + def hlo_verification_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to verify the HLO?""" + + @property + def compilation_prologue_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to prepare for compilation after verification?""" + + @property + def compilation_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did it take to compile?""" + + @property + def total_duration(self) -> google.protobuf.duration_pb2.Duration: + """How long did everything take?""" + + def __init__( + self, + *, + init_duration: google.protobuf.duration_pb2.Duration | None = ..., + hlo_verification_duration: google.protobuf.duration_pb2.Duration | None = ..., + compilation_prologue_duration: google.protobuf.duration_pb2.Duration | None = ..., + compilation_duration: google.protobuf.duration_pb2.Duration | None = ..., + total_duration: google.protobuf.duration_pb2.Duration | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "compilation_duration", + b"compilation_duration", + "compilation_prologue_duration", + b"compilation_prologue_duration", + "hlo_verification_duration", + b"hlo_verification_duration", + "init_duration", + b"init_duration", + "total_duration", + b"total_duration", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_duration", + b"compilation_duration", + "compilation_prologue_duration", + b"compilation_prologue_duration", + "hlo_verification_duration", + b"hlo_verification_duration", + "init_duration", + b"init_duration", + "total_duration", + b"total_duration", + ], + ) -> None: ... + +global___CompilerPerfStats = CompilerPerfStats + +@typing.final +class CompilationResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class CountersEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + HLO_MODULE_FIELD_NUMBER: builtins.int + PERF_STATS_FIELD_NUMBER: builtins.int + STATUS_FIELD_NUMBER: builtins.int + COUNTERS_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: + """The compiled HLO. Only set when compilation succeeds.""" + + @property + def perf_stats(self) -> global___CompilerPerfStats: + """Always set when compilation succeeds. May or may not be set when + compilation fails. + """ + + @property + def status(self) -> tensorflow.tsl.protobuf.status_pb2.StatusProto: + """Always set even when compilation succeeds.""" + + @property + def counters(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Collects counters collected during compilation. Not every producer may + include counter support at all or any particular counter. + """ + + def __init__( + self, + *, + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + perf_stats: global___CompilerPerfStats | None = ..., + status: tensorflow.tsl.protobuf.status_pb2.StatusProto | None = ..., + counters: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["hlo_module", b"hlo_module", "perf_stats", b"perf_stats", "status", b"status"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "counters", b"counters", "hlo_module", b"hlo_module", "perf_stats", b"perf_stats", "status", b"status" + ], + ) -> None: ... + +global___CompilationResult = CompilationResult diff --git a/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi new file mode 100644 index 000000000000..0fe33b725b8e --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/bfc_memory_map_pb2.pyi @@ -0,0 +1,218 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class MemAllocatorStats(google.protobuf.message.Message): + """Some of the data from AllocatorStats""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUM_ALLOCS_FIELD_NUMBER: builtins.int + BYTES_IN_USE_FIELD_NUMBER: builtins.int + PEAK_BYTES_IN_USE_FIELD_NUMBER: builtins.int + LARGEST_ALLOC_SIZE_FIELD_NUMBER: builtins.int + FRAGMENTATION_METRIC_FIELD_NUMBER: builtins.int + num_allocs: builtins.int + bytes_in_use: builtins.int + peak_bytes_in_use: builtins.int + largest_alloc_size: builtins.int + fragmentation_metric: builtins.float + def __init__( + self, + *, + num_allocs: builtins.int | None = ..., + bytes_in_use: builtins.int | None = ..., + peak_bytes_in_use: builtins.int | None = ..., + largest_alloc_size: builtins.int | None = ..., + fragmentation_metric: builtins.float | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_in_use", + b"bytes_in_use", + "fragmentation_metric", + b"fragmentation_metric", + "largest_alloc_size", + b"largest_alloc_size", + "num_allocs", + b"num_allocs", + "peak_bytes_in_use", + b"peak_bytes_in_use", + ], + ) -> None: ... + +global___MemAllocatorStats = MemAllocatorStats + +@typing.final +class MemChunk(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ADDRESS_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + REQUESTED_SIZE_FIELD_NUMBER: builtins.int + BIN_FIELD_NUMBER: builtins.int + OP_NAME_FIELD_NUMBER: builtins.int + FREED_AT_COUNT_FIELD_NUMBER: builtins.int + ACTION_COUNT_FIELD_NUMBER: builtins.int + IN_USE_FIELD_NUMBER: builtins.int + STEP_ID_FIELD_NUMBER: builtins.int + address: builtins.int + size: builtins.int + requested_size: builtins.int + bin: builtins.int + op_name: builtins.str + freed_at_count: builtins.int + action_count: builtins.int + in_use: builtins.bool + step_id: builtins.int + def __init__( + self, + *, + address: builtins.int | None = ..., + size: builtins.int | None = ..., + requested_size: builtins.int | None = ..., + bin: builtins.int | None = ..., + op_name: builtins.str | None = ..., + freed_at_count: builtins.int | None = ..., + action_count: builtins.int | None = ..., + in_use: builtins.bool | None = ..., + step_id: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "action_count", + b"action_count", + "address", + b"address", + "bin", + b"bin", + "freed_at_count", + b"freed_at_count", + "in_use", + b"in_use", + "op_name", + b"op_name", + "requested_size", + b"requested_size", + "size", + b"size", + "step_id", + b"step_id", + ], + ) -> None: ... + +global___MemChunk = MemChunk + +@typing.final +class BinSummary(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BIN_FIELD_NUMBER: builtins.int + TOTAL_BYTES_IN_USE_FIELD_NUMBER: builtins.int + TOTAL_BYTES_IN_BIN_FIELD_NUMBER: builtins.int + TOTAL_CHUNKS_IN_USE_FIELD_NUMBER: builtins.int + TOTAL_CHUNKS_IN_BIN_FIELD_NUMBER: builtins.int + bin: builtins.int + total_bytes_in_use: builtins.int + total_bytes_in_bin: builtins.int + total_chunks_in_use: builtins.int + total_chunks_in_bin: builtins.int + def __init__( + self, + *, + bin: builtins.int | None = ..., + total_bytes_in_use: builtins.int | None = ..., + total_bytes_in_bin: builtins.int | None = ..., + total_chunks_in_use: builtins.int | None = ..., + total_chunks_in_bin: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bin", + b"bin", + "total_bytes_in_bin", + b"total_bytes_in_bin", + "total_bytes_in_use", + b"total_bytes_in_use", + "total_chunks_in_bin", + b"total_chunks_in_bin", + "total_chunks_in_use", + b"total_chunks_in_use", + ], + ) -> None: ... + +global___BinSummary = BinSummary + +@typing.final +class SnapShot(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ACTION_COUNT_FIELD_NUMBER: builtins.int + SIZE_FIELD_NUMBER: builtins.int + action_count: builtins.int + size: builtins.int + def __init__(self, *, action_count: builtins.int | None = ..., size: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["action_count", b"action_count", "size", b"size"]) -> None: ... + +global___SnapShot = SnapShot + +@typing.final +class MemoryDump(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ALLOCATOR_NAME_FIELD_NUMBER: builtins.int + BIN_SUMMARY_FIELD_NUMBER: builtins.int + CHUNK_FIELD_NUMBER: builtins.int + SNAP_SHOT_FIELD_NUMBER: builtins.int + STATS_FIELD_NUMBER: builtins.int + allocator_name: builtins.str + @property + def bin_summary(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinSummary]: ... + @property + def chunk(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MemChunk]: ... + @property + def snap_shot(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SnapShot]: ... + @property + def stats(self) -> global___MemAllocatorStats: ... + def __init__( + self, + *, + allocator_name: builtins.str | None = ..., + bin_summary: collections.abc.Iterable[global___BinSummary] | None = ..., + chunk: collections.abc.Iterable[global___MemChunk] | None = ..., + snap_shot: collections.abc.Iterable[global___SnapShot] | None = ..., + stats: global___MemAllocatorStats | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["stats", b"stats"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "allocator_name", + b"allocator_name", + "bin_summary", + b"bin_summary", + "chunk", + b"chunk", + "snap_shot", + b"snap_shot", + "stats", + b"stats", + ], + ) -> None: ... + +global___MemoryDump = MemoryDump diff --git a/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi new file mode 100644 index 000000000000..a0cd6ef6a44b --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/tsl/protobuf/test_log_pb2.pyi @@ -0,0 +1,707 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing the results of benchmarks and unit tests.""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import google.protobuf.wrappers_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class EntryValue(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DOUBLE_VALUE_FIELD_NUMBER: builtins.int + STRING_VALUE_FIELD_NUMBER: builtins.int + double_value: builtins.float + string_value: builtins.str + def __init__(self, *, double_value: builtins.float | None = ..., string_value: builtins.str | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["double_value", b"double_value", "kind", b"kind", "string_value", b"string_value"] + ) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["double_value", b"double_value", "kind", b"kind", "string_value", b"string_value"] + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["double_value", "string_value"] | None: ... + +global___EntryValue = EntryValue + +@typing.final +class MetricEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + MIN_VALUE_FIELD_NUMBER: builtins.int + MAX_VALUE_FIELD_NUMBER: builtins.int + name: builtins.str + """Metric name""" + value: builtins.float + """Metric value""" + @property + def min_value(self) -> google.protobuf.wrappers_pb2.DoubleValue: + """The minimum acceptable value for the metric if specified""" + + @property + def max_value(self) -> google.protobuf.wrappers_pb2.DoubleValue: + """The maximum acceptable value for the metric if specified""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + value: builtins.float | None = ..., + min_value: google.protobuf.wrappers_pb2.DoubleValue | None = ..., + max_value: google.protobuf.wrappers_pb2.DoubleValue | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["max_value", b"max_value", "min_value", b"min_value"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["max_value", b"max_value", "min_value", b"min_value", "name", b"name", "value", b"value"] + ) -> None: ... + +global___MetricEntry = MetricEntry + +@typing.final +class BenchmarkEntry(google.protobuf.message.Message): + """Each unit test or benchmark in a test or benchmark run provides + some set of information. Here we provide some reasonable keys + one would expect to see, with optional key/value pairs for things + we haven't considered. + + This BenchmarkEntry should be emitted by each unit test or benchmark + reporter. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ExtrasEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___EntryValue: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___EntryValue | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ITERS_FIELD_NUMBER: builtins.int + CPU_TIME_FIELD_NUMBER: builtins.int + WALL_TIME_FIELD_NUMBER: builtins.int + THROUGHPUT_FIELD_NUMBER: builtins.int + EXTRAS_FIELD_NUMBER: builtins.int + METRICS_FIELD_NUMBER: builtins.int + name: builtins.str + """The name of the specific benchmark or test + (e.g. BM_AdjustContrast_gpu_B_W_H) + """ + iters: builtins.int + """If a benchmark, how many iterations it was run for""" + cpu_time: builtins.float + """Total cpu time used for all iterations (in seconds)""" + wall_time: builtins.float + """Total wall time used for all iterations (in seconds)""" + throughput: builtins.float + """Throughput (in MB/s)""" + @property + def extras(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___EntryValue]: + """Generic map from result key to value.""" + + @property + def metrics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___MetricEntry]: + """Metric name, value and expected range. This can include accuracy metrics + typically used to determine whether the accuracy test has passed + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + iters: builtins.int | None = ..., + cpu_time: builtins.float | None = ..., + wall_time: builtins.float | None = ..., + throughput: builtins.float | None = ..., + extras: collections.abc.Mapping[builtins.str, global___EntryValue] | None = ..., + metrics: collections.abc.Iterable[global___MetricEntry] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cpu_time", + b"cpu_time", + "extras", + b"extras", + "iters", + b"iters", + "metrics", + b"metrics", + "name", + b"name", + "throughput", + b"throughput", + "wall_time", + b"wall_time", + ], + ) -> None: ... + +global___BenchmarkEntry = BenchmarkEntry + +@typing.final +class BenchmarkEntries(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENTRY_FIELD_NUMBER: builtins.int + @property + def entry(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BenchmarkEntry]: ... + def __init__(self, *, entry: collections.abc.Iterable[global___BenchmarkEntry] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["entry", b"entry"]) -> None: ... + +global___BenchmarkEntries = BenchmarkEntries + +@typing.final +class BuildConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODE_FIELD_NUMBER: builtins.int + CC_FLAGS_FIELD_NUMBER: builtins.int + OPTS_FIELD_NUMBER: builtins.int + mode: builtins.str + """opt, dbg, etc""" + @property + def cc_flags(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """CC compiler flags, if known""" + + @property + def opts(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Bazel compilation options, if known""" + + def __init__( + self, + *, + mode: builtins.str | None = ..., + cc_flags: collections.abc.Iterable[builtins.str] | None = ..., + opts: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["cc_flags", b"cc_flags", "mode", b"mode", "opts", b"opts"]) -> None: ... + +global___BuildConfiguration = BuildConfiguration + +@typing.final +class CommitId(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CHANGELIST_FIELD_NUMBER: builtins.int + HASH_FIELD_NUMBER: builtins.int + SNAPSHOT_FIELD_NUMBER: builtins.int + PENDING_CHANGELIST_FIELD_NUMBER: builtins.int + changelist: builtins.int + """Submitted changelist.""" + hash: builtins.str + snapshot: builtins.str + """Hash of intermediate change between hash/changelist and what was tested. + Not used if the build is from a commit without modifications. + """ + pending_changelist: builtins.int + """Changelist tested if the change list is not already submitted.""" + def __init__( + self, + *, + changelist: builtins.int | None = ..., + hash: builtins.str | None = ..., + snapshot: builtins.str | None = ..., + pending_changelist: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, field_name: typing.Literal["changelist", b"changelist", "hash", b"hash", "kind", b"kind"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "changelist", + b"changelist", + "hash", + b"hash", + "kind", + b"kind", + "pending_changelist", + b"pending_changelist", + "snapshot", + b"snapshot", + ], + ) -> None: ... + def WhichOneof(self, oneof_group: typing.Literal["kind", b"kind"]) -> typing.Literal["changelist", "hash"] | None: ... + +global___CommitId = CommitId + +@typing.final +class CPUInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class CacheSizeEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NUM_CORES_FIELD_NUMBER: builtins.int + NUM_CORES_ALLOWED_FIELD_NUMBER: builtins.int + MHZ_PER_CPU_FIELD_NUMBER: builtins.int + CPU_INFO_FIELD_NUMBER: builtins.int + CPU_GOVERNOR_FIELD_NUMBER: builtins.int + CACHE_SIZE_FIELD_NUMBER: builtins.int + num_cores: builtins.int + num_cores_allowed: builtins.int + mhz_per_cpu: builtins.float + """How fast are these cpus?""" + cpu_info: builtins.str + """Additional cpu information. For example, + Intel Ivybridge with HyperThreading (24 cores) dL1:32KB dL2:256KB dL3:30MB + """ + cpu_governor: builtins.str + """What kind of cpu scaling is enabled on the host. + Examples include "performance", "ondemand", "conservative", "mixed". + """ + @property + def cache_size(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: + """Cache sizes (in bytes), e.g. "L2": 262144 (for 256KB)""" + + def __init__( + self, + *, + num_cores: builtins.int | None = ..., + num_cores_allowed: builtins.int | None = ..., + mhz_per_cpu: builtins.float | None = ..., + cpu_info: builtins.str | None = ..., + cpu_governor: builtins.str | None = ..., + cache_size: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "cache_size", + b"cache_size", + "cpu_governor", + b"cpu_governor", + "cpu_info", + b"cpu_info", + "mhz_per_cpu", + b"mhz_per_cpu", + "num_cores", + b"num_cores", + "num_cores_allowed", + b"num_cores_allowed", + ], + ) -> None: ... + +global___CPUInfo = CPUInfo + +@typing.final +class MemoryInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TOTAL_FIELD_NUMBER: builtins.int + AVAILABLE_FIELD_NUMBER: builtins.int + total: builtins.int + """Total virtual memory in bytes""" + available: builtins.int + """Immediately available memory in bytes""" + def __init__(self, *, total: builtins.int | None = ..., available: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["available", b"available", "total", b"total"]) -> None: ... + +global___MemoryInfo = MemoryInfo + +@typing.final +class GPUInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MODEL_FIELD_NUMBER: builtins.int + UUID_FIELD_NUMBER: builtins.int + BUS_ID_FIELD_NUMBER: builtins.int + model: builtins.str + """e.g. "Tesla K40c" """ + uuid: builtins.str + """Final entry in output of "nvidia-smi -L" """ + bus_id: builtins.str + """e.g. "0000:04:00.0" """ + def __init__( + self, *, model: builtins.str | None = ..., uuid: builtins.str | None = ..., bus_id: builtins.str | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["bus_id", b"bus_id", "model", b"model", "uuid", b"uuid"]) -> None: ... + +global___GPUInfo = GPUInfo + +@typing.final +class PlatformInfo(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BITS_FIELD_NUMBER: builtins.int + LINKAGE_FIELD_NUMBER: builtins.int + MACHINE_FIELD_NUMBER: builtins.int + RELEASE_FIELD_NUMBER: builtins.int + SYSTEM_FIELD_NUMBER: builtins.int + VERSION_FIELD_NUMBER: builtins.int + bits: builtins.str + """e.g. '64bit'""" + linkage: builtins.str + """e.g. 'ELF'""" + machine: builtins.str + """e.g. 'i386'""" + release: builtins.str + """e.g. '3.13.0-76-generic'""" + system: builtins.str + """e.g. 'Linux'""" + version: builtins.str + """e.g. '#120-Ubuntu SMP Mon Jan 18 15:59:10 UTC 2016'""" + def __init__( + self, + *, + bits: builtins.str | None = ..., + linkage: builtins.str | None = ..., + machine: builtins.str | None = ..., + release: builtins.str | None = ..., + system: builtins.str | None = ..., + version: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "bits", + b"bits", + "linkage", + b"linkage", + "machine", + b"machine", + "release", + b"release", + "system", + b"system", + "version", + b"version", + ], + ) -> None: ... + +global___PlatformInfo = PlatformInfo + +@typing.final +class AvailableDeviceInfo(google.protobuf.message.Message): + """Matches DeviceAttributes""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + MEMORY_LIMIT_FIELD_NUMBER: builtins.int + PHYSICAL_DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + """Device name.""" + type: builtins.str + """Device type, e.g. 'CPU' or 'GPU'.""" + memory_limit: builtins.int + """Memory capacity in bytes.""" + physical_description: builtins.str + """The physical description of this device.""" + def __init__( + self, + *, + name: builtins.str | None = ..., + type: builtins.str | None = ..., + memory_limit: builtins.int | None = ..., + physical_description: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "memory_limit", b"memory_limit", "name", b"name", "physical_description", b"physical_description", "type", b"type" + ], + ) -> None: ... + +global___AvailableDeviceInfo = AvailableDeviceInfo + +@typing.final +class MachineConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HOSTNAME_FIELD_NUMBER: builtins.int + SERIAL_IDENTIFIER_FIELD_NUMBER: builtins.int + PLATFORM_INFO_FIELD_NUMBER: builtins.int + CPU_INFO_FIELD_NUMBER: builtins.int + DEVICE_INFO_FIELD_NUMBER: builtins.int + AVAILABLE_DEVICE_INFO_FIELD_NUMBER: builtins.int + MEMORY_INFO_FIELD_NUMBER: builtins.int + hostname: builtins.str + """Host name of machine that ran the benchmark.""" + serial_identifier: builtins.str + """Unique serial number of the machine.""" + @property + def platform_info(self) -> global___PlatformInfo: + """Additional platform information.""" + + @property + def cpu_info(self) -> global___CPUInfo: + """CPU Information.""" + + @property + def device_info(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.any_pb2.Any]: + """Other devices that are attached and relevant (e.g. GPUInfo).""" + + @property + def available_device_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___AvailableDeviceInfo]: + """Devices accessible to the test (e.g. as given by list_local_devices).""" + + @property + def memory_info(self) -> global___MemoryInfo: ... + def __init__( + self, + *, + hostname: builtins.str | None = ..., + serial_identifier: builtins.str | None = ..., + platform_info: global___PlatformInfo | None = ..., + cpu_info: global___CPUInfo | None = ..., + device_info: collections.abc.Iterable[google.protobuf.any_pb2.Any] | None = ..., + available_device_info: collections.abc.Iterable[global___AvailableDeviceInfo] | None = ..., + memory_info: global___MemoryInfo | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal["cpu_info", b"cpu_info", "memory_info", b"memory_info", "platform_info", b"platform_info"], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "available_device_info", + b"available_device_info", + "cpu_info", + b"cpu_info", + "device_info", + b"device_info", + "hostname", + b"hostname", + "memory_info", + b"memory_info", + "platform_info", + b"platform_info", + "serial_identifier", + b"serial_identifier", + ], + ) -> None: ... + +global___MachineConfiguration = MachineConfiguration + +@typing.final +class RunConfiguration(google.protobuf.message.Message): + """Run-specific items such as arguments to the test / benchmark.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class EnvVarsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + ARGUMENT_FIELD_NUMBER: builtins.int + ENV_VARS_FIELD_NUMBER: builtins.int + @property + def argument(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def env_vars(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: + """Environment variables used to run the test/benchmark.""" + + def __init__( + self, + *, + argument: collections.abc.Iterable[builtins.str] | None = ..., + env_vars: collections.abc.Mapping[builtins.str, builtins.str] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["argument", b"argument", "env_vars", b"env_vars"]) -> None: ... + +global___RunConfiguration = RunConfiguration + +@typing.final +class TestResults(google.protobuf.message.Message): + """The output of one benchmark / test run. Each run contains a list of + tests or benchmarks, stored as BenchmarkEntry messages. + + This message should be emitted by the reporter (which runs the + test / BM in a subprocess and then reads the emitted BenchmarkEntry messages; + usually from a serialized json file, finally collecting them along + with additional information about the test run. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _BenchmarkType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _BenchmarkTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[TestResults._BenchmarkType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + UNKNOWN: TestResults._BenchmarkType.ValueType # 0 + """Fallback for protos written before Type was introduced.""" + CPP_MICROBENCHMARK: TestResults._BenchmarkType.ValueType # 1 + PYTHON_BENCHMARK: TestResults._BenchmarkType.ValueType # 2 + ANDROID_BENCHMARK: TestResults._BenchmarkType.ValueType # 3 + EDGE_BENCHMARK: TestResults._BenchmarkType.ValueType # 4 + IOS_BENCHMARK: TestResults._BenchmarkType.ValueType # 5 + + class BenchmarkType(_BenchmarkType, metaclass=_BenchmarkTypeEnumTypeWrapper): + """The type of benchmark.""" + + UNKNOWN: TestResults.BenchmarkType.ValueType # 0 + """Fallback for protos written before Type was introduced.""" + CPP_MICROBENCHMARK: TestResults.BenchmarkType.ValueType # 1 + PYTHON_BENCHMARK: TestResults.BenchmarkType.ValueType # 2 + ANDROID_BENCHMARK: TestResults.BenchmarkType.ValueType # 3 + EDGE_BENCHMARK: TestResults.BenchmarkType.ValueType # 4 + IOS_BENCHMARK: TestResults.BenchmarkType.ValueType # 5 + + TARGET_FIELD_NUMBER: builtins.int + ENTRIES_FIELD_NUMBER: builtins.int + BUILD_CONFIGURATION_FIELD_NUMBER: builtins.int + COMMIT_ID_FIELD_NUMBER: builtins.int + START_TIME_FIELD_NUMBER: builtins.int + RUN_TIME_FIELD_NUMBER: builtins.int + MACHINE_CONFIGURATION_FIELD_NUMBER: builtins.int + RUN_CONFIGURATION_FIELD_NUMBER: builtins.int + NAME_FIELD_NUMBER: builtins.int + BENCHMARK_TYPE_FIELD_NUMBER: builtins.int + RUN_MODE_FIELD_NUMBER: builtins.int + TF_VERSION_FIELD_NUMBER: builtins.int + target: builtins.str + """The target of the run, e.g.: + //tensorflow/core:kernels_adjust_contrast_op_benchmark_test + """ + start_time: builtins.int + """The time the run started (in seconds of UTC time since Unix epoch)""" + run_time: builtins.float + """The amount of time the total run took (wall time in seconds)""" + name: builtins.str + """Benchmark target identifier.""" + benchmark_type: global___TestResults.BenchmarkType.ValueType + run_mode: builtins.str + """Used for differentiating between continuous and debug builds. + Must be one of: + * cbuild: results from continuous build. + * presubmit: results from oneshot requests. + * culprit: results from culprit finder rerun. + """ + tf_version: builtins.str + """TensorFlow version this benchmark runs against. + This can be either set to full version or just the major version. + """ + @property + def entries(self) -> global___BenchmarkEntries: + """The list of tests or benchmarks in this run.""" + + @property + def build_configuration(self) -> global___BuildConfiguration: + """The configuration of the build (compiled opt? with cuda? any copts?)""" + + @property + def commit_id(self) -> global___CommitId: + """The commit id (git hash or changelist)""" + + @property + def machine_configuration(self) -> global___MachineConfiguration: + """Machine-specific parameters (Platform and CPU info)""" + + @property + def run_configuration(self) -> global___RunConfiguration: + """Run-specific parameters (arguments, etc)""" + + def __init__( + self, + *, + target: builtins.str | None = ..., + entries: global___BenchmarkEntries | None = ..., + build_configuration: global___BuildConfiguration | None = ..., + commit_id: global___CommitId | None = ..., + start_time: builtins.int | None = ..., + run_time: builtins.float | None = ..., + machine_configuration: global___MachineConfiguration | None = ..., + run_configuration: global___RunConfiguration | None = ..., + name: builtins.str | None = ..., + benchmark_type: global___TestResults.BenchmarkType.ValueType | None = ..., + run_mode: builtins.str | None = ..., + tf_version: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "build_configuration", + b"build_configuration", + "commit_id", + b"commit_id", + "entries", + b"entries", + "machine_configuration", + b"machine_configuration", + "run_configuration", + b"run_configuration", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "benchmark_type", + b"benchmark_type", + "build_configuration", + b"build_configuration", + "commit_id", + b"commit_id", + "entries", + b"entries", + "machine_configuration", + b"machine_configuration", + "name", + b"name", + "run_configuration", + b"run_configuration", + "run_mode", + b"run_mode", + "run_time", + b"run_time", + "start_time", + b"start_time", + "target", + b"target", + "tf_version", + b"tf_version", + ], + ) -> None: ... + +global___TestResults = TestResults diff --git a/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi new file mode 100644 index 000000000000..de86f1c8f255 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/xla_data_pb2.pyi @@ -0,0 +1,2681 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2017 The OpenXLA 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 builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _PrimitiveType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PrimitiveTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PrimitiveType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PRIMITIVE_TYPE_INVALID: _PrimitiveType.ValueType # 0 + """Invalid primitive type to serve as default.""" + PRED: _PrimitiveType.ValueType # 1 + """Predicates are two-state booleans.""" + S2: _PrimitiveType.ValueType # 26 + """Signed integral values of fixed width.""" + S4: _PrimitiveType.ValueType # 21 + S8: _PrimitiveType.ValueType # 2 + S16: _PrimitiveType.ValueType # 3 + S32: _PrimitiveType.ValueType # 4 + S64: _PrimitiveType.ValueType # 5 + U2: _PrimitiveType.ValueType # 27 + """Unsigned integral values of fixed width.""" + U4: _PrimitiveType.ValueType # 22 + U8: _PrimitiveType.ValueType # 6 + U16: _PrimitiveType.ValueType # 7 + U32: _PrimitiveType.ValueType # 8 + U64: _PrimitiveType.ValueType # 9 + F16: _PrimitiveType.ValueType # 10 + """Floating-point values of fixed width. + + Note: if f16s are not natively supported on the device, they will be + converted to f16 from f32 at arbirary points in the computation. + """ + F32: _PrimitiveType.ValueType # 11 + BF16: _PrimitiveType.ValueType # 16 + """Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit + floating-point format, but uses 1 bit for the sign, 8 bits for the exponent + and 7 bits for the mantissa. + """ + F64: _PrimitiveType.ValueType # 12 + F8E5M2: _PrimitiveType.ValueType # 19 + """FP8 dtypes, as described in this paper: https://arxiv.org/abs/2209.05433 + + F8E5M2 has 5 exponent bits and 2 mantissa bits, and is similar to the + existing IEEE types. + + F8E4M3FN has 4 exponent bits and 3 mantissa bits. The "FN" means only + Finite and NaN values are supported. Unlike IEEE types, infinities are not + supported. NaN is represented when the exponent and mantissa bits are all + 1s. All other values are finite. + + F8E4M3B11FNUZ has 4 exponent bits and 3 mantissa bits and a bias of 11. The + "FNUZ" means only Finite and NaN values are supported; zero is unsigned. + Unlike IEEE types, infinities are not supported. NaN is represented when + the exponent and mantissa bits are all 0s with a sign bit of 1. All other + values are finite. + + Support for these dtypes is under development. They do not yet work + properly in most cases. + TODO(b/259609697): Fully support FP8. + """ + F8E4M3FN: _PrimitiveType.ValueType # 20 + F8E4M3B11FNUZ: _PrimitiveType.ValueType # 23 + F8E5M2FNUZ: _PrimitiveType.ValueType # 24 + """FP8 dtypes, as described in this paper: https://arxiv.org/abs/2206.02915 + + F8E5M2FNUZ has 5 exponent bits and 2 mantissa bits. + F8E4M3FNUZ has 4 exponent bits and 3 mantissa bits. + + The "FNUZ" means only Finite and NaN values are supported; zero is + unsigned. Unlike IEEE types, infinities are not supported. NaN is + represented when the exponent and mantissa bits are all 0s with a sign bit + of 1. All other values are finite. + + These differences mean there's an additional exponent value available. To + keep the same dynamic range as an IEEE-like FP8 type, the exponent is + biased one more than would be expected given the number of exponent bits + (8 for Float8E4M3FNUZ and 16 for Float8E5M2FNUZ). + """ + F8E4M3FNUZ: _PrimitiveType.ValueType # 25 + C64: _PrimitiveType.ValueType # 15 + """Complex values of fixed width. + Paired F32 (real, imag), as in std::complex. + """ + C128: _PrimitiveType.ValueType # 18 + """Paired F64 (real, imag), as in std::complex.""" + TUPLE: _PrimitiveType.ValueType # 13 + """A tuple is a polymorphic sequence; e.g. a shape that holds different + sub-shapes. They are used for things like returning multiple values from a + computation; e.g. a computation that returns weights and biases may have a + signature that results in a tuple like (f32[784x2000], f32[2000]) + + If a shape proto has the tuple element type, it may not have any entries + in the dimensions field. + """ + OPAQUE_TYPE: _PrimitiveType.ValueType # 14 + """An opaque type used for passing context-specific data to a custom + operation. Shapes of this primitive type will have empty dimensions and + tuple_shapes fields. + + (OPAQUE would be a better name for this identifier, but that conflicts with + a macro defined in windows.h.) + """ + TOKEN: _PrimitiveType.ValueType # 17 + """A token type threaded between side-effecting operations. Shapes of this + primitive type will have empty dimensions and tuple_shapes fields. + """ + +class PrimitiveType(_PrimitiveType, metaclass=_PrimitiveTypeEnumTypeWrapper): + """Primitive types are the individual values that can be held in rectangular + multidimensional arrays. A description of the rectangular multidimensional + array dimensions / primitive type is given by Shape, below. + + LINT.IfChange + """ + +PRIMITIVE_TYPE_INVALID: PrimitiveType.ValueType # 0 +"""Invalid primitive type to serve as default.""" +PRED: PrimitiveType.ValueType # 1 +"""Predicates are two-state booleans.""" +S2: PrimitiveType.ValueType # 26 +"""Signed integral values of fixed width.""" +S4: PrimitiveType.ValueType # 21 +S8: PrimitiveType.ValueType # 2 +S16: PrimitiveType.ValueType # 3 +S32: PrimitiveType.ValueType # 4 +S64: PrimitiveType.ValueType # 5 +U2: PrimitiveType.ValueType # 27 +"""Unsigned integral values of fixed width.""" +U4: PrimitiveType.ValueType # 22 +U8: PrimitiveType.ValueType # 6 +U16: PrimitiveType.ValueType # 7 +U32: PrimitiveType.ValueType # 8 +U64: PrimitiveType.ValueType # 9 +F16: PrimitiveType.ValueType # 10 +"""Floating-point values of fixed width. + +Note: if f16s are not natively supported on the device, they will be +converted to f16 from f32 at arbirary points in the computation. +""" +F32: PrimitiveType.ValueType # 11 +BF16: PrimitiveType.ValueType # 16 +"""Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit +floating-point format, but uses 1 bit for the sign, 8 bits for the exponent +and 7 bits for the mantissa. +""" +F64: PrimitiveType.ValueType # 12 +F8E5M2: PrimitiveType.ValueType # 19 +"""FP8 dtypes, as described in this paper: https://arxiv.org/abs/2209.05433 + +F8E5M2 has 5 exponent bits and 2 mantissa bits, and is similar to the +existing IEEE types. + +F8E4M3FN has 4 exponent bits and 3 mantissa bits. The "FN" means only +Finite and NaN values are supported. Unlike IEEE types, infinities are not +supported. NaN is represented when the exponent and mantissa bits are all +1s. All other values are finite. + +F8E4M3B11FNUZ has 4 exponent bits and 3 mantissa bits and a bias of 11. The +"FNUZ" means only Finite and NaN values are supported; zero is unsigned. +Unlike IEEE types, infinities are not supported. NaN is represented when +the exponent and mantissa bits are all 0s with a sign bit of 1. All other +values are finite. + +Support for these dtypes is under development. They do not yet work +properly in most cases. +TODO(b/259609697): Fully support FP8. +""" +F8E4M3FN: PrimitiveType.ValueType # 20 +F8E4M3B11FNUZ: PrimitiveType.ValueType # 23 +F8E5M2FNUZ: PrimitiveType.ValueType # 24 +"""FP8 dtypes, as described in this paper: https://arxiv.org/abs/2206.02915 + +F8E5M2FNUZ has 5 exponent bits and 2 mantissa bits. +F8E4M3FNUZ has 4 exponent bits and 3 mantissa bits. + +The "FNUZ" means only Finite and NaN values are supported; zero is +unsigned. Unlike IEEE types, infinities are not supported. NaN is +represented when the exponent and mantissa bits are all 0s with a sign bit +of 1. All other values are finite. + +These differences mean there's an additional exponent value available. To +keep the same dynamic range as an IEEE-like FP8 type, the exponent is +biased one more than would be expected given the number of exponent bits +(8 for Float8E4M3FNUZ and 16 for Float8E5M2FNUZ). +""" +F8E4M3FNUZ: PrimitiveType.ValueType # 25 +C64: PrimitiveType.ValueType # 15 +"""Complex values of fixed width. +Paired F32 (real, imag), as in std::complex. +""" +C128: PrimitiveType.ValueType # 18 +"""Paired F64 (real, imag), as in std::complex.""" +TUPLE: PrimitiveType.ValueType # 13 +"""A tuple is a polymorphic sequence; e.g. a shape that holds different +sub-shapes. They are used for things like returning multiple values from a +computation; e.g. a computation that returns weights and biases may have a +signature that results in a tuple like (f32[784x2000], f32[2000]) + +If a shape proto has the tuple element type, it may not have any entries +in the dimensions field. +""" +OPAQUE_TYPE: PrimitiveType.ValueType # 14 +"""An opaque type used for passing context-specific data to a custom +operation. Shapes of this primitive type will have empty dimensions and +tuple_shapes fields. + +(OPAQUE would be a better name for this identifier, but that conflicts with +a macro defined in windows.h.) +""" +TOKEN: PrimitiveType.ValueType # 17 +"""A token type threaded between side-effecting operations. Shapes of this +primitive type will have empty dimensions and tuple_shapes fields. +""" +global___PrimitiveType = PrimitiveType + +class _DimLevelType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _DimLevelTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_DimLevelType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DIM_DENSE: _DimLevelType.ValueType # 0 + """The corresponding dimension is Dense, every entry is stored.""" + DIM_COMPRESSED: _DimLevelType.ValueType # 1 + """The corresponding dimension is Compressed, only nonzeros are stored.""" + DIM_SINGLETON: _DimLevelType.ValueType # 2 + """The corresponding dimension contains a single coordinate, no sibling + elements for each parent. + """ + DIM_LOOSE_COMPRESSED: _DimLevelType.ValueType # 3 + """The corresponding dimension is Compressed, but with potential trailing + zeros, thus an extra upper bound (high) is used to exclude those zeros. + E.g., indices = [1, 2, 0, 0, 3, 4, 0, 0], position = [(0, 2), (4, 6)]. + """ + +class DimLevelType(_DimLevelType, metaclass=_DimLevelTypeEnumTypeWrapper): + """A DimLevelType indicates the encoding method for a dimension in an array. + The semantics of this field are identical to those of the MLIR SparseTensor + dialect. + This should be kept in sync with the SparseTensor DimLevelType enum: + https://github.com/llvm/llvm-project/blob/5674a3c88088e668b684326c2194a6282e8270ff/mlir/include/mlir/Dialect/SparseTensor/IR/SparseTensorAttrDefs.td#L86 + """ + +DIM_DENSE: DimLevelType.ValueType # 0 +"""The corresponding dimension is Dense, every entry is stored.""" +DIM_COMPRESSED: DimLevelType.ValueType # 1 +"""The corresponding dimension is Compressed, only nonzeros are stored.""" +DIM_SINGLETON: DimLevelType.ValueType # 2 +"""The corresponding dimension contains a single coordinate, no sibling +elements for each parent. +""" +DIM_LOOSE_COMPRESSED: DimLevelType.ValueType # 3 +"""The corresponding dimension is Compressed, but with potential trailing +zeros, thus an extra upper bound (high) is used to exclude those zeros. +E.g., indices = [1, 2, 0, 0, 3, 4, 0, 0], position = [(0, 2), (4, 6)]. +""" +global___DimLevelType = DimLevelType + +class _ProfileType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ProfileTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ProfileType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: _ProfileType.ValueType # 0 + WINDOW: _ProfileType.ValueType # 1 + FLAG: _ProfileType.ValueType # 2 + INTEGER: _ProfileType.ValueType # 3 + +class ProfileType(_ProfileType, metaclass=_ProfileTypeEnumTypeWrapper): + """The type optimization profiles in use for Op-level optimizations.""" + +INVALID: ProfileType.ValueType # 0 +WINDOW: ProfileType.ValueType # 1 +FLAG: ProfileType.ValueType # 2 +INTEGER: ProfileType.ValueType # 3 +global___ProfileType = ProfileType + +class _ProfileSource: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ProfileSourceEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ProfileSource.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PROFILE_SOURCE_UNKNOWN_SOURCE: _ProfileSource.ValueType # 0 + PROFILE_SOURCE_EMBEDDED: _ProfileSource.ValueType # 1 + PROFILE_SOURCE_REMOTE: _ProfileSource.ValueType # 2 + +class ProfileSource(_ProfileSource, metaclass=_ProfileSourceEnumTypeWrapper): + """The source of the optimization profile.""" + +PROFILE_SOURCE_UNKNOWN_SOURCE: ProfileSource.ValueType # 0 +PROFILE_SOURCE_EMBEDDED: ProfileSource.ValueType # 1 +PROFILE_SOURCE_REMOTE: ProfileSource.ValueType # 2 +global___ProfileSource = ProfileSource + +class _CompilationEvent: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _CompilationEventEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_CompilationEvent.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + COMPILATION_EVENT_UNKNOWN_EVENT: _CompilationEvent.ValueType # 0 + COMPILATION_EVENT_FIRST_COMPILATION: _CompilationEvent.ValueType # 1 + COMPILATION_EVENT_RECOMPILATION: _CompilationEvent.ValueType # 2 + +class CompilationEvent(_CompilationEvent, metaclass=_CompilationEventEnumTypeWrapper): + """The compilation event that triggered the use of the profile.""" + +COMPILATION_EVENT_UNKNOWN_EVENT: CompilationEvent.ValueType # 0 +COMPILATION_EVENT_FIRST_COMPILATION: CompilationEvent.ValueType # 1 +COMPILATION_EVENT_RECOMPILATION: CompilationEvent.ValueType # 2 +global___CompilationEvent = CompilationEvent + +class _PaddingType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _PaddingTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_PaddingType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PADDING_INVALID: _PaddingType.ValueType # 0 + PADDING_VALID: _PaddingType.ValueType # 1 + """Only valid portion of the base are covered.""" + PADDING_SAME: _PaddingType.ValueType # 2 + """Extra is added to produce same output size as the input.""" + +class PaddingType(_PaddingType, metaclass=_PaddingTypeEnumTypeWrapper): ... + +PADDING_INVALID: PaddingType.ValueType # 0 +PADDING_VALID: PaddingType.ValueType # 1 +"""Only valid portion of the base are covered.""" +PADDING_SAME: PaddingType.ValueType # 2 +"""Extra is added to produce same output size as the input.""" +global___PaddingType = PaddingType + +class _FftType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _FftTypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_FftType.ValueType], builtins.type): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + FFT: _FftType.ValueType # 0 + """Forward FFT; complex in, complex out.""" + IFFT: _FftType.ValueType # 1 + """Inverse FFT; complex in, complex out.""" + RFFT: _FftType.ValueType # 2 + """Forward real FFT; real in, fft_length / 2 + 1 complex out""" + IRFFT: _FftType.ValueType # 3 + """Inverse real FFT; fft_length / 2 + 1 complex in,""" + +class FftType(_FftType, metaclass=_FftTypeEnumTypeWrapper): ... + +FFT: FftType.ValueType # 0 +"""Forward FFT; complex in, complex out.""" +IFFT: FftType.ValueType # 1 +"""Inverse FFT; complex in, complex out.""" +RFFT: FftType.ValueType # 2 +"""Forward real FFT; real in, fft_length / 2 + 1 complex out""" +IRFFT: FftType.ValueType # 3 +"""Inverse real FFT; fft_length / 2 + 1 complex in,""" +global___FftType = FftType + +class _SparsityType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _SparsityTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_SparsityType.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + SPARSITY_INVALID: _SparsityType.ValueType # 0 + SPARSITY_STRUCTURED_N_M: _SparsityType.ValueType # 1 + """Structured N:M sparsity.""" + +class SparsityType(_SparsityType, metaclass=_SparsityTypeEnumTypeWrapper): ... + +SPARSITY_INVALID: SparsityType.ValueType # 0 +SPARSITY_STRUCTURED_N_M: SparsityType.ValueType # 1 +"""Structured N:M sparsity.""" +global___SparsityType = SparsityType + +class _RandomDistribution: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RandomDistributionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_RandomDistribution.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RNG_INVALID: _RandomDistribution.ValueType # 0 + RNG_UNIFORM: _RandomDistribution.ValueType # 1 + """Creates a uniform-distribution-generated random number on the semi-open + interval [parameter[0], parameter[1]). + """ + RNG_NORMAL: _RandomDistribution.ValueType # 2 + """Creates a normal-distribution-generated random number with mean + parameter[0] and standard deviation parameter[1]. + """ + +class RandomDistribution(_RandomDistribution, metaclass=_RandomDistributionEnumTypeWrapper): ... + +RNG_INVALID: RandomDistribution.ValueType # 0 +RNG_UNIFORM: RandomDistribution.ValueType # 1 +"""Creates a uniform-distribution-generated random number on the semi-open +interval [parameter[0], parameter[1]). +""" +RNG_NORMAL: RandomDistribution.ValueType # 2 +"""Creates a normal-distribution-generated random number with mean +parameter[0] and standard deviation parameter[1]. +""" +global___RandomDistribution = RandomDistribution + +class _RandomAlgorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _RandomAlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_RandomAlgorithm.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + RNG_DEFAULT: _RandomAlgorithm.ValueType # 0 + """Backend dependent default algorithm.""" + RNG_THREE_FRY: _RandomAlgorithm.ValueType # 1 + RNG_PHILOX: _RandomAlgorithm.ValueType # 2 + """Next: 2""" + +class RandomAlgorithm(_RandomAlgorithm, metaclass=_RandomAlgorithmEnumTypeWrapper): ... + +RNG_DEFAULT: RandomAlgorithm.ValueType # 0 +"""Backend dependent default algorithm.""" +RNG_THREE_FRY: RandomAlgorithm.ValueType # 1 +RNG_PHILOX: RandomAlgorithm.ValueType # 2 +"""Next: 2""" +global___RandomAlgorithm = RandomAlgorithm + +@typing.final +class PaddingConfig(google.protobuf.message.Message): + """Describes the padding configuration for Pad operation. The padding amount on + both edges as well as between the elements are specified for each dimension. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class PaddingConfigDimension(google.protobuf.message.Message): + """Describes the padding configuration for a dimension.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + EDGE_PADDING_LOW_FIELD_NUMBER: builtins.int + EDGE_PADDING_HIGH_FIELD_NUMBER: builtins.int + INTERIOR_PADDING_FIELD_NUMBER: builtins.int + edge_padding_low: builtins.int + """Padding amount on the low-end (next to the index 0). May be negative.""" + edge_padding_high: builtins.int + """Padding amount on the high-end (next to the highest index). May be + negative. + """ + interior_padding: builtins.int + """Padding amount between the elements. May not be negative.""" + def __init__( + self, + *, + edge_padding_low: builtins.int | None = ..., + edge_padding_high: builtins.int | None = ..., + interior_padding: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "edge_padding_high", + b"edge_padding_high", + "edge_padding_low", + b"edge_padding_low", + "interior_padding", + b"interior_padding", + ], + ) -> None: ... + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___PaddingConfig.PaddingConfigDimension]: + """The padding configuration for all dimensions.""" + + def __init__( + self, *, dimensions: collections.abc.Iterable[global___PaddingConfig.PaddingConfigDimension] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___PaddingConfig = PaddingConfig + +@typing.final +class TileProto(google.protobuf.message.Message): + """Describes a tile used in tiling-based layout. Refer to + g3doc/third_party/xla/docs/tiled_layout.md for details about tiling-based + layout. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Number of elements in each dimension of the tile. It's ordered from the + most major dimension of the tile to the most minor dimension of the tile. + The dimensions correspond to a suffix of the dimensions of the shape being + tiled. + """ + + def __init__(self, *, dimensions: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___TileProto = TileProto + +@typing.final +class SplitConfigProto(google.protobuf.message.Message): + """Describes how data should be split between different memories.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSION_FIELD_NUMBER: builtins.int + SPLIT_INDICES_FIELD_NUMBER: builtins.int + dimension: builtins.int + """The dimension that is split.""" + @property + def split_indices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The indices where each split point occurs. For example, if the dimension + size is 1024, a split_indices value of {512} indicates a two-way split of + data through the middle. + """ + + def __init__( + self, *, dimension: builtins.int | None = ..., split_indices: collections.abc.Iterable[builtins.int] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["dimension", b"dimension", "split_indices", b"split_indices"]) -> None: ... + +global___SplitConfigProto = SplitConfigProto + +@typing.final +class LayoutProto(google.protobuf.message.Message): + """A layout describes how the array is placed in (1D) memory space. This + includes the minor-to-major ordering of dimensions within a shape. + + Clients must specify the layouts of input Literals to the + computation. Layouts specified in interior operations which take Shapes (for + example, Convert) are ignored. + + See the XLA documentation for more information on shapes and layouts. + + LINT.IfChange + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIM_LEVEL_TYPES_FIELD_NUMBER: builtins.int + DIM_UNIQUE_FIELD_NUMBER: builtins.int + DIM_ORDERED_FIELD_NUMBER: builtins.int + MINOR_TO_MAJOR_FIELD_NUMBER: builtins.int + TILES_FIELD_NUMBER: builtins.int + TAIL_PADDING_ALIGNMENT_IN_ELEMENTS_FIELD_NUMBER: builtins.int + ELEMENT_SIZE_IN_BITS_FIELD_NUMBER: builtins.int + MEMORY_SPACE_FIELD_NUMBER: builtins.int + INDEX_PRIMITIVE_TYPE_FIELD_NUMBER: builtins.int + POINTER_PRIMITIVE_TYPE_FIELD_NUMBER: builtins.int + PHYSICAL_SHAPE_FIELD_NUMBER: builtins.int + DYNAMIC_SHAPE_METADATA_PREFIX_BYTES_FIELD_NUMBER: builtins.int + SPLIT_CONFIGS_FIELD_NUMBER: builtins.int + tail_padding_alignment_in_elements: builtins.int + """The shape is padded at the end to multiple of, in terms of number of + elements. This is useful when tiling does not bring the shape to certain + desired granules. Tiling effectively pads/reshapes/transposes the shape + to another shape. This field pads the total number of elements of that + new shape to a multiple of certain number of elements. This is useful such + as we want a layout which does not tile the data but still requires it to + be padded to certain number of elements. + """ + element_size_in_bits: builtins.int + """(Optional) Bit size of each element. When unspecified or being 0, default + to ShapeUtil::ByteSizeOfPrimitiveType. + """ + memory_space: builtins.int + """Memory space where this array resides. The integer field is interpreted in + a backend-specific manner. + """ + index_primitive_type: global___PrimitiveType.ValueType + """The integer types to be used for indices and pointers. These fields must + not be used unless the layout represents a sparse array. The PrimitiveType + must correspond to an unsigned integer (U8, U16, U32, or U64). + If not provided, the compiler will use the largest unsigned integer + that is naturally supported by the target device (U32 or U64 in currently + supported devices). + """ + pointer_primitive_type: global___PrimitiveType.ValueType + dynamic_shape_metadata_prefix_bytes: builtins.int + """The dynamic shape metadata size in bytes in front of the shape data. The + field may be non-zero for a static shape whose associated buffer is for a + dynamic shape, e.g. a result of SliceToDynamic. + """ + @property + def dim_level_types( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DimLevelType.ValueType]: + """The dimension level type list for this array, specifying the way in which + each array dimension is represented in memory. If this list is empty, the + array is assumed to be dense. + """ + + @property + def dim_unique(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Whether each dimension is unique or ordered. Each of the following lists + must be empty, or have one entry for each entry of dim_level_types. If + either list is empty, all dimensions are assumed to be unique and ordered, + respectively. Entries in this list may not be false for some DimLevelType + values (such as DIM_DENSE in particular). + """ + + @property + def dim_ordered(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def minor_to_major(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Sequence of dimension numbers, from minor (fastest varying index) to major + (slowest varying index). This field is required. + """ + + @property + def tiles(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___TileProto]: + """A sequence of tiles, starting from the tile that's applied first to the + Shape. + + TODO(b/119839262): implement tiling in each backend or add Unimplemented + error. + """ + + @property + def physical_shape(self) -> global___ShapeProto: + """The physical, on-device shape used to represent the shape this layout + belongs to. Only used for sparse arrays. + The layout(s) contained within the physical shape should not also contain + a physical shape. + """ + + @property + def split_configs(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___SplitConfigProto]: + """The split configurations which describe if/how the data is split between + different memories. + """ + + def __init__( + self, + *, + dim_level_types: collections.abc.Iterable[global___DimLevelType.ValueType] | None = ..., + dim_unique: collections.abc.Iterable[builtins.bool] | None = ..., + dim_ordered: collections.abc.Iterable[builtins.bool] | None = ..., + minor_to_major: collections.abc.Iterable[builtins.int] | None = ..., + tiles: collections.abc.Iterable[global___TileProto] | None = ..., + tail_padding_alignment_in_elements: builtins.int | None = ..., + element_size_in_bits: builtins.int | None = ..., + memory_space: builtins.int | None = ..., + index_primitive_type: global___PrimitiveType.ValueType | None = ..., + pointer_primitive_type: global___PrimitiveType.ValueType | None = ..., + physical_shape: global___ShapeProto | None = ..., + dynamic_shape_metadata_prefix_bytes: builtins.int | None = ..., + split_configs: collections.abc.Iterable[global___SplitConfigProto] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["physical_shape", b"physical_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dim_level_types", + b"dim_level_types", + "dim_ordered", + b"dim_ordered", + "dim_unique", + b"dim_unique", + "dynamic_shape_metadata_prefix_bytes", + b"dynamic_shape_metadata_prefix_bytes", + "element_size_in_bits", + b"element_size_in_bits", + "index_primitive_type", + b"index_primitive_type", + "memory_space", + b"memory_space", + "minor_to_major", + b"minor_to_major", + "physical_shape", + b"physical_shape", + "pointer_primitive_type", + b"pointer_primitive_type", + "split_configs", + b"split_configs", + "tail_padding_alignment_in_elements", + b"tail_padding_alignment_in_elements", + "tiles", + b"tiles", + ], + ) -> None: ... + +global___LayoutProto = LayoutProto + +@typing.final +class ShapeProto(google.protobuf.message.Message): + """A shape describes the number of dimensions in the array, the size of each + dimension, and the primitive component type. + + Tuples are a special case in that they have rank zero and have tuple_shapes + defined. + + See the XLA documentation for more information on shapes and layouts. + + LINT.IfChange + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ELEMENT_TYPE_FIELD_NUMBER: builtins.int + DIMENSIONS_FIELD_NUMBER: builtins.int + TUPLE_SHAPES_FIELD_NUMBER: builtins.int + LAYOUT_FIELD_NUMBER: builtins.int + IS_DYNAMIC_DIMENSION_FIELD_NUMBER: builtins.int + element_type: global___PrimitiveType.ValueType + """The element type for this shape.""" + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The size (number of elements) for each dimension, or an upper bound on the + size if the dimension is dynamic. In XLA, dimensions are numbered from 0 + to N-1 for an N-dimensional array. The first element of 'dimensions' is the + size of dimension 0, the second element is the size of dimension 1, and so + forth. Empty list indicates a scalar. + + If the respective element in 'is_dimension_dynamic' is true then the value + in this field represents an upper bound on the size of the dimension. + """ + + @property + def tuple_shapes(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShapeProto]: + """For tuples only, the shapes of constituent shapes in the tuple sequence.""" + + @property + def layout(self) -> global___LayoutProto: + """The layout used to back this shape.""" + + @property + def is_dynamic_dimension(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """For arrays, this indicates whether or not each dimension is + dynamically-sized. The number of elements in this repeated field should be + zero (indicating that no dimensions are dynamic) or equal to the number of + elements in the 'dimensions' field. + """ + + def __init__( + self, + *, + element_type: global___PrimitiveType.ValueType | None = ..., + dimensions: collections.abc.Iterable[builtins.int] | None = ..., + tuple_shapes: collections.abc.Iterable[global___ShapeProto] | None = ..., + layout: global___LayoutProto | None = ..., + is_dynamic_dimension: collections.abc.Iterable[builtins.bool] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["layout", b"layout"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dimensions", + b"dimensions", + "element_type", + b"element_type", + "is_dynamic_dimension", + b"is_dynamic_dimension", + "layout", + b"layout", + "tuple_shapes", + b"tuple_shapes", + ], + ) -> None: ... + +global___ShapeProto = ShapeProto + +@typing.final +class ProgramShapeProto(google.protobuf.message.Message): + """Shape of the parameters and output of a computation (like a traditional + function signature). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PARAMETERS_FIELD_NUMBER: builtins.int + RESULT_FIELD_NUMBER: builtins.int + PARAMETER_NAMES_FIELD_NUMBER: builtins.int + @property + def parameters(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShapeProto]: ... + @property + def result(self) -> global___ShapeProto: ... + @property + def parameter_names(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + def __init__( + self, + *, + parameters: collections.abc.Iterable[global___ShapeProto] | None = ..., + result: global___ShapeProto | None = ..., + parameter_names: collections.abc.Iterable[builtins.str] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["result", b"result"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["parameter_names", b"parameter_names", "parameters", b"parameters", "result", b"result"] + ) -> None: ... + +global___ProgramShapeProto = ProgramShapeProto + +@typing.final +class ComputationStats(google.protobuf.message.Message): + """Statistics of a computation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FLOP_COUNT_FIELD_NUMBER: builtins.int + TRANSCENDENTAL_COUNT_FIELD_NUMBER: builtins.int + flop_count: builtins.float + """The number of floating point operations in the computation.""" + transcendental_count: builtins.float + """The number of transcendental operations (e.g., exp) in the computation.""" + def __init__(self, *, flop_count: builtins.float | None = ..., transcendental_count: builtins.float | None = ...) -> None: ... + def ClearField( + self, field_name: typing.Literal["flop_count", b"flop_count", "transcendental_count", b"transcendental_count"] + ) -> None: ... + +global___ComputationStats = ComputationStats + +@typing.final +class OpMetadata(google.protobuf.message.Message): + """Symbolization metadata for HLO Instructions. + + This metadata is used for debugging XLA code generation, as well as + performance profiling of XLA-generated executables. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ProfileInfo(google.protobuf.message.Message): + """Information about the optimization profile that this operation contains.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PROFILE_TYPE_FIELD_NUMBER: builtins.int + RELATIVE_SPEEDUP_FIELD_NUMBER: builtins.int + PROFILE_SOURCE_FIELD_NUMBER: builtins.int + COMPILATION_EVENT_FIELD_NUMBER: builtins.int + relative_speedup: builtins.float + """Speedup of tuned config compared to default config. + TODO(b/203817882) Set the relative_speedup. + """ + profile_source: global___ProfileSource.ValueType + """The source of the optimization profiles that this operation contains.""" + compilation_event: global___CompilationEvent.ValueType + """The compilation event that triggered the use of the profiles.""" + @property + def profile_type( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___ProfileType.ValueType]: + """The type of optimization profiles that this operation contains.""" + + def __init__( + self, + *, + profile_type: collections.abc.Iterable[global___ProfileType.ValueType] | None = ..., + relative_speedup: builtins.float | None = ..., + profile_source: global___ProfileSource.ValueType | None = ..., + compilation_event: global___CompilationEvent.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_event", + b"compilation_event", + "profile_source", + b"profile_source", + "profile_type", + b"profile_type", + "relative_speedup", + b"relative_speedup", + ], + ) -> None: ... + + OP_TYPE_FIELD_NUMBER: builtins.int + OP_NAME_FIELD_NUMBER: builtins.int + SOURCE_FILE_FIELD_NUMBER: builtins.int + SOURCE_LINE_FIELD_NUMBER: builtins.int + PROFILE_TYPE_FIELD_NUMBER: builtins.int + SIZE_OF_GENERATED_CODE_IN_BYTES_FIELD_NUMBER: builtins.int + SIZE_OF_MEMORY_WORKING_SET_IN_BYTES_FIELD_NUMBER: builtins.int + PROFILE_INFO_FIELD_NUMBER: builtins.int + DEDUPLICATED_NAME_FIELD_NUMBER: builtins.int + PRESERVE_LAYOUT_FIELD_NUMBER: builtins.int + STACK_FRAME_ID_FIELD_NUMBER: builtins.int + SCHEDULING_NAME_FIELD_NUMBER: builtins.int + op_type: builtins.str + """The framework op name that generated this XLA op. + + Frameworks that build on top of XLA should mirror the names of their ops + back to users by specifying the op_type. In this way, even if the + framework's "ops" are implemented as multiple XLA HLO Ops, they can be + grouped appropriately. (e.g. if a SoftMax layer is emitted into XLA as + multiple ops, then each op should have the op_type be "SoftMax".) + """ + op_name: builtins.str + """The user-specified name of the op. + + This name is often unique within a computation. Note: some frameworks + add auto-generated names if the user does not provide one. + """ + source_file: builtins.str + """Indicate a file and line that this op is associated to in a user's program. + + e.g. it could be the file and line of user code that generated the op. + """ + source_line: builtins.int + size_of_generated_code_in_bytes: builtins.int + """The footprint of the generated code for the instruction.""" + size_of_memory_working_set_in_bytes: builtins.int + """The size of the working set, i.e., the amount of memory, used by the + instruction in a compiler-managed fast device memory. + """ + deduplicated_name: builtins.str + """Deduplicated HLO name for this op. In some cases, we can have multiple + instructions (e.g. fusions) that are considered duplicates. We want to + group them together under the same name so that we can group them together + during analysis (e.g. HLO Op Profile tool in Xprof). + E.g. If we have fusion.1, fusion.2, and fusion.3 marked as duplicates, + fusion.2 and fusion.3 will have deduplicated_name = fusion.1 + """ + preserve_layout: builtins.bool + """Whether to preserve the layout of the HLO op.""" + stack_frame_id: builtins.int + """1-based position of the frame in frames flat array. + Ids are 1-based to keep 0 value as representation of non-set property. + """ + scheduling_name: builtins.str + """Instruction name available upon scheduling.""" + @property + def profile_type(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___ProfileType.ValueType]: + """Deprecated, use [ProfileInfo][profile_type] instead.""" + + @property + def profile_info(self) -> global___OpMetadata.ProfileInfo: + """Profile information for the Op.""" + + def __init__( + self, + *, + op_type: builtins.str | None = ..., + op_name: builtins.str | None = ..., + source_file: builtins.str | None = ..., + source_line: builtins.int | None = ..., + profile_type: collections.abc.Iterable[global___ProfileType.ValueType] | None = ..., + size_of_generated_code_in_bytes: builtins.int | None = ..., + size_of_memory_working_set_in_bytes: builtins.int | None = ..., + profile_info: global___OpMetadata.ProfileInfo | None = ..., + deduplicated_name: builtins.str | None = ..., + preserve_layout: builtins.bool | None = ..., + stack_frame_id: builtins.int | None = ..., + scheduling_name: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["profile_info", b"profile_info"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "deduplicated_name", + b"deduplicated_name", + "op_name", + b"op_name", + "op_type", + b"op_type", + "preserve_layout", + b"preserve_layout", + "profile_info", + b"profile_info", + "profile_type", + b"profile_type", + "scheduling_name", + b"scheduling_name", + "size_of_generated_code_in_bytes", + b"size_of_generated_code_in_bytes", + "size_of_memory_working_set_in_bytes", + b"size_of_memory_working_set_in_bytes", + "source_file", + b"source_file", + "source_line", + b"source_line", + "stack_frame_id", + b"stack_frame_id", + ], + ) -> None: ... + +global___OpMetadata = OpMetadata + +@typing.final +class ExecutionProfile(google.protobuf.message.Message): + """Profile data from the execution of a computation.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COMPILATION_CACHE_HIT_FIELD_NUMBER: builtins.int + COMPILE_TIME_MS_FIELD_NUMBER: builtins.int + COMPUTE_CYCLE_COUNT_FIELD_NUMBER: builtins.int + COMPUTE_TIME_NS_FIELD_NUMBER: builtins.int + COMPUTE_AND_TRANSFER_TIME_NS_FIELD_NUMBER: builtins.int + EXECUTABLE_SIZE_IN_BYTES_FIELD_NUMBER: builtins.int + PROFILE_CACHE_HIT_FIELD_NUMBER: builtins.int + WARMUP_RUN_EXECUTED_FIELD_NUMBER: builtins.int + compilation_cache_hit: builtins.bool + """Whether the executable was read from the compilation cache.""" + compile_time_ms: builtins.int + """The time in milliseconds spent to compile the computation. This only set if + the executable was not read from the compilation cache + (compilation_cache_hit == false). + """ + compute_cycle_count: builtins.int + """The number of cycles spent for the computation. This does not include the + time taken for the data transfers between the host and the device. This is + a target-dependent field and only used for debugging purposes. + """ + compute_time_ns: builtins.int + """The time in nanoseconds spent for the computation, without data transfer.""" + compute_and_transfer_time_ns: builtins.int + """The time in nanoseconds spent for the entire computation, including the + result data transfer time. Current implementation does not spend any cycles + for the input data transfer since the memory is initialized with the proper + values before the execution. + """ + executable_size_in_bytes: builtins.int + """The size of the binary code in the executable.""" + profile_cache_hit: builtins.bool + """Whether this profile was drawn from a cache of profiles instead of from + execution on the hardware. + """ + warmup_run_executed: builtins.bool + """Whether a warm-up run of the computation was executed before the + measured execution. + """ + def __init__( + self, + *, + compilation_cache_hit: builtins.bool | None = ..., + compile_time_ms: builtins.int | None = ..., + compute_cycle_count: builtins.int | None = ..., + compute_time_ns: builtins.int | None = ..., + compute_and_transfer_time_ns: builtins.int | None = ..., + executable_size_in_bytes: builtins.int | None = ..., + profile_cache_hit: builtins.bool | None = ..., + warmup_run_executed: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compilation_cache_hit", + b"compilation_cache_hit", + "compile_time_ms", + b"compile_time_ms", + "compute_and_transfer_time_ns", + b"compute_and_transfer_time_ns", + "compute_cycle_count", + b"compute_cycle_count", + "compute_time_ns", + b"compute_time_ns", + "executable_size_in_bytes", + b"executable_size_in_bytes", + "profile_cache_hit", + b"profile_cache_hit", + "warmup_run_executed", + b"warmup_run_executed", + ], + ) -> None: ... + +global___ExecutionProfile = ExecutionProfile + +@typing.final +class ExecutionHandle(google.protobuf.message.Message): + """Handle given to a user that represents an execution that the user launched + asynchronously on the device. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + handle: builtins.int + def __init__(self, *, handle: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle"]) -> None: ... + +global___ExecutionHandle = ExecutionHandle + +@typing.final +class GlobalDataHandle(google.protobuf.message.Message): + """Handle given to a user that represents a globally accessible allocation. + Contrast this against a ComputationDataHandle, which is not globally + accessible, since it only exists within a specific computation. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + handle: builtins.int + def __init__(self, *, handle: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle"]) -> None: ... + +global___GlobalDataHandle = GlobalDataHandle + +@typing.final +class DeviceHandle(google.protobuf.message.Message): + """Handle given to a user that represents a replicated virtual device. Each + replicated device represents N physical devices for execution where N is the + number of replicas. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HANDLE_FIELD_NUMBER: builtins.int + DEVICE_COUNT_FIELD_NUMBER: builtins.int + handle: builtins.int + device_count: builtins.int + """The number of model-parallel virtual devices that communicate via XLA + Send/Recv instructions. + """ + def __init__(self, *, handle: builtins.int | None = ..., device_count: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["device_count", b"device_count", "handle", b"handle"]) -> None: ... + +global___DeviceHandle = DeviceHandle + +@typing.final +class ChannelHandle(google.protobuf.message.Message): + """Handle given to a user to represent a channel between two computations + via a Send and Recv instruction pair. Channels are unbuffered, so Send + Send instructions will be blocked until the data is transferred. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ChannelType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ChannelTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ChannelHandle._ChannelType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CHANNEL_TYPE_INVALID: ChannelHandle._ChannelType.ValueType # 0 + """Invalid primitive type to serve as default.""" + DEVICE_TO_DEVICE: ChannelHandle._ChannelType.ValueType # 1 + """A channel for sending data between devices.""" + DEVICE_TO_HOST: ChannelHandle._ChannelType.ValueType # 2 + """A channel for sending data from the device to the host. Can only be used + with a Send operation. + """ + HOST_TO_DEVICE: ChannelHandle._ChannelType.ValueType # 3 + """A channel for sending data from the host to the device. Can only be used + with a Recv operation. + """ + + class ChannelType(_ChannelType, metaclass=_ChannelTypeEnumTypeWrapper): ... + CHANNEL_TYPE_INVALID: ChannelHandle.ChannelType.ValueType # 0 + """Invalid primitive type to serve as default.""" + DEVICE_TO_DEVICE: ChannelHandle.ChannelType.ValueType # 1 + """A channel for sending data between devices.""" + DEVICE_TO_HOST: ChannelHandle.ChannelType.ValueType # 2 + """A channel for sending data from the device to the host. Can only be used + with a Send operation. + """ + HOST_TO_DEVICE: ChannelHandle.ChannelType.ValueType # 3 + """A channel for sending data from the host to the device. Can only be used + with a Recv operation. + """ + + HANDLE_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + handle: builtins.int + type: global___ChannelHandle.ChannelType.ValueType + def __init__( + self, *, handle: builtins.int | None = ..., type: global___ChannelHandle.ChannelType.ValueType | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["handle", b"handle", "type", b"type"]) -> None: ... + +global___ChannelHandle = ChannelHandle + +@typing.final +class DeviceAssignmentProto(google.protobuf.message.Message): + """DeviceAssignmentProto is a serialized form of DeviceAssignment class, which + represents the device ids assigned to a set of replicated computations. + See xla::DeviceAssignment class comment for more details. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ComputationDevice(google.protobuf.message.Message): + """Each logical computation runs on replica_count physical devices. + ComputationDevice represents the device ids assinged to the replicas. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_DEVICE_IDS_FIELD_NUMBER: builtins.int + @property + def replica_device_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, replica_device_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replica_device_ids", b"replica_device_ids"]) -> None: ... + + REPLICA_COUNT_FIELD_NUMBER: builtins.int + COMPUTATION_COUNT_FIELD_NUMBER: builtins.int + COMPUTATION_DEVICES_FIELD_NUMBER: builtins.int + replica_count: builtins.int + computation_count: builtins.int + @property + def computation_devices( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___DeviceAssignmentProto.ComputationDevice + ]: ... + def __init__( + self, + *, + replica_count: builtins.int | None = ..., + computation_count: builtins.int | None = ..., + computation_devices: collections.abc.Iterable[global___DeviceAssignmentProto.ComputationDevice] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_count", + b"computation_count", + "computation_devices", + b"computation_devices", + "replica_count", + b"replica_count", + ], + ) -> None: ... + +global___DeviceAssignmentProto = DeviceAssignmentProto + +@typing.final +class LiteralProto(google.protobuf.message.Message): + """Literals are used when the server and client need to exchange materialized + data / results. Literals are also used to describe constants used in + computations. + + Transfers to/from the client are encoded in literal form, and the structure + of the repeated fields is implied by the shape. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_FIELD_NUMBER: builtins.int + PREDS_FIELD_NUMBER: builtins.int + S2S_FIELD_NUMBER: builtins.int + S4S_FIELD_NUMBER: builtins.int + S8S_FIELD_NUMBER: builtins.int + U2S_FIELD_NUMBER: builtins.int + U4S_FIELD_NUMBER: builtins.int + U8S_FIELD_NUMBER: builtins.int + S32S_FIELD_NUMBER: builtins.int + S64S_FIELD_NUMBER: builtins.int + U32S_FIELD_NUMBER: builtins.int + U64S_FIELD_NUMBER: builtins.int + F32S_FIELD_NUMBER: builtins.int + F64S_FIELD_NUMBER: builtins.int + C64S_FIELD_NUMBER: builtins.int + C128S_FIELD_NUMBER: builtins.int + TUPLE_LITERALS_FIELD_NUMBER: builtins.int + F16S_FIELD_NUMBER: builtins.int + BF16S_FIELD_NUMBER: builtins.int + U16S_FIELD_NUMBER: builtins.int + S16S_FIELD_NUMBER: builtins.int + F8E5M2S_FIELD_NUMBER: builtins.int + F8E4M3FNS_FIELD_NUMBER: builtins.int + F8E4M3B11FNUZS_FIELD_NUMBER: builtins.int + F8E5M2FNUZS_FIELD_NUMBER: builtins.int + F8E4M3FNUZS_FIELD_NUMBER: builtins.int + SPARSE_INDICES_FIELD_NUMBER: builtins.int + s2s: builtins.bytes + s4s: builtins.bytes + s8s: builtins.bytes + u2s: builtins.bytes + u4s: builtins.bytes + u8s: builtins.bytes + f16s: builtins.bytes + """The F16s, BF16s, U16s and S16s are encoded in little endian byte order""" + bf16s: builtins.bytes + u16s: builtins.bytes + s16s: builtins.bytes + f8e5m2s: builtins.bytes + f8e4m3fns: builtins.bytes + f8e4m3b11fnuzs: builtins.bytes + f8e5m2fnuzs: builtins.bytes + f8e4m3fnuzs: builtins.bytes + @property + def shape(self) -> global___ShapeProto: ... + @property + def preds(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def s32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def s64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def u32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def u64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def f32s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + @property + def f64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + @property + def c64s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """Stored as interleaved real, imag floats.""" + + @property + def c128s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """Stored as interleaved real, imag doubles.""" + + @property + def tuple_literals(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___LiteralProto]: ... + @property + def sparse_indices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Next = 28""" + + def __init__( + self, + *, + shape: global___ShapeProto | None = ..., + preds: collections.abc.Iterable[builtins.bool] | None = ..., + s2s: builtins.bytes | None = ..., + s4s: builtins.bytes | None = ..., + s8s: builtins.bytes | None = ..., + u2s: builtins.bytes | None = ..., + u4s: builtins.bytes | None = ..., + u8s: builtins.bytes | None = ..., + s32s: collections.abc.Iterable[builtins.int] | None = ..., + s64s: collections.abc.Iterable[builtins.int] | None = ..., + u32s: collections.abc.Iterable[builtins.int] | None = ..., + u64s: collections.abc.Iterable[builtins.int] | None = ..., + f32s: collections.abc.Iterable[builtins.float] | None = ..., + f64s: collections.abc.Iterable[builtins.float] | None = ..., + c64s: collections.abc.Iterable[builtins.float] | None = ..., + c128s: collections.abc.Iterable[builtins.float] | None = ..., + tuple_literals: collections.abc.Iterable[global___LiteralProto] | None = ..., + f16s: builtins.bytes | None = ..., + bf16s: builtins.bytes | None = ..., + u16s: builtins.bytes | None = ..., + s16s: builtins.bytes | None = ..., + f8e5m2s: builtins.bytes | None = ..., + f8e4m3fns: builtins.bytes | None = ..., + f8e4m3b11fnuzs: builtins.bytes | None = ..., + f8e5m2fnuzs: builtins.bytes | None = ..., + f8e4m3fnuzs: builtins.bytes | None = ..., + sparse_indices: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bf16s", + b"bf16s", + "c128s", + b"c128s", + "c64s", + b"c64s", + "f16s", + b"f16s", + "f32s", + b"f32s", + "f64s", + b"f64s", + "f8e4m3b11fnuzs", + b"f8e4m3b11fnuzs", + "f8e4m3fns", + b"f8e4m3fns", + "f8e4m3fnuzs", + b"f8e4m3fnuzs", + "f8e5m2fnuzs", + b"f8e5m2fnuzs", + "f8e5m2s", + b"f8e5m2s", + "preds", + b"preds", + "s16s", + b"s16s", + "s2s", + b"s2s", + "s32s", + b"s32s", + "s4s", + b"s4s", + "s64s", + b"s64s", + "s8s", + b"s8s", + "shape", + b"shape", + "sparse_indices", + b"sparse_indices", + "tuple_literals", + b"tuple_literals", + "u16s", + b"u16s", + "u2s", + b"u2s", + "u32s", + b"u32s", + "u4s", + b"u4s", + "u64s", + b"u64s", + "u8s", + b"u8s", + ], + ) -> None: ... + +global___LiteralProto = LiteralProto + +@typing.final +class WindowDimension(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIZE_FIELD_NUMBER: builtins.int + STRIDE_FIELD_NUMBER: builtins.int + PADDING_LOW_FIELD_NUMBER: builtins.int + PADDING_HIGH_FIELD_NUMBER: builtins.int + WINDOW_DILATION_FIELD_NUMBER: builtins.int + BASE_DILATION_FIELD_NUMBER: builtins.int + WINDOW_REVERSAL_FIELD_NUMBER: builtins.int + size: builtins.int + """The size of the window in this dimension. For a rectangle, this would be + the width or height. + """ + stride: builtins.int + """The stride at which the window moves across the base area in this + dimension. In other words, this is the spacing between different + positions of the window in this dimension. + """ + padding_low: builtins.int + """If positive, means the amount of padding to add to the base area at the low + end of this dimension; if negative, its negative means the number of + elements removed from the low end of this dimension. For example, in the + horizontal dimension of a rectangle, this would be the number of padding + values to pad on the left, given that indices increase when going right. + The actual padding value depends upon the context. Convolution pads with + zeros. ReduceWindow and SelectAndScatter pads with the reduce function's + init value. + """ + padding_high: builtins.int + """As padding_low, but on the high end of this dimension. For example, in the + horizontal dimension of a rectangle, this would be the number of values to + pad on the right, given that indices increase when going right. + """ + window_dilation: builtins.int + """Dilation factor of the sliding window in this dimension. A dilation factor + of 1 means no dilation. window_dilation - 1 no-op entries ("holes") are + implicitly placed between each kernel element. This value may not be less + than 1. See documentation for convolution. + """ + base_dilation: builtins.int + """Dilation factor of the base area in this dimension. A dilation factor of 1 + means no dilation. base_dilation - 1 no-op entries ("holes") are implicitly + placed between each base area element. This value may not be less than 1. + See documentation for convolution. + """ + window_reversal: builtins.bool + """Window reversal means that this dimension was logically reversed before the + operation. + """ + def __init__( + self, + *, + size: builtins.int | None = ..., + stride: builtins.int | None = ..., + padding_low: builtins.int | None = ..., + padding_high: builtins.int | None = ..., + window_dilation: builtins.int | None = ..., + base_dilation: builtins.int | None = ..., + window_reversal: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "base_dilation", + b"base_dilation", + "padding_high", + b"padding_high", + "padding_low", + b"padding_low", + "size", + b"size", + "stride", + b"stride", + "window_dilation", + b"window_dilation", + "window_reversal", + b"window_reversal", + ], + ) -> None: ... + +global___WindowDimension = WindowDimension + +@typing.final +class Window(google.protobuf.message.Message): + """Describes the windowing in an operation such as convolution. + + The window is moved across a base area and for each position of the + window a computation is performed. The field below describes the + window and the movement of the window across a base area. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def dimensions(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___WindowDimension]: ... + def __init__(self, *, dimensions: collections.abc.Iterable[global___WindowDimension] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dimensions", b"dimensions"]) -> None: ... + +global___Window = Window + +@typing.final +class GatherDimensionNumbers(google.protobuf.message.Message): + """Describes the dimension numbers for a gather operation. + + See https://www.tensorflow.org/performance/xla/operation_semantics#gather for + more details. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OFFSET_DIMS_FIELD_NUMBER: builtins.int + COLLAPSED_SLICE_DIMS_FIELD_NUMBER: builtins.int + START_INDEX_MAP_FIELD_NUMBER: builtins.int + INDEX_VECTOR_DIM_FIELD_NUMBER: builtins.int + OPERAND_BATCHING_DIMS_FIELD_NUMBER: builtins.int + START_INDICES_BATCHING_DIMS_FIELD_NUMBER: builtins.int + index_vector_dim: builtins.int + """The dimension in the start_indices input that contains the starting + indices. + """ + @property + def offset_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ "Window indices" is a term for a set of indices that index into the + interior of a dynamic-slice from the input tensor, the starting indices for + which were computed from output_gather_dims (see the operation semantic for + how this is defined) and the start_indices tensor. + + The window indices for a specific output index Out is computed as: + + i = 0 + for (k : [0, input_tensor_shape.rank)) + window_indices[k] = + if k in collapsed_slice_dims + then 0 + else Out[offset_dims[i++]] + """ + + @property + def collapsed_slice_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def start_index_map(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is interpreted as a map from i to start_index_map[i]. It + transforms the gather index looked up from the start_indices tensor into + the starting index in the input space. + """ + + @property + def operand_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimensions in the operand.""" + + @property + def start_indices_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimensions in the index, and it should be the same size + as operand_batching_dims. + """ + + def __init__( + self, + *, + offset_dims: collections.abc.Iterable[builtins.int] | None = ..., + collapsed_slice_dims: collections.abc.Iterable[builtins.int] | None = ..., + start_index_map: collections.abc.Iterable[builtins.int] | None = ..., + index_vector_dim: builtins.int | None = ..., + operand_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + start_indices_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "collapsed_slice_dims", + b"collapsed_slice_dims", + "index_vector_dim", + b"index_vector_dim", + "offset_dims", + b"offset_dims", + "operand_batching_dims", + b"operand_batching_dims", + "start_index_map", + b"start_index_map", + "start_indices_batching_dims", + b"start_indices_batching_dims", + ], + ) -> None: ... + +global___GatherDimensionNumbers = GatherDimensionNumbers + +@typing.final +class ScatterDimensionNumbers(google.protobuf.message.Message): + """Describes the dimension numbers for a scatter operation. + + All the fields are similar to the corresponding fields in + GatherDimensionNumbers. Differences are noted below. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + UPDATE_WINDOW_DIMS_FIELD_NUMBER: builtins.int + INSERTED_WINDOW_DIMS_FIELD_NUMBER: builtins.int + SCATTER_DIMS_TO_OPERAND_DIMS_FIELD_NUMBER: builtins.int + INDEX_VECTOR_DIM_FIELD_NUMBER: builtins.int + INPUT_BATCHING_DIMS_FIELD_NUMBER: builtins.int + SCATTER_INDICES_BATCHING_DIMS_FIELD_NUMBER: builtins.int + index_vector_dim: builtins.int + @property + def update_window_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The set of dimensions in the updates shape that are window dimensions.""" + + @property + def inserted_window_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The set of window dimensions that must be inserted into the updates shape.""" + + @property + def scatter_dims_to_operand_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def input_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimension in the input.""" + + @property + def scatter_indices_batching_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """This is the batch dimension in the index.""" + + def __init__( + self, + *, + update_window_dims: collections.abc.Iterable[builtins.int] | None = ..., + inserted_window_dims: collections.abc.Iterable[builtins.int] | None = ..., + scatter_dims_to_operand_dims: collections.abc.Iterable[builtins.int] | None = ..., + index_vector_dim: builtins.int | None = ..., + input_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + scatter_indices_batching_dims: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "index_vector_dim", + b"index_vector_dim", + "input_batching_dims", + b"input_batching_dims", + "inserted_window_dims", + b"inserted_window_dims", + "scatter_dims_to_operand_dims", + b"scatter_dims_to_operand_dims", + "scatter_indices_batching_dims", + b"scatter_indices_batching_dims", + "update_window_dims", + b"update_window_dims", + ], + ) -> None: ... + +global___ScatterDimensionNumbers = ScatterDimensionNumbers + +@typing.final +class ConvolutionDimensionNumbers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_BATCH_DIMENSION_FIELD_NUMBER: builtins.int + INPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + INPUT_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + KERNEL_INPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + KERNEL_OUTPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + KERNEL_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + OUTPUT_BATCH_DIMENSION_FIELD_NUMBER: builtins.int + OUTPUT_FEATURE_DIMENSION_FIELD_NUMBER: builtins.int + OUTPUT_SPATIAL_DIMENSIONS_FIELD_NUMBER: builtins.int + input_batch_dimension: builtins.int + """The number of the dimension that represents batch in the input.""" + input_feature_dimension: builtins.int + """The number of the dimension that represents features in the input.""" + kernel_input_feature_dimension: builtins.int + """The number of the dimension that represents input features in the + convolutional kernel (rhs). + """ + kernel_output_feature_dimension: builtins.int + """The number of the dimension that represents output features in + the convolutional kernel (rhs). + """ + output_batch_dimension: builtins.int + """The number of the dimension that represents batch in the output.""" + output_feature_dimension: builtins.int + """The number of the dimension that represents features in the output.""" + @property + def input_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the input. + """ + + @property + def kernel_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the kernel (rhs). window.strides(0) is the + stride in the kernel_spatial_dimensions(0) dimension. + """ + + @property + def output_spatial_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers for the spatial dimensions that the window + moves through in the output. + """ + + def __init__( + self, + *, + input_batch_dimension: builtins.int | None = ..., + input_feature_dimension: builtins.int | None = ..., + input_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + kernel_input_feature_dimension: builtins.int | None = ..., + kernel_output_feature_dimension: builtins.int | None = ..., + kernel_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + output_batch_dimension: builtins.int | None = ..., + output_feature_dimension: builtins.int | None = ..., + output_spatial_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_batch_dimension", + b"input_batch_dimension", + "input_feature_dimension", + b"input_feature_dimension", + "input_spatial_dimensions", + b"input_spatial_dimensions", + "kernel_input_feature_dimension", + b"kernel_input_feature_dimension", + "kernel_output_feature_dimension", + b"kernel_output_feature_dimension", + "kernel_spatial_dimensions", + b"kernel_spatial_dimensions", + "output_batch_dimension", + b"output_batch_dimension", + "output_feature_dimension", + b"output_feature_dimension", + "output_spatial_dimensions", + b"output_spatial_dimensions", + ], + ) -> None: ... + +global___ConvolutionDimensionNumbers = ConvolutionDimensionNumbers + +@typing.final +class DotDimensionNumbers(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LHS_CONTRACTING_DIMENSIONS_FIELD_NUMBER: builtins.int + RHS_CONTRACTING_DIMENSIONS_FIELD_NUMBER: builtins.int + LHS_BATCH_DIMENSIONS_FIELD_NUMBER: builtins.int + RHS_BATCH_DIMENSIONS_FIELD_NUMBER: builtins.int + @property + def lhs_contracting_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'lhs' contracting dimensions.""" + + @property + def rhs_contracting_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'rhs' contracting dimensions.""" + + @property + def lhs_batch_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'lhs' batch dimensions.""" + + @property + def rhs_batch_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension numbers that represent the 'rhs' batch dimensions.""" + + def __init__( + self, + *, + lhs_contracting_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + rhs_contracting_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + lhs_batch_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + rhs_batch_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "lhs_batch_dimensions", + b"lhs_batch_dimensions", + "lhs_contracting_dimensions", + b"lhs_contracting_dimensions", + "rhs_batch_dimensions", + b"rhs_batch_dimensions", + "rhs_contracting_dimensions", + b"rhs_contracting_dimensions", + ], + ) -> None: ... + +global___DotDimensionNumbers = DotDimensionNumbers + +@typing.final +class SparsityDescriptor(google.protobuf.message.Message): + """Contains sparsity metadata for a sparse dot operation. + The only supported type atm is structured 2:4 sparsity, which is natively + supported on NVidia GPUs. + Restrictions: + - only one operand of the dot operation may be sparse; + - only the contracting dimension may be sparse. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + TYPE_FIELD_NUMBER: builtins.int + INDEX_FIELD_NUMBER: builtins.int + DIMENSION_FIELD_NUMBER: builtins.int + N_FIELD_NUMBER: builtins.int + M_FIELD_NUMBER: builtins.int + type: global___SparsityType.ValueType + index: builtins.int + """Sparse operand index (0 or 1).""" + dimension: builtins.int + """Sparse dimension number.""" + n: builtins.int + """Structured N:M sparsity (N < M).""" + m: builtins.int + def __init__( + self, + *, + type: global___SparsityType.ValueType | None = ..., + index: builtins.int | None = ..., + dimension: builtins.int | None = ..., + n: builtins.int | None = ..., + m: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["dimension", b"dimension", "index", b"index", "m", b"m", "n", b"n", "type", b"type"] + ) -> None: ... + +global___SparsityDescriptor = SparsityDescriptor + +@typing.final +class TriangularSolveOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Transpose: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TransposeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[TriangularSolveOptions._Transpose.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TRANSPOSE_INVALID: TriangularSolveOptions._Transpose.ValueType # 0 + NO_TRANSPOSE: TriangularSolveOptions._Transpose.ValueType # 1 + """Don't transpose 'a'.""" + TRANSPOSE: TriangularSolveOptions._Transpose.ValueType # 2 + """Transpose 'a'.""" + ADJOINT: TriangularSolveOptions._Transpose.ValueType # 3 + """Complex conjugate and transpose 'a'.""" + + class Transpose(_Transpose, metaclass=_TransposeEnumTypeWrapper): + """Should we transpose or use the adjoint of 'a'?""" + + TRANSPOSE_INVALID: TriangularSolveOptions.Transpose.ValueType # 0 + NO_TRANSPOSE: TriangularSolveOptions.Transpose.ValueType # 1 + """Don't transpose 'a'.""" + TRANSPOSE: TriangularSolveOptions.Transpose.ValueType # 2 + """Transpose 'a'.""" + ADJOINT: TriangularSolveOptions.Transpose.ValueType # 3 + """Complex conjugate and transpose 'a'.""" + + LEFT_SIDE_FIELD_NUMBER: builtins.int + LOWER_FIELD_NUMBER: builtins.int + UNIT_DIAGONAL_FIELD_NUMBER: builtins.int + TRANSPOSE_A_FIELD_NUMBER: builtins.int + left_side: builtins.bool + """If true, solves ax = b. If false, solves xa = b.""" + lower: builtins.bool + """If true, 'a' is lower triangular. If false, 'a' is upper triangular.""" + unit_diagonal: builtins.bool + """If true, the diagonal elements of 'a' are assumed to be 1 and not accessed.""" + transpose_a: global___TriangularSolveOptions.Transpose.ValueType + def __init__( + self, + *, + left_side: builtins.bool | None = ..., + lower: builtins.bool | None = ..., + unit_diagonal: builtins.bool | None = ..., + transpose_a: global___TriangularSolveOptions.Transpose.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "left_side", b"left_side", "lower", b"lower", "transpose_a", b"transpose_a", "unit_diagonal", b"unit_diagonal" + ], + ) -> None: ... + +global___TriangularSolveOptions = TriangularSolveOptions + +@typing.final +class CholeskyOptions(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LOWER_FIELD_NUMBER: builtins.int + lower: builtins.bool + """If true, uses the lower triangle of `a`. If false, uses the upper triangle + of `a`. + """ + def __init__(self, *, lower: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["lower", b"lower"]) -> None: ... + +global___CholeskyOptions = CholeskyOptions + +@typing.final +class SortOptions(google.protobuf.message.Message): + """Attributes of the sort custom call (cub::DeviceRadixSort).""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DESCENDING_FIELD_NUMBER: builtins.int + descending: builtins.bool + def __init__(self, *, descending: builtins.bool | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["descending", b"descending"]) -> None: ... + +global___SortOptions = SortOptions + +@typing.final +class FrontendAttributes(google.protobuf.message.Message): + """Generic map of attributes used to pass hints / configuration options from + the Python frontend to the XLA backend. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class MapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + MAP_FIELD_NUMBER: builtins.int + @property + def map(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: ... + def __init__(self, *, map: collections.abc.Mapping[builtins.str, builtins.str] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["map", b"map"]) -> None: ... + +global___FrontendAttributes = FrontendAttributes + +@typing.final +class Statistic(google.protobuf.message.Message): + """Represents a single statistic to track.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STAT_NAME_FIELD_NUMBER: builtins.int + STAT_VAL_FIELD_NUMBER: builtins.int + stat_name: builtins.str + """Must be a single word consisting of any alphanumeric characters""" + stat_val: builtins.float + """Must be within a range of [0, 100], in order for the graph dumper to + properly render the statistic onto the graph. + """ + def __init__(self, *, stat_name: builtins.str | None = ..., stat_val: builtins.float | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["stat_name", b"stat_name", "stat_val", b"stat_val"]) -> None: ... + +global___Statistic = Statistic + +@typing.final +class StatisticsViz(google.protobuf.message.Message): + """Represents the information needed to visualize propagation statistics when + rendering an HLO graph. This includes an array of statistics as well as the + index of the statistic to render. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + STAT_INDEX_TO_VISUALIZE_FIELD_NUMBER: builtins.int + STATISTICS_FIELD_NUMBER: builtins.int + stat_index_to_visualize: builtins.int + @property + def statistics(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Statistic]: ... + def __init__( + self, + *, + stat_index_to_visualize: builtins.int | None = ..., + statistics: collections.abc.Iterable[global___Statistic] | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["stat_index_to_visualize", b"stat_index_to_visualize", "statistics", b"statistics"] + ) -> None: ... + +global___StatisticsViz = StatisticsViz + +@typing.final +class OpSharding(google.protobuf.message.Message): + """LINT.IfChange""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Type: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _TypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[OpSharding._Type.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + REPLICATED: OpSharding._Type.ValueType # 0 + """This sharding is replicated across all devices (implies maximal, + all other fields are unused). + """ + MAXIMAL: OpSharding._Type.ValueType # 1 + """This sharding is maximal - one device runs the entire operation.""" + TUPLE: OpSharding._Type.ValueType # 2 + """This sharding is a tuple - only the tuple_shardings field is valid.""" + OTHER: OpSharding._Type.ValueType # 3 + """None of the above; tile_shape and tile_assignment are both used.""" + MANUAL: OpSharding._Type.ValueType # 4 + """This op is manually sharded: the shapes are already partitioned and the + partitioner should not change this op. + """ + UNKNOWN: OpSharding._Type.ValueType # 5 + """This sharding is a placeholder sharding with lowest precedence, it can be + overwriten by any other shardings. + """ + + class Type(_Type, metaclass=_TypeEnumTypeWrapper): ... + REPLICATED: OpSharding.Type.ValueType # 0 + """This sharding is replicated across all devices (implies maximal, + all other fields are unused). + """ + MAXIMAL: OpSharding.Type.ValueType # 1 + """This sharding is maximal - one device runs the entire operation.""" + TUPLE: OpSharding.Type.ValueType # 2 + """This sharding is a tuple - only the tuple_shardings field is valid.""" + OTHER: OpSharding.Type.ValueType # 3 + """None of the above; tile_shape and tile_assignment are both used.""" + MANUAL: OpSharding.Type.ValueType # 4 + """This op is manually sharded: the shapes are already partitioned and the + partitioner should not change this op. + """ + UNKNOWN: OpSharding.Type.ValueType # 5 + """This sharding is a placeholder sharding with lowest precedence, it can be + overwriten by any other shardings. + """ + + class _ShardGroupType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ShardGroupTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[OpSharding._ShardGroupType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AS: OpSharding._ShardGroupType.ValueType # 0 + """This op will be sharded exactly the same as the other op. (hard + restriction) + """ + LIKE: OpSharding._ShardGroupType.ValueType # 1 + """This op will try to allow sharding propagation within the same group even + there is no data dependencies among them, but there is no guarantee that + the final shardings within the same group will be exactly the same. (soft + restriction) + """ + + class ShardGroupType(_ShardGroupType, metaclass=_ShardGroupTypeEnumTypeWrapper): + """Used to decide whether this op is to be sharded like some other ops, or to + which other ops will be sharded like. + """ + + AS: OpSharding.ShardGroupType.ValueType # 0 + """This op will be sharded exactly the same as the other op. (hard + restriction) + """ + LIKE: OpSharding.ShardGroupType.ValueType # 1 + """This op will try to allow sharding propagation within the same group even + there is no data dependencies among them, but there is no guarantee that + the final shardings within the same group will be exactly the same. (soft + restriction) + """ + + TYPE_FIELD_NUMBER: builtins.int + TILE_SHAPE_FIELD_NUMBER: builtins.int + TILE_ASSIGNMENT_DIMENSIONS_FIELD_NUMBER: builtins.int + TILE_ASSIGNMENT_DEVICES_FIELD_NUMBER: builtins.int + TUPLE_SHARDINGS_FIELD_NUMBER: builtins.int + REPLICATE_ON_LAST_TILE_DIM_FIELD_NUMBER: builtins.int + METADATA_FIELD_NUMBER: builtins.int + LAST_TILE_DIMS_FIELD_NUMBER: builtins.int + IOTA_RESHAPE_DIMS_FIELD_NUMBER: builtins.int + IOTA_TRANSPOSE_PERM_FIELD_NUMBER: builtins.int + IS_SHARD_GROUP_FIELD_NUMBER: builtins.int + SHARD_GROUP_ID_FIELD_NUMBER: builtins.int + SHARD_GROUP_TYPE_FIELD_NUMBER: builtins.int + type: global___OpSharding.Type.ValueType + replicate_on_last_tile_dim: builtins.bool + """Only used for OTHER type. If true, data is sharded according to other + dimensions of tile_assignment(), but replicated across devices along the + last dimension. (Experimental) + """ + is_shard_group: builtins.bool + """This field decides whether this op is in a shard group.""" + shard_group_id: builtins.int + """This field is used to store the unique id of the shard group.""" + shard_group_type: global___OpSharding.ShardGroupType.ValueType + @property + def tile_shape(self) -> global___ShapeProto: + """The shape of the sharded tile.""" + + @property + def tile_assignment_dimensions(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The shape of the tile assignment tensor - this must be the same rank as + tile_shape and the product of its dimensions must equal + tile_assignment_devices.size(). + """ + + @property + def tile_assignment_devices(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Flattened list of device IDs. The order of flattening is the same as used + by IndexUtil::MultiToLinearIndex(tile_assignment_shape). + Only one of tile_assignment_devices and iota_dimensions shall be non-empty. + """ + + @property + def tuple_shardings(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OpSharding]: + """If type == TUPLE, the sub-shardings, one per leaf node in the tuple shape, + in pre-order. The tuple shape could be nested; here we store just a + flattened list of all leaves in the tuple shape. Note that the tuple shape + is not stored here; shardings do not store the shapes to which they are + applied, this is inferred from the instruction this sharding gets attached + to. + """ + + @property + def metadata(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OpMetadata]: + """This field is used to track the source of this sharding, usually derived + from instructions. Multple metadata may be populated if sharding is + combined with other shardings. Metadata are to not be populated when + type == TUPLE and instead metadata should be set on individual tuple + elements. + """ + + @property + def last_tile_dims( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___OpSharding.Type.ValueType]: + """This field is used to represented the sharding type of each subgroup. + For example, sharding={devices=[2,2,2,2]0,1,2,...,15 last_tile_dims={ + replicate, manual, unreduced}} means that each of the last 3 dimensions + in [2,2,2,2] represents a subgrouping in replicate, manual, + unreduced sharding type respectively. + """ + + @property + def iota_reshape_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimensions used to reshape the 1D iota array of device IDs. + Only one of tile_assignment_devices and iota_reshape_dims shall be + non-empty. + """ + + @property + def iota_transpose_perm(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Dimension permutations to transposed the iota array reshaped to + iota_reshape_dims. This must have the same size as iota_reshape_dims. + """ + + def __init__( + self, + *, + type: global___OpSharding.Type.ValueType | None = ..., + tile_shape: global___ShapeProto | None = ..., + tile_assignment_dimensions: collections.abc.Iterable[builtins.int] | None = ..., + tile_assignment_devices: collections.abc.Iterable[builtins.int] | None = ..., + tuple_shardings: collections.abc.Iterable[global___OpSharding] | None = ..., + replicate_on_last_tile_dim: builtins.bool | None = ..., + metadata: collections.abc.Iterable[global___OpMetadata] | None = ..., + last_tile_dims: collections.abc.Iterable[global___OpSharding.Type.ValueType] | None = ..., + iota_reshape_dims: collections.abc.Iterable[builtins.int] | None = ..., + iota_transpose_perm: collections.abc.Iterable[builtins.int] | None = ..., + is_shard_group: builtins.bool | None = ..., + shard_group_id: builtins.int | None = ..., + shard_group_type: global___OpSharding.ShardGroupType.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["tile_shape", b"tile_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "iota_reshape_dims", + b"iota_reshape_dims", + "iota_transpose_perm", + b"iota_transpose_perm", + "is_shard_group", + b"is_shard_group", + "last_tile_dims", + b"last_tile_dims", + "metadata", + b"metadata", + "replicate_on_last_tile_dim", + b"replicate_on_last_tile_dim", + "shard_group_id", + b"shard_group_id", + "shard_group_type", + b"shard_group_type", + "tile_assignment_devices", + b"tile_assignment_devices", + "tile_assignment_dimensions", + b"tile_assignment_dimensions", + "tile_shape", + b"tile_shape", + "tuple_shardings", + b"tuple_shardings", + "type", + b"type", + ], + ) -> None: ... + +global___OpSharding = OpSharding + +@typing.final +class ReplicaGroup(google.protobuf.message.Message): + """Describes the replica groups in a cross replica op (e.g., all-reduce and + all-to-all). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_IDS_FIELD_NUMBER: builtins.int + @property + def replica_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The ids of the replicas that belongs to the same group. The ordering of the + ids matters in some ops (e.g., all-to-all). + """ + + def __init__(self, *, replica_ids: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replica_ids", b"replica_ids"]) -> None: ... + +global___ReplicaGroup = ReplicaGroup + +@typing.final +class IotaReplicaGroupListProto(google.protobuf.message.Message): + """Represents a list of replica groups (a list of list of devices) with + reshaping and transposing an iota array (iota tile assignment). Can be used + to represent certain common patterns of device lists in a compact, scalable + format. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NUM_REPLICA_GROUPS_FIELD_NUMBER: builtins.int + NUM_DEVICES_PER_GROUP_FIELD_NUMBER: builtins.int + IOTA_RESHAPE_DIMS_FIELD_NUMBER: builtins.int + IOTA_TRANSPOSE_PERM_FIELD_NUMBER: builtins.int + num_replica_groups: builtins.int + """Number of replica groups.""" + num_devices_per_group: builtins.int + """Number of devices per group.""" + @property + def iota_reshape_dims(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimensions used to reshape the 1D iota array of device IDs.""" + + @property + def iota_transpose_perm(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The dimension permutations to transposed the iota array reshaped to + iota_reshape_dims. This must have the same size as iota_reshape_dims. + """ + + def __init__( + self, + *, + num_replica_groups: builtins.int | None = ..., + num_devices_per_group: builtins.int | None = ..., + iota_reshape_dims: collections.abc.Iterable[builtins.int] | None = ..., + iota_transpose_perm: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "iota_reshape_dims", + b"iota_reshape_dims", + "iota_transpose_perm", + b"iota_transpose_perm", + "num_devices_per_group", + b"num_devices_per_group", + "num_replica_groups", + b"num_replica_groups", + ], + ) -> None: ... + +global___IotaReplicaGroupListProto = IotaReplicaGroupListProto + +@typing.final +class CollectiveDeviceListProto(google.protobuf.message.Message): + """Represents a series of devices participating in a collective operation (e.g., + all-reduce and all-to-all). While this directly translates to a list of + replica groups, it may be used to represent these lists in a compact form. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICA_GROUPS_FIELD_NUMBER: builtins.int + IOTA_REPLICA_GROUP_LIST_FIELD_NUMBER: builtins.int + @property + def replica_groups(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ReplicaGroup]: + """ReplicaGroupV1: List of replica groups. Legacy way of representing device + lists. + """ + + @property + def iota_replica_group_list(self) -> global___IotaReplicaGroupListProto: + """ReplicaGroupV2: Represents a list of replica groups with reshaping and + transposing an iota array. + """ + + def __init__( + self, + *, + replica_groups: collections.abc.Iterable[global___ReplicaGroup] | None = ..., + iota_replica_group_list: global___IotaReplicaGroupListProto | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["iota_replica_group_list", b"iota_replica_group_list"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal["iota_replica_group_list", b"iota_replica_group_list", "replica_groups", b"replica_groups"], + ) -> None: ... + +global___CollectiveDeviceListProto = CollectiveDeviceListProto + +@typing.final +class SourceTarget(google.protobuf.message.Message): + """Describes the source target pair in the collective permute op.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SOURCE_FIELD_NUMBER: builtins.int + TARGET_FIELD_NUMBER: builtins.int + source: builtins.int + target: builtins.int + def __init__(self, *, source: builtins.int | None = ..., target: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["source", b"source", "target", b"target"]) -> None: ... + +global___SourceTarget = SourceTarget + +@typing.final +class PrecisionConfig(google.protobuf.message.Message): + """Used to indicate the precision configuration. It has backend specific + meaning. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Precision: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _PrecisionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[PrecisionConfig._Precision.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT: PrecisionConfig._Precision.ValueType # 0 + HIGH: PrecisionConfig._Precision.ValueType # 1 + HIGHEST: PrecisionConfig._Precision.ValueType # 2 + PACKED_NIBBLE: PrecisionConfig._Precision.ValueType # 3 + """Each U8/S8 value in a tensor actually represents 2 nibble values.""" + + class Precision(_Precision, metaclass=_PrecisionEnumTypeWrapper): ... + DEFAULT: PrecisionConfig.Precision.ValueType # 0 + HIGH: PrecisionConfig.Precision.ValueType # 1 + HIGHEST: PrecisionConfig.Precision.ValueType # 2 + PACKED_NIBBLE: PrecisionConfig.Precision.ValueType # 3 + """Each U8/S8 value in a tensor actually represents 2 nibble values.""" + + class _Algorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _AlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[PrecisionConfig._Algorithm.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + ALG_UNSET: PrecisionConfig._Algorithm.ValueType # 0 + """If the algorithm is `ALG_UNSET`, we will decide the algorithm based on + the operand_precision values (for now). + """ + ALG_DOT_ANY_F8_ANY_F8_F32: PrecisionConfig._Algorithm.ValueType # 1 + """The storage type can be any 8-bit floating point type.""" + ALG_DOT_ANY_F8_ANY_F8_F32_FAST_ACCUM: PrecisionConfig._Algorithm.ValueType # 2 + """The storage type can be any 8-bit floating point type. Intermediate + results will not periodically be promoted to a higher precision. This + corresponds to CUBLASLT_MATMUL_DESC_FAST_ACCUM. Triton's + maxNumImpreciseAcc=32 setting may be similar. + """ + ALG_DOT_F16_F16_F16: PrecisionConfig._Algorithm.ValueType # 3 + ALG_DOT_F16_F16_F32: PrecisionConfig._Algorithm.ValueType # 4 + ALG_DOT_BF16_BF16_BF16: PrecisionConfig._Algorithm.ValueType # 5 + ALG_DOT_BF16_BF16_F32: PrecisionConfig._Algorithm.ValueType # 6 + ALG_DOT_BF16_BF16_F32_X3: PrecisionConfig._Algorithm.ValueType # 7 + """An algorithm which uses 3 BF16_BF16_F32 matmuls to achieve better + precision. + """ + ALG_DOT_BF16_BF16_F32_X6: PrecisionConfig._Algorithm.ValueType # 8 + """An algorithm which uses 6 BF16_BF16_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_TF32_TF32_F32: PrecisionConfig._Algorithm.ValueType # 9 + ALG_DOT_TF32_TF32_F32_X3: PrecisionConfig._Algorithm.ValueType # 10 + """An algorithm which uses 3 TF32_TF32_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_F32_F32_F32: PrecisionConfig._Algorithm.ValueType # 11 + ALG_DOT_F64_F64_F64: PrecisionConfig._Algorithm.ValueType # 12 + + class Algorithm(_Algorithm, metaclass=_AlgorithmEnumTypeWrapper): + """The algorithm used to evaluate the instruction. + + The naming convention for the dot instruction is + ALG_DOT_{A_TYPE}_{B_TYPE}_{ACCUM_TYPE}[_X{NUM_OPS}] where A_TYPE, B_TYPE + and ACCUM_TYPE correspond to the types in the "primitive dot operations" + (such as TensorCore operations) and NUM_OPS is the number of such + operations used per "primitive tile". When the NUM_OPS + field is skipped, it is assumed to be 1. The types mentioned in the name + are independent of the storage types. + + In general ATYPE and BTYPE are the precisions that the LHS and RHS of the + operation are rounded to and ACCUMTYPE is the accumulation type. If a + backend does not support the given algorithm, an error is raised. The + Algorithm enum is intended to eventually replace the Precision enum. + """ + + ALG_UNSET: PrecisionConfig.Algorithm.ValueType # 0 + """If the algorithm is `ALG_UNSET`, we will decide the algorithm based on + the operand_precision values (for now). + """ + ALG_DOT_ANY_F8_ANY_F8_F32: PrecisionConfig.Algorithm.ValueType # 1 + """The storage type can be any 8-bit floating point type.""" + ALG_DOT_ANY_F8_ANY_F8_F32_FAST_ACCUM: PrecisionConfig.Algorithm.ValueType # 2 + """The storage type can be any 8-bit floating point type. Intermediate + results will not periodically be promoted to a higher precision. This + corresponds to CUBLASLT_MATMUL_DESC_FAST_ACCUM. Triton's + maxNumImpreciseAcc=32 setting may be similar. + """ + ALG_DOT_F16_F16_F16: PrecisionConfig.Algorithm.ValueType # 3 + ALG_DOT_F16_F16_F32: PrecisionConfig.Algorithm.ValueType # 4 + ALG_DOT_BF16_BF16_BF16: PrecisionConfig.Algorithm.ValueType # 5 + ALG_DOT_BF16_BF16_F32: PrecisionConfig.Algorithm.ValueType # 6 + ALG_DOT_BF16_BF16_F32_X3: PrecisionConfig.Algorithm.ValueType # 7 + """An algorithm which uses 3 BF16_BF16_F32 matmuls to achieve better + precision. + """ + ALG_DOT_BF16_BF16_F32_X6: PrecisionConfig.Algorithm.ValueType # 8 + """An algorithm which uses 6 BF16_BF16_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_TF32_TF32_F32: PrecisionConfig.Algorithm.ValueType # 9 + ALG_DOT_TF32_TF32_F32_X3: PrecisionConfig.Algorithm.ValueType # 10 + """An algorithm which uses 3 TF32_TF32_F32 matmuls to achieve better + precision (similar to F32). + """ + ALG_DOT_F32_F32_F32: PrecisionConfig.Algorithm.ValueType # 11 + ALG_DOT_F64_F64_F64: PrecisionConfig.Algorithm.ValueType # 12 + + OPERAND_PRECISION_FIELD_NUMBER: builtins.int + ALGORITHM_FIELD_NUMBER: builtins.int + algorithm: global___PrecisionConfig.Algorithm.ValueType + """Currently doesn't do anything, but we plan to support it for dot and + possibly more instructions. + + TODO(b/316147294): Support this on GPU and add this to StableHLO as well. + + If this is set, then `operand_precision` should be set to DEFAULT and it + will be ignored. + """ + @property + def operand_precision( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___PrecisionConfig.Precision.ValueType]: ... + def __init__( + self, + *, + operand_precision: collections.abc.Iterable[global___PrecisionConfig.Precision.ValueType] | None = ..., + algorithm: global___PrecisionConfig.Algorithm.ValueType | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["algorithm", b"algorithm", "operand_precision", b"operand_precision"] + ) -> None: ... + +global___PrecisionConfig = PrecisionConfig + +@typing.final +class ParameterReplication(google.protobuf.message.Message): + """Describes whether all data-parallelism replicas will receive the same + parameter data at each buffer. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REPLICATED_AT_LEAF_BUFFERS_FIELD_NUMBER: builtins.int + @property + def replicated_at_leaf_buffers(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """A list of boolean values for the flattened leaf buffers. Each value + indicates whether the corresponding leaf buffer is replicated. + + If this field is empty, it means no buffer is replicated. Otherwise, the + number of elements in this field must match the number of leaf buffers in + the HLO instruction's shape. + """ + + def __init__(self, *, replicated_at_leaf_buffers: collections.abc.Iterable[builtins.bool] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["replicated_at_leaf_buffers", b"replicated_at_leaf_buffers"]) -> None: ... + +global___ParameterReplication = ParameterReplication + +@typing.final +class WhileLoopBackendConfig(google.protobuf.message.Message): + """A backend-config for kWhile loops that stores the loop's trip count, if it is + known. + + This is useful for backends that can implement a `for i in 0..N` loop more + efficiently than a `while` loop. For example, on GPUs, we can implement a + `for i in 0..N` loop by enqueueing the kernels for the loop body N times, + whereas implementing a `while` loop requires a host-device sync on each + iteration. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class KnownTripCount(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + N_FIELD_NUMBER: builtins.int + n: builtins.int + def __init__(self, *, n: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["n", b"n"]) -> None: ... + + KNOWN_TRIP_COUNT_FIELD_NUMBER: builtins.int + @property + def known_trip_count(self) -> global___WhileLoopBackendConfig.KnownTripCount: + """This indirection lets us distinguish between known-trip-count == 0 and + unknown-trip-count. + """ + + def __init__(self, *, known_trip_count: global___WhileLoopBackendConfig.KnownTripCount | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["known_trip_count", b"known_trip_count"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["known_trip_count", b"known_trip_count"]) -> None: ... + +global___WhileLoopBackendConfig = WhileLoopBackendConfig + +@typing.final +class OutputOperandAliasing(google.protobuf.message.Message): + """Specifies a pair of output/operand buffers that alias each other for + kCustomCall and kFusion + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + OPERAND_INDEX_FIELD_NUMBER: builtins.int + OPERAND_SHAPE_INDEX_FIELD_NUMBER: builtins.int + operand_index: builtins.int + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def operand_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + operand_index: builtins.int | None = ..., + operand_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "operand_index", + b"operand_index", + "operand_shape_index", + b"operand_shape_index", + "output_shape_index", + b"output_shape_index", + ], + ) -> None: ... + +global___OutputOperandAliasing = OutputOperandAliasing + +@typing.final +class OriginalArrayProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LEAF_SHAPE_INDEX_FIELD_NUMBER: builtins.int + INSTRUCTION_NAME_FIELD_NUMBER: builtins.int + SHAPE_INDEX_FIELD_NUMBER: builtins.int + instruction_name: builtins.str + @property + def leaf_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + leaf_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + instruction_name: builtins.str | None = ..., + shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "instruction_name", b"instruction_name", "leaf_shape_index", b"leaf_shape_index", "shape_index", b"shape_index" + ], + ) -> None: ... + +global___OriginalArrayProto = OriginalArrayProto + +@typing.final +class OriginalValueProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LEAVES_FIELD_NUMBER: builtins.int + @property + def leaves(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___OriginalArrayProto]: ... + def __init__(self, *, leaves: collections.abc.Iterable[global___OriginalArrayProto] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["leaves", b"leaves"]) -> None: ... + +global___OriginalValueProto = OriginalValueProto diff --git a/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi b/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi new file mode 100644 index 000000000000..17820b9e12c0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/compiler/xla/xla_pb2.pyi @@ -0,0 +1,2558 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Copyright 2017 The OpenXLA 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 builtins +import collections.abc +import sys +import typing + +import google.protobuf.any_pb2 +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.compiler.xla.service.hlo_pb2 +import tensorflow.compiler.xla.xla_data_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompilationEnvironmentsProto(google.protobuf.message.Message): + """Proto version of `xla::CompilationEnvironments`.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENVIRONMENTS_FIELD_NUMBER: builtins.int + @property + def environments( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[google.protobuf.any_pb2.Any]: ... + def __init__(self, *, environments: collections.abc.Iterable[google.protobuf.any_pb2.Any] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["environments", b"environments"]) -> None: ... + +global___CompilationEnvironmentsProto = CompilationEnvironmentsProto + +@typing.final +class DebugOptions(google.protobuf.message.Message): + """Debugging options for XLA. These options may change at any time - there are + no guarantees about backward or forward compatibility for these fields. + + Debug options naming and organization: + + 1. Backend-agnostic options: `xla_$flag_name` - go first, and sorted + alphabetically by the flag name. + + 2. Backend-specific options: `xla_$backend_$flag_name` - must be in the + corresponding backend section, and sorted alphabetically by the flag name. + --------------------------------------------------------------------------// + XLA backend-agnostic options. + --------------------------------------------------------------------------// + go/keep-sorted start + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ShapeChecks: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ShapeChecksEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._ShapeChecks.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + IGNORE: DebugOptions._ShapeChecks.ValueType # 0 + """Do not insert any shape checks for dynamically shaped operations; output + buffers might contain garbage data if shapes don't match. + """ + RUNTIME: DebugOptions._ShapeChecks.ValueType # 1 + """Check shapes at runtime, will insert an extra synchronization if shapes + cannot be proven correct at compile time. + """ + COMPILE_TIME: DebugOptions._ShapeChecks.ValueType # 2 + """Will refuse to compile any program where shape correctness can not be + established at compile time. + """ + + class ShapeChecks(_ShapeChecks, metaclass=_ShapeChecksEnumTypeWrapper): ... + IGNORE: DebugOptions.ShapeChecks.ValueType # 0 + """Do not insert any shape checks for dynamically shaped operations; output + buffers might contain garbage data if shapes don't match. + """ + RUNTIME: DebugOptions.ShapeChecks.ValueType # 1 + """Check shapes at runtime, will insert an extra synchronization if shapes + cannot be proven correct at compile time. + """ + COMPILE_TIME: DebugOptions.ShapeChecks.ValueType # 2 + """Will refuse to compile any program where shape correctness can not be + established at compile time. + """ + + class _StepMarkerLocation: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _StepMarkerLocationEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._StepMarkerLocation.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + STEP_MARK_AT_ENTRY: DebugOptions._StepMarkerLocation.ValueType # 0 + """Generate a step marker at the program entry. This handles the case where + each step is done by one or multiple program execution(s). Only the first + program will be tagged for generating a step marker at the program entry. + This is the default. + """ + STEP_MARK_AT_TOP_LEVEL_WHILE_LOOP: DebugOptions._StepMarkerLocation.ValueType # 1 + """Generate a step marker at each iteration of the top level while loop, + which is assumed to be a training loop. + """ + STEP_MARK_AT_SECOND_LEVEL_WHILE_LOOP: DebugOptions._StepMarkerLocation.ValueType # 3 + """Generate a step marker at each iteration of the second level while loops, + which is assumed to be a training or eval loop. + """ + STEP_MARK_NONE: DebugOptions._StepMarkerLocation.ValueType # 2 + """No step marker generated.""" + + class StepMarkerLocation(_StepMarkerLocation, metaclass=_StepMarkerLocationEnumTypeWrapper): ... + STEP_MARK_AT_ENTRY: DebugOptions.StepMarkerLocation.ValueType # 0 + """Generate a step marker at the program entry. This handles the case where + each step is done by one or multiple program execution(s). Only the first + program will be tagged for generating a step marker at the program entry. + This is the default. + """ + STEP_MARK_AT_TOP_LEVEL_WHILE_LOOP: DebugOptions.StepMarkerLocation.ValueType # 1 + """Generate a step marker at each iteration of the top level while loop, + which is assumed to be a training loop. + """ + STEP_MARK_AT_SECOND_LEVEL_WHILE_LOOP: DebugOptions.StepMarkerLocation.ValueType # 3 + """Generate a step marker at each iteration of the second level while loops, + which is assumed to be a training or eval loop. + """ + STEP_MARK_NONE: DebugOptions.StepMarkerLocation.ValueType # 2 + """No step marker generated.""" + + class _CollectiveOpType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CollectiveOpTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._CollectiveOpType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + NOOP: DebugOptions._CollectiveOpType.ValueType # 0 + ALLREDUCE: DebugOptions._CollectiveOpType.ValueType # 1 + ALLGATHER: DebugOptions._CollectiveOpType.ValueType # 2 + REDUCESCATTER: DebugOptions._CollectiveOpType.ValueType # 3 + COLLECTIVEBROADCAST: DebugOptions._CollectiveOpType.ValueType # 4 + ALLTOALL: DebugOptions._CollectiveOpType.ValueType # 5 + COLLECTIVEPERMUTE: DebugOptions._CollectiveOpType.ValueType # 6 + + class CollectiveOpType(_CollectiveOpType, metaclass=_CollectiveOpTypeEnumTypeWrapper): + """Enum to define all collective ops + that xla supports. + """ + + NOOP: DebugOptions.CollectiveOpType.ValueType # 0 + ALLREDUCE: DebugOptions.CollectiveOpType.ValueType # 1 + ALLGATHER: DebugOptions.CollectiveOpType.ValueType # 2 + REDUCESCATTER: DebugOptions.CollectiveOpType.ValueType # 3 + COLLECTIVEBROADCAST: DebugOptions.CollectiveOpType.ValueType # 4 + ALLTOALL: DebugOptions.CollectiveOpType.ValueType # 5 + COLLECTIVEPERMUTE: DebugOptions.CollectiveOpType.ValueType # 6 + + class _CommandBufferCmdType: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _CommandBufferCmdTypeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._CommandBufferCmdType.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + INVALID: DebugOptions._CommandBufferCmdType.ValueType # 0 + FUSION: DebugOptions._CommandBufferCmdType.ValueType # 1 + CUBLAS: DebugOptions._CommandBufferCmdType.ValueType # 2 + CUDNN: DebugOptions._CommandBufferCmdType.ValueType # 3 + COLLECTIVES: DebugOptions._CommandBufferCmdType.ValueType # 4 + CONDITIONALS: DebugOptions._CommandBufferCmdType.ValueType # 5 + CUSTOM_CALL: DebugOptions._CommandBufferCmdType.ValueType # 6 + CUBLASLT: DebugOptions._CommandBufferCmdType.ValueType # 7 + + class CommandBufferCmdType(_CommandBufferCmdType, metaclass=_CommandBufferCmdTypeEnumTypeWrapper): + """Commands are categorized into 5 types: + FUSION represents regular fusion kernels. + CUBLAS/CUBLASLT, CUDNN, and COLLECTIVES represent library calls. + CONDITIONALS represents control flow. + """ + + INVALID: DebugOptions.CommandBufferCmdType.ValueType # 0 + FUSION: DebugOptions.CommandBufferCmdType.ValueType # 1 + CUBLAS: DebugOptions.CommandBufferCmdType.ValueType # 2 + CUDNN: DebugOptions.CommandBufferCmdType.ValueType # 3 + COLLECTIVES: DebugOptions.CommandBufferCmdType.ValueType # 4 + CONDITIONALS: DebugOptions.CommandBufferCmdType.ValueType # 5 + CUSTOM_CALL: DebugOptions.CommandBufferCmdType.ValueType # 6 + CUBLASLT: DebugOptions.CommandBufferCmdType.ValueType # 7 + + class _PartitioningAlgorithm: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _PartitioningAlgorithmEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._PartitioningAlgorithm.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + PARTITIONING_ALGORITHM_NOOP: DebugOptions._PartitioningAlgorithm.ValueType # 0 + PARTITIONING_ALGORITHM_EXP0: DebugOptions._PartitioningAlgorithm.ValueType # 1 + PARTITIONING_ALGORITHM_EXP1: DebugOptions._PartitioningAlgorithm.ValueType # 2 + PARTITIONING_ALGORITHM_EXP2: DebugOptions._PartitioningAlgorithm.ValueType # 3 + + class PartitioningAlgorithm(_PartitioningAlgorithm, metaclass=_PartitioningAlgorithmEnumTypeWrapper): ... + PARTITIONING_ALGORITHM_NOOP: DebugOptions.PartitioningAlgorithm.ValueType # 0 + PARTITIONING_ALGORITHM_EXP0: DebugOptions.PartitioningAlgorithm.ValueType # 1 + PARTITIONING_ALGORITHM_EXP1: DebugOptions.PartitioningAlgorithm.ValueType # 2 + PARTITIONING_ALGORITHM_EXP2: DebugOptions.PartitioningAlgorithm.ValueType # 3 + + class _WhileLoopUnrolling: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _WhileLoopUnrollingEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._WhileLoopUnrolling.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + WHILE_LOOP_UNROLLING_NO_UNROLL: DebugOptions._WhileLoopUnrolling.ValueType # 0 + WHILE_LOOP_UNROLLING_DOUBLE_BUFFER: DebugOptions._WhileLoopUnrolling.ValueType # 1 + """Has the same effect as setting + `xla_gpu_enable_while_loop_double_buffering`. + """ + WHILE_LOOP_UNROLLING_FULL_UNROLL: DebugOptions._WhileLoopUnrolling.ValueType # 2 + """Enables full loop unrolling using the same strategy as `DOUBLE_BUFFER`.""" + + class WhileLoopUnrolling(_WhileLoopUnrolling, metaclass=_WhileLoopUnrollingEnumTypeWrapper): ... + WHILE_LOOP_UNROLLING_NO_UNROLL: DebugOptions.WhileLoopUnrolling.ValueType # 0 + WHILE_LOOP_UNROLLING_DOUBLE_BUFFER: DebugOptions.WhileLoopUnrolling.ValueType # 1 + """Has the same effect as setting + `xla_gpu_enable_while_loop_double_buffering`. + """ + WHILE_LOOP_UNROLLING_FULL_UNROLL: DebugOptions.WhileLoopUnrolling.ValueType # 2 + """Enables full loop unrolling using the same strategy as `DOUBLE_BUFFER`.""" + + class _AutotuneCacheMode: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _AutotuneCacheModeEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[DebugOptions._AutotuneCacheMode.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AUTOTUNE_CACHE_MODE_UNSPECIFIED: DebugOptions._AutotuneCacheMode.ValueType # 0 + AUTOTUNE_CACHE_MODE_UPDATE: DebugOptions._AutotuneCacheMode.ValueType # 1 + """If the cache exists per fusion autotuner loads it and terminates, + otherwise runs autotuner and dumps the result. + """ + AUTOTUNE_CACHE_MODE_READ: DebugOptions._AutotuneCacheMode.ValueType # 2 + """Sets readonly access to the cache for the per fusion autotuner. Same as + above, but doesn't dump anything. + """ + + class AutotuneCacheMode(_AutotuneCacheMode, metaclass=_AutotuneCacheModeEnumTypeWrapper): ... + AUTOTUNE_CACHE_MODE_UNSPECIFIED: DebugOptions.AutotuneCacheMode.ValueType # 0 + AUTOTUNE_CACHE_MODE_UPDATE: DebugOptions.AutotuneCacheMode.ValueType # 1 + """If the cache exists per fusion autotuner loads it and terminates, + otherwise runs autotuner and dumps the result. + """ + AUTOTUNE_CACHE_MODE_READ: DebugOptions.AutotuneCacheMode.ValueType # 2 + """Sets readonly access to the cache for the per fusion autotuner. Same as + above, but doesn't dump anything. + """ + + @typing.final + class XlaBackendExtraOptionsEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.str + def __init__(self, *, key: builtins.str | None = ..., value: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + XLA_CPU_ENABLE_CONCURRENCY_OPTIMIZED_SCHEDULER_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_FAST_MATH_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_FAST_MIN_MAX_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_DIVISION_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_FUNCTIONS_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_INFS_FIELD_NUMBER: builtins.int + XLA_CPU_FAST_MATH_HONOR_NANS_FIELD_NUMBER: builtins.int + XLA_CPU_USE_THUNK_RUNTIME_FIELD_NUMBER: builtins.int + XLA_CPU_PARALLEL_CODEGEN_SPLIT_COUNT_FIELD_NUMBER: builtins.int + XLA_CPU_PREFER_VECTOR_WIDTH_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_AUTOTUNE_CACHE_MODE_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_DISABLE_BINARY_LIBRARIES_FIELD_NUMBER: builtins.int + XLA_GPU_EXPERIMENTAL_ENABLE_TRITON_SOFTMAX_PRIORITY_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_UNSUPPORTED_ENABLE_TRITON_GEMM_FIELD_NUMBER: builtins.int + XLA_HLO_GRAPH_ADDRESSES_FIELD_NUMBER: builtins.int + XLA_HLO_PROFILE_FIELD_NUMBER: builtins.int + XLA_DISABLE_HLO_PASSES_FIELD_NUMBER: builtins.int + XLA_ENABLE_HLO_PASSES_ONLY_FIELD_NUMBER: builtins.int + XLA_DISABLE_ALL_HLO_PASSES_FIELD_NUMBER: builtins.int + XLA_BACKEND_OPTIMIZATION_LEVEL_FIELD_NUMBER: builtins.int + XLA_EMBED_IR_IN_EXECUTABLE_FIELD_NUMBER: builtins.int + XLA_ELIMINATE_HLO_IMPLICIT_BROADCAST_FIELD_NUMBER: builtins.int + XLA_CPU_MULTI_THREAD_EIGEN_FIELD_NUMBER: builtins.int + XLA_GPU_CUDA_DATA_DIR_FIELD_NUMBER: builtins.int + XLA_GPU_FTZ_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_ALIAS_SCOPE_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_NOALIAS_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_ENABLE_INVARIANT_LOAD_METADATA_FIELD_NUMBER: builtins.int + XLA_LLVM_DISABLE_EXPENSIVE_PASSES_FIELD_NUMBER: builtins.int + XLA_TEST_ALL_OUTPUT_LAYOUTS_FIELD_NUMBER: builtins.int + XLA_TEST_ALL_INPUT_LAYOUTS_FIELD_NUMBER: builtins.int + XLA_HLO_GRAPH_SHARDING_COLOR_FIELD_NUMBER: builtins.int + XLA_CPU_USE_MKL_DNN_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_FAST_MIN_MAX_FIELD_NUMBER: builtins.int + XLA_ALLOW_EXCESS_PRECISION_FIELD_NUMBER: builtins.int + XLA_GPU_CRASH_ON_VERIFICATION_FAILURES_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_LEVEL_FIELD_NUMBER: builtins.int + XLA_FORCE_HOST_PLATFORM_DEVICE_COUNT_FIELD_NUMBER: builtins.int + XLA_GPU_DISABLE_GPUASM_OPTIMIZATIONS_FIELD_NUMBER: builtins.int + XLA_GPU_SHAPE_CHECKS_FIELD_NUMBER: builtins.int + XLA_HLO_EVALUATOR_USE_FAST_PATH_FIELD_NUMBER: builtins.int + XLA_ALLOW_SCALAR_INDEX_DYNAMIC_OPS_FIELD_NUMBER: builtins.int + XLA_STEP_MARKER_LOCATION_FIELD_NUMBER: builtins.int + XLA_DUMP_TO_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_MODULE_RE_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_PASS_RE_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_TEXT_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_PROTO_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_DOT_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_URL_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_HTML_FIELD_NUMBER: builtins.int + XLA_DUMP_FUSION_VISUALIZATION_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_SNAPSHOTS_FIELD_NUMBER: builtins.int + XLA_DUMP_INCLUDE_TIMESTAMP_FIELD_NUMBER: builtins.int + XLA_DUMP_MAX_HLO_MODULES_FIELD_NUMBER: builtins.int + XLA_DUMP_MODULE_METADATA_FIELD_NUMBER: builtins.int + XLA_DUMP_COMPRESS_PROTOS_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_AS_LONG_TEXT_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_CONV_NCHW_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_CONV_NHWC_FIELD_NUMBER: builtins.int + XLA_GPU_PTX_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_LLVMIR_FIELD_NUMBER: builtins.int + XLA_DUMP_ENABLE_MLIR_PRETTY_FORM_FIELD_NUMBER: builtins.int + XLA_GPU_ALGORITHM_DENYLIST_PATH_FIELD_NUMBER: builtins.int + XLA_TPU_DETECT_NAN_FIELD_NUMBER: builtins.int + XLA_TPU_DETECT_INF_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_XPROF_TRACEME_FIELD_NUMBER: builtins.int + XLA_GPU_UNSAFE_FALLBACK_TO_DRIVER_ON_PTXAS_NOT_FOUND_FIELD_NUMBER: builtins.int + XLA_GPU_ASM_EXTRA_FLAGS_FIELD_NUMBER: builtins.int + XLA_MULTIHEAP_SIZE_CONSTRAINT_PER_HEAP_FIELD_NUMBER: builtins.int + XLA_DETAILED_LOGGING_FIELD_NUMBER: builtins.int + XLA_ENABLE_DUMPING_FIELD_NUMBER: builtins.int + XLA_GPU_FORCE_COMPILATION_PARALLELISM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LLVM_MODULE_COMPILATION_PARALLELISM_FIELD_NUMBER: builtins.int + XLA_GPU_DETERMINISTIC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_LLVM_IR_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_DISABLE_ASYNC_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_REDUCE_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_GATHER_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_REDUCE_SCATTER_COMBINE_THRESHOLD_BYTES_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_ALL_GATHER_COMBINE_BY_DIM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REDUCE_SCATTER_COMBINE_BY_DIM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REASSOCIATION_FOR_CONVERTED_AR_FIELD_NUMBER: builtins.int + XLA_GPU_ALL_REDUCE_BLUECONNECT_NUM_DEVICES_PER_HOST_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_REDUCE_SCATTER_CODE_MOTION_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECTIVE_INFLATION_FACTOR_FIELD_NUMBER: builtins.int + XLA_LLVM_FORCE_INLINE_BEFORE_SPLIT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_FRONTEND_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_FMHA_FIELD_NUMBER: builtins.int + XLA_GPU_FUSED_ATTENTION_USE_CUDNN_RNG_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_LAYER_NORM_FIELD_NUMBER: builtins.int + XLA_DUMP_DISABLE_METADATA_FIELD_NUMBER: builtins.int + XLA_DUMP_HLO_PIPELINE_RE_FIELD_NUMBER: builtins.int + XLA_GPU_STRICT_CONV_ALGORITHM_PICKER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUSTOM_FUSIONS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUSTOM_FUSIONS_RE_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_DYNAMIC_SLICE_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_TERMINATION_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_SHARED_CONSTANTS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUBLASLT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_COMMAND_BUFFER_FIELD_NUMBER: builtins.int + XLA_GPU_GRAPH_MIN_GRAPH_SIZE_FIELD_NUMBER: builtins.int + XLA_GPU_GRAPH_ENABLE_CONCURRENT_REGION_FIELD_NUMBER: builtins.int + XLA_GPU_REDZONE_SCRATCH_MAX_MEGABYTES_FIELD_NUMBER: builtins.int + XLA_GPU_REDZONE_PADDING_BYTES_FIELD_NUMBER: builtins.int + XLA_CPU_USE_ACL_FIELD_NUMBER: builtins.int + XLA_CPU_STRICT_DOT_CONV_MATH_FIELD_NUMBER: builtins.int + XLA_GPU_USE_RUNTIME_FUSION_FIELD_NUMBER: builtins.int + XLA_DUMP_LATENCY_HIDING_SCHEDULE_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_MLIR_TILING_AND_FUSION_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_CUSTOM_MATMUL_TILING_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_M_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_N_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_MATMUL_TILING_K_DIM_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_MLIR_FUSION_OUTLINING_FIELD_NUMBER: builtins.int + XLA_CPU_ENABLE_EXPERIMENTAL_DEALLOCATION_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LATENCY_HIDING_SCHEDULER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_HIGHEST_PRIORITY_ASYNC_STREAM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_ANALYTICAL_LATENCY_ESTIMATOR_FIELD_NUMBER: builtins.int + XLA_GPU_LHS_ENABLE_GPU_ASYNC_TRACKER_FIELD_NUMBER: builtins.int + XLA_GPU_PGLE_PROFILE_FILE_OR_DIRECTORY_PATH_FIELD_NUMBER: builtins.int + XLA_GPU_MEMORY_LIMIT_SLOP_FACTOR_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_ALL_REDUCE_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_ALL_GATHER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_REDUCE_SCATTER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PIPELINED_P2P_FIELD_NUMBER: builtins.int + XLA_GPU_RUN_POST_LAYOUT_COLLECTIVE_PIPELINER_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECTIVE_PERMUTE_DECOMPOSER_THRESHOLD_FIELD_NUMBER: builtins.int + XLA_PARTITIONING_ALGORITHM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUDNN_INT8X32_CONVOLUTION_REORDERING_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_GEMM_ANY_FIELD_NUMBER: builtins.int + XLA_GPU_EXHAUSTIVE_TILING_SEARCH_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PRIORITY_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNE_RESULTS_TO_FIELD_NUMBER: builtins.int + XLA_GPU_LOAD_AUTOTUNE_RESULTS_FROM_FIELD_NUMBER: builtins.int + XLA_GPU_TARGET_CONFIG_FILENAME_FIELD_NUMBER: builtins.int + XLA_GPU_AUTO_SPMD_PARTITIONING_MEMORY_BUDGET_GB_FIELD_NUMBER: builtins.int + XLA_GPU_AUTO_SPMD_PARTITIONING_MEMORY_BUDGET_RATIO_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_GEMM_DISABLE_REDUCED_PRECISION_REDUCTION_FIELD_NUMBER: builtins.int + XLA_GPU_TRITON_FUSION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNED_GEMM_FUSIONS_FIELD_NUMBER: builtins.int + XLA_GPU_OVERRIDE_GEMM_AUTOTUNER_FIELD_NUMBER: builtins.int + XLA_GPU_COPY_INSERTION_USE_REGION_ANALYSIS_FIELD_NUMBER: builtins.int + XLA_GPU_COLLECT_COST_MODEL_STATS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_SPLIT_K_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_REDUCTION_EPILOGUE_FUSION_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_CLIQUE_OPTIMIZATION_FIELD_NUMBER: builtins.int + XLA_GPU_MOCK_CUSTOM_CALLS_FIELD_NUMBER: builtins.int + XLA_GPU_CUBLAS_FALLBACK_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_DOUBLE_BUFFERING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_WHILE_LOOP_UNROLLING_FIELD_NUMBER: builtins.int + XLA_GPU_ENSURE_MINOR_DOT_CONTRACTION_DIMS_FIELD_NUMBER: builtins.int + XLA_GPU_FILTER_KERNELS_SPILLING_REGISTERS_ON_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_DEBUG_BUFFER_ASSIGNMENT_SHOW_MAX_FIELD_NUMBER: builtins.int + XLA_GPU_LLVM_VERIFICATION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_CUB_RADIX_SORT_FIELD_NUMBER: builtins.int + XLA_GPU_THRESHOLD_FOR_WINDOWED_EINSUM_MIB_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_HOPPER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_USER_BUFFERS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_COMM_SPLITTING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_NCCL_PER_STREAM_COMMS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LIBNVPTXCOMPILER_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_DOT_STRENGTH_REDUCTION_FIELD_NUMBER: builtins.int + XLA_GPU_MULTI_STREAMED_WINDOWED_EINSUM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_BF16_6WAY_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_BF16_3WAY_GEMM_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_COLLECTIVE_MAX_NCHANNELS_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_P2P_MAX_NCHANNELS_FIELD_NUMBER: builtins.int + XLA_GPU_MLIR_EMITTER_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_GEMM_REWRITE_SIZE_THRESHOLD_FIELD_NUMBER: builtins.int + XLA_GPU_REQUIRE_COMPLETE_AOT_AUTOTUNE_RESULTS_FIELD_NUMBER: builtins.int + XLA_GPU_CUDNN_GEMM_FUSION_LEVEL_FIELD_NUMBER: builtins.int + XLA_GPU_USE_MEMCPY_LOCAL_P2P_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_MAX_SOLUTIONS_FIELD_NUMBER: builtins.int + XLA_DUMP_LARGE_CONSTANTS_FIELD_NUMBER: builtins.int + XLA_GPU_VERIFY_TRITON_FUSION_NUMERICS_FIELD_NUMBER: builtins.int + XLA_GPU_DUMP_AUTOTUNE_LOGS_TO_FIELD_NUMBER: builtins.int + XLA_REDUCE_WINDOW_REWRITE_BASE_LENGTH_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_HOST_MEMORY_OFFLOADING_FIELD_NUMBER: builtins.int + XLA_GPU_EXCLUDE_NONDETERMINISTIC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_NCCL_TERMINATE_ON_ERROR_FIELD_NUMBER: builtins.int + XLA_GPU_SHARD_AUTOTUNING_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_APPROX_COSTLY_COLLECTIVES_FIELD_NUMBER: builtins.int + XLA_GPU_KERNEL_CACHE_FILE_FIELD_NUMBER: builtins.int + XLA_GPU_UNSAFE_PIPELINED_LOOP_ANNOTATOR_FIELD_NUMBER: builtins.int + XLA_GPU_PER_FUSION_AUTOTUNE_CACHE_DIR_FIELD_NUMBER: builtins.int + XLA_CMD_BUFFER_TRACE_CACHE_SIZE_FIELD_NUMBER: builtins.int + XLA_GPU_TEMP_BUFFER_USE_SEPARATE_COLOR_FIELD_NUMBER: builtins.int + LEGACY_COMMAND_BUFFER_CUSTOM_CALL_TARGETS_FIELD_NUMBER: builtins.int + XLA_SYNTAX_SUGAR_ASYNC_OPS_FIELD_NUMBER: builtins.int + XLA_GPU_AUTOTUNE_GEMM_RTOL_FIELD_NUMBER: builtins.int + XLA_ENABLE_COMMAND_BUFFERS_DURING_PROFILING_FIELD_NUMBER: builtins.int + XLA_GPU_CUDNN_GEMM_MAX_PLANS_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_LIBNVJITLINK_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_TRITON_GEMM_INT4_FIELD_NUMBER: builtins.int + XLA_GPU_ASYNC_DOT_FIELD_NUMBER: builtins.int + XLA_GPU_ENABLE_PGLE_ACCURACY_CHECKER_FIELD_NUMBER: builtins.int + XLA_GPU_EXECUTABLE_WARN_STUCK_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_GPU_EXECUTABLE_TERMINATE_TIMEOUT_SECONDS_FIELD_NUMBER: builtins.int + XLA_EXPERIMENTAL_IGNORE_CHANNEL_ID_FIELD_NUMBER: builtins.int + XLA_BACKEND_EXTRA_OPTIONS_FIELD_NUMBER: builtins.int + xla_cpu_enable_concurrency_optimized_scheduler: builtins.bool + """--------------------------------------------------------------------------// + XLA:CPU options. + --------------------------------------------------------------------------// + + go/keep-sorted start newline_separated=yes + + When true, XLA:CPU uses HLO module scheduler that is optimized for + extracting concurrency at the cost of extra memory: we extend the live + ranges of temporaries to allow XLA runtime to schedule independent + operations in parallel on separate threads. + """ + xla_cpu_enable_fast_math: builtins.bool + """When true, "unsafe" mathematical optimizations are enabled. These + transformations include but are not limited to: + + - Reducing the precision of operations (e.g. using an approximate sin + function, or transforming x/y into x * (1/y)). + - Assuming that operations never produce or consume NaN or +/- Inf (this + behavior can be adjusted using xla_cpu_fast_math_allow_{nans|infs}). + - Assuming that +0 and -0 are indistinguishable. + """ + xla_cpu_enable_fast_min_max: builtins.bool + """When false we lower the Minimum and Maximum hlos in the CPU backend such + that Min(NotNaN, NaN) = Min(NaN, NotNaN) = NaN. In other words, if flag + this is false we always propagate NaNs through Min and Max. + + Note, this does not correspond to the exact same behavior as the gpu flag + below! + """ + xla_cpu_fast_math_honor_division: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we forbid + to use the reciprocal of an argument instead of division. Ignored when + xla_cpu_enable_fast_math is false. + """ + xla_cpu_fast_math_honor_functions: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we forbid + to approximate calculations for functions. Ignored when + xla_cpu_enable_fast_math is false. + """ + xla_cpu_fast_math_honor_infs: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we allow + operations to produce infinites. Ignored when xla_cpu_enable_fast_math is + false. + """ + xla_cpu_fast_math_honor_nans: builtins.bool + """When xla_cpu_enable_fast_math is true then this controls whether we allow + operations to produce NaNs. Ignored when xla_cpu_enable_fast_math is + false. + """ + xla_cpu_use_thunk_runtime: builtins.bool + """When true, XLA:CPU uses the thunk runtime to execute compiled program.""" + xla_cpu_parallel_codegen_split_count: builtins.int + """The number of parts to split the LLVM module into before codegen. This + allows XLA to compile all parts in parallel, and resolve kernel symbols + from different dynamic libraries. + """ + xla_cpu_prefer_vector_width: builtins.int + """A `prefer-vector-width` value that is passed to the LLVM backend. Default + value is `256` (AVX2 on x86 platforms). + """ + xla_gpu_experimental_autotune_cache_mode: global___DebugOptions.AutotuneCacheMode.ValueType + """--------------------------------------------------------------------------// + XLA:GPU options. + --------------------------------------------------------------------------// + go/keep-sorted start newline_separated=yes skip_lines=1 + + Specifies the behavior of per kernel autotuning cache. + """ + xla_gpu_experimental_disable_binary_libraries: builtins.bool + """Experimentally disables binary libraries in GPU compiler passes.""" + xla_gpu_experimental_enable_triton_softmax_priority_fusion: builtins.bool + """Gates the experimental feature coupling the Triton Softmax pattern matcher + with priority fusion. + """ + xla_gpu_unsupported_enable_triton_gemm: builtins.bool + """Internal debug/testing flag to switch Triton GEMM fusions on or off.""" + xla_hlo_graph_addresses: builtins.bool + """--------------------------------------------------------------------------// + A bag of XLA options that have to be categorized. + --------------------------------------------------------------------------// + + Show addresses of HLO ops in graph dump. + """ + xla_hlo_profile: builtins.bool + """Instrument the computation to collect per-HLO cycle counts.""" + xla_disable_all_hlo_passes: builtins.bool + """Disables all HLO passes. Notes that some passes are necessary for + correctness and the invariants that must be satisfied by "fully optimized" + HLO are different for different devices and may change over time. The only + "guarantee", such as it is, is that if you compile XLA and dump the + optimized HLO for some graph, you should be able to run it again on the + same device with the same build of XLA. + """ + xla_backend_optimization_level: builtins.int + """Numerical optimization level for the XLA compiler backend; the specific + interpretation of this value is left to the backends. + """ + xla_embed_ir_in_executable: builtins.bool + """Embed the compiler IR as a string in the executable.""" + xla_eliminate_hlo_implicit_broadcast: builtins.bool + """Eliminate implicit broadcasts when lowering user computations to HLO + instructions; use explicit broadcast instead. + """ + xla_cpu_multi_thread_eigen: builtins.bool + """When generating calls to Eigen in the CPU backend, use multi-threaded Eigen + mode. + """ + xla_gpu_cuda_data_dir: builtins.str + """Path to directory with cuda/ptx tools and libraries.""" + xla_gpu_ftz: builtins.bool + """Enable flush-to-zero semantics in the GPU backend.""" + xla_llvm_enable_alias_scope_metadata: builtins.bool + """If true, in LLVM-based backends, emit !alias.scope metadata in + generated IR. + """ + xla_llvm_enable_noalias_metadata: builtins.bool + """If true, in LLVM-based backends, emit !noalias metadata in the + generated IR. + """ + xla_llvm_enable_invariant_load_metadata: builtins.bool + """If true, in LLVM-based backends, emit !invariant.load metadata in + the generated IR. + """ + xla_llvm_disable_expensive_passes: builtins.bool + """If true, a set of expensive LLVM optimization passes will not be run.""" + xla_test_all_output_layouts: builtins.bool + """This is used by ClientLibraryTestBase::ComputeAndCompare*. If true, the + computation will run n! times with all permunations of layouts for the + output shape in rank n. For example, with a 3D shape, all permutations of + the set {0, 1, 2} are tried. + """ + xla_test_all_input_layouts: builtins.bool + """This is used by ClientLibraryTestBase::ComputeAndCompare*. If true, the + computation will run for all permunations of layouts of all input + arguments. For example, with 2 input arguments in 2D and 4D shapes, the + computation will run 2! * 4! times. + """ + xla_hlo_graph_sharding_color: builtins.bool + """Assign colors based on sharding information when generating the Graphviz + HLO graph. + """ + xla_cpu_use_mkl_dnn: builtins.bool + """Generate calls to MKL-DNN in the CPU backend.""" + xla_gpu_enable_fast_min_max: builtins.bool + """When true we lower the Minimum and Maximum hlos in the GPU backend such + that Min(NotNaN, NaN) = Min(NaN, NotNaN) = NotNaN. In other words, if flag + this is true we don't propagate NaNs through Min and Max. + + Note, this does not correspond to the exact same behavior as the cpu flag + above! + """ + xla_allow_excess_precision: builtins.bool + """Allows xla to increase the output precision of floating point operations + and all floating-point conversions to be simplified, including those + that affect the numerics. The `FloatNormalization` pass inserts many + `f32 -> bf16 -> f32` conversion pairs. These are not removed by the + `AlgebraicSimplifier`, as that will only simplify conversions that are + no-ops, e.g. `bf16 -> f32 -> bf16`. Removing these improves accuracy. + """ + xla_gpu_crash_on_verification_failures: builtins.bool + """Crashes the program when any kind of verification fails, instead of just + logging the failures. One example is cross checking of convolution results + among different algorithms. + """ + xla_gpu_autotune_level: builtins.int + """0: Disable gemm and convolution autotuning. + 1: Enable autotuning, but disable correctness checking. + 2: Also set output buffers to random numbers during autotuning. + 3: Also reset output buffers to random numbers after autotuning each + algorithm. + 4+: Also check for correct outputs and for out-of-bounds reads/writes. + + Default: 4. + """ + xla_force_host_platform_device_count: builtins.int + """Force the host platform to pretend that there are these many host + "devices". All these devices are backed by the same threadpool. Defaults + to 1. + + Setting this to anything other than 1 can increase overhead from context + switching but we let the user override this behavior to help run tests on + the host that run models in parallel across multiple devices. + """ + xla_gpu_disable_gpuasm_optimizations: builtins.bool + """If set to true XLA:GPU invokes `ptxas` with -O0 (default is -O3).""" + xla_gpu_shape_checks: global___DebugOptions.ShapeChecks.ValueType + xla_hlo_evaluator_use_fast_path: builtins.bool + """Enable fast math with eigen in the HLO evaluator.""" + xla_allow_scalar_index_dynamic_ops: builtins.bool + """Temporary option to allow support for both the R1 and the scalar index + versions of DynamicSlice and DynamicUpdateSlice. Only used for testing. + """ + xla_step_marker_location: global___DebugOptions.StepMarkerLocation.ValueType + """Option to emit a target-specific marker to indicate the start of a training + step. The location of the marker (if any) is determined by the option + value. + """ + xla_dump_to: builtins.str + """ + BEGIN flags controlling dumping HLO modules for debugging. + + When dumping is enabled, HLO modules dumped at the very beginning and end + of compilation, and optionally also during the pass pipeline. + + In general, if you set one of these flags, we will try to infer reasonable + defaults for the others. For example: + + * Setting --xla_dump_to=/tmp/foo without specifying a format + with --xla_dump_hlo_as_* will turn on --xla_dump_hlo_as_text. + + * Setting --xla_dump_hlo_as_text without specifying --xla_dump_to will + dump to stdout. + + Directory to dump into. + """ + xla_dump_hlo_module_re: builtins.str + """If specified, will only dump modules which match this regexp.""" + xla_dump_hlo_pass_re: builtins.str + """If this flag is specified, will also dump HLO before and after passes that + match this regular expression. Set to .* to dump before/after all passes. + """ + xla_dump_hlo_as_text: builtins.bool + """Specifies the format that HLO is dumped in. Multiple of these may be + specified. + """ + xla_dump_hlo_as_proto: builtins.bool + xla_dump_hlo_as_dot: builtins.bool + xla_dump_hlo_as_url: builtins.bool + xla_dump_hlo_as_html: builtins.bool + """Dump HLO graphs as an HTML (DOT -> SVG inlined in HTML)""" + xla_dump_fusion_visualization: builtins.bool + """Dump the visualization of the fusion progress.""" + xla_dump_hlo_snapshots: builtins.bool + """If true, every time an HLO module is run, we will dump an HloSnapshot + (essentially, a serialized module plus its inputs) to the --xla_dump_to + directory. + """ + xla_dump_include_timestamp: builtins.bool + """Include a timestamp in the dumped filenames.""" + xla_dump_max_hlo_modules: builtins.int + """Max number of hlo module dumps in a directory. Set to < 0 for unbounded.""" + xla_dump_module_metadata: builtins.bool + """Dump HloModuleMetadata as a text proto for each HLO module.""" + xla_dump_compress_protos: builtins.bool + """GZip-compress protos dumped via --xla_dump_hlo_as_proto.""" + xla_dump_hlo_as_long_text: builtins.bool + """Dump HLO in long text format. Ignored unless xla_dump_hlo_as_text is true.""" + xla_gpu_force_conv_nchw: builtins.bool + """ + END flags controlling dumping HLO modules. + + Overrides for XLA GPU's convolution layout heuristic. + """ + xla_gpu_force_conv_nhwc: builtins.bool + xla_gpu_dump_llvmir: builtins.bool + """Whether to dump llvm ir when compiling to ptx.""" + xla_dump_enable_mlir_pretty_form: builtins.bool + """Whether to dump mlir using pretty print form.""" + xla_gpu_algorithm_denylist_path: builtins.str + """Denylist for cuDNN convolutions.""" + xla_tpu_detect_nan: builtins.bool + """Debug options that trigger execution errors when NaN or Inf are detected.""" + xla_tpu_detect_inf: builtins.bool + xla_cpu_enable_xprof_traceme: builtins.bool + """True if TraceMe annotations are enabled for XLA:CPU.""" + xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found: builtins.bool + """It is usually preferable to not fallback to the driver; it can consume more + memory, or have bugs. + """ + xla_gpu_asm_extra_flags: builtins.str + """Extra parameters to pass the GPU assembler.""" + xla_multiheap_size_constraint_per_heap: builtins.int + """Per-heap size constraint. New heaps will be created if per-heap max size is + reached. + """ + xla_detailed_logging: builtins.bool + """Enable detailed logging into vlog. If this is disabled, no + compilation summary will be printed in the end of computation. + """ + xla_enable_dumping: builtins.bool + """Enable HLO dumping. If this is disabled, no HLO modules will be dumped.""" + xla_gpu_force_compilation_parallelism: builtins.int + """Overrides normal multi-threaded compilation setting to use this many + threads. Setting to 0 (the default value) means no enforcement. + """ + xla_gpu_enable_llvm_module_compilation_parallelism: builtins.bool + xla_gpu_deterministic_ops: builtins.bool + """Guarantees run-to-run determinism. + This flag implies --xla_gpu_exclude_nondeterministic_ops and in addition + disables autotuning. + """ + xla_gpu_all_reduce_combine_threshold_bytes: builtins.int + """Size threshold (in bytes) for the GPU collective combiners.""" + xla_gpu_all_gather_combine_threshold_bytes: builtins.int + xla_gpu_reduce_scatter_combine_threshold_bytes: builtins.int + xla_gpu_enable_all_gather_combine_by_dim: builtins.bool + """Combine all-gather/scatter-reduce ops with the same dimension or + irrespective of their dimension. + """ + xla_gpu_enable_reduce_scatter_combine_by_dim: builtins.bool + xla_gpu_enable_reassociation_for_converted_ar: builtins.bool + """Enable allreduce reassociation on allreduces that are converted to a wider + type. The resulting allreduce will be promoted to a wider-typed allreduce. + """ + xla_gpu_all_reduce_blueconnect_num_devices_per_host: builtins.int + """Number of devices per host for first stage of BlueConnect decomposition + pass. The pass will attempt to decompose all-reduces ops into a + ReduceScatter-AllReduce-AllGather sequence, with the initial ReduceScatter + being performed over all of the devices in the same host. Set to < 1 to + disable all-reduce decomposition. + """ + xla_gpu_enable_while_loop_reduce_scatter_code_motion: builtins.bool + """Enable hoisting of reduce-scatter out of while loops.""" + xla_gpu_collective_inflation_factor: builtins.int + """Inflate collective cost by running each collective multiple times.""" + xla_llvm_force_inline_before_split: builtins.bool + """Whether to force inline before llvm module split to get a more balanced + splits for parallel compilation. + """ + xla_gpu_enable_cudnn_frontend: builtins.bool + """Whether to use the cuDNN frontend API for convolutions when possible.""" + xla_gpu_enable_cudnn_fmha: builtins.bool + xla_gpu_fused_attention_use_cudnn_rng: builtins.bool + xla_gpu_enable_cudnn_layer_norm: builtins.bool + """Rewrite layer norm patterns into cuDNN library calls.""" + xla_dump_disable_metadata: builtins.bool + """Disable dumping metadata in HLO dumps.""" + xla_dump_hlo_pipeline_re: builtins.str + """If this flag is specified, will only dump HLO before and after passes in + the pass pipeline that matches this regular expression. Default empty value + enables dumping in all pipelines. + """ + xla_gpu_strict_conv_algorithm_picker: builtins.bool + """If true, abort immediately when conv algorithm picker fails, rather than + logging a warning and proceeding with fallback. + """ + xla_gpu_enable_custom_fusions: builtins.bool + """If true, XLA will try to pattern match subgraphs of HLO operations into + custom fusions registered in the current process (pre-compiled hand written + kernels, e.g. various GEMM fusions writtent in CUTLASS). + """ + xla_gpu_enable_custom_fusions_re: builtins.str + """A regular expression enabling only a subset of custom fusions. Enabled only + if `xla_gpu_enable_custom_fusion` set to true. + """ + xla_gpu_enable_dynamic_slice_fusion: builtins.bool + """Enables address computation fusion to optimize dynamic-slice and + dynamic-update-slice operations around library calls. + """ + xla_gpu_nccl_termination_timeout_seconds: builtins.int + """Timeout in seconds before terminating jobs that are stuck in a NCCL + Rendezvous. Negative value disables the timeout and will not terminate. + """ + xla_gpu_enable_shared_constants: builtins.bool + """Enables shared constants for XLA/GPU. This allows large constants to be + shared among multiple GPU executables. + """ + xla_gpu_enable_cublaslt: builtins.bool + """Whether to use cuBLASLt for GEMMs on GPUs.""" + xla_gpu_graph_min_graph_size: builtins.int + """This number determines how many moved instructions like fusion kernels are + required for a region to be captured as a function to be launched as a GPU + graph. + """ + xla_gpu_graph_enable_concurrent_region: builtins.bool + """Identify concurrent regions in GPU graphs and execute them concurrently.""" + xla_gpu_redzone_scratch_max_megabytes: builtins.int + """Size threshold (in megabytes) for the GPU redzone scratch allocator.""" + xla_gpu_redzone_padding_bytes: builtins.int + """Amount of padding the redzone allocator will put on one side of each buffer + it allocates. (So the buffer's total size will be increased by 2x this + value.) + + Higher values make it more likely that we'll catch an out-of-bounds read or + write. Smaller values consume less memory during autotuning. Note that a + fused cudnn conv has up to 6 total buffers (4 inputs, 1 output, and 1 + scratch), so this can be multiplied by quite a lot. + """ + xla_cpu_use_acl: builtins.bool + """Generate calls to Arm Compute Library in the CPU backend.""" + xla_cpu_strict_dot_conv_math: builtins.bool + """By default, XLA:CPU will run fp16 dot/conv as fp32, as this is generally + (much) faster on our hardware. Set this flag to disable this behavior. + """ + xla_gpu_use_runtime_fusion: builtins.bool + """An option to enable using cuDNN runtime compiled fusion kernels which is + available and recommended for Ampere+ GPUs. + """ + xla_dump_latency_hiding_schedule: builtins.bool + xla_cpu_enable_mlir_tiling_and_fusion: builtins.bool + """By default, MLIR lowering will use Linalg elementwise fusion. If this flag + is enabled, the pipeline will use tiling, fusion, peeling, vectorization + instead. + """ + xla_cpu_enable_custom_matmul_tiling: builtins.bool + """XLA:CPU-Next tiling parameters for matmul.""" + xla_cpu_matmul_tiling_m_dim: builtins.int + xla_cpu_matmul_tiling_n_dim: builtins.int + xla_cpu_matmul_tiling_k_dim: builtins.int + xla_cpu_enable_mlir_fusion_outlining: builtins.bool + xla_cpu_enable_experimental_deallocation: builtins.bool + """If set, use the experimental deallocation pass from mlir-hlo.""" + xla_gpu_enable_latency_hiding_scheduler: builtins.bool + xla_gpu_enable_highest_priority_async_stream: builtins.bool + xla_gpu_enable_analytical_latency_estimator: builtins.bool + xla_gpu_lhs_enable_gpu_async_tracker: builtins.bool + xla_gpu_pgle_profile_file_or_directory_path: builtins.str + xla_gpu_memory_limit_slop_factor: builtins.int + xla_gpu_enable_pipelined_collectives: builtins.bool + xla_gpu_enable_pipelined_all_reduce: builtins.bool + xla_gpu_enable_pipelined_all_gather: builtins.bool + xla_gpu_enable_pipelined_reduce_scatter: builtins.bool + xla_gpu_enable_pipelined_p2p: builtins.bool + xla_gpu_run_post_layout_collective_pipeliner: builtins.bool + xla_gpu_collective_permute_decomposer_threshold: builtins.int + """The minimum data size in bytes to trigger collective-permute-decomposer + transformation. + """ + xla_partitioning_algorithm: global___DebugOptions.PartitioningAlgorithm.ValueType + """The partitioning algorithm to be used in the PartitionAssignment pass.""" + xla_gpu_enable_triton_gemm: builtins.bool + xla_gpu_enable_cudnn_int8x32_convolution_reordering: builtins.bool + xla_gpu_triton_gemm_any: builtins.bool + """Creates triton fusion for all supported gemms. + To make sure only triton gemm is chosen by the autotuner run with + `xla_gpu_cublas_fallback` set to false. + """ + xla_gpu_exhaustive_tiling_search: builtins.bool + xla_gpu_enable_priority_fusion: builtins.bool + xla_gpu_dump_autotune_results_to: builtins.str + """File to write autotune results to. It will be a binary file unless the name + ends with .txt or .textproto. Warning: The results are written at every + compilation, possibly multiple times per process. This only works on CUDA. + """ + xla_gpu_load_autotune_results_from: builtins.str + """File to load autotune results from. It will be considered a binary file + unless the name ends with .txt or .textproto. At most one loading will + happen during the lifetime of one process, even if the first one is + unsuccessful or different file paths are passed here. This only works on + CUDA. + """ + xla_gpu_target_config_filename: builtins.str + """Description of the target platform in GpuTargetConfigProto format; if + provided, deviceless compilation is assumed, and the current device is + ignored. + """ + xla_gpu_auto_spmd_partitioning_memory_budget_gb: builtins.int + """Memory budget in GB per device for AutoSharding.""" + xla_gpu_auto_spmd_partitioning_memory_budget_ratio: builtins.float + """See the definition of the + xla_gpu_auto_spmd_partitioning_memory_budget_ratio flag for the meaning of + this field. + """ + xla_gpu_triton_gemm_disable_reduced_precision_reduction: builtins.bool + xla_gpu_triton_fusion_level: builtins.int + xla_gpu_dump_autotuned_gemm_fusions: builtins.bool + xla_gpu_override_gemm_autotuner: builtins.str + xla_gpu_copy_insertion_use_region_analysis: builtins.bool + xla_gpu_collect_cost_model_stats: builtins.bool + """If true, each fusion instruction will have a cost model runtime estimate in + backend config after compilation. + """ + xla_gpu_enable_split_k_autotuning: builtins.bool + xla_gpu_enable_reduction_epilogue_fusion: builtins.bool + """Whether reduction epilogue fusion is enabled in fusion passes.""" + xla_gpu_enable_nccl_clique_optimization: builtins.bool + """Allow early return when acquiring NCCL cliques.""" + xla_gpu_mock_custom_calls: builtins.bool + """Replace custom calls with noop operations.""" + xla_gpu_cublas_fallback: builtins.bool + """Allow Triton GEMM autotuning to fall back to cuBLAS when that is + faster. + """ + xla_gpu_enable_while_loop_double_buffering: builtins.bool + """Enable double buffering for loops.""" + xla_gpu_enable_while_loop_unrolling: global___DebugOptions.WhileLoopUnrolling.ValueType + """Determine the while loop unrolling scheme.""" + xla_gpu_ensure_minor_dot_contraction_dims: builtins.bool + """Change the layout of the second triton dot operand to be column major. + Only works for (bf16 x bf16) -> bf16. + """ + xla_gpu_filter_kernels_spilling_registers_on_autotuning: builtins.bool + """Filter out kernels that spill registers during autotuning.""" + xla_debug_buffer_assignment_show_max: builtins.int + """Maximum number of buffers to print when debugging buffer assignment.""" + xla_gpu_llvm_verification_level: builtins.int + xla_gpu_enable_cub_radix_sort: builtins.bool + """Enable radix sort using CUB.""" + xla_gpu_threshold_for_windowed_einsum_mib: builtins.int + """Threshold to enable windowed einsum (collective matmul) in MB.""" + xla_gpu_enable_triton_hopper: builtins.bool + """Enables currently disabled features within Triton for Hopper.""" + xla_gpu_enable_nccl_user_buffers: builtins.bool + """Enable NCCL user buffers.""" + xla_gpu_enable_nccl_comm_splitting: builtins.bool + """Enable NCCL communicator splitting.""" + xla_gpu_enable_nccl_per_stream_comms: builtins.bool + """Enable NCCL per stream communicators.""" + xla_gpu_enable_libnvptxcompiler: builtins.bool + """If enabled, uses the libnvptxcompiler library to compile PTX to cuBIN.""" + xla_gpu_enable_dot_strength_reduction: builtins.bool + xla_gpu_multi_streamed_windowed_einsum: builtins.bool + """Whether to use multiple compute streams to run windowed einsum.""" + xla_gpu_enable_bf16_6way_gemm: builtins.bool + """If enabled, uses bf16_6way gemm to compute F32 gemm.""" + xla_gpu_enable_bf16_3way_gemm: builtins.bool + """If enabled, uses bf16_3way gemm to compute F32 gemm.""" + xla_gpu_nccl_collective_max_nchannels: builtins.int + """Specify the maximum number of channels(SMs) NCCL + will use for collective operations. + """ + xla_gpu_nccl_p2p_max_nchannels: builtins.int + """Specify the maximum number of channels(SMs) NCCL + will use for p2p operations. + """ + xla_gpu_mlir_emitter_level: builtins.int + """Choose the level of mlir emitters that are enabled. + Current levels: + 0: Disabled. + 1: Loop emitter + 2: + Loop-like emitters + 3: + Transpose + 4: + Reduce + """ + xla_gpu_gemm_rewrite_size_threshold: builtins.int + """Threshold to rewrite matmul to cuBLAS or Triton (minimum combined number of + elements of both matrices in non-batch dimensions to be considered for a + rewrite). + """ + xla_gpu_require_complete_aot_autotune_results: builtins.bool + """If true, will require complete AOT autotuning results; in the case of + missing AOT result, the model will not be compiled or executed, a + `NotFound` error will be returned. + """ + xla_gpu_cudnn_gemm_fusion_level: builtins.int + """Let GEMM fusion autotuning probe cuDNN as a backend. + Current levels: + 0: Disabled. + 1: Fusions of GEMM, elementwise, transpose/reshape operations. + 2: + Broadcasts, slicing. + 3: + Nontrivial noncontracting dimension reshapes/transposes. + """ + xla_gpu_use_memcpy_local_p2p: builtins.bool + """This instructs the runtime whether to use + memcpy for p2p communication when source and + target are located within a node(nvlink). + """ + xla_gpu_autotune_max_solutions: builtins.int + """If non-zero, limits the number of solutions to be used by GEMM autotuner. + This might be useful if underlying math library returns too many GEMM + solutions. + """ + xla_dump_large_constants: builtins.bool + """If true, large constants will be printed out when dumping HLOs.""" + xla_gpu_verify_triton_fusion_numerics: builtins.bool + """If true, will verify that the numerical results of Triton fusions match + the results of regular emitters. + """ + xla_gpu_dump_autotune_logs_to: builtins.str + """File to write autotune logs to. It will stored in txt format.""" + xla_reduce_window_rewrite_base_length: builtins.int + """Base length to rewrite the reduce window to, no rewrite if set to 0.""" + xla_gpu_enable_host_memory_offloading: builtins.bool + """If true, will enable host memory offloading on a device.""" + xla_gpu_exclude_nondeterministic_ops: builtins.bool + """Excludes non-deterministic ops from compiled executables. + Unlike --xla_gpu_deterministic_ops does not disable autotuning - the + compilation itself can be non-deterministic. + At present, the HLO op SelectAndScatter does not have a + deterministic XLA:GPU implementation. + Compilation errors out if SelectAndScatter is encountered. + Scatter ops can non-deterministic by default; these get converted to + a deterministic implementation. + """ + xla_gpu_nccl_terminate_on_error: builtins.bool + """If true, Nccl errors will terminate the process.""" + xla_gpu_shard_autotuning: builtins.bool + xla_gpu_enable_approx_costly_collectives: builtins.bool + xla_gpu_kernel_cache_file: builtins.str + xla_gpu_unsafe_pipelined_loop_annotator: builtins.bool + """Recognises rotate-right patterns (slice, slice, concat) within a while + loop and labels the while loop as a pipelined while loop. This is an + unsafe flag. + """ + xla_gpu_per_fusion_autotune_cache_dir: builtins.str + xla_cmd_buffer_trace_cache_size: builtins.int + """The command buffer trace cache size, increasing the cache size may + sometimes reduces the chances of doing command buffer tracing for + updating command buffer instance. + """ + xla_gpu_temp_buffer_use_separate_color: builtins.bool + """Enable this flag will use a separate memory space color for + temp buffer, and then will use separate memory allocator to allocate it, + as there is no other memory allocation interference, + it will allocate temp buffer to some fix address on every iteration, + which is good for cuda-graph perf. + """ + xla_syntax_sugar_async_ops: builtins.bool + """This flag is used for controlling HLO dumping and NVTX marker. If turned + on, both HLO dumping and NVTX marker will use syntactic sugar wrappers + as op names, while the actual op names will be shown if turned off. + + Here is an example HLO excerpt with the flag off: + + async_computation { + param_0 = f32[1,4,8]{1,0,2} parameter(0) + ROOT all-to-all.3.1 = f32[1,4,8]{1,0,2} all-to-all(param_0), + replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={2} + } + ... + + all-to-all-start = + ((f32[1,4,8]{1,0,2}), f32[1,4,8]{1,0,2}) async-start(bitcast.24.0), + calls=async_computation, backend_config={...} + all-to-all-done = f32[1,4,8]{1,0,2} async-done(all-to-all-start) + + and with the flag on: + + all-to-all-start = ((f32[1,4,8]{1,0,2}), f32[1,4,8]{1,0,2}) + all-to-all-start(bitcast.24.0), + replica_groups={{0,1,2,3,4,5,6,7}}, dimensions={2}, + backend_config={...} + all-to-all-done = f32[1,4,8]{1,0,2} all-to-all-done(all-to-all-start) + """ + xla_gpu_autotune_gemm_rtol: builtins.float + """Relative precision for comparing different GEMM solutions""" + xla_enable_command_buffers_during_profiling: builtins.bool + """Allow launching command buffers while profiling active. + When disabled, execute in op-by-op mode. + TODO(b/355487968): Remove this option when validation complete. + """ + xla_gpu_cudnn_gemm_max_plans: builtins.int + """Limit for the number of kernel configurations (plans) to use during + autotuning of cuDNN GEMM fusions. The more - the slower the autotuning + but potentially higher the performance. + """ + xla_gpu_enable_libnvjitlink: builtins.bool + """If enabled, uses the libnvjitlink library for PTX compilation and linking""" + xla_gpu_enable_triton_gemm_int4: builtins.bool + """If enabled, generates triton gemm kernels for int4 inputs.""" + xla_gpu_async_dot: builtins.bool + """If true, XLA will wrap `dot` operations into async computations in an + effort to parallelize matrix operations. + """ + xla_gpu_enable_pgle_accuracy_checker: builtins.bool + """Enables strict PGLE checking. If an FDO profile is specified and latency + hiding scheduler encounters missing instructions in the profile + compilation will halt. + """ + xla_gpu_executable_warn_stuck_timeout_seconds: builtins.int + """Timeouts for RendezvousSingle stuck warning and termination.""" + xla_gpu_executable_terminate_timeout_seconds: builtins.int + xla_experimental_ignore_channel_id: builtins.bool + """Whether to ignore channel ids(including verifier channel id checks) + for collectives in the given HLO. + """ + @property + def xla_disable_hlo_passes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of HLO passes to disable/enable. These names must exactly match the + pass names as specified by the HloPassInterface::name() method. + + At least one of xla_disable_hlo_passes and xla_enable_hlo_passes_only must + be empty. + """ + + @property + def xla_enable_hlo_passes_only(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ... + @property + def xla_gpu_ptx_file(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Paths to files with ptx code.""" + + @property + def xla_gpu_llvm_ir_file(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Paths to files with LLVM code.""" + + @property + def xla_gpu_disable_async_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DebugOptions.CollectiveOpType.ValueType]: ... + @property + def xla_gpu_enable_command_buffer( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[global___DebugOptions.CommandBufferCmdType.ValueType]: + """Determine the types of commands that are recorded into command buffers.""" + + @property + def legacy_command_buffer_custom_call_targets( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """Custom call targets with legacy registry API (non FFI API), + that support recording to command buffer custom command, + i.e., custom call target supports cuda-graph capturing for CUDA devices. + This flag is read if CUSTOM_CALL command type is recorded into + command buffer. + """ + + @property + def xla_backend_extra_options(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.str]: + """Next id: 331 + + Extra options to pass to the compilation backend (e.g. LLVM); specific + interpretation of these values is left to the backend. + """ + + def __init__( + self, + *, + xla_cpu_enable_concurrency_optimized_scheduler: builtins.bool | None = ..., + xla_cpu_enable_fast_math: builtins.bool | None = ..., + xla_cpu_enable_fast_min_max: builtins.bool | None = ..., + xla_cpu_fast_math_honor_division: builtins.bool | None = ..., + xla_cpu_fast_math_honor_functions: builtins.bool | None = ..., + xla_cpu_fast_math_honor_infs: builtins.bool | None = ..., + xla_cpu_fast_math_honor_nans: builtins.bool | None = ..., + xla_cpu_use_thunk_runtime: builtins.bool | None = ..., + xla_cpu_parallel_codegen_split_count: builtins.int | None = ..., + xla_cpu_prefer_vector_width: builtins.int | None = ..., + xla_gpu_experimental_autotune_cache_mode: global___DebugOptions.AutotuneCacheMode.ValueType | None = ..., + xla_gpu_experimental_disable_binary_libraries: builtins.bool | None = ..., + xla_gpu_experimental_enable_triton_softmax_priority_fusion: builtins.bool | None = ..., + xla_gpu_unsupported_enable_triton_gemm: builtins.bool | None = ..., + xla_hlo_graph_addresses: builtins.bool | None = ..., + xla_hlo_profile: builtins.bool | None = ..., + xla_disable_hlo_passes: collections.abc.Iterable[builtins.str] | None = ..., + xla_enable_hlo_passes_only: collections.abc.Iterable[builtins.str] | None = ..., + xla_disable_all_hlo_passes: builtins.bool | None = ..., + xla_backend_optimization_level: builtins.int | None = ..., + xla_embed_ir_in_executable: builtins.bool | None = ..., + xla_eliminate_hlo_implicit_broadcast: builtins.bool | None = ..., + xla_cpu_multi_thread_eigen: builtins.bool | None = ..., + xla_gpu_cuda_data_dir: builtins.str | None = ..., + xla_gpu_ftz: builtins.bool | None = ..., + xla_llvm_enable_alias_scope_metadata: builtins.bool | None = ..., + xla_llvm_enable_noalias_metadata: builtins.bool | None = ..., + xla_llvm_enable_invariant_load_metadata: builtins.bool | None = ..., + xla_llvm_disable_expensive_passes: builtins.bool | None = ..., + xla_test_all_output_layouts: builtins.bool | None = ..., + xla_test_all_input_layouts: builtins.bool | None = ..., + xla_hlo_graph_sharding_color: builtins.bool | None = ..., + xla_cpu_use_mkl_dnn: builtins.bool | None = ..., + xla_gpu_enable_fast_min_max: builtins.bool | None = ..., + xla_allow_excess_precision: builtins.bool | None = ..., + xla_gpu_crash_on_verification_failures: builtins.bool | None = ..., + xla_gpu_autotune_level: builtins.int | None = ..., + xla_force_host_platform_device_count: builtins.int | None = ..., + xla_gpu_disable_gpuasm_optimizations: builtins.bool | None = ..., + xla_gpu_shape_checks: global___DebugOptions.ShapeChecks.ValueType | None = ..., + xla_hlo_evaluator_use_fast_path: builtins.bool | None = ..., + xla_allow_scalar_index_dynamic_ops: builtins.bool | None = ..., + xla_step_marker_location: global___DebugOptions.StepMarkerLocation.ValueType | None = ..., + xla_dump_to: builtins.str | None = ..., + xla_dump_hlo_module_re: builtins.str | None = ..., + xla_dump_hlo_pass_re: builtins.str | None = ..., + xla_dump_hlo_as_text: builtins.bool | None = ..., + xla_dump_hlo_as_proto: builtins.bool | None = ..., + xla_dump_hlo_as_dot: builtins.bool | None = ..., + xla_dump_hlo_as_url: builtins.bool | None = ..., + xla_dump_hlo_as_html: builtins.bool | None = ..., + xla_dump_fusion_visualization: builtins.bool | None = ..., + xla_dump_hlo_snapshots: builtins.bool | None = ..., + xla_dump_include_timestamp: builtins.bool | None = ..., + xla_dump_max_hlo_modules: builtins.int | None = ..., + xla_dump_module_metadata: builtins.bool | None = ..., + xla_dump_compress_protos: builtins.bool | None = ..., + xla_dump_hlo_as_long_text: builtins.bool | None = ..., + xla_gpu_force_conv_nchw: builtins.bool | None = ..., + xla_gpu_force_conv_nhwc: builtins.bool | None = ..., + xla_gpu_ptx_file: collections.abc.Iterable[builtins.str] | None = ..., + xla_gpu_dump_llvmir: builtins.bool | None = ..., + xla_dump_enable_mlir_pretty_form: builtins.bool | None = ..., + xla_gpu_algorithm_denylist_path: builtins.str | None = ..., + xla_tpu_detect_nan: builtins.bool | None = ..., + xla_tpu_detect_inf: builtins.bool | None = ..., + xla_cpu_enable_xprof_traceme: builtins.bool | None = ..., + xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found: builtins.bool | None = ..., + xla_gpu_asm_extra_flags: builtins.str | None = ..., + xla_multiheap_size_constraint_per_heap: builtins.int | None = ..., + xla_detailed_logging: builtins.bool | None = ..., + xla_enable_dumping: builtins.bool | None = ..., + xla_gpu_force_compilation_parallelism: builtins.int | None = ..., + xla_gpu_enable_llvm_module_compilation_parallelism: builtins.bool | None = ..., + xla_gpu_deterministic_ops: builtins.bool | None = ..., + xla_gpu_llvm_ir_file: collections.abc.Iterable[builtins.str] | None = ..., + xla_gpu_disable_async_collectives: ( + collections.abc.Iterable[global___DebugOptions.CollectiveOpType.ValueType] | None + ) = ..., + xla_gpu_all_reduce_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_all_gather_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_reduce_scatter_combine_threshold_bytes: builtins.int | None = ..., + xla_gpu_enable_all_gather_combine_by_dim: builtins.bool | None = ..., + xla_gpu_enable_reduce_scatter_combine_by_dim: builtins.bool | None = ..., + xla_gpu_enable_reassociation_for_converted_ar: builtins.bool | None = ..., + xla_gpu_all_reduce_blueconnect_num_devices_per_host: builtins.int | None = ..., + xla_gpu_enable_while_loop_reduce_scatter_code_motion: builtins.bool | None = ..., + xla_gpu_collective_inflation_factor: builtins.int | None = ..., + xla_llvm_force_inline_before_split: builtins.bool | None = ..., + xla_gpu_enable_cudnn_frontend: builtins.bool | None = ..., + xla_gpu_enable_cudnn_fmha: builtins.bool | None = ..., + xla_gpu_fused_attention_use_cudnn_rng: builtins.bool | None = ..., + xla_gpu_enable_cudnn_layer_norm: builtins.bool | None = ..., + xla_dump_disable_metadata: builtins.bool | None = ..., + xla_dump_hlo_pipeline_re: builtins.str | None = ..., + xla_gpu_strict_conv_algorithm_picker: builtins.bool | None = ..., + xla_gpu_enable_custom_fusions: builtins.bool | None = ..., + xla_gpu_enable_custom_fusions_re: builtins.str | None = ..., + xla_gpu_enable_dynamic_slice_fusion: builtins.bool | None = ..., + xla_gpu_nccl_termination_timeout_seconds: builtins.int | None = ..., + xla_gpu_enable_shared_constants: builtins.bool | None = ..., + xla_gpu_enable_cublaslt: builtins.bool | None = ..., + xla_gpu_enable_command_buffer: ( + collections.abc.Iterable[global___DebugOptions.CommandBufferCmdType.ValueType] | None + ) = ..., + xla_gpu_graph_min_graph_size: builtins.int | None = ..., + xla_gpu_graph_enable_concurrent_region: builtins.bool | None = ..., + xla_gpu_redzone_scratch_max_megabytes: builtins.int | None = ..., + xla_gpu_redzone_padding_bytes: builtins.int | None = ..., + xla_cpu_use_acl: builtins.bool | None = ..., + xla_cpu_strict_dot_conv_math: builtins.bool | None = ..., + xla_gpu_use_runtime_fusion: builtins.bool | None = ..., + xla_dump_latency_hiding_schedule: builtins.bool | None = ..., + xla_cpu_enable_mlir_tiling_and_fusion: builtins.bool | None = ..., + xla_cpu_enable_custom_matmul_tiling: builtins.bool | None = ..., + xla_cpu_matmul_tiling_m_dim: builtins.int | None = ..., + xla_cpu_matmul_tiling_n_dim: builtins.int | None = ..., + xla_cpu_matmul_tiling_k_dim: builtins.int | None = ..., + xla_cpu_enable_mlir_fusion_outlining: builtins.bool | None = ..., + xla_cpu_enable_experimental_deallocation: builtins.bool | None = ..., + xla_gpu_enable_latency_hiding_scheduler: builtins.bool | None = ..., + xla_gpu_enable_highest_priority_async_stream: builtins.bool | None = ..., + xla_gpu_enable_analytical_latency_estimator: builtins.bool | None = ..., + xla_gpu_lhs_enable_gpu_async_tracker: builtins.bool | None = ..., + xla_gpu_pgle_profile_file_or_directory_path: builtins.str | None = ..., + xla_gpu_memory_limit_slop_factor: builtins.int | None = ..., + xla_gpu_enable_pipelined_collectives: builtins.bool | None = ..., + xla_gpu_enable_pipelined_all_reduce: builtins.bool | None = ..., + xla_gpu_enable_pipelined_all_gather: builtins.bool | None = ..., + xla_gpu_enable_pipelined_reduce_scatter: builtins.bool | None = ..., + xla_gpu_enable_pipelined_p2p: builtins.bool | None = ..., + xla_gpu_run_post_layout_collective_pipeliner: builtins.bool | None = ..., + xla_gpu_collective_permute_decomposer_threshold: builtins.int | None = ..., + xla_partitioning_algorithm: global___DebugOptions.PartitioningAlgorithm.ValueType | None = ..., + xla_gpu_enable_triton_gemm: builtins.bool | None = ..., + xla_gpu_enable_cudnn_int8x32_convolution_reordering: builtins.bool | None = ..., + xla_gpu_triton_gemm_any: builtins.bool | None = ..., + xla_gpu_exhaustive_tiling_search: builtins.bool | None = ..., + xla_gpu_enable_priority_fusion: builtins.bool | None = ..., + xla_gpu_dump_autotune_results_to: builtins.str | None = ..., + xla_gpu_load_autotune_results_from: builtins.str | None = ..., + xla_gpu_target_config_filename: builtins.str | None = ..., + xla_gpu_auto_spmd_partitioning_memory_budget_gb: builtins.int | None = ..., + xla_gpu_auto_spmd_partitioning_memory_budget_ratio: builtins.float | None = ..., + xla_gpu_triton_gemm_disable_reduced_precision_reduction: builtins.bool | None = ..., + xla_gpu_triton_fusion_level: builtins.int | None = ..., + xla_gpu_dump_autotuned_gemm_fusions: builtins.bool | None = ..., + xla_gpu_override_gemm_autotuner: builtins.str | None = ..., + xla_gpu_copy_insertion_use_region_analysis: builtins.bool | None = ..., + xla_gpu_collect_cost_model_stats: builtins.bool | None = ..., + xla_gpu_enable_split_k_autotuning: builtins.bool | None = ..., + xla_gpu_enable_reduction_epilogue_fusion: builtins.bool | None = ..., + xla_gpu_enable_nccl_clique_optimization: builtins.bool | None = ..., + xla_gpu_mock_custom_calls: builtins.bool | None = ..., + xla_gpu_cublas_fallback: builtins.bool | None = ..., + xla_gpu_enable_while_loop_double_buffering: builtins.bool | None = ..., + xla_gpu_enable_while_loop_unrolling: global___DebugOptions.WhileLoopUnrolling.ValueType | None = ..., + xla_gpu_ensure_minor_dot_contraction_dims: builtins.bool | None = ..., + xla_gpu_filter_kernels_spilling_registers_on_autotuning: builtins.bool | None = ..., + xla_debug_buffer_assignment_show_max: builtins.int | None = ..., + xla_gpu_llvm_verification_level: builtins.int | None = ..., + xla_gpu_enable_cub_radix_sort: builtins.bool | None = ..., + xla_gpu_threshold_for_windowed_einsum_mib: builtins.int | None = ..., + xla_gpu_enable_triton_hopper: builtins.bool | None = ..., + xla_gpu_enable_nccl_user_buffers: builtins.bool | None = ..., + xla_gpu_enable_nccl_comm_splitting: builtins.bool | None = ..., + xla_gpu_enable_nccl_per_stream_comms: builtins.bool | None = ..., + xla_gpu_enable_libnvptxcompiler: builtins.bool | None = ..., + xla_gpu_enable_dot_strength_reduction: builtins.bool | None = ..., + xla_gpu_multi_streamed_windowed_einsum: builtins.bool | None = ..., + xla_gpu_enable_bf16_6way_gemm: builtins.bool | None = ..., + xla_gpu_enable_bf16_3way_gemm: builtins.bool | None = ..., + xla_gpu_nccl_collective_max_nchannels: builtins.int | None = ..., + xla_gpu_nccl_p2p_max_nchannels: builtins.int | None = ..., + xla_gpu_mlir_emitter_level: builtins.int | None = ..., + xla_gpu_gemm_rewrite_size_threshold: builtins.int | None = ..., + xla_gpu_require_complete_aot_autotune_results: builtins.bool | None = ..., + xla_gpu_cudnn_gemm_fusion_level: builtins.int | None = ..., + xla_gpu_use_memcpy_local_p2p: builtins.bool | None = ..., + xla_gpu_autotune_max_solutions: builtins.int | None = ..., + xla_dump_large_constants: builtins.bool | None = ..., + xla_gpu_verify_triton_fusion_numerics: builtins.bool | None = ..., + xla_gpu_dump_autotune_logs_to: builtins.str | None = ..., + xla_reduce_window_rewrite_base_length: builtins.int | None = ..., + xla_gpu_enable_host_memory_offloading: builtins.bool | None = ..., + xla_gpu_exclude_nondeterministic_ops: builtins.bool | None = ..., + xla_gpu_nccl_terminate_on_error: builtins.bool | None = ..., + xla_gpu_shard_autotuning: builtins.bool | None = ..., + xla_gpu_enable_approx_costly_collectives: builtins.bool | None = ..., + xla_gpu_kernel_cache_file: builtins.str | None = ..., + xla_gpu_unsafe_pipelined_loop_annotator: builtins.bool | None = ..., + xla_gpu_per_fusion_autotune_cache_dir: builtins.str | None = ..., + xla_cmd_buffer_trace_cache_size: builtins.int | None = ..., + xla_gpu_temp_buffer_use_separate_color: builtins.bool | None = ..., + legacy_command_buffer_custom_call_targets: collections.abc.Iterable[builtins.str] | None = ..., + xla_syntax_sugar_async_ops: builtins.bool | None = ..., + xla_gpu_autotune_gemm_rtol: builtins.float | None = ..., + xla_enable_command_buffers_during_profiling: builtins.bool | None = ..., + xla_gpu_cudnn_gemm_max_plans: builtins.int | None = ..., + xla_gpu_enable_libnvjitlink: builtins.bool | None = ..., + xla_gpu_enable_triton_gemm_int4: builtins.bool | None = ..., + xla_gpu_async_dot: builtins.bool | None = ..., + xla_gpu_enable_pgle_accuracy_checker: builtins.bool | None = ..., + xla_gpu_executable_warn_stuck_timeout_seconds: builtins.int | None = ..., + xla_gpu_executable_terminate_timeout_seconds: builtins.int | None = ..., + xla_experimental_ignore_channel_id: builtins.bool | None = ..., + xla_backend_extra_options: collections.abc.Mapping[builtins.str, builtins.str] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "legacy_command_buffer_custom_call_targets", + b"legacy_command_buffer_custom_call_targets", + "xla_allow_excess_precision", + b"xla_allow_excess_precision", + "xla_allow_scalar_index_dynamic_ops", + b"xla_allow_scalar_index_dynamic_ops", + "xla_backend_extra_options", + b"xla_backend_extra_options", + "xla_backend_optimization_level", + b"xla_backend_optimization_level", + "xla_cmd_buffer_trace_cache_size", + b"xla_cmd_buffer_trace_cache_size", + "xla_cpu_enable_concurrency_optimized_scheduler", + b"xla_cpu_enable_concurrency_optimized_scheduler", + "xla_cpu_enable_custom_matmul_tiling", + b"xla_cpu_enable_custom_matmul_tiling", + "xla_cpu_enable_experimental_deallocation", + b"xla_cpu_enable_experimental_deallocation", + "xla_cpu_enable_fast_math", + b"xla_cpu_enable_fast_math", + "xla_cpu_enable_fast_min_max", + b"xla_cpu_enable_fast_min_max", + "xla_cpu_enable_mlir_fusion_outlining", + b"xla_cpu_enable_mlir_fusion_outlining", + "xla_cpu_enable_mlir_tiling_and_fusion", + b"xla_cpu_enable_mlir_tiling_and_fusion", + "xla_cpu_enable_xprof_traceme", + b"xla_cpu_enable_xprof_traceme", + "xla_cpu_fast_math_honor_division", + b"xla_cpu_fast_math_honor_division", + "xla_cpu_fast_math_honor_functions", + b"xla_cpu_fast_math_honor_functions", + "xla_cpu_fast_math_honor_infs", + b"xla_cpu_fast_math_honor_infs", + "xla_cpu_fast_math_honor_nans", + b"xla_cpu_fast_math_honor_nans", + "xla_cpu_matmul_tiling_k_dim", + b"xla_cpu_matmul_tiling_k_dim", + "xla_cpu_matmul_tiling_m_dim", + b"xla_cpu_matmul_tiling_m_dim", + "xla_cpu_matmul_tiling_n_dim", + b"xla_cpu_matmul_tiling_n_dim", + "xla_cpu_multi_thread_eigen", + b"xla_cpu_multi_thread_eigen", + "xla_cpu_parallel_codegen_split_count", + b"xla_cpu_parallel_codegen_split_count", + "xla_cpu_prefer_vector_width", + b"xla_cpu_prefer_vector_width", + "xla_cpu_strict_dot_conv_math", + b"xla_cpu_strict_dot_conv_math", + "xla_cpu_use_acl", + b"xla_cpu_use_acl", + "xla_cpu_use_mkl_dnn", + b"xla_cpu_use_mkl_dnn", + "xla_cpu_use_thunk_runtime", + b"xla_cpu_use_thunk_runtime", + "xla_debug_buffer_assignment_show_max", + b"xla_debug_buffer_assignment_show_max", + "xla_detailed_logging", + b"xla_detailed_logging", + "xla_disable_all_hlo_passes", + b"xla_disable_all_hlo_passes", + "xla_disable_hlo_passes", + b"xla_disable_hlo_passes", + "xla_dump_compress_protos", + b"xla_dump_compress_protos", + "xla_dump_disable_metadata", + b"xla_dump_disable_metadata", + "xla_dump_enable_mlir_pretty_form", + b"xla_dump_enable_mlir_pretty_form", + "xla_dump_fusion_visualization", + b"xla_dump_fusion_visualization", + "xla_dump_hlo_as_dot", + b"xla_dump_hlo_as_dot", + "xla_dump_hlo_as_html", + b"xla_dump_hlo_as_html", + "xla_dump_hlo_as_long_text", + b"xla_dump_hlo_as_long_text", + "xla_dump_hlo_as_proto", + b"xla_dump_hlo_as_proto", + "xla_dump_hlo_as_text", + b"xla_dump_hlo_as_text", + "xla_dump_hlo_as_url", + b"xla_dump_hlo_as_url", + "xla_dump_hlo_module_re", + b"xla_dump_hlo_module_re", + "xla_dump_hlo_pass_re", + b"xla_dump_hlo_pass_re", + "xla_dump_hlo_pipeline_re", + b"xla_dump_hlo_pipeline_re", + "xla_dump_hlo_snapshots", + b"xla_dump_hlo_snapshots", + "xla_dump_include_timestamp", + b"xla_dump_include_timestamp", + "xla_dump_large_constants", + b"xla_dump_large_constants", + "xla_dump_latency_hiding_schedule", + b"xla_dump_latency_hiding_schedule", + "xla_dump_max_hlo_modules", + b"xla_dump_max_hlo_modules", + "xla_dump_module_metadata", + b"xla_dump_module_metadata", + "xla_dump_to", + b"xla_dump_to", + "xla_eliminate_hlo_implicit_broadcast", + b"xla_eliminate_hlo_implicit_broadcast", + "xla_embed_ir_in_executable", + b"xla_embed_ir_in_executable", + "xla_enable_command_buffers_during_profiling", + b"xla_enable_command_buffers_during_profiling", + "xla_enable_dumping", + b"xla_enable_dumping", + "xla_enable_hlo_passes_only", + b"xla_enable_hlo_passes_only", + "xla_experimental_ignore_channel_id", + b"xla_experimental_ignore_channel_id", + "xla_force_host_platform_device_count", + b"xla_force_host_platform_device_count", + "xla_gpu_algorithm_denylist_path", + b"xla_gpu_algorithm_denylist_path", + "xla_gpu_all_gather_combine_threshold_bytes", + b"xla_gpu_all_gather_combine_threshold_bytes", + "xla_gpu_all_reduce_blueconnect_num_devices_per_host", + b"xla_gpu_all_reduce_blueconnect_num_devices_per_host", + "xla_gpu_all_reduce_combine_threshold_bytes", + b"xla_gpu_all_reduce_combine_threshold_bytes", + "xla_gpu_asm_extra_flags", + b"xla_gpu_asm_extra_flags", + "xla_gpu_async_dot", + b"xla_gpu_async_dot", + "xla_gpu_auto_spmd_partitioning_memory_budget_gb", + b"xla_gpu_auto_spmd_partitioning_memory_budget_gb", + "xla_gpu_auto_spmd_partitioning_memory_budget_ratio", + b"xla_gpu_auto_spmd_partitioning_memory_budget_ratio", + "xla_gpu_autotune_gemm_rtol", + b"xla_gpu_autotune_gemm_rtol", + "xla_gpu_autotune_level", + b"xla_gpu_autotune_level", + "xla_gpu_autotune_max_solutions", + b"xla_gpu_autotune_max_solutions", + "xla_gpu_collect_cost_model_stats", + b"xla_gpu_collect_cost_model_stats", + "xla_gpu_collective_inflation_factor", + b"xla_gpu_collective_inflation_factor", + "xla_gpu_collective_permute_decomposer_threshold", + b"xla_gpu_collective_permute_decomposer_threshold", + "xla_gpu_copy_insertion_use_region_analysis", + b"xla_gpu_copy_insertion_use_region_analysis", + "xla_gpu_crash_on_verification_failures", + b"xla_gpu_crash_on_verification_failures", + "xla_gpu_cublas_fallback", + b"xla_gpu_cublas_fallback", + "xla_gpu_cuda_data_dir", + b"xla_gpu_cuda_data_dir", + "xla_gpu_cudnn_gemm_fusion_level", + b"xla_gpu_cudnn_gemm_fusion_level", + "xla_gpu_cudnn_gemm_max_plans", + b"xla_gpu_cudnn_gemm_max_plans", + "xla_gpu_deterministic_ops", + b"xla_gpu_deterministic_ops", + "xla_gpu_disable_async_collectives", + b"xla_gpu_disable_async_collectives", + "xla_gpu_disable_gpuasm_optimizations", + b"xla_gpu_disable_gpuasm_optimizations", + "xla_gpu_dump_autotune_logs_to", + b"xla_gpu_dump_autotune_logs_to", + "xla_gpu_dump_autotune_results_to", + b"xla_gpu_dump_autotune_results_to", + "xla_gpu_dump_autotuned_gemm_fusions", + b"xla_gpu_dump_autotuned_gemm_fusions", + "xla_gpu_dump_llvmir", + b"xla_gpu_dump_llvmir", + "xla_gpu_enable_all_gather_combine_by_dim", + b"xla_gpu_enable_all_gather_combine_by_dim", + "xla_gpu_enable_analytical_latency_estimator", + b"xla_gpu_enable_analytical_latency_estimator", + "xla_gpu_enable_approx_costly_collectives", + b"xla_gpu_enable_approx_costly_collectives", + "xla_gpu_enable_bf16_3way_gemm", + b"xla_gpu_enable_bf16_3way_gemm", + "xla_gpu_enable_bf16_6way_gemm", + b"xla_gpu_enable_bf16_6way_gemm", + "xla_gpu_enable_command_buffer", + b"xla_gpu_enable_command_buffer", + "xla_gpu_enable_cub_radix_sort", + b"xla_gpu_enable_cub_radix_sort", + "xla_gpu_enable_cublaslt", + b"xla_gpu_enable_cublaslt", + "xla_gpu_enable_cudnn_fmha", + b"xla_gpu_enable_cudnn_fmha", + "xla_gpu_enable_cudnn_frontend", + b"xla_gpu_enable_cudnn_frontend", + "xla_gpu_enable_cudnn_int8x32_convolution_reordering", + b"xla_gpu_enable_cudnn_int8x32_convolution_reordering", + "xla_gpu_enable_cudnn_layer_norm", + b"xla_gpu_enable_cudnn_layer_norm", + "xla_gpu_enable_custom_fusions", + b"xla_gpu_enable_custom_fusions", + "xla_gpu_enable_custom_fusions_re", + b"xla_gpu_enable_custom_fusions_re", + "xla_gpu_enable_dot_strength_reduction", + b"xla_gpu_enable_dot_strength_reduction", + "xla_gpu_enable_dynamic_slice_fusion", + b"xla_gpu_enable_dynamic_slice_fusion", + "xla_gpu_enable_fast_min_max", + b"xla_gpu_enable_fast_min_max", + "xla_gpu_enable_highest_priority_async_stream", + b"xla_gpu_enable_highest_priority_async_stream", + "xla_gpu_enable_host_memory_offloading", + b"xla_gpu_enable_host_memory_offloading", + "xla_gpu_enable_latency_hiding_scheduler", + b"xla_gpu_enable_latency_hiding_scheduler", + "xla_gpu_enable_libnvjitlink", + b"xla_gpu_enable_libnvjitlink", + "xla_gpu_enable_libnvptxcompiler", + b"xla_gpu_enable_libnvptxcompiler", + "xla_gpu_enable_llvm_module_compilation_parallelism", + b"xla_gpu_enable_llvm_module_compilation_parallelism", + "xla_gpu_enable_nccl_clique_optimization", + b"xla_gpu_enable_nccl_clique_optimization", + "xla_gpu_enable_nccl_comm_splitting", + b"xla_gpu_enable_nccl_comm_splitting", + "xla_gpu_enable_nccl_per_stream_comms", + b"xla_gpu_enable_nccl_per_stream_comms", + "xla_gpu_enable_nccl_user_buffers", + b"xla_gpu_enable_nccl_user_buffers", + "xla_gpu_enable_pgle_accuracy_checker", + b"xla_gpu_enable_pgle_accuracy_checker", + "xla_gpu_enable_pipelined_all_gather", + b"xla_gpu_enable_pipelined_all_gather", + "xla_gpu_enable_pipelined_all_reduce", + b"xla_gpu_enable_pipelined_all_reduce", + "xla_gpu_enable_pipelined_collectives", + b"xla_gpu_enable_pipelined_collectives", + "xla_gpu_enable_pipelined_p2p", + b"xla_gpu_enable_pipelined_p2p", + "xla_gpu_enable_pipelined_reduce_scatter", + b"xla_gpu_enable_pipelined_reduce_scatter", + "xla_gpu_enable_priority_fusion", + b"xla_gpu_enable_priority_fusion", + "xla_gpu_enable_reassociation_for_converted_ar", + b"xla_gpu_enable_reassociation_for_converted_ar", + "xla_gpu_enable_reduce_scatter_combine_by_dim", + b"xla_gpu_enable_reduce_scatter_combine_by_dim", + "xla_gpu_enable_reduction_epilogue_fusion", + b"xla_gpu_enable_reduction_epilogue_fusion", + "xla_gpu_enable_shared_constants", + b"xla_gpu_enable_shared_constants", + "xla_gpu_enable_split_k_autotuning", + b"xla_gpu_enable_split_k_autotuning", + "xla_gpu_enable_triton_gemm", + b"xla_gpu_enable_triton_gemm", + "xla_gpu_enable_triton_gemm_int4", + b"xla_gpu_enable_triton_gemm_int4", + "xla_gpu_enable_triton_hopper", + b"xla_gpu_enable_triton_hopper", + "xla_gpu_enable_while_loop_double_buffering", + b"xla_gpu_enable_while_loop_double_buffering", + "xla_gpu_enable_while_loop_reduce_scatter_code_motion", + b"xla_gpu_enable_while_loop_reduce_scatter_code_motion", + "xla_gpu_enable_while_loop_unrolling", + b"xla_gpu_enable_while_loop_unrolling", + "xla_gpu_ensure_minor_dot_contraction_dims", + b"xla_gpu_ensure_minor_dot_contraction_dims", + "xla_gpu_exclude_nondeterministic_ops", + b"xla_gpu_exclude_nondeterministic_ops", + "xla_gpu_executable_terminate_timeout_seconds", + b"xla_gpu_executable_terminate_timeout_seconds", + "xla_gpu_executable_warn_stuck_timeout_seconds", + b"xla_gpu_executable_warn_stuck_timeout_seconds", + "xla_gpu_exhaustive_tiling_search", + b"xla_gpu_exhaustive_tiling_search", + "xla_gpu_experimental_autotune_cache_mode", + b"xla_gpu_experimental_autotune_cache_mode", + "xla_gpu_experimental_disable_binary_libraries", + b"xla_gpu_experimental_disable_binary_libraries", + "xla_gpu_experimental_enable_triton_softmax_priority_fusion", + b"xla_gpu_experimental_enable_triton_softmax_priority_fusion", + "xla_gpu_filter_kernels_spilling_registers_on_autotuning", + b"xla_gpu_filter_kernels_spilling_registers_on_autotuning", + "xla_gpu_force_compilation_parallelism", + b"xla_gpu_force_compilation_parallelism", + "xla_gpu_force_conv_nchw", + b"xla_gpu_force_conv_nchw", + "xla_gpu_force_conv_nhwc", + b"xla_gpu_force_conv_nhwc", + "xla_gpu_ftz", + b"xla_gpu_ftz", + "xla_gpu_fused_attention_use_cudnn_rng", + b"xla_gpu_fused_attention_use_cudnn_rng", + "xla_gpu_gemm_rewrite_size_threshold", + b"xla_gpu_gemm_rewrite_size_threshold", + "xla_gpu_graph_enable_concurrent_region", + b"xla_gpu_graph_enable_concurrent_region", + "xla_gpu_graph_min_graph_size", + b"xla_gpu_graph_min_graph_size", + "xla_gpu_kernel_cache_file", + b"xla_gpu_kernel_cache_file", + "xla_gpu_lhs_enable_gpu_async_tracker", + b"xla_gpu_lhs_enable_gpu_async_tracker", + "xla_gpu_llvm_ir_file", + b"xla_gpu_llvm_ir_file", + "xla_gpu_llvm_verification_level", + b"xla_gpu_llvm_verification_level", + "xla_gpu_load_autotune_results_from", + b"xla_gpu_load_autotune_results_from", + "xla_gpu_memory_limit_slop_factor", + b"xla_gpu_memory_limit_slop_factor", + "xla_gpu_mlir_emitter_level", + b"xla_gpu_mlir_emitter_level", + "xla_gpu_mock_custom_calls", + b"xla_gpu_mock_custom_calls", + "xla_gpu_multi_streamed_windowed_einsum", + b"xla_gpu_multi_streamed_windowed_einsum", + "xla_gpu_nccl_collective_max_nchannels", + b"xla_gpu_nccl_collective_max_nchannels", + "xla_gpu_nccl_p2p_max_nchannels", + b"xla_gpu_nccl_p2p_max_nchannels", + "xla_gpu_nccl_terminate_on_error", + b"xla_gpu_nccl_terminate_on_error", + "xla_gpu_nccl_termination_timeout_seconds", + b"xla_gpu_nccl_termination_timeout_seconds", + "xla_gpu_override_gemm_autotuner", + b"xla_gpu_override_gemm_autotuner", + "xla_gpu_per_fusion_autotune_cache_dir", + b"xla_gpu_per_fusion_autotune_cache_dir", + "xla_gpu_pgle_profile_file_or_directory_path", + b"xla_gpu_pgle_profile_file_or_directory_path", + "xla_gpu_ptx_file", + b"xla_gpu_ptx_file", + "xla_gpu_reduce_scatter_combine_threshold_bytes", + b"xla_gpu_reduce_scatter_combine_threshold_bytes", + "xla_gpu_redzone_padding_bytes", + b"xla_gpu_redzone_padding_bytes", + "xla_gpu_redzone_scratch_max_megabytes", + b"xla_gpu_redzone_scratch_max_megabytes", + "xla_gpu_require_complete_aot_autotune_results", + b"xla_gpu_require_complete_aot_autotune_results", + "xla_gpu_run_post_layout_collective_pipeliner", + b"xla_gpu_run_post_layout_collective_pipeliner", + "xla_gpu_shape_checks", + b"xla_gpu_shape_checks", + "xla_gpu_shard_autotuning", + b"xla_gpu_shard_autotuning", + "xla_gpu_strict_conv_algorithm_picker", + b"xla_gpu_strict_conv_algorithm_picker", + "xla_gpu_target_config_filename", + b"xla_gpu_target_config_filename", + "xla_gpu_temp_buffer_use_separate_color", + b"xla_gpu_temp_buffer_use_separate_color", + "xla_gpu_threshold_for_windowed_einsum_mib", + b"xla_gpu_threshold_for_windowed_einsum_mib", + "xla_gpu_triton_fusion_level", + b"xla_gpu_triton_fusion_level", + "xla_gpu_triton_gemm_any", + b"xla_gpu_triton_gemm_any", + "xla_gpu_triton_gemm_disable_reduced_precision_reduction", + b"xla_gpu_triton_gemm_disable_reduced_precision_reduction", + "xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found", + b"xla_gpu_unsafe_fallback_to_driver_on_ptxas_not_found", + "xla_gpu_unsafe_pipelined_loop_annotator", + b"xla_gpu_unsafe_pipelined_loop_annotator", + "xla_gpu_unsupported_enable_triton_gemm", + b"xla_gpu_unsupported_enable_triton_gemm", + "xla_gpu_use_memcpy_local_p2p", + b"xla_gpu_use_memcpy_local_p2p", + "xla_gpu_use_runtime_fusion", + b"xla_gpu_use_runtime_fusion", + "xla_gpu_verify_triton_fusion_numerics", + b"xla_gpu_verify_triton_fusion_numerics", + "xla_hlo_evaluator_use_fast_path", + b"xla_hlo_evaluator_use_fast_path", + "xla_hlo_graph_addresses", + b"xla_hlo_graph_addresses", + "xla_hlo_graph_sharding_color", + b"xla_hlo_graph_sharding_color", + "xla_hlo_profile", + b"xla_hlo_profile", + "xla_llvm_disable_expensive_passes", + b"xla_llvm_disable_expensive_passes", + "xla_llvm_enable_alias_scope_metadata", + b"xla_llvm_enable_alias_scope_metadata", + "xla_llvm_enable_invariant_load_metadata", + b"xla_llvm_enable_invariant_load_metadata", + "xla_llvm_enable_noalias_metadata", + b"xla_llvm_enable_noalias_metadata", + "xla_llvm_force_inline_before_split", + b"xla_llvm_force_inline_before_split", + "xla_multiheap_size_constraint_per_heap", + b"xla_multiheap_size_constraint_per_heap", + "xla_partitioning_algorithm", + b"xla_partitioning_algorithm", + "xla_reduce_window_rewrite_base_length", + b"xla_reduce_window_rewrite_base_length", + "xla_step_marker_location", + b"xla_step_marker_location", + "xla_syntax_sugar_async_ops", + b"xla_syntax_sugar_async_ops", + "xla_test_all_input_layouts", + b"xla_test_all_input_layouts", + "xla_test_all_output_layouts", + b"xla_test_all_output_layouts", + "xla_tpu_detect_inf", + b"xla_tpu_detect_inf", + "xla_tpu_detect_nan", + b"xla_tpu_detect_nan", + ], + ) -> None: ... + +global___DebugOptions = DebugOptions + +@typing.final +class GpuCompilationEnvironment(google.protobuf.message.Message): + """Contains flags which affects the GPU compilation result. + These flags are part of Debug Options as of now, and will be migrated to + this proto. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DUMMY_FLAG_FIELD_NUMBER: builtins.int + dummy_flag: builtins.int + """Temporary dummy flag is added to test the flow. + To be removed when we add flags here. + """ + def __init__(self, *, dummy_flag: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["dummy_flag", b"dummy_flag"]) -> None: ... + +global___GpuCompilationEnvironment = GpuCompilationEnvironment + +@typing.final +class ShardableValueUpdatePairProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_PARAMETER_NUMBER_FIELD_NUMBER: builtins.int + PARAMETER_SHAPE_INDEX_FIELD_NUMBER: builtins.int + OUTPUT_SHAPE_INDEX_FIELD_NUMBER: builtins.int + input_parameter_number: builtins.int + @property + def parameter_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def output_shape_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + input_parameter_number: builtins.int | None = ..., + parameter_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + output_shape_index: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_parameter_number", + b"input_parameter_number", + "output_shape_index", + b"output_shape_index", + "parameter_shape_index", + b"parameter_shape_index", + ], + ) -> None: ... + +global___ShardableValueUpdatePairProto = ShardableValueUpdatePairProto + +@typing.final +class ExecutionOptions(google.protobuf.message.Message): + """These settings control how XLA compiles and/or runs code. Not all settings + will have an effect on every platform. + + When adding new fields, keep in mind that boolean fields default to false. + Next id: 25. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_WITH_OUTPUT_LAYOUT_FIELD_NUMBER: builtins.int + SEED_FIELD_NUMBER: builtins.int + DEBUG_OPTIONS_FIELD_NUMBER: builtins.int + DEVICE_HANDLES_FIELD_NUMBER: builtins.int + NUM_REPLICAS_FIELD_NUMBER: builtins.int + DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + ALIAS_PASSTHROUGH_PARAMS_FIELD_NUMBER: builtins.int + NUM_PARTITIONS_FIELD_NUMBER: builtins.int + LAUNCH_ID_FIELD_NUMBER: builtins.int + USE_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_SHAPE_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_IDS_FIELD_NUMBER: builtins.int + DEDUPLICATE_HLO_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_PARAMETERS_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_OUTPUT_FIELD_NUMBER: builtins.int + PARAM_REQUIRES_BROADCAST_VIA_COLLECTIVES_FIELD_NUMBER: builtins.int + ALLOW_SEPARATE_SHARDING_PROGRAMS_FIELD_NUMBER: builtins.int + SHARDABLE_VALUE_UPDATE_PAIRS_FIELD_NUMBER: builtins.int + FDO_PROFILE_FIELD_NUMBER: builtins.int + DEVICE_MEMORY_SIZE_FIELD_NUMBER: builtins.int + USE_SHARDY_PARTITIONER_FIELD_NUMBER: builtins.int + seed: builtins.int + """Used to seed random-number generators used in this computation. If this is + 0, we generate a seed ourselves. + + TODO(b/32083678): Changing the seed unnecessarily forces a recompilation. + """ + num_replicas: builtins.int + """Number of replicas of the computation to run. If zero, uses the default + number of replicas for the XLA service. + """ + alias_passthrough_params: builtins.bool + """Alias input and output buffers for parameters that are passed-through XLA + modules without being changed. + """ + num_partitions: builtins.int + """Number of partitions of the computation to run (model parallelism). + If zero, uses the default number of partitions for the XLA service. + """ + launch_id: builtins.int + """Used to identify a set of programs that should be launch together.""" + use_spmd_partitioning: builtins.bool + """Indicates whether to use SPMD (true) or MPMD (false) partitioning when + num_partitions > 1 and XLA is requested to partition the input program. + """ + use_auto_spmd_partitioning: builtins.bool + """Whether to automatically generate XLA shardings for SPMD partitioner.""" + deduplicate_hlo: builtins.bool + """If set, deduplicate hlo into function calls to reduce binary size. Only + works on TPU. + """ + allow_separate_sharding_programs: builtins.bool + """If enabled, the compiler may generate sharding and unsharding programs as + separate HLO modules, and modify the main program's input and output to + be sharded. + """ + fdo_profile: builtins.bytes + """Profiling data for feedback directed optimizations. Note that this is not + the only way to feed FDO data into the compiler and individual backends + may choose to get FDO data by other means. + """ + device_memory_size: builtins.int + """Amount of device memory available for the executable to use.""" + use_shardy_partitioner: builtins.bool + """Use Shardy, a new partitioner, to replace the existing + ShardingPropagation and SpmdPartitioner. See go/xla-sdy-pipeline for + details. + """ + @property + def shape_with_output_layout(self) -> tensorflow.compiler.xla.xla_data_pb2.ShapeProto: + """This optional field's layout is used as a hint when storing the output of + this computation. Subsequent transfers of this output array to the client + may be faster when using this layout. + + We use a Shape here to accommodate computations that return a tuple. + """ + + @property + def debug_options(self) -> global___DebugOptions: ... + @property + def device_handles( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[tensorflow.compiler.xla.xla_data_pb2.DeviceHandle]: + """This optional field specifies a particular set of devices to run the + computation on. The computation will be partitioned across these devices. + If not provided, the default device will be chosen. + """ + + @property + def device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """This optional field specifies the device assignment if known at compile + time. + """ + + @property + def auto_spmd_partitioning_mesh_shape(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Device mesh shape used to create the sharding search space when + use_auto_spmd_partitioning=true. + """ + + @property + def auto_spmd_partitioning_mesh_ids(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Device mesh ids compatible with the above mesh_shape used when + use_auto_spmd_partitioning=true. + """ + + @property + def allow_spmd_sharding_propagation_to_parameters( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Allows sharding propagation to propagate to the parameters. This changes + the input shape of the computation (which is undesirable), but it can be + used to allow to run partial compilation to determine what would be the + input sharding of a computation if XLA would be allowed to propagate the + sharding which can be used by higher level framework as a way to query + intermediate sharding of operations when multiple computation would be + chained and merged together. + This is a vector of bool, because the user can control which parameters can + have the sharding substituted. If only one boolean value is passed in the + vector that is interpreted as the value to be applied for every parameter. + """ + + @property + def allow_spmd_sharding_propagation_to_output( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Allows sharding propagation to propagate to the outputs. This changes the + output shape of the computation (which is undesirable), but it can be used + to allow to run partial compilation to determine what would be the output + sharding of a computation if XLA would be allowed to propagate the sharding + which can be used by higher level framework as a way to query intermediate + sharding of operations when multiple computation would be chained and + merged together. + This is a vector of bool, because the user can control (if the output of + the computation is a tuple) which elements of the tuple can have the + sharding substituted and which don't. If only one boolean value is passed + in the vector that's interpreted as the value to be applied for every + single element of the output tuple. One value per element of the tuple + means that each value is attached to one of the output elements. + """ + + @property + def param_requires_broadcast_via_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """Whether to broadcast args across all replicas. One entry per arg.""" + + @property + def shardable_value_update_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShardableValueUpdatePairProto]: + """The list of input/output pairs in the main program that could be sharded.""" + + def __init__( + self, + *, + shape_with_output_layout: tensorflow.compiler.xla.xla_data_pb2.ShapeProto | None = ..., + seed: builtins.int | None = ..., + debug_options: global___DebugOptions | None = ..., + device_handles: collections.abc.Iterable[tensorflow.compiler.xla.xla_data_pb2.DeviceHandle] | None = ..., + num_replicas: builtins.int | None = ..., + device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + alias_passthrough_params: builtins.bool | None = ..., + num_partitions: builtins.int | None = ..., + launch_id: builtins.int | None = ..., + use_spmd_partitioning: builtins.bool | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + auto_spmd_partitioning_mesh_shape: collections.abc.Iterable[builtins.int] | None = ..., + auto_spmd_partitioning_mesh_ids: collections.abc.Iterable[builtins.int] | None = ..., + deduplicate_hlo: builtins.bool | None = ..., + allow_spmd_sharding_propagation_to_parameters: collections.abc.Iterable[builtins.bool] | None = ..., + allow_spmd_sharding_propagation_to_output: collections.abc.Iterable[builtins.bool] | None = ..., + param_requires_broadcast_via_collectives: collections.abc.Iterable[builtins.bool] | None = ..., + allow_separate_sharding_programs: builtins.bool | None = ..., + shardable_value_update_pairs: collections.abc.Iterable[global___ShardableValueUpdatePairProto] | None = ..., + fdo_profile: builtins.bytes | None = ..., + device_memory_size: builtins.int | None = ..., + use_shardy_partitioner: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_options", + b"debug_options", + "device_assignment", + b"device_assignment", + "shape_with_output_layout", + b"shape_with_output_layout", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_passthrough_params", + b"alias_passthrough_params", + "allow_separate_sharding_programs", + b"allow_separate_sharding_programs", + "allow_spmd_sharding_propagation_to_output", + b"allow_spmd_sharding_propagation_to_output", + "allow_spmd_sharding_propagation_to_parameters", + b"allow_spmd_sharding_propagation_to_parameters", + "auto_spmd_partitioning_mesh_ids", + b"auto_spmd_partitioning_mesh_ids", + "auto_spmd_partitioning_mesh_shape", + b"auto_spmd_partitioning_mesh_shape", + "debug_options", + b"debug_options", + "deduplicate_hlo", + b"deduplicate_hlo", + "device_assignment", + b"device_assignment", + "device_handles", + b"device_handles", + "device_memory_size", + b"device_memory_size", + "fdo_profile", + b"fdo_profile", + "launch_id", + b"launch_id", + "num_partitions", + b"num_partitions", + "num_replicas", + b"num_replicas", + "param_requires_broadcast_via_collectives", + b"param_requires_broadcast_via_collectives", + "seed", + b"seed", + "shape_with_output_layout", + b"shape_with_output_layout", + "shardable_value_update_pairs", + b"shardable_value_update_pairs", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + "use_shardy_partitioner", + b"use_shardy_partitioner", + "use_spmd_partitioning", + b"use_spmd_partitioning", + ], + ) -> None: ... + +global___ExecutionOptions = ExecutionOptions + +@typing.final +class HloModuleConfigProto(google.protobuf.message.Message): + """Serialization of HloModuleConfig. See the C++ class definition for + descriptions of each field. + There are no guarantees of backwards or forwards compatibility. + Next id: 36. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _FusionConfigCollection: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _FusionConfigCollectionEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[HloModuleConfigProto._FusionConfigCollection.ValueType], + builtins.type, + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + OFF: HloModuleConfigProto._FusionConfigCollection.ValueType # 0 + """Do not collect configuration.""" + PER_EDGE: HloModuleConfigProto._FusionConfigCollection.ValueType # 1 + """Collect per-edge configuration.""" + PER_NODE: HloModuleConfigProto._FusionConfigCollection.ValueType # 2 + """Collect per-node configuration.""" + + class FusionConfigCollection(_FusionConfigCollection, metaclass=_FusionConfigCollectionEnumTypeWrapper): ... + OFF: HloModuleConfigProto.FusionConfigCollection.ValueType # 0 + """Do not collect configuration.""" + PER_EDGE: HloModuleConfigProto.FusionConfigCollection.ValueType # 1 + """Collect per-edge configuration.""" + PER_NODE: HloModuleConfigProto.FusionConfigCollection.ValueType # 2 + """Collect per-node configuration.""" + + @typing.final + class BoolList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALS_FIELD_NUMBER: builtins.int + @property + def vals(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + def __init__(self, *, vals: collections.abc.Iterable[builtins.bool] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["vals", b"vals"]) -> None: ... + + @typing.final + class Int64List(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALS_FIELD_NUMBER: builtins.int + @property + def vals(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, vals: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["vals", b"vals"]) -> None: ... + + @typing.final + class Int64ListList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LISTS_FIELD_NUMBER: builtins.int + @property + def lists( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.Int64List]: ... + def __init__(self, *, lists: collections.abc.Iterable[global___HloModuleConfigProto.Int64List] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["lists", b"lists"]) -> None: ... + + @typing.final + class DotConfigEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___HloModuleConfigProto.Int64List: ... + def __init__( + self, *, key: builtins.str | None = ..., value: global___HloModuleConfigProto.Int64List | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + @typing.final + class AnalysisAllowanceMapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + value: builtins.int + def __init__(self, *, key: builtins.str | None = ..., value: builtins.int | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + ENTRY_COMPUTATION_LAYOUT_FIELD_NUMBER: builtins.int + SEED_FIELD_NUMBER: builtins.int + LAUNCH_ID_FIELD_NUMBER: builtins.int + REPLICA_COUNT_FIELD_NUMBER: builtins.int + NUM_PARTITIONS_FIELD_NUMBER: builtins.int + PARAM_REQUIRES_BROADCAST_VIA_COLLECTIVES_FIELD_NUMBER: builtins.int + USE_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + USE_AUTO_SPMD_PARTITIONING_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_SHAPE_FIELD_NUMBER: builtins.int + AUTO_SPMD_PARTITIONING_MESH_IDS_FIELD_NUMBER: builtins.int + DEDUPLICATE_HLO_FIELD_NUMBER: builtins.int + INTRA_OP_PARALLELISM_THREADS_FIELD_NUMBER: builtins.int + DEVICE_TYPE_FIELD_NUMBER: builtins.int + DEBUG_OPTIONS_FIELD_NUMBER: builtins.int + STATIC_DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + PRE_SIMULATION_DEVICE_ASSIGNMENT_FIELD_NUMBER: builtins.int + ALLOW_SEPARATE_SHARDING_PROGRAMS_FIELD_NUMBER: builtins.int + SHARDABLE_VALUE_UPDATE_PAIRS_FIELD_NUMBER: builtins.int + ALIAS_PASSTHROUGH_PARAMS_FIELD_NUMBER: builtins.int + CONTENT_AWARE_COMPUTATION_SORTING_FIELD_NUMBER: builtins.int + FUSION_CONFIG_COLLECTION_FIELD_NUMBER: builtins.int + FUSION_CONFIG_FIELD_NUMBER: builtins.int + DOT_CONFIG_FIELD_NUMBER: builtins.int + LAYOUT_CONFIG_FIELD_NUMBER: builtins.int + MEMORY_SPACE_ASSIGNMENT_CONFIG_FIELD_NUMBER: builtins.int + PHASE_ORDERING_CONFIG_FIELD_NUMBER: builtins.int + PHASE_INDEX_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_PARAMETERS_FIELD_NUMBER: builtins.int + ALLOW_SPMD_SHARDING_PROPAGATION_TO_OUTPUT_FIELD_NUMBER: builtins.int + ANALYSIS_ALLOWANCE_MAP_FIELD_NUMBER: builtins.int + MATRIX_UNIT_OPERAND_PRECISION_FIELD_NUMBER: builtins.int + FDO_PROFILE_FIELD_NUMBER: builtins.int + DEVICE_MEMORY_SIZE_FIELD_NUMBER: builtins.int + USE_SHARDY_PARTITIONER_FIELD_NUMBER: builtins.int + seed: builtins.int + launch_id: builtins.int + replica_count: builtins.int + num_partitions: builtins.int + use_spmd_partitioning: builtins.bool + use_auto_spmd_partitioning: builtins.bool + deduplicate_hlo: builtins.bool + intra_op_parallelism_threads: builtins.int + device_type: builtins.str + allow_separate_sharding_programs: builtins.bool + alias_passthrough_params: builtins.bool + content_aware_computation_sorting: builtins.bool + fusion_config_collection: global___HloModuleConfigProto.FusionConfigCollection.ValueType + phase_index: builtins.int + matrix_unit_operand_precision: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig.Precision.ValueType + fdo_profile: builtins.bytes + device_memory_size: builtins.int + use_shardy_partitioner: builtins.bool + @property + def entry_computation_layout(self) -> tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto: ... + @property + def param_requires_broadcast_via_collectives( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def auto_spmd_partitioning_mesh_shape( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def auto_spmd_partitioning_mesh_ids( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def debug_options(self) -> global___DebugOptions: ... + @property + def static_device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: ... + @property + def pre_simulation_device_assignment(self) -> tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto: + """The original device assignment before being changed by a simulator. + Simulators, like HybridSim, may change the device assignment to a smaller + topology, to make simulation easier. + """ + + @property + def shardable_value_update_pairs( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ShardableValueUpdatePairProto]: ... + @property + def fusion_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.BoolList]: ... + @property + def dot_config( + self, + ) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___HloModuleConfigProto.Int64List]: ... + @property + def layout_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.Int64ListList]: ... + @property + def memory_space_assignment_config( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def phase_ordering_config( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___HloModuleConfigProto.BoolList]: ... + @property + def allow_spmd_sharding_propagation_to_parameters( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def allow_spmd_sharding_propagation_to_output( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: ... + @property + def analysis_allowance_map(self) -> google.protobuf.internal.containers.ScalarMap[builtins.str, builtins.int]: ... + def __init__( + self, + *, + entry_computation_layout: tensorflow.compiler.xla.xla_data_pb2.ProgramShapeProto | None = ..., + seed: builtins.int | None = ..., + launch_id: builtins.int | None = ..., + replica_count: builtins.int | None = ..., + num_partitions: builtins.int | None = ..., + param_requires_broadcast_via_collectives: collections.abc.Iterable[builtins.bool] | None = ..., + use_spmd_partitioning: builtins.bool | None = ..., + use_auto_spmd_partitioning: builtins.bool | None = ..., + auto_spmd_partitioning_mesh_shape: collections.abc.Iterable[builtins.int] | None = ..., + auto_spmd_partitioning_mesh_ids: collections.abc.Iterable[builtins.int] | None = ..., + deduplicate_hlo: builtins.bool | None = ..., + intra_op_parallelism_threads: builtins.int | None = ..., + device_type: builtins.str | None = ..., + debug_options: global___DebugOptions | None = ..., + static_device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + pre_simulation_device_assignment: tensorflow.compiler.xla.xla_data_pb2.DeviceAssignmentProto | None = ..., + allow_separate_sharding_programs: builtins.bool | None = ..., + shardable_value_update_pairs: collections.abc.Iterable[global___ShardableValueUpdatePairProto] | None = ..., + alias_passthrough_params: builtins.bool | None = ..., + content_aware_computation_sorting: builtins.bool | None = ..., + fusion_config_collection: global___HloModuleConfigProto.FusionConfigCollection.ValueType | None = ..., + fusion_config: collections.abc.Iterable[global___HloModuleConfigProto.BoolList] | None = ..., + dot_config: collections.abc.Mapping[builtins.str, global___HloModuleConfigProto.Int64List] | None = ..., + layout_config: collections.abc.Iterable[global___HloModuleConfigProto.Int64ListList] | None = ..., + memory_space_assignment_config: collections.abc.Iterable[builtins.int] | None = ..., + phase_ordering_config: collections.abc.Iterable[global___HloModuleConfigProto.BoolList] | None = ..., + phase_index: builtins.int | None = ..., + allow_spmd_sharding_propagation_to_parameters: collections.abc.Iterable[builtins.bool] | None = ..., + allow_spmd_sharding_propagation_to_output: collections.abc.Iterable[builtins.bool] | None = ..., + analysis_allowance_map: collections.abc.Mapping[builtins.str, builtins.int] | None = ..., + matrix_unit_operand_precision: tensorflow.compiler.xla.xla_data_pb2.PrecisionConfig.Precision.ValueType | None = ..., + fdo_profile: builtins.bytes | None = ..., + device_memory_size: builtins.int | None = ..., + use_shardy_partitioner: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "debug_options", + b"debug_options", + "entry_computation_layout", + b"entry_computation_layout", + "pre_simulation_device_assignment", + b"pre_simulation_device_assignment", + "static_device_assignment", + b"static_device_assignment", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_passthrough_params", + b"alias_passthrough_params", + "allow_separate_sharding_programs", + b"allow_separate_sharding_programs", + "allow_spmd_sharding_propagation_to_output", + b"allow_spmd_sharding_propagation_to_output", + "allow_spmd_sharding_propagation_to_parameters", + b"allow_spmd_sharding_propagation_to_parameters", + "analysis_allowance_map", + b"analysis_allowance_map", + "auto_spmd_partitioning_mesh_ids", + b"auto_spmd_partitioning_mesh_ids", + "auto_spmd_partitioning_mesh_shape", + b"auto_spmd_partitioning_mesh_shape", + "content_aware_computation_sorting", + b"content_aware_computation_sorting", + "debug_options", + b"debug_options", + "deduplicate_hlo", + b"deduplicate_hlo", + "device_memory_size", + b"device_memory_size", + "device_type", + b"device_type", + "dot_config", + b"dot_config", + "entry_computation_layout", + b"entry_computation_layout", + "fdo_profile", + b"fdo_profile", + "fusion_config", + b"fusion_config", + "fusion_config_collection", + b"fusion_config_collection", + "intra_op_parallelism_threads", + b"intra_op_parallelism_threads", + "launch_id", + b"launch_id", + "layout_config", + b"layout_config", + "matrix_unit_operand_precision", + b"matrix_unit_operand_precision", + "memory_space_assignment_config", + b"memory_space_assignment_config", + "num_partitions", + b"num_partitions", + "param_requires_broadcast_via_collectives", + b"param_requires_broadcast_via_collectives", + "phase_index", + b"phase_index", + "phase_ordering_config", + b"phase_ordering_config", + "pre_simulation_device_assignment", + b"pre_simulation_device_assignment", + "replica_count", + b"replica_count", + "seed", + b"seed", + "shardable_value_update_pairs", + b"shardable_value_update_pairs", + "static_device_assignment", + b"static_device_assignment", + "use_auto_spmd_partitioning", + b"use_auto_spmd_partitioning", + "use_shardy_partitioner", + b"use_shardy_partitioner", + "use_spmd_partitioning", + b"use_spmd_partitioning", + ], + ) -> None: ... + +global___HloModuleConfigProto = HloModuleConfigProto + +@typing.final +class HloModuleProtoWithConfig(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + HLO_MODULE_FIELD_NUMBER: builtins.int + CONFIG_FIELD_NUMBER: builtins.int + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: ... + @property + def config(self) -> global___HloModuleConfigProto: ... + def __init__( + self, + *, + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + config: global___HloModuleConfigProto | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["config", b"config", "hlo_module", b"hlo_module"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["config", b"config", "hlo_module", b"hlo_module"]) -> None: ... + +global___HloModuleProtoWithConfig = HloModuleProtoWithConfig + +@typing.final +class ScheduleProto(google.protobuf.message.Message): + """A trace estimated by the Latency Hiding Scheduler.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Instruction(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ID_FIELD_NUMBER: builtins.int + START_TIMESTAMP_CYCLES_FIELD_NUMBER: builtins.int + END_TIMESTAMP_CYCLES_FIELD_NUMBER: builtins.int + id: builtins.int + """Instruction id (matches the id in HloInstructionProto).""" + start_timestamp_cycles: builtins.float + """Start and end timestamps in cycles.""" + end_timestamp_cycles: builtins.float + def __init__( + self, + *, + id: builtins.int | None = ..., + start_timestamp_cycles: builtins.float | None = ..., + end_timestamp_cycles: builtins.float | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "end_timestamp_cycles", b"end_timestamp_cycles", "id", b"id", "start_timestamp_cycles", b"start_timestamp_cycles" + ], + ) -> None: ... + + INSTRUCTIONS_FIELD_NUMBER: builtins.int + COMPUTATION_ID_FIELD_NUMBER: builtins.int + HLO_MODULE_FIELD_NUMBER: builtins.int + CYCLES_PER_MICROSECOND_FIELD_NUMBER: builtins.int + computation_id: builtins.int + """Computation id (matches the id in HloComputationProto).""" + cycles_per_microsecond: builtins.int + @property + def instructions( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ScheduleProto.Instruction]: ... + @property + def hlo_module(self) -> tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto: ... + def __init__( + self, + *, + instructions: collections.abc.Iterable[global___ScheduleProto.Instruction] | None = ..., + computation_id: builtins.int | None = ..., + hlo_module: tensorflow.compiler.xla.service.hlo_pb2.HloModuleProto | None = ..., + cycles_per_microsecond: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["hlo_module", b"hlo_module"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "computation_id", + b"computation_id", + "cycles_per_microsecond", + b"cycles_per_microsecond", + "hlo_module", + b"hlo_module", + "instructions", + b"instructions", + ], + ) -> None: ... + +global___ScheduleProto = ScheduleProto diff --git a/stubs/tensorflow/tensorflow/config/__init__.pyi b/stubs/tensorflow/tensorflow/config/__init__.pyi new file mode 100644 index 000000000000..1eb72d000ff9 --- /dev/null +++ b/stubs/tensorflow/tensorflow/config/__init__.pyi @@ -0,0 +1,12 @@ +from typing import NamedTuple + +from tensorflow.config import experimental as experimental + +class PhysicalDevice(NamedTuple): + name: str + device_type: str + +def list_physical_devices(device_type: None | str = None) -> list[PhysicalDevice]: ... +def get_visible_devices(device_type: None | str = None) -> list[PhysicalDevice]: ... +def set_visible_devices(devices: list[PhysicalDevice] | PhysicalDevice, device_type: None | str = None) -> None: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/config/experimental.pyi b/stubs/tensorflow/tensorflow/config/experimental.pyi new file mode 100644 index 000000000000..aa9dcc53ed2e --- /dev/null +++ b/stubs/tensorflow/tensorflow/config/experimental.pyi @@ -0,0 +1,17 @@ +import typing_extensions +from typing import TypedDict, type_check_only + +from tensorflow.config import PhysicalDevice + +@type_check_only +class _MemoryInfo(TypedDict): + current: int + peak: int + +def get_memory_info(device: str) -> _MemoryInfo: ... +def reset_memory_stats(device: str) -> None: ... +@typing_extensions.deprecated("This function is deprecated in favor of tf.config.experimental.get_memory_info") +def get_memory_usage(device: PhysicalDevice) -> int: ... +def get_memory_growth(device: PhysicalDevice) -> bool: ... +def set_memory_growth(device: PhysicalDevice, enable: bool) -> None: ... +def __getattr__(name: str): ... # incomplete module diff --git a/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi new file mode 100644 index 000000000000..9ffaef3d17a0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/example_parser_configuration_pb2.pyi @@ -0,0 +1,153 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing the configuration of the ExampleParserOp.""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class VarLenFeatureProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + VALUES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + INDICES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + SHAPES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + values_output_tensor_name: builtins.str + indices_output_tensor_name: builtins.str + shapes_output_tensor_name: builtins.str + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + values_output_tensor_name: builtins.str | None = ..., + indices_output_tensor_name: builtins.str | None = ..., + shapes_output_tensor_name: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "dtype", + b"dtype", + "indices_output_tensor_name", + b"indices_output_tensor_name", + "shapes_output_tensor_name", + b"shapes_output_tensor_name", + "values_output_tensor_name", + b"values_output_tensor_name", + ], + ) -> None: ... + +global___VarLenFeatureProto = VarLenFeatureProto + +@typing.final +class FixedLenFeatureProto(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + VALUES_OUTPUT_TENSOR_NAME_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + values_output_tensor_name: builtins.str + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def default_value(self) -> tensorflow.core.framework.tensor_pb2.TensorProto: ... + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + default_value: tensorflow.core.framework.tensor_pb2.TensorProto | None = ..., + values_output_tensor_name: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["default_value", b"default_value", "shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", + b"default_value", + "dtype", + b"dtype", + "shape", + b"shape", + "values_output_tensor_name", + b"values_output_tensor_name", + ], + ) -> None: ... + +global___FixedLenFeatureProto = FixedLenFeatureProto + +@typing.final +class FeatureConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FIXED_LEN_FEATURE_FIELD_NUMBER: builtins.int + VAR_LEN_FEATURE_FIELD_NUMBER: builtins.int + @property + def fixed_len_feature(self) -> global___FixedLenFeatureProto: ... + @property + def var_len_feature(self) -> global___VarLenFeatureProto: ... + def __init__( + self, + *, + fixed_len_feature: global___FixedLenFeatureProto | None = ..., + var_len_feature: global___VarLenFeatureProto | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "config", b"config", "fixed_len_feature", b"fixed_len_feature", "var_len_feature", b"var_len_feature" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "config", b"config", "fixed_len_feature", b"fixed_len_feature", "var_len_feature", b"var_len_feature" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["config", b"config"] + ) -> typing.Literal["fixed_len_feature", "var_len_feature"] | None: ... + +global___FeatureConfiguration = FeatureConfiguration + +@typing.final +class ExampleParserConfiguration(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureMapEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___FeatureConfiguration: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___FeatureConfiguration | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_MAP_FIELD_NUMBER: builtins.int + @property + def feature_map(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___FeatureConfiguration]: ... + def __init__( + self, *, feature_map: collections.abc.Mapping[builtins.str, global___FeatureConfiguration] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["feature_map", b"feature_map"]) -> None: ... + +global___ExampleParserConfiguration = ExampleParserConfiguration diff --git a/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi new file mode 100644 index 000000000000..63cf2c14f17a --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/example_pb2.pyi @@ -0,0 +1,330 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing input data Examples for machine learning +model training or inference. +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message +import tensorflow.core.example.feature_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Example(google.protobuf.message.Message): + """An Example is a mostly-normalized data format for storing data for + training and inference. It contains a key-value store (features); where + each key (string) maps to a Feature message (which is oneof packed BytesList, + FloatList, or Int64List). This flexible and compact format allows the + storage of large amounts of typed data, but requires that the data shape + and use be determined by the configuration files and parsers that are used to + read and write this format. That is, the Example is mostly *not* a + self-describing format. In TensorFlow, Examples are read in row-major + format, so any configuration that describes data with rank-2 or above + should keep this in mind. If you flatten a matrix into a FloatList it should + be stored as [ row 0 ... row 1 ... row M-1 ] + + An Example for a movie recommendation application: + features { + feature { + key: "age" + value { float_list { + value: 29.0 + }} + } + feature { + key: "movie" + value { bytes_list { + value: "The Shawshank Redemption" + value: "Fight Club" + }} + } + feature { + key: "movie_ratings" + value { float_list { + value: 9.0 + value: 9.7 + }} + } + feature { + key: "suggestion" + value { bytes_list { + value: "Inception" + }} + } + # Note that this feature exists to be used as a label in training. + # E.g., if training a logistic regression model to predict purchase + # probability in our learning tool we would set the label feature to + # "suggestion_purchased". + feature { + key: "suggestion_purchased" + value { float_list { + value: 1.0 + }} + } + # Similar to "suggestion_purchased" above this feature exists to be used + # as a label in training. + # E.g., if training a linear regression model to predict purchase + # price in our learning tool we would set the label feature to + # "purchase_price". + feature { + key: "purchase_price" + value { float_list { + value: 9.99 + }} + } + } + + A conformant Example data set obeys the following conventions: + - If a Feature K exists in one example with data type T, it must be of + type T in all other examples when present. It may be omitted. + - The number of instances of Feature K list data may vary across examples, + depending on the requirements of the model. + - If a Feature K doesn't exist in an example, a K-specific default will be + used, if configured. + - If a Feature K exists in an example but contains no items, the intent + is considered to be an empty tensor and no default will be used. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURES_FIELD_NUMBER: builtins.int + @property + def features(self) -> tensorflow.core.example.feature_pb2.Features: ... + def __init__(self, *, features: tensorflow.core.example.feature_pb2.Features | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["features", b"features"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["features", b"features"]) -> None: ... + +global___Example = Example + +@typing.final +class SequenceExample(google.protobuf.message.Message): + """A SequenceExample is an Example representing one or more sequences, and + some context. The context contains features which apply to the entire + example. The feature_lists contain a key, value map where each key is + associated with a repeated set of Features (a FeatureList). + A FeatureList thus represents the values of a feature identified by its key + over time / frames. + + Below is a SequenceExample for a movie recommendation application recording a + sequence of ratings by a user. The time-independent features ("locale", + "age", "favorites") describing the user are part of the context. The sequence + of movies the user rated are part of the feature_lists. For each movie in the + sequence we have information on its name and actors and the user's rating. + This information is recorded in three separate feature_list(s). + In the example below there are only two movies. All three feature_list(s), + namely "movie_ratings", "movie_names", and "actors" have a feature value for + both movies. Note, that "actors" is itself a bytes_list with multiple + strings per movie. + + context: { + feature: { + key : "locale" + value: { + bytes_list: { + value: [ "pt_BR" ] + } + } + } + feature: { + key : "age" + value: { + float_list: { + value: [ 19.0 ] + } + } + } + feature: { + key : "favorites" + value: { + bytes_list: { + value: [ "Majesty Rose", "Savannah Outen", "One Direction" ] + } + } + } + } + feature_lists: { + feature_list: { + key : "movie_ratings" + value: { + feature: { + float_list: { + value: [ 4.5 ] + } + } + feature: { + float_list: { + value: [ 5.0 ] + } + } + } + } + feature_list: { + key : "movie_names" + value: { + feature: { + bytes_list: { + value: [ "The Shawshank Redemption" ] + } + } + feature: { + bytes_list: { + value: [ "Fight Club" ] + } + } + } + } + feature_list: { + key : "actors" + value: { + feature: { + bytes_list: { + value: [ "Tim Robbins", "Morgan Freeman" ] + } + } + feature: { + bytes_list: { + value: [ "Brad Pitt", "Edward Norton", "Helena Bonham Carter" ] + } + } + } + } + } + + A conformant SequenceExample data set obeys the following conventions: + + Context: + - All conformant context features K must obey the same conventions as + a conformant Example's features (see above). + Feature lists: + - A FeatureList L may be missing in an example; it is up to the + parser configuration to determine if this is allowed or considered + an empty list (zero length). + - If a FeatureList L exists, it may be empty (zero length). + - If a FeatureList L is non-empty, all features within the FeatureList + must have the same data type T. Even across SequenceExamples, the type T + of the FeatureList identified by the same key must be the same. An entry + without any values may serve as an empty feature. + - If a FeatureList L is non-empty, it is up to the parser configuration + to determine if all features within the FeatureList must + have the same size. The same holds for this FeatureList across multiple + examples. + - For sequence modeling, e.g.: + http://colah.github.io/posts/2015-08-Understanding-LSTMs/ + https://github.com/tensorflow/nmt + the feature lists represent a sequence of frames. + In this scenario, all FeatureLists in a SequenceExample have the same + number of Feature messages, so that the ith element in each FeatureList + is part of the ith frame (or time step). + Examples of conformant and non-conformant examples' FeatureLists: + + Conformant FeatureLists: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + + Non-conformant FeatureLists (mismatched types): + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { int64_list: { value: [ 5 ] } } } + } } + + Conditionally conformant FeatureLists, the parser configuration determines + if the feature sizes must match: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0, 6.0 ] } } } + } } + + Conformant pair of SequenceExample + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } + feature: { float_list: { value: [ 2.0 ] } } } + } } + + Conformant pair of SequenceExample + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { } + } } + + Conditionally conformant pair of SequenceExample, the parser configuration + determines if the second feature_lists is consistent (zero-length) or + invalid (missing "movie_ratings"): + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { } + + Non-conformant pair of SequenceExample (mismatched types) + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { int64_list: { value: [ 4 ] } } + feature: { int64_list: { value: [ 5 ] } } + feature: { int64_list: { value: [ 2 ] } } } + } } + + Conditionally conformant pair of SequenceExample; the parser configuration + determines if the feature sizes must match: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.5 ] } } + feature: { float_list: { value: [ 5.0 ] } } } + } } + and: + feature_lists: { feature_list: { + key: "movie_ratings" + value: { feature: { float_list: { value: [ 4.0 ] } } + feature: { float_list: { value: [ 5.0, 3.0 ] } } + } } + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + CONTEXT_FIELD_NUMBER: builtins.int + FEATURE_LISTS_FIELD_NUMBER: builtins.int + @property + def context(self) -> tensorflow.core.example.feature_pb2.Features: ... + @property + def feature_lists(self) -> tensorflow.core.example.feature_pb2.FeatureLists: ... + def __init__( + self, + *, + context: tensorflow.core.example.feature_pb2.Features | None = ..., + feature_lists: tensorflow.core.example.feature_pb2.FeatureLists | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["context", b"context", "feature_lists", b"feature_lists"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["context", b"context", "feature_lists", b"feature_lists"]) -> None: ... + +global___SequenceExample = SequenceExample diff --git a/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi b/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi new file mode 100644 index 000000000000..9bec4dd165e0 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/example/feature_pb2.pyi @@ -0,0 +1,222 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Protocol messages for describing features for machine learning model +training or inference. + +There are three base Feature types: + - bytes + - float + - int64 + +A Feature contains Lists which may hold zero or more values. These +lists are the base values BytesList, FloatList, Int64List. + +Features are organized into categories by name. The Features message +contains the mapping from name to Feature. + +Example Features for a movie recommendation application: + feature { + key: "age" + value { float_list { + value: 29.0 + }} + } + feature { + key: "movie" + value { bytes_list { + value: "The Shawshank Redemption" + value: "Fight Club" + }} + } + feature { + key: "movie_ratings" + value { float_list { + value: 9.0 + value: 9.7 + }} + } + feature { + key: "suggestion" + value { bytes_list { + value: "Inception" + }} + } + feature { + key: "suggestion_purchased" + value { int64_list { + value: 1 + }} + } + feature { + key: "purchase_price" + value { float_list { + value: 9.99 + }} + } +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class BytesList(google.protobuf.message.Message): + """LINT.IfChange + Containers to hold repeated fundamental values. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bytes]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.bytes] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___BytesList = BytesList + +@typing.final +class FloatList(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.float] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___FloatList = FloatList + +@typing.final +class Int64List(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + VALUE_FIELD_NUMBER: builtins.int + @property + def value(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__(self, *, value: collections.abc.Iterable[builtins.int] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["value", b"value"]) -> None: ... + +global___Int64List = Int64List + +@typing.final +class Feature(google.protobuf.message.Message): + """Containers for non-sequential data.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BYTES_LIST_FIELD_NUMBER: builtins.int + FLOAT_LIST_FIELD_NUMBER: builtins.int + INT64_LIST_FIELD_NUMBER: builtins.int + @property + def bytes_list(self) -> global___BytesList: ... + @property + def float_list(self) -> global___FloatList: ... + @property + def int64_list(self) -> global___Int64List: ... + def __init__( + self, + *, + bytes_list: global___BytesList | None = ..., + float_list: global___FloatList | None = ..., + int64_list: global___Int64List | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "bytes_list", b"bytes_list", "float_list", b"float_list", "int64_list", b"int64_list", "kind", b"kind" + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "bytes_list", b"bytes_list", "float_list", b"float_list", "int64_list", b"int64_list", "kind", b"kind" + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["kind", b"kind"] + ) -> typing.Literal["bytes_list", "float_list", "int64_list"] | None: ... + +global___Feature = Feature + +@typing.final +class Features(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___Feature: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___Feature | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_FIELD_NUMBER: builtins.int + @property + def feature(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___Feature]: + """Map from feature name to feature.""" + + def __init__(self, *, feature: collections.abc.Mapping[builtins.str, global___Feature] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature", b"feature"]) -> None: ... + +global___Features = Features + +@typing.final +class FeatureList(google.protobuf.message.Message): + """Containers for sequential data. + + A FeatureList contains lists of Features. These may hold zero or more + Feature values. + + FeatureLists are organized into categories by name. The FeatureLists message + contains the mapping from name to FeatureList. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + FEATURE_FIELD_NUMBER: builtins.int + @property + def feature(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___Feature]: ... + def __init__(self, *, feature: collections.abc.Iterable[global___Feature] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature", b"feature"]) -> None: ... + +global___FeatureList = FeatureList + +@typing.final +class FeatureLists(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class FeatureListEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___FeatureList: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___FeatureList | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + FEATURE_LIST_FIELD_NUMBER: builtins.int + @property + def feature_list(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___FeatureList]: + """Map from feature name to feature list.""" + + def __init__(self, *, feature_list: collections.abc.Mapping[builtins.str, global___FeatureList] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["feature_list", b"feature_list"]) -> None: ... + +global___FeatureLists = FeatureLists diff --git a/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi new file mode 100644 index 000000000000..9f4e541f2299 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/allocation_description_pb2.pyi @@ -0,0 +1,64 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class AllocationDescription(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + REQUESTED_BYTES_FIELD_NUMBER: builtins.int + ALLOCATED_BYTES_FIELD_NUMBER: builtins.int + ALLOCATOR_NAME_FIELD_NUMBER: builtins.int + ALLOCATION_ID_FIELD_NUMBER: builtins.int + HAS_SINGLE_REFERENCE_FIELD_NUMBER: builtins.int + PTR_FIELD_NUMBER: builtins.int + requested_bytes: builtins.int + """Total number of bytes requested""" + allocated_bytes: builtins.int + """Total number of bytes allocated if known""" + allocator_name: builtins.str + """Name of the allocator used""" + allocation_id: builtins.int + """Identifier of the allocated buffer if known""" + has_single_reference: builtins.bool + """Set if this tensor only has one remaining reference""" + ptr: builtins.int + """Address of the allocation.""" + def __init__( + self, + *, + requested_bytes: builtins.int | None = ..., + allocated_bytes: builtins.int | None = ..., + allocator_name: builtins.str | None = ..., + allocation_id: builtins.int | None = ..., + has_single_reference: builtins.bool | None = ..., + ptr: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "allocated_bytes", + b"allocated_bytes", + "allocation_id", + b"allocation_id", + "allocator_name", + b"allocator_name", + "has_single_reference", + b"has_single_reference", + "ptr", + b"ptr", + "requested_bytes", + b"requested_bytes", + ], + ) -> None: ... + +global___AllocationDescription = AllocationDescription diff --git a/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi new file mode 100644 index 000000000000..b3d8c424234f --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/api_def_pb2.pyi @@ -0,0 +1,312 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +Defines the text format for including per-op API definition and +overrides for client language op code generators. +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.core.framework.attr_value_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class ApiDef(google.protobuf.message.Message): + """Used to specify and override the default API & behavior in the + generated code for client languages, from what you would get from + the OpDef alone. There will be a set of ApiDefs that are common + to all client languages, and another set per client language. + The per-client-language ApiDefs will inherit values from the + common ApiDefs which it can either replace or modify. + + We separate the API definition from the OpDef so we can evolve the + API while remaining backwards compatible when interpreting old + graphs. Overrides go in an "api_def.pbtxt" file with a text-format + ApiDefs message. + + WARNING: Be *very* careful changing the API for any existing op -- + you can change the semantics of existing code. These changes may + need to wait until a major release of TensorFlow to avoid breaking + our compatibility promises. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _Visibility: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _VisibilityEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[ApiDef._Visibility.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + DEFAULT_VISIBILITY: ApiDef._Visibility.ValueType # 0 + """Normally this is "VISIBLE" unless you are inheriting a + different value from another ApiDef. + """ + VISIBLE: ApiDef._Visibility.ValueType # 1 + """Publicly visible in the API.""" + SKIP: ApiDef._Visibility.ValueType # 2 + """Do not include this op in the generated API. If visibility is + set to 'SKIP', other fields are ignored for this op. + """ + HIDDEN: ApiDef._Visibility.ValueType # 3 + """Hide this op by putting it into an internal namespace (or whatever + is appropriate in the target language). + """ + + class Visibility(_Visibility, metaclass=_VisibilityEnumTypeWrapper): ... + DEFAULT_VISIBILITY: ApiDef.Visibility.ValueType # 0 + """Normally this is "VISIBLE" unless you are inheriting a + different value from another ApiDef. + """ + VISIBLE: ApiDef.Visibility.ValueType # 1 + """Publicly visible in the API.""" + SKIP: ApiDef.Visibility.ValueType # 2 + """Do not include this op in the generated API. If visibility is + set to 'SKIP', other fields are ignored for this op. + """ + HIDDEN: ApiDef.Visibility.ValueType # 3 + """Hide this op by putting it into an internal namespace (or whatever + is appropriate in the target language). + """ + + @typing.final + class Endpoint(google.protobuf.message.Message): + """If you specify any endpoint, this will replace all of the + inherited endpoints. The first endpoint should be the + "canonical" endpoint, and should not be deprecated (unless all + endpoints are deprecated). + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + DEPRECATED_FIELD_NUMBER: builtins.int + DEPRECATION_VERSION_FIELD_NUMBER: builtins.int + name: builtins.str + """Name should be either like "CamelCaseName" or + "Package.CamelCaseName". Client-language-specific ApiDefs may + use a snake_case convention instead of CamelCase. + """ + deprecated: builtins.bool + """Set if this endpoint is deprecated. If set to true, a message suggesting + to use a non-deprecated endpoint instead will be printed. If all + endpoints are deprecated, set deprecation_message in ApiDef instead. + """ + deprecation_version: builtins.int + """Major version when an endpoint will be deleted. For e.g. set this + value to 2 if endpoint should be removed in TensorFlow 2.0 and + deprecated in versions before that. + """ + def __init__( + self, + *, + name: builtins.str | None = ..., + deprecated: builtins.bool | None = ..., + deprecation_version: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "deprecated", b"deprecated", "deprecation_version", b"deprecation_version", "name", b"name" + ], + ) -> None: ... + + @typing.final + class Arg(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + RENAME_TO_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + rename_to: builtins.str + """Change the name used to access this arg in the API from what + is used in the GraphDef. Note that these names in `backticks` + will also be replaced in the summary & description fields. + """ + description: builtins.str + """Note: this will replace any inherited arg doc. There is no + current way of modifying arg descriptions (other than replacing + them entirely) as can be done with op descriptions. + """ + def __init__( + self, *, name: builtins.str | None = ..., rename_to: builtins.str | None = ..., description: builtins.str | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["description", b"description", "name", b"name", "rename_to", b"rename_to"] + ) -> None: ... + + @typing.final + class Attr(google.protobuf.message.Message): + """Description of the graph-construction-time configuration of this + Op. That is to say, this describes the attr fields that will + be specified in the NodeDef. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + RENAME_TO_FIELD_NUMBER: builtins.int + DEFAULT_VALUE_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + name: builtins.str + rename_to: builtins.str + """Change the name used to access this attr in the API from what + is used in the GraphDef. Note that these names in `backticks` + will also be replaced in the summary & description fields. + """ + description: builtins.str + """Note: this will replace any inherited attr doc, there is no current + way of modifying attr descriptions as can be done with op descriptions. + """ + @property + def default_value(self) -> tensorflow.core.framework.attr_value_pb2.AttrValue: + """Specify a new default value to use for this attr. This default + will be used when creating new graphs, as opposed to the + default in the OpDef, which will be used when interpreting old + GraphDefs. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + rename_to: builtins.str | None = ..., + default_value: tensorflow.core.framework.attr_value_pb2.AttrValue | None = ..., + description: builtins.str | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["default_value", b"default_value"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "default_value", b"default_value", "description", b"description", "name", b"name", "rename_to", b"rename_to" + ], + ) -> None: ... + + GRAPH_OP_NAME_FIELD_NUMBER: builtins.int + DEPRECATION_MESSAGE_FIELD_NUMBER: builtins.int + DEPRECATION_VERSION_FIELD_NUMBER: builtins.int + VISIBILITY_FIELD_NUMBER: builtins.int + ENDPOINT_FIELD_NUMBER: builtins.int + IN_ARG_FIELD_NUMBER: builtins.int + OUT_ARG_FIELD_NUMBER: builtins.int + ARG_ORDER_FIELD_NUMBER: builtins.int + ATTR_FIELD_NUMBER: builtins.int + SUMMARY_FIELD_NUMBER: builtins.int + DESCRIPTION_FIELD_NUMBER: builtins.int + DESCRIPTION_PREFIX_FIELD_NUMBER: builtins.int + DESCRIPTION_SUFFIX_FIELD_NUMBER: builtins.int + graph_op_name: builtins.str + """Name of the op (in the OpDef) to specify the API for.""" + deprecation_message: builtins.str + """If this op is deprecated, set deprecation message to the message + that should be logged when this op is used. + The message should indicate alternative op to use, if any. + """ + deprecation_version: builtins.int + """Major version when the op will be deleted. For e.g. set this + value to 2 if op API should be removed in TensorFlow 2.0 and + deprecated in versions before that. + """ + visibility: global___ApiDef.Visibility.ValueType + summary: builtins.str + """One-line human-readable description of what the Op does.""" + description: builtins.str + """Additional, longer human-readable description of what the Op does.""" + description_prefix: builtins.str + """Modify an existing/inherited description by adding text to the beginning + or end. + """ + description_suffix: builtins.str + @property + def endpoint(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Endpoint]: ... + @property + def in_arg(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Arg]: ... + @property + def out_arg(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Arg]: ... + @property + def arg_order(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of original in_arg names to specify new argument order. + Length of arg_order should be either empty to keep current order + or match size of in_arg. + """ + + @property + def attr(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef.Attr]: ... + def __init__( + self, + *, + graph_op_name: builtins.str | None = ..., + deprecation_message: builtins.str | None = ..., + deprecation_version: builtins.int | None = ..., + visibility: global___ApiDef.Visibility.ValueType | None = ..., + endpoint: collections.abc.Iterable[global___ApiDef.Endpoint] | None = ..., + in_arg: collections.abc.Iterable[global___ApiDef.Arg] | None = ..., + out_arg: collections.abc.Iterable[global___ApiDef.Arg] | None = ..., + arg_order: collections.abc.Iterable[builtins.str] | None = ..., + attr: collections.abc.Iterable[global___ApiDef.Attr] | None = ..., + summary: builtins.str | None = ..., + description: builtins.str | None = ..., + description_prefix: builtins.str | None = ..., + description_suffix: builtins.str | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "arg_order", + b"arg_order", + "attr", + b"attr", + "deprecation_message", + b"deprecation_message", + "deprecation_version", + b"deprecation_version", + "description", + b"description", + "description_prefix", + b"description_prefix", + "description_suffix", + b"description_suffix", + "endpoint", + b"endpoint", + "graph_op_name", + b"graph_op_name", + "in_arg", + b"in_arg", + "out_arg", + b"out_arg", + "summary", + b"summary", + "visibility", + b"visibility", + ], + ) -> None: ... + +global___ApiDef = ApiDef + +@typing.final +class ApiDefs(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + OP_FIELD_NUMBER: builtins.int + @property + def op(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___ApiDef]: ... + def __init__(self, *, op: collections.abc.Iterable[global___ApiDef] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["op", b"op"]) -> None: ... + +global___ApiDefs = ApiDefs diff --git a/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi new file mode 100644 index 000000000000..bc36030c511d --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/attr_value_pb2.pyi @@ -0,0 +1,274 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class AttrValue(google.protobuf.message.Message): + """Protocol buffer representing the value for an attr used to configure an Op. + Comment indicates the corresponding attr type. Only the field matching the + attr type may be filled. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class ListValue(google.protobuf.message.Message): + """LINT.IfChange""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + S_FIELD_NUMBER: builtins.int + I_FIELD_NUMBER: builtins.int + F_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + TENSOR_FIELD_NUMBER: builtins.int + FUNC_FIELD_NUMBER: builtins.int + @property + def s(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bytes]: + """ "list(string)" """ + + @property + def i(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """ "list(int)" """ + + @property + def f(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.float]: + """ "list(float)" """ + + @property + def b(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.bool]: + """ "list(bool)" """ + + @property + def type( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[ + tensorflow.core.framework.types_pb2.DataType.ValueType + ]: + """ "list(type)" """ + + @property + def shape( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto + ]: + """ "list(shape)" """ + + @property + def tensor( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_pb2.TensorProto + ]: + """ "list(tensor)" """ + + @property + def func(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___NameAttrList]: + """ "list(attr)" """ + + def __init__( + self, + *, + s: collections.abc.Iterable[builtins.bytes] | None = ..., + i: collections.abc.Iterable[builtins.int] | None = ..., + f: collections.abc.Iterable[builtins.float] | None = ..., + b: collections.abc.Iterable[builtins.bool] | None = ..., + type: collections.abc.Iterable[tensorflow.core.framework.types_pb2.DataType.ValueType] | None = ..., + shape: collections.abc.Iterable[tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto] | None = ..., + tensor: collections.abc.Iterable[tensorflow.core.framework.tensor_pb2.TensorProto] | None = ..., + func: collections.abc.Iterable[global___NameAttrList] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + ], + ) -> None: ... + + S_FIELD_NUMBER: builtins.int + I_FIELD_NUMBER: builtins.int + F_FIELD_NUMBER: builtins.int + B_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + TENSOR_FIELD_NUMBER: builtins.int + LIST_FIELD_NUMBER: builtins.int + FUNC_FIELD_NUMBER: builtins.int + PLACEHOLDER_FIELD_NUMBER: builtins.int + s: builtins.bytes + """"string" """ + i: builtins.int + """"int" """ + f: builtins.float + """"float" """ + b: builtins.bool + """"bool" """ + type: tensorflow.core.framework.types_pb2.DataType.ValueType + """"type" """ + placeholder: builtins.str + """This is a placeholder only used in nodes defined inside a + function. It indicates the attr value will be supplied when + the function is instantiated. For example, let us suppose a + node "N" in function "FN". "N" has an attr "A" with value + placeholder = "foo". When FN is instantiated with attr "foo" + set to "bar", the instantiated node N's attr A will have been + given the value "bar". + """ + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: + """ "shape" """ + + @property + def tensor(self) -> tensorflow.core.framework.tensor_pb2.TensorProto: + """ "tensor" """ + + @property + def list(self) -> global___AttrValue.ListValue: + """any "list(...)" """ + + @property + def func(self) -> global___NameAttrList: + """ "func" represents a function. func.name is a function's name or + a primitive op's name. func.attr.first is the name of an attr + defined for that function. func.attr.second is the value for + that attr in the instantiation. + """ + + def __init__( + self, + *, + s: builtins.bytes | None = ..., + i: builtins.int | None = ..., + f: builtins.float | None = ..., + b: builtins.bool | None = ..., + type: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + tensor: tensorflow.core.framework.tensor_pb2.TensorProto | None = ..., + list: global___AttrValue.ListValue | None = ..., + func: global___NameAttrList | None = ..., + placeholder: builtins.str | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "list", + b"list", + "placeholder", + b"placeholder", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + "value", + b"value", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "b", + b"b", + "f", + b"f", + "func", + b"func", + "i", + b"i", + "list", + b"list", + "placeholder", + b"placeholder", + "s", + b"s", + "shape", + b"shape", + "tensor", + b"tensor", + "type", + b"type", + "value", + b"value", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["value", b"value"] + ) -> typing.Literal["s", "i", "f", "b", "type", "shape", "tensor", "list", "func", "placeholder"] | None: ... + +global___AttrValue = AttrValue + +@typing.final +class NameAttrList(google.protobuf.message.Message): + """A list of attr names and their values. The whole list is attached + with a string name. E.g., MatMul[T=float]. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class AttrEntry(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + KEY_FIELD_NUMBER: builtins.int + VALUE_FIELD_NUMBER: builtins.int + key: builtins.str + @property + def value(self) -> global___AttrValue: ... + def __init__(self, *, key: builtins.str | None = ..., value: global___AttrValue | None = ...) -> None: ... + def HasField(self, field_name: typing.Literal["value", b"value"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["key", b"key", "value", b"value"]) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + ATTR_FIELD_NUMBER: builtins.int + name: builtins.str + @property + def attr(self) -> google.protobuf.internal.containers.MessageMap[builtins.str, global___AttrValue]: ... + def __init__( + self, *, name: builtins.str | None = ..., attr: collections.abc.Mapping[builtins.str, global___AttrValue] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["attr", b"attr", "name", b"name"]) -> None: ... + +global___NameAttrList = NameAttrList diff --git a/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi new file mode 100644 index 000000000000..3ba7d01628bf --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/cost_graph_pb2.pyi @@ -0,0 +1,229 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CostGraphDef(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class Node(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class InputInfo(google.protobuf.message.Message): + """Inputs of this node. They must be executed before this node can be + executed. An input is a particular output of another node, specified + by the node id and the output index. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PRECEDING_NODE_FIELD_NUMBER: builtins.int + PRECEDING_PORT_FIELD_NUMBER: builtins.int + preceding_node: builtins.int + preceding_port: builtins.int + def __init__( + self, *, preceding_node: builtins.int | None = ..., preceding_port: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["preceding_node", b"preceding_node", "preceding_port", b"preceding_port"] + ) -> None: ... + + @typing.final + class OutputInfo(google.protobuf.message.Message): + """Outputs of this node.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SIZE_FIELD_NUMBER: builtins.int + ALIAS_INPUT_PORT_FIELD_NUMBER: builtins.int + SHAPE_FIELD_NUMBER: builtins.int + DTYPE_FIELD_NUMBER: builtins.int + size: builtins.int + alias_input_port: builtins.int + """If >= 0, the output is an alias of an input. Note that an alias input + may itself be an alias. The algorithm will therefore need to follow + those pointers. + """ + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + def __init__( + self, + *, + size: builtins.int | None = ..., + alias_input_port: builtins.int | None = ..., + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "alias_input_port", b"alias_input_port", "dtype", b"dtype", "shape", b"shape", "size", b"size" + ], + ) -> None: ... + + NAME_FIELD_NUMBER: builtins.int + DEVICE_FIELD_NUMBER: builtins.int + ID_FIELD_NUMBER: builtins.int + INPUT_INFO_FIELD_NUMBER: builtins.int + OUTPUT_INFO_FIELD_NUMBER: builtins.int + TEMPORARY_MEMORY_SIZE_FIELD_NUMBER: builtins.int + PERSISTENT_MEMORY_SIZE_FIELD_NUMBER: builtins.int + HOST_TEMP_MEMORY_SIZE_FIELD_NUMBER: builtins.int + DEVICE_TEMP_MEMORY_SIZE_FIELD_NUMBER: builtins.int + DEVICE_PERSISTENT_MEMORY_SIZE_FIELD_NUMBER: builtins.int + COMPUTE_COST_FIELD_NUMBER: builtins.int + COMPUTE_TIME_FIELD_NUMBER: builtins.int + MEMORY_TIME_FIELD_NUMBER: builtins.int + IS_FINAL_FIELD_NUMBER: builtins.int + CONTROL_INPUT_FIELD_NUMBER: builtins.int + INACCURATE_FIELD_NUMBER: builtins.int + name: builtins.str + """The name of the node. Names are globally unique.""" + device: builtins.str + """The device of the node. Can be empty if the node is mapped to the + default partition or partitioning hasn't been run yet. + """ + id: builtins.int + """The id of the node. Node ids are only unique inside a partition.""" + temporary_memory_size: builtins.int + """Temporary memory used by this node.""" + persistent_memory_size: builtins.int + """Persistent memory used by this node.""" + host_temp_memory_size: builtins.int + device_temp_memory_size: builtins.int + device_persistent_memory_size: builtins.int + compute_cost: builtins.int + """Estimate of the computational cost of this node, in microseconds.""" + compute_time: builtins.int + """Analytical estimate of the computational cost of this node, in + microseconds. + """ + memory_time: builtins.int + """Analytical estimate of the memory access cost of this node, in + microseconds. + """ + is_final: builtins.bool + """If true, the output is permanent: it can't be discarded, because this + node is part of the "final output". Nodes may depend on final nodes. + """ + inaccurate: builtins.bool + """Are the costs inaccurate?""" + @property + def input_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node.InputInfo]: ... + @property + def output_info( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node.OutputInfo]: ... + @property + def control_input(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """Ids of the control inputs for this node.""" + + def __init__( + self, + *, + name: builtins.str | None = ..., + device: builtins.str | None = ..., + id: builtins.int | None = ..., + input_info: collections.abc.Iterable[global___CostGraphDef.Node.InputInfo] | None = ..., + output_info: collections.abc.Iterable[global___CostGraphDef.Node.OutputInfo] | None = ..., + temporary_memory_size: builtins.int | None = ..., + persistent_memory_size: builtins.int | None = ..., + host_temp_memory_size: builtins.int | None = ..., + device_temp_memory_size: builtins.int | None = ..., + device_persistent_memory_size: builtins.int | None = ..., + compute_cost: builtins.int | None = ..., + compute_time: builtins.int | None = ..., + memory_time: builtins.int | None = ..., + is_final: builtins.bool | None = ..., + control_input: collections.abc.Iterable[builtins.int] | None = ..., + inaccurate: builtins.bool | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "compute_cost", + b"compute_cost", + "compute_time", + b"compute_time", + "control_input", + b"control_input", + "device", + b"device", + "device_persistent_memory_size", + b"device_persistent_memory_size", + "device_temp_memory_size", + b"device_temp_memory_size", + "host_temp_memory_size", + b"host_temp_memory_size", + "id", + b"id", + "inaccurate", + b"inaccurate", + "input_info", + b"input_info", + "is_final", + b"is_final", + "memory_time", + b"memory_time", + "name", + b"name", + "output_info", + b"output_info", + "persistent_memory_size", + b"persistent_memory_size", + "temporary_memory_size", + b"temporary_memory_size", + ], + ) -> None: ... + + @typing.final + class AggregatedCost(google.protobuf.message.Message): + """Total cost of this graph, typically used for balancing decisions.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COST_FIELD_NUMBER: builtins.int + DIMENSION_FIELD_NUMBER: builtins.int + cost: builtins.float + """Aggregated cost value.""" + dimension: builtins.str + """Aggregated cost dimension (e.g. 'memory', 'compute', 'network').""" + def __init__(self, *, cost: builtins.float | None = ..., dimension: builtins.str | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["cost", b"cost", "dimension", b"dimension"]) -> None: ... + + NODE_FIELD_NUMBER: builtins.int + COST_FIELD_NUMBER: builtins.int + @property + def node(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.Node]: ... + @property + def cost( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CostGraphDef.AggregatedCost]: ... + def __init__( + self, + *, + node: collections.abc.Iterable[global___CostGraphDef.Node] | None = ..., + cost: collections.abc.Iterable[global___CostGraphDef.AggregatedCost] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["cost", b"cost", "node", b"node"]) -> None: ... + +global___CostGraphDef = CostGraphDef diff --git a/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi new file mode 100644 index 000000000000..1bf1c41641cc --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/cpp_shape_inference_pb2.pyi @@ -0,0 +1,110 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.full_type_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CppShapeInferenceResult(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + @typing.final + class HandleShapeAndType(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + SHAPE_FIELD_NUMBER: builtins.int + DTYPE_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def type(self) -> tensorflow.core.framework.full_type_pb2.FullTypeDef: ... + def __init__( + self, + *, + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + type: tensorflow.core.framework.full_type_pb2.FullTypeDef | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["shape", b"shape", "type", b"type"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["dtype", b"dtype", "shape", b"shape", "type", b"type"]) -> None: ... + + @typing.final + class HandleData(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + IS_SET_FIELD_NUMBER: builtins.int + SHAPE_AND_TYPE_FIELD_NUMBER: builtins.int + is_set: builtins.bool + @property + def shape_and_type( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + global___CppShapeInferenceResult.HandleShapeAndType + ]: + """Only valid if .""" + + def __init__( + self, + *, + is_set: builtins.bool | None = ..., + shape_and_type: collections.abc.Iterable[global___CppShapeInferenceResult.HandleShapeAndType] | None = ..., + ) -> None: ... + def ClearField(self, field_name: typing.Literal["is_set", b"is_set", "shape_and_type", b"shape_and_type"]) -> None: ... + + SHAPE_FIELD_NUMBER: builtins.int + HANDLE_DATA_FIELD_NUMBER: builtins.int + @property + def shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: ... + @property + def handle_data(self) -> global___CppShapeInferenceResult.HandleData: ... + def __init__( + self, + *, + shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + handle_data: global___CppShapeInferenceResult.HandleData | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["handle_data", b"handle_data", "shape", b"shape"]) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["handle_data", b"handle_data", "shape", b"shape"]) -> None: ... + +global___CppShapeInferenceResult = CppShapeInferenceResult + +@typing.final +class CppShapeInferenceInputsNeeded(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + INPUT_TENSORS_NEEDED_FIELD_NUMBER: builtins.int + INPUT_TENSORS_AS_SHAPES_NEEDED_FIELD_NUMBER: builtins.int + @property + def input_tensors_needed(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + @property + def input_tensors_as_shapes_needed( + self, + ) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: ... + def __init__( + self, + *, + input_tensors_needed: collections.abc.Iterable[builtins.int] | None = ..., + input_tensors_as_shapes_needed: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def ClearField( + self, + field_name: typing.Literal[ + "input_tensors_as_shapes_needed", b"input_tensors_as_shapes_needed", "input_tensors_needed", b"input_tensors_needed" + ], + ) -> None: ... + +global___CppShapeInferenceInputsNeeded = CppShapeInferenceInputsNeeded diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi new file mode 100644 index 000000000000..afde78f967f6 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_metadata_pb2.pyi @@ -0,0 +1,25 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import typing + +import google.protobuf.descriptor +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class Metadata(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + name: builtins.bytes + def __init__(self, *, name: builtins.bytes | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["name", b"name"]) -> None: ... + +global___Metadata = Metadata diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi new file mode 100644 index 000000000000..284c97869d3c --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_options_pb2.pyi @@ -0,0 +1,724 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message +import tensorflow.core.framework.model_pb2 + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _AutoShardPolicy: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _AutoShardPolicyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_AutoShardPolicy.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + AUTO: _AutoShardPolicy.ValueType # 0 + """AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.""" + FILE: _AutoShardPolicy.ValueType # 1 + """FILE: Shards by input files (i.e. each worker will get a set of files to + process). When this option is selected, make sure that there is at least as + many files as workers. If there are fewer input files than workers, a + runtime error will be raised. + """ + DATA: _AutoShardPolicy.ValueType # 2 + """DATA: Shards by elements produced by the dataset. Each worker will process + the whole dataset and discard the portion that is not for itself. Note that + for this mode to correctly partitions the dataset elements, the dataset + needs to produce elements in a deterministic order. + """ + HINT: _AutoShardPolicy.ValueType # 3 + """HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated + as a placeholder to replace with `shard(num_workers, worker_index)`. + """ + OFF: _AutoShardPolicy.ValueType # -1 + """OFF: No sharding will be performed.""" + +class AutoShardPolicy(_AutoShardPolicy, metaclass=_AutoShardPolicyEnumTypeWrapper): + """Represents the type of auto-sharding we enable.""" + +AUTO: AutoShardPolicy.ValueType # 0 +"""AUTO: Attempts FILE-based sharding, falling back to DATA-based sharding.""" +FILE: AutoShardPolicy.ValueType # 1 +"""FILE: Shards by input files (i.e. each worker will get a set of files to +process). When this option is selected, make sure that there is at least as +many files as workers. If there are fewer input files than workers, a +runtime error will be raised. +""" +DATA: AutoShardPolicy.ValueType # 2 +"""DATA: Shards by elements produced by the dataset. Each worker will process +the whole dataset and discard the portion that is not for itself. Note that +for this mode to correctly partitions the dataset elements, the dataset +needs to produce elements in a deterministic order. +""" +HINT: AutoShardPolicy.ValueType # 3 +"""HINT: Looks for the presence of `shard(SHARD_HINT, ...)` which is treated +as a placeholder to replace with `shard(num_workers, worker_index)`. +""" +OFF: AutoShardPolicy.ValueType # -1 +"""OFF: No sharding will be performed.""" +global___AutoShardPolicy = AutoShardPolicy + +class _ExternalStatePolicy: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _ExternalStatePolicyEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_ExternalStatePolicy.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + POLICY_WARN: _ExternalStatePolicy.ValueType # 0 + POLICY_IGNORE: _ExternalStatePolicy.ValueType # 1 + POLICY_FAIL: _ExternalStatePolicy.ValueType # 2 + +class ExternalStatePolicy(_ExternalStatePolicy, metaclass=_ExternalStatePolicyEnumTypeWrapper): + """Represents how to handle external state during serialization.""" + +POLICY_WARN: ExternalStatePolicy.ValueType # 0 +POLICY_IGNORE: ExternalStatePolicy.ValueType # 1 +POLICY_FAIL: ExternalStatePolicy.ValueType # 2 +global___ExternalStatePolicy = ExternalStatePolicy + +@typing.final +class AutotuneOptions(google.protobuf.message.Message): + """next: 6""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + ENABLED_FIELD_NUMBER: builtins.int + CPU_BUDGET_FIELD_NUMBER: builtins.int + RAM_BUDGET_FIELD_NUMBER: builtins.int + AUTOTUNE_ALGORITHM_FIELD_NUMBER: builtins.int + INITIAL_PARALLELISM_FIELD_NUMBER: builtins.int + enabled: builtins.bool + cpu_budget: builtins.int + ram_budget: builtins.int + autotune_algorithm: tensorflow.core.framework.model_pb2.AutotuneAlgorithm.ValueType + initial_parallelism: builtins.int + def __init__( + self, + *, + enabled: builtins.bool | None = ..., + cpu_budget: builtins.int | None = ..., + ram_budget: builtins.int | None = ..., + autotune_algorithm: tensorflow.core.framework.model_pb2.AutotuneAlgorithm.ValueType | None = ..., + initial_parallelism: builtins.int | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "autotune_algorithm", + b"autotune_algorithm", + "cpu_budget", + b"cpu_budget", + "enabled", + b"enabled", + "initial_parallelism", + b"initial_parallelism", + "optional_autotune_algorithm", + b"optional_autotune_algorithm", + "optional_cpu_budget", + b"optional_cpu_budget", + "optional_enabled", + b"optional_enabled", + "optional_initial_parallelism", + b"optional_initial_parallelism", + "optional_ram_budget", + b"optional_ram_budget", + "ram_budget", + b"ram_budget", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "autotune_algorithm", + b"autotune_algorithm", + "cpu_budget", + b"cpu_budget", + "enabled", + b"enabled", + "initial_parallelism", + b"initial_parallelism", + "optional_autotune_algorithm", + b"optional_autotune_algorithm", + "optional_cpu_budget", + b"optional_cpu_budget", + "optional_enabled", + b"optional_enabled", + "optional_initial_parallelism", + b"optional_initial_parallelism", + "optional_ram_budget", + b"optional_ram_budget", + "ram_budget", + b"ram_budget", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_autotune_algorithm", b"optional_autotune_algorithm"] + ) -> typing.Literal["autotune_algorithm"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_cpu_budget", b"optional_cpu_budget"] + ) -> typing.Literal["cpu_budget"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_enabled", b"optional_enabled"] + ) -> typing.Literal["enabled"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_initial_parallelism", b"optional_initial_parallelism"] + ) -> typing.Literal["initial_parallelism"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_ram_budget", b"optional_ram_budget"] + ) -> typing.Literal["ram_budget"] | None: ... + +global___AutotuneOptions = AutotuneOptions + +@typing.final +class CardinalityOptions(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + class _ComputeLevel: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + + class _ComputeLevelEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[CardinalityOptions._ComputeLevel.ValueType], builtins.type + ): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + CARDINALITY_COMPUTE_UNSPECIFIED: CardinalityOptions._ComputeLevel.ValueType # 0 + CARDINALITY_COMPUTE_LOW: CardinalityOptions._ComputeLevel.ValueType # 1 + """Cardinality will only be computed if it can be determined in a cheap + manner (ie. without reading from file sources). If the cardinality would + be nontrivial to compute, Cardinality() will return UNKNOWN_CARDINALITY. + """ + CARDINALITY_COMPUTE_MODERATE: CardinalityOptions._ComputeLevel.ValueType # 2 + """Moderate effort will be made to determine cardinality, such as reading + index data from source files. If significant work is needed to compute + cardinality (e.g. reading entire source file contents or executing user + defined functions), Cardinality() will return UNKNOWN_CARDINALITY. + """ + + class ComputeLevel(_ComputeLevel, metaclass=_ComputeLevelEnumTypeWrapper): ... + CARDINALITY_COMPUTE_UNSPECIFIED: CardinalityOptions.ComputeLevel.ValueType # 0 + CARDINALITY_COMPUTE_LOW: CardinalityOptions.ComputeLevel.ValueType # 1 + """Cardinality will only be computed if it can be determined in a cheap + manner (ie. without reading from file sources). If the cardinality would + be nontrivial to compute, Cardinality() will return UNKNOWN_CARDINALITY. + """ + CARDINALITY_COMPUTE_MODERATE: CardinalityOptions.ComputeLevel.ValueType # 2 + """Moderate effort will be made to determine cardinality, such as reading + index data from source files. If significant work is needed to compute + cardinality (e.g. reading entire source file contents or executing user + defined functions), Cardinality() will return UNKNOWN_CARDINALITY. + """ + + COMPUTE_LEVEL_FIELD_NUMBER: builtins.int + compute_level: global___CardinalityOptions.ComputeLevel.ValueType + def __init__(self, *, compute_level: global___CardinalityOptions.ComputeLevel.ValueType | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["compute_level", b"compute_level"]) -> None: ... + +global___CardinalityOptions = CardinalityOptions + +@typing.final +class DistributeOptions(google.protobuf.message.Message): + """next: 3""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + AUTO_SHARD_POLICY_FIELD_NUMBER: builtins.int + NUM_DEVICES_FIELD_NUMBER: builtins.int + auto_shard_policy: global___AutoShardPolicy.ValueType + num_devices: builtins.int + def __init__( + self, *, auto_shard_policy: global___AutoShardPolicy.ValueType | None = ..., num_devices: builtins.int | None = ... + ) -> None: ... + def HasField( + self, field_name: typing.Literal["num_devices", b"num_devices", "optional_num_devices", b"optional_num_devices"] + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "auto_shard_policy", + b"auto_shard_policy", + "num_devices", + b"num_devices", + "optional_num_devices", + b"optional_num_devices", + ], + ) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_num_devices", b"optional_num_devices"] + ) -> typing.Literal["num_devices"] | None: ... + +global___DistributeOptions = DistributeOptions + +@typing.final +class OptimizationOptions(google.protobuf.message.Message): + """next: 22""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + APPLY_DEFAULT_OPTIMIZATIONS_FIELD_NUMBER: builtins.int + FILTER_FUSION_FIELD_NUMBER: builtins.int + MAP_AND_BATCH_FUSION_FIELD_NUMBER: builtins.int + MAP_AND_FILTER_FUSION_FIELD_NUMBER: builtins.int + MAP_FUSION_FIELD_NUMBER: builtins.int + MAP_PARALLELIZATION_FIELD_NUMBER: builtins.int + NOOP_ELIMINATION_FIELD_NUMBER: builtins.int + PARALLEL_BATCH_FIELD_NUMBER: builtins.int + SHUFFLE_AND_REPEAT_FUSION_FIELD_NUMBER: builtins.int + FILTER_PARALLELIZATION_FIELD_NUMBER: builtins.int + INJECT_PREFETCH_FIELD_NUMBER: builtins.int + SEQ_INTERLEAVE_PREFETCH_FIELD_NUMBER: builtins.int + apply_default_optimizations: builtins.bool + filter_fusion: builtins.bool + map_and_batch_fusion: builtins.bool + map_and_filter_fusion: builtins.bool + map_fusion: builtins.bool + map_parallelization: builtins.bool + noop_elimination: builtins.bool + parallel_batch: builtins.bool + shuffle_and_repeat_fusion: builtins.bool + filter_parallelization: builtins.bool + inject_prefetch: builtins.bool + seq_interleave_prefetch: builtins.bool + def __init__( + self, + *, + apply_default_optimizations: builtins.bool | None = ..., + filter_fusion: builtins.bool | None = ..., + map_and_batch_fusion: builtins.bool | None = ..., + map_and_filter_fusion: builtins.bool | None = ..., + map_fusion: builtins.bool | None = ..., + map_parallelization: builtins.bool | None = ..., + noop_elimination: builtins.bool | None = ..., + parallel_batch: builtins.bool | None = ..., + shuffle_and_repeat_fusion: builtins.bool | None = ..., + filter_parallelization: builtins.bool | None = ..., + inject_prefetch: builtins.bool | None = ..., + seq_interleave_prefetch: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "apply_default_optimizations", + b"apply_default_optimizations", + "filter_fusion", + b"filter_fusion", + "filter_parallelization", + b"filter_parallelization", + "inject_prefetch", + b"inject_prefetch", + "map_and_batch_fusion", + b"map_and_batch_fusion", + "map_and_filter_fusion", + b"map_and_filter_fusion", + "map_fusion", + b"map_fusion", + "map_parallelization", + b"map_parallelization", + "noop_elimination", + b"noop_elimination", + "optional_apply_default_optimizations", + b"optional_apply_default_optimizations", + "optional_filter_fusion", + b"optional_filter_fusion", + "optional_filter_parallelization", + b"optional_filter_parallelization", + "optional_inject_prefetch", + b"optional_inject_prefetch", + "optional_map_and_batch_fusion", + b"optional_map_and_batch_fusion", + "optional_map_and_filter_fusion", + b"optional_map_and_filter_fusion", + "optional_map_fusion", + b"optional_map_fusion", + "optional_map_parallelization", + b"optional_map_parallelization", + "optional_noop_elimination", + b"optional_noop_elimination", + "optional_parallel_batch", + b"optional_parallel_batch", + "optional_seq_interleave_prefetch", + b"optional_seq_interleave_prefetch", + "optional_shuffle_and_repeat_fusion", + b"optional_shuffle_and_repeat_fusion", + "parallel_batch", + b"parallel_batch", + "seq_interleave_prefetch", + b"seq_interleave_prefetch", + "shuffle_and_repeat_fusion", + b"shuffle_and_repeat_fusion", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "apply_default_optimizations", + b"apply_default_optimizations", + "filter_fusion", + b"filter_fusion", + "filter_parallelization", + b"filter_parallelization", + "inject_prefetch", + b"inject_prefetch", + "map_and_batch_fusion", + b"map_and_batch_fusion", + "map_and_filter_fusion", + b"map_and_filter_fusion", + "map_fusion", + b"map_fusion", + "map_parallelization", + b"map_parallelization", + "noop_elimination", + b"noop_elimination", + "optional_apply_default_optimizations", + b"optional_apply_default_optimizations", + "optional_filter_fusion", + b"optional_filter_fusion", + "optional_filter_parallelization", + b"optional_filter_parallelization", + "optional_inject_prefetch", + b"optional_inject_prefetch", + "optional_map_and_batch_fusion", + b"optional_map_and_batch_fusion", + "optional_map_and_filter_fusion", + b"optional_map_and_filter_fusion", + "optional_map_fusion", + b"optional_map_fusion", + "optional_map_parallelization", + b"optional_map_parallelization", + "optional_noop_elimination", + b"optional_noop_elimination", + "optional_parallel_batch", + b"optional_parallel_batch", + "optional_seq_interleave_prefetch", + b"optional_seq_interleave_prefetch", + "optional_shuffle_and_repeat_fusion", + b"optional_shuffle_and_repeat_fusion", + "parallel_batch", + b"parallel_batch", + "seq_interleave_prefetch", + b"seq_interleave_prefetch", + "shuffle_and_repeat_fusion", + b"shuffle_and_repeat_fusion", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_apply_default_optimizations", b"optional_apply_default_optimizations"] + ) -> typing.Literal["apply_default_optimizations"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_filter_fusion", b"optional_filter_fusion"] + ) -> typing.Literal["filter_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_filter_parallelization", b"optional_filter_parallelization"] + ) -> typing.Literal["filter_parallelization"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_inject_prefetch", b"optional_inject_prefetch"] + ) -> typing.Literal["inject_prefetch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_and_batch_fusion", b"optional_map_and_batch_fusion"] + ) -> typing.Literal["map_and_batch_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_and_filter_fusion", b"optional_map_and_filter_fusion"] + ) -> typing.Literal["map_and_filter_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_fusion", b"optional_map_fusion"] + ) -> typing.Literal["map_fusion"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_map_parallelization", b"optional_map_parallelization"] + ) -> typing.Literal["map_parallelization"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_noop_elimination", b"optional_noop_elimination"] + ) -> typing.Literal["noop_elimination"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_parallel_batch", b"optional_parallel_batch"] + ) -> typing.Literal["parallel_batch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_seq_interleave_prefetch", b"optional_seq_interleave_prefetch"] + ) -> typing.Literal["seq_interleave_prefetch"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_shuffle_and_repeat_fusion", b"optional_shuffle_and_repeat_fusion"] + ) -> typing.Literal["shuffle_and_repeat_fusion"] | None: ... + +global___OptimizationOptions = OptimizationOptions + +@typing.final +class ServiceOptions(google.protobuf.message.Message): + """next: 2""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + PINNED_FIELD_NUMBER: builtins.int + pinned: builtins.bool + def __init__(self, *, pinned: builtins.bool | None = ...) -> None: ... + def HasField( + self, field_name: typing.Literal["optional_pinned", b"optional_pinned", "pinned", b"pinned"] + ) -> builtins.bool: ... + def ClearField(self, field_name: typing.Literal["optional_pinned", b"optional_pinned", "pinned", b"pinned"]) -> None: ... + def WhichOneof( + self, oneof_group: typing.Literal["optional_pinned", b"optional_pinned"] + ) -> typing.Literal["pinned"] | None: ... + +global___ServiceOptions = ServiceOptions + +@typing.final +class ThreadingOptions(google.protobuf.message.Message): + """next: 3""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + MAX_INTRA_OP_PARALLELISM_FIELD_NUMBER: builtins.int + PRIVATE_THREADPOOL_SIZE_FIELD_NUMBER: builtins.int + max_intra_op_parallelism: builtins.int + private_threadpool_size: builtins.int + def __init__( + self, *, max_intra_op_parallelism: builtins.int | None = ..., private_threadpool_size: builtins.int | None = ... + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "max_intra_op_parallelism", + b"max_intra_op_parallelism", + "optional_max_intra_op_parallelism", + b"optional_max_intra_op_parallelism", + "optional_private_threadpool_size", + b"optional_private_threadpool_size", + "private_threadpool_size", + b"private_threadpool_size", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "max_intra_op_parallelism", + b"max_intra_op_parallelism", + "optional_max_intra_op_parallelism", + b"optional_max_intra_op_parallelism", + "optional_private_threadpool_size", + b"optional_private_threadpool_size", + "private_threadpool_size", + b"private_threadpool_size", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_max_intra_op_parallelism", b"optional_max_intra_op_parallelism"] + ) -> typing.Literal["max_intra_op_parallelism"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_private_threadpool_size", b"optional_private_threadpool_size"] + ) -> typing.Literal["private_threadpool_size"] | None: ... + +global___ThreadingOptions = ThreadingOptions + +@typing.final +class Options(google.protobuf.message.Message): + """Message stored with Dataset objects to control how datasets are processed and + optimized. + + next: 13 + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATASET_NAME_FIELD_NUMBER: builtins.int + FRAMEWORK_TYPE_FIELD_NUMBER: builtins.int + DETERMINISTIC_FIELD_NUMBER: builtins.int + AUTOTUNE_OPTIONS_FIELD_NUMBER: builtins.int + DISTRIBUTE_OPTIONS_FIELD_NUMBER: builtins.int + OPTIMIZATION_OPTIONS_FIELD_NUMBER: builtins.int + SERVICE_OPTIONS_FIELD_NUMBER: builtins.int + SLACK_FIELD_NUMBER: builtins.int + THREADING_OPTIONS_FIELD_NUMBER: builtins.int + EXTERNAL_STATE_POLICY_FIELD_NUMBER: builtins.int + SYMBOLIC_CHECKPOINT_FIELD_NUMBER: builtins.int + WARM_START_FIELD_NUMBER: builtins.int + dataset_name: builtins.str + deterministic: builtins.bool + slack: builtins.bool + external_state_policy: global___ExternalStatePolicy.ValueType + symbolic_checkpoint: builtins.bool + warm_start: builtins.bool + @property + def framework_type(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: + """List of frameworks used to generate this dataset.""" + + @property + def autotune_options(self) -> global___AutotuneOptions: + """The autotune options associated with the dataset.""" + + @property + def distribute_options(self) -> global___DistributeOptions: + """The distribution strategy options associated with the dataset.""" + + @property + def optimization_options(self) -> global___OptimizationOptions: + """The optimization options associated with the dataset.""" + + @property + def service_options(self) -> global___ServiceOptions: + """The tf.data service options associated with the dataset.""" + + @property + def threading_options(self) -> global___ThreadingOptions: + """The threading options associated with the dataset.""" + + def __init__( + self, + *, + dataset_name: builtins.str | None = ..., + framework_type: collections.abc.Iterable[builtins.str] | None = ..., + deterministic: builtins.bool | None = ..., + autotune_options: global___AutotuneOptions | None = ..., + distribute_options: global___DistributeOptions | None = ..., + optimization_options: global___OptimizationOptions | None = ..., + service_options: global___ServiceOptions | None = ..., + slack: builtins.bool | None = ..., + threading_options: global___ThreadingOptions | None = ..., + external_state_policy: global___ExternalStatePolicy.ValueType | None = ..., + symbolic_checkpoint: builtins.bool | None = ..., + warm_start: builtins.bool | None = ..., + ) -> None: ... + def HasField( + self, + field_name: typing.Literal[ + "autotune_options", + b"autotune_options", + "dataset_name", + b"dataset_name", + "deterministic", + b"deterministic", + "distribute_options", + b"distribute_options", + "external_state_policy", + b"external_state_policy", + "optimization_options", + b"optimization_options", + "optional_dataset_name", + b"optional_dataset_name", + "optional_deterministic", + b"optional_deterministic", + "optional_external_state_policy", + b"optional_external_state_policy", + "optional_slack", + b"optional_slack", + "optional_symbolic_checkpoint", + b"optional_symbolic_checkpoint", + "optional_warm_start", + b"optional_warm_start", + "service_options", + b"service_options", + "slack", + b"slack", + "symbolic_checkpoint", + b"symbolic_checkpoint", + "threading_options", + b"threading_options", + "warm_start", + b"warm_start", + ], + ) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "autotune_options", + b"autotune_options", + "dataset_name", + b"dataset_name", + "deterministic", + b"deterministic", + "distribute_options", + b"distribute_options", + "external_state_policy", + b"external_state_policy", + "framework_type", + b"framework_type", + "optimization_options", + b"optimization_options", + "optional_dataset_name", + b"optional_dataset_name", + "optional_deterministic", + b"optional_deterministic", + "optional_external_state_policy", + b"optional_external_state_policy", + "optional_slack", + b"optional_slack", + "optional_symbolic_checkpoint", + b"optional_symbolic_checkpoint", + "optional_warm_start", + b"optional_warm_start", + "service_options", + b"service_options", + "slack", + b"slack", + "symbolic_checkpoint", + b"symbolic_checkpoint", + "threading_options", + b"threading_options", + "warm_start", + b"warm_start", + ], + ) -> None: ... + + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_dataset_name", b"optional_dataset_name"] + ) -> typing.Literal["dataset_name"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_deterministic", b"optional_deterministic"] + ) -> typing.Literal["deterministic"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_external_state_policy", b"optional_external_state_policy"] + ) -> typing.Literal["external_state_policy"] | None: ... + @typing.overload + def WhichOneof(self, oneof_group: typing.Literal["optional_slack", b"optional_slack"]) -> typing.Literal["slack"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_symbolic_checkpoint", b"optional_symbolic_checkpoint"] + ) -> typing.Literal["symbolic_checkpoint"] | None: ... + @typing.overload + def WhichOneof( + self, oneof_group: typing.Literal["optional_warm_start", b"optional_warm_start"] + ) -> typing.Literal["warm_start"] | None: ... + +global___Options = Options diff --git a/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi new file mode 100644 index 000000000000..0cfb9bb85928 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/dataset_pb2.pyi @@ -0,0 +1,116 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message +import tensorflow.core.framework.tensor_pb2 +import tensorflow.core.framework.tensor_shape_pb2 +import tensorflow.core.framework.types_pb2 + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class CompressedComponentMetadata(google.protobuf.message.Message): + """This file contains protocol buffers for working with tf.data Datasets. + + Metadata describing a compressed component of a dataset element. + """ + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DTYPE_FIELD_NUMBER: builtins.int + TENSOR_SHAPE_FIELD_NUMBER: builtins.int + UNCOMPRESSED_BYTES_FIELD_NUMBER: builtins.int + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType + """The dtype of the component tensor.""" + @property + def tensor_shape(self) -> tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto: + """The shape of the component tensor.""" + + @property + def uncompressed_bytes(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]: + """The amount of uncompressed tensor data. + - For string tensors, there is an element for each string indicating the + size of the string. + - For all other tensors, there is a single element indicating the size of + the tensor. + """ + + def __init__( + self, + *, + dtype: tensorflow.core.framework.types_pb2.DataType.ValueType | None = ..., + tensor_shape: tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto | None = ..., + uncompressed_bytes: collections.abc.Iterable[builtins.int] | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["tensor_shape", b"tensor_shape"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "dtype", b"dtype", "tensor_shape", b"tensor_shape", "uncompressed_bytes", b"uncompressed_bytes" + ], + ) -> None: ... + +global___CompressedComponentMetadata = CompressedComponentMetadata + +@typing.final +class CompressedElement(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DATA_FIELD_NUMBER: builtins.int + COMPONENT_METADATA_FIELD_NUMBER: builtins.int + VERSION_FIELD_NUMBER: builtins.int + data: builtins.bytes + """Compressed tensor bytes for all components of the element.""" + version: builtins.int + """Version of the CompressedElement. CompressedElements may be stored on disk + and read back by later versions of code, so we store a version number to + help readers understand which version they are reading. When you add a new + field to this proto, you need to increment kCompressedElementVersion in + tensorflow/core/data/compression_utils.cc. + """ + @property + def component_metadata( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___CompressedComponentMetadata]: + """Metadata for the components of the element.""" + + def __init__( + self, + *, + data: builtins.bytes | None = ..., + component_metadata: collections.abc.Iterable[global___CompressedComponentMetadata] | None = ..., + version: builtins.int | None = ..., + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["component_metadata", b"component_metadata", "data", b"data", "version", b"version"] + ) -> None: ... + +global___CompressedElement = CompressedElement + +@typing.final +class UncompressedElement(google.protobuf.message.Message): + """An uncompressed dataset element.""" + + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + COMPONENTS_FIELD_NUMBER: builtins.int + @property + def components( + self, + ) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[ + tensorflow.core.framework.tensor_pb2.TensorProto + ]: ... + def __init__( + self, *, components: collections.abc.Iterable[tensorflow.core.framework.tensor_pb2.TensorProto] | None = ... + ) -> None: ... + def ClearField(self, field_name: typing.Literal["components", b"components"]) -> None: ... + +global___UncompressedElement = UncompressedElement diff --git a/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi new file mode 100644 index 000000000000..41abb3a43b72 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/device_attributes_pb2.pyi @@ -0,0 +1,140 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.message + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +@typing.final +class InterconnectLink(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + DEVICE_ID_FIELD_NUMBER: builtins.int + TYPE_FIELD_NUMBER: builtins.int + STRENGTH_FIELD_NUMBER: builtins.int + device_id: builtins.int + type: builtins.str + strength: builtins.int + def __init__( + self, *, device_id: builtins.int | None = ..., type: builtins.str | None = ..., strength: builtins.int | None = ... + ) -> None: ... + def ClearField( + self, field_name: typing.Literal["device_id", b"device_id", "strength", b"strength", "type", b"type"] + ) -> None: ... + +global___InterconnectLink = InterconnectLink + +@typing.final +class LocalLinks(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + LINK_FIELD_NUMBER: builtins.int + @property + def link(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___InterconnectLink]: ... + def __init__(self, *, link: collections.abc.Iterable[global___InterconnectLink] | None = ...) -> None: ... + def ClearField(self, field_name: typing.Literal["link", b"link"]) -> None: ... + +global___LocalLinks = LocalLinks + +@typing.final +class DeviceLocality(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + BUS_ID_FIELD_NUMBER: builtins.int + NUMA_NODE_FIELD_NUMBER: builtins.int + LINKS_FIELD_NUMBER: builtins.int + bus_id: builtins.int + """Optional bus locality of device. Default value of 0 means + no specific locality. Specific localities are indexed from 1. + """ + numa_node: builtins.int + """Optional NUMA locality of device.""" + @property + def links(self) -> global___LocalLinks: + """Optional local interconnect links to other devices.""" + + def __init__( + self, *, bus_id: builtins.int | None = ..., numa_node: builtins.int | None = ..., links: global___LocalLinks | None = ... + ) -> None: ... + def HasField(self, field_name: typing.Literal["links", b"links"]) -> builtins.bool: ... + def ClearField( + self, field_name: typing.Literal["bus_id", b"bus_id", "links", b"links", "numa_node", b"numa_node"] + ) -> None: ... + +global___DeviceLocality = DeviceLocality + +@typing.final +class DeviceAttributes(google.protobuf.message.Message): + DESCRIPTOR: google.protobuf.descriptor.Descriptor + + NAME_FIELD_NUMBER: builtins.int + DEVICE_TYPE_FIELD_NUMBER: builtins.int + MEMORY_LIMIT_FIELD_NUMBER: builtins.int + LOCALITY_FIELD_NUMBER: builtins.int + INCARNATION_FIELD_NUMBER: builtins.int + PHYSICAL_DEVICE_DESC_FIELD_NUMBER: builtins.int + XLA_GLOBAL_ID_FIELD_NUMBER: builtins.int + name: builtins.str + """Fully specified name of the device within a cluster.""" + device_type: builtins.str + """String representation of device_type.""" + memory_limit: builtins.int + """Memory capacity of device in bytes.""" + incarnation: builtins.int + """A device is assigned a global unique number each time it is + initialized. "incarnation" should never be 0. + """ + physical_device_desc: builtins.str + """String representation of the physical device that this device maps to.""" + xla_global_id: builtins.int + """A physical device ID for use in XLA DeviceAssignments, unique across + clients in a multi-client setup. Set to -1 if unavailable, non-negative + otherwise. + """ + @property + def locality(self) -> global___DeviceLocality: + """Platform-specific data about device that may be useful + for supporting efficient data transfers. + """ + + def __init__( + self, + *, + name: builtins.str | None = ..., + device_type: builtins.str | None = ..., + memory_limit: builtins.int | None = ..., + locality: global___DeviceLocality | None = ..., + incarnation: builtins.int | None = ..., + physical_device_desc: builtins.str | None = ..., + xla_global_id: builtins.int | None = ..., + ) -> None: ... + def HasField(self, field_name: typing.Literal["locality", b"locality"]) -> builtins.bool: ... + def ClearField( + self, + field_name: typing.Literal[ + "device_type", + b"device_type", + "incarnation", + b"incarnation", + "locality", + b"locality", + "memory_limit", + b"memory_limit", + "name", + b"name", + "physical_device_desc", + b"physical_device_desc", + "xla_global_id", + b"xla_global_id", + ], + ) -> None: ... + +global___DeviceAttributes = DeviceAttributes diff --git a/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi b/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi new file mode 100644 index 000000000000..8025593122d5 --- /dev/null +++ b/stubs/tensorflow/tensorflow/core/framework/full_type_pb2.pyi @@ -0,0 +1,617 @@ +""" +@generated by mypy-protobuf. Do not edit manually! +isort:skip_file +""" + +import builtins +import collections.abc +import sys +import typing + +import google.protobuf.descriptor +import google.protobuf.internal.containers +import google.protobuf.internal.enum_type_wrapper +import google.protobuf.message + +if sys.version_info >= (3, 10): + import typing as typing_extensions +else: + import typing_extensions + +DESCRIPTOR: google.protobuf.descriptor.FileDescriptor + +class _FullTypeId: + ValueType = typing.NewType("ValueType", builtins.int) + V: typing_extensions.TypeAlias = ValueType + +class _FullTypeIdEnumTypeWrapper( + google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_FullTypeId.ValueType], builtins.type +): + DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor + TFT_UNSET: _FullTypeId.ValueType # 0 + """The default represents an uninitialized values.""" + TFT_VAR: _FullTypeId.ValueType # 1 + """Type symbols. Used to construct more complex type expressions like + algebraic data types. + + Type variables may serve as placeholder for any other type ID in type + templates. + + Examples: + TFT_DATASET[TFT_VAR["T"]] is a Dataset returning a type indicated by "T". + TFT_TENSOR[TFT_VAR["T"]] is a Tensor of n element type indicated by "T". + TFT_TENSOR[TFT_VAR["T"]], TFT_TENSOR[TFT_VAR["T"]] are two tensors of + identical element types. + TFT_TENSOR[TFT_VAR["P"]], TFT_TENSOR[TFT_VAR["Q"]] are two tensors of + independent element types. + """ + TFT_ANY: _FullTypeId.ValueType # 2 + """Wildcard type. Describes a parameter of unknown type. In TensorFlow, that + can mean either a "Top" type (accepts any type), or a dynamically typed + object whose type is unknown in context. + Important: "unknown" does not necessarily mean undeterminable! + """ + TFT_PRODUCT: _FullTypeId.ValueType # 3 + """The algebraic product type. This is an algebraic type that may be used just + for logical grouping. Not to confused with TFT_TUPLE which describes a + concrete object of several elements. + + Example: + TFT_DATASET[TFT_PRODUCT[TFT_TENSOR[TFT_INT32], TFT_TENSOR[TFT_FLOAT64]]] + is a Dataset producing two tensors, an integer one and a float one. + """ + TFT_NAMED: _FullTypeId.ValueType # 4 + """Represents a named field, with the name stored in the attribute. + + Parametrization: + TFT_NAMED[]{} + * is the type of the field + * is the field name, as string (thpugh can theoretically be an int + as well) + + Example: + TFT_RECORD[ + TFT_NAMED[TFT_TENSOR[TFT_INT32]]{'foo'}, + TFT_NAMED[TFT_TENSOR[TFT_FLOAT32]]{'bar'}, + ] + is a structure with two fields, an int tensor "foo" and a float tensor + "bar". + """ + TFT_FOR_EACH: _FullTypeId.ValueType # 20 + """Template definition. Expands the variables by repeating a template as + arguments of container. + + Parametrization: + TFT_FOR_EACH[,